[SCM] mapserver branch, upstream, updated. upstream/6.0.1-2-ga274d9c

Jerome Villeneuve Larouche jlarouche at mapgears.com
Mon Nov 19 20:08:27 UTC 2012


The following commit has been merged in the upstream branch:
commit a274d9ca4594f0b8184cd3f5a007ab83d6dee285
Author: Jerome Villeneuve Larouche <jlarouche at mapgears.com>
Date:   Thu Nov 15 13:37:40 2012 +0000

    Imported Upstream version 6.2.0

diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000..5966153
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,2 @@
+.gitattributes export-ignore
+.gitignore export-ignore
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..403df5a
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,41 @@
+.libs
+*.o
+*.lo
+config.log
+config.status
+*.dll
+*.swp
+*.pyc
+Makefile
+legend
+libmapserver.a
+libmapserver.la
+libtool
+mapscript/csharp/Makefile
+mapscript/java/Makefile
+mapscript/perl/Makefile.PL
+mapscript/python/_mapscript.la
+mapscript/python/build/
+mapscript/python/mapscript.py
+mapscript/python/mapscript_wrap.c
+mapscript/php/php_mapscript.la
+mapscript/java/edu
+mapscript/java/javamapscript_wrap.c
+mapscript/java/libjavamapscript.la
+mapscript/java/mapscript.jar
+mapscript/perl/MYMETA.yml
+mapscript/perl/Makefile.old
+mapscriptvars
+mapserv
+mapserver-config
+msencrypt
+nbproject
+scalebar
+shp2img
+shptree
+shptreetst
+shptreevis
+sortshp
+tile4ms
+autom4te.cache
+tags
diff --git a/.gitmodules b/.gitmodules
new file mode 100644
index 0000000..7d633d3
--- /dev/null
+++ b/.gitmodules
@@ -0,0 +1,3 @@
+[submodule "msautotest"]
+	path = msautotest
+	url = git://github.com/mapserver/msautotest.git
diff --git a/.travis.yml b/.travis.yml
new file mode 100644
index 0000000..8243455
--- /dev/null
+++ b/.travis.yml
@@ -0,0 +1,35 @@
+language: c
+
+compiler:
+  - gcc
+
+before_install:
+  - git submodule update --init --recursive
+  - sudo add-apt-repository -y ppa:ubuntugis/ubuntugis-unstable
+  - sudo apt-get update -qq
+  - sudo apt-get install -qq php-pear colordiff postgis libpq-dev libpng12-dev libjpeg-dev libgif-dev libgeos-dev libgd2-noxpm-dev libfreetype6-dev libfcgi-dev libcurl4-gnutls-dev libcairo2-dev libgdal1-dev libproj-dev libxml2-dev
+  - sudo pear config-set auto_discover 1 && sudo pear install --alldeps channel://pear.phpunit.de/PHPUnit-3.6.12
+  - echo "extension=php_mapscript.so" | sudo tee -a /etc/php5/cli/php.ini
+  - cd msautotest
+  - ./create_postgis_test_data.sh
+  - cd ..
+
+install:
+  - ./configure --with-gd --with-postgis --with-wmsclient --with-wfsclient --with-kml --with-cairo --with-wcs --with-proj --with-geos --with-gdal --with-ogr --with-wfs --with-sos --with-php
+  - make -j3
+  - sudo make install 
+  - sudo ldconfig
+
+script:
+  - make -j3 test
+  - cd msautotest/php && ./run_test.py
+
+notifications:
+  email:
+    recipients:
+      - thomas.bonfort at gmail.com
+
+  irc:
+    channels:
+      - "irc.freenode.org#mapserver"
+    use_notice: true
diff --git a/COMMITERS b/COMMITERS
index 3f4d8aa..127814f 100644
--- a/COMMITERS
+++ b/COMMITERS
@@ -4,7 +4,7 @@
 sdlime       Steve Lime             steve.lime at dnr.state.mn.us        Overall
 dan          Daniel Morissette      dmorissette at mapgears.com          OGC Web Services, PHP MapScript
 sean         Sean Gillies           sgillies at frii.com                 SWIG MapScript (retired)
-assefa       Assefa Yewondwossen    assefa at dmsolutions.ca             OGC Web Services, Flash, SVG, 
+assefa       Assefa Yewondwossen    assefay at gmail.com             	 OGC Web Services,  PHP MapScript 
 julien       Julien-Samuel Lacroix  jlacroix at dmsolutions.ca           OGC Web Services
 warmerdam    Frank Warmerdam        warmerdam at pobox.com               Raster, outputFormatObj, 
 hobu         Howard Butler          hobu.inc at gmail.com                mapsde.c
diff --git a/HISTORY.TXT b/HISTORY.TXT
index c4fb575..fed66da 100644
--- a/HISTORY.TXT
+++ b/HISTORY.TXT
@@ -1,3 +1,4 @@
+
 MapServer Revision History
 ==========================
 
@@ -11,112 +12,244 @@ the top of the list.)
 
 For a complete change history, please see the Git log comments.
 
-Version 6.0.3 (2012-05-18):
----------------------------
+Current Version (git master, 6.3-dev, future 6.4):
+--------------------------------------------------
+
+- Fix WFS GetFeature result bounds are not written in requested projection (#4494)
+
+- Fixed wrong size in LegendURL of root layer (#4441)
+
+- Fixed wms_style_name in GetMap requests (#4439)
+
+- Fix segfault in queryByFilter function in MapScript
+
+- Adjusted WCS 2.0 to WCS Core 2.0.1 and GMLCOV 1.0.1 corrigenda (#4003)
+
+- Adjusted mediatype to multipart/related in WCS 2.0 (#4003)
+
+- Fix symbolObj.getImage seg fault in PHP/MapScript
+
+- Fix bad handling of startindex in some drivers (#4011)
+  WFSGetFeature also now uses a global maxfeatures and startindex to support
+  maxfeatures across layers rather than within layers
+
+- Fixed bugs with WCS 1.1/2.0 with VSIMEM (#4369)
+
+- Add notable changes here. Less important changes should go only in the
+  commit message and not appear here.
+  
+- Fixed the OGR driver to use point or line spatial filter geometries in degenerated cases (#4420)
+
+- Fix WFS filter is produced as non-standard XML (#4171)
+
+- Fix pixmap symbol loading issue (#4329)
+
+- Added INSPIRE ExtendedCapabilities and DOCTYPE definition to WMS 1.1.1 (#3608)
+
+- Fix wms_enable_request-related errors are not properly tagged (#4187)
+
+- Fixed "msGetMarkerSize() called on unloaded pixmap symbol" in mapsymbol.c (#4225)
+
+- Fixed PHP MapScript support for PHP 5.4 (#4309)
+
+- Fix msOGREscapeSQLParam could return random data (#4335)
+
+- Fixed locations of supported and native formats in Capabilities and CoverageDescriptions for WCS 2.0 (#4003)
+
+- Made format parameter for WCS 2.0 GetCoverage requests optional (#4003)
+
+- Swig mapscript for multi-label support (#4310)
 
 - Fix creation of a vector symbolObj in mapscript (#4318)
 
 - Added coverage metadata in WCS (#4306)
 
-- Adjusted WCS 2.0 GetCapbilities response (#4003)
-
 - Ignore unknown requets parameteres in WCS 2.0 (#4307).
 
-- Fixed mapscript is unusable in a web application due to
-  memory leaks (#4262)
-
-- Fixed getFeature request with custom output format fails on filter
-  encoding (#4190)
+- Fixed getFeature request with custom output format fails on filter encoding (#4190)
 
 - Fixed resolution when UoM changes in WCS 2.0 (#4283)
 
-- Added missing DEFRESOLUTION parameter to msCopyMap() function (#4272)
+- Added missing DEFRESOLUTION parameter to msCopyMap() function (#4272) 
 
-- Fixed Python MapScript layerObj/classObj Error (#3940)
+- Migrated svn to git, and issue tracking from trac to github
 
-- Fixed WCS 2.0 axis order, offset vector, and origin (#4006, #4191)
+- Fixed mapscript is unusable in a web application due to memory leaks (#4262)
+ 
+- Fixed legend image problem with annotation layers with label offsets (#4147)
 
-- Fixed PHP MapScript opacity property of StyleObj no longer works (#3920)
+- Add support for mutiple labels per feature (RFC81)
+
+- Add support for INSPIRE view service (RFC 75)
+
+- Drop support for GDAL/OGR older than 1.5.0 (#4224)
+
+- PDF backend: add support for generating geospatial PDF, when
+  GDAL 2.0 with PDF driver is used, and the GEO_ENCODING FORMATOPTION
+  (set to ISO32000 or OGC_BP) is added to the OUTPUTFORMAT definition. (#4216)
+
+- Python mapscript: fix swig mappings to work with both python 2.5.and 2.6 (#3940)
+
+- Added classgroup CGI parameter support (#4207)
+
+- Java mapscript: renamed shared library and completed libtool support (#2595)
+
+- Fixed WCS 2.0 axis order (#4191)
 
 - Added MS_CJC_* constants in PHP/MapScript (#4183)
 
-- Fixed Memory leak with fribidi strings (#4188)
+- Fixed Memory Leak with Fribidi Strings (#4188)
 
-- Added missing properties in styleObj setter of PHP/MapScript (#3901)
+- Allow multiple label definitions within a class (RFC 77/#4127)
 
-Version 6.0.2 (2012-02-08):
----------------------------
+- shp2img: make it possible to specify layers (with -l option) that match GROUP names.
+
+- reuse a pre-parsed mapfile across fastcgi loops in case the mapfile is
+  specified with the MS_MAPFILE env variable. (#4018)
 
-- Fix security issue with quote escape in WFS GetFeature Filter (#4087)
+- Ability to do use PropertyIsLike with a column of a different type than text (postgis) (#4176)
+
+- Fixed SLD with FILTER doesn't apply properly to database layers (#4112)
 
 - Fixed lexer buffer size issue with single quotes in a string  (#4175)
 
+- WFS Quote Escape issue (#4087)
+
 - Raster layer fails to be drawn if the window is less than half a pixel (#4172)
 
-- Fixed SLD with FILTER doesn't apply properly to database layers (#4112)
+- shptree: Improvement to reduce size of .qix files (#4169)
+
+- avoid potential gd fontcache deadlock on fastcgi exit signals(#4093)
+
+- Adjusted WCS GetCapabilities for an empty list of layers (#4140)
+
+- Adjusted WMS GetCapabilities for an empty list of layers (#3755)
+
+- Refactor cgi masperv to not call exit on argument errors (#3099)
+
+- Add --with-apache-module configure option to build an apache dso module
+  (#2565)
+
+- Use libtool to build object files and libraries
+
+- Dynamically link libmapserver to the created binaries by default
+  (requires the make install step to be run)
+
+- Python mapscript builds with make instead of setuptools
+
+- Fix LABELPNT geomtransform position for non-cached labels (#4121)
+
+- Add RFC80 font fallback support (#4114)
+
+- Added POLAROFFSET style option for a different symbol transform (#4117)
 
-- Fixed a problem with calls to labelInImage() (maplabel.c) when label gutter
-  and label buffers are both used (#3303). Also changed the usage around that
-  function to make it easier to understand. At a result the
-  "labelcache_map_edge_buffer" processing option (i.e. gutter) can be provided
-  as a positive or negative value. (closes #1355 too)
+- automatically translate vector symbol points (#4116)
 
-- Added label->style markers to collision detection (#4133)
+- Add RFC79 Layer masking (#4111)
 
 - Fixed single pixel coverages in WCS 2.0 (#4110)
 
+- Add svg symbols support (#3671)
+
 - Fixed subsetting in WCS 2.0 (#4099)
 
+- Upgrade clipper library to 4.6.3
+
+- Make openlayers wms template request images with mimetype of outputformat
+  defined in the mapfile's imagetype
+
+- Fix memory leak in msSLDParseRasterSymbolizer()
+
+- Fix compilation error with clang in renderers/agg/include/agg_renderer_outline_aa.h
+
+- Add stable hatch rendering (#3847)
+
+- Added vector field rendering (#4094)
+
+- Add wms dimensions support (#3466)
+
 - Fixed segfault when calling classObj::updateFromString() with SYMBOL (#4062)
 
-- fix rendering offset on thick GD lines (#3962)
+- Use a renderer native follow text implementation if available.
 
-- fix segfault on join with postgresql tables (#4074)
+- Fixed layer with inline feature to support multiple classes (#4070)
 
-- Fixed Python Mapscript does not write COLOR to reference map (#4042)
- 
-- Fixed cannot add a style to a label in PHP/SWIG Mapscript (#4038) 
+- Add support for rfc45 anchorpoint on marker symbols (#4066)
+
+- Add initial gap support for line marker symbols (#3879)
+
+- Fix center to center computation of gaps for line marker symbols
+  and polygon tile patterns (#3867)
+
+- Add initial gap support for line patterns (#3879)
 
-- Add missing outputFormat support in WFS GetFeature POST XML requests (#4052)
+- Fixed grid of thin lines in polygon symbol fills (#3868)
+
+- Fixed cannot add a style to a label in PHP/SWIG Mapscript (#4038)
 
 - Fixed schema validity issue for WCS 1.1 GetCoverage responses (#4047)
 
-- fix centroid geomtransform parser (#4029)
+- remove default compiler search paths from the GD CFLAGS/LDFLAGS (#4046)
 
-- PHP MapScript is missing many styleObj properties (#3901)
+- Fixed Python Mapscript does not write COLOR to reference map (#4042)
+
+- Added XMP support for metadata embedding, RFC 76, (#3932)
 
-- Added GEOMTRANSFORM in writeStyle function
+- Added GetLegendGraphic Cascading support (#3923)
+
+- Rewrite  postgres TIME queries to take advantage of indexes (#3374)
+
+- Unified OWS requests and applied to WCS (defaults to version 2.0 now) (#3925)
 
 - WCS 1.0: Fix crash with some _rangeset_axes values (#4020)
 
-- Changed msDrawVectorLayer() not to cache shapes if attribute binding is 
-  present after the first style (#3976)
+- WCS 2.0: Adjusted offset vector and origin (#4006)
+
+- Added addParameter() method to MapScript (#3973)
+
+- Changed msDrawVectorLayer() not to cache shapes if attribute binding is present after	the first style	(#3976)
 
 - Fix mapscript to build when TRUE macro is not defined (#3926)
 
 - Fix mapscript php build issues with MSVC (#4004)
 
-- PHP/Mapscript: Segmentation fault when getting complex object using 
-  PHP 5.2 (#3930)
+- PHP MapScript is missing many styleObj properties (#3901)
+
+- PHP/Mapscript: Segmentation fault when getting complex object using PHP 5.2  (#3930)
+
+- PHP/Mapscript: Fixed webObj->metadata returns a webObj (#3971)
+
+- WCS 1.1: Added check for imageCRS in msOWSCommonBoundingBox() (#3966)
 
 - Fixed contains operator in logical expresions (#3974)
 
+- WCS 1.0: WCS Exceptions raise mapscript exceptions (#3972)
+
+- WMS: LAYERS parameter is optional when sld is given (#1166)
+
+- Add runtime substitution for "filename" output format option (#3571) and
+  allow setting defaults in either metadata or validation (preferred) blocks
+  for both layer and output format.
+
+- Add non antialiased text rendering for GD (#3896)
+
+- Fixed OGC filter using expressions (#3481)
+
 - Fix incorrect rendering of GD lines between 1 and 2 pixels wide (#3962)
 
-Version 6.0.1 (2011-07-12):
----------------------------
+- Add gamma correction to AGG polygon rendering (#3165)
+
+- Initialize the scalebar image color to transparent by default (#3957)
+
+- Do not divide by zero in io read/write funcs (#4135)
 
-IMPORTANT SECURITY FIXES:
+IMPORTANT SECURITY FIX:
 
 -  Fixes to prevent SQL injections through OGC filter encoding (in WMS, WFS 
    and SOS), as well as a potential SQL injection in WMS time support. 
    Your system may be vulnerable if it has MapServer with OGC protocols 
    enabled, with layers connecting to an SQL RDBMS backend, either 
-   natively or via OGR (#3903) 
-
-Other fixes:
-
-- Applied patch for ticket (symbol writing issues) (#3589)
+   natively or via OGR (#3903)
 
 - Fix performance issue with Oracle and scrollable cursors (#3905)
 
@@ -128,26 +261,36 @@ Other fixes:
 
 - Fix rendering of lines with outlinewidth set if not on first style (#3935)
 
-- Added writing of cluster object when saving map. Also improved handling of
-  cluster parsing errors (#3934)
+- Correct SLD with spatial filters bbox and intersects (#3929)
+
+- Applied patch for ticket (symbol writing issues) (#3589)
+
+- Added WMS GetFeatureInfo Cascading (#3764)
+
+- Fixed png lib is not found on multiarch systems (#3921)
+
+- Fixed PHP MapScript opacity property of StyleObj no longer works (#3920)
+
+- Fixed Using STYLEITEM AUTO, loadExpression fails when the label text
+  contains a space or begins with a double quote (#3481)
 
 - Fix for the cluster processing if the shape bounds doesn't overlap 
   with the given extent (#3913)
+  
+- Add support for dashes on polygon hatches (#3912)
 
-- OGC Filter: fix segfault when a ows_varname_type or wfs_varname_type is
-  defined but not a gml_varname_type (#3902)
-
-- Fix regression of MapServer 6.0.0 when specifying a time range in WMS time
-  requests on a Postgis layer (#3909)
+- Union layer 3 new processing options added (#3900)
 
-- Fixed order of metadata lookup for WMS GML GetFeatureInfo. 'ows' should 
-  come last, not first (#3636).
+- Changed msRemoveStyle to allow removing all styles (#3895)
 
 - Fixed mssql2008 to return correct geometries with chart layer type (#3894)
 
+- Ensure msLayerSetProcessingKey() supports setting a NULL value to clear
+  a processing key. 
+
 - Write SYMBOLSET/END tags when saving a symbol file (#3885)
 
-- Make java threadtests work again (#3887) 
+- Make java threadtests work again (#3887)
 
 - Fix segfault on malformed <PropertyIsLike> filters (#3888)
 
@@ -155,17 +298,27 @@ Other fixes:
 
 - Fixed potential crash with AVERAGE resampling and crazy reprojection (#3886)
 
+- Adjusted OperationsMetadata for POST in WCS 2.0 GetCapabilities response
+
 - Fix for the warnings in mapunion.c (#3880)
 
+- SLD: correct when same layer is used with multiple styles (#1602)
+
 - Fixed the build problem in mapunion.c (#3877)
 
+- Implement to get all shapes with the clustered layer (#3873)
+
 - Union layer: Fixed the crash when styling source layers using attributes (#3870)
 
+- Added GEOS difference operator to expression support (#3871) 
+
 - Improve rangeset item checking so that Bands=1,2,3 is supported with WCS 1.0
   (#3919).
 
 - Fix GetMapserverUnitUsingProj() for proj=latlong (#3883)
 
+- Add support for OGR output of 2.5D geometries (#3906)
+
 
 Version 6.0.0 (2011-05-11)
 --------------------------
diff --git a/MIGRATION_GUIDE.txt b/MIGRATION_GUIDE.txt
index 7b3f27d..77bcf4c 100644
--- a/MIGRATION_GUIDE.txt
+++ b/MIGRATION_GUIDE.txt
@@ -10,7 +10,72 @@ MapServer Migration Guide
     :depth: 2
     :backlinks: top
     
-    
+Mapserver 6.0 to 6.2 Migration
+==============================
+
+This section documents the changes that must be made to MapServer 
+applications when migrating from version 6.0.x (or earlier versions) 
+to 6.2 (i.e. backwards incompatibilities), as well as information
+on some of the new features.
+
+--------------------
+Build system changes
+--------------------
+
+If you are building MapServer from source, then the following may be of interest to you:
+
+* Use of libtool: In version 6.2, the Unix/Linux build scripts and Makefiles were converted to use libtool. One impact of this change is that the 'mapserv' file in the main source tree is a libtool wrapper script and not the actual binary. To use 'mapserv' you actually have to use 'make install' and then point to the installed binary. More info is available in the Compiling on Unix document at http://mapserver.org/trunk/installation/unix.html#installation
+
+* The --with-php configure option has been changed to point directly to the php-config script instead of to the directory where the PHP headers are located.
+
+-----------
+CGI Changes
+-----------
+
+* Changing MIN/MAXSCALE or MIN/MAXSCALEDENOM via URL is no longer supported.
+
+-----------------
+Rendering changes
+-----------------
+
+* STYLE->GAP interpretation
+  Starting in 6.2, STYLE->GAP specifies the gap between the symbols
+  using the centre to centre distance.
+  In earlier versions of Mapserver, GAP was used as the approximate
+  distance between the symbol boundaries.
+  See ticket #3867 for more information.
+
+  In order to get the same effect with 6.2 as with 6.0, STYLE->GAP
+  must be increased with the size of the symbol.
+
+* Removal of one pixel gap between symbols
+  In earlier versions of Mapserver, an extra gap of one pixel was
+  added between the symbols (in addition to the gap specified in
+  STYLE->GAP).  This has been discontinued in 6.2.
+  See ticket #3868 for more information.
+
+  In order to get the same effect with 6.2 as with 6.0, STYLE->GAP
+  must be increased with one pixel.
+
+* STYLE->INITIALGAP introduced
+  Support for more powerful line styling has been provided with the
+  introduction of STYLE->INITIALGAP.  See ticket #3879 and the
+  documentation for more information.
+
+* SYMBOL->ANCHORPOINT introduced
+  A symbol anchorpoint has been introduced to facilitate precise
+  positioning of symbols.  See ticket #4066 and the documentation for
+  more information.
+
+* Change in vector symbol size calculation.
+  In 6.2, vector symbol coordinates are shifted to get rid of
+  negative x and y coordinate values.
+  See ticket #4116 for more information.
+
+  In order to get the shifting effect that could be obtained using
+  negative coordinate values, SYMBOL->ANCHORPOINT should be used
+  instead.
+
 MapServer 5.6 to 6.0 Migration
 ==============================
     
@@ -178,6 +243,21 @@ are evaluated in OGC WCS services. Previous versions used "wms_*"
 prefixed entries as fallback which is dropped in version 6.0 in favor of
 forcing explicit decisions.
 
+-------------------------------------------------------
+Mapfile Changes - OGC requests - DUMP parameter removed
+-------------------------------------------------------
+
+The DUMP LAYER parameter has been removed.  To enable output of
+geometries in WMS getfeatureinfo requests - GML
+(INFO_FORMAT=application/vnd.ogc.gml), LAYER METADATA is used
+instead::
+
+   METADATA
+     gml_geometries "geom"
+     gml_geom_type "polygon"
+     ...
+   END
+
 --------------------------------------------------------
 Mapfile Changes - Ability to escape single/double quotes
 --------------------------------------------------------
@@ -185,7 +265,7 @@ Mapfile Changes - Ability to escape single/double quotes
 We can now escape single and double quotes in strings and logical
 expressions. Examples:
 
-::
+:: 
 
   NAME "RO\"AD" # double quote inside a a double quote delimited string
   NAME 'RO\'AD' # single quote inside a a single quote delimited string
@@ -195,10 +275,10 @@ NOTE: The escape character (backslash) will only work if the
 following character is ", ' or \.
 
 For Windows users: if you have a path string delimited by single/double
-quotes that ends with \, you will have to escape the last backslash.
+quotes that ends with \, you will have to escape the last backslash. 
 
 ::
-
+  
   SHAPEPATH "C:\ms4w\shapefiles\"
   # should be modified to...
   SHAPEPATH "C:\ms4w\shapefiles\\"
diff --git a/Makefile.in b/Makefile.in
index 42924fd..18956af 100644
--- a/Makefile.in
+++ b/Makefile.in
@@ -1,12 +1,15 @@
+# @configure_input@
 # Run ./configure in the main MapServer directory to turn this Makefile.in
 # into a proper Makefile
 
 prefix		=	@prefix@
 exec_prefix	=	@exec_prefix@
-INST_PREFIX	=	@exec_prefix@
-INST_LIB	=	@libdir@
-INST_BIN	=	@bindir@
-
+libdir	=	@libdir@
+bindir	=	@bindir@
+srcdir	=	@srcdir@
+top_builddir = @top_builddir@
+SHELL = @SHELL@
+package     = @PACKAGE_NAME@
 #
 # MS_VERSION - Set by configure based in mapserver.h
 #
@@ -15,9 +18,7 @@ MS_VERSION=	@MS_VERSION@
 #
 # Name of static and shared libs to produce
 #
-LIBMAP_STATIC=	libmapserver.a
-LIBMAP_SHARED=	libmapserver. at SO_EXT@
-LIBMAP_SH_VER=	libmapserver.$(MS_VERSION). at SO_EXT@
+LIBMAP=	libmapserver.la
 
 #
 # If you want to ignore missing datafile errors uncomment the following
@@ -54,25 +55,11 @@ PROJ_INC=  @PROJ_INC@
 PROJ_LIBS= @PROJ_LIBS@
 PROJ=      @PROJ_ENABLED@
 
-# GD distribution (graphics library GIF and/or PNG support). (REQUIRED)
-#
-#   - Versions 1.3 to 1.5 write non-LZW GIF (-DUSE_GD_1_3).
-#   - Versions 1.6 and greater write PNG (-DUSE_GD_1_6). Add -lpng -lz to GD_LIB line.
-#
-#
-GDFONT_OBJ=gd-1.2/gdfontt.o gd-1.2/gdfonts.o gd-1.2/gdfontmb.o gd-1.2/gdfontl.o gd-1.2/gdfontg.o
+# GD distribution
 GD_INC=  @GD_INC@
 GD_LIB=  @GD_LIB@
-GD=      @GD_DEF@
-GD_STATIC = @GD_STATIC@
 
-#
-# Optional Anti-Grain Geometry Support.
-#
-AGG=     @AGG_ENABLED@
-AGG_INC=  @AGG_INC@
-AGG_OBJ=  @AGG_OBJ@
-AGG_LIB= @AGG_LIB@
+AGG_INC=  -Irenderers/agg/include
 
 #
 # Optional Opengl Support.
@@ -104,12 +91,6 @@ GIF_INC= @GIF_INC@
 GIF_LIB= @GIF_LIB@
 GIF=	 @GIF_ENABLED@
 
-# 
-# ZLIB option (compressed SVG)
-#
-ZLIB_INC=  @ZLIB_INC@
-ZLIB_LIB=  @ZLIB_LIB@
-ZLIB=      @ZLIB_ENABLED@
 
 # JPEG distribution (raster support for grayscale JPEG images, INPUT ONLY).
 JPEG_INC= @JPEG_INC@
@@ -177,13 +158,21 @@ XSLT_LIB=@XSLT_LIB@
 EXSLT_INC=@EXSLT_INC@
 EXSLT_LIB=@EXSLT_LIB@
 
-
+# Optional Exempi
+EXEMPI=@EXEMPI_ENABLED@
+EXEMPI_INC=@EXEMPI_INC@
+EXEMPI_LIB=@EXEMPI_LIB@
 
 # Optional FastCGI
 FASTCGI=@FASTCGI_ENABLED@
 FASTCGI_INC=@FASTCGI_INC@
 FASTCGI_LIB=@FASTCGI_LIB@
 
+APXS=@APXS@
+APACHE_INC=@APACHE_INC@
+APR_INC=@APR_INC@
+APR_LIB=@APR_LIBS@
+
 # OWS: OGC Web Services support
 # OGC WMS Server:  -DUSE_WMS_SVR (Requires PROJ4 support)
 # OGC WMS Client Connections:  -DUSE_WMS_LYR (Requires PROJ4 and libcurl)
@@ -219,6 +208,13 @@ CAIRO=@CAIRO_ENABLED@
 CAIRO_LIB=@CAIRO_LIB@
 CAIRO_INC=@CAIRO_INC@
 
+LIBSVG_CAIRO=@LIBSVG_CAIRO_ENABLED@
+LIBSVG_CAIRO_LIB=@LIBSVG_CAIRO_LIB@
+LIBSVG_CAIRO_INC=@LIBSVG_CAIRO_INC@
+
+PHP_MAPSCRIPT=@PHP_MAPSCRIPT@
+PYTHON_MAPSCRIPT=@PYTHON_MAPSCRIPT@
+
 #
 # Pick a compiler, etc. Flex and bison are only required if you need to modify the mapserver lexer (maplexer.l) or expression parser (mapparser.y).
 #
@@ -229,25 +225,30 @@ AR= ar rc
 RANLIB= @RANLIB@
 LEX=    @LEX@
 YACC=   @YACC@
+LIBTOOL=@LIBTOOL@
+INSTALL=@INSTALL@
+SED=@SED@
 
-
-# figure out how to build a shared library.  
-# most of the relevant stuff is in AC_LD_SHARED in 
-# aclocal.m4
-
-LD_SHARED = @LD_SHARED@
-LD_SONAME_LIBMAP = -W1, at SO_COMMAND_NAME@,$(LIBMAP_SH_VER)
+LTCC=$(LIBTOOL) --mode=compile --tag=CC
+LTCXX=$(LIBTOOL) --mode=compile --tag=CXX
+LTLD=$(LIBTOOL) --mode=link --tag=CXX
+LTINSTALL=$(LIBTOOL) --mode=install
+OBJ_SUFFIX=lo
 
 XTRALIBS= @XTRALIBS@
-RUNPATHS= @RPATHS@
+RUNPATHS= -rpath $(libdir)
 
-DEFINES = $(IGNORE_MISSING_DATA) $(USE_POINT_Z_M) $(STRINGS) @ALL_ENABLED@ $(FRIBIDI) -DDISABLE_CVSID
+LT_LDFLAGS= $(RUNPATHS)
+LINK=$(LTLD) $(LD) $(LT_LDFLAGS)
+
+DEFINES = @ALL_ENABLED@ 
 
 INCLUDES = $(FT_INC) $(REGEX_INC) $(PNG_INC) $(GIF_INC) $(JPEG_INC) $(GD_INC) \
         $(AGG_INC) $(OGL_INC) $(FTGL_INC) $(PROJ_INC) $(EGIS_INC) \
         $(SDE_INC) $(GDAL_INC) $(POSTGIS_INC) $(MYSQL_INC) \
         $(CURL_INC) $(ORACLESPATIAL_INC) $(GEOS_INC) $(ICONV_INC) \
-        $(FASTCGI_INC) $(ZLIB_INC) $(XML2_INC) $(FRIBIDI_INC) $(CAIRO_INC)
+        $(EXEMPI_INC) $(XML2_INC) $(FRIBIDI_INC) $(CAIRO_INC) $(LIBSVG_CAIRO_INC) \
+		  $(APR_INC) $(APACHE_INC)
 
 FLAGS = @DEBUG_FLAGS@ $(DEFINES) $(INCLUDES)
 
@@ -255,42 +256,59 @@ CFLAGS   = @CFLAGS@ $(FLAGS)
 CXXFLAGS = @CXXFLAGS@ $(FLAGS)
 
 # Link flags and shared libs only
-SUP_LIBS =  $(FT_LIB) $(GD_LIB) $(AGG_LIB) $(OGL_LIB) $(FTGL_LIB) $(PROJ_LIBS) \
+SUP_LIBS =  $(FT_LIB) $(GD_LIB) $(OGL_LIB) $(FTGL_LIB) $(PROJ_LIBS) \
           $(JPEG_LIB) $(PNG_LIB) $(GIF_LIB) $(SDE_LIB) $(GDAL_LIB) $(POSTGIS_LIB) \
 	  $(MYSQL_LIB) $(CURL_LIB) $(ORACLESPATIAL_LIB) $(GEOS_LIB) \
-	  $(THREAD_LIB) $(ICONV_LIB) $(FASTCGI_LIB) $(XSLT_LIB) $(EXSLT_LIB) \
-	  $(ZLIB_LIB) $(XML2_LIB) $(FRIBIDI_LIB) $(XTRALIBS)  $(CAIRO_LIB)
+	  $(THREAD_LIB) $(ICONV_LIB) $(EXEMPI_LIB) $(XSLT_LIB) $(EXSLT_LIB) \
+	  $(XML2_LIB) $(FRIBIDI_LIB) $(XTRALIBS)  $(CAIRO_LIB) $(LIBSVG_CAIRO_LIB) \
+	  $(APR_LIB)
 
-# STATIC_LIBS is full filename with path of libs that will be statically linked
-STATIC_LIBS= $(GD_STATIC)
 
-EXE_LDFLAGS =	$(RUNPATHS) -L. -lmapserver $(SUP_LIBS) $(STATIC_LIBS)
+EXE_LDFLAGS =	$(RUNPATHS) -lmapserver $(SUP_LIBS)
 
 RM= /bin/rm -f
 
-OBJS= $(AGG_OBJ) mapgeomutil.o mapdummyrenderer.o mapogl.o mapoglrenderer.o mapoglcontext.o \
-				mapimageio.o mapcairo.o maprendering.o mapgeomtransform.o mapquantization.o \
-				maptemplate.o mapbits.o maphash.o mapshape.o mapxbase.o mapparser.o maplexer.o \
-				maptree.o mapsearch.o mapstring.o mapsymbol.o mapfile.o maplegend.o maputil.o \
-				mapscale.o mapquery.o maplabel.o maperror.o mapprimitive.o mapproject.o mapraster.o \
-				mapsde.o mapogr.o mappostgis.o maplayer.o mapresample.o mapwms.o \
-				mapwmslayer.o maporaclespatial.o mapgml.o mapprojhack.o mapthread.o mapdraw.o \
-				mapgd.o mapagg.o mapoutput.o mapgdal.o mapimagemap.o mapows.o mapwfs.o \
-				mapwfs11.o mapwfslayer.o mapcontext.o maphttp.o mapdrawgdal.o mapjoin.o mapgraticule.o \
-				mapcopy.o mapogcfilter.o mapogcsld.o maptime.o mapwcs.o mapwcs11.o mapcpl.o cgiutil.o \
-				maprasterquery.o mapobject.o mapgeos.o classobject.o layerobject.o mapio.o mappool.o \
-				mapregex.o mappluginlayer.o mapogcsos.o mappostgresql.o mapcrypto.o mapowscommon.o \
-				maplibxml2.o mapdebug.o mapchart.o maptclutf.o mapxml.o mapkml.o mapkmlrenderer.o \
-				mapogroutput.o mapwcs20.o  mapogcfiltercommon.o mapunion.o mapcluster.o
+AGG_OBJ=renderers/agg/src/clipper.$(OBJ_SUFFIX) renderers/agg/src/agg_arc.$(OBJ_SUFFIX) renderers/agg/src/agg_curves.$(OBJ_SUFFIX)\
+		  renderers/agg/src/agg_vcgen_contour.$(OBJ_SUFFIX) renderers/agg/src/agg_vcgen_dash.$(OBJ_SUFFIX)\
+		  renderers/agg/src/agg_vcgen_stroke.$(OBJ_SUFFIX) renderers/agg/src/agg_image_filters.$(OBJ_SUFFIX)\
+		  renderers/agg/src/agg_line_aa_basics.$(OBJ_SUFFIX) renderers/agg/src/agg_line_profile_aa.$(OBJ_SUFFIX)\
+		  renderers/agg/src/agg_sqrt_tables.$(OBJ_SUFFIX) renderers/agg/src/agg_embedded_raster_fonts.$(OBJ_SUFFIX)\
+		  renderers/agg/src/agg_trans_affine.$(OBJ_SUFFIX) renderers/agg/src/agg_vpgen_clip_polygon.$(OBJ_SUFFIX)\
+		  renderers/agg/src/agg_vpgen_clip_polyline.$(OBJ_SUFFIX) renderers/agg/src/agg_font_freetype.$(OBJ_SUFFIX)
+
+OBJS= $(AGG_OBJ) mapgeomutil.$(OBJ_SUFFIX) mapdummyrenderer.$(OBJ_SUFFIX) mapogl.$(OBJ_SUFFIX) mapoglrenderer.$(OBJ_SUFFIX) mapoglcontext.$(OBJ_SUFFIX) \
+				mapimageio.$(OBJ_SUFFIX) mapcairo.$(OBJ_SUFFIX) maprendering.$(OBJ_SUFFIX) mapgeomtransform.$(OBJ_SUFFIX) mapquantization.$(OBJ_SUFFIX) \
+				maptemplate.$(OBJ_SUFFIX) mapbits.$(OBJ_SUFFIX) maphash.$(OBJ_SUFFIX) mapshape.$(OBJ_SUFFIX) mapxbase.$(OBJ_SUFFIX) mapparser.$(OBJ_SUFFIX) maplexer.$(OBJ_SUFFIX) \
+				maptree.$(OBJ_SUFFIX) mapsearch.$(OBJ_SUFFIX) mapstring.$(OBJ_SUFFIX) mapsymbol.$(OBJ_SUFFIX) mapfile.$(OBJ_SUFFIX) maplegend.$(OBJ_SUFFIX) maputil.$(OBJ_SUFFIX) \
+				mapscale.$(OBJ_SUFFIX) mapquery.$(OBJ_SUFFIX) maplabel.$(OBJ_SUFFIX) maperror.$(OBJ_SUFFIX) mapprimitive.$(OBJ_SUFFIX) mapproject.$(OBJ_SUFFIX) mapraster.$(OBJ_SUFFIX) \
+				mapsde.$(OBJ_SUFFIX) mapogr.$(OBJ_SUFFIX) mappostgis.$(OBJ_SUFFIX) maplayer.$(OBJ_SUFFIX) mapresample.$(OBJ_SUFFIX) mapwms.$(OBJ_SUFFIX) \
+				mapwmslayer.$(OBJ_SUFFIX) maporaclespatial.$(OBJ_SUFFIX) mapgml.$(OBJ_SUFFIX) mapprojhack.$(OBJ_SUFFIX) mapthread.$(OBJ_SUFFIX) mapdraw.$(OBJ_SUFFIX) \
+				mapgd.$(OBJ_SUFFIX) mapagg.$(OBJ_SUFFIX) mapoutput.$(OBJ_SUFFIX) mapgdal.$(OBJ_SUFFIX) mapimagemap.$(OBJ_SUFFIX) mapows.$(OBJ_SUFFIX) mapwfs.$(OBJ_SUFFIX) \
+				mapwfs11.$(OBJ_SUFFIX) mapwfslayer.$(OBJ_SUFFIX) mapcontext.$(OBJ_SUFFIX) maphttp.$(OBJ_SUFFIX) mapdrawgdal.$(OBJ_SUFFIX) mapjoin.$(OBJ_SUFFIX) mapgraticule.$(OBJ_SUFFIX) \
+				mapcopy.$(OBJ_SUFFIX) mapogcfilter.$(OBJ_SUFFIX) mapogcsld.$(OBJ_SUFFIX) maptime.$(OBJ_SUFFIX) mapwcs.$(OBJ_SUFFIX) mapwcs11.$(OBJ_SUFFIX) mapcpl.$(OBJ_SUFFIX) cgiutil.$(OBJ_SUFFIX) \
+				maprasterquery.$(OBJ_SUFFIX) mapobject.$(OBJ_SUFFIX) mapgeos.$(OBJ_SUFFIX) classobject.$(OBJ_SUFFIX) layerobject.$(OBJ_SUFFIX) mapio.$(OBJ_SUFFIX) mappool.$(OBJ_SUFFIX) \
+				mapregex.$(OBJ_SUFFIX) mappluginlayer.$(OBJ_SUFFIX) mapogcsos.$(OBJ_SUFFIX) mappostgresql.$(OBJ_SUFFIX) mapcrypto.$(OBJ_SUFFIX) mapowscommon.$(OBJ_SUFFIX) \
+				maplibxml2.$(OBJ_SUFFIX) mapdebug.$(OBJ_SUFFIX) mapchart.$(OBJ_SUFFIX) maptclutf.$(OBJ_SUFFIX) mapxml.$(OBJ_SUFFIX) mapkml.$(OBJ_SUFFIX) mapkmlrenderer.$(OBJ_SUFFIX) \
+				mapogroutput.$(OBJ_SUFFIX) mapwcs20.$(OBJ_SUFFIX)  mapogcfiltercommon.$(OBJ_SUFFIX) mapunion.$(OBJ_SUFFIX) mapcluster.$(OBJ_SUFFIX) mapxmp.$(OBJ_SUFFIX) \
+				mapuvraster.$(OBJ_SUFFIX) mapservutil.$(OBJ_SUFFIX) maptile.$(OBJ_SUFFIX)
+
+HEADERS=	cgiutil.h mapgml.h mapoglcontext.h mapregex.h\
+			maptile.h dxfcolor.h maphash.h mapoglrenderer.h mapresample.h\
+			maptime.h mapagg.h maphttp.h mapows.h mapserv.h\
+			maptree.h mapaxisorder.h mapio.h mapowscommon.h\
+			mapwcs.h mapcopy.h mapkmlrenderer.h mapparser.h mapshape.h\
+			mapentities.h maplibxml2.h mappostgis.h mapsymbol.h maperror.h\
+			mapogcfilter.h mapprimitive.h maptemplate.h mapfile.h mapogcsld.h\
+			mapproject.h mapthread.h
 
 EXE_LIST = 	shp2img legend mapserv shptree shptreevis \
-		shptreetst scalebar sortshp mapscriptvars tile4ms \
+		shptreetst scalebar sortshp tile4ms \
 		msencrypt mapserver-config
 
 #
 # --- You shouldn't have to edit anything else. ---
 #
-all: $(MAKE_GD) libmapserver.a $(EXTRA_DEFAULT) $(EXE_LIST) @MAKE_PHPMS@ 
+all: $(LIBMAP) $(EXE_LIST) mapscriptvars $(PHP_MAPSCRIPT) $(PYTHON_MAPSCRIPT)
 
 # Explicitly invoke this rule when maplexer.l is altered.  We don't do
 # it automatically for the reasons listed in #2310
@@ -303,29 +321,31 @@ maplexer.c:	maplexer.l
 	@echo '--  Please run "make lexer" if you have altered maplexer.l     -'
 	@echo '----------------------------------------------------------------'
 
+Makefile: Makefile.in config.status
+	./config.status $@
+
+config.status: configure
+	./config.status --recheck
 #
 # Non-gnumake's don't seem to use this pattern rule, 
 # but have a similar built-in rule for C code.  So try not
 # to change these, since the change is unlikely to stick.
 # 
-.c.o:
-	$(CC) -c $(CFLAGS) $< -o $@
-   
-mapogl.o: mapogl.cpp
-	$(CXX) -c $(CXXFLAGS) mapogl.cpp -o mapogl.o
+.SUFFIXES:
+.SUFFIXES: .cpp .c .$(OBJ_SUFFIX)
 
-mapoglrenderer.o: mapoglrenderer.cpp mapoglrenderer.h
-	$(CXX) -c $(CXXFLAGS) mapoglrenderer.cpp -o mapoglrenderer.o
-   
-mapoglcontext.o: mapoglcontext.cpp mapoglcontext.h
-	$(CXX) -c $(CXXFLAGS) mapoglcontext.cpp -o mapoglcontext.o
-   
-mapogr.o:	mapogr.cpp
-	$(CXX) -c $(CXXFLAGS) mapogr.cpp -o mapogr.o
+mapserver.h: $(HEADERS)
+	touch mapserver.h
+
+.c.$(OBJ_SUFFIX): $(HEADERS)
+	$(LTCC) $(CC) -c $(CFLAGS) $< -o $@
 
-php_mapscript:: $(LIBMAP_STATIC)
-	cd mapscript/php; $(MAKE); cd ../..
+mapserv.$(OBJ_SUFFIX): mapserv.c $(HEADERS)
+	$(LTCC) $(CC) -c $(CFLAGS) $(FASTCGI_INC) mapserv.c -o $@
 
+.cpp.$(OBJ_SUFFIX): mapserver.h
+	$(LTCXX) $(CXX) -c $(CXXFLAGS) $< -o $@
+   
 maplexer.o: maplexer.c mapserver.h mapfile.h
 
 mapparser.o: mapparser.c mapserver.h
@@ -333,78 +353,69 @@ mapparser.o: mapparser.c mapserver.h
 mapparser.c: mapparser.y
 	$(YACC) -d -omapparser.c mapparser.y
 
-lib:    $(LIBMAP_STATIC)
-libmapserver: $(LIBMAP_STATIC)
-libmapserver.a: mapserver.h $(OBJS)
-	$(AR) $(LIBMAP_STATIC) $(OBJS)
-	$(RANLIB) $(LIBMAP_STATIC)
-	# We don't want to let the shared library get out of sync with the
-	# static library if it exists. 
-	if test -r $(LIBMAP_SHARED) ; then \
-	  make shared ; \
-	fi
+mod_mapserver.la: $(LIBMAP) mod_mapserver.c
+	$(APXS) -c -Wc,"$(CFLAGS)" $(LIBMAP) mod_mapserver.c
 
-shared:	$(LIBMAP_SHARED)
-$(LIBMAP_SHARED):	$(LIBMAP_STATIC)
-	$(LD_SHARED) $(LD_SONAME_LIBMAP) -o $(LIBMAP_SH_VER) \
-		$(RUNPATHS) $(OBJS) $(SUP_LIBS) $(STATIC_LIBS) \
-	&& ln -f -s $(LIBMAP_SH_VER) $(LIBMAP_SHARED)
+mapscript: mapscriptvars mapserver-config
 
-shp2pdf: $(LIBMAP_STATIC) shp2pdf.o mapserver.h
-	$(LD) $(CFLAGS) shp2pdf.o $(EXE_LDFLAGS) -o shp2pdf
+$(LIBMAP): $(OBJS)
+	$(LINK) -release $(MS_VERSION)  $(OBJS) $(SUP_LIBS) -o $(LIBMAP)
 
-shp2img: $(LIBMAP_STATIC)  shp2img.o mapserver.h
-	$(LD) $(CFLAGS) shp2img.o $(EXE_LDFLAGS) -o shp2img
+shp2pdf: $(LIBMAP) shp2pdf.$(OBJ_SUFFIX)
+	$(LINK) shp2pdf.$(OBJ_SUFFIX) $(LIBMAP) -o shp2pdf
 
-sym2img: $(LIBMAP_STATIC)   sym2img.o mapserver.h
-	$(LD) $(CFLAGS) sym2img.o $(EXE_LDFLAGS) -o sym2img
+shp2img: $(LIBMAP) shp2img.$(OBJ_SUFFIX)
+	$(LINK) shp2img.$(OBJ_SUFFIX) $(LIBMAP) -o shp2img
 
-legend: $(LIBMAP_STATIC)  legend.o mapserver.h
-	$(LD) $(CFLAGS) legend.o $(EXE_LDFLAGS) -o legend
+sym2img:  sym2img.$(OBJ_SUFFIX) $(LIBMAP)
+	$(LINK) sym2img.$(OBJ_SUFFIX) $(LIBMAP) -o sym2img
 
-scalebar: $(LIBMAP_STATIC)  scalebar.o mapserver.h
-	$(LD) $(CFLAGS) scalebar.o $(EXE_LDFLAGS) -o scalebar
+legend: legend.$(OBJ_SUFFIX) $(LIBMAP)
+	$(LINK) legend.$(OBJ_SUFFIX) $(LIBMAP) -o legend
 
-mapserv: mapserv.h maptile.h $(LIBMAP_STATIC)  mapserv.o cgiutil.o maptile.o mapserver.h
-	$(LD) $(CFLAGS) mapserv.o cgiutil.o maptile.o $(EXE_LDFLAGS) -o mapserv
+scalebar: scalebar.$(OBJ_SUFFIX) $(LIBMAP)
+	$(LINK) scalebar.$(OBJ_SUFFIX) $(LIBMAP) -o scalebar
 
-shpindex: $(LIBMAP_STATIC) shpindex.o mapserver.h
-	$(LD) $(CFLAGS) shpindex.o $(EXE_LDFLAGS) -o shpindex
+mapserv: mapserv.$(OBJ_SUFFIX) $(LIBMAP)
+	$(LINK) mapserv.$(OBJ_SUFFIX) $(LIBMAP) $(FASTCGI_LIB) -o mapserv
 
-shptree: $(LIBMAP_STATIC) shptree.o mapserver.h
-	$(LD) $(CFLAGS) shptree.o $(EXE_LDFLAGS) -o shptree
+shpindex: shpindex.$(OBJ_SUFFIX) $(LIBMAP)
+	$(LINK) shpindex.$(OBJ_SUFFIX) $(LIBMAP) -o shpindex
 
-shptreevis: $(LIBMAP_STATIC) shptreevis.o mapserver.h
-	$(LD) $(CFLAGS) shptreevis.o $(EXE_LDFLAGS) -o shptreevis
+shptree: shptree.$(OBJ_SUFFIX) $(LIBMAP)
+	$(LINK) shptree.$(OBJ_SUFFIX) $(LIBMAP) -o shptree
 
-shptreetst: $(LIBMAP_STATIC) shptreetst.o mapserver.h
-	$(LD) $(CFLAGS) shptreetst.o $(EXE_LDFLAGS) -o shptreetst
+shptreevis: shptreevis.$(OBJ_SUFFIX) $(LIBMAP)
+	$(LINK) shptreevis.$(OBJ_SUFFIX) $(LIBMAP) -o shptreevis
 
-sortshp: $(LIBMAP_STATIC) sortshp.o mapserver.h
-	$(LD) $(CFLAGS) sortshp.o $(EXE_LDFLAGS) -o sortshp
+shptreetst: shptreetst.$(OBJ_SUFFIX) $(LIBMAP)
+	$(LINK) shptreetst.$(OBJ_SUFFIX) $(LIBMAP) -o shptreetst
 
-tile4ms: $(LIBMAP_STATIC) tile4ms.o mapserver.h
-	$(LD) $(CFLAGS) tile4ms.o $(EXE_LDFLAGS) -o tile4ms
+sortshp: sortshp.$(OBJ_SUFFIX) $(LIBMAP)
+	$(LINK) sortshp.$(OBJ_SUFFIX) $(LIBMAP) -o sortshp
 
-msencrypt: $(LIBMAP_STATIC) msencrypt.o mapserver.h
-	$(LD) $(CFLAGS) msencrypt.o $(EXE_LDFLAGS) -o msencrypt
+tile4ms: tile4ms.$(OBJ_SUFFIX) $(LIBMAP)
+	$(LINK) tile4ms.$(OBJ_SUFFIX) $(LIBMAP) -o tile4ms
 
-testexpr: $(LIBMAP_STATIC) testexpr.o mapparser.o maplexer.o mapserver.h
-	$(LD) $(CFLAGS) testexpr.o $(EXE_LDFLAGS) -o testexpr
+msencrypt: msencrypt.$(OBJ_SUFFIX) $(LIBMAP)
+	$(LINK) msencrypt.$(OBJ_SUFFIX) $(LIBMAP) -o msencrypt
 
-testcopy: $(LIBMAP_STATIC) testcopy.o mapcopy.o mapserver.h
-	$(LD) $(CFLAGS) testcopy.o $(EXE_LDFLAGS) -o testcopy
+testexpr: testexpr.$(OBJ_SUFFIX) mapparser.$(OBJ_SUFFIX) maplexer.$(OBJ_SUFFIX) $(LIBMAP)
+	$(LINK) testexpr.$(OBJ_SUFFIX) $(LIBMAP) -o testexpr
 
-test_mapcrypto: $(LIBMAP_STATIC) mapcrypto.c mapserver.h
-	$(CC) $(CFLAGS) mapcrypto.c -DTEST_MAPCRYPTO $(EXE_LDFLAGS) -o test_mapcrypto
+testcopy: testcopy.$(OBJ_SUFFIX) $(LIBMAP)
+	$(LINK) testcopy.$(OBJ_SUFFIX) $(LIBMAP) -o testcopy
+
+test_mapcrypto: mapcrypto.c mapserver.h $(LIBMAP)
+	$(LINK) mapcrypto.c -DTEST_MAPCRYPTO $(LIBMAP) -o test_mapcrypto
 
 mapscriptvars:	Makefile
 	touch mapscriptvars
 	pwd > mapscriptvars
 	echo $(IGNORE_MISSING_DATA) $(USE_POINT_Z_M) $(STRINGS) @ALL_ENABLED@ >> mapscriptvars
 	echo -I. $(PROJ_INC) $(GD_INC) $(TTF_INC) $(JPEG_INC) $(SDE_INC) $(OGR_INC) $(GDAL_INC) $(GEOS_INC) >> mapscriptvars
+	echo $(LIBMAP) >> mapscriptvars
 	echo $(EXE_LDFLAGS) >> mapscriptvars
-	echo $(STATIC_LIBS) >> mapscriptvars
 	grep '#define MS_VERSION ' mapserver.h >> mapscriptvars
 
 mapserver-config: Makefile
@@ -415,45 +426,108 @@ mapserver-config: Makefile
 	echo 'CONFIG_CFLAGS="$(CFLAGS)"' >> mapserver-config
 	echo 'CONFIG_DEFINES="$(DEFINES)"' >> mapserver-config
 	echo 'CONFIG_INCLUDES="$(INCLUDES)"' >> mapserver-config
-	echo 'CONFIG_VERSION="'`grep '#define MS_VERSION ' mapserver.h | sed 's/\"//g' | sed 's/#define MS_VERSION //'`'"' >> mapserver-config
+	echo 'CONFIG_VERSION="'`grep '#define MS_VERSION ' mapserver.h | $(SED) 's/\"//g' | $(SED) 's/#define MS_VERSION //'`'"' >> mapserver-config
 	cat mapserver-config.in >> mapserver-config
 	chmod a+x mapserver-config
 
-php_mapscript_clean::
-	cd mapscript/php; $(MAKE) clean; cd ../..
+php_mapscript: $(LIBMAP)
+	cd mapscript/php; $(MAKE) $(MFLAGS);
+
+php_mapscript_clean:
+	test -z "$(PHP_MAPSCRIPT)" || (cd mapscript/php; $(MAKE) clean;)
+
+php_mapscript_install:
+	test -z "$(PHP_MAPSCRIPT)" || (cd mapscript/php; $(MAKE) install DESTDIR=$(DESTDIR);)
+
+python_mapscript: $(LIBMAP)
+	cd mapscript/python; $(MAKE) $(MFLAGS);
+
+python_mapscript_clean:
+	test -z "$(PYTHON_MAPSCRIPT)" || (cd mapscript/python; $(MAKE) clean;)
+
+python_mapscript_install:
+	test -z "$(PYTHON_MAPSCRIPT)" || (cd mapscript/python; $(MAKE) install DESTDIR=$(DESTDIR);)
 
-install:
+install: install-lib install-bin install-cgibin php_mapscript_install python_mapscript_install
+
+install-cgibin: install-lib mapserv
+	$(LTINSTALL) $(INSTALL) mapserv $(DESTDIR)$(bindir)/mapserv
 	@echo ""
-	@echo "***** MapServer Installation *****"
-	@echo "To install MapServer, copy the 'mapserv' file to your web server's cgi-bin "
-	@echo "directory."
+	@echo "***** MapServer CGI / FastCGI Installation *****"
+	@echo "To install MapServer, copy or symlink the \"$(bindir)/mapserv\" file"
+	@echo "to your web server's cgi-bin directory."
 	@echo "If you use MapScript then see the documentation for your specific MapScript"
 	@echo "version for installation instructions."
 	@echo ""
 
-install-force:	all
-	cp $(EXE_LIST) $(INST_BIN)
-	if test -x $(LIBMAP_SHARED) ; then \
-	  cp $(LIBMAP_SH_VER) $(INST_LIB) ; \
-	  (cd $(INST_LIB) ; ln -f -s $(LIBMAP_SH_VER) $(LIBMAP_SHARED) ) ; \
-	fi
+install-dirs:
+	$(INSTALL) -d $(DESTDIR)$(bindir) $(DESTDIR)$(libdir)
+
+install-bin: install-dirs install-lib $(EXE_LIST)
+	@list='$(EXE_LIST)'; for p in $$list; do \
+	  if test -f $$p; then \
+	    $(LTINSTALL) $(INSTALL) $$p $(DESTDIR)$(bindir)/$$p; \
+	  else :; fi; \
+	done
+
+install-lib: install-dirs $(LIBMAP)
+	$(LTINSTALL) $(INSTALL) $(LIBMAP) $(DESTDIR)$(libdir)/$(LIBMAP); \
 
 uninstall:
-	(cd $(INST_BIN) && rm $(EXE_LIST) )
-	(cd $(INST_LIB) && rm $(LIBMAP_SH_VER) $(LIBMAP_SHARED) )
+	@list='$(EXE_LIST)'; for p in $$list; do \
+	  if test -f $(DESTDIR)$(bindir)/$$p; then \
+	    $(LIBTOOL)  --mode=uninstall rm -f $(DESTDIR)$(bindir)/$$p; \
+	  else :; fi; \
+	done
+	$(LIBTOOL)  --mode=uninstall rm -f $(DESTDIR)$(libdir)/$(LIBMAP)
+
+install-module: mod_mapserver.la install-lib
+	$(APXS) -i -a -n "mapserver" mod_mapserver.la
 
-clean: @MAKE_PHPMS_CLEAN@
-	rm -f $(LIBMAP_STATIC) $(LIBMAP_SHARED) $(LIBMAP_SH_VER) *.o $(EXE_LIST) renderers/agg/src/*.o
+clean: php_mapscript_clean python_mapscript_clean
+	rm -rf $(LIBMAP) mapscriptvars *.o *.lo *.la .libs $(EXE_LIST) renderers/agg/src/*.o renderers/agg/src/*.lo renderers/agg/src/.libs
 
 exe-clean:
 	rm -f $(EXE_LIST)
 
 distclean:
 	$(MAKE) clean
-	rm config.*
+	rm config.log
 	if test -d autom4te.cache ; then \
 	  rm -f -r autom4te.cache ; \
 	fi
 
 sorta-clean:
-	rm -f *.o
+	rm -f *.o *.lo
+
+
+AUTOTEST_OPTS=-strict
+
+wxs-testcase:
+	cd msautotest/wxs && export PATH=../..:$(PATH) && ./run_test.py $(AUTOTEST_OPTS)
+
+renderers-testcase:
+	cd msautotest/renderers && export PATH=../..:$(PATH) && ./run_test.py $(AUTOTEST_OPTS)
+
+misc-testcase:
+	cd msautotest/misc && export PATH=../..:$(PATH) && ./run_test.py $(AUTOTEST_OPTS)
+
+gdal-testcase:
+	cd msautotest/gdal && export PATH=../..:$(PATH) && ./run_test.py $(AUTOTEST_OPTS)
+
+query-testcase:
+	cd msautotest/query && export PATH=../..:$(PATH) && ./run_test.py $(AUTOTEST_OPTS)
+
+autotest-install:
+	test -d "msautotest/wxs" ||  ( git submodule init && git submodule update )
+
+php-testcase:
+	test -z "$(PHP_MAPSCRIPT)" || (export PHP_MAPSCRIPT_SO="../../mapscript/php/.libs/php_mapscript.so" && cd msautotest/php && ./run_test.sh)
+
+print-test-results:
+	@./print-test-results.sh
+
+test: shp2img mapserv autotest-install $(PHP_MAPSCRIPT) $(PYTHON_MAPSCRIPT)
+	@$(MAKE) $(MFLAGS)	wxs-testcase renderers-testcase misc-testcase gdal-testcase query-testcase
+	@$(MAKE) print-test-results
+	@$(MAKE) php-testcase
diff --git a/Makefile.vc b/Makefile.vc
index 787d0b1..494c526 100644
--- a/Makefile.vc
+++ b/Makefile.vc
@@ -48,7 +48,7 @@ MS_OBJS = mapbits.obj maphash.obj mapshape.obj mapxbase.obj \
 		mapoglrenderer.obj mapoglcontext.obj mapogl.obj \
 		maptile.obj $(EPPL_OBJ) $(REGEX_OBJ) mapgeomtransform.obj mapunion.obj \
                 mapkmlrenderer.obj mapkml.obj mapdummyrenderer.obj mapgeomutil.obj mapquantization.obj \
-                mapogcfiltercommon.obj mapcluster.obj $(AGG_OBJ)
+                mapogcfiltercommon.obj mapcluster.obj mapuvraster.obj mapservutil.obj $(AGG_OBJ)
 
 MS_HDRS = 	mapserver.h mapfile.h
 
diff --git a/README b/README
index 277aab2..416d414 100644
--- a/README
+++ b/README
@@ -3,7 +3,7 @@ Summary
 -------
 
    
-The MapServer is a system for developing web-based GIS applications. 
+MapServer is a system for developing web-based GIS applications. 
 The basic system consists of a CGI program that can be configured to 
 respond to a variety of spatial requests like making maps, scalebars, 
 and point, area and feature queries. Virtually all aspects of an 
@@ -16,10 +16,10 @@ visit:
   http://www.mapserver.org/
 
 Bug reports and enhancment submissions can be reported in the MapServer 
-Bugzilla at the following url.   If you do make changes and/or enhancements, 
+issue tracker at the following url.   If you do make changes and/or enhancements, 
 please let us know so that they might be incorporated into future releases.
 
-  http://trac.osgeo.org/mapserver
+  https://github.com/mapserver/mapserver/issues
 
 
 Join the MapServer user mailing list online at:
@@ -87,3 +87,4 @@ License
   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 
   SOFTWARE.
 
+
diff --git a/README.CONFIGURE b/README.CONFIGURE
index e646300..71ce550 100644
--- a/README.CONFIGURE
+++ b/README.CONFIGURE
@@ -5,7 +5,7 @@ README.CONFIGURE - MapServer "configure" script compilation options
 For Unix users, Mapserver comes with a GNU autoconf "configure" script 
 that should take care of (hopefully!) all compilation issues for you.
 
-The configure script won't work on Windows NT.  See the file README.WIN32
+The configure script won't work on Windows.  See the file README.WIN32
 for details on compiling on Windows systems.
 
 The default configure behavior is to try to locate on your system the most
@@ -22,16 +22,19 @@ directory where you extracted the MapServer source code package and...
 
 ::
 
- $ cd mapserver-6.0.x
+ $ cd mapserver-6.2.x
  $ ./configure
  $ make
+ $ make install
 
-Unless something went wrong, you should have executables in the current 
-directory for the "mapserv" CGI program and the other utility programs.
-You can copy the "mapserv" program to your HTTP server's CGI directory
-and start using it.  
+Unless something went wrong, this should compile and install the "mapserv"
+CGI program and the other utility programs.
 
-See the MapServer web site at http://mapserver.gis.umn.edu/ for usage
+You should then locate the installed "mapserv" executable and link to it
+from your web server's cgi-bin directory. More information on how to do this
+is available at http://mapserver.org/installation/unix.html#installation
+
+See the MapServer web site at http://mapserver.org/ for usage
 instructions.
 
 
@@ -125,8 +128,8 @@ Optional Packages:
   --with-fastcgi=path     Enable FastCGI, point to installed tree.
   --with-httpd            Specify path to 'httpd' executable.
   --with-warnings[=flags] Enable strict warnings (or user defined warnings)
-  --with-php=DIR          Specify directory where PHP4's include files are
-                          installed (or a pointer to the full source tree)
+  --with-php=yes|no|/path/to/php-config
+                          Specify location of php-config script.
                           Required in order to compile the PHP/MapScript
                           module.
   --without-ld-shared     Disable shared library support
@@ -303,8 +306,21 @@ GEOS Support:
 - GEOS support is optional, and is not included by default.
   MapServer requires GEOS version 2.2.3 or more recent.
 
-- The GEOS library can be found at http://geos.refractions.net/
+- The GEOS library can be found at http://trac.osgeo.org/geos/
+
+
+XMP Support:
+------------
+
+::
 
+  --with-exempi=PATH
+
+- XMP support is optional, and is not incuded by default.
+
+- XMP support allows metadata (title, attribute, license, etc) to be directly embedded in the images generated by MapServer.
+
+- The exempi library can be found at http://libopenraw.freedesktop.org/wiki/Exempi
 
 
 OGR Support:
@@ -683,8 +699,8 @@ PHP/MapScript module:
 
 ::
 
-  --with-php=DIR          Specify directory where PHP4's include files are
-                          installed (or a pointer to the full source tree)
+  --with-php=yes|no|/path/to/php-config
+                          Specify location of php-config script.
                           Required in order to compile the PHP/MapScript
                           module.
   --enable-perlv-ld-detect (applies to --with-php only)
@@ -694,22 +710,15 @@ PHP/MapScript module:
 
 
 - The --with-php option will trigger the compilation of the PHP MapScript
-  module in the ./mapscript/php3/ directory.  
-
-- DIR should be the location of the PHP4 or PHP5 distribution (source or dev
-  package).  The module may work with older versions of PHP (4.1.x or 4.2.x), but 
-  PHP 4.3.x is strongly recommended. The configure script should 
-  automatically detect which version of PHP you are attempting to build 
-  with and take the necessary actions.
-
-    e.g.  $ ./configure --with-php=../php-4.3.11
-
-- The PHP module has to be built as a shared library that will then
-  be loaded as a Dynamic Module by the PHP interpreter using the dl()
-  PHP command.  See the Wiki for detailed build instructions for various
-  platforms: http://mapserver.gis.umn.edu/cgi-bin/wiki.pl?PHPMapScript
-  See also the file ./mapscript/php3/README for more details on the
-  MapScript classes and functions.  
+  module in the ./mapscript/php/ directory.  
+
+- The argument to the --with-php option is the full path to the php-config
+  script
+    e.g.  $ ./configure --with-php=/usr/local/bin/php-config
+
+- PHP MapScript now requires PHP 5.2.0 or more recent.
+  Support for PHP3 has been dropped after MapServer version 3.5.
+  Support for PHP4 has been dropped after MapServer version 5.6.
 
 - Some libraries are used by both PHP and MapServer, and using different 
   versions of these libs will lead to potential crashes at runtime.  In most
diff --git a/aclocal.m4 b/aclocal.m4
index 377a65c..55f3c92 100644
--- a/aclocal.m4
+++ b/aclocal.m4
@@ -1,376 +1,8620 @@
+# generated automatically by aclocal 1.11.3 -*- Autoconf -*-
 
-dnl
-dnl AC_EXPAND_PATH(path, variable)
-dnl
-dnl expands path to an absolute path and assigns it to variable
-dnl
-AC_DEFUN(AC_EXPAND_PATH,[
-  if test -z "$1" || echo "$1" | grep '^/' >/dev/null ; then
-    $2="$1"
-  else
-    $2="`pwd`/$1"
-  fi
-])
+# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
+# 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software Foundation,
+# Inc.
+# This file is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
 
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
+# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+# PARTICULAR PURPOSE.
 
-dnl
-dnl AC_PARSE_WITH_LIB_STATIC(with_param, out_libpath, out_isstatic)
-dnl
-dnl parse a --with-lib=[static,]/path/to/lib string, and set out_libpath 
-dnl with the library path, and out_isstatic=yes if "static," was there.
-dnl
-AC_DEFUN(AC_PARSE_WITH_LIB_STATIC,[
-  if echo "$1" | grep '^static,' >/dev/null ; then
-    $2=`echo "$1" | sed "s/^static,//"`
-    $3=yes
-  else
-    $2=$1
-    $3=no
-  fi
+# libtool.m4 - Configure libtool for the host system. -*-Autoconf-*-
+#
+#   Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005,
+#                 2006, 2007, 2008, 2009, 2010, 2011 Free Software
+#                 Foundation, Inc.
+#   Written by Gordon Matzigkeit, 1996
+#
+# This file is free software; the Free Software Foundation gives
+# unlimited permission to copy and/or distribute it, with or without
+# modifications, as long as this notice is preserved.
+
+m4_define([_LT_COPYING], [dnl
+#   Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005,
+#                 2006, 2007, 2008, 2009, 2010, 2011 Free Software
+#                 Foundation, Inc.
+#   Written by Gordon Matzigkeit, 1996
+#
+#   This file is part of GNU Libtool.
+#
+# GNU Libtool is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License as
+# published by the Free Software Foundation; either version 2 of
+# the License, or (at your option) any later version.
+#
+# As a special exception to the GNU General Public License,
+# if you distribute this file as part of a program or library that
+# is built using GNU Libtool, you may include this file under the
+# same distribution terms that you use for the rest of that program.
+#
+# GNU Libtool is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with GNU Libtool; see the file COPYING.  If not, a copy
+# can be downloaded from http://www.gnu.org/licenses/gpl.html, or
+# obtained by writing to the Free Software Foundation, Inc.,
+# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 ])
 
+# serial 57 LT_INIT
+
+
+# LT_PREREQ(VERSION)
+# ------------------
+# Complain and exit if this libtool version is less that VERSION.
+m4_defun([LT_PREREQ],
+[m4_if(m4_version_compare(m4_defn([LT_PACKAGE_VERSION]), [$1]), -1,
+       [m4_default([$3],
+		   [m4_fatal([Libtool version $1 or higher is required],
+		             63)])],
+       [$2])])
 
-AC_DEFUN(AC_COMPILER_PIC,
-[
-	echo 'void f(){}' > conftest.c
-	if test -z "`${CC} -fPIC -c conftest.c 2>&1`"; then
-	  C_PIC=-fPIC
-	else
-	  C_PIC=
-	fi
-	rm -f conftest*
 
-	AC_SUBST(C_PIC,$C_PIC)
+# _LT_CHECK_BUILDDIR
+# ------------------
+# Complain if the absolute build directory name contains unusual characters
+m4_defun([_LT_CHECK_BUILDDIR],
+[case `pwd` in
+  *\ * | *\	*)
+    AC_MSG_WARN([Libtool does not cope well with whitespace in `pwd`]) ;;
+esac
 ])
 
 
-dnl
-dnl check for -R, etc. switch
-dnl 
-dnl This was borrowed and adapted from the PHP configure.in script
-dnl
-AC_DEFUN(AC_RUNPATH_SWITCH,
-[
-  AC_MSG_CHECKING(if compiler supports -R)
-  AC_CACHE_VAL(php_cv_cc_dashr,[
-	SAVE_LIBS="${LIBS}"
-	LIBS="-R /usr/lib ${LIBS}"
-	AC_TRY_LINK([], [], php_cv_cc_dashr=yes, php_cv_cc_dashr=no)
-	LIBS="${SAVE_LIBS}"])
-  AC_MSG_RESULT($php_cv_cc_dashr)
-  if test $php_cv_cc_dashr = "yes"; then
-	ld_runpath_switch="-R"
-	apxs_runpath_switch="-Wl,-R'"
-  fi
-  if test -z "$ld_runpath_switch" ; then
-	AC_MSG_CHECKING([if compiler supports -Wl,-rpath,])
-	AC_CACHE_VAL(php_cv_cc_rpath,[
-		SAVE_LIBS="${LIBS}"
-		LIBS="-Wl,-rpath,/usr/lib ${LIBS}"
-		AC_TRY_LINK([], [], php_cv_cc_rpath=yes, php_cv_cc_rpath=no)
-		LIBS="${SAVE_LIBS}"])
-	AC_MSG_RESULT($php_cv_cc_rpath)
-	if test $php_cv_cc_rpath = "yes"; then
-		ld_runpath_switch="-Wl,-rpath,"
-		apxs_runpath_switch="-Wl,'-rpath "
-	fi
-  fi
-  if test -z "$ld_runpath_switch" ; then
-	AC_MSG_CHECKING([if compiler supports -Wl,-R])
-	AC_CACHE_VAL(php_cv_cc_dashwlr,[
-		SAVE_LIBS="${LIBS}"
-		LIBS="-Wl,-R/usr/lib ${LIBS}"
-		AC_TRY_LINK([], [], php_cv_cc_dashwlr=yes, php_cv_cc_dashwlr=no)
-		LIBS="${SAVE_LIBS}"])
-	AC_MSG_RESULT($php_cv_cc_dashwlr)
-	if test $php_cv_cc_rpath = "yes"; then
-		ld_runpath_switch="-Wl,-R"
-		apxs_runpath_switch="-Wl,-R'"
-	fi
-  fi
-  if test -z "$ld_runpath_switch" ; then
-	dnl something innocuous
-	ld_runpath_switch="-L"
-	apxs_runpath_switch="-L'"
-  fi
-  
+# LT_INIT([OPTIONS])
+# ------------------
+AC_DEFUN([LT_INIT],
+[AC_PREREQ([2.58])dnl We use AC_INCLUDES_DEFAULT
+AC_REQUIRE([AC_CONFIG_AUX_DIR_DEFAULT])dnl
+AC_BEFORE([$0], [LT_LANG])dnl
+AC_BEFORE([$0], [LT_OUTPUT])dnl
+AC_BEFORE([$0], [LTDL_INIT])dnl
+m4_require([_LT_CHECK_BUILDDIR])dnl
+
+dnl Autoconf doesn't catch unexpanded LT_ macros by default:
+m4_pattern_forbid([^_?LT_[A-Z_]+$])dnl
+m4_pattern_allow([^(_LT_EOF|LT_DLGLOBAL|LT_DLLAZY_OR_NOW|LT_MULTI_MODULE)$])dnl
+dnl aclocal doesn't pull ltoptions.m4, ltsugar.m4, or ltversion.m4
+dnl unless we require an AC_DEFUNed macro:
+AC_REQUIRE([LTOPTIONS_VERSION])dnl
+AC_REQUIRE([LTSUGAR_VERSION])dnl
+AC_REQUIRE([LTVERSION_VERSION])dnl
+AC_REQUIRE([LTOBSOLETE_VERSION])dnl
+m4_require([_LT_PROG_LTMAIN])dnl
+
+_LT_SHELL_INIT([SHELL=${CONFIG_SHELL-/bin/sh}])
+
+dnl Parse OPTIONS
+_LT_SET_OPTIONS([$0], [$1])
+
+# This can be used to rebuild libtool when needed
+LIBTOOL_DEPS="$ltmain"
+
+# Always use our own libtool.
+LIBTOOL='$(SHELL) $(top_builddir)/libtool'
+AC_SUBST(LIBTOOL)dnl
+
+_LT_SETUP
+
+# Only expand once:
+m4_define([LT_INIT])
+])# LT_INIT
+
+# Old names:
+AU_ALIAS([AC_PROG_LIBTOOL], [LT_INIT])
+AU_ALIAS([AM_PROG_LIBTOOL], [LT_INIT])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_PROG_LIBTOOL], [])
+dnl AC_DEFUN([AM_PROG_LIBTOOL], [])
+
+
+# _LT_CC_BASENAME(CC)
+# -------------------
+# Calculate cc_basename.  Skip known compiler wrappers and cross-prefix.
+m4_defun([_LT_CC_BASENAME],
+[for cc_temp in $1""; do
+  case $cc_temp in
+    compile | *[[\\/]]compile | ccache | *[[\\/]]ccache ) ;;
+    distcc | *[[\\/]]distcc | purify | *[[\\/]]purify ) ;;
+    \-*) ;;
+    *) break;;
+  esac
+done
+cc_basename=`$ECHO "$cc_temp" | $SED "s%.*/%%; s%^$host_alias-%%"`
 ])
 
 
+# _LT_FILEUTILS_DEFAULTS
+# ----------------------
+# It is okay to use these file commands and assume they have been set
+# sensibly after `m4_require([_LT_FILEUTILS_DEFAULTS])'.
+m4_defun([_LT_FILEUTILS_DEFAULTS],
+[: ${CP="cp -f"}
+: ${MV="mv -f"}
+: ${RM="rm -f"}
+])# _LT_FILEUTILS_DEFAULTS
+
+
+# _LT_SETUP
+# ---------
+m4_defun([_LT_SETUP],
+[AC_REQUIRE([AC_CANONICAL_HOST])dnl
+AC_REQUIRE([AC_CANONICAL_BUILD])dnl
+AC_REQUIRE([_LT_PREPARE_SED_QUOTE_VARS])dnl
+AC_REQUIRE([_LT_PROG_ECHO_BACKSLASH])dnl
+
+_LT_DECL([], [PATH_SEPARATOR], [1], [The PATH separator for the build system])dnl
 dnl
-dnl AC_PHP_ONCE(namespace, variable, code)
+_LT_DECL([], [host_alias], [0], [The host system])dnl
+_LT_DECL([], [host], [0])dnl
+_LT_DECL([], [host_os], [0])dnl
 dnl
-dnl execute code, if variable is not set in namespace
+_LT_DECL([], [build_alias], [0], [The build system])dnl
+_LT_DECL([], [build], [0])dnl
+_LT_DECL([], [build_os], [0])dnl
 dnl
-AC_DEFUN(AC_PHP_ONCE,[
-  unique=`echo $ac_n "$2$ac_c" | tr -c -d a-zA-Z0-9`
-  cmd="echo $ac_n \"\$$1$unique$ac_c\""
-  if test -n "$unique" && test "`eval $cmd`" = "" ; then
-    eval "$1$unique=set"
-    $3
-  fi
-])
-
+AC_REQUIRE([AC_PROG_CC])dnl
+AC_REQUIRE([LT_PATH_LD])dnl
+AC_REQUIRE([LT_PATH_NM])dnl
 dnl
-dnl AC_ADD_RUNPATH(path)
+AC_REQUIRE([AC_PROG_LN_S])dnl
+test -z "$LN_S" && LN_S="ln -s"
+_LT_DECL([], [LN_S], [1], [Whether we need soft or hard links])dnl
 dnl
-dnl add a library to linkpath/runpath stored in RPATH 
-dnl works together with AC_RUNPATH_SWITCH()
+AC_REQUIRE([LT_CMD_MAX_LEN])dnl
+_LT_DECL([objext], [ac_objext], [0], [Object file suffix (normally "o")])dnl
+_LT_DECL([], [exeext], [0], [Executable file suffix (normally "")])dnl
 dnl
-AC_DEFUN(AC_ADD_RUNPATH,[
-  if test "$1" != "/usr/lib"; then
-    AC_EXPAND_PATH($1, ai_p)
-    AC_PHP_ONCE(LIBPATH, $ai_p, [
-      EXTRA_LIBS="$EXTRA_LIBS -L$ai_p"
-dnl      if test -n "$APXS" ; then
-dnl        RPATHS="$RPATHS ${apxs_runpath_switch}$ai_p'"
-dnl      else
-        RPATHS="$RPATHS ${ld_runpath_switch}$ai_p"
-dnl      fi
-    ])
+m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+m4_require([_LT_CHECK_SHELL_FEATURES])dnl
+m4_require([_LT_PATH_CONVERSION_FUNCTIONS])dnl
+m4_require([_LT_CMD_RELOAD])dnl
+m4_require([_LT_CHECK_MAGIC_METHOD])dnl
+m4_require([_LT_CHECK_SHAREDLIB_FROM_LINKLIB])dnl
+m4_require([_LT_CMD_OLD_ARCHIVE])dnl
+m4_require([_LT_CMD_GLOBAL_SYMBOLS])dnl
+m4_require([_LT_WITH_SYSROOT])dnl
+
+_LT_CONFIG_LIBTOOL_INIT([
+# See if we are running on zsh, and set the options which allow our
+# commands through without removal of \ escapes INIT.
+if test -n "\${ZSH_VERSION+set}" ; then
+   setopt NO_GLOB_SUBST
+fi
+])
+if test -n "${ZSH_VERSION+set}" ; then
+   setopt NO_GLOB_SUBST
+fi
+
+_LT_CHECK_OBJDIR
+
+m4_require([_LT_TAG_COMPILER])dnl
+
+case $host_os in
+aix3*)
+  # AIX sometimes has problems with the GCC collect2 program.  For some
+  # reason, if we set the COLLECT_NAMES environment variable, the problems
+  # vanish in a puff of smoke.
+  if test "X${COLLECT_NAMES+set}" != Xset; then
+    COLLECT_NAMES=
+    export COLLECT_NAMES
+  fi
+  ;;
+esac
+
+# Global variables:
+ofile=libtool
+can_build_shared=yes
+
+# All known linkers require a `.a' archive for static linking (except MSVC,
+# which needs '.lib').
+libext=a
+
+with_gnu_ld="$lt_cv_prog_gnu_ld"
+
+old_CC="$CC"
+old_CFLAGS="$CFLAGS"
+
+# Set sane defaults for various variables
+test -z "$CC" && CC=cc
+test -z "$LTCC" && LTCC=$CC
+test -z "$LTCFLAGS" && LTCFLAGS=$CFLAGS
+test -z "$LD" && LD=ld
+test -z "$ac_objext" && ac_objext=o
+
+_LT_CC_BASENAME([$compiler])
+
+# Only perform the check for file, if the check method requires it
+test -z "$MAGIC_CMD" && MAGIC_CMD=file
+case $deplibs_check_method in
+file_magic*)
+  if test "$file_magic_cmd" = '$MAGIC_CMD'; then
+    _LT_PATH_MAGIC
   fi
+  ;;
+esac
+
+# Use C for the default configuration in the libtool script
+LT_SUPPORTED_TAG([CC])
+_LT_LANG_C_CONFIG
+_LT_LANG_DEFAULT_CONFIG
+_LT_CONFIG_COMMANDS
+])# _LT_SETUP
+
+
+# _LT_PREPARE_SED_QUOTE_VARS
+# --------------------------
+# Define a few sed substitution that help us do robust quoting.
+m4_defun([_LT_PREPARE_SED_QUOTE_VARS],
+[# Backslashify metacharacters that are still active within
+# double-quoted strings.
+sed_quote_subst='s/\([["`$\\]]\)/\\\1/g'
+
+# Same as above, but do not quote variable references.
+double_quote_subst='s/\([["`\\]]\)/\\\1/g'
+
+# Sed substitution to delay expansion of an escaped shell variable in a
+# double_quote_subst'ed string.
+delay_variable_subst='s/\\\\\\\\\\\$/\\\\\\$/g'
+
+# Sed substitution to delay expansion of an escaped single quote.
+delay_single_quote_subst='s/'\''/'\'\\\\\\\'\''/g'
+
+# Sed substitution to avoid accidental globbing in evaled expressions
+no_glob_subst='s/\*/\\\*/g'
 ])
 
+# _LT_PROG_LTMAIN
+# ---------------
+# Note that this code is called both from `configure', and `config.status'
+# now that we use AC_CONFIG_COMMANDS to generate libtool.  Notably,
+# `config.status' has no value for ac_aux_dir unless we are using Automake,
+# so we pass a copy along to make sure it has a sensible value anyway.
+m4_defun([_LT_PROG_LTMAIN],
+[m4_ifdef([AC_REQUIRE_AUX_FILE], [AC_REQUIRE_AUX_FILE([ltmain.sh])])dnl
+_LT_CONFIG_LIBTOOL_INIT([ac_aux_dir='$ac_aux_dir'])
+ltmain="$ac_aux_dir/ltmain.sh"
+])# _LT_PROG_LTMAIN
 
 
-dnl
-dnl Try to find something to link shared libraries with.  Use "c++ -shared"
-dnl in preference to "ld -shared" because it will link in required c++
-dnl run time support for us. 
-dnl
-AC_DEFUN(AC_LD_SHARED,
+
+# So that we can recreate a full libtool script including additional
+# tags, we accumulate the chunks of code to send to AC_CONFIG_COMMANDS
+# in macros and then make a single call at the end using the `libtool'
+# label.
+
+
+# _LT_CONFIG_LIBTOOL_INIT([INIT-COMMANDS])
+# ----------------------------------------
+# Register INIT-COMMANDS to be passed to AC_CONFIG_COMMANDS later.
+m4_define([_LT_CONFIG_LIBTOOL_INIT],
+[m4_ifval([$1],
+          [m4_append([_LT_OUTPUT_LIBTOOL_INIT],
+                     [$1
+])])])
+
+# Initialize.
+m4_define([_LT_OUTPUT_LIBTOOL_INIT])
+
+
+# _LT_CONFIG_LIBTOOL([COMMANDS])
+# ------------------------------
+# Register COMMANDS to be passed to AC_CONFIG_COMMANDS later.
+m4_define([_LT_CONFIG_LIBTOOL],
+[m4_ifval([$1],
+          [m4_append([_LT_OUTPUT_LIBTOOL_COMMANDS],
+                     [$1
+])])])
+
+# Initialize.
+m4_define([_LT_OUTPUT_LIBTOOL_COMMANDS])
+
+
+# _LT_CONFIG_SAVE_COMMANDS([COMMANDS], [INIT_COMMANDS])
+# -----------------------------------------------------
+m4_defun([_LT_CONFIG_SAVE_COMMANDS],
+[_LT_CONFIG_LIBTOOL([$1])
+_LT_CONFIG_LIBTOOL_INIT([$2])
+])
+
+
+# _LT_FORMAT_COMMENT([COMMENT])
+# -----------------------------
+# Add leading comment marks to the start of each line, and a trailing
+# full-stop to the whole comment if one is not present already.
+m4_define([_LT_FORMAT_COMMENT],
+[m4_ifval([$1], [
+m4_bpatsubst([m4_bpatsubst([$1], [^ *], [# ])],
+              [['`$\]], [\\\&])]m4_bmatch([$1], [[!?.]$], [], [.])
+)])
+
+
+
+
+
+# _LT_DECL([CONFIGNAME], VARNAME, VALUE, [DESCRIPTION], [IS-TAGGED?])
+# -------------------------------------------------------------------
+# CONFIGNAME is the name given to the value in the libtool script.
+# VARNAME is the (base) name used in the configure script.
+# VALUE may be 0, 1 or 2 for a computed quote escaped value based on
+# VARNAME.  Any other value will be used directly.
+m4_define([_LT_DECL],
+[lt_if_append_uniq([lt_decl_varnames], [$2], [, ],
+    [lt_dict_add_subkey([lt_decl_dict], [$2], [libtool_name],
+	[m4_ifval([$1], [$1], [$2])])
+    lt_dict_add_subkey([lt_decl_dict], [$2], [value], [$3])
+    m4_ifval([$4],
+	[lt_dict_add_subkey([lt_decl_dict], [$2], [description], [$4])])
+    lt_dict_add_subkey([lt_decl_dict], [$2],
+	[tagged?], [m4_ifval([$5], [yes], [no])])])
+])
+
+
+# _LT_TAGDECL([CONFIGNAME], VARNAME, VALUE, [DESCRIPTION])
+# --------------------------------------------------------
+m4_define([_LT_TAGDECL], [_LT_DECL([$1], [$2], [$3], [$4], [yes])])
+
+
+# lt_decl_tag_varnames([SEPARATOR], [VARNAME1...])
+# ------------------------------------------------
+m4_define([lt_decl_tag_varnames],
+[_lt_decl_filter([tagged?], [yes], $@)])
+
+
+# _lt_decl_filter(SUBKEY, VALUE, [SEPARATOR], [VARNAME1..])
+# ---------------------------------------------------------
+m4_define([_lt_decl_filter],
+[m4_case([$#],
+  [0], [m4_fatal([$0: too few arguments: $#])],
+  [1], [m4_fatal([$0: too few arguments: $#: $1])],
+  [2], [lt_dict_filter([lt_decl_dict], [$1], [$2], [], lt_decl_varnames)],
+  [3], [lt_dict_filter([lt_decl_dict], [$1], [$2], [$3], lt_decl_varnames)],
+  [lt_dict_filter([lt_decl_dict], $@)])[]dnl
+])
+
+
+# lt_decl_quote_varnames([SEPARATOR], [VARNAME1...])
+# --------------------------------------------------
+m4_define([lt_decl_quote_varnames],
+[_lt_decl_filter([value], [1], $@)])
+
+
+# lt_decl_dquote_varnames([SEPARATOR], [VARNAME1...])
+# ---------------------------------------------------
+m4_define([lt_decl_dquote_varnames],
+[_lt_decl_filter([value], [2], $@)])
+
+
+# lt_decl_varnames_tagged([SEPARATOR], [VARNAME1...])
+# ---------------------------------------------------
+m4_define([lt_decl_varnames_tagged],
+[m4_assert([$# <= 2])dnl
+_$0(m4_quote(m4_default([$1], [[, ]])),
+    m4_ifval([$2], [[$2]], [m4_dquote(lt_decl_tag_varnames)]),
+    m4_split(m4_normalize(m4_quote(_LT_TAGS)), [ ]))])
+m4_define([_lt_decl_varnames_tagged],
+[m4_ifval([$3], [lt_combine([$1], [$2], [_], $3)])])
+
+
+# lt_decl_all_varnames([SEPARATOR], [VARNAME1...])
+# ------------------------------------------------
+m4_define([lt_decl_all_varnames],
+[_$0(m4_quote(m4_default([$1], [[, ]])),
+     m4_if([$2], [],
+	   m4_quote(lt_decl_varnames),
+	m4_quote(m4_shift($@))))[]dnl
+])
+m4_define([_lt_decl_all_varnames],
+[lt_join($@, lt_decl_varnames_tagged([$1],
+			lt_decl_tag_varnames([[, ]], m4_shift($@))))dnl
+])
+
+
+# _LT_CONFIG_STATUS_DECLARE([VARNAME])
+# ------------------------------------
+# Quote a variable value, and forward it to `config.status' so that its
+# declaration there will have the same value as in `configure'.  VARNAME
+# must have a single quote delimited value for this to work.
+m4_define([_LT_CONFIG_STATUS_DECLARE],
+[$1='`$ECHO "$][$1" | $SED "$delay_single_quote_subst"`'])
+
+
+# _LT_CONFIG_STATUS_DECLARATIONS
+# ------------------------------
+# We delimit libtool config variables with single quotes, so when
+# we write them to config.status, we have to be sure to quote all
+# embedded single quotes properly.  In configure, this macro expands
+# each variable declared with _LT_DECL (and _LT_TAGDECL) into:
+#
+#    <var>='`$ECHO "$<var>" | $SED "$delay_single_quote_subst"`'
+m4_defun([_LT_CONFIG_STATUS_DECLARATIONS],
+[m4_foreach([_lt_var], m4_quote(lt_decl_all_varnames),
+    [m4_n([_LT_CONFIG_STATUS_DECLARE(_lt_var)])])])
+
+
+# _LT_LIBTOOL_TAGS
+# ----------------
+# Output comment and list of tags supported by the script
+m4_defun([_LT_LIBTOOL_TAGS],
+[_LT_FORMAT_COMMENT([The names of the tagged configurations supported by this script])dnl
+available_tags="_LT_TAGS"dnl
+])
+
+
+# _LT_LIBTOOL_DECLARE(VARNAME, [TAG])
+# -----------------------------------
+# Extract the dictionary values for VARNAME (optionally with TAG) and
+# expand to a commented shell variable setting:
+#
+#    # Some comment about what VAR is for.
+#    visible_name=$lt_internal_name
+m4_define([_LT_LIBTOOL_DECLARE],
+[_LT_FORMAT_COMMENT(m4_quote(lt_dict_fetch([lt_decl_dict], [$1],
+					   [description])))[]dnl
+m4_pushdef([_libtool_name],
+    m4_quote(lt_dict_fetch([lt_decl_dict], [$1], [libtool_name])))[]dnl
+m4_case(m4_quote(lt_dict_fetch([lt_decl_dict], [$1], [value])),
+    [0], [_libtool_name=[$]$1],
+    [1], [_libtool_name=$lt_[]$1],
+    [2], [_libtool_name=$lt_[]$1],
+    [_libtool_name=lt_dict_fetch([lt_decl_dict], [$1], [value])])[]dnl
+m4_ifval([$2], [_$2])[]m4_popdef([_libtool_name])[]dnl
+])
+
+
+# _LT_LIBTOOL_CONFIG_VARS
+# -----------------------
+# Produce commented declarations of non-tagged libtool config variables
+# suitable for insertion in the LIBTOOL CONFIG section of the `libtool'
+# script.  Tagged libtool config variables (even for the LIBTOOL CONFIG
+# section) are produced by _LT_LIBTOOL_TAG_VARS.
+m4_defun([_LT_LIBTOOL_CONFIG_VARS],
+[m4_foreach([_lt_var],
+    m4_quote(_lt_decl_filter([tagged?], [no], [], lt_decl_varnames)),
+    [m4_n([_LT_LIBTOOL_DECLARE(_lt_var)])])])
+
+
+# _LT_LIBTOOL_TAG_VARS(TAG)
+# -------------------------
+m4_define([_LT_LIBTOOL_TAG_VARS],
+[m4_foreach([_lt_var], m4_quote(lt_decl_tag_varnames),
+    [m4_n([_LT_LIBTOOL_DECLARE(_lt_var, [$1])])])])
+
+
+# _LT_TAGVAR(VARNAME, [TAGNAME])
+# ------------------------------
+m4_define([_LT_TAGVAR], [m4_ifval([$2], [$1_$2], [$1])])
+
+
+# _LT_CONFIG_COMMANDS
+# -------------------
+# Send accumulated output to $CONFIG_STATUS.  Thanks to the lists of
+# variables for single and double quote escaping we saved from calls
+# to _LT_DECL, we can put quote escaped variables declarations
+# into `config.status', and then the shell code to quote escape them in
+# for loops in `config.status'.  Finally, any additional code accumulated
+# from calls to _LT_CONFIG_LIBTOOL_INIT is expanded.
+m4_defun([_LT_CONFIG_COMMANDS],
+[AC_PROVIDE_IFELSE([LT_OUTPUT],
+	dnl If the libtool generation code has been placed in $CONFIG_LT,
+	dnl instead of duplicating it all over again into config.status,
+	dnl then we will have config.status run $CONFIG_LT later, so it
+	dnl needs to know what name is stored there:
+        [AC_CONFIG_COMMANDS([libtool],
+            [$SHELL $CONFIG_LT || AS_EXIT(1)], [CONFIG_LT='$CONFIG_LT'])],
+    dnl If the libtool generation code is destined for config.status,
+    dnl expand the accumulated commands and init code now:
+    [AC_CONFIG_COMMANDS([libtool],
+        [_LT_OUTPUT_LIBTOOL_COMMANDS], [_LT_OUTPUT_LIBTOOL_COMMANDS_INIT])])
+])#_LT_CONFIG_COMMANDS
+
+
+# Initialize.
+m4_define([_LT_OUTPUT_LIBTOOL_COMMANDS_INIT],
 [
 
-  echo 'void g(); int main(){ g(); return 0; }' > conftest1.c
-
-  echo '#include <stdio.h>' > conftest2.c
-  echo 'void g(); void g(){printf("");}' >> conftest2.c
-  ${CC} ${C_PIC} -c conftest2.c
-  SO_EXT="so"
-  SO_COMMAND_NAME="-soname"
-  export SO_EXT
-  export SO_COMMAND_NAME 
-  LD_SHARED="/bin/true"
-  if test ! -z "`uname -a | grep IRIX`" ; then
-    IRIX_ALL=-all
-  else
-    IRIX_ALL=
-  fi
+# The HP-UX ksh and POSIX shell print the target directory to stdout
+# if CDPATH is set.
+(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
 
-  AC_ARG_WITH(ld-shared,[  --with-ld-shared=CMD    Specify link command to use to build shared libs
-  --without-ld-shared     Disable shared library support],,)
+sed_quote_subst='$sed_quote_subst'
+double_quote_subst='$double_quote_subst'
+delay_variable_subst='$delay_variable_subst'
+_LT_CONFIG_STATUS_DECLARATIONS
+LTCC='$LTCC'
+LTCFLAGS='$LTCFLAGS'
+compiler='$compiler_DEFAULT'
 
-  dnl using --with-ld-shared with no CMD arg has no effect (but some people
-  dnl still try it!)
-  if test "$with_ld_shared" != "" -a "$with_ld_shared" != "yes"; then
-    if test "$with_ld_shared" = "no" ; then
-      AC_MSG_RESULT([user disabled shared library support.])
-    else
-      AC_MSG_RESULT([using user supplied .so link command ... $with_ld_shared])	
-    fi
-    LD_SHARED="$with_ld_shared"
-  fi
+# A function that is used when there is no print builtin or printf.
+func_fallback_echo ()
+{
+  eval 'cat <<_LTECHO_EOF
+\$[]1
+_LTECHO_EOF'
+}
 
-  dnl Check For Cygwin case.  Actually verify that the produced DLL works.
-  if test ! -z "`uname -a | grep CYGWIN`" \
-        -a "$LD_SHARED" = "/bin/true" ; then
-    if test -z "`gcc -shared conftest2.o -o libconftest.dll`" ; then
-      if test -z "`${CC} conftest1.c -L./ -lconftest -o conftest1 2>&1`"; then
-        LD_LIBRARY_PATH_OLD="$LD_LIBRARY_PATH"
-        if test -z "$LD_LIBRARY_PATH" ; then
-          LD_LIBRARY_PATH="`pwd`"
-        else
-          LD_LIBRARY_PATH="`pwd`:$LD_LIBRARY_PATH"
-        fi
-        export LD_LIBRARY_PATH
-        if test -z "`./conftest1 2>&1`" ; then
-          echo "checking for Cygwin gcc -shared ... yes"
-          LD_SHARED="c++ -shared"
-          SO_EXT="dll"
-        fi
-        LD_LIBRARY_PATH="$LD_LIBRARY_PATH_OLD"
-      fi
+# Quote evaled strings.
+for var in lt_decl_all_varnames([[ \
+]], lt_decl_quote_varnames); do
+    case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in
+    *[[\\\\\\\`\\"\\\$]]*)
+      eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED \\"\\\$sed_quote_subst\\"\\\`\\\\\\""
+      ;;
+    *)
+      eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\""
+      ;;
+    esac
+done
+
+# Double-quote double-evaled strings.
+for var in lt_decl_all_varnames([[ \
+]], lt_decl_dquote_varnames); do
+    case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in
+    *[[\\\\\\\`\\"\\\$]]*)
+      eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED -e \\"\\\$double_quote_subst\\" -e \\"\\\$sed_quote_subst\\" -e \\"\\\$delay_variable_subst\\"\\\`\\\\\\""
+      ;;
+    *)
+      eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\""
+      ;;
+    esac
+done
+
+_LT_OUTPUT_LIBTOOL_INIT
+])
+
+# _LT_GENERATED_FILE_INIT(FILE, [COMMENT])
+# ------------------------------------
+# Generate a child script FILE with all initialization necessary to
+# reuse the environment learned by the parent script, and make the
+# file executable.  If COMMENT is supplied, it is inserted after the
+# `#!' sequence but before initialization text begins.  After this
+# macro, additional text can be appended to FILE to form the body of
+# the child script.  The macro ends with non-zero status if the
+# file could not be fully written (such as if the disk is full).
+m4_ifdef([AS_INIT_GENERATED],
+[m4_defun([_LT_GENERATED_FILE_INIT],[AS_INIT_GENERATED($@)])],
+[m4_defun([_LT_GENERATED_FILE_INIT],
+[m4_require([AS_PREPARE])]dnl
+[m4_pushdef([AS_MESSAGE_LOG_FD])]dnl
+[lt_write_fail=0
+cat >$1 <<_ASEOF || lt_write_fail=1
+#! $SHELL
+# Generated by $as_me.
+$2
+SHELL=\${CONFIG_SHELL-$SHELL}
+export SHELL
+_ASEOF
+cat >>$1 <<\_ASEOF || lt_write_fail=1
+AS_SHELL_SANITIZE
+_AS_PREPARE
+exec AS_MESSAGE_FD>&1
+_ASEOF
+test $lt_write_fail = 0 && chmod +x $1[]dnl
+m4_popdef([AS_MESSAGE_LOG_FD])])])# _LT_GENERATED_FILE_INIT
+
+# LT_OUTPUT
+# ---------
+# This macro allows early generation of the libtool script (before
+# AC_OUTPUT is called), incase it is used in configure for compilation
+# tests.
+AC_DEFUN([LT_OUTPUT],
+[: ${CONFIG_LT=./config.lt}
+AC_MSG_NOTICE([creating $CONFIG_LT])
+_LT_GENERATED_FILE_INIT(["$CONFIG_LT"],
+[# Run this file to recreate a libtool stub with the current configuration.])
+
+cat >>"$CONFIG_LT" <<\_LTEOF
+lt_cl_silent=false
+exec AS_MESSAGE_LOG_FD>>config.log
+{
+  echo
+  AS_BOX([Running $as_me.])
+} >&AS_MESSAGE_LOG_FD
+
+lt_cl_help="\
+\`$as_me' creates a local libtool stub from the current configuration,
+for use in further configure time tests before the real libtool is
+generated.
+
+Usage: $[0] [[OPTIONS]]
+
+  -h, --help      print this help, then exit
+  -V, --version   print version number, then exit
+  -q, --quiet     do not print progress messages
+  -d, --debug     don't remove temporary files
+
+Report bugs to <bug-libtool at gnu.org>."
+
+lt_cl_version="\
+m4_ifset([AC_PACKAGE_NAME], [AC_PACKAGE_NAME ])config.lt[]dnl
+m4_ifset([AC_PACKAGE_VERSION], [ AC_PACKAGE_VERSION])
+configured by $[0], generated by m4_PACKAGE_STRING.
+
+Copyright (C) 2011 Free Software Foundation, Inc.
+This config.lt script is free software; the Free Software Foundation
+gives unlimited permision to copy, distribute and modify it."
+
+while test $[#] != 0
+do
+  case $[1] in
+    --version | --v* | -V )
+      echo "$lt_cl_version"; exit 0 ;;
+    --help | --h* | -h )
+      echo "$lt_cl_help"; exit 0 ;;
+    --debug | --d* | -d )
+      debug=: ;;
+    --quiet | --q* | --silent | --s* | -q )
+      lt_cl_silent=: ;;
+
+    -*) AC_MSG_ERROR([unrecognized option: $[1]
+Try \`$[0] --help' for more information.]) ;;
+
+    *) AC_MSG_ERROR([unrecognized argument: $[1]
+Try \`$[0] --help' for more information.]) ;;
+  esac
+  shift
+done
+
+if $lt_cl_silent; then
+  exec AS_MESSAGE_FD>/dev/null
+fi
+_LTEOF
+
+cat >>"$CONFIG_LT" <<_LTEOF
+_LT_OUTPUT_LIBTOOL_COMMANDS_INIT
+_LTEOF
+
+cat >>"$CONFIG_LT" <<\_LTEOF
+AC_MSG_NOTICE([creating $ofile])
+_LT_OUTPUT_LIBTOOL_COMMANDS
+AS_EXIT(0)
+_LTEOF
+chmod +x "$CONFIG_LT"
+
+# configure is writing to config.log, but config.lt does its own redirection,
+# appending to config.log, which fails on DOS, as config.log is still kept
+# open by configure.  Here we exec the FD to /dev/null, effectively closing
+# config.log, so it can be properly (re)opened and appended to by config.lt.
+lt_cl_success=:
+test "$silent" = yes &&
+  lt_config_lt_args="$lt_config_lt_args --quiet"
+exec AS_MESSAGE_LOG_FD>/dev/null
+$SHELL "$CONFIG_LT" $lt_config_lt_args || lt_cl_success=false
+exec AS_MESSAGE_LOG_FD>>config.log
+$lt_cl_success || AS_EXIT(1)
+])# LT_OUTPUT
+
+
+# _LT_CONFIG(TAG)
+# ---------------
+# If TAG is the built-in tag, create an initial libtool script with a
+# default configuration from the untagged config vars.  Otherwise add code
+# to config.status for appending the configuration named by TAG from the
+# matching tagged config vars.
+m4_defun([_LT_CONFIG],
+[m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+_LT_CONFIG_SAVE_COMMANDS([
+  m4_define([_LT_TAG], m4_if([$1], [], [C], [$1]))dnl
+  m4_if(_LT_TAG, [C], [
+    # See if we are running on zsh, and set the options which allow our
+    # commands through without removal of \ escapes.
+    if test -n "${ZSH_VERSION+set}" ; then
+      setopt NO_GLOB_SUBST
     fi
-  fi
 
+    cfgfile="${ofile}T"
+    trap "$RM \"$cfgfile\"; exit 1" 1 2 15
+    $RM "$cfgfile"
 
-  dnl Test special MacOS (Darwin) case. 
-  if test ! -z "`uname | grep Darwin`" \
-          -a "$LD_SHARED" = "/bin/true" ; then
-    if test -z "`${CXX} -dynamiclib conftest2.o -o libconftest.so 2>&1`" ; then
-      ${CC} -c conftest1.c
-      if test -z "`${CXX} conftest1.o libconftest.so -o conftest1 2>&1`"; then
-        DYLD_LIBRARY_PATH_OLD="$DYLD_LIBRARY_PATH"
-        if test -z "$DYLD_LIBRARY_PATH" ; then
-          DYLD_LIBRARY_PATH="`pwd`"
-        else
-          DYLD_LIBRARY_PATH="`pwd`:$DYLD_LIBRARY_PATH"
-        fi
-        export DYLD_LIBRARY_PATH
-        if test -z "`./conftest1 2>&1`" ; then
-          echo "checking for ${CXX} -dynamiclib ... yes"
-          LD_SHARED="${CXX} -dynamiclib -single_module -flat_namespace -undefined suppress"
-	  SO_EXT=dylib
-          SO_COMMAND_NAME='-dylib_install_name'
-        fi
-        DYLD_LIBRARY_PATH="$DYLD_LIBRARY_PATH_OLD"
-      fi
-      rm -f conftest1.o
-    fi 
+    cat <<_LT_EOF >> "$cfgfile"
+#! $SHELL
+
+# `$ECHO "$ofile" | sed 's%^.*/%%'` - Provide generalized library-building support services.
+# Generated automatically by $as_me ($PACKAGE$TIMESTAMP) $VERSION
+# Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`:
+# NOTE: Changes made to this file will be lost: look at ltmain.sh.
+#
+_LT_COPYING
+_LT_LIBTOOL_TAGS
+
+# ### BEGIN LIBTOOL CONFIG
+_LT_LIBTOOL_CONFIG_VARS
+_LT_LIBTOOL_TAG_VARS
+# ### END LIBTOOL CONFIG
+
+_LT_EOF
+
+  case $host_os in
+  aix3*)
+    cat <<\_LT_EOF >> "$cfgfile"
+# AIX sometimes has problems with the GCC collect2 program.  For some
+# reason, if we set the COLLECT_NAMES environment variable, the problems
+# vanish in a puff of smoke.
+if test "X${COLLECT_NAMES+set}" != Xset; then
+  COLLECT_NAMES=
+  export COLLECT_NAMES
+fi
+_LT_EOF
+    ;;
+  esac
+
+  _LT_PROG_LTMAIN
+
+  # We use sed instead of cat because bash on DJGPP gets confused if
+  # if finds mixed CR/LF and LF-only lines.  Since sed operates in
+  # text mode, it properly converts lines to CR/LF.  This bash problem
+  # is reportedly fixed, but why not run on old versions too?
+  sed '$q' "$ltmain" >> "$cfgfile" \
+     || (rm -f "$cfgfile"; exit 1)
+
+  _LT_PROG_REPLACE_SHELLFNS
+
+   mv -f "$cfgfile" "$ofile" ||
+    (rm -f "$ofile" && cp "$cfgfile" "$ofile" && rm -f "$cfgfile")
+  chmod +x "$ofile"
+],
+[cat <<_LT_EOF >> "$ofile"
+
+dnl Unfortunately we have to use $1 here, since _LT_TAG is not expanded
+dnl in a comment (ie after a #).
+# ### BEGIN LIBTOOL TAG CONFIG: $1
+_LT_LIBTOOL_TAG_VARS(_LT_TAG)
+# ### END LIBTOOL TAG CONFIG: $1
+_LT_EOF
+])dnl /m4_if
+],
+[m4_if([$1], [], [
+    PACKAGE='$PACKAGE'
+    VERSION='$VERSION'
+    TIMESTAMP='$TIMESTAMP'
+    RM='$RM'
+    ofile='$ofile'], [])
+])dnl /_LT_CONFIG_SAVE_COMMANDS
+])# _LT_CONFIG
+
+
+# LT_SUPPORTED_TAG(TAG)
+# ---------------------
+# Trace this macro to discover what tags are supported by the libtool
+# --tag option, using:
+#    autoconf --trace 'LT_SUPPORTED_TAG:$1'
+AC_DEFUN([LT_SUPPORTED_TAG], [])
+
+
+# C support is built-in for now
+m4_define([_LT_LANG_C_enabled], [])
+m4_define([_LT_TAGS], [])
+
+
+# LT_LANG(LANG)
+# -------------
+# Enable libtool support for the given language if not already enabled.
+AC_DEFUN([LT_LANG],
+[AC_BEFORE([$0], [LT_OUTPUT])dnl
+m4_case([$1],
+  [C],			[_LT_LANG(C)],
+  [C++],		[_LT_LANG(CXX)],
+  [Go],			[_LT_LANG(GO)],
+  [Java],		[_LT_LANG(GCJ)],
+  [Fortran 77],		[_LT_LANG(F77)],
+  [Fortran],		[_LT_LANG(FC)],
+  [Windows Resource],	[_LT_LANG(RC)],
+  [m4_ifdef([_LT_LANG_]$1[_CONFIG],
+    [_LT_LANG($1)],
+    [m4_fatal([$0: unsupported language: "$1"])])])dnl
+])# LT_LANG
+
+
+# _LT_LANG(LANGNAME)
+# ------------------
+m4_defun([_LT_LANG],
+[m4_ifdef([_LT_LANG_]$1[_enabled], [],
+  [LT_SUPPORTED_TAG([$1])dnl
+  m4_append([_LT_TAGS], [$1 ])dnl
+  m4_define([_LT_LANG_]$1[_enabled], [])dnl
+  _LT_LANG_$1_CONFIG($1)])dnl
+])# _LT_LANG
+
+
+m4_ifndef([AC_PROG_GO], [
+# NOTE: This macro has been submitted for inclusion into   #
+#  GNU Autoconf as AC_PROG_GO.  When it is available in    #
+#  a released version of Autoconf we should remove this    #
+#  macro and use it instead.                               #
+m4_defun([AC_PROG_GO],
+[AC_LANG_PUSH(Go)dnl
+AC_ARG_VAR([GOC],     [Go compiler command])dnl
+AC_ARG_VAR([GOFLAGS], [Go compiler flags])dnl
+_AC_ARG_VAR_LDFLAGS()dnl
+AC_CHECK_TOOL(GOC, gccgo)
+if test -z "$GOC"; then
+  if test -n "$ac_tool_prefix"; then
+    AC_CHECK_PROG(GOC, [${ac_tool_prefix}gccgo], [${ac_tool_prefix}gccgo])
   fi
+fi
+if test -z "$GOC"; then
+  AC_CHECK_PROG(GOC, gccgo, gccgo, false)
+fi
+])#m4_defun
+])#m4_ifndef
 
-  if test "$LD_SHARED" = "/bin/true" \
-	-a -z "`${CXX} -shared $IRIX_ALL conftest2.o -o libconftest.so 2>&1|grep -v WARNING`" ; then
-    if test -z "`${CC} conftest1.c libconftest.so -o conftest1 2>&1`"; then
-      LD_LIBRARY_PATH_OLD="$LD_LIBRARY_PATH"
-      if test -z "$LD_LIBRARY_PATH" ; then
-        LD_LIBRARY_PATH="`pwd`"
-      else
-        LD_LIBRARY_PATH="`pwd`:$LD_LIBRARY_PATH"
-      fi
-      export LD_LIBRARY_PATH
-      if test -z "`./conftest1 2>&1`" ; then
-        echo "checking for ${CXX} -shared ... yes"
-        LD_SHARED="${CXX} -shared $IRIX_ALL"
+
+# _LT_LANG_DEFAULT_CONFIG
+# -----------------------
+m4_defun([_LT_LANG_DEFAULT_CONFIG],
+[AC_PROVIDE_IFELSE([AC_PROG_CXX],
+  [LT_LANG(CXX)],
+  [m4_define([AC_PROG_CXX], defn([AC_PROG_CXX])[LT_LANG(CXX)])])
+
+AC_PROVIDE_IFELSE([AC_PROG_F77],
+  [LT_LANG(F77)],
+  [m4_define([AC_PROG_F77], defn([AC_PROG_F77])[LT_LANG(F77)])])
+
+AC_PROVIDE_IFELSE([AC_PROG_FC],
+  [LT_LANG(FC)],
+  [m4_define([AC_PROG_FC], defn([AC_PROG_FC])[LT_LANG(FC)])])
+
+dnl The call to [A][M_PROG_GCJ] is quoted like that to stop aclocal
+dnl pulling things in needlessly.
+AC_PROVIDE_IFELSE([AC_PROG_GCJ],
+  [LT_LANG(GCJ)],
+  [AC_PROVIDE_IFELSE([A][M_PROG_GCJ],
+    [LT_LANG(GCJ)],
+    [AC_PROVIDE_IFELSE([LT_PROG_GCJ],
+      [LT_LANG(GCJ)],
+      [m4_ifdef([AC_PROG_GCJ],
+	[m4_define([AC_PROG_GCJ], defn([AC_PROG_GCJ])[LT_LANG(GCJ)])])
+       m4_ifdef([A][M_PROG_GCJ],
+	[m4_define([A][M_PROG_GCJ], defn([A][M_PROG_GCJ])[LT_LANG(GCJ)])])
+       m4_ifdef([LT_PROG_GCJ],
+	[m4_define([LT_PROG_GCJ], defn([LT_PROG_GCJ])[LT_LANG(GCJ)])])])])])
+
+AC_PROVIDE_IFELSE([AC_PROG_GO],
+  [LT_LANG(GO)],
+  [m4_define([AC_PROG_GO], defn([AC_PROG_GO])[LT_LANG(GO)])])
+
+AC_PROVIDE_IFELSE([LT_PROG_RC],
+  [LT_LANG(RC)],
+  [m4_define([LT_PROG_RC], defn([LT_PROG_RC])[LT_LANG(RC)])])
+])# _LT_LANG_DEFAULT_CONFIG
+
+# Obsolete macros:
+AU_DEFUN([AC_LIBTOOL_CXX], [LT_LANG(C++)])
+AU_DEFUN([AC_LIBTOOL_F77], [LT_LANG(Fortran 77)])
+AU_DEFUN([AC_LIBTOOL_FC], [LT_LANG(Fortran)])
+AU_DEFUN([AC_LIBTOOL_GCJ], [LT_LANG(Java)])
+AU_DEFUN([AC_LIBTOOL_RC], [LT_LANG(Windows Resource)])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_LIBTOOL_CXX], [])
+dnl AC_DEFUN([AC_LIBTOOL_F77], [])
+dnl AC_DEFUN([AC_LIBTOOL_FC], [])
+dnl AC_DEFUN([AC_LIBTOOL_GCJ], [])
+dnl AC_DEFUN([AC_LIBTOOL_RC], [])
+
+
+# _LT_TAG_COMPILER
+# ----------------
+m4_defun([_LT_TAG_COMPILER],
+[AC_REQUIRE([AC_PROG_CC])dnl
+
+_LT_DECL([LTCC], [CC], [1], [A C compiler])dnl
+_LT_DECL([LTCFLAGS], [CFLAGS], [1], [LTCC compiler flags])dnl
+_LT_TAGDECL([CC], [compiler], [1], [A language specific compiler])dnl
+_LT_TAGDECL([with_gcc], [GCC], [0], [Is the compiler the GNU compiler?])dnl
+
+# If no C compiler was specified, use CC.
+LTCC=${LTCC-"$CC"}
+
+# If no C compiler flags were specified, use CFLAGS.
+LTCFLAGS=${LTCFLAGS-"$CFLAGS"}
+
+# Allow CC to be a program name with arguments.
+compiler=$CC
+])# _LT_TAG_COMPILER
+
+
+# _LT_COMPILER_BOILERPLATE
+# ------------------------
+# Check for compiler boilerplate output or warnings with
+# the simple compiler test code.
+m4_defun([_LT_COMPILER_BOILERPLATE],
+[m4_require([_LT_DECL_SED])dnl
+ac_outfile=conftest.$ac_objext
+echo "$lt_simple_compile_test_code" >conftest.$ac_ext
+eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
+_lt_compiler_boilerplate=`cat conftest.err`
+$RM conftest*
+])# _LT_COMPILER_BOILERPLATE
+
+
+# _LT_LINKER_BOILERPLATE
+# ----------------------
+# Check for linker boilerplate output or warnings with
+# the simple link test code.
+m4_defun([_LT_LINKER_BOILERPLATE],
+[m4_require([_LT_DECL_SED])dnl
+ac_outfile=conftest.$ac_objext
+echo "$lt_simple_link_test_code" >conftest.$ac_ext
+eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
+_lt_linker_boilerplate=`cat conftest.err`
+$RM -r conftest*
+])# _LT_LINKER_BOILERPLATE
+
+# _LT_REQUIRED_DARWIN_CHECKS
+# -------------------------
+m4_defun_once([_LT_REQUIRED_DARWIN_CHECKS],[
+  case $host_os in
+    rhapsody* | darwin*)
+    AC_CHECK_TOOL([DSYMUTIL], [dsymutil], [:])
+    AC_CHECK_TOOL([NMEDIT], [nmedit], [:])
+    AC_CHECK_TOOL([LIPO], [lipo], [:])
+    AC_CHECK_TOOL([OTOOL], [otool], [:])
+    AC_CHECK_TOOL([OTOOL64], [otool64], [:])
+    _LT_DECL([], [DSYMUTIL], [1],
+      [Tool to manipulate archived DWARF debug symbol files on Mac OS X])
+    _LT_DECL([], [NMEDIT], [1],
+      [Tool to change global to local symbols on Mac OS X])
+    _LT_DECL([], [LIPO], [1],
+      [Tool to manipulate fat objects and archives on Mac OS X])
+    _LT_DECL([], [OTOOL], [1],
+      [ldd/readelf like tool for Mach-O binaries on Mac OS X])
+    _LT_DECL([], [OTOOL64], [1],
+      [ldd/readelf like tool for 64 bit Mach-O binaries on Mac OS X 10.4])
+
+    AC_CACHE_CHECK([for -single_module linker flag],[lt_cv_apple_cc_single_mod],
+      [lt_cv_apple_cc_single_mod=no
+      if test -z "${LT_MULTI_MODULE}"; then
+	# By default we will add the -single_module flag. You can override
+	# by either setting the environment variable LT_MULTI_MODULE
+	# non-empty at configure time, or by adding -multi_module to the
+	# link flags.
+	rm -rf libconftest.dylib*
+	echo "int foo(void){return 1;}" > conftest.c
+	echo "$LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \
+-dynamiclib -Wl,-single_module conftest.c" >&AS_MESSAGE_LOG_FD
+	$LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \
+	  -dynamiclib -Wl,-single_module conftest.c 2>conftest.err
+        _lt_result=$?
+	# If there is a non-empty error log, and "single_module"
+	# appears in it, assume the flag caused a linker warning
+        if test -s conftest.err && $GREP single_module conftest.err; then
+	  cat conftest.err >&AS_MESSAGE_LOG_FD
+	# Otherwise, if the output was created with a 0 exit code from
+	# the compiler, it worked.
+	elif test -f libconftest.dylib && test $_lt_result -eq 0; then
+	  lt_cv_apple_cc_single_mod=yes
+	else
+	  cat conftest.err >&AS_MESSAGE_LOG_FD
+	fi
+	rm -rf libconftest.dylib*
+	rm -f conftest.*
+      fi])
+
+    AC_CACHE_CHECK([for -exported_symbols_list linker flag],
+      [lt_cv_ld_exported_symbols_list],
+      [lt_cv_ld_exported_symbols_list=no
+      save_LDFLAGS=$LDFLAGS
+      echo "_main" > conftest.sym
+      LDFLAGS="$LDFLAGS -Wl,-exported_symbols_list,conftest.sym"
+      AC_LINK_IFELSE([AC_LANG_PROGRAM([],[])],
+	[lt_cv_ld_exported_symbols_list=yes],
+	[lt_cv_ld_exported_symbols_list=no])
+	LDFLAGS="$save_LDFLAGS"
+    ])
+
+    AC_CACHE_CHECK([for -force_load linker flag],[lt_cv_ld_force_load],
+      [lt_cv_ld_force_load=no
+      cat > conftest.c << _LT_EOF
+int forced_loaded() { return 2;}
+_LT_EOF
+      echo "$LTCC $LTCFLAGS -c -o conftest.o conftest.c" >&AS_MESSAGE_LOG_FD
+      $LTCC $LTCFLAGS -c -o conftest.o conftest.c 2>&AS_MESSAGE_LOG_FD
+      echo "$AR cru libconftest.a conftest.o" >&AS_MESSAGE_LOG_FD
+      $AR cru libconftest.a conftest.o 2>&AS_MESSAGE_LOG_FD
+      echo "$RANLIB libconftest.a" >&AS_MESSAGE_LOG_FD
+      $RANLIB libconftest.a 2>&AS_MESSAGE_LOG_FD
+      cat > conftest.c << _LT_EOF
+int main() { return 0;}
+_LT_EOF
+      echo "$LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a" >&AS_MESSAGE_LOG_FD
+      $LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a 2>conftest.err
+      _lt_result=$?
+      if test -s conftest.err && $GREP force_load conftest.err; then
+	cat conftest.err >&AS_MESSAGE_LOG_FD
+      elif test -f conftest && test $_lt_result -eq 0 && $GREP forced_load conftest >/dev/null 2>&1 ; then
+	lt_cv_ld_force_load=yes
       else
-        echo "checking for ${CXX} -shared ... no(3)"
+	cat conftest.err >&AS_MESSAGE_LOG_FD
       fi
-      LD_LIBRARY_PATH="$LD_LIBRARY_PATH_OLD"
+        rm -f conftest.err libconftest.a conftest conftest.c
+        rm -rf conftest.dSYM
+    ])
+    case $host_os in
+    rhapsody* | darwin1.[[012]])
+      _lt_dar_allow_undefined='${wl}-undefined ${wl}suppress' ;;
+    darwin1.*)
+      _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;;
+    darwin*) # darwin 5.x on
+      # if running on 10.5 or later, the deployment target defaults
+      # to the OS version, if on x86, and 10.4, the deployment
+      # target defaults to 10.4. Don't you love it?
+      case ${MACOSX_DEPLOYMENT_TARGET-10.0},$host in
+	10.0,*86*-darwin8*|10.0,*-darwin[[91]]*)
+	  _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;;
+	10.[[012]]*)
+	  _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;;
+	10.*)
+	  _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;;
+      esac
+    ;;
+  esac
+    if test "$lt_cv_apple_cc_single_mod" = "yes"; then
+      _lt_dar_single_mod='$single_module'
+    fi
+    if test "$lt_cv_ld_exported_symbols_list" = "yes"; then
+      _lt_dar_export_syms=' ${wl}-exported_symbols_list,$output_objdir/${libname}-symbols.expsym'
     else
-      echo "checking for ${CXX} -shared ... no(2)"
+      _lt_dar_export_syms='~$NMEDIT -s $output_objdir/${libname}-symbols.expsym ${lib}'
     fi
-  else 
-    if test "$LD_SHARED" = "/bin/true" ; then
-      echo "checking for ${CXX} -shared ... no(1)"
+    if test "$DSYMUTIL" != ":" && test "$lt_cv_ld_force_load" = "no"; then
+      _lt_dsymutil='~$DSYMUTIL $lib || :'
+    else
+      _lt_dsymutil=
     fi
-  fi
+    ;;
+  esac
+])
 
-  if test "$LD_SHARED" = "/bin/true" \
-          -a -z "`ld -shared conftest2.o -o libconftest.so 2>&1`" ; then
-    if test -z "`${CC} conftest1.c libconftest.so -o conftest1 2>&1`"; then
-      LD_LIBRARY_PATH_OLD="$LD_LIBRARY_PATH"
-      if test -z "$LD_LIBRARY_PATH" ; then
-        LD_LIBRARY_PATH="`pwd`"
-      else
-        LD_LIBRARY_PATH="`pwd`:$LD_LIBRARY_PATH"
-      fi
-      export LD_LIBRARY_PATH
-      if test -z "`./conftest1 2>&1`" ; then
-        echo "checking for ld -shared ... yes"
-        LD_SHARED="ld -shared"
-      fi
-      LD_LIBRARY_PATH="$LD_LIBRARY_PATH_OLD"
-    fi
-  fi
 
-  if test "$LD_SHARED" = "/bin/true" ; then
-    echo "checking for ld -shared ... no"
-    if test ! -x /bin/true ; then
-      LD_SHARED=/usr/bin/true
-    fi
+# _LT_DARWIN_LINKER_FEATURES([TAG])
+# ---------------------------------
+# Checks for linker and compiler features on darwin
+m4_defun([_LT_DARWIN_LINKER_FEATURES],
+[
+  m4_require([_LT_REQUIRED_DARWIN_CHECKS])
+  _LT_TAGVAR(archive_cmds_need_lc, $1)=no
+  _LT_TAGVAR(hardcode_direct, $1)=no
+  _LT_TAGVAR(hardcode_automatic, $1)=yes
+  _LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported
+  if test "$lt_cv_ld_force_load" = "yes"; then
+    _LT_TAGVAR(whole_archive_flag_spec, $1)='`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience ${wl}-force_load,$conv\"; done; func_echo_all \"$new_convenience\"`'
+    m4_case([$1], [F77], [_LT_TAGVAR(compiler_needs_object, $1)=yes],
+                  [FC],  [_LT_TAGVAR(compiler_needs_object, $1)=yes])
+  else
+    _LT_TAGVAR(whole_archive_flag_spec, $1)=''
   fi
-  if test "$LD_SHARED" = "no" ; then
-    if test -x /bin/true ; then
-      LD_SHARED=/bin/true
-    else
-      LD_SHARED=/usr/bin/true
+  _LT_TAGVAR(link_all_deplibs, $1)=yes
+  _LT_TAGVAR(allow_undefined_flag, $1)="$_lt_dar_allow_undefined"
+  case $cc_basename in
+     ifort*) _lt_dar_can_shared=yes ;;
+     *) _lt_dar_can_shared=$GCC ;;
+  esac
+  if test "$_lt_dar_can_shared" = "yes"; then
+    output_verbose_link_cmd=func_echo_all
+    _LT_TAGVAR(archive_cmds, $1)="\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod${_lt_dsymutil}"
+    _LT_TAGVAR(module_cmds, $1)="\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dsymutil}"
+    _LT_TAGVAR(archive_expsym_cmds, $1)="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring ${_lt_dar_single_mod}${_lt_dar_export_syms}${_lt_dsymutil}"
+    _LT_TAGVAR(module_expsym_cmds, $1)="sed -e 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dar_export_syms}${_lt_dsymutil}"
+    m4_if([$1], [CXX],
+[   if test "$lt_cv_apple_cc_single_mod" != "yes"; then
+      _LT_TAGVAR(archive_cmds, $1)="\$CC -r -keep_private_externs -nostdlib -o \${lib}-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \${lib}-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring${_lt_dsymutil}"
+      _LT_TAGVAR(archive_expsym_cmds, $1)="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -r -keep_private_externs -nostdlib -o \${lib}-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \${lib}-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring${_lt_dar_export_syms}${_lt_dsymutil}"
     fi
+],[])
+  else
+  _LT_TAGVAR(ld_shlibs, $1)=no
+  fi
+])
+
+# _LT_SYS_MODULE_PATH_AIX([TAGNAME])
+# ----------------------------------
+# Links a minimal program and checks the executable
+# for the system default hardcoded library path. In most cases,
+# this is /usr/lib:/lib, but when the MPI compilers are used
+# the location of the communication and MPI libs are included too.
+# If we don't find anything, use the default library path according
+# to the aix ld manual.
+# Store the results from the different compilers for each TAGNAME.
+# Allow to override them for all tags through lt_cv_aix_libpath.
+m4_defun([_LT_SYS_MODULE_PATH_AIX],
+[m4_require([_LT_DECL_SED])dnl
+if test "${lt_cv_aix_libpath+set}" = set; then
+  aix_libpath=$lt_cv_aix_libpath
+else
+  AC_CACHE_VAL([_LT_TAGVAR([lt_cv_aix_libpath_], [$1])],
+  [AC_LINK_IFELSE([AC_LANG_PROGRAM],[
+  lt_aix_libpath_sed='[
+      /Import File Strings/,/^$/ {
+	  /^0/ {
+	      s/^0  *\([^ ]*\) *$/\1/
+	      p
+	  }
+      }]'
+  _LT_TAGVAR([lt_cv_aix_libpath_], [$1])=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"`
+  # Check for a 64-bit object if we didn't find anything.
+  if test -z "$_LT_TAGVAR([lt_cv_aix_libpath_], [$1])"; then
+    _LT_TAGVAR([lt_cv_aix_libpath_], [$1])=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"`
+  fi],[])
+  if test -z "$_LT_TAGVAR([lt_cv_aix_libpath_], [$1])"; then
+    _LT_TAGVAR([lt_cv_aix_libpath_], [$1])="/usr/lib:/lib"
   fi
+  ])
+  aix_libpath=$_LT_TAGVAR([lt_cv_aix_libpath_], [$1])
+fi
+])# _LT_SYS_MODULE_PATH_AIX
 
-  rm -f conftest* libconftest* 
 
-  AC_SUBST(LD_SHARED,$LD_SHARED)
-  AC_SUBST(SO_EXT,$SO_EXT)
-  AC_SUBST(SO_COMMAND_NAME,$SO_COMMAND_NAME)
-])
+# _LT_SHELL_INIT(ARG)
+# -------------------
+m4_define([_LT_SHELL_INIT],
+[m4_divert_text([M4SH-INIT], [$1
+])])# _LT_SHELL_INIT
 
-dnl
-dnl PHP on OSX (and potentially other platforms) does not use the 
-dnl same options for creating a shared MapScript that Python 
-dnl and a normal 'make shared' need to use.  The only way around 
-dnl this is to use our normal LD_SHARED stuff for everything 
-dnl except MacOSX.
-dnl
 
-AC_DEFUN(AC_PHP_LD_SHARED,[
 
+# _LT_PROG_ECHO_BACKSLASH
+# -----------------------
+# Find how we can fake an echo command that does not interpret backslash.
+# In particular, with Autoconf 2.60 or later we add some code to the start
+# of the generated configure script which will find a shell with a builtin
+# printf (which we can use as an echo command).
+m4_defun([_LT_PROG_ECHO_BACKSLASH],
+[ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
+ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO
+ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO$ECHO
 
-  AC_LD_SHARED()
-  
-  dnl Test special MacOS (Darwin) case.
-  if test ! -z "`uname | grep Darwin`" ;then
-          PHP_LD_SHARED="${CXX} -bundle -flat_namespace -undefined suppress"
-  else
-	  PHP_LD_SHARED=$LD_SHARED
-  fi
+AC_MSG_CHECKING([how to print strings])
+# Test print first, because it will be a builtin if present.
+if test "X`( print -r -- -n ) 2>/dev/null`" = X-n && \
+   test "X`print -r -- $ECHO 2>/dev/null`" = "X$ECHO"; then
+  ECHO='print -r --'
+elif test "X`printf %s $ECHO 2>/dev/null`" = "X$ECHO"; then
+  ECHO='printf %s\n'
+else
+  # Use this function as a fallback that always works.
+  func_fallback_echo ()
+  {
+    eval 'cat <<_LTECHO_EOF
+$[]1
+_LTECHO_EOF'
+  }
+  ECHO='func_fallback_echo'
+fi
 
-export PHP_LD_SHARED
-AC_SUBST(PHP_LD_SHARED,$PHP_LD_SHARED)
+# func_echo_all arg...
+# Invoke $ECHO with all args, space-separated.
+func_echo_all ()
+{
+    $ECHO "$*" 
+}
 
-])
+case "$ECHO" in
+  printf*) AC_MSG_RESULT([printf]) ;;
+  print*) AC_MSG_RESULT([print -r]) ;;
+  *) AC_MSG_RESULT([cat]) ;;
+esac
 
-dnl
-dnl The following macro is actually based on the "setup" script that
-dnl was included in the php-3.0.14 dl directory and will look at the 
-dnl Perl compile flags to figure the mechanism to build a shared lib
-dnl on this system.
-dnl This is the preferred macro for the PHP module, but if perl is not
-dnl available then we can always fallback on AC_LD_SHARED above.
-dnl
+m4_ifdef([_AS_DETECT_SUGGESTED],
+[_AS_DETECT_SUGGESTED([
+  test -n "${ZSH_VERSION+set}${BASH_VERSION+set}" || (
+    ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
+    ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO
+    ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO$ECHO
+    PATH=/empty FPATH=/empty; export PATH FPATH
+    test "X`printf %s $ECHO`" = "X$ECHO" \
+      || test "X`print -r -- $ECHO`" = "X$ECHO" )])])
 
-AC_DEFUN(AC_LD_SHARED_FROM_PERL,
-[
-#
-# The following is a massive hack.  It tries to steal the
-# mechanism for build a dynamic library from Perl's -V output
-# If this script fails on this machine, try running 'perl -V'
-# manually and pick out the setting for:
-#   
-#    cc, optimize, ccflags, ld, cccdlflags and lddlflags
-#
-# Replace the below definitions with the output you see.
-#
+_LT_DECL([], [SHELL], [1], [Shell to use when invoking shell scripts])
+_LT_DECL([], [ECHO], [1], [An echo program that protects backslashes])
+])# _LT_PROG_ECHO_BACKSLASH
 
-if test ! -r "perl.out"; then
-	perl -V > perl.out
-fi
-
-# if the greps and cuts don't do the job, set these manually
-PERL_CC="`grep ' cc=' perl.out | cut -d, -f1 | cut -d\' -f2 | grep -v undef`"
-PERL_OPT="`grep ' optimize=' perl.out | cut -d, -f2 | cut -d\' -f2 | grep -v undef`"
-PERL_CCFLAGS="`grep ' ccflags' perl.out | cut -d, -f1 | grep cflags | cut -d\' -f2 | grep -v undef` `grep ' ccflags' perl.out | cut -d, -f2 | grep ccflags | cut -d\' -f2 | grep -v undef`"
-PERL_LD="`grep ' ld=' perl.out | cut -d, -f1 | cut -d\' -f2 | grep -v undef`"
-PERL_LFLAGS="`grep ' cccdlflags=' perl.out | cut -d, -f1 | cut -d\' -f2 | grep -v undef`"
-PERL_CCDLFLAGS="`grep ' ccdlflags=' perl.out | cut -d, -f4 | cut -d\' -f2 | sed 's, ,,' | grep -v undef`"
-PERL_LDDLFLAGS=`grep ' lddlflags' perl.out | cut -d, -f2 | cut -d\' -f2 | grep -v undef`
-#--------
-
-#if test -n "$PERL_CCDLFLAGS" ; then
-#	echo "-------------------------"
-#	echo "----- IMPORTANT !!! -----"
-#	echo "-------------------------"
-#	echo "To use PHP extensions on your OS, you will need to recompile "
-#	echo "PHP.                                                         "
-#	echo "You need to edit the Makefile in the php3 directory and add  "
-#	echo "$PERL_CCDLFLAGS to the start of the LDFLAGS line at the top  "
-#	echo "of the Makefile.  Then type: 'make clean; make'              "
-#	echo "You can still go ahead and build the extensions now by typing"
-#	echo "'make' in this directory.  They just won't work correctly    "
-#	echo "until you recompile your PHP.                                "
-#        echo "If you are compiling php as a module, you should also add    "
-#        echo "$PERL_CCDLFLAGS to the start of the EXTRA_LDFLAGS in Apache  "
-#        echo "Configuration file.  Note that if you are using the APACI    "
-#        echo "build mechanism you should make this change in the           "
-#        echo "Configuration.tmpl file instead.                             "
-#	echo "-------------------------"
-#	echo "-------------------------"
-#	echo "-------------------------"
-#fi
-
-PERL_CC="$PERL_CC $PERL_OPT $PERL_CCFLAGS -I. -I.. $PERL_LFLAGS"
-PERL_LD="$PERL_LD $PERL_LDDLFLAGS $PERL_CCDLFLAGS"
-
-rm -f perl.out
 
-])
+# _LT_WITH_SYSROOT
+# ----------------
+AC_DEFUN([_LT_WITH_SYSROOT],
+[AC_MSG_CHECKING([for sysroot])
+AC_ARG_WITH([sysroot],
+[  --with-sysroot[=DIR] Search for dependent libraries within DIR
+                        (or the compiler's sysroot if not specified).],
+[], [with_sysroot=no])
+
+dnl lt_sysroot will always be passed unquoted.  We quote it here
+dnl in case the user passed a directory name.
+lt_sysroot=
+case ${with_sysroot} in #(
+ yes)
+   if test "$GCC" = yes; then
+     lt_sysroot=`$CC --print-sysroot 2>/dev/null`
+   fi
+   ;; #(
+ /*)
+   lt_sysroot=`echo "$with_sysroot" | sed -e "$sed_quote_subst"`
+   ;; #(
+ no|'')
+   ;; #(
+ *)
+   AC_MSG_RESULT([${with_sysroot}])
+   AC_MSG_ERROR([The sysroot must be an absolute path.])
+   ;;
+esac
+
+ AC_MSG_RESULT([${lt_sysroot:-no}])
+_LT_DECL([], [lt_sysroot], [0], [The root where to search for ]dnl
+[dependent libraries, and in which our libraries should be installed.])])
+
+# _LT_ENABLE_LOCK
+# ---------------
+m4_defun([_LT_ENABLE_LOCK],
+[AC_ARG_ENABLE([libtool-lock],
+  [AS_HELP_STRING([--disable-libtool-lock],
+    [avoid locking (might break parallel builds)])])
+test "x$enable_libtool_lock" != xno && enable_libtool_lock=yes
+
+# Some flags need to be propagated to the compiler or linker for good
+# libtool support.
+case $host in
+ia64-*-hpux*)
+  # Find out which ABI we are using.
+  echo 'int i;' > conftest.$ac_ext
+  if AC_TRY_EVAL(ac_compile); then
+    case `/usr/bin/file conftest.$ac_objext` in
+      *ELF-32*)
+	HPUX_IA64_MODE="32"
+	;;
+      *ELF-64*)
+	HPUX_IA64_MODE="64"
+	;;
+    esac
+  fi
+  rm -rf conftest*
+  ;;
+*-*-irix6*)
+  # Find out which ABI we are using.
+  echo '[#]line '$LINENO' "configure"' > conftest.$ac_ext
+  if AC_TRY_EVAL(ac_compile); then
+    if test "$lt_cv_prog_gnu_ld" = yes; then
+      case `/usr/bin/file conftest.$ac_objext` in
+	*32-bit*)
+	  LD="${LD-ld} -melf32bsmip"
+	  ;;
+	*N32*)
+	  LD="${LD-ld} -melf32bmipn32"
+	  ;;
+	*64-bit*)
+	  LD="${LD-ld} -melf64bmip"
+	;;
+      esac
+    else
+      case `/usr/bin/file conftest.$ac_objext` in
+	*32-bit*)
+	  LD="${LD-ld} -32"
+	  ;;
+	*N32*)
+	  LD="${LD-ld} -n32"
+	  ;;
+	*64-bit*)
+	  LD="${LD-ld} -64"
+	  ;;
+      esac
+    fi
+  fi
+  rm -rf conftest*
+  ;;
+
+x86_64-*kfreebsd*-gnu|x86_64-*linux*|ppc*-*linux*|powerpc*-*linux*| \
+s390*-*linux*|s390*-*tpf*|sparc*-*linux*)
+  # Find out which ABI we are using.
+  echo 'int i;' > conftest.$ac_ext
+  if AC_TRY_EVAL(ac_compile); then
+    case `/usr/bin/file conftest.o` in
+      *32-bit*)
+	case $host in
+	  x86_64-*kfreebsd*-gnu)
+	    LD="${LD-ld} -m elf_i386_fbsd"
+	    ;;
+	  x86_64-*linux*)
+	    LD="${LD-ld} -m elf_i386"
+	    ;;
+	  ppc64-*linux*|powerpc64-*linux*)
+	    LD="${LD-ld} -m elf32ppclinux"
+	    ;;
+	  s390x-*linux*)
+	    LD="${LD-ld} -m elf_s390"
+	    ;;
+	  sparc64-*linux*)
+	    LD="${LD-ld} -m elf32_sparc"
+	    ;;
+	esac
+	;;
+      *64-bit*)
+	case $host in
+	  x86_64-*kfreebsd*-gnu)
+	    LD="${LD-ld} -m elf_x86_64_fbsd"
+	    ;;
+	  x86_64-*linux*)
+	    LD="${LD-ld} -m elf_x86_64"
+	    ;;
+	  ppc*-*linux*|powerpc*-*linux*)
+	    LD="${LD-ld} -m elf64ppc"
+	    ;;
+	  s390*-*linux*|s390*-*tpf*)
+	    LD="${LD-ld} -m elf64_s390"
+	    ;;
+	  sparc*-*linux*)
+	    LD="${LD-ld} -m elf64_sparc"
+	    ;;
+	esac
+	;;
+    esac
+  fi
+  rm -rf conftest*
+  ;;
+
+*-*-sco3.2v5*)
+  # On SCO OpenServer 5, we need -belf to get full-featured binaries.
+  SAVE_CFLAGS="$CFLAGS"
+  CFLAGS="$CFLAGS -belf"
+  AC_CACHE_CHECK([whether the C compiler needs -belf], lt_cv_cc_needs_belf,
+    [AC_LANG_PUSH(C)
+     AC_LINK_IFELSE([AC_LANG_PROGRAM([[]],[[]])],[lt_cv_cc_needs_belf=yes],[lt_cv_cc_needs_belf=no])
+     AC_LANG_POP])
+  if test x"$lt_cv_cc_needs_belf" != x"yes"; then
+    # this is probably gcc 2.8.0, egcs 1.0 or newer; no need for -belf
+    CFLAGS="$SAVE_CFLAGS"
+  fi
+  ;;
+*-*solaris*)
+  # Find out which ABI we are using.
+  echo 'int i;' > conftest.$ac_ext
+  if AC_TRY_EVAL(ac_compile); then
+    case `/usr/bin/file conftest.o` in
+    *64-bit*)
+      case $lt_cv_prog_gnu_ld in
+      yes*)
+        case $host in
+        i?86-*-solaris*)
+          LD="${LD-ld} -m elf_x86_64"
+          ;;
+        sparc*-*-solaris*)
+          LD="${LD-ld} -m elf64_sparc"
+          ;;
+        esac
+        # GNU ld 2.21 introduced _sol2 emulations.  Use them if available.
+        if ${LD-ld} -V | grep _sol2 >/dev/null 2>&1; then
+          LD="${LD-ld}_sol2"
+        fi
+        ;;
+      *)
+	if ${LD-ld} -64 -r -o conftest2.o conftest.o >/dev/null 2>&1; then
+	  LD="${LD-ld} -64"
+	fi
+	;;
+      esac
+      ;;
+    esac
+  fi
+  rm -rf conftest*
+  ;;
+esac
+
+need_locks="$enable_libtool_lock"
+])# _LT_ENABLE_LOCK
+
+
+# _LT_PROG_AR
+# -----------
+m4_defun([_LT_PROG_AR],
+[AC_CHECK_TOOLS(AR, [ar], false)
+: ${AR=ar}
+: ${AR_FLAGS=cru}
+_LT_DECL([], [AR], [1], [The archiver])
+_LT_DECL([], [AR_FLAGS], [1], [Flags to create an archive])
+
+AC_CACHE_CHECK([for archiver @FILE support], [lt_cv_ar_at_file],
+  [lt_cv_ar_at_file=no
+   AC_COMPILE_IFELSE([AC_LANG_PROGRAM],
+     [echo conftest.$ac_objext > conftest.lst
+      lt_ar_try='$AR $AR_FLAGS libconftest.a @conftest.lst >&AS_MESSAGE_LOG_FD'
+      AC_TRY_EVAL([lt_ar_try])
+      if test "$ac_status" -eq 0; then
+	# Ensure the archiver fails upon bogus file names.
+	rm -f conftest.$ac_objext libconftest.a
+	AC_TRY_EVAL([lt_ar_try])
+	if test "$ac_status" -ne 0; then
+          lt_cv_ar_at_file=@
+        fi
+      fi
+      rm -f conftest.* libconftest.a
+     ])
+  ])
+
+if test "x$lt_cv_ar_at_file" = xno; then
+  archiver_list_spec=
+else
+  archiver_list_spec=$lt_cv_ar_at_file
+fi
+_LT_DECL([], [archiver_list_spec], [1],
+  [How to feed a file listing to the archiver])
+])# _LT_PROG_AR
+
+
+# _LT_CMD_OLD_ARCHIVE
+# -------------------
+m4_defun([_LT_CMD_OLD_ARCHIVE],
+[_LT_PROG_AR
+
+AC_CHECK_TOOL(STRIP, strip, :)
+test -z "$STRIP" && STRIP=:
+_LT_DECL([], [STRIP], [1], [A symbol stripping program])
+
+AC_CHECK_TOOL(RANLIB, ranlib, :)
+test -z "$RANLIB" && RANLIB=:
+_LT_DECL([], [RANLIB], [1],
+    [Commands used to install an old-style archive])
+
+# Determine commands to create old-style static archives.
+old_archive_cmds='$AR $AR_FLAGS $oldlib$oldobjs'
+old_postinstall_cmds='chmod 644 $oldlib'
+old_postuninstall_cmds=
+
+if test -n "$RANLIB"; then
+  case $host_os in
+  openbsd*)
+    old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB -t \$tool_oldlib"
+    ;;
+  *)
+    old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB \$tool_oldlib"
+    ;;
+  esac
+  old_archive_cmds="$old_archive_cmds~\$RANLIB \$tool_oldlib"
+fi
+
+case $host_os in
+  darwin*)
+    lock_old_archive_extraction=yes ;;
+  *)
+    lock_old_archive_extraction=no ;;
+esac
+_LT_DECL([], [old_postinstall_cmds], [2])
+_LT_DECL([], [old_postuninstall_cmds], [2])
+_LT_TAGDECL([], [old_archive_cmds], [2],
+    [Commands used to build an old-style archive])
+_LT_DECL([], [lock_old_archive_extraction], [0],
+    [Whether to use a lock for old archive extraction])
+])# _LT_CMD_OLD_ARCHIVE
+
+
+# _LT_COMPILER_OPTION(MESSAGE, VARIABLE-NAME, FLAGS,
+#		[OUTPUT-FILE], [ACTION-SUCCESS], [ACTION-FAILURE])
+# ----------------------------------------------------------------
+# Check whether the given compiler option works
+AC_DEFUN([_LT_COMPILER_OPTION],
+[m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+m4_require([_LT_DECL_SED])dnl
+AC_CACHE_CHECK([$1], [$2],
+  [$2=no
+   m4_if([$4], , [ac_outfile=conftest.$ac_objext], [ac_outfile=$4])
+   echo "$lt_simple_compile_test_code" > conftest.$ac_ext
+   lt_compiler_flag="$3"
+   # Insert the option either (1) after the last *FLAGS variable, or
+   # (2) before a word containing "conftest.", or (3) at the end.
+   # Note that $ac_compile itself does not contain backslashes and begins
+   # with a dollar sign (not a hyphen), so the echo should work correctly.
+   # The option is referenced via a variable to avoid confusing sed.
+   lt_compile=`echo "$ac_compile" | $SED \
+   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
+   -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \
+   -e 's:$: $lt_compiler_flag:'`
+   (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&AS_MESSAGE_LOG_FD)
+   (eval "$lt_compile" 2>conftest.err)
+   ac_status=$?
+   cat conftest.err >&AS_MESSAGE_LOG_FD
+   echo "$as_me:$LINENO: \$? = $ac_status" >&AS_MESSAGE_LOG_FD
+   if (exit $ac_status) && test -s "$ac_outfile"; then
+     # The compiler can only warn and ignore the option if not recognized
+     # So say no if there are warnings other than the usual output.
+     $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' >conftest.exp
+     $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
+     if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then
+       $2=yes
+     fi
+   fi
+   $RM conftest*
+])
+
+if test x"[$]$2" = xyes; then
+    m4_if([$5], , :, [$5])
+else
+    m4_if([$6], , :, [$6])
+fi
+])# _LT_COMPILER_OPTION
+
+# Old name:
+AU_ALIAS([AC_LIBTOOL_COMPILER_OPTION], [_LT_COMPILER_OPTION])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_LIBTOOL_COMPILER_OPTION], [])
+
+
+# _LT_LINKER_OPTION(MESSAGE, VARIABLE-NAME, FLAGS,
+#                  [ACTION-SUCCESS], [ACTION-FAILURE])
+# ----------------------------------------------------
+# Check whether the given linker option works
+AC_DEFUN([_LT_LINKER_OPTION],
+[m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+m4_require([_LT_DECL_SED])dnl
+AC_CACHE_CHECK([$1], [$2],
+  [$2=no
+   save_LDFLAGS="$LDFLAGS"
+   LDFLAGS="$LDFLAGS $3"
+   echo "$lt_simple_link_test_code" > conftest.$ac_ext
+   if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then
+     # The linker can only warn and ignore the option if not recognized
+     # So say no if there are warnings
+     if test -s conftest.err; then
+       # Append any errors to the config.log.
+       cat conftest.err 1>&AS_MESSAGE_LOG_FD
+       $ECHO "$_lt_linker_boilerplate" | $SED '/^$/d' > conftest.exp
+       $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
+       if diff conftest.exp conftest.er2 >/dev/null; then
+         $2=yes
+       fi
+     else
+       $2=yes
+     fi
+   fi
+   $RM -r conftest*
+   LDFLAGS="$save_LDFLAGS"
+])
+
+if test x"[$]$2" = xyes; then
+    m4_if([$4], , :, [$4])
+else
+    m4_if([$5], , :, [$5])
+fi
+])# _LT_LINKER_OPTION
+
+# Old name:
+AU_ALIAS([AC_LIBTOOL_LINKER_OPTION], [_LT_LINKER_OPTION])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_LIBTOOL_LINKER_OPTION], [])
+
+
+# LT_CMD_MAX_LEN
+#---------------
+AC_DEFUN([LT_CMD_MAX_LEN],
+[AC_REQUIRE([AC_CANONICAL_HOST])dnl
+# find the maximum length of command line arguments
+AC_MSG_CHECKING([the maximum length of command line arguments])
+AC_CACHE_VAL([lt_cv_sys_max_cmd_len], [dnl
+  i=0
+  teststring="ABCD"
+
+  case $build_os in
+  msdosdjgpp*)
+    # On DJGPP, this test can blow up pretty badly due to problems in libc
+    # (any single argument exceeding 2000 bytes causes a buffer overrun
+    # during glob expansion).  Even if it were fixed, the result of this
+    # check would be larger than it should be.
+    lt_cv_sys_max_cmd_len=12288;    # 12K is about right
+    ;;
+
+  gnu*)
+    # Under GNU Hurd, this test is not required because there is
+    # no limit to the length of command line arguments.
+    # Libtool will interpret -1 as no limit whatsoever
+    lt_cv_sys_max_cmd_len=-1;
+    ;;
+
+  cygwin* | mingw* | cegcc*)
+    # On Win9x/ME, this test blows up -- it succeeds, but takes
+    # about 5 minutes as the teststring grows exponentially.
+    # Worse, since 9x/ME are not pre-emptively multitasking,
+    # you end up with a "frozen" computer, even though with patience
+    # the test eventually succeeds (with a max line length of 256k).
+    # Instead, let's just punt: use the minimum linelength reported by
+    # all of the supported platforms: 8192 (on NT/2K/XP).
+    lt_cv_sys_max_cmd_len=8192;
+    ;;
+
+  mint*)
+    # On MiNT this can take a long time and run out of memory.
+    lt_cv_sys_max_cmd_len=8192;
+    ;;
+
+  amigaos*)
+    # On AmigaOS with pdksh, this test takes hours, literally.
+    # So we just punt and use a minimum line length of 8192.
+    lt_cv_sys_max_cmd_len=8192;
+    ;;
+
+  netbsd* | freebsd* | openbsd* | darwin* | dragonfly*)
+    # This has been around since 386BSD, at least.  Likely further.
+    if test -x /sbin/sysctl; then
+      lt_cv_sys_max_cmd_len=`/sbin/sysctl -n kern.argmax`
+    elif test -x /usr/sbin/sysctl; then
+      lt_cv_sys_max_cmd_len=`/usr/sbin/sysctl -n kern.argmax`
+    else
+      lt_cv_sys_max_cmd_len=65536	# usable default for all BSDs
+    fi
+    # And add a safety zone
+    lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4`
+    lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3`
+    ;;
+
+  interix*)
+    # We know the value 262144 and hardcode it with a safety zone (like BSD)
+    lt_cv_sys_max_cmd_len=196608
+    ;;
+
+  os2*)
+    # The test takes a long time on OS/2.
+    lt_cv_sys_max_cmd_len=8192
+    ;;
+
+  osf*)
+    # Dr. Hans Ekkehard Plesser reports seeing a kernel panic running configure
+    # due to this test when exec_disable_arg_limit is 1 on Tru64. It is not
+    # nice to cause kernel panics so lets avoid the loop below.
+    # First set a reasonable default.
+    lt_cv_sys_max_cmd_len=16384
+    #
+    if test -x /sbin/sysconfig; then
+      case `/sbin/sysconfig -q proc exec_disable_arg_limit` in
+        *1*) lt_cv_sys_max_cmd_len=-1 ;;
+      esac
+    fi
+    ;;
+  sco3.2v5*)
+    lt_cv_sys_max_cmd_len=102400
+    ;;
+  sysv5* | sco5v6* | sysv4.2uw2*)
+    kargmax=`grep ARG_MAX /etc/conf/cf.d/stune 2>/dev/null`
+    if test -n "$kargmax"; then
+      lt_cv_sys_max_cmd_len=`echo $kargmax | sed 's/.*[[	 ]]//'`
+    else
+      lt_cv_sys_max_cmd_len=32768
+    fi
+    ;;
+  *)
+    lt_cv_sys_max_cmd_len=`(getconf ARG_MAX) 2> /dev/null`
+    if test -n "$lt_cv_sys_max_cmd_len"; then
+      lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4`
+      lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3`
+    else
+      # Make teststring a little bigger before we do anything with it.
+      # a 1K string should be a reasonable start.
+      for i in 1 2 3 4 5 6 7 8 ; do
+        teststring=$teststring$teststring
+      done
+      SHELL=${SHELL-${CONFIG_SHELL-/bin/sh}}
+      # If test is not a shell built-in, we'll probably end up computing a
+      # maximum length that is only half of the actual maximum length, but
+      # we can't tell.
+      while { test "X"`env echo "$teststring$teststring" 2>/dev/null` \
+	         = "X$teststring$teststring"; } >/dev/null 2>&1 &&
+	      test $i != 17 # 1/2 MB should be enough
+      do
+        i=`expr $i + 1`
+        teststring=$teststring$teststring
+      done
+      # Only check the string length outside the loop.
+      lt_cv_sys_max_cmd_len=`expr "X$teststring" : ".*" 2>&1`
+      teststring=
+      # Add a significant safety factor because C++ compilers can tack on
+      # massive amounts of additional arguments before passing them to the
+      # linker.  It appears as though 1/2 is a usable value.
+      lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 2`
+    fi
+    ;;
+  esac
+])
+if test -n $lt_cv_sys_max_cmd_len ; then
+  AC_MSG_RESULT($lt_cv_sys_max_cmd_len)
+else
+  AC_MSG_RESULT(none)
+fi
+max_cmd_len=$lt_cv_sys_max_cmd_len
+_LT_DECL([], [max_cmd_len], [0],
+    [What is the maximum length of a command?])
+])# LT_CMD_MAX_LEN
+
+# Old name:
+AU_ALIAS([AC_LIBTOOL_SYS_MAX_CMD_LEN], [LT_CMD_MAX_LEN])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_LIBTOOL_SYS_MAX_CMD_LEN], [])
+
+
+# _LT_HEADER_DLFCN
+# ----------------
+m4_defun([_LT_HEADER_DLFCN],
+[AC_CHECK_HEADERS([dlfcn.h], [], [], [AC_INCLUDES_DEFAULT])dnl
+])# _LT_HEADER_DLFCN
+
+
+# _LT_TRY_DLOPEN_SELF (ACTION-IF-TRUE, ACTION-IF-TRUE-W-USCORE,
+#                      ACTION-IF-FALSE, ACTION-IF-CROSS-COMPILING)
+# ----------------------------------------------------------------
+m4_defun([_LT_TRY_DLOPEN_SELF],
+[m4_require([_LT_HEADER_DLFCN])dnl
+if test "$cross_compiling" = yes; then :
+  [$4]
+else
+  lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2
+  lt_status=$lt_dlunknown
+  cat > conftest.$ac_ext <<_LT_EOF
+[#line $LINENO "configure"
+#include "confdefs.h"
+
+#if HAVE_DLFCN_H
+#include <dlfcn.h>
+#endif
+
+#include <stdio.h>
+
+#ifdef RTLD_GLOBAL
+#  define LT_DLGLOBAL		RTLD_GLOBAL
+#else
+#  ifdef DL_GLOBAL
+#    define LT_DLGLOBAL		DL_GLOBAL
+#  else
+#    define LT_DLGLOBAL		0
+#  endif
+#endif
+
+/* We may have to define LT_DLLAZY_OR_NOW in the command line if we
+   find out it does not work in some platform. */
+#ifndef LT_DLLAZY_OR_NOW
+#  ifdef RTLD_LAZY
+#    define LT_DLLAZY_OR_NOW		RTLD_LAZY
+#  else
+#    ifdef DL_LAZY
+#      define LT_DLLAZY_OR_NOW		DL_LAZY
+#    else
+#      ifdef RTLD_NOW
+#        define LT_DLLAZY_OR_NOW	RTLD_NOW
+#      else
+#        ifdef DL_NOW
+#          define LT_DLLAZY_OR_NOW	DL_NOW
+#        else
+#          define LT_DLLAZY_OR_NOW	0
+#        endif
+#      endif
+#    endif
+#  endif
+#endif
+
+/* When -fvisbility=hidden is used, assume the code has been annotated
+   correspondingly for the symbols needed.  */
+#if defined(__GNUC__) && (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3))
+int fnord () __attribute__((visibility("default")));
+#endif
+
+int fnord () { return 42; }
+int main ()
+{
+  void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW);
+  int status = $lt_dlunknown;
+
+  if (self)
+    {
+      if (dlsym (self,"fnord"))       status = $lt_dlno_uscore;
+      else
+        {
+	  if (dlsym( self,"_fnord"))  status = $lt_dlneed_uscore;
+          else puts (dlerror ());
+	}
+      /* dlclose (self); */
+    }
+  else
+    puts (dlerror ());
+
+  return status;
+}]
+_LT_EOF
+  if AC_TRY_EVAL(ac_link) && test -s conftest${ac_exeext} 2>/dev/null; then
+    (./conftest; exit; ) >&AS_MESSAGE_LOG_FD 2>/dev/null
+    lt_status=$?
+    case x$lt_status in
+      x$lt_dlno_uscore) $1 ;;
+      x$lt_dlneed_uscore) $2 ;;
+      x$lt_dlunknown|x*) $3 ;;
+    esac
+  else :
+    # compilation failed
+    $3
+  fi
+fi
+rm -fr conftest*
+])# _LT_TRY_DLOPEN_SELF
+
+
+# LT_SYS_DLOPEN_SELF
+# ------------------
+AC_DEFUN([LT_SYS_DLOPEN_SELF],
+[m4_require([_LT_HEADER_DLFCN])dnl
+if test "x$enable_dlopen" != xyes; then
+  enable_dlopen=unknown
+  enable_dlopen_self=unknown
+  enable_dlopen_self_static=unknown
+else
+  lt_cv_dlopen=no
+  lt_cv_dlopen_libs=
+
+  case $host_os in
+  beos*)
+    lt_cv_dlopen="load_add_on"
+    lt_cv_dlopen_libs=
+    lt_cv_dlopen_self=yes
+    ;;
+
+  mingw* | pw32* | cegcc*)
+    lt_cv_dlopen="LoadLibrary"
+    lt_cv_dlopen_libs=
+    ;;
+
+  cygwin*)
+    lt_cv_dlopen="dlopen"
+    lt_cv_dlopen_libs=
+    ;;
+
+  darwin*)
+  # if libdl is installed we need to link against it
+    AC_CHECK_LIB([dl], [dlopen],
+		[lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"],[
+    lt_cv_dlopen="dyld"
+    lt_cv_dlopen_libs=
+    lt_cv_dlopen_self=yes
+    ])
+    ;;
+
+  *)
+    AC_CHECK_FUNC([shl_load],
+	  [lt_cv_dlopen="shl_load"],
+      [AC_CHECK_LIB([dld], [shl_load],
+	    [lt_cv_dlopen="shl_load" lt_cv_dlopen_libs="-ldld"],
+	[AC_CHECK_FUNC([dlopen],
+	      [lt_cv_dlopen="dlopen"],
+	  [AC_CHECK_LIB([dl], [dlopen],
+		[lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"],
+	    [AC_CHECK_LIB([svld], [dlopen],
+		  [lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-lsvld"],
+	      [AC_CHECK_LIB([dld], [dld_link],
+		    [lt_cv_dlopen="dld_link" lt_cv_dlopen_libs="-ldld"])
+	      ])
+	    ])
+	  ])
+	])
+      ])
+    ;;
+  esac
+
+  if test "x$lt_cv_dlopen" != xno; then
+    enable_dlopen=yes
+  else
+    enable_dlopen=no
+  fi
+
+  case $lt_cv_dlopen in
+  dlopen)
+    save_CPPFLAGS="$CPPFLAGS"
+    test "x$ac_cv_header_dlfcn_h" = xyes && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H"
+
+    save_LDFLAGS="$LDFLAGS"
+    wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\"
+
+    save_LIBS="$LIBS"
+    LIBS="$lt_cv_dlopen_libs $LIBS"
+
+    AC_CACHE_CHECK([whether a program can dlopen itself],
+	  lt_cv_dlopen_self, [dnl
+	  _LT_TRY_DLOPEN_SELF(
+	    lt_cv_dlopen_self=yes, lt_cv_dlopen_self=yes,
+	    lt_cv_dlopen_self=no, lt_cv_dlopen_self=cross)
+    ])
+
+    if test "x$lt_cv_dlopen_self" = xyes; then
+      wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $lt_prog_compiler_static\"
+      AC_CACHE_CHECK([whether a statically linked program can dlopen itself],
+	  lt_cv_dlopen_self_static, [dnl
+	  _LT_TRY_DLOPEN_SELF(
+	    lt_cv_dlopen_self_static=yes, lt_cv_dlopen_self_static=yes,
+	    lt_cv_dlopen_self_static=no,  lt_cv_dlopen_self_static=cross)
+      ])
+    fi
+
+    CPPFLAGS="$save_CPPFLAGS"
+    LDFLAGS="$save_LDFLAGS"
+    LIBS="$save_LIBS"
+    ;;
+  esac
+
+  case $lt_cv_dlopen_self in
+  yes|no) enable_dlopen_self=$lt_cv_dlopen_self ;;
+  *) enable_dlopen_self=unknown ;;
+  esac
+
+  case $lt_cv_dlopen_self_static in
+  yes|no) enable_dlopen_self_static=$lt_cv_dlopen_self_static ;;
+  *) enable_dlopen_self_static=unknown ;;
+  esac
+fi
+_LT_DECL([dlopen_support], [enable_dlopen], [0],
+	 [Whether dlopen is supported])
+_LT_DECL([dlopen_self], [enable_dlopen_self], [0],
+	 [Whether dlopen of programs is supported])
+_LT_DECL([dlopen_self_static], [enable_dlopen_self_static], [0],
+	 [Whether dlopen of statically linked programs is supported])
+])# LT_SYS_DLOPEN_SELF
+
+# Old name:
+AU_ALIAS([AC_LIBTOOL_DLOPEN_SELF], [LT_SYS_DLOPEN_SELF])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_LIBTOOL_DLOPEN_SELF], [])
+
+
+# _LT_COMPILER_C_O([TAGNAME])
+# ---------------------------
+# Check to see if options -c and -o are simultaneously supported by compiler.
+# This macro does not hard code the compiler like AC_PROG_CC_C_O.
+m4_defun([_LT_COMPILER_C_O],
+[m4_require([_LT_DECL_SED])dnl
+m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+m4_require([_LT_TAG_COMPILER])dnl
+AC_CACHE_CHECK([if $compiler supports -c -o file.$ac_objext],
+  [_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)],
+  [_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=no
+   $RM -r conftest 2>/dev/null
+   mkdir conftest
+   cd conftest
+   mkdir out
+   echo "$lt_simple_compile_test_code" > conftest.$ac_ext
+
+   lt_compiler_flag="-o out/conftest2.$ac_objext"
+   # Insert the option either (1) after the last *FLAGS variable, or
+   # (2) before a word containing "conftest.", or (3) at the end.
+   # Note that $ac_compile itself does not contain backslashes and begins
+   # with a dollar sign (not a hyphen), so the echo should work correctly.
+   lt_compile=`echo "$ac_compile" | $SED \
+   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
+   -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \
+   -e 's:$: $lt_compiler_flag:'`
+   (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&AS_MESSAGE_LOG_FD)
+   (eval "$lt_compile" 2>out/conftest.err)
+   ac_status=$?
+   cat out/conftest.err >&AS_MESSAGE_LOG_FD
+   echo "$as_me:$LINENO: \$? = $ac_status" >&AS_MESSAGE_LOG_FD
+   if (exit $ac_status) && test -s out/conftest2.$ac_objext
+   then
+     # The compiler can only warn and ignore the option if not recognized
+     # So say no if there are warnings
+     $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' > out/conftest.exp
+     $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2
+     if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then
+       _LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=yes
+     fi
+   fi
+   chmod u+w . 2>&AS_MESSAGE_LOG_FD
+   $RM conftest*
+   # SGI C++ compiler will create directory out/ii_files/ for
+   # template instantiation
+   test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files
+   $RM out/* && rmdir out
+   cd ..
+   $RM -r conftest
+   $RM conftest*
+])
+_LT_TAGDECL([compiler_c_o], [lt_cv_prog_compiler_c_o], [1],
+	[Does compiler simultaneously support -c and -o options?])
+])# _LT_COMPILER_C_O
+
+
+# _LT_COMPILER_FILE_LOCKS([TAGNAME])
+# ----------------------------------
+# Check to see if we can do hard links to lock some files if needed
+m4_defun([_LT_COMPILER_FILE_LOCKS],
+[m4_require([_LT_ENABLE_LOCK])dnl
+m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+_LT_COMPILER_C_O([$1])
+
+hard_links="nottested"
+if test "$_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)" = no && test "$need_locks" != no; then
+  # do not overwrite the value of need_locks provided by the user
+  AC_MSG_CHECKING([if we can lock with hard links])
+  hard_links=yes
+  $RM conftest*
+  ln conftest.a conftest.b 2>/dev/null && hard_links=no
+  touch conftest.a
+  ln conftest.a conftest.b 2>&5 || hard_links=no
+  ln conftest.a conftest.b 2>/dev/null && hard_links=no
+  AC_MSG_RESULT([$hard_links])
+  if test "$hard_links" = no; then
+    AC_MSG_WARN([`$CC' does not support `-c -o', so `make -j' may be unsafe])
+    need_locks=warn
+  fi
+else
+  need_locks=no
+fi
+_LT_DECL([], [need_locks], [1], [Must we lock files when doing compilation?])
+])# _LT_COMPILER_FILE_LOCKS
+
+
+# _LT_CHECK_OBJDIR
+# ----------------
+m4_defun([_LT_CHECK_OBJDIR],
+[AC_CACHE_CHECK([for objdir], [lt_cv_objdir],
+[rm -f .libs 2>/dev/null
+mkdir .libs 2>/dev/null
+if test -d .libs; then
+  lt_cv_objdir=.libs
+else
+  # MS-DOS does not allow filenames that begin with a dot.
+  lt_cv_objdir=_libs
+fi
+rmdir .libs 2>/dev/null])
+objdir=$lt_cv_objdir
+_LT_DECL([], [objdir], [0],
+         [The name of the directory that contains temporary libtool files])dnl
+m4_pattern_allow([LT_OBJDIR])dnl
+AC_DEFINE_UNQUOTED(LT_OBJDIR, "$lt_cv_objdir/",
+  [Define to the sub-directory in which libtool stores uninstalled libraries.])
+])# _LT_CHECK_OBJDIR
+
+
+# _LT_LINKER_HARDCODE_LIBPATH([TAGNAME])
+# --------------------------------------
+# Check hardcoding attributes.
+m4_defun([_LT_LINKER_HARDCODE_LIBPATH],
+[AC_MSG_CHECKING([how to hardcode library paths into programs])
+_LT_TAGVAR(hardcode_action, $1)=
+if test -n "$_LT_TAGVAR(hardcode_libdir_flag_spec, $1)" ||
+   test -n "$_LT_TAGVAR(runpath_var, $1)" ||
+   test "X$_LT_TAGVAR(hardcode_automatic, $1)" = "Xyes" ; then
+
+  # We can hardcode non-existent directories.
+  if test "$_LT_TAGVAR(hardcode_direct, $1)" != no &&
+     # If the only mechanism to avoid hardcoding is shlibpath_var, we
+     # have to relink, otherwise we might link with an installed library
+     # when we should be linking with a yet-to-be-installed one
+     ## test "$_LT_TAGVAR(hardcode_shlibpath_var, $1)" != no &&
+     test "$_LT_TAGVAR(hardcode_minus_L, $1)" != no; then
+    # Linking always hardcodes the temporary library directory.
+    _LT_TAGVAR(hardcode_action, $1)=relink
+  else
+    # We can link without hardcoding, and we can hardcode nonexisting dirs.
+    _LT_TAGVAR(hardcode_action, $1)=immediate
+  fi
+else
+  # We cannot hardcode anything, or else we can only hardcode existing
+  # directories.
+  _LT_TAGVAR(hardcode_action, $1)=unsupported
+fi
+AC_MSG_RESULT([$_LT_TAGVAR(hardcode_action, $1)])
+
+if test "$_LT_TAGVAR(hardcode_action, $1)" = relink ||
+   test "$_LT_TAGVAR(inherit_rpath, $1)" = yes; then
+  # Fast installation is not supported
+  enable_fast_install=no
+elif test "$shlibpath_overrides_runpath" = yes ||
+     test "$enable_shared" = no; then
+  # Fast installation is not necessary
+  enable_fast_install=needless
+fi
+_LT_TAGDECL([], [hardcode_action], [0],
+    [How to hardcode a shared library path into an executable])
+])# _LT_LINKER_HARDCODE_LIBPATH
+
+
+# _LT_CMD_STRIPLIB
+# ----------------
+m4_defun([_LT_CMD_STRIPLIB],
+[m4_require([_LT_DECL_EGREP])
+striplib=
+old_striplib=
+AC_MSG_CHECKING([whether stripping libraries is possible])
+if test -n "$STRIP" && $STRIP -V 2>&1 | $GREP "GNU strip" >/dev/null; then
+  test -z "$old_striplib" && old_striplib="$STRIP --strip-debug"
+  test -z "$striplib" && striplib="$STRIP --strip-unneeded"
+  AC_MSG_RESULT([yes])
+else
+# FIXME - insert some real tests, host_os isn't really good enough
+  case $host_os in
+  darwin*)
+    if test -n "$STRIP" ; then
+      striplib="$STRIP -x"
+      old_striplib="$STRIP -S"
+      AC_MSG_RESULT([yes])
+    else
+      AC_MSG_RESULT([no])
+    fi
+    ;;
+  *)
+    AC_MSG_RESULT([no])
+    ;;
+  esac
+fi
+_LT_DECL([], [old_striplib], [1], [Commands to strip libraries])
+_LT_DECL([], [striplib], [1])
+])# _LT_CMD_STRIPLIB
+
+
+# _LT_SYS_DYNAMIC_LINKER([TAG])
+# -----------------------------
+# PORTME Fill in your ld.so characteristics
+m4_defun([_LT_SYS_DYNAMIC_LINKER],
+[AC_REQUIRE([AC_CANONICAL_HOST])dnl
+m4_require([_LT_DECL_EGREP])dnl
+m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+m4_require([_LT_DECL_OBJDUMP])dnl
+m4_require([_LT_DECL_SED])dnl
+m4_require([_LT_CHECK_SHELL_FEATURES])dnl
+AC_MSG_CHECKING([dynamic linker characteristics])
+m4_if([$1],
+	[], [
+if test "$GCC" = yes; then
+  case $host_os in
+    darwin*) lt_awk_arg="/^libraries:/,/LR/" ;;
+    *) lt_awk_arg="/^libraries:/" ;;
+  esac
+  case $host_os in
+    mingw* | cegcc*) lt_sed_strip_eq="s,=\([[A-Za-z]]:\),\1,g" ;;
+    *) lt_sed_strip_eq="s,=/,/,g" ;;
+  esac
+  lt_search_path_spec=`$CC -print-search-dirs | awk $lt_awk_arg | $SED -e "s/^libraries://" -e $lt_sed_strip_eq`
+  case $lt_search_path_spec in
+  *\;*)
+    # if the path contains ";" then we assume it to be the separator
+    # otherwise default to the standard path separator (i.e. ":") - it is
+    # assumed that no part of a normal pathname contains ";" but that should
+    # okay in the real world where ";" in dirpaths is itself problematic.
+    lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED 's/;/ /g'`
+    ;;
+  *)
+    lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED "s/$PATH_SEPARATOR/ /g"`
+    ;;
+  esac
+  # Ok, now we have the path, separated by spaces, we can step through it
+  # and add multilib dir if necessary.
+  lt_tmp_lt_search_path_spec=
+  lt_multi_os_dir=`$CC $CPPFLAGS $CFLAGS $LDFLAGS -print-multi-os-directory 2>/dev/null`
+  for lt_sys_path in $lt_search_path_spec; do
+    if test -d "$lt_sys_path/$lt_multi_os_dir"; then
+      lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path/$lt_multi_os_dir"
+    else
+      test -d "$lt_sys_path" && \
+	lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path"
+    fi
+  done
+  lt_search_path_spec=`$ECHO "$lt_tmp_lt_search_path_spec" | awk '
+BEGIN {RS=" "; FS="/|\n";} {
+  lt_foo="";
+  lt_count=0;
+  for (lt_i = NF; lt_i > 0; lt_i--) {
+    if ($lt_i != "" && $lt_i != ".") {
+      if ($lt_i == "..") {
+        lt_count++;
+      } else {
+        if (lt_count == 0) {
+          lt_foo="/" $lt_i lt_foo;
+        } else {
+          lt_count--;
+        }
+      }
+    }
+  }
+  if (lt_foo != "") { lt_freq[[lt_foo]]++; }
+  if (lt_freq[[lt_foo]] == 1) { print lt_foo; }
+}'`
+  # AWK program above erroneously prepends '/' to C:/dos/paths
+  # for these hosts.
+  case $host_os in
+    mingw* | cegcc*) lt_search_path_spec=`$ECHO "$lt_search_path_spec" |\
+      $SED 's,/\([[A-Za-z]]:\),\1,g'` ;;
+  esac
+  sys_lib_search_path_spec=`$ECHO "$lt_search_path_spec" | $lt_NL2SP`
+else
+  sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib"
+fi])
+library_names_spec=
+libname_spec='lib$name'
+soname_spec=
+shrext_cmds=".so"
+postinstall_cmds=
+postuninstall_cmds=
+finish_cmds=
+finish_eval=
+shlibpath_var=
+shlibpath_overrides_runpath=unknown
+version_type=none
+dynamic_linker="$host_os ld.so"
+sys_lib_dlsearch_path_spec="/lib /usr/lib"
+need_lib_prefix=unknown
+hardcode_into_libs=no
+
+# when you set need_version to no, make sure it does not cause -set_version
+# flags to be left without arguments
+need_version=unknown
+
+case $host_os in
+aix3*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a'
+  shlibpath_var=LIBPATH
+
+  # AIX 3 has no versioning support, so we append a major version to the name.
+  soname_spec='${libname}${release}${shared_ext}$major'
+  ;;
+
+aix[[4-9]]*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_lib_prefix=no
+  need_version=no
+  hardcode_into_libs=yes
+  if test "$host_cpu" = ia64; then
+    # AIX 5 supports IA64
+    library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}'
+    shlibpath_var=LD_LIBRARY_PATH
+  else
+    # With GCC up to 2.95.x, collect2 would create an import file
+    # for dependence libraries.  The import file would start with
+    # the line `#! .'.  This would cause the generated library to
+    # depend on `.', always an invalid library.  This was fixed in
+    # development snapshots of GCC prior to 3.0.
+    case $host_os in
+      aix4 | aix4.[[01]] | aix4.[[01]].*)
+      if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)'
+	   echo ' yes '
+	   echo '#endif'; } | ${CC} -E - | $GREP yes > /dev/null; then
+	:
+      else
+	can_build_shared=no
+      fi
+      ;;
+    esac
+    # AIX (on Power*) has no versioning support, so currently we can not hardcode correct
+    # soname into executable. Probably we can add versioning support to
+    # collect2, so additional links can be useful in future.
+    if test "$aix_use_runtimelinking" = yes; then
+      # If using run time linking (on AIX 4.2 or later) use lib<name>.so
+      # instead of lib<name>.a to let people know that these are not
+      # typical AIX shared libraries.
+      library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+    else
+      # We preserve .a as extension for shared libraries through AIX4.2
+      # and later when we are not doing run time linking.
+      library_names_spec='${libname}${release}.a $libname.a'
+      soname_spec='${libname}${release}${shared_ext}$major'
+    fi
+    shlibpath_var=LIBPATH
+  fi
+  ;;
+
+amigaos*)
+  case $host_cpu in
+  powerpc)
+    # Since July 2007 AmigaOS4 officially supports .so libraries.
+    # When compiling the executable, add -use-dynld -Lsobjs: to the compileline.
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+    ;;
+  m68k)
+    library_names_spec='$libname.ixlibrary $libname.a'
+    # Create ${libname}_ixlibrary.a entries in /sys/libs.
+    finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`func_echo_all "$lib" | $SED '\''s%^.*/\([[^/]]*\)\.ixlibrary$%\1%'\''`; test $RM /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done'
+    ;;
+  esac
+  ;;
+
+beos*)
+  library_names_spec='${libname}${shared_ext}'
+  dynamic_linker="$host_os ld.so"
+  shlibpath_var=LIBRARY_PATH
+  ;;
+
+bsdi[[45]]*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir'
+  shlibpath_var=LD_LIBRARY_PATH
+  sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib"
+  sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib"
+  # the default ld.so.conf also contains /usr/contrib/lib and
+  # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow
+  # libtool to hard-code these into programs
+  ;;
+
+cygwin* | mingw* | pw32* | cegcc*)
+  version_type=windows
+  shrext_cmds=".dll"
+  need_version=no
+  need_lib_prefix=no
+
+  case $GCC,$cc_basename in
+  yes,*)
+    # gcc
+    library_names_spec='$libname.dll.a'
+    # DLL is installed to $(libdir)/../bin by postinstall_cmds
+    postinstall_cmds='base_file=`basename \${file}`~
+      dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~
+      dldir=$destdir/`dirname \$dlpath`~
+      test -d \$dldir || mkdir -p \$dldir~
+      $install_prog $dir/$dlname \$dldir/$dlname~
+      chmod a+x \$dldir/$dlname~
+      if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then
+        eval '\''$striplib \$dldir/$dlname'\'' || exit \$?;
+      fi'
+    postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~
+      dlpath=$dir/\$dldll~
+       $RM \$dlpath'
+    shlibpath_overrides_runpath=yes
+
+    case $host_os in
+    cygwin*)
+      # Cygwin DLLs use 'cyg' prefix rather than 'lib'
+      soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}'
+m4_if([$1], [],[
+      sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/lib/w32api"])
+      ;;
+    mingw* | cegcc*)
+      # MinGW DLLs use traditional 'lib' prefix
+      soname_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}'
+      ;;
+    pw32*)
+      # pw32 DLLs use 'pw' prefix rather than 'lib'
+      library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}'
+      ;;
+    esac
+    dynamic_linker='Win32 ld.exe'
+    ;;
+
+  *,cl*)
+    # Native MSVC
+    libname_spec='$name'
+    soname_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}'
+    library_names_spec='${libname}.dll.lib'
+
+    case $build_os in
+    mingw*)
+      sys_lib_search_path_spec=
+      lt_save_ifs=$IFS
+      IFS=';'
+      for lt_path in $LIB
+      do
+        IFS=$lt_save_ifs
+        # Let DOS variable expansion print the short 8.3 style file name.
+        lt_path=`cd "$lt_path" 2>/dev/null && cmd //C "for %i in (".") do @echo %~si"`
+        sys_lib_search_path_spec="$sys_lib_search_path_spec $lt_path"
+      done
+      IFS=$lt_save_ifs
+      # Convert to MSYS style.
+      sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | sed -e 's|\\\\|/|g' -e 's| \\([[a-zA-Z]]\\):| /\\1|g' -e 's|^ ||'`
+      ;;
+    cygwin*)
+      # Convert to unix form, then to dos form, then back to unix form
+      # but this time dos style (no spaces!) so that the unix form looks
+      # like /cygdrive/c/PROGRA~1:/cygdr...
+      sys_lib_search_path_spec=`cygpath --path --unix "$LIB"`
+      sys_lib_search_path_spec=`cygpath --path --dos "$sys_lib_search_path_spec" 2>/dev/null`
+      sys_lib_search_path_spec=`cygpath --path --unix "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"`
+      ;;
+    *)
+      sys_lib_search_path_spec="$LIB"
+      if $ECHO "$sys_lib_search_path_spec" | [$GREP ';[c-zC-Z]:/' >/dev/null]; then
+        # It is most probably a Windows format PATH.
+        sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'`
+      else
+        sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"`
+      fi
+      # FIXME: find the short name or the path components, as spaces are
+      # common. (e.g. "Program Files" -> "PROGRA~1")
+      ;;
+    esac
+
+    # DLL is installed to $(libdir)/../bin by postinstall_cmds
+    postinstall_cmds='base_file=`basename \${file}`~
+      dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~
+      dldir=$destdir/`dirname \$dlpath`~
+      test -d \$dldir || mkdir -p \$dldir~
+      $install_prog $dir/$dlname \$dldir/$dlname'
+    postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~
+      dlpath=$dir/\$dldll~
+       $RM \$dlpath'
+    shlibpath_overrides_runpath=yes
+    dynamic_linker='Win32 link.exe'
+    ;;
+
+  *)
+    # Assume MSVC wrapper
+    library_names_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext} $libname.lib'
+    dynamic_linker='Win32 ld.exe'
+    ;;
+  esac
+  # FIXME: first we should search . and the directory the executable is in
+  shlibpath_var=PATH
+  ;;
+
+darwin* | rhapsody*)
+  dynamic_linker="$host_os dyld"
+  version_type=darwin
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${major}$shared_ext ${libname}$shared_ext'
+  soname_spec='${libname}${release}${major}$shared_ext'
+  shlibpath_overrides_runpath=yes
+  shlibpath_var=DYLD_LIBRARY_PATH
+  shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`'
+m4_if([$1], [],[
+  sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/local/lib"])
+  sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib'
+  ;;
+
+dgux*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  ;;
+
+freebsd* | dragonfly*)
+  # DragonFly does not have aout.  When/if they implement a new
+  # versioning mechanism, adjust this.
+  if test -x /usr/bin/objformat; then
+    objformat=`/usr/bin/objformat`
+  else
+    case $host_os in
+    freebsd[[23]].*) objformat=aout ;;
+    *) objformat=elf ;;
+    esac
+  fi
+  version_type=freebsd-$objformat
+  case $version_type in
+    freebsd-elf*)
+      library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
+      need_version=no
+      need_lib_prefix=no
+      ;;
+    freebsd-*)
+      library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix'
+      need_version=yes
+      ;;
+  esac
+  shlibpath_var=LD_LIBRARY_PATH
+  case $host_os in
+  freebsd2.*)
+    shlibpath_overrides_runpath=yes
+    ;;
+  freebsd3.[[01]]* | freebsdelf3.[[01]]*)
+    shlibpath_overrides_runpath=yes
+    hardcode_into_libs=yes
+    ;;
+  freebsd3.[[2-9]]* | freebsdelf3.[[2-9]]* | \
+  freebsd4.[[0-5]] | freebsdelf4.[[0-5]] | freebsd4.1.1 | freebsdelf4.1.1)
+    shlibpath_overrides_runpath=no
+    hardcode_into_libs=yes
+    ;;
+  *) # from 4.6 on, and DragonFly
+    shlibpath_overrides_runpath=yes
+    hardcode_into_libs=yes
+    ;;
+  esac
+  ;;
+
+gnu*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=no
+  hardcode_into_libs=yes
+  ;;
+
+haiku*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_lib_prefix=no
+  need_version=no
+  dynamic_linker="$host_os runtime_loader"
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  sys_lib_dlsearch_path_spec='/boot/home/config/lib /boot/common/lib /boot/system/lib'
+  hardcode_into_libs=yes
+  ;;
+
+hpux9* | hpux10* | hpux11*)
+  # Give a soname corresponding to the major version so that dld.sl refuses to
+  # link against other versions.
+  version_type=sunos
+  need_lib_prefix=no
+  need_version=no
+  case $host_cpu in
+  ia64*)
+    shrext_cmds='.so'
+    hardcode_into_libs=yes
+    dynamic_linker="$host_os dld.so"
+    shlibpath_var=LD_LIBRARY_PATH
+    shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+    soname_spec='${libname}${release}${shared_ext}$major'
+    if test "X$HPUX_IA64_MODE" = X32; then
+      sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib"
+    else
+      sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64"
+    fi
+    sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
+    ;;
+  hppa*64*)
+    shrext_cmds='.sl'
+    hardcode_into_libs=yes
+    dynamic_linker="$host_os dld.sl"
+    shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH
+    shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+    soname_spec='${libname}${release}${shared_ext}$major'
+    sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64"
+    sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
+    ;;
+  *)
+    shrext_cmds='.sl'
+    dynamic_linker="$host_os dld.sl"
+    shlibpath_var=SHLIB_PATH
+    shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+    soname_spec='${libname}${release}${shared_ext}$major'
+    ;;
+  esac
+  # HP-UX runs *really* slowly unless shared libraries are mode 555, ...
+  postinstall_cmds='chmod 555 $lib'
+  # or fails outright, so override atomically:
+  install_override_mode=555
+  ;;
+
+interix[[3-9]]*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=no
+  hardcode_into_libs=yes
+  ;;
+
+irix5* | irix6* | nonstopux*)
+  case $host_os in
+    nonstopux*) version_type=nonstopux ;;
+    *)
+	if test "$lt_cv_prog_gnu_ld" = yes; then
+		version_type=linux # correct to gnu/linux during the next big refactor
+	else
+		version_type=irix
+	fi ;;
+  esac
+  need_lib_prefix=no
+  need_version=no
+  soname_spec='${libname}${release}${shared_ext}$major'
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}'
+  case $host_os in
+  irix5* | nonstopux*)
+    libsuff= shlibsuff=
+    ;;
+  *)
+    case $LD in # libtool.m4 will add one of these switches to LD
+    *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ")
+      libsuff= shlibsuff= libmagic=32-bit;;
+    *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ")
+      libsuff=32 shlibsuff=N32 libmagic=N32;;
+    *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ")
+      libsuff=64 shlibsuff=64 libmagic=64-bit;;
+    *) libsuff= shlibsuff= libmagic=never-match;;
+    esac
+    ;;
+  esac
+  shlibpath_var=LD_LIBRARY${shlibsuff}_PATH
+  shlibpath_overrides_runpath=no
+  sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}"
+  sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}"
+  hardcode_into_libs=yes
+  ;;
+
+# No shared lib support for Linux oldld, aout, or coff.
+linux*oldld* | linux*aout* | linux*coff*)
+  dynamic_linker=no
+  ;;
+
+# This must be glibc/ELF.
+linux* | k*bsd*-gnu | kopensolaris*-gnu)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=no
+
+  # Some binutils ld are patched to set DT_RUNPATH
+  AC_CACHE_VAL([lt_cv_shlibpath_overrides_runpath],
+    [lt_cv_shlibpath_overrides_runpath=no
+    save_LDFLAGS=$LDFLAGS
+    save_libdir=$libdir
+    eval "libdir=/foo; wl=\"$_LT_TAGVAR(lt_prog_compiler_wl, $1)\"; \
+	 LDFLAGS=\"\$LDFLAGS $_LT_TAGVAR(hardcode_libdir_flag_spec, $1)\""
+    AC_LINK_IFELSE([AC_LANG_PROGRAM([],[])],
+      [AS_IF([ ($OBJDUMP -p conftest$ac_exeext) 2>/dev/null | grep "RUNPATH.*$libdir" >/dev/null],
+	 [lt_cv_shlibpath_overrides_runpath=yes])])
+    LDFLAGS=$save_LDFLAGS
+    libdir=$save_libdir
+    ])
+  shlibpath_overrides_runpath=$lt_cv_shlibpath_overrides_runpath
+
+  # This implies no fast_install, which is unacceptable.
+  # Some rework will be needed to allow for fast_install
+  # before this can be enabled.
+  hardcode_into_libs=yes
+
+  # Append ld.so.conf contents to the search path
+  if test -f /etc/ld.so.conf; then
+    lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \[$]2)); skip = 1; } { if (!skip) print \[$]0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;/^[	 ]*hwcap[	 ]/d;s/[:,	]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;s/"//g;/^$/d' | tr '\n' ' '`
+    sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra"
+  fi
+
+  # We used to test for /lib/ld.so.1 and disable shared libraries on
+  # powerpc, because MkLinux only supported shared libraries with the
+  # GNU dynamic linker.  Since this was broken with cross compilers,
+  # most powerpc-linux boxes support dynamic linking these days and
+  # people can always --disable-shared, the test was removed, and we
+  # assume the GNU/Linux dynamic linker is in use.
+  dynamic_linker='GNU/Linux ld.so'
+  ;;
+
+netbsdelf*-gnu)
+  version_type=linux
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=no
+  hardcode_into_libs=yes
+  dynamic_linker='NetBSD ld.elf_so'
+  ;;
+
+netbsd*)
+  version_type=sunos
+  need_lib_prefix=no
+  need_version=no
+  if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+    finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
+    dynamic_linker='NetBSD (a.out) ld.so'
+  else
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+    soname_spec='${libname}${release}${shared_ext}$major'
+    dynamic_linker='NetBSD ld.elf_so'
+  fi
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  hardcode_into_libs=yes
+  ;;
+
+newsos6)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  ;;
+
+*nto* | *qnx*)
+  version_type=qnx
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=no
+  hardcode_into_libs=yes
+  dynamic_linker='ldqnx.so'
+  ;;
+
+openbsd*)
+  version_type=sunos
+  sys_lib_dlsearch_path_spec="/usr/lib"
+  need_lib_prefix=no
+  # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs.
+  case $host_os in
+    openbsd3.3 | openbsd3.3.*)	need_version=yes ;;
+    *)				need_version=no  ;;
+  esac
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+  finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
+  shlibpath_var=LD_LIBRARY_PATH
+  if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+    case $host_os in
+      openbsd2.[[89]] | openbsd2.[[89]].*)
+	shlibpath_overrides_runpath=no
+	;;
+      *)
+	shlibpath_overrides_runpath=yes
+	;;
+      esac
+  else
+    shlibpath_overrides_runpath=yes
+  fi
+  ;;
+
+os2*)
+  libname_spec='$name'
+  shrext_cmds=".dll"
+  need_lib_prefix=no
+  library_names_spec='$libname${shared_ext} $libname.a'
+  dynamic_linker='OS/2 ld.exe'
+  shlibpath_var=LIBPATH
+  ;;
+
+osf3* | osf4* | osf5*)
+  version_type=osf
+  need_lib_prefix=no
+  need_version=no
+  soname_spec='${libname}${release}${shared_ext}$major'
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  shlibpath_var=LD_LIBRARY_PATH
+  sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib"
+  sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec"
+  ;;
+
+rdos*)
+  dynamic_linker=no
+  ;;
+
+solaris*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  hardcode_into_libs=yes
+  # ldd complains unless libraries are executable
+  postinstall_cmds='chmod +x $lib'
+  ;;
+
+sunos4*)
+  version_type=sunos
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+  finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  if test "$with_gnu_ld" = yes; then
+    need_lib_prefix=no
+  fi
+  need_version=yes
+  ;;
+
+sysv4 | sysv4.3*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  case $host_vendor in
+    sni)
+      shlibpath_overrides_runpath=no
+      need_lib_prefix=no
+      runpath_var=LD_RUN_PATH
+      ;;
+    siemens)
+      need_lib_prefix=no
+      ;;
+    motorola)
+      need_lib_prefix=no
+      need_version=no
+      shlibpath_overrides_runpath=no
+      sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib'
+      ;;
+  esac
+  ;;
+
+sysv4*MP*)
+  if test -d /usr/nec ;then
+    version_type=linux # correct to gnu/linux during the next big refactor
+    library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}'
+    soname_spec='$libname${shared_ext}.$major'
+    shlibpath_var=LD_LIBRARY_PATH
+  fi
+  ;;
+
+sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
+  version_type=freebsd-elf
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  hardcode_into_libs=yes
+  if test "$with_gnu_ld" = yes; then
+    sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib'
+  else
+    sys_lib_search_path_spec='/usr/ccs/lib /usr/lib'
+    case $host_os in
+      sco3.2v5*)
+        sys_lib_search_path_spec="$sys_lib_search_path_spec /lib"
+	;;
+    esac
+  fi
+  sys_lib_dlsearch_path_spec='/usr/lib'
+  ;;
+
+tpf*)
+  # TPF is a cross-target only.  Preferred cross-host = GNU/Linux.
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=no
+  hardcode_into_libs=yes
+  ;;
+
+uts4*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  ;;
+
+*)
+  dynamic_linker=no
+  ;;
+esac
+AC_MSG_RESULT([$dynamic_linker])
+test "$dynamic_linker" = no && can_build_shared=no
+
+variables_saved_for_relink="PATH $shlibpath_var $runpath_var"
+if test "$GCC" = yes; then
+  variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH"
+fi
+
+if test "${lt_cv_sys_lib_search_path_spec+set}" = set; then
+  sys_lib_search_path_spec="$lt_cv_sys_lib_search_path_spec"
+fi
+if test "${lt_cv_sys_lib_dlsearch_path_spec+set}" = set; then
+  sys_lib_dlsearch_path_spec="$lt_cv_sys_lib_dlsearch_path_spec"
+fi
+
+_LT_DECL([], [variables_saved_for_relink], [1],
+    [Variables whose values should be saved in libtool wrapper scripts and
+    restored at link time])
+_LT_DECL([], [need_lib_prefix], [0],
+    [Do we need the "lib" prefix for modules?])
+_LT_DECL([], [need_version], [0], [Do we need a version for libraries?])
+_LT_DECL([], [version_type], [0], [Library versioning type])
+_LT_DECL([], [runpath_var], [0],  [Shared library runtime path variable])
+_LT_DECL([], [shlibpath_var], [0],[Shared library path variable])
+_LT_DECL([], [shlibpath_overrides_runpath], [0],
+    [Is shlibpath searched before the hard-coded library search path?])
+_LT_DECL([], [libname_spec], [1], [Format of library name prefix])
+_LT_DECL([], [library_names_spec], [1],
+    [[List of archive names.  First name is the real one, the rest are links.
+    The last name is the one that the linker finds with -lNAME]])
+_LT_DECL([], [soname_spec], [1],
+    [[The coded name of the library, if different from the real name]])
+_LT_DECL([], [install_override_mode], [1],
+    [Permission mode override for installation of shared libraries])
+_LT_DECL([], [postinstall_cmds], [2],
+    [Command to use after installation of a shared archive])
+_LT_DECL([], [postuninstall_cmds], [2],
+    [Command to use after uninstallation of a shared archive])
+_LT_DECL([], [finish_cmds], [2],
+    [Commands used to finish a libtool library installation in a directory])
+_LT_DECL([], [finish_eval], [1],
+    [[As "finish_cmds", except a single script fragment to be evaled but
+    not shown]])
+_LT_DECL([], [hardcode_into_libs], [0],
+    [Whether we should hardcode library paths into libraries])
+_LT_DECL([], [sys_lib_search_path_spec], [2],
+    [Compile-time system search path for libraries])
+_LT_DECL([], [sys_lib_dlsearch_path_spec], [2],
+    [Run-time system search path for libraries])
+])# _LT_SYS_DYNAMIC_LINKER
+
+
+# _LT_PATH_TOOL_PREFIX(TOOL)
+# --------------------------
+# find a file program which can recognize shared library
+AC_DEFUN([_LT_PATH_TOOL_PREFIX],
+[m4_require([_LT_DECL_EGREP])dnl
+AC_MSG_CHECKING([for $1])
+AC_CACHE_VAL(lt_cv_path_MAGIC_CMD,
+[case $MAGIC_CMD in
+[[\\/*] |  ?:[\\/]*])
+  lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path.
+  ;;
+*)
+  lt_save_MAGIC_CMD="$MAGIC_CMD"
+  lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
+dnl $ac_dummy forces splitting on constant user-supplied paths.
+dnl POSIX.2 word splitting is done only on the output of word expansions,
+dnl not every word.  This closes a longstanding sh security hole.
+  ac_dummy="m4_if([$2], , $PATH, [$2])"
+  for ac_dir in $ac_dummy; do
+    IFS="$lt_save_ifs"
+    test -z "$ac_dir" && ac_dir=.
+    if test -f $ac_dir/$1; then
+      lt_cv_path_MAGIC_CMD="$ac_dir/$1"
+      if test -n "$file_magic_test_file"; then
+	case $deplibs_check_method in
+	"file_magic "*)
+	  file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"`
+	  MAGIC_CMD="$lt_cv_path_MAGIC_CMD"
+	  if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null |
+	    $EGREP "$file_magic_regex" > /dev/null; then
+	    :
+	  else
+	    cat <<_LT_EOF 1>&2
+
+*** Warning: the command libtool uses to detect shared libraries,
+*** $file_magic_cmd, produces output that libtool cannot recognize.
+*** The result is that libtool may fail to recognize shared libraries
+*** as such.  This will affect the creation of libtool libraries that
+*** depend on shared libraries, but programs linked with such libtool
+*** libraries will work regardless of this problem.  Nevertheless, you
+*** may want to report the problem to your system manager and/or to
+*** bug-libtool at gnu.org
+
+_LT_EOF
+	  fi ;;
+	esac
+      fi
+      break
+    fi
+  done
+  IFS="$lt_save_ifs"
+  MAGIC_CMD="$lt_save_MAGIC_CMD"
+  ;;
+esac])
+MAGIC_CMD="$lt_cv_path_MAGIC_CMD"
+if test -n "$MAGIC_CMD"; then
+  AC_MSG_RESULT($MAGIC_CMD)
+else
+  AC_MSG_RESULT(no)
+fi
+_LT_DECL([], [MAGIC_CMD], [0],
+	 [Used to examine libraries when file_magic_cmd begins with "file"])dnl
+])# _LT_PATH_TOOL_PREFIX
+
+# Old name:
+AU_ALIAS([AC_PATH_TOOL_PREFIX], [_LT_PATH_TOOL_PREFIX])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_PATH_TOOL_PREFIX], [])
+
+
+# _LT_PATH_MAGIC
+# --------------
+# find a file program which can recognize a shared library
+m4_defun([_LT_PATH_MAGIC],
+[_LT_PATH_TOOL_PREFIX(${ac_tool_prefix}file, /usr/bin$PATH_SEPARATOR$PATH)
+if test -z "$lt_cv_path_MAGIC_CMD"; then
+  if test -n "$ac_tool_prefix"; then
+    _LT_PATH_TOOL_PREFIX(file, /usr/bin$PATH_SEPARATOR$PATH)
+  else
+    MAGIC_CMD=:
+  fi
+fi
+])# _LT_PATH_MAGIC
+
+
+# LT_PATH_LD
+# ----------
+# find the pathname to the GNU or non-GNU linker
+AC_DEFUN([LT_PATH_LD],
+[AC_REQUIRE([AC_PROG_CC])dnl
+AC_REQUIRE([AC_CANONICAL_HOST])dnl
+AC_REQUIRE([AC_CANONICAL_BUILD])dnl
+m4_require([_LT_DECL_SED])dnl
+m4_require([_LT_DECL_EGREP])dnl
+m4_require([_LT_PROG_ECHO_BACKSLASH])dnl
+
+AC_ARG_WITH([gnu-ld],
+    [AS_HELP_STRING([--with-gnu-ld],
+	[assume the C compiler uses GNU ld @<:@default=no@:>@])],
+    [test "$withval" = no || with_gnu_ld=yes],
+    [with_gnu_ld=no])dnl
+
+ac_prog=ld
+if test "$GCC" = yes; then
+  # Check if gcc -print-prog-name=ld gives a path.
+  AC_MSG_CHECKING([for ld used by $CC])
+  case $host in
+  *-*-mingw*)
+    # gcc leaves a trailing carriage return which upsets mingw
+    ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;;
+  *)
+    ac_prog=`($CC -print-prog-name=ld) 2>&5` ;;
+  esac
+  case $ac_prog in
+    # Accept absolute paths.
+    [[\\/]]* | ?:[[\\/]]*)
+      re_direlt='/[[^/]][[^/]]*/\.\./'
+      # Canonicalize the pathname of ld
+      ac_prog=`$ECHO "$ac_prog"| $SED 's%\\\\%/%g'`
+      while $ECHO "$ac_prog" | $GREP "$re_direlt" > /dev/null 2>&1; do
+	ac_prog=`$ECHO $ac_prog| $SED "s%$re_direlt%/%"`
+      done
+      test -z "$LD" && LD="$ac_prog"
+      ;;
+  "")
+    # If it fails, then pretend we aren't using GCC.
+    ac_prog=ld
+    ;;
+  *)
+    # If it is relative, then search for the first ld in PATH.
+    with_gnu_ld=unknown
+    ;;
+  esac
+elif test "$with_gnu_ld" = yes; then
+  AC_MSG_CHECKING([for GNU ld])
+else
+  AC_MSG_CHECKING([for non-GNU ld])
+fi
+AC_CACHE_VAL(lt_cv_path_LD,
+[if test -z "$LD"; then
+  lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
+  for ac_dir in $PATH; do
+    IFS="$lt_save_ifs"
+    test -z "$ac_dir" && ac_dir=.
+    if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then
+      lt_cv_path_LD="$ac_dir/$ac_prog"
+      # Check to see if the program is GNU ld.  I'd rather use --version,
+      # but apparently some variants of GNU ld only accept -v.
+      # Break only if it was the GNU/non-GNU ld that we prefer.
+      case `"$lt_cv_path_LD" -v 2>&1 </dev/null` in
+      *GNU* | *'with BFD'*)
+	test "$with_gnu_ld" != no && break
+	;;
+      *)
+	test "$with_gnu_ld" != yes && break
+	;;
+      esac
+    fi
+  done
+  IFS="$lt_save_ifs"
+else
+  lt_cv_path_LD="$LD" # Let the user override the test with a path.
+fi])
+LD="$lt_cv_path_LD"
+if test -n "$LD"; then
+  AC_MSG_RESULT($LD)
+else
+  AC_MSG_RESULT(no)
+fi
+test -z "$LD" && AC_MSG_ERROR([no acceptable ld found in \$PATH])
+_LT_PATH_LD_GNU
+AC_SUBST([LD])
+
+_LT_TAGDECL([], [LD], [1], [The linker used to build libraries])
+])# LT_PATH_LD
+
+# Old names:
+AU_ALIAS([AM_PROG_LD], [LT_PATH_LD])
+AU_ALIAS([AC_PROG_LD], [LT_PATH_LD])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AM_PROG_LD], [])
+dnl AC_DEFUN([AC_PROG_LD], [])
+
+
+# _LT_PATH_LD_GNU
+#- --------------
+m4_defun([_LT_PATH_LD_GNU],
+[AC_CACHE_CHECK([if the linker ($LD) is GNU ld], lt_cv_prog_gnu_ld,
+[# I'd rather use --version here, but apparently some GNU lds only accept -v.
+case `$LD -v 2>&1 </dev/null` in
+*GNU* | *'with BFD'*)
+  lt_cv_prog_gnu_ld=yes
+  ;;
+*)
+  lt_cv_prog_gnu_ld=no
+  ;;
+esac])
+with_gnu_ld=$lt_cv_prog_gnu_ld
+])# _LT_PATH_LD_GNU
+
+
+# _LT_CMD_RELOAD
+# --------------
+# find reload flag for linker
+#   -- PORTME Some linkers may need a different reload flag.
+m4_defun([_LT_CMD_RELOAD],
+[AC_CACHE_CHECK([for $LD option to reload object files],
+  lt_cv_ld_reload_flag,
+  [lt_cv_ld_reload_flag='-r'])
+reload_flag=$lt_cv_ld_reload_flag
+case $reload_flag in
+"" | " "*) ;;
+*) reload_flag=" $reload_flag" ;;
+esac
+reload_cmds='$LD$reload_flag -o $output$reload_objs'
+case $host_os in
+  cygwin* | mingw* | pw32* | cegcc*)
+    if test "$GCC" != yes; then
+      reload_cmds=false
+    fi
+    ;;
+  darwin*)
+    if test "$GCC" = yes; then
+      reload_cmds='$LTCC $LTCFLAGS -nostdlib ${wl}-r -o $output$reload_objs'
+    else
+      reload_cmds='$LD$reload_flag -o $output$reload_objs'
+    fi
+    ;;
+esac
+_LT_TAGDECL([], [reload_flag], [1], [How to create reloadable object files])dnl
+_LT_TAGDECL([], [reload_cmds], [2])dnl
+])# _LT_CMD_RELOAD
+
+
+# _LT_CHECK_MAGIC_METHOD
+# ----------------------
+# how to check for library dependencies
+#  -- PORTME fill in with the dynamic library characteristics
+m4_defun([_LT_CHECK_MAGIC_METHOD],
+[m4_require([_LT_DECL_EGREP])
+m4_require([_LT_DECL_OBJDUMP])
+AC_CACHE_CHECK([how to recognize dependent libraries],
+lt_cv_deplibs_check_method,
+[lt_cv_file_magic_cmd='$MAGIC_CMD'
+lt_cv_file_magic_test_file=
+lt_cv_deplibs_check_method='unknown'
+# Need to set the preceding variable on all platforms that support
+# interlibrary dependencies.
+# 'none' -- dependencies not supported.
+# `unknown' -- same as none, but documents that we really don't know.
+# 'pass_all' -- all dependencies passed with no checks.
+# 'test_compile' -- check by making test program.
+# 'file_magic [[regex]]' -- check by looking for files in library path
+# which responds to the $file_magic_cmd with a given extended regex.
+# If you have `file' or equivalent on your system and you're not sure
+# whether `pass_all' will *always* work, you probably want this one.
+
+case $host_os in
+aix[[4-9]]*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+beos*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+bsdi[[45]]*)
+  lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (shared object|dynamic lib)'
+  lt_cv_file_magic_cmd='/usr/bin/file -L'
+  lt_cv_file_magic_test_file=/shlib/libc.so
+  ;;
+
+cygwin*)
+  # func_win32_libid is a shell function defined in ltmain.sh
+  lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL'
+  lt_cv_file_magic_cmd='func_win32_libid'
+  ;;
+
+mingw* | pw32*)
+  # Base MSYS/MinGW do not provide the 'file' command needed by
+  # func_win32_libid shell function, so use a weaker test based on 'objdump',
+  # unless we find 'file', for example because we are cross-compiling.
+  # func_win32_libid assumes BSD nm, so disallow it if using MS dumpbin.
+  if ( test "$lt_cv_nm_interface" = "BSD nm" && file / ) >/dev/null 2>&1; then
+    lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL'
+    lt_cv_file_magic_cmd='func_win32_libid'
+  else
+    # Keep this pattern in sync with the one in func_win32_libid.
+    lt_cv_deplibs_check_method='file_magic file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)'
+    lt_cv_file_magic_cmd='$OBJDUMP -f'
+  fi
+  ;;
+
+cegcc*)
+  # use the weaker test based on 'objdump'. See mingw*.
+  lt_cv_deplibs_check_method='file_magic file format pe-arm-.*little(.*architecture: arm)?'
+  lt_cv_file_magic_cmd='$OBJDUMP -f'
+  ;;
+
+darwin* | rhapsody*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+freebsd* | dragonfly*)
+  if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then
+    case $host_cpu in
+    i*86 )
+      # Not sure whether the presence of OpenBSD here was a mistake.
+      # Let's accept both of them until this is cleared up.
+      lt_cv_deplibs_check_method='file_magic (FreeBSD|OpenBSD|DragonFly)/i[[3-9]]86 (compact )?demand paged shared library'
+      lt_cv_file_magic_cmd=/usr/bin/file
+      lt_cv_file_magic_test_file=`echo /usr/lib/libc.so.*`
+      ;;
+    esac
+  else
+    lt_cv_deplibs_check_method=pass_all
+  fi
+  ;;
+
+gnu*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+haiku*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+hpux10.20* | hpux11*)
+  lt_cv_file_magic_cmd=/usr/bin/file
+  case $host_cpu in
+  ia64*)
+    lt_cv_deplibs_check_method='file_magic (s[[0-9]][[0-9]][[0-9]]|ELF-[[0-9]][[0-9]]) shared object file - IA64'
+    lt_cv_file_magic_test_file=/usr/lib/hpux32/libc.so
+    ;;
+  hppa*64*)
+    [lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF[ -][0-9][0-9])(-bit)?( [LM]SB)? shared object( file)?[, -]* PA-RISC [0-9]\.[0-9]']
+    lt_cv_file_magic_test_file=/usr/lib/pa20_64/libc.sl
+    ;;
+  *)
+    lt_cv_deplibs_check_method='file_magic (s[[0-9]][[0-9]][[0-9]]|PA-RISC[[0-9]]\.[[0-9]]) shared library'
+    lt_cv_file_magic_test_file=/usr/lib/libc.sl
+    ;;
+  esac
+  ;;
+
+interix[[3-9]]*)
+  # PIC code is broken on Interix 3.x, that's why |\.a not |_pic\.a here
+  lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so|\.a)$'
+  ;;
+
+irix5* | irix6* | nonstopux*)
+  case $LD in
+  *-32|*"-32 ") libmagic=32-bit;;
+  *-n32|*"-n32 ") libmagic=N32;;
+  *-64|*"-64 ") libmagic=64-bit;;
+  *) libmagic=never-match;;
+  esac
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+# This must be glibc/ELF.
+linux* | k*bsd*-gnu | kopensolaris*-gnu)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+netbsd* | netbsdelf*-gnu)
+  if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then
+    lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|_pic\.a)$'
+  else
+    lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so|_pic\.a)$'
+  fi
+  ;;
+
+newos6*)
+  lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (executable|dynamic lib)'
+  lt_cv_file_magic_cmd=/usr/bin/file
+  lt_cv_file_magic_test_file=/usr/lib/libnls.so
+  ;;
+
+*nto* | *qnx*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+openbsd*)
+  if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+    lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|\.so|_pic\.a)$'
+  else
+    lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|_pic\.a)$'
+  fi
+  ;;
+
+osf3* | osf4* | osf5*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+rdos*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+solaris*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+sysv4 | sysv4.3*)
+  case $host_vendor in
+  motorola)
+    lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (shared object|dynamic lib) M[[0-9]][[0-9]]* Version [[0-9]]'
+    lt_cv_file_magic_test_file=`echo /usr/lib/libc.so*`
+    ;;
+  ncr)
+    lt_cv_deplibs_check_method=pass_all
+    ;;
+  sequent)
+    lt_cv_file_magic_cmd='/bin/file'
+    lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[LM]]SB (shared object|dynamic lib )'
+    ;;
+  sni)
+    lt_cv_file_magic_cmd='/bin/file'
+    lt_cv_deplibs_check_method="file_magic ELF [[0-9]][[0-9]]*-bit [[LM]]SB dynamic lib"
+    lt_cv_file_magic_test_file=/lib/libc.so
+    ;;
+  siemens)
+    lt_cv_deplibs_check_method=pass_all
+    ;;
+  pc)
+    lt_cv_deplibs_check_method=pass_all
+    ;;
+  esac
+  ;;
+
+tpf*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+esac
+])
+
+file_magic_glob=
+want_nocaseglob=no
+if test "$build" = "$host"; then
+  case $host_os in
+  mingw* | pw32*)
+    if ( shopt | grep nocaseglob ) >/dev/null 2>&1; then
+      want_nocaseglob=yes
+    else
+      file_magic_glob=`echo aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ | $SED -e "s/\(..\)/s\/[[\1]]\/[[\1]]\/g;/g"`
+    fi
+    ;;
+  esac
+fi
+
+file_magic_cmd=$lt_cv_file_magic_cmd
+deplibs_check_method=$lt_cv_deplibs_check_method
+test -z "$deplibs_check_method" && deplibs_check_method=unknown
+
+_LT_DECL([], [deplibs_check_method], [1],
+    [Method to check whether dependent libraries are shared objects])
+_LT_DECL([], [file_magic_cmd], [1],
+    [Command to use when deplibs_check_method = "file_magic"])
+_LT_DECL([], [file_magic_glob], [1],
+    [How to find potential files when deplibs_check_method = "file_magic"])
+_LT_DECL([], [want_nocaseglob], [1],
+    [Find potential files using nocaseglob when deplibs_check_method = "file_magic"])
+])# _LT_CHECK_MAGIC_METHOD
+
+
+# LT_PATH_NM
+# ----------
+# find the pathname to a BSD- or MS-compatible name lister
+AC_DEFUN([LT_PATH_NM],
+[AC_REQUIRE([AC_PROG_CC])dnl
+AC_CACHE_CHECK([for BSD- or MS-compatible name lister (nm)], lt_cv_path_NM,
+[if test -n "$NM"; then
+  # Let the user override the test.
+  lt_cv_path_NM="$NM"
+else
+  lt_nm_to_check="${ac_tool_prefix}nm"
+  if test -n "$ac_tool_prefix" && test "$build" = "$host"; then
+    lt_nm_to_check="$lt_nm_to_check nm"
+  fi
+  for lt_tmp_nm in $lt_nm_to_check; do
+    lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
+    for ac_dir in $PATH /usr/ccs/bin/elf /usr/ccs/bin /usr/ucb /bin; do
+      IFS="$lt_save_ifs"
+      test -z "$ac_dir" && ac_dir=.
+      tmp_nm="$ac_dir/$lt_tmp_nm"
+      if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext" ; then
+	# Check to see if the nm accepts a BSD-compat flag.
+	# Adding the `sed 1q' prevents false positives on HP-UX, which says:
+	#   nm: unknown option "B" ignored
+	# Tru64's nm complains that /dev/null is an invalid object file
+	case `"$tmp_nm" -B /dev/null 2>&1 | sed '1q'` in
+	*/dev/null* | *'Invalid file or object type'*)
+	  lt_cv_path_NM="$tmp_nm -B"
+	  break
+	  ;;
+	*)
+	  case `"$tmp_nm" -p /dev/null 2>&1 | sed '1q'` in
+	  */dev/null*)
+	    lt_cv_path_NM="$tmp_nm -p"
+	    break
+	    ;;
+	  *)
+	    lt_cv_path_NM=${lt_cv_path_NM="$tmp_nm"} # keep the first match, but
+	    continue # so that we can try to find one that supports BSD flags
+	    ;;
+	  esac
+	  ;;
+	esac
+      fi
+    done
+    IFS="$lt_save_ifs"
+  done
+  : ${lt_cv_path_NM=no}
+fi])
+if test "$lt_cv_path_NM" != "no"; then
+  NM="$lt_cv_path_NM"
+else
+  # Didn't find any BSD compatible name lister, look for dumpbin.
+  if test -n "$DUMPBIN"; then :
+    # Let the user override the test.
+  else
+    AC_CHECK_TOOLS(DUMPBIN, [dumpbin "link -dump"], :)
+    case `$DUMPBIN -symbols /dev/null 2>&1 | sed '1q'` in
+    *COFF*)
+      DUMPBIN="$DUMPBIN -symbols"
+      ;;
+    *)
+      DUMPBIN=:
+      ;;
+    esac
+  fi
+  AC_SUBST([DUMPBIN])
+  if test "$DUMPBIN" != ":"; then
+    NM="$DUMPBIN"
+  fi
+fi
+test -z "$NM" && NM=nm
+AC_SUBST([NM])
+_LT_DECL([], [NM], [1], [A BSD- or MS-compatible name lister])dnl
+
+AC_CACHE_CHECK([the name lister ($NM) interface], [lt_cv_nm_interface],
+  [lt_cv_nm_interface="BSD nm"
+  echo "int some_variable = 0;" > conftest.$ac_ext
+  (eval echo "\"\$as_me:$LINENO: $ac_compile\"" >&AS_MESSAGE_LOG_FD)
+  (eval "$ac_compile" 2>conftest.err)
+  cat conftest.err >&AS_MESSAGE_LOG_FD
+  (eval echo "\"\$as_me:$LINENO: $NM \\\"conftest.$ac_objext\\\"\"" >&AS_MESSAGE_LOG_FD)
+  (eval "$NM \"conftest.$ac_objext\"" 2>conftest.err > conftest.out)
+  cat conftest.err >&AS_MESSAGE_LOG_FD
+  (eval echo "\"\$as_me:$LINENO: output\"" >&AS_MESSAGE_LOG_FD)
+  cat conftest.out >&AS_MESSAGE_LOG_FD
+  if $GREP 'External.*some_variable' conftest.out > /dev/null; then
+    lt_cv_nm_interface="MS dumpbin"
+  fi
+  rm -f conftest*])
+])# LT_PATH_NM
+
+# Old names:
+AU_ALIAS([AM_PROG_NM], [LT_PATH_NM])
+AU_ALIAS([AC_PROG_NM], [LT_PATH_NM])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AM_PROG_NM], [])
+dnl AC_DEFUN([AC_PROG_NM], [])
+
+# _LT_CHECK_SHAREDLIB_FROM_LINKLIB
+# --------------------------------
+# how to determine the name of the shared library
+# associated with a specific link library.
+#  -- PORTME fill in with the dynamic library characteristics
+m4_defun([_LT_CHECK_SHAREDLIB_FROM_LINKLIB],
+[m4_require([_LT_DECL_EGREP])
+m4_require([_LT_DECL_OBJDUMP])
+m4_require([_LT_DECL_DLLTOOL])
+AC_CACHE_CHECK([how to associate runtime and link libraries],
+lt_cv_sharedlib_from_linklib_cmd,
+[lt_cv_sharedlib_from_linklib_cmd='unknown'
+
+case $host_os in
+cygwin* | mingw* | pw32* | cegcc*)
+  # two different shell functions defined in ltmain.sh
+  # decide which to use based on capabilities of $DLLTOOL
+  case `$DLLTOOL --help 2>&1` in
+  *--identify-strict*)
+    lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib
+    ;;
+  *)
+    lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib_fallback
+    ;;
+  esac
+  ;;
+*)
+  # fallback: assume linklib IS sharedlib
+  lt_cv_sharedlib_from_linklib_cmd="$ECHO"
+  ;;
+esac
+])
+sharedlib_from_linklib_cmd=$lt_cv_sharedlib_from_linklib_cmd
+test -z "$sharedlib_from_linklib_cmd" && sharedlib_from_linklib_cmd=$ECHO
+
+_LT_DECL([], [sharedlib_from_linklib_cmd], [1],
+    [Command to associate shared and link libraries])
+])# _LT_CHECK_SHAREDLIB_FROM_LINKLIB
+
+
+# _LT_PATH_MANIFEST_TOOL
+# ----------------------
+# locate the manifest tool
+m4_defun([_LT_PATH_MANIFEST_TOOL],
+[AC_CHECK_TOOL(MANIFEST_TOOL, mt, :)
+test -z "$MANIFEST_TOOL" && MANIFEST_TOOL=mt
+AC_CACHE_CHECK([if $MANIFEST_TOOL is a manifest tool], [lt_cv_path_mainfest_tool],
+  [lt_cv_path_mainfest_tool=no
+  echo "$as_me:$LINENO: $MANIFEST_TOOL '-?'" >&AS_MESSAGE_LOG_FD
+  $MANIFEST_TOOL '-?' 2>conftest.err > conftest.out
+  cat conftest.err >&AS_MESSAGE_LOG_FD
+  if $GREP 'Manifest Tool' conftest.out > /dev/null; then
+    lt_cv_path_mainfest_tool=yes
+  fi
+  rm -f conftest*])
+if test "x$lt_cv_path_mainfest_tool" != xyes; then
+  MANIFEST_TOOL=:
+fi
+_LT_DECL([], [MANIFEST_TOOL], [1], [Manifest tool])dnl
+])# _LT_PATH_MANIFEST_TOOL
+
+
+# LT_LIB_M
+# --------
+# check for math library
+AC_DEFUN([LT_LIB_M],
+[AC_REQUIRE([AC_CANONICAL_HOST])dnl
+LIBM=
+case $host in
+*-*-beos* | *-*-cegcc* | *-*-cygwin* | *-*-haiku* | *-*-pw32* | *-*-darwin*)
+  # These system don't have libm, or don't need it
+  ;;
+*-ncr-sysv4.3*)
+  AC_CHECK_LIB(mw, _mwvalidcheckl, LIBM="-lmw")
+  AC_CHECK_LIB(m, cos, LIBM="$LIBM -lm")
+  ;;
+*)
+  AC_CHECK_LIB(m, cos, LIBM="-lm")
+  ;;
+esac
+AC_SUBST([LIBM])
+])# LT_LIB_M
+
+# Old name:
+AU_ALIAS([AC_CHECK_LIBM], [LT_LIB_M])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_CHECK_LIBM], [])
+
+
+# _LT_COMPILER_NO_RTTI([TAGNAME])
+# -------------------------------
+m4_defun([_LT_COMPILER_NO_RTTI],
+[m4_require([_LT_TAG_COMPILER])dnl
+
+_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=
+
+if test "$GCC" = yes; then
+  case $cc_basename in
+  nvcc*)
+    _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -Xcompiler -fno-builtin' ;;
+  *)
+    _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -fno-builtin' ;;
+  esac
+
+  _LT_COMPILER_OPTION([if $compiler supports -fno-rtti -fno-exceptions],
+    lt_cv_prog_compiler_rtti_exceptions,
+    [-fno-rtti -fno-exceptions], [],
+    [_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)="$_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1) -fno-rtti -fno-exceptions"])
+fi
+_LT_TAGDECL([no_builtin_flag], [lt_prog_compiler_no_builtin_flag], [1],
+	[Compiler flag to turn off builtin functions])
+])# _LT_COMPILER_NO_RTTI
+
+
+# _LT_CMD_GLOBAL_SYMBOLS
+# ----------------------
+m4_defun([_LT_CMD_GLOBAL_SYMBOLS],
+[AC_REQUIRE([AC_CANONICAL_HOST])dnl
+AC_REQUIRE([AC_PROG_CC])dnl
+AC_REQUIRE([AC_PROG_AWK])dnl
+AC_REQUIRE([LT_PATH_NM])dnl
+AC_REQUIRE([LT_PATH_LD])dnl
+m4_require([_LT_DECL_SED])dnl
+m4_require([_LT_DECL_EGREP])dnl
+m4_require([_LT_TAG_COMPILER])dnl
+
+# Check for command to grab the raw symbol name followed by C symbol from nm.
+AC_MSG_CHECKING([command to parse $NM output from $compiler object])
+AC_CACHE_VAL([lt_cv_sys_global_symbol_pipe],
+[
+# These are sane defaults that work on at least a few old systems.
+# [They come from Ultrix.  What could be older than Ultrix?!! ;)]
+
+# Character class describing NM global symbol codes.
+symcode='[[BCDEGRST]]'
+
+# Regexp to match symbols that can be accessed directly from C.
+sympat='\([[_A-Za-z]][[_A-Za-z0-9]]*\)'
+
+# Define system-specific variables.
+case $host_os in
+aix*)
+  symcode='[[BCDT]]'
+  ;;
+cygwin* | mingw* | pw32* | cegcc*)
+  symcode='[[ABCDGISTW]]'
+  ;;
+hpux*)
+  if test "$host_cpu" = ia64; then
+    symcode='[[ABCDEGRST]]'
+  fi
+  ;;
+irix* | nonstopux*)
+  symcode='[[BCDEGRST]]'
+  ;;
+osf*)
+  symcode='[[BCDEGQRST]]'
+  ;;
+solaris*)
+  symcode='[[BDRT]]'
+  ;;
+sco3.2v5*)
+  symcode='[[DT]]'
+  ;;
+sysv4.2uw2*)
+  symcode='[[DT]]'
+  ;;
+sysv5* | sco5v6* | unixware* | OpenUNIX*)
+  symcode='[[ABDT]]'
+  ;;
+sysv4)
+  symcode='[[DFNSTU]]'
+  ;;
+esac
+
+# If we're using GNU nm, then use its standard symbol codes.
+case `$NM -V 2>&1` in
+*GNU* | *'with BFD'*)
+  symcode='[[ABCDGIRSTW]]' ;;
+esac
+
+# Transform an extracted symbol line into a proper C declaration.
+# Some systems (esp. on ia64) link data and code symbols differently,
+# so use this general approach.
+lt_cv_sys_global_symbol_to_cdecl="sed -n -e 's/^T .* \(.*\)$/extern int \1();/p' -e 's/^$symcode* .* \(.*\)$/extern char \1;/p'"
+
+# Transform an extracted symbol line into symbol name and symbol address
+lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([[^ ]]*\)[[ ]]*$/  {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([[^ ]]*\) \([[^ ]]*\)$/  {\"\2\", (void *) \&\2},/p'"
+lt_cv_sys_global_symbol_to_c_name_address_lib_prefix="sed -n -e 's/^: \([[^ ]]*\)[[ ]]*$/  {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([[^ ]]*\) \(lib[[^ ]]*\)$/  {\"\2\", (void *) \&\2},/p' -e 's/^$symcode* \([[^ ]]*\) \([[^ ]]*\)$/  {\"lib\2\", (void *) \&\2},/p'"
+
+# Handle CRLF in mingw tool chain
+opt_cr=
+case $build_os in
+mingw*)
+  opt_cr=`$ECHO 'x\{0,1\}' | tr x '\015'` # option cr in regexp
+  ;;
+esac
+
+# Try without a prefix underscore, then with it.
+for ac_symprfx in "" "_"; do
+
+  # Transform symcode, sympat, and symprfx into a raw symbol and a C symbol.
+  symxfrm="\\1 $ac_symprfx\\2 \\2"
+
+  # Write the raw and C identifiers.
+  if test "$lt_cv_nm_interface" = "MS dumpbin"; then
+    # Fake it for dumpbin and say T for any non-static function
+    # and D for any global variable.
+    # Also find C++ and __fastcall symbols from MSVC++,
+    # which start with @ or ?.
+    lt_cv_sys_global_symbol_pipe="$AWK ['"\
+"     {last_section=section; section=\$ 3};"\
+"     /^COFF SYMBOL TABLE/{for(i in hide) delete hide[i]};"\
+"     /Section length .*#relocs.*(pick any)/{hide[last_section]=1};"\
+"     \$ 0!~/External *\|/{next};"\
+"     / 0+ UNDEF /{next}; / UNDEF \([^|]\)*()/{next};"\
+"     {if(hide[section]) next};"\
+"     {f=0}; \$ 0~/\(\).*\|/{f=1}; {printf f ? \"T \" : \"D \"};"\
+"     {split(\$ 0, a, /\||\r/); split(a[2], s)};"\
+"     s[1]~/^[@?]/{print s[1], s[1]; next};"\
+"     s[1]~prfx {split(s[1],t,\"@\"); print t[1], substr(t[1],length(prfx))}"\
+"     ' prfx=^$ac_symprfx]"
+  else
+    lt_cv_sys_global_symbol_pipe="sed -n -e 's/^.*[[	 ]]\($symcode$symcode*\)[[	 ]][[	 ]]*$ac_symprfx$sympat$opt_cr$/$symxfrm/p'"
+  fi
+  lt_cv_sys_global_symbol_pipe="$lt_cv_sys_global_symbol_pipe | sed '/ __gnu_lto/d'"
+
+  # Check to see that the pipe works correctly.
+  pipe_works=no
+
+  rm -f conftest*
+  cat > conftest.$ac_ext <<_LT_EOF
+#ifdef __cplusplus
+extern "C" {
+#endif
+char nm_test_var;
+void nm_test_func(void);
+void nm_test_func(void){}
+#ifdef __cplusplus
+}
+#endif
+int main(){nm_test_var='a';nm_test_func();return(0);}
+_LT_EOF
+
+  if AC_TRY_EVAL(ac_compile); then
+    # Now try to grab the symbols.
+    nlist=conftest.nm
+    if AC_TRY_EVAL(NM conftest.$ac_objext \| "$lt_cv_sys_global_symbol_pipe" \> $nlist) && test -s "$nlist"; then
+      # Try sorting and uniquifying the output.
+      if sort "$nlist" | uniq > "$nlist"T; then
+	mv -f "$nlist"T "$nlist"
+      else
+	rm -f "$nlist"T
+      fi
+
+      # Make sure that we snagged all the symbols we need.
+      if $GREP ' nm_test_var$' "$nlist" >/dev/null; then
+	if $GREP ' nm_test_func$' "$nlist" >/dev/null; then
+	  cat <<_LT_EOF > conftest.$ac_ext
+/* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests.  */
+#if defined(_WIN32) || defined(__CYGWIN__) || defined(_WIN32_WCE)
+/* DATA imports from DLLs on WIN32 con't be const, because runtime
+   relocations are performed -- see ld's documentation on pseudo-relocs.  */
+# define LT@&t at _DLSYM_CONST
+#elif defined(__osf__)
+/* This system does not cope well with relocations in const data.  */
+# define LT@&t at _DLSYM_CONST
+#else
+# define LT@&t at _DLSYM_CONST const
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+_LT_EOF
+	  # Now generate the symbol file.
+	  eval "$lt_cv_sys_global_symbol_to_cdecl"' < "$nlist" | $GREP -v main >> conftest.$ac_ext'
+
+	  cat <<_LT_EOF >> conftest.$ac_ext
+
+/* The mapping between symbol names and symbols.  */
+LT@&t at _DLSYM_CONST struct {
+  const char *name;
+  void       *address;
+}
+lt__PROGRAM__LTX_preloaded_symbols[[]] =
+{
+  { "@PROGRAM@", (void *) 0 },
+_LT_EOF
+	  $SED "s/^$symcode$symcode* \(.*\) \(.*\)$/  {\"\2\", (void *) \&\2},/" < "$nlist" | $GREP -v main >> conftest.$ac_ext
+	  cat <<\_LT_EOF >> conftest.$ac_ext
+  {0, (void *) 0}
+};
+
+/* This works around a problem in FreeBSD linker */
+#ifdef FREEBSD_WORKAROUND
+static const void *lt_preloaded_setup() {
+  return lt__PROGRAM__LTX_preloaded_symbols;
+}
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+_LT_EOF
+	  # Now try linking the two files.
+	  mv conftest.$ac_objext conftstm.$ac_objext
+	  lt_globsym_save_LIBS=$LIBS
+	  lt_globsym_save_CFLAGS=$CFLAGS
+	  LIBS="conftstm.$ac_objext"
+	  CFLAGS="$CFLAGS$_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)"
+	  if AC_TRY_EVAL(ac_link) && test -s conftest${ac_exeext}; then
+	    pipe_works=yes
+	  fi
+	  LIBS=$lt_globsym_save_LIBS
+	  CFLAGS=$lt_globsym_save_CFLAGS
+	else
+	  echo "cannot find nm_test_func in $nlist" >&AS_MESSAGE_LOG_FD
+	fi
+      else
+	echo "cannot find nm_test_var in $nlist" >&AS_MESSAGE_LOG_FD
+      fi
+    else
+      echo "cannot run $lt_cv_sys_global_symbol_pipe" >&AS_MESSAGE_LOG_FD
+    fi
+  else
+    echo "$progname: failed program was:" >&AS_MESSAGE_LOG_FD
+    cat conftest.$ac_ext >&5
+  fi
+  rm -rf conftest* conftst*
+
+  # Do not use the global_symbol_pipe unless it works.
+  if test "$pipe_works" = yes; then
+    break
+  else
+    lt_cv_sys_global_symbol_pipe=
+  fi
+done
+])
+if test -z "$lt_cv_sys_global_symbol_pipe"; then
+  lt_cv_sys_global_symbol_to_cdecl=
+fi
+if test -z "$lt_cv_sys_global_symbol_pipe$lt_cv_sys_global_symbol_to_cdecl"; then
+  AC_MSG_RESULT(failed)
+else
+  AC_MSG_RESULT(ok)
+fi
+
+# Response file support.
+if test "$lt_cv_nm_interface" = "MS dumpbin"; then
+  nm_file_list_spec='@'
+elif $NM --help 2>/dev/null | grep '[[@]]FILE' >/dev/null; then
+  nm_file_list_spec='@'
+fi
+
+_LT_DECL([global_symbol_pipe], [lt_cv_sys_global_symbol_pipe], [1],
+    [Take the output of nm and produce a listing of raw symbols and C names])
+_LT_DECL([global_symbol_to_cdecl], [lt_cv_sys_global_symbol_to_cdecl], [1],
+    [Transform the output of nm in a proper C declaration])
+_LT_DECL([global_symbol_to_c_name_address],
+    [lt_cv_sys_global_symbol_to_c_name_address], [1],
+    [Transform the output of nm in a C name address pair])
+_LT_DECL([global_symbol_to_c_name_address_lib_prefix],
+    [lt_cv_sys_global_symbol_to_c_name_address_lib_prefix], [1],
+    [Transform the output of nm in a C name address pair when lib prefix is needed])
+_LT_DECL([], [nm_file_list_spec], [1],
+    [Specify filename containing input files for $NM])
+]) # _LT_CMD_GLOBAL_SYMBOLS
+
+
+# _LT_COMPILER_PIC([TAGNAME])
+# ---------------------------
+m4_defun([_LT_COMPILER_PIC],
+[m4_require([_LT_TAG_COMPILER])dnl
+_LT_TAGVAR(lt_prog_compiler_wl, $1)=
+_LT_TAGVAR(lt_prog_compiler_pic, $1)=
+_LT_TAGVAR(lt_prog_compiler_static, $1)=
+
+m4_if([$1], [CXX], [
+  # C++ specific cases for pic, static, wl, etc.
+  if test "$GXX" = yes; then
+    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+    _LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
+
+    case $host_os in
+    aix*)
+      # All AIX code is PIC.
+      if test "$host_cpu" = ia64; then
+	# AIX 5 now supports IA64 processor
+	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      fi
+      ;;
+
+    amigaos*)
+      case $host_cpu in
+      powerpc)
+            # see comment about AmigaOS4 .so support
+            _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+        ;;
+      m68k)
+            # FIXME: we need at least 68020 code to build shared libraries, but
+            # adding the `-m68020' flag to GCC prevents building anything better,
+            # like `-m68040'.
+            _LT_TAGVAR(lt_prog_compiler_pic, $1)='-m68020 -resident32 -malways-restore-a4'
+        ;;
+      esac
+      ;;
+
+    beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*)
+      # PIC is the default for these OSes.
+      ;;
+    mingw* | cygwin* | os2* | pw32* | cegcc*)
+      # This hack is so that the source file can tell whether it is being
+      # built for inclusion in a dll (and should export symbols for example).
+      # Although the cygwin gcc ignores -fPIC, still need this for old-style
+      # (--disable-auto-import) libraries
+      m4_if([$1], [GCJ], [],
+	[_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT'])
+      ;;
+    darwin* | rhapsody*)
+      # PIC is the default on this platform
+      # Common symbols not allowed in MH_DYLIB files
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fno-common'
+      ;;
+    *djgpp*)
+      # DJGPP does not support shared libraries at all
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)=
+      ;;
+    haiku*)
+      # PIC is the default for Haiku.
+      # The "-static" flag exists, but is broken.
+      _LT_TAGVAR(lt_prog_compiler_static, $1)=
+      ;;
+    interix[[3-9]]*)
+      # Interix 3.x gcc -fpic/-fPIC options generate broken code.
+      # Instead, we relocate shared libraries at runtime.
+      ;;
+    sysv4*MP*)
+      if test -d /usr/nec; then
+	_LT_TAGVAR(lt_prog_compiler_pic, $1)=-Kconform_pic
+      fi
+      ;;
+    hpux*)
+      # PIC is the default for 64-bit PA HP-UX, but not for 32-bit
+      # PA HP-UX.  On IA64 HP-UX, PIC is the default but the pic flag
+      # sets the default TLS model and affects inlining.
+      case $host_cpu in
+      hppa*64*)
+	;;
+      *)
+	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+	;;
+      esac
+      ;;
+    *qnx* | *nto*)
+      # QNX uses GNU C++, but need to define -shared option too, otherwise
+      # it will coredump.
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared'
+      ;;
+    *)
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+      ;;
+    esac
+  else
+    case $host_os in
+      aix[[4-9]]*)
+	# All AIX code is PIC.
+	if test "$host_cpu" = ia64; then
+	  # AIX 5 now supports IA64 processor
+	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+	else
+	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-bnso -bI:/lib/syscalls.exp'
+	fi
+	;;
+      chorus*)
+	case $cc_basename in
+	cxch68*)
+	  # Green Hills C++ Compiler
+	  # _LT_TAGVAR(lt_prog_compiler_static, $1)="--no_auto_instantiation -u __main -u __premain -u _abort -r $COOL_DIR/lib/libOrb.a $MVME_DIR/lib/CC/libC.a $MVME_DIR/lib/classix/libcx.s.a"
+	  ;;
+	esac
+	;;
+      mingw* | cygwin* | os2* | pw32* | cegcc*)
+	# This hack is so that the source file can tell whether it is being
+	# built for inclusion in a dll (and should export symbols for example).
+	m4_if([$1], [GCJ], [],
+	  [_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT'])
+	;;
+      dgux*)
+	case $cc_basename in
+	  ec++*)
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+	    ;;
+	  ghcx*)
+	    # Green Hills C++ Compiler
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
+	    ;;
+	  *)
+	    ;;
+	esac
+	;;
+      freebsd* | dragonfly*)
+	# FreeBSD uses GNU C++
+	;;
+      hpux9* | hpux10* | hpux11*)
+	case $cc_basename in
+	  CC*)
+	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive'
+	    if test "$host_cpu" != ia64; then
+	      _LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z'
+	    fi
+	    ;;
+	  aCC*)
+	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive'
+	    case $host_cpu in
+	    hppa*64*|ia64*)
+	      # +Z the default
+	      ;;
+	    *)
+	      _LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z'
+	      ;;
+	    esac
+	    ;;
+	  *)
+	    ;;
+	esac
+	;;
+      interix*)
+	# This is c89, which is MS Visual C++ (no shared libs)
+	# Anyone wants to do a port?
+	;;
+      irix5* | irix6* | nonstopux*)
+	case $cc_basename in
+	  CC*)
+	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
+	    # CC pic flag -KPIC is the default.
+	    ;;
+	  *)
+	    ;;
+	esac
+	;;
+      linux* | k*bsd*-gnu | kopensolaris*-gnu)
+	case $cc_basename in
+	  KCC*)
+	    # KAI C++ Compiler
+	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='--backend -Wl,'
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+	    ;;
+	  ecpc* )
+	    # old Intel C++ for x86_64 which still supported -KPIC.
+	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
+	    ;;
+	  icpc* )
+	    # Intel C++, used to be incompatible with GCC.
+	    # ICC 10 doesn't accept -KPIC any more.
+	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
+	    ;;
+	  pgCC* | pgcpp*)
+	    # Portland Group C++ compiler
+	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fpic'
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+	    ;;
+	  cxx*)
+	    # Compaq C++
+	    # Make sure the PIC flag is empty.  It appears that all Alpha
+	    # Linux and Compaq Tru64 Unix objects are PIC.
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)=
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
+	    ;;
+	  xlc* | xlC* | bgxl[[cC]]* | mpixl[[cC]]*)
+	    # IBM XL 8.0, 9.0 on PPC and BlueGene
+	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-qpic'
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-qstaticlink'
+	    ;;
+	  *)
+	    case `$CC -V 2>&1 | sed 5q` in
+	    *Sun\ C*)
+	      # Sun C++ 5.9
+	      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+	      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+	      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld '
+	      ;;
+	    esac
+	    ;;
+	esac
+	;;
+      lynxos*)
+	;;
+      m88k*)
+	;;
+      mvs*)
+	case $cc_basename in
+	  cxx*)
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-W c,exportall'
+	    ;;
+	  *)
+	    ;;
+	esac
+	;;
+      netbsd* | netbsdelf*-gnu)
+	;;
+      *qnx* | *nto*)
+        # QNX uses GNU C++, but need to define -shared option too, otherwise
+        # it will coredump.
+        _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared'
+        ;;
+      osf3* | osf4* | osf5*)
+	case $cc_basename in
+	  KCC*)
+	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='--backend -Wl,'
+	    ;;
+	  RCC*)
+	    # Rational C++ 2.4.1
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
+	    ;;
+	  cxx*)
+	    # Digital/Compaq C++
+	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	    # Make sure the PIC flag is empty.  It appears that all Alpha
+	    # Linux and Compaq Tru64 Unix objects are PIC.
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)=
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
+	    ;;
+	  *)
+	    ;;
+	esac
+	;;
+      psos*)
+	;;
+      solaris*)
+	case $cc_basename in
+	  CC* | sunCC*)
+	    # Sun C++ 4.2, 5.x and Centerline C++
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld '
+	    ;;
+	  gcx*)
+	    # Green Hills C++ Compiler
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC'
+	    ;;
+	  *)
+	    ;;
+	esac
+	;;
+      sunos4*)
+	case $cc_basename in
+	  CC*)
+	    # Sun C++ 4.x
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+	    ;;
+	  lcc*)
+	    # Lucid
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
+	    ;;
+	  *)
+	    ;;
+	esac
+	;;
+      sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*)
+	case $cc_basename in
+	  CC*)
+	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+	    ;;
+	esac
+	;;
+      tandem*)
+	case $cc_basename in
+	  NCC*)
+	    # NonStop-UX NCC 3.20
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+	    ;;
+	  *)
+	    ;;
+	esac
+	;;
+      vxworks*)
+	;;
+      *)
+	_LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no
+	;;
+    esac
+  fi
+],
+[
+  if test "$GCC" = yes; then
+    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+    _LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
+
+    case $host_os in
+      aix*)
+      # All AIX code is PIC.
+      if test "$host_cpu" = ia64; then
+	# AIX 5 now supports IA64 processor
+	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      fi
+      ;;
+
+    amigaos*)
+      case $host_cpu in
+      powerpc)
+            # see comment about AmigaOS4 .so support
+            _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+        ;;
+      m68k)
+            # FIXME: we need at least 68020 code to build shared libraries, but
+            # adding the `-m68020' flag to GCC prevents building anything better,
+            # like `-m68040'.
+            _LT_TAGVAR(lt_prog_compiler_pic, $1)='-m68020 -resident32 -malways-restore-a4'
+        ;;
+      esac
+      ;;
+
+    beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*)
+      # PIC is the default for these OSes.
+      ;;
+
+    mingw* | cygwin* | pw32* | os2* | cegcc*)
+      # This hack is so that the source file can tell whether it is being
+      # built for inclusion in a dll (and should export symbols for example).
+      # Although the cygwin gcc ignores -fPIC, still need this for old-style
+      # (--disable-auto-import) libraries
+      m4_if([$1], [GCJ], [],
+	[_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT'])
+      ;;
+
+    darwin* | rhapsody*)
+      # PIC is the default on this platform
+      # Common symbols not allowed in MH_DYLIB files
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fno-common'
+      ;;
+
+    haiku*)
+      # PIC is the default for Haiku.
+      # The "-static" flag exists, but is broken.
+      _LT_TAGVAR(lt_prog_compiler_static, $1)=
+      ;;
+
+    hpux*)
+      # PIC is the default for 64-bit PA HP-UX, but not for 32-bit
+      # PA HP-UX.  On IA64 HP-UX, PIC is the default but the pic flag
+      # sets the default TLS model and affects inlining.
+      case $host_cpu in
+      hppa*64*)
+	# +Z the default
+	;;
+      *)
+	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+	;;
+      esac
+      ;;
+
+    interix[[3-9]]*)
+      # Interix 3.x gcc -fpic/-fPIC options generate broken code.
+      # Instead, we relocate shared libraries at runtime.
+      ;;
+
+    msdosdjgpp*)
+      # Just because we use GCC doesn't mean we suddenly get shared libraries
+      # on systems that don't support them.
+      _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no
+      enable_shared=no
+      ;;
+
+    *nto* | *qnx*)
+      # QNX uses GNU C++, but need to define -shared option too, otherwise
+      # it will coredump.
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared'
+      ;;
+
+    sysv4*MP*)
+      if test -d /usr/nec; then
+	_LT_TAGVAR(lt_prog_compiler_pic, $1)=-Kconform_pic
+      fi
+      ;;
+
+    *)
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+      ;;
+    esac
+
+    case $cc_basename in
+    nvcc*) # Cuda Compiler Driver 2.2
+      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Xlinker '
+      if test -n "$_LT_TAGVAR(lt_prog_compiler_pic, $1)"; then
+        _LT_TAGVAR(lt_prog_compiler_pic, $1)="-Xcompiler $_LT_TAGVAR(lt_prog_compiler_pic, $1)"
+      fi
+      ;;
+    esac
+  else
+    # PORTME Check for flag to pass linker flags through the system compiler.
+    case $host_os in
+    aix*)
+      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+      if test "$host_cpu" = ia64; then
+	# AIX 5 now supports IA64 processor
+	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      else
+	_LT_TAGVAR(lt_prog_compiler_static, $1)='-bnso -bI:/lib/syscalls.exp'
+      fi
+      ;;
+
+    mingw* | cygwin* | pw32* | os2* | cegcc*)
+      # This hack is so that the source file can tell whether it is being
+      # built for inclusion in a dll (and should export symbols for example).
+      m4_if([$1], [GCJ], [],
+	[_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT'])
+      ;;
+
+    hpux9* | hpux10* | hpux11*)
+      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+      # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but
+      # not for PA HP-UX.
+      case $host_cpu in
+      hppa*64*|ia64*)
+	# +Z the default
+	;;
+      *)
+	_LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z'
+	;;
+      esac
+      # Is there a better lt_prog_compiler_static that works with the bundled CC?
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive'
+      ;;
+
+    irix5* | irix6* | nonstopux*)
+      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+      # PIC (with -KPIC) is the default.
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
+      ;;
+
+    linux* | k*bsd*-gnu | kopensolaris*-gnu)
+      case $cc_basename in
+      # old Intel for x86_64 which still supported -KPIC.
+      ecc*)
+	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+	_LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
+        ;;
+      # icc used to be incompatible with GCC.
+      # ICC 10 doesn't accept -KPIC any more.
+      icc* | ifort*)
+	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+	_LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
+        ;;
+      # Lahey Fortran 8.1.
+      lf95*)
+	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	_LT_TAGVAR(lt_prog_compiler_pic, $1)='--shared'
+	_LT_TAGVAR(lt_prog_compiler_static, $1)='--static'
+	;;
+      nagfor*)
+	# NAG Fortran compiler
+	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,-Wl,,'
+	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC'
+	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+	;;
+      pgcc* | pgf77* | pgf90* | pgf95* | pgfortran*)
+        # Portland Group compilers (*not* the Pentium gcc compiler,
+	# which looks to be a dead project)
+	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-fpic'
+	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+        ;;
+      ccc*)
+        _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+        # All Alpha code is PIC.
+        _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
+        ;;
+      xl* | bgxl* | bgf* | mpixl*)
+	# IBM XL C 8.0/Fortran 10.1, 11.1 on PPC and BlueGene
+	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-qpic'
+	_LT_TAGVAR(lt_prog_compiler_static, $1)='-qstaticlink'
+	;;
+      *)
+	case `$CC -V 2>&1 | sed 5q` in
+	*Sun\ Ceres\ Fortran* | *Sun*Fortran*\ [[1-7]].* | *Sun*Fortran*\ 8.[[0-3]]*)
+	  # Sun Fortran 8.3 passes all unrecognized flags to the linker
+	  _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+	  _LT_TAGVAR(lt_prog_compiler_wl, $1)=''
+	  ;;
+	*Sun\ F* | *Sun*Fortran*)
+	  _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+	  _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld '
+	  ;;
+	*Sun\ C*)
+	  # Sun C 5.9
+	  _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+	  _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	  ;;
+        *Intel*\ [[CF]]*Compiler*)
+	  _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	  _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
+	  ;;
+	*Portland\ Group*)
+	  _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	  _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fpic'
+	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+	  ;;
+	esac
+	;;
+      esac
+      ;;
+
+    newsos6)
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      ;;
+
+    *nto* | *qnx*)
+      # QNX uses GNU C++, but need to define -shared option too, otherwise
+      # it will coredump.
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared'
+      ;;
+
+    osf3* | osf4* | osf5*)
+      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+      # All OSF/1 code is PIC.
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
+      ;;
+
+    rdos*)
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
+      ;;
+
+    solaris*)
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      case $cc_basename in
+      f77* | f90* | f95* | sunf77* | sunf90* | sunf95*)
+	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ';;
+      *)
+	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,';;
+      esac
+      ;;
+
+    sunos4*)
+      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld '
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC'
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      ;;
+
+    sysv4 | sysv4.2uw2* | sysv4.3*)
+      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      ;;
+
+    sysv4*MP*)
+      if test -d /usr/nec ;then
+	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-Kconform_pic'
+	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      fi
+      ;;
+
+    sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*)
+      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      ;;
+
+    unicos*)
+      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+      _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no
+      ;;
+
+    uts4*)
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      ;;
+
+    *)
+      _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no
+      ;;
+    esac
+  fi
+])
+case $host_os in
+  # For platforms which do not support PIC, -DPIC is meaningless:
+  *djgpp*)
+    _LT_TAGVAR(lt_prog_compiler_pic, $1)=
+    ;;
+  *)
+    _LT_TAGVAR(lt_prog_compiler_pic, $1)="$_LT_TAGVAR(lt_prog_compiler_pic, $1)@&t at m4_if([$1],[],[ -DPIC],[m4_if([$1],[CXX],[ -DPIC],[])])"
+    ;;
+esac
+
+AC_CACHE_CHECK([for $compiler option to produce PIC],
+  [_LT_TAGVAR(lt_cv_prog_compiler_pic, $1)],
+  [_LT_TAGVAR(lt_cv_prog_compiler_pic, $1)=$_LT_TAGVAR(lt_prog_compiler_pic, $1)])
+_LT_TAGVAR(lt_prog_compiler_pic, $1)=$_LT_TAGVAR(lt_cv_prog_compiler_pic, $1)
+
+#
+# Check to make sure the PIC flag actually works.
+#
+if test -n "$_LT_TAGVAR(lt_prog_compiler_pic, $1)"; then
+  _LT_COMPILER_OPTION([if $compiler PIC flag $_LT_TAGVAR(lt_prog_compiler_pic, $1) works],
+    [_LT_TAGVAR(lt_cv_prog_compiler_pic_works, $1)],
+    [$_LT_TAGVAR(lt_prog_compiler_pic, $1)@&t at m4_if([$1],[],[ -DPIC],[m4_if([$1],[CXX],[ -DPIC],[])])], [],
+    [case $_LT_TAGVAR(lt_prog_compiler_pic, $1) in
+     "" | " "*) ;;
+     *) _LT_TAGVAR(lt_prog_compiler_pic, $1)=" $_LT_TAGVAR(lt_prog_compiler_pic, $1)" ;;
+     esac],
+    [_LT_TAGVAR(lt_prog_compiler_pic, $1)=
+     _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no])
+fi
+_LT_TAGDECL([pic_flag], [lt_prog_compiler_pic], [1],
+	[Additional compiler flags for building library objects])
+
+_LT_TAGDECL([wl], [lt_prog_compiler_wl], [1],
+	[How to pass a linker flag through the compiler])
+#
+# Check to make sure the static flag actually works.
+#
+wl=$_LT_TAGVAR(lt_prog_compiler_wl, $1) eval lt_tmp_static_flag=\"$_LT_TAGVAR(lt_prog_compiler_static, $1)\"
+_LT_LINKER_OPTION([if $compiler static flag $lt_tmp_static_flag works],
+  _LT_TAGVAR(lt_cv_prog_compiler_static_works, $1),
+  $lt_tmp_static_flag,
+  [],
+  [_LT_TAGVAR(lt_prog_compiler_static, $1)=])
+_LT_TAGDECL([link_static_flag], [lt_prog_compiler_static], [1],
+	[Compiler flag to prevent dynamic linking])
+])# _LT_COMPILER_PIC
+
+
+# _LT_LINKER_SHLIBS([TAGNAME])
+# ----------------------------
+# See if the linker supports building shared libraries.
+m4_defun([_LT_LINKER_SHLIBS],
+[AC_REQUIRE([LT_PATH_LD])dnl
+AC_REQUIRE([LT_PATH_NM])dnl
+m4_require([_LT_PATH_MANIFEST_TOOL])dnl
+m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+m4_require([_LT_DECL_EGREP])dnl
+m4_require([_LT_DECL_SED])dnl
+m4_require([_LT_CMD_GLOBAL_SYMBOLS])dnl
+m4_require([_LT_TAG_COMPILER])dnl
+AC_MSG_CHECKING([whether the $compiler linker ($LD) supports shared libraries])
+m4_if([$1], [CXX], [
+  _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
+  _LT_TAGVAR(exclude_expsyms, $1)=['_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*']
+  case $host_os in
+  aix[[4-9]]*)
+    # If we're using GNU nm, then we don't want the "-C" option.
+    # -C means demangle to AIX nm, but means don't demangle with GNU nm
+    # Also, AIX nm treats weak defined symbols like other global defined
+    # symbols, whereas GNU nm marks them as "W".
+    if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then
+      _LT_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
+    else
+      _LT_TAGVAR(export_symbols_cmds, $1)='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
+    fi
+    ;;
+  pw32*)
+    _LT_TAGVAR(export_symbols_cmds, $1)="$ltdll_cmds"
+    ;;
+  cygwin* | mingw* | cegcc*)
+    case $cc_basename in
+    cl*)
+      _LT_TAGVAR(exclude_expsyms, $1)='_NULL_IMPORT_DESCRIPTOR|_IMPORT_DESCRIPTOR_.*'
+      ;;
+    *)
+      _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1 DATA/;s/^.*[[ ]]__nm__\([[^ ]]*\)[[ ]][[^ ]]*/\1 DATA/;/^I[[ ]]/d;/^[[AITW]][[ ]]/s/.* //'\'' | sort | uniq > $export_symbols'
+      _LT_TAGVAR(exclude_expsyms, $1)=['[_]+GLOBAL_OFFSET_TABLE_|[_]+GLOBAL__[FID]_.*|[_]+head_[A-Za-z0-9_]+_dll|[A-Za-z0-9_]+_dll_iname']
+      ;;
+    esac
+    ;;
+  linux* | k*bsd*-gnu | gnu*)
+    _LT_TAGVAR(link_all_deplibs, $1)=no
+    ;;
+  *)
+    _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
+    ;;
+  esac
+], [
+  runpath_var=
+  _LT_TAGVAR(allow_undefined_flag, $1)=
+  _LT_TAGVAR(always_export_symbols, $1)=no
+  _LT_TAGVAR(archive_cmds, $1)=
+  _LT_TAGVAR(archive_expsym_cmds, $1)=
+  _LT_TAGVAR(compiler_needs_object, $1)=no
+  _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no
+  _LT_TAGVAR(export_dynamic_flag_spec, $1)=
+  _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
+  _LT_TAGVAR(hardcode_automatic, $1)=no
+  _LT_TAGVAR(hardcode_direct, $1)=no
+  _LT_TAGVAR(hardcode_direct_absolute, $1)=no
+  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
+  _LT_TAGVAR(hardcode_libdir_separator, $1)=
+  _LT_TAGVAR(hardcode_minus_L, $1)=no
+  _LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported
+  _LT_TAGVAR(inherit_rpath, $1)=no
+  _LT_TAGVAR(link_all_deplibs, $1)=unknown
+  _LT_TAGVAR(module_cmds, $1)=
+  _LT_TAGVAR(module_expsym_cmds, $1)=
+  _LT_TAGVAR(old_archive_from_new_cmds, $1)=
+  _LT_TAGVAR(old_archive_from_expsyms_cmds, $1)=
+  _LT_TAGVAR(thread_safe_flag_spec, $1)=
+  _LT_TAGVAR(whole_archive_flag_spec, $1)=
+  # include_expsyms should be a list of space-separated symbols to be *always*
+  # included in the symbol list
+  _LT_TAGVAR(include_expsyms, $1)=
+  # exclude_expsyms can be an extended regexp of symbols to exclude
+  # it will be wrapped by ` (' and `)$', so one must not match beginning or
+  # end of line.  Example: `a|bc|.*d.*' will exclude the symbols `a' and `bc',
+  # as well as any symbol that contains `d'.
+  _LT_TAGVAR(exclude_expsyms, $1)=['_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*']
+  # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out
+  # platforms (ab)use it in PIC code, but their linkers get confused if
+  # the symbol is explicitly referenced.  Since portable code cannot
+  # rely on this symbol name, it's probably fine to never include it in
+  # preloaded symbol tables.
+  # Exclude shared library initialization/finalization symbols.
+dnl Note also adjust exclude_expsyms for C++ above.
+  extract_expsyms_cmds=
+
+  case $host_os in
+  cygwin* | mingw* | pw32* | cegcc*)
+    # FIXME: the MSVC++ port hasn't been tested in a loooong time
+    # When not using gcc, we currently assume that we are using
+    # Microsoft Visual C++.
+    if test "$GCC" != yes; then
+      with_gnu_ld=no
+    fi
+    ;;
+  interix*)
+    # we just hope/assume this is gcc and not c89 (= MSVC++)
+    with_gnu_ld=yes
+    ;;
+  openbsd*)
+    with_gnu_ld=no
+    ;;
+  linux* | k*bsd*-gnu | gnu*)
+    _LT_TAGVAR(link_all_deplibs, $1)=no
+    ;;
+  esac
+
+  _LT_TAGVAR(ld_shlibs, $1)=yes
+
+  # On some targets, GNU ld is compatible enough with the native linker
+  # that we're better off using the native interface for both.
+  lt_use_gnu_ld_interface=no
+  if test "$with_gnu_ld" = yes; then
+    case $host_os in
+      aix*)
+	# The AIX port of GNU ld has always aspired to compatibility
+	# with the native linker.  However, as the warning in the GNU ld
+	# block says, versions before 2.19.5* couldn't really create working
+	# shared libraries, regardless of the interface used.
+	case `$LD -v 2>&1` in
+	  *\ \(GNU\ Binutils\)\ 2.19.5*) ;;
+	  *\ \(GNU\ Binutils\)\ 2.[[2-9]]*) ;;
+	  *\ \(GNU\ Binutils\)\ [[3-9]]*) ;;
+	  *)
+	    lt_use_gnu_ld_interface=yes
+	    ;;
+	esac
+	;;
+      *)
+	lt_use_gnu_ld_interface=yes
+	;;
+    esac
+  fi
+
+  if test "$lt_use_gnu_ld_interface" = yes; then
+    # If archive_cmds runs LD, not CC, wlarc should be empty
+    wlarc='${wl}'
+
+    # Set some defaults for GNU ld with shared library support. These
+    # are reset later if shared libraries are not supported. Putting them
+    # here allows them to be overridden if necessary.
+    runpath_var=LD_RUN_PATH
+    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
+    # ancient GNU ld didn't support --whole-archive et. al.
+    if $LD --help 2>&1 | $GREP 'no-whole-archive' > /dev/null; then
+      _LT_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
+    else
+      _LT_TAGVAR(whole_archive_flag_spec, $1)=
+    fi
+    supports_anon_versioning=no
+    case `$LD -v 2>&1` in
+      *GNU\ gold*) supports_anon_versioning=yes ;;
+      *\ [[01]].* | *\ 2.[[0-9]].* | *\ 2.10.*) ;; # catch versions < 2.11
+      *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ...
+      *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ...
+      *\ 2.11.*) ;; # other 2.11 versions
+      *) supports_anon_versioning=yes ;;
+    esac
+
+    # See if GNU ld supports shared libraries.
+    case $host_os in
+    aix[[3-9]]*)
+      # On AIX/PPC, the GNU linker is very broken
+      if test "$host_cpu" != ia64; then
+	_LT_TAGVAR(ld_shlibs, $1)=no
+	cat <<_LT_EOF 1>&2
+
+*** Warning: the GNU linker, at least up to release 2.19, is reported
+*** to be unable to reliably create shared libraries on AIX.
+*** Therefore, libtool is disabling shared libraries support.  If you
+*** really care for shared libraries, you may want to install binutils
+*** 2.20 or above, or modify your PATH so that a non-GNU linker is found.
+*** You will then need to restart the configuration process.
+
+_LT_EOF
+      fi
+      ;;
+
+    amigaos*)
+      case $host_cpu in
+      powerpc)
+            # see comment about AmigaOS4 .so support
+            _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+            _LT_TAGVAR(archive_expsym_cmds, $1)=''
+        ;;
+      m68k)
+            _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)'
+            _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+            _LT_TAGVAR(hardcode_minus_L, $1)=yes
+        ;;
+      esac
+      ;;
+
+    beos*)
+      if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
+	_LT_TAGVAR(allow_undefined_flag, $1)=unsupported
+	# Joseph Beckenbach <jrb3 at best.com> says some releases of gcc
+	# support --undefined.  This deserves some investigation.  FIXME
+	_LT_TAGVAR(archive_cmds, $1)='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+      else
+	_LT_TAGVAR(ld_shlibs, $1)=no
+      fi
+      ;;
+
+    cygwin* | mingw* | pw32* | cegcc*)
+      # _LT_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless,
+      # as there is no search path for DLLs.
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-all-symbols'
+      _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
+      _LT_TAGVAR(always_export_symbols, $1)=no
+      _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
+      _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1 DATA/;s/^.*[[ ]]__nm__\([[^ ]]*\)[[ ]][[^ ]]*/\1 DATA/;/^I[[ ]]/d;/^[[AITW]][[ ]]/s/.* //'\'' | sort | uniq > $export_symbols'
+      _LT_TAGVAR(exclude_expsyms, $1)=['[_]+GLOBAL_OFFSET_TABLE_|[_]+GLOBAL__[FID]_.*|[_]+head_[A-Za-z0-9_]+_dll|[A-Za-z0-9_]+_dll_iname']
+
+      if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then
+        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+	# If the export-symbols file already is a .def file (1st line
+	# is EXPORTS), use it as is; otherwise, prepend...
+	_LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
+	  cp $export_symbols $output_objdir/$soname.def;
+	else
+	  echo EXPORTS > $output_objdir/$soname.def;
+	  cat $export_symbols >> $output_objdir/$soname.def;
+	fi~
+	$CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+      else
+	_LT_TAGVAR(ld_shlibs, $1)=no
+      fi
+      ;;
+
+    haiku*)
+      _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+      _LT_TAGVAR(link_all_deplibs, $1)=yes
+      ;;
+
+    interix[[3-9]]*)
+      _LT_TAGVAR(hardcode_direct, $1)=no
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+      # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc.
+      # Instead, shared libraries are loaded at an image base (0x10000000 by
+      # default) and relocated if they conflict, which is a slow very memory
+      # consuming and fragmenting process.  To avoid this, we pick a random,
+      # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link
+      # time.  Moving up from 0x10000000 also allows more sbrk(2) space.
+      _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
+      _LT_TAGVAR(archive_expsym_cmds, $1)='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
+      ;;
+
+    gnu* | linux* | tpf* | k*bsd*-gnu | kopensolaris*-gnu)
+      tmp_diet=no
+      if test "$host_os" = linux-dietlibc; then
+	case $cc_basename in
+	  diet\ *) tmp_diet=yes;;	# linux-dietlibc with static linking (!diet-dyn)
+	esac
+      fi
+      if $LD --help 2>&1 | $EGREP ': supported targets:.* elf' > /dev/null \
+	 && test "$tmp_diet" = no
+      then
+	tmp_addflag=' $pic_flag'
+	tmp_sharedflag='-shared'
+	case $cc_basename,$host_cpu in
+        pgcc*)				# Portland Group C compiler
+	  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
+	  tmp_addflag=' $pic_flag'
+	  ;;
+	pgf77* | pgf90* | pgf95* | pgfortran*)
+					# Portland Group f77 and f90 compilers
+	  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
+	  tmp_addflag=' $pic_flag -Mnomain' ;;
+	ecc*,ia64* | icc*,ia64*)	# Intel C compiler on ia64
+	  tmp_addflag=' -i_dynamic' ;;
+	efc*,ia64* | ifort*,ia64*)	# Intel Fortran compiler on ia64
+	  tmp_addflag=' -i_dynamic -nofor_main' ;;
+	ifc* | ifort*)			# Intel Fortran compiler
+	  tmp_addflag=' -nofor_main' ;;
+	lf95*)				# Lahey Fortran 8.1
+	  _LT_TAGVAR(whole_archive_flag_spec, $1)=
+	  tmp_sharedflag='--shared' ;;
+	xl[[cC]]* | bgxl[[cC]]* | mpixl[[cC]]*) # IBM XL C 8.0 on PPC (deal with xlf below)
+	  tmp_sharedflag='-qmkshrobj'
+	  tmp_addflag= ;;
+	nvcc*)	# Cuda Compiler Driver 2.2
+	  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
+	  _LT_TAGVAR(compiler_needs_object, $1)=yes
+	  ;;
+	esac
+	case `$CC -V 2>&1 | sed 5q` in
+	*Sun\ C*)			# Sun C 5.9
+	  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
+	  _LT_TAGVAR(compiler_needs_object, $1)=yes
+	  tmp_sharedflag='-G' ;;
+	*Sun\ F*)			# Sun Fortran 8.3
+	  tmp_sharedflag='-G' ;;
+	esac
+	_LT_TAGVAR(archive_cmds, $1)='$CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+
+        if test "x$supports_anon_versioning" = xyes; then
+          _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~
+	    cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
+	    echo "local: *; };" >> $output_objdir/$libname.ver~
+	    $CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib'
+        fi
+
+	case $cc_basename in
+	xlf* | bgf* | bgxlf* | mpixlf*)
+	  # IBM XL Fortran 10.1 on PPC cannot create shared libs itself
+	  _LT_TAGVAR(whole_archive_flag_spec, $1)='--whole-archive$convenience --no-whole-archive'
+	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+	  _LT_TAGVAR(archive_cmds, $1)='$LD -shared $libobjs $deplibs $linker_flags -soname $soname -o $lib'
+	  if test "x$supports_anon_versioning" = xyes; then
+	    _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~
+	      cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
+	      echo "local: *; };" >> $output_objdir/$libname.ver~
+	      $LD -shared $libobjs $deplibs $linker_flags -soname $soname -version-script $output_objdir/$libname.ver -o $lib'
+	  fi
+	  ;;
+	esac
+      else
+        _LT_TAGVAR(ld_shlibs, $1)=no
+      fi
+      ;;
+
+    netbsd* | netbsdelf*-gnu)
+      if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
+	_LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib'
+	wlarc=
+      else
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+      fi
+      ;;
+
+    solaris*)
+      if $LD -v 2>&1 | $GREP 'BFD 2\.8' > /dev/null; then
+	_LT_TAGVAR(ld_shlibs, $1)=no
+	cat <<_LT_EOF 1>&2
+
+*** Warning: The releases 2.8.* of the GNU linker cannot reliably
+*** create shared libraries on Solaris systems.  Therefore, libtool
+*** is disabling shared libraries support.  We urge you to upgrade GNU
+*** binutils to release 2.9.1 or newer.  Another option is to modify
+*** your PATH or compiler configuration so that the native linker is
+*** used, and then restart.
+
+_LT_EOF
+      elif $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+      else
+	_LT_TAGVAR(ld_shlibs, $1)=no
+      fi
+      ;;
+
+    sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX*)
+      case `$LD -v 2>&1` in
+        *\ [[01]].* | *\ 2.[[0-9]].* | *\ 2.1[[0-5]].*)
+	_LT_TAGVAR(ld_shlibs, $1)=no
+	cat <<_LT_EOF 1>&2
+
+*** Warning: Releases of the GNU linker prior to 2.16.91.0.3 can not
+*** reliably create shared libraries on SCO systems.  Therefore, libtool
+*** is disabling shared libraries support.  We urge you to upgrade GNU
+*** binutils to release 2.16.91.0.3 or newer.  Another option is to modify
+*** your PATH or compiler configuration so that the native linker is
+*** used, and then restart.
+
+_LT_EOF
+	;;
+	*)
+	  # For security reasons, it is highly recommended that you always
+	  # use absolute paths for naming shared libraries, and exclude the
+	  # DT_RUNPATH tag from executables and libraries.  But doing so
+	  # requires that you compile everything twice, which is a pain.
+	  if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+	    _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+	  else
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	  fi
+	;;
+      esac
+      ;;
+
+    sunos4*)
+      _LT_TAGVAR(archive_cmds, $1)='$LD -assert pure-text -Bshareable -o $lib $libobjs $deplibs $linker_flags'
+      wlarc=
+      _LT_TAGVAR(hardcode_direct, $1)=yes
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    *)
+      if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+      else
+	_LT_TAGVAR(ld_shlibs, $1)=no
+      fi
+      ;;
+    esac
+
+    if test "$_LT_TAGVAR(ld_shlibs, $1)" = no; then
+      runpath_var=
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
+      _LT_TAGVAR(export_dynamic_flag_spec, $1)=
+      _LT_TAGVAR(whole_archive_flag_spec, $1)=
+    fi
+  else
+    # PORTME fill in a description of your system's linker (not GNU ld)
+    case $host_os in
+    aix3*)
+      _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
+      _LT_TAGVAR(always_export_symbols, $1)=yes
+      _LT_TAGVAR(archive_expsym_cmds, $1)='$LD -o $output_objdir/$soname $libobjs $deplibs $linker_flags -bE:$export_symbols -T512 -H512 -bM:SRE~$AR $AR_FLAGS $lib $output_objdir/$soname'
+      # Note: this linker hardcodes the directories in LIBPATH if there
+      # are no directories specified by -L.
+      _LT_TAGVAR(hardcode_minus_L, $1)=yes
+      if test "$GCC" = yes && test -z "$lt_prog_compiler_static"; then
+	# Neither direct hardcoding nor static linking is supported with a
+	# broken collect2.
+	_LT_TAGVAR(hardcode_direct, $1)=unsupported
+      fi
+      ;;
+
+    aix[[4-9]]*)
+      if test "$host_cpu" = ia64; then
+	# On IA64, the linker does run time linking by default, so we don't
+	# have to do anything special.
+	aix_use_runtimelinking=no
+	exp_sym_flag='-Bexport'
+	no_entry_flag=""
+      else
+	# If we're using GNU nm, then we don't want the "-C" option.
+	# -C means demangle to AIX nm, but means don't demangle with GNU nm
+	# Also, AIX nm treats weak defined symbols like other global
+	# defined symbols, whereas GNU nm marks them as "W".
+	if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then
+	  _LT_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
+	else
+	  _LT_TAGVAR(export_symbols_cmds, $1)='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
+	fi
+	aix_use_runtimelinking=no
+
+	# Test if we are trying to use run time linking or normal
+	# AIX style linking. If -brtl is somewhere in LDFLAGS, we
+	# need to do runtime linking.
+	case $host_os in aix4.[[23]]|aix4.[[23]].*|aix[[5-9]]*)
+	  for ld_flag in $LDFLAGS; do
+	  if (test $ld_flag = "-brtl" || test $ld_flag = "-Wl,-brtl"); then
+	    aix_use_runtimelinking=yes
+	    break
+	  fi
+	  done
+	  ;;
+	esac
+
+	exp_sym_flag='-bexport'
+	no_entry_flag='-bnoentry'
+      fi
+
+      # When large executables or shared objects are built, AIX ld can
+      # have problems creating the table of contents.  If linking a library
+      # or program results in "error TOC overflow" add -mminimal-toc to
+      # CXXFLAGS/CFLAGS for g++/gcc.  In the cases where that is not
+      # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS.
+
+      _LT_TAGVAR(archive_cmds, $1)=''
+      _LT_TAGVAR(hardcode_direct, $1)=yes
+      _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
+      _LT_TAGVAR(hardcode_libdir_separator, $1)=':'
+      _LT_TAGVAR(link_all_deplibs, $1)=yes
+      _LT_TAGVAR(file_list_spec, $1)='${wl}-f,'
+
+      if test "$GCC" = yes; then
+	case $host_os in aix4.[[012]]|aix4.[[012]].*)
+	# We only want to do this on AIX 4.2 and lower, the check
+	# below for broken collect2 doesn't work under 4.3+
+	  collect2name=`${CC} -print-prog-name=collect2`
+	  if test -f "$collect2name" &&
+	   strings "$collect2name" | $GREP resolve_lib_name >/dev/null
+	  then
+	  # We have reworked collect2
+	  :
+	  else
+	  # We have old collect2
+	  _LT_TAGVAR(hardcode_direct, $1)=unsupported
+	  # It fails to find uninstalled libraries when the uninstalled
+	  # path is not listed in the libpath.  Setting hardcode_minus_L
+	  # to unsupported forces relinking
+	  _LT_TAGVAR(hardcode_minus_L, $1)=yes
+	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+	  _LT_TAGVAR(hardcode_libdir_separator, $1)=
+	  fi
+	  ;;
+	esac
+	shared_flag='-shared'
+	if test "$aix_use_runtimelinking" = yes; then
+	  shared_flag="$shared_flag "'${wl}-G'
+	fi
+	_LT_TAGVAR(link_all_deplibs, $1)=no
+      else
+	# not using gcc
+	if test "$host_cpu" = ia64; then
+	# VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release
+	# chokes on -Wl,-G. The following line is correct:
+	  shared_flag='-G'
+	else
+	  if test "$aix_use_runtimelinking" = yes; then
+	    shared_flag='${wl}-G'
+	  else
+	    shared_flag='${wl}-bM:SRE'
+	  fi
+	fi
+      fi
+
+      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-bexpall'
+      # It seems that -bexpall does not export symbols beginning with
+      # underscore (_), so it is better to generate a list of symbols to export.
+      _LT_TAGVAR(always_export_symbols, $1)=yes
+      if test "$aix_use_runtimelinking" = yes; then
+	# Warning - without using the other runtime loading flags (-brtl),
+	# -berok will link without error, but may produce a broken library.
+	_LT_TAGVAR(allow_undefined_flag, $1)='-berok'
+        # Determine the default libpath from the value encoded in an
+        # empty executable.
+        _LT_SYS_MODULE_PATH_AIX([$1])
+        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
+        _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then func_echo_all "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag"
+      else
+	if test "$host_cpu" = ia64; then
+	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $libdir:/usr/lib:/lib'
+	  _LT_TAGVAR(allow_undefined_flag, $1)="-z nodefs"
+	  _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols"
+	else
+	 # Determine the default libpath from the value encoded in an
+	 # empty executable.
+	 _LT_SYS_MODULE_PATH_AIX([$1])
+	 _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
+	  # Warning - without using the other run time loading flags,
+	  # -berok will link without error, but may produce a broken library.
+	  _LT_TAGVAR(no_undefined_flag, $1)=' ${wl}-bernotok'
+	  _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-berok'
+	  if test "$with_gnu_ld" = yes; then
+	    # We only use this code for GNU lds that support --whole-archive.
+	    _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive$convenience ${wl}--no-whole-archive'
+	  else
+	    # Exported symbols can be pulled into shared objects from archives
+	    _LT_TAGVAR(whole_archive_flag_spec, $1)='$convenience'
+	  fi
+	  _LT_TAGVAR(archive_cmds_need_lc, $1)=yes
+	  # This is similar to how AIX traditionally builds its shared libraries.
+	  _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname'
+	fi
+      fi
+      ;;
+
+    amigaos*)
+      case $host_cpu in
+      powerpc)
+            # see comment about AmigaOS4 .so support
+            _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+            _LT_TAGVAR(archive_expsym_cmds, $1)=''
+        ;;
+      m68k)
+            _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)'
+            _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+            _LT_TAGVAR(hardcode_minus_L, $1)=yes
+        ;;
+      esac
+      ;;
+
+    bsdi[[45]]*)
+      _LT_TAGVAR(export_dynamic_flag_spec, $1)=-rdynamic
+      ;;
+
+    cygwin* | mingw* | pw32* | cegcc*)
+      # When not using gcc, we currently assume that we are using
+      # Microsoft Visual C++.
+      # hardcode_libdir_flag_spec is actually meaningless, as there is
+      # no search path for DLLs.
+      case $cc_basename in
+      cl*)
+	# Native MSVC
+	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)=' '
+	_LT_TAGVAR(allow_undefined_flag, $1)=unsupported
+	_LT_TAGVAR(always_export_symbols, $1)=yes
+	_LT_TAGVAR(file_list_spec, $1)='@'
+	# Tell ltmain to make .lib files, not .a files.
+	libext=lib
+	# Tell ltmain to make .dll files, not .so files.
+	shrext_cmds=".dll"
+	# FIXME: Setting linknames here is a bad hack.
+	_LT_TAGVAR(archive_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-dll~linknames='
+	_LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
+	    sed -n -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' -e '1\\\!p' < $export_symbols > $output_objdir/$soname.exp;
+	  else
+	    sed -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' < $export_symbols > $output_objdir/$soname.exp;
+	  fi~
+	  $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~
+	  linknames='
+	# The linker will not automatically build a static lib if we build a DLL.
+	# _LT_TAGVAR(old_archive_from_new_cmds, $1)='true'
+	_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
+	_LT_TAGVAR(exclude_expsyms, $1)='_NULL_IMPORT_DESCRIPTOR|_IMPORT_DESCRIPTOR_.*'
+	_LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1,DATA/'\'' | $SED -e '\''/^[[AITW]][[ ]]/s/.*[[ ]]//'\'' | sort | uniq > $export_symbols'
+	# Don't use ranlib
+	_LT_TAGVAR(old_postinstall_cmds, $1)='chmod 644 $oldlib'
+	_LT_TAGVAR(postlink_cmds, $1)='lt_outputfile="@OUTPUT@"~
+	  lt_tool_outputfile="@TOOL_OUTPUT@"~
+	  case $lt_outputfile in
+	    *.exe|*.EXE) ;;
+	    *)
+	      lt_outputfile="$lt_outputfile.exe"
+	      lt_tool_outputfile="$lt_tool_outputfile.exe"
+	      ;;
+	  esac~
+	  if test "$MANIFEST_TOOL" != ":" && test -f "$lt_outputfile.manifest"; then
+	    $MANIFEST_TOOL -manifest "$lt_tool_outputfile.manifest" -outputresource:"$lt_tool_outputfile" || exit 1;
+	    $RM "$lt_outputfile.manifest";
+	  fi'
+	;;
+      *)
+	# Assume MSVC wrapper
+	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)=' '
+	_LT_TAGVAR(allow_undefined_flag, $1)=unsupported
+	# Tell ltmain to make .lib files, not .a files.
+	libext=lib
+	# Tell ltmain to make .dll files, not .so files.
+	shrext_cmds=".dll"
+	# FIXME: Setting linknames here is a bad hack.
+	_LT_TAGVAR(archive_cmds, $1)='$CC -o $lib $libobjs $compiler_flags `func_echo_all "$deplibs" | $SED '\''s/ -lc$//'\''` -link -dll~linknames='
+	# The linker will automatically build a .lib file if we build a DLL.
+	_LT_TAGVAR(old_archive_from_new_cmds, $1)='true'
+	# FIXME: Should let the user specify the lib program.
+	_LT_TAGVAR(old_archive_cmds, $1)='lib -OUT:$oldlib$oldobjs$old_deplibs'
+	_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
+	;;
+      esac
+      ;;
+
+    darwin* | rhapsody*)
+      _LT_DARWIN_LINKER_FEATURES($1)
+      ;;
+
+    dgux*)
+      _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor
+    # support.  Future versions do this automatically, but an explicit c++rt0.o
+    # does not break anything, and helps significantly (at the cost of a little
+    # extra space).
+    freebsd2.2*)
+      _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags /usr/lib/c++rt0.o'
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+      _LT_TAGVAR(hardcode_direct, $1)=yes
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    # Unfortunately, older versions of FreeBSD 2 do not have this feature.
+    freebsd2.*)
+      _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'
+      _LT_TAGVAR(hardcode_direct, $1)=yes
+      _LT_TAGVAR(hardcode_minus_L, $1)=yes
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    # FreeBSD 3 and greater uses gcc -shared to do shared libraries.
+    freebsd* | dragonfly*)
+      _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+      _LT_TAGVAR(hardcode_direct, $1)=yes
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    hpux9*)
+      if test "$GCC" = yes; then
+	_LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -shared $pic_flag ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+      else
+	_LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+      fi
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
+      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+      _LT_TAGVAR(hardcode_direct, $1)=yes
+
+      # hardcode_minus_L: Not really in the search PATH,
+      # but as the default location of the library.
+      _LT_TAGVAR(hardcode_minus_L, $1)=yes
+      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+      ;;
+
+    hpux10*)
+      if test "$GCC" = yes && test "$with_gnu_ld" = no; then
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
+      else
+	_LT_TAGVAR(archive_cmds, $1)='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags'
+      fi
+      if test "$with_gnu_ld" = no; then
+	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
+	_LT_TAGVAR(hardcode_libdir_separator, $1)=:
+	_LT_TAGVAR(hardcode_direct, $1)=yes
+	_LT_TAGVAR(hardcode_direct_absolute, $1)=yes
+	_LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+	# hardcode_minus_L: Not really in the search PATH,
+	# but as the default location of the library.
+	_LT_TAGVAR(hardcode_minus_L, $1)=yes
+      fi
+      ;;
+
+    hpux11*)
+      if test "$GCC" = yes && test "$with_gnu_ld" = no; then
+	case $host_cpu in
+	hppa*64*)
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
+	  ;;
+	ia64*)
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
+	  ;;
+	*)
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
+	  ;;
+	esac
+      else
+	case $host_cpu in
+	hppa*64*)
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
+	  ;;
+	ia64*)
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
+	  ;;
+	*)
+	m4_if($1, [], [
+	  # Older versions of the 11.00 compiler do not understand -b yet
+	  # (HP92453-01 A.11.01.20 doesn't, HP92453-01 B.11.X.35175-35176.GP does)
+	  _LT_LINKER_OPTION([if $CC understands -b],
+	    _LT_TAGVAR(lt_cv_prog_compiler__b, $1), [-b],
+	    [_LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'],
+	    [_LT_TAGVAR(archive_cmds, $1)='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags'])],
+	  [_LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'])
+	  ;;
+	esac
+      fi
+      if test "$with_gnu_ld" = no; then
+	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
+	_LT_TAGVAR(hardcode_libdir_separator, $1)=:
+
+	case $host_cpu in
+	hppa*64*|ia64*)
+	  _LT_TAGVAR(hardcode_direct, $1)=no
+	  _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+	  ;;
+	*)
+	  _LT_TAGVAR(hardcode_direct, $1)=yes
+	  _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
+	  _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+
+	  # hardcode_minus_L: Not really in the search PATH,
+	  # but as the default location of the library.
+	  _LT_TAGVAR(hardcode_minus_L, $1)=yes
+	  ;;
+	esac
+      fi
+      ;;
+
+    irix5* | irix6* | nonstopux*)
+      if test "$GCC" = yes; then
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+	# Try to use the -exported_symbol ld option, if it does not
+	# work, assume that -exports_file does not work either and
+	# implicitly export all symbols.
+	# This should be the same for all languages, so no per-tag cache variable.
+	AC_CACHE_CHECK([whether the $host_os linker accepts -exported_symbol],
+	  [lt_cv_irix_exported_symbol],
+	  [save_LDFLAGS="$LDFLAGS"
+	   LDFLAGS="$LDFLAGS -shared ${wl}-exported_symbol ${wl}foo ${wl}-update_registry ${wl}/dev/null"
+	   AC_LINK_IFELSE(
+	     [AC_LANG_SOURCE(
+	        [AC_LANG_CASE([C], [[int foo (void) { return 0; }]],
+			      [C++], [[int foo (void) { return 0; }]],
+			      [Fortran 77], [[
+      subroutine foo
+      end]],
+			      [Fortran], [[
+      subroutine foo
+      end]])])],
+	      [lt_cv_irix_exported_symbol=yes],
+	      [lt_cv_irix_exported_symbol=no])
+           LDFLAGS="$save_LDFLAGS"])
+	if test "$lt_cv_irix_exported_symbol" = yes; then
+          _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations ${wl}-exports_file ${wl}$export_symbols -o $lib'
+	fi
+      else
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -exports_file $export_symbols -o $lib'
+      fi
+      _LT_TAGVAR(archive_cmds_need_lc, $1)='no'
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+      _LT_TAGVAR(inherit_rpath, $1)=yes
+      _LT_TAGVAR(link_all_deplibs, $1)=yes
+      ;;
+
+    netbsd* | netbsdelf*-gnu)
+      if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
+	_LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'  # a.out
+      else
+	_LT_TAGVAR(archive_cmds, $1)='$LD -shared -o $lib $libobjs $deplibs $linker_flags'      # ELF
+      fi
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+      _LT_TAGVAR(hardcode_direct, $1)=yes
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    newsos6)
+      _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+      _LT_TAGVAR(hardcode_direct, $1)=yes
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    *nto* | *qnx*)
+      ;;
+
+    openbsd*)
+      if test -f /usr/libexec/ld.so; then
+	_LT_TAGVAR(hardcode_direct, $1)=yes
+	_LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+	_LT_TAGVAR(hardcode_direct_absolute, $1)=yes
+	if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
+	  _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-retain-symbols-file,$export_symbols'
+	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+	  _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+	else
+	  case $host_os in
+	   openbsd[[01]].* | openbsd2.[[0-7]] | openbsd2.[[0-7]].*)
+	     _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'
+	     _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+	     ;;
+	   *)
+	     _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
+	     _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+	     ;;
+	  esac
+	fi
+      else
+	_LT_TAGVAR(ld_shlibs, $1)=no
+      fi
+      ;;
+
+    os2*)
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+      _LT_TAGVAR(hardcode_minus_L, $1)=yes
+      _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
+      _LT_TAGVAR(archive_cmds, $1)='$ECHO "LIBRARY $libname INITINSTANCE" > $output_objdir/$libname.def~$ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~echo DATA >> $output_objdir/$libname.def~echo " SINGLE NONSHARED" >> $output_objdir/$libname.def~echo EXPORTS >> $output_objdir/$libname.def~emxexp $libobjs >> $output_objdir/$libname.def~$CC -Zdll -Zcrtdll -o $lib $libobjs $deplibs $compiler_flags $output_objdir/$libname.def'
+      _LT_TAGVAR(old_archive_from_new_cmds, $1)='emximp -o $output_objdir/$libname.a $output_objdir/$libname.def'
+      ;;
+
+    osf3*)
+      if test "$GCC" = yes; then
+	_LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+      else
+	_LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*'
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
+      fi
+      _LT_TAGVAR(archive_cmds_need_lc, $1)='no'
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+      ;;
+
+    osf4* | osf5*)	# as osf3* with the addition of -msym flag
+      if test "$GCC" = yes; then
+	_LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $pic_flag $libobjs $deplibs $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+      else
+	_LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*'
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -msym -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; printf "%s\\n" "-hidden">> $lib.exp~
+	$CC -shared${allow_undefined_flag} ${wl}-input ${wl}$lib.exp $compiler_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && $ECHO "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib~$RM $lib.exp'
+
+	# Both c and cxx compiler support -rpath directly
+	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir'
+      fi
+      _LT_TAGVAR(archive_cmds_need_lc, $1)='no'
+      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+      ;;
+
+    solaris*)
+      _LT_TAGVAR(no_undefined_flag, $1)=' -z defs'
+      if test "$GCC" = yes; then
+	wlarc='${wl}'
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag ${wl}-z ${wl}text ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
+	  $CC -shared $pic_flag ${wl}-z ${wl}text ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp'
+      else
+	case `$CC -V 2>&1` in
+	*"Compilers 5.0"*)
+	  wlarc=''
+	  _LT_TAGVAR(archive_cmds, $1)='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags'
+	  _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
+	  $LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$RM $lib.exp'
+	  ;;
+	*)
+	  wlarc='${wl}'
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $compiler_flags'
+	  _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
+	  $CC -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp'
+	  ;;
+	esac
+      fi
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      case $host_os in
+      solaris2.[[0-5]] | solaris2.[[0-5]].*) ;;
+      *)
+	# The compiler driver will combine and reorder linker options,
+	# but understands `-z linker_flag'.  GCC discards it without `$wl',
+	# but is careful enough not to reorder.
+	# Supported since Solaris 2.6 (maybe 2.5.1?)
+	if test "$GCC" = yes; then
+	  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract'
+	else
+	  _LT_TAGVAR(whole_archive_flag_spec, $1)='-z allextract$convenience -z defaultextract'
+	fi
+	;;
+      esac
+      _LT_TAGVAR(link_all_deplibs, $1)=yes
+      ;;
+
+    sunos4*)
+      if test "x$host_vendor" = xsequent; then
+	# Use $CC to link under sequent, because it throws in some extra .o
+	# files that make .init and .fini sections work.
+	_LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h $soname -o $lib $libobjs $deplibs $compiler_flags'
+      else
+	_LT_TAGVAR(archive_cmds, $1)='$LD -assert pure-text -Bstatic -o $lib $libobjs $deplibs $linker_flags'
+      fi
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+      _LT_TAGVAR(hardcode_direct, $1)=yes
+      _LT_TAGVAR(hardcode_minus_L, $1)=yes
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    sysv4)
+      case $host_vendor in
+	sni)
+	  _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+	  _LT_TAGVAR(hardcode_direct, $1)=yes # is this really true???
+	;;
+	siemens)
+	  ## LD is ld it makes a PLAMLIB
+	  ## CC just makes a GrossModule.
+	  _LT_TAGVAR(archive_cmds, $1)='$LD -G -o $lib $libobjs $deplibs $linker_flags'
+	  _LT_TAGVAR(reload_cmds, $1)='$CC -r -o $output$reload_objs'
+	  _LT_TAGVAR(hardcode_direct, $1)=no
+        ;;
+	motorola)
+	  _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+	  _LT_TAGVAR(hardcode_direct, $1)=no #Motorola manual says yes, but my tests say they lie
+	;;
+      esac
+      runpath_var='LD_RUN_PATH'
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    sysv4.3*)
+      _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      _LT_TAGVAR(export_dynamic_flag_spec, $1)='-Bexport'
+      ;;
+
+    sysv4*MP*)
+      if test -d /usr/nec; then
+	_LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+	_LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+	runpath_var=LD_RUN_PATH
+	hardcode_runpath_var=yes
+	_LT_TAGVAR(ld_shlibs, $1)=yes
+      fi
+      ;;
+
+    sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[[01]].[[10]]* | unixware7* | sco3.2v5.0.[[024]]*)
+      _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
+      _LT_TAGVAR(archive_cmds_need_lc, $1)=no
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      runpath_var='LD_RUN_PATH'
+
+      if test "$GCC" = yes; then
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+      else
+	_LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+      fi
+      ;;
+
+    sysv5* | sco3.2v5* | sco5v6*)
+      # Note: We can NOT use -z defs as we might desire, because we do not
+      # link with -lc, and that would cause any symbols used from libc to
+      # always be unresolved, which means just about no library would
+      # ever link correctly.  If we're not using GNU ld we use -z text
+      # though, which does catch some bad symbols but isn't as heavy-handed
+      # as -z defs.
+      _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
+      _LT_TAGVAR(allow_undefined_flag, $1)='${wl}-z,nodefs'
+      _LT_TAGVAR(archive_cmds_need_lc, $1)=no
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R,$libdir'
+      _LT_TAGVAR(hardcode_libdir_separator, $1)=':'
+      _LT_TAGVAR(link_all_deplibs, $1)=yes
+      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Bexport'
+      runpath_var='LD_RUN_PATH'
+
+      if test "$GCC" = yes; then
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+      else
+	_LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+      fi
+      ;;
+
+    uts4*)
+      _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    *)
+      _LT_TAGVAR(ld_shlibs, $1)=no
+      ;;
+    esac
+
+    if test x$host_vendor = xsni; then
+      case $host in
+      sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*)
+	_LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Blargedynsym'
+	;;
+      esac
+    fi
+  fi
+])
+AC_MSG_RESULT([$_LT_TAGVAR(ld_shlibs, $1)])
+test "$_LT_TAGVAR(ld_shlibs, $1)" = no && can_build_shared=no
+
+_LT_TAGVAR(with_gnu_ld, $1)=$with_gnu_ld
+
+_LT_DECL([], [libext], [0], [Old archive suffix (normally "a")])dnl
+_LT_DECL([], [shrext_cmds], [1], [Shared library suffix (normally ".so")])dnl
+_LT_DECL([], [extract_expsyms_cmds], [2],
+    [The commands to extract the exported symbol list from a shared archive])
+
+#
+# Do we need to explicitly link libc?
+#
+case "x$_LT_TAGVAR(archive_cmds_need_lc, $1)" in
+x|xyes)
+  # Assume -lc should be added
+  _LT_TAGVAR(archive_cmds_need_lc, $1)=yes
+
+  if test "$enable_shared" = yes && test "$GCC" = yes; then
+    case $_LT_TAGVAR(archive_cmds, $1) in
+    *'~'*)
+      # FIXME: we may have to deal with multi-command sequences.
+      ;;
+    '$CC '*)
+      # Test whether the compiler implicitly links with -lc since on some
+      # systems, -lgcc has to come before -lc. If gcc already passes -lc
+      # to ld, don't add -lc before -lgcc.
+      AC_CACHE_CHECK([whether -lc should be explicitly linked in],
+	[lt_cv_]_LT_TAGVAR(archive_cmds_need_lc, $1),
+	[$RM conftest*
+	echo "$lt_simple_compile_test_code" > conftest.$ac_ext
+
+	if AC_TRY_EVAL(ac_compile) 2>conftest.err; then
+	  soname=conftest
+	  lib=conftest
+	  libobjs=conftest.$ac_objext
+	  deplibs=
+	  wl=$_LT_TAGVAR(lt_prog_compiler_wl, $1)
+	  pic_flag=$_LT_TAGVAR(lt_prog_compiler_pic, $1)
+	  compiler_flags=-v
+	  linker_flags=-v
+	  verstring=
+	  output_objdir=.
+	  libname=conftest
+	  lt_save_allow_undefined_flag=$_LT_TAGVAR(allow_undefined_flag, $1)
+	  _LT_TAGVAR(allow_undefined_flag, $1)=
+	  if AC_TRY_EVAL(_LT_TAGVAR(archive_cmds, $1) 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1)
+	  then
+	    lt_cv_[]_LT_TAGVAR(archive_cmds_need_lc, $1)=no
+	  else
+	    lt_cv_[]_LT_TAGVAR(archive_cmds_need_lc, $1)=yes
+	  fi
+	  _LT_TAGVAR(allow_undefined_flag, $1)=$lt_save_allow_undefined_flag
+	else
+	  cat conftest.err 1>&5
+	fi
+	$RM conftest*
+	])
+      _LT_TAGVAR(archive_cmds_need_lc, $1)=$lt_cv_[]_LT_TAGVAR(archive_cmds_need_lc, $1)
+      ;;
+    esac
+  fi
+  ;;
+esac
+
+_LT_TAGDECL([build_libtool_need_lc], [archive_cmds_need_lc], [0],
+    [Whether or not to add -lc for building shared libraries])
+_LT_TAGDECL([allow_libtool_libs_with_static_runtimes],
+    [enable_shared_with_static_runtimes], [0],
+    [Whether or not to disallow shared libs when runtime libs are static])
+_LT_TAGDECL([], [export_dynamic_flag_spec], [1],
+    [Compiler flag to allow reflexive dlopens])
+_LT_TAGDECL([], [whole_archive_flag_spec], [1],
+    [Compiler flag to generate shared objects directly from archives])
+_LT_TAGDECL([], [compiler_needs_object], [1],
+    [Whether the compiler copes with passing no objects directly])
+_LT_TAGDECL([], [old_archive_from_new_cmds], [2],
+    [Create an old-style archive from a shared archive])
+_LT_TAGDECL([], [old_archive_from_expsyms_cmds], [2],
+    [Create a temporary old-style archive to link instead of a shared archive])
+_LT_TAGDECL([], [archive_cmds], [2], [Commands used to build a shared archive])
+_LT_TAGDECL([], [archive_expsym_cmds], [2])
+_LT_TAGDECL([], [module_cmds], [2],
+    [Commands used to build a loadable module if different from building
+    a shared archive.])
+_LT_TAGDECL([], [module_expsym_cmds], [2])
+_LT_TAGDECL([], [with_gnu_ld], [1],
+    [Whether we are building with GNU ld or not])
+_LT_TAGDECL([], [allow_undefined_flag], [1],
+    [Flag that allows shared libraries with undefined symbols to be built])
+_LT_TAGDECL([], [no_undefined_flag], [1],
+    [Flag that enforces no undefined symbols])
+_LT_TAGDECL([], [hardcode_libdir_flag_spec], [1],
+    [Flag to hardcode $libdir into a binary during linking.
+    This must work even if $libdir does not exist])
+_LT_TAGDECL([], [hardcode_libdir_separator], [1],
+    [Whether we need a single "-rpath" flag with a separated argument])
+_LT_TAGDECL([], [hardcode_direct], [0],
+    [Set to "yes" if using DIR/libNAME${shared_ext} during linking hardcodes
+    DIR into the resulting binary])
+_LT_TAGDECL([], [hardcode_direct_absolute], [0],
+    [Set to "yes" if using DIR/libNAME${shared_ext} during linking hardcodes
+    DIR into the resulting binary and the resulting library dependency is
+    "absolute", i.e impossible to change by setting ${shlibpath_var} if the
+    library is relocated])
+_LT_TAGDECL([], [hardcode_minus_L], [0],
+    [Set to "yes" if using the -LDIR flag during linking hardcodes DIR
+    into the resulting binary])
+_LT_TAGDECL([], [hardcode_shlibpath_var], [0],
+    [Set to "yes" if using SHLIBPATH_VAR=DIR during linking hardcodes DIR
+    into the resulting binary])
+_LT_TAGDECL([], [hardcode_automatic], [0],
+    [Set to "yes" if building a shared library automatically hardcodes DIR
+    into the library and all subsequent libraries and executables linked
+    against it])
+_LT_TAGDECL([], [inherit_rpath], [0],
+    [Set to yes if linker adds runtime paths of dependent libraries
+    to runtime path list])
+_LT_TAGDECL([], [link_all_deplibs], [0],
+    [Whether libtool must link a program against all its dependency libraries])
+_LT_TAGDECL([], [always_export_symbols], [0],
+    [Set to "yes" if exported symbols are required])
+_LT_TAGDECL([], [export_symbols_cmds], [2],
+    [The commands to list exported symbols])
+_LT_TAGDECL([], [exclude_expsyms], [1],
+    [Symbols that should not be listed in the preloaded symbols])
+_LT_TAGDECL([], [include_expsyms], [1],
+    [Symbols that must always be exported])
+_LT_TAGDECL([], [prelink_cmds], [2],
+    [Commands necessary for linking programs (against libraries) with templates])
+_LT_TAGDECL([], [postlink_cmds], [2],
+    [Commands necessary for finishing linking programs])
+_LT_TAGDECL([], [file_list_spec], [1],
+    [Specify filename containing input files])
+dnl FIXME: Not yet implemented
+dnl _LT_TAGDECL([], [thread_safe_flag_spec], [1],
+dnl    [Compiler flag to generate thread safe objects])
+])# _LT_LINKER_SHLIBS
+
+
+# _LT_LANG_C_CONFIG([TAG])
+# ------------------------
+# Ensure that the configuration variables for a C compiler are suitably
+# defined.  These variables are subsequently used by _LT_CONFIG to write
+# the compiler configuration to `libtool'.
+m4_defun([_LT_LANG_C_CONFIG],
+[m4_require([_LT_DECL_EGREP])dnl
+lt_save_CC="$CC"
+AC_LANG_PUSH(C)
+
+# Source file extension for C test sources.
+ac_ext=c
+
+# Object file extension for compiled C test sources.
+objext=o
+_LT_TAGVAR(objext, $1)=$objext
+
+# Code to be used in simple compile tests
+lt_simple_compile_test_code="int some_variable = 0;"
+
+# Code to be used in simple link tests
+lt_simple_link_test_code='int main(){return(0);}'
+
+_LT_TAG_COMPILER
+# Save the default compiler, since it gets overwritten when the other
+# tags are being tested, and _LT_TAGVAR(compiler, []) is a NOP.
+compiler_DEFAULT=$CC
+
+# save warnings/boilerplate of simple test code
+_LT_COMPILER_BOILERPLATE
+_LT_LINKER_BOILERPLATE
+
+if test -n "$compiler"; then
+  _LT_COMPILER_NO_RTTI($1)
+  _LT_COMPILER_PIC($1)
+  _LT_COMPILER_C_O($1)
+  _LT_COMPILER_FILE_LOCKS($1)
+  _LT_LINKER_SHLIBS($1)
+  _LT_SYS_DYNAMIC_LINKER($1)
+  _LT_LINKER_HARDCODE_LIBPATH($1)
+  LT_SYS_DLOPEN_SELF
+  _LT_CMD_STRIPLIB
+
+  # Report which library types will actually be built
+  AC_MSG_CHECKING([if libtool supports shared libraries])
+  AC_MSG_RESULT([$can_build_shared])
+
+  AC_MSG_CHECKING([whether to build shared libraries])
+  test "$can_build_shared" = "no" && enable_shared=no
+
+  # On AIX, shared libraries and static libraries use the same namespace, and
+  # are all built from PIC.
+  case $host_os in
+  aix3*)
+    test "$enable_shared" = yes && enable_static=no
+    if test -n "$RANLIB"; then
+      archive_cmds="$archive_cmds~\$RANLIB \$lib"
+      postinstall_cmds='$RANLIB $lib'
+    fi
+    ;;
+
+  aix[[4-9]]*)
+    if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then
+      test "$enable_shared" = yes && enable_static=no
+    fi
+    ;;
+  esac
+  AC_MSG_RESULT([$enable_shared])
+
+  AC_MSG_CHECKING([whether to build static libraries])
+  # Make sure either enable_shared or enable_static is yes.
+  test "$enable_shared" = yes || enable_static=yes
+  AC_MSG_RESULT([$enable_static])
+
+  _LT_CONFIG($1)
+fi
+AC_LANG_POP
+CC="$lt_save_CC"
+])# _LT_LANG_C_CONFIG
+
+
+# _LT_LANG_CXX_CONFIG([TAG])
+# --------------------------
+# Ensure that the configuration variables for a C++ compiler are suitably
+# defined.  These variables are subsequently used by _LT_CONFIG to write
+# the compiler configuration to `libtool'.
+m4_defun([_LT_LANG_CXX_CONFIG],
+[m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+m4_require([_LT_DECL_EGREP])dnl
+m4_require([_LT_PATH_MANIFEST_TOOL])dnl
+if test -n "$CXX" && ( test "X$CXX" != "Xno" &&
+    ( (test "X$CXX" = "Xg++" && `g++ -v >/dev/null 2>&1` ) ||
+    (test "X$CXX" != "Xg++"))) ; then
+  AC_PROG_CXXCPP
+else
+  _lt_caught_CXX_error=yes
+fi
+
+AC_LANG_PUSH(C++)
+_LT_TAGVAR(archive_cmds_need_lc, $1)=no
+_LT_TAGVAR(allow_undefined_flag, $1)=
+_LT_TAGVAR(always_export_symbols, $1)=no
+_LT_TAGVAR(archive_expsym_cmds, $1)=
+_LT_TAGVAR(compiler_needs_object, $1)=no
+_LT_TAGVAR(export_dynamic_flag_spec, $1)=
+_LT_TAGVAR(hardcode_direct, $1)=no
+_LT_TAGVAR(hardcode_direct_absolute, $1)=no
+_LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
+_LT_TAGVAR(hardcode_libdir_separator, $1)=
+_LT_TAGVAR(hardcode_minus_L, $1)=no
+_LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported
+_LT_TAGVAR(hardcode_automatic, $1)=no
+_LT_TAGVAR(inherit_rpath, $1)=no
+_LT_TAGVAR(module_cmds, $1)=
+_LT_TAGVAR(module_expsym_cmds, $1)=
+_LT_TAGVAR(link_all_deplibs, $1)=unknown
+_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
+_LT_TAGVAR(reload_flag, $1)=$reload_flag
+_LT_TAGVAR(reload_cmds, $1)=$reload_cmds
+_LT_TAGVAR(no_undefined_flag, $1)=
+_LT_TAGVAR(whole_archive_flag_spec, $1)=
+_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no
+
+# Source file extension for C++ test sources.
+ac_ext=cpp
+
+# Object file extension for compiled C++ test sources.
+objext=o
+_LT_TAGVAR(objext, $1)=$objext
+
+# No sense in running all these tests if we already determined that
+# the CXX compiler isn't working.  Some variables (like enable_shared)
+# are currently assumed to apply to all compilers on this platform,
+# and will be corrupted by setting them based on a non-working compiler.
+if test "$_lt_caught_CXX_error" != yes; then
+  # Code to be used in simple compile tests
+  lt_simple_compile_test_code="int some_variable = 0;"
+
+  # Code to be used in simple link tests
+  lt_simple_link_test_code='int main(int, char *[[]]) { return(0); }'
+
+  # ltmain only uses $CC for tagged configurations so make sure $CC is set.
+  _LT_TAG_COMPILER
+
+  # save warnings/boilerplate of simple test code
+  _LT_COMPILER_BOILERPLATE
+  _LT_LINKER_BOILERPLATE
+
+  # Allow CC to be a program name with arguments.
+  lt_save_CC=$CC
+  lt_save_CFLAGS=$CFLAGS
+  lt_save_LD=$LD
+  lt_save_GCC=$GCC
+  GCC=$GXX
+  lt_save_with_gnu_ld=$with_gnu_ld
+  lt_save_path_LD=$lt_cv_path_LD
+  if test -n "${lt_cv_prog_gnu_ldcxx+set}"; then
+    lt_cv_prog_gnu_ld=$lt_cv_prog_gnu_ldcxx
+  else
+    $as_unset lt_cv_prog_gnu_ld
+  fi
+  if test -n "${lt_cv_path_LDCXX+set}"; then
+    lt_cv_path_LD=$lt_cv_path_LDCXX
+  else
+    $as_unset lt_cv_path_LD
+  fi
+  test -z "${LDCXX+set}" || LD=$LDCXX
+  CC=${CXX-"c++"}
+  CFLAGS=$CXXFLAGS
+  compiler=$CC
+  _LT_TAGVAR(compiler, $1)=$CC
+  _LT_CC_BASENAME([$compiler])
+
+  if test -n "$compiler"; then
+    # We don't want -fno-exception when compiling C++ code, so set the
+    # no_builtin_flag separately
+    if test "$GXX" = yes; then
+      _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -fno-builtin'
+    else
+      _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=
+    fi
+
+    if test "$GXX" = yes; then
+      # Set up default GNU C++ configuration
+
+      LT_PATH_LD
+
+      # Check if GNU C++ uses GNU ld as the underlying linker, since the
+      # archiving commands below assume that GNU ld is being used.
+      if test "$with_gnu_ld" = yes; then
+        _LT_TAGVAR(archive_cmds, $1)='$CC $pic_flag -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib'
+        _LT_TAGVAR(archive_expsym_cmds, $1)='$CC $pic_flag -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+
+        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+        _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
+
+        # If archive_cmds runs LD, not CC, wlarc should be empty
+        # XXX I think wlarc can be eliminated in ltcf-cxx, but I need to
+        #     investigate it a little bit more. (MM)
+        wlarc='${wl}'
+
+        # ancient GNU ld didn't support --whole-archive et. al.
+        if eval "`$CC -print-prog-name=ld` --help 2>&1" |
+	  $GREP 'no-whole-archive' > /dev/null; then
+          _LT_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
+        else
+          _LT_TAGVAR(whole_archive_flag_spec, $1)=
+        fi
+      else
+        with_gnu_ld=no
+        wlarc=
+
+        # A generic and very simple default shared library creation
+        # command for GNU C++ for the case where it uses the native
+        # linker, instead of GNU ld.  If possible, this setting should
+        # overridden to take advantage of the native linker features on
+        # the platform it is being used on.
+        _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib'
+      fi
+
+      # Commands to make compiler produce verbose output that lists
+      # what "hidden" libraries, object files and flags are used when
+      # linking a shared library.
+      output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"'
+
+    else
+      GXX=no
+      with_gnu_ld=no
+      wlarc=
+    fi
+
+    # PORTME: fill in a description of your system's C++ link characteristics
+    AC_MSG_CHECKING([whether the $compiler linker ($LD) supports shared libraries])
+    _LT_TAGVAR(ld_shlibs, $1)=yes
+    case $host_os in
+      aix3*)
+        # FIXME: insert proper C++ library support
+        _LT_TAGVAR(ld_shlibs, $1)=no
+        ;;
+      aix[[4-9]]*)
+        if test "$host_cpu" = ia64; then
+          # On IA64, the linker does run time linking by default, so we don't
+          # have to do anything special.
+          aix_use_runtimelinking=no
+          exp_sym_flag='-Bexport'
+          no_entry_flag=""
+        else
+          aix_use_runtimelinking=no
+
+          # Test if we are trying to use run time linking or normal
+          # AIX style linking. If -brtl is somewhere in LDFLAGS, we
+          # need to do runtime linking.
+          case $host_os in aix4.[[23]]|aix4.[[23]].*|aix[[5-9]]*)
+	    for ld_flag in $LDFLAGS; do
+	      case $ld_flag in
+	      *-brtl*)
+	        aix_use_runtimelinking=yes
+	        break
+	        ;;
+	      esac
+	    done
+	    ;;
+          esac
+
+          exp_sym_flag='-bexport'
+          no_entry_flag='-bnoentry'
+        fi
+
+        # When large executables or shared objects are built, AIX ld can
+        # have problems creating the table of contents.  If linking a library
+        # or program results in "error TOC overflow" add -mminimal-toc to
+        # CXXFLAGS/CFLAGS for g++/gcc.  In the cases where that is not
+        # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS.
+
+        _LT_TAGVAR(archive_cmds, $1)=''
+        _LT_TAGVAR(hardcode_direct, $1)=yes
+        _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
+        _LT_TAGVAR(hardcode_libdir_separator, $1)=':'
+        _LT_TAGVAR(link_all_deplibs, $1)=yes
+        _LT_TAGVAR(file_list_spec, $1)='${wl}-f,'
+
+        if test "$GXX" = yes; then
+          case $host_os in aix4.[[012]]|aix4.[[012]].*)
+          # We only want to do this on AIX 4.2 and lower, the check
+          # below for broken collect2 doesn't work under 4.3+
+	  collect2name=`${CC} -print-prog-name=collect2`
+	  if test -f "$collect2name" &&
+	     strings "$collect2name" | $GREP resolve_lib_name >/dev/null
+	  then
+	    # We have reworked collect2
+	    :
+	  else
+	    # We have old collect2
+	    _LT_TAGVAR(hardcode_direct, $1)=unsupported
+	    # It fails to find uninstalled libraries when the uninstalled
+	    # path is not listed in the libpath.  Setting hardcode_minus_L
+	    # to unsupported forces relinking
+	    _LT_TAGVAR(hardcode_minus_L, $1)=yes
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+	    _LT_TAGVAR(hardcode_libdir_separator, $1)=
+	  fi
+          esac
+          shared_flag='-shared'
+	  if test "$aix_use_runtimelinking" = yes; then
+	    shared_flag="$shared_flag "'${wl}-G'
+	  fi
+        else
+          # not using gcc
+          if test "$host_cpu" = ia64; then
+	  # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release
+	  # chokes on -Wl,-G. The following line is correct:
+	  shared_flag='-G'
+          else
+	    if test "$aix_use_runtimelinking" = yes; then
+	      shared_flag='${wl}-G'
+	    else
+	      shared_flag='${wl}-bM:SRE'
+	    fi
+          fi
+        fi
+
+        _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-bexpall'
+        # It seems that -bexpall does not export symbols beginning with
+        # underscore (_), so it is better to generate a list of symbols to
+	# export.
+        _LT_TAGVAR(always_export_symbols, $1)=yes
+        if test "$aix_use_runtimelinking" = yes; then
+          # Warning - without using the other runtime loading flags (-brtl),
+          # -berok will link without error, but may produce a broken library.
+          _LT_TAGVAR(allow_undefined_flag, $1)='-berok'
+          # Determine the default libpath from the value encoded in an empty
+          # executable.
+          _LT_SYS_MODULE_PATH_AIX([$1])
+          _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
+
+          _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then func_echo_all "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag"
+        else
+          if test "$host_cpu" = ia64; then
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $libdir:/usr/lib:/lib'
+	    _LT_TAGVAR(allow_undefined_flag, $1)="-z nodefs"
+	    _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols"
+          else
+	    # Determine the default libpath from the value encoded in an
+	    # empty executable.
+	    _LT_SYS_MODULE_PATH_AIX([$1])
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
+	    # Warning - without using the other run time loading flags,
+	    # -berok will link without error, but may produce a broken library.
+	    _LT_TAGVAR(no_undefined_flag, $1)=' ${wl}-bernotok'
+	    _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-berok'
+	    if test "$with_gnu_ld" = yes; then
+	      # We only use this code for GNU lds that support --whole-archive.
+	      _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive$convenience ${wl}--no-whole-archive'
+	    else
+	      # Exported symbols can be pulled into shared objects from archives
+	      _LT_TAGVAR(whole_archive_flag_spec, $1)='$convenience'
+	    fi
+	    _LT_TAGVAR(archive_cmds_need_lc, $1)=yes
+	    # This is similar to how AIX traditionally builds its shared
+	    # libraries.
+	    _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname'
+          fi
+        fi
+        ;;
+
+      beos*)
+	if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
+	  _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
+	  # Joseph Beckenbach <jrb3 at best.com> says some releases of gcc
+	  # support --undefined.  This deserves some investigation.  FIXME
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+	else
+	  _LT_TAGVAR(ld_shlibs, $1)=no
+	fi
+	;;
+
+      chorus*)
+        case $cc_basename in
+          *)
+	  # FIXME: insert proper C++ library support
+	  _LT_TAGVAR(ld_shlibs, $1)=no
+	  ;;
+        esac
+        ;;
+
+      cygwin* | mingw* | pw32* | cegcc*)
+	case $GXX,$cc_basename in
+	,cl* | no,cl*)
+	  # Native MSVC
+	  # hardcode_libdir_flag_spec is actually meaningless, as there is
+	  # no search path for DLLs.
+	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=' '
+	  _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
+	  _LT_TAGVAR(always_export_symbols, $1)=yes
+	  _LT_TAGVAR(file_list_spec, $1)='@'
+	  # Tell ltmain to make .lib files, not .a files.
+	  libext=lib
+	  # Tell ltmain to make .dll files, not .so files.
+	  shrext_cmds=".dll"
+	  # FIXME: Setting linknames here is a bad hack.
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-dll~linknames='
+	  _LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
+	      $SED -n -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' -e '1\\\!p' < $export_symbols > $output_objdir/$soname.exp;
+	    else
+	      $SED -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' < $export_symbols > $output_objdir/$soname.exp;
+	    fi~
+	    $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~
+	    linknames='
+	  # The linker will not automatically build a static lib if we build a DLL.
+	  # _LT_TAGVAR(old_archive_from_new_cmds, $1)='true'
+	  _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
+	  # Don't use ranlib
+	  _LT_TAGVAR(old_postinstall_cmds, $1)='chmod 644 $oldlib'
+	  _LT_TAGVAR(postlink_cmds, $1)='lt_outputfile="@OUTPUT@"~
+	    lt_tool_outputfile="@TOOL_OUTPUT@"~
+	    case $lt_outputfile in
+	      *.exe|*.EXE) ;;
+	      *)
+		lt_outputfile="$lt_outputfile.exe"
+		lt_tool_outputfile="$lt_tool_outputfile.exe"
+		;;
+	    esac~
+	    func_to_tool_file "$lt_outputfile"~
+	    if test "$MANIFEST_TOOL" != ":" && test -f "$lt_outputfile.manifest"; then
+	      $MANIFEST_TOOL -manifest "$lt_tool_outputfile.manifest" -outputresource:"$lt_tool_outputfile" || exit 1;
+	      $RM "$lt_outputfile.manifest";
+	    fi'
+	  ;;
+	*)
+	  # g++
+	  # _LT_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless,
+	  # as there is no search path for DLLs.
+	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+	  _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-all-symbols'
+	  _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
+	  _LT_TAGVAR(always_export_symbols, $1)=no
+	  _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
+
+	  if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then
+	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+	    # If the export-symbols file already is a .def file (1st line
+	    # is EXPORTS), use it as is; otherwise, prepend...
+	    _LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
+	      cp $export_symbols $output_objdir/$soname.def;
+	    else
+	      echo EXPORTS > $output_objdir/$soname.def;
+	      cat $export_symbols >> $output_objdir/$soname.def;
+	    fi~
+	    $CC -shared -nostdlib $output_objdir/$soname.def $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+	  else
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	  fi
+	  ;;
+	esac
+	;;
+      darwin* | rhapsody*)
+        _LT_DARWIN_LINKER_FEATURES($1)
+	;;
+
+      dgux*)
+        case $cc_basename in
+          ec++*)
+	    # FIXME: insert proper C++ library support
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	    ;;
+          ghcx*)
+	    # Green Hills C++ Compiler
+	    # FIXME: insert proper C++ library support
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	    ;;
+          *)
+	    # FIXME: insert proper C++ library support
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	    ;;
+        esac
+        ;;
+
+      freebsd2.*)
+        # C++ shared libraries reported to be fairly broken before
+	# switch to ELF
+        _LT_TAGVAR(ld_shlibs, $1)=no
+        ;;
+
+      freebsd-elf*)
+        _LT_TAGVAR(archive_cmds_need_lc, $1)=no
+        ;;
+
+      freebsd* | dragonfly*)
+        # FreeBSD 3 and later use GNU C++ and GNU ld with standard ELF
+        # conventions
+        _LT_TAGVAR(ld_shlibs, $1)=yes
+        ;;
+
+      gnu*)
+        ;;
+
+      haiku*)
+        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+        _LT_TAGVAR(link_all_deplibs, $1)=yes
+        ;;
+
+      hpux9*)
+        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
+        _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+        _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+        _LT_TAGVAR(hardcode_direct, $1)=yes
+        _LT_TAGVAR(hardcode_minus_L, $1)=yes # Not in the search PATH,
+				             # but as the default
+				             # location of the library.
+
+        case $cc_basename in
+          CC*)
+            # FIXME: insert proper C++ library support
+            _LT_TAGVAR(ld_shlibs, $1)=no
+            ;;
+          aCC*)
+            _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -b ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+            # Commands to make compiler produce verbose output that lists
+            # what "hidden" libraries, object files and flags are used when
+            # linking a shared library.
+            #
+            # There doesn't appear to be a way to prevent this compiler from
+            # explicitly linking system object files so we need to strip them
+            # from the output so that they don't get included in the library
+            # dependencies.
+            output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $EGREP "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"'
+            ;;
+          *)
+            if test "$GXX" = yes; then
+              _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -shared -nostdlib $pic_flag ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+            else
+              # FIXME: insert proper C++ library support
+              _LT_TAGVAR(ld_shlibs, $1)=no
+            fi
+            ;;
+        esac
+        ;;
+
+      hpux10*|hpux11*)
+        if test $with_gnu_ld = no; then
+	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
+	  _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+
+          case $host_cpu in
+            hppa*64*|ia64*)
+              ;;
+            *)
+	      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+              ;;
+          esac
+        fi
+        case $host_cpu in
+          hppa*64*|ia64*)
+            _LT_TAGVAR(hardcode_direct, $1)=no
+            _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+            ;;
+          *)
+            _LT_TAGVAR(hardcode_direct, $1)=yes
+            _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
+            _LT_TAGVAR(hardcode_minus_L, $1)=yes # Not in the search PATH,
+					         # but as the default
+					         # location of the library.
+            ;;
+        esac
+
+        case $cc_basename in
+          CC*)
+	    # FIXME: insert proper C++ library support
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	    ;;
+          aCC*)
+	    case $host_cpu in
+	      hppa*64*)
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	        ;;
+	      ia64*)
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	        ;;
+	      *)
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	        ;;
+	    esac
+	    # Commands to make compiler produce verbose output that lists
+	    # what "hidden" libraries, object files and flags are used when
+	    # linking a shared library.
+	    #
+	    # There doesn't appear to be a way to prevent this compiler from
+	    # explicitly linking system object files so we need to strip them
+	    # from the output so that they don't get included in the library
+	    # dependencies.
+	    output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $GREP "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"'
+	    ;;
+          *)
+	    if test "$GXX" = yes; then
+	      if test $with_gnu_ld = no; then
+	        case $host_cpu in
+	          hppa*64*)
+	            _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	            ;;
+	          ia64*)
+	            _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $pic_flag ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	            ;;
+	          *)
+	            _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	            ;;
+	        esac
+	      fi
+	    else
+	      # FIXME: insert proper C++ library support
+	      _LT_TAGVAR(ld_shlibs, $1)=no
+	    fi
+	    ;;
+        esac
+        ;;
+
+      interix[[3-9]]*)
+	_LT_TAGVAR(hardcode_direct, $1)=no
+	_LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+	_LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+	# Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc.
+	# Instead, shared libraries are loaded at an image base (0x10000000 by
+	# default) and relocated if they conflict, which is a slow very memory
+	# consuming and fragmenting process.  To avoid this, we pick a random,
+	# 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link
+	# time.  Moving up from 0x10000000 also allows more sbrk(2) space.
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
+	;;
+      irix5* | irix6*)
+        case $cc_basename in
+          CC*)
+	    # SGI C++
+	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared -all -multigot $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
+
+	    # Archives containing C++ object files must be created using
+	    # "CC -ar", where "CC" is the IRIX C++ compiler.  This is
+	    # necessary to make sure instantiated templates are included
+	    # in the archive.
+	    _LT_TAGVAR(old_archive_cmds, $1)='$CC -ar -WR,-u -o $oldlib $oldobjs'
+	    ;;
+          *)
+	    if test "$GXX" = yes; then
+	      if test "$with_gnu_ld" = no; then
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+	      else
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` -o $lib'
+	      fi
+	    fi
+	    _LT_TAGVAR(link_all_deplibs, $1)=yes
+	    ;;
+        esac
+        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+        _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+        _LT_TAGVAR(inherit_rpath, $1)=yes
+        ;;
+
+      linux* | k*bsd*-gnu | kopensolaris*-gnu)
+        case $cc_basename in
+          KCC*)
+	    # Kuck and Associates, Inc. (KAI) C++ Compiler
+
+	    # KCC will only create a shared library if the output file
+	    # ends with ".so" (or ".sl" for HP-UX), so rename the library
+	    # to its proper name (with version) after linking.
+	    _LT_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib'
+	    _LT_TAGVAR(archive_expsym_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib ${wl}-retain-symbols-file,$export_symbols; mv \$templib $lib'
+	    # Commands to make compiler produce verbose output that lists
+	    # what "hidden" libraries, object files and flags are used when
+	    # linking a shared library.
+	    #
+	    # There doesn't appear to be a way to prevent this compiler from
+	    # explicitly linking system object files so we need to strip them
+	    # from the output so that they don't get included in the library
+	    # dependencies.
+	    output_verbose_link_cmd='templist=`$CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1 | $GREP "ld"`; rm -f libconftest$shared_ext; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"'
+
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
+
+	    # Archives containing C++ object files must be created using
+	    # "CC -Bstatic", where "CC" is the KAI C++ compiler.
+	    _LT_TAGVAR(old_archive_cmds, $1)='$CC -Bstatic -o $oldlib $oldobjs'
+	    ;;
+	  icpc* | ecpc* )
+	    # Intel C++
+	    with_gnu_ld=yes
+	    # version 8.0 and above of icpc choke on multiply defined symbols
+	    # if we add $predep_objects and $postdep_objects, however 7.1 and
+	    # earlier do not add the objects themselves.
+	    case `$CC -V 2>&1` in
+	      *"Version 7."*)
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib'
+		_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+		;;
+	      *)  # Version 8.0 or newer
+	        tmp_idyn=
+	        case $host_cpu in
+		  ia64*) tmp_idyn=' -i_dynamic';;
+		esac
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+		_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+		;;
+	    esac
+	    _LT_TAGVAR(archive_cmds_need_lc, $1)=no
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
+	    _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive$convenience ${wl}--no-whole-archive'
+	    ;;
+          pgCC* | pgcpp*)
+            # Portland Group C++ compiler
+	    case `$CC -V` in
+	    *pgCC\ [[1-5]].* | *pgcpp\ [[1-5]].*)
+	      _LT_TAGVAR(prelink_cmds, $1)='tpldir=Template.dir~
+		rm -rf $tpldir~
+		$CC --prelink_objects --instantiation_dir $tpldir $objs $libobjs $compile_deplibs~
+		compile_command="$compile_command `find $tpldir -name \*.o | sort | $NL2SP`"'
+	      _LT_TAGVAR(old_archive_cmds, $1)='tpldir=Template.dir~
+		rm -rf $tpldir~
+		$CC --prelink_objects --instantiation_dir $tpldir $oldobjs$old_deplibs~
+		$AR $AR_FLAGS $oldlib$oldobjs$old_deplibs `find $tpldir -name \*.o | sort | $NL2SP`~
+		$RANLIB $oldlib'
+	      _LT_TAGVAR(archive_cmds, $1)='tpldir=Template.dir~
+		rm -rf $tpldir~
+		$CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~
+		$CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | sort | $NL2SP` $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib'
+	      _LT_TAGVAR(archive_expsym_cmds, $1)='tpldir=Template.dir~
+		rm -rf $tpldir~
+		$CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~
+		$CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | sort | $NL2SP` $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib'
+	      ;;
+	    *) # Version 6 and above use weak symbols
+	      _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib'
+	      _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib'
+	      ;;
+	    esac
+
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}--rpath ${wl}$libdir'
+	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
+	    _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
+            ;;
+	  cxx*)
+	    # Compaq C++
+	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib'
+	    _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname  -o $lib ${wl}-retain-symbols-file $wl$export_symbols'
+
+	    runpath_var=LD_RUN_PATH
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir'
+	    _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+
+	    # Commands to make compiler produce verbose output that lists
+	    # what "hidden" libraries, object files and flags are used when
+	    # linking a shared library.
+	    #
+	    # There doesn't appear to be a way to prevent this compiler from
+	    # explicitly linking system object files so we need to strip them
+	    # from the output so that they don't get included in the library
+	    # dependencies.
+	    output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld"`; templist=`func_echo_all "$templist" | $SED "s/\(^.*ld.*\)\( .*ld .*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "X$list" | $Xsed'
+	    ;;
+	  xl* | mpixl* | bgxl*)
+	    # IBM XL 8.0 on PPC, with GNU ld
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
+	    _LT_TAGVAR(archive_cmds, $1)='$CC -qmkshrobj $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+	    if test "x$supports_anon_versioning" = xyes; then
+	      _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~
+		cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
+		echo "local: *; };" >> $output_objdir/$libname.ver~
+		$CC -qmkshrobj $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib'
+	    fi
+	    ;;
+	  *)
+	    case `$CC -V 2>&1 | sed 5q` in
+	    *Sun\ C*)
+	      # Sun C++ 5.9
+	      _LT_TAGVAR(no_undefined_flag, $1)=' -zdefs'
+	      _LT_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	      _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file ${wl}$export_symbols'
+	      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+	      _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
+	      _LT_TAGVAR(compiler_needs_object, $1)=yes
+
+	      # Not sure whether something based on
+	      # $CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1
+	      # would be better.
+	      output_verbose_link_cmd='func_echo_all'
+
+	      # Archives containing C++ object files must be created using
+	      # "CC -xar", where "CC" is the Sun C++ compiler.  This is
+	      # necessary to make sure instantiated templates are included
+	      # in the archive.
+	      _LT_TAGVAR(old_archive_cmds, $1)='$CC -xar -o $oldlib $oldobjs'
+	      ;;
+	    esac
+	    ;;
+	esac
+	;;
+
+      lynxos*)
+        # FIXME: insert proper C++ library support
+	_LT_TAGVAR(ld_shlibs, $1)=no
+	;;
+
+      m88k*)
+        # FIXME: insert proper C++ library support
+        _LT_TAGVAR(ld_shlibs, $1)=no
+	;;
+
+      mvs*)
+        case $cc_basename in
+          cxx*)
+	    # FIXME: insert proper C++ library support
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	    ;;
+	  *)
+	    # FIXME: insert proper C++ library support
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	    ;;
+	esac
+	;;
+
+      netbsd*)
+        if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
+	  _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable  -o $lib $predep_objects $libobjs $deplibs $postdep_objects $linker_flags'
+	  wlarc=
+	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+	  _LT_TAGVAR(hardcode_direct, $1)=yes
+	  _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+	fi
+	# Workaround some broken pre-1.5 toolchains
+	output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP conftest.$objext | $SED -e "s:-lgcc -lc -lgcc::"'
+	;;
+
+      *nto* | *qnx*)
+        _LT_TAGVAR(ld_shlibs, $1)=yes
+	;;
+
+      openbsd2*)
+        # C++ shared libraries are fairly broken
+	_LT_TAGVAR(ld_shlibs, $1)=no
+	;;
+
+      openbsd*)
+	if test -f /usr/libexec/ld.so; then
+	  _LT_TAGVAR(hardcode_direct, $1)=yes
+	  _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+	  _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib'
+	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+	  if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+	    _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file,$export_symbols -o $lib'
+	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+	    _LT_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
+	  fi
+	  output_verbose_link_cmd=func_echo_all
+	else
+	  _LT_TAGVAR(ld_shlibs, $1)=no
+	fi
+	;;
+
+      osf3* | osf4* | osf5*)
+        case $cc_basename in
+          KCC*)
+	    # Kuck and Associates, Inc. (KAI) C++ Compiler
+
+	    # KCC will only create a shared library if the output file
+	    # ends with ".so" (or ".sl" for HP-UX), so rename the library
+	    # to its proper name (with version) after linking.
+	    _LT_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo "$lib" | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib'
+
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+	    _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+
+	    # Archives containing C++ object files must be created using
+	    # the KAI C++ compiler.
+	    case $host in
+	      osf3*) _LT_TAGVAR(old_archive_cmds, $1)='$CC -Bstatic -o $oldlib $oldobjs' ;;
+	      *) _LT_TAGVAR(old_archive_cmds, $1)='$CC -o $oldlib $oldobjs' ;;
+	    esac
+	    ;;
+          RCC*)
+	    # Rational C++ 2.4.1
+	    # FIXME: insert proper C++ library support
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	    ;;
+          cxx*)
+	    case $host in
+	      osf3*)
+	        _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $soname `test -n "$verstring" && func_echo_all "${wl}-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
+	        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+		;;
+	      *)
+	        _LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*'
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
+	        _LT_TAGVAR(archive_expsym_cmds, $1)='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done~
+	          echo "-hidden">> $lib.exp~
+	          $CC -shared$allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname ${wl}-input ${wl}$lib.exp  `test -n "$verstring" && $ECHO "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib~
+	          $RM $lib.exp'
+	        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir'
+		;;
+	    esac
+
+	    _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+
+	    # Commands to make compiler produce verbose output that lists
+	    # what "hidden" libraries, object files and flags are used when
+	    # linking a shared library.
+	    #
+	    # There doesn't appear to be a way to prevent this compiler from
+	    # explicitly linking system object files so we need to strip them
+	    # from the output so that they don't get included in the library
+	    # dependencies.
+	    output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld" | $GREP -v "ld:"`; templist=`func_echo_all "$templist" | $SED "s/\(^.*ld.*\)\( .*ld.*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"'
+	    ;;
+	  *)
+	    if test "$GXX" = yes && test "$with_gnu_ld" = no; then
+	      _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
+	      case $host in
+	        osf3*)
+	          _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+		  ;;
+	        *)
+	          _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+		  ;;
+	      esac
+
+	      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+	      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+
+	      # Commands to make compiler produce verbose output that lists
+	      # what "hidden" libraries, object files and flags are used when
+	      # linking a shared library.
+	      output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"'
+
+	    else
+	      # FIXME: insert proper C++ library support
+	      _LT_TAGVAR(ld_shlibs, $1)=no
+	    fi
+	    ;;
+        esac
+        ;;
+
+      psos*)
+        # FIXME: insert proper C++ library support
+        _LT_TAGVAR(ld_shlibs, $1)=no
+        ;;
+
+      sunos4*)
+        case $cc_basename in
+          CC*)
+	    # Sun C++ 4.x
+	    # FIXME: insert proper C++ library support
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	    ;;
+          lcc*)
+	    # Lucid
+	    # FIXME: insert proper C++ library support
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	    ;;
+          *)
+	    # FIXME: insert proper C++ library support
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	    ;;
+        esac
+        ;;
+
+      solaris*)
+        case $cc_basename in
+          CC* | sunCC*)
+	    # Sun C++ 4.2, 5.x and Centerline C++
+            _LT_TAGVAR(archive_cmds_need_lc,$1)=yes
+	    _LT_TAGVAR(no_undefined_flag, $1)=' -zdefs'
+	    _LT_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag}  -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	    _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
+	      $CC -G${allow_undefined_flag} ${wl}-M ${wl}$lib.exp -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp'
+
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+	    _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+	    case $host_os in
+	      solaris2.[[0-5]] | solaris2.[[0-5]].*) ;;
+	      *)
+		# The compiler driver will combine and reorder linker options,
+		# but understands `-z linker_flag'.
+	        # Supported since Solaris 2.6 (maybe 2.5.1?)
+		_LT_TAGVAR(whole_archive_flag_spec, $1)='-z allextract$convenience -z defaultextract'
+	        ;;
+	    esac
+	    _LT_TAGVAR(link_all_deplibs, $1)=yes
+
+	    output_verbose_link_cmd='func_echo_all'
+
+	    # Archives containing C++ object files must be created using
+	    # "CC -xar", where "CC" is the Sun C++ compiler.  This is
+	    # necessary to make sure instantiated templates are included
+	    # in the archive.
+	    _LT_TAGVAR(old_archive_cmds, $1)='$CC -xar -o $oldlib $oldobjs'
+	    ;;
+          gcx*)
+	    # Green Hills C++ Compiler
+	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib'
+
+	    # The C++ compiler must be used to create the archive.
+	    _LT_TAGVAR(old_archive_cmds, $1)='$CC $LDFLAGS -archive -o $oldlib $oldobjs'
+	    ;;
+          *)
+	    # GNU C++ compiler with Solaris linker
+	    if test "$GXX" = yes && test "$with_gnu_ld" = no; then
+	      _LT_TAGVAR(no_undefined_flag, $1)=' ${wl}-z ${wl}defs'
+	      if $CC --version | $GREP -v '^2\.7' > /dev/null; then
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib'
+	        _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
+		  $CC -shared $pic_flag -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp'
+
+	        # Commands to make compiler produce verbose output that lists
+	        # what "hidden" libraries, object files and flags are used when
+	        # linking a shared library.
+	        output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"'
+	      else
+	        # g++ 2.7 appears to require `-G' NOT `-shared' on this
+	        # platform.
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -G -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib'
+	        _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
+		  $CC -G -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp'
+
+	        # Commands to make compiler produce verbose output that lists
+	        # what "hidden" libraries, object files and flags are used when
+	        # linking a shared library.
+	        output_verbose_link_cmd='$CC -G $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"'
+	      fi
+
+	      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $wl$libdir'
+	      case $host_os in
+		solaris2.[[0-5]] | solaris2.[[0-5]].*) ;;
+		*)
+		  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract'
+		  ;;
+	      esac
+	    fi
+	    ;;
+        esac
+        ;;
+
+    sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[[01]].[[10]]* | unixware7* | sco3.2v5.0.[[024]]*)
+      _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
+      _LT_TAGVAR(archive_cmds_need_lc, $1)=no
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      runpath_var='LD_RUN_PATH'
+
+      case $cc_basename in
+        CC*)
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	  _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	  ;;
+	*)
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	  _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	  ;;
+      esac
+      ;;
+
+      sysv5* | sco3.2v5* | sco5v6*)
+	# Note: We can NOT use -z defs as we might desire, because we do not
+	# link with -lc, and that would cause any symbols used from libc to
+	# always be unresolved, which means just about no library would
+	# ever link correctly.  If we're not using GNU ld we use -z text
+	# though, which does catch some bad symbols but isn't as heavy-handed
+	# as -z defs.
+	_LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
+	_LT_TAGVAR(allow_undefined_flag, $1)='${wl}-z,nodefs'
+	_LT_TAGVAR(archive_cmds_need_lc, $1)=no
+	_LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R,$libdir'
+	_LT_TAGVAR(hardcode_libdir_separator, $1)=':'
+	_LT_TAGVAR(link_all_deplibs, $1)=yes
+	_LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Bexport'
+	runpath_var='LD_RUN_PATH'
+
+	case $cc_basename in
+          CC*)
+	    _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	    _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	    _LT_TAGVAR(old_archive_cmds, $1)='$CC -Tprelink_objects $oldobjs~
+	      '"$_LT_TAGVAR(old_archive_cmds, $1)"
+	    _LT_TAGVAR(reload_cmds, $1)='$CC -Tprelink_objects $reload_objs~
+	      '"$_LT_TAGVAR(reload_cmds, $1)"
+	    ;;
+	  *)
+	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	    _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	    ;;
+	esac
+      ;;
+
+      tandem*)
+        case $cc_basename in
+          NCC*)
+	    # NonStop-UX NCC 3.20
+	    # FIXME: insert proper C++ library support
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	    ;;
+          *)
+	    # FIXME: insert proper C++ library support
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	    ;;
+        esac
+        ;;
+
+      vxworks*)
+        # FIXME: insert proper C++ library support
+        _LT_TAGVAR(ld_shlibs, $1)=no
+        ;;
+
+      *)
+        # FIXME: insert proper C++ library support
+        _LT_TAGVAR(ld_shlibs, $1)=no
+        ;;
+    esac
+
+    AC_MSG_RESULT([$_LT_TAGVAR(ld_shlibs, $1)])
+    test "$_LT_TAGVAR(ld_shlibs, $1)" = no && can_build_shared=no
+
+    _LT_TAGVAR(GCC, $1)="$GXX"
+    _LT_TAGVAR(LD, $1)="$LD"
+
+    ## CAVEAT EMPTOR:
+    ## There is no encapsulation within the following macros, do not change
+    ## the running order or otherwise move them around unless you know exactly
+    ## what you are doing...
+    _LT_SYS_HIDDEN_LIBDEPS($1)
+    _LT_COMPILER_PIC($1)
+    _LT_COMPILER_C_O($1)
+    _LT_COMPILER_FILE_LOCKS($1)
+    _LT_LINKER_SHLIBS($1)
+    _LT_SYS_DYNAMIC_LINKER($1)
+    _LT_LINKER_HARDCODE_LIBPATH($1)
+
+    _LT_CONFIG($1)
+  fi # test -n "$compiler"
+
+  CC=$lt_save_CC
+  CFLAGS=$lt_save_CFLAGS
+  LDCXX=$LD
+  LD=$lt_save_LD
+  GCC=$lt_save_GCC
+  with_gnu_ld=$lt_save_with_gnu_ld
+  lt_cv_path_LDCXX=$lt_cv_path_LD
+  lt_cv_path_LD=$lt_save_path_LD
+  lt_cv_prog_gnu_ldcxx=$lt_cv_prog_gnu_ld
+  lt_cv_prog_gnu_ld=$lt_save_with_gnu_ld
+fi # test "$_lt_caught_CXX_error" != yes
+
+AC_LANG_POP
+])# _LT_LANG_CXX_CONFIG
+
+
+# _LT_FUNC_STRIPNAME_CNF
+# ----------------------
+# func_stripname_cnf prefix suffix name
+# strip PREFIX and SUFFIX off of NAME.
+# PREFIX and SUFFIX must not contain globbing or regex special
+# characters, hashes, percent signs, but SUFFIX may contain a leading
+# dot (in which case that matches only a dot).
+#
+# This function is identical to the (non-XSI) version of func_stripname,
+# except this one can be used by m4 code that may be executed by configure,
+# rather than the libtool script.
+m4_defun([_LT_FUNC_STRIPNAME_CNF],[dnl
+AC_REQUIRE([_LT_DECL_SED])
+AC_REQUIRE([_LT_PROG_ECHO_BACKSLASH])
+func_stripname_cnf ()
+{
+  case ${2} in
+  .*) func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%\\\\${2}\$%%"`;;
+  *)  func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%${2}\$%%"`;;
+  esac
+} # func_stripname_cnf
+])# _LT_FUNC_STRIPNAME_CNF
+
+# _LT_SYS_HIDDEN_LIBDEPS([TAGNAME])
+# ---------------------------------
+# Figure out "hidden" library dependencies from verbose
+# compiler output when linking a shared library.
+# Parse the compiler output and extract the necessary
+# objects, libraries and library flags.
+m4_defun([_LT_SYS_HIDDEN_LIBDEPS],
+[m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+AC_REQUIRE([_LT_FUNC_STRIPNAME_CNF])dnl
+# Dependencies to place before and after the object being linked:
+_LT_TAGVAR(predep_objects, $1)=
+_LT_TAGVAR(postdep_objects, $1)=
+_LT_TAGVAR(predeps, $1)=
+_LT_TAGVAR(postdeps, $1)=
+_LT_TAGVAR(compiler_lib_search_path, $1)=
+
+dnl we can't use the lt_simple_compile_test_code here,
+dnl because it contains code intended for an executable,
+dnl not a library.  It's possible we should let each
+dnl tag define a new lt_????_link_test_code variable,
+dnl but it's only used here...
+m4_if([$1], [], [cat > conftest.$ac_ext <<_LT_EOF
+int a;
+void foo (void) { a = 0; }
+_LT_EOF
+], [$1], [CXX], [cat > conftest.$ac_ext <<_LT_EOF
+class Foo
+{
+public:
+  Foo (void) { a = 0; }
+private:
+  int a;
+};
+_LT_EOF
+], [$1], [F77], [cat > conftest.$ac_ext <<_LT_EOF
+      subroutine foo
+      implicit none
+      integer*4 a
+      a=0
+      return
+      end
+_LT_EOF
+], [$1], [FC], [cat > conftest.$ac_ext <<_LT_EOF
+      subroutine foo
+      implicit none
+      integer a
+      a=0
+      return
+      end
+_LT_EOF
+], [$1], [GCJ], [cat > conftest.$ac_ext <<_LT_EOF
+public class foo {
+  private int a;
+  public void bar (void) {
+    a = 0;
+  }
+};
+_LT_EOF
+], [$1], [GO], [cat > conftest.$ac_ext <<_LT_EOF
+package foo
+func foo() {
+}
+_LT_EOF
+])
+
+_lt_libdeps_save_CFLAGS=$CFLAGS
+case "$CC $CFLAGS " in #(
+*\ -flto*\ *) CFLAGS="$CFLAGS -fno-lto" ;;
+*\ -fwhopr*\ *) CFLAGS="$CFLAGS -fno-whopr" ;;
+*\ -fuse-linker-plugin*\ *) CFLAGS="$CFLAGS -fno-use-linker-plugin" ;;
+esac
+
+dnl Parse the compiler output and extract the necessary
+dnl objects, libraries and library flags.
+if AC_TRY_EVAL(ac_compile); then
+  # Parse the compiler output and extract the necessary
+  # objects, libraries and library flags.
+
+  # Sentinel used to keep track of whether or not we are before
+  # the conftest object file.
+  pre_test_object_deps_done=no
+
+  for p in `eval "$output_verbose_link_cmd"`; do
+    case ${prev}${p} in
+
+    -L* | -R* | -l*)
+       # Some compilers place space between "-{L,R}" and the path.
+       # Remove the space.
+       if test $p = "-L" ||
+          test $p = "-R"; then
+	 prev=$p
+	 continue
+       fi
+
+       # Expand the sysroot to ease extracting the directories later.
+       if test -z "$prev"; then
+         case $p in
+         -L*) func_stripname_cnf '-L' '' "$p"; prev=-L; p=$func_stripname_result ;;
+         -R*) func_stripname_cnf '-R' '' "$p"; prev=-R; p=$func_stripname_result ;;
+         -l*) func_stripname_cnf '-l' '' "$p"; prev=-l; p=$func_stripname_result ;;
+         esac
+       fi
+       case $p in
+       =*) func_stripname_cnf '=' '' "$p"; p=$lt_sysroot$func_stripname_result ;;
+       esac
+       if test "$pre_test_object_deps_done" = no; then
+	 case ${prev} in
+	 -L | -R)
+	   # Internal compiler library paths should come after those
+	   # provided the user.  The postdeps already come after the
+	   # user supplied libs so there is no need to process them.
+	   if test -z "$_LT_TAGVAR(compiler_lib_search_path, $1)"; then
+	     _LT_TAGVAR(compiler_lib_search_path, $1)="${prev}${p}"
+	   else
+	     _LT_TAGVAR(compiler_lib_search_path, $1)="${_LT_TAGVAR(compiler_lib_search_path, $1)} ${prev}${p}"
+	   fi
+	   ;;
+	 # The "-l" case would never come before the object being
+	 # linked, so don't bother handling this case.
+	 esac
+       else
+	 if test -z "$_LT_TAGVAR(postdeps, $1)"; then
+	   _LT_TAGVAR(postdeps, $1)="${prev}${p}"
+	 else
+	   _LT_TAGVAR(postdeps, $1)="${_LT_TAGVAR(postdeps, $1)} ${prev}${p}"
+	 fi
+       fi
+       prev=
+       ;;
+
+    *.lto.$objext) ;; # Ignore GCC LTO objects
+    *.$objext)
+       # This assumes that the test object file only shows up
+       # once in the compiler output.
+       if test "$p" = "conftest.$objext"; then
+	 pre_test_object_deps_done=yes
+	 continue
+       fi
+
+       if test "$pre_test_object_deps_done" = no; then
+	 if test -z "$_LT_TAGVAR(predep_objects, $1)"; then
+	   _LT_TAGVAR(predep_objects, $1)="$p"
+	 else
+	   _LT_TAGVAR(predep_objects, $1)="$_LT_TAGVAR(predep_objects, $1) $p"
+	 fi
+       else
+	 if test -z "$_LT_TAGVAR(postdep_objects, $1)"; then
+	   _LT_TAGVAR(postdep_objects, $1)="$p"
+	 else
+	   _LT_TAGVAR(postdep_objects, $1)="$_LT_TAGVAR(postdep_objects, $1) $p"
+	 fi
+       fi
+       ;;
+
+    *) ;; # Ignore the rest.
+
+    esac
+  done
+
+  # Clean up.
+  rm -f a.out a.exe
+else
+  echo "libtool.m4: error: problem compiling $1 test program"
+fi
+
+$RM -f confest.$objext
+CFLAGS=$_lt_libdeps_save_CFLAGS
+
+# PORTME: override above test on systems where it is broken
+m4_if([$1], [CXX],
+[case $host_os in
+interix[[3-9]]*)
+  # Interix 3.5 installs completely hosed .la files for C++, so rather than
+  # hack all around it, let's just trust "g++" to DTRT.
+  _LT_TAGVAR(predep_objects,$1)=
+  _LT_TAGVAR(postdep_objects,$1)=
+  _LT_TAGVAR(postdeps,$1)=
+  ;;
+
+linux*)
+  case `$CC -V 2>&1 | sed 5q` in
+  *Sun\ C*)
+    # Sun C++ 5.9
+
+    # The more standards-conforming stlport4 library is
+    # incompatible with the Cstd library. Avoid specifying
+    # it if it's in CXXFLAGS. Ignore libCrun as
+    # -library=stlport4 depends on it.
+    case " $CXX $CXXFLAGS " in
+    *" -library=stlport4 "*)
+      solaris_use_stlport4=yes
+      ;;
+    esac
+
+    if test "$solaris_use_stlport4" != yes; then
+      _LT_TAGVAR(postdeps,$1)='-library=Cstd -library=Crun'
+    fi
+    ;;
+  esac
+  ;;
+
+solaris*)
+  case $cc_basename in
+  CC* | sunCC*)
+    # The more standards-conforming stlport4 library is
+    # incompatible with the Cstd library. Avoid specifying
+    # it if it's in CXXFLAGS. Ignore libCrun as
+    # -library=stlport4 depends on it.
+    case " $CXX $CXXFLAGS " in
+    *" -library=stlport4 "*)
+      solaris_use_stlport4=yes
+      ;;
+    esac
+
+    # Adding this requires a known-good setup of shared libraries for
+    # Sun compiler versions before 5.6, else PIC objects from an old
+    # archive will be linked into the output, leading to subtle bugs.
+    if test "$solaris_use_stlport4" != yes; then
+      _LT_TAGVAR(postdeps,$1)='-library=Cstd -library=Crun'
+    fi
+    ;;
+  esac
+  ;;
+esac
+])
+
+case " $_LT_TAGVAR(postdeps, $1) " in
+*" -lc "*) _LT_TAGVAR(archive_cmds_need_lc, $1)=no ;;
+esac
+ _LT_TAGVAR(compiler_lib_search_dirs, $1)=
+if test -n "${_LT_TAGVAR(compiler_lib_search_path, $1)}"; then
+ _LT_TAGVAR(compiler_lib_search_dirs, $1)=`echo " ${_LT_TAGVAR(compiler_lib_search_path, $1)}" | ${SED} -e 's! -L! !g' -e 's!^ !!'`
+fi
+_LT_TAGDECL([], [compiler_lib_search_dirs], [1],
+    [The directories searched by this compiler when creating a shared library])
+_LT_TAGDECL([], [predep_objects], [1],
+    [Dependencies to place before and after the objects being linked to
+    create a shared library])
+_LT_TAGDECL([], [postdep_objects], [1])
+_LT_TAGDECL([], [predeps], [1])
+_LT_TAGDECL([], [postdeps], [1])
+_LT_TAGDECL([], [compiler_lib_search_path], [1],
+    [The library search path used internally by the compiler when linking
+    a shared library])
+])# _LT_SYS_HIDDEN_LIBDEPS
+
+
+# _LT_LANG_F77_CONFIG([TAG])
+# --------------------------
+# Ensure that the configuration variables for a Fortran 77 compiler are
+# suitably defined.  These variables are subsequently used by _LT_CONFIG
+# to write the compiler configuration to `libtool'.
+m4_defun([_LT_LANG_F77_CONFIG],
+[AC_LANG_PUSH(Fortran 77)
+if test -z "$F77" || test "X$F77" = "Xno"; then
+  _lt_disable_F77=yes
+fi
+
+_LT_TAGVAR(archive_cmds_need_lc, $1)=no
+_LT_TAGVAR(allow_undefined_flag, $1)=
+_LT_TAGVAR(always_export_symbols, $1)=no
+_LT_TAGVAR(archive_expsym_cmds, $1)=
+_LT_TAGVAR(export_dynamic_flag_spec, $1)=
+_LT_TAGVAR(hardcode_direct, $1)=no
+_LT_TAGVAR(hardcode_direct_absolute, $1)=no
+_LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
+_LT_TAGVAR(hardcode_libdir_separator, $1)=
+_LT_TAGVAR(hardcode_minus_L, $1)=no
+_LT_TAGVAR(hardcode_automatic, $1)=no
+_LT_TAGVAR(inherit_rpath, $1)=no
+_LT_TAGVAR(module_cmds, $1)=
+_LT_TAGVAR(module_expsym_cmds, $1)=
+_LT_TAGVAR(link_all_deplibs, $1)=unknown
+_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
+_LT_TAGVAR(reload_flag, $1)=$reload_flag
+_LT_TAGVAR(reload_cmds, $1)=$reload_cmds
+_LT_TAGVAR(no_undefined_flag, $1)=
+_LT_TAGVAR(whole_archive_flag_spec, $1)=
+_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no
+
+# Source file extension for f77 test sources.
+ac_ext=f
+
+# Object file extension for compiled f77 test sources.
+objext=o
+_LT_TAGVAR(objext, $1)=$objext
+
+# No sense in running all these tests if we already determined that
+# the F77 compiler isn't working.  Some variables (like enable_shared)
+# are currently assumed to apply to all compilers on this platform,
+# and will be corrupted by setting them based on a non-working compiler.
+if test "$_lt_disable_F77" != yes; then
+  # Code to be used in simple compile tests
+  lt_simple_compile_test_code="\
+      subroutine t
+      return
+      end
+"
+
+  # Code to be used in simple link tests
+  lt_simple_link_test_code="\
+      program t
+      end
+"
+
+  # ltmain only uses $CC for tagged configurations so make sure $CC is set.
+  _LT_TAG_COMPILER
+
+  # save warnings/boilerplate of simple test code
+  _LT_COMPILER_BOILERPLATE
+  _LT_LINKER_BOILERPLATE
+
+  # Allow CC to be a program name with arguments.
+  lt_save_CC="$CC"
+  lt_save_GCC=$GCC
+  lt_save_CFLAGS=$CFLAGS
+  CC=${F77-"f77"}
+  CFLAGS=$FFLAGS
+  compiler=$CC
+  _LT_TAGVAR(compiler, $1)=$CC
+  _LT_CC_BASENAME([$compiler])
+  GCC=$G77
+  if test -n "$compiler"; then
+    AC_MSG_CHECKING([if libtool supports shared libraries])
+    AC_MSG_RESULT([$can_build_shared])
+
+    AC_MSG_CHECKING([whether to build shared libraries])
+    test "$can_build_shared" = "no" && enable_shared=no
+
+    # On AIX, shared libraries and static libraries use the same namespace, and
+    # are all built from PIC.
+    case $host_os in
+      aix3*)
+        test "$enable_shared" = yes && enable_static=no
+        if test -n "$RANLIB"; then
+          archive_cmds="$archive_cmds~\$RANLIB \$lib"
+          postinstall_cmds='$RANLIB $lib'
+        fi
+        ;;
+      aix[[4-9]]*)
+	if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then
+	  test "$enable_shared" = yes && enable_static=no
+	fi
+        ;;
+    esac
+    AC_MSG_RESULT([$enable_shared])
+
+    AC_MSG_CHECKING([whether to build static libraries])
+    # Make sure either enable_shared or enable_static is yes.
+    test "$enable_shared" = yes || enable_static=yes
+    AC_MSG_RESULT([$enable_static])
+
+    _LT_TAGVAR(GCC, $1)="$G77"
+    _LT_TAGVAR(LD, $1)="$LD"
+
+    ## CAVEAT EMPTOR:
+    ## There is no encapsulation within the following macros, do not change
+    ## the running order or otherwise move them around unless you know exactly
+    ## what you are doing...
+    _LT_COMPILER_PIC($1)
+    _LT_COMPILER_C_O($1)
+    _LT_COMPILER_FILE_LOCKS($1)
+    _LT_LINKER_SHLIBS($1)
+    _LT_SYS_DYNAMIC_LINKER($1)
+    _LT_LINKER_HARDCODE_LIBPATH($1)
+
+    _LT_CONFIG($1)
+  fi # test -n "$compiler"
+
+  GCC=$lt_save_GCC
+  CC="$lt_save_CC"
+  CFLAGS="$lt_save_CFLAGS"
+fi # test "$_lt_disable_F77" != yes
+
+AC_LANG_POP
+])# _LT_LANG_F77_CONFIG
+
+
+# _LT_LANG_FC_CONFIG([TAG])
+# -------------------------
+# Ensure that the configuration variables for a Fortran compiler are
+# suitably defined.  These variables are subsequently used by _LT_CONFIG
+# to write the compiler configuration to `libtool'.
+m4_defun([_LT_LANG_FC_CONFIG],
+[AC_LANG_PUSH(Fortran)
+
+if test -z "$FC" || test "X$FC" = "Xno"; then
+  _lt_disable_FC=yes
+fi
+
+_LT_TAGVAR(archive_cmds_need_lc, $1)=no
+_LT_TAGVAR(allow_undefined_flag, $1)=
+_LT_TAGVAR(always_export_symbols, $1)=no
+_LT_TAGVAR(archive_expsym_cmds, $1)=
+_LT_TAGVAR(export_dynamic_flag_spec, $1)=
+_LT_TAGVAR(hardcode_direct, $1)=no
+_LT_TAGVAR(hardcode_direct_absolute, $1)=no
+_LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
+_LT_TAGVAR(hardcode_libdir_separator, $1)=
+_LT_TAGVAR(hardcode_minus_L, $1)=no
+_LT_TAGVAR(hardcode_automatic, $1)=no
+_LT_TAGVAR(inherit_rpath, $1)=no
+_LT_TAGVAR(module_cmds, $1)=
+_LT_TAGVAR(module_expsym_cmds, $1)=
+_LT_TAGVAR(link_all_deplibs, $1)=unknown
+_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
+_LT_TAGVAR(reload_flag, $1)=$reload_flag
+_LT_TAGVAR(reload_cmds, $1)=$reload_cmds
+_LT_TAGVAR(no_undefined_flag, $1)=
+_LT_TAGVAR(whole_archive_flag_spec, $1)=
+_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no
+
+# Source file extension for fc test sources.
+ac_ext=${ac_fc_srcext-f}
+
+# Object file extension for compiled fc test sources.
+objext=o
+_LT_TAGVAR(objext, $1)=$objext
+
+# No sense in running all these tests if we already determined that
+# the FC compiler isn't working.  Some variables (like enable_shared)
+# are currently assumed to apply to all compilers on this platform,
+# and will be corrupted by setting them based on a non-working compiler.
+if test "$_lt_disable_FC" != yes; then
+  # Code to be used in simple compile tests
+  lt_simple_compile_test_code="\
+      subroutine t
+      return
+      end
+"
+
+  # Code to be used in simple link tests
+  lt_simple_link_test_code="\
+      program t
+      end
+"
+
+  # ltmain only uses $CC for tagged configurations so make sure $CC is set.
+  _LT_TAG_COMPILER
+
+  # save warnings/boilerplate of simple test code
+  _LT_COMPILER_BOILERPLATE
+  _LT_LINKER_BOILERPLATE
+
+  # Allow CC to be a program name with arguments.
+  lt_save_CC="$CC"
+  lt_save_GCC=$GCC
+  lt_save_CFLAGS=$CFLAGS
+  CC=${FC-"f95"}
+  CFLAGS=$FCFLAGS
+  compiler=$CC
+  GCC=$ac_cv_fc_compiler_gnu
+
+  _LT_TAGVAR(compiler, $1)=$CC
+  _LT_CC_BASENAME([$compiler])
+
+  if test -n "$compiler"; then
+    AC_MSG_CHECKING([if libtool supports shared libraries])
+    AC_MSG_RESULT([$can_build_shared])
+
+    AC_MSG_CHECKING([whether to build shared libraries])
+    test "$can_build_shared" = "no" && enable_shared=no
+
+    # On AIX, shared libraries and static libraries use the same namespace, and
+    # are all built from PIC.
+    case $host_os in
+      aix3*)
+        test "$enable_shared" = yes && enable_static=no
+        if test -n "$RANLIB"; then
+          archive_cmds="$archive_cmds~\$RANLIB \$lib"
+          postinstall_cmds='$RANLIB $lib'
+        fi
+        ;;
+      aix[[4-9]]*)
+	if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then
+	  test "$enable_shared" = yes && enable_static=no
+	fi
+        ;;
+    esac
+    AC_MSG_RESULT([$enable_shared])
+
+    AC_MSG_CHECKING([whether to build static libraries])
+    # Make sure either enable_shared or enable_static is yes.
+    test "$enable_shared" = yes || enable_static=yes
+    AC_MSG_RESULT([$enable_static])
+
+    _LT_TAGVAR(GCC, $1)="$ac_cv_fc_compiler_gnu"
+    _LT_TAGVAR(LD, $1)="$LD"
+
+    ## CAVEAT EMPTOR:
+    ## There is no encapsulation within the following macros, do not change
+    ## the running order or otherwise move them around unless you know exactly
+    ## what you are doing...
+    _LT_SYS_HIDDEN_LIBDEPS($1)
+    _LT_COMPILER_PIC($1)
+    _LT_COMPILER_C_O($1)
+    _LT_COMPILER_FILE_LOCKS($1)
+    _LT_LINKER_SHLIBS($1)
+    _LT_SYS_DYNAMIC_LINKER($1)
+    _LT_LINKER_HARDCODE_LIBPATH($1)
+
+    _LT_CONFIG($1)
+  fi # test -n "$compiler"
+
+  GCC=$lt_save_GCC
+  CC=$lt_save_CC
+  CFLAGS=$lt_save_CFLAGS
+fi # test "$_lt_disable_FC" != yes
+
+AC_LANG_POP
+])# _LT_LANG_FC_CONFIG
+
+
+# _LT_LANG_GCJ_CONFIG([TAG])
+# --------------------------
+# Ensure that the configuration variables for the GNU Java Compiler compiler
+# are suitably defined.  These variables are subsequently used by _LT_CONFIG
+# to write the compiler configuration to `libtool'.
+m4_defun([_LT_LANG_GCJ_CONFIG],
+[AC_REQUIRE([LT_PROG_GCJ])dnl
+AC_LANG_SAVE
+
+# Source file extension for Java test sources.
+ac_ext=java
+
+# Object file extension for compiled Java test sources.
+objext=o
+_LT_TAGVAR(objext, $1)=$objext
+
+# Code to be used in simple compile tests
+lt_simple_compile_test_code="class foo {}"
+
+# Code to be used in simple link tests
+lt_simple_link_test_code='public class conftest { public static void main(String[[]] argv) {}; }'
+
+# ltmain only uses $CC for tagged configurations so make sure $CC is set.
+_LT_TAG_COMPILER
+
+# save warnings/boilerplate of simple test code
+_LT_COMPILER_BOILERPLATE
+_LT_LINKER_BOILERPLATE
+
+# Allow CC to be a program name with arguments.
+lt_save_CC=$CC
+lt_save_CFLAGS=$CFLAGS
+lt_save_GCC=$GCC
+GCC=yes
+CC=${GCJ-"gcj"}
+CFLAGS=$GCJFLAGS
+compiler=$CC
+_LT_TAGVAR(compiler, $1)=$CC
+_LT_TAGVAR(LD, $1)="$LD"
+_LT_CC_BASENAME([$compiler])
+
+# GCJ did not exist at the time GCC didn't implicitly link libc in.
+_LT_TAGVAR(archive_cmds_need_lc, $1)=no
+
+_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
+_LT_TAGVAR(reload_flag, $1)=$reload_flag
+_LT_TAGVAR(reload_cmds, $1)=$reload_cmds
+
+if test -n "$compiler"; then
+  _LT_COMPILER_NO_RTTI($1)
+  _LT_COMPILER_PIC($1)
+  _LT_COMPILER_C_O($1)
+  _LT_COMPILER_FILE_LOCKS($1)
+  _LT_LINKER_SHLIBS($1)
+  _LT_LINKER_HARDCODE_LIBPATH($1)
+
+  _LT_CONFIG($1)
+fi
+
+AC_LANG_RESTORE
+
+GCC=$lt_save_GCC
+CC=$lt_save_CC
+CFLAGS=$lt_save_CFLAGS
+])# _LT_LANG_GCJ_CONFIG
+
+
+# _LT_LANG_GO_CONFIG([TAG])
+# --------------------------
+# Ensure that the configuration variables for the GNU Go compiler
+# are suitably defined.  These variables are subsequently used by _LT_CONFIG
+# to write the compiler configuration to `libtool'.
+m4_defun([_LT_LANG_GO_CONFIG],
+[AC_REQUIRE([LT_PROG_GO])dnl
+AC_LANG_SAVE
+
+# Source file extension for Go test sources.
+ac_ext=go
+
+# Object file extension for compiled Go test sources.
+objext=o
+_LT_TAGVAR(objext, $1)=$objext
+
+# Code to be used in simple compile tests
+lt_simple_compile_test_code="package main; func main() { }"
+
+# Code to be used in simple link tests
+lt_simple_link_test_code='package main; func main() { }'
+
+# ltmain only uses $CC for tagged configurations so make sure $CC is set.
+_LT_TAG_COMPILER
+
+# save warnings/boilerplate of simple test code
+_LT_COMPILER_BOILERPLATE
+_LT_LINKER_BOILERPLATE
+
+# Allow CC to be a program name with arguments.
+lt_save_CC=$CC
+lt_save_CFLAGS=$CFLAGS
+lt_save_GCC=$GCC
+GCC=yes
+CC=${GOC-"gccgo"}
+CFLAGS=$GOFLAGS
+compiler=$CC
+_LT_TAGVAR(compiler, $1)=$CC
+_LT_TAGVAR(LD, $1)="$LD"
+_LT_CC_BASENAME([$compiler])
+
+# Go did not exist at the time GCC didn't implicitly link libc in.
+_LT_TAGVAR(archive_cmds_need_lc, $1)=no
+
+_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
+_LT_TAGVAR(reload_flag, $1)=$reload_flag
+_LT_TAGVAR(reload_cmds, $1)=$reload_cmds
+
+if test -n "$compiler"; then
+  _LT_COMPILER_NO_RTTI($1)
+  _LT_COMPILER_PIC($1)
+  _LT_COMPILER_C_O($1)
+  _LT_COMPILER_FILE_LOCKS($1)
+  _LT_LINKER_SHLIBS($1)
+  _LT_LINKER_HARDCODE_LIBPATH($1)
+
+  _LT_CONFIG($1)
+fi
+
+AC_LANG_RESTORE
+
+GCC=$lt_save_GCC
+CC=$lt_save_CC
+CFLAGS=$lt_save_CFLAGS
+])# _LT_LANG_GO_CONFIG
+
+
+# _LT_LANG_RC_CONFIG([TAG])
+# -------------------------
+# Ensure that the configuration variables for the Windows resource compiler
+# are suitably defined.  These variables are subsequently used by _LT_CONFIG
+# to write the compiler configuration to `libtool'.
+m4_defun([_LT_LANG_RC_CONFIG],
+[AC_REQUIRE([LT_PROG_RC])dnl
+AC_LANG_SAVE
+
+# Source file extension for RC test sources.
+ac_ext=rc
+
+# Object file extension for compiled RC test sources.
+objext=o
+_LT_TAGVAR(objext, $1)=$objext
+
+# Code to be used in simple compile tests
+lt_simple_compile_test_code='sample MENU { MENUITEM "&Soup", 100, CHECKED }'
+
+# Code to be used in simple link tests
+lt_simple_link_test_code="$lt_simple_compile_test_code"
+
+# ltmain only uses $CC for tagged configurations so make sure $CC is set.
+_LT_TAG_COMPILER
+
+# save warnings/boilerplate of simple test code
+_LT_COMPILER_BOILERPLATE
+_LT_LINKER_BOILERPLATE
+
+# Allow CC to be a program name with arguments.
+lt_save_CC="$CC"
+lt_save_CFLAGS=$CFLAGS
+lt_save_GCC=$GCC
+GCC=
+CC=${RC-"windres"}
+CFLAGS=
+compiler=$CC
+_LT_TAGVAR(compiler, $1)=$CC
+_LT_CC_BASENAME([$compiler])
+_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=yes
+
+if test -n "$compiler"; then
+  :
+  _LT_CONFIG($1)
+fi
+
+GCC=$lt_save_GCC
+AC_LANG_RESTORE
+CC=$lt_save_CC
+CFLAGS=$lt_save_CFLAGS
+])# _LT_LANG_RC_CONFIG
+
+
+# LT_PROG_GCJ
+# -----------
+AC_DEFUN([LT_PROG_GCJ],
+[m4_ifdef([AC_PROG_GCJ], [AC_PROG_GCJ],
+  [m4_ifdef([A][M_PROG_GCJ], [A][M_PROG_GCJ],
+    [AC_CHECK_TOOL(GCJ, gcj,)
+      test "x${GCJFLAGS+set}" = xset || GCJFLAGS="-g -O2"
+      AC_SUBST(GCJFLAGS)])])[]dnl
+])
+
+# Old name:
+AU_ALIAS([LT_AC_PROG_GCJ], [LT_PROG_GCJ])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([LT_AC_PROG_GCJ], [])
+
+
+# LT_PROG_GO
+# ----------
+AC_DEFUN([LT_PROG_GO],
+[AC_CHECK_TOOL(GOC, gccgo,)
+])
+
+
+# LT_PROG_RC
+# ----------
+AC_DEFUN([LT_PROG_RC],
+[AC_CHECK_TOOL(RC, windres,)
+])
+
+# Old name:
+AU_ALIAS([LT_AC_PROG_RC], [LT_PROG_RC])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([LT_AC_PROG_RC], [])
+
+
+# _LT_DECL_EGREP
+# --------------
+# If we don't have a new enough Autoconf to choose the best grep
+# available, choose the one first in the user's PATH.
+m4_defun([_LT_DECL_EGREP],
+[AC_REQUIRE([AC_PROG_EGREP])dnl
+AC_REQUIRE([AC_PROG_FGREP])dnl
+test -z "$GREP" && GREP=grep
+_LT_DECL([], [GREP], [1], [A grep program that handles long lines])
+_LT_DECL([], [EGREP], [1], [An ERE matcher])
+_LT_DECL([], [FGREP], [1], [A literal string matcher])
+dnl Non-bleeding-edge autoconf doesn't subst GREP, so do it here too
+AC_SUBST([GREP])
+])
+
+
+# _LT_DECL_OBJDUMP
+# --------------
+# If we don't have a new enough Autoconf to choose the best objdump
+# available, choose the one first in the user's PATH.
+m4_defun([_LT_DECL_OBJDUMP],
+[AC_CHECK_TOOL(OBJDUMP, objdump, false)
+test -z "$OBJDUMP" && OBJDUMP=objdump
+_LT_DECL([], [OBJDUMP], [1], [An object symbol dumper])
+AC_SUBST([OBJDUMP])
+])
+
+# _LT_DECL_DLLTOOL
+# ----------------
+# Ensure DLLTOOL variable is set.
+m4_defun([_LT_DECL_DLLTOOL],
+[AC_CHECK_TOOL(DLLTOOL, dlltool, false)
+test -z "$DLLTOOL" && DLLTOOL=dlltool
+_LT_DECL([], [DLLTOOL], [1], [DLL creation program])
+AC_SUBST([DLLTOOL])
+])
+
+# _LT_DECL_SED
+# ------------
+# Check for a fully-functional sed program, that truncates
+# as few characters as possible.  Prefer GNU sed if found.
+m4_defun([_LT_DECL_SED],
+[AC_PROG_SED
+test -z "$SED" && SED=sed
+Xsed="$SED -e 1s/^X//"
+_LT_DECL([], [SED], [1], [A sed program that does not truncate output])
+_LT_DECL([], [Xsed], ["\$SED -e 1s/^X//"],
+    [Sed that helps us avoid accidentally triggering echo(1) options like -n])
+])# _LT_DECL_SED
+
+m4_ifndef([AC_PROG_SED], [
+# NOTE: This macro has been submitted for inclusion into   #
+#  GNU Autoconf as AC_PROG_SED.  When it is available in   #
+#  a released version of Autoconf we should remove this    #
+#  macro and use it instead.                               #
+
+m4_defun([AC_PROG_SED],
+[AC_MSG_CHECKING([for a sed that does not truncate output])
+AC_CACHE_VAL(lt_cv_path_SED,
+[# Loop through the user's path and test for sed and gsed.
+# Then use that list of sed's as ones to test for truncation.
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  for lt_ac_prog in sed gsed; do
+    for ac_exec_ext in '' $ac_executable_extensions; do
+      if $as_executable_p "$as_dir/$lt_ac_prog$ac_exec_ext"; then
+        lt_ac_sed_list="$lt_ac_sed_list $as_dir/$lt_ac_prog$ac_exec_ext"
+      fi
+    done
+  done
+done
+IFS=$as_save_IFS
+lt_ac_max=0
+lt_ac_count=0
+# Add /usr/xpg4/bin/sed as it is typically found on Solaris
+# along with /bin/sed that truncates output.
+for lt_ac_sed in $lt_ac_sed_list /usr/xpg4/bin/sed; do
+  test ! -f $lt_ac_sed && continue
+  cat /dev/null > conftest.in
+  lt_ac_count=0
+  echo $ECHO_N "0123456789$ECHO_C" >conftest.in
+  # Check for GNU sed and select it if it is found.
+  if "$lt_ac_sed" --version 2>&1 < /dev/null | grep 'GNU' > /dev/null; then
+    lt_cv_path_SED=$lt_ac_sed
+    break
+  fi
+  while true; do
+    cat conftest.in conftest.in >conftest.tmp
+    mv conftest.tmp conftest.in
+    cp conftest.in conftest.nl
+    echo >>conftest.nl
+    $lt_ac_sed -e 's/a$//' < conftest.nl >conftest.out || break
+    cmp -s conftest.out conftest.nl || break
+    # 10000 chars as input seems more than enough
+    test $lt_ac_count -gt 10 && break
+    lt_ac_count=`expr $lt_ac_count + 1`
+    if test $lt_ac_count -gt $lt_ac_max; then
+      lt_ac_max=$lt_ac_count
+      lt_cv_path_SED=$lt_ac_sed
+    fi
+  done
+done
+])
+SED=$lt_cv_path_SED
+AC_SUBST([SED])
+AC_MSG_RESULT([$SED])
+])#AC_PROG_SED
+])#m4_ifndef
+
+# Old name:
+AU_ALIAS([LT_AC_PROG_SED], [AC_PROG_SED])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([LT_AC_PROG_SED], [])
+
+
+# _LT_CHECK_SHELL_FEATURES
+# ------------------------
+# Find out whether the shell is Bourne or XSI compatible,
+# or has some other useful features.
+m4_defun([_LT_CHECK_SHELL_FEATURES],
+[AC_MSG_CHECKING([whether the shell understands some XSI constructs])
+# Try some XSI features
+xsi_shell=no
+( _lt_dummy="a/b/c"
+  test "${_lt_dummy##*/},${_lt_dummy%/*},${_lt_dummy#??}"${_lt_dummy%"$_lt_dummy"}, \
+      = c,a/b,b/c, \
+    && eval 'test $(( 1 + 1 )) -eq 2 \
+    && test "${#_lt_dummy}" -eq 5' ) >/dev/null 2>&1 \
+  && xsi_shell=yes
+AC_MSG_RESULT([$xsi_shell])
+_LT_CONFIG_LIBTOOL_INIT([xsi_shell='$xsi_shell'])
+
+AC_MSG_CHECKING([whether the shell understands "+="])
+lt_shell_append=no
+( foo=bar; set foo baz; eval "$[1]+=\$[2]" && test "$foo" = barbaz ) \
+    >/dev/null 2>&1 \
+  && lt_shell_append=yes
+AC_MSG_RESULT([$lt_shell_append])
+_LT_CONFIG_LIBTOOL_INIT([lt_shell_append='$lt_shell_append'])
+
+if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then
+  lt_unset=unset
+else
+  lt_unset=false
+fi
+_LT_DECL([], [lt_unset], [0], [whether the shell understands "unset"])dnl
+
+# test EBCDIC or ASCII
+case `echo X|tr X '\101'` in
+ A) # ASCII based system
+    # \n is not interpreted correctly by Solaris 8 /usr/ucb/tr
+  lt_SP2NL='tr \040 \012'
+  lt_NL2SP='tr \015\012 \040\040'
+  ;;
+ *) # EBCDIC based system
+  lt_SP2NL='tr \100 \n'
+  lt_NL2SP='tr \r\n \100\100'
+  ;;
+esac
+_LT_DECL([SP2NL], [lt_SP2NL], [1], [turn spaces into newlines])dnl
+_LT_DECL([NL2SP], [lt_NL2SP], [1], [turn newlines into spaces])dnl
+])# _LT_CHECK_SHELL_FEATURES
+
+
+# _LT_PROG_FUNCTION_REPLACE (FUNCNAME, REPLACEMENT-BODY)
+# ------------------------------------------------------
+# In `$cfgfile', look for function FUNCNAME delimited by `^FUNCNAME ()$' and
+# '^} FUNCNAME ', and replace its body with REPLACEMENT-BODY.
+m4_defun([_LT_PROG_FUNCTION_REPLACE],
+[dnl {
+sed -e '/^$1 ()$/,/^} # $1 /c\
+$1 ()\
+{\
+m4_bpatsubsts([$2], [$], [\\], [^\([	 ]\)], [\\\1])
+} # Extended-shell $1 implementation' "$cfgfile" > $cfgfile.tmp \
+  && mv -f "$cfgfile.tmp" "$cfgfile" \
+    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
+test 0 -eq $? || _lt_function_replace_fail=:
+])
+
+
+# _LT_PROG_REPLACE_SHELLFNS
+# -------------------------
+# Replace existing portable implementations of several shell functions with
+# equivalent extended shell implementations where those features are available..
+m4_defun([_LT_PROG_REPLACE_SHELLFNS],
+[if test x"$xsi_shell" = xyes; then
+  _LT_PROG_FUNCTION_REPLACE([func_dirname], [dnl
+    case ${1} in
+      */*) func_dirname_result="${1%/*}${2}" ;;
+      *  ) func_dirname_result="${3}" ;;
+    esac])
+
+  _LT_PROG_FUNCTION_REPLACE([func_basename], [dnl
+    func_basename_result="${1##*/}"])
+
+  _LT_PROG_FUNCTION_REPLACE([func_dirname_and_basename], [dnl
+    case ${1} in
+      */*) func_dirname_result="${1%/*}${2}" ;;
+      *  ) func_dirname_result="${3}" ;;
+    esac
+    func_basename_result="${1##*/}"])
+
+  _LT_PROG_FUNCTION_REPLACE([func_stripname], [dnl
+    # pdksh 5.2.14 does not do ${X%$Y} correctly if both X and Y are
+    # positional parameters, so assign one to ordinary parameter first.
+    func_stripname_result=${3}
+    func_stripname_result=${func_stripname_result#"${1}"}
+    func_stripname_result=${func_stripname_result%"${2}"}])
+
+  _LT_PROG_FUNCTION_REPLACE([func_split_long_opt], [dnl
+    func_split_long_opt_name=${1%%=*}
+    func_split_long_opt_arg=${1#*=}])
+
+  _LT_PROG_FUNCTION_REPLACE([func_split_short_opt], [dnl
+    func_split_short_opt_arg=${1#??}
+    func_split_short_opt_name=${1%"$func_split_short_opt_arg"}])
+
+  _LT_PROG_FUNCTION_REPLACE([func_lo2o], [dnl
+    case ${1} in
+      *.lo) func_lo2o_result=${1%.lo}.${objext} ;;
+      *)    func_lo2o_result=${1} ;;
+    esac])
+
+  _LT_PROG_FUNCTION_REPLACE([func_xform], [    func_xform_result=${1%.*}.lo])
+
+  _LT_PROG_FUNCTION_REPLACE([func_arith], [    func_arith_result=$(( $[*] ))])
+
+  _LT_PROG_FUNCTION_REPLACE([func_len], [    func_len_result=${#1}])
+fi
+
+if test x"$lt_shell_append" = xyes; then
+  _LT_PROG_FUNCTION_REPLACE([func_append], [    eval "${1}+=\\${2}"])
+
+  _LT_PROG_FUNCTION_REPLACE([func_append_quoted], [dnl
+    func_quote_for_eval "${2}"
+dnl m4 expansion turns \\\\ into \\, and then the shell eval turns that into \
+    eval "${1}+=\\\\ \\$func_quote_for_eval_result"])
+
+  # Save a `func_append' function call where possible by direct use of '+='
+  sed -e 's%func_append \([[a-zA-Z_]]\{1,\}\) "%\1+="%g' $cfgfile > $cfgfile.tmp \
+    && mv -f "$cfgfile.tmp" "$cfgfile" \
+      || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
+  test 0 -eq $? || _lt_function_replace_fail=:
+else
+  # Save a `func_append' function call even when '+=' is not available
+  sed -e 's%func_append \([[a-zA-Z_]]\{1,\}\) "%\1="$\1%g' $cfgfile > $cfgfile.tmp \
+    && mv -f "$cfgfile.tmp" "$cfgfile" \
+      || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
+  test 0 -eq $? || _lt_function_replace_fail=:
+fi
+
+if test x"$_lt_function_replace_fail" = x":"; then
+  AC_MSG_WARN([Unable to substitute extended shell functions in $ofile])
+fi
+])
+
+# _LT_PATH_CONVERSION_FUNCTIONS
+# -----------------------------
+# Determine which file name conversion functions should be used by
+# func_to_host_file (and, implicitly, by func_to_host_path).  These are needed
+# for certain cross-compile configurations and native mingw.
+m4_defun([_LT_PATH_CONVERSION_FUNCTIONS],
+[AC_REQUIRE([AC_CANONICAL_HOST])dnl
+AC_REQUIRE([AC_CANONICAL_BUILD])dnl
+AC_MSG_CHECKING([how to convert $build file names to $host format])
+AC_CACHE_VAL(lt_cv_to_host_file_cmd,
+[case $host in
+  *-*-mingw* )
+    case $build in
+      *-*-mingw* ) # actually msys
+        lt_cv_to_host_file_cmd=func_convert_file_msys_to_w32
+        ;;
+      *-*-cygwin* )
+        lt_cv_to_host_file_cmd=func_convert_file_cygwin_to_w32
+        ;;
+      * ) # otherwise, assume *nix
+        lt_cv_to_host_file_cmd=func_convert_file_nix_to_w32
+        ;;
+    esac
+    ;;
+  *-*-cygwin* )
+    case $build in
+      *-*-mingw* ) # actually msys
+        lt_cv_to_host_file_cmd=func_convert_file_msys_to_cygwin
+        ;;
+      *-*-cygwin* )
+        lt_cv_to_host_file_cmd=func_convert_file_noop
+        ;;
+      * ) # otherwise, assume *nix
+        lt_cv_to_host_file_cmd=func_convert_file_nix_to_cygwin
+        ;;
+    esac
+    ;;
+  * ) # unhandled hosts (and "normal" native builds)
+    lt_cv_to_host_file_cmd=func_convert_file_noop
+    ;;
+esac
+])
+to_host_file_cmd=$lt_cv_to_host_file_cmd
+AC_MSG_RESULT([$lt_cv_to_host_file_cmd])
+_LT_DECL([to_host_file_cmd], [lt_cv_to_host_file_cmd],
+         [0], [convert $build file names to $host format])dnl
+
+AC_MSG_CHECKING([how to convert $build file names to toolchain format])
+AC_CACHE_VAL(lt_cv_to_tool_file_cmd,
+[#assume ordinary cross tools, or native build.
+lt_cv_to_tool_file_cmd=func_convert_file_noop
+case $host in
+  *-*-mingw* )
+    case $build in
+      *-*-mingw* ) # actually msys
+        lt_cv_to_tool_file_cmd=func_convert_file_msys_to_w32
+        ;;
+    esac
+    ;;
+esac
+])
+to_tool_file_cmd=$lt_cv_to_tool_file_cmd
+AC_MSG_RESULT([$lt_cv_to_tool_file_cmd])
+_LT_DECL([to_tool_file_cmd], [lt_cv_to_tool_file_cmd],
+         [0], [convert $build files to toolchain format])dnl
+])# _LT_PATH_CONVERSION_FUNCTIONS
+
+# Helper functions for option handling.                    -*- Autoconf -*-
+#
+#   Copyright (C) 2004, 2005, 2007, 2008, 2009 Free Software Foundation,
+#   Inc.
+#   Written by Gary V. Vaughan, 2004
+#
+# This file is free software; the Free Software Foundation gives
+# unlimited permission to copy and/or distribute it, with or without
+# modifications, as long as this notice is preserved.
+
+# serial 7 ltoptions.m4
+
+# This is to help aclocal find these macros, as it can't see m4_define.
+AC_DEFUN([LTOPTIONS_VERSION], [m4_if([1])])
+
+
+# _LT_MANGLE_OPTION(MACRO-NAME, OPTION-NAME)
+# ------------------------------------------
+m4_define([_LT_MANGLE_OPTION],
+[[_LT_OPTION_]m4_bpatsubst($1__$2, [[^a-zA-Z0-9_]], [_])])
+
+
+# _LT_SET_OPTION(MACRO-NAME, OPTION-NAME)
+# ---------------------------------------
+# Set option OPTION-NAME for macro MACRO-NAME, and if there is a
+# matching handler defined, dispatch to it.  Other OPTION-NAMEs are
+# saved as a flag.
+m4_define([_LT_SET_OPTION],
+[m4_define(_LT_MANGLE_OPTION([$1], [$2]))dnl
+m4_ifdef(_LT_MANGLE_DEFUN([$1], [$2]),
+        _LT_MANGLE_DEFUN([$1], [$2]),
+    [m4_warning([Unknown $1 option `$2'])])[]dnl
+])
+
+
+# _LT_IF_OPTION(MACRO-NAME, OPTION-NAME, IF-SET, [IF-NOT-SET])
+# ------------------------------------------------------------
+# Execute IF-SET if OPTION is set, IF-NOT-SET otherwise.
+m4_define([_LT_IF_OPTION],
+[m4_ifdef(_LT_MANGLE_OPTION([$1], [$2]), [$3], [$4])])
+
+
+# _LT_UNLESS_OPTIONS(MACRO-NAME, OPTION-LIST, IF-NOT-SET)
+# -------------------------------------------------------
+# Execute IF-NOT-SET unless all options in OPTION-LIST for MACRO-NAME
+# are set.
+m4_define([_LT_UNLESS_OPTIONS],
+[m4_foreach([_LT_Option], m4_split(m4_normalize([$2])),
+	    [m4_ifdef(_LT_MANGLE_OPTION([$1], _LT_Option),
+		      [m4_define([$0_found])])])[]dnl
+m4_ifdef([$0_found], [m4_undefine([$0_found])], [$3
+])[]dnl
+])
+
+
+# _LT_SET_OPTIONS(MACRO-NAME, OPTION-LIST)
+# ----------------------------------------
+# OPTION-LIST is a space-separated list of Libtool options associated
+# with MACRO-NAME.  If any OPTION has a matching handler declared with
+# LT_OPTION_DEFINE, dispatch to that macro; otherwise complain about
+# the unknown option and exit.
+m4_defun([_LT_SET_OPTIONS],
+[# Set options
+m4_foreach([_LT_Option], m4_split(m4_normalize([$2])),
+    [_LT_SET_OPTION([$1], _LT_Option)])
+
+m4_if([$1],[LT_INIT],[
+  dnl
+  dnl Simply set some default values (i.e off) if boolean options were not
+  dnl specified:
+  _LT_UNLESS_OPTIONS([LT_INIT], [dlopen], [enable_dlopen=no
+  ])
+  _LT_UNLESS_OPTIONS([LT_INIT], [win32-dll], [enable_win32_dll=no
+  ])
+  dnl
+  dnl If no reference was made to various pairs of opposing options, then
+  dnl we run the default mode handler for the pair.  For example, if neither
+  dnl `shared' nor `disable-shared' was passed, we enable building of shared
+  dnl archives by default:
+  _LT_UNLESS_OPTIONS([LT_INIT], [shared disable-shared], [_LT_ENABLE_SHARED])
+  _LT_UNLESS_OPTIONS([LT_INIT], [static disable-static], [_LT_ENABLE_STATIC])
+  _LT_UNLESS_OPTIONS([LT_INIT], [pic-only no-pic], [_LT_WITH_PIC])
+  _LT_UNLESS_OPTIONS([LT_INIT], [fast-install disable-fast-install],
+  		   [_LT_ENABLE_FAST_INSTALL])
+  ])
+])# _LT_SET_OPTIONS
+
+
+
+# _LT_MANGLE_DEFUN(MACRO-NAME, OPTION-NAME)
+# -----------------------------------------
+m4_define([_LT_MANGLE_DEFUN],
+[[_LT_OPTION_DEFUN_]m4_bpatsubst(m4_toupper([$1__$2]), [[^A-Z0-9_]], [_])])
+
+
+# LT_OPTION_DEFINE(MACRO-NAME, OPTION-NAME, CODE)
+# -----------------------------------------------
+m4_define([LT_OPTION_DEFINE],
+[m4_define(_LT_MANGLE_DEFUN([$1], [$2]), [$3])[]dnl
+])# LT_OPTION_DEFINE
+
+
+# dlopen
+# ------
+LT_OPTION_DEFINE([LT_INIT], [dlopen], [enable_dlopen=yes
+])
+
+AU_DEFUN([AC_LIBTOOL_DLOPEN],
+[_LT_SET_OPTION([LT_INIT], [dlopen])
+AC_DIAGNOSE([obsolete],
+[$0: Remove this warning and the call to _LT_SET_OPTION when you
+put the `dlopen' option into LT_INIT's first parameter.])
+])
+
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_LIBTOOL_DLOPEN], [])
+
+
+# win32-dll
+# ---------
+# Declare package support for building win32 dll's.
+LT_OPTION_DEFINE([LT_INIT], [win32-dll],
+[enable_win32_dll=yes
+
+case $host in
+*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-cegcc*)
+  AC_CHECK_TOOL(AS, as, false)
+  AC_CHECK_TOOL(DLLTOOL, dlltool, false)
+  AC_CHECK_TOOL(OBJDUMP, objdump, false)
+  ;;
+esac
+
+test -z "$AS" && AS=as
+_LT_DECL([], [AS],      [1], [Assembler program])dnl
+
+test -z "$DLLTOOL" && DLLTOOL=dlltool
+_LT_DECL([], [DLLTOOL], [1], [DLL creation program])dnl
+
+test -z "$OBJDUMP" && OBJDUMP=objdump
+_LT_DECL([], [OBJDUMP], [1], [Object dumper program])dnl
+])# win32-dll
+
+AU_DEFUN([AC_LIBTOOL_WIN32_DLL],
+[AC_REQUIRE([AC_CANONICAL_HOST])dnl
+_LT_SET_OPTION([LT_INIT], [win32-dll])
+AC_DIAGNOSE([obsolete],
+[$0: Remove this warning and the call to _LT_SET_OPTION when you
+put the `win32-dll' option into LT_INIT's first parameter.])
+])
+
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_LIBTOOL_WIN32_DLL], [])
+
+
+# _LT_ENABLE_SHARED([DEFAULT])
+# ----------------------------
+# implement the --enable-shared flag, and supports the `shared' and
+# `disable-shared' LT_INIT options.
+# DEFAULT is either `yes' or `no'.  If omitted, it defaults to `yes'.
+m4_define([_LT_ENABLE_SHARED],
+[m4_define([_LT_ENABLE_SHARED_DEFAULT], [m4_if($1, no, no, yes)])dnl
+AC_ARG_ENABLE([shared],
+    [AS_HELP_STRING([--enable-shared@<:@=PKGS@:>@],
+	[build shared libraries @<:@default=]_LT_ENABLE_SHARED_DEFAULT[@:>@])],
+    [p=${PACKAGE-default}
+    case $enableval in
+    yes) enable_shared=yes ;;
+    no) enable_shared=no ;;
+    *)
+      enable_shared=no
+      # Look at the argument we got.  We use all the common list separators.
+      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
+      for pkg in $enableval; do
+	IFS="$lt_save_ifs"
+	if test "X$pkg" = "X$p"; then
+	  enable_shared=yes
+	fi
+      done
+      IFS="$lt_save_ifs"
+      ;;
+    esac],
+    [enable_shared=]_LT_ENABLE_SHARED_DEFAULT)
+
+    _LT_DECL([build_libtool_libs], [enable_shared], [0],
+	[Whether or not to build shared libraries])
+])# _LT_ENABLE_SHARED
+
+LT_OPTION_DEFINE([LT_INIT], [shared], [_LT_ENABLE_SHARED([yes])])
+LT_OPTION_DEFINE([LT_INIT], [disable-shared], [_LT_ENABLE_SHARED([no])])
+
+# Old names:
+AC_DEFUN([AC_ENABLE_SHARED],
+[_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[shared])
+])
+
+AC_DEFUN([AC_DISABLE_SHARED],
+[_LT_SET_OPTION([LT_INIT], [disable-shared])
+])
+
+AU_DEFUN([AM_ENABLE_SHARED], [AC_ENABLE_SHARED($@)])
+AU_DEFUN([AM_DISABLE_SHARED], [AC_DISABLE_SHARED($@)])
+
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AM_ENABLE_SHARED], [])
+dnl AC_DEFUN([AM_DISABLE_SHARED], [])
+
+
+
+# _LT_ENABLE_STATIC([DEFAULT])
+# ----------------------------
+# implement the --enable-static flag, and support the `static' and
+# `disable-static' LT_INIT options.
+# DEFAULT is either `yes' or `no'.  If omitted, it defaults to `yes'.
+m4_define([_LT_ENABLE_STATIC],
+[m4_define([_LT_ENABLE_STATIC_DEFAULT], [m4_if($1, no, no, yes)])dnl
+AC_ARG_ENABLE([static],
+    [AS_HELP_STRING([--enable-static@<:@=PKGS@:>@],
+	[build static libraries @<:@default=]_LT_ENABLE_STATIC_DEFAULT[@:>@])],
+    [p=${PACKAGE-default}
+    case $enableval in
+    yes) enable_static=yes ;;
+    no) enable_static=no ;;
+    *)
+     enable_static=no
+      # Look at the argument we got.  We use all the common list separators.
+      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
+      for pkg in $enableval; do
+	IFS="$lt_save_ifs"
+	if test "X$pkg" = "X$p"; then
+	  enable_static=yes
+	fi
+      done
+      IFS="$lt_save_ifs"
+      ;;
+    esac],
+    [enable_static=]_LT_ENABLE_STATIC_DEFAULT)
+
+    _LT_DECL([build_old_libs], [enable_static], [0],
+	[Whether or not to build static libraries])
+])# _LT_ENABLE_STATIC
+
+LT_OPTION_DEFINE([LT_INIT], [static], [_LT_ENABLE_STATIC([yes])])
+LT_OPTION_DEFINE([LT_INIT], [disable-static], [_LT_ENABLE_STATIC([no])])
+
+# Old names:
+AC_DEFUN([AC_ENABLE_STATIC],
+[_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[static])
+])
+
+AC_DEFUN([AC_DISABLE_STATIC],
+[_LT_SET_OPTION([LT_INIT], [disable-static])
+])
+
+AU_DEFUN([AM_ENABLE_STATIC], [AC_ENABLE_STATIC($@)])
+AU_DEFUN([AM_DISABLE_STATIC], [AC_DISABLE_STATIC($@)])
+
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AM_ENABLE_STATIC], [])
+dnl AC_DEFUN([AM_DISABLE_STATIC], [])
+
+
+
+# _LT_ENABLE_FAST_INSTALL([DEFAULT])
+# ----------------------------------
+# implement the --enable-fast-install flag, and support the `fast-install'
+# and `disable-fast-install' LT_INIT options.
+# DEFAULT is either `yes' or `no'.  If omitted, it defaults to `yes'.
+m4_define([_LT_ENABLE_FAST_INSTALL],
+[m4_define([_LT_ENABLE_FAST_INSTALL_DEFAULT], [m4_if($1, no, no, yes)])dnl
+AC_ARG_ENABLE([fast-install],
+    [AS_HELP_STRING([--enable-fast-install@<:@=PKGS@:>@],
+    [optimize for fast installation @<:@default=]_LT_ENABLE_FAST_INSTALL_DEFAULT[@:>@])],
+    [p=${PACKAGE-default}
+    case $enableval in
+    yes) enable_fast_install=yes ;;
+    no) enable_fast_install=no ;;
+    *)
+      enable_fast_install=no
+      # Look at the argument we got.  We use all the common list separators.
+      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
+      for pkg in $enableval; do
+	IFS="$lt_save_ifs"
+	if test "X$pkg" = "X$p"; then
+	  enable_fast_install=yes
+	fi
+      done
+      IFS="$lt_save_ifs"
+      ;;
+    esac],
+    [enable_fast_install=]_LT_ENABLE_FAST_INSTALL_DEFAULT)
+
+_LT_DECL([fast_install], [enable_fast_install], [0],
+	 [Whether or not to optimize for fast installation])dnl
+])# _LT_ENABLE_FAST_INSTALL
+
+LT_OPTION_DEFINE([LT_INIT], [fast-install], [_LT_ENABLE_FAST_INSTALL([yes])])
+LT_OPTION_DEFINE([LT_INIT], [disable-fast-install], [_LT_ENABLE_FAST_INSTALL([no])])
+
+# Old names:
+AU_DEFUN([AC_ENABLE_FAST_INSTALL],
+[_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[fast-install])
+AC_DIAGNOSE([obsolete],
+[$0: Remove this warning and the call to _LT_SET_OPTION when you put
+the `fast-install' option into LT_INIT's first parameter.])
+])
+
+AU_DEFUN([AC_DISABLE_FAST_INSTALL],
+[_LT_SET_OPTION([LT_INIT], [disable-fast-install])
+AC_DIAGNOSE([obsolete],
+[$0: Remove this warning and the call to _LT_SET_OPTION when you put
+the `disable-fast-install' option into LT_INIT's first parameter.])
+])
+
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_ENABLE_FAST_INSTALL], [])
+dnl AC_DEFUN([AM_DISABLE_FAST_INSTALL], [])
+
+
+# _LT_WITH_PIC([MODE])
+# --------------------
+# implement the --with-pic flag, and support the `pic-only' and `no-pic'
+# LT_INIT options.
+# MODE is either `yes' or `no'.  If omitted, it defaults to `both'.
+m4_define([_LT_WITH_PIC],
+[AC_ARG_WITH([pic],
+    [AS_HELP_STRING([--with-pic@<:@=PKGS@:>@],
+	[try to use only PIC/non-PIC objects @<:@default=use both@:>@])],
+    [lt_p=${PACKAGE-default}
+    case $withval in
+    yes|no) pic_mode=$withval ;;
+    *)
+      pic_mode=default
+      # Look at the argument we got.  We use all the common list separators.
+      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
+      for lt_pkg in $withval; do
+	IFS="$lt_save_ifs"
+	if test "X$lt_pkg" = "X$lt_p"; then
+	  pic_mode=yes
+	fi
+      done
+      IFS="$lt_save_ifs"
+      ;;
+    esac],
+    [pic_mode=default])
+
+test -z "$pic_mode" && pic_mode=m4_default([$1], [default])
+
+_LT_DECL([], [pic_mode], [0], [What type of objects to build])dnl
+])# _LT_WITH_PIC
+
+LT_OPTION_DEFINE([LT_INIT], [pic-only], [_LT_WITH_PIC([yes])])
+LT_OPTION_DEFINE([LT_INIT], [no-pic], [_LT_WITH_PIC([no])])
+
+# Old name:
+AU_DEFUN([AC_LIBTOOL_PICMODE],
+[_LT_SET_OPTION([LT_INIT], [pic-only])
+AC_DIAGNOSE([obsolete],
+[$0: Remove this warning and the call to _LT_SET_OPTION when you
+put the `pic-only' option into LT_INIT's first parameter.])
+])
+
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_LIBTOOL_PICMODE], [])
+
+
+m4_define([_LTDL_MODE], [])
+LT_OPTION_DEFINE([LTDL_INIT], [nonrecursive],
+		 [m4_define([_LTDL_MODE], [nonrecursive])])
+LT_OPTION_DEFINE([LTDL_INIT], [recursive],
+		 [m4_define([_LTDL_MODE], [recursive])])
+LT_OPTION_DEFINE([LTDL_INIT], [subproject],
+		 [m4_define([_LTDL_MODE], [subproject])])
+
+m4_define([_LTDL_TYPE], [])
+LT_OPTION_DEFINE([LTDL_INIT], [installable],
+		 [m4_define([_LTDL_TYPE], [installable])])
+LT_OPTION_DEFINE([LTDL_INIT], [convenience],
+		 [m4_define([_LTDL_TYPE], [convenience])])
+
+# ltsugar.m4 -- libtool m4 base layer.                         -*-Autoconf-*-
+#
+# Copyright (C) 2004, 2005, 2007, 2008 Free Software Foundation, Inc.
+# Written by Gary V. Vaughan, 2004
+#
+# This file is free software; the Free Software Foundation gives
+# unlimited permission to copy and/or distribute it, with or without
+# modifications, as long as this notice is preserved.
+
+# serial 6 ltsugar.m4
+
+# This is to help aclocal find these macros, as it can't see m4_define.
+AC_DEFUN([LTSUGAR_VERSION], [m4_if([0.1])])
+
+
+# lt_join(SEP, ARG1, [ARG2...])
+# -----------------------------
+# Produce ARG1SEPARG2...SEPARGn, omitting [] arguments and their
+# associated separator.
+# Needed until we can rely on m4_join from Autoconf 2.62, since all earlier
+# versions in m4sugar had bugs.
+m4_define([lt_join],
+[m4_if([$#], [1], [],
+       [$#], [2], [[$2]],
+       [m4_if([$2], [], [], [[$2]_])$0([$1], m4_shift(m4_shift($@)))])])
+m4_define([_lt_join],
+[m4_if([$#$2], [2], [],
+       [m4_if([$2], [], [], [[$1$2]])$0([$1], m4_shift(m4_shift($@)))])])
+
+
+# lt_car(LIST)
+# lt_cdr(LIST)
+# ------------
+# Manipulate m4 lists.
+# These macros are necessary as long as will still need to support
+# Autoconf-2.59 which quotes differently.
+m4_define([lt_car], [[$1]])
+m4_define([lt_cdr],
+[m4_if([$#], 0, [m4_fatal([$0: cannot be called without arguments])],
+       [$#], 1, [],
+       [m4_dquote(m4_shift($@))])])
+m4_define([lt_unquote], $1)
+
+
+# lt_append(MACRO-NAME, STRING, [SEPARATOR])
+# ------------------------------------------
+# Redefine MACRO-NAME to hold its former content plus `SEPARATOR'`STRING'.
+# Note that neither SEPARATOR nor STRING are expanded; they are appended
+# to MACRO-NAME as is (leaving the expansion for when MACRO-NAME is invoked).
+# No SEPARATOR is output if MACRO-NAME was previously undefined (different
+# than defined and empty).
+#
+# This macro is needed until we can rely on Autoconf 2.62, since earlier
+# versions of m4sugar mistakenly expanded SEPARATOR but not STRING.
+m4_define([lt_append],
+[m4_define([$1],
+	   m4_ifdef([$1], [m4_defn([$1])[$3]])[$2])])
+
+
+
+# lt_combine(SEP, PREFIX-LIST, INFIX, SUFFIX1, [SUFFIX2...])
+# ----------------------------------------------------------
+# Produce a SEP delimited list of all paired combinations of elements of
+# PREFIX-LIST with SUFFIX1 through SUFFIXn.  Each element of the list
+# has the form PREFIXmINFIXSUFFIXn.
+# Needed until we can rely on m4_combine added in Autoconf 2.62.
+m4_define([lt_combine],
+[m4_if(m4_eval([$# > 3]), [1],
+       [m4_pushdef([_Lt_sep], [m4_define([_Lt_sep], m4_defn([lt_car]))])]]dnl
+[[m4_foreach([_Lt_prefix], [$2],
+	     [m4_foreach([_Lt_suffix],
+		]m4_dquote(m4_dquote(m4_shift(m4_shift(m4_shift($@)))))[,
+	[_Lt_sep([$1])[]m4_defn([_Lt_prefix])[$3]m4_defn([_Lt_suffix])])])])])
+
+
+# lt_if_append_uniq(MACRO-NAME, VARNAME, [SEPARATOR], [UNIQ], [NOT-UNIQ])
+# -----------------------------------------------------------------------
+# Iff MACRO-NAME does not yet contain VARNAME, then append it (delimited
+# by SEPARATOR if supplied) and expand UNIQ, else NOT-UNIQ.
+m4_define([lt_if_append_uniq],
+[m4_ifdef([$1],
+	  [m4_if(m4_index([$3]m4_defn([$1])[$3], [$3$2$3]), [-1],
+		 [lt_append([$1], [$2], [$3])$4],
+		 [$5])],
+	  [lt_append([$1], [$2], [$3])$4])])
+
+
+# lt_dict_add(DICT, KEY, VALUE)
+# -----------------------------
+m4_define([lt_dict_add],
+[m4_define([$1($2)], [$3])])
+
+
+# lt_dict_add_subkey(DICT, KEY, SUBKEY, VALUE)
+# --------------------------------------------
+m4_define([lt_dict_add_subkey],
+[m4_define([$1($2:$3)], [$4])])
+
+
+# lt_dict_fetch(DICT, KEY, [SUBKEY])
+# ----------------------------------
+m4_define([lt_dict_fetch],
+[m4_ifval([$3],
+	m4_ifdef([$1($2:$3)], [m4_defn([$1($2:$3)])]),
+    m4_ifdef([$1($2)], [m4_defn([$1($2)])]))])
+
+
+# lt_if_dict_fetch(DICT, KEY, [SUBKEY], VALUE, IF-TRUE, [IF-FALSE])
+# -----------------------------------------------------------------
+m4_define([lt_if_dict_fetch],
+[m4_if(lt_dict_fetch([$1], [$2], [$3]), [$4],
+	[$5],
+    [$6])])
+
+
+# lt_dict_filter(DICT, [SUBKEY], VALUE, [SEPARATOR], KEY, [...])
+# --------------------------------------------------------------
+m4_define([lt_dict_filter],
+[m4_if([$5], [], [],
+  [lt_join(m4_quote(m4_default([$4], [[, ]])),
+           lt_unquote(m4_split(m4_normalize(m4_foreach(_Lt_key, lt_car([m4_shiftn(4, $@)]),
+		      [lt_if_dict_fetch([$1], _Lt_key, [$2], [$3], [_Lt_key ])])))))])[]dnl
+])
+
+# ltversion.m4 -- version numbers			-*- Autoconf -*-
+#
+#   Copyright (C) 2004 Free Software Foundation, Inc.
+#   Written by Scott James Remnant, 2004
+#
+# This file is free software; the Free Software Foundation gives
+# unlimited permission to copy and/or distribute it, with or without
+# modifications, as long as this notice is preserved.
+
+# @configure_input@
+
+# serial 3337 ltversion.m4
+# This file is part of GNU Libtool
+
+m4_define([LT_PACKAGE_VERSION], [2.4.2])
+m4_define([LT_PACKAGE_REVISION], [1.3337])
+
+AC_DEFUN([LTVERSION_VERSION],
+[macro_version='2.4.2'
+macro_revision='1.3337'
+_LT_DECL(, macro_version, 0, [Which release of libtool.m4 was used?])
+_LT_DECL(, macro_revision, 0)
+])
+
+# lt~obsolete.m4 -- aclocal satisfying obsolete definitions.    -*-Autoconf-*-
+#
+#   Copyright (C) 2004, 2005, 2007, 2009 Free Software Foundation, Inc.
+#   Written by Scott James Remnant, 2004.
+#
+# This file is free software; the Free Software Foundation gives
+# unlimited permission to copy and/or distribute it, with or without
+# modifications, as long as this notice is preserved.
+
+# serial 5 lt~obsolete.m4
+
+# These exist entirely to fool aclocal when bootstrapping libtool.
+#
+# In the past libtool.m4 has provided macros via AC_DEFUN (or AU_DEFUN)
+# which have later been changed to m4_define as they aren't part of the
+# exported API, or moved to Autoconf or Automake where they belong.
+#
+# The trouble is, aclocal is a bit thick.  It'll see the old AC_DEFUN
+# in /usr/share/aclocal/libtool.m4 and remember it, then when it sees us
+# using a macro with the same name in our local m4/libtool.m4 it'll
+# pull the old libtool.m4 in (it doesn't see our shiny new m4_define
+# and doesn't know about Autoconf macros at all.)
+#
+# So we provide this file, which has a silly filename so it's always
+# included after everything else.  This provides aclocal with the
+# AC_DEFUNs it wants, but when m4 processes it, it doesn't do anything
+# because those macros already exist, or will be overwritten later.
+# We use AC_DEFUN over AU_DEFUN for compatibility with aclocal-1.6. 
+#
+# Anytime we withdraw an AC_DEFUN or AU_DEFUN, remember to add it here.
+# Yes, that means every name once taken will need to remain here until
+# we give up compatibility with versions before 1.7, at which point
+# we need to keep only those names which we still refer to.
+
+# This is to help aclocal find these macros, as it can't see m4_define.
+AC_DEFUN([LTOBSOLETE_VERSION], [m4_if([1])])
+
+m4_ifndef([AC_LIBTOOL_LINKER_OPTION],	[AC_DEFUN([AC_LIBTOOL_LINKER_OPTION])])
+m4_ifndef([AC_PROG_EGREP],		[AC_DEFUN([AC_PROG_EGREP])])
+m4_ifndef([_LT_AC_PROG_ECHO_BACKSLASH],	[AC_DEFUN([_LT_AC_PROG_ECHO_BACKSLASH])])
+m4_ifndef([_LT_AC_SHELL_INIT],		[AC_DEFUN([_LT_AC_SHELL_INIT])])
+m4_ifndef([_LT_AC_SYS_LIBPATH_AIX],	[AC_DEFUN([_LT_AC_SYS_LIBPATH_AIX])])
+m4_ifndef([_LT_PROG_LTMAIN],		[AC_DEFUN([_LT_PROG_LTMAIN])])
+m4_ifndef([_LT_AC_TAGVAR],		[AC_DEFUN([_LT_AC_TAGVAR])])
+m4_ifndef([AC_LTDL_ENABLE_INSTALL],	[AC_DEFUN([AC_LTDL_ENABLE_INSTALL])])
+m4_ifndef([AC_LTDL_PREOPEN],		[AC_DEFUN([AC_LTDL_PREOPEN])])
+m4_ifndef([_LT_AC_SYS_COMPILER],	[AC_DEFUN([_LT_AC_SYS_COMPILER])])
+m4_ifndef([_LT_AC_LOCK],		[AC_DEFUN([_LT_AC_LOCK])])
+m4_ifndef([AC_LIBTOOL_SYS_OLD_ARCHIVE],	[AC_DEFUN([AC_LIBTOOL_SYS_OLD_ARCHIVE])])
+m4_ifndef([_LT_AC_TRY_DLOPEN_SELF],	[AC_DEFUN([_LT_AC_TRY_DLOPEN_SELF])])
+m4_ifndef([AC_LIBTOOL_PROG_CC_C_O],	[AC_DEFUN([AC_LIBTOOL_PROG_CC_C_O])])
+m4_ifndef([AC_LIBTOOL_SYS_HARD_LINK_LOCKS], [AC_DEFUN([AC_LIBTOOL_SYS_HARD_LINK_LOCKS])])
+m4_ifndef([AC_LIBTOOL_OBJDIR],		[AC_DEFUN([AC_LIBTOOL_OBJDIR])])
+m4_ifndef([AC_LTDL_OBJDIR],		[AC_DEFUN([AC_LTDL_OBJDIR])])
+m4_ifndef([AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH], [AC_DEFUN([AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH])])
+m4_ifndef([AC_LIBTOOL_SYS_LIB_STRIP],	[AC_DEFUN([AC_LIBTOOL_SYS_LIB_STRIP])])
+m4_ifndef([AC_PATH_MAGIC],		[AC_DEFUN([AC_PATH_MAGIC])])
+m4_ifndef([AC_PROG_LD_GNU],		[AC_DEFUN([AC_PROG_LD_GNU])])
+m4_ifndef([AC_PROG_LD_RELOAD_FLAG],	[AC_DEFUN([AC_PROG_LD_RELOAD_FLAG])])
+m4_ifndef([AC_DEPLIBS_CHECK_METHOD],	[AC_DEFUN([AC_DEPLIBS_CHECK_METHOD])])
+m4_ifndef([AC_LIBTOOL_PROG_COMPILER_NO_RTTI], [AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_NO_RTTI])])
+m4_ifndef([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE], [AC_DEFUN([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE])])
+m4_ifndef([AC_LIBTOOL_PROG_COMPILER_PIC], [AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_PIC])])
+m4_ifndef([AC_LIBTOOL_PROG_LD_SHLIBS],	[AC_DEFUN([AC_LIBTOOL_PROG_LD_SHLIBS])])
+m4_ifndef([AC_LIBTOOL_POSTDEP_PREDEP],	[AC_DEFUN([AC_LIBTOOL_POSTDEP_PREDEP])])
+m4_ifndef([LT_AC_PROG_EGREP],		[AC_DEFUN([LT_AC_PROG_EGREP])])
+m4_ifndef([LT_AC_PROG_SED],		[AC_DEFUN([LT_AC_PROG_SED])])
+m4_ifndef([_LT_CC_BASENAME],		[AC_DEFUN([_LT_CC_BASENAME])])
+m4_ifndef([_LT_COMPILER_BOILERPLATE],	[AC_DEFUN([_LT_COMPILER_BOILERPLATE])])
+m4_ifndef([_LT_LINKER_BOILERPLATE],	[AC_DEFUN([_LT_LINKER_BOILERPLATE])])
+m4_ifndef([_AC_PROG_LIBTOOL],		[AC_DEFUN([_AC_PROG_LIBTOOL])])
+m4_ifndef([AC_LIBTOOL_SETUP],		[AC_DEFUN([AC_LIBTOOL_SETUP])])
+m4_ifndef([_LT_AC_CHECK_DLFCN],		[AC_DEFUN([_LT_AC_CHECK_DLFCN])])
+m4_ifndef([AC_LIBTOOL_SYS_DYNAMIC_LINKER],	[AC_DEFUN([AC_LIBTOOL_SYS_DYNAMIC_LINKER])])
+m4_ifndef([_LT_AC_TAGCONFIG],		[AC_DEFUN([_LT_AC_TAGCONFIG])])
+m4_ifndef([AC_DISABLE_FAST_INSTALL],	[AC_DEFUN([AC_DISABLE_FAST_INSTALL])])
+m4_ifndef([_LT_AC_LANG_CXX],		[AC_DEFUN([_LT_AC_LANG_CXX])])
+m4_ifndef([_LT_AC_LANG_F77],		[AC_DEFUN([_LT_AC_LANG_F77])])
+m4_ifndef([_LT_AC_LANG_GCJ],		[AC_DEFUN([_LT_AC_LANG_GCJ])])
+m4_ifndef([AC_LIBTOOL_LANG_C_CONFIG],	[AC_DEFUN([AC_LIBTOOL_LANG_C_CONFIG])])
+m4_ifndef([_LT_AC_LANG_C_CONFIG],	[AC_DEFUN([_LT_AC_LANG_C_CONFIG])])
+m4_ifndef([AC_LIBTOOL_LANG_CXX_CONFIG],	[AC_DEFUN([AC_LIBTOOL_LANG_CXX_CONFIG])])
+m4_ifndef([_LT_AC_LANG_CXX_CONFIG],	[AC_DEFUN([_LT_AC_LANG_CXX_CONFIG])])
+m4_ifndef([AC_LIBTOOL_LANG_F77_CONFIG],	[AC_DEFUN([AC_LIBTOOL_LANG_F77_CONFIG])])
+m4_ifndef([_LT_AC_LANG_F77_CONFIG],	[AC_DEFUN([_LT_AC_LANG_F77_CONFIG])])
+m4_ifndef([AC_LIBTOOL_LANG_GCJ_CONFIG],	[AC_DEFUN([AC_LIBTOOL_LANG_GCJ_CONFIG])])
+m4_ifndef([_LT_AC_LANG_GCJ_CONFIG],	[AC_DEFUN([_LT_AC_LANG_GCJ_CONFIG])])
+m4_ifndef([AC_LIBTOOL_LANG_RC_CONFIG],	[AC_DEFUN([AC_LIBTOOL_LANG_RC_CONFIG])])
+m4_ifndef([_LT_AC_LANG_RC_CONFIG],	[AC_DEFUN([_LT_AC_LANG_RC_CONFIG])])
+m4_ifndef([AC_LIBTOOL_CONFIG],		[AC_DEFUN([AC_LIBTOOL_CONFIG])])
+m4_ifndef([_LT_AC_FILE_LTDLL_C],	[AC_DEFUN([_LT_AC_FILE_LTDLL_C])])
+m4_ifndef([_LT_REQUIRED_DARWIN_CHECKS],	[AC_DEFUN([_LT_REQUIRED_DARWIN_CHECKS])])
+m4_ifndef([_LT_AC_PROG_CXXCPP],		[AC_DEFUN([_LT_AC_PROG_CXXCPP])])
+m4_ifndef([_LT_PREPARE_SED_QUOTE_VARS],	[AC_DEFUN([_LT_PREPARE_SED_QUOTE_VARS])])
+m4_ifndef([_LT_PROG_ECHO_BACKSLASH],	[AC_DEFUN([_LT_PROG_ECHO_BACKSLASH])])
+m4_ifndef([_LT_PROG_F77],		[AC_DEFUN([_LT_PROG_F77])])
+m4_ifndef([_LT_PROG_FC],		[AC_DEFUN([_LT_PROG_FC])])
+m4_ifndef([_LT_PROG_CXX],		[AC_DEFUN([_LT_PROG_CXX])])
 
diff --git a/astyle.sh b/astyle.sh
new file mode 100755
index 0000000..4b6d301
--- /dev/null
+++ b/astyle.sh
@@ -0,0 +1,10 @@
+#!/bin/bash
+
+ASTYLEOPTS="--style=kr --indent=spaces=2 -c --lineend=linux -S"
+ASTYLEBIN=astyle
+
+$ASTYLEBIN $ASTYLEOPTS *.c *.h *.cpp opengl/*.h
+$ASTYLEBIN $ASTYLEOPTS -R 'mapscript/*.c'
+$ASTYLEBIN $ASTYLEOPTS -R 'mapscript/*.h'
+
+#find . -name '*.orig' -exec rm -f {} \;
diff --git a/cgiutil.c b/cgiutil.c
index 1530b81..ac8a828 100644
--- a/cgiutil.c
+++ b/cgiutil.c
@@ -2,7 +2,7 @@
  * $Id$
  *
  * Project:  MapServer
- * Purpose:  cgiRequestObj and CGI parameter parsing. 
+ * Purpose:  cgiRequestObj and CGI parameter parsing.
  * Author:   Steve Lime and the MapServer team.
  *
  * Notes: Portions derived from NCSA HTTPd Server's example CGI programs (util.c).
@@ -17,7 +17,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -32,18 +32,17 @@
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
-#include <ctype.h> 
+#include <ctype.h>
 #include "mapserver.h"
 #include "cgiutil.h"
 
-MS_CVSID("$Id$")
+
 
 #define LF 10
 #define CR 13
 
-static char *readPostBody( cgiRequestObj *request ) 
+int readPostBody( cgiRequestObj *request, char **data )
 {
-  char *data; 
   size_t data_max, data_len;
   int chunk_size;
 
@@ -56,25 +55,28 @@ static char *readPostBody( cgiRequestObj *request )
     data_max = (size_t) atoi(getenv("CONTENT_LENGTH"));
     /* Test for suspicious CONTENT_LENGTH (negative value or SIZE_MAX) */
     if( data_max >= SIZE_MAX ) {
-      msIO_printf("Content-type: text/html%c%c",10,10);
+      msIO_setHeader("Content-Type","text/html");
+      msIO_sendHeaders();
       msIO_printf("Suspicious Content-Length.\n");
-      exit( 1 );
+      return MS_FAILURE;
     }
-    data = (char *) malloc(data_max+1);
-    if( data == NULL ) {
-      msIO_printf("Content-type: text/html%c%c",10,10);
+    *data = (char *) malloc(data_max+1);
+    if( *data == NULL ) {
+      msIO_setHeader("Content-Type","text/html");
+      msIO_sendHeaders();
       msIO_printf("malloc() failed, Content-Length: %u unreasonably large?\n", data_max );
-      exit( 1 );
+      return MS_FAILURE;
     }
 
-    if( (int) msIO_fread(data, 1, data_max, stdin) < data_max ) {
-      msIO_printf("Content-type: text/html%c%c",10,10);
+    if( (int) msIO_fread(*data, 1, data_max, stdin) < data_max ) {
+      msIO_setHeader("Content-Type","text/html");
+      msIO_sendHeaders();
       msIO_printf("POST body is short\n");
-      exit(1);
+      return MS_FAILURE;
     }
 
-    data[data_max] = '\0';
-    return data;
+    (*data)[data_max] = '\0';
+    return MS_SUCCESS;
   }
   /* -------------------------------------------------------------------- */
   /*      Otherwise read in chunks to the end.                            */
@@ -83,107 +85,89 @@ static char *readPostBody( cgiRequestObj *request )
 
   data_max = DATA_ALLOC_SIZE;
   data_len = 0;
-  data = (char *) malloc(data_max+1);
-  if (data == NULL) {
-    msIO_printf("Content-type: text/html%c%c",10,10);
-    msIO_printf("Out of memory allocating %u bytes.\n", data_max+1);
-    exit(1);
-  }
+  *data = (char *) msSmallMalloc(data_max+1);
 
-  while( (chunk_size = msIO_fread( data + data_len, 1, data_max-data_len, stdin )) > 0 ) {
+  while( (chunk_size = msIO_fread( *data + data_len, 1, data_max-data_len, stdin )) > 0 ) {
     data_len += chunk_size;
 
     if( data_len == data_max ) {
       /* Realloc buffer, making sure we check for possible size_t overflow */
-        if ( data_max > SIZE_MAX - (DATA_ALLOC_SIZE+1) ) {
-        msIO_printf("Content-type: text/html%c%c",10,10);
+      if ( data_max > SIZE_MAX - (DATA_ALLOC_SIZE+1) ) {
+        msIO_setHeader("Content-Type","text/html");
+        msIO_sendHeaders();
         msIO_printf("Possible size_t overflow, cannot reallocate input buffer, POST body too large?\n" );
-        exit(1);
+        return MS_FAILURE;
       }
 
       data_max = data_max + DATA_ALLOC_SIZE;
-      data = (char *) realloc(data, data_max+1);
-
-      if( data == NULL ) {
-        msIO_printf("Content-type: text/html%c%c",10,10);
-        msIO_printf("out of memory trying to allocate %u input buffer, POST body too large?\n", data_max+1 );
-        exit(1);
-      }
+      *data = (char *) msSmallRealloc(*data, data_max+1);
     }
   }
 
-  data[data_len] = '\0';  
-  return data;
+  *data[data_len] = '\0';
+  return MS_SUCCESS;
 }
 
 static char* msGetEnv(const char *name, void* thread_context)
 {
-    return getenv(name);
+  return getenv(name);
 }
 
-int loadParams(cgiRequestObj *request, 
+int loadParams(cgiRequestObj *request,
                char* (*getenv2)(const char*, void* thread_context),
                char *raw_post_data,
                ms_uint32 raw_post_data_length,
-               void* thread_context) {
+               void* thread_context)
+{
   register int x,m=0;
   char *s, *queryString = NULL, *httpCookie = NULL;
   int debuglevel;
   int maxParams = MS_DEFAULT_CGI_PARAMS;
-  
+
   if (getenv2==NULL)
-      getenv2 = &msGetEnv;
+    getenv2 = &msGetEnv;
 
   if(getenv2("REQUEST_METHOD", thread_context)==NULL) {
     msIO_printf("This script can only be used to decode form results and \n");
     msIO_printf("should be initiated as a CGI process via a httpd server.\n");
-    exit(0);
+    return -1;
   }
 
   debuglevel = (int)msGetGlobalDebugLevel();
 
-  if(strcmp(getenv2("REQUEST_METHOD", thread_context),"POST") == 0) { /* we've got a post from a form */     
+  if(strcmp(getenv2("REQUEST_METHOD", thread_context),"POST") == 0) { /* we've got a post from a form */
     char *post_data;
     int data_len;
     request->type = MS_POST_REQUEST;
 
-    s = getenv2("CONTENT_TYPE", thread_context); 
+    s = getenv2("CONTENT_TYPE", thread_context);
     if (s != NULL)
       request->contenttype = msStrdup(s);
-     /* we've to set default content-type which is
-      * application/octet-stream according to
-      * W3 RFC 2626 section 7.2.1 */
+    /* we've to set default Content-Type which is
+     * application/octet-stream according to
+     * W3 RFC 2626 section 7.2.1 */
     else request->contenttype = msStrdup("application/octet-stream");
 
     if (raw_post_data) {
-        post_data = msStrdup(raw_post_data);
-        data_len = raw_post_data_length;
-    }
-    else {
-        post_data = readPostBody( request );
-        data_len = strlen(post_data);
+      post_data = msStrdup(raw_post_data);
+      data_len = raw_post_data_length;
+    } else {
+      if(MS_SUCCESS != readPostBody( request, &post_data ))
+        return -1;
+      data_len = strlen(post_data);
     }
 
-    /* if the content_type is application/x-www-form-urlencoded, 
+    /* if the content_type is application/x-www-form-urlencoded,
        we have to parse it like the QUERY_STRING variable */
-    if(strcmp(request->contenttype, "application/x-www-form-urlencoded") == 0)   
-    {
+    if(strcmp(request->contenttype, "application/x-www-form-urlencoded") == 0) {
       while( data_len > 0 && isspace(post_data[data_len-1]) )
         post_data[--data_len] = '\0';
 
       while( post_data[0] ) {
         if(m >= maxParams) {
           maxParams *= 2;
-          request->ParamNames = (char **) realloc(request->ParamNames,sizeof(char *) * maxParams);
-          if (request->ParamNames == NULL) {
-              msIO_printf("Out of memory trying to allocate name/value pairs.\n");
-              exit(1);
-          }
-          request->ParamValues = (char **) realloc(request->ParamValues,sizeof(char *) * maxParams);
-          if (request->ParamValues ==  NULL) {
-              msIO_printf("Out of memory trying to allocate name/value pairs.\n");
-              exit(1);
-          }
+          request->ParamNames = (char **) msSmallRealloc(request->ParamNames,sizeof(char *) * maxParams);
+          request->ParamValues = (char **) msSmallRealloc(request->ParamValues,sizeof(char *) * maxParams);
         }
         request->ParamValues[m] = makeword(post_data,'&');
         plustospace(request->ParamValues[m]);
@@ -192,85 +176,71 @@ int loadParams(cgiRequestObj *request,
         m++;
       }
       free( post_data );
-    }
-    else 
-        request->postrequest = post_data;
+    } else
+      request->postrequest = post_data;
 
-    /* check the QUERY_STRING even in the post request since it can contain 
+    /* check the QUERY_STRING even in the post request since it can contain
        information. Eg a wfs request with  */
     s = getenv2("QUERY_STRING", thread_context);
     if(s) {
       if (debuglevel >= MS_DEBUGLEVEL_DEBUG)
-		  msDebug("loadParams() QUERY_STRING: %s\n", s);
+        msDebug("loadParams() QUERY_STRING: %s\n", s);
 
       queryString = msStrdup(s);
-      for(x=0;queryString[0] != '\0';x++) {       
+      for(x=0; queryString[0] != '\0'; x++) {
         if(m >= maxParams) {
           maxParams *= 2;
-          request->ParamNames = (char **) realloc(request->ParamNames,sizeof(char *) * maxParams);
-          if (request->ParamNames == NULL) {
-              msIO_printf("Out of memory trying to allocate name/value pairs.\n");
-              exit(1);
-          }
-          request->ParamValues = (char **) realloc(request->ParamValues,sizeof(char *) * maxParams);
-          if (request->ParamValues ==  NULL) {
-              msIO_printf("Out of memory trying to allocate name/value pairs.\n");
-              exit(1);
-          }
-        } 
-        request->ParamValues[m] = makeword(queryString,'&'); 
+          request->ParamNames = (char **) msSmallRealloc(request->ParamNames,sizeof(char *) * maxParams);
+          request->ParamValues = (char **) msSmallRealloc(request->ParamValues,sizeof(char *) * maxParams);
+        }
+        request->ParamValues[m] = makeword(queryString,'&');
         plustospace(request->ParamValues[m]);
         unescape_url(request->ParamValues[m]);
         request->ParamNames[m] = makeword(request->ParamValues[m],'=');
         m++;
       }
-    }     
-  } else { 
+    }
+  } else {
     if(strcmp(getenv2("REQUEST_METHOD", thread_context),"GET") == 0) { /* we've got a get request */
       request->type = MS_GET_REQUEST;
 
       s = getenv2("QUERY_STRING", thread_context);
       if(s == NULL) {
-        msIO_printf("Content-type: text/html%c%c",10,10);
-        msIO_printf("No query information to decode. QUERY_STRING not set.\n");	
-        exit(1);
+        msIO_setHeader("Content-Type","text/html");
+        msIO_sendHeaders();
+        msIO_printf("No query information to decode. QUERY_STRING not set.\n");
+        return -1;
       }
-            
+
       if (debuglevel >= MS_DEBUGLEVEL_DEBUG)
-          msDebug("loadParams() QUERY_STRING: %s\n", s);
+        msDebug("loadParams() QUERY_STRING: %s\n", s);
 
       if(strlen(s)==0) {
-        msIO_printf("Content-type: text/html%c%c",10,10);
+        msIO_setHeader("Content-Type","text/html");
+        msIO_sendHeaders();
         msIO_printf("No query information to decode. QUERY_STRING is set, but empty.\n");
-        exit(1);
+        return -1;
       }
-      
+
       /* don't modify the string returned by getenv2 */
       queryString = msStrdup(s);
-      for(x=0;queryString[0] != '\0';x++) {
-          if(m >= maxParams) {
-            maxParams *= 2;
-            request->ParamNames = (char **) realloc(request->ParamNames,sizeof(char *) * maxParams);
-            if (request->ParamNames == NULL) {
-                msIO_printf("Out of memory trying to allocate name/value pairs.\n");
-                exit(1);
-            }
-            request->ParamValues = (char **) realloc(request->ParamValues,sizeof(char *) * maxParams);
-            if (request->ParamValues ==  NULL) {
-                msIO_printf("Out of memory trying to allocate name/value pairs.\n");
-                exit(1);
-            }
-          } 
-          request->ParamValues[m] = makeword(queryString,'&');
-          plustospace(request->ParamValues[m]);
-          unescape_url(request->ParamValues[m]);
-          request->ParamNames[m] = makeword(request->ParamValues[m],'=');
-          m++; 
+      for(x=0; queryString[0] != '\0'; x++) {
+        if(m >= maxParams) {
+          maxParams *= 2;
+          request->ParamNames = (char **) msSmallRealloc(request->ParamNames,sizeof(char *) * maxParams);
+          request->ParamValues = (char **) msSmallRealloc(request->ParamValues,sizeof(char *) * maxParams);
+        }
+        request->ParamValues[m] = makeword(queryString,'&');
+        plustospace(request->ParamValues[m]);
+        unescape_url(request->ParamValues[m]);
+        request->ParamNames[m] = makeword(request->ParamValues[m],'=');
+        m++;
       }
     } else {
-      msIO_printf("Content-type: text/html%c%c",10,10);
+      msIO_setHeader("Content-Type","text/html");
+      msIO_sendHeaders();
       msIO_printf("This script should be referenced with a METHOD of GET or METHOD of POST.\n");
-      exit(1);
+      return -1;
     }
   }
 
@@ -279,19 +249,11 @@ int loadParams(cgiRequestObj *request,
   if(s != NULL) {
     httpCookie = msStrdup(s);
     request->httpcookiedata = msStrdup(s);
-    for(x=0;httpCookie[0] != '\0';x++) {
-        if(m >= maxParams) {
-          maxParams *= 2;
-          request->ParamNames = (char **) realloc(request->ParamNames,sizeof(char *) * maxParams);
-          if (request->ParamNames == NULL) {
-              msIO_printf("Out of memory trying to allocate name/value pairs.\n");
-              exit(1);
-          }
-          request->ParamValues = (char **) realloc(request->ParamValues,sizeof(char *) * maxParams);
-          if (request->ParamValues ==  NULL) {
-              msIO_printf("Out of memory trying to allocate name/value pairs.\n");
-              exit(1);
-          }
+    for(x=0; httpCookie[0] != '\0'; x++) {
+      if(m >= maxParams) {
+        maxParams *= 2;
+        request->ParamNames = (char **) msSmallRealloc(request->ParamNames,sizeof(char *) * maxParams);
+        request->ParamValues = (char **) msSmallRealloc(request->ParamValues,sizeof(char *) * maxParams);
       }
       request->ParamValues[m] = makeword(httpCookie,';');
       plustospace(request->ParamValues[m]);
@@ -300,19 +262,20 @@ int loadParams(cgiRequestObj *request,
       m++;
     }
   }
-  
+
   if (queryString)
-      free(queryString);
+    free(queryString);
   if (httpCookie)
-      free(httpCookie);
+    free(httpCookie);
 
   return(m);
 }
 
-void getword(char *word, char *line, char stop) {
+void getword(char *word, char *line, char stop)
+{
   int x = 0,y;
 
-  for(x=0;((line[x]) && (line[x] != stop));x++)
+  for(x=0; ((line[x]) && (line[x] != stop)); x++)
     word[x] = line[x];
 
   word[x] = '\0';
@@ -322,14 +285,15 @@ void getword(char *word, char *line, char stop) {
   while((line[y++] = line[x++]));
 }
 
-char *makeword_skip(char *line, char stop, char skip) {
+char *makeword_skip(char *line, char stop, char skip)
+{
   int x = 0,y,offset=0;
   char *word = (char *) msSmallMalloc(sizeof(char) * (strlen(line) + 1));
 
-  for(x=0;((line[x]) && (line[x] == skip));x++);
+  for(x=0; ((line[x]) && (line[x] == skip)); x++);
   offset = x;
 
-  for(x=offset;((line[x]) && (line[x] != stop));x++)
+  for(x=offset; ((line[x]) && (line[x] != stop)); x++)
     word[x-offset] = line[x];
 
   word[x-offset] = '\0';
@@ -340,13 +304,14 @@ char *makeword_skip(char *line, char stop, char skip) {
   return word;
 }
 
-char *makeword(char *line, char stop) {
-    int x = 0,y;
+char *makeword(char *line, char stop)
+{
+  int x = 0,y;
   char *word = (char *) msSmallMalloc(sizeof(char) * (strlen(line) + 1));
-  
-  for(x=0;((line[x]) && (line[x] != stop));x++)
+
+  for(x=0; ((line[x]) && (line[x] != stop)); x++)
     word[x] = line[x];
-  
+
   word[x] = '\0';
   if(line[x]) ++x;
   y=0;
@@ -355,7 +320,8 @@ char *makeword(char *line, char stop) {
   return word;
 }
 
-char *fmakeword(FILE *f, char stop, int *cl) {
+char *fmakeword(FILE *f, char stop, int *cl)
+{
   int wsize;
   char *word;
   int ll;
@@ -382,7 +348,8 @@ char *fmakeword(FILE *f, char stop, int *cl) {
   }
 }
 
-char x2c(char *what) {
+char x2c(char *what)
+{
   register char digit;
 
   digit = (what[0] >= 'A' ? ((what[0] & 0xdf) - 'A')+10 : (what[0] - '0'));
@@ -391,10 +358,11 @@ char x2c(char *what) {
   return(digit);
 }
 
-void unescape_url(char *url) {
+void unescape_url(char *url)
+{
   register int x,y;
 
-  for(x=0,y=0;url[y];++x,++y) {
+  for(x=0,y=0; url[y]; ++x,++y) {
     if((url[x] = url[y]) == '%') {
       url[x] = x2c(&url[y+1]);
       y+=2;
@@ -403,20 +371,23 @@ void unescape_url(char *url) {
   url[x] = '\0';
 }
 
-void plustospace(char *str) {
+void plustospace(char *str)
+{
   register int x;
 
-  for(x=0;str[x];x++) if(str[x] == '+') str[x] = ' ';
+  for(x=0; str[x]; x++) if(str[x] == '+') str[x] = ' ';
 }
 
-int rind(char *s, char c) {
+int rind(char *s, char c)
+{
   register int x;
-  for(x=strlen(s) - 1;x != -1; x--)
+  for(x=strlen(s) - 1; x != -1; x--)
     if(s[x] == c) return x;
   return -1;
 }
 
-int _getline(char *s, int n, FILE *f) {
+int _getline(char *s, int n, FILE *f)
+{
   register int i=0;
 
   while(1) {
@@ -433,7 +404,8 @@ int _getline(char *s, int n, FILE *f) {
   }
 }
 
-void send_fd(FILE *f, FILE *fd) {
+void send_fd(FILE *f, FILE *fd)
+{
   char c;
 
   while (1) {
@@ -444,10 +416,11 @@ void send_fd(FILE *f, FILE *fd) {
   }
 }
 
-int ind(char *s, char c) {
+int ind(char *s, char c)
+{
   register int x;
 
-  for(x=0;s[x];x++)
+  for(x=0; s[x]; x++)
     if(s[x] == c) return x;
 
   return -1;
@@ -456,13 +429,14 @@ int ind(char *s, char c) {
 /*
 ** patched version according to CERT advisory...
 */
-void escape_shell_cmd(char *cmd) {
+void escape_shell_cmd(char *cmd)
+{
   register int x,y,l;
 
   l=strlen(cmd);
-  for(x=0;cmd[x];x++) {
+  for(x=0; cmd[x]; x++) {
     if(ind("&;`'\"|*?~<>^()[]{}$\\\n",cmd[x]) != -1) {
-      for(y=l+1;y>x;y--)
+      for(y=l+1; y>x; y--)
         cmd[y] = cmd[y-1];
       l++; /* length has been increased */
       cmd[x] = '\\';
@@ -474,7 +448,8 @@ void escape_shell_cmd(char *cmd) {
 /*
 ** Allocate a new request holder structure
 */
-cgiRequestObj *msAllocCgiObj() {
+cgiRequestObj *msAllocCgiObj()
+{
   cgiRequestObj *request = (cgiRequestObj *)malloc(sizeof(cgiRequestObj));
 
   if(!request)
@@ -483,15 +458,16 @@ cgiRequestObj *msAllocCgiObj() {
   request->ParamNames = (char **) msSmallMalloc(MS_DEFAULT_CGI_PARAMS*sizeof(char*));
   request->ParamValues = (char **) msSmallMalloc(MS_DEFAULT_CGI_PARAMS*sizeof(char*));
   request->NumParams = 0;
-  request->type = -1;
+  request->type = MS_GET_REQUEST;
   request->contenttype = NULL;
   request->postrequest = NULL;
   request->httpcookiedata = NULL;
 
   return request;
 }
-      
-void msFreeCgiObj(cgiRequestObj *request) {
+
+void msFreeCgiObj(cgiRequestObj *request)
+{
   msFreeCharArray(request->ParamNames, request->NumParams);
   msFreeCharArray(request->ParamValues, request->NumParams);
   request->ParamNames = NULL;
diff --git a/cgiutil.h b/cgiutil.h
index 5d2c1b5..424519f 100644
--- a/cgiutil.h
+++ b/cgiutil.h
@@ -5,7 +5,7 @@
  * Purpose:  cgiRequestObj and CGI parsing utility related declarations.
  * Author:   Steve Lime and the MapServer team.
  *
- * Notes: Portions derived from NCSA HTTPd Server's example CGI programs (util.c). 
+ * Notes: Portions derived from NCSA HTTPd Server's example CGI programs (util.c).
  *
  ******************************************************************************
  * Copyright (c) 1996-2005 Regents of the University of Minnesota.
@@ -17,7 +17,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -47,19 +47,18 @@
 enum MS_REQUEST_TYPE {MS_GET_REQUEST, MS_POST_REQUEST};
 
 /* structure to hold request information */
-typedef struct
-{
+typedef struct {
 #ifndef SWIG
   char **ParamNames;
   char **ParamValues;
 #endif
 
 #ifdef SWIG
-%immutable;
+  %immutable;
 #endif
   int NumParams;
 #ifdef SWIG
-%mutable;
+  %mutable;
 #endif
 
   enum MS_REQUEST_TYPE type;
@@ -69,13 +68,13 @@ typedef struct
 
   char *httpcookiedata;
 } cgiRequestObj;
-      
+
 
 /*
 ** Function prototypes
 */
 #ifndef SWIG
-MS_DLL_EXPORT int loadParams(cgiRequestObj *request, char* (*getenv2)(const char*, void* thread_context), 
+MS_DLL_EXPORT int loadParams(cgiRequestObj *request, char* (*getenv2)(const char*, void* thread_context),
                              char *raw_post_data, ms_uint32 raw_post_data_length, void* thread_context);
 MS_DLL_EXPORT void getword(char *, char *, char);
 MS_DLL_EXPORT char *makeword_skip(char *, char, char);
diff --git a/classobject.c b/classobject.c
index b3a7be5..25e1b13 100644
--- a/classobject.c
+++ b/classobject.c
@@ -3,7 +3,7 @@
  *
  * Project:  MapServer
  * Purpose:  Functions for operating on a classObj that don't belong in a
- *           more specific file such as mapfile.c.  
+ *           more specific file such as mapfile.c.
  *           Adapted from mapobject.c.
  * Author:   Sean Gillies, sgillies at frii.com
  *
@@ -17,7 +17,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -36,149 +36,180 @@
 #  include "cpl_conv.h"
 #endif
 
-MS_CVSID("$Id$")
+
+
+/*
+** Add a label to a classObj (order doesn't matter for labels like it does with styles)
+*/
+int msAddLabelToClass(classObj *class, labelObj *label)
+{
+  if (!label) {
+    msSetError(MS_CHILDERR, "Can't add a NULL label.", "msAddLabelToClass()");
+    return MS_FAILURE;
+  }
+  if (msGrowClassLabels(class) == NULL) return MS_FAILURE;
+
+  /* msGrowClassLabels will alloc the label, free it in this case */
+  free(class->labels[class->numlabels]);
+  class->labels[class->numlabels] = label;
+  MS_REFCNT_INCR(label);
+  class->numlabels++;
+  return MS_SUCCESS;
+}
+
+/*
+** Remove a label from a classObj.
+*/
+labelObj *msRemoveLabelFromClass(classObj *class, int nLabelIndex)
+{
+  int i;
+  labelObj *label;
+
+  if (nLabelIndex < 0 || nLabelIndex >= class->numlabels) {
+    msSetError(MS_CHILDERR, "Cannot remove label, invalid index %d", "msRemoveLabelFromClass()", nLabelIndex);
+    return NULL;
+  } else {
+    label=class->labels[nLabelIndex];
+    for (i=nLabelIndex; i<class->numlabels-1; i++) {
+      class->labels[i]=class->labels[i+1];
+    }
+    class->labels[class->numlabels-1]=NULL;
+    class->numlabels--;
+    MS_REFCNT_DECR(label);
+    return label;
+  }
+}
 
 /**
  * Move the style up inside the array of styles.
- */  
+ */
 int msMoveStyleUp(classObj *class, int nStyleIndex)
 {
-    styleObj *psTmpStyle = NULL;
-    if (class && nStyleIndex < class->numstyles && nStyleIndex >0)
-    {
-        psTmpStyle = (styleObj *)malloc(sizeof(styleObj));
-        initStyle(psTmpStyle);
-        
-        msCopyStyle(psTmpStyle, class->styles[nStyleIndex]);
-
-        msCopyStyle(class->styles[nStyleIndex], 
-                    class->styles[nStyleIndex-1]);
-        
-        msCopyStyle(class->styles[nStyleIndex-1], psTmpStyle);
-
-        return(MS_SUCCESS);
-    }
-    msSetError(MS_CHILDERR, "Invalid index: %d", "msMoveStyleUp()",
-               nStyleIndex);
-    return (MS_FAILURE);
+  styleObj *psTmpStyle = NULL;
+  if (class && nStyleIndex < class->numstyles && nStyleIndex >0) {
+    psTmpStyle = (styleObj *)malloc(sizeof(styleObj));
+    initStyle(psTmpStyle);
+
+    msCopyStyle(psTmpStyle, class->styles[nStyleIndex]);
+
+    msCopyStyle(class->styles[nStyleIndex],
+                class->styles[nStyleIndex-1]);
+
+    msCopyStyle(class->styles[nStyleIndex-1], psTmpStyle);
+
+    return(MS_SUCCESS);
+  }
+  msSetError(MS_CHILDERR, "Invalid index: %d", "msMoveStyleUp()",
+             nStyleIndex);
+  return (MS_FAILURE);
 }
 
 
 /**
  * Move the style down inside the array of styles.
- */  
+ */
 int msMoveStyleDown(classObj *class, int nStyleIndex)
 {
-    styleObj *psTmpStyle = NULL;
+  styleObj *psTmpStyle = NULL;
 
-    if (class && nStyleIndex < class->numstyles-1 && nStyleIndex >=0)
-    {
-        psTmpStyle = (styleObj *)malloc(sizeof(styleObj));
-        initStyle(psTmpStyle);
-        
-        msCopyStyle(psTmpStyle, class->styles[nStyleIndex]);
+  if (class && nStyleIndex < class->numstyles-1 && nStyleIndex >=0) {
+    psTmpStyle = (styleObj *)malloc(sizeof(styleObj));
+    initStyle(psTmpStyle);
 
-        msCopyStyle(class->styles[nStyleIndex], 
-                    class->styles[nStyleIndex+1]);
-        
-        msCopyStyle(class->styles[nStyleIndex+1], psTmpStyle);
+    msCopyStyle(psTmpStyle, class->styles[nStyleIndex]);
 
-        return(MS_SUCCESS);
-    }
-    msSetError(MS_CHILDERR, "Invalid index: %d", "msMoveStyleDown()",
-               nStyleIndex);
-    return (MS_FAILURE);
+    msCopyStyle(class->styles[nStyleIndex],
+                class->styles[nStyleIndex+1]);
+
+    msCopyStyle(class->styles[nStyleIndex+1], psTmpStyle);
+
+    return(MS_SUCCESS);
+  }
+  msSetError(MS_CHILDERR, "Invalid index: %d", "msMoveStyleDown()",
+             nStyleIndex);
+  return (MS_FAILURE);
 }
 
-/* Moved here from mapscript.i 
+/* Moved here from mapscript.i
  *
  * Returns the index at which the style was inserted
  *
  */
-int msInsertStyle(classObj *class, styleObj *style, int nStyleIndex) {
-    int i;
-
-    if (!style)
-    {
-        msSetError(MS_CHILDERR, "Can't insert a NULL Style", "msInsertStyle()");
-        return -1;
-    }
-
-    /* Ensure there is room for a new style */
-    if (msGrowClassStyles(class) == NULL) {
-        return -1;
-    }
-    /* Catch attempt to insert past end of styles array */
-    else if (nStyleIndex >= class->numstyles) {
-        msSetError(MS_CHILDERR, "Cannot insert style beyond index %d", "insertStyle()", class->numstyles-1);
-        return -1;
-    }
-    else if (nStyleIndex < 0) { /* Insert at the end by default */
-        class->styles[class->numstyles]=style;
-	MS_REFCNT_INCR(style);
-        class->numstyles++;
-        return class->numstyles-1;
-    }
-    else if (nStyleIndex >= 0 && nStyleIndex < class->numstyles) {
-        /* Move styles existing at the specified nStyleIndex or greater */
-        /* to a higher nStyleIndex */
-        for (i=class->numstyles-1; i>=nStyleIndex; i--) {
-            class->styles[i+1] = class->styles[i];
-        }
-        class->styles[nStyleIndex]=style;
-	MS_REFCNT_INCR(style);
-        class->numstyles++;
-        return nStyleIndex;
-    }
-    else {
-        msSetError(MS_CHILDERR, "Invalid nStyleIndex", "insertStyle()");
-        return -1;
+int msInsertStyle(classObj *class, styleObj *style, int nStyleIndex)
+{
+  int i;
+
+  if (!style) {
+    msSetError(MS_CHILDERR, "Can't insert a NULL Style", "msInsertStyle()");
+    return -1;
+  }
+
+  /* Ensure there is room for a new style */
+  if (msGrowClassStyles(class) == NULL) {
+    return -1;
+  }
+  /* Catch attempt to insert past end of styles array */
+  else if (nStyleIndex >= class->numstyles) {
+    msSetError(MS_CHILDERR, "Cannot insert style beyond index %d", "insertStyle()", class->numstyles-1);
+    return -1;
+  } else if (nStyleIndex < 0) { /* Insert at the end by default */
+    class->styles[class->numstyles]=style;
+    MS_REFCNT_INCR(style);
+    class->numstyles++;
+    return class->numstyles-1;
+  } else if (nStyleIndex >= 0 && nStyleIndex < class->numstyles) {
+    /* Move styles existing at the specified nStyleIndex or greater */
+    /* to a higher nStyleIndex */
+    for (i=class->numstyles-1; i>=nStyleIndex; i--) {
+      class->styles[i+1] = class->styles[i];
     }
+    class->styles[nStyleIndex]=style;
+    MS_REFCNT_INCR(style);
+    class->numstyles++;
+    return nStyleIndex;
+  } else {
+    msSetError(MS_CHILDERR, "Invalid nStyleIndex", "insertStyle()");
+    return -1;
+  }
 }
 
-styleObj *msRemoveStyle(classObj *class, int nStyleIndex) {
-    int i;
-    styleObj *style;
-    if (class->numstyles == 1) {
-        msSetError(MS_CHILDERR, "Cannot remove a class's sole style", "removeStyle()");
-        return NULL;
-    }
-    else if (nStyleIndex < 0 || nStyleIndex >= class->numstyles) {
-        msSetError(MS_CHILDERR, "Cannot remove style, invalid nStyleIndex %d", "removeStyle()", nStyleIndex);
-        return NULL;
-    }
-    else {
-        style=class->styles[nStyleIndex];
-        for (i=nStyleIndex; i<class->numstyles-1; i++) {
-             class->styles[i]=class->styles[i+1];
-        }
-	class->styles[class->numstyles-1]=NULL;
-        class->numstyles--;
-	MS_REFCNT_DECR(style);
-        return style;
+styleObj *msRemoveStyle(classObj *class, int nStyleIndex)
+{
+  int i;
+  styleObj *style;
+  if (nStyleIndex < 0 || nStyleIndex >= class->numstyles) {
+    msSetError(MS_CHILDERR, "Cannot remove style, invalid nStyleIndex %d", "removeStyle()", nStyleIndex);
+    return NULL;
+  } else {
+    style=class->styles[nStyleIndex];
+    for (i=nStyleIndex; i<class->numstyles-1; i++) {
+      class->styles[i]=class->styles[i+1];
     }
+    class->styles[class->numstyles-1]=NULL;
+    class->numstyles--;
+    MS_REFCNT_DECR(style);
+    return style;
+  }
 }
 
 /**
  * Delete the style identified by the index and shift
  * styles that follows the deleted style.
- */  
+ */
 int msDeleteStyle(classObj *class, int nStyleIndex)
 {
-    int i = 0;
-    if (class && nStyleIndex < class->numstyles && nStyleIndex >=0)
-    {
-        if (freeStyle(class->styles[nStyleIndex]) == MS_SUCCESS)
-            msFree(class->styles[nStyleIndex]);
-        for (i=nStyleIndex; i< class->numstyles-1; i++)
-        {
-            class->styles[i] = class->styles[i+1];
-        }
-        class->styles[class->numstyles-1] = NULL;
-        class->numstyles--;
-        return(MS_SUCCESS);
+  int i = 0;
+  if (class && nStyleIndex < class->numstyles && nStyleIndex >=0) {
+    if (freeStyle(class->styles[nStyleIndex]) == MS_SUCCESS)
+      msFree(class->styles[nStyleIndex]);
+    for (i=nStyleIndex; i< class->numstyles-1; i++) {
+      class->styles[i] = class->styles[i+1];
     }
-    msSetError(MS_CHILDERR, "Invalid index: %d", "msDeleteStyle()",
-               nStyleIndex);
-    return (MS_FAILURE);
+    class->styles[class->numstyles-1] = NULL;
+    class->numstyles--;
+    return(MS_SUCCESS);
+  }
+  msSetError(MS_CHILDERR, "Invalid index: %d", "msDeleteStyle()",
+             nStyleIndex);
+  return (MS_FAILURE);
 }
diff --git a/config.guess b/config.guess
new file mode 100755
index 0000000..43f0cdb
--- /dev/null
+++ b/config.guess
@@ -0,0 +1,1519 @@
+#! /bin/sh
+# Attempt to guess a canonical system name.
+#   Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
+#   2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
+#   2011 Free Software Foundation, Inc.
+
+timestamp='2011-10-01'
+
+# This file is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA
+# 02110-1301, USA.
+#
+# As a special exception to the GNU General Public License, if you
+# distribute this file as part of a program that contains a
+# configuration script generated by Autoconf, you may include it under
+# the same distribution terms that you use for the rest of that program.
+
+
+# Originally written by Per Bothner.  Please send patches (context
+# diff format) to <config-patches at gnu.org> and include a ChangeLog
+# entry.
+#
+# This script attempts to guess a canonical system name similar to
+# config.sub.  If it succeeds, it prints the system name on stdout, and
+# exits with 0.  Otherwise, it exits with 1.
+#
+# You can get the latest version of this script from:
+# http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess;hb=HEAD
+
+me=`echo "$0" | sed -e 's,.*/,,'`
+
+usage="\
+Usage: $0 [OPTION]
+
+Output the configuration name of the system \`$me' is run on.
+
+Operation modes:
+  -h, --help         print this help, then exit
+  -t, --time-stamp   print date of last modification, then exit
+  -v, --version      print version number, then exit
+
+Report bugs and patches to <config-patches at gnu.org>."
+
+version="\
+GNU config.guess ($timestamp)
+
+Originally written by Per Bothner.
+Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
+2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free
+Software Foundation, Inc.
+
+This is free software; see the source for copying conditions.  There is NO
+warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
+
+help="
+Try \`$me --help' for more information."
+
+# Parse command line
+while test $# -gt 0 ; do
+  case $1 in
+    --time-stamp | --time* | -t )
+       echo "$timestamp" ; exit ;;
+    --version | -v )
+       echo "$version" ; exit ;;
+    --help | --h* | -h )
+       echo "$usage"; exit ;;
+    -- )     # Stop option processing
+       shift; break ;;
+    - )	# Use stdin as input.
+       break ;;
+    -* )
+       echo "$me: invalid option $1$help" >&2
+       exit 1 ;;
+    * )
+       break ;;
+  esac
+done
+
+if test $# != 0; then
+  echo "$me: too many arguments$help" >&2
+  exit 1
+fi
+
+trap 'exit 1' 1 2 15
+
+# CC_FOR_BUILD -- compiler used by this script. Note that the use of a
+# compiler to aid in system detection is discouraged as it requires
+# temporary files to be created and, as you can see below, it is a
+# headache to deal with in a portable fashion.
+
+# Historically, `CC_FOR_BUILD' used to be named `HOST_CC'. We still
+# use `HOST_CC' if defined, but it is deprecated.
+
+# Portable tmp directory creation inspired by the Autoconf team.
+
+set_cc_for_build='
+trap "exitcode=\$?; (rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null) && exit \$exitcode" 0 ;
+trap "rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null; exit 1" 1 2 13 15 ;
+: ${TMPDIR=/tmp} ;
+ { tmp=`(umask 077 && mktemp -d "$TMPDIR/cgXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" ; } ||
+ { test -n "$RANDOM" && tmp=$TMPDIR/cg$$-$RANDOM && (umask 077 && mkdir $tmp) ; } ||
+ { tmp=$TMPDIR/cg-$$ && (umask 077 && mkdir $tmp) && echo "Warning: creating insecure temp directory" >&2 ; } ||
+ { echo "$me: cannot create a temporary directory in $TMPDIR" >&2 ; exit 1 ; } ;
+dummy=$tmp/dummy ;
+tmpfiles="$dummy.c $dummy.o $dummy.rel $dummy" ;
+case $CC_FOR_BUILD,$HOST_CC,$CC in
+ ,,)    echo "int x;" > $dummy.c ;
+	for c in cc gcc c89 c99 ; do
+	  if ($c -c -o $dummy.o $dummy.c) >/dev/null 2>&1 ; then
+	     CC_FOR_BUILD="$c"; break ;
+	  fi ;
+	done ;
+	if test x"$CC_FOR_BUILD" = x ; then
+	  CC_FOR_BUILD=no_compiler_found ;
+	fi
+	;;
+ ,,*)   CC_FOR_BUILD=$CC ;;
+ ,*,*)  CC_FOR_BUILD=$HOST_CC ;;
+esac ; set_cc_for_build= ;'
+
+# This is needed to find uname on a Pyramid OSx when run in the BSD universe.
+# (ghazi at noc.rutgers.edu 1994-08-24)
+if (test -f /.attbin/uname) >/dev/null 2>&1 ; then
+	PATH=$PATH:/.attbin ; export PATH
+fi
+
+UNAME_MACHINE=`(uname -m) 2>/dev/null` || UNAME_MACHINE=unknown
+UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown
+UNAME_SYSTEM=`(uname -s) 2>/dev/null`  || UNAME_SYSTEM=unknown
+UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown
+
+# Note: order is significant - the case branches are not exclusive.
+
+case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
+    *:NetBSD:*:*)
+	# NetBSD (nbsd) targets should (where applicable) match one or
+	# more of the tupples: *-*-netbsdelf*, *-*-netbsdaout*,
+	# *-*-netbsdecoff* and *-*-netbsd*.  For targets that recently
+	# switched to ELF, *-*-netbsd* would select the old
+	# object file format.  This provides both forward
+	# compatibility and a consistent mechanism for selecting the
+	# object file format.
+	#
+	# Note: NetBSD doesn't particularly care about the vendor
+	# portion of the name.  We always set it to "unknown".
+	sysctl="sysctl -n hw.machine_arch"
+	UNAME_MACHINE_ARCH=`(/sbin/$sysctl 2>/dev/null || \
+	    /usr/sbin/$sysctl 2>/dev/null || echo unknown)`
+	case "${UNAME_MACHINE_ARCH}" in
+	    armeb) machine=armeb-unknown ;;
+	    arm*) machine=arm-unknown ;;
+	    sh3el) machine=shl-unknown ;;
+	    sh3eb) machine=sh-unknown ;;
+	    sh5el) machine=sh5le-unknown ;;
+	    *) machine=${UNAME_MACHINE_ARCH}-unknown ;;
+	esac
+	# The Operating System including object format, if it has switched
+	# to ELF recently, or will in the future.
+	case "${UNAME_MACHINE_ARCH}" in
+	    arm*|i386|m68k|ns32k|sh3*|sparc|vax)
+		eval $set_cc_for_build
+		if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \
+			| grep -q __ELF__
+		then
+		    # Once all utilities can be ECOFF (netbsdecoff) or a.out (netbsdaout).
+		    # Return netbsd for either.  FIX?
+		    os=netbsd
+		else
+		    os=netbsdelf
+		fi
+		;;
+	    *)
+		os=netbsd
+		;;
+	esac
+	# The OS release
+	# Debian GNU/NetBSD machines have a different userland, and
+	# thus, need a distinct triplet. However, they do not need
+	# kernel version information, so it can be replaced with a
+	# suitable tag, in the style of linux-gnu.
+	case "${UNAME_VERSION}" in
+	    Debian*)
+		release='-gnu'
+		;;
+	    *)
+		release=`echo ${UNAME_RELEASE}|sed -e 's/[-_].*/\./'`
+		;;
+	esac
+	# Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM:
+	# contains redundant information, the shorter form:
+	# CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used.
+	echo "${machine}-${os}${release}"
+	exit ;;
+    *:OpenBSD:*:*)
+	UNAME_MACHINE_ARCH=`arch | sed 's/OpenBSD.//'`
+	echo ${UNAME_MACHINE_ARCH}-unknown-openbsd${UNAME_RELEASE}
+	exit ;;
+    *:ekkoBSD:*:*)
+	echo ${UNAME_MACHINE}-unknown-ekkobsd${UNAME_RELEASE}
+	exit ;;
+    *:SolidBSD:*:*)
+	echo ${UNAME_MACHINE}-unknown-solidbsd${UNAME_RELEASE}
+	exit ;;
+    macppc:MirBSD:*:*)
+	echo powerpc-unknown-mirbsd${UNAME_RELEASE}
+	exit ;;
+    *:MirBSD:*:*)
+	echo ${UNAME_MACHINE}-unknown-mirbsd${UNAME_RELEASE}
+	exit ;;
+    alpha:OSF1:*:*)
+	case $UNAME_RELEASE in
+	*4.0)
+		UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'`
+		;;
+	*5.*)
+		UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $4}'`
+		;;
+	esac
+	# According to Compaq, /usr/sbin/psrinfo has been available on
+	# OSF/1 and Tru64 systems produced since 1995.  I hope that
+	# covers most systems running today.  This code pipes the CPU
+	# types through head -n 1, so we only detect the type of CPU 0.
+	ALPHA_CPU_TYPE=`/usr/sbin/psrinfo -v | sed -n -e 's/^  The alpha \(.*\) processor.*$/\1/p' | head -n 1`
+	case "$ALPHA_CPU_TYPE" in
+	    "EV4 (21064)")
+		UNAME_MACHINE="alpha" ;;
+	    "EV4.5 (21064)")
+		UNAME_MACHINE="alpha" ;;
+	    "LCA4 (21066/21068)")
+		UNAME_MACHINE="alpha" ;;
+	    "EV5 (21164)")
+		UNAME_MACHINE="alphaev5" ;;
+	    "EV5.6 (21164A)")
+		UNAME_MACHINE="alphaev56" ;;
+	    "EV5.6 (21164PC)")
+		UNAME_MACHINE="alphapca56" ;;
+	    "EV5.7 (21164PC)")
+		UNAME_MACHINE="alphapca57" ;;
+	    "EV6 (21264)")
+		UNAME_MACHINE="alphaev6" ;;
+	    "EV6.7 (21264A)")
+		UNAME_MACHINE="alphaev67" ;;
+	    "EV6.8CB (21264C)")
+		UNAME_MACHINE="alphaev68" ;;
+	    "EV6.8AL (21264B)")
+		UNAME_MACHINE="alphaev68" ;;
+	    "EV6.8CX (21264D)")
+		UNAME_MACHINE="alphaev68" ;;
+	    "EV6.9A (21264/EV69A)")
+		UNAME_MACHINE="alphaev69" ;;
+	    "EV7 (21364)")
+		UNAME_MACHINE="alphaev7" ;;
+	    "EV7.9 (21364A)")
+		UNAME_MACHINE="alphaev79" ;;
+	esac
+	# A Pn.n version is a patched version.
+	# A Vn.n version is a released version.
+	# A Tn.n version is a released field test version.
+	# A Xn.n version is an unreleased experimental baselevel.
+	# 1.2 uses "1.2" for uname -r.
+	echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[PVTX]//' | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
+	# Reset EXIT trap before exiting to avoid spurious non-zero exit code.
+	exitcode=$?
+	trap '' 0
+	exit $exitcode ;;
+    Alpha\ *:Windows_NT*:*)
+	# How do we know it's Interix rather than the generic POSIX subsystem?
+	# Should we change UNAME_MACHINE based on the output of uname instead
+	# of the specific Alpha model?
+	echo alpha-pc-interix
+	exit ;;
+    21064:Windows_NT:50:3)
+	echo alpha-dec-winnt3.5
+	exit ;;
+    Amiga*:UNIX_System_V:4.0:*)
+	echo m68k-unknown-sysv4
+	exit ;;
+    *:[Aa]miga[Oo][Ss]:*:*)
+	echo ${UNAME_MACHINE}-unknown-amigaos
+	exit ;;
+    *:[Mm]orph[Oo][Ss]:*:*)
+	echo ${UNAME_MACHINE}-unknown-morphos
+	exit ;;
+    *:OS/390:*:*)
+	echo i370-ibm-openedition
+	exit ;;
+    *:z/VM:*:*)
+	echo s390-ibm-zvmoe
+	exit ;;
+    *:OS400:*:*)
+	echo powerpc-ibm-os400
+	exit ;;
+    arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*)
+	echo arm-acorn-riscix${UNAME_RELEASE}
+	exit ;;
+    arm:riscos:*:*|arm:RISCOS:*:*)
+	echo arm-unknown-riscos
+	exit ;;
+    SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*)
+	echo hppa1.1-hitachi-hiuxmpp
+	exit ;;
+    Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*)
+	# akee at wpdis03.wpafb.af.mil (Earle F. Ake) contributed MIS and NILE.
+	if test "`(/bin/universe) 2>/dev/null`" = att ; then
+		echo pyramid-pyramid-sysv3
+	else
+		echo pyramid-pyramid-bsd
+	fi
+	exit ;;
+    NILE*:*:*:dcosx)
+	echo pyramid-pyramid-svr4
+	exit ;;
+    DRS?6000:unix:4.0:6*)
+	echo sparc-icl-nx6
+	exit ;;
+    DRS?6000:UNIX_SV:4.2*:7* | DRS?6000:isis:4.2*:7*)
+	case `/usr/bin/uname -p` in
+	    sparc) echo sparc-icl-nx7; exit ;;
+	esac ;;
+    s390x:SunOS:*:*)
+	echo ${UNAME_MACHINE}-ibm-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+	exit ;;
+    sun4H:SunOS:5.*:*)
+	echo sparc-hal-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+	exit ;;
+    sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*)
+	echo sparc-sun-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+	exit ;;
+    i86pc:AuroraUX:5.*:* | i86xen:AuroraUX:5.*:*)
+	echo i386-pc-auroraux${UNAME_RELEASE}
+	exit ;;
+    i86pc:SunOS:5.*:* | i86xen:SunOS:5.*:*)
+	eval $set_cc_for_build
+	SUN_ARCH="i386"
+	# If there is a compiler, see if it is configured for 64-bit objects.
+	# Note that the Sun cc does not turn __LP64__ into 1 like gcc does.
+	# This test works for both compilers.
+	if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then
+	    if (echo '#ifdef __amd64'; echo IS_64BIT_ARCH; echo '#endif') | \
+		(CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \
+		grep IS_64BIT_ARCH >/dev/null
+	    then
+		SUN_ARCH="x86_64"
+	    fi
+	fi
+	echo ${SUN_ARCH}-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+	exit ;;
+    sun4*:SunOS:6*:*)
+	# According to config.sub, this is the proper way to canonicalize
+	# SunOS6.  Hard to guess exactly what SunOS6 will be like, but
+	# it's likely to be more like Solaris than SunOS4.
+	echo sparc-sun-solaris3`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+	exit ;;
+    sun4*:SunOS:*:*)
+	case "`/usr/bin/arch -k`" in
+	    Series*|S4*)
+		UNAME_RELEASE=`uname -v`
+		;;
+	esac
+	# Japanese Language versions have a version number like `4.1.3-JL'.
+	echo sparc-sun-sunos`echo ${UNAME_RELEASE}|sed -e 's/-/_/'`
+	exit ;;
+    sun3*:SunOS:*:*)
+	echo m68k-sun-sunos${UNAME_RELEASE}
+	exit ;;
+    sun*:*:4.2BSD:*)
+	UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null`
+	test "x${UNAME_RELEASE}" = "x" && UNAME_RELEASE=3
+	case "`/bin/arch`" in
+	    sun3)
+		echo m68k-sun-sunos${UNAME_RELEASE}
+		;;
+	    sun4)
+		echo sparc-sun-sunos${UNAME_RELEASE}
+		;;
+	esac
+	exit ;;
+    aushp:SunOS:*:*)
+	echo sparc-auspex-sunos${UNAME_RELEASE}
+	exit ;;
+    # The situation for MiNT is a little confusing.  The machine name
+    # can be virtually everything (everything which is not
+    # "atarist" or "atariste" at least should have a processor
+    # > m68000).  The system name ranges from "MiNT" over "FreeMiNT"
+    # to the lowercase version "mint" (or "freemint").  Finally
+    # the system name "TOS" denotes a system which is actually not
+    # MiNT.  But MiNT is downward compatible to TOS, so this should
+    # be no problem.
+    atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*)
+	echo m68k-atari-mint${UNAME_RELEASE}
+	exit ;;
+    atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*)
+	echo m68k-atari-mint${UNAME_RELEASE}
+	exit ;;
+    *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*)
+	echo m68k-atari-mint${UNAME_RELEASE}
+	exit ;;
+    milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*)
+	echo m68k-milan-mint${UNAME_RELEASE}
+	exit ;;
+    hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*)
+	echo m68k-hades-mint${UNAME_RELEASE}
+	exit ;;
+    *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*)
+	echo m68k-unknown-mint${UNAME_RELEASE}
+	exit ;;
+    m68k:machten:*:*)
+	echo m68k-apple-machten${UNAME_RELEASE}
+	exit ;;
+    powerpc:machten:*:*)
+	echo powerpc-apple-machten${UNAME_RELEASE}
+	exit ;;
+    RISC*:Mach:*:*)
+	echo mips-dec-mach_bsd4.3
+	exit ;;
+    RISC*:ULTRIX:*:*)
+	echo mips-dec-ultrix${UNAME_RELEASE}
+	exit ;;
+    VAX*:ULTRIX*:*:*)
+	echo vax-dec-ultrix${UNAME_RELEASE}
+	exit ;;
+    2020:CLIX:*:* | 2430:CLIX:*:*)
+	echo clipper-intergraph-clix${UNAME_RELEASE}
+	exit ;;
+    mips:*:*:UMIPS | mips:*:*:RISCos)
+	eval $set_cc_for_build
+	sed 's/^	//' << EOF >$dummy.c
+#ifdef __cplusplus
+#include <stdio.h>  /* for printf() prototype */
+	int main (int argc, char *argv[]) {
+#else
+	int main (argc, argv) int argc; char *argv[]; {
+#endif
+	#if defined (host_mips) && defined (MIPSEB)
+	#if defined (SYSTYPE_SYSV)
+	  printf ("mips-mips-riscos%ssysv\n", argv[1]); exit (0);
+	#endif
+	#if defined (SYSTYPE_SVR4)
+	  printf ("mips-mips-riscos%ssvr4\n", argv[1]); exit (0);
+	#endif
+	#if defined (SYSTYPE_BSD43) || defined(SYSTYPE_BSD)
+	  printf ("mips-mips-riscos%sbsd\n", argv[1]); exit (0);
+	#endif
+	#endif
+	  exit (-1);
+	}
+EOF
+	$CC_FOR_BUILD -o $dummy $dummy.c &&
+	  dummyarg=`echo "${UNAME_RELEASE}" | sed -n 's/\([0-9]*\).*/\1/p'` &&
+	  SYSTEM_NAME=`$dummy $dummyarg` &&
+	    { echo "$SYSTEM_NAME"; exit; }
+	echo mips-mips-riscos${UNAME_RELEASE}
+	exit ;;
+    Motorola:PowerMAX_OS:*:*)
+	echo powerpc-motorola-powermax
+	exit ;;
+    Motorola:*:4.3:PL8-*)
+	echo powerpc-harris-powermax
+	exit ;;
+    Night_Hawk:*:*:PowerMAX_OS | Synergy:PowerMAX_OS:*:*)
+	echo powerpc-harris-powermax
+	exit ;;
+    Night_Hawk:Power_UNIX:*:*)
+	echo powerpc-harris-powerunix
+	exit ;;
+    m88k:CX/UX:7*:*)
+	echo m88k-harris-cxux7
+	exit ;;
+    m88k:*:4*:R4*)
+	echo m88k-motorola-sysv4
+	exit ;;
+    m88k:*:3*:R3*)
+	echo m88k-motorola-sysv3
+	exit ;;
+    AViiON:dgux:*:*)
+	# DG/UX returns AViiON for all architectures
+	UNAME_PROCESSOR=`/usr/bin/uname -p`
+	if [ $UNAME_PROCESSOR = mc88100 ] || [ $UNAME_PROCESSOR = mc88110 ]
+	then
+	    if [ ${TARGET_BINARY_INTERFACE}x = m88kdguxelfx ] || \
+	       [ ${TARGET_BINARY_INTERFACE}x = x ]
+	    then
+		echo m88k-dg-dgux${UNAME_RELEASE}
+	    else
+		echo m88k-dg-dguxbcs${UNAME_RELEASE}
+	    fi
+	else
+	    echo i586-dg-dgux${UNAME_RELEASE}
+	fi
+	exit ;;
+    M88*:DolphinOS:*:*)	# DolphinOS (SVR3)
+	echo m88k-dolphin-sysv3
+	exit ;;
+    M88*:*:R3*:*)
+	# Delta 88k system running SVR3
+	echo m88k-motorola-sysv3
+	exit ;;
+    XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3)
+	echo m88k-tektronix-sysv3
+	exit ;;
+    Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD)
+	echo m68k-tektronix-bsd
+	exit ;;
+    *:IRIX*:*:*)
+	echo mips-sgi-irix`echo ${UNAME_RELEASE}|sed -e 's/-/_/g'`
+	exit ;;
+    ????????:AIX?:[12].1:2)   # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX.
+	echo romp-ibm-aix     # uname -m gives an 8 hex-code CPU id
+	exit ;;               # Note that: echo "'`uname -s`'" gives 'AIX '
+    i*86:AIX:*:*)
+	echo i386-ibm-aix
+	exit ;;
+    ia64:AIX:*:*)
+	if [ -x /usr/bin/oslevel ] ; then
+		IBM_REV=`/usr/bin/oslevel`
+	else
+		IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE}
+	fi
+	echo ${UNAME_MACHINE}-ibm-aix${IBM_REV}
+	exit ;;
+    *:AIX:2:3)
+	if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then
+		eval $set_cc_for_build
+		sed 's/^		//' << EOF >$dummy.c
+		#include <sys/systemcfg.h>
+
+		main()
+			{
+			if (!__power_pc())
+				exit(1);
+			puts("powerpc-ibm-aix3.2.5");
+			exit(0);
+			}
+EOF
+		if $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy`
+		then
+			echo "$SYSTEM_NAME"
+		else
+			echo rs6000-ibm-aix3.2.5
+		fi
+	elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then
+		echo rs6000-ibm-aix3.2.4
+	else
+		echo rs6000-ibm-aix3.2
+	fi
+	exit ;;
+    *:AIX:*:[4567])
+	IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | sed 1q | awk '{ print $1 }'`
+	if /usr/sbin/lsattr -El ${IBM_CPU_ID} | grep ' POWER' >/dev/null 2>&1; then
+		IBM_ARCH=rs6000
+	else
+		IBM_ARCH=powerpc
+	fi
+	if [ -x /usr/bin/oslevel ] ; then
+		IBM_REV=`/usr/bin/oslevel`
+	else
+		IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE}
+	fi
+	echo ${IBM_ARCH}-ibm-aix${IBM_REV}
+	exit ;;
+    *:AIX:*:*)
+	echo rs6000-ibm-aix
+	exit ;;
+    ibmrt:4.4BSD:*|romp-ibm:BSD:*)
+	echo romp-ibm-bsd4.4
+	exit ;;
+    ibmrt:*BSD:*|romp-ibm:BSD:*)            # covers RT/PC BSD and
+	echo romp-ibm-bsd${UNAME_RELEASE}   # 4.3 with uname added to
+	exit ;;                             # report: romp-ibm BSD 4.3
+    *:BOSX:*:*)
+	echo rs6000-bull-bosx
+	exit ;;
+    DPX/2?00:B.O.S.:*:*)
+	echo m68k-bull-sysv3
+	exit ;;
+    9000/[34]??:4.3bsd:1.*:*)
+	echo m68k-hp-bsd
+	exit ;;
+    hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*)
+	echo m68k-hp-bsd4.4
+	exit ;;
+    9000/[34678]??:HP-UX:*:*)
+	HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'`
+	case "${UNAME_MACHINE}" in
+	    9000/31? )            HP_ARCH=m68000 ;;
+	    9000/[34]?? )         HP_ARCH=m68k ;;
+	    9000/[678][0-9][0-9])
+		if [ -x /usr/bin/getconf ]; then
+		    sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null`
+		    sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null`
+		    case "${sc_cpu_version}" in
+		      523) HP_ARCH="hppa1.0" ;; # CPU_PA_RISC1_0
+		      528) HP_ARCH="hppa1.1" ;; # CPU_PA_RISC1_1
+		      532)                      # CPU_PA_RISC2_0
+			case "${sc_kernel_bits}" in
+			  32) HP_ARCH="hppa2.0n" ;;
+			  64) HP_ARCH="hppa2.0w" ;;
+			  '') HP_ARCH="hppa2.0" ;;   # HP-UX 10.20
+			esac ;;
+		    esac
+		fi
+		if [ "${HP_ARCH}" = "" ]; then
+		    eval $set_cc_for_build
+		    sed 's/^		//' << EOF >$dummy.c
+
+		#define _HPUX_SOURCE
+		#include <stdlib.h>
+		#include <unistd.h>
+
+		int main ()
+		{
+		#if defined(_SC_KERNEL_BITS)
+		    long bits = sysconf(_SC_KERNEL_BITS);
+		#endif
+		    long cpu  = sysconf (_SC_CPU_VERSION);
+
+		    switch (cpu)
+			{
+			case CPU_PA_RISC1_0: puts ("hppa1.0"); break;
+			case CPU_PA_RISC1_1: puts ("hppa1.1"); break;
+			case CPU_PA_RISC2_0:
+		#if defined(_SC_KERNEL_BITS)
+			    switch (bits)
+				{
+				case 64: puts ("hppa2.0w"); break;
+				case 32: puts ("hppa2.0n"); break;
+				default: puts ("hppa2.0"); break;
+				} break;
+		#else  /* !defined(_SC_KERNEL_BITS) */
+			    puts ("hppa2.0"); break;
+		#endif
+			default: puts ("hppa1.0"); break;
+			}
+		    exit (0);
+		}
+EOF
+		    (CCOPTS= $CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null) && HP_ARCH=`$dummy`
+		    test -z "$HP_ARCH" && HP_ARCH=hppa
+		fi ;;
+	esac
+	if [ ${HP_ARCH} = "hppa2.0w" ]
+	then
+	    eval $set_cc_for_build
+
+	    # hppa2.0w-hp-hpux* has a 64-bit kernel and a compiler generating
+	    # 32-bit code.  hppa64-hp-hpux* has the same kernel and a compiler
+	    # generating 64-bit code.  GNU and HP use different nomenclature:
+	    #
+	    # $ CC_FOR_BUILD=cc ./config.guess
+	    # => hppa2.0w-hp-hpux11.23
+	    # $ CC_FOR_BUILD="cc +DA2.0w" ./config.guess
+	    # => hppa64-hp-hpux11.23
+
+	    if echo __LP64__ | (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) |
+		grep -q __LP64__
+	    then
+		HP_ARCH="hppa2.0w"
+	    else
+		HP_ARCH="hppa64"
+	    fi
+	fi
+	echo ${HP_ARCH}-hp-hpux${HPUX_REV}
+	exit ;;
+    ia64:HP-UX:*:*)
+	HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'`
+	echo ia64-hp-hpux${HPUX_REV}
+	exit ;;
+    3050*:HI-UX:*:*)
+	eval $set_cc_for_build
+	sed 's/^	//' << EOF >$dummy.c
+	#include <unistd.h>
+	int
+	main ()
+	{
+	  long cpu = sysconf (_SC_CPU_VERSION);
+	  /* The order matters, because CPU_IS_HP_MC68K erroneously returns
+	     true for CPU_PA_RISC1_0.  CPU_IS_PA_RISC returns correct
+	     results, however.  */
+	  if (CPU_IS_PA_RISC (cpu))
+	    {
+	      switch (cpu)
+		{
+		  case CPU_PA_RISC1_0: puts ("hppa1.0-hitachi-hiuxwe2"); break;
+		  case CPU_PA_RISC1_1: puts ("hppa1.1-hitachi-hiuxwe2"); break;
+		  case CPU_PA_RISC2_0: puts ("hppa2.0-hitachi-hiuxwe2"); break;
+		  default: puts ("hppa-hitachi-hiuxwe2"); break;
+		}
+	    }
+	  else if (CPU_IS_HP_MC68K (cpu))
+	    puts ("m68k-hitachi-hiuxwe2");
+	  else puts ("unknown-hitachi-hiuxwe2");
+	  exit (0);
+	}
+EOF
+	$CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` &&
+		{ echo "$SYSTEM_NAME"; exit; }
+	echo unknown-hitachi-hiuxwe2
+	exit ;;
+    9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:* )
+	echo hppa1.1-hp-bsd
+	exit ;;
+    9000/8??:4.3bsd:*:*)
+	echo hppa1.0-hp-bsd
+	exit ;;
+    *9??*:MPE/iX:*:* | *3000*:MPE/iX:*:*)
+	echo hppa1.0-hp-mpeix
+	exit ;;
+    hp7??:OSF1:*:* | hp8?[79]:OSF1:*:* )
+	echo hppa1.1-hp-osf
+	exit ;;
+    hp8??:OSF1:*:*)
+	echo hppa1.0-hp-osf
+	exit ;;
+    i*86:OSF1:*:*)
+	if [ -x /usr/sbin/sysversion ] ; then
+	    echo ${UNAME_MACHINE}-unknown-osf1mk
+	else
+	    echo ${UNAME_MACHINE}-unknown-osf1
+	fi
+	exit ;;
+    parisc*:Lites*:*:*)
+	echo hppa1.1-hp-lites
+	exit ;;
+    C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*)
+	echo c1-convex-bsd
+	exit ;;
+    C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*)
+	if getsysinfo -f scalar_acc
+	then echo c32-convex-bsd
+	else echo c2-convex-bsd
+	fi
+	exit ;;
+    C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*)
+	echo c34-convex-bsd
+	exit ;;
+    C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*)
+	echo c38-convex-bsd
+	exit ;;
+    C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*)
+	echo c4-convex-bsd
+	exit ;;
+    CRAY*Y-MP:*:*:*)
+	echo ymp-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+	exit ;;
+    CRAY*[A-Z]90:*:*:*)
+	echo ${UNAME_MACHINE}-cray-unicos${UNAME_RELEASE} \
+	| sed -e 's/CRAY.*\([A-Z]90\)/\1/' \
+	      -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/ \
+	      -e 's/\.[^.]*$/.X/'
+	exit ;;
+    CRAY*TS:*:*:*)
+	echo t90-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+	exit ;;
+    CRAY*T3E:*:*:*)
+	echo alphaev5-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+	exit ;;
+    CRAY*SV1:*:*:*)
+	echo sv1-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+	exit ;;
+    *:UNICOS/mp:*:*)
+	echo craynv-cray-unicosmp${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+	exit ;;
+    F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*)
+	FUJITSU_PROC=`uname -m | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
+	FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'`
+	FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'`
+	echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}"
+	exit ;;
+    5000:UNIX_System_V:4.*:*)
+	FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'`
+	FUJITSU_REL=`echo ${UNAME_RELEASE} | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/ /_/'`
+	echo "sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}"
+	exit ;;
+    i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*)
+	echo ${UNAME_MACHINE}-pc-bsdi${UNAME_RELEASE}
+	exit ;;
+    sparc*:BSD/OS:*:*)
+	echo sparc-unknown-bsdi${UNAME_RELEASE}
+	exit ;;
+    *:BSD/OS:*:*)
+	echo ${UNAME_MACHINE}-unknown-bsdi${UNAME_RELEASE}
+	exit ;;
+    *:FreeBSD:*:*)
+	UNAME_PROCESSOR=`/usr/bin/uname -p`
+	case ${UNAME_PROCESSOR} in
+	    amd64)
+		echo x86_64-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;;
+	    *)
+		echo ${UNAME_PROCESSOR}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;;
+	esac
+	exit ;;
+    i*:CYGWIN*:*)
+	echo ${UNAME_MACHINE}-pc-cygwin
+	exit ;;
+    *:MINGW*:*)
+	echo ${UNAME_MACHINE}-pc-mingw32
+	exit ;;
+    i*:windows32*:*)
+	# uname -m includes "-pc" on this system.
+	echo ${UNAME_MACHINE}-mingw32
+	exit ;;
+    i*:PW*:*)
+	echo ${UNAME_MACHINE}-pc-pw32
+	exit ;;
+    *:Interix*:*)
+	case ${UNAME_MACHINE} in
+	    x86)
+		echo i586-pc-interix${UNAME_RELEASE}
+		exit ;;
+	    authenticamd | genuineintel | EM64T)
+		echo x86_64-unknown-interix${UNAME_RELEASE}
+		exit ;;
+	    IA64)
+		echo ia64-unknown-interix${UNAME_RELEASE}
+		exit ;;
+	esac ;;
+    [345]86:Windows_95:* | [345]86:Windows_98:* | [345]86:Windows_NT:*)
+	echo i${UNAME_MACHINE}-pc-mks
+	exit ;;
+    8664:Windows_NT:*)
+	echo x86_64-pc-mks
+	exit ;;
+    i*:Windows_NT*:* | Pentium*:Windows_NT*:*)
+	# How do we know it's Interix rather than the generic POSIX subsystem?
+	# It also conflicts with pre-2.0 versions of AT&T UWIN. Should we
+	# UNAME_MACHINE based on the output of uname instead of i386?
+	echo i586-pc-interix
+	exit ;;
+    i*:UWIN*:*)
+	echo ${UNAME_MACHINE}-pc-uwin
+	exit ;;
+    amd64:CYGWIN*:*:* | x86_64:CYGWIN*:*:*)
+	echo x86_64-unknown-cygwin
+	exit ;;
+    p*:CYGWIN*:*)
+	echo powerpcle-unknown-cygwin
+	exit ;;
+    prep*:SunOS:5.*:*)
+	echo powerpcle-unknown-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+	exit ;;
+    *:GNU:*:*)
+	# the GNU system
+	echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-gnu`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'`
+	exit ;;
+    *:GNU/*:*:*)
+	# other systems with GNU libc and userland
+	echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr '[A-Z]' '[a-z]'``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-gnu
+	exit ;;
+    i*86:Minix:*:*)
+	echo ${UNAME_MACHINE}-pc-minix
+	exit ;;
+    alpha:Linux:*:*)
+	case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in
+	  EV5)   UNAME_MACHINE=alphaev5 ;;
+	  EV56)  UNAME_MACHINE=alphaev56 ;;
+	  PCA56) UNAME_MACHINE=alphapca56 ;;
+	  PCA57) UNAME_MACHINE=alphapca56 ;;
+	  EV6)   UNAME_MACHINE=alphaev6 ;;
+	  EV67)  UNAME_MACHINE=alphaev67 ;;
+	  EV68*) UNAME_MACHINE=alphaev68 ;;
+	esac
+	objdump --private-headers /bin/sh | grep -q ld.so.1
+	if test "$?" = 0 ; then LIBC="libc1" ; else LIBC="" ; fi
+	echo ${UNAME_MACHINE}-unknown-linux-gnu${LIBC}
+	exit ;;
+    arm*:Linux:*:*)
+	eval $set_cc_for_build
+	if echo __ARM_EABI__ | $CC_FOR_BUILD -E - 2>/dev/null \
+	    | grep -q __ARM_EABI__
+	then
+	    echo ${UNAME_MACHINE}-unknown-linux-gnu
+	else
+	    if echo __ARM_PCS_VFP | $CC_FOR_BUILD -E - 2>/dev/null \
+		| grep -q __ARM_PCS_VFP
+	    then
+		echo ${UNAME_MACHINE}-unknown-linux-gnueabi
+	    else
+		echo ${UNAME_MACHINE}-unknown-linux-gnueabihf
+	    fi
+	fi
+	exit ;;
+    avr32*:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	exit ;;
+    cris:Linux:*:*)
+	echo cris-axis-linux-gnu
+	exit ;;
+    crisv32:Linux:*:*)
+	echo crisv32-axis-linux-gnu
+	exit ;;
+    frv:Linux:*:*)
+	echo frv-unknown-linux-gnu
+	exit ;;
+    hexagon:Linux:*:*)
+	echo hexagon-unknown-linux-gnu
+	exit ;;
+    i*86:Linux:*:*)
+	LIBC=gnu
+	eval $set_cc_for_build
+	sed 's/^	//' << EOF >$dummy.c
+	#ifdef __dietlibc__
+	LIBC=dietlibc
+	#endif
+EOF
+	eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^LIBC'`
+	echo "${UNAME_MACHINE}-pc-linux-${LIBC}"
+	exit ;;
+    ia64:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	exit ;;
+    m32r*:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	exit ;;
+    m68*:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	exit ;;
+    mips:Linux:*:* | mips64:Linux:*:*)
+	eval $set_cc_for_build
+	sed 's/^	//' << EOF >$dummy.c
+	#undef CPU
+	#undef ${UNAME_MACHINE}
+	#undef ${UNAME_MACHINE}el
+	#if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL)
+	CPU=${UNAME_MACHINE}el
+	#else
+	#if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB)
+	CPU=${UNAME_MACHINE}
+	#else
+	CPU=
+	#endif
+	#endif
+EOF
+	eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^CPU'`
+	test x"${CPU}" != x && { echo "${CPU}-unknown-linux-gnu"; exit; }
+	;;
+    or32:Linux:*:*)
+	echo or32-unknown-linux-gnu
+	exit ;;
+    padre:Linux:*:*)
+	echo sparc-unknown-linux-gnu
+	exit ;;
+    parisc64:Linux:*:* | hppa64:Linux:*:*)
+	echo hppa64-unknown-linux-gnu
+	exit ;;
+    parisc:Linux:*:* | hppa:Linux:*:*)
+	# Look for CPU level
+	case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in
+	  PA7*) echo hppa1.1-unknown-linux-gnu ;;
+	  PA8*) echo hppa2.0-unknown-linux-gnu ;;
+	  *)    echo hppa-unknown-linux-gnu ;;
+	esac
+	exit ;;
+    ppc64:Linux:*:*)
+	echo powerpc64-unknown-linux-gnu
+	exit ;;
+    ppc:Linux:*:*)
+	echo powerpc-unknown-linux-gnu
+	exit ;;
+    s390:Linux:*:* | s390x:Linux:*:*)
+	echo ${UNAME_MACHINE}-ibm-linux
+	exit ;;
+    sh64*:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	exit ;;
+    sh*:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	exit ;;
+    sparc:Linux:*:* | sparc64:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	exit ;;
+    tile*:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	exit ;;
+    vax:Linux:*:*)
+	echo ${UNAME_MACHINE}-dec-linux-gnu
+	exit ;;
+    x86_64:Linux:*:*)
+	echo x86_64-unknown-linux-gnu
+	exit ;;
+    xtensa*:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	exit ;;
+    i*86:DYNIX/ptx:4*:*)
+	# ptx 4.0 does uname -s correctly, with DYNIX/ptx in there.
+	# earlier versions are messed up and put the nodename in both
+	# sysname and nodename.
+	echo i386-sequent-sysv4
+	exit ;;
+    i*86:UNIX_SV:4.2MP:2.*)
+	# Unixware is an offshoot of SVR4, but it has its own version
+	# number series starting with 2...
+	# I am not positive that other SVR4 systems won't match this,
+	# I just have to hope.  -- rms.
+	# Use sysv4.2uw... so that sysv4* matches it.
+	echo ${UNAME_MACHINE}-pc-sysv4.2uw${UNAME_VERSION}
+	exit ;;
+    i*86:OS/2:*:*)
+	# If we were able to find `uname', then EMX Unix compatibility
+	# is probably installed.
+	echo ${UNAME_MACHINE}-pc-os2-emx
+	exit ;;
+    i*86:XTS-300:*:STOP)
+	echo ${UNAME_MACHINE}-unknown-stop
+	exit ;;
+    i*86:atheos:*:*)
+	echo ${UNAME_MACHINE}-unknown-atheos
+	exit ;;
+    i*86:syllable:*:*)
+	echo ${UNAME_MACHINE}-pc-syllable
+	exit ;;
+    i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.[02]*:*)
+	echo i386-unknown-lynxos${UNAME_RELEASE}
+	exit ;;
+    i*86:*DOS:*:*)
+	echo ${UNAME_MACHINE}-pc-msdosdjgpp
+	exit ;;
+    i*86:*:4.*:* | i*86:SYSTEM_V:4.*:*)
+	UNAME_REL=`echo ${UNAME_RELEASE} | sed 's/\/MP$//'`
+	if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then
+		echo ${UNAME_MACHINE}-univel-sysv${UNAME_REL}
+	else
+		echo ${UNAME_MACHINE}-pc-sysv${UNAME_REL}
+	fi
+	exit ;;
+    i*86:*:5:[678]*)
+	# UnixWare 7.x, OpenUNIX and OpenServer 6.
+	case `/bin/uname -X | grep "^Machine"` in
+	    *486*)	     UNAME_MACHINE=i486 ;;
+	    *Pentium)	     UNAME_MACHINE=i586 ;;
+	    *Pent*|*Celeron) UNAME_MACHINE=i686 ;;
+	esac
+	echo ${UNAME_MACHINE}-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}${UNAME_VERSION}
+	exit ;;
+    i*86:*:3.2:*)
+	if test -f /usr/options/cb.name; then
+		UNAME_REL=`sed -n 's/.*Version //p' </usr/options/cb.name`
+		echo ${UNAME_MACHINE}-pc-isc$UNAME_REL
+	elif /bin/uname -X 2>/dev/null >/dev/null ; then
+		UNAME_REL=`(/bin/uname -X|grep Release|sed -e 's/.*= //')`
+		(/bin/uname -X|grep i80486 >/dev/null) && UNAME_MACHINE=i486
+		(/bin/uname -X|grep '^Machine.*Pentium' >/dev/null) \
+			&& UNAME_MACHINE=i586
+		(/bin/uname -X|grep '^Machine.*Pent *II' >/dev/null) \
+			&& UNAME_MACHINE=i686
+		(/bin/uname -X|grep '^Machine.*Pentium Pro' >/dev/null) \
+			&& UNAME_MACHINE=i686
+		echo ${UNAME_MACHINE}-pc-sco$UNAME_REL
+	else
+		echo ${UNAME_MACHINE}-pc-sysv32
+	fi
+	exit ;;
+    pc:*:*:*)
+	# Left here for compatibility:
+	# uname -m prints for DJGPP always 'pc', but it prints nothing about
+	# the processor, so we play safe by assuming i586.
+	# Note: whatever this is, it MUST be the same as what config.sub
+	# prints for the "djgpp" host, or else GDB configury will decide that
+	# this is a cross-build.
+	echo i586-pc-msdosdjgpp
+	exit ;;
+    Intel:Mach:3*:*)
+	echo i386-pc-mach3
+	exit ;;
+    paragon:*:*:*)
+	echo i860-intel-osf1
+	exit ;;
+    i860:*:4.*:*) # i860-SVR4
+	if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then
+	  echo i860-stardent-sysv${UNAME_RELEASE} # Stardent Vistra i860-SVR4
+	else # Add other i860-SVR4 vendors below as they are discovered.
+	  echo i860-unknown-sysv${UNAME_RELEASE}  # Unknown i860-SVR4
+	fi
+	exit ;;
+    mini*:CTIX:SYS*5:*)
+	# "miniframe"
+	echo m68010-convergent-sysv
+	exit ;;
+    mc68k:UNIX:SYSTEM5:3.51m)
+	echo m68k-convergent-sysv
+	exit ;;
+    M680?0:D-NIX:5.3:*)
+	echo m68k-diab-dnix
+	exit ;;
+    M68*:*:R3V[5678]*:*)
+	test -r /sysV68 && { echo 'm68k-motorola-sysv'; exit; } ;;
+    3[345]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 3[34]??/*:*:4.0:3.0 | 4400:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0 | SDS2:*:4.0:3.0 | SHG2:*:4.0:3.0 | S7501*:*:4.0:3.0)
+	OS_REL=''
+	test -r /etc/.relid \
+	&& OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid`
+	/bin/uname -p 2>/dev/null | grep 86 >/dev/null \
+	  && { echo i486-ncr-sysv4.3${OS_REL}; exit; }
+	/bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \
+	  && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;;
+    3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*)
+	/bin/uname -p 2>/dev/null | grep 86 >/dev/null \
+	  && { echo i486-ncr-sysv4; exit; } ;;
+    NCR*:*:4.2:* | MPRAS*:*:4.2:*)
+	OS_REL='.3'
+	test -r /etc/.relid \
+	    && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid`
+	/bin/uname -p 2>/dev/null | grep 86 >/dev/null \
+	    && { echo i486-ncr-sysv4.3${OS_REL}; exit; }
+	/bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \
+	    && { echo i586-ncr-sysv4.3${OS_REL}; exit; }
+	/bin/uname -p 2>/dev/null | /bin/grep pteron >/dev/null \
+	    && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;;
+    m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*)
+	echo m68k-unknown-lynxos${UNAME_RELEASE}
+	exit ;;
+    mc68030:UNIX_System_V:4.*:*)
+	echo m68k-atari-sysv4
+	exit ;;
+    TSUNAMI:LynxOS:2.*:*)
+	echo sparc-unknown-lynxos${UNAME_RELEASE}
+	exit ;;
+    rs6000:LynxOS:2.*:*)
+	echo rs6000-unknown-lynxos${UNAME_RELEASE}
+	exit ;;
+    PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.[02]*:*)
+	echo powerpc-unknown-lynxos${UNAME_RELEASE}
+	exit ;;
+    SM[BE]S:UNIX_SV:*:*)
+	echo mips-dde-sysv${UNAME_RELEASE}
+	exit ;;
+    RM*:ReliantUNIX-*:*:*)
+	echo mips-sni-sysv4
+	exit ;;
+    RM*:SINIX-*:*:*)
+	echo mips-sni-sysv4
+	exit ;;
+    *:SINIX-*:*:*)
+	if uname -p 2>/dev/null >/dev/null ; then
+		UNAME_MACHINE=`(uname -p) 2>/dev/null`
+		echo ${UNAME_MACHINE}-sni-sysv4
+	else
+		echo ns32k-sni-sysv
+	fi
+	exit ;;
+    PENTIUM:*:4.0*:*)	# Unisys `ClearPath HMP IX 4000' SVR4/MP effort
+			# says <Richard.M.Bartel at ccMail.Census.GOV>
+	echo i586-unisys-sysv4
+	exit ;;
+    *:UNIX_System_V:4*:FTX*)
+	# From Gerald Hewes <hewes at openmarket.com>.
+	# How about differentiating between stratus architectures? -djm
+	echo hppa1.1-stratus-sysv4
+	exit ;;
+    *:*:*:FTX*)
+	# From seanf at swdc.stratus.com.
+	echo i860-stratus-sysv4
+	exit ;;
+    i*86:VOS:*:*)
+	# From Paul.Green at stratus.com.
+	echo ${UNAME_MACHINE}-stratus-vos
+	exit ;;
+    *:VOS:*:*)
+	# From Paul.Green at stratus.com.
+	echo hppa1.1-stratus-vos
+	exit ;;
+    mc68*:A/UX:*:*)
+	echo m68k-apple-aux${UNAME_RELEASE}
+	exit ;;
+    news*:NEWS-OS:6*:*)
+	echo mips-sony-newsos6
+	exit ;;
+    R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*)
+	if [ -d /usr/nec ]; then
+		echo mips-nec-sysv${UNAME_RELEASE}
+	else
+		echo mips-unknown-sysv${UNAME_RELEASE}
+	fi
+	exit ;;
+    BeBox:BeOS:*:*)	# BeOS running on hardware made by Be, PPC only.
+	echo powerpc-be-beos
+	exit ;;
+    BeMac:BeOS:*:*)	# BeOS running on Mac or Mac clone, PPC only.
+	echo powerpc-apple-beos
+	exit ;;
+    BePC:BeOS:*:*)	# BeOS running on Intel PC compatible.
+	echo i586-pc-beos
+	exit ;;
+    BePC:Haiku:*:*)	# Haiku running on Intel PC compatible.
+	echo i586-pc-haiku
+	exit ;;
+    SX-4:SUPER-UX:*:*)
+	echo sx4-nec-superux${UNAME_RELEASE}
+	exit ;;
+    SX-5:SUPER-UX:*:*)
+	echo sx5-nec-superux${UNAME_RELEASE}
+	exit ;;
+    SX-6:SUPER-UX:*:*)
+	echo sx6-nec-superux${UNAME_RELEASE}
+	exit ;;
+    SX-7:SUPER-UX:*:*)
+	echo sx7-nec-superux${UNAME_RELEASE}
+	exit ;;
+    SX-8:SUPER-UX:*:*)
+	echo sx8-nec-superux${UNAME_RELEASE}
+	exit ;;
+    SX-8R:SUPER-UX:*:*)
+	echo sx8r-nec-superux${UNAME_RELEASE}
+	exit ;;
+    Power*:Rhapsody:*:*)
+	echo powerpc-apple-rhapsody${UNAME_RELEASE}
+	exit ;;
+    *:Rhapsody:*:*)
+	echo ${UNAME_MACHINE}-apple-rhapsody${UNAME_RELEASE}
+	exit ;;
+    *:Darwin:*:*)
+	UNAME_PROCESSOR=`uname -p` || UNAME_PROCESSOR=unknown
+	case $UNAME_PROCESSOR in
+	    i386)
+		eval $set_cc_for_build
+		if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then
+		  if (echo '#ifdef __LP64__'; echo IS_64BIT_ARCH; echo '#endif') | \
+		      (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \
+		      grep IS_64BIT_ARCH >/dev/null
+		  then
+		      UNAME_PROCESSOR="x86_64"
+		  fi
+		fi ;;
+	    unknown) UNAME_PROCESSOR=powerpc ;;
+	esac
+	echo ${UNAME_PROCESSOR}-apple-darwin${UNAME_RELEASE}
+	exit ;;
+    *:procnto*:*:* | *:QNX:[0123456789]*:*)
+	UNAME_PROCESSOR=`uname -p`
+	if test "$UNAME_PROCESSOR" = "x86"; then
+		UNAME_PROCESSOR=i386
+		UNAME_MACHINE=pc
+	fi
+	echo ${UNAME_PROCESSOR}-${UNAME_MACHINE}-nto-qnx${UNAME_RELEASE}
+	exit ;;
+    *:QNX:*:4*)
+	echo i386-pc-qnx
+	exit ;;
+    NEO-?:NONSTOP_KERNEL:*:*)
+	echo neo-tandem-nsk${UNAME_RELEASE}
+	exit ;;
+    NSE-?:NONSTOP_KERNEL:*:*)
+	echo nse-tandem-nsk${UNAME_RELEASE}
+	exit ;;
+    NSR-?:NONSTOP_KERNEL:*:*)
+	echo nsr-tandem-nsk${UNAME_RELEASE}
+	exit ;;
+    *:NonStop-UX:*:*)
+	echo mips-compaq-nonstopux
+	exit ;;
+    BS2000:POSIX*:*:*)
+	echo bs2000-siemens-sysv
+	exit ;;
+    DS/*:UNIX_System_V:*:*)
+	echo ${UNAME_MACHINE}-${UNAME_SYSTEM}-${UNAME_RELEASE}
+	exit ;;
+    *:Plan9:*:*)
+	# "uname -m" is not consistent, so use $cputype instead. 386
+	# is converted to i386 for consistency with other x86
+	# operating systems.
+	if test "$cputype" = "386"; then
+	    UNAME_MACHINE=i386
+	else
+	    UNAME_MACHINE="$cputype"
+	fi
+	echo ${UNAME_MACHINE}-unknown-plan9
+	exit ;;
+    *:TOPS-10:*:*)
+	echo pdp10-unknown-tops10
+	exit ;;
+    *:TENEX:*:*)
+	echo pdp10-unknown-tenex
+	exit ;;
+    KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*)
+	echo pdp10-dec-tops20
+	exit ;;
+    XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*)
+	echo pdp10-xkl-tops20
+	exit ;;
+    *:TOPS-20:*:*)
+	echo pdp10-unknown-tops20
+	exit ;;
+    *:ITS:*:*)
+	echo pdp10-unknown-its
+	exit ;;
+    SEI:*:*:SEIUX)
+	echo mips-sei-seiux${UNAME_RELEASE}
+	exit ;;
+    *:DragonFly:*:*)
+	echo ${UNAME_MACHINE}-unknown-dragonfly`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`
+	exit ;;
+    *:*VMS:*:*)
+	UNAME_MACHINE=`(uname -p) 2>/dev/null`
+	case "${UNAME_MACHINE}" in
+	    A*) echo alpha-dec-vms ; exit ;;
+	    I*) echo ia64-dec-vms ; exit ;;
+	    V*) echo vax-dec-vms ; exit ;;
+	esac ;;
+    *:XENIX:*:SysV)
+	echo i386-pc-xenix
+	exit ;;
+    i*86:skyos:*:*)
+	echo ${UNAME_MACHINE}-pc-skyos`echo ${UNAME_RELEASE}` | sed -e 's/ .*$//'
+	exit ;;
+    i*86:rdos:*:*)
+	echo ${UNAME_MACHINE}-pc-rdos
+	exit ;;
+    i*86:AROS:*:*)
+	echo ${UNAME_MACHINE}-pc-aros
+	exit ;;
+esac
+
+#echo '(No uname command or uname output not recognized.)' 1>&2
+#echo "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" 1>&2
+
+eval $set_cc_for_build
+cat >$dummy.c <<EOF
+#ifdef _SEQUENT_
+# include <sys/types.h>
+# include <sys/utsname.h>
+#endif
+main ()
+{
+#if defined (sony)
+#if defined (MIPSEB)
+  /* BFD wants "bsd" instead of "newsos".  Perhaps BFD should be changed,
+     I don't know....  */
+  printf ("mips-sony-bsd\n"); exit (0);
+#else
+#include <sys/param.h>
+  printf ("m68k-sony-newsos%s\n",
+#ifdef NEWSOS4
+	"4"
+#else
+	""
+#endif
+	); exit (0);
+#endif
+#endif
+
+#if defined (__arm) && defined (__acorn) && defined (__unix)
+  printf ("arm-acorn-riscix\n"); exit (0);
+#endif
+
+#if defined (hp300) && !defined (hpux)
+  printf ("m68k-hp-bsd\n"); exit (0);
+#endif
+
+#if defined (NeXT)
+#if !defined (__ARCHITECTURE__)
+#define __ARCHITECTURE__ "m68k"
+#endif
+  int version;
+  version=`(hostinfo | sed -n 's/.*NeXT Mach \([0-9]*\).*/\1/p') 2>/dev/null`;
+  if (version < 4)
+    printf ("%s-next-nextstep%d\n", __ARCHITECTURE__, version);
+  else
+    printf ("%s-next-openstep%d\n", __ARCHITECTURE__, version);
+  exit (0);
+#endif
+
+#if defined (MULTIMAX) || defined (n16)
+#if defined (UMAXV)
+  printf ("ns32k-encore-sysv\n"); exit (0);
+#else
+#if defined (CMU)
+  printf ("ns32k-encore-mach\n"); exit (0);
+#else
+  printf ("ns32k-encore-bsd\n"); exit (0);
+#endif
+#endif
+#endif
+
+#if defined (__386BSD__)
+  printf ("i386-pc-bsd\n"); exit (0);
+#endif
+
+#if defined (sequent)
+#if defined (i386)
+  printf ("i386-sequent-dynix\n"); exit (0);
+#endif
+#if defined (ns32000)
+  printf ("ns32k-sequent-dynix\n"); exit (0);
+#endif
+#endif
+
+#if defined (_SEQUENT_)
+    struct utsname un;
+
+    uname(&un);
+
+    if (strncmp(un.version, "V2", 2) == 0) {
+	printf ("i386-sequent-ptx2\n"); exit (0);
+    }
+    if (strncmp(un.version, "V1", 2) == 0) { /* XXX is V1 correct? */
+	printf ("i386-sequent-ptx1\n"); exit (0);
+    }
+    printf ("i386-sequent-ptx\n"); exit (0);
+
+#endif
+
+#if defined (vax)
+# if !defined (ultrix)
+#  include <sys/param.h>
+#  if defined (BSD)
+#   if BSD == 43
+      printf ("vax-dec-bsd4.3\n"); exit (0);
+#   else
+#    if BSD == 199006
+      printf ("vax-dec-bsd4.3reno\n"); exit (0);
+#    else
+      printf ("vax-dec-bsd\n"); exit (0);
+#    endif
+#   endif
+#  else
+    printf ("vax-dec-bsd\n"); exit (0);
+#  endif
+# else
+    printf ("vax-dec-ultrix\n"); exit (0);
+# endif
+#endif
+
+#if defined (alliant) && defined (i860)
+  printf ("i860-alliant-bsd\n"); exit (0);
+#endif
+
+  exit (1);
+}
+EOF
+
+$CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null && SYSTEM_NAME=`$dummy` &&
+	{ echo "$SYSTEM_NAME"; exit; }
+
+# Apollos put the system type in the environment.
+
+test -d /usr/apollo && { echo ${ISP}-apollo-${SYSTYPE}; exit; }
+
+# Convex versions that predate uname can use getsysinfo(1)
+
+if [ -x /usr/convex/getsysinfo ]
+then
+    case `getsysinfo -f cpu_type` in
+    c1*)
+	echo c1-convex-bsd
+	exit ;;
+    c2*)
+	if getsysinfo -f scalar_acc
+	then echo c32-convex-bsd
+	else echo c2-convex-bsd
+	fi
+	exit ;;
+    c34*)
+	echo c34-convex-bsd
+	exit ;;
+    c38*)
+	echo c38-convex-bsd
+	exit ;;
+    c4*)
+	echo c4-convex-bsd
+	exit ;;
+    esac
+fi
+
+cat >&2 <<EOF
+$0: unable to guess system type
+
+This script, last modified $timestamp, has failed to recognize
+the operating system you are using. It is advised that you
+download the most up to date version of the config scripts from
+
+  http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess;hb=HEAD
+and
+  http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub;hb=HEAD
+
+If the version you run ($0) is already up to date, please
+send the following data and any information you think might be
+pertinent to <config-patches at gnu.org> in order to provide the needed
+information to handle your system.
+
+config.guess timestamp = $timestamp
+
+uname -m = `(uname -m) 2>/dev/null || echo unknown`
+uname -r = `(uname -r) 2>/dev/null || echo unknown`
+uname -s = `(uname -s) 2>/dev/null || echo unknown`
+uname -v = `(uname -v) 2>/dev/null || echo unknown`
+
+/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null`
+/bin/uname -X     = `(/bin/uname -X) 2>/dev/null`
+
+hostinfo               = `(hostinfo) 2>/dev/null`
+/bin/universe          = `(/bin/universe) 2>/dev/null`
+/usr/bin/arch -k       = `(/usr/bin/arch -k) 2>/dev/null`
+/bin/arch              = `(/bin/arch) 2>/dev/null`
+/usr/bin/oslevel       = `(/usr/bin/oslevel) 2>/dev/null`
+/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null`
+
+UNAME_MACHINE = ${UNAME_MACHINE}
+UNAME_RELEASE = ${UNAME_RELEASE}
+UNAME_SYSTEM  = ${UNAME_SYSTEM}
+UNAME_VERSION = ${UNAME_VERSION}
+EOF
+
+exit 1
+
+# Local variables:
+# eval: (add-hook 'write-file-hooks 'time-stamp)
+# time-stamp-start: "timestamp='"
+# time-stamp-format: "%:y-%02m-%02d"
+# time-stamp-end: "'"
+# End:
diff --git a/config.sub b/config.sub
new file mode 100755
index 0000000..5b87368
--- /dev/null
+++ b/config.sub
@@ -0,0 +1,1767 @@
+#! /bin/sh
+# Configuration validation subroutine script.
+#   Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
+#   2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
+#   2011 Free Software Foundation, Inc.
+
+timestamp='2011-10-08'
+
+# This file is (in principle) common to ALL GNU software.
+# The presence of a machine in this file suggests that SOME GNU software
+# can handle that machine.  It does not imply ALL GNU software can.
+#
+# This file is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA
+# 02110-1301, USA.
+#
+# As a special exception to the GNU General Public License, if you
+# distribute this file as part of a program that contains a
+# configuration script generated by Autoconf, you may include it under
+# the same distribution terms that you use for the rest of that program.
+
+
+# Please send patches to <config-patches at gnu.org>.  Submit a context
+# diff and a properly formatted GNU ChangeLog entry.
+#
+# Configuration subroutine to validate and canonicalize a configuration type.
+# Supply the specified configuration type as an argument.
+# If it is invalid, we print an error message on stderr and exit with code 1.
+# Otherwise, we print the canonical config type on stdout and succeed.
+
+# You can get the latest version of this script from:
+# http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub;hb=HEAD
+
+# This file is supposed to be the same for all GNU packages
+# and recognize all the CPU types, system types and aliases
+# that are meaningful with *any* GNU software.
+# Each package is responsible for reporting which valid configurations
+# it does not support.  The user should be able to distinguish
+# a failure to support a valid configuration from a meaningless
+# configuration.
+
+# The goal of this file is to map all the various variations of a given
+# machine specification into a single specification in the form:
+#	CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM
+# or in some cases, the newer four-part form:
+#	CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM
+# It is wrong to echo any other type of specification.
+
+me=`echo "$0" | sed -e 's,.*/,,'`
+
+usage="\
+Usage: $0 [OPTION] CPU-MFR-OPSYS
+       $0 [OPTION] ALIAS
+
+Canonicalize a configuration name.
+
+Operation modes:
+  -h, --help         print this help, then exit
+  -t, --time-stamp   print date of last modification, then exit
+  -v, --version      print version number, then exit
+
+Report bugs and patches to <config-patches at gnu.org>."
+
+version="\
+GNU config.sub ($timestamp)
+
+Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
+2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free
+Software Foundation, Inc.
+
+This is free software; see the source for copying conditions.  There is NO
+warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
+
+help="
+Try \`$me --help' for more information."
+
+# Parse command line
+while test $# -gt 0 ; do
+  case $1 in
+    --time-stamp | --time* | -t )
+       echo "$timestamp" ; exit ;;
+    --version | -v )
+       echo "$version" ; exit ;;
+    --help | --h* | -h )
+       echo "$usage"; exit ;;
+    -- )     # Stop option processing
+       shift; break ;;
+    - )	# Use stdin as input.
+       break ;;
+    -* )
+       echo "$me: invalid option $1$help"
+       exit 1 ;;
+
+    *local*)
+       # First pass through any local machine types.
+       echo $1
+       exit ;;
+
+    * )
+       break ;;
+  esac
+done
+
+case $# in
+ 0) echo "$me: missing argument$help" >&2
+    exit 1;;
+ 1) ;;
+ *) echo "$me: too many arguments$help" >&2
+    exit 1;;
+esac
+
+# Separate what the user gave into CPU-COMPANY and OS or KERNEL-OS (if any).
+# Here we must recognize all the valid KERNEL-OS combinations.
+maybe_os=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\2/'`
+case $maybe_os in
+  nto-qnx* | linux-gnu* | linux-android* | linux-dietlibc | linux-newlib* | \
+  linux-uclibc* | uclinux-uclibc* | uclinux-gnu* | kfreebsd*-gnu* | \
+  knetbsd*-gnu* | netbsd*-gnu* | \
+  kopensolaris*-gnu* | \
+  storm-chaos* | os2-emx* | rtmk-nova*)
+    os=-$maybe_os
+    basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`
+    ;;
+  *)
+    basic_machine=`echo $1 | sed 's/-[^-]*$//'`
+    if [ $basic_machine != $1 ]
+    then os=`echo $1 | sed 's/.*-/-/'`
+    else os=; fi
+    ;;
+esac
+
+### Let's recognize common machines as not being operating systems so
+### that things like config.sub decstation-3100 work.  We also
+### recognize some manufacturers as not being operating systems, so we
+### can provide default operating systems below.
+case $os in
+	-sun*os*)
+		# Prevent following clause from handling this invalid input.
+		;;
+	-dec* | -mips* | -sequent* | -encore* | -pc532* | -sgi* | -sony* | \
+	-att* | -7300* | -3300* | -delta* | -motorola* | -sun[234]* | \
+	-unicom* | -ibm* | -next | -hp | -isi* | -apollo | -altos* | \
+	-convergent* | -ncr* | -news | -32* | -3600* | -3100* | -hitachi* |\
+	-c[123]* | -convex* | -sun | -crds | -omron* | -dg | -ultra | -tti* | \
+	-harris | -dolphin | -highlevel | -gould | -cbm | -ns | -masscomp | \
+	-apple | -axis | -knuth | -cray | -microblaze)
+		os=
+		basic_machine=$1
+		;;
+	-bluegene*)
+		os=-cnk
+		;;
+	-sim | -cisco | -oki | -wec | -winbond)
+		os=
+		basic_machine=$1
+		;;
+	-scout)
+		;;
+	-wrs)
+		os=-vxworks
+		basic_machine=$1
+		;;
+	-chorusos*)
+		os=-chorusos
+		basic_machine=$1
+		;;
+	-chorusrdb)
+		os=-chorusrdb
+		basic_machine=$1
+		;;
+	-hiux*)
+		os=-hiuxwe2
+		;;
+	-sco6)
+		os=-sco5v6
+		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+		;;
+	-sco5)
+		os=-sco3.2v5
+		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+		;;
+	-sco4)
+		os=-sco3.2v4
+		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+		;;
+	-sco3.2.[4-9]*)
+		os=`echo $os | sed -e 's/sco3.2./sco3.2v/'`
+		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+		;;
+	-sco3.2v[4-9]*)
+		# Don't forget version if it is 3.2v4 or newer.
+		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+		;;
+	-sco5v6*)
+		# Don't forget version if it is 3.2v4 or newer.
+		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+		;;
+	-sco*)
+		os=-sco3.2v2
+		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+		;;
+	-udk*)
+		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+		;;
+	-isc)
+		os=-isc2.2
+		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+		;;
+	-clix*)
+		basic_machine=clipper-intergraph
+		;;
+	-isc*)
+		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+		;;
+	-lynx*)
+		os=-lynxos
+		;;
+	-ptx*)
+		basic_machine=`echo $1 | sed -e 's/86-.*/86-sequent/'`
+		;;
+	-windowsnt*)
+		os=`echo $os | sed -e 's/windowsnt/winnt/'`
+		;;
+	-psos*)
+		os=-psos
+		;;
+	-mint | -mint[0-9]*)
+		basic_machine=m68k-atari
+		os=-mint
+		;;
+esac
+
+# Decode aliases for certain CPU-COMPANY combinations.
+case $basic_machine in
+	# Recognize the basic CPU types without company name.
+	# Some are omitted here because they have special meanings below.
+	1750a | 580 \
+	| a29k \
+	| alpha | alphaev[4-8] | alphaev56 | alphaev6[78] | alphapca5[67] \
+	| alpha64 | alpha64ev[4-8] | alpha64ev56 | alpha64ev6[78] | alpha64pca5[67] \
+	| am33_2.0 \
+	| arc | arm | arm[bl]e | arme[lb] | armv[2345] | armv[345][lb] | avr | avr32 \
+        | be32 | be64 \
+	| bfin \
+	| c4x | clipper \
+	| d10v | d30v | dlx | dsp16xx \
+	| epiphany \
+	| fido | fr30 | frv \
+	| h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \
+	| hexagon \
+	| i370 | i860 | i960 | ia64 \
+	| ip2k | iq2000 \
+	| le32 | le64 \
+	| lm32 \
+	| m32c | m32r | m32rle | m68000 | m68k | m88k \
+	| maxq | mb | microblaze | mcore | mep | metag \
+	| mips | mipsbe | mipseb | mipsel | mipsle \
+	| mips16 \
+	| mips64 | mips64el \
+	| mips64octeon | mips64octeonel \
+	| mips64orion | mips64orionel \
+	| mips64r5900 | mips64r5900el \
+	| mips64vr | mips64vrel \
+	| mips64vr4100 | mips64vr4100el \
+	| mips64vr4300 | mips64vr4300el \
+	| mips64vr5000 | mips64vr5000el \
+	| mips64vr5900 | mips64vr5900el \
+	| mipsisa32 | mipsisa32el \
+	| mipsisa32r2 | mipsisa32r2el \
+	| mipsisa64 | mipsisa64el \
+	| mipsisa64r2 | mipsisa64r2el \
+	| mipsisa64sb1 | mipsisa64sb1el \
+	| mipsisa64sr71k | mipsisa64sr71kel \
+	| mipstx39 | mipstx39el \
+	| mn10200 | mn10300 \
+	| moxie \
+	| mt \
+	| msp430 \
+	| nds32 | nds32le | nds32be \
+	| nios | nios2 \
+	| ns16k | ns32k \
+	| open8 \
+	| or32 \
+	| pdp10 | pdp11 | pj | pjl \
+	| powerpc | powerpc64 | powerpc64le | powerpcle \
+	| pyramid \
+	| rx \
+	| score \
+	| sh | sh[1234] | sh[24]a | sh[24]aeb | sh[23]e | sh[34]eb | sheb | shbe | shle | sh[1234]le | sh3ele \
+	| sh64 | sh64le \
+	| sparc | sparc64 | sparc64b | sparc64v | sparc86x | sparclet | sparclite \
+	| sparcv8 | sparcv9 | sparcv9b | sparcv9v \
+	| spu \
+	| tahoe | tic4x | tic54x | tic55x | tic6x | tic80 | tron \
+	| ubicom32 \
+	| v850 | v850e | v850e1 | v850e2 | v850es | v850e2v3 \
+	| we32k \
+	| x86 | xc16x | xstormy16 | xtensa \
+	| z8k | z80)
+		basic_machine=$basic_machine-unknown
+		;;
+	c54x)
+		basic_machine=tic54x-unknown
+		;;
+	c55x)
+		basic_machine=tic55x-unknown
+		;;
+	c6x)
+		basic_machine=tic6x-unknown
+		;;
+	m6811 | m68hc11 | m6812 | m68hc12 | picochip)
+		# Motorola 68HC11/12.
+		basic_machine=$basic_machine-unknown
+		os=-none
+		;;
+	m88110 | m680[12346]0 | m683?2 | m68360 | m5200 | v70 | w65 | z8k)
+		;;
+	ms1)
+		basic_machine=mt-unknown
+		;;
+
+	strongarm | thumb | xscale)
+		basic_machine=arm-unknown
+		;;
+
+	xscaleeb)
+		basic_machine=armeb-unknown
+		;;
+
+	xscaleel)
+		basic_machine=armel-unknown
+		;;
+
+	# We use `pc' rather than `unknown'
+	# because (1) that's what they normally are, and
+	# (2) the word "unknown" tends to confuse beginning users.
+	i*86 | x86_64)
+	  basic_machine=$basic_machine-pc
+	  ;;
+	# Object if more than one company name word.
+	*-*-*)
+		echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2
+		exit 1
+		;;
+	# Recognize the basic CPU types with company name.
+	580-* \
+	| a29k-* \
+	| alpha-* | alphaev[4-8]-* | alphaev56-* | alphaev6[78]-* \
+	| alpha64-* | alpha64ev[4-8]-* | alpha64ev56-* | alpha64ev6[78]-* \
+	| alphapca5[67]-* | alpha64pca5[67]-* | arc-* \
+	| arm-*  | armbe-* | armle-* | armeb-* | armv*-* \
+	| avr-* | avr32-* \
+	| be32-* | be64-* \
+	| bfin-* | bs2000-* \
+	| c[123]* | c30-* | [cjt]90-* | c4x-* \
+	| clipper-* | craynv-* | cydra-* \
+	| d10v-* | d30v-* | dlx-* \
+	| elxsi-* \
+	| f30[01]-* | f700-* | fido-* | fr30-* | frv-* | fx80-* \
+	| h8300-* | h8500-* \
+	| hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \
+	| hexagon-* \
+	| i*86-* | i860-* | i960-* | ia64-* \
+	| ip2k-* | iq2000-* \
+	| le32-* | le64-* \
+	| lm32-* \
+	| m32c-* | m32r-* | m32rle-* \
+	| m68000-* | m680[012346]0-* | m68360-* | m683?2-* | m68k-* \
+	| m88110-* | m88k-* | maxq-* | mcore-* | metag-* | microblaze-* \
+	| mips-* | mipsbe-* | mipseb-* | mipsel-* | mipsle-* \
+	| mips16-* \
+	| mips64-* | mips64el-* \
+	| mips64octeon-* | mips64octeonel-* \
+	| mips64orion-* | mips64orionel-* \
+	| mips64r5900-* | mips64r5900el-* \
+	| mips64vr-* | mips64vrel-* \
+	| mips64vr4100-* | mips64vr4100el-* \
+	| mips64vr4300-* | mips64vr4300el-* \
+	| mips64vr5000-* | mips64vr5000el-* \
+	| mips64vr5900-* | mips64vr5900el-* \
+	| mipsisa32-* | mipsisa32el-* \
+	| mipsisa32r2-* | mipsisa32r2el-* \
+	| mipsisa64-* | mipsisa64el-* \
+	| mipsisa64r2-* | mipsisa64r2el-* \
+	| mipsisa64sb1-* | mipsisa64sb1el-* \
+	| mipsisa64sr71k-* | mipsisa64sr71kel-* \
+	| mipstx39-* | mipstx39el-* \
+	| mmix-* \
+	| mt-* \
+	| msp430-* \
+	| nds32-* | nds32le-* | nds32be-* \
+	| nios-* | nios2-* \
+	| none-* | np1-* | ns16k-* | ns32k-* \
+	| open8-* \
+	| orion-* \
+	| pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \
+	| powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* \
+	| pyramid-* \
+	| romp-* | rs6000-* | rx-* \
+	| sh-* | sh[1234]-* | sh[24]a-* | sh[24]aeb-* | sh[23]e-* | sh[34]eb-* | sheb-* | shbe-* \
+	| shle-* | sh[1234]le-* | sh3ele-* | sh64-* | sh64le-* \
+	| sparc-* | sparc64-* | sparc64b-* | sparc64v-* | sparc86x-* | sparclet-* \
+	| sparclite-* \
+	| sparcv8-* | sparcv9-* | sparcv9b-* | sparcv9v-* | sv1-* | sx?-* \
+	| tahoe-* \
+	| tic30-* | tic4x-* | tic54x-* | tic55x-* | tic6x-* | tic80-* \
+	| tile*-* \
+	| tron-* \
+	| ubicom32-* \
+	| v850-* | v850e-* | v850e1-* | v850es-* | v850e2-* | v850e2v3-* \
+	| vax-* \
+	| we32k-* \
+	| x86-* | x86_64-* | xc16x-* | xps100-* \
+	| xstormy16-* | xtensa*-* \
+	| ymp-* \
+	| z8k-* | z80-*)
+		;;
+	# Recognize the basic CPU types without company name, with glob match.
+	xtensa*)
+		basic_machine=$basic_machine-unknown
+		;;
+	# Recognize the various machine names and aliases which stand
+	# for a CPU type and a company and sometimes even an OS.
+	386bsd)
+		basic_machine=i386-unknown
+		os=-bsd
+		;;
+	3b1 | 7300 | 7300-att | att-7300 | pc7300 | safari | unixpc)
+		basic_machine=m68000-att
+		;;
+	3b*)
+		basic_machine=we32k-att
+		;;
+	a29khif)
+		basic_machine=a29k-amd
+		os=-udi
+		;;
+	abacus)
+		basic_machine=abacus-unknown
+		;;
+	adobe68k)
+		basic_machine=m68010-adobe
+		os=-scout
+		;;
+	alliant | fx80)
+		basic_machine=fx80-alliant
+		;;
+	altos | altos3068)
+		basic_machine=m68k-altos
+		;;
+	am29k)
+		basic_machine=a29k-none
+		os=-bsd
+		;;
+	amd64)
+		basic_machine=x86_64-pc
+		;;
+	amd64-*)
+		basic_machine=x86_64-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	amdahl)
+		basic_machine=580-amdahl
+		os=-sysv
+		;;
+	amiga | amiga-*)
+		basic_machine=m68k-unknown
+		;;
+	amigaos | amigados)
+		basic_machine=m68k-unknown
+		os=-amigaos
+		;;
+	amigaunix | amix)
+		basic_machine=m68k-unknown
+		os=-sysv4
+		;;
+	apollo68)
+		basic_machine=m68k-apollo
+		os=-sysv
+		;;
+	apollo68bsd)
+		basic_machine=m68k-apollo
+		os=-bsd
+		;;
+	aros)
+		basic_machine=i386-pc
+		os=-aros
+		;;
+	aux)
+		basic_machine=m68k-apple
+		os=-aux
+		;;
+	balance)
+		basic_machine=ns32k-sequent
+		os=-dynix
+		;;
+	blackfin)
+		basic_machine=bfin-unknown
+		os=-linux
+		;;
+	blackfin-*)
+		basic_machine=bfin-`echo $basic_machine | sed 's/^[^-]*-//'`
+		os=-linux
+		;;
+	bluegene*)
+		basic_machine=powerpc-ibm
+		os=-cnk
+		;;
+	c54x-*)
+		basic_machine=tic54x-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	c55x-*)
+		basic_machine=tic55x-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	c6x-*)
+		basic_machine=tic6x-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	c90)
+		basic_machine=c90-cray
+		os=-unicos
+		;;
+	cegcc)
+		basic_machine=arm-unknown
+		os=-cegcc
+		;;
+	convex-c1)
+		basic_machine=c1-convex
+		os=-bsd
+		;;
+	convex-c2)
+		basic_machine=c2-convex
+		os=-bsd
+		;;
+	convex-c32)
+		basic_machine=c32-convex
+		os=-bsd
+		;;
+	convex-c34)
+		basic_machine=c34-convex
+		os=-bsd
+		;;
+	convex-c38)
+		basic_machine=c38-convex
+		os=-bsd
+		;;
+	cray | j90)
+		basic_machine=j90-cray
+		os=-unicos
+		;;
+	craynv)
+		basic_machine=craynv-cray
+		os=-unicosmp
+		;;
+	cr16 | cr16-*)
+		basic_machine=cr16-unknown
+		os=-elf
+		;;
+	crds | unos)
+		basic_machine=m68k-crds
+		;;
+	crisv32 | crisv32-* | etraxfs*)
+		basic_machine=crisv32-axis
+		;;
+	cris | cris-* | etrax*)
+		basic_machine=cris-axis
+		;;
+	crx)
+		basic_machine=crx-unknown
+		os=-elf
+		;;
+	da30 | da30-*)
+		basic_machine=m68k-da30
+		;;
+	decstation | decstation-3100 | pmax | pmax-* | pmin | dec3100 | decstatn)
+		basic_machine=mips-dec
+		;;
+	decsystem10* | dec10*)
+		basic_machine=pdp10-dec
+		os=-tops10
+		;;
+	decsystem20* | dec20*)
+		basic_machine=pdp10-dec
+		os=-tops20
+		;;
+	delta | 3300 | motorola-3300 | motorola-delta \
+	      | 3300-motorola | delta-motorola)
+		basic_machine=m68k-motorola
+		;;
+	delta88)
+		basic_machine=m88k-motorola
+		os=-sysv3
+		;;
+	dicos)
+		basic_machine=i686-pc
+		os=-dicos
+		;;
+	djgpp)
+		basic_machine=i586-pc
+		os=-msdosdjgpp
+		;;
+	dpx20 | dpx20-*)
+		basic_machine=rs6000-bull
+		os=-bosx
+		;;
+	dpx2* | dpx2*-bull)
+		basic_machine=m68k-bull
+		os=-sysv3
+		;;
+	ebmon29k)
+		basic_machine=a29k-amd
+		os=-ebmon
+		;;
+	elxsi)
+		basic_machine=elxsi-elxsi
+		os=-bsd
+		;;
+	encore | umax | mmax)
+		basic_machine=ns32k-encore
+		;;
+	es1800 | OSE68k | ose68k | ose | OSE)
+		basic_machine=m68k-ericsson
+		os=-ose
+		;;
+	fx2800)
+		basic_machine=i860-alliant
+		;;
+	genix)
+		basic_machine=ns32k-ns
+		;;
+	gmicro)
+		basic_machine=tron-gmicro
+		os=-sysv
+		;;
+	go32)
+		basic_machine=i386-pc
+		os=-go32
+		;;
+	h3050r* | hiux*)
+		basic_machine=hppa1.1-hitachi
+		os=-hiuxwe2
+		;;
+	h8300hms)
+		basic_machine=h8300-hitachi
+		os=-hms
+		;;
+	h8300xray)
+		basic_machine=h8300-hitachi
+		os=-xray
+		;;
+	h8500hms)
+		basic_machine=h8500-hitachi
+		os=-hms
+		;;
+	harris)
+		basic_machine=m88k-harris
+		os=-sysv3
+		;;
+	hp300-*)
+		basic_machine=m68k-hp
+		;;
+	hp300bsd)
+		basic_machine=m68k-hp
+		os=-bsd
+		;;
+	hp300hpux)
+		basic_machine=m68k-hp
+		os=-hpux
+		;;
+	hp3k9[0-9][0-9] | hp9[0-9][0-9])
+		basic_machine=hppa1.0-hp
+		;;
+	hp9k2[0-9][0-9] | hp9k31[0-9])
+		basic_machine=m68000-hp
+		;;
+	hp9k3[2-9][0-9])
+		basic_machine=m68k-hp
+		;;
+	hp9k6[0-9][0-9] | hp6[0-9][0-9])
+		basic_machine=hppa1.0-hp
+		;;
+	hp9k7[0-79][0-9] | hp7[0-79][0-9])
+		basic_machine=hppa1.1-hp
+		;;
+	hp9k78[0-9] | hp78[0-9])
+		# FIXME: really hppa2.0-hp
+		basic_machine=hppa1.1-hp
+		;;
+	hp9k8[67]1 | hp8[67]1 | hp9k80[24] | hp80[24] | hp9k8[78]9 | hp8[78]9 | hp9k893 | hp893)
+		# FIXME: really hppa2.0-hp
+		basic_machine=hppa1.1-hp
+		;;
+	hp9k8[0-9][13679] | hp8[0-9][13679])
+		basic_machine=hppa1.1-hp
+		;;
+	hp9k8[0-9][0-9] | hp8[0-9][0-9])
+		basic_machine=hppa1.0-hp
+		;;
+	hppa-next)
+		os=-nextstep3
+		;;
+	hppaosf)
+		basic_machine=hppa1.1-hp
+		os=-osf
+		;;
+	hppro)
+		basic_machine=hppa1.1-hp
+		os=-proelf
+		;;
+	i370-ibm* | ibm*)
+		basic_machine=i370-ibm
+		;;
+# I'm not sure what "Sysv32" means.  Should this be sysv3.2?
+	i*86v32)
+		basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
+		os=-sysv32
+		;;
+	i*86v4*)
+		basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
+		os=-sysv4
+		;;
+	i*86v)
+		basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
+		os=-sysv
+		;;
+	i*86sol2)
+		basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
+		os=-solaris2
+		;;
+	i386mach)
+		basic_machine=i386-mach
+		os=-mach
+		;;
+	i386-vsta | vsta)
+		basic_machine=i386-unknown
+		os=-vsta
+		;;
+	iris | iris4d)
+		basic_machine=mips-sgi
+		case $os in
+		    -irix*)
+			;;
+		    *)
+			os=-irix4
+			;;
+		esac
+		;;
+	isi68 | isi)
+		basic_machine=m68k-isi
+		os=-sysv
+		;;
+	m68knommu)
+		basic_machine=m68k-unknown
+		os=-linux
+		;;
+	m68knommu-*)
+		basic_machine=m68k-`echo $basic_machine | sed 's/^[^-]*-//'`
+		os=-linux
+		;;
+	m88k-omron*)
+		basic_machine=m88k-omron
+		;;
+	magnum | m3230)
+		basic_machine=mips-mips
+		os=-sysv
+		;;
+	merlin)
+		basic_machine=ns32k-utek
+		os=-sysv
+		;;
+	microblaze)
+		basic_machine=microblaze-xilinx
+		;;
+	mingw32)
+		basic_machine=i386-pc
+		os=-mingw32
+		;;
+	mingw32ce)
+		basic_machine=arm-unknown
+		os=-mingw32ce
+		;;
+	miniframe)
+		basic_machine=m68000-convergent
+		;;
+	*mint | -mint[0-9]* | *MiNT | *MiNT[0-9]*)
+		basic_machine=m68k-atari
+		os=-mint
+		;;
+	mips3*-*)
+		basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`
+		;;
+	mips3*)
+		basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`-unknown
+		;;
+	monitor)
+		basic_machine=m68k-rom68k
+		os=-coff
+		;;
+	morphos)
+		basic_machine=powerpc-unknown
+		os=-morphos
+		;;
+	msdos)
+		basic_machine=i386-pc
+		os=-msdos
+		;;
+	ms1-*)
+		basic_machine=`echo $basic_machine | sed -e 's/ms1-/mt-/'`
+		;;
+	mvs)
+		basic_machine=i370-ibm
+		os=-mvs
+		;;
+	nacl)
+		basic_machine=le32-unknown
+		os=-nacl
+		;;
+	ncr3000)
+		basic_machine=i486-ncr
+		os=-sysv4
+		;;
+	netbsd386)
+		basic_machine=i386-unknown
+		os=-netbsd
+		;;
+	netwinder)
+		basic_machine=armv4l-rebel
+		os=-linux
+		;;
+	news | news700 | news800 | news900)
+		basic_machine=m68k-sony
+		os=-newsos
+		;;
+	news1000)
+		basic_machine=m68030-sony
+		os=-newsos
+		;;
+	news-3600 | risc-news)
+		basic_machine=mips-sony
+		os=-newsos
+		;;
+	necv70)
+		basic_machine=v70-nec
+		os=-sysv
+		;;
+	next | m*-next )
+		basic_machine=m68k-next
+		case $os in
+		    -nextstep* )
+			;;
+		    -ns2*)
+		      os=-nextstep2
+			;;
+		    *)
+		      os=-nextstep3
+			;;
+		esac
+		;;
+	nh3000)
+		basic_machine=m68k-harris
+		os=-cxux
+		;;
+	nh[45]000)
+		basic_machine=m88k-harris
+		os=-cxux
+		;;
+	nindy960)
+		basic_machine=i960-intel
+		os=-nindy
+		;;
+	mon960)
+		basic_machine=i960-intel
+		os=-mon960
+		;;
+	nonstopux)
+		basic_machine=mips-compaq
+		os=-nonstopux
+		;;
+	np1)
+		basic_machine=np1-gould
+		;;
+	neo-tandem)
+		basic_machine=neo-tandem
+		;;
+	nse-tandem)
+		basic_machine=nse-tandem
+		;;
+	nsr-tandem)
+		basic_machine=nsr-tandem
+		;;
+	op50n-* | op60c-*)
+		basic_machine=hppa1.1-oki
+		os=-proelf
+		;;
+	openrisc | openrisc-*)
+		basic_machine=or32-unknown
+		;;
+	os400)
+		basic_machine=powerpc-ibm
+		os=-os400
+		;;
+	OSE68000 | ose68000)
+		basic_machine=m68000-ericsson
+		os=-ose
+		;;
+	os68k)
+		basic_machine=m68k-none
+		os=-os68k
+		;;
+	pa-hitachi)
+		basic_machine=hppa1.1-hitachi
+		os=-hiuxwe2
+		;;
+	paragon)
+		basic_machine=i860-intel
+		os=-osf
+		;;
+	parisc)
+		basic_machine=hppa-unknown
+		os=-linux
+		;;
+	parisc-*)
+		basic_machine=hppa-`echo $basic_machine | sed 's/^[^-]*-//'`
+		os=-linux
+		;;
+	pbd)
+		basic_machine=sparc-tti
+		;;
+	pbb)
+		basic_machine=m68k-tti
+		;;
+	pc532 | pc532-*)
+		basic_machine=ns32k-pc532
+		;;
+	pc98)
+		basic_machine=i386-pc
+		;;
+	pc98-*)
+		basic_machine=i386-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	pentium | p5 | k5 | k6 | nexgen | viac3)
+		basic_machine=i586-pc
+		;;
+	pentiumpro | p6 | 6x86 | athlon | athlon_*)
+		basic_machine=i686-pc
+		;;
+	pentiumii | pentium2 | pentiumiii | pentium3)
+		basic_machine=i686-pc
+		;;
+	pentium4)
+		basic_machine=i786-pc
+		;;
+	pentium-* | p5-* | k5-* | k6-* | nexgen-* | viac3-*)
+		basic_machine=i586-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	pentiumpro-* | p6-* | 6x86-* | athlon-*)
+		basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	pentiumii-* | pentium2-* | pentiumiii-* | pentium3-*)
+		basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	pentium4-*)
+		basic_machine=i786-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	pn)
+		basic_machine=pn-gould
+		;;
+	power)	basic_machine=power-ibm
+		;;
+	ppc | ppcbe)	basic_machine=powerpc-unknown
+		;;
+	ppc-* | ppcbe-*)
+		basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	ppcle | powerpclittle | ppc-le | powerpc-little)
+		basic_machine=powerpcle-unknown
+		;;
+	ppcle-* | powerpclittle-*)
+		basic_machine=powerpcle-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	ppc64)	basic_machine=powerpc64-unknown
+		;;
+	ppc64-*) basic_machine=powerpc64-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	ppc64le | powerpc64little | ppc64-le | powerpc64-little)
+		basic_machine=powerpc64le-unknown
+		;;
+	ppc64le-* | powerpc64little-*)
+		basic_machine=powerpc64le-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	ps2)
+		basic_machine=i386-ibm
+		;;
+	pw32)
+		basic_machine=i586-unknown
+		os=-pw32
+		;;
+	rdos)
+		basic_machine=i386-pc
+		os=-rdos
+		;;
+	rom68k)
+		basic_machine=m68k-rom68k
+		os=-coff
+		;;
+	rm[46]00)
+		basic_machine=mips-siemens
+		;;
+	rtpc | rtpc-*)
+		basic_machine=romp-ibm
+		;;
+	s390 | s390-*)
+		basic_machine=s390-ibm
+		;;
+	s390x | s390x-*)
+		basic_machine=s390x-ibm
+		;;
+	sa29200)
+		basic_machine=a29k-amd
+		os=-udi
+		;;
+	sb1)
+		basic_machine=mipsisa64sb1-unknown
+		;;
+	sb1el)
+		basic_machine=mipsisa64sb1el-unknown
+		;;
+	sde)
+		basic_machine=mipsisa32-sde
+		os=-elf
+		;;
+	sei)
+		basic_machine=mips-sei
+		os=-seiux
+		;;
+	sequent)
+		basic_machine=i386-sequent
+		;;
+	sh)
+		basic_machine=sh-hitachi
+		os=-hms
+		;;
+	sh5el)
+		basic_machine=sh5le-unknown
+		;;
+	sh64)
+		basic_machine=sh64-unknown
+		;;
+	sparclite-wrs | simso-wrs)
+		basic_machine=sparclite-wrs
+		os=-vxworks
+		;;
+	sps7)
+		basic_machine=m68k-bull
+		os=-sysv2
+		;;
+	spur)
+		basic_machine=spur-unknown
+		;;
+	st2000)
+		basic_machine=m68k-tandem
+		;;
+	stratus)
+		basic_machine=i860-stratus
+		os=-sysv4
+		;;
+	strongarm-* | thumb-*)
+		basic_machine=arm-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	sun2)
+		basic_machine=m68000-sun
+		;;
+	sun2os3)
+		basic_machine=m68000-sun
+		os=-sunos3
+		;;
+	sun2os4)
+		basic_machine=m68000-sun
+		os=-sunos4
+		;;
+	sun3os3)
+		basic_machine=m68k-sun
+		os=-sunos3
+		;;
+	sun3os4)
+		basic_machine=m68k-sun
+		os=-sunos4
+		;;
+	sun4os3)
+		basic_machine=sparc-sun
+		os=-sunos3
+		;;
+	sun4os4)
+		basic_machine=sparc-sun
+		os=-sunos4
+		;;
+	sun4sol2)
+		basic_machine=sparc-sun
+		os=-solaris2
+		;;
+	sun3 | sun3-*)
+		basic_machine=m68k-sun
+		;;
+	sun4)
+		basic_machine=sparc-sun
+		;;
+	sun386 | sun386i | roadrunner)
+		basic_machine=i386-sun
+		;;
+	sv1)
+		basic_machine=sv1-cray
+		os=-unicos
+		;;
+	symmetry)
+		basic_machine=i386-sequent
+		os=-dynix
+		;;
+	t3e)
+		basic_machine=alphaev5-cray
+		os=-unicos
+		;;
+	t90)
+		basic_machine=t90-cray
+		os=-unicos
+		;;
+	tile*)
+		basic_machine=$basic_machine-unknown
+		os=-linux-gnu
+		;;
+	tx39)
+		basic_machine=mipstx39-unknown
+		;;
+	tx39el)
+		basic_machine=mipstx39el-unknown
+		;;
+	toad1)
+		basic_machine=pdp10-xkl
+		os=-tops20
+		;;
+	tower | tower-32)
+		basic_machine=m68k-ncr
+		;;
+	tpf)
+		basic_machine=s390x-ibm
+		os=-tpf
+		;;
+	udi29k)
+		basic_machine=a29k-amd
+		os=-udi
+		;;
+	ultra3)
+		basic_machine=a29k-nyu
+		os=-sym1
+		;;
+	v810 | necv810)
+		basic_machine=v810-nec
+		os=-none
+		;;
+	vaxv)
+		basic_machine=vax-dec
+		os=-sysv
+		;;
+	vms)
+		basic_machine=vax-dec
+		os=-vms
+		;;
+	vpp*|vx|vx-*)
+		basic_machine=f301-fujitsu
+		;;
+	vxworks960)
+		basic_machine=i960-wrs
+		os=-vxworks
+		;;
+	vxworks68)
+		basic_machine=m68k-wrs
+		os=-vxworks
+		;;
+	vxworks29k)
+		basic_machine=a29k-wrs
+		os=-vxworks
+		;;
+	w65*)
+		basic_machine=w65-wdc
+		os=-none
+		;;
+	w89k-*)
+		basic_machine=hppa1.1-winbond
+		os=-proelf
+		;;
+	xbox)
+		basic_machine=i686-pc
+		os=-mingw32
+		;;
+	xps | xps100)
+		basic_machine=xps100-honeywell
+		;;
+	xscale-* | xscalee[bl]-*)
+		basic_machine=`echo $basic_machine | sed 's/^xscale/arm/'`
+		;;
+	ymp)
+		basic_machine=ymp-cray
+		os=-unicos
+		;;
+	z8k-*-coff)
+		basic_machine=z8k-unknown
+		os=-sim
+		;;
+	z80-*-coff)
+		basic_machine=z80-unknown
+		os=-sim
+		;;
+	none)
+		basic_machine=none-none
+		os=-none
+		;;
+
+# Here we handle the default manufacturer of certain CPU types.  It is in
+# some cases the only manufacturer, in others, it is the most popular.
+	w89k)
+		basic_machine=hppa1.1-winbond
+		;;
+	op50n)
+		basic_machine=hppa1.1-oki
+		;;
+	op60c)
+		basic_machine=hppa1.1-oki
+		;;
+	romp)
+		basic_machine=romp-ibm
+		;;
+	mmix)
+		basic_machine=mmix-knuth
+		;;
+	rs6000)
+		basic_machine=rs6000-ibm
+		;;
+	vax)
+		basic_machine=vax-dec
+		;;
+	pdp10)
+		# there are many clones, so DEC is not a safe bet
+		basic_machine=pdp10-unknown
+		;;
+	pdp11)
+		basic_machine=pdp11-dec
+		;;
+	we32k)
+		basic_machine=we32k-att
+		;;
+	sh[1234] | sh[24]a | sh[24]aeb | sh[34]eb | sh[1234]le | sh[23]ele)
+		basic_machine=sh-unknown
+		;;
+	sparc | sparcv8 | sparcv9 | sparcv9b | sparcv9v)
+		basic_machine=sparc-sun
+		;;
+	cydra)
+		basic_machine=cydra-cydrome
+		;;
+	orion)
+		basic_machine=orion-highlevel
+		;;
+	orion105)
+		basic_machine=clipper-highlevel
+		;;
+	mac | mpw | mac-mpw)
+		basic_machine=m68k-apple
+		;;
+	pmac | pmac-mpw)
+		basic_machine=powerpc-apple
+		;;
+	*-unknown)
+		# Make sure to match an already-canonicalized machine name.
+		;;
+	*)
+		echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2
+		exit 1
+		;;
+esac
+
+# Here we canonicalize certain aliases for manufacturers.
+case $basic_machine in
+	*-digital*)
+		basic_machine=`echo $basic_machine | sed 's/digital.*/dec/'`
+		;;
+	*-commodore*)
+		basic_machine=`echo $basic_machine | sed 's/commodore.*/cbm/'`
+		;;
+	*)
+		;;
+esac
+
+# Decode manufacturer-specific aliases for certain operating systems.
+
+if [ x"$os" != x"" ]
+then
+case $os in
+	# First match some system type aliases
+	# that might get confused with valid system types.
+	# -solaris* is a basic system type, with this one exception.
+	-auroraux)
+		os=-auroraux
+		;;
+	-solaris1 | -solaris1.*)
+		os=`echo $os | sed -e 's|solaris1|sunos4|'`
+		;;
+	-solaris)
+		os=-solaris2
+		;;
+	-svr4*)
+		os=-sysv4
+		;;
+	-unixware*)
+		os=-sysv4.2uw
+		;;
+	-gnu/linux*)
+		os=`echo $os | sed -e 's|gnu/linux|linux-gnu|'`
+		;;
+	# First accept the basic system types.
+	# The portable systems comes first.
+	# Each alternative MUST END IN A *, to match a version number.
+	# -sysv* is not here because it comes later, after sysvr4.
+	-gnu* | -bsd* | -mach* | -minix* | -genix* | -ultrix* | -irix* \
+	      | -*vms* | -sco* | -esix* | -isc* | -aix* | -cnk* | -sunos | -sunos[34]*\
+	      | -hpux* | -unos* | -osf* | -luna* | -dgux* | -auroraux* | -solaris* \
+	      | -sym* | -kopensolaris* \
+	      | -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \
+	      | -aos* | -aros* \
+	      | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \
+	      | -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \
+	      | -hiux* | -386bsd* | -knetbsd* | -mirbsd* | -netbsd* \
+	      | -openbsd* | -solidbsd* \
+	      | -ekkobsd* | -kfreebsd* | -freebsd* | -riscix* | -lynxos* \
+	      | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \
+	      | -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \
+	      | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \
+	      | -chorusos* | -chorusrdb* | -cegcc* \
+	      | -cygwin* | -pe* | -psos* | -moss* | -proelf* | -rtems* \
+	      | -mingw32* | -linux-gnu* | -linux-android* \
+	      | -linux-newlib* | -linux-uclibc* \
+	      | -uxpv* | -beos* | -mpeix* | -udk* \
+	      | -interix* | -uwin* | -mks* | -rhapsody* | -darwin* | -opened* \
+	      | -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \
+	      | -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* \
+	      | -os2* | -vos* | -palmos* | -uclinux* | -nucleus* \
+	      | -morphos* | -superux* | -rtmk* | -rtmk-nova* | -windiss* \
+	      | -powermax* | -dnix* | -nx6 | -nx7 | -sei* | -dragonfly* \
+	      | -skyos* | -haiku* | -rdos* | -toppers* | -drops* | -es*)
+	# Remember, each alternative MUST END IN *, to match a version number.
+		;;
+	-qnx*)
+		case $basic_machine in
+		    x86-* | i*86-*)
+			;;
+		    *)
+			os=-nto$os
+			;;
+		esac
+		;;
+	-nto-qnx*)
+		;;
+	-nto*)
+		os=`echo $os | sed -e 's|nto|nto-qnx|'`
+		;;
+	-sim | -es1800* | -hms* | -xray | -os68k* | -none* | -v88r* \
+	      | -windows* | -osx | -abug | -netware* | -os9* | -beos* | -haiku* \
+	      | -macos* | -mpw* | -magic* | -mmixware* | -mon960* | -lnews*)
+		;;
+	-mac*)
+		os=`echo $os | sed -e 's|mac|macos|'`
+		;;
+	-linux-dietlibc)
+		os=-linux-dietlibc
+		;;
+	-linux*)
+		os=`echo $os | sed -e 's|linux|linux-gnu|'`
+		;;
+	-sunos5*)
+		os=`echo $os | sed -e 's|sunos5|solaris2|'`
+		;;
+	-sunos6*)
+		os=`echo $os | sed -e 's|sunos6|solaris3|'`
+		;;
+	-opened*)
+		os=-openedition
+		;;
+	-os400*)
+		os=-os400
+		;;
+	-wince*)
+		os=-wince
+		;;
+	-osfrose*)
+		os=-osfrose
+		;;
+	-osf*)
+		os=-osf
+		;;
+	-utek*)
+		os=-bsd
+		;;
+	-dynix*)
+		os=-bsd
+		;;
+	-acis*)
+		os=-aos
+		;;
+	-atheos*)
+		os=-atheos
+		;;
+	-syllable*)
+		os=-syllable
+		;;
+	-386bsd)
+		os=-bsd
+		;;
+	-ctix* | -uts*)
+		os=-sysv
+		;;
+	-nova*)
+		os=-rtmk-nova
+		;;
+	-ns2 )
+		os=-nextstep2
+		;;
+	-nsk*)
+		os=-nsk
+		;;
+	# Preserve the version number of sinix5.
+	-sinix5.*)
+		os=`echo $os | sed -e 's|sinix|sysv|'`
+		;;
+	-sinix*)
+		os=-sysv4
+		;;
+	-tpf*)
+		os=-tpf
+		;;
+	-triton*)
+		os=-sysv3
+		;;
+	-oss*)
+		os=-sysv3
+		;;
+	-svr4)
+		os=-sysv4
+		;;
+	-svr3)
+		os=-sysv3
+		;;
+	-sysvr4)
+		os=-sysv4
+		;;
+	# This must come after -sysvr4.
+	-sysv*)
+		;;
+	-ose*)
+		os=-ose
+		;;
+	-es1800*)
+		os=-ose
+		;;
+	-xenix)
+		os=-xenix
+		;;
+	-*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*)
+		os=-mint
+		;;
+	-aros*)
+		os=-aros
+		;;
+	-kaos*)
+		os=-kaos
+		;;
+	-zvmoe)
+		os=-zvmoe
+		;;
+	-dicos*)
+		os=-dicos
+		;;
+	-nacl*)
+		;;
+	-none)
+		;;
+	*)
+		# Get rid of the `-' at the beginning of $os.
+		os=`echo $os | sed 's/[^-]*-//'`
+		echo Invalid configuration \`$1\': system \`$os\' not recognized 1>&2
+		exit 1
+		;;
+esac
+else
+
+# Here we handle the default operating systems that come with various machines.
+# The value should be what the vendor currently ships out the door with their
+# machine or put another way, the most popular os provided with the machine.
+
+# Note that if you're going to try to match "-MANUFACTURER" here (say,
+# "-sun"), then you have to tell the case statement up towards the top
+# that MANUFACTURER isn't an operating system.  Otherwise, code above
+# will signal an error saying that MANUFACTURER isn't an operating
+# system, and we'll never get to this point.
+
+case $basic_machine in
+	score-*)
+		os=-elf
+		;;
+	spu-*)
+		os=-elf
+		;;
+	*-acorn)
+		os=-riscix1.2
+		;;
+	arm*-rebel)
+		os=-linux
+		;;
+	arm*-semi)
+		os=-aout
+		;;
+	c4x-* | tic4x-*)
+		os=-coff
+		;;
+	tic54x-*)
+		os=-coff
+		;;
+	tic55x-*)
+		os=-coff
+		;;
+	tic6x-*)
+		os=-coff
+		;;
+	# This must come before the *-dec entry.
+	pdp10-*)
+		os=-tops20
+		;;
+	pdp11-*)
+		os=-none
+		;;
+	*-dec | vax-*)
+		os=-ultrix4.2
+		;;
+	m68*-apollo)
+		os=-domain
+		;;
+	i386-sun)
+		os=-sunos4.0.2
+		;;
+	m68000-sun)
+		os=-sunos3
+		# This also exists in the configure program, but was not the
+		# default.
+		# os=-sunos4
+		;;
+	m68*-cisco)
+		os=-aout
+		;;
+	mep-*)
+		os=-elf
+		;;
+	mips*-cisco)
+		os=-elf
+		;;
+	mips*-*)
+		os=-elf
+		;;
+	or32-*)
+		os=-coff
+		;;
+	*-tti)	# must be before sparc entry or we get the wrong os.
+		os=-sysv3
+		;;
+	sparc-* | *-sun)
+		os=-sunos4.1.1
+		;;
+	*-be)
+		os=-beos
+		;;
+	*-haiku)
+		os=-haiku
+		;;
+	*-ibm)
+		os=-aix
+		;;
+	*-knuth)
+		os=-mmixware
+		;;
+	*-wec)
+		os=-proelf
+		;;
+	*-winbond)
+		os=-proelf
+		;;
+	*-oki)
+		os=-proelf
+		;;
+	*-hp)
+		os=-hpux
+		;;
+	*-hitachi)
+		os=-hiux
+		;;
+	i860-* | *-att | *-ncr | *-altos | *-motorola | *-convergent)
+		os=-sysv
+		;;
+	*-cbm)
+		os=-amigaos
+		;;
+	*-dg)
+		os=-dgux
+		;;
+	*-dolphin)
+		os=-sysv3
+		;;
+	m68k-ccur)
+		os=-rtu
+		;;
+	m88k-omron*)
+		os=-luna
+		;;
+	*-next )
+		os=-nextstep
+		;;
+	*-sequent)
+		os=-ptx
+		;;
+	*-crds)
+		os=-unos
+		;;
+	*-ns)
+		os=-genix
+		;;
+	i370-*)
+		os=-mvs
+		;;
+	*-next)
+		os=-nextstep3
+		;;
+	*-gould)
+		os=-sysv
+		;;
+	*-highlevel)
+		os=-bsd
+		;;
+	*-encore)
+		os=-bsd
+		;;
+	*-sgi)
+		os=-irix
+		;;
+	*-siemens)
+		os=-sysv4
+		;;
+	*-masscomp)
+		os=-rtu
+		;;
+	f30[01]-fujitsu | f700-fujitsu)
+		os=-uxpv
+		;;
+	*-rom68k)
+		os=-coff
+		;;
+	*-*bug)
+		os=-coff
+		;;
+	*-apple)
+		os=-macos
+		;;
+	*-atari*)
+		os=-mint
+		;;
+	*)
+		os=-none
+		;;
+esac
+fi
+
+# Here we handle the case where we know the os, and the CPU type, but not the
+# manufacturer.  We pick the logical manufacturer.
+vendor=unknown
+case $basic_machine in
+	*-unknown)
+		case $os in
+			-riscix*)
+				vendor=acorn
+				;;
+			-sunos*)
+				vendor=sun
+				;;
+			-cnk*|-aix*)
+				vendor=ibm
+				;;
+			-beos*)
+				vendor=be
+				;;
+			-hpux*)
+				vendor=hp
+				;;
+			-mpeix*)
+				vendor=hp
+				;;
+			-hiux*)
+				vendor=hitachi
+				;;
+			-unos*)
+				vendor=crds
+				;;
+			-dgux*)
+				vendor=dg
+				;;
+			-luna*)
+				vendor=omron
+				;;
+			-genix*)
+				vendor=ns
+				;;
+			-mvs* | -opened*)
+				vendor=ibm
+				;;
+			-os400*)
+				vendor=ibm
+				;;
+			-ptx*)
+				vendor=sequent
+				;;
+			-tpf*)
+				vendor=ibm
+				;;
+			-vxsim* | -vxworks* | -windiss*)
+				vendor=wrs
+				;;
+			-aux*)
+				vendor=apple
+				;;
+			-hms*)
+				vendor=hitachi
+				;;
+			-mpw* | -macos*)
+				vendor=apple
+				;;
+			-*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*)
+				vendor=atari
+				;;
+			-vos*)
+				vendor=stratus
+				;;
+		esac
+		basic_machine=`echo $basic_machine | sed "s/unknown/$vendor/"`
+		;;
+esac
+
+echo $basic_machine$os
+exit
+
+# Local variables:
+# eval: (add-hook 'write-file-hooks 'time-stamp)
+# time-stamp-start: "timestamp='"
+# time-stamp-format: "%:y-%02m-%02d"
+# time-stamp-end: "'"
+# End:
diff --git a/configure b/configure
index d6b7834..2f9526f 100755
--- a/configure
+++ b/configure
@@ -1,81 +1,431 @@
 #! /bin/sh
 # Guess values for system-dependent variables and create Makefiles.
-# Generated by GNU Autoconf 2.59.
+# Generated by GNU Autoconf 2.68.
+#
+#
+# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001,
+# 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software
+# Foundation, Inc.
+#
 #
-# Copyright (C) 2003 Free Software Foundation, Inc.
 # This configure script is free software; the Free Software Foundation
 # gives unlimited permission to copy, distribute and modify it.
-## --------------------- ##
-## M4sh Initialization.  ##
-## --------------------- ##
+## -------------------- ##
+## M4sh Initialization. ##
+## -------------------- ##
 
-# Be Bourne compatible
-if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
+# Be more Bourne compatible
+DUALCASE=1; export DUALCASE # for MKS sh
+if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then :
   emulate sh
   NULLCMD=:
-  # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
+  # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which
   # is contrary to our usage.  Disable this feature.
   alias -g '${1+"$@"}'='"$@"'
-elif test -n "${BASH_VERSION+set}" && (set -o posix) >/dev/null 2>&1; then
-  set -o posix
+  setopt NO_GLOB_SUBST
+else
+  case `(set -o) 2>/dev/null` in #(
+  *posix*) :
+    set -o posix ;; #(
+  *) :
+     ;;
+esac
 fi
-DUALCASE=1; export DUALCASE # for MKS sh
 
-# Support unset when possible.
-if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then
-  as_unset=unset
-else
-  as_unset=false
+
+as_nl='
+'
+export as_nl
+# Printing a long string crashes Solaris 7 /usr/bin/printf.
+as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
+as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo
+as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo
+# Prefer a ksh shell builtin over an external printf program on Solaris,
+# but without wasting forks for bash or zsh.
+if test -z "$BASH_VERSION$ZSH_VERSION" \
+    && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then
+  as_echo='print -r --'
+  as_echo_n='print -rn --'
+elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then
+  as_echo='printf %s\n'
+  as_echo_n='printf %s'
+else
+  if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then
+    as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"'
+    as_echo_n='/usr/ucb/echo -n'
+  else
+    as_echo_body='eval expr "X$1" : "X\\(.*\\)"'
+    as_echo_n_body='eval
+      arg=$1;
+      case $arg in #(
+      *"$as_nl"*)
+	expr "X$arg" : "X\\(.*\\)$as_nl";
+	arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;;
+      esac;
+      expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl"
+    '
+    export as_echo_n_body
+    as_echo_n='sh -c $as_echo_n_body as_echo'
+  fi
+  export as_echo_body
+  as_echo='sh -c $as_echo_body as_echo'
 fi
 
+# The user is always right.
+if test "${PATH_SEPARATOR+set}" != set; then
+  PATH_SEPARATOR=:
+  (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && {
+    (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 ||
+      PATH_SEPARATOR=';'
+  }
+fi
+
+
+# IFS
+# We need space, tab and new line, in precisely that order.  Quoting is
+# there to prevent editors from complaining about space-tab.
+# (If _AS_PATH_WALK were called with IFS unset, it would disable word
+# splitting by setting IFS to empty value.)
+IFS=" ""	$as_nl"
+
+# Find who we are.  Look in the path if we contain no directory separator.
+as_myself=
+case $0 in #((
+  *[\\/]* ) as_myself=$0 ;;
+  *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
+  done
+IFS=$as_save_IFS
 
-# Work around bugs in pre-3.0 UWIN ksh.
-$as_unset ENV MAIL MAILPATH
+     ;;
+esac
+# We did not find ourselves, most probably we were run as `sh COMMAND'
+# in which case we are not to be found in the path.
+if test "x$as_myself" = x; then
+  as_myself=$0
+fi
+if test ! -f "$as_myself"; then
+  $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2
+  exit 1
+fi
+
+# Unset variables that we do not need and which cause bugs (e.g. in
+# pre-3.0 UWIN ksh).  But do not cause bugs in bash 2.01; the "|| exit 1"
+# suppresses any "Segmentation fault" message there.  '((' could
+# trigger a bug in pdksh 5.2.14.
+for as_var in BASH_ENV ENV MAIL MAILPATH
+do eval test x\${$as_var+set} = xset \
+  && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || :
+done
 PS1='$ '
 PS2='> '
 PS4='+ '
 
 # NLS nuisances.
-for as_var in \
-  LANG LANGUAGE LC_ADDRESS LC_ALL LC_COLLATE LC_CTYPE LC_IDENTIFICATION \
-  LC_MEASUREMENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER \
-  LC_TELEPHONE LC_TIME
+LC_ALL=C
+export LC_ALL
+LANGUAGE=C
+export LANGUAGE
+
+# CDPATH.
+(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
+
+if test "x$CONFIG_SHELL" = x; then
+  as_bourne_compatible="if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then :
+  emulate sh
+  NULLCMD=:
+  # Pre-4.2 versions of Zsh do word splitting on \${1+\"\$@\"}, which
+  # is contrary to our usage.  Disable this feature.
+  alias -g '\${1+\"\$@\"}'='\"\$@\"'
+  setopt NO_GLOB_SUBST
+else
+  case \`(set -o) 2>/dev/null\` in #(
+  *posix*) :
+    set -o posix ;; #(
+  *) :
+     ;;
+esac
+fi
+"
+  as_required="as_fn_return () { (exit \$1); }
+as_fn_success () { as_fn_return 0; }
+as_fn_failure () { as_fn_return 1; }
+as_fn_ret_success () { return 0; }
+as_fn_ret_failure () { return 1; }
+
+exitcode=0
+as_fn_success || { exitcode=1; echo as_fn_success failed.; }
+as_fn_failure && { exitcode=1; echo as_fn_failure succeeded.; }
+as_fn_ret_success || { exitcode=1; echo as_fn_ret_success failed.; }
+as_fn_ret_failure && { exitcode=1; echo as_fn_ret_failure succeeded.; }
+if ( set x; as_fn_ret_success y && test x = \"\$1\" ); then :
+
+else
+  exitcode=1; echo positional parameters were not saved.
+fi
+test x\$exitcode = x0 || exit 1"
+  as_suggested="  as_lineno_1=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_1a=\$LINENO
+  as_lineno_2=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_2a=\$LINENO
+  eval 'test \"x\$as_lineno_1'\$as_run'\" != \"x\$as_lineno_2'\$as_run'\" &&
+  test \"x\`expr \$as_lineno_1'\$as_run' + 1\`\" = \"x\$as_lineno_2'\$as_run'\"' || exit 1
+
+  test -n \"\${ZSH_VERSION+set}\${BASH_VERSION+set}\" || (
+    ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
+    ECHO=\$ECHO\$ECHO\$ECHO\$ECHO\$ECHO
+    ECHO=\$ECHO\$ECHO\$ECHO\$ECHO\$ECHO\$ECHO
+    PATH=/empty FPATH=/empty; export PATH FPATH
+    test \"X\`printf %s \$ECHO\`\" = \"X\$ECHO\" \\
+      || test \"X\`print -r -- \$ECHO\`\" = \"X\$ECHO\" ) || exit 1
+test \$(( 1 + 1 )) = 2 || exit 1"
+  if (eval "$as_required") 2>/dev/null; then :
+  as_have_required=yes
+else
+  as_have_required=no
+fi
+  if test x$as_have_required = xyes && (eval "$as_suggested") 2>/dev/null; then :
+
+else
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+as_found=false
+for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH
 do
-  if (set +x; test -z "`(eval $as_var=C; export $as_var) 2>&1`"); then
-    eval $as_var=C; export $as_var
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  as_found=:
+  case $as_dir in #(
+	 /*)
+	   for as_base in sh bash ksh sh5; do
+	     # Try only shells that exist, to save several forks.
+	     as_shell=$as_dir/$as_base
+	     if { test -f "$as_shell" || test -f "$as_shell.exe"; } &&
+		    { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$as_shell"; } 2>/dev/null; then :
+  CONFIG_SHELL=$as_shell as_have_required=yes
+		   if { $as_echo "$as_bourne_compatible""$as_suggested" | as_run=a "$as_shell"; } 2>/dev/null; then :
+  break 2
+fi
+fi
+	   done;;
+       esac
+  as_found=false
+done
+$as_found || { if { test -f "$SHELL" || test -f "$SHELL.exe"; } &&
+	      { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$SHELL"; } 2>/dev/null; then :
+  CONFIG_SHELL=$SHELL as_have_required=yes
+fi; }
+IFS=$as_save_IFS
+
+
+      if test "x$CONFIG_SHELL" != x; then :
+  # We cannot yet assume a decent shell, so we have to provide a
+	# neutralization value for shells without unset; and this also
+	# works around shells that cannot unset nonexistent variables.
+	# Preserve -v and -x to the replacement shell.
+	BASH_ENV=/dev/null
+	ENV=/dev/null
+	(unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV
+	export CONFIG_SHELL
+	case $- in # ((((
+	  *v*x* | *x*v* ) as_opts=-vx ;;
+	  *v* ) as_opts=-v ;;
+	  *x* ) as_opts=-x ;;
+	  * ) as_opts= ;;
+	esac
+	exec "$CONFIG_SHELL" $as_opts "$as_myself" ${1+"$@"}
+fi
+
+    if test x$as_have_required = xno; then :
+  $as_echo "$0: This script requires a shell more modern than all"
+  $as_echo "$0: the shells that I found on your system."
+  if test x${ZSH_VERSION+set} = xset ; then
+    $as_echo "$0: In particular, zsh $ZSH_VERSION has bugs and should"
+    $as_echo "$0: be upgraded to zsh 4.3.4 or later."
   else
-    $as_unset $as_var
+    $as_echo "$0: Please tell bug-autoconf at gnu.org about your system,
+$0: including any error possibly output before this
+$0: message. Then install a modern shell, or manually run
+$0: the script under such a shell if you do have one."
   fi
-done
+  exit 1
+fi
+fi
+fi
+SHELL=${CONFIG_SHELL-/bin/sh}
+export SHELL
+# Unset more variables known to interfere with behavior of common tools.
+CLICOLOR_FORCE= GREP_OPTIONS=
+unset CLICOLOR_FORCE GREP_OPTIONS
+
+## --------------------- ##
+## M4sh Shell Functions. ##
+## --------------------- ##
+# as_fn_unset VAR
+# ---------------
+# Portably unset VAR.
+as_fn_unset ()
+{
+  { eval $1=; unset $1;}
+}
+as_unset=as_fn_unset
+
+# as_fn_set_status STATUS
+# -----------------------
+# Set $? to STATUS, without forking.
+as_fn_set_status ()
+{
+  return $1
+} # as_fn_set_status
+
+# as_fn_exit STATUS
+# -----------------
+# Exit the shell with STATUS, even in a "trap 0" or "set -e" context.
+as_fn_exit ()
+{
+  set +e
+  as_fn_set_status $1
+  exit $1
+} # as_fn_exit
+
+# as_fn_mkdir_p
+# -------------
+# Create "$as_dir" as a directory, including parents if necessary.
+as_fn_mkdir_p ()
+{
+
+  case $as_dir in #(
+  -*) as_dir=./$as_dir;;
+  esac
+  test -d "$as_dir" || eval $as_mkdir_p || {
+    as_dirs=
+    while :; do
+      case $as_dir in #(
+      *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'(
+      *) as_qdir=$as_dir;;
+      esac
+      as_dirs="'$as_qdir' $as_dirs"
+      as_dir=`$as_dirname -- "$as_dir" ||
+$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	 X"$as_dir" : 'X\(//\)[^/]' \| \
+	 X"$as_dir" : 'X\(//\)$' \| \
+	 X"$as_dir" : 'X\(/\)' \| . 2>/dev/null ||
+$as_echo X"$as_dir" |
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)[^/].*/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+      test -d "$as_dir" && break
+    done
+    test -z "$as_dirs" || eval "mkdir $as_dirs"
+  } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir"
+
+
+} # as_fn_mkdir_p
+# as_fn_append VAR VALUE
+# ----------------------
+# Append the text in VALUE to the end of the definition contained in VAR. Take
+# advantage of any shell optimizations that allow amortized linear growth over
+# repeated appends, instead of the typical quadratic growth present in naive
+# implementations.
+if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then :
+  eval 'as_fn_append ()
+  {
+    eval $1+=\$2
+  }'
+else
+  as_fn_append ()
+  {
+    eval $1=\$$1\$2
+  }
+fi # as_fn_append
+
+# as_fn_arith ARG...
+# ------------------
+# Perform arithmetic evaluation on the ARGs, and store the result in the
+# global $as_val. Take advantage of shells that can avoid forks. The arguments
+# must be portable across $(()) and expr.
+if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then :
+  eval 'as_fn_arith ()
+  {
+    as_val=$(( $* ))
+  }'
+else
+  as_fn_arith ()
+  {
+    as_val=`expr "$@" || test $? -eq 1`
+  }
+fi # as_fn_arith
+
+
+# as_fn_error STATUS ERROR [LINENO LOG_FD]
+# ----------------------------------------
+# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are
+# provided, also output the error to LOG_FD, referencing LINENO. Then exit the
+# script with STATUS, using 1 if that was 0.
+as_fn_error ()
+{
+  as_status=$1; test $as_status -eq 0 && as_status=1
+  if test "$4"; then
+    as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+    $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4
+  fi
+  $as_echo "$as_me: error: $2" >&2
+  as_fn_exit $as_status
+} # as_fn_error
 
-# Required to use basename.
-if expr a : '\(a\)' >/dev/null 2>&1; then
+if expr a : '\(a\)' >/dev/null 2>&1 &&
+   test "X`expr 00001 : '.*\(...\)'`" = X001; then
   as_expr=expr
 else
   as_expr=false
 fi
 
-if (basename /) >/dev/null 2>&1 && test "X`basename / 2>&1`" = "X/"; then
+if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then
   as_basename=basename
 else
   as_basename=false
 fi
 
+if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then
+  as_dirname=dirname
+else
+  as_dirname=false
+fi
 
-# Name of the executable.
-as_me=`$as_basename "$0" ||
+as_me=`$as_basename -- "$0" ||
 $as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
 	 X"$0" : 'X\(//\)$' \| \
-	 X"$0" : 'X\(/\)$' \| \
-	 .     : '\(.\)' 2>/dev/null ||
-echo X/"$0" |
-    sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/; q; }
-  	  /^X\/\(\/\/\)$/{ s//\1/; q; }
-  	  /^X\/\(\/\).*/{ s//\1/; q; }
-  	  s/.*/./; q'`
+	 X"$0" : 'X\(/\)' \| . 2>/dev/null ||
+$as_echo X/"$0" |
+    sed '/^.*\/\([^/][^/]*\)\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\/\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\/\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
 
-
-# PATH needs CR, and LINENO needs CR and PATH.
 # Avoid depending upon Character Ranges.
 as_cr_letters='abcdefghijklmnopqrstuvwxyz'
 as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
@@ -83,146 +433,107 @@ as_cr_Letters=$as_cr_letters$as_cr_LETTERS
 as_cr_digits='0123456789'
 as_cr_alnum=$as_cr_Letters$as_cr_digits
 
-# The user is always right.
-if test "${PATH_SEPARATOR+set}" != set; then
-  echo "#! /bin/sh" >conf$$.sh
-  echo  "exit 0"   >>conf$$.sh
-  chmod +x conf$$.sh
-  if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then
-    PATH_SEPARATOR=';'
-  else
-    PATH_SEPARATOR=:
-  fi
-  rm -f conf$$.sh
-fi
-
-
-  as_lineno_1=$LINENO
-  as_lineno_2=$LINENO
-  as_lineno_3=`(expr $as_lineno_1 + 1) 2>/dev/null`
-  test "x$as_lineno_1" != "x$as_lineno_2" &&
-  test "x$as_lineno_3"  = "x$as_lineno_2"  || {
-  # Find who we are.  Look in the path if we contain no path at all
-  # relative or not.
-  case $0 in
-    *[\\/]* ) as_myself=$0 ;;
-    *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
-done
-
-       ;;
-  esac
-  # We did not find ourselves, most probably we were run as `sh COMMAND'
-  # in which case we are not to be found in the path.
-  if test "x$as_myself" = x; then
-    as_myself=$0
-  fi
-  if test ! -f "$as_myself"; then
-    { echo "$as_me: error: cannot find myself; rerun with an absolute path" >&2
-   { (exit 1); exit 1; }; }
-  fi
-  case $CONFIG_SHELL in
-  '')
-    as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  for as_base in sh bash ksh sh5; do
-	 case $as_dir in
-	 /*)
-	   if ("$as_dir/$as_base" -c '
-  as_lineno_1=$LINENO
-  as_lineno_2=$LINENO
-  as_lineno_3=`(expr $as_lineno_1 + 1) 2>/dev/null`
-  test "x$as_lineno_1" != "x$as_lineno_2" &&
-  test "x$as_lineno_3"  = "x$as_lineno_2" ') 2>/dev/null; then
-	     $as_unset BASH_ENV || test "${BASH_ENV+set}" != set || { BASH_ENV=; export BASH_ENV; }
-	     $as_unset ENV || test "${ENV+set}" != set || { ENV=; export ENV; }
-	     CONFIG_SHELL=$as_dir/$as_base
-	     export CONFIG_SHELL
-	     exec "$CONFIG_SHELL" "$0" ${1+"$@"}
-	   fi;;
-	 esac
-       done
-done
-;;
-  esac
 
-  # Create $as_me.lineno as a copy of $as_myself, but with $LINENO
-  # uniformly replaced by the line number.  The first 'sed' inserts a
-  # line-number line before each line; the second 'sed' does the real
-  # work.  The second script uses 'N' to pair each line-number line
-  # with the numbered line, and appends trailing '-' during
-  # substitution so that $LINENO is not a special case at line end.
-  # (Raja R Harinath suggested sed '=', and Paul Eggert wrote the
-  # second 'sed' script.  Blame Lee E. McMahon for sed's syntax.  :-)
-  sed '=' <$as_myself |
+  as_lineno_1=$LINENO as_lineno_1a=$LINENO
+  as_lineno_2=$LINENO as_lineno_2a=$LINENO
+  eval 'test "x$as_lineno_1'$as_run'" != "x$as_lineno_2'$as_run'" &&
+  test "x`expr $as_lineno_1'$as_run' + 1`" = "x$as_lineno_2'$as_run'"' || {
+  # Blame Lee E. McMahon (1931-1989) for sed's syntax.  :-)
+  sed -n '
+    p
+    /[$]LINENO/=
+  ' <$as_myself |
     sed '
+      s/[$]LINENO.*/&-/
+      t lineno
+      b
+      :lineno
       N
-      s,$,-,
-      : loop
-      s,^\(['$as_cr_digits']*\)\(.*\)[$]LINENO\([^'$as_cr_alnum'_]\),\1\2\1\3,
+      :loop
+      s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/
       t loop
-      s,-$,,
-      s,^['$as_cr_digits']*\n,,
+      s/-\n.*//
     ' >$as_me.lineno &&
-  chmod +x $as_me.lineno ||
-    { echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2
-   { (exit 1); exit 1; }; }
+  chmod +x "$as_me.lineno" ||
+    { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2; as_fn_exit 1; }
 
   # Don't try to exec as it changes $[0], causing all sort of problems
   # (the dirname of $[0] is not the place where we might find the
-  # original and so on.  Autoconf is especially sensible to this).
-  . ./$as_me.lineno
+  # original and so on.  Autoconf is especially sensitive to this).
+  . "./$as_me.lineno"
   # Exit status is that of the last command.
   exit
 }
 
-
-case `echo "testing\c"; echo 1,2,3`,`echo -n testing; echo 1,2,3` in
-  *c*,-n*) ECHO_N= ECHO_C='
-' ECHO_T='	' ;;
-  *c*,*  ) ECHO_N=-n ECHO_C= ECHO_T= ;;
-  *)       ECHO_N= ECHO_C='\c' ECHO_T= ;;
+ECHO_C= ECHO_N= ECHO_T=
+case `echo -n x` in #(((((
+-n*)
+  case `echo 'xy\c'` in
+  *c*) ECHO_T='	';;	# ECHO_T is single tab character.
+  xy)  ECHO_C='\c';;
+  *)   echo `echo ksh88 bug on AIX 6.1` > /dev/null
+       ECHO_T='	';;
+  esac;;
+*)
+  ECHO_N='-n';;
 esac
 
-if expr a : '\(a\)' >/dev/null 2>&1; then
-  as_expr=expr
+rm -f conf$$ conf$$.exe conf$$.file
+if test -d conf$$.dir; then
+  rm -f conf$$.dir/conf$$.file
 else
-  as_expr=false
+  rm -f conf$$.dir
+  mkdir conf$$.dir 2>/dev/null
 fi
-
-rm -f conf$$ conf$$.exe conf$$.file
-echo >conf$$.file
-if ln -s conf$$.file conf$$ 2>/dev/null; then
-  # We could just check for DJGPP; but this test a) works b) is more generic
-  # and c) will remain valid once DJGPP supports symlinks (DJGPP 2.04).
-  if test -f conf$$.exe; then
-    # Don't use ln at all; we don't have any links
-    as_ln_s='cp -p'
-  else
+if (echo >conf$$.file) 2>/dev/null; then
+  if ln -s conf$$.file conf$$ 2>/dev/null; then
     as_ln_s='ln -s'
+    # ... but there are two gotchas:
+    # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
+    # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.
+    # In both cases, we have to default to `cp -p'.
+    ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
+      as_ln_s='cp -p'
+  elif ln conf$$.file conf$$ 2>/dev/null; then
+    as_ln_s=ln
+  else
+    as_ln_s='cp -p'
   fi
-elif ln conf$$.file conf$$ 2>/dev/null; then
-  as_ln_s=ln
 else
   as_ln_s='cp -p'
 fi
-rm -f conf$$ conf$$.exe conf$$.file
+rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file
+rmdir conf$$.dir 2>/dev/null
 
 if mkdir -p . 2>/dev/null; then
-  as_mkdir_p=:
+  as_mkdir_p='mkdir -p "$as_dir"'
 else
   test -d ./-p && rmdir ./-p
   as_mkdir_p=false
 fi
 
-as_executable_p="test -f"
+if test -x / >/dev/null 2>&1; then
+  as_test_x='test -x'
+else
+  if ls -dL / >/dev/null 2>&1; then
+    as_ls_L_option=L
+  else
+    as_ls_L_option=
+  fi
+  as_test_x='
+    eval sh -c '\''
+      if test -d "$1"; then
+	test -d "$1/.";
+      else
+	case $1 in #(
+	-*)set "./$1";;
+	esac;
+	case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in #((
+	???[sx]*):;;*)false;;esac;fi
+    '\'' sh
+  '
+fi
+as_executable_p=$as_test_x
 
 # Sed expression to map a string onto a valid CPP name.
 as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
@@ -230,39 +541,28 @@ as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
 # Sed expression to map a string onto a valid variable name.
 as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
 
+SHELL=${CONFIG_SHELL-/bin/sh}
 
-# IFS
-# We need space, tab and new line, in precisely that order.
-as_nl='
-'
-IFS=" 	$as_nl"
-
-# CDPATH.
-$as_unset CDPATH
 
+test -n "$DJDIR" || exec 7<&0 </dev/null
+exec 6>&1
 
 # Name of the host.
-# hostname on some systems (SVR3.2, Linux) returns a bogus exit status,
+# hostname on some systems (SVR3.2, old GNU/Linux) returns a bogus exit status,
 # so uname gets run too.
 ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q`
 
-exec 6>&1
-
 #
 # Initializations.
 #
 ac_default_prefix=/usr/local
+ac_clean_files=
 ac_config_libobj_dir=.
+LIBOBJS=
 cross_compiling=no
 subdirs=
 MFLAGS=
 MAKEFLAGS=
-SHELL=${CONFIG_SHELL-/bin/sh}
-
-# Maximum number of lines to put in a shell here document.
-# This variable seems obsolete.  It should probably be removed, and
-# only ac_max_sed_lines should be used.
-: ${ac_max_here_lines=38}
 
 # Identity of this package.
 PACKAGE_NAME=
@@ -270,51 +570,357 @@ PACKAGE_TARNAME=
 PACKAGE_VERSION=
 PACKAGE_STRING=
 PACKAGE_BUGREPORT=
+PACKAGE_URL=
 
 ac_unique_file="Makefile.in"
 # Factoring default headers for most tests.
 ac_includes_default="\
 #include <stdio.h>
-#if HAVE_SYS_TYPES_H
+#ifdef HAVE_SYS_TYPES_H
 # include <sys/types.h>
 #endif
-#if HAVE_SYS_STAT_H
+#ifdef HAVE_SYS_STAT_H
 # include <sys/stat.h>
 #endif
-#if STDC_HEADERS
+#ifdef STDC_HEADERS
 # include <stdlib.h>
 # include <stddef.h>
 #else
-# if HAVE_STDLIB_H
+# ifdef HAVE_STDLIB_H
 #  include <stdlib.h>
 # endif
 #endif
-#if HAVE_STRING_H
-# if !STDC_HEADERS && HAVE_MEMORY_H
+#ifdef HAVE_STRING_H
+# if !defined STDC_HEADERS && defined HAVE_MEMORY_H
 #  include <memory.h>
 # endif
 # include <string.h>
 #endif
-#if HAVE_STRINGS_H
+#ifdef HAVE_STRINGS_H
 # include <strings.h>
 #endif
-#if HAVE_INTTYPES_H
+#ifdef HAVE_INTTYPES_H
 # include <inttypes.h>
-#else
-# if HAVE_STDINT_H
-#  include <stdint.h>
-# endif
 #endif
-#if HAVE_UNISTD_H
+#ifdef HAVE_STDINT_H
+# include <stdint.h>
+#endif
+#ifdef HAVE_UNISTD_H
 # include <unistd.h>
 #endif"
 
-ac_subst_vars='SHELL PATH_SEPARATOR PACKAGE_NAME PACKAGE_TARNAME PACKAGE_VERSION PACKAGE_STRING PACKAGE_BUGREPORT exec_prefix prefix program_transform_name bindir sbindir libexecdir datadir sysconfdir sharedstatedir localstatedir libdir includedir oldincludedir infodir mandir build_alias host_alias target_alias DEFS ECHO_C ECHO_N ECHO_T LIBS CC CFLAGS LDFLAGS CPPFLAGS ac_ct_CC EXEEXT OBJEXT CXX CXXFLAGS ac_ct_CXX RANLIB ac_ct_RANLIB LEX LEXLIB LEX_OUTPUT_ROOT YACC XTRALIBS CPP EGREP C_PIC STRINGS MS_VERSION PKG_CONFIG FT_BIN FT_ENABLED FT_INC FT_LIB ZLIB_ENABLED ZLIB_INC ZLIB_LIB PNG_ENABLED PNG_INC PNG_LIB GIF_ENABLED GIF_INC GIF_LIB JPEG_ENABLED JPEG_INC JPEG_LIB ICONV_ENABLED ICONV_INC ICONV_LIB GD_DEF GD_INC GD_LIB GD_STATIC MAKE_GD MAKE_GD_CLEAN FTGL_ENABLED FTGL_INC FTGL_LIB OGL_ENABLED OGL_INC OGL_LIB AGG_LIB AGG_INC AGG_OBJ PROJ_ENABLED PROJ_INC PROJ_LIBS THREAD_FLAG THREAD_LIB SDE_ENABLED SDE_INC SDE_LIB GEOS_CONFIG GEOS_ENABLED GEOS_INC GEOS_LIB GDAL_CONFIG GDAL_ENABLED OGR_ENABLED GDAL_INC GDAL_LIB PG_CONFIG POSTGIS_ENABLED POSTGIS_INC POSTGIS_LIB MY_CONFIG MYSQL_ENABLED MYSQL_INC MYSQL_LIB ORACLESPATIAL_ENABLED ORACLESPATIAL_INC ORACLESPATIAL_LIB WMS_SVR_ENABLED WFS_SVR_ENABLED WCS_SVR_ENABLED LIBCURL_CONFIG CURL_INC CURL_LIB LIBXML2_CONFIG XML2_INC XML2_LIB WMS_LYR_ENABLED WFS_LYR_ENABLED SOS_SVR_ENABLED XSLT_ENABLED XSLT_INC XSLT_LIB EXSLT_ENABLED EXSLT_INC EXSLT_LIB FRIBIDI_CONFIG FRIBIDI_ENABLED FRIBIDI_INC FRIBIDI_LIB CAIRO_ENABLED CAIRO_INC CAIRO_LIB FASTCGI_ENABLED FASTCGI_INC FASTCGI_LIB HTTPD MS_INC MS_LIB IGNORE_MISSING_DATA USE_POINT_Z_M USE_NINT DEBUG_FLAGS LD_SHARED SO_EXT SO_COMMAND_NAME PHP_LD_SHARED PHP_VERSION_FLAG PHP_SRC_DIR PHP_CC PHP_LD PHP_REGEX_INC PHP_REGEX_OBJ USE_PHP_REGEX MAKE_PHPMS MAKE_PHPMS_CLEAN APACHE_INC OS_INCLUDE_DIR ALL_ENABLED ALL_INC ALL_LIB ALL_STATIC_LIB RPATHS LIBOBJS LTLIBOBJS'
+ac_unique_file="mapserv.c"
+ac_subst_vars='LTLIBOBJS
+LIBOBJS
+RPATHS
+ALL_STATIC_LIB
+ALL_LIB
+ALL_INC
+ALL_ENABLED
+OS_INCLUDE_DIR
+PYTHON_MAPSCRIPT
+PYTHON
+SWIG_LIB
+SWIG
+JAVA_INCLUDE
+_ACJNI_JAVAC
+SO_COMMAND_NAME
+SO_EXT
+LD_SHARED
+C_PIC
+PHP_MAPSCRIPT
+USE_PHP_REGEX
+PHP_REGEX_OBJ
+PHP_REGEX_INC
+PHP_VERSION_FLAG
+PHPCONFIG
+DEBUG_FLAGS
+PROJ_FASTPATH_ENABLED
+USE_NINT
+USE_POINT_Z_M
+IGNORE_MISSING_DATA
+MS_LIB
+MS_INC
+APR_LIBS
+APR_INC
+APR_CFLAGS
+APRCONFIG
+HTTPD
+APACHE_LDFLAGS
+APACHE_LIBS
+APACHE_INC
+APACHECTL
+APACHE_BINDIR
+APACHE_SBINDIR
+APXS
+FASTCGI_LIB
+FASTCGI_INC
+FASTCGI_ENABLED
+LIBSVG_CAIRO_LIB
+LIBSVG_CAIRO_INC
+LIBSVG_CAIRO_ENABLED
+CAIRO_LIB
+CAIRO_INC
+CAIRO_ENABLED
+FRIBIDI_LIB
+FRIBIDI_INC
+FRIBIDI_ENABLED
+FRIBIDI_CONFIG
+EXSLT_LIB
+EXSLT_INC
+EXSLT_ENABLED
+XSLT_LIB
+XSLT_INC
+XSLT_ENABLED
+SOS_SVR_ENABLED
+WFS_LYR_ENABLED
+WMS_LYR_ENABLED
+XML2_LIB
+XML2_INC
+LIBXML2_CONFIG
+EXEMPI_LIB
+EXEMPI_INC
+EXEMPI_ENABLED
+CURL_LIB
+CURL_INC
+LIBCURL_CONFIG
+WCS_SVR_ENABLED
+WFS_SVR_ENABLED
+WMS_SVR_ENABLED
+ORACLESPATIAL_LIB
+ORACLESPATIAL_INC
+ORACLESPATIAL_ENABLED
+MYSQL_LIB
+MYSQL_INC
+MYSQL_ENABLED
+MY_CONFIG
+POSTGIS_LIB
+POSTGIS_INC
+POSTGIS_ENABLED
+PG_CONFIG
+GDAL_LIB
+GDAL_INC
+OGR_ENABLED
+GDAL_ENABLED
+GDAL_CONFIG
+GEOS_LIB
+GEOS_INC
+GEOS_ENABLED
+GEOS_CONFIG
+SDE_LIB
+SDE_INC
+SDE_ENABLED
+THREAD_LIB
+THREAD_FLAG
+PROJ_LIBS
+PROJ_INC
+PROJ_ENABLED
+OGL_LIB
+OGL_INC
+OGL_ENABLED
+FTGL_LIB
+FTGL_INC
+FTGL_ENABLED
+GDCONFIG
+GD_LIB
+GD_INC
+GD_ENABLED
+ICONV_LIB
+ICONV_INC
+ICONV_ENABLED
+JPEG_LIB
+JPEG_INC
+JPEG_ENABLED
+GIF_LIB
+GIF_INC
+GIF_ENABLED
+PNG_LIB
+PNG_INC
+PNG_ENABLED
+FT_LIB
+FT_INC
+FT_ENABLED
+FT_BIN
+PKG_CONFIG
+STRINGS
+XTRALIBS
+MS_VERSION
+INSTALL_DATA
+INSTALL_SCRIPT
+INSTALL_PROGRAM
+YFLAGS
+YACC
+LEXLIB
+LEX_OUTPUT_ROOT
+LEX
+CXXCPP
+ac_ct_CXX
+CXXFLAGS
+CXX
+CPP
+OTOOL64
+OTOOL
+LIPO
+NMEDIT
+DSYMUTIL
+MANIFEST_TOOL
+AWK
+RANLIB
+STRIP
+ac_ct_AR
+AR
+DLLTOOL
+OBJDUMP
+LN_S
+NM
+ac_ct_DUMPBIN
+DUMPBIN
+LD
+FGREP
+EGREP
+GREP
+SED
+OBJEXT
+EXEEXT
+ac_ct_CC
+CPPFLAGS
+LDFLAGS
+CFLAGS
+CC
+host_os
+host_vendor
+host_cpu
+host
+build_os
+build_vendor
+build_cpu
+build
+LIBTOOL
+target_alias
+host_alias
+build_alias
+LIBS
+ECHO_T
+ECHO_N
+ECHO_C
+DEFS
+mandir
+localedir
+libdir
+psdir
+pdfdir
+dvidir
+htmldir
+infodir
+docdir
+oldincludedir
+includedir
+localstatedir
+sharedstatedir
+sysconfdir
+datadir
+datarootdir
+libexecdir
+sbindir
+bindir
+program_transform_name
+prefix
+exec_prefix
+PACKAGE_URL
+PACKAGE_BUGREPORT
+PACKAGE_STRING
+PACKAGE_VERSION
+PACKAGE_TARNAME
+PACKAGE_NAME
+PATH_SEPARATOR
+SHELL'
 ac_subst_files=''
+ac_user_opts='
+enable_option_checking
+enable_static
+enable_shared
+with_pic
+enable_fast_install
+with_gnu_ld
+with_sysroot
+enable_libtool_lock
+with_pkg_config
+with_freetype
+with_png
+with_gif
+with_jpeg
+with_libiconv
+with_gd
+with_ftgl
+with_ogl
+with_expat
+with_proj
+with_threads
+with_sde
+with_sde_version
+with_geos
+with_ogr
+with_gdal
+with_postgis
+with_mysql
+with_oraclespatial
+with_wms
+with_wfs
+with_wcs
+with_wmsclient
+with_wfsclient
+with_sos
+with_curl_config
+with_kml
+with_exempi
+with_xml2_config
+with_xml_mapfile
+with_xslt
+with_exslt
+with_fribidi_config
+with_cairo
+with_libsvg_cairo
+with_fastcgi
+with_apache_module
+with_apxs
+with_apr_config
+enable_ignore_missing_data
+enable_point_z_m
+enable_fast_nint
+with_warnings
+enable_debug
+enable_proj_fastpath
+enable_cgi_cl_debug_args
+enable_gcov
+with_php
+enable_internal_ld_detect
+with_ld_shared
+with_java_include_os_name
+enable_python_mapscript
+with_python
+'
+      ac_precious_vars='build_alias
+host_alias
+target_alias
+CC
+CFLAGS
+LDFLAGS
+LIBS
+CPPFLAGS
+CPP
+CXX
+CXXFLAGS
+CCC
+CXXCPP
+YACC
+YFLAGS'
+
 
 # Initialize some variables set by options.
 ac_init_help=
 ac_init_version=false
+ac_unrecognized_opts=
+ac_unrecognized_sep=
 # The variables have the same names as the options, with
 # dashes changed to underlines.
 cache_file=/dev/null
@@ -337,34 +943,49 @@ x_libraries=NONE
 # and all the variables that are supposed to be based on exec_prefix
 # by default will actually change.
 # Use braces instead of parens because sh, perl, etc. also accept them.
+# (The list follows the same order as the GNU Coding Standards.)
 bindir='${exec_prefix}/bin'
 sbindir='${exec_prefix}/sbin'
 libexecdir='${exec_prefix}/libexec'
-datadir='${prefix}/share'
+datarootdir='${prefix}/share'
+datadir='${datarootdir}'
 sysconfdir='${prefix}/etc'
 sharedstatedir='${prefix}/com'
 localstatedir='${prefix}/var'
-libdir='${exec_prefix}/lib'
 includedir='${prefix}/include'
 oldincludedir='/usr/include'
-infodir='${prefix}/info'
-mandir='${prefix}/man'
+docdir='${datarootdir}/doc/${PACKAGE}'
+infodir='${datarootdir}/info'
+htmldir='${docdir}'
+dvidir='${docdir}'
+pdfdir='${docdir}'
+psdir='${docdir}'
+libdir='${exec_prefix}/lib'
+localedir='${datarootdir}/locale'
+mandir='${datarootdir}/man'
 
 ac_prev=
+ac_dashdash=
 for ac_option
 do
   # If the previous option needs an argument, assign it.
   if test -n "$ac_prev"; then
-    eval "$ac_prev=\$ac_option"
+    eval $ac_prev=\$ac_option
     ac_prev=
     continue
   fi
 
-  ac_optarg=`expr "x$ac_option" : 'x[^=]*=\(.*\)'`
+  case $ac_option in
+  *=?*) ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;;
+  *=)   ac_optarg= ;;
+  *)    ac_optarg=yes ;;
+  esac
 
   # Accept the important Cygnus configure options, so we can diagnose typos.
 
-  case $ac_option in
+  case $ac_dashdash$ac_option in
+  --)
+    ac_dashdash=yes ;;
 
   -bindir | --bindir | --bindi | --bind | --bin | --bi)
     ac_prev=bindir ;;
@@ -386,33 +1007,59 @@ do
   --config-cache | -C)
     cache_file=config.cache ;;
 
-  -datadir | --datadir | --datadi | --datad | --data | --dat | --da)
+  -datadir | --datadir | --datadi | --datad)
     ac_prev=datadir ;;
-  -datadir=* | --datadir=* | --datadi=* | --datad=* | --data=* | --dat=* \
-  | --da=*)
+  -datadir=* | --datadir=* | --datadi=* | --datad=*)
     datadir=$ac_optarg ;;
 
+  -datarootdir | --datarootdir | --datarootdi | --datarootd | --dataroot \
+  | --dataroo | --dataro | --datar)
+    ac_prev=datarootdir ;;
+  -datarootdir=* | --datarootdir=* | --datarootdi=* | --datarootd=* \
+  | --dataroot=* | --dataroo=* | --dataro=* | --datar=*)
+    datarootdir=$ac_optarg ;;
+
   -disable-* | --disable-*)
-    ac_feature=`expr "x$ac_option" : 'x-*disable-\(.*\)'`
+    ac_useropt=`expr "x$ac_option" : 'x-*disable-\(.*\)'`
     # Reject names that are not valid shell variable names.
-    expr "x$ac_feature" : ".*[^-_$as_cr_alnum]" >/dev/null &&
-      { echo "$as_me: error: invalid feature name: $ac_feature" >&2
-   { (exit 1); exit 1; }; }
-    ac_feature=`echo $ac_feature | sed 's/-/_/g'`
-    eval "enable_$ac_feature=no" ;;
+    expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
+      as_fn_error $? "invalid feature name: $ac_useropt"
+    ac_useropt_orig=$ac_useropt
+    ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
+    case $ac_user_opts in
+      *"
+"enable_$ac_useropt"
+"*) ;;
+      *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--disable-$ac_useropt_orig"
+	 ac_unrecognized_sep=', ';;
+    esac
+    eval enable_$ac_useropt=no ;;
+
+  -docdir | --docdir | --docdi | --doc | --do)
+    ac_prev=docdir ;;
+  -docdir=* | --docdir=* | --docdi=* | --doc=* | --do=*)
+    docdir=$ac_optarg ;;
+
+  -dvidir | --dvidir | --dvidi | --dvid | --dvi | --dv)
+    ac_prev=dvidir ;;
+  -dvidir=* | --dvidir=* | --dvidi=* | --dvid=* | --dvi=* | --dv=*)
+    dvidir=$ac_optarg ;;
 
   -enable-* | --enable-*)
-    ac_feature=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'`
+    ac_useropt=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'`
     # Reject names that are not valid shell variable names.
-    expr "x$ac_feature" : ".*[^-_$as_cr_alnum]" >/dev/null &&
-      { echo "$as_me: error: invalid feature name: $ac_feature" >&2
-   { (exit 1); exit 1; }; }
-    ac_feature=`echo $ac_feature | sed 's/-/_/g'`
-    case $ac_option in
-      *=*) ac_optarg=`echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"`;;
-      *) ac_optarg=yes ;;
+    expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
+      as_fn_error $? "invalid feature name: $ac_useropt"
+    ac_useropt_orig=$ac_useropt
+    ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
+    case $ac_user_opts in
+      *"
+"enable_$ac_useropt"
+"*) ;;
+      *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--enable-$ac_useropt_orig"
+	 ac_unrecognized_sep=', ';;
     esac
-    eval "enable_$ac_feature='$ac_optarg'" ;;
+    eval enable_$ac_useropt=\$ac_optarg ;;
 
   -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \
   | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \
@@ -439,6 +1086,12 @@ do
   -host=* | --host=* | --hos=* | --ho=*)
     host_alias=$ac_optarg ;;
 
+  -htmldir | --htmldir | --htmldi | --htmld | --html | --htm | --ht)
+    ac_prev=htmldir ;;
+  -htmldir=* | --htmldir=* | --htmldi=* | --htmld=* | --html=* | --htm=* \
+  | --ht=*)
+    htmldir=$ac_optarg ;;
+
   -includedir | --includedir | --includedi | --included | --include \
   | --includ | --inclu | --incl | --inc)
     ac_prev=includedir ;;
@@ -463,13 +1116,16 @@ do
   | --libexe=* | --libex=* | --libe=*)
     libexecdir=$ac_optarg ;;
 
+  -localedir | --localedir | --localedi | --localed | --locale)
+    ac_prev=localedir ;;
+  -localedir=* | --localedir=* | --localedi=* | --localed=* | --locale=*)
+    localedir=$ac_optarg ;;
+
   -localstatedir | --localstatedir | --localstatedi | --localstated \
-  | --localstate | --localstat | --localsta | --localst \
-  | --locals | --local | --loca | --loc | --lo)
+  | --localstate | --localstat | --localsta | --localst | --locals)
     ac_prev=localstatedir ;;
   -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \
-  | --localstate=* | --localstat=* | --localsta=* | --localst=* \
-  | --locals=* | --local=* | --loca=* | --loc=* | --lo=*)
+  | --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*)
     localstatedir=$ac_optarg ;;
 
   -mandir | --mandir | --mandi | --mand | --man | --ma | --m)
@@ -534,6 +1190,16 @@ do
   | --progr-tra=* | --program-tr=* | --program-t=*)
     program_transform_name=$ac_optarg ;;
 
+  -pdfdir | --pdfdir | --pdfdi | --pdfd | --pdf | --pd)
+    ac_prev=pdfdir ;;
+  -pdfdir=* | --pdfdir=* | --pdfdi=* | --pdfd=* | --pdf=* | --pd=*)
+    pdfdir=$ac_optarg ;;
+
+  -psdir | --psdir | --psdi | --psd | --ps)
+    ac_prev=psdir ;;
+  -psdir=* | --psdir=* | --psdi=* | --psd=* | --ps=*)
+    psdir=$ac_optarg ;;
+
   -q | -quiet | --quiet | --quie | --qui | --qu | --q \
   | -silent | --silent | --silen | --sile | --sil)
     silent=yes ;;
@@ -584,26 +1250,36 @@ do
     ac_init_version=: ;;
 
   -with-* | --with-*)
-    ac_package=`expr "x$ac_option" : 'x-*with-\([^=]*\)'`
+    ac_useropt=`expr "x$ac_option" : 'x-*with-\([^=]*\)'`
     # Reject names that are not valid shell variable names.
-    expr "x$ac_package" : ".*[^-_$as_cr_alnum]" >/dev/null &&
-      { echo "$as_me: error: invalid package name: $ac_package" >&2
-   { (exit 1); exit 1; }; }
-    ac_package=`echo $ac_package| sed 's/-/_/g'`
-    case $ac_option in
-      *=*) ac_optarg=`echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"`;;
-      *) ac_optarg=yes ;;
+    expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
+      as_fn_error $? "invalid package name: $ac_useropt"
+    ac_useropt_orig=$ac_useropt
+    ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
+    case $ac_user_opts in
+      *"
+"with_$ac_useropt"
+"*) ;;
+      *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--with-$ac_useropt_orig"
+	 ac_unrecognized_sep=', ';;
     esac
-    eval "with_$ac_package='$ac_optarg'" ;;
+    eval with_$ac_useropt=\$ac_optarg ;;
 
   -without-* | --without-*)
-    ac_package=`expr "x$ac_option" : 'x-*without-\(.*\)'`
+    ac_useropt=`expr "x$ac_option" : 'x-*without-\(.*\)'`
     # Reject names that are not valid shell variable names.
-    expr "x$ac_package" : ".*[^-_$as_cr_alnum]" >/dev/null &&
-      { echo "$as_me: error: invalid package name: $ac_package" >&2
-   { (exit 1); exit 1; }; }
-    ac_package=`echo $ac_package | sed 's/-/_/g'`
-    eval "with_$ac_package=no" ;;
+    expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
+      as_fn_error $? "invalid package name: $ac_useropt"
+    ac_useropt_orig=$ac_useropt
+    ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
+    case $ac_user_opts in
+      *"
+"with_$ac_useropt"
+"*) ;;
+      *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--without-$ac_useropt_orig"
+	 ac_unrecognized_sep=', ';;
+    esac
+    eval with_$ac_useropt=no ;;
 
   --x)
     # Obsolete; use --with-x.
@@ -623,27 +1299,26 @@ do
   | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*)
     x_libraries=$ac_optarg ;;
 
-  -*) { echo "$as_me: error: unrecognized option: $ac_option
-Try \`$0 --help' for more information." >&2
-   { (exit 1); exit 1; }; }
+  -*) as_fn_error $? "unrecognized option: \`$ac_option'
+Try \`$0 --help' for more information"
     ;;
 
   *=*)
     ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='`
     # Reject names that are not valid shell variable names.
-    expr "x$ac_envvar" : ".*[^_$as_cr_alnum]" >/dev/null &&
-      { echo "$as_me: error: invalid variable name: $ac_envvar" >&2
-   { (exit 1); exit 1; }; }
-    ac_optarg=`echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"`
-    eval "$ac_envvar='$ac_optarg'"
+    case $ac_envvar in #(
+      '' | [0-9]* | *[!_$as_cr_alnum]* )
+      as_fn_error $? "invalid variable name: \`$ac_envvar'" ;;
+    esac
+    eval $ac_envvar=\$ac_optarg
     export $ac_envvar ;;
 
   *)
     # FIXME: should be removed in autoconf 3.0.
-    echo "$as_me: WARNING: you should use --build, --host, --target" >&2
+    $as_echo "$as_me: WARNING: you should use --build, --host, --target" >&2
     expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null &&
-      echo "$as_me: WARNING: invalid host type: $ac_option" >&2
-    : ${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option}
+      $as_echo "$as_me: WARNING: invalid host type: $ac_option" >&2
+    : "${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option}"
     ;;
 
   esac
@@ -651,31 +1326,36 @@ done
 
 if test -n "$ac_prev"; then
   ac_option=--`echo $ac_prev | sed 's/_/-/g'`
-  { echo "$as_me: error: missing argument to $ac_option" >&2
-   { (exit 1); exit 1; }; }
+  as_fn_error $? "missing argument to $ac_option"
 fi
 
-# Be sure to have absolute paths.
-for ac_var in exec_prefix prefix
-do
-  eval ac_val=$`echo $ac_var`
-  case $ac_val in
-    [\\/$]* | ?:[\\/]* | NONE | '' ) ;;
-    *)  { echo "$as_me: error: expected an absolute directory name for --$ac_var: $ac_val" >&2
-   { (exit 1); exit 1; }; };;
+if test -n "$ac_unrecognized_opts"; then
+  case $enable_option_checking in
+    no) ;;
+    fatal) as_fn_error $? "unrecognized options: $ac_unrecognized_opts" ;;
+    *)     $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2 ;;
   esac
-done
+fi
 
-# Be sure to have absolute paths.
-for ac_var in bindir sbindir libexecdir datadir sysconfdir sharedstatedir \
-	      localstatedir libdir includedir oldincludedir infodir mandir
+# Check all directory arguments for consistency.
+for ac_var in	exec_prefix prefix bindir sbindir libexecdir datarootdir \
+		datadir sysconfdir sharedstatedir localstatedir includedir \
+		oldincludedir docdir infodir htmldir dvidir pdfdir psdir \
+		libdir localedir mandir
 do
-  eval ac_val=$`echo $ac_var`
+  eval ac_val=\$$ac_var
+  # Remove trailing slashes.
+  case $ac_val in
+    */ )
+      ac_val=`expr "X$ac_val" : 'X\(.*[^/]\)' \| "X$ac_val" : 'X\(.*\)'`
+      eval $ac_var=\$ac_val;;
+  esac
+  # Be sure to have absolute directory names.
   case $ac_val in
-    [\\/$]* | ?:[\\/]* ) ;;
-    *)  { echo "$as_me: error: expected an absolute directory name for --$ac_var: $ac_val" >&2
-   { (exit 1); exit 1; }; };;
+    [\\/$]* | ?:[\\/]* )  continue;;
+    NONE | '' ) case $ac_var in *prefix ) continue;; esac;;
   esac
+  as_fn_error $? "expected an absolute directory name for --$ac_var: $ac_val"
 done
 
 # There might be people who depend on the old broken behavior: `$host'
@@ -689,8 +1369,8 @@ target=$target_alias
 if test "x$host_alias" != x; then
   if test "x$build_alias" = x; then
     cross_compiling=maybe
-    echo "$as_me: WARNING: If you wanted to set the --build type, don't use --host.
-    If a cross compiler is detected then cross compile mode will be used." >&2
+    $as_echo "$as_me: WARNING: if you wanted to set the --build type, don't use --host.
+    If a cross compiler is detected then cross compile mode will be used" >&2
   elif test "x$build_alias" != "x$host_alias"; then
     cross_compiling=yes
   fi
@@ -702,82 +1382,72 @@ test -n "$host_alias" && ac_tool_prefix=$host_alias-
 test "$silent" = yes && exec 6>/dev/null
 
 
+ac_pwd=`pwd` && test -n "$ac_pwd" &&
+ac_ls_di=`ls -di .` &&
+ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` ||
+  as_fn_error $? "working directory cannot be determined"
+test "X$ac_ls_di" = "X$ac_pwd_ls_di" ||
+  as_fn_error $? "pwd does not report name of working directory"
+
+
 # Find the source files, if location was not specified.
 if test -z "$srcdir"; then
   ac_srcdir_defaulted=yes
-  # Try the directory containing this script, then its parent.
-  ac_confdir=`(dirname "$0") 2>/dev/null ||
-$as_expr X"$0" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
-	 X"$0" : 'X\(//\)[^/]' \| \
-	 X"$0" : 'X\(//\)$' \| \
-	 X"$0" : 'X\(/\)' \| \
-	 .     : '\(.\)' 2>/dev/null ||
-echo X"$0" |
-    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; }
-  	  /^X\(\/\/\)[^/].*/{ s//\1/; q; }
-  	  /^X\(\/\/\)$/{ s//\1/; q; }
-  	  /^X\(\/\).*/{ s//\1/; q; }
-  	  s/.*/./; q'`
+  # Try the directory containing this script, then the parent directory.
+  ac_confdir=`$as_dirname -- "$as_myself" ||
+$as_expr X"$as_myself" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	 X"$as_myself" : 'X\(//\)[^/]' \| \
+	 X"$as_myself" : 'X\(//\)$' \| \
+	 X"$as_myself" : 'X\(/\)' \| . 2>/dev/null ||
+$as_echo X"$as_myself" |
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)[^/].*/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
   srcdir=$ac_confdir
-  if test ! -r $srcdir/$ac_unique_file; then
+  if test ! -r "$srcdir/$ac_unique_file"; then
     srcdir=..
   fi
 else
   ac_srcdir_defaulted=no
 fi
-if test ! -r $srcdir/$ac_unique_file; then
-  if test "$ac_srcdir_defaulted" = yes; then
-    { echo "$as_me: error: cannot find sources ($ac_unique_file) in $ac_confdir or .." >&2
-   { (exit 1); exit 1; }; }
-  else
-    { echo "$as_me: error: cannot find sources ($ac_unique_file) in $srcdir" >&2
-   { (exit 1); exit 1; }; }
-  fi
-fi
-(cd $srcdir && test -r ./$ac_unique_file) 2>/dev/null ||
-  { echo "$as_me: error: sources are in $srcdir, but \`cd $srcdir' does not work" >&2
-   { (exit 1); exit 1; }; }
-srcdir=`echo "$srcdir" | sed 's%\([^\\/]\)[\\/]*$%\1%'`
-ac_env_build_alias_set=${build_alias+set}
-ac_env_build_alias_value=$build_alias
-ac_cv_env_build_alias_set=${build_alias+set}
-ac_cv_env_build_alias_value=$build_alias
-ac_env_host_alias_set=${host_alias+set}
-ac_env_host_alias_value=$host_alias
-ac_cv_env_host_alias_set=${host_alias+set}
-ac_cv_env_host_alias_value=$host_alias
-ac_env_target_alias_set=${target_alias+set}
-ac_env_target_alias_value=$target_alias
-ac_cv_env_target_alias_set=${target_alias+set}
-ac_cv_env_target_alias_value=$target_alias
-ac_env_CC_set=${CC+set}
-ac_env_CC_value=$CC
-ac_cv_env_CC_set=${CC+set}
-ac_cv_env_CC_value=$CC
-ac_env_CFLAGS_set=${CFLAGS+set}
-ac_env_CFLAGS_value=$CFLAGS
-ac_cv_env_CFLAGS_set=${CFLAGS+set}
-ac_cv_env_CFLAGS_value=$CFLAGS
-ac_env_LDFLAGS_set=${LDFLAGS+set}
-ac_env_LDFLAGS_value=$LDFLAGS
-ac_cv_env_LDFLAGS_set=${LDFLAGS+set}
-ac_cv_env_LDFLAGS_value=$LDFLAGS
-ac_env_CPPFLAGS_set=${CPPFLAGS+set}
-ac_env_CPPFLAGS_value=$CPPFLAGS
-ac_cv_env_CPPFLAGS_set=${CPPFLAGS+set}
-ac_cv_env_CPPFLAGS_value=$CPPFLAGS
-ac_env_CXX_set=${CXX+set}
-ac_env_CXX_value=$CXX
-ac_cv_env_CXX_set=${CXX+set}
-ac_cv_env_CXX_value=$CXX
-ac_env_CXXFLAGS_set=${CXXFLAGS+set}
-ac_env_CXXFLAGS_value=$CXXFLAGS
-ac_cv_env_CXXFLAGS_set=${CXXFLAGS+set}
-ac_cv_env_CXXFLAGS_value=$CXXFLAGS
-ac_env_CPP_set=${CPP+set}
-ac_env_CPP_value=$CPP
-ac_cv_env_CPP_set=${CPP+set}
-ac_cv_env_CPP_value=$CPP
+if test ! -r "$srcdir/$ac_unique_file"; then
+  test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .."
+  as_fn_error $? "cannot find sources ($ac_unique_file) in $srcdir"
+fi
+ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work"
+ac_abs_confdir=`(
+	cd "$srcdir" && test -r "./$ac_unique_file" || as_fn_error $? "$ac_msg"
+	pwd)`
+# When building in place, set srcdir=.
+if test "$ac_abs_confdir" = "$ac_pwd"; then
+  srcdir=.
+fi
+# Remove unnecessary trailing slashes from srcdir.
+# Double slashes in file names in object file debugging info
+# mess up M-x gdb in Emacs.
+case $srcdir in
+*/) srcdir=`expr "X$srcdir" : 'X\(.*[^/]\)' \| "X$srcdir" : 'X\(.*\)'`;;
+esac
+for ac_var in $ac_precious_vars; do
+  eval ac_env_${ac_var}_set=\${${ac_var}+set}
+  eval ac_env_${ac_var}_value=\$${ac_var}
+  eval ac_cv_env_${ac_var}_set=\${${ac_var}+set}
+  eval ac_cv_env_${ac_var}_value=\$${ac_var}
+done
 
 #
 # Report the --help message.
@@ -800,20 +1470,17 @@ Configuration:
       --help=short        display options specific to this package
       --help=recursive    display the short help of all the included packages
   -V, --version           display version information and exit
-  -q, --quiet, --silent   do not print \`checking...' messages
+  -q, --quiet, --silent   do not print \`checking ...' messages
       --cache-file=FILE   cache test results in FILE [disabled]
   -C, --config-cache      alias for \`--cache-file=config.cache'
   -n, --no-create         do not create output files
       --srcdir=DIR        find the sources in DIR [configure dir or \`..']
 
-_ACEOF
-
-  cat <<_ACEOF
 Installation directories:
   --prefix=PREFIX         install architecture-independent files in PREFIX
-			  [$ac_default_prefix]
+                          [$ac_default_prefix]
   --exec-prefix=EPREFIX   install architecture-dependent files in EPREFIX
-			  [PREFIX]
+                          [PREFIX]
 
 By default, \`make install' will install all the files in
 \`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc.  You can specify
@@ -823,21 +1490,32 @@ for instance \`--prefix=\$HOME'.
 For better control, use the options below.
 
 Fine tuning of the installation directories:
-  --bindir=DIR           user executables [EPREFIX/bin]
-  --sbindir=DIR          system admin executables [EPREFIX/sbin]
-  --libexecdir=DIR       program executables [EPREFIX/libexec]
-  --datadir=DIR          read-only architecture-independent data [PREFIX/share]
-  --sysconfdir=DIR       read-only single-machine data [PREFIX/etc]
-  --sharedstatedir=DIR   modifiable architecture-independent data [PREFIX/com]
-  --localstatedir=DIR    modifiable single-machine data [PREFIX/var]
-  --libdir=DIR           object code libraries [EPREFIX/lib]
-  --includedir=DIR       C header files [PREFIX/include]
-  --oldincludedir=DIR    C header files for non-gcc [/usr/include]
-  --infodir=DIR          info documentation [PREFIX/info]
-  --mandir=DIR           man documentation [PREFIX/man]
+  --bindir=DIR            user executables [EPREFIX/bin]
+  --sbindir=DIR           system admin executables [EPREFIX/sbin]
+  --libexecdir=DIR        program executables [EPREFIX/libexec]
+  --sysconfdir=DIR        read-only single-machine data [PREFIX/etc]
+  --sharedstatedir=DIR    modifiable architecture-independent data [PREFIX/com]
+  --localstatedir=DIR     modifiable single-machine data [PREFIX/var]
+  --libdir=DIR            object code libraries [EPREFIX/lib]
+  --includedir=DIR        C header files [PREFIX/include]
+  --oldincludedir=DIR     C header files for non-gcc [/usr/include]
+  --datarootdir=DIR       read-only arch.-independent data root [PREFIX/share]
+  --datadir=DIR           read-only architecture-independent data [DATAROOTDIR]
+  --infodir=DIR           info documentation [DATAROOTDIR/info]
+  --localedir=DIR         locale-dependent data [DATAROOTDIR/locale]
+  --mandir=DIR            man documentation [DATAROOTDIR/man]
+  --docdir=DIR            documentation root [DATAROOTDIR/doc/PACKAGE]
+  --htmldir=DIR           html documentation [DOCDIR]
+  --dvidir=DIR            dvi documentation [DOCDIR]
+  --pdfdir=DIR            pdf documentation [DOCDIR]
+  --psdir=DIR             ps documentation [DOCDIR]
 _ACEOF
 
   cat <<\_ACEOF
+
+System types:
+  --build=BUILD     configure for building on BUILD [guessed]
+  --host=HOST       cross-compile to build programs to run on HOST [BUILD]
 _ACEOF
 fi
 
@@ -846,8 +1524,14 @@ if test -n "$ac_init_help"; then
   cat <<\_ACEOF
 
 Optional Features:
+  --disable-option-checking  ignore unrecognized --enable/--with options
   --disable-FEATURE       do not include FEATURE (same as --enable-FEATURE=no)
   --enable-FEATURE[=ARG]  include FEATURE [ARG=yes]
+  --enable-static[=PKGS]  build static libraries [default=no]
+  --enable-shared[=PKGS]  build shared libraries [default=yes]
+  --enable-fast-install[=PKGS]
+                          optimize for fast installation [default=yes]
+  --disable-libtool-lock  avoid locking (might break parallel builds)
   --enable-ignore-missing-data
                           Ignore missing data file errors at runtime
   --disable-ignore-missing-data
@@ -857,6 +1541,8 @@ Optional Features:
   --disable-fast-nint     Use safe MS_NINT with reliable rounding
   --enable-debug          Include "-g" in CFLAGS for debugging.
   --disable-debug         Do not include "-g" in CFLAGS (the default).
+  --enable-proj-fastpath  bypass proj.4 for epsg:4326 to epsg:3857
+                          reprojections
   --enable-cgi-cl-debug-args
                           Enable mapserv CGI command-line debug arguments
                           (disabled by default). These command-line args may
@@ -869,36 +1555,29 @@ Optional Features:
                           Use perl -V output to figure the command to use to
                           link php_mapscript.so.  Try this only if the default
                           internal macro didn't work.
-  --enable-runpath        Include runtime library path flags (-Wl,-R) in link.
-                          Required on *BSD systems.
-  --disable-runpath       Do not link with runtime lib path (the default).
+  --enable-python-mapscript     build the python mapscript module.
 
 Optional Packages:
   --with-PACKAGE[=ARG]    use PACKAGE [ARG=yes]
   --without-PACKAGE       do not use PACKAGE (same as --with-PACKAGE=no)
+  --with-pic[=PKGS]       try to use only PIC/non-PIC objects [default=use
+                          both]
+  --with-gnu-ld           assume the C compiler uses GNU ld [default=no]
+  --with-sysroot=DIR Search for dependent libraries within DIR
+                        (or the compiler's sysroot if not specified).
   --with-pkg-config[=PATH]
                           Include pkg-config support (PATH is path to pkg-config)
   --with-freetype=DIR     GD: Specify where FreeType 2.x is installed (DIR is
                               path to freetype-config program or install dir).
-  --with-zlib=DIR         GD,SVG: Specify where zlib is installed (DIR is path
-                              to zlib install dir).
-  --with-png=DIR          GD: Specify where PNG is installed (DIR is path to
-                              PNG install dir).
-  --with-gif=DIR          Specify where GIF is installed (DIR is path to
-                              GIF install dir).
-  --with-jpeg[=DIR]       Include JPEG support (DIR is LibJPEG's install dir).
-  --with-xpm=DIR          GD: Specify where libXpm is installed (DIR it the
-                              libXpm install prefix).
+  --with-png              libpng location: [yes|/path/to/png/prefix]
+  --with-gif              libgif location: [yes|no|/path/to/gif/prefix]
+  --with-jpeg             libjpeg location: [yes|/path/to/jpeg/prefix]
   --with-libiconv=DIR     Specify where libiconv is installed (DIR is path
                           to libiconv install dir (prefix)).
-  --with-gd[=[static,]DIR]
-                          Specify which version of GD to use (DIR is GD's
-                          install dir).
+  --with-gd               libgd location: [yes|no|/path/to/gdlib-config]
   --with-ftgl[=DIR]       Include OpenGl support (DIR is OpenGL's install dir).
   --with-opengl[=DIR]     Include OpenGl support (DIR is OpenGL's install dir).
   --with-expat=DIR          Specify expat location, needed for SVG symbol parsing
-  --with-agg-svg-symbols[=yes/no]
-                          Include AGG SVG symbol support (Requires expat).
   --with-proj[=DIR]       Include PROJ.4 support (DIR is PROJ.4's install dir).
   --with-threads[=linkopt]Include thread safe support
   --with-sde[=DIR]        Include ESRI SDE support (DIR is SDE's install dir).
@@ -923,6 +1602,7 @@ Optional Packages:
                           OGR required).
   --with-curl-config=PATH Specify path to curl-config.
   --with-kml=                KML output Support (ARG=yes/no).
+  --with-exempi=DIR Specify path to exempi.
   --with-xml2-config=PATH Specify path to xml2-config.
   --with-xml-mapfile=                Include xml-mapfile Support (ARG=yes/no).
   --with-xslt=DIR         Include xslt Support (ARG=yes/path to
@@ -933,25 +1613,18 @@ Optional Packages:
                           Include FriBidi Support (ARG=yes/path to
                           fribidi-config or fribidi.pc)
   --with-cairo[=ARG]      Include Cairo Support (ARG=yes/path to cairo.pc)
+  --with-libsvg-cairo[=ARG]      Include Cairo SVG Parser Support (ARG=yes/path to cairo.pc)
   --with-fastcgi=path     Enable FastCGI, point to installed tree.
-  --with-httpd            Specify path to 'httpd' executable.
+  --with-apache-module    enable building mod_mapserver module
+  --with-apxs=/path/to/apxs     Apache 2 apxs tool location
+  --with-apr-config       path to apr-config program
   --with-warnings[=flags] Enable strict warnings (or user defined warnings)
-  --with-php=DIR          Specify directory where PHP5's include files are
-                          installed (or a pointer to the full source tree)
+  --with-php=yes|no|/path/to/php-config
+                          Specify location of php-config script.
                           Required in order to compile the PHP/MapScript
                           module.
   --with-ld-shared=CMD    Specify link command to use to build shared libs
   --without-ld-shared     Disable shared library support
-  --with-apxs[=FILE]      (CURRENTLY DISABLED)
-                          Use this option only if building the PHP MapScript
-                          on a system where PHP was built as a shared Apache
-                          module.  FILE is the optional pathname to the
-                          Apache apxs tool; defaults to apxs.
-  --with-apache=DIR       (CURRENTLY DISABLED)
-                          Use this option only if building the PHP MapScript
-                          on a system where PHP was built as an Apache
-                          module statically linked into the httpd executable.
-                          DIR is the path to the apache include files.
   --with-java-include-os-name=dirname
                           (AUTODETECTED)
                           Use this option only if building of Java Mapscript
@@ -960,170 +1633,623 @@ Optional Packages:
                           installation where os-dependent include files are
                           found (for instance linux or solaris).
                           Only used by Java mapscript.
+  --with-python[=PATH] Specify python binary (PATH is path to python)
 
 Some influential environment variables:
   CC          C compiler command
   CFLAGS      C compiler flags
   LDFLAGS     linker flags, e.g. -L<lib dir> if you have libraries in a
               nonstandard directory <lib dir>
-  CPPFLAGS    C/C++ preprocessor flags, e.g. -I<include dir> if you have
-              headers in a nonstandard directory <include dir>
+  LIBS        libraries to pass to the linker, e.g. -l<library>
+  CPPFLAGS    (Objective) C/C++ preprocessor flags, e.g. -I<include dir> if
+              you have headers in a nonstandard directory <include dir>
+  CPP         C preprocessor
   CXX         C++ compiler command
   CXXFLAGS    C++ compiler flags
-  CPP         C preprocessor
+  CXXCPP      C++ preprocessor
+  YACC        The `Yet Another Compiler Compiler' implementation to use.
+              Defaults to the first program found out of: `bison -y', `byacc',
+              `yacc'.
+  YFLAGS      The list of arguments that will be passed by default to $YACC.
+              This script will default YFLAGS to the empty string to avoid a
+              default value of `-d' given by some make applications.
 
 Use these variables to override the choices made by `configure' or to help
 it to find libraries and programs with nonstandard names/locations.
 
+Report bugs to the package provider.
 _ACEOF
+ac_status=$?
 fi
 
 if test "$ac_init_help" = "recursive"; then
   # If there are subdirs, report their specific --help.
-  ac_popdir=`pwd`
   for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue
-    test -d $ac_dir || continue
+    test -d "$ac_dir" ||
+      { cd "$srcdir" && ac_pwd=`pwd` && srcdir=. && test -d "$ac_dir"; } ||
+      continue
     ac_builddir=.
 
-if test "$ac_dir" != .; then
-  ac_dir_suffix=/`echo "$ac_dir" | sed 's,^\.[\\/],,'`
-  # A "../" for each directory in $ac_dir_suffix.
-  ac_top_builddir=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,../,g'`
-else
-  ac_dir_suffix= ac_top_builddir=
-fi
+case "$ac_dir" in
+.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
+*)
+  ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'`
+  # A ".." for each directory in $ac_dir_suffix.
+  ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'`
+  case $ac_top_builddir_sub in
+  "") ac_top_builddir_sub=. ac_top_build_prefix= ;;
+  *)  ac_top_build_prefix=$ac_top_builddir_sub/ ;;
+  esac ;;
+esac
+ac_abs_top_builddir=$ac_pwd
+ac_abs_builddir=$ac_pwd$ac_dir_suffix
+# for backward compatibility:
+ac_top_builddir=$ac_top_build_prefix
 
 case $srcdir in
-  .)  # No --srcdir option.  We are building in place.
+  .)  # We are building in place.
     ac_srcdir=.
-    if test -z "$ac_top_builddir"; then
-       ac_top_srcdir=.
-    else
-       ac_top_srcdir=`echo $ac_top_builddir | sed 's,/$,,'`
-    fi ;;
-  [\\/]* | ?:[\\/]* )  # Absolute path.
+    ac_top_srcdir=$ac_top_builddir_sub
+    ac_abs_top_srcdir=$ac_pwd ;;
+  [\\/]* | ?:[\\/]* )  # Absolute name.
     ac_srcdir=$srcdir$ac_dir_suffix;
-    ac_top_srcdir=$srcdir ;;
-  *) # Relative path.
-    ac_srcdir=$ac_top_builddir$srcdir$ac_dir_suffix
-    ac_top_srcdir=$ac_top_builddir$srcdir ;;
-esac
-
-# Do not use `cd foo && pwd` to compute absolute paths, because
-# the directories may not exist.
-case `pwd` in
-.) ac_abs_builddir="$ac_dir";;
-*)
-  case "$ac_dir" in
-  .) ac_abs_builddir=`pwd`;;
-  [\\/]* | ?:[\\/]* ) ac_abs_builddir="$ac_dir";;
-  *) ac_abs_builddir=`pwd`/"$ac_dir";;
-  esac;;
+    ac_top_srcdir=$srcdir
+    ac_abs_top_srcdir=$srcdir ;;
+  *) # Relative name.
+    ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix
+    ac_top_srcdir=$ac_top_build_prefix$srcdir
+    ac_abs_top_srcdir=$ac_pwd/$srcdir ;;
 esac
-case $ac_abs_builddir in
-.) ac_abs_top_builddir=${ac_top_builddir}.;;
-*)
-  case ${ac_top_builddir}. in
-  .) ac_abs_top_builddir=$ac_abs_builddir;;
-  [\\/]* | ?:[\\/]* ) ac_abs_top_builddir=${ac_top_builddir}.;;
-  *) ac_abs_top_builddir=$ac_abs_builddir/${ac_top_builddir}.;;
-  esac;;
-esac
-case $ac_abs_builddir in
-.) ac_abs_srcdir=$ac_srcdir;;
-*)
-  case $ac_srcdir in
-  .) ac_abs_srcdir=$ac_abs_builddir;;
-  [\\/]* | ?:[\\/]* ) ac_abs_srcdir=$ac_srcdir;;
-  *) ac_abs_srcdir=$ac_abs_builddir/$ac_srcdir;;
-  esac;;
-esac
-case $ac_abs_builddir in
-.) ac_abs_top_srcdir=$ac_top_srcdir;;
-*)
-  case $ac_top_srcdir in
-  .) ac_abs_top_srcdir=$ac_abs_builddir;;
-  [\\/]* | ?:[\\/]* ) ac_abs_top_srcdir=$ac_top_srcdir;;
-  *) ac_abs_top_srcdir=$ac_abs_builddir/$ac_top_srcdir;;
-  esac;;
-esac
-
-    cd $ac_dir
-    # Check for guested configure; otherwise get Cygnus style configure.
-    if test -f $ac_srcdir/configure.gnu; then
-      echo
-      $SHELL $ac_srcdir/configure.gnu  --help=recursive
-    elif test -f $ac_srcdir/configure; then
-      echo
-      $SHELL $ac_srcdir/configure  --help=recursive
-    elif test -f $ac_srcdir/configure.ac ||
-	   test -f $ac_srcdir/configure.in; then
-      echo
-      $ac_configure --help
+ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
+
+    cd "$ac_dir" || { ac_status=$?; continue; }
+    # Check for guested configure.
+    if test -f "$ac_srcdir/configure.gnu"; then
+      echo &&
+      $SHELL "$ac_srcdir/configure.gnu" --help=recursive
+    elif test -f "$ac_srcdir/configure"; then
+      echo &&
+      $SHELL "$ac_srcdir/configure" --help=recursive
     else
-      echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2
-    fi
-    cd $ac_popdir
+      $as_echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2
+    fi || ac_status=$?
+    cd "$ac_pwd" || { ac_status=$?; break; }
   done
 fi
 
-test -n "$ac_init_help" && exit 0
+test -n "$ac_init_help" && exit $ac_status
 if $ac_init_version; then
   cat <<\_ACEOF
+configure
+generated by GNU Autoconf 2.68
 
-Copyright (C) 2003 Free Software Foundation, Inc.
+Copyright (C) 2010 Free Software Foundation, Inc.
 This configure script is free software; the Free Software Foundation
 gives unlimited permission to copy, distribute and modify it.
 _ACEOF
-  exit 0
+  exit
 fi
-exec 5>config.log
-cat >&5 <<_ACEOF
-This file contains any messages produced by compilers while
-running configure, to aid debugging if configure makes a mistake.
-
-It was created by $as_me, which was
-generated by GNU Autoconf 2.59.  Invocation command line was
 
-  $ $0 $@
+## ------------------------ ##
+## Autoconf initialization. ##
+## ------------------------ ##
 
-_ACEOF
+# ac_fn_c_try_compile LINENO
+# --------------------------
+# Try to compile conftest.$ac_ext, and return whether this succeeded.
+ac_fn_c_try_compile ()
 {
-cat <<_ASUNAME
-## --------- ##
-## Platform. ##
-## --------- ##
-
-hostname = `(hostname || uname -n) 2>/dev/null | sed 1q`
-uname -m = `(uname -m) 2>/dev/null || echo unknown`
-uname -r = `(uname -r) 2>/dev/null || echo unknown`
-uname -s = `(uname -s) 2>/dev/null || echo unknown`
-uname -v = `(uname -v) 2>/dev/null || echo unknown`
-
-/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown`
-/bin/uname -X     = `(/bin/uname -X) 2>/dev/null     || echo unknown`
+  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+  rm -f conftest.$ac_objext
+  if { { ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_compile") 2>conftest.err
+  ac_status=$?
+  if test -s conftest.err; then
+    grep -v '^ *+' conftest.err >conftest.er1
+    cat conftest.er1 >&5
+    mv -f conftest.er1 conftest.err
+  fi
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; } && {
+	 test -z "$ac_c_werror_flag" ||
+	 test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then :
+  ac_retval=0
+else
+  $as_echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
 
-/bin/arch              = `(/bin/arch) 2>/dev/null              || echo unknown`
-/usr/bin/arch -k       = `(/usr/bin/arch -k) 2>/dev/null       || echo unknown`
-/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown`
-hostinfo               = `(hostinfo) 2>/dev/null               || echo unknown`
-/bin/machine           = `(/bin/machine) 2>/dev/null           || echo unknown`
-/usr/bin/oslevel       = `(/usr/bin/oslevel) 2>/dev/null       || echo unknown`
-/bin/universe          = `(/bin/universe) 2>/dev/null          || echo unknown`
+	ac_retval=1
+fi
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
+  as_fn_set_status $ac_retval
 
-_ASUNAME
+} # ac_fn_c_try_compile
 
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  echo "PATH: $as_dir"
-done
+# ac_fn_c_try_link LINENO
+# -----------------------
+# Try to link conftest.$ac_ext, and return whether this succeeded.
+ac_fn_c_try_link ()
+{
+  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+  rm -f conftest.$ac_objext conftest$ac_exeext
+  if { { ac_try="$ac_link"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_link") 2>conftest.err
+  ac_status=$?
+  if test -s conftest.err; then
+    grep -v '^ *+' conftest.err >conftest.er1
+    cat conftest.er1 >&5
+    mv -f conftest.er1 conftest.err
+  fi
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; } && {
+	 test -z "$ac_c_werror_flag" ||
+	 test ! -s conftest.err
+       } && test -s conftest$ac_exeext && {
+	 test "$cross_compiling" = yes ||
+	 $as_test_x conftest$ac_exeext
+       }; then :
+  ac_retval=0
+else
+  $as_echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
 
-} >&5
+	ac_retval=1
+fi
+  # Delete the IPA/IPO (Inter Procedural Analysis/Optimization) information
+  # created by the PGI compiler (conftest_ipa8_conftest.oo), as it would
+  # interfere with the next link command; also delete a directory that is
+  # left behind by Apple's compiler.  We do this before executing the actions.
+  rm -rf conftest.dSYM conftest_ipa8_conftest.oo
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
+  as_fn_set_status $ac_retval
 
-cat >&5 <<_ACEOF
+} # ac_fn_c_try_link
+
+# ac_fn_c_check_header_compile LINENO HEADER VAR INCLUDES
+# -------------------------------------------------------
+# Tests whether HEADER exists and can be compiled using the include files in
+# INCLUDES, setting the cache variable VAR accordingly.
+ac_fn_c_check_header_compile ()
+{
+  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
+$as_echo_n "checking for $2... " >&6; }
+if eval \${$3+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+$4
+#include <$2>
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  eval "$3=yes"
+else
+  eval "$3=no"
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+eval ac_res=\$$3
+	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
+$as_echo "$ac_res" >&6; }
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
+
+} # ac_fn_c_check_header_compile
+
+# ac_fn_c_try_cpp LINENO
+# ----------------------
+# Try to preprocess conftest.$ac_ext, and return whether this succeeded.
+ac_fn_c_try_cpp ()
+{
+  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+  if { { ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.err
+  ac_status=$?
+  if test -s conftest.err; then
+    grep -v '^ *+' conftest.err >conftest.er1
+    cat conftest.er1 >&5
+    mv -f conftest.er1 conftest.err
+  fi
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; } > conftest.i && {
+	 test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
+	 test ! -s conftest.err
+       }; then :
+  ac_retval=0
+else
+  $as_echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+    ac_retval=1
+fi
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
+  as_fn_set_status $ac_retval
+
+} # ac_fn_c_try_cpp
+
+# ac_fn_c_try_run LINENO
+# ----------------------
+# Try to link conftest.$ac_ext, and return whether this succeeded. Assumes
+# that executables *can* be run.
+ac_fn_c_try_run ()
+{
+  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+  if { { ac_try="$ac_link"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_link") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; } && { ac_try='./conftest$ac_exeext'
+  { { case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_try") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; }; then :
+  ac_retval=0
+else
+  $as_echo "$as_me: program exited with status $ac_status" >&5
+       $as_echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+       ac_retval=$ac_status
+fi
+  rm -rf conftest.dSYM conftest_ipa8_conftest.oo
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
+  as_fn_set_status $ac_retval
+
+} # ac_fn_c_try_run
+
+# ac_fn_c_check_func LINENO FUNC VAR
+# ----------------------------------
+# Tests whether FUNC exists, setting the cache variable VAR accordingly
+ac_fn_c_check_func ()
+{
+  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
+$as_echo_n "checking for $2... " >&6; }
+if eval \${$3+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+/* Define $2 to an innocuous variant, in case <limits.h> declares $2.
+   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
+#define $2 innocuous_$2
+
+/* System header to define __stub macros and hopefully few prototypes,
+    which can conflict with char $2 (); below.
+    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+    <limits.h> exists even on freestanding compilers.  */
+
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+
+#undef $2
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char $2 ();
+/* The GNU C library defines this for functions which it implements
+    to always fail with ENOSYS.  Some functions are actually named
+    something starting with __ and the normal name is an alias.  */
+#if defined __stub_$2 || defined __stub___$2
+choke me
+#endif
+
+int
+main ()
+{
+return $2 ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  eval "$3=yes"
+else
+  eval "$3=no"
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+fi
+eval ac_res=\$$3
+	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
+$as_echo "$ac_res" >&6; }
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
+
+} # ac_fn_c_check_func
+
+# ac_fn_cxx_try_compile LINENO
+# ----------------------------
+# Try to compile conftest.$ac_ext, and return whether this succeeded.
+ac_fn_cxx_try_compile ()
+{
+  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+  rm -f conftest.$ac_objext
+  if { { ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_compile") 2>conftest.err
+  ac_status=$?
+  if test -s conftest.err; then
+    grep -v '^ *+' conftest.err >conftest.er1
+    cat conftest.er1 >&5
+    mv -f conftest.er1 conftest.err
+  fi
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; } && {
+	 test -z "$ac_cxx_werror_flag" ||
+	 test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then :
+  ac_retval=0
+else
+  $as_echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+	ac_retval=1
+fi
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
+  as_fn_set_status $ac_retval
+
+} # ac_fn_cxx_try_compile
+
+# ac_fn_cxx_try_cpp LINENO
+# ------------------------
+# Try to preprocess conftest.$ac_ext, and return whether this succeeded.
+ac_fn_cxx_try_cpp ()
+{
+  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+  if { { ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.err
+  ac_status=$?
+  if test -s conftest.err; then
+    grep -v '^ *+' conftest.err >conftest.er1
+    cat conftest.er1 >&5
+    mv -f conftest.er1 conftest.err
+  fi
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; } > conftest.i && {
+	 test -z "$ac_cxx_preproc_warn_flag$ac_cxx_werror_flag" ||
+	 test ! -s conftest.err
+       }; then :
+  ac_retval=0
+else
+  $as_echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+    ac_retval=1
+fi
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
+  as_fn_set_status $ac_retval
+
+} # ac_fn_cxx_try_cpp
+
+# ac_fn_cxx_try_link LINENO
+# -------------------------
+# Try to link conftest.$ac_ext, and return whether this succeeded.
+ac_fn_cxx_try_link ()
+{
+  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+  rm -f conftest.$ac_objext conftest$ac_exeext
+  if { { ac_try="$ac_link"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_link") 2>conftest.err
+  ac_status=$?
+  if test -s conftest.err; then
+    grep -v '^ *+' conftest.err >conftest.er1
+    cat conftest.er1 >&5
+    mv -f conftest.er1 conftest.err
+  fi
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; } && {
+	 test -z "$ac_cxx_werror_flag" ||
+	 test ! -s conftest.err
+       } && test -s conftest$ac_exeext && {
+	 test "$cross_compiling" = yes ||
+	 $as_test_x conftest$ac_exeext
+       }; then :
+  ac_retval=0
+else
+  $as_echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+	ac_retval=1
+fi
+  # Delete the IPA/IPO (Inter Procedural Analysis/Optimization) information
+  # created by the PGI compiler (conftest_ipa8_conftest.oo), as it would
+  # interfere with the next link command; also delete a directory that is
+  # left behind by Apple's compiler.  We do this before executing the actions.
+  rm -rf conftest.dSYM conftest_ipa8_conftest.oo
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
+  as_fn_set_status $ac_retval
+
+} # ac_fn_cxx_try_link
+
+# ac_fn_c_check_header_mongrel LINENO HEADER VAR INCLUDES
+# -------------------------------------------------------
+# Tests whether HEADER exists, giving a warning if it cannot be compiled using
+# the include files in INCLUDES and setting the cache variable VAR
+# accordingly.
+ac_fn_c_check_header_mongrel ()
+{
+  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+  if eval \${$3+:} false; then :
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
+$as_echo_n "checking for $2... " >&6; }
+if eval \${$3+:} false; then :
+  $as_echo_n "(cached) " >&6
+fi
+eval ac_res=\$$3
+	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
+$as_echo "$ac_res" >&6; }
+else
+  # Is the header compilable?
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 usability" >&5
+$as_echo_n "checking $2 usability... " >&6; }
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+$4
+#include <$2>
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_header_compiler=yes
+else
+  ac_header_compiler=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_compiler" >&5
+$as_echo "$ac_header_compiler" >&6; }
+
+# Is the header present?
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 presence" >&5
+$as_echo_n "checking $2 presence... " >&6; }
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <$2>
+_ACEOF
+if ac_fn_c_try_cpp "$LINENO"; then :
+  ac_header_preproc=yes
+else
+  ac_header_preproc=no
+fi
+rm -f conftest.err conftest.i conftest.$ac_ext
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_preproc" >&5
+$as_echo "$ac_header_preproc" >&6; }
+
+# So?  What about this header?
+case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in #((
+  yes:no: )
+    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&5
+$as_echo "$as_me: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&2;}
+    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5
+$as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;}
+    ;;
+  no:yes:* )
+    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: present but cannot be compiled" >&5
+$as_echo "$as_me: WARNING: $2: present but cannot be compiled" >&2;}
+    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2:     check for missing prerequisite headers?" >&5
+$as_echo "$as_me: WARNING: $2:     check for missing prerequisite headers?" >&2;}
+    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: see the Autoconf documentation" >&5
+$as_echo "$as_me: WARNING: $2: see the Autoconf documentation" >&2;}
+    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2:     section \"Present But Cannot Be Compiled\"" >&5
+$as_echo "$as_me: WARNING: $2:     section \"Present But Cannot Be Compiled\"" >&2;}
+    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5
+$as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;}
+    ;;
+esac
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
+$as_echo_n "checking for $2... " >&6; }
+if eval \${$3+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  eval "$3=\$ac_header_compiler"
+fi
+eval ac_res=\$$3
+	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
+$as_echo "$ac_res" >&6; }
+fi
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
+
+} # ac_fn_c_check_header_mongrel
+cat >config.log <<_ACEOF
+This file contains any messages produced by compilers while
+running configure, to aid debugging if configure makes a mistake.
+
+It was created by $as_me, which was
+generated by GNU Autoconf 2.68.  Invocation command line was
+
+  $ $0 $@
+
+_ACEOF
+exec 5>>config.log
+{
+cat <<_ASUNAME
+## --------- ##
+## Platform. ##
+## --------- ##
+
+hostname = `(hostname || uname -n) 2>/dev/null | sed 1q`
+uname -m = `(uname -m) 2>/dev/null || echo unknown`
+uname -r = `(uname -r) 2>/dev/null || echo unknown`
+uname -s = `(uname -s) 2>/dev/null || echo unknown`
+uname -v = `(uname -v) 2>/dev/null || echo unknown`
+
+/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown`
+/bin/uname -X     = `(/bin/uname -X) 2>/dev/null     || echo unknown`
+
+/bin/arch              = `(/bin/arch) 2>/dev/null              || echo unknown`
+/usr/bin/arch -k       = `(/usr/bin/arch -k) 2>/dev/null       || echo unknown`
+/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown`
+/usr/bin/hostinfo      = `(/usr/bin/hostinfo) 2>/dev/null      || echo unknown`
+/bin/machine           = `(/bin/machine) 2>/dev/null           || echo unknown`
+/usr/bin/oslevel       = `(/usr/bin/oslevel) 2>/dev/null       || echo unknown`
+/bin/universe          = `(/bin/universe) 2>/dev/null          || echo unknown`
+
+_ASUNAME
+
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    $as_echo "PATH: $as_dir"
+  done
+IFS=$as_save_IFS
+
+} >&5
+
+cat >&5 <<_ACEOF
 
 
 ## ----------- ##
@@ -1141,7 +2267,6 @@ _ACEOF
 ac_configure_args=
 ac_configure_args0=
 ac_configure_args1=
-ac_sep=
 ac_must_keep_next=false
 for ac_pass in 1 2
 do
@@ -1152,13 +2277,13 @@ do
     -q | -quiet | --quiet | --quie | --qui | --qu | --q \
     | -silent | --silent | --silen | --sile | --sil)
       continue ;;
-    *" "*|*"	"*|*[\[\]\~\#\$\^\&\*\(\)\{\}\\\|\;\<\>\?\"\']*)
-      ac_arg=`echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;;
+    *\'*)
+      ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;;
     esac
     case $ac_pass in
-    1) ac_configure_args0="$ac_configure_args0 '$ac_arg'" ;;
+    1) as_fn_append ac_configure_args0 " '$ac_arg'" ;;
     2)
-      ac_configure_args1="$ac_configure_args1 '$ac_arg'"
+      as_fn_append ac_configure_args1 " '$ac_arg'"
       if test $ac_must_keep_next = true; then
 	ac_must_keep_next=false # Got value, back to normal.
       else
@@ -1174,104 +2299,115 @@ do
 	  -* ) ac_must_keep_next=true ;;
 	esac
       fi
-      ac_configure_args="$ac_configure_args$ac_sep'$ac_arg'"
-      # Get rid of the leading space.
-      ac_sep=" "
+      as_fn_append ac_configure_args " '$ac_arg'"
       ;;
     esac
   done
 done
-$as_unset ac_configure_args0 || test "${ac_configure_args0+set}" != set || { ac_configure_args0=; export ac_configure_args0; }
-$as_unset ac_configure_args1 || test "${ac_configure_args1+set}" != set || { ac_configure_args1=; export ac_configure_args1; }
+{ ac_configure_args0=; unset ac_configure_args0;}
+{ ac_configure_args1=; unset ac_configure_args1;}
 
 # When interrupted or exit'd, cleanup temporary files, and complete
 # config.log.  We remove comments because anyway the quotes in there
 # would cause problems or look ugly.
-# WARNING: Be sure not to use single quotes in there, as some shells,
-# such as our DU 5.0 friend, will then `close' the trap.
+# WARNING: Use '\'' to represent an apostrophe within the trap.
+# WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug.
 trap 'exit_status=$?
   # Save into config.log some information that might help in debugging.
   {
     echo
 
-    cat <<\_ASBOX
-## ---------------- ##
+    $as_echo "## ---------------- ##
 ## Cache variables. ##
-## ---------------- ##
-_ASBOX
+## ---------------- ##"
     echo
     # The following way of writing the cache mishandles newlines in values,
-{
+(
+  for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do
+    eval ac_val=\$$ac_var
+    case $ac_val in #(
+    *${as_nl}*)
+      case $ac_var in #(
+      *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5
+$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;;
+      esac
+      case $ac_var in #(
+      _ | IFS | as_nl) ;; #(
+      BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #(
+      *) { eval $ac_var=; unset $ac_var;} ;;
+      esac ;;
+    esac
+  done
   (set) 2>&1 |
-    case `(ac_space='"'"' '"'"'; set | grep ac_space) 2>&1` in
-    *ac_space=\ *)
+    case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #(
+    *${as_nl}ac_space=\ *)
       sed -n \
-	"s/'"'"'/'"'"'\\\\'"'"''"'"'/g;
-	  s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='"'"'\\2'"'"'/p"
-      ;;
+	"s/'\''/'\''\\\\'\'''\''/g;
+	  s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p"
+      ;; #(
     *)
-      sed -n \
-	"s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1=\\2/p"
+      sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p"
       ;;
-    esac;
-}
+    esac |
+    sort
+)
     echo
 
-    cat <<\_ASBOX
-## ----------------- ##
+    $as_echo "## ----------------- ##
 ## Output variables. ##
-## ----------------- ##
-_ASBOX
+## ----------------- ##"
     echo
     for ac_var in $ac_subst_vars
     do
-      eval ac_val=$`echo $ac_var`
-      echo "$ac_var='"'"'$ac_val'"'"'"
+      eval ac_val=\$$ac_var
+      case $ac_val in
+      *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;;
+      esac
+      $as_echo "$ac_var='\''$ac_val'\''"
     done | sort
     echo
 
     if test -n "$ac_subst_files"; then
-      cat <<\_ASBOX
-## ------------- ##
-## Output files. ##
-## ------------- ##
-_ASBOX
+      $as_echo "## ------------------- ##
+## File substitutions. ##
+## ------------------- ##"
       echo
       for ac_var in $ac_subst_files
       do
-	eval ac_val=$`echo $ac_var`
-	echo "$ac_var='"'"'$ac_val'"'"'"
+	eval ac_val=\$$ac_var
+	case $ac_val in
+	*\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;;
+	esac
+	$as_echo "$ac_var='\''$ac_val'\''"
       done | sort
       echo
     fi
 
     if test -s confdefs.h; then
-      cat <<\_ASBOX
-## ----------- ##
+      $as_echo "## ----------- ##
 ## confdefs.h. ##
-## ----------- ##
-_ASBOX
+## ----------- ##"
       echo
-      sed "/^$/d" confdefs.h | sort
+      cat confdefs.h
       echo
     fi
     test "$ac_signal" != 0 &&
-      echo "$as_me: caught signal $ac_signal"
-    echo "$as_me: exit $exit_status"
+      $as_echo "$as_me: caught signal $ac_signal"
+    $as_echo "$as_me: exit $exit_status"
   } >&5
-  rm -f core *.core &&
-  rm -rf conftest* confdefs* conf$$* $ac_clean_files &&
+  rm -f core *.core core.conftest.* &&
+    rm -f -r conftest* confdefs* conf$$* $ac_clean_files &&
     exit $exit_status
-     ' 0
+' 0
 for ac_signal in 1 2 13 15; do
-  trap 'ac_signal='$ac_signal'; { (exit 1); exit 1; }' $ac_signal
+  trap 'ac_signal='$ac_signal'; as_fn_exit 1' $ac_signal
 done
 ac_signal=0
 
 # confdefs.h avoids OS command line length limits that DEFS can exceed.
-rm -rf conftest* confdefs.h
-# AIX cpp loses on an empty file, so make sure it contains at least a newline.
-echo >confdefs.h
+rm -f -r conftest* confdefs.h
+
+$as_echo "/* confdefs.h */" > confdefs.h
 
 # Predefined preprocessor variables.
 
@@ -1279,112 +2415,137 @@ cat >>confdefs.h <<_ACEOF
 #define PACKAGE_NAME "$PACKAGE_NAME"
 _ACEOF
 
-
 cat >>confdefs.h <<_ACEOF
 #define PACKAGE_TARNAME "$PACKAGE_TARNAME"
 _ACEOF
 
-
 cat >>confdefs.h <<_ACEOF
 #define PACKAGE_VERSION "$PACKAGE_VERSION"
 _ACEOF
 
-
 cat >>confdefs.h <<_ACEOF
 #define PACKAGE_STRING "$PACKAGE_STRING"
 _ACEOF
 
-
 cat >>confdefs.h <<_ACEOF
 #define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT"
 _ACEOF
 
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_URL "$PACKAGE_URL"
+_ACEOF
+
 
 # Let the site file select an alternate cache file if it wants to.
-# Prefer explicitly selected file to automatically selected ones.
-if test -z "$CONFIG_SITE"; then
-  if test "x$prefix" != xNONE; then
-    CONFIG_SITE="$prefix/share/config.site $prefix/etc/config.site"
-  else
-    CONFIG_SITE="$ac_default_prefix/share/config.site $ac_default_prefix/etc/config.site"
-  fi
+# Prefer an explicitly selected file to automatically selected ones.
+ac_site_file1=NONE
+ac_site_file2=NONE
+if test -n "$CONFIG_SITE"; then
+  # We do not want a PATH search for config.site.
+  case $CONFIG_SITE in #((
+    -*)  ac_site_file1=./$CONFIG_SITE;;
+    */*) ac_site_file1=$CONFIG_SITE;;
+    *)   ac_site_file1=./$CONFIG_SITE;;
+  esac
+elif test "x$prefix" != xNONE; then
+  ac_site_file1=$prefix/share/config.site
+  ac_site_file2=$prefix/etc/config.site
+else
+  ac_site_file1=$ac_default_prefix/share/config.site
+  ac_site_file2=$ac_default_prefix/etc/config.site
 fi
-for ac_site_file in $CONFIG_SITE; do
-  if test -r "$ac_site_file"; then
-    { echo "$as_me:$LINENO: loading site script $ac_site_file" >&5
-echo "$as_me: loading site script $ac_site_file" >&6;}
+for ac_site_file in "$ac_site_file1" "$ac_site_file2"
+do
+  test "x$ac_site_file" = xNONE && continue
+  if test /dev/null != "$ac_site_file" && test -r "$ac_site_file"; then
+    { $as_echo "$as_me:${as_lineno-$LINENO}: loading site script $ac_site_file" >&5
+$as_echo "$as_me: loading site script $ac_site_file" >&6;}
     sed 's/^/| /' "$ac_site_file" >&5
-    . "$ac_site_file"
+    . "$ac_site_file" \
+      || { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error $? "failed to load site script $ac_site_file
+See \`config.log' for more details" "$LINENO" 5; }
   fi
 done
 
 if test -r "$cache_file"; then
-  # Some versions of bash will fail to source /dev/null (special
-  # files actually), so we avoid doing that.
-  if test -f "$cache_file"; then
-    { echo "$as_me:$LINENO: loading cache $cache_file" >&5
-echo "$as_me: loading cache $cache_file" >&6;}
+  # Some versions of bash will fail to source /dev/null (special files
+  # actually), so we avoid doing that.  DJGPP emulates it as a regular file.
+  if test /dev/null != "$cache_file" && test -f "$cache_file"; then
+    { $as_echo "$as_me:${as_lineno-$LINENO}: loading cache $cache_file" >&5
+$as_echo "$as_me: loading cache $cache_file" >&6;}
     case $cache_file in
-      [\\/]* | ?:[\\/]* ) . $cache_file;;
-      *)                      . ./$cache_file;;
+      [\\/]* | ?:[\\/]* ) . "$cache_file";;
+      *)                      . "./$cache_file";;
     esac
   fi
 else
-  { echo "$as_me:$LINENO: creating cache $cache_file" >&5
-echo "$as_me: creating cache $cache_file" >&6;}
+  { $as_echo "$as_me:${as_lineno-$LINENO}: creating cache $cache_file" >&5
+$as_echo "$as_me: creating cache $cache_file" >&6;}
   >$cache_file
 fi
 
 # Check that the precious variables saved in the cache have kept the same
 # value.
 ac_cache_corrupted=false
-for ac_var in `(set) 2>&1 |
-	       sed -n 's/^ac_env_\([a-zA-Z_0-9]*\)_set=.*/\1/p'`; do
+for ac_var in $ac_precious_vars; do
   eval ac_old_set=\$ac_cv_env_${ac_var}_set
   eval ac_new_set=\$ac_env_${ac_var}_set
-  eval ac_old_val="\$ac_cv_env_${ac_var}_value"
-  eval ac_new_val="\$ac_env_${ac_var}_value"
+  eval ac_old_val=\$ac_cv_env_${ac_var}_value
+  eval ac_new_val=\$ac_env_${ac_var}_value
   case $ac_old_set,$ac_new_set in
     set,)
-      { echo "$as_me:$LINENO: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5
-echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;}
+      { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5
+$as_echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;}
       ac_cache_corrupted=: ;;
     ,set)
-      { echo "$as_me:$LINENO: error: \`$ac_var' was not set in the previous run" >&5
-echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;}
+      { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was not set in the previous run" >&5
+$as_echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;}
       ac_cache_corrupted=: ;;
     ,);;
     *)
       if test "x$ac_old_val" != "x$ac_new_val"; then
-	{ echo "$as_me:$LINENO: error: \`$ac_var' has changed since the previous run:" >&5
-echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;}
-	{ echo "$as_me:$LINENO:   former value:  $ac_old_val" >&5
-echo "$as_me:   former value:  $ac_old_val" >&2;}
-	{ echo "$as_me:$LINENO:   current value: $ac_new_val" >&5
-echo "$as_me:   current value: $ac_new_val" >&2;}
-	ac_cache_corrupted=:
+	# differences in whitespace do not lead to failure.
+	ac_old_val_w=`echo x $ac_old_val`
+	ac_new_val_w=`echo x $ac_new_val`
+	if test "$ac_old_val_w" != "$ac_new_val_w"; then
+	  { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' has changed since the previous run:" >&5
+$as_echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;}
+	  ac_cache_corrupted=:
+	else
+	  { $as_echo "$as_me:${as_lineno-$LINENO}: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&5
+$as_echo "$as_me: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&2;}
+	  eval $ac_var=\$ac_old_val
+	fi
+	{ $as_echo "$as_me:${as_lineno-$LINENO}:   former value:  \`$ac_old_val'" >&5
+$as_echo "$as_me:   former value:  \`$ac_old_val'" >&2;}
+	{ $as_echo "$as_me:${as_lineno-$LINENO}:   current value: \`$ac_new_val'" >&5
+$as_echo "$as_me:   current value: \`$ac_new_val'" >&2;}
       fi;;
   esac
   # Pass precious variables to config.status.
   if test "$ac_new_set" = set; then
     case $ac_new_val in
-    *" "*|*"	"*|*[\[\]\~\#\$\^\&\*\(\)\{\}\\\|\;\<\>\?\"\']*)
-      ac_arg=$ac_var=`echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;;
+    *\'*) ac_arg=$ac_var=`$as_echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;;
     *) ac_arg=$ac_var=$ac_new_val ;;
     esac
     case " $ac_configure_args " in
       *" '$ac_arg' "*) ;; # Avoid dups.  Use of quotes ensures accuracy.
-      *) ac_configure_args="$ac_configure_args '$ac_arg'" ;;
+      *) as_fn_append ac_configure_args " '$ac_arg'" ;;
     esac
   fi
 done
 if $ac_cache_corrupted; then
-  { echo "$as_me:$LINENO: error: changes in the environment can compromise the build" >&5
-echo "$as_me: error: changes in the environment can compromise the build" >&2;}
-  { { echo "$as_me:$LINENO: error: run \`make distclean' and/or \`rm $cache_file' and start over" >&5
-echo "$as_me: error: run \`make distclean' and/or \`rm $cache_file' and start over" >&2;}
-   { (exit 1); exit 1; }; }
+  { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+  { $as_echo "$as_me:${as_lineno-$LINENO}: error: changes in the environment can compromise the build" >&5
+$as_echo "$as_me: error: changes in the environment can compromise the build" >&2;}
+  as_fn_error $? "run \`make distclean' and/or \`rm $cache_file' and start over" "$LINENO" 5
 fi
+## -------------------- ##
+## Main body of script. ##
+## -------------------- ##
 
 ac_ext=c
 ac_cpp='$CPP $CPPFLAGS'
@@ -1393,10 +2554,186 @@ ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $
 ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
 
+ac_aux_dir=
+for ac_dir in "$srcdir" "$srcdir/.." "$srcdir/../.."; do
+  if test -f "$ac_dir/install-sh"; then
+    ac_aux_dir=$ac_dir
+    ac_install_sh="$ac_aux_dir/install-sh -c"
+    break
+  elif test -f "$ac_dir/install.sh"; then
+    ac_aux_dir=$ac_dir
+    ac_install_sh="$ac_aux_dir/install.sh -c"
+    break
+  elif test -f "$ac_dir/shtool"; then
+    ac_aux_dir=$ac_dir
+    ac_install_sh="$ac_aux_dir/shtool install -c"
+    break
+  fi
+done
+if test -z "$ac_aux_dir"; then
+  as_fn_error $? "cannot find install-sh, install.sh, or shtool in \"$srcdir\" \"$srcdir/..\" \"$srcdir/../..\"" "$LINENO" 5
+fi
+
+# These three variables are undocumented and unsupported,
+# and are intended to be withdrawn in a future Autoconf release.
+# They can cause serious problems if a builder's source tree is in a directory
+# whose full name contains unusual characters.
+ac_config_guess="$SHELL $ac_aux_dir/config.guess"  # Please don't use this var.
+ac_config_sub="$SHELL $ac_aux_dir/config.sub"  # Please don't use this var.
+ac_configure="$SHELL $ac_aux_dir/configure"  # Please don't use this var.
+
+
+case `pwd` in
+  *\ * | *\	*)
+    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Libtool does not cope well with whitespace in \`pwd\`" >&5
+$as_echo "$as_me: WARNING: Libtool does not cope well with whitespace in \`pwd\`" >&2;} ;;
+esac
+
+
+
+macro_version='2.4.2'
+macro_revision='1.3337'
+
+
+
+
+
+
+
+
+
+
+
+
+
+ltmain="$ac_aux_dir/ltmain.sh"
 
+# Make sure we can run config.sub.
+$SHELL "$ac_aux_dir/config.sub" sun4 >/dev/null 2>&1 ||
+  as_fn_error $? "cannot run $SHELL $ac_aux_dir/config.sub" "$LINENO" 5
 
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking build system type" >&5
+$as_echo_n "checking build system type... " >&6; }
+if ${ac_cv_build+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_build_alias=$build_alias
+test "x$ac_build_alias" = x &&
+  ac_build_alias=`$SHELL "$ac_aux_dir/config.guess"`
+test "x$ac_build_alias" = x &&
+  as_fn_error $? "cannot guess build type; you must specify one" "$LINENO" 5
+ac_cv_build=`$SHELL "$ac_aux_dir/config.sub" $ac_build_alias` ||
+  as_fn_error $? "$SHELL $ac_aux_dir/config.sub $ac_build_alias failed" "$LINENO" 5
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_build" >&5
+$as_echo "$ac_cv_build" >&6; }
+case $ac_cv_build in
+*-*-*) ;;
+*) as_fn_error $? "invalid value of canonical build" "$LINENO" 5;;
+esac
+build=$ac_cv_build
+ac_save_IFS=$IFS; IFS='-'
+set x $ac_cv_build
+shift
+build_cpu=$1
+build_vendor=$2
+shift; shift
+# Remember, the first character of IFS is used to create $*,
+# except with old shells:
+build_os=$*
+IFS=$ac_save_IFS
+case $build_os in *\ *) build_os=`echo "$build_os" | sed 's/ /-/g'`;; esac
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking host system type" >&5
+$as_echo_n "checking host system type... " >&6; }
+if ${ac_cv_host+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test "x$host_alias" = x; then
+  ac_cv_host=$ac_cv_build
+else
+  ac_cv_host=`$SHELL "$ac_aux_dir/config.sub" $host_alias` ||
+    as_fn_error $? "$SHELL $ac_aux_dir/config.sub $host_alias failed" "$LINENO" 5
+fi
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_host" >&5
+$as_echo "$ac_cv_host" >&6; }
+case $ac_cv_host in
+*-*-*) ;;
+*) as_fn_error $? "invalid value of canonical host" "$LINENO" 5;;
+esac
+host=$ac_cv_host
+ac_save_IFS=$IFS; IFS='-'
+set x $ac_cv_host
+shift
+host_cpu=$1
+host_vendor=$2
+shift; shift
+# Remember, the first character of IFS is used to create $*,
+# except with old shells:
+host_os=$*
+IFS=$ac_save_IFS
+case $host_os in *\ *) host_os=`echo "$host_os" | sed 's/ /-/g'`;; esac
+
+
+# Backslashify metacharacters that are still active within
+# double-quoted strings.
+sed_quote_subst='s/\(["`$\\]\)/\\\1/g'
+
+# Same as above, but do not quote variable references.
+double_quote_subst='s/\(["`\\]\)/\\\1/g'
+
+# Sed substitution to delay expansion of an escaped shell variable in a
+# double_quote_subst'ed string.
+delay_variable_subst='s/\\\\\\\\\\\$/\\\\\\$/g'
+
+# Sed substitution to delay expansion of an escaped single quote.
+delay_single_quote_subst='s/'\''/'\'\\\\\\\'\''/g'
+
+# Sed substitution to avoid accidental globbing in evaled expressions
+no_glob_subst='s/\*/\\\*/g'
+
+ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
+ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO
+ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO$ECHO
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to print strings" >&5
+$as_echo_n "checking how to print strings... " >&6; }
+# Test print first, because it will be a builtin if present.
+if test "X`( print -r -- -n ) 2>/dev/null`" = X-n && \
+   test "X`print -r -- $ECHO 2>/dev/null`" = "X$ECHO"; then
+  ECHO='print -r --'
+elif test "X`printf %s $ECHO 2>/dev/null`" = "X$ECHO"; then
+  ECHO='printf %s\n'
+else
+  # Use this function as a fallback that always works.
+  func_fallback_echo ()
+  {
+    eval 'cat <<_LTECHO_EOF
+$1
+_LTECHO_EOF'
+  }
+  ECHO='func_fallback_echo'
+fi
 
+# func_echo_all arg...
+# Invoke $ECHO with all args, space-separated.
+func_echo_all ()
+{
+    $ECHO ""
+}
 
+case "$ECHO" in
+  printf*) { $as_echo "$as_me:${as_lineno-$LINENO}: result: printf" >&5
+$as_echo "printf" >&6; } ;;
+  print*) { $as_echo "$as_me:${as_lineno-$LINENO}: result: print -r" >&5
+$as_echo "print -r" >&6; } ;;
+  *) { $as_echo "$as_me:${as_lineno-$LINENO}: result: cat" >&5
+$as_echo "cat" >&6; } ;;
+esac
 
 
 
@@ -1419,10 +2756,10 @@ ac_compiler_gnu=$ac_cv_c_compiler_gnu
 if test -n "$ac_tool_prefix"; then
   # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args.
 set dummy ${ac_tool_prefix}gcc; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
-if test "${ac_cv_prog_CC+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_CC+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
   if test -n "$CC"; then
   ac_cv_prog_CC="$CC" # Let the user override the test.
@@ -1432,35 +2769,37 @@ for as_dir in $PATH
 do
   IFS=$as_save_IFS
   test -z "$as_dir" && as_dir=.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
     ac_cv_prog_CC="${ac_tool_prefix}gcc"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
-done
+  done
+IFS=$as_save_IFS
 
 fi
 fi
 CC=$ac_cv_prog_CC
 if test -n "$CC"; then
-  echo "$as_me:$LINENO: result: $CC" >&5
-echo "${ECHO_T}$CC" >&6
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
+$as_echo "$CC" >&6; }
 else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
 
+
 fi
 if test -z "$ac_cv_prog_CC"; then
   ac_ct_CC=$CC
   # Extract the first word of "gcc", so it can be a program name with args.
 set dummy gcc; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
-if test "${ac_cv_prog_ac_ct_CC+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_ac_ct_CC+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
   if test -n "$ac_ct_CC"; then
   ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test.
@@ -1470,39 +2809,50 @@ for as_dir in $PATH
 do
   IFS=$as_save_IFS
   test -z "$as_dir" && as_dir=.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
     ac_cv_prog_ac_ct_CC="gcc"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
-done
+  done
+IFS=$as_save_IFS
 
 fi
 fi
 ac_ct_CC=$ac_cv_prog_ac_ct_CC
 if test -n "$ac_ct_CC"; then
-  echo "$as_me:$LINENO: result: $ac_ct_CC" >&5
-echo "${ECHO_T}$ac_ct_CC" >&6
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5
+$as_echo "$ac_ct_CC" >&6; }
 else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
 
-  CC=$ac_ct_CC
+  if test "x$ac_ct_CC" = x; then
+    CC=""
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
+$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
+ac_tool_warned=yes ;;
+esac
+    CC=$ac_ct_CC
+  fi
 else
   CC="$ac_cv_prog_CC"
 fi
 
 if test -z "$CC"; then
-  if test -n "$ac_tool_prefix"; then
-  # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args.
+          if test -n "$ac_tool_prefix"; then
+    # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args.
 set dummy ${ac_tool_prefix}cc; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
-if test "${ac_cv_prog_CC+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_CC+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
   if test -n "$CC"; then
   ac_cv_prog_CC="$CC" # Let the user override the test.
@@ -1512,99 +2862,60 @@ for as_dir in $PATH
 do
   IFS=$as_save_IFS
   test -z "$as_dir" && as_dir=.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
     ac_cv_prog_CC="${ac_tool_prefix}cc"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
-done
+  done
+IFS=$as_save_IFS
 
 fi
 fi
 CC=$ac_cv_prog_CC
 if test -n "$CC"; then
-  echo "$as_me:$LINENO: result: $CC" >&5
-echo "${ECHO_T}$CC" >&6
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
+$as_echo "$CC" >&6; }
 else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
 
+
+  fi
 fi
-if test -z "$ac_cv_prog_CC"; then
-  ac_ct_CC=$CC
+if test -z "$CC"; then
   # Extract the first word of "cc", so it can be a program name with args.
 set dummy cc; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
-if test "${ac_cv_prog_ac_ct_CC+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_CC+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
-  if test -n "$ac_ct_CC"; then
-  ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test.
+  if test -n "$CC"; then
+  ac_cv_prog_CC="$CC" # Let the user override the test.
 else
+  ac_prog_rejected=no
 as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
 for as_dir in $PATH
 do
   IFS=$as_save_IFS
   test -z "$as_dir" && as_dir=.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_ac_ct_CC="cc"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
-
-fi
-fi
-ac_ct_CC=$ac_cv_prog_ac_ct_CC
-if test -n "$ac_ct_CC"; then
-  echo "$as_me:$LINENO: result: $ac_ct_CC" >&5
-echo "${ECHO_T}$ac_ct_CC" >&6
-else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
-fi
-
-  CC=$ac_ct_CC
-else
-  CC="$ac_cv_prog_CC"
-fi
-
-fi
-if test -z "$CC"; then
-  # Extract the first word of "cc", so it can be a program name with args.
-set dummy cc; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
-if test "${ac_cv_prog_CC+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  if test -n "$CC"; then
-  ac_cv_prog_CC="$CC" # Let the user override the test.
-else
-  ac_prog_rejected=no
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
     if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then
        ac_prog_rejected=yes
        continue
      fi
     ac_cv_prog_CC="cc"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
-done
+  done
+IFS=$as_save_IFS
 
 if test $ac_prog_rejected = yes; then
   # We found a bogon in the path, so make sure we never use it.
@@ -1622,24 +2933,25 @@ fi
 fi
 CC=$ac_cv_prog_CC
 if test -n "$CC"; then
-  echo "$as_me:$LINENO: result: $CC" >&5
-echo "${ECHO_T}$CC" >&6
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
+$as_echo "$CC" >&6; }
 else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
 
+
 fi
 if test -z "$CC"; then
   if test -n "$ac_tool_prefix"; then
-  for ac_prog in cl
+  for ac_prog in cl.exe
   do
     # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args.
 set dummy $ac_tool_prefix$ac_prog; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
-if test "${ac_cv_prog_CC+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_CC+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
   if test -n "$CC"; then
   ac_cv_prog_CC="$CC" # Let the user override the test.
@@ -1649,39 +2961,41 @@ for as_dir in $PATH
 do
   IFS=$as_save_IFS
   test -z "$as_dir" && as_dir=.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
     ac_cv_prog_CC="$ac_tool_prefix$ac_prog"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
-done
+  done
+IFS=$as_save_IFS
 
 fi
 fi
 CC=$ac_cv_prog_CC
 if test -n "$CC"; then
-  echo "$as_me:$LINENO: result: $CC" >&5
-echo "${ECHO_T}$CC" >&6
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
+$as_echo "$CC" >&6; }
 else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
 
+
     test -n "$CC" && break
   done
 fi
 if test -z "$CC"; then
   ac_ct_CC=$CC
-  for ac_prog in cl
+  for ac_prog in cl.exe
 do
   # Extract the first word of "$ac_prog", so it can be a program name with args.
 set dummy $ac_prog; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
-if test "${ac_cv_prog_ac_ct_CC+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_ac_ct_CC+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
   if test -n "$ac_ct_CC"; then
   ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test.
@@ -1691,66 +3005,78 @@ for as_dir in $PATH
 do
   IFS=$as_save_IFS
   test -z "$as_dir" && as_dir=.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
     ac_cv_prog_ac_ct_CC="$ac_prog"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
-done
+  done
+IFS=$as_save_IFS
 
 fi
 fi
 ac_ct_CC=$ac_cv_prog_ac_ct_CC
 if test -n "$ac_ct_CC"; then
-  echo "$as_me:$LINENO: result: $ac_ct_CC" >&5
-echo "${ECHO_T}$ac_ct_CC" >&6
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5
+$as_echo "$ac_ct_CC" >&6; }
 else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
 
+
   test -n "$ac_ct_CC" && break
 done
 
-  CC=$ac_ct_CC
+  if test "x$ac_ct_CC" = x; then
+    CC=""
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
+$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
+ac_tool_warned=yes ;;
+esac
+    CC=$ac_ct_CC
+  fi
 fi
 
 fi
 
 
-test -z "$CC" && { { echo "$as_me:$LINENO: error: no acceptable C compiler found in \$PATH
-See \`config.log' for more details." >&5
-echo "$as_me: error: no acceptable C compiler found in \$PATH
-See \`config.log' for more details." >&2;}
-   { (exit 1); exit 1; }; }
+test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error $? "no acceptable C compiler found in \$PATH
+See \`config.log' for more details" "$LINENO" 5; }
 
 # Provide some information about the compiler.
-echo "$as_me:$LINENO:" \
-     "checking for C compiler version" >&5
-ac_compiler=`set X $ac_compile; echo $2`
-{ (eval echo "$as_me:$LINENO: \"$ac_compiler --version </dev/null >&5\"") >&5
-  (eval $ac_compiler --version </dev/null >&5) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }
-{ (eval echo "$as_me:$LINENO: \"$ac_compiler -v </dev/null >&5\"") >&5
-  (eval $ac_compiler -v </dev/null >&5) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }
-{ (eval echo "$as_me:$LINENO: \"$ac_compiler -V </dev/null >&5\"") >&5
-  (eval $ac_compiler -V </dev/null >&5) 2>&5
+$as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5
+set X $ac_compile
+ac_compiler=$2
+for ac_option in --version -v -V -qversion; do
+  { { ac_try="$ac_compiler $ac_option >&5"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_compiler $ac_option >&5") 2>conftest.err
   ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }
+  if test -s conftest.err; then
+    sed '10a\
+... rest of stderr output deleted ...
+         10q' conftest.err >conftest.er1
+    cat conftest.er1 >&5
+  fi
+  rm -f conftest.er1 conftest.err
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }
+done
 
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
 int
@@ -1762,112 +3088,108 @@ main ()
 }
 _ACEOF
 ac_clean_files_save=$ac_clean_files
-ac_clean_files="$ac_clean_files a.out a.exe b.out"
+ac_clean_files="$ac_clean_files a.out a.out.dSYM a.exe b.out"
 # Try to create an executable without -o first, disregard a.out.
 # It will help us diagnose broken compilers, and finding out an intuition
 # of exeext.
-echo "$as_me:$LINENO: checking for C compiler default output file name" >&5
-echo $ECHO_N "checking for C compiler default output file name... $ECHO_C" >&6
-ac_link_default=`echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'`
-if { (eval echo "$as_me:$LINENO: \"$ac_link_default\"") >&5
-  (eval $ac_link_default) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; then
-  # Find the output, starting from the most likely.  This scheme is
-# not robust to junk in `.', hence go to wildcards (a.*) only as a last
-# resort.
-
-# Be careful to initialize this variable, since it used to be cached.
-# Otherwise an old cache value of `no' led to `EXEEXT = no' in a Makefile.
-ac_cv_exeext=
-# b.out is created by i960 compilers.
-for ac_file in a_out.exe a.exe conftest.exe a.out conftest a.* conftest.* b.out
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler works" >&5
+$as_echo_n "checking whether the C compiler works... " >&6; }
+ac_link_default=`$as_echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'`
+
+# The possible output files:
+ac_files="a.out conftest.exe conftest a.exe a_out.exe b.out conftest.*"
+
+ac_rmfiles=
+for ac_file in $ac_files
+do
+  case $ac_file in
+    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;;
+    * ) ac_rmfiles="$ac_rmfiles $ac_file";;
+  esac
+done
+rm -f $ac_rmfiles
+
+if { { ac_try="$ac_link_default"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_link_default") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; then :
+  # Autoconf-2.13 could set the ac_cv_exeext variable to `no'.
+# So ignore a value of `no', otherwise this would lead to `EXEEXT = no'
+# in a Makefile.  We should not override ac_cv_exeext if it was cached,
+# so that the user can short-circuit this test for compilers unknown to
+# Autoconf.
+for ac_file in $ac_files ''
 do
   test -f "$ac_file" || continue
   case $ac_file in
-    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.o | *.obj )
-	;;
-    conftest.$ac_ext )
-	# This is the source file.
+    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj )
 	;;
     [ab].out )
 	# We found the default executable, but exeext='' is most
 	# certainly right.
 	break;;
     *.* )
-	ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'`
-	# FIXME: I believe we export ac_cv_exeext for Libtool,
-	# but it would be cool to find out if it's true.  Does anybody
-	# maintain Libtool? --akim.
-	export ac_cv_exeext
+	if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no;
+	then :; else
+	   ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'`
+	fi
+	# We set ac_cv_exeext here because the later test for it is not
+	# safe: cross compilers may not add the suffix if given an `-o'
+	# argument, so we may need to know it at that point already.
+	# Even if this section looks crufty: it has the advantage of
+	# actually working.
 	break;;
     * )
 	break;;
   esac
 done
+test "$ac_cv_exeext" = no && ac_cv_exeext=
+
 else
-  echo "$as_me: failed program was:" >&5
+  ac_file=''
+fi
+if test -z "$ac_file"; then :
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+$as_echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-{ { echo "$as_me:$LINENO: error: C compiler cannot create executables
-See \`config.log' for more details." >&5
-echo "$as_me: error: C compiler cannot create executables
-See \`config.log' for more details." >&2;}
-   { (exit 77); exit 77; }; }
+{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error 77 "C compiler cannot create executables
+See \`config.log' for more details" "$LINENO" 5; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
 fi
-
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler default output file name" >&5
+$as_echo_n "checking for C compiler default output file name... " >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_file" >&5
+$as_echo "$ac_file" >&6; }
 ac_exeext=$ac_cv_exeext
-echo "$as_me:$LINENO: result: $ac_file" >&5
-echo "${ECHO_T}$ac_file" >&6
-
-# Check the compiler produces executables we can run.  If not, either
-# the compiler is broken, or we cross compile.
-echo "$as_me:$LINENO: checking whether the C compiler works" >&5
-echo $ECHO_N "checking whether the C compiler works... $ECHO_C" >&6
-# FIXME: These cross compiler hacks should be removed for Autoconf 3.0
-# If not cross compiling, check that we can run a simple program.
-if test "$cross_compiling" != yes; then
-  if { ac_try='./$ac_file'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-    cross_compiling=no
-  else
-    if test "$cross_compiling" = maybe; then
-	cross_compiling=yes
-    else
-	{ { echo "$as_me:$LINENO: error: cannot run C compiled programs.
-If you meant to cross compile, use \`--host'.
-See \`config.log' for more details." >&5
-echo "$as_me: error: cannot run C compiled programs.
-If you meant to cross compile, use \`--host'.
-See \`config.log' for more details." >&2;}
-   { (exit 1); exit 1; }; }
-    fi
-  fi
-fi
-echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6
 
-rm -f a.out a.exe conftest$ac_cv_exeext b.out
+rm -f -r a.out a.out.dSYM a.exe conftest$ac_cv_exeext b.out
 ac_clean_files=$ac_clean_files_save
-# Check the compiler produces executables we can run.  If not, either
-# the compiler is broken, or we cross compile.
-echo "$as_me:$LINENO: checking whether we are cross compiling" >&5
-echo $ECHO_N "checking whether we are cross compiling... $ECHO_C" >&6
-echo "$as_me:$LINENO: result: $cross_compiling" >&5
-echo "${ECHO_T}$cross_compiling" >&6
-
-echo "$as_me:$LINENO: checking for suffix of executables" >&5
-echo $ECHO_N "checking for suffix of executables... $ECHO_C" >&6
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>&5
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of executables" >&5
+$as_echo_n "checking for suffix of executables... " >&6; }
+if { { ac_try="$ac_link"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_link") 2>&5
   ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; then
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; then :
   # If both `conftest.exe' and `conftest' are `present' (well, observable)
 # catch `conftest.exe'.  For instance with Cygwin, `ls conftest' will
 # work properly (i.e., refer to `conftest.exe'), while it won't with
@@ -1875,38 +3197,90 @@ if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
 for ac_file in conftest.exe conftest conftest.*; do
   test -f "$ac_file" || continue
   case $ac_file in
-    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.o | *.obj ) ;;
+    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;;
     *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'`
-	  export ac_cv_exeext
 	  break;;
     * ) break;;
   esac
 done
 else
-  { { echo "$as_me:$LINENO: error: cannot compute suffix of executables: cannot compile and link
-See \`config.log' for more details." >&5
-echo "$as_me: error: cannot compute suffix of executables: cannot compile and link
-See \`config.log' for more details." >&2;}
-   { (exit 1); exit 1; }; }
+  { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error $? "cannot compute suffix of executables: cannot compile and link
+See \`config.log' for more details" "$LINENO" 5; }
 fi
-
-rm -f conftest$ac_cv_exeext
-echo "$as_me:$LINENO: result: $ac_cv_exeext" >&5
-echo "${ECHO_T}$ac_cv_exeext" >&6
+rm -f conftest conftest$ac_cv_exeext
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5
+$as_echo "$ac_cv_exeext" >&6; }
 
 rm -f conftest.$ac_ext
 EXEEXT=$ac_cv_exeext
 ac_exeext=$EXEEXT
-echo "$as_me:$LINENO: checking for suffix of object files" >&5
-echo $ECHO_N "checking for suffix of object files... $ECHO_C" >&6
-if test "${ac_cv_objext+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <stdio.h>
+int
+main ()
+{
+FILE *f = fopen ("conftest.out", "w");
+ return ferror (f) || fclose (f) != 0;
+
+  ;
+  return 0;
+}
 _ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+ac_clean_files="$ac_clean_files conftest.out"
+# Check that the compiler produces executables we can run.  If not, either
+# the compiler is broken, or we cross compile.
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are cross compiling" >&5
+$as_echo_n "checking whether we are cross compiling... " >&6; }
+if test "$cross_compiling" != yes; then
+  { { ac_try="$ac_link"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_link") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }
+  if { ac_try='./conftest$ac_cv_exeext'
+  { { case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_try") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; }; then
+    cross_compiling=no
+  else
+    if test "$cross_compiling" = maybe; then
+	cross_compiling=yes
+    else
+	{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error $? "cannot run C compiled programs.
+If you meant to cross compile, use \`--host'.
+See \`config.log' for more details" "$LINENO" 5; }
+    fi
+  fi
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $cross_compiling" >&5
+$as_echo "$cross_compiling" >&6; }
+
+rm -f conftest.$ac_ext conftest$ac_cv_exeext conftest.out
+ac_clean_files=$ac_clean_files_save
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of object files" >&5
+$as_echo_n "checking for suffix of object files... " >&6; }
+if ${ac_cv_objext+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
 int
@@ -1918,45 +3292,46 @@ main ()
 }
 _ACEOF
 rm -f conftest.o conftest.obj
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; then
-  for ac_file in `(ls conftest.o conftest.obj; ls conftest.*) 2>/dev/null`; do
+if { { ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_compile") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; then :
+  for ac_file in conftest.o conftest.obj conftest.*; do
+  test -f "$ac_file" || continue;
   case $ac_file in
-    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg ) ;;
+    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM ) ;;
     *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'`
        break;;
   esac
 done
 else
-  echo "$as_me: failed program was:" >&5
+  $as_echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-{ { echo "$as_me:$LINENO: error: cannot compute suffix of object files: cannot compile
-See \`config.log' for more details." >&5
-echo "$as_me: error: cannot compute suffix of object files: cannot compile
-See \`config.log' for more details." >&2;}
-   { (exit 1); exit 1; }; }
+{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error $? "cannot compute suffix of object files: cannot compile
+See \`config.log' for more details" "$LINENO" 5; }
 fi
-
 rm -f conftest.$ac_cv_objext conftest.$ac_ext
 fi
-echo "$as_me:$LINENO: result: $ac_cv_objext" >&5
-echo "${ECHO_T}$ac_cv_objext" >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_objext" >&5
+$as_echo "$ac_cv_objext" >&6; }
 OBJEXT=$ac_cv_objext
 ac_objext=$OBJEXT
-echo "$as_me:$LINENO: checking whether we are using the GNU C compiler" >&5
-echo $ECHO_N "checking whether we are using the GNU C compiler... $ECHO_C" >&6
-if test "${ac_cv_c_compiler_gnu+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C compiler" >&5
+$as_echo_n "checking whether we are using the GNU C compiler... " >&6; }
+if ${ac_cv_c_compiler_gnu+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
 int
@@ -1970,55 +3345,34 @@ main ()
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest.$ac_objext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
+if ac_fn_c_try_compile "$LINENO"; then :
   ac_compiler_gnu=yes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-ac_compiler_gnu=no
+  ac_compiler_gnu=no
 fi
-rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
 ac_cv_c_compiler_gnu=$ac_compiler_gnu
 
 fi
-echo "$as_me:$LINENO: result: $ac_cv_c_compiler_gnu" >&5
-echo "${ECHO_T}$ac_cv_c_compiler_gnu" >&6
-GCC=`test $ac_compiler_gnu = yes && echo yes`
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5
+$as_echo "$ac_cv_c_compiler_gnu" >&6; }
+if test $ac_compiler_gnu = yes; then
+  GCC=yes
+else
+  GCC=
+fi
 ac_test_CFLAGS=${CFLAGS+set}
 ac_save_CFLAGS=$CFLAGS
-CFLAGS="-g"
-echo "$as_me:$LINENO: checking whether $CC accepts -g" >&5
-echo $ECHO_N "checking whether $CC accepts -g... $ECHO_C" >&6
-if test "${ac_cv_prog_cc_g+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5
+$as_echo_n "checking whether $CC accepts -g... " >&6; }
+if ${ac_cv_prog_cc_g+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_save_c_werror_flag=$ac_c_werror_flag
+   ac_c_werror_flag=yes
+   ac_cv_prog_cc_g=no
+   CFLAGS="-g"
+   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
 int
@@ -2029,39 +3383,49 @@ main ()
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest.$ac_objext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
+if ac_fn_c_try_compile "$LINENO"; then :
   ac_cv_prog_cc_g=yes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
+  CFLAGS=""
+      cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
 
-ac_cv_prog_cc_g=no
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+
+else
+  ac_c_werror_flag=$ac_save_c_werror_flag
+	 CFLAGS="-g"
+	 cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_prog_cc_g=yes
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
 fi
-rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
 fi
-echo "$as_me:$LINENO: result: $ac_cv_prog_cc_g" >&5
-echo "${ECHO_T}$ac_cv_prog_cc_g" >&6
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+   ac_c_werror_flag=$ac_save_c_werror_flag
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5
+$as_echo "$ac_cv_prog_cc_g" >&6; }
 if test "$ac_test_CFLAGS" = set; then
   CFLAGS=$ac_save_CFLAGS
 elif test $ac_cv_prog_cc_g = yes; then
@@ -2077,18 +3441,14 @@ else
     CFLAGS=
   fi
 fi
-echo "$as_me:$LINENO: checking for $CC option to accept ANSI C" >&5
-echo $ECHO_N "checking for $CC option to accept ANSI C... $ECHO_C" >&6
-if test "${ac_cv_prog_cc_stdc+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C89" >&5
+$as_echo_n "checking for $CC option to accept ISO C89... " >&6; }
+if ${ac_cv_prog_cc_c89+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
-  ac_cv_prog_cc_stdc=no
+  ac_cv_prog_cc_c89=no
 ac_save_CC=$CC
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <stdarg.h>
 #include <stdio.h>
@@ -2116,12 +3476,17 @@ static char *f (char * (*g) (char **, int), char **p, ...)
 /* OSF 4.0 Compaq cc is some sort of almost-ANSI by default.  It has
    function prototypes and stuff, but not '\xHH' hex character constants.
    These don't provoke an error unfortunately, instead are silently treated
-   as 'x'.  The following induces an error, until -std1 is added to get
+   as 'x'.  The following induces an error, until -std is added to get
    proper ANSI mode.  Curiously '\x00'!='x' always comes out true, for an
    array size at least.  It's necessary to write '\x00'==0 to get something
-   that's true only with -std1.  */
+   that's true only with -std.  */
 int osf4_cc_array ['\x00' == 0 ? 1 : -1];
 
+/* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters
+   inside strings and character constants.  */
+#define FOO(x) 'x'
+int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1];
+
 int test (int i, double x);
 struct s1 {int (*f) (int a);};
 struct s2 {int (*f) (double a);};
@@ -2136,1572 +3501,1590 @@ return f (e, argv, 0) != argv[0]  ||  f (e, argv, 1) != argv[1];
   return 0;
 }
 _ACEOF
-# Don't try gcc -ansi; that turns off useful extensions and
-# breaks some systems' header files.
-# AIX			-qlanglvl=ansi
-# Ultrix and OSF/1	-std1
-# HP-UX 10.20 and later	-Ae
-# HP-UX older versions	-Aa -D_HPUX_SOURCE
-# SVR4			-Xc -D__EXTENSIONS__
-for ac_arg in "" -qlanglvl=ansi -std1 -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__"
+for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \
+	-Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__"
 do
   CC="$ac_save_CC $ac_arg"
-  rm -f conftest.$ac_objext
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest.$ac_objext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_prog_cc_stdc=$ac_arg
-break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
+  if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_prog_cc_c89=$ac_arg
 fi
-rm -f conftest.err conftest.$ac_objext
+rm -f core conftest.err conftest.$ac_objext
+  test "x$ac_cv_prog_cc_c89" != "xno" && break
 done
-rm -f conftest.$ac_ext conftest.$ac_objext
+rm -f conftest.$ac_ext
 CC=$ac_save_CC
 
 fi
-
-case "x$ac_cv_prog_cc_stdc" in
-  x|xno)
-    echo "$as_me:$LINENO: result: none needed" >&5
-echo "${ECHO_T}none needed" >&6 ;;
+# AC_CACHE_VAL
+case "x$ac_cv_prog_cc_c89" in
+  x)
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: none needed" >&5
+$as_echo "none needed" >&6; } ;;
+  xno)
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5
+$as_echo "unsupported" >&6; } ;;
   *)
-    echo "$as_me:$LINENO: result: $ac_cv_prog_cc_stdc" >&5
-echo "${ECHO_T}$ac_cv_prog_cc_stdc" >&6
-    CC="$CC $ac_cv_prog_cc_stdc" ;;
+    CC="$CC $ac_cv_prog_cc_c89"
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5
+$as_echo "$ac_cv_prog_cc_c89" >&6; } ;;
 esac
-
-# Some people use a C++ compiler to compile C.  Since we use `exit',
-# in C++ we need to declare it.  In case someone uses the same compiler
-# for both compiling C and C++ we need to have the C++ compiler decide
-# the declaration of exit, since it's the most demanding environment.
-cat >conftest.$ac_ext <<_ACEOF
-#ifndef __cplusplus
-  choke me
-#endif
-_ACEOF
-rm -f conftest.$ac_objext
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest.$ac_objext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  for ac_declaration in \
-   '' \
-   'extern "C" void std::exit (int) throw (); using std::exit;' \
-   'extern "C" void std::exit (int); using std::exit;' \
-   'extern "C" void exit (int) throw ();' \
-   'extern "C" void exit (int);' \
-   'void exit (int);'
-do
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_declaration
-#include <stdlib.h>
-int
-main ()
-{
-exit (42);
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest.$ac_objext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  :
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-continue
-fi
-rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_declaration
-int
-main ()
-{
-exit (42);
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest.$ac_objext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
+if test "x$ac_cv_prog_cc_c89" != xno; then :
 
 fi
-rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
-done
-rm -f conftest*
-if test -n "$ac_declaration"; then
-  echo '#ifdef __cplusplus' >>confdefs.h
-  echo $ac_declaration      >>confdefs.h
-  echo '#endif'             >>confdefs.h
-fi
-
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
 
-fi
-rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
 ac_ext=c
 ac_cpp='$CPP $CPPFLAGS'
 ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
 ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
 ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
-ac_ext=cc
-ac_cpp='$CXXCPP $CPPFLAGS'
-ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
-if test -n "$ac_tool_prefix"; then
-  for ac_prog in $CCC g++ c++ gpp aCC CC cxx cc++ cl FCC KCC RCC xlC_r xlC
-  do
-    # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args.
-set dummy $ac_tool_prefix$ac_prog; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
-if test "${ac_cv_prog_CXX+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  if test -n "$CXX"; then
-  ac_cv_prog_CXX="$CXX" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for a sed that does not truncate output" >&5
+$as_echo_n "checking for a sed that does not truncate output... " >&6; }
+if ${ac_cv_path_SED+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+            ac_script=s/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/
+     for ac_i in 1 2 3 4 5 6 7; do
+       ac_script="$ac_script$as_nl$ac_script"
+     done
+     echo "$ac_script" 2>/dev/null | sed 99q >conftest.sed
+     { ac_script=; unset ac_script;}
+     if test -z "$SED"; then
+  ac_path_SED_found=false
+  # Loop through the user's path and test for each of PROGNAME-LIST
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
 for as_dir in $PATH
 do
   IFS=$as_save_IFS
   test -z "$as_dir" && as_dir=.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_CXX="$ac_tool_prefix$ac_prog"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
+    for ac_prog in sed gsed; do
+    for ac_exec_ext in '' $ac_executable_extensions; do
+      ac_path_SED="$as_dir/$ac_prog$ac_exec_ext"
+      { test -f "$ac_path_SED" && $as_test_x "$ac_path_SED"; } || continue
+# Check for GNU ac_path_SED and select it if it is found.
+  # Check for GNU $ac_path_SED
+case `"$ac_path_SED" --version 2>&1` in
+*GNU*)
+  ac_cv_path_SED="$ac_path_SED" ac_path_SED_found=:;;
+*)
+  ac_count=0
+  $as_echo_n 0123456789 >"conftest.in"
+  while :
+  do
+    cat "conftest.in" "conftest.in" >"conftest.tmp"
+    mv "conftest.tmp" "conftest.in"
+    cp "conftest.in" "conftest.nl"
+    $as_echo '' >> "conftest.nl"
+    "$ac_path_SED" -f conftest.sed < "conftest.nl" >"conftest.out" 2>/dev/null || break
+    diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break
+    as_fn_arith $ac_count + 1 && ac_count=$as_val
+    if test $ac_count -gt ${ac_path_SED_max-0}; then
+      # Best one so far, save it but keep looking for a better one
+      ac_cv_path_SED="$ac_path_SED"
+      ac_path_SED_max=$ac_count
+    fi
+    # 10*(2^10) chars as input seems more than enough
+    test $ac_count -gt 10 && break
+  done
+  rm -f conftest.in conftest.tmp conftest.nl conftest.out;;
+esac
 
-fi
-fi
-CXX=$ac_cv_prog_CXX
-if test -n "$CXX"; then
-  echo "$as_me:$LINENO: result: $CXX" >&5
-echo "${ECHO_T}$CXX" >&6
+      $ac_path_SED_found && break 3
+    done
+  done
+  done
+IFS=$as_save_IFS
+  if test -z "$ac_cv_path_SED"; then
+    as_fn_error $? "no acceptable sed could be found in \$PATH" "$LINENO" 5
+  fi
 else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
+  ac_cv_path_SED=$SED
 fi
 
-    test -n "$CXX" && break
-  done
 fi
-if test -z "$CXX"; then
-  ac_ct_CXX=$CXX
-  for ac_prog in $CCC g++ c++ gpp aCC CC cxx cc++ cl FCC KCC RCC xlC_r xlC
-do
-  # Extract the first word of "$ac_prog", so it can be a program name with args.
-set dummy $ac_prog; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
-if test "${ac_cv_prog_ac_ct_CXX+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  if test -n "$ac_ct_CXX"; then
-  ac_cv_prog_ac_ct_CXX="$ac_ct_CXX" # Let the user override the test.
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_SED" >&5
+$as_echo "$ac_cv_path_SED" >&6; }
+ SED="$ac_cv_path_SED"
+  rm -f conftest.sed
+
+test -z "$SED" && SED=sed
+Xsed="$SED -e 1s/^X//"
+
+
+
+
+
+
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for grep that handles long lines and -e" >&5
+$as_echo_n "checking for grep that handles long lines and -e... " >&6; }
+if ${ac_cv_path_GREP+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
+  if test -z "$GREP"; then
+  ac_path_GREP_found=false
+  # Loop through the user's path and test for each of PROGNAME-LIST
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin
 do
   IFS=$as_save_IFS
   test -z "$as_dir" && as_dir=.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_ac_ct_CXX="$ac_prog"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
+    for ac_prog in grep ggrep; do
+    for ac_exec_ext in '' $ac_executable_extensions; do
+      ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext"
+      { test -f "$ac_path_GREP" && $as_test_x "$ac_path_GREP"; } || continue
+# Check for GNU ac_path_GREP and select it if it is found.
+  # Check for GNU $ac_path_GREP
+case `"$ac_path_GREP" --version 2>&1` in
+*GNU*)
+  ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;;
+*)
+  ac_count=0
+  $as_echo_n 0123456789 >"conftest.in"
+  while :
+  do
+    cat "conftest.in" "conftest.in" >"conftest.tmp"
+    mv "conftest.tmp" "conftest.in"
+    cp "conftest.in" "conftest.nl"
+    $as_echo 'GREP' >> "conftest.nl"
+    "$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"conftest.out" 2>/dev/null || break
+    diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break
+    as_fn_arith $ac_count + 1 && ac_count=$as_val
+    if test $ac_count -gt ${ac_path_GREP_max-0}; then
+      # Best one so far, save it but keep looking for a better one
+      ac_cv_path_GREP="$ac_path_GREP"
+      ac_path_GREP_max=$ac_count
+    fi
+    # 10*(2^10) chars as input seems more than enough
+    test $ac_count -gt 10 && break
+  done
+  rm -f conftest.in conftest.tmp conftest.nl conftest.out;;
+esac
 
-fi
-fi
-ac_ct_CXX=$ac_cv_prog_ac_ct_CXX
-if test -n "$ac_ct_CXX"; then
-  echo "$as_me:$LINENO: result: $ac_ct_CXX" >&5
-echo "${ECHO_T}$ac_ct_CXX" >&6
+      $ac_path_GREP_found && break 3
+    done
+  done
+  done
+IFS=$as_save_IFS
+  if test -z "$ac_cv_path_GREP"; then
+    as_fn_error $? "no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5
+  fi
 else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
+  ac_cv_path_GREP=$GREP
 fi
 
-  test -n "$ac_ct_CXX" && break
-done
-test -n "$ac_ct_CXX" || ac_ct_CXX="g++"
-
-  CXX=$ac_ct_CXX
 fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_GREP" >&5
+$as_echo "$ac_cv_path_GREP" >&6; }
+ GREP="$ac_cv_path_GREP"
 
 
-# Provide some information about the compiler.
-echo "$as_me:$LINENO:" \
-     "checking for C++ compiler version" >&5
-ac_compiler=`set X $ac_compile; echo $2`
-{ (eval echo "$as_me:$LINENO: \"$ac_compiler --version </dev/null >&5\"") >&5
-  (eval $ac_compiler --version </dev/null >&5) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }
-{ (eval echo "$as_me:$LINENO: \"$ac_compiler -v </dev/null >&5\"") >&5
-  (eval $ac_compiler -v </dev/null >&5) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }
-{ (eval echo "$as_me:$LINENO: \"$ac_compiler -V </dev/null >&5\"") >&5
-  (eval $ac_compiler -V </dev/null >&5) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for egrep" >&5
+$as_echo_n "checking for egrep... " >&6; }
+if ${ac_cv_path_EGREP+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if echo a | $GREP -E '(a|b)' >/dev/null 2>&1
+   then ac_cv_path_EGREP="$GREP -E"
+   else
+     if test -z "$EGREP"; then
+  ac_path_EGREP_found=false
+  # Loop through the user's path and test for each of PROGNAME-LIST
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_prog in egrep; do
+    for ac_exec_ext in '' $ac_executable_extensions; do
+      ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext"
+      { test -f "$ac_path_EGREP" && $as_test_x "$ac_path_EGREP"; } || continue
+# Check for GNU ac_path_EGREP and select it if it is found.
+  # Check for GNU $ac_path_EGREP
+case `"$ac_path_EGREP" --version 2>&1` in
+*GNU*)
+  ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;;
+*)
+  ac_count=0
+  $as_echo_n 0123456789 >"conftest.in"
+  while :
+  do
+    cat "conftest.in" "conftest.in" >"conftest.tmp"
+    mv "conftest.tmp" "conftest.in"
+    cp "conftest.in" "conftest.nl"
+    $as_echo 'EGREP' >> "conftest.nl"
+    "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break
+    diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break
+    as_fn_arith $ac_count + 1 && ac_count=$as_val
+    if test $ac_count -gt ${ac_path_EGREP_max-0}; then
+      # Best one so far, save it but keep looking for a better one
+      ac_cv_path_EGREP="$ac_path_EGREP"
+      ac_path_EGREP_max=$ac_count
+    fi
+    # 10*(2^10) chars as input seems more than enough
+    test $ac_count -gt 10 && break
+  done
+  rm -f conftest.in conftest.tmp conftest.nl conftest.out;;
+esac
 
-echo "$as_me:$LINENO: checking whether we are using the GNU C++ compiler" >&5
-echo $ECHO_N "checking whether we are using the GNU C++ compiler... $ECHO_C" >&6
-if test "${ac_cv_cxx_compiler_gnu+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+      $ac_path_EGREP_found && break 3
+    done
+  done
+  done
+IFS=$as_save_IFS
+  if test -z "$ac_cv_path_EGREP"; then
+    as_fn_error $? "no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5
+  fi
 else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
+  ac_cv_path_EGREP=$EGREP
+fi
 
-int
-main ()
-{
-#ifndef __GNUC__
-       choke me
-#endif
+   fi
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_EGREP" >&5
+$as_echo "$ac_cv_path_EGREP" >&6; }
+ EGREP="$ac_cv_path_EGREP"
 
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_cxx_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest.$ac_objext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_compiler_gnu=yes
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for fgrep" >&5
+$as_echo_n "checking for fgrep... " >&6; }
+if ${ac_cv_path_FGREP+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
+  if echo 'ab*c' | $GREP -F 'ab*c' >/dev/null 2>&1
+   then ac_cv_path_FGREP="$GREP -F"
+   else
+     if test -z "$FGREP"; then
+  ac_path_FGREP_found=false
+  # Loop through the user's path and test for each of PROGNAME-LIST
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_prog in fgrep; do
+    for ac_exec_ext in '' $ac_executable_extensions; do
+      ac_path_FGREP="$as_dir/$ac_prog$ac_exec_ext"
+      { test -f "$ac_path_FGREP" && $as_test_x "$ac_path_FGREP"; } || continue
+# Check for GNU ac_path_FGREP and select it if it is found.
+  # Check for GNU $ac_path_FGREP
+case `"$ac_path_FGREP" --version 2>&1` in
+*GNU*)
+  ac_cv_path_FGREP="$ac_path_FGREP" ac_path_FGREP_found=:;;
+*)
+  ac_count=0
+  $as_echo_n 0123456789 >"conftest.in"
+  while :
+  do
+    cat "conftest.in" "conftest.in" >"conftest.tmp"
+    mv "conftest.tmp" "conftest.in"
+    cp "conftest.in" "conftest.nl"
+    $as_echo 'FGREP' >> "conftest.nl"
+    "$ac_path_FGREP" FGREP < "conftest.nl" >"conftest.out" 2>/dev/null || break
+    diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break
+    as_fn_arith $ac_count + 1 && ac_count=$as_val
+    if test $ac_count -gt ${ac_path_FGREP_max-0}; then
+      # Best one so far, save it but keep looking for a better one
+      ac_cv_path_FGREP="$ac_path_FGREP"
+      ac_path_FGREP_max=$ac_count
+    fi
+    # 10*(2^10) chars as input seems more than enough
+    test $ac_count -gt 10 && break
+  done
+  rm -f conftest.in conftest.tmp conftest.nl conftest.out;;
+esac
 
-ac_compiler_gnu=no
+      $ac_path_FGREP_found && break 3
+    done
+  done
+  done
+IFS=$as_save_IFS
+  if test -z "$ac_cv_path_FGREP"; then
+    as_fn_error $? "no acceptable fgrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5
+  fi
+else
+  ac_cv_path_FGREP=$FGREP
 fi
-rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
-ac_cv_cxx_compiler_gnu=$ac_compiler_gnu
 
+   fi
 fi
-echo "$as_me:$LINENO: result: $ac_cv_cxx_compiler_gnu" >&5
-echo "${ECHO_T}$ac_cv_cxx_compiler_gnu" >&6
-GXX=`test $ac_compiler_gnu = yes && echo yes`
-ac_test_CXXFLAGS=${CXXFLAGS+set}
-ac_save_CXXFLAGS=$CXXFLAGS
-CXXFLAGS="-g"
-echo "$as_me:$LINENO: checking whether $CXX accepts -g" >&5
-echo $ECHO_N "checking whether $CXX accepts -g... $ECHO_C" >&6
-if test "${ac_cv_prog_cxx_g+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_FGREP" >&5
+$as_echo "$ac_cv_path_FGREP" >&6; }
+ FGREP="$ac_cv_path_FGREP"
 
-int
-main ()
-{
 
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_cxx_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest.$ac_objext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_prog_cxx_g=yes
+test -z "$GREP" && GREP=grep
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+# Check whether --with-gnu-ld was given.
+if test "${with_gnu_ld+set}" = set; then :
+  withval=$with_gnu_ld; test "$withval" = no || with_gnu_ld=yes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
+  with_gnu_ld=no
+fi
 
-ac_cv_prog_cxx_g=no
+ac_prog=ld
+if test "$GCC" = yes; then
+  # Check if gcc -print-prog-name=ld gives a path.
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ld used by $CC" >&5
+$as_echo_n "checking for ld used by $CC... " >&6; }
+  case $host in
+  *-*-mingw*)
+    # gcc leaves a trailing carriage return which upsets mingw
+    ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;;
+  *)
+    ac_prog=`($CC -print-prog-name=ld) 2>&5` ;;
+  esac
+  case $ac_prog in
+    # Accept absolute paths.
+    [\\/]* | ?:[\\/]*)
+      re_direlt='/[^/][^/]*/\.\./'
+      # Canonicalize the pathname of ld
+      ac_prog=`$ECHO "$ac_prog"| $SED 's%\\\\%/%g'`
+      while $ECHO "$ac_prog" | $GREP "$re_direlt" > /dev/null 2>&1; do
+	ac_prog=`$ECHO $ac_prog| $SED "s%$re_direlt%/%"`
+      done
+      test -z "$LD" && LD="$ac_prog"
+      ;;
+  "")
+    # If it fails, then pretend we aren't using GCC.
+    ac_prog=ld
+    ;;
+  *)
+    # If it is relative, then search for the first ld in PATH.
+    with_gnu_ld=unknown
+    ;;
+  esac
+elif test "$with_gnu_ld" = yes; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for GNU ld" >&5
+$as_echo_n "checking for GNU ld... " >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for non-GNU ld" >&5
+$as_echo_n "checking for non-GNU ld... " >&6; }
+fi
+if ${lt_cv_path_LD+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -z "$LD"; then
+  lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
+  for ac_dir in $PATH; do
+    IFS="$lt_save_ifs"
+    test -z "$ac_dir" && ac_dir=.
+    if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then
+      lt_cv_path_LD="$ac_dir/$ac_prog"
+      # Check to see if the program is GNU ld.  I'd rather use --version,
+      # but apparently some variants of GNU ld only accept -v.
+      # Break only if it was the GNU/non-GNU ld that we prefer.
+      case `"$lt_cv_path_LD" -v 2>&1 </dev/null` in
+      *GNU* | *'with BFD'*)
+	test "$with_gnu_ld" != no && break
+	;;
+      *)
+	test "$with_gnu_ld" != yes && break
+	;;
+      esac
+    fi
+  done
+  IFS="$lt_save_ifs"
+else
+  lt_cv_path_LD="$LD" # Let the user override the test with a path.
 fi
-rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
 fi
-echo "$as_me:$LINENO: result: $ac_cv_prog_cxx_g" >&5
-echo "${ECHO_T}$ac_cv_prog_cxx_g" >&6
-if test "$ac_test_CXXFLAGS" = set; then
-  CXXFLAGS=$ac_save_CXXFLAGS
-elif test $ac_cv_prog_cxx_g = yes; then
-  if test "$GXX" = yes; then
-    CXXFLAGS="-g -O2"
-  else
-    CXXFLAGS="-g"
-  fi
+
+LD="$lt_cv_path_LD"
+if test -n "$LD"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $LD" >&5
+$as_echo "$LD" >&6; }
 else
-  if test "$GXX" = yes; then
-    CXXFLAGS="-O2"
-  else
-    CXXFLAGS=
-  fi
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
-for ac_declaration in \
-   '' \
-   'extern "C" void std::exit (int) throw (); using std::exit;' \
-   'extern "C" void std::exit (int); using std::exit;' \
-   'extern "C" void exit (int) throw ();' \
-   'extern "C" void exit (int);' \
-   'void exit (int);'
-do
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_declaration
-#include <stdlib.h>
-int
-main ()
-{
-exit (42);
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_cxx_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest.$ac_objext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  :
+test -z "$LD" && as_fn_error $? "no acceptable ld found in \$PATH" "$LINENO" 5
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if the linker ($LD) is GNU ld" >&5
+$as_echo_n "checking if the linker ($LD) is GNU ld... " >&6; }
+if ${lt_cv_prog_gnu_ld+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-continue
+  # I'd rather use --version here, but apparently some GNU lds only accept -v.
+case `$LD -v 2>&1 </dev/null` in
+*GNU* | *'with BFD'*)
+  lt_cv_prog_gnu_ld=yes
+  ;;
+*)
+  lt_cv_prog_gnu_ld=no
+  ;;
+esac
 fi
-rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_declaration
-int
-main ()
-{
-exit (42);
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_cxx_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest.$ac_objext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_gnu_ld" >&5
+$as_echo "$lt_cv_prog_gnu_ld" >&6; }
+with_gnu_ld=$lt_cv_prog_gnu_ld
 
-fi
-rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
-done
-rm -f conftest*
-if test -n "$ac_declaration"; then
-  echo '#ifdef __cplusplus' >>confdefs.h
-  echo $ac_declaration      >>confdefs.h
-  echo '#endif'             >>confdefs.h
-fi
 
-ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
-if test -n "$ac_tool_prefix"; then
-  # Extract the first word of "${ac_tool_prefix}ranlib", so it can be a program name with args.
-set dummy ${ac_tool_prefix}ranlib; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
-if test "${ac_cv_prog_RANLIB+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for BSD- or MS-compatible name lister (nm)" >&5
+$as_echo_n "checking for BSD- or MS-compatible name lister (nm)... " >&6; }
+if ${lt_cv_path_NM+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
-  if test -n "$RANLIB"; then
-  ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test.
+  if test -n "$NM"; then
+  # Let the user override the test.
+  lt_cv_path_NM="$NM"
+else
+  lt_nm_to_check="${ac_tool_prefix}nm"
+  if test -n "$ac_tool_prefix" && test "$build" = "$host"; then
+    lt_nm_to_check="$lt_nm_to_check nm"
+  fi
+  for lt_tmp_nm in $lt_nm_to_check; do
+    lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
+    for ac_dir in $PATH /usr/ccs/bin/elf /usr/ccs/bin /usr/ucb /bin; do
+      IFS="$lt_save_ifs"
+      test -z "$ac_dir" && ac_dir=.
+      tmp_nm="$ac_dir/$lt_tmp_nm"
+      if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext" ; then
+	# Check to see if the nm accepts a BSD-compat flag.
+	# Adding the `sed 1q' prevents false positives on HP-UX, which says:
+	#   nm: unknown option "B" ignored
+	# Tru64's nm complains that /dev/null is an invalid object file
+	case `"$tmp_nm" -B /dev/null 2>&1 | sed '1q'` in
+	*/dev/null* | *'Invalid file or object type'*)
+	  lt_cv_path_NM="$tmp_nm -B"
+	  break
+	  ;;
+	*)
+	  case `"$tmp_nm" -p /dev/null 2>&1 | sed '1q'` in
+	  */dev/null*)
+	    lt_cv_path_NM="$tmp_nm -p"
+	    break
+	    ;;
+	  *)
+	    lt_cv_path_NM=${lt_cv_path_NM="$tmp_nm"} # keep the first match, but
+	    continue # so that we can try to find one that supports BSD flags
+	    ;;
+	  esac
+	  ;;
+	esac
+      fi
+    done
+    IFS="$lt_save_ifs"
+  done
+  : ${lt_cv_path_NM=no}
+fi
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_path_NM" >&5
+$as_echo "$lt_cv_path_NM" >&6; }
+if test "$lt_cv_path_NM" != "no"; then
+  NM="$lt_cv_path_NM"
+else
+  # Didn't find any BSD compatible name lister, look for dumpbin.
+  if test -n "$DUMPBIN"; then :
+    # Let the user override the test.
+  else
+    if test -n "$ac_tool_prefix"; then
+  for ac_prog in dumpbin "link -dump"
+  do
+    # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args.
+set dummy $ac_tool_prefix$ac_prog; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_DUMPBIN+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$DUMPBIN"; then
+  ac_cv_prog_DUMPBIN="$DUMPBIN" # Let the user override the test.
 else
 as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
 for as_dir in $PATH
 do
   IFS=$as_save_IFS
   test -z "$as_dir" && as_dir=.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_RANLIB="${ac_tool_prefix}ranlib"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_DUMPBIN="$ac_tool_prefix$ac_prog"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
-done
+  done
+IFS=$as_save_IFS
 
 fi
 fi
-RANLIB=$ac_cv_prog_RANLIB
-if test -n "$RANLIB"; then
-  echo "$as_me:$LINENO: result: $RANLIB" >&5
-echo "${ECHO_T}$RANLIB" >&6
+DUMPBIN=$ac_cv_prog_DUMPBIN
+if test -n "$DUMPBIN"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DUMPBIN" >&5
+$as_echo "$DUMPBIN" >&6; }
 else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
 
+
+    test -n "$DUMPBIN" && break
+  done
 fi
-if test -z "$ac_cv_prog_RANLIB"; then
-  ac_ct_RANLIB=$RANLIB
-  # Extract the first word of "ranlib", so it can be a program name with args.
-set dummy ranlib; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
-if test "${ac_cv_prog_ac_ct_RANLIB+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+if test -z "$DUMPBIN"; then
+  ac_ct_DUMPBIN=$DUMPBIN
+  for ac_prog in dumpbin "link -dump"
+do
+  # Extract the first word of "$ac_prog", so it can be a program name with args.
+set dummy $ac_prog; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_ac_ct_DUMPBIN+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
-  if test -n "$ac_ct_RANLIB"; then
-  ac_cv_prog_ac_ct_RANLIB="$ac_ct_RANLIB" # Let the user override the test.
+  if test -n "$ac_ct_DUMPBIN"; then
+  ac_cv_prog_ac_ct_DUMPBIN="$ac_ct_DUMPBIN" # Let the user override the test.
 else
 as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
 for as_dir in $PATH
 do
   IFS=$as_save_IFS
   test -z "$as_dir" && as_dir=.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_ac_ct_RANLIB="ranlib"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_ac_ct_DUMPBIN="$ac_prog"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
-done
+  done
+IFS=$as_save_IFS
 
-  test -z "$ac_cv_prog_ac_ct_RANLIB" && ac_cv_prog_ac_ct_RANLIB=":"
 fi
 fi
-ac_ct_RANLIB=$ac_cv_prog_ac_ct_RANLIB
-if test -n "$ac_ct_RANLIB"; then
-  echo "$as_me:$LINENO: result: $ac_ct_RANLIB" >&5
-echo "${ECHO_T}$ac_ct_RANLIB" >&6
+ac_ct_DUMPBIN=$ac_cv_prog_ac_ct_DUMPBIN
+if test -n "$ac_ct_DUMPBIN"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_DUMPBIN" >&5
+$as_echo "$ac_ct_DUMPBIN" >&6; }
 else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
 
-  RANLIB=$ac_ct_RANLIB
-else
-  RANLIB="$ac_cv_prog_RANLIB"
-fi
 
+  test -n "$ac_ct_DUMPBIN" && break
+done
 
-for ac_prog in flex lex
-do
-  # Extract the first word of "$ac_prog", so it can be a program name with args.
-set dummy $ac_prog; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
-if test "${ac_cv_prog_LEX+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  if test -n "$LEX"; then
-  ac_cv_prog_LEX="$LEX" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_LEX="$ac_prog"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
+  if test "x$ac_ct_DUMPBIN" = x; then
+    DUMPBIN=":"
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
+$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
+ac_tool_warned=yes ;;
+esac
+    DUMPBIN=$ac_ct_DUMPBIN
+  fi
+fi
+
+    case `$DUMPBIN -symbols /dev/null 2>&1 | sed '1q'` in
+    *COFF*)
+      DUMPBIN="$DUMPBIN -symbols"
+      ;;
+    *)
+      DUMPBIN=:
+      ;;
+    esac
   fi
-done
-done
 
+  if test "$DUMPBIN" != ":"; then
+    NM="$DUMPBIN"
+  fi
 fi
+test -z "$NM" && NM=nm
+
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking the name lister ($NM) interface" >&5
+$as_echo_n "checking the name lister ($NM) interface... " >&6; }
+if ${lt_cv_nm_interface+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  lt_cv_nm_interface="BSD nm"
+  echo "int some_variable = 0;" > conftest.$ac_ext
+  (eval echo "\"\$as_me:$LINENO: $ac_compile\"" >&5)
+  (eval "$ac_compile" 2>conftest.err)
+  cat conftest.err >&5
+  (eval echo "\"\$as_me:$LINENO: $NM \\\"conftest.$ac_objext\\\"\"" >&5)
+  (eval "$NM \"conftest.$ac_objext\"" 2>conftest.err > conftest.out)
+  cat conftest.err >&5
+  (eval echo "\"\$as_me:$LINENO: output\"" >&5)
+  cat conftest.out >&5
+  if $GREP 'External.*some_variable' conftest.out > /dev/null; then
+    lt_cv_nm_interface="MS dumpbin"
+  fi
+  rm -f conftest*
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_nm_interface" >&5
+$as_echo "$lt_cv_nm_interface" >&6; }
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether ln -s works" >&5
+$as_echo_n "checking whether ln -s works... " >&6; }
+LN_S=$as_ln_s
+if test "$LN_S" = "ln -s"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no, using $LN_S" >&5
+$as_echo "no, using $LN_S" >&6; }
+fi
+
+# find the maximum length of command line arguments
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking the maximum length of command line arguments" >&5
+$as_echo_n "checking the maximum length of command line arguments... " >&6; }
+if ${lt_cv_sys_max_cmd_len+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+    i=0
+  teststring="ABCD"
+
+  case $build_os in
+  msdosdjgpp*)
+    # On DJGPP, this test can blow up pretty badly due to problems in libc
+    # (any single argument exceeding 2000 bytes causes a buffer overrun
+    # during glob expansion).  Even if it were fixed, the result of this
+    # check would be larger than it should be.
+    lt_cv_sys_max_cmd_len=12288;    # 12K is about right
+    ;;
+
+  gnu*)
+    # Under GNU Hurd, this test is not required because there is
+    # no limit to the length of command line arguments.
+    # Libtool will interpret -1 as no limit whatsoever
+    lt_cv_sys_max_cmd_len=-1;
+    ;;
+
+  cygwin* | mingw* | cegcc*)
+    # On Win9x/ME, this test blows up -- it succeeds, but takes
+    # about 5 minutes as the teststring grows exponentially.
+    # Worse, since 9x/ME are not pre-emptively multitasking,
+    # you end up with a "frozen" computer, even though with patience
+    # the test eventually succeeds (with a max line length of 256k).
+    # Instead, let's just punt: use the minimum linelength reported by
+    # all of the supported platforms: 8192 (on NT/2K/XP).
+    lt_cv_sys_max_cmd_len=8192;
+    ;;
+
+  mint*)
+    # On MiNT this can take a long time and run out of memory.
+    lt_cv_sys_max_cmd_len=8192;
+    ;;
+
+  amigaos*)
+    # On AmigaOS with pdksh, this test takes hours, literally.
+    # So we just punt and use a minimum line length of 8192.
+    lt_cv_sys_max_cmd_len=8192;
+    ;;
+
+  netbsd* | freebsd* | openbsd* | darwin* | dragonfly*)
+    # This has been around since 386BSD, at least.  Likely further.
+    if test -x /sbin/sysctl; then
+      lt_cv_sys_max_cmd_len=`/sbin/sysctl -n kern.argmax`
+    elif test -x /usr/sbin/sysctl; then
+      lt_cv_sys_max_cmd_len=`/usr/sbin/sysctl -n kern.argmax`
+    else
+      lt_cv_sys_max_cmd_len=65536	# usable default for all BSDs
+    fi
+    # And add a safety zone
+    lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4`
+    lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3`
+    ;;
+
+  interix*)
+    # We know the value 262144 and hardcode it with a safety zone (like BSD)
+    lt_cv_sys_max_cmd_len=196608
+    ;;
+
+  os2*)
+    # The test takes a long time on OS/2.
+    lt_cv_sys_max_cmd_len=8192
+    ;;
+
+  osf*)
+    # Dr. Hans Ekkehard Plesser reports seeing a kernel panic running configure
+    # due to this test when exec_disable_arg_limit is 1 on Tru64. It is not
+    # nice to cause kernel panics so lets avoid the loop below.
+    # First set a reasonable default.
+    lt_cv_sys_max_cmd_len=16384
+    #
+    if test -x /sbin/sysconfig; then
+      case `/sbin/sysconfig -q proc exec_disable_arg_limit` in
+        *1*) lt_cv_sys_max_cmd_len=-1 ;;
+      esac
+    fi
+    ;;
+  sco3.2v5*)
+    lt_cv_sys_max_cmd_len=102400
+    ;;
+  sysv5* | sco5v6* | sysv4.2uw2*)
+    kargmax=`grep ARG_MAX /etc/conf/cf.d/stune 2>/dev/null`
+    if test -n "$kargmax"; then
+      lt_cv_sys_max_cmd_len=`echo $kargmax | sed 's/.*[	 ]//'`
+    else
+      lt_cv_sys_max_cmd_len=32768
+    fi
+    ;;
+  *)
+    lt_cv_sys_max_cmd_len=`(getconf ARG_MAX) 2> /dev/null`
+    if test -n "$lt_cv_sys_max_cmd_len"; then
+      lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4`
+      lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3`
+    else
+      # Make teststring a little bigger before we do anything with it.
+      # a 1K string should be a reasonable start.
+      for i in 1 2 3 4 5 6 7 8 ; do
+        teststring=$teststring$teststring
+      done
+      SHELL=${SHELL-${CONFIG_SHELL-/bin/sh}}
+      # If test is not a shell built-in, we'll probably end up computing a
+      # maximum length that is only half of the actual maximum length, but
+      # we can't tell.
+      while { test "X"`env echo "$teststring$teststring" 2>/dev/null` \
+	         = "X$teststring$teststring"; } >/dev/null 2>&1 &&
+	      test $i != 17 # 1/2 MB should be enough
+      do
+        i=`expr $i + 1`
+        teststring=$teststring$teststring
+      done
+      # Only check the string length outside the loop.
+      lt_cv_sys_max_cmd_len=`expr "X$teststring" : ".*" 2>&1`
+      teststring=
+      # Add a significant safety factor because C++ compilers can tack on
+      # massive amounts of additional arguments before passing them to the
+      # linker.  It appears as though 1/2 is a usable value.
+      lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 2`
+    fi
+    ;;
+  esac
+
 fi
-LEX=$ac_cv_prog_LEX
-if test -n "$LEX"; then
-  echo "$as_me:$LINENO: result: $LEX" >&5
-echo "${ECHO_T}$LEX" >&6
+
+if test -n $lt_cv_sys_max_cmd_len ; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_sys_max_cmd_len" >&5
+$as_echo "$lt_cv_sys_max_cmd_len" >&6; }
 else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: none" >&5
+$as_echo "none" >&6; }
 fi
+max_cmd_len=$lt_cv_sys_max_cmd_len
+
+
+
+
 
-  test -n "$LEX" && break
-done
-test -n "$LEX" || LEX=":"
 
-if test -z "$LEXLIB"
-then
-  echo "$as_me:$LINENO: checking for yywrap in -lfl" >&5
-echo $ECHO_N "checking for yywrap in -lfl... $ECHO_C" >&6
-if test "${ac_cv_lib_fl_yywrap+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+: ${CP="cp -f"}
+: ${MV="mv -f"}
+: ${RM="rm -f"}
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the shell understands some XSI constructs" >&5
+$as_echo_n "checking whether the shell understands some XSI constructs... " >&6; }
+# Try some XSI features
+xsi_shell=no
+( _lt_dummy="a/b/c"
+  test "${_lt_dummy##*/},${_lt_dummy%/*},${_lt_dummy#??}"${_lt_dummy%"$_lt_dummy"}, \
+      = c,a/b,b/c, \
+    && eval 'test $(( 1 + 1 )) -eq 2 \
+    && test "${#_lt_dummy}" -eq 5' ) >/dev/null 2>&1 \
+  && xsi_shell=yes
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $xsi_shell" >&5
+$as_echo "$xsi_shell" >&6; }
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the shell understands \"+=\"" >&5
+$as_echo_n "checking whether the shell understands \"+=\"... " >&6; }
+lt_shell_append=no
+( foo=bar; set foo baz; eval "$1+=\$2" && test "$foo" = barbaz ) \
+    >/dev/null 2>&1 \
+  && lt_shell_append=yes
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_shell_append" >&5
+$as_echo "$lt_shell_append" >&6; }
+
+
+if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then
+  lt_unset=unset
 else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-lfl  $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
+  lt_unset=false
+fi
 
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char yywrap ();
-int
-main ()
-{
-yywrap ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_fl_yywrap=yes
+
+
+
+
+# test EBCDIC or ASCII
+case `echo X|tr X '\101'` in
+ A) # ASCII based system
+    # \n is not interpreted correctly by Solaris 8 /usr/ucb/tr
+  lt_SP2NL='tr \040 \012'
+  lt_NL2SP='tr \015\012 \040\040'
+  ;;
+ *) # EBCDIC based system
+  lt_SP2NL='tr \100 \n'
+  lt_NL2SP='tr \r\n \100\100'
+  ;;
+esac
+
+
+
+
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to convert $build file names to $host format" >&5
+$as_echo_n "checking how to convert $build file names to $host format... " >&6; }
+if ${lt_cv_to_host_file_cmd+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
+  case $host in
+  *-*-mingw* )
+    case $build in
+      *-*-mingw* ) # actually msys
+        lt_cv_to_host_file_cmd=func_convert_file_msys_to_w32
+        ;;
+      *-*-cygwin* )
+        lt_cv_to_host_file_cmd=func_convert_file_cygwin_to_w32
+        ;;
+      * ) # otherwise, assume *nix
+        lt_cv_to_host_file_cmd=func_convert_file_nix_to_w32
+        ;;
+    esac
+    ;;
+  *-*-cygwin* )
+    case $build in
+      *-*-mingw* ) # actually msys
+        lt_cv_to_host_file_cmd=func_convert_file_msys_to_cygwin
+        ;;
+      *-*-cygwin* )
+        lt_cv_to_host_file_cmd=func_convert_file_noop
+        ;;
+      * ) # otherwise, assume *nix
+        lt_cv_to_host_file_cmd=func_convert_file_nix_to_cygwin
+        ;;
+    esac
+    ;;
+  * ) # unhandled hosts (and "normal" native builds)
+    lt_cv_to_host_file_cmd=func_convert_file_noop
+    ;;
+esac
 
-ac_cv_lib_fl_yywrap=no
 fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_fl_yywrap" >&5
-echo "${ECHO_T}$ac_cv_lib_fl_yywrap" >&6
-if test $ac_cv_lib_fl_yywrap = yes; then
-  LEXLIB="-lfl"
-else
-  echo "$as_me:$LINENO: checking for yywrap in -ll" >&5
-echo $ECHO_N "checking for yywrap in -ll... $ECHO_C" >&6
-if test "${ac_cv_lib_l_yywrap+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-ll  $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
 
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char yywrap ();
-int
-main ()
-{
-yywrap ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_l_yywrap=yes
+to_host_file_cmd=$lt_cv_to_host_file_cmd
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_to_host_file_cmd" >&5
+$as_echo "$lt_cv_to_host_file_cmd" >&6; }
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to convert $build file names to toolchain format" >&5
+$as_echo_n "checking how to convert $build file names to toolchain format... " >&6; }
+if ${lt_cv_to_tool_file_cmd+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
+  #assume ordinary cross tools, or native build.
+lt_cv_to_tool_file_cmd=func_convert_file_noop
+case $host in
+  *-*-mingw* )
+    case $build in
+      *-*-mingw* ) # actually msys
+        lt_cv_to_tool_file_cmd=func_convert_file_msys_to_w32
+        ;;
+    esac
+    ;;
+esac
 
-ac_cv_lib_l_yywrap=no
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_l_yywrap" >&5
-echo "${ECHO_T}$ac_cv_lib_l_yywrap" >&6
-if test $ac_cv_lib_l_yywrap = yes; then
-  LEXLIB="-ll"
 fi
 
-fi
+to_tool_file_cmd=$lt_cv_to_tool_file_cmd
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_to_tool_file_cmd" >&5
+$as_echo "$lt_cv_to_tool_file_cmd" >&6; }
 
-fi
 
-if test "x$LEX" != "x:"; then
-  echo "$as_me:$LINENO: checking lex output file root" >&5
-echo $ECHO_N "checking lex output file root... $ECHO_C" >&6
-if test "${ac_cv_prog_lex_root+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  # The minimal lex program is just a single line: %%.  But some broken lexes
-# (Solaris, I think it was) want two %% lines, so accommodate them.
-cat >conftest.l <<_ACEOF
-%%
-%%
-_ACEOF
-{ (eval echo "$as_me:$LINENO: \"$LEX conftest.l\"") >&5
-  (eval $LEX conftest.l) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }
-if test -f lex.yy.c; then
-  ac_cv_prog_lex_root=lex.yy
-elif test -f lexyy.c; then
-  ac_cv_prog_lex_root=lexyy
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $LD option to reload object files" >&5
+$as_echo_n "checking for $LD option to reload object files... " >&6; }
+if ${lt_cv_ld_reload_flag+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
-  { { echo "$as_me:$LINENO: error: cannot find output from $LEX; giving up" >&5
-echo "$as_me: error: cannot find output from $LEX; giving up" >&2;}
-   { (exit 1); exit 1; }; }
+  lt_cv_ld_reload_flag='-r'
 fi
-fi
-echo "$as_me:$LINENO: result: $ac_cv_prog_lex_root" >&5
-echo "${ECHO_T}$ac_cv_prog_lex_root" >&6
-rm -f conftest.l
-LEX_OUTPUT_ROOT=$ac_cv_prog_lex_root
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ld_reload_flag" >&5
+$as_echo "$lt_cv_ld_reload_flag" >&6; }
+reload_flag=$lt_cv_ld_reload_flag
+case $reload_flag in
+"" | " "*) ;;
+*) reload_flag=" $reload_flag" ;;
+esac
+reload_cmds='$LD$reload_flag -o $output$reload_objs'
+case $host_os in
+  cygwin* | mingw* | pw32* | cegcc*)
+    if test "$GCC" != yes; then
+      reload_cmds=false
+    fi
+    ;;
+  darwin*)
+    if test "$GCC" = yes; then
+      reload_cmds='$LTCC $LTCFLAGS -nostdlib ${wl}-r -o $output$reload_objs'
+    else
+      reload_cmds='$LD$reload_flag -o $output$reload_objs'
+    fi
+    ;;
+esac
 
-echo "$as_me:$LINENO: checking whether yytext is a pointer" >&5
-echo $ECHO_N "checking whether yytext is a pointer... $ECHO_C" >&6
-if test "${ac_cv_prog_lex_yytext_pointer+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  # POSIX says lex can declare yytext either as a pointer or an array; the
-# default is implementation-dependent. Figure out which it is, since
-# not all implementations provide the %pointer and %array declarations.
-ac_cv_prog_lex_yytext_pointer=no
-echo 'extern char *yytext;' >>$LEX_OUTPUT_ROOT.c
-ac_save_LIBS=$LIBS
-LIBS="$LIBS $LEXLIB"
-cat >conftest.$ac_ext <<_ACEOF
-`cat $LEX_OUTPUT_ROOT.c`
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_prog_lex_yytext_pointer=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
 
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_save_LIBS
-rm -f "${LEX_OUTPUT_ROOT}.c"
 
-fi
-echo "$as_me:$LINENO: result: $ac_cv_prog_lex_yytext_pointer" >&5
-echo "${ECHO_T}$ac_cv_prog_lex_yytext_pointer" >&6
-if test $ac_cv_prog_lex_yytext_pointer = yes; then
 
-cat >>confdefs.h <<\_ACEOF
-#define YYTEXT_POINTER 1
-_ACEOF
 
-fi
 
-fi
-for ac_prog in 'bison -y' byacc
-do
-  # Extract the first word of "$ac_prog", so it can be a program name with args.
-set dummy $ac_prog; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
-if test "${ac_cv_prog_YACC+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+
+
+
+if test -n "$ac_tool_prefix"; then
+  # Extract the first word of "${ac_tool_prefix}objdump", so it can be a program name with args.
+set dummy ${ac_tool_prefix}objdump; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_OBJDUMP+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
-  if test -n "$YACC"; then
-  ac_cv_prog_YACC="$YACC" # Let the user override the test.
+  if test -n "$OBJDUMP"; then
+  ac_cv_prog_OBJDUMP="$OBJDUMP" # Let the user override the test.
 else
 as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
 for as_dir in $PATH
 do
   IFS=$as_save_IFS
   test -z "$as_dir" && as_dir=.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_YACC="$ac_prog"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_OBJDUMP="${ac_tool_prefix}objdump"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
-done
+  done
+IFS=$as_save_IFS
 
 fi
 fi
-YACC=$ac_cv_prog_YACC
-if test -n "$YACC"; then
-  echo "$as_me:$LINENO: result: $YACC" >&5
-echo "${ECHO_T}$YACC" >&6
+OBJDUMP=$ac_cv_prog_OBJDUMP
+if test -n "$OBJDUMP"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $OBJDUMP" >&5
+$as_echo "$OBJDUMP" >&6; }
 else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
 
-  test -n "$YACC" && break
-done
-test -n "$YACC" || YACC="yacc"
-
 
-  echo "$as_me:$LINENO: checking if compiler supports -R" >&5
-echo $ECHO_N "checking if compiler supports -R... $ECHO_C" >&6
-  if test "${php_cv_cc_dashr+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+fi
+if test -z "$ac_cv_prog_OBJDUMP"; then
+  ac_ct_OBJDUMP=$OBJDUMP
+  # Extract the first word of "objdump", so it can be a program name with args.
+set dummy objdump; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_ac_ct_OBJDUMP+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
-
-	SAVE_LIBS="${LIBS}"
-	LIBS="-R /usr/lib ${LIBS}"
-	cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  php_cv_cc_dashr=yes
+  if test -n "$ac_ct_OBJDUMP"; then
+  ac_cv_prog_ac_ct_OBJDUMP="$ac_ct_OBJDUMP" # Let the user override the test.
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_ac_ct_OBJDUMP="objdump"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
 
-php_cv_cc_dashr=no
 fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-	LIBS="${SAVE_LIBS}"
+fi
+ac_ct_OBJDUMP=$ac_cv_prog_ac_ct_OBJDUMP
+if test -n "$ac_ct_OBJDUMP"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_OBJDUMP" >&5
+$as_echo "$ac_ct_OBJDUMP" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
 
-  echo "$as_me:$LINENO: result: $php_cv_cc_dashr" >&5
-echo "${ECHO_T}$php_cv_cc_dashr" >&6
-  if test $php_cv_cc_dashr = "yes"; then
-	ld_runpath_switch="-R"
-	apxs_runpath_switch="-Wl,-R'"
+  if test "x$ac_ct_OBJDUMP" = x; then
+    OBJDUMP="false"
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
+$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
+ac_tool_warned=yes ;;
+esac
+    OBJDUMP=$ac_ct_OBJDUMP
   fi
-  if test -z "$ld_runpath_switch" ; then
-	echo "$as_me:$LINENO: checking if compiler supports -Wl,-rpath," >&5
-echo $ECHO_N "checking if compiler supports -Wl,-rpath,... $ECHO_C" >&6
-	if test "${php_cv_cc_rpath+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
 else
+  OBJDUMP="$ac_cv_prog_OBJDUMP"
+fi
 
-		SAVE_LIBS="${LIBS}"
-		LIBS="-Wl,-rpath,/usr/lib ${LIBS}"
-		cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
+test -z "$OBJDUMP" && OBJDUMP=objdump
 
-int
-main ()
-{
 
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  php_cv_cc_rpath=yes
+
+
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to recognize dependent libraries" >&5
+$as_echo_n "checking how to recognize dependent libraries... " >&6; }
+if ${lt_cv_deplibs_check_method+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
+  lt_cv_file_magic_cmd='$MAGIC_CMD'
+lt_cv_file_magic_test_file=
+lt_cv_deplibs_check_method='unknown'
+# Need to set the preceding variable on all platforms that support
+# interlibrary dependencies.
+# 'none' -- dependencies not supported.
+# `unknown' -- same as none, but documents that we really don't know.
+# 'pass_all' -- all dependencies passed with no checks.
+# 'test_compile' -- check by making test program.
+# 'file_magic [[regex]]' -- check by looking for files in library path
+# which responds to the $file_magic_cmd with a given extended regex.
+# If you have `file' or equivalent on your system and you're not sure
+# whether `pass_all' will *always* work, you probably want this one.
 
-php_cv_cc_rpath=no
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-		LIBS="${SAVE_LIBS}"
-fi
+case $host_os in
+aix[4-9]*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
 
-	echo "$as_me:$LINENO: result: $php_cv_cc_rpath" >&5
-echo "${ECHO_T}$php_cv_cc_rpath" >&6
-	if test $php_cv_cc_rpath = "yes"; then
-		ld_runpath_switch="-Wl,-rpath,"
-		apxs_runpath_switch="-Wl,'-rpath "
-	fi
+beos*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+bsdi[45]*)
+  lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (shared object|dynamic lib)'
+  lt_cv_file_magic_cmd='/usr/bin/file -L'
+  lt_cv_file_magic_test_file=/shlib/libc.so
+  ;;
+
+cygwin*)
+  # func_win32_libid is a shell function defined in ltmain.sh
+  lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL'
+  lt_cv_file_magic_cmd='func_win32_libid'
+  ;;
+
+mingw* | pw32*)
+  # Base MSYS/MinGW do not provide the 'file' command needed by
+  # func_win32_libid shell function, so use a weaker test based on 'objdump',
+  # unless we find 'file', for example because we are cross-compiling.
+  # func_win32_libid assumes BSD nm, so disallow it if using MS dumpbin.
+  if ( test "$lt_cv_nm_interface" = "BSD nm" && file / ) >/dev/null 2>&1; then
+    lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL'
+    lt_cv_file_magic_cmd='func_win32_libid'
+  else
+    # Keep this pattern in sync with the one in func_win32_libid.
+    lt_cv_deplibs_check_method='file_magic file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)'
+    lt_cv_file_magic_cmd='$OBJDUMP -f'
   fi
-  if test -z "$ld_runpath_switch" ; then
-	echo "$as_me:$LINENO: checking if compiler supports -Wl,-R" >&5
-echo $ECHO_N "checking if compiler supports -Wl,-R... $ECHO_C" >&6
-	if test "${php_cv_cc_dashwlr+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
+  ;;
 
-		SAVE_LIBS="${LIBS}"
-		LIBS="-Wl,-R/usr/lib ${LIBS}"
-		cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
+cegcc*)
+  # use the weaker test based on 'objdump'. See mingw*.
+  lt_cv_deplibs_check_method='file_magic file format pe-arm-.*little(.*architecture: arm)?'
+  lt_cv_file_magic_cmd='$OBJDUMP -f'
+  ;;
 
-int
-main ()
-{
+darwin* | rhapsody*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
 
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  php_cv_cc_dashwlr=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
+freebsd* | dragonfly*)
+  if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then
+    case $host_cpu in
+    i*86 )
+      # Not sure whether the presence of OpenBSD here was a mistake.
+      # Let's accept both of them until this is cleared up.
+      lt_cv_deplibs_check_method='file_magic (FreeBSD|OpenBSD|DragonFly)/i[3-9]86 (compact )?demand paged shared library'
+      lt_cv_file_magic_cmd=/usr/bin/file
+      lt_cv_file_magic_test_file=`echo /usr/lib/libc.so.*`
+      ;;
+    esac
+  else
+    lt_cv_deplibs_check_method=pass_all
+  fi
+  ;;
 
-php_cv_cc_dashwlr=no
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-		LIBS="${SAVE_LIBS}"
-fi
+gnu*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
 
-	echo "$as_me:$LINENO: result: $php_cv_cc_dashwlr" >&5
-echo "${ECHO_T}$php_cv_cc_dashwlr" >&6
-	if test $php_cv_cc_rpath = "yes"; then
-		ld_runpath_switch="-Wl,-R"
-		apxs_runpath_switch="-Wl,-R'"
-	fi
+haiku*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+hpux10.20* | hpux11*)
+  lt_cv_file_magic_cmd=/usr/bin/file
+  case $host_cpu in
+  ia64*)
+    lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF-[0-9][0-9]) shared object file - IA64'
+    lt_cv_file_magic_test_file=/usr/lib/hpux32/libc.so
+    ;;
+  hppa*64*)
+    lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF[ -][0-9][0-9])(-bit)?( [LM]SB)? shared object( file)?[, -]* PA-RISC [0-9]\.[0-9]'
+    lt_cv_file_magic_test_file=/usr/lib/pa20_64/libc.sl
+    ;;
+  *)
+    lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|PA-RISC[0-9]\.[0-9]) shared library'
+    lt_cv_file_magic_test_file=/usr/lib/libc.sl
+    ;;
+  esac
+  ;;
+
+interix[3-9]*)
+  # PIC code is broken on Interix 3.x, that's why |\.a not |_pic\.a here
+  lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so|\.a)$'
+  ;;
+
+irix5* | irix6* | nonstopux*)
+  case $LD in
+  *-32|*"-32 ") libmagic=32-bit;;
+  *-n32|*"-n32 ") libmagic=N32;;
+  *-64|*"-64 ") libmagic=64-bit;;
+  *) libmagic=never-match;;
+  esac
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+# This must be glibc/ELF.
+linux* | k*bsd*-gnu | kopensolaris*-gnu)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+netbsd* | netbsdelf*-gnu)
+  if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then
+    lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|_pic\.a)$'
+  else
+    lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so|_pic\.a)$'
   fi
-  if test -z "$ld_runpath_switch" ; then
-		ld_runpath_switch="-L"
-	apxs_runpath_switch="-L'"
+  ;;
+
+newos6*)
+  lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (executable|dynamic lib)'
+  lt_cv_file_magic_cmd=/usr/bin/file
+  lt_cv_file_magic_test_file=/usr/lib/libnls.so
+  ;;
+
+*nto* | *qnx*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+openbsd*)
+  if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+    lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|\.so|_pic\.a)$'
+  else
+    lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|_pic\.a)$'
   fi
+  ;;
 
+osf3* | osf4* | osf5*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
 
+rdos*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
 
-echo "$as_me:$LINENO: checking for exp in -lm" >&5
-echo $ECHO_N "checking for exp in -lm... $ECHO_C" >&6
-if test "${ac_cv_lib_m_exp+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-lm  $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
+solaris*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
 
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char exp ();
-int
-main ()
-{
-exp ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_m_exp=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
+sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+sysv4 | sysv4.3*)
+  case $host_vendor in
+  motorola)
+    lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (shared object|dynamic lib) M[0-9][0-9]* Version [0-9]'
+    lt_cv_file_magic_test_file=`echo /usr/lib/libc.so*`
+    ;;
+  ncr)
+    lt_cv_deplibs_check_method=pass_all
+    ;;
+  sequent)
+    lt_cv_file_magic_cmd='/bin/file'
+    lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [LM]SB (shared object|dynamic lib )'
+    ;;
+  sni)
+    lt_cv_file_magic_cmd='/bin/file'
+    lt_cv_deplibs_check_method="file_magic ELF [0-9][0-9]*-bit [LM]SB dynamic lib"
+    lt_cv_file_magic_test_file=/lib/libc.so
+    ;;
+  siemens)
+    lt_cv_deplibs_check_method=pass_all
+    ;;
+  pc)
+    lt_cv_deplibs_check_method=pass_all
+    ;;
+  esac
+  ;;
+
+tpf*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+esac
 
-ac_cv_lib_m_exp=no
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
 fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_m_exp" >&5
-echo "${ECHO_T}$ac_cv_lib_m_exp" >&6
-if test $ac_cv_lib_m_exp = yes; then
-  XTRALIBS="$XTRALIBS -lm"
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_deplibs_check_method" >&5
+$as_echo "$lt_cv_deplibs_check_method" >&6; }
+
+file_magic_glob=
+want_nocaseglob=no
+if test "$build" = "$host"; then
+  case $host_os in
+  mingw* | pw32*)
+    if ( shopt | grep nocaseglob ) >/dev/null 2>&1; then
+      want_nocaseglob=yes
+    else
+      file_magic_glob=`echo aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ | $SED -e "s/\(..\)/s\/[\1]\/[\1]\/g;/g"`
+    fi
+    ;;
+  esac
 fi
 
-XTRALIBS=$XTRALIBS
+file_magic_cmd=$lt_cv_file_magic_cmd
+deplibs_check_method=$lt_cv_deplibs_check_method
+test -z "$deplibs_check_method" && deplibs_check_method=unknown
 
 
-echo "$as_me:$LINENO: checking for __gxx_personality_v0 in -lstdc++" >&5
-echo $ECHO_N "checking for __gxx_personality_v0 in -lstdc++... $ECHO_C" >&6
-if test "${ac_cv_lib_stdcpp___gxx_personality_v0+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-lstdc++  $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
 
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char __gxx_personality_v0 ();
-int
-main ()
-{
-__gxx_personality_v0 ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_stdcpp___gxx_personality_v0=yes
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+if test -n "$ac_tool_prefix"; then
+  # Extract the first word of "${ac_tool_prefix}dlltool", so it can be a program name with args.
+set dummy ${ac_tool_prefix}dlltool; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_DLLTOOL+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
+  if test -n "$DLLTOOL"; then
+  ac_cv_prog_DLLTOOL="$DLLTOOL" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_DLLTOOL="${ac_tool_prefix}dlltool"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
 
-ac_cv_lib_stdcpp___gxx_personality_v0=no
 fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
 fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_stdcpp___gxx_personality_v0" >&5
-echo "${ECHO_T}$ac_cv_lib_stdcpp___gxx_personality_v0" >&6
-if test $ac_cv_lib_stdcpp___gxx_personality_v0 = yes; then
-  XTRALIBS="$XTRALIBS -lstdc++"
+DLLTOOL=$ac_cv_prog_DLLTOOL
+if test -n "$DLLTOOL"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DLLTOOL" >&5
+$as_echo "$DLLTOOL" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
 
-XTRALIBS=$XTRALIBS
-
-
-LIBS="$XTRALIBS $LIBS"
 
-ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-echo "$as_me:$LINENO: checking how to run the C preprocessor" >&5
-echo $ECHO_N "checking how to run the C preprocessor... $ECHO_C" >&6
-# On Suns, sometimes $CPP names a directory.
-if test -n "$CPP" && test -d "$CPP"; then
-  CPP=
 fi
-if test -z "$CPP"; then
-  if test "${ac_cv_prog_CPP+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+if test -z "$ac_cv_prog_DLLTOOL"; then
+  ac_ct_DLLTOOL=$DLLTOOL
+  # Extract the first word of "dlltool", so it can be a program name with args.
+set dummy dlltool; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_ac_ct_DLLTOOL+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
-      # Double quotes because CPP needs to be expanded
-    for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp"
-    do
-      ac_preproc_ok=false
-for ac_c_preproc_warn_flag in '' yes
+  if test -n "$ac_ct_DLLTOOL"; then
+  ac_cv_prog_ac_ct_DLLTOOL="$ac_ct_DLLTOOL" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
 do
-  # Use a header file that comes with gcc, so configuring glibc
-  # with a fresh cross-compiler works.
-  # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-  # <limits.h> exists even on freestanding compilers.
-  # On the NeXT, cc -E runs the code through the compiler's parser,
-  # not just through cpp. "Syntax error" is here to catch this case.
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-		     Syntax error
-_ACEOF
-if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5
-  (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } >/dev/null; then
-  if test -s conftest.err; then
-    ac_cpp_err=$ac_c_preproc_warn_flag
-    ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
-  else
-    ac_cpp_err=
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_ac_ct_DLLTOOL="dlltool"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
   fi
-else
-  ac_cpp_err=yes
+done
+  done
+IFS=$as_save_IFS
+
 fi
-if test -z "$ac_cpp_err"; then
-  :
+fi
+ac_ct_DLLTOOL=$ac_cv_prog_ac_ct_DLLTOOL
+if test -n "$ac_ct_DLLTOOL"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_DLLTOOL" >&5
+$as_echo "$ac_ct_DLLTOOL" >&6; }
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-  # Broken: fails on valid input.
-continue
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
-rm -f conftest.err conftest.$ac_ext
 
-  # OK, works on sane cases.  Now check whether non-existent headers
-  # can be detected and how.
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#include <ac_nonexistent.h>
-_ACEOF
-if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5
-  (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } >/dev/null; then
-  if test -s conftest.err; then
-    ac_cpp_err=$ac_c_preproc_warn_flag
-    ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
+  if test "x$ac_ct_DLLTOOL" = x; then
+    DLLTOOL="false"
   else
-    ac_cpp_err=
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
+$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
+ac_tool_warned=yes ;;
+esac
+    DLLTOOL=$ac_ct_DLLTOOL
   fi
 else
-  ac_cpp_err=yes
+  DLLTOOL="$ac_cv_prog_DLLTOOL"
 fi
-if test -z "$ac_cpp_err"; then
-  # Broken: success on invalid input.
-continue
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
 
-  # Passes both tests.
-ac_preproc_ok=:
-break
+test -z "$DLLTOOL" && DLLTOOL=dlltool
+
+
+
+
+
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to associate runtime and link libraries" >&5
+$as_echo_n "checking how to associate runtime and link libraries... " >&6; }
+if ${lt_cv_sharedlib_from_linklib_cmd+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  lt_cv_sharedlib_from_linklib_cmd='unknown'
+
+case $host_os in
+cygwin* | mingw* | pw32* | cegcc*)
+  # two different shell functions defined in ltmain.sh
+  # decide which to use based on capabilities of $DLLTOOL
+  case `$DLLTOOL --help 2>&1` in
+  *--identify-strict*)
+    lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib
+    ;;
+  *)
+    lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib_fallback
+    ;;
+  esac
+  ;;
+*)
+  # fallback: assume linklib IS sharedlib
+  lt_cv_sharedlib_from_linklib_cmd="$ECHO"
+  ;;
+esac
+
 fi
-rm -f conftest.err conftest.$ac_ext
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_sharedlib_from_linklib_cmd" >&5
+$as_echo "$lt_cv_sharedlib_from_linklib_cmd" >&6; }
+sharedlib_from_linklib_cmd=$lt_cv_sharedlib_from_linklib_cmd
+test -z "$sharedlib_from_linklib_cmd" && sharedlib_from_linklib_cmd=$ECHO
+
+
+
+
+
+
+
 
+if test -n "$ac_tool_prefix"; then
+  for ac_prog in ar
+  do
+    # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args.
+set dummy $ac_tool_prefix$ac_prog; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_AR+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$AR"; then
+  ac_cv_prog_AR="$AR" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_AR="$ac_tool_prefix$ac_prog"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
 done
-# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
-rm -f conftest.err conftest.$ac_ext
-if $ac_preproc_ok; then
-  break
+  done
+IFS=$as_save_IFS
+
+fi
+fi
+AR=$ac_cv_prog_AR
+if test -n "$AR"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $AR" >&5
+$as_echo "$AR" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
 
-    done
-    ac_cv_prog_CPP=$CPP
 
+    test -n "$AR" && break
+  done
 fi
-  CPP=$ac_cv_prog_CPP
+if test -z "$AR"; then
+  ac_ct_AR=$AR
+  for ac_prog in ar
+do
+  # Extract the first word of "$ac_prog", so it can be a program name with args.
+set dummy $ac_prog; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_ac_ct_AR+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
-  ac_cv_prog_CPP=$CPP
-fi
-echo "$as_me:$LINENO: result: $CPP" >&5
-echo "${ECHO_T}$CPP" >&6
-ac_preproc_ok=false
-for ac_c_preproc_warn_flag in '' yes
+  if test -n "$ac_ct_AR"; then
+  ac_cv_prog_ac_ct_AR="$ac_ct_AR" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
 do
-  # Use a header file that comes with gcc, so configuring glibc
-  # with a fresh cross-compiler works.
-  # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-  # <limits.h> exists even on freestanding compilers.
-  # On the NeXT, cc -E runs the code through the compiler's parser,
-  # not just through cpp. "Syntax error" is here to catch this case.
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-		     Syntax error
-_ACEOF
-if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5
-  (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } >/dev/null; then
-  if test -s conftest.err; then
-    ac_cpp_err=$ac_c_preproc_warn_flag
-    ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
-  else
-    ac_cpp_err=
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_ac_ct_AR="$ac_prog"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
   fi
-else
-  ac_cpp_err=yes
+done
+  done
+IFS=$as_save_IFS
+
 fi
-if test -z "$ac_cpp_err"; then
-  :
+fi
+ac_ct_AR=$ac_cv_prog_ac_ct_AR
+if test -n "$ac_ct_AR"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_AR" >&5
+$as_echo "$ac_ct_AR" >&6; }
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-  # Broken: fails on valid input.
-continue
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
-rm -f conftest.err conftest.$ac_ext
 
-  # OK, works on sane cases.  Now check whether non-existent headers
-  # can be detected and how.
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#include <ac_nonexistent.h>
-_ACEOF
-if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5
-  (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } >/dev/null; then
-  if test -s conftest.err; then
-    ac_cpp_err=$ac_c_preproc_warn_flag
-    ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
+
+  test -n "$ac_ct_AR" && break
+done
+
+  if test "x$ac_ct_AR" = x; then
+    AR="false"
   else
-    ac_cpp_err=
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
+$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
+ac_tool_warned=yes ;;
+esac
+    AR=$ac_ct_AR
   fi
-else
-  ac_cpp_err=yes
 fi
-if test -z "$ac_cpp_err"; then
-  # Broken: success on invalid input.
-continue
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
 
-  # Passes both tests.
-ac_preproc_ok=:
-break
-fi
-rm -f conftest.err conftest.$ac_ext
+: ${AR=ar}
+: ${AR_FLAGS=cru}
+
+
+
+
 
-done
-# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
-rm -f conftest.err conftest.$ac_ext
-if $ac_preproc_ok; then
-  :
-else
-  { { echo "$as_me:$LINENO: error: C preprocessor \"$CPP\" fails sanity check
-See \`config.log' for more details." >&5
-echo "$as_me: error: C preprocessor \"$CPP\" fails sanity check
-See \`config.log' for more details." >&2;}
-   { (exit 1); exit 1; }; }
-fi
 
-ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
 
-echo "$as_me:$LINENO: checking for egrep" >&5
-echo $ECHO_N "checking for egrep... $ECHO_C" >&6
-if test "${ac_cv_prog_egrep+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  if echo a | (grep -E '(a|b)') >/dev/null 2>&1
-    then ac_cv_prog_egrep='grep -E'
-    else ac_cv_prog_egrep='egrep'
-    fi
-fi
-echo "$as_me:$LINENO: result: $ac_cv_prog_egrep" >&5
-echo "${ECHO_T}$ac_cv_prog_egrep" >&6
- EGREP=$ac_cv_prog_egrep
 
 
-echo "$as_me:$LINENO: checking for ANSI C header files" >&5
-echo $ECHO_N "checking for ANSI C header files... $ECHO_C" >&6
-if test "${ac_cv_header_stdc+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for archiver @FILE support" >&5
+$as_echo_n "checking for archiver @FILE support... " >&6; }
+if ${lt_cv_ar_at_file+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+  lt_cv_ar_at_file=no
+   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
-#include <stdlib.h>
-#include <stdarg.h>
-#include <string.h>
-#include <float.h>
 
 int
 main ()
@@ -3711,6225 +5094,13082 @@ main ()
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest.$ac_objext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_header_stdc=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
+if ac_fn_c_try_compile "$LINENO"; then :
+  echo conftest.$ac_objext > conftest.lst
+      lt_ar_try='$AR $AR_FLAGS libconftest.a @conftest.lst >&5'
+      { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$lt_ar_try\""; } >&5
+  (eval $lt_ar_try) 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }
+      if test "$ac_status" -eq 0; then
+	# Ensure the archiver fails upon bogus file names.
+	rm -f conftest.$ac_objext libconftest.a
+	{ { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$lt_ar_try\""; } >&5
+  (eval $lt_ar_try) 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }
+	if test "$ac_status" -ne 0; then
+          lt_cv_ar_at_file=@
+        fi
+      fi
+      rm -f conftest.* libconftest.a
 
-ac_cv_header_stdc=no
 fi
-rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
 
-if test $ac_cv_header_stdc = yes; then
-  # SunOS 4.x string.h does not declare mem*, contrary to ANSI.
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#include <string.h>
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ar_at_file" >&5
+$as_echo "$lt_cv_ar_at_file" >&6; }
 
-_ACEOF
-if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
-  $EGREP "memchr" >/dev/null 2>&1; then
-  :
+if test "x$lt_cv_ar_at_file" = xno; then
+  archiver_list_spec=
 else
-  ac_cv_header_stdc=no
+  archiver_list_spec=$lt_cv_ar_at_file
 fi
-rm -f conftest*
 
-fi
 
-if test $ac_cv_header_stdc = yes; then
-  # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI.
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#include <stdlib.h>
 
-_ACEOF
-if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
-  $EGREP "free" >/dev/null 2>&1; then
-  :
-else
-  ac_cv_header_stdc=no
-fi
-rm -f conftest*
 
-fi
 
-if test $ac_cv_header_stdc = yes; then
-  # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi.
-  if test "$cross_compiling" = yes; then
-  :
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#include <ctype.h>
-#if ((' ' & 0x0FF) == 0x020)
-# define ISLOWER(c) ('a' <= (c) && (c) <= 'z')
-# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c))
-#else
-# define ISLOWER(c) \
-		   (('a' <= (c) && (c) <= 'i') \
-		     || ('j' <= (c) && (c) <= 'r') \
-		     || ('s' <= (c) && (c) <= 'z'))
-# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c))
-#endif
 
-#define XOR(e, f) (((e) && !(f)) || (!(e) && (f)))
-int
-main ()
-{
-  int i;
-  for (i = 0; i < 256; i++)
-    if (XOR (islower (i), ISLOWER (i))
-	|| toupper (i) != TOUPPER (i))
-      exit(2);
-  exit (0);
-}
-_ACEOF
-rm -f conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && { ac_try='./conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  :
+
+if test -n "$ac_tool_prefix"; then
+  # Extract the first word of "${ac_tool_prefix}strip", so it can be a program name with args.
+set dummy ${ac_tool_prefix}strip; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_STRIP+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
-  echo "$as_me: program exited with status $ac_status" >&5
-echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
+  if test -n "$STRIP"; then
+  ac_cv_prog_STRIP="$STRIP" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_STRIP="${ac_tool_prefix}strip"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
 
-( exit $ac_status )
-ac_cv_header_stdc=no
 fi
-rm -f core *.core gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext
 fi
+STRIP=$ac_cv_prog_STRIP
+if test -n "$STRIP"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $STRIP" >&5
+$as_echo "$STRIP" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
+
+
 fi
-echo "$as_me:$LINENO: result: $ac_cv_header_stdc" >&5
-echo "${ECHO_T}$ac_cv_header_stdc" >&6
-if test $ac_cv_header_stdc = yes; then
+if test -z "$ac_cv_prog_STRIP"; then
+  ac_ct_STRIP=$STRIP
+  # Extract the first word of "strip", so it can be a program name with args.
+set dummy strip; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_ac_ct_STRIP+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$ac_ct_STRIP"; then
+  ac_cv_prog_ac_ct_STRIP="$ac_ct_STRIP" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_ac_ct_STRIP="strip"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
 
-cat >>confdefs.h <<\_ACEOF
-#define STDC_HEADERS 1
-_ACEOF
+fi
+fi
+ac_ct_STRIP=$ac_cv_prog_ac_ct_STRIP
+if test -n "$ac_ct_STRIP"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_STRIP" >&5
+$as_echo "$ac_ct_STRIP" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
 
+  if test "x$ac_ct_STRIP" = x; then
+    STRIP=":"
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
+$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
+ac_tool_warned=yes ;;
+esac
+    STRIP=$ac_ct_STRIP
+  fi
+else
+  STRIP="$ac_cv_prog_STRIP"
 fi
 
+test -z "$STRIP" && STRIP=:
 
 
-	echo 'void f(){}' > conftest.c
-	if test -z "`${CC} -fPIC -c conftest.c 2>&1`"; then
-	  C_PIC=-fPIC
-	else
-	  C_PIC=
-	fi
-	rm -f conftest*
 
-	C_PIC=$C_PIC
 
 
-CFLAGS="$CFLAGS $C_PIC"
-CXXFLAGS="$CXXFLAGS $C_PIC"
 
-echo "$as_me:$LINENO: checking for strcasecmp" >&5
-echo $ECHO_N "checking for strcasecmp... $ECHO_C" >&6
-if test "${ac_cv_func_strcasecmp+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+if test -n "$ac_tool_prefix"; then
+  # Extract the first word of "${ac_tool_prefix}ranlib", so it can be a program name with args.
+set dummy ${ac_tool_prefix}ranlib; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_RANLIB+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define strcasecmp to an innocuous variant, in case <limits.h> declares strcasecmp.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define strcasecmp innocuous_strcasecmp
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char strcasecmp (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
+  if test -n "$RANLIB"; then
+  ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_RANLIB="${ac_tool_prefix}ranlib"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
 
-#undef strcasecmp
+fi
+fi
+RANLIB=$ac_cv_prog_RANLIB
+if test -n "$RANLIB"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $RANLIB" >&5
+$as_echo "$RANLIB" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
 
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-{
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char strcasecmp ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined (__stub_strcasecmp) || defined (__stub___strcasecmp)
-choke me
-#else
-char (*f) () = strcasecmp;
-#endif
-#ifdef __cplusplus
-}
-#endif
 
-int
-main ()
-{
-return f != strcasecmp;
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_func_strcasecmp=yes
+fi
+if test -z "$ac_cv_prog_RANLIB"; then
+  ac_ct_RANLIB=$RANLIB
+  # Extract the first word of "ranlib", so it can be a program name with args.
+set dummy ranlib; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_ac_ct_RANLIB+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
+  if test -n "$ac_ct_RANLIB"; then
+  ac_cv_prog_ac_ct_RANLIB="$ac_ct_RANLIB" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_ac_ct_RANLIB="ranlib"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
 
-ac_cv_func_strcasecmp=no
 fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
 fi
-echo "$as_me:$LINENO: result: $ac_cv_func_strcasecmp" >&5
-echo "${ECHO_T}$ac_cv_func_strcasecmp" >&6
-if test $ac_cv_func_strcasecmp = yes; then
-  :
+ac_ct_RANLIB=$ac_cv_prog_ac_ct_RANLIB
+if test -n "$ac_ct_RANLIB"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_RANLIB" >&5
+$as_echo "$ac_ct_RANLIB" >&6; }
 else
-  STRINGS="-DNEED_STRCASECMP $STRINGS"
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
 
-echo "$as_me:$LINENO: checking for strncasecmp" >&5
-echo $ECHO_N "checking for strncasecmp... $ECHO_C" >&6
-if test "${ac_cv_func_strncasecmp+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+  if test "x$ac_ct_RANLIB" = x; then
+    RANLIB=":"
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
+$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
+ac_tool_warned=yes ;;
+esac
+    RANLIB=$ac_ct_RANLIB
+  fi
 else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define strncasecmp to an innocuous variant, in case <limits.h> declares strncasecmp.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define strncasecmp innocuous_strncasecmp
+  RANLIB="$ac_cv_prog_RANLIB"
+fi
 
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char strncasecmp (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
+test -z "$RANLIB" && RANLIB=:
 
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
 
-#undef strncasecmp
 
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-{
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char strncasecmp ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined (__stub_strncasecmp) || defined (__stub___strncasecmp)
-choke me
-#else
-char (*f) () = strncasecmp;
-#endif
-#ifdef __cplusplus
-}
-#endif
 
-int
-main ()
-{
-return f != strncasecmp;
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_func_strncasecmp=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
 
-ac_cv_func_strncasecmp=no
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-echo "$as_me:$LINENO: result: $ac_cv_func_strncasecmp" >&5
-echo "${ECHO_T}$ac_cv_func_strncasecmp" >&6
-if test $ac_cv_func_strncasecmp = yes; then
-  :
-else
-  STRINGS="-DNEED_STRNCASECMP $STRINGS"
+
+# Determine commands to create old-style static archives.
+old_archive_cmds='$AR $AR_FLAGS $oldlib$oldobjs'
+old_postinstall_cmds='chmod 644 $oldlib'
+old_postuninstall_cmds=
+
+if test -n "$RANLIB"; then
+  case $host_os in
+  openbsd*)
+    old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB -t \$tool_oldlib"
+    ;;
+  *)
+    old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB \$tool_oldlib"
+    ;;
+  esac
+  old_archive_cmds="$old_archive_cmds~\$RANLIB \$tool_oldlib"
 fi
 
-echo "$as_me:$LINENO: checking for strdup" >&5
-echo $ECHO_N "checking for strdup... $ECHO_C" >&6
-if test "${ac_cv_func_strdup+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define strdup to an innocuous variant, in case <limits.h> declares strdup.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define strdup innocuous_strdup
+case $host_os in
+  darwin*)
+    lock_old_archive_extraction=yes ;;
+  *)
+    lock_old_archive_extraction=no ;;
+esac
 
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char strdup (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
 
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
 
-#undef strdup
 
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-{
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char strdup ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined (__stub_strdup) || defined (__stub___strdup)
-choke me
-#else
-char (*f) () = strdup;
-#endif
-#ifdef __cplusplus
-}
-#endif
 
-int
-main ()
-{
-return f != strdup;
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_func_strdup=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
 
-ac_cv_func_strdup=no
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-echo "$as_me:$LINENO: result: $ac_cv_func_strdup" >&5
-echo "${ECHO_T}$ac_cv_func_strdup" >&6
-if test $ac_cv_func_strdup = yes; then
-  :
-else
-  STRINGS="-DNEED_STRDUP $STRINGS"
-fi
 
-echo "$as_me:$LINENO: checking for strrstr" >&5
-echo $ECHO_N "checking for strrstr... $ECHO_C" >&6
-if test "${ac_cv_func_strrstr+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define strrstr to an innocuous variant, in case <limits.h> declares strrstr.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define strrstr innocuous_strrstr
 
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char strrstr (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
 
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
 
-#undef strrstr
 
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-{
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char strrstr ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined (__stub_strrstr) || defined (__stub___strrstr)
-choke me
-#else
-char (*f) () = strrstr;
-#endif
-#ifdef __cplusplus
-}
-#endif
 
-int
-main ()
-{
-return f != strrstr;
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_func_strrstr=yes
+
+
+
+
+
+
+
+
+
+for ac_prog in gawk mawk nawk awk
+do
+  # Extract the first word of "$ac_prog", so it can be a program name with args.
+set dummy $ac_prog; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_AWK+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
+  if test -n "$AWK"; then
+  ac_cv_prog_AWK="$AWK" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_AWK="$ac_prog"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
 
-ac_cv_func_strrstr=no
 fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
 fi
-echo "$as_me:$LINENO: result: $ac_cv_func_strrstr" >&5
-echo "${ECHO_T}$ac_cv_func_strrstr" >&6
-if test $ac_cv_func_strrstr = yes; then
-  :
+AWK=$ac_cv_prog_AWK
+if test -n "$AWK"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $AWK" >&5
+$as_echo "$AWK" >&6; }
 else
-  STRINGS="-DNEED_STRRSTR $STRINGS"
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
 
-echo "$as_me:$LINENO: checking for strcasestr" >&5
-echo $ECHO_N "checking for strcasestr... $ECHO_C" >&6
-if test "${ac_cv_func_strcasestr+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define strcasestr to an innocuous variant, in case <limits.h> declares strcasestr.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define strcasestr innocuous_strcasestr
 
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char strcasestr (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
+  test -n "$AWK" && break
+done
+
+
 
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
 
-#undef strcasestr
 
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-{
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char strcasestr ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined (__stub_strcasestr) || defined (__stub___strcasestr)
-choke me
-#else
-char (*f) () = strcasestr;
-#endif
-#ifdef __cplusplus
-}
-#endif
 
-int
-main ()
-{
-return f != strcasestr;
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_func_strcasestr=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
 
-ac_cv_func_strcasestr=no
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-echo "$as_me:$LINENO: result: $ac_cv_func_strcasestr" >&5
-echo "${ECHO_T}$ac_cv_func_strcasestr" >&6
-if test $ac_cv_func_strcasestr = yes; then
-  :
-else
-  STRINGS="-DNEED_STRCASESTR $STRINGS"
-fi
 
-echo "$as_me:$LINENO: checking for strlcat" >&5
-echo $ECHO_N "checking for strlcat... $ECHO_C" >&6
-if test "${ac_cv_func_strlcat+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define strlcat to an innocuous variant, in case <limits.h> declares strlcat.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define strlcat innocuous_strlcat
 
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char strlcat (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
 
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
 
-#undef strlcat
 
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-{
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char strlcat ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined (__stub_strlcat) || defined (__stub___strlcat)
-choke me
-#else
-char (*f) () = strlcat;
-#endif
-#ifdef __cplusplus
-}
-#endif
 
-int
-main ()
-{
-return f != strlcat;
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_func_strlcat=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
 
-ac_cv_func_strlcat=no
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-echo "$as_me:$LINENO: result: $ac_cv_func_strlcat" >&5
-echo "${ECHO_T}$ac_cv_func_strlcat" >&6
-if test $ac_cv_func_strlcat = yes; then
-  :
-else
-  STRINGS="-DNEED_STRLCAT $STRINGS"
-fi
 
-echo "$as_me:$LINENO: checking for strlcpy" >&5
-echo $ECHO_N "checking for strlcpy... $ECHO_C" >&6
-if test "${ac_cv_func_strlcpy+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+
+
+
+
+# If no C compiler was specified, use CC.
+LTCC=${LTCC-"$CC"}
+
+# If no C compiler flags were specified, use CFLAGS.
+LTCFLAGS=${LTCFLAGS-"$CFLAGS"}
+
+# Allow CC to be a program name with arguments.
+compiler=$CC
+
+
+# Check for command to grab the raw symbol name followed by C symbol from nm.
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking command to parse $NM output from $compiler object" >&5
+$as_echo_n "checking command to parse $NM output from $compiler object... " >&6; }
+if ${lt_cv_sys_global_symbol_pipe+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define strlcpy to an innocuous variant, in case <limits.h> declares strlcpy.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define strlcpy innocuous_strlcpy
 
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char strlcpy (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
+# These are sane defaults that work on at least a few old systems.
+# [They come from Ultrix.  What could be older than Ultrix?!! ;)]
 
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
+# Character class describing NM global symbol codes.
+symcode='[BCDEGRST]'
+
+# Regexp to match symbols that can be accessed directly from C.
+sympat='\([_A-Za-z][_A-Za-z0-9]*\)'
+
+# Define system-specific variables.
+case $host_os in
+aix*)
+  symcode='[BCDT]'
+  ;;
+cygwin* | mingw* | pw32* | cegcc*)
+  symcode='[ABCDGISTW]'
+  ;;
+hpux*)
+  if test "$host_cpu" = ia64; then
+    symcode='[ABCDEGRST]'
+  fi
+  ;;
+irix* | nonstopux*)
+  symcode='[BCDEGRST]'
+  ;;
+osf*)
+  symcode='[BCDEGQRST]'
+  ;;
+solaris*)
+  symcode='[BDRT]'
+  ;;
+sco3.2v5*)
+  symcode='[DT]'
+  ;;
+sysv4.2uw2*)
+  symcode='[DT]'
+  ;;
+sysv5* | sco5v6* | unixware* | OpenUNIX*)
+  symcode='[ABDT]'
+  ;;
+sysv4)
+  symcode='[DFNSTU]'
+  ;;
+esac
+
+# If we're using GNU nm, then use its standard symbol codes.
+case `$NM -V 2>&1` in
+*GNU* | *'with BFD'*)
+  symcode='[ABCDGIRSTW]' ;;
+esac
+
+# Transform an extracted symbol line into a proper C declaration.
+# Some systems (esp. on ia64) link data and code symbols differently,
+# so use this general approach.
+lt_cv_sys_global_symbol_to_cdecl="sed -n -e 's/^T .* \(.*\)$/extern int \1();/p' -e 's/^$symcode* .* \(.*\)$/extern char \1;/p'"
+
+# Transform an extracted symbol line into symbol name and symbol address
+lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([^ ]*\)[ ]*$/  {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([^ ]*\) \([^ ]*\)$/  {\"\2\", (void *) \&\2},/p'"
+lt_cv_sys_global_symbol_to_c_name_address_lib_prefix="sed -n -e 's/^: \([^ ]*\)[ ]*$/  {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([^ ]*\) \(lib[^ ]*\)$/  {\"\2\", (void *) \&\2},/p' -e 's/^$symcode* \([^ ]*\) \([^ ]*\)$/  {\"lib\2\", (void *) \&\2},/p'"
+
+# Handle CRLF in mingw tool chain
+opt_cr=
+case $build_os in
+mingw*)
+  opt_cr=`$ECHO 'x\{0,1\}' | tr x '\015'` # option cr in regexp
+  ;;
+esac
 
-#undef strlcpy
+# Try without a prefix underscore, then with it.
+for ac_symprfx in "" "_"; do
+
+  # Transform symcode, sympat, and symprfx into a raw symbol and a C symbol.
+  symxfrm="\\1 $ac_symprfx\\2 \\2"
+
+  # Write the raw and C identifiers.
+  if test "$lt_cv_nm_interface" = "MS dumpbin"; then
+    # Fake it for dumpbin and say T for any non-static function
+    # and D for any global variable.
+    # Also find C++ and __fastcall symbols from MSVC++,
+    # which start with @ or ?.
+    lt_cv_sys_global_symbol_pipe="$AWK '"\
+"     {last_section=section; section=\$ 3};"\
+"     /^COFF SYMBOL TABLE/{for(i in hide) delete hide[i]};"\
+"     /Section length .*#relocs.*(pick any)/{hide[last_section]=1};"\
+"     \$ 0!~/External *\|/{next};"\
+"     / 0+ UNDEF /{next}; / UNDEF \([^|]\)*()/{next};"\
+"     {if(hide[section]) next};"\
+"     {f=0}; \$ 0~/\(\).*\|/{f=1}; {printf f ? \"T \" : \"D \"};"\
+"     {split(\$ 0, a, /\||\r/); split(a[2], s)};"\
+"     s[1]~/^[@?]/{print s[1], s[1]; next};"\
+"     s[1]~prfx {split(s[1],t,\"@\"); print t[1], substr(t[1],length(prfx))}"\
+"     ' prfx=^$ac_symprfx"
+  else
+    lt_cv_sys_global_symbol_pipe="sed -n -e 's/^.*[	 ]\($symcode$symcode*\)[	 ][	 ]*$ac_symprfx$sympat$opt_cr$/$symxfrm/p'"
+  fi
+  lt_cv_sys_global_symbol_pipe="$lt_cv_sys_global_symbol_pipe | sed '/ __gnu_lto/d'"
 
-/* Override any gcc2 internal prototype to avoid an error.  */
+  # Check to see that the pipe works correctly.
+  pipe_works=no
+
+  rm -f conftest*
+  cat > conftest.$ac_ext <<_LT_EOF
 #ifdef __cplusplus
-extern "C"
-{
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char strlcpy ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined (__stub_strlcpy) || defined (__stub___strlcpy)
-choke me
-#else
-char (*f) () = strlcpy;
+extern "C" {
 #endif
+char nm_test_var;
+void nm_test_func(void);
+void nm_test_func(void){}
 #ifdef __cplusplus
 }
 #endif
+int main(){nm_test_var='a';nm_test_func();return(0);}
+_LT_EOF
 
-int
-main ()
-{
-return f != strlcpy;
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
+  if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5
+  (eval $ac_compile) 2>&5
   ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_func_strlcpy=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-ac_cv_func_strlcpy=no
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-echo "$as_me:$LINENO: result: $ac_cv_func_strlcpy" >&5
-echo "${ECHO_T}$ac_cv_func_strlcpy" >&6
-if test $ac_cv_func_strlcpy = yes; then
-  :
-else
-  STRINGS="-DNEED_STRLCPY $STRINGS"
-fi
-
-echo "$as_me:$LINENO: checking for vsnprintf" >&5
-echo $ECHO_N "checking for vsnprintf... $ECHO_C" >&6
-if test "${ac_cv_func_vsnprintf+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define vsnprintf to an innocuous variant, in case <limits.h> declares vsnprintf.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define vsnprintf innocuous_vsnprintf
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char vsnprintf (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; then
+    # Now try to grab the symbols.
+    nlist=conftest.nm
+    if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$NM conftest.$ac_objext \| "$lt_cv_sys_global_symbol_pipe" \> $nlist\""; } >&5
+  (eval $NM conftest.$ac_objext \| "$lt_cv_sys_global_symbol_pipe" \> $nlist) 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; } && test -s "$nlist"; then
+      # Try sorting and uniquifying the output.
+      if sort "$nlist" | uniq > "$nlist"T; then
+	mv -f "$nlist"T "$nlist"
+      else
+	rm -f "$nlist"T
+      fi
 
-#ifdef __STDC__
-# include <limits.h>
+      # Make sure that we snagged all the symbols we need.
+      if $GREP ' nm_test_var$' "$nlist" >/dev/null; then
+	if $GREP ' nm_test_func$' "$nlist" >/dev/null; then
+	  cat <<_LT_EOF > conftest.$ac_ext
+/* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests.  */
+#if defined(_WIN32) || defined(__CYGWIN__) || defined(_WIN32_WCE)
+/* DATA imports from DLLs on WIN32 con't be const, because runtime
+   relocations are performed -- see ld's documentation on pseudo-relocs.  */
+# define LT_DLSYM_CONST
+#elif defined(__osf__)
+/* This system does not cope well with relocations in const data.  */
+# define LT_DLSYM_CONST
 #else
-# include <assert.h>
+# define LT_DLSYM_CONST const
 #endif
 
-#undef vsnprintf
-
-/* Override any gcc2 internal prototype to avoid an error.  */
 #ifdef __cplusplus
-extern "C"
-{
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char vsnprintf ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined (__stub_vsnprintf) || defined (__stub___vsnprintf)
-choke me
-#else
-char (*f) () = vsnprintf;
+extern "C" {
 #endif
-#ifdef __cplusplus
+
+_LT_EOF
+	  # Now generate the symbol file.
+	  eval "$lt_cv_sys_global_symbol_to_cdecl"' < "$nlist" | $GREP -v main >> conftest.$ac_ext'
+
+	  cat <<_LT_EOF >> conftest.$ac_ext
+
+/* The mapping between symbol names and symbols.  */
+LT_DLSYM_CONST struct {
+  const char *name;
+  void       *address;
+}
+lt__PROGRAM__LTX_preloaded_symbols[] =
+{
+  { "@PROGRAM@", (void *) 0 },
+_LT_EOF
+	  $SED "s/^$symcode$symcode* \(.*\) \(.*\)$/  {\"\2\", (void *) \&\2},/" < "$nlist" | $GREP -v main >> conftest.$ac_ext
+	  cat <<\_LT_EOF >> conftest.$ac_ext
+  {0, (void *) 0}
+};
+
+/* This works around a problem in FreeBSD linker */
+#ifdef FREEBSD_WORKAROUND
+static const void *lt_preloaded_setup() {
+  return lt__PROGRAM__LTX_preloaded_symbols;
 }
 #endif
 
-int
-main ()
-{
-return f != vsnprintf;
-  ;
-  return 0;
+#ifdef __cplusplus
 }
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
+#endif
+_LT_EOF
+	  # Now try linking the two files.
+	  mv conftest.$ac_objext conftstm.$ac_objext
+	  lt_globsym_save_LIBS=$LIBS
+	  lt_globsym_save_CFLAGS=$CFLAGS
+	  LIBS="conftstm.$ac_objext"
+	  CFLAGS="$CFLAGS$lt_prog_compiler_no_builtin_flag"
+	  if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_link\""; } >&5
+  (eval $ac_link) 2>&5
   ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_func_vsnprintf=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; } && test -s conftest${ac_exeext}; then
+	    pipe_works=yes
+	  fi
+	  LIBS=$lt_globsym_save_LIBS
+	  CFLAGS=$lt_globsym_save_CFLAGS
+	else
+	  echo "cannot find nm_test_func in $nlist" >&5
+	fi
+      else
+	echo "cannot find nm_test_var in $nlist" >&5
+      fi
+    else
+      echo "cannot run $lt_cv_sys_global_symbol_pipe" >&5
+    fi
+  else
+    echo "$progname: failed program was:" >&5
+    cat conftest.$ac_ext >&5
+  fi
+  rm -rf conftest* conftst*
+
+  # Do not use the global_symbol_pipe unless it works.
+  if test "$pipe_works" = yes; then
+    break
+  else
+    lt_cv_sys_global_symbol_pipe=
+  fi
+done
 
-ac_cv_func_vsnprintf=no
 fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
+
+if test -z "$lt_cv_sys_global_symbol_pipe"; then
+  lt_cv_sys_global_symbol_to_cdecl=
 fi
-echo "$as_me:$LINENO: result: $ac_cv_func_vsnprintf" >&5
-echo "${ECHO_T}$ac_cv_func_vsnprintf" >&6
-if test $ac_cv_func_vsnprintf = yes; then
-  STRINGS="-DHAVE_VSNPRINTF $STRINGS"
+if test -z "$lt_cv_sys_global_symbol_pipe$lt_cv_sys_global_symbol_to_cdecl"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: failed" >&5
+$as_echo "failed" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: ok" >&5
+$as_echo "ok" >&6; }
 fi
 
-STRINGS=$STRINGS
+# Response file support.
+if test "$lt_cv_nm_interface" = "MS dumpbin"; then
+  nm_file_list_spec='@'
+elif $NM --help 2>/dev/null | grep '[@]FILE' >/dev/null; then
+  nm_file_list_spec='@'
+fi
 
 
-MS_VERSION=`grep 'MS_VERSION ' mapserver.h | grep '#define' | cut -d\" -f2`
-echo "$as_me:$LINENO: result: MapServer Version from mapserver.h: '$MS_VERSION'" >&5
-echo "${ECHO_T}MapServer Version from mapserver.h: '$MS_VERSION'" >&6
-MS_VERSION="$MS_VERSION"
 
 
 
-echo "$as_me:$LINENO: checking if pkg-config path is provided" >&5
-echo $ECHO_N "checking if pkg-config path is provided... $ECHO_C" >&6
 
 
-# Check whether --with-pkg-config or --without-pkg-config was given.
-if test "${with_pkg_config+set}" = set; then
-  withval="$with_pkg_config"
 
-fi;
 
-if test -n "$with_pkg_config" -a "$with_pkg_config" != "no" ; then
 
-  echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6
 
-  PKG_CONFIG=$with_pkg_config
-else
-  PKG_CONFIG="yes"
-fi
 
-if test "$PKG_CONFIG" = "yes" ; then
 
-   # Extract the first word of "pkg-config", so it can be a program name with args.
-set dummy pkg-config; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
-if test "${ac_cv_path_PKG_CONFIG+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  case $PKG_CONFIG in
-  [\\/]* | ?:[\\/]*)
-  ac_cv_path_PKG_CONFIG="$PKG_CONFIG" # Let the user override the test with a path.
-  ;;
-  *)
-  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_path_PKG_CONFIG="$as_dir/$ac_word$ac_exec_ext"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
 
-  test -z "$ac_cv_path_PKG_CONFIG" && ac_cv_path_PKG_CONFIG="no"
-  ;;
-esac
-fi
-PKG_CONFIG=$ac_cv_path_PKG_CONFIG
 
-if test -n "$PKG_CONFIG"; then
-  echo "$as_me:$LINENO: result: $PKG_CONFIG" >&5
-echo "${ECHO_T}$PKG_CONFIG" >&6
-else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
-fi
 
 
-   if test "$PKG_CONFIG" = "no" ; then
-      echo "$as_me:$LINENO: result: couldn't find pkg-config in default path. Please specify full path to pkg-config if needed" >&5
-echo "${ECHO_T}couldn't find pkg-config in default path. Please specify full path to pkg-config if needed" >&6
-   fi
 
-elif test -f "$PKG_CONFIG" -a -x "$PKG_CONFIG" ; then
-     echo "$as_me:$LINENO: result: user supplied pkg-config ($PKG_CONFIG)" >&5
-echo "${ECHO_T}user supplied pkg-config ($PKG_CONFIG)" >&6
-else
-     { { echo "$as_me:$LINENO: error: '$PKG_CONFIG' is not an executable.  Make sure you use --with-pkg-config=/path/to/pkg-config" >&5
-echo "$as_me: error: '$PKG_CONFIG' is not an executable.  Make sure you use --with-pkg-config=/path/to/pkg-config" >&2;}
-   { (exit 1); exit 1; }; }
-fi
 
 
 
-unset ac_cv_lib_freetype_FT_Init_FreeType
-unset ac_cv_lib_ttf_TT_Init_FreeType
 
 
-# Check whether --with-freetype or --without-freetype was given.
-if test "${with_freetype+set}" = set; then
-  withval="$with_freetype"
-  FT_DIR=$withval
-else
-  FT_DIR=''
-fi;
 
-FT_LDFLAGS=''
-FT_CFLAGS=''
-FT_BIN=''
 
-if test "x$FT_DIR" = "xno" ; then
-    { { echo "$as_me:$LINENO: error: Freetype support disabled but is now mandatory. Rerun without --without-freetype or --with-freetype=no" >&5
-echo "$as_me: error: Freetype support disabled but is now mandatory. Rerun without --without-freetype or --with-freetype=no" >&2;}
-   { (exit 1); exit 1; }; }
-fi
 
 
-if test -z "$FT_DIR" -o "$FT_DIR" = "yes" ; then
-        # Extract the first word of "freetype-config", so it can be a program name with args.
-set dummy freetype-config; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
-if test "${ac_cv_path_FT_BIN+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for sysroot" >&5
+$as_echo_n "checking for sysroot... " >&6; }
+
+# Check whether --with-sysroot was given.
+if test "${with_sysroot+set}" = set; then :
+  withval=$with_sysroot;
 else
-  case $FT_BIN in
-  [\\/]* | ?:[\\/]*)
-  ac_cv_path_FT_BIN="$FT_BIN" # Let the user override the test with a path.
-  ;;
-  *)
-  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_path_FT_BIN="$as_dir/$ac_word$ac_exec_ext"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
+  with_sysroot=no
+fi
 
-  test -z "$ac_cv_path_FT_BIN" && ac_cv_path_FT_BIN=""""
-  ;;
+
+lt_sysroot=
+case ${with_sysroot} in #(
+ yes)
+   if test "$GCC" = yes; then
+     lt_sysroot=`$CC --print-sysroot 2>/dev/null`
+   fi
+   ;; #(
+ /*)
+   lt_sysroot=`echo "$with_sysroot" | sed -e "$sed_quote_subst"`
+   ;; #(
+ no|'')
+   ;; #(
+ *)
+   { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${with_sysroot}" >&5
+$as_echo "${with_sysroot}" >&6; }
+   as_fn_error $? "The sysroot must be an absolute path." "$LINENO" 5
+   ;;
 esac
-fi
-FT_BIN=$ac_cv_path_FT_BIN
 
-if test -n "$FT_BIN"; then
-  echo "$as_me:$LINENO: result: $FT_BIN" >&5
-echo "${ECHO_T}$FT_BIN" >&6
-else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
-fi
+ { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${lt_sysroot:-no}" >&5
+$as_echo "${lt_sysroot:-no}" >&6; }
 
-    if test "x$FT_BIN" = "xno" ; then
-                echo "$as_me:$LINENO: checking for Freetype2.x in system locations" >&5
-echo $ECHO_N "checking for Freetype2.x in system locations... $ECHO_C" >&6
-        test -f /usr/include/ft2build.h -a -d /usr/include/freetype2 && FT_CFLAGS=-I/usr/include/freetype2
-        test -f /usr/local/include/ft2build.h -a -d /usr/local/include/freetype2 && FT_CFLAGS=-I/usr/local/include -I/usr/local/include/freetype2
-        FT_LDFLAGS="-lfreetype -lz"
-        fi
-else
 
-  if test -z "$FT_DIR" || echo "$FT_DIR" | grep '^/' >/dev/null ; then
-    FT_DIR="$FT_DIR"
-  else
-    FT_DIR="`pwd`/$FT_DIR"
-  fi
 
-    echo "$as_me:$LINENO: checking for Freetype2.x in $FT_DIR" >&5
-echo $ECHO_N "checking for Freetype2.x in $FT_DIR... $ECHO_C" >&6
-    test -x "$FT_DIR" -a "freetype-config" = "`basename $FT_DIR ''`" && FT_BIN="$FT_DIR"
-    test -x "$FT_DIR/freetype-config" && FT_BIN="$FT_DIR/freetype-config"
-    test -x "$FT_DIR/bin/freetype-config" && FT_BIN="$FT_DIR/bin/freetype-config"
-    if test "x$FT_BIN" = "x"; then
-        test -f $FT_DIR/ft2build.h -a -d $FT_DIR/freetype2 && FT_CFLAGS="-I$FT_DIR -I$FT_DIR/freetype2"
-        test -f $FT_DIR/include/ft2build.h -a -d $FT_DIR/include/freetype2 && FT_CFLAGS="-I$FT_DIR/include -I$FT_DIR/include/freetype2"
-        test -f $FT_DIR/lib/libfreetype.a -o -f $FT_DIR/lib/libfreetype.so -o -f $FT_DIR/lib/libfreetype.sl -o -f $FT_DIR/lib/libfreetype.dylib && FT_LDFLAGS="-L$FT_DIR/lib"
-        test -f $FT_DIR/lib64/libfreetype.a -o -f $FT_DIR/lib64/libfreetype.so -o -f $FT_DIR/lib64/libfreetype.sl && FT_LDFLAGS="-L$FT_DIR/lib64"
-        test -f $FT_DIR/libfreetype.a -o -f $FT_DIR/libfreetype.so -o -f $FT_DIR/libfreetype.sl -o -f $FT_DIR/libfreetype.dylib && FT_LDFLAGS="-L$FT_DIR"
-        fi
-fi
 
-if test "x$FT_BIN" != "x" ; then
-        FT_LDFLAGS=`$FT_BIN --libs`
-        FT_CFLAGS=`$FT_BIN --cflags`
+
+# Check whether --enable-libtool-lock was given.
+if test "${enable_libtool_lock+set}" = set; then :
+  enableval=$enable_libtool_lock;
 fi
 
+test "x$enable_libtool_lock" != xno && enable_libtool_lock=yes
 
-_cppflags="$CPPFLAGS"
-_ldflags="$LDFLAGS"
-_libs="$LIBS"
-CPPFLAGS="$FT_CFLAGS $CPPFLAGS"
-LDFLAGS="$FT_LDFLAGS $LDFLAGS"
+# Some flags need to be propagated to the compiler or linker for good
+# libtool support.
+case $host in
+ia64-*-hpux*)
+  # Find out which ABI we are using.
+  echo 'int i;' > conftest.$ac_ext
+  if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5
+  (eval $ac_compile) 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; then
+    case `/usr/bin/file conftest.$ac_objext` in
+      *ELF-32*)
+	HPUX_IA64_MODE="32"
+	;;
+      *ELF-64*)
+	HPUX_IA64_MODE="64"
+	;;
+    esac
+  fi
+  rm -rf conftest*
+  ;;
+*-*-irix6*)
+  # Find out which ABI we are using.
+  echo '#line '$LINENO' "configure"' > conftest.$ac_ext
+  if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5
+  (eval $ac_compile) 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; then
+    if test "$lt_cv_prog_gnu_ld" = yes; then
+      case `/usr/bin/file conftest.$ac_objext` in
+	*32-bit*)
+	  LD="${LD-ld} -melf32bsmip"
+	  ;;
+	*N32*)
+	  LD="${LD-ld} -melf32bmipn32"
+	  ;;
+	*64-bit*)
+	  LD="${LD-ld} -melf64bmip"
+	;;
+      esac
+    else
+      case `/usr/bin/file conftest.$ac_objext` in
+	*32-bit*)
+	  LD="${LD-ld} -32"
+	  ;;
+	*N32*)
+	  LD="${LD-ld} -n32"
+	  ;;
+	*64-bit*)
+	  LD="${LD-ld} -64"
+	  ;;
+      esac
+    fi
+  fi
+  rm -rf conftest*
+  ;;
 
+x86_64-*kfreebsd*-gnu|x86_64-*linux*|ppc*-*linux*|powerpc*-*linux*| \
+s390*-*linux*|s390*-*tpf*|sparc*-*linux*)
+  # Find out which ABI we are using.
+  echo 'int i;' > conftest.$ac_ext
+  if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5
+  (eval $ac_compile) 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; then
+    case `/usr/bin/file conftest.o` in
+      *32-bit*)
+	case $host in
+	  x86_64-*kfreebsd*-gnu)
+	    LD="${LD-ld} -m elf_i386_fbsd"
+	    ;;
+	  x86_64-*linux*)
+	    LD="${LD-ld} -m elf_i386"
+	    ;;
+	  ppc64-*linux*|powerpc64-*linux*)
+	    LD="${LD-ld} -m elf32ppclinux"
+	    ;;
+	  s390x-*linux*)
+	    LD="${LD-ld} -m elf_s390"
+	    ;;
+	  sparc64-*linux*)
+	    LD="${LD-ld} -m elf32_sparc"
+	    ;;
+	esac
+	;;
+      *64-bit*)
+	case $host in
+	  x86_64-*kfreebsd*-gnu)
+	    LD="${LD-ld} -m elf_x86_64_fbsd"
+	    ;;
+	  x86_64-*linux*)
+	    LD="${LD-ld} -m elf_x86_64"
+	    ;;
+	  ppc*-*linux*|powerpc*-*linux*)
+	    LD="${LD-ld} -m elf64ppc"
+	    ;;
+	  s390*-*linux*|s390*-*tpf*)
+	    LD="${LD-ld} -m elf64_s390"
+	    ;;
+	  sparc*-*linux*)
+	    LD="${LD-ld} -m elf64_sparc"
+	    ;;
+	esac
+	;;
+    esac
+  fi
+  rm -rf conftest*
+  ;;
 
-echo "$as_me:$LINENO: checking for FT_Init_FreeType in -lfreetype" >&5
-echo $ECHO_N "checking for FT_Init_FreeType in -lfreetype... $ECHO_C" >&6
-if test "${ac_cv_lib_freetype_FT_Init_FreeType+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+*-*-sco3.2v5*)
+  # On SCO OpenServer 5, we need -belf to get full-featured binaries.
+  SAVE_CFLAGS="$CFLAGS"
+  CFLAGS="$CFLAGS -belf"
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler needs -belf" >&5
+$as_echo_n "checking whether the C compiler needs -belf... " >&6; }
+if ${lt_cv_cc_needs_belf+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-lfreetype  $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+  ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+     cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char FT_Init_FreeType ();
 int
 main ()
 {
-FT_Init_FreeType ();
+
   ;
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_freetype_FT_Init_FreeType=yes
+if ac_fn_c_try_link "$LINENO"; then :
+  lt_cv_cc_needs_belf=yes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-ac_cv_lib_freetype_FT_Init_FreeType=no
+  lt_cv_cc_needs_belf=no
 fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+     ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
 fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_freetype_FT_Init_FreeType" >&5
-echo "${ECHO_T}$ac_cv_lib_freetype_FT_Init_FreeType" >&6
-if test $ac_cv_lib_freetype_FT_Init_FreeType = yes; then
-  cat >>confdefs.h <<_ACEOF
-#define HAVE_LIBFREETYPE 1
-_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_cc_needs_belf" >&5
+$as_echo "$lt_cv_cc_needs_belf" >&6; }
+  if test x"$lt_cv_cc_needs_belf" != x"yes"; then
+    # this is probably gcc 2.8.0, egcs 1.0 or newer; no need for -belf
+    CFLAGS="$SAVE_CFLAGS"
+  fi
+  ;;
+*-*solaris*)
+  # Find out which ABI we are using.
+  echo 'int i;' > conftest.$ac_ext
+  if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5
+  (eval $ac_compile) 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; then
+    case `/usr/bin/file conftest.o` in
+    *64-bit*)
+      case $lt_cv_prog_gnu_ld in
+      yes*)
+        case $host in
+        i?86-*-solaris*)
+          LD="${LD-ld} -m elf_x86_64"
+          ;;
+        sparc*-*-solaris*)
+          LD="${LD-ld} -m elf64_sparc"
+          ;;
+        esac
+        # GNU ld 2.21 introduced _sol2 emulations.  Use them if available.
+        if ${LD-ld} -V | grep _sol2 >/dev/null 2>&1; then
+          LD="${LD-ld}_sol2"
+        fi
+        ;;
+      *)
+	if ${LD-ld} -64 -r -o conftest2.o conftest.o >/dev/null 2>&1; then
+	  LD="${LD-ld} -64"
+	fi
+	;;
+      esac
+      ;;
+    esac
+  fi
+  rm -rf conftest*
+  ;;
+esac
 
-  LIBS="-lfreetype $LIBS"
+need_locks="$enable_libtool_lock"
 
+if test -n "$ac_tool_prefix"; then
+  # Extract the first word of "${ac_tool_prefix}mt", so it can be a program name with args.
+set dummy ${ac_tool_prefix}mt; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_MANIFEST_TOOL+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
-  { { echo "$as_me:$LINENO: error: unable to link - reconfigure with correct --with-freetype=dir " >&5
-echo "$as_me: error: unable to link - reconfigure with correct --with-freetype=dir " >&2;}
-   { (exit 1); exit 1; }; }
-fi
+  if test -n "$MANIFEST_TOOL"; then
+  ac_cv_prog_MANIFEST_TOOL="$MANIFEST_TOOL" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_MANIFEST_TOOL="${ac_tool_prefix}mt"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
 
+fi
+fi
+MANIFEST_TOOL=$ac_cv_prog_MANIFEST_TOOL
+if test -n "$MANIFEST_TOOL"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MANIFEST_TOOL" >&5
+$as_echo "$MANIFEST_TOOL" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
 
-# On IRIX 5.3, sys/types and inttypes.h are conflicting.
 
+fi
+if test -z "$ac_cv_prog_MANIFEST_TOOL"; then
+  ac_ct_MANIFEST_TOOL=$MANIFEST_TOOL
+  # Extract the first word of "mt", so it can be a program name with args.
+set dummy mt; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_ac_ct_MANIFEST_TOOL+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$ac_ct_MANIFEST_TOOL"; then
+  ac_cv_prog_ac_ct_MANIFEST_TOOL="$ac_ct_MANIFEST_TOOL" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_ac_ct_MANIFEST_TOOL="mt"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
 
+fi
+fi
+ac_ct_MANIFEST_TOOL=$ac_cv_prog_ac_ct_MANIFEST_TOOL
+if test -n "$ac_ct_MANIFEST_TOOL"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_MANIFEST_TOOL" >&5
+$as_echo "$ac_ct_MANIFEST_TOOL" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
 
+  if test "x$ac_ct_MANIFEST_TOOL" = x; then
+    MANIFEST_TOOL=":"
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
+$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
+ac_tool_warned=yes ;;
+esac
+    MANIFEST_TOOL=$ac_ct_MANIFEST_TOOL
+  fi
+else
+  MANIFEST_TOOL="$ac_cv_prog_MANIFEST_TOOL"
+fi
 
+test -z "$MANIFEST_TOOL" && MANIFEST_TOOL=mt
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if $MANIFEST_TOOL is a manifest tool" >&5
+$as_echo_n "checking if $MANIFEST_TOOL is a manifest tool... " >&6; }
+if ${lt_cv_path_mainfest_tool+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  lt_cv_path_mainfest_tool=no
+  echo "$as_me:$LINENO: $MANIFEST_TOOL '-?'" >&5
+  $MANIFEST_TOOL '-?' 2>conftest.err > conftest.out
+  cat conftest.err >&5
+  if $GREP 'Manifest Tool' conftest.out > /dev/null; then
+    lt_cv_path_mainfest_tool=yes
+  fi
+  rm -f conftest*
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_path_mainfest_tool" >&5
+$as_echo "$lt_cv_path_mainfest_tool" >&6; }
+if test "x$lt_cv_path_mainfest_tool" != xyes; then
+  MANIFEST_TOOL=:
+fi
 
 
 
 
 
-for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \
-		  inttypes.h stdint.h unistd.h
-do
-as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh`
-echo "$as_me:$LINENO: checking for $ac_header" >&5
-echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6
-if eval "test \"\${$as_ac_Header+set}\" = set"; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
 
-#include <$ac_header>
-_ACEOF
-rm -f conftest.$ac_objext
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest.$ac_objext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  eval "$as_ac_Header=yes"
+  case $host_os in
+    rhapsody* | darwin*)
+    if test -n "$ac_tool_prefix"; then
+  # Extract the first word of "${ac_tool_prefix}dsymutil", so it can be a program name with args.
+set dummy ${ac_tool_prefix}dsymutil; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_DSYMUTIL+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
+  if test -n "$DSYMUTIL"; then
+  ac_cv_prog_DSYMUTIL="$DSYMUTIL" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_DSYMUTIL="${ac_tool_prefix}dsymutil"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
 
-eval "$as_ac_Header=no"
 fi
-rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
 fi
-echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Header'}'`" >&5
-echo "${ECHO_T}`eval echo '${'$as_ac_Header'}'`" >&6
-if test `eval echo '${'$as_ac_Header'}'` = yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
-_ACEOF
-
+DSYMUTIL=$ac_cv_prog_DSYMUTIL
+if test -n "$DSYMUTIL"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DSYMUTIL" >&5
+$as_echo "$DSYMUTIL" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
 
-done
-
 
-
-for ac_header in ft2build.h
-do
-as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh`
-if eval "test \"\${$as_ac_Header+set}\" = set"; then
-  echo "$as_me:$LINENO: checking for $ac_header" >&5
-echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6
-if eval "test \"\${$as_ac_Header+set}\" = set"; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
 fi
-echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Header'}'`" >&5
-echo "${ECHO_T}`eval echo '${'$as_ac_Header'}'`" >&6
+if test -z "$ac_cv_prog_DSYMUTIL"; then
+  ac_ct_DSYMUTIL=$DSYMUTIL
+  # Extract the first word of "dsymutil", so it can be a program name with args.
+set dummy dsymutil; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_ac_ct_DSYMUTIL+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
-  # Is the header compilable?
-echo "$as_me:$LINENO: checking $ac_header usability" >&5
-echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
-#include <$ac_header>
-_ACEOF
-rm -f conftest.$ac_objext
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest.$ac_objext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_header_compiler=yes
+  if test -n "$ac_ct_DSYMUTIL"; then
+  ac_cv_prog_ac_ct_DSYMUTIL="$ac_ct_DSYMUTIL" # Let the user override the test.
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_ac_ct_DSYMUTIL="dsymutil"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
 
-ac_header_compiler=no
 fi
-rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
-echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
-echo "${ECHO_T}$ac_header_compiler" >&6
+fi
+ac_ct_DSYMUTIL=$ac_cv_prog_ac_ct_DSYMUTIL
+if test -n "$ac_ct_DSYMUTIL"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_DSYMUTIL" >&5
+$as_echo "$ac_ct_DSYMUTIL" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
 
-# Is the header present?
-echo "$as_me:$LINENO: checking $ac_header presence" >&5
-echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#include <$ac_header>
-_ACEOF
-if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5
-  (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } >/dev/null; then
-  if test -s conftest.err; then
-    ac_cpp_err=$ac_c_preproc_warn_flag
-    ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
+  if test "x$ac_ct_DSYMUTIL" = x; then
+    DSYMUTIL=":"
   else
-    ac_cpp_err=
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
+$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
+ac_tool_warned=yes ;;
+esac
+    DSYMUTIL=$ac_ct_DSYMUTIL
   fi
 else
-  ac_cpp_err=yes
-fi
-if test -z "$ac_cpp_err"; then
-  ac_header_preproc=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-  ac_header_preproc=no
+  DSYMUTIL="$ac_cv_prog_DSYMUTIL"
 fi
-rm -f conftest.err conftest.$ac_ext
-echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
-echo "${ECHO_T}$ac_header_preproc" >&6
 
-# So?  What about this header?
-case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
-  yes:no: )
-    { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5
-echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5
-echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;}
-    ac_header_preproc=yes
-    ;;
-  no:yes:* )
-    { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5
-echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header:     check for missing prerequisite headers?" >&5
-echo "$as_me: WARNING: $ac_header:     check for missing prerequisite headers?" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5
-echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header:     section \"Present But Cannot Be Compiled\"" >&5
-echo "$as_me: WARNING: $ac_header:     section \"Present But Cannot Be Compiled\"" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5
-echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5
-echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;}
-    (
-      cat <<\_ASBOX
-## ------------------------------------------ ##
-## Report this to the AC_PACKAGE_NAME lists.  ##
-## ------------------------------------------ ##
-_ASBOX
-    ) |
-      sed "s/^/$as_me: WARNING:     /" >&2
-    ;;
-esac
-echo "$as_me:$LINENO: checking for $ac_header" >&5
-echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6
-if eval "test \"\${$as_ac_Header+set}\" = set"; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+    if test -n "$ac_tool_prefix"; then
+  # Extract the first word of "${ac_tool_prefix}nmedit", so it can be a program name with args.
+set dummy ${ac_tool_prefix}nmedit; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_NMEDIT+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
-  eval "$as_ac_Header=\$ac_header_preproc"
-fi
-echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Header'}'`" >&5
-echo "${ECHO_T}`eval echo '${'$as_ac_Header'}'`" >&6
+  if test -n "$NMEDIT"; then
+  ac_cv_prog_NMEDIT="$NMEDIT" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_NMEDIT="${ac_tool_prefix}nmedit"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
 
 fi
-if test `eval echo '${'$as_ac_Header'}'` = yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
-_ACEOF
-
+fi
+NMEDIT=$ac_cv_prog_NMEDIT
+if test -n "$NMEDIT"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $NMEDIT" >&5
+$as_echo "$NMEDIT" >&6; }
 else
-  { { echo "$as_me:$LINENO: error: ft2build.h header not found - reconfigure with correct --with-freetype=dir " >&5
-echo "$as_me: error: ft2build.h header not found - reconfigure with correct --with-freetype=dir " >&2;}
-   { (exit 1); exit 1; }; }
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
 
-done
-
-
-CPPFLAGS=$_cppflags
-LDFLAGS=$_ldflags
-LIBS=$_libs
-FT_ENABLED="-DUSE_FREETYPE"
-FT_ENABLED=$FT_ENABLED
-
-FT_INC=$FT_CFLAGS
-
-FT_LIB=$FT_LDFLAGS
-
-ALL_ENABLED="$FT_ENABLED $ALL_ENABLED"
-ALL_INC="$FT_CFLAGS $ALL_INC"
-ALL_LIB="$FT_LDFLAGS $ALL_LIB"
-
-
-
-unset ac_cv_lib_z_zlibVersion
 
-
-# Check whether --with-zlib or --without-zlib was given.
-if test "${with_zlib+set}" = set; then
-  withval="$with_zlib"
-  ZLIB_DIR=$withval
+fi
+if test -z "$ac_cv_prog_NMEDIT"; then
+  ac_ct_NMEDIT=$NMEDIT
+  # Extract the first word of "nmedit", so it can be a program name with args.
+set dummy nmedit; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_ac_ct_NMEDIT+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
-  ZLIB_DIR=''
-fi;
+  if test -n "$ac_ct_NMEDIT"; then
+  ac_cv_prog_ac_ct_NMEDIT="$ac_ct_NMEDIT" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_ac_ct_NMEDIT="nmedit"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
 
+fi
+fi
+ac_ct_NMEDIT=$ac_cv_prog_ac_ct_NMEDIT
+if test -n "$ac_ct_NMEDIT"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_NMEDIT" >&5
+$as_echo "$ac_ct_NMEDIT" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
 
-  if test -z "$ZLIB_DIR" || echo "$ZLIB_DIR" | grep '^/' >/dev/null ; then
-    ZLIB_DIR="$ZLIB_DIR"
+  if test "x$ac_ct_NMEDIT" = x; then
+    NMEDIT=":"
   else
-    ZLIB_DIR="`pwd`/$ZLIB_DIR"
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
+$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
+ac_tool_warned=yes ;;
+esac
+    NMEDIT=$ac_ct_NMEDIT
   fi
+else
+  NMEDIT="$ac_cv_prog_NMEDIT"
+fi
 
-{ echo "$as_me:$LINENO: checking where Zlib is installed..." >&5
-echo "$as_me: checking where Zlib is installed..." >&6;}
-ZLIB_LIB=''
-
-test -f $ZLIB_DIR/include/zlib.h && ZLIB_INCDIR="$ZLIB_DIR/include"
-
-test -f $ZLIB_DIR/lib/libz.a -o -f $ZLIB_DIR/lib/libz.so -o -f $ZLIB_DIR/lib/libz.sl -o -f $ZLIB_DIR/lib/libz.dylib && ZLIB_LIBDIR="$ZLIB_DIR/lib"
-test -f $ZLIB_DIR/lib64/libz.a -o -f $ZLIB_DIR/lib64/libz.so -o -f $ZLIB_DIR/lib64/libz.sl && ZLIB_LIBDIR="$ZLIB_DIR/lib64"
-test -f $ZLIB_DIR/libz.a -o -f $ZLIB_DIR/libz.so -o -f $ZLIB_DIR/libz.sl && ZLIB_LIBDIR="$ZLIB_DIR"
-
-
-if test -n "$ZLIB_LIBDIR" -a -n "$ZLIB_INCDIR" ; then
+    if test -n "$ac_tool_prefix"; then
+  # Extract the first word of "${ac_tool_prefix}lipo", so it can be a program name with args.
+set dummy ${ac_tool_prefix}lipo; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_LIPO+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$LIPO"; then
+  ac_cv_prog_LIPO="$LIPO" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_LIPO="${ac_tool_prefix}lipo"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
 
-        ZLIB_ENABLED="-DUSE_ZLIB"
-  ZLIB_INC="-I$ZLIB_INCDIR"
-  ZLIB_LIB="-L$ZLIB_LIBDIR -lz"
-  echo "$as_me:$LINENO: result:         using libz from $ZLIB_LIB ($ZLIB_ENABLED)" >&5
-echo "${ECHO_T}        using libz from $ZLIB_LIB ($ZLIB_ENABLED)" >&6
+fi
+fi
+LIPO=$ac_cv_prog_LIPO
+if test -n "$LIPO"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $LIPO" >&5
+$as_echo "$LIPO" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
 
-  if test ""$ZLIB_DIR"" != "/usr/lib"; then
 
-  if test -z ""$ZLIB_DIR"" || echo ""$ZLIB_DIR"" | grep '^/' >/dev/null ; then
-    ai_p=""$ZLIB_DIR""
-  else
-    ai_p="`pwd`/"$ZLIB_DIR""
+fi
+if test -z "$ac_cv_prog_LIPO"; then
+  ac_ct_LIPO=$LIPO
+  # Extract the first word of "lipo", so it can be a program name with args.
+set dummy lipo; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_ac_ct_LIPO+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$ac_ct_LIPO"; then
+  ac_cv_prog_ac_ct_LIPO="$ac_ct_LIPO" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_ac_ct_LIPO="lipo"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
   fi
+done
+  done
+IFS=$as_save_IFS
 
+fi
+fi
+ac_ct_LIPO=$ac_cv_prog_ac_ct_LIPO
+if test -n "$ac_ct_LIPO"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_LIPO" >&5
+$as_echo "$ac_ct_LIPO" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
 
-  unique=`echo $ac_n "$ai_p$ac_c" | tr -c -d a-zA-Z0-9`
-  cmd="echo $ac_n \"\$LIBPATH$unique$ac_c\""
-  if test -n "$unique" && test "`eval $cmd`" = "" ; then
-    eval "LIBPATH$unique=set"
-
-      EXTRA_LIBS="$EXTRA_LIBS -L$ai_p"
-        RPATHS="$RPATHS ${ld_runpath_switch}$ai_p"
-
+  if test "x$ac_ct_LIPO" = x; then
+    LIPO=":"
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
+$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
+ac_tool_warned=yes ;;
+esac
+    LIPO=$ac_ct_LIPO
   fi
+else
+  LIPO="$ac_cv_prog_LIPO"
+fi
 
+    if test -n "$ac_tool_prefix"; then
+  # Extract the first word of "${ac_tool_prefix}otool", so it can be a program name with args.
+set dummy ${ac_tool_prefix}otool; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_OTOOL+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$OTOOL"; then
+  ac_cv_prog_OTOOL="$OTOOL" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_OTOOL="${ac_tool_prefix}otool"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
   fi
+done
+  done
+IFS=$as_save_IFS
 
+fi
+fi
+OTOOL=$ac_cv_prog_OTOOL
+if test -n "$OTOOL"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $OTOOL" >&5
+$as_echo "$OTOOL" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
 
-elif test -n "$ZLIB_LIBDIR" ; then
-
-        ZLIB_LIB="-L$ZLIB_LIBDIR -lz"
-  echo "$as_me:$LINENO: result:         using runtime libz from $ZLIB_LIB" >&5
-echo "${ECHO_T}        using runtime libz from $ZLIB_LIB" >&6
-
-  if test ""$ZLIB_DIR"" != "/usr/lib"; then
 
-  if test -z ""$ZLIB_DIR"" || echo ""$ZLIB_DIR"" | grep '^/' >/dev/null ; then
-    ai_p=""$ZLIB_DIR""
-  else
-    ai_p="`pwd`/"$ZLIB_DIR""
+fi
+if test -z "$ac_cv_prog_OTOOL"; then
+  ac_ct_OTOOL=$OTOOL
+  # Extract the first word of "otool", so it can be a program name with args.
+set dummy otool; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_ac_ct_OTOOL+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$ac_ct_OTOOL"; then
+  ac_cv_prog_ac_ct_OTOOL="$ac_ct_OTOOL" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_ac_ct_OTOOL="otool"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
   fi
+done
+  done
+IFS=$as_save_IFS
 
+fi
+fi
+ac_ct_OTOOL=$ac_cv_prog_ac_ct_OTOOL
+if test -n "$ac_ct_OTOOL"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_OTOOL" >&5
+$as_echo "$ac_ct_OTOOL" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
 
-  unique=`echo $ac_n "$ai_p$ac_c" | tr -c -d a-zA-Z0-9`
-  cmd="echo $ac_n \"\$LIBPATH$unique$ac_c\""
-  if test -n "$unique" && test "`eval $cmd`" = "" ; then
-    eval "LIBPATH$unique=set"
-
-      EXTRA_LIBS="$EXTRA_LIBS -L$ai_p"
-        RPATHS="$RPATHS ${ld_runpath_switch}$ai_p"
-
+  if test "x$ac_ct_OTOOL" = x; then
+    OTOOL=":"
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
+$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
+ac_tool_warned=yes ;;
+esac
+    OTOOL=$ac_ct_OTOOL
   fi
+else
+  OTOOL="$ac_cv_prog_OTOOL"
+fi
 
+    if test -n "$ac_tool_prefix"; then
+  # Extract the first word of "${ac_tool_prefix}otool64", so it can be a program name with args.
+set dummy ${ac_tool_prefix}otool64; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_OTOOL64+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$OTOOL64"; then
+  ac_cv_prog_OTOOL64="$OTOOL64" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_OTOOL64="${ac_tool_prefix}otool64"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
   fi
+done
+  done
+IFS=$as_save_IFS
 
-
+fi
+fi
+OTOOL64=$ac_cv_prog_OTOOL64
+if test -n "$OTOOL64"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $OTOOL64" >&5
+$as_echo "$OTOOL64" >&6; }
 else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
 
 
-  echo "$as_me:$LINENO: checking for zlibVersion in -lz" >&5
-echo $ECHO_N "checking for zlibVersion in -lz... $ECHO_C" >&6
-if test "${ac_cv_lib_z_zlibVersion+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+fi
+if test -z "$ac_cv_prog_OTOOL64"; then
+  ac_ct_OTOOL64=$OTOOL64
+  # Extract the first word of "otool64", so it can be a program name with args.
+set dummy otool64; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_ac_ct_OTOOL64+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-lz  $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char zlibVersion ();
-int
-main ()
-{
-zlibVersion ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_z_zlibVersion=yes
+  if test -n "$ac_ct_OTOOL64"; then
+  ac_cv_prog_ac_ct_OTOOL64="$ac_ct_OTOOL64" # Let the user override the test.
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_ac_ct_OTOOL64="otool64"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
 
-ac_cv_lib_z_zlibVersion=no
 fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
 fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_z_zlibVersion" >&5
-echo "${ECHO_T}$ac_cv_lib_z_zlibVersion" >&6
-if test $ac_cv_lib_z_zlibVersion = yes; then
-  ZLIB_LIB="-lz"
+ac_ct_OTOOL64=$ac_cv_prog_ac_ct_OTOOL64
+if test -n "$ac_ct_OTOOL64"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_OTOOL64" >&5
+$as_echo "$ac_ct_OTOOL64" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
 
-
-  if test -n "$ZLIB_LIB" ; then
-    ZLIB_ENABLED="-DUSE_ZLIB"
-    echo "$as_me:$LINENO: result:         using libz from system libs ($ZLIB_ENABLED)." >&5
-echo "${ECHO_T}        using libz from system libs ($ZLIB_ENABLED)." >&6
+  if test "x$ac_ct_OTOOL64" = x; then
+    OTOOL64=":"
   else
-    echo "$as_me:$LINENO: result:         Zlib (libz) library cannot be found, possibly needed for GD" >&5
-echo "${ECHO_T}        Zlib (libz) library cannot be found, possibly needed for GD" >&6
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
+$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
+ac_tool_warned=yes ;;
+esac
+    OTOOL64=$ac_ct_OTOOL64
   fi
-
+else
+  OTOOL64="$ac_cv_prog_OTOOL64"
 fi
 
 
-ZLIB_ENABLED=$ZLIB_ENABLED
 
-ZLIB_INC=$ZLIB_INC
 
-ZLIB_LIB=$ZLIB_LIB
 
 
-ALL_ENABLED="$ZLIB_ENABLED $ALL_ENABLED"
-ALL_INC="$ZLIB_INC $ALL_INC"
-ALL_LIB="$ZLIB_LIB $ALL_LIB"
 
 
-unset ac_cv_lib_png_png_init_io
 
 
-# Check whether --with-png or --without-png was given.
-if test "${with_png+set}" = set; then
-  withval="$with_png"
-  PNG_DIR=$withval
-else
-  PNG_DIR=''
-fi;
 
 
-  if test -z "$PNG_DIR" || echo "$PNG_DIR" | grep '^/' >/dev/null ; then
-    PNG_DIR="$PNG_DIR"
-  else
-    PNG_DIR="`pwd`/$PNG_DIR"
-  fi
 
-{ echo "$as_me:$LINENO: checking where PNG is installed..." >&5
-echo "$as_me: checking where PNG is installed..." >&6;}
-PNG_LIB=''
-PNG_INC=''
-PNG_ENABLED=''
 
 
-if test -n "$PNG_DIR" ; then
-    test -f $PNG_DIR/lib/libpng.a -o -f $PNG_DIR/lib/libpng.so -o -f $PNG_DIR/lib/libpng.sl -o -f $PNG_DIR/lib/libpng.dylib && PNG_LIBDIR="$PNG_DIR/lib"
-    test -f $PNG_DIR/lib64/libpng.a -o -f $PNG_DIR/lib64/libpng.so -o -f $PNG_DIR/lib64/libpng.sl -o -f $PNG_DIR/libpng.dylib && PNG_LIBDIR="$PNG_DIR/lib64"
-    test -f $PNG_DIR/libpng.a -o -f $PNG_DIR/libpng.so -o -f $PNG_DIR/libpng.sl -o -f $PNG_DIR/libpng.dylib && PNG_LIBDIR="$PNG_DIR"
-    test -f $PNG_DIR/include/png.h && PNG_INCLUDE="$PNG_DIR/include"
-    test -f $PNG_DIR/lib/png.h && PNG_INCLUDE="$PNG_DIR/lib"
-    test -f $PNG_DIR/png.h && PNG_INCLUDE="$PNG_DIR"
 
-    if test -n "$PNG_LIBDIR" ; then
-      PNG_LIB="-L$PNG_LIBDIR -lpng"
-      echo "$as_me:$LINENO: result:         using libpng from $PNG_LIB" >&5
-echo "${ECHO_T}        using libpng from $PNG_LIB" >&6
 
-  if test ""$PNG_LIBDIR"" != "/usr/lib"; then
 
-  if test -z ""$PNG_LIBDIR"" || echo ""$PNG_LIBDIR"" | grep '^/' >/dev/null ; then
-    ai_p=""$PNG_LIBDIR""
-  else
-    ai_p="`pwd`/"$PNG_LIBDIR""
-  fi
 
 
-  unique=`echo $ac_n "$ai_p$ac_c" | tr -c -d a-zA-Z0-9`
-  cmd="echo $ac_n \"\$LIBPATH$unique$ac_c\""
-  if test -n "$unique" && test "`eval $cmd`" = "" ; then
-    eval "LIBPATH$unique=set"
 
-      EXTRA_LIBS="$EXTRA_LIBS -L$ai_p"
-        RPATHS="$RPATHS ${ld_runpath_switch}$ai_p"
 
-  fi
 
-  fi
 
-    else
-      { { echo "$as_me:$LINENO: error: cannot find png lib in $PNG_DIR" >&5
-echo "$as_me: error: cannot find png lib in $PNG_DIR" >&2;}
-   { (exit 1); exit 1; }; }
-    fi
 
-    if test -n "$PNG_INCLUDE" ; then
-            old_cflags="$CFLAGS"
-      CFLAGS="$ZLIB_INC $CFLAGS"
-      as_ac_Header=`echo "ac_cv_header_$PNG_INCLUDE/png.h" | $as_tr_sh`
-if eval "test \"\${$as_ac_Header+set}\" = set"; then
-  echo "$as_me:$LINENO: checking for $PNG_INCLUDE/png.h" >&5
-echo $ECHO_N "checking for $PNG_INCLUDE/png.h... $ECHO_C" >&6
-if eval "test \"\${$as_ac_Header+set}\" = set"; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-fi
-echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Header'}'`" >&5
-echo "${ECHO_T}`eval echo '${'$as_ac_Header'}'`" >&6
-else
-  # Is the header compilable?
-echo "$as_me:$LINENO: checking $PNG_INCLUDE/png.h usability" >&5
-echo $ECHO_N "checking $PNG_INCLUDE/png.h usability... $ECHO_C" >&6
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
-#include <$PNG_INCLUDE/png.h>
-_ACEOF
-rm -f conftest.$ac_objext
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest.$ac_objext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_header_compiler=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
 
-ac_header_compiler=no
-fi
-rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
-echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
-echo "${ECHO_T}$ac_header_compiler" >&6
 
-# Is the header present?
-echo "$as_me:$LINENO: checking $PNG_INCLUDE/png.h presence" >&5
-echo $ECHO_N "checking $PNG_INCLUDE/png.h presence... $ECHO_C" >&6
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#include <$PNG_INCLUDE/png.h>
-_ACEOF
-if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5
-  (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } >/dev/null; then
-  if test -s conftest.err; then
-    ac_cpp_err=$ac_c_preproc_warn_flag
-    ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
-  else
-    ac_cpp_err=
-  fi
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for -single_module linker flag" >&5
+$as_echo_n "checking for -single_module linker flag... " >&6; }
+if ${lt_cv_apple_cc_single_mod+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
-  ac_cpp_err=yes
+  lt_cv_apple_cc_single_mod=no
+      if test -z "${LT_MULTI_MODULE}"; then
+	# By default we will add the -single_module flag. You can override
+	# by either setting the environment variable LT_MULTI_MODULE
+	# non-empty at configure time, or by adding -multi_module to the
+	# link flags.
+	rm -rf libconftest.dylib*
+	echo "int foo(void){return 1;}" > conftest.c
+	echo "$LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \
+-dynamiclib -Wl,-single_module conftest.c" >&5
+	$LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \
+	  -dynamiclib -Wl,-single_module conftest.c 2>conftest.err
+        _lt_result=$?
+	# If there is a non-empty error log, and "single_module"
+	# appears in it, assume the flag caused a linker warning
+        if test -s conftest.err && $GREP single_module conftest.err; then
+	  cat conftest.err >&5
+	# Otherwise, if the output was created with a 0 exit code from
+	# the compiler, it worked.
+	elif test -f libconftest.dylib && test $_lt_result -eq 0; then
+	  lt_cv_apple_cc_single_mod=yes
+	else
+	  cat conftest.err >&5
+	fi
+	rm -rf libconftest.dylib*
+	rm -f conftest.*
+      fi
 fi
-if test -z "$ac_cpp_err"; then
-  ac_header_preproc=yes
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_apple_cc_single_mod" >&5
+$as_echo "$lt_cv_apple_cc_single_mod" >&6; }
+
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for -exported_symbols_list linker flag" >&5
+$as_echo_n "checking for -exported_symbols_list linker flag... " >&6; }
+if ${lt_cv_ld_exported_symbols_list+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
+  lt_cv_ld_exported_symbols_list=no
+      save_LDFLAGS=$LDFLAGS
+      echo "_main" > conftest.sym
+      LDFLAGS="$LDFLAGS -Wl,-exported_symbols_list,conftest.sym"
+      cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
 
-  ac_header_preproc=no
-fi
-rm -f conftest.err conftest.$ac_ext
-echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
-echo "${ECHO_T}$ac_header_preproc" >&6
+int
+main ()
+{
 
-# So?  What about this header?
-case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
-  yes:no: )
-    { echo "$as_me:$LINENO: WARNING: $PNG_INCLUDE/png.h: accepted by the compiler, rejected by the preprocessor!" >&5
-echo "$as_me: WARNING: $PNG_INCLUDE/png.h: accepted by the compiler, rejected by the preprocessor!" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $PNG_INCLUDE/png.h: proceeding with the compiler's result" >&5
-echo "$as_me: WARNING: $PNG_INCLUDE/png.h: proceeding with the compiler's result" >&2;}
-    ac_header_preproc=yes
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  lt_cv_ld_exported_symbols_list=yes
+else
+  lt_cv_ld_exported_symbols_list=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+	LDFLAGS="$save_LDFLAGS"
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ld_exported_symbols_list" >&5
+$as_echo "$lt_cv_ld_exported_symbols_list" >&6; }
+
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for -force_load linker flag" >&5
+$as_echo_n "checking for -force_load linker flag... " >&6; }
+if ${lt_cv_ld_force_load+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  lt_cv_ld_force_load=no
+      cat > conftest.c << _LT_EOF
+int forced_loaded() { return 2;}
+_LT_EOF
+      echo "$LTCC $LTCFLAGS -c -o conftest.o conftest.c" >&5
+      $LTCC $LTCFLAGS -c -o conftest.o conftest.c 2>&5
+      echo "$AR cru libconftest.a conftest.o" >&5
+      $AR cru libconftest.a conftest.o 2>&5
+      echo "$RANLIB libconftest.a" >&5
+      $RANLIB libconftest.a 2>&5
+      cat > conftest.c << _LT_EOF
+int main() { return 0;}
+_LT_EOF
+      echo "$LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a" >&5
+      $LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a 2>conftest.err
+      _lt_result=$?
+      if test -s conftest.err && $GREP force_load conftest.err; then
+	cat conftest.err >&5
+      elif test -f conftest && test $_lt_result -eq 0 && $GREP forced_load conftest >/dev/null 2>&1 ; then
+	lt_cv_ld_force_load=yes
+      else
+	cat conftest.err >&5
+      fi
+        rm -f conftest.err libconftest.a conftest conftest.c
+        rm -rf conftest.dSYM
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ld_force_load" >&5
+$as_echo "$lt_cv_ld_force_load" >&6; }
+    case $host_os in
+    rhapsody* | darwin1.[012])
+      _lt_dar_allow_undefined='${wl}-undefined ${wl}suppress' ;;
+    darwin1.*)
+      _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;;
+    darwin*) # darwin 5.x on
+      # if running on 10.5 or later, the deployment target defaults
+      # to the OS version, if on x86, and 10.4, the deployment
+      # target defaults to 10.4. Don't you love it?
+      case ${MACOSX_DEPLOYMENT_TARGET-10.0},$host in
+	10.0,*86*-darwin8*|10.0,*-darwin[91]*)
+	  _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;;
+	10.[012]*)
+	  _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;;
+	10.*)
+	  _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;;
+      esac
     ;;
-  no:yes:* )
-    { echo "$as_me:$LINENO: WARNING: $PNG_INCLUDE/png.h: present but cannot be compiled" >&5
-echo "$as_me: WARNING: $PNG_INCLUDE/png.h: present but cannot be compiled" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $PNG_INCLUDE/png.h:     check for missing prerequisite headers?" >&5
-echo "$as_me: WARNING: $PNG_INCLUDE/png.h:     check for missing prerequisite headers?" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $PNG_INCLUDE/png.h: see the Autoconf documentation" >&5
-echo "$as_me: WARNING: $PNG_INCLUDE/png.h: see the Autoconf documentation" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $PNG_INCLUDE/png.h:     section \"Present But Cannot Be Compiled\"" >&5
-echo "$as_me: WARNING: $PNG_INCLUDE/png.h:     section \"Present But Cannot Be Compiled\"" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $PNG_INCLUDE/png.h: proceeding with the preprocessor's result" >&5
-echo "$as_me: WARNING: $PNG_INCLUDE/png.h: proceeding with the preprocessor's result" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $PNG_INCLUDE/png.h: in the future, the compiler will take precedence" >&5
-echo "$as_me: WARNING: $PNG_INCLUDE/png.h: in the future, the compiler will take precedence" >&2;}
-    (
-      cat <<\_ASBOX
-## ------------------------------------------ ##
-## Report this to the AC_PACKAGE_NAME lists.  ##
-## ------------------------------------------ ##
-_ASBOX
-    ) |
-      sed "s/^/$as_me: WARNING:     /" >&2
+  esac
+    if test "$lt_cv_apple_cc_single_mod" = "yes"; then
+      _lt_dar_single_mod='$single_module'
+    fi
+    if test "$lt_cv_ld_exported_symbols_list" = "yes"; then
+      _lt_dar_export_syms=' ${wl}-exported_symbols_list,$output_objdir/${libname}-symbols.expsym'
+    else
+      _lt_dar_export_syms='~$NMEDIT -s $output_objdir/${libname}-symbols.expsym ${lib}'
+    fi
+    if test "$DSYMUTIL" != ":" && test "$lt_cv_ld_force_load" = "no"; then
+      _lt_dsymutil='~$DSYMUTIL $lib || :'
+    else
+      _lt_dsymutil=
+    fi
     ;;
-esac
-echo "$as_me:$LINENO: checking for $PNG_INCLUDE/png.h" >&5
-echo $ECHO_N "checking for $PNG_INCLUDE/png.h... $ECHO_C" >&6
-if eval "test \"\${$as_ac_Header+set}\" = set"; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  eval "$as_ac_Header=\$ac_header_preproc"
-fi
-echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Header'}'`" >&5
-echo "${ECHO_T}`eval echo '${'$as_ac_Header'}'`" >&6
+  esac
 
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to run the C preprocessor" >&5
+$as_echo_n "checking how to run the C preprocessor... " >&6; }
+# On Suns, sometimes $CPP names a directory.
+if test -n "$CPP" && test -d "$CPP"; then
+  CPP=
 fi
-if test `eval echo '${'$as_ac_Header'}'` = yes; then
-  PNG_INC=-I$PNG_INCLUDE
+if test -z "$CPP"; then
+  if ${ac_cv_prog_CPP+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
-  { { echo "$as_me:$LINENO: error: cannot find png headers" >&5
-echo "$as_me: error: cannot find png headers" >&2;}
-   { (exit 1); exit 1; }; }
-fi
-
+      # Double quotes because CPP needs to be expanded
+    for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp"
+    do
+      ac_preproc_ok=false
+for ac_c_preproc_warn_flag in '' yes
+do
+  # Use a header file that comes with gcc, so configuring glibc
+  # with a fresh cross-compiler works.
+  # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+  # <limits.h> exists even on freestanding compilers.
+  # On the NeXT, cc -E runs the code through the compiler's parser,
+  # not just through cpp. "Syntax error" is here to catch this case.
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+		     Syntax error
+_ACEOF
+if ac_fn_c_try_cpp "$LINENO"; then :
 
-      CFLAGS="$old_cflags"
-      ALL_INC="$PNG_INC $ALL_INC"
-    else
-        { { echo "$as_me:$LINENO: error: cannot find png headers in $PNG_DIR" >&5
-echo "$as_me: error: cannot find png headers in $PNG_DIR" >&2;}
-   { (exit 1); exit 1; }; }
-    fi
-    PNG_ENABLED="-DUSE_PNG"
 else
+  # Broken: fails on valid input.
+continue
+fi
+rm -f conftest.err conftest.i conftest.$ac_ext
 
-
-  echo "$as_me:$LINENO: checking for png_init_io in -lpng" >&5
-echo $ECHO_N "checking for png_init_io in -lpng... $ECHO_C" >&6
-if test "${ac_cv_lib_png_png_init_io+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-lpng $ZLIB_LIB $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+  # OK, works on sane cases.  Now check whether nonexistent headers
+  # can be detected and how.
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
-
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char png_init_io ();
-int
-main ()
-{
-png_init_io ();
-  ;
-  return 0;
-}
+#include <ac_nonexistent.h>
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_png_png_init_io=yes
+if ac_fn_c_try_cpp "$LINENO"; then :
+  # Broken: success on invalid input.
+continue
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-ac_cv_lib_png_png_init_io=no
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
+  # Passes both tests.
+ac_preproc_ok=:
+break
 fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_png_png_init_io" >&5
-echo "${ECHO_T}$ac_cv_lib_png_png_init_io" >&6
-if test $ac_cv_lib_png_png_init_io = yes; then
-  PNG_LIB="-lpng"
+rm -f conftest.err conftest.i conftest.$ac_ext
+
+done
+# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
+rm -f conftest.i conftest.err conftest.$ac_ext
+if $ac_preproc_ok; then :
+  break
 fi
 
-  if test "${ac_cv_header_png_h+set}" = set; then
-  echo "$as_me:$LINENO: checking for png.h" >&5
-echo $ECHO_N "checking for png.h... $ECHO_C" >&6
-if test "${ac_cv_header_png_h+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+    done
+    ac_cv_prog_CPP=$CPP
+
 fi
-echo "$as_me:$LINENO: result: $ac_cv_header_png_h" >&5
-echo "${ECHO_T}$ac_cv_header_png_h" >&6
+  CPP=$ac_cv_prog_CPP
 else
-  # Is the header compilable?
-echo "$as_me:$LINENO: checking png.h usability" >&5
-echo $ECHO_N "checking png.h usability... $ECHO_C" >&6
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+  ac_cv_prog_CPP=$CPP
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $CPP" >&5
+$as_echo "$CPP" >&6; }
+ac_preproc_ok=false
+for ac_c_preproc_warn_flag in '' yes
+do
+  # Use a header file that comes with gcc, so configuring glibc
+  # with a fresh cross-compiler works.
+  # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+  # <limits.h> exists even on freestanding compilers.
+  # On the NeXT, cc -E runs the code through the compiler's parser,
+  # not just through cpp. "Syntax error" is here to catch this case.
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
-$ac_includes_default
-#include <png.h>
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+		     Syntax error
 _ACEOF
-rm -f conftest.$ac_objext
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest.$ac_objext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_header_compiler=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
+if ac_fn_c_try_cpp "$LINENO"; then :
 
-ac_header_compiler=no
+else
+  # Broken: fails on valid input.
+continue
 fi
-rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
-echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
-echo "${ECHO_T}$ac_header_compiler" >&6
+rm -f conftest.err conftest.i conftest.$ac_ext
 
-# Is the header present?
-echo "$as_me:$LINENO: checking png.h presence" >&5
-echo $ECHO_N "checking png.h presence... $ECHO_C" >&6
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+  # OK, works on sane cases.  Now check whether nonexistent headers
+  # can be detected and how.
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
-#include <png.h>
+#include <ac_nonexistent.h>
 _ACEOF
-if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5
-  (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } >/dev/null; then
-  if test -s conftest.err; then
-    ac_cpp_err=$ac_c_preproc_warn_flag
-    ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
-  else
-    ac_cpp_err=
-  fi
-else
-  ac_cpp_err=yes
-fi
-if test -z "$ac_cpp_err"; then
-  ac_header_preproc=yes
+if ac_fn_c_try_cpp "$LINENO"; then :
+  # Broken: success on invalid input.
+continue
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-  ac_header_preproc=no
+  # Passes both tests.
+ac_preproc_ok=:
+break
 fi
-rm -f conftest.err conftest.$ac_ext
-echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
-echo "${ECHO_T}$ac_header_preproc" >&6
+rm -f conftest.err conftest.i conftest.$ac_ext
 
-# So?  What about this header?
-case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
-  yes:no: )
-    { echo "$as_me:$LINENO: WARNING: png.h: accepted by the compiler, rejected by the preprocessor!" >&5
-echo "$as_me: WARNING: png.h: accepted by the compiler, rejected by the preprocessor!" >&2;}
-    { echo "$as_me:$LINENO: WARNING: png.h: proceeding with the compiler's result" >&5
-echo "$as_me: WARNING: png.h: proceeding with the compiler's result" >&2;}
-    ac_header_preproc=yes
-    ;;
-  no:yes:* )
-    { echo "$as_me:$LINENO: WARNING: png.h: present but cannot be compiled" >&5
-echo "$as_me: WARNING: png.h: present but cannot be compiled" >&2;}
-    { echo "$as_me:$LINENO: WARNING: png.h:     check for missing prerequisite headers?" >&5
-echo "$as_me: WARNING: png.h:     check for missing prerequisite headers?" >&2;}
-    { echo "$as_me:$LINENO: WARNING: png.h: see the Autoconf documentation" >&5
-echo "$as_me: WARNING: png.h: see the Autoconf documentation" >&2;}
-    { echo "$as_me:$LINENO: WARNING: png.h:     section \"Present But Cannot Be Compiled\"" >&5
-echo "$as_me: WARNING: png.h:     section \"Present But Cannot Be Compiled\"" >&2;}
-    { echo "$as_me:$LINENO: WARNING: png.h: proceeding with the preprocessor's result" >&5
-echo "$as_me: WARNING: png.h: proceeding with the preprocessor's result" >&2;}
-    { echo "$as_me:$LINENO: WARNING: png.h: in the future, the compiler will take precedence" >&5
-echo "$as_me: WARNING: png.h: in the future, the compiler will take precedence" >&2;}
-    (
-      cat <<\_ASBOX
-## ------------------------------------------ ##
-## Report this to the AC_PACKAGE_NAME lists.  ##
-## ------------------------------------------ ##
-_ASBOX
-    ) |
-      sed "s/^/$as_me: WARNING:     /" >&2
-    ;;
-esac
-echo "$as_me:$LINENO: checking for png.h" >&5
-echo $ECHO_N "checking for png.h... $ECHO_C" >&6
-if test "${ac_cv_header_png_h+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_cv_header_png_h=$ac_header_preproc
-fi
-echo "$as_me:$LINENO: result: $ac_cv_header_png_h" >&5
-echo "${ECHO_T}$ac_cv_header_png_h" >&6
+done
+# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
+rm -f conftest.i conftest.err conftest.$ac_ext
+if $ac_preproc_ok; then :
 
-fi
-if test $ac_cv_header_png_h = yes; then
-  :
 else
-  { { echo "$as_me:$LINENO: error: cannot find png headers in system path" >&5
-echo "$as_me: error: cannot find png headers in system path" >&2;}
-   { (exit 1); exit 1; }; }
+  { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error $? "C preprocessor \"$CPP\" fails sanity check
+See \`config.log' for more details" "$LINENO" 5; }
 fi
 
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
-  if test -n "$PNG_LIB" ; then
-    echo "$as_me:$LINENO: result:         using libpng from system libs." >&5
-echo "${ECHO_T}        using libpng from system libs." >&6
-  else
-    { { echo "$as_me:$LINENO: error: PNG (libpng) library cannot be found. install or reconfigure with --with-png=DIR" >&5
-echo "$as_me: error: PNG (libpng) library cannot be found. install or reconfigure with --with-png=DIR" >&2;}
-   { (exit 1); exit 1; }; }
-  fi
-  PNG_ENABLED="-DUSE_PNG"
-fi
 
-if test "${ac_cv_header_setjmp_h+set}" = set; then
-  echo "$as_me:$LINENO: checking for setjmp.h" >&5
-echo $ECHO_N "checking for setjmp.h... $ECHO_C" >&6
-if test "${ac_cv_header_setjmp_h+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-fi
-echo "$as_me:$LINENO: result: $ac_cv_header_setjmp_h" >&5
-echo "${ECHO_T}$ac_cv_header_setjmp_h" >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5
+$as_echo_n "checking for ANSI C header files... " >&6; }
+if ${ac_cv_header_stdc+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
-  # Is the header compilable?
-echo "$as_me:$LINENO: checking setjmp.h usability" >&5
-echo $ECHO_N "checking setjmp.h usability... $ECHO_C" >&6
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
-$ac_includes_default
-#include <setjmp.h>
+#include <stdlib.h>
+#include <stdarg.h>
+#include <string.h>
+#include <float.h>
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
 _ACEOF
-rm -f conftest.$ac_objext
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest.$ac_objext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_header_compiler=yes
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_header_stdc=yes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-ac_header_compiler=no
+  ac_cv_header_stdc=no
 fi
-rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
-echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
-echo "${ECHO_T}$ac_header_compiler" >&6
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
 
-# Is the header present?
-echo "$as_me:$LINENO: checking setjmp.h presence" >&5
-echo $ECHO_N "checking setjmp.h presence... $ECHO_C" >&6
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+if test $ac_cv_header_stdc = yes; then
+  # SunOS 4.x string.h does not declare mem*, contrary to ANSI.
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
-#include <setjmp.h>
+#include <string.h>
+
 _ACEOF
-if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5
-  (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } >/dev/null; then
-  if test -s conftest.err; then
-    ac_cpp_err=$ac_c_preproc_warn_flag
-    ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
-  else
-    ac_cpp_err=
-  fi
+if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
+  $EGREP "memchr" >/dev/null 2>&1; then :
+
 else
-  ac_cpp_err=yes
+  ac_cv_header_stdc=no
 fi
-if test -z "$ac_cpp_err"; then
-  ac_header_preproc=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
+rm -f conftest*
 
-  ac_header_preproc=no
 fi
-rm -f conftest.err conftest.$ac_ext
-echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
-echo "${ECHO_T}$ac_header_preproc" >&6
 
-# So?  What about this header?
-case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
-  yes:no: )
-    { echo "$as_me:$LINENO: WARNING: setjmp.h: accepted by the compiler, rejected by the preprocessor!" >&5
-echo "$as_me: WARNING: setjmp.h: accepted by the compiler, rejected by the preprocessor!" >&2;}
-    { echo "$as_me:$LINENO: WARNING: setjmp.h: proceeding with the compiler's result" >&5
-echo "$as_me: WARNING: setjmp.h: proceeding with the compiler's result" >&2;}
-    ac_header_preproc=yes
-    ;;
-  no:yes:* )
-    { echo "$as_me:$LINENO: WARNING: setjmp.h: present but cannot be compiled" >&5
-echo "$as_me: WARNING: setjmp.h: present but cannot be compiled" >&2;}
-    { echo "$as_me:$LINENO: WARNING: setjmp.h:     check for missing prerequisite headers?" >&5
-echo "$as_me: WARNING: setjmp.h:     check for missing prerequisite headers?" >&2;}
-    { echo "$as_me:$LINENO: WARNING: setjmp.h: see the Autoconf documentation" >&5
-echo "$as_me: WARNING: setjmp.h: see the Autoconf documentation" >&2;}
-    { echo "$as_me:$LINENO: WARNING: setjmp.h:     section \"Present But Cannot Be Compiled\"" >&5
-echo "$as_me: WARNING: setjmp.h:     section \"Present But Cannot Be Compiled\"" >&2;}
-    { echo "$as_me:$LINENO: WARNING: setjmp.h: proceeding with the preprocessor's result" >&5
-echo "$as_me: WARNING: setjmp.h: proceeding with the preprocessor's result" >&2;}
-    { echo "$as_me:$LINENO: WARNING: setjmp.h: in the future, the compiler will take precedence" >&5
-echo "$as_me: WARNING: setjmp.h: in the future, the compiler will take precedence" >&2;}
-    (
-      cat <<\_ASBOX
-## ------------------------------------------ ##
-## Report this to the AC_PACKAGE_NAME lists.  ##
-## ------------------------------------------ ##
-_ASBOX
-    ) |
-      sed "s/^/$as_me: WARNING:     /" >&2
-    ;;
-esac
-echo "$as_me:$LINENO: checking for setjmp.h" >&5
-echo $ECHO_N "checking for setjmp.h... $ECHO_C" >&6
-if test "${ac_cv_header_setjmp_h+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+if test $ac_cv_header_stdc = yes; then
+  # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI.
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <stdlib.h>
+
+_ACEOF
+if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
+  $EGREP "free" >/dev/null 2>&1; then :
+
 else
-  ac_cv_header_setjmp_h=$ac_header_preproc
+  ac_cv_header_stdc=no
 fi
-echo "$as_me:$LINENO: result: $ac_cv_header_setjmp_h" >&5
-echo "${ECHO_T}$ac_cv_header_setjmp_h" >&6
+rm -f conftest*
 
 fi
-if test $ac_cv_header_setjmp_h = yes; then
+
+if test $ac_cv_header_stdc = yes; then
+  # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi.
+  if test "$cross_compiling" = yes; then :
   :
 else
-  { { echo "$as_me:$LINENO: error: setjmp.h is required with libpng" >&5
-echo "$as_me: error: setjmp.h is required with libpng" >&2;}
-   { (exit 1); exit 1; }; }
-fi
-
-
-
-ALL_ENABLED="$PNG_ENABLED $ALL_ENABLED"
-PNG_ENABLED=$PNG_ENABLED
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <ctype.h>
+#include <stdlib.h>
+#if ((' ' & 0x0FF) == 0x020)
+# define ISLOWER(c) ('a' <= (c) && (c) <= 'z')
+# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c))
+#else
+# define ISLOWER(c) \
+		   (('a' <= (c) && (c) <= 'i') \
+		     || ('j' <= (c) && (c) <= 'r') \
+		     || ('s' <= (c) && (c) <= 'z'))
+# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c))
+#endif
 
-PNG_INC=$PNG_INC
+#define XOR(e, f) (((e) && !(f)) || (!(e) && (f)))
+int
+main ()
+{
+  int i;
+  for (i = 0; i < 256; i++)
+    if (XOR (islower (i), ISLOWER (i))
+	|| toupper (i) != TOUPPER (i))
+      return 2;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_run "$LINENO"; then :
 
-PNG_LIB=$PNG_LIB
+else
+  ac_cv_header_stdc=no
+fi
+rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
+  conftest.$ac_objext conftest.beam conftest.$ac_ext
+fi
 
+fi
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5
+$as_echo "$ac_cv_header_stdc" >&6; }
+if test $ac_cv_header_stdc = yes; then
 
+$as_echo "#define STDC_HEADERS 1" >>confdefs.h
 
+fi
 
+# On IRIX 5.3, sys/types and inttypes.h are conflicting.
+for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \
+		  inttypes.h stdint.h unistd.h
+do :
+  as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh`
+ac_fn_c_check_header_compile "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default
+"
+if eval test \"x\$"$as_ac_Header"\" = x"yes"; then :
+  cat >>confdefs.h <<_ACEOF
+#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1
+_ACEOF
 
-# Check whether --with-gif or --without-gif was given.
-if test "${with_gif+set}" = set; then
-  withval="$with_gif"
-  GIF_DIR=$withval
-else
-  GIF_DIR=''
-fi;
+fi
 
+done
 
-  if test -z "$GIF_DIR" || echo "$GIF_DIR" | grep '^/' >/dev/null ; then
-    GIF_DIR="$GIF_DIR"
-  else
-    GIF_DIR="`pwd`/$GIF_DIR"
-  fi
 
-{ echo "$as_me:$LINENO: checking where GIF is installed..." >&5
-echo "$as_me: checking where GIF is installed..." >&6;}
-GIF_LIB=''
-GIF_INC=''
-GIF_ENABLED=''
+for ac_header in dlfcn.h
+do :
+  ac_fn_c_check_header_compile "$LINENO" "dlfcn.h" "ac_cv_header_dlfcn_h" "$ac_includes_default
+"
+if test "x$ac_cv_header_dlfcn_h" = xyes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_DLFCN_H 1
+_ACEOF
 
+fi
 
-if test -n "$GIF_DIR" -a "GIF_DIR" != "yes" ; then
-    test -f $GIF_DIR/lib/libgif.a -o -f $GIF_DIR/lib/libgif.so -o -f $GIF_DIR/lib/libgif.sl -o -f $GIF_DIR/lib/libgif.dylib && GIF_LIBDIR="$GIF_DIR/lib"
-    test -f $GIF_DIR/lib64/libgif.a -o -f $GIF_DIR/lib64/libgif.so -o -f $GIF_DIR/lib64/libgif.sl -o -f $GIF_DIR/libgif.dylib && GIF_LIBDIR="$GIF_DIR/lib64"
-    test -f $GIF_DIR/libgif.a -o -f $GIF_DIR/libgif.so -o -f $GIF_DIR/libgif.sl -o -f $GIF_DIR/libgif.dylib && GIF_LIBDIR="$GIF_DIR"
-    test -f $GIF_DIR/include/gif_lib.h && GIF_INCLUDE="$GIF_DIR/include"
-    test -f $GIF_DIR/lib/gif_lib.h && GIF_INCLUDE="$GIF_DIR/lib"
-    test -f $GIF_DIR/gif_lib.h && GIF_INCLUDE="$GIF_DIR"
+done
 
-    if test -n "$GIF_LIBDIR" ; then
-      GIF_LIB="-L$GIF_LIBDIR -lgif"
-      echo "$as_me:$LINENO: result:         using libgif from $GIF_LIB" >&5
-echo "${ECHO_T}        using libgif from $GIF_LIB" >&6
 
-  if test ""$GIF_LIBDIR"" != "/usr/lib"; then
 
-  if test -z ""$GIF_LIBDIR"" || echo ""$GIF_LIBDIR"" | grep '^/' >/dev/null ; then
-    ai_p=""$GIF_LIBDIR""
-  else
-    ai_p="`pwd`/"$GIF_LIBDIR""
-  fi
 
 
-  unique=`echo $ac_n "$ai_p$ac_c" | tr -c -d a-zA-Z0-9`
-  cmd="echo $ac_n \"\$LIBPATH$unique$ac_c\""
-  if test -n "$unique" && test "`eval $cmd`" = "" ; then
-    eval "LIBPATH$unique=set"
+# Set options
+# Check whether --enable-static was given.
+if test "${enable_static+set}" = set; then :
+  enableval=$enable_static; p=${PACKAGE-default}
+    case $enableval in
+    yes) enable_static=yes ;;
+    no) enable_static=no ;;
+    *)
+     enable_static=no
+      # Look at the argument we got.  We use all the common list separators.
+      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
+      for pkg in $enableval; do
+	IFS="$lt_save_ifs"
+	if test "X$pkg" = "X$p"; then
+	  enable_static=yes
+	fi
+      done
+      IFS="$lt_save_ifs"
+      ;;
+    esac
+else
+  enable_static=no
+fi
 
-      EXTRA_LIBS="$EXTRA_LIBS -L$ai_p"
-        RPATHS="$RPATHS ${ld_runpath_switch}$ai_p"
 
-  fi
 
-  fi
 
-    else
-      { { echo "$as_me:$LINENO: error: cannot find gif lib in $GIF_DIR" >&5
-echo "$as_me: error: cannot find gif lib in $GIF_DIR" >&2;}
-   { (exit 1); exit 1; }; }
-    fi
 
-    if test -n "$GIF_INCLUDE" ; then
-      as_ac_Header=`echo "ac_cv_header_$GIF_INCLUDE/gif_lib.h" | $as_tr_sh`
-if eval "test \"\${$as_ac_Header+set}\" = set"; then
-  echo "$as_me:$LINENO: checking for $GIF_INCLUDE/gif_lib.h" >&5
-echo $ECHO_N "checking for $GIF_INCLUDE/gif_lib.h... $ECHO_C" >&6
-if eval "test \"\${$as_ac_Header+set}\" = set"; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-fi
-echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Header'}'`" >&5
-echo "${ECHO_T}`eval echo '${'$as_ac_Header'}'`" >&6
-else
-  # Is the header compilable?
-echo "$as_me:$LINENO: checking $GIF_INCLUDE/gif_lib.h usability" >&5
-echo $ECHO_N "checking $GIF_INCLUDE/gif_lib.h usability... $ECHO_C" >&6
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
-#include <$GIF_INCLUDE/gif_lib.h>
-_ACEOF
-rm -f conftest.$ac_objext
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest.$ac_objext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_header_compiler=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
 
-ac_header_compiler=no
-fi
-rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
-echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
-echo "${ECHO_T}$ac_header_compiler" >&6
 
-# Is the header present?
-echo "$as_me:$LINENO: checking $GIF_INCLUDE/gif_lib.h presence" >&5
-echo $ECHO_N "checking $GIF_INCLUDE/gif_lib.h presence... $ECHO_C" >&6
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#include <$GIF_INCLUDE/gif_lib.h>
-_ACEOF
-if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5
-  (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } >/dev/null; then
-  if test -s conftest.err; then
-    ac_cpp_err=$ac_c_preproc_warn_flag
-    ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
-  else
-    ac_cpp_err=
-  fi
-else
-  ac_cpp_err=yes
-fi
-if test -z "$ac_cpp_err"; then
-  ac_header_preproc=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
 
-  ac_header_preproc=no
-fi
-rm -f conftest.err conftest.$ac_ext
-echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
-echo "${ECHO_T}$ac_header_preproc" >&6
 
-# So?  What about this header?
-case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
-  yes:no: )
-    { echo "$as_me:$LINENO: WARNING: $GIF_INCLUDE/gif_lib.h: accepted by the compiler, rejected by the preprocessor!" >&5
-echo "$as_me: WARNING: $GIF_INCLUDE/gif_lib.h: accepted by the compiler, rejected by the preprocessor!" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $GIF_INCLUDE/gif_lib.h: proceeding with the compiler's result" >&5
-echo "$as_me: WARNING: $GIF_INCLUDE/gif_lib.h: proceeding with the compiler's result" >&2;}
-    ac_header_preproc=yes
-    ;;
-  no:yes:* )
-    { echo "$as_me:$LINENO: WARNING: $GIF_INCLUDE/gif_lib.h: present but cannot be compiled" >&5
-echo "$as_me: WARNING: $GIF_INCLUDE/gif_lib.h: present but cannot be compiled" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $GIF_INCLUDE/gif_lib.h:     check for missing prerequisite headers?" >&5
-echo "$as_me: WARNING: $GIF_INCLUDE/gif_lib.h:     check for missing prerequisite headers?" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $GIF_INCLUDE/gif_lib.h: see the Autoconf documentation" >&5
-echo "$as_me: WARNING: $GIF_INCLUDE/gif_lib.h: see the Autoconf documentation" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $GIF_INCLUDE/gif_lib.h:     section \"Present But Cannot Be Compiled\"" >&5
-echo "$as_me: WARNING: $GIF_INCLUDE/gif_lib.h:     section \"Present But Cannot Be Compiled\"" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $GIF_INCLUDE/gif_lib.h: proceeding with the preprocessor's result" >&5
-echo "$as_me: WARNING: $GIF_INCLUDE/gif_lib.h: proceeding with the preprocessor's result" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $GIF_INCLUDE/gif_lib.h: in the future, the compiler will take precedence" >&5
-echo "$as_me: WARNING: $GIF_INCLUDE/gif_lib.h: in the future, the compiler will take precedence" >&2;}
-    (
-      cat <<\_ASBOX
-## ------------------------------------------ ##
-## Report this to the AC_PACKAGE_NAME lists.  ##
-## ------------------------------------------ ##
-_ASBOX
-    ) |
-      sed "s/^/$as_me: WARNING:     /" >&2
-    ;;
-esac
-echo "$as_me:$LINENO: checking for $GIF_INCLUDE/gif_lib.h" >&5
-echo $ECHO_N "checking for $GIF_INCLUDE/gif_lib.h... $ECHO_C" >&6
-if eval "test \"\${$as_ac_Header+set}\" = set"; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  eval "$as_ac_Header=\$ac_header_preproc"
-fi
-echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Header'}'`" >&5
-echo "${ECHO_T}`eval echo '${'$as_ac_Header'}'`" >&6
 
-fi
-if test `eval echo '${'$as_ac_Header'}'` = yes; then
-  GIF_INC=-I$GIF_INCLUDE
+        enable_dlopen=no
+
+
+  enable_win32_dll=no
+
+
+            # Check whether --enable-shared was given.
+if test "${enable_shared+set}" = set; then :
+  enableval=$enable_shared; p=${PACKAGE-default}
+    case $enableval in
+    yes) enable_shared=yes ;;
+    no) enable_shared=no ;;
+    *)
+      enable_shared=no
+      # Look at the argument we got.  We use all the common list separators.
+      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
+      for pkg in $enableval; do
+	IFS="$lt_save_ifs"
+	if test "X$pkg" = "X$p"; then
+	  enable_shared=yes
+	fi
+      done
+      IFS="$lt_save_ifs"
+      ;;
+    esac
 else
-  { { echo "$as_me:$LINENO: error: cannot find gif headers" >&5
-echo "$as_me: error: cannot find gif headers" >&2;}
-   { (exit 1); exit 1; }; }
+  enable_shared=yes
 fi
 
 
-      ALL_INC="$GIF_INC $ALL_INC"
-    else
-        { { echo "$as_me:$LINENO: error: cannot find gif headers in $GIF_DIR" >&5
-echo "$as_me: error: cannot find gif headers in $GIF_DIR" >&2;}
-   { (exit 1); exit 1; }; }
-    fi
-    GIF_ENABLED="-DUSE_GIF"
-else
 
 
-  echo "$as_me:$LINENO: checking for DGifOpenFileHandle in -lgif" >&5
-echo $ECHO_N "checking for DGifOpenFileHandle in -lgif... $ECHO_C" >&6
-if test "${ac_cv_lib_gif_DGifOpenFileHandle+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-lgif  $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
 
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char DGifOpenFileHandle ();
-int
-main ()
-{
-DGifOpenFileHandle ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_gif_DGifOpenFileHandle=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
 
-ac_cv_lib_gif_DGifOpenFileHandle=no
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_gif_DGifOpenFileHandle" >&5
-echo "${ECHO_T}$ac_cv_lib_gif_DGifOpenFileHandle" >&6
-if test $ac_cv_lib_gif_DGifOpenFileHandle = yes; then
-  GIF_LIB="-lgif"
-fi
 
-  if test "${ac_cv_header_gif_lib_h+set}" = set; then
-  echo "$as_me:$LINENO: checking for gif_lib.h" >&5
-echo $ECHO_N "checking for gif_lib.h... $ECHO_C" >&6
-if test "${ac_cv_header_gif_lib_h+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-fi
-echo "$as_me:$LINENO: result: $ac_cv_header_gif_lib_h" >&5
-echo "${ECHO_T}$ac_cv_header_gif_lib_h" >&6
-else
-  # Is the header compilable?
-echo "$as_me:$LINENO: checking gif_lib.h usability" >&5
-echo $ECHO_N "checking gif_lib.h usability... $ECHO_C" >&6
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
-#include <gif_lib.h>
-_ACEOF
-rm -f conftest.$ac_objext
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest.$ac_objext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_header_compiler=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
 
-ac_header_compiler=no
-fi
-rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
-echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
-echo "${ECHO_T}$ac_header_compiler" >&6
 
-# Is the header present?
-echo "$as_me:$LINENO: checking gif_lib.h presence" >&5
-echo $ECHO_N "checking gif_lib.h presence... $ECHO_C" >&6
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#include <gif_lib.h>
-_ACEOF
-if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5
-  (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } >/dev/null; then
-  if test -s conftest.err; then
-    ac_cpp_err=$ac_c_preproc_warn_flag
-    ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
-  else
-    ac_cpp_err=
-  fi
-else
-  ac_cpp_err=yes
-fi
-if test -z "$ac_cpp_err"; then
-  ac_header_preproc=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
 
-  ac_header_preproc=no
-fi
-rm -f conftest.err conftest.$ac_ext
-echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
-echo "${ECHO_T}$ac_header_preproc" >&6
 
-# So?  What about this header?
-case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
-  yes:no: )
-    { echo "$as_me:$LINENO: WARNING: gif_lib.h: accepted by the compiler, rejected by the preprocessor!" >&5
-echo "$as_me: WARNING: gif_lib.h: accepted by the compiler, rejected by the preprocessor!" >&2;}
-    { echo "$as_me:$LINENO: WARNING: gif_lib.h: proceeding with the compiler's result" >&5
-echo "$as_me: WARNING: gif_lib.h: proceeding with the compiler's result" >&2;}
-    ac_header_preproc=yes
-    ;;
-  no:yes:* )
-    { echo "$as_me:$LINENO: WARNING: gif_lib.h: present but cannot be compiled" >&5
-echo "$as_me: WARNING: gif_lib.h: present but cannot be compiled" >&2;}
-    { echo "$as_me:$LINENO: WARNING: gif_lib.h:     check for missing prerequisite headers?" >&5
-echo "$as_me: WARNING: gif_lib.h:     check for missing prerequisite headers?" >&2;}
-    { echo "$as_me:$LINENO: WARNING: gif_lib.h: see the Autoconf documentation" >&5
-echo "$as_me: WARNING: gif_lib.h: see the Autoconf documentation" >&2;}
-    { echo "$as_me:$LINENO: WARNING: gif_lib.h:     section \"Present But Cannot Be Compiled\"" >&5
-echo "$as_me: WARNING: gif_lib.h:     section \"Present But Cannot Be Compiled\"" >&2;}
-    { echo "$as_me:$LINENO: WARNING: gif_lib.h: proceeding with the preprocessor's result" >&5
-echo "$as_me: WARNING: gif_lib.h: proceeding with the preprocessor's result" >&2;}
-    { echo "$as_me:$LINENO: WARNING: gif_lib.h: in the future, the compiler will take precedence" >&5
-echo "$as_me: WARNING: gif_lib.h: in the future, the compiler will take precedence" >&2;}
-    (
-      cat <<\_ASBOX
-## ------------------------------------------ ##
-## Report this to the AC_PACKAGE_NAME lists.  ##
-## ------------------------------------------ ##
-_ASBOX
-    ) |
-      sed "s/^/$as_me: WARNING:     /" >&2
-    ;;
-esac
-echo "$as_me:$LINENO: checking for gif_lib.h" >&5
-echo $ECHO_N "checking for gif_lib.h... $ECHO_C" >&6
-if test "${ac_cv_header_gif_lib_h+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+# Check whether --with-pic was given.
+if test "${with_pic+set}" = set; then :
+  withval=$with_pic; lt_p=${PACKAGE-default}
+    case $withval in
+    yes|no) pic_mode=$withval ;;
+    *)
+      pic_mode=default
+      # Look at the argument we got.  We use all the common list separators.
+      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
+      for lt_pkg in $withval; do
+	IFS="$lt_save_ifs"
+	if test "X$lt_pkg" = "X$lt_p"; then
+	  pic_mode=yes
+	fi
+      done
+      IFS="$lt_save_ifs"
+      ;;
+    esac
 else
-  ac_cv_header_gif_lib_h=$ac_header_preproc
+  pic_mode=default
 fi
-echo "$as_me:$LINENO: result: $ac_cv_header_gif_lib_h" >&5
-echo "${ECHO_T}$ac_cv_header_gif_lib_h" >&6
 
-fi
-if test $ac_cv_header_gif_lib_h = yes; then
-  :
-else
-  { { echo "$as_me:$LINENO: error: cannot find gif headers in system path" >&5
-echo "$as_me: error: cannot find gif headers in system path" >&2;}
-   { (exit 1); exit 1; }; }
-fi
 
+test -z "$pic_mode" && pic_mode=default
 
-  if test -n "$GIF_LIB" ; then
-    echo "$as_me:$LINENO: result:         using libgif from system libs." >&5
-echo "${ECHO_T}        using libgif from system libs." >&6
-  else
-    { { echo "$as_me:$LINENO: error: GIF (libgif) library cannot be found. install or reconfigure with --with-gif=DIR" >&5
-echo "$as_me: error: GIF (libgif) library cannot be found. install or reconfigure with --with-gif=DIR" >&2;}
-   { (exit 1); exit 1; }; }
-  fi
-  GIF_ENABLED="-DUSE_GIF"
-fi
 
-ALL_ENABLED="$GIF_ENABLED $ALL_ENABLED"
-GIF_ENABLED=$GIF_ENABLED
 
-GIF_INC=$GIF_INC
 
-GIF_LIB=$GIF_LIB
 
 
 
+  # Check whether --enable-fast-install was given.
+if test "${enable_fast_install+set}" = set; then :
+  enableval=$enable_fast_install; p=${PACKAGE-default}
+    case $enableval in
+    yes) enable_fast_install=yes ;;
+    no) enable_fast_install=no ;;
+    *)
+      enable_fast_install=no
+      # Look at the argument we got.  We use all the common list separators.
+      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
+      for pkg in $enableval; do
+	IFS="$lt_save_ifs"
+	if test "X$pkg" = "X$p"; then
+	  enable_fast_install=yes
+	fi
+      done
+      IFS="$lt_save_ifs"
+      ;;
+    esac
+else
+  enable_fast_install=yes
+fi
 
-unset ac_cv_lib_jpeg_jpeg_read_header
 
-{ echo "$as_me:$LINENO: checking whether we should include JPEG support..." >&5
-echo "$as_me: checking whether we should include JPEG support..." >&6;}
 
-# Check whether --with-jpeg or --without-jpeg was given.
-if test "${with_jpeg+set}" = set; then
-  withval="$with_jpeg"
 
-fi;
 
-if test -n "$with_jpeg" -a "$with_jpeg" != "yes" ; then
 
 
-  if test -z "$with_jpeg" || echo "$with_jpeg" | grep '^/' >/dev/null ; then
-    JPEG_DIR="$with_jpeg"
-  else
-    JPEG_DIR="`pwd`/$with_jpeg"
-  fi
 
-  test -f $JPEG_DIR/include/jpeg/jpeglib.h && JPEG_INCLUDE="$JPEG_DIR/include/jpeg"
-  test -f $JPEG_DIR/include/jpeglib.h && JPEG_INCLUDE="$JPEG_DIR/include"
-  test -f $JPEG_DIR/lib/jpeglib.h && JPEG_INCLUDE="$JPEG_DIR/lib"
-  test -f $JPEG_DIR/jpeglib.h && JPEG_INCLUDE="$JPEG_DIR"
 
-  test -f $JPEG_DIR/lib/libjpeg.a && JPEG_LIBDIR="$JPEG_DIR/lib"
-  test -f $JPEG_DIR/lib64/libjpeg.a && JPEG_LIBDIR="$JPEG_DIR/lib64"
-  test -f $JPEG_DIR/libjpeg.a && JPEG_LIBDIR="$JPEG_DIR"
 
-  test -f $JPEG_DIR/lib/libjpeg.so -o -f $JPEG_DIR/lib/libjpeg.sl -o -f $JPEG_DIR/lib/libjpeg.dylib && JPEG_LIBDIR="$JPEG_DIR/lib"
-  test -f $JPEG_DIR/lib64/libjpeg.so -o -f $JPEG_DIR/lib64/libjpeg.sl && JPEG_LIBDIR="$JPEG_DIR/lib64"
-  test -f $JPEG_DIR/libjpeg.so -o -f $JPEG_DIR/libjpeg.sl -o -f $JPEG_DIR/libjpeg.dylib && JPEG_LIBDIR="$JPEG_DIR"
 
-  if test -n "$JPEG_INCLUDE" -a -n "$JPEG_LIBDIR" ; then
-      JPEG_INC=-I$JPEG_INCLUDE
-      JPEG_LIB="-L$JPEG_LIBDIR -ljpeg"
+# This can be used to rebuild libtool when needed
+LIBTOOL_DEPS="$ltmain"
 
-  if test ""$JPEG_LIBDIR"" != "/usr/lib"; then
+# Always use our own libtool.
+LIBTOOL='$(SHELL) $(top_builddir)/libtool'
 
-  if test -z ""$JPEG_LIBDIR"" || echo ""$JPEG_LIBDIR"" | grep '^/' >/dev/null ; then
-    ai_p=""$JPEG_LIBDIR""
-  else
-    ai_p="`pwd`/"$JPEG_LIBDIR""
-  fi
 
 
-  unique=`echo $ac_n "$ai_p$ac_c" | tr -c -d a-zA-Z0-9`
-  cmd="echo $ac_n \"\$LIBPATH$unique$ac_c\""
-  if test -n "$unique" && test "`eval $cmd`" = "" ; then
-    eval "LIBPATH$unique=set"
 
-      EXTRA_LIBS="$EXTRA_LIBS -L$ai_p"
-        RPATHS="$RPATHS ${ld_runpath_switch}$ai_p"
 
-  fi
 
-  fi
 
-  else
-        { { echo "$as_me:$LINENO: error: \"Could not find jpeglib.h or libjpeg.a/libjpeg.so/libjpeg.dylib in $JPEG_DIR.\"" >&5
-echo "$as_me: error: \"Could not find jpeglib.h or libjpeg.a/libjpeg.so/libjpeg.dylib in $JPEG_DIR.\"" >&2;}
-   { (exit 1); exit 1; }; }
-  fi
 
 
-    _cppflags="$CPPFLAGS"
-    _ldflags="$LDFLAGS"
-    _libs="$LIBS"
-    CPPFLAGS="$JPEG_INC $CPPFLAGS"
-    LDFLAGS="$JPEG_LIB $LDFLAGS"
 
-echo "$as_me:$LINENO: checking for jpeg_read_header in -ljpeg" >&5
-echo $ECHO_N "checking for jpeg_read_header in -ljpeg... $ECHO_C" >&6
-if test "${ac_cv_lib_jpeg_jpeg_read_header+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-ljpeg  $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
 
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char jpeg_read_header ();
-int
-main ()
-{
-jpeg_read_header ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_jpeg_jpeg_read_header=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
 
-ac_cv_lib_jpeg_jpeg_read_header=no
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_jpeg_jpeg_read_header" >&5
-echo "${ECHO_T}$ac_cv_lib_jpeg_jpeg_read_header" >&6
-if test $ac_cv_lib_jpeg_jpeg_read_header = yes; then
-  cat >>confdefs.h <<_ACEOF
-#define HAVE_LIBJPEG 1
-_ACEOF
 
-  LIBS="-ljpeg $LIBS"
 
-else
-  { { echo "$as_me:$LINENO: error: \"cannot link with libjpeg\"" >&5
-echo "$as_me: error: \"cannot link with libjpeg\"" >&2;}
-   { (exit 1); exit 1; }; }
-fi
 
-    if test "${ac_cv_header_jpeglib_h+set}" = set; then
-  echo "$as_me:$LINENO: checking for jpeglib.h" >&5
-echo $ECHO_N "checking for jpeglib.h... $ECHO_C" >&6
-if test "${ac_cv_header_jpeglib_h+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-fi
-echo "$as_me:$LINENO: result: $ac_cv_header_jpeglib_h" >&5
-echo "${ECHO_T}$ac_cv_header_jpeglib_h" >&6
-else
-  # Is the header compilable?
-echo "$as_me:$LINENO: checking jpeglib.h usability" >&5
-echo $ECHO_N "checking jpeglib.h usability... $ECHO_C" >&6
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
-#include <jpeglib.h>
-_ACEOF
-rm -f conftest.$ac_objext
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest.$ac_objext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_header_compiler=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
 
-ac_header_compiler=no
-fi
-rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
-echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
-echo "${ECHO_T}$ac_header_compiler" >&6
 
-# Is the header present?
-echo "$as_me:$LINENO: checking jpeglib.h presence" >&5
-echo $ECHO_N "checking jpeglib.h presence... $ECHO_C" >&6
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#include <jpeglib.h>
-_ACEOF
-if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5
-  (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } >/dev/null; then
-  if test -s conftest.err; then
-    ac_cpp_err=$ac_c_preproc_warn_flag
-    ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
-  else
-    ac_cpp_err=
-  fi
-else
-  ac_cpp_err=yes
-fi
-if test -z "$ac_cpp_err"; then
-  ac_header_preproc=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
 
-  ac_header_preproc=no
-fi
-rm -f conftest.err conftest.$ac_ext
-echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
-echo "${ECHO_T}$ac_header_preproc" >&6
 
-# So?  What about this header?
-case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
-  yes:no: )
-    { echo "$as_me:$LINENO: WARNING: jpeglib.h: accepted by the compiler, rejected by the preprocessor!" >&5
-echo "$as_me: WARNING: jpeglib.h: accepted by the compiler, rejected by the preprocessor!" >&2;}
-    { echo "$as_me:$LINENO: WARNING: jpeglib.h: proceeding with the compiler's result" >&5
-echo "$as_me: WARNING: jpeglib.h: proceeding with the compiler's result" >&2;}
-    ac_header_preproc=yes
-    ;;
-  no:yes:* )
-    { echo "$as_me:$LINENO: WARNING: jpeglib.h: present but cannot be compiled" >&5
-echo "$as_me: WARNING: jpeglib.h: present but cannot be compiled" >&2;}
-    { echo "$as_me:$LINENO: WARNING: jpeglib.h:     check for missing prerequisite headers?" >&5
-echo "$as_me: WARNING: jpeglib.h:     check for missing prerequisite headers?" >&2;}
-    { echo "$as_me:$LINENO: WARNING: jpeglib.h: see the Autoconf documentation" >&5
-echo "$as_me: WARNING: jpeglib.h: see the Autoconf documentation" >&2;}
-    { echo "$as_me:$LINENO: WARNING: jpeglib.h:     section \"Present But Cannot Be Compiled\"" >&5
-echo "$as_me: WARNING: jpeglib.h:     section \"Present But Cannot Be Compiled\"" >&2;}
-    { echo "$as_me:$LINENO: WARNING: jpeglib.h: proceeding with the preprocessor's result" >&5
-echo "$as_me: WARNING: jpeglib.h: proceeding with the preprocessor's result" >&2;}
-    { echo "$as_me:$LINENO: WARNING: jpeglib.h: in the future, the compiler will take precedence" >&5
-echo "$as_me: WARNING: jpeglib.h: in the future, the compiler will take precedence" >&2;}
-    (
-      cat <<\_ASBOX
-## ------------------------------------------ ##
-## Report this to the AC_PACKAGE_NAME lists.  ##
-## ------------------------------------------ ##
-_ASBOX
-    ) |
-      sed "s/^/$as_me: WARNING:     /" >&2
-    ;;
-esac
-echo "$as_me:$LINENO: checking for jpeglib.h" >&5
-echo $ECHO_N "checking for jpeglib.h... $ECHO_C" >&6
-if test "${ac_cv_header_jpeglib_h+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_cv_header_jpeglib_h=$ac_header_preproc
-fi
-echo "$as_me:$LINENO: result: $ac_cv_header_jpeglib_h" >&5
-echo "${ECHO_T}$ac_cv_header_jpeglib_h" >&6
 
-fi
-if test $ac_cv_header_jpeglib_h = yes; then
-  :
-else
-  { { echo "$as_me:$LINENO: error: \"cannot find jpeg headers\"" >&5
-echo "$as_me: error: \"cannot find jpeg headers\"" >&2;}
-   { (exit 1); exit 1; }; }
-fi
 
 
-    JPEG_ENABLED="-DUSE_JPEG"
-    CPPFLAGS=$_cppflags
-    LDFLAGS=$_ldflags
-    LIBS=$_libs
-    echo "$as_me:$LINENO: result:         using libjpeg from system $JPEG_LIB" >&5
-echo "${ECHO_T}        using libjpeg from system $JPEG_LIB" >&6
 
-else
 
 
-echo "$as_me:$LINENO: checking for jpeg_read_header in -ljpeg" >&5
-echo $ECHO_N "checking for jpeg_read_header in -ljpeg... $ECHO_C" >&6
-if test "${ac_cv_lib_jpeg_jpeg_read_header+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-ljpeg  $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
 
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char jpeg_read_header ();
-int
-main ()
-{
-jpeg_read_header ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_jpeg_jpeg_read_header=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
 
-ac_cv_lib_jpeg_jpeg_read_header=no
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_jpeg_jpeg_read_header" >&5
-echo "${ECHO_T}$ac_cv_lib_jpeg_jpeg_read_header" >&6
-if test $ac_cv_lib_jpeg_jpeg_read_header = yes; then
-  cat >>confdefs.h <<_ACEOF
-#define HAVE_LIBJPEG 1
-_ACEOF
 
-  LIBS="-ljpeg $LIBS"
 
-else
-  { { echo "$as_me:$LINENO: error: \"cannot link with libjpeg\"" >&5
-echo "$as_me: error: \"cannot link with libjpeg\"" >&2;}
-   { (exit 1); exit 1; }; }
-fi
 
-    if test "${ac_cv_header_jpeglib_h+set}" = set; then
-  echo "$as_me:$LINENO: checking for jpeglib.h" >&5
-echo $ECHO_N "checking for jpeglib.h... $ECHO_C" >&6
-if test "${ac_cv_header_jpeglib_h+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+test -z "$LN_S" && LN_S="ln -s"
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+if test -n "${ZSH_VERSION+set}" ; then
+   setopt NO_GLOB_SUBST
 fi
-echo "$as_me:$LINENO: result: $ac_cv_header_jpeglib_h" >&5
-echo "${ECHO_T}$ac_cv_header_jpeglib_h" >&6
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for objdir" >&5
+$as_echo_n "checking for objdir... " >&6; }
+if ${lt_cv_objdir+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
-  # Is the header compilable?
-echo "$as_me:$LINENO: checking jpeglib.h usability" >&5
-echo $ECHO_N "checking jpeglib.h usability... $ECHO_C" >&6
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
-#include <jpeglib.h>
-_ACEOF
-rm -f conftest.$ac_objext
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest.$ac_objext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_header_compiler=yes
+  rm -f .libs 2>/dev/null
+mkdir .libs 2>/dev/null
+if test -d .libs; then
+  lt_cv_objdir=.libs
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-ac_header_compiler=no
+  # MS-DOS does not allow filenames that begin with a dot.
+  lt_cv_objdir=_libs
+fi
+rmdir .libs 2>/dev/null
 fi
-rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
-echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
-echo "${ECHO_T}$ac_header_compiler" >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_objdir" >&5
+$as_echo "$lt_cv_objdir" >&6; }
+objdir=$lt_cv_objdir
 
-# Is the header present?
-echo "$as_me:$LINENO: checking jpeglib.h presence" >&5
-echo $ECHO_N "checking jpeglib.h presence... $ECHO_C" >&6
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#include <jpeglib.h>
+
+
+
+
+cat >>confdefs.h <<_ACEOF
+#define LT_OBJDIR "$lt_cv_objdir/"
 _ACEOF
-if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5
-  (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } >/dev/null; then
-  if test -s conftest.err; then
-    ac_cpp_err=$ac_c_preproc_warn_flag
-    ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
-  else
-    ac_cpp_err=
+
+
+
+
+case $host_os in
+aix3*)
+  # AIX sometimes has problems with the GCC collect2 program.  For some
+  # reason, if we set the COLLECT_NAMES environment variable, the problems
+  # vanish in a puff of smoke.
+  if test "X${COLLECT_NAMES+set}" != Xset; then
+    COLLECT_NAMES=
+    export COLLECT_NAMES
   fi
-else
-  ac_cpp_err=yes
-fi
-if test -z "$ac_cpp_err"; then
-  ac_header_preproc=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
+  ;;
+esac
 
-  ac_header_preproc=no
-fi
-rm -f conftest.err conftest.$ac_ext
-echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
-echo "${ECHO_T}$ac_header_preproc" >&6
+# Global variables:
+ofile=libtool
+can_build_shared=yes
 
-# So?  What about this header?
-case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
-  yes:no: )
-    { echo "$as_me:$LINENO: WARNING: jpeglib.h: accepted by the compiler, rejected by the preprocessor!" >&5
-echo "$as_me: WARNING: jpeglib.h: accepted by the compiler, rejected by the preprocessor!" >&2;}
-    { echo "$as_me:$LINENO: WARNING: jpeglib.h: proceeding with the compiler's result" >&5
-echo "$as_me: WARNING: jpeglib.h: proceeding with the compiler's result" >&2;}
-    ac_header_preproc=yes
-    ;;
-  no:yes:* )
-    { echo "$as_me:$LINENO: WARNING: jpeglib.h: present but cannot be compiled" >&5
-echo "$as_me: WARNING: jpeglib.h: present but cannot be compiled" >&2;}
-    { echo "$as_me:$LINENO: WARNING: jpeglib.h:     check for missing prerequisite headers?" >&5
-echo "$as_me: WARNING: jpeglib.h:     check for missing prerequisite headers?" >&2;}
-    { echo "$as_me:$LINENO: WARNING: jpeglib.h: see the Autoconf documentation" >&5
-echo "$as_me: WARNING: jpeglib.h: see the Autoconf documentation" >&2;}
-    { echo "$as_me:$LINENO: WARNING: jpeglib.h:     section \"Present But Cannot Be Compiled\"" >&5
-echo "$as_me: WARNING: jpeglib.h:     section \"Present But Cannot Be Compiled\"" >&2;}
-    { echo "$as_me:$LINENO: WARNING: jpeglib.h: proceeding with the preprocessor's result" >&5
-echo "$as_me: WARNING: jpeglib.h: proceeding with the preprocessor's result" >&2;}
-    { echo "$as_me:$LINENO: WARNING: jpeglib.h: in the future, the compiler will take precedence" >&5
-echo "$as_me: WARNING: jpeglib.h: in the future, the compiler will take precedence" >&2;}
-    (
-      cat <<\_ASBOX
-## ------------------------------------------ ##
-## Report this to the AC_PACKAGE_NAME lists.  ##
-## ------------------------------------------ ##
-_ASBOX
-    ) |
-      sed "s/^/$as_me: WARNING:     /" >&2
-    ;;
+# All known linkers require a `.a' archive for static linking (except MSVC,
+# which needs '.lib').
+libext=a
+
+with_gnu_ld="$lt_cv_prog_gnu_ld"
+
+old_CC="$CC"
+old_CFLAGS="$CFLAGS"
+
+# Set sane defaults for various variables
+test -z "$CC" && CC=cc
+test -z "$LTCC" && LTCC=$CC
+test -z "$LTCFLAGS" && LTCFLAGS=$CFLAGS
+test -z "$LD" && LD=ld
+test -z "$ac_objext" && ac_objext=o
+
+for cc_temp in $compiler""; do
+  case $cc_temp in
+    compile | *[\\/]compile | ccache | *[\\/]ccache ) ;;
+    distcc | *[\\/]distcc | purify | *[\\/]purify ) ;;
+    \-*) ;;
+    *) break;;
+  esac
+done
+cc_basename=`$ECHO "$cc_temp" | $SED "s%.*/%%; s%^$host_alias-%%"`
+
+
+# Only perform the check for file, if the check method requires it
+test -z "$MAGIC_CMD" && MAGIC_CMD=file
+case $deplibs_check_method in
+file_magic*)
+  if test "$file_magic_cmd" = '$MAGIC_CMD'; then
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ${ac_tool_prefix}file" >&5
+$as_echo_n "checking for ${ac_tool_prefix}file... " >&6; }
+if ${lt_cv_path_MAGIC_CMD+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  case $MAGIC_CMD in
+[\\/*] |  ?:[\\/]*)
+  lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path.
+  ;;
+*)
+  lt_save_MAGIC_CMD="$MAGIC_CMD"
+  lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
+  ac_dummy="/usr/bin$PATH_SEPARATOR$PATH"
+  for ac_dir in $ac_dummy; do
+    IFS="$lt_save_ifs"
+    test -z "$ac_dir" && ac_dir=.
+    if test -f $ac_dir/${ac_tool_prefix}file; then
+      lt_cv_path_MAGIC_CMD="$ac_dir/${ac_tool_prefix}file"
+      if test -n "$file_magic_test_file"; then
+	case $deplibs_check_method in
+	"file_magic "*)
+	  file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"`
+	  MAGIC_CMD="$lt_cv_path_MAGIC_CMD"
+	  if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null |
+	    $EGREP "$file_magic_regex" > /dev/null; then
+	    :
+	  else
+	    cat <<_LT_EOF 1>&2
+
+*** Warning: the command libtool uses to detect shared libraries,
+*** $file_magic_cmd, produces output that libtool cannot recognize.
+*** The result is that libtool may fail to recognize shared libraries
+*** as such.  This will affect the creation of libtool libraries that
+*** depend on shared libraries, but programs linked with such libtool
+*** libraries will work regardless of this problem.  Nevertheless, you
+*** may want to report the problem to your system manager and/or to
+*** bug-libtool at gnu.org
+
+_LT_EOF
+	  fi ;;
+	esac
+      fi
+      break
+    fi
+  done
+  IFS="$lt_save_ifs"
+  MAGIC_CMD="$lt_save_MAGIC_CMD"
+  ;;
 esac
-echo "$as_me:$LINENO: checking for jpeglib.h" >&5
-echo $ECHO_N "checking for jpeglib.h... $ECHO_C" >&6
-if test "${ac_cv_header_jpeglib_h+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+fi
+
+MAGIC_CMD="$lt_cv_path_MAGIC_CMD"
+if test -n "$MAGIC_CMD"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MAGIC_CMD" >&5
+$as_echo "$MAGIC_CMD" >&6; }
 else
-  ac_cv_header_jpeglib_h=$ac_header_preproc
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
-echo "$as_me:$LINENO: result: $ac_cv_header_jpeglib_h" >&5
-echo "${ECHO_T}$ac_cv_header_jpeglib_h" >&6
 
+
+
+
+
+if test -z "$lt_cv_path_MAGIC_CMD"; then
+  if test -n "$ac_tool_prefix"; then
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for file" >&5
+$as_echo_n "checking for file... " >&6; }
+if ${lt_cv_path_MAGIC_CMD+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  case $MAGIC_CMD in
+[\\/*] |  ?:[\\/]*)
+  lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path.
+  ;;
+*)
+  lt_save_MAGIC_CMD="$MAGIC_CMD"
+  lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
+  ac_dummy="/usr/bin$PATH_SEPARATOR$PATH"
+  for ac_dir in $ac_dummy; do
+    IFS="$lt_save_ifs"
+    test -z "$ac_dir" && ac_dir=.
+    if test -f $ac_dir/file; then
+      lt_cv_path_MAGIC_CMD="$ac_dir/file"
+      if test -n "$file_magic_test_file"; then
+	case $deplibs_check_method in
+	"file_magic "*)
+	  file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"`
+	  MAGIC_CMD="$lt_cv_path_MAGIC_CMD"
+	  if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null |
+	    $EGREP "$file_magic_regex" > /dev/null; then
+	    :
+	  else
+	    cat <<_LT_EOF 1>&2
+
+*** Warning: the command libtool uses to detect shared libraries,
+*** $file_magic_cmd, produces output that libtool cannot recognize.
+*** The result is that libtool may fail to recognize shared libraries
+*** as such.  This will affect the creation of libtool libraries that
+*** depend on shared libraries, but programs linked with such libtool
+*** libraries will work regardless of this problem.  Nevertheless, you
+*** may want to report the problem to your system manager and/or to
+*** bug-libtool at gnu.org
+
+_LT_EOF
+	  fi ;;
+	esac
+      fi
+      break
+    fi
+  done
+  IFS="$lt_save_ifs"
+  MAGIC_CMD="$lt_save_MAGIC_CMD"
+  ;;
+esac
 fi
-if test $ac_cv_header_jpeglib_h = yes; then
-  :
+
+MAGIC_CMD="$lt_cv_path_MAGIC_CMD"
+if test -n "$MAGIC_CMD"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MAGIC_CMD" >&5
+$as_echo "$MAGIC_CMD" >&6; }
 else
-  { { echo "$as_me:$LINENO: error: \"cannot find jpeg headers\"" >&5
-echo "$as_me: error: \"cannot find jpeg headers\"" >&2;}
-   { (exit 1); exit 1; }; }
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
 
 
-    JPEG_ENABLED="-DUSE_JPEG"
-    JPEG_LIB="-ljpeg"
-    echo "$as_me:$LINENO: result:         using libjpeg from system libs." >&5
-echo "${ECHO_T}        using libjpeg from system libs." >&6
+  else
+    MAGIC_CMD=:
+  fi
 fi
 
-JPEG_ENABLED=$JPEG_ENABLED
+  fi
+  ;;
+esac
 
-JPEG_INC=$JPEG_INC
+# Use C for the default configuration in the libtool script
 
-JPEG_LIB=$JPEG_LIB
+lt_save_CC="$CC"
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
 
+# Source file extension for C test sources.
+ac_ext=c
 
-unset ac_cv_lib_Xpm_XpmFreeXpmImage
+# Object file extension for compiled C test sources.
+objext=o
+objext=$objext
 
+# Code to be used in simple compile tests
+lt_simple_compile_test_code="int some_variable = 0;"
 
-# Check whether --with-xpm or --without-xpm was given.
-if test "${with_xpm+set}" = set; then
-  withval="$with_xpm"
-  XPM_DIR=$withval
-else
-  XPM_DIR=''
-fi;
+# Code to be used in simple link tests
+lt_simple_link_test_code='int main(){return(0);}'
 
-if test "$with_xpm" != "no" ; then
 
 
-  if test -z "$XPM_DIR" || echo "$XPM_DIR" | grep '^/' >/dev/null ; then
-    XPM_DIR="$XPM_DIR"
-  else
-    XPM_DIR="`pwd`/$XPM_DIR"
-  fi
 
-  { echo "$as_me:$LINENO: checking where libXpm is installed..." >&5
-echo "$as_me: checking where libXpm is installed..." >&6;}
-  XPM_LIB=''
 
-  test -f $XPM_DIR/lib/libXpm.a -o -f $XPM_DIR/lib/libXpm.so -o -f $XPM_DIR/lib/libXpm.sl -o -f $XPM_DIR/lib/libXpm.dylib && XPM_LIBDIR="$XPM_DIR/lib"
-  test -f $XPM_DIR/lib64/libXpm.a -o -f $XPM_DIR/lib64/libXpm.so -o -f $XPM_DIR/lib64/libXpm.sl && XPM_LIBDIR="$XPM_DIR/lib64"
-  test -f $XPM_DIR/libXpm.a -o -f $XPM_DIR/libXpm.so -o -f $XPM_DIR/libXpm.sl -o -f $XPM_DIR/libXpm.dylib && XPM_LIBDIR="$XPM_DIR"
 
-  if test -n "$XPM_LIBDIR" ; then
 
-    XPM_LIB="-L$XPM_LIBDIR -lXpm -lX11"
-    echo "$as_me:$LINENO: result:         using libXpm from $XPM_LIB" >&5
-echo "${ECHO_T}        using libXpm from $XPM_LIB" >&6
+# If no C compiler was specified, use CC.
+LTCC=${LTCC-"$CC"}
 
-  if test ""$XPM_LIBDIR"" != "/usr/lib"; then
+# If no C compiler flags were specified, use CFLAGS.
+LTCFLAGS=${LTCFLAGS-"$CFLAGS"}
 
-  if test -z ""$XPM_LIBDIR"" || echo ""$XPM_LIBDIR"" | grep '^/' >/dev/null ; then
-    ai_p=""$XPM_LIBDIR""
-  else
-    ai_p="`pwd`/"$XPM_LIBDIR""
-  fi
+# Allow CC to be a program name with arguments.
+compiler=$CC
 
+# Save the default compiler, since it gets overwritten when the other
+# tags are being tested, and _LT_TAGVAR(compiler, []) is a NOP.
+compiler_DEFAULT=$CC
 
-  unique=`echo $ac_n "$ai_p$ac_c" | tr -c -d a-zA-Z0-9`
-  cmd="echo $ac_n \"\$LIBPATH$unique$ac_c\""
-  if test -n "$unique" && test "`eval $cmd`" = "" ; then
-    eval "LIBPATH$unique=set"
+# save warnings/boilerplate of simple test code
+ac_outfile=conftest.$ac_objext
+echo "$lt_simple_compile_test_code" >conftest.$ac_ext
+eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
+_lt_compiler_boilerplate=`cat conftest.err`
+$RM conftest*
 
-      EXTRA_LIBS="$EXTRA_LIBS -L$ai_p"
-        RPATHS="$RPATHS ${ld_runpath_switch}$ai_p"
+ac_outfile=conftest.$ac_objext
+echo "$lt_simple_link_test_code" >conftest.$ac_ext
+eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
+_lt_linker_boilerplate=`cat conftest.err`
+$RM -r conftest*
 
-  fi
 
-  fi
+if test -n "$compiler"; then
 
+lt_prog_compiler_no_builtin_flag=
 
-  else
+if test "$GCC" = yes; then
+  case $cc_basename in
+  nvcc*)
+    lt_prog_compiler_no_builtin_flag=' -Xcompiler -fno-builtin' ;;
+  *)
+    lt_prog_compiler_no_builtin_flag=' -fno-builtin' ;;
+  esac
 
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler supports -fno-rtti -fno-exceptions" >&5
+$as_echo_n "checking if $compiler supports -fno-rtti -fno-exceptions... " >&6; }
+if ${lt_cv_prog_compiler_rtti_exceptions+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  lt_cv_prog_compiler_rtti_exceptions=no
+   ac_outfile=conftest.$ac_objext
+   echo "$lt_simple_compile_test_code" > conftest.$ac_ext
+   lt_compiler_flag="-fno-rtti -fno-exceptions"
+   # Insert the option either (1) after the last *FLAGS variable, or
+   # (2) before a word containing "conftest.", or (3) at the end.
+   # Note that $ac_compile itself does not contain backslashes and begins
+   # with a dollar sign (not a hyphen), so the echo should work correctly.
+   # The option is referenced via a variable to avoid confusing sed.
+   lt_compile=`echo "$ac_compile" | $SED \
+   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
+   -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
+   -e 's:$: $lt_compiler_flag:'`
+   (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5)
+   (eval "$lt_compile" 2>conftest.err)
+   ac_status=$?
+   cat conftest.err >&5
+   echo "$as_me:$LINENO: \$? = $ac_status" >&5
+   if (exit $ac_status) && test -s "$ac_outfile"; then
+     # The compiler can only warn and ignore the option if not recognized
+     # So say no if there are warnings other than the usual output.
+     $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' >conftest.exp
+     $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
+     if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then
+       lt_cv_prog_compiler_rtti_exceptions=yes
+     fi
+   fi
+   $RM conftest*
 
-    echo "$as_me:$LINENO: checking for XpmFreeXpmImage in -lXpm" >&5
-echo $ECHO_N "checking for XpmFreeXpmImage in -lXpm... $ECHO_C" >&6
-if test "${ac_cv_lib_Xpm_XpmFreeXpmImage+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-lXpm -lX11 $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_rtti_exceptions" >&5
+$as_echo "$lt_cv_prog_compiler_rtti_exceptions" >&6; }
 
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char XpmFreeXpmImage ();
-int
-main ()
-{
-XpmFreeXpmImage ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_Xpm_XpmFreeXpmImage=yes
+if test x"$lt_cv_prog_compiler_rtti_exceptions" = xyes; then
+    lt_prog_compiler_no_builtin_flag="$lt_prog_compiler_no_builtin_flag -fno-rtti -fno-exceptions"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-ac_cv_lib_Xpm_XpmFreeXpmImage=no
+    :
 fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_Xpm_XpmFreeXpmImage" >&5
-echo "${ECHO_T}$ac_cv_lib_Xpm_XpmFreeXpmImage" >&6
-if test $ac_cv_lib_Xpm_XpmFreeXpmImage = yes; then
-  XPM_LIB="-lXpm -lX11"
+
 fi
 
 
-    if test -n "$XPM_LIB" ; then
-      echo "$as_me:$LINENO: result:         using libXpm from system libs." >&5
-echo "${ECHO_T}        using libXpm from system libs." >&6
-    else
-      echo "$as_me:$LINENO: result:         XPM (libXpm) library cannot be found, possibly needed for GD" >&5
-echo "${ECHO_T}        XPM (libXpm) library cannot be found, possibly needed for GD" >&6
-    fi
-  fi
 
-fi
 
 
-GD_XTRA_LIBS="$JPEG_LIB $FT_LIB $PNG_LIB $ZLIB_LIB $XPM_LIB"
 
+  lt_prog_compiler_wl=
+lt_prog_compiler_pic=
+lt_prog_compiler_static=
 
 
-unset ac_cv_lib_iconv_libiconv_open
-unset ac_cv_lib_iconv_iconv_open
-unset ac_cv_lib_c_iconv_open
+  if test "$GCC" = yes; then
+    lt_prog_compiler_wl='-Wl,'
+    lt_prog_compiler_static='-static'
+
+    case $host_os in
+      aix*)
+      # All AIX code is PIC.
+      if test "$host_cpu" = ia64; then
+	# AIX 5 now supports IA64 processor
+	lt_prog_compiler_static='-Bstatic'
+      fi
+      ;;
 
+    amigaos*)
+      case $host_cpu in
+      powerpc)
+            # see comment about AmigaOS4 .so support
+            lt_prog_compiler_pic='-fPIC'
+        ;;
+      m68k)
+            # FIXME: we need at least 68020 code to build shared libraries, but
+            # adding the `-m68020' flag to GCC prevents building anything better,
+            # like `-m68040'.
+            lt_prog_compiler_pic='-m68020 -resident32 -malways-restore-a4'
+        ;;
+      esac
+      ;;
 
-# Check whether --with-libiconv or --without-libiconv was given.
-if test "${with_libiconv+set}" = set; then
-  withval="$with_libiconv"
-  ICONV_DIR=$withval
-else
-  ICONV_DIR=''
-fi;
+    beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*)
+      # PIC is the default for these OSes.
+      ;;
 
-{ echo "$as_me:$LINENO: checking where libiconv is installed..." >&5
-echo "$as_me: checking where libiconv is installed..." >&6;}
+    mingw* | cygwin* | pw32* | os2* | cegcc*)
+      # This hack is so that the source file can tell whether it is being
+      # built for inclusion in a dll (and should export symbols for example).
+      # Although the cygwin gcc ignores -fPIC, still need this for old-style
+      # (--disable-auto-import) libraries
+      lt_prog_compiler_pic='-DDLL_EXPORT'
+      ;;
 
-ICONV_LIB=''
+    darwin* | rhapsody*)
+      # PIC is the default on this platform
+      # Common symbols not allowed in MH_DYLIB files
+      lt_prog_compiler_pic='-fno-common'
+      ;;
 
-if test -n "$ICONV_DIR" ; then
+    haiku*)
+      # PIC is the default for Haiku.
+      # The "-static" flag exists, but is broken.
+      lt_prog_compiler_static=
+      ;;
 
+    hpux*)
+      # PIC is the default for 64-bit PA HP-UX, but not for 32-bit
+      # PA HP-UX.  On IA64 HP-UX, PIC is the default but the pic flag
+      # sets the default TLS model and affects inlining.
+      case $host_cpu in
+      hppa*64*)
+	# +Z the default
+	;;
+      *)
+	lt_prog_compiler_pic='-fPIC'
+	;;
+      esac
+      ;;
 
-  if test -z "$ICONV_DIR" || echo "$ICONV_DIR" | grep '^/' >/dev/null ; then
-    ICONV_DIR="$ICONV_DIR"
-  else
-    ICONV_DIR="`pwd`/$ICONV_DIR"
-  fi
+    interix[3-9]*)
+      # Interix 3.x gcc -fpic/-fPIC options generate broken code.
+      # Instead, we relocate shared libraries at runtime.
+      ;;
 
+    msdosdjgpp*)
+      # Just because we use GCC doesn't mean we suddenly get shared libraries
+      # on systems that don't support them.
+      lt_prog_compiler_can_build_shared=no
+      enable_shared=no
+      ;;
 
-  test -f $ICONV_DIR/include/iconv.h && ICONV_LIBDIR="$ICONV_DIR/lib" && ICONV_INCDIR="$ICONV_DIR/include"
-  test -f $ICONV_DIR/lib/libiconv.a -o -f $ICONV_DIR/lib/libiconv.so -o -f $ICONV_DIR/lib/libiconv.sl -o -f $ICONV_DIR/lib/libiconv.dylib && ICONV_LIBDIR="$ICONV_DIR/lib" && ICONV_INCDIR="$ICONV_DIR/include"
-  test -f $ICONV_DIR/lib64/libiconv.a -o -f $ICONV_DIR/lib64/libiconv.so -o -f $ICONV_DIR/lib64/libiconv.sl && ICONV_LIBDIR="$ICONV_DIR/lib64" && ICONV_INCDIR="$ICONV_DIR/include"
+    *nto* | *qnx*)
+      # QNX uses GNU C++, but need to define -shared option too, otherwise
+      # it will coredump.
+      lt_prog_compiler_pic='-fPIC -shared'
+      ;;
 
-            echo "$as_me:$LINENO: checking for iconv_open in -lc" >&5
-echo $ECHO_N "checking for iconv_open in -lc... $ECHO_C" >&6
-if test "${ac_cv_lib_c_iconv_open+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-lc "-L$ICONV_LIBDIR" $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
+    sysv4*MP*)
+      if test -d /usr/nec; then
+	lt_prog_compiler_pic=-Kconform_pic
+      fi
+      ;;
 
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char iconv_open ();
-int
-main ()
-{
-iconv_open ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_c_iconv_open=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
+    *)
+      lt_prog_compiler_pic='-fPIC'
+      ;;
+    esac
 
-ac_cv_lib_c_iconv_open=no
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_c_iconv_open" >&5
-echo "${ECHO_T}$ac_cv_lib_c_iconv_open" >&6
-if test $ac_cv_lib_c_iconv_open = yes; then
-  ICONV_LIB="-L$ICONV_LIBDIR -lc"
-fi
+    case $cc_basename in
+    nvcc*) # Cuda Compiler Driver 2.2
+      lt_prog_compiler_wl='-Xlinker '
+      if test -n "$lt_prog_compiler_pic"; then
+        lt_prog_compiler_pic="-Xcompiler $lt_prog_compiler_pic"
+      fi
+      ;;
+    esac
+  else
+    # PORTME Check for flag to pass linker flags through the system compiler.
+    case $host_os in
+    aix*)
+      lt_prog_compiler_wl='-Wl,'
+      if test "$host_cpu" = ia64; then
+	# AIX 5 now supports IA64 processor
+	lt_prog_compiler_static='-Bstatic'
+      else
+	lt_prog_compiler_static='-bnso -bI:/lib/syscalls.exp'
+      fi
+      ;;
 
-  echo "$as_me:$LINENO: checking for libiconv_open in -liconv" >&5
-echo $ECHO_N "checking for libiconv_open in -liconv... $ECHO_C" >&6
-if test "${ac_cv_lib_iconv_libiconv_open+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-liconv "-L$ICONV_LIBDIR" $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
+    mingw* | cygwin* | pw32* | os2* | cegcc*)
+      # This hack is so that the source file can tell whether it is being
+      # built for inclusion in a dll (and should export symbols for example).
+      lt_prog_compiler_pic='-DDLL_EXPORT'
+      ;;
 
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char libiconv_open ();
-int
-main ()
-{
-libiconv_open ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_iconv_libiconv_open=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
+    hpux9* | hpux10* | hpux11*)
+      lt_prog_compiler_wl='-Wl,'
+      # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but
+      # not for PA HP-UX.
+      case $host_cpu in
+      hppa*64*|ia64*)
+	# +Z the default
+	;;
+      *)
+	lt_prog_compiler_pic='+Z'
+	;;
+      esac
+      # Is there a better lt_prog_compiler_static that works with the bundled CC?
+      lt_prog_compiler_static='${wl}-a ${wl}archive'
+      ;;
 
-ac_cv_lib_iconv_libiconv_open=no
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_iconv_libiconv_open" >&5
-echo "${ECHO_T}$ac_cv_lib_iconv_libiconv_open" >&6
-if test $ac_cv_lib_iconv_libiconv_open = yes; then
-  ICONV_LIB="-L$ICONV_LIBDIR -liconv"
-fi
+    irix5* | irix6* | nonstopux*)
+      lt_prog_compiler_wl='-Wl,'
+      # PIC (with -KPIC) is the default.
+      lt_prog_compiler_static='-non_shared'
+      ;;
 
-  echo "$as_me:$LINENO: checking for iconv_open in -liconv" >&5
-echo $ECHO_N "checking for iconv_open in -liconv... $ECHO_C" >&6
-if test "${ac_cv_lib_iconv_iconv_open+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-liconv "-L$ICONV_LIBDIR" $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
+    linux* | k*bsd*-gnu | kopensolaris*-gnu)
+      case $cc_basename in
+      # old Intel for x86_64 which still supported -KPIC.
+      ecc*)
+	lt_prog_compiler_wl='-Wl,'
+	lt_prog_compiler_pic='-KPIC'
+	lt_prog_compiler_static='-static'
+        ;;
+      # icc used to be incompatible with GCC.
+      # ICC 10 doesn't accept -KPIC any more.
+      icc* | ifort*)
+	lt_prog_compiler_wl='-Wl,'
+	lt_prog_compiler_pic='-fPIC'
+	lt_prog_compiler_static='-static'
+        ;;
+      # Lahey Fortran 8.1.
+      lf95*)
+	lt_prog_compiler_wl='-Wl,'
+	lt_prog_compiler_pic='--shared'
+	lt_prog_compiler_static='--static'
+	;;
+      nagfor*)
+	# NAG Fortran compiler
+	lt_prog_compiler_wl='-Wl,-Wl,,'
+	lt_prog_compiler_pic='-PIC'
+	lt_prog_compiler_static='-Bstatic'
+	;;
+      pgcc* | pgf77* | pgf90* | pgf95* | pgfortran*)
+        # Portland Group compilers (*not* the Pentium gcc compiler,
+	# which looks to be a dead project)
+	lt_prog_compiler_wl='-Wl,'
+	lt_prog_compiler_pic='-fpic'
+	lt_prog_compiler_static='-Bstatic'
+        ;;
+      ccc*)
+        lt_prog_compiler_wl='-Wl,'
+        # All Alpha code is PIC.
+        lt_prog_compiler_static='-non_shared'
+        ;;
+      xl* | bgxl* | bgf* | mpixl*)
+	# IBM XL C 8.0/Fortran 10.1, 11.1 on PPC and BlueGene
+	lt_prog_compiler_wl='-Wl,'
+	lt_prog_compiler_pic='-qpic'
+	lt_prog_compiler_static='-qstaticlink'
+	;;
+      *)
+	case `$CC -V 2>&1 | sed 5q` in
+	*Sun\ Ceres\ Fortran* | *Sun*Fortran*\ [1-7].* | *Sun*Fortran*\ 8.[0-3]*)
+	  # Sun Fortran 8.3 passes all unrecognized flags to the linker
+	  lt_prog_compiler_pic='-KPIC'
+	  lt_prog_compiler_static='-Bstatic'
+	  lt_prog_compiler_wl=''
+	  ;;
+	*Sun\ F* | *Sun*Fortran*)
+	  lt_prog_compiler_pic='-KPIC'
+	  lt_prog_compiler_static='-Bstatic'
+	  lt_prog_compiler_wl='-Qoption ld '
+	  ;;
+	*Sun\ C*)
+	  # Sun C 5.9
+	  lt_prog_compiler_pic='-KPIC'
+	  lt_prog_compiler_static='-Bstatic'
+	  lt_prog_compiler_wl='-Wl,'
+	  ;;
+        *Intel*\ [CF]*Compiler*)
+	  lt_prog_compiler_wl='-Wl,'
+	  lt_prog_compiler_pic='-fPIC'
+	  lt_prog_compiler_static='-static'
+	  ;;
+	*Portland\ Group*)
+	  lt_prog_compiler_wl='-Wl,'
+	  lt_prog_compiler_pic='-fpic'
+	  lt_prog_compiler_static='-Bstatic'
+	  ;;
+	esac
+	;;
+      esac
+      ;;
 
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char iconv_open ();
-int
-main ()
-{
-iconv_open ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_iconv_iconv_open=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
+    newsos6)
+      lt_prog_compiler_pic='-KPIC'
+      lt_prog_compiler_static='-Bstatic'
+      ;;
 
-ac_cv_lib_iconv_iconv_open=no
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_iconv_iconv_open" >&5
-echo "${ECHO_T}$ac_cv_lib_iconv_iconv_open" >&6
-if test $ac_cv_lib_iconv_iconv_open = yes; then
-  ICONV_LIB="-L$ICONV_LIBDIR -liconv"
-fi
+    *nto* | *qnx*)
+      # QNX uses GNU C++, but need to define -shared option too, otherwise
+      # it will coredump.
+      lt_prog_compiler_pic='-fPIC -shared'
+      ;;
 
+    osf3* | osf4* | osf5*)
+      lt_prog_compiler_wl='-Wl,'
+      # All OSF/1 code is PIC.
+      lt_prog_compiler_static='-non_shared'
+      ;;
 
-fi
+    rdos*)
+      lt_prog_compiler_static='-non_shared'
+      ;;
 
-if test -n "$ICONV_LIB" ; then
-  if test -n "$ICONV_INCDIR"; then
-     ICONV_INC="-I$ICONV_INCDIR"
-  fi
-  echo "$as_me:$LINENO: result:         using libiconv from $ICONV_LIB" >&5
-echo "${ECHO_T}        using libiconv from $ICONV_LIB" >&6
+    solaris*)
+      lt_prog_compiler_pic='-KPIC'
+      lt_prog_compiler_static='-Bstatic'
+      case $cc_basename in
+      f77* | f90* | f95* | sunf77* | sunf90* | sunf95*)
+	lt_prog_compiler_wl='-Qoption ld ';;
+      *)
+	lt_prog_compiler_wl='-Wl,';;
+      esac
+      ;;
 
-  if test ""$ICONV_DIR"" != "/usr/lib"; then
+    sunos4*)
+      lt_prog_compiler_wl='-Qoption ld '
+      lt_prog_compiler_pic='-PIC'
+      lt_prog_compiler_static='-Bstatic'
+      ;;
 
-  if test -z ""$ICONV_DIR"" || echo ""$ICONV_DIR"" | grep '^/' >/dev/null ; then
-    ai_p=""$ICONV_DIR""
-  else
-    ai_p="`pwd`/"$ICONV_DIR""
-  fi
+    sysv4 | sysv4.2uw2* | sysv4.3*)
+      lt_prog_compiler_wl='-Wl,'
+      lt_prog_compiler_pic='-KPIC'
+      lt_prog_compiler_static='-Bstatic'
+      ;;
 
+    sysv4*MP*)
+      if test -d /usr/nec ;then
+	lt_prog_compiler_pic='-Kconform_pic'
+	lt_prog_compiler_static='-Bstatic'
+      fi
+      ;;
 
-  unique=`echo $ac_n "$ai_p$ac_c" | tr -c -d a-zA-Z0-9`
-  cmd="echo $ac_n \"\$LIBPATH$unique$ac_c\""
-  if test -n "$unique" && test "`eval $cmd`" = "" ; then
-    eval "LIBPATH$unique=set"
+    sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*)
+      lt_prog_compiler_wl='-Wl,'
+      lt_prog_compiler_pic='-KPIC'
+      lt_prog_compiler_static='-Bstatic'
+      ;;
 
-      EXTRA_LIBS="$EXTRA_LIBS -L$ai_p"
-        RPATHS="$RPATHS ${ld_runpath_switch}$ai_p"
+    unicos*)
+      lt_prog_compiler_wl='-Wl,'
+      lt_prog_compiler_can_build_shared=no
+      ;;
 
-  fi
+    uts4*)
+      lt_prog_compiler_pic='-pic'
+      lt_prog_compiler_static='-Bstatic'
+      ;;
 
+    *)
+      lt_prog_compiler_can_build_shared=no
+      ;;
+    esac
   fi
 
+case $host_os in
+  # For platforms which do not support PIC, -DPIC is meaningless:
+  *djgpp*)
+    lt_prog_compiler_pic=
+    ;;
+  *)
+    lt_prog_compiler_pic="$lt_prog_compiler_pic -DPIC"
+    ;;
+esac
 
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $compiler option to produce PIC" >&5
+$as_echo_n "checking for $compiler option to produce PIC... " >&6; }
+if ${lt_cv_prog_compiler_pic+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
+  lt_cv_prog_compiler_pic=$lt_prog_compiler_pic
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_pic" >&5
+$as_echo "$lt_cv_prog_compiler_pic" >&6; }
+lt_prog_compiler_pic=$lt_cv_prog_compiler_pic
 
+#
+# Check to make sure the PIC flag actually works.
+#
+if test -n "$lt_prog_compiler_pic"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler PIC flag $lt_prog_compiler_pic works" >&5
+$as_echo_n "checking if $compiler PIC flag $lt_prog_compiler_pic works... " >&6; }
+if ${lt_cv_prog_compiler_pic_works+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  lt_cv_prog_compiler_pic_works=no
+   ac_outfile=conftest.$ac_objext
+   echo "$lt_simple_compile_test_code" > conftest.$ac_ext
+   lt_compiler_flag="$lt_prog_compiler_pic -DPIC"
+   # Insert the option either (1) after the last *FLAGS variable, or
+   # (2) before a word containing "conftest.", or (3) at the end.
+   # Note that $ac_compile itself does not contain backslashes and begins
+   # with a dollar sign (not a hyphen), so the echo should work correctly.
+   # The option is referenced via a variable to avoid confusing sed.
+   lt_compile=`echo "$ac_compile" | $SED \
+   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
+   -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
+   -e 's:$: $lt_compiler_flag:'`
+   (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5)
+   (eval "$lt_compile" 2>conftest.err)
+   ac_status=$?
+   cat conftest.err >&5
+   echo "$as_me:$LINENO: \$? = $ac_status" >&5
+   if (exit $ac_status) && test -s "$ac_outfile"; then
+     # The compiler can only warn and ignore the option if not recognized
+     # So say no if there are warnings other than the usual output.
+     $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' >conftest.exp
+     $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
+     if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then
+       lt_cv_prog_compiler_pic_works=yes
+     fi
+   fi
+   $RM conftest*
 
-  unset ac_cv_lib_iconv_libiconv_open
-  unset ac_cv_lib_c_iconv_open
-  echo "$as_me:$LINENO: checking for iconv_open in -lc" >&5
-echo $ECHO_N "checking for iconv_open in -lc... $ECHO_C" >&6
-if test "${ac_cv_lib_c_iconv_open+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-lc  $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_pic_works" >&5
+$as_echo "$lt_cv_prog_compiler_pic_works" >&6; }
 
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char iconv_open ();
-int
-main ()
-{
-iconv_open ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_c_iconv_open=yes
+if test x"$lt_cv_prog_compiler_pic_works" = xyes; then
+    case $lt_prog_compiler_pic in
+     "" | " "*) ;;
+     *) lt_prog_compiler_pic=" $lt_prog_compiler_pic" ;;
+     esac
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-ac_cv_lib_c_iconv_open=no
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
+    lt_prog_compiler_pic=
+     lt_prog_compiler_can_build_shared=no
 fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_c_iconv_open" >&5
-echo "${ECHO_T}$ac_cv_lib_c_iconv_open" >&6
-if test $ac_cv_lib_c_iconv_open = yes; then
-  ICONV_LIB="-lc"
+
 fi
 
-  echo "$as_me:$LINENO: checking for libiconv_open in -liconv" >&5
-echo $ECHO_N "checking for libiconv_open in -liconv... $ECHO_C" >&6
-if test "${ac_cv_lib_iconv_libiconv_open+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-liconv  $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
 
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char libiconv_open ();
-int
-main ()
-{
-libiconv_open ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_iconv_libiconv_open=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
 
-ac_cv_lib_iconv_libiconv_open=no
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_iconv_libiconv_open" >&5
-echo "${ECHO_T}$ac_cv_lib_iconv_libiconv_open" >&6
-if test $ac_cv_lib_iconv_libiconv_open = yes; then
-  ICONV_LIB="-liconv"
-fi
 
-  echo "$as_me:$LINENO: checking for iconv_open in -liconv" >&5
-echo $ECHO_N "checking for iconv_open in -liconv... $ECHO_C" >&6
-if test "${ac_cv_lib_iconv_iconv_open+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-liconv  $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
 
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char iconv_open ();
-int
-main ()
-{
-iconv_open ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_iconv_iconv_open=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
 
-ac_cv_lib_iconv_iconv_open=no
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_iconv_iconv_open" >&5
-echo "${ECHO_T}$ac_cv_lib_iconv_iconv_open" >&6
-if test $ac_cv_lib_iconv_iconv_open = yes; then
-  ICONV_LIB="-liconv"
-fi
 
 
-  if test -n "$ICONV_LIB" ; then
-    echo "$as_me:$LINENO: result:         using libiconv from system libs." >&5
-echo "${ECHO_T}        using libiconv from system libs." >&6
-  else
-    echo "$as_me:$LINENO: result:         libiconv library cannot be found, possibly needed for GD" >&5
-echo "${ECHO_T}        libiconv library cannot be found, possibly needed for GD" >&6
-  fi
 
-fi
 
-if test -n "$ICONV_LIB" ; then
-  ICONV_ENABLED="-DUSE_ICONV"
-  echo "$as_me:$LINENO: result:         libiconv found. Enabling internationalization ($ICONV_ENABLED)" >&5
-echo "${ECHO_T}        libiconv found. Enabling internationalization ($ICONV_ENABLED)" >&6
+
+#
+# Check to make sure the static flag actually works.
+#
+wl=$lt_prog_compiler_wl eval lt_tmp_static_flag=\"$lt_prog_compiler_static\"
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler static flag $lt_tmp_static_flag works" >&5
+$as_echo_n "checking if $compiler static flag $lt_tmp_static_flag works... " >&6; }
+if ${lt_cv_prog_compiler_static_works+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  lt_cv_prog_compiler_static_works=no
+   save_LDFLAGS="$LDFLAGS"
+   LDFLAGS="$LDFLAGS $lt_tmp_static_flag"
+   echo "$lt_simple_link_test_code" > conftest.$ac_ext
+   if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then
+     # The linker can only warn and ignore the option if not recognized
+     # So say no if there are warnings
+     if test -s conftest.err; then
+       # Append any errors to the config.log.
+       cat conftest.err 1>&5
+       $ECHO "$_lt_linker_boilerplate" | $SED '/^$/d' > conftest.exp
+       $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
+       if diff conftest.exp conftest.er2 >/dev/null; then
+         lt_cv_prog_compiler_static_works=yes
+       fi
+     else
+       lt_cv_prog_compiler_static_works=yes
+     fi
+   fi
+   $RM -r conftest*
+   LDFLAGS="$save_LDFLAGS"
+
 fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_static_works" >&5
+$as_echo "$lt_cv_prog_compiler_static_works" >&6; }
 
+if test x"$lt_cv_prog_compiler_static_works" = xyes; then
+    :
+else
+    lt_prog_compiler_static=
+fi
 
-ICONV_ENABLED=$ICONV_ENABLED
 
-ICONV_INC=$ICONV_INC
 
-ICONV_LIB=$ICONV_LIB
 
 
-ALL_ENABLED="$ICONV_ENABLED $ALL_ENABLED"
-ALL_INC="$ICONV_INC $ALL_INC"
-ALL_LIB="$ICONV_LIB $ALL_LIB"
 
 
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler supports -c -o file.$ac_objext" >&5
+$as_echo_n "checking if $compiler supports -c -o file.$ac_objext... " >&6; }
+if ${lt_cv_prog_compiler_c_o+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  lt_cv_prog_compiler_c_o=no
+   $RM -r conftest 2>/dev/null
+   mkdir conftest
+   cd conftest
+   mkdir out
+   echo "$lt_simple_compile_test_code" > conftest.$ac_ext
 
+   lt_compiler_flag="-o out/conftest2.$ac_objext"
+   # Insert the option either (1) after the last *FLAGS variable, or
+   # (2) before a word containing "conftest.", or (3) at the end.
+   # Note that $ac_compile itself does not contain backslashes and begins
+   # with a dollar sign (not a hyphen), so the echo should work correctly.
+   lt_compile=`echo "$ac_compile" | $SED \
+   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
+   -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
+   -e 's:$: $lt_compiler_flag:'`
+   (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5)
+   (eval "$lt_compile" 2>out/conftest.err)
+   ac_status=$?
+   cat out/conftest.err >&5
+   echo "$as_me:$LINENO: \$? = $ac_status" >&5
+   if (exit $ac_status) && test -s out/conftest2.$ac_objext
+   then
+     # The compiler can only warn and ignore the option if not recognized
+     # So say no if there are warnings
+     $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' > out/conftest.exp
+     $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2
+     if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then
+       lt_cv_prog_compiler_c_o=yes
+     fi
+   fi
+   chmod u+w . 2>&5
+   $RM conftest*
+   # SGI C++ compiler will create directory out/ii_files/ for
+   # template instantiation
+   test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files
+   $RM out/* && rmdir out
+   cd ..
+   $RM -r conftest
+   $RM conftest*
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_c_o" >&5
+$as_echo "$lt_cv_prog_compiler_c_o" >&6; }
+
+
+
+
+
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler supports -c -o file.$ac_objext" >&5
+$as_echo_n "checking if $compiler supports -c -o file.$ac_objext... " >&6; }
+if ${lt_cv_prog_compiler_c_o+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  lt_cv_prog_compiler_c_o=no
+   $RM -r conftest 2>/dev/null
+   mkdir conftest
+   cd conftest
+   mkdir out
+   echo "$lt_simple_compile_test_code" > conftest.$ac_ext
+
+   lt_compiler_flag="-o out/conftest2.$ac_objext"
+   # Insert the option either (1) after the last *FLAGS variable, or
+   # (2) before a word containing "conftest.", or (3) at the end.
+   # Note that $ac_compile itself does not contain backslashes and begins
+   # with a dollar sign (not a hyphen), so the echo should work correctly.
+   lt_compile=`echo "$ac_compile" | $SED \
+   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
+   -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
+   -e 's:$: $lt_compiler_flag:'`
+   (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5)
+   (eval "$lt_compile" 2>out/conftest.err)
+   ac_status=$?
+   cat out/conftest.err >&5
+   echo "$as_me:$LINENO: \$? = $ac_status" >&5
+   if (exit $ac_status) && test -s out/conftest2.$ac_objext
+   then
+     # The compiler can only warn and ignore the option if not recognized
+     # So say no if there are warnings
+     $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' > out/conftest.exp
+     $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2
+     if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then
+       lt_cv_prog_compiler_c_o=yes
+     fi
+   fi
+   chmod u+w . 2>&5
+   $RM conftest*
+   # SGI C++ compiler will create directory out/ii_files/ for
+   # template instantiation
+   test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files
+   $RM out/* && rmdir out
+   cd ..
+   $RM -r conftest
+   $RM conftest*
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_c_o" >&5
+$as_echo "$lt_cv_prog_compiler_c_o" >&6; }
+
+
+
+
+hard_links="nottested"
+if test "$lt_cv_prog_compiler_c_o" = no && test "$need_locks" != no; then
+  # do not overwrite the value of need_locks provided by the user
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if we can lock with hard links" >&5
+$as_echo_n "checking if we can lock with hard links... " >&6; }
+  hard_links=yes
+  $RM conftest*
+  ln conftest.a conftest.b 2>/dev/null && hard_links=no
+  touch conftest.a
+  ln conftest.a conftest.b 2>&5 || hard_links=no
+  ln conftest.a conftest.b 2>/dev/null && hard_links=no
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $hard_links" >&5
+$as_echo "$hard_links" >&6; }
+  if test "$hard_links" = no; then
+    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&5
+$as_echo "$as_me: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&2;}
+    need_locks=warn
+  fi
+else
+  need_locks=no
+fi
+
+
+
+
+
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the $compiler linker ($LD) supports shared libraries" >&5
+$as_echo_n "checking whether the $compiler linker ($LD) supports shared libraries... " >&6; }
+
+  runpath_var=
+  allow_undefined_flag=
+  always_export_symbols=no
+  archive_cmds=
+  archive_expsym_cmds=
+  compiler_needs_object=no
+  enable_shared_with_static_runtimes=no
+  export_dynamic_flag_spec=
+  export_symbols_cmds='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
+  hardcode_automatic=no
+  hardcode_direct=no
+  hardcode_direct_absolute=no
+  hardcode_libdir_flag_spec=
+  hardcode_libdir_separator=
+  hardcode_minus_L=no
+  hardcode_shlibpath_var=unsupported
+  inherit_rpath=no
+  link_all_deplibs=unknown
+  module_cmds=
+  module_expsym_cmds=
+  old_archive_from_new_cmds=
+  old_archive_from_expsyms_cmds=
+  thread_safe_flag_spec=
+  whole_archive_flag_spec=
+  # include_expsyms should be a list of space-separated symbols to be *always*
+  # included in the symbol list
+  include_expsyms=
+  # exclude_expsyms can be an extended regexp of symbols to exclude
+  # it will be wrapped by ` (' and `)$', so one must not match beginning or
+  # end of line.  Example: `a|bc|.*d.*' will exclude the symbols `a' and `bc',
+  # as well as any symbol that contains `d'.
+  exclude_expsyms='_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*'
+  # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out
+  # platforms (ab)use it in PIC code, but their linkers get confused if
+  # the symbol is explicitly referenced.  Since portable code cannot
+  # rely on this symbol name, it's probably fine to never include it in
+  # preloaded symbol tables.
+  # Exclude shared library initialization/finalization symbols.
+  extract_expsyms_cmds=
+
+  case $host_os in
+  cygwin* | mingw* | pw32* | cegcc*)
+    # FIXME: the MSVC++ port hasn't been tested in a loooong time
+    # When not using gcc, we currently assume that we are using
+    # Microsoft Visual C++.
+    if test "$GCC" != yes; then
+      with_gnu_ld=no
+    fi
+    ;;
+  interix*)
+    # we just hope/assume this is gcc and not c89 (= MSVC++)
+    with_gnu_ld=yes
+    ;;
+  openbsd*)
+    with_gnu_ld=no
+    ;;
+  linux* | k*bsd*-gnu | gnu*)
+    link_all_deplibs=no
+    ;;
+  esac
 
-ms_saved_LIBS="$LIBS"
-IS_GD2="false";
-
-unset ac_cv_lib_gd_gdImageCreate
-unset ac_cv_lib_gd_gdImageString16
-unset ac_cv_lib_gd_gdImageGif
-unset ac_cv_lib_gd_gdImagePng
-unset ac_cv_lib_gd_gdImageJpeg
-unset ac_cv_lib_gd_gdImageWBMP
-unset ac_cv_lib_gd_gdImageStringFT
-unset ac_cv_lib_gd_gdImageGifPtr
-unset ac_cv_lib_gd_gdFontGetTiny
-unset ac_cv_lib_c_gdImageCreate
-unset ac_cv_lib_c_gdImageString16
-unset ac_cv_lib_c_gdImageGif
-unset ac_cv_lib_c_gdImagePng
-unset ac_cv_lib_c_gdImageJpeg
-unset ac_cv_lib_c_gdImageWBMP
-unset ac_cv_lib_c_gdImageStringFT
-unset ac_cv_lib_c_gdImageGifPtr
-unset ac_cv_lib_c_gdFontGetTiny
-unset ac_cv_lib_gd_gdImageCreatePaletteFromTrueColor
-
-{ echo "$as_me:$LINENO: checking for GD 2.0.28 or higher..." >&5
-echo "$as_me: checking for GD 2.0.28 or higher..." >&6;}
-
-# Check whether --with-gd or --without-gd was given.
-if test "${with_gd+set}" = set; then
-  withval="$with_gd"
-
-fi;
-
-if test "$with_gd" = "no" ; then
-  { { echo "$as_me:$LINENO: error: GD library cannot be disabled" >&5
-echo "$as_me: error: GD library cannot be disabled" >&2;}
-   { (exit 1); exit 1; }; }
-elif test -n "$with_gd" -a "$with_gd" != "yes" ; then
-
-  if echo "$with_gd" | grep '^static,' >/dev/null ; then
-    GD_DIR=`echo "$with_gd" | sed "s/^static,//"`
-    GD_STATIC=yes
-  else
-    GD_DIR=$with_gd
-    GD_STATIC=no
+  ld_shlibs=yes
+
+  # On some targets, GNU ld is compatible enough with the native linker
+  # that we're better off using the native interface for both.
+  lt_use_gnu_ld_interface=no
+  if test "$with_gnu_ld" = yes; then
+    case $host_os in
+      aix*)
+	# The AIX port of GNU ld has always aspired to compatibility
+	# with the native linker.  However, as the warning in the GNU ld
+	# block says, versions before 2.19.5* couldn't really create working
+	# shared libraries, regardless of the interface used.
+	case `$LD -v 2>&1` in
+	  *\ \(GNU\ Binutils\)\ 2.19.5*) ;;
+	  *\ \(GNU\ Binutils\)\ 2.[2-9]*) ;;
+	  *\ \(GNU\ Binutils\)\ [3-9]*) ;;
+	  *)
+	    lt_use_gnu_ld_interface=yes
+	    ;;
+	esac
+	;;
+      *)
+	lt_use_gnu_ld_interface=yes
+	;;
+    esac
   fi
 
+  if test "$lt_use_gnu_ld_interface" = yes; then
+    # If archive_cmds runs LD, not CC, wlarc should be empty
+    wlarc='${wl}'
+
+    # Set some defaults for GNU ld with shared library support. These
+    # are reset later if shared libraries are not supported. Putting them
+    # here allows them to be overridden if necessary.
+    runpath_var=LD_RUN_PATH
+    hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir'
+    export_dynamic_flag_spec='${wl}--export-dynamic'
+    # ancient GNU ld didn't support --whole-archive et. al.
+    if $LD --help 2>&1 | $GREP 'no-whole-archive' > /dev/null; then
+      whole_archive_flag_spec="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
+    else
+      whole_archive_flag_spec=
+    fi
+    supports_anon_versioning=no
+    case `$LD -v 2>&1` in
+      *GNU\ gold*) supports_anon_versioning=yes ;;
+      *\ [01].* | *\ 2.[0-9].* | *\ 2.10.*) ;; # catch versions < 2.11
+      *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ...
+      *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ...
+      *\ 2.11.*) ;; # other 2.11 versions
+      *) supports_anon_versioning=yes ;;
+    esac
 
-  if test -z "$GD_DIR" || echo "$GD_DIR" | grep '^/' >/dev/null ; then
-    GD_DIR="$GD_DIR"
-  else
-    GD_DIR="`pwd`/$GD_DIR"
-  fi
+    # See if GNU ld supports shared libraries.
+    case $host_os in
+    aix[3-9]*)
+      # On AIX/PPC, the GNU linker is very broken
+      if test "$host_cpu" != ia64; then
+	ld_shlibs=no
+	cat <<_LT_EOF 1>&2
+
+*** Warning: the GNU linker, at least up to release 2.19, is reported
+*** to be unable to reliably create shared libraries on AIX.
+*** Therefore, libtool is disabling shared libraries support.  If you
+*** really care for shared libraries, you may want to install binutils
+*** 2.20 or above, or modify your PATH so that a non-GNU linker is found.
+*** You will then need to restart the configuration process.
+
+_LT_EOF
+      fi
+      ;;
 
-  test -f $GD_DIR/include/gd.h && GD_INCLUDE="$GD_DIR/include"
-  test -f $GD_DIR/include/gd/gd.h && GD_INCLUDE="$GD_DIR/include/gd"
-  test -f $GD_DIR/gd.h && GD_INCLUDE="$GD_DIR"
+    amigaos*)
+      case $host_cpu in
+      powerpc)
+            # see comment about AmigaOS4 .so support
+            archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+            archive_expsym_cmds=''
+        ;;
+      m68k)
+            archive_cmds='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)'
+            hardcode_libdir_flag_spec='-L$libdir'
+            hardcode_minus_L=yes
+        ;;
+      esac
+      ;;
 
-  test -f $GD_DIR/lib/libgd.a && GD_LIBDIR="$GD_DIR/lib"
-  test -f $GD_DIR/lib64/libgd.a && GD_LIBDIR="$GD_DIR/lib64"
-  test -f $GD_DIR/.libs/libgd.a && GD_LIBDIR="$GD_DIR/.libs"
-  test -f $GD_DIR/_libs/libgd.a && GD_LIBDIR="$GD_DIR/_libs"
-  test -f $GD_DIR/libgd.a && GD_LIBDIR="$GD_DIR"
+    beos*)
+      if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
+	allow_undefined_flag=unsupported
+	# Joseph Beckenbach <jrb3 at best.com> says some releases of gcc
+	# support --undefined.  This deserves some investigation.  FIXME
+	archive_cmds='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+      else
+	ld_shlibs=no
+      fi
+      ;;
 
-  test -f $GD_DIR/lib/libgd.so -o -f $GD_DIR/lib/libgd.sl -o -f $GD_DIR/lib/libgd.dylib && GD_LIBDIR="$GD_DIR/lib"
-  test -f $GD_DIR/lib64/libgd.so -o -f $GD_DIR/lib/libgd.sl && GD_LIBDIR="$GD_DIR/lib64"
-  test -f $GD_DIR/.libs/libgd.so -o -f $GD_DIR/.libs/libgd.sl -o -f $GD_DIR/.libs/libgd.dylib && GD_LIBDIR="$GD_DIR/.libs"
-  test -f $GD_DIR/_libs/libgd.so -o -f $GD_DIR/_libs/libgd.sl -o -f $GD_DIR/_libs/libgd.dylib && GD_LIBDIR="$GD_DIR/_libs"
-  test -f $GD_DIR/libgd.so -o -f $GD_DIR/libgd.sl -o -f $GD_DIR/libgd.dylib && GD_LIBDIR="$GD_DIR"
+    cygwin* | mingw* | pw32* | cegcc*)
+      # _LT_TAGVAR(hardcode_libdir_flag_spec, ) is actually meaningless,
+      # as there is no search path for DLLs.
+      hardcode_libdir_flag_spec='-L$libdir'
+      export_dynamic_flag_spec='${wl}--export-all-symbols'
+      allow_undefined_flag=unsupported
+      always_export_symbols=no
+      enable_shared_with_static_runtimes=yes
+      export_symbols_cmds='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[BCDGRS][ ]/s/.*[ ]\([^ ]*\)/\1 DATA/;s/^.*[ ]__nm__\([^ ]*\)[ ][^ ]*/\1 DATA/;/^I[ ]/d;/^[AITW][ ]/s/.* //'\'' | sort | uniq > $export_symbols'
+      exclude_expsyms='[_]+GLOBAL_OFFSET_TABLE_|[_]+GLOBAL__[FID]_.*|[_]+head_[A-Za-z0-9_]+_dll|[A-Za-z0-9_]+_dll_iname'
+
+      if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then
+        archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+	# If the export-symbols file already is a .def file (1st line
+	# is EXPORTS), use it as is; otherwise, prepend...
+	archive_expsym_cmds='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
+	  cp $export_symbols $output_objdir/$soname.def;
+	else
+	  echo EXPORTS > $output_objdir/$soname.def;
+	  cat $export_symbols >> $output_objdir/$soname.def;
+	fi~
+	$CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+      else
+	ld_shlibs=no
+      fi
+      ;;
 
-    echo "$as_me:$LINENO: checking for gdImageCreatePaletteFromTrueColor in -lgd" >&5
-echo $ECHO_N "checking for gdImageCreatePaletteFromTrueColor in -lgd... $ECHO_C" >&6
-if test "${ac_cv_lib_gd_gdImageCreatePaletteFromTrueColor+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-lgd $GD_XTRA_LIBS -L$GD_LIBDIR $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
+    haiku*)
+      archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+      link_all_deplibs=yes
+      ;;
 
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char gdImageCreatePaletteFromTrueColor ();
-int
-main ()
-{
-gdImageCreatePaletteFromTrueColor ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_gd_gdImageCreatePaletteFromTrueColor=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-ac_cv_lib_gd_gdImageCreatePaletteFromTrueColor=no
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_gd_gdImageCreatePaletteFromTrueColor" >&5
-echo "${ECHO_T}$ac_cv_lib_gd_gdImageCreatePaletteFromTrueColor" >&6
-if test $ac_cv_lib_gd_gdImageCreatePaletteFromTrueColor = yes; then
-  IS_GD2="true"
-fi
+    interix[3-9]*)
+      hardcode_direct=no
+      hardcode_shlibpath_var=no
+      hardcode_libdir_flag_spec='${wl}-rpath,$libdir'
+      export_dynamic_flag_spec='${wl}-E'
+      # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc.
+      # Instead, shared libraries are loaded at an image base (0x10000000 by
+      # default) and relocated if they conflict, which is a slow very memory
+      # consuming and fragmenting process.  To avoid this, we pick a random,
+      # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link
+      # time.  Moving up from 0x10000000 also allows more sbrk(2) space.
+      archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
+      archive_expsym_cmds='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
+      ;;
 
+    gnu* | linux* | tpf* | k*bsd*-gnu | kopensolaris*-gnu)
+      tmp_diet=no
+      if test "$host_os" = linux-dietlibc; then
+	case $cc_basename in
+	  diet\ *) tmp_diet=yes;;	# linux-dietlibc with static linking (!diet-dyn)
+	esac
+      fi
+      if $LD --help 2>&1 | $EGREP ': supported targets:.* elf' > /dev/null \
+	 && test "$tmp_diet" = no
+      then
+	tmp_addflag=' $pic_flag'
+	tmp_sharedflag='-shared'
+	case $cc_basename,$host_cpu in
+        pgcc*)				# Portland Group C compiler
+	  whole_archive_flag_spec='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
+	  tmp_addflag=' $pic_flag'
+	  ;;
+	pgf77* | pgf90* | pgf95* | pgfortran*)
+					# Portland Group f77 and f90 compilers
+	  whole_archive_flag_spec='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
+	  tmp_addflag=' $pic_flag -Mnomain' ;;
+	ecc*,ia64* | icc*,ia64*)	# Intel C compiler on ia64
+	  tmp_addflag=' -i_dynamic' ;;
+	efc*,ia64* | ifort*,ia64*)	# Intel Fortran compiler on ia64
+	  tmp_addflag=' -i_dynamic -nofor_main' ;;
+	ifc* | ifort*)			# Intel Fortran compiler
+	  tmp_addflag=' -nofor_main' ;;
+	lf95*)				# Lahey Fortran 8.1
+	  whole_archive_flag_spec=
+	  tmp_sharedflag='--shared' ;;
+	xl[cC]* | bgxl[cC]* | mpixl[cC]*) # IBM XL C 8.0 on PPC (deal with xlf below)
+	  tmp_sharedflag='-qmkshrobj'
+	  tmp_addflag= ;;
+	nvcc*)	# Cuda Compiler Driver 2.2
+	  whole_archive_flag_spec='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
+	  compiler_needs_object=yes
+	  ;;
+	esac
+	case `$CC -V 2>&1 | sed 5q` in
+	*Sun\ C*)			# Sun C 5.9
+	  whole_archive_flag_spec='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
+	  compiler_needs_object=yes
+	  tmp_sharedflag='-G' ;;
+	*Sun\ F*)			# Sun Fortran 8.3
+	  tmp_sharedflag='-G' ;;
+	esac
+	archive_cmds='$CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
 
-  if test "$IS_GD2" = "false" -a -n "$ICONV_LIB"; then
-        unset ac_cv_lib_gd_gdImageCreatePaletteFromTrueColor
-    { echo "$as_me:$LINENO: checking whether GD needs libiconv..." >&5
-echo "$as_me: checking whether GD needs libiconv..." >&6;}
-    echo "$as_me:$LINENO: checking for gdImageCreatePaletteFromTrueColor in -lgd" >&5
-echo $ECHO_N "checking for gdImageCreatePaletteFromTrueColor in -lgd... $ECHO_C" >&6
-if test "${ac_cv_lib_gd_gdImageCreatePaletteFromTrueColor+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-lgd $GD_XTRA_LIBS -L$GD_LIBDIR $ICONV_LIB $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
+        if test "x$supports_anon_versioning" = xyes; then
+          archive_expsym_cmds='echo "{ global:" > $output_objdir/$libname.ver~
+	    cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
+	    echo "local: *; };" >> $output_objdir/$libname.ver~
+	    $CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib'
+        fi
 
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char gdImageCreatePaletteFromTrueColor ();
-int
-main ()
-{
-gdImageCreatePaletteFromTrueColor ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_gd_gdImageCreatePaletteFromTrueColor=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
+	case $cc_basename in
+	xlf* | bgf* | bgxlf* | mpixlf*)
+	  # IBM XL Fortran 10.1 on PPC cannot create shared libs itself
+	  whole_archive_flag_spec='--whole-archive$convenience --no-whole-archive'
+	  hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir'
+	  archive_cmds='$LD -shared $libobjs $deplibs $linker_flags -soname $soname -o $lib'
+	  if test "x$supports_anon_versioning" = xyes; then
+	    archive_expsym_cmds='echo "{ global:" > $output_objdir/$libname.ver~
+	      cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
+	      echo "local: *; };" >> $output_objdir/$libname.ver~
+	      $LD -shared $libobjs $deplibs $linker_flags -soname $soname -version-script $output_objdir/$libname.ver -o $lib'
+	  fi
+	  ;;
+	esac
+      else
+        ld_shlibs=no
+      fi
+      ;;
 
-ac_cv_lib_gd_gdImageCreatePaletteFromTrueColor=no
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_gd_gdImageCreatePaletteFromTrueColor" >&5
-echo "${ECHO_T}$ac_cv_lib_gd_gdImageCreatePaletteFromTrueColor" >&6
-if test $ac_cv_lib_gd_gdImageCreatePaletteFromTrueColor = yes; then
-  IS_GD2="true"
-fi
+    netbsd* | netbsdelf*-gnu)
+      if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
+	archive_cmds='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib'
+	wlarc=
+      else
+	archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+	archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+      fi
+      ;;
 
-    GD_NEED_ICONV_LIB="$ICONV_LIB"
-  fi
+    solaris*)
+      if $LD -v 2>&1 | $GREP 'BFD 2\.8' > /dev/null; then
+	ld_shlibs=no
+	cat <<_LT_EOF 1>&2
+
+*** Warning: The releases 2.8.* of the GNU linker cannot reliably
+*** create shared libraries on Solaris systems.  Therefore, libtool
+*** is disabling shared libraries support.  We urge you to upgrade GNU
+*** binutils to release 2.9.1 or newer.  Another option is to modify
+*** your PATH or compiler configuration so that the native linker is
+*** used, and then restart.
+
+_LT_EOF
+      elif $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
+	archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+	archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+      else
+	ld_shlibs=no
+      fi
+      ;;
 
-  if test -n "$GD_INCLUDE" -a -n "$GD_LIBDIR" -a "$IS_GD2" = "true"; then
-      GD_INC=-I$GD_INCLUDE
-      GD_LIB="-L$GD_LIBDIR -lgd"
-      GD_XTRA_LIBS="$GD_XTRA_LIBS $GD_NEED_ICONV_LIB"
-      echo "$as_me:$LINENO: result:         using libgd 2.0.28 (or higher) from $GD_LIB $GD_XTRA_LIBS" >&5
-echo "${ECHO_T}        using libgd 2.0.28 (or higher) from $GD_LIB $GD_XTRA_LIBS" >&6
+    sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX*)
+      case `$LD -v 2>&1` in
+        *\ [01].* | *\ 2.[0-9].* | *\ 2.1[0-5].*)
+	ld_shlibs=no
+	cat <<_LT_EOF 1>&2
 
-  if test ""$GD_LIBDIR"" != "/usr/lib"; then
+*** Warning: Releases of the GNU linker prior to 2.16.91.0.3 can not
+*** reliably create shared libraries on SCO systems.  Therefore, libtool
+*** is disabling shared libraries support.  We urge you to upgrade GNU
+*** binutils to release 2.16.91.0.3 or newer.  Another option is to modify
+*** your PATH or compiler configuration so that the native linker is
+*** used, and then restart.
 
-  if test -z ""$GD_LIBDIR"" || echo ""$GD_LIBDIR"" | grep '^/' >/dev/null ; then
-    ai_p=""$GD_LIBDIR""
-  else
-    ai_p="`pwd`/"$GD_LIBDIR""
-  fi
+_LT_EOF
+	;;
+	*)
+	  # For security reasons, it is highly recommended that you always
+	  # use absolute paths for naming shared libraries, and exclude the
+	  # DT_RUNPATH tag from executables and libraries.  But doing so
+	  # requires that you compile everything twice, which is a pain.
+	  if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
+	    hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir'
+	    archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+	    archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+	  else
+	    ld_shlibs=no
+	  fi
+	;;
+      esac
+      ;;
 
+    sunos4*)
+      archive_cmds='$LD -assert pure-text -Bshareable -o $lib $libobjs $deplibs $linker_flags'
+      wlarc=
+      hardcode_direct=yes
+      hardcode_shlibpath_var=no
+      ;;
 
-  unique=`echo $ac_n "$ai_p$ac_c" | tr -c -d a-zA-Z0-9`
-  cmd="echo $ac_n \"\$LIBPATH$unique$ac_c\""
-  if test -n "$unique" && test "`eval $cmd`" = "" ; then
-    eval "LIBPATH$unique=set"
+    *)
+      if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
+	archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+	archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+      else
+	ld_shlibs=no
+      fi
+      ;;
+    esac
 
-      EXTRA_LIBS="$EXTRA_LIBS -L$ai_p"
-        RPATHS="$RPATHS ${ld_runpath_switch}$ai_p"
+    if test "$ld_shlibs" = no; then
+      runpath_var=
+      hardcode_libdir_flag_spec=
+      export_dynamic_flag_spec=
+      whole_archive_flag_spec=
+    fi
+  else
+    # PORTME fill in a description of your system's linker (not GNU ld)
+    case $host_os in
+    aix3*)
+      allow_undefined_flag=unsupported
+      always_export_symbols=yes
+      archive_expsym_cmds='$LD -o $output_objdir/$soname $libobjs $deplibs $linker_flags -bE:$export_symbols -T512 -H512 -bM:SRE~$AR $AR_FLAGS $lib $output_objdir/$soname'
+      # Note: this linker hardcodes the directories in LIBPATH if there
+      # are no directories specified by -L.
+      hardcode_minus_L=yes
+      if test "$GCC" = yes && test -z "$lt_prog_compiler_static"; then
+	# Neither direct hardcoding nor static linking is supported with a
+	# broken collect2.
+	hardcode_direct=unsupported
+      fi
+      ;;
 
-  fi
+    aix[4-9]*)
+      if test "$host_cpu" = ia64; then
+	# On IA64, the linker does run time linking by default, so we don't
+	# have to do anything special.
+	aix_use_runtimelinking=no
+	exp_sym_flag='-Bexport'
+	no_entry_flag=""
+      else
+	# If we're using GNU nm, then we don't want the "-C" option.
+	# -C means demangle to AIX nm, but means don't demangle with GNU nm
+	# Also, AIX nm treats weak defined symbols like other global
+	# defined symbols, whereas GNU nm marks them as "W".
+	if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then
+	  export_symbols_cmds='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W")) && (substr(\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
+	else
+	  export_symbols_cmds='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && (substr(\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
+	fi
+	aix_use_runtimelinking=no
+
+	# Test if we are trying to use run time linking or normal
+	# AIX style linking. If -brtl is somewhere in LDFLAGS, we
+	# need to do runtime linking.
+	case $host_os in aix4.[23]|aix4.[23].*|aix[5-9]*)
+	  for ld_flag in $LDFLAGS; do
+	  if (test $ld_flag = "-brtl" || test $ld_flag = "-Wl,-brtl"); then
+	    aix_use_runtimelinking=yes
+	    break
+	  fi
+	  done
+	  ;;
+	esac
 
-  fi
+	exp_sym_flag='-bexport'
+	no_entry_flag='-bnoentry'
+      fi
 
-  else
-      { { echo "$as_me:$LINENO: error: Could not find gd.h or libgd.a/libgd.so in $GD_DIR.  Make sure GD 2.0.28 or higher is compiled before calling configure. You may also get this error if you didn't specify the appropriate location for one of GD's dependencies (freetype, libpng, libjpeg or libiconv)." >&5
-echo "$as_me: error: Could not find gd.h or libgd.a/libgd.so in $GD_DIR.  Make sure GD 2.0.28 or higher is compiled before calling configure. You may also get this error if you didn't specify the appropriate location for one of GD's dependencies (freetype, libpng, libjpeg or libiconv)." >&2;}
-   { (exit 1); exit 1; }; }
-  fi
-else
-    FOUND_GD="false"
-  for GD_DIR in /usr /usr/local
-  do
-    test -f $GD_DIR/include/gd.h && GD_INCLUDE="$GD_DIR/include"
-    test -f $GD_DIR/lib/libgd.a && GD_LIBDIR="$GD_DIR/lib"
-    test -f $GD_DIR/lib64/libgd.a && GD_LIBDIR="$GD_DIR/lib64"
-    test -f $GD_DIR/lib/libgd.so -o -f $GD_DIR/lib/libgd.sl -o -f $GD_DIR/lib/libgd.dylib && GD_LIBDIR="$GD_DIR/lib"
-    test -f $GD_DIR/lib64/libgd.so -o -f $GD_DIR/lib/libgd.sl && GD_LIBDIR="$GD_DIR/lib64"
+      # When large executables or shared objects are built, AIX ld can
+      # have problems creating the table of contents.  If linking a library
+      # or program results in "error TOC overflow" add -mminimal-toc to
+      # CXXFLAGS/CFLAGS for g++/gcc.  In the cases where that is not
+      # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS.
+
+      archive_cmds=''
+      hardcode_direct=yes
+      hardcode_direct_absolute=yes
+      hardcode_libdir_separator=':'
+      link_all_deplibs=yes
+      file_list_spec='${wl}-f,'
+
+      if test "$GCC" = yes; then
+	case $host_os in aix4.[012]|aix4.[012].*)
+	# We only want to do this on AIX 4.2 and lower, the check
+	# below for broken collect2 doesn't work under 4.3+
+	  collect2name=`${CC} -print-prog-name=collect2`
+	  if test -f "$collect2name" &&
+	   strings "$collect2name" | $GREP resolve_lib_name >/dev/null
+	  then
+	  # We have reworked collect2
+	  :
+	  else
+	  # We have old collect2
+	  hardcode_direct=unsupported
+	  # It fails to find uninstalled libraries when the uninstalled
+	  # path is not listed in the libpath.  Setting hardcode_minus_L
+	  # to unsupported forces relinking
+	  hardcode_minus_L=yes
+	  hardcode_libdir_flag_spec='-L$libdir'
+	  hardcode_libdir_separator=
+	  fi
+	  ;;
+	esac
+	shared_flag='-shared'
+	if test "$aix_use_runtimelinking" = yes; then
+	  shared_flag="$shared_flag "'${wl}-G'
+	fi
+	link_all_deplibs=no
+      else
+	# not using gcc
+	if test "$host_cpu" = ia64; then
+	# VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release
+	# chokes on -Wl,-G. The following line is correct:
+	  shared_flag='-G'
+	else
+	  if test "$aix_use_runtimelinking" = yes; then
+	    shared_flag='${wl}-G'
+	  else
+	    shared_flag='${wl}-bM:SRE'
+	  fi
+	fi
+      fi
 
-        echo "$as_me:$LINENO: checking for gdImageCreatePaletteFromTrueColor in -lgd" >&5
-echo $ECHO_N "checking for gdImageCreatePaletteFromTrueColor in -lgd... $ECHO_C" >&6
-if test "${ac_cv_lib_gd_gdImageCreatePaletteFromTrueColor+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-lgd $GD_XTRA_LIBS $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+      export_dynamic_flag_spec='${wl}-bexpall'
+      # It seems that -bexpall does not export symbols beginning with
+      # underscore (_), so it is better to generate a list of symbols to export.
+      always_export_symbols=yes
+      if test "$aix_use_runtimelinking" = yes; then
+	# Warning - without using the other runtime loading flags (-brtl),
+	# -berok will link without error, but may produce a broken library.
+	allow_undefined_flag='-berok'
+        # Determine the default libpath from the value encoded in an
+        # empty executable.
+        if test "${lt_cv_aix_libpath+set}" = set; then
+  aix_libpath=$lt_cv_aix_libpath
+else
+  if ${lt_cv_aix_libpath_+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char gdImageCreatePaletteFromTrueColor ();
 int
 main ()
 {
-gdImageCreatePaletteFromTrueColor ();
+
   ;
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_gd_gdImageCreatePaletteFromTrueColor=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-ac_cv_lib_gd_gdImageCreatePaletteFromTrueColor=no
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
+if ac_fn_c_try_link "$LINENO"; then :
+
+  lt_aix_libpath_sed='
+      /Import File Strings/,/^$/ {
+	  /^0/ {
+	      s/^0  *\([^ ]*\) *$/\1/
+	      p
+	  }
+      }'
+  lt_cv_aix_libpath_=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"`
+  # Check for a 64-bit object if we didn't find anything.
+  if test -z "$lt_cv_aix_libpath_"; then
+    lt_cv_aix_libpath_=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"`
+  fi
 fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_gd_gdImageCreatePaletteFromTrueColor" >&5
-echo "${ECHO_T}$ac_cv_lib_gd_gdImageCreatePaletteFromTrueColor" >&6
-if test $ac_cv_lib_gd_gdImageCreatePaletteFromTrueColor = yes; then
-  IS_GD2="true"
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+  if test -z "$lt_cv_aix_libpath_"; then
+    lt_cv_aix_libpath_="/usr/lib:/lib"
+  fi
+
 fi
 
+  aix_libpath=$lt_cv_aix_libpath_
+fi
 
-    if test "$IS_GD2" = "false" -a -n "$ICONV_LIB"; then
-            { echo "$as_me:$LINENO: checking whether GD needs libiconv..." >&5
-echo "$as_me: checking whether GD needs libiconv..." >&6;}
-      unset ac_cv_lib_gd_gdImageCreatePaletteFromTrueColor
-      echo "$as_me:$LINENO: checking for gdImageCreatePaletteFromTrueColor in -lgd" >&5
-echo $ECHO_N "checking for gdImageCreatePaletteFromTrueColor in -lgd... $ECHO_C" >&6
-if test "${ac_cv_lib_gd_gdImageCreatePaletteFromTrueColor+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+        hardcode_libdir_flag_spec='${wl}-blibpath:$libdir:'"$aix_libpath"
+        archive_expsym_cmds='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then func_echo_all "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag"
+      else
+	if test "$host_cpu" = ia64; then
+	  hardcode_libdir_flag_spec='${wl}-R $libdir:/usr/lib:/lib'
+	  allow_undefined_flag="-z nodefs"
+	  archive_expsym_cmds="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols"
+	else
+	 # Determine the default libpath from the value encoded in an
+	 # empty executable.
+	 if test "${lt_cv_aix_libpath+set}" = set; then
+  aix_libpath=$lt_cv_aix_libpath
 else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-lgd $GD_XTRA_LIBS $ICONV_LIB $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+  if ${lt_cv_aix_libpath_+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char gdImageCreatePaletteFromTrueColor ();
 int
 main ()
 {
-gdImageCreatePaletteFromTrueColor ();
+
   ;
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_gd_gdImageCreatePaletteFromTrueColor=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-ac_cv_lib_gd_gdImageCreatePaletteFromTrueColor=no
+if ac_fn_c_try_link "$LINENO"; then :
+
+  lt_aix_libpath_sed='
+      /Import File Strings/,/^$/ {
+	  /^0/ {
+	      s/^0  *\([^ ]*\) *$/\1/
+	      p
+	  }
+      }'
+  lt_cv_aix_libpath_=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"`
+  # Check for a 64-bit object if we didn't find anything.
+  if test -z "$lt_cv_aix_libpath_"; then
+    lt_cv_aix_libpath_=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"`
+  fi
 fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+  if test -z "$lt_cv_aix_libpath_"; then
+    lt_cv_aix_libpath_="/usr/lib:/lib"
+  fi
+
 fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_gd_gdImageCreatePaletteFromTrueColor" >&5
-echo "${ECHO_T}$ac_cv_lib_gd_gdImageCreatePaletteFromTrueColor" >&6
-if test $ac_cv_lib_gd_gdImageCreatePaletteFromTrueColor = yes; then
-  IS_GD2="true"
+
+  aix_libpath=$lt_cv_aix_libpath_
 fi
 
-      GD_NEED_ICONV_LIB="$ICONV_LIB"
-    fi
+	 hardcode_libdir_flag_spec='${wl}-blibpath:$libdir:'"$aix_libpath"
+	  # Warning - without using the other run time loading flags,
+	  # -berok will link without error, but may produce a broken library.
+	  no_undefined_flag=' ${wl}-bernotok'
+	  allow_undefined_flag=' ${wl}-berok'
+	  if test "$with_gnu_ld" = yes; then
+	    # We only use this code for GNU lds that support --whole-archive.
+	    whole_archive_flag_spec='${wl}--whole-archive$convenience ${wl}--no-whole-archive'
+	  else
+	    # Exported symbols can be pulled into shared objects from archives
+	    whole_archive_flag_spec='$convenience'
+	  fi
+	  archive_cmds_need_lc=yes
+	  # This is similar to how AIX traditionally builds its shared libraries.
+	  archive_expsym_cmds="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname'
+	fi
+      fi
+      ;;
 
-    if test -n "$GD_INCLUDE" -a -n "$GD_LIBDIR" -a "$IS_GD2" = "true"; then
-      GD_INC=-I$GD_INCLUDE
-      GD_LIB="-L$GD_LIBDIR -lgd"
-      GD_XTRA_LIBS="$GD_XTRA_LIBS $GD_NEED_ICONV_LIB"
-      echo "$as_me:$LINENO: result:         using libgd 2.0.28 (or higher) from system libs ($GD_LIB $GD_XTRA_LIBS)." >&5
-echo "${ECHO_T}        using libgd 2.0.28 (or higher) from system libs ($GD_LIB $GD_XTRA_LIBS)." >&6
+    amigaos*)
+      case $host_cpu in
+      powerpc)
+            # see comment about AmigaOS4 .so support
+            archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+            archive_expsym_cmds=''
+        ;;
+      m68k)
+            archive_cmds='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)'
+            hardcode_libdir_flag_spec='-L$libdir'
+            hardcode_minus_L=yes
+        ;;
+      esac
+      ;;
 
-  if test ""$GD_LIBDIR"" != "/usr/lib"; then
+    bsdi[45]*)
+      export_dynamic_flag_spec=-rdynamic
+      ;;
 
-  if test -z ""$GD_LIBDIR"" || echo ""$GD_LIBDIR"" | grep '^/' >/dev/null ; then
-    ai_p=""$GD_LIBDIR""
-  else
-    ai_p="`pwd`/"$GD_LIBDIR""
-  fi
+    cygwin* | mingw* | pw32* | cegcc*)
+      # When not using gcc, we currently assume that we are using
+      # Microsoft Visual C++.
+      # hardcode_libdir_flag_spec is actually meaningless, as there is
+      # no search path for DLLs.
+      case $cc_basename in
+      cl*)
+	# Native MSVC
+	hardcode_libdir_flag_spec=' '
+	allow_undefined_flag=unsupported
+	always_export_symbols=yes
+	file_list_spec='@'
+	# Tell ltmain to make .lib files, not .a files.
+	libext=lib
+	# Tell ltmain to make .dll files, not .so files.
+	shrext_cmds=".dll"
+	# FIXME: Setting linknames here is a bad hack.
+	archive_cmds='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-dll~linknames='
+	archive_expsym_cmds='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
+	    sed -n -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' -e '1\\\!p' < $export_symbols > $output_objdir/$soname.exp;
+	  else
+	    sed -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' < $export_symbols > $output_objdir/$soname.exp;
+	  fi~
+	  $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~
+	  linknames='
+	# The linker will not automatically build a static lib if we build a DLL.
+	# _LT_TAGVAR(old_archive_from_new_cmds, )='true'
+	enable_shared_with_static_runtimes=yes
+	exclude_expsyms='_NULL_IMPORT_DESCRIPTOR|_IMPORT_DESCRIPTOR_.*'
+	export_symbols_cmds='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[BCDGRS][ ]/s/.*[ ]\([^ ]*\)/\1,DATA/'\'' | $SED -e '\''/^[AITW][ ]/s/.*[ ]//'\'' | sort | uniq > $export_symbols'
+	# Don't use ranlib
+	old_postinstall_cmds='chmod 644 $oldlib'
+	postlink_cmds='lt_outputfile="@OUTPUT@"~
+	  lt_tool_outputfile="@TOOL_OUTPUT@"~
+	  case $lt_outputfile in
+	    *.exe|*.EXE) ;;
+	    *)
+	      lt_outputfile="$lt_outputfile.exe"
+	      lt_tool_outputfile="$lt_tool_outputfile.exe"
+	      ;;
+	  esac~
+	  if test "$MANIFEST_TOOL" != ":" && test -f "$lt_outputfile.manifest"; then
+	    $MANIFEST_TOOL -manifest "$lt_tool_outputfile.manifest" -outputresource:"$lt_tool_outputfile" || exit 1;
+	    $RM "$lt_outputfile.manifest";
+	  fi'
+	;;
+      *)
+	# Assume MSVC wrapper
+	hardcode_libdir_flag_spec=' '
+	allow_undefined_flag=unsupported
+	# Tell ltmain to make .lib files, not .a files.
+	libext=lib
+	# Tell ltmain to make .dll files, not .so files.
+	shrext_cmds=".dll"
+	# FIXME: Setting linknames here is a bad hack.
+	archive_cmds='$CC -o $lib $libobjs $compiler_flags `func_echo_all "$deplibs" | $SED '\''s/ -lc$//'\''` -link -dll~linknames='
+	# The linker will automatically build a .lib file if we build a DLL.
+	old_archive_from_new_cmds='true'
+	# FIXME: Should let the user specify the lib program.
+	old_archive_cmds='lib -OUT:$oldlib$oldobjs$old_deplibs'
+	enable_shared_with_static_runtimes=yes
+	;;
+      esac
+      ;;
 
+    darwin* | rhapsody*)
 
-  unique=`echo $ac_n "$ai_p$ac_c" | tr -c -d a-zA-Z0-9`
-  cmd="echo $ac_n \"\$LIBPATH$unique$ac_c\""
-  if test -n "$unique" && test "`eval $cmd`" = "" ; then
-    eval "LIBPATH$unique=set"
 
-      EXTRA_LIBS="$EXTRA_LIBS -L$ai_p"
-        RPATHS="$RPATHS ${ld_runpath_switch}$ai_p"
+  archive_cmds_need_lc=no
+  hardcode_direct=no
+  hardcode_automatic=yes
+  hardcode_shlibpath_var=unsupported
+  if test "$lt_cv_ld_force_load" = "yes"; then
+    whole_archive_flag_spec='`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience ${wl}-force_load,$conv\"; done; func_echo_all \"$new_convenience\"`'
 
+  else
+    whole_archive_flag_spec=''
   fi
+  link_all_deplibs=yes
+  allow_undefined_flag="$_lt_dar_allow_undefined"
+  case $cc_basename in
+     ifort*) _lt_dar_can_shared=yes ;;
+     *) _lt_dar_can_shared=$GCC ;;
+  esac
+  if test "$_lt_dar_can_shared" = "yes"; then
+    output_verbose_link_cmd=func_echo_all
+    archive_cmds="\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod${_lt_dsymutil}"
+    module_cmds="\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dsymutil}"
+    archive_expsym_cmds="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring ${_lt_dar_single_mod}${_lt_dar_export_syms}${_lt_dsymutil}"
+    module_expsym_cmds="sed -e 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dar_export_syms}${_lt_dsymutil}"
 
+  else
+  ld_shlibs=no
   fi
 
-      FOUND_GD="true"
-      break;
-    fi
-  done
+      ;;
 
-  if test "$FOUND_GD" = "false" ; then
-    { { echo "$as_me:$LINENO: error: Could not find gd.h or libgd.a/libgd.so in $GD_DIR.  Make sure GD 2.0.28 or higher is compiled before calling configure. You may also get this error if you didn't specify the appropriate location for one of GD's dependencies (freetype, libpng, libjpeg or libiconv)." >&5
-echo "$as_me: error: Could not find gd.h or libgd.a/libgd.so in $GD_DIR.  Make sure GD 2.0.28 or higher is compiled before calling configure. You may also get this error if you didn't specify the appropriate location for one of GD's dependencies (freetype, libpng, libjpeg or libiconv)." >&2;}
-   { (exit 1); exit 1; }; }
-  fi
-fi
+    dgux*)
+      archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+      hardcode_libdir_flag_spec='-L$libdir'
+      hardcode_shlibpath_var=no
+      ;;
 
+    # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor
+    # support.  Future versions do this automatically, but an explicit c++rt0.o
+    # does not break anything, and helps significantly (at the cost of a little
+    # extra space).
+    freebsd2.2*)
+      archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags /usr/lib/c++rt0.o'
+      hardcode_libdir_flag_spec='-R$libdir'
+      hardcode_direct=yes
+      hardcode_shlibpath_var=no
+      ;;
 
-if test -n "$with_gd" -a "$with_gd" != "yes" ; then
+    # Unfortunately, older versions of FreeBSD 2 do not have this feature.
+    freebsd2.*)
+      archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'
+      hardcode_direct=yes
+      hardcode_minus_L=yes
+      hardcode_shlibpath_var=no
+      ;;
 
+    # FreeBSD 3 and greater uses gcc -shared to do shared libraries.
+    freebsd* | dragonfly*)
+      archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
+      hardcode_libdir_flag_spec='-R$libdir'
+      hardcode_direct=yes
+      hardcode_shlibpath_var=no
+      ;;
 
-  if test "$GD_STATIC" = "yes" ; then
-            GD_CHECKLIB=c
-    GD_LIB=$GD_LIBDIR/libgd.a
-    GD_STATIC=$GD_LIBDIR/libgd.a
-    echo "$as_me:$LINENO: result: static linkage of $GD_STATIC requested... testing supported formats..." >&5
-echo "${ECHO_T}static linkage of $GD_STATIC requested... testing supported formats..." >&6
-  else
-    GD_CHECKLIB=c
-    # GD_LIB was already set above
-    GD_STATIC=""
-  fi
+    hpux9*)
+      if test "$GCC" = yes; then
+	archive_cmds='$RM $output_objdir/$soname~$CC -shared $pic_flag ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+      else
+	archive_cmds='$RM $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+      fi
+      hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir'
+      hardcode_libdir_separator=:
+      hardcode_direct=yes
+
+      # hardcode_minus_L: Not really in the search PATH,
+      # but as the default location of the library.
+      hardcode_minus_L=yes
+      export_dynamic_flag_spec='${wl}-E'
+      ;;
 
-  as_ac_Lib=`echo "ac_cv_lib_$GD_CHECKLIB''_gdImageGif" | $as_tr_sh`
-echo "$as_me:$LINENO: checking for gdImageGif in -l$GD_CHECKLIB" >&5
-echo $ECHO_N "checking for gdImageGif in -l$GD_CHECKLIB... $ECHO_C" >&6
-if eval "test \"\${$as_ac_Lib+set}\" = set"; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-l$GD_CHECKLIB $GD_STATIC $GD_LIB $GD_XTRA_LIBS $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
+    hpux10*)
+      if test "$GCC" = yes && test "$with_gnu_ld" = no; then
+	archive_cmds='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
+      else
+	archive_cmds='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags'
+      fi
+      if test "$with_gnu_ld" = no; then
+	hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir'
+	hardcode_libdir_separator=:
+	hardcode_direct=yes
+	hardcode_direct_absolute=yes
+	export_dynamic_flag_spec='${wl}-E'
+	# hardcode_minus_L: Not really in the search PATH,
+	# but as the default location of the library.
+	hardcode_minus_L=yes
+      fi
+      ;;
 
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char gdImageGif ();
-int
-main ()
-{
-gdImageGif ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  eval "$as_ac_Lib=yes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
+    hpux11*)
+      if test "$GCC" = yes && test "$with_gnu_ld" = no; then
+	case $host_cpu in
+	hppa*64*)
+	  archive_cmds='$CC -shared ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
+	  ;;
+	ia64*)
+	  archive_cmds='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
+	  ;;
+	*)
+	  archive_cmds='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
+	  ;;
+	esac
+      else
+	case $host_cpu in
+	hppa*64*)
+	  archive_cmds='$CC -b ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
+	  ;;
+	ia64*)
+	  archive_cmds='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
+	  ;;
+	*)
+
+	  # Older versions of the 11.00 compiler do not understand -b yet
+	  # (HP92453-01 A.11.01.20 doesn't, HP92453-01 B.11.X.35175-35176.GP does)
+	  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $CC understands -b" >&5
+$as_echo_n "checking if $CC understands -b... " >&6; }
+if ${lt_cv_prog_compiler__b+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  lt_cv_prog_compiler__b=no
+   save_LDFLAGS="$LDFLAGS"
+   LDFLAGS="$LDFLAGS -b"
+   echo "$lt_simple_link_test_code" > conftest.$ac_ext
+   if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then
+     # The linker can only warn and ignore the option if not recognized
+     # So say no if there are warnings
+     if test -s conftest.err; then
+       # Append any errors to the config.log.
+       cat conftest.err 1>&5
+       $ECHO "$_lt_linker_boilerplate" | $SED '/^$/d' > conftest.exp
+       $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
+       if diff conftest.exp conftest.er2 >/dev/null; then
+         lt_cv_prog_compiler__b=yes
+       fi
+     else
+       lt_cv_prog_compiler__b=yes
+     fi
+   fi
+   $RM -r conftest*
+   LDFLAGS="$save_LDFLAGS"
 
-eval "$as_ac_Lib=no"
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Lib'}'`" >&5
-echo "${ECHO_T}`eval echo '${'$as_ac_Lib'}'`" >&6
-if test `eval echo '${'$as_ac_Lib'}'` = yes; then
-  GD_DEF="$GD_DEF -DUSE_GD_GIF"
 fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler__b" >&5
+$as_echo "$lt_cv_prog_compiler__b" >&6; }
 
-  as_ac_Lib=`echo "ac_cv_lib_$GD_CHECKLIB''_gdImagePng" | $as_tr_sh`
-echo "$as_me:$LINENO: checking for gdImagePng in -l$GD_CHECKLIB" >&5
-echo $ECHO_N "checking for gdImagePng in -l$GD_CHECKLIB... $ECHO_C" >&6
-if eval "test \"\${$as_ac_Lib+set}\" = set"; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+if test x"$lt_cv_prog_compiler__b" = xyes; then
+    archive_cmds='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
 else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-l$GD_CHECKLIB $GD_STATIC $GD_LIB $GD_XTRA_LIBS $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
+    archive_cmds='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags'
+fi
 
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char gdImagePng ();
-int
-main ()
-{
-gdImagePng ();
-  ;
-  return 0;
-}
+	  ;;
+	esac
+      fi
+      if test "$with_gnu_ld" = no; then
+	hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir'
+	hardcode_libdir_separator=:
+
+	case $host_cpu in
+	hppa*64*|ia64*)
+	  hardcode_direct=no
+	  hardcode_shlibpath_var=no
+	  ;;
+	*)
+	  hardcode_direct=yes
+	  hardcode_direct_absolute=yes
+	  export_dynamic_flag_spec='${wl}-E'
+
+	  # hardcode_minus_L: Not really in the search PATH,
+	  # but as the default location of the library.
+	  hardcode_minus_L=yes
+	  ;;
+	esac
+      fi
+      ;;
+
+    irix5* | irix6* | nonstopux*)
+      if test "$GCC" = yes; then
+	archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+	# Try to use the -exported_symbol ld option, if it does not
+	# work, assume that -exports_file does not work either and
+	# implicitly export all symbols.
+	# This should be the same for all languages, so no per-tag cache variable.
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the $host_os linker accepts -exported_symbol" >&5
+$as_echo_n "checking whether the $host_os linker accepts -exported_symbol... " >&6; }
+if ${lt_cv_irix_exported_symbol+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  save_LDFLAGS="$LDFLAGS"
+	   LDFLAGS="$LDFLAGS -shared ${wl}-exported_symbol ${wl}foo ${wl}-update_registry ${wl}/dev/null"
+	   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+int foo (void) { return 0; }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  eval "$as_ac_Lib=yes"
+if ac_fn_c_try_link "$LINENO"; then :
+  lt_cv_irix_exported_symbol=yes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-eval "$as_ac_Lib=no"
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
+  lt_cv_irix_exported_symbol=no
 fi
-echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Lib'}'`" >&5
-echo "${ECHO_T}`eval echo '${'$as_ac_Lib'}'`" >&6
-if test `eval echo '${'$as_ac_Lib'}'` = yes; then
-  GD_DEF="$GD_DEF -DUSE_GD_PNG"
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+           LDFLAGS="$save_LDFLAGS"
 fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_irix_exported_symbol" >&5
+$as_echo "$lt_cv_irix_exported_symbol" >&6; }
+	if test "$lt_cv_irix_exported_symbol" = yes; then
+          archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations ${wl}-exports_file ${wl}$export_symbols -o $lib'
+	fi
+      else
+	archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
+	archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -exports_file $export_symbols -o $lib'
+      fi
+      archive_cmds_need_lc='no'
+      hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir'
+      hardcode_libdir_separator=:
+      inherit_rpath=yes
+      link_all_deplibs=yes
+      ;;
 
-  as_ac_Lib=`echo "ac_cv_lib_$GD_CHECKLIB''_gdImageJpeg" | $as_tr_sh`
-echo "$as_me:$LINENO: checking for gdImageJpeg in -l$GD_CHECKLIB" >&5
-echo $ECHO_N "checking for gdImageJpeg in -l$GD_CHECKLIB... $ECHO_C" >&6
-if eval "test \"\${$as_ac_Lib+set}\" = set"; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-l$GD_CHECKLIB $GD_STATIC $GD_LIB $GD_XTRA_LIBS $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
+    netbsd* | netbsdelf*-gnu)
+      if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
+	archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'  # a.out
+      else
+	archive_cmds='$LD -shared -o $lib $libobjs $deplibs $linker_flags'      # ELF
+      fi
+      hardcode_libdir_flag_spec='-R$libdir'
+      hardcode_direct=yes
+      hardcode_shlibpath_var=no
+      ;;
 
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
+    newsos6)
+      archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+      hardcode_direct=yes
+      hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir'
+      hardcode_libdir_separator=:
+      hardcode_shlibpath_var=no
+      ;;
+
+    *nto* | *qnx*)
+      ;;
+
+    openbsd*)
+      if test -f /usr/libexec/ld.so; then
+	hardcode_direct=yes
+	hardcode_shlibpath_var=no
+	hardcode_direct_absolute=yes
+	if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+	  archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
+	  archive_expsym_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-retain-symbols-file,$export_symbols'
+	  hardcode_libdir_flag_spec='${wl}-rpath,$libdir'
+	  export_dynamic_flag_spec='${wl}-E'
+	else
+	  case $host_os in
+	   openbsd[01].* | openbsd2.[0-7] | openbsd2.[0-7].*)
+	     archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'
+	     hardcode_libdir_flag_spec='-R$libdir'
+	     ;;
+	   *)
+	     archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
+	     hardcode_libdir_flag_spec='${wl}-rpath,$libdir'
+	     ;;
+	  esac
+	fi
+      else
+	ld_shlibs=no
+      fi
+      ;;
+
+    os2*)
+      hardcode_libdir_flag_spec='-L$libdir'
+      hardcode_minus_L=yes
+      allow_undefined_flag=unsupported
+      archive_cmds='$ECHO "LIBRARY $libname INITINSTANCE" > $output_objdir/$libname.def~$ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~echo DATA >> $output_objdir/$libname.def~echo " SINGLE NONSHARED" >> $output_objdir/$libname.def~echo EXPORTS >> $output_objdir/$libname.def~emxexp $libobjs >> $output_objdir/$libname.def~$CC -Zdll -Zcrtdll -o $lib $libobjs $deplibs $compiler_flags $output_objdir/$libname.def'
+      old_archive_from_new_cmds='emximp -o $output_objdir/$libname.a $output_objdir/$libname.def'
+      ;;
+
+    osf3*)
+      if test "$GCC" = yes; then
+	allow_undefined_flag=' ${wl}-expect_unresolved ${wl}\*'
+	archive_cmds='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+      else
+	allow_undefined_flag=' -expect_unresolved \*'
+	archive_cmds='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
+      fi
+      archive_cmds_need_lc='no'
+      hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir'
+      hardcode_libdir_separator=:
+      ;;
+
+    osf4* | osf5*)	# as osf3* with the addition of -msym flag
+      if test "$GCC" = yes; then
+	allow_undefined_flag=' ${wl}-expect_unresolved ${wl}\*'
+	archive_cmds='$CC -shared${allow_undefined_flag} $pic_flag $libobjs $deplibs $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+	hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir'
+      else
+	allow_undefined_flag=' -expect_unresolved \*'
+	archive_cmds='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -msym -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
+	archive_expsym_cmds='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; printf "%s\\n" "-hidden">> $lib.exp~
+	$CC -shared${allow_undefined_flag} ${wl}-input ${wl}$lib.exp $compiler_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && $ECHO "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib~$RM $lib.exp'
+
+	# Both c and cxx compiler support -rpath directly
+	hardcode_libdir_flag_spec='-rpath $libdir'
+      fi
+      archive_cmds_need_lc='no'
+      hardcode_libdir_separator=:
+      ;;
+
+    solaris*)
+      no_undefined_flag=' -z defs'
+      if test "$GCC" = yes; then
+	wlarc='${wl}'
+	archive_cmds='$CC -shared $pic_flag ${wl}-z ${wl}text ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
+	archive_expsym_cmds='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
+	  $CC -shared $pic_flag ${wl}-z ${wl}text ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp'
+      else
+	case `$CC -V 2>&1` in
+	*"Compilers 5.0"*)
+	  wlarc=''
+	  archive_cmds='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags'
+	  archive_expsym_cmds='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
+	  $LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$RM $lib.exp'
+	  ;;
+	*)
+	  wlarc='${wl}'
+	  archive_cmds='$CC -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $compiler_flags'
+	  archive_expsym_cmds='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
+	  $CC -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp'
+	  ;;
+	esac
+      fi
+      hardcode_libdir_flag_spec='-R$libdir'
+      hardcode_shlibpath_var=no
+      case $host_os in
+      solaris2.[0-5] | solaris2.[0-5].*) ;;
+      *)
+	# The compiler driver will combine and reorder linker options,
+	# but understands `-z linker_flag'.  GCC discards it without `$wl',
+	# but is careful enough not to reorder.
+	# Supported since Solaris 2.6 (maybe 2.5.1?)
+	if test "$GCC" = yes; then
+	  whole_archive_flag_spec='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract'
+	else
+	  whole_archive_flag_spec='-z allextract$convenience -z defaultextract'
+	fi
+	;;
+      esac
+      link_all_deplibs=yes
+      ;;
+
+    sunos4*)
+      if test "x$host_vendor" = xsequent; then
+	# Use $CC to link under sequent, because it throws in some extra .o
+	# files that make .init and .fini sections work.
+	archive_cmds='$CC -G ${wl}-h $soname -o $lib $libobjs $deplibs $compiler_flags'
+      else
+	archive_cmds='$LD -assert pure-text -Bstatic -o $lib $libobjs $deplibs $linker_flags'
+      fi
+      hardcode_libdir_flag_spec='-L$libdir'
+      hardcode_direct=yes
+      hardcode_minus_L=yes
+      hardcode_shlibpath_var=no
+      ;;
+
+    sysv4)
+      case $host_vendor in
+	sni)
+	  archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+	  hardcode_direct=yes # is this really true???
+	;;
+	siemens)
+	  ## LD is ld it makes a PLAMLIB
+	  ## CC just makes a GrossModule.
+	  archive_cmds='$LD -G -o $lib $libobjs $deplibs $linker_flags'
+	  reload_cmds='$CC -r -o $output$reload_objs'
+	  hardcode_direct=no
+        ;;
+	motorola)
+	  archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+	  hardcode_direct=no #Motorola manual says yes, but my tests say they lie
+	;;
+      esac
+      runpath_var='LD_RUN_PATH'
+      hardcode_shlibpath_var=no
+      ;;
+
+    sysv4.3*)
+      archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+      hardcode_shlibpath_var=no
+      export_dynamic_flag_spec='-Bexport'
+      ;;
+
+    sysv4*MP*)
+      if test -d /usr/nec; then
+	archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+	hardcode_shlibpath_var=no
+	runpath_var=LD_RUN_PATH
+	hardcode_runpath_var=yes
+	ld_shlibs=yes
+      fi
+      ;;
+
+    sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[01].[10]* | unixware7* | sco3.2v5.0.[024]*)
+      no_undefined_flag='${wl}-z,text'
+      archive_cmds_need_lc=no
+      hardcode_shlibpath_var=no
+      runpath_var='LD_RUN_PATH'
+
+      if test "$GCC" = yes; then
+	archive_cmds='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	archive_expsym_cmds='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+      else
+	archive_cmds='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	archive_expsym_cmds='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+      fi
+      ;;
+
+    sysv5* | sco3.2v5* | sco5v6*)
+      # Note: We can NOT use -z defs as we might desire, because we do not
+      # link with -lc, and that would cause any symbols used from libc to
+      # always be unresolved, which means just about no library would
+      # ever link correctly.  If we're not using GNU ld we use -z text
+      # though, which does catch some bad symbols but isn't as heavy-handed
+      # as -z defs.
+      no_undefined_flag='${wl}-z,text'
+      allow_undefined_flag='${wl}-z,nodefs'
+      archive_cmds_need_lc=no
+      hardcode_shlibpath_var=no
+      hardcode_libdir_flag_spec='${wl}-R,$libdir'
+      hardcode_libdir_separator=':'
+      link_all_deplibs=yes
+      export_dynamic_flag_spec='${wl}-Bexport'
+      runpath_var='LD_RUN_PATH'
+
+      if test "$GCC" = yes; then
+	archive_cmds='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	archive_expsym_cmds='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+      else
+	archive_cmds='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	archive_expsym_cmds='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+      fi
+      ;;
+
+    uts4*)
+      archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+      hardcode_libdir_flag_spec='-L$libdir'
+      hardcode_shlibpath_var=no
+      ;;
+
+    *)
+      ld_shlibs=no
+      ;;
+    esac
+
+    if test x$host_vendor = xsni; then
+      case $host in
+      sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*)
+	export_dynamic_flag_spec='${wl}-Blargedynsym'
+	;;
+      esac
+    fi
+  fi
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ld_shlibs" >&5
+$as_echo "$ld_shlibs" >&6; }
+test "$ld_shlibs" = no && can_build_shared=no
+
+with_gnu_ld=$with_gnu_ld
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+#
+# Do we need to explicitly link libc?
+#
+case "x$archive_cmds_need_lc" in
+x|xyes)
+  # Assume -lc should be added
+  archive_cmds_need_lc=yes
+
+  if test "$enable_shared" = yes && test "$GCC" = yes; then
+    case $archive_cmds in
+    *'~'*)
+      # FIXME: we may have to deal with multi-command sequences.
+      ;;
+    '$CC '*)
+      # Test whether the compiler implicitly links with -lc since on some
+      # systems, -lgcc has to come before -lc. If gcc already passes -lc
+      # to ld, don't add -lc before -lgcc.
+      { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether -lc should be explicitly linked in" >&5
+$as_echo_n "checking whether -lc should be explicitly linked in... " >&6; }
+if ${lt_cv_archive_cmds_need_lc+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  $RM conftest*
+	echo "$lt_simple_compile_test_code" > conftest.$ac_ext
+
+	if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5
+  (eval $ac_compile) 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; } 2>conftest.err; then
+	  soname=conftest
+	  lib=conftest
+	  libobjs=conftest.$ac_objext
+	  deplibs=
+	  wl=$lt_prog_compiler_wl
+	  pic_flag=$lt_prog_compiler_pic
+	  compiler_flags=-v
+	  linker_flags=-v
+	  verstring=
+	  output_objdir=.
+	  libname=conftest
+	  lt_save_allow_undefined_flag=$allow_undefined_flag
+	  allow_undefined_flag=
+	  if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$archive_cmds 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1\""; } >&5
+  (eval $archive_cmds 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1) 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }
+	  then
+	    lt_cv_archive_cmds_need_lc=no
+	  else
+	    lt_cv_archive_cmds_need_lc=yes
+	  fi
+	  allow_undefined_flag=$lt_save_allow_undefined_flag
+	else
+	  cat conftest.err 1>&5
+	fi
+	$RM conftest*
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_archive_cmds_need_lc" >&5
+$as_echo "$lt_cv_archive_cmds_need_lc" >&6; }
+      archive_cmds_need_lc=$lt_cv_archive_cmds_need_lc
+      ;;
+    esac
+  fi
+  ;;
+esac
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking dynamic linker characteristics" >&5
+$as_echo_n "checking dynamic linker characteristics... " >&6; }
+
+if test "$GCC" = yes; then
+  case $host_os in
+    darwin*) lt_awk_arg="/^libraries:/,/LR/" ;;
+    *) lt_awk_arg="/^libraries:/" ;;
+  esac
+  case $host_os in
+    mingw* | cegcc*) lt_sed_strip_eq="s,=\([A-Za-z]:\),\1,g" ;;
+    *) lt_sed_strip_eq="s,=/,/,g" ;;
+  esac
+  lt_search_path_spec=`$CC -print-search-dirs | awk $lt_awk_arg | $SED -e "s/^libraries://" -e $lt_sed_strip_eq`
+  case $lt_search_path_spec in
+  *\;*)
+    # if the path contains ";" then we assume it to be the separator
+    # otherwise default to the standard path separator (i.e. ":") - it is
+    # assumed that no part of a normal pathname contains ";" but that should
+    # okay in the real world where ";" in dirpaths is itself problematic.
+    lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED 's/;/ /g'`
+    ;;
+  *)
+    lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED "s/$PATH_SEPARATOR/ /g"`
+    ;;
+  esac
+  # Ok, now we have the path, separated by spaces, we can step through it
+  # and add multilib dir if necessary.
+  lt_tmp_lt_search_path_spec=
+  lt_multi_os_dir=`$CC $CPPFLAGS $CFLAGS $LDFLAGS -print-multi-os-directory 2>/dev/null`
+  for lt_sys_path in $lt_search_path_spec; do
+    if test -d "$lt_sys_path/$lt_multi_os_dir"; then
+      lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path/$lt_multi_os_dir"
+    else
+      test -d "$lt_sys_path" && \
+	lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path"
+    fi
+  done
+  lt_search_path_spec=`$ECHO "$lt_tmp_lt_search_path_spec" | awk '
+BEGIN {RS=" "; FS="/|\n";} {
+  lt_foo="";
+  lt_count=0;
+  for (lt_i = NF; lt_i > 0; lt_i--) {
+    if ($lt_i != "" && $lt_i != ".") {
+      if ($lt_i == "..") {
+        lt_count++;
+      } else {
+        if (lt_count == 0) {
+          lt_foo="/" $lt_i lt_foo;
+        } else {
+          lt_count--;
+        }
+      }
+    }
+  }
+  if (lt_foo != "") { lt_freq[lt_foo]++; }
+  if (lt_freq[lt_foo] == 1) { print lt_foo; }
+}'`
+  # AWK program above erroneously prepends '/' to C:/dos/paths
+  # for these hosts.
+  case $host_os in
+    mingw* | cegcc*) lt_search_path_spec=`$ECHO "$lt_search_path_spec" |\
+      $SED 's,/\([A-Za-z]:\),\1,g'` ;;
+  esac
+  sys_lib_search_path_spec=`$ECHO "$lt_search_path_spec" | $lt_NL2SP`
+else
+  sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib"
+fi
+library_names_spec=
+libname_spec='lib$name'
+soname_spec=
+shrext_cmds=".so"
+postinstall_cmds=
+postuninstall_cmds=
+finish_cmds=
+finish_eval=
+shlibpath_var=
+shlibpath_overrides_runpath=unknown
+version_type=none
+dynamic_linker="$host_os ld.so"
+sys_lib_dlsearch_path_spec="/lib /usr/lib"
+need_lib_prefix=unknown
+hardcode_into_libs=no
+
+# when you set need_version to no, make sure it does not cause -set_version
+# flags to be left without arguments
+need_version=unknown
+
+case $host_os in
+aix3*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a'
+  shlibpath_var=LIBPATH
+
+  # AIX 3 has no versioning support, so we append a major version to the name.
+  soname_spec='${libname}${release}${shared_ext}$major'
+  ;;
+
+aix[4-9]*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_lib_prefix=no
+  need_version=no
+  hardcode_into_libs=yes
+  if test "$host_cpu" = ia64; then
+    # AIX 5 supports IA64
+    library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}'
+    shlibpath_var=LD_LIBRARY_PATH
+  else
+    # With GCC up to 2.95.x, collect2 would create an import file
+    # for dependence libraries.  The import file would start with
+    # the line `#! .'.  This would cause the generated library to
+    # depend on `.', always an invalid library.  This was fixed in
+    # development snapshots of GCC prior to 3.0.
+    case $host_os in
+      aix4 | aix4.[01] | aix4.[01].*)
+      if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)'
+	   echo ' yes '
+	   echo '#endif'; } | ${CC} -E - | $GREP yes > /dev/null; then
+	:
+      else
+	can_build_shared=no
+      fi
+      ;;
+    esac
+    # AIX (on Power*) has no versioning support, so currently we can not hardcode correct
+    # soname into executable. Probably we can add versioning support to
+    # collect2, so additional links can be useful in future.
+    if test "$aix_use_runtimelinking" = yes; then
+      # If using run time linking (on AIX 4.2 or later) use lib<name>.so
+      # instead of lib<name>.a to let people know that these are not
+      # typical AIX shared libraries.
+      library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+    else
+      # We preserve .a as extension for shared libraries through AIX4.2
+      # and later when we are not doing run time linking.
+      library_names_spec='${libname}${release}.a $libname.a'
+      soname_spec='${libname}${release}${shared_ext}$major'
+    fi
+    shlibpath_var=LIBPATH
+  fi
+  ;;
+
+amigaos*)
+  case $host_cpu in
+  powerpc)
+    # Since July 2007 AmigaOS4 officially supports .so libraries.
+    # When compiling the executable, add -use-dynld -Lsobjs: to the compileline.
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+    ;;
+  m68k)
+    library_names_spec='$libname.ixlibrary $libname.a'
+    # Create ${libname}_ixlibrary.a entries in /sys/libs.
+    finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`func_echo_all "$lib" | $SED '\''s%^.*/\([^/]*\)\.ixlibrary$%\1%'\''`; test $RM /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done'
+    ;;
+  esac
+  ;;
+
+beos*)
+  library_names_spec='${libname}${shared_ext}'
+  dynamic_linker="$host_os ld.so"
+  shlibpath_var=LIBRARY_PATH
+  ;;
+
+bsdi[45]*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir'
+  shlibpath_var=LD_LIBRARY_PATH
+  sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib"
+  sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib"
+  # the default ld.so.conf also contains /usr/contrib/lib and
+  # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow
+  # libtool to hard-code these into programs
+  ;;
+
+cygwin* | mingw* | pw32* | cegcc*)
+  version_type=windows
+  shrext_cmds=".dll"
+  need_version=no
+  need_lib_prefix=no
+
+  case $GCC,$cc_basename in
+  yes,*)
+    # gcc
+    library_names_spec='$libname.dll.a'
+    # DLL is installed to $(libdir)/../bin by postinstall_cmds
+    postinstall_cmds='base_file=`basename \${file}`~
+      dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~
+      dldir=$destdir/`dirname \$dlpath`~
+      test -d \$dldir || mkdir -p \$dldir~
+      $install_prog $dir/$dlname \$dldir/$dlname~
+      chmod a+x \$dldir/$dlname~
+      if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then
+        eval '\''$striplib \$dldir/$dlname'\'' || exit \$?;
+      fi'
+    postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~
+      dlpath=$dir/\$dldll~
+       $RM \$dlpath'
+    shlibpath_overrides_runpath=yes
+
+    case $host_os in
+    cygwin*)
+      # Cygwin DLLs use 'cyg' prefix rather than 'lib'
+      soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}'
+
+      sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/lib/w32api"
+      ;;
+    mingw* | cegcc*)
+      # MinGW DLLs use traditional 'lib' prefix
+      soname_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}'
+      ;;
+    pw32*)
+      # pw32 DLLs use 'pw' prefix rather than 'lib'
+      library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}'
+      ;;
+    esac
+    dynamic_linker='Win32 ld.exe'
+    ;;
+
+  *,cl*)
+    # Native MSVC
+    libname_spec='$name'
+    soname_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}'
+    library_names_spec='${libname}.dll.lib'
+
+    case $build_os in
+    mingw*)
+      sys_lib_search_path_spec=
+      lt_save_ifs=$IFS
+      IFS=';'
+      for lt_path in $LIB
+      do
+        IFS=$lt_save_ifs
+        # Let DOS variable expansion print the short 8.3 style file name.
+        lt_path=`cd "$lt_path" 2>/dev/null && cmd //C "for %i in (".") do @echo %~si"`
+        sys_lib_search_path_spec="$sys_lib_search_path_spec $lt_path"
+      done
+      IFS=$lt_save_ifs
+      # Convert to MSYS style.
+      sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | sed -e 's|\\\\|/|g' -e 's| \\([a-zA-Z]\\):| /\\1|g' -e 's|^ ||'`
+      ;;
+    cygwin*)
+      # Convert to unix form, then to dos form, then back to unix form
+      # but this time dos style (no spaces!) so that the unix form looks
+      # like /cygdrive/c/PROGRA~1:/cygdr...
+      sys_lib_search_path_spec=`cygpath --path --unix "$LIB"`
+      sys_lib_search_path_spec=`cygpath --path --dos "$sys_lib_search_path_spec" 2>/dev/null`
+      sys_lib_search_path_spec=`cygpath --path --unix "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"`
+      ;;
+    *)
+      sys_lib_search_path_spec="$LIB"
+      if $ECHO "$sys_lib_search_path_spec" | $GREP ';[c-zC-Z]:/' >/dev/null; then
+        # It is most probably a Windows format PATH.
+        sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'`
+      else
+        sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"`
+      fi
+      # FIXME: find the short name or the path components, as spaces are
+      # common. (e.g. "Program Files" -> "PROGRA~1")
+      ;;
+    esac
+
+    # DLL is installed to $(libdir)/../bin by postinstall_cmds
+    postinstall_cmds='base_file=`basename \${file}`~
+      dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~
+      dldir=$destdir/`dirname \$dlpath`~
+      test -d \$dldir || mkdir -p \$dldir~
+      $install_prog $dir/$dlname \$dldir/$dlname'
+    postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~
+      dlpath=$dir/\$dldll~
+       $RM \$dlpath'
+    shlibpath_overrides_runpath=yes
+    dynamic_linker='Win32 link.exe'
+    ;;
+
+  *)
+    # Assume MSVC wrapper
+    library_names_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext} $libname.lib'
+    dynamic_linker='Win32 ld.exe'
+    ;;
+  esac
+  # FIXME: first we should search . and the directory the executable is in
+  shlibpath_var=PATH
+  ;;
+
+darwin* | rhapsody*)
+  dynamic_linker="$host_os dyld"
+  version_type=darwin
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${major}$shared_ext ${libname}$shared_ext'
+  soname_spec='${libname}${release}${major}$shared_ext'
+  shlibpath_overrides_runpath=yes
+  shlibpath_var=DYLD_LIBRARY_PATH
+  shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`'
+
+  sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/local/lib"
+  sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib'
+  ;;
+
+dgux*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  ;;
+
+freebsd* | dragonfly*)
+  # DragonFly does not have aout.  When/if they implement a new
+  # versioning mechanism, adjust this.
+  if test -x /usr/bin/objformat; then
+    objformat=`/usr/bin/objformat`
+  else
+    case $host_os in
+    freebsd[23].*) objformat=aout ;;
+    *) objformat=elf ;;
+    esac
+  fi
+  version_type=freebsd-$objformat
+  case $version_type in
+    freebsd-elf*)
+      library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
+      need_version=no
+      need_lib_prefix=no
+      ;;
+    freebsd-*)
+      library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix'
+      need_version=yes
+      ;;
+  esac
+  shlibpath_var=LD_LIBRARY_PATH
+  case $host_os in
+  freebsd2.*)
+    shlibpath_overrides_runpath=yes
+    ;;
+  freebsd3.[01]* | freebsdelf3.[01]*)
+    shlibpath_overrides_runpath=yes
+    hardcode_into_libs=yes
+    ;;
+  freebsd3.[2-9]* | freebsdelf3.[2-9]* | \
+  freebsd4.[0-5] | freebsdelf4.[0-5] | freebsd4.1.1 | freebsdelf4.1.1)
+    shlibpath_overrides_runpath=no
+    hardcode_into_libs=yes
+    ;;
+  *) # from 4.6 on, and DragonFly
+    shlibpath_overrides_runpath=yes
+    hardcode_into_libs=yes
+    ;;
+  esac
+  ;;
+
+gnu*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=no
+  hardcode_into_libs=yes
+  ;;
+
+haiku*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_lib_prefix=no
+  need_version=no
+  dynamic_linker="$host_os runtime_loader"
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  sys_lib_dlsearch_path_spec='/boot/home/config/lib /boot/common/lib /boot/system/lib'
+  hardcode_into_libs=yes
+  ;;
+
+hpux9* | hpux10* | hpux11*)
+  # Give a soname corresponding to the major version so that dld.sl refuses to
+  # link against other versions.
+  version_type=sunos
+  need_lib_prefix=no
+  need_version=no
+  case $host_cpu in
+  ia64*)
+    shrext_cmds='.so'
+    hardcode_into_libs=yes
+    dynamic_linker="$host_os dld.so"
+    shlibpath_var=LD_LIBRARY_PATH
+    shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+    soname_spec='${libname}${release}${shared_ext}$major'
+    if test "X$HPUX_IA64_MODE" = X32; then
+      sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib"
+    else
+      sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64"
+    fi
+    sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
+    ;;
+  hppa*64*)
+    shrext_cmds='.sl'
+    hardcode_into_libs=yes
+    dynamic_linker="$host_os dld.sl"
+    shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH
+    shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+    soname_spec='${libname}${release}${shared_ext}$major'
+    sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64"
+    sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
+    ;;
+  *)
+    shrext_cmds='.sl'
+    dynamic_linker="$host_os dld.sl"
+    shlibpath_var=SHLIB_PATH
+    shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+    soname_spec='${libname}${release}${shared_ext}$major'
+    ;;
+  esac
+  # HP-UX runs *really* slowly unless shared libraries are mode 555, ...
+  postinstall_cmds='chmod 555 $lib'
+  # or fails outright, so override atomically:
+  install_override_mode=555
+  ;;
+
+interix[3-9]*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=no
+  hardcode_into_libs=yes
+  ;;
+
+irix5* | irix6* | nonstopux*)
+  case $host_os in
+    nonstopux*) version_type=nonstopux ;;
+    *)
+	if test "$lt_cv_prog_gnu_ld" = yes; then
+		version_type=linux # correct to gnu/linux during the next big refactor
+	else
+		version_type=irix
+	fi ;;
+  esac
+  need_lib_prefix=no
+  need_version=no
+  soname_spec='${libname}${release}${shared_ext}$major'
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}'
+  case $host_os in
+  irix5* | nonstopux*)
+    libsuff= shlibsuff=
+    ;;
+  *)
+    case $LD in # libtool.m4 will add one of these switches to LD
+    *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ")
+      libsuff= shlibsuff= libmagic=32-bit;;
+    *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ")
+      libsuff=32 shlibsuff=N32 libmagic=N32;;
+    *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ")
+      libsuff=64 shlibsuff=64 libmagic=64-bit;;
+    *) libsuff= shlibsuff= libmagic=never-match;;
+    esac
+    ;;
+  esac
+  shlibpath_var=LD_LIBRARY${shlibsuff}_PATH
+  shlibpath_overrides_runpath=no
+  sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}"
+  sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}"
+  hardcode_into_libs=yes
+  ;;
+
+# No shared lib support for Linux oldld, aout, or coff.
+linux*oldld* | linux*aout* | linux*coff*)
+  dynamic_linker=no
+  ;;
+
+# This must be glibc/ELF.
+linux* | k*bsd*-gnu | kopensolaris*-gnu)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=no
+
+  # Some binutils ld are patched to set DT_RUNPATH
+  if ${lt_cv_shlibpath_overrides_runpath+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  lt_cv_shlibpath_overrides_runpath=no
+    save_LDFLAGS=$LDFLAGS
+    save_libdir=$libdir
+    eval "libdir=/foo; wl=\"$lt_prog_compiler_wl\"; \
+	 LDFLAGS=\"\$LDFLAGS $hardcode_libdir_flag_spec\""
+    cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  if  ($OBJDUMP -p conftest$ac_exeext) 2>/dev/null | grep "RUNPATH.*$libdir" >/dev/null; then :
+  lt_cv_shlibpath_overrides_runpath=yes
+fi
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+    LDFLAGS=$save_LDFLAGS
+    libdir=$save_libdir
+
+fi
+
+  shlibpath_overrides_runpath=$lt_cv_shlibpath_overrides_runpath
+
+  # This implies no fast_install, which is unacceptable.
+  # Some rework will be needed to allow for fast_install
+  # before this can be enabled.
+  hardcode_into_libs=yes
+
+  # Append ld.so.conf contents to the search path
+  if test -f /etc/ld.so.conf; then
+    lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;/^[	 ]*hwcap[	 ]/d;s/[:,	]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;s/"//g;/^$/d' | tr '\n' ' '`
+    sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra"
+  fi
+
+  # We used to test for /lib/ld.so.1 and disable shared libraries on
+  # powerpc, because MkLinux only supported shared libraries with the
+  # GNU dynamic linker.  Since this was broken with cross compilers,
+  # most powerpc-linux boxes support dynamic linking these days and
+  # people can always --disable-shared, the test was removed, and we
+  # assume the GNU/Linux dynamic linker is in use.
+  dynamic_linker='GNU/Linux ld.so'
+  ;;
+
+netbsdelf*-gnu)
+  version_type=linux
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=no
+  hardcode_into_libs=yes
+  dynamic_linker='NetBSD ld.elf_so'
+  ;;
+
+netbsd*)
+  version_type=sunos
+  need_lib_prefix=no
+  need_version=no
+  if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+    finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
+    dynamic_linker='NetBSD (a.out) ld.so'
+  else
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+    soname_spec='${libname}${release}${shared_ext}$major'
+    dynamic_linker='NetBSD ld.elf_so'
+  fi
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  hardcode_into_libs=yes
+  ;;
+
+newsos6)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  ;;
+
+*nto* | *qnx*)
+  version_type=qnx
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=no
+  hardcode_into_libs=yes
+  dynamic_linker='ldqnx.so'
+  ;;
+
+openbsd*)
+  version_type=sunos
+  sys_lib_dlsearch_path_spec="/usr/lib"
+  need_lib_prefix=no
+  # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs.
+  case $host_os in
+    openbsd3.3 | openbsd3.3.*)	need_version=yes ;;
+    *)				need_version=no  ;;
+  esac
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+  finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
+  shlibpath_var=LD_LIBRARY_PATH
+  if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+    case $host_os in
+      openbsd2.[89] | openbsd2.[89].*)
+	shlibpath_overrides_runpath=no
+	;;
+      *)
+	shlibpath_overrides_runpath=yes
+	;;
+      esac
+  else
+    shlibpath_overrides_runpath=yes
+  fi
+  ;;
+
+os2*)
+  libname_spec='$name'
+  shrext_cmds=".dll"
+  need_lib_prefix=no
+  library_names_spec='$libname${shared_ext} $libname.a'
+  dynamic_linker='OS/2 ld.exe'
+  shlibpath_var=LIBPATH
+  ;;
+
+osf3* | osf4* | osf5*)
+  version_type=osf
+  need_lib_prefix=no
+  need_version=no
+  soname_spec='${libname}${release}${shared_ext}$major'
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  shlibpath_var=LD_LIBRARY_PATH
+  sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib"
+  sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec"
+  ;;
+
+rdos*)
+  dynamic_linker=no
+  ;;
+
+solaris*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  hardcode_into_libs=yes
+  # ldd complains unless libraries are executable
+  postinstall_cmds='chmod +x $lib'
+  ;;
+
+sunos4*)
+  version_type=sunos
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+  finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  if test "$with_gnu_ld" = yes; then
+    need_lib_prefix=no
+  fi
+  need_version=yes
+  ;;
+
+sysv4 | sysv4.3*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  case $host_vendor in
+    sni)
+      shlibpath_overrides_runpath=no
+      need_lib_prefix=no
+      runpath_var=LD_RUN_PATH
+      ;;
+    siemens)
+      need_lib_prefix=no
+      ;;
+    motorola)
+      need_lib_prefix=no
+      need_version=no
+      shlibpath_overrides_runpath=no
+      sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib'
+      ;;
+  esac
+  ;;
+
+sysv4*MP*)
+  if test -d /usr/nec ;then
+    version_type=linux # correct to gnu/linux during the next big refactor
+    library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}'
+    soname_spec='$libname${shared_ext}.$major'
+    shlibpath_var=LD_LIBRARY_PATH
+  fi
+  ;;
+
+sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
+  version_type=freebsd-elf
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  hardcode_into_libs=yes
+  if test "$with_gnu_ld" = yes; then
+    sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib'
+  else
+    sys_lib_search_path_spec='/usr/ccs/lib /usr/lib'
+    case $host_os in
+      sco3.2v5*)
+        sys_lib_search_path_spec="$sys_lib_search_path_spec /lib"
+	;;
+    esac
+  fi
+  sys_lib_dlsearch_path_spec='/usr/lib'
+  ;;
+
+tpf*)
+  # TPF is a cross-target only.  Preferred cross-host = GNU/Linux.
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=no
+  hardcode_into_libs=yes
+  ;;
+
+uts4*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  ;;
+
+*)
+  dynamic_linker=no
+  ;;
+esac
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $dynamic_linker" >&5
+$as_echo "$dynamic_linker" >&6; }
+test "$dynamic_linker" = no && can_build_shared=no
+
+variables_saved_for_relink="PATH $shlibpath_var $runpath_var"
+if test "$GCC" = yes; then
+  variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH"
+fi
+
+if test "${lt_cv_sys_lib_search_path_spec+set}" = set; then
+  sys_lib_search_path_spec="$lt_cv_sys_lib_search_path_spec"
+fi
+if test "${lt_cv_sys_lib_dlsearch_path_spec+set}" = set; then
+  sys_lib_dlsearch_path_spec="$lt_cv_sys_lib_dlsearch_path_spec"
+fi
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to hardcode library paths into programs" >&5
+$as_echo_n "checking how to hardcode library paths into programs... " >&6; }
+hardcode_action=
+if test -n "$hardcode_libdir_flag_spec" ||
+   test -n "$runpath_var" ||
+   test "X$hardcode_automatic" = "Xyes" ; then
+
+  # We can hardcode non-existent directories.
+  if test "$hardcode_direct" != no &&
+     # If the only mechanism to avoid hardcoding is shlibpath_var, we
+     # have to relink, otherwise we might link with an installed library
+     # when we should be linking with a yet-to-be-installed one
+     ## test "$_LT_TAGVAR(hardcode_shlibpath_var, )" != no &&
+     test "$hardcode_minus_L" != no; then
+    # Linking always hardcodes the temporary library directory.
+    hardcode_action=relink
+  else
+    # We can link without hardcoding, and we can hardcode nonexisting dirs.
+    hardcode_action=immediate
+  fi
+else
+  # We cannot hardcode anything, or else we can only hardcode existing
+  # directories.
+  hardcode_action=unsupported
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $hardcode_action" >&5
+$as_echo "$hardcode_action" >&6; }
+
+if test "$hardcode_action" = relink ||
+   test "$inherit_rpath" = yes; then
+  # Fast installation is not supported
+  enable_fast_install=no
+elif test "$shlibpath_overrides_runpath" = yes ||
+     test "$enable_shared" = no; then
+  # Fast installation is not necessary
+  enable_fast_install=needless
+fi
+
+
+
+
+
+
+  if test "x$enable_dlopen" != xyes; then
+  enable_dlopen=unknown
+  enable_dlopen_self=unknown
+  enable_dlopen_self_static=unknown
+else
+  lt_cv_dlopen=no
+  lt_cv_dlopen_libs=
+
+  case $host_os in
+  beos*)
+    lt_cv_dlopen="load_add_on"
+    lt_cv_dlopen_libs=
+    lt_cv_dlopen_self=yes
+    ;;
+
+  mingw* | pw32* | cegcc*)
+    lt_cv_dlopen="LoadLibrary"
+    lt_cv_dlopen_libs=
+    ;;
+
+  cygwin*)
+    lt_cv_dlopen="dlopen"
+    lt_cv_dlopen_libs=
+    ;;
+
+  darwin*)
+  # if libdl is installed we need to link against it
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -ldl" >&5
+$as_echo_n "checking for dlopen in -ldl... " >&6; }
+if ${ac_cv_lib_dl_dlopen+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-ldl  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char dlopen ();
+int
+main ()
+{
+return dlopen ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_dl_dlopen=yes
+else
+  ac_cv_lib_dl_dlopen=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dl_dlopen" >&5
+$as_echo "$ac_cv_lib_dl_dlopen" >&6; }
+if test "x$ac_cv_lib_dl_dlopen" = xyes; then :
+  lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"
+else
+
+    lt_cv_dlopen="dyld"
+    lt_cv_dlopen_libs=
+    lt_cv_dlopen_self=yes
+
+fi
+
+    ;;
+
+  *)
+    ac_fn_c_check_func "$LINENO" "shl_load" "ac_cv_func_shl_load"
+if test "x$ac_cv_func_shl_load" = xyes; then :
+  lt_cv_dlopen="shl_load"
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for shl_load in -ldld" >&5
+$as_echo_n "checking for shl_load in -ldld... " >&6; }
+if ${ac_cv_lib_dld_shl_load+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-ldld  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char shl_load ();
+int
+main ()
+{
+return shl_load ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_dld_shl_load=yes
+else
+  ac_cv_lib_dld_shl_load=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dld_shl_load" >&5
+$as_echo "$ac_cv_lib_dld_shl_load" >&6; }
+if test "x$ac_cv_lib_dld_shl_load" = xyes; then :
+  lt_cv_dlopen="shl_load" lt_cv_dlopen_libs="-ldld"
+else
+  ac_fn_c_check_func "$LINENO" "dlopen" "ac_cv_func_dlopen"
+if test "x$ac_cv_func_dlopen" = xyes; then :
+  lt_cv_dlopen="dlopen"
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -ldl" >&5
+$as_echo_n "checking for dlopen in -ldl... " >&6; }
+if ${ac_cv_lib_dl_dlopen+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-ldl  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char dlopen ();
+int
+main ()
+{
+return dlopen ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_dl_dlopen=yes
+else
+  ac_cv_lib_dl_dlopen=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dl_dlopen" >&5
+$as_echo "$ac_cv_lib_dl_dlopen" >&6; }
+if test "x$ac_cv_lib_dl_dlopen" = xyes; then :
+  lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -lsvld" >&5
+$as_echo_n "checking for dlopen in -lsvld... " >&6; }
+if ${ac_cv_lib_svld_dlopen+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-lsvld  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char dlopen ();
+int
+main ()
+{
+return dlopen ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_svld_dlopen=yes
+else
+  ac_cv_lib_svld_dlopen=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_svld_dlopen" >&5
+$as_echo "$ac_cv_lib_svld_dlopen" >&6; }
+if test "x$ac_cv_lib_svld_dlopen" = xyes; then :
+  lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-lsvld"
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dld_link in -ldld" >&5
+$as_echo_n "checking for dld_link in -ldld... " >&6; }
+if ${ac_cv_lib_dld_dld_link+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-ldld  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char dld_link ();
+int
+main ()
+{
+return dld_link ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_dld_dld_link=yes
+else
+  ac_cv_lib_dld_dld_link=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dld_dld_link" >&5
+$as_echo "$ac_cv_lib_dld_dld_link" >&6; }
+if test "x$ac_cv_lib_dld_dld_link" = xyes; then :
+  lt_cv_dlopen="dld_link" lt_cv_dlopen_libs="-ldld"
+fi
+
+
+fi
+
+
+fi
+
+
+fi
+
+
+fi
+
+
+fi
+
+    ;;
+  esac
+
+  if test "x$lt_cv_dlopen" != xno; then
+    enable_dlopen=yes
+  else
+    enable_dlopen=no
+  fi
+
+  case $lt_cv_dlopen in
+  dlopen)
+    save_CPPFLAGS="$CPPFLAGS"
+    test "x$ac_cv_header_dlfcn_h" = xyes && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H"
+
+    save_LDFLAGS="$LDFLAGS"
+    wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\"
+
+    save_LIBS="$LIBS"
+    LIBS="$lt_cv_dlopen_libs $LIBS"
+
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether a program can dlopen itself" >&5
+$as_echo_n "checking whether a program can dlopen itself... " >&6; }
+if ${lt_cv_dlopen_self+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  	  if test "$cross_compiling" = yes; then :
+  lt_cv_dlopen_self=cross
+else
+  lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2
+  lt_status=$lt_dlunknown
+  cat > conftest.$ac_ext <<_LT_EOF
+#line $LINENO "configure"
+#include "confdefs.h"
+
+#if HAVE_DLFCN_H
+#include <dlfcn.h>
+#endif
+
+#include <stdio.h>
+
+#ifdef RTLD_GLOBAL
+#  define LT_DLGLOBAL		RTLD_GLOBAL
+#else
+#  ifdef DL_GLOBAL
+#    define LT_DLGLOBAL		DL_GLOBAL
+#  else
+#    define LT_DLGLOBAL		0
+#  endif
+#endif
+
+/* We may have to define LT_DLLAZY_OR_NOW in the command line if we
+   find out it does not work in some platform. */
+#ifndef LT_DLLAZY_OR_NOW
+#  ifdef RTLD_LAZY
+#    define LT_DLLAZY_OR_NOW		RTLD_LAZY
+#  else
+#    ifdef DL_LAZY
+#      define LT_DLLAZY_OR_NOW		DL_LAZY
+#    else
+#      ifdef RTLD_NOW
+#        define LT_DLLAZY_OR_NOW	RTLD_NOW
+#      else
+#        ifdef DL_NOW
+#          define LT_DLLAZY_OR_NOW	DL_NOW
+#        else
+#          define LT_DLLAZY_OR_NOW	0
+#        endif
+#      endif
+#    endif
+#  endif
+#endif
+
+/* When -fvisbility=hidden is used, assume the code has been annotated
+   correspondingly for the symbols needed.  */
+#if defined(__GNUC__) && (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3))
+int fnord () __attribute__((visibility("default")));
+#endif
+
+int fnord () { return 42; }
+int main ()
+{
+  void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW);
+  int status = $lt_dlunknown;
+
+  if (self)
+    {
+      if (dlsym (self,"fnord"))       status = $lt_dlno_uscore;
+      else
+        {
+	  if (dlsym( self,"_fnord"))  status = $lt_dlneed_uscore;
+          else puts (dlerror ());
+	}
+      /* dlclose (self); */
+    }
+  else
+    puts (dlerror ());
+
+  return status;
+}
+_LT_EOF
+  if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_link\""; } >&5
+  (eval $ac_link) 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; } && test -s conftest${ac_exeext} 2>/dev/null; then
+    (./conftest; exit; ) >&5 2>/dev/null
+    lt_status=$?
+    case x$lt_status in
+      x$lt_dlno_uscore) lt_cv_dlopen_self=yes ;;
+      x$lt_dlneed_uscore) lt_cv_dlopen_self=yes ;;
+      x$lt_dlunknown|x*) lt_cv_dlopen_self=no ;;
+    esac
+  else :
+    # compilation failed
+    lt_cv_dlopen_self=no
+  fi
+fi
+rm -fr conftest*
+
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_dlopen_self" >&5
+$as_echo "$lt_cv_dlopen_self" >&6; }
+
+    if test "x$lt_cv_dlopen_self" = xyes; then
+      wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $lt_prog_compiler_static\"
+      { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether a statically linked program can dlopen itself" >&5
+$as_echo_n "checking whether a statically linked program can dlopen itself... " >&6; }
+if ${lt_cv_dlopen_self_static+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  	  if test "$cross_compiling" = yes; then :
+  lt_cv_dlopen_self_static=cross
+else
+  lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2
+  lt_status=$lt_dlunknown
+  cat > conftest.$ac_ext <<_LT_EOF
+#line $LINENO "configure"
+#include "confdefs.h"
+
+#if HAVE_DLFCN_H
+#include <dlfcn.h>
+#endif
+
+#include <stdio.h>
+
+#ifdef RTLD_GLOBAL
+#  define LT_DLGLOBAL		RTLD_GLOBAL
+#else
+#  ifdef DL_GLOBAL
+#    define LT_DLGLOBAL		DL_GLOBAL
+#  else
+#    define LT_DLGLOBAL		0
+#  endif
+#endif
+
+/* We may have to define LT_DLLAZY_OR_NOW in the command line if we
+   find out it does not work in some platform. */
+#ifndef LT_DLLAZY_OR_NOW
+#  ifdef RTLD_LAZY
+#    define LT_DLLAZY_OR_NOW		RTLD_LAZY
+#  else
+#    ifdef DL_LAZY
+#      define LT_DLLAZY_OR_NOW		DL_LAZY
+#    else
+#      ifdef RTLD_NOW
+#        define LT_DLLAZY_OR_NOW	RTLD_NOW
+#      else
+#        ifdef DL_NOW
+#          define LT_DLLAZY_OR_NOW	DL_NOW
+#        else
+#          define LT_DLLAZY_OR_NOW	0
+#        endif
+#      endif
+#    endif
+#  endif
+#endif
+
+/* When -fvisbility=hidden is used, assume the code has been annotated
+   correspondingly for the symbols needed.  */
+#if defined(__GNUC__) && (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3))
+int fnord () __attribute__((visibility("default")));
+#endif
+
+int fnord () { return 42; }
+int main ()
+{
+  void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW);
+  int status = $lt_dlunknown;
+
+  if (self)
+    {
+      if (dlsym (self,"fnord"))       status = $lt_dlno_uscore;
+      else
+        {
+	  if (dlsym( self,"_fnord"))  status = $lt_dlneed_uscore;
+          else puts (dlerror ());
+	}
+      /* dlclose (self); */
+    }
+  else
+    puts (dlerror ());
+
+  return status;
+}
+_LT_EOF
+  if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_link\""; } >&5
+  (eval $ac_link) 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; } && test -s conftest${ac_exeext} 2>/dev/null; then
+    (./conftest; exit; ) >&5 2>/dev/null
+    lt_status=$?
+    case x$lt_status in
+      x$lt_dlno_uscore) lt_cv_dlopen_self_static=yes ;;
+      x$lt_dlneed_uscore) lt_cv_dlopen_self_static=yes ;;
+      x$lt_dlunknown|x*) lt_cv_dlopen_self_static=no ;;
+    esac
+  else :
+    # compilation failed
+    lt_cv_dlopen_self_static=no
+  fi
+fi
+rm -fr conftest*
+
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_dlopen_self_static" >&5
+$as_echo "$lt_cv_dlopen_self_static" >&6; }
+    fi
+
+    CPPFLAGS="$save_CPPFLAGS"
+    LDFLAGS="$save_LDFLAGS"
+    LIBS="$save_LIBS"
+    ;;
+  esac
+
+  case $lt_cv_dlopen_self in
+  yes|no) enable_dlopen_self=$lt_cv_dlopen_self ;;
+  *) enable_dlopen_self=unknown ;;
+  esac
+
+  case $lt_cv_dlopen_self_static in
+  yes|no) enable_dlopen_self_static=$lt_cv_dlopen_self_static ;;
+  *) enable_dlopen_self_static=unknown ;;
+  esac
+fi
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+striplib=
+old_striplib=
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether stripping libraries is possible" >&5
+$as_echo_n "checking whether stripping libraries is possible... " >&6; }
+if test -n "$STRIP" && $STRIP -V 2>&1 | $GREP "GNU strip" >/dev/null; then
+  test -z "$old_striplib" && old_striplib="$STRIP --strip-debug"
+  test -z "$striplib" && striplib="$STRIP --strip-unneeded"
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+else
+# FIXME - insert some real tests, host_os isn't really good enough
+  case $host_os in
+  darwin*)
+    if test -n "$STRIP" ; then
+      striplib="$STRIP -x"
+      old_striplib="$STRIP -S"
+      { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+    else
+      { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+    fi
+    ;;
+  *)
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+    ;;
+  esac
+fi
+
+
+
+
+
+
+
+
+
+
+
+
+  # Report which library types will actually be built
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if libtool supports shared libraries" >&5
+$as_echo_n "checking if libtool supports shared libraries... " >&6; }
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $can_build_shared" >&5
+$as_echo "$can_build_shared" >&6; }
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to build shared libraries" >&5
+$as_echo_n "checking whether to build shared libraries... " >&6; }
+  test "$can_build_shared" = "no" && enable_shared=no
+
+  # On AIX, shared libraries and static libraries use the same namespace, and
+  # are all built from PIC.
+  case $host_os in
+  aix3*)
+    test "$enable_shared" = yes && enable_static=no
+    if test -n "$RANLIB"; then
+      archive_cmds="$archive_cmds~\$RANLIB \$lib"
+      postinstall_cmds='$RANLIB $lib'
+    fi
+    ;;
+
+  aix[4-9]*)
+    if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then
+      test "$enable_shared" = yes && enable_static=no
+    fi
+    ;;
+  esac
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $enable_shared" >&5
+$as_echo "$enable_shared" >&6; }
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to build static libraries" >&5
+$as_echo_n "checking whether to build static libraries... " >&6; }
+  # Make sure either enable_shared or enable_static is yes.
+  test "$enable_shared" = yes || enable_static=yes
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $enable_static" >&5
+$as_echo "$enable_static" >&6; }
+
+
+
+
+fi
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+CC="$lt_save_CC"
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+        ac_config_commands="$ac_config_commands libtool"
+
+
+
+
+# Only expand once:
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+# macro that is used to parse a --with-apxs parameter
+
+
+
+
+
+# ===========================================================================
+#    http://www.gnu.org/software/autoconf-archive/ax_jni_include_dir.html
+# ===========================================================================
+#
+# SYNOPSIS
+#
+#   AX_JNI_INCLUDE_DIR
+#
+# DESCRIPTION
+#
+#   AX_JNI_INCLUDE_DIR finds include directories needed for compiling
+#   programs using the JNI interface.
+#
+#   JNI include directories are usually in the java distribution This is
+#   deduced from the value of JAVAC. When this macro completes, a list of
+#   directories is left in the variable JNI_INCLUDE_DIRS.
+#
+#   Example usage follows:
+#
+#     AX_JNI_INCLUDE_DIR
+#
+#     for JNI_INCLUDE_DIR in $JNI_INCLUDE_DIRS
+#     do
+#             CPPFLAGS="$CPPFLAGS -I$JNI_INCLUDE_DIR"
+#     done
+#
+#   If you want to force a specific compiler:
+#
+#   - at the configure.in level, set JAVAC=yourcompiler before calling
+#   AX_JNI_INCLUDE_DIR
+#
+#   - at the configure level, setenv JAVAC
+#
+#   Note: This macro can work with the autoconf M4 macros for Java programs.
+#   This particular macro is not part of the original set of macros.
+#
+# LICENSE
+#
+#   Copyright (c) 2008 Don Anderson <dda at sleepycat.com>
+#
+#   Copying and distribution of this file, with or without modification, are
+#   permitted in any medium without royalty provided the copyright notice
+#   and this notice are preserved. This file is offered as-is, without any
+#   warranty.
+
+#serial 7
+
+# This is what autoupdate's m4 run will expand.  It fires
+# the warning (with _au_warn_XXX), outputs it into the
+# updated configure.ac (with AC_DIAGNOSE), and then outputs
+# the replacement expansion.
+
+
+# This is an auxiliary macro that is also run when
+# autoupdate runs m4.  It simply calls m4_warning, but
+# we need a wrapper so that each warning is emitted only
+# once.  We break the quoting in m4_warning's argument in
+# order to expand this macro's arguments, not AU_DEFUN's.
+
+
+# Finally, this is the expansion that is picked up by
+# autoconf.  It tells the user to run autoupdate, and
+# then outputs the replacement expansion.  We do not care
+# about autoupdate's warning because that contains
+# information on what to do *after* running autoupdate.
+
+
+
+# _ACJNI_FOLLOW_SYMLINKS <path>
+# Follows symbolic links on <path>,
+# finally setting variable _ACJNI_FOLLOWED
+# ----------------------------------------
+# _ACJNI
+
+# ===========================================================================
+#        http://www.gnu.org/software/autoconf-archive/ax_pkg_swig.html
+# ===========================================================================
+#
+# SYNOPSIS
+#
+#   AX_PKG_SWIG([major.minor.micro], [action-if-found], [action-if-not-found])
+#
+# DESCRIPTION
+#
+#   This macro searches for a SWIG installation on your system. If found,
+#   then SWIG is AC_SUBST'd; if not found, then $SWIG is empty.  If SWIG is
+#   found, then SWIG_LIB is set to the SWIG library path, and AC_SUBST'd.
+#
+#   You can use the optional first argument to check if the version of the
+#   available SWIG is greater than or equal to the value of the argument. It
+#   should have the format: N[.N[.N]] (N is a number between 0 and 999. Only
+#   the first N is mandatory.) If the version argument is given (e.g.
+#   1.3.17), AX_PKG_SWIG checks that the swig package is this version number
+#   or higher.
+#
+#   As usual, action-if-found is executed if SWIG is found, otherwise
+#   action-if-not-found is executed.
+#
+#   In configure.in, use as:
+#
+#     AX_PKG_SWIG(1.3.17, [], [ AC_MSG_ERROR([SWIG is required to build..]) ])
+#     AX_SWIG_ENABLE_CXX
+#     AX_SWIG_MULTI_MODULE_SUPPORT
+#     AX_SWIG_PYTHON
+#
+# LICENSE
+#
+#   Copyright (c) 2008 Sebastian Huber <sebastian-huber at web.de>
+#   Copyright (c) 2008 Alan W. Irwin <irwin at beluga.phys.uvic.ca>
+#   Copyright (c) 2008 Rafael Laboissiere <rafael at laboissiere.net>
+#   Copyright (c) 2008 Andrew Collier <colliera at ukzn.ac.za>
+#   Copyright (c) 2011 Murray Cumming <murrayc at openismus.com>
+#
+#   This program is free software; you can redistribute it and/or modify it
+#   under the terms of the GNU General Public License as published by the
+#   Free Software Foundation; either version 2 of the License, or (at your
+#   option) any later version.
+#
+#   This program is distributed in the hope that it will be useful, but
+#   WITHOUT ANY WARRANTY; without even the implied warranty of
+#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
+#   Public License for more details.
+#
+#   You should have received a copy of the GNU General Public License along
+#   with this program. If not, see <http://www.gnu.org/licenses/>.
+#
+#   As a special exception, the respective Autoconf Macro's copyright owner
+#   gives unlimited permission to copy, distribute and modify the configure
+#   scripts that are the output of Autoconf when processing the Macro. You
+#   need not follow the terms of the GNU General Public License when using
+#   or distributing such scripts, even though portions of the text of the
+#   Macro appear in them. The GNU General Public License (GPL) does govern
+#   all other use of the material that constitutes the Autoconf Macro.
+#
+#   This special exception to the GPL applies to versions of the Autoconf
+#   Macro released by the Autoconf Archive. When you make and distribute a
+#   modified version of the Autoconf Macro, you may extend this special
+#   exception to the GPL to apply to your modified version as well.
+
+#serial 8
+
+
+
+
+
+
+
+
+
+
+
+
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+if test -n "$ac_tool_prefix"; then
+  # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args.
+set dummy ${ac_tool_prefix}gcc; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_CC+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$CC"; then
+  ac_cv_prog_CC="$CC" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_CC="${ac_tool_prefix}gcc"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+fi
+fi
+CC=$ac_cv_prog_CC
+if test -n "$CC"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
+$as_echo "$CC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+fi
+if test -z "$ac_cv_prog_CC"; then
+  ac_ct_CC=$CC
+  # Extract the first word of "gcc", so it can be a program name with args.
+set dummy gcc; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_ac_ct_CC+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$ac_ct_CC"; then
+  ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_ac_ct_CC="gcc"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+fi
+fi
+ac_ct_CC=$ac_cv_prog_ac_ct_CC
+if test -n "$ac_ct_CC"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5
+$as_echo "$ac_ct_CC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+  if test "x$ac_ct_CC" = x; then
+    CC=""
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
+$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
+ac_tool_warned=yes ;;
+esac
+    CC=$ac_ct_CC
+  fi
+else
+  CC="$ac_cv_prog_CC"
+fi
+
+if test -z "$CC"; then
+          if test -n "$ac_tool_prefix"; then
+    # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args.
+set dummy ${ac_tool_prefix}cc; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_CC+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$CC"; then
+  ac_cv_prog_CC="$CC" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_CC="${ac_tool_prefix}cc"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+fi
+fi
+CC=$ac_cv_prog_CC
+if test -n "$CC"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
+$as_echo "$CC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+  fi
+fi
+if test -z "$CC"; then
+  # Extract the first word of "cc", so it can be a program name with args.
+set dummy cc; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_CC+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$CC"; then
+  ac_cv_prog_CC="$CC" # Let the user override the test.
+else
+  ac_prog_rejected=no
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then
+       ac_prog_rejected=yes
+       continue
+     fi
+    ac_cv_prog_CC="cc"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+if test $ac_prog_rejected = yes; then
+  # We found a bogon in the path, so make sure we never use it.
+  set dummy $ac_cv_prog_CC
+  shift
+  if test $# != 0; then
+    # We chose a different compiler from the bogus one.
+    # However, it has the same basename, so the bogon will be chosen
+    # first if we set CC to just the basename; use the full file name.
+    shift
+    ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@"
+  fi
+fi
+fi
+fi
+CC=$ac_cv_prog_CC
+if test -n "$CC"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
+$as_echo "$CC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+fi
+if test -z "$CC"; then
+  if test -n "$ac_tool_prefix"; then
+  for ac_prog in cl.exe
+  do
+    # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args.
+set dummy $ac_tool_prefix$ac_prog; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_CC+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$CC"; then
+  ac_cv_prog_CC="$CC" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_CC="$ac_tool_prefix$ac_prog"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+fi
+fi
+CC=$ac_cv_prog_CC
+if test -n "$CC"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
+$as_echo "$CC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+    test -n "$CC" && break
+  done
+fi
+if test -z "$CC"; then
+  ac_ct_CC=$CC
+  for ac_prog in cl.exe
+do
+  # Extract the first word of "$ac_prog", so it can be a program name with args.
+set dummy $ac_prog; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_ac_ct_CC+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$ac_ct_CC"; then
+  ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_ac_ct_CC="$ac_prog"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+fi
+fi
+ac_ct_CC=$ac_cv_prog_ac_ct_CC
+if test -n "$ac_ct_CC"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5
+$as_echo "$ac_ct_CC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+  test -n "$ac_ct_CC" && break
+done
+
+  if test "x$ac_ct_CC" = x; then
+    CC=""
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
+$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
+ac_tool_warned=yes ;;
+esac
+    CC=$ac_ct_CC
+  fi
+fi
+
+fi
+
+
+test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error $? "no acceptable C compiler found in \$PATH
+See \`config.log' for more details" "$LINENO" 5; }
+
+# Provide some information about the compiler.
+$as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5
+set X $ac_compile
+ac_compiler=$2
+for ac_option in --version -v -V -qversion; do
+  { { ac_try="$ac_compiler $ac_option >&5"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_compiler $ac_option >&5") 2>conftest.err
+  ac_status=$?
+  if test -s conftest.err; then
+    sed '10a\
+... rest of stderr output deleted ...
+         10q' conftest.err >conftest.er1
+    cat conftest.er1 >&5
+  fi
+  rm -f conftest.er1 conftest.err
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }
+done
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C compiler" >&5
+$as_echo_n "checking whether we are using the GNU C compiler... " >&6; }
+if ${ac_cv_c_compiler_gnu+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+#ifndef __GNUC__
+       choke me
+#endif
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_compiler_gnu=yes
+else
+  ac_compiler_gnu=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+ac_cv_c_compiler_gnu=$ac_compiler_gnu
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5
+$as_echo "$ac_cv_c_compiler_gnu" >&6; }
+if test $ac_compiler_gnu = yes; then
+  GCC=yes
+else
+  GCC=
+fi
+ac_test_CFLAGS=${CFLAGS+set}
+ac_save_CFLAGS=$CFLAGS
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5
+$as_echo_n "checking whether $CC accepts -g... " >&6; }
+if ${ac_cv_prog_cc_g+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_save_c_werror_flag=$ac_c_werror_flag
+   ac_c_werror_flag=yes
+   ac_cv_prog_cc_g=no
+   CFLAGS="-g"
+   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_prog_cc_g=yes
+else
+  CFLAGS=""
+      cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+
+else
+  ac_c_werror_flag=$ac_save_c_werror_flag
+	 CFLAGS="-g"
+	 cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_prog_cc_g=yes
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+   ac_c_werror_flag=$ac_save_c_werror_flag
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5
+$as_echo "$ac_cv_prog_cc_g" >&6; }
+if test "$ac_test_CFLAGS" = set; then
+  CFLAGS=$ac_save_CFLAGS
+elif test $ac_cv_prog_cc_g = yes; then
+  if test "$GCC" = yes; then
+    CFLAGS="-g -O2"
+  else
+    CFLAGS="-g"
+  fi
+else
+  if test "$GCC" = yes; then
+    CFLAGS="-O2"
+  else
+    CFLAGS=
+  fi
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C89" >&5
+$as_echo_n "checking for $CC option to accept ISO C89... " >&6; }
+if ${ac_cv_prog_cc_c89+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_cv_prog_cc_c89=no
+ac_save_CC=$CC
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <stdarg.h>
+#include <stdio.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+/* Most of the following tests are stolen from RCS 5.7's src/conf.sh.  */
+struct buf { int x; };
+FILE * (*rcsopen) (struct buf *, struct stat *, int);
+static char *e (p, i)
+     char **p;
+     int i;
+{
+  return p[i];
+}
+static char *f (char * (*g) (char **, int), char **p, ...)
+{
+  char *s;
+  va_list v;
+  va_start (v,p);
+  s = g (p, va_arg (v,int));
+  va_end (v);
+  return s;
+}
+
+/* OSF 4.0 Compaq cc is some sort of almost-ANSI by default.  It has
+   function prototypes and stuff, but not '\xHH' hex character constants.
+   These don't provoke an error unfortunately, instead are silently treated
+   as 'x'.  The following induces an error, until -std is added to get
+   proper ANSI mode.  Curiously '\x00'!='x' always comes out true, for an
+   array size at least.  It's necessary to write '\x00'==0 to get something
+   that's true only with -std.  */
+int osf4_cc_array ['\x00' == 0 ? 1 : -1];
+
+/* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters
+   inside strings and character constants.  */
+#define FOO(x) 'x'
+int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1];
+
+int test (int i, double x);
+struct s1 {int (*f) (int a);};
+struct s2 {int (*f) (double a);};
+int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int);
+int argc;
+char **argv;
+int
+main ()
+{
+return f (e, argv, 0) != argv[0]  ||  f (e, argv, 1) != argv[1];
+  ;
+  return 0;
+}
+_ACEOF
+for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \
+	-Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__"
+do
+  CC="$ac_save_CC $ac_arg"
+  if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_prog_cc_c89=$ac_arg
+fi
+rm -f core conftest.err conftest.$ac_objext
+  test "x$ac_cv_prog_cc_c89" != "xno" && break
+done
+rm -f conftest.$ac_ext
+CC=$ac_save_CC
+
+fi
+# AC_CACHE_VAL
+case "x$ac_cv_prog_cc_c89" in
+  x)
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: none needed" >&5
+$as_echo "none needed" >&6; } ;;
+  xno)
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5
+$as_echo "unsupported" >&6; } ;;
+  *)
+    CC="$CC $ac_cv_prog_cc_c89"
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5
+$as_echo "$ac_cv_prog_cc_c89" >&6; } ;;
+esac
+if test "x$ac_cv_prog_cc_c89" != xno; then :
+
+fi
+
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+ac_ext=cpp
+ac_cpp='$CXXCPP $CPPFLAGS'
+ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
+if test -z "$CXX"; then
+  if test -n "$CCC"; then
+    CXX=$CCC
+  else
+    if test -n "$ac_tool_prefix"; then
+  for ac_prog in g++ c++ gpp aCC CC cxx cc++ cl.exe FCC KCC RCC xlC_r xlC
+  do
+    # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args.
+set dummy $ac_tool_prefix$ac_prog; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_CXX+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$CXX"; then
+  ac_cv_prog_CXX="$CXX" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_CXX="$ac_tool_prefix$ac_prog"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+fi
+fi
+CXX=$ac_cv_prog_CXX
+if test -n "$CXX"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CXX" >&5
+$as_echo "$CXX" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+    test -n "$CXX" && break
+  done
+fi
+if test -z "$CXX"; then
+  ac_ct_CXX=$CXX
+  for ac_prog in g++ c++ gpp aCC CC cxx cc++ cl.exe FCC KCC RCC xlC_r xlC
+do
+  # Extract the first word of "$ac_prog", so it can be a program name with args.
+set dummy $ac_prog; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_ac_ct_CXX+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$ac_ct_CXX"; then
+  ac_cv_prog_ac_ct_CXX="$ac_ct_CXX" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_ac_ct_CXX="$ac_prog"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+fi
+fi
+ac_ct_CXX=$ac_cv_prog_ac_ct_CXX
+if test -n "$ac_ct_CXX"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CXX" >&5
+$as_echo "$ac_ct_CXX" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+  test -n "$ac_ct_CXX" && break
+done
+
+  if test "x$ac_ct_CXX" = x; then
+    CXX="g++"
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
+$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
+ac_tool_warned=yes ;;
+esac
+    CXX=$ac_ct_CXX
+  fi
+fi
+
+  fi
+fi
+# Provide some information about the compiler.
+$as_echo "$as_me:${as_lineno-$LINENO}: checking for C++ compiler version" >&5
+set X $ac_compile
+ac_compiler=$2
+for ac_option in --version -v -V -qversion; do
+  { { ac_try="$ac_compiler $ac_option >&5"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_compiler $ac_option >&5") 2>conftest.err
+  ac_status=$?
+  if test -s conftest.err; then
+    sed '10a\
+... rest of stderr output deleted ...
+         10q' conftest.err >conftest.er1
+    cat conftest.er1 >&5
+  fi
+  rm -f conftest.er1 conftest.err
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }
+done
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C++ compiler" >&5
+$as_echo_n "checking whether we are using the GNU C++ compiler... " >&6; }
+if ${ac_cv_cxx_compiler_gnu+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+#ifndef __GNUC__
+       choke me
+#endif
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_cxx_try_compile "$LINENO"; then :
+  ac_compiler_gnu=yes
+else
+  ac_compiler_gnu=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+ac_cv_cxx_compiler_gnu=$ac_compiler_gnu
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_cxx_compiler_gnu" >&5
+$as_echo "$ac_cv_cxx_compiler_gnu" >&6; }
+if test $ac_compiler_gnu = yes; then
+  GXX=yes
+else
+  GXX=
+fi
+ac_test_CXXFLAGS=${CXXFLAGS+set}
+ac_save_CXXFLAGS=$CXXFLAGS
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CXX accepts -g" >&5
+$as_echo_n "checking whether $CXX accepts -g... " >&6; }
+if ${ac_cv_prog_cxx_g+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_save_cxx_werror_flag=$ac_cxx_werror_flag
+   ac_cxx_werror_flag=yes
+   ac_cv_prog_cxx_g=no
+   CXXFLAGS="-g"
+   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_cxx_try_compile "$LINENO"; then :
+  ac_cv_prog_cxx_g=yes
+else
+  CXXFLAGS=""
+      cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_cxx_try_compile "$LINENO"; then :
+
+else
+  ac_cxx_werror_flag=$ac_save_cxx_werror_flag
+	 CXXFLAGS="-g"
+	 cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_cxx_try_compile "$LINENO"; then :
+  ac_cv_prog_cxx_g=yes
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+   ac_cxx_werror_flag=$ac_save_cxx_werror_flag
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cxx_g" >&5
+$as_echo "$ac_cv_prog_cxx_g" >&6; }
+if test "$ac_test_CXXFLAGS" = set; then
+  CXXFLAGS=$ac_save_CXXFLAGS
+elif test $ac_cv_prog_cxx_g = yes; then
+  if test "$GXX" = yes; then
+    CXXFLAGS="-g -O2"
+  else
+    CXXFLAGS="-g"
+  fi
+else
+  if test "$GXX" = yes; then
+    CXXFLAGS="-O2"
+  else
+    CXXFLAGS=
+  fi
+fi
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+
+
+func_stripname_cnf ()
+{
+  case ${2} in
+  .*) func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%\\\\${2}\$%%"`;;
+  *)  func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%${2}\$%%"`;;
+  esac
+} # func_stripname_cnf
+
+      if test -n "$CXX" && ( test "X$CXX" != "Xno" &&
+    ( (test "X$CXX" = "Xg++" && `g++ -v >/dev/null 2>&1` ) ||
+    (test "X$CXX" != "Xg++"))) ; then
+  ac_ext=cpp
+ac_cpp='$CXXCPP $CPPFLAGS'
+ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to run the C++ preprocessor" >&5
+$as_echo_n "checking how to run the C++ preprocessor... " >&6; }
+if test -z "$CXXCPP"; then
+  if ${ac_cv_prog_CXXCPP+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+      # Double quotes because CXXCPP needs to be expanded
+    for CXXCPP in "$CXX -E" "/lib/cpp"
+    do
+      ac_preproc_ok=false
+for ac_cxx_preproc_warn_flag in '' yes
+do
+  # Use a header file that comes with gcc, so configuring glibc
+  # with a fresh cross-compiler works.
+  # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+  # <limits.h> exists even on freestanding compilers.
+  # On the NeXT, cc -E runs the code through the compiler's parser,
+  # not just through cpp. "Syntax error" is here to catch this case.
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+		     Syntax error
+_ACEOF
+if ac_fn_cxx_try_cpp "$LINENO"; then :
+
+else
+  # Broken: fails on valid input.
+continue
+fi
+rm -f conftest.err conftest.i conftest.$ac_ext
+
+  # OK, works on sane cases.  Now check whether nonexistent headers
+  # can be detected and how.
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <ac_nonexistent.h>
+_ACEOF
+if ac_fn_cxx_try_cpp "$LINENO"; then :
+  # Broken: success on invalid input.
+continue
+else
+  # Passes both tests.
+ac_preproc_ok=:
+break
+fi
+rm -f conftest.err conftest.i conftest.$ac_ext
+
+done
+# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
+rm -f conftest.i conftest.err conftest.$ac_ext
+if $ac_preproc_ok; then :
+  break
+fi
+
+    done
+    ac_cv_prog_CXXCPP=$CXXCPP
+
+fi
+  CXXCPP=$ac_cv_prog_CXXCPP
+else
+  ac_cv_prog_CXXCPP=$CXXCPP
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $CXXCPP" >&5
+$as_echo "$CXXCPP" >&6; }
+ac_preproc_ok=false
+for ac_cxx_preproc_warn_flag in '' yes
+do
+  # Use a header file that comes with gcc, so configuring glibc
+  # with a fresh cross-compiler works.
+  # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+  # <limits.h> exists even on freestanding compilers.
+  # On the NeXT, cc -E runs the code through the compiler's parser,
+  # not just through cpp. "Syntax error" is here to catch this case.
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+		     Syntax error
+_ACEOF
+if ac_fn_cxx_try_cpp "$LINENO"; then :
+
+else
+  # Broken: fails on valid input.
+continue
+fi
+rm -f conftest.err conftest.i conftest.$ac_ext
+
+  # OK, works on sane cases.  Now check whether nonexistent headers
+  # can be detected and how.
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <ac_nonexistent.h>
+_ACEOF
+if ac_fn_cxx_try_cpp "$LINENO"; then :
+  # Broken: success on invalid input.
+continue
+else
+  # Passes both tests.
+ac_preproc_ok=:
+break
+fi
+rm -f conftest.err conftest.i conftest.$ac_ext
+
+done
+# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
+rm -f conftest.i conftest.err conftest.$ac_ext
+if $ac_preproc_ok; then :
+
+else
+  { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error $? "C++ preprocessor \"$CXXCPP\" fails sanity check
+See \`config.log' for more details" "$LINENO" 5; }
+fi
+
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+else
+  _lt_caught_CXX_error=yes
+fi
+
+ac_ext=cpp
+ac_cpp='$CXXCPP $CPPFLAGS'
+ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
+
+archive_cmds_need_lc_CXX=no
+allow_undefined_flag_CXX=
+always_export_symbols_CXX=no
+archive_expsym_cmds_CXX=
+compiler_needs_object_CXX=no
+export_dynamic_flag_spec_CXX=
+hardcode_direct_CXX=no
+hardcode_direct_absolute_CXX=no
+hardcode_libdir_flag_spec_CXX=
+hardcode_libdir_separator_CXX=
+hardcode_minus_L_CXX=no
+hardcode_shlibpath_var_CXX=unsupported
+hardcode_automatic_CXX=no
+inherit_rpath_CXX=no
+module_cmds_CXX=
+module_expsym_cmds_CXX=
+link_all_deplibs_CXX=unknown
+old_archive_cmds_CXX=$old_archive_cmds
+reload_flag_CXX=$reload_flag
+reload_cmds_CXX=$reload_cmds
+no_undefined_flag_CXX=
+whole_archive_flag_spec_CXX=
+enable_shared_with_static_runtimes_CXX=no
+
+# Source file extension for C++ test sources.
+ac_ext=cpp
+
+# Object file extension for compiled C++ test sources.
+objext=o
+objext_CXX=$objext
+
+# No sense in running all these tests if we already determined that
+# the CXX compiler isn't working.  Some variables (like enable_shared)
+# are currently assumed to apply to all compilers on this platform,
+# and will be corrupted by setting them based on a non-working compiler.
+if test "$_lt_caught_CXX_error" != yes; then
+  # Code to be used in simple compile tests
+  lt_simple_compile_test_code="int some_variable = 0;"
+
+  # Code to be used in simple link tests
+  lt_simple_link_test_code='int main(int, char *[]) { return(0); }'
+
+  # ltmain only uses $CC for tagged configurations so make sure $CC is set.
+
+
+
+
+
+
+# If no C compiler was specified, use CC.
+LTCC=${LTCC-"$CC"}
+
+# If no C compiler flags were specified, use CFLAGS.
+LTCFLAGS=${LTCFLAGS-"$CFLAGS"}
+
+# Allow CC to be a program name with arguments.
+compiler=$CC
+
+
+  # save warnings/boilerplate of simple test code
+  ac_outfile=conftest.$ac_objext
+echo "$lt_simple_compile_test_code" >conftest.$ac_ext
+eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
+_lt_compiler_boilerplate=`cat conftest.err`
+$RM conftest*
+
+  ac_outfile=conftest.$ac_objext
+echo "$lt_simple_link_test_code" >conftest.$ac_ext
+eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
+_lt_linker_boilerplate=`cat conftest.err`
+$RM -r conftest*
+
+
+  # Allow CC to be a program name with arguments.
+  lt_save_CC=$CC
+  lt_save_CFLAGS=$CFLAGS
+  lt_save_LD=$LD
+  lt_save_GCC=$GCC
+  GCC=$GXX
+  lt_save_with_gnu_ld=$with_gnu_ld
+  lt_save_path_LD=$lt_cv_path_LD
+  if test -n "${lt_cv_prog_gnu_ldcxx+set}"; then
+    lt_cv_prog_gnu_ld=$lt_cv_prog_gnu_ldcxx
+  else
+    $as_unset lt_cv_prog_gnu_ld
+  fi
+  if test -n "${lt_cv_path_LDCXX+set}"; then
+    lt_cv_path_LD=$lt_cv_path_LDCXX
+  else
+    $as_unset lt_cv_path_LD
+  fi
+  test -z "${LDCXX+set}" || LD=$LDCXX
+  CC=${CXX-"c++"}
+  CFLAGS=$CXXFLAGS
+  compiler=$CC
+  compiler_CXX=$CC
+  for cc_temp in $compiler""; do
+  case $cc_temp in
+    compile | *[\\/]compile | ccache | *[\\/]ccache ) ;;
+    distcc | *[\\/]distcc | purify | *[\\/]purify ) ;;
+    \-*) ;;
+    *) break;;
+  esac
+done
+cc_basename=`$ECHO "$cc_temp" | $SED "s%.*/%%; s%^$host_alias-%%"`
+
+
+  if test -n "$compiler"; then
+    # We don't want -fno-exception when compiling C++ code, so set the
+    # no_builtin_flag separately
+    if test "$GXX" = yes; then
+      lt_prog_compiler_no_builtin_flag_CXX=' -fno-builtin'
+    else
+      lt_prog_compiler_no_builtin_flag_CXX=
+    fi
+
+    if test "$GXX" = yes; then
+      # Set up default GNU C++ configuration
+
+
+
+# Check whether --with-gnu-ld was given.
+if test "${with_gnu_ld+set}" = set; then :
+  withval=$with_gnu_ld; test "$withval" = no || with_gnu_ld=yes
+else
+  with_gnu_ld=no
+fi
+
+ac_prog=ld
+if test "$GCC" = yes; then
+  # Check if gcc -print-prog-name=ld gives a path.
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ld used by $CC" >&5
+$as_echo_n "checking for ld used by $CC... " >&6; }
+  case $host in
+  *-*-mingw*)
+    # gcc leaves a trailing carriage return which upsets mingw
+    ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;;
+  *)
+    ac_prog=`($CC -print-prog-name=ld) 2>&5` ;;
+  esac
+  case $ac_prog in
+    # Accept absolute paths.
+    [\\/]* | ?:[\\/]*)
+      re_direlt='/[^/][^/]*/\.\./'
+      # Canonicalize the pathname of ld
+      ac_prog=`$ECHO "$ac_prog"| $SED 's%\\\\%/%g'`
+      while $ECHO "$ac_prog" | $GREP "$re_direlt" > /dev/null 2>&1; do
+	ac_prog=`$ECHO $ac_prog| $SED "s%$re_direlt%/%"`
+      done
+      test -z "$LD" && LD="$ac_prog"
+      ;;
+  "")
+    # If it fails, then pretend we aren't using GCC.
+    ac_prog=ld
+    ;;
+  *)
+    # If it is relative, then search for the first ld in PATH.
+    with_gnu_ld=unknown
+    ;;
+  esac
+elif test "$with_gnu_ld" = yes; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for GNU ld" >&5
+$as_echo_n "checking for GNU ld... " >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for non-GNU ld" >&5
+$as_echo_n "checking for non-GNU ld... " >&6; }
+fi
+if ${lt_cv_path_LD+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -z "$LD"; then
+  lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
+  for ac_dir in $PATH; do
+    IFS="$lt_save_ifs"
+    test -z "$ac_dir" && ac_dir=.
+    if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then
+      lt_cv_path_LD="$ac_dir/$ac_prog"
+      # Check to see if the program is GNU ld.  I'd rather use --version,
+      # but apparently some variants of GNU ld only accept -v.
+      # Break only if it was the GNU/non-GNU ld that we prefer.
+      case `"$lt_cv_path_LD" -v 2>&1 </dev/null` in
+      *GNU* | *'with BFD'*)
+	test "$with_gnu_ld" != no && break
+	;;
+      *)
+	test "$with_gnu_ld" != yes && break
+	;;
+      esac
+    fi
+  done
+  IFS="$lt_save_ifs"
+else
+  lt_cv_path_LD="$LD" # Let the user override the test with a path.
+fi
+fi
+
+LD="$lt_cv_path_LD"
+if test -n "$LD"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $LD" >&5
+$as_echo "$LD" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+test -z "$LD" && as_fn_error $? "no acceptable ld found in \$PATH" "$LINENO" 5
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if the linker ($LD) is GNU ld" >&5
+$as_echo_n "checking if the linker ($LD) is GNU ld... " >&6; }
+if ${lt_cv_prog_gnu_ld+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  # I'd rather use --version here, but apparently some GNU lds only accept -v.
+case `$LD -v 2>&1 </dev/null` in
+*GNU* | *'with BFD'*)
+  lt_cv_prog_gnu_ld=yes
+  ;;
+*)
+  lt_cv_prog_gnu_ld=no
+  ;;
+esac
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_gnu_ld" >&5
+$as_echo "$lt_cv_prog_gnu_ld" >&6; }
+with_gnu_ld=$lt_cv_prog_gnu_ld
+
+
+
+
+
+
+
+      # Check if GNU C++ uses GNU ld as the underlying linker, since the
+      # archiving commands below assume that GNU ld is being used.
+      if test "$with_gnu_ld" = yes; then
+        archive_cmds_CXX='$CC $pic_flag -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib'
+        archive_expsym_cmds_CXX='$CC $pic_flag -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+
+        hardcode_libdir_flag_spec_CXX='${wl}-rpath ${wl}$libdir'
+        export_dynamic_flag_spec_CXX='${wl}--export-dynamic'
+
+        # If archive_cmds runs LD, not CC, wlarc should be empty
+        # XXX I think wlarc can be eliminated in ltcf-cxx, but I need to
+        #     investigate it a little bit more. (MM)
+        wlarc='${wl}'
+
+        # ancient GNU ld didn't support --whole-archive et. al.
+        if eval "`$CC -print-prog-name=ld` --help 2>&1" |
+	  $GREP 'no-whole-archive' > /dev/null; then
+          whole_archive_flag_spec_CXX="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
+        else
+          whole_archive_flag_spec_CXX=
+        fi
+      else
+        with_gnu_ld=no
+        wlarc=
+
+        # A generic and very simple default shared library creation
+        # command for GNU C++ for the case where it uses the native
+        # linker, instead of GNU ld.  If possible, this setting should
+        # overridden to take advantage of the native linker features on
+        # the platform it is being used on.
+        archive_cmds_CXX='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib'
+      fi
+
+      # Commands to make compiler produce verbose output that lists
+      # what "hidden" libraries, object files and flags are used when
+      # linking a shared library.
+      output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"'
+
+    else
+      GXX=no
+      with_gnu_ld=no
+      wlarc=
+    fi
+
+    # PORTME: fill in a description of your system's C++ link characteristics
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the $compiler linker ($LD) supports shared libraries" >&5
+$as_echo_n "checking whether the $compiler linker ($LD) supports shared libraries... " >&6; }
+    ld_shlibs_CXX=yes
+    case $host_os in
+      aix3*)
+        # FIXME: insert proper C++ library support
+        ld_shlibs_CXX=no
+        ;;
+      aix[4-9]*)
+        if test "$host_cpu" = ia64; then
+          # On IA64, the linker does run time linking by default, so we don't
+          # have to do anything special.
+          aix_use_runtimelinking=no
+          exp_sym_flag='-Bexport'
+          no_entry_flag=""
+        else
+          aix_use_runtimelinking=no
+
+          # Test if we are trying to use run time linking or normal
+          # AIX style linking. If -brtl is somewhere in LDFLAGS, we
+          # need to do runtime linking.
+          case $host_os in aix4.[23]|aix4.[23].*|aix[5-9]*)
+	    for ld_flag in $LDFLAGS; do
+	      case $ld_flag in
+	      *-brtl*)
+	        aix_use_runtimelinking=yes
+	        break
+	        ;;
+	      esac
+	    done
+	    ;;
+          esac
+
+          exp_sym_flag='-bexport'
+          no_entry_flag='-bnoentry'
+        fi
+
+        # When large executables or shared objects are built, AIX ld can
+        # have problems creating the table of contents.  If linking a library
+        # or program results in "error TOC overflow" add -mminimal-toc to
+        # CXXFLAGS/CFLAGS for g++/gcc.  In the cases where that is not
+        # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS.
+
+        archive_cmds_CXX=''
+        hardcode_direct_CXX=yes
+        hardcode_direct_absolute_CXX=yes
+        hardcode_libdir_separator_CXX=':'
+        link_all_deplibs_CXX=yes
+        file_list_spec_CXX='${wl}-f,'
+
+        if test "$GXX" = yes; then
+          case $host_os in aix4.[012]|aix4.[012].*)
+          # We only want to do this on AIX 4.2 and lower, the check
+          # below for broken collect2 doesn't work under 4.3+
+	  collect2name=`${CC} -print-prog-name=collect2`
+	  if test -f "$collect2name" &&
+	     strings "$collect2name" | $GREP resolve_lib_name >/dev/null
+	  then
+	    # We have reworked collect2
+	    :
+	  else
+	    # We have old collect2
+	    hardcode_direct_CXX=unsupported
+	    # It fails to find uninstalled libraries when the uninstalled
+	    # path is not listed in the libpath.  Setting hardcode_minus_L
+	    # to unsupported forces relinking
+	    hardcode_minus_L_CXX=yes
+	    hardcode_libdir_flag_spec_CXX='-L$libdir'
+	    hardcode_libdir_separator_CXX=
+	  fi
+          esac
+          shared_flag='-shared'
+	  if test "$aix_use_runtimelinking" = yes; then
+	    shared_flag="$shared_flag "'${wl}-G'
+	  fi
+        else
+          # not using gcc
+          if test "$host_cpu" = ia64; then
+	  # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release
+	  # chokes on -Wl,-G. The following line is correct:
+	  shared_flag='-G'
+          else
+	    if test "$aix_use_runtimelinking" = yes; then
+	      shared_flag='${wl}-G'
+	    else
+	      shared_flag='${wl}-bM:SRE'
+	    fi
+          fi
+        fi
+
+        export_dynamic_flag_spec_CXX='${wl}-bexpall'
+        # It seems that -bexpall does not export symbols beginning with
+        # underscore (_), so it is better to generate a list of symbols to
+	# export.
+        always_export_symbols_CXX=yes
+        if test "$aix_use_runtimelinking" = yes; then
+          # Warning - without using the other runtime loading flags (-brtl),
+          # -berok will link without error, but may produce a broken library.
+          allow_undefined_flag_CXX='-berok'
+          # Determine the default libpath from the value encoded in an empty
+          # executable.
+          if test "${lt_cv_aix_libpath+set}" = set; then
+  aix_libpath=$lt_cv_aix_libpath
+else
+  if ${lt_cv_aix_libpath__CXX+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_cxx_try_link "$LINENO"; then :
+
+  lt_aix_libpath_sed='
+      /Import File Strings/,/^$/ {
+	  /^0/ {
+	      s/^0  *\([^ ]*\) *$/\1/
+	      p
+	  }
+      }'
+  lt_cv_aix_libpath__CXX=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"`
+  # Check for a 64-bit object if we didn't find anything.
+  if test -z "$lt_cv_aix_libpath__CXX"; then
+    lt_cv_aix_libpath__CXX=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"`
+  fi
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+  if test -z "$lt_cv_aix_libpath__CXX"; then
+    lt_cv_aix_libpath__CXX="/usr/lib:/lib"
+  fi
+
+fi
+
+  aix_libpath=$lt_cv_aix_libpath__CXX
+fi
+
+          hardcode_libdir_flag_spec_CXX='${wl}-blibpath:$libdir:'"$aix_libpath"
+
+          archive_expsym_cmds_CXX='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then func_echo_all "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag"
+        else
+          if test "$host_cpu" = ia64; then
+	    hardcode_libdir_flag_spec_CXX='${wl}-R $libdir:/usr/lib:/lib'
+	    allow_undefined_flag_CXX="-z nodefs"
+	    archive_expsym_cmds_CXX="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols"
+          else
+	    # Determine the default libpath from the value encoded in an
+	    # empty executable.
+	    if test "${lt_cv_aix_libpath+set}" = set; then
+  aix_libpath=$lt_cv_aix_libpath
+else
+  if ${lt_cv_aix_libpath__CXX+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_cxx_try_link "$LINENO"; then :
+
+  lt_aix_libpath_sed='
+      /Import File Strings/,/^$/ {
+	  /^0/ {
+	      s/^0  *\([^ ]*\) *$/\1/
+	      p
+	  }
+      }'
+  lt_cv_aix_libpath__CXX=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"`
+  # Check for a 64-bit object if we didn't find anything.
+  if test -z "$lt_cv_aix_libpath__CXX"; then
+    lt_cv_aix_libpath__CXX=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"`
+  fi
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+  if test -z "$lt_cv_aix_libpath__CXX"; then
+    lt_cv_aix_libpath__CXX="/usr/lib:/lib"
+  fi
+
+fi
+
+  aix_libpath=$lt_cv_aix_libpath__CXX
+fi
+
+	    hardcode_libdir_flag_spec_CXX='${wl}-blibpath:$libdir:'"$aix_libpath"
+	    # Warning - without using the other run time loading flags,
+	    # -berok will link without error, but may produce a broken library.
+	    no_undefined_flag_CXX=' ${wl}-bernotok'
+	    allow_undefined_flag_CXX=' ${wl}-berok'
+	    if test "$with_gnu_ld" = yes; then
+	      # We only use this code for GNU lds that support --whole-archive.
+	      whole_archive_flag_spec_CXX='${wl}--whole-archive$convenience ${wl}--no-whole-archive'
+	    else
+	      # Exported symbols can be pulled into shared objects from archives
+	      whole_archive_flag_spec_CXX='$convenience'
+	    fi
+	    archive_cmds_need_lc_CXX=yes
+	    # This is similar to how AIX traditionally builds its shared
+	    # libraries.
+	    archive_expsym_cmds_CXX="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname'
+          fi
+        fi
+        ;;
+
+      beos*)
+	if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
+	  allow_undefined_flag_CXX=unsupported
+	  # Joseph Beckenbach <jrb3 at best.com> says some releases of gcc
+	  # support --undefined.  This deserves some investigation.  FIXME
+	  archive_cmds_CXX='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+	else
+	  ld_shlibs_CXX=no
+	fi
+	;;
+
+      chorus*)
+        case $cc_basename in
+          *)
+	  # FIXME: insert proper C++ library support
+	  ld_shlibs_CXX=no
+	  ;;
+        esac
+        ;;
+
+      cygwin* | mingw* | pw32* | cegcc*)
+	case $GXX,$cc_basename in
+	,cl* | no,cl*)
+	  # Native MSVC
+	  # hardcode_libdir_flag_spec is actually meaningless, as there is
+	  # no search path for DLLs.
+	  hardcode_libdir_flag_spec_CXX=' '
+	  allow_undefined_flag_CXX=unsupported
+	  always_export_symbols_CXX=yes
+	  file_list_spec_CXX='@'
+	  # Tell ltmain to make .lib files, not .a files.
+	  libext=lib
+	  # Tell ltmain to make .dll files, not .so files.
+	  shrext_cmds=".dll"
+	  # FIXME: Setting linknames here is a bad hack.
+	  archive_cmds_CXX='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-dll~linknames='
+	  archive_expsym_cmds_CXX='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
+	      $SED -n -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' -e '1\\\!p' < $export_symbols > $output_objdir/$soname.exp;
+	    else
+	      $SED -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' < $export_symbols > $output_objdir/$soname.exp;
+	    fi~
+	    $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~
+	    linknames='
+	  # The linker will not automatically build a static lib if we build a DLL.
+	  # _LT_TAGVAR(old_archive_from_new_cmds, CXX)='true'
+	  enable_shared_with_static_runtimes_CXX=yes
+	  # Don't use ranlib
+	  old_postinstall_cmds_CXX='chmod 644 $oldlib'
+	  postlink_cmds_CXX='lt_outputfile="@OUTPUT@"~
+	    lt_tool_outputfile="@TOOL_OUTPUT@"~
+	    case $lt_outputfile in
+	      *.exe|*.EXE) ;;
+	      *)
+		lt_outputfile="$lt_outputfile.exe"
+		lt_tool_outputfile="$lt_tool_outputfile.exe"
+		;;
+	    esac~
+	    func_to_tool_file "$lt_outputfile"~
+	    if test "$MANIFEST_TOOL" != ":" && test -f "$lt_outputfile.manifest"; then
+	      $MANIFEST_TOOL -manifest "$lt_tool_outputfile.manifest" -outputresource:"$lt_tool_outputfile" || exit 1;
+	      $RM "$lt_outputfile.manifest";
+	    fi'
+	  ;;
+	*)
+	  # g++
+	  # _LT_TAGVAR(hardcode_libdir_flag_spec, CXX) is actually meaningless,
+	  # as there is no search path for DLLs.
+	  hardcode_libdir_flag_spec_CXX='-L$libdir'
+	  export_dynamic_flag_spec_CXX='${wl}--export-all-symbols'
+	  allow_undefined_flag_CXX=unsupported
+	  always_export_symbols_CXX=no
+	  enable_shared_with_static_runtimes_CXX=yes
+
+	  if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then
+	    archive_cmds_CXX='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+	    # If the export-symbols file already is a .def file (1st line
+	    # is EXPORTS), use it as is; otherwise, prepend...
+	    archive_expsym_cmds_CXX='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
+	      cp $export_symbols $output_objdir/$soname.def;
+	    else
+	      echo EXPORTS > $output_objdir/$soname.def;
+	      cat $export_symbols >> $output_objdir/$soname.def;
+	    fi~
+	    $CC -shared -nostdlib $output_objdir/$soname.def $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+	  else
+	    ld_shlibs_CXX=no
+	  fi
+	  ;;
+	esac
+	;;
+      darwin* | rhapsody*)
+
+
+  archive_cmds_need_lc_CXX=no
+  hardcode_direct_CXX=no
+  hardcode_automatic_CXX=yes
+  hardcode_shlibpath_var_CXX=unsupported
+  if test "$lt_cv_ld_force_load" = "yes"; then
+    whole_archive_flag_spec_CXX='`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience ${wl}-force_load,$conv\"; done; func_echo_all \"$new_convenience\"`'
+
+  else
+    whole_archive_flag_spec_CXX=''
+  fi
+  link_all_deplibs_CXX=yes
+  allow_undefined_flag_CXX="$_lt_dar_allow_undefined"
+  case $cc_basename in
+     ifort*) _lt_dar_can_shared=yes ;;
+     *) _lt_dar_can_shared=$GCC ;;
+  esac
+  if test "$_lt_dar_can_shared" = "yes"; then
+    output_verbose_link_cmd=func_echo_all
+    archive_cmds_CXX="\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod${_lt_dsymutil}"
+    module_cmds_CXX="\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dsymutil}"
+    archive_expsym_cmds_CXX="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring ${_lt_dar_single_mod}${_lt_dar_export_syms}${_lt_dsymutil}"
+    module_expsym_cmds_CXX="sed -e 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dar_export_syms}${_lt_dsymutil}"
+       if test "$lt_cv_apple_cc_single_mod" != "yes"; then
+      archive_cmds_CXX="\$CC -r -keep_private_externs -nostdlib -o \${lib}-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \${lib}-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring${_lt_dsymutil}"
+      archive_expsym_cmds_CXX="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -r -keep_private_externs -nostdlib -o \${lib}-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \${lib}-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring${_lt_dar_export_syms}${_lt_dsymutil}"
+    fi
+
+  else
+  ld_shlibs_CXX=no
+  fi
+
+	;;
+
+      dgux*)
+        case $cc_basename in
+          ec++*)
+	    # FIXME: insert proper C++ library support
+	    ld_shlibs_CXX=no
+	    ;;
+          ghcx*)
+	    # Green Hills C++ Compiler
+	    # FIXME: insert proper C++ library support
+	    ld_shlibs_CXX=no
+	    ;;
+          *)
+	    # FIXME: insert proper C++ library support
+	    ld_shlibs_CXX=no
+	    ;;
+        esac
+        ;;
+
+      freebsd2.*)
+        # C++ shared libraries reported to be fairly broken before
+	# switch to ELF
+        ld_shlibs_CXX=no
+        ;;
+
+      freebsd-elf*)
+        archive_cmds_need_lc_CXX=no
+        ;;
+
+      freebsd* | dragonfly*)
+        # FreeBSD 3 and later use GNU C++ and GNU ld with standard ELF
+        # conventions
+        ld_shlibs_CXX=yes
+        ;;
+
+      gnu*)
+        ;;
+
+      haiku*)
+        archive_cmds_CXX='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+        link_all_deplibs_CXX=yes
+        ;;
+
+      hpux9*)
+        hardcode_libdir_flag_spec_CXX='${wl}+b ${wl}$libdir'
+        hardcode_libdir_separator_CXX=:
+        export_dynamic_flag_spec_CXX='${wl}-E'
+        hardcode_direct_CXX=yes
+        hardcode_minus_L_CXX=yes # Not in the search PATH,
+				             # but as the default
+				             # location of the library.
+
+        case $cc_basename in
+          CC*)
+            # FIXME: insert proper C++ library support
+            ld_shlibs_CXX=no
+            ;;
+          aCC*)
+            archive_cmds_CXX='$RM $output_objdir/$soname~$CC -b ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+            # Commands to make compiler produce verbose output that lists
+            # what "hidden" libraries, object files and flags are used when
+            # linking a shared library.
+            #
+            # There doesn't appear to be a way to prevent this compiler from
+            # explicitly linking system object files so we need to strip them
+            # from the output so that they don't get included in the library
+            # dependencies.
+            output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $EGREP "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"'
+            ;;
+          *)
+            if test "$GXX" = yes; then
+              archive_cmds_CXX='$RM $output_objdir/$soname~$CC -shared -nostdlib $pic_flag ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+            else
+              # FIXME: insert proper C++ library support
+              ld_shlibs_CXX=no
+            fi
+            ;;
+        esac
+        ;;
+
+      hpux10*|hpux11*)
+        if test $with_gnu_ld = no; then
+	  hardcode_libdir_flag_spec_CXX='${wl}+b ${wl}$libdir'
+	  hardcode_libdir_separator_CXX=:
+
+          case $host_cpu in
+            hppa*64*|ia64*)
+              ;;
+            *)
+	      export_dynamic_flag_spec_CXX='${wl}-E'
+              ;;
+          esac
+        fi
+        case $host_cpu in
+          hppa*64*|ia64*)
+            hardcode_direct_CXX=no
+            hardcode_shlibpath_var_CXX=no
+            ;;
+          *)
+            hardcode_direct_CXX=yes
+            hardcode_direct_absolute_CXX=yes
+            hardcode_minus_L_CXX=yes # Not in the search PATH,
+					         # but as the default
+					         # location of the library.
+            ;;
+        esac
+
+        case $cc_basename in
+          CC*)
+	    # FIXME: insert proper C++ library support
+	    ld_shlibs_CXX=no
+	    ;;
+          aCC*)
+	    case $host_cpu in
+	      hppa*64*)
+	        archive_cmds_CXX='$CC -b ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	        ;;
+	      ia64*)
+	        archive_cmds_CXX='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	        ;;
+	      *)
+	        archive_cmds_CXX='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	        ;;
+	    esac
+	    # Commands to make compiler produce verbose output that lists
+	    # what "hidden" libraries, object files and flags are used when
+	    # linking a shared library.
+	    #
+	    # There doesn't appear to be a way to prevent this compiler from
+	    # explicitly linking system object files so we need to strip them
+	    # from the output so that they don't get included in the library
+	    # dependencies.
+	    output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $GREP "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"'
+	    ;;
+          *)
+	    if test "$GXX" = yes; then
+	      if test $with_gnu_ld = no; then
+	        case $host_cpu in
+	          hppa*64*)
+	            archive_cmds_CXX='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	            ;;
+	          ia64*)
+	            archive_cmds_CXX='$CC -shared -nostdlib $pic_flag ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	            ;;
+	          *)
+	            archive_cmds_CXX='$CC -shared -nostdlib $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	            ;;
+	        esac
+	      fi
+	    else
+	      # FIXME: insert proper C++ library support
+	      ld_shlibs_CXX=no
+	    fi
+	    ;;
+        esac
+        ;;
+
+      interix[3-9]*)
+	hardcode_direct_CXX=no
+	hardcode_shlibpath_var_CXX=no
+	hardcode_libdir_flag_spec_CXX='${wl}-rpath,$libdir'
+	export_dynamic_flag_spec_CXX='${wl}-E'
+	# Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc.
+	# Instead, shared libraries are loaded at an image base (0x10000000 by
+	# default) and relocated if they conflict, which is a slow very memory
+	# consuming and fragmenting process.  To avoid this, we pick a random,
+	# 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link
+	# time.  Moving up from 0x10000000 also allows more sbrk(2) space.
+	archive_cmds_CXX='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
+	archive_expsym_cmds_CXX='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
+	;;
+      irix5* | irix6*)
+        case $cc_basename in
+          CC*)
+	    # SGI C++
+	    archive_cmds_CXX='$CC -shared -all -multigot $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
+
+	    # Archives containing C++ object files must be created using
+	    # "CC -ar", where "CC" is the IRIX C++ compiler.  This is
+	    # necessary to make sure instantiated templates are included
+	    # in the archive.
+	    old_archive_cmds_CXX='$CC -ar -WR,-u -o $oldlib $oldobjs'
+	    ;;
+          *)
+	    if test "$GXX" = yes; then
+	      if test "$with_gnu_ld" = no; then
+	        archive_cmds_CXX='$CC -shared $pic_flag -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+	      else
+	        archive_cmds_CXX='$CC -shared $pic_flag -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` -o $lib'
+	      fi
+	    fi
+	    link_all_deplibs_CXX=yes
+	    ;;
+        esac
+        hardcode_libdir_flag_spec_CXX='${wl}-rpath ${wl}$libdir'
+        hardcode_libdir_separator_CXX=:
+        inherit_rpath_CXX=yes
+        ;;
+
+      linux* | k*bsd*-gnu | kopensolaris*-gnu)
+        case $cc_basename in
+          KCC*)
+	    # Kuck and Associates, Inc. (KAI) C++ Compiler
+
+	    # KCC will only create a shared library if the output file
+	    # ends with ".so" (or ".sl" for HP-UX), so rename the library
+	    # to its proper name (with version) after linking.
+	    archive_cmds_CXX='tempext=`echo $shared_ext | $SED -e '\''s/\([^()0-9A-Za-z{}]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib'
+	    archive_expsym_cmds_CXX='tempext=`echo $shared_ext | $SED -e '\''s/\([^()0-9A-Za-z{}]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib ${wl}-retain-symbols-file,$export_symbols; mv \$templib $lib'
+	    # Commands to make compiler produce verbose output that lists
+	    # what "hidden" libraries, object files and flags are used when
+	    # linking a shared library.
+	    #
+	    # There doesn't appear to be a way to prevent this compiler from
+	    # explicitly linking system object files so we need to strip them
+	    # from the output so that they don't get included in the library
+	    # dependencies.
+	    output_verbose_link_cmd='templist=`$CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1 | $GREP "ld"`; rm -f libconftest$shared_ext; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"'
+
+	    hardcode_libdir_flag_spec_CXX='${wl}-rpath,$libdir'
+	    export_dynamic_flag_spec_CXX='${wl}--export-dynamic'
+
+	    # Archives containing C++ object files must be created using
+	    # "CC -Bstatic", where "CC" is the KAI C++ compiler.
+	    old_archive_cmds_CXX='$CC -Bstatic -o $oldlib $oldobjs'
+	    ;;
+	  icpc* | ecpc* )
+	    # Intel C++
+	    with_gnu_ld=yes
+	    # version 8.0 and above of icpc choke on multiply defined symbols
+	    # if we add $predep_objects and $postdep_objects, however 7.1 and
+	    # earlier do not add the objects themselves.
+	    case `$CC -V 2>&1` in
+	      *"Version 7."*)
+	        archive_cmds_CXX='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib'
+		archive_expsym_cmds_CXX='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+		;;
+	      *)  # Version 8.0 or newer
+	        tmp_idyn=
+	        case $host_cpu in
+		  ia64*) tmp_idyn=' -i_dynamic';;
+		esac
+	        archive_cmds_CXX='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+		archive_expsym_cmds_CXX='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+		;;
+	    esac
+	    archive_cmds_need_lc_CXX=no
+	    hardcode_libdir_flag_spec_CXX='${wl}-rpath,$libdir'
+	    export_dynamic_flag_spec_CXX='${wl}--export-dynamic'
+	    whole_archive_flag_spec_CXX='${wl}--whole-archive$convenience ${wl}--no-whole-archive'
+	    ;;
+          pgCC* | pgcpp*)
+            # Portland Group C++ compiler
+	    case `$CC -V` in
+	    *pgCC\ [1-5].* | *pgcpp\ [1-5].*)
+	      prelink_cmds_CXX='tpldir=Template.dir~
+		rm -rf $tpldir~
+		$CC --prelink_objects --instantiation_dir $tpldir $objs $libobjs $compile_deplibs~
+		compile_command="$compile_command `find $tpldir -name \*.o | sort | $NL2SP`"'
+	      old_archive_cmds_CXX='tpldir=Template.dir~
+		rm -rf $tpldir~
+		$CC --prelink_objects --instantiation_dir $tpldir $oldobjs$old_deplibs~
+		$AR $AR_FLAGS $oldlib$oldobjs$old_deplibs `find $tpldir -name \*.o | sort | $NL2SP`~
+		$RANLIB $oldlib'
+	      archive_cmds_CXX='tpldir=Template.dir~
+		rm -rf $tpldir~
+		$CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~
+		$CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | sort | $NL2SP` $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib'
+	      archive_expsym_cmds_CXX='tpldir=Template.dir~
+		rm -rf $tpldir~
+		$CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~
+		$CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | sort | $NL2SP` $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib'
+	      ;;
+	    *) # Version 6 and above use weak symbols
+	      archive_cmds_CXX='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib'
+	      archive_expsym_cmds_CXX='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib'
+	      ;;
+	    esac
+
+	    hardcode_libdir_flag_spec_CXX='${wl}--rpath ${wl}$libdir'
+	    export_dynamic_flag_spec_CXX='${wl}--export-dynamic'
+	    whole_archive_flag_spec_CXX='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
+            ;;
+	  cxx*)
+	    # Compaq C++
+	    archive_cmds_CXX='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib'
+	    archive_expsym_cmds_CXX='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname  -o $lib ${wl}-retain-symbols-file $wl$export_symbols'
+
+	    runpath_var=LD_RUN_PATH
+	    hardcode_libdir_flag_spec_CXX='-rpath $libdir'
+	    hardcode_libdir_separator_CXX=:
+
+	    # Commands to make compiler produce verbose output that lists
+	    # what "hidden" libraries, object files and flags are used when
+	    # linking a shared library.
+	    #
+	    # There doesn't appear to be a way to prevent this compiler from
+	    # explicitly linking system object files so we need to strip them
+	    # from the output so that they don't get included in the library
+	    # dependencies.
+	    output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld"`; templist=`func_echo_all "$templist" | $SED "s/\(^.*ld.*\)\( .*ld .*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "X$list" | $Xsed'
+	    ;;
+	  xl* | mpixl* | bgxl*)
+	    # IBM XL 8.0 on PPC, with GNU ld
+	    hardcode_libdir_flag_spec_CXX='${wl}-rpath ${wl}$libdir'
+	    export_dynamic_flag_spec_CXX='${wl}--export-dynamic'
+	    archive_cmds_CXX='$CC -qmkshrobj $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+	    if test "x$supports_anon_versioning" = xyes; then
+	      archive_expsym_cmds_CXX='echo "{ global:" > $output_objdir/$libname.ver~
+		cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
+		echo "local: *; };" >> $output_objdir/$libname.ver~
+		$CC -qmkshrobj $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib'
+	    fi
+	    ;;
+	  *)
+	    case `$CC -V 2>&1 | sed 5q` in
+	    *Sun\ C*)
+	      # Sun C++ 5.9
+	      no_undefined_flag_CXX=' -zdefs'
+	      archive_cmds_CXX='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	      archive_expsym_cmds_CXX='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file ${wl}$export_symbols'
+	      hardcode_libdir_flag_spec_CXX='-R$libdir'
+	      whole_archive_flag_spec_CXX='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
+	      compiler_needs_object_CXX=yes
+
+	      # Not sure whether something based on
+	      # $CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1
+	      # would be better.
+	      output_verbose_link_cmd='func_echo_all'
+
+	      # Archives containing C++ object files must be created using
+	      # "CC -xar", where "CC" is the Sun C++ compiler.  This is
+	      # necessary to make sure instantiated templates are included
+	      # in the archive.
+	      old_archive_cmds_CXX='$CC -xar -o $oldlib $oldobjs'
+	      ;;
+	    esac
+	    ;;
+	esac
+	;;
+
+      lynxos*)
+        # FIXME: insert proper C++ library support
+	ld_shlibs_CXX=no
+	;;
+
+      m88k*)
+        # FIXME: insert proper C++ library support
+        ld_shlibs_CXX=no
+	;;
+
+      mvs*)
+        case $cc_basename in
+          cxx*)
+	    # FIXME: insert proper C++ library support
+	    ld_shlibs_CXX=no
+	    ;;
+	  *)
+	    # FIXME: insert proper C++ library support
+	    ld_shlibs_CXX=no
+	    ;;
+	esac
+	;;
+
+      netbsd*)
+        if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
+	  archive_cmds_CXX='$LD -Bshareable  -o $lib $predep_objects $libobjs $deplibs $postdep_objects $linker_flags'
+	  wlarc=
+	  hardcode_libdir_flag_spec_CXX='-R$libdir'
+	  hardcode_direct_CXX=yes
+	  hardcode_shlibpath_var_CXX=no
+	fi
+	# Workaround some broken pre-1.5 toolchains
+	output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP conftest.$objext | $SED -e "s:-lgcc -lc -lgcc::"'
+	;;
+
+      *nto* | *qnx*)
+        ld_shlibs_CXX=yes
+	;;
+
+      openbsd2*)
+        # C++ shared libraries are fairly broken
+	ld_shlibs_CXX=no
+	;;
+
+      openbsd*)
+	if test -f /usr/libexec/ld.so; then
+	  hardcode_direct_CXX=yes
+	  hardcode_shlibpath_var_CXX=no
+	  hardcode_direct_absolute_CXX=yes
+	  archive_cmds_CXX='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib'
+	  hardcode_libdir_flag_spec_CXX='${wl}-rpath,$libdir'
+	  if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+	    archive_expsym_cmds_CXX='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file,$export_symbols -o $lib'
+	    export_dynamic_flag_spec_CXX='${wl}-E'
+	    whole_archive_flag_spec_CXX="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
+	  fi
+	  output_verbose_link_cmd=func_echo_all
+	else
+	  ld_shlibs_CXX=no
+	fi
+	;;
+
+      osf3* | osf4* | osf5*)
+        case $cc_basename in
+          KCC*)
+	    # Kuck and Associates, Inc. (KAI) C++ Compiler
+
+	    # KCC will only create a shared library if the output file
+	    # ends with ".so" (or ".sl" for HP-UX), so rename the library
+	    # to its proper name (with version) after linking.
+	    archive_cmds_CXX='tempext=`echo $shared_ext | $SED -e '\''s/\([^()0-9A-Za-z{}]\)/\\\\\1/g'\''`; templib=`echo "$lib" | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib'
+
+	    hardcode_libdir_flag_spec_CXX='${wl}-rpath,$libdir'
+	    hardcode_libdir_separator_CXX=:
+
+	    # Archives containing C++ object files must be created using
+	    # the KAI C++ compiler.
+	    case $host in
+	      osf3*) old_archive_cmds_CXX='$CC -Bstatic -o $oldlib $oldobjs' ;;
+	      *) old_archive_cmds_CXX='$CC -o $oldlib $oldobjs' ;;
+	    esac
+	    ;;
+          RCC*)
+	    # Rational C++ 2.4.1
+	    # FIXME: insert proper C++ library support
+	    ld_shlibs_CXX=no
+	    ;;
+          cxx*)
+	    case $host in
+	      osf3*)
+	        allow_undefined_flag_CXX=' ${wl}-expect_unresolved ${wl}\*'
+	        archive_cmds_CXX='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $soname `test -n "$verstring" && func_echo_all "${wl}-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
+	        hardcode_libdir_flag_spec_CXX='${wl}-rpath ${wl}$libdir'
+		;;
+	      *)
+	        allow_undefined_flag_CXX=' -expect_unresolved \*'
+	        archive_cmds_CXX='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
+	        archive_expsym_cmds_CXX='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done~
+	          echo "-hidden">> $lib.exp~
+	          $CC -shared$allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname ${wl}-input ${wl}$lib.exp  `test -n "$verstring" && $ECHO "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib~
+	          $RM $lib.exp'
+	        hardcode_libdir_flag_spec_CXX='-rpath $libdir'
+		;;
+	    esac
+
+	    hardcode_libdir_separator_CXX=:
+
+	    # Commands to make compiler produce verbose output that lists
+	    # what "hidden" libraries, object files and flags are used when
+	    # linking a shared library.
+	    #
+	    # There doesn't appear to be a way to prevent this compiler from
+	    # explicitly linking system object files so we need to strip them
+	    # from the output so that they don't get included in the library
+	    # dependencies.
+	    output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld" | $GREP -v "ld:"`; templist=`func_echo_all "$templist" | $SED "s/\(^.*ld.*\)\( .*ld.*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"'
+	    ;;
+	  *)
+	    if test "$GXX" = yes && test "$with_gnu_ld" = no; then
+	      allow_undefined_flag_CXX=' ${wl}-expect_unresolved ${wl}\*'
+	      case $host in
+	        osf3*)
+	          archive_cmds_CXX='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+		  ;;
+	        *)
+	          archive_cmds_CXX='$CC -shared $pic_flag -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+		  ;;
+	      esac
+
+	      hardcode_libdir_flag_spec_CXX='${wl}-rpath ${wl}$libdir'
+	      hardcode_libdir_separator_CXX=:
+
+	      # Commands to make compiler produce verbose output that lists
+	      # what "hidden" libraries, object files and flags are used when
+	      # linking a shared library.
+	      output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"'
+
+	    else
+	      # FIXME: insert proper C++ library support
+	      ld_shlibs_CXX=no
+	    fi
+	    ;;
+        esac
+        ;;
+
+      psos*)
+        # FIXME: insert proper C++ library support
+        ld_shlibs_CXX=no
+        ;;
+
+      sunos4*)
+        case $cc_basename in
+          CC*)
+	    # Sun C++ 4.x
+	    # FIXME: insert proper C++ library support
+	    ld_shlibs_CXX=no
+	    ;;
+          lcc*)
+	    # Lucid
+	    # FIXME: insert proper C++ library support
+	    ld_shlibs_CXX=no
+	    ;;
+          *)
+	    # FIXME: insert proper C++ library support
+	    ld_shlibs_CXX=no
+	    ;;
+        esac
+        ;;
+
+      solaris*)
+        case $cc_basename in
+          CC* | sunCC*)
+	    # Sun C++ 4.2, 5.x and Centerline C++
+            archive_cmds_need_lc_CXX=yes
+	    no_undefined_flag_CXX=' -zdefs'
+	    archive_cmds_CXX='$CC -G${allow_undefined_flag}  -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	    archive_expsym_cmds_CXX='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
+	      $CC -G${allow_undefined_flag} ${wl}-M ${wl}$lib.exp -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp'
+
+	    hardcode_libdir_flag_spec_CXX='-R$libdir'
+	    hardcode_shlibpath_var_CXX=no
+	    case $host_os in
+	      solaris2.[0-5] | solaris2.[0-5].*) ;;
+	      *)
+		# The compiler driver will combine and reorder linker options,
+		# but understands `-z linker_flag'.
+	        # Supported since Solaris 2.6 (maybe 2.5.1?)
+		whole_archive_flag_spec_CXX='-z allextract$convenience -z defaultextract'
+	        ;;
+	    esac
+	    link_all_deplibs_CXX=yes
+
+	    output_verbose_link_cmd='func_echo_all'
+
+	    # Archives containing C++ object files must be created using
+	    # "CC -xar", where "CC" is the Sun C++ compiler.  This is
+	    # necessary to make sure instantiated templates are included
+	    # in the archive.
+	    old_archive_cmds_CXX='$CC -xar -o $oldlib $oldobjs'
+	    ;;
+          gcx*)
+	    # Green Hills C++ Compiler
+	    archive_cmds_CXX='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib'
+
+	    # The C++ compiler must be used to create the archive.
+	    old_archive_cmds_CXX='$CC $LDFLAGS -archive -o $oldlib $oldobjs'
+	    ;;
+          *)
+	    # GNU C++ compiler with Solaris linker
+	    if test "$GXX" = yes && test "$with_gnu_ld" = no; then
+	      no_undefined_flag_CXX=' ${wl}-z ${wl}defs'
+	      if $CC --version | $GREP -v '^2\.7' > /dev/null; then
+	        archive_cmds_CXX='$CC -shared $pic_flag -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib'
+	        archive_expsym_cmds_CXX='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
+		  $CC -shared $pic_flag -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp'
+
+	        # Commands to make compiler produce verbose output that lists
+	        # what "hidden" libraries, object files and flags are used when
+	        # linking a shared library.
+	        output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"'
+	      else
+	        # g++ 2.7 appears to require `-G' NOT `-shared' on this
+	        # platform.
+	        archive_cmds_CXX='$CC -G -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib'
+	        archive_expsym_cmds_CXX='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
+		  $CC -G -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp'
+
+	        # Commands to make compiler produce verbose output that lists
+	        # what "hidden" libraries, object files and flags are used when
+	        # linking a shared library.
+	        output_verbose_link_cmd='$CC -G $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"'
+	      fi
+
+	      hardcode_libdir_flag_spec_CXX='${wl}-R $wl$libdir'
+	      case $host_os in
+		solaris2.[0-5] | solaris2.[0-5].*) ;;
+		*)
+		  whole_archive_flag_spec_CXX='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract'
+		  ;;
+	      esac
+	    fi
+	    ;;
+        esac
+        ;;
+
+    sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[01].[10]* | unixware7* | sco3.2v5.0.[024]*)
+      no_undefined_flag_CXX='${wl}-z,text'
+      archive_cmds_need_lc_CXX=no
+      hardcode_shlibpath_var_CXX=no
+      runpath_var='LD_RUN_PATH'
+
+      case $cc_basename in
+        CC*)
+	  archive_cmds_CXX='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	  archive_expsym_cmds_CXX='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	  ;;
+	*)
+	  archive_cmds_CXX='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	  archive_expsym_cmds_CXX='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	  ;;
+      esac
+      ;;
+
+      sysv5* | sco3.2v5* | sco5v6*)
+	# Note: We can NOT use -z defs as we might desire, because we do not
+	# link with -lc, and that would cause any symbols used from libc to
+	# always be unresolved, which means just about no library would
+	# ever link correctly.  If we're not using GNU ld we use -z text
+	# though, which does catch some bad symbols but isn't as heavy-handed
+	# as -z defs.
+	no_undefined_flag_CXX='${wl}-z,text'
+	allow_undefined_flag_CXX='${wl}-z,nodefs'
+	archive_cmds_need_lc_CXX=no
+	hardcode_shlibpath_var_CXX=no
+	hardcode_libdir_flag_spec_CXX='${wl}-R,$libdir'
+	hardcode_libdir_separator_CXX=':'
+	link_all_deplibs_CXX=yes
+	export_dynamic_flag_spec_CXX='${wl}-Bexport'
+	runpath_var='LD_RUN_PATH'
+
+	case $cc_basename in
+          CC*)
+	    archive_cmds_CXX='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	    archive_expsym_cmds_CXX='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	    old_archive_cmds_CXX='$CC -Tprelink_objects $oldobjs~
+	      '"$old_archive_cmds_CXX"
+	    reload_cmds_CXX='$CC -Tprelink_objects $reload_objs~
+	      '"$reload_cmds_CXX"
+	    ;;
+	  *)
+	    archive_cmds_CXX='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	    archive_expsym_cmds_CXX='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	    ;;
+	esac
+      ;;
+
+      tandem*)
+        case $cc_basename in
+          NCC*)
+	    # NonStop-UX NCC 3.20
+	    # FIXME: insert proper C++ library support
+	    ld_shlibs_CXX=no
+	    ;;
+          *)
+	    # FIXME: insert proper C++ library support
+	    ld_shlibs_CXX=no
+	    ;;
+        esac
+        ;;
+
+      vxworks*)
+        # FIXME: insert proper C++ library support
+        ld_shlibs_CXX=no
+        ;;
+
+      *)
+        # FIXME: insert proper C++ library support
+        ld_shlibs_CXX=no
+        ;;
+    esac
+
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ld_shlibs_CXX" >&5
+$as_echo "$ld_shlibs_CXX" >&6; }
+    test "$ld_shlibs_CXX" = no && can_build_shared=no
+
+    GCC_CXX="$GXX"
+    LD_CXX="$LD"
+
+    ## CAVEAT EMPTOR:
+    ## There is no encapsulation within the following macros, do not change
+    ## the running order or otherwise move them around unless you know exactly
+    ## what you are doing...
+    # Dependencies to place before and after the object being linked:
+predep_objects_CXX=
+postdep_objects_CXX=
+predeps_CXX=
+postdeps_CXX=
+compiler_lib_search_path_CXX=
+
+cat > conftest.$ac_ext <<_LT_EOF
+class Foo
+{
+public:
+  Foo (void) { a = 0; }
+private:
+  int a;
+};
+_LT_EOF
+
+
+_lt_libdeps_save_CFLAGS=$CFLAGS
+case "$CC $CFLAGS " in #(
+*\ -flto*\ *) CFLAGS="$CFLAGS -fno-lto" ;;
+*\ -fwhopr*\ *) CFLAGS="$CFLAGS -fno-whopr" ;;
+*\ -fuse-linker-plugin*\ *) CFLAGS="$CFLAGS -fno-use-linker-plugin" ;;
+esac
+
+if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5
+  (eval $ac_compile) 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; then
+  # Parse the compiler output and extract the necessary
+  # objects, libraries and library flags.
+
+  # Sentinel used to keep track of whether or not we are before
+  # the conftest object file.
+  pre_test_object_deps_done=no
+
+  for p in `eval "$output_verbose_link_cmd"`; do
+    case ${prev}${p} in
+
+    -L* | -R* | -l*)
+       # Some compilers place space between "-{L,R}" and the path.
+       # Remove the space.
+       if test $p = "-L" ||
+          test $p = "-R"; then
+	 prev=$p
+	 continue
+       fi
+
+       # Expand the sysroot to ease extracting the directories later.
+       if test -z "$prev"; then
+         case $p in
+         -L*) func_stripname_cnf '-L' '' "$p"; prev=-L; p=$func_stripname_result ;;
+         -R*) func_stripname_cnf '-R' '' "$p"; prev=-R; p=$func_stripname_result ;;
+         -l*) func_stripname_cnf '-l' '' "$p"; prev=-l; p=$func_stripname_result ;;
+         esac
+       fi
+       case $p in
+       =*) func_stripname_cnf '=' '' "$p"; p=$lt_sysroot$func_stripname_result ;;
+       esac
+       if test "$pre_test_object_deps_done" = no; then
+	 case ${prev} in
+	 -L | -R)
+	   # Internal compiler library paths should come after those
+	   # provided the user.  The postdeps already come after the
+	   # user supplied libs so there is no need to process them.
+	   if test -z "$compiler_lib_search_path_CXX"; then
+	     compiler_lib_search_path_CXX="${prev}${p}"
+	   else
+	     compiler_lib_search_path_CXX="${compiler_lib_search_path_CXX} ${prev}${p}"
+	   fi
+	   ;;
+	 # The "-l" case would never come before the object being
+	 # linked, so don't bother handling this case.
+	 esac
+       else
+	 if test -z "$postdeps_CXX"; then
+	   postdeps_CXX="${prev}${p}"
+	 else
+	   postdeps_CXX="${postdeps_CXX} ${prev}${p}"
+	 fi
+       fi
+       prev=
+       ;;
+
+    *.lto.$objext) ;; # Ignore GCC LTO objects
+    *.$objext)
+       # This assumes that the test object file only shows up
+       # once in the compiler output.
+       if test "$p" = "conftest.$objext"; then
+	 pre_test_object_deps_done=yes
+	 continue
+       fi
+
+       if test "$pre_test_object_deps_done" = no; then
+	 if test -z "$predep_objects_CXX"; then
+	   predep_objects_CXX="$p"
+	 else
+	   predep_objects_CXX="$predep_objects_CXX $p"
+	 fi
+       else
+	 if test -z "$postdep_objects_CXX"; then
+	   postdep_objects_CXX="$p"
+	 else
+	   postdep_objects_CXX="$postdep_objects_CXX $p"
+	 fi
+       fi
+       ;;
+
+    *) ;; # Ignore the rest.
+
+    esac
+  done
+
+  # Clean up.
+  rm -f a.out a.exe
+else
+  echo "libtool.m4: error: problem compiling CXX test program"
+fi
+
+$RM -f confest.$objext
+CFLAGS=$_lt_libdeps_save_CFLAGS
+
+# PORTME: override above test on systems where it is broken
+case $host_os in
+interix[3-9]*)
+  # Interix 3.5 installs completely hosed .la files for C++, so rather than
+  # hack all around it, let's just trust "g++" to DTRT.
+  predep_objects_CXX=
+  postdep_objects_CXX=
+  postdeps_CXX=
+  ;;
+
+linux*)
+  case `$CC -V 2>&1 | sed 5q` in
+  *Sun\ C*)
+    # Sun C++ 5.9
+
+    # The more standards-conforming stlport4 library is
+    # incompatible with the Cstd library. Avoid specifying
+    # it if it's in CXXFLAGS. Ignore libCrun as
+    # -library=stlport4 depends on it.
+    case " $CXX $CXXFLAGS " in
+    *" -library=stlport4 "*)
+      solaris_use_stlport4=yes
+      ;;
+    esac
+
+    if test "$solaris_use_stlport4" != yes; then
+      postdeps_CXX='-library=Cstd -library=Crun'
+    fi
+    ;;
+  esac
+  ;;
+
+solaris*)
+  case $cc_basename in
+  CC* | sunCC*)
+    # The more standards-conforming stlport4 library is
+    # incompatible with the Cstd library. Avoid specifying
+    # it if it's in CXXFLAGS. Ignore libCrun as
+    # -library=stlport4 depends on it.
+    case " $CXX $CXXFLAGS " in
+    *" -library=stlport4 "*)
+      solaris_use_stlport4=yes
+      ;;
+    esac
+
+    # Adding this requires a known-good setup of shared libraries for
+    # Sun compiler versions before 5.6, else PIC objects from an old
+    # archive will be linked into the output, leading to subtle bugs.
+    if test "$solaris_use_stlport4" != yes; then
+      postdeps_CXX='-library=Cstd -library=Crun'
+    fi
+    ;;
+  esac
+  ;;
+esac
+
+
+case " $postdeps_CXX " in
+*" -lc "*) archive_cmds_need_lc_CXX=no ;;
+esac
+ compiler_lib_search_dirs_CXX=
+if test -n "${compiler_lib_search_path_CXX}"; then
+ compiler_lib_search_dirs_CXX=`echo " ${compiler_lib_search_path_CXX}" | ${SED} -e 's! -L! !g' -e 's!^ !!'`
+fi
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+    lt_prog_compiler_wl_CXX=
+lt_prog_compiler_pic_CXX=
+lt_prog_compiler_static_CXX=
+
+
+  # C++ specific cases for pic, static, wl, etc.
+  if test "$GXX" = yes; then
+    lt_prog_compiler_wl_CXX='-Wl,'
+    lt_prog_compiler_static_CXX='-static'
+
+    case $host_os in
+    aix*)
+      # All AIX code is PIC.
+      if test "$host_cpu" = ia64; then
+	# AIX 5 now supports IA64 processor
+	lt_prog_compiler_static_CXX='-Bstatic'
+      fi
+      ;;
+
+    amigaos*)
+      case $host_cpu in
+      powerpc)
+            # see comment about AmigaOS4 .so support
+            lt_prog_compiler_pic_CXX='-fPIC'
+        ;;
+      m68k)
+            # FIXME: we need at least 68020 code to build shared libraries, but
+            # adding the `-m68020' flag to GCC prevents building anything better,
+            # like `-m68040'.
+            lt_prog_compiler_pic_CXX='-m68020 -resident32 -malways-restore-a4'
+        ;;
+      esac
+      ;;
+
+    beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*)
+      # PIC is the default for these OSes.
+      ;;
+    mingw* | cygwin* | os2* | pw32* | cegcc*)
+      # This hack is so that the source file can tell whether it is being
+      # built for inclusion in a dll (and should export symbols for example).
+      # Although the cygwin gcc ignores -fPIC, still need this for old-style
+      # (--disable-auto-import) libraries
+      lt_prog_compiler_pic_CXX='-DDLL_EXPORT'
+      ;;
+    darwin* | rhapsody*)
+      # PIC is the default on this platform
+      # Common symbols not allowed in MH_DYLIB files
+      lt_prog_compiler_pic_CXX='-fno-common'
+      ;;
+    *djgpp*)
+      # DJGPP does not support shared libraries at all
+      lt_prog_compiler_pic_CXX=
+      ;;
+    haiku*)
+      # PIC is the default for Haiku.
+      # The "-static" flag exists, but is broken.
+      lt_prog_compiler_static_CXX=
+      ;;
+    interix[3-9]*)
+      # Interix 3.x gcc -fpic/-fPIC options generate broken code.
+      # Instead, we relocate shared libraries at runtime.
+      ;;
+    sysv4*MP*)
+      if test -d /usr/nec; then
+	lt_prog_compiler_pic_CXX=-Kconform_pic
+      fi
+      ;;
+    hpux*)
+      # PIC is the default for 64-bit PA HP-UX, but not for 32-bit
+      # PA HP-UX.  On IA64 HP-UX, PIC is the default but the pic flag
+      # sets the default TLS model and affects inlining.
+      case $host_cpu in
+      hppa*64*)
+	;;
+      *)
+	lt_prog_compiler_pic_CXX='-fPIC'
+	;;
+      esac
+      ;;
+    *qnx* | *nto*)
+      # QNX uses GNU C++, but need to define -shared option too, otherwise
+      # it will coredump.
+      lt_prog_compiler_pic_CXX='-fPIC -shared'
+      ;;
+    *)
+      lt_prog_compiler_pic_CXX='-fPIC'
+      ;;
+    esac
+  else
+    case $host_os in
+      aix[4-9]*)
+	# All AIX code is PIC.
+	if test "$host_cpu" = ia64; then
+	  # AIX 5 now supports IA64 processor
+	  lt_prog_compiler_static_CXX='-Bstatic'
+	else
+	  lt_prog_compiler_static_CXX='-bnso -bI:/lib/syscalls.exp'
+	fi
+	;;
+      chorus*)
+	case $cc_basename in
+	cxch68*)
+	  # Green Hills C++ Compiler
+	  # _LT_TAGVAR(lt_prog_compiler_static, CXX)="--no_auto_instantiation -u __main -u __premain -u _abort -r $COOL_DIR/lib/libOrb.a $MVME_DIR/lib/CC/libC.a $MVME_DIR/lib/classix/libcx.s.a"
+	  ;;
+	esac
+	;;
+      mingw* | cygwin* | os2* | pw32* | cegcc*)
+	# This hack is so that the source file can tell whether it is being
+	# built for inclusion in a dll (and should export symbols for example).
+	lt_prog_compiler_pic_CXX='-DDLL_EXPORT'
+	;;
+      dgux*)
+	case $cc_basename in
+	  ec++*)
+	    lt_prog_compiler_pic_CXX='-KPIC'
+	    ;;
+	  ghcx*)
+	    # Green Hills C++ Compiler
+	    lt_prog_compiler_pic_CXX='-pic'
+	    ;;
+	  *)
+	    ;;
+	esac
+	;;
+      freebsd* | dragonfly*)
+	# FreeBSD uses GNU C++
+	;;
+      hpux9* | hpux10* | hpux11*)
+	case $cc_basename in
+	  CC*)
+	    lt_prog_compiler_wl_CXX='-Wl,'
+	    lt_prog_compiler_static_CXX='${wl}-a ${wl}archive'
+	    if test "$host_cpu" != ia64; then
+	      lt_prog_compiler_pic_CXX='+Z'
+	    fi
+	    ;;
+	  aCC*)
+	    lt_prog_compiler_wl_CXX='-Wl,'
+	    lt_prog_compiler_static_CXX='${wl}-a ${wl}archive'
+	    case $host_cpu in
+	    hppa*64*|ia64*)
+	      # +Z the default
+	      ;;
+	    *)
+	      lt_prog_compiler_pic_CXX='+Z'
+	      ;;
+	    esac
+	    ;;
+	  *)
+	    ;;
+	esac
+	;;
+      interix*)
+	# This is c89, which is MS Visual C++ (no shared libs)
+	# Anyone wants to do a port?
+	;;
+      irix5* | irix6* | nonstopux*)
+	case $cc_basename in
+	  CC*)
+	    lt_prog_compiler_wl_CXX='-Wl,'
+	    lt_prog_compiler_static_CXX='-non_shared'
+	    # CC pic flag -KPIC is the default.
+	    ;;
+	  *)
+	    ;;
+	esac
+	;;
+      linux* | k*bsd*-gnu | kopensolaris*-gnu)
+	case $cc_basename in
+	  KCC*)
+	    # KAI C++ Compiler
+	    lt_prog_compiler_wl_CXX='--backend -Wl,'
+	    lt_prog_compiler_pic_CXX='-fPIC'
+	    ;;
+	  ecpc* )
+	    # old Intel C++ for x86_64 which still supported -KPIC.
+	    lt_prog_compiler_wl_CXX='-Wl,'
+	    lt_prog_compiler_pic_CXX='-KPIC'
+	    lt_prog_compiler_static_CXX='-static'
+	    ;;
+	  icpc* )
+	    # Intel C++, used to be incompatible with GCC.
+	    # ICC 10 doesn't accept -KPIC any more.
+	    lt_prog_compiler_wl_CXX='-Wl,'
+	    lt_prog_compiler_pic_CXX='-fPIC'
+	    lt_prog_compiler_static_CXX='-static'
+	    ;;
+	  pgCC* | pgcpp*)
+	    # Portland Group C++ compiler
+	    lt_prog_compiler_wl_CXX='-Wl,'
+	    lt_prog_compiler_pic_CXX='-fpic'
+	    lt_prog_compiler_static_CXX='-Bstatic'
+	    ;;
+	  cxx*)
+	    # Compaq C++
+	    # Make sure the PIC flag is empty.  It appears that all Alpha
+	    # Linux and Compaq Tru64 Unix objects are PIC.
+	    lt_prog_compiler_pic_CXX=
+	    lt_prog_compiler_static_CXX='-non_shared'
+	    ;;
+	  xlc* | xlC* | bgxl[cC]* | mpixl[cC]*)
+	    # IBM XL 8.0, 9.0 on PPC and BlueGene
+	    lt_prog_compiler_wl_CXX='-Wl,'
+	    lt_prog_compiler_pic_CXX='-qpic'
+	    lt_prog_compiler_static_CXX='-qstaticlink'
+	    ;;
+	  *)
+	    case `$CC -V 2>&1 | sed 5q` in
+	    *Sun\ C*)
+	      # Sun C++ 5.9
+	      lt_prog_compiler_pic_CXX='-KPIC'
+	      lt_prog_compiler_static_CXX='-Bstatic'
+	      lt_prog_compiler_wl_CXX='-Qoption ld '
+	      ;;
+	    esac
+	    ;;
+	esac
+	;;
+      lynxos*)
+	;;
+      m88k*)
+	;;
+      mvs*)
+	case $cc_basename in
+	  cxx*)
+	    lt_prog_compiler_pic_CXX='-W c,exportall'
+	    ;;
+	  *)
+	    ;;
+	esac
+	;;
+      netbsd* | netbsdelf*-gnu)
+	;;
+      *qnx* | *nto*)
+        # QNX uses GNU C++, but need to define -shared option too, otherwise
+        # it will coredump.
+        lt_prog_compiler_pic_CXX='-fPIC -shared'
+        ;;
+      osf3* | osf4* | osf5*)
+	case $cc_basename in
+	  KCC*)
+	    lt_prog_compiler_wl_CXX='--backend -Wl,'
+	    ;;
+	  RCC*)
+	    # Rational C++ 2.4.1
+	    lt_prog_compiler_pic_CXX='-pic'
+	    ;;
+	  cxx*)
+	    # Digital/Compaq C++
+	    lt_prog_compiler_wl_CXX='-Wl,'
+	    # Make sure the PIC flag is empty.  It appears that all Alpha
+	    # Linux and Compaq Tru64 Unix objects are PIC.
+	    lt_prog_compiler_pic_CXX=
+	    lt_prog_compiler_static_CXX='-non_shared'
+	    ;;
+	  *)
+	    ;;
+	esac
+	;;
+      psos*)
+	;;
+      solaris*)
+	case $cc_basename in
+	  CC* | sunCC*)
+	    # Sun C++ 4.2, 5.x and Centerline C++
+	    lt_prog_compiler_pic_CXX='-KPIC'
+	    lt_prog_compiler_static_CXX='-Bstatic'
+	    lt_prog_compiler_wl_CXX='-Qoption ld '
+	    ;;
+	  gcx*)
+	    # Green Hills C++ Compiler
+	    lt_prog_compiler_pic_CXX='-PIC'
+	    ;;
+	  *)
+	    ;;
+	esac
+	;;
+      sunos4*)
+	case $cc_basename in
+	  CC*)
+	    # Sun C++ 4.x
+	    lt_prog_compiler_pic_CXX='-pic'
+	    lt_prog_compiler_static_CXX='-Bstatic'
+	    ;;
+	  lcc*)
+	    # Lucid
+	    lt_prog_compiler_pic_CXX='-pic'
+	    ;;
+	  *)
+	    ;;
+	esac
+	;;
+      sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*)
+	case $cc_basename in
+	  CC*)
+	    lt_prog_compiler_wl_CXX='-Wl,'
+	    lt_prog_compiler_pic_CXX='-KPIC'
+	    lt_prog_compiler_static_CXX='-Bstatic'
+	    ;;
+	esac
+	;;
+      tandem*)
+	case $cc_basename in
+	  NCC*)
+	    # NonStop-UX NCC 3.20
+	    lt_prog_compiler_pic_CXX='-KPIC'
+	    ;;
+	  *)
+	    ;;
+	esac
+	;;
+      vxworks*)
+	;;
+      *)
+	lt_prog_compiler_can_build_shared_CXX=no
+	;;
+    esac
+  fi
+
+case $host_os in
+  # For platforms which do not support PIC, -DPIC is meaningless:
+  *djgpp*)
+    lt_prog_compiler_pic_CXX=
+    ;;
+  *)
+    lt_prog_compiler_pic_CXX="$lt_prog_compiler_pic_CXX -DPIC"
+    ;;
+esac
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $compiler option to produce PIC" >&5
+$as_echo_n "checking for $compiler option to produce PIC... " >&6; }
+if ${lt_cv_prog_compiler_pic_CXX+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  lt_cv_prog_compiler_pic_CXX=$lt_prog_compiler_pic_CXX
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_pic_CXX" >&5
+$as_echo "$lt_cv_prog_compiler_pic_CXX" >&6; }
+lt_prog_compiler_pic_CXX=$lt_cv_prog_compiler_pic_CXX
+
+#
+# Check to make sure the PIC flag actually works.
+#
+if test -n "$lt_prog_compiler_pic_CXX"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler PIC flag $lt_prog_compiler_pic_CXX works" >&5
+$as_echo_n "checking if $compiler PIC flag $lt_prog_compiler_pic_CXX works... " >&6; }
+if ${lt_cv_prog_compiler_pic_works_CXX+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  lt_cv_prog_compiler_pic_works_CXX=no
+   ac_outfile=conftest.$ac_objext
+   echo "$lt_simple_compile_test_code" > conftest.$ac_ext
+   lt_compiler_flag="$lt_prog_compiler_pic_CXX -DPIC"
+   # Insert the option either (1) after the last *FLAGS variable, or
+   # (2) before a word containing "conftest.", or (3) at the end.
+   # Note that $ac_compile itself does not contain backslashes and begins
+   # with a dollar sign (not a hyphen), so the echo should work correctly.
+   # The option is referenced via a variable to avoid confusing sed.
+   lt_compile=`echo "$ac_compile" | $SED \
+   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
+   -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
+   -e 's:$: $lt_compiler_flag:'`
+   (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5)
+   (eval "$lt_compile" 2>conftest.err)
+   ac_status=$?
+   cat conftest.err >&5
+   echo "$as_me:$LINENO: \$? = $ac_status" >&5
+   if (exit $ac_status) && test -s "$ac_outfile"; then
+     # The compiler can only warn and ignore the option if not recognized
+     # So say no if there are warnings other than the usual output.
+     $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' >conftest.exp
+     $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
+     if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then
+       lt_cv_prog_compiler_pic_works_CXX=yes
+     fi
+   fi
+   $RM conftest*
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_pic_works_CXX" >&5
+$as_echo "$lt_cv_prog_compiler_pic_works_CXX" >&6; }
+
+if test x"$lt_cv_prog_compiler_pic_works_CXX" = xyes; then
+    case $lt_prog_compiler_pic_CXX in
+     "" | " "*) ;;
+     *) lt_prog_compiler_pic_CXX=" $lt_prog_compiler_pic_CXX" ;;
+     esac
+else
+    lt_prog_compiler_pic_CXX=
+     lt_prog_compiler_can_build_shared_CXX=no
+fi
+
+fi
+
+
+
+
+
+#
+# Check to make sure the static flag actually works.
+#
+wl=$lt_prog_compiler_wl_CXX eval lt_tmp_static_flag=\"$lt_prog_compiler_static_CXX\"
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler static flag $lt_tmp_static_flag works" >&5
+$as_echo_n "checking if $compiler static flag $lt_tmp_static_flag works... " >&6; }
+if ${lt_cv_prog_compiler_static_works_CXX+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  lt_cv_prog_compiler_static_works_CXX=no
+   save_LDFLAGS="$LDFLAGS"
+   LDFLAGS="$LDFLAGS $lt_tmp_static_flag"
+   echo "$lt_simple_link_test_code" > conftest.$ac_ext
+   if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then
+     # The linker can only warn and ignore the option if not recognized
+     # So say no if there are warnings
+     if test -s conftest.err; then
+       # Append any errors to the config.log.
+       cat conftest.err 1>&5
+       $ECHO "$_lt_linker_boilerplate" | $SED '/^$/d' > conftest.exp
+       $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
+       if diff conftest.exp conftest.er2 >/dev/null; then
+         lt_cv_prog_compiler_static_works_CXX=yes
+       fi
+     else
+       lt_cv_prog_compiler_static_works_CXX=yes
+     fi
+   fi
+   $RM -r conftest*
+   LDFLAGS="$save_LDFLAGS"
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_static_works_CXX" >&5
+$as_echo "$lt_cv_prog_compiler_static_works_CXX" >&6; }
+
+if test x"$lt_cv_prog_compiler_static_works_CXX" = xyes; then
+    :
+else
+    lt_prog_compiler_static_CXX=
+fi
+
+
+
+
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler supports -c -o file.$ac_objext" >&5
+$as_echo_n "checking if $compiler supports -c -o file.$ac_objext... " >&6; }
+if ${lt_cv_prog_compiler_c_o_CXX+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  lt_cv_prog_compiler_c_o_CXX=no
+   $RM -r conftest 2>/dev/null
+   mkdir conftest
+   cd conftest
+   mkdir out
+   echo "$lt_simple_compile_test_code" > conftest.$ac_ext
+
+   lt_compiler_flag="-o out/conftest2.$ac_objext"
+   # Insert the option either (1) after the last *FLAGS variable, or
+   # (2) before a word containing "conftest.", or (3) at the end.
+   # Note that $ac_compile itself does not contain backslashes and begins
+   # with a dollar sign (not a hyphen), so the echo should work correctly.
+   lt_compile=`echo "$ac_compile" | $SED \
+   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
+   -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
+   -e 's:$: $lt_compiler_flag:'`
+   (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5)
+   (eval "$lt_compile" 2>out/conftest.err)
+   ac_status=$?
+   cat out/conftest.err >&5
+   echo "$as_me:$LINENO: \$? = $ac_status" >&5
+   if (exit $ac_status) && test -s out/conftest2.$ac_objext
+   then
+     # The compiler can only warn and ignore the option if not recognized
+     # So say no if there are warnings
+     $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' > out/conftest.exp
+     $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2
+     if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then
+       lt_cv_prog_compiler_c_o_CXX=yes
+     fi
+   fi
+   chmod u+w . 2>&5
+   $RM conftest*
+   # SGI C++ compiler will create directory out/ii_files/ for
+   # template instantiation
+   test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files
+   $RM out/* && rmdir out
+   cd ..
+   $RM -r conftest
+   $RM conftest*
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_c_o_CXX" >&5
+$as_echo "$lt_cv_prog_compiler_c_o_CXX" >&6; }
+
+
+
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler supports -c -o file.$ac_objext" >&5
+$as_echo_n "checking if $compiler supports -c -o file.$ac_objext... " >&6; }
+if ${lt_cv_prog_compiler_c_o_CXX+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  lt_cv_prog_compiler_c_o_CXX=no
+   $RM -r conftest 2>/dev/null
+   mkdir conftest
+   cd conftest
+   mkdir out
+   echo "$lt_simple_compile_test_code" > conftest.$ac_ext
+
+   lt_compiler_flag="-o out/conftest2.$ac_objext"
+   # Insert the option either (1) after the last *FLAGS variable, or
+   # (2) before a word containing "conftest.", or (3) at the end.
+   # Note that $ac_compile itself does not contain backslashes and begins
+   # with a dollar sign (not a hyphen), so the echo should work correctly.
+   lt_compile=`echo "$ac_compile" | $SED \
+   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
+   -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
+   -e 's:$: $lt_compiler_flag:'`
+   (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5)
+   (eval "$lt_compile" 2>out/conftest.err)
+   ac_status=$?
+   cat out/conftest.err >&5
+   echo "$as_me:$LINENO: \$? = $ac_status" >&5
+   if (exit $ac_status) && test -s out/conftest2.$ac_objext
+   then
+     # The compiler can only warn and ignore the option if not recognized
+     # So say no if there are warnings
+     $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' > out/conftest.exp
+     $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2
+     if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then
+       lt_cv_prog_compiler_c_o_CXX=yes
+     fi
+   fi
+   chmod u+w . 2>&5
+   $RM conftest*
+   # SGI C++ compiler will create directory out/ii_files/ for
+   # template instantiation
+   test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files
+   $RM out/* && rmdir out
+   cd ..
+   $RM -r conftest
+   $RM conftest*
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_c_o_CXX" >&5
+$as_echo "$lt_cv_prog_compiler_c_o_CXX" >&6; }
+
+
+
+
+hard_links="nottested"
+if test "$lt_cv_prog_compiler_c_o_CXX" = no && test "$need_locks" != no; then
+  # do not overwrite the value of need_locks provided by the user
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if we can lock with hard links" >&5
+$as_echo_n "checking if we can lock with hard links... " >&6; }
+  hard_links=yes
+  $RM conftest*
+  ln conftest.a conftest.b 2>/dev/null && hard_links=no
+  touch conftest.a
+  ln conftest.a conftest.b 2>&5 || hard_links=no
+  ln conftest.a conftest.b 2>/dev/null && hard_links=no
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $hard_links" >&5
+$as_echo "$hard_links" >&6; }
+  if test "$hard_links" = no; then
+    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&5
+$as_echo "$as_me: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&2;}
+    need_locks=warn
+  fi
+else
+  need_locks=no
+fi
+
+
+
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the $compiler linker ($LD) supports shared libraries" >&5
+$as_echo_n "checking whether the $compiler linker ($LD) supports shared libraries... " >&6; }
+
+  export_symbols_cmds_CXX='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
+  exclude_expsyms_CXX='_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*'
+  case $host_os in
+  aix[4-9]*)
+    # If we're using GNU nm, then we don't want the "-C" option.
+    # -C means demangle to AIX nm, but means don't demangle with GNU nm
+    # Also, AIX nm treats weak defined symbols like other global defined
+    # symbols, whereas GNU nm marks them as "W".
+    if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then
+      export_symbols_cmds_CXX='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W")) && (substr(\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
+    else
+      export_symbols_cmds_CXX='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && (substr(\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
+    fi
+    ;;
+  pw32*)
+    export_symbols_cmds_CXX="$ltdll_cmds"
+    ;;
+  cygwin* | mingw* | cegcc*)
+    case $cc_basename in
+    cl*)
+      exclude_expsyms_CXX='_NULL_IMPORT_DESCRIPTOR|_IMPORT_DESCRIPTOR_.*'
+      ;;
+    *)
+      export_symbols_cmds_CXX='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[BCDGRS][ ]/s/.*[ ]\([^ ]*\)/\1 DATA/;s/^.*[ ]__nm__\([^ ]*\)[ ][^ ]*/\1 DATA/;/^I[ ]/d;/^[AITW][ ]/s/.* //'\'' | sort | uniq > $export_symbols'
+      exclude_expsyms_CXX='[_]+GLOBAL_OFFSET_TABLE_|[_]+GLOBAL__[FID]_.*|[_]+head_[A-Za-z0-9_]+_dll|[A-Za-z0-9_]+_dll_iname'
+      ;;
+    esac
+    ;;
+  linux* | k*bsd*-gnu | gnu*)
+    link_all_deplibs_CXX=no
+    ;;
+  *)
+    export_symbols_cmds_CXX='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
+    ;;
+  esac
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ld_shlibs_CXX" >&5
+$as_echo "$ld_shlibs_CXX" >&6; }
+test "$ld_shlibs_CXX" = no && can_build_shared=no
+
+with_gnu_ld_CXX=$with_gnu_ld
+
+
+
+
+
+
+#
+# Do we need to explicitly link libc?
+#
+case "x$archive_cmds_need_lc_CXX" in
+x|xyes)
+  # Assume -lc should be added
+  archive_cmds_need_lc_CXX=yes
+
+  if test "$enable_shared" = yes && test "$GCC" = yes; then
+    case $archive_cmds_CXX in
+    *'~'*)
+      # FIXME: we may have to deal with multi-command sequences.
+      ;;
+    '$CC '*)
+      # Test whether the compiler implicitly links with -lc since on some
+      # systems, -lgcc has to come before -lc. If gcc already passes -lc
+      # to ld, don't add -lc before -lgcc.
+      { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether -lc should be explicitly linked in" >&5
+$as_echo_n "checking whether -lc should be explicitly linked in... " >&6; }
+if ${lt_cv_archive_cmds_need_lc_CXX+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  $RM conftest*
+	echo "$lt_simple_compile_test_code" > conftest.$ac_ext
+
+	if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5
+  (eval $ac_compile) 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; } 2>conftest.err; then
+	  soname=conftest
+	  lib=conftest
+	  libobjs=conftest.$ac_objext
+	  deplibs=
+	  wl=$lt_prog_compiler_wl_CXX
+	  pic_flag=$lt_prog_compiler_pic_CXX
+	  compiler_flags=-v
+	  linker_flags=-v
+	  verstring=
+	  output_objdir=.
+	  libname=conftest
+	  lt_save_allow_undefined_flag=$allow_undefined_flag_CXX
+	  allow_undefined_flag_CXX=
+	  if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$archive_cmds_CXX 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1\""; } >&5
+  (eval $archive_cmds_CXX 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1) 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }
+	  then
+	    lt_cv_archive_cmds_need_lc_CXX=no
+	  else
+	    lt_cv_archive_cmds_need_lc_CXX=yes
+	  fi
+	  allow_undefined_flag_CXX=$lt_save_allow_undefined_flag
+	else
+	  cat conftest.err 1>&5
+	fi
+	$RM conftest*
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_archive_cmds_need_lc_CXX" >&5
+$as_echo "$lt_cv_archive_cmds_need_lc_CXX" >&6; }
+      archive_cmds_need_lc_CXX=$lt_cv_archive_cmds_need_lc_CXX
+      ;;
+    esac
+  fi
+  ;;
+esac
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking dynamic linker characteristics" >&5
+$as_echo_n "checking dynamic linker characteristics... " >&6; }
+
+library_names_spec=
+libname_spec='lib$name'
+soname_spec=
+shrext_cmds=".so"
+postinstall_cmds=
+postuninstall_cmds=
+finish_cmds=
+finish_eval=
+shlibpath_var=
+shlibpath_overrides_runpath=unknown
+version_type=none
+dynamic_linker="$host_os ld.so"
+sys_lib_dlsearch_path_spec="/lib /usr/lib"
+need_lib_prefix=unknown
+hardcode_into_libs=no
+
+# when you set need_version to no, make sure it does not cause -set_version
+# flags to be left without arguments
+need_version=unknown
+
+case $host_os in
+aix3*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a'
+  shlibpath_var=LIBPATH
+
+  # AIX 3 has no versioning support, so we append a major version to the name.
+  soname_spec='${libname}${release}${shared_ext}$major'
+  ;;
+
+aix[4-9]*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_lib_prefix=no
+  need_version=no
+  hardcode_into_libs=yes
+  if test "$host_cpu" = ia64; then
+    # AIX 5 supports IA64
+    library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}'
+    shlibpath_var=LD_LIBRARY_PATH
+  else
+    # With GCC up to 2.95.x, collect2 would create an import file
+    # for dependence libraries.  The import file would start with
+    # the line `#! .'.  This would cause the generated library to
+    # depend on `.', always an invalid library.  This was fixed in
+    # development snapshots of GCC prior to 3.0.
+    case $host_os in
+      aix4 | aix4.[01] | aix4.[01].*)
+      if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)'
+	   echo ' yes '
+	   echo '#endif'; } | ${CC} -E - | $GREP yes > /dev/null; then
+	:
+      else
+	can_build_shared=no
+      fi
+      ;;
+    esac
+    # AIX (on Power*) has no versioning support, so currently we can not hardcode correct
+    # soname into executable. Probably we can add versioning support to
+    # collect2, so additional links can be useful in future.
+    if test "$aix_use_runtimelinking" = yes; then
+      # If using run time linking (on AIX 4.2 or later) use lib<name>.so
+      # instead of lib<name>.a to let people know that these are not
+      # typical AIX shared libraries.
+      library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+    else
+      # We preserve .a as extension for shared libraries through AIX4.2
+      # and later when we are not doing run time linking.
+      library_names_spec='${libname}${release}.a $libname.a'
+      soname_spec='${libname}${release}${shared_ext}$major'
+    fi
+    shlibpath_var=LIBPATH
+  fi
+  ;;
+
+amigaos*)
+  case $host_cpu in
+  powerpc)
+    # Since July 2007 AmigaOS4 officially supports .so libraries.
+    # When compiling the executable, add -use-dynld -Lsobjs: to the compileline.
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+    ;;
+  m68k)
+    library_names_spec='$libname.ixlibrary $libname.a'
+    # Create ${libname}_ixlibrary.a entries in /sys/libs.
+    finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`func_echo_all "$lib" | $SED '\''s%^.*/\([^/]*\)\.ixlibrary$%\1%'\''`; test $RM /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done'
+    ;;
+  esac
+  ;;
+
+beos*)
+  library_names_spec='${libname}${shared_ext}'
+  dynamic_linker="$host_os ld.so"
+  shlibpath_var=LIBRARY_PATH
+  ;;
+
+bsdi[45]*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir'
+  shlibpath_var=LD_LIBRARY_PATH
+  sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib"
+  sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib"
+  # the default ld.so.conf also contains /usr/contrib/lib and
+  # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow
+  # libtool to hard-code these into programs
+  ;;
+
+cygwin* | mingw* | pw32* | cegcc*)
+  version_type=windows
+  shrext_cmds=".dll"
+  need_version=no
+  need_lib_prefix=no
+
+  case $GCC,$cc_basename in
+  yes,*)
+    # gcc
+    library_names_spec='$libname.dll.a'
+    # DLL is installed to $(libdir)/../bin by postinstall_cmds
+    postinstall_cmds='base_file=`basename \${file}`~
+      dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~
+      dldir=$destdir/`dirname \$dlpath`~
+      test -d \$dldir || mkdir -p \$dldir~
+      $install_prog $dir/$dlname \$dldir/$dlname~
+      chmod a+x \$dldir/$dlname~
+      if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then
+        eval '\''$striplib \$dldir/$dlname'\'' || exit \$?;
+      fi'
+    postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~
+      dlpath=$dir/\$dldll~
+       $RM \$dlpath'
+    shlibpath_overrides_runpath=yes
+
+    case $host_os in
+    cygwin*)
+      # Cygwin DLLs use 'cyg' prefix rather than 'lib'
+      soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}'
+
+      ;;
+    mingw* | cegcc*)
+      # MinGW DLLs use traditional 'lib' prefix
+      soname_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}'
+      ;;
+    pw32*)
+      # pw32 DLLs use 'pw' prefix rather than 'lib'
+      library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}'
+      ;;
+    esac
+    dynamic_linker='Win32 ld.exe'
+    ;;
+
+  *,cl*)
+    # Native MSVC
+    libname_spec='$name'
+    soname_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}'
+    library_names_spec='${libname}.dll.lib'
+
+    case $build_os in
+    mingw*)
+      sys_lib_search_path_spec=
+      lt_save_ifs=$IFS
+      IFS=';'
+      for lt_path in $LIB
+      do
+        IFS=$lt_save_ifs
+        # Let DOS variable expansion print the short 8.3 style file name.
+        lt_path=`cd "$lt_path" 2>/dev/null && cmd //C "for %i in (".") do @echo %~si"`
+        sys_lib_search_path_spec="$sys_lib_search_path_spec $lt_path"
+      done
+      IFS=$lt_save_ifs
+      # Convert to MSYS style.
+      sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | sed -e 's|\\\\|/|g' -e 's| \\([a-zA-Z]\\):| /\\1|g' -e 's|^ ||'`
+      ;;
+    cygwin*)
+      # Convert to unix form, then to dos form, then back to unix form
+      # but this time dos style (no spaces!) so that the unix form looks
+      # like /cygdrive/c/PROGRA~1:/cygdr...
+      sys_lib_search_path_spec=`cygpath --path --unix "$LIB"`
+      sys_lib_search_path_spec=`cygpath --path --dos "$sys_lib_search_path_spec" 2>/dev/null`
+      sys_lib_search_path_spec=`cygpath --path --unix "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"`
+      ;;
+    *)
+      sys_lib_search_path_spec="$LIB"
+      if $ECHO "$sys_lib_search_path_spec" | $GREP ';[c-zC-Z]:/' >/dev/null; then
+        # It is most probably a Windows format PATH.
+        sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'`
+      else
+        sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"`
+      fi
+      # FIXME: find the short name or the path components, as spaces are
+      # common. (e.g. "Program Files" -> "PROGRA~1")
+      ;;
+    esac
+
+    # DLL is installed to $(libdir)/../bin by postinstall_cmds
+    postinstall_cmds='base_file=`basename \${file}`~
+      dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~
+      dldir=$destdir/`dirname \$dlpath`~
+      test -d \$dldir || mkdir -p \$dldir~
+      $install_prog $dir/$dlname \$dldir/$dlname'
+    postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~
+      dlpath=$dir/\$dldll~
+       $RM \$dlpath'
+    shlibpath_overrides_runpath=yes
+    dynamic_linker='Win32 link.exe'
+    ;;
+
+  *)
+    # Assume MSVC wrapper
+    library_names_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext} $libname.lib'
+    dynamic_linker='Win32 ld.exe'
+    ;;
+  esac
+  # FIXME: first we should search . and the directory the executable is in
+  shlibpath_var=PATH
+  ;;
+
+darwin* | rhapsody*)
+  dynamic_linker="$host_os dyld"
+  version_type=darwin
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${major}$shared_ext ${libname}$shared_ext'
+  soname_spec='${libname}${release}${major}$shared_ext'
+  shlibpath_overrides_runpath=yes
+  shlibpath_var=DYLD_LIBRARY_PATH
+  shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`'
+
+  sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib'
+  ;;
+
+dgux*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  ;;
+
+freebsd* | dragonfly*)
+  # DragonFly does not have aout.  When/if they implement a new
+  # versioning mechanism, adjust this.
+  if test -x /usr/bin/objformat; then
+    objformat=`/usr/bin/objformat`
+  else
+    case $host_os in
+    freebsd[23].*) objformat=aout ;;
+    *) objformat=elf ;;
+    esac
+  fi
+  version_type=freebsd-$objformat
+  case $version_type in
+    freebsd-elf*)
+      library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
+      need_version=no
+      need_lib_prefix=no
+      ;;
+    freebsd-*)
+      library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix'
+      need_version=yes
+      ;;
+  esac
+  shlibpath_var=LD_LIBRARY_PATH
+  case $host_os in
+  freebsd2.*)
+    shlibpath_overrides_runpath=yes
+    ;;
+  freebsd3.[01]* | freebsdelf3.[01]*)
+    shlibpath_overrides_runpath=yes
+    hardcode_into_libs=yes
+    ;;
+  freebsd3.[2-9]* | freebsdelf3.[2-9]* | \
+  freebsd4.[0-5] | freebsdelf4.[0-5] | freebsd4.1.1 | freebsdelf4.1.1)
+    shlibpath_overrides_runpath=no
+    hardcode_into_libs=yes
+    ;;
+  *) # from 4.6 on, and DragonFly
+    shlibpath_overrides_runpath=yes
+    hardcode_into_libs=yes
+    ;;
+  esac
+  ;;
+
+gnu*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=no
+  hardcode_into_libs=yes
+  ;;
+
+haiku*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_lib_prefix=no
+  need_version=no
+  dynamic_linker="$host_os runtime_loader"
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  sys_lib_dlsearch_path_spec='/boot/home/config/lib /boot/common/lib /boot/system/lib'
+  hardcode_into_libs=yes
+  ;;
+
+hpux9* | hpux10* | hpux11*)
+  # Give a soname corresponding to the major version so that dld.sl refuses to
+  # link against other versions.
+  version_type=sunos
+  need_lib_prefix=no
+  need_version=no
+  case $host_cpu in
+  ia64*)
+    shrext_cmds='.so'
+    hardcode_into_libs=yes
+    dynamic_linker="$host_os dld.so"
+    shlibpath_var=LD_LIBRARY_PATH
+    shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+    soname_spec='${libname}${release}${shared_ext}$major'
+    if test "X$HPUX_IA64_MODE" = X32; then
+      sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib"
+    else
+      sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64"
+    fi
+    sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
+    ;;
+  hppa*64*)
+    shrext_cmds='.sl'
+    hardcode_into_libs=yes
+    dynamic_linker="$host_os dld.sl"
+    shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH
+    shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+    soname_spec='${libname}${release}${shared_ext}$major'
+    sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64"
+    sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
+    ;;
+  *)
+    shrext_cmds='.sl'
+    dynamic_linker="$host_os dld.sl"
+    shlibpath_var=SHLIB_PATH
+    shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+    soname_spec='${libname}${release}${shared_ext}$major'
+    ;;
+  esac
+  # HP-UX runs *really* slowly unless shared libraries are mode 555, ...
+  postinstall_cmds='chmod 555 $lib'
+  # or fails outright, so override atomically:
+  install_override_mode=555
+  ;;
+
+interix[3-9]*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=no
+  hardcode_into_libs=yes
+  ;;
+
+irix5* | irix6* | nonstopux*)
+  case $host_os in
+    nonstopux*) version_type=nonstopux ;;
+    *)
+	if test "$lt_cv_prog_gnu_ld" = yes; then
+		version_type=linux # correct to gnu/linux during the next big refactor
+	else
+		version_type=irix
+	fi ;;
+  esac
+  need_lib_prefix=no
+  need_version=no
+  soname_spec='${libname}${release}${shared_ext}$major'
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}'
+  case $host_os in
+  irix5* | nonstopux*)
+    libsuff= shlibsuff=
+    ;;
+  *)
+    case $LD in # libtool.m4 will add one of these switches to LD
+    *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ")
+      libsuff= shlibsuff= libmagic=32-bit;;
+    *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ")
+      libsuff=32 shlibsuff=N32 libmagic=N32;;
+    *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ")
+      libsuff=64 shlibsuff=64 libmagic=64-bit;;
+    *) libsuff= shlibsuff= libmagic=never-match;;
+    esac
+    ;;
+  esac
+  shlibpath_var=LD_LIBRARY${shlibsuff}_PATH
+  shlibpath_overrides_runpath=no
+  sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}"
+  sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}"
+  hardcode_into_libs=yes
+  ;;
+
+# No shared lib support for Linux oldld, aout, or coff.
+linux*oldld* | linux*aout* | linux*coff*)
+  dynamic_linker=no
+  ;;
+
+# This must be glibc/ELF.
+linux* | k*bsd*-gnu | kopensolaris*-gnu)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=no
+
+  # Some binutils ld are patched to set DT_RUNPATH
+  if ${lt_cv_shlibpath_overrides_runpath+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  lt_cv_shlibpath_overrides_runpath=no
+    save_LDFLAGS=$LDFLAGS
+    save_libdir=$libdir
+    eval "libdir=/foo; wl=\"$lt_prog_compiler_wl_CXX\"; \
+	 LDFLAGS=\"\$LDFLAGS $hardcode_libdir_flag_spec_CXX\""
+    cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_cxx_try_link "$LINENO"; then :
+  if  ($OBJDUMP -p conftest$ac_exeext) 2>/dev/null | grep "RUNPATH.*$libdir" >/dev/null; then :
+  lt_cv_shlibpath_overrides_runpath=yes
+fi
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+    LDFLAGS=$save_LDFLAGS
+    libdir=$save_libdir
+
+fi
+
+  shlibpath_overrides_runpath=$lt_cv_shlibpath_overrides_runpath
+
+  # This implies no fast_install, which is unacceptable.
+  # Some rework will be needed to allow for fast_install
+  # before this can be enabled.
+  hardcode_into_libs=yes
+
+  # Append ld.so.conf contents to the search path
+  if test -f /etc/ld.so.conf; then
+    lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;/^[	 ]*hwcap[	 ]/d;s/[:,	]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;s/"//g;/^$/d' | tr '\n' ' '`
+    sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra"
+  fi
+
+  # We used to test for /lib/ld.so.1 and disable shared libraries on
+  # powerpc, because MkLinux only supported shared libraries with the
+  # GNU dynamic linker.  Since this was broken with cross compilers,
+  # most powerpc-linux boxes support dynamic linking these days and
+  # people can always --disable-shared, the test was removed, and we
+  # assume the GNU/Linux dynamic linker is in use.
+  dynamic_linker='GNU/Linux ld.so'
+  ;;
+
+netbsdelf*-gnu)
+  version_type=linux
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=no
+  hardcode_into_libs=yes
+  dynamic_linker='NetBSD ld.elf_so'
+  ;;
+
+netbsd*)
+  version_type=sunos
+  need_lib_prefix=no
+  need_version=no
+  if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+    finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
+    dynamic_linker='NetBSD (a.out) ld.so'
+  else
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+    soname_spec='${libname}${release}${shared_ext}$major'
+    dynamic_linker='NetBSD ld.elf_so'
+  fi
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  hardcode_into_libs=yes
+  ;;
+
+newsos6)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  ;;
+
+*nto* | *qnx*)
+  version_type=qnx
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=no
+  hardcode_into_libs=yes
+  dynamic_linker='ldqnx.so'
+  ;;
+
+openbsd*)
+  version_type=sunos
+  sys_lib_dlsearch_path_spec="/usr/lib"
+  need_lib_prefix=no
+  # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs.
+  case $host_os in
+    openbsd3.3 | openbsd3.3.*)	need_version=yes ;;
+    *)				need_version=no  ;;
+  esac
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+  finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
+  shlibpath_var=LD_LIBRARY_PATH
+  if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+    case $host_os in
+      openbsd2.[89] | openbsd2.[89].*)
+	shlibpath_overrides_runpath=no
+	;;
+      *)
+	shlibpath_overrides_runpath=yes
+	;;
+      esac
+  else
+    shlibpath_overrides_runpath=yes
+  fi
+  ;;
+
+os2*)
+  libname_spec='$name'
+  shrext_cmds=".dll"
+  need_lib_prefix=no
+  library_names_spec='$libname${shared_ext} $libname.a'
+  dynamic_linker='OS/2 ld.exe'
+  shlibpath_var=LIBPATH
+  ;;
+
+osf3* | osf4* | osf5*)
+  version_type=osf
+  need_lib_prefix=no
+  need_version=no
+  soname_spec='${libname}${release}${shared_ext}$major'
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  shlibpath_var=LD_LIBRARY_PATH
+  sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib"
+  sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec"
+  ;;
+
+rdos*)
+  dynamic_linker=no
+  ;;
+
+solaris*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  hardcode_into_libs=yes
+  # ldd complains unless libraries are executable
+  postinstall_cmds='chmod +x $lib'
+  ;;
+
+sunos4*)
+  version_type=sunos
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+  finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  if test "$with_gnu_ld" = yes; then
+    need_lib_prefix=no
+  fi
+  need_version=yes
+  ;;
+
+sysv4 | sysv4.3*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  case $host_vendor in
+    sni)
+      shlibpath_overrides_runpath=no
+      need_lib_prefix=no
+      runpath_var=LD_RUN_PATH
+      ;;
+    siemens)
+      need_lib_prefix=no
+      ;;
+    motorola)
+      need_lib_prefix=no
+      need_version=no
+      shlibpath_overrides_runpath=no
+      sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib'
+      ;;
+  esac
+  ;;
+
+sysv4*MP*)
+  if test -d /usr/nec ;then
+    version_type=linux # correct to gnu/linux during the next big refactor
+    library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}'
+    soname_spec='$libname${shared_ext}.$major'
+    shlibpath_var=LD_LIBRARY_PATH
+  fi
+  ;;
+
+sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
+  version_type=freebsd-elf
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  hardcode_into_libs=yes
+  if test "$with_gnu_ld" = yes; then
+    sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib'
+  else
+    sys_lib_search_path_spec='/usr/ccs/lib /usr/lib'
+    case $host_os in
+      sco3.2v5*)
+        sys_lib_search_path_spec="$sys_lib_search_path_spec /lib"
+	;;
+    esac
+  fi
+  sys_lib_dlsearch_path_spec='/usr/lib'
+  ;;
+
+tpf*)
+  # TPF is a cross-target only.  Preferred cross-host = GNU/Linux.
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=no
+  hardcode_into_libs=yes
+  ;;
+
+uts4*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  ;;
+
+*)
+  dynamic_linker=no
+  ;;
+esac
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $dynamic_linker" >&5
+$as_echo "$dynamic_linker" >&6; }
+test "$dynamic_linker" = no && can_build_shared=no
+
+variables_saved_for_relink="PATH $shlibpath_var $runpath_var"
+if test "$GCC" = yes; then
+  variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH"
+fi
+
+if test "${lt_cv_sys_lib_search_path_spec+set}" = set; then
+  sys_lib_search_path_spec="$lt_cv_sys_lib_search_path_spec"
+fi
+if test "${lt_cv_sys_lib_dlsearch_path_spec+set}" = set; then
+  sys_lib_dlsearch_path_spec="$lt_cv_sys_lib_dlsearch_path_spec"
+fi
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to hardcode library paths into programs" >&5
+$as_echo_n "checking how to hardcode library paths into programs... " >&6; }
+hardcode_action_CXX=
+if test -n "$hardcode_libdir_flag_spec_CXX" ||
+   test -n "$runpath_var_CXX" ||
+   test "X$hardcode_automatic_CXX" = "Xyes" ; then
+
+  # We can hardcode non-existent directories.
+  if test "$hardcode_direct_CXX" != no &&
+     # If the only mechanism to avoid hardcoding is shlibpath_var, we
+     # have to relink, otherwise we might link with an installed library
+     # when we should be linking with a yet-to-be-installed one
+     ## test "$_LT_TAGVAR(hardcode_shlibpath_var, CXX)" != no &&
+     test "$hardcode_minus_L_CXX" != no; then
+    # Linking always hardcodes the temporary library directory.
+    hardcode_action_CXX=relink
+  else
+    # We can link without hardcoding, and we can hardcode nonexisting dirs.
+    hardcode_action_CXX=immediate
+  fi
+else
+  # We cannot hardcode anything, or else we can only hardcode existing
+  # directories.
+  hardcode_action_CXX=unsupported
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $hardcode_action_CXX" >&5
+$as_echo "$hardcode_action_CXX" >&6; }
+
+if test "$hardcode_action_CXX" = relink ||
+   test "$inherit_rpath_CXX" = yes; then
+  # Fast installation is not supported
+  enable_fast_install=no
+elif test "$shlibpath_overrides_runpath" = yes ||
+     test "$enable_shared" = no; then
+  # Fast installation is not necessary
+  enable_fast_install=needless
+fi
+
+
+
+
+
+
+
+  fi # test -n "$compiler"
+
+  CC=$lt_save_CC
+  CFLAGS=$lt_save_CFLAGS
+  LDCXX=$LD
+  LD=$lt_save_LD
+  GCC=$lt_save_GCC
+  with_gnu_ld=$lt_save_with_gnu_ld
+  lt_cv_path_LDCXX=$lt_cv_path_LD
+  lt_cv_path_LD=$lt_save_path_LD
+  lt_cv_prog_gnu_ldcxx=$lt_cv_prog_gnu_ld
+  lt_cv_prog_gnu_ld=$lt_save_with_gnu_ld
+fi # test "$_lt_caught_CXX_error" != yes
+
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C++ compiler works" >&5
+$as_echo_n "checking whether the C++ compiler works... " >&6; }
+if ${rw_cv_prog_cxx_works+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_ext=cpp
+ac_cpp='$CXXCPP $CPPFLAGS'
+ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
+
+                cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_cxx_try_link "$LINENO"; then :
+
+else
+  as_fn_error $? "$CXX cannot compile" "$LINENO" 5
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+                ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $rw_cv_prog_cxx_works" >&5
+$as_echo "$rw_cv_prog_cxx_works" >&6; }
+
+for ac_prog in flex lex
+do
+  # Extract the first word of "$ac_prog", so it can be a program name with args.
+set dummy $ac_prog; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_LEX+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$LEX"; then
+  ac_cv_prog_LEX="$LEX" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_LEX="$ac_prog"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+fi
+fi
+LEX=$ac_cv_prog_LEX
+if test -n "$LEX"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $LEX" >&5
+$as_echo "$LEX" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+  test -n "$LEX" && break
+done
+test -n "$LEX" || LEX=":"
+
+if test "x$LEX" != "x:"; then
+  cat >conftest.l <<_ACEOF
+%%
+a { ECHO; }
+b { REJECT; }
+c { yymore (); }
+d { yyless (1); }
+e { yyless (input () != 0); }
+f { unput (yytext[0]); }
+. { BEGIN INITIAL; }
+%%
+#ifdef YYTEXT_POINTER
+extern char *yytext;
+#endif
+int
+main (void)
+{
+  return ! yylex () + ! yywrap ();
+}
+_ACEOF
+{ { ac_try="$LEX conftest.l"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$LEX conftest.l") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking lex output file root" >&5
+$as_echo_n "checking lex output file root... " >&6; }
+if ${ac_cv_prog_lex_root+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+
+if test -f lex.yy.c; then
+  ac_cv_prog_lex_root=lex.yy
+elif test -f lexyy.c; then
+  ac_cv_prog_lex_root=lexyy
+else
+  as_fn_error $? "cannot find output from $LEX; giving up" "$LINENO" 5
+fi
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_lex_root" >&5
+$as_echo "$ac_cv_prog_lex_root" >&6; }
+LEX_OUTPUT_ROOT=$ac_cv_prog_lex_root
+
+if test -z "${LEXLIB+set}"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking lex library" >&5
+$as_echo_n "checking lex library... " >&6; }
+if ${ac_cv_lib_lex+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+
+    ac_save_LIBS=$LIBS
+    ac_cv_lib_lex='none needed'
+    for ac_lib in '' -lfl -ll; do
+      LIBS="$ac_lib $ac_save_LIBS"
+      cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+`cat $LEX_OUTPUT_ROOT.c`
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_lex=$ac_lib
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+      test "$ac_cv_lib_lex" != 'none needed' && break
+    done
+    LIBS=$ac_save_LIBS
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_lex" >&5
+$as_echo "$ac_cv_lib_lex" >&6; }
+  test "$ac_cv_lib_lex" != 'none needed' && LEXLIB=$ac_cv_lib_lex
+fi
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether yytext is a pointer" >&5
+$as_echo_n "checking whether yytext is a pointer... " >&6; }
+if ${ac_cv_prog_lex_yytext_pointer+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  # POSIX says lex can declare yytext either as a pointer or an array; the
+# default is implementation-dependent.  Figure out which it is, since
+# not all implementations provide the %pointer and %array declarations.
+ac_cv_prog_lex_yytext_pointer=no
+ac_save_LIBS=$LIBS
+LIBS="$LEXLIB $ac_save_LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+  #define YYTEXT_POINTER 1
+`cat $LEX_OUTPUT_ROOT.c`
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_prog_lex_yytext_pointer=yes
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_save_LIBS
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_lex_yytext_pointer" >&5
+$as_echo "$ac_cv_prog_lex_yytext_pointer" >&6; }
+if test $ac_cv_prog_lex_yytext_pointer = yes; then
+
+$as_echo "#define YYTEXT_POINTER 1" >>confdefs.h
+
+fi
+rm -f conftest.l $LEX_OUTPUT_ROOT.c
+
+fi
+for ac_prog in 'bison -y' byacc
+do
+  # Extract the first word of "$ac_prog", so it can be a program name with args.
+set dummy $ac_prog; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_YACC+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$YACC"; then
+  ac_cv_prog_YACC="$YACC" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_YACC="$ac_prog"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+fi
+fi
+YACC=$ac_cv_prog_YACC
+if test -n "$YACC"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $YACC" >&5
+$as_echo "$YACC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+  test -n "$YACC" && break
+done
+test -n "$YACC" || YACC="yacc"
+
+
+# Find a good install program.  We prefer a C program (faster),
+# so one script is as good as another.  But avoid the broken or
+# incompatible versions:
+# SysV /etc/install, /usr/sbin/install
+# SunOS /usr/etc/install
+# IRIX /sbin/install
+# AIX /bin/install
+# AmigaOS /C/install, which installs bootblocks on floppy discs
+# AIX 4 /usr/bin/installbsd, which doesn't work without a -g flag
+# AFS /usr/afsws/bin/install, which mishandles nonexistent args
+# SVR4 /usr/ucb/install, which tries to use the nonexistent group "staff"
+# OS/2's system install, which has a completely different semantic
+# ./install, which can be erroneously created by make from ./install.sh.
+# Reject install programs that cannot install multiple files.
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for a BSD-compatible install" >&5
+$as_echo_n "checking for a BSD-compatible install... " >&6; }
+if test -z "$INSTALL"; then
+if ${ac_cv_path_install+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    # Account for people who put trailing slashes in PATH elements.
+case $as_dir/ in #((
+  ./ | .// | /[cC]/* | \
+  /etc/* | /usr/sbin/* | /usr/etc/* | /sbin/* | /usr/afsws/bin/* | \
+  ?:[\\/]os2[\\/]install[\\/]* | ?:[\\/]OS2[\\/]INSTALL[\\/]* | \
+  /usr/ucb/* ) ;;
+  *)
+    # OSF1 and SCO ODT 3.0 have their own names for install.
+    # Don't use installbsd from OSF since it installs stuff as root
+    # by default.
+    for ac_prog in ginstall scoinst install; do
+      for ac_exec_ext in '' $ac_executable_extensions; do
+	if { test -f "$as_dir/$ac_prog$ac_exec_ext" && $as_test_x "$as_dir/$ac_prog$ac_exec_ext"; }; then
+	  if test $ac_prog = install &&
+	    grep dspmsg "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then
+	    # AIX install.  It has an incompatible calling convention.
+	    :
+	  elif test $ac_prog = install &&
+	    grep pwplus "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then
+	    # program-specific install script used by HP pwplus--don't use.
+	    :
+	  else
+	    rm -rf conftest.one conftest.two conftest.dir
+	    echo one > conftest.one
+	    echo two > conftest.two
+	    mkdir conftest.dir
+	    if "$as_dir/$ac_prog$ac_exec_ext" -c conftest.one conftest.two "`pwd`/conftest.dir" &&
+	      test -s conftest.one && test -s conftest.two &&
+	      test -s conftest.dir/conftest.one &&
+	      test -s conftest.dir/conftest.two
+	    then
+	      ac_cv_path_install="$as_dir/$ac_prog$ac_exec_ext -c"
+	      break 3
+	    fi
+	  fi
+	fi
+      done
+    done
+    ;;
+esac
+
+  done
+IFS=$as_save_IFS
+
+rm -rf conftest.one conftest.two conftest.dir
+
+fi
+  if test "${ac_cv_path_install+set}" = set; then
+    INSTALL=$ac_cv_path_install
+  else
+    # As a last resort, use the slow shell script.  Don't cache a
+    # value for INSTALL within a source directory, because that will
+    # break other packages using the cache if that directory is
+    # removed, or if the value is a relative name.
+    INSTALL=$ac_install_sh
+  fi
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $INSTALL" >&5
+$as_echo "$INSTALL" >&6; }
+
+# Use test -z because SunOS4 sh mishandles braces in ${var-val}.
+# It thinks the first close brace ends the variable substitution.
+test -z "$INSTALL_PROGRAM" && INSTALL_PROGRAM='${INSTALL}'
+
+test -z "$INSTALL_SCRIPT" && INSTALL_SCRIPT='${INSTALL}'
+
+test -z "$INSTALL_DATA" && INSTALL_DATA='${INSTALL} -m 644'
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for a sed that does not truncate output" >&5
+$as_echo_n "checking for a sed that does not truncate output... " >&6; }
+if ${ac_cv_path_SED+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+            ac_script=s/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/
+     for ac_i in 1 2 3 4 5 6 7; do
+       ac_script="$ac_script$as_nl$ac_script"
+     done
+     echo "$ac_script" 2>/dev/null | sed 99q >conftest.sed
+     { ac_script=; unset ac_script;}
+     if test -z "$SED"; then
+  ac_path_SED_found=false
+  # Loop through the user's path and test for each of PROGNAME-LIST
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_prog in sed gsed; do
+    for ac_exec_ext in '' $ac_executable_extensions; do
+      ac_path_SED="$as_dir/$ac_prog$ac_exec_ext"
+      { test -f "$ac_path_SED" && $as_test_x "$ac_path_SED"; } || continue
+# Check for GNU ac_path_SED and select it if it is found.
+  # Check for GNU $ac_path_SED
+case `"$ac_path_SED" --version 2>&1` in
+*GNU*)
+  ac_cv_path_SED="$ac_path_SED" ac_path_SED_found=:;;
+*)
+  ac_count=0
+  $as_echo_n 0123456789 >"conftest.in"
+  while :
+  do
+    cat "conftest.in" "conftest.in" >"conftest.tmp"
+    mv "conftest.tmp" "conftest.in"
+    cp "conftest.in" "conftest.nl"
+    $as_echo '' >> "conftest.nl"
+    "$ac_path_SED" -f conftest.sed < "conftest.nl" >"conftest.out" 2>/dev/null || break
+    diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break
+    as_fn_arith $ac_count + 1 && ac_count=$as_val
+    if test $ac_count -gt ${ac_path_SED_max-0}; then
+      # Best one so far, save it but keep looking for a better one
+      ac_cv_path_SED="$ac_path_SED"
+      ac_path_SED_max=$ac_count
+    fi
+    # 10*(2^10) chars as input seems more than enough
+    test $ac_count -gt 10 && break
+  done
+  rm -f conftest.in conftest.tmp conftest.nl conftest.out;;
+esac
+
+      $ac_path_SED_found && break 3
+    done
+  done
+  done
+IFS=$as_save_IFS
+  if test -z "$ac_cv_path_SED"; then
+    as_fn_error $? "no acceptable sed could be found in \$PATH" "$LINENO" 5
+  fi
+else
+  ac_cv_path_SED=$SED
+fi
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_SED" >&5
+$as_echo "$ac_cv_path_SED" >&6; }
+ SED="$ac_cv_path_SED"
+  rm -f conftest.sed
+
+
+MS_VERSION=`grep 'MS_VERSION ' mapserver.h | grep '#define' | cut -d\" -f2`
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: MapServer Version from mapserver.h: '$MS_VERSION'" >&5
+$as_echo "MapServer Version from mapserver.h: '$MS_VERSION'" >&6; }
+MS_VERSION="$MS_VERSION"
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for exp in -lm" >&5
+$as_echo_n "checking for exp in -lm... " >&6; }
+if ${ac_cv_lib_m_exp+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-lm  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char exp ();
+int
+main ()
+{
+return exp ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_m_exp=yes
+else
+  ac_cv_lib_m_exp=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_m_exp" >&5
+$as_echo "$ac_cv_lib_m_exp" >&6; }
+if test "x$ac_cv_lib_m_exp" = xyes; then :
+  XTRALIBS="$XTRALIBS -lm"
+fi
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -ldl" >&5
+$as_echo_n "checking for dlopen in -ldl... " >&6; }
+if ${ac_cv_lib_dl_dlopen+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-ldl  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char dlopen ();
+int
+main ()
+{
+return dlopen ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_dl_dlopen=yes
+else
+  ac_cv_lib_dl_dlopen=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dl_dlopen" >&5
+$as_echo "$ac_cv_lib_dl_dlopen" >&6; }
+if test "x$ac_cv_lib_dl_dlopen" = xyes; then :
+  XTRALIBS="$XTRALIBS -ldl"
+fi
+
+XTRALIBS=$XTRALIBS
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for __gxx_personality_v0 in -lstdc++" >&5
+$as_echo_n "checking for __gxx_personality_v0 in -lstdc++... " >&6; }
+if ${ac_cv_lib_stdcpp___gxx_personality_v0+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-lstdc++  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char __gxx_personality_v0 ();
+int
+main ()
+{
+return __gxx_personality_v0 ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_stdcpp___gxx_personality_v0=yes
+else
+  ac_cv_lib_stdcpp___gxx_personality_v0=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_stdcpp___gxx_personality_v0" >&5
+$as_echo "$ac_cv_lib_stdcpp___gxx_personality_v0" >&6; }
+if test "x$ac_cv_lib_stdcpp___gxx_personality_v0" = xyes; then :
+  XTRALIBS="$XTRALIBS -lstdc++"
+fi
+
+XTRALIBS=$XTRALIBS
+
+
+LIBS="$XTRALIBS $LIBS"
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5
+$as_echo_n "checking for ANSI C header files... " >&6; }
+if ${ac_cv_header_stdc+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <stdlib.h>
+#include <stdarg.h>
+#include <string.h>
+#include <float.h>
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_header_stdc=yes
+else
+  ac_cv_header_stdc=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+
+if test $ac_cv_header_stdc = yes; then
+  # SunOS 4.x string.h does not declare mem*, contrary to ANSI.
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <string.h>
+
+_ACEOF
+if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
+  $EGREP "memchr" >/dev/null 2>&1; then :
+
+else
+  ac_cv_header_stdc=no
+fi
+rm -f conftest*
+
+fi
+
+if test $ac_cv_header_stdc = yes; then
+  # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI.
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <stdlib.h>
+
+_ACEOF
+if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
+  $EGREP "free" >/dev/null 2>&1; then :
+
+else
+  ac_cv_header_stdc=no
+fi
+rm -f conftest*
+
+fi
+
+if test $ac_cv_header_stdc = yes; then
+  # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi.
+  if test "$cross_compiling" = yes; then :
+  :
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <ctype.h>
+#include <stdlib.h>
+#if ((' ' & 0x0FF) == 0x020)
+# define ISLOWER(c) ('a' <= (c) && (c) <= 'z')
+# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c))
+#else
+# define ISLOWER(c) \
+		   (('a' <= (c) && (c) <= 'i') \
+		     || ('j' <= (c) && (c) <= 'r') \
+		     || ('s' <= (c) && (c) <= 'z'))
+# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c))
+#endif
+
+#define XOR(e, f) (((e) && !(f)) || (!(e) && (f)))
+int
+main ()
+{
+  int i;
+  for (i = 0; i < 256; i++)
+    if (XOR (islower (i), ISLOWER (i))
+	|| toupper (i) != TOUPPER (i))
+      return 2;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_run "$LINENO"; then :
+
+else
+  ac_cv_header_stdc=no
+fi
+rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
+  conftest.$ac_objext conftest.beam conftest.$ac_ext
+fi
+
+fi
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5
+$as_echo "$ac_cv_header_stdc" >&6; }
+if test $ac_cv_header_stdc = yes; then
+
+$as_echo "#define STDC_HEADERS 1" >>confdefs.h
+
+fi
+
+
+ac_fn_c_check_func "$LINENO" "strcasecmp" "ac_cv_func_strcasecmp"
+if test "x$ac_cv_func_strcasecmp" = xyes; then :
+
+else
+  STRINGS="-DNEED_STRCASECMP $STRINGS"
+fi
+
+ac_fn_c_check_func "$LINENO" "strncasecmp" "ac_cv_func_strncasecmp"
+if test "x$ac_cv_func_strncasecmp" = xyes; then :
+
+else
+  STRINGS="-DNEED_STRNCASECMP $STRINGS"
+fi
+
+ac_fn_c_check_func "$LINENO" "strdup" "ac_cv_func_strdup"
+if test "x$ac_cv_func_strdup" = xyes; then :
+
+else
+  STRINGS="-DNEED_STRDUP $STRINGS"
+fi
+
+ac_fn_c_check_func "$LINENO" "strrstr" "ac_cv_func_strrstr"
+if test "x$ac_cv_func_strrstr" = xyes; then :
+
+else
+  STRINGS="-DNEED_STRRSTR $STRINGS"
+fi
+
+ac_fn_c_check_func "$LINENO" "strcasestr" "ac_cv_func_strcasestr"
+if test "x$ac_cv_func_strcasestr" = xyes; then :
+
+else
+  STRINGS="-DNEED_STRCASESTR $STRINGS"
+fi
+
+ac_fn_c_check_func "$LINENO" "strlcat" "ac_cv_func_strlcat"
+if test "x$ac_cv_func_strlcat" = xyes; then :
+
+else
+  STRINGS="-DNEED_STRLCAT $STRINGS"
+fi
+
+ac_fn_c_check_func "$LINENO" "strlcpy" "ac_cv_func_strlcpy"
+if test "x$ac_cv_func_strlcpy" = xyes; then :
+
+else
+  STRINGS="-DNEED_STRLCPY $STRINGS"
+fi
+
+ac_fn_c_check_func "$LINENO" "vsnprintf" "ac_cv_func_vsnprintf"
+if test "x$ac_cv_func_vsnprintf" = xyes; then :
+  STRINGS="-DHAVE_VSNPRINTF $STRINGS"
+fi
+
+STRINGS=$STRINGS
+
+ALL_ENABLED="$STRINGS $ALL_ENABLED"
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if pkg-config path is provided" >&5
+$as_echo_n "checking if pkg-config path is provided... " >&6; }
+
+
+# Check whether --with-pkg-config was given.
+if test "${with_pkg_config+set}" = set; then :
+  withval=$with_pkg_config;
+fi
+
+
+if test -n "$with_pkg_config" -a "$with_pkg_config" != "no" ; then
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+
+  PKG_CONFIG=$with_pkg_config
+else
+  PKG_CONFIG="yes"
+fi
+
+if test "$PKG_CONFIG" = "yes" ; then
+
+   # Extract the first word of "pkg-config", so it can be a program name with args.
+set dummy pkg-config; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_path_PKG_CONFIG+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  case $PKG_CONFIG in
+  [\\/]* | ?:[\\/]*)
+  ac_cv_path_PKG_CONFIG="$PKG_CONFIG" # Let the user override the test with a path.
+  ;;
+  *)
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_path_PKG_CONFIG="$as_dir/$ac_word$ac_exec_ext"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+  test -z "$ac_cv_path_PKG_CONFIG" && ac_cv_path_PKG_CONFIG="no"
+  ;;
+esac
+fi
+PKG_CONFIG=$ac_cv_path_PKG_CONFIG
+if test -n "$PKG_CONFIG"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $PKG_CONFIG" >&5
+$as_echo "$PKG_CONFIG" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+
+   if test "$PKG_CONFIG" = "no" ; then
+      { $as_echo "$as_me:${as_lineno-$LINENO}: result: couldn't find pkg-config in default path. Please specify full path to pkg-config if needed" >&5
+$as_echo "couldn't find pkg-config in default path. Please specify full path to pkg-config if needed" >&6; }
+   fi
+
+elif test -f "$PKG_CONFIG" -a -x "$PKG_CONFIG" ; then
+     { $as_echo "$as_me:${as_lineno-$LINENO}: result: user supplied pkg-config ($PKG_CONFIG)" >&5
+$as_echo "user supplied pkg-config ($PKG_CONFIG)" >&6; }
+else
+     as_fn_error $? "'$PKG_CONFIG' is not an executable.  Make sure you use --with-pkg-config=/path/to/pkg-config" "$LINENO" 5
+fi
+
+
+
+unset ac_cv_lib_freetype_FT_Init_FreeType
+unset ac_cv_lib_ttf_TT_Init_FreeType
+
+
+# Check whether --with-freetype was given.
+if test "${with_freetype+set}" = set; then :
+  withval=$with_freetype; FT_DIR=$withval
+else
+  FT_DIR=''
+fi
+
+
+FT_LDFLAGS=''
+FT_CFLAGS=''
+FT_BIN=''
+
+if test "x$FT_DIR" = "xno" ; then
+    as_fn_error $? "Freetype support disabled but is now mandatory. Rerun without --without-freetype or --with-freetype=no" "$LINENO" 5
+fi
+
+
+if test -z "$FT_DIR" -o "$FT_DIR" = "yes" ; then
+        # Extract the first word of "freetype-config", so it can be a program name with args.
+set dummy freetype-config; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_path_FT_BIN+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  case $FT_BIN in
+  [\\/]* | ?:[\\/]*)
+  ac_cv_path_FT_BIN="$FT_BIN" # Let the user override the test with a path.
+  ;;
+  *)
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_path_FT_BIN="$as_dir/$ac_word$ac_exec_ext"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+  test -z "$ac_cv_path_FT_BIN" && ac_cv_path_FT_BIN=""""
+  ;;
+esac
+fi
+FT_BIN=$ac_cv_path_FT_BIN
+if test -n "$FT_BIN"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $FT_BIN" >&5
+$as_echo "$FT_BIN" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+    if test "x$FT_BIN" = "xno" ; then
+                { $as_echo "$as_me:${as_lineno-$LINENO}: checking for Freetype2.x in system locations" >&5
+$as_echo_n "checking for Freetype2.x in system locations... " >&6; }
+        test -f /usr/include/ft2build.h -a -d /usr/include/freetype2 && FT_CFLAGS=-I/usr/include/freetype2
+        test -f /usr/local/include/ft2build.h -a -d /usr/local/include/freetype2 && FT_CFLAGS=-I/usr/local/include -I/usr/local/include/freetype2
+        FT_LDFLAGS="-lfreetype -lz"
+        fi
+else
+
+  if test -z "$FT_DIR" || echo "$FT_DIR" | grep '^/' >/dev/null ; then
+    FT_DIR="$FT_DIR"
+  else
+    FT_DIR="`pwd`/$FT_DIR"
+  fi
+
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for Freetype2.x in $FT_DIR" >&5
+$as_echo_n "checking for Freetype2.x in $FT_DIR... " >&6; }
+    test -x "$FT_DIR" -a "freetype-config" = "`basename $FT_DIR ''`" && FT_BIN="$FT_DIR"
+    test -x "$FT_DIR/freetype-config" && FT_BIN="$FT_DIR/freetype-config"
+    test -x "$FT_DIR/bin/freetype-config" && FT_BIN="$FT_DIR/bin/freetype-config"
+    if test "x$FT_BIN" = "x"; then
+        test -f $FT_DIR/ft2build.h -a -d $FT_DIR/freetype2 && FT_CFLAGS="-I$FT_DIR -I$FT_DIR/freetype2"
+        test -f $FT_DIR/include/ft2build.h -a -d $FT_DIR/include/freetype2 && FT_CFLAGS="-I$FT_DIR/include -I$FT_DIR/include/freetype2"
+        test -f $FT_DIR/lib/libfreetype.a -o -f $FT_DIR/lib/libfreetype.so -o -f $FT_DIR/lib/libfreetype.sl -o -f $FT_DIR/lib/libfreetype.dylib && FT_LDFLAGS="-L$FT_DIR/lib"
+        test -f $FT_DIR/lib64/libfreetype.a -o -f $FT_DIR/lib64/libfreetype.so -o -f $FT_DIR/lib64/libfreetype.sl && FT_LDFLAGS="-L$FT_DIR/lib64"
+        test -f $FT_DIR/libfreetype.a -o -f $FT_DIR/libfreetype.so -o -f $FT_DIR/libfreetype.sl -o -f $FT_DIR/libfreetype.dylib && FT_LDFLAGS="-L$FT_DIR"
+        fi
+fi
+
+if test "x$FT_BIN" != "x" ; then
+        FT_LDFLAGS=`$FT_BIN --libs`
+        FT_CFLAGS=`$FT_BIN --cflags`
+fi
+
+
+_cppflags="$CPPFLAGS"
+_ldflags="$LDFLAGS"
+_libs="$LIBS"
+CPPFLAGS="$FT_CFLAGS $CPPFLAGS"
+LDFLAGS="$FT_LDFLAGS $LDFLAGS"
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for FT_Init_FreeType in -lfreetype" >&5
+$as_echo_n "checking for FT_Init_FreeType in -lfreetype... " >&6; }
+if ${ac_cv_lib_freetype_FT_Init_FreeType+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-lfreetype  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char FT_Init_FreeType ();
+int
+main ()
+{
+return FT_Init_FreeType ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_freetype_FT_Init_FreeType=yes
+else
+  ac_cv_lib_freetype_FT_Init_FreeType=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_freetype_FT_Init_FreeType" >&5
+$as_echo "$ac_cv_lib_freetype_FT_Init_FreeType" >&6; }
+if test "x$ac_cv_lib_freetype_FT_Init_FreeType" = xyes; then :
+  :
+else
+  as_fn_error $? "unable to link - reconfigure with correct --with-freetype=dir " "$LINENO" 5
+fi
+
+
+for ac_header in ft2build.h
+do :
+  ac_fn_c_check_header_mongrel "$LINENO" "ft2build.h" "ac_cv_header_ft2build_h" "$ac_includes_default"
+if test "x$ac_cv_header_ft2build_h" = xyes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_FT2BUILD_H 1
+_ACEOF
+ :
+else
+  as_fn_error $? "ft2build.h header not found - reconfigure with correct --with-freetype=dir " "$LINENO" 5
+fi
+
+done
+
+
+CPPFLAGS=$_cppflags
+LDFLAGS=$_ldflags
+LIBS=$_libs
+FT_ENABLED="-DUSE_FREETYPE"
+FT_ENABLED=$FT_ENABLED
+
+FT_INC=$FT_CFLAGS
+
+FT_LIB=$FT_LDFLAGS
+
+ALL_ENABLED="$FT_ENABLED $ALL_ENABLED"
+ALL_INC="$FT_CFLAGS $ALL_INC"
+ALL_LIB="$FT_LDFLAGS $ALL_LIB"
+
+
+
+
+
+
+
+
+
+
+
+# Check whether --with-png was given.
+if test "${with_png+set}" = set; then :
+  withval=$with_png;
+else
+  with_png=yes
+fi
+
+   if test x"$with_png" == "xno"; then
+      as_fn_error $? "png support cannot be disabled" "$LINENO" 5
+   fi
+
+   if test -z "$with_png" -o "$with_png" == "yes" -o "$with_png" == "/usr"; then
+      ac_fn_c_check_header_mongrel "$LINENO" "png.h" "ac_cv_header_png_h" "$ac_includes_default"
+if test "x$ac_cv_header_png_h" = xyes; then :
+  :
+else
+  as_fn_error $? "png.h header not found. install png development package, or reconfigure with --with-png=/path/to/png/prefix" "$LINENO" 5
+fi
+
+
+      ac_fn_c_check_header_mongrel "$LINENO" "setjmp.h" "ac_cv_header_setjmp_h" "$ac_includes_default"
+if test "x$ac_cv_header_setjmp_h" = xyes; then :
+  :
+else
+  as_fn_error $? "setjmp.h header not found. install png development package, or reconfigure with --with-png=/path/to/png/prefix" "$LINENO" 5
+fi
+
+
+      { $as_echo "$as_me:${as_lineno-$LINENO}: checking for png_init_io in -lpng" >&5
+$as_echo_n "checking for png_init_io in -lpng... " >&6; }
+if ${ac_cv_lib_png_png_init_io+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-lpng  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char png_init_io ();
+int
+main ()
+{
+return png_init_io ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_png_png_init_io=yes
+else
+  ac_cv_lib_png_png_init_io=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_png_png_init_io" >&5
+$as_echo "$ac_cv_lib_png_png_init_io" >&6; }
+if test "x$ac_cv_lib_png_png_init_io" = xyes; then :
+  :
+else
+  as_fn_error $? "libpng library not found. install png development package, or reconfigure with --with-png=/path/to/png/prefix" "$LINENO" 5
+fi
+
+
+   else
+      old_LDFLAGS="$LDFLAGS"
+      old_CPPFLAGS="$CPPFLAGS"
+
+      CPPFLAGS="-I$with_png/include"
+      LDFLAGS="-L$with_png/lib"
+
+      ac_fn_c_check_header_mongrel "$LINENO" "png.h" "ac_cv_header_png_h" "$ac_includes_default"
+if test "x$ac_cv_header_png_h" = xyes; then :
+  :
+else
+  as_fn_error $? "png.h header not found in $with_png. install png development package, or reconfigure with --with-png=/path/to/png/prefix" "$LINENO" 5
+fi
+
+
+      ac_fn_c_check_header_mongrel "$LINENO" "setjmp.h" "ac_cv_header_setjmp_h" "$ac_includes_default"
+if test "x$ac_cv_header_setjmp_h" = xyes; then :
+  :
+else
+  as_fn_error $? "setjmp.h header not found. install png development package, or reconfigure with --with-png=/path/to/png/prefix" "$LINENO" 5
+fi
+
+
+      { $as_echo "$as_me:${as_lineno-$LINENO}: checking for png_init_io in -lpng" >&5
+$as_echo_n "checking for png_init_io in -lpng... " >&6; }
+if ${ac_cv_lib_png_png_init_io+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-lpng  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char png_init_io ();
+int
+main ()
+{
+return png_init_io ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_png_png_init_io=yes
+else
+  ac_cv_lib_png_png_init_io=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_png_png_init_io" >&5
+$as_echo "$ac_cv_lib_png_png_init_io" >&6; }
+if test "x$ac_cv_lib_png_png_init_io" = xyes; then :
+  :
+else
+  as_fn_error $? "libpng library not found in $with_png. install png development package, or reconfigure with --with-png=/path/to/png/prefix" "$LINENO" 5
+fi
+
+      PNG_INC="$CPPFLAGS"
+      PNG_LIB="$LDFLAGS"
+      CPPFLAGS="$old_CPPFLAGS"
+      LDFLAGS="$old_LDFLAGS"
+   fi
+   PNG_ENABLED="-DUSE_PNG"
+
+   ALL_ENABLED="$PNG_ENABLED $ALL_ENABLED"
+   ALL_INC="$ALL_INC $PNG_INC"
+   ALL_LIB="$ALL_LIB $PNG_LIB -lpng"
+   PNG_ENABLED="$PNG_ENABLED"
+
+   PNG_INC="$PNG_INC"
+
+   PNG_LIB="$PNG_LIB -lpng"
+
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we should include GIF support" >&5
+$as_echo_n "checking whether we should include GIF support... " >&6; }
+
+
+
+
+# Check whether --with-gif was given.
+if test "${with_gif+set}" = set; then :
+  withval=$with_gif;
+else
+  with_gif=yes
+fi
+
+   if test x"$with_gif" == "xno"; then
+      GIF_ENABLED=""
+
+      GIF_INC=""
+
+      GIF_LIB=""
+
+      { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+   else
+      { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+      if test -z "$with_gif" -o "$with_gif" == "yes" -o "$with_gif" == "/usr"; then
+         ac_fn_c_check_header_mongrel "$LINENO" "gif_lib.h" "ac_cv_header_gif_lib_h" "$ac_includes_default"
+if test "x$ac_cv_header_gif_lib_h" = xyes; then :
+  :
+else
+  as_fn_error $? "gif_lib.h header not found. install gif development package, or reconfigure with --with-gif=/path/to/gif/prefix" "$LINENO" 5
+fi
+
+
+         { $as_echo "$as_me:${as_lineno-$LINENO}: checking for DGifOpenFileHandle in -lgif" >&5
+$as_echo_n "checking for DGifOpenFileHandle in -lgif... " >&6; }
+if ${ac_cv_lib_gif_DGifOpenFileHandle+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-lgif  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char DGifOpenFileHandle ();
+int
+main ()
+{
+return DGifOpenFileHandle ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_gif_DGifOpenFileHandle=yes
+else
+  ac_cv_lib_gif_DGifOpenFileHandle=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_gif_DGifOpenFileHandle" >&5
+$as_echo "$ac_cv_lib_gif_DGifOpenFileHandle" >&6; }
+if test "x$ac_cv_lib_gif_DGifOpenFileHandle" = xyes; then :
+  :
+else
+  as_fn_error $? "libgif library not found. install gif development package, or reconfigure with --with-gif=/path/to/gif/prefix" "$LINENO" 5
+fi
+
+
+      else
+         old_LDFLAGS="$LDFLAGS"
+         old_CPPFLAGS="$CPPFLAGS"
+
+         CPPFLAGS="-I$with_gif/include"
+         LDFLAGS="-L$with_gif/lib"
+
+         ac_fn_c_check_header_mongrel "$LINENO" "gif_lib.h" "ac_cv_header_gif_lib_h" "$ac_includes_default"
+if test "x$ac_cv_header_gif_lib_h" = xyes; then :
+  :
+else
+  as_fn_error $? "gif_lib.h header not found in $with_gif. install gif development package, or reconfigure with --with-gif=/path/to/gif/prefix" "$LINENO" 5
+fi
+
+
+         { $as_echo "$as_me:${as_lineno-$LINENO}: checking for DGifOpenFileHandle in -lgif" >&5
+$as_echo_n "checking for DGifOpenFileHandle in -lgif... " >&6; }
+if ${ac_cv_lib_gif_DGifOpenFileHandle+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-lgif  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char DGifOpenFileHandle ();
+int
+main ()
+{
+return DGifOpenFileHandle ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_gif_DGifOpenFileHandle=yes
+else
+  ac_cv_lib_gif_DGifOpenFileHandle=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_gif_DGifOpenFileHandle" >&5
+$as_echo "$ac_cv_lib_gif_DGifOpenFileHandle" >&6; }
+if test "x$ac_cv_lib_gif_DGifOpenFileHandle" = xyes; then :
+  :
+else
+  as_fn_error $? "libgif library not found in $with_gif. install gif development package, or reconfigure with --with-gif=/path/to/gif/prefix" "$LINENO" 5
+fi
+
+         GIF_INC="$CPPFLAGS"
+         GIF_LIB="$LDFLAGS"
+         CPPFLAGS="$old_CPPFLAGS"
+         LDFLAGS="$old_LDFLAGS"
+      fi
+      GIF_ENABLED="-DUSE_GIF"
+
+      ALL_ENABLED="$GIF_ENABLED $ALL_ENABLED"
+      ALL_INC="$ALL_INC $GIF_INC"
+      ALL_LIB="$ALL_LIB $GIF_LIB -lgif"
+      GIF_ENABLED="$GIF_ENABLED"
+
+      GIF_INC="$GIF_INC"
+
+      GIF_LIB="$GIF_LIB -lgif"
+
+   fi
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for jpeg library location (mandatory)..." >&5
+$as_echo "$as_me: checking for jpeg library location (mandatory)..." >&6;}
+
+
+# Check whether --with-jpeg was given.
+if test "${with_jpeg+set}" = set; then :
+  withval=$with_jpeg;
+else
+  with_jpeg=yes
+fi
+
+   if test x"$with_jpeg" == "xno"; then
+      as_fn_error $? "jpeg support cannot be disabled" "$LINENO" 5
+   fi
+
+   if test -z "$with_jpeg" -o "$with_jpeg" == "yes" -o "$with_jpeg" == "/usr"; then
+      ac_fn_c_check_header_mongrel "$LINENO" "jpeglib.h" "ac_cv_header_jpeglib_h" "$ac_includes_default"
+if test "x$ac_cv_header_jpeglib_h" = xyes; then :
+  :
+else
+  as_fn_error $? "jpeglib.h header not found. install jpeg development package, or reconfigure with --with-jpeg=/path/to/jpeg/prefix" "$LINENO" 5
+fi
+
+
+      { $as_echo "$as_me:${as_lineno-$LINENO}: checking for jpeg_read_header in -ljpeg" >&5
+$as_echo_n "checking for jpeg_read_header in -ljpeg... " >&6; }
+if ${ac_cv_lib_jpeg_jpeg_read_header+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-ljpeg  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char jpeg_read_header ();
+int
+main ()
+{
+return jpeg_read_header ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_jpeg_jpeg_read_header=yes
+else
+  ac_cv_lib_jpeg_jpeg_read_header=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_jpeg_jpeg_read_header" >&5
+$as_echo "$ac_cv_lib_jpeg_jpeg_read_header" >&6; }
+if test "x$ac_cv_lib_jpeg_jpeg_read_header" = xyes; then :
+  :
+else
+  as_fn_error $? "libjpeg library not found. install jpeg development package, or reconfigure with --with-jpeg=/path/to/jpeg/prefix" "$LINENO" 5
+fi
+
+
+   else
+      old_LDFLAGS="$LDFLAGS"
+      old_CPPFLAGS="$CPPFLAGS"
+
+      CPPFLAGS="-I$with_jpeg/include"
+      LDFLAGS="-L$with_jpeg/lib"
+
+      ac_fn_c_check_header_mongrel "$LINENO" "jpeglib.h" "ac_cv_header_jpeglib_h" "$ac_includes_default"
+if test "x$ac_cv_header_jpeglib_h" = xyes; then :
+  :
+else
+  as_fn_error $? "jpeglib.h header not found in $with_jpeg. install jpeg development package, or reconfigure with --with-jpeg=/path/to/jpeg/prefix" "$LINENO" 5
+fi
+
+
+      { $as_echo "$as_me:${as_lineno-$LINENO}: checking for jpeg_read_header in -ljpeg" >&5
+$as_echo_n "checking for jpeg_read_header in -ljpeg... " >&6; }
+if ${ac_cv_lib_jpeg_jpeg_read_header+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-ljpeg  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char jpeg_read_header ();
+int
+main ()
+{
+return jpeg_read_header ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_jpeg_jpeg_read_header=yes
+else
+  ac_cv_lib_jpeg_jpeg_read_header=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_jpeg_jpeg_read_header" >&5
+$as_echo "$ac_cv_lib_jpeg_jpeg_read_header" >&6; }
+if test "x$ac_cv_lib_jpeg_jpeg_read_header" = xyes; then :
+  :
+else
+  as_fn_error $? "libjpeg library not found in $with_jpeg. install jpeg development package, or reconfigure with --with-jpeg=/path/to/jpeg/prefix" "$LINENO" 5
+fi
+
+      JPEG_INC="$CPPFLAGS"
+      JPEG_LIB="$LDFLAGS"
+      CPPFLAGS="$old_CPPFLAGS"
+      LDFLAGS="$old_LDFLAGS"
+   fi
+   JPEG_ENABLED="-DUSE_JPEG"
+
+   ALL_ENABLED="$JPEG_ENABLED $ALL_ENABLED"
+   ALL_INC="$ALL_INC $JPEG_INC"
+   ALL_LIB="$ALL_LIB $JPEG_LIB -ljpeg"
+   JPEG_ENABLED="$JPEG_ENABLED"
+
+   JPEG_INC="$JPEG_INC"
+
+   JPEG_LIB="$JPEG_LIB -ljpeg"
+
+
+
+
+
+
+unset ac_cv_lib_iconv_libiconv_open
+unset ac_cv_lib_iconv_iconv_open
+unset ac_cv_lib_c_iconv_open
+
+
+# Check whether --with-libiconv was given.
+if test "${with_libiconv+set}" = set; then :
+  withval=$with_libiconv; ICONV_DIR=$withval
+else
+  ICONV_DIR=''
+fi
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking where libiconv is installed..." >&5
+$as_echo "$as_me: checking where libiconv is installed..." >&6;}
+
+ICONV_LIB=''
+
+if test -n "$ICONV_DIR" -a "$ICONV_DIR" != "yes" ; then
+
+
+  if test -z "$ICONV_DIR" || echo "$ICONV_DIR" | grep '^/' >/dev/null ; then
+    ICONV_DIR="$ICONV_DIR"
+  else
+    ICONV_DIR="`pwd`/$ICONV_DIR"
+  fi
+
+
+  test -f $ICONV_DIR/include/iconv.h && ICONV_LIBDIR="$ICONV_DIR/lib" && ICONV_INCDIR="$ICONV_DIR/include"
+  test -f $ICONV_DIR/lib/libiconv.a -o -f $ICONV_DIR/lib/libiconv.so -o -f $ICONV_DIR/lib/libiconv.sl -o -f $ICONV_DIR/lib/libiconv.dylib && ICONV_LIBDIR="$ICONV_DIR/lib" && ICONV_INCDIR="$ICONV_DIR/include"
+  test -f $ICONV_DIR/lib64/libiconv.a -o -f $ICONV_DIR/lib64/libiconv.so -o -f $ICONV_DIR/lib64/libiconv.sl && ICONV_LIBDIR="$ICONV_DIR/lib64" && ICONV_INCDIR="$ICONV_DIR/include"
+
+            { $as_echo "$as_me:${as_lineno-$LINENO}: checking for iconv_open in -lc" >&5
+$as_echo_n "checking for iconv_open in -lc... " >&6; }
+if ${ac_cv_lib_c_iconv_open+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-lc "-L$ICONV_LIBDIR" $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char iconv_open ();
+int
+main ()
+{
+return iconv_open ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_c_iconv_open=yes
+else
+  ac_cv_lib_c_iconv_open=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_c_iconv_open" >&5
+$as_echo "$ac_cv_lib_c_iconv_open" >&6; }
+if test "x$ac_cv_lib_c_iconv_open" = xyes; then :
+  ICONV_LIB="-L$ICONV_LIBDIR -lc"
+fi
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for libiconv_open in -liconv" >&5
+$as_echo_n "checking for libiconv_open in -liconv... " >&6; }
+if ${ac_cv_lib_iconv_libiconv_open+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-liconv "-L$ICONV_LIBDIR" $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char libiconv_open ();
+int
+main ()
+{
+return libiconv_open ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_iconv_libiconv_open=yes
+else
+  ac_cv_lib_iconv_libiconv_open=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_iconv_libiconv_open" >&5
+$as_echo "$ac_cv_lib_iconv_libiconv_open" >&6; }
+if test "x$ac_cv_lib_iconv_libiconv_open" = xyes; then :
+  ICONV_LIB="-L$ICONV_LIBDIR -liconv"
+fi
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for iconv_open in -liconv" >&5
+$as_echo_n "checking for iconv_open in -liconv... " >&6; }
+if ${ac_cv_lib_iconv_iconv_open+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-liconv "-L$ICONV_LIBDIR" $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char iconv_open ();
+int
+main ()
+{
+return iconv_open ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_iconv_iconv_open=yes
+else
+  ac_cv_lib_iconv_iconv_open=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_iconv_iconv_open" >&5
+$as_echo "$ac_cv_lib_iconv_iconv_open" >&6; }
+if test "x$ac_cv_lib_iconv_iconv_open" = xyes; then :
+  ICONV_LIB="-L$ICONV_LIBDIR -liconv"
+fi
+
+
+fi
+
+if test -n "$ICONV_LIB" ; then
+  if test -n "$ICONV_INCDIR"; then
+     ICONV_INC="-I$ICONV_INCDIR"
+  fi
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result:         using libiconv from $ICONV_LIB" >&5
+$as_echo "        using libiconv from $ICONV_LIB" >&6; }
+
+  if test ""$ICONV_DIR"" != "/usr/lib"; then
+
+  if test -z ""$ICONV_DIR"" || echo ""$ICONV_DIR"" | grep '^/' >/dev/null ; then
+    ai_p=""$ICONV_DIR""
+  else
+    ai_p="`pwd`/"$ICONV_DIR""
+  fi
+
+
+  unique=`echo $ac_n "$ai_p$ac_c" | tr -c -d a-zA-Z0-9`
+  cmd="echo $ac_n \"\$LIBPATH$unique$ac_c\""
+  if test -n "$unique" && test "`eval $cmd`" = "" ; then
+    eval "LIBPATH$unique=set"
+
+      EXTRA_LIBS="$EXTRA_LIBS -L$ai_p"
+        RPATHS="$RPATHS ${ld_runpath_switch}$ai_p"
+
+  fi
+
+  fi
+
+
+else
+
+
+  unset ac_cv_lib_iconv_libiconv_open
+  unset ac_cv_lib_c_iconv_open
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for iconv_open in -lc" >&5
+$as_echo_n "checking for iconv_open in -lc... " >&6; }
+if ${ac_cv_lib_c_iconv_open+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-lc  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char iconv_open ();
+int
+main ()
+{
+return iconv_open ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_c_iconv_open=yes
+else
+  ac_cv_lib_c_iconv_open=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_c_iconv_open" >&5
+$as_echo "$ac_cv_lib_c_iconv_open" >&6; }
+if test "x$ac_cv_lib_c_iconv_open" = xyes; then :
+  ICONV_LIB="-lc"
+fi
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for libiconv_open in -liconv" >&5
+$as_echo_n "checking for libiconv_open in -liconv... " >&6; }
+if ${ac_cv_lib_iconv_libiconv_open+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-liconv  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
 extern "C"
 #endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char gdImageJpeg ();
+char libiconv_open ();
 int
 main ()
 {
-gdImageJpeg ();
+return libiconv_open ();
   ;
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  eval "$as_ac_Lib=yes"
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_iconv_libiconv_open=yes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-eval "$as_ac_Lib=no"
+  ac_cv_lib_iconv_libiconv_open=no
 fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 LIBS=$ac_check_lib_save_LIBS
 fi
-echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Lib'}'`" >&5
-echo "${ECHO_T}`eval echo '${'$as_ac_Lib'}'`" >&6
-if test `eval echo '${'$as_ac_Lib'}'` = yes; then
-  GD_DEF="$GD_DEF -DUSE_GD_JPEG"
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_iconv_libiconv_open" >&5
+$as_echo "$ac_cv_lib_iconv_libiconv_open" >&6; }
+if test "x$ac_cv_lib_iconv_libiconv_open" = xyes; then :
+  ICONV_LIB="-liconv"
 fi
 
-  as_ac_Lib=`echo "ac_cv_lib_$GD_CHECKLIB''_gdImageWBMP" | $as_tr_sh`
-echo "$as_me:$LINENO: checking for gdImageWBMP in -l$GD_CHECKLIB" >&5
-echo $ECHO_N "checking for gdImageWBMP in -l$GD_CHECKLIB... $ECHO_C" >&6
-if eval "test \"\${$as_ac_Lib+set}\" = set"; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for iconv_open in -liconv" >&5
+$as_echo_n "checking for iconv_open in -liconv... " >&6; }
+if ${ac_cv_lib_iconv_iconv_open+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
   ac_check_lib_save_LIBS=$LIBS
-LIBS="-l$GD_CHECKLIB $GD_STATIC $GD_LIB $GD_XTRA_LIBS $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+LIBS="-liconv  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
-/* Override any gcc2 internal prototype to avoid an error.  */
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
 #ifdef __cplusplus
 extern "C"
 #endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char gdImageWBMP ();
+char iconv_open ();
 int
 main ()
 {
-gdImageWBMP ();
+return iconv_open ();
   ;
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  eval "$as_ac_Lib=yes"
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_iconv_iconv_open=yes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
+  ac_cv_lib_iconv_iconv_open=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_iconv_iconv_open" >&5
+$as_echo "$ac_cv_lib_iconv_iconv_open" >&6; }
+if test "x$ac_cv_lib_iconv_iconv_open" = xyes; then :
+  ICONV_LIB="-liconv"
+fi
+
+
+  if test -n "$ICONV_LIB" ; then
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result:         using libiconv from system libs." >&5
+$as_echo "        using libiconv from system libs." >&6; }
+  else
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result:         libiconv library cannot be found, possibly needed for GD" >&5
+$as_echo "        libiconv library cannot be found, possibly needed for GD" >&6; }
+  fi
+
+fi
+
+if test -n "$ICONV_LIB" ; then
+  ICONV_ENABLED="-DUSE_ICONV"
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result:         libiconv found. Enabling internationalization ($ICONV_ENABLED)" >&5
+$as_echo "        libiconv found. Enabling internationalization ($ICONV_ENABLED)" >&6; }
+fi
+
+
+ICONV_ENABLED=$ICONV_ENABLED
+
+ICONV_INC=$ICONV_INC
+
+ICONV_LIB=$ICONV_LIB
+
+
+ALL_ENABLED="$ICONV_ENABLED $ALL_ENABLED"
+ALL_INC="$ICONV_INC $ALL_INC"
+ALL_LIB="$ICONV_LIB $ALL_LIB"
+
+
+
+
+
+
+
+
+# Check whether --with-gd was given.
+if test "${with_gd+set}" = set; then :
+  withval=$with_gd;
+else
+  with_gd=no
+fi
+
+
+   if test x"$with_gd" == "xno"; then
+      GD_ENABLED=""
+
+      GD_INC=""
+
+      GD_LIB=""
+
+      { $as_echo "$as_me:${as_lineno-$LINENO}: result: GD support not requested, disabling" >&5
+$as_echo "GD support not requested, disabling" >&6; }
+   else
+      if test "$with_gd" == "yes"; then
+         # Extract the first word of "gdlib-config", so it can be a program name with args.
+set dummy gdlib-config; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_path_GDCONFIG+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  case $GDCONFIG in
+  [\\/]* | ?:[\\/]*)
+  ac_cv_path_GDCONFIG="$GDCONFIG" # Let the user override the test with a path.
+  ;;
+  *)
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_path_GDCONFIG="$as_dir/$ac_word$ac_exec_ext"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+  test -z "$ac_cv_path_GDCONFIG" && ac_cv_path_GDCONFIG="no"
+  ;;
+esac
+fi
+GDCONFIG=$ac_cv_path_GDCONFIG
+if test -n "$GDCONFIG"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $GDCONFIG" >&5
+$as_echo "$GDCONFIG" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+         if test "$GDCONFIG" == "no"; then
+            as_fn_error $? "gdlib-config not found in path, reconfigure with --with-gd=/path/to/gdlib-config" "$LINENO" 5
+         fi
+      else
+         if test ! -f "$with_gd"; then
+            if test ! -d "$with_gd"; then
+               as_fn_error $? "cannot find $with_gd" "$LINENO" 5
+            fi
+            if test ! -f "$with_gd/bin/gdlib-config"; then
+               as_fn_error $? "gdlib-config not found in $with_gd (tried $with_gd/bin/gdlib-config)" "$LINENO" 5
+            else
+               GDCONFIG="$with_gd/bin/gdlib-config"
+            fi
+         else
+            GDCONFIG="$with_gd"
+         fi
+         # Extract the first word of "$GDCONFIG", so it can be a program name with args.
+set dummy $GDCONFIG; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_path_GDCONFIG+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  case $GDCONFIG in
+  [\\/]* | ?:[\\/]*)
+  ac_cv_path_GDCONFIG="$GDCONFIG" # Let the user override the test with a path.
+  ;;
+  *)
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_path_GDCONFIG="$as_dir/$ac_word$ac_exec_ext"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+  test -z "$ac_cv_path_GDCONFIG" && ac_cv_path_GDCONFIG="no"
+  ;;
+esac
+fi
+GDCONFIG=$ac_cv_path_GDCONFIG
+if test -n "$GDCONFIG"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $GDCONFIG" >&5
+$as_echo "$GDCONFIG" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+         if test "$GDCONFIG" == "no"; then
+            as_fn_error $? "gdlib-config not usable, reconfigure with --with-gd=(yes|no|/path/to/gdlib-config)" "$LINENO" 5
+         fi
+      fi
+
+      GDMAJOR=`$GDCONFIG --majorversion`
+      GDMINOR=`$GDCONFIG --minorversion`
+      GDREV=`$GDCONFIG --revision`
+      GDVERSION=`$GDCONFIG --version`
+      GDFEATURES=`$GDCONFIG --features`
+      { $as_echo "$as_me:${as_lineno-$LINENO}: result: using libgd $GDVERSION from $GDCONFIG" >&5
+$as_echo "using libgd $GDVERSION from $GDCONFIG" >&6; }
+
+      if test -z "`echo $GDFEATURES | grep 'GD_PNG'`"  ; then
+         as_fn_error $? "supplied GD is missing PNG support" "$LINENO" 5
+      else
+         GD_ENABLED="$GD_ENABLED -DUSE_GD_PNG"
+      fi
+      if test -z "`echo $GDFEATURES | grep 'GD_JPEG'`"  ; then
+         as_fn_error $? "supplied GD is missing JPEG support" "$LINENO" 5
+      else
+         GD_ENABLED="$GD_ENABLED -DUSE_GD_JPEG"
+      fi
+      if test -z "`echo $GDFEATURES | grep 'GD_GIF'`"  ; then
+         as_fn_error $? "supplied GD is missing GIF support" "$LINENO" 5
+      else
+         GD_ENABLED="$GD_ENABLED -DUSE_GD_GIF"
+      fi
+      if test -z "`echo $GDFEATURES | grep 'GD_FREETYPE'`"  ; then
+         as_fn_error $? "supplied GD is missing FT support" "$LINENO" 5
+      fi
+
+
+
+      if test $GDMAJOR -lt 2 -o $GDMINOR -lt 0 -o $GDREV -lt 28 ; then
+         as_fn_error $? "GD version $GDVERSION too old. need at least 2.0.28" "$LINENO" 5
+      fi
+
+
+
+            GD_INC=`$GDCONFIG --includedir`
+      if test "x$GD_INC" != "x/usr/include" -a "x$GD_INC" != "x/usr/include/" -a -n "$GD_INC"; then
+         GD_INC="-I$GD_INC"
+      else
+         GD_INC=""
+      fi
+
+            GD_LIB=`$GDCONFIG --libdir`
+      if test "x$GD_LIB" != "x/usr/lib" -a "x$GD_LIB" != "x/usr/lib/" -a -n "$GD_LIB"; then
+         GD_LIB="-L$GD_LIB"
+      else
+         GD_LIB=""
+      fi
+
+      GD_ENABLED="-DUSE_GD $GD_ENABLED"
+      ALL_ENABLED="$GD_ENABLED $ALL_ENABLED"
+      GD_ENABLED="$GD_ENABLED"
+
+      ALL_INC="$ALL_INC $GD_INC"
+      ALL_LIB="$ALL_LIB $GD_LIB -lgd"
+      GD_INC="$GD_INC"
+
+      GD_LIB="$GD_LIB -lgd"
+
+   fi
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if FTGL support requested" >&5
+$as_echo_n "checking if FTGL support requested... " >&6; }
+
+# Check whether --with-ftgl was given.
+if test "${with_ftgl+set}" = set; then :
+  withval=$with_ftgl;
+fi
+
+
+if test "$with_ftgl" = "yes" ; then
+  with_ftgl="/usr"
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: looking for ftgl libs in /usr" >&5
+$as_echo "looking for ftgl libs in /usr" >&6; }
+fi
+if test -n "$with_ftgl" -a "$with_ftgl" != "no" ; then
+
+
+  if test -z "$with_ftgl" || echo "$with_ftgl" | grep '^/' >/dev/null ; then
+    FTGL_DIR="$with_ftgl"
+  else
+    FTGL_DIR="`pwd`/$with_ftgl"
+  fi
+
+
+  FTGL_FLAG=""
+  if  test -f $FTGL_DIR/include/FTGL/ftgl.h -a -f $FTGL_DIR/include/FTGL/FTGLTextureFont.h ; then
+      FTGL_INCLUDE="-I$FTGL_DIR/include/FTGL/"
+  elif  test -f $FTGL_DIR/include/FTGL/FTGL.h -a -f $FTGL_DIR/include/FTGL/FTGLTextureFont.h ; then
+      FTGL_INCLUDE="-I$FTGL_DIR/include/FTGL/"
+      FTGL_FLAG="-DUSE_FTGL_2_1_2"
+  fi
+
+  if test -z "$FTGL_INCLUDE" ; then
+      as_fn_error $? "\"could not find ftgl.h/FTGL.h in $FTGL_DIR/include/FTGL.\"" "$LINENO" 5
+  fi
+
+  test -f $FTGL_DIR/lib/libftgl.so && FTGL_LIBDIR="$FTGL_DIR/lib"
+  test -f $FTGL_DIR/lib/libftgl.dylib && FTGL_LIBDIR="$FTGL_DIR/lib"
+  test -f $FTGL_DIR/lib64/libftgl.so && FTGL_LIBDIR="$FTGL_DIR/lib64"
+
+  if test -z "$FTGL_LIBDIR" ; then
+      as_fn_error $? "\"could not find libftgl in $FTGL_DIR.\"" "$LINENO" 5
+  fi
+
+
+
+    FTGL_ENABLED="-DUSE_FTGL $FTGL_FLAG"
+  FTGL_INC="$FTGL_INCLUDE"
+  FTGL_LIB="-L$FTGL_LIBDIR -lftgl"
+
+  if test ""$FTGL_LIBDIR"" != "/usr/lib"; then
+
+  if test -z ""$FTGL_LIBDIR"" || echo ""$FTGL_LIBDIR"" | grep '^/' >/dev/null ; then
+    ai_p=""$FTGL_LIBDIR""
+  else
+    ai_p="`pwd`/"$FTGL_LIBDIR""
+  fi
+
+
+  unique=`echo $ac_n "$ai_p$ac_c" | tr -c -d a-zA-Z0-9`
+  cmd="echo $ac_n \"\$LIBPATH$unique$ac_c\""
+  if test -n "$unique" && test "`eval $cmd`" = "" ; then
+    eval "LIBPATH$unique=set"
+
+      EXTRA_LIBS="$EXTRA_LIBS -L$ai_p"
+        RPATHS="$RPATHS ${ld_runpath_switch}$ai_p"
+
+  fi
+
+  fi
+
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: using ftgl from $FTGL_DIR" >&5
+$as_echo "using ftgl from $FTGL_DIR" >&6; }
+
+else
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+
+fi
+
+FTGL_ENABLED=$FTGL_ENABLED
+
+FTGL_INC=$FTGL_INC
+
+FTGL_LIB=$FTGL_LIB
+
+
+
+ALL_ENABLED="$FTGL_ENABLED $ALL_ENABLED"
+ALL_INC="$FTGL_INC $ALL_INC"
+ALL_LIB="$FTGL_LIB $ALL_LIB"
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if OGL support requested" >&5
+$as_echo_n "checking if OGL support requested... " >&6; }
+
+# Check whether --with-ogl was given.
+if test "${with_ogl+set}" = set; then :
+  withval=$with_ogl;
+fi
+
+
+if test "$with_opengl" = "yes" ; then
+
+  with_opengl="/usr"
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: looking for opengl libs in /usr" >&5
+$as_echo "looking for opengl libs in /usr" >&6; }
+fi
+if test -n "$with_opengl" -a "$with_opengl" != "no" ; then
+
+  if test -z "$FTGL_LIB" ; then
+     as_fn_error $? "FTGL required for opengl support - please configure --with-ftgl." "$LINENO" 5
+  fi
+
+
+  if test -z "$with_opengl" || echo "$with_opengl" | grep '^/' >/dev/null ; then
+    OGL_DIR="$with_opengl"
+  else
+    OGL_DIR="`pwd`/$with_opengl"
+  fi
+
+
+  test -f $OGL_DIR/include/GL/gl.h -a -f $OGL_DIR/include/GL/glx.h -a -f $OGL_DIR/include/GL/glu.h && OGL_INCLUDE="-I$OGL_DIR/include"
+
+  if test -z "$OGL_INCLUDE" ; then
+      as_fn_error $? "\"could not find gl.h in $OGL_DIR/include/.\"" "$LINENO" 5
+  fi
 
-eval "$as_ac_Lib=no"
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Lib'}'`" >&5
-echo "${ECHO_T}`eval echo '${'$as_ac_Lib'}'`" >&6
-if test `eval echo '${'$as_ac_Lib'}'` = yes; then
-  GD_DEF="$GD_DEF -DUSE_GD_WBMP"
-fi
+  test -f $OGL_DIR/lib/libGL.so -a -f $OGL_DIR/lib/libGLU.so && OGL_LIBDIR="$OGL_DIR/lib"
+  test -f $OGL_DIR/lib/libGL.dylib -a -f $OGL_DIR/lib/libGLU.dylib && OGL_LIBDIR="$OGL_DIR/lib"
+  test -f $OGL_DIR/lib64/libGL.so -a -f $OGL_DIR/lib64/libGLU.so && OGL_LIBDIR="$OGL_DIR/lib64"
 
+  if test -z "$OGL_LIBDIR" ; then
+      as_fn_error $? "\"could not find libGL or libGLU in $OGL_DIR/lib/ or $OGL_DIR/lib64/.\"" "$LINENO" 5
+  fi
 
-    GD_FT_SUPPORT=no
-  as_ac_Lib=`echo "ac_cv_lib_$GD_CHECKLIB''_gdImageStringFT" | $as_tr_sh`
-echo "$as_me:$LINENO: checking for gdImageStringFT in -l$GD_CHECKLIB" >&5
-echo $ECHO_N "checking for gdImageStringFT in -l$GD_CHECKLIB... $ECHO_C" >&6
-if eval "test \"\${$as_ac_Lib+set}\" = set"; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-l$GD_CHECKLIB $GD_STATIC $GD_LIB $GD_XTRA_LIBS $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
 
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char gdImageStringFT ();
-int
-main ()
-{
-gdImageStringFT ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  eval "$as_ac_Lib=yes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
 
-eval "$as_ac_Lib=no"
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Lib'}'`" >&5
-echo "${ECHO_T}`eval echo '${'$as_ac_Lib'}'`" >&6
-if test `eval echo '${'$as_ac_Lib'}'` = yes; then
-  GD_FT_SUPPORT=yes
-fi
+    OGL_ENABLED="-DUSE_OGL"
+  OGL_INC="$OGL_INCLUDE"
+  OGL_LIB="-L$OGL_LIBDIR -lGL -lGLU"
 
+  if test ""$OGL_LIBDIR"" != "/usr/lib"; then
 
-    if test -n "$GD_STATIC" ; then
-     GD_LIB="$GD_LIB -lfontconfig"
-     unset ac_cv_lib_c___gdImageStringFT
-     as_ac_Lib=`echo "ac_cv_lib_$GD_CHECKLIB''_gdImageStringFT" | $as_tr_sh`
-echo "$as_me:$LINENO: checking for gdImageStringFT in -l$GD_CHECKLIB" >&5
-echo $ECHO_N "checking for gdImageStringFT in -l$GD_CHECKLIB... $ECHO_C" >&6
-if eval "test \"\${$as_ac_Lib+set}\" = set"; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-l$GD_CHECKLIB $GD_STATIC $GD_LIB $GD_XTRA_LIBS $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
+  if test -z ""$OGL_LIBDIR"" || echo ""$OGL_LIBDIR"" | grep '^/' >/dev/null ; then
+    ai_p=""$OGL_LIBDIR""
+  else
+    ai_p="`pwd`/"$OGL_LIBDIR""
+  fi
 
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char gdImageStringFT ();
-int
-main ()
-{
-gdImageStringFT ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  eval "$as_ac_Lib=yes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
 
-eval "$as_ac_Lib=no"
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Lib'}'`" >&5
-echo "${ECHO_T}`eval echo '${'$as_ac_Lib'}'`" >&6
-if test `eval echo '${'$as_ac_Lib'}'` = yes; then
-  GD_FT_SUPPORT=yes
-fi
+  unique=`echo $ac_n "$ai_p$ac_c" | tr -c -d a-zA-Z0-9`
+  cmd="echo $ac_n \"\$LIBPATH$unique$ac_c\""
+  if test -n "$unique" && test "`eval $cmd`" = "" ; then
+    eval "LIBPATH$unique=set"
+
+      EXTRA_LIBS="$EXTRA_LIBS -L$ai_p"
+        RPATHS="$RPATHS ${ld_runpath_switch}$ai_p"
 
   fi
 
-  if test "$GD_FT_SUPPORT" = "yes"; then
-     GD_DEF="$GD_DEF -DUSE_GD_FT"
   fi
 
-    GD_RESOLUTION_SUPPORT=no
-  as_ac_Lib=`echo "ac_cv_lib_$GD_CHECKLIB''_gdImageSetResolution" | $as_tr_sh`
-echo "$as_me:$LINENO: checking for gdImageSetResolution in -l$GD_CHECKLIB" >&5
-echo $ECHO_N "checking for gdImageSetResolution in -l$GD_CHECKLIB... $ECHO_C" >&6
-if eval "test \"\${$as_ac_Lib+set}\" = set"; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-l$GD_CHECKLIB $GD_STATIC $GD_LIB $GD_XTRA_LIBS $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
 
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char gdImageSetResolution ();
-int
-main ()
-{
-gdImageSetResolution ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  eval "$as_ac_Lib=yes"
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: using opengl from $OGL_DIR" >&5
+$as_echo "using opengl from $OGL_DIR" >&6; }
+
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
 
-eval "$as_ac_Lib=no"
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Lib'}'`" >&5
-echo "${ECHO_T}`eval echo '${'$as_ac_Lib'}'`" >&6
-if test `eval echo '${'$as_ac_Lib'}'` = yes; then
-  GD_RESOLUTION_SUPPORT=yes
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+
 fi
 
+OGL_ENABLED=$OGL_ENABLED
 
-  if test "$GD_RESOLUTION_SUPPORT" = "yes"; then
-     GD_DEF="$GD_DEF -DUSE_GD_RESOLUTION"
-  fi
+OGL_INC=$OGL_INC
 
-    as_ac_Lib=`echo "ac_cv_lib_$GD_CHECKLIB''_gdImageOpenPolygon" | $as_tr_sh`
-echo "$as_me:$LINENO: checking for gdImageOpenPolygon in -l$GD_CHECKLIB" >&5
-echo $ECHO_N "checking for gdImageOpenPolygon in -l$GD_CHECKLIB... $ECHO_C" >&6
-if eval "test \"\${$as_ac_Lib+set}\" = set"; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-l$GD_CHECKLIB $GD_STATIC $GD_LIB $GD_XTRA_LIBS $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
+OGL_LIB=$OGL_LIB
 
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char gdImageOpenPolygon ();
-int
-main ()
-{
-gdImageOpenPolygon ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  eval "$as_ac_Lib=yes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
 
-eval "$as_ac_Lib=no"
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Lib'}'`" >&5
-echo "${ECHO_T}`eval echo '${'$as_ac_Lib'}'`" >&6
-if test `eval echo '${'$as_ac_Lib'}'` = yes; then
-  GD_DEF="$GD_DEF -DGD_HAS_FTEX_XSHOW"
-fi
 
+ALL_ENABLED="$OGL_ENABLED $ALL_ENABLED"
+ALL_INC="$OGL_INC $ALL_INC"
+ALL_LIB="$OGL_LIB $ALL_LIB"
 
-    as_ac_Lib=`echo "ac_cv_lib_$GD_CHECKLIB''_gdImageGifPtr" | $as_tr_sh`
-echo "$as_me:$LINENO: checking for gdImageGifPtr in -l$GD_CHECKLIB" >&5
-echo $ECHO_N "checking for gdImageGifPtr in -l$GD_CHECKLIB... $ECHO_C" >&6
-if eval "test \"\${$as_ac_Lib+set}\" = set"; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-l$GD_CHECKLIB $GD_STATIC $GD_LIB $GD_XTRA_LIBS $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
 
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char gdImageGifPtr ();
-int
-main ()
-{
-gdImageGifPtr ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  eval "$as_ac_Lib=yes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
 
-eval "$as_ac_Lib=no"
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Lib'}'`" >&5
-echo "${ECHO_T}`eval echo '${'$as_ac_Lib'}'`" >&6
-if test `eval echo '${'$as_ac_Lib'}'` = yes; then
-  GD_DEF="$GD_DEF -DGD_HAS_GDIMAGEGIFPTR"
-fi
 
 
-      as_ac_Lib=`echo "ac_cv_lib_$GD_CHECKLIB''_gdFontGetTiny" | $as_tr_sh`
-echo "$as_me:$LINENO: checking for gdFontGetTiny in -l$GD_CHECKLIB" >&5
-echo $ECHO_N "checking for gdFontGetTiny in -l$GD_CHECKLIB... $ECHO_C" >&6
-if eval "test \"\${$as_ac_Lib+set}\" = set"; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+# Check whether --with-expat was given.
+if test "${with_expat+set}" = set; then :
+  withval=$with_expat; EXPAT_DIR=$withval
 else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-l$GD_CHECKLIB $GD_STATIC $GD_LIB $GD_XTRA_LIBS $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
+  EXPAT_DIR=''
+fi
 
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char gdFontGetTiny ();
-int
-main ()
-{
-gdFontGetTiny ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  eval "$as_ac_Lib=yes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
 
-eval "$as_ac_Lib=no"
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Lib'}'`" >&5
-echo "${ECHO_T}`eval echo '${'$as_ac_Lib'}'`" >&6
-if test `eval echo '${'$as_ac_Lib'}'` = yes; then
-  GD_DEF="$GD_DEF -DGD_HAS_GETBITMAPFONTS"
-fi
 
+  if test -z "$EXPAT_DIR" || echo "$EXPAT_DIR" | grep '^/' >/dev/null ; then
+    EXPAT_DIR="$EXPAT_DIR"
+  else
+    EXPAT_DIR="`pwd`/$EXPAT_DIR"
+  fi
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking where EXPAT is installed..." >&5
+$as_echo "$as_me: checking where EXPAT is installed..." >&6;}
+EXPAT_LIB=''
+EXPAT_INC=''
+EXPAT_FOUND='no'
 
-        GD_HAS_GET_TRUE_COLOR_PIXEL=
 
-    CFLAGS_BACKUP="$CFLAGS"
-  CXXFLAGS_BACKUP="$CXXFLAGS"
-  CFLAGS="$CFLAGS $GD_INC"
-  CXXFLAGS="$CXXFLAGS $GD_INC"
-  echo "$as_me:$LINENO: checking whether gdImageGetTrueColorPixel is declared" >&5
-echo $ECHO_N "checking whether gdImageGetTrueColorPixel is declared... $ECHO_C" >&6
-if test "${ac_cv_have_decl_gdImageGetTrueColorPixel+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#include <gd.h>
+if test -n "$EXPAT_DIR" ; then
+    test -f $EXPAT_DIR/lib/libexpat.a -o -f $EXPAT_DIR/lib/libexpat.so -o -f $EXPAT_DIR/lib/libexpat.sl -o -f $EXPAT_DIR/lib/libexpat.dylib && EXPAT_LIBDIR="$EXPAT_DIR/lib"
+    test -f $EXPAT_DIR/lib64/libexpat.a -o -f $EXPAT_DIR/lib64/libexpat.so -o -f $EXPAT_DIR/lib64/libexpat.sl -o -f $EXPAT_DIR/libexpat.dylib && EXPAT_LIBDIR="$EXPAT_DIR/lib64"
+    test -f $EXPAT_DIR/libexpat.a -o -f $EXPAT_DIR/libexpat.so -o -f $EXPAT_DIR/libexpat.sl -o -f $EXPAT_DIR/libexpat.dylib && EXPAT_LIBDIR="$EXPAT_DIR"
+    test -f $EXPAT_DIR/include/expat.h && EXPAT_INCDIR="$EXPAT_DIR/include"
+    test -f $EXPAT_DIR/lib/expat.h && EXPAT_INCDIR="$EXPAT_DIR/lib"
+    test -f $EXPAT_DIR/expat.h && EXPAT_INCDIR="$EXPAT_DIR"
 
-int
-main ()
-{
-#ifndef gdImageGetTrueColorPixel
-  char *p = (char *) gdImageGetTrueColorPixel;
-#endif
+    if test -n "$EXPAT_LIBDIR" ; then
+      EXPAT_LIB="-L$EXPAT_LIBDIR -lexpat"
+      { $as_echo "$as_me:${as_lineno-$LINENO}: result:         using libexpat from $EXPAT_LIB" >&5
+$as_echo "        using libexpat from $EXPAT_LIB" >&6; }
 
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest.$ac_objext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_have_decl_gdImageGetTrueColorPixel=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
+  if test ""$EXPAT_LIBDIR"" != "/usr/lib"; then
 
-ac_cv_have_decl_gdImageGetTrueColorPixel=no
-fi
-rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-echo "$as_me:$LINENO: result: $ac_cv_have_decl_gdImageGetTrueColorPixel" >&5
-echo "${ECHO_T}$ac_cv_have_decl_gdImageGetTrueColorPixel" >&6
-if test $ac_cv_have_decl_gdImageGetTrueColorPixel = yes; then
-  GD_HAS_GET_TRUE_COLOR_PIXEL=yes
+  if test -z ""$EXPAT_LIBDIR"" || echo ""$EXPAT_LIBDIR"" | grep '^/' >/dev/null ; then
+    ai_p=""$EXPAT_LIBDIR""
+  else
+    ai_p="`pwd`/"$EXPAT_LIBDIR""
+  fi
+
+
+  unique=`echo $ac_n "$ai_p$ac_c" | tr -c -d a-zA-Z0-9`
+  cmd="echo $ac_n \"\$LIBPATH$unique$ac_c\""
+  if test -n "$unique" && test "`eval $cmd`" = "" ; then
+    eval "LIBPATH$unique=set"
+
+      EXTRA_LIBS="$EXTRA_LIBS -L$ai_p"
+        RPATHS="$RPATHS ${ld_runpath_switch}$ai_p"
+
+  fi
+
+  fi
+
+    else
+      as_fn_error $? "cannot find expat lib in $EXPAT_DIR" "$LINENO" 5
+    fi
+
+    if test -n "$EXPAT_INCDIR" ; then
+      as_ac_Header=`$as_echo "ac_cv_header_$EXPAT_INCDIR/expat.h" | $as_tr_sh`
+ac_fn_c_check_header_mongrel "$LINENO" "$EXPAT_INCDIR/expat.h" "$as_ac_Header" "$ac_includes_default"
+if eval test \"x\$"$as_ac_Header"\" = x"yes"; then :
+  EXPAT_INC=-I$EXPAT_INCDIR
+else
+  as_fn_error $? "cannot find expat headers" "$LINENO" 5
 fi
 
-  CFLAGS="$CFLAGS_BACKUP"
-  CXXFLAGS="$CXXFLAGS_BACKUP"
 
-    if test .$GD_HAS_GET_TRUE_COLOR_PIXEL = .yes ; then
-    as_ac_Lib=`echo "ac_cv_lib_$GD_CHECKLIB''_gdImageGetTrueColorPixel" | $as_tr_sh`
-echo "$as_me:$LINENO: checking for gdImageGetTrueColorPixel in -l$GD_CHECKLIB" >&5
-echo $ECHO_N "checking for gdImageGetTrueColorPixel in -l$GD_CHECKLIB... $ECHO_C" >&6
-if eval "test \"\${$as_ac_Lib+set}\" = set"; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+      ALL_INC="$EXPAT_INC $ALL_INC"
+    else
+        as_fn_error $? "cannot find expat headers in $EXPAT_DIR" "$LINENO" 5
+    fi
+    EXPAT_FOUND="yes"
+else
+
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for XML_ParserCreate in -lexpat" >&5
+$as_echo_n "checking for XML_ParserCreate in -lexpat... " >&6; }
+if ${ac_cv_lib_expat_XML_ParserCreate+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
   ac_check_lib_save_LIBS=$LIBS
-LIBS="-l$GD_CHECKLIB $GD_STATIC $GD_LIB $GD_XTRA_LIBS $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+LIBS="-lexpat  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
-/* Override any gcc2 internal prototype to avoid an error.  */
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
 #ifdef __cplusplus
 extern "C"
 #endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char gdImageGetTrueColorPixel ();
+char XML_ParserCreate ();
 int
 main ()
 {
-gdImageGetTrueColorPixel ();
+return XML_ParserCreate ();
   ;
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  eval "$as_ac_Lib=yes"
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_expat_XML_ParserCreate=yes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-eval "$as_ac_Lib=no"
+  ac_cv_lib_expat_XML_ParserCreate=no
 fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 LIBS=$ac_check_lib_save_LIBS
 fi
-echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Lib'}'`" >&5
-echo "${ECHO_T}`eval echo '${'$as_ac_Lib'}'`" >&6
-if test `eval echo '${'$as_ac_Lib'}'` = yes; then
-  GD_DEF="$GD_DEF -DGD_HAS_GET_TRUE_COLOR_PIXEL"
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_expat_XML_ParserCreate" >&5
+$as_echo "$ac_cv_lib_expat_XML_ParserCreate" >&6; }
+if test "x$ac_cv_lib_expat_XML_ParserCreate" = xyes; then :
+  EXPAT_LIB="-lexpat"
+fi
+
+  ac_fn_c_check_header_mongrel "$LINENO" "expat.h" "ac_cv_header_expat_h" "$ac_includes_default"
+if test "x$ac_cv_header_expat_h" = xyes; then :
+
+else
+  EXPAT_HEADER_FOUND="no"
 fi
 
+
+  if test -n "$EXPAT_LIB" -a "$EXPAT_HEADER_FOUND" != "no"; then
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result:         using libexpat from system libs." >&5
+$as_echo "        using libexpat from system libs." >&6; }
+    EXPAT_FOUND='yes'
+  else
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result:         not found in system libs. svg symbol support will be disabled" >&5
+$as_echo "        not found in system libs. svg symbol support will be disabled" >&6; }
+    EXPAT_FOUND='no'
   fi
 
-  echo "$as_me:$LINENO: result:         using GD ($GD_DEF) from $GD_DIR." >&5
-echo "${ECHO_T}        using GD ($GD_DEF) from $GD_DIR." >&6
+fi
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for AGG support" >&5
+$as_echo_n "checking for AGG support... " >&6; }
+AGG_ENABLED="internal"
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result:         internal" >&5
+$as_echo "        internal" >&6; }
+
 
-else
 
+unset ac_cv_lib_proj_pj_init
+unset ac_cv_lib_proj_pj_transform
+unset ac_cv_lib_proj_pj_latlong_from_proj
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we should include PROJ.4 support..." >&5
+$as_echo "$as_me: checking whether we should include PROJ.4 support..." >&6;}
+
+# Check whether --with-proj was given.
+if test "${with_proj+set}" = set; then :
+  withval=$with_proj;
+fi
+
+
+if test "$with_proj" = "yes" ; then
 
-    echo "$as_me:$LINENO: checking for gdImageCreate in -lgd" >&5
-echo $ECHO_N "checking for gdImageCreate in -lgd... $ECHO_C" >&6
-if test "${ac_cv_lib_gd_gdImageCreate+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for pj_init in -lproj" >&5
+$as_echo_n "checking for pj_init in -lproj... " >&6; }
+if ${ac_cv_lib_proj_pj_init+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
   ac_check_lib_save_LIBS=$LIBS
-LIBS="-lgd $GD_XTRA_LIBS $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+LIBS="-lproj  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
-/* Override any gcc2 internal prototype to avoid an error.  */
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
 #ifdef __cplusplus
 extern "C"
 #endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char gdImageCreate ();
+char pj_init ();
 int
 main ()
 {
-gdImageCreate ();
+return pj_init ();
   ;
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_gd_gdImageCreate=yes
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_proj_pj_init=yes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-ac_cv_lib_gd_gdImageCreate=no
+  ac_cv_lib_proj_pj_init=no
 fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 LIBS=$ac_check_lib_save_LIBS
 fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_gd_gdImageCreate" >&5
-echo "${ECHO_T}$ac_cv_lib_gd_gdImageCreate" >&6
-if test $ac_cv_lib_gd_gdImageCreate = yes; then
-  GD_FOUND=yes
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_proj_pj_init" >&5
+$as_echo "$ac_cv_lib_proj_pj_init" >&6; }
+if test "x$ac_cv_lib_proj_pj_init" = xyes; then :
+  PROJ_ENABLED=-DUSE_PROJ
 fi
 
-  if test -z "$GD_FOUND" ; then
-      { { echo "$as_me:$LINENO: error: GD is required but was not found... use --with-gd=DIR to specify its location." >&5
-echo "$as_me: error: GD is required but was not found... use --with-gd=DIR to specify its location." >&2;}
-   { (exit 1); exit 1; }; }
-  fi
-
-    echo "$as_me:$LINENO: checking for gdImageGif in -lgd" >&5
-echo $ECHO_N "checking for gdImageGif in -lgd... $ECHO_C" >&6
-if test "${ac_cv_lib_gd_gdImageGif+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for pj_transform in -lproj" >&5
+$as_echo_n "checking for pj_transform in -lproj... " >&6; }
+if ${ac_cv_lib_proj_pj_transform+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
   ac_check_lib_save_LIBS=$LIBS
-LIBS="-lgd $GD_LIB $GD_XTRA_LIBS $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+LIBS="-lproj  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
-/* Override any gcc2 internal prototype to avoid an error.  */
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
 #ifdef __cplusplus
 extern "C"
 #endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char gdImageGif ();
+char pj_transform ();
 int
 main ()
 {
-gdImageGif ();
+return pj_transform ();
   ;
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_gd_gdImageGif=yes
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_proj_pj_transform=yes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-ac_cv_lib_gd_gdImageGif=no
+  ac_cv_lib_proj_pj_transform=no
 fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 LIBS=$ac_check_lib_save_LIBS
 fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_gd_gdImageGif" >&5
-echo "${ECHO_T}$ac_cv_lib_gd_gdImageGif" >&6
-if test $ac_cv_lib_gd_gdImageGif = yes; then
-  GD_DEF="$GD_DEF -DUSE_GD_GIF"
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_proj_pj_transform" >&5
+$as_echo "$ac_cv_lib_proj_pj_transform" >&6; }
+if test "x$ac_cv_lib_proj_pj_transform" = xyes; then :
+  PJ_TRANSFORM=yes
+else
+  PJ_TRANSFORM=no
 fi
 
-  echo "$as_me:$LINENO: checking for gdImagePng in -lgd" >&5
-echo $ECHO_N "checking for gdImagePng in -lgd... $ECHO_C" >&6
-if test "${ac_cv_lib_gd_gdImagePng+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+
+  if test -n "$PROJ_ENABLED" -a "$PJ_TRANSFORM" = "no"; then
+      as_fn_error $? "This version of PROJ is too old.  PROJ4.4.2 or later is required." "$LINENO" 5
+  elif test -n "$PROJ_ENABLED" -a "$PJ_TRANSFORM" = "yes"; then
+      PROJ_LIBS="-lproj"
+      { $as_echo "$as_me:${as_lineno-$LINENO}: result:         using PROJ.4 from system libs." >&5
+$as_echo "        using PROJ.4 from system libs." >&6; }
+  else
+      { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING:         PROJ.4 not found in system libs... use --with-proj=DIR." >&5
+$as_echo "$as_me: WARNING:         PROJ.4 not found in system libs... use --with-proj=DIR." >&2;}
+  fi
+
+elif test -n "$with_proj" -a "$with_proj" != "no" ; then
+
+
+  if test -z "$with_proj" || echo "$with_proj" | grep '^/' >/dev/null ; then
+    PROJ_DIR="$with_proj"
+  else
+    PROJ_DIR="`pwd`/$with_proj"
+  fi
+
+  test -f $PROJ_DIR/include/proj_api.h && PROJ_INCLUDE="$PROJ_DIR/include"
+  test -f $PROJ_DIR/include/proj/proj_api.h && PROJ_INCLUDE="$PROJ_DIR/include/proj"
+  test -f $PROJ_DIR/src/proj_api.h && PROJ_INCLUDE="$PROJ_DIR/src"
+  test -f $PROJ_DIR/proj_api.h && PROJ_INCLUDE="$PROJ_DIR"
+
+  test -f $PROJ_DIR/src/.libs/libproj.a && PROJ_LIBDIR="$PROJ_DIR/src/.libs"
+  test -f $PROJ_DIR/lib/libproj.a && PROJ_LIBDIR="$PROJ_DIR/lib"
+  test -f $PROJ_DIR/lib64/libproj.a && PROJ_LIBDIR="$PROJ_DIR/lib64"
+  test -f $PROJ_DIR/libproj.a && PROJ_LIBDIR="$PROJ_DIR"
+
+  test -f $PROJ_DIR/src/.libs/libproj.so -o -f $PROJ_DIR/src/.libs/libproj.sl -o -f $PROJ_DIR/src/.libs/libproj.dylib && PROJ_LIBDIR="$PROJ_DIR/src/.libs"
+  test -f $PROJ_DIR/lib/libproj.so -o -f $PROJ_DIR/lib/libproj.sl -o -f $PROJ_DIR/lib/libproj.dylib && PROJ_LIBDIR="$PROJ_DIR/lib"
+  test -f $PROJ_DIR/lib64/libproj.so -o -f $PROJ_DIR/lib64/libproj.sl && PROJ_LIBDIR="$PROJ_DIR/lib64"
+  test -f $PROJ_DIR/libproj.so -o -f $PROJ_DIR/libproj.sl -o -f $PROJ_DIR/libproj.dylib && PROJ_LIBDIR="$PROJ_DIR"
+
+  if test -n "$PROJ_INCLUDE" -a -n "$PROJ_LIBDIR" ; then
+      PROJ_INC=-I$PROJ_INCLUDE
+      PROJ_LIBS="-L$PROJ_LIBDIR -lproj"
+
+  if test ""$PROJ_LIBDIR"" != "/usr/lib"; then
+
+  if test -z ""$PROJ_LIBDIR"" || echo ""$PROJ_LIBDIR"" | grep '^/' >/dev/null ; then
+    ai_p=""$PROJ_LIBDIR""
+  else
+    ai_p="`pwd`/"$PROJ_LIBDIR""
+  fi
+
+
+  unique=`echo $ac_n "$ai_p$ac_c" | tr -c -d a-zA-Z0-9`
+  cmd="echo $ac_n \"\$LIBPATH$unique$ac_c\""
+  if test -n "$unique" && test "`eval $cmd`" = "" ; then
+    eval "LIBPATH$unique=set"
+
+      EXTRA_LIBS="$EXTRA_LIBS -L$ai_p"
+        RPATHS="$RPATHS ${ld_runpath_switch}$ai_p"
+
+  fi
+
+  fi
+
+  else
+      as_fn_error $? "\"Could not find proj_api.h or libproj.a/libproj.so in $PROJ_DIR.\"" "$LINENO" 5
+  fi
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for pj_transform in -lproj" >&5
+$as_echo_n "checking for pj_transform in -lproj... " >&6; }
+if ${ac_cv_lib_proj_pj_transform+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
   ac_check_lib_save_LIBS=$LIBS
-LIBS="-lgd $GD_LIB $GD_XTRA_LIBS $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+LIBS="-lproj $PROJ_LIBS $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
-/* Override any gcc2 internal prototype to avoid an error.  */
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
 #ifdef __cplusplus
 extern "C"
 #endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char gdImagePng ();
+char pj_transform ();
 int
 main ()
 {
-gdImagePng ();
+return pj_transform ();
   ;
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_gd_gdImagePng=yes
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_proj_pj_transform=yes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-ac_cv_lib_gd_gdImagePng=no
+  ac_cv_lib_proj_pj_transform=no
 fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 LIBS=$ac_check_lib_save_LIBS
 fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_gd_gdImagePng" >&5
-echo "${ECHO_T}$ac_cv_lib_gd_gdImagePng" >&6
-if test $ac_cv_lib_gd_gdImagePng = yes; then
-  GD_DEF="$GD_DEF -DUSE_GD_PNG"
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_proj_pj_transform" >&5
+$as_echo "$ac_cv_lib_proj_pj_transform" >&6; }
+if test "x$ac_cv_lib_proj_pj_transform" = xyes; then :
+  PJ_TRANSFORM=yes
+else
+  PJ_TRANSFORM=no
 fi
 
-  echo "$as_me:$LINENO: checking for gdImageJpeg in -lgd" >&5
-echo $ECHO_N "checking for gdImageJpeg in -lgd... $ECHO_C" >&6
-if test "${ac_cv_lib_gd_gdImageJpeg+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-lgd $GD_LIB $GD_XTRA_LIBS $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
+  if test "$PJ_TRANSFORM" = "no"; then
+      as_fn_error $? "This version of PROJ is too old.  PROJ4.4.2 or later is required." "$LINENO" 5
+  fi
+
+  PROJ_ENABLED=-DUSE_PROJ
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result:         using PROJ.4 from $PROJ_DIR." >&5
+$as_echo "        using PROJ.4 from $PROJ_DIR." >&6; }
 
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char gdImageJpeg ();
-int
-main ()
-{
-gdImageJpeg ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_gd_gdImageJpeg=yes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
 
-ac_cv_lib_gd_gdImageJpeg=no
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result:         PROJ.4 support not requested." >&5
+$as_echo "        PROJ.4 support not requested." >&6; }
 fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_gd_gdImageJpeg" >&5
-echo "${ECHO_T}$ac_cv_lib_gd_gdImageJpeg" >&6
-if test $ac_cv_lib_gd_gdImageJpeg = yes; then
-  GD_DEF="$GD_DEF -DUSE_GD_JPEG"
+
+PROJ_ENABLED=$PROJ_ENABLED
+
+PROJ_INC=$PROJ_INC
+
+PROJ_LIBS=$PROJ_LIBS
+
+
+ALL_ENABLED="$PROJ_ENABLED $ALL_ENABLED"
+ALL_INC="$PROJ_INC $ALL_INC"
+ALL_LIB="$PROJ_LIBS $ALL_LIB"
+
+
+THREAD_LIB=""
+THREAD_FLAG=""
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we should include thread safe support..." >&5
+$as_echo "$as_me: checking whether we should include thread safe support..." >&6;}
+
+# Check whether --with-threads was given.
+if test "${with_threads+set}" = set; then :
+  withval=$with_threads;
 fi
 
-  echo "$as_me:$LINENO: checking for gdImageWBMP in -lgd" >&5
-echo $ECHO_N "checking for gdImageWBMP in -lgd... $ECHO_C" >&6
-if test "${ac_cv_lib_gd_gdImageWBMP+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+
+if test "$with_threads" = "yes" ; then
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for pthread_create in -lpthread" >&5
+$as_echo_n "checking for pthread_create in -lpthread... " >&6; }
+if ${ac_cv_lib_pthread_pthread_create+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
   ac_check_lib_save_LIBS=$LIBS
-LIBS="-lgd $GD_LIB $GD_XTRA_LIBS $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+LIBS="-lpthread  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
-/* Override any gcc2 internal prototype to avoid an error.  */
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
 #ifdef __cplusplus
 extern "C"
 #endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char gdImageWBMP ();
+char pthread_create ();
 int
 main ()
 {
-gdImageWBMP ();
+return pthread_create ();
   ;
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_gd_gdImageWBMP=yes
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_pthread_pthread_create=yes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-ac_cv_lib_gd_gdImageWBMP=no
+  ac_cv_lib_pthread_pthread_create=no
 fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 LIBS=$ac_check_lib_save_LIBS
 fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_gd_gdImageWBMP" >&5
-echo "${ECHO_T}$ac_cv_lib_gd_gdImageWBMP" >&6
-if test $ac_cv_lib_gd_gdImageWBMP = yes; then
-  GD_DEF="$GD_DEF -DUSE_GD_WBMP"
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_pthread_pthread_create" >&5
+$as_echo "$ac_cv_lib_pthread_pthread_create" >&6; }
+if test "x$ac_cv_lib_pthread_pthread_create" = xyes; then :
+  THREAD_FLAG=-DUSE_THREAD
 fi
 
 
-    echo "$as_me:$LINENO: checking for gdImageStringFT in -lgd" >&5
-echo $ECHO_N "checking for gdImageStringFT in -lgd... $ECHO_C" >&6
-if test "${ac_cv_lib_gd_gdImageStringFT+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+  if test -n "$THREAD_FLAG" ; then
+      THREAD_LIB="-lpthread"
+      { $as_echo "$as_me:${as_lineno-$LINENO}: result:         using -lpthread from system libs." >&5
+$as_echo "        using -lpthread from system libs." >&6; }
+  else
+      as_fn_error $? "        -lpthread not found, use --with-thread=<pthread link options>" "$LINENO" 5
+  fi
+
+elif test -n "$with_threads" -a "$with_threads" != "no" ; then
+
+  THREAD_FLAG=-DUSE_THREAD
+  THREAD_LIB="$with_threads"
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result:         using threads with link options \"$THREAD_LIB\"." >&5
+$as_echo "        using threads with link options \"$THREAD_LIB\"." >&6; }
+
 else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-lgd $GD_LIB $GD_XTRA_LIBS $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result:         thread safe support disabled." >&5
+$as_echo "        thread safe support disabled." >&6; }
+fi
+
+THREAD_FLAG=$THREAD_FLAG
+
+THREAD_LIB=$THREAD_LIB
+
+
+ALL_ENABLED="$THREAD_FLAG $ALL_ENABLED"
+ALL_LIB="$THREAD_LIB $ALL_LIB"
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for __sync_fetch_and_add" >&5
+$as_echo_n "checking for __sync_fetch_and_add... " >&6; }
+if ${ac_cv_func_sync_fetch_and_add+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char gdImageStringFT ();
 int
 main ()
 {
-gdImageStringFT ();
+int x;__sync_fetch_and_add(&x,1);
   ;
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_gd_gdImageStringFT=yes
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_func_sync_fetch_and_add=yes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
+  ac_cv_func_sync_fetch_and_add=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_sync_fetch_and_add" >&5
+$as_echo "$ac_cv_func_sync_fetch_and_add" >&6; }
+if test "$ac_cv_func_sync_fetch_and_add" = yes; then
+  ALL_ENABLED="-DHAVE_SYNC_FETCH_AND_ADD $ALL_ENABLED"
+
+$as_echo "#define HAVE_SYNC_FETCH_AND_ADD 1" >>confdefs.h
 
-ac_cv_lib_gd_gdImageStringFT=no
 fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we should include ESRI SDE support..." >&5
+$as_echo "$as_me: checking whether we should include ESRI SDE support..." >&6;}
+
+# Check whether --with-sde was given.
+if test "${with_sde+set}" = set; then :
+  withval=$with_sde;
 fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_gd_gdImageStringFT" >&5
-echo "${ECHO_T}$ac_cv_lib_gd_gdImageStringFT" >&6
-if test $ac_cv_lib_gd_gdImageStringFT = yes; then
-  GD_DEF="$GD_DEF -DUSE_GD_FT"
+
+
+
+# Check whether --with-sde-version was given.
+if test "${with_sde_version+set}" = set; then :
+  withval=$with_sde_version; SDE_VERSION=$with_sde_version
+else
+  SDE_VERSION=91
 fi
 
 
-    echo "$as_me:$LINENO: checking for gdImageOpenPolygon in -lgd" >&5
-echo $ECHO_N "checking for gdImageOpenPolygon in -lgd... $ECHO_C" >&6
-if test "${ac_cv_lib_gd_gdImageOpenPolygon+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+if test -z "$SDE_VERSION" -o `expr "$SDE_VERSION" \>\= 92` = 1; then
+SDE_VERSION=""
+fi
+if test "$with_sde" = "yes" ; then
+
+  as_ac_Lib=`$as_echo "ac_cv_lib_sde$SDE_VERSION''_SE_connection_create" | $as_tr_sh`
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for SE_connection_create in -lsde$SDE_VERSION" >&5
+$as_echo_n "checking for SE_connection_create in -lsde$SDE_VERSION... " >&6; }
+if eval \${$as_ac_Lib+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
   ac_check_lib_save_LIBS=$LIBS
-LIBS="-lgd $GD_STATIC $GD_LIB $GD_XTRA_LIBS $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+LIBS="-lsde$SDE_VERSION  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
-/* Override any gcc2 internal prototype to avoid an error.  */
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
 #ifdef __cplusplus
 extern "C"
 #endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char gdImageOpenPolygon ();
+char SE_connection_create ();
 int
 main ()
 {
-gdImageOpenPolygon ();
+return SE_connection_create ();
   ;
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_gd_gdImageOpenPolygon=yes
+if ac_fn_c_try_link "$LINENO"; then :
+  eval "$as_ac_Lib=yes"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-ac_cv_lib_gd_gdImageOpenPolygon=no
+  eval "$as_ac_Lib=no"
 fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 LIBS=$ac_check_lib_save_LIBS
 fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_gd_gdImageOpenPolygon" >&5
-echo "${ECHO_T}$ac_cv_lib_gd_gdImageOpenPolygon" >&6
-if test $ac_cv_lib_gd_gdImageOpenPolygon = yes; then
-  GD_DEF="$GD_DEF -DGD_HAS_FTEX_XSHOW"
+eval ac_res=\$$as_ac_Lib
+	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
+$as_echo "$ac_res" >&6; }
+if eval test \"x\$"$as_ac_Lib"\" = x"yes"; then :
+  SDE_ENABLED=-DUSE_SDE
 fi
 
 
-    echo "$as_me:$LINENO: checking for gdImageGifPtr in -lgd" >&5
-echo $ECHO_N "checking for gdImageGifPtr in -lgd... $ECHO_C" >&6
-if test "${ac_cv_lib_gd_gdImageGifPtr+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+  if test -n "$SDE_ENABLED" ; then
+      SDE_LIB="-lsde$SDE_VERSION -lpe$SDE_VERSION -lsg$SDE_VERSION"
+      { $as_echo "$as_me:${as_lineno-$LINENO}: checking for main in -lpthread" >&5
+$as_echo_n "checking for main in -lpthread... " >&6; }
+if ${ac_cv_lib_pthread_main+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
   ac_check_lib_save_LIBS=$LIBS
-LIBS="-lgd $GD_LIB $GD_XTRA_LIBS $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+LIBS="-lpthread  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char gdImageGifPtr ();
+
 int
 main ()
 {
-gdImageGifPtr ();
+return main ();
   ;
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_gd_gdImageGifPtr=yes
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_pthread_main=yes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-ac_cv_lib_gd_gdImageGifPtr=no
+  ac_cv_lib_pthread_main=no
 fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 LIBS=$ac_check_lib_save_LIBS
 fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_gd_gdImageGifPtr" >&5
-echo "${ECHO_T}$ac_cv_lib_gd_gdImageGifPtr" >&6
-if test $ac_cv_lib_gd_gdImageGifPtr = yes; then
-  GD_DEF="$GD_DEF -DGD_HAS_GDIMAGEGIFPTR"
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_pthread_main" >&5
+$as_echo "$ac_cv_lib_pthread_main" >&6; }
+if test "x$ac_cv_lib_pthread_main" = xyes; then :
+  SDE_LIB="$SDE_LIB -lpthread"
 fi
 
-
-      echo "$as_me:$LINENO: checking for gdFontGetTiny in -lgd" >&5
-echo $ECHO_N "checking for gdFontGetTiny in -lgd... $ECHO_C" >&6
-if test "${ac_cv_lib_gd_gdFontGetTiny+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+      { $as_echo "$as_me:${as_lineno-$LINENO}: checking for main in -lsocket" >&5
+$as_echo_n "checking for main in -lsocket... " >&6; }
+if ${ac_cv_lib_socket_main+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
   ac_check_lib_save_LIBS=$LIBS
-LIBS="-lgd $GD_LIB $GD_XTRA_LIBS $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+LIBS="-lsocket  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char gdFontGetTiny ();
+
 int
 main ()
 {
-gdFontGetTiny ();
+return main ();
   ;
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_gd_gdFontGetTiny=yes
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_socket_main=yes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-ac_cv_lib_gd_gdFontGetTiny=no
+  ac_cv_lib_socket_main=no
 fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 LIBS=$ac_check_lib_save_LIBS
 fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_gd_gdFontGetTiny" >&5
-echo "${ECHO_T}$ac_cv_lib_gd_gdFontGetTiny" >&6
-if test $ac_cv_lib_gd_gdFontGetTiny = yes; then
-  GD_DEF="$GD_DEF -DGD_HAS_GETBITMAPFONTS"
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_socket_main" >&5
+$as_echo "$ac_cv_lib_socket_main" >&6; }
+if test "x$ac_cv_lib_socket_main" = xyes; then :
+  SDE_LIB="$SDE_LIB -lsocket"
 fi
 
-
-    GD_RESOLUTION_SUPPORT=no
-  as_ac_Lib=`echo "ac_cv_lib_$GD_CHECKLIB''_gdImageSetResolution" | $as_tr_sh`
-echo "$as_me:$LINENO: checking for gdImageSetResolution in -l$GD_CHECKLIB" >&5
-echo $ECHO_N "checking for gdImageSetResolution in -l$GD_CHECKLIB... $ECHO_C" >&6
-if eval "test \"\${$as_ac_Lib+set}\" = set"; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+      { $as_echo "$as_me:${as_lineno-$LINENO}: checking for main in -ldl" >&5
+$as_echo_n "checking for main in -ldl... " >&6; }
+if ${ac_cv_lib_dl_main+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
   ac_check_lib_save_LIBS=$LIBS
-LIBS="-l$GD_CHECKLIB $GD_STATIC $GD_LIB $GD_XTRA_LIBS $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+LIBS="-ldl  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char gdImageSetResolution ();
+
 int
 main ()
 {
-gdImageSetResolution ();
+return main ();
   ;
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  eval "$as_ac_Lib=yes"
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_dl_main=yes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-eval "$as_ac_Lib=no"
+  ac_cv_lib_dl_main=no
 fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 LIBS=$ac_check_lib_save_LIBS
 fi
-echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Lib'}'`" >&5
-echo "${ECHO_T}`eval echo '${'$as_ac_Lib'}'`" >&6
-if test `eval echo '${'$as_ac_Lib'}'` = yes; then
-  GD_RESOLUTION_SUPPORT=yes
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dl_main" >&5
+$as_echo "$ac_cv_lib_dl_main" >&6; }
+if test "x$ac_cv_lib_dl_main" = xyes; then :
+  SDE_LIB="$SDE_LIB -ldl"
 fi
 
+      { $as_echo "$as_me:${as_lineno-$LINENO}: result:         using ESRI SDE from system libs." >&5
+$as_echo "        using ESRI SDE from system libs." >&6; }
+  else
+      { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING:         ESRI SDE not found in system libs... use --with-sde=DIR." >&5
+$as_echo "$as_me: WARNING:         ESRI SDE not found in system libs... use --with-sde=DIR." >&2;}
+  fi
+
+elif test -n "$with_sde" -a "$with_sde" != "no" ; then
+
 
-  if test "$GD_RESOLUTION_SUPPORT" = "yes"; then
-     GD_DEF="$GD_DEF -DUSE_GD_RESOLUTION"
+  if test -z "$with_sde" || echo "$with_sde" | grep '^/' >/dev/null ; then
+    SDE_DIR="$with_sde"
+  else
+    SDE_DIR="`pwd`/$with_sde"
   fi
 
-        GD_HAS_GET_TRUE_COLOR_PIXEL=
-  echo "$as_me:$LINENO: checking whether gdImageGetTrueColorPixel is declared" >&5
-echo $ECHO_N "checking whether gdImageGetTrueColorPixel is declared... $ECHO_C" >&6
-if test "${ac_cv_have_decl_gdImageGetTrueColorPixel+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+
+  test -f $SDE_DIR/arcsde/coverages/include/sdetype.h && SDE_INCDIR="$SDE_DIR/arcsde/coverages/include"
+  test -f $SDE_DIR/include/sdetype.h && SDE_INCDIR="$SDE_DIR/include"
+  test -f $SDE_DIR/sdetype.h && SDE_INCDIR="$SDE_DIR"
+
+  test -f $SDE_DIR/lib/libsde$SDE_VERSION.a && SDE_LIBDIR="$SDE_DIR/lib"
+  test -f $SDE_DIR/lib64/libsde$SDE_VERSION.a && SDE_LIBDIR="$SDE_DIR/lib64"
+  test -f $SDE_DIR/libsde$SDE_VERSION.a && SDE_LIBDIR="$SDE_DIR"
+
+  test -f $SDE_DIR/lib/libsde$SDE_VERSION.so -o -f $SDE_DIR/lib/libsde$SDE_VERSION.sl && SDE_LIBDIR="$SDE_DIR/lib"
+  test -f $SDE_DIR/lib64/libsde$SDE_VERSION.so -o -f $SDE_DIR/lib64/libsde$SDE_VERSION.sl && SDE_LIBDIR="$SDE_DIR/lib64"
+  test -f $SDE_DIR/libsde$SDE_VERSION.so -o -f $SDE_DIR/libsde$SDE_VERSION.sl && SDE_LIBDIR="$SDE_DIR"
+
+  if test -n "$SDE_INCDIR" -a -n "$SDE_LIBDIR" ; then
+      SDE_INC=-I$SDE_INCDIR
+      SDE_LIB="-L$SDE_LIBDIR -lsde$SDE_VERSION -lpe$SDE_VERSION -lsg$SDE_VERSION"
+      { $as_echo "$as_me:${as_lineno-$LINENO}: checking for main in -lpthread" >&5
+$as_echo_n "checking for main in -lpthread... " >&6; }
+if ${ac_cv_lib_pthread_main+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-lpthread  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
-#include <gd.h>
+
 
 int
 main ()
 {
-#ifndef gdImageGetTrueColorPixel
-  char *p = (char *) gdImageGetTrueColorPixel;
-#endif
-
+return main ();
   ;
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest.$ac_objext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_have_decl_gdImageGetTrueColorPixel=yes
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_pthread_main=yes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-ac_cv_have_decl_gdImageGetTrueColorPixel=no
+  ac_cv_lib_pthread_main=no
 fi
-rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
 fi
-echo "$as_me:$LINENO: result: $ac_cv_have_decl_gdImageGetTrueColorPixel" >&5
-echo "${ECHO_T}$ac_cv_have_decl_gdImageGetTrueColorPixel" >&6
-if test $ac_cv_have_decl_gdImageGetTrueColorPixel = yes; then
-  GD_HAS_GET_TRUE_COLOR_PIXEL=yes
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_pthread_main" >&5
+$as_echo "$ac_cv_lib_pthread_main" >&6; }
+if test "x$ac_cv_lib_pthread_main" = xyes; then :
+  SDE_LIB="$SDE_LIB -lpthread"
 fi
 
-    if test .$GD_HAS_GET_TRUE_COLOR_PIXEL = .yes ; then
-    echo "$as_me:$LINENO: checking for gdImageGetTrueColorPixel in -lgd" >&5
-echo $ECHO_N "checking for gdImageGetTrueColorPixel in -lgd... $ECHO_C" >&6
-if test "${ac_cv_lib_gd_gdImageGetTrueColorPixel+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+      { $as_echo "$as_me:${as_lineno-$LINENO}: checking for main in -lsocket" >&5
+$as_echo_n "checking for main in -lsocket... " >&6; }
+if ${ac_cv_lib_socket_main+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
   ac_check_lib_save_LIBS=$LIBS
-LIBS="-lgd $GD_STATIC $GD_LIB $GD_XTRA_LIBS $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+LIBS="-lsocket  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char gdImageGetTrueColorPixel ();
+
 int
 main ()
 {
-gdImageGetTrueColorPixel ();
+return main ();
   ;
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_gd_gdImageGetTrueColorPixel=yes
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_socket_main=yes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-ac_cv_lib_gd_gdImageGetTrueColorPixel=no
+  ac_cv_lib_socket_main=no
 fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 LIBS=$ac_check_lib_save_LIBS
 fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_gd_gdImageGetTrueColorPixel" >&5
-echo "${ECHO_T}$ac_cv_lib_gd_gdImageGetTrueColorPixel" >&6
-if test $ac_cv_lib_gd_gdImageGetTrueColorPixel = yes; then
-  GD_DEF="$GD_DEF -DGD_HAS_GET_TRUE_COLOR_PIXEL"
-fi
-
-  fi
-
-  if test -n "$GD_DEF" ; then
-      GD_LIB="-lgd $GD_LIB"
-      echo "$as_me:$LINENO: result:         using GD ($GD_DEF) from system libs." >&5
-echo "${ECHO_T}        using GD ($GD_DEF) from system libs." >&6
-  fi
-fi
-
-GD_LIB="$GD_LIB $GD_XTRA_LIBS"
-
-GD_DEF=$GD_DEF
-
-GD_INC=$GD_INC
-
-GD_LIB=$GD_LIB
-
-GD_STATIC=$GD_STATIC
-
-MAKE_GD=$MAKE_GD
-
-MAKE_GD_CLEAN=$MAKE_GD_CLEAN
-
-
-ALL_ENABLED="$GD_DEF $ALL_ENABLED"
-ALL_INC="$GD_INC $ALL_INC"
-ALL_LIB="$GD_LIB $ALL_LIB"
-ALL_STATIC_LIB="$GD_STATIC $ALL_STATIC_LIB"
-
-LIBS="$ms_saved_LIBS"
-
-
-
-echo "$as_me:$LINENO: checking if FTGL support requested" >&5
-echo $ECHO_N "checking if FTGL support requested... $ECHO_C" >&6
-
-# Check whether --with-ftgl or --without-ftgl was given.
-if test "${with_ftgl+set}" = set; then
-  withval="$with_ftgl"
-
-fi;
-
-if test "$with_ftgl" = "yes" ; then
-  with_ftgl="/usr"
-  echo "$as_me:$LINENO: result: looking for ftgl libs in /usr" >&5
-echo "${ECHO_T}looking for ftgl libs in /usr" >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_socket_main" >&5
+$as_echo "$ac_cv_lib_socket_main" >&6; }
+if test "x$ac_cv_lib_socket_main" = xyes; then :
+  SDE_LIB="$SDE_LIB -lsocket"
 fi
-if test -n "$with_ftgl" -a "$with_ftgl" != "no" ; then
-
-
-  if test -z "$with_ftgl" || echo "$with_ftgl" | grep '^/' >/dev/null ; then
-    FTGL_DIR="$with_ftgl"
-  else
-    FTGL_DIR="`pwd`/$with_ftgl"
-  fi
-
-
-  FTGL_FLAG=""
-  if  test -f $FTGL_DIR/include/FTGL/ftgl.h -a -f $FTGL_DIR/include/FTGL/FTGLTextureFont.h ; then
-      FTGL_INCLUDE="-I$FTGL_DIR/include/FTGL/"
-  elif  test -f $FTGL_DIR/include/FTGL/FTGL.h -a -f $FTGL_DIR/include/FTGL/FTGLTextureFont.h ; then
-      FTGL_INCLUDE="-I$FTGL_DIR/include/FTGL/"
-      FTGL_FLAG="-DUSE_FTGL_2_1_2"
-  fi
-
-  if test -z "$FTGL_INCLUDE" ; then
-      { { echo "$as_me:$LINENO: error: \"could not find ftgl.h/FTGL.h in $FTGL_DIR/include/FTGL.\"" >&5
-echo "$as_me: error: \"could not find ftgl.h/FTGL.h in $FTGL_DIR/include/FTGL.\"" >&2;}
-   { (exit 1); exit 1; }; }
-  fi
-
-  test -f $FTGL_DIR/lib/libftgl.so && FTGL_LIBDIR="$FTGL_DIR/lib"
-  test -f $FTGL_DIR/lib/libftgl.dylib && FTGL_LIBDIR="$FTGL_DIR/lib"
-  test -f $FTGL_DIR/lib64/libftgl.so && FTGL_LIBDIR="$FTGL_DIR/lib64"
-
-  if test -z "$FTGL_LIBDIR" ; then
-      { { echo "$as_me:$LINENO: error: \"could not find libftgl in $FTGL_DIR.\"" >&5
-echo "$as_me: error: \"could not find libftgl in $FTGL_DIR.\"" >&2;}
-   { (exit 1); exit 1; }; }
-  fi
-
-
-
-    FTGL_ENABLED="-DUSE_FTGL $FTGL_FLAG"
-  FTGL_INC="$FTGL_INCLUDE"
-  FTGL_LIB="-L$FTGL_LIBDIR -lftgl"
-
-  if test ""$FTGL_LIBDIR"" != "/usr/lib"; then
-
-  if test -z ""$FTGL_LIBDIR"" || echo ""$FTGL_LIBDIR"" | grep '^/' >/dev/null ; then
-    ai_p=""$FTGL_LIBDIR""
-  else
-    ai_p="`pwd`/"$FTGL_LIBDIR""
-  fi
-
-
-  unique=`echo $ac_n "$ai_p$ac_c" | tr -c -d a-zA-Z0-9`
-  cmd="echo $ac_n \"\$LIBPATH$unique$ac_c\""
-  if test -n "$unique" && test "`eval $cmd`" = "" ; then
-    eval "LIBPATH$unique=set"
-
-      EXTRA_LIBS="$EXTRA_LIBS -L$ai_p"
-        RPATHS="$RPATHS ${ld_runpath_switch}$ai_p"
-
-  fi
-
-  fi
-
-
-  echo "$as_me:$LINENO: result: using ftgl from $FTGL_DIR" >&5
-echo "${ECHO_T}using ftgl from $FTGL_DIR" >&6
 
+      { $as_echo "$as_me:${as_lineno-$LINENO}: checking for main in -ldl" >&5
+$as_echo_n "checking for main in -ldl... " >&6; }
+if ${ac_cv_lib_dl_main+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-ldl  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
 
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
-
-fi
-
-FTGL_ENABLED=$FTGL_ENABLED
-
-FTGL_INC=$FTGL_INC
-
-FTGL_LIB=$FTGL_LIB
-
-
-
-ALL_ENABLED="$FTGL_ENABLED $ALL_ENABLED"
-ALL_INC="$FTGL_INC $ALL_INC"
-ALL_LIB="$FTGL_LIB $ALL_LIB"
-
-
-
-echo "$as_me:$LINENO: checking if OGL support requested" >&5
-echo $ECHO_N "checking if OGL support requested... $ECHO_C" >&6
-
-# Check whether --with-ogl or --without-ogl was given.
-if test "${with_ogl+set}" = set; then
-  withval="$with_ogl"
-
-fi;
-
-if test "$with_opengl" = "yes" ; then
 
-  with_opengl="/usr"
-  echo "$as_me:$LINENO: result: looking for opengl libs in /usr" >&5
-echo "${ECHO_T}looking for opengl libs in /usr" >&6
+int
+main ()
+{
+return main ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_dl_main=yes
+else
+  ac_cv_lib_dl_main=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dl_main" >&5
+$as_echo "$ac_cv_lib_dl_main" >&6; }
+if test "x$ac_cv_lib_dl_main" = xyes; then :
+  SDE_LIB="$SDE_LIB -ldl"
 fi
-if test -n "$with_opengl" -a "$with_opengl" != "no" ; then
-
-  if test -z "$FTGL_LIB" ; then
-     { { echo "$as_me:$LINENO: error: FTGL required for opengl support - please configure --with-ftgl." >&5
-echo "$as_me: error: FTGL required for opengl support - please configure --with-ftgl." >&2;}
-   { (exit 1); exit 1; }; }
-  fi
-
-
-  if test -z "$with_opengl" || echo "$with_opengl" | grep '^/' >/dev/null ; then
-    OGL_DIR="$with_opengl"
-  else
-    OGL_DIR="`pwd`/$with_opengl"
-  fi
-
-
-  test -f $OGL_DIR/include/GL/gl.h -a -f $OGL_DIR/include/GL/glx.h -a -f $OGL_DIR/include/GL/glu.h && OGL_INCLUDE="-I$OGL_DIR/include"
-
-  if test -z "$OGL_INCLUDE" ; then
-      { { echo "$as_me:$LINENO: error: \"could not find gl.h in $OGL_DIR/include/.\"" >&5
-echo "$as_me: error: \"could not find gl.h in $OGL_DIR/include/.\"" >&2;}
-   { (exit 1); exit 1; }; }
-  fi
-
-  test -f $OGL_DIR/lib/libGL.so -a -f $OGL_DIR/lib/libGLU.so && OGL_LIBDIR="$OGL_DIR/lib"
-  test -f $OGL_DIR/lib/libGL.dylib -a -f $OGL_DIR/lib/libGLU.dylib && OGL_LIBDIR="$OGL_DIR/lib"
-  test -f $OGL_DIR/lib64/libGL.so -a -f $OGL_DIR/lib64/libGLU.so && OGL_LIBDIR="$OGL_DIR/lib64"
-
-  if test -z "$OGL_LIBDIR" ; then
-      { { echo "$as_me:$LINENO: error: \"could not find libGL or libGLU in $OGL_DIR/lib/ or $OGL_DIR/lib64/.\"" >&5
-echo "$as_me: error: \"could not find libGL or libGLU in $OGL_DIR/lib/ or $OGL_DIR/lib64/.\"" >&2;}
-   { (exit 1); exit 1; }; }
-  fi
-
-
 
-    OGL_ENABLED="-DUSE_OGL"
-  OGL_INC="$OGL_INCLUDE"
-  OGL_LIB="-L$OGL_LIBDIR -lGL -lGLU"
 
-  if test ""$OGL_LIBDIR"" != "/usr/lib"; then
+  if test ""$SDE_LIBDIR"" != "/usr/lib"; then
 
-  if test -z ""$OGL_LIBDIR"" || echo ""$OGL_LIBDIR"" | grep '^/' >/dev/null ; then
-    ai_p=""$OGL_LIBDIR""
+  if test -z ""$SDE_LIBDIR"" || echo ""$SDE_LIBDIR"" | grep '^/' >/dev/null ; then
+    ai_p=""$SDE_LIBDIR""
   else
-    ai_p="`pwd`/"$OGL_LIBDIR""
+    ai_p="`pwd`/"$SDE_LIBDIR""
   fi
 
 
@@ -9945,1542 +18185,1253 @@ echo "$as_me: error: \"could not find libGL or libGLU in $OGL_DIR/lib/ or $OGL_D
 
   fi
 
+  else
+      as_fn_error $? "\"Could not find sdetype.h or libsde$SDE_VERSION.a/libsde$SDE_VERSION.so in $SDE_DIR.\"" "$LINENO" 5
+  fi
 
-  echo "$as_me:$LINENO: result: using opengl from $OGL_DIR" >&5
-echo "${ECHO_T}using opengl from $OGL_DIR" >&6
+  SDE_ENABLED=-DUSE_SDE
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result:         using ESRI SDE from $SDE_DIR." >&5
+$as_echo "        using ESRI SDE from $SDE_DIR." >&6; }
 
 else
 
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
-
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result:         ESRI SDE support not requested." >&5
+$as_echo "        ESRI SDE support not requested." >&6; }
 fi
 
-OGL_ENABLED=$OGL_ENABLED
+SDE_ENABLED=$SDE_ENABLED
 
-OGL_INC=$OGL_INC
+SDE_INC=$SDE_INC
+
+SDE_LIB=$SDE_LIB
 
-OGL_LIB=$OGL_LIB
 
+ALL_ENABLED="$SDE_ENABLED $ALL_ENABLED"
+ALL_INC="$SDE_INC $ALL_INC"
+ALL_LIB="$SDE_LIB $ALL_LIB"
 
 
-ALL_ENABLED="$OGL_ENABLED $ALL_ENABLED"
-ALL_INC="$OGL_INC $ALL_INC"
-ALL_LIB="$OGL_LIB $ALL_LIB"
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if GEOS support requested" >&5
+$as_echo_n "checking if GEOS support requested... " >&6; }
 
 
+# Check whether --with-geos was given.
+if test "${with_geos+set}" = set; then :
+  withval=$with_geos;
+fi
+
+
+if test -n "$with_geos" -a "$with_geos" != "no" ; then
 
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
 
+  GEOS_CONFIG=$with_geos
+
+  if test "$GEOS_CONFIG" = "yes" ; then
 
-# Check whether --with-expat or --without-expat was given.
-if test "${with_expat+set}" = set; then
-  withval="$with_expat"
-  EXPAT_DIR=$withval
+    # Extract the first word of "geos-config", so it can be a program name with args.
+set dummy geos-config; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_path_GEOS_CONFIG+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
-  EXPAT_DIR=''
-fi;
+  case $GEOS_CONFIG in
+  [\\/]* | ?:[\\/]*)
+  ac_cv_path_GEOS_CONFIG="$GEOS_CONFIG" # Let the user override the test with a path.
+  ;;
+  *)
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_path_GEOS_CONFIG="$as_dir/$ac_word$ac_exec_ext"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+  test -z "$ac_cv_path_GEOS_CONFIG" && ac_cv_path_GEOS_CONFIG="no"
+  ;;
+esac
+fi
+GEOS_CONFIG=$ac_cv_path_GEOS_CONFIG
+if test -n "$GEOS_CONFIG"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $GEOS_CONFIG" >&5
+$as_echo "$GEOS_CONFIG" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
 
 
-  if test -z "$EXPAT_DIR" || echo "$EXPAT_DIR" | grep '^/' >/dev/null ; then
-    EXPAT_DIR="$EXPAT_DIR"
+
+    if test "$GEOS_CONFIG" = "no" ; then
+      as_fn_error $? "couldn't find geos-config in default path. Please specify full path to geos-config" "$LINENO" 5
+    fi
+
+  elif test -f "$GEOS_CONFIG" -a -x "$GEOS_CONFIG" ; then
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: user supplied geos-config ($GEOS_CONFIG)" >&5
+$as_echo "user supplied geos-config ($GEOS_CONFIG)" >&6; }
   else
-    EXPAT_DIR="`pwd`/$EXPAT_DIR"
+    as_fn_error $? "'$GEOS_CONFIG' is not an executable.  Make sure you use --with-geos=/path/to/geos-config" "$LINENO" 5
   fi
 
-{ echo "$as_me:$LINENO: checking where EXPAT is installed..." >&5
-echo "$as_me: checking where EXPAT is installed..." >&6;}
-EXPAT_LIB=''
-EXPAT_INC=''
-EXPAT_FOUND='no'
 
+  min_geos_version=3.0.0
 
-if test -n "$EXPAT_DIR" ; then
-    test -f $EXPAT_DIR/lib/libexpat.a -o -f $EXPAT_DIR/lib/libexpat.so -o -f $EXPAT_DIR/lib/libexpat.sl -o -f $EXPAT_DIR/lib/libexpat.dylib && EXPAT_LIBDIR="$PNG_DIR/lib"
-    test -f $EXPAT_DIR/lib64/libexpat.a -o -f $EXPAT_DIR/lib64/libexpat.so -o -f $EXPAT_DIR/lib64/libexpat.sl -o -f $EXPAT_DIR/libexpat.dylib && EXPAT_LIBDIR="$PNG_DIR/lib64"
-    test -f $EXPAT_DIR/libexpat.a -o -f $EXPAT_DIR/libexpat.so -o -f $EXPAT_DIR/libexpat.sl -o -f $PNG_DIR/libexpat.dylib && EXPAT_LIBDIR="$PNG_DIR"
-    test -f $EXPAT_DIR/include/expat.h && EXPAT_INCDIR="$EXPAT_DIR/include"
-    test -f $EXPAT_DIR/lib/expat.h && EXPAT_INCDIR="$EXPAT_DIR/lib"
-    test -f $EXPAT_DIR/expat.h && EXPAT_INCDIR="$EXPAT_DIR"
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for GEOS version >= $min_geos_version" >&5
+$as_echo_n "checking for GEOS version >= $min_geos_version... " >&6; }
 
-    if test -n "$EXPAT_LIBDIR" ; then
-      EXPAT_LIB="-L$EXPAT_LIBDIR -lexpat"
-      echo "$as_me:$LINENO: result:         using libexpat from $EXPAT_LIB" >&5
-echo "${ECHO_T}        using libexpat from $EXPAT_LIB" >&6
+  geos_major_version=`$GEOS_CONFIG --version | \
+       sed 's/\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\).*/\1/'`
+  geos_minor_version=`$GEOS_CONFIG --version | \
+       sed 's/\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\).*/\2/'`
+  geos_micro_version=`$GEOS_CONFIG --version | \
+       sed 's/\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\).*/\3/'`
 
-  if test ""$EXPAT_LIBDIR"" != "/usr/lib"; then
+  req_major=`echo $min_geos_version | \
+       sed 's/\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\).*/\1/'`
+  req_minor=`echo $min_geos_version | \
+       sed 's/\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\).*/\2/'`
+  req_micro=`echo $min_geos_version | \
+       sed 's/\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\).*/\3/'`
 
-  if test -z ""$EXPAT_LIBDIR"" || echo ""$EXPAT_LIBDIR"" | grep '^/' >/dev/null ; then
-    ai_p=""$EXPAT_LIBDIR""
+  ac_req_version=`expr $req_major \* 100000 \+  $req_minor \* 100 \+ $req_micro`
+  ac_geos_version=`expr $geos_major_version \* 100000 \+  $geos_minor_version \* 100 \+ $geos_micro_version`
+
+  if test $ac_req_version -le $ac_geos_version; then
+     { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes. Found version ${geos_major_version}.${geos_minor_version}.${geos_micro_version}" >&5
+$as_echo "yes. Found version ${geos_major_version}.${geos_minor_version}.${geos_micro_version}" >&6; }
   else
-    ai_p="`pwd`/"$EXPAT_LIBDIR""
+     { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+     as_fn_error $? "geos-config reports version ${geos_major_version}.${geos_minor_version}.${geos_micro_version}, need at least $min_geos_version or configure --without-geos" "$LINENO" 5
   fi
 
 
-  unique=`echo $ac_n "$ai_p$ac_c" | tr -c -d a-zA-Z0-9`
-  cmd="echo $ac_n \"\$LIBPATH$unique$ac_c\""
-  if test -n "$unique" && test "`eval $cmd`" = "" ; then
-    eval "LIBPATH$unique=set"
 
-      EXTRA_LIBS="$EXTRA_LIBS -L$ai_p"
-        RPATHS="$RPATHS ${ld_runpath_switch}$ai_p"
+  GEOS_ENABLED=-DUSE_GEOS
 
+  GEOS_INCDIR=`$GEOS_CONFIG --includes`
+  GEOS_INC="-I$GEOS_INCDIR"
+    if test $ac_geos_version -ge 300300; then
+     GEOS_LIB="`$GEOS_CONFIG --clibs`"
+  else
+     GEOS_LIB="`$GEOS_CONFIG --libs`_c"
   fi
 
-  fi
+  GEOS_ENABLED=$GEOS_ENABLED
 
-    else
-      { { echo "$as_me:$LINENO: error: cannot find expat lib in $EXPAT_DIR" >&5
-echo "$as_me: error: cannot find expat lib in $EXPAT_DIR" >&2;}
-   { (exit 1); exit 1; }; }
-    fi
+  GEOS_INC=$GEOS_INC
+
+  GEOS_LIB=$GEOS_LIB
+
+
+  ALL_ENABLED="$GEOS_ENABLED $ALL_ENABLED"
+  ALL_INC="$GEOS_INC $ALL_INC"
+  ALL_LIB="$GEOS_LIB $ALL_LIB"
 
-    if test -n "$EXPAT_INCDIR" ; then
-      as_ac_Header=`echo "ac_cv_header_$EXPAT_INCDIR/expat.h" | $as_tr_sh`
-if eval "test \"\${$as_ac_Header+set}\" = set"; then
-  echo "$as_me:$LINENO: checking for $EXPAT_INCDIR/expat.h" >&5
-echo $ECHO_N "checking for $EXPAT_INCDIR/expat.h... $ECHO_C" >&6
-if eval "test \"\${$as_ac_Header+set}\" = set"; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-fi
-echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Header'}'`" >&5
-echo "${ECHO_T}`eval echo '${'$as_ac_Header'}'`" >&6
-else
-  # Is the header compilable?
-echo "$as_me:$LINENO: checking $EXPAT_INCDIR/expat.h usability" >&5
-echo $ECHO_N "checking $EXPAT_INCDIR/expat.h usability... $ECHO_C" >&6
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
-#include <$EXPAT_INCDIR/expat.h>
-_ACEOF
-rm -f conftest.$ac_objext
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest.$ac_objext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_header_compiler=yes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
 
-ac_header_compiler=no
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+
 fi
-rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
-echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
-echo "${ECHO_T}$ac_header_compiler" >&6
 
-# Is the header present?
-echo "$as_me:$LINENO: checking $EXPAT_INCDIR/expat.h presence" >&5
-echo $ECHO_N "checking $EXPAT_INCDIR/expat.h presence... $ECHO_C" >&6
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#include <$EXPAT_INCDIR/expat.h>
-_ACEOF
-if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5
-  (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } >/dev/null; then
-  if test -s conftest.err; then
-    ac_cpp_err=$ac_c_preproc_warn_flag
-    ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
-  else
-    ac_cpp_err=
-  fi
-else
-  ac_cpp_err=yes
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we should include OGR support..." >&5
+$as_echo "$as_me: checking whether we should include OGR support..." >&6;}
+
+# Check whether --with-ogr was given.
+if test "${with_ogr+set}" = set; then :
+  withval=$with_ogr;
 fi
-if test -z "$ac_cpp_err"; then
-  ac_header_preproc=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
 
-  ac_header_preproc=no
+
+if test "`basename xx/$with_ogr`" = "gdal-config" ; then
+  GDAL_CONFIG="$with_ogr"
 fi
-rm -f conftest.err conftest.$ac_ext
-echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
-echo "${ECHO_T}$ac_header_preproc" >&6
 
-# So?  What about this header?
-case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
-  yes:no: )
-    { echo "$as_me:$LINENO: WARNING: $EXPAT_INCDIR/expat.h: accepted by the compiler, rejected by the preprocessor!" >&5
-echo "$as_me: WARNING: $EXPAT_INCDIR/expat.h: accepted by the compiler, rejected by the preprocessor!" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $EXPAT_INCDIR/expat.h: proceeding with the compiler's result" >&5
-echo "$as_me: WARNING: $EXPAT_INCDIR/expat.h: proceeding with the compiler's result" >&2;}
-    ac_header_preproc=yes
-    ;;
-  no:yes:* )
-    { echo "$as_me:$LINENO: WARNING: $EXPAT_INCDIR/expat.h: present but cannot be compiled" >&5
-echo "$as_me: WARNING: $EXPAT_INCDIR/expat.h: present but cannot be compiled" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $EXPAT_INCDIR/expat.h:     check for missing prerequisite headers?" >&5
-echo "$as_me: WARNING: $EXPAT_INCDIR/expat.h:     check for missing prerequisite headers?" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $EXPAT_INCDIR/expat.h: see the Autoconf documentation" >&5
-echo "$as_me: WARNING: $EXPAT_INCDIR/expat.h: see the Autoconf documentation" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $EXPAT_INCDIR/expat.h:     section \"Present But Cannot Be Compiled\"" >&5
-echo "$as_me: WARNING: $EXPAT_INCDIR/expat.h:     section \"Present But Cannot Be Compiled\"" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $EXPAT_INCDIR/expat.h: proceeding with the preprocessor's result" >&5
-echo "$as_me: WARNING: $EXPAT_INCDIR/expat.h: proceeding with the preprocessor's result" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $EXPAT_INCDIR/expat.h: in the future, the compiler will take precedence" >&5
-echo "$as_me: WARNING: $EXPAT_INCDIR/expat.h: in the future, the compiler will take precedence" >&2;}
-    (
-      cat <<\_ASBOX
-## ------------------------------------------ ##
-## Report this to the AC_PACKAGE_NAME lists.  ##
-## ------------------------------------------ ##
-_ASBOX
-    ) |
-      sed "s/^/$as_me: WARNING:     /" >&2
-    ;;
+if test "$with_ogr" = "yes" ; then
+ # Extract the first word of "gdal-config", so it can be a program name with args.
+set dummy gdal-config; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_path_GDAL_CONFIG+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  case $GDAL_CONFIG in
+  [\\/]* | ?:[\\/]*)
+  ac_cv_path_GDAL_CONFIG="$GDAL_CONFIG" # Let the user override the test with a path.
+  ;;
+  *)
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_path_GDAL_CONFIG="$as_dir/$ac_word$ac_exec_ext"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+  test -z "$ac_cv_path_GDAL_CONFIG" && ac_cv_path_GDAL_CONFIG="no"
+  ;;
 esac
-echo "$as_me:$LINENO: checking for $EXPAT_INCDIR/expat.h" >&5
-echo $ECHO_N "checking for $EXPAT_INCDIR/expat.h... $ECHO_C" >&6
-if eval "test \"\${$as_ac_Header+set}\" = set"; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+fi
+GDAL_CONFIG=$ac_cv_path_GDAL_CONFIG
+if test -n "$GDAL_CONFIG"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $GDAL_CONFIG" >&5
+$as_echo "$GDAL_CONFIG" >&6; }
 else
-  eval "$as_ac_Header=\$ac_header_preproc"
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
-echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Header'}'`" >&5
-echo "${ECHO_T}`eval echo '${'$as_ac_Header'}'`" >&6
 
+
+
+  if test "$GDAL_CONFIG" = "no" ; then
+    as_fn_error $? "couldn't find gdal-config" "$LINENO" 5
+  fi
 fi
-if test `eval echo '${'$as_ac_Header'}'` = yes; then
-  EXPAT_INC=-I$EXPAT_INCDIR
+
+if test -n "$GDAL_CONFIG" -a "$with_ogr" != "no" ; then
+
+
+  if test x`$GDAL_CONFIG --ogr-enabled` = "xyes" ; then
+      OGR_ENABLED=-DUSE_OGR
+      { $as_echo "$as_me:${as_lineno-$LINENO}: result:         OGR enabled ($OGR_ENABLED)." >&5
+$as_echo "        OGR enabled ($OGR_ENABLED)." >&6; }
+  else
+      { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING:         OGR not available." >&5
+$as_echo "$as_me: WARNING:         OGR not available." >&2;}
+  fi
+
 else
-  { { echo "$as_me:$LINENO: error: cannot find expat headers" >&5
-echo "$as_me: error: cannot find expat headers" >&2;}
-   { (exit 1); exit 1; }; }
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result:         OGR support not requested." >&5
+$as_echo "        OGR support not requested." >&6; }
 fi
 
 
-      ALL_INC="$EXPAT_INC $ALL_INC"
-    else
-        { { echo "$as_me:$LINENO: error: cannot find expat headers in $EXPAT_DIR" >&5
-echo "$as_me: error: cannot find expat headers in $EXPAT_DIR" >&2;}
-   { (exit 1); exit 1; }; }
-    fi
-    EXPAT_FOUND="yes"
-else
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if GDAL support requested" >&5
+$as_echo_n "checking if GDAL support requested... " >&6; }
 
 
-  echo "$as_me:$LINENO: checking for XML_ParserCreate in -lexpat" >&5
-echo $ECHO_N "checking for XML_ParserCreate in -lexpat... $ECHO_C" >&6
-if test "${ac_cv_lib_expat_XML_ParserCreate+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-lexpat  $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
+# Check whether --with-gdal was given.
+if test "${with_gdal+set}" = set; then :
+  withval=$with_gdal;
+fi
 
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char XML_ParserCreate ();
-int
-main ()
-{
-XML_ParserCreate ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_expat_XML_ParserCreate=yes
+
+if test "$with_gdal" = "yes" ; then
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+
+  if test "`basename xx/$with_gdal`" = "gdal-config" ; then
+    GDAL_CONFIG="$with_gdal"
+  fi
+
+  if test -z "$GDAL_CONFIG" ; then
+    # Extract the first word of "gdal-config", so it can be a program name with args.
+set dummy gdal-config; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_path_GDAL_CONFIG+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
+  case $GDAL_CONFIG in
+  [\\/]* | ?:[\\/]*)
+  ac_cv_path_GDAL_CONFIG="$GDAL_CONFIG" # Let the user override the test with a path.
+  ;;
+  *)
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_path_GDAL_CONFIG="$as_dir/$ac_word$ac_exec_ext"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
 
-ac_cv_lib_expat_XML_ParserCreate=no
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
+  test -z "$ac_cv_path_GDAL_CONFIG" && ac_cv_path_GDAL_CONFIG="no"
+  ;;
+esac
 fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_expat_XML_ParserCreate" >&5
-echo "${ECHO_T}$ac_cv_lib_expat_XML_ParserCreate" >&6
-if test $ac_cv_lib_expat_XML_ParserCreate = yes; then
-  EXPAT_LIB="-lexpat"
+GDAL_CONFIG=$ac_cv_path_GDAL_CONFIG
+if test -n "$GDAL_CONFIG"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $GDAL_CONFIG" >&5
+$as_echo "$GDAL_CONFIG" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
 
-  if test "${ac_cv_header_expat_h+set}" = set; then
-  echo "$as_me:$LINENO: checking for expat.h" >&5
-echo $ECHO_N "checking for expat.h... $ECHO_C" >&6
-if test "${ac_cv_header_expat_h+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-fi
-echo "$as_me:$LINENO: result: $ac_cv_header_expat_h" >&5
-echo "${ECHO_T}$ac_cv_header_expat_h" >&6
-else
-  # Is the header compilable?
-echo "$as_me:$LINENO: checking expat.h usability" >&5
-echo $ECHO_N "checking expat.h usability... $ECHO_C" >&6
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
-#include <expat.h>
-_ACEOF
-rm -f conftest.$ac_objext
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest.$ac_objext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_header_compiler=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
 
-ac_header_compiler=no
-fi
-rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
-echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
-echo "${ECHO_T}$ac_header_compiler" >&6
+  fi
 
-# Is the header present?
-echo "$as_me:$LINENO: checking expat.h presence" >&5
-echo $ECHO_N "checking expat.h presence... $ECHO_C" >&6
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#include <expat.h>
-_ACEOF
-if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5
-  (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } >/dev/null; then
-  if test -s conftest.err; then
-    ac_cpp_err=$ac_c_preproc_warn_flag
-    ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
+  if test "$GDAL_CONFIG" = "no" ; then
+    as_fn_error $? "couldn't find gdal-config" "$LINENO" 5
+  fi
+
+  GDAL_ENABLED=-DUSE_GDAL
+
+elif test -n "$with_gdal" -a "$with_gdal" != "no" ; then
+
+  GDAL_CONFIG=$with_gdal
+
+  if test -f "$GDAL_CONFIG" -a -x "$GDAL_CONFIG" ; then
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, user supplied gdal-config ($GDAL_CONFIG)" >&5
+$as_echo "yes, user supplied gdal-config ($GDAL_CONFIG)" >&6; }
   else
-    ac_cpp_err=
+    as_fn_error $? "'$GDAL_CONFIG' is not an executable.  Make sure you use --with-gdal=/path/to/gdal-config" "$LINENO" 5
   fi
-else
-  ac_cpp_err=yes
-fi
-if test -z "$ac_cpp_err"; then
-  ac_header_preproc=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
 
-  ac_header_preproc=no
-fi
-rm -f conftest.err conftest.$ac_ext
-echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
-echo "${ECHO_T}$ac_header_preproc" >&6
+  GDAL_ENABLED=-DUSE_GDAL
 
-# So?  What about this header?
-case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
-  yes:no: )
-    { echo "$as_me:$LINENO: WARNING: expat.h: accepted by the compiler, rejected by the preprocessor!" >&5
-echo "$as_me: WARNING: expat.h: accepted by the compiler, rejected by the preprocessor!" >&2;}
-    { echo "$as_me:$LINENO: WARNING: expat.h: proceeding with the compiler's result" >&5
-echo "$as_me: WARNING: expat.h: proceeding with the compiler's result" >&2;}
-    ac_header_preproc=yes
-    ;;
-  no:yes:* )
-    { echo "$as_me:$LINENO: WARNING: expat.h: present but cannot be compiled" >&5
-echo "$as_me: WARNING: expat.h: present but cannot be compiled" >&2;}
-    { echo "$as_me:$LINENO: WARNING: expat.h:     check for missing prerequisite headers?" >&5
-echo "$as_me: WARNING: expat.h:     check for missing prerequisite headers?" >&2;}
-    { echo "$as_me:$LINENO: WARNING: expat.h: see the Autoconf documentation" >&5
-echo "$as_me: WARNING: expat.h: see the Autoconf documentation" >&2;}
-    { echo "$as_me:$LINENO: WARNING: expat.h:     section \"Present But Cannot Be Compiled\"" >&5
-echo "$as_me: WARNING: expat.h:     section \"Present But Cannot Be Compiled\"" >&2;}
-    { echo "$as_me:$LINENO: WARNING: expat.h: proceeding with the preprocessor's result" >&5
-echo "$as_me: WARNING: expat.h: proceeding with the preprocessor's result" >&2;}
-    { echo "$as_me:$LINENO: WARNING: expat.h: in the future, the compiler will take precedence" >&5
-echo "$as_me: WARNING: expat.h: in the future, the compiler will take precedence" >&2;}
-    (
-      cat <<\_ASBOX
-## ------------------------------------------ ##
-## Report this to the AC_PACKAGE_NAME lists.  ##
-## ------------------------------------------ ##
-_ASBOX
-    ) |
-      sed "s/^/$as_me: WARNING:     /" >&2
-    ;;
-esac
-echo "$as_me:$LINENO: checking for expat.h" >&5
-echo $ECHO_N "checking for expat.h... $ECHO_C" >&6
-if test "${ac_cv_header_expat_h+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
 else
-  ac_cv_header_expat_h=$ac_header_preproc
-fi
-echo "$as_me:$LINENO: result: $ac_cv_header_expat_h" >&5
-echo "${ECHO_T}$ac_cv_header_expat_h" >&6
 
-fi
-if test $ac_cv_header_expat_h = yes; then
-  :
-else
-  EXPAT_HEADER_FOUND="no"
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+
 fi
 
 
-  if test -n "$EXPAT_LIB" -a "$EXPAT_HEADER_FOUND" != "no"; then
-    echo "$as_me:$LINENO: result:         using libexpat from system libs." >&5
-echo "${ECHO_T}        using libexpat from system libs." >&6
-    EXPAT_FOUND='yes'
-  else
-    echo "$as_me:$LINENO: result:         not found in system libs. svg symbol support will be disabled" >&5
-echo "${ECHO_T}        not found in system libs. svg symbol support will be disabled" >&6
-    EXPAT_FOUND='no'
-  fi
+if test -n "$GDAL_ENABLED" -o "$OGR_ENABLED"; then
+
+  GDAL_LIB=`$GDAL_CONFIG --libs`
+  GDAL_INC=`$GDAL_CONFIG --cflags`
 
 fi
 
+GDAL_ENABLED=$GDAL_ENABLED
+
+OGR_ENABLED=$OGR_ENABLED
 
-echo "$as_me:$LINENO: checking for AGG support" >&5
-echo $ECHO_N "checking for AGG support... $ECHO_C" >&6
-AGG_ENABLED="internal"
-echo "$as_me:$LINENO: result:         yes" >&5
-echo "${ECHO_T}        yes" >&6
-AGG_OBJ="renderers/agg/src/clipper.o renderers/agg/src/agg_arc.o renderers/agg/src/agg_curves.o renderers/agg/src/agg_vcgen_contour.o renderers/agg/src/agg_vcgen_dash.o renderers/agg/src/agg_vcgen_stroke.o renderers/agg/src/agg_image_filters.o renderers/agg/src/agg_line_aa_basics.o renderers/agg/src/agg_line_profile_aa.o renderers/agg/src/agg_sqrt_tables.o renderers/agg/src/agg_embedded_raster_fonts.o renderers/agg/src/agg_trans_affine.o renderers/agg/src/agg_vpgen_clip_polygon.o renderers/agg/src/agg_vpgen_clip_polyline.o renderers/agg/src/agg_font_freetype.o"
-AGG_LIB=""
-AGG_INC="-Irenderers/agg/include"
-ALL_INC="$AGG_INC $ALL_INC"
+GDAL_INC=$GDAL_INC
 
+GDAL_LIB=$GDAL_LIB
 
-echo "$as_me:$LINENO: checking if SVG Symbol support requested" >&5
-echo $ECHO_N "checking if SVG Symbol support requested... $ECHO_C" >&6
 
-# Check whether --with-agg-svg-symbols or --without-agg-svg-symbols was given.
-if test "${with_agg_svg_symbols+set}" = set; then
-  withval="$with_agg_svg_symbols"
+ALL_ENABLED="$GDAL_ENABLED $OGR_ENABLED $ALL_ENABLED"
+ALL_INC="$GDAL_INC $ALL_INC"
+ALL_LIB="$GDAL_LIB $ALL_LIB"
 
-fi;
 
 
-if test "$with_agg_svg_symbols" != "no" ; then
-    if test "$EXPAT_FOUND" = "yes" ; then
-                AGG_OBJ="$AGG_OBJ renderers/agg/src/agg_svg_parser.o renderers/agg/src/agg_svg_path_renderer.o renderers/agg/src/agg_svg_path_tokenizer.o"
-        AGG_LIB="$AGG_LIB $EXPAT_LIB"
-        AGG_LIB=$AGG_LIB
 
-        ALL_LIB="$AGG_LIB $ALL_LIB"
-        AGG_INC="$AGG_INC $EXPAT_INC"
-        AGG_INC=$AGG_INC
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if PostGIS support requested" >&5
+$as_echo_n "checking if PostGIS support requested... " >&6; }
 
-        ALL_INC="$AGG_INC $ALL_INC"
-        AGG_SVG_SYMBOLS_ENABLED="-DUSE_AGG_SVG_SYMBOLS"
-        ALL_ENABLED="$AGG_SVG_SYMBOLS_ENABLED $ALL_ENABLED"
-        echo "$as_me:$LINENO: result:         enabled" >&5
-echo "${ECHO_T}        enabled" >&6
 
-    else
-        echo "$as_me:$LINENO: result:         disabled due to missing expat dependency" >&5
-echo "${ECHO_T}        disabled due to missing expat dependency" >&6
-    fi
+# Check whether --with-postgis was given.
+if test "${with_postgis+set}" = set; then :
+  withval=$with_postgis;
 fi
 
-AGG_OBJ=$AGG_OBJ
-
 
+if test "$with_postgis" = "no" -o "$with_postgis" = "" ; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+  PG_CONFIG="no"
+elif test "$with_postgis" = "yes" ; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+  # Extract the first word of "pg_config", so it can be a program name with args.
+set dummy pg_config; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_path_PG_CONFIG+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  case $PG_CONFIG in
+  [\\/]* | ?:[\\/]*)
+  ac_cv_path_PG_CONFIG="$PG_CONFIG" # Let the user override the test with a path.
+  ;;
+  *)
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_path_PG_CONFIG="$as_dir/$ac_word$ac_exec_ext"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
 
+  test -z "$ac_cv_path_PG_CONFIG" && ac_cv_path_PG_CONFIG="no"
+  ;;
+esac
+fi
+PG_CONFIG=$ac_cv_path_PG_CONFIG
+if test -n "$PG_CONFIG"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $PG_CONFIG" >&5
+$as_echo "$PG_CONFIG" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
 
 
+else
+  PG_CONFIG=$with_postgis
+fi
 
+if test "$PG_CONFIG" = "no" ; then
+  POSTGIS_ENABLED=
+  POSTGIS_INC=
+  POSTGIS_LIB=
+else
+  POSTGIS_ENABLED=
 
-unset ac_cv_lib_proj_pj_init
-unset ac_cv_lib_proj_pj_transform
-unset ac_cv_lib_proj_pj_latlong_from_proj
+  if test -f "$PG_CONFIG" -a -x "$PG_CONFIG" ; then
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, user supplied pg_config ($PG_CONFIG)" >&5
+$as_echo "yes, user supplied pg_config ($PG_CONFIG)" >&6; }
+  else
+    as_fn_error $? "'$PG_CONFIG' is not an executable.  Make sure you use --with-postgis=/path/to/pg_config" "$LINENO" 5
+  fi
 
-{ echo "$as_me:$LINENO: checking whether we should include PROJ.4 support..." >&5
-echo "$as_me: checking whether we should include PROJ.4 support..." >&6;}
+  POSTGIS_EXTRALIBS="`$PG_CONFIG --libs`"
+    if test $? -ne 0 ; then
+      POSTGIS_EXTRALIBS=
+  fi
 
-# Check whether --with-proj or --without-proj was given.
-if test "${with_proj+set}" = set; then
-  withval="$with_proj"
+  POSTGIS_INC="-I`$PG_CONFIG --includedir`"
 
-fi;
+  old_LDFLAGS="$LDFLAGS"
 
-if test "$with_proj" = "yes" ; then
+  POSTGIS_LIB="-L`$PG_CONFIG --libdir` -lpq"
+  LDFLAGS="$LDFLAGS $POSTGIS_LIB"
 
-  echo "$as_me:$LINENO: checking for pj_init in -lproj" >&5
-echo $ECHO_N "checking for pj_init in -lproj... $ECHO_C" >&6
-if test "${ac_cv_lib_proj_pj_init+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for PQconnectdb in -lpq" >&5
+$as_echo_n "checking for PQconnectdb in -lpq... " >&6; }
+if ${ac_cv_lib_pq_PQconnectdb+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
   ac_check_lib_save_LIBS=$LIBS
-LIBS="-lproj  $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+LIBS="-lpq  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
-/* Override any gcc2 internal prototype to avoid an error.  */
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
 #ifdef __cplusplus
 extern "C"
 #endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char pj_init ();
+char PQconnectdb ();
 int
 main ()
 {
-pj_init ();
+return PQconnectdb ();
   ;
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_proj_pj_init=yes
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_pq_PQconnectdb=yes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-ac_cv_lib_proj_pj_init=no
+  ac_cv_lib_pq_PQconnectdb=no
 fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 LIBS=$ac_check_lib_save_LIBS
 fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_proj_pj_init" >&5
-echo "${ECHO_T}$ac_cv_lib_proj_pj_init" >&6
-if test $ac_cv_lib_proj_pj_init = yes; then
-  PROJ_ENABLED=-DUSE_PROJ
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_pq_PQconnectdb" >&5
+$as_echo "$ac_cv_lib_pq_PQconnectdb" >&6; }
+if test "x$ac_cv_lib_pq_PQconnectdb" = xyes; then :
+  POSTGIS_ENABLED="-DUSE_POSTGIS"
 fi
 
-  echo "$as_me:$LINENO: checking for pj_transform in -lproj" >&5
-echo $ECHO_N "checking for pj_transform in -lproj... $ECHO_C" >&6
-if test "${ac_cv_lib_proj_pj_transform+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+
+    if test  "$POSTGIS_ENABLED"x = x ; then
+    POSTGIS_LIB="$POSTGIS_LIB $POSTGIS_EXTRALIBS"
+    LDFLAGS="$old_LDFLAGS $POSTGIS_LIB"
+    unset ac_cv_lib_pq_PQconnectdb
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for PQconnectdb in -lpq" >&5
+$as_echo_n "checking for PQconnectdb in -lpq... " >&6; }
+if ${ac_cv_lib_pq_PQconnectdb+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
   ac_check_lib_save_LIBS=$LIBS
-LIBS="-lproj  $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+LIBS="-lpq  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
-/* Override any gcc2 internal prototype to avoid an error.  */
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
 #ifdef __cplusplus
 extern "C"
 #endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char pj_transform ();
+char PQconnectdb ();
 int
 main ()
 {
-pj_transform ();
+return PQconnectdb ();
   ;
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_proj_pj_transform=yes
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_pq_PQconnectdb=yes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
+  ac_cv_lib_pq_PQconnectdb=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_pq_PQconnectdb" >&5
+$as_echo "$ac_cv_lib_pq_PQconnectdb" >&6; }
+if test "x$ac_cv_lib_pq_PQconnectdb" = xyes; then :
+  POSTGIS_ENABLED="-DUSE_POSTGIS"
+fi
+
+  fi
+
+    if test "$POSTGIS_ENABLED" = "-DUSE_POSTGIS" ; then
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for PQserverVersion in -lpq" >&5
+$as_echo_n "checking for PQserverVersion in -lpq... " >&6; }
+if ${ac_cv_lib_pq_PQserverVersion+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-lpq  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
 
-ac_cv_lib_proj_pj_transform=no
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char PQserverVersion ();
+int
+main ()
+{
+return PQserverVersion ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_pq_PQserverVersion=yes
+else
+  ac_cv_lib_pq_PQserverVersion=no
 fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 LIBS=$ac_check_lib_save_LIBS
 fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_proj_pj_transform" >&5
-echo "${ECHO_T}$ac_cv_lib_proj_pj_transform" >&6
-if test $ac_cv_lib_proj_pj_transform = yes; then
-  PJ_TRANSFORM=yes
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_pq_PQserverVersion" >&5
+$as_echo "$ac_cv_lib_pq_PQserverVersion" >&6; }
+if test "x$ac_cv_lib_pq_PQserverVersion" = xyes; then :
+  POSTGIS_ENABLED="$POSTGIS_ENABLED -DPOSTGIS_HAS_SERVER_VERSION"
+fi
+
+  fi
+
+  LDFLAGS="$old_LDFLAGS"
+
+fi
+
+POSTGIS_ENABLED=$POSTGIS_ENABLED
+
+POSTGIS_INC=$POSTGIS_INC
+
+POSTGIS_LIB=$POSTGIS_LIB
+
+
+ALL_ENABLED="$POSTGIS_ENABLED $ALL_ENABLED"
+ALL_INC="$POSTGIS_INC $ALL_INC"
+ALL_LIB="$POSTGIS_LIB $ALL_LIB"
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if Mysql support requested" >&5
+$as_echo_n "checking if Mysql support requested... " >&6; }
+
+
+# Check whether --with-mysql was given.
+if test "${with_mysql+set}" = set; then :
+  withval=$with_mysql;
+fi
+
+
+if test "$with_mysql" = "no" -o "$with_mysql" = "" ; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+  MY_CONFIG="no"
+elif test "$with_mysql" = "yes" ; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+  # Extract the first word of "mysql_config", so it can be a program name with args.
+set dummy mysql_config; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_path_MY_CONFIG+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  case $MY_CONFIG in
+  [\\/]* | ?:[\\/]*)
+  ac_cv_path_MY_CONFIG="$MY_CONFIG" # Let the user override the test with a path.
+  ;;
+  *)
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_path_MY_CONFIG="$as_dir/$ac_word$ac_exec_ext"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+  test -z "$ac_cv_path_MY_CONFIG" && ac_cv_path_MY_CONFIG="no"
+  ;;
+esac
+fi
+MY_CONFIG=$ac_cv_path_MY_CONFIG
+if test -n "$MY_CONFIG"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MY_CONFIG" >&5
+$as_echo "$MY_CONFIG" >&6; }
 else
-  PJ_TRANSFORM=no
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
 
 
-  if test -n "$PROJ_ENABLED" -a "$PJ_TRANSFORM" = "no"; then
-      { { echo "$as_me:$LINENO: error: This version of PROJ is too old.  PROJ4.4.2 or later is required." >&5
-echo "$as_me: error: This version of PROJ is too old.  PROJ4.4.2 or later is required." >&2;}
-   { (exit 1); exit 1; }; }
-  elif test -n "$PROJ_ENABLED" -a "$PJ_TRANSFORM" = "yes"; then
-      PROJ_LIBS="-lproj"
-      echo "$as_me:$LINENO: result:         using PROJ.4 from system libs." >&5
-echo "${ECHO_T}        using PROJ.4 from system libs." >&6
+else
+  MY_CONFIG=$with_mysql
+fi
+
+if test "$MY_CONFIG" = "no" ; then
+  MYSQL_ENABLED=
+  MYSQL_INC=
+  MYSQL_LIB=
+else
+  if test -f "$MY_CONFIG" -a -x "$MY_CONFIG" ; then
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, user supplied mysql_config ($MY_CONFIG)" >&5
+$as_echo "yes, user supplied mysql_config ($MY_CONFIG)" >&6; }
   else
-      { echo "$as_me:$LINENO: WARNING:         PROJ.4 not found in system libs... use --with-proj=DIR." >&5
-echo "$as_me: WARNING:         PROJ.4 not found in system libs... use --with-proj=DIR." >&2;}
+    as_fn_error $? "'$MY_CONFIG' is not an executable.  Make sure you use --with-mysql=/path/to/mysql_config" "$LINENO" 5
   fi
 
-elif test -n "$with_proj" -a "$with_proj" != "no" ; then
+  MYSQL_ENABLED=-DUSE_MYSQL
+  MYSQL_LIB="`$MY_CONFIG --libs` -lmysqlclient"
+#  MYSQL_LIB="-L/usr/lib/mysql -lmysqlclient"
+  MYSQL_INC="`$MY_CONFIG --cflags`"
+#  MYSQL_INC="-I/usr/include/mysql"
+fi
 
+MYSQL_ENABLED=$MYSQL_ENABLED
 
-  if test -z "$with_proj" || echo "$with_proj" | grep '^/' >/dev/null ; then
-    PROJ_DIR="$with_proj"
-  else
-    PROJ_DIR="`pwd`/$with_proj"
-  fi
+MYSQL_INC=$MYSQL_INC
 
-  test -f $PROJ_DIR/include/proj_api.h && PROJ_INCLUDE="$PROJ_DIR/include"
-  test -f $PROJ_DIR/include/proj/proj_api.h && PROJ_INCLUDE="$PROJ_DIR/include/proj"
-  test -f $PROJ_DIR/src/proj_api.h && PROJ_INCLUDE="$PROJ_DIR/src"
-  test -f $PROJ_DIR/proj_api.h && PROJ_INCLUDE="$PROJ_DIR"
+MYSQL_LIB=$MYSQL_LIB
 
-  test -f $PROJ_DIR/src/.libs/libproj.a && PROJ_LIBDIR="$PROJ_DIR/src/.libs"
-  test -f $PROJ_DIR/lib/libproj.a && PROJ_LIBDIR="$PROJ_DIR/lib"
-  test -f $PROJ_DIR/lib64/libproj.a && PROJ_LIBDIR="$PROJ_DIR/lib64"
-  test -f $PROJ_DIR/libproj.a && PROJ_LIBDIR="$PROJ_DIR"
 
-  test -f $PROJ_DIR/src/.libs/libproj.so -o -f $PROJ_DIR/src/.libs/libproj.sl -o -f $PROJ_DIR/src/.libs/libproj.dylib && PROJ_LIBDIR="$PROJ_DIR/src/.libs"
-  test -f $PROJ_DIR/lib/libproj.so -o -f $PROJ_DIR/lib/libproj.sl -o -f $PROJ_DIR/lib/libproj.dylib && PROJ_LIBDIR="$PROJ_DIR/lib"
-  test -f $PROJ_DIR/lib64/libproj.so -o -f $PROJ_DIR/lib64/libproj.sl && PROJ_LIBDIR="$PROJ_DIR/lib64"
-  test -f $PROJ_DIR/libproj.so -o -f $PROJ_DIR/libproj.sl -o -f $PROJ_DIR/libproj.dylib && PROJ_LIBDIR="$PROJ_DIR"
+ALL_ENABLED="$MYSQL_ENABLED $ALL_ENABLED"
+ALL_INC="$MYSQL_INC $ALL_INC"
+ALL_LIB="$MYSQL_LIB $ALL_LIB"
 
-  if test -n "$PROJ_INCLUDE" -a -n "$PROJ_LIBDIR" ; then
-      PROJ_INC=-I$PROJ_INCLUDE
-      PROJ_LIBS="-L$PROJ_LIBDIR -lproj"
 
-  if test ""$PROJ_LIBDIR"" != "/usr/lib"; then
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if OracleSpatial support requested" >&5
+$as_echo_n "checking if OracleSpatial support requested... " >&6; }
 
-  if test -z ""$PROJ_LIBDIR"" || echo ""$PROJ_LIBDIR"" | grep '^/' >/dev/null ; then
-    ai_p=""$PROJ_LIBDIR""
+# Check whether --with-oraclespatial was given.
+if test "${with_oraclespatial+set}" = set; then :
+  withval=$with_oraclespatial;
+fi
+
+
+if test "$with_oraclespatial" = "no" -o "$with_oraclespatial" = ""; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+  ORA_HOME="no"
+elif test "$with_oraclespatial" = "yes"; then
+  if test -d "$ORACLE_HOME"; then
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, set from ORACLE_HOME environment variable" >&5
+$as_echo "yes, set from ORACLE_HOME environment variable" >&6; }
+    ORA_HOME="$ORACLE_HOME"
   else
-    ai_p="`pwd`/"$PROJ_LIBDIR""
+    ORA_HOME="no"
+    as_fn_error $? "ORACLE_HOME variable is not properly set" "$LINENO" 5
   fi
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, user supplied ORACLE_HOME" >&5
+$as_echo "yes, user supplied ORACLE_HOME" >&6; }
+  ORA_HOME=$with_oraclespatial
+fi
 
+if test "$ORA_HOME" = "no" ; then
+  ORACLESPATIAL_ENABLED=
+  ORACLESPATIAL_INC=
+  ORACLESPATIAL_LIB=
+else
 
-  unique=`echo $ac_n "$ai_p$ac_c" | tr -c -d a-zA-Z0-9`
-  cmd="echo $ac_n \"\$LIBPATH$unique$ac_c\""
-  if test -n "$unique" && test "`eval $cmd`" = "" ; then
-    eval "LIBPATH$unique=set"
-
-      EXTRA_LIBS="$EXTRA_LIBS -L$ai_p"
-        RPATHS="$RPATHS ${ld_runpath_switch}$ai_p"
+    test -f $ORA_HOME/lib/libclntsh.so -o -f $ORA_HOME/lib/libclntsh.dylib && ORA_LIBDIR="$ORA_HOME/lib"
+  test -f $ORA_HOME/libclntsh.so -o -f $ORA_HOME/libclntsh.dylib && ORA_LIBDIR="$ORA_HOME"
+  test -f $ORA_HOME/lib/oracle/10*/client/lib/libclntsh.so && ORA_LIBDIR=`dirname $ORA_HOME/lib/oracle/10*/client/lib/libclntsh.so`
+  test -f $ORA_HOME/lib/oracle/10*/client/lib/libclntsh.dylib && ORA_LIBDIR=`dirname $ORA_HOME/lib/oracle/10*/client/lib/libclntsh.dylib`
 
+  if test -z "$ORA_LIBDIR" ; then
+    as_fn_error $? "Oracle Spatial: libclntsh.so not found." "$LINENO" 5
   fi
 
-  fi
+    test -f $ORA_HOME/include/oci.h && ORA_INCDIR="$ORA_HOME/include"
+  test -f $ORA_HOME/sdk/include/oci.h && ORA_INCDIR="$ORA_HOME/sdk/include"
+  test -f $ORA_HOME/rdbms/public/oci.h && ORA_INCDIR="$ORA_HOME/rdbms/public"
+  test -f $ORA_HOME/rdbms/demo/oci.h && ORA_INCDIR="$ORA_HOME/rdbms/public"
+  test -f $ORA_HOME/include/oracle/10*/client/oci.h && ORA_INCDIR=`dirname $ORA_HOME/include/oracle/10*/client/oci.h`
 
-  else
-      { { echo "$as_me:$LINENO: error: \"Could not find proj_api.h or libproj.a/libproj.so in $PROJ_DIR.\"" >&5
-echo "$as_me: error: \"Could not find proj_api.h or libproj.a/libproj.so in $PROJ_DIR.\"" >&2;}
-   { (exit 1); exit 1; }; }
+  if test -z "$ORA_INCDIR" ; then
+    as_fn_error $? "Oracle Spatial: oci.h not found." "$LINENO" 5
   fi
 
-  echo "$as_me:$LINENO: checking for pj_transform in -lproj" >&5
-echo $ECHO_N "checking for pj_transform in -lproj... $ECHO_C" >&6
-if test "${ac_cv_lib_proj_pj_transform+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-lproj $PROJ_LIBS $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
+  ORACLESPATIAL_ENABLED=-DUSE_ORACLESPATIAL
+  ORACLESPATIAL_LIB="-L$ORA_LIBDIR -lclntsh"
+  ORACLESPATIAL_INC="-I$ORA_INCDIR -I$ORA_HOME/rdbms/demo -I$ORA_HOME/rdbms/public"
 
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char pj_transform ();
-int
-main ()
-{
-pj_transform ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_proj_pj_transform=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result:         Oracle Spatial found in $ORA_HOME." >&5
+$as_echo "        Oracle Spatial found in $ORA_HOME." >&6; }
 
-ac_cv_lib_proj_pj_transform=no
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_proj_pj_transform" >&5
-echo "${ECHO_T}$ac_cv_lib_proj_pj_transform" >&6
-if test $ac_cv_lib_proj_pj_transform = yes; then
-  PJ_TRANSFORM=yes
-else
-  PJ_TRANSFORM=no
 fi
 
-  if test "$PJ_TRANSFORM" = "no"; then
-      { { echo "$as_me:$LINENO: error: This version of PROJ is too old.  PROJ4.4.2 or later is required." >&5
-echo "$as_me: error: This version of PROJ is too old.  PROJ4.4.2 or later is required." >&2;}
-   { (exit 1); exit 1; }; }
-  fi
+ORACLESPATIAL_ENABLED=$ORACLESPATIAL_ENABLED
 
-  PROJ_ENABLED=-DUSE_PROJ
-  echo "$as_me:$LINENO: result:         using PROJ.4 from $PROJ_DIR." >&5
-echo "${ECHO_T}        using PROJ.4 from $PROJ_DIR." >&6
+ORACLESPATIAL_INC=$ORACLESPATIAL_INC
 
-else
+ORACLESPATIAL_LIB=$ORACLESPATIAL_LIB
 
-  echo "$as_me:$LINENO: result:         PROJ.4 support not requested." >&5
-echo "${ECHO_T}        PROJ.4 support not requested." >&6
-fi
 
-PROJ_ENABLED=$PROJ_ENABLED
+ALL_ENABLED="$ORACLESPATIAL_ENABLED $ALL_ENABLED"
+ALL_INC="$ORACLESPATIAL_INC $ALL_INC"
+ALL_LIB="$ORACLESPATIAL_LIB $ALL_LIB"
 
-PROJ_INC=$PROJ_INC
 
-PROJ_LIBS=$PROJ_LIBS
 
 
-ALL_ENABLED="$PROJ_ENABLED $ALL_ENABLED"
-ALL_INC="$PROJ_INC $ALL_INC"
-ALL_LIB="$PROJ_LIBS $ALL_LIB"
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we should include WMS Server support..." >&5
+$as_echo "$as_me: checking whether we should include WMS Server support..." >&6;}
 
+# Check whether --with-wms was given.
+if test "${with_wms+set}" = set; then :
+  withval=$with_wms;
+fi
 
-THREAD_LIB=""
-THREAD_FLAG=""
 
-{ echo "$as_me:$LINENO: checking whether we should include thread safe support..." >&5
-echo "$as_me: checking whether we should include thread safe support..." >&6;}
+if test "$with_wms" = "no" ; then
 
-# Check whether --with-threads or --without-threads was given.
-if test "${with_threads+set}" = set; then
-  withval="$with_threads"
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result:         OGC WMS Compatibility disabled by --without-wms." >&5
+$as_echo "        OGC WMS Compatibility disabled by --without-wms." >&6; }
 
-fi;
+elif test -z "$PROJ_ENABLED" ; then
 
-if test "$with_threads" = "yes" ; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result:         OGC WMS Compatibility not enabled (PROJ.4 is required for WMS)." >&5
+$as_echo "        OGC WMS Compatibility not enabled (PROJ.4 is required for WMS)." >&6; }
 
-  echo "$as_me:$LINENO: checking for pthread_create in -lpthread" >&5
-echo $ECHO_N "checking for pthread_create in -lpthread... $ECHO_C" >&6
-if test "${ac_cv_lib_pthread_pthread_create+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
 else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-lpthread  $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
 
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char pthread_create ();
-int
-main ()
-{
-pthread_create ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_pthread_pthread_create=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
+  WMS_SVR_ENABLED="-DUSE_WMS_SVR"
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result:         OGC WMS compatibility enabled ($WMS_SVR_ENABLED)." >&5
+$as_echo "        OGC WMS compatibility enabled ($WMS_SVR_ENABLED)." >&6; }
 
-ac_cv_lib_pthread_pthread_create=no
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_pthread_pthread_create" >&5
-echo "${ECHO_T}$ac_cv_lib_pthread_pthread_create" >&6
-if test $ac_cv_lib_pthread_pthread_create = yes; then
-  THREAD_FLAG=-DUSE_THREAD
 fi
 
+WMS_SVR_ENABLED=$WMS_SVR_ENABLED
 
-  if test -n "$THREAD_FLAG" ; then
-      THREAD_LIB="-lpthread"
-      echo "$as_me:$LINENO: result:         using -lpthread from system libs." >&5
-echo "${ECHO_T}        using -lpthread from system libs." >&6
-  else
-      { { echo "$as_me:$LINENO: error:         -lpthread not found, use --with-thread=<pthread link options>" >&5
-echo "$as_me: error:         -lpthread not found, use --with-thread=<pthread link options>" >&2;}
-   { (exit 1); exit 1; }; }
-  fi
 
-elif test -n "$with_threads" -a "$with_threads" != "no" ; then
+ALL_ENABLED="$WMS_SVR_ENABLED $ALL_ENABLED"
 
-  THREAD_FLAG=-DUSE_THREAD
-  THREAD_LIB="$with_threads"
 
-  echo "$as_me:$LINENO: result:         using threads with link options \"$THREAD_LIB\"." >&5
-echo "${ECHO_T}        using threads with link options \"$THREAD_LIB\"." >&6
 
-else
-  echo "$as_me:$LINENO: result:         thread safe support disabled." >&5
-echo "${ECHO_T}        thread safe support disabled." >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we should include WFS Server support..." >&5
+$as_echo "$as_me: checking whether we should include WFS Server support..." >&6;}
+
+# Check whether --with-wfs was given.
+if test "${with_wfs+set}" = set; then :
+  withval=$with_wfs;
 fi
 
-THREAD_FLAG=$THREAD_FLAG
 
-THREAD_LIB=$THREAD_LIB
+if test "$with_wfs" != "yes" ; then
 
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result:         OGC WFS Server support not requested." >&5
+$as_echo "        OGC WFS Server support not requested." >&6; }
 
-ALL_ENABLED="$THREAD_FLAG $ALL_ENABLED"
-ALL_LIB="$THREAD_LIB $ALL_LIB"
+elif test -z "$OGR_ENABLED" ; then
+
+  as_fn_error $? "OGC WFS Server support cannot be enabled: missing OGR which is required)." "$LINENO" 5
+
+elif test -z "$PROJ_ENABLED" ; then
 
+  as_fn_error $? "OGC WFS Server support cannot be enabled: missing PROJ4 which is required)." "$LINENO" 5
 
-{ echo "$as_me:$LINENO: checking whether we should include ESRI SDE support..." >&5
-echo "$as_me: checking whether we should include ESRI SDE support..." >&6;}
+elif test "$with_wfs" = "yes" ; then
 
-# Check whether --with-sde or --without-sde was given.
-if test "${with_sde+set}" = set; then
-  withval="$with_sde"
+  WFS_SVR_ENABLED="-DUSE_WFS_SVR"
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result:         OGC WFS Server support enabled ($WFS_SVR_ENABLED)." >&5
+$as_echo "        OGC WFS Server support enabled ($WFS_SVR_ENABLED)." >&6; }
 
-fi;
+fi
 
+WFS_SVR_ENABLED=$WFS_SVR_ENABLED
 
-# Check whether --with-sde-version or --without-sde-version was given.
-if test "${with_sde_version+set}" = set; then
-  withval="$with_sde_version"
-  SDE_VERSION=$with_sde_version
-else
-  SDE_VERSION=91
-fi;
 
-if test -z "$SDE_VERSION" -o `expr "$SDE_VERSION" \>\= 92` = 1; then
-SDE_VERSION=""
+ALL_ENABLED="$WFS_SVR_ENABLED $ALL_ENABLED"
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we should include WCS Server support..." >&5
+$as_echo "$as_me: checking whether we should include WCS Server support..." >&6;}
+
+# Check whether --with-wcs was given.
+if test "${with_wcs+set}" = set; then :
+  withval=$with_wcs;
 fi
-if test "$with_sde" = "yes" ; then
 
-  as_ac_Lib=`echo "ac_cv_lib_sde$SDE_VERSION''_SE_connection_create" | $as_tr_sh`
-echo "$as_me:$LINENO: checking for SE_connection_create in -lsde$SDE_VERSION" >&5
-echo $ECHO_N "checking for SE_connection_create in -lsde$SDE_VERSION... $ECHO_C" >&6
-if eval "test \"\${$as_ac_Lib+set}\" = set"; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-lsde$SDE_VERSION  $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
 
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char SE_connection_create ();
-int
-main ()
-{
-SE_connection_create ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  eval "$as_ac_Lib=yes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
+if test "$with_wcs" != "yes" ; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result:         OGC WCS Server support not requested." >&5
+$as_echo "        OGC WCS Server support not requested." >&6; }
+elif test -z "$GDAL_ENABLED" ; then
+  as_fn_error $? "OGC WCS Server support cannot be enabled: missing GDAL which is required)." "$LINENO" 5
+elif test -z "$PROJ_ENABLED" ; then
+  as_fn_error $? "OGC WCS Server support cannot be enabled: missing PROJ4 which is required)." "$LINENO" 5
+elif test "$with_wcs" = "yes" ; then
+  WCS_SVR_ENABLED="-DUSE_WCS_SVR"
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result:         OGC WCS Server support enabled ($WCS_SVR_ENABLED)." >&5
+$as_echo "        OGC WCS Server support enabled ($WCS_SVR_ENABLED)." >&6; }
+fi
+
+WCS_SVR_ENABLED=$WCS_SVR_ENABLED
+
+ALL_ENABLED="$WCS_SVR_ENABLED $ALL_ENABLED"
 
-eval "$as_ac_Lib=no"
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we should include WMS Client Connections support..." >&5
+$as_echo "$as_me: checking whether we should include WMS Client Connections support..." >&6;}
+
+# Check whether --with-wmsclient was given.
+if test "${with_wmsclient+set}" = set; then :
+  withval=$with_wmsclient;
 fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
+
+
+if test "$with_wmsclient" = "no" ; then
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result:         OGC WMS Client Layers disabled by --without-wmsclient." >&5
+$as_echo "        OGC WMS Client Layers disabled by --without-wmsclient." >&6; }
+
+elif test -z "$PROJ_ENABLED" -o -z "$GDAL_ENABLED"; then
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result:         OGC WMS Client Connections not enabled (PROJ.4, libcurl and GDAL required)." >&5
+$as_echo "        OGC WMS Client Connections not enabled (PROJ.4, libcurl and GDAL required)." >&6; }
+
+elif test "$with_wmsclient" = "yes" ; then
+
+    WMS_REQUESTED="yes"
+
 fi
-echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Lib'}'`" >&5
-echo "${ECHO_T}`eval echo '${'$as_ac_Lib'}'`" >&6
-if test `eval echo '${'$as_ac_Lib'}'` = yes; then
-  SDE_ENABLED=-DUSE_SDE
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we should include WFS Client Connections support..." >&5
+$as_echo "$as_me: checking whether we should include WFS Client Connections support..." >&6;}
+
+# Check whether --with-wfsclient was given.
+if test "${with_wfsclient+set}" = set; then :
+  withval=$with_wfsclient;
 fi
 
 
-  if test -n "$SDE_ENABLED" ; then
-      SDE_LIB="-lsde$SDE_VERSION -lpe$SDE_VERSION -lsg$SDE_VERSION"
-      echo "$as_me:$LINENO: checking for main in -lpthread" >&5
-echo $ECHO_N "checking for main in -lpthread... $ECHO_C" >&6
-if test "${ac_cv_lib_pthread_main+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-lpthread  $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
+if test "$with_wfsclient" = "no" ; then
 
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result:         OGC WFS Client Layers disabled by --without-wfsclient." >&5
+$as_echo "        OGC WFS Client Layers disabled by --without-wfsclient." >&6; }
 
-int
-main ()
-{
-main ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_pthread_main=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
+elif test -z "$PROJ_ENABLED" -o -z "$OGR_ENABLED"; then
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result:         OGC WFS Client Connections not enabled (PROJ.4, libcurl and OGR required)." >&5
+$as_echo "        OGC WFS Client Connections not enabled (PROJ.4, libcurl and OGR required)." >&6; }
+
+elif test "$with_wfsclient" = "yes" ; then
+
+    WFS_REQUESTED="yes"
 
-ac_cv_lib_pthread_main=no
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
 fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_pthread_main" >&5
-echo "${ECHO_T}$ac_cv_lib_pthread_main" >&6
-if test $ac_cv_lib_pthread_main = yes; then
-  SDE_LIB="$SDE_LIB -lpthread"
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we should include OGC SOS Server support..." >&5
+$as_echo "$as_me: checking whether we should include OGC SOS Server support..." >&6;}
+
+# Check whether --with-sos was given.
+if test "${with_sos+set}" = set; then :
+  withval=$with_sos;
 fi
 
-      echo "$as_me:$LINENO: checking for main in -lsocket" >&5
-echo $ECHO_N "checking for main in -lsocket... $ECHO_C" >&6
-if test "${ac_cv_lib_socket_main+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-lsocket  $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
 
+if test "x$with_sos" != "xyes" ; then
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result:         OGC SOS Server support not requested." >&5
+$as_echo "        OGC SOS Server support not requested." >&6; }
 
-int
-main ()
-{
-main ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_socket_main=yes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
 
-ac_cv_lib_socket_main=no
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
+  if test -z "$PROJ_ENABLED" ; then
+    as_fn_error $? "        OGC SOS Support requested, but PROJ.4 required and missing." "$LINENO" 5
+  fi
+  if test -z "$OGR_ENABLED" ; then
+    as_fn_error $? "        OGC SOS Support requested, but OGR required and missing." "$LINENO" 5
+  fi
+
+    SOS_REQUESTED="yes"
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result:         OGC SOS Server support requested." >&5
+$as_echo "        OGC SOS Server support requested." >&6; }
+
 fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_socket_main" >&5
-echo "${ECHO_T}$ac_cv_lib_socket_main" >&6
-if test $ac_cv_lib_socket_main = yes; then
-  SDE_LIB="$SDE_LIB -lsocket"
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for curl-config" >&5
+$as_echo_n "checking for curl-config... " >&6; }
+
+# Check whether --with-curl-config was given.
+if test "${with_curl_config+set}" = set; then :
+  withval=$with_curl_config;
 fi
 
-      echo "$as_me:$LINENO: checking for main in -ldl" >&5
-echo $ECHO_N "checking for main in -ldl... $ECHO_C" >&6
-if test "${ac_cv_lib_dl_main+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-ldl  $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
 
+unset ac_cv_path_LIBCURL_CONFIG
 
-int
-main ()
-{
-main ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_dl_main=yes
+if test "$WMS_REQUESTED" = "yes" -o "$WFS_REQUESTED" = "yes" ; then
+
+  if test "`basename xx/$with_curl_config`" = "curl-config" ; then
+    LIBCURL_CONFIG="$with_curl_config"
+    if test -f "$LIBCURL_CONFIG" -a -x "$LIBCURL_CONFIG" ; then
+      { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, user supplied curl-config ($LIBCURL_CONFIG)" >&5
+$as_echo "yes, user supplied curl-config ($LIBCURL_CONFIG)" >&6; }
+    else
+      as_fn_error $? "'$LIBCURL_CONFIG' is not an executable.  Make sure you use --with-curl-config=/path/to/curl-config" "$LINENO" 5
+    fi
+  else
+    # Extract the first word of "curl-config", so it can be a program name with args.
+set dummy curl-config; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_path_LIBCURL_CONFIG+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
+  case $LIBCURL_CONFIG in
+  [\\/]* | ?:[\\/]*)
+  ac_cv_path_LIBCURL_CONFIG="$LIBCURL_CONFIG" # Let the user override the test with a path.
+  ;;
+  *)
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_path_LIBCURL_CONFIG="$as_dir/$ac_word$ac_exec_ext"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
 
-ac_cv_lib_dl_main=no
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
+  test -z "$ac_cv_path_LIBCURL_CONFIG" && ac_cv_path_LIBCURL_CONFIG="no"
+  ;;
+esac
 fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_dl_main" >&5
-echo "${ECHO_T}$ac_cv_lib_dl_main" >&6
-if test $ac_cv_lib_dl_main = yes; then
-  SDE_LIB="$SDE_LIB -ldl"
+LIBCURL_CONFIG=$ac_cv_path_LIBCURL_CONFIG
+if test -n "$LIBCURL_CONFIG"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $LIBCURL_CONFIG" >&5
+$as_echo "$LIBCURL_CONFIG" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
 
-      echo "$as_me:$LINENO: result:         using ESRI SDE from system libs." >&5
-echo "${ECHO_T}        using ESRI SDE from system libs." >&6
-  else
-      { echo "$as_me:$LINENO: WARNING:         ESRI SDE not found in system libs... use --with-sde=DIR." >&5
-echo "$as_me: WARNING:         ESRI SDE not found in system libs... use --with-sde=DIR." >&2;}
+
   fi
 
-elif test -n "$with_sde" -a "$with_sde" != "no" ; then
+  if test "$LIBCURL_CONFIG" = "no" ; then
+    as_fn_error $? "couldn't find curl-config, try using --with-curl-config=PATH" "$LINENO" 5
+  fi
 
+  CURL_VERNUM=`$LIBCURL_CONFIG --vernum`
+  CURL_VER=`$LIBCURL_CONFIG --version | awk '{print $2}'`
+  CURL_FLAGS=""
 
-  if test -z "$with_sde" || echo "$with_sde" | grep '^/' >/dev/null ; then
-    SDE_DIR="$with_sde"
-  else
-    SDE_DIR="`pwd`/$with_sde"
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result:         found libcurl version $CURL_VER" >&5
+$as_echo "        found libcurl version $CURL_VER" >&6; }
+
+    if test -z "$CURL_VERNUM" -o `expr "0x$CURL_VERNUM" \< "0x070a01"` = 1; then
+    as_fn_error $? "libcurl version 7.10.1 or more recent is required." "$LINENO" 5
   fi
 
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for CURLOPT_PROXYAUTH support" >&5
+$as_echo_n "checking for CURLOPT_PROXYAUTH support... " >&6; }
+  if test -z "$CURL_VERNUM" -o `expr "0x$CURL_VERNUM" \>= "0x070a07"` = 1; then
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes." >&5
+$as_echo "yes." >&6; }
+    CURL_FLAGS="-DUSE_CURLOPT_PROXYAUTH"
+  else
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: no." >&5
+$as_echo "no." >&6; }
+  fi
 
-  test -f $SDE_DIR/arcsde/coverages/include/sdetype.h && SDE_INCDIR="$SDE_DIR/arcsde/coverages/include"
-  test -f $SDE_DIR/include/sdetype.h && SDE_INCDIR="$SDE_DIR/include"
-  test -f $SDE_DIR/sdetype.h && SDE_INCDIR="$SDE_DIR"
+      if test "$WMS_REQUESTED" = "yes" ; then
+    WMS_LYR_ENABLED="-DUSE_WMS_LYR"
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result:         OGC WMS Client Connections enabled ($WMS_LYR_ENABLED)." >&5
+$as_echo "        OGC WMS Client Connections enabled ($WMS_LYR_ENABLED)." >&6; }
+  fi
 
-  test -f $SDE_DIR/lib/libsde$SDE_VERSION.a && SDE_LIBDIR="$SDE_DIR/lib"
-  test -f $SDE_DIR/lib64/libsde$SDE_VERSION.a && SDE_LIBDIR="$SDE_DIR/lib64"
-  test -f $SDE_DIR/libsde$SDE_VERSION.a && SDE_LIBDIR="$SDE_DIR"
+  if test "$WFS_REQUESTED" = "yes" ; then
+    WFS_LYR_ENABLED="-DUSE_WFS_LYR"
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result:         OGC WFS Client Connections enabled ($WFS_LYR_ENABLED)." >&5
+$as_echo "        OGC WFS Client Connections enabled ($WFS_LYR_ENABLED)." >&6; }
+  fi
 
-  test -f $SDE_DIR/lib/libsde$SDE_VERSION.so -o -f $SDE_DIR/lib/libsde$SDE_VERSION.sl && SDE_LIBDIR="$SDE_DIR/lib"
-  test -f $SDE_DIR/lib64/libsde$SDE_VERSION.so -o -f $SDE_DIR/lib64/libsde$SDE_VERSION.sl && SDE_LIBDIR="$SDE_DIR/lib64"
-  test -f $SDE_DIR/libsde$SDE_VERSION.so -o -f $SDE_DIR/libsde$SDE_VERSION.sl && SDE_LIBDIR="$SDE_DIR"
+  CURL_INC=`$LIBCURL_CONFIG --cflags`
+  CURL_LIB=`$LIBCURL_CONFIG --libs`
+  CURL_ENABLED="-DUSE_CURL $CURL_FLAGS"
 
-  if test -n "$SDE_INCDIR" -a -n "$SDE_LIBDIR" ; then
-      SDE_INC=-I$SDE_INCDIR
-      SDE_LIB="-L$SDE_LIBDIR -lsde$SDE_VERSION -lpe$SDE_VERSION -lsg$SDE_VERSION"
-      echo "$as_me:$LINENO: checking for main in -lpthread" >&5
-echo $ECHO_N "checking for main in -lpthread... $ECHO_C" >&6
-if test "${ac_cv_lib_pthread_main+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-lpthread  $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
+fi
 
+CURL_INC=$CURL_INC
 
-int
-main ()
-{
-main ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_pthread_main=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
+CURL_LIB=$CURL_LIB
 
-ac_cv_lib_pthread_main=no
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_pthread_main" >&5
-echo "${ECHO_T}$ac_cv_lib_pthread_main" >&6
-if test $ac_cv_lib_pthread_main = yes; then
-  SDE_LIB="$SDE_LIB -lpthread"
-fi
 
-      echo "$as_me:$LINENO: checking for main in -lsocket" >&5
-echo $ECHO_N "checking for main in -lsocket... $ECHO_C" >&6
-if test "${ac_cv_lib_socket_main+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-lsocket  $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
+ALL_INC="$CURL_INC $ALL_INC"
+ALL_LIB="$CURL_LIB $ALL_LIB"
 
 
-int
-main ()
-{
-main ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_socket_main=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
 
-ac_cv_lib_socket_main=no
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_socket_main" >&5
-echo "${ECHO_T}$ac_cv_lib_socket_main" >&6
-if test $ac_cv_lib_socket_main = yes; then
-  SDE_LIB="$SDE_LIB -lsocket"
+# Check whether --with-kml was given.
+if test "${with_kml+set}" = set; then :
+  withval=$with_kml;
 fi
 
-      echo "$as_me:$LINENO: checking for main in -ldl" >&5
-echo $ECHO_N "checking for main in -ldl... $ECHO_C" >&6
-if test "${ac_cv_lib_dl_main+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-ldl  $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
 
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if KML output is requested" >&5
+$as_echo_n "checking if KML output is requested... " >&6; }
+KML_REQUESTED=""
 
-int
-main ()
-{
-main ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_dl_main=yes
+if test "$with_kml" = "yes"; then
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+    KML_REQUESTED="yes"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-ac_cv_lib_dl_main=no
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_dl_main" >&5
-echo "${ECHO_T}$ac_cv_lib_dl_main" >&6
-if test $ac_cv_lib_dl_main = yes; then
-  SDE_LIB="$SDE_LIB -ldl"
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
 
 
-  if test ""$SDE_LIBDIR"" != "/usr/lib"; then
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if exempi support requested" >&5
+$as_echo_n "checking if exempi support requested... " >&6; }
 
-  if test -z ""$SDE_LIBDIR"" || echo ""$SDE_LIBDIR"" | grep '^/' >/dev/null ; then
-    ai_p=""$SDE_LIBDIR""
-  else
-    ai_p="`pwd`/"$SDE_LIBDIR""
-  fi
+# Check whether --with-exempi was given.
+if test "${with_exempi+set}" = set; then :
+  withval=$with_exempi;
+fi
 
 
-  unique=`echo $ac_n "$ai_p$ac_c" | tr -c -d a-zA-Z0-9`
-  cmd="echo $ac_n \"\$LIBPATH$unique$ac_c\""
-  if test -n "$unique" && test "`eval $cmd`" = "" ; then
-    eval "LIBPATH$unique=set"
+if test -n "$with_exempi" -a "$with_exempi" != "no" ; then
 
-      EXTRA_LIBS="$EXTRA_LIBS -L$ai_p"
-        RPATHS="$RPATHS ${ld_runpath_switch}$ai_p"
+  if test "$with_exempi" = "yes" ; then
+    if test -f /usr/include/exempi-2.0/exempi/xmp.h; then
+        EXEMPI_INC="-I/usr/include/exempi-2.0/exempi"
+        EXEMPI_LIB="-lexempi"
+    else
+        ac_fn_c_check_header_mongrel "$LINENO" "xmp.h" "ac_cv_header_xmp_h" "$ac_includes_default"
+if test "x$ac_cv_header_xmp_h" = xyes; then :
 
-  fi
+else
+  as_fn_error $? "cannot find xmp.h" "$LINENO" 5
+fi
 
-  fi
 
+        EXEMPI_INC=""
+        EXEMPI_LIB="-lexempi"
+    fi
   else
-      { { echo "$as_me:$LINENO: error: \"Could not find sdetype.h or libsde$SDE_VERSION.a/libsde$SDE_VERSION.so in $SDE_DIR.\"" >&5
-echo "$as_me: error: \"Could not find sdetype.h or libsde$SDE_VERSION.a/libsde$SDE_VERSION.so in $SDE_DIR.\"" >&2;}
-   { (exit 1); exit 1; }; }
-  fi
+    xmp_dir=$with_exempi
+    xmp_include=$xmp_dir/include
+    xmp_lib=$xmp_dir/lib
+    xmp_found=
+    for xmp_subdir in / /exempi /exempi-2.0/exempi; do
+      as_ac_Header=`$as_echo "ac_cv_header_$xmp_include$xmp_subdir/xmp.h" | $as_tr_sh`
+ac_fn_c_check_header_mongrel "$LINENO" "$xmp_include$xmp_subdir/xmp.h" "$as_ac_Header" "$ac_includes_default"
+if eval test \"x\$"$as_ac_Header"\" = x"yes"; then :
+  xmp_found=$xmp_subdir
+fi
 
-  SDE_ENABLED=-DUSE_SDE
-  echo "$as_me:$LINENO: result:         using ESRI SDE from $SDE_DIR." >&5
-echo "${ECHO_T}        using ESRI SDE from $SDE_DIR." >&6
 
+    done
+    if test "x$xmp_found" = "x" ; then
+      as_fn_error $? "cannot find xmp.h in $xmp_include" "$LINENO" 5
+    else
+      EXEMPI_INC="-I$xmp_include$xmp_subdir"
+    fi
+    EXEMPI_LIB="-L$xmp_lib -lexempi"
+  fi
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for xmp_init in -lexempi" >&5
+$as_echo_n "checking for xmp_init in -lexempi... " >&6; }
+if ${ac_cv_lib_exempi_xmp_init+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-lexempi $EXEMPI_LIB $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
 
-  echo "$as_me:$LINENO: result:         ESRI SDE support not requested." >&5
-echo "${ECHO_T}        ESRI SDE support not requested." >&6
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char xmp_init ();
+int
+main ()
+{
+return xmp_init ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_exempi_xmp_init=yes
+else
+  ac_cv_lib_exempi_xmp_init=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_exempi_xmp_init" >&5
+$as_echo "$ac_cv_lib_exempi_xmp_init" >&6; }
+if test "x$ac_cv_lib_exempi_xmp_init" = xyes; then :
+  EXEMPI_ENABLED=-DUSE_EXEMPI
 fi
 
-SDE_ENABLED=$SDE_ENABLED
 
-SDE_INC=$SDE_INC
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
 
-SDE_LIB=$SDE_LIB
+EXEMPI_ENABLED=$EXEMPI_ENABLED
 
+EXEMPI_INC=$EXEMPI_INC
 
-ALL_ENABLED="$SDE_ENABLED $ALL_ENABLED"
-ALL_INC="$SDE_INC $ALL_INC"
-ALL_LIB="$SDE_LIB $ALL_LIB"
+EXEMPI_LIB=$EXEMPI_LIB
 
+ALL_ENABLED="$EXEMPI_ENABLED $ALL_ENABLED"
 
-echo "$as_me:$LINENO: checking if GEOS support requested" >&5
-echo $ECHO_N "checking if GEOS support requested... $ECHO_C" >&6
 
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for libxml2" >&5
+$as_echo_n "checking for libxml2... " >&6; }
 
-# Check whether --with-geos or --without-geos was given.
-if test "${with_geos+set}" = set; then
-  withval="$with_geos"
 
-fi;
+# Check whether --with-xml2-config was given.
+if test "${with_xml2_config+set}" = set; then :
+  withval=$with_xml2_config;
+fi
 
-if test -n "$with_geos" -a "$with_geos" != "no" ; then
 
-  echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6
+unset ac_cv_path_LIBXML2_CONFIG
 
-  GEOS_CONFIG=$with_geos
 
-  if test "$GEOS_CONFIG" = "yes" ; then
+if test -z "$with_xml2_config" ; then
+  if test "x$SOS_REQUESTED" = "xyes" ; then
+    with_xml2_config=yes
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: libxml2 required." >&5
+$as_echo "libxml2 required." >&6; }
+  elif test "x$KML_REQUESTED" = "xyes" ; then
+    with_xml2_config=yes
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: libxml2 required." >&5
+$as_echo "libxml2 required." >&6; }
+  elif test "x$WCS_SVR_ENABLED" != "x" ; then
+    with_xml2_config=yes
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: libxml2 requested for WCS Server." >&5
+$as_echo "libxml2 requested for WCS Server." >&6; }
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result:       If unavailable disable using --without-xml2-config," >&5
+$as_echo "      If unavailable disable using --without-xml2-config," >&6; }
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result:       but WCS 1.1 support will be disabled." >&5
+$as_echo "      but WCS 1.1 support will be disabled." >&6; }
+  elif test "x$WFS_SVR_ENABLED" != "x" ; then
+    with_xml2_config=yes
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: libxml2 requested for WFS Server." >&5
+$as_echo "libxml2 requested for WFS Server." >&6; }
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result:       If unavailable disable using --without-xml2-config," >&5
+$as_echo "      If unavailable disable using --without-xml2-config," >&6; }
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result:       but WFS 1.1 support will be disabled." >&5
+$as_echo "      but WFS 1.1 support will be disabled." >&6; }
+  else
+    with_xml2_config=no
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: libxml2 not required." >&5
+$as_echo "libxml2 not required." >&6; }
+  fi
+fi
 
-    # Extract the first word of "geos-config", so it can be a program name with args.
-set dummy geos-config; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
-if test "${ac_cv_path_GEOS_CONFIG+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+if test "$with_xml2_config" != "no" ; then
+
+  if test "`basename xx/$with_xml2_config`" = "xml2-config" ; then
+    LIBXML2_CONFIG="$with_xml2_config"
+    if test -f "$LIBXML2_CONFIG" -a -x "$LIBXML2_CONFIG" ; then
+      { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, user supplied xml2-config ($LIBXML2_CONFIG)" >&5
+$as_echo "yes, user supplied xml2-config ($LIBXML2_CONFIG)" >&6; }
+    else
+      as_fn_error $? "'$LIBXML2_CONFIG' is not an executable.  Make sure you use --with-xml2-config=/path/to/xml2-config" "$LINENO" 5
+    fi
+  else
+    # Extract the first word of "xml2-config", so it can be a program name with args.
+set dummy xml2-config; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_path_LIBXML2_CONFIG+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
-  case $GEOS_CONFIG in
+  case $LIBXML2_CONFIG in
   [\\/]* | ?:[\\/]*)
-  ac_cv_path_GEOS_CONFIG="$GEOS_CONFIG" # Let the user override the test with a path.
+  ac_cv_path_LIBXML2_CONFIG="$LIBXML2_CONFIG" # Let the user override the test with a path.
   ;;
   *)
   as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
@@ -11488,217 +19439,270 @@ for as_dir in $PATH
 do
   IFS=$as_save_IFS
   test -z "$as_dir" && as_dir=.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_path_GEOS_CONFIG="$as_dir/$ac_word$ac_exec_ext"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_path_LIBXML2_CONFIG="$as_dir/$ac_word$ac_exec_ext"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
-done
+  done
+IFS=$as_save_IFS
 
-  test -z "$ac_cv_path_GEOS_CONFIG" && ac_cv_path_GEOS_CONFIG="no"
+  test -z "$ac_cv_path_LIBXML2_CONFIG" && ac_cv_path_LIBXML2_CONFIG="no"
   ;;
 esac
 fi
-GEOS_CONFIG=$ac_cv_path_GEOS_CONFIG
-
-if test -n "$GEOS_CONFIG"; then
-  echo "$as_me:$LINENO: result: $GEOS_CONFIG" >&5
-echo "${ECHO_T}$GEOS_CONFIG" >&6
+LIBXML2_CONFIG=$ac_cv_path_LIBXML2_CONFIG
+if test -n "$LIBXML2_CONFIG"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $LIBXML2_CONFIG" >&5
+$as_echo "$LIBXML2_CONFIG" >&6; }
 else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
 
 
-    if test "$GEOS_CONFIG" = "no" ; then
-      { { echo "$as_me:$LINENO: error: couldn't find geos-config in default path. Please specify full path to geos-config" >&5
-echo "$as_me: error: couldn't find geos-config in default path. Please specify full path to geos-config" >&2;}
-   { (exit 1); exit 1; }; }
-    fi
-
-  elif test -f "$GEOS_CONFIG" -a -x "$GEOS_CONFIG" ; then
-    echo "$as_me:$LINENO: result: user supplied geos-config ($GEOS_CONFIG)" >&5
-echo "${ECHO_T}user supplied geos-config ($GEOS_CONFIG)" >&6
-  else
-    { { echo "$as_me:$LINENO: error: '$GEOS_CONFIG' is not an executable.  Make sure you use --with-geos=/path/to/geos-config" >&5
-echo "$as_me: error: '$GEOS_CONFIG' is not an executable.  Make sure you use --with-geos=/path/to/geos-config" >&2;}
-   { (exit 1); exit 1; }; }
   fi
 
+  if test "$LIBXML2_CONFIG" = "no" ; then
+   as_fn_error $? "couldn't find xml2-config, try using --with-xml2-config=PATH" "$LINENO" 5
+  fi
 
-  min_geos_version=3.0.0
+  XML2_VER=`$LIBXML2_CONFIG --version`
 
-  echo "$as_me:$LINENO: checking for GEOS version >= $min_geos_version" >&5
-echo $ECHO_N "checking for GEOS version >= $min_geos_version... $ECHO_C" >&6
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result:         found libxml2 version $XML2_VER" >&5
+$as_echo "        found libxml2 version $XML2_VER" >&6; }
 
-  geos_major_version=`$GEOS_CONFIG --version | \
-       sed 's/\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\).*/\1/'`
-  geos_minor_version=`$GEOS_CONFIG --version | \
-       sed 's/\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\).*/\2/'`
-  geos_micro_version=`$GEOS_CONFIG --version | \
-       sed 's/\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\).*/\3/'`
+  XML2_INC=`$LIBXML2_CONFIG --cflags`
+  XML2_LIB=`$LIBXML2_CONFIG --libs`
+  XML2_ENABLED=-DUSE_LIBXML2
 
-  req_major=`echo $min_geos_version | \
-       sed 's/\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\).*/\1/'`
-  req_minor=`echo $min_geos_version | \
-       sed 's/\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\).*/\2/'`
-  req_micro=`echo $min_geos_version | \
-       sed 's/\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\).*/\3/'`
+  if test "$SOS_REQUESTED" = "yes" ; then
+    SOS_SVR_ENABLED="-DUSE_SOS_SVR"
+  fi
+  if test "$KML_REQUESTED" = "yes" ; then
+    KML_ENABLED="-DUSE_KML"
+  fi
+fi
 
-  ac_req_version=`expr $req_major \* 100000 \+  $req_minor \* 100 \+ $req_micro`
-  ac_geos_version=`expr $geos_major_version \* 100000 \+  $geos_minor_version \* 100 \+ $geos_micro_version`
+XML2_INC=$XML2_INC
 
-  if test $ac_req_version -le $ac_geos_version; then
-     echo "$as_me:$LINENO: result: yes. Found version ${geos_major_version}.${geos_minor_version}.${geos_micro_version}" >&5
-echo "${ECHO_T}yes. Found version ${geos_major_version}.${geos_minor_version}.${geos_micro_version}" >&6
-  else
-     echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
-     { { echo "$as_me:$LINENO: error: geos-config reports version ${geos_major_version}.${geos_minor_version}.${geos_micro_version}, need at least $min_geos_version or configure --without-geos" >&5
-echo "$as_me: error: geos-config reports version ${geos_major_version}.${geos_minor_version}.${geos_micro_version}, need at least $min_geos_version or configure --without-geos" >&2;}
-   { (exit 1); exit 1; }; }
-  fi
+XML2_LIB=$XML2_LIB
 
 
+ALL_INC="$XML2_INC $ALL_INC"
+ALL_LIB="$XML2_LIB $ALL_LIB"
 
-  GEOS_ENABLED=-DUSE_GEOS
 
-  GEOS_INCDIR=`$GEOS_CONFIG --includes`
-  GEOS_INC="-I$GEOS_INCDIR"
-  GEOS_LIB="`$GEOS_CONFIG --libs`_c"
+WMS_LYR_ENABLED=$WMS_LYR_ENABLED
 
-  GEOS_ENABLED=$GEOS_ENABLED
+WFS_LYR_ENABLED=$WFS_LYR_ENABLED
 
-  GEOS_INC=$GEOS_INC
+SOS_SVR_ENABLED=$SOS_SVR_ENABLED
 
-  GEOS_LIB=$GEOS_LIB
 
+ALL_ENABLED="$WMS_LYR_ENABLED $WFS_LYR_ENABLED $SOS_SVR_ENABLED $XML2_ENABLED $CURL_ENABLED $KML_ENABLED $ALL_ENABLED"
 
-  ALL_ENABLED="$GEOS_ENABLED $ALL_ENABLED"
-  ALL_INC="$GEOS_INC $ALL_INC"
-  ALL_LIB="$GEOS_LIB $ALL_LIB"
 
-else
 
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
 
+# Check whether --with-xml-mapfile was given.
+if test "${with_xml_mapfile+set}" = set; then :
+  withval=$with_xml_mapfile; XMLMAPFILE_REQUESTED=""
 fi
 
 
-{ echo "$as_me:$LINENO: checking whether we should include OGR support..." >&5
-echo "$as_me: checking whether we should include OGR support..." >&6;}
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if xml-mapfile is requested" >&5
+$as_echo_n "checking if xml-mapfile is requested... " >&6; }
+XMLMAPFILE_ENABLED=""
 
-# Check whether --with-ogr or --without-ogr was given.
-if test "${with_ogr+set}" = set; then
-  withval="$with_ogr"
+if test "$with_xml_mapfile" = "yes"; then
+  XMLMAPFILE_ENABLED="-DUSE_XMLMAPFILE"
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes.. xslt and exslt support needed" >&5
+$as_echo "yes.. xslt and exslt support needed" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
 
-fi;
+ALL_ENABLED="$XMLMAPFILE_ENABLED $ALL_ENABLED"
 
-if test "`basename xx/$with_ogr`" = "gdal-config" ; then
-  GDAL_CONFIG="$with_ogr"
+
+
+# Check whether --with-xslt was given.
+if test "${with_xslt+set}" = set; then :
+  withval=$with_xslt; XSLT_DIR=$withval
+else
+  XSLT_DIR=''
 fi
 
-if test "$with_ogr" = "yes" ; then
- # Extract the first word of "gdal-config", so it can be a program name with args.
-set dummy gdal-config; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
-if test "${ac_cv_path_GDAL_CONFIG+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if xslt is requested" >&5
+$as_echo_n "checking if xslt is requested... " >&6; }
+XSLT_LIB=''
+
+if test -z "$XMLMAPFILE_ENABLED" -a \( "$with_xslt" = "no" -o "$with_xslt" = ""  \); then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 else
-  case $GDAL_CONFIG in
-  [\\/]* | ?:[\\/]*)
-  ac_cv_path_GDAL_CONFIG="$GDAL_CONFIG" # Let the user override the test with a path.
-  ;;
-  *)
-  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_path_GDAL_CONFIG="$as_dir/$ac_word$ac_exec_ext"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
+
+  if test "$XSLT_DIR" = "yes" -o "$XSLT_DIR" = ""; then
+     XSLT_DIR="/usr"
   fi
-done
-done
 
-  test -z "$ac_cv_path_GDAL_CONFIG" && ac_cv_path_GDAL_CONFIG="no"
-  ;;
-esac
+  test -f $XSLT_DIR/include/libxslt/xslt.h && XSLT_INCDIR="$XSLT_DIR/include"
+  test -f $XSLT_DIR/lib/libxslt.so && XSLT_LIBDIR="$XSLT_DIR/lib"
+  test -f $XSLT_DIR/lib64/libxslt.so && XSLT_LIBDIR="$XSLT_DIR/lib64"
+  test -f $XSLT_DIR/lib/x86_64-linux-gnu/libxslt.so && XSLT_LIBDIR="$XSLT_DIR/lib/x86_64-linux-gnu"
+
+  if test -n "$XSLT_LIBDIR" -a -n "$XSLT_INCDIR" ; then
+                XSLT_ENABLED="-DUSE_XSLT"
+    XSLT_INC="-I$XSLT_INCDIR"
+    XSLT_LIB="-L$XSLT_LIBDIR -lxslt"
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: using xslt from $XSLT_LIB ($XSLT_ENABLED)" >&5
+$as_echo "using xslt from $XSLT_LIB ($XSLT_ENABLED)" >&6; }
+
+  if test ""$XSLT_DIR"" != "/usr/lib"; then
+
+  if test -z ""$XSLT_DIR"" || echo ""$XSLT_DIR"" | grep '^/' >/dev/null ; then
+    ai_p=""$XSLT_DIR""
+  else
+    ai_p="`pwd`/"$XSLT_DIR""
+  fi
+
+
+  unique=`echo $ac_n "$ai_p$ac_c" | tr -c -d a-zA-Z0-9`
+  cmd="echo $ac_n \"\$LIBPATH$unique$ac_c\""
+  if test -n "$unique" && test "`eval $cmd`" = "" ; then
+    eval "LIBPATH$unique=set"
+
+      EXTRA_LIBS="$EXTRA_LIBS -L$ai_p"
+        RPATHS="$RPATHS ${ld_runpath_switch}$ai_p"
+
+  fi
+
+  fi
+
+
+  else
+    as_fn_error $? "'$XSLT_DIR' not a valid installation path of xslt." "$LINENO" 5
+  fi
 fi
-GDAL_CONFIG=$ac_cv_path_GDAL_CONFIG
 
-if test -n "$GDAL_CONFIG"; then
-  echo "$as_me:$LINENO: result: $GDAL_CONFIG" >&5
-echo "${ECHO_T}$GDAL_CONFIG" >&6
+XSLT_ENABLED=$XSLT_ENABLED
+
+XSLT_INC=$XSLT_INC
+
+XSLT_LIB=$XSLT_LIB
+
+
+ALL_ENABLED="$XSLT_ENABLED $ALL_ENABLED"
+ALL_INC="$XSLT_INC $ALL_INC"
+ALL_LIB="$XSLT_LIB $ALL_LIB"
+
+
+
+# Check whether --with-exslt was given.
+if test "${with_exslt+set}" = set; then :
+  withval=$with_exslt; EXSLT_DIR=$withval
 else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
+  EXSLT_DIR=''
 fi
 
 
-  if test "$GDAL_CONFIG" = "no" ; then
-    { { echo "$as_me:$LINENO: error: couldn't find gdal-config" >&5
-echo "$as_me: error: couldn't find gdal-config" >&2;}
-   { (exit 1); exit 1; }; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if exslt is requested" >&5
+$as_echo_n "checking if exslt is requested... " >&6; }
+EXSLT_LIB=''
+
+if test -z "$XMLMAPFILE_ENABLED" -a \( "$with_exslt" = "no" -o "$with_exslt" = ""  \); then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+else
+
+  if test "$EXSLT_DIR" = "yes" -o "$EXSLT_DIR" = ""; then
+     EXSLT_DIR="/usr"
+  fi
+
+  test -f $EXSLT_DIR/include/libexslt/exslt.h && EXSLT_INCDIR="$EXSLT_DIR/include"
+  test -f $EXSLT_DIR/lib/libexslt.so && EXSLT_LIBDIR="$EXSLT_DIR/lib"
+  test -f $EXSLT_DIR/lib64/libexslt.so && EXSLT_LIBDIR="$EXSLT_DIR/lib64"
+  test -f $EXSLT_DIR/lib/x86_64-linux-gnu/libexslt.so && EXSLT_LIBDIR="$EXSLT_DIR/lib/x86_64-linux-gnu"
+
+  if test -n "$EXSLT_LIBDIR" -a -n "$EXSLT_INCDIR" ; then
+                EXSLT_ENABLED="-DUSE_EXSLT"
+    EXSLT_INC="-I$EXSLT_INCDIR"
+    EXSLT_LIB="-L$EXSLT_LIBDIR -lexslt"
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: using exslt from $EXSLT_LIB ($EXSLT_ENABLED)" >&5
+$as_echo "using exslt from $EXSLT_LIB ($EXSLT_ENABLED)" >&6; }
+
+  if test ""$EXSLT_DIR"" != "/usr/lib"; then
+
+  if test -z ""$EXSLT_DIR"" || echo ""$EXSLT_DIR"" | grep '^/' >/dev/null ; then
+    ai_p=""$EXSLT_DIR""
+  else
+    ai_p="`pwd`/"$EXSLT_DIR""
+  fi
+
+
+  unique=`echo $ac_n "$ai_p$ac_c" | tr -c -d a-zA-Z0-9`
+  cmd="echo $ac_n \"\$LIBPATH$unique$ac_c\""
+  if test -n "$unique" && test "`eval $cmd`" = "" ; then
+    eval "LIBPATH$unique=set"
+
+      EXTRA_LIBS="$EXTRA_LIBS -L$ai_p"
+        RPATHS="$RPATHS ${ld_runpath_switch}$ai_p"
+
   fi
-fi
-
-if test -n "$GDAL_CONFIG" -a "$with_ogr" != "no" ; then
 
+  fi
 
-  if test x`$GDAL_CONFIG --ogr-enabled` = "xyes" ; then
-      OGR_ENABLED=-DUSE_OGR
-      echo "$as_me:$LINENO: result:         OGR enabled ($OGR_ENABLED)." >&5
-echo "${ECHO_T}        OGR enabled ($OGR_ENABLED)." >&6
   else
-      { echo "$as_me:$LINENO: WARNING:         OGR not available." >&5
-echo "$as_me: WARNING:         OGR not available." >&2;}
+    as_fn_error $? "'$EXSLT_DIR' not a valid installation path of exslt." "$LINENO" 5
   fi
+fi
 
-else
+EXSLT_ENABLED=$EXSLT_ENABLED
 
-  echo "$as_me:$LINENO: result:         OGR support not requested." >&5
-echo "${ECHO_T}        OGR support not requested." >&6
-fi
+EXSLT_INC=$EXSLT_INC
+
+EXSLT_LIB=$EXSLT_LIB
 
 
-echo "$as_me:$LINENO: checking if GDAL support requested" >&5
-echo $ECHO_N "checking if GDAL support requested... $ECHO_C" >&6
+ALL_ENABLED="$EXSLT_ENABLED $ALL_ENABLED"
+ALL_INC="$EXSLT_INC $ALL_INC"
+ALL_LIB="$EXSLT_LIB $ALL_LIB"
 
 
-# Check whether --with-gdal or --without-gdal was given.
-if test "${with_gdal+set}" = set; then
-  withval="$with_gdal"
 
-fi;
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if FriBidi support requested" >&5
+$as_echo_n "checking if FriBidi support requested... " >&6; }
 
-if test "$with_gdal" = "yes" ; then
 
-  echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6
+# Check whether --with-fribidi-config was given.
+if test "${with_fribidi_config+set}" = set; then :
+  withval=$with_fribidi_config;
+fi
 
-  if test "`basename xx/$with_gdal`" = "gdal-config" ; then
-    GDAL_CONFIG="$with_gdal"
-  fi
 
-  if test -z "$GDAL_CONFIG" ; then
-    # Extract the first word of "gdal-config", so it can be a program name with args.
-set dummy gdal-config; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
-if test "${ac_cv_path_GDAL_CONFIG+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+if test "$with_fribidi_config" = "no" -o "$with_fribidi_config" = "" ; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+  FRIBIDI_CONFIG="no"
+
+elif test "$with_fribidi_config" = "yes" ; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+  # Extract the first word of "fribidi-config", so it can be a program name with args.
+set dummy fribidi-config; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_path_FRIBIDI_CONFIG+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
-  case $GDAL_CONFIG in
+  case $FRIBIDI_CONFIG in
   [\\/]* | ?:[\\/]*)
-  ac_cv_path_GDAL_CONFIG="$GDAL_CONFIG" # Let the user override the test with a path.
+  ac_cv_path_FRIBIDI_CONFIG="$FRIBIDI_CONFIG" # Let the user override the test with a path.
   ;;
   *)
   as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
@@ -11706,431 +19710,336 @@ for as_dir in $PATH
 do
   IFS=$as_save_IFS
   test -z "$as_dir" && as_dir=.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_path_GDAL_CONFIG="$as_dir/$ac_word$ac_exec_ext"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_path_FRIBIDI_CONFIG="$as_dir/$ac_word$ac_exec_ext"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
-done
+  done
+IFS=$as_save_IFS
 
-  test -z "$ac_cv_path_GDAL_CONFIG" && ac_cv_path_GDAL_CONFIG="no"
+  test -z "$ac_cv_path_FRIBIDI_CONFIG" && ac_cv_path_FRIBIDI_CONFIG="no"
   ;;
 esac
 fi
-GDAL_CONFIG=$ac_cv_path_GDAL_CONFIG
-
-if test -n "$GDAL_CONFIG"; then
-  echo "$as_me:$LINENO: result: $GDAL_CONFIG" >&5
-echo "${ECHO_T}$GDAL_CONFIG" >&6
+FRIBIDI_CONFIG=$ac_cv_path_FRIBIDI_CONFIG
+if test -n "$FRIBIDI_CONFIG"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $FRIBIDI_CONFIG" >&5
+$as_echo "$FRIBIDI_CONFIG" >&6; }
 else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
 
+
+  FRIBIDI_PKG_CONFIG="no"
+  if test "$FRIBIDI_CONFIG" = "no" -a "$PKG_CONFIG" != "no" ; then
+     { $as_echo "$as_me:${as_lineno-$LINENO}: checking for fribidi pkg-config path" >&5
+$as_echo_n "checking for fribidi pkg-config path... " >&6; }
+     `$PKG_CONFIG --silence-errors --libs fribidi >> /dev/null`
+     if test $? -eq 0 ; then
+        { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+        FRIBIDI_PKG_CONFIG="yes"
+        FRIBIDI_CONFIG="fribidi"
+     else
+       { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+     fi
   fi
+else
+  FRIBIDI_CONFIG=$with_fribidi_config
+fi
 
-  if test "$GDAL_CONFIG" = "no" ; then
-    { { echo "$as_me:$LINENO: error: couldn't find gdal-config" >&5
-echo "$as_me: error: couldn't find gdal-config" >&2;}
-   { (exit 1); exit 1; }; }
+if test "$FRIBIDI_CONFIG" = "no" ; then
+  FRIBIDI_ENABLED=
+  FRIBIDI_INC=
+  FRIBIDI_LIB=
+else
+  if test "$FRIBIDI_PKG_CONFIG" = "yes" -o ${FRIBIDI_CONFIG: -3} = ".pc" ; then
+     { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, user supplied path to fribidi.pc" >&5
+$as_echo "yes, user supplied path to fribidi.pc" >&6; }
+     FRIBIDI_ENABLED="-DUSE_FRIBIDI -DUSE_FRIBIDI2"
+     FRIBIDI_LIB=`$PKG_CONFIG --libs $FRIBIDI_CONFIG`
+     FRIBIDI_INC=`$PKG_CONFIG --cflags $FRIBIDI_CONFIG`
+  else
+     if test -f "$FRIBIDI_CONFIG" -a -x "$FRIBIDI_CONFIG" ; then
+       { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, user supplied fribidi-config ($FRIBIDI_CONFIG)" >&5
+$as_echo "yes, user supplied fribidi-config ($FRIBIDI_CONFIG)" >&6; }
+     else
+       as_fn_error $? "'$FRIBIDI_CONFIG' is not an executable.  Make sure you use --with-fribidi-config=/path/to/fribidi-config or fribidi.pc" "$LINENO" 5
+     fi
+     FRIBIDI_ENABLED=-DUSE_FRIBIDI
+     FRIBIDI_LIB=`$FRIBIDI_CONFIG --libs`
+     FRIBIDI_INC=`$FRIBIDI_CONFIG --cflags`
   fi
+fi
 
-  GDAL_ENABLED=-DUSE_GDAL
+FRIBIDI_ENABLED=$FRIBIDI_ENABLED
 
-elif test -n "$with_gdal" -a "$with_gdal" != "no" ; then
+FRIBIDI_INC=$FRIBIDI_INC
 
-  GDAL_CONFIG=$with_gdal
+FRIBIDI_LIB=$FRIBIDI_LIB
 
-  if test -f "$GDAL_CONFIG" -a -x "$GDAL_CONFIG" ; then
-    echo "$as_me:$LINENO: result: yes, user supplied gdal-config ($GDAL_CONFIG)" >&5
-echo "${ECHO_T}yes, user supplied gdal-config ($GDAL_CONFIG)" >&6
-  else
-    { { echo "$as_me:$LINENO: error: '$GDAL_CONFIG' is not an executable.  Make sure you use --with-gdal=/path/to/gdal-config" >&5
-echo "$as_me: error: '$GDAL_CONFIG' is not an executable.  Make sure you use --with-gdal=/path/to/gdal-config" >&2;}
-   { (exit 1); exit 1; }; }
-  fi
 
-  GDAL_ENABLED=-DUSE_GDAL
+ALL_ENABLED="$FRIBIDI_ENABLED $ALL_ENABLED"
+ALL_INC="$FRIBIDI_INC $ALL_INC"
+ALL_LIB="$FRIBIDI_LIB $ALL_LIB"
 
-else
 
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
 
-fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if Cairo support requested" >&5
+$as_echo_n "checking if Cairo support requested... " >&6; }
 
 
-if test -n "$GDAL_ENABLED" -o "$OGR_ENABLED"; then
+# Check whether --with-cairo was given.
+if test "${with_cairo+set}" = set; then :
+  withval=$with_cairo;
+fi
 
-  GDAL_LIB=`$GDAL_CONFIG --libs`
-  GDAL_INC=`$GDAL_CONFIG --cflags`
 
+if test "$with_cairo" = "no" -o "$with_cairo" = "" ; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+  CAIRO_CONFIG="no"
+
+elif test "$with_cairo" = "yes" ; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+  if test "$PKG_CONFIG" != "no" ; then
+     { $as_echo "$as_me:${as_lineno-$LINENO}: checking for cairo pkg-config path" >&5
+$as_echo_n "checking for cairo pkg-config path... " >&6; }
+     `$PKG_CONFIG --silence-errors -- cairo cairo-ft cairo-svg cairo-pdf cairo-png >> /dev/null`
+     if test $? -eq 0 ; then
+        { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+        CAIRO_CONFIG="cairo cairo-ft cairo-svg cairo-pdf cairo-png"
+     else
+       as_fn_error $? "cairo support requested, but not found.Try installing the cairo development headers" "$LINENO" 5
+     fi
+  else
+    as_fn_error $? "pkg-config required for cairo support, try using --with-pkg-config=PATH" "$LINENO" 5
+  fi
+else
+  CAIRO_CONFIG=$with_cairo
 fi
 
-GDAL_ENABLED=$GDAL_ENABLED
+if test "$CAIRO_CONFIG" = "no" ; then
+  CAIRO_ENABLED=
+  CAIRO_INC=
+  CAIRO_LIB=
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, pkg-config defaults, or user supplied path to cairo.pc" >&5
+$as_echo "yes, pkg-config defaults, or user supplied path to cairo.pc" >&6; }
+  CAIRO_ENABLED="-DUSE_CAIRO"
+  CAIRO_LIB=`$PKG_CONFIG --libs $CAIRO_CONFIG`
+  CAIRO_INC=`$PKG_CONFIG --cflags $CAIRO_CONFIG`
+fi
 
-OGR_ENABLED=$OGR_ENABLED
+CAIRO_ENABLED=$CAIRO_ENABLED
 
-GDAL_INC=$GDAL_INC
+CAIRO_INC=$CAIRO_INC
 
-GDAL_LIB=$GDAL_LIB
+CAIRO_LIB=$CAIRO_LIB
 
 
-ALL_ENABLED="$GDAL_ENABLED $OGR_ENABLED $ALL_ENABLED"
-ALL_INC="$GDAL_INC $ALL_INC"
-ALL_LIB="$GDAL_LIB $ALL_LIB"
+ALL_ENABLED="$CAIRO_ENABLED $ALL_ENABLED"
+ALL_INC="$CAIRO_INC $ALL_INC"
+ALL_LIB="$CAIRO_LIB $ALL_LIB"
 
 
 
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if Cairo svg parser support requested" >&5
+$as_echo_n "checking if Cairo svg parser support requested... " >&6; }
 
-echo "$as_me:$LINENO: checking if PostGIS support requested" >&5
-echo $ECHO_N "checking if PostGIS support requested... $ECHO_C" >&6
+LIBSVG_CAIRO_ENABLED=$LIBSVG_CAIRO_ENABLED
 
+LIBSVG_CAIRO_INC=$LIBSVG_CAIRO_INC
 
-# Check whether --with-postgis or --without-postgis was given.
-if test "${with_postgis+set}" = set; then
-  withval="$with_postgis"
+LIBSVG_CAIRO_LIB=$LIBSVG_CAIRO_LIB
 
-fi;
 
-if test "$with_postgis" = "no" -o "$with_postgis" = "" ; then
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
-  PG_CONFIG="no"
-elif test "$with_postgis" = "yes" ; then
-  echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6
-  # Extract the first word of "pg_config", so it can be a program name with args.
-set dummy pg_config; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
-if test "${ac_cv_path_PG_CONFIG+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  case $PG_CONFIG in
-  [\\/]* | ?:[\\/]*)
-  ac_cv_path_PG_CONFIG="$PG_CONFIG" # Let the user override the test with a path.
-  ;;
-  *)
-  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_path_PG_CONFIG="$as_dir/$ac_word$ac_exec_ext"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
 
-  test -z "$ac_cv_path_PG_CONFIG" && ac_cv_path_PG_CONFIG="no"
-  ;;
-esac
+# Check whether --with-libsvg-cairo was given.
+if test "${with_libsvg_cairo+set}" = set; then :
+  withval=$with_libsvg_cairo;
 fi
-PG_CONFIG=$ac_cv_path_PG_CONFIG
 
-if test -n "$PG_CONFIG"; then
-  echo "$as_me:$LINENO: result: $PG_CONFIG" >&5
-echo "${ECHO_T}$PG_CONFIG" >&6
-else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
-fi
 
+if test "$with_libsvg_cairo" = "no" -o "$with_libsvg_cairo" = "" ; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+  LIBSVG_CAIRO_CONFIG="no"
+
+elif test "$with_libsvg_cairo" = "yes" ; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+  if test "$PKG_CONFIG" != "no" ; then
+     { $as_echo "$as_me:${as_lineno-$LINENO}: checking for libsvg-cairo pkg-config path" >&5
+$as_echo_n "checking for libsvg-cairo pkg-config path... " >&6; }
+     `$PKG_CONFIG --silence-errors -- libsvg-cairo >> /dev/null`
+     if test $? -eq 0 ; then
+        { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+        LIBSVG_CAIRO_CONFIG="libsvg-cairo"
+     else
+       as_fn_error $? "libsvg-cairo support requested, but not found." "$LINENO" 5
+     fi
+  else
+    as_fn_error $? "pkg-config required for libsvg-cairo support, try using --with-pkg-config=PATH" "$LINENO" 5
+  fi
 else
-  PG_CONFIG=$with_postgis
+  LIBSVG_CAIRO_CONFIG=$with_libsvg_cairo
 fi
 
-if test "$PG_CONFIG" = "no" ; then
-  POSTGIS_ENABLED=
-  POSTGIS_INC=
-  POSTGIS_LIB=
+if test "$LIBSVG_CAIRO_CONFIG" = "no" ; then
+  LIBSVG_CAIRO_ENABLED=
+  LIBSVG_CAIRO_INC=
+  LIBSVG_CAIRO_LIB=
 else
-  POSTGIS_ENABLED=
-
-  if test -f "$PG_CONFIG" -a -x "$PG_CONFIG" ; then
-    echo "$as_me:$LINENO: result: yes, user supplied pg_config ($PG_CONFIG)" >&5
-echo "${ECHO_T}yes, user supplied pg_config ($PG_CONFIG)" >&6
-  else
-    { { echo "$as_me:$LINENO: error: '$PG_CONFIG' is not an executable.  Make sure you use --with-postgis=/path/to/pg_config" >&5
-echo "$as_me: error: '$PG_CONFIG' is not an executable.  Make sure you use --with-postgis=/path/to/pg_config" >&2;}
-   { (exit 1); exit 1; }; }
+  if test -z "$CAIRO_ENABLED"; then
+       as_fn_error $? "libsvg-cairo support requires cairo support. (hint: rerun with --with-cairo)" "$LINENO" 5
   fi
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, pkg-config defaults, or user supplied path to cairo.pc" >&5
+$as_echo "yes, pkg-config defaults, or user supplied path to cairo.pc" >&6; }
+  LIBSVG_CAIRO_ENABLED="-DUSE_SVG_CAIRO"
+  LIBSVG_CAIRO_LIB=`$PKG_CONFIG --libs $LIBSVG_CAIRO_CONFIG`
+  LIBSVG_CAIRO_INC=`$PKG_CONFIG --cflags $LIBSVG_CAIRO_CONFIG`
+fi
 
-  POSTGIS_EXTRALIBS="`$PG_CONFIG --libs`"
-    if test $? -ne 0 ; then
-      POSTGIS_EXTRALIBS=
-  fi
+LIBSVG_CAIRO_ENABLED=$LIBSVG_CAIRO_ENABLED
 
-  POSTGIS_INC="-I`$PG_CONFIG --includedir`"
+LIBSVG_CAIRO_INC=$LIBSVG_CAIRO_INC
 
-  old_LDFLAGS="$LDFLAGS"
+LIBSVG_CAIRO_LIB=$LIBSVG_CAIRO_LIB
 
-  POSTGIS_LIB="-L`$PG_CONFIG --libdir` -lpq"
-  LDFLAGS="$LDFLAGS $POSTGIS_LIB"
 
-  echo "$as_me:$LINENO: checking for PQconnectdb in -lpq" >&5
-echo $ECHO_N "checking for PQconnectdb in -lpq... $ECHO_C" >&6
-if test "${ac_cv_lib_pq_PQconnectdb+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-lpq  $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
+ALL_ENABLED="$LIBSVG_CAIRO_ENABLED $ALL_ENABLED"
+ALL_INC="$LIBSVG_CAIRO_INC $ALL_INC"
+ALL_LIB="$LIBSVG_CAIRO_LIB $ALL_LIB"
 
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char PQconnectdb ();
-int
-main ()
-{
-PQconnectdb ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_pq_PQconnectdb=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
 
-ac_cv_lib_pq_PQconnectdb=no
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_pq_PQconnectdb" >&5
-echo "${ECHO_T}$ac_cv_lib_pq_PQconnectdb" >&6
-if test $ac_cv_lib_pq_PQconnectdb = yes; then
-  POSTGIS_ENABLED="-DUSE_POSTGIS"
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking FastCGI support" >&5
+$as_echo_n "checking FastCGI support... " >&6; }
+
+# Check whether --with-fastcgi was given.
+if test "${with_fastcgi+set}" = set; then :
+  withval=$with_fastcgi;
 fi
 
 
-    if test  "$POSTGIS_ENABLED"x = x ; then
-    POSTGIS_LIB="$POSTGIS_LIB $POSTGIS_EXTRALIBS"
-    LDFLAGS="$old_LDFLAGS $POSTGIS_LIB"
-    unset ac_cv_lib_pq_PQconnectdb
-    echo "$as_me:$LINENO: checking for PQconnectdb in -lpq" >&5
-echo $ECHO_N "checking for PQconnectdb in -lpq... $ECHO_C" >&6
-if test "${ac_cv_lib_pq_PQconnectdb+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-lpq  $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
+if test "$with_fastcgi" = "no" -o "$with_fastcgi" = "" ; then
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: not requested." >&5
+$as_echo "not requested." >&6; }
 
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char PQconnectdb ();
-int
-main ()
-{
-PQconnectdb ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_pq_PQconnectdb=yes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
 
-ac_cv_lib_pq_PQconnectdb=no
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_pq_PQconnectdb" >&5
-echo "${ECHO_T}$ac_cv_lib_pq_PQconnectdb" >&6
-if test $ac_cv_lib_pq_PQconnectdb = yes; then
-  POSTGIS_ENABLED="-DUSE_POSTGIS"
-fi
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: requested." >&5
+$as_echo "requested." >&6; }
 
+  if test "$with_fastcgi" = "yes" ; then
+    FASTCGI_INC=""
+    FASTCGI_LIB="-lfcgi"
+  else
+    FASTCGI_INC="-I$with_fastcgi/include -I$with_fastcgi/include/fastcgi"
+    FASTCGI_LIB="-L$with_fastcgi/lib -lfcgi"
   fi
 
-    if test "$POSTGIS_ENABLED" = "-DUSE_POSTGIS" ; then
-    echo "$as_me:$LINENO: checking for PQserverVersion in -lpq" >&5
-echo $ECHO_N "checking for PQserverVersion in -lpq... $ECHO_C" >&6
-if test "${ac_cv_lib_pq_PQserverVersion+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for FCGI_Accept in -lfcgi" >&5
+$as_echo_n "checking for FCGI_Accept in -lfcgi... " >&6; }
+if ${ac_cv_lib_fcgi_FCGI_Accept+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
   ac_check_lib_save_LIBS=$LIBS
-LIBS="-lpq  $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+LIBS="-lfcgi $FASTCGI_LIB $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
-/* Override any gcc2 internal prototype to avoid an error.  */
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
 #ifdef __cplusplus
 extern "C"
 #endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char PQserverVersion ();
+char FCGI_Accept ();
 int
 main ()
 {
-PQserverVersion ();
+return FCGI_Accept ();
   ;
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_pq_PQserverVersion=yes
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_fcgi_FCGI_Accept=yes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-ac_cv_lib_pq_PQserverVersion=no
+  ac_cv_lib_fcgi_FCGI_Accept=no
 fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 LIBS=$ac_check_lib_save_LIBS
 fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_pq_PQserverVersion" >&5
-echo "${ECHO_T}$ac_cv_lib_pq_PQserverVersion" >&6
-if test $ac_cv_lib_pq_PQserverVersion = yes; then
-  POSTGIS_ENABLED="$POSTGIS_ENABLED -DPOSTGIS_HAS_SERVER_VERSION"
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_fcgi_FCGI_Accept" >&5
+$as_echo "$ac_cv_lib_fcgi_FCGI_Accept" >&6; }
+if test "x$ac_cv_lib_fcgi_FCGI_Accept" = xyes; then :
+  FASTCGI_ENABLED=-DUSE_FASTCGI
 fi
 
-  fi
 
-  LDFLAGS="$old_LDFLAGS"
+  if test "x$FASTCGI_ENABLED" = "x" ; then
+    as_fn_error $? "Unable to link against $FASTCGI_LIB" "$LINENO" 5
+  fi
 
 fi
 
-POSTGIS_ENABLED=$POSTGIS_ENABLED
+FASTCGI_ENABLED=$FASTCGI_ENABLED
 
-POSTGIS_INC=$POSTGIS_INC
+FASTCGI_INC=$FASTCGI_INC
 
-POSTGIS_LIB=$POSTGIS_LIB
+FASTCGI_LIB=$FASTCGI_LIB
 
 
-ALL_ENABLED="$POSTGIS_ENABLED $ALL_ENABLED"
-ALL_INC="$POSTGIS_INC $ALL_INC"
-ALL_LIB="$POSTGIS_LIB $ALL_LIB"
+ALL_ENABLED="$FASTCGI_ENABLED $ALL_ENABLED"
+ALL_INC="$FASTCGI_INC $ALL_INC"
+ALL_LIB="$FASTCGI_LIB $ALL_LIB"
 
 
-echo "$as_me:$LINENO: checking if Mysql support requested" >&5
-echo $ECHO_N "checking if Mysql support requested... $ECHO_C" >&6
+# Check whether --with-apache-module was given.
+if test "${with_apache_module+set}" = set; then :
+  withval=$with_apache_module;
+else
+  with_apache_module=no
 
+fi
 
-# Check whether --with-mysql or --without-mysql was given.
-if test "${with_mysql+set}" = set; then
-  withval="$with_mysql"
+   if test "$with_apache_module" = "yes"; then
 
-fi;
 
-if test "$with_mysql" = "no" -o "$with_mysql" = "" ; then
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
-  MY_CONFIG="no"
-elif test "$with_mysql" = "yes" ; then
-  echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6
-  # Extract the first word of "mysql_config", so it can be a program name with args.
-set dummy mysql_config; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
-if test "${ac_cv_path_MY_CONFIG+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+
+
+# Check whether --with-apxs was given.
+if test "${with_apxs+set}" = set; then :
+  withval=$with_apxs;
 else
-  case $MY_CONFIG in
+  with_apxs="yes"
+
+fi
+
+
+    if test "$with_apxs" = "yes"; then
+        # Extract the first word of "apxs2", so it can be a program name with args.
+set dummy apxs2; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_path_APXS+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  case $APXS in
   [\\/]* | ?:[\\/]*)
-  ac_cv_path_MY_CONFIG="$MY_CONFIG" # Let the user override the test with a path.
+  ac_cv_path_APXS="$APXS" # Let the user override the test with a path.
   ;;
   *)
   as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
@@ -12138,826 +20047,1057 @@ for as_dir in $PATH
 do
   IFS=$as_save_IFS
   test -z "$as_dir" && as_dir=.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_path_MY_CONFIG="$as_dir/$ac_word$ac_exec_ext"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_path_APXS="$as_dir/$ac_word$ac_exec_ext"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
-done
+  done
+IFS=$as_save_IFS
 
-  test -z "$ac_cv_path_MY_CONFIG" && ac_cv_path_MY_CONFIG="no"
   ;;
 esac
 fi
-MY_CONFIG=$ac_cv_path_MY_CONFIG
-
-if test -n "$MY_CONFIG"; then
-  echo "$as_me:$LINENO: result: $MY_CONFIG" >&5
-echo "${ECHO_T}$MY_CONFIG" >&6
+APXS=$ac_cv_path_APXS
+if test -n "$APXS"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $APXS" >&5
+$as_echo "$APXS" >&6; }
 else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
 
-else
-  MY_CONFIG=$with_mysql
-fi
 
-if test "$MY_CONFIG" = "no" ; then
-  MYSQL_ENABLED=
-  MYSQL_INC=
-  MYSQL_LIB=
+        if test -z "$APXS"; then
+            # Extract the first word of "apxs", so it can be a program name with args.
+set dummy apxs; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_path_APXS+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
-  if test -f "$MY_CONFIG" -a -x "$MY_CONFIG" ; then
-    echo "$as_me:$LINENO: result: yes, user supplied mysql_config ($MY_CONFIG)" >&5
-echo "${ECHO_T}yes, user supplied mysql_config ($MY_CONFIG)" >&6
-  else
-    { { echo "$as_me:$LINENO: error: '$MY_CONFIG' is not an executable.  Make sure you use --with-mysql=/path/to/mysql_config" >&5
-echo "$as_me: error: '$MY_CONFIG' is not an executable.  Make sure you use --with-mysql=/path/to/mysql_config" >&2;}
-   { (exit 1); exit 1; }; }
+  case $APXS in
+  [\\/]* | ?:[\\/]*)
+  ac_cv_path_APXS="$APXS" # Let the user override the test with a path.
+  ;;
+  *)
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_path_APXS="$as_dir/$ac_word$ac_exec_ext"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
   fi
+done
+  done
+IFS=$as_save_IFS
 
-  MYSQL_ENABLED=-DUSE_MYSQL
-  MYSQL_LIB="`$MY_CONFIG --libs` -lmysqlclient"
-#  MYSQL_LIB="-L/usr/lib/mysql -lmysqlclient"
-  MYSQL_INC="`$MY_CONFIG --cflags`"
-#  MYSQL_INC="-I/usr/include/mysql"
+  ;;
+esac
 fi
-
-MYSQL_ENABLED=$MYSQL_ENABLED
-
-MYSQL_INC=$MYSQL_INC
-
-MYSQL_LIB=$MYSQL_LIB
-
-
-ALL_ENABLED="$MYSQL_ENABLED $ALL_ENABLED"
-ALL_INC="$MYSQL_INC $ALL_INC"
-ALL_LIB="$MYSQL_LIB $ALL_LIB"
-
-
-echo "$as_me:$LINENO: checking if OracleSpatial support requested" >&5
-echo $ECHO_N "checking if OracleSpatial support requested... $ECHO_C" >&6
-
-# Check whether --with-oraclespatial or --without-oraclespatial was given.
-if test "${with_oraclespatial+set}" = set; then
-  withval="$with_oraclespatial"
-
-fi;
-
-if test "$with_oraclespatial" = "no" -o "$with_oraclespatial" = ""; then
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
-  ORA_HOME="no"
-elif test "$with_oraclespatial" = "yes"; then
-  if test -d "$ORACLE_HOME"; then
-    echo "$as_me:$LINENO: result: yes, set from ORACLE_HOME environment variable" >&5
-echo "${ECHO_T}yes, set from ORACLE_HOME environment variable" >&6
-    ORA_HOME="$ORACLE_HOME"
-  else
-    ORA_HOME="no"
-    { { echo "$as_me:$LINENO: error: ORACLE_HOME variable is not properly set" >&5
-echo "$as_me: error: ORACLE_HOME variable is not properly set" >&2;}
-   { (exit 1); exit 1; }; }
-  fi
+APXS=$ac_cv_path_APXS
+if test -n "$APXS"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $APXS" >&5
+$as_echo "$APXS" >&6; }
 else
-  echo "$as_me:$LINENO: result: yes, user supplied ORACLE_HOME" >&5
-echo "${ECHO_T}yes, user supplied ORACLE_HOME" >&6
-  ORA_HOME=$with_oraclespatial
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
 
-if test "$ORA_HOME" = "no" ; then
-  ORACLESPATIAL_ENABLED=
-  ORACLESPATIAL_INC=
-  ORACLESPATIAL_LIB=
-else
 
-    test -f $ORA_HOME/lib/libclntsh.so -o -f $ORA_HOME/lib/libclntsh.dylib && ORA_LIBDIR="$ORA_HOME/lib"
-  test -f $ORA_HOME/libclntsh.so -o -f $ORA_HOME/libclntsh.dylib && ORA_LIBDIR="$ORA_HOME"
-  test -f $ORA_HOME/lib/oracle/10*/client/lib/libclntsh.so && ORA_LIBDIR=`dirname $ORA_HOME/lib/oracle/10*/client/lib/libclntsh.so`
-  test -f $ORA_HOME/lib/oracle/10*/client/lib/libclntsh.dylib && ORA_LIBDIR=`dirname $ORA_HOME/lib/oracle/10*/client/lib/libclntsh.dylib`
+        fi
+    elif test "$with_apxs" = "no"; then
+        as_fn_error $? "apxs is required and cannot be disabled" "$LINENO" 5
+    else
+        { $as_echo "$as_me:${as_lineno-$LINENO}: checking for apxs usability in $with_apxs" >&5
+$as_echo_n "checking for apxs usability in $with_apxs... " >&6; }
+        if test -x "$with_apxs"; then
+            APXS=$with_apxs
+            { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+        else
+            as_fn_error $? "$with_apxs not found or not executable" "$LINENO" 5
+        fi
+    fi
+    if test -z "$APXS"; then
+        as_fn_error $? "apxs utility not found. use --with-apxs to specify its location." "$LINENO" 5
+    fi
 
-  if test -z "$ORA_LIBDIR" ; then
-    { { echo "$as_me:$LINENO: error: Oracle Spatial: libclntsh.so not found." >&5
-echo "$as_me: error: Oracle Spatial: libclntsh.so not found." >&2;}
-   { (exit 1); exit 1; }; }
-  fi
+    APACHE_SBINDIR=`$APXS -q SBINDIR`
+    APACHE_BINDIR=`$APXS -q BINDIR`
 
-    test -f $ORA_HOME/sdk/include/oci.h && ORA_INCDIR="$ORA_HOME/sdk/include"
-  test -f $ORA_HOME/rdbms/public/oci.h && ORA_INCDIR="$ORA_HOME/rdbms/public"
-  test -f $ORA_HOME/rdbms/demo/oci.h && ORA_INCDIR="$ORA_HOME/rdbms/public"
-  test -f $ORA_HOME/include/oracle/10*/client/oci.h && ORA_INCDIR=`dirname $ORA_HOME/include/oracle/10*/client/oci.h`
 
-  if test -z "$ORA_INCDIR" ; then
-    { { echo "$as_me:$LINENO: error: Oracle Spatial: oci.h not found." >&5
-echo "$as_me: error: Oracle Spatial: oci.h not found." >&2;}
-   { (exit 1); exit 1; }; }
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for apachectl utility" >&5
+$as_echo_n "checking for apachectl utility... " >&6; }
+    APACHECTL=
+    if test -x "$APACHE_SBINDIR/apachectl" ; then
+      APACHECTL="$APACHE_SBINDIR/apachectl"
+    else
+      if test -x "$APACHE_SBINDIR/apache2ctl" ; then
+        APACHECTL="$APACHE_SBINDIR/apache2ctl"
+      else
+        # Extract the first word of "apachectl", so it can be a program name with args.
+set dummy apachectl; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_path_APACHECTL+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  case $APACHECTL in
+  [\\/]* | ?:[\\/]*)
+  ac_cv_path_APACHECTL="$APACHECTL" # Let the user override the test with a path.
+  ;;
+  *)
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_path_APACHECTL="$as_dir/$ac_word$ac_exec_ext"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
   fi
+done
+  done
+IFS=$as_save_IFS
 
-  ORACLESPATIAL_ENABLED=-DUSE_ORACLESPATIAL
-  ORACLESPATIAL_LIB="-L$ORA_LIBDIR -lclntsh"
-  ORACLESPATIAL_INC="-I$ORA_INCDIR -I$ORA_HOME/rdbms/demo -I$ORA_HOME/rdbms/public"
-
-  echo "$as_me:$LINENO: result:         Oracle Spatial found in $ORA_HOME." >&5
-echo "${ECHO_T}        Oracle Spatial found in $ORA_HOME." >&6
-
+  ;;
+esac
 fi
-
-ORACLESPATIAL_ENABLED=$ORACLESPATIAL_ENABLED
-
-ORACLESPATIAL_INC=$ORACLESPATIAL_INC
-
-ORACLESPATIAL_LIB=$ORACLESPATIAL_LIB
-
-
-ALL_ENABLED="$ORACLESPATIAL_ENABLED $ALL_ENABLED"
-ALL_INC="$ORACLESPATIAL_INC $ALL_INC"
-ALL_LIB="$ORACLESPATIAL_LIB $ALL_LIB"
-
-
-
-
-{ echo "$as_me:$LINENO: checking whether we should include WMS Server support..." >&5
-echo "$as_me: checking whether we should include WMS Server support..." >&6;}
-
-# Check whether --with-wms or --without-wms was given.
-if test "${with_wms+set}" = set; then
-  withval="$with_wms"
-
-fi;
-
-if test "$with_wms" = "no" ; then
-
-  echo "$as_me:$LINENO: result:         OGC WMS Compatibility disabled by --without-wms." >&5
-echo "${ECHO_T}        OGC WMS Compatibility disabled by --without-wms." >&6
-
-elif test -z "$PROJ_ENABLED" ; then
-
-  echo "$as_me:$LINENO: result:         OGC WMS Compatibility not enabled (PROJ.4 is required for WMS)." >&5
-echo "${ECHO_T}        OGC WMS Compatibility not enabled (PROJ.4 is required for WMS)." >&6
-
+APACHECTL=$ac_cv_path_APACHECTL
+if test -n "$APACHECTL"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $APACHECTL" >&5
+$as_echo "$APACHECTL" >&6; }
 else
-
-  WMS_SVR_ENABLED="-DUSE_WMS_SVR"
-  echo "$as_me:$LINENO: result:         OGC WMS compatibility enabled ($WMS_SVR_ENABLED)." >&5
-echo "${ECHO_T}        OGC WMS compatibility enabled ($WMS_SVR_ENABLED)." >&6
-
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
 
-WMS_SVR_ENABLED=$WMS_SVR_ENABLED
 
+        if test -z "$APACHECTL"; then
+          # Extract the first word of "apache2ctl", so it can be a program name with args.
+set dummy apache2ctl; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_path_APACHECTL+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  case $APACHECTL in
+  [\\/]* | ?:[\\/]*)
+  ac_cv_path_APACHECTL="$APACHECTL" # Let the user override the test with a path.
+  ;;
+  *)
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_path_APACHECTL="$as_dir/$ac_word$ac_exec_ext"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
 
-ALL_ENABLED="$WMS_SVR_ENABLED $ALL_ENABLED"
+  ;;
+esac
+fi
+APACHECTL=$ac_cv_path_APACHECTL
+if test -n "$APACHECTL"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $APACHECTL" >&5
+$as_echo "$APACHECTL" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
 
 
+        fi
+      fi
+    fi
 
-{ echo "$as_me:$LINENO: checking whether we should include WFS Server support..." >&5
-echo "$as_me: checking whether we should include WFS Server support..." >&6;}
+    if test -z "$APACHECTL"; then
+      { $as_echo "$as_me:${as_lineno-$LINENO}: result: Unable to find apachectl utility, you will not be able to restart
+                   and install module with the created Makefile" >&5
+$as_echo "Unable to find apachectl utility, you will not be able to restart
+                   and install module with the created Makefile" >&6; }
+    else
+      { $as_echo "$as_me:${as_lineno-$LINENO}: result: $APACHECTL" >&5
+$as_echo "$APACHECTL" >&6; }
+    fi
 
-# Check whether --with-wfs or --without-wfs was given.
-if test "${with_wfs+set}" = set; then
-  withval="$with_wfs"
+    APACHE_INC=-I`$APXS -q INCLUDEDIR`
 
-fi;
+    APACHE_LIBS=`$APXS -q LIBS`
 
-if test "$with_wfs" != "yes" ; then
+    APACHE_LDFLAGS=`$APXS -q LDFLAGS`
 
-  echo "$as_me:$LINENO: result:         OGC WFS Server support not requested." >&5
-echo "${ECHO_T}        OGC WFS Server support not requested." >&6
+    SBINDIR=`$APXS -q SBINDIR`
+    TARGET=`$APXS -q TARGET`
+    HTTPD="$SBINDIR/$TARGET"
+    HTTPD="$HTTPD"
 
-elif test -z "$OGR_ENABLED" ; then
 
-  { { echo "$as_me:$LINENO: error: OGC WFS Server support cannot be enabled: missing OGR which is required)." >&5
-echo "$as_me: error: OGC WFS Server support cannot be enabled: missing OGR which is required)." >&2;}
-   { (exit 1); exit 1; }; }
 
-elif test -z "$PROJ_ENABLED" ; then
 
-  { { echo "$as_me:$LINENO: error: OGC WFS Server support cannot be enabled: missing PROJ4 which is required)." >&5
-echo "$as_me: error: OGC WFS Server support cannot be enabled: missing PROJ4 which is required)." >&2;}
-   { (exit 1); exit 1; }; }
 
-elif test "$with_wfs" = "yes" ; then
 
-  WFS_SVR_ENABLED="-DUSE_WFS_SVR"
-  echo "$as_me:$LINENO: result:         OGC WFS Server support enabled ($WFS_SVR_ENABLED)." >&5
-echo "${ECHO_T}        OGC WFS Server support enabled ($WFS_SVR_ENABLED)." >&6
+# Check whether --with-apr_config was given.
+if test "${with_apr_config+set}" = set; then :
+  withval=$with_apr_config;
+else
+  with_apr_config=yes
 
 fi
 
-WFS_SVR_ENABLED=$WFS_SVR_ENABLED
-
-
-ALL_ENABLED="$WFS_SVR_ENABLED $ALL_ENABLED"
-
-
-
-{ echo "$as_me:$LINENO: checking whether we should include WCS Server support..." >&5
-echo "$as_me: checking whether we should include WCS Server support..." >&6;}
-
-# Check whether --with-wcs or --without-wcs was given.
-if test "${with_wcs+set}" = set; then
-  withval="$with_wcs"
-
-fi;
+    if test "$with_apr_config" = "yes"; then
+        { $as_echo "$as_me:${as_lineno-$LINENO}: checking for apr-config in default locations" >&5
+$as_echo_n "checking for apr-config in default locations... " >&6; }
+        if test -n "$APXS"; then
+            APXSFULL=`which "$APXS"`
+            APXSDIR=`dirname "$APXSFULL"`
+            if test -x "$APXSDIR/apr-config"; then
+                APRCONFIG="$APXSDIR/apr-config"
+            elif test -x "$APACHE_SBINDIR/apr-config"; then
+                APRCONFIG="$APACHE_SBINDIR/apr-config"
+            elif test -x "$APACHE_BINDIR/apr-config"; then
+                APRCONFIG="$APACHE_BINDIR/apr-config"
+            elif test -x "$APXSDIR/apr-1-config"; then
+                APRCONFIG="$APXSDIR/apr-1-config"
+            elif test -x "$APACHE_SBINDIR/apr-1-config"; then
+                APRCONFIG="$APACHE_SBINDIR/apr-1-config"
+            elif test -x "$APACHE_BINDIR/apr-1-config"; then
+                APRCONFIG="$APACHE_BINDIR/apr-1-config"
+            fi
+        fi
+        if test -z "$APRCONFIG"; then
+            # Extract the first word of "apr-config", so it can be a program name with args.
+set dummy apr-config; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_path_APRCONFIG+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  case $APRCONFIG in
+  [\\/]* | ?:[\\/]*)
+  ac_cv_path_APRCONFIG="$APRCONFIG" # Let the user override the test with a path.
+  ;;
+  *)
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_path_APRCONFIG="$as_dir/$ac_word$ac_exec_ext"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
 
-if test "$with_wcs" != "yes" ; then
-  echo "$as_me:$LINENO: result:         OGC WCS Server support not requested." >&5
-echo "${ECHO_T}        OGC WCS Server support not requested." >&6
-elif test -z "$GDAL_ENABLED" ; then
-  { { echo "$as_me:$LINENO: error: OGC WCS Server support cannot be enabled: missing GDAL which is required)." >&5
-echo "$as_me: error: OGC WCS Server support cannot be enabled: missing GDAL which is required)." >&2;}
-   { (exit 1); exit 1; }; }
-elif test -z "$PROJ_ENABLED" ; then
-  { { echo "$as_me:$LINENO: error: OGC WCS Server support cannot be enabled: missing PROJ4 which is required)." >&5
-echo "$as_me: error: OGC WCS Server support cannot be enabled: missing PROJ4 which is required)." >&2;}
-   { (exit 1); exit 1; }; }
-elif test "$with_wcs" = "yes" ; then
-  WCS_SVR_ENABLED="-DUSE_WCS_SVR"
-  echo "$as_me:$LINENO: result:         OGC WCS Server support enabled ($WCS_SVR_ENABLED)." >&5
-echo "${ECHO_T}        OGC WCS Server support enabled ($WCS_SVR_ENABLED)." >&6
+  ;;
+esac
+fi
+APRCONFIG=$ac_cv_path_APRCONFIG
+if test -n "$APRCONFIG"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $APRCONFIG" >&5
+$as_echo "$APRCONFIG" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
 
-WCS_SVR_ENABLED=$WCS_SVR_ENABLED
 
-ALL_ENABLED="$WCS_SVR_ENABLED $ALL_ENABLED"
+        fi
+        if test -z "$APRCONFIG"; then
+            # Extract the first word of "apr-1-config", so it can be a program name with args.
+set dummy apr-1-config; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_path_APRCONFIG+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  case $APRCONFIG in
+  [\\/]* | ?:[\\/]*)
+  ac_cv_path_APRCONFIG="$APRCONFIG" # Let the user override the test with a path.
+  ;;
+  *)
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_path_APRCONFIG="$as_dir/$ac_word$ac_exec_ext"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+  ;;
+esac
+fi
+APRCONFIG=$ac_cv_path_APRCONFIG
+if test -n "$APRCONFIG"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $APRCONFIG" >&5
+$as_echo "$APRCONFIG" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
 
 
+        fi
+        if test -n "$APRCONFIG"; then
+            { $as_echo "$as_me:${as_lineno-$LINENO}: result: using $APRCONFIG, use --with-apr-config=/path/to/apr-(1-)config to modify" >&5
+$as_echo "using $APRCONFIG, use --with-apr-config=/path/to/apr-(1-)config to modify" >&6; }
+        else
+            { $as_echo "$as_me:${as_lineno-$LINENO}: result: not found" >&5
+$as_echo "not found" >&6; }
+        fi
+    elif test "$with_apr_config" = "no"; then
+        as_fn_error $? "apr-config is required and cannot be disabled" "$LINENO" 5
+    else
+        { $as_echo "$as_me:${as_lineno-$LINENO}: checking for apr-config usability in $with_apr_config" >&5
+$as_echo_n "checking for apr-config usability in $with_apr_config... " >&6; }
+        if test -x "$with_apr_config"; then
+            APRCONFIG=$with_apr_config
+            { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+        else
+            as_fn_error $? "$with_apr_config not found or not executable" "$LINENO" 5
+        fi
+    fi
+    if test -z "$APRCONFIG"; then
+        as_fn_error $? "apr-config utility not found. use --with-apr-config to specify its location." "$LINENO" 5
+    fi
 
-{ echo "$as_me:$LINENO: checking whether we should include WMS Client Connections support..." >&5
-echo "$as_me: checking whether we should include WMS Client Connections support..." >&6;}
+    APR_CFLAGS=`$APRCONFIG --cppflags --cflags`
 
-# Check whether --with-wmsclient or --without-wmsclient was given.
-if test "${with_wmsclient+set}" = set; then
-  withval="$with_wmsclient"
+    APR_INC=`$APRCONFIG --includes`
 
-fi;
+    APR_LIBS=`$APRCONFIG --link-libtool`
 
-if test "$with_wmsclient" = "no" ; then
 
-  echo "$as_me:$LINENO: result:         OGC WMS Client Layers disabled by --without-wmsclient." >&5
-echo "${ECHO_T}        OGC WMS Client Layers disabled by --without-wmsclient." >&6
+      if test -z "$APRCONFIG"; then
+         as_fn_error $? "apr-config utility not found. use --with-apr-config to specify its location." "$LINENO" 5
+      else
+         ALL_ENABLED="-DMOD_WMS_ENABLED $ALL_ENABLED"
+      fi
+   fi
 
-elif test -z "$PROJ_ENABLED" -o -z "$GDAL_ENABLED"; then
 
-  echo "$as_me:$LINENO: result:         OGC WMS Client Connections not enabled (PROJ.4, libcurl and GDAL required)." >&5
-echo "${ECHO_T}        OGC WMS Client Connections not enabled (PROJ.4, libcurl and GDAL required)." >&6
 
-elif test "$with_wmsclient" = "yes" ; then
 
-    WMS_REQUESTED="yes"
+MS_DIR="`pwd`"
+MS_INC="-I$MS_DIR"
+MS_LIB="-L$MS_DIR -lmapserver"
 
-fi
+  if test ""$MS_DIR"" != "/usr/lib"; then
 
+  if test -z ""$MS_DIR"" || echo ""$MS_DIR"" | grep '^/' >/dev/null ; then
+    ai_p=""$MS_DIR""
+  else
+    ai_p="`pwd`/"$MS_DIR""
+  fi
 
-{ echo "$as_me:$LINENO: checking whether we should include WFS Client Connections support..." >&5
-echo "$as_me: checking whether we should include WFS Client Connections support..." >&6;}
 
-# Check whether --with-wfsclient or --without-wfsclient was given.
-if test "${with_wfsclient+set}" = set; then
-  withval="$with_wfsclient"
+  unique=`echo $ac_n "$ai_p$ac_c" | tr -c -d a-zA-Z0-9`
+  cmd="echo $ac_n \"\$LIBPATH$unique$ac_c\""
+  if test -n "$unique" && test "`eval $cmd`" = "" ; then
+    eval "LIBPATH$unique=set"
 
-fi;
+      EXTRA_LIBS="$EXTRA_LIBS -L$ai_p"
+        RPATHS="$RPATHS ${ld_runpath_switch}$ai_p"
 
-if test "$with_wfsclient" = "no" ; then
+  fi
 
-  echo "$as_me:$LINENO: result:         OGC WFS Client Layers disabled by --without-wfsclient." >&5
-echo "${ECHO_T}        OGC WFS Client Layers disabled by --without-wfsclient." >&6
+  fi
 
-elif test -z "$PROJ_ENABLED" -o -z "$OGR_ENABLED"; then
+MS_INC=$MS_INC
 
-  echo "$as_me:$LINENO: result:         OGC WFS Client Connections not enabled (PROJ.4, libcurl and OGR required)." >&5
-echo "${ECHO_T}        OGC WFS Client Connections not enabled (PROJ.4, libcurl and OGR required)." >&6
+MS_LIB=$MS_LIB
 
-elif test "$with_wfsclient" = "yes" ; then
 
-    WFS_REQUESTED="yes"
 
+# Check whether --enable-ignore-missing-data was given.
+if test "${enable_ignore_missing_data+set}" = set; then :
+  enableval=$enable_ignore_missing_data;
 fi
 
+if test "$enable_ignore_missing_data" = "yes" ; then
 
-{ echo "$as_me:$LINENO: checking whether we should include OGC SOS Server support..." >&5
-echo "$as_me: checking whether we should include OGC SOS Server support..." >&6;}
-
-# Check whether --with-sos or --without-sos was given.
-if test "${with_sos+set}" = set; then
-  withval="$with_sos"
+  IGNORE_MISSING_DATA="-DIGNORE_MISSING_DATA"
 
-fi;
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: Compiling with -DIGNORE_MISSING_DATA." >&5
+$as_echo "Compiling with -DIGNORE_MISSING_DATA." >&6; }
+fi
+IGNORE_MISSING_DATA=$IGNORE_MISSING_DATA
 
-if test "x$with_sos" != "xyes" ; then
+ALL_ENABLED="$IGNORE_MISSING_DATA $ALL_ENABLED"
 
-  echo "$as_me:$LINENO: result:         OGC SOS Server support not requested." >&5
-echo "${ECHO_T}        OGC SOS Server support not requested." >&6
 
-else
+# Check whether --enable-point-z-m was given.
+if test "${enable_point_z_m+set}" = set; then :
+  enableval=$enable_point_z_m;
+fi
 
-  if test -z "$PROJ_ENABLED" ; then
-    { { echo "$as_me:$LINENO: error:         OGC SOS Support requested, but PROJ.4 required and missing." >&5
-echo "$as_me: error:         OGC SOS Support requested, but PROJ.4 required and missing." >&2;}
-   { (exit 1); exit 1; }; }
-  fi
-  if test -z "$OGR_ENABLED" ; then
-    { { echo "$as_me:$LINENO: error:         OGC SOS Support requested, but OGR required and missing." >&5
-echo "$as_me: error:         OGC SOS Support requested, but OGR required and missing." >&2;}
-   { (exit 1); exit 1; }; }
-  fi
+if test "$enable_point_z_m" = "yes" ; then
 
-    SOS_REQUESTED="yes"
-  echo "$as_me:$LINENO: result:         OGC SOS Server support requested." >&5
-echo "${ECHO_T}        OGC SOS Server support requested." >&6
+  USE_POINT_Z_M="-DUSE_POINT_Z_M"
 
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: Compiling with -DUSE_POINT_Z_M." >&5
+$as_echo "Compiling with -DUSE_POINT_Z_M." >&6; }
 fi
+USE_POINT_Z_M=$USE_POINT_Z_M
 
+ALL_ENABLED="$USE_POINT_Z_M $ALL_ENABLED"
 
-echo "$as_me:$LINENO: checking for curl-config" >&5
-echo $ECHO_N "checking for curl-config... $ECHO_C" >&6
-
-# Check whether --with-curl-config or --without-curl-config was given.
-if test "${with_curl_config+set}" = set; then
-  withval="$with_curl_config"
 
-fi;
 
-unset ac_cv_path_LIBCURL_CONFIG
+# Check whether --enable-fast-nint was given.
+if test "${enable_fast_nint+set}" = set; then :
+  enableval=$enable_fast_nint;
+fi
 
-if test "$WMS_REQUESTED" = "yes" -o "$WFS_REQUESTED" = "yes" ; then
 
-  if test "`basename xx/$with_curl_config`" = "curl-config" ; then
-    LIBCURL_CONFIG="$with_curl_config"
-    if test -f "$LIBCURL_CONFIG" -a -x "$LIBCURL_CONFIG" ; then
-      echo "$as_me:$LINENO: result: yes, user supplied curl-config ($LIBCURL_CONFIG)" >&5
-echo "${ECHO_T}yes, user supplied curl-config ($LIBCURL_CONFIG)" >&6
-    else
-      { { echo "$as_me:$LINENO: error: '$LIBCURL_CONFIG' is not an executable.  Make sure you use --with-curl-config=/path/to/curl-config" >&5
-echo "$as_me: error: '$LIBCURL_CONFIG' is not an executable.  Make sure you use --with-curl-config=/path/to/curl-config" >&2;}
-   { (exit 1); exit 1; }; }
-    fi
-  else
-    # Extract the first word of "curl-config", so it can be a program name with args.
-set dummy curl-config; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
-if test "${ac_cv_path_LIBCURL_CONFIG+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  case $LIBCURL_CONFIG in
-  [\\/]* | ?:[\\/]*)
-  ac_cv_path_LIBCURL_CONFIG="$LIBCURL_CONFIG" # Let the user override the test with a path.
-  ;;
-  *)
-  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_path_LIBCURL_CONFIG="$as_dir/$ac_word$ac_exec_ext"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
+if test "$enable_fast_nint" = "no" ; then
 
-  test -z "$ac_cv_path_LIBCURL_CONFIG" && ac_cv_path_LIBCURL_CONFIG="no"
-  ;;
-esac
-fi
-LIBCURL_CONFIG=$ac_cv_path_LIBCURL_CONFIG
+  USE_NINT="-DUSE_GENERIC_MS_NINT"
 
-if test -n "$LIBCURL_CONFIG"; then
-  echo "$as_me:$LINENO: result: $LIBCURL_CONFIG" >&5
-echo "${ECHO_T}$LIBCURL_CONFIG" >&6
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: Compiling with safe MS_NINT" >&5
+$as_echo "Compiling with safe MS_NINT" >&6; }
 else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
+  USE_NINT=""
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: Compiling with fast MS_NINT" >&5
+$as_echo "Compiling with fast MS_NINT" >&6; }
 fi
+USE_NINT=$USE_NINT
 
-  fi
+ALL_ENABLED="$USE_NINT $ALL_ENABLED"
 
-  if test "$LIBCURL_CONFIG" = "no" ; then
-    { { echo "$as_me:$LINENO: error: couldn't find curl-config, try using --with-curl-config=PATH" >&5
-echo "$as_me: error: couldn't find curl-config, try using --with-curl-config=PATH" >&2;}
-   { (exit 1); exit 1; }; }
-  fi
 
-  CURL_VERNUM=`$LIBCURL_CONFIG --vernum`
-  CURL_VER=`$LIBCURL_CONFIG --version | awk '{print $2}'`
-  CURL_FLAGS=""
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking compiler warnings" >&5
+$as_echo_n "checking compiler warnings... " >&6; }
 
-  echo "$as_me:$LINENO: result:         found libcurl version $CURL_VER" >&5
-echo "${ECHO_T}        found libcurl version $CURL_VER" >&6
 
-    if test -z "$CURL_VERNUM" -o `expr "0x$CURL_VERNUM" \< "0x070a01"` = 1; then
-    { { echo "$as_me:$LINENO: error: libcurl version 7.10.1 or more recent is required." >&5
-echo "$as_me: error: libcurl version 7.10.1 or more recent is required." >&2;}
-   { (exit 1); exit 1; }; }
-  fi
+# Check whether --with-warnings was given.
+if test "${with_warnings+set}" = set; then :
+  withval=$with_warnings;
+fi
 
-    echo "$as_me:$LINENO: checking for CURLOPT_PROXYAUTH support" >&5
-echo $ECHO_N "checking for CURLOPT_PROXYAUTH support... $ECHO_C" >&6
-  if test -z "$CURL_VERNUM" -o `expr "0x$CURL_VERNUM" \>= "0x070a07"` = 1; then
-    echo "$as_me:$LINENO: result: yes." >&5
-echo "${ECHO_T}yes." >&6
-    CURL_FLAGS="-DUSE_CURLOPT_PROXYAUTH"
-  else
-    echo "$as_me:$LINENO: result: no." >&5
-echo "${ECHO_T}no." >&6
-  fi
 
-      if test "$WMS_REQUESTED" = "yes" ; then
-    WMS_LYR_ENABLED="-DUSE_WMS_LYR"
-    echo "$as_me:$LINENO: result:         OGC WMS Client Connections enabled ($WMS_LYR_ENABLED)." >&5
-echo "${ECHO_T}        OGC WMS Client Connections enabled ($WMS_LYR_ENABLED)." >&6
-  fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking C_WFLAGS for maximum warnings" >&5
+$as_echo_n "checking C_WFLAGS for maximum warnings... " >&6; }
+if ${ac_cv_cflags_warn_all+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_cv_cflags_warn_all="no, unknown"
 
-  if test "$WFS_REQUESTED" = "yes" ; then
-    WFS_LYR_ENABLED="-DUSE_WFS_LYR"
-    echo "$as_me:$LINENO: result:         OGC WFS Client Connections enabled ($WFS_LYR_ENABLED)." >&5
-echo "${ECHO_T}        OGC WFS Client Connections enabled ($WFS_LYR_ENABLED)." >&6
-  fi
+ ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
-  CURL_INC=`$LIBCURL_CONFIG --cflags`
-  CURL_LIB=`$LIBCURL_CONFIG --libs`
-  CURL_ENABLED="-DUSE_CURL $CURL_FLAGS"
+ ac_save_CFLAGS="$CFLAGS"
+for ac_arg in "-pedantic -Wdeclaration-after-statement %        -Wall -Wdeclaration-after-statement"    "-pedantic  % -Wall"          "-xstrconst % -v"             "-std1      % -verbose -w0 -warnprotos"    "-qlanglvl=ansi % -qsrcmsg -qinfo=all:noppt:noppc:noobs:nocnd"    "-ansi -ansiE % -fullwarn"    "+ESlit     % +w1"            "-Xc        % -pvctl,fullmsg"    "-h conform % -h msglevel 2"    #
+do CFLAGS="$ac_save_CFLAGS "`echo $ac_arg | sed -e 's,%%.*,,' -e 's,%,,'`
+   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
 
+int
+main ()
+{
+return 0;
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_cflags_warn_all=`echo $ac_arg | sed -e 's,.*% *,,'` ; break
 fi
-
-CURL_INC=$CURL_INC
-
-CURL_LIB=$CURL_LIB
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+done
+ CFLAGS="$ac_save_CFLAGS"
+ ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
 
-ALL_INC="$CURL_INC $ALL_INC"
-ALL_LIB="$CURL_LIB $ALL_LIB"
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_cflags_warn_all" >&5
+$as_echo "$ac_cv_cflags_warn_all" >&6; }
+case ".$ac_cv_cflags_warn_all" in
+     .ok|.ok,*)  ;;
+   .|.no|.no,*)
+ ;;
+   *)
+   if echo " $C_WFLAGS " | grep " $ac_cv_cflags_warn_all " 2>&1 >/dev/null
+   then { { $as_echo "$as_me:${as_lineno-$LINENO}: : C_WFLAGS does contain \$ac_cv_cflags_warn_all"; } >&5
+  (: C_WFLAGS does contain $ac_cv_cflags_warn_all) 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }
+   else { { $as_echo "$as_me:${as_lineno-$LINENO}: : C_WFLAGS=\"\$C_WFLAGS \$ac_cv_cflags_warn_all\""; } >&5
+  (: C_WFLAGS="$C_WFLAGS $ac_cv_cflags_warn_all") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }
+                      C_WFLAGS="$C_WFLAGS $ac_cv_cflags_warn_all"
+   fi
+ ;;
+esac
 
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking CXX_WFLAGS for maximum warnings" >&5
+$as_echo_n "checking CXX_WFLAGS for maximum warnings... " >&6; }
+if ${ac_cv_cxxflags_warn_all+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_cv_cxxflags_warn_all="no, unknown"
 
+ ac_ext=cpp
+ac_cpp='$CXXCPP $CPPFLAGS'
+ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
 
-# Check whether --with-kml or --without-kml was given.
-if test "${with_kml+set}" = set; then
-  withval="$with_kml"
+ ac_save_CXXFLAGS="$CXXFLAGS"
+for ac_arg in "-pedantic  % -Wall"          "-xstrconst % -v"             "-std1      % -verbose -w0 -warnprotos"    "-qlanglvl=ansi % -qsrcmsg -qinfo=all:noppt:noppc:noobs:nocnd"    "-ansi -ansiE % -fullwarn"    "+ESlit     % +w1"            "-Xc        % -pvctl,fullmsg"    "-h conform % -h msglevel 2"    #
+do CXXFLAGS="$ac_save_CXXFLAGS "`echo $ac_arg | sed -e 's,%%.*,,' -e 's,%,,'`
+   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
 
-fi;
+int
+main ()
+{
+return 0;
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_cxx_try_compile "$LINENO"; then :
+  ac_cv_cxxflags_warn_all=`echo $ac_arg | sed -e 's,.*% *,,'` ; break
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+done
+ CXXFLAGS="$ac_save_CXXFLAGS"
+ ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
-echo "$as_me:$LINENO: checking if KML output is requested" >&5
-echo $ECHO_N "checking if KML output is requested... $ECHO_C" >&6
-KML_REQUESTED=""
 
-if test "$with_kml" = "yes"; then
-    echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6
-    KML_REQUESTED="yes"
-else
-    echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
 fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_cxxflags_warn_all" >&5
+$as_echo "$ac_cv_cxxflags_warn_all" >&6; }
+case ".$ac_cv_cxxflags_warn_all" in
+     .ok|.ok,*)  ;;
+   .|.no|.no,*)
+ ;;
+   *)
+   if echo " $CXX_WFLAGS " | grep " $ac_cv_cxxflags_warn_all " 2>&1 >/dev/null
+   then { { $as_echo "$as_me:${as_lineno-$LINENO}: : CXX_WFLAGS does contain \$ac_cv_cxxflags_warn_all"; } >&5
+  (: CXX_WFLAGS does contain $ac_cv_cxxflags_warn_all) 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }
+   else { { $as_echo "$as_me:${as_lineno-$LINENO}: : CXX_WFLAGS=\"\$CXX_WFLAGS \$ac_cv_cxxflags_warn_all\""; } >&5
+  (: CXX_WFLAGS="$CXX_WFLAGS $ac_cv_cxxflags_warn_all") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }
+                      CXX_WFLAGS="$CXX_WFLAGS $ac_cv_cxxflags_warn_all"
+   fi
+ ;;
+esac
 
 
-echo "$as_me:$LINENO: checking for libxml2" >&5
-echo $ECHO_N "checking for libxml2... $ECHO_C" >&6
+if test "$with_warnings" = "yes" ; then
+  if test "$GCC" = "yes" ; then
+    WFLAGS="-W -Wcast-align -Wmissing-prototypes -Wstrict-prototypes -Wpointer-arith -Wreturn-type"
+    C_WFLAGS="$C_WFLAGS -Wmissing-declarations"
 
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: strict" >&5
+$as_echo "strict" >&6; }
+  else
+    WFLAGS=""
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: disabled" >&5
+$as_echo "disabled" >&6; }
+  fi
 
-# Check whether --with-xml2-config or --without-xml2-config was given.
-if test "${with_xml2_config+set}" = set; then
-  withval="$with_xml2_config"
+elif test "$with_warnings" = "no" ; then
+  WFLAGS=""
+  C_WFLAGS=""
+  CXX_WFLAGS=""
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: disabled" >&5
+$as_echo "disabled" >&6; }
 
-fi;
+elif test "$with_warnings" != "" ; then
+  WFLAGS="$with_warnings"
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: user defined" >&5
+$as_echo "user defined" >&6; }
+fi
 
-unset ac_cv_path_LIBXML2_CONFIG
+CFLAGS="$CFLAGS $WFLAGS $C_WFLAGS"
+CXXFLAGS="$CXXFLAGS $WFLAGS $CXX_WFLAGS"
 
 
-if test -z "$with_xml2_config" ; then
-  if test "x$SOS_REQUESTED" = "xyes" ; then
-    with_xml2_config=yes
-    echo "$as_me:$LINENO: result: libxml2 required." >&5
-echo "${ECHO_T}libxml2 required." >&6
-  elif test "x$KML_REQUESTED" = "xyes" ; then
-    with_xml2_config=yes
-    echo "$as_me:$LINENO: result: libxml2 required." >&5
-echo "${ECHO_T}libxml2 required." >&6
-  elif test "x$WCS_SVR_ENABLED" != "x" ; then
-    with_xml2_config=yes
-    echo "$as_me:$LINENO: result: libxml2 requested for WCS Server." >&5
-echo "${ECHO_T}libxml2 requested for WCS Server." >&6
-    echo "$as_me:$LINENO: result:       If unavailable disable using --without-xml2-config," >&5
-echo "${ECHO_T}      If unavailable disable using --without-xml2-config," >&6
-    echo "$as_me:$LINENO: result:       but WCS 1.1 support will be disabled." >&5
-echo "${ECHO_T}      but WCS 1.1 support will be disabled." >&6
-  elif test "x$WFS_SVR_ENABLED" != "x" ; then
-    with_xml2_config=yes
-    echo "$as_me:$LINENO: result: libxml2 requested for WFS Server." >&5
-echo "${ECHO_T}libxml2 requested for WFS Server." >&6
-    echo "$as_me:$LINENO: result:       If unavailable disable using --without-xml2-config," >&5
-echo "${ECHO_T}      If unavailable disable using --without-xml2-config," >&6
-    echo "$as_me:$LINENO: result:       but WFS 1.1 support will be disabled." >&5
-echo "${ECHO_T}      but WFS 1.1 support will be disabled." >&6
-  else
-    with_xml2_config=no
-    echo "$as_me:$LINENO: result: libxml2 not required." >&5
-echo "${ECHO_T}libxml2 not required." >&6
-  fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we should enable debug features..." >&5
+$as_echo "$as_me: checking whether we should enable debug features..." >&6;}
+# Check whether --enable-debug was given.
+if test "${enable_debug+set}" = set; then :
+  enableval=$enable_debug;
 fi
 
-if test "$with_xml2_config" != "no" ; then
 
-  if test "`basename xx/$with_xml2_config`" = "xml2-config" ; then
-    LIBXML2_CONFIG="$with_xml2_config"
-    if test -f "$LIBXML2_CONFIG" -a -x "$LIBXML2_CONFIG" ; then
-      echo "$as_me:$LINENO: result: yes, user supplied xml2-config ($LIBXML2_CONFIG)" >&5
-echo "${ECHO_T}yes, user supplied xml2-config ($LIBXML2_CONFIG)" >&6
-    else
-      { { echo "$as_me:$LINENO: error: '$LIBXML2_CONFIG' is not an executable.  Make sure you use --with-xml2-config=/path/to/xml2-config" >&5
-echo "$as_me: error: '$LIBXML2_CONFIG' is not an executable.  Make sure you use --with-xml2-config=/path/to/xml2-config" >&2;}
-   { (exit 1); exit 1; }; }
-    fi
-  else
-    # Extract the first word of "xml2-config", so it can be a program name with args.
-set dummy xml2-config; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
-if test "${ac_cv_path_LIBXML2_CONFIG+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  case $LIBXML2_CONFIG in
-  [\\/]* | ?:[\\/]*)
-  ac_cv_path_LIBXML2_CONFIG="$LIBXML2_CONFIG" # Let the user override the test with a path.
-  ;;
-  *)
-  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_path_LIBXML2_CONFIG="$as_dir/$ac_word$ac_exec_ext"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
+if test "$enable_debug" = "yes" ; then
+    CXXFLAGS=`echo "$CXXFLAGS " | sed 's/-O[123] / /'`
+  CFLAGS=`echo "$CFLAGS " | sed 's/-O[123] / /'`
 
-  test -z "$ac_cv_path_LIBXML2_CONFIG" && ac_cv_path_LIBXML2_CONFIG="no"
-  ;;
-esac
-fi
-LIBXML2_CONFIG=$ac_cv_path_LIBXML2_CONFIG
+  REPORT_ENABLE_DEBUG="-g "
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result:         Enabling debug features: -g in CFLAGS." >&5
+$as_echo "        Enabling debug features: -g in CFLAGS." >&6; }
 
-if test -n "$LIBXML2_CONFIG"; then
-  echo "$as_me:$LINENO: result: $LIBXML2_CONFIG" >&5
-echo "${ECHO_T}$LIBXML2_CONFIG" >&6
 else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
+  CXXFLAGS=`echo "$CXXFLAGS -DNDEBUG " | sed "s/-g //"`
+  CFLAGS=`echo "$CFLAGS -DNDEBUG " | sed "s/-g //"`
 fi
 
-  fi
-
-  if test "$LIBXML2_CONFIG" = "no" ; then
-   { { echo "$as_me:$LINENO: error: couldn't find xml2-config, try using --with-xml2-config=PATH" >&5
-echo "$as_me: error: couldn't find xml2-config, try using --with-xml2-config=PATH" >&2;}
-   { (exit 1); exit 1; }; }
-  fi
-
-  XML2_VER=`$LIBXML2_CONFIG --version`
-
-  echo "$as_me:$LINENO: result:         found libxml2 version $XML2_VER" >&5
-echo "${ECHO_T}        found libxml2 version $XML2_VER" >&6
-
-  XML2_INC=`$LIBXML2_CONFIG --cflags`
-  XML2_LIB=`$LIBXML2_CONFIG --libs`
-  XML2_ENABLED=-DUSE_LIBXML2
-
-  if test "$SOS_REQUESTED" = "yes" ; then
-    SOS_SVR_ENABLED="-DUSE_SOS_SVR"
-  fi
-  if test "$KML_REQUESTED" = "yes" ; then
-    KML_ENABLED="-DUSE_KML"
-  fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to enable proj shortcuts..." >&5
+$as_echo "$as_me: checking whether to enable proj shortcuts..." >&6;}
+# Check whether --enable-proj-fastpath was given.
+if test "${enable_proj_fastpath+set}" = set; then :
+  enableval=$enable_proj_fastpath;
 fi
 
-XML2_INC=$XML2_INC
 
-XML2_LIB=$XML2_LIB
+if test "$enable_proj_fastpath" = "yes" ; then
+   PROJ_FASTPATH_ENABLED="-DUSE_PROJ_FASTPATHS"
+   ALL_ENABLED="$PROJ_FASTPATH_ENABLED $ALL_ENABLED"
+fi
+PROJ_FASTPATH_ENABLED=$PROJ_FASTPATH_ENABLED
+
 
 
-ALL_INC="$XML2_INC $ALL_INC"
-ALL_LIB="$XML2_LIB $ALL_LIB"
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we should enable mapserv CGI command-line debug arguments..." >&5
+$as_echo "$as_me: checking whether we should enable mapserv CGI command-line debug arguments..." >&6;}
+# Check whether --enable-cgi-cl-debug-args was given.
+if test "${enable_cgi_cl_debug_args+set}" = set; then :
+  enableval=$enable_cgi_cl_debug_args;
+fi
 
 
-WMS_LYR_ENABLED=$WMS_LYR_ENABLED
+if test "$enable_cgi_cl_debug_args" = "yes" ; then
+  DEBUG_FLAGS="$DEBUG_FLAGS -DMS_ENABLE_CGI_CL_DEBUG_ARGS"
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result:         Enabling (potentially insecure) mapserv CGI command-line debug arguments: -DMS_ENABLE_CGI_CL_DEBUG_ARGS." >&5
+$as_echo "        Enabling (potentially insecure) mapserv CGI command-line debug arguments: -DMS_ENABLE_CGI_CL_DEBUG_ARGS." >&6; }
+fi
 
-WFS_LYR_ENABLED=$WFS_LYR_ENABLED
+DEBUG_FLAGS=$DEBUG_FLAGS
 
-SOS_SVR_ENABLED=$SOS_SVR_ENABLED
+ALL_ENABLED="$DEBUG_FLAGS $ALL_ENABLED"
 
 
-ALL_ENABLED="$WMS_LYR_ENABLED $WFS_LYR_ENABLED $SOS_SVR_ENABLED $XML2_ENABLED $CURL_ENABLED $KML_ENABLED $ALL_ENABLED"
 
+# Check whether --enable-gcov was given.
+if test "${enable_gcov+set}" = set; then :
+  enableval=$enable_gcov; CFLAGS="$CFLAGS -fprofile-arcs -ftest-coverage"
+ PHP_LD_XTRAFLAGS="$PHP_LD_XTRAFLAGS -fprofile-arcs -ftest-coverage"
+fi
 
 
 
-# Check whether --with-xml-mapfile or --without-xml-mapfile was given.
-if test "${with_xml_mapfile+set}" = set; then
-  withval="$with_xml_mapfile"
-  XMLMAPFILE_REQUESTED=""
-fi;
 
-echo "$as_me:$LINENO: checking if xml-mapfile is requested" >&5
-echo $ECHO_N "checking if xml-mapfile is requested... $ECHO_C" >&6
-XMLMAPFILE_ENABLED=""
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for PHP/MapScript module options..." >&5
+$as_echo "$as_me: checking for PHP/MapScript module options..." >&6;}
 
-if test "$with_xml_mapfile" = "yes"; then
-  XMLMAPFILE_ENABLED="-DUSE_XMLMAPFILE"
-  echo "$as_me:$LINENO: result: yes.. xslt and exslt support needed" >&5
-echo "${ECHO_T}yes.. xslt and exslt support needed" >&6
+# Check whether --with-php was given.
+if test "${with_php+set}" = set; then :
+  withval=$with_php;
 else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
+  with_php=no
 fi
 
-ALL_ENABLED="$XMLMAPFILE_ENABLED $ALL_ENABLED"
-
 
+# Check whether --enable-internal-ld-detect was given.
+if test "${enable_internal_ld_detect+set}" = set; then :
+  enableval=$enable_internal_ld_detect;
+fi
 
-# Check whether --with-xslt or --without-xslt was given.
-if test "${with_xslt+set}" = set; then
-  withval="$with_xslt"
-  XSLT_DIR=$withval
-else
-  XSLT_DIR=''
-fi;
 
-echo "$as_me:$LINENO: checking if xslt is requested" >&5
-echo $ECHO_N "checking if xslt is requested... $ECHO_C" >&6
-XSLT_LIB=''
+if test "$with_php" != "no" ; then
+  if test -d "$with_php"; then
+      as_fn_error $? "--with-php now expects an optional path to php-config, not a directory" "$LINENO" 5
+  fi
+  if test "$with_php" == "yes" ; then
+      # Extract the first word of "php-config", so it can be a program name with args.
+set dummy php-config; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_path_PHPCONFIG+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  case $PHPCONFIG in
+  [\\/]* | ?:[\\/]*)
+  ac_cv_path_PHPCONFIG="$PHPCONFIG" # Let the user override the test with a path.
+  ;;
+  *)
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_path_PHPCONFIG="$as_dir/$ac_word$ac_exec_ext"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
 
-if test -z "$XMLMAPFILE_ENABLED" -a \( "$with_xslt" = "no" -o "$with_xslt" = ""  \); then
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
+  test -z "$ac_cv_path_PHPCONFIG" && ac_cv_path_PHPCONFIG="no"
+  ;;
+esac
+fi
+PHPCONFIG=$ac_cv_path_PHPCONFIG
+if test -n "$PHPCONFIG"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $PHPCONFIG" >&5
+$as_echo "$PHPCONFIG" >&6; }
 else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
 
-  if test "$XSLT_DIR" = "yes" -o "$XSLT_DIR" = ""; then
-     XSLT_DIR="/usr"
-  fi
 
-  test -f $XSLT_DIR/include/libxslt/xslt.h && XSLT_INCDIR="$XSLT_DIR/include"
-  test -f $XSLT_DIR/lib/libxslt.so && XSLT_LIBDIR="$XSLT_DIR/lib"
-  test -f $XSLT_DIR/lib64/libxslt.so && XSLT_LIBDIR="$XSLT_DIR/lib64"
+      if test "x$PHPCONFIG" == "xno"; then
+         as_fn_error $? "php-config not found on path, please give its full location" "$LINENO" 5
+      fi
+  else
+      PHPCONFIG="$with_php"
+  fi
+  if test ! -f "$PHPCONFIG"; then
+      as_fn_error $? "$PHPCONFIG not found" "$LINENO" 5
+  fi
 
-  if test -n "$XSLT_LIBDIR" -a -n "$XSLT_INCDIR" ; then
-                XSLT_ENABLED="-DUSE_XSLT"
-    XSLT_INC="-I$XSLT_INCDIR"
-    XSLT_LIB="-L$XSLT_LIBDIR -lxslt"
-    echo "$as_me:$LINENO: result: using xslt from $XSLT_LIB ($XSLT_ENABLED)" >&5
-echo "${ECHO_T}using xslt from $XSLT_LIB ($XSLT_ENABLED)" >&6
+  PHPINCDIR=`$PHPCONFIG --include-dir`
 
-  if test ""$XSLT_DIR"" != "/usr/lib"; then
+          { $as_echo "$as_me:${as_lineno-$LINENO}: checking for location of php_config.h" >&5
+$as_echo_n "checking for location of php_config.h... " >&6; }
+    test -f "$PHPINCDIR/main/php_config.h" && PHP_CONFIG_H="$PHPINCDIR/main/php_config.h"
 
-  if test -z ""$XSLT_DIR"" || echo ""$XSLT_DIR"" | grep '^/' >/dev/null ; then
-    ai_p=""$XSLT_DIR""
+  if test -n "$PHP_CONFIG_H" ; then
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: $PHP_CONFIG_H" >&5
+$as_echo "$PHP_CONFIG_H" >&6; }
   else
-    ai_p="`pwd`/"$XSLT_DIR""
+    as_fn_error $? "
+!!! Could not find php_config.h and php_version.h in $PHPINCDIR.          !!!
+!!! Has PHP been installed yet?                                      !!!" "$LINENO" 5
   fi
 
 
-  unique=`echo $ac_n "$ai_p$ac_c" | tr -c -d a-zA-Z0-9`
-  cmd="echo $ac_n \"\$LIBPATH$unique$ac_c\""
-  if test -n "$unique" && test "`eval $cmd`" = "" ; then
-    eval "LIBPATH$unique=set"
-
-      EXTRA_LIBS="$EXTRA_LIBS -L$ai_p"
-        RPATHS="$RPATHS ${ld_runpath_switch}$ai_p"
-
+        { $as_echo "$as_me:${as_lineno-$LINENO}: checking if we have PHP 5.2.0+" >&5
+$as_echo_n "checking if we have PHP 5.2.0+... " >&6; }
+  PHP_VERSION=`$PHPCONFIG --vernum`
+  if test -z "$PHP_VERSION" || test $PHP_VERSION -lt 50200; then
+    as_fn_error $? "
+!!! PHP MapScript now requires PHP 5.2.0 or more recent.              !!!
+!!! Support for PHP3 has been dropped after MapServer version 3.5.    !!!
+!!! Support for PHP4 has been dropped after MapServer version 5.6.    !!!" "$LINENO" 5
+  else
+     { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
   fi
 
-  fi
+          { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we should use PHP's regex" >&5
+$as_echo_n "checking whether we should use PHP's regex... " >&6; }
+  if test -n "`grep 'define REGEX 1' $PHP_CONFIG_H`"  ; then
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
 
+            test -f "$PHPINCDIR/regex/regex_extra.h" && PHP_NO_SOURCE="1"
+        if test -n "$PHP_NO_SOURCE" ; then
+                    USE_PHP_REGEX="-DUSE_PHP_REGEX"
+          PHP_REGEX_INC="-I$PHPINCDIR"
+          PHP_REGEX_OBJ=php_regex.lo
+          { $as_echo "$as_me:${as_lineno-$LINENO}: result:         found regex_extra.h - building PHP MapScript with PHP's bundled regex " >&5
+$as_echo "        found regex_extra.h - building PHP MapScript with PHP's bundled regex " >&6; }
+        else
+                    test -f "$PHPINCDIR/ext/ereg/regex/regex.h" && PHP_NO_SOURCE="1"
+          if test -n "$PHP_NO_SOURCE" ; then
+                    USE_PHP_REGEX="-DUSE_PHP_REGEX"
+          PHP_REGEX_INC="-I$PHPINCDIR/ext/ereg/"
+          PHP_REGEX_OBJ=php_regex.lo
+          { $as_echo "$as_me:${as_lineno-$LINENO}: result:         found regex.h - building PHP MapScript with PHP's bundled regex " >&5
+$as_echo "        found regex.h - building PHP MapScript with PHP's bundled regex " >&6; }
+          else
+            as_fn_error $? "
+!!! PHP uses its bundled regex library but regex/regex_extra.h (PHP <=5.2) or !!!
+!!! ext/ereg/regex/regex.h (PHP >=5.3) cannot be found.                                  !!!" "$LINENO" 5
+          fi
+	fi
 
   else
-    { { echo "$as_me:$LINENO: error: '$XSLT_DIR' not a valid installation path of xslt." >&5
-echo "$as_me: error: '$XSLT_DIR' not a valid installation path of xslt." >&2;}
-   { (exit 1); exit 1; }; }
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
   fi
-fi
 
-XSLT_ENABLED=$XSLT_ENABLED
 
-XSLT_INC=$XSLT_INC
+  PHP_MAPSCRIPT="php_mapscript"
+  PHP_VERSION_FLAG="-DPHP_VERSION_ID=$PHP_VERSION"
 
-XSLT_LIB=$XSLT_LIB
+  PHPCONFIG=$PHPCONFIG
 
+  PHP_REGEX_INC=$PHP_REGEX_INC
 
-ALL_ENABLED="$XSLT_ENABLED $ALL_ENABLED"
-ALL_INC="$XSLT_INC $ALL_INC"
-ALL_LIB="$XSLT_LIB $ALL_LIB"
+  PHP_REGEX_OBJ=$PHP_REGEX_OBJ
 
+  USE_PHP_REGEX=$USE_PHP_REGEX
 
 
-# Check whether --with-exslt or --without-exslt was given.
-if test "${with_exslt+set}" = set; then
-  withval="$with_exslt"
-  EXSLT_DIR=$withval
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result:         PHP/MapScript module configured." >&5
+$as_echo "        PHP/MapScript module configured." >&6; }
 else
-  EXSLT_DIR=''
-fi;
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result:         PHP/MapScript module not configured." >&5
+$as_echo "        PHP/MapScript module not configured." >&6; }
+fi
 
-echo "$as_me:$LINENO: checking if exslt is requested" >&5
-echo $ECHO_N "checking if exslt is requested... $ECHO_C" >&6
-EXSLT_LIB=''
+PHP_MAPSCRIPT=$PHP_MAPSCRIPT
 
-if test -z "$XMLMAPFILE_ENABLED" -a \( "$with_exslt" = "no" -o "$with_exslt" = ""  \); then
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
-else
 
-  if test "$EXSLT_DIR" = "yes" -o "$EXSLT_DIR" = ""; then
-     EXSLT_DIR="/usr"
-  fi
 
-  test -f $EXSLT_DIR/include/libexslt/exslt.h && EXSLT_INCDIR="$EXSLT_DIR/include"
-  test -f $EXSLT_DIR/lib/libexslt.so && EXSLT_LIBDIR="$EXSLT_DIR/lib"
-  test -f $EXSLT_DIR/lib64/libexslt.so && EXSLT_LIBDIR="$EXSLT_DIR/lib64"
+if test "x$LD_SHARED" = "x" ; then
 
-  if test -n "$EXSLT_LIBDIR" -a -n "$EXSLT_INCDIR" ; then
-                EXSLT_ENABLED="-DUSE_EXSLT"
-    EXSLT_INC="-I$EXSLT_INCDIR"
-    EXSLT_LIB="-L$EXSLT_LIBDIR -lexslt"
-    echo "$as_me:$LINENO: result: using exslt from $EXSLT_LIB ($EXSLT_ENABLED)" >&5
-echo "${ECHO_T}using exslt from $EXSLT_LIB ($EXSLT_ENABLED)" >&6
+	echo 'void f(){}' > conftest.c
+	if test -z "`${CC} -fPIC -c conftest.c 2>&1`"; then
+	  C_PIC=-fPIC
+	else
+	  C_PIC=
+	fi
+	rm -f conftest*
 
-  if test ""$EXSLT_DIR"" != "/usr/lib"; then
+	C_PIC=$C_PIC
 
-  if test -z ""$EXSLT_DIR"" || echo ""$EXSLT_DIR"" | grep '^/' >/dev/null ; then
-    ai_p=""$EXSLT_DIR""
+
+
+
+  echo 'void g(); int main(){ g(); return 0; }' > conftest1.c
+
+  echo '#include <stdio.h>' > conftest2.c
+  echo 'void g(); void g(){printf("");}' >> conftest2.c
+  ${CC} ${C_PIC} -c conftest2.c
+  SO_EXT="so"
+  SO_COMMAND_NAME="-soname"
+  export SO_EXT
+  export SO_COMMAND_NAME
+  LD_SHARED="/bin/true"
+  if test ! -z "`uname -a | grep IRIX`" ; then
+    IRIX_ALL=-all
   else
-    ai_p="`pwd`/"$EXSLT_DIR""
+    IRIX_ALL=
   fi
 
 
-  unique=`echo $ac_n "$ai_p$ac_c" | tr -c -d a-zA-Z0-9`
-  cmd="echo $ac_n \"\$LIBPATH$unique$ac_c\""
-  if test -n "$unique" && test "`eval $cmd`" = "" ; then
-    eval "LIBPATH$unique=set"
+# Check whether --with-ld-shared was given.
+if test "${with_ld_shared+set}" = set; then :
+  withval=$with_ld_shared;
+fi
 
-      EXTRA_LIBS="$EXTRA_LIBS -L$ai_p"
-        RPATHS="$RPATHS ${ld_runpath_switch}$ai_p"
 
+      if test "$with_ld_shared" != "" -a "$with_ld_shared" != "yes"; then
+    if test "$with_ld_shared" = "no" ; then
+      { $as_echo "$as_me:${as_lineno-$LINENO}: result: user disabled shared library support." >&5
+$as_echo "user disabled shared library support." >&6; }
+    else
+      { $as_echo "$as_me:${as_lineno-$LINENO}: result: using user supplied .so link command ... $with_ld_shared" >&5
+$as_echo "using user supplied .so link command ... $with_ld_shared" >&6; }
+    fi
+    LD_SHARED="$with_ld_shared"
+  fi
+
+    if test ! -z "`uname -a | grep CYGWIN`" \
+        -a "$LD_SHARED" = "/bin/true" ; then
+    if test -z "`gcc -shared conftest2.o -o libconftest.dll`" ; then
+      if test -z "`${CC} conftest1.c -L./ -lconftest -o conftest1 2>&1`"; then
+        LD_LIBRARY_PATH_OLD="$LD_LIBRARY_PATH"
+        if test -z "$LD_LIBRARY_PATH" ; then
+          LD_LIBRARY_PATH="`pwd`"
+        else
+          LD_LIBRARY_PATH="`pwd`:$LD_LIBRARY_PATH"
+        fi
+        export LD_LIBRARY_PATH
+        if test -z "`./conftest1 2>&1`" ; then
+          echo "checking for Cygwin gcc -shared ... yes"
+          LD_SHARED="c++ -shared"
+          SO_EXT="dll"
+        fi
+        LD_LIBRARY_PATH="$LD_LIBRARY_PATH_OLD"
+      fi
+    fi
   fi
 
+
+    if test ! -z "`uname | grep Darwin`" \
+          -a "$LD_SHARED" = "/bin/true" ; then
+    if test -z "`${CXX} -dynamiclib conftest2.o -o libconftest.so 2>&1`" ; then
+      ${CC} -c conftest1.c
+      if test -z "`${CXX} conftest1.o libconftest.so -o conftest1 2>&1`"; then
+        DYLD_LIBRARY_PATH_OLD="$DYLD_LIBRARY_PATH"
+        if test -z "$DYLD_LIBRARY_PATH" ; then
+          DYLD_LIBRARY_PATH="`pwd`"
+        else
+          DYLD_LIBRARY_PATH="`pwd`:$DYLD_LIBRARY_PATH"
+        fi
+        export DYLD_LIBRARY_PATH
+        if test -z "`./conftest1 2>&1`" ; then
+          echo "checking for ${CXX} -dynamiclib ... yes"
+          LD_SHARED="${CXX} -dynamiclib -single_module -flat_namespace -undefined suppress"
+	  SO_EXT=dylib
+          SO_COMMAND_NAME='-dylib_install_name'
+        fi
+        DYLD_LIBRARY_PATH="$DYLD_LIBRARY_PATH_OLD"
+      fi
+      rm -f conftest1.o
+    fi
   fi
 
+  if test "$LD_SHARED" = "/bin/true" \
+	-a -z "`${CXX} -shared $IRIX_ALL conftest2.o -o libconftest.so 2>&1|grep -v WARNING`" ; then
+    if test -z "`${CC} conftest1.c libconftest.so -o conftest1 2>&1`"; then
+      LD_LIBRARY_PATH_OLD="$LD_LIBRARY_PATH"
+      if test -z "$LD_LIBRARY_PATH" ; then
+        LD_LIBRARY_PATH="`pwd`"
+      else
+        LD_LIBRARY_PATH="`pwd`:$LD_LIBRARY_PATH"
+      fi
+      export LD_LIBRARY_PATH
+      if test -z "`./conftest1 2>&1`" ; then
+        echo "checking for ${CXX} -shared ... yes"
+        LD_SHARED="${CXX} -shared $IRIX_ALL"
+      else
+        echo "checking for ${CXX} -shared ... no(3)"
+      fi
+      LD_LIBRARY_PATH="$LD_LIBRARY_PATH_OLD"
+    else
+      echo "checking for ${CXX} -shared ... no(2)"
+    fi
   else
-    { { echo "$as_me:$LINENO: error: '$EXSLT_DIR' not a valid installation path of exslt." >&5
-echo "$as_me: error: '$EXSLT_DIR' not a valid installation path of exslt." >&2;}
-   { (exit 1); exit 1; }; }
+    if test "$LD_SHARED" = "/bin/true" ; then
+      echo "checking for ${CXX} -shared ... no(1)"
+    fi
   fi
-fi
 
-EXSLT_ENABLED=$EXSLT_ENABLED
+  if test "$LD_SHARED" = "/bin/true" \
+          -a -z "`ld -shared conftest2.o -o libconftest.so 2>&1`" ; then
+    if test -z "`${CC} conftest1.c libconftest.so -o conftest1 2>&1`"; then
+      LD_LIBRARY_PATH_OLD="$LD_LIBRARY_PATH"
+      if test -z "$LD_LIBRARY_PATH" ; then
+        LD_LIBRARY_PATH="`pwd`"
+      else
+        LD_LIBRARY_PATH="`pwd`:$LD_LIBRARY_PATH"
+      fi
+      export LD_LIBRARY_PATH
+      if test -z "`./conftest1 2>&1`" ; then
+        echo "checking for ld -shared ... yes"
+        LD_SHARED="ld -shared"
+      fi
+      LD_LIBRARY_PATH="$LD_LIBRARY_PATH_OLD"
+    fi
+  fi
+
+  if test "$LD_SHARED" = "/bin/true" ; then
+    echo "checking for ld -shared ... no"
+    if test ! -x /bin/true ; then
+      LD_SHARED=/usr/bin/true
+    fi
+  fi
+  if test "$LD_SHARED" = "no" ; then
+    if test -x /bin/true ; then
+      LD_SHARED=/bin/true
+    else
+      LD_SHARED=/usr/bin/true
+    fi
+  fi
+
+  rm -f conftest* libconftest*
+
+  LD_SHARED=$LD_SHARED
+
+  SO_EXT=$SO_EXT
 
-EXSLT_INC=$EXSLT_INC
+  SO_COMMAND_NAME=$SO_COMMAND_NAME
 
-EXSLT_LIB=$EXSLT_LIB
 
+fi
 
-ALL_ENABLED="$EXSLT_ENABLED $ALL_ENABLED"
-ALL_INC="$EXSLT_INC $ALL_INC"
-ALL_LIB="$EXSLT_LIB $ALL_LIB"
 
 
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if --with-java-include-os-name specified" >&5
+$as_echo_n "checking if --with-java-include-os-name specified... " >&6; }
 
-echo "$as_me:$LINENO: checking if FriBidi support requested" >&5
-echo $ECHO_N "checking if FriBidi support requested... $ECHO_C" >&6
+# Check whether --with-java-include-os-name was given.
+if test "${with_java_include_os_name+set}" = set; then :
+  withval=$with_java_include_os_name;
+fi
 
+if test -n "${with_java_include_os_name}" ; then
+OS_INCLUDE_DIR="${with_java_include_os_name}"
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes ($OS_INCLUDE_DIR)" >&5
+$as_echo "yes ($OS_INCLUDE_DIR)" >&6; }
+else
+OUR_OSNAME=`uname -s`
+case "${OUR_OSNAME}" in
+[Ll]inux) OS_INCLUDE_DIR="linux" ;;
+[sS]olaris*) OS_INCLUDE_DIR="solaris" ;;
+[sS]unOS*) OS_INCLUDE_DIR="solaris" ;;
+[Ww]in*) OS_INCLUDE_DIR="win32" ;;
+*) OS_INCLUDE_DIR="linux" ;;
+esac
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no, autodetected $OS_INCLUDE_DIR" >&5
+$as_echo "no, autodetected $OS_INCLUDE_DIR" >&6; }
+fi
 
-# Check whether --with-fribidi-config or --without-fribidi-config was given.
-if test "${with_fribidi_config+set}" = set; then
-  withval="$with_fribidi_config"
+if test -z $JAVAC; then
+   JAVAC="javac"
+fi
 
-fi;
 
-if test "$with_fribidi_config" = "no" -o "$with_fribidi_config" = "" ; then
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
-  FRIBIDI_CONFIG="no"
+JNI_INCLUDE_DIRS=""
 
-elif test "$with_fribidi_config" = "yes" ; then
-  echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6
-  # Extract the first word of "fribidi-config", so it can be a program name with args.
-set dummy fribidi-config; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
-if test "${ac_cv_path_FRIBIDI_CONFIG+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+test "x$JAVAC" = x && as_fn_error $? "'\$JAVAC' undefined" "$LINENO" 5
+# Extract the first word of "$JAVAC", so it can be a program name with args.
+set dummy $JAVAC; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_path__ACJNI_JAVAC+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
-  case $FRIBIDI_CONFIG in
+  case $_ACJNI_JAVAC in
   [\\/]* | ?:[\\/]*)
-  ac_cv_path_FRIBIDI_CONFIG="$FRIBIDI_CONFIG" # Let the user override the test with a path.
+  ac_cv_path__ACJNI_JAVAC="$_ACJNI_JAVAC" # Let the user override the test with a path.
   ;;
   *)
   as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
@@ -12965,2293 +21105,2677 @@ for as_dir in $PATH
 do
   IFS=$as_save_IFS
   test -z "$as_dir" && as_dir=.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_path_FRIBIDI_CONFIG="$as_dir/$ac_word$ac_exec_ext"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_path__ACJNI_JAVAC="$as_dir/$ac_word$ac_exec_ext"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
-done
+  done
+IFS=$as_save_IFS
 
-  test -z "$ac_cv_path_FRIBIDI_CONFIG" && ac_cv_path_FRIBIDI_CONFIG="no"
+  test -z "$ac_cv_path__ACJNI_JAVAC" && ac_cv_path__ACJNI_JAVAC="no"
   ;;
 esac
 fi
-FRIBIDI_CONFIG=$ac_cv_path_FRIBIDI_CONFIG
-
-if test -n "$FRIBIDI_CONFIG"; then
-  echo "$as_me:$LINENO: result: $FRIBIDI_CONFIG" >&5
-echo "${ECHO_T}$FRIBIDI_CONFIG" >&6
+_ACJNI_JAVAC=$ac_cv_path__ACJNI_JAVAC
+if test -n "$_ACJNI_JAVAC"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $_ACJNI_JAVAC" >&5
+$as_echo "$_ACJNI_JAVAC" >&6; }
 else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
 
-  FRIBIDI_PKG_CONFIG="no"
-  if test "$FRIBIDI_CONFIG" = "no" -a "$PKG_CONFIG" != "no" ; then
-     echo "$as_me:$LINENO: checking for fribidi pkg-config path" >&5
-echo $ECHO_N "checking for fribidi pkg-config path... $ECHO_C" >&6
-     `$PKG_CONFIG --silence-errors --libs fribidi >> /dev/null`
-     if test $? -eq 0 ; then
-        echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6
-        FRIBIDI_PKG_CONFIG="yes"
-        FRIBIDI_CONFIG="fribidi"
-     else
-       echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
-     fi
-  fi
-else
-  FRIBIDI_CONFIG=$with_fribidi_config
-fi
 
-if test "$FRIBIDI_CONFIG" = "no" ; then
-  FRIBIDI_ENABLED=
-  FRIBIDI_INC=
-  FRIBIDI_LIB=
+if test "x$_ACJNI_JAVAC" = xno; then
+   { $as_echo "$as_me:${as_lineno-$LINENO}: result: $JAVAC could not be found in path" >&5
+$as_echo "$JAVAC could not be found in path" >&6; }
 else
-  if test "$FRIBIDI_PKG_CONFIG" = "yes" -o ${FRIBIDI_CONFIG: -3} = ".pc" ; then
-     echo "$as_me:$LINENO: result: yes, user supplied path to fribidi.pc" >&5
-echo "${ECHO_T}yes, user supplied path to fribidi.pc" >&6
-     FRIBIDI_ENABLED="-DUSE_FRIBIDI -DUSE_FRIBIDI2"
-     FRIBIDI_LIB=`$PKG_CONFIG --libs $FRIBIDI_CONFIG`
-     FRIBIDI_INC=`$PKG_CONFIG --cflags $FRIBIDI_CONFIG`
-  else
-     if test -f "$FRIBIDI_CONFIG" -a -x "$FRIBIDI_CONFIG" ; then
-       echo "$as_me:$LINENO: result: yes, user supplied fribidi-config ($FRIBIDI_CONFIG)" >&5
-echo "${ECHO_T}yes, user supplied fribidi-config ($FRIBIDI_CONFIG)" >&6
-     else
-       { { echo "$as_me:$LINENO: error: '$FRIBIDI_CONFIG' is not an executable.  Make sure you use --with-fribidi-config=/path/to/fribidi-config or fribidi.pc" >&5
-echo "$as_me: error: '$FRIBIDI_CONFIG' is not an executable.  Make sure you use --with-fribidi-config=/path/to/fribidi-config or fribidi.pc" >&2;}
-   { (exit 1); exit 1; }; }
-     fi
-     FRIBIDI_ENABLED=-DUSE_FRIBIDI
-     FRIBIDI_LIB=`$FRIBIDI_CONFIG --libs`
-     FRIBIDI_INC=`$FRIBIDI_CONFIG --cflags`
-  fi
-fi
-
-FRIBIDI_ENABLED=$FRIBIDI_ENABLED
-
-FRIBIDI_INC=$FRIBIDI_INC
-
-FRIBIDI_LIB=$FRIBIDI_LIB
-
 
-ALL_ENABLED="$FRIBIDI_ENABLED $ALL_ENABLED"
-ALL_INC="$FRIBIDI_INC $ALL_INC"
-ALL_LIB="$FRIBIDI_LIB $ALL_LIB"
+# find the include directory relative to the javac executable
+_cur=""$_ACJNI_JAVAC""
+while ls -ld "$_cur" 2>/dev/null | grep " -> " >/dev/null; do
+        { $as_echo "$as_me:${as_lineno-$LINENO}: checking symlink for $_cur" >&5
+$as_echo_n "checking symlink for $_cur... " >&6; }
+        _slink=`ls -ld "$_cur" | sed 's/.* -> //'`
+        case "$_slink" in
+        /*) _cur="$_slink";;
+        # 'X' avoids triggering unwanted echo options.
+        *) _cur=`echo "X$_cur" | sed -e 's/^X//' -e 's:[^/]*$::'`"$_slink";;
+        esac
+        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $_cur" >&5
+$as_echo "$_cur" >&6; }
+done
+_ACJNI_FOLLOWED="$_cur"
+
+   _JTOPDIR=`echo "$_ACJNI_FOLLOWED" | sed -e 's://*:/:g' -e 's:/[^/]*$::'`
+   case "$host_os" in
+           darwin*)        _JTOPDIR=`echo "$_JTOPDIR" | sed -e 's:/[^/]*$::'`
+                           _JINC="$_JTOPDIR/Headers";;
+           *)              _JINC="$_JTOPDIR/include";;
+   esac
+   $as_echo "$as_me:${as_lineno-$LINENO}: _JTOPDIR=$_JTOPDIR" >&5
+   $as_echo "$as_me:${as_lineno-$LINENO}: _JINC=$_JINC" >&5
+
+   # On Mac OS X 10.6.4, jni.h is a symlink:
+   # /System/Library/Frameworks/JavaVM.framework/Versions/Current/Headers/jni.h
+   # -> ../../CurrentJDK/Headers/jni.h.
+   if test -f "$_JINC/jni.h" || test -L "$_JINC/jni.h"; then
+           JNI_INCLUDE_DIRS="$JNI_INCLUDE_DIRS $_JINC"
+   else
+           _JTOPDIR=`echo "$_JTOPDIR" | sed -e 's:/[^/]*$::'`
+           if test -f "$_JTOPDIR/include/jni.h"; then
+                   JNI_INCLUDE_DIRS="$JNI_INCLUDE_DIRS $_JTOPDIR/include"
+           else
+                   as_fn_error $? "cannot find java include files" "$LINENO" 5
+           fi
+   fi
 
+   # get the likely subdirectories for system specific java includes
+   case "$host_os" in
+   bsdi*)          _JNI_INC_SUBDIRS="bsdos";;
+   linux*)         _JNI_INC_SUBDIRS="linux genunix";;
+   osf*)           _JNI_INC_SUBDIRS="alpha";;
+   solaris*)       _JNI_INC_SUBDIRS="solaris";;
+   mingw*)		_JNI_INC_SUBDIRS="win32";;
+   cygwin*)	_JNI_INC_SUBDIRS="win32";;
+   *)              _JNI_INC_SUBDIRS="genunix";;
+   esac
+
+   # add any subdirectories that are present
+   for JINCSUBDIR in $_JNI_INC_SUBDIRS
+   do
+       if test -d "$_JTOPDIR/include/$JINCSUBDIR"; then
+            JNI_INCLUDE_DIRS="$JNI_INCLUDE_DIRS $_JTOPDIR/include/$JINCSUBDIR"
+       fi
+   done
+fi
+
+for JNI_INCLUDE_DIR in $JNI_INCLUDE_DIRS
+do
+   JAVA_INCLUDE="$JAVA_INCLUDE -I$JNI_INCLUDE_DIR"
+done
+JAVA_INCLUDE=$JAVA_INCLUDE
 
 
-echo "$as_me:$LINENO: checking if Cairo support requested" >&5
-echo $ECHO_N "checking if Cairo support requested... $ECHO_C" >&6
 
 
-# Check whether --with-cairo or --without-cairo was given.
-if test "${with_cairo+set}" = set; then
-  withval="$with_cairo"
 
-fi;
+# Check whether --enable-python-mapscript was given.
+if test "${enable_python_mapscript+set}" = set; then :
+  enableval=$enable_python_mapscript;
+else
+  enable_python_mapscript=no
+fi
 
-if test "$with_cairo" = "no" -o "$with_cairo" = "" ; then
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
-  CAIRO_CONFIG="no"
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if we should build python mapscript" >&5
+$as_echo_n "checking if we should build python mapscript... " >&6; }
+if test "$enable_python_mapscript" = "yes" ; then
 
-elif test "$with_cairo" = "yes" ; then
-  echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6
-  if test "$PKG_CONFIG" != "no" ; then
-     echo "$as_me:$LINENO: checking for cairo pkg-config path" >&5
-echo $ECHO_N "checking for cairo pkg-config path... $ECHO_C" >&6
-     `$PKG_CONFIG --silence-errors -- cairo cairo-ft cairo-svg cairo-pdf cairo-png >> /dev/null`
-     if test $? -eq 0 ; then
-        echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6
-        CAIRO_CONFIG="cairo cairo-ft cairo-svg cairo-pdf cairo-png"
-     else
-       { { echo "$as_me:$LINENO: error: cairo support requested, but not found.Try installing the cairo development headers" >&5
-echo "$as_me: error: cairo support requested, but not found.Try installing the cairo development headers" >&2;}
-   { (exit 1); exit 1; }; }
-     fi
-  else
-    { { echo "$as_me:$LINENO: error: pkg-config required for cairo support, try using --with-pkg-config=PATH" >&5
-echo "$as_me: error: pkg-config required for cairo support, try using --with-pkg-config=PATH" >&2;}
-   { (exit 1); exit 1; }; }
-  fi
+        # Ubuntu has swig 2.0 as /usr/bin/swig2.0
+        for ac_prog in swig swig2.0
+do
+  # Extract the first word of "$ac_prog", so it can be a program name with args.
+set dummy $ac_prog; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_path_SWIG+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
-  CAIRO_CONFIG=$with_cairo_config
-fi
+  case $SWIG in
+  [\\/]* | ?:[\\/]*)
+  ac_cv_path_SWIG="$SWIG" # Let the user override the test with a path.
+  ;;
+  *)
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_path_SWIG="$as_dir/$ac_word$ac_exec_ext"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
 
-if test "$CAIRO_CONFIG" = "no" ; then
-  CAIRO_ENABLED=
-  CAIRO_INC=
-  CAIRO_LIB=
+  ;;
+esac
+fi
+SWIG=$ac_cv_path_SWIG
+if test -n "$SWIG"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $SWIG" >&5
+$as_echo "$SWIG" >&6; }
 else
-  echo "$as_me:$LINENO: result: yes, pkg-config defaults, or user supplied path to cairo.pc" >&5
-echo "${ECHO_T}yes, pkg-config defaults, or user supplied path to cairo.pc" >&6
-  CAIRO_ENABLED="-DUSE_CAIRO"
-  CAIRO_LIB=`$PKG_CONFIG --libs $CAIRO_CONFIG`
-  CAIRO_INC=`$PKG_CONFIG --cflags $CAIRO_CONFIG`
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
 
-CAIRO_ENABLED=$CAIRO_ENABLED
-
-CAIRO_INC=$CAIRO_INC
-
-CAIRO_LIB=$CAIRO_LIB
-
-
-ALL_ENABLED="$CAIRO_ENABLED $ALL_ENABLED"
-ALL_INC="$CAIRO_INC $ALL_INC"
-ALL_LIB="$CAIRO_LIB $ALL_LIB"
 
+  test -n "$SWIG" && break
+done
 
-echo "$as_me:$LINENO: checking FastCGI support" >&5
-echo $ECHO_N "checking FastCGI support... $ECHO_C" >&6
+        if test -z "$SWIG" ; then
+                :
+        elif test -n "2.0.0" ; then
+                { $as_echo "$as_me:${as_lineno-$LINENO}: checking SWIG version" >&5
+$as_echo_n "checking SWIG version... " >&6; }
+                swig_version=`$SWIG -version 2>&1 | grep 'SWIG Version' | sed 's/.*\([0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\).*/\1/g'`
+                { $as_echo "$as_me:${as_lineno-$LINENO}: result: $swig_version" >&5
+$as_echo "$swig_version" >&6; }
+                if test -n "$swig_version" ; then
+                        # Calculate the required version number components
+                        required=2.0.0
+                        required_major=`echo $required | sed 's/[^0-9].*//'`
+                        if test -z "$required_major" ; then
+                                required_major=0
+                        fi
+                        required=`echo $required | sed 's/[0-9]*[^0-9]//'`
+                        required_minor=`echo $required | sed 's/[^0-9].*//'`
+                        if test -z "$required_minor" ; then
+                                required_minor=0
+                        fi
+                        required=`echo $required | sed 's/[0-9]*[^0-9]//'`
+                        required_patch=`echo $required | sed 's/[^0-9].*//'`
+                        if test -z "$required_patch" ; then
+                                required_patch=0
+                        fi
+                        # Calculate the available version number components
+                        available=$swig_version
+                        available_major=`echo $available | sed 's/[^0-9].*//'`
+                        if test -z "$available_major" ; then
+                                available_major=0
+                        fi
+                        available=`echo $available | sed 's/[0-9]*[^0-9]//'`
+                        available_minor=`echo $available | sed 's/[^0-9].*//'`
+                        if test -z "$available_minor" ; then
+                                available_minor=0
+                        fi
+                        available=`echo $available | sed 's/[0-9]*[^0-9]//'`
+                        available_patch=`echo $available | sed 's/[^0-9].*//'`
+                        if test -z "$available_patch" ; then
+                                available_patch=0
+                        fi
+                        # Convert the version tuple into a single number for easier comparison.
+                        # Using base 100 should be safe since SWIG internally uses BCD values
+                        # to encode its version number.
+                        required_swig_vernum=`expr $required_major \* 10000 \
+                            \+ $required_minor \* 100 \+ $required_patch`
+                        available_swig_vernum=`expr $available_major \* 10000 \
+                            \+ $available_minor \* 100 \+ $available_patch`
+
+                        if test $available_swig_vernum -lt $required_swig_vernum; then
+                                { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: SWIG version >= 2.0.0 is required.  You have $swig_version." >&5
+$as_echo "$as_me: WARNING: SWIG version >= 2.0.0 is required.  You have $swig_version." >&2;}
+                                SWIG=''
+
+                        else
+                                { $as_echo "$as_me:${as_lineno-$LINENO}: checking for SWIG library" >&5
+$as_echo_n "checking for SWIG library... " >&6; }
+                                SWIG_LIB=`$SWIG -swiglib`
+                                { $as_echo "$as_me:${as_lineno-$LINENO}: result: $SWIG_LIB" >&5
+$as_echo "$SWIG_LIB" >&6; }
+
+                        fi
+                else
+                        { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cannot determine SWIG version" >&5
+$as_echo "$as_me: WARNING: cannot determine SWIG version" >&2;}
+                        SWIG=''
+
+                fi
+        fi
 
-# Check whether --with-fastcgi or --without-fastcgi was given.
-if test "${with_fastcgi+set}" = set; then
-  withval="$with_fastcgi"
 
-fi;
+  if test -z $SWIG; then
+      { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: swig not found, you will not be able to build/update wrappers" >&5
+$as_echo "$as_me: WARNING: swig not found, you will not be able to build/update wrappers" >&2;}
+  fi
 
-if test "$with_fastcgi" = "no" -o "$with_fastcgi" = "" ; then
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if python path is provided" >&5
+$as_echo_n "checking if python path is provided... " >&6; }
 
-  echo "$as_me:$LINENO: result: not requested." >&5
-echo "${ECHO_T}not requested." >&6
 
+# Check whether --with-python was given.
+if test "${with_python+set}" = set; then :
+  withval=$with_python;
 else
+  with_python=yes
+fi
 
-  echo "$as_me:$LINENO: result: requested." >&5
-echo "${ECHO_T}requested." >&6
-
-  if test "$with_fastcgi" = "yes" ; then
-    FASTCGI_INC=""
-    FASTCGI_LIB="-lfcgi"
-  else
-    FASTCGI_INC="-I$with_fastcgi/include -I$with_fastcgi/include/fastcgi"
-    FASTCGI_LIB="-L$with_fastcgi/lib -lfcgi"
-  fi
 
-  echo "$as_me:$LINENO: checking for FCGI_Accept in -lfcgi" >&5
-echo $ECHO_N "checking for FCGI_Accept in -lfcgi... $ECHO_C" >&6
-if test "${ac_cv_lib_fcgi_FCGI_Accept+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+if test -n "$with_python" -a "$with_python" != "yes" ; then
+   { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+   if test -x "$with_python"; then
+      PYTHON=$with_python
+   else
+      as_fn_error $? "$with_python does not seem to be an executable" "$LINENO" 5
+   fi
 else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-lfcgi $FASTCGI_LIB $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
-/* Override any gcc2 internal prototype to avoid an error.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char FCGI_Accept ();
-int
-main ()
-{
-FCGI_Accept ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_fcgi_FCGI_Accept=yes
+   { $as_echo "$as_me:${as_lineno-$LINENO}: result: using system default" >&5
+$as_echo "using system default" >&6; }
+   # Extract the first word of "python", so it can be a program name with args.
+set dummy python; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_path_PYTHON+:} false; then :
+  $as_echo_n "(cached) " >&6
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
+  case $PYTHON in
+  [\\/]* | ?:[\\/]*)
+  ac_cv_path_PYTHON="$PYTHON" # Let the user override the test with a path.
+  ;;
+  *)
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_path_PYTHON="$as_dir/$ac_word$ac_exec_ext"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
 
-ac_cv_lib_fcgi_FCGI_Accept=no
+  ;;
+esac
 fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
+PYTHON=$ac_cv_path_PYTHON
+if test -n "$PYTHON"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $PYTHON" >&5
+$as_echo "$PYTHON" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_fcgi_FCGI_Accept" >&5
-echo "${ECHO_T}$ac_cv_lib_fcgi_FCGI_Accept" >&6
-if test $ac_cv_lib_fcgi_FCGI_Accept = yes; then
-  FASTCGI_ENABLED=-DUSE_FASTCGI
+
+
+   if test -z "$PYTHON"; then
+      as_fn_error $? "no python found on path" "$LINENO" 5
+   fi
 fi
+PYTHON=$PYTHON
 
 
-  if test "x$FASTCGI_ENABLED" = "x" ; then
-    { { echo "$as_me:$LINENO: error: Unable to link against $FASTCGI_LIB" >&5
-echo "$as_me: error: Unable to link against $FASTCGI_LIB" >&2;}
-   { (exit 1); exit 1; }; }
-  fi
+  PYTHON_MAPSCRIPT="python_mapscript"
 
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result:         Python/MapScript module configured." >&5
+$as_echo "        Python/MapScript module configured." >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result:         Python/MapScript module not configured." >&5
+$as_echo "        Python/MapScript module not configured." >&6; }
 fi
 
-FASTCGI_ENABLED=$FASTCGI_ENABLED
+PYTHON_MAPSCRIPT=$PYTHON_MAPSCRIPT
 
-FASTCGI_INC=$FASTCGI_INC
 
-FASTCGI_LIB=$FASTCGI_LIB
+OS_INCLUDE_DIR=$OS_INCLUDE_DIR
 
 
-ALL_ENABLED="$FASTCGI_ENABLED $ALL_ENABLED"
-ALL_INC="$FASTCGI_INC $ALL_INC"
-ALL_LIB="$FASTCGI_LIB $ALL_LIB"
 
+ALL_ENABLED="$ALL_ENABLED -DDISABLE_CVSID"
 
-{ echo "$as_me:$LINENO: checking HTTPD server (Apache) version..." >&5
-echo "$as_me: checking HTTPD server (Apache) version..." >&6;}
+ALL_INC=$ALL_INC
 
-# Check whether --with-httpd or --without-httpd was given.
-if test "${with_httpd+set}" = set; then
-  withval="$with_httpd"
+ALL_LIB=$ALL_LIB
 
-fi;
+ALL_STATIC_LIB=$ALL_STATIC_LIB
 
+RPATHS=$RPATHS
 
-if test "$with_httpd" = "no" ; then
 
-  echo "$as_me:$LINENO: result:         HTTPD server (Apache) version detection disabled by --without-httpd." >&5
-echo "${ECHO_T}        HTTPD server (Apache) version detection disabled by --without-httpd." >&6
+ac_config_files="$ac_config_files Makefile mapscript/php/Makefile mapscript/python/Makefile mapscript/java/Makefile mapscript/csharp/Makefile mapscript/perl/Makefile.PL"
 
-elif test "$with_httpd" = "yes" ; then
-  { { echo "$as_me:$LINENO: error: full path to httpd executable is required as argument when using --with-httpd" >&5
-echo "$as_me: error: full path to httpd executable is required as argument when using --with-httpd" >&2;}
-   { (exit 1); exit 1; }; }
+cat >confcache <<\_ACEOF
+# This file is a shell script that caches the results of configure
+# tests run on this system so they can be shared between configure
+# scripts and configure runs, see configure's option --config-cache.
+# It is not useful on other systems.  If it contains results you don't
+# want to keep, you may remove or edit it.
+#
+# config.status only pays attention to the cache file if you give it
+# the --recheck option to rerun configure.
+#
+# `ac_cv_env_foo' variables (set or unset) will be overridden when
+# loading this file, other *unset* `ac_cv_foo' will be assigned the
+# following values.
 
-else
+_ACEOF
 
-  if test -n "$with_httpd" ; then
-                HTTPD="$with_httpd"
+# The following way of writing the cache mishandles newlines in values,
+# but we know of no workaround that is simple, portable, and efficient.
+# So, we kill variables containing newlines.
+# Ultrix sh set writes to stderr and can't be redirected directly,
+# and sets the high bit in the cache file unless we assign to the vars.
+(
+  for ac_var in `(set) 2>&1 | sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'`; do
+    eval ac_val=\$$ac_var
+    case $ac_val in #(
+    *${as_nl}*)
+      case $ac_var in #(
+      *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5
+$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;;
+      esac
+      case $ac_var in #(
+      _ | IFS | as_nl) ;; #(
+      BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #(
+      *) { eval $ac_var=; unset $ac_var;} ;;
+      esac ;;
+    esac
+  done
 
-    if test -f "$HTTPD" -a -x "$HTTPD" ; then
-      echo "$as_me:$LINENO: result:         using user-supplied httpd ($HTTPD)" >&5
-echo "${ECHO_T}        using user-supplied httpd ($HTTPD)" >&6
-    else
-      { { echo "$as_me:$LINENO: error: $HTTPD is not an executable.  Make sure you use --with-httpd=/path/to/httpd" >&5
-echo "$as_me: error: $HTTPD is not an executable.  Make sure you use --with-httpd=/path/to/httpd" >&2;}
-   { (exit 1); exit 1; }; }
+  (set) 2>&1 |
+    case $as_nl`(ac_space=' '; set) 2>&1` in #(
+    *${as_nl}ac_space=\ *)
+      # `set' does not quote correctly, so add quotes: double-quote
+      # substitution turns \\\\ into \\, and sed turns \\ into \.
+      sed -n \
+	"s/'/'\\\\''/g;
+	  s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p"
+      ;; #(
+    *)
+      # `set' quotes correctly as required by POSIX, so do not add quotes.
+      sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p"
+      ;;
+    esac |
+    sort
+) |
+  sed '
+     /^ac_cv_env_/b end
+     t clear
+     :clear
+     s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/
+     t end
+     s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/
+     :end' >>confcache
+if diff "$cache_file" confcache >/dev/null 2>&1; then :; else
+  if test -w "$cache_file"; then
+    if test "x$cache_file" != "x/dev/null"; then
+      { $as_echo "$as_me:${as_lineno-$LINENO}: updating cache $cache_file" >&5
+$as_echo "$as_me: updating cache $cache_file" >&6;}
+      if test ! -f "$cache_file" || test -h "$cache_file"; then
+	cat confcache >"$cache_file"
+      else
+        case $cache_file in #(
+        */* | ?:*)
+	  mv -f confcache "$cache_file"$$ &&
+	  mv -f "$cache_file"$$ "$cache_file" ;; #(
+        *)
+	  mv -f confcache "$cache_file" ;;
+	esac
+      fi
     fi
   else
-                # Extract the first word of "httpd", so it can be a program name with args.
-set dummy httpd; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
-if test "${ac_cv_path_HTTPD+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  case $HTTPD in
-  [\\/]* | ?:[\\/]*)
-  ac_cv_path_HTTPD="$HTTPD" # Let the user override the test with a path.
-  ;;
-  *)
-  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-as_dummy=""$PATH:/usr/sbin:/usr/bin:/usr/local/bin:/usr/local/apache/bin""
-for as_dir in $as_dummy
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_path_HTTPD="$as_dir/$ac_word$ac_exec_ext"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
+    { $as_echo "$as_me:${as_lineno-$LINENO}: not updating unwritable cache $cache_file" >&5
+$as_echo "$as_me: not updating unwritable cache $cache_file" >&6;}
   fi
-done
-done
-
-  test -z "$ac_cv_path_HTTPD" && ac_cv_path_HTTPD=""""
-  ;;
-esac
-fi
-HTTPD=$ac_cv_path_HTTPD
-
-if test -n "$HTTPD"; then
-  echo "$as_me:$LINENO: result: $HTTPD" >&5
-echo "${ECHO_T}$HTTPD" >&6
-else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
 fi
+rm -f confcache
 
-  fi
+test "x$prefix" = xNONE && prefix=$ac_default_prefix
+# Let make expand exec_prefix.
+test "x$exec_prefix" = xNONE && exec_prefix='${prefix}'
 
-  if test -z "$HTTPD" ; then
-    echo "$as_me:$LINENO: result:         'httpd' not found, skipping Apache version detection. You may want to use --with-httpd=/path/to/httpd" >&5
-echo "${ECHO_T}        'httpd' not found, skipping Apache version detection. You may want to use --with-httpd=/path/to/httpd" >&6
-  else
-    HTTPD_VERSION_STRING=`$HTTPD -v | grep "Server version" | awk '{print $3}'`
-        APACHE_VERSION=`echo "$HTTPD_VERSION_STRING" | grep Apache | awk -F / '{print $2}' | awk -F . '{print $1*1000000 + $2*1000 + $3}'`
+# Transform confdefs.h into DEFS.
+# Protect against shell expansion while executing Makefile rules.
+# Protect against Makefile macro expansion.
+#
+# If the first sed substitution is executed (which looks for macros that
+# take arguments), then branch to the quote section.  Otherwise,
+# look for a macro that doesn't take arguments.
+ac_script='
+:mline
+/\\$/{
+ N
+ s,\\\n,,
+ b mline
+}
+t clear
+:clear
+s/^[	 ]*#[	 ]*define[	 ][	 ]*\([^	 (][^	 (]*([^)]*)\)[	 ]*\(.*\)/-D\1=\2/g
+t quote
+s/^[	 ]*#[	 ]*define[	 ][	 ]*\([^	 ][^	 ]*\)[	 ]*\(.*\)/-D\1=\2/g
+t quote
+b any
+:quote
+s/[	 `~#$^&*(){}\\|;'\''"<>?]/\\&/g
+s/\[/\\&/g
+s/\]/\\&/g
+s/\$/$$/g
+H
+:any
+${
+	g
+	s/^\n//
+	s/\n/ /g
+	p
+}
+'
+DEFS=`sed -n "$ac_script" confdefs.h`
 
-    echo "$as_me:$LINENO: result:         $HTTPD version is $HTTPD_VERSION_STRING ($APACHE_VERSION)." >&5
-echo "${ECHO_T}        $HTTPD version is $HTTPD_VERSION_STRING ($APACHE_VERSION)." >&6
 
+ac_libobjs=
+ac_ltlibobjs=
+U=
+for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue
+  # 1. Remove the extension, and $U if already installed.
+  ac_script='s/\$U\././;s/\.o$//;s/\.obj$//'
+  ac_i=`$as_echo "$ac_i" | sed "$ac_script"`
+  # 2. Prepend LIBOBJDIR.  When used with automake>=1.10 LIBOBJDIR
+  #    will be set to the directory where LIBOBJS objects are built.
+  as_fn_append ac_libobjs " \${LIBOBJDIR}$ac_i\$U.$ac_objext"
+  as_fn_append ac_ltlibobjs " \${LIBOBJDIR}$ac_i"'$U.lo'
+done
+LIBOBJS=$ac_libobjs
 
-        if test -n "$APACHE_VERSION" -a `expr "$APACHE_VERSION" \>= "2000000"` = 1 -a `expr "$APACHE_VERSION" \< "2000049"` = 1 ; then
-      echo "$as_me:$LINENO: result:         Your system is apparently running $HTTPD_VERSION_STRING.  Setting stderr to non-blocking for msDebug() due to Apache 2.0.0-2.0.48 bug (see MapServer bug 458 or Apache bug 22030)." >&5
-echo "${ECHO_T}        Your system is apparently running $HTTPD_VERSION_STRING.  Setting stderr to non-blocking for msDebug() due to Apache 2.0.0-2.0.48 bug (see MapServer bug 458 or Apache bug 22030)." >&6
-      DEBUG_FLAGS="${DEBUG_FLAGS} -DNEED_NONBLOCKING_STDERR"
-    fi
+LTLIBOBJS=$ac_ltlibobjs
 
-  fi
 
-fi
 
+: "${CONFIG_STATUS=./config.status}"
+ac_write_fail=0
+ac_clean_files_save=$ac_clean_files
+ac_clean_files="$ac_clean_files $CONFIG_STATUS"
+{ $as_echo "$as_me:${as_lineno-$LINENO}: creating $CONFIG_STATUS" >&5
+$as_echo "$as_me: creating $CONFIG_STATUS" >&6;}
+as_write_fail=0
+cat >$CONFIG_STATUS <<_ASEOF || as_write_fail=1
+#! $SHELL
+# Generated by $as_me.
+# Run this file to recreate the current configuration.
+# Compiler output produced by configure, useful for debugging
+# configure, is in config.log if it exists.
 
+debug=false
+ac_cs_recheck=false
+ac_cs_silent=false
 
-MS_DIR="`pwd`"
-MS_INC="-I$MS_DIR"
-MS_LIB="-L$MS_DIR -lmapserver"
+SHELL=\${CONFIG_SHELL-$SHELL}
+export SHELL
+_ASEOF
+cat >>$CONFIG_STATUS <<\_ASEOF || as_write_fail=1
+## -------------------- ##
+## M4sh Initialization. ##
+## -------------------- ##
+
+# Be more Bourne compatible
+DUALCASE=1; export DUALCASE # for MKS sh
+if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then :
+  emulate sh
+  NULLCMD=:
+  # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which
+  # is contrary to our usage.  Disable this feature.
+  alias -g '${1+"$@"}'='"$@"'
+  setopt NO_GLOB_SUBST
+else
+  case `(set -o) 2>/dev/null` in #(
+  *posix*) :
+    set -o posix ;; #(
+  *) :
+     ;;
+esac
+fi
 
-  if test ""$MS_DIR"" != "/usr/lib"; then
 
-  if test -z ""$MS_DIR"" || echo ""$MS_DIR"" | grep '^/' >/dev/null ; then
-    ai_p=""$MS_DIR""
+as_nl='
+'
+export as_nl
+# Printing a long string crashes Solaris 7 /usr/bin/printf.
+as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
+as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo
+as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo
+# Prefer a ksh shell builtin over an external printf program on Solaris,
+# but without wasting forks for bash or zsh.
+if test -z "$BASH_VERSION$ZSH_VERSION" \
+    && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then
+  as_echo='print -r --'
+  as_echo_n='print -rn --'
+elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then
+  as_echo='printf %s\n'
+  as_echo_n='printf %s'
+else
+  if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then
+    as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"'
+    as_echo_n='/usr/ucb/echo -n'
   else
-    ai_p="`pwd`/"$MS_DIR""
+    as_echo_body='eval expr "X$1" : "X\\(.*\\)"'
+    as_echo_n_body='eval
+      arg=$1;
+      case $arg in #(
+      *"$as_nl"*)
+	expr "X$arg" : "X\\(.*\\)$as_nl";
+	arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;;
+      esac;
+      expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl"
+    '
+    export as_echo_n_body
+    as_echo_n='sh -c $as_echo_n_body as_echo'
   fi
+  export as_echo_body
+  as_echo='sh -c $as_echo_body as_echo'
+fi
 
+# The user is always right.
+if test "${PATH_SEPARATOR+set}" != set; then
+  PATH_SEPARATOR=:
+  (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && {
+    (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 ||
+      PATH_SEPARATOR=';'
+  }
+fi
 
-  unique=`echo $ac_n "$ai_p$ac_c" | tr -c -d a-zA-Z0-9`
-  cmd="echo $ac_n \"\$LIBPATH$unique$ac_c\""
-  if test -n "$unique" && test "`eval $cmd`" = "" ; then
-    eval "LIBPATH$unique=set"
 
-      EXTRA_LIBS="$EXTRA_LIBS -L$ai_p"
-        RPATHS="$RPATHS ${ld_runpath_switch}$ai_p"
+# IFS
+# We need space, tab and new line, in precisely that order.  Quoting is
+# there to prevent editors from complaining about space-tab.
+# (If _AS_PATH_WALK were called with IFS unset, it would disable word
+# splitting by setting IFS to empty value.)
+IFS=" ""	$as_nl"
+
+# Find who we are.  Look in the path if we contain no directory separator.
+as_myself=
+case $0 in #((
+  *[\\/]* ) as_myself=$0 ;;
+  *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
+  done
+IFS=$as_save_IFS
 
-  fi
+     ;;
+esac
+# We did not find ourselves, most probably we were run as `sh COMMAND'
+# in which case we are not to be found in the path.
+if test "x$as_myself" = x; then
+  as_myself=$0
+fi
+if test ! -f "$as_myself"; then
+  $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2
+  exit 1
+fi
+
+# Unset variables that we do not need and which cause bugs (e.g. in
+# pre-3.0 UWIN ksh).  But do not cause bugs in bash 2.01; the "|| exit 1"
+# suppresses any "Segmentation fault" message there.  '((' could
+# trigger a bug in pdksh 5.2.14.
+for as_var in BASH_ENV ENV MAIL MAILPATH
+do eval test x\${$as_var+set} = xset \
+  && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || :
+done
+PS1='$ '
+PS2='> '
+PS4='+ '
 
-  fi
+# NLS nuisances.
+LC_ALL=C
+export LC_ALL
+LANGUAGE=C
+export LANGUAGE
 
-MS_INC=$MS_INC
+# CDPATH.
+(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
 
-MS_LIB=$MS_LIB
 
+# as_fn_error STATUS ERROR [LINENO LOG_FD]
+# ----------------------------------------
+# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are
+# provided, also output the error to LOG_FD, referencing LINENO. Then exit the
+# script with STATUS, using 1 if that was 0.
+as_fn_error ()
+{
+  as_status=$1; test $as_status -eq 0 && as_status=1
+  if test "$4"; then
+    as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+    $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4
+  fi
+  $as_echo "$as_me: error: $2" >&2
+  as_fn_exit $as_status
+} # as_fn_error
 
 
-# Check whether --enable-ignore-missing-data or --disable-ignore-missing-data was given.
-if test "${enable_ignore_missing_data+set}" = set; then
-  enableval="$enable_ignore_missing_data"
+# as_fn_set_status STATUS
+# -----------------------
+# Set $? to STATUS, without forking.
+as_fn_set_status ()
+{
+  return $1
+} # as_fn_set_status
 
-fi;
-if test "$enable_ignore_missing_data" = "yes" ; then
+# as_fn_exit STATUS
+# -----------------
+# Exit the shell with STATUS, even in a "trap 0" or "set -e" context.
+as_fn_exit ()
+{
+  set +e
+  as_fn_set_status $1
+  exit $1
+} # as_fn_exit
+
+# as_fn_unset VAR
+# ---------------
+# Portably unset VAR.
+as_fn_unset ()
+{
+  { eval $1=; unset $1;}
+}
+as_unset=as_fn_unset
+# as_fn_append VAR VALUE
+# ----------------------
+# Append the text in VALUE to the end of the definition contained in VAR. Take
+# advantage of any shell optimizations that allow amortized linear growth over
+# repeated appends, instead of the typical quadratic growth present in naive
+# implementations.
+if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then :
+  eval 'as_fn_append ()
+  {
+    eval $1+=\$2
+  }'
+else
+  as_fn_append ()
+  {
+    eval $1=\$$1\$2
+  }
+fi # as_fn_append
+
+# as_fn_arith ARG...
+# ------------------
+# Perform arithmetic evaluation on the ARGs, and store the result in the
+# global $as_val. Take advantage of shells that can avoid forks. The arguments
+# must be portable across $(()) and expr.
+if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then :
+  eval 'as_fn_arith ()
+  {
+    as_val=$(( $* ))
+  }'
+else
+  as_fn_arith ()
+  {
+    as_val=`expr "$@" || test $? -eq 1`
+  }
+fi # as_fn_arith
 
-  IGNORE_MISSING_DATA="-DIGNORE_MISSING_DATA"
 
-  echo "$as_me:$LINENO: result: Compiling with -DIGNORE_MISSING_DATA." >&5
-echo "${ECHO_T}Compiling with -DIGNORE_MISSING_DATA." >&6
+if expr a : '\(a\)' >/dev/null 2>&1 &&
+   test "X`expr 00001 : '.*\(...\)'`" = X001; then
+  as_expr=expr
+else
+  as_expr=false
 fi
-IGNORE_MISSING_DATA=$IGNORE_MISSING_DATA
 
+if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then
+  as_basename=basename
+else
+  as_basename=false
+fi
 
+if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then
+  as_dirname=dirname
+else
+  as_dirname=false
+fi
 
-# Check whether --enable-point-z-m or --disable-point-z-m was given.
-if test "${enable_point_z_m+set}" = set; then
-  enableval="$enable_point_z_m"
+as_me=`$as_basename -- "$0" ||
+$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
+	 X"$0" : 'X\(//\)$' \| \
+	 X"$0" : 'X\(/\)' \| . 2>/dev/null ||
+$as_echo X/"$0" |
+    sed '/^.*\/\([^/][^/]*\)\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\/\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\/\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
 
-fi;
-if test "$enable_point_z_m" = "yes" ; then
+# Avoid depending upon Character Ranges.
+as_cr_letters='abcdefghijklmnopqrstuvwxyz'
+as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
+as_cr_Letters=$as_cr_letters$as_cr_LETTERS
+as_cr_digits='0123456789'
+as_cr_alnum=$as_cr_Letters$as_cr_digits
 
-  USE_POINT_Z_M="-DUSE_POINT_Z_M"
+ECHO_C= ECHO_N= ECHO_T=
+case `echo -n x` in #(((((
+-n*)
+  case `echo 'xy\c'` in
+  *c*) ECHO_T='	';;	# ECHO_T is single tab character.
+  xy)  ECHO_C='\c';;
+  *)   echo `echo ksh88 bug on AIX 6.1` > /dev/null
+       ECHO_T='	';;
+  esac;;
+*)
+  ECHO_N='-n';;
+esac
 
-  echo "$as_me:$LINENO: result: Compiling with -DUSE_POINT_Z_M." >&5
-echo "${ECHO_T}Compiling with -DUSE_POINT_Z_M." >&6
+rm -f conf$$ conf$$.exe conf$$.file
+if test -d conf$$.dir; then
+  rm -f conf$$.dir/conf$$.file
+else
+  rm -f conf$$.dir
+  mkdir conf$$.dir 2>/dev/null
 fi
-USE_POINT_Z_M=$USE_POINT_Z_M
-
-ALL_ENABLED="$USE_POINT_Z_M $ALL_ENABLED"
-
-
+if (echo >conf$$.file) 2>/dev/null; then
+  if ln -s conf$$.file conf$$ 2>/dev/null; then
+    as_ln_s='ln -s'
+    # ... but there are two gotchas:
+    # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
+    # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.
+    # In both cases, we have to default to `cp -p'.
+    ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
+      as_ln_s='cp -p'
+  elif ln conf$$.file conf$$ 2>/dev/null; then
+    as_ln_s=ln
+  else
+    as_ln_s='cp -p'
+  fi
+else
+  as_ln_s='cp -p'
+fi
+rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file
+rmdir conf$$.dir 2>/dev/null
 
-# Check whether --enable-point-z-m or --disable-point-z-m was given.
-if test "${enable_point_z_m+set}" = set; then
-  enableval="$enable_point_z_m"
 
-fi;
+# as_fn_mkdir_p
+# -------------
+# Create "$as_dir" as a directory, including parents if necessary.
+as_fn_mkdir_p ()
+{
 
-if test "$enable_fast_nint" = "no" ; then
+  case $as_dir in #(
+  -*) as_dir=./$as_dir;;
+  esac
+  test -d "$as_dir" || eval $as_mkdir_p || {
+    as_dirs=
+    while :; do
+      case $as_dir in #(
+      *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'(
+      *) as_qdir=$as_dir;;
+      esac
+      as_dirs="'$as_qdir' $as_dirs"
+      as_dir=`$as_dirname -- "$as_dir" ||
+$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	 X"$as_dir" : 'X\(//\)[^/]' \| \
+	 X"$as_dir" : 'X\(//\)$' \| \
+	 X"$as_dir" : 'X\(/\)' \| . 2>/dev/null ||
+$as_echo X"$as_dir" |
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)[^/].*/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+      test -d "$as_dir" && break
+    done
+    test -z "$as_dirs" || eval "mkdir $as_dirs"
+  } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir"
 
-  USE_NINT="-DUSE_GENERIC_MS_NINT"
 
-  echo "$as_me:$LINENO: result: Compiling with safe MS_NINT" >&5
-echo "${ECHO_T}Compiling with safe MS_NINT" >&6
+} # as_fn_mkdir_p
+if mkdir -p . 2>/dev/null; then
+  as_mkdir_p='mkdir -p "$as_dir"'
 else
-  USE_NINT=""
-
-  echo "$as_me:$LINENO: result: Compiling with fast MS_NINT" >&5
-echo "${ECHO_T}Compiling with fast MS_NINT" >&6
+  test -d ./-p && rmdir ./-p
+  as_mkdir_p=false
 fi
-USE_NINT=$USE_NINT
-
-ALL_ENABLED="$USE_NINT $ALL_ENABLED"
 
+if test -x / >/dev/null 2>&1; then
+  as_test_x='test -x'
+else
+  if ls -dL / >/dev/null 2>&1; then
+    as_ls_L_option=L
+  else
+    as_ls_L_option=
+  fi
+  as_test_x='
+    eval sh -c '\''
+      if test -d "$1"; then
+	test -d "$1/.";
+      else
+	case $1 in #(
+	-*)set "./$1";;
+	esac;
+	case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in #((
+	???[sx]*):;;*)false;;esac;fi
+    '\'' sh
+  '
+fi
+as_executable_p=$as_test_x
 
-echo "$as_me:$LINENO: checking compiler warnings" >&5
-echo $ECHO_N "checking compiler warnings... $ECHO_C" >&6
+# Sed expression to map a string onto a valid CPP name.
+as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
 
+# Sed expression to map a string onto a valid variable name.
+as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
 
-# Check whether --with-warnings or --without-warnings was given.
-if test "${with_warnings+set}" = set; then
-  withval="$with_warnings"
 
-fi;
+exec 6>&1
+## ----------------------------------- ##
+## Main body of $CONFIG_STATUS script. ##
+## ----------------------------------- ##
+_ASEOF
+test $as_write_fail = 0 && chmod +x $CONFIG_STATUS || ac_write_fail=1
+
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+# Save the log message, to keep $0 and so on meaningful, and to
+# report actual input values of CONFIG_FILES etc. instead of their
+# values after options handling.
+ac_log="
+This file was extended by $as_me, which was
+generated by GNU Autoconf 2.68.  Invocation command line was
 
-if test "$with_warnings" = "yes" ; then
-  if test "$GCC" = "yes" ; then
-    WFLAGS="-W -Wall -Wcast-align -Wmissing-prototypes -Wstrict-prototypes -Wpointer-arith -Wreturn-type"
-    C_EXTRA_WFLAGS="-Wmissing-declarations"
+  CONFIG_FILES    = $CONFIG_FILES
+  CONFIG_HEADERS  = $CONFIG_HEADERS
+  CONFIG_LINKS    = $CONFIG_LINKS
+  CONFIG_COMMANDS = $CONFIG_COMMANDS
+  $ $0 $@
 
-    echo "$as_me:$LINENO: result: strict" >&5
-echo "${ECHO_T}strict" >&6
-  else
-    WFLAGS=""
-    C_EXTRA_WFLAGS=""
-    echo "$as_me:$LINENO: result: disabled" >&5
-echo "${ECHO_T}disabled" >&6
-  fi
+on `(hostname || uname -n) 2>/dev/null | sed 1q`
+"
 
-elif test "$with_warnings" = "" ; then
-  if test "$GCC" = "yes" ; then
-    WFLAGS="-Wall"
-    C_EXTRA_WFLAGS=""
-    echo "$as_me:$LINENO: result: basic" >&5
-echo "${ECHO_T}basic" >&6
-  else
-    WFLAGS=""
-    C_EXTRA_WFLAGS=""
-    echo "$as_me:$LINENO: result: disabled" >&5
-echo "${ECHO_T}disabled" >&6
-  fi
+_ACEOF
 
-elif test "$with_warnings" = "no" ; then
-  WFLAGS=""
-  C_EXTRA_WFLAGS=""
-  echo "$as_me:$LINENO: result: disabled" >&5
-echo "${ECHO_T}disabled" >&6
+case $ac_config_files in *"
+"*) set x $ac_config_files; shift; ac_config_files=$*;;
+esac
 
-else
-  WFLAGS="$with_warnings"
-  C_EXTRA_WFLAGS=""
-  echo "$as_me:$LINENO: result: user defined" >&5
-echo "${ECHO_T}user defined" >&6
-fi
 
-CFLAGS="$CFLAGS $WFLAGS $C_EXTRA_WFLAGS"
-CXXFLAGS="$CXXFLAGS $WFLAGS "
 
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+# Files that config.status was made for.
+config_files="$ac_config_files"
+config_commands="$ac_config_commands"
 
-{ echo "$as_me:$LINENO: checking whether we should enable debug features..." >&5
-echo "$as_me: checking whether we should enable debug features..." >&6;}
-# Check whether --enable-debug or --disable-debug was given.
-if test "${enable_debug+set}" = set; then
-  enableval="$enable_debug"
+_ACEOF
 
-fi;
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+ac_cs_usage="\
+\`$as_me' instantiates files and other configuration actions
+from templates according to the current configuration.  Unless the files
+and actions are specified as TAGs, all are instantiated by default.
 
-if test "$enable_debug" = "yes" ; then
-    CXXFLAGS=`echo "$CXXFLAGS " | sed 's/-O[123] / /'`
-  CFLAGS=`echo "$CFLAGS " | sed 's/-O[123] / /'`
+Usage: $0 [OPTION]... [TAG]...
 
-  REPORT_ENABLE_DEBUG="-g "
-  echo "$as_me:$LINENO: result:         Enabling debug features: -g in CFLAGS." >&5
-echo "${ECHO_T}        Enabling debug features: -g in CFLAGS." >&6
+  -h, --help       print this help, then exit
+  -V, --version    print version number and configuration settings, then exit
+      --config     print configuration, then exit
+  -q, --quiet, --silent
+                   do not print progress messages
+  -d, --debug      don't remove temporary files
+      --recheck    update $as_me by reconfiguring in the same conditions
+      --file=FILE[:TEMPLATE]
+                   instantiate the configuration file FILE
 
-else
-  CXXFLAGS=`echo "$CXXFLAGS -DNDEBUG " | sed "s/-g //"`
-  CFLAGS=`echo "$CFLAGS -DNDEBUG " | sed "s/-g //"`
-fi
+Configuration files:
+$config_files
 
+Configuration commands:
+$config_commands
 
-{ echo "$as_me:$LINENO: checking whether we should enable mapserv CGI command-line debug arguments..." >&5
-echo "$as_me: checking whether we should enable mapserv CGI command-line debug arguments..." >&6;}
-# Check whether --enable-cgi-cl-debug-args or --disable-cgi-cl-debug-args was given.
-if test "${enable_cgi_cl_debug_args+set}" = set; then
-  enableval="$enable_cgi_cl_debug_args"
+Report bugs to the package provider."
 
-fi;
+_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`"
+ac_cs_version="\\
+config.status
+configured by $0, generated by GNU Autoconf 2.68,
+  with options \\"\$ac_cs_config\\"
 
-if test "$enable_cgi_cl_debug_args" = "yes" ; then
-  DEBUG_FLAGS="$DEBUG_FLAGS -DMS_ENABLE_CGI_CL_DEBUG_ARGS"
-  echo "$as_me:$LINENO: result:         Enabling (potentially insecure) mapserv CGI command-line debug arguments: -DMS_ENABLE_CGI_CL_DEBUG_ARGS." >&5
-echo "${ECHO_T}        Enabling (potentially insecure) mapserv CGI command-line debug arguments: -DMS_ENABLE_CGI_CL_DEBUG_ARGS." >&6
-fi
+Copyright (C) 2010 Free Software Foundation, Inc.
+This config.status script is free software; the Free Software Foundation
+gives unlimited permission to copy, distribute and modify it."
 
-DEBUG_FLAGS=$DEBUG_FLAGS
+ac_pwd='$ac_pwd'
+srcdir='$srcdir'
+INSTALL='$INSTALL'
+AWK='$AWK'
+test -n "\$AWK" || AWK=awk
+_ACEOF
 
-ALL_ENABLED="$DEBUG_FLAGS $ALL_ENABLED"
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+# The default lists apply if the user does not specify any file.
+ac_need_defaults=:
+while test $# != 0
+do
+  case $1 in
+  --*=?*)
+    ac_option=`expr "X$1" : 'X\([^=]*\)='`
+    ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'`
+    ac_shift=:
+    ;;
+  --*=)
+    ac_option=`expr "X$1" : 'X\([^=]*\)='`
+    ac_optarg=
+    ac_shift=:
+    ;;
+  *)
+    ac_option=$1
+    ac_optarg=$2
+    ac_shift=shift
+    ;;
+  esac
 
+  case $ac_option in
+  # Handling of the options.
+  -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r)
+    ac_cs_recheck=: ;;
+  --version | --versio | --versi | --vers | --ver | --ve | --v | -V )
+    $as_echo "$ac_cs_version"; exit ;;
+  --config | --confi | --conf | --con | --co | --c )
+    $as_echo "$ac_cs_config"; exit ;;
+  --debug | --debu | --deb | --de | --d | -d )
+    debug=: ;;
+  --file | --fil | --fi | --f )
+    $ac_shift
+    case $ac_optarg in
+    *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;;
+    '') as_fn_error $? "missing file argument" ;;
+    esac
+    as_fn_append CONFIG_FILES " '$ac_optarg'"
+    ac_need_defaults=false;;
+  --he | --h |  --help | --hel | -h )
+    $as_echo "$ac_cs_usage"; exit ;;
+  -q | -quiet | --quiet | --quie | --qui | --qu | --q \
+  | -silent | --silent | --silen | --sile | --sil | --si | --s)
+    ac_cs_silent=: ;;
 
+  # This is an error.
+  -*) as_fn_error $? "unrecognized option: \`$1'
+Try \`$0 --help' for more information." ;;
 
-# Check whether --enable-gcov or --disable-gcov was given.
-if test "${enable_gcov+set}" = set; then
-  enableval="$enable_gcov"
-  CFLAGS="$CFLAGS -fprofile-arcs -ftest-coverage"
- PHP_LD_XTRAFLAGS="$PHP_LD_XTRAFLAGS -fprofile-arcs -ftest-coverage"
-fi;
+  *) as_fn_append ac_config_targets " $1"
+     ac_need_defaults=false ;;
 
+  esac
+  shift
+done
 
+ac_configure_extra_args=
 
-{ echo "$as_me:$LINENO: checking for PHP/MapScript module options..." >&5
-echo "$as_me: checking for PHP/MapScript module options..." >&6;}
+if $ac_cs_silent; then
+  exec 6>/dev/null
+  ac_configure_extra_args="$ac_configure_extra_args --silent"
+fi
 
-# Check whether --with-php or --without-php was given.
-if test "${with_php+set}" = set; then
-  withval="$with_php"
+_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+if \$ac_cs_recheck; then
+  set X '$SHELL' '$0' $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion
+  shift
+  \$as_echo "running CONFIG_SHELL=$SHELL \$*" >&6
+  CONFIG_SHELL='$SHELL'
+  export CONFIG_SHELL
+  exec "\$@"
+fi
 
-fi;
+_ACEOF
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+exec 5>>config.log
+{
+  echo
+  sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX
+## Running $as_me. ##
+_ASBOX
+  $as_echo "$ac_log"
+} >&5
 
-# Check whether --enable-internal-ld-detect or --disable-internal-ld-detect was given.
-if test "${enable_internal_ld_detect+set}" = set; then
-  enableval="$enable_internal_ld_detect"
+_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+#
+# INIT-COMMANDS
+#
 
-fi;
 
-if test -n "$with_php" -a -d "$with_php" ; then
+# The HP-UX ksh and POSIX shell print the target directory to stdout
+# if CDPATH is set.
+(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
+
+sed_quote_subst='$sed_quote_subst'
+double_quote_subst='$double_quote_subst'
+delay_variable_subst='$delay_variable_subst'
+macro_version='`$ECHO "$macro_version" | $SED "$delay_single_quote_subst"`'
+macro_revision='`$ECHO "$macro_revision" | $SED "$delay_single_quote_subst"`'
+enable_static='`$ECHO "$enable_static" | $SED "$delay_single_quote_subst"`'
+enable_shared='`$ECHO "$enable_shared" | $SED "$delay_single_quote_subst"`'
+pic_mode='`$ECHO "$pic_mode" | $SED "$delay_single_quote_subst"`'
+enable_fast_install='`$ECHO "$enable_fast_install" | $SED "$delay_single_quote_subst"`'
+SHELL='`$ECHO "$SHELL" | $SED "$delay_single_quote_subst"`'
+ECHO='`$ECHO "$ECHO" | $SED "$delay_single_quote_subst"`'
+PATH_SEPARATOR='`$ECHO "$PATH_SEPARATOR" | $SED "$delay_single_quote_subst"`'
+host_alias='`$ECHO "$host_alias" | $SED "$delay_single_quote_subst"`'
+host='`$ECHO "$host" | $SED "$delay_single_quote_subst"`'
+host_os='`$ECHO "$host_os" | $SED "$delay_single_quote_subst"`'
+build_alias='`$ECHO "$build_alias" | $SED "$delay_single_quote_subst"`'
+build='`$ECHO "$build" | $SED "$delay_single_quote_subst"`'
+build_os='`$ECHO "$build_os" | $SED "$delay_single_quote_subst"`'
+SED='`$ECHO "$SED" | $SED "$delay_single_quote_subst"`'
+Xsed='`$ECHO "$Xsed" | $SED "$delay_single_quote_subst"`'
+GREP='`$ECHO "$GREP" | $SED "$delay_single_quote_subst"`'
+EGREP='`$ECHO "$EGREP" | $SED "$delay_single_quote_subst"`'
+FGREP='`$ECHO "$FGREP" | $SED "$delay_single_quote_subst"`'
+LD='`$ECHO "$LD" | $SED "$delay_single_quote_subst"`'
+NM='`$ECHO "$NM" | $SED "$delay_single_quote_subst"`'
+LN_S='`$ECHO "$LN_S" | $SED "$delay_single_quote_subst"`'
+max_cmd_len='`$ECHO "$max_cmd_len" | $SED "$delay_single_quote_subst"`'
+ac_objext='`$ECHO "$ac_objext" | $SED "$delay_single_quote_subst"`'
+exeext='`$ECHO "$exeext" | $SED "$delay_single_quote_subst"`'
+lt_unset='`$ECHO "$lt_unset" | $SED "$delay_single_quote_subst"`'
+lt_SP2NL='`$ECHO "$lt_SP2NL" | $SED "$delay_single_quote_subst"`'
+lt_NL2SP='`$ECHO "$lt_NL2SP" | $SED "$delay_single_quote_subst"`'
+lt_cv_to_host_file_cmd='`$ECHO "$lt_cv_to_host_file_cmd" | $SED "$delay_single_quote_subst"`'
+lt_cv_to_tool_file_cmd='`$ECHO "$lt_cv_to_tool_file_cmd" | $SED "$delay_single_quote_subst"`'
+reload_flag='`$ECHO "$reload_flag" | $SED "$delay_single_quote_subst"`'
+reload_cmds='`$ECHO "$reload_cmds" | $SED "$delay_single_quote_subst"`'
+OBJDUMP='`$ECHO "$OBJDUMP" | $SED "$delay_single_quote_subst"`'
+deplibs_check_method='`$ECHO "$deplibs_check_method" | $SED "$delay_single_quote_subst"`'
+file_magic_cmd='`$ECHO "$file_magic_cmd" | $SED "$delay_single_quote_subst"`'
+file_magic_glob='`$ECHO "$file_magic_glob" | $SED "$delay_single_quote_subst"`'
+want_nocaseglob='`$ECHO "$want_nocaseglob" | $SED "$delay_single_quote_subst"`'
+DLLTOOL='`$ECHO "$DLLTOOL" | $SED "$delay_single_quote_subst"`'
+sharedlib_from_linklib_cmd='`$ECHO "$sharedlib_from_linklib_cmd" | $SED "$delay_single_quote_subst"`'
+AR='`$ECHO "$AR" | $SED "$delay_single_quote_subst"`'
+AR_FLAGS='`$ECHO "$AR_FLAGS" | $SED "$delay_single_quote_subst"`'
+archiver_list_spec='`$ECHO "$archiver_list_spec" | $SED "$delay_single_quote_subst"`'
+STRIP='`$ECHO "$STRIP" | $SED "$delay_single_quote_subst"`'
+RANLIB='`$ECHO "$RANLIB" | $SED "$delay_single_quote_subst"`'
+old_postinstall_cmds='`$ECHO "$old_postinstall_cmds" | $SED "$delay_single_quote_subst"`'
+old_postuninstall_cmds='`$ECHO "$old_postuninstall_cmds" | $SED "$delay_single_quote_subst"`'
+old_archive_cmds='`$ECHO "$old_archive_cmds" | $SED "$delay_single_quote_subst"`'
+lock_old_archive_extraction='`$ECHO "$lock_old_archive_extraction" | $SED "$delay_single_quote_subst"`'
+CC='`$ECHO "$CC" | $SED "$delay_single_quote_subst"`'
+CFLAGS='`$ECHO "$CFLAGS" | $SED "$delay_single_quote_subst"`'
+compiler='`$ECHO "$compiler" | $SED "$delay_single_quote_subst"`'
+GCC='`$ECHO "$GCC" | $SED "$delay_single_quote_subst"`'
+lt_cv_sys_global_symbol_pipe='`$ECHO "$lt_cv_sys_global_symbol_pipe" | $SED "$delay_single_quote_subst"`'
+lt_cv_sys_global_symbol_to_cdecl='`$ECHO "$lt_cv_sys_global_symbol_to_cdecl" | $SED "$delay_single_quote_subst"`'
+lt_cv_sys_global_symbol_to_c_name_address='`$ECHO "$lt_cv_sys_global_symbol_to_c_name_address" | $SED "$delay_single_quote_subst"`'
+lt_cv_sys_global_symbol_to_c_name_address_lib_prefix='`$ECHO "$lt_cv_sys_global_symbol_to_c_name_address_lib_prefix" | $SED "$delay_single_quote_subst"`'
+nm_file_list_spec='`$ECHO "$nm_file_list_spec" | $SED "$delay_single_quote_subst"`'
+lt_sysroot='`$ECHO "$lt_sysroot" | $SED "$delay_single_quote_subst"`'
+objdir='`$ECHO "$objdir" | $SED "$delay_single_quote_subst"`'
+MAGIC_CMD='`$ECHO "$MAGIC_CMD" | $SED "$delay_single_quote_subst"`'
+lt_prog_compiler_no_builtin_flag='`$ECHO "$lt_prog_compiler_no_builtin_flag" | $SED "$delay_single_quote_subst"`'
+lt_prog_compiler_pic='`$ECHO "$lt_prog_compiler_pic" | $SED "$delay_single_quote_subst"`'
+lt_prog_compiler_wl='`$ECHO "$lt_prog_compiler_wl" | $SED "$delay_single_quote_subst"`'
+lt_prog_compiler_static='`$ECHO "$lt_prog_compiler_static" | $SED "$delay_single_quote_subst"`'
+lt_cv_prog_compiler_c_o='`$ECHO "$lt_cv_prog_compiler_c_o" | $SED "$delay_single_quote_subst"`'
+need_locks='`$ECHO "$need_locks" | $SED "$delay_single_quote_subst"`'
+MANIFEST_TOOL='`$ECHO "$MANIFEST_TOOL" | $SED "$delay_single_quote_subst"`'
+DSYMUTIL='`$ECHO "$DSYMUTIL" | $SED "$delay_single_quote_subst"`'
+NMEDIT='`$ECHO "$NMEDIT" | $SED "$delay_single_quote_subst"`'
+LIPO='`$ECHO "$LIPO" | $SED "$delay_single_quote_subst"`'
+OTOOL='`$ECHO "$OTOOL" | $SED "$delay_single_quote_subst"`'
+OTOOL64='`$ECHO "$OTOOL64" | $SED "$delay_single_quote_subst"`'
+libext='`$ECHO "$libext" | $SED "$delay_single_quote_subst"`'
+shrext_cmds='`$ECHO "$shrext_cmds" | $SED "$delay_single_quote_subst"`'
+extract_expsyms_cmds='`$ECHO "$extract_expsyms_cmds" | $SED "$delay_single_quote_subst"`'
+archive_cmds_need_lc='`$ECHO "$archive_cmds_need_lc" | $SED "$delay_single_quote_subst"`'
+enable_shared_with_static_runtimes='`$ECHO "$enable_shared_with_static_runtimes" | $SED "$delay_single_quote_subst"`'
+export_dynamic_flag_spec='`$ECHO "$export_dynamic_flag_spec" | $SED "$delay_single_quote_subst"`'
+whole_archive_flag_spec='`$ECHO "$whole_archive_flag_spec" | $SED "$delay_single_quote_subst"`'
+compiler_needs_object='`$ECHO "$compiler_needs_object" | $SED "$delay_single_quote_subst"`'
+old_archive_from_new_cmds='`$ECHO "$old_archive_from_new_cmds" | $SED "$delay_single_quote_subst"`'
+old_archive_from_expsyms_cmds='`$ECHO "$old_archive_from_expsyms_cmds" | $SED "$delay_single_quote_subst"`'
+archive_cmds='`$ECHO "$archive_cmds" | $SED "$delay_single_quote_subst"`'
+archive_expsym_cmds='`$ECHO "$archive_expsym_cmds" | $SED "$delay_single_quote_subst"`'
+module_cmds='`$ECHO "$module_cmds" | $SED "$delay_single_quote_subst"`'
+module_expsym_cmds='`$ECHO "$module_expsym_cmds" | $SED "$delay_single_quote_subst"`'
+with_gnu_ld='`$ECHO "$with_gnu_ld" | $SED "$delay_single_quote_subst"`'
+allow_undefined_flag='`$ECHO "$allow_undefined_flag" | $SED "$delay_single_quote_subst"`'
+no_undefined_flag='`$ECHO "$no_undefined_flag" | $SED "$delay_single_quote_subst"`'
+hardcode_libdir_flag_spec='`$ECHO "$hardcode_libdir_flag_spec" | $SED "$delay_single_quote_subst"`'
+hardcode_libdir_separator='`$ECHO "$hardcode_libdir_separator" | $SED "$delay_single_quote_subst"`'
+hardcode_direct='`$ECHO "$hardcode_direct" | $SED "$delay_single_quote_subst"`'
+hardcode_direct_absolute='`$ECHO "$hardcode_direct_absolute" | $SED "$delay_single_quote_subst"`'
+hardcode_minus_L='`$ECHO "$hardcode_minus_L" | $SED "$delay_single_quote_subst"`'
+hardcode_shlibpath_var='`$ECHO "$hardcode_shlibpath_var" | $SED "$delay_single_quote_subst"`'
+hardcode_automatic='`$ECHO "$hardcode_automatic" | $SED "$delay_single_quote_subst"`'
+inherit_rpath='`$ECHO "$inherit_rpath" | $SED "$delay_single_quote_subst"`'
+link_all_deplibs='`$ECHO "$link_all_deplibs" | $SED "$delay_single_quote_subst"`'
+always_export_symbols='`$ECHO "$always_export_symbols" | $SED "$delay_single_quote_subst"`'
+export_symbols_cmds='`$ECHO "$export_symbols_cmds" | $SED "$delay_single_quote_subst"`'
+exclude_expsyms='`$ECHO "$exclude_expsyms" | $SED "$delay_single_quote_subst"`'
+include_expsyms='`$ECHO "$include_expsyms" | $SED "$delay_single_quote_subst"`'
+prelink_cmds='`$ECHO "$prelink_cmds" | $SED "$delay_single_quote_subst"`'
+postlink_cmds='`$ECHO "$postlink_cmds" | $SED "$delay_single_quote_subst"`'
+file_list_spec='`$ECHO "$file_list_spec" | $SED "$delay_single_quote_subst"`'
+variables_saved_for_relink='`$ECHO "$variables_saved_for_relink" | $SED "$delay_single_quote_subst"`'
+need_lib_prefix='`$ECHO "$need_lib_prefix" | $SED "$delay_single_quote_subst"`'
+need_version='`$ECHO "$need_version" | $SED "$delay_single_quote_subst"`'
+version_type='`$ECHO "$version_type" | $SED "$delay_single_quote_subst"`'
+runpath_var='`$ECHO "$runpath_var" | $SED "$delay_single_quote_subst"`'
+shlibpath_var='`$ECHO "$shlibpath_var" | $SED "$delay_single_quote_subst"`'
+shlibpath_overrides_runpath='`$ECHO "$shlibpath_overrides_runpath" | $SED "$delay_single_quote_subst"`'
+libname_spec='`$ECHO "$libname_spec" | $SED "$delay_single_quote_subst"`'
+library_names_spec='`$ECHO "$library_names_spec" | $SED "$delay_single_quote_subst"`'
+soname_spec='`$ECHO "$soname_spec" | $SED "$delay_single_quote_subst"`'
+install_override_mode='`$ECHO "$install_override_mode" | $SED "$delay_single_quote_subst"`'
+postinstall_cmds='`$ECHO "$postinstall_cmds" | $SED "$delay_single_quote_subst"`'
+postuninstall_cmds='`$ECHO "$postuninstall_cmds" | $SED "$delay_single_quote_subst"`'
+finish_cmds='`$ECHO "$finish_cmds" | $SED "$delay_single_quote_subst"`'
+finish_eval='`$ECHO "$finish_eval" | $SED "$delay_single_quote_subst"`'
+hardcode_into_libs='`$ECHO "$hardcode_into_libs" | $SED "$delay_single_quote_subst"`'
+sys_lib_search_path_spec='`$ECHO "$sys_lib_search_path_spec" | $SED "$delay_single_quote_subst"`'
+sys_lib_dlsearch_path_spec='`$ECHO "$sys_lib_dlsearch_path_spec" | $SED "$delay_single_quote_subst"`'
+hardcode_action='`$ECHO "$hardcode_action" | $SED "$delay_single_quote_subst"`'
+enable_dlopen='`$ECHO "$enable_dlopen" | $SED "$delay_single_quote_subst"`'
+enable_dlopen_self='`$ECHO "$enable_dlopen_self" | $SED "$delay_single_quote_subst"`'
+enable_dlopen_self_static='`$ECHO "$enable_dlopen_self_static" | $SED "$delay_single_quote_subst"`'
+old_striplib='`$ECHO "$old_striplib" | $SED "$delay_single_quote_subst"`'
+striplib='`$ECHO "$striplib" | $SED "$delay_single_quote_subst"`'
+compiler_lib_search_dirs='`$ECHO "$compiler_lib_search_dirs" | $SED "$delay_single_quote_subst"`'
+predep_objects='`$ECHO "$predep_objects" | $SED "$delay_single_quote_subst"`'
+postdep_objects='`$ECHO "$postdep_objects" | $SED "$delay_single_quote_subst"`'
+predeps='`$ECHO "$predeps" | $SED "$delay_single_quote_subst"`'
+postdeps='`$ECHO "$postdeps" | $SED "$delay_single_quote_subst"`'
+compiler_lib_search_path='`$ECHO "$compiler_lib_search_path" | $SED "$delay_single_quote_subst"`'
+LD_CXX='`$ECHO "$LD_CXX" | $SED "$delay_single_quote_subst"`'
+reload_flag_CXX='`$ECHO "$reload_flag_CXX" | $SED "$delay_single_quote_subst"`'
+reload_cmds_CXX='`$ECHO "$reload_cmds_CXX" | $SED "$delay_single_quote_subst"`'
+old_archive_cmds_CXX='`$ECHO "$old_archive_cmds_CXX" | $SED "$delay_single_quote_subst"`'
+compiler_CXX='`$ECHO "$compiler_CXX" | $SED "$delay_single_quote_subst"`'
+GCC_CXX='`$ECHO "$GCC_CXX" | $SED "$delay_single_quote_subst"`'
+lt_prog_compiler_no_builtin_flag_CXX='`$ECHO "$lt_prog_compiler_no_builtin_flag_CXX" | $SED "$delay_single_quote_subst"`'
+lt_prog_compiler_pic_CXX='`$ECHO "$lt_prog_compiler_pic_CXX" | $SED "$delay_single_quote_subst"`'
+lt_prog_compiler_wl_CXX='`$ECHO "$lt_prog_compiler_wl_CXX" | $SED "$delay_single_quote_subst"`'
+lt_prog_compiler_static_CXX='`$ECHO "$lt_prog_compiler_static_CXX" | $SED "$delay_single_quote_subst"`'
+lt_cv_prog_compiler_c_o_CXX='`$ECHO "$lt_cv_prog_compiler_c_o_CXX" | $SED "$delay_single_quote_subst"`'
+archive_cmds_need_lc_CXX='`$ECHO "$archive_cmds_need_lc_CXX" | $SED "$delay_single_quote_subst"`'
+enable_shared_with_static_runtimes_CXX='`$ECHO "$enable_shared_with_static_runtimes_CXX" | $SED "$delay_single_quote_subst"`'
+export_dynamic_flag_spec_CXX='`$ECHO "$export_dynamic_flag_spec_CXX" | $SED "$delay_single_quote_subst"`'
+whole_archive_flag_spec_CXX='`$ECHO "$whole_archive_flag_spec_CXX" | $SED "$delay_single_quote_subst"`'
+compiler_needs_object_CXX='`$ECHO "$compiler_needs_object_CXX" | $SED "$delay_single_quote_subst"`'
+old_archive_from_new_cmds_CXX='`$ECHO "$old_archive_from_new_cmds_CXX" | $SED "$delay_single_quote_subst"`'
+old_archive_from_expsyms_cmds_CXX='`$ECHO "$old_archive_from_expsyms_cmds_CXX" | $SED "$delay_single_quote_subst"`'
+archive_cmds_CXX='`$ECHO "$archive_cmds_CXX" | $SED "$delay_single_quote_subst"`'
+archive_expsym_cmds_CXX='`$ECHO "$archive_expsym_cmds_CXX" | $SED "$delay_single_quote_subst"`'
+module_cmds_CXX='`$ECHO "$module_cmds_CXX" | $SED "$delay_single_quote_subst"`'
+module_expsym_cmds_CXX='`$ECHO "$module_expsym_cmds_CXX" | $SED "$delay_single_quote_subst"`'
+with_gnu_ld_CXX='`$ECHO "$with_gnu_ld_CXX" | $SED "$delay_single_quote_subst"`'
+allow_undefined_flag_CXX='`$ECHO "$allow_undefined_flag_CXX" | $SED "$delay_single_quote_subst"`'
+no_undefined_flag_CXX='`$ECHO "$no_undefined_flag_CXX" | $SED "$delay_single_quote_subst"`'
+hardcode_libdir_flag_spec_CXX='`$ECHO "$hardcode_libdir_flag_spec_CXX" | $SED "$delay_single_quote_subst"`'
+hardcode_libdir_separator_CXX='`$ECHO "$hardcode_libdir_separator_CXX" | $SED "$delay_single_quote_subst"`'
+hardcode_direct_CXX='`$ECHO "$hardcode_direct_CXX" | $SED "$delay_single_quote_subst"`'
+hardcode_direct_absolute_CXX='`$ECHO "$hardcode_direct_absolute_CXX" | $SED "$delay_single_quote_subst"`'
+hardcode_minus_L_CXX='`$ECHO "$hardcode_minus_L_CXX" | $SED "$delay_single_quote_subst"`'
+hardcode_shlibpath_var_CXX='`$ECHO "$hardcode_shlibpath_var_CXX" | $SED "$delay_single_quote_subst"`'
+hardcode_automatic_CXX='`$ECHO "$hardcode_automatic_CXX" | $SED "$delay_single_quote_subst"`'
+inherit_rpath_CXX='`$ECHO "$inherit_rpath_CXX" | $SED "$delay_single_quote_subst"`'
+link_all_deplibs_CXX='`$ECHO "$link_all_deplibs_CXX" | $SED "$delay_single_quote_subst"`'
+always_export_symbols_CXX='`$ECHO "$always_export_symbols_CXX" | $SED "$delay_single_quote_subst"`'
+export_symbols_cmds_CXX='`$ECHO "$export_symbols_cmds_CXX" | $SED "$delay_single_quote_subst"`'
+exclude_expsyms_CXX='`$ECHO "$exclude_expsyms_CXX" | $SED "$delay_single_quote_subst"`'
+include_expsyms_CXX='`$ECHO "$include_expsyms_CXX" | $SED "$delay_single_quote_subst"`'
+prelink_cmds_CXX='`$ECHO "$prelink_cmds_CXX" | $SED "$delay_single_quote_subst"`'
+postlink_cmds_CXX='`$ECHO "$postlink_cmds_CXX" | $SED "$delay_single_quote_subst"`'
+file_list_spec_CXX='`$ECHO "$file_list_spec_CXX" | $SED "$delay_single_quote_subst"`'
+hardcode_action_CXX='`$ECHO "$hardcode_action_CXX" | $SED "$delay_single_quote_subst"`'
+compiler_lib_search_dirs_CXX='`$ECHO "$compiler_lib_search_dirs_CXX" | $SED "$delay_single_quote_subst"`'
+predep_objects_CXX='`$ECHO "$predep_objects_CXX" | $SED "$delay_single_quote_subst"`'
+postdep_objects_CXX='`$ECHO "$postdep_objects_CXX" | $SED "$delay_single_quote_subst"`'
+predeps_CXX='`$ECHO "$predeps_CXX" | $SED "$delay_single_quote_subst"`'
+postdeps_CXX='`$ECHO "$postdeps_CXX" | $SED "$delay_single_quote_subst"`'
+compiler_lib_search_path_CXX='`$ECHO "$compiler_lib_search_path_CXX" | $SED "$delay_single_quote_subst"`'
+
+LTCC='$LTCC'
+LTCFLAGS='$LTCFLAGS'
+compiler='$compiler_DEFAULT'
+
+# A function that is used when there is no print builtin or printf.
+func_fallback_echo ()
+{
+  eval 'cat <<_LTECHO_EOF
+\$1
+_LTECHO_EOF'
+}
 
-  if test -z "$with_php" || echo "$with_php" | grep '^/' >/dev/null ; then
-    PHP_SRC_DIR="$with_php"
-  else
-    PHP_SRC_DIR="`pwd`/$with_php"
-  fi
+# Quote evaled strings.
+for var in SHELL \
+ECHO \
+PATH_SEPARATOR \
+SED \
+GREP \
+EGREP \
+FGREP \
+LD \
+NM \
+LN_S \
+lt_SP2NL \
+lt_NL2SP \
+reload_flag \
+OBJDUMP \
+deplibs_check_method \
+file_magic_cmd \
+file_magic_glob \
+want_nocaseglob \
+DLLTOOL \
+sharedlib_from_linklib_cmd \
+AR \
+AR_FLAGS \
+archiver_list_spec \
+STRIP \
+RANLIB \
+CC \
+CFLAGS \
+compiler \
+lt_cv_sys_global_symbol_pipe \
+lt_cv_sys_global_symbol_to_cdecl \
+lt_cv_sys_global_symbol_to_c_name_address \
+lt_cv_sys_global_symbol_to_c_name_address_lib_prefix \
+nm_file_list_spec \
+lt_prog_compiler_no_builtin_flag \
+lt_prog_compiler_pic \
+lt_prog_compiler_wl \
+lt_prog_compiler_static \
+lt_cv_prog_compiler_c_o \
+need_locks \
+MANIFEST_TOOL \
+DSYMUTIL \
+NMEDIT \
+LIPO \
+OTOOL \
+OTOOL64 \
+shrext_cmds \
+export_dynamic_flag_spec \
+whole_archive_flag_spec \
+compiler_needs_object \
+with_gnu_ld \
+allow_undefined_flag \
+no_undefined_flag \
+hardcode_libdir_flag_spec \
+hardcode_libdir_separator \
+exclude_expsyms \
+include_expsyms \
+file_list_spec \
+variables_saved_for_relink \
+libname_spec \
+library_names_spec \
+soname_spec \
+install_override_mode \
+finish_eval \
+old_striplib \
+striplib \
+compiler_lib_search_dirs \
+predep_objects \
+postdep_objects \
+predeps \
+postdeps \
+compiler_lib_search_path \
+LD_CXX \
+reload_flag_CXX \
+compiler_CXX \
+lt_prog_compiler_no_builtin_flag_CXX \
+lt_prog_compiler_pic_CXX \
+lt_prog_compiler_wl_CXX \
+lt_prog_compiler_static_CXX \
+lt_cv_prog_compiler_c_o_CXX \
+export_dynamic_flag_spec_CXX \
+whole_archive_flag_spec_CXX \
+compiler_needs_object_CXX \
+with_gnu_ld_CXX \
+allow_undefined_flag_CXX \
+no_undefined_flag_CXX \
+hardcode_libdir_flag_spec_CXX \
+hardcode_libdir_separator_CXX \
+exclude_expsyms_CXX \
+include_expsyms_CXX \
+file_list_spec_CXX \
+compiler_lib_search_dirs_CXX \
+predep_objects_CXX \
+postdep_objects_CXX \
+predeps_CXX \
+postdeps_CXX \
+compiler_lib_search_path_CXX; do
+    case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in
+    *[\\\\\\\`\\"\\\$]*)
+      eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED \\"\\\$sed_quote_subst\\"\\\`\\\\\\""
+      ;;
+    *)
+      eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\""
+      ;;
+    esac
+done
 
+# Double-quote double-evaled strings.
+for var in reload_cmds \
+old_postinstall_cmds \
+old_postuninstall_cmds \
+old_archive_cmds \
+extract_expsyms_cmds \
+old_archive_from_new_cmds \
+old_archive_from_expsyms_cmds \
+archive_cmds \
+archive_expsym_cmds \
+module_cmds \
+module_expsym_cmds \
+export_symbols_cmds \
+prelink_cmds \
+postlink_cmds \
+postinstall_cmds \
+postuninstall_cmds \
+finish_cmds \
+sys_lib_search_path_spec \
+sys_lib_dlsearch_path_spec \
+reload_cmds_CXX \
+old_archive_cmds_CXX \
+old_archive_from_new_cmds_CXX \
+old_archive_from_expsyms_cmds_CXX \
+archive_cmds_CXX \
+archive_expsym_cmds_CXX \
+module_cmds_CXX \
+module_expsym_cmds_CXX \
+export_symbols_cmds_CXX \
+prelink_cmds_CXX \
+postlink_cmds_CXX; do
+    case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in
+    *[\\\\\\\`\\"\\\$]*)
+      eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED -e \\"\\\$double_quote_subst\\" -e \\"\\\$sed_quote_subst\\" -e \\"\\\$delay_variable_subst\\"\\\`\\\\\\""
+      ;;
+    *)
+      eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\""
+      ;;
+    esac
+done
 
-  if test "$enable_perlv_ld_detect" = "yes" ; then
-      echo "$as_me:$LINENO: result: Using perl -V macro to figure ld command to link php_mapscript.so" >&5
-echo "${ECHO_T}Using perl -V macro to figure ld command to link php_mapscript.so" >&6
+ac_aux_dir='$ac_aux_dir'
+xsi_shell='$xsi_shell'
+lt_shell_append='$lt_shell_append'
 
-      echo "$as_me:$LINENO: checking whether 'perl -V' works" >&5
-echo $ECHO_N "checking whether 'perl -V' works... $ECHO_C" >&6
-      if  (perl -V > /dev/null 2>&1)  ; then
-        echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6
+# See if we are running on zsh, and set the options which allow our
+# commands through without removal of \ escapes INIT.
+if test -n "\${ZSH_VERSION+set}" ; then
+   setopt NO_GLOB_SUBST
+fi
 
-#
-# The following is a massive hack.  It tries to steal the
-# mechanism for build a dynamic library from Perl's -V output
-# If this script fails on this machine, try running 'perl -V'
-# manually and pick out the setting for:
-#
-#    cc, optimize, ccflags, ld, cccdlflags and lddlflags
-#
-# Replace the below definitions with the output you see.
-#
 
-if test ! -r "perl.out"; then
-	perl -V > perl.out
-fi
-
-# if the greps and cuts don't do the job, set these manually
-PERL_CC="`grep ' cc=' perl.out | cut -d, -f1 | cut -d\' -f2 | grep -v undef`"
-PERL_OPT="`grep ' optimize=' perl.out | cut -d, -f2 | cut -d\' -f2 | grep -v undef`"
-PERL_CCFLAGS="`grep ' ccflags' perl.out | cut -d, -f1 | grep cflags | cut -d\' -f2 | grep -v undef` `grep ' ccflags' perl.out | cut -d, -f2 | grep ccflags | cut -d\' -f2 | grep -v undef`"
-PERL_LD="`grep ' ld=' perl.out | cut -d, -f1 | cut -d\' -f2 | grep -v undef`"
-PERL_LFLAGS="`grep ' cccdlflags=' perl.out | cut -d, -f1 | cut -d\' -f2 | grep -v undef`"
-PERL_CCDLFLAGS="`grep ' ccdlflags=' perl.out | cut -d, -f4 | cut -d\' -f2 | sed 's, ,,' | grep -v undef`"
-PERL_LDDLFLAGS=`grep ' lddlflags' perl.out | cut -d, -f2 | cut -d\' -f2 | grep -v undef`
-#--------
-
-#if test -n "$PERL_CCDLFLAGS" ; then
-#	echo "-------------------------"
-#	echo "----- IMPORTANT !!! -----"
-#	echo "-------------------------"
-#	echo "To use PHP extensions on your OS, you will need to recompile "
-#	echo "PHP.                                                         "
-#	echo "You need to edit the Makefile in the php3 directory and add  "
-#	echo "$PERL_CCDLFLAGS to the start of the LDFLAGS line at the top  "
-#	echo "of the Makefile.  Then type: 'make clean; make'              "
-#	echo "You can still go ahead and build the extensions now by typing"
-#	echo "'make' in this directory.  They just won't work correctly    "
-#	echo "until you recompile your PHP.                                "
-#        echo "If you are compiling php as a module, you should also add    "
-#        echo "$PERL_CCDLFLAGS to the start of the EXTRA_LDFLAGS in Apache  "
-#        echo "Configuration file.  Note that if you are using the APACI    "
-#        echo "build mechanism you should make this change in the           "
-#        echo "Configuration.tmpl file instead.                             "
-#	echo "-------------------------"
-#	echo "-------------------------"
-#	echo "-------------------------"
-#fi
-
-PERL_CC="$PERL_CC $PERL_OPT $PERL_CCFLAGS -I. -I.. $PERL_LFLAGS"
-PERL_LD="$PERL_LD $PERL_LDDLFLAGS $PERL_CCDLFLAGS"
-
-rm -f perl.out
-
-
-        PHP_CC="$PERL_CC"
-        PHP_LD="$PERL_LD $PHP_LD_XTRAFLAGS"
-      else
-        echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
-        { { echo "$as_me:$LINENO: error: ERROR: Cannot use --enable-perlv-ld-detect since Perl -V does not work on this system." >&5
-echo "$as_me: error: ERROR: Cannot use --enable-perlv-ld-detect since Perl -V does not work on this system." >&2;}
-   { (exit 1); exit 1; }; }
-      fi
-  else
+    PACKAGE='$PACKAGE'
+    VERSION='$VERSION'
+    TIMESTAMP='$TIMESTAMP'
+    RM='$RM'
+    ofile='$ofile'
 
-	echo 'void f(){}' > conftest.c
-	if test -z "`${CC} -fPIC -c conftest.c 2>&1`"; then
-	  C_PIC=-fPIC
-	else
-	  C_PIC=
-	fi
-	rm -f conftest*
 
-	C_PIC=$C_PIC
 
 
 
 
+_ACEOF
 
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
 
+# Handling of arguments.
+for ac_config_target in $ac_config_targets
+do
+  case $ac_config_target in
+    "libtool") CONFIG_COMMANDS="$CONFIG_COMMANDS libtool" ;;
+    "Makefile") CONFIG_FILES="$CONFIG_FILES Makefile" ;;
+    "mapscript/php/Makefile") CONFIG_FILES="$CONFIG_FILES mapscript/php/Makefile" ;;
+    "mapscript/python/Makefile") CONFIG_FILES="$CONFIG_FILES mapscript/python/Makefile" ;;
+    "mapscript/java/Makefile") CONFIG_FILES="$CONFIG_FILES mapscript/java/Makefile" ;;
+    "mapscript/csharp/Makefile") CONFIG_FILES="$CONFIG_FILES mapscript/csharp/Makefile" ;;
+    "mapscript/perl/Makefile.PL") CONFIG_FILES="$CONFIG_FILES mapscript/perl/Makefile.PL" ;;
+
+  *) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5;;
+  esac
+done
 
-  echo 'void g(); int main(){ g(); return 0; }' > conftest1.c
 
-  echo '#include <stdio.h>' > conftest2.c
-  echo 'void g(); void g(){printf("");}' >> conftest2.c
-  ${CC} ${C_PIC} -c conftest2.c
-  SO_EXT="so"
-  SO_COMMAND_NAME="-soname"
-  export SO_EXT
-  export SO_COMMAND_NAME
-  LD_SHARED="/bin/true"
-  if test ! -z "`uname -a | grep IRIX`" ; then
-    IRIX_ALL=-all
-  else
-    IRIX_ALL=
-  fi
+# If the user did not use the arguments to specify the items to instantiate,
+# then the envvar interface is used.  Set only those that are not.
+# We use the long form for the default assignment because of an extremely
+# bizarre bug on SunOS 4.1.3.
+if $ac_need_defaults; then
+  test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files
+  test "${CONFIG_COMMANDS+set}" = set || CONFIG_COMMANDS=$config_commands
+fi
 
+# Have a temporary directory for convenience.  Make it in the build tree
+# simply because there is no reason against having it here, and in addition,
+# creating and moving files from /tmp can sometimes cause problems.
+# Hook for its removal unless debugging.
+# Note that there is a small window in which the directory will not be cleaned:
+# after its creation but before its name has been assigned to `$tmp'.
+$debug ||
+{
+  tmp= ac_tmp=
+  trap 'exit_status=$?
+  : "${ac_tmp:=$tmp}"
+  { test ! -d "$ac_tmp" || rm -fr "$ac_tmp"; } && exit $exit_status
+' 0
+  trap 'as_fn_exit 1' 1 2 13 15
+}
+# Create a (secure) tmp directory for tmp files.
 
-# Check whether --with-ld-shared or --without-ld-shared was given.
-if test "${with_ld_shared+set}" = set; then
-  withval="$with_ld_shared"
+{
+  tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` &&
+  test -d "$tmp"
+}  ||
+{
+  tmp=./conf$$-$RANDOM
+  (umask 077 && mkdir "$tmp")
+} || as_fn_error $? "cannot create a temporary directory in ." "$LINENO" 5
+ac_tmp=$tmp
 
-fi;
+# Set up the scripts for CONFIG_FILES section.
+# No need to generate them if there are no CONFIG_FILES.
+# This happens for instance with `./config.status config.h'.
+if test -n "$CONFIG_FILES"; then
 
-      if test "$with_ld_shared" != "" -a "$with_ld_shared" != "yes"; then
-    if test "$with_ld_shared" = "no" ; then
-      echo "$as_me:$LINENO: result: user disabled shared library support." >&5
-echo "${ECHO_T}user disabled shared library support." >&6
-    else
-      echo "$as_me:$LINENO: result: using user supplied .so link command ... $with_ld_shared" >&5
-echo "${ECHO_T}using user supplied .so link command ... $with_ld_shared" >&6
-    fi
-    LD_SHARED="$with_ld_shared"
-  fi
 
-    if test ! -z "`uname -a | grep CYGWIN`" \
-        -a "$LD_SHARED" = "/bin/true" ; then
-    if test -z "`gcc -shared conftest2.o -o libconftest.dll`" ; then
-      if test -z "`${CC} conftest1.c -L./ -lconftest -o conftest1 2>&1`"; then
-        LD_LIBRARY_PATH_OLD="$LD_LIBRARY_PATH"
-        if test -z "$LD_LIBRARY_PATH" ; then
-          LD_LIBRARY_PATH="`pwd`"
-        else
-          LD_LIBRARY_PATH="`pwd`:$LD_LIBRARY_PATH"
-        fi
-        export LD_LIBRARY_PATH
-        if test -z "`./conftest1 2>&1`" ; then
-          echo "checking for Cygwin gcc -shared ... yes"
-          LD_SHARED="c++ -shared"
-          SO_EXT="dll"
-        fi
-        LD_LIBRARY_PATH="$LD_LIBRARY_PATH_OLD"
-      fi
-    fi
-  fi
+ac_cr=`echo X | tr X '\015'`
+# On cygwin, bash can eat \r inside `` if the user requested igncr.
+# But we know of no other shell where ac_cr would be empty at this
+# point, so we can use a bashism as a fallback.
+if test "x$ac_cr" = x; then
+  eval ac_cr=\$\'\\r\'
+fi
+ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' </dev/null 2>/dev/null`
+if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then
+  ac_cs_awk_cr='\\r'
+else
+  ac_cs_awk_cr=$ac_cr
+fi
 
+echo 'BEGIN {' >"$ac_tmp/subs1.awk" &&
+_ACEOF
 
-    if test ! -z "`uname | grep Darwin`" \
-          -a "$LD_SHARED" = "/bin/true" ; then
-    if test -z "`${CXX} -dynamiclib conftest2.o -o libconftest.so 2>&1`" ; then
-      ${CC} -c conftest1.c
-      if test -z "`${CXX} conftest1.o libconftest.so -o conftest1 2>&1`"; then
-        DYLD_LIBRARY_PATH_OLD="$DYLD_LIBRARY_PATH"
-        if test -z "$DYLD_LIBRARY_PATH" ; then
-          DYLD_LIBRARY_PATH="`pwd`"
-        else
-          DYLD_LIBRARY_PATH="`pwd`:$DYLD_LIBRARY_PATH"
-        fi
-        export DYLD_LIBRARY_PATH
-        if test -z "`./conftest1 2>&1`" ; then
-          echo "checking for ${CXX} -dynamiclib ... yes"
-          LD_SHARED="${CXX} -dynamiclib -single_module -flat_namespace -undefined suppress"
-	  SO_EXT=dylib
-          SO_COMMAND_NAME='-dylib_install_name'
-        fi
-        DYLD_LIBRARY_PATH="$DYLD_LIBRARY_PATH_OLD"
-      fi
-      rm -f conftest1.o
-    fi
-  fi
 
-  if test "$LD_SHARED" = "/bin/true" \
-	-a -z "`${CXX} -shared $IRIX_ALL conftest2.o -o libconftest.so 2>&1|grep -v WARNING`" ; then
-    if test -z "`${CC} conftest1.c libconftest.so -o conftest1 2>&1`"; then
-      LD_LIBRARY_PATH_OLD="$LD_LIBRARY_PATH"
-      if test -z "$LD_LIBRARY_PATH" ; then
-        LD_LIBRARY_PATH="`pwd`"
-      else
-        LD_LIBRARY_PATH="`pwd`:$LD_LIBRARY_PATH"
-      fi
-      export LD_LIBRARY_PATH
-      if test -z "`./conftest1 2>&1`" ; then
-        echo "checking for ${CXX} -shared ... yes"
-        LD_SHARED="${CXX} -shared $IRIX_ALL"
-      else
-        echo "checking for ${CXX} -shared ... no(3)"
-      fi
-      LD_LIBRARY_PATH="$LD_LIBRARY_PATH_OLD"
-    else
-      echo "checking for ${CXX} -shared ... no(2)"
-    fi
+{
+  echo "cat >conf$$subs.awk <<_ACEOF" &&
+  echo "$ac_subst_vars" | sed 's/.*/&!$&$ac_delim/' &&
+  echo "_ACEOF"
+} >conf$$subs.sh ||
+  as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5
+ac_delim_num=`echo "$ac_subst_vars" | grep -c '^'`
+ac_delim='%!_!# '
+for ac_last_try in false false false false false :; do
+  . ./conf$$subs.sh ||
+    as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5
+
+  ac_delim_n=`sed -n "s/.*$ac_delim\$/X/p" conf$$subs.awk | grep -c X`
+  if test $ac_delim_n = $ac_delim_num; then
+    break
+  elif $ac_last_try; then
+    as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5
   else
-    if test "$LD_SHARED" = "/bin/true" ; then
-      echo "checking for ${CXX} -shared ... no(1)"
-    fi
+    ac_delim="$ac_delim!$ac_delim _$ac_delim!! "
   fi
+done
+rm -f conf$$subs.sh
 
-  if test "$LD_SHARED" = "/bin/true" \
-          -a -z "`ld -shared conftest2.o -o libconftest.so 2>&1`" ; then
-    if test -z "`${CC} conftest1.c libconftest.so -o conftest1 2>&1`"; then
-      LD_LIBRARY_PATH_OLD="$LD_LIBRARY_PATH"
-      if test -z "$LD_LIBRARY_PATH" ; then
-        LD_LIBRARY_PATH="`pwd`"
-      else
-        LD_LIBRARY_PATH="`pwd`:$LD_LIBRARY_PATH"
-      fi
-      export LD_LIBRARY_PATH
-      if test -z "`./conftest1 2>&1`" ; then
-        echo "checking for ld -shared ... yes"
-        LD_SHARED="ld -shared"
-      fi
-      LD_LIBRARY_PATH="$LD_LIBRARY_PATH_OLD"
-    fi
-  fi
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+cat >>"\$ac_tmp/subs1.awk" <<\\_ACAWK &&
+_ACEOF
+sed -n '
+h
+s/^/S["/; s/!.*/"]=/
+p
+g
+s/^[^!]*!//
+:repl
+t repl
+s/'"$ac_delim"'$//
+t delim
+:nl
+h
+s/\(.\{148\}\)..*/\1/
+t more1
+s/["\\]/\\&/g; s/^/"/; s/$/\\n"\\/
+p
+n
+b repl
+:more1
+s/["\\]/\\&/g; s/^/"/; s/$/"\\/
+p
+g
+s/.\{148\}//
+t nl
+:delim
+h
+s/\(.\{148\}\)..*/\1/
+t more2
+s/["\\]/\\&/g; s/^/"/; s/$/"/
+p
+b
+:more2
+s/["\\]/\\&/g; s/^/"/; s/$/"\\/
+p
+g
+s/.\{148\}//
+t delim
+' <conf$$subs.awk | sed '
+/^[^""]/{
+  N
+  s/\n//
+}
+' >>$CONFIG_STATUS || ac_write_fail=1
+rm -f conf$$subs.awk
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+_ACAWK
+cat >>"\$ac_tmp/subs1.awk" <<_ACAWK &&
+  for (key in S) S_is_set[key] = 1
+  FS = ""
 
-  if test "$LD_SHARED" = "/bin/true" ; then
-    echo "checking for ld -shared ... no"
-    if test ! -x /bin/true ; then
-      LD_SHARED=/usr/bin/true
-    fi
-  fi
-  if test "$LD_SHARED" = "no" ; then
-    if test -x /bin/true ; then
-      LD_SHARED=/bin/true
-    else
-      LD_SHARED=/usr/bin/true
-    fi
-  fi
+}
+{
+  line = $ 0
+  nfields = split(line, field, "@")
+  substed = 0
+  len = length(field[1])
+  for (i = 2; i < nfields; i++) {
+    key = field[i]
+    keylen = length(key)
+    if (S_is_set[key]) {
+      value = S[key]
+      line = substr(line, 1, len) "" value "" substr(line, len + keylen + 3)
+      len += length(value) + length(field[++i])
+      substed = 1
+    } else
+      len += 1 + keylen
+  }
+
+  print line
+}
 
-  rm -f conftest* libconftest*
+_ACAWK
+_ACEOF
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then
+  sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g"
+else
+  cat
+fi < "$ac_tmp/subs1.awk" > "$ac_tmp/subs.awk" \
+  || as_fn_error $? "could not setup config files machinery" "$LINENO" 5
+_ACEOF
 
-  LD_SHARED=$LD_SHARED
+# VPATH may cause trouble with some makes, so we remove sole $(srcdir),
+# ${srcdir} and @srcdir@ entries from VPATH if srcdir is ".", strip leading and
+# trailing colons and then remove the whole line if VPATH becomes empty
+# (actually we leave an empty line to preserve line numbers).
+if test "x$srcdir" = x.; then
+  ac_vpsub='/^[	 ]*VPATH[	 ]*=[	 ]*/{
+h
+s///
+s/^/:/
+s/[	 ]*$/:/
+s/:\$(srcdir):/:/g
+s/:\${srcdir}:/:/g
+s/:@srcdir@:/:/g
+s/^:*//
+s/:*$//
+x
+s/\(=[	 ]*\).*/\1/
+G
+s/\n//
+s/^[^=]*=[	 ]*$//
+}'
+fi
 
-  SO_EXT=$SO_EXT
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+fi # test -n "$CONFIG_FILES"
 
-  SO_COMMAND_NAME=$SO_COMMAND_NAME
 
+eval set X "  :F $CONFIG_FILES      :C $CONFIG_COMMANDS"
+shift
+for ac_tag
+do
+  case $ac_tag in
+  :[FHLC]) ac_mode=$ac_tag; continue;;
+  esac
+  case $ac_mode$ac_tag in
+  :[FHL]*:*);;
+  :L* | :C*:*) as_fn_error $? "invalid tag \`$ac_tag'" "$LINENO" 5;;
+  :[FH]-) ac_tag=-:-;;
+  :[FH]*) ac_tag=$ac_tag:$ac_tag.in;;
+  esac
+  ac_save_IFS=$IFS
+  IFS=:
+  set x $ac_tag
+  IFS=$ac_save_IFS
+  shift
+  ac_file=$1
+  shift
 
+  case $ac_mode in
+  :L) ac_source=$1;;
+  :[FH])
+    ac_file_inputs=
+    for ac_f
+    do
+      case $ac_f in
+      -) ac_f="$ac_tmp/stdin";;
+      *) # Look for the file first in the build tree, then in the source tree
+	 # (if the path is not absolute).  The absolute path cannot be DOS-style,
+	 # because $ac_f cannot contain `:'.
+	 test -f "$ac_f" ||
+	   case $ac_f in
+	   [\\/$]*) false;;
+	   *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";;
+	   esac ||
+	   as_fn_error 1 "cannot find input file: \`$ac_f'" "$LINENO" 5;;
+      esac
+      case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac
+      as_fn_append ac_file_inputs " '$ac_f'"
+    done
 
-    if test ! -z "`uname | grep Darwin`" ;then
-          PHP_LD_SHARED="${CXX} -bundle -flat_namespace -undefined suppress"
-  else
-	  PHP_LD_SHARED=$LD_SHARED
-  fi
+    # Let's still pretend it is `configure' which instantiates (i.e., don't
+    # use $as_me), people would be surprised to read:
+    #    /* config.h.  Generated by config.status.  */
+    configure_input='Generated from '`
+	  $as_echo "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g'
+	`' by configure.'
+    if test x"$ac_file" != x-; then
+      configure_input="$ac_file.  $configure_input"
+      { $as_echo "$as_me:${as_lineno-$LINENO}: creating $ac_file" >&5
+$as_echo "$as_me: creating $ac_file" >&6;}
+    fi
+    # Neutralize special characters interpreted by sed in replacement strings.
+    case $configure_input in #(
+    *\&* | *\|* | *\\* )
+       ac_sed_conf_input=`$as_echo "$configure_input" |
+       sed 's/[\\\\&|]/\\\\&/g'`;; #(
+    *) ac_sed_conf_input=$configure_input;;
+    esac
 
-export PHP_LD_SHARED
-PHP_LD_SHARED=$PHP_LD_SHARED
+    case $ac_tag in
+    *:-:* | *:-) cat >"$ac_tmp/stdin" \
+      || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;;
+    esac
+    ;;
+  esac
 
+  ac_dir=`$as_dirname -- "$ac_file" ||
+$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	 X"$ac_file" : 'X\(//\)[^/]' \| \
+	 X"$ac_file" : 'X\(//\)$' \| \
+	 X"$ac_file" : 'X\(/\)' \| . 2>/dev/null ||
+$as_echo X"$ac_file" |
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)[^/].*/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+  as_dir="$ac_dir"; as_fn_mkdir_p
+  ac_builddir=.
 
+case "$ac_dir" in
+.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
+*)
+  ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'`
+  # A ".." for each directory in $ac_dir_suffix.
+  ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'`
+  case $ac_top_builddir_sub in
+  "") ac_top_builddir_sub=. ac_top_build_prefix= ;;
+  *)  ac_top_build_prefix=$ac_top_builddir_sub/ ;;
+  esac ;;
+esac
+ac_abs_top_builddir=$ac_pwd
+ac_abs_builddir=$ac_pwd$ac_dir_suffix
+# for backward compatibility:
+ac_top_builddir=$ac_top_build_prefix
 
-    PHP_CC="$CC $C_PIC"
-    PHP_LD="$PHP_LD_SHARED $PHP_LD_XTRAFLAGS"
-  fi
+case $srcdir in
+  .)  # We are building in place.
+    ac_srcdir=.
+    ac_top_srcdir=$ac_top_builddir_sub
+    ac_abs_top_srcdir=$ac_pwd ;;
+  [\\/]* | ?:[\\/]* )  # Absolute name.
+    ac_srcdir=$srcdir$ac_dir_suffix;
+    ac_top_srcdir=$srcdir
+    ac_abs_top_srcdir=$srcdir ;;
+  *) # Relative name.
+    ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix
+    ac_top_srcdir=$ac_top_build_prefix$srcdir
+    ac_abs_top_srcdir=$ac_pwd/$srcdir ;;
+esac
+ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
 
-          echo "$as_me:$LINENO: checking for location of php_config.h" >&5
-echo $ECHO_N "checking for location of php_config.h... $ECHO_C" >&6
-    test -f "$PHP_SRC_DIR/main/php_config.h" && test -f "$PHP_SRC_DIR/main/php_version.h"  && PHP_CONFIG_H="$PHP_SRC_DIR/main/php_config.h"
 
-    test -f "$PHP_SRC_DIR/include/php/main/php_config.h" && PHP_SRC_DIR="$PHP_SRC_DIR/include/php/" && PHP_CONFIG_H="$PHP_SRC_DIR/main/php_config.h"
-    test -f "$PHP_SRC_DIR/include/php5/main/php_config.h" && PHP_SRC_DIR="$PHP_SRC_DIR/include/php5/" && PHP_CONFIG_H="$PHP_SRC_DIR/main/php_config.h"
+  case $ac_mode in
+  :F)
+  #
+  # CONFIG_FILE
+  #
 
-  if test -n "$PHP_CONFIG_H" ; then
-    echo "$as_me:$LINENO: result: $PHP_CONFIG_H" >&5
-echo "${ECHO_T}$PHP_CONFIG_H" >&6
-  else
-    { { echo "$as_me:$LINENO: error:
-!!! Could not find php_config.h and php_version.h in $PHP_SRC_DIR.          !!!
-!!! Has PHP been configured yet?                                      !!!" >&5
-echo "$as_me: error:
-!!! Could not find php_config.h and php_version.h in $PHP_SRC_DIR.          !!!
-!!! Has PHP been configured yet?                                      !!!" >&2;}
-   { (exit 1); exit 1; }; }
-  fi
+  case $INSTALL in
+  [\\/$]* | ?:[\\/]* ) ac_INSTALL=$INSTALL ;;
+  *) ac_INSTALL=$ac_top_build_prefix$INSTALL ;;
+  esac
+_ACEOF
 
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+# If the template does not know about datarootdir, expand it.
+# FIXME: This hack should be removed a few years after 2.60.
+ac_datarootdir_hack=; ac_datarootdir_seen=
+ac_sed_dataroot='
+/datarootdir/ {
+  p
+  q
+}
+/@datadir@/p
+/@docdir@/p
+/@infodir@/p
+/@localedir@/p
+/@mandir@/p'
+case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in
+*datarootdir*) ac_datarootdir_seen=yes;;
+*@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*)
+  { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5
+$as_echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;}
+_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+  ac_datarootdir_hack='
+  s&@datadir@&$datadir&g
+  s&@docdir@&$docdir&g
+  s&@infodir@&$infodir&g
+  s&@localedir@&$localedir&g
+  s&@mandir@&$mandir&g
+  s&\\\${datarootdir}&$datarootdir&g' ;;
+esac
+_ACEOF
 
-        echo "$as_me:$LINENO: checking if we have PHP 5.2.0+" >&5
-echo $ECHO_N "checking if we have PHP 5.2.0+... $ECHO_C" >&6
-  PHP_VERSION=`grep 'PHP_VERSION_ID' $PHP_SRC_DIR/main/php_version.h | cut -d' ' -f3`
-  if test -z "$PHP_VERSION" || test $PHP_VERSION -lt 50200; then
-    { { echo "$as_me:$LINENO: error:
-!!! PHP MapScript now requires PHP 5.2.0 or more recent.              !!!
-!!! Support for PHP3 has been dropped after MapServer version 3.5.    !!!
-!!! Support for PHP4 has been dropped after MapServer version 5.6.    !!!" >&5
-echo "$as_me: error:
-!!! PHP MapScript now requires PHP 5.2.0 or more recent.              !!!
-!!! Support for PHP3 has been dropped after MapServer version 3.5.    !!!
-!!! Support for PHP4 has been dropped after MapServer version 5.6.    !!!" >&2;}
-   { (exit 1); exit 1; }; }
-  else
-     echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6
-  fi
-  echo "$as_me:$LINENO: result: $PHP_VERSION_FLAG" >&5
-echo "${ECHO_T}$PHP_VERSION_FLAG" >&6
+# Neutralize VPATH when `$srcdir' = `.'.
+# Shell code in configure.ac might set extrasub.
+# FIXME: do we really want to maintain this feature?
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+ac_sed_extra="$ac_vpsub
+$extrasub
+_ACEOF
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+:t
+/@[a-zA-Z_][a-zA-Z_0-9]*@/!b
+s|@configure_input@|$ac_sed_conf_input|;t t
+s&@top_builddir@&$ac_top_builddir_sub&;t t
+s&@top_build_prefix@&$ac_top_build_prefix&;t t
+s&@srcdir@&$ac_srcdir&;t t
+s&@abs_srcdir@&$ac_abs_srcdir&;t t
+s&@top_srcdir@&$ac_top_srcdir&;t t
+s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t
+s&@builddir@&$ac_builddir&;t t
+s&@abs_builddir@&$ac_abs_builddir&;t t
+s&@abs_top_builddir@&$ac_abs_top_builddir&;t t
+s&@INSTALL@&$ac_INSTALL&;t t
+$ac_datarootdir_hack
+"
+eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$ac_tmp/subs.awk" \
+  >$ac_tmp/out || as_fn_error $? "could not create $ac_file" "$LINENO" 5
+
+test -z "$ac_datarootdir_hack$ac_datarootdir_seen" &&
+  { ac_out=`sed -n '/\${datarootdir}/p' "$ac_tmp/out"`; test -n "$ac_out"; } &&
+  { ac_out=`sed -n '/^[	 ]*datarootdir[	 ]*:*=/p' \
+      "$ac_tmp/out"`; test -z "$ac_out"; } &&
+  { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir'
+which seems to be undefined.  Please make sure it is defined" >&5
+$as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir'
+which seems to be undefined.  Please make sure it is defined" >&2;}
+
+  rm -f "$ac_tmp/stdin"
+  case $ac_file in
+  -) cat "$ac_tmp/out" && rm -f "$ac_tmp/out";;
+  *) rm -f "$ac_file" && mv "$ac_tmp/out" "$ac_file";;
+  esac \
+  || as_fn_error $? "could not create $ac_file" "$LINENO" 5
+ ;;
 
-          echo "$as_me:$LINENO: checking whether we should use PHP's regex" >&5
-echo $ECHO_N "checking whether we should use PHP's regex... $ECHO_C" >&6
-  if test -n "`grep 'define REGEX 1' $PHP_CONFIG_H`"  ; then
-    echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6
 
-            test -f "$PHP_SRC_DIR/regex/regex_extra.h" && PHP_NO_SOURCE="1"
-        if test -n "$PHP_NO_SOURCE" ; then
-                    USE_PHP_REGEX="-DUSE_PHP_REGEX"
-          PHP_REGEX_INC="-I$PHP_SRC_DIR"
-          PHP_REGEX_OBJ=php_regex.o
-          echo "$as_me:$LINENO: result:         found regex_extra.h - building PHP MapScript with PHP's bundled regex " >&5
-echo "${ECHO_T}        found regex_extra.h - building PHP MapScript with PHP's bundled regex " >&6
-        else
-                    test -f "$PHP_SRC_DIR/ext/ereg/regex/regex.h" && PHP_NO_SOURCE="1"
-          if test -n "$PHP_NO_SOURCE" ; then
-                    USE_PHP_REGEX="-DUSE_PHP_REGEX"
-          PHP_REGEX_INC="-I$PHP_SRC_DIR/ext/ereg/"
-          PHP_REGEX_OBJ=php_regex.o
-          echo "$as_me:$LINENO: result:         found regex.h - building PHP MapScript with PHP's bundled regex " >&5
-echo "${ECHO_T}        found regex.h - building PHP MapScript with PHP's bundled regex " >&6
-          else
-            { { echo "$as_me:$LINENO: error:
-!!! PHP uses its bundled regex library but regex/regex_extra.h (PHP <=5.2) or !!!
-!!! ext/ereg/regex/regex.h (PHP >=5.3) cannot be found.                                  !!!" >&5
-echo "$as_me: error:
-!!! PHP uses its bundled regex library but regex/regex_extra.h (PHP <=5.2) or !!!
-!!! ext/ereg/regex/regex.h (PHP >=5.3) cannot be found.                                  !!!" >&2;}
-   { (exit 1); exit 1; }; }
-          fi
-	fi
+  :C)  { $as_echo "$as_me:${as_lineno-$LINENO}: executing $ac_file commands" >&5
+$as_echo "$as_me: executing $ac_file commands" >&6;}
+ ;;
+  esac
 
-  else
-    echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
-  fi
 
-  PHPMS_MAKEFILE=mapscript/php/Makefile
-  MAKE_PHPMS=php_mapscript
-  MAKE_PHPMS_CLEAN=php_mapscript_clean
+  case $ac_file$ac_mode in
+    "libtool":C)
 
-  PHP_VERSION_FLAG=$PHP_VERSION_FLAG
+    # See if we are running on zsh, and set the options which allow our
+    # commands through without removal of \ escapes.
+    if test -n "${ZSH_VERSION+set}" ; then
+      setopt NO_GLOB_SUBST
+    fi
 
-  PHP_SRC_DIR=$PHP_SRC_DIR
+    cfgfile="${ofile}T"
+    trap "$RM \"$cfgfile\"; exit 1" 1 2 15
+    $RM "$cfgfile"
 
-  PHP_CC=$PHP_CC
+    cat <<_LT_EOF >> "$cfgfile"
+#! $SHELL
 
-  PHP_LD=$PHP_LD
+# `$ECHO "$ofile" | sed 's%^.*/%%'` - Provide generalized library-building support services.
+# Generated automatically by $as_me ($PACKAGE$TIMESTAMP) $VERSION
+# Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`:
+# NOTE: Changes made to this file will be lost: look at ltmain.sh.
+#
+#   Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005,
+#                 2006, 2007, 2008, 2009, 2010, 2011 Free Software
+#                 Foundation, Inc.
+#   Written by Gordon Matzigkeit, 1996
+#
+#   This file is part of GNU Libtool.
+#
+# GNU Libtool is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License as
+# published by the Free Software Foundation; either version 2 of
+# the License, or (at your option) any later version.
+#
+# As a special exception to the GNU General Public License,
+# if you distribute this file as part of a program or library that
+# is built using GNU Libtool, you may include this file under the
+# same distribution terms that you use for the rest of that program.
+#
+# GNU Libtool is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with GNU Libtool; see the file COPYING.  If not, a copy
+# can be downloaded from http://www.gnu.org/licenses/gpl.html, or
+# obtained by writing to the Free Software Foundation, Inc.,
+# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 
-  PHP_REGEX_INC=$PHP_REGEX_INC
 
-  PHP_REGEX_OBJ=$PHP_REGEX_OBJ
+# The names of the tagged configurations supported by this script.
+available_tags="CXX "
 
-  USE_PHP_REGEX=$USE_PHP_REGEX
+# ### BEGIN LIBTOOL CONFIG
 
+# Which release of libtool.m4 was used?
+macro_version=$macro_version
+macro_revision=$macro_revision
 
-  echo "$as_me:$LINENO: result:         PHP/MapScript module configured." >&5
-echo "${ECHO_T}        PHP/MapScript module configured." >&6
-elif test -n "$with_php" -a "$with_php" != "no" ; then
-  { { echo "$as_me:$LINENO: error: Missing or invalid PHP source directory in --with-php=DIR." >&5
-echo "$as_me: error: Missing or invalid PHP source directory in --with-php=DIR." >&2;}
-   { (exit 1); exit 1; }; }
-else
-  echo "$as_me:$LINENO: result:         PHP/MapScript module not configured." >&5
-echo "${ECHO_T}        PHP/MapScript module not configured." >&6
-fi
+# Whether or not to build static libraries.
+build_old_libs=$enable_static
 
-MAKE_PHPMS=$MAKE_PHPMS
+# Whether or not to build shared libraries.
+build_libtool_libs=$enable_shared
 
-MAKE_PHPMS_CLEAN=$MAKE_PHPMS_CLEAN
+# What type of objects to build.
+pic_mode=$pic_mode
 
+# Whether or not to optimize for fast installation.
+fast_install=$enable_fast_install
 
+# Shell to use when invoking shell scripts.
+SHELL=$lt_SHELL
 
-if test "x$LD_SHARED" = "x" ; then
+# An echo program that protects backslashes.
+ECHO=$lt_ECHO
 
-	echo 'void f(){}' > conftest.c
-	if test -z "`${CC} -fPIC -c conftest.c 2>&1`"; then
-	  C_PIC=-fPIC
-	else
-	  C_PIC=
-	fi
-	rm -f conftest*
+# The PATH separator for the build system.
+PATH_SEPARATOR=$lt_PATH_SEPARATOR
 
-	C_PIC=$C_PIC
+# The host system.
+host_alias=$host_alias
+host=$host
+host_os=$host_os
 
+# The build system.
+build_alias=$build_alias
+build=$build
+build_os=$build_os
 
+# A sed program that does not truncate output.
+SED=$lt_SED
 
+# Sed that helps us avoid accidentally triggering echo(1) options like -n.
+Xsed="\$SED -e 1s/^X//"
 
-  echo 'void g(); int main(){ g(); return 0; }' > conftest1.c
+# A grep program that handles long lines.
+GREP=$lt_GREP
 
-  echo '#include <stdio.h>' > conftest2.c
-  echo 'void g(); void g(){printf("");}' >> conftest2.c
-  ${CC} ${C_PIC} -c conftest2.c
-  SO_EXT="so"
-  SO_COMMAND_NAME="-soname"
-  export SO_EXT
-  export SO_COMMAND_NAME
-  LD_SHARED="/bin/true"
-  if test ! -z "`uname -a | grep IRIX`" ; then
-    IRIX_ALL=-all
-  else
-    IRIX_ALL=
-  fi
+# An ERE matcher.
+EGREP=$lt_EGREP
 
+# A literal string matcher.
+FGREP=$lt_FGREP
 
-# Check whether --with-ld-shared or --without-ld-shared was given.
-if test "${with_ld_shared+set}" = set; then
-  withval="$with_ld_shared"
+# A BSD- or MS-compatible name lister.
+NM=$lt_NM
 
-fi;
+# Whether we need soft or hard links.
+LN_S=$lt_LN_S
 
-      if test "$with_ld_shared" != "" -a "$with_ld_shared" != "yes"; then
-    if test "$with_ld_shared" = "no" ; then
-      echo "$as_me:$LINENO: result: user disabled shared library support." >&5
-echo "${ECHO_T}user disabled shared library support." >&6
-    else
-      echo "$as_me:$LINENO: result: using user supplied .so link command ... $with_ld_shared" >&5
-echo "${ECHO_T}using user supplied .so link command ... $with_ld_shared" >&6
-    fi
-    LD_SHARED="$with_ld_shared"
-  fi
+# What is the maximum length of a command?
+max_cmd_len=$max_cmd_len
 
-    if test ! -z "`uname -a | grep CYGWIN`" \
-        -a "$LD_SHARED" = "/bin/true" ; then
-    if test -z "`gcc -shared conftest2.o -o libconftest.dll`" ; then
-      if test -z "`${CC} conftest1.c -L./ -lconftest -o conftest1 2>&1`"; then
-        LD_LIBRARY_PATH_OLD="$LD_LIBRARY_PATH"
-        if test -z "$LD_LIBRARY_PATH" ; then
-          LD_LIBRARY_PATH="`pwd`"
-        else
-          LD_LIBRARY_PATH="`pwd`:$LD_LIBRARY_PATH"
-        fi
-        export LD_LIBRARY_PATH
-        if test -z "`./conftest1 2>&1`" ; then
-          echo "checking for Cygwin gcc -shared ... yes"
-          LD_SHARED="c++ -shared"
-          SO_EXT="dll"
-        fi
-        LD_LIBRARY_PATH="$LD_LIBRARY_PATH_OLD"
-      fi
-    fi
-  fi
+# Object file suffix (normally "o").
+objext=$ac_objext
 
+# Executable file suffix (normally "").
+exeext=$exeext
 
-    if test ! -z "`uname | grep Darwin`" \
-          -a "$LD_SHARED" = "/bin/true" ; then
-    if test -z "`${CXX} -dynamiclib conftest2.o -o libconftest.so 2>&1`" ; then
-      ${CC} -c conftest1.c
-      if test -z "`${CXX} conftest1.o libconftest.so -o conftest1 2>&1`"; then
-        DYLD_LIBRARY_PATH_OLD="$DYLD_LIBRARY_PATH"
-        if test -z "$DYLD_LIBRARY_PATH" ; then
-          DYLD_LIBRARY_PATH="`pwd`"
-        else
-          DYLD_LIBRARY_PATH="`pwd`:$DYLD_LIBRARY_PATH"
-        fi
-        export DYLD_LIBRARY_PATH
-        if test -z "`./conftest1 2>&1`" ; then
-          echo "checking for ${CXX} -dynamiclib ... yes"
-          LD_SHARED="${CXX} -dynamiclib -single_module -flat_namespace -undefined suppress"
-	  SO_EXT=dylib
-          SO_COMMAND_NAME='-dylib_install_name'
-        fi
-        DYLD_LIBRARY_PATH="$DYLD_LIBRARY_PATH_OLD"
-      fi
-      rm -f conftest1.o
-    fi
-  fi
+# whether the shell understands "unset".
+lt_unset=$lt_unset
 
-  if test "$LD_SHARED" = "/bin/true" \
-	-a -z "`${CXX} -shared $IRIX_ALL conftest2.o -o libconftest.so 2>&1|grep -v WARNING`" ; then
-    if test -z "`${CC} conftest1.c libconftest.so -o conftest1 2>&1`"; then
-      LD_LIBRARY_PATH_OLD="$LD_LIBRARY_PATH"
-      if test -z "$LD_LIBRARY_PATH" ; then
-        LD_LIBRARY_PATH="`pwd`"
-      else
-        LD_LIBRARY_PATH="`pwd`:$LD_LIBRARY_PATH"
-      fi
-      export LD_LIBRARY_PATH
-      if test -z "`./conftest1 2>&1`" ; then
-        echo "checking for ${CXX} -shared ... yes"
-        LD_SHARED="${CXX} -shared $IRIX_ALL"
-      else
-        echo "checking for ${CXX} -shared ... no(3)"
-      fi
-      LD_LIBRARY_PATH="$LD_LIBRARY_PATH_OLD"
-    else
-      echo "checking for ${CXX} -shared ... no(2)"
-    fi
-  else
-    if test "$LD_SHARED" = "/bin/true" ; then
-      echo "checking for ${CXX} -shared ... no(1)"
-    fi
-  fi
+# turn spaces into newlines.
+SP2NL=$lt_lt_SP2NL
 
-  if test "$LD_SHARED" = "/bin/true" \
-          -a -z "`ld -shared conftest2.o -o libconftest.so 2>&1`" ; then
-    if test -z "`${CC} conftest1.c libconftest.so -o conftest1 2>&1`"; then
-      LD_LIBRARY_PATH_OLD="$LD_LIBRARY_PATH"
-      if test -z "$LD_LIBRARY_PATH" ; then
-        LD_LIBRARY_PATH="`pwd`"
-      else
-        LD_LIBRARY_PATH="`pwd`:$LD_LIBRARY_PATH"
-      fi
-      export LD_LIBRARY_PATH
-      if test -z "`./conftest1 2>&1`" ; then
-        echo "checking for ld -shared ... yes"
-        LD_SHARED="ld -shared"
-      fi
-      LD_LIBRARY_PATH="$LD_LIBRARY_PATH_OLD"
-    fi
-  fi
+# turn newlines into spaces.
+NL2SP=$lt_lt_NL2SP
 
-  if test "$LD_SHARED" = "/bin/true" ; then
-    echo "checking for ld -shared ... no"
-    if test ! -x /bin/true ; then
-      LD_SHARED=/usr/bin/true
-    fi
-  fi
-  if test "$LD_SHARED" = "no" ; then
-    if test -x /bin/true ; then
-      LD_SHARED=/bin/true
-    else
-      LD_SHARED=/usr/bin/true
-    fi
-  fi
+# convert \$build file names to \$host format.
+to_host_file_cmd=$lt_cv_to_host_file_cmd
 
-  rm -f conftest* libconftest*
+# convert \$build files to toolchain format.
+to_tool_file_cmd=$lt_cv_to_tool_file_cmd
 
-  LD_SHARED=$LD_SHARED
+# An object symbol dumper.
+OBJDUMP=$lt_OBJDUMP
 
-  SO_EXT=$SO_EXT
+# Method to check whether dependent libraries are shared objects.
+deplibs_check_method=$lt_deplibs_check_method
 
-  SO_COMMAND_NAME=$SO_COMMAND_NAME
+# Command to use when deplibs_check_method = "file_magic".
+file_magic_cmd=$lt_file_magic_cmd
 
+# How to find potential files when deplibs_check_method = "file_magic".
+file_magic_glob=$lt_file_magic_glob
 
-fi
+# Find potential files using nocaseglob when deplibs_check_method = "file_magic".
+want_nocaseglob=$lt_want_nocaseglob
 
+# DLL creation program.
+DLLTOOL=$lt_DLLTOOL
 
+# Command to associate shared and link libraries.
+sharedlib_from_linklib_cmd=$lt_sharedlib_from_linklib_cmd
 
-# Check whether --with-apxs or --without-apxs was given.
-if test "${with_apxs+set}" = set; then
-  withval="$with_apxs"
+# The archiver.
+AR=$lt_AR
 
-fi;
+# Flags to create an archive.
+AR_FLAGS=$lt_AR_FLAGS
 
-if test -n "$with_apxs" -a "$with_apxs" != "no" ; then
+# How to feed a file listing to the archiver.
+archiver_list_spec=$lt_archiver_list_spec
 
-  { { echo "$as_me:$LINENO: error:
-!!! The current version of PHP MapScript requires PHP4 configured as  !!!
-!!! a CGI and cannot be used with PHP4 configured as an Apache module,!!!
-!!! so you cannot use the --with-apxs option.                         !!!
-!!! See: http://mapserver.gis.umn.edu/cgi-bin/wiki.pl?PHPMapScriptCGI !!!" >&5
-echo "$as_me: error:
-!!! The current version of PHP MapScript requires PHP4 configured as  !!!
-!!! a CGI and cannot be used with PHP4 configured as an Apache module,!!!
-!!! so you cannot use the --with-apxs option.                         !!!
-!!! See: http://mapserver.gis.umn.edu/cgi-bin/wiki.pl?PHPMapScriptCGI !!!" >&2;}
-   { (exit 1); exit 1; }; }
+# A symbol stripping program.
+STRIP=$lt_STRIP
 
+# Commands used to install an old-style archive.
+RANLIB=$lt_RANLIB
+old_postinstall_cmds=$lt_old_postinstall_cmds
+old_postuninstall_cmds=$lt_old_postuninstall_cmds
 
-  echo "$as_me:$LINENO: checking for location of Apache headers using apxs" >&5
-echo $ECHO_N "checking for location of Apache headers using apxs... $ECHO_C" >&6
-  if test -z "$MAKE_PHPMS" ; then
-    { { echo "$as_me:$LINENO: error: --with-apxs applies only if --with-php is used." >&5
-echo "$as_me: error: --with-apxs applies only if --with-php is used." >&2;}
-   { (exit 1); exit 1; }; }
+# Whether to use a lock for old archive extraction.
+lock_old_archive_extraction=$lock_old_archive_extraction
 
-  elif test "$with_apxs" = "yes" ; then
-    APXS=apxs
-  else
-    APXS="$with_apxs"
-  fi
+# A C compiler.
+LTCC=$lt_CC
 
-  APACHE_INC=-I`$APXS -q INCLUDEDIR`
-  echo "$as_me:$LINENO: result: $APACHE_INC" >&5
-echo "${ECHO_T}$APACHE_INC" >&6
+# LTCC compiler flags.
+LTCFLAGS=$lt_CFLAGS
 
-    fi
+# Take the output of nm and produce a listing of raw symbols and C names.
+global_symbol_pipe=$lt_lt_cv_sys_global_symbol_pipe
 
+# Transform the output of nm in a proper C declaration.
+global_symbol_to_cdecl=$lt_lt_cv_sys_global_symbol_to_cdecl
 
+# Transform the output of nm in a C name address pair.
+global_symbol_to_c_name_address=$lt_lt_cv_sys_global_symbol_to_c_name_address
 
+# Transform the output of nm in a C name address pair when lib prefix is needed.
+global_symbol_to_c_name_address_lib_prefix=$lt_lt_cv_sys_global_symbol_to_c_name_address_lib_prefix
 
-# Check whether --with-apache or --without-apache was given.
-if test "${with_apache+set}" = set; then
-  withval="$with_apache"
+# Specify filename containing input files for \$NM.
+nm_file_list_spec=$lt_nm_file_list_spec
 
-fi;
+# The root where to search for dependent libraries,and in which our libraries should be installed.
+lt_sysroot=$lt_sysroot
 
-if test -n "$with_apache" -a "$with_apache" != "no" ; then
+# The name of the directory that contains temporary libtool files.
+objdir=$objdir
 
-  { { echo "$as_me:$LINENO: error:
-!!! The current version of PHP MapScript requires PHP4 configured as  !!!
-!!! a CGI and cannot be used with PHP4 configured as an Apache module,!!!
-!!! so you cannot use the --with-apache option.                       !!!
-!!! See: http://mapserver.gis.umn.edu/cgi-bin/wiki.pl?PHPMapScriptCGI !!!" >&5
-echo "$as_me: error:
-!!! The current version of PHP MapScript requires PHP4 configured as  !!!
-!!! a CGI and cannot be used with PHP4 configured as an Apache module,!!!
-!!! so you cannot use the --with-apache option.                       !!!
-!!! See: http://mapserver.gis.umn.edu/cgi-bin/wiki.pl?PHPMapScriptCGI !!!" >&2;}
-   { (exit 1); exit 1; }; }
+# Used to examine libraries when file_magic_cmd begins with "file".
+MAGIC_CMD=$MAGIC_CMD
 
-  echo "$as_me:$LINENO: checking for location of Apache headers" >&5
-echo $ECHO_N "checking for location of Apache headers... $ECHO_C" >&6
-  if test -z "$MAKE_PHPMS" ; then
-    { { echo "$as_me:$LINENO: error: --with-apache applies only if --with-php is used." >&5
-echo "$as_me: error: --with-apache applies only if --with-php is used." >&2;}
-   { (exit 1); exit 1; }; }
-  fi
+# Must we lock files when doing compilation?
+need_locks=$lt_need_locks
 
+# Manifest tool.
+MANIFEST_TOOL=$lt_MANIFEST_TOOL
 
-  if test -z "$with_apache" || echo "$with_apache" | grep '^/' >/dev/null ; then
-    APACHE_DIR="$with_apache"
-  else
-    APACHE_DIR="`pwd`/$with_apache"
-  fi
+# Tool to manipulate archived DWARF debug symbol files on Mac OS X.
+DSYMUTIL=$lt_DSYMUTIL
 
-  test -f $APACHE_DIR/httpd.h && APACHE_INC_DIR="$APACHE_DIR"
-  test -f $APACHE_DIR/include/httpd.h && APACHE_INC_DIR="$APACHE_DIR/include"
-  test -f $APACHE_DIR/src/include/httpd.h && APACHE_INC_DIR="$APACHE_DIR/src/include"
-  if test -n "$APACHE_INC_DIR" ; then
-    APACHE_INC="-I$APACHE_INC_DIR $APACHE_INC"
-    echo "$as_me:$LINENO: result: \"-I$APACHE_INC_DIR\"" >&5
-echo "${ECHO_T}\"-I$APACHE_INC_DIR\"" >&6
-  else
-    { { echo "$as_me:$LINENO: error: \"Could not find httpd.h in $APACHE_DIR.\"" >&5
-echo "$as_me: error: \"Could not find httpd.h in $APACHE_DIR.\"" >&2;}
-   { (exit 1); exit 1; }; }
-  fi
-fi
+# Tool to change global to local symbols on Mac OS X.
+NMEDIT=$lt_NMEDIT
 
-APACHE_INC=$APACHE_INC
+# Tool to manipulate fat objects and archives on Mac OS X.
+LIPO=$lt_LIPO
 
+# ldd/readelf like tool for Mach-O binaries on Mac OS X.
+OTOOL=$lt_OTOOL
 
+# ldd/readelf like tool for 64 bit Mach-O binaries on Mac OS X 10.4.
+OTOOL64=$lt_OTOOL64
 
+# Old archive suffix (normally "a").
+libext=$libext
 
-echo "$as_me:$LINENO: checking if --enable-runpath requested" >&5
-echo $ECHO_N "checking if --enable-runpath requested... $ECHO_C" >&6
-# Check whether --enable-runpath or --disable-runpath was given.
-if test "${enable_runpath+set}" = set; then
-  enableval="$enable_runpath"
+# Shared library suffix (normally ".so").
+shrext_cmds=$lt_shrext_cmds
 
-fi;
+# The commands to extract the exported symbol list from a shared archive.
+extract_expsyms_cmds=$lt_extract_expsyms_cmds
 
-if test "$enable_runpath" != "yes" ; then
-  RPATHS=""
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
-else
-  echo "$as_me:$LINENO: result: yes ($RPATHS)" >&5
-echo "${ECHO_T}yes ($RPATHS)" >&6
-fi
+# Variables whose values should be saved in libtool wrapper scripts and
+# restored at link time.
+variables_saved_for_relink=$lt_variables_saved_for_relink
 
+# Do we need the "lib" prefix for modules?
+need_lib_prefix=$need_lib_prefix
 
-echo "$as_me:$LINENO: checking if --with-java-include-os-name specified" >&5
-echo $ECHO_N "checking if --with-java-include-os-name specified... $ECHO_C" >&6
+# Do we need a version for libraries?
+need_version=$need_version
 
-# Check whether --with-java-include-os-name or --without-java-include-os-name was given.
-if test "${with_java_include_os_name+set}" = set; then
-  withval="$with_java_include_os_name"
+# Library versioning type.
+version_type=$version_type
 
-fi;
-if test -n "${with_java_include_os_name}" ; then
-OS_INCLUDE_DIR="${with_java_include_os_name}"
-echo "$as_me:$LINENO: result: yes ($OS_INCLUDE_DIR)" >&5
-echo "${ECHO_T}yes ($OS_INCLUDE_DIR)" >&6
-else
-OUR_OSNAME=`uname -s`
-case "${OUR_OSNAME}" in
-[Ll]inux) OS_INCLUDE_DIR="linux" ;;
-[sS]olaris*) OS_INCLUDE_DIR="solaris" ;;
-[sS]unOS*) OS_INCLUDE_DIR="solaris" ;;
-[Ww]in*) OS_INCLUDE_DIR="win32" ;;
-*) OS_INCLUDE_DIR="linux" ;;
-esac
-echo "$as_me:$LINENO: result: no, autodetected $OS_INCLUDE_DIR" >&5
-echo "${ECHO_T}no, autodetected $OS_INCLUDE_DIR" >&6
-fi
+# Shared library runtime path variable.
+runpath_var=$runpath_var
 
-OS_INCLUDE_DIR=$OS_INCLUDE_DIR
+# Shared library path variable.
+shlibpath_var=$shlibpath_var
 
+# Is shlibpath searched before the hard-coded library search path?
+shlibpath_overrides_runpath=$shlibpath_overrides_runpath
 
+# Format of library name prefix.
+libname_spec=$lt_libname_spec
 
-ALL_ENABLED=$ALL_ENABLED
+# List of archive names.  First name is the real one, the rest are links.
+# The last name is the one that the linker finds with -lNAME
+library_names_spec=$lt_library_names_spec
 
-ALL_INC=$ALL_INC
+# The coded name of the library, if different from the real name.
+soname_spec=$lt_soname_spec
 
-ALL_LIB=$ALL_LIB
+# Permission mode override for installation of shared libraries.
+install_override_mode=$lt_install_override_mode
 
-ALL_STATIC_LIB=$ALL_STATIC_LIB
+# Command to use after installation of a shared archive.
+postinstall_cmds=$lt_postinstall_cmds
 
-RPATHS=$RPATHS
+# Command to use after uninstallation of a shared archive.
+postuninstall_cmds=$lt_postuninstall_cmds
 
+# Commands used to finish a libtool library installation in a directory.
+finish_cmds=$lt_finish_cmds
 
-                                        ac_config_files="$ac_config_files Makefile $PHPMS_MAKEFILE mapscript/java/Makefile mapscript/csharp/Makefile"
-cat >confcache <<\_ACEOF
-# This file is a shell script that caches the results of configure
-# tests run on this system so they can be shared between configure
-# scripts and configure runs, see configure's option --config-cache.
-# It is not useful on other systems.  If it contains results you don't
-# want to keep, you may remove or edit it.
-#
-# config.status only pays attention to the cache file if you give it
-# the --recheck option to rerun configure.
-#
-# `ac_cv_env_foo' variables (set or unset) will be overridden when
-# loading this file, other *unset* `ac_cv_foo' will be assigned the
-# following values.
+# As "finish_cmds", except a single script fragment to be evaled but
+# not shown.
+finish_eval=$lt_finish_eval
 
-_ACEOF
+# Whether we should hardcode library paths into libraries.
+hardcode_into_libs=$hardcode_into_libs
 
-# The following way of writing the cache mishandles newlines in values,
-# but we know of no workaround that is simple, portable, and efficient.
-# So, don't put newlines in cache variables' values.
-# Ultrix sh set writes to stderr and can't be redirected directly,
-# and sets the high bit in the cache file unless we assign to the vars.
-{
-  (set) 2>&1 |
-    case `(ac_space=' '; set | grep ac_space) 2>&1` in
-    *ac_space=\ *)
-      # `set' does not quote correctly, so add quotes (double-quote
-      # substitution turns \\\\ into \\, and sed turns \\ into \).
-      sed -n \
-	"s/'/'\\\\''/g;
-	  s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p"
-      ;;
-    *)
-      # `set' quotes correctly as required by POSIX, so do not add quotes.
-      sed -n \
-	"s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1=\\2/p"
-      ;;
-    esac;
-} |
-  sed '
-     t clear
-     : clear
-     s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/
-     t end
-     /^ac_cv_env/!s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/
-     : end' >>confcache
-if diff $cache_file confcache >/dev/null 2>&1; then :; else
-  if test -w $cache_file; then
-    test "x$cache_file" != "x/dev/null" && echo "updating cache $cache_file"
-    cat confcache >$cache_file
-  else
-    echo "not updating unwritable cache $cache_file"
-  fi
-fi
-rm -f confcache
+# Compile-time system search path for libraries.
+sys_lib_search_path_spec=$lt_sys_lib_search_path_spec
 
-test "x$prefix" = xNONE && prefix=$ac_default_prefix
-# Let make expand exec_prefix.
-test "x$exec_prefix" = xNONE && exec_prefix='${prefix}'
+# Run-time system search path for libraries.
+sys_lib_dlsearch_path_spec=$lt_sys_lib_dlsearch_path_spec
 
-# VPATH may cause trouble with some makes, so we remove $(srcdir),
-# ${srcdir} and @srcdir@ from VPATH if srcdir is ".", strip leading and
-# trailing colons and then remove the whole line if VPATH becomes empty
-# (actually we leave an empty line to preserve line numbers).
-if test "x$srcdir" = x.; then
-  ac_vpsub='/^[	 ]*VPATH[	 ]*=/{
-s/:*\$(srcdir):*/:/;
-s/:*\${srcdir}:*/:/;
-s/:*@srcdir@:*/:/;
-s/^\([^=]*=[	 ]*\):*/\1/;
-s/:*$//;
-s/^[^=]*=[	 ]*$//;
-}'
-fi
+# Whether dlopen is supported.
+dlopen_support=$enable_dlopen
 
-# Transform confdefs.h into DEFS.
-# Protect against shell expansion while executing Makefile rules.
-# Protect against Makefile macro expansion.
-#
-# If the first sed substitution is executed (which looks for macros that
-# take arguments), then we branch to the quote section.  Otherwise,
-# look for a macro that doesn't take arguments.
-cat >confdef2opt.sed <<\_ACEOF
-t clear
-: clear
-s,^[	 ]*#[	 ]*define[	 ][	 ]*\([^	 (][^	 (]*([^)]*)\)[	 ]*\(.*\),-D\1=\2,g
-t quote
-s,^[	 ]*#[	 ]*define[	 ][	 ]*\([^	 ][^	 ]*\)[	 ]*\(.*\),-D\1=\2,g
-t quote
-d
-: quote
-s,[	 `~#$^&*(){}\\|;'"<>?],\\&,g
-s,\[,\\&,g
-s,\],\\&,g
-s,\$,$$,g
-p
-_ACEOF
-# We use echo to avoid assuming a particular line-breaking character.
-# The extra dot is to prevent the shell from consuming trailing
-# line-breaks from the sub-command output.  A line-break within
-# single-quotes doesn't work because, if this script is created in a
-# platform that uses two characters for line-breaks (e.g., DOS), tr
-# would break.
-ac_LF_and_DOT=`echo; echo .`
-DEFS=`sed -n -f confdef2opt.sed confdefs.h | tr "$ac_LF_and_DOT" ' .'`
-rm -f confdef2opt.sed
+# Whether dlopen of programs is supported.
+dlopen_self=$enable_dlopen_self
 
+# Whether dlopen of statically linked programs is supported.
+dlopen_self_static=$enable_dlopen_self_static
 
-ac_libobjs=
-ac_ltlibobjs=
-for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue
-  # 1. Remove the extension, and $U if already installed.
-  ac_i=`echo "$ac_i" |
-	 sed 's/\$U\././;s/\.o$//;s/\.obj$//'`
-  # 2. Add them.
-  ac_libobjs="$ac_libobjs $ac_i\$U.$ac_objext"
-  ac_ltlibobjs="$ac_ltlibobjs $ac_i"'$U.lo'
-done
-LIBOBJS=$ac_libobjs
+# Commands to strip libraries.
+old_striplib=$lt_old_striplib
+striplib=$lt_striplib
 
-LTLIBOBJS=$ac_ltlibobjs
 
+# The linker used to build libraries.
+LD=$lt_LD
 
+# How to create reloadable object files.
+reload_flag=$lt_reload_flag
+reload_cmds=$lt_reload_cmds
 
-: ${CONFIG_STATUS=./config.status}
-ac_clean_files_save=$ac_clean_files
-ac_clean_files="$ac_clean_files $CONFIG_STATUS"
-{ echo "$as_me:$LINENO: creating $CONFIG_STATUS" >&5
-echo "$as_me: creating $CONFIG_STATUS" >&6;}
-cat >$CONFIG_STATUS <<_ACEOF
-#! $SHELL
-# Generated by $as_me.
-# Run this file to recreate the current configuration.
-# Compiler output produced by configure, useful for debugging
-# configure, is in config.log if it exists.
+# Commands used to build an old-style archive.
+old_archive_cmds=$lt_old_archive_cmds
 
-debug=false
-ac_cs_recheck=false
-ac_cs_silent=false
-SHELL=\${CONFIG_SHELL-$SHELL}
-_ACEOF
+# A language specific compiler.
+CC=$lt_compiler
+
+# Is the compiler the GNU compiler?
+with_gcc=$GCC
+
+# Compiler flag to turn off builtin functions.
+no_builtin_flag=$lt_lt_prog_compiler_no_builtin_flag
+
+# Additional compiler flags for building library objects.
+pic_flag=$lt_lt_prog_compiler_pic
+
+# How to pass a linker flag through the compiler.
+wl=$lt_lt_prog_compiler_wl
+
+# Compiler flag to prevent dynamic linking.
+link_static_flag=$lt_lt_prog_compiler_static
+
+# Does compiler simultaneously support -c and -o options?
+compiler_c_o=$lt_lt_cv_prog_compiler_c_o
 
-cat >>$CONFIG_STATUS <<\_ACEOF
-## --------------------- ##
-## M4sh Initialization.  ##
-## --------------------- ##
+# Whether or not to add -lc for building shared libraries.
+build_libtool_need_lc=$archive_cmds_need_lc
 
-# Be Bourne compatible
-if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
-  emulate sh
-  NULLCMD=:
-  # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
-  # is contrary to our usage.  Disable this feature.
-  alias -g '${1+"$@"}'='"$@"'
-elif test -n "${BASH_VERSION+set}" && (set -o posix) >/dev/null 2>&1; then
-  set -o posix
-fi
-DUALCASE=1; export DUALCASE # for MKS sh
+# Whether or not to disallow shared libs when runtime libs are static.
+allow_libtool_libs_with_static_runtimes=$enable_shared_with_static_runtimes
 
-# Support unset when possible.
-if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then
-  as_unset=unset
-else
-  as_unset=false
-fi
+# Compiler flag to allow reflexive dlopens.
+export_dynamic_flag_spec=$lt_export_dynamic_flag_spec
 
+# Compiler flag to generate shared objects directly from archives.
+whole_archive_flag_spec=$lt_whole_archive_flag_spec
 
-# Work around bugs in pre-3.0 UWIN ksh.
-$as_unset ENV MAIL MAILPATH
-PS1='$ '
-PS2='> '
-PS4='+ '
+# Whether the compiler copes with passing no objects directly.
+compiler_needs_object=$lt_compiler_needs_object
 
-# NLS nuisances.
-for as_var in \
-  LANG LANGUAGE LC_ADDRESS LC_ALL LC_COLLATE LC_CTYPE LC_IDENTIFICATION \
-  LC_MEASUREMENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER \
-  LC_TELEPHONE LC_TIME
-do
-  if (set +x; test -z "`(eval $as_var=C; export $as_var) 2>&1`"); then
-    eval $as_var=C; export $as_var
-  else
-    $as_unset $as_var
-  fi
-done
+# Create an old-style archive from a shared archive.
+old_archive_from_new_cmds=$lt_old_archive_from_new_cmds
 
-# Required to use basename.
-if expr a : '\(a\)' >/dev/null 2>&1; then
-  as_expr=expr
-else
-  as_expr=false
-fi
+# Create a temporary old-style archive to link instead of a shared archive.
+old_archive_from_expsyms_cmds=$lt_old_archive_from_expsyms_cmds
 
-if (basename /) >/dev/null 2>&1 && test "X`basename / 2>&1`" = "X/"; then
-  as_basename=basename
-else
-  as_basename=false
-fi
+# Commands used to build a shared archive.
+archive_cmds=$lt_archive_cmds
+archive_expsym_cmds=$lt_archive_expsym_cmds
 
+# Commands used to build a loadable module if different from building
+# a shared archive.
+module_cmds=$lt_module_cmds
+module_expsym_cmds=$lt_module_expsym_cmds
 
-# Name of the executable.
-as_me=`$as_basename "$0" ||
-$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
-	 X"$0" : 'X\(//\)$' \| \
-	 X"$0" : 'X\(/\)$' \| \
-	 .     : '\(.\)' 2>/dev/null ||
-echo X/"$0" |
-    sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/; q; }
-  	  /^X\/\(\/\/\)$/{ s//\1/; q; }
-  	  /^X\/\(\/\).*/{ s//\1/; q; }
-  	  s/.*/./; q'`
+# Whether we are building with GNU ld or not.
+with_gnu_ld=$lt_with_gnu_ld
 
+# Flag that allows shared libraries with undefined symbols to be built.
+allow_undefined_flag=$lt_allow_undefined_flag
 
-# PATH needs CR, and LINENO needs CR and PATH.
-# Avoid depending upon Character Ranges.
-as_cr_letters='abcdefghijklmnopqrstuvwxyz'
-as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
-as_cr_Letters=$as_cr_letters$as_cr_LETTERS
-as_cr_digits='0123456789'
-as_cr_alnum=$as_cr_Letters$as_cr_digits
+# Flag that enforces no undefined symbols.
+no_undefined_flag=$lt_no_undefined_flag
 
-# The user is always right.
-if test "${PATH_SEPARATOR+set}" != set; then
-  echo "#! /bin/sh" >conf$$.sh
-  echo  "exit 0"   >>conf$$.sh
-  chmod +x conf$$.sh
-  if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then
-    PATH_SEPARATOR=';'
-  else
-    PATH_SEPARATOR=:
-  fi
-  rm -f conf$$.sh
-fi
+# Flag to hardcode \$libdir into a binary during linking.
+# This must work even if \$libdir does not exist
+hardcode_libdir_flag_spec=$lt_hardcode_libdir_flag_spec
 
+# Whether we need a single "-rpath" flag with a separated argument.
+hardcode_libdir_separator=$lt_hardcode_libdir_separator
 
-  as_lineno_1=$LINENO
-  as_lineno_2=$LINENO
-  as_lineno_3=`(expr $as_lineno_1 + 1) 2>/dev/null`
-  test "x$as_lineno_1" != "x$as_lineno_2" &&
-  test "x$as_lineno_3"  = "x$as_lineno_2"  || {
-  # Find who we are.  Look in the path if we contain no path at all
-  # relative or not.
-  case $0 in
-    *[\\/]* ) as_myself=$0 ;;
-    *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
-done
+# Set to "yes" if using DIR/libNAME\${shared_ext} during linking hardcodes
+# DIR into the resulting binary.
+hardcode_direct=$hardcode_direct
 
-       ;;
-  esac
-  # We did not find ourselves, most probably we were run as `sh COMMAND'
-  # in which case we are not to be found in the path.
-  if test "x$as_myself" = x; then
-    as_myself=$0
-  fi
-  if test ! -f "$as_myself"; then
-    { { echo "$as_me:$LINENO: error: cannot find myself; rerun with an absolute path" >&5
-echo "$as_me: error: cannot find myself; rerun with an absolute path" >&2;}
-   { (exit 1); exit 1; }; }
-  fi
-  case $CONFIG_SHELL in
-  '')
-    as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  for as_base in sh bash ksh sh5; do
-	 case $as_dir in
-	 /*)
-	   if ("$as_dir/$as_base" -c '
-  as_lineno_1=$LINENO
-  as_lineno_2=$LINENO
-  as_lineno_3=`(expr $as_lineno_1 + 1) 2>/dev/null`
-  test "x$as_lineno_1" != "x$as_lineno_2" &&
-  test "x$as_lineno_3"  = "x$as_lineno_2" ') 2>/dev/null; then
-	     $as_unset BASH_ENV || test "${BASH_ENV+set}" != set || { BASH_ENV=; export BASH_ENV; }
-	     $as_unset ENV || test "${ENV+set}" != set || { ENV=; export ENV; }
-	     CONFIG_SHELL=$as_dir/$as_base
-	     export CONFIG_SHELL
-	     exec "$CONFIG_SHELL" "$0" ${1+"$@"}
-	   fi;;
-	 esac
-       done
-done
-;;
-  esac
+# Set to "yes" if using DIR/libNAME\${shared_ext} during linking hardcodes
+# DIR into the resulting binary and the resulting library dependency is
+# "absolute",i.e impossible to change by setting \${shlibpath_var} if the
+# library is relocated.
+hardcode_direct_absolute=$hardcode_direct_absolute
 
-  # Create $as_me.lineno as a copy of $as_myself, but with $LINENO
-  # uniformly replaced by the line number.  The first 'sed' inserts a
-  # line-number line before each line; the second 'sed' does the real
-  # work.  The second script uses 'N' to pair each line-number line
-  # with the numbered line, and appends trailing '-' during
-  # substitution so that $LINENO is not a special case at line end.
-  # (Raja R Harinath suggested sed '=', and Paul Eggert wrote the
-  # second 'sed' script.  Blame Lee E. McMahon for sed's syntax.  :-)
-  sed '=' <$as_myself |
-    sed '
-      N
-      s,$,-,
-      : loop
-      s,^\(['$as_cr_digits']*\)\(.*\)[$]LINENO\([^'$as_cr_alnum'_]\),\1\2\1\3,
-      t loop
-      s,-$,,
-      s,^['$as_cr_digits']*\n,,
-    ' >$as_me.lineno &&
-  chmod +x $as_me.lineno ||
-    { { echo "$as_me:$LINENO: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&5
-echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2;}
-   { (exit 1); exit 1; }; }
+# Set to "yes" if using the -LDIR flag during linking hardcodes DIR
+# into the resulting binary.
+hardcode_minus_L=$hardcode_minus_L
 
-  # Don't try to exec as it changes $[0], causing all sort of problems
-  # (the dirname of $[0] is not the place where we might find the
-  # original and so on.  Autoconf is especially sensible to this).
-  . ./$as_me.lineno
-  # Exit status is that of the last command.
-  exit
-}
+# Set to "yes" if using SHLIBPATH_VAR=DIR during linking hardcodes DIR
+# into the resulting binary.
+hardcode_shlibpath_var=$hardcode_shlibpath_var
 
+# Set to "yes" if building a shared library automatically hardcodes DIR
+# into the library and all subsequent libraries and executables linked
+# against it.
+hardcode_automatic=$hardcode_automatic
 
-case `echo "testing\c"; echo 1,2,3`,`echo -n testing; echo 1,2,3` in
-  *c*,-n*) ECHO_N= ECHO_C='
-' ECHO_T='	' ;;
-  *c*,*  ) ECHO_N=-n ECHO_C= ECHO_T= ;;
-  *)       ECHO_N= ECHO_C='\c' ECHO_T= ;;
-esac
+# Set to yes if linker adds runtime paths of dependent libraries
+# to runtime path list.
+inherit_rpath=$inherit_rpath
 
-if expr a : '\(a\)' >/dev/null 2>&1; then
-  as_expr=expr
-else
-  as_expr=false
-fi
+# Whether libtool must link a program against all its dependency libraries.
+link_all_deplibs=$link_all_deplibs
 
-rm -f conf$$ conf$$.exe conf$$.file
-echo >conf$$.file
-if ln -s conf$$.file conf$$ 2>/dev/null; then
-  # We could just check for DJGPP; but this test a) works b) is more generic
-  # and c) will remain valid once DJGPP supports symlinks (DJGPP 2.04).
-  if test -f conf$$.exe; then
-    # Don't use ln at all; we don't have any links
-    as_ln_s='cp -p'
-  else
-    as_ln_s='ln -s'
-  fi
-elif ln conf$$.file conf$$ 2>/dev/null; then
-  as_ln_s=ln
-else
-  as_ln_s='cp -p'
-fi
-rm -f conf$$ conf$$.exe conf$$.file
+# Set to "yes" if exported symbols are required.
+always_export_symbols=$always_export_symbols
 
-if mkdir -p . 2>/dev/null; then
-  as_mkdir_p=:
-else
-  test -d ./-p && rmdir ./-p
-  as_mkdir_p=false
-fi
+# The commands to list exported symbols.
+export_symbols_cmds=$lt_export_symbols_cmds
 
-as_executable_p="test -f"
+# Symbols that should not be listed in the preloaded symbols.
+exclude_expsyms=$lt_exclude_expsyms
 
-# Sed expression to map a string onto a valid CPP name.
-as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
+# Symbols that must always be exported.
+include_expsyms=$lt_include_expsyms
 
-# Sed expression to map a string onto a valid variable name.
-as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
+# Commands necessary for linking programs (against libraries) with templates.
+prelink_cmds=$lt_prelink_cmds
 
+# Commands necessary for finishing linking programs.
+postlink_cmds=$lt_postlink_cmds
 
-# IFS
-# We need space, tab and new line, in precisely that order.
-as_nl='
-'
-IFS=" 	$as_nl"
+# Specify filename containing input files.
+file_list_spec=$lt_file_list_spec
 
-# CDPATH.
-$as_unset CDPATH
+# How to hardcode a shared library path into an executable.
+hardcode_action=$hardcode_action
 
-exec 6>&1
+# The directories searched by this compiler when creating a shared library.
+compiler_lib_search_dirs=$lt_compiler_lib_search_dirs
 
-# Open the log real soon, to keep \$[0] and so on meaningful, and to
-# report actual input values of CONFIG_FILES etc. instead of their
-# values after options handling.  Logging --version etc. is OK.
-exec 5>>config.log
-{
-  echo
-  sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX
-## Running $as_me. ##
-_ASBOX
-} >&5
-cat >&5 <<_CSEOF
+# Dependencies to place before and after the objects being linked to
+# create a shared library.
+predep_objects=$lt_predep_objects
+postdep_objects=$lt_postdep_objects
+predeps=$lt_predeps
+postdeps=$lt_postdeps
 
-This file was extended by $as_me, which was
-generated by GNU Autoconf 2.59.  Invocation command line was
+# The library search path used internally by the compiler when linking
+# a shared library.
+compiler_lib_search_path=$lt_compiler_lib_search_path
 
-  CONFIG_FILES    = $CONFIG_FILES
-  CONFIG_HEADERS  = $CONFIG_HEADERS
-  CONFIG_LINKS    = $CONFIG_LINKS
-  CONFIG_COMMANDS = $CONFIG_COMMANDS
-  $ $0 $@
+# ### END LIBTOOL CONFIG
 
-_CSEOF
-echo "on `(hostname || uname -n) 2>/dev/null | sed 1q`" >&5
-echo >&5
-_ACEOF
+_LT_EOF
 
-# Files that config.status was made for.
-if test -n "$ac_config_files"; then
-  echo "config_files=\"$ac_config_files\"" >>$CONFIG_STATUS
+  case $host_os in
+  aix3*)
+    cat <<\_LT_EOF >> "$cfgfile"
+# AIX sometimes has problems with the GCC collect2 program.  For some
+# reason, if we set the COLLECT_NAMES environment variable, the problems
+# vanish in a puff of smoke.
+if test "X${COLLECT_NAMES+set}" != Xset; then
+  COLLECT_NAMES=
+  export COLLECT_NAMES
 fi
+_LT_EOF
+    ;;
+  esac
+
+
+ltmain="$ac_aux_dir/ltmain.sh"
+
+
+  # We use sed instead of cat because bash on DJGPP gets confused if
+  # if finds mixed CR/LF and LF-only lines.  Since sed operates in
+  # text mode, it properly converts lines to CR/LF.  This bash problem
+  # is reportedly fixed, but why not run on old versions too?
+  sed '$q' "$ltmain" >> "$cfgfile" \
+     || (rm -f "$cfgfile"; exit 1)
+
+  if test x"$xsi_shell" = xyes; then
+  sed -e '/^func_dirname ()$/,/^} # func_dirname /c\
+func_dirname ()\
+{\
+\    case ${1} in\
+\      */*) func_dirname_result="${1%/*}${2}" ;;\
+\      *  ) func_dirname_result="${3}" ;;\
+\    esac\
+} # Extended-shell func_dirname implementation' "$cfgfile" > $cfgfile.tmp \
+  && mv -f "$cfgfile.tmp" "$cfgfile" \
+    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
+test 0 -eq $? || _lt_function_replace_fail=:
+
+
+  sed -e '/^func_basename ()$/,/^} # func_basename /c\
+func_basename ()\
+{\
+\    func_basename_result="${1##*/}"\
+} # Extended-shell func_basename implementation' "$cfgfile" > $cfgfile.tmp \
+  && mv -f "$cfgfile.tmp" "$cfgfile" \
+    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
+test 0 -eq $? || _lt_function_replace_fail=:
+
+
+  sed -e '/^func_dirname_and_basename ()$/,/^} # func_dirname_and_basename /c\
+func_dirname_and_basename ()\
+{\
+\    case ${1} in\
+\      */*) func_dirname_result="${1%/*}${2}" ;;\
+\      *  ) func_dirname_result="${3}" ;;\
+\    esac\
+\    func_basename_result="${1##*/}"\
+} # Extended-shell func_dirname_and_basename implementation' "$cfgfile" > $cfgfile.tmp \
+  && mv -f "$cfgfile.tmp" "$cfgfile" \
+    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
+test 0 -eq $? || _lt_function_replace_fail=:
+
+
+  sed -e '/^func_stripname ()$/,/^} # func_stripname /c\
+func_stripname ()\
+{\
+\    # pdksh 5.2.14 does not do ${X%$Y} correctly if both X and Y are\
+\    # positional parameters, so assign one to ordinary parameter first.\
+\    func_stripname_result=${3}\
+\    func_stripname_result=${func_stripname_result#"${1}"}\
+\    func_stripname_result=${func_stripname_result%"${2}"}\
+} # Extended-shell func_stripname implementation' "$cfgfile" > $cfgfile.tmp \
+  && mv -f "$cfgfile.tmp" "$cfgfile" \
+    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
+test 0 -eq $? || _lt_function_replace_fail=:
+
+
+  sed -e '/^func_split_long_opt ()$/,/^} # func_split_long_opt /c\
+func_split_long_opt ()\
+{\
+\    func_split_long_opt_name=${1%%=*}\
+\    func_split_long_opt_arg=${1#*=}\
+} # Extended-shell func_split_long_opt implementation' "$cfgfile" > $cfgfile.tmp \
+  && mv -f "$cfgfile.tmp" "$cfgfile" \
+    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
+test 0 -eq $? || _lt_function_replace_fail=:
+
+
+  sed -e '/^func_split_short_opt ()$/,/^} # func_split_short_opt /c\
+func_split_short_opt ()\
+{\
+\    func_split_short_opt_arg=${1#??}\
+\    func_split_short_opt_name=${1%"$func_split_short_opt_arg"}\
+} # Extended-shell func_split_short_opt implementation' "$cfgfile" > $cfgfile.tmp \
+  && mv -f "$cfgfile.tmp" "$cfgfile" \
+    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
+test 0 -eq $? || _lt_function_replace_fail=:
+
+
+  sed -e '/^func_lo2o ()$/,/^} # func_lo2o /c\
+func_lo2o ()\
+{\
+\    case ${1} in\
+\      *.lo) func_lo2o_result=${1%.lo}.${objext} ;;\
+\      *)    func_lo2o_result=${1} ;;\
+\    esac\
+} # Extended-shell func_lo2o implementation' "$cfgfile" > $cfgfile.tmp \
+  && mv -f "$cfgfile.tmp" "$cfgfile" \
+    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
+test 0 -eq $? || _lt_function_replace_fail=:
+
+
+  sed -e '/^func_xform ()$/,/^} # func_xform /c\
+func_xform ()\
+{\
+    func_xform_result=${1%.*}.lo\
+} # Extended-shell func_xform implementation' "$cfgfile" > $cfgfile.tmp \
+  && mv -f "$cfgfile.tmp" "$cfgfile" \
+    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
+test 0 -eq $? || _lt_function_replace_fail=:
+
+
+  sed -e '/^func_arith ()$/,/^} # func_arith /c\
+func_arith ()\
+{\
+    func_arith_result=$(( $* ))\
+} # Extended-shell func_arith implementation' "$cfgfile" > $cfgfile.tmp \
+  && mv -f "$cfgfile.tmp" "$cfgfile" \
+    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
+test 0 -eq $? || _lt_function_replace_fail=:
+
+
+  sed -e '/^func_len ()$/,/^} # func_len /c\
+func_len ()\
+{\
+    func_len_result=${#1}\
+} # Extended-shell func_len implementation' "$cfgfile" > $cfgfile.tmp \
+  && mv -f "$cfgfile.tmp" "$cfgfile" \
+    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
+test 0 -eq $? || _lt_function_replace_fail=:
+
+fi
+
+if test x"$lt_shell_append" = xyes; then
+  sed -e '/^func_append ()$/,/^} # func_append /c\
+func_append ()\
+{\
+    eval "${1}+=\\${2}"\
+} # Extended-shell func_append implementation' "$cfgfile" > $cfgfile.tmp \
+  && mv -f "$cfgfile.tmp" "$cfgfile" \
+    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
+test 0 -eq $? || _lt_function_replace_fail=:
 
-if test -n "$ac_config_headers"; then
-  echo "config_headers=\"$ac_config_headers\"" >>$CONFIG_STATUS
-fi
 
-if test -n "$ac_config_links"; then
-  echo "config_links=\"$ac_config_links\"" >>$CONFIG_STATUS
+  sed -e '/^func_append_quoted ()$/,/^} # func_append_quoted /c\
+func_append_quoted ()\
+{\
+\    func_quote_for_eval "${2}"\
+\    eval "${1}+=\\\\ \\$func_quote_for_eval_result"\
+} # Extended-shell func_append_quoted implementation' "$cfgfile" > $cfgfile.tmp \
+  && mv -f "$cfgfile.tmp" "$cfgfile" \
+    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
+test 0 -eq $? || _lt_function_replace_fail=:
+
+
+  # Save a `func_append' function call where possible by direct use of '+='
+  sed -e 's%func_append \([a-zA-Z_]\{1,\}\) "%\1+="%g' $cfgfile > $cfgfile.tmp \
+    && mv -f "$cfgfile.tmp" "$cfgfile" \
+      || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
+  test 0 -eq $? || _lt_function_replace_fail=:
+else
+  # Save a `func_append' function call even when '+=' is not available
+  sed -e 's%func_append \([a-zA-Z_]\{1,\}\) "%\1="$\1%g' $cfgfile > $cfgfile.tmp \
+    && mv -f "$cfgfile.tmp" "$cfgfile" \
+      || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
+  test 0 -eq $? || _lt_function_replace_fail=:
 fi
 
-if test -n "$ac_config_commands"; then
-  echo "config_commands=\"$ac_config_commands\"" >>$CONFIG_STATUS
+if test x"$_lt_function_replace_fail" = x":"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Unable to substitute extended shell functions in $ofile" >&5
+$as_echo "$as_me: WARNING: Unable to substitute extended shell functions in $ofile" >&2;}
 fi
 
-cat >>$CONFIG_STATUS <<\_ACEOF
 
-ac_cs_usage="\
-\`$as_me' instantiates files from templates according to the
-current configuration.
+   mv -f "$cfgfile" "$ofile" ||
+    (rm -f "$ofile" && cp "$cfgfile" "$ofile" && rm -f "$cfgfile")
+  chmod +x "$ofile"
 
-Usage: $0 [OPTIONS] [FILE]...
 
-  -h, --help       print this help, then exit
-  -V, --version    print version number, then exit
-  -q, --quiet      do not print progress messages
-  -d, --debug      don't remove temporary files
-      --recheck    update $as_me by reconfiguring in the same conditions
-  --file=FILE[:TEMPLATE]
-		   instantiate the configuration file FILE
+    cat <<_LT_EOF >> "$ofile"
 
-Configuration files:
-$config_files
+# ### BEGIN LIBTOOL TAG CONFIG: CXX
 
-Report bugs to <bug-autoconf at gnu.org>."
-_ACEOF
+# The linker used to build libraries.
+LD=$lt_LD_CXX
 
-cat >>$CONFIG_STATUS <<_ACEOF
-ac_cs_version="\\
-config.status
-configured by $0, generated by GNU Autoconf 2.59,
-  with options \\"`echo "$ac_configure_args" | sed 's/[\\""\`\$]/\\\\&/g'`\\"
+# How to create reloadable object files.
+reload_flag=$lt_reload_flag_CXX
+reload_cmds=$lt_reload_cmds_CXX
 
-Copyright (C) 2003 Free Software Foundation, Inc.
-This config.status script is free software; the Free Software Foundation
-gives unlimited permission to copy, distribute and modify it."
-srcdir=$srcdir
-_ACEOF
+# Commands used to build an old-style archive.
+old_archive_cmds=$lt_old_archive_cmds_CXX
 
-cat >>$CONFIG_STATUS <<\_ACEOF
-# If no file are specified by the user, then we need to provide default
-# value.  By we need to know if files were specified by the user.
-ac_need_defaults=:
-while test $# != 0
-do
-  case $1 in
-  --*=*)
-    ac_option=`expr "x$1" : 'x\([^=]*\)='`
-    ac_optarg=`expr "x$1" : 'x[^=]*=\(.*\)'`
-    ac_shift=:
-    ;;
-  -*)
-    ac_option=$1
-    ac_optarg=$2
-    ac_shift=shift
-    ;;
-  *) # This is not an option, so the user has probably given explicit
-     # arguments.
-     ac_option=$1
-     ac_need_defaults=false;;
-  esac
+# A language specific compiler.
+CC=$lt_compiler_CXX
 
-  case $ac_option in
-  # Handling of the options.
-_ACEOF
-cat >>$CONFIG_STATUS <<\_ACEOF
-  -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r)
-    ac_cs_recheck=: ;;
-  --version | --vers* | -V )
-    echo "$ac_cs_version"; exit 0 ;;
-  --he | --h)
-    # Conflict between --help and --header
-    { { echo "$as_me:$LINENO: error: ambiguous option: $1
-Try \`$0 --help' for more information." >&5
-echo "$as_me: error: ambiguous option: $1
-Try \`$0 --help' for more information." >&2;}
-   { (exit 1); exit 1; }; };;
-  --help | --hel | -h )
-    echo "$ac_cs_usage"; exit 0 ;;
-  --debug | --d* | -d )
-    debug=: ;;
-  --file | --fil | --fi | --f )
-    $ac_shift
-    CONFIG_FILES="$CONFIG_FILES $ac_optarg"
-    ac_need_defaults=false;;
-  --header | --heade | --head | --hea )
-    $ac_shift
-    CONFIG_HEADERS="$CONFIG_HEADERS $ac_optarg"
-    ac_need_defaults=false;;
-  -q | -quiet | --quiet | --quie | --qui | --qu | --q \
-  | -silent | --silent | --silen | --sile | --sil | --si | --s)
-    ac_cs_silent=: ;;
+# Is the compiler the GNU compiler?
+with_gcc=$GCC_CXX
 
-  # This is an error.
-  -*) { { echo "$as_me:$LINENO: error: unrecognized option: $1
-Try \`$0 --help' for more information." >&5
-echo "$as_me: error: unrecognized option: $1
-Try \`$0 --help' for more information." >&2;}
-   { (exit 1); exit 1; }; } ;;
+# Compiler flag to turn off builtin functions.
+no_builtin_flag=$lt_lt_prog_compiler_no_builtin_flag_CXX
 
-  *) ac_config_targets="$ac_config_targets $1" ;;
+# Additional compiler flags for building library objects.
+pic_flag=$lt_lt_prog_compiler_pic_CXX
 
-  esac
-  shift
-done
+# How to pass a linker flag through the compiler.
+wl=$lt_lt_prog_compiler_wl_CXX
 
-ac_configure_extra_args=
+# Compiler flag to prevent dynamic linking.
+link_static_flag=$lt_lt_prog_compiler_static_CXX
 
-if $ac_cs_silent; then
-  exec 6>/dev/null
-  ac_configure_extra_args="$ac_configure_extra_args --silent"
-fi
+# Does compiler simultaneously support -c and -o options?
+compiler_c_o=$lt_lt_cv_prog_compiler_c_o_CXX
 
-_ACEOF
-cat >>$CONFIG_STATUS <<_ACEOF
-if \$ac_cs_recheck; then
-  echo "running $SHELL $0 " $ac_configure_args \$ac_configure_extra_args " --no-create --no-recursion" >&6
-  exec $SHELL $0 $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion
-fi
+# Whether or not to add -lc for building shared libraries.
+build_libtool_need_lc=$archive_cmds_need_lc_CXX
 
-_ACEOF
+# Whether or not to disallow shared libs when runtime libs are static.
+allow_libtool_libs_with_static_runtimes=$enable_shared_with_static_runtimes_CXX
 
+# Compiler flag to allow reflexive dlopens.
+export_dynamic_flag_spec=$lt_export_dynamic_flag_spec_CXX
 
+# Compiler flag to generate shared objects directly from archives.
+whole_archive_flag_spec=$lt_whole_archive_flag_spec_CXX
 
+# Whether the compiler copes with passing no objects directly.
+compiler_needs_object=$lt_compiler_needs_object_CXX
 
+# Create an old-style archive from a shared archive.
+old_archive_from_new_cmds=$lt_old_archive_from_new_cmds_CXX
 
-cat >>$CONFIG_STATUS <<\_ACEOF
-for ac_config_target in $ac_config_targets
-do
-  case "$ac_config_target" in
-  # Handling of arguments.
-  "Makefile" ) CONFIG_FILES="$CONFIG_FILES Makefile" ;;
-  "$PHPMS_MAKEFILE" ) CONFIG_FILES="$CONFIG_FILES $PHPMS_MAKEFILE" ;;
-  "mapscript/java/Makefile" ) CONFIG_FILES="$CONFIG_FILES mapscript/java/Makefile" ;;
-  "mapscript/csharp/Makefile" ) CONFIG_FILES="$CONFIG_FILES mapscript/csharp/Makefile" ;;
-  *) { { echo "$as_me:$LINENO: error: invalid argument: $ac_config_target" >&5
-echo "$as_me: error: invalid argument: $ac_config_target" >&2;}
-   { (exit 1); exit 1; }; };;
-  esac
-done
+# Create a temporary old-style archive to link instead of a shared archive.
+old_archive_from_expsyms_cmds=$lt_old_archive_from_expsyms_cmds_CXX
 
-# If the user did not use the arguments to specify the items to instantiate,
-# then the envvar interface is used.  Set only those that are not.
-# We use the long form for the default assignment because of an extremely
-# bizarre bug on SunOS 4.1.3.
-if $ac_need_defaults; then
-  test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files
-fi
+# Commands used to build a shared archive.
+archive_cmds=$lt_archive_cmds_CXX
+archive_expsym_cmds=$lt_archive_expsym_cmds_CXX
 
-# Have a temporary directory for convenience.  Make it in the build tree
-# simply because there is no reason to put it here, and in addition,
-# creating and moving files from /tmp can sometimes cause problems.
-# Create a temporary directory, and hook for its removal unless debugging.
-$debug ||
-{
-  trap 'exit_status=$?; rm -rf $tmp && exit $exit_status' 0
-  trap '{ (exit 1); exit 1; }' 1 2 13 15
-}
+# Commands used to build a loadable module if different from building
+# a shared archive.
+module_cmds=$lt_module_cmds_CXX
+module_expsym_cmds=$lt_module_expsym_cmds_CXX
 
-# Create a (secure) tmp directory for tmp files.
+# Whether we are building with GNU ld or not.
+with_gnu_ld=$lt_with_gnu_ld_CXX
 
-{
-  tmp=`(umask 077 && mktemp -d -q "./confstatXXXXXX") 2>/dev/null` &&
-  test -n "$tmp" && test -d "$tmp"
-}  ||
-{
-  tmp=./confstat$$-$RANDOM
-  (umask 077 && mkdir $tmp)
-} ||
-{
-   echo "$me: cannot create a temporary directory in ." >&2
-   { (exit 1); exit 1; }
-}
+# Flag that allows shared libraries with undefined symbols to be built.
+allow_undefined_flag=$lt_allow_undefined_flag_CXX
 
-_ACEOF
+# Flag that enforces no undefined symbols.
+no_undefined_flag=$lt_no_undefined_flag_CXX
 
-cat >>$CONFIG_STATUS <<_ACEOF
+# Flag to hardcode \$libdir into a binary during linking.
+# This must work even if \$libdir does not exist
+hardcode_libdir_flag_spec=$lt_hardcode_libdir_flag_spec_CXX
 
-#
-# CONFIG_FILES section.
-#
+# Whether we need a single "-rpath" flag with a separated argument.
+hardcode_libdir_separator=$lt_hardcode_libdir_separator_CXX
 
-# No need to generate the scripts if there are no CONFIG_FILES.
-# This happens for instance when ./config.status config.h
-if test -n "\$CONFIG_FILES"; then
-  # Protect against being on the right side of a sed subst in config.status.
-  sed 's/,@/@@/; s/@,/@@/; s/,;t t\$/@;t t/; /@;t t\$/s/[\\\\&,]/\\\\&/g;
-   s/@@/,@/; s/@@/@,/; s/@;t t\$/,;t t/' >\$tmp/subs.sed <<\\CEOF
-s, at SHELL@,$SHELL,;t t
-s, at PATH_SEPARATOR@,$PATH_SEPARATOR,;t t
-s, at PACKAGE_NAME@,$PACKAGE_NAME,;t t
-s, at PACKAGE_TARNAME@,$PACKAGE_TARNAME,;t t
-s, at PACKAGE_VERSION@,$PACKAGE_VERSION,;t t
-s, at PACKAGE_STRING@,$PACKAGE_STRING,;t t
-s, at PACKAGE_BUGREPORT@,$PACKAGE_BUGREPORT,;t t
-s, at exec_prefix@,$exec_prefix,;t t
-s, at prefix@,$prefix,;t t
-s, at program_transform_name@,$program_transform_name,;t t
-s, at bindir@,$bindir,;t t
-s, at sbindir@,$sbindir,;t t
-s, at libexecdir@,$libexecdir,;t t
-s, at datadir@,$datadir,;t t
-s, at sysconfdir@,$sysconfdir,;t t
-s, at sharedstatedir@,$sharedstatedir,;t t
-s, at localstatedir@,$localstatedir,;t t
-s, at libdir@,$libdir,;t t
-s, at includedir@,$includedir,;t t
-s, at oldincludedir@,$oldincludedir,;t t
-s, at infodir@,$infodir,;t t
-s, at mandir@,$mandir,;t t
-s, at build_alias@,$build_alias,;t t
-s, at host_alias@,$host_alias,;t t
-s, at target_alias@,$target_alias,;t t
-s, at DEFS@,$DEFS,;t t
-s, at ECHO_C@,$ECHO_C,;t t
-s, at ECHO_N@,$ECHO_N,;t t
-s, at ECHO_T@,$ECHO_T,;t t
-s, at LIBS@,$LIBS,;t t
-s, at CC@,$CC,;t t
-s, at CFLAGS@,$CFLAGS,;t t
-s, at LDFLAGS@,$LDFLAGS,;t t
-s, at CPPFLAGS@,$CPPFLAGS,;t t
-s, at ac_ct_CC@,$ac_ct_CC,;t t
-s, at EXEEXT@,$EXEEXT,;t t
-s, at OBJEXT@,$OBJEXT,;t t
-s, at CXX@,$CXX,;t t
-s, at CXXFLAGS@,$CXXFLAGS,;t t
-s, at ac_ct_CXX@,$ac_ct_CXX,;t t
-s, at RANLIB@,$RANLIB,;t t
-s, at ac_ct_RANLIB@,$ac_ct_RANLIB,;t t
-s, at LEX@,$LEX,;t t
-s, at LEXLIB@,$LEXLIB,;t t
-s, at LEX_OUTPUT_ROOT@,$LEX_OUTPUT_ROOT,;t t
-s, at YACC@,$YACC,;t t
-s, at XTRALIBS@,$XTRALIBS,;t t
-s, at CPP@,$CPP,;t t
-s, at EGREP@,$EGREP,;t t
-s, at C_PIC@,$C_PIC,;t t
-s, at STRINGS@,$STRINGS,;t t
-s, at MS_VERSION@,$MS_VERSION,;t t
-s, at PKG_CONFIG@,$PKG_CONFIG,;t t
-s, at FT_BIN@,$FT_BIN,;t t
-s, at FT_ENABLED@,$FT_ENABLED,;t t
-s, at FT_INC@,$FT_INC,;t t
-s, at FT_LIB@,$FT_LIB,;t t
-s, at ZLIB_ENABLED@,$ZLIB_ENABLED,;t t
-s, at ZLIB_INC@,$ZLIB_INC,;t t
-s, at ZLIB_LIB@,$ZLIB_LIB,;t t
-s, at PNG_ENABLED@,$PNG_ENABLED,;t t
-s, at PNG_INC@,$PNG_INC,;t t
-s, at PNG_LIB@,$PNG_LIB,;t t
-s, at GIF_ENABLED@,$GIF_ENABLED,;t t
-s, at GIF_INC@,$GIF_INC,;t t
-s, at GIF_LIB@,$GIF_LIB,;t t
-s, at JPEG_ENABLED@,$JPEG_ENABLED,;t t
-s, at JPEG_INC@,$JPEG_INC,;t t
-s, at JPEG_LIB@,$JPEG_LIB,;t t
-s, at ICONV_ENABLED@,$ICONV_ENABLED,;t t
-s, at ICONV_INC@,$ICONV_INC,;t t
-s, at ICONV_LIB@,$ICONV_LIB,;t t
-s, at GD_DEF@,$GD_DEF,;t t
-s, at GD_INC@,$GD_INC,;t t
-s, at GD_LIB@,$GD_LIB,;t t
-s, at GD_STATIC@,$GD_STATIC,;t t
-s, at MAKE_GD@,$MAKE_GD,;t t
-s, at MAKE_GD_CLEAN@,$MAKE_GD_CLEAN,;t t
-s, at FTGL_ENABLED@,$FTGL_ENABLED,;t t
-s, at FTGL_INC@,$FTGL_INC,;t t
-s, at FTGL_LIB@,$FTGL_LIB,;t t
-s, at OGL_ENABLED@,$OGL_ENABLED,;t t
-s, at OGL_INC@,$OGL_INC,;t t
-s, at OGL_LIB@,$OGL_LIB,;t t
-s, at AGG_LIB@,$AGG_LIB,;t t
-s, at AGG_INC@,$AGG_INC,;t t
-s, at AGG_OBJ@,$AGG_OBJ,;t t
-s, at PROJ_ENABLED@,$PROJ_ENABLED,;t t
-s, at PROJ_INC@,$PROJ_INC,;t t
-s, at PROJ_LIBS@,$PROJ_LIBS,;t t
-s, at THREAD_FLAG@,$THREAD_FLAG,;t t
-s, at THREAD_LIB@,$THREAD_LIB,;t t
-s, at SDE_ENABLED@,$SDE_ENABLED,;t t
-s, at SDE_INC@,$SDE_INC,;t t
-s, at SDE_LIB@,$SDE_LIB,;t t
-s, at GEOS_CONFIG@,$GEOS_CONFIG,;t t
-s, at GEOS_ENABLED@,$GEOS_ENABLED,;t t
-s, at GEOS_INC@,$GEOS_INC,;t t
-s, at GEOS_LIB@,$GEOS_LIB,;t t
-s, at GDAL_CONFIG@,$GDAL_CONFIG,;t t
-s, at GDAL_ENABLED@,$GDAL_ENABLED,;t t
-s, at OGR_ENABLED@,$OGR_ENABLED,;t t
-s, at GDAL_INC@,$GDAL_INC,;t t
-s, at GDAL_LIB@,$GDAL_LIB,;t t
-s, at PG_CONFIG@,$PG_CONFIG,;t t
-s, at POSTGIS_ENABLED@,$POSTGIS_ENABLED,;t t
-s, at POSTGIS_INC@,$POSTGIS_INC,;t t
-s, at POSTGIS_LIB@,$POSTGIS_LIB,;t t
-s, at MY_CONFIG@,$MY_CONFIG,;t t
-s, at MYSQL_ENABLED@,$MYSQL_ENABLED,;t t
-s, at MYSQL_INC@,$MYSQL_INC,;t t
-s, at MYSQL_LIB@,$MYSQL_LIB,;t t
-s, at ORACLESPATIAL_ENABLED@,$ORACLESPATIAL_ENABLED,;t t
-s, at ORACLESPATIAL_INC@,$ORACLESPATIAL_INC,;t t
-s, at ORACLESPATIAL_LIB@,$ORACLESPATIAL_LIB,;t t
-s, at WMS_SVR_ENABLED@,$WMS_SVR_ENABLED,;t t
-s, at WFS_SVR_ENABLED@,$WFS_SVR_ENABLED,;t t
-s, at WCS_SVR_ENABLED@,$WCS_SVR_ENABLED,;t t
-s, at LIBCURL_CONFIG@,$LIBCURL_CONFIG,;t t
-s, at CURL_INC@,$CURL_INC,;t t
-s, at CURL_LIB@,$CURL_LIB,;t t
-s, at LIBXML2_CONFIG@,$LIBXML2_CONFIG,;t t
-s, at XML2_INC@,$XML2_INC,;t t
-s, at XML2_LIB@,$XML2_LIB,;t t
-s, at WMS_LYR_ENABLED@,$WMS_LYR_ENABLED,;t t
-s, at WFS_LYR_ENABLED@,$WFS_LYR_ENABLED,;t t
-s, at SOS_SVR_ENABLED@,$SOS_SVR_ENABLED,;t t
-s, at XSLT_ENABLED@,$XSLT_ENABLED,;t t
-s, at XSLT_INC@,$XSLT_INC,;t t
-s, at XSLT_LIB@,$XSLT_LIB,;t t
-s, at EXSLT_ENABLED@,$EXSLT_ENABLED,;t t
-s, at EXSLT_INC@,$EXSLT_INC,;t t
-s, at EXSLT_LIB@,$EXSLT_LIB,;t t
-s, at FRIBIDI_CONFIG@,$FRIBIDI_CONFIG,;t t
-s, at FRIBIDI_ENABLED@,$FRIBIDI_ENABLED,;t t
-s, at FRIBIDI_INC@,$FRIBIDI_INC,;t t
-s, at FRIBIDI_LIB@,$FRIBIDI_LIB,;t t
-s, at CAIRO_ENABLED@,$CAIRO_ENABLED,;t t
-s, at CAIRO_INC@,$CAIRO_INC,;t t
-s, at CAIRO_LIB@,$CAIRO_LIB,;t t
-s, at FASTCGI_ENABLED@,$FASTCGI_ENABLED,;t t
-s, at FASTCGI_INC@,$FASTCGI_INC,;t t
-s, at FASTCGI_LIB@,$FASTCGI_LIB,;t t
-s, at HTTPD@,$HTTPD,;t t
-s, at MS_INC@,$MS_INC,;t t
-s, at MS_LIB@,$MS_LIB,;t t
-s, at IGNORE_MISSING_DATA@,$IGNORE_MISSING_DATA,;t t
-s, at USE_POINT_Z_M@,$USE_POINT_Z_M,;t t
-s, at USE_NINT@,$USE_NINT,;t t
-s, at DEBUG_FLAGS@,$DEBUG_FLAGS,;t t
-s, at LD_SHARED@,$LD_SHARED,;t t
-s, at SO_EXT@,$SO_EXT,;t t
-s, at SO_COMMAND_NAME@,$SO_COMMAND_NAME,;t t
-s, at PHP_LD_SHARED@,$PHP_LD_SHARED,;t t
-s, at PHP_VERSION_FLAG@,$PHP_VERSION_FLAG,;t t
-s, at PHP_SRC_DIR@,$PHP_SRC_DIR,;t t
-s, at PHP_CC@,$PHP_CC,;t t
-s, at PHP_LD@,$PHP_LD,;t t
-s, at PHP_REGEX_INC@,$PHP_REGEX_INC,;t t
-s, at PHP_REGEX_OBJ@,$PHP_REGEX_OBJ,;t t
-s, at USE_PHP_REGEX@,$USE_PHP_REGEX,;t t
-s, at MAKE_PHPMS@,$MAKE_PHPMS,;t t
-s, at MAKE_PHPMS_CLEAN@,$MAKE_PHPMS_CLEAN,;t t
-s, at APACHE_INC@,$APACHE_INC,;t t
-s, at OS_INCLUDE_DIR@,$OS_INCLUDE_DIR,;t t
-s, at ALL_ENABLED@,$ALL_ENABLED,;t t
-s, at ALL_INC@,$ALL_INC,;t t
-s, at ALL_LIB@,$ALL_LIB,;t t
-s, at ALL_STATIC_LIB@,$ALL_STATIC_LIB,;t t
-s, at RPATHS@,$RPATHS,;t t
-s, at LIBOBJS@,$LIBOBJS,;t t
-s, at LTLIBOBJS@,$LTLIBOBJS,;t t
-CEOF
+# Set to "yes" if using DIR/libNAME\${shared_ext} during linking hardcodes
+# DIR into the resulting binary.
+hardcode_direct=$hardcode_direct_CXX
 
-_ACEOF
+# Set to "yes" if using DIR/libNAME\${shared_ext} during linking hardcodes
+# DIR into the resulting binary and the resulting library dependency is
+# "absolute",i.e impossible to change by setting \${shlibpath_var} if the
+# library is relocated.
+hardcode_direct_absolute=$hardcode_direct_absolute_CXX
 
-  cat >>$CONFIG_STATUS <<\_ACEOF
-  # Split the substitutions into bite-sized pieces for seds with
-  # small command number limits, like on Digital OSF/1 and HP-UX.
-  ac_max_sed_lines=48
-  ac_sed_frag=1 # Number of current file.
-  ac_beg=1 # First line for current file.
-  ac_end=$ac_max_sed_lines # Line after last line for current file.
-  ac_more_lines=:
-  ac_sed_cmds=
-  while $ac_more_lines; do
-    if test $ac_beg -gt 1; then
-      sed "1,${ac_beg}d; ${ac_end}q" $tmp/subs.sed >$tmp/subs.frag
-    else
-      sed "${ac_end}q" $tmp/subs.sed >$tmp/subs.frag
-    fi
-    if test ! -s $tmp/subs.frag; then
-      ac_more_lines=false
-    else
-      # The purpose of the label and of the branching condition is to
-      # speed up the sed processing (if there are no `@' at all, there
-      # is no need to browse any of the substitutions).
-      # These are the two extra sed commands mentioned above.
-      (echo ':t
-  /@[a-zA-Z_][a-zA-Z_0-9]*@/!b' && cat $tmp/subs.frag) >$tmp/subs-$ac_sed_frag.sed
-      if test -z "$ac_sed_cmds"; then
-	ac_sed_cmds="sed -f $tmp/subs-$ac_sed_frag.sed"
-      else
-	ac_sed_cmds="$ac_sed_cmds | sed -f $tmp/subs-$ac_sed_frag.sed"
-      fi
-      ac_sed_frag=`expr $ac_sed_frag + 1`
-      ac_beg=$ac_end
-      ac_end=`expr $ac_end + $ac_max_sed_lines`
-    fi
-  done
-  if test -z "$ac_sed_cmds"; then
-    ac_sed_cmds=cat
-  fi
-fi # test -n "$CONFIG_FILES"
+# Set to "yes" if using the -LDIR flag during linking hardcodes DIR
+# into the resulting binary.
+hardcode_minus_L=$hardcode_minus_L_CXX
 
-_ACEOF
-cat >>$CONFIG_STATUS <<\_ACEOF
-for ac_file in : $CONFIG_FILES; do test "x$ac_file" = x: && continue
-  # Support "outfile[:infile[:infile...]]", defaulting infile="outfile.in".
-  case $ac_file in
-  - | *:- | *:-:* ) # input from stdin
-	cat >$tmp/stdin
-	ac_file_in=`echo "$ac_file" | sed 's,[^:]*:,,'`
-	ac_file=`echo "$ac_file" | sed 's,:.*,,'` ;;
-  *:* ) ac_file_in=`echo "$ac_file" | sed 's,[^:]*:,,'`
-	ac_file=`echo "$ac_file" | sed 's,:.*,,'` ;;
-  * )   ac_file_in=$ac_file.in ;;
-  esac
+# Set to "yes" if using SHLIBPATH_VAR=DIR during linking hardcodes DIR
+# into the resulting binary.
+hardcode_shlibpath_var=$hardcode_shlibpath_var_CXX
 
-  # Compute @srcdir@, @top_srcdir@, and @INSTALL@ for subdirectories.
-  ac_dir=`(dirname "$ac_file") 2>/dev/null ||
-$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
-	 X"$ac_file" : 'X\(//\)[^/]' \| \
-	 X"$ac_file" : 'X\(//\)$' \| \
-	 X"$ac_file" : 'X\(/\)' \| \
-	 .     : '\(.\)' 2>/dev/null ||
-echo X"$ac_file" |
-    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; }
-  	  /^X\(\/\/\)[^/].*/{ s//\1/; q; }
-  	  /^X\(\/\/\)$/{ s//\1/; q; }
-  	  /^X\(\/\).*/{ s//\1/; q; }
-  	  s/.*/./; q'`
-  { if $as_mkdir_p; then
-    mkdir -p "$ac_dir"
-  else
-    as_dir="$ac_dir"
-    as_dirs=
-    while test ! -d "$as_dir"; do
-      as_dirs="$as_dir $as_dirs"
-      as_dir=`(dirname "$as_dir") 2>/dev/null ||
-$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
-	 X"$as_dir" : 'X\(//\)[^/]' \| \
-	 X"$as_dir" : 'X\(//\)$' \| \
-	 X"$as_dir" : 'X\(/\)' \| \
-	 .     : '\(.\)' 2>/dev/null ||
-echo X"$as_dir" |
-    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; }
-  	  /^X\(\/\/\)[^/].*/{ s//\1/; q; }
-  	  /^X\(\/\/\)$/{ s//\1/; q; }
-  	  /^X\(\/\).*/{ s//\1/; q; }
-  	  s/.*/./; q'`
-    done
-    test ! -n "$as_dirs" || mkdir $as_dirs
-  fi || { { echo "$as_me:$LINENO: error: cannot create directory \"$ac_dir\"" >&5
-echo "$as_me: error: cannot create directory \"$ac_dir\"" >&2;}
-   { (exit 1); exit 1; }; }; }
+# Set to "yes" if building a shared library automatically hardcodes DIR
+# into the library and all subsequent libraries and executables linked
+# against it.
+hardcode_automatic=$hardcode_automatic_CXX
 
-  ac_builddir=.
+# Set to yes if linker adds runtime paths of dependent libraries
+# to runtime path list.
+inherit_rpath=$inherit_rpath_CXX
 
-if test "$ac_dir" != .; then
-  ac_dir_suffix=/`echo "$ac_dir" | sed 's,^\.[\\/],,'`
-  # A "../" for each directory in $ac_dir_suffix.
-  ac_top_builddir=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,../,g'`
-else
-  ac_dir_suffix= ac_top_builddir=
-fi
+# Whether libtool must link a program against all its dependency libraries.
+link_all_deplibs=$link_all_deplibs_CXX
 
-case $srcdir in
-  .)  # No --srcdir option.  We are building in place.
-    ac_srcdir=.
-    if test -z "$ac_top_builddir"; then
-       ac_top_srcdir=.
-    else
-       ac_top_srcdir=`echo $ac_top_builddir | sed 's,/$,,'`
-    fi ;;
-  [\\/]* | ?:[\\/]* )  # Absolute path.
-    ac_srcdir=$srcdir$ac_dir_suffix;
-    ac_top_srcdir=$srcdir ;;
-  *) # Relative path.
-    ac_srcdir=$ac_top_builddir$srcdir$ac_dir_suffix
-    ac_top_srcdir=$ac_top_builddir$srcdir ;;
-esac
+# Set to "yes" if exported symbols are required.
+always_export_symbols=$always_export_symbols_CXX
 
-# Do not use `cd foo && pwd` to compute absolute paths, because
-# the directories may not exist.
-case `pwd` in
-.) ac_abs_builddir="$ac_dir";;
-*)
-  case "$ac_dir" in
-  .) ac_abs_builddir=`pwd`;;
-  [\\/]* | ?:[\\/]* ) ac_abs_builddir="$ac_dir";;
-  *) ac_abs_builddir=`pwd`/"$ac_dir";;
-  esac;;
-esac
-case $ac_abs_builddir in
-.) ac_abs_top_builddir=${ac_top_builddir}.;;
-*)
-  case ${ac_top_builddir}. in
-  .) ac_abs_top_builddir=$ac_abs_builddir;;
-  [\\/]* | ?:[\\/]* ) ac_abs_top_builddir=${ac_top_builddir}.;;
-  *) ac_abs_top_builddir=$ac_abs_builddir/${ac_top_builddir}.;;
-  esac;;
-esac
-case $ac_abs_builddir in
-.) ac_abs_srcdir=$ac_srcdir;;
-*)
-  case $ac_srcdir in
-  .) ac_abs_srcdir=$ac_abs_builddir;;
-  [\\/]* | ?:[\\/]* ) ac_abs_srcdir=$ac_srcdir;;
-  *) ac_abs_srcdir=$ac_abs_builddir/$ac_srcdir;;
-  esac;;
-esac
-case $ac_abs_builddir in
-.) ac_abs_top_srcdir=$ac_top_srcdir;;
-*)
-  case $ac_top_srcdir in
-  .) ac_abs_top_srcdir=$ac_abs_builddir;;
-  [\\/]* | ?:[\\/]* ) ac_abs_top_srcdir=$ac_top_srcdir;;
-  *) ac_abs_top_srcdir=$ac_abs_builddir/$ac_top_srcdir;;
-  esac;;
-esac
+# The commands to list exported symbols.
+export_symbols_cmds=$lt_export_symbols_cmds_CXX
 
+# Symbols that should not be listed in the preloaded symbols.
+exclude_expsyms=$lt_exclude_expsyms_CXX
 
+# Symbols that must always be exported.
+include_expsyms=$lt_include_expsyms_CXX
 
-  if test x"$ac_file" != x-; then
-    { echo "$as_me:$LINENO: creating $ac_file" >&5
-echo "$as_me: creating $ac_file" >&6;}
-    rm -f "$ac_file"
-  fi
-  # Let's still pretend it is `configure' which instantiates (i.e., don't
-  # use $as_me), people would be surprised to read:
-  #    /* config.h.  Generated by config.status.  */
-  if test x"$ac_file" = x-; then
-    configure_input=
-  else
-    configure_input="$ac_file.  "
-  fi
-  configure_input=$configure_input"Generated from `echo $ac_file_in |
-				     sed 's,.*/,,'` by configure."
-
-  # First look for the input files in the build tree, otherwise in the
-  # src tree.
-  ac_file_inputs=`IFS=:
-    for f in $ac_file_in; do
-      case $f in
-      -) echo $tmp/stdin ;;
-      [\\/$]*)
-	 # Absolute (can't be DOS-style, as IFS=:)
-	 test -f "$f" || { { echo "$as_me:$LINENO: error: cannot find input file: $f" >&5
-echo "$as_me: error: cannot find input file: $f" >&2;}
-   { (exit 1); exit 1; }; }
-	 echo "$f";;
-      *) # Relative
-	 if test -f "$f"; then
-	   # Build tree
-	   echo "$f"
-	 elif test -f "$srcdir/$f"; then
-	   # Source tree
-	   echo "$srcdir/$f"
-	 else
-	   # /dev/null tree
-	   { { echo "$as_me:$LINENO: error: cannot find input file: $f" >&5
-echo "$as_me: error: cannot find input file: $f" >&2;}
-   { (exit 1); exit 1; }; }
-	 fi;;
-      esac
-    done` || { (exit 1); exit 1; }
-_ACEOF
-cat >>$CONFIG_STATUS <<_ACEOF
-  sed "$ac_vpsub
-$extrasub
-_ACEOF
-cat >>$CONFIG_STATUS <<\_ACEOF
-:t
-/@[a-zA-Z_][a-zA-Z_0-9]*@/!b
-s, at configure_input@,$configure_input,;t t
-s, at srcdir@,$ac_srcdir,;t t
-s, at abs_srcdir@,$ac_abs_srcdir,;t t
-s, at top_srcdir@,$ac_top_srcdir,;t t
-s, at abs_top_srcdir@,$ac_abs_top_srcdir,;t t
-s, at builddir@,$ac_builddir,;t t
-s, at abs_builddir@,$ac_abs_builddir,;t t
-s, at top_builddir@,$ac_top_builddir,;t t
-s, at abs_top_builddir@,$ac_abs_top_builddir,;t t
-" $ac_file_inputs | (eval "$ac_sed_cmds") >$tmp/out
-  rm -f $tmp/stdin
-  if test x"$ac_file" != x-; then
-    mv $tmp/out $ac_file
-  else
-    cat $tmp/out
-    rm -f $tmp/out
-  fi
+# Commands necessary for linking programs (against libraries) with templates.
+prelink_cmds=$lt_prelink_cmds_CXX
 
-done
-_ACEOF
+# Commands necessary for finishing linking programs.
+postlink_cmds=$lt_postlink_cmds_CXX
+
+# Specify filename containing input files.
+file_list_spec=$lt_file_list_spec_CXX
+
+# How to hardcode a shared library path into an executable.
+hardcode_action=$hardcode_action_CXX
 
-cat >>$CONFIG_STATUS <<\_ACEOF
+# The directories searched by this compiler when creating a shared library.
+compiler_lib_search_dirs=$lt_compiler_lib_search_dirs_CXX
 
-{ (exit 0); exit 0; }
+# Dependencies to place before and after the objects being linked to
+# create a shared library.
+predep_objects=$lt_predep_objects_CXX
+postdep_objects=$lt_postdep_objects_CXX
+predeps=$lt_predeps_CXX
+postdeps=$lt_postdeps_CXX
+
+# The library search path used internally by the compiler when linking
+# a shared library.
+compiler_lib_search_path=$lt_compiler_lib_search_path_CXX
+
+# ### END LIBTOOL TAG CONFIG: CXX
+_LT_EOF
+
+ ;;
+
+  esac
+done # for ac_tag
+
+
+as_fn_exit 0
 _ACEOF
-chmod +x $CONFIG_STATUS
 ac_clean_files=$ac_clean_files_save
 
+test $ac_write_fail = 0 ||
+  as_fn_error $? "write failure creating $CONFIG_STATUS" "$LINENO" 5
+
 
 # configure is writing to config.log, and then calls config.status.
 # config.status does its own redirection, appending to config.log.
@@ -15271,123 +23795,140 @@ if test "$no_create" != yes; then
   exec 5>>config.log
   # Use ||, not &&, to avoid exiting from the if with $? = 1, which
   # would make configure fail if this is the last instruction.
-  $ac_cs_success || { (exit 1); exit 1; }
-fi
-
-
-
-
-echo "$as_me:$LINENO: result: " >&5
-echo "${ECHO_T}" >&6
-echo "$as_me:$LINENO: result: MapServer is now configured for ${host}" >&5
-echo "${ECHO_T}MapServer is now configured for ${host}" >&6
-echo "$as_me:$LINENO: result: " >&5
-echo "${ECHO_T}" >&6
-echo "$as_me:$LINENO: result:  -------------- Compiler Info ------------- " >&5
-echo "${ECHO_T} -------------- Compiler Info ------------- " >&6
-echo "$as_me:$LINENO: result:   C compiler:                ${CC} ${CFLAGS}" >&5
-echo "${ECHO_T}  C compiler:                ${CC} ${CFLAGS}" >&6
-echo "$as_me:$LINENO: result:   C++ compiler:              ${CXX} ${CXXFLAGS}" >&5
-echo "${ECHO_T}  C++ compiler:              ${CXX} ${CXXFLAGS}" >&6
-echo "$as_me:$LINENO: result:   Debug:                     ${REPORT_ENABLE_DEBUG}${DEBUG_FLAGS}" >&5
-echo "${ECHO_T}  Debug:                     ${REPORT_ENABLE_DEBUG}${DEBUG_FLAGS}" >&6
-echo "$as_me:$LINENO: result:   Generic NINT:              ${USE_NINT}" >&5
-echo "${ECHO_T}  Generic NINT:              ${USE_NINT}" >&6
-echo "$as_me:$LINENO: result: " >&5
-echo "${ECHO_T}" >&6
-echo "$as_me:$LINENO: result:  -------------- Renderer Settings --------- " >&5
-echo "${ECHO_T} -------------- Renderer Settings --------- " >&6
-echo "$as_me:$LINENO: result:   OpenGL support:            ${OGL_ENABLED}" >&5
-echo "${ECHO_T}  OpenGL support:            ${OGL_ENABLED}" >&6
-echo "$as_me:$LINENO: result:   zlib support:              ${ZLIB_ENABLED}" >&5
-echo "${ECHO_T}  zlib support:              ${ZLIB_ENABLED}" >&6
-echo "$as_me:$LINENO: result:   png support:               ${PNG_ENABLED}" >&5
-echo "${ECHO_T}  png support:               ${PNG_ENABLED}" >&6
-echo "$as_me:$LINENO: result:   gif support:               ${GIF_ENABLED}" >&5
-echo "${ECHO_T}  gif support:               ${GIF_ENABLED}" >&6
-echo "$as_me:$LINENO: result:   jpeg support:              ${JPEG_ENABLED}" >&5
-echo "${ECHO_T}  jpeg support:              ${JPEG_ENABLED}" >&6
-echo "$as_me:$LINENO: result:   freetype support:          ${FT_ENABLED}" >&5
-echo "${ECHO_T}  freetype support:          ${FT_ENABLED}" >&6
-echo "$as_me:$LINENO: result:   iconv support:             ${ICONV_ENABLED}" >&5
-echo "${ECHO_T}  iconv support:             ${ICONV_ENABLED}" >&6
-echo "$as_me:$LINENO: result:   AGG support:               ${AGG_ENABLED}" >&5
-echo "${ECHO_T}  AGG support:               ${AGG_ENABLED}" >&6
-echo "$as_me:$LINENO: result:   SVG Symbol support:        ${AGG_SVG_SYMBOLS_ENABLED}" >&5
-echo "${ECHO_T}  SVG Symbol support:        ${AGG_SVG_SYMBOLS_ENABLED}" >&6
-echo "$as_me:$LINENO: result:   Cairo (SVG,PDF) support:   ${CAIRO_ENABLED}" >&5
-echo "${ECHO_T}  Cairo (SVG,PDF) support:   ${CAIRO_ENABLED}" >&6
-echo "$as_me:$LINENO: result:   KML support:               ${KML_ENABLED}" >&5
-echo "${ECHO_T}  KML support:               ${KML_ENABLED}" >&6
-echo "$as_me:$LINENO: result: " >&5
-echo "${ECHO_T}" >&6
-
-echo "$as_me:$LINENO: result:  -------------- Support Libraries --------- " >&5
-echo "${ECHO_T} -------------- Support Libraries --------- " >&6
-echo "$as_me:$LINENO: result:   Proj.4 support:            ${PROJ_ENABLED}" >&5
-echo "${ECHO_T}  Proj.4 support:            ${PROJ_ENABLED}" >&6
-echo "$as_me:$LINENO: result:   Libxml2 support:           ${XML2_ENABLED}" >&5
-echo "${ECHO_T}  Libxml2 support:           ${XML2_ENABLED}" >&6
-echo "$as_me:$LINENO: result:   FriBidi support:           ${FRIBIDI_ENABLED}" >&5
-echo "${ECHO_T}  FriBidi support:           ${FRIBIDI_ENABLED}" >&6
-echo "$as_me:$LINENO: result:   Curl support:              ${CURL_ENABLED}" >&5
-echo "${ECHO_T}  Curl support:              ${CURL_ENABLED}" >&6
-echo "$as_me:$LINENO: result:   FastCGI support:           ${FASTCGI_ENABLED}" >&5
-echo "${ECHO_T}  FastCGI support:           ${FASTCGI_ENABLED}" >&6
-echo "$as_me:$LINENO: result:   Threading support:         ${THREAD_FLAG}" >&5
-echo "${ECHO_T}  Threading support:         ${THREAD_FLAG}" >&6
-echo "$as_me:$LINENO: result:   GEOS support:              ${GEOS_ENABLED}" >&5
-echo "${ECHO_T}  GEOS support:              ${GEOS_ENABLED}" >&6
-echo "$as_me:$LINENO: result:   XML Mapfile support:        ${XMLMAPFILE_ENABLED}" >&5
-echo "${ECHO_T}  XML Mapfile support:        ${XMLMAPFILE_ENABLED}" >&6
-echo "$as_me:$LINENO: result:   XSLT support:              ${XSLT_ENABLED}" >&5
-echo "${ECHO_T}  XSLT support:              ${XSLT_ENABLED}" >&6
-echo "$as_me:$LINENO: result:   EXSLT support:              ${EXSLT_ENABLED}" >&5
-echo "${ECHO_T}  EXSLT support:              ${EXSLT_ENABLED}" >&6
-echo "$as_me:$LINENO: result: " >&5
-echo "${ECHO_T}" >&6
-
-echo "$as_me:$LINENO: result:  -------------- Data Format Drivers ------- " >&5
-echo "${ECHO_T} -------------- Data Format Drivers ------- " >&6
-echo "$as_me:$LINENO: result:   PostGIS support:           ${POSTGIS_ENABLED}" >&5
-echo "${ECHO_T}  PostGIS support:           ${POSTGIS_ENABLED}" >&6
-echo "$as_me:$LINENO: result:   ArcSDE support:            ${SDE_ENABLED}" >&5
-echo "${ECHO_T}  ArcSDE support:            ${SDE_ENABLED}" >&6
-echo "$as_me:$LINENO: result:   OGR support:               ${OGR_ENABLED}" >&5
-echo "${ECHO_T}  OGR support:               ${OGR_ENABLED}" >&6
-echo "$as_me:$LINENO: result:   GDAL support:              ${GDAL_ENABLED}" >&5
-echo "${ECHO_T}  GDAL support:              ${GDAL_ENABLED}" >&6
-echo "$as_me:$LINENO: result:   Oracle Spatial support:    ${ORACLESPATIAL_ENABLED}" >&5
-echo "${ECHO_T}  Oracle Spatial support:    ${ORACLESPATIAL_ENABLED}" >&6
-echo "$as_me:$LINENO: result: " >&5
-echo "${ECHO_T}" >&6
-
-echo "$as_me:$LINENO: result:  -------------- OGC Services -------------- " >&5
-echo "${ECHO_T} -------------- OGC Services -------------- " >&6
-echo "$as_me:$LINENO: result:   WMS Server:                ${WMS_SVR_ENABLED}" >&5
-echo "${ECHO_T}  WMS Server:                ${WMS_SVR_ENABLED}" >&6
-echo "$as_me:$LINENO: result:   WMS Client:                ${WMS_LYR_ENABLED}" >&5
-echo "${ECHO_T}  WMS Client:                ${WMS_LYR_ENABLED}" >&6
-echo "$as_me:$LINENO: result:   WFS Server:                ${WFS_SVR_ENABLED}" >&5
-echo "${ECHO_T}  WFS Server:                ${WFS_SVR_ENABLED}" >&6
-echo "$as_me:$LINENO: result:   WFS Client:                ${WFS_LYR_ENABLED}" >&5
-echo "${ECHO_T}  WFS Client:                ${WFS_LYR_ENABLED}" >&6
-echo "$as_me:$LINENO: result:   WCS Server:                ${WCS_SVR_ENABLED}" >&5
-echo "${ECHO_T}  WCS Server:                ${WCS_SVR_ENABLED}" >&6
-echo "$as_me:$LINENO: result:   SOS Server:                ${SOS_SVR_ENABLED}" >&5
-echo "${ECHO_T}  SOS Server:                ${SOS_SVR_ENABLED}" >&6
-echo "$as_me:$LINENO: result: " >&5
-echo "${ECHO_T}" >&6
-
-echo "$as_me:$LINENO: result:  -------------- MapScript ----------------- " >&5
-echo "${ECHO_T} -------------- MapScript ----------------- " >&6
-if test -n "${PHP_SRC_DIR}"; then
-  echo "$as_me:$LINENO: result:   PHP MapScript:             yes" >&5
-echo "${ECHO_T}  PHP MapScript:             yes" >&6
-else
-  echo "$as_me:$LINENO: result:   PHP MapScript:             no" >&5
-echo "${ECHO_T}  PHP MapScript:             no" >&6
-fi
-
-echo "$as_me:$LINENO: result: " >&5
-echo "${ECHO_T}" >&6
+  $ac_cs_success || as_fn_exit 1
+fi
+if test -n "$ac_unrecognized_opts" && test "$enable_option_checking" != no; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: unrecognized options: $ac_unrecognized_opts" >&5
+$as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;}
+fi
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: " >&5
+$as_echo "" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: MapServer is now configured for ${host}" >&5
+$as_echo "MapServer is now configured for ${host}" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: " >&5
+$as_echo "" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result:  -------------- Compiler Info ------------- " >&5
+$as_echo " -------------- Compiler Info ------------- " >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result:   C compiler:                ${CC} ${CFLAGS}" >&5
+$as_echo "  C compiler:                ${CC} ${CFLAGS}" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result:   C++ compiler:              ${CXX} ${CXXFLAGS}" >&5
+$as_echo "  C++ compiler:              ${CXX} ${CXXFLAGS}" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result:   Debug:                     ${REPORT_ENABLE_DEBUG}${DEBUG_FLAGS}" >&5
+$as_echo "  Debug:                     ${REPORT_ENABLE_DEBUG}${DEBUG_FLAGS}" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result:   Generic NINT:              ${USE_NINT}" >&5
+$as_echo "  Generic NINT:              ${USE_NINT}" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: " >&5
+$as_echo "" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result:  -------------- Renderer Settings --------- " >&5
+$as_echo " -------------- Renderer Settings --------- " >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result:   OpenGL support:            ${OGL_ENABLED}" >&5
+$as_echo "  OpenGL support:            ${OGL_ENABLED}" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result:   zlib support:              ${ZLIB_ENABLED}" >&5
+$as_echo "  zlib support:              ${ZLIB_ENABLED}" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result:   png support:               ${PNG_ENABLED}" >&5
+$as_echo "  png support:               ${PNG_ENABLED}" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result:   gif support:               ${GIF_ENABLED}" >&5
+$as_echo "  gif support:               ${GIF_ENABLED}" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result:   jpeg support:              ${JPEG_ENABLED}" >&5
+$as_echo "  jpeg support:              ${JPEG_ENABLED}" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result:   freetype support:          ${FT_ENABLED}" >&5
+$as_echo "  freetype support:          ${FT_ENABLED}" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result:   iconv support:             ${ICONV_ENABLED}" >&5
+$as_echo "  iconv support:             ${ICONV_ENABLED}" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result:   AGG support:               ${AGG_ENABLED}" >&5
+$as_echo "  AGG support:               ${AGG_ENABLED}" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result:   GD support:                ${GD_ENABLED}" >&5
+$as_echo "  GD support:                ${GD_ENABLED}" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result:   Cairo (SVG,PDF) support:   ${CAIRO_ENABLED}" >&5
+$as_echo "  Cairo (SVG,PDF) support:   ${CAIRO_ENABLED}" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result:   Cairo SVG symbol support:  ${LIBSVG_CAIRO_ENABLED}" >&5
+$as_echo "  Cairo SVG symbol support:  ${LIBSVG_CAIRO_ENABLED}" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result:   KML support:               ${KML_ENABLED}" >&5
+$as_echo "  KML support:               ${KML_ENABLED}" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: " >&5
+$as_echo "" >&6; }
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result:  -------------- Support Libraries --------- " >&5
+$as_echo " -------------- Support Libraries --------- " >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result:   Proj.4 support:            ${PROJ_ENABLED}" >&5
+$as_echo "  Proj.4 support:            ${PROJ_ENABLED}" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result:   Proj Fastpaths:            ${PROJ_FASTPATH_ENABLED}" >&5
+$as_echo "  Proj Fastpaths:            ${PROJ_FASTPATH_ENABLED}" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result:   Libxml2 support:           ${XML2_ENABLED}" >&5
+$as_echo "  Libxml2 support:           ${XML2_ENABLED}" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result:   FriBidi support:           ${FRIBIDI_ENABLED}" >&5
+$as_echo "  FriBidi support:           ${FRIBIDI_ENABLED}" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result:   Curl support:              ${CURL_ENABLED}" >&5
+$as_echo "  Curl support:              ${CURL_ENABLED}" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result:   FastCGI support:           ${FASTCGI_ENABLED}" >&5
+$as_echo "  FastCGI support:           ${FASTCGI_ENABLED}" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result:   Exempi support:            ${EXEMPI_ENABLED}" >&5
+$as_echo "  Exempi support:            ${EXEMPI_ENABLED}" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result:   Threading support:         ${THREAD_FLAG}" >&5
+$as_echo "  Threading support:         ${THREAD_FLAG}" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result:   GEOS support:              ${GEOS_ENABLED}" >&5
+$as_echo "  GEOS support:              ${GEOS_ENABLED}" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result:   XML Mapfile support:        ${XMLMAPFILE_ENABLED}" >&5
+$as_echo "  XML Mapfile support:        ${XMLMAPFILE_ENABLED}" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result:   XSLT support:              ${XSLT_ENABLED}" >&5
+$as_echo "  XSLT support:              ${XSLT_ENABLED}" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result:   EXSLT support:              ${EXSLT_ENABLED}" >&5
+$as_echo "  EXSLT support:              ${EXSLT_ENABLED}" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: " >&5
+$as_echo "" >&6; }
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result:  -------------- Data Format Drivers ------- " >&5
+$as_echo " -------------- Data Format Drivers ------- " >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result:   PostGIS support:           ${POSTGIS_ENABLED}" >&5
+$as_echo "  PostGIS support:           ${POSTGIS_ENABLED}" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result:   ArcSDE support:            ${SDE_ENABLED}" >&5
+$as_echo "  ArcSDE support:            ${SDE_ENABLED}" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result:   OGR support:               ${OGR_ENABLED}" >&5
+$as_echo "  OGR support:               ${OGR_ENABLED}" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result:   GDAL support:              ${GDAL_ENABLED}" >&5
+$as_echo "  GDAL support:              ${GDAL_ENABLED}" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result:   Oracle Spatial support:    ${ORACLESPATIAL_ENABLED}" >&5
+$as_echo "  Oracle Spatial support:    ${ORACLESPATIAL_ENABLED}" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: " >&5
+$as_echo "" >&6; }
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result:  -------------- OGC Services -------------- " >&5
+$as_echo " -------------- OGC Services -------------- " >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result:   WMS Server:                ${WMS_SVR_ENABLED}" >&5
+$as_echo "  WMS Server:                ${WMS_SVR_ENABLED}" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result:   WMS Client:                ${WMS_LYR_ENABLED}" >&5
+$as_echo "  WMS Client:                ${WMS_LYR_ENABLED}" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result:   WFS Server:                ${WFS_SVR_ENABLED}" >&5
+$as_echo "  WFS Server:                ${WFS_SVR_ENABLED}" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result:   WFS Client:                ${WFS_LYR_ENABLED}" >&5
+$as_echo "  WFS Client:                ${WFS_LYR_ENABLED}" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result:   WCS Server:                ${WCS_SVR_ENABLED}" >&5
+$as_echo "  WCS Server:                ${WCS_SVR_ENABLED}" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result:   SOS Server:                ${SOS_SVR_ENABLED}" >&5
+$as_echo "  SOS Server:                ${SOS_SVR_ENABLED}" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: " >&5
+$as_echo "" >&6; }
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result:  -------------- MapScript ----------------- " >&5
+$as_echo " -------------- MapScript ----------------- " >&6; }
+if test -n "${PHP_MAPSCRIPT}"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result:   PHP MapScript:             yes" >&5
+$as_echo "  PHP MapScript:             yes" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result:   PHP MapScript:             no" >&5
+$as_echo "  PHP MapScript:             no" >&6; }
+fi
+if test -n "${PYTHON_MAPSCRIPT}"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result:   Python MapScript:          yes" >&5
+$as_echo "  Python MapScript:          yes" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result:   Python MapScript:          no" >&5
+$as_echo "  Python MapScript:          no" >&6; }
+fi
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: " >&5
+$as_echo "" >&6; }
diff --git a/configure.in b/configure.in
index ba42418..f5b7643 100755
--- a/configure.in
+++ b/configure.in
@@ -28,20 +28,41 @@ dnl FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 dnl DEALINGS IN THE SOFTWARE.
 dnl **************************************************************************
 
-AC_INIT(Makefile.in)
 
+AC_INIT(Makefile.in)
+LT_INIT([disable-static])
+AC_CONFIG_MACRO_DIR([m4/])
+m4_include([m4/mapserver.m4])
+m4_include([m4/apache.m4])
+m4_include([m4/ax_jni_include_dir.m4])
+m4_include([m4/ax_pkg_swig.m4])
+m4_include([m4/ax_cflags_warn_all.m4])
+
+AC_CONFIG_SRCDIR([mapserv.c])
 dnl Checks for programs.
 AC_PROG_CC
 AC_PROG_CXX
-AC_PROG_RANLIB
+PROG_CXX_WORKS
 AC_PROG_LEX
 AC_PROG_YACC
-AC_RUNPATH_SWITCH
+AC_PROG_LIBTOOL
+AC_PROG_INSTALL
+AC_PROG_SED
+
+dnl ---------------------------------------------------------------------
+dnl Look for MapServer version in mapserver.h
+dnl ---------------------------------------------------------------------
+MS_VERSION=`grep 'MS_VERSION ' mapserver.h | grep '#define' | cut -d\" -f2`
+AC_MSG_RESULT([MapServer Version from mapserver.h: '$MS_VERSION'])
+AC_SUBST(MS_VERSION,    "$MS_VERSION")
+
+
 
 dnl ---------------------------------------------------------------------
 dnl Checks for libraries.
 dnl ---------------------------------------------------------------------
 AC_CHECK_LIB(m,exp, XTRALIBS="$XTRALIBS -lm",,)
+AC_CHECK_LIB(dl,dlopen, XTRALIBS="$XTRALIBS -ldl",,)
 AC_SUBST(XTRALIBS, $XTRALIBS)
 
 AC_CHECK_LIB(stdc++,__gxx_personality_v0, XTRALIBS="$XTRALIBS -lstdc++",,)
@@ -55,13 +76,6 @@ dnl ---------------------------------------------------------------------
 AC_HEADER_STDC
 
 dnl ---------------------------------------------------------------------
-dnl Add -fPIC to compiler flags if appropriate
-dnl ---------------------------------------------------------------------
-AC_COMPILER_PIC
-CFLAGS="$CFLAGS $C_PIC"
-CXXFLAGS="$CXXFLAGS $C_PIC"
-
-dnl ---------------------------------------------------------------------
 dnl Check for some string functions
 dnl ---------------------------------------------------------------------
 AC_CHECK_FUNC(strcasecmp, ,  STRINGS="-DNEED_STRCASECMP $STRINGS")
@@ -73,13 +87,8 @@ AC_CHECK_FUNC(strlcat, ,      STRINGS="-DNEED_STRLCAT $STRINGS")
 AC_CHECK_FUNC(strlcpy, ,      STRINGS="-DNEED_STRLCPY $STRINGS")
 AC_CHECK_FUNC(vsnprintf, STRINGS="-DHAVE_VSNPRINTF $STRINGS", )
 AC_SUBST(STRINGS, $STRINGS)
+ALL_ENABLED="$STRINGS $ALL_ENABLED"
 
-dnl ---------------------------------------------------------------------
-dnl Look for MapServer version in mapserver.h
-dnl ---------------------------------------------------------------------
-MS_VERSION=`grep 'MS_VERSION ' mapserver.h | grep '#define' | cut -d\" -f2`
-AC_MSG_RESULT([MapServer Version from mapserver.h: '$MS_VERSION'])
-AC_SUBST(MS_VERSION,    "$MS_VERSION")
 
 dnl ---------------------------------------------------------------------
 dnl Several libraries may use pkg-config.
@@ -179,10 +188,10 @@ _libs="$LIBS"
 CPPFLAGS="$FT_CFLAGS $CPPFLAGS"
 LDFLAGS="$FT_LDFLAGS $LDFLAGS"
 
-AC_CHECK_LIB(freetype,FT_Init_FreeType,,
+AC_CHECK_LIB(freetype,FT_Init_FreeType,[:],
              AC_MSG_ERROR([unable to link - reconfigure with correct --with-freetype=dir ]))
 
-AC_CHECK_HEADERS(ft2build.h,,
+AC_CHECK_HEADERS(ft2build.h,[:],
                  AC_MSG_ERROR([ft2build.h header not found - reconfigure with correct --with-freetype=dir ]))
 
 CPPFLAGS=$_cppflags
@@ -197,314 +206,157 @@ ALL_INC="$FT_CFLAGS $ALL_INC"
 ALL_LIB="$FT_LDFLAGS $ALL_LIB"
 
 
-dnl ---------------------------------------------------------------------
-dnl Check where zlib is installed (used by libpng and by ZVG compressed output)
-dnl ---------------------------------------------------------------------
-
-unset ac_cv_lib_z_zlibVersion
-
-AC_ARG_WITH(zlib,
-[  --with-zlib=DIR         GD,SVG: Specify where zlib is installed (DIR is path
-                              to zlib install dir).],
-    ZLIB_DIR=$withval,ZLIB_DIR='')
-
-AC_EXPAND_PATH($ZLIB_DIR, ZLIB_DIR)
-AC_CHECKING(where Zlib is installed)
-ZLIB_LIB=''
-
-test -f $ZLIB_DIR/include/zlib.h && ZLIB_INCDIR="$ZLIB_DIR/include"
 
-test -f $ZLIB_DIR/lib/libz.a -o -f $ZLIB_DIR/lib/libz.so -o -f $ZLIB_DIR/lib/libz.sl -o -f $ZLIB_DIR/lib/libz.dylib && ZLIB_LIBDIR="$ZLIB_DIR/lib"
-test -f $ZLIB_DIR/lib64/libz.a -o -f $ZLIB_DIR/lib64/libz.so -o -f $ZLIB_DIR/lib64/libz.sl && ZLIB_LIBDIR="$ZLIB_DIR/lib64"
-test -f $ZLIB_DIR/libz.a -o -f $ZLIB_DIR/libz.so -o -f $ZLIB_DIR/libz.sl && ZLIB_LIBDIR="$ZLIB_DIR"
+AC_DEFUN([MS_CHECK_PNG],[
+   AC_ARG_WITH(png,
+      AC_HELP_STRING([--with-png], [libpng location: [yes|/path/to/png/prefix]]),
+      [],
+      [with_png=yes])
+   if test x"$with_png" == "xno"; then
+      AC_MSG_ERROR([png support cannot be disabled])
+   fi
 
+   if test -z "$with_png" -o "$with_png" == "yes" -o "$with_png" == "/usr"; then
+      AC_CHECK_HEADER([png.h],[:],
+                   [AC_MSG_ERROR([png.h header not found. install png development package, or reconfigure with --with-png=/path/to/png/prefix])])
+      AC_CHECK_HEADER([setjmp.h],[:],
+                   [AC_MSG_ERROR([setjmp.h header not found. install png development package, or reconfigure with --with-png=/path/to/png/prefix])])
+      AC_CHECK_LIB([png], [png_init_io],[:],
+                   [AC_MSG_ERROR([libpng library not found. install png development package, or reconfigure with --with-png=/path/to/png/prefix])])
 
-if test -n "$ZLIB_LIBDIR" -a -n "$ZLIB_INCDIR" ; then
+   else
+      old_LDFLAGS="$LDFLAGS"
+      old_CPPFLAGS="$CPPFLAGS"
 
-  dnl
-  dnl Found libz runtime and headers. Enable USE_ZLIB (SVG compressed output)
-  dnl
-  ZLIB_ENABLED="-DUSE_ZLIB"
-  ZLIB_INC="-I$ZLIB_INCDIR"
-  ZLIB_LIB="-L$ZLIB_LIBDIR -lz"
-  AC_MSG_RESULT([        using libz from $ZLIB_LIB ($ZLIB_ENABLED)])
-  AC_ADD_RUNPATH("$ZLIB_DIR")
+      CPPFLAGS="-I$with_png/include"
+      LDFLAGS="-L$with_png/lib"
+      
+      AC_CHECK_HEADER([png.h],[:],
+                   [AC_MSG_ERROR([png.h header not found in $with_png. install png development package, or reconfigure with --with-png=/path/to/png/prefix])])
+      AC_CHECK_HEADER([setjmp.h],[:],
+                   [AC_MSG_ERROR([setjmp.h header not found. install png development package, or reconfigure with --with-png=/path/to/png/prefix])])
+      AC_CHECK_LIB([png], [png_init_io],[:],
+                   [AC_MSG_ERROR([libpng library not found in $with_png. install png development package, or reconfigure with --with-png=/path/to/png/prefix])])
+      PNG_INC="$CPPFLAGS"
+      PNG_LIB="$LDFLAGS"
+      CPPFLAGS="$old_CPPFLAGS"
+      LDFLAGS="$old_LDFLAGS"
+   fi
+   PNG_ENABLED="-DUSE_PNG"
 
-elif test -n "$ZLIB_LIBDIR" ; then
+   ALL_ENABLED="$PNG_ENABLED $ALL_ENABLED"
+   ALL_INC="$ALL_INC $PNG_INC"
+   ALL_LIB="$ALL_LIB $PNG_LIB -lpng"
+   AC_SUBST(PNG_ENABLED, "$PNG_ENABLED")
+   AC_SUBST(PNG_INC,    "$PNG_INC")
+   AC_SUBST(PNG_LIB,    "$PNG_LIB -lpng")
 
-  dnl
-  dnl Found only runtime but no headers (good only for libpng)
-  dnl
-  ZLIB_LIB="-L$ZLIB_LIBDIR -lz"
-  AC_MSG_RESULT([        using runtime libz from $ZLIB_LIB])
-  AC_ADD_RUNPATH("$ZLIB_DIR")
+])
 
-else
 
-  dnl check for lib in system libs
-
-  AC_CHECK_LIB(z, zlibVersion, ZLIB_LIB="-lz",,)
+AC_DEFUN([MS_CHECK_JPEG],[
+   AC_ARG_WITH(jpeg,
+      AC_HELP_STRING([--with-jpeg], [libjpeg location: [yes|/path/to/jpeg/prefix]]),
+      [],
+      [with_jpeg=yes])
+   if test x"$with_jpeg" == "xno"; then
+      AC_MSG_ERROR([jpeg support cannot be disabled])
+   fi
 
-  if test -n "$ZLIB_LIB" ; then
-    ZLIB_ENABLED="-DUSE_ZLIB"
-    AC_MSG_RESULT([        using libz from system libs ($ZLIB_ENABLED).])
-  else
-    AC_MSG_RESULT([        Zlib (libz) library cannot be found, possibly needed for GD])
-  fi
+   if test -z "$with_jpeg" -o "$with_jpeg" == "yes" -o "$with_jpeg" == "/usr"; then
+      AC_CHECK_HEADER([jpeglib.h],[:],
+                   [AC_MSG_ERROR([jpeglib.h header not found. install jpeg development package, or reconfigure with --with-jpeg=/path/to/jpeg/prefix])])
+      AC_CHECK_LIB([jpeg], [jpeg_read_header],[:],
+                   [AC_MSG_ERROR([libjpeg library not found. install jpeg development package, or reconfigure with --with-jpeg=/path/to/jpeg/prefix])])
 
-fi
+   else
+      old_LDFLAGS="$LDFLAGS"
+      old_CPPFLAGS="$CPPFLAGS"
 
-dnl If we found ZLIB headers then enable it by default since SVG output
-dnl is enabled by default and will take advantage of it, otherwise the 
-dnl PNG code below will take care of including the runtime lib only.
+      CPPFLAGS="-I$with_jpeg/include"
+      LDFLAGS="-L$with_jpeg/lib"
+      
+      AC_CHECK_HEADER([jpeglib.h],[:],
+                   [AC_MSG_ERROR([jpeglib.h header not found in $with_jpeg. install jpeg development package, or reconfigure with --with-jpeg=/path/to/jpeg/prefix])])
+      AC_CHECK_LIB([jpeg], [jpeg_read_header],[:],
+                   [AC_MSG_ERROR([libjpeg library not found in $with_jpeg. install jpeg development package, or reconfigure with --with-jpeg=/path/to/jpeg/prefix])])
+      JPEG_INC="$CPPFLAGS"
+      JPEG_LIB="$LDFLAGS"
+      CPPFLAGS="$old_CPPFLAGS"
+      LDFLAGS="$old_LDFLAGS"
+   fi
+   JPEG_ENABLED="-DUSE_JPEG"
 
-AC_SUBST(ZLIB_ENABLED,$ZLIB_ENABLED)
-AC_SUBST(ZLIB_INC,    $ZLIB_INC)
-AC_SUBST(ZLIB_LIB,    $ZLIB_LIB)
+   ALL_ENABLED="$JPEG_ENABLED $ALL_ENABLED"
+   ALL_INC="$ALL_INC $JPEG_INC"
+   ALL_LIB="$ALL_LIB $JPEG_LIB -ljpeg"
+   AC_SUBST(JPEG_ENABLED, "$JPEG_ENABLED")
+   AC_SUBST(JPEG_INC,    "$JPEG_INC")
+   AC_SUBST(JPEG_LIB,    "$JPEG_LIB -ljpeg")
 
-ALL_ENABLED="$ZLIB_ENABLED $ALL_ENABLED"
-ALL_INC="$ZLIB_INC $ALL_INC"
-ALL_LIB="$ZLIB_LIB $ALL_LIB"
+])
 
 dnl ---------------------------------------------------------------------
 dnl Check where PNG is installed
 dnl ---------------------------------------------------------------------
 
-unset ac_cv_lib_png_png_init_io
-
-AC_ARG_WITH(png,
-[  --with-png=DIR          GD: Specify where PNG is installed (DIR is path to
-                              PNG install dir).],
-    PNG_DIR=$withval,PNG_DIR='')
-
-AC_EXPAND_PATH($PNG_DIR, PNG_DIR)
-AC_CHECKING(where PNG is installed)
-PNG_LIB=''
-PNG_INC=''
-PNG_ENABLED=''
-
-
-if test -n "$PNG_DIR" ; then
-    test -f $PNG_DIR/lib/libpng.a -o -f $PNG_DIR/lib/libpng.so -o -f $PNG_DIR/lib/libpng.sl -o -f $PNG_DIR/lib/libpng.dylib && PNG_LIBDIR="$PNG_DIR/lib"
-    test -f $PNG_DIR/lib64/libpng.a -o -f $PNG_DIR/lib64/libpng.so -o -f $PNG_DIR/lib64/libpng.sl -o -f $PNG_DIR/libpng.dylib && PNG_LIBDIR="$PNG_DIR/lib64"
-    test -f $PNG_DIR/libpng.a -o -f $PNG_DIR/libpng.so -o -f $PNG_DIR/libpng.sl -o -f $PNG_DIR/libpng.dylib && PNG_LIBDIR="$PNG_DIR"
-    test -f $PNG_DIR/include/png.h && PNG_INCLUDE="$PNG_DIR/include"
-    test -f $PNG_DIR/lib/png.h && PNG_INCLUDE="$PNG_DIR/lib"
-    test -f $PNG_DIR/png.h && PNG_INCLUDE="$PNG_DIR"
-    
-    if test -n "$PNG_LIBDIR" ; then   
-      PNG_LIB="-L$PNG_LIBDIR -lpng"
-      AC_MSG_RESULT([        using libpng from $PNG_LIB])
-      AC_ADD_RUNPATH("$PNG_LIBDIR")
-    else
-      AC_MSG_ERROR([cannot find png lib in $PNG_DIR])
-    fi
-    
-    if test -n "$PNG_INCLUDE" ; then
-      dnl make sure we'll be able to find zlib.h
-      old_cflags="$CFLAGS"
-      CFLAGS="$ZLIB_INC $CFLAGS"
-      AC_CHECK_HEADER([$PNG_INCLUDE/png.h],PNG_INC=-I$PNG_INCLUDE,
-        [AC_MSG_ERROR([cannot find png headers])])
-      CFLAGS="$old_cflags"
-      ALL_INC="$PNG_INC $ALL_INC"
-    else
-        AC_MSG_ERROR([cannot find png headers in $PNG_DIR])
-    fi
-    PNG_ENABLED="-DUSE_PNG"
-else
-
-  dnl check for png in system locations
-
-  AC_CHECK_LIB(png, png_init_io, PNG_LIB="-lpng",, $ZLIB_LIB)
-  AC_CHECK_HEADER([png.h],,
-        [AC_MSG_ERROR([cannot find png headers in system path])])
-  if test -n "$PNG_LIB" ; then
-    AC_MSG_RESULT([        using libpng from system libs.])
-  else
-    AC_MSG_ERROR([PNG (libpng) library cannot be found. install or reconfigure with --with-png=DIR])
-  fi
-  PNG_ENABLED="-DUSE_PNG"
-fi
-
-AC_CHECK_HEADER([setjmp.h],,
-        [AC_MSG_ERROR([setjmp.h is required with libpng])])
-
-ALL_ENABLED="$PNG_ENABLED $ALL_ENABLED"
-AC_SUBST(PNG_ENABLED, $PNG_ENABLED)
-AC_SUBST(PNG_INC,    $PNG_INC)
-AC_SUBST(PNG_LIB,    $PNG_LIB)
+MS_CHECK_PNG
 
 
 dnl ---------------------------------------------------------------------
 dnl Check where GIF is installed
 dnl ---------------------------------------------------------------------
 
-AC_ARG_WITH(gif,
-[  --with-gif=DIR          Specify where GIF is installed (DIR is path to
-                              GIF install dir).],
-    GIF_DIR=$withval,GIF_DIR='')
-
-AC_EXPAND_PATH($GIF_DIR, GIF_DIR)
-AC_CHECKING(where GIF is installed)
-GIF_LIB=''
-GIF_INC=''
-GIF_ENABLED=''
-
-
-if test -n "$GIF_DIR" -a "GIF_DIR" != "yes" ; then
-    test -f $GIF_DIR/lib/libgif.a -o -f $GIF_DIR/lib/libgif.so -o -f $GIF_DIR/lib/libgif.sl -o -f $GIF_DIR/lib/libgif.dylib && GIF_LIBDIR="$GIF_DIR/lib"
-    test -f $GIF_DIR/lib64/libgif.a -o -f $GIF_DIR/lib64/libgif.so -o -f $GIF_DIR/lib64/libgif.sl -o -f $GIF_DIR/libgif.dylib && GIF_LIBDIR="$GIF_DIR/lib64"
-    test -f $GIF_DIR/libgif.a -o -f $GIF_DIR/libgif.so -o -f $GIF_DIR/libgif.sl -o -f $GIF_DIR/libgif.dylib && GIF_LIBDIR="$GIF_DIR"
-    test -f $GIF_DIR/include/gif_lib.h && GIF_INCLUDE="$GIF_DIR/include"
-    test -f $GIF_DIR/lib/gif_lib.h && GIF_INCLUDE="$GIF_DIR/lib"
-    test -f $GIF_DIR/gif_lib.h && GIF_INCLUDE="$GIF_DIR"
-    
-    if test -n "$GIF_LIBDIR" ; then   
-      GIF_LIB="-L$GIF_LIBDIR -lgif"
-      AC_MSG_RESULT([        using libgif from $GIF_LIB])
-      AC_ADD_RUNPATH("$GIF_LIBDIR")
-    else
-      AC_MSG_ERROR([cannot find gif lib in $GIF_DIR])
-    fi
-    
-    if test -n "$GIF_INCLUDE" ; then
-      AC_CHECK_HEADER([$GIF_INCLUDE/gif_lib.h],GIF_INC=-I$GIF_INCLUDE,
-        [AC_MSG_ERROR([cannot find gif headers])])
-      ALL_INC="$GIF_INC $ALL_INC"
-    else
-        AC_MSG_ERROR([cannot find gif headers in $GIF_DIR])
-    fi
-    GIF_ENABLED="-DUSE_GIF"
-else
-
-  dnl check for gif in system locations
-
-  AC_CHECK_LIB(gif, DGifOpenFileHandle, GIF_LIB="-lgif",,)
-  AC_CHECK_HEADER([gif_lib.h],,
-        [AC_MSG_ERROR([cannot find gif headers in system path])])
-  if test -n "$GIF_LIB" ; then
-    AC_MSG_RESULT([        using libgif from system libs.])
-  else
-    AC_MSG_ERROR([GIF (libgif) library cannot be found. install or reconfigure with --with-gif=DIR])
-  fi
-  GIF_ENABLED="-DUSE_GIF"
-fi
-
-ALL_ENABLED="$GIF_ENABLED $ALL_ENABLED"
-AC_SUBST(GIF_ENABLED, $GIF_ENABLED)
-AC_SUBST(GIF_INC,    $GIF_INC)
-AC_SUBST(GIF_LIB,    $GIF_LIB)
-
-
-dnl ---------------------------------------------------------------------
-dnl libJPEG (included by default if found on system).
-dnl ---------------------------------------------------------------------
-
-unset ac_cv_lib_jpeg_jpeg_read_header
-
-AC_CHECKING(whether we should include JPEG support)
-AC_ARG_WITH(jpeg,
-[  --with-jpeg[[=DIR]]       Include JPEG support (DIR is LibJPEG's install dir).],,)
-
-if test -n "$with_jpeg" -a "$with_jpeg" != "yes" ; then
-
-  AC_EXPAND_PATH($with_jpeg, JPEG_DIR)
-  test -f $JPEG_DIR/include/jpeg/jpeglib.h && JPEG_INCLUDE="$JPEG_DIR/include/jpeg"
-  test -f $JPEG_DIR/include/jpeglib.h && JPEG_INCLUDE="$JPEG_DIR/include"
-  test -f $JPEG_DIR/lib/jpeglib.h && JPEG_INCLUDE="$JPEG_DIR/lib"
-  test -f $JPEG_DIR/jpeglib.h && JPEG_INCLUDE="$JPEG_DIR"
-
-  test -f $JPEG_DIR/lib/libjpeg.a && JPEG_LIBDIR="$JPEG_DIR/lib"
-  test -f $JPEG_DIR/lib64/libjpeg.a && JPEG_LIBDIR="$JPEG_DIR/lib64"
-  test -f $JPEG_DIR/libjpeg.a && JPEG_LIBDIR="$JPEG_DIR"
-
-  test -f $JPEG_DIR/lib/libjpeg.so -o -f $JPEG_DIR/lib/libjpeg.sl -o -f $JPEG_DIR/lib/libjpeg.dylib && JPEG_LIBDIR="$JPEG_DIR/lib"
-  test -f $JPEG_DIR/lib64/libjpeg.so -o -f $JPEG_DIR/lib64/libjpeg.sl && JPEG_LIBDIR="$JPEG_DIR/lib64"
-  test -f $JPEG_DIR/libjpeg.so -o -f $JPEG_DIR/libjpeg.sl -o -f $JPEG_DIR/libjpeg.dylib && JPEG_LIBDIR="$JPEG_DIR"
-
-  if test -n "$JPEG_INCLUDE" -a -n "$JPEG_LIBDIR" ; then
-      JPEG_INC=-I$JPEG_INCLUDE
-      JPEG_LIB="-L$JPEG_LIBDIR -ljpeg"
-      AC_ADD_RUNPATH("$JPEG_LIBDIR")
-  else
-        AC_MSG_ERROR("Could not find jpeglib.h or libjpeg.a/libjpeg.so/libjpeg.dylib in $JPEG_DIR.")
-  fi
-
-
-    _cppflags="$CPPFLAGS"
-    _ldflags="$LDFLAGS"
-    _libs="$LIBS"
-    CPPFLAGS="$JPEG_INC $CPPFLAGS"
-    LDFLAGS="$JPEG_LIB $LDFLAGS"
-    AC_CHECK_LIB(jpeg, jpeg_read_header,,AC_MSG_ERROR(["cannot link with libjpeg"]),,)
-    AC_CHECK_HEADER(jpeglib.h,,AC_MSG_ERROR(["cannot find jpeg headers"]))
-    JPEG_ENABLED="-DUSE_JPEG"
-    CPPFLAGS=$_cppflags
-    LDFLAGS=$_ldflags
-    LIBS=$_libs
-    AC_MSG_RESULT([        using libjpeg from system $JPEG_LIB])
-
-else
-    dnl Look for libjpeg in system dirs
-
-    AC_CHECK_LIB(jpeg, jpeg_read_header,,AC_MSG_ERROR(["cannot link with libjpeg"]),,)
-    AC_CHECK_HEADER(jpeglib.h,,AC_MSG_ERROR(["cannot find jpeg headers"]))
-    JPEG_ENABLED="-DUSE_JPEG"
-    JPEG_LIB="-ljpeg"
-    AC_MSG_RESULT([        using libjpeg from system libs.])
-fi
-
-AC_SUBST(JPEG_ENABLED,$JPEG_ENABLED)
-AC_SUBST(JPEG_INC,    $JPEG_INC)
-AC_SUBST(JPEG_LIB,    $JPEG_LIB)
-
-dnl ---------------------------------------------------------------------
-dnl Look for X11 and XPM libs used by GD
-dnl ---------------------------------------------------------------------
-
-unset ac_cv_lib_Xpm_XpmFreeXpmImage
-
-AC_ARG_WITH(xpm,
-[  --with-xpm=DIR          GD: Specify where libXpm is installed (DIR it the 
-                              libXpm install prefix).],
-    XPM_DIR=$withval,XPM_DIR='')
-
-if test "$with_xpm" != "no" ; then
-
-  AC_EXPAND_PATH($XPM_DIR, XPM_DIR)
-  AC_CHECKING(where libXpm is installed)
-  XPM_LIB=''
-
-  test -f $XPM_DIR/lib/libXpm.a -o -f $XPM_DIR/lib/libXpm.so -o -f $XPM_DIR/lib/libXpm.sl -o -f $XPM_DIR/lib/libXpm.dylib && XPM_LIBDIR="$XPM_DIR/lib"
-  test -f $XPM_DIR/lib64/libXpm.a -o -f $XPM_DIR/lib64/libXpm.so -o -f $XPM_DIR/lib64/libXpm.sl && XPM_LIBDIR="$XPM_DIR/lib64"
-  test -f $XPM_DIR/libXpm.a -o -f $XPM_DIR/libXpm.so -o -f $XPM_DIR/libXpm.sl -o -f $XPM_DIR/libXpm.dylib && XPM_LIBDIR="$XPM_DIR"
-
-  if test -n "$XPM_LIBDIR" ; then
-
-    XPM_LIB="-L$XPM_LIBDIR -lXpm -lX11"
-    AC_MSG_RESULT([        using libXpm from $XPM_LIB])
-    AC_ADD_RUNPATH("$XPM_LIBDIR")
-
-  else
-  
-    dnl check for lib in system libs
-
-    AC_CHECK_LIB(Xpm, XpmFreeXpmImage, XPM_LIB="-lXpm -lX11",,-lX11)
-
-    if test -n "$XPM_LIB" ; then
-      AC_MSG_RESULT([        using libXpm from system libs.])
-    else
-      AC_MSG_RESULT([        XPM (libXpm) library cannot be found, possibly needed for GD])
-    fi
-  fi
+AC_MSG_CHECKING(whether we should include GIF support)
+AC_DEFUN([MS_CHECK_GIF],[
+   AC_ARG_WITH(gif,
+      AC_HELP_STRING([--with-gif], [libgif location: [yes|no|/path/to/gif/prefix]]),
+      [],
+      [with_gif=yes])
+   if test x"$with_gif" == "xno"; then
+      AC_SUBST(GIF_ENABLED, "")
+      AC_SUBST(GIF_INC,    "")
+      AC_SUBST(GIF_LIB,    "")
+      AC_MSG_RESULT([no])
+   else
+      AC_MSG_RESULT([yes])
+      if test -z "$with_gif" -o "$with_gif" == "yes" -o "$with_gif" == "/usr"; then
+         AC_CHECK_HEADER([gif_lib.h],[:],
+                      [AC_MSG_ERROR([gif_lib.h header not found. install gif development package, or reconfigure with --with-gif=/path/to/gif/prefix])])
+         AC_CHECK_LIB([gif], [DGifOpenFileHandle],[:],
+                      [AC_MSG_ERROR([libgif library not found. install gif development package, or reconfigure with --with-gif=/path/to/gif/prefix])])
 
-fi
+      else
+         old_LDFLAGS="$LDFLAGS"
+         old_CPPFLAGS="$CPPFLAGS"
+
+         CPPFLAGS="-I$with_gif/include"
+         LDFLAGS="-L$with_gif/lib"
+         
+         AC_CHECK_HEADER([gif_lib.h],[:],
+                      [AC_MSG_ERROR([gif_lib.h header not found in $with_gif. install gif development package, or reconfigure with --with-gif=/path/to/gif/prefix])])
+         AC_CHECK_LIB([gif], [DGifOpenFileHandle],[:],
+                      [AC_MSG_ERROR([libgif library not found in $with_gif. install gif development package, or reconfigure with --with-gif=/path/to/gif/prefix])])
+         GIF_INC="$CPPFLAGS"
+         GIF_LIB="$LDFLAGS"
+         CPPFLAGS="$old_CPPFLAGS"
+         LDFLAGS="$old_LDFLAGS"
+      fi
+      GIF_ENABLED="-DUSE_GIF"
+
+      ALL_ENABLED="$GIF_ENABLED $ALL_ENABLED"
+      ALL_INC="$ALL_INC $GIF_INC"
+      ALL_LIB="$ALL_LIB $GIF_LIB -lgif"
+      AC_SUBST(GIF_ENABLED, "$GIF_ENABLED")
+      AC_SUBST(GIF_INC,    "$GIF_INC")
+      AC_SUBST(GIF_LIB,    "$GIF_LIB -lgif")
+   fi
+])
 
-dnl Note: don't include iconv by default in GD_XTRA_LIBS as it may not
-dnl       be required by GD.
+MS_CHECK_GIF
 
-GD_XTRA_LIBS="$JPEG_LIB $FT_LIB $PNG_LIB $ZLIB_LIB $XPM_LIB"
+AC_CHECKING([for jpeg library location (mandatory)])
+MS_CHECK_JPEG
 
 
 dnl ---------------------------------------------------------------------
@@ -526,7 +378,7 @@ AC_CHECKING(where libiconv is installed)
 
 ICONV_LIB=''
 
-if test -n "$ICONV_DIR" ; then
+if test -n "$ICONV_DIR" -a "$ICONV_DIR" != "yes" ; then
 
   AC_EXPAND_PATH($ICONV_DIR, ICONV_DIR)
 
@@ -588,275 +440,110 @@ ALL_LIB="$ICONV_LIB $ALL_LIB"
 dnl ---------------------------------------------------------------------
 dnl Find GD library
 dnl
-dnl If --with-gd not given, then check in system libs.
 dnl ---------------------------------------------------------------------
 
-dnl We don't want LIBS updated by all the GD stuff, so we save it and
-dnl restore later.
-
-ms_saved_LIBS="$LIBS"
-IS_GD2="false";
-
-dnl Clear some cache variables
-unset ac_cv_lib_gd_gdImageCreate
-unset ac_cv_lib_gd_gdImageString16
-unset ac_cv_lib_gd_gdImageGif
-unset ac_cv_lib_gd_gdImagePng
-unset ac_cv_lib_gd_gdImageJpeg
-unset ac_cv_lib_gd_gdImageWBMP
-unset ac_cv_lib_gd_gdImageStringFT
-unset ac_cv_lib_gd_gdImageGifPtr
-unset ac_cv_lib_gd_gdFontGetTiny
-unset ac_cv_lib_c_gdImageCreate
-unset ac_cv_lib_c_gdImageString16
-unset ac_cv_lib_c_gdImageGif
-unset ac_cv_lib_c_gdImagePng
-unset ac_cv_lib_c_gdImageJpeg
-unset ac_cv_lib_c_gdImageWBMP
-unset ac_cv_lib_c_gdImageStringFT
-unset ac_cv_lib_c_gdImageGifPtr
-unset ac_cv_lib_c_gdFontGetTiny
-unset ac_cv_lib_gd_gdImageCreatePaletteFromTrueColor
-
-AC_CHECKING(for GD 2.0.28 or higher)
-AC_ARG_WITH(gd,
-[  --with-gd[[=[static,]DIR]]
-                          Specify which version of GD to use (DIR is GD's
-                          install dir).],,)
-
-if test "$with_gd" = "no" ; then
-  AC_MSG_ERROR(GD library cannot be disabled)
-elif test -n "$with_gd" -a "$with_gd" != "yes" ; then
-  dnl
-  dnl --with-gd was specified explicitly... 
-  dnl
-  AC_PARSE_WITH_LIB_STATIC($with_gd, GD_DIR, GD_STATIC)
-  AC_EXPAND_PATH($GD_DIR, GD_DIR)
-  test -f $GD_DIR/include/gd.h && GD_INCLUDE="$GD_DIR/include"
-  test -f $GD_DIR/include/gd/gd.h && GD_INCLUDE="$GD_DIR/include/gd"
-  test -f $GD_DIR/gd.h && GD_INCLUDE="$GD_DIR"
-
-  test -f $GD_DIR/lib/libgd.a && GD_LIBDIR="$GD_DIR/lib"
-  test -f $GD_DIR/lib64/libgd.a && GD_LIBDIR="$GD_DIR/lib64"
-  test -f $GD_DIR/.libs/libgd.a && GD_LIBDIR="$GD_DIR/.libs"
-  test -f $GD_DIR/_libs/libgd.a && GD_LIBDIR="$GD_DIR/_libs"
-  test -f $GD_DIR/libgd.a && GD_LIBDIR="$GD_DIR"
-
-  test -f $GD_DIR/lib/libgd.so -o -f $GD_DIR/lib/libgd.sl -o -f $GD_DIR/lib/libgd.dylib && GD_LIBDIR="$GD_DIR/lib"
-  test -f $GD_DIR/lib64/libgd.so -o -f $GD_DIR/lib/libgd.sl && GD_LIBDIR="$GD_DIR/lib64"
-  test -f $GD_DIR/.libs/libgd.so -o -f $GD_DIR/.libs/libgd.sl -o -f $GD_DIR/.libs/libgd.dylib && GD_LIBDIR="$GD_DIR/.libs"
-  test -f $GD_DIR/_libs/libgd.so -o -f $GD_DIR/_libs/libgd.sl -o -f $GD_DIR/_libs/libgd.dylib && GD_LIBDIR="$GD_DIR/_libs"
-  test -f $GD_DIR/libgd.so -o -f $GD_DIR/libgd.sl -o -f $GD_DIR/libgd.dylib && GD_LIBDIR="$GD_DIR"
-
-  dnl make sure it is GD 2.0.28+ with antialias and gdFontCacheSetup() and gdImageCreatePaletteFromTrueColor support
-  AC_CHECK_LIB(gd, gdImageCreatePaletteFromTrueColor,IS_GD2="true",,$GD_XTRA_LIBS -L$GD_LIBDIR)
-
-  if test "$IS_GD2" = "false" -a -n "$ICONV_LIB"; then
-    dnl try again including libiconv this time
-    unset ac_cv_lib_gd_gdImageCreatePaletteFromTrueColor
-    AC_CHECKING(whether GD needs libiconv)
-    AC_CHECK_LIB(gd, gdImageCreatePaletteFromTrueColor,IS_GD2="true",,$GD_XTRA_LIBS -L$GD_LIBDIR $ICONV_LIB)
-    GD_NEED_ICONV_LIB="$ICONV_LIB"
-  fi
-
-  if test -n "$GD_INCLUDE" -a -n "$GD_LIBDIR" -a "$IS_GD2" = "true"; then
-      GD_INC=-I$GD_INCLUDE
-      GD_LIB="-L$GD_LIBDIR -lgd"
-      GD_XTRA_LIBS="$GD_XTRA_LIBS $GD_NEED_ICONV_LIB"
-      AC_MSG_RESULT([        using libgd 2.0.28 (or higher) from $GD_LIB $GD_XTRA_LIBS])
-      AC_ADD_RUNPATH("$GD_LIBDIR")
-  else
-      AC_MSG_ERROR([Could not find gd.h or libgd.a/libgd.so in $GD_DIR.  Make sure GD 2.0.28 or higher is compiled before calling configure. You may also get this error if you didn't specify the appropriate location for one of GD's dependencies (freetype, libpng, libjpeg or libiconv).])
-  fi
-else
-  dnl  --with-gd specified without a DIR, look for gd in system dirs /usr or /usr/local
-  FOUND_GD="false"
-  for GD_DIR in /usr /usr/local
-  do
-    test -f $GD_DIR/include/gd.h && GD_INCLUDE="$GD_DIR/include"
-    test -f $GD_DIR/lib/libgd.a && GD_LIBDIR="$GD_DIR/lib"
-    test -f $GD_DIR/lib64/libgd.a && GD_LIBDIR="$GD_DIR/lib64"
-    test -f $GD_DIR/lib/libgd.so -o -f $GD_DIR/lib/libgd.sl -o -f $GD_DIR/lib/libgd.dylib && GD_LIBDIR="$GD_DIR/lib"
-    test -f $GD_DIR/lib64/libgd.so -o -f $GD_DIR/lib/libgd.sl && GD_LIBDIR="$GD_DIR/lib64"
-
-    dnl make sure it is GD 2.0.28 or higher
-    AC_CHECK_LIB(gd, gdImageCreatePaletteFromTrueColor, IS_GD2="true",,$GD_XTRA_LIBS)
- 
-    if test "$IS_GD2" = "false" -a -n "$ICONV_LIB"; then
-      dnl try again including libiconv this time
-      AC_CHECKING(whether GD needs libiconv)
-      unset ac_cv_lib_gd_gdImageCreatePaletteFromTrueColor
-      AC_CHECK_LIB(gd, gdImageCreatePaletteFromTrueColor,IS_GD2="true",,$GD_XTRA_LIBS $ICONV_LIB)
-      GD_NEED_ICONV_LIB="$ICONV_LIB"
-    fi
-
-    if test -n "$GD_INCLUDE" -a -n "$GD_LIBDIR" -a "$IS_GD2" = "true"; then
-      GD_INC=-I$GD_INCLUDE
-      GD_LIB="-L$GD_LIBDIR -lgd"
-      GD_XTRA_LIBS="$GD_XTRA_LIBS $GD_NEED_ICONV_LIB"
-      AC_MSG_RESULT([        using libgd 2.0.28 (or higher) from system libs ($GD_LIB $GD_XTRA_LIBS).])
-      AC_ADD_RUNPATH("$GD_LIBDIR")
-      FOUND_GD="true"
-      break;
-    fi
-  done
-
-  if test "$FOUND_GD" = "false" ; then
-    AC_MSG_ERROR([Could not find gd.h or libgd.a/libgd.so in $GD_DIR.  Make sure GD 2.0.28 or higher is compiled before calling configure. You may also get this error if you didn't specify the appropriate location for one of GD's dependencies (freetype, libpng, libjpeg or libiconv).])
-  fi
-fi
-
-dnl ----------------------------------------------------------------------
-dnl Continue with GD processing - determine GD formats and other features
-dnl ----------------------------------------------------------------------
-
-if test -n "$with_gd" -a "$with_gd" != "yes" ; then
 
-  dnl check gd lib that was found on --with-gd=
-  
-  if test "$GD_STATIC" = "yes" ; then
-    dnl To test against static GD, do AC_CHECK_LIB calls against -lc and
-    dnl include libgd.a in GD_LIB param
-    GD_CHECKLIB=c
-    GD_LIB=$GD_LIBDIR/libgd.a
-    GD_STATIC=$GD_LIBDIR/libgd.a
-    AC_MSG_RESULT([static linkage of $GD_STATIC requested... testing supported formats...])
-  else
-    GD_CHECKLIB=c
-    # GD_LIB was already set above
-    GD_STATIC=""
-  fi
-  
-  AC_CHECK_LIB($GD_CHECKLIB, gdImageGif, GD_DEF="$GD_DEF -DUSE_GD_GIF",, $GD_STATIC $GD_LIB $GD_XTRA_LIBS)
-  AC_CHECK_LIB($GD_CHECKLIB, gdImagePng, GD_DEF="$GD_DEF -DUSE_GD_PNG",, $GD_STATIC $GD_LIB $GD_XTRA_LIBS)
-  AC_CHECK_LIB($GD_CHECKLIB, gdImageJpeg, GD_DEF="$GD_DEF -DUSE_GD_JPEG",, $GD_STATIC $GD_LIB $GD_XTRA_LIBS)
-  AC_CHECK_LIB($GD_CHECKLIB, gdImageWBMP, GD_DEF="$GD_DEF -DUSE_GD_WBMP",, $GD_STATIC $GD_LIB $GD_XTRA_LIBS)
-
-  dnl check for Freetype 2.x support
-  GD_FT_SUPPORT=no  
-  AC_CHECK_LIB($GD_CHECKLIB, gdImageStringFT, GD_FT_SUPPORT=yes,, $GD_STATIC $GD_LIB $GD_XTRA_LIBS)
-
-  dnl If GD static is requested, it may needs libfontconfig.
-  if test -n "$GD_STATIC" ; then
-     GD_LIB="$GD_LIB -lfontconfig"
-     unset ac_cv_lib_c___gdImageStringFT
-     AC_CHECK_LIB($GD_CHECKLIB, gdImageStringFT, GD_FT_SUPPORT=yes,, $GD_STATIC $GD_LIB $GD_XTRA_LIBS)
-  fi
-
-  if test "$GD_FT_SUPPORT" = "yes"; then
-     GD_DEF="$GD_DEF -DUSE_GD_FT"
-  fi
-
-  dnl check for Resolution support
-  GD_RESOLUTION_SUPPORT=no  
-  AC_CHECK_LIB($GD_CHECKLIB, gdImageSetResolution, GD_RESOLUTION_SUPPORT=yes,, $GD_STATIC $GD_LIB $GD_XTRA_LIBS)
-
-  if test "$GD_RESOLUTION_SUPPORT" = "yes"; then
-     GD_DEF="$GD_DEF -DUSE_GD_RESOLUTION"
-  fi
-
-  dnl check for gdImageOpenPolygon (means GD version 2.0.29 or higher)
-  AC_CHECK_LIB($GD_CHECKLIB, gdImageOpenPolygon, GD_DEF="$GD_DEF -DGD_HAS_FTEX_XSHOW",, $GD_STATIC $GD_LIB $GD_XTRA_LIBS)
-
-  dnl gdImageGifPtr is there only in GIF-patched GD versions
-  AC_CHECK_LIB($GD_CHECKLIB, gdImageGifPtr, GD_DEF="$GD_DEF -DGD_HAS_GDIMAGEGIFPTR",, $GD_STATIC $GD_LIB $GD_XTRA_LIBS)
-
-  dnl GD 2.0.22 and more recent replaced the static font pointers with 
-  dnl getter functions.
-  AC_CHECK_LIB($GD_CHECKLIB, gdFontGetTiny, GD_DEF="$GD_DEF -DGD_HAS_GETBITMAPFONTS",, $GD_STATIC $GD_LIB $GD_XTRA_LIBS)
-
-  dnl check for gdImageGetTrueColorPixel.
-  dnl In some GD versions this function is defined, but not declared in gd.h,
-  dnl so check headers first
-  GD_HAS_GET_TRUE_COLOR_PIXEL=
-
-  dnl AC_CHECK_DECL needs to know the gd include path
-  CFLAGS_BACKUP="$CFLAGS"
-  CXXFLAGS_BACKUP="$CXXFLAGS"
-  CFLAGS="$CFLAGS $GD_INC"
-  CXXFLAGS="$CXXFLAGS $GD_INC"
-  AC_CHECK_DECL(gdImageGetTrueColorPixel,[GD_HAS_GET_TRUE_COLOR_PIXEL=yes],,[#include <gd.h>])
-  CFLAGS="$CFLAGS_BACKUP"
-  CXXFLAGS="$CXXFLAGS_BACKUP"
-
-  dnl if it's declared, check if we can link with it
-  if test .$GD_HAS_GET_TRUE_COLOR_PIXEL = .yes ; then
-    AC_CHECK_LIB($GD_CHECKLIB, gdImageGetTrueColorPixel, GD_DEF="$GD_DEF -DGD_HAS_GET_TRUE_COLOR_PIXEL",, $GD_STATIC $GD_LIB $GD_XTRA_LIBS)
-  fi
-
-  AC_MSG_RESULT([        using GD ($GD_DEF) from $GD_DIR.])
-
-else
-
-  dnl
-  dnl --with-gd was not given... then look in system libs
-  dnl
-
-  dnl Make sure GD is at least there!
-  AC_CHECK_LIB(gd, gdImageCreate, GD_FOUND=yes , ,$GD_XTRA_LIBS)
-  if test -z "$GD_FOUND" ; then
-      AC_MSG_ERROR([GD is required but was not found... use --with-gd=DIR to specify its location.])
-  fi
-
-  dnl Check supported formats
-  AC_CHECK_LIB(gd, gdImageGif, GD_DEF="$GD_DEF -DUSE_GD_GIF",, $GD_LIB $GD_XTRA_LIBS)
-  AC_CHECK_LIB(gd, gdImagePng, GD_DEF="$GD_DEF -DUSE_GD_PNG",, $GD_LIB $GD_XTRA_LIBS)
-  AC_CHECK_LIB(gd, gdImageJpeg, GD_DEF="$GD_DEF -DUSE_GD_JPEG",, $GD_LIB $GD_XTRA_LIBS)
-  AC_CHECK_LIB(gd, gdImageWBMP, GD_DEF="$GD_DEF -DUSE_GD_WBMP",, $GD_LIB $GD_XTRA_LIBS)
-
-  dnl Check for Freetype 2 support
-  AC_CHECK_LIB(gd, gdImageStringFT, GD_DEF="$GD_DEF -DUSE_GD_FT",, $GD_LIB $GD_XTRA_LIBS)
-
-  dnl check for gdImageOpenPolygon (means GD version 2.0.29 or higher)
-  AC_CHECK_LIB(gd, gdImageOpenPolygon, GD_DEF="$GD_DEF -DGD_HAS_FTEX_XSHOW",, $GD_STATIC $GD_LIB $GD_XTRA_LIBS)
-
-  dnl gdImageGifPtr is there only in GIF-patched GD versions
-  AC_CHECK_LIB(gd, gdImageGifPtr, GD_DEF="$GD_DEF -DGD_HAS_GDIMAGEGIFPTR",, $GD_LIB $GD_XTRA_LIBS)
+AC_DEFUN([MS_CHECK_GD],[
+   AC_ARG_WITH(gd,
+      AC_HELP_STRING([--with-gd], [libgd location: [yes|no|/path/to/gdlib-config]]),
+      [],
+      [with_gd=no])
+
+   if test x"$with_gd" == "xno"; then
+      AC_SUBST(GD_ENABLED, "")
+      AC_SUBST(GD_INC, "")
+      AC_SUBST(GD_LIB, "")
+      AC_MSG_RESULT([GD support not requested, disabling])
+   else
+      if test "$with_gd" == "yes"; then
+         AC_PATH_PROG(GDCONFIG,gdlib-config,no)
+         if test "$GDCONFIG" == "no"; then
+            AC_MSG_ERROR([gdlib-config not found in path, reconfigure with --with-gd=/path/to/gdlib-config])
+         fi
+      else
+         if test ! -f "$with_gd"; then
+            if test ! -d "$with_gd"; then
+               AC_MSG_ERROR([cannot find $with_gd])
+            fi
+            if test ! -f "$with_gd/bin/gdlib-config"; then
+               AC_MSG_ERROR([gdlib-config not found in $with_gd (tried $with_gd/bin/gdlib-config)])
+            else
+               GDCONFIG="$with_gd/bin/gdlib-config"
+            fi
+         else
+            GDCONFIG="$with_gd"
+         fi
+         AC_PATH_PROG(GDCONFIG,$GDCONFIG,no)
+         if test "$GDCONFIG" == "no"; then
+            AC_MSG_ERROR([gdlib-config not usable, reconfigure with --with-gd[=(yes|no|/path/to/gdlib-config)]])
+         fi
+      fi
 
-  dnl GD 2.0.22 and more recent replaced the static font pointers with 
-  dnl getter functions.
-  AC_CHECK_LIB(gd, gdFontGetTiny, GD_DEF="$GD_DEF -DGD_HAS_GETBITMAPFONTS",, $GD_LIB $GD_XTRA_LIBS)
+      GDMAJOR=`$GDCONFIG --majorversion`
+      GDMINOR=`$GDCONFIG --minorversion`
+      GDREV=`$GDCONFIG --revision`
+      GDVERSION=`$GDCONFIG --version`
+      GDFEATURES=`$GDCONFIG --features`
+      AC_MSG_RESULT([using libgd $GDVERSION from $GDCONFIG])
+      
+      if test -z "`echo $GDFEATURES | grep 'GD_PNG'`"  ; then
+         AC_MSG_ERROR([supplied GD is missing PNG support])
+      else
+         GD_ENABLED="$GD_ENABLED -DUSE_GD_PNG"
+      fi
+      if test -z "`echo $GDFEATURES | grep 'GD_JPEG'`"  ; then
+         AC_MSG_ERROR([supplied GD is missing JPEG support])
+      else
+         GD_ENABLED="$GD_ENABLED -DUSE_GD_JPEG"
+      fi
+      if test -z "`echo $GDFEATURES | grep 'GD_GIF'`"  ; then
+         AC_MSG_ERROR([supplied GD is missing GIF support])
+      else
+         GD_ENABLED="$GD_ENABLED -DUSE_GD_GIF"
+      fi
+      if test -z "`echo $GDFEATURES | grep 'GD_FREETYPE'`"  ; then
+         AC_MSG_ERROR([supplied GD is missing FT support])
+      fi
 
-  dnl check for Resolution support
-  GD_RESOLUTION_SUPPORT=no  
-  AC_CHECK_LIB($GD_CHECKLIB, gdImageSetResolution, GD_RESOLUTION_SUPPORT=yes,, $GD_STATIC $GD_LIB $GD_XTRA_LIBS)
 
-  if test "$GD_RESOLUTION_SUPPORT" = "yes"; then
-     GD_DEF="$GD_DEF -DUSE_GD_RESOLUTION"
-  fi
 
-  dnl check for gdImageGetTrueColorPixel.
-  dnl In some GD versions this function is defined, but not declared in gd.h,
-  dnl so check headers first
-  GD_HAS_GET_TRUE_COLOR_PIXEL=
-  AC_CHECK_DECL(gdImageGetTrueColorPixel,[GD_HAS_GET_TRUE_COLOR_PIXEL=yes],,[#include <gd.h>])
-  dnl if it's declared, check if we can link with it
-  if test .$GD_HAS_GET_TRUE_COLOR_PIXEL = .yes ; then
-    AC_CHECK_LIB(gd, gdImageGetTrueColorPixel, GD_DEF="$GD_DEF -DGD_HAS_GET_TRUE_COLOR_PIXEL",, $GD_STATIC $GD_LIB $GD_XTRA_LIBS)
-  fi
+      if test $GDMAJOR -lt 2 -o $GDMINOR -lt 0 -o $GDREV -lt 28 ; then
+         AC_MSG_ERROR([GD version $GDVERSION too old. need at least 2.0.28])
+      fi
 
-  if test -n "$GD_DEF" ; then
-      GD_LIB="-lgd $GD_LIB"
-      AC_MSG_RESULT([        using GD ($GD_DEF) from system libs.])
-  fi
-fi
 
-GD_LIB="$GD_LIB $GD_XTRA_LIBS"
+      dnl gdlib-config adds /usr/include and /usr/lib to the compile paths
+      dnl which we do not want, as they may take precedence on locally
+      dnl supplied paths for other libraries
 
-AC_SUBST(GD_DEF, $GD_DEF)
-AC_SUBST(GD_INC, $GD_INC)
-AC_SUBST(GD_LIB, $GD_LIB)
-AC_SUBST(GD_STATIC, $GD_STATIC)
-AC_SUBST(MAKE_GD, $MAKE_GD)
-AC_SUBST(MAKE_GD_CLEAN, $MAKE_GD_CLEAN)
+      dnl remove /usr/include/ from default include path
+      GD_INC=`$GDCONFIG --includedir`
+      if test "x$GD_INC" != "x/usr/include" -a "x$GD_INC" != "x/usr/include/" -a -n "$GD_INC"; then
+         GD_INC="-I$GD_INC"
+      else
+         GD_INC=""
+      fi
+      
+      dnl remove /usr/lib/ from default lib path
+      GD_LIB=`$GDCONFIG --libdir`
+      if test "x$GD_LIB" != "x/usr/lib" -a "x$GD_LIB" != "x/usr/lib/" -a -n "$GD_LIB"; then
+         GD_LIB="-L$GD_LIB"
+      else
+         GD_LIB=""
+      fi
+      
+      GD_ENABLED="-DUSE_GD $GD_ENABLED"
+      ALL_ENABLED="$GD_ENABLED $ALL_ENABLED"
+      AC_SUBST(GD_ENABLED, "$GD_ENABLED")
+      ALL_INC="$ALL_INC $GD_INC"
+      ALL_LIB="$ALL_LIB $GD_LIB -lgd"
+      AC_SUBST(GD_INC, "$GD_INC")
+      AC_SUBST(GD_LIB, "$GD_LIB -lgd")
+   fi
 
-ALL_ENABLED="$GD_DEF $ALL_ENABLED"
-ALL_INC="$GD_INC $ALL_INC"
-ALL_LIB="$GD_LIB $ALL_LIB"
-ALL_STATIC_LIB="$GD_STATIC $ALL_STATIC_LIB"
+])
 
-dnl Restore LIBS environment to state at beginning of gd tests.
-LIBS="$ms_saved_LIBS"
+MS_CHECK_GD
 
 
 dnl ---------------------------------------------------------------------
@@ -999,9 +686,9 @@ EXPAT_FOUND='no'
 
 
 if test -n "$EXPAT_DIR" ; then
-    test -f $EXPAT_DIR/lib/libexpat.a -o -f $EXPAT_DIR/lib/libexpat.so -o -f $EXPAT_DIR/lib/libexpat.sl -o -f $EXPAT_DIR/lib/libexpat.dylib && EXPAT_LIBDIR="$PNG_DIR/lib"
-    test -f $EXPAT_DIR/lib64/libexpat.a -o -f $EXPAT_DIR/lib64/libexpat.so -o -f $EXPAT_DIR/lib64/libexpat.sl -o -f $EXPAT_DIR/libexpat.dylib && EXPAT_LIBDIR="$PNG_DIR/lib64"
-    test -f $EXPAT_DIR/libexpat.a -o -f $EXPAT_DIR/libexpat.so -o -f $EXPAT_DIR/libexpat.sl -o -f $PNG_DIR/libexpat.dylib && EXPAT_LIBDIR="$PNG_DIR"
+    test -f $EXPAT_DIR/lib/libexpat.a -o -f $EXPAT_DIR/lib/libexpat.so -o -f $EXPAT_DIR/lib/libexpat.sl -o -f $EXPAT_DIR/lib/libexpat.dylib && EXPAT_LIBDIR="$EXPAT_DIR/lib"
+    test -f $EXPAT_DIR/lib64/libexpat.a -o -f $EXPAT_DIR/lib64/libexpat.so -o -f $EXPAT_DIR/lib64/libexpat.sl -o -f $EXPAT_DIR/libexpat.dylib && EXPAT_LIBDIR="$EXPAT_DIR/lib64"
+    test -f $EXPAT_DIR/libexpat.a -o -f $EXPAT_DIR/libexpat.so -o -f $EXPAT_DIR/libexpat.sl -o -f $EXPAT_DIR/libexpat.dylib && EXPAT_LIBDIR="$EXPAT_DIR"
     test -f $EXPAT_DIR/include/expat.h && EXPAT_INCDIR="$EXPAT_DIR/include"
     test -f $EXPAT_DIR/lib/expat.h && EXPAT_INCDIR="$EXPAT_DIR/lib"
     test -f $EXPAT_DIR/expat.h && EXPAT_INCDIR="$EXPAT_DIR"
@@ -1044,46 +731,7 @@ dnl ---------------------------------------------------------------------
 
 AC_MSG_CHECKING(for AGG support)
 AGG_ENABLED="internal"
-AC_MSG_RESULT([        yes])
-AGG_OBJ="renderers/agg/src/clipper.o renderers/agg/src/agg_arc.o renderers/agg/src/agg_curves.o renderers/agg/src/agg_vcgen_contour.o renderers/agg/src/agg_vcgen_dash.o renderers/agg/src/agg_vcgen_stroke.o renderers/agg/src/agg_image_filters.o renderers/agg/src/agg_line_aa_basics.o renderers/agg/src/agg_line_profile_aa.o renderers/agg/src/agg_sqrt_tables.o renderers/agg/src/agg_embedded_raster_fonts.o renderers/agg/src/agg_trans_affine.o renderers/agg/src/agg_vpgen_clip_polygon.o renderers/agg/src/agg_vpgen_clip_polyline.o renderers/agg/src/agg_font_freetype.o"
-AGG_LIB=""
-AGG_INC="-Irenderers/agg/include"
-ALL_INC="$AGG_INC $ALL_INC"
-
-dnl ---------------------------------------------------------------------
-dnl Optional AGG SVG Symbol Support.
-dnl ---------------------------------------------------------------------
-
-AC_MSG_CHECKING(if SVG Symbol support requested)
-AC_ARG_WITH(agg-svg-symbols,
-[  --with-agg-svg-symbols[[=yes/no]]
-                          Include AGG SVG symbol support (Requires expat).],,)
-
-dnl Check for expat availability
-
-if test "$with_agg_svg_symbols" != "no" ; then
-    if test "$EXPAT_FOUND" = "yes" ; then
-        dnl add SVG to the AGG build
-        AGG_OBJ="$AGG_OBJ renderers/agg/src/agg_svg_parser.o renderers/agg/src/agg_svg_path_renderer.o renderers/agg/src/agg_svg_path_tokenizer.o"
-        AGG_LIB="$AGG_LIB $EXPAT_LIB"
-        AC_SUBST(AGG_LIB, $AGG_LIB)
-        ALL_LIB="$AGG_LIB $ALL_LIB"
-        AGG_INC="$AGG_INC $EXPAT_INC"
-        AC_SUBST(AGG_INC, $AGG_INC)
-        ALL_INC="$AGG_INC $ALL_INC"
-        AGG_SVG_SYMBOLS_ENABLED="-DUSE_AGG_SVG_SYMBOLS"
-        ALL_ENABLED="$AGG_SVG_SYMBOLS_ENABLED $ALL_ENABLED"
-        AC_MSG_RESULT([        enabled])
-
-    else
-        AC_MSG_RESULT([        disabled due to missing expat dependency])
-    fi
-fi
-
-AC_SUBST(AGG_OBJ,    $AGG_OBJ)
-
-
-
+AC_MSG_RESULT([        internal])
 
 
 dnl ---------------------------------------------------------------------
@@ -1200,6 +848,16 @@ ALL_ENABLED="$THREAD_FLAG $ALL_ENABLED"
 ALL_LIB="$THREAD_LIB $ALL_LIB"
 
 dnl ---------------------------------------------------------------------
+dnl Check for the __sync_fetch_and_add builtin
+dnl ---------------------------------------------------------------------
+AC_CACHE_CHECK([for __sync_fetch_and_add], ac_cv_func_sync_fetch_and_add,
+[AC_TRY_LINK([],[int x;__sync_fetch_and_add(&x,1);],ac_cv_func_sync_fetch_and_add=yes,ac_cv_func_sync_fetch_and_add=no)])
+if test "$ac_cv_func_sync_fetch_and_add" = yes; then
+  ALL_ENABLED="-DHAVE_SYNC_FETCH_AND_ADD $ALL_ENABLED"
+  AC_DEFINE(HAVE_SYNC_FETCH_AND_ADD,1,[Define if you have the __sync_fetch_and_add function])
+fi
+
+dnl ---------------------------------------------------------------------
 dnl Find ESRI SDE ONLY IF REQUESTED.
 dnl ---------------------------------------------------------------------
 
@@ -1342,8 +1000,13 @@ if test -n "$with_geos" -a "$with_geos" != "no" ; then
 
   GEOS_INCDIR=`$GEOS_CONFIG --includes`
   GEOS_INC="-I$GEOS_INCDIR"
-  GEOS_LIB="`$GEOS_CONFIG --libs`_c"
-
+  dnl Geos >=3.3 has a new config option: --clibs.
+  if test $ac_geos_version -ge 300300; then
+     GEOS_LIB="`$GEOS_CONFIG --clibs`"
+  else
+     GEOS_LIB="`$GEOS_CONFIG --libs`_c"
+  fi
+  
   AC_SUBST(GEOS_ENABLED,$GEOS_ENABLED)
   AC_SUBST(GEOS_INC,    $GEOS_INC)
   AC_SUBST(GEOS_LIB,    $GEOS_LIB)
@@ -1637,6 +1300,7 @@ else
   fi
 
   dnl Try to locate include directory
+  test -f $ORA_HOME/include/oci.h && ORA_INCDIR="$ORA_HOME/include"
   test -f $ORA_HOME/sdk/include/oci.h && ORA_INCDIR="$ORA_HOME/sdk/include"
   test -f $ORA_HOME/rdbms/public/oci.h && ORA_INCDIR="$ORA_HOME/rdbms/public"
   test -f $ORA_HOME/rdbms/demo/oci.h && ORA_INCDIR="$ORA_HOME/rdbms/public"
@@ -1942,6 +1606,52 @@ else
 fi
 
 dnl ---------------------------------------------------------------------
+dnl Exempi support
+dnl ---------------------------------------------------------------------
+
+AC_MSG_CHECKING(if exempi support requested)
+AC_ARG_WITH(exempi,
+[  --with-exempi=DIR Specify path to exempi.],,)
+
+if test -n "$with_exempi" -a "$with_exempi" != "no" ; then
+
+  if test "$with_exempi" = "yes" ; then
+    if test -f /usr/include/exempi-2.0/exempi/xmp.h; then
+        EXEMPI_INC="-I/usr/include/exempi-2.0/exempi"
+        EXEMPI_LIB="-lexempi"
+    else
+        AC_CHECK_HEADER([xmp.h],,[AC_MSG_ERROR([cannot find xmp.h])])
+        EXEMPI_INC=""
+        EXEMPI_LIB="-lexempi"
+    fi
+  else
+    xmp_dir=$with_exempi
+    xmp_include=$xmp_dir/include
+    xmp_lib=$xmp_dir/lib
+    xmp_found=
+    for xmp_subdir in / /exempi /exempi-2.0/exempi; do
+      AC_CHECK_HEADER([$xmp_include$xmp_subdir/xmp.h],xmp_found=$xmp_subdir,,)
+    done
+    if test "x$xmp_found" = "x" ; then
+      AC_MSG_ERROR([cannot find xmp.h in $xmp_include])
+    else
+      EXEMPI_INC="-I$xmp_include$xmp_subdir"
+    fi
+    EXEMPI_LIB="-L$xmp_lib -lexempi"
+  fi
+
+  AC_CHECK_LIB(exempi,xmp_init,EXEMPI_ENABLED=-DUSE_EXEMPI,,$EXEMPI_LIB)
+
+else
+  AC_MSG_RESULT(no)
+fi
+
+AC_SUBST(EXEMPI_ENABLED,$EXEMPI_ENABLED)
+AC_SUBST(EXEMPI_INC,    $EXEMPI_INC)
+AC_SUBST(EXEMPI_LIB,    $EXEMPI_LIB)
+ALL_ENABLED="$EXEMPI_ENABLED $ALL_ENABLED"
+
+dnl ---------------------------------------------------------------------
 dnl Look for libxml2 if SOS Server requested
 dnl ---------------------------------------------------------------------
 
@@ -2072,6 +1782,7 @@ else
   test -f $XSLT_DIR/include/libxslt/xslt.h && XSLT_INCDIR="$XSLT_DIR/include"
   test -f $XSLT_DIR/lib/libxslt.so && XSLT_LIBDIR="$XSLT_DIR/lib"
   test -f $XSLT_DIR/lib64/libxslt.so && XSLT_LIBDIR="$XSLT_DIR/lib64"
+  test -f $XSLT_DIR/lib/x86_64-linux-gnu/libxslt.so && XSLT_LIBDIR="$XSLT_DIR/lib/x86_64-linux-gnu"
 
   if test -n "$XSLT_LIBDIR" -a -n "$XSLT_INCDIR" ; then
     dnl
@@ -2119,6 +1830,7 @@ else
   test -f $EXSLT_DIR/include/libexslt/exslt.h && EXSLT_INCDIR="$EXSLT_DIR/include"
   test -f $EXSLT_DIR/lib/libexslt.so && EXSLT_LIBDIR="$EXSLT_DIR/lib"
   test -f $EXSLT_DIR/lib64/libexslt.so && EXSLT_LIBDIR="$EXSLT_DIR/lib64"
+  test -f $EXSLT_DIR/lib/x86_64-linux-gnu/libexslt.so && EXSLT_LIBDIR="$EXSLT_DIR/lib/x86_64-linux-gnu"
 
   if test -n "$EXSLT_LIBDIR" -a -n "$EXSLT_INCDIR" ; then
     dnl
@@ -2236,7 +1948,7 @@ elif test "$with_cairo" = "yes" ; then
     AC_MSG_ERROR([pkg-config required for cairo support, try using --with-pkg-config=PATH])
   fi 
 else
-  CAIRO_CONFIG=$with_cairo_config
+  CAIRO_CONFIG=$with_cairo
 fi
 
 if test "$CAIRO_CONFIG" = "no" ; then 
@@ -2259,6 +1971,64 @@ ALL_INC="$CAIRO_INC $ALL_INC"
 ALL_LIB="$CAIRO_LIB $ALL_LIB"
 
 
+dnl ---------------------------------------------------------------------------
+dnl Look for Cairo SVG parser if requested.
+dnl ---------------------------------------------------------------------------
+
+AC_MSG_CHECKING(if Cairo svg parser support requested)
+
+AC_SUBST(LIBSVG_CAIRO_ENABLED,$LIBSVG_CAIRO_ENABLED)
+AC_SUBST(LIBSVG_CAIRO_INC,$LIBSVG_CAIRO_INC)
+AC_SUBST(LIBSVG_CAIRO_LIB,$LIBSVG_CAIRO_LIB)
+
+AC_ARG_WITH(libsvg-cairo,
+[  --with-libsvg-cairo[[=ARG]]      Include Cairo SVG Parser Support (ARG=yes/path to cairo.pc)],,)
+
+if test "$with_libsvg_cairo" = "no" -o "$with_libsvg_cairo" = "" ; then
+  AC_MSG_RESULT(no)
+  LIBSVG_CAIRO_CONFIG="no"
+
+elif test "$with_libsvg_cairo" = "yes" ; then
+  AC_MSG_RESULT(yes)
+  if test "$PKG_CONFIG" != "no" ; then 
+     AC_MSG_CHECKING(for libsvg-cairo pkg-config path)
+     `$PKG_CONFIG --silence-errors -- libsvg-cairo >> /dev/null`
+     if test $? -eq 0 ; then
+        AC_MSG_RESULT(yes)
+        LIBSVG_CAIRO_CONFIG="libsvg-cairo"
+     else
+       AC_MSG_ERROR([libsvg-cairo support requested, but not found.])
+     fi
+  else
+    AC_MSG_ERROR([pkg-config required for libsvg-cairo support, try using --with-pkg-config=PATH])
+  fi 
+else
+  LIBSVG_CAIRO_CONFIG=$with_libsvg_cairo
+fi
+
+if test "$LIBSVG_CAIRO_CONFIG" = "no" ; then 
+  LIBSVG_CAIRO_ENABLED=
+  LIBSVG_CAIRO_INC=
+  LIBSVG_CAIRO_LIB=
+else
+  if test -z "$CAIRO_ENABLED"; then
+       AC_MSG_ERROR([libsvg-cairo support requires cairo support. (hint: rerun with --with-cairo)])
+  fi
+  AC_MSG_RESULT([yes, pkg-config defaults, or user supplied path to cairo.pc])
+  LIBSVG_CAIRO_ENABLED="-DUSE_SVG_CAIRO"
+  LIBSVG_CAIRO_LIB=`$PKG_CONFIG --libs $LIBSVG_CAIRO_CONFIG`
+  LIBSVG_CAIRO_INC=`$PKG_CONFIG --cflags $LIBSVG_CAIRO_CONFIG`
+fi
+
+AC_SUBST(LIBSVG_CAIRO_ENABLED,$LIBSVG_CAIRO_ENABLED)
+AC_SUBST(LIBSVG_CAIRO_INC,$LIBSVG_CAIRO_INC)
+AC_SUBST(LIBSVG_CAIRO_LIB,$LIBSVG_CAIRO_LIB)
+
+ALL_ENABLED="$LIBSVG_CAIRO_ENABLED $ALL_ENABLED"
+ALL_INC="$LIBSVG_CAIRO_INC $ALL_INC"
+ALL_LIB="$LIBSVG_CAIRO_LIB $ALL_LIB"
+
+
 dnl ---------------------------------------------------------------------
 dnl Support for FastCGI enabled builds.
 dnl ---------------------------------------------------------------------
@@ -2298,61 +2068,21 @@ ALL_ENABLED="$FASTCGI_ENABLED $ALL_ENABLED"
 ALL_INC="$FASTCGI_INC $ALL_INC"
 ALL_LIB="$FASTCGI_LIB $ALL_LIB"
 
-dnl ---------------------------------------------------------------------
-dnl Try to detect Apache version (httpd -v)
-dnl ---------------------------------------------------------------------
-
-AC_CHECKING(HTTPD server (Apache) version)
-AC_ARG_WITH(httpd,
-[  --with-httpd            Specify path to 'httpd' executable.],,)
-
-
-if test "$with_httpd" = "no" ; then
-
-  AC_MSG_RESULT([        HTTPD server (Apache) version detection disabled by --without-httpd.])
-
-elif test "$with_httpd" = "yes" ; then
-  AC_MSG_ERROR([full path to httpd executable is required as argument when using --with-httpd])
-
-else
-
-  if test -n "$with_httpd" ; then
-    dnl
-    dnl User supplied explicit httpd path
-    dnl
-    HTTPD="$with_httpd"
-    
-    if test -f "$HTTPD" -a -x "$HTTPD" ; then
-      AC_MSG_RESULT([        using user-supplied httpd ($HTTPD)])
-    else
-      AC_MSG_ERROR([$HTTPD is not an executable.  Make sure you use --with-httpd=/path/to/httpd])
-    fi
-  else
-    dnl 
-    dnl Try to locate httpd
-    dnl
-    AC_PATH_PROG(HTTPD, httpd, "", "$PATH:/usr/sbin:/usr/bin:/usr/local/bin:/usr/local/apache/bin")
-  fi
-
-  if test -z "$HTTPD" ; then
-    AC_MSG_RESULT([        'httpd' not found, skipping Apache version detection. You may want to use --with-httpd=/path/to/httpd])
-  else
-    HTTPD_VERSION_STRING=`$HTTPD -v | grep "Server version" | awk '{print $3}'`
-    dnl If server is not Apache then APACHE_VERSION will be empty
-    APACHE_VERSION=`echo "$HTTPD_VERSION_STRING" | grep Apache | awk -F / '{print $2}' | awk -F . '{print $1*1000000 + $2*1000 + $3}'`
-
-    AC_MSG_RESULT([        $HTTPD version is $HTTPD_VERSION_STRING ($APACHE_VERSION).])
-
-
-    dnl Check whether msDebug() calls need non-blocking stderr
-    if test -n "$APACHE_VERSION" -a `expr "$APACHE_VERSION" \>= "2000000"` = 1 -a `expr "$APACHE_VERSION" \< "2000049"` = 1 ; then
-      AC_MSG_RESULT([        Your system is apparently running $HTTPD_VERSION_STRING.  Setting stderr to non-blocking for msDebug() due to Apache 2.0.0-2.0.48 bug (see MapServer bug 458 or Apache bug 22030).])
-      DEBUG_FLAGS="${DEBUG_FLAGS} -DNEED_NONBLOCKING_STDERR"
-    fi
-
-  fi
-
-fi
+AC_ARG_WITH(apache-module, 
+     AC_HELP_STRING([--with-apache-module], [enable building mod_mapserver module]), 
+     , 
+     [with_apache_module=no] 
+   ) 
+   if test "$with_apache_module" = "yes"; then 
+      APXS_CHECK
+      APR_CHECK
+      if test -z "$APRCONFIG"; then
+         AC_MSG_ERROR(apr-config utility not found. use --with-apr-config to specify its location.)
+      else
+         ALL_ENABLED="-DMOD_WMS_ENABLED $ALL_ENABLED"
+      fi
+   fi
+     
 
 
 dnl ---------------------------------------------------------------------
@@ -2383,6 +2113,7 @@ if test "$enable_ignore_missing_data" = "yes" ; then
   AC_MSG_RESULT([Compiling with -DIGNORE_MISSING_DATA.])
 fi
 AC_SUBST(IGNORE_MISSING_DATA, $IGNORE_MISSING_DATA)
+ALL_ENABLED="$IGNORE_MISSING_DATA $ALL_ENABLED"
 
 dnl ---------------------------------------------------------------------
 dnl Check USE_POINT_Z_M option (OFF by default)
@@ -2405,7 +2136,7 @@ dnl ---------------------------------------------------------------------
 dnl Force use of slow (generic) MS_NINT macro.
 dnl ---------------------------------------------------------------------
 
-AC_ARG_ENABLE(point-z-m,
+AC_ARG_ENABLE(fast-nint,
 [  --disable-fast-nint     Use safe MS_NINT with reliable rounding],,)
 
 if test "$enable_fast_nint" = "no" ; then
@@ -2433,42 +2164,33 @@ AC_MSG_CHECKING(compiler warnings)
 AC_ARG_WITH(warnings,
 [  --with-warnings[[=flags]] Enable strict warnings (or user defined warnings)],,)
 
+AX_CFLAGS_WARN_ALL(C_WFLAGS)
+AX_CXXFLAGS_WARN_ALL(CXX_WFLAGS)
+
 if test "$with_warnings" = "yes" ; then 
   if test "$GCC" = "yes" ; then
-    WFLAGS="-W -Wall -Wcast-align -Wmissing-prototypes -Wstrict-prototypes -Wpointer-arith -Wreturn-type"
-    C_EXTRA_WFLAGS="-Wmissing-declarations"
+    WFLAGS="-W -Wcast-align -Wmissing-prototypes -Wstrict-prototypes -Wpointer-arith -Wreturn-type"
+    C_WFLAGS="$C_WFLAGS -Wmissing-declarations"
   
     AC_MSG_RESULT([strict])
   else
     WFLAGS=""
-    C_EXTRA_WFLAGS=""
-    AC_MSG_RESULT([disabled])
-  fi
-
-elif test "$with_warnings" = "" ; then 
-  if test "$GCC" = "yes" ; then
-    WFLAGS="-Wall"
-    C_EXTRA_WFLAGS=""
-    AC_MSG_RESULT([basic])
-  else
-    WFLAGS=""
-    C_EXTRA_WFLAGS=""
     AC_MSG_RESULT([disabled])
   fi
 
 elif test "$with_warnings" = "no" ; then
   WFLAGS=""
-  C_EXTRA_WFLAGS=""
+  C_WFLAGS=""
+  CXX_WFLAGS=""
   AC_MSG_RESULT([disabled])
 
-else
+elif test "$with_warnings" != "" ; then 
   WFLAGS="$with_warnings"
-  C_EXTRA_WFLAGS=""
   AC_MSG_RESULT([user defined])
 fi
 
-CFLAGS="$CFLAGS $WFLAGS $C_EXTRA_WFLAGS"
-CXXFLAGS="$CXXFLAGS $WFLAGS "
+CFLAGS="$CFLAGS $WFLAGS $C_WFLAGS"
+CXXFLAGS="$CXXFLAGS $WFLAGS $CXX_WFLAGS"
 
 dnl ---------------------------------------------------------------------
 dnl Check --enable-debug option for "-g" compile flag. (OFF by default)
@@ -2492,6 +2214,16 @@ else
   CFLAGS=`echo "$CFLAGS -DNDEBUG " | sed "s/-g //"`
 fi
 
+AC_CHECKING(whether to enable proj shortcuts)
+AC_ARG_ENABLE(proj-fastpath,
+     AC_HELP_STRING([--enable-proj-fastpath], [bypass proj.4 for epsg:4326 to epsg:3857 reprojections]),,) 
+
+if test "$enable_proj_fastpath" = "yes" ; then
+   PROJ_FASTPATH_ENABLED="-DUSE_PROJ_FASTPATHS"
+   ALL_ENABLED="$PROJ_FASTPATH_ENABLED $ALL_ENABLED"
+fi
+AC_SUBST(PROJ_FASTPATH_ENABLED,$PROJ_FASTPATH_ENABLED)
+
 dnl ---------------------------------------------------------------------
 dnl Check --enable-cgi-cl-debug-args option (OFF by default)
 dnl ---------------------------------------------------------------------
@@ -2530,10 +2262,10 @@ dnl ---------------------------------------------------------------------
 
 AC_CHECKING(for PHP/MapScript module options)
 AC_ARG_WITH(php,
-[  --with-php=DIR          Specify directory where PHP5's include files are
-                          installed (or a pointer to the full source tree)
+[  --with-php=yes|no|/path/to/php-config
+                          Specify location of php-config script.
                           Required in order to compile the PHP/MapScript 
-                          module.],,)
+                          module.],,[with_php=no])
 
 AC_ARG_ENABLE(internal-ld-detect,
 [  --enable-perlv-ld-detect
@@ -2542,59 +2274,38 @@ AC_ARG_ENABLE(internal-ld-detect,
                           link php_mapscript.so.  Try this only if the default
                           internal macro didn't work.],,)
 
-if test -n "$with_php" -a -d "$with_php" ; then
-  AC_EXPAND_PATH($with_php, PHP_SRC_DIR)
-  dnl
-  dnl Checks for shared library linking.
-  dnl
-  dnl Default to internal AC_LD_SHARED macro, or use the the perl-based 
-  dnl if requested and perl is available... 
-  dnl (The perl-V macro was the default in 3.6 and before but this was
-  dnl  changed in 3.7 to use the internal AC_LD_SHARED macro by default)
-  dnl
-
-  if test "$enable_perlv_ld_detect" = "yes" ; then
-      AC_MSG_RESULT(Using perl -V macro to figure ld command to link php_mapscript.so)
-
-      AC_MSG_CHECKING([whether 'perl -V' works])
-      if  (perl -V > /dev/null 2>&1)  ; then
-        AC_MSG_RESULT(yes)
-        AC_LD_SHARED_FROM_PERL
-        PHP_CC="$PERL_CC"
-        PHP_LD="$PERL_LD $PHP_LD_XTRAFLAGS"
-      else
-        AC_MSG_RESULT(no)
-        AC_MSG_ERROR([ERROR: Cannot use --enable-perlv-ld-detect since Perl -V does not work on this system.])
+if test "$with_php" != "no" ; then
+  if test -d "$with_php"; then
+      AC_MSG_ERROR([--with-php now expects an optional path to php-config, not a directory])
+  fi
+  if test "$with_php" == "yes" ; then
+      AC_PATH_PROG(PHPCONFIG,php-config,no)
+      if test "x$PHPCONFIG" == "xno"; then
+         AC_MSG_ERROR([php-config not found on path, please give its full location])
       fi
   else
-    dnl The default: use the internal AC_LD_SHARED macro
-    dnl
-    AC_COMPILER_PIC
-    dnl AC_LD_SHARED
-    AC_PHP_LD_SHARED
-    PHP_CC="$CC $C_PIC"
-    PHP_LD="$PHP_LD_SHARED $PHP_LD_XTRAFLAGS"
+      PHPCONFIG="$with_php"
+  fi
+  if test ! -f "$PHPCONFIG"; then
+      AC_MSG_ERROR([$PHPCONFIG not found])
   fi
 
+  PHPINCDIR=`$PHPCONFIG --include-dir`
+
   dnl
   dnl Look for PHP5's php_config.h.
   dnl We'll need the config file to find info about the PHP configuration
   dnl
   AC_MSG_CHECKING([for location of php_config.h])
   dnl Look for the main/php_config.h
-  test -f "$PHP_SRC_DIR/main/php_config.h" && test -f "$PHP_SRC_DIR/main/php_version.h"  && PHP_CONFIG_H="$PHP_SRC_DIR/main/php_config.h"
-
-  dnl If php was installed, then the headers are under $prefix/include/php/*
-  test -f "$PHP_SRC_DIR/include/php/main/php_config.h" && PHP_SRC_DIR="$PHP_SRC_DIR/include/php/" && PHP_CONFIG_H="$PHP_SRC_DIR/main/php_config.h"
-  dnl In PHP 5, few distributions use "/usr/include/php5" directory
-  test -f "$PHP_SRC_DIR/include/php5/main/php_config.h" && PHP_SRC_DIR="$PHP_SRC_DIR/include/php5/" && PHP_CONFIG_H="$PHP_SRC_DIR/main/php_config.h"
+  test -f "$PHPINCDIR/main/php_config.h" && PHP_CONFIG_H="$PHPINCDIR/main/php_config.h"
 
   if test -n "$PHP_CONFIG_H" ; then
     AC_MSG_RESULT([$PHP_CONFIG_H])
   else
     AC_MSG_ERROR([
-!!! Could not find php_config.h and php_version.h in $PHP_SRC_DIR.          !!!
-!!! Has PHP been configured yet?                                      !!!])
+!!! Could not find php_config.h and php_version.h in $PHPINCDIR.          !!!
+!!! Has PHP been installed yet?                                      !!!])
   fi
 
 
@@ -2602,7 +2313,7 @@ if test -n "$with_php" -a -d "$with_php" ; then
   dnl Default is PHP3, and if ZEND_API is set then we assume that we have PHP4.
   dnl
   AC_MSG_CHECKING([if we have PHP 5.2.0+])
-  PHP_VERSION=`grep 'PHP_VERSION_ID' $PHP_SRC_DIR/main/php_version.h | cut -d' ' -f3`
+  PHP_VERSION=`$PHPCONFIG --vernum`
   if test -z "$PHP_VERSION" || test $PHP_VERSION -lt 50200; then
     AC_MSG_ERROR([
 !!! PHP MapScript now requires PHP 5.2.0 or more recent.              !!!
@@ -2611,7 +2322,6 @@ if test -n "$with_php" -a -d "$with_php" ; then
   else
      AC_MSG_RESULT([yes])
   fi
-  AC_MSG_RESULT([$PHP_VERSION_FLAG])
 
   dnl
   dnl Check if PHP was compiled with the bundled regex, and if so then
@@ -2623,21 +2333,21 @@ if test -n "$with_php" -a -d "$with_php" ; then
 
     dnl We'll check for regex_extra.h - that might let use build
     dnl without the source using libphp_common.so
-    test -f "$PHP_SRC_DIR/regex/regex_extra.h" && PHP_NO_SOURCE="1"
+    test -f "$PHPINCDIR/regex/regex_extra.h" && PHP_NO_SOURCE="1"
         if test -n "$PHP_NO_SOURCE" ; then
           dnl Found regex_extra.h
           USE_PHP_REGEX="-DUSE_PHP_REGEX"
-          PHP_REGEX_INC="-I$PHP_SRC_DIR"
-          PHP_REGEX_OBJ=php_regex.o
+          PHP_REGEX_INC="-I$PHPINCDIR"
+          PHP_REGEX_OBJ=php_regex.lo
           AC_MSG_RESULT([        found regex_extra.h - building PHP MapScript with PHP's bundled regex ])
         else
           dnl PHP 5.3 changed the layout of regex-related files.
-          test -f "$PHP_SRC_DIR/ext/ereg/regex/regex.h" && PHP_NO_SOURCE="1"
+          test -f "$PHPINCDIR/ext/ereg/regex/regex.h" && PHP_NO_SOURCE="1"
           if test -n "$PHP_NO_SOURCE" ; then
           dnl Found regex.h
           USE_PHP_REGEX="-DUSE_PHP_REGEX"
-          PHP_REGEX_INC="-I$PHP_SRC_DIR/ext/ereg/"
-          PHP_REGEX_OBJ=php_regex.o
+          PHP_REGEX_INC="-I$PHPINCDIR/ext/ereg/"
+          PHP_REGEX_OBJ=php_regex.lo
           AC_MSG_RESULT([        found regex.h - building PHP MapScript with PHP's bundled regex ])
           else
             AC_MSG_ERROR([
@@ -2650,27 +2360,20 @@ if test -n "$with_php" -a -d "$with_php" ; then
     AC_MSG_RESULT(no)
   fi
 
-  PHPMS_MAKEFILE=mapscript/php/Makefile
-  MAKE_PHPMS=php_mapscript
-  MAKE_PHPMS_CLEAN=php_mapscript_clean
 
-  AC_SUBST(PHP_VERSION_FLAG, $PHP_VERSION_FLAG)
-  AC_SUBST(PHP_SRC_DIR, $PHP_SRC_DIR)
-  AC_SUBST(PHP_CC, $PHP_CC)
-  AC_SUBST(PHP_LD, $PHP_LD)
+  PHP_MAPSCRIPT="php_mapscript"
+  AC_SUBST(PHP_VERSION_FLAG, "-DPHP_VERSION_ID=$PHP_VERSION")
+  AC_SUBST(PHPCONFIG, $PHPCONFIG)
   AC_SUBST(PHP_REGEX_INC, $PHP_REGEX_INC)
   AC_SUBST(PHP_REGEX_OBJ, $PHP_REGEX_OBJ)
   AC_SUBST(USE_PHP_REGEX, $USE_PHP_REGEX)
 
   AC_MSG_RESULT([        PHP/MapScript module configured.])
-elif test -n "$with_php" -a "$with_php" != "no" ; then
-  AC_MSG_ERROR([Missing or invalid PHP source directory in --with-php=DIR.])
 else
   AC_MSG_RESULT([        PHP/MapScript module not configured.])
 fi
 
-AC_SUBST(MAKE_PHPMS, $MAKE_PHPMS)
-AC_SUBST(MAKE_PHPMS_CLEAN, $MAKE_PHPMS_CLEAN)
+AC_SUBST(PHP_MAPSCRIPT,$PHP_MAPSCRIPT)
 
 dnl ---------------------------------------------------------------------
 dnl Shared library building.
@@ -2683,109 +2386,6 @@ if test "x$LD_SHARED" = "x" ; then
   AC_LD_SHARED
 fi
 
-dnl ---------------------------------------------------------------------
-dnl 'apxs' option for PHP built as an Apache module (libphp3.so)
-dnl --with-apxs[=FILE] should be the exact same value that was passed
-dnl   to the PHP configure command.
-dnl
-dnl All we need is to add the Apache include files to the php module
-dnl include path.
-dnl
-dnl The APXS variable also affects the way AC_ADD_RUNPATH() works
-dnl ---------------------------------------------------------------------
-
-AC_ARG_WITH(apxs,
-[  --with-apxs[[=FILE]]      (CURRENTLY DISABLED) 
-                          Use this option only if building the PHP MapScript
-                          on a system where PHP was built as a shared Apache
-                          module.  FILE is the optional pathname to the
-                          Apache apxs tool; defaults to apxs.],,)
-
-if test -n "$with_apxs" -a "$with_apxs" != "no" ; then
-
-  AC_MSG_ERROR([
-!!! The current version of PHP MapScript requires PHP4 configured as  !!!
-!!! a CGI and cannot be used with PHP4 configured as an Apache module,!!!
-!!! so you cannot use the --with-apxs option.                         !!!
-!!! See: http://mapserver.gis.umn.edu/cgi-bin/wiki.pl?PHPMapScriptCGI !!!])
-
-
-  AC_MSG_CHECKING([for location of Apache headers using apxs])
-  if test -z "$MAKE_PHPMS" ; then
-    AC_MSG_ERROR([--with-apxs applies only if --with-php is used.])
-
-  elif test "$with_apxs" = "yes" ; then
-    APXS=apxs
-  else
-    APXS="$with_apxs"
-  fi
-
-  APACHE_INC=-I`$APXS -q INCLUDEDIR`
-  AC_MSG_RESULT($APACHE_INC)
-
-  dnl APACHE_INC substitution is done after --with-apache switch processing
-  dnl below.
-fi
-
-
-dnl ---------------------------------------------------------------------
-dnl '--with-apache' option for PHP built as an Apache module and statically
-dnl linked into the httpd executable.  This option is used to specify the
-dnl location of the apache include files.
-dnl ---------------------------------------------------------------------
-
-AC_ARG_WITH(apache,
-[  --with-apache=DIR       (CURRENTLY DISABLED) 
-                          Use this option only if building the PHP MapScript
-                          on a system where PHP was built as an Apache
-                          module statically linked into the httpd executable.
-                          DIR is the path to the apache include files.],,)
-
-if test -n "$with_apache" -a "$with_apache" != "no" ; then
-
-  AC_MSG_ERROR([
-!!! The current version of PHP MapScript requires PHP4 configured as  !!!
-!!! a CGI and cannot be used with PHP4 configured as an Apache module,!!!
-!!! so you cannot use the --with-apache option.                       !!!
-!!! See: http://mapserver.gis.umn.edu/cgi-bin/wiki.pl?PHPMapScriptCGI !!!])
-
-  AC_MSG_CHECKING([for location of Apache headers])
-  if test -z "$MAKE_PHPMS" ; then
-    AC_MSG_ERROR([--with-apache applies only if --with-php is used.])
-  fi
-
-  AC_EXPAND_PATH($with_apache, APACHE_DIR)
-  test -f $APACHE_DIR/httpd.h && APACHE_INC_DIR="$APACHE_DIR"
-  test -f $APACHE_DIR/include/httpd.h && APACHE_INC_DIR="$APACHE_DIR/include"
-  test -f $APACHE_DIR/src/include/httpd.h && APACHE_INC_DIR="$APACHE_DIR/src/include"
-  if test -n "$APACHE_INC_DIR" ; then
-    APACHE_INC="-I$APACHE_INC_DIR $APACHE_INC"
-    AC_MSG_RESULT("-I$APACHE_INC_DIR")
-  else
-    AC_MSG_ERROR("Could not find httpd.h in $APACHE_DIR.")
-  fi
-fi
-
-AC_SUBST(APACHE_INC, $APACHE_INC)
-
-
-dnl ---------------------------------------------------------------------
-dnl Check --enable-runpath to request including -Wl,-R for runtime
-dnl lib path in link command (disabled by default)
-dnl ---------------------------------------------------------------------
-
-AC_MSG_CHECKING([if --enable-runpath requested])
-AC_ARG_ENABLE(runpath,
-[  --enable-runpath        Include runtime library path flags (-Wl,-R) in link.
-                          Required on *BSD systems.
-  --disable-runpath       Do not link with runtime lib path (the default).],,)
-
-if test "$enable_runpath" != "yes" ; then
-  RPATHS=""
-  AC_MSG_RESULT([no])
-else
-  AC_MSG_RESULT([yes ($RPATHS)])
-fi
 
 dnl ---------------------------------------------------------------------
 dnl Check operating system (used by Java Mapscript and possibily
@@ -2818,19 +2418,71 @@ esac
 AC_MSG_RESULT([no, autodetected $OS_INCLUDE_DIR])
 fi
 
+if test -z $JAVAC; then
+   JAVAC="javac"
+fi
+AX_JNI_INCLUDE_DIR
+for JNI_INCLUDE_DIR in $JNI_INCLUDE_DIRS
+do
+   JAVA_INCLUDE="$JAVA_INCLUDE -I$JNI_INCLUDE_DIR"
+done
+AC_SUBST(JAVA_INCLUDE,$JAVA_INCLUDE)
+
+AC_DEFUN([PYTHON_CHECK],[
+AC_MSG_CHECKING(if python path is provided)
+
+AC_ARG_WITH(python,
+[  --with-python[[=PATH]] Specify python binary (PATH is path to python)],,[with_python=yes])
+
+if test -n "$with_python" -a "$with_python" != "yes" ; then
+   AC_MSG_RESULT([yes])
+   if test -x "$with_python"; then
+      PYTHON=$with_python
+   else
+      AC_MSG_ERROR([$with_python does not seem to be an executable])
+   fi
+else
+   AC_MSG_RESULT([using system default])
+   AC_PATH_PROG(PYTHON,python)
+   if test -z "$PYTHON"; then
+      AC_MSG_ERROR([no python found on path])
+   fi
+fi
+AC_SUBST(PYTHON,$PYTHON)
+])
+
+
+AC_ARG_ENABLE(python-mapscript,
+[  --enable-python-mapscript     build the python mapscript module. ],,[enable_python_mapscript=no])
+AC_MSG_CHECKING([if we should build python mapscript])
+if test "$enable_python_mapscript" = "yes" ; then
+  AX_PKG_SWIG([2.0.0])
+  if test -z $SWIG; then
+      AC_MSG_WARN([swig not found, you will not be able to build/update wrappers])
+  fi
+  PYTHON_CHECK
+  PYTHON_MAPSCRIPT="python_mapscript"
+
+  AC_MSG_RESULT([        Python/MapScript module configured.])
+else
+  AC_MSG_RESULT([        Python/MapScript module not configured.])
+fi
+
+AC_SUBST(PYTHON_MAPSCRIPT,$PYTHON_MAPSCRIPT)
+
 AC_SUBST(OS_INCLUDE_DIR, $OS_INCLUDE_DIR)
 
 dnl ---------------------------------------------------------------------
 dnl Generate output files
 dnl ---------------------------------------------------------------------
 
-AC_SUBST(ALL_ENABLED, $ALL_ENABLED)
+AC_SUBST(ALL_ENABLED, "$ALL_ENABLED -DDISABLE_CVSID")
 AC_SUBST(ALL_INC, $ALL_INC)
 AC_SUBST(ALL_LIB, $ALL_LIB)
 AC_SUBST(ALL_STATIC_LIB, $ALL_STATIC_LIB)
 AC_SUBST(RPATHS, [$RPATHS])
 
-AC_OUTPUT(Makefile $PHPMS_MAKEFILE mapscript/java/Makefile mapscript/csharp/Makefile)
+AC_OUTPUT(Makefile mapscript/php/Makefile mapscript/python/Makefile mapscript/java/Makefile mapscript/csharp/Makefile mapscript/perl/Makefile.PL)
 
 dnl ---------------------------------------------------------------------------
 dnl Display configuration status
@@ -2855,17 +2507,20 @@ AC_MSG_RESULT([  jpeg support:              ${JPEG_ENABLED}])
 AC_MSG_RESULT([  freetype support:          ${FT_ENABLED}])
 AC_MSG_RESULT([  iconv support:             ${ICONV_ENABLED}])
 AC_MSG_RESULT([  AGG support:               ${AGG_ENABLED}])
-AC_MSG_RESULT([  SVG Symbol support:        ${AGG_SVG_SYMBOLS_ENABLED}])
+AC_MSG_RESULT([  GD support:                ${GD_ENABLED}])
 AC_MSG_RESULT([  Cairo (SVG,PDF) support:   ${CAIRO_ENABLED}])
+AC_MSG_RESULT([  Cairo SVG symbol support:  ${LIBSVG_CAIRO_ENABLED}])
 AC_MSG_RESULT([  KML support:               ${KML_ENABLED}])
 AC_MSG_RESULT()
 
 AC_MSG_RESULT([ -------------- Support Libraries --------- ])
 AC_MSG_RESULT([  Proj.4 support:            ${PROJ_ENABLED}])
+AC_MSG_RESULT([  Proj Fastpaths:            ${PROJ_FASTPATH_ENABLED}])
 AC_MSG_RESULT([  Libxml2 support:           ${XML2_ENABLED}])
 AC_MSG_RESULT([  FriBidi support:           ${FRIBIDI_ENABLED}])
 AC_MSG_RESULT([  Curl support:              ${CURL_ENABLED}])
 AC_MSG_RESULT([  FastCGI support:           ${FASTCGI_ENABLED}])
+AC_MSG_RESULT([  Exempi support:            ${EXEMPI_ENABLED}])
 AC_MSG_RESULT([  Threading support:         ${THREAD_FLAG}])
 AC_MSG_RESULT([  GEOS support:              ${GEOS_ENABLED}])
 AC_MSG_RESULT([  XML Mapfile support:        ${XMLMAPFILE_ENABLED}])
@@ -2891,10 +2546,15 @@ AC_MSG_RESULT([  SOS Server:                ${SOS_SVR_ENABLED}])
 AC_MSG_RESULT()
 
 AC_MSG_RESULT([ -------------- MapScript ----------------- ])
-if test -n "${PHP_SRC_DIR}"; then
+if test -n "${PHP_MAPSCRIPT}"; then
   AC_MSG_RESULT([  PHP MapScript:             yes])
 else
   AC_MSG_RESULT([  PHP MapScript:             no])
 fi
+if test -n "${PYTHON_MAPSCRIPT}"; then
+  AC_MSG_RESULT([  Python MapScript:          yes])
+else
+  AC_MSG_RESULT([  Python MapScript:          no])
+fi
 
 AC_MSG_RESULT()
diff --git a/dxfcolor.h b/dxfcolor.h
index 2839061..5de4706 100644
--- a/dxfcolor.h
+++ b/dxfcolor.h
@@ -1,261 +1,261 @@
-struct dxfcolor{
- 	int r,g,b;
+struct dxfcolor {
+  int r,g,b;
 };
 struct dxfcolor ctable[256] = {
-{0, 	0, 	0},
-{255, 	0, 	0},
-{255, 	255, 	0},
-{0, 	255, 	0},
-{0, 	255, 	255},
-{0, 	0, 	255},
-{255, 	0, 	255},
-{255, 	255, 	255},
-{128, 	128, 	128},
-{192, 	192, 	192},
-{255, 	0, 	0},
-{255, 	127, 	127},
-{204, 	0, 	0},
-{204, 	102, 	102},
-{153, 	0, 	0},
-{153, 	76, 	76},
-{127, 	0, 	0},
-{127, 	63, 	63},
-{76, 	0, 	0},
-{76, 	38, 	38},
-{255, 	63, 	0},
-{255, 	159, 	127},
-{204, 	51, 	0},
-{204, 	127, 	102},
-{153, 	38, 	0},
-{153, 	95, 	76},
-{127, 	31, 	0},
-{127, 	79, 	63},
-{76, 	19, 	0},
-{76, 	47, 	38},
-{255, 	127, 	0},
-{255, 	191, 	127},
-{204, 	102, 	0},
-{204, 	153, 	102},
-{153, 	76, 	0},
-{153, 	114, 	76},
-{127, 	63, 	0},
-{127, 	95, 	63},
-{76, 	38, 	0},
-{76, 	57, 	38},
-{255, 	191, 	0},
-{255, 	223, 	127},
-{204, 	153, 	0},
-{204, 	178, 	102},
-{153, 	114, 	0},
-{153, 	133, 	76},
-{127, 	95, 	0},
-{127, 	111, 	63},
-{76, 	57, 	0},
-{76, 	66, 	38},
-{255, 	255, 	0},
-{255, 	255, 	127},
-{204, 	204, 	0},
-{204, 	204, 	102},
-{153, 	153, 	0},
-{153, 	153, 	76},
-{127, 	127, 	0},
-{127, 	127, 	63},
-{76, 	76, 	0},
-{76, 	76, 	38},
-{191, 	255, 	0},
-{223, 	255, 	127},
-{153, 	204, 	0},
-{178, 	204, 	102},
-{114, 	153, 	0},
-{133, 	153, 	76},
-{95, 	127, 	0},
-{111, 	127, 	63},
-{57, 	76, 	0},
-{66, 	76, 	38},
-{127, 	255, 	0},
-{191, 	255, 	127},
-{102, 	204, 	0},
-{153, 	204, 	102},
-{76, 	153, 	0},
-{114, 	153, 	76},
-{63, 	127, 	0},
-{95, 	127, 	63},
-{38, 	76, 	0},
-{57, 	76, 	38},
-{63, 	255, 	0},
-{159, 	255, 	127},
-{51, 	204, 	0},
-{127, 	204, 	102},
-{38, 	153, 	0},
-{95, 	153, 	76},
-{31, 	127, 	0},
-{79, 	127, 	63},
-{19, 	76, 	0},
-{47, 	76, 	38},
-{0, 	255, 	0},
-{127, 	255, 	127},
-{0, 	204, 	0},
-{102, 	204, 	102},
-{0, 	153, 	0},
-{76, 	153, 	76},
-{0, 	127, 	0},
-{63, 	127, 	63},
-{0, 	76, 	0},
-{38, 	76, 	38},
-{0, 	255, 	63},
-{127, 	255, 	159},
-{0, 	204, 	51},
-{102, 	204, 	127},
-{0, 	153, 	38},
-{76, 	153, 	95},
-{0, 	127, 	31},
-{63, 	127, 	79},
-{0, 	76, 	19},
-{38, 	76, 	47},
-{0, 	255, 	127},
-{127, 	255, 	191},
-{0, 	204, 	102},
-{102, 	204, 	153},
-{0, 	153, 	76},
-{76, 	153, 	114},
-{0, 	127, 	63},
-{63, 	127, 	95},
-{0, 	76, 	38},
-{38, 	76, 	57},
-{0, 	255, 	191},
-{127, 	255, 	223},
-{0, 	204, 	153},
-{102, 	204, 	178},
-{0, 	153, 	114},
-{76, 	153, 	133},
-{0, 	127, 	95},
-{63, 	127, 	111},
-{0, 	76, 	57},
-{38, 	76, 	66},
-{0, 	255, 	255},
-{127, 	255, 	255},
-{0, 	204, 	204},
-{102, 	204, 	204},
-{0, 	153, 	153},
-{76, 	153, 	153},
-{0, 	127, 	127},
-{63, 	127, 	127},
-{0, 	76, 	76},
-{38, 	76, 	76},
-{0, 	191, 	255},
-{127, 	223, 	255},
-{0, 	153, 	204},
-{102, 	178, 	204},
-{0, 	114, 	153},
-{76, 	133, 	153},
-{0, 	95, 	127},
-{63, 	111, 	127},
-{0, 	57, 	76},
-{38, 	66, 	76},
-{0, 	127, 	255},
-{127, 	191, 	255},
-{0, 	102, 	204},
-{102, 	153, 	204},
-{0, 	76, 	153},
-{76, 	114, 	153},
-{0, 	63, 	127},
-{63, 	95, 	127},
-{0, 	38, 	76},
-{38, 	57, 	76},
-{0, 	63, 	255},
-{127, 	159, 	255},
-{0, 	51, 	204},
-{102, 	127, 	204},
-{0, 	38, 	153},
-{76, 	95, 	153},
-{0, 	31, 	127},
-{63, 	79, 	127},
-{0, 	19, 	76},
-{38, 	47, 	76},
-{0, 	0, 	255},
-{127, 	127, 	255},
-{0, 	0, 	204},
-{102, 	102, 	204},
-{0, 	0, 	153},
-{76, 	76, 	153},
-{0, 	0, 	127},
-{63, 	63, 	127},
-{0, 	0, 	76},
-{38, 	38, 	76},
-{63, 	0, 	255},
-{159, 	127, 	255},
-{51, 	0, 	204},
-{127, 	102, 	204},
-{38, 	0, 	153},
-{95, 	76, 	153},
-{31, 	0, 	127},
-{79, 	63, 	127},
-{19, 	0, 	76},
-{47, 	38, 	76},
-{127, 	0, 	255},
-{191, 	127, 	255},
-{102, 	0, 	204},
-{153, 	102, 	204},
-{76, 	0, 	153},
-{114, 	76, 	153},
-{63, 	0, 	127},
-{95, 	63, 	127},
-{38, 	0, 	76},
-{57, 	38, 	76},
-{191, 	0, 	255},
-{223, 	127, 	255},
-{153, 	0, 	204},
-{178, 	102, 	204},
-{114, 	0, 	153},
-{133, 	76, 	153},
-{95, 	0, 	127},
-{111, 	63, 	127},
-{57, 	0, 	76},
-{66, 	38, 	76},
-{255, 	0, 	255},
-{255, 	127, 	255},
-{204, 	0, 	204},
-{204, 	102, 	204},
-{153, 	0, 	153},
-{153, 	76, 	153},
-{127, 	0, 	127},
-{127, 	63, 	127},
-{76, 	0, 	76},
-{76, 	38, 	76},
-{255, 	0, 	191},
-{255, 	127, 	223},
-{204, 	0, 	153},
-{204, 	102, 	178},
-{153, 	0, 	114},
-{153, 	76, 	133},
-{127, 	0, 	95},
-{127, 	63, 	111},
-{76, 	0, 	57},
-{76, 	38, 	66},
-{255, 	0, 	127},
-{255, 	127, 	191},
-{204, 	0, 	102},
-{204, 	102, 	153},
-{153, 	0, 	76},
-{153, 	76, 	114},
-{127, 	0, 	63},
-{127, 	63, 	95},
-{76, 	0, 	38},
-{76, 	38, 	57},
-{255, 	0, 	63},
-{255, 	127, 	159},
-{204, 	0, 	51},
-{204, 	102, 	127},
-{153, 	0, 	38},
-{153, 	76, 	95},
-{127, 	0, 	31},
-{127, 	63, 	79},
-{76, 	0, 	19},
-{76, 	38, 	47},
-{51, 	51, 	51},
-{91, 	91, 	91},
-{132, 	132, 	132},
-{173, 	173, 	173},
-{214, 	214, 	214},
-{255, 	255, 	255},
+  {0,   0,  0},
+  {255,   0,  0},
+  {255,   255,  0},
+  {0,   255,  0},
+  {0,   255,  255},
+  {0,   0,  255},
+  {255,   0,  255},
+  {255,   255,  255},
+  {128,   128,  128},
+  {192,   192,  192},
+  {255,   0,  0},
+  {255,   127,  127},
+  {204,   0,  0},
+  {204,   102,  102},
+  {153,   0,  0},
+  {153,   76,   76},
+  {127,   0,  0},
+  {127,   63,   63},
+  {76,  0,  0},
+  {76,  38,   38},
+  {255,   63,   0},
+  {255,   159,  127},
+  {204,   51,   0},
+  {204,   127,  102},
+  {153,   38,   0},
+  {153,   95,   76},
+  {127,   31,   0},
+  {127,   79,   63},
+  {76,  19,   0},
+  {76,  47,   38},
+  {255,   127,  0},
+  {255,   191,  127},
+  {204,   102,  0},
+  {204,   153,  102},
+  {153,   76,   0},
+  {153,   114,  76},
+  {127,   63,   0},
+  {127,   95,   63},
+  {76,  38,   0},
+  {76,  57,   38},
+  {255,   191,  0},
+  {255,   223,  127},
+  {204,   153,  0},
+  {204,   178,  102},
+  {153,   114,  0},
+  {153,   133,  76},
+  {127,   95,   0},
+  {127,   111,  63},
+  {76,  57,   0},
+  {76,  66,   38},
+  {255,   255,  0},
+  {255,   255,  127},
+  {204,   204,  0},
+  {204,   204,  102},
+  {153,   153,  0},
+  {153,   153,  76},
+  {127,   127,  0},
+  {127,   127,  63},
+  {76,  76,   0},
+  {76,  76,   38},
+  {191,   255,  0},
+  {223,   255,  127},
+  {153,   204,  0},
+  {178,   204,  102},
+  {114,   153,  0},
+  {133,   153,  76},
+  {95,  127,  0},
+  {111,   127,  63},
+  {57,  76,   0},
+  {66,  76,   38},
+  {127,   255,  0},
+  {191,   255,  127},
+  {102,   204,  0},
+  {153,   204,  102},
+  {76,  153,  0},
+  {114,   153,  76},
+  {63,  127,  0},
+  {95,  127,  63},
+  {38,  76,   0},
+  {57,  76,   38},
+  {63,  255,  0},
+  {159,   255,  127},
+  {51,  204,  0},
+  {127,   204,  102},
+  {38,  153,  0},
+  {95,  153,  76},
+  {31,  127,  0},
+  {79,  127,  63},
+  {19,  76,   0},
+  {47,  76,   38},
+  {0,   255,  0},
+  {127,   255,  127},
+  {0,   204,  0},
+  {102,   204,  102},
+  {0,   153,  0},
+  {76,  153,  76},
+  {0,   127,  0},
+  {63,  127,  63},
+  {0,   76,   0},
+  {38,  76,   38},
+  {0,   255,  63},
+  {127,   255,  159},
+  {0,   204,  51},
+  {102,   204,  127},
+  {0,   153,  38},
+  {76,  153,  95},
+  {0,   127,  31},
+  {63,  127,  79},
+  {0,   76,   19},
+  {38,  76,   47},
+  {0,   255,  127},
+  {127,   255,  191},
+  {0,   204,  102},
+  {102,   204,  153},
+  {0,   153,  76},
+  {76,  153,  114},
+  {0,   127,  63},
+  {63,  127,  95},
+  {0,   76,   38},
+  {38,  76,   57},
+  {0,   255,  191},
+  {127,   255,  223},
+  {0,   204,  153},
+  {102,   204,  178},
+  {0,   153,  114},
+  {76,  153,  133},
+  {0,   127,  95},
+  {63,  127,  111},
+  {0,   76,   57},
+  {38,  76,   66},
+  {0,   255,  255},
+  {127,   255,  255},
+  {0,   204,  204},
+  {102,   204,  204},
+  {0,   153,  153},
+  {76,  153,  153},
+  {0,   127,  127},
+  {63,  127,  127},
+  {0,   76,   76},
+  {38,  76,   76},
+  {0,   191,  255},
+  {127,   223,  255},
+  {0,   153,  204},
+  {102,   178,  204},
+  {0,   114,  153},
+  {76,  133,  153},
+  {0,   95,   127},
+  {63,  111,  127},
+  {0,   57,   76},
+  {38,  66,   76},
+  {0,   127,  255},
+  {127,   191,  255},
+  {0,   102,  204},
+  {102,   153,  204},
+  {0,   76,   153},
+  {76,  114,  153},
+  {0,   63,   127},
+  {63,  95,   127},
+  {0,   38,   76},
+  {38,  57,   76},
+  {0,   63,   255},
+  {127,   159,  255},
+  {0,   51,   204},
+  {102,   127,  204},
+  {0,   38,   153},
+  {76,  95,   153},
+  {0,   31,   127},
+  {63,  79,   127},
+  {0,   19,   76},
+  {38,  47,   76},
+  {0,   0,  255},
+  {127,   127,  255},
+  {0,   0,  204},
+  {102,   102,  204},
+  {0,   0,  153},
+  {76,  76,   153},
+  {0,   0,  127},
+  {63,  63,   127},
+  {0,   0,  76},
+  {38,  38,   76},
+  {63,  0,  255},
+  {159,   127,  255},
+  {51,  0,  204},
+  {127,   102,  204},
+  {38,  0,  153},
+  {95,  76,   153},
+  {31,  0,  127},
+  {79,  63,   127},
+  {19,  0,  76},
+  {47,  38,   76},
+  {127,   0,  255},
+  {191,   127,  255},
+  {102,   0,  204},
+  {153,   102,  204},
+  {76,  0,  153},
+  {114,   76,   153},
+  {63,  0,  127},
+  {95,  63,   127},
+  {38,  0,  76},
+  {57,  38,   76},
+  {191,   0,  255},
+  {223,   127,  255},
+  {153,   0,  204},
+  {178,   102,  204},
+  {114,   0,  153},
+  {133,   76,   153},
+  {95,  0,  127},
+  {111,   63,   127},
+  {57,  0,  76},
+  {66,  38,   76},
+  {255,   0,  255},
+  {255,   127,  255},
+  {204,   0,  204},
+  {204,   102,  204},
+  {153,   0,  153},
+  {153,   76,   153},
+  {127,   0,  127},
+  {127,   63,   127},
+  {76,  0,  76},
+  {76,  38,   76},
+  {255,   0,  191},
+  {255,   127,  223},
+  {204,   0,  153},
+  {204,   102,  178},
+  {153,   0,  114},
+  {153,   76,   133},
+  {127,   0,  95},
+  {127,   63,   111},
+  {76,  0,  57},
+  {76,  38,   66},
+  {255,   0,  127},
+  {255,   127,  191},
+  {204,   0,  102},
+  {204,   102,  153},
+  {153,   0,  76},
+  {153,   76,   114},
+  {127,   0,  63},
+  {127,   63,   95},
+  {76,  0,  38},
+  {76,  38,   57},
+  {255,   0,  63},
+  {255,   127,  159},
+  {204,   0,  51},
+  {204,   102,  127},
+  {153,   0,  38},
+  {153,   76,   95},
+  {127,   0,  31},
+  {127,   63,   79},
+  {76,  0,  19},
+  {76,  38,   47},
+  {51,  51,   51},
+  {91,  91,   91},
+  {132,   132,  132},
+  {173,   173,  173},
+  {214,   214,  214},
+  {255,   255,  255},
 };
diff --git a/install-sh b/install-sh
new file mode 100755
index 0000000..a9244eb
--- /dev/null
+++ b/install-sh
@@ -0,0 +1,527 @@
+#!/bin/sh
+# install - install a program, script, or datafile
+
+scriptversion=2011-01-19.21; # UTC
+
+# This originates from X11R5 (mit/util/scripts/install.sh), which was
+# later released in X11R6 (xc/config/util/install.sh) with the
+# following copyright and license.
+#
+# Copyright (C) 1994 X Consortium
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to
+# deal in the Software without restriction, including without limitation the
+# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+# sell copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
+# X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNEC-
+# TION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+#
+# Except as contained in this notice, the name of the X Consortium shall not
+# be used in advertising or otherwise to promote the sale, use or other deal-
+# ings in this Software without prior written authorization from the X Consor-
+# tium.
+#
+#
+# FSF changes to this file are in the public domain.
+#
+# Calling this script install-sh is preferred over install.sh, to prevent
+# `make' implicit rules from creating a file called install from it
+# when there is no Makefile.
+#
+# This script is compatible with the BSD install script, but was written
+# from scratch.
+
+nl='
+'
+IFS=" ""	$nl"
+
+# set DOITPROG to echo to test this script
+
+# Don't use :- since 4.3BSD and earlier shells don't like it.
+doit=${DOITPROG-}
+if test -z "$doit"; then
+  doit_exec=exec
+else
+  doit_exec=$doit
+fi
+
+# Put in absolute file names if you don't have them in your path;
+# or use environment vars.
+
+chgrpprog=${CHGRPPROG-chgrp}
+chmodprog=${CHMODPROG-chmod}
+chownprog=${CHOWNPROG-chown}
+cmpprog=${CMPPROG-cmp}
+cpprog=${CPPROG-cp}
+mkdirprog=${MKDIRPROG-mkdir}
+mvprog=${MVPROG-mv}
+rmprog=${RMPROG-rm}
+stripprog=${STRIPPROG-strip}
+
+posix_glob='?'
+initialize_posix_glob='
+  test "$posix_glob" != "?" || {
+    if (set -f) 2>/dev/null; then
+      posix_glob=
+    else
+      posix_glob=:
+    fi
+  }
+'
+
+posix_mkdir=
+
+# Desired mode of installed file.
+mode=0755
+
+chgrpcmd=
+chmodcmd=$chmodprog
+chowncmd=
+mvcmd=$mvprog
+rmcmd="$rmprog -f"
+stripcmd=
+
+src=
+dst=
+dir_arg=
+dst_arg=
+
+copy_on_change=false
+no_target_directory=
+
+usage="\
+Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE
+   or: $0 [OPTION]... SRCFILES... DIRECTORY
+   or: $0 [OPTION]... -t DIRECTORY SRCFILES...
+   or: $0 [OPTION]... -d DIRECTORIES...
+
+In the 1st form, copy SRCFILE to DSTFILE.
+In the 2nd and 3rd, copy all SRCFILES to DIRECTORY.
+In the 4th, create DIRECTORIES.
+
+Options:
+     --help     display this help and exit.
+     --version  display version info and exit.
+
+  -c            (ignored)
+  -C            install only if different (preserve the last data modification time)
+  -d            create directories instead of installing files.
+  -g GROUP      $chgrpprog installed files to GROUP.
+  -m MODE       $chmodprog installed files to MODE.
+  -o USER       $chownprog installed files to USER.
+  -s            $stripprog installed files.
+  -t DIRECTORY  install into DIRECTORY.
+  -T            report an error if DSTFILE is a directory.
+
+Environment variables override the default commands:
+  CHGRPPROG CHMODPROG CHOWNPROG CMPPROG CPPROG MKDIRPROG MVPROG
+  RMPROG STRIPPROG
+"
+
+while test $# -ne 0; do
+  case $1 in
+    -c) ;;
+
+    -C) copy_on_change=true;;
+
+    -d) dir_arg=true;;
+
+    -g) chgrpcmd="$chgrpprog $2"
+	shift;;
+
+    --help) echo "$usage"; exit $?;;
+
+    -m) mode=$2
+	case $mode in
+	  *' '* | *'	'* | *'
+'*	  | *'*'* | *'?'* | *'['*)
+	    echo "$0: invalid mode: $mode" >&2
+	    exit 1;;
+	esac
+	shift;;
+
+    -o) chowncmd="$chownprog $2"
+	shift;;
+
+    -s) stripcmd=$stripprog;;
+
+    -t) dst_arg=$2
+	# Protect names problematic for `test' and other utilities.
+	case $dst_arg in
+	  -* | [=\(\)!]) dst_arg=./$dst_arg;;
+	esac
+	shift;;
+
+    -T) no_target_directory=true;;
+
+    --version) echo "$0 $scriptversion"; exit $?;;
+
+    --)	shift
+	break;;
+
+    -*)	echo "$0: invalid option: $1" >&2
+	exit 1;;
+
+    *)  break;;
+  esac
+  shift
+done
+
+if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then
+  # When -d is used, all remaining arguments are directories to create.
+  # When -t is used, the destination is already specified.
+  # Otherwise, the last argument is the destination.  Remove it from $@.
+  for arg
+  do
+    if test -n "$dst_arg"; then
+      # $@ is not empty: it contains at least $arg.
+      set fnord "$@" "$dst_arg"
+      shift # fnord
+    fi
+    shift # arg
+    dst_arg=$arg
+    # Protect names problematic for `test' and other utilities.
+    case $dst_arg in
+      -* | [=\(\)!]) dst_arg=./$dst_arg;;
+    esac
+  done
+fi
+
+if test $# -eq 0; then
+  if test -z "$dir_arg"; then
+    echo "$0: no input file specified." >&2
+    exit 1
+  fi
+  # It's OK to call `install-sh -d' without argument.
+  # This can happen when creating conditional directories.
+  exit 0
+fi
+
+if test -z "$dir_arg"; then
+  do_exit='(exit $ret); exit $ret'
+  trap "ret=129; $do_exit" 1
+  trap "ret=130; $do_exit" 2
+  trap "ret=141; $do_exit" 13
+  trap "ret=143; $do_exit" 15
+
+  # Set umask so as not to create temps with too-generous modes.
+  # However, 'strip' requires both read and write access to temps.
+  case $mode in
+    # Optimize common cases.
+    *644) cp_umask=133;;
+    *755) cp_umask=22;;
+
+    *[0-7])
+      if test -z "$stripcmd"; then
+	u_plus_rw=
+      else
+	u_plus_rw='% 200'
+      fi
+      cp_umask=`expr '(' 777 - $mode % 1000 ')' $u_plus_rw`;;
+    *)
+      if test -z "$stripcmd"; then
+	u_plus_rw=
+      else
+	u_plus_rw=,u+rw
+      fi
+      cp_umask=$mode$u_plus_rw;;
+  esac
+fi
+
+for src
+do
+  # Protect names problematic for `test' and other utilities.
+  case $src in
+    -* | [=\(\)!]) src=./$src;;
+  esac
+
+  if test -n "$dir_arg"; then
+    dst=$src
+    dstdir=$dst
+    test -d "$dstdir"
+    dstdir_status=$?
+  else
+
+    # Waiting for this to be detected by the "$cpprog $src $dsttmp" command
+    # might cause directories to be created, which would be especially bad
+    # if $src (and thus $dsttmp) contains '*'.
+    if test ! -f "$src" && test ! -d "$src"; then
+      echo "$0: $src does not exist." >&2
+      exit 1
+    fi
+
+    if test -z "$dst_arg"; then
+      echo "$0: no destination specified." >&2
+      exit 1
+    fi
+    dst=$dst_arg
+
+    # If destination is a directory, append the input filename; won't work
+    # if double slashes aren't ignored.
+    if test -d "$dst"; then
+      if test -n "$no_target_directory"; then
+	echo "$0: $dst_arg: Is a directory" >&2
+	exit 1
+      fi
+      dstdir=$dst
+      dst=$dstdir/`basename "$src"`
+      dstdir_status=0
+    else
+      # Prefer dirname, but fall back on a substitute if dirname fails.
+      dstdir=`
+	(dirname "$dst") 2>/dev/null ||
+	expr X"$dst" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	     X"$dst" : 'X\(//\)[^/]' \| \
+	     X"$dst" : 'X\(//\)$' \| \
+	     X"$dst" : 'X\(/\)' \| . 2>/dev/null ||
+	echo X"$dst" |
+	    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+		   s//\1/
+		   q
+		 }
+		 /^X\(\/\/\)[^/].*/{
+		   s//\1/
+		   q
+		 }
+		 /^X\(\/\/\)$/{
+		   s//\1/
+		   q
+		 }
+		 /^X\(\/\).*/{
+		   s//\1/
+		   q
+		 }
+		 s/.*/./; q'
+      `
+
+      test -d "$dstdir"
+      dstdir_status=$?
+    fi
+  fi
+
+  obsolete_mkdir_used=false
+
+  if test $dstdir_status != 0; then
+    case $posix_mkdir in
+      '')
+	# Create intermediate dirs using mode 755 as modified by the umask.
+	# This is like FreeBSD 'install' as of 1997-10-28.
+	umask=`umask`
+	case $stripcmd.$umask in
+	  # Optimize common cases.
+	  *[2367][2367]) mkdir_umask=$umask;;
+	  .*0[02][02] | .[02][02] | .[02]) mkdir_umask=22;;
+
+	  *[0-7])
+	    mkdir_umask=`expr $umask + 22 \
+	      - $umask % 100 % 40 + $umask % 20 \
+	      - $umask % 10 % 4 + $umask % 2
+	    `;;
+	  *) mkdir_umask=$umask,go-w;;
+	esac
+
+	# With -d, create the new directory with the user-specified mode.
+	# Otherwise, rely on $mkdir_umask.
+	if test -n "$dir_arg"; then
+	  mkdir_mode=-m$mode
+	else
+	  mkdir_mode=
+	fi
+
+	posix_mkdir=false
+	case $umask in
+	  *[123567][0-7][0-7])
+	    # POSIX mkdir -p sets u+wx bits regardless of umask, which
+	    # is incompatible with FreeBSD 'install' when (umask & 300) != 0.
+	    ;;
+	  *)
+	    tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$
+	    trap 'ret=$?; rmdir "$tmpdir/d" "$tmpdir" 2>/dev/null; exit $ret' 0
+
+	    if (umask $mkdir_umask &&
+		exec $mkdirprog $mkdir_mode -p -- "$tmpdir/d") >/dev/null 2>&1
+	    then
+	      if test -z "$dir_arg" || {
+		   # Check for POSIX incompatibilities with -m.
+		   # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or
+		   # other-writeable bit of parent directory when it shouldn't.
+		   # FreeBSD 6.1 mkdir -m -p sets mode of existing directory.
+		   ls_ld_tmpdir=`ls -ld "$tmpdir"`
+		   case $ls_ld_tmpdir in
+		     d????-?r-*) different_mode=700;;
+		     d????-?--*) different_mode=755;;
+		     *) false;;
+		   esac &&
+		   $mkdirprog -m$different_mode -p -- "$tmpdir" && {
+		     ls_ld_tmpdir_1=`ls -ld "$tmpdir"`
+		     test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1"
+		   }
+		 }
+	      then posix_mkdir=:
+	      fi
+	      rmdir "$tmpdir/d" "$tmpdir"
+	    else
+	      # Remove any dirs left behind by ancient mkdir implementations.
+	      rmdir ./$mkdir_mode ./-p ./-- 2>/dev/null
+	    fi
+	    trap '' 0;;
+	esac;;
+    esac
+
+    if
+      $posix_mkdir && (
+	umask $mkdir_umask &&
+	$doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir"
+      )
+    then :
+    else
+
+      # The umask is ridiculous, or mkdir does not conform to POSIX,
+      # or it failed possibly due to a race condition.  Create the
+      # directory the slow way, step by step, checking for races as we go.
+
+      case $dstdir in
+	/*) prefix='/';;
+	[-=\(\)!]*) prefix='./';;
+	*)  prefix='';;
+      esac
+
+      eval "$initialize_posix_glob"
+
+      oIFS=$IFS
+      IFS=/
+      $posix_glob set -f
+      set fnord $dstdir
+      shift
+      $posix_glob set +f
+      IFS=$oIFS
+
+      prefixes=
+
+      for d
+      do
+	test X"$d" = X && continue
+
+	prefix=$prefix$d
+	if test -d "$prefix"; then
+	  prefixes=
+	else
+	  if $posix_mkdir; then
+	    (umask=$mkdir_umask &&
+	     $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break
+	    # Don't fail if two instances are running concurrently.
+	    test -d "$prefix" || exit 1
+	  else
+	    case $prefix in
+	      *\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;;
+	      *) qprefix=$prefix;;
+	    esac
+	    prefixes="$prefixes '$qprefix'"
+	  fi
+	fi
+	prefix=$prefix/
+      done
+
+      if test -n "$prefixes"; then
+	# Don't fail if two instances are running concurrently.
+	(umask $mkdir_umask &&
+	 eval "\$doit_exec \$mkdirprog $prefixes") ||
+	  test -d "$dstdir" || exit 1
+	obsolete_mkdir_used=true
+      fi
+    fi
+  fi
+
+  if test -n "$dir_arg"; then
+    { test -z "$chowncmd" || $doit $chowncmd "$dst"; } &&
+    { test -z "$chgrpcmd" || $doit $chgrpcmd "$dst"; } &&
+    { test "$obsolete_mkdir_used$chowncmd$chgrpcmd" = false ||
+      test -z "$chmodcmd" || $doit $chmodcmd $mode "$dst"; } || exit 1
+  else
+
+    # Make a couple of temp file names in the proper directory.
+    dsttmp=$dstdir/_inst.$$_
+    rmtmp=$dstdir/_rm.$$_
+
+    # Trap to clean up those temp files at exit.
+    trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0
+
+    # Copy the file name to the temp name.
+    (umask $cp_umask && $doit_exec $cpprog "$src" "$dsttmp") &&
+
+    # and set any options; do chmod last to preserve setuid bits.
+    #
+    # If any of these fail, we abort the whole thing.  If we want to
+    # ignore errors from any of these, just make sure not to ignore
+    # errors from the above "$doit $cpprog $src $dsttmp" command.
+    #
+    { test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } &&
+    { test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } &&
+    { test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } &&
+    { test -z "$chmodcmd" || $doit $chmodcmd $mode "$dsttmp"; } &&
+
+    # If -C, don't bother to copy if it wouldn't change the file.
+    if $copy_on_change &&
+       old=`LC_ALL=C ls -dlL "$dst"	2>/dev/null` &&
+       new=`LC_ALL=C ls -dlL "$dsttmp"	2>/dev/null` &&
+
+       eval "$initialize_posix_glob" &&
+       $posix_glob set -f &&
+       set X $old && old=:$2:$4:$5:$6 &&
+       set X $new && new=:$2:$4:$5:$6 &&
+       $posix_glob set +f &&
+
+       test "$old" = "$new" &&
+       $cmpprog "$dst" "$dsttmp" >/dev/null 2>&1
+    then
+      rm -f "$dsttmp"
+    else
+      # Rename the file to the real destination.
+      $doit $mvcmd -f "$dsttmp" "$dst" 2>/dev/null ||
+
+      # The rename failed, perhaps because mv can't rename something else
+      # to itself, or perhaps because mv is so ancient that it does not
+      # support -f.
+      {
+	# Now remove or move aside any old file at destination location.
+	# We try this two ways since rm can't unlink itself on some
+	# systems and the destination file might be busy for other
+	# reasons.  In this case, the final cleanup might fail but the new
+	# file should still install successfully.
+	{
+	  test ! -f "$dst" ||
+	  $doit $rmcmd -f "$dst" 2>/dev/null ||
+	  { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null &&
+	    { $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; }
+	  } ||
+	  { echo "$0: cannot unlink or rename $dst" >&2
+	    (exit 1); exit 1
+	  }
+	} &&
+
+	# Now rename the file to the real destination.
+	$doit $mvcmd "$dsttmp" "$dst"
+      }
+    fi || exit 1
+
+    trap '' 0
+  fi
+done
+
+# Local variables:
+# eval: (add-hook 'write-file-hooks 'time-stamp)
+# time-stamp-start: "scriptversion="
+# time-stamp-format: "%:y-%02m-%02d.%02H"
+# time-stamp-time-zone: "UTC"
+# time-stamp-end: "; # UTC"
+# End:
diff --git a/layerobject.c b/layerobject.c
index c2cc75d..b5f74de 100644
--- a/layerobject.c
+++ b/layerobject.c
@@ -3,7 +3,7 @@
  *
  * Project:  MapServer
  * Purpose:  Functions for operating on a layerObj that don't belong in a
- *           more specific file such as mapfile.c.  
+ *           more specific file such as mapfile.c.
  *           Adapted from mapobject.c.
  * Author:   Sean Gillies, sgillies at frii.com
  *
@@ -17,7 +17,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -36,72 +36,68 @@
 #  include "cpl_conv.h"
 #endif
 
-MS_CVSID("$Id$")
+
 
 /* ===========================================================================
    msInsertClass
 
    Returns the index at which the class was inserted.
    ======================================================================== */
- 
-int msInsertClass(layerObj *layer, classObj *classobj, int nIndex) 
-{
-    int i;
 
-    if (!classobj)
-    {
-        msSetError(MS_CHILDERR, "Cannot insert NULL class", "msInsertClass()");
-        return -1;
-    }
-        
-    /* Ensure there is room for a new class */
-    if (msGrowLayerClasses(layer) == NULL) {
-        return -1;
-    }
-    /* Catch attempt to insert past end of styles array */
-    else if (nIndex >= layer->numclasses) {
-        msSetError(MS_CHILDERR, "Cannot insert class beyond index %d",
-                   "msInsertClass()", layer->numclasses-1);
-        return -1;
-    }
-    else if (nIndex < 0) { /* Insert at the end by default */
+int msInsertClass(layerObj *layer, classObj *classobj, int nIndex)
+{
+  int i;
+
+  if (!classobj) {
+    msSetError(MS_CHILDERR, "Cannot insert NULL class", "msInsertClass()");
+    return -1;
+  }
+
+  /* Ensure there is room for a new class */
+  if (msGrowLayerClasses(layer) == NULL) {
+    return -1;
+  }
+  /* Catch attempt to insert past end of styles array */
+  else if (nIndex >= layer->numclasses) {
+    msSetError(MS_CHILDERR, "Cannot insert class beyond index %d",
+               "msInsertClass()", layer->numclasses-1);
+    return -1;
+  } else if (nIndex < 0) { /* Insert at the end by default */
 #ifndef __cplusplus
-        layer->class[layer->numclasses]=classobj;
+    layer->class[layer->numclasses]=classobj;
 #else
-        layer->_class[layer->numclasses]=classobj;
+    layer->_class[layer->numclasses]=classobj;
 #endif
-	/* set parent pointer */
-	classobj->layer=layer;
-	MS_REFCNT_INCR(classobj);
-        layer->numclasses++;
-        return layer->numclasses-1;
-    }
-    else if (nIndex >= 0 && nIndex < layer->numclasses) {
-    
-        /* Copy classes existing at the specified nIndex or greater */
-        /* to an index one higher */
+    /* set parent pointer */
+    classobj->layer=layer;
+    MS_REFCNT_INCR(classobj);
+    layer->numclasses++;
+    return layer->numclasses-1;
+  } else if (nIndex >= 0 && nIndex < layer->numclasses) {
+
+    /* Copy classes existing at the specified nIndex or greater */
+    /* to an index one higher */
 
 #ifndef __cplusplus
-        for (i=layer->numclasses-1; i>=nIndex; i--)
-            layer->class[i+1] = layer->class[i];
-        layer->class[nIndex]=classobj;
+    for (i=layer->numclasses-1; i>=nIndex; i--)
+      layer->class[i+1] = layer->class[i];
+    layer->class[nIndex]=classobj;
 #else
-        for (i=layer->numclasses-1; i>=nIndex; i--)
-            layer->_class[i+1] = layer->_class[i];
-        layer->_class[nIndex]=classobj;
+    for (i=layer->numclasses-1; i>=nIndex; i--)
+      layer->_class[i+1] = layer->_class[i];
+    layer->_class[nIndex]=classobj;
 #endif
 
-	/* set parent pointer */
-	classobj->layer=layer;
-	MS_REFCNT_INCR(classobj);
-        /* increment number of classes and return */
-        layer->numclasses++;
-        return nIndex;
-    }
-    else {
-        msSetError(MS_CHILDERR, "Invalid index", "msInsertClass()");
-        return -1;
-    }
+    /* set parent pointer */
+    classobj->layer=layer;
+    MS_REFCNT_INCR(classobj);
+    /* increment number of classes and return */
+    layer->numclasses++;
+    return nIndex;
+  } else {
+    msSetError(MS_CHILDERR, "Invalid index", "msInsertClass()");
+    return -1;
+  }
 }
 
 /* ===========================================================================
@@ -110,111 +106,105 @@ int msInsertClass(layerObj *layer, classObj *classobj, int nIndex)
    remove the class at an index from a layer, returning a copy
    ======================================================================== */
 
-classObj *msRemoveClass(layerObj *layer, int nIndex) 
+classObj *msRemoveClass(layerObj *layer, int nIndex)
 {
-    int i;
-    classObj *classobj;
-    
-    if (nIndex < 0 || nIndex >= layer->numclasses)
-    {
-        msSetError(MS_CHILDERR, "Cannot remove class, invalid index %d",
-                   "removeClass()", nIndex);
-        return NULL;
-    }
-    else 
-    {
+  int i;
+  classObj *classobj;
+
+  if (nIndex < 0 || nIndex >= layer->numclasses) {
+    msSetError(MS_CHILDERR, "Cannot remove class, invalid index %d",
+               "removeClass()", nIndex);
+    return NULL;
+  } else {
 #ifndef __cplusplus
-        classobj=layer->class[nIndex];
+    classobj=layer->class[nIndex];
 #else
-        classobj=layer->_class[nIndex];
+    classobj=layer->_class[nIndex];
 #endif
-	classobj->layer=NULL;
-	MS_REFCNT_DECR(classobj);
+    classobj->layer=NULL;
+    MS_REFCNT_DECR(classobj);
 
-        /* Iteratively copy the higher index classes down one index */
-        for (i=nIndex; i<layer->numclasses-1; i++)
-        {
+    /* Iteratively copy the higher index classes down one index */
+    for (i=nIndex; i<layer->numclasses-1; i++) {
 #ifndef __cplusplus
-            layer->class[i]=layer->class[i+1];
+      layer->class[i]=layer->class[i+1];
 #else
-            layer->_class[i]=layer->_class[i+1];
+      layer->_class[i]=layer->_class[i+1];
 #endif
-        }
+    }
 #ifndef __cplusplus
-        layer->class[i]=NULL;
+    layer->class[i]=NULL;
 #else
-        layer->_class[i]=NULL;
+    layer->_class[i]=NULL;
 #endif
-        
-        /* decrement number of layers and return copy of removed layer */
-        layer->numclasses--;
-        return classobj;
-    }
+
+    /* decrement number of layers and return copy of removed layer */
+    layer->numclasses--;
+    return classobj;
+  }
 }
 
 /**
  * Move the class up inside the array of classes.
- */  
+ */
 int msMoveClassUp(layerObj *layer, int nClassIndex)
 {
-    classObj *psTmpClass = NULL;
-    if (layer && nClassIndex < layer->numclasses && nClassIndex >0)
-    {
-        psTmpClass=layer->class[nClassIndex];
+  classObj *psTmpClass = NULL;
+  if (layer && nClassIndex < layer->numclasses && nClassIndex >0) {
+    psTmpClass=layer->class[nClassIndex];
 
-        layer->class[nClassIndex] = layer->class[nClassIndex-1];
-        
-        layer->class[nClassIndex-1] = psTmpClass;
+    layer->class[nClassIndex] = layer->class[nClassIndex-1];
 
-        return(MS_SUCCESS);
-    }
-    msSetError(MS_CHILDERR, "Invalid index: %d", "msMoveClassUp()",
-               nClassIndex);
-    return (MS_FAILURE);
+    layer->class[nClassIndex-1] = psTmpClass;
+
+    return(MS_SUCCESS);
+  }
+  msSetError(MS_CHILDERR, "Invalid index: %d", "msMoveClassUp()",
+             nClassIndex);
+  return (MS_FAILURE);
 }
 
 
 /**
  * Move the class down inside the array of classes.
- */  
+ */
 int msMoveClassDown(layerObj *layer, int nClassIndex)
 {
-    classObj *psTmpClass = NULL;
-    if (layer && nClassIndex < layer->numclasses-1 && nClassIndex >=0)
-    {
-        psTmpClass=layer->class[nClassIndex];
+  classObj *psTmpClass = NULL;
+  if (layer && nClassIndex < layer->numclasses-1 && nClassIndex >=0) {
+    psTmpClass=layer->class[nClassIndex];
 
-        layer->class[nClassIndex] = layer->class[nClassIndex+1];
+    layer->class[nClassIndex] = layer->class[nClassIndex+1];
 
-        layer->class[nClassIndex+1] = psTmpClass;
+    layer->class[nClassIndex+1] = psTmpClass;
 
-        return(MS_SUCCESS);
-    }
-    msSetError(MS_CHILDERR, "Invalid index: %d", "msMoveClassDown()",
-               nClassIndex);
-    return (MS_FAILURE);
+    return(MS_SUCCESS);
+  }
+  msSetError(MS_CHILDERR, "Invalid index: %d", "msMoveClassDown()",
+             nClassIndex);
+  return (MS_FAILURE);
 }
 
 /**
  * Set the extent of a layer.
- */  
-
-int msLayerSetExtent( layerObj *layer, 
-                    double minx, double miny, double maxx, double maxy) 
-{ 
-
-    layer->extent.minx = minx;
-    layer->extent.miny = miny;
-    layer->extent.maxx = maxx;
-    layer->extent.maxy = maxy;
-    
-    if (minx == -1.0 && miny == -1.0 && maxx == -1.0 && maxy == -1.0)
-      return(MS_SUCCESS);
-      
-    if (!MS_VALID_EXTENT(layer->extent)) {
-      msSetError(MS_MISCERR, "Given layer extent is invalid. minx=%lf, miny=%lf, maxx=%lf, maxy=%lf.", "msLayerSetExtent()", layer->extent.minx, layer->extent.miny, layer->extent.maxx, layer->extent.maxy); 
-      return(MS_FAILURE);
-      }
-      
+ */
+
+int msLayerSetExtent( layerObj *layer,
+                      double minx, double miny, double maxx, double maxy)
+{
+
+  layer->extent.minx = minx;
+  layer->extent.miny = miny;
+  layer->extent.maxx = maxx;
+  layer->extent.maxy = maxy;
+
+  if (minx == -1.0 && miny == -1.0 && maxx == -1.0 && maxy == -1.0)
     return(MS_SUCCESS);
+
+  if (!MS_VALID_EXTENT(layer->extent)) {
+    msSetError(MS_MISCERR, "Given layer extent is invalid. minx=%lf, miny=%lf, maxx=%lf, maxy=%lf.", "msLayerSetExtent()", layer->extent.minx, layer->extent.miny, layer->extent.maxx, layer->extent.maxy);
+    return(MS_FAILURE);
+  }
+
+  return(MS_SUCCESS);
 }
diff --git a/legend.c b/legend.c
index 1377af5..0549aed 100644
--- a/legend.c
+++ b/legend.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -29,7 +29,7 @@
 
 #include "mapserver.h"
 
-MS_CVSID("$Id$")
+
 
 int main(int argc, char *argv[])
 {
@@ -42,8 +42,8 @@ int main(int argc, char *argv[])
   }
 
   if( argc < 3 ) {
-      fprintf(stdout,"Syntax: legend [mapfile] [output image]\n" );
-      exit(0);
+    fprintf(stdout,"Syntax: legend [mapfile] [output image]\n" );
+    exit(0);
   }
 
   map = msLoadMap(argv[1], NULL);
@@ -62,6 +62,6 @@ int main(int argc, char *argv[])
 
   msFreeImage(img);
   msFreeMap(map);
-  
+
   return(MS_TRUE);
 }
diff --git a/ltmain.sh b/ltmain.sh
new file mode 100644
index 0000000..63ae69d
--- /dev/null
+++ b/ltmain.sh
@@ -0,0 +1,9655 @@
+
+# libtool (GNU libtool) 2.4.2
+# Written by Gordon Matzigkeit <gord at gnu.ai.mit.edu>, 1996
+
+# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, 2006,
+# 2007, 2008, 2009, 2010, 2011 Free Software Foundation, Inc.
+# This is free software; see the source for copying conditions.  There is NO
+# warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+
+# GNU Libtool is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# As a special exception to the GNU General Public License,
+# if you distribute this file as part of a program or library that
+# is built using GNU Libtool, you may include this file under the
+# same distribution terms that you use for the rest of that program.
+#
+# GNU Libtool is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with GNU Libtool; see the file COPYING.  If not, a copy
+# can be downloaded from http://www.gnu.org/licenses/gpl.html,
+# or obtained by writing to the Free Software Foundation, Inc.,
+# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+
+# Usage: $progname [OPTION]... [MODE-ARG]...
+#
+# Provide generalized library-building support services.
+#
+#       --config             show all configuration variables
+#       --debug              enable verbose shell tracing
+#   -n, --dry-run            display commands without modifying any files
+#       --features           display basic configuration information and exit
+#       --mode=MODE          use operation mode MODE
+#       --preserve-dup-deps  don't remove duplicate dependency libraries
+#       --quiet, --silent    don't print informational messages
+#       --no-quiet, --no-silent
+#                            print informational messages (default)
+#       --no-warn            don't display warning messages
+#       --tag=TAG            use configuration variables from tag TAG
+#   -v, --verbose            print more informational messages than default
+#       --no-verbose         don't print the extra informational messages
+#       --version            print version information
+#   -h, --help, --help-all   print short, long, or detailed help message
+#
+# MODE must be one of the following:
+#
+#         clean              remove files from the build directory
+#         compile            compile a source file into a libtool object
+#         execute            automatically set library path, then run a program
+#         finish             complete the installation of libtool libraries
+#         install            install libraries or executables
+#         link               create a library or an executable
+#         uninstall          remove libraries from an installed directory
+#
+# MODE-ARGS vary depending on the MODE.  When passed as first option,
+# `--mode=MODE' may be abbreviated as `MODE' or a unique abbreviation of that.
+# Try `$progname --help --mode=MODE' for a more detailed description of MODE.
+#
+# When reporting a bug, please describe a test case to reproduce it and
+# include the following information:
+#
+#         host-triplet:	$host
+#         shell:		$SHELL
+#         compiler:		$LTCC
+#         compiler flags:		$LTCFLAGS
+#         linker:		$LD (gnu? $with_gnu_ld)
+#         $progname:	(GNU libtool) 2.4.2
+#         automake:	$automake_version
+#         autoconf:	$autoconf_version
+#
+# Report bugs to <bug-libtool at gnu.org>.
+# GNU libtool home page: <http://www.gnu.org/software/libtool/>.
+# General help using GNU software: <http://www.gnu.org/gethelp/>.
+
+PROGRAM=libtool
+PACKAGE=libtool
+VERSION=2.4.2
+TIMESTAMP=""
+package_revision=1.3337
+
+# Be Bourne compatible
+if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
+  emulate sh
+  NULLCMD=:
+  # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
+  # is contrary to our usage.  Disable this feature.
+  alias -g '${1+"$@"}'='"$@"'
+  setopt NO_GLOB_SUBST
+else
+  case `(set -o) 2>/dev/null` in *posix*) set -o posix;; esac
+fi
+BIN_SH=xpg4; export BIN_SH # for Tru64
+DUALCASE=1; export DUALCASE # for MKS sh
+
+# A function that is used when there is no print builtin or printf.
+func_fallback_echo ()
+{
+  eval 'cat <<_LTECHO_EOF
+$1
+_LTECHO_EOF'
+}
+
+# NLS nuisances: We save the old values to restore during execute mode.
+lt_user_locale=
+lt_safe_locale=
+for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES
+do
+  eval "if test \"\${$lt_var+set}\" = set; then
+          save_$lt_var=\$$lt_var
+          $lt_var=C
+	  export $lt_var
+	  lt_user_locale=\"$lt_var=\\\$save_\$lt_var; \$lt_user_locale\"
+	  lt_safe_locale=\"$lt_var=C; \$lt_safe_locale\"
+	fi"
+done
+LC_ALL=C
+LANGUAGE=C
+export LANGUAGE LC_ALL
+
+$lt_unset CDPATH
+
+
+# Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh
+# is ksh but when the shell is invoked as "sh" and the current value of
+# the _XPG environment variable is not equal to 1 (one), the special
+# positional parameter $0, within a function call, is the name of the
+# function.
+progpath="$0"
+
+
+
+: ${CP="cp -f"}
+test "${ECHO+set}" = set || ECHO=${as_echo-'printf %s\n'}
+: ${MAKE="make"}
+: ${MKDIR="mkdir"}
+: ${MV="mv -f"}
+: ${RM="rm -f"}
+: ${SHELL="${CONFIG_SHELL-/bin/sh}"}
+: ${Xsed="$SED -e 1s/^X//"}
+
+# Global variables:
+EXIT_SUCCESS=0
+EXIT_FAILURE=1
+EXIT_MISMATCH=63  # $? = 63 is used to indicate version mismatch to missing.
+EXIT_SKIP=77	  # $? = 77 is used to indicate a skipped test to automake.
+
+exit_status=$EXIT_SUCCESS
+
+# Make sure IFS has a sensible default
+lt_nl='
+'
+IFS=" 	$lt_nl"
+
+dirname="s,/[^/]*$,,"
+basename="s,^.*/,,"
+
+# func_dirname file append nondir_replacement
+# Compute the dirname of FILE.  If nonempty, add APPEND to the result,
+# otherwise set result to NONDIR_REPLACEMENT.
+func_dirname ()
+{
+    func_dirname_result=`$ECHO "${1}" | $SED "$dirname"`
+    if test "X$func_dirname_result" = "X${1}"; then
+      func_dirname_result="${3}"
+    else
+      func_dirname_result="$func_dirname_result${2}"
+    fi
+} # func_dirname may be replaced by extended shell implementation
+
+
+# func_basename file
+func_basename ()
+{
+    func_basename_result=`$ECHO "${1}" | $SED "$basename"`
+} # func_basename may be replaced by extended shell implementation
+
+
+# func_dirname_and_basename file append nondir_replacement
+# perform func_basename and func_dirname in a single function
+# call:
+#   dirname:  Compute the dirname of FILE.  If nonempty,
+#             add APPEND to the result, otherwise set result
+#             to NONDIR_REPLACEMENT.
+#             value returned in "$func_dirname_result"
+#   basename: Compute filename of FILE.
+#             value retuned in "$func_basename_result"
+# Implementation must be kept synchronized with func_dirname
+# and func_basename. For efficiency, we do not delegate to
+# those functions but instead duplicate the functionality here.
+func_dirname_and_basename ()
+{
+    # Extract subdirectory from the argument.
+    func_dirname_result=`$ECHO "${1}" | $SED -e "$dirname"`
+    if test "X$func_dirname_result" = "X${1}"; then
+      func_dirname_result="${3}"
+    else
+      func_dirname_result="$func_dirname_result${2}"
+    fi
+    func_basename_result=`$ECHO "${1}" | $SED -e "$basename"`
+} # func_dirname_and_basename may be replaced by extended shell implementation
+
+
+# func_stripname prefix suffix name
+# strip PREFIX and SUFFIX off of NAME.
+# PREFIX and SUFFIX must not contain globbing or regex special
+# characters, hashes, percent signs, but SUFFIX may contain a leading
+# dot (in which case that matches only a dot).
+# func_strip_suffix prefix name
+func_stripname ()
+{
+    case ${2} in
+      .*) func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%\\\\${2}\$%%"`;;
+      *)  func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%${2}\$%%"`;;
+    esac
+} # func_stripname may be replaced by extended shell implementation
+
+
+# These SED scripts presuppose an absolute path with a trailing slash.
+pathcar='s,^/\([^/]*\).*$,\1,'
+pathcdr='s,^/[^/]*,,'
+removedotparts=':dotsl
+		s@/\./@/@g
+		t dotsl
+		s,/\.$,/,'
+collapseslashes='s@/\{1,\}@/@g'
+finalslash='s,/*$,/,'
+
+# func_normal_abspath PATH
+# Remove doubled-up and trailing slashes, "." path components,
+# and cancel out any ".." path components in PATH after making
+# it an absolute path.
+#             value returned in "$func_normal_abspath_result"
+func_normal_abspath ()
+{
+  # Start from root dir and reassemble the path.
+  func_normal_abspath_result=
+  func_normal_abspath_tpath=$1
+  func_normal_abspath_altnamespace=
+  case $func_normal_abspath_tpath in
+    "")
+      # Empty path, that just means $cwd.
+      func_stripname '' '/' "`pwd`"
+      func_normal_abspath_result=$func_stripname_result
+      return
+    ;;
+    # The next three entries are used to spot a run of precisely
+    # two leading slashes without using negated character classes;
+    # we take advantage of case's first-match behaviour.
+    ///*)
+      # Unusual form of absolute path, do nothing.
+    ;;
+    //*)
+      # Not necessarily an ordinary path; POSIX reserves leading '//'
+      # and for example Cygwin uses it to access remote file shares
+      # over CIFS/SMB, so we conserve a leading double slash if found.
+      func_normal_abspath_altnamespace=/
+    ;;
+    /*)
+      # Absolute path, do nothing.
+    ;;
+    *)
+      # Relative path, prepend $cwd.
+      func_normal_abspath_tpath=`pwd`/$func_normal_abspath_tpath
+    ;;
+  esac
+  # Cancel out all the simple stuff to save iterations.  We also want
+  # the path to end with a slash for ease of parsing, so make sure
+  # there is one (and only one) here.
+  func_normal_abspath_tpath=`$ECHO "$func_normal_abspath_tpath" | $SED \
+        -e "$removedotparts" -e "$collapseslashes" -e "$finalslash"`
+  while :; do
+    # Processed it all yet?
+    if test "$func_normal_abspath_tpath" = / ; then
+      # If we ascended to the root using ".." the result may be empty now.
+      if test -z "$func_normal_abspath_result" ; then
+        func_normal_abspath_result=/
+      fi
+      break
+    fi
+    func_normal_abspath_tcomponent=`$ECHO "$func_normal_abspath_tpath" | $SED \
+        -e "$pathcar"`
+    func_normal_abspath_tpath=`$ECHO "$func_normal_abspath_tpath" | $SED \
+        -e "$pathcdr"`
+    # Figure out what to do with it
+    case $func_normal_abspath_tcomponent in
+      "")
+        # Trailing empty path component, ignore it.
+      ;;
+      ..)
+        # Parent dir; strip last assembled component from result.
+        func_dirname "$func_normal_abspath_result"
+        func_normal_abspath_result=$func_dirname_result
+      ;;
+      *)
+        # Actual path component, append it.
+        func_normal_abspath_result=$func_normal_abspath_result/$func_normal_abspath_tcomponent
+      ;;
+    esac
+  done
+  # Restore leading double-slash if one was found on entry.
+  func_normal_abspath_result=$func_normal_abspath_altnamespace$func_normal_abspath_result
+}
+
+# func_relative_path SRCDIR DSTDIR
+# generates a relative path from SRCDIR to DSTDIR, with a trailing
+# slash if non-empty, suitable for immediately appending a filename
+# without needing to append a separator.
+#             value returned in "$func_relative_path_result"
+func_relative_path ()
+{
+  func_relative_path_result=
+  func_normal_abspath "$1"
+  func_relative_path_tlibdir=$func_normal_abspath_result
+  func_normal_abspath "$2"
+  func_relative_path_tbindir=$func_normal_abspath_result
+
+  # Ascend the tree starting from libdir
+  while :; do
+    # check if we have found a prefix of bindir
+    case $func_relative_path_tbindir in
+      $func_relative_path_tlibdir)
+        # found an exact match
+        func_relative_path_tcancelled=
+        break
+        ;;
+      $func_relative_path_tlibdir*)
+        # found a matching prefix
+        func_stripname "$func_relative_path_tlibdir" '' "$func_relative_path_tbindir"
+        func_relative_path_tcancelled=$func_stripname_result
+        if test -z "$func_relative_path_result"; then
+          func_relative_path_result=.
+        fi
+        break
+        ;;
+      *)
+        func_dirname $func_relative_path_tlibdir
+        func_relative_path_tlibdir=${func_dirname_result}
+        if test "x$func_relative_path_tlibdir" = x ; then
+          # Have to descend all the way to the root!
+          func_relative_path_result=../$func_relative_path_result
+          func_relative_path_tcancelled=$func_relative_path_tbindir
+          break
+        fi
+        func_relative_path_result=../$func_relative_path_result
+        ;;
+    esac
+  done
+
+  # Now calculate path; take care to avoid doubling-up slashes.
+  func_stripname '' '/' "$func_relative_path_result"
+  func_relative_path_result=$func_stripname_result
+  func_stripname '/' '/' "$func_relative_path_tcancelled"
+  if test "x$func_stripname_result" != x ; then
+    func_relative_path_result=${func_relative_path_result}/${func_stripname_result}
+  fi
+
+  # Normalisation. If bindir is libdir, return empty string,
+  # else relative path ending with a slash; either way, target
+  # file name can be directly appended.
+  if test ! -z "$func_relative_path_result"; then
+    func_stripname './' '' "$func_relative_path_result/"
+    func_relative_path_result=$func_stripname_result
+  fi
+}
+
+# The name of this program:
+func_dirname_and_basename "$progpath"
+progname=$func_basename_result
+
+# Make sure we have an absolute path for reexecution:
+case $progpath in
+  [\\/]*|[A-Za-z]:\\*) ;;
+  *[\\/]*)
+     progdir=$func_dirname_result
+     progdir=`cd "$progdir" && pwd`
+     progpath="$progdir/$progname"
+     ;;
+  *)
+     save_IFS="$IFS"
+     IFS=${PATH_SEPARATOR-:}
+     for progdir in $PATH; do
+       IFS="$save_IFS"
+       test -x "$progdir/$progname" && break
+     done
+     IFS="$save_IFS"
+     test -n "$progdir" || progdir=`pwd`
+     progpath="$progdir/$progname"
+     ;;
+esac
+
+# Sed substitution that helps us do robust quoting.  It backslashifies
+# metacharacters that are still active within double-quoted strings.
+Xsed="${SED}"' -e 1s/^X//'
+sed_quote_subst='s/\([`"$\\]\)/\\\1/g'
+
+# Same as above, but do not quote variable references.
+double_quote_subst='s/\(["`\\]\)/\\\1/g'
+
+# Sed substitution that turns a string into a regex matching for the
+# string literally.
+sed_make_literal_regex='s,[].[^$\\*\/],\\&,g'
+
+# Sed substitution that converts a w32 file name or path
+# which contains forward slashes, into one that contains
+# (escaped) backslashes.  A very naive implementation.
+lt_sed_naive_backslashify='s|\\\\*|\\|g;s|/|\\|g;s|\\|\\\\|g'
+
+# Re-`\' parameter expansions in output of double_quote_subst that were
+# `\'-ed in input to the same.  If an odd number of `\' preceded a '$'
+# in input to double_quote_subst, that '$' was protected from expansion.
+# Since each input `\' is now two `\'s, look for any number of runs of
+# four `\'s followed by two `\'s and then a '$'.  `\' that '$'.
+bs='\\'
+bs2='\\\\'
+bs4='\\\\\\\\'
+dollar='\$'
+sed_double_backslash="\
+  s/$bs4/&\\
+/g
+  s/^$bs2$dollar/$bs&/
+  s/\\([^$bs]\\)$bs2$dollar/\\1$bs2$bs$dollar/g
+  s/\n//g"
+
+# Standard options:
+opt_dry_run=false
+opt_help=false
+opt_quiet=false
+opt_verbose=false
+opt_warning=:
+
+# func_echo arg...
+# Echo program name prefixed message, along with the current mode
+# name if it has been set yet.
+func_echo ()
+{
+    $ECHO "$progname: ${opt_mode+$opt_mode: }$*"
+}
+
+# func_verbose arg...
+# Echo program name prefixed message in verbose mode only.
+func_verbose ()
+{
+    $opt_verbose && func_echo ${1+"$@"}
+
+    # A bug in bash halts the script if the last line of a function
+    # fails when set -e is in force, so we need another command to
+    # work around that:
+    :
+}
+
+# func_echo_all arg...
+# Invoke $ECHO with all args, space-separated.
+func_echo_all ()
+{
+    $ECHO "$*"
+}
+
+# func_error arg...
+# Echo program name prefixed message to standard error.
+func_error ()
+{
+    $ECHO "$progname: ${opt_mode+$opt_mode: }"${1+"$@"} 1>&2
+}
+
+# func_warning arg...
+# Echo program name prefixed warning message to standard error.
+func_warning ()
+{
+    $opt_warning && $ECHO "$progname: ${opt_mode+$opt_mode: }warning: "${1+"$@"} 1>&2
+
+    # bash bug again:
+    :
+}
+
+# func_fatal_error arg...
+# Echo program name prefixed message to standard error, and exit.
+func_fatal_error ()
+{
+    func_error ${1+"$@"}
+    exit $EXIT_FAILURE
+}
+
+# func_fatal_help arg...
+# Echo program name prefixed message to standard error, followed by
+# a help hint, and exit.
+func_fatal_help ()
+{
+    func_error ${1+"$@"}
+    func_fatal_error "$help"
+}
+help="Try \`$progname --help' for more information."  ## default
+
+
+# func_grep expression filename
+# Check whether EXPRESSION matches any line of FILENAME, without output.
+func_grep ()
+{
+    $GREP "$1" "$2" >/dev/null 2>&1
+}
+
+
+# func_mkdir_p directory-path
+# Make sure the entire path to DIRECTORY-PATH is available.
+func_mkdir_p ()
+{
+    my_directory_path="$1"
+    my_dir_list=
+
+    if test -n "$my_directory_path" && test "$opt_dry_run" != ":"; then
+
+      # Protect directory names starting with `-'
+      case $my_directory_path in
+        -*) my_directory_path="./$my_directory_path" ;;
+      esac
+
+      # While some portion of DIR does not yet exist...
+      while test ! -d "$my_directory_path"; do
+        # ...make a list in topmost first order.  Use a colon delimited
+	# list incase some portion of path contains whitespace.
+        my_dir_list="$my_directory_path:$my_dir_list"
+
+        # If the last portion added has no slash in it, the list is done
+        case $my_directory_path in */*) ;; *) break ;; esac
+
+        # ...otherwise throw away the child directory and loop
+        my_directory_path=`$ECHO "$my_directory_path" | $SED -e "$dirname"`
+      done
+      my_dir_list=`$ECHO "$my_dir_list" | $SED 's,:*$,,'`
+
+      save_mkdir_p_IFS="$IFS"; IFS=':'
+      for my_dir in $my_dir_list; do
+	IFS="$save_mkdir_p_IFS"
+        # mkdir can fail with a `File exist' error if two processes
+        # try to create one of the directories concurrently.  Don't
+        # stop in that case!
+        $MKDIR "$my_dir" 2>/dev/null || :
+      done
+      IFS="$save_mkdir_p_IFS"
+
+      # Bail out if we (or some other process) failed to create a directory.
+      test -d "$my_directory_path" || \
+        func_fatal_error "Failed to create \`$1'"
+    fi
+}
+
+
+# func_mktempdir [string]
+# Make a temporary directory that won't clash with other running
+# libtool processes, and avoids race conditions if possible.  If
+# given, STRING is the basename for that directory.
+func_mktempdir ()
+{
+    my_template="${TMPDIR-/tmp}/${1-$progname}"
+
+    if test "$opt_dry_run" = ":"; then
+      # Return a directory name, but don't create it in dry-run mode
+      my_tmpdir="${my_template}-$$"
+    else
+
+      # If mktemp works, use that first and foremost
+      my_tmpdir=`mktemp -d "${my_template}-XXXXXXXX" 2>/dev/null`
+
+      if test ! -d "$my_tmpdir"; then
+        # Failing that, at least try and use $RANDOM to avoid a race
+        my_tmpdir="${my_template}-${RANDOM-0}$$"
+
+        save_mktempdir_umask=`umask`
+        umask 0077
+        $MKDIR "$my_tmpdir"
+        umask $save_mktempdir_umask
+      fi
+
+      # If we're not in dry-run mode, bomb out on failure
+      test -d "$my_tmpdir" || \
+        func_fatal_error "cannot create temporary directory \`$my_tmpdir'"
+    fi
+
+    $ECHO "$my_tmpdir"
+}
+
+
+# func_quote_for_eval arg
+# Aesthetically quote ARG to be evaled later.
+# This function returns two values: FUNC_QUOTE_FOR_EVAL_RESULT
+# is double-quoted, suitable for a subsequent eval, whereas
+# FUNC_QUOTE_FOR_EVAL_UNQUOTED_RESULT has merely all characters
+# which are still active within double quotes backslashified.
+func_quote_for_eval ()
+{
+    case $1 in
+      *[\\\`\"\$]*)
+	func_quote_for_eval_unquoted_result=`$ECHO "$1" | $SED "$sed_quote_subst"` ;;
+      *)
+        func_quote_for_eval_unquoted_result="$1" ;;
+    esac
+
+    case $func_quote_for_eval_unquoted_result in
+      # Double-quote args containing shell metacharacters to delay
+      # word splitting, command substitution and and variable
+      # expansion for a subsequent eval.
+      # Many Bourne shells cannot handle close brackets correctly
+      # in scan sets, so we specify it separately.
+      *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \	]*|*]*|"")
+        func_quote_for_eval_result="\"$func_quote_for_eval_unquoted_result\""
+        ;;
+      *)
+        func_quote_for_eval_result="$func_quote_for_eval_unquoted_result"
+    esac
+}
+
+
+# func_quote_for_expand arg
+# Aesthetically quote ARG to be evaled later; same as above,
+# but do not quote variable references.
+func_quote_for_expand ()
+{
+    case $1 in
+      *[\\\`\"]*)
+	my_arg=`$ECHO "$1" | $SED \
+	    -e "$double_quote_subst" -e "$sed_double_backslash"` ;;
+      *)
+        my_arg="$1" ;;
+    esac
+
+    case $my_arg in
+      # Double-quote args containing shell metacharacters to delay
+      # word splitting and command substitution for a subsequent eval.
+      # Many Bourne shells cannot handle close brackets correctly
+      # in scan sets, so we specify it separately.
+      *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \	]*|*]*|"")
+        my_arg="\"$my_arg\""
+        ;;
+    esac
+
+    func_quote_for_expand_result="$my_arg"
+}
+
+
+# func_show_eval cmd [fail_exp]
+# Unless opt_silent is true, then output CMD.  Then, if opt_dryrun is
+# not true, evaluate CMD.  If the evaluation of CMD fails, and FAIL_EXP
+# is given, then evaluate it.
+func_show_eval ()
+{
+    my_cmd="$1"
+    my_fail_exp="${2-:}"
+
+    ${opt_silent-false} || {
+      func_quote_for_expand "$my_cmd"
+      eval "func_echo $func_quote_for_expand_result"
+    }
+
+    if ${opt_dry_run-false}; then :; else
+      eval "$my_cmd"
+      my_status=$?
+      if test "$my_status" -eq 0; then :; else
+	eval "(exit $my_status); $my_fail_exp"
+      fi
+    fi
+}
+
+
+# func_show_eval_locale cmd [fail_exp]
+# Unless opt_silent is true, then output CMD.  Then, if opt_dryrun is
+# not true, evaluate CMD.  If the evaluation of CMD fails, and FAIL_EXP
+# is given, then evaluate it.  Use the saved locale for evaluation.
+func_show_eval_locale ()
+{
+    my_cmd="$1"
+    my_fail_exp="${2-:}"
+
+    ${opt_silent-false} || {
+      func_quote_for_expand "$my_cmd"
+      eval "func_echo $func_quote_for_expand_result"
+    }
+
+    if ${opt_dry_run-false}; then :; else
+      eval "$lt_user_locale
+	    $my_cmd"
+      my_status=$?
+      eval "$lt_safe_locale"
+      if test "$my_status" -eq 0; then :; else
+	eval "(exit $my_status); $my_fail_exp"
+      fi
+    fi
+}
+
+# func_tr_sh
+# Turn $1 into a string suitable for a shell variable name.
+# Result is stored in $func_tr_sh_result.  All characters
+# not in the set a-zA-Z0-9_ are replaced with '_'. Further,
+# if $1 begins with a digit, a '_' is prepended as well.
+func_tr_sh ()
+{
+  case $1 in
+  [0-9]* | *[!a-zA-Z0-9_]*)
+    func_tr_sh_result=`$ECHO "$1" | $SED 's/^\([0-9]\)/_\1/; s/[^a-zA-Z0-9_]/_/g'`
+    ;;
+  * )
+    func_tr_sh_result=$1
+    ;;
+  esac
+}
+
+
+# func_version
+# Echo version message to standard output and exit.
+func_version ()
+{
+    $opt_debug
+
+    $SED -n '/(C)/!b go
+	:more
+	/\./!{
+	  N
+	  s/\n# / /
+	  b more
+	}
+	:go
+	/^# '$PROGRAM' (GNU /,/# warranty; / {
+        s/^# //
+	s/^# *$//
+        s/\((C)\)[ 0-9,-]*\( [1-9][0-9]*\)/\1\2/
+        p
+     }' < "$progpath"
+     exit $?
+}
+
+# func_usage
+# Echo short help message to standard output and exit.
+func_usage ()
+{
+    $opt_debug
+
+    $SED -n '/^# Usage:/,/^#  *.*--help/ {
+        s/^# //
+	s/^# *$//
+	s/\$progname/'$progname'/
+	p
+    }' < "$progpath"
+    echo
+    $ECHO "run \`$progname --help | more' for full usage"
+    exit $?
+}
+
+# func_help [NOEXIT]
+# Echo long help message to standard output and exit,
+# unless 'noexit' is passed as argument.
+func_help ()
+{
+    $opt_debug
+
+    $SED -n '/^# Usage:/,/# Report bugs to/ {
+	:print
+        s/^# //
+	s/^# *$//
+	s*\$progname*'$progname'*
+	s*\$host*'"$host"'*
+	s*\$SHELL*'"$SHELL"'*
+	s*\$LTCC*'"$LTCC"'*
+	s*\$LTCFLAGS*'"$LTCFLAGS"'*
+	s*\$LD*'"$LD"'*
+	s/\$with_gnu_ld/'"$with_gnu_ld"'/
+	s/\$automake_version/'"`(${AUTOMAKE-automake} --version) 2>/dev/null |$SED 1q`"'/
+	s/\$autoconf_version/'"`(${AUTOCONF-autoconf} --version) 2>/dev/null |$SED 1q`"'/
+	p
+	d
+     }
+     /^# .* home page:/b print
+     /^# General help using/b print
+     ' < "$progpath"
+    ret=$?
+    if test -z "$1"; then
+      exit $ret
+    fi
+}
+
+# func_missing_arg argname
+# Echo program name prefixed message to standard error and set global
+# exit_cmd.
+func_missing_arg ()
+{
+    $opt_debug
+
+    func_error "missing argument for $1."
+    exit_cmd=exit
+}
+
+
+# func_split_short_opt shortopt
+# Set func_split_short_opt_name and func_split_short_opt_arg shell
+# variables after splitting SHORTOPT after the 2nd character.
+func_split_short_opt ()
+{
+    my_sed_short_opt='1s/^\(..\).*$/\1/;q'
+    my_sed_short_rest='1s/^..\(.*\)$/\1/;q'
+
+    func_split_short_opt_name=`$ECHO "$1" | $SED "$my_sed_short_opt"`
+    func_split_short_opt_arg=`$ECHO "$1" | $SED "$my_sed_short_rest"`
+} # func_split_short_opt may be replaced by extended shell implementation
+
+
+# func_split_long_opt longopt
+# Set func_split_long_opt_name and func_split_long_opt_arg shell
+# variables after splitting LONGOPT at the `=' sign.
+func_split_long_opt ()
+{
+    my_sed_long_opt='1s/^\(--[^=]*\)=.*/\1/;q'
+    my_sed_long_arg='1s/^--[^=]*=//'
+
+    func_split_long_opt_name=`$ECHO "$1" | $SED "$my_sed_long_opt"`
+    func_split_long_opt_arg=`$ECHO "$1" | $SED "$my_sed_long_arg"`
+} # func_split_long_opt may be replaced by extended shell implementation
+
+exit_cmd=:
+
+
+
+
+
+magic="%%%MAGIC variable%%%"
+magic_exe="%%%MAGIC EXE variable%%%"
+
+# Global variables.
+nonopt=
+preserve_args=
+lo2o="s/\\.lo\$/.${objext}/"
+o2lo="s/\\.${objext}\$/.lo/"
+extracted_archives=
+extracted_serial=0
+
+# If this variable is set in any of the actions, the command in it
+# will be execed at the end.  This prevents here-documents from being
+# left over by shells.
+exec_cmd=
+
+# func_append var value
+# Append VALUE to the end of shell variable VAR.
+func_append ()
+{
+    eval "${1}=\$${1}\${2}"
+} # func_append may be replaced by extended shell implementation
+
+# func_append_quoted var value
+# Quote VALUE and append to the end of shell variable VAR, separated
+# by a space.
+func_append_quoted ()
+{
+    func_quote_for_eval "${2}"
+    eval "${1}=\$${1}\\ \$func_quote_for_eval_result"
+} # func_append_quoted may be replaced by extended shell implementation
+
+
+# func_arith arithmetic-term...
+func_arith ()
+{
+    func_arith_result=`expr "${@}"`
+} # func_arith may be replaced by extended shell implementation
+
+
+# func_len string
+# STRING may not start with a hyphen.
+func_len ()
+{
+    func_len_result=`expr "${1}" : ".*" 2>/dev/null || echo $max_cmd_len`
+} # func_len may be replaced by extended shell implementation
+
+
+# func_lo2o object
+func_lo2o ()
+{
+    func_lo2o_result=`$ECHO "${1}" | $SED "$lo2o"`
+} # func_lo2o may be replaced by extended shell implementation
+
+
+# func_xform libobj-or-source
+func_xform ()
+{
+    func_xform_result=`$ECHO "${1}" | $SED 's/\.[^.]*$/.lo/'`
+} # func_xform may be replaced by extended shell implementation
+
+
+# func_fatal_configuration arg...
+# Echo program name prefixed message to standard error, followed by
+# a configuration failure hint, and exit.
+func_fatal_configuration ()
+{
+    func_error ${1+"$@"}
+    func_error "See the $PACKAGE documentation for more information."
+    func_fatal_error "Fatal configuration error."
+}
+
+
+# func_config
+# Display the configuration for all the tags in this script.
+func_config ()
+{
+    re_begincf='^# ### BEGIN LIBTOOL'
+    re_endcf='^# ### END LIBTOOL'
+
+    # Default configuration.
+    $SED "1,/$re_begincf CONFIG/d;/$re_endcf CONFIG/,\$d" < "$progpath"
+
+    # Now print the configurations for the tags.
+    for tagname in $taglist; do
+      $SED -n "/$re_begincf TAG CONFIG: $tagname\$/,/$re_endcf TAG CONFIG: $tagname\$/p" < "$progpath"
+    done
+
+    exit $?
+}
+
+# func_features
+# Display the features supported by this script.
+func_features ()
+{
+    echo "host: $host"
+    if test "$build_libtool_libs" = yes; then
+      echo "enable shared libraries"
+    else
+      echo "disable shared libraries"
+    fi
+    if test "$build_old_libs" = yes; then
+      echo "enable static libraries"
+    else
+      echo "disable static libraries"
+    fi
+
+    exit $?
+}
+
+# func_enable_tag tagname
+# Verify that TAGNAME is valid, and either flag an error and exit, or
+# enable the TAGNAME tag.  We also add TAGNAME to the global $taglist
+# variable here.
+func_enable_tag ()
+{
+  # Global variable:
+  tagname="$1"
+
+  re_begincf="^# ### BEGIN LIBTOOL TAG CONFIG: $tagname\$"
+  re_endcf="^# ### END LIBTOOL TAG CONFIG: $tagname\$"
+  sed_extractcf="/$re_begincf/,/$re_endcf/p"
+
+  # Validate tagname.
+  case $tagname in
+    *[!-_A-Za-z0-9,/]*)
+      func_fatal_error "invalid tag name: $tagname"
+      ;;
+  esac
+
+  # Don't test for the "default" C tag, as we know it's
+  # there but not specially marked.
+  case $tagname in
+    CC) ;;
+    *)
+      if $GREP "$re_begincf" "$progpath" >/dev/null 2>&1; then
+	taglist="$taglist $tagname"
+
+	# Evaluate the configuration.  Be careful to quote the path
+	# and the sed script, to avoid splitting on whitespace, but
+	# also don't use non-portable quotes within backquotes within
+	# quotes we have to do it in 2 steps:
+	extractedcf=`$SED -n -e "$sed_extractcf" < "$progpath"`
+	eval "$extractedcf"
+      else
+	func_error "ignoring unknown tag $tagname"
+      fi
+      ;;
+  esac
+}
+
+# func_check_version_match
+# Ensure that we are using m4 macros, and libtool script from the same
+# release of libtool.
+func_check_version_match ()
+{
+  if test "$package_revision" != "$macro_revision"; then
+    if test "$VERSION" != "$macro_version"; then
+      if test -z "$macro_version"; then
+        cat >&2 <<_LT_EOF
+$progname: Version mismatch error.  This is $PACKAGE $VERSION, but the
+$progname: definition of this LT_INIT comes from an older release.
+$progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION
+$progname: and run autoconf again.
+_LT_EOF
+      else
+        cat >&2 <<_LT_EOF
+$progname: Version mismatch error.  This is $PACKAGE $VERSION, but the
+$progname: definition of this LT_INIT comes from $PACKAGE $macro_version.
+$progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION
+$progname: and run autoconf again.
+_LT_EOF
+      fi
+    else
+      cat >&2 <<_LT_EOF
+$progname: Version mismatch error.  This is $PACKAGE $VERSION, revision $package_revision,
+$progname: but the definition of this LT_INIT comes from revision $macro_revision.
+$progname: You should recreate aclocal.m4 with macros from revision $package_revision
+$progname: of $PACKAGE $VERSION and run autoconf again.
+_LT_EOF
+    fi
+
+    exit $EXIT_MISMATCH
+  fi
+}
+
+
+# Shorthand for --mode=foo, only valid as the first argument
+case $1 in
+clean|clea|cle|cl)
+  shift; set dummy --mode clean ${1+"$@"}; shift
+  ;;
+compile|compil|compi|comp|com|co|c)
+  shift; set dummy --mode compile ${1+"$@"}; shift
+  ;;
+execute|execut|execu|exec|exe|ex|e)
+  shift; set dummy --mode execute ${1+"$@"}; shift
+  ;;
+finish|finis|fini|fin|fi|f)
+  shift; set dummy --mode finish ${1+"$@"}; shift
+  ;;
+install|instal|insta|inst|ins|in|i)
+  shift; set dummy --mode install ${1+"$@"}; shift
+  ;;
+link|lin|li|l)
+  shift; set dummy --mode link ${1+"$@"}; shift
+  ;;
+uninstall|uninstal|uninsta|uninst|unins|unin|uni|un|u)
+  shift; set dummy --mode uninstall ${1+"$@"}; shift
+  ;;
+esac
+
+
+
+# Option defaults:
+opt_debug=:
+opt_dry_run=false
+opt_config=false
+opt_preserve_dup_deps=false
+opt_features=false
+opt_finish=false
+opt_help=false
+opt_help_all=false
+opt_silent=:
+opt_warning=:
+opt_verbose=:
+opt_silent=false
+opt_verbose=false
+
+
+# Parse options once, thoroughly.  This comes as soon as possible in the
+# script to make things like `--version' happen as quickly as we can.
+{
+  # this just eases exit handling
+  while test $# -gt 0; do
+    opt="$1"
+    shift
+    case $opt in
+      --debug|-x)	opt_debug='set -x'
+			func_echo "enabling shell trace mode"
+			$opt_debug
+			;;
+      --dry-run|--dryrun|-n)
+			opt_dry_run=:
+			;;
+      --config)
+			opt_config=:
+func_config
+			;;
+      --dlopen|-dlopen)
+			optarg="$1"
+			opt_dlopen="${opt_dlopen+$opt_dlopen
+}$optarg"
+			shift
+			;;
+      --preserve-dup-deps)
+			opt_preserve_dup_deps=:
+			;;
+      --features)
+			opt_features=:
+func_features
+			;;
+      --finish)
+			opt_finish=:
+set dummy --mode finish ${1+"$@"}; shift
+			;;
+      --help)
+			opt_help=:
+			;;
+      --help-all)
+			opt_help_all=:
+opt_help=': help-all'
+			;;
+      --mode)
+			test $# = 0 && func_missing_arg $opt && break
+			optarg="$1"
+			opt_mode="$optarg"
+case $optarg in
+  # Valid mode arguments:
+  clean|compile|execute|finish|install|link|relink|uninstall) ;;
+
+  # Catch anything else as an error
+  *) func_error "invalid argument for $opt"
+     exit_cmd=exit
+     break
+     ;;
+esac
+			shift
+			;;
+      --no-silent|--no-quiet)
+			opt_silent=false
+func_append preserve_args " $opt"
+			;;
+      --no-warning|--no-warn)
+			opt_warning=false
+func_append preserve_args " $opt"
+			;;
+      --no-verbose)
+			opt_verbose=false
+func_append preserve_args " $opt"
+			;;
+      --silent|--quiet)
+			opt_silent=:
+func_append preserve_args " $opt"
+        opt_verbose=false
+			;;
+      --verbose|-v)
+			opt_verbose=:
+func_append preserve_args " $opt"
+opt_silent=false
+			;;
+      --tag)
+			test $# = 0 && func_missing_arg $opt && break
+			optarg="$1"
+			opt_tag="$optarg"
+func_append preserve_args " $opt $optarg"
+func_enable_tag "$optarg"
+			shift
+			;;
+
+      -\?|-h)		func_usage				;;
+      --help)		func_help				;;
+      --version)	func_version				;;
+
+      # Separate optargs to long options:
+      --*=*)
+			func_split_long_opt "$opt"
+			set dummy "$func_split_long_opt_name" "$func_split_long_opt_arg" ${1+"$@"}
+			shift
+			;;
+
+      # Separate non-argument short options:
+      -\?*|-h*|-n*|-v*)
+			func_split_short_opt "$opt"
+			set dummy "$func_split_short_opt_name" "-$func_split_short_opt_arg" ${1+"$@"}
+			shift
+			;;
+
+      --)		break					;;
+      -*)		func_fatal_help "unrecognized option \`$opt'" ;;
+      *)		set dummy "$opt" ${1+"$@"};	shift; break  ;;
+    esac
+  done
+
+  # Validate options:
+
+  # save first non-option argument
+  if test "$#" -gt 0; then
+    nonopt="$opt"
+    shift
+  fi
+
+  # preserve --debug
+  test "$opt_debug" = : || func_append preserve_args " --debug"
+
+  case $host in
+    *cygwin* | *mingw* | *pw32* | *cegcc*)
+      # don't eliminate duplications in $postdeps and $predeps
+      opt_duplicate_compiler_generated_deps=:
+      ;;
+    *)
+      opt_duplicate_compiler_generated_deps=$opt_preserve_dup_deps
+      ;;
+  esac
+
+  $opt_help || {
+    # Sanity checks first:
+    func_check_version_match
+
+    if test "$build_libtool_libs" != yes && test "$build_old_libs" != yes; then
+      func_fatal_configuration "not configured to build any kind of library"
+    fi
+
+    # Darwin sucks
+    eval std_shrext=\"$shrext_cmds\"
+
+    # Only execute mode is allowed to have -dlopen flags.
+    if test -n "$opt_dlopen" && test "$opt_mode" != execute; then
+      func_error "unrecognized option \`-dlopen'"
+      $ECHO "$help" 1>&2
+      exit $EXIT_FAILURE
+    fi
+
+    # Change the help message to a mode-specific one.
+    generic_help="$help"
+    help="Try \`$progname --help --mode=$opt_mode' for more information."
+  }
+
+
+  # Bail if the options were screwed
+  $exit_cmd $EXIT_FAILURE
+}
+
+
+
+
+## ----------- ##
+##    Main.    ##
+## ----------- ##
+
+# func_lalib_p file
+# True iff FILE is a libtool `.la' library or `.lo' object file.
+# This function is only a basic sanity check; it will hardly flush out
+# determined imposters.
+func_lalib_p ()
+{
+    test -f "$1" &&
+      $SED -e 4q "$1" 2>/dev/null \
+        | $GREP "^# Generated by .*$PACKAGE" > /dev/null 2>&1
+}
+
+# func_lalib_unsafe_p file
+# True iff FILE is a libtool `.la' library or `.lo' object file.
+# This function implements the same check as func_lalib_p without
+# resorting to external programs.  To this end, it redirects stdin and
+# closes it afterwards, without saving the original file descriptor.
+# As a safety measure, use it only where a negative result would be
+# fatal anyway.  Works if `file' does not exist.
+func_lalib_unsafe_p ()
+{
+    lalib_p=no
+    if test -f "$1" && test -r "$1" && exec 5<&0 <"$1"; then
+	for lalib_p_l in 1 2 3 4
+	do
+	    read lalib_p_line
+	    case "$lalib_p_line" in
+		\#\ Generated\ by\ *$PACKAGE* ) lalib_p=yes; break;;
+	    esac
+	done
+	exec 0<&5 5<&-
+    fi
+    test "$lalib_p" = yes
+}
+
+# func_ltwrapper_script_p file
+# True iff FILE is a libtool wrapper script
+# This function is only a basic sanity check; it will hardly flush out
+# determined imposters.
+func_ltwrapper_script_p ()
+{
+    func_lalib_p "$1"
+}
+
+# func_ltwrapper_executable_p file
+# True iff FILE is a libtool wrapper executable
+# This function is only a basic sanity check; it will hardly flush out
+# determined imposters.
+func_ltwrapper_executable_p ()
+{
+    func_ltwrapper_exec_suffix=
+    case $1 in
+    *.exe) ;;
+    *) func_ltwrapper_exec_suffix=.exe ;;
+    esac
+    $GREP "$magic_exe" "$1$func_ltwrapper_exec_suffix" >/dev/null 2>&1
+}
+
+# func_ltwrapper_scriptname file
+# Assumes file is an ltwrapper_executable
+# uses $file to determine the appropriate filename for a
+# temporary ltwrapper_script.
+func_ltwrapper_scriptname ()
+{
+    func_dirname_and_basename "$1" "" "."
+    func_stripname '' '.exe' "$func_basename_result"
+    func_ltwrapper_scriptname_result="$func_dirname_result/$objdir/${func_stripname_result}_ltshwrapper"
+}
+
+# func_ltwrapper_p file
+# True iff FILE is a libtool wrapper script or wrapper executable
+# This function is only a basic sanity check; it will hardly flush out
+# determined imposters.
+func_ltwrapper_p ()
+{
+    func_ltwrapper_script_p "$1" || func_ltwrapper_executable_p "$1"
+}
+
+
+# func_execute_cmds commands fail_cmd
+# Execute tilde-delimited COMMANDS.
+# If FAIL_CMD is given, eval that upon failure.
+# FAIL_CMD may read-access the current command in variable CMD!
+func_execute_cmds ()
+{
+    $opt_debug
+    save_ifs=$IFS; IFS='~'
+    for cmd in $1; do
+      IFS=$save_ifs
+      eval cmd=\"$cmd\"
+      func_show_eval "$cmd" "${2-:}"
+    done
+    IFS=$save_ifs
+}
+
+
+# func_source file
+# Source FILE, adding directory component if necessary.
+# Note that it is not necessary on cygwin/mingw to append a dot to
+# FILE even if both FILE and FILE.exe exist: automatic-append-.exe
+# behavior happens only for exec(3), not for open(2)!  Also, sourcing
+# `FILE.' does not work on cygwin managed mounts.
+func_source ()
+{
+    $opt_debug
+    case $1 in
+    */* | *\\*)	. "$1" ;;
+    *)		. "./$1" ;;
+    esac
+}
+
+
+# func_resolve_sysroot PATH
+# Replace a leading = in PATH with a sysroot.  Store the result into
+# func_resolve_sysroot_result
+func_resolve_sysroot ()
+{
+  func_resolve_sysroot_result=$1
+  case $func_resolve_sysroot_result in
+  =*)
+    func_stripname '=' '' "$func_resolve_sysroot_result"
+    func_resolve_sysroot_result=$lt_sysroot$func_stripname_result
+    ;;
+  esac
+}
+
+# func_replace_sysroot PATH
+# If PATH begins with the sysroot, replace it with = and
+# store the result into func_replace_sysroot_result.
+func_replace_sysroot ()
+{
+  case "$lt_sysroot:$1" in
+  ?*:"$lt_sysroot"*)
+    func_stripname "$lt_sysroot" '' "$1"
+    func_replace_sysroot_result="=$func_stripname_result"
+    ;;
+  *)
+    # Including no sysroot.
+    func_replace_sysroot_result=$1
+    ;;
+  esac
+}
+
+# func_infer_tag arg
+# Infer tagged configuration to use if any are available and
+# if one wasn't chosen via the "--tag" command line option.
+# Only attempt this if the compiler in the base compile
+# command doesn't match the default compiler.
+# arg is usually of the form 'gcc ...'
+func_infer_tag ()
+{
+    $opt_debug
+    if test -n "$available_tags" && test -z "$tagname"; then
+      CC_quoted=
+      for arg in $CC; do
+	func_append_quoted CC_quoted "$arg"
+      done
+      CC_expanded=`func_echo_all $CC`
+      CC_quoted_expanded=`func_echo_all $CC_quoted`
+      case $@ in
+      # Blanks in the command may have been stripped by the calling shell,
+      # but not from the CC environment variable when configure was run.
+      " $CC "* | "$CC "* | " $CC_expanded "* | "$CC_expanded "* | \
+      " $CC_quoted"* | "$CC_quoted "* | " $CC_quoted_expanded "* | "$CC_quoted_expanded "*) ;;
+      # Blanks at the start of $base_compile will cause this to fail
+      # if we don't check for them as well.
+      *)
+	for z in $available_tags; do
+	  if $GREP "^# ### BEGIN LIBTOOL TAG CONFIG: $z$" < "$progpath" > /dev/null; then
+	    # Evaluate the configuration.
+	    eval "`${SED} -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$z'$/,/^# ### END LIBTOOL TAG CONFIG: '$z'$/p' < $progpath`"
+	    CC_quoted=
+	    for arg in $CC; do
+	      # Double-quote args containing other shell metacharacters.
+	      func_append_quoted CC_quoted "$arg"
+	    done
+	    CC_expanded=`func_echo_all $CC`
+	    CC_quoted_expanded=`func_echo_all $CC_quoted`
+	    case "$@ " in
+	    " $CC "* | "$CC "* | " $CC_expanded "* | "$CC_expanded "* | \
+	    " $CC_quoted"* | "$CC_quoted "* | " $CC_quoted_expanded "* | "$CC_quoted_expanded "*)
+	      # The compiler in the base compile command matches
+	      # the one in the tagged configuration.
+	      # Assume this is the tagged configuration we want.
+	      tagname=$z
+	      break
+	      ;;
+	    esac
+	  fi
+	done
+	# If $tagname still isn't set, then no tagged configuration
+	# was found and let the user know that the "--tag" command
+	# line option must be used.
+	if test -z "$tagname"; then
+	  func_echo "unable to infer tagged configuration"
+	  func_fatal_error "specify a tag with \`--tag'"
+#	else
+#	  func_verbose "using $tagname tagged configuration"
+	fi
+	;;
+      esac
+    fi
+}
+
+
+
+# func_write_libtool_object output_name pic_name nonpic_name
+# Create a libtool object file (analogous to a ".la" file),
+# but don't create it if we're doing a dry run.
+func_write_libtool_object ()
+{
+    write_libobj=${1}
+    if test "$build_libtool_libs" = yes; then
+      write_lobj=\'${2}\'
+    else
+      write_lobj=none
+    fi
+
+    if test "$build_old_libs" = yes; then
+      write_oldobj=\'${3}\'
+    else
+      write_oldobj=none
+    fi
+
+    $opt_dry_run || {
+      cat >${write_libobj}T <<EOF
+# $write_libobj - a libtool object file
+# Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION
+#
+# Please DO NOT delete this file!
+# It is necessary for linking the library.
+
+# Name of the PIC object.
+pic_object=$write_lobj
+
+# Name of the non-PIC object
+non_pic_object=$write_oldobj
+
+EOF
+      $MV "${write_libobj}T" "${write_libobj}"
+    }
+}
+
+
+##################################################
+# FILE NAME AND PATH CONVERSION HELPER FUNCTIONS #
+##################################################
+
+# func_convert_core_file_wine_to_w32 ARG
+# Helper function used by file name conversion functions when $build is *nix,
+# and $host is mingw, cygwin, or some other w32 environment. Relies on a
+# correctly configured wine environment available, with the winepath program
+# in $build's $PATH.
+#
+# ARG is the $build file name to be converted to w32 format.
+# Result is available in $func_convert_core_file_wine_to_w32_result, and will
+# be empty on error (or when ARG is empty)
+func_convert_core_file_wine_to_w32 ()
+{
+  $opt_debug
+  func_convert_core_file_wine_to_w32_result="$1"
+  if test -n "$1"; then
+    # Unfortunately, winepath does not exit with a non-zero error code, so we
+    # are forced to check the contents of stdout. On the other hand, if the
+    # command is not found, the shell will set an exit code of 127 and print
+    # *an error message* to stdout. So we must check for both error code of
+    # zero AND non-empty stdout, which explains the odd construction:
+    func_convert_core_file_wine_to_w32_tmp=`winepath -w "$1" 2>/dev/null`
+    if test "$?" -eq 0 && test -n "${func_convert_core_file_wine_to_w32_tmp}"; then
+      func_convert_core_file_wine_to_w32_result=`$ECHO "$func_convert_core_file_wine_to_w32_tmp" |
+        $SED -e "$lt_sed_naive_backslashify"`
+    else
+      func_convert_core_file_wine_to_w32_result=
+    fi
+  fi
+}
+# end: func_convert_core_file_wine_to_w32
+
+
+# func_convert_core_path_wine_to_w32 ARG
+# Helper function used by path conversion functions when $build is *nix, and
+# $host is mingw, cygwin, or some other w32 environment. Relies on a correctly
+# configured wine environment available, with the winepath program in $build's
+# $PATH. Assumes ARG has no leading or trailing path separator characters.
+#
+# ARG is path to be converted from $build format to win32.
+# Result is available in $func_convert_core_path_wine_to_w32_result.
+# Unconvertible file (directory) names in ARG are skipped; if no directory names
+# are convertible, then the result may be empty.
+func_convert_core_path_wine_to_w32 ()
+{
+  $opt_debug
+  # unfortunately, winepath doesn't convert paths, only file names
+  func_convert_core_path_wine_to_w32_result=""
+  if test -n "$1"; then
+    oldIFS=$IFS
+    IFS=:
+    for func_convert_core_path_wine_to_w32_f in $1; do
+      IFS=$oldIFS
+      func_convert_core_file_wine_to_w32 "$func_convert_core_path_wine_to_w32_f"
+      if test -n "$func_convert_core_file_wine_to_w32_result" ; then
+        if test -z "$func_convert_core_path_wine_to_w32_result"; then
+          func_convert_core_path_wine_to_w32_result="$func_convert_core_file_wine_to_w32_result"
+        else
+          func_append func_convert_core_path_wine_to_w32_result ";$func_convert_core_file_wine_to_w32_result"
+        fi
+      fi
+    done
+    IFS=$oldIFS
+  fi
+}
+# end: func_convert_core_path_wine_to_w32
+
+
+# func_cygpath ARGS...
+# Wrapper around calling the cygpath program via LT_CYGPATH. This is used when
+# when (1) $build is *nix and Cygwin is hosted via a wine environment; or (2)
+# $build is MSYS and $host is Cygwin, or (3) $build is Cygwin. In case (1) or
+# (2), returns the Cygwin file name or path in func_cygpath_result (input
+# file name or path is assumed to be in w32 format, as previously converted
+# from $build's *nix or MSYS format). In case (3), returns the w32 file name
+# or path in func_cygpath_result (input file name or path is assumed to be in
+# Cygwin format). Returns an empty string on error.
+#
+# ARGS are passed to cygpath, with the last one being the file name or path to
+# be converted.
+#
+# Specify the absolute *nix (or w32) name to cygpath in the LT_CYGPATH
+# environment variable; do not put it in $PATH.
+func_cygpath ()
+{
+  $opt_debug
+  if test -n "$LT_CYGPATH" && test -f "$LT_CYGPATH"; then
+    func_cygpath_result=`$LT_CYGPATH "$@" 2>/dev/null`
+    if test "$?" -ne 0; then
+      # on failure, ensure result is empty
+      func_cygpath_result=
+    fi
+  else
+    func_cygpath_result=
+    func_error "LT_CYGPATH is empty or specifies non-existent file: \`$LT_CYGPATH'"
+  fi
+}
+#end: func_cygpath
+
+
+# func_convert_core_msys_to_w32 ARG
+# Convert file name or path ARG from MSYS format to w32 format.  Return
+# result in func_convert_core_msys_to_w32_result.
+func_convert_core_msys_to_w32 ()
+{
+  $opt_debug
+  # awkward: cmd appends spaces to result
+  func_convert_core_msys_to_w32_result=`( cmd //c echo "$1" ) 2>/dev/null |
+    $SED -e 's/[ ]*$//' -e "$lt_sed_naive_backslashify"`
+}
+#end: func_convert_core_msys_to_w32
+
+
+# func_convert_file_check ARG1 ARG2
+# Verify that ARG1 (a file name in $build format) was converted to $host
+# format in ARG2. Otherwise, emit an error message, but continue (resetting
+# func_to_host_file_result to ARG1).
+func_convert_file_check ()
+{
+  $opt_debug
+  if test -z "$2" && test -n "$1" ; then
+    func_error "Could not determine host file name corresponding to"
+    func_error "  \`$1'"
+    func_error "Continuing, but uninstalled executables may not work."
+    # Fallback:
+    func_to_host_file_result="$1"
+  fi
+}
+# end func_convert_file_check
+
+
+# func_convert_path_check FROM_PATHSEP TO_PATHSEP FROM_PATH TO_PATH
+# Verify that FROM_PATH (a path in $build format) was converted to $host
+# format in TO_PATH. Otherwise, emit an error message, but continue, resetting
+# func_to_host_file_result to a simplistic fallback value (see below).
+func_convert_path_check ()
+{
+  $opt_debug
+  if test -z "$4" && test -n "$3"; then
+    func_error "Could not determine the host path corresponding to"
+    func_error "  \`$3'"
+    func_error "Continuing, but uninstalled executables may not work."
+    # Fallback.  This is a deliberately simplistic "conversion" and
+    # should not be "improved".  See libtool.info.
+    if test "x$1" != "x$2"; then
+      lt_replace_pathsep_chars="s|$1|$2|g"
+      func_to_host_path_result=`echo "$3" |
+        $SED -e "$lt_replace_pathsep_chars"`
+    else
+      func_to_host_path_result="$3"
+    fi
+  fi
+}
+# end func_convert_path_check
+
+
+# func_convert_path_front_back_pathsep FRONTPAT BACKPAT REPL ORIG
+# Modifies func_to_host_path_result by prepending REPL if ORIG matches FRONTPAT
+# and appending REPL if ORIG matches BACKPAT.
+func_convert_path_front_back_pathsep ()
+{
+  $opt_debug
+  case $4 in
+  $1 ) func_to_host_path_result="$3$func_to_host_path_result"
+    ;;
+  esac
+  case $4 in
+  $2 ) func_append func_to_host_path_result "$3"
+    ;;
+  esac
+}
+# end func_convert_path_front_back_pathsep
+
+
+##################################################
+# $build to $host FILE NAME CONVERSION FUNCTIONS #
+##################################################
+# invoked via `$to_host_file_cmd ARG'
+#
+# In each case, ARG is the path to be converted from $build to $host format.
+# Result will be available in $func_to_host_file_result.
+
+
+# func_to_host_file ARG
+# Converts the file name ARG from $build format to $host format. Return result
+# in func_to_host_file_result.
+func_to_host_file ()
+{
+  $opt_debug
+  $to_host_file_cmd "$1"
+}
+# end func_to_host_file
+
+
+# func_to_tool_file ARG LAZY
+# converts the file name ARG from $build format to toolchain format. Return
+# result in func_to_tool_file_result.  If the conversion in use is listed
+# in (the comma separated) LAZY, no conversion takes place.
+func_to_tool_file ()
+{
+  $opt_debug
+  case ,$2, in
+    *,"$to_tool_file_cmd",*)
+      func_to_tool_file_result=$1
+      ;;
+    *)
+      $to_tool_file_cmd "$1"
+      func_to_tool_file_result=$func_to_host_file_result
+      ;;
+  esac
+}
+# end func_to_tool_file
+
+
+# func_convert_file_noop ARG
+# Copy ARG to func_to_host_file_result.
+func_convert_file_noop ()
+{
+  func_to_host_file_result="$1"
+}
+# end func_convert_file_noop
+
+
+# func_convert_file_msys_to_w32 ARG
+# Convert file name ARG from (mingw) MSYS to (mingw) w32 format; automatic
+# conversion to w32 is not available inside the cwrapper.  Returns result in
+# func_to_host_file_result.
+func_convert_file_msys_to_w32 ()
+{
+  $opt_debug
+  func_to_host_file_result="$1"
+  if test -n "$1"; then
+    func_convert_core_msys_to_w32 "$1"
+    func_to_host_file_result="$func_convert_core_msys_to_w32_result"
+  fi
+  func_convert_file_check "$1" "$func_to_host_file_result"
+}
+# end func_convert_file_msys_to_w32
+
+
+# func_convert_file_cygwin_to_w32 ARG
+# Convert file name ARG from Cygwin to w32 format.  Returns result in
+# func_to_host_file_result.
+func_convert_file_cygwin_to_w32 ()
+{
+  $opt_debug
+  func_to_host_file_result="$1"
+  if test -n "$1"; then
+    # because $build is cygwin, we call "the" cygpath in $PATH; no need to use
+    # LT_CYGPATH in this case.
+    func_to_host_file_result=`cygpath -m "$1"`
+  fi
+  func_convert_file_check "$1" "$func_to_host_file_result"
+}
+# end func_convert_file_cygwin_to_w32
+
+
+# func_convert_file_nix_to_w32 ARG
+# Convert file name ARG from *nix to w32 format.  Requires a wine environment
+# and a working winepath. Returns result in func_to_host_file_result.
+func_convert_file_nix_to_w32 ()
+{
+  $opt_debug
+  func_to_host_file_result="$1"
+  if test -n "$1"; then
+    func_convert_core_file_wine_to_w32 "$1"
+    func_to_host_file_result="$func_convert_core_file_wine_to_w32_result"
+  fi
+  func_convert_file_check "$1" "$func_to_host_file_result"
+}
+# end func_convert_file_nix_to_w32
+
+
+# func_convert_file_msys_to_cygwin ARG
+# Convert file name ARG from MSYS to Cygwin format.  Requires LT_CYGPATH set.
+# Returns result in func_to_host_file_result.
+func_convert_file_msys_to_cygwin ()
+{
+  $opt_debug
+  func_to_host_file_result="$1"
+  if test -n "$1"; then
+    func_convert_core_msys_to_w32 "$1"
+    func_cygpath -u "$func_convert_core_msys_to_w32_result"
+    func_to_host_file_result="$func_cygpath_result"
+  fi
+  func_convert_file_check "$1" "$func_to_host_file_result"
+}
+# end func_convert_file_msys_to_cygwin
+
+
+# func_convert_file_nix_to_cygwin ARG
+# Convert file name ARG from *nix to Cygwin format.  Requires Cygwin installed
+# in a wine environment, working winepath, and LT_CYGPATH set.  Returns result
+# in func_to_host_file_result.
+func_convert_file_nix_to_cygwin ()
+{
+  $opt_debug
+  func_to_host_file_result="$1"
+  if test -n "$1"; then
+    # convert from *nix to w32, then use cygpath to convert from w32 to cygwin.
+    func_convert_core_file_wine_to_w32 "$1"
+    func_cygpath -u "$func_convert_core_file_wine_to_w32_result"
+    func_to_host_file_result="$func_cygpath_result"
+  fi
+  func_convert_file_check "$1" "$func_to_host_file_result"
+}
+# end func_convert_file_nix_to_cygwin
+
+
+#############################################
+# $build to $host PATH CONVERSION FUNCTIONS #
+#############################################
+# invoked via `$to_host_path_cmd ARG'
+#
+# In each case, ARG is the path to be converted from $build to $host format.
+# The result will be available in $func_to_host_path_result.
+#
+# Path separators are also converted from $build format to $host format.  If
+# ARG begins or ends with a path separator character, it is preserved (but
+# converted to $host format) on output.
+#
+# All path conversion functions are named using the following convention:
+#   file name conversion function    : func_convert_file_X_to_Y ()
+#   path conversion function         : func_convert_path_X_to_Y ()
+# where, for any given $build/$host combination the 'X_to_Y' value is the
+# same.  If conversion functions are added for new $build/$host combinations,
+# the two new functions must follow this pattern, or func_init_to_host_path_cmd
+# will break.
+
+
+# func_init_to_host_path_cmd
+# Ensures that function "pointer" variable $to_host_path_cmd is set to the
+# appropriate value, based on the value of $to_host_file_cmd.
+to_host_path_cmd=
+func_init_to_host_path_cmd ()
+{
+  $opt_debug
+  if test -z "$to_host_path_cmd"; then
+    func_stripname 'func_convert_file_' '' "$to_host_file_cmd"
+    to_host_path_cmd="func_convert_path_${func_stripname_result}"
+  fi
+}
+
+
+# func_to_host_path ARG
+# Converts the path ARG from $build format to $host format. Return result
+# in func_to_host_path_result.
+func_to_host_path ()
+{
+  $opt_debug
+  func_init_to_host_path_cmd
+  $to_host_path_cmd "$1"
+}
+# end func_to_host_path
+
+
+# func_convert_path_noop ARG
+# Copy ARG to func_to_host_path_result.
+func_convert_path_noop ()
+{
+  func_to_host_path_result="$1"
+}
+# end func_convert_path_noop
+
+
+# func_convert_path_msys_to_w32 ARG
+# Convert path ARG from (mingw) MSYS to (mingw) w32 format; automatic
+# conversion to w32 is not available inside the cwrapper.  Returns result in
+# func_to_host_path_result.
+func_convert_path_msys_to_w32 ()
+{
+  $opt_debug
+  func_to_host_path_result="$1"
+  if test -n "$1"; then
+    # Remove leading and trailing path separator characters from ARG.  MSYS
+    # behavior is inconsistent here; cygpath turns them into '.;' and ';.';
+    # and winepath ignores them completely.
+    func_stripname : : "$1"
+    func_to_host_path_tmp1=$func_stripname_result
+    func_convert_core_msys_to_w32 "$func_to_host_path_tmp1"
+    func_to_host_path_result="$func_convert_core_msys_to_w32_result"
+    func_convert_path_check : ";" \
+      "$func_to_host_path_tmp1" "$func_to_host_path_result"
+    func_convert_path_front_back_pathsep ":*" "*:" ";" "$1"
+  fi
+}
+# end func_convert_path_msys_to_w32
+
+
+# func_convert_path_cygwin_to_w32 ARG
+# Convert path ARG from Cygwin to w32 format.  Returns result in
+# func_to_host_file_result.
+func_convert_path_cygwin_to_w32 ()
+{
+  $opt_debug
+  func_to_host_path_result="$1"
+  if test -n "$1"; then
+    # See func_convert_path_msys_to_w32:
+    func_stripname : : "$1"
+    func_to_host_path_tmp1=$func_stripname_result
+    func_to_host_path_result=`cygpath -m -p "$func_to_host_path_tmp1"`
+    func_convert_path_check : ";" \
+      "$func_to_host_path_tmp1" "$func_to_host_path_result"
+    func_convert_path_front_back_pathsep ":*" "*:" ";" "$1"
+  fi
+}
+# end func_convert_path_cygwin_to_w32
+
+
+# func_convert_path_nix_to_w32 ARG
+# Convert path ARG from *nix to w32 format.  Requires a wine environment and
+# a working winepath.  Returns result in func_to_host_file_result.
+func_convert_path_nix_to_w32 ()
+{
+  $opt_debug
+  func_to_host_path_result="$1"
+  if test -n "$1"; then
+    # See func_convert_path_msys_to_w32:
+    func_stripname : : "$1"
+    func_to_host_path_tmp1=$func_stripname_result
+    func_convert_core_path_wine_to_w32 "$func_to_host_path_tmp1"
+    func_to_host_path_result="$func_convert_core_path_wine_to_w32_result"
+    func_convert_path_check : ";" \
+      "$func_to_host_path_tmp1" "$func_to_host_path_result"
+    func_convert_path_front_back_pathsep ":*" "*:" ";" "$1"
+  fi
+}
+# end func_convert_path_nix_to_w32
+
+
+# func_convert_path_msys_to_cygwin ARG
+# Convert path ARG from MSYS to Cygwin format.  Requires LT_CYGPATH set.
+# Returns result in func_to_host_file_result.
+func_convert_path_msys_to_cygwin ()
+{
+  $opt_debug
+  func_to_host_path_result="$1"
+  if test -n "$1"; then
+    # See func_convert_path_msys_to_w32:
+    func_stripname : : "$1"
+    func_to_host_path_tmp1=$func_stripname_result
+    func_convert_core_msys_to_w32 "$func_to_host_path_tmp1"
+    func_cygpath -u -p "$func_convert_core_msys_to_w32_result"
+    func_to_host_path_result="$func_cygpath_result"
+    func_convert_path_check : : \
+      "$func_to_host_path_tmp1" "$func_to_host_path_result"
+    func_convert_path_front_back_pathsep ":*" "*:" : "$1"
+  fi
+}
+# end func_convert_path_msys_to_cygwin
+
+
+# func_convert_path_nix_to_cygwin ARG
+# Convert path ARG from *nix to Cygwin format.  Requires Cygwin installed in a
+# a wine environment, working winepath, and LT_CYGPATH set.  Returns result in
+# func_to_host_file_result.
+func_convert_path_nix_to_cygwin ()
+{
+  $opt_debug
+  func_to_host_path_result="$1"
+  if test -n "$1"; then
+    # Remove leading and trailing path separator characters from
+    # ARG. msys behavior is inconsistent here, cygpath turns them
+    # into '.;' and ';.', and winepath ignores them completely.
+    func_stripname : : "$1"
+    func_to_host_path_tmp1=$func_stripname_result
+    func_convert_core_path_wine_to_w32 "$func_to_host_path_tmp1"
+    func_cygpath -u -p "$func_convert_core_path_wine_to_w32_result"
+    func_to_host_path_result="$func_cygpath_result"
+    func_convert_path_check : : \
+      "$func_to_host_path_tmp1" "$func_to_host_path_result"
+    func_convert_path_front_back_pathsep ":*" "*:" : "$1"
+  fi
+}
+# end func_convert_path_nix_to_cygwin
+
+
+# func_mode_compile arg...
+func_mode_compile ()
+{
+    $opt_debug
+    # Get the compilation command and the source file.
+    base_compile=
+    srcfile="$nonopt"  #  always keep a non-empty value in "srcfile"
+    suppress_opt=yes
+    suppress_output=
+    arg_mode=normal
+    libobj=
+    later=
+    pie_flag=
+
+    for arg
+    do
+      case $arg_mode in
+      arg  )
+	# do not "continue".  Instead, add this to base_compile
+	lastarg="$arg"
+	arg_mode=normal
+	;;
+
+      target )
+	libobj="$arg"
+	arg_mode=normal
+	continue
+	;;
+
+      normal )
+	# Accept any command-line options.
+	case $arg in
+	-o)
+	  test -n "$libobj" && \
+	    func_fatal_error "you cannot specify \`-o' more than once"
+	  arg_mode=target
+	  continue
+	  ;;
+
+	-pie | -fpie | -fPIE)
+          func_append pie_flag " $arg"
+	  continue
+	  ;;
+
+	-shared | -static | -prefer-pic | -prefer-non-pic)
+	  func_append later " $arg"
+	  continue
+	  ;;
+
+	-no-suppress)
+	  suppress_opt=no
+	  continue
+	  ;;
+
+	-Xcompiler)
+	  arg_mode=arg  #  the next one goes into the "base_compile" arg list
+	  continue      #  The current "srcfile" will either be retained or
+	  ;;            #  replaced later.  I would guess that would be a bug.
+
+	-Wc,*)
+	  func_stripname '-Wc,' '' "$arg"
+	  args=$func_stripname_result
+	  lastarg=
+	  save_ifs="$IFS"; IFS=','
+	  for arg in $args; do
+	    IFS="$save_ifs"
+	    func_append_quoted lastarg "$arg"
+	  done
+	  IFS="$save_ifs"
+	  func_stripname ' ' '' "$lastarg"
+	  lastarg=$func_stripname_result
+
+	  # Add the arguments to base_compile.
+	  func_append base_compile " $lastarg"
+	  continue
+	  ;;
+
+	*)
+	  # Accept the current argument as the source file.
+	  # The previous "srcfile" becomes the current argument.
+	  #
+	  lastarg="$srcfile"
+	  srcfile="$arg"
+	  ;;
+	esac  #  case $arg
+	;;
+      esac    #  case $arg_mode
+
+      # Aesthetically quote the previous argument.
+      func_append_quoted base_compile "$lastarg"
+    done # for arg
+
+    case $arg_mode in
+    arg)
+      func_fatal_error "you must specify an argument for -Xcompile"
+      ;;
+    target)
+      func_fatal_error "you must specify a target with \`-o'"
+      ;;
+    *)
+      # Get the name of the library object.
+      test -z "$libobj" && {
+	func_basename "$srcfile"
+	libobj="$func_basename_result"
+      }
+      ;;
+    esac
+
+    # Recognize several different file suffixes.
+    # If the user specifies -o file.o, it is replaced with file.lo
+    case $libobj in
+    *.[cCFSifmso] | \
+    *.ada | *.adb | *.ads | *.asm | \
+    *.c++ | *.cc | *.ii | *.class | *.cpp | *.cxx | \
+    *.[fF][09]? | *.for | *.java | *.go | *.obj | *.sx | *.cu | *.cup)
+      func_xform "$libobj"
+      libobj=$func_xform_result
+      ;;
+    esac
+
+    case $libobj in
+    *.lo) func_lo2o "$libobj"; obj=$func_lo2o_result ;;
+    *)
+      func_fatal_error "cannot determine name of library object from \`$libobj'"
+      ;;
+    esac
+
+    func_infer_tag $base_compile
+
+    for arg in $later; do
+      case $arg in
+      -shared)
+	test "$build_libtool_libs" != yes && \
+	  func_fatal_configuration "can not build a shared library"
+	build_old_libs=no
+	continue
+	;;
+
+      -static)
+	build_libtool_libs=no
+	build_old_libs=yes
+	continue
+	;;
+
+      -prefer-pic)
+	pic_mode=yes
+	continue
+	;;
+
+      -prefer-non-pic)
+	pic_mode=no
+	continue
+	;;
+      esac
+    done
+
+    func_quote_for_eval "$libobj"
+    test "X$libobj" != "X$func_quote_for_eval_result" \
+      && $ECHO "X$libobj" | $GREP '[]~#^*{};<>?"'"'"'	 &()|`$[]' \
+      && func_warning "libobj name \`$libobj' may not contain shell special characters."
+    func_dirname_and_basename "$obj" "/" ""
+    objname="$func_basename_result"
+    xdir="$func_dirname_result"
+    lobj=${xdir}$objdir/$objname
+
+    test -z "$base_compile" && \
+      func_fatal_help "you must specify a compilation command"
+
+    # Delete any leftover library objects.
+    if test "$build_old_libs" = yes; then
+      removelist="$obj $lobj $libobj ${libobj}T"
+    else
+      removelist="$lobj $libobj ${libobj}T"
+    fi
+
+    # On Cygwin there's no "real" PIC flag so we must build both object types
+    case $host_os in
+    cygwin* | mingw* | pw32* | os2* | cegcc*)
+      pic_mode=default
+      ;;
+    esac
+    if test "$pic_mode" = no && test "$deplibs_check_method" != pass_all; then
+      # non-PIC code in shared libraries is not supported
+      pic_mode=default
+    fi
+
+    # Calculate the filename of the output object if compiler does
+    # not support -o with -c
+    if test "$compiler_c_o" = no; then
+      output_obj=`$ECHO "$srcfile" | $SED 's%^.*/%%; s%\.[^.]*$%%'`.${objext}
+      lockfile="$output_obj.lock"
+    else
+      output_obj=
+      need_locks=no
+      lockfile=
+    fi
+
+    # Lock this critical section if it is needed
+    # We use this script file to make the link, it avoids creating a new file
+    if test "$need_locks" = yes; then
+      until $opt_dry_run || ln "$progpath" "$lockfile" 2>/dev/null; do
+	func_echo "Waiting for $lockfile to be removed"
+	sleep 2
+      done
+    elif test "$need_locks" = warn; then
+      if test -f "$lockfile"; then
+	$ECHO "\
+*** ERROR, $lockfile exists and contains:
+`cat $lockfile 2>/dev/null`
+
+This indicates that another process is trying to use the same
+temporary object file, and libtool could not work around it because
+your compiler does not support \`-c' and \`-o' together.  If you
+repeat this compilation, it may succeed, by chance, but you had better
+avoid parallel builds (make -j) in this platform, or get a better
+compiler."
+
+	$opt_dry_run || $RM $removelist
+	exit $EXIT_FAILURE
+      fi
+      func_append removelist " $output_obj"
+      $ECHO "$srcfile" > "$lockfile"
+    fi
+
+    $opt_dry_run || $RM $removelist
+    func_append removelist " $lockfile"
+    trap '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' 1 2 15
+
+    func_to_tool_file "$srcfile" func_convert_file_msys_to_w32
+    srcfile=$func_to_tool_file_result
+    func_quote_for_eval "$srcfile"
+    qsrcfile=$func_quote_for_eval_result
+
+    # Only build a PIC object if we are building libtool libraries.
+    if test "$build_libtool_libs" = yes; then
+      # Without this assignment, base_compile gets emptied.
+      fbsd_hideous_sh_bug=$base_compile
+
+      if test "$pic_mode" != no; then
+	command="$base_compile $qsrcfile $pic_flag"
+      else
+	# Don't build PIC code
+	command="$base_compile $qsrcfile"
+      fi
+
+      func_mkdir_p "$xdir$objdir"
+
+      if test -z "$output_obj"; then
+	# Place PIC objects in $objdir
+	func_append command " -o $lobj"
+      fi
+
+      func_show_eval_locale "$command"	\
+          'test -n "$output_obj" && $RM $removelist; exit $EXIT_FAILURE'
+
+      if test "$need_locks" = warn &&
+	 test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then
+	$ECHO "\
+*** ERROR, $lockfile contains:
+`cat $lockfile 2>/dev/null`
+
+but it should contain:
+$srcfile
+
+This indicates that another process is trying to use the same
+temporary object file, and libtool could not work around it because
+your compiler does not support \`-c' and \`-o' together.  If you
+repeat this compilation, it may succeed, by chance, but you had better
+avoid parallel builds (make -j) in this platform, or get a better
+compiler."
+
+	$opt_dry_run || $RM $removelist
+	exit $EXIT_FAILURE
+      fi
+
+      # Just move the object if needed, then go on to compile the next one
+      if test -n "$output_obj" && test "X$output_obj" != "X$lobj"; then
+	func_show_eval '$MV "$output_obj" "$lobj"' \
+	  'error=$?; $opt_dry_run || $RM $removelist; exit $error'
+      fi
+
+      # Allow error messages only from the first compilation.
+      if test "$suppress_opt" = yes; then
+	suppress_output=' >/dev/null 2>&1'
+      fi
+    fi
+
+    # Only build a position-dependent object if we build old libraries.
+    if test "$build_old_libs" = yes; then
+      if test "$pic_mode" != yes; then
+	# Don't build PIC code
+	command="$base_compile $qsrcfile$pie_flag"
+      else
+	command="$base_compile $qsrcfile $pic_flag"
+      fi
+      if test "$compiler_c_o" = yes; then
+	func_append command " -o $obj"
+      fi
+
+      # Suppress compiler output if we already did a PIC compilation.
+      func_append command "$suppress_output"
+      func_show_eval_locale "$command" \
+        '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE'
+
+      if test "$need_locks" = warn &&
+	 test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then
+	$ECHO "\
+*** ERROR, $lockfile contains:
+`cat $lockfile 2>/dev/null`
+
+but it should contain:
+$srcfile
+
+This indicates that another process is trying to use the same
+temporary object file, and libtool could not work around it because
+your compiler does not support \`-c' and \`-o' together.  If you
+repeat this compilation, it may succeed, by chance, but you had better
+avoid parallel builds (make -j) in this platform, or get a better
+compiler."
+
+	$opt_dry_run || $RM $removelist
+	exit $EXIT_FAILURE
+      fi
+
+      # Just move the object if needed
+      if test -n "$output_obj" && test "X$output_obj" != "X$obj"; then
+	func_show_eval '$MV "$output_obj" "$obj"' \
+	  'error=$?; $opt_dry_run || $RM $removelist; exit $error'
+      fi
+    fi
+
+    $opt_dry_run || {
+      func_write_libtool_object "$libobj" "$objdir/$objname" "$objname"
+
+      # Unlock the critical section if it was locked
+      if test "$need_locks" != no; then
+	removelist=$lockfile
+        $RM "$lockfile"
+      fi
+    }
+
+    exit $EXIT_SUCCESS
+}
+
+$opt_help || {
+  test "$opt_mode" = compile && func_mode_compile ${1+"$@"}
+}
+
+func_mode_help ()
+{
+    # We need to display help for each of the modes.
+    case $opt_mode in
+      "")
+        # Generic help is extracted from the usage comments
+        # at the start of this file.
+        func_help
+        ;;
+
+      clean)
+        $ECHO \
+"Usage: $progname [OPTION]... --mode=clean RM [RM-OPTION]... FILE...
+
+Remove files from the build directory.
+
+RM is the name of the program to use to delete files associated with each FILE
+(typically \`/bin/rm').  RM-OPTIONS are options (such as \`-f') to be passed
+to RM.
+
+If FILE is a libtool library, object or program, all the files associated
+with it are deleted. Otherwise, only FILE itself is deleted using RM."
+        ;;
+
+      compile)
+      $ECHO \
+"Usage: $progname [OPTION]... --mode=compile COMPILE-COMMAND... SOURCEFILE
+
+Compile a source file into a libtool library object.
+
+This mode accepts the following additional options:
+
+  -o OUTPUT-FILE    set the output file name to OUTPUT-FILE
+  -no-suppress      do not suppress compiler output for multiple passes
+  -prefer-pic       try to build PIC objects only
+  -prefer-non-pic   try to build non-PIC objects only
+  -shared           do not build a \`.o' file suitable for static linking
+  -static           only build a \`.o' file suitable for static linking
+  -Wc,FLAG          pass FLAG directly to the compiler
+
+COMPILE-COMMAND is a command to be used in creating a \`standard' object file
+from the given SOURCEFILE.
+
+The output file name is determined by removing the directory component from
+SOURCEFILE, then substituting the C source code suffix \`.c' with the
+library object suffix, \`.lo'."
+        ;;
+
+      execute)
+        $ECHO \
+"Usage: $progname [OPTION]... --mode=execute COMMAND [ARGS]...
+
+Automatically set library path, then run a program.
+
+This mode accepts the following additional options:
+
+  -dlopen FILE      add the directory containing FILE to the library path
+
+This mode sets the library path environment variable according to \`-dlopen'
+flags.
+
+If any of the ARGS are libtool executable wrappers, then they are translated
+into their corresponding uninstalled binary, and any of their required library
+directories are added to the library path.
+
+Then, COMMAND is executed, with ARGS as arguments."
+        ;;
+
+      finish)
+        $ECHO \
+"Usage: $progname [OPTION]... --mode=finish [LIBDIR]...
+
+Complete the installation of libtool libraries.
+
+Each LIBDIR is a directory that contains libtool libraries.
+
+The commands that this mode executes may require superuser privileges.  Use
+the \`--dry-run' option if you just want to see what would be executed."
+        ;;
+
+      install)
+        $ECHO \
+"Usage: $progname [OPTION]... --mode=install INSTALL-COMMAND...
+
+Install executables or libraries.
+
+INSTALL-COMMAND is the installation command.  The first component should be
+either the \`install' or \`cp' program.
+
+The following components of INSTALL-COMMAND are treated specially:
+
+  -inst-prefix-dir PREFIX-DIR  Use PREFIX-DIR as a staging area for installation
+
+The rest of the components are interpreted as arguments to that command (only
+BSD-compatible install options are recognized)."
+        ;;
+
+      link)
+        $ECHO \
+"Usage: $progname [OPTION]... --mode=link LINK-COMMAND...
+
+Link object files or libraries together to form another library, or to
+create an executable program.
+
+LINK-COMMAND is a command using the C compiler that you would use to create
+a program from several object files.
+
+The following components of LINK-COMMAND are treated specially:
+
+  -all-static       do not do any dynamic linking at all
+  -avoid-version    do not add a version suffix if possible
+  -bindir BINDIR    specify path to binaries directory (for systems where
+                    libraries must be found in the PATH setting at runtime)
+  -dlopen FILE      \`-dlpreopen' FILE if it cannot be dlopened at runtime
+  -dlpreopen FILE   link in FILE and add its symbols to lt_preloaded_symbols
+  -export-dynamic   allow symbols from OUTPUT-FILE to be resolved with dlsym(3)
+  -export-symbols SYMFILE
+                    try to export only the symbols listed in SYMFILE
+  -export-symbols-regex REGEX
+                    try to export only the symbols matching REGEX
+  -LLIBDIR          search LIBDIR for required installed libraries
+  -lNAME            OUTPUT-FILE requires the installed library libNAME
+  -module           build a library that can dlopened
+  -no-fast-install  disable the fast-install mode
+  -no-install       link a not-installable executable
+  -no-undefined     declare that a library does not refer to external symbols
+  -o OUTPUT-FILE    create OUTPUT-FILE from the specified objects
+  -objectlist FILE  Use a list of object files found in FILE to specify objects
+  -precious-files-regex REGEX
+                    don't remove output files matching REGEX
+  -release RELEASE  specify package release information
+  -rpath LIBDIR     the created library will eventually be installed in LIBDIR
+  -R[ ]LIBDIR       add LIBDIR to the runtime path of programs and libraries
+  -shared           only do dynamic linking of libtool libraries
+  -shrext SUFFIX    override the standard shared library file extension
+  -static           do not do any dynamic linking of uninstalled libtool libraries
+  -static-libtool-libs
+                    do not do any dynamic linking of libtool libraries
+  -version-info CURRENT[:REVISION[:AGE]]
+                    specify library version info [each variable defaults to 0]
+  -weak LIBNAME     declare that the target provides the LIBNAME interface
+  -Wc,FLAG
+  -Xcompiler FLAG   pass linker-specific FLAG directly to the compiler
+  -Wl,FLAG
+  -Xlinker FLAG     pass linker-specific FLAG directly to the linker
+  -XCClinker FLAG   pass link-specific FLAG to the compiler driver (CC)
+
+All other options (arguments beginning with \`-') are ignored.
+
+Every other argument is treated as a filename.  Files ending in \`.la' are
+treated as uninstalled libtool libraries, other files are standard or library
+object files.
+
+If the OUTPUT-FILE ends in \`.la', then a libtool library is created,
+only library objects (\`.lo' files) may be specified, and \`-rpath' is
+required, except when creating a convenience library.
+
+If OUTPUT-FILE ends in \`.a' or \`.lib', then a standard library is created
+using \`ar' and \`ranlib', or on Windows using \`lib'.
+
+If OUTPUT-FILE ends in \`.lo' or \`.${objext}', then a reloadable object file
+is created, otherwise an executable program is created."
+        ;;
+
+      uninstall)
+        $ECHO \
+"Usage: $progname [OPTION]... --mode=uninstall RM [RM-OPTION]... FILE...
+
+Remove libraries from an installation directory.
+
+RM is the name of the program to use to delete files associated with each FILE
+(typically \`/bin/rm').  RM-OPTIONS are options (such as \`-f') to be passed
+to RM.
+
+If FILE is a libtool library, all the files associated with it are deleted.
+Otherwise, only FILE itself is deleted using RM."
+        ;;
+
+      *)
+        func_fatal_help "invalid operation mode \`$opt_mode'"
+        ;;
+    esac
+
+    echo
+    $ECHO "Try \`$progname --help' for more information about other modes."
+}
+
+# Now that we've collected a possible --mode arg, show help if necessary
+if $opt_help; then
+  if test "$opt_help" = :; then
+    func_mode_help
+  else
+    {
+      func_help noexit
+      for opt_mode in compile link execute install finish uninstall clean; do
+	func_mode_help
+      done
+    } | sed -n '1p; 2,$s/^Usage:/  or: /p'
+    {
+      func_help noexit
+      for opt_mode in compile link execute install finish uninstall clean; do
+	echo
+	func_mode_help
+      done
+    } |
+    sed '1d
+      /^When reporting/,/^Report/{
+	H
+	d
+      }
+      $x
+      /information about other modes/d
+      /more detailed .*MODE/d
+      s/^Usage:.*--mode=\([^ ]*\) .*/Description of \1 mode:/'
+  fi
+  exit $?
+fi
+
+
+# func_mode_execute arg...
+func_mode_execute ()
+{
+    $opt_debug
+    # The first argument is the command name.
+    cmd="$nonopt"
+    test -z "$cmd" && \
+      func_fatal_help "you must specify a COMMAND"
+
+    # Handle -dlopen flags immediately.
+    for file in $opt_dlopen; do
+      test -f "$file" \
+	|| func_fatal_help "\`$file' is not a file"
+
+      dir=
+      case $file in
+      *.la)
+	func_resolve_sysroot "$file"
+	file=$func_resolve_sysroot_result
+
+	# Check to see that this really is a libtool archive.
+	func_lalib_unsafe_p "$file" \
+	  || func_fatal_help "\`$lib' is not a valid libtool archive"
+
+	# Read the libtool library.
+	dlname=
+	library_names=
+	func_source "$file"
+
+	# Skip this library if it cannot be dlopened.
+	if test -z "$dlname"; then
+	  # Warn if it was a shared library.
+	  test -n "$library_names" && \
+	    func_warning "\`$file' was not linked with \`-export-dynamic'"
+	  continue
+	fi
+
+	func_dirname "$file" "" "."
+	dir="$func_dirname_result"
+
+	if test -f "$dir/$objdir/$dlname"; then
+	  func_append dir "/$objdir"
+	else
+	  if test ! -f "$dir/$dlname"; then
+	    func_fatal_error "cannot find \`$dlname' in \`$dir' or \`$dir/$objdir'"
+	  fi
+	fi
+	;;
+
+      *.lo)
+	# Just add the directory containing the .lo file.
+	func_dirname "$file" "" "."
+	dir="$func_dirname_result"
+	;;
+
+      *)
+	func_warning "\`-dlopen' is ignored for non-libtool libraries and objects"
+	continue
+	;;
+      esac
+
+      # Get the absolute pathname.
+      absdir=`cd "$dir" && pwd`
+      test -n "$absdir" && dir="$absdir"
+
+      # Now add the directory to shlibpath_var.
+      if eval "test -z \"\$$shlibpath_var\""; then
+	eval "$shlibpath_var=\"\$dir\""
+      else
+	eval "$shlibpath_var=\"\$dir:\$$shlibpath_var\""
+      fi
+    done
+
+    # This variable tells wrapper scripts just to set shlibpath_var
+    # rather than running their programs.
+    libtool_execute_magic="$magic"
+
+    # Check if any of the arguments is a wrapper script.
+    args=
+    for file
+    do
+      case $file in
+      -* | *.la | *.lo ) ;;
+      *)
+	# Do a test to see if this is really a libtool program.
+	if func_ltwrapper_script_p "$file"; then
+	  func_source "$file"
+	  # Transform arg to wrapped name.
+	  file="$progdir/$program"
+	elif func_ltwrapper_executable_p "$file"; then
+	  func_ltwrapper_scriptname "$file"
+	  func_source "$func_ltwrapper_scriptname_result"
+	  # Transform arg to wrapped name.
+	  file="$progdir/$program"
+	fi
+	;;
+      esac
+      # Quote arguments (to preserve shell metacharacters).
+      func_append_quoted args "$file"
+    done
+
+    if test "X$opt_dry_run" = Xfalse; then
+      if test -n "$shlibpath_var"; then
+	# Export the shlibpath_var.
+	eval "export $shlibpath_var"
+      fi
+
+      # Restore saved environment variables
+      for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES
+      do
+	eval "if test \"\${save_$lt_var+set}\" = set; then
+                $lt_var=\$save_$lt_var; export $lt_var
+	      else
+		$lt_unset $lt_var
+	      fi"
+      done
+
+      # Now prepare to actually exec the command.
+      exec_cmd="\$cmd$args"
+    else
+      # Display what would be done.
+      if test -n "$shlibpath_var"; then
+	eval "\$ECHO \"\$shlibpath_var=\$$shlibpath_var\""
+	echo "export $shlibpath_var"
+      fi
+      $ECHO "$cmd$args"
+      exit $EXIT_SUCCESS
+    fi
+}
+
+test "$opt_mode" = execute && func_mode_execute ${1+"$@"}
+
+
+# func_mode_finish arg...
+func_mode_finish ()
+{
+    $opt_debug
+    libs=
+    libdirs=
+    admincmds=
+
+    for opt in "$nonopt" ${1+"$@"}
+    do
+      if test -d "$opt"; then
+	func_append libdirs " $opt"
+
+      elif test -f "$opt"; then
+	if func_lalib_unsafe_p "$opt"; then
+	  func_append libs " $opt"
+	else
+	  func_warning "\`$opt' is not a valid libtool archive"
+	fi
+
+      else
+	func_fatal_error "invalid argument \`$opt'"
+      fi
+    done
+
+    if test -n "$libs"; then
+      if test -n "$lt_sysroot"; then
+        sysroot_regex=`$ECHO "$lt_sysroot" | $SED "$sed_make_literal_regex"`
+        sysroot_cmd="s/\([ ']\)$sysroot_regex/\1/g;"
+      else
+        sysroot_cmd=
+      fi
+
+      # Remove sysroot references
+      if $opt_dry_run; then
+        for lib in $libs; do
+          echo "removing references to $lt_sysroot and \`=' prefixes from $lib"
+        done
+      else
+        tmpdir=`func_mktempdir`
+        for lib in $libs; do
+	  sed -e "${sysroot_cmd} s/\([ ']-[LR]\)=/\1/g; s/\([ ']\)=/\1/g" $lib \
+	    > $tmpdir/tmp-la
+	  mv -f $tmpdir/tmp-la $lib
+	done
+        ${RM}r "$tmpdir"
+      fi
+    fi
+
+    if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then
+      for libdir in $libdirs; do
+	if test -n "$finish_cmds"; then
+	  # Do each command in the finish commands.
+	  func_execute_cmds "$finish_cmds" 'admincmds="$admincmds
+'"$cmd"'"'
+	fi
+	if test -n "$finish_eval"; then
+	  # Do the single finish_eval.
+	  eval cmds=\"$finish_eval\"
+	  $opt_dry_run || eval "$cmds" || func_append admincmds "
+       $cmds"
+	fi
+      done
+    fi
+
+    # Exit here if they wanted silent mode.
+    $opt_silent && exit $EXIT_SUCCESS
+
+    if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then
+      echo "----------------------------------------------------------------------"
+      echo "Libraries have been installed in:"
+      for libdir in $libdirs; do
+	$ECHO "   $libdir"
+      done
+      echo
+      echo "If you ever happen to want to link against installed libraries"
+      echo "in a given directory, LIBDIR, you must either use libtool, and"
+      echo "specify the full pathname of the library, or use the \`-LLIBDIR'"
+      echo "flag during linking and do at least one of the following:"
+      if test -n "$shlibpath_var"; then
+	echo "   - add LIBDIR to the \`$shlibpath_var' environment variable"
+	echo "     during execution"
+      fi
+      if test -n "$runpath_var"; then
+	echo "   - add LIBDIR to the \`$runpath_var' environment variable"
+	echo "     during linking"
+      fi
+      if test -n "$hardcode_libdir_flag_spec"; then
+	libdir=LIBDIR
+	eval flag=\"$hardcode_libdir_flag_spec\"
+
+	$ECHO "   - use the \`$flag' linker flag"
+      fi
+      if test -n "$admincmds"; then
+	$ECHO "   - have your system administrator run these commands:$admincmds"
+      fi
+      if test -f /etc/ld.so.conf; then
+	echo "   - have your system administrator add LIBDIR to \`/etc/ld.so.conf'"
+      fi
+      echo
+
+      echo "See any operating system documentation about shared libraries for"
+      case $host in
+	solaris2.[6789]|solaris2.1[0-9])
+	  echo "more information, such as the ld(1), crle(1) and ld.so(8) manual"
+	  echo "pages."
+	  ;;
+	*)
+	  echo "more information, such as the ld(1) and ld.so(8) manual pages."
+	  ;;
+      esac
+      echo "----------------------------------------------------------------------"
+    fi
+    exit $EXIT_SUCCESS
+}
+
+test "$opt_mode" = finish && func_mode_finish ${1+"$@"}
+
+
+# func_mode_install arg...
+func_mode_install ()
+{
+    $opt_debug
+    # There may be an optional sh(1) argument at the beginning of
+    # install_prog (especially on Windows NT).
+    if test "$nonopt" = "$SHELL" || test "$nonopt" = /bin/sh ||
+       # Allow the use of GNU shtool's install command.
+       case $nonopt in *shtool*) :;; *) false;; esac; then
+      # Aesthetically quote it.
+      func_quote_for_eval "$nonopt"
+      install_prog="$func_quote_for_eval_result "
+      arg=$1
+      shift
+    else
+      install_prog=
+      arg=$nonopt
+    fi
+
+    # The real first argument should be the name of the installation program.
+    # Aesthetically quote it.
+    func_quote_for_eval "$arg"
+    func_append install_prog "$func_quote_for_eval_result"
+    install_shared_prog=$install_prog
+    case " $install_prog " in
+      *[\\\ /]cp\ *) install_cp=: ;;
+      *) install_cp=false ;;
+    esac
+
+    # We need to accept at least all the BSD install flags.
+    dest=
+    files=
+    opts=
+    prev=
+    install_type=
+    isdir=no
+    stripme=
+    no_mode=:
+    for arg
+    do
+      arg2=
+      if test -n "$dest"; then
+	func_append files " $dest"
+	dest=$arg
+	continue
+      fi
+
+      case $arg in
+      -d) isdir=yes ;;
+      -f)
+	if $install_cp; then :; else
+	  prev=$arg
+	fi
+	;;
+      -g | -m | -o)
+	prev=$arg
+	;;
+      -s)
+	stripme=" -s"
+	continue
+	;;
+      -*)
+	;;
+      *)
+	# If the previous option needed an argument, then skip it.
+	if test -n "$prev"; then
+	  if test "x$prev" = x-m && test -n "$install_override_mode"; then
+	    arg2=$install_override_mode
+	    no_mode=false
+	  fi
+	  prev=
+	else
+	  dest=$arg
+	  continue
+	fi
+	;;
+      esac
+
+      # Aesthetically quote the argument.
+      func_quote_for_eval "$arg"
+      func_append install_prog " $func_quote_for_eval_result"
+      if test -n "$arg2"; then
+	func_quote_for_eval "$arg2"
+      fi
+      func_append install_shared_prog " $func_quote_for_eval_result"
+    done
+
+    test -z "$install_prog" && \
+      func_fatal_help "you must specify an install program"
+
+    test -n "$prev" && \
+      func_fatal_help "the \`$prev' option requires an argument"
+
+    if test -n "$install_override_mode" && $no_mode; then
+      if $install_cp; then :; else
+	func_quote_for_eval "$install_override_mode"
+	func_append install_shared_prog " -m $func_quote_for_eval_result"
+      fi
+    fi
+
+    if test -z "$files"; then
+      if test -z "$dest"; then
+	func_fatal_help "no file or destination specified"
+      else
+	func_fatal_help "you must specify a destination"
+      fi
+    fi
+
+    # Strip any trailing slash from the destination.
+    func_stripname '' '/' "$dest"
+    dest=$func_stripname_result
+
+    # Check to see that the destination is a directory.
+    test -d "$dest" && isdir=yes
+    if test "$isdir" = yes; then
+      destdir="$dest"
+      destname=
+    else
+      func_dirname_and_basename "$dest" "" "."
+      destdir="$func_dirname_result"
+      destname="$func_basename_result"
+
+      # Not a directory, so check to see that there is only one file specified.
+      set dummy $files; shift
+      test "$#" -gt 1 && \
+	func_fatal_help "\`$dest' is not a directory"
+    fi
+    case $destdir in
+    [\\/]* | [A-Za-z]:[\\/]*) ;;
+    *)
+      for file in $files; do
+	case $file in
+	*.lo) ;;
+	*)
+	  func_fatal_help "\`$destdir' must be an absolute directory name"
+	  ;;
+	esac
+      done
+      ;;
+    esac
+
+    # This variable tells wrapper scripts just to set variables rather
+    # than running their programs.
+    libtool_install_magic="$magic"
+
+    staticlibs=
+    future_libdirs=
+    current_libdirs=
+    for file in $files; do
+
+      # Do each installation.
+      case $file in
+      *.$libext)
+	# Do the static libraries later.
+	func_append staticlibs " $file"
+	;;
+
+      *.la)
+	func_resolve_sysroot "$file"
+	file=$func_resolve_sysroot_result
+
+	# Check to see that this really is a libtool archive.
+	func_lalib_unsafe_p "$file" \
+	  || func_fatal_help "\`$file' is not a valid libtool archive"
+
+	library_names=
+	old_library=
+	relink_command=
+	func_source "$file"
+
+	# Add the libdir to current_libdirs if it is the destination.
+	if test "X$destdir" = "X$libdir"; then
+	  case "$current_libdirs " in
+	  *" $libdir "*) ;;
+	  *) func_append current_libdirs " $libdir" ;;
+	  esac
+	else
+	  # Note the libdir as a future libdir.
+	  case "$future_libdirs " in
+	  *" $libdir "*) ;;
+	  *) func_append future_libdirs " $libdir" ;;
+	  esac
+	fi
+
+	func_dirname "$file" "/" ""
+	dir="$func_dirname_result"
+	func_append dir "$objdir"
+
+	if test -n "$relink_command"; then
+	  # Determine the prefix the user has applied to our future dir.
+	  inst_prefix_dir=`$ECHO "$destdir" | $SED -e "s%$libdir\$%%"`
+
+	  # Don't allow the user to place us outside of our expected
+	  # location b/c this prevents finding dependent libraries that
+	  # are installed to the same prefix.
+	  # At present, this check doesn't affect windows .dll's that
+	  # are installed into $libdir/../bin (currently, that works fine)
+	  # but it's something to keep an eye on.
+	  test "$inst_prefix_dir" = "$destdir" && \
+	    func_fatal_error "error: cannot install \`$file' to a directory not ending in $libdir"
+
+	  if test -n "$inst_prefix_dir"; then
+	    # Stick the inst_prefix_dir data into the link command.
+	    relink_command=`$ECHO "$relink_command" | $SED "s%@inst_prefix_dir@%-inst-prefix-dir $inst_prefix_dir%"`
+	  else
+	    relink_command=`$ECHO "$relink_command" | $SED "s%@inst_prefix_dir@%%"`
+	  fi
+
+	  func_warning "relinking \`$file'"
+	  func_show_eval "$relink_command" \
+	    'func_fatal_error "error: relink \`$file'\'' with the above command before installing it"'
+	fi
+
+	# See the names of the shared library.
+	set dummy $library_names; shift
+	if test -n "$1"; then
+	  realname="$1"
+	  shift
+
+	  srcname="$realname"
+	  test -n "$relink_command" && srcname="$realname"T
+
+	  # Install the shared library and build the symlinks.
+	  func_show_eval "$install_shared_prog $dir/$srcname $destdir/$realname" \
+	      'exit $?'
+	  tstripme="$stripme"
+	  case $host_os in
+	  cygwin* | mingw* | pw32* | cegcc*)
+	    case $realname in
+	    *.dll.a)
+	      tstripme=""
+	      ;;
+	    esac
+	    ;;
+	  esac
+	  if test -n "$tstripme" && test -n "$striplib"; then
+	    func_show_eval "$striplib $destdir/$realname" 'exit $?'
+	  fi
+
+	  if test "$#" -gt 0; then
+	    # Delete the old symlinks, and create new ones.
+	    # Try `ln -sf' first, because the `ln' binary might depend on
+	    # the symlink we replace!  Solaris /bin/ln does not understand -f,
+	    # so we also need to try rm && ln -s.
+	    for linkname
+	    do
+	      test "$linkname" != "$realname" \
+		&& func_show_eval "(cd $destdir && { $LN_S -f $realname $linkname || { $RM $linkname && $LN_S $realname $linkname; }; })"
+	    done
+	  fi
+
+	  # Do each command in the postinstall commands.
+	  lib="$destdir/$realname"
+	  func_execute_cmds "$postinstall_cmds" 'exit $?'
+	fi
+
+	# Install the pseudo-library for information purposes.
+	func_basename "$file"
+	name="$func_basename_result"
+	instname="$dir/$name"i
+	func_show_eval "$install_prog $instname $destdir/$name" 'exit $?'
+
+	# Maybe install the static library, too.
+	test -n "$old_library" && func_append staticlibs " $dir/$old_library"
+	;;
+
+      *.lo)
+	# Install (i.e. copy) a libtool object.
+
+	# Figure out destination file name, if it wasn't already specified.
+	if test -n "$destname"; then
+	  destfile="$destdir/$destname"
+	else
+	  func_basename "$file"
+	  destfile="$func_basename_result"
+	  destfile="$destdir/$destfile"
+	fi
+
+	# Deduce the name of the destination old-style object file.
+	case $destfile in
+	*.lo)
+	  func_lo2o "$destfile"
+	  staticdest=$func_lo2o_result
+	  ;;
+	*.$objext)
+	  staticdest="$destfile"
+	  destfile=
+	  ;;
+	*)
+	  func_fatal_help "cannot copy a libtool object to \`$destfile'"
+	  ;;
+	esac
+
+	# Install the libtool object if requested.
+	test -n "$destfile" && \
+	  func_show_eval "$install_prog $file $destfile" 'exit $?'
+
+	# Install the old object if enabled.
+	if test "$build_old_libs" = yes; then
+	  # Deduce the name of the old-style object file.
+	  func_lo2o "$file"
+	  staticobj=$func_lo2o_result
+	  func_show_eval "$install_prog \$staticobj \$staticdest" 'exit $?'
+	fi
+	exit $EXIT_SUCCESS
+	;;
+
+      *)
+	# Figure out destination file name, if it wasn't already specified.
+	if test -n "$destname"; then
+	  destfile="$destdir/$destname"
+	else
+	  func_basename "$file"
+	  destfile="$func_basename_result"
+	  destfile="$destdir/$destfile"
+	fi
+
+	# If the file is missing, and there is a .exe on the end, strip it
+	# because it is most likely a libtool script we actually want to
+	# install
+	stripped_ext=""
+	case $file in
+	  *.exe)
+	    if test ! -f "$file"; then
+	      func_stripname '' '.exe' "$file"
+	      file=$func_stripname_result
+	      stripped_ext=".exe"
+	    fi
+	    ;;
+	esac
+
+	# Do a test to see if this is really a libtool program.
+	case $host in
+	*cygwin* | *mingw*)
+	    if func_ltwrapper_executable_p "$file"; then
+	      func_ltwrapper_scriptname "$file"
+	      wrapper=$func_ltwrapper_scriptname_result
+	    else
+	      func_stripname '' '.exe' "$file"
+	      wrapper=$func_stripname_result
+	    fi
+	    ;;
+	*)
+	    wrapper=$file
+	    ;;
+	esac
+	if func_ltwrapper_script_p "$wrapper"; then
+	  notinst_deplibs=
+	  relink_command=
+
+	  func_source "$wrapper"
+
+	  # Check the variables that should have been set.
+	  test -z "$generated_by_libtool_version" && \
+	    func_fatal_error "invalid libtool wrapper script \`$wrapper'"
+
+	  finalize=yes
+	  for lib in $notinst_deplibs; do
+	    # Check to see that each library is installed.
+	    libdir=
+	    if test -f "$lib"; then
+	      func_source "$lib"
+	    fi
+	    libfile="$libdir/"`$ECHO "$lib" | $SED 's%^.*/%%g'` ### testsuite: skip nested quoting test
+	    if test -n "$libdir" && test ! -f "$libfile"; then
+	      func_warning "\`$lib' has not been installed in \`$libdir'"
+	      finalize=no
+	    fi
+	  done
+
+	  relink_command=
+	  func_source "$wrapper"
+
+	  outputname=
+	  if test "$fast_install" = no && test -n "$relink_command"; then
+	    $opt_dry_run || {
+	      if test "$finalize" = yes; then
+	        tmpdir=`func_mktempdir`
+		func_basename "$file$stripped_ext"
+		file="$func_basename_result"
+	        outputname="$tmpdir/$file"
+	        # Replace the output file specification.
+	        relink_command=`$ECHO "$relink_command" | $SED 's%@OUTPUT@%'"$outputname"'%g'`
+
+	        $opt_silent || {
+	          func_quote_for_expand "$relink_command"
+		  eval "func_echo $func_quote_for_expand_result"
+	        }
+	        if eval "$relink_command"; then :
+	          else
+		  func_error "error: relink \`$file' with the above command before installing it"
+		  $opt_dry_run || ${RM}r "$tmpdir"
+		  continue
+	        fi
+	        file="$outputname"
+	      else
+	        func_warning "cannot relink \`$file'"
+	      fi
+	    }
+	  else
+	    # Install the binary that we compiled earlier.
+	    file=`$ECHO "$file$stripped_ext" | $SED "s%\([^/]*\)$%$objdir/\1%"`
+	  fi
+	fi
+
+	# remove .exe since cygwin /usr/bin/install will append another
+	# one anyway
+	case $install_prog,$host in
+	*/usr/bin/install*,*cygwin*)
+	  case $file:$destfile in
+	  *.exe:*.exe)
+	    # this is ok
+	    ;;
+	  *.exe:*)
+	    destfile=$destfile.exe
+	    ;;
+	  *:*.exe)
+	    func_stripname '' '.exe' "$destfile"
+	    destfile=$func_stripname_result
+	    ;;
+	  esac
+	  ;;
+	esac
+	func_show_eval "$install_prog\$stripme \$file \$destfile" 'exit $?'
+	$opt_dry_run || if test -n "$outputname"; then
+	  ${RM}r "$tmpdir"
+	fi
+	;;
+      esac
+    done
+
+    for file in $staticlibs; do
+      func_basename "$file"
+      name="$func_basename_result"
+
+      # Set up the ranlib parameters.
+      oldlib="$destdir/$name"
+      func_to_tool_file "$oldlib" func_convert_file_msys_to_w32
+      tool_oldlib=$func_to_tool_file_result
+
+      func_show_eval "$install_prog \$file \$oldlib" 'exit $?'
+
+      if test -n "$stripme" && test -n "$old_striplib"; then
+	func_show_eval "$old_striplib $tool_oldlib" 'exit $?'
+      fi
+
+      # Do each command in the postinstall commands.
+      func_execute_cmds "$old_postinstall_cmds" 'exit $?'
+    done
+
+    test -n "$future_libdirs" && \
+      func_warning "remember to run \`$progname --finish$future_libdirs'"
+
+    if test -n "$current_libdirs"; then
+      # Maybe just do a dry run.
+      $opt_dry_run && current_libdirs=" -n$current_libdirs"
+      exec_cmd='$SHELL $progpath $preserve_args --finish$current_libdirs'
+    else
+      exit $EXIT_SUCCESS
+    fi
+}
+
+test "$opt_mode" = install && func_mode_install ${1+"$@"}
+
+
+# func_generate_dlsyms outputname originator pic_p
+# Extract symbols from dlprefiles and create ${outputname}S.o with
+# a dlpreopen symbol table.
+func_generate_dlsyms ()
+{
+    $opt_debug
+    my_outputname="$1"
+    my_originator="$2"
+    my_pic_p="${3-no}"
+    my_prefix=`$ECHO "$my_originator" | sed 's%[^a-zA-Z0-9]%_%g'`
+    my_dlsyms=
+
+    if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then
+      if test -n "$NM" && test -n "$global_symbol_pipe"; then
+	my_dlsyms="${my_outputname}S.c"
+      else
+	func_error "not configured to extract global symbols from dlpreopened files"
+      fi
+    fi
+
+    if test -n "$my_dlsyms"; then
+      case $my_dlsyms in
+      "") ;;
+      *.c)
+	# Discover the nlist of each of the dlfiles.
+	nlist="$output_objdir/${my_outputname}.nm"
+
+	func_show_eval "$RM $nlist ${nlist}S ${nlist}T"
+
+	# Parse the name list into a source file.
+	func_verbose "creating $output_objdir/$my_dlsyms"
+
+	$opt_dry_run || $ECHO > "$output_objdir/$my_dlsyms" "\
+/* $my_dlsyms - symbol resolution table for \`$my_outputname' dlsym emulation. */
+/* Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION */
+
+#ifdef __cplusplus
+extern \"C\" {
+#endif
+
+#if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 4)) || (__GNUC__ > 4))
+#pragma GCC diagnostic ignored \"-Wstrict-prototypes\"
+#endif
+
+/* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests.  */
+#if defined(_WIN32) || defined(__CYGWIN__) || defined(_WIN32_WCE)
+/* DATA imports from DLLs on WIN32 con't be const, because runtime
+   relocations are performed -- see ld's documentation on pseudo-relocs.  */
+# define LT_DLSYM_CONST
+#elif defined(__osf__)
+/* This system does not cope well with relocations in const data.  */
+# define LT_DLSYM_CONST
+#else
+# define LT_DLSYM_CONST const
+#endif
+
+/* External symbol declarations for the compiler. */\
+"
+
+	if test "$dlself" = yes; then
+	  func_verbose "generating symbol list for \`$output'"
+
+	  $opt_dry_run || echo ': @PROGRAM@ ' > "$nlist"
+
+	  # Add our own program objects to the symbol list.
+	  progfiles=`$ECHO "$objs$old_deplibs" | $SP2NL | $SED "$lo2o" | $NL2SP`
+	  for progfile in $progfiles; do
+	    func_to_tool_file "$progfile" func_convert_file_msys_to_w32
+	    func_verbose "extracting global C symbols from \`$func_to_tool_file_result'"
+	    $opt_dry_run || eval "$NM $func_to_tool_file_result | $global_symbol_pipe >> '$nlist'"
+	  done
+
+	  if test -n "$exclude_expsyms"; then
+	    $opt_dry_run || {
+	      eval '$EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T'
+	      eval '$MV "$nlist"T "$nlist"'
+	    }
+	  fi
+
+	  if test -n "$export_symbols_regex"; then
+	    $opt_dry_run || {
+	      eval '$EGREP -e "$export_symbols_regex" "$nlist" > "$nlist"T'
+	      eval '$MV "$nlist"T "$nlist"'
+	    }
+	  fi
+
+	  # Prepare the list of exported symbols
+	  if test -z "$export_symbols"; then
+	    export_symbols="$output_objdir/$outputname.exp"
+	    $opt_dry_run || {
+	      $RM $export_symbols
+	      eval "${SED} -n -e '/^: @PROGRAM@ $/d' -e 's/^.* \(.*\)$/\1/p' "'< "$nlist" > "$export_symbols"'
+	      case $host in
+	      *cygwin* | *mingw* | *cegcc* )
+                eval "echo EXPORTS "'> "$output_objdir/$outputname.def"'
+                eval 'cat "$export_symbols" >> "$output_objdir/$outputname.def"'
+	        ;;
+	      esac
+	    }
+	  else
+	    $opt_dry_run || {
+	      eval "${SED} -e 's/\([].[*^$]\)/\\\\\1/g' -e 's/^/ /' -e 's/$/$/'"' < "$export_symbols" > "$output_objdir/$outputname.exp"'
+	      eval '$GREP -f "$output_objdir/$outputname.exp" < "$nlist" > "$nlist"T'
+	      eval '$MV "$nlist"T "$nlist"'
+	      case $host in
+	        *cygwin* | *mingw* | *cegcc* )
+	          eval "echo EXPORTS "'> "$output_objdir/$outputname.def"'
+	          eval 'cat "$nlist" >> "$output_objdir/$outputname.def"'
+	          ;;
+	      esac
+	    }
+	  fi
+	fi
+
+	for dlprefile in $dlprefiles; do
+	  func_verbose "extracting global C symbols from \`$dlprefile'"
+	  func_basename "$dlprefile"
+	  name="$func_basename_result"
+          case $host in
+	    *cygwin* | *mingw* | *cegcc* )
+	      # if an import library, we need to obtain dlname
+	      if func_win32_import_lib_p "$dlprefile"; then
+	        func_tr_sh "$dlprefile"
+	        eval "curr_lafile=\$libfile_$func_tr_sh_result"
+	        dlprefile_dlbasename=""
+	        if test -n "$curr_lafile" && func_lalib_p "$curr_lafile"; then
+	          # Use subshell, to avoid clobbering current variable values
+	          dlprefile_dlname=`source "$curr_lafile" && echo "$dlname"`
+	          if test -n "$dlprefile_dlname" ; then
+	            func_basename "$dlprefile_dlname"
+	            dlprefile_dlbasename="$func_basename_result"
+	          else
+	            # no lafile. user explicitly requested -dlpreopen <import library>.
+	            $sharedlib_from_linklib_cmd "$dlprefile"
+	            dlprefile_dlbasename=$sharedlib_from_linklib_result
+	          fi
+	        fi
+	        $opt_dry_run || {
+	          if test -n "$dlprefile_dlbasename" ; then
+	            eval '$ECHO ": $dlprefile_dlbasename" >> "$nlist"'
+	          else
+	            func_warning "Could not compute DLL name from $name"
+	            eval '$ECHO ": $name " >> "$nlist"'
+	          fi
+	          func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32
+	          eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe |
+	            $SED -e '/I __imp/d' -e 's/I __nm_/D /;s/_nm__//' >> '$nlist'"
+	        }
+	      else # not an import lib
+	        $opt_dry_run || {
+	          eval '$ECHO ": $name " >> "$nlist"'
+	          func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32
+	          eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe >> '$nlist'"
+	        }
+	      fi
+	    ;;
+	    *)
+	      $opt_dry_run || {
+	        eval '$ECHO ": $name " >> "$nlist"'
+	        func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32
+	        eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe >> '$nlist'"
+	      }
+	    ;;
+          esac
+	done
+
+	$opt_dry_run || {
+	  # Make sure we have at least an empty file.
+	  test -f "$nlist" || : > "$nlist"
+
+	  if test -n "$exclude_expsyms"; then
+	    $EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T
+	    $MV "$nlist"T "$nlist"
+	  fi
+
+	  # Try sorting and uniquifying the output.
+	  if $GREP -v "^: " < "$nlist" |
+	      if sort -k 3 </dev/null >/dev/null 2>&1; then
+		sort -k 3
+	      else
+		sort +2
+	      fi |
+	      uniq > "$nlist"S; then
+	    :
+	  else
+	    $GREP -v "^: " < "$nlist" > "$nlist"S
+	  fi
+
+	  if test -f "$nlist"S; then
+	    eval "$global_symbol_to_cdecl"' < "$nlist"S >> "$output_objdir/$my_dlsyms"'
+	  else
+	    echo '/* NONE */' >> "$output_objdir/$my_dlsyms"
+	  fi
+
+	  echo >> "$output_objdir/$my_dlsyms" "\
+
+/* The mapping between symbol names and symbols.  */
+typedef struct {
+  const char *name;
+  void *address;
+} lt_dlsymlist;
+extern LT_DLSYM_CONST lt_dlsymlist
+lt_${my_prefix}_LTX_preloaded_symbols[];
+LT_DLSYM_CONST lt_dlsymlist
+lt_${my_prefix}_LTX_preloaded_symbols[] =
+{\
+  { \"$my_originator\", (void *) 0 },"
+
+	  case $need_lib_prefix in
+	  no)
+	    eval "$global_symbol_to_c_name_address" < "$nlist" >> "$output_objdir/$my_dlsyms"
+	    ;;
+	  *)
+	    eval "$global_symbol_to_c_name_address_lib_prefix" < "$nlist" >> "$output_objdir/$my_dlsyms"
+	    ;;
+	  esac
+	  echo >> "$output_objdir/$my_dlsyms" "\
+  {0, (void *) 0}
+};
+
+/* This works around a problem in FreeBSD linker */
+#ifdef FREEBSD_WORKAROUND
+static const void *lt_preloaded_setup() {
+  return lt_${my_prefix}_LTX_preloaded_symbols;
+}
+#endif
+
+#ifdef __cplusplus
+}
+#endif\
+"
+	} # !$opt_dry_run
+
+	pic_flag_for_symtable=
+	case "$compile_command " in
+	*" -static "*) ;;
+	*)
+	  case $host in
+	  # compiling the symbol table file with pic_flag works around
+	  # a FreeBSD bug that causes programs to crash when -lm is
+	  # linked before any other PIC object.  But we must not use
+	  # pic_flag when linking with -static.  The problem exists in
+	  # FreeBSD 2.2.6 and is fixed in FreeBSD 3.1.
+	  *-*-freebsd2.*|*-*-freebsd3.0*|*-*-freebsdelf3.0*)
+	    pic_flag_for_symtable=" $pic_flag -DFREEBSD_WORKAROUND" ;;
+	  *-*-hpux*)
+	    pic_flag_for_symtable=" $pic_flag"  ;;
+	  *)
+	    if test "X$my_pic_p" != Xno; then
+	      pic_flag_for_symtable=" $pic_flag"
+	    fi
+	    ;;
+	  esac
+	  ;;
+	esac
+	symtab_cflags=
+	for arg in $LTCFLAGS; do
+	  case $arg in
+	  -pie | -fpie | -fPIE) ;;
+	  *) func_append symtab_cflags " $arg" ;;
+	  esac
+	done
+
+	# Now compile the dynamic symbol file.
+	func_show_eval '(cd $output_objdir && $LTCC$symtab_cflags -c$no_builtin_flag$pic_flag_for_symtable "$my_dlsyms")' 'exit $?'
+
+	# Clean up the generated files.
+	func_show_eval '$RM "$output_objdir/$my_dlsyms" "$nlist" "${nlist}S" "${nlist}T"'
+
+	# Transform the symbol file into the correct name.
+	symfileobj="$output_objdir/${my_outputname}S.$objext"
+	case $host in
+	*cygwin* | *mingw* | *cegcc* )
+	  if test -f "$output_objdir/$my_outputname.def"; then
+	    compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"`
+	    finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"`
+	  else
+	    compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$symfileobj%"`
+	    finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$symfileobj%"`
+	  fi
+	  ;;
+	*)
+	  compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$symfileobj%"`
+	  finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$symfileobj%"`
+	  ;;
+	esac
+	;;
+      *)
+	func_fatal_error "unknown suffix for \`$my_dlsyms'"
+	;;
+      esac
+    else
+      # We keep going just in case the user didn't refer to
+      # lt_preloaded_symbols.  The linker will fail if global_symbol_pipe
+      # really was required.
+
+      # Nullify the symbol file.
+      compile_command=`$ECHO "$compile_command" | $SED "s% @SYMFILE@%%"`
+      finalize_command=`$ECHO "$finalize_command" | $SED "s% @SYMFILE@%%"`
+    fi
+}
+
+# func_win32_libid arg
+# return the library type of file 'arg'
+#
+# Need a lot of goo to handle *both* DLLs and import libs
+# Has to be a shell function in order to 'eat' the argument
+# that is supplied when $file_magic_command is called.
+# Despite the name, also deal with 64 bit binaries.
+func_win32_libid ()
+{
+  $opt_debug
+  win32_libid_type="unknown"
+  win32_fileres=`file -L $1 2>/dev/null`
+  case $win32_fileres in
+  *ar\ archive\ import\ library*) # definitely import
+    win32_libid_type="x86 archive import"
+    ;;
+  *ar\ archive*) # could be an import, or static
+    # Keep the egrep pattern in sync with the one in _LT_CHECK_MAGIC_METHOD.
+    if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null |
+       $EGREP 'file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' >/dev/null; then
+      func_to_tool_file "$1" func_convert_file_msys_to_w32
+      win32_nmres=`eval $NM -f posix -A \"$func_to_tool_file_result\" |
+	$SED -n -e '
+	    1,100{
+		/ I /{
+		    s,.*,import,
+		    p
+		    q
+		}
+	    }'`
+      case $win32_nmres in
+      import*)  win32_libid_type="x86 archive import";;
+      *)        win32_libid_type="x86 archive static";;
+      esac
+    fi
+    ;;
+  *DLL*)
+    win32_libid_type="x86 DLL"
+    ;;
+  *executable*) # but shell scripts are "executable" too...
+    case $win32_fileres in
+    *MS\ Windows\ PE\ Intel*)
+      win32_libid_type="x86 DLL"
+      ;;
+    esac
+    ;;
+  esac
+  $ECHO "$win32_libid_type"
+}
+
+# func_cygming_dll_for_implib ARG
+#
+# Platform-specific function to extract the
+# name of the DLL associated with the specified
+# import library ARG.
+# Invoked by eval'ing the libtool variable
+#    $sharedlib_from_linklib_cmd
+# Result is available in the variable
+#    $sharedlib_from_linklib_result
+func_cygming_dll_for_implib ()
+{
+  $opt_debug
+  sharedlib_from_linklib_result=`$DLLTOOL --identify-strict --identify "$1"`
+}
+
+# func_cygming_dll_for_implib_fallback_core SECTION_NAME LIBNAMEs
+#
+# The is the core of a fallback implementation of a
+# platform-specific function to extract the name of the
+# DLL associated with the specified import library LIBNAME.
+#
+# SECTION_NAME is either .idata$6 or .idata$7, depending
+# on the platform and compiler that created the implib.
+#
+# Echos the name of the DLL associated with the
+# specified import library.
+func_cygming_dll_for_implib_fallback_core ()
+{
+  $opt_debug
+  match_literal=`$ECHO "$1" | $SED "$sed_make_literal_regex"`
+  $OBJDUMP -s --section "$1" "$2" 2>/dev/null |
+    $SED '/^Contents of section '"$match_literal"':/{
+      # Place marker at beginning of archive member dllname section
+      s/.*/====MARK====/
+      p
+      d
+    }
+    # These lines can sometimes be longer than 43 characters, but
+    # are always uninteresting
+    /:[	 ]*file format pe[i]\{,1\}-/d
+    /^In archive [^:]*:/d
+    # Ensure marker is printed
+    /^====MARK====/p
+    # Remove all lines with less than 43 characters
+    /^.\{43\}/!d
+    # From remaining lines, remove first 43 characters
+    s/^.\{43\}//' |
+    $SED -n '
+      # Join marker and all lines until next marker into a single line
+      /^====MARK====/ b para
+      H
+      $ b para
+      b
+      :para
+      x
+      s/\n//g
+      # Remove the marker
+      s/^====MARK====//
+      # Remove trailing dots and whitespace
+      s/[\. \t]*$//
+      # Print
+      /./p' |
+    # we now have a list, one entry per line, of the stringified
+    # contents of the appropriate section of all members of the
+    # archive which possess that section. Heuristic: eliminate
+    # all those which have a first or second character that is
+    # a '.' (that is, objdump's representation of an unprintable
+    # character.) This should work for all archives with less than
+    # 0x302f exports -- but will fail for DLLs whose name actually
+    # begins with a literal '.' or a single character followed by
+    # a '.'.
+    #
+    # Of those that remain, print the first one.
+    $SED -e '/^\./d;/^.\./d;q'
+}
+
+# func_cygming_gnu_implib_p ARG
+# This predicate returns with zero status (TRUE) if
+# ARG is a GNU/binutils-style import library. Returns
+# with nonzero status (FALSE) otherwise.
+func_cygming_gnu_implib_p ()
+{
+  $opt_debug
+  func_to_tool_file "$1" func_convert_file_msys_to_w32
+  func_cygming_gnu_implib_tmp=`$NM "$func_to_tool_file_result" | eval "$global_symbol_pipe" | $EGREP ' (_head_[A-Za-z0-9_]+_[ad]l*|[A-Za-z0-9_]+_[ad]l*_iname)$'`
+  test -n "$func_cygming_gnu_implib_tmp"
+}
+
+# func_cygming_ms_implib_p ARG
+# This predicate returns with zero status (TRUE) if
+# ARG is an MS-style import library. Returns
+# with nonzero status (FALSE) otherwise.
+func_cygming_ms_implib_p ()
+{
+  $opt_debug
+  func_to_tool_file "$1" func_convert_file_msys_to_w32
+  func_cygming_ms_implib_tmp=`$NM "$func_to_tool_file_result" | eval "$global_symbol_pipe" | $GREP '_NULL_IMPORT_DESCRIPTOR'`
+  test -n "$func_cygming_ms_implib_tmp"
+}
+
+# func_cygming_dll_for_implib_fallback ARG
+# Platform-specific function to extract the
+# name of the DLL associated with the specified
+# import library ARG.
+#
+# This fallback implementation is for use when $DLLTOOL
+# does not support the --identify-strict option.
+# Invoked by eval'ing the libtool variable
+#    $sharedlib_from_linklib_cmd
+# Result is available in the variable
+#    $sharedlib_from_linklib_result
+func_cygming_dll_for_implib_fallback ()
+{
+  $opt_debug
+  if func_cygming_gnu_implib_p "$1" ; then
+    # binutils import library
+    sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$7' "$1"`
+  elif func_cygming_ms_implib_p "$1" ; then
+    # ms-generated import library
+    sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$6' "$1"`
+  else
+    # unknown
+    sharedlib_from_linklib_result=""
+  fi
+}
+
+
+# func_extract_an_archive dir oldlib
+func_extract_an_archive ()
+{
+    $opt_debug
+    f_ex_an_ar_dir="$1"; shift
+    f_ex_an_ar_oldlib="$1"
+    if test "$lock_old_archive_extraction" = yes; then
+      lockfile=$f_ex_an_ar_oldlib.lock
+      until $opt_dry_run || ln "$progpath" "$lockfile" 2>/dev/null; do
+	func_echo "Waiting for $lockfile to be removed"
+	sleep 2
+      done
+    fi
+    func_show_eval "(cd \$f_ex_an_ar_dir && $AR x \"\$f_ex_an_ar_oldlib\")" \
+		   'stat=$?; rm -f "$lockfile"; exit $stat'
+    if test "$lock_old_archive_extraction" = yes; then
+      $opt_dry_run || rm -f "$lockfile"
+    fi
+    if ($AR t "$f_ex_an_ar_oldlib" | sort | sort -uc >/dev/null 2>&1); then
+     :
+    else
+      func_fatal_error "object name conflicts in archive: $f_ex_an_ar_dir/$f_ex_an_ar_oldlib"
+    fi
+}
+
+
+# func_extract_archives gentop oldlib ...
+func_extract_archives ()
+{
+    $opt_debug
+    my_gentop="$1"; shift
+    my_oldlibs=${1+"$@"}
+    my_oldobjs=""
+    my_xlib=""
+    my_xabs=""
+    my_xdir=""
+
+    for my_xlib in $my_oldlibs; do
+      # Extract the objects.
+      case $my_xlib in
+	[\\/]* | [A-Za-z]:[\\/]*) my_xabs="$my_xlib" ;;
+	*) my_xabs=`pwd`"/$my_xlib" ;;
+      esac
+      func_basename "$my_xlib"
+      my_xlib="$func_basename_result"
+      my_xlib_u=$my_xlib
+      while :; do
+        case " $extracted_archives " in
+	*" $my_xlib_u "*)
+	  func_arith $extracted_serial + 1
+	  extracted_serial=$func_arith_result
+	  my_xlib_u=lt$extracted_serial-$my_xlib ;;
+	*) break ;;
+	esac
+      done
+      extracted_archives="$extracted_archives $my_xlib_u"
+      my_xdir="$my_gentop/$my_xlib_u"
+
+      func_mkdir_p "$my_xdir"
+
+      case $host in
+      *-darwin*)
+	func_verbose "Extracting $my_xabs"
+	# Do not bother doing anything if just a dry run
+	$opt_dry_run || {
+	  darwin_orig_dir=`pwd`
+	  cd $my_xdir || exit $?
+	  darwin_archive=$my_xabs
+	  darwin_curdir=`pwd`
+	  darwin_base_archive=`basename "$darwin_archive"`
+	  darwin_arches=`$LIPO -info "$darwin_archive" 2>/dev/null | $GREP Architectures 2>/dev/null || true`
+	  if test -n "$darwin_arches"; then
+	    darwin_arches=`$ECHO "$darwin_arches" | $SED -e 's/.*are://'`
+	    darwin_arch=
+	    func_verbose "$darwin_base_archive has multiple architectures $darwin_arches"
+	    for darwin_arch in  $darwin_arches ; do
+	      func_mkdir_p "unfat-$$/${darwin_base_archive}-${darwin_arch}"
+	      $LIPO -thin $darwin_arch -output "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}" "${darwin_archive}"
+	      cd "unfat-$$/${darwin_base_archive}-${darwin_arch}"
+	      func_extract_an_archive "`pwd`" "${darwin_base_archive}"
+	      cd "$darwin_curdir"
+	      $RM "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}"
+	    done # $darwin_arches
+            ## Okay now we've a bunch of thin objects, gotta fatten them up :)
+	    darwin_filelist=`find unfat-$$ -type f -name \*.o -print -o -name \*.lo -print | $SED -e "$basename" | sort -u`
+	    darwin_file=
+	    darwin_files=
+	    for darwin_file in $darwin_filelist; do
+	      darwin_files=`find unfat-$$ -name $darwin_file -print | sort | $NL2SP`
+	      $LIPO -create -output "$darwin_file" $darwin_files
+	    done # $darwin_filelist
+	    $RM -rf unfat-$$
+	    cd "$darwin_orig_dir"
+	  else
+	    cd $darwin_orig_dir
+	    func_extract_an_archive "$my_xdir" "$my_xabs"
+	  fi # $darwin_arches
+	} # !$opt_dry_run
+	;;
+      *)
+        func_extract_an_archive "$my_xdir" "$my_xabs"
+	;;
+      esac
+      my_oldobjs="$my_oldobjs "`find $my_xdir -name \*.$objext -print -o -name \*.lo -print | sort | $NL2SP`
+    done
+
+    func_extract_archives_result="$my_oldobjs"
+}
+
+
+# func_emit_wrapper [arg=no]
+#
+# Emit a libtool wrapper script on stdout.
+# Don't directly open a file because we may want to
+# incorporate the script contents within a cygwin/mingw
+# wrapper executable.  Must ONLY be called from within
+# func_mode_link because it depends on a number of variables
+# set therein.
+#
+# ARG is the value that the WRAPPER_SCRIPT_BELONGS_IN_OBJDIR
+# variable will take.  If 'yes', then the emitted script
+# will assume that the directory in which it is stored is
+# the $objdir directory.  This is a cygwin/mingw-specific
+# behavior.
+func_emit_wrapper ()
+{
+	func_emit_wrapper_arg1=${1-no}
+
+	$ECHO "\
+#! $SHELL
+
+# $output - temporary wrapper script for $objdir/$outputname
+# Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION
+#
+# The $output program cannot be directly executed until all the libtool
+# libraries that it depends on are installed.
+#
+# This wrapper script should never be moved out of the build directory.
+# If it is, it will not operate correctly.
+
+# Sed substitution that helps us do robust quoting.  It backslashifies
+# metacharacters that are still active within double-quoted strings.
+sed_quote_subst='$sed_quote_subst'
+
+# Be Bourne compatible
+if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then
+  emulate sh
+  NULLCMD=:
+  # Zsh 3.x and 4.x performs word splitting on \${1+\"\$@\"}, which
+  # is contrary to our usage.  Disable this feature.
+  alias -g '\${1+\"\$@\"}'='\"\$@\"'
+  setopt NO_GLOB_SUBST
+else
+  case \`(set -o) 2>/dev/null\` in *posix*) set -o posix;; esac
+fi
+BIN_SH=xpg4; export BIN_SH # for Tru64
+DUALCASE=1; export DUALCASE # for MKS sh
+
+# The HP-UX ksh and POSIX shell print the target directory to stdout
+# if CDPATH is set.
+(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
+
+relink_command=\"$relink_command\"
+
+# This environment variable determines our operation mode.
+if test \"\$libtool_install_magic\" = \"$magic\"; then
+  # install mode needs the following variables:
+  generated_by_libtool_version='$macro_version'
+  notinst_deplibs='$notinst_deplibs'
+else
+  # When we are sourced in execute mode, \$file and \$ECHO are already set.
+  if test \"\$libtool_execute_magic\" != \"$magic\"; then
+    file=\"\$0\""
+
+    qECHO=`$ECHO "$ECHO" | $SED "$sed_quote_subst"`
+    $ECHO "\
+
+# A function that is used when there is no print builtin or printf.
+func_fallback_echo ()
+{
+  eval 'cat <<_LTECHO_EOF
+\$1
+_LTECHO_EOF'
+}
+    ECHO=\"$qECHO\"
+  fi
+
+# Very basic option parsing. These options are (a) specific to
+# the libtool wrapper, (b) are identical between the wrapper
+# /script/ and the wrapper /executable/ which is used only on
+# windows platforms, and (c) all begin with the string "--lt-"
+# (application programs are unlikely to have options which match
+# this pattern).
+#
+# There are only two supported options: --lt-debug and
+# --lt-dump-script. There is, deliberately, no --lt-help.
+#
+# The first argument to this parsing function should be the
+# script's $0 value, followed by "$@".
+lt_option_debug=
+func_parse_lt_options ()
+{
+  lt_script_arg0=\$0
+  shift
+  for lt_opt
+  do
+    case \"\$lt_opt\" in
+    --lt-debug) lt_option_debug=1 ;;
+    --lt-dump-script)
+        lt_dump_D=\`\$ECHO \"X\$lt_script_arg0\" | $SED -e 's/^X//' -e 's%/[^/]*$%%'\`
+        test \"X\$lt_dump_D\" = \"X\$lt_script_arg0\" && lt_dump_D=.
+        lt_dump_F=\`\$ECHO \"X\$lt_script_arg0\" | $SED -e 's/^X//' -e 's%^.*/%%'\`
+        cat \"\$lt_dump_D/\$lt_dump_F\"
+        exit 0
+      ;;
+    --lt-*)
+        \$ECHO \"Unrecognized --lt- option: '\$lt_opt'\" 1>&2
+        exit 1
+      ;;
+    esac
+  done
+
+  # Print the debug banner immediately:
+  if test -n \"\$lt_option_debug\"; then
+    echo \"${outputname}:${output}:\${LINENO}: libtool wrapper (GNU $PACKAGE$TIMESTAMP) $VERSION\" 1>&2
+  fi
+}
+
+# Used when --lt-debug. Prints its arguments to stdout
+# (redirection is the responsibility of the caller)
+func_lt_dump_args ()
+{
+  lt_dump_args_N=1;
+  for lt_arg
+  do
+    \$ECHO \"${outputname}:${output}:\${LINENO}: newargv[\$lt_dump_args_N]: \$lt_arg\"
+    lt_dump_args_N=\`expr \$lt_dump_args_N + 1\`
+  done
+}
+
+# Core function for launching the target application
+func_exec_program_core ()
+{
+"
+  case $host in
+  # Backslashes separate directories on plain windows
+  *-*-mingw | *-*-os2* | *-cegcc*)
+    $ECHO "\
+      if test -n \"\$lt_option_debug\"; then
+        \$ECHO \"${outputname}:${output}:\${LINENO}: newargv[0]: \$progdir\\\\\$program\" 1>&2
+        func_lt_dump_args \${1+\"\$@\"} 1>&2
+      fi
+      exec \"\$progdir\\\\\$program\" \${1+\"\$@\"}
+"
+    ;;
+
+  *)
+    $ECHO "\
+      if test -n \"\$lt_option_debug\"; then
+        \$ECHO \"${outputname}:${output}:\${LINENO}: newargv[0]: \$progdir/\$program\" 1>&2
+        func_lt_dump_args \${1+\"\$@\"} 1>&2
+      fi
+      exec \"\$progdir/\$program\" \${1+\"\$@\"}
+"
+    ;;
+  esac
+  $ECHO "\
+      \$ECHO \"\$0: cannot exec \$program \$*\" 1>&2
+      exit 1
+}
+
+# A function to encapsulate launching the target application
+# Strips options in the --lt-* namespace from \$@ and
+# launches target application with the remaining arguments.
+func_exec_program ()
+{
+  case \" \$* \" in
+  *\\ --lt-*)
+    for lt_wr_arg
+    do
+      case \$lt_wr_arg in
+      --lt-*) ;;
+      *) set x \"\$@\" \"\$lt_wr_arg\"; shift;;
+      esac
+      shift
+    done ;;
+  esac
+  func_exec_program_core \${1+\"\$@\"}
+}
+
+  # Parse options
+  func_parse_lt_options \"\$0\" \${1+\"\$@\"}
+
+  # Find the directory that this script lives in.
+  thisdir=\`\$ECHO \"\$file\" | $SED 's%/[^/]*$%%'\`
+  test \"x\$thisdir\" = \"x\$file\" && thisdir=.
+
+  # Follow symbolic links until we get to the real thisdir.
+  file=\`ls -ld \"\$file\" | $SED -n 's/.*-> //p'\`
+  while test -n \"\$file\"; do
+    destdir=\`\$ECHO \"\$file\" | $SED 's%/[^/]*\$%%'\`
+
+    # If there was a directory component, then change thisdir.
+    if test \"x\$destdir\" != \"x\$file\"; then
+      case \"\$destdir\" in
+      [\\\\/]* | [A-Za-z]:[\\\\/]*) thisdir=\"\$destdir\" ;;
+      *) thisdir=\"\$thisdir/\$destdir\" ;;
+      esac
+    fi
+
+    file=\`\$ECHO \"\$file\" | $SED 's%^.*/%%'\`
+    file=\`ls -ld \"\$thisdir/\$file\" | $SED -n 's/.*-> //p'\`
+  done
+
+  # Usually 'no', except on cygwin/mingw when embedded into
+  # the cwrapper.
+  WRAPPER_SCRIPT_BELONGS_IN_OBJDIR=$func_emit_wrapper_arg1
+  if test \"\$WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\" = \"yes\"; then
+    # special case for '.'
+    if test \"\$thisdir\" = \".\"; then
+      thisdir=\`pwd\`
+    fi
+    # remove .libs from thisdir
+    case \"\$thisdir\" in
+    *[\\\\/]$objdir ) thisdir=\`\$ECHO \"\$thisdir\" | $SED 's%[\\\\/][^\\\\/]*$%%'\` ;;
+    $objdir )   thisdir=. ;;
+    esac
+  fi
+
+  # Try to get the absolute directory name.
+  absdir=\`cd \"\$thisdir\" && pwd\`
+  test -n \"\$absdir\" && thisdir=\"\$absdir\"
+"
+
+	if test "$fast_install" = yes; then
+	  $ECHO "\
+  program=lt-'$outputname'$exeext
+  progdir=\"\$thisdir/$objdir\"
+
+  if test ! -f \"\$progdir/\$program\" ||
+     { file=\`ls -1dt \"\$progdir/\$program\" \"\$progdir/../\$program\" 2>/dev/null | ${SED} 1q\`; \\
+       test \"X\$file\" != \"X\$progdir/\$program\"; }; then
+
+    file=\"\$\$-\$program\"
+
+    if test ! -d \"\$progdir\"; then
+      $MKDIR \"\$progdir\"
+    else
+      $RM \"\$progdir/\$file\"
+    fi"
+
+	  $ECHO "\
+
+    # relink executable if necessary
+    if test -n \"\$relink_command\"; then
+      if relink_command_output=\`eval \$relink_command 2>&1\`; then :
+      else
+	$ECHO \"\$relink_command_output\" >&2
+	$RM \"\$progdir/\$file\"
+	exit 1
+      fi
+    fi
+
+    $MV \"\$progdir/\$file\" \"\$progdir/\$program\" 2>/dev/null ||
+    { $RM \"\$progdir/\$program\";
+      $MV \"\$progdir/\$file\" \"\$progdir/\$program\"; }
+    $RM \"\$progdir/\$file\"
+  fi"
+	else
+	  $ECHO "\
+  program='$outputname'
+  progdir=\"\$thisdir/$objdir\"
+"
+	fi
+
+	$ECHO "\
+
+  if test -f \"\$progdir/\$program\"; then"
+
+	# fixup the dll searchpath if we need to.
+	#
+	# Fix the DLL searchpath if we need to.  Do this before prepending
+	# to shlibpath, because on Windows, both are PATH and uninstalled
+	# libraries must come first.
+	if test -n "$dllsearchpath"; then
+	  $ECHO "\
+    # Add the dll search path components to the executable PATH
+    PATH=$dllsearchpath:\$PATH
+"
+	fi
+
+	# Export our shlibpath_var if we have one.
+	if test "$shlibpath_overrides_runpath" = yes && test -n "$shlibpath_var" && test -n "$temp_rpath"; then
+	  $ECHO "\
+    # Add our own library path to $shlibpath_var
+    $shlibpath_var=\"$temp_rpath\$$shlibpath_var\"
+
+    # Some systems cannot cope with colon-terminated $shlibpath_var
+    # The second colon is a workaround for a bug in BeOS R4 sed
+    $shlibpath_var=\`\$ECHO \"\$$shlibpath_var\" | $SED 's/::*\$//'\`
+
+    export $shlibpath_var
+"
+	fi
+
+	$ECHO "\
+    if test \"\$libtool_execute_magic\" != \"$magic\"; then
+      # Run the actual program with our arguments.
+      func_exec_program \${1+\"\$@\"}
+    fi
+  else
+    # The program doesn't exist.
+    \$ECHO \"\$0: error: \\\`\$progdir/\$program' does not exist\" 1>&2
+    \$ECHO \"This script is just a wrapper for \$program.\" 1>&2
+    \$ECHO \"See the $PACKAGE documentation for more information.\" 1>&2
+    exit 1
+  fi
+fi\
+"
+}
+
+
+# func_emit_cwrapperexe_src
+# emit the source code for a wrapper executable on stdout
+# Must ONLY be called from within func_mode_link because
+# it depends on a number of variable set therein.
+func_emit_cwrapperexe_src ()
+{
+	cat <<EOF
+
+/* $cwrappersource - temporary wrapper executable for $objdir/$outputname
+   Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION
+
+   The $output program cannot be directly executed until all the libtool
+   libraries that it depends on are installed.
+
+   This wrapper executable should never be moved out of the build directory.
+   If it is, it will not operate correctly.
+*/
+EOF
+	    cat <<"EOF"
+#ifdef _MSC_VER
+# define _CRT_SECURE_NO_DEPRECATE 1
+#endif
+#include <stdio.h>
+#include <stdlib.h>
+#ifdef _MSC_VER
+# include <direct.h>
+# include <process.h>
+# include <io.h>
+#else
+# include <unistd.h>
+# include <stdint.h>
+# ifdef __CYGWIN__
+#  include <io.h>
+# endif
+#endif
+#include <malloc.h>
+#include <stdarg.h>
+#include <assert.h>
+#include <string.h>
+#include <ctype.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <sys/stat.h>
+
+/* declarations of non-ANSI functions */
+#if defined(__MINGW32__)
+# ifdef __STRICT_ANSI__
+int _putenv (const char *);
+# endif
+#elif defined(__CYGWIN__)
+# ifdef __STRICT_ANSI__
+char *realpath (const char *, char *);
+int putenv (char *);
+int setenv (const char *, const char *, int);
+# endif
+/* #elif defined (other platforms) ... */
+#endif
+
+/* portability defines, excluding path handling macros */
+#if defined(_MSC_VER)
+# define setmode _setmode
+# define stat    _stat
+# define chmod   _chmod
+# define getcwd  _getcwd
+# define putenv  _putenv
+# define S_IXUSR _S_IEXEC
+# ifndef _INTPTR_T_DEFINED
+#  define _INTPTR_T_DEFINED
+#  define intptr_t int
+# endif
+#elif defined(__MINGW32__)
+# define setmode _setmode
+# define stat    _stat
+# define chmod   _chmod
+# define getcwd  _getcwd
+# define putenv  _putenv
+#elif defined(__CYGWIN__)
+# define HAVE_SETENV
+# define FOPEN_WB "wb"
+/* #elif defined (other platforms) ... */
+#endif
+
+#if defined(PATH_MAX)
+# define LT_PATHMAX PATH_MAX
+#elif defined(MAXPATHLEN)
+# define LT_PATHMAX MAXPATHLEN
+#else
+# define LT_PATHMAX 1024
+#endif
+
+#ifndef S_IXOTH
+# define S_IXOTH 0
+#endif
+#ifndef S_IXGRP
+# define S_IXGRP 0
+#endif
+
+/* path handling portability macros */
+#ifndef DIR_SEPARATOR
+# define DIR_SEPARATOR '/'
+# define PATH_SEPARATOR ':'
+#endif
+
+#if defined (_WIN32) || defined (__MSDOS__) || defined (__DJGPP__) || \
+  defined (__OS2__)
+# define HAVE_DOS_BASED_FILE_SYSTEM
+# define FOPEN_WB "wb"
+# ifndef DIR_SEPARATOR_2
+#  define DIR_SEPARATOR_2 '\\'
+# endif
+# ifndef PATH_SEPARATOR_2
+#  define PATH_SEPARATOR_2 ';'
+# endif
+#endif
+
+#ifndef DIR_SEPARATOR_2
+# define IS_DIR_SEPARATOR(ch) ((ch) == DIR_SEPARATOR)
+#else /* DIR_SEPARATOR_2 */
+# define IS_DIR_SEPARATOR(ch) \
+	(((ch) == DIR_SEPARATOR) || ((ch) == DIR_SEPARATOR_2))
+#endif /* DIR_SEPARATOR_2 */
+
+#ifndef PATH_SEPARATOR_2
+# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR)
+#else /* PATH_SEPARATOR_2 */
+# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR_2)
+#endif /* PATH_SEPARATOR_2 */
+
+#ifndef FOPEN_WB
+# define FOPEN_WB "w"
+#endif
+#ifndef _O_BINARY
+# define _O_BINARY 0
+#endif
+
+#define XMALLOC(type, num)      ((type *) xmalloc ((num) * sizeof(type)))
+#define XFREE(stale) do { \
+  if (stale) { free ((void *) stale); stale = 0; } \
+} while (0)
+
+#if defined(LT_DEBUGWRAPPER)
+static int lt_debug = 1;
+#else
+static int lt_debug = 0;
+#endif
+
+const char *program_name = "libtool-wrapper"; /* in case xstrdup fails */
+
+void *xmalloc (size_t num);
+char *xstrdup (const char *string);
+const char *base_name (const char *name);
+char *find_executable (const char *wrapper);
+char *chase_symlinks (const char *pathspec);
+int make_executable (const char *path);
+int check_executable (const char *path);
+char *strendzap (char *str, const char *pat);
+void lt_debugprintf (const char *file, int line, const char *fmt, ...);
+void lt_fatal (const char *file, int line, const char *message, ...);
+static const char *nonnull (const char *s);
+static const char *nonempty (const char *s);
+void lt_setenv (const char *name, const char *value);
+char *lt_extend_str (const char *orig_value, const char *add, int to_end);
+void lt_update_exe_path (const char *name, const char *value);
+void lt_update_lib_path (const char *name, const char *value);
+char **prepare_spawn (char **argv);
+void lt_dump_script (FILE *f);
+EOF
+
+	    cat <<EOF
+volatile const char * MAGIC_EXE = "$magic_exe";
+const char * LIB_PATH_VARNAME = "$shlibpath_var";
+EOF
+
+	    if test "$shlibpath_overrides_runpath" = yes && test -n "$shlibpath_var" && test -n "$temp_rpath"; then
+              func_to_host_path "$temp_rpath"
+	      cat <<EOF
+const char * LIB_PATH_VALUE   = "$func_to_host_path_result";
+EOF
+	    else
+	      cat <<"EOF"
+const char * LIB_PATH_VALUE   = "";
+EOF
+	    fi
+
+	    if test -n "$dllsearchpath"; then
+              func_to_host_path "$dllsearchpath:"
+	      cat <<EOF
+const char * EXE_PATH_VARNAME = "PATH";
+const char * EXE_PATH_VALUE   = "$func_to_host_path_result";
+EOF
+	    else
+	      cat <<"EOF"
+const char * EXE_PATH_VARNAME = "";
+const char * EXE_PATH_VALUE   = "";
+EOF
+	    fi
+
+	    if test "$fast_install" = yes; then
+	      cat <<EOF
+const char * TARGET_PROGRAM_NAME = "lt-$outputname"; /* hopefully, no .exe */
+EOF
+	    else
+	      cat <<EOF
+const char * TARGET_PROGRAM_NAME = "$outputname"; /* hopefully, no .exe */
+EOF
+	    fi
+
+
+	    cat <<"EOF"
+
+#define LTWRAPPER_OPTION_PREFIX         "--lt-"
+
+static const char *ltwrapper_option_prefix = LTWRAPPER_OPTION_PREFIX;
+static const char *dumpscript_opt       = LTWRAPPER_OPTION_PREFIX "dump-script";
+static const char *debug_opt            = LTWRAPPER_OPTION_PREFIX "debug";
+
+int
+main (int argc, char *argv[])
+{
+  char **newargz;
+  int  newargc;
+  char *tmp_pathspec;
+  char *actual_cwrapper_path;
+  char *actual_cwrapper_name;
+  char *target_name;
+  char *lt_argv_zero;
+  intptr_t rval = 127;
+
+  int i;
+
+  program_name = (char *) xstrdup (base_name (argv[0]));
+  newargz = XMALLOC (char *, argc + 1);
+
+  /* very simple arg parsing; don't want to rely on getopt
+   * also, copy all non cwrapper options to newargz, except
+   * argz[0], which is handled differently
+   */
+  newargc=0;
+  for (i = 1; i < argc; i++)
+    {
+      if (strcmp (argv[i], dumpscript_opt) == 0)
+	{
+EOF
+	    case "$host" in
+	      *mingw* | *cygwin* )
+		# make stdout use "unix" line endings
+		echo "          setmode(1,_O_BINARY);"
+		;;
+	      esac
+
+	    cat <<"EOF"
+	  lt_dump_script (stdout);
+	  return 0;
+	}
+      if (strcmp (argv[i], debug_opt) == 0)
+	{
+          lt_debug = 1;
+          continue;
+	}
+      if (strcmp (argv[i], ltwrapper_option_prefix) == 0)
+        {
+          /* however, if there is an option in the LTWRAPPER_OPTION_PREFIX
+             namespace, but it is not one of the ones we know about and
+             have already dealt with, above (inluding dump-script), then
+             report an error. Otherwise, targets might begin to believe
+             they are allowed to use options in the LTWRAPPER_OPTION_PREFIX
+             namespace. The first time any user complains about this, we'll
+             need to make LTWRAPPER_OPTION_PREFIX a configure-time option
+             or a configure.ac-settable value.
+           */
+          lt_fatal (__FILE__, __LINE__,
+		    "unrecognized %s option: '%s'",
+                    ltwrapper_option_prefix, argv[i]);
+        }
+      /* otherwise ... */
+      newargz[++newargc] = xstrdup (argv[i]);
+    }
+  newargz[++newargc] = NULL;
+
+EOF
+	    cat <<EOF
+  /* The GNU banner must be the first non-error debug message */
+  lt_debugprintf (__FILE__, __LINE__, "libtool wrapper (GNU $PACKAGE$TIMESTAMP) $VERSION\n");
+EOF
+	    cat <<"EOF"
+  lt_debugprintf (__FILE__, __LINE__, "(main) argv[0]: %s\n", argv[0]);
+  lt_debugprintf (__FILE__, __LINE__, "(main) program_name: %s\n", program_name);
+
+  tmp_pathspec = find_executable (argv[0]);
+  if (tmp_pathspec == NULL)
+    lt_fatal (__FILE__, __LINE__, "couldn't find %s", argv[0]);
+  lt_debugprintf (__FILE__, __LINE__,
+                  "(main) found exe (before symlink chase) at: %s\n",
+		  tmp_pathspec);
+
+  actual_cwrapper_path = chase_symlinks (tmp_pathspec);
+  lt_debugprintf (__FILE__, __LINE__,
+                  "(main) found exe (after symlink chase) at: %s\n",
+		  actual_cwrapper_path);
+  XFREE (tmp_pathspec);
+
+  actual_cwrapper_name = xstrdup (base_name (actual_cwrapper_path));
+  strendzap (actual_cwrapper_path, actual_cwrapper_name);
+
+  /* wrapper name transforms */
+  strendzap (actual_cwrapper_name, ".exe");
+  tmp_pathspec = lt_extend_str (actual_cwrapper_name, ".exe", 1);
+  XFREE (actual_cwrapper_name);
+  actual_cwrapper_name = tmp_pathspec;
+  tmp_pathspec = 0;
+
+  /* target_name transforms -- use actual target program name; might have lt- prefix */
+  target_name = xstrdup (base_name (TARGET_PROGRAM_NAME));
+  strendzap (target_name, ".exe");
+  tmp_pathspec = lt_extend_str (target_name, ".exe", 1);
+  XFREE (target_name);
+  target_name = tmp_pathspec;
+  tmp_pathspec = 0;
+
+  lt_debugprintf (__FILE__, __LINE__,
+		  "(main) libtool target name: %s\n",
+		  target_name);
+EOF
+
+	    cat <<EOF
+  newargz[0] =
+    XMALLOC (char, (strlen (actual_cwrapper_path) +
+		    strlen ("$objdir") + 1 + strlen (actual_cwrapper_name) + 1));
+  strcpy (newargz[0], actual_cwrapper_path);
+  strcat (newargz[0], "$objdir");
+  strcat (newargz[0], "/");
+EOF
+
+	    cat <<"EOF"
+  /* stop here, and copy so we don't have to do this twice */
+  tmp_pathspec = xstrdup (newargz[0]);
+
+  /* do NOT want the lt- prefix here, so use actual_cwrapper_name */
+  strcat (newargz[0], actual_cwrapper_name);
+
+  /* DO want the lt- prefix here if it exists, so use target_name */
+  lt_argv_zero = lt_extend_str (tmp_pathspec, target_name, 1);
+  XFREE (tmp_pathspec);
+  tmp_pathspec = NULL;
+EOF
+
+	    case $host_os in
+	      mingw*)
+	    cat <<"EOF"
+  {
+    char* p;
+    while ((p = strchr (newargz[0], '\\')) != NULL)
+      {
+	*p = '/';
+      }
+    while ((p = strchr (lt_argv_zero, '\\')) != NULL)
+      {
+	*p = '/';
+      }
+  }
+EOF
+	    ;;
+	    esac
+
+	    cat <<"EOF"
+  XFREE (target_name);
+  XFREE (actual_cwrapper_path);
+  XFREE (actual_cwrapper_name);
+
+  lt_setenv ("BIN_SH", "xpg4"); /* for Tru64 */
+  lt_setenv ("DUALCASE", "1");  /* for MSK sh */
+  /* Update the DLL searchpath.  EXE_PATH_VALUE ($dllsearchpath) must
+     be prepended before (that is, appear after) LIB_PATH_VALUE ($temp_rpath)
+     because on Windows, both *_VARNAMEs are PATH but uninstalled
+     libraries must come first. */
+  lt_update_exe_path (EXE_PATH_VARNAME, EXE_PATH_VALUE);
+  lt_update_lib_path (LIB_PATH_VARNAME, LIB_PATH_VALUE);
+
+  lt_debugprintf (__FILE__, __LINE__, "(main) lt_argv_zero: %s\n",
+		  nonnull (lt_argv_zero));
+  for (i = 0; i < newargc; i++)
+    {
+      lt_debugprintf (__FILE__, __LINE__, "(main) newargz[%d]: %s\n",
+		      i, nonnull (newargz[i]));
+    }
+
+EOF
+
+	    case $host_os in
+	      mingw*)
+		cat <<"EOF"
+  /* execv doesn't actually work on mingw as expected on unix */
+  newargz = prepare_spawn (newargz);
+  rval = _spawnv (_P_WAIT, lt_argv_zero, (const char * const *) newargz);
+  if (rval == -1)
+    {
+      /* failed to start process */
+      lt_debugprintf (__FILE__, __LINE__,
+		      "(main) failed to launch target \"%s\": %s\n",
+		      lt_argv_zero, nonnull (strerror (errno)));
+      return 127;
+    }
+  return rval;
+EOF
+		;;
+	      *)
+		cat <<"EOF"
+  execv (lt_argv_zero, newargz);
+  return rval; /* =127, but avoids unused variable warning */
+EOF
+		;;
+	    esac
+
+	    cat <<"EOF"
+}
+
+void *
+xmalloc (size_t num)
+{
+  void *p = (void *) malloc (num);
+  if (!p)
+    lt_fatal (__FILE__, __LINE__, "memory exhausted");
+
+  return p;
+}
+
+char *
+xstrdup (const char *string)
+{
+  return string ? strcpy ((char *) xmalloc (strlen (string) + 1),
+			  string) : NULL;
+}
+
+const char *
+base_name (const char *name)
+{
+  const char *base;
+
+#if defined (HAVE_DOS_BASED_FILE_SYSTEM)
+  /* Skip over the disk name in MSDOS pathnames. */
+  if (isalpha ((unsigned char) name[0]) && name[1] == ':')
+    name += 2;
+#endif
+
+  for (base = name; *name; name++)
+    if (IS_DIR_SEPARATOR (*name))
+      base = name + 1;
+  return base;
+}
+
+int
+check_executable (const char *path)
+{
+  struct stat st;
+
+  lt_debugprintf (__FILE__, __LINE__, "(check_executable): %s\n",
+                  nonempty (path));
+  if ((!path) || (!*path))
+    return 0;
+
+  if ((stat (path, &st) >= 0)
+      && (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)))
+    return 1;
+  else
+    return 0;
+}
+
+int
+make_executable (const char *path)
+{
+  int rval = 0;
+  struct stat st;
+
+  lt_debugprintf (__FILE__, __LINE__, "(make_executable): %s\n",
+                  nonempty (path));
+  if ((!path) || (!*path))
+    return 0;
+
+  if (stat (path, &st) >= 0)
+    {
+      rval = chmod (path, st.st_mode | S_IXOTH | S_IXGRP | S_IXUSR);
+    }
+  return rval;
+}
+
+/* Searches for the full path of the wrapper.  Returns
+   newly allocated full path name if found, NULL otherwise
+   Does not chase symlinks, even on platforms that support them.
+*/
+char *
+find_executable (const char *wrapper)
+{
+  int has_slash = 0;
+  const char *p;
+  const char *p_next;
+  /* static buffer for getcwd */
+  char tmp[LT_PATHMAX + 1];
+  int tmp_len;
+  char *concat_name;
+
+  lt_debugprintf (__FILE__, __LINE__, "(find_executable): %s\n",
+                  nonempty (wrapper));
+
+  if ((wrapper == NULL) || (*wrapper == '\0'))
+    return NULL;
+
+  /* Absolute path? */
+#if defined (HAVE_DOS_BASED_FILE_SYSTEM)
+  if (isalpha ((unsigned char) wrapper[0]) && wrapper[1] == ':')
+    {
+      concat_name = xstrdup (wrapper);
+      if (check_executable (concat_name))
+	return concat_name;
+      XFREE (concat_name);
+    }
+  else
+    {
+#endif
+      if (IS_DIR_SEPARATOR (wrapper[0]))
+	{
+	  concat_name = xstrdup (wrapper);
+	  if (check_executable (concat_name))
+	    return concat_name;
+	  XFREE (concat_name);
+	}
+#if defined (HAVE_DOS_BASED_FILE_SYSTEM)
+    }
+#endif
+
+  for (p = wrapper; *p; p++)
+    if (*p == '/')
+      {
+	has_slash = 1;
+	break;
+      }
+  if (!has_slash)
+    {
+      /* no slashes; search PATH */
+      const char *path = getenv ("PATH");
+      if (path != NULL)
+	{
+	  for (p = path; *p; p = p_next)
+	    {
+	      const char *q;
+	      size_t p_len;
+	      for (q = p; *q; q++)
+		if (IS_PATH_SEPARATOR (*q))
+		  break;
+	      p_len = q - p;
+	      p_next = (*q == '\0' ? q : q + 1);
+	      if (p_len == 0)
+		{
+		  /* empty path: current directory */
+		  if (getcwd (tmp, LT_PATHMAX) == NULL)
+		    lt_fatal (__FILE__, __LINE__, "getcwd failed: %s",
+                              nonnull (strerror (errno)));
+		  tmp_len = strlen (tmp);
+		  concat_name =
+		    XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1);
+		  memcpy (concat_name, tmp, tmp_len);
+		  concat_name[tmp_len] = '/';
+		  strcpy (concat_name + tmp_len + 1, wrapper);
+		}
+	      else
+		{
+		  concat_name =
+		    XMALLOC (char, p_len + 1 + strlen (wrapper) + 1);
+		  memcpy (concat_name, p, p_len);
+		  concat_name[p_len] = '/';
+		  strcpy (concat_name + p_len + 1, wrapper);
+		}
+	      if (check_executable (concat_name))
+		return concat_name;
+	      XFREE (concat_name);
+	    }
+	}
+      /* not found in PATH; assume curdir */
+    }
+  /* Relative path | not found in path: prepend cwd */
+  if (getcwd (tmp, LT_PATHMAX) == NULL)
+    lt_fatal (__FILE__, __LINE__, "getcwd failed: %s",
+              nonnull (strerror (errno)));
+  tmp_len = strlen (tmp);
+  concat_name = XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1);
+  memcpy (concat_name, tmp, tmp_len);
+  concat_name[tmp_len] = '/';
+  strcpy (concat_name + tmp_len + 1, wrapper);
+
+  if (check_executable (concat_name))
+    return concat_name;
+  XFREE (concat_name);
+  return NULL;
+}
+
+char *
+chase_symlinks (const char *pathspec)
+{
+#ifndef S_ISLNK
+  return xstrdup (pathspec);
+#else
+  char buf[LT_PATHMAX];
+  struct stat s;
+  char *tmp_pathspec = xstrdup (pathspec);
+  char *p;
+  int has_symlinks = 0;
+  while (strlen (tmp_pathspec) && !has_symlinks)
+    {
+      lt_debugprintf (__FILE__, __LINE__,
+		      "checking path component for symlinks: %s\n",
+		      tmp_pathspec);
+      if (lstat (tmp_pathspec, &s) == 0)
+	{
+	  if (S_ISLNK (s.st_mode) != 0)
+	    {
+	      has_symlinks = 1;
+	      break;
+	    }
+
+	  /* search backwards for last DIR_SEPARATOR */
+	  p = tmp_pathspec + strlen (tmp_pathspec) - 1;
+	  while ((p > tmp_pathspec) && (!IS_DIR_SEPARATOR (*p)))
+	    p--;
+	  if ((p == tmp_pathspec) && (!IS_DIR_SEPARATOR (*p)))
+	    {
+	      /* no more DIR_SEPARATORS left */
+	      break;
+	    }
+	  *p = '\0';
+	}
+      else
+	{
+	  lt_fatal (__FILE__, __LINE__,
+		    "error accessing file \"%s\": %s",
+		    tmp_pathspec, nonnull (strerror (errno)));
+	}
+    }
+  XFREE (tmp_pathspec);
+
+  if (!has_symlinks)
+    {
+      return xstrdup (pathspec);
+    }
+
+  tmp_pathspec = realpath (pathspec, buf);
+  if (tmp_pathspec == 0)
+    {
+      lt_fatal (__FILE__, __LINE__,
+		"could not follow symlinks for %s", pathspec);
+    }
+  return xstrdup (tmp_pathspec);
+#endif
+}
+
+char *
+strendzap (char *str, const char *pat)
+{
+  size_t len, patlen;
+
+  assert (str != NULL);
+  assert (pat != NULL);
+
+  len = strlen (str);
+  patlen = strlen (pat);
+
+  if (patlen <= len)
+    {
+      str += len - patlen;
+      if (strcmp (str, pat) == 0)
+	*str = '\0';
+    }
+  return str;
+}
+
+void
+lt_debugprintf (const char *file, int line, const char *fmt, ...)
+{
+  va_list args;
+  if (lt_debug)
+    {
+      (void) fprintf (stderr, "%s:%s:%d: ", program_name, file, line);
+      va_start (args, fmt);
+      (void) vfprintf (stderr, fmt, args);
+      va_end (args);
+    }
+}
+
+static void
+lt_error_core (int exit_status, const char *file,
+	       int line, const char *mode,
+	       const char *message, va_list ap)
+{
+  fprintf (stderr, "%s:%s:%d: %s: ", program_name, file, line, mode);
+  vfprintf (stderr, message, ap);
+  fprintf (stderr, ".\n");
+
+  if (exit_status >= 0)
+    exit (exit_status);
+}
+
+void
+lt_fatal (const char *file, int line, const char *message, ...)
+{
+  va_list ap;
+  va_start (ap, message);
+  lt_error_core (EXIT_FAILURE, file, line, "FATAL", message, ap);
+  va_end (ap);
+}
+
+static const char *
+nonnull (const char *s)
+{
+  return s ? s : "(null)";
+}
+
+static const char *
+nonempty (const char *s)
+{
+  return (s && !*s) ? "(empty)" : nonnull (s);
+}
+
+void
+lt_setenv (const char *name, const char *value)
+{
+  lt_debugprintf (__FILE__, __LINE__,
+		  "(lt_setenv) setting '%s' to '%s'\n",
+                  nonnull (name), nonnull (value));
+  {
+#ifdef HAVE_SETENV
+    /* always make a copy, for consistency with !HAVE_SETENV */
+    char *str = xstrdup (value);
+    setenv (name, str, 1);
+#else
+    int len = strlen (name) + 1 + strlen (value) + 1;
+    char *str = XMALLOC (char, len);
+    sprintf (str, "%s=%s", name, value);
+    if (putenv (str) != EXIT_SUCCESS)
+      {
+        XFREE (str);
+      }
+#endif
+  }
+}
+
+char *
+lt_extend_str (const char *orig_value, const char *add, int to_end)
+{
+  char *new_value;
+  if (orig_value && *orig_value)
+    {
+      int orig_value_len = strlen (orig_value);
+      int add_len = strlen (add);
+      new_value = XMALLOC (char, add_len + orig_value_len + 1);
+      if (to_end)
+        {
+          strcpy (new_value, orig_value);
+          strcpy (new_value + orig_value_len, add);
+        }
+      else
+        {
+          strcpy (new_value, add);
+          strcpy (new_value + add_len, orig_value);
+        }
+    }
+  else
+    {
+      new_value = xstrdup (add);
+    }
+  return new_value;
+}
+
+void
+lt_update_exe_path (const char *name, const char *value)
+{
+  lt_debugprintf (__FILE__, __LINE__,
+		  "(lt_update_exe_path) modifying '%s' by prepending '%s'\n",
+                  nonnull (name), nonnull (value));
+
+  if (name && *name && value && *value)
+    {
+      char *new_value = lt_extend_str (getenv (name), value, 0);
+      /* some systems can't cope with a ':'-terminated path #' */
+      int len = strlen (new_value);
+      while (((len = strlen (new_value)) > 0) && IS_PATH_SEPARATOR (new_value[len-1]))
+        {
+          new_value[len-1] = '\0';
+        }
+      lt_setenv (name, new_value);
+      XFREE (new_value);
+    }
+}
+
+void
+lt_update_lib_path (const char *name, const char *value)
+{
+  lt_debugprintf (__FILE__, __LINE__,
+		  "(lt_update_lib_path) modifying '%s' by prepending '%s'\n",
+                  nonnull (name), nonnull (value));
+
+  if (name && *name && value && *value)
+    {
+      char *new_value = lt_extend_str (getenv (name), value, 0);
+      lt_setenv (name, new_value);
+      XFREE (new_value);
+    }
+}
+
+EOF
+	    case $host_os in
+	      mingw*)
+		cat <<"EOF"
+
+/* Prepares an argument vector before calling spawn().
+   Note that spawn() does not by itself call the command interpreter
+     (getenv ("COMSPEC") != NULL ? getenv ("COMSPEC") :
+      ({ OSVERSIONINFO v; v.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
+         GetVersionEx(&v);
+         v.dwPlatformId == VER_PLATFORM_WIN32_NT;
+      }) ? "cmd.exe" : "command.com").
+   Instead it simply concatenates the arguments, separated by ' ', and calls
+   CreateProcess().  We must quote the arguments since Win32 CreateProcess()
+   interprets characters like ' ', '\t', '\\', '"' (but not '<' and '>') in a
+   special way:
+   - Space and tab are interpreted as delimiters. They are not treated as
+     delimiters if they are surrounded by double quotes: "...".
+   - Unescaped double quotes are removed from the input. Their only effect is
+     that within double quotes, space and tab are treated like normal
+     characters.
+   - Backslashes not followed by double quotes are not special.
+   - But 2*n+1 backslashes followed by a double quote become
+     n backslashes followed by a double quote (n >= 0):
+       \" -> "
+       \\\" -> \"
+       \\\\\" -> \\"
+ */
+#define SHELL_SPECIAL_CHARS "\"\\ \001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037"
+#define SHELL_SPACE_CHARS " \001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037"
+char **
+prepare_spawn (char **argv)
+{
+  size_t argc;
+  char **new_argv;
+  size_t i;
+
+  /* Count number of arguments.  */
+  for (argc = 0; argv[argc] != NULL; argc++)
+    ;
+
+  /* Allocate new argument vector.  */
+  new_argv = XMALLOC (char *, argc + 1);
+
+  /* Put quoted arguments into the new argument vector.  */
+  for (i = 0; i < argc; i++)
+    {
+      const char *string = argv[i];
+
+      if (string[0] == '\0')
+	new_argv[i] = xstrdup ("\"\"");
+      else if (strpbrk (string, SHELL_SPECIAL_CHARS) != NULL)
+	{
+	  int quote_around = (strpbrk (string, SHELL_SPACE_CHARS) != NULL);
+	  size_t length;
+	  unsigned int backslashes;
+	  const char *s;
+	  char *quoted_string;
+	  char *p;
+
+	  length = 0;
+	  backslashes = 0;
+	  if (quote_around)
+	    length++;
+	  for (s = string; *s != '\0'; s++)
+	    {
+	      char c = *s;
+	      if (c == '"')
+		length += backslashes + 1;
+	      length++;
+	      if (c == '\\')
+		backslashes++;
+	      else
+		backslashes = 0;
+	    }
+	  if (quote_around)
+	    length += backslashes + 1;
+
+	  quoted_string = XMALLOC (char, length + 1);
+
+	  p = quoted_string;
+	  backslashes = 0;
+	  if (quote_around)
+	    *p++ = '"';
+	  for (s = string; *s != '\0'; s++)
+	    {
+	      char c = *s;
+	      if (c == '"')
+		{
+		  unsigned int j;
+		  for (j = backslashes + 1; j > 0; j--)
+		    *p++ = '\\';
+		}
+	      *p++ = c;
+	      if (c == '\\')
+		backslashes++;
+	      else
+		backslashes = 0;
+	    }
+	  if (quote_around)
+	    {
+	      unsigned int j;
+	      for (j = backslashes; j > 0; j--)
+		*p++ = '\\';
+	      *p++ = '"';
+	    }
+	  *p = '\0';
+
+	  new_argv[i] = quoted_string;
+	}
+      else
+	new_argv[i] = (char *) string;
+    }
+  new_argv[argc] = NULL;
+
+  return new_argv;
+}
+EOF
+		;;
+	    esac
+
+            cat <<"EOF"
+void lt_dump_script (FILE* f)
+{
+EOF
+	    func_emit_wrapper yes |
+	      $SED -n -e '
+s/^\(.\{79\}\)\(..*\)/\1\
+\2/
+h
+s/\([\\"]\)/\\\1/g
+s/$/\\n/
+s/\([^\n]*\).*/  fputs ("\1", f);/p
+g
+D'
+            cat <<"EOF"
+}
+EOF
+}
+# end: func_emit_cwrapperexe_src
+
+# func_win32_import_lib_p ARG
+# True if ARG is an import lib, as indicated by $file_magic_cmd
+func_win32_import_lib_p ()
+{
+    $opt_debug
+    case `eval $file_magic_cmd \"\$1\" 2>/dev/null | $SED -e 10q` in
+    *import*) : ;;
+    *) false ;;
+    esac
+}
+
+# func_mode_link arg...
+func_mode_link ()
+{
+    $opt_debug
+    case $host in
+    *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)
+      # It is impossible to link a dll without this setting, and
+      # we shouldn't force the makefile maintainer to figure out
+      # which system we are compiling for in order to pass an extra
+      # flag for every libtool invocation.
+      # allow_undefined=no
+
+      # FIXME: Unfortunately, there are problems with the above when trying
+      # to make a dll which has undefined symbols, in which case not
+      # even a static library is built.  For now, we need to specify
+      # -no-undefined on the libtool link line when we can be certain
+      # that all symbols are satisfied, otherwise we get a static library.
+      allow_undefined=yes
+      ;;
+    *)
+      allow_undefined=yes
+      ;;
+    esac
+    libtool_args=$nonopt
+    base_compile="$nonopt $@"
+    compile_command=$nonopt
+    finalize_command=$nonopt
+
+    compile_rpath=
+    finalize_rpath=
+    compile_shlibpath=
+    finalize_shlibpath=
+    convenience=
+    old_convenience=
+    deplibs=
+    old_deplibs=
+    compiler_flags=
+    linker_flags=
+    dllsearchpath=
+    lib_search_path=`pwd`
+    inst_prefix_dir=
+    new_inherited_linker_flags=
+
+    avoid_version=no
+    bindir=
+    dlfiles=
+    dlprefiles=
+    dlself=no
+    export_dynamic=no
+    export_symbols=
+    export_symbols_regex=
+    generated=
+    libobjs=
+    ltlibs=
+    module=no
+    no_install=no
+    objs=
+    non_pic_objects=
+    precious_files_regex=
+    prefer_static_libs=no
+    preload=no
+    prev=
+    prevarg=
+    release=
+    rpath=
+    xrpath=
+    perm_rpath=
+    temp_rpath=
+    thread_safe=no
+    vinfo=
+    vinfo_number=no
+    weak_libs=
+    single_module="${wl}-single_module"
+    func_infer_tag $base_compile
+
+    # We need to know -static, to get the right output filenames.
+    for arg
+    do
+      case $arg in
+      -shared)
+	test "$build_libtool_libs" != yes && \
+	  func_fatal_configuration "can not build a shared library"
+	build_old_libs=no
+	break
+	;;
+      -all-static | -static | -static-libtool-libs)
+	case $arg in
+	-all-static)
+	  if test "$build_libtool_libs" = yes && test -z "$link_static_flag"; then
+	    func_warning "complete static linking is impossible in this configuration"
+	  fi
+	  if test -n "$link_static_flag"; then
+	    dlopen_self=$dlopen_self_static
+	  fi
+	  prefer_static_libs=yes
+	  ;;
+	-static)
+	  if test -z "$pic_flag" && test -n "$link_static_flag"; then
+	    dlopen_self=$dlopen_self_static
+	  fi
+	  prefer_static_libs=built
+	  ;;
+	-static-libtool-libs)
+	  if test -z "$pic_flag" && test -n "$link_static_flag"; then
+	    dlopen_self=$dlopen_self_static
+	  fi
+	  prefer_static_libs=yes
+	  ;;
+	esac
+	build_libtool_libs=no
+	build_old_libs=yes
+	break
+	;;
+      esac
+    done
+
+    # See if our shared archives depend on static archives.
+    test -n "$old_archive_from_new_cmds" && build_old_libs=yes
+
+    # Go through the arguments, transforming them on the way.
+    while test "$#" -gt 0; do
+      arg="$1"
+      shift
+      func_quote_for_eval "$arg"
+      qarg=$func_quote_for_eval_unquoted_result
+      func_append libtool_args " $func_quote_for_eval_result"
+
+      # If the previous option needs an argument, assign it.
+      if test -n "$prev"; then
+	case $prev in
+	output)
+	  func_append compile_command " @OUTPUT@"
+	  func_append finalize_command " @OUTPUT@"
+	  ;;
+	esac
+
+	case $prev in
+	bindir)
+	  bindir="$arg"
+	  prev=
+	  continue
+	  ;;
+	dlfiles|dlprefiles)
+	  if test "$preload" = no; then
+	    # Add the symbol object into the linking commands.
+	    func_append compile_command " @SYMFILE@"
+	    func_append finalize_command " @SYMFILE@"
+	    preload=yes
+	  fi
+	  case $arg in
+	  *.la | *.lo) ;;  # We handle these cases below.
+	  force)
+	    if test "$dlself" = no; then
+	      dlself=needless
+	      export_dynamic=yes
+	    fi
+	    prev=
+	    continue
+	    ;;
+	  self)
+	    if test "$prev" = dlprefiles; then
+	      dlself=yes
+	    elif test "$prev" = dlfiles && test "$dlopen_self" != yes; then
+	      dlself=yes
+	    else
+	      dlself=needless
+	      export_dynamic=yes
+	    fi
+	    prev=
+	    continue
+	    ;;
+	  *)
+	    if test "$prev" = dlfiles; then
+	      func_append dlfiles " $arg"
+	    else
+	      func_append dlprefiles " $arg"
+	    fi
+	    prev=
+	    continue
+	    ;;
+	  esac
+	  ;;
+	expsyms)
+	  export_symbols="$arg"
+	  test -f "$arg" \
+	    || func_fatal_error "symbol file \`$arg' does not exist"
+	  prev=
+	  continue
+	  ;;
+	expsyms_regex)
+	  export_symbols_regex="$arg"
+	  prev=
+	  continue
+	  ;;
+	framework)
+	  case $host in
+	    *-*-darwin*)
+	      case "$deplibs " in
+		*" $qarg.ltframework "*) ;;
+		*) func_append deplibs " $qarg.ltframework" # this is fixed later
+		   ;;
+	      esac
+	      ;;
+	  esac
+	  prev=
+	  continue
+	  ;;
+	inst_prefix)
+	  inst_prefix_dir="$arg"
+	  prev=
+	  continue
+	  ;;
+	objectlist)
+	  if test -f "$arg"; then
+	    save_arg=$arg
+	    moreargs=
+	    for fil in `cat "$save_arg"`
+	    do
+#	      func_append moreargs " $fil"
+	      arg=$fil
+	      # A libtool-controlled object.
+
+	      # Check to see that this really is a libtool object.
+	      if func_lalib_unsafe_p "$arg"; then
+		pic_object=
+		non_pic_object=
+
+		# Read the .lo file
+		func_source "$arg"
+
+		if test -z "$pic_object" ||
+		   test -z "$non_pic_object" ||
+		   test "$pic_object" = none &&
+		   test "$non_pic_object" = none; then
+		  func_fatal_error "cannot find name of object for \`$arg'"
+		fi
+
+		# Extract subdirectory from the argument.
+		func_dirname "$arg" "/" ""
+		xdir="$func_dirname_result"
+
+		if test "$pic_object" != none; then
+		  # Prepend the subdirectory the object is found in.
+		  pic_object="$xdir$pic_object"
+
+		  if test "$prev" = dlfiles; then
+		    if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then
+		      func_append dlfiles " $pic_object"
+		      prev=
+		      continue
+		    else
+		      # If libtool objects are unsupported, then we need to preload.
+		      prev=dlprefiles
+		    fi
+		  fi
+
+		  # CHECK ME:  I think I busted this.  -Ossama
+		  if test "$prev" = dlprefiles; then
+		    # Preload the old-style object.
+		    func_append dlprefiles " $pic_object"
+		    prev=
+		  fi
+
+		  # A PIC object.
+		  func_append libobjs " $pic_object"
+		  arg="$pic_object"
+		fi
+
+		# Non-PIC object.
+		if test "$non_pic_object" != none; then
+		  # Prepend the subdirectory the object is found in.
+		  non_pic_object="$xdir$non_pic_object"
+
+		  # A standard non-PIC object
+		  func_append non_pic_objects " $non_pic_object"
+		  if test -z "$pic_object" || test "$pic_object" = none ; then
+		    arg="$non_pic_object"
+		  fi
+		else
+		  # If the PIC object exists, use it instead.
+		  # $xdir was prepended to $pic_object above.
+		  non_pic_object="$pic_object"
+		  func_append non_pic_objects " $non_pic_object"
+		fi
+	      else
+		# Only an error if not doing a dry-run.
+		if $opt_dry_run; then
+		  # Extract subdirectory from the argument.
+		  func_dirname "$arg" "/" ""
+		  xdir="$func_dirname_result"
+
+		  func_lo2o "$arg"
+		  pic_object=$xdir$objdir/$func_lo2o_result
+		  non_pic_object=$xdir$func_lo2o_result
+		  func_append libobjs " $pic_object"
+		  func_append non_pic_objects " $non_pic_object"
+	        else
+		  func_fatal_error "\`$arg' is not a valid libtool object"
+		fi
+	      fi
+	    done
+	  else
+	    func_fatal_error "link input file \`$arg' does not exist"
+	  fi
+	  arg=$save_arg
+	  prev=
+	  continue
+	  ;;
+	precious_regex)
+	  precious_files_regex="$arg"
+	  prev=
+	  continue
+	  ;;
+	release)
+	  release="-$arg"
+	  prev=
+	  continue
+	  ;;
+	rpath | xrpath)
+	  # We need an absolute path.
+	  case $arg in
+	  [\\/]* | [A-Za-z]:[\\/]*) ;;
+	  *)
+	    func_fatal_error "only absolute run-paths are allowed"
+	    ;;
+	  esac
+	  if test "$prev" = rpath; then
+	    case "$rpath " in
+	    *" $arg "*) ;;
+	    *) func_append rpath " $arg" ;;
+	    esac
+	  else
+	    case "$xrpath " in
+	    *" $arg "*) ;;
+	    *) func_append xrpath " $arg" ;;
+	    esac
+	  fi
+	  prev=
+	  continue
+	  ;;
+	shrext)
+	  shrext_cmds="$arg"
+	  prev=
+	  continue
+	  ;;
+	weak)
+	  func_append weak_libs " $arg"
+	  prev=
+	  continue
+	  ;;
+	xcclinker)
+	  func_append linker_flags " $qarg"
+	  func_append compiler_flags " $qarg"
+	  prev=
+	  func_append compile_command " $qarg"
+	  func_append finalize_command " $qarg"
+	  continue
+	  ;;
+	xcompiler)
+	  func_append compiler_flags " $qarg"
+	  prev=
+	  func_append compile_command " $qarg"
+	  func_append finalize_command " $qarg"
+	  continue
+	  ;;
+	xlinker)
+	  func_append linker_flags " $qarg"
+	  func_append compiler_flags " $wl$qarg"
+	  prev=
+	  func_append compile_command " $wl$qarg"
+	  func_append finalize_command " $wl$qarg"
+	  continue
+	  ;;
+	*)
+	  eval "$prev=\"\$arg\""
+	  prev=
+	  continue
+	  ;;
+	esac
+      fi # test -n "$prev"
+
+      prevarg="$arg"
+
+      case $arg in
+      -all-static)
+	if test -n "$link_static_flag"; then
+	  # See comment for -static flag below, for more details.
+	  func_append compile_command " $link_static_flag"
+	  func_append finalize_command " $link_static_flag"
+	fi
+	continue
+	;;
+
+      -allow-undefined)
+	# FIXME: remove this flag sometime in the future.
+	func_fatal_error "\`-allow-undefined' must not be used because it is the default"
+	;;
+
+      -avoid-version)
+	avoid_version=yes
+	continue
+	;;
+
+      -bindir)
+	prev=bindir
+	continue
+	;;
+
+      -dlopen)
+	prev=dlfiles
+	continue
+	;;
+
+      -dlpreopen)
+	prev=dlprefiles
+	continue
+	;;
+
+      -export-dynamic)
+	export_dynamic=yes
+	continue
+	;;
+
+      -export-symbols | -export-symbols-regex)
+	if test -n "$export_symbols" || test -n "$export_symbols_regex"; then
+	  func_fatal_error "more than one -exported-symbols argument is not allowed"
+	fi
+	if test "X$arg" = "X-export-symbols"; then
+	  prev=expsyms
+	else
+	  prev=expsyms_regex
+	fi
+	continue
+	;;
+
+      -framework)
+	prev=framework
+	continue
+	;;
+
+      -inst-prefix-dir)
+	prev=inst_prefix
+	continue
+	;;
+
+      # The native IRIX linker understands -LANG:*, -LIST:* and -LNO:*
+      # so, if we see these flags be careful not to treat them like -L
+      -L[A-Z][A-Z]*:*)
+	case $with_gcc/$host in
+	no/*-*-irix* | /*-*-irix*)
+	  func_append compile_command " $arg"
+	  func_append finalize_command " $arg"
+	  ;;
+	esac
+	continue
+	;;
+
+      -L*)
+	func_stripname "-L" '' "$arg"
+	if test -z "$func_stripname_result"; then
+	  if test "$#" -gt 0; then
+	    func_fatal_error "require no space between \`-L' and \`$1'"
+	  else
+	    func_fatal_error "need path for \`-L' option"
+	  fi
+	fi
+	func_resolve_sysroot "$func_stripname_result"
+	dir=$func_resolve_sysroot_result
+	# We need an absolute path.
+	case $dir in
+	[\\/]* | [A-Za-z]:[\\/]*) ;;
+	*)
+	  absdir=`cd "$dir" && pwd`
+	  test -z "$absdir" && \
+	    func_fatal_error "cannot determine absolute directory name of \`$dir'"
+	  dir="$absdir"
+	  ;;
+	esac
+	case "$deplibs " in
+	*" -L$dir "* | *" $arg "*)
+	  # Will only happen for absolute or sysroot arguments
+	  ;;
+	*)
+	  # Preserve sysroot, but never include relative directories
+	  case $dir in
+	    [\\/]* | [A-Za-z]:[\\/]* | =*) func_append deplibs " $arg" ;;
+	    *) func_append deplibs " -L$dir" ;;
+	  esac
+	  func_append lib_search_path " $dir"
+	  ;;
+	esac
+	case $host in
+	*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)
+	  testbindir=`$ECHO "$dir" | $SED 's*/lib$*/bin*'`
+	  case :$dllsearchpath: in
+	  *":$dir:"*) ;;
+	  ::) dllsearchpath=$dir;;
+	  *) func_append dllsearchpath ":$dir";;
+	  esac
+	  case :$dllsearchpath: in
+	  *":$testbindir:"*) ;;
+	  ::) dllsearchpath=$testbindir;;
+	  *) func_append dllsearchpath ":$testbindir";;
+	  esac
+	  ;;
+	esac
+	continue
+	;;
+
+      -l*)
+	if test "X$arg" = "X-lc" || test "X$arg" = "X-lm"; then
+	  case $host in
+	  *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos* | *-cegcc* | *-*-haiku*)
+	    # These systems don't actually have a C or math library (as such)
+	    continue
+	    ;;
+	  *-*-os2*)
+	    # These systems don't actually have a C library (as such)
+	    test "X$arg" = "X-lc" && continue
+	    ;;
+	  *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*)
+	    # Do not include libc due to us having libc/libc_r.
+	    test "X$arg" = "X-lc" && continue
+	    ;;
+	  *-*-rhapsody* | *-*-darwin1.[012])
+	    # Rhapsody C and math libraries are in the System framework
+	    func_append deplibs " System.ltframework"
+	    continue
+	    ;;
+	  *-*-sco3.2v5* | *-*-sco5v6*)
+	    # Causes problems with __ctype
+	    test "X$arg" = "X-lc" && continue
+	    ;;
+	  *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*)
+	    # Compiler inserts libc in the correct place for threads to work
+	    test "X$arg" = "X-lc" && continue
+	    ;;
+	  esac
+	elif test "X$arg" = "X-lc_r"; then
+	 case $host in
+	 *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*)
+	   # Do not include libc_r directly, use -pthread flag.
+	   continue
+	   ;;
+	 esac
+	fi
+	func_append deplibs " $arg"
+	continue
+	;;
+
+      -module)
+	module=yes
+	continue
+	;;
+
+      # Tru64 UNIX uses -model [arg] to determine the layout of C++
+      # classes, name mangling, and exception handling.
+      # Darwin uses the -arch flag to determine output architecture.
+      -model|-arch|-isysroot|--sysroot)
+	func_append compiler_flags " $arg"
+	func_append compile_command " $arg"
+	func_append finalize_command " $arg"
+	prev=xcompiler
+	continue
+	;;
+
+      -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \
+      |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*)
+	func_append compiler_flags " $arg"
+	func_append compile_command " $arg"
+	func_append finalize_command " $arg"
+	case "$new_inherited_linker_flags " in
+	    *" $arg "*) ;;
+	    * ) func_append new_inherited_linker_flags " $arg" ;;
+	esac
+	continue
+	;;
+
+      -multi_module)
+	single_module="${wl}-multi_module"
+	continue
+	;;
+
+      -no-fast-install)
+	fast_install=no
+	continue
+	;;
+
+      -no-install)
+	case $host in
+	*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-darwin* | *-cegcc*)
+	  # The PATH hackery in wrapper scripts is required on Windows
+	  # and Darwin in order for the loader to find any dlls it needs.
+	  func_warning "\`-no-install' is ignored for $host"
+	  func_warning "assuming \`-no-fast-install' instead"
+	  fast_install=no
+	  ;;
+	*) no_install=yes ;;
+	esac
+	continue
+	;;
+
+      -no-undefined)
+	allow_undefined=no
+	continue
+	;;
+
+      -objectlist)
+	prev=objectlist
+	continue
+	;;
+
+      -o) prev=output ;;
+
+      -precious-files-regex)
+	prev=precious_regex
+	continue
+	;;
+
+      -release)
+	prev=release
+	continue
+	;;
+
+      -rpath)
+	prev=rpath
+	continue
+	;;
+
+      -R)
+	prev=xrpath
+	continue
+	;;
+
+      -R*)
+	func_stripname '-R' '' "$arg"
+	dir=$func_stripname_result
+	# We need an absolute path.
+	case $dir in
+	[\\/]* | [A-Za-z]:[\\/]*) ;;
+	=*)
+	  func_stripname '=' '' "$dir"
+	  dir=$lt_sysroot$func_stripname_result
+	  ;;
+	*)
+	  func_fatal_error "only absolute run-paths are allowed"
+	  ;;
+	esac
+	case "$xrpath " in
+	*" $dir "*) ;;
+	*) func_append xrpath " $dir" ;;
+	esac
+	continue
+	;;
+
+      -shared)
+	# The effects of -shared are defined in a previous loop.
+	continue
+	;;
+
+      -shrext)
+	prev=shrext
+	continue
+	;;
+
+      -static | -static-libtool-libs)
+	# The effects of -static are defined in a previous loop.
+	# We used to do the same as -all-static on platforms that
+	# didn't have a PIC flag, but the assumption that the effects
+	# would be equivalent was wrong.  It would break on at least
+	# Digital Unix and AIX.
+	continue
+	;;
+
+      -thread-safe)
+	thread_safe=yes
+	continue
+	;;
+
+      -version-info)
+	prev=vinfo
+	continue
+	;;
+
+      -version-number)
+	prev=vinfo
+	vinfo_number=yes
+	continue
+	;;
+
+      -weak)
+        prev=weak
+	continue
+	;;
+
+      -Wc,*)
+	func_stripname '-Wc,' '' "$arg"
+	args=$func_stripname_result
+	arg=
+	save_ifs="$IFS"; IFS=','
+	for flag in $args; do
+	  IFS="$save_ifs"
+          func_quote_for_eval "$flag"
+	  func_append arg " $func_quote_for_eval_result"
+	  func_append compiler_flags " $func_quote_for_eval_result"
+	done
+	IFS="$save_ifs"
+	func_stripname ' ' '' "$arg"
+	arg=$func_stripname_result
+	;;
+
+      -Wl,*)
+	func_stripname '-Wl,' '' "$arg"
+	args=$func_stripname_result
+	arg=
+	save_ifs="$IFS"; IFS=','
+	for flag in $args; do
+	  IFS="$save_ifs"
+          func_quote_for_eval "$flag"
+	  func_append arg " $wl$func_quote_for_eval_result"
+	  func_append compiler_flags " $wl$func_quote_for_eval_result"
+	  func_append linker_flags " $func_quote_for_eval_result"
+	done
+	IFS="$save_ifs"
+	func_stripname ' ' '' "$arg"
+	arg=$func_stripname_result
+	;;
+
+      -Xcompiler)
+	prev=xcompiler
+	continue
+	;;
+
+      -Xlinker)
+	prev=xlinker
+	continue
+	;;
+
+      -XCClinker)
+	prev=xcclinker
+	continue
+	;;
+
+      # -msg_* for osf cc
+      -msg_*)
+	func_quote_for_eval "$arg"
+	arg="$func_quote_for_eval_result"
+	;;
+
+      # Flags to be passed through unchanged, with rationale:
+      # -64, -mips[0-9]      enable 64-bit mode for the SGI compiler
+      # -r[0-9][0-9]*        specify processor for the SGI compiler
+      # -xarch=*, -xtarget=* enable 64-bit mode for the Sun compiler
+      # +DA*, +DD*           enable 64-bit mode for the HP compiler
+      # -q*                  compiler args for the IBM compiler
+      # -m*, -t[45]*, -txscale* architecture-specific flags for GCC
+      # -F/path              path to uninstalled frameworks, gcc on darwin
+      # -p, -pg, --coverage, -fprofile-*  profiling flags for GCC
+      # @file                GCC response files
+      # -tp=*                Portland pgcc target processor selection
+      # --sysroot=*          for sysroot support
+      # -O*, -flto*, -fwhopr*, -fuse-linker-plugin GCC link-time optimization
+      -64|-mips[0-9]|-r[0-9][0-9]*|-xarch=*|-xtarget=*|+DA*|+DD*|-q*|-m*| \
+      -t[45]*|-txscale*|-p|-pg|--coverage|-fprofile-*|-F*|@*|-tp=*|--sysroot=*| \
+      -O*|-flto*|-fwhopr*|-fuse-linker-plugin)
+        func_quote_for_eval "$arg"
+	arg="$func_quote_for_eval_result"
+        func_append compile_command " $arg"
+        func_append finalize_command " $arg"
+        func_append compiler_flags " $arg"
+        continue
+        ;;
+
+      # Some other compiler flag.
+      -* | +*)
+        func_quote_for_eval "$arg"
+	arg="$func_quote_for_eval_result"
+	;;
+
+      *.$objext)
+	# A standard object.
+	func_append objs " $arg"
+	;;
+
+      *.lo)
+	# A libtool-controlled object.
+
+	# Check to see that this really is a libtool object.
+	if func_lalib_unsafe_p "$arg"; then
+	  pic_object=
+	  non_pic_object=
+
+	  # Read the .lo file
+	  func_source "$arg"
+
+	  if test -z "$pic_object" ||
+	     test -z "$non_pic_object" ||
+	     test "$pic_object" = none &&
+	     test "$non_pic_object" = none; then
+	    func_fatal_error "cannot find name of object for \`$arg'"
+	  fi
+
+	  # Extract subdirectory from the argument.
+	  func_dirname "$arg" "/" ""
+	  xdir="$func_dirname_result"
+
+	  if test "$pic_object" != none; then
+	    # Prepend the subdirectory the object is found in.
+	    pic_object="$xdir$pic_object"
+
+	    if test "$prev" = dlfiles; then
+	      if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then
+		func_append dlfiles " $pic_object"
+		prev=
+		continue
+	      else
+		# If libtool objects are unsupported, then we need to preload.
+		prev=dlprefiles
+	      fi
+	    fi
+
+	    # CHECK ME:  I think I busted this.  -Ossama
+	    if test "$prev" = dlprefiles; then
+	      # Preload the old-style object.
+	      func_append dlprefiles " $pic_object"
+	      prev=
+	    fi
+
+	    # A PIC object.
+	    func_append libobjs " $pic_object"
+	    arg="$pic_object"
+	  fi
+
+	  # Non-PIC object.
+	  if test "$non_pic_object" != none; then
+	    # Prepend the subdirectory the object is found in.
+	    non_pic_object="$xdir$non_pic_object"
+
+	    # A standard non-PIC object
+	    func_append non_pic_objects " $non_pic_object"
+	    if test -z "$pic_object" || test "$pic_object" = none ; then
+	      arg="$non_pic_object"
+	    fi
+	  else
+	    # If the PIC object exists, use it instead.
+	    # $xdir was prepended to $pic_object above.
+	    non_pic_object="$pic_object"
+	    func_append non_pic_objects " $non_pic_object"
+	  fi
+	else
+	  # Only an error if not doing a dry-run.
+	  if $opt_dry_run; then
+	    # Extract subdirectory from the argument.
+	    func_dirname "$arg" "/" ""
+	    xdir="$func_dirname_result"
+
+	    func_lo2o "$arg"
+	    pic_object=$xdir$objdir/$func_lo2o_result
+	    non_pic_object=$xdir$func_lo2o_result
+	    func_append libobjs " $pic_object"
+	    func_append non_pic_objects " $non_pic_object"
+	  else
+	    func_fatal_error "\`$arg' is not a valid libtool object"
+	  fi
+	fi
+	;;
+
+      *.$libext)
+	# An archive.
+	func_append deplibs " $arg"
+	func_append old_deplibs " $arg"
+	continue
+	;;
+
+      *.la)
+	# A libtool-controlled library.
+
+	func_resolve_sysroot "$arg"
+	if test "$prev" = dlfiles; then
+	  # This library was specified with -dlopen.
+	  func_append dlfiles " $func_resolve_sysroot_result"
+	  prev=
+	elif test "$prev" = dlprefiles; then
+	  # The library was specified with -dlpreopen.
+	  func_append dlprefiles " $func_resolve_sysroot_result"
+	  prev=
+	else
+	  func_append deplibs " $func_resolve_sysroot_result"
+	fi
+	continue
+	;;
+
+      # Some other compiler argument.
+      *)
+	# Unknown arguments in both finalize_command and compile_command need
+	# to be aesthetically quoted because they are evaled later.
+	func_quote_for_eval "$arg"
+	arg="$func_quote_for_eval_result"
+	;;
+      esac # arg
+
+      # Now actually substitute the argument into the commands.
+      if test -n "$arg"; then
+	func_append compile_command " $arg"
+	func_append finalize_command " $arg"
+      fi
+    done # argument parsing loop
+
+    test -n "$prev" && \
+      func_fatal_help "the \`$prevarg' option requires an argument"
+
+    if test "$export_dynamic" = yes && test -n "$export_dynamic_flag_spec"; then
+      eval arg=\"$export_dynamic_flag_spec\"
+      func_append compile_command " $arg"
+      func_append finalize_command " $arg"
+    fi
+
+    oldlibs=
+    # calculate the name of the file, without its directory
+    func_basename "$output"
+    outputname="$func_basename_result"
+    libobjs_save="$libobjs"
+
+    if test -n "$shlibpath_var"; then
+      # get the directories listed in $shlibpath_var
+      eval shlib_search_path=\`\$ECHO \"\${$shlibpath_var}\" \| \$SED \'s/:/ /g\'\`
+    else
+      shlib_search_path=
+    fi
+    eval sys_lib_search_path=\"$sys_lib_search_path_spec\"
+    eval sys_lib_dlsearch_path=\"$sys_lib_dlsearch_path_spec\"
+
+    func_dirname "$output" "/" ""
+    output_objdir="$func_dirname_result$objdir"
+    func_to_tool_file "$output_objdir/"
+    tool_output_objdir=$func_to_tool_file_result
+    # Create the object directory.
+    func_mkdir_p "$output_objdir"
+
+    # Determine the type of output
+    case $output in
+    "")
+      func_fatal_help "you must specify an output file"
+      ;;
+    *.$libext) linkmode=oldlib ;;
+    *.lo | *.$objext) linkmode=obj ;;
+    *.la) linkmode=lib ;;
+    *) linkmode=prog ;; # Anything else should be a program.
+    esac
+
+    specialdeplibs=
+
+    libs=
+    # Find all interdependent deplibs by searching for libraries
+    # that are linked more than once (e.g. -la -lb -la)
+    for deplib in $deplibs; do
+      if $opt_preserve_dup_deps ; then
+	case "$libs " in
+	*" $deplib "*) func_append specialdeplibs " $deplib" ;;
+	esac
+      fi
+      func_append libs " $deplib"
+    done
+
+    if test "$linkmode" = lib; then
+      libs="$predeps $libs $compiler_lib_search_path $postdeps"
+
+      # Compute libraries that are listed more than once in $predeps
+      # $postdeps and mark them as special (i.e., whose duplicates are
+      # not to be eliminated).
+      pre_post_deps=
+      if $opt_duplicate_compiler_generated_deps; then
+	for pre_post_dep in $predeps $postdeps; do
+	  case "$pre_post_deps " in
+	  *" $pre_post_dep "*) func_append specialdeplibs " $pre_post_deps" ;;
+	  esac
+	  func_append pre_post_deps " $pre_post_dep"
+	done
+      fi
+      pre_post_deps=
+    fi
+
+    deplibs=
+    newdependency_libs=
+    newlib_search_path=
+    need_relink=no # whether we're linking any uninstalled libtool libraries
+    notinst_deplibs= # not-installed libtool libraries
+    notinst_path= # paths that contain not-installed libtool libraries
+
+    case $linkmode in
+    lib)
+	passes="conv dlpreopen link"
+	for file in $dlfiles $dlprefiles; do
+	  case $file in
+	  *.la) ;;
+	  *)
+	    func_fatal_help "libraries can \`-dlopen' only libtool libraries: $file"
+	    ;;
+	  esac
+	done
+	;;
+    prog)
+	compile_deplibs=
+	finalize_deplibs=
+	alldeplibs=no
+	newdlfiles=
+	newdlprefiles=
+	passes="conv scan dlopen dlpreopen link"
+	;;
+    *)  passes="conv"
+	;;
+    esac
+
+    for pass in $passes; do
+      # The preopen pass in lib mode reverses $deplibs; put it back here
+      # so that -L comes before libs that need it for instance...
+      if test "$linkmode,$pass" = "lib,link"; then
+	## FIXME: Find the place where the list is rebuilt in the wrong
+	##        order, and fix it there properly
+        tmp_deplibs=
+	for deplib in $deplibs; do
+	  tmp_deplibs="$deplib $tmp_deplibs"
+	done
+	deplibs="$tmp_deplibs"
+      fi
+
+      if test "$linkmode,$pass" = "lib,link" ||
+	 test "$linkmode,$pass" = "prog,scan"; then
+	libs="$deplibs"
+	deplibs=
+      fi
+      if test "$linkmode" = prog; then
+	case $pass in
+	dlopen) libs="$dlfiles" ;;
+	dlpreopen) libs="$dlprefiles" ;;
+	link) libs="$deplibs %DEPLIBS% $dependency_libs" ;;
+	esac
+      fi
+      if test "$linkmode,$pass" = "lib,dlpreopen"; then
+	# Collect and forward deplibs of preopened libtool libs
+	for lib in $dlprefiles; do
+	  # Ignore non-libtool-libs
+	  dependency_libs=
+	  func_resolve_sysroot "$lib"
+	  case $lib in
+	  *.la)	func_source "$func_resolve_sysroot_result" ;;
+	  esac
+
+	  # Collect preopened libtool deplibs, except any this library
+	  # has declared as weak libs
+	  for deplib in $dependency_libs; do
+	    func_basename "$deplib"
+            deplib_base=$func_basename_result
+	    case " $weak_libs " in
+	    *" $deplib_base "*) ;;
+	    *) func_append deplibs " $deplib" ;;
+	    esac
+	  done
+	done
+	libs="$dlprefiles"
+      fi
+      if test "$pass" = dlopen; then
+	# Collect dlpreopened libraries
+	save_deplibs="$deplibs"
+	deplibs=
+      fi
+
+      for deplib in $libs; do
+	lib=
+	found=no
+	case $deplib in
+	-mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \
+        |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*)
+	  if test "$linkmode,$pass" = "prog,link"; then
+	    compile_deplibs="$deplib $compile_deplibs"
+	    finalize_deplibs="$deplib $finalize_deplibs"
+	  else
+	    func_append compiler_flags " $deplib"
+	    if test "$linkmode" = lib ; then
+		case "$new_inherited_linker_flags " in
+		    *" $deplib "*) ;;
+		    * ) func_append new_inherited_linker_flags " $deplib" ;;
+		esac
+	    fi
+	  fi
+	  continue
+	  ;;
+	-l*)
+	  if test "$linkmode" != lib && test "$linkmode" != prog; then
+	    func_warning "\`-l' is ignored for archives/objects"
+	    continue
+	  fi
+	  func_stripname '-l' '' "$deplib"
+	  name=$func_stripname_result
+	  if test "$linkmode" = lib; then
+	    searchdirs="$newlib_search_path $lib_search_path $compiler_lib_search_dirs $sys_lib_search_path $shlib_search_path"
+	  else
+	    searchdirs="$newlib_search_path $lib_search_path $sys_lib_search_path $shlib_search_path"
+	  fi
+	  for searchdir in $searchdirs; do
+	    for search_ext in .la $std_shrext .so .a; do
+	      # Search the libtool library
+	      lib="$searchdir/lib${name}${search_ext}"
+	      if test -f "$lib"; then
+		if test "$search_ext" = ".la"; then
+		  found=yes
+		else
+		  found=no
+		fi
+		break 2
+	      fi
+	    done
+	  done
+	  if test "$found" != yes; then
+	    # deplib doesn't seem to be a libtool library
+	    if test "$linkmode,$pass" = "prog,link"; then
+	      compile_deplibs="$deplib $compile_deplibs"
+	      finalize_deplibs="$deplib $finalize_deplibs"
+	    else
+	      deplibs="$deplib $deplibs"
+	      test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs"
+	    fi
+	    continue
+	  else # deplib is a libtool library
+	    # If $allow_libtool_libs_with_static_runtimes && $deplib is a stdlib,
+	    # We need to do some special things here, and not later.
+	    if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
+	      case " $predeps $postdeps " in
+	      *" $deplib "*)
+		if func_lalib_p "$lib"; then
+		  library_names=
+		  old_library=
+		  func_source "$lib"
+		  for l in $old_library $library_names; do
+		    ll="$l"
+		  done
+		  if test "X$ll" = "X$old_library" ; then # only static version available
+		    found=no
+		    func_dirname "$lib" "" "."
+		    ladir="$func_dirname_result"
+		    lib=$ladir/$old_library
+		    if test "$linkmode,$pass" = "prog,link"; then
+		      compile_deplibs="$deplib $compile_deplibs"
+		      finalize_deplibs="$deplib $finalize_deplibs"
+		    else
+		      deplibs="$deplib $deplibs"
+		      test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs"
+		    fi
+		    continue
+		  fi
+		fi
+		;;
+	      *) ;;
+	      esac
+	    fi
+	  fi
+	  ;; # -l
+	*.ltframework)
+	  if test "$linkmode,$pass" = "prog,link"; then
+	    compile_deplibs="$deplib $compile_deplibs"
+	    finalize_deplibs="$deplib $finalize_deplibs"
+	  else
+	    deplibs="$deplib $deplibs"
+	    if test "$linkmode" = lib ; then
+		case "$new_inherited_linker_flags " in
+		    *" $deplib "*) ;;
+		    * ) func_append new_inherited_linker_flags " $deplib" ;;
+		esac
+	    fi
+	  fi
+	  continue
+	  ;;
+	-L*)
+	  case $linkmode in
+	  lib)
+	    deplibs="$deplib $deplibs"
+	    test "$pass" = conv && continue
+	    newdependency_libs="$deplib $newdependency_libs"
+	    func_stripname '-L' '' "$deplib"
+	    func_resolve_sysroot "$func_stripname_result"
+	    func_append newlib_search_path " $func_resolve_sysroot_result"
+	    ;;
+	  prog)
+	    if test "$pass" = conv; then
+	      deplibs="$deplib $deplibs"
+	      continue
+	    fi
+	    if test "$pass" = scan; then
+	      deplibs="$deplib $deplibs"
+	    else
+	      compile_deplibs="$deplib $compile_deplibs"
+	      finalize_deplibs="$deplib $finalize_deplibs"
+	    fi
+	    func_stripname '-L' '' "$deplib"
+	    func_resolve_sysroot "$func_stripname_result"
+	    func_append newlib_search_path " $func_resolve_sysroot_result"
+	    ;;
+	  *)
+	    func_warning "\`-L' is ignored for archives/objects"
+	    ;;
+	  esac # linkmode
+	  continue
+	  ;; # -L
+	-R*)
+	  if test "$pass" = link; then
+	    func_stripname '-R' '' "$deplib"
+	    func_resolve_sysroot "$func_stripname_result"
+	    dir=$func_resolve_sysroot_result
+	    # Make sure the xrpath contains only unique directories.
+	    case "$xrpath " in
+	    *" $dir "*) ;;
+	    *) func_append xrpath " $dir" ;;
+	    esac
+	  fi
+	  deplibs="$deplib $deplibs"
+	  continue
+	  ;;
+	*.la)
+	  func_resolve_sysroot "$deplib"
+	  lib=$func_resolve_sysroot_result
+	  ;;
+	*.$libext)
+	  if test "$pass" = conv; then
+	    deplibs="$deplib $deplibs"
+	    continue
+	  fi
+	  case $linkmode in
+	  lib)
+	    # Linking convenience modules into shared libraries is allowed,
+	    # but linking other static libraries is non-portable.
+	    case " $dlpreconveniencelibs " in
+	    *" $deplib "*) ;;
+	    *)
+	      valid_a_lib=no
+	      case $deplibs_check_method in
+		match_pattern*)
+		  set dummy $deplibs_check_method; shift
+		  match_pattern_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"`
+		  if eval "\$ECHO \"$deplib\"" 2>/dev/null | $SED 10q \
+		    | $EGREP "$match_pattern_regex" > /dev/null; then
+		    valid_a_lib=yes
+		  fi
+		;;
+		pass_all)
+		  valid_a_lib=yes
+		;;
+	      esac
+	      if test "$valid_a_lib" != yes; then
+		echo
+		$ECHO "*** Warning: Trying to link with static lib archive $deplib."
+		echo "*** I have the capability to make that library automatically link in when"
+		echo "*** you link to this library.  But I can only do this if you have a"
+		echo "*** shared version of the library, which you do not appear to have"
+		echo "*** because the file extensions .$libext of this argument makes me believe"
+		echo "*** that it is just a static archive that I should not use here."
+	      else
+		echo
+		$ECHO "*** Warning: Linking the shared library $output against the"
+		$ECHO "*** static library $deplib is not portable!"
+		deplibs="$deplib $deplibs"
+	      fi
+	      ;;
+	    esac
+	    continue
+	    ;;
+	  prog)
+	    if test "$pass" != link; then
+	      deplibs="$deplib $deplibs"
+	    else
+	      compile_deplibs="$deplib $compile_deplibs"
+	      finalize_deplibs="$deplib $finalize_deplibs"
+	    fi
+	    continue
+	    ;;
+	  esac # linkmode
+	  ;; # *.$libext
+	*.lo | *.$objext)
+	  if test "$pass" = conv; then
+	    deplibs="$deplib $deplibs"
+	  elif test "$linkmode" = prog; then
+	    if test "$pass" = dlpreopen || test "$dlopen_support" != yes || test "$build_libtool_libs" = no; then
+	      # If there is no dlopen support or we're linking statically,
+	      # we need to preload.
+	      func_append newdlprefiles " $deplib"
+	      compile_deplibs="$deplib $compile_deplibs"
+	      finalize_deplibs="$deplib $finalize_deplibs"
+	    else
+	      func_append newdlfiles " $deplib"
+	    fi
+	  fi
+	  continue
+	  ;;
+	%DEPLIBS%)
+	  alldeplibs=yes
+	  continue
+	  ;;
+	esac # case $deplib
+
+	if test "$found" = yes || test -f "$lib"; then :
+	else
+	  func_fatal_error "cannot find the library \`$lib' or unhandled argument \`$deplib'"
+	fi
+
+	# Check to see that this really is a libtool archive.
+	func_lalib_unsafe_p "$lib" \
+	  || func_fatal_error "\`$lib' is not a valid libtool archive"
+
+	func_dirname "$lib" "" "."
+	ladir="$func_dirname_result"
+
+	dlname=
+	dlopen=
+	dlpreopen=
+	libdir=
+	library_names=
+	old_library=
+	inherited_linker_flags=
+	# If the library was installed with an old release of libtool,
+	# it will not redefine variables installed, or shouldnotlink
+	installed=yes
+	shouldnotlink=no
+	avoidtemprpath=
+
+
+	# Read the .la file
+	func_source "$lib"
+
+	# Convert "-framework foo" to "foo.ltframework"
+	if test -n "$inherited_linker_flags"; then
+	  tmp_inherited_linker_flags=`$ECHO "$inherited_linker_flags" | $SED 's/-framework \([^ $]*\)/\1.ltframework/g'`
+	  for tmp_inherited_linker_flag in $tmp_inherited_linker_flags; do
+	    case " $new_inherited_linker_flags " in
+	      *" $tmp_inherited_linker_flag "*) ;;
+	      *) func_append new_inherited_linker_flags " $tmp_inherited_linker_flag";;
+	    esac
+	  done
+	fi
+	dependency_libs=`$ECHO " $dependency_libs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'`
+	if test "$linkmode,$pass" = "lib,link" ||
+	   test "$linkmode,$pass" = "prog,scan" ||
+	   { test "$linkmode" != prog && test "$linkmode" != lib; }; then
+	  test -n "$dlopen" && func_append dlfiles " $dlopen"
+	  test -n "$dlpreopen" && func_append dlprefiles " $dlpreopen"
+	fi
+
+	if test "$pass" = conv; then
+	  # Only check for convenience libraries
+	  deplibs="$lib $deplibs"
+	  if test -z "$libdir"; then
+	    if test -z "$old_library"; then
+	      func_fatal_error "cannot find name of link library for \`$lib'"
+	    fi
+	    # It is a libtool convenience library, so add in its objects.
+	    func_append convenience " $ladir/$objdir/$old_library"
+	    func_append old_convenience " $ladir/$objdir/$old_library"
+	  elif test "$linkmode" != prog && test "$linkmode" != lib; then
+	    func_fatal_error "\`$lib' is not a convenience library"
+	  fi
+	  tmp_libs=
+	  for deplib in $dependency_libs; do
+	    deplibs="$deplib $deplibs"
+	    if $opt_preserve_dup_deps ; then
+	      case "$tmp_libs " in
+	      *" $deplib "*) func_append specialdeplibs " $deplib" ;;
+	      esac
+	    fi
+	    func_append tmp_libs " $deplib"
+	  done
+	  continue
+	fi # $pass = conv
+
+
+	# Get the name of the library we link against.
+	linklib=
+	if test -n "$old_library" &&
+	   { test "$prefer_static_libs" = yes ||
+	     test "$prefer_static_libs,$installed" = "built,no"; }; then
+	  linklib=$old_library
+	else
+	  for l in $old_library $library_names; do
+	    linklib="$l"
+	  done
+	fi
+	if test -z "$linklib"; then
+	  func_fatal_error "cannot find name of link library for \`$lib'"
+	fi
+
+	# This library was specified with -dlopen.
+	if test "$pass" = dlopen; then
+	  if test -z "$libdir"; then
+	    func_fatal_error "cannot -dlopen a convenience library: \`$lib'"
+	  fi
+	  if test -z "$dlname" ||
+	     test "$dlopen_support" != yes ||
+	     test "$build_libtool_libs" = no; then
+	    # If there is no dlname, no dlopen support or we're linking
+	    # statically, we need to preload.  We also need to preload any
+	    # dependent libraries so libltdl's deplib preloader doesn't
+	    # bomb out in the load deplibs phase.
+	    func_append dlprefiles " $lib $dependency_libs"
+	  else
+	    func_append newdlfiles " $lib"
+	  fi
+	  continue
+	fi # $pass = dlopen
+
+	# We need an absolute path.
+	case $ladir in
+	[\\/]* | [A-Za-z]:[\\/]*) abs_ladir="$ladir" ;;
+	*)
+	  abs_ladir=`cd "$ladir" && pwd`
+	  if test -z "$abs_ladir"; then
+	    func_warning "cannot determine absolute directory name of \`$ladir'"
+	    func_warning "passing it literally to the linker, although it might fail"
+	    abs_ladir="$ladir"
+	  fi
+	  ;;
+	esac
+	func_basename "$lib"
+	laname="$func_basename_result"
+
+	# Find the relevant object directory and library name.
+	if test "X$installed" = Xyes; then
+	  if test ! -f "$lt_sysroot$libdir/$linklib" && test -f "$abs_ladir/$linklib"; then
+	    func_warning "library \`$lib' was moved."
+	    dir="$ladir"
+	    absdir="$abs_ladir"
+	    libdir="$abs_ladir"
+	  else
+	    dir="$lt_sysroot$libdir"
+	    absdir="$lt_sysroot$libdir"
+	  fi
+	  test "X$hardcode_automatic" = Xyes && avoidtemprpath=yes
+	else
+	  if test ! -f "$ladir/$objdir/$linklib" && test -f "$abs_ladir/$linklib"; then
+	    dir="$ladir"
+	    absdir="$abs_ladir"
+	    # Remove this search path later
+	    func_append notinst_path " $abs_ladir"
+	  else
+	    dir="$ladir/$objdir"
+	    absdir="$abs_ladir/$objdir"
+	    # Remove this search path later
+	    func_append notinst_path " $abs_ladir"
+	  fi
+	fi # $installed = yes
+	func_stripname 'lib' '.la' "$laname"
+	name=$func_stripname_result
+
+	# This library was specified with -dlpreopen.
+	if test "$pass" = dlpreopen; then
+	  if test -z "$libdir" && test "$linkmode" = prog; then
+	    func_fatal_error "only libraries may -dlpreopen a convenience library: \`$lib'"
+	  fi
+	  case "$host" in
+	    # special handling for platforms with PE-DLLs.
+	    *cygwin* | *mingw* | *cegcc* )
+	      # Linker will automatically link against shared library if both
+	      # static and shared are present.  Therefore, ensure we extract
+	      # symbols from the import library if a shared library is present
+	      # (otherwise, the dlopen module name will be incorrect).  We do
+	      # this by putting the import library name into $newdlprefiles.
+	      # We recover the dlopen module name by 'saving' the la file
+	      # name in a special purpose variable, and (later) extracting the
+	      # dlname from the la file.
+	      if test -n "$dlname"; then
+	        func_tr_sh "$dir/$linklib"
+	        eval "libfile_$func_tr_sh_result=\$abs_ladir/\$laname"
+	        func_append newdlprefiles " $dir/$linklib"
+	      else
+	        func_append newdlprefiles " $dir/$old_library"
+	        # Keep a list of preopened convenience libraries to check
+	        # that they are being used correctly in the link pass.
+	        test -z "$libdir" && \
+	          func_append dlpreconveniencelibs " $dir/$old_library"
+	      fi
+	    ;;
+	    * )
+	      # Prefer using a static library (so that no silly _DYNAMIC symbols
+	      # are required to link).
+	      if test -n "$old_library"; then
+	        func_append newdlprefiles " $dir/$old_library"
+	        # Keep a list of preopened convenience libraries to check
+	        # that they are being used correctly in the link pass.
+	        test -z "$libdir" && \
+	          func_append dlpreconveniencelibs " $dir/$old_library"
+	      # Otherwise, use the dlname, so that lt_dlopen finds it.
+	      elif test -n "$dlname"; then
+	        func_append newdlprefiles " $dir/$dlname"
+	      else
+	        func_append newdlprefiles " $dir/$linklib"
+	      fi
+	    ;;
+	  esac
+	fi # $pass = dlpreopen
+
+	if test -z "$libdir"; then
+	  # Link the convenience library
+	  if test "$linkmode" = lib; then
+	    deplibs="$dir/$old_library $deplibs"
+	  elif test "$linkmode,$pass" = "prog,link"; then
+	    compile_deplibs="$dir/$old_library $compile_deplibs"
+	    finalize_deplibs="$dir/$old_library $finalize_deplibs"
+	  else
+	    deplibs="$lib $deplibs" # used for prog,scan pass
+	  fi
+	  continue
+	fi
+
+
+	if test "$linkmode" = prog && test "$pass" != link; then
+	  func_append newlib_search_path " $ladir"
+	  deplibs="$lib $deplibs"
+
+	  linkalldeplibs=no
+	  if test "$link_all_deplibs" != no || test -z "$library_names" ||
+	     test "$build_libtool_libs" = no; then
+	    linkalldeplibs=yes
+	  fi
+
+	  tmp_libs=
+	  for deplib in $dependency_libs; do
+	    case $deplib in
+	    -L*) func_stripname '-L' '' "$deplib"
+	         func_resolve_sysroot "$func_stripname_result"
+	         func_append newlib_search_path " $func_resolve_sysroot_result"
+		 ;;
+	    esac
+	    # Need to link against all dependency_libs?
+	    if test "$linkalldeplibs" = yes; then
+	      deplibs="$deplib $deplibs"
+	    else
+	      # Need to hardcode shared library paths
+	      # or/and link against static libraries
+	      newdependency_libs="$deplib $newdependency_libs"
+	    fi
+	    if $opt_preserve_dup_deps ; then
+	      case "$tmp_libs " in
+	      *" $deplib "*) func_append specialdeplibs " $deplib" ;;
+	      esac
+	    fi
+	    func_append tmp_libs " $deplib"
+	  done # for deplib
+	  continue
+	fi # $linkmode = prog...
+
+	if test "$linkmode,$pass" = "prog,link"; then
+	  if test -n "$library_names" &&
+	     { { test "$prefer_static_libs" = no ||
+	         test "$prefer_static_libs,$installed" = "built,yes"; } ||
+	       test -z "$old_library"; }; then
+	    # We need to hardcode the library path
+	    if test -n "$shlibpath_var" && test -z "$avoidtemprpath" ; then
+	      # Make sure the rpath contains only unique directories.
+	      case "$temp_rpath:" in
+	      *"$absdir:"*) ;;
+	      *) func_append temp_rpath "$absdir:" ;;
+	      esac
+	    fi
+
+	    # Hardcode the library path.
+	    # Skip directories that are in the system default run-time
+	    # search path.
+	    case " $sys_lib_dlsearch_path " in
+	    *" $absdir "*) ;;
+	    *)
+	      case "$compile_rpath " in
+	      *" $absdir "*) ;;
+	      *) func_append compile_rpath " $absdir" ;;
+	      esac
+	      ;;
+	    esac
+	    case " $sys_lib_dlsearch_path " in
+	    *" $libdir "*) ;;
+	    *)
+	      case "$finalize_rpath " in
+	      *" $libdir "*) ;;
+	      *) func_append finalize_rpath " $libdir" ;;
+	      esac
+	      ;;
+	    esac
+	  fi # $linkmode,$pass = prog,link...
+
+	  if test "$alldeplibs" = yes &&
+	     { test "$deplibs_check_method" = pass_all ||
+	       { test "$build_libtool_libs" = yes &&
+		 test -n "$library_names"; }; }; then
+	    # We only need to search for static libraries
+	    continue
+	  fi
+	fi
+
+	link_static=no # Whether the deplib will be linked statically
+	use_static_libs=$prefer_static_libs
+	if test "$use_static_libs" = built && test "$installed" = yes; then
+	  use_static_libs=no
+	fi
+	if test -n "$library_names" &&
+	   { test "$use_static_libs" = no || test -z "$old_library"; }; then
+	  case $host in
+	  *cygwin* | *mingw* | *cegcc*)
+	      # No point in relinking DLLs because paths are not encoded
+	      func_append notinst_deplibs " $lib"
+	      need_relink=no
+	    ;;
+	  *)
+	    if test "$installed" = no; then
+	      func_append notinst_deplibs " $lib"
+	      need_relink=yes
+	    fi
+	    ;;
+	  esac
+	  # This is a shared library
+
+	  # Warn about portability, can't link against -module's on some
+	  # systems (darwin).  Don't bleat about dlopened modules though!
+	  dlopenmodule=""
+	  for dlpremoduletest in $dlprefiles; do
+	    if test "X$dlpremoduletest" = "X$lib"; then
+	      dlopenmodule="$dlpremoduletest"
+	      break
+	    fi
+	  done
+	  if test -z "$dlopenmodule" && test "$shouldnotlink" = yes && test "$pass" = link; then
+	    echo
+	    if test "$linkmode" = prog; then
+	      $ECHO "*** Warning: Linking the executable $output against the loadable module"
+	    else
+	      $ECHO "*** Warning: Linking the shared library $output against the loadable module"
+	    fi
+	    $ECHO "*** $linklib is not portable!"
+	  fi
+	  if test "$linkmode" = lib &&
+	     test "$hardcode_into_libs" = yes; then
+	    # Hardcode the library path.
+	    # Skip directories that are in the system default run-time
+	    # search path.
+	    case " $sys_lib_dlsearch_path " in
+	    *" $absdir "*) ;;
+	    *)
+	      case "$compile_rpath " in
+	      *" $absdir "*) ;;
+	      *) func_append compile_rpath " $absdir" ;;
+	      esac
+	      ;;
+	    esac
+	    case " $sys_lib_dlsearch_path " in
+	    *" $libdir "*) ;;
+	    *)
+	      case "$finalize_rpath " in
+	      *" $libdir "*) ;;
+	      *) func_append finalize_rpath " $libdir" ;;
+	      esac
+	      ;;
+	    esac
+	  fi
+
+	  if test -n "$old_archive_from_expsyms_cmds"; then
+	    # figure out the soname
+	    set dummy $library_names
+	    shift
+	    realname="$1"
+	    shift
+	    libname=`eval "\\$ECHO \"$libname_spec\""`
+	    # use dlname if we got it. it's perfectly good, no?
+	    if test -n "$dlname"; then
+	      soname="$dlname"
+	    elif test -n "$soname_spec"; then
+	      # bleh windows
+	      case $host in
+	      *cygwin* | mingw* | *cegcc*)
+	        func_arith $current - $age
+		major=$func_arith_result
+		versuffix="-$major"
+		;;
+	      esac
+	      eval soname=\"$soname_spec\"
+	    else
+	      soname="$realname"
+	    fi
+
+	    # Make a new name for the extract_expsyms_cmds to use
+	    soroot="$soname"
+	    func_basename "$soroot"
+	    soname="$func_basename_result"
+	    func_stripname 'lib' '.dll' "$soname"
+	    newlib=libimp-$func_stripname_result.a
+
+	    # If the library has no export list, then create one now
+	    if test -f "$output_objdir/$soname-def"; then :
+	    else
+	      func_verbose "extracting exported symbol list from \`$soname'"
+	      func_execute_cmds "$extract_expsyms_cmds" 'exit $?'
+	    fi
+
+	    # Create $newlib
+	    if test -f "$output_objdir/$newlib"; then :; else
+	      func_verbose "generating import library for \`$soname'"
+	      func_execute_cmds "$old_archive_from_expsyms_cmds" 'exit $?'
+	    fi
+	    # make sure the library variables are pointing to the new library
+	    dir=$output_objdir
+	    linklib=$newlib
+	  fi # test -n "$old_archive_from_expsyms_cmds"
+
+	  if test "$linkmode" = prog || test "$opt_mode" != relink; then
+	    add_shlibpath=
+	    add_dir=
+	    add=
+	    lib_linked=yes
+	    case $hardcode_action in
+	    immediate | unsupported)
+	      if test "$hardcode_direct" = no; then
+		add="$dir/$linklib"
+		case $host in
+		  *-*-sco3.2v5.0.[024]*) add_dir="-L$dir" ;;
+		  *-*-sysv4*uw2*) add_dir="-L$dir" ;;
+		  *-*-sysv5OpenUNIX* | *-*-sysv5UnixWare7.[01].[10]* | \
+		    *-*-unixware7*) add_dir="-L$dir" ;;
+		  *-*-darwin* )
+		    # if the lib is a (non-dlopened) module then we can not
+		    # link against it, someone is ignoring the earlier warnings
+		    if /usr/bin/file -L $add 2> /dev/null |
+			 $GREP ": [^:]* bundle" >/dev/null ; then
+		      if test "X$dlopenmodule" != "X$lib"; then
+			$ECHO "*** Warning: lib $linklib is a module, not a shared library"
+			if test -z "$old_library" ; then
+			  echo
+			  echo "*** And there doesn't seem to be a static archive available"
+			  echo "*** The link will probably fail, sorry"
+			else
+			  add="$dir/$old_library"
+			fi
+		      elif test -n "$old_library"; then
+			add="$dir/$old_library"
+		      fi
+		    fi
+		esac
+	      elif test "$hardcode_minus_L" = no; then
+		case $host in
+		*-*-sunos*) add_shlibpath="$dir" ;;
+		esac
+		add_dir="-L$dir"
+		add="-l$name"
+	      elif test "$hardcode_shlibpath_var" = no; then
+		add_shlibpath="$dir"
+		add="-l$name"
+	      else
+		lib_linked=no
+	      fi
+	      ;;
+	    relink)
+	      if test "$hardcode_direct" = yes &&
+	         test "$hardcode_direct_absolute" = no; then
+		add="$dir/$linklib"
+	      elif test "$hardcode_minus_L" = yes; then
+		add_dir="-L$absdir"
+		# Try looking first in the location we're being installed to.
+		if test -n "$inst_prefix_dir"; then
+		  case $libdir in
+		    [\\/]*)
+		      func_append add_dir " -L$inst_prefix_dir$libdir"
+		      ;;
+		  esac
+		fi
+		add="-l$name"
+	      elif test "$hardcode_shlibpath_var" = yes; then
+		add_shlibpath="$dir"
+		add="-l$name"
+	      else
+		lib_linked=no
+	      fi
+	      ;;
+	    *) lib_linked=no ;;
+	    esac
+
+	    if test "$lib_linked" != yes; then
+	      func_fatal_configuration "unsupported hardcode properties"
+	    fi
+
+	    if test -n "$add_shlibpath"; then
+	      case :$compile_shlibpath: in
+	      *":$add_shlibpath:"*) ;;
+	      *) func_append compile_shlibpath "$add_shlibpath:" ;;
+	      esac
+	    fi
+	    if test "$linkmode" = prog; then
+	      test -n "$add_dir" && compile_deplibs="$add_dir $compile_deplibs"
+	      test -n "$add" && compile_deplibs="$add $compile_deplibs"
+	    else
+	      test -n "$add_dir" && deplibs="$add_dir $deplibs"
+	      test -n "$add" && deplibs="$add $deplibs"
+	      if test "$hardcode_direct" != yes &&
+		 test "$hardcode_minus_L" != yes &&
+		 test "$hardcode_shlibpath_var" = yes; then
+		case :$finalize_shlibpath: in
+		*":$libdir:"*) ;;
+		*) func_append finalize_shlibpath "$libdir:" ;;
+		esac
+	      fi
+	    fi
+	  fi
+
+	  if test "$linkmode" = prog || test "$opt_mode" = relink; then
+	    add_shlibpath=
+	    add_dir=
+	    add=
+	    # Finalize command for both is simple: just hardcode it.
+	    if test "$hardcode_direct" = yes &&
+	       test "$hardcode_direct_absolute" = no; then
+	      add="$libdir/$linklib"
+	    elif test "$hardcode_minus_L" = yes; then
+	      add_dir="-L$libdir"
+	      add="-l$name"
+	    elif test "$hardcode_shlibpath_var" = yes; then
+	      case :$finalize_shlibpath: in
+	      *":$libdir:"*) ;;
+	      *) func_append finalize_shlibpath "$libdir:" ;;
+	      esac
+	      add="-l$name"
+	    elif test "$hardcode_automatic" = yes; then
+	      if test -n "$inst_prefix_dir" &&
+		 test -f "$inst_prefix_dir$libdir/$linklib" ; then
+		add="$inst_prefix_dir$libdir/$linklib"
+	      else
+		add="$libdir/$linklib"
+	      fi
+	    else
+	      # We cannot seem to hardcode it, guess we'll fake it.
+	      add_dir="-L$libdir"
+	      # Try looking first in the location we're being installed to.
+	      if test -n "$inst_prefix_dir"; then
+		case $libdir in
+		  [\\/]*)
+		    func_append add_dir " -L$inst_prefix_dir$libdir"
+		    ;;
+		esac
+	      fi
+	      add="-l$name"
+	    fi
+
+	    if test "$linkmode" = prog; then
+	      test -n "$add_dir" && finalize_deplibs="$add_dir $finalize_deplibs"
+	      test -n "$add" && finalize_deplibs="$add $finalize_deplibs"
+	    else
+	      test -n "$add_dir" && deplibs="$add_dir $deplibs"
+	      test -n "$add" && deplibs="$add $deplibs"
+	    fi
+	  fi
+	elif test "$linkmode" = prog; then
+	  # Here we assume that one of hardcode_direct or hardcode_minus_L
+	  # is not unsupported.  This is valid on all known static and
+	  # shared platforms.
+	  if test "$hardcode_direct" != unsupported; then
+	    test -n "$old_library" && linklib="$old_library"
+	    compile_deplibs="$dir/$linklib $compile_deplibs"
+	    finalize_deplibs="$dir/$linklib $finalize_deplibs"
+	  else
+	    compile_deplibs="-l$name -L$dir $compile_deplibs"
+	    finalize_deplibs="-l$name -L$dir $finalize_deplibs"
+	  fi
+	elif test "$build_libtool_libs" = yes; then
+	  # Not a shared library
+	  if test "$deplibs_check_method" != pass_all; then
+	    # We're trying link a shared library against a static one
+	    # but the system doesn't support it.
+
+	    # Just print a warning and add the library to dependency_libs so
+	    # that the program can be linked against the static library.
+	    echo
+	    $ECHO "*** Warning: This system can not link to static lib archive $lib."
+	    echo "*** I have the capability to make that library automatically link in when"
+	    echo "*** you link to this library.  But I can only do this if you have a"
+	    echo "*** shared version of the library, which you do not appear to have."
+	    if test "$module" = yes; then
+	      echo "*** But as you try to build a module library, libtool will still create "
+	      echo "*** a static module, that should work as long as the dlopening application"
+	      echo "*** is linked with the -dlopen flag to resolve symbols at runtime."
+	      if test -z "$global_symbol_pipe"; then
+		echo
+		echo "*** However, this would only work if libtool was able to extract symbol"
+		echo "*** lists from a program, using \`nm' or equivalent, but libtool could"
+		echo "*** not find such a program.  So, this module is probably useless."
+		echo "*** \`nm' from GNU binutils and a full rebuild may help."
+	      fi
+	      if test "$build_old_libs" = no; then
+		build_libtool_libs=module
+		build_old_libs=yes
+	      else
+		build_libtool_libs=no
+	      fi
+	    fi
+	  else
+	    deplibs="$dir/$old_library $deplibs"
+	    link_static=yes
+	  fi
+	fi # link shared/static library?
+
+	if test "$linkmode" = lib; then
+	  if test -n "$dependency_libs" &&
+	     { test "$hardcode_into_libs" != yes ||
+	       test "$build_old_libs" = yes ||
+	       test "$link_static" = yes; }; then
+	    # Extract -R from dependency_libs
+	    temp_deplibs=
+	    for libdir in $dependency_libs; do
+	      case $libdir in
+	      -R*) func_stripname '-R' '' "$libdir"
+	           temp_xrpath=$func_stripname_result
+		   case " $xrpath " in
+		   *" $temp_xrpath "*) ;;
+		   *) func_append xrpath " $temp_xrpath";;
+		   esac;;
+	      *) func_append temp_deplibs " $libdir";;
+	      esac
+	    done
+	    dependency_libs="$temp_deplibs"
+	  fi
+
+	  func_append newlib_search_path " $absdir"
+	  # Link against this library
+	  test "$link_static" = no && newdependency_libs="$abs_ladir/$laname $newdependency_libs"
+	  # ... and its dependency_libs
+	  tmp_libs=
+	  for deplib in $dependency_libs; do
+	    newdependency_libs="$deplib $newdependency_libs"
+	    case $deplib in
+              -L*) func_stripname '-L' '' "$deplib"
+                   func_resolve_sysroot "$func_stripname_result";;
+              *) func_resolve_sysroot "$deplib" ;;
+            esac
+	    if $opt_preserve_dup_deps ; then
+	      case "$tmp_libs " in
+	      *" $func_resolve_sysroot_result "*)
+                func_append specialdeplibs " $func_resolve_sysroot_result" ;;
+	      esac
+	    fi
+	    func_append tmp_libs " $func_resolve_sysroot_result"
+	  done
+
+	  if test "$link_all_deplibs" != no; then
+	    # Add the search paths of all dependency libraries
+	    for deplib in $dependency_libs; do
+	      path=
+	      case $deplib in
+	      -L*) path="$deplib" ;;
+	      *.la)
+	        func_resolve_sysroot "$deplib"
+	        deplib=$func_resolve_sysroot_result
+	        func_dirname "$deplib" "" "."
+		dir=$func_dirname_result
+		# We need an absolute path.
+		case $dir in
+		[\\/]* | [A-Za-z]:[\\/]*) absdir="$dir" ;;
+		*)
+		  absdir=`cd "$dir" && pwd`
+		  if test -z "$absdir"; then
+		    func_warning "cannot determine absolute directory name of \`$dir'"
+		    absdir="$dir"
+		  fi
+		  ;;
+		esac
+		if $GREP "^installed=no" $deplib > /dev/null; then
+		case $host in
+		*-*-darwin*)
+		  depdepl=
+		  eval deplibrary_names=`${SED} -n -e 's/^library_names=\(.*\)$/\1/p' $deplib`
+		  if test -n "$deplibrary_names" ; then
+		    for tmp in $deplibrary_names ; do
+		      depdepl=$tmp
+		    done
+		    if test -f "$absdir/$objdir/$depdepl" ; then
+		      depdepl="$absdir/$objdir/$depdepl"
+		      darwin_install_name=`${OTOOL} -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'`
+                      if test -z "$darwin_install_name"; then
+                          darwin_install_name=`${OTOOL64} -L $depdepl  | awk '{if (NR == 2) {print $1;exit}}'`
+                      fi
+		      func_append compiler_flags " ${wl}-dylib_file ${wl}${darwin_install_name}:${depdepl}"
+		      func_append linker_flags " -dylib_file ${darwin_install_name}:${depdepl}"
+		      path=
+		    fi
+		  fi
+		  ;;
+		*)
+		  path="-L$absdir/$objdir"
+		  ;;
+		esac
+		else
+		  eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $deplib`
+		  test -z "$libdir" && \
+		    func_fatal_error "\`$deplib' is not a valid libtool archive"
+		  test "$absdir" != "$libdir" && \
+		    func_warning "\`$deplib' seems to be moved"
+
+		  path="-L$absdir"
+		fi
+		;;
+	      esac
+	      case " $deplibs " in
+	      *" $path "*) ;;
+	      *) deplibs="$path $deplibs" ;;
+	      esac
+	    done
+	  fi # link_all_deplibs != no
+	fi # linkmode = lib
+      done # for deplib in $libs
+      if test "$pass" = link; then
+	if test "$linkmode" = "prog"; then
+	  compile_deplibs="$new_inherited_linker_flags $compile_deplibs"
+	  finalize_deplibs="$new_inherited_linker_flags $finalize_deplibs"
+	else
+	  compiler_flags="$compiler_flags "`$ECHO " $new_inherited_linker_flags" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'`
+	fi
+      fi
+      dependency_libs="$newdependency_libs"
+      if test "$pass" = dlpreopen; then
+	# Link the dlpreopened libraries before other libraries
+	for deplib in $save_deplibs; do
+	  deplibs="$deplib $deplibs"
+	done
+      fi
+      if test "$pass" != dlopen; then
+	if test "$pass" != conv; then
+	  # Make sure lib_search_path contains only unique directories.
+	  lib_search_path=
+	  for dir in $newlib_search_path; do
+	    case "$lib_search_path " in
+	    *" $dir "*) ;;
+	    *) func_append lib_search_path " $dir" ;;
+	    esac
+	  done
+	  newlib_search_path=
+	fi
+
+	if test "$linkmode,$pass" != "prog,link"; then
+	  vars="deplibs"
+	else
+	  vars="compile_deplibs finalize_deplibs"
+	fi
+	for var in $vars dependency_libs; do
+	  # Add libraries to $var in reverse order
+	  eval tmp_libs=\"\$$var\"
+	  new_libs=
+	  for deplib in $tmp_libs; do
+	    # FIXME: Pedantically, this is the right thing to do, so
+	    #        that some nasty dependency loop isn't accidentally
+	    #        broken:
+	    #new_libs="$deplib $new_libs"
+	    # Pragmatically, this seems to cause very few problems in
+	    # practice:
+	    case $deplib in
+	    -L*) new_libs="$deplib $new_libs" ;;
+	    -R*) ;;
+	    *)
+	      # And here is the reason: when a library appears more
+	      # than once as an explicit dependence of a library, or
+	      # is implicitly linked in more than once by the
+	      # compiler, it is considered special, and multiple
+	      # occurrences thereof are not removed.  Compare this
+	      # with having the same library being listed as a
+	      # dependency of multiple other libraries: in this case,
+	      # we know (pedantically, we assume) the library does not
+	      # need to be listed more than once, so we keep only the
+	      # last copy.  This is not always right, but it is rare
+	      # enough that we require users that really mean to play
+	      # such unportable linking tricks to link the library
+	      # using -Wl,-lname, so that libtool does not consider it
+	      # for duplicate removal.
+	      case " $specialdeplibs " in
+	      *" $deplib "*) new_libs="$deplib $new_libs" ;;
+	      *)
+		case " $new_libs " in
+		*" $deplib "*) ;;
+		*) new_libs="$deplib $new_libs" ;;
+		esac
+		;;
+	      esac
+	      ;;
+	    esac
+	  done
+	  tmp_libs=
+	  for deplib in $new_libs; do
+	    case $deplib in
+	    -L*)
+	      case " $tmp_libs " in
+	      *" $deplib "*) ;;
+	      *) func_append tmp_libs " $deplib" ;;
+	      esac
+	      ;;
+	    *) func_append tmp_libs " $deplib" ;;
+	    esac
+	  done
+	  eval $var=\"$tmp_libs\"
+	done # for var
+      fi
+      # Last step: remove runtime libs from dependency_libs
+      # (they stay in deplibs)
+      tmp_libs=
+      for i in $dependency_libs ; do
+	case " $predeps $postdeps $compiler_lib_search_path " in
+	*" $i "*)
+	  i=""
+	  ;;
+	esac
+	if test -n "$i" ; then
+	  func_append tmp_libs " $i"
+	fi
+      done
+      dependency_libs=$tmp_libs
+    done # for pass
+    if test "$linkmode" = prog; then
+      dlfiles="$newdlfiles"
+    fi
+    if test "$linkmode" = prog || test "$linkmode" = lib; then
+      dlprefiles="$newdlprefiles"
+    fi
+
+    case $linkmode in
+    oldlib)
+      if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then
+	func_warning "\`-dlopen' is ignored for archives"
+      fi
+
+      case " $deplibs" in
+      *\ -l* | *\ -L*)
+	func_warning "\`-l' and \`-L' are ignored for archives" ;;
+      esac
+
+      test -n "$rpath" && \
+	func_warning "\`-rpath' is ignored for archives"
+
+      test -n "$xrpath" && \
+	func_warning "\`-R' is ignored for archives"
+
+      test -n "$vinfo" && \
+	func_warning "\`-version-info/-version-number' is ignored for archives"
+
+      test -n "$release" && \
+	func_warning "\`-release' is ignored for archives"
+
+      test -n "$export_symbols$export_symbols_regex" && \
+	func_warning "\`-export-symbols' is ignored for archives"
+
+      # Now set the variables for building old libraries.
+      build_libtool_libs=no
+      oldlibs="$output"
+      func_append objs "$old_deplibs"
+      ;;
+
+    lib)
+      # Make sure we only generate libraries of the form `libNAME.la'.
+      case $outputname in
+      lib*)
+	func_stripname 'lib' '.la' "$outputname"
+	name=$func_stripname_result
+	eval shared_ext=\"$shrext_cmds\"
+	eval libname=\"$libname_spec\"
+	;;
+      *)
+	test "$module" = no && \
+	  func_fatal_help "libtool library \`$output' must begin with \`lib'"
+
+	if test "$need_lib_prefix" != no; then
+	  # Add the "lib" prefix for modules if required
+	  func_stripname '' '.la' "$outputname"
+	  name=$func_stripname_result
+	  eval shared_ext=\"$shrext_cmds\"
+	  eval libname=\"$libname_spec\"
+	else
+	  func_stripname '' '.la' "$outputname"
+	  libname=$func_stripname_result
+	fi
+	;;
+      esac
+
+      if test -n "$objs"; then
+	if test "$deplibs_check_method" != pass_all; then
+	  func_fatal_error "cannot build libtool library \`$output' from non-libtool objects on this host:$objs"
+	else
+	  echo
+	  $ECHO "*** Warning: Linking the shared library $output against the non-libtool"
+	  $ECHO "*** objects $objs is not portable!"
+	  func_append libobjs " $objs"
+	fi
+      fi
+
+      test "$dlself" != no && \
+	func_warning "\`-dlopen self' is ignored for libtool libraries"
+
+      set dummy $rpath
+      shift
+      test "$#" -gt 1 && \
+	func_warning "ignoring multiple \`-rpath's for a libtool library"
+
+      install_libdir="$1"
+
+      oldlibs=
+      if test -z "$rpath"; then
+	if test "$build_libtool_libs" = yes; then
+	  # Building a libtool convenience library.
+	  # Some compilers have problems with a `.al' extension so
+	  # convenience libraries should have the same extension an
+	  # archive normally would.
+	  oldlibs="$output_objdir/$libname.$libext $oldlibs"
+	  build_libtool_libs=convenience
+	  build_old_libs=yes
+	fi
+
+	test -n "$vinfo" && \
+	  func_warning "\`-version-info/-version-number' is ignored for convenience libraries"
+
+	test -n "$release" && \
+	  func_warning "\`-release' is ignored for convenience libraries"
+      else
+
+	# Parse the version information argument.
+	save_ifs="$IFS"; IFS=':'
+	set dummy $vinfo 0 0 0
+	shift
+	IFS="$save_ifs"
+
+	test -n "$7" && \
+	  func_fatal_help "too many parameters to \`-version-info'"
+
+	# convert absolute version numbers to libtool ages
+	# this retains compatibility with .la files and attempts
+	# to make the code below a bit more comprehensible
+
+	case $vinfo_number in
+	yes)
+	  number_major="$1"
+	  number_minor="$2"
+	  number_revision="$3"
+	  #
+	  # There are really only two kinds -- those that
+	  # use the current revision as the major version
+	  # and those that subtract age and use age as
+	  # a minor version.  But, then there is irix
+	  # which has an extra 1 added just for fun
+	  #
+	  case $version_type in
+	  # correct linux to gnu/linux during the next big refactor
+	  darwin|linux|osf|windows|none)
+	    func_arith $number_major + $number_minor
+	    current=$func_arith_result
+	    age="$number_minor"
+	    revision="$number_revision"
+	    ;;
+	  freebsd-aout|freebsd-elf|qnx|sunos)
+	    current="$number_major"
+	    revision="$number_minor"
+	    age="0"
+	    ;;
+	  irix|nonstopux)
+	    func_arith $number_major + $number_minor
+	    current=$func_arith_result
+	    age="$number_minor"
+	    revision="$number_minor"
+	    lt_irix_increment=no
+	    ;;
+	  esac
+	  ;;
+	no)
+	  current="$1"
+	  revision="$2"
+	  age="$3"
+	  ;;
+	esac
+
+	# Check that each of the things are valid numbers.
+	case $current in
+	0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;
+	*)
+	  func_error "CURRENT \`$current' must be a nonnegative integer"
+	  func_fatal_error "\`$vinfo' is not valid version information"
+	  ;;
+	esac
+
+	case $revision in
+	0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;
+	*)
+	  func_error "REVISION \`$revision' must be a nonnegative integer"
+	  func_fatal_error "\`$vinfo' is not valid version information"
+	  ;;
+	esac
+
+	case $age in
+	0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;
+	*)
+	  func_error "AGE \`$age' must be a nonnegative integer"
+	  func_fatal_error "\`$vinfo' is not valid version information"
+	  ;;
+	esac
+
+	if test "$age" -gt "$current"; then
+	  func_error "AGE \`$age' is greater than the current interface number \`$current'"
+	  func_fatal_error "\`$vinfo' is not valid version information"
+	fi
+
+	# Calculate the version variables.
+	major=
+	versuffix=
+	verstring=
+	case $version_type in
+	none) ;;
+
+	darwin)
+	  # Like Linux, but with the current version available in
+	  # verstring for coding it into the library header
+	  func_arith $current - $age
+	  major=.$func_arith_result
+	  versuffix="$major.$age.$revision"
+	  # Darwin ld doesn't like 0 for these options...
+	  func_arith $current + 1
+	  minor_current=$func_arith_result
+	  xlcverstring="${wl}-compatibility_version ${wl}$minor_current ${wl}-current_version ${wl}$minor_current.$revision"
+	  verstring="-compatibility_version $minor_current -current_version $minor_current.$revision"
+	  ;;
+
+	freebsd-aout)
+	  major=".$current"
+	  versuffix=".$current.$revision";
+	  ;;
+
+	freebsd-elf)
+	  major=".$current"
+	  versuffix=".$current"
+	  ;;
+
+	irix | nonstopux)
+	  if test "X$lt_irix_increment" = "Xno"; then
+	    func_arith $current - $age
+	  else
+	    func_arith $current - $age + 1
+	  fi
+	  major=$func_arith_result
+
+	  case $version_type in
+	    nonstopux) verstring_prefix=nonstopux ;;
+	    *)         verstring_prefix=sgi ;;
+	  esac
+	  verstring="$verstring_prefix$major.$revision"
+
+	  # Add in all the interfaces that we are compatible with.
+	  loop=$revision
+	  while test "$loop" -ne 0; do
+	    func_arith $revision - $loop
+	    iface=$func_arith_result
+	    func_arith $loop - 1
+	    loop=$func_arith_result
+	    verstring="$verstring_prefix$major.$iface:$verstring"
+	  done
+
+	  # Before this point, $major must not contain `.'.
+	  major=.$major
+	  versuffix="$major.$revision"
+	  ;;
+
+	linux) # correct to gnu/linux during the next big refactor
+	  func_arith $current - $age
+	  major=.$func_arith_result
+	  versuffix="$major.$age.$revision"
+	  ;;
+
+	osf)
+	  func_arith $current - $age
+	  major=.$func_arith_result
+	  versuffix=".$current.$age.$revision"
+	  verstring="$current.$age.$revision"
+
+	  # Add in all the interfaces that we are compatible with.
+	  loop=$age
+	  while test "$loop" -ne 0; do
+	    func_arith $current - $loop
+	    iface=$func_arith_result
+	    func_arith $loop - 1
+	    loop=$func_arith_result
+	    verstring="$verstring:${iface}.0"
+	  done
+
+	  # Make executables depend on our current version.
+	  func_append verstring ":${current}.0"
+	  ;;
+
+	qnx)
+	  major=".$current"
+	  versuffix=".$current"
+	  ;;
+
+	sunos)
+	  major=".$current"
+	  versuffix=".$current.$revision"
+	  ;;
+
+	windows)
+	  # Use '-' rather than '.', since we only want one
+	  # extension on DOS 8.3 filesystems.
+	  func_arith $current - $age
+	  major=$func_arith_result
+	  versuffix="-$major"
+	  ;;
+
+	*)
+	  func_fatal_configuration "unknown library version type \`$version_type'"
+	  ;;
+	esac
+
+	# Clear the version info if we defaulted, and they specified a release.
+	if test -z "$vinfo" && test -n "$release"; then
+	  major=
+	  case $version_type in
+	  darwin)
+	    # we can't check for "0.0" in archive_cmds due to quoting
+	    # problems, so we reset it completely
+	    verstring=
+	    ;;
+	  *)
+	    verstring="0.0"
+	    ;;
+	  esac
+	  if test "$need_version" = no; then
+	    versuffix=
+	  else
+	    versuffix=".0.0"
+	  fi
+	fi
+
+	# Remove version info from name if versioning should be avoided
+	if test "$avoid_version" = yes && test "$need_version" = no; then
+	  major=
+	  versuffix=
+	  verstring=""
+	fi
+
+	# Check to see if the archive will have undefined symbols.
+	if test "$allow_undefined" = yes; then
+	  if test "$allow_undefined_flag" = unsupported; then
+	    func_warning "undefined symbols not allowed in $host shared libraries"
+	    build_libtool_libs=no
+	    build_old_libs=yes
+	  fi
+	else
+	  # Don't allow undefined symbols.
+	  allow_undefined_flag="$no_undefined_flag"
+	fi
+
+      fi
+
+      func_generate_dlsyms "$libname" "$libname" "yes"
+      func_append libobjs " $symfileobj"
+      test "X$libobjs" = "X " && libobjs=
+
+      if test "$opt_mode" != relink; then
+	# Remove our outputs, but don't remove object files since they
+	# may have been created when compiling PIC objects.
+	removelist=
+	tempremovelist=`$ECHO "$output_objdir/*"`
+	for p in $tempremovelist; do
+	  case $p in
+	    *.$objext | *.gcno)
+	       ;;
+	    $output_objdir/$outputname | $output_objdir/$libname.* | $output_objdir/${libname}${release}.*)
+	       if test "X$precious_files_regex" != "X"; then
+		 if $ECHO "$p" | $EGREP -e "$precious_files_regex" >/dev/null 2>&1
+		 then
+		   continue
+		 fi
+	       fi
+	       func_append removelist " $p"
+	       ;;
+	    *) ;;
+	  esac
+	done
+	test -n "$removelist" && \
+	  func_show_eval "${RM}r \$removelist"
+      fi
+
+      # Now set the variables for building old libraries.
+      if test "$build_old_libs" = yes && test "$build_libtool_libs" != convenience ; then
+	func_append oldlibs " $output_objdir/$libname.$libext"
+
+	# Transform .lo files to .o files.
+	oldobjs="$objs "`$ECHO "$libobjs" | $SP2NL | $SED "/\.${libext}$/d; $lo2o" | $NL2SP`
+      fi
+
+      # Eliminate all temporary directories.
+      #for path in $notinst_path; do
+      #	lib_search_path=`$ECHO "$lib_search_path " | $SED "s% $path % %g"`
+      #	deplibs=`$ECHO "$deplibs " | $SED "s% -L$path % %g"`
+      #	dependency_libs=`$ECHO "$dependency_libs " | $SED "s% -L$path % %g"`
+      #done
+
+      if test -n "$xrpath"; then
+	# If the user specified any rpath flags, then add them.
+	temp_xrpath=
+	for libdir in $xrpath; do
+	  func_replace_sysroot "$libdir"
+	  func_append temp_xrpath " -R$func_replace_sysroot_result"
+	  case "$finalize_rpath " in
+	  *" $libdir "*) ;;
+	  *) func_append finalize_rpath " $libdir" ;;
+	  esac
+	done
+	if test "$hardcode_into_libs" != yes || test "$build_old_libs" = yes; then
+	  dependency_libs="$temp_xrpath $dependency_libs"
+	fi
+      fi
+
+      # Make sure dlfiles contains only unique files that won't be dlpreopened
+      old_dlfiles="$dlfiles"
+      dlfiles=
+      for lib in $old_dlfiles; do
+	case " $dlprefiles $dlfiles " in
+	*" $lib "*) ;;
+	*) func_append dlfiles " $lib" ;;
+	esac
+      done
+
+      # Make sure dlprefiles contains only unique files
+      old_dlprefiles="$dlprefiles"
+      dlprefiles=
+      for lib in $old_dlprefiles; do
+	case "$dlprefiles " in
+	*" $lib "*) ;;
+	*) func_append dlprefiles " $lib" ;;
+	esac
+      done
+
+      if test "$build_libtool_libs" = yes; then
+	if test -n "$rpath"; then
+	  case $host in
+	  *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos* | *-cegcc* | *-*-haiku*)
+	    # these systems don't actually have a c library (as such)!
+	    ;;
+	  *-*-rhapsody* | *-*-darwin1.[012])
+	    # Rhapsody C library is in the System framework
+	    func_append deplibs " System.ltframework"
+	    ;;
+	  *-*-netbsd*)
+	    # Don't link with libc until the a.out ld.so is fixed.
+	    ;;
+	  *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*)
+	    # Do not include libc due to us having libc/libc_r.
+	    ;;
+	  *-*-sco3.2v5* | *-*-sco5v6*)
+	    # Causes problems with __ctype
+	    ;;
+	  *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*)
+	    # Compiler inserts libc in the correct place for threads to work
+	    ;;
+	  *)
+	    # Add libc to deplibs on all other systems if necessary.
+	    if test "$build_libtool_need_lc" = "yes"; then
+	      func_append deplibs " -lc"
+	    fi
+	    ;;
+	  esac
+	fi
+
+	# Transform deplibs into only deplibs that can be linked in shared.
+	name_save=$name
+	libname_save=$libname
+	release_save=$release
+	versuffix_save=$versuffix
+	major_save=$major
+	# I'm not sure if I'm treating the release correctly.  I think
+	# release should show up in the -l (ie -lgmp5) so we don't want to
+	# add it in twice.  Is that correct?
+	release=""
+	versuffix=""
+	major=""
+	newdeplibs=
+	droppeddeps=no
+	case $deplibs_check_method in
+	pass_all)
+	  # Don't check for shared/static.  Everything works.
+	  # This might be a little naive.  We might want to check
+	  # whether the library exists or not.  But this is on
+	  # osf3 & osf4 and I'm not really sure... Just
+	  # implementing what was already the behavior.
+	  newdeplibs=$deplibs
+	  ;;
+	test_compile)
+	  # This code stresses the "libraries are programs" paradigm to its
+	  # limits. Maybe even breaks it.  We compile a program, linking it
+	  # against the deplibs as a proxy for the library.  Then we can check
+	  # whether they linked in statically or dynamically with ldd.
+	  $opt_dry_run || $RM conftest.c
+	  cat > conftest.c <<EOF
+	  int main() { return 0; }
+EOF
+	  $opt_dry_run || $RM conftest
+	  if $LTCC $LTCFLAGS -o conftest conftest.c $deplibs; then
+	    ldd_output=`ldd conftest`
+	    for i in $deplibs; do
+	      case $i in
+	      -l*)
+		func_stripname -l '' "$i"
+		name=$func_stripname_result
+		if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
+		  case " $predeps $postdeps " in
+		  *" $i "*)
+		    func_append newdeplibs " $i"
+		    i=""
+		    ;;
+		  esac
+		fi
+		if test -n "$i" ; then
+		  libname=`eval "\\$ECHO \"$libname_spec\""`
+		  deplib_matches=`eval "\\$ECHO \"$library_names_spec\""`
+		  set dummy $deplib_matches; shift
+		  deplib_match=$1
+		  if test `expr "$ldd_output" : ".*$deplib_match"` -ne 0 ; then
+		    func_append newdeplibs " $i"
+		  else
+		    droppeddeps=yes
+		    echo
+		    $ECHO "*** Warning: dynamic linker does not accept needed library $i."
+		    echo "*** I have the capability to make that library automatically link in when"
+		    echo "*** you link to this library.  But I can only do this if you have a"
+		    echo "*** shared version of the library, which I believe you do not have"
+		    echo "*** because a test_compile did reveal that the linker did not use it for"
+		    echo "*** its dynamic dependency list that programs get resolved with at runtime."
+		  fi
+		fi
+		;;
+	      *)
+		func_append newdeplibs " $i"
+		;;
+	      esac
+	    done
+	  else
+	    # Error occurred in the first compile.  Let's try to salvage
+	    # the situation: Compile a separate program for each library.
+	    for i in $deplibs; do
+	      case $i in
+	      -l*)
+		func_stripname -l '' "$i"
+		name=$func_stripname_result
+		$opt_dry_run || $RM conftest
+		if $LTCC $LTCFLAGS -o conftest conftest.c $i; then
+		  ldd_output=`ldd conftest`
+		  if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
+		    case " $predeps $postdeps " in
+		    *" $i "*)
+		      func_append newdeplibs " $i"
+		      i=""
+		      ;;
+		    esac
+		  fi
+		  if test -n "$i" ; then
+		    libname=`eval "\\$ECHO \"$libname_spec\""`
+		    deplib_matches=`eval "\\$ECHO \"$library_names_spec\""`
+		    set dummy $deplib_matches; shift
+		    deplib_match=$1
+		    if test `expr "$ldd_output" : ".*$deplib_match"` -ne 0 ; then
+		      func_append newdeplibs " $i"
+		    else
+		      droppeddeps=yes
+		      echo
+		      $ECHO "*** Warning: dynamic linker does not accept needed library $i."
+		      echo "*** I have the capability to make that library automatically link in when"
+		      echo "*** you link to this library.  But I can only do this if you have a"
+		      echo "*** shared version of the library, which you do not appear to have"
+		      echo "*** because a test_compile did reveal that the linker did not use this one"
+		      echo "*** as a dynamic dependency that programs can get resolved with at runtime."
+		    fi
+		  fi
+		else
+		  droppeddeps=yes
+		  echo
+		  $ECHO "*** Warning!  Library $i is needed by this library but I was not able to"
+		  echo "*** make it link in!  You will probably need to install it or some"
+		  echo "*** library that it depends on before this library will be fully"
+		  echo "*** functional.  Installing it before continuing would be even better."
+		fi
+		;;
+	      *)
+		func_append newdeplibs " $i"
+		;;
+	      esac
+	    done
+	  fi
+	  ;;
+	file_magic*)
+	  set dummy $deplibs_check_method; shift
+	  file_magic_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"`
+	  for a_deplib in $deplibs; do
+	    case $a_deplib in
+	    -l*)
+	      func_stripname -l '' "$a_deplib"
+	      name=$func_stripname_result
+	      if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
+		case " $predeps $postdeps " in
+		*" $a_deplib "*)
+		  func_append newdeplibs " $a_deplib"
+		  a_deplib=""
+		  ;;
+		esac
+	      fi
+	      if test -n "$a_deplib" ; then
+		libname=`eval "\\$ECHO \"$libname_spec\""`
+		if test -n "$file_magic_glob"; then
+		  libnameglob=`func_echo_all "$libname" | $SED -e $file_magic_glob`
+		else
+		  libnameglob=$libname
+		fi
+		test "$want_nocaseglob" = yes && nocaseglob=`shopt -p nocaseglob`
+		for i in $lib_search_path $sys_lib_search_path $shlib_search_path; do
+		  if test "$want_nocaseglob" = yes; then
+		    shopt -s nocaseglob
+		    potential_libs=`ls $i/$libnameglob[.-]* 2>/dev/null`
+		    $nocaseglob
+		  else
+		    potential_libs=`ls $i/$libnameglob[.-]* 2>/dev/null`
+		  fi
+		  for potent_lib in $potential_libs; do
+		      # Follow soft links.
+		      if ls -lLd "$potent_lib" 2>/dev/null |
+			 $GREP " -> " >/dev/null; then
+			continue
+		      fi
+		      # The statement above tries to avoid entering an
+		      # endless loop below, in case of cyclic links.
+		      # We might still enter an endless loop, since a link
+		      # loop can be closed while we follow links,
+		      # but so what?
+		      potlib="$potent_lib"
+		      while test -h "$potlib" 2>/dev/null; do
+			potliblink=`ls -ld $potlib | ${SED} 's/.* -> //'`
+			case $potliblink in
+			[\\/]* | [A-Za-z]:[\\/]*) potlib="$potliblink";;
+			*) potlib=`$ECHO "$potlib" | $SED 's,[^/]*$,,'`"$potliblink";;
+			esac
+		      done
+		      if eval $file_magic_cmd \"\$potlib\" 2>/dev/null |
+			 $SED -e 10q |
+			 $EGREP "$file_magic_regex" > /dev/null; then
+			func_append newdeplibs " $a_deplib"
+			a_deplib=""
+			break 2
+		      fi
+		  done
+		done
+	      fi
+	      if test -n "$a_deplib" ; then
+		droppeddeps=yes
+		echo
+		$ECHO "*** Warning: linker path does not have real file for library $a_deplib."
+		echo "*** I have the capability to make that library automatically link in when"
+		echo "*** you link to this library.  But I can only do this if you have a"
+		echo "*** shared version of the library, which you do not appear to have"
+		echo "*** because I did check the linker path looking for a file starting"
+		if test -z "$potlib" ; then
+		  $ECHO "*** with $libname but no candidates were found. (...for file magic test)"
+		else
+		  $ECHO "*** with $libname and none of the candidates passed a file format test"
+		  $ECHO "*** using a file magic. Last file checked: $potlib"
+		fi
+	      fi
+	      ;;
+	    *)
+	      # Add a -L argument.
+	      func_append newdeplibs " $a_deplib"
+	      ;;
+	    esac
+	  done # Gone through all deplibs.
+	  ;;
+	match_pattern*)
+	  set dummy $deplibs_check_method; shift
+	  match_pattern_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"`
+	  for a_deplib in $deplibs; do
+	    case $a_deplib in
+	    -l*)
+	      func_stripname -l '' "$a_deplib"
+	      name=$func_stripname_result
+	      if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
+		case " $predeps $postdeps " in
+		*" $a_deplib "*)
+		  func_append newdeplibs " $a_deplib"
+		  a_deplib=""
+		  ;;
+		esac
+	      fi
+	      if test -n "$a_deplib" ; then
+		libname=`eval "\\$ECHO \"$libname_spec\""`
+		for i in $lib_search_path $sys_lib_search_path $shlib_search_path; do
+		  potential_libs=`ls $i/$libname[.-]* 2>/dev/null`
+		  for potent_lib in $potential_libs; do
+		    potlib="$potent_lib" # see symlink-check above in file_magic test
+		    if eval "\$ECHO \"$potent_lib\"" 2>/dev/null | $SED 10q | \
+		       $EGREP "$match_pattern_regex" > /dev/null; then
+		      func_append newdeplibs " $a_deplib"
+		      a_deplib=""
+		      break 2
+		    fi
+		  done
+		done
+	      fi
+	      if test -n "$a_deplib" ; then
+		droppeddeps=yes
+		echo
+		$ECHO "*** Warning: linker path does not have real file for library $a_deplib."
+		echo "*** I have the capability to make that library automatically link in when"
+		echo "*** you link to this library.  But I can only do this if you have a"
+		echo "*** shared version of the library, which you do not appear to have"
+		echo "*** because I did check the linker path looking for a file starting"
+		if test -z "$potlib" ; then
+		  $ECHO "*** with $libname but no candidates were found. (...for regex pattern test)"
+		else
+		  $ECHO "*** with $libname and none of the candidates passed a file format test"
+		  $ECHO "*** using a regex pattern. Last file checked: $potlib"
+		fi
+	      fi
+	      ;;
+	    *)
+	      # Add a -L argument.
+	      func_append newdeplibs " $a_deplib"
+	      ;;
+	    esac
+	  done # Gone through all deplibs.
+	  ;;
+	none | unknown | *)
+	  newdeplibs=""
+	  tmp_deplibs=`$ECHO " $deplibs" | $SED 's/ -lc$//; s/ -[LR][^ ]*//g'`
+	  if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
+	    for i in $predeps $postdeps ; do
+	      # can't use Xsed below, because $i might contain '/'
+	      tmp_deplibs=`$ECHO " $tmp_deplibs" | $SED "s,$i,,"`
+	    done
+	  fi
+	  case $tmp_deplibs in
+	  *[!\	\ ]*)
+	    echo
+	    if test "X$deplibs_check_method" = "Xnone"; then
+	      echo "*** Warning: inter-library dependencies are not supported in this platform."
+	    else
+	      echo "*** Warning: inter-library dependencies are not known to be supported."
+	    fi
+	    echo "*** All declared inter-library dependencies are being dropped."
+	    droppeddeps=yes
+	    ;;
+	  esac
+	  ;;
+	esac
+	versuffix=$versuffix_save
+	major=$major_save
+	release=$release_save
+	libname=$libname_save
+	name=$name_save
+
+	case $host in
+	*-*-rhapsody* | *-*-darwin1.[012])
+	  # On Rhapsody replace the C library with the System framework
+	  newdeplibs=`$ECHO " $newdeplibs" | $SED 's/ -lc / System.ltframework /'`
+	  ;;
+	esac
+
+	if test "$droppeddeps" = yes; then
+	  if test "$module" = yes; then
+	    echo
+	    echo "*** Warning: libtool could not satisfy all declared inter-library"
+	    $ECHO "*** dependencies of module $libname.  Therefore, libtool will create"
+	    echo "*** a static module, that should work as long as the dlopening"
+	    echo "*** application is linked with the -dlopen flag."
+	    if test -z "$global_symbol_pipe"; then
+	      echo
+	      echo "*** However, this would only work if libtool was able to extract symbol"
+	      echo "*** lists from a program, using \`nm' or equivalent, but libtool could"
+	      echo "*** not find such a program.  So, this module is probably useless."
+	      echo "*** \`nm' from GNU binutils and a full rebuild may help."
+	    fi
+	    if test "$build_old_libs" = no; then
+	      oldlibs="$output_objdir/$libname.$libext"
+	      build_libtool_libs=module
+	      build_old_libs=yes
+	    else
+	      build_libtool_libs=no
+	    fi
+	  else
+	    echo "*** The inter-library dependencies that have been dropped here will be"
+	    echo "*** automatically added whenever a program is linked with this library"
+	    echo "*** or is declared to -dlopen it."
+
+	    if test "$allow_undefined" = no; then
+	      echo
+	      echo "*** Since this library must not contain undefined symbols,"
+	      echo "*** because either the platform does not support them or"
+	      echo "*** it was explicitly requested with -no-undefined,"
+	      echo "*** libtool will only create a static version of it."
+	      if test "$build_old_libs" = no; then
+		oldlibs="$output_objdir/$libname.$libext"
+		build_libtool_libs=module
+		build_old_libs=yes
+	      else
+		build_libtool_libs=no
+	      fi
+	    fi
+	  fi
+	fi
+	# Done checking deplibs!
+	deplibs=$newdeplibs
+      fi
+      # Time to change all our "foo.ltframework" stuff back to "-framework foo"
+      case $host in
+	*-*-darwin*)
+	  newdeplibs=`$ECHO " $newdeplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'`
+	  new_inherited_linker_flags=`$ECHO " $new_inherited_linker_flags" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'`
+	  deplibs=`$ECHO " $deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'`
+	  ;;
+      esac
+
+      # move library search paths that coincide with paths to not yet
+      # installed libraries to the beginning of the library search list
+      new_libs=
+      for path in $notinst_path; do
+	case " $new_libs " in
+	*" -L$path/$objdir "*) ;;
+	*)
+	  case " $deplibs " in
+	  *" -L$path/$objdir "*)
+	    func_append new_libs " -L$path/$objdir" ;;
+	  esac
+	  ;;
+	esac
+      done
+      for deplib in $deplibs; do
+	case $deplib in
+	-L*)
+	  case " $new_libs " in
+	  *" $deplib "*) ;;
+	  *) func_append new_libs " $deplib" ;;
+	  esac
+	  ;;
+	*) func_append new_libs " $deplib" ;;
+	esac
+      done
+      deplibs="$new_libs"
+
+      # All the library-specific variables (install_libdir is set above).
+      library_names=
+      old_library=
+      dlname=
+
+      # Test again, we may have decided not to build it any more
+      if test "$build_libtool_libs" = yes; then
+	# Remove ${wl} instances when linking with ld.
+	# FIXME: should test the right _cmds variable.
+	case $archive_cmds in
+	  *\$LD\ *) wl= ;;
+        esac
+	if test "$hardcode_into_libs" = yes; then
+	  # Hardcode the library paths
+	  hardcode_libdirs=
+	  dep_rpath=
+	  rpath="$finalize_rpath"
+	  test "$opt_mode" != relink && rpath="$compile_rpath$rpath"
+	  for libdir in $rpath; do
+	    if test -n "$hardcode_libdir_flag_spec"; then
+	      if test -n "$hardcode_libdir_separator"; then
+		func_replace_sysroot "$libdir"
+		libdir=$func_replace_sysroot_result
+		if test -z "$hardcode_libdirs"; then
+		  hardcode_libdirs="$libdir"
+		else
+		  # Just accumulate the unique libdirs.
+		  case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in
+		  *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*)
+		    ;;
+		  *)
+		    func_append hardcode_libdirs "$hardcode_libdir_separator$libdir"
+		    ;;
+		  esac
+		fi
+	      else
+		eval flag=\"$hardcode_libdir_flag_spec\"
+		func_append dep_rpath " $flag"
+	      fi
+	    elif test -n "$runpath_var"; then
+	      case "$perm_rpath " in
+	      *" $libdir "*) ;;
+	      *) func_append perm_rpath " $libdir" ;;
+	      esac
+	    fi
+	  done
+	  # Substitute the hardcoded libdirs into the rpath.
+	  if test -n "$hardcode_libdir_separator" &&
+	     test -n "$hardcode_libdirs"; then
+	    libdir="$hardcode_libdirs"
+	    eval "dep_rpath=\"$hardcode_libdir_flag_spec\""
+	  fi
+	  if test -n "$runpath_var" && test -n "$perm_rpath"; then
+	    # We should set the runpath_var.
+	    rpath=
+	    for dir in $perm_rpath; do
+	      func_append rpath "$dir:"
+	    done
+	    eval "$runpath_var='$rpath\$$runpath_var'; export $runpath_var"
+	  fi
+	  test -n "$dep_rpath" && deplibs="$dep_rpath $deplibs"
+	fi
+
+	shlibpath="$finalize_shlibpath"
+	test "$opt_mode" != relink && shlibpath="$compile_shlibpath$shlibpath"
+	if test -n "$shlibpath"; then
+	  eval "$shlibpath_var='$shlibpath\$$shlibpath_var'; export $shlibpath_var"
+	fi
+
+	# Get the real and link names of the library.
+	eval shared_ext=\"$shrext_cmds\"
+	eval library_names=\"$library_names_spec\"
+	set dummy $library_names
+	shift
+	realname="$1"
+	shift
+
+	if test -n "$soname_spec"; then
+	  eval soname=\"$soname_spec\"
+	else
+	  soname="$realname"
+	fi
+	if test -z "$dlname"; then
+	  dlname=$soname
+	fi
+
+	lib="$output_objdir/$realname"
+	linknames=
+	for link
+	do
+	  func_append linknames " $link"
+	done
+
+	# Use standard objects if they are pic
+	test -z "$pic_flag" && libobjs=`$ECHO "$libobjs" | $SP2NL | $SED "$lo2o" | $NL2SP`
+	test "X$libobjs" = "X " && libobjs=
+
+	delfiles=
+	if test -n "$export_symbols" && test -n "$include_expsyms"; then
+	  $opt_dry_run || cp "$export_symbols" "$output_objdir/$libname.uexp"
+	  export_symbols="$output_objdir/$libname.uexp"
+	  func_append delfiles " $export_symbols"
+	fi
+
+	orig_export_symbols=
+	case $host_os in
+	cygwin* | mingw* | cegcc*)
+	  if test -n "$export_symbols" && test -z "$export_symbols_regex"; then
+	    # exporting using user supplied symfile
+	    if test "x`$SED 1q $export_symbols`" != xEXPORTS; then
+	      # and it's NOT already a .def file. Must figure out
+	      # which of the given symbols are data symbols and tag
+	      # them as such. So, trigger use of export_symbols_cmds.
+	      # export_symbols gets reassigned inside the "prepare
+	      # the list of exported symbols" if statement, so the
+	      # include_expsyms logic still works.
+	      orig_export_symbols="$export_symbols"
+	      export_symbols=
+	      always_export_symbols=yes
+	    fi
+	  fi
+	  ;;
+	esac
+
+	# Prepare the list of exported symbols
+	if test -z "$export_symbols"; then
+	  if test "$always_export_symbols" = yes || test -n "$export_symbols_regex"; then
+	    func_verbose "generating symbol list for \`$libname.la'"
+	    export_symbols="$output_objdir/$libname.exp"
+	    $opt_dry_run || $RM $export_symbols
+	    cmds=$export_symbols_cmds
+	    save_ifs="$IFS"; IFS='~'
+	    for cmd1 in $cmds; do
+	      IFS="$save_ifs"
+	      # Take the normal branch if the nm_file_list_spec branch
+	      # doesn't work or if tool conversion is not needed.
+	      case $nm_file_list_spec~$to_tool_file_cmd in
+		*~func_convert_file_noop | *~func_convert_file_msys_to_w32 | ~*)
+		  try_normal_branch=yes
+		  eval cmd=\"$cmd1\"
+		  func_len " $cmd"
+		  len=$func_len_result
+		  ;;
+		*)
+		  try_normal_branch=no
+		  ;;
+	      esac
+	      if test "$try_normal_branch" = yes \
+		 && { test "$len" -lt "$max_cmd_len" \
+		      || test "$max_cmd_len" -le -1; }
+	      then
+		func_show_eval "$cmd" 'exit $?'
+		skipped_export=false
+	      elif test -n "$nm_file_list_spec"; then
+		func_basename "$output"
+		output_la=$func_basename_result
+		save_libobjs=$libobjs
+		save_output=$output
+		output=${output_objdir}/${output_la}.nm
+		func_to_tool_file "$output"
+		libobjs=$nm_file_list_spec$func_to_tool_file_result
+		func_append delfiles " $output"
+		func_verbose "creating $NM input file list: $output"
+		for obj in $save_libobjs; do
+		  func_to_tool_file "$obj"
+		  $ECHO "$func_to_tool_file_result"
+		done > "$output"
+		eval cmd=\"$cmd1\"
+		func_show_eval "$cmd" 'exit $?'
+		output=$save_output
+		libobjs=$save_libobjs
+		skipped_export=false
+	      else
+		# The command line is too long to execute in one step.
+		func_verbose "using reloadable object file for export list..."
+		skipped_export=:
+		# Break out early, otherwise skipped_export may be
+		# set to false by a later but shorter cmd.
+		break
+	      fi
+	    done
+	    IFS="$save_ifs"
+	    if test -n "$export_symbols_regex" && test "X$skipped_export" != "X:"; then
+	      func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"'
+	      func_show_eval '$MV "${export_symbols}T" "$export_symbols"'
+	    fi
+	  fi
+	fi
+
+	if test -n "$export_symbols" && test -n "$include_expsyms"; then
+	  tmp_export_symbols="$export_symbols"
+	  test -n "$orig_export_symbols" && tmp_export_symbols="$orig_export_symbols"
+	  $opt_dry_run || eval '$ECHO "$include_expsyms" | $SP2NL >> "$tmp_export_symbols"'
+	fi
+
+	if test "X$skipped_export" != "X:" && test -n "$orig_export_symbols"; then
+	  # The given exports_symbols file has to be filtered, so filter it.
+	  func_verbose "filter symbol list for \`$libname.la' to tag DATA exports"
+	  # FIXME: $output_objdir/$libname.filter potentially contains lots of
+	  # 's' commands which not all seds can handle. GNU sed should be fine
+	  # though. Also, the filter scales superlinearly with the number of
+	  # global variables. join(1) would be nice here, but unfortunately
+	  # isn't a blessed tool.
+	  $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter
+	  func_append delfiles " $export_symbols $output_objdir/$libname.filter"
+	  export_symbols=$output_objdir/$libname.def
+	  $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols
+	fi
+
+	tmp_deplibs=
+	for test_deplib in $deplibs; do
+	  case " $convenience " in
+	  *" $test_deplib "*) ;;
+	  *)
+	    func_append tmp_deplibs " $test_deplib"
+	    ;;
+	  esac
+	done
+	deplibs="$tmp_deplibs"
+
+	if test -n "$convenience"; then
+	  if test -n "$whole_archive_flag_spec" &&
+	    test "$compiler_needs_object" = yes &&
+	    test -z "$libobjs"; then
+	    # extract the archives, so we have objects to list.
+	    # TODO: could optimize this to just extract one archive.
+	    whole_archive_flag_spec=
+	  fi
+	  if test -n "$whole_archive_flag_spec"; then
+	    save_libobjs=$libobjs
+	    eval libobjs=\"\$libobjs $whole_archive_flag_spec\"
+	    test "X$libobjs" = "X " && libobjs=
+	  else
+	    gentop="$output_objdir/${outputname}x"
+	    func_append generated " $gentop"
+
+	    func_extract_archives $gentop $convenience
+	    func_append libobjs " $func_extract_archives_result"
+	    test "X$libobjs" = "X " && libobjs=
+	  fi
+	fi
+
+	if test "$thread_safe" = yes && test -n "$thread_safe_flag_spec"; then
+	  eval flag=\"$thread_safe_flag_spec\"
+	  func_append linker_flags " $flag"
+	fi
+
+	# Make a backup of the uninstalled library when relinking
+	if test "$opt_mode" = relink; then
+	  $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}U && $MV $realname ${realname}U)' || exit $?
+	fi
+
+	# Do each of the archive commands.
+	if test "$module" = yes && test -n "$module_cmds" ; then
+	  if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then
+	    eval test_cmds=\"$module_expsym_cmds\"
+	    cmds=$module_expsym_cmds
+	  else
+	    eval test_cmds=\"$module_cmds\"
+	    cmds=$module_cmds
+	  fi
+	else
+	  if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then
+	    eval test_cmds=\"$archive_expsym_cmds\"
+	    cmds=$archive_expsym_cmds
+	  else
+	    eval test_cmds=\"$archive_cmds\"
+	    cmds=$archive_cmds
+	  fi
+	fi
+
+	if test "X$skipped_export" != "X:" &&
+	   func_len " $test_cmds" &&
+	   len=$func_len_result &&
+	   test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then
+	  :
+	else
+	  # The command line is too long to link in one step, link piecewise
+	  # or, if using GNU ld and skipped_export is not :, use a linker
+	  # script.
+
+	  # Save the value of $output and $libobjs because we want to
+	  # use them later.  If we have whole_archive_flag_spec, we
+	  # want to use save_libobjs as it was before
+	  # whole_archive_flag_spec was expanded, because we can't
+	  # assume the linker understands whole_archive_flag_spec.
+	  # This may have to be revisited, in case too many
+	  # convenience libraries get linked in and end up exceeding
+	  # the spec.
+	  if test -z "$convenience" || test -z "$whole_archive_flag_spec"; then
+	    save_libobjs=$libobjs
+	  fi
+	  save_output=$output
+	  func_basename "$output"
+	  output_la=$func_basename_result
+
+	  # Clear the reloadable object creation command queue and
+	  # initialize k to one.
+	  test_cmds=
+	  concat_cmds=
+	  objlist=
+	  last_robj=
+	  k=1
+
+	  if test -n "$save_libobjs" && test "X$skipped_export" != "X:" && test "$with_gnu_ld" = yes; then
+	    output=${output_objdir}/${output_la}.lnkscript
+	    func_verbose "creating GNU ld script: $output"
+	    echo 'INPUT (' > $output
+	    for obj in $save_libobjs
+	    do
+	      func_to_tool_file "$obj"
+	      $ECHO "$func_to_tool_file_result" >> $output
+	    done
+	    echo ')' >> $output
+	    func_append delfiles " $output"
+	    func_to_tool_file "$output"
+	    output=$func_to_tool_file_result
+	  elif test -n "$save_libobjs" && test "X$skipped_export" != "X:" && test "X$file_list_spec" != X; then
+	    output=${output_objdir}/${output_la}.lnk
+	    func_verbose "creating linker input file list: $output"
+	    : > $output
+	    set x $save_libobjs
+	    shift
+	    firstobj=
+	    if test "$compiler_needs_object" = yes; then
+	      firstobj="$1 "
+	      shift
+	    fi
+	    for obj
+	    do
+	      func_to_tool_file "$obj"
+	      $ECHO "$func_to_tool_file_result" >> $output
+	    done
+	    func_append delfiles " $output"
+	    func_to_tool_file "$output"
+	    output=$firstobj\"$file_list_spec$func_to_tool_file_result\"
+	  else
+	    if test -n "$save_libobjs"; then
+	      func_verbose "creating reloadable object files..."
+	      output=$output_objdir/$output_la-${k}.$objext
+	      eval test_cmds=\"$reload_cmds\"
+	      func_len " $test_cmds"
+	      len0=$func_len_result
+	      len=$len0
+
+	      # Loop over the list of objects to be linked.
+	      for obj in $save_libobjs
+	      do
+		func_len " $obj"
+		func_arith $len + $func_len_result
+		len=$func_arith_result
+		if test "X$objlist" = X ||
+		   test "$len" -lt "$max_cmd_len"; then
+		  func_append objlist " $obj"
+		else
+		  # The command $test_cmds is almost too long, add a
+		  # command to the queue.
+		  if test "$k" -eq 1 ; then
+		    # The first file doesn't have a previous command to add.
+		    reload_objs=$objlist
+		    eval concat_cmds=\"$reload_cmds\"
+		  else
+		    # All subsequent reloadable object files will link in
+		    # the last one created.
+		    reload_objs="$objlist $last_robj"
+		    eval concat_cmds=\"\$concat_cmds~$reload_cmds~\$RM $last_robj\"
+		  fi
+		  last_robj=$output_objdir/$output_la-${k}.$objext
+		  func_arith $k + 1
+		  k=$func_arith_result
+		  output=$output_objdir/$output_la-${k}.$objext
+		  objlist=" $obj"
+		  func_len " $last_robj"
+		  func_arith $len0 + $func_len_result
+		  len=$func_arith_result
+		fi
+	      done
+	      # Handle the remaining objects by creating one last
+	      # reloadable object file.  All subsequent reloadable object
+	      # files will link in the last one created.
+	      test -z "$concat_cmds" || concat_cmds=$concat_cmds~
+	      reload_objs="$objlist $last_robj"
+	      eval concat_cmds=\"\${concat_cmds}$reload_cmds\"
+	      if test -n "$last_robj"; then
+	        eval concat_cmds=\"\${concat_cmds}~\$RM $last_robj\"
+	      fi
+	      func_append delfiles " $output"
+
+	    else
+	      output=
+	    fi
+
+	    if ${skipped_export-false}; then
+	      func_verbose "generating symbol list for \`$libname.la'"
+	      export_symbols="$output_objdir/$libname.exp"
+	      $opt_dry_run || $RM $export_symbols
+	      libobjs=$output
+	      # Append the command to create the export file.
+	      test -z "$concat_cmds" || concat_cmds=$concat_cmds~
+	      eval concat_cmds=\"\$concat_cmds$export_symbols_cmds\"
+	      if test -n "$last_robj"; then
+		eval concat_cmds=\"\$concat_cmds~\$RM $last_robj\"
+	      fi
+	    fi
+
+	    test -n "$save_libobjs" &&
+	      func_verbose "creating a temporary reloadable object file: $output"
+
+	    # Loop through the commands generated above and execute them.
+	    save_ifs="$IFS"; IFS='~'
+	    for cmd in $concat_cmds; do
+	      IFS="$save_ifs"
+	      $opt_silent || {
+		  func_quote_for_expand "$cmd"
+		  eval "func_echo $func_quote_for_expand_result"
+	      }
+	      $opt_dry_run || eval "$cmd" || {
+		lt_exit=$?
+
+		# Restore the uninstalled library and exit
+		if test "$opt_mode" = relink; then
+		  ( cd "$output_objdir" && \
+		    $RM "${realname}T" && \
+		    $MV "${realname}U" "$realname" )
+		fi
+
+		exit $lt_exit
+	      }
+	    done
+	    IFS="$save_ifs"
+
+	    if test -n "$export_symbols_regex" && ${skipped_export-false}; then
+	      func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"'
+	      func_show_eval '$MV "${export_symbols}T" "$export_symbols"'
+	    fi
+	  fi
+
+          if ${skipped_export-false}; then
+	    if test -n "$export_symbols" && test -n "$include_expsyms"; then
+	      tmp_export_symbols="$export_symbols"
+	      test -n "$orig_export_symbols" && tmp_export_symbols="$orig_export_symbols"
+	      $opt_dry_run || eval '$ECHO "$include_expsyms" | $SP2NL >> "$tmp_export_symbols"'
+	    fi
+
+	    if test -n "$orig_export_symbols"; then
+	      # The given exports_symbols file has to be filtered, so filter it.
+	      func_verbose "filter symbol list for \`$libname.la' to tag DATA exports"
+	      # FIXME: $output_objdir/$libname.filter potentially contains lots of
+	      # 's' commands which not all seds can handle. GNU sed should be fine
+	      # though. Also, the filter scales superlinearly with the number of
+	      # global variables. join(1) would be nice here, but unfortunately
+	      # isn't a blessed tool.
+	      $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter
+	      func_append delfiles " $export_symbols $output_objdir/$libname.filter"
+	      export_symbols=$output_objdir/$libname.def
+	      $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols
+	    fi
+	  fi
+
+	  libobjs=$output
+	  # Restore the value of output.
+	  output=$save_output
+
+	  if test -n "$convenience" && test -n "$whole_archive_flag_spec"; then
+	    eval libobjs=\"\$libobjs $whole_archive_flag_spec\"
+	    test "X$libobjs" = "X " && libobjs=
+	  fi
+	  # Expand the library linking commands again to reset the
+	  # value of $libobjs for piecewise linking.
+
+	  # Do each of the archive commands.
+	  if test "$module" = yes && test -n "$module_cmds" ; then
+	    if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then
+	      cmds=$module_expsym_cmds
+	    else
+	      cmds=$module_cmds
+	    fi
+	  else
+	    if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then
+	      cmds=$archive_expsym_cmds
+	    else
+	      cmds=$archive_cmds
+	    fi
+	  fi
+	fi
+
+	if test -n "$delfiles"; then
+	  # Append the command to remove temporary files to $cmds.
+	  eval cmds=\"\$cmds~\$RM $delfiles\"
+	fi
+
+	# Add any objects from preloaded convenience libraries
+	if test -n "$dlprefiles"; then
+	  gentop="$output_objdir/${outputname}x"
+	  func_append generated " $gentop"
+
+	  func_extract_archives $gentop $dlprefiles
+	  func_append libobjs " $func_extract_archives_result"
+	  test "X$libobjs" = "X " && libobjs=
+	fi
+
+	save_ifs="$IFS"; IFS='~'
+	for cmd in $cmds; do
+	  IFS="$save_ifs"
+	  eval cmd=\"$cmd\"
+	  $opt_silent || {
+	    func_quote_for_expand "$cmd"
+	    eval "func_echo $func_quote_for_expand_result"
+	  }
+	  $opt_dry_run || eval "$cmd" || {
+	    lt_exit=$?
+
+	    # Restore the uninstalled library and exit
+	    if test "$opt_mode" = relink; then
+	      ( cd "$output_objdir" && \
+	        $RM "${realname}T" && \
+		$MV "${realname}U" "$realname" )
+	    fi
+
+	    exit $lt_exit
+	  }
+	done
+	IFS="$save_ifs"
+
+	# Restore the uninstalled library and exit
+	if test "$opt_mode" = relink; then
+	  $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}T && $MV $realname ${realname}T && $MV ${realname}U $realname)' || exit $?
+
+	  if test -n "$convenience"; then
+	    if test -z "$whole_archive_flag_spec"; then
+	      func_show_eval '${RM}r "$gentop"'
+	    fi
+	  fi
+
+	  exit $EXIT_SUCCESS
+	fi
+
+	# Create links to the real library.
+	for linkname in $linknames; do
+	  if test "$realname" != "$linkname"; then
+	    func_show_eval '(cd "$output_objdir" && $RM "$linkname" && $LN_S "$realname" "$linkname")' 'exit $?'
+	  fi
+	done
+
+	# If -module or -export-dynamic was specified, set the dlname.
+	if test "$module" = yes || test "$export_dynamic" = yes; then
+	  # On all known operating systems, these are identical.
+	  dlname="$soname"
+	fi
+      fi
+      ;;
+
+    obj)
+      if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then
+	func_warning "\`-dlopen' is ignored for objects"
+      fi
+
+      case " $deplibs" in
+      *\ -l* | *\ -L*)
+	func_warning "\`-l' and \`-L' are ignored for objects" ;;
+      esac
+
+      test -n "$rpath" && \
+	func_warning "\`-rpath' is ignored for objects"
+
+      test -n "$xrpath" && \
+	func_warning "\`-R' is ignored for objects"
+
+      test -n "$vinfo" && \
+	func_warning "\`-version-info' is ignored for objects"
+
+      test -n "$release" && \
+	func_warning "\`-release' is ignored for objects"
+
+      case $output in
+      *.lo)
+	test -n "$objs$old_deplibs" && \
+	  func_fatal_error "cannot build library object \`$output' from non-libtool objects"
+
+	libobj=$output
+	func_lo2o "$libobj"
+	obj=$func_lo2o_result
+	;;
+      *)
+	libobj=
+	obj="$output"
+	;;
+      esac
+
+      # Delete the old objects.
+      $opt_dry_run || $RM $obj $libobj
+
+      # Objects from convenience libraries.  This assumes
+      # single-version convenience libraries.  Whenever we create
+      # different ones for PIC/non-PIC, this we'll have to duplicate
+      # the extraction.
+      reload_conv_objs=
+      gentop=
+      # reload_cmds runs $LD directly, so let us get rid of
+      # -Wl from whole_archive_flag_spec and hope we can get by with
+      # turning comma into space..
+      wl=
+
+      if test -n "$convenience"; then
+	if test -n "$whole_archive_flag_spec"; then
+	  eval tmp_whole_archive_flags=\"$whole_archive_flag_spec\"
+	  reload_conv_objs=$reload_objs\ `$ECHO "$tmp_whole_archive_flags" | $SED 's|,| |g'`
+	else
+	  gentop="$output_objdir/${obj}x"
+	  func_append generated " $gentop"
+
+	  func_extract_archives $gentop $convenience
+	  reload_conv_objs="$reload_objs $func_extract_archives_result"
+	fi
+      fi
+
+      # If we're not building shared, we need to use non_pic_objs
+      test "$build_libtool_libs" != yes && libobjs="$non_pic_objects"
+
+      # Create the old-style object.
+      reload_objs="$objs$old_deplibs "`$ECHO "$libobjs" | $SP2NL | $SED "/\.${libext}$/d; /\.lib$/d; $lo2o" | $NL2SP`" $reload_conv_objs" ### testsuite: skip nested quoting test
+
+      output="$obj"
+      func_execute_cmds "$reload_cmds" 'exit $?'
+
+      # Exit if we aren't doing a library object file.
+      if test -z "$libobj"; then
+	if test -n "$gentop"; then
+	  func_show_eval '${RM}r "$gentop"'
+	fi
+
+	exit $EXIT_SUCCESS
+      fi
+
+      if test "$build_libtool_libs" != yes; then
+	if test -n "$gentop"; then
+	  func_show_eval '${RM}r "$gentop"'
+	fi
+
+	# Create an invalid libtool object if no PIC, so that we don't
+	# accidentally link it into a program.
+	# $show "echo timestamp > $libobj"
+	# $opt_dry_run || eval "echo timestamp > $libobj" || exit $?
+	exit $EXIT_SUCCESS
+      fi
+
+      if test -n "$pic_flag" || test "$pic_mode" != default; then
+	# Only do commands if we really have different PIC objects.
+	reload_objs="$libobjs $reload_conv_objs"
+	output="$libobj"
+	func_execute_cmds "$reload_cmds" 'exit $?'
+      fi
+
+      if test -n "$gentop"; then
+	func_show_eval '${RM}r "$gentop"'
+      fi
+
+      exit $EXIT_SUCCESS
+      ;;
+
+    prog)
+      case $host in
+	*cygwin*) func_stripname '' '.exe' "$output"
+	          output=$func_stripname_result.exe;;
+      esac
+      test -n "$vinfo" && \
+	func_warning "\`-version-info' is ignored for programs"
+
+      test -n "$release" && \
+	func_warning "\`-release' is ignored for programs"
+
+      test "$preload" = yes \
+        && test "$dlopen_support" = unknown \
+	&& test "$dlopen_self" = unknown \
+	&& test "$dlopen_self_static" = unknown && \
+	  func_warning "\`LT_INIT([dlopen])' not used. Assuming no dlopen support."
+
+      case $host in
+      *-*-rhapsody* | *-*-darwin1.[012])
+	# On Rhapsody replace the C library is the System framework
+	compile_deplibs=`$ECHO " $compile_deplibs" | $SED 's/ -lc / System.ltframework /'`
+	finalize_deplibs=`$ECHO " $finalize_deplibs" | $SED 's/ -lc / System.ltframework /'`
+	;;
+      esac
+
+      case $host in
+      *-*-darwin*)
+	# Don't allow lazy linking, it breaks C++ global constructors
+	# But is supposedly fixed on 10.4 or later (yay!).
+	if test "$tagname" = CXX ; then
+	  case ${MACOSX_DEPLOYMENT_TARGET-10.0} in
+	    10.[0123])
+	      func_append compile_command " ${wl}-bind_at_load"
+	      func_append finalize_command " ${wl}-bind_at_load"
+	    ;;
+	  esac
+	fi
+	# Time to change all our "foo.ltframework" stuff back to "-framework foo"
+	compile_deplibs=`$ECHO " $compile_deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'`
+	finalize_deplibs=`$ECHO " $finalize_deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'`
+	;;
+      esac
+
+
+      # move library search paths that coincide with paths to not yet
+      # installed libraries to the beginning of the library search list
+      new_libs=
+      for path in $notinst_path; do
+	case " $new_libs " in
+	*" -L$path/$objdir "*) ;;
+	*)
+	  case " $compile_deplibs " in
+	  *" -L$path/$objdir "*)
+	    func_append new_libs " -L$path/$objdir" ;;
+	  esac
+	  ;;
+	esac
+      done
+      for deplib in $compile_deplibs; do
+	case $deplib in
+	-L*)
+	  case " $new_libs " in
+	  *" $deplib "*) ;;
+	  *) func_append new_libs " $deplib" ;;
+	  esac
+	  ;;
+	*) func_append new_libs " $deplib" ;;
+	esac
+      done
+      compile_deplibs="$new_libs"
+
+
+      func_append compile_command " $compile_deplibs"
+      func_append finalize_command " $finalize_deplibs"
+
+      if test -n "$rpath$xrpath"; then
+	# If the user specified any rpath flags, then add them.
+	for libdir in $rpath $xrpath; do
+	  # This is the magic to use -rpath.
+	  case "$finalize_rpath " in
+	  *" $libdir "*) ;;
+	  *) func_append finalize_rpath " $libdir" ;;
+	  esac
+	done
+      fi
+
+      # Now hardcode the library paths
+      rpath=
+      hardcode_libdirs=
+      for libdir in $compile_rpath $finalize_rpath; do
+	if test -n "$hardcode_libdir_flag_spec"; then
+	  if test -n "$hardcode_libdir_separator"; then
+	    if test -z "$hardcode_libdirs"; then
+	      hardcode_libdirs="$libdir"
+	    else
+	      # Just accumulate the unique libdirs.
+	      case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in
+	      *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*)
+		;;
+	      *)
+		func_append hardcode_libdirs "$hardcode_libdir_separator$libdir"
+		;;
+	      esac
+	    fi
+	  else
+	    eval flag=\"$hardcode_libdir_flag_spec\"
+	    func_append rpath " $flag"
+	  fi
+	elif test -n "$runpath_var"; then
+	  case "$perm_rpath " in
+	  *" $libdir "*) ;;
+	  *) func_append perm_rpath " $libdir" ;;
+	  esac
+	fi
+	case $host in
+	*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)
+	  testbindir=`${ECHO} "$libdir" | ${SED} -e 's*/lib$*/bin*'`
+	  case :$dllsearchpath: in
+	  *":$libdir:"*) ;;
+	  ::) dllsearchpath=$libdir;;
+	  *) func_append dllsearchpath ":$libdir";;
+	  esac
+	  case :$dllsearchpath: in
+	  *":$testbindir:"*) ;;
+	  ::) dllsearchpath=$testbindir;;
+	  *) func_append dllsearchpath ":$testbindir";;
+	  esac
+	  ;;
+	esac
+      done
+      # Substitute the hardcoded libdirs into the rpath.
+      if test -n "$hardcode_libdir_separator" &&
+	 test -n "$hardcode_libdirs"; then
+	libdir="$hardcode_libdirs"
+	eval rpath=\" $hardcode_libdir_flag_spec\"
+      fi
+      compile_rpath="$rpath"
+
+      rpath=
+      hardcode_libdirs=
+      for libdir in $finalize_rpath; do
+	if test -n "$hardcode_libdir_flag_spec"; then
+	  if test -n "$hardcode_libdir_separator"; then
+	    if test -z "$hardcode_libdirs"; then
+	      hardcode_libdirs="$libdir"
+	    else
+	      # Just accumulate the unique libdirs.
+	      case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in
+	      *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*)
+		;;
+	      *)
+		func_append hardcode_libdirs "$hardcode_libdir_separator$libdir"
+		;;
+	      esac
+	    fi
+	  else
+	    eval flag=\"$hardcode_libdir_flag_spec\"
+	    func_append rpath " $flag"
+	  fi
+	elif test -n "$runpath_var"; then
+	  case "$finalize_perm_rpath " in
+	  *" $libdir "*) ;;
+	  *) func_append finalize_perm_rpath " $libdir" ;;
+	  esac
+	fi
+      done
+      # Substitute the hardcoded libdirs into the rpath.
+      if test -n "$hardcode_libdir_separator" &&
+	 test -n "$hardcode_libdirs"; then
+	libdir="$hardcode_libdirs"
+	eval rpath=\" $hardcode_libdir_flag_spec\"
+      fi
+      finalize_rpath="$rpath"
+
+      if test -n "$libobjs" && test "$build_old_libs" = yes; then
+	# Transform all the library objects into standard objects.
+	compile_command=`$ECHO "$compile_command" | $SP2NL | $SED "$lo2o" | $NL2SP`
+	finalize_command=`$ECHO "$finalize_command" | $SP2NL | $SED "$lo2o" | $NL2SP`
+      fi
+
+      func_generate_dlsyms "$outputname" "@PROGRAM@" "no"
+
+      # template prelinking step
+      if test -n "$prelink_cmds"; then
+	func_execute_cmds "$prelink_cmds" 'exit $?'
+      fi
+
+      wrappers_required=yes
+      case $host in
+      *cegcc* | *mingw32ce*)
+        # Disable wrappers for cegcc and mingw32ce hosts, we are cross compiling anyway.
+        wrappers_required=no
+        ;;
+      *cygwin* | *mingw* )
+        if test "$build_libtool_libs" != yes; then
+          wrappers_required=no
+        fi
+        ;;
+      *)
+        if test "$need_relink" = no || test "$build_libtool_libs" != yes; then
+          wrappers_required=no
+        fi
+        ;;
+      esac
+      if test "$wrappers_required" = no; then
+	# Replace the output file specification.
+	compile_command=`$ECHO "$compile_command" | $SED 's%@OUTPUT@%'"$output"'%g'`
+	link_command="$compile_command$compile_rpath"
+
+	# We have no uninstalled library dependencies, so finalize right now.
+	exit_status=0
+	func_show_eval "$link_command" 'exit_status=$?'
+
+	if test -n "$postlink_cmds"; then
+	  func_to_tool_file "$output"
+	  postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'`
+	  func_execute_cmds "$postlink_cmds" 'exit $?'
+	fi
+
+	# Delete the generated files.
+	if test -f "$output_objdir/${outputname}S.${objext}"; then
+	  func_show_eval '$RM "$output_objdir/${outputname}S.${objext}"'
+	fi
+
+	exit $exit_status
+      fi
+
+      if test -n "$compile_shlibpath$finalize_shlibpath"; then
+	compile_command="$shlibpath_var=\"$compile_shlibpath$finalize_shlibpath\$$shlibpath_var\" $compile_command"
+      fi
+      if test -n "$finalize_shlibpath"; then
+	finalize_command="$shlibpath_var=\"$finalize_shlibpath\$$shlibpath_var\" $finalize_command"
+      fi
+
+      compile_var=
+      finalize_var=
+      if test -n "$runpath_var"; then
+	if test -n "$perm_rpath"; then
+	  # We should set the runpath_var.
+	  rpath=
+	  for dir in $perm_rpath; do
+	    func_append rpath "$dir:"
+	  done
+	  compile_var="$runpath_var=\"$rpath\$$runpath_var\" "
+	fi
+	if test -n "$finalize_perm_rpath"; then
+	  # We should set the runpath_var.
+	  rpath=
+	  for dir in $finalize_perm_rpath; do
+	    func_append rpath "$dir:"
+	  done
+	  finalize_var="$runpath_var=\"$rpath\$$runpath_var\" "
+	fi
+      fi
+
+      if test "$no_install" = yes; then
+	# We don't need to create a wrapper script.
+	link_command="$compile_var$compile_command$compile_rpath"
+	# Replace the output file specification.
+	link_command=`$ECHO "$link_command" | $SED 's%@OUTPUT@%'"$output"'%g'`
+	# Delete the old output file.
+	$opt_dry_run || $RM $output
+	# Link the executable and exit
+	func_show_eval "$link_command" 'exit $?'
+
+	if test -n "$postlink_cmds"; then
+	  func_to_tool_file "$output"
+	  postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'`
+	  func_execute_cmds "$postlink_cmds" 'exit $?'
+	fi
+
+	exit $EXIT_SUCCESS
+      fi
+
+      if test "$hardcode_action" = relink; then
+	# Fast installation is not supported
+	link_command="$compile_var$compile_command$compile_rpath"
+	relink_command="$finalize_var$finalize_command$finalize_rpath"
+
+	func_warning "this platform does not like uninstalled shared libraries"
+	func_warning "\`$output' will be relinked during installation"
+      else
+	if test "$fast_install" != no; then
+	  link_command="$finalize_var$compile_command$finalize_rpath"
+	  if test "$fast_install" = yes; then
+	    relink_command=`$ECHO "$compile_var$compile_command$compile_rpath" | $SED 's%@OUTPUT@%\$progdir/\$file%g'`
+	  else
+	    # fast_install is set to needless
+	    relink_command=
+	  fi
+	else
+	  link_command="$compile_var$compile_command$compile_rpath"
+	  relink_command="$finalize_var$finalize_command$finalize_rpath"
+	fi
+      fi
+
+      # Replace the output file specification.
+      link_command=`$ECHO "$link_command" | $SED 's%@OUTPUT@%'"$output_objdir/$outputname"'%g'`
+
+      # Delete the old output files.
+      $opt_dry_run || $RM $output $output_objdir/$outputname $output_objdir/lt-$outputname
+
+      func_show_eval "$link_command" 'exit $?'
+
+      if test -n "$postlink_cmds"; then
+	func_to_tool_file "$output_objdir/$outputname"
+	postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output_objdir/$outputname"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'`
+	func_execute_cmds "$postlink_cmds" 'exit $?'
+      fi
+
+      # Now create the wrapper script.
+      func_verbose "creating $output"
+
+      # Quote the relink command for shipping.
+      if test -n "$relink_command"; then
+	# Preserve any variables that may affect compiler behavior
+	for var in $variables_saved_for_relink; do
+	  if eval test -z \"\${$var+set}\"; then
+	    relink_command="{ test -z \"\${$var+set}\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command"
+	  elif eval var_value=\$$var; test -z "$var_value"; then
+	    relink_command="$var=; export $var; $relink_command"
+	  else
+	    func_quote_for_eval "$var_value"
+	    relink_command="$var=$func_quote_for_eval_result; export $var; $relink_command"
+	  fi
+	done
+	relink_command="(cd `pwd`; $relink_command)"
+	relink_command=`$ECHO "$relink_command" | $SED "$sed_quote_subst"`
+      fi
+
+      # Only actually do things if not in dry run mode.
+      $opt_dry_run || {
+	# win32 will think the script is a binary if it has
+	# a .exe suffix, so we strip it off here.
+	case $output in
+	  *.exe) func_stripname '' '.exe' "$output"
+	         output=$func_stripname_result ;;
+	esac
+	# test for cygwin because mv fails w/o .exe extensions
+	case $host in
+	  *cygwin*)
+	    exeext=.exe
+	    func_stripname '' '.exe' "$outputname"
+	    outputname=$func_stripname_result ;;
+	  *) exeext= ;;
+	esac
+	case $host in
+	  *cygwin* | *mingw* )
+	    func_dirname_and_basename "$output" "" "."
+	    output_name=$func_basename_result
+	    output_path=$func_dirname_result
+	    cwrappersource="$output_path/$objdir/lt-$output_name.c"
+	    cwrapper="$output_path/$output_name.exe"
+	    $RM $cwrappersource $cwrapper
+	    trap "$RM $cwrappersource $cwrapper; exit $EXIT_FAILURE" 1 2 15
+
+	    func_emit_cwrapperexe_src > $cwrappersource
+
+	    # The wrapper executable is built using the $host compiler,
+	    # because it contains $host paths and files. If cross-
+	    # compiling, it, like the target executable, must be
+	    # executed on the $host or under an emulation environment.
+	    $opt_dry_run || {
+	      $LTCC $LTCFLAGS -o $cwrapper $cwrappersource
+	      $STRIP $cwrapper
+	    }
+
+	    # Now, create the wrapper script for func_source use:
+	    func_ltwrapper_scriptname $cwrapper
+	    $RM $func_ltwrapper_scriptname_result
+	    trap "$RM $func_ltwrapper_scriptname_result; exit $EXIT_FAILURE" 1 2 15
+	    $opt_dry_run || {
+	      # note: this script will not be executed, so do not chmod.
+	      if test "x$build" = "x$host" ; then
+		$cwrapper --lt-dump-script > $func_ltwrapper_scriptname_result
+	      else
+		func_emit_wrapper no > $func_ltwrapper_scriptname_result
+	      fi
+	    }
+	  ;;
+	  * )
+	    $RM $output
+	    trap "$RM $output; exit $EXIT_FAILURE" 1 2 15
+
+	    func_emit_wrapper no > $output
+	    chmod +x $output
+	  ;;
+	esac
+      }
+      exit $EXIT_SUCCESS
+      ;;
+    esac
+
+    # See if we need to build an old-fashioned archive.
+    for oldlib in $oldlibs; do
+
+      if test "$build_libtool_libs" = convenience; then
+	oldobjs="$libobjs_save $symfileobj"
+	addlibs="$convenience"
+	build_libtool_libs=no
+      else
+	if test "$build_libtool_libs" = module; then
+	  oldobjs="$libobjs_save"
+	  build_libtool_libs=no
+	else
+	  oldobjs="$old_deplibs $non_pic_objects"
+	  if test "$preload" = yes && test -f "$symfileobj"; then
+	    func_append oldobjs " $symfileobj"
+	  fi
+	fi
+	addlibs="$old_convenience"
+      fi
+
+      if test -n "$addlibs"; then
+	gentop="$output_objdir/${outputname}x"
+	func_append generated " $gentop"
+
+	func_extract_archives $gentop $addlibs
+	func_append oldobjs " $func_extract_archives_result"
+      fi
+
+      # Do each command in the archive commands.
+      if test -n "$old_archive_from_new_cmds" && test "$build_libtool_libs" = yes; then
+	cmds=$old_archive_from_new_cmds
+      else
+
+	# Add any objects from preloaded convenience libraries
+	if test -n "$dlprefiles"; then
+	  gentop="$output_objdir/${outputname}x"
+	  func_append generated " $gentop"
+
+	  func_extract_archives $gentop $dlprefiles
+	  func_append oldobjs " $func_extract_archives_result"
+	fi
+
+	# POSIX demands no paths to be encoded in archives.  We have
+	# to avoid creating archives with duplicate basenames if we
+	# might have to extract them afterwards, e.g., when creating a
+	# static archive out of a convenience library, or when linking
+	# the entirety of a libtool archive into another (currently
+	# not supported by libtool).
+	if (for obj in $oldobjs
+	    do
+	      func_basename "$obj"
+	      $ECHO "$func_basename_result"
+	    done | sort | sort -uc >/dev/null 2>&1); then
+	  :
+	else
+	  echo "copying selected object files to avoid basename conflicts..."
+	  gentop="$output_objdir/${outputname}x"
+	  func_append generated " $gentop"
+	  func_mkdir_p "$gentop"
+	  save_oldobjs=$oldobjs
+	  oldobjs=
+	  counter=1
+	  for obj in $save_oldobjs
+	  do
+	    func_basename "$obj"
+	    objbase="$func_basename_result"
+	    case " $oldobjs " in
+	    " ") oldobjs=$obj ;;
+	    *[\ /]"$objbase "*)
+	      while :; do
+		# Make sure we don't pick an alternate name that also
+		# overlaps.
+		newobj=lt$counter-$objbase
+		func_arith $counter + 1
+		counter=$func_arith_result
+		case " $oldobjs " in
+		*[\ /]"$newobj "*) ;;
+		*) if test ! -f "$gentop/$newobj"; then break; fi ;;
+		esac
+	      done
+	      func_show_eval "ln $obj $gentop/$newobj || cp $obj $gentop/$newobj"
+	      func_append oldobjs " $gentop/$newobj"
+	      ;;
+	    *) func_append oldobjs " $obj" ;;
+	    esac
+	  done
+	fi
+	func_to_tool_file "$oldlib" func_convert_file_msys_to_w32
+	tool_oldlib=$func_to_tool_file_result
+	eval cmds=\"$old_archive_cmds\"
+
+	func_len " $cmds"
+	len=$func_len_result
+	if test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then
+	  cmds=$old_archive_cmds
+	elif test -n "$archiver_list_spec"; then
+	  func_verbose "using command file archive linking..."
+	  for obj in $oldobjs
+	  do
+	    func_to_tool_file "$obj"
+	    $ECHO "$func_to_tool_file_result"
+	  done > $output_objdir/$libname.libcmd
+	  func_to_tool_file "$output_objdir/$libname.libcmd"
+	  oldobjs=" $archiver_list_spec$func_to_tool_file_result"
+	  cmds=$old_archive_cmds
+	else
+	  # the command line is too long to link in one step, link in parts
+	  func_verbose "using piecewise archive linking..."
+	  save_RANLIB=$RANLIB
+	  RANLIB=:
+	  objlist=
+	  concat_cmds=
+	  save_oldobjs=$oldobjs
+	  oldobjs=
+	  # Is there a better way of finding the last object in the list?
+	  for obj in $save_oldobjs
+	  do
+	    last_oldobj=$obj
+	  done
+	  eval test_cmds=\"$old_archive_cmds\"
+	  func_len " $test_cmds"
+	  len0=$func_len_result
+	  len=$len0
+	  for obj in $save_oldobjs
+	  do
+	    func_len " $obj"
+	    func_arith $len + $func_len_result
+	    len=$func_arith_result
+	    func_append objlist " $obj"
+	    if test "$len" -lt "$max_cmd_len"; then
+	      :
+	    else
+	      # the above command should be used before it gets too long
+	      oldobjs=$objlist
+	      if test "$obj" = "$last_oldobj" ; then
+		RANLIB=$save_RANLIB
+	      fi
+	      test -z "$concat_cmds" || concat_cmds=$concat_cmds~
+	      eval concat_cmds=\"\${concat_cmds}$old_archive_cmds\"
+	      objlist=
+	      len=$len0
+	    fi
+	  done
+	  RANLIB=$save_RANLIB
+	  oldobjs=$objlist
+	  if test "X$oldobjs" = "X" ; then
+	    eval cmds=\"\$concat_cmds\"
+	  else
+	    eval cmds=\"\$concat_cmds~\$old_archive_cmds\"
+	  fi
+	fi
+      fi
+      func_execute_cmds "$cmds" 'exit $?'
+    done
+
+    test -n "$generated" && \
+      func_show_eval "${RM}r$generated"
+
+    # Now create the libtool archive.
+    case $output in
+    *.la)
+      old_library=
+      test "$build_old_libs" = yes && old_library="$libname.$libext"
+      func_verbose "creating $output"
+
+      # Preserve any variables that may affect compiler behavior
+      for var in $variables_saved_for_relink; do
+	if eval test -z \"\${$var+set}\"; then
+	  relink_command="{ test -z \"\${$var+set}\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command"
+	elif eval var_value=\$$var; test -z "$var_value"; then
+	  relink_command="$var=; export $var; $relink_command"
+	else
+	  func_quote_for_eval "$var_value"
+	  relink_command="$var=$func_quote_for_eval_result; export $var; $relink_command"
+	fi
+      done
+      # Quote the link command for shipping.
+      relink_command="(cd `pwd`; $SHELL $progpath $preserve_args --mode=relink $libtool_args @inst_prefix_dir@)"
+      relink_command=`$ECHO "$relink_command" | $SED "$sed_quote_subst"`
+      if test "$hardcode_automatic" = yes ; then
+	relink_command=
+      fi
+
+      # Only create the output if not a dry run.
+      $opt_dry_run || {
+	for installed in no yes; do
+	  if test "$installed" = yes; then
+	    if test -z "$install_libdir"; then
+	      break
+	    fi
+	    output="$output_objdir/$outputname"i
+	    # Replace all uninstalled libtool libraries with the installed ones
+	    newdependency_libs=
+	    for deplib in $dependency_libs; do
+	      case $deplib in
+	      *.la)
+		func_basename "$deplib"
+		name="$func_basename_result"
+		func_resolve_sysroot "$deplib"
+		eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $func_resolve_sysroot_result`
+		test -z "$libdir" && \
+		  func_fatal_error "\`$deplib' is not a valid libtool archive"
+		func_append newdependency_libs " ${lt_sysroot:+=}$libdir/$name"
+		;;
+	      -L*)
+		func_stripname -L '' "$deplib"
+		func_replace_sysroot "$func_stripname_result"
+		func_append newdependency_libs " -L$func_replace_sysroot_result"
+		;;
+	      -R*)
+		func_stripname -R '' "$deplib"
+		func_replace_sysroot "$func_stripname_result"
+		func_append newdependency_libs " -R$func_replace_sysroot_result"
+		;;
+	      *) func_append newdependency_libs " $deplib" ;;
+	      esac
+	    done
+	    dependency_libs="$newdependency_libs"
+	    newdlfiles=
+
+	    for lib in $dlfiles; do
+	      case $lib in
+	      *.la)
+	        func_basename "$lib"
+		name="$func_basename_result"
+		eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib`
+		test -z "$libdir" && \
+		  func_fatal_error "\`$lib' is not a valid libtool archive"
+		func_append newdlfiles " ${lt_sysroot:+=}$libdir/$name"
+		;;
+	      *) func_append newdlfiles " $lib" ;;
+	      esac
+	    done
+	    dlfiles="$newdlfiles"
+	    newdlprefiles=
+	    for lib in $dlprefiles; do
+	      case $lib in
+	      *.la)
+		# Only pass preopened files to the pseudo-archive (for
+		# eventual linking with the app. that links it) if we
+		# didn't already link the preopened objects directly into
+		# the library:
+		func_basename "$lib"
+		name="$func_basename_result"
+		eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib`
+		test -z "$libdir" && \
+		  func_fatal_error "\`$lib' is not a valid libtool archive"
+		func_append newdlprefiles " ${lt_sysroot:+=}$libdir/$name"
+		;;
+	      esac
+	    done
+	    dlprefiles="$newdlprefiles"
+	  else
+	    newdlfiles=
+	    for lib in $dlfiles; do
+	      case $lib in
+		[\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;;
+		*) abs=`pwd`"/$lib" ;;
+	      esac
+	      func_append newdlfiles " $abs"
+	    done
+	    dlfiles="$newdlfiles"
+	    newdlprefiles=
+	    for lib in $dlprefiles; do
+	      case $lib in
+		[\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;;
+		*) abs=`pwd`"/$lib" ;;
+	      esac
+	      func_append newdlprefiles " $abs"
+	    done
+	    dlprefiles="$newdlprefiles"
+	  fi
+	  $RM $output
+	  # place dlname in correct position for cygwin
+	  # In fact, it would be nice if we could use this code for all target
+	  # systems that can't hard-code library paths into their executables
+	  # and that have no shared library path variable independent of PATH,
+	  # but it turns out we can't easily determine that from inspecting
+	  # libtool variables, so we have to hard-code the OSs to which it
+	  # applies here; at the moment, that means platforms that use the PE
+	  # object format with DLL files.  See the long comment at the top of
+	  # tests/bindir.at for full details.
+	  tdlname=$dlname
+	  case $host,$output,$installed,$module,$dlname in
+	    *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll | *cegcc*,*lai,yes,no,*.dll)
+	      # If a -bindir argument was supplied, place the dll there.
+	      if test "x$bindir" != x ;
+	      then
+		func_relative_path "$install_libdir" "$bindir"
+		tdlname=$func_relative_path_result$dlname
+	      else
+		# Otherwise fall back on heuristic.
+		tdlname=../bin/$dlname
+	      fi
+	      ;;
+	  esac
+	  $ECHO > $output "\
+# $outputname - a libtool library file
+# Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION
+#
+# Please DO NOT delete this file!
+# It is necessary for linking the library.
+
+# The name that we can dlopen(3).
+dlname='$tdlname'
+
+# Names of this library.
+library_names='$library_names'
+
+# The name of the static archive.
+old_library='$old_library'
+
+# Linker flags that can not go in dependency_libs.
+inherited_linker_flags='$new_inherited_linker_flags'
+
+# Libraries that this one depends upon.
+dependency_libs='$dependency_libs'
+
+# Names of additional weak libraries provided by this library
+weak_library_names='$weak_libs'
+
+# Version information for $libname.
+current=$current
+age=$age
+revision=$revision
+
+# Is this an already installed library?
+installed=$installed
+
+# Should we warn about portability when linking against -modules?
+shouldnotlink=$module
+
+# Files to dlopen/dlpreopen
+dlopen='$dlfiles'
+dlpreopen='$dlprefiles'
+
+# Directory that this library needs to be installed in:
+libdir='$install_libdir'"
+	  if test "$installed" = no && test "$need_relink" = yes; then
+	    $ECHO >> $output "\
+relink_command=\"$relink_command\""
+	  fi
+	done
+      }
+
+      # Do a symbolic link so that the libtool archive can be found in
+      # LD_LIBRARY_PATH before the program is installed.
+      func_show_eval '( cd "$output_objdir" && $RM "$outputname" && $LN_S "../$outputname" "$outputname" )' 'exit $?'
+      ;;
+    esac
+    exit $EXIT_SUCCESS
+}
+
+{ test "$opt_mode" = link || test "$opt_mode" = relink; } &&
+    func_mode_link ${1+"$@"}
+
+
+# func_mode_uninstall arg...
+func_mode_uninstall ()
+{
+    $opt_debug
+    RM="$nonopt"
+    files=
+    rmforce=
+    exit_status=0
+
+    # This variable tells wrapper scripts just to set variables rather
+    # than running their programs.
+    libtool_install_magic="$magic"
+
+    for arg
+    do
+      case $arg in
+      -f) func_append RM " $arg"; rmforce=yes ;;
+      -*) func_append RM " $arg" ;;
+      *) func_append files " $arg" ;;
+      esac
+    done
+
+    test -z "$RM" && \
+      func_fatal_help "you must specify an RM program"
+
+    rmdirs=
+
+    for file in $files; do
+      func_dirname "$file" "" "."
+      dir="$func_dirname_result"
+      if test "X$dir" = X.; then
+	odir="$objdir"
+      else
+	odir="$dir/$objdir"
+      fi
+      func_basename "$file"
+      name="$func_basename_result"
+      test "$opt_mode" = uninstall && odir="$dir"
+
+      # Remember odir for removal later, being careful to avoid duplicates
+      if test "$opt_mode" = clean; then
+	case " $rmdirs " in
+	  *" $odir "*) ;;
+	  *) func_append rmdirs " $odir" ;;
+	esac
+      fi
+
+      # Don't error if the file doesn't exist and rm -f was used.
+      if { test -L "$file"; } >/dev/null 2>&1 ||
+	 { test -h "$file"; } >/dev/null 2>&1 ||
+	 test -f "$file"; then
+	:
+      elif test -d "$file"; then
+	exit_status=1
+	continue
+      elif test "$rmforce" = yes; then
+	continue
+      fi
+
+      rmfiles="$file"
+
+      case $name in
+      *.la)
+	# Possibly a libtool archive, so verify it.
+	if func_lalib_p "$file"; then
+	  func_source $dir/$name
+
+	  # Delete the libtool libraries and symlinks.
+	  for n in $library_names; do
+	    func_append rmfiles " $odir/$n"
+	  done
+	  test -n "$old_library" && func_append rmfiles " $odir/$old_library"
+
+	  case "$opt_mode" in
+	  clean)
+	    case " $library_names " in
+	    *" $dlname "*) ;;
+	    *) test -n "$dlname" && func_append rmfiles " $odir/$dlname" ;;
+	    esac
+	    test -n "$libdir" && func_append rmfiles " $odir/$name $odir/${name}i"
+	    ;;
+	  uninstall)
+	    if test -n "$library_names"; then
+	      # Do each command in the postuninstall commands.
+	      func_execute_cmds "$postuninstall_cmds" 'test "$rmforce" = yes || exit_status=1'
+	    fi
+
+	    if test -n "$old_library"; then
+	      # Do each command in the old_postuninstall commands.
+	      func_execute_cmds "$old_postuninstall_cmds" 'test "$rmforce" = yes || exit_status=1'
+	    fi
+	    # FIXME: should reinstall the best remaining shared library.
+	    ;;
+	  esac
+	fi
+	;;
+
+      *.lo)
+	# Possibly a libtool object, so verify it.
+	if func_lalib_p "$file"; then
+
+	  # Read the .lo file
+	  func_source $dir/$name
+
+	  # Add PIC object to the list of files to remove.
+	  if test -n "$pic_object" &&
+	     test "$pic_object" != none; then
+	    func_append rmfiles " $dir/$pic_object"
+	  fi
+
+	  # Add non-PIC object to the list of files to remove.
+	  if test -n "$non_pic_object" &&
+	     test "$non_pic_object" != none; then
+	    func_append rmfiles " $dir/$non_pic_object"
+	  fi
+	fi
+	;;
+
+      *)
+	if test "$opt_mode" = clean ; then
+	  noexename=$name
+	  case $file in
+	  *.exe)
+	    func_stripname '' '.exe' "$file"
+	    file=$func_stripname_result
+	    func_stripname '' '.exe' "$name"
+	    noexename=$func_stripname_result
+	    # $file with .exe has already been added to rmfiles,
+	    # add $file without .exe
+	    func_append rmfiles " $file"
+	    ;;
+	  esac
+	  # Do a test to see if this is a libtool program.
+	  if func_ltwrapper_p "$file"; then
+	    if func_ltwrapper_executable_p "$file"; then
+	      func_ltwrapper_scriptname "$file"
+	      relink_command=
+	      func_source $func_ltwrapper_scriptname_result
+	      func_append rmfiles " $func_ltwrapper_scriptname_result"
+	    else
+	      relink_command=
+	      func_source $dir/$noexename
+	    fi
+
+	    # note $name still contains .exe if it was in $file originally
+	    # as does the version of $file that was added into $rmfiles
+	    func_append rmfiles " $odir/$name $odir/${name}S.${objext}"
+	    if test "$fast_install" = yes && test -n "$relink_command"; then
+	      func_append rmfiles " $odir/lt-$name"
+	    fi
+	    if test "X$noexename" != "X$name" ; then
+	      func_append rmfiles " $odir/lt-${noexename}.c"
+	    fi
+	  fi
+	fi
+	;;
+      esac
+      func_show_eval "$RM $rmfiles" 'exit_status=1'
+    done
+
+    # Try to remove the ${objdir}s in the directories where we deleted files
+    for dir in $rmdirs; do
+      if test -d "$dir"; then
+	func_show_eval "rmdir $dir >/dev/null 2>&1"
+      fi
+    done
+
+    exit $exit_status
+}
+
+{ test "$opt_mode" = uninstall || test "$opt_mode" = clean; } &&
+    func_mode_uninstall ${1+"$@"}
+
+test -z "$opt_mode" && {
+  help="$generic_help"
+  func_fatal_help "you must specify a MODE"
+}
+
+test -z "$exec_cmd" && \
+  func_fatal_help "invalid operation mode \`$opt_mode'"
+
+if test -n "$exec_cmd"; then
+  eval exec "$exec_cmd"
+  exit $EXIT_FAILURE
+fi
+
+exit $exit_status
+
+
+# The TAGs below are defined such that we never get into a situation
+# in which we disable both kinds of libraries.  Given conflicting
+# choices, we go for a static library, that is the most portable,
+# since we can't tell whether shared libraries were disabled because
+# the user asked for that or because the platform doesn't support
+# them.  This is particularly important on AIX, because we don't
+# support having both static and shared libraries enabled at the same
+# time on that platform, so we default to a shared-only configuration.
+# If a disable-shared tag is given, we'll fallback to a static-only
+# configuration.  But we'll never go from static-only to shared-only.
+
+# ### BEGIN LIBTOOL TAG CONFIG: disable-shared
+build_libtool_libs=no
+build_old_libs=yes
+# ### END LIBTOOL TAG CONFIG: disable-shared
+
+# ### BEGIN LIBTOOL TAG CONFIG: disable-static
+build_old_libs=`case $build_libtool_libs in yes) echo no;; *) echo yes;; esac`
+# ### END LIBTOOL TAG CONFIG: disable-static
+
+# Local Variables:
+# mode:shell-script
+# sh-indentation:2
+# End:
+# vi:sw=2
+
diff --git a/m4/apache.m4 b/m4/apache.m4
new file mode 100644
index 0000000..e16385d
--- /dev/null
+++ b/m4/apache.m4
@@ -0,0 +1,124 @@
+# macro that is used to parse a --with-apxs parameter
+AC_DEFUN([APXS_CHECK],[
+    AC_SUBST(APXS)
+    
+    AC_ARG_WITH(
+        apxs,
+        [  --with-apxs[=/path/to/apxs]     Apache 2 apxs tool location],
+        ,
+        [with_apxs="yes"]
+    )
+    
+    if test "$with_apxs" = "yes"; then
+        AC_PATH_PROG(APXS, apxs2)
+        if test -z "$APXS"; then
+            AC_PATH_PROG(APXS, apxs)
+        fi
+    elif test "$with_apxs" = "no"; then
+        AC_MSG_ERROR(apxs is required and cannot be disabled)
+    else
+        AC_MSG_CHECKING(for apxs usability in $with_apxs)
+        if test -x "$with_apxs"; then
+            APXS=$with_apxs
+            AC_MSG_RESULT(yes)
+        else
+            AC_MSG_ERROR($with_apxs not found or not executable)
+        fi
+    fi
+    if test -z "$APXS"; then
+        AC_MSG_ERROR(apxs utility not found. use --with-apxs to specify its location.)
+    fi
+    AC_SUBST(APXS)
+    APACHE_SBINDIR=`$APXS -q SBINDIR`
+    APACHE_BINDIR=`$APXS -q BINDIR`
+    AC_SUBST(APACHE_SBINDIR)
+    AC_SUBST(APACHE_BINDIR)
+    AC_MSG_CHECKING([for apachectl utility])
+    APACHECTL=
+    if test -x "$APACHE_SBINDIR/apachectl" ; then
+      APACHECTL="$APACHE_SBINDIR/apachectl" 
+    else
+      if test -x "$APACHE_SBINDIR/apache2ctl" ; then
+        APACHECTL="$APACHE_SBINDIR/apache2ctl" 
+      else
+        AC_PATH_PROG(APACHECTL,apachectl)
+        if test -z "$APACHECTL"; then
+          AC_PATH_PROG(APACHECTL,apache2ctl)
+        fi
+      fi
+    fi
+    
+    if test -z "$APACHECTL"; then
+      AC_MSG_RESULT([Unable to find apachectl utility, you will not be able to restart
+                   and install module with the created Makefile])
+    else
+      AC_MSG_RESULT([$APACHECTL])
+    fi
+    AC_SUBST(APACHECTL)
+    AC_SUBST(APACHE_INC,-I`$APXS -q INCLUDEDIR`)
+    AC_SUBST(APACHE_LIBS,`$APXS -q LIBS`)
+    AC_SUBST(APACHE_LDFLAGS,`$APXS -q LDFLAGS`)
+    SBINDIR=`$APXS -q SBINDIR`
+    TARGET=`$APXS -q TARGET`
+    HTTPD="$SBINDIR/$TARGET"
+    AC_SUBST(HTTPD,"$HTTPD")
+    
+])
+ 
+AC_DEFUN([APR_CHECK],[
+  AC_SUBST(APRCONFIG)
+  AC_ARG_WITH(apr_config,
+    AC_HELP_STRING([--with-apr-config], [path to apr-config program]),
+    ,
+    [with_apr_config=yes]
+  )
+    if test "$with_apr_config" = "yes"; then
+        AC_MSG_CHECKING(for apr-config in default locations)
+        if test -n "$APXS"; then
+            APXSFULL=`which "$APXS"`
+            APXSDIR=`dirname "$APXSFULL"`
+            if test -x "$APXSDIR/apr-config"; then
+                APRCONFIG="$APXSDIR/apr-config"
+            elif test -x "$APACHE_SBINDIR/apr-config"; then
+                APRCONFIG="$APACHE_SBINDIR/apr-config"
+            elif test -x "$APACHE_BINDIR/apr-config"; then
+                APRCONFIG="$APACHE_BINDIR/apr-config"
+            elif test -x "$APXSDIR/apr-1-config"; then
+                APRCONFIG="$APXSDIR/apr-1-config"
+            elif test -x "$APACHE_SBINDIR/apr-1-config"; then
+                APRCONFIG="$APACHE_SBINDIR/apr-1-config"
+            elif test -x "$APACHE_BINDIR/apr-1-config"; then
+                APRCONFIG="$APACHE_BINDIR/apr-1-config"
+            fi
+        fi
+        if test -z "$APRCONFIG"; then
+            AC_PATH_PROG(APRCONFIG, apr-config)
+        fi
+        if test -z "$APRCONFIG"; then
+            AC_PATH_PROG(APRCONFIG, apr-1-config)
+        fi
+        if test -n "$APRCONFIG"; then
+            AC_MSG_RESULT([using $APRCONFIG, use --with-apr-config=/path/to/apr-(1-)config to modify])
+        else
+            AC_MSG_RESULT([not found])
+        fi
+    elif test "$with_apr_config" = "no"; then
+        AC_MSG_ERROR(apr-config is required and cannot be disabled)
+    else
+        AC_MSG_CHECKING(for apr-config usability in $with_apr_config)
+        if test -x "$with_apr_config"; then
+            APRCONFIG=$with_apr_config
+            AC_MSG_RESULT(yes)
+        else
+            AC_MSG_ERROR($with_apr_config not found or not executable)
+        fi
+    fi
+    if test -z "$APRCONFIG"; then
+        AC_MSG_ERROR(apr-config utility not found. use --with-apr-config to specify its location.)
+    fi
+    AC_SUBST(APRCONFIG)
+    AC_SUBST(APR_CFLAGS,`$APRCONFIG --cppflags --cflags`) 
+    AC_SUBST(APR_INC,`$APRCONFIG --includes`)
+    AC_SUBST(APR_LIBS,`$APRCONFIG --link-libtool`)
+])
+
diff --git a/m4/ax_append_flag.m4 b/m4/ax_append_flag.m4
new file mode 100644
index 0000000..39c7a86
--- /dev/null
+++ b/m4/ax_append_flag.m4
@@ -0,0 +1,241 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
+<!-- git web interface version 1.7.2.5, (C) 2005-2006, Kay Sievers <kay.sievers at vrfy.org>, Christian Gierke -->
+<!-- git core binaries version 1.7.2.5 -->
+<head>
+<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
+<meta name="generator" content="gitweb/1.7.2.5 git/1.7.2.5"/>
+<meta name="robots" content="index, nofollow"/>
+<title>Savannah Git Hosting - autoconf-archive.git/summary</title>
+<link rel="stylesheet" type="text/css" href="gitweb.css"/>
+<link rel="alternate" title="autoconf-archive.git - log - RSS feed" href="/gitweb/?p=autoconf-archive.git;a=rss" type="application/rss+xml" />
+<link rel="alternate" title="autoconf-archive.git - log - RSS feed (no merges)" href="/gitweb/?p=autoconf-archive.git;a=rss;opt=--no-merges" type="application/rss+xml" />
+<link rel="alternate" title="autoconf-archive.git - log - Atom feed" href="/gitweb/?p=autoconf-archive.git;a=atom;opt=--no-merges" type="application/atom+xml" />
+<link rel="alternate" title="autoconf-archive.git - log - Atom feed (no merges)" href="/gitweb/?p=autoconf-archive.git;a=atom;opt=--no-merges" type="application/atom+xml" />
+<link rel="shortcut icon" href="git-favicon.png" type="image/png" />
+</head>
+<body>
+<div class="page_header">
+<a title="git homepage" href="http://git-scm.com/"><img src="git-logo.png" width="72" height="27" alt="git" class="logo"/></a><a href="/gitweb/">git at sv</a> / <a href="/gitweb/?p=autoconf-archive.git;a=summary">autoconf-archive.git</a> / summary
+</div>
+<form method="get" action="/gitweb/" enctype="application/x-www-form-urlencoded">
+<div class="search">
+<input name="p" type="hidden" value="autoconf-archive.git" />
+<input name="a" type="hidden" value="search" />
+<input name="h" type="hidden" value="HEAD" />
+<select name="st" >
+<option selected="selected" value="commit">commit</option>
+<option value="grep">grep</option>
+<option value="author">author</option>
+<option value="committer">committer</option>
+<option value="pickaxe">pickaxe</option>
+</select><sup><a href="/gitweb/?p=autoconf-archive.git;a=search_help">?</a></sup> search:
+<input type="text" name="s"  />
+<span title="Extended regular expression"><label><input type="checkbox" name="sr" value="1" />re</label></span></div>
+</form>
+<div class="page_nav">
+summary | <a href="/gitweb/?p=autoconf-archive.git;a=shortlog">shortlog</a> | <a href="/gitweb/?p=autoconf-archive.git;a=log">log</a> | <a href="/gitweb/?p=autoconf-archive.git;a=commit;h=4696309f0f32878dc88f02a912258c27ab732f41">commit</a> | <a href="/gitweb/?p=autoconf-archive.git;a=commitdiff;h=4696309f0f32878dc88f02a912258c27ab732f41">commitdiff</a> | <a href="/gitweb/?p=autoconf-archive.git;a=tree">tree</a><br/>
+<br/>
+</div>
+<div class="title"> </div>
+<table class="projects_list">
+<tr id="metadata_desc"><td>description</td><td>autoconf-archive</td></tr>
+<tr id="metadata_owner"><td>owner</td><td></td></tr>
+<tr id="metadata_lchange"><td>last change</td><td>Wed, 21 Dec 2011 11:08:23 +0000</td></tr>
+<tr class="metadata_url"><td>URL</td><td>git://git.sv.gnu.org/autoconf-archive.git</td></tr>
+<tr class="metadata_url"><td></td><td>http://git.savannah.gnu.org/r/autoconf-archive.git</td></tr>
+<tr class="metadata_url"><td></td><td>ssh://git.sv.gnu.org/srv/git/autoconf-archive.git</td></tr>
+</table>
+<div class="header">
+<a class="title" href="/gitweb/?p=autoconf-archive.git;a=shortlog">shortlog</a>
+</div>
+<table class="shortlog">
+<tr class="dark">
+<td title="2011-12-21"><i>5 hours ago</i></td>
+<td class="author"><a title="Search for commits authored by Peter Simons" class="list" href="/gitweb/?p=autoconf-archive.git;a=search;s=Peter+Simons;st=author">Peter Simons</a></td><td><a class="list subject" title="README-maint: updated the documentation of the release procedure" href="/gitweb/?p=autoconf-archive.git;a=commit;h=4696309f0f32878dc88f02a912258c27ab732f41">README-maint: updated the documentation of the release... </a> <span class="refs"> <span class="head" title="heads/master"><a href="/gitweb/?p=autoconf-archive.git;a=shortlog;h=refs/heads/master">master</a></span></span></td>
+<td class="link"><a href="/gitweb/?p=autoconf-archive.git;a=commit;h=4696309f0f32878dc88f02a912258c27ab732f41">commit</a> | <a href="/gitweb/?p=autoconf-archive.git;a=commitdiff;h=4696309f0f32878dc88f02a912258c27ab732f41">commitdiff</a> | <a href="/gitweb/?p=autoconf-archive.git;a=tree;h=4696309f0f32878dc88f02a912258c27ab732f41;hb=4696309f0f32878dc88f02a912258c27ab732f41">tree</a> | <a title="in format: tar.gz" href="/gitweb/?p=autoconf-archive.git;a=snapshot;h=4696309f0f32878dc88f02a912258c27ab732f41;sf=tgz">snapshot</a></td>
+</tr>
+<tr class="light">
+<td title="2011-12-21"><i>5 hours ago</i></td>
+<td class="author"><a title="Search for commits authored by Peter Simons" class="list" href="/gitweb/?p=autoconf-archive.git;a=search;s=Peter+Simons;st=author">Peter Simons</a></td><td><a class="list subject" href="/gitweb/?p=autoconf-archive.git;a=commit;h=52959f86fa0e77f629551dbc66fcc9ee2d331950">maint: post-release administrivia</a></td>
+<td class="link"><a href="/gitweb/?p=autoconf-archive.git;a=commit;h=52959f86fa0e77f629551dbc66fcc9ee2d331950">commit</a> | <a href="/gitweb/?p=autoconf-archive.git;a=commitdiff;h=52959f86fa0e77f629551dbc66fcc9ee2d331950">commitdiff</a> | <a href="/gitweb/?p=autoconf-archive.git;a=tree;h=52959f86fa0e77f629551dbc66fcc9ee2d331950;hb=52959f86fa0e77f629551dbc66fcc9ee2d331950">tree</a> | <a title="in format: tar.gz" href="/gitweb/?p=autoconf-archive.git;a=snapshot;h=52959f86fa0e77f629551dbc66fcc9ee2d331950;sf=tgz">snapshot</a></td>
+</tr>
+<tr class="dark">
+<td title="2011-12-21"><i>5 hours ago</i></td>
+<td class="author"><a title="Search for commits authored by Peter Simons" class="list" href="/gitweb/?p=autoconf-archive.git;a=search;s=Peter+Simons;st=author">Peter Simons</a></td><td><a class="list subject" href="/gitweb/?p=autoconf-archive.git;a=commit;h=77bb2ab18a583eca3717406e47cba73426f59ab1">README, NEWS: bumped version number for release</a> <span class="refs"> <span class="tag indirect" title="tags/v2011.12.21"><a href="/gitweb/?p=autoconf-archive.git;a=tag;h=refs/tags/v2011.12.21">v2011.12.21</a></span></span></td>
+<td class="link"><a href="/gitweb/?p=autoconf-archive.git;a=commit;h=77bb2ab18a583eca3717406e47cba73426f59ab1">commit</a> | <a href="/gitweb/?p=autoconf-archive.git;a=commitdiff;h=77bb2ab18a583eca3717406e47cba73426f59ab1">commitdiff</a> | <a href="/gitweb/?p=autoconf-archive.git;a=tree;h=77bb2ab18a583eca3717406e47cba73426f59ab1;hb=77bb2ab18a583eca3717406e47cba73426f59ab1">tree</a> | <a title="in format: tar.gz" href="/gitweb/?p=autoconf-archive.git;a=snapshot;h=77bb2ab18a583eca3717406e47cba73426f59ab1;sf=tgz">snapshot</a></td>
+</tr>
+<tr class="light">
+<td title="2 weeks ago"><i>2011-12-02</i></td>
+<td class="author"><a title="Search for commits authored by Stephan Sürken" class="list" href="/gitweb/?p=autoconf-archive.git;a=search;s=Stephan+S%C3%BCrken;st=author">Stephan Sürken</a></td><td><a class="list subject" title="AX_BERKELEY_DB_CXX: Add 'AC_LANG_ASSERT(C++)' (as suggested by Amir Taaki, thanks!)." href="/gitweb/?p=autoconf-archive.git;a=commit;h=abb350c0ff5ea95f1e309adb8f46ffcd4245c6c6">AX_BERKELEY_DB_CXX: Add 'AC_LANG_ASSERT(C++)' (as sugge... </a></td>
+<td class="link"><a href="/gitweb/?p=autoconf-archive.git;a=commit;h=abb350c0ff5ea95f1e309adb8f46ffcd4245c6c6">commit</a> | <a href="/gitweb/?p=autoconf-archive.git;a=commitdiff;h=abb350c0ff5ea95f1e309adb8f46ffcd4245c6c6">commitdiff</a> | <a href="/gitweb/?p=autoconf-archive.git;a=tree;h=abb350c0ff5ea95f1e309adb8f46ffcd4245c6c6;hb=abb350c0ff5ea95f1e309adb8f46ffcd4245c6c6">tree</a> | <a title="in format: tar.gz" href="/gitweb/?p=autoconf-archive.git;a=snapshot;h=abb350c0ff5ea95f1e309adb8f46ffcd4245c6c6;sf=tgz">snapshot</a></td>
+</tr>
+<tr class="dark">
+<td title="4 weeks ago"><i>2011-11-22</i></td>
+<td class="author"><a title="Search for commits authored by Rhys Ulerich" class="list" href="/gitweb/?p=autoconf-archive.git;a=search;s=Rhys+Ulerich;st=author">Rhys Ulerich</a></td><td><a class="list subject" href="/gitweb/?p=autoconf-archive.git;a=commit;h=aaa6e5bfe0ac2a0ceaff9832ef4e8b1c6ba5f160">Fix inadvertent breakage from commit cfea4ee52f7</a></td>
+<td class="link"><a href="/gitweb/?p=autoconf-archive.git;a=commit;h=aaa6e5bfe0ac2a0ceaff9832ef4e8b1c6ba5f160">commit</a> | <a href="/gitweb/?p=autoconf-archive.git;a=commitdiff;h=aaa6e5bfe0ac2a0ceaff9832ef4e8b1c6ba5f160">commitdiff</a> | <a href="/gitweb/?p=autoconf-archive.git;a=tree;h=aaa6e5bfe0ac2a0ceaff9832ef4e8b1c6ba5f160;hb=aaa6e5bfe0ac2a0ceaff9832ef4e8b1c6ba5f160">tree</a> | <a title="in format: tar.gz" href="/gitweb/?p=autoconf-archive.git;a=snapshot;h=aaa6e5bfe0ac2a0ceaff9832ef4e8b1c6ba5f160;sf=tgz">snapshot</a></td>
+</tr>
+<tr class="light">
+<td title="4 weeks ago"><i>2011-11-21</i></td>
+<td class="author"><a title="Search for commits authored by Peter Simons" class="list" href="/gitweb/?p=autoconf-archive.git;a=search;s=Peter+Simons;st=author">Peter Simons</a></td><td><a class="list subject" title="AX_PTHREAD: added missing -mt option for Oracle/Sun CC on Solaris" href="/gitweb/?p=autoconf-archive.git;a=commit;h=6c8eddf2606e768cea66e49fc746330ba88de18e">AX_PTHREAD: added missing -mt option for Oracle/Sun... </a></td>
+<td class="link"><a href="/gitweb/?p=autoconf-archive.git;a=commit;h=6c8eddf2606e768cea66e49fc746330ba88de18e">commit</a> | <a href="/gitweb/?p=autoconf-archive.git;a=commitdiff;h=6c8eddf2606e768cea66e49fc746330ba88de18e">commitdiff</a> | <a href="/gitweb/?p=autoconf-archive.git;a=tree;h=6c8eddf2606e768cea66e49fc746330ba88de18e;hb=6c8eddf2606e768cea66e49fc746330ba88de18e">tree</a> | <a title="in format: tar.gz" href="/gitweb/?p=autoconf-archive.git;a=snapshot;h=6c8eddf2606e768cea66e49fc746330ba88de18e;sf=tgz">snapshot</a></td>
+</tr>
+<tr class="dark">
+<td title="4 weeks ago"><i>2011-11-21</i></td>
+<td class="author"><a title="Search for commits authored by Michael Terry" class="list" href="/gitweb/?p=autoconf-archive.git;a=search;s=Michael+Terry;st=author">Michael Terry</a></td><td><a class="list subject" href="/gitweb/?p=autoconf-archive.git;a=commit;h=2fca6b72c6a18efd00712c185f22efb4d61c725c">AX_BOOST_PYTHON: fixed under-quoted use of $CPPFLAGS</a></td>
+<td class="link"><a href="/gitweb/?p=autoconf-archive.git;a=commit;h=2fca6b72c6a18efd00712c185f22efb4d61c725c">commit</a> | <a href="/gitweb/?p=autoconf-archive.git;a=commitdiff;h=2fca6b72c6a18efd00712c185f22efb4d61c725c">commitdiff</a> | <a href="/gitweb/?p=autoconf-archive.git;a=tree;h=2fca6b72c6a18efd00712c185f22efb4d61c725c;hb=2fca6b72c6a18efd00712c185f22efb4d61c725c">tree</a> | <a title="in format: tar.gz" href="/gitweb/?p=autoconf-archive.git;a=snapshot;h=2fca6b72c6a18efd00712c185f22efb4d61c725c;sf=tgz">snapshot</a></td>
+</tr>
+<tr class="light">
+<td title="4 weeks ago"><i>2011-11-21</i></td>
+<td class="author"><a title="Search for commits authored by Jonathan Wakely" class="list" href="/gitweb/?p=autoconf-archive.git;a=search;s=Jonathan+Wakely;st=author">Jonathan Wakely</a></td><td><a class="list subject" title="AX_CXX_HEADER_STDCXX_0X: updated the list of headers required by C++11 (the standard... " href="/gitweb/?p=autoconf-archive.git;a=commit;h=c398ff19a45daf82754eca619ecea1e9231e8c04">AX_CXX_HEADER_STDCXX_0X: updated the list of headers... </a></td>
+<td class="link"><a href="/gitweb/?p=autoconf-archive.git;a=commit;h=c398ff19a45daf82754eca619ecea1e9231e8c04">commit</a> | <a href="/gitweb/?p=autoconf-archive.git;a=commitdiff;h=c398ff19a45daf82754eca619ecea1e9231e8c04">commitdiff</a> | <a href="/gitweb/?p=autoconf-archive.git;a=tree;h=c398ff19a45daf82754eca619ecea1e9231e8c04;hb=c398ff19a45daf82754eca619ecea1e9231e8c04">tree</a> | <a title="in format: tar.gz" href="/gitweb/?p=autoconf-archive.git;a=snapshot;h=c398ff19a45daf82754eca619ecea1e9231e8c04;sf=tgz">snapshot</a></td>
+</tr>
+<tr class="dark">
+<td title="4 weeks ago"><i>2011-11-21</i></td>
+<td class="author"><a title="Search for commits authored by Peter Simons" class="list" href="/gitweb/?p=autoconf-archive.git;a=search;s=Peter+Simons;st=author">Peter Simons</a></td><td><a class="list subject" title="AX_WITH_CURSES: fixed broken AS_IF() test that prevented $CURSES_LIB from being used" href="/gitweb/?p=autoconf-archive.git;a=commit;h=f0e013b8697406c5be33091e83db56a9f07567fc">AX_WITH_CURSES: fixed broken AS_IF() test that prevente... </a></td>
+<td class="link"><a href="/gitweb/?p=autoconf-archive.git;a=commit;h=f0e013b8697406c5be33091e83db56a9f07567fc">commit</a> | <a href="/gitweb/?p=autoconf-archive.git;a=commitdiff;h=f0e013b8697406c5be33091e83db56a9f07567fc">commitdiff</a> | <a href="/gitweb/?p=autoconf-archive.git;a=tree;h=f0e013b8697406c5be33091e83db56a9f07567fc;hb=f0e013b8697406c5be33091e83db56a9f07567fc">tree</a> | <a title="in format: tar.gz" href="/gitweb/?p=autoconf-archive.git;a=snapshot;h=f0e013b8697406c5be33091e83db56a9f07567fc;sf=tgz">snapshot</a></td>
+</tr>
+<tr class="light">
+<td title="8 weeks ago"><i>2011-10-22</i></td>
+<td class="author"><a title="Search for commits authored by Peter Simons" class="list" href="/gitweb/?p=autoconf-archive.git;a=search;s=Peter+Simons;st=author">Peter Simons</a></td><td><a class="list subject" title="AX_EXT: fixed compiler tests and added support for detection of SSE4.1, SSE4.2, AVX... " href="/gitweb/?p=autoconf-archive.git;a=commit;h=d85b563135e7f9ed8c8da55df1c590ca064c0c3f">AX_EXT: fixed compiler tests and added support for... </a></td>
+<td class="link"><a href="/gitweb/?p=autoconf-archive.git;a=commit;h=d85b563135e7f9ed8c8da55df1c590ca064c0c3f">commit</a> | <a href="/gitweb/?p=autoconf-archive.git;a=commitdiff;h=d85b563135e7f9ed8c8da55df1c590ca064c0c3f">commitdiff</a> | <a href="/gitweb/?p=autoconf-archive.git;a=tree;h=d85b563135e7f9ed8c8da55df1c590ca064c0c3f;hb=d85b563135e7f9ed8c8da55df1c590ca064c0c3f">tree</a> | <a title="in format: tar.gz" href="/gitweb/?p=autoconf-archive.git;a=snapshot;h=d85b563135e7f9ed8c8da55df1c590ca064c0c3f;sf=tgz">snapshot</a></td>
+</tr>
+<tr class="dark">
+<td title="8 weeks ago"><i>2011-10-22</i></td>
+<td class="author"><a title="Search for commits authored by Mateusz Loskot" class="list" href="/gitweb/?p=autoconf-archive.git;a=search;s=Mateusz+Loskot;st=author">Mateusz Loskot</a></td><td><a class="list subject" href="/gitweb/?p=autoconf-archive.git;a=commit;h=8c8faf2f41d81f9acdd09d659f57f392afeb0c2b">AX_LIB_GDAL: new submission</a></td>
+<td class="link"><a href="/gitweb/?p=autoconf-archive.git;a=commit;h=8c8faf2f41d81f9acdd09d659f57f392afeb0c2b">commit</a> | <a href="/gitweb/?p=autoconf-archive.git;a=commitdiff;h=8c8faf2f41d81f9acdd09d659f57f392afeb0c2b">commitdiff</a> | <a href="/gitweb/?p=autoconf-archive.git;a=tree;h=8c8faf2f41d81f9acdd09d659f57f392afeb0c2b;hb=8c8faf2f41d81f9acdd09d659f57f392afeb0c2b">tree</a> | <a title="in format: tar.gz" href="/gitweb/?p=autoconf-archive.git;a=snapshot;h=8c8faf2f41d81f9acdd09d659f57f392afeb0c2b;sf=tgz">snapshot</a></td>
+</tr>
+<tr class="light">
+<td title="2 months ago"><i>2011-09-26</i></td>
+<td class="author"><a title="Search for commits authored by Peter Simons" class="list" href="/gitweb/?p=autoconf-archive.git;a=search;s=Peter+Simons;st=author">Peter Simons</a></td><td><a class="list subject" title="AX_LIB_SQLITE3: replace C++-style commend with C-style to improve portability" href="/gitweb/?p=autoconf-archive.git;a=commit;h=c72bfeb5a83529af1c37c87b7e532a2c879baf06">AX_LIB_SQLITE3: replace C++-style commend with C-style... </a></td>
+<td class="link"><a href="/gitweb/?p=autoconf-archive.git;a=commit;h=c72bfeb5a83529af1c37c87b7e532a2c879baf06">commit</a> | <a href="/gitweb/?p=autoconf-archive.git;a=commitdiff;h=c72bfeb5a83529af1c37c87b7e532a2c879baf06">commitdiff</a> | <a href="/gitweb/?p=autoconf-archive.git;a=tree;h=c72bfeb5a83529af1c37c87b7e532a2c879baf06;hb=c72bfeb5a83529af1c37c87b7e532a2c879baf06">tree</a> | <a title="in format: tar.gz" href="/gitweb/?p=autoconf-archive.git;a=snapshot;h=c72bfeb5a83529af1c37c87b7e532a2c879baf06;sf=tgz">snapshot</a></td>
+</tr>
+<tr class="dark">
+<td title="2 months ago"><i>2011-09-25</i></td>
+<td class="author"><a title="Search for commits authored by Peter Simons" class="list" href="/gitweb/?p=autoconf-archive.git;a=search;s=Peter+Simons;st=author">Peter Simons</a></td><td><a class="list subject" href="/gitweb/?p=autoconf-archive.git;a=commit;h=f0922d23154cc89303af2f22a17445d91d30006c">AX_ENABLE_BUILDDIR: fixed Darwin support</a></td>
+<td class="link"><a href="/gitweb/?p=autoconf-archive.git;a=commit;h=f0922d23154cc89303af2f22a17445d91d30006c">commit</a> | <a href="/gitweb/?p=autoconf-archive.git;a=commitdiff;h=f0922d23154cc89303af2f22a17445d91d30006c">commitdiff</a> | <a href="/gitweb/?p=autoconf-archive.git;a=tree;h=f0922d23154cc89303af2f22a17445d91d30006c;hb=f0922d23154cc89303af2f22a17445d91d30006c">tree</a> | <a title="in format: tar.gz" href="/gitweb/?p=autoconf-archive.git;a=snapshot;h=f0922d23154cc89303af2f22a17445d91d30006c;sf=tgz">snapshot</a></td>
+</tr>
+<tr class="light">
+<td title="3 months ago"><i>2011-09-19</i></td>
+<td class="author"><a title="Search for commits authored by Peter Simons" class="list" href="/gitweb/?p=autoconf-archive.git;a=search;s=Peter+Simons;st=author">Peter Simons</a></td><td><a class="list subject" href="/gitweb/?p=autoconf-archive.git;a=commit;h=374002f42844d25521bc7fc8bd68e3629e1ac3c0">gen-authors.sh: spell Daniel Richard G.'s name consistently</a></td>
+<td class="link"><a href="/gitweb/?p=autoconf-archive.git;a=commit;h=374002f42844d25521bc7fc8bd68e3629e1ac3c0">commit</a> | <a href="/gitweb/?p=autoconf-archive.git;a=commitdiff;h=374002f42844d25521bc7fc8bd68e3629e1ac3c0">commitdiff</a> | <a href="/gitweb/?p=autoconf-archive.git;a=tree;h=374002f42844d25521bc7fc8bd68e3629e1ac3c0;hb=374002f42844d25521bc7fc8bd68e3629e1ac3c0">tree</a> | <a title="in format: tar.gz" href="/gitweb/?p=autoconf-archive.git;a=snapshot;h=374002f42844d25521bc7fc8bd68e3629e1ac3c0;sf=tgz">snapshot</a></td>
+</tr>
+<tr class="dark">
+<td title="3 months ago"><i>2011-09-19</i></td>
+<td class="author"><a title="Search for commits authored by Peter Simons" class="list" href="/gitweb/?p=autoconf-archive.git;a=search;s=Peter+Simons;st=author">Peter Simons</a></td><td><a class="list subject" href="/gitweb/?p=autoconf-archive.git;a=commit;h=01738c00a51efab548b7270108d0ed8084a08ac7">Dropped obsolete macros from the distribution.</a></td>
+<td class="link"><a href="/gitweb/?p=autoconf-archive.git;a=commit;h=01738c00a51efab548b7270108d0ed8084a08ac7">commit</a> | <a href="/gitweb/?p=autoconf-archive.git;a=commitdiff;h=01738c00a51efab548b7270108d0ed8084a08ac7">commitdiff</a> | <a href="/gitweb/?p=autoconf-archive.git;a=tree;h=01738c00a51efab548b7270108d0ed8084a08ac7;hb=01738c00a51efab548b7270108d0ed8084a08ac7">tree</a> | <a title="in format: tar.gz" href="/gitweb/?p=autoconf-archive.git;a=snapshot;h=01738c00a51efab548b7270108d0ed8084a08ac7;sf=tgz">snapshot</a></td>
+</tr>
+<tr class="light">
+<td title="3 months ago"><i>2011-09-17</i></td>
+<td class="author"><a title="Search for commits authored by Peter Simons" class="list" href="/gitweb/?p=autoconf-archive.git;a=search;s=Peter+Simons;st=author">Peter Simons</a></td><td><a class="list subject" href="/gitweb/?p=autoconf-archive.git;a=commit;h=5ebf13f6985acda24f6751def74b0dab1df3d6d4">maint: post-release administrivia</a></td>
+<td class="link"><a href="/gitweb/?p=autoconf-archive.git;a=commit;h=5ebf13f6985acda24f6751def74b0dab1df3d6d4">commit</a> | <a href="/gitweb/?p=autoconf-archive.git;a=commitdiff;h=5ebf13f6985acda24f6751def74b0dab1df3d6d4">commitdiff</a> | <a href="/gitweb/?p=autoconf-archive.git;a=tree;h=5ebf13f6985acda24f6751def74b0dab1df3d6d4;hb=5ebf13f6985acda24f6751def74b0dab1df3d6d4">tree</a> | <a title="in format: tar.gz" href="/gitweb/?p=autoconf-archive.git;a=snapshot;h=5ebf13f6985acda24f6751def74b0dab1df3d6d4;sf=tgz">snapshot</a></td>
+</tr>
+<tr>
+<td colspan="4"><a href="/gitweb/?p=autoconf-archive.git;a=shortlog">...</a></td>
+</tr>
+</table>
+<div class="header">
+<a class="title" href="/gitweb/?p=autoconf-archive.git;a=tags">tags</a>
+</div>
+<table class="tags">
+<tr class="dark">
+<td><i>5 hours ago</i></td>
+<td><a class="list name" href="/gitweb/?p=autoconf-archive.git;a=commit;h=77bb2ab18a583eca3717406e47cba73426f59ab1">v2011.12.21</a></td>
+<td><a class="list subject" title="GNU Autoconf Archive Version 2011.12.21" href="/gitweb/?p=autoconf-archive.git;a=tag;h=b57da13e32c04d5a800257ab1b3ca48cd7aa1871">GNU Autoconf Archive Version 2011... </a></td>
+<td class="selflink"><a href="/gitweb/?p=autoconf-archive.git;a=tag;h=b57da13e32c04d5a800257ab1b3ca48cd7aa1871">tag</a></td>
+<td class="link"> | <a href="/gitweb/?p=autoconf-archive.git;a=commit;h=77bb2ab18a583eca3717406e47cba73426f59ab1">commit</a> | <a href="/gitweb/?p=autoconf-archive.git;a=shortlog;h=refs/tags/v2011.12.21">shortlog</a> | <a href="/gitweb/?p=autoconf-archive.git;a=log;h=refs/tags/v2011.12.21">log</a></td>
+</tr><tr class="light">
+<td><i>3 months ago</i></td>
+<td><a class="list name" href="/gitweb/?p=autoconf-archive.git;a=commit;h=e6d6aa7c38f235c09efbe97976454e4f65a52539">v2011.09.17</a></td>
+<td><a class="list subject" title="GNU Autoconf Archive Version 2011.09.17" href="/gitweb/?p=autoconf-archive.git;a=tag;h=7d6e0f275e488dc135ac0b73330ec69978f9dabf">GNU Autoconf Archive Version 2011... </a></td>
+<td class="selflink"><a href="/gitweb/?p=autoconf-archive.git;a=tag;h=7d6e0f275e488dc135ac0b73330ec69978f9dabf">tag</a></td>
+<td class="link"> | <a href="/gitweb/?p=autoconf-archive.git;a=commit;h=e6d6aa7c38f235c09efbe97976454e4f65a52539">commit</a> | <a href="/gitweb/?p=autoconf-archive.git;a=shortlog;h=refs/tags/v2011.09.17">shortlog</a> | <a href="/gitweb/?p=autoconf-archive.git;a=log;h=refs/tags/v2011.09.17">log</a></td>
+</tr><tr class="dark">
+<td><i>5 months ago</i></td>
+<td><a class="list name" href="/gitweb/?p=autoconf-archive.git;a=commit;h=756c399edef5a71f73f05b61cefde0ba4842e6c5">v2011.07.17</a></td>
+<td><a class="list subject" title="GNU Autoconf Archive Version 2011.07.17" href="/gitweb/?p=autoconf-archive.git;a=tag;h=7630d0be0daee35103e690dcd98a41e7780dbad9">GNU Autoconf Archive Version 2011... </a></td>
+<td class="selflink"><a href="/gitweb/?p=autoconf-archive.git;a=tag;h=7630d0be0daee35103e690dcd98a41e7780dbad9">tag</a></td>
+<td class="link"> | <a href="/gitweb/?p=autoconf-archive.git;a=commit;h=756c399edef5a71f73f05b61cefde0ba4842e6c5">commit</a> | <a href="/gitweb/?p=autoconf-archive.git;a=shortlog;h=refs/tags/v2011.07.17">shortlog</a> | <a href="/gitweb/?p=autoconf-archive.git;a=log;h=refs/tags/v2011.07.17">log</a></td>
+</tr><tr class="light">
+<td><i>8 months ago</i></td>
+<td><a class="list name" href="/gitweb/?p=autoconf-archive.git;a=commit;h=7fd27beef29f4d6ff69f4fce874185522174806b">v2011.04.12</a></td>
+<td><a class="list subject" title="GNU Autoconf Archive Version 2011.04.12" href="/gitweb/?p=autoconf-archive.git;a=tag;h=899801493b5120e9d1aaa75146adf04acff3cc99">GNU Autoconf Archive Version 2011... </a></td>
+<td class="selflink"><a href="/gitweb/?p=autoconf-archive.git;a=tag;h=899801493b5120e9d1aaa75146adf04acff3cc99">tag</a></td>
+<td class="link"> | <a href="/gitweb/?p=autoconf-archive.git;a=commit;h=7fd27beef29f4d6ff69f4fce874185522174806b">commit</a> | <a href="/gitweb/?p=autoconf-archive.git;a=shortlog;h=refs/tags/v2011.04.12">shortlog</a> | <a href="/gitweb/?p=autoconf-archive.git;a=log;h=refs/tags/v2011.04.12">log</a></td>
+</tr><tr class="dark">
+<td><i>9 months ago</i></td>
+<td><a class="list name" href="/gitweb/?p=autoconf-archive.git;a=commit;h=d69f040d752e5369ab7d729a769935161becab7e">v2011.03.17</a></td>
+<td><a class="list subject" title="GNU Autoconf Archive Version 2011.03.17" href="/gitweb/?p=autoconf-archive.git;a=tag;h=2de12abc6dfe6053ff171cdb398c8d331691ae5a">GNU Autoconf Archive Version 2011... </a></td>
+<td class="selflink"><a href="/gitweb/?p=autoconf-archive.git;a=tag;h=2de12abc6dfe6053ff171cdb398c8d331691ae5a">tag</a></td>
+<td class="link"> | <a href="/gitweb/?p=autoconf-archive.git;a=commit;h=d69f040d752e5369ab7d729a769935161becab7e">commit</a> | <a href="/gitweb/?p=autoconf-archive.git;a=shortlog;h=refs/tags/v2011.03.17">shortlog</a> | <a href="/gitweb/?p=autoconf-archive.git;a=log;h=refs/tags/v2011.03.17">log</a></td>
+</tr><tr class="light">
+<td><i>11 months ago</i></td>
+<td><a class="list name" href="/gitweb/?p=autoconf-archive.git;a=commit;h=93d8aeba2a2208cbd8952e906a3e583786b12286">v2011.01.02</a></td>
+<td><a class="list subject" title="GNU Autoconf Archive Version 2011.01.02" href="/gitweb/?p=autoconf-archive.git;a=tag;h=9dcdf90eb3f267967e619e6e6944a2d623b03992">GNU Autoconf Archive Version 2011... </a></td>
+<td class="selflink"><a href="/gitweb/?p=autoconf-archive.git;a=tag;h=9dcdf90eb3f267967e619e6e6944a2d623b03992">tag</a></td>
+<td class="link"> | <a href="/gitweb/?p=autoconf-archive.git;a=commit;h=93d8aeba2a2208cbd8952e906a3e583786b12286">commit</a> | <a href="/gitweb/?p=autoconf-archive.git;a=shortlog;h=refs/tags/v2011.01.02">shortlog</a> | <a href="/gitweb/?p=autoconf-archive.git;a=log;h=refs/tags/v2011.01.02">log</a></td>
+</tr><tr class="dark">
+<td><i>13 months ago</i></td>
+<td><a class="list name" href="/gitweb/?p=autoconf-archive.git;a=commit;h=f704f9e49fc0e620bb022937be188ffca4694676">v2010.10.26</a></td>
+<td><a class="list subject" title="GNU Autoconf Archive Version 2010.10.26" href="/gitweb/?p=autoconf-archive.git;a=tag;h=47db176c37a7bf59fe3df0530b87b13659ae11d0">GNU Autoconf Archive Version 2010... </a></td>
+<td class="selflink"><a href="/gitweb/?p=autoconf-archive.git;a=tag;h=47db176c37a7bf59fe3df0530b87b13659ae11d0">tag</a></td>
+<td class="link"> | <a href="/gitweb/?p=autoconf-archive.git;a=commit;h=f704f9e49fc0e620bb022937be188ffca4694676">commit</a> | <a href="/gitweb/?p=autoconf-archive.git;a=shortlog;h=refs/tags/v2010.10.26">shortlog</a> | <a href="/gitweb/?p=autoconf-archive.git;a=log;h=refs/tags/v2010.10.26">log</a></td>
+</tr><tr class="light">
+<td><i>16 months ago</i></td>
+<td><a class="list name" href="/gitweb/?p=autoconf-archive.git;a=commit;h=2c5e5114a808a6827f77087ed4e785842a63933e">v2010.08.19</a></td>
+<td><a class="list subject" title="GNU Autoconf Archive Version 2010.08.19" href="/gitweb/?p=autoconf-archive.git;a=tag;h=8ec386962567bff3884b71c10d010734a3cfd096">GNU Autoconf Archive Version 2010... </a></td>
+<td class="selflink"><a href="/gitweb/?p=autoconf-archive.git;a=tag;h=8ec386962567bff3884b71c10d010734a3cfd096">tag</a></td>
+<td class="link"> | <a href="/gitweb/?p=autoconf-archive.git;a=commit;h=2c5e5114a808a6827f77087ed4e785842a63933e">commit</a> | <a href="/gitweb/?p=autoconf-archive.git;a=shortlog;h=refs/tags/v2010.08.19">shortlog</a> | <a href="/gitweb/?p=autoconf-archive.git;a=log;h=refs/tags/v2010.08.19">log</a></td>
+</tr><tr class="dark">
+<td><i>17 months ago</i></td>
+<td><a class="list name" href="/gitweb/?p=autoconf-archive.git;a=commit;h=cf3e3144e3ed6d9ba84c20ecacd2771e5ec26f76">v2010.07.06</a></td>
+<td><a class="list subject" title="GNU Autoconf Archive Version 2010.07.06" href="/gitweb/?p=autoconf-archive.git;a=tag;h=5a22e2859b389d6550f01db7d8e79f794c50d85b">GNU Autoconf Archive Version 2010... </a></td>
+<td class="selflink"><a href="/gitweb/?p=autoconf-archive.git;a=tag;h=5a22e2859b389d6550f01db7d8e79f794c50d85b">tag</a></td>
+<td class="link"> | <a href="/gitweb/?p=autoconf-archive.git;a=commit;h=cf3e3144e3ed6d9ba84c20ecacd2771e5ec26f76">commit</a> | <a href="/gitweb/?p=autoconf-archive.git;a=shortlog;h=refs/tags/v2010.07.06">shortlog</a> | <a href="/gitweb/?p=autoconf-archive.git;a=log;h=refs/tags/v2010.07.06">log</a></td>
+</tr><tr class="light">
+<td><i>18 months ago</i></td>
+<td><a class="list name" href="/gitweb/?p=autoconf-archive.git;a=commit;h=a4b5c3132e68928f02354ec06ccda28bd63de4e4">v2010.06.04</a></td>
+<td><a class="list subject" title="GNU Autoconf Archive Version 2010.06.04" href="/gitweb/?p=autoconf-archive.git;a=tag;h=8837aac49910c94f3dc33129e01dcad2b880e4db">GNU Autoconf Archive Version 2010... </a></td>
+<td class="selflink"><a href="/gitweb/?p=autoconf-archive.git;a=tag;h=8837aac49910c94f3dc33129e01dcad2b880e4db">tag</a></td>
+<td class="link"> | <a href="/gitweb/?p=autoconf-archive.git;a=commit;h=a4b5c3132e68928f02354ec06ccda28bd63de4e4">commit</a> | <a href="/gitweb/?p=autoconf-archive.git;a=shortlog;h=refs/tags/v2010.06.04">shortlog</a> | <a href="/gitweb/?p=autoconf-archive.git;a=log;h=refs/tags/v2010.06.04">log</a></td>
+</tr><tr class="dark">
+<td><i>22 months ago</i></td>
+<td><a class="list name" href="/gitweb/?p=autoconf-archive.git;a=commit;h=4bd00f3f40a681cc492cdae312d4ace73c0d6232">v2010.02.14</a></td>
+<td><a class="list subject" href="/gitweb/?p=autoconf-archive.git;a=tag;h=2320490582aaacc524c13068dc0921944d12b828">Autoconf Archive Version 2010.02.14</a></td>
+<td class="selflink"><a href="/gitweb/?p=autoconf-archive.git;a=tag;h=2320490582aaacc524c13068dc0921944d12b828">tag</a></td>
+<td class="link"> | <a href="/gitweb/?p=autoconf-archive.git;a=commit;h=4bd00f3f40a681cc492cdae312d4ace73c0d6232">commit</a> | <a href="/gitweb/?p=autoconf-archive.git;a=shortlog;h=refs/tags/v2010.02.14">shortlog</a> | <a href="/gitweb/?p=autoconf-archive.git;a=log;h=refs/tags/v2010.02.14">log</a></td>
+</tr><tr class="light">
+<td><i>2 years ago</i></td>
+<td><a class="list name" href="/gitweb/?p=autoconf-archive.git;a=commit;h=5abf6d91814a0bd79698abbb27fb1a26b21fba58">v2009.12.16</a></td>
+<td><a class="list subject" title="Autoconf Archive release 2009.12.16 is an alpha release that's been" href="/gitweb/?p=autoconf-archive.git;a=tag;h=f763b3bdf1a1e44d0b43b28bea556aae9111fbe6">Autoconf Archive release 2009.12... </a></td>
+<td class="selflink"><a href="/gitweb/?p=autoconf-archive.git;a=tag;h=f763b3bdf1a1e44d0b43b28bea556aae9111fbe6">tag</a></td>
+<td class="link"> | <a href="/gitweb/?p=autoconf-archive.git;a=commit;h=5abf6d91814a0bd79698abbb27fb1a26b21fba58">commit</a> | <a href="/gitweb/?p=autoconf-archive.git;a=shortlog;h=refs/tags/v2009.12.16">shortlog</a> | <a href="/gitweb/?p=autoconf-archive.git;a=log;h=refs/tags/v2009.12.16">log</a></td>
+</tr><tr class="dark">
+<td><i>2 years ago</i></td>
+<td><a class="list name" href="/gitweb/?p=autoconf-archive.git;a=commit;h=822cdbb0d636d26bc3557c11cf22fed152434c19">v2009.07.20</a></td>
+<td><a class="list subject" title="Autoconf Archive version 2009.07.20 is an interim release, mostly for" href="/gitweb/?p=autoconf-archive.git;a=tag;h=914875eae2d5b5b02f2525fd071c20c53c9cbef0">Autoconf Archive version 2009.07... </a></td>
+<td class="selflink"><a href="/gitweb/?p=autoconf-archive.git;a=tag;h=914875eae2d5b5b02f2525fd071c20c53c9cbef0">tag</a></td>
+<td class="link"> | <a href="/gitweb/?p=autoconf-archive.git;a=commit;h=822cdbb0d636d26bc3557c11cf22fed152434c19">commit</a> | <a href="/gitweb/?p=autoconf-archive.git;a=shortlog;h=refs/tags/v2009.07.20">shortlog</a> | <a href="/gitweb/?p=autoconf-archive.git;a=log;h=refs/tags/v2009.07.20">log</a></td>
+</tr></table>
+<div class="header">
+<a class="title" href="/gitweb/?p=autoconf-archive.git;a=heads">heads</a>
+</div>
+<table class="heads">
+<tr class="dark">
+<td><i>5 hours ago</i></td>
+<td class="current_head"><a class="list name" href="/gitweb/?p=autoconf-archive.git;a=shortlog;h=refs/heads/master">master</a></td>
+<td class="link"><a href="/gitweb/?p=autoconf-archive.git;a=shortlog;h=refs/heads/master">shortlog</a> | <a href="/gitweb/?p=autoconf-archive.git;a=log;h=refs/heads/master">log</a> | <a href="/gitweb/?p=autoconf-archive.git;a=tree;h=refs/heads/master;hb=master">tree</a></td>
+</tr><tr class="light">
+<td><i>2 years ago</i></td>
+<td><a class="list name" href="/gitweb/?p=autoconf-archive.git;a=shortlog;h=refs/heads/pre-savannah-history">pre-savannah-history</a></td>
+<td class="link"><a href="/gitweb/?p=autoconf-archive.git;a=shortlog;h=refs/heads/pre-savannah-history">shortlog</a> | <a href="/gitweb/?p=autoconf-archive.git;a=log;h=refs/heads/pre-savannah-history">log</a> | <a href="/gitweb/?p=autoconf-archive.git;a=tree;h=refs/heads/pre-savannah-history;hb=pre-savannah-history">tree</a></td>
+</tr></table>
+<div class="page_footer">
+<div class="page_footer_text">autoconf-archive</div>
+<a class="rss_logo" title="log RSS feed" href="/gitweb/?p=autoconf-archive.git;a=rss">RSS</a>
+<a class="rss_logo" title="log Atom feed" href="/gitweb/?p=autoconf-archive.git;a=atom">Atom</a>
+</div>
+<script type="text/javascript" src="gitweb.js"></script>
+</body>
+</html>
\ No newline at end of file
diff --git a/m4/ax_cflags_warn_all.m4 b/m4/ax_cflags_warn_all.m4
new file mode 100644
index 0000000..ae0e7ef
--- /dev/null
+++ b/m4/ax_cflags_warn_all.m4
@@ -0,0 +1,120 @@
+dnl @synopsis AX_CFLAGS_WARN_ALL [(shellvar [,default, [A/NA]])]
+dnl
+dnl Try to find a compiler option that enables most reasonable
+dnl warnings. This macro is directly derived from VL_PROG_CC_WARNINGS
+dnl which is split up into two AX_CFLAGS_WARN_ALL and
+dnl AX_CFLAGS_WARN_ALL_ANSI
+dnl
+dnl For the GNU CC compiler it will be -Wall (and -ansi -pedantic) The
+dnl result is added to the shellvar being CFLAGS by default.
+dnl
+dnl Currently this macro knows about GCC, Solaris C compiler, Digital
+dnl Unix C compiler, C for AIX Compiler, HP-UX C compiler, IRIX C
+dnl compiler, NEC SX-5 (Super-UX 10) C compiler, and Cray J90 (Unicos
+dnl 10.0.0.8) C compiler.
+dnl
+dnl  - $1 shell-variable-to-add-to : CFLAGS
+dnl  - $2 add-value-if-not-found : nothing
+dnl  - $3 action-if-found : add value to shellvariable
+dnl  - $4 action-if-not-found : nothing
+dnl
+dnl @category C
+dnl @author Guido Draheim <guidod at gmx.de>
+dnl @version 2003-01-06
+dnl @license GPLWithACException
+
+AC_DEFUN([AX_CFLAGS_WARN_ALL],[dnl
+AS_VAR_PUSHDEF([FLAGS],[CFLAGS])dnl
+AS_VAR_PUSHDEF([VAR],[ac_cv_cflags_warn_all])dnl
+AC_CACHE_CHECK([m4_ifval($1,$1,FLAGS) for maximum warnings],
+VAR,[VAR="no, unknown"
+ AC_LANG_SAVE
+ AC_LANG(C)
+ ac_save_[]FLAGS="$[]FLAGS"
+for ac_arg dnl
+in "-pedantic -Wdeclaration-after-statement % dnl
+       -Wall -Wdeclaration-after-statement" dnl works since GCC version 3
+   "-pedantic  % -Wall"       dnl older GCC
+   "-xstrconst % -v"          dnl Solaris C
+   "-std1      % -verbose -w0 -warnprotos" dnl Digital Unix
+   "-qlanglvl=ansi % -qsrcmsg -qinfo=all:noppt:noppc:noobs:nocnd" dnl AIX
+   "-ansi -ansiE % -fullwarn" dnl IRIX
+   "+ESlit     % +w1"         dnl HP-UX C
+   "-Xc        % -pvctl[,]fullmsg" dnl NEC SX-5 (Super-UX 10)
+   "-h conform % -h msglevel 2" dnl Cray C (Unicos)
+   #
+do FLAGS="$ac_save_[]FLAGS "`echo $ac_arg | sed -e 's,%%.*,,' -e 's,%,,'`
+   AC_TRY_COMPILE([],[return 0;],
+   [VAR=`echo $ac_arg | sed -e 's,.*% *,,'` ; break])
+done
+ FLAGS="$ac_save_[]FLAGS"
+ AC_LANG_RESTORE
+])
+case ".$VAR" in
+     .ok|.ok,*) m4_ifvaln($3,$3) ;;
+   .|.no|.no,*) m4_ifvaln($4,$4,[m4_ifval($2,[
+        AC_RUN_LOG([: m4_ifval($1,$1,FLAGS)="$m4_ifval($1,$1,FLAGS) $2"])
+                      m4_ifval($1,$1,FLAGS)="$m4_ifval($1,$1,FLAGS) $2"])]) ;;
+   *) m4_ifvaln($3,$3,[
+   if echo " $[]m4_ifval($1,$1,FLAGS) " | grep " $VAR " 2>&1 >/dev/null
+   then AC_RUN_LOG([: m4_ifval($1,$1,FLAGS) does contain $VAR])
+   else AC_RUN_LOG([: m4_ifval($1,$1,FLAGS)="$m4_ifval($1,$1,FLAGS) $VAR"])
+                      m4_ifval($1,$1,FLAGS)="$m4_ifval($1,$1,FLAGS) $VAR"
+   fi ]) ;;
+esac
+AS_VAR_POPDEF([VAR])dnl
+AS_VAR_POPDEF([FLAGS])dnl
+])
+
+dnl the only difference - the LANG selection... and the default FLAGS
+
+AC_DEFUN([AX_CXXFLAGS_WARN_ALL],[dnl
+AS_VAR_PUSHDEF([FLAGS],[CXXFLAGS])dnl
+AS_VAR_PUSHDEF([VAR],[ac_cv_cxxflags_warn_all])dnl
+AC_CACHE_CHECK([m4_ifval($1,$1,FLAGS) for maximum warnings],
+VAR,[VAR="no, unknown"
+ AC_LANG_SAVE
+ AC_LANG(C++)
+ ac_save_[]FLAGS="$[]FLAGS"
+for ac_arg dnl
+in "-pedantic  % -Wall"       dnl   GCC
+   "-xstrconst % -v"          dnl Solaris C
+   "-std1      % -verbose -w0 -warnprotos" dnl Digital Unix
+   "-qlanglvl=ansi % -qsrcmsg -qinfo=all:noppt:noppc:noobs:nocnd" dnl AIX
+   "-ansi -ansiE % -fullwarn" dnl IRIX
+   "+ESlit     % +w1"         dnl HP-UX C
+   "-Xc        % -pvctl[,]fullmsg" dnl NEC SX-5 (Super-UX 10)
+   "-h conform % -h msglevel 2" dnl Cray C (Unicos)
+   #
+do FLAGS="$ac_save_[]FLAGS "`echo $ac_arg | sed -e 's,%%.*,,' -e 's,%,,'`
+   AC_TRY_COMPILE([],[return 0;],
+   [VAR=`echo $ac_arg | sed -e 's,.*% *,,'` ; break])
+done
+ FLAGS="$ac_save_[]FLAGS"
+ AC_LANG_RESTORE
+])
+case ".$VAR" in
+     .ok|.ok,*) m4_ifvaln($3,$3) ;;
+   .|.no|.no,*) m4_ifvaln($4,$4,[m4_ifval($2,[
+        AC_RUN_LOG([: m4_ifval($1,$1,FLAGS)="$m4_ifval($1,$1,FLAGS) $2"])
+                      m4_ifval($1,$1,FLAGS)="$m4_ifval($1,$1,FLAGS) $2"])]) ;;
+   *) m4_ifvaln($3,$3,[
+   if echo " $[]m4_ifval($1,$1,FLAGS) " | grep " $VAR " 2>&1 >/dev/null
+   then AC_RUN_LOG([: m4_ifval($1,$1,FLAGS) does contain $VAR])
+   else AC_RUN_LOG([: m4_ifval($1,$1,FLAGS)="$m4_ifval($1,$1,FLAGS) $VAR"])
+                      m4_ifval($1,$1,FLAGS)="$m4_ifval($1,$1,FLAGS) $VAR"
+   fi ]) ;;
+esac
+AS_VAR_POPDEF([VAR])dnl
+AS_VAR_POPDEF([FLAGS])dnl
+])
+
+dnl  implementation tactics:
+dnl   the for-argument contains a list of options. The first part of
+dnl   these does only exist to detect the compiler - usually it is
+dnl   a global option to enable -ansi or -extrawarnings. All other
+dnl   compilers will fail about it. That was needed since a lot of
+dnl   compilers will give false positives for some option-syntax
+dnl   like -Woption or -Xoption as they think of it is a pass-through
+dnl   to later compile stages or something. The "%" is used as a
+dnl   delimimiter. A non-option comment can be given after "%%" marks.
diff --git a/m4/ax_jni_include_dir.m4 b/m4/ax_jni_include_dir.m4
new file mode 100644
index 0000000..57511bb
--- /dev/null
+++ b/m4/ax_jni_include_dir.m4
@@ -0,0 +1,121 @@
+# ===========================================================================
+#    http://www.gnu.org/software/autoconf-archive/ax_jni_include_dir.html
+# ===========================================================================
+#
+# SYNOPSIS
+#
+#   AX_JNI_INCLUDE_DIR
+#
+# DESCRIPTION
+#
+#   AX_JNI_INCLUDE_DIR finds include directories needed for compiling
+#   programs using the JNI interface.
+#
+#   JNI include directories are usually in the java distribution This is
+#   deduced from the value of JAVAC. When this macro completes, a list of
+#   directories is left in the variable JNI_INCLUDE_DIRS.
+#
+#   Example usage follows:
+#
+#     AX_JNI_INCLUDE_DIR
+#
+#     for JNI_INCLUDE_DIR in $JNI_INCLUDE_DIRS
+#     do
+#             CPPFLAGS="$CPPFLAGS -I$JNI_INCLUDE_DIR"
+#     done
+#
+#   If you want to force a specific compiler:
+#
+#   - at the configure.in level, set JAVAC=yourcompiler before calling
+#   AX_JNI_INCLUDE_DIR
+#
+#   - at the configure level, setenv JAVAC
+#
+#   Note: This macro can work with the autoconf M4 macros for Java programs.
+#   This particular macro is not part of the original set of macros.
+#
+# LICENSE
+#
+#   Copyright (c) 2008 Don Anderson <dda at sleepycat.com>
+#
+#   Copying and distribution of this file, with or without modification, are
+#   permitted in any medium without royalty provided the copyright notice
+#   and this notice are preserved. This file is offered as-is, without any
+#   warranty.
+
+#serial 7
+
+AU_ALIAS([AC_JNI_INCLUDE_DIR], [AX_JNI_INCLUDE_DIR])
+AC_DEFUN([AX_JNI_INCLUDE_DIR],[
+
+JNI_INCLUDE_DIRS=""
+
+test "x$JAVAC" = x && AC_MSG_ERROR(['\$JAVAC' undefined])
+AC_PATH_PROG([_ACJNI_JAVAC], [$JAVAC], [no])
+if test "x$_ACJNI_JAVAC" = xno; then
+   AC_MSG_RESULT([$JAVAC could not be found in path])
+else
+   _ACJNI_FOLLOW_SYMLINKS("$_ACJNI_JAVAC")
+   _JTOPDIR=`echo "$_ACJNI_FOLLOWED" | sed -e 's://*:/:g' -e 's:/[[^/]]*$::'`
+   case "$host_os" in
+           darwin*)        _JTOPDIR=`echo "$_JTOPDIR" | sed -e 's:/[[^/]]*$::'`
+                           _JINC="$_JTOPDIR/Headers";;
+           *)              _JINC="$_JTOPDIR/include";;
+   esac
+   _AS_ECHO_LOG([_JTOPDIR=$_JTOPDIR])
+   _AS_ECHO_LOG([_JINC=$_JINC])
+   
+   # On Mac OS X 10.6.4, jni.h is a symlink:
+   # /System/Library/Frameworks/JavaVM.framework/Versions/Current/Headers/jni.h
+   # -> ../../CurrentJDK/Headers/jni.h.
+   if test -f "$_JINC/jni.h" || test -L "$_JINC/jni.h"; then
+           JNI_INCLUDE_DIRS="$JNI_INCLUDE_DIRS $_JINC"
+   else
+           _JTOPDIR=`echo "$_JTOPDIR" | sed -e 's:/[[^/]]*$::'`
+           if test -f "$_JTOPDIR/include/jni.h"; then
+                   JNI_INCLUDE_DIRS="$JNI_INCLUDE_DIRS $_JTOPDIR/include"
+           else
+                   AC_MSG_ERROR([cannot find java include files])
+           fi
+   fi
+   
+   # get the likely subdirectories for system specific java includes
+   case "$host_os" in
+   bsdi*)          _JNI_INC_SUBDIRS="bsdos";;
+   linux*)         _JNI_INC_SUBDIRS="linux genunix";;
+   osf*)           _JNI_INC_SUBDIRS="alpha";;
+   solaris*)       _JNI_INC_SUBDIRS="solaris";;
+   mingw*)		_JNI_INC_SUBDIRS="win32";;
+   cygwin*)	_JNI_INC_SUBDIRS="win32";;
+   *)              _JNI_INC_SUBDIRS="genunix";;
+   esac
+   
+   # add any subdirectories that are present
+   for JINCSUBDIR in $_JNI_INC_SUBDIRS
+   do
+       if test -d "$_JTOPDIR/include/$JINCSUBDIR"; then
+            JNI_INCLUDE_DIRS="$JNI_INCLUDE_DIRS $_JTOPDIR/include/$JINCSUBDIR"
+       fi
+   done
+fi
+])
+
+# _ACJNI_FOLLOW_SYMLINKS <path>
+# Follows symbolic links on <path>,
+# finally setting variable _ACJNI_FOLLOWED
+# ----------------------------------------
+AC_DEFUN([_ACJNI_FOLLOW_SYMLINKS],[
+# find the include directory relative to the javac executable
+_cur="$1"
+while ls -ld "$_cur" 2>/dev/null | grep " -> " >/dev/null; do
+        AC_MSG_CHECKING([symlink for $_cur])
+        _slink=`ls -ld "$_cur" | sed 's/.* -> //'`
+        case "$_slink" in
+        /*) _cur="$_slink";;
+        # 'X' avoids triggering unwanted echo options.
+        *) _cur=`echo "X$_cur" | sed -e 's/^X//' -e 's:[[^/]]*$::'`"$_slink";;
+        esac
+        AC_MSG_RESULT([$_cur])
+done
+_ACJNI_FOLLOWED="$_cur"
+])# _ACJNI
diff --git a/m4/ax_pkg_swig.m4 b/m4/ax_pkg_swig.m4
new file mode 100644
index 0000000..e112f3d
--- /dev/null
+++ b/m4/ax_pkg_swig.m4
@@ -0,0 +1,135 @@
+# ===========================================================================
+#        http://www.gnu.org/software/autoconf-archive/ax_pkg_swig.html
+# ===========================================================================
+#
+# SYNOPSIS
+#
+#   AX_PKG_SWIG([major.minor.micro], [action-if-found], [action-if-not-found])
+#
+# DESCRIPTION
+#
+#   This macro searches for a SWIG installation on your system. If found,
+#   then SWIG is AC_SUBST'd; if not found, then $SWIG is empty.  If SWIG is
+#   found, then SWIG_LIB is set to the SWIG library path, and AC_SUBST'd.
+#
+#   You can use the optional first argument to check if the version of the
+#   available SWIG is greater than or equal to the value of the argument. It
+#   should have the format: N[.N[.N]] (N is a number between 0 and 999. Only
+#   the first N is mandatory.) If the version argument is given (e.g.
+#   1.3.17), AX_PKG_SWIG checks that the swig package is this version number
+#   or higher.
+#
+#   As usual, action-if-found is executed if SWIG is found, otherwise
+#   action-if-not-found is executed.
+#
+#   In configure.in, use as:
+#
+#     AX_PKG_SWIG(1.3.17, [], [ AC_MSG_ERROR([SWIG is required to build..]) ])
+#     AX_SWIG_ENABLE_CXX
+#     AX_SWIG_MULTI_MODULE_SUPPORT
+#     AX_SWIG_PYTHON
+#
+# LICENSE
+#
+#   Copyright (c) 2008 Sebastian Huber <sebastian-huber at web.de>
+#   Copyright (c) 2008 Alan W. Irwin <irwin at beluga.phys.uvic.ca>
+#   Copyright (c) 2008 Rafael Laboissiere <rafael at laboissiere.net>
+#   Copyright (c) 2008 Andrew Collier <colliera at ukzn.ac.za>
+#   Copyright (c) 2011 Murray Cumming <murrayc at openismus.com>
+#
+#   This program is free software; you can redistribute it and/or modify it
+#   under the terms of the GNU General Public License as published by the
+#   Free Software Foundation; either version 2 of the License, or (at your
+#   option) any later version.
+#
+#   This program is distributed in the hope that it will be useful, but
+#   WITHOUT ANY WARRANTY; without even the implied warranty of
+#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
+#   Public License for more details.
+#
+#   You should have received a copy of the GNU General Public License along
+#   with this program. If not, see <http://www.gnu.org/licenses/>.
+#
+#   As a special exception, the respective Autoconf Macro's copyright owner
+#   gives unlimited permission to copy, distribute and modify the configure
+#   scripts that are the output of Autoconf when processing the Macro. You
+#   need not follow the terms of the GNU General Public License when using
+#   or distributing such scripts, even though portions of the text of the
+#   Macro appear in them. The GNU General Public License (GPL) does govern
+#   all other use of the material that constitutes the Autoconf Macro.
+#
+#   This special exception to the GPL applies to versions of the Autoconf
+#   Macro released by the Autoconf Archive. When you make and distribute a
+#   modified version of the Autoconf Macro, you may extend this special
+#   exception to the GPL to apply to your modified version as well.
+
+#serial 8
+
+AC_DEFUN([AX_PKG_SWIG],[
+        # Ubuntu has swig 2.0 as /usr/bin/swig2.0
+        AC_PATH_PROGS([SWIG],[swig swig2.0])
+        if test -z "$SWIG" ; then
+                m4_ifval([$3],[$3],[:])
+        elif test -n "$1" ; then
+                AC_MSG_CHECKING([SWIG version])
+                [swig_version=`$SWIG -version 2>&1 | grep 'SWIG Version' | sed 's/.*\([0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\).*/\1/g'`]
+                AC_MSG_RESULT([$swig_version])
+                if test -n "$swig_version" ; then
+                        # Calculate the required version number components
+                        [required=$1]
+                        [required_major=`echo $required | sed 's/[^0-9].*//'`]
+                        if test -z "$required_major" ; then
+                                [required_major=0]
+                        fi
+                        [required=`echo $required | sed 's/[0-9]*[^0-9]//'`]
+                        [required_minor=`echo $required | sed 's/[^0-9].*//'`]
+                        if test -z "$required_minor" ; then
+                                [required_minor=0]
+                        fi
+                        [required=`echo $required | sed 's/[0-9]*[^0-9]//'`]
+                        [required_patch=`echo $required | sed 's/[^0-9].*//'`]
+                        if test -z "$required_patch" ; then
+                                [required_patch=0]
+                        fi
+                        # Calculate the available version number components
+                        [available=$swig_version]
+                        [available_major=`echo $available | sed 's/[^0-9].*//'`]
+                        if test -z "$available_major" ; then
+                                [available_major=0]
+                        fi
+                        [available=`echo $available | sed 's/[0-9]*[^0-9]//'`]
+                        [available_minor=`echo $available | sed 's/[^0-9].*//'`]
+                        if test -z "$available_minor" ; then
+                                [available_minor=0]
+                        fi
+                        [available=`echo $available | sed 's/[0-9]*[^0-9]//'`]
+                        [available_patch=`echo $available | sed 's/[^0-9].*//'`]
+                        if test -z "$available_patch" ; then
+                                [available_patch=0]
+                        fi
+                        # Convert the version tuple into a single number for easier comparison.
+                        # Using base 100 should be safe since SWIG internally uses BCD values
+                        # to encode its version number.
+                        required_swig_vernum=`expr $required_major \* 10000 \
+                            \+ $required_minor \* 100 \+ $required_patch`
+                        available_swig_vernum=`expr $available_major \* 10000 \
+                            \+ $available_minor \* 100 \+ $available_patch`
+
+                        if test $available_swig_vernum -lt $required_swig_vernum; then
+                                AC_MSG_WARN([SWIG version >= $1 is required.  You have $swig_version.])
+                                SWIG=''
+                                m4_ifval([$3],[$3],[])
+                        else
+                                AC_MSG_CHECKING([for SWIG library])
+                                SWIG_LIB=`$SWIG -swiglib`
+                                AC_MSG_RESULT([$SWIG_LIB])
+                                m4_ifval([$2],[$2],[])
+                        fi
+                else
+                        AC_MSG_WARN([cannot determine SWIG version])
+                        SWIG=''
+                        m4_ifval([$3],[$3],[])
+                fi
+        fi
+        AC_SUBST([SWIG_LIB])
+])
diff --git a/m4/libtool.m4 b/m4/libtool.m4
new file mode 100644
index 0000000..44e0ecf
--- /dev/null
+++ b/m4/libtool.m4
@@ -0,0 +1,7982 @@
+# libtool.m4 - Configure libtool for the host system. -*-Autoconf-*-
+#
+#   Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005,
+#                 2006, 2007, 2008, 2009, 2010, 2011 Free Software
+#                 Foundation, Inc.
+#   Written by Gordon Matzigkeit, 1996
+#
+# This file is free software; the Free Software Foundation gives
+# unlimited permission to copy and/or distribute it, with or without
+# modifications, as long as this notice is preserved.
+
+m4_define([_LT_COPYING], [dnl
+#   Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005,
+#                 2006, 2007, 2008, 2009, 2010, 2011 Free Software
+#                 Foundation, Inc.
+#   Written by Gordon Matzigkeit, 1996
+#
+#   This file is part of GNU Libtool.
+#
+# GNU Libtool is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License as
+# published by the Free Software Foundation; either version 2 of
+# the License, or (at your option) any later version.
+#
+# As a special exception to the GNU General Public License,
+# if you distribute this file as part of a program or library that
+# is built using GNU Libtool, you may include this file under the
+# same distribution terms that you use for the rest of that program.
+#
+# GNU Libtool is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with GNU Libtool; see the file COPYING.  If not, a copy
+# can be downloaded from http://www.gnu.org/licenses/gpl.html, or
+# obtained by writing to the Free Software Foundation, Inc.,
+# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+])
+
+# serial 57 LT_INIT
+
+
+# LT_PREREQ(VERSION)
+# ------------------
+# Complain and exit if this libtool version is less that VERSION.
+m4_defun([LT_PREREQ],
+[m4_if(m4_version_compare(m4_defn([LT_PACKAGE_VERSION]), [$1]), -1,
+       [m4_default([$3],
+		   [m4_fatal([Libtool version $1 or higher is required],
+		             63)])],
+       [$2])])
+
+
+# _LT_CHECK_BUILDDIR
+# ------------------
+# Complain if the absolute build directory name contains unusual characters
+m4_defun([_LT_CHECK_BUILDDIR],
+[case `pwd` in
+  *\ * | *\	*)
+    AC_MSG_WARN([Libtool does not cope well with whitespace in `pwd`]) ;;
+esac
+])
+
+
+# LT_INIT([OPTIONS])
+# ------------------
+AC_DEFUN([LT_INIT],
+[AC_PREREQ([2.58])dnl We use AC_INCLUDES_DEFAULT
+AC_REQUIRE([AC_CONFIG_AUX_DIR_DEFAULT])dnl
+AC_BEFORE([$0], [LT_LANG])dnl
+AC_BEFORE([$0], [LT_OUTPUT])dnl
+AC_BEFORE([$0], [LTDL_INIT])dnl
+m4_require([_LT_CHECK_BUILDDIR])dnl
+
+dnl Autoconf doesn't catch unexpanded LT_ macros by default:
+m4_pattern_forbid([^_?LT_[A-Z_]+$])dnl
+m4_pattern_allow([^(_LT_EOF|LT_DLGLOBAL|LT_DLLAZY_OR_NOW|LT_MULTI_MODULE)$])dnl
+dnl aclocal doesn't pull ltoptions.m4, ltsugar.m4, or ltversion.m4
+dnl unless we require an AC_DEFUNed macro:
+AC_REQUIRE([LTOPTIONS_VERSION])dnl
+AC_REQUIRE([LTSUGAR_VERSION])dnl
+AC_REQUIRE([LTVERSION_VERSION])dnl
+AC_REQUIRE([LTOBSOLETE_VERSION])dnl
+m4_require([_LT_PROG_LTMAIN])dnl
+
+_LT_SHELL_INIT([SHELL=${CONFIG_SHELL-/bin/sh}])
+
+dnl Parse OPTIONS
+_LT_SET_OPTIONS([$0], [$1])
+
+# This can be used to rebuild libtool when needed
+LIBTOOL_DEPS="$ltmain"
+
+# Always use our own libtool.
+LIBTOOL='$(SHELL) $(top_builddir)/libtool'
+AC_SUBST(LIBTOOL)dnl
+
+_LT_SETUP
+
+# Only expand once:
+m4_define([LT_INIT])
+])# LT_INIT
+
+# Old names:
+AU_ALIAS([AC_PROG_LIBTOOL], [LT_INIT])
+AU_ALIAS([AM_PROG_LIBTOOL], [LT_INIT])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_PROG_LIBTOOL], [])
+dnl AC_DEFUN([AM_PROG_LIBTOOL], [])
+
+
+# _LT_CC_BASENAME(CC)
+# -------------------
+# Calculate cc_basename.  Skip known compiler wrappers and cross-prefix.
+m4_defun([_LT_CC_BASENAME],
+[for cc_temp in $1""; do
+  case $cc_temp in
+    compile | *[[\\/]]compile | ccache | *[[\\/]]ccache ) ;;
+    distcc | *[[\\/]]distcc | purify | *[[\\/]]purify ) ;;
+    \-*) ;;
+    *) break;;
+  esac
+done
+cc_basename=`$ECHO "$cc_temp" | $SED "s%.*/%%; s%^$host_alias-%%"`
+])
+
+
+# _LT_FILEUTILS_DEFAULTS
+# ----------------------
+# It is okay to use these file commands and assume they have been set
+# sensibly after `m4_require([_LT_FILEUTILS_DEFAULTS])'.
+m4_defun([_LT_FILEUTILS_DEFAULTS],
+[: ${CP="cp -f"}
+: ${MV="mv -f"}
+: ${RM="rm -f"}
+])# _LT_FILEUTILS_DEFAULTS
+
+
+# _LT_SETUP
+# ---------
+m4_defun([_LT_SETUP],
+[AC_REQUIRE([AC_CANONICAL_HOST])dnl
+AC_REQUIRE([AC_CANONICAL_BUILD])dnl
+AC_REQUIRE([_LT_PREPARE_SED_QUOTE_VARS])dnl
+AC_REQUIRE([_LT_PROG_ECHO_BACKSLASH])dnl
+
+_LT_DECL([], [PATH_SEPARATOR], [1], [The PATH separator for the build system])dnl
+dnl
+_LT_DECL([], [host_alias], [0], [The host system])dnl
+_LT_DECL([], [host], [0])dnl
+_LT_DECL([], [host_os], [0])dnl
+dnl
+_LT_DECL([], [build_alias], [0], [The build system])dnl
+_LT_DECL([], [build], [0])dnl
+_LT_DECL([], [build_os], [0])dnl
+dnl
+AC_REQUIRE([AC_PROG_CC])dnl
+AC_REQUIRE([LT_PATH_LD])dnl
+AC_REQUIRE([LT_PATH_NM])dnl
+dnl
+AC_REQUIRE([AC_PROG_LN_S])dnl
+test -z "$LN_S" && LN_S="ln -s"
+_LT_DECL([], [LN_S], [1], [Whether we need soft or hard links])dnl
+dnl
+AC_REQUIRE([LT_CMD_MAX_LEN])dnl
+_LT_DECL([objext], [ac_objext], [0], [Object file suffix (normally "o")])dnl
+_LT_DECL([], [exeext], [0], [Executable file suffix (normally "")])dnl
+dnl
+m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+m4_require([_LT_CHECK_SHELL_FEATURES])dnl
+m4_require([_LT_PATH_CONVERSION_FUNCTIONS])dnl
+m4_require([_LT_CMD_RELOAD])dnl
+m4_require([_LT_CHECK_MAGIC_METHOD])dnl
+m4_require([_LT_CHECK_SHAREDLIB_FROM_LINKLIB])dnl
+m4_require([_LT_CMD_OLD_ARCHIVE])dnl
+m4_require([_LT_CMD_GLOBAL_SYMBOLS])dnl
+m4_require([_LT_WITH_SYSROOT])dnl
+
+_LT_CONFIG_LIBTOOL_INIT([
+# See if we are running on zsh, and set the options which allow our
+# commands through without removal of \ escapes INIT.
+if test -n "\${ZSH_VERSION+set}" ; then
+   setopt NO_GLOB_SUBST
+fi
+])
+if test -n "${ZSH_VERSION+set}" ; then
+   setopt NO_GLOB_SUBST
+fi
+
+_LT_CHECK_OBJDIR
+
+m4_require([_LT_TAG_COMPILER])dnl
+
+case $host_os in
+aix3*)
+  # AIX sometimes has problems with the GCC collect2 program.  For some
+  # reason, if we set the COLLECT_NAMES environment variable, the problems
+  # vanish in a puff of smoke.
+  if test "X${COLLECT_NAMES+set}" != Xset; then
+    COLLECT_NAMES=
+    export COLLECT_NAMES
+  fi
+  ;;
+esac
+
+# Global variables:
+ofile=libtool
+can_build_shared=yes
+
+# All known linkers require a `.a' archive for static linking (except MSVC,
+# which needs '.lib').
+libext=a
+
+with_gnu_ld="$lt_cv_prog_gnu_ld"
+
+old_CC="$CC"
+old_CFLAGS="$CFLAGS"
+
+# Set sane defaults for various variables
+test -z "$CC" && CC=cc
+test -z "$LTCC" && LTCC=$CC
+test -z "$LTCFLAGS" && LTCFLAGS=$CFLAGS
+test -z "$LD" && LD=ld
+test -z "$ac_objext" && ac_objext=o
+
+_LT_CC_BASENAME([$compiler])
+
+# Only perform the check for file, if the check method requires it
+test -z "$MAGIC_CMD" && MAGIC_CMD=file
+case $deplibs_check_method in
+file_magic*)
+  if test "$file_magic_cmd" = '$MAGIC_CMD'; then
+    _LT_PATH_MAGIC
+  fi
+  ;;
+esac
+
+# Use C for the default configuration in the libtool script
+LT_SUPPORTED_TAG([CC])
+_LT_LANG_C_CONFIG
+_LT_LANG_DEFAULT_CONFIG
+_LT_CONFIG_COMMANDS
+])# _LT_SETUP
+
+
+# _LT_PREPARE_SED_QUOTE_VARS
+# --------------------------
+# Define a few sed substitution that help us do robust quoting.
+m4_defun([_LT_PREPARE_SED_QUOTE_VARS],
+[# Backslashify metacharacters that are still active within
+# double-quoted strings.
+sed_quote_subst='s/\([["`$\\]]\)/\\\1/g'
+
+# Same as above, but do not quote variable references.
+double_quote_subst='s/\([["`\\]]\)/\\\1/g'
+
+# Sed substitution to delay expansion of an escaped shell variable in a
+# double_quote_subst'ed string.
+delay_variable_subst='s/\\\\\\\\\\\$/\\\\\\$/g'
+
+# Sed substitution to delay expansion of an escaped single quote.
+delay_single_quote_subst='s/'\''/'\'\\\\\\\'\''/g'
+
+# Sed substitution to avoid accidental globbing in evaled expressions
+no_glob_subst='s/\*/\\\*/g'
+])
+
+# _LT_PROG_LTMAIN
+# ---------------
+# Note that this code is called both from `configure', and `config.status'
+# now that we use AC_CONFIG_COMMANDS to generate libtool.  Notably,
+# `config.status' has no value for ac_aux_dir unless we are using Automake,
+# so we pass a copy along to make sure it has a sensible value anyway.
+m4_defun([_LT_PROG_LTMAIN],
+[m4_ifdef([AC_REQUIRE_AUX_FILE], [AC_REQUIRE_AUX_FILE([ltmain.sh])])dnl
+_LT_CONFIG_LIBTOOL_INIT([ac_aux_dir='$ac_aux_dir'])
+ltmain="$ac_aux_dir/ltmain.sh"
+])# _LT_PROG_LTMAIN
+
+
+## ------------------------------------- ##
+## Accumulate code for creating libtool. ##
+## ------------------------------------- ##
+
+# So that we can recreate a full libtool script including additional
+# tags, we accumulate the chunks of code to send to AC_CONFIG_COMMANDS
+# in macros and then make a single call at the end using the `libtool'
+# label.
+
+
+# _LT_CONFIG_LIBTOOL_INIT([INIT-COMMANDS])
+# ----------------------------------------
+# Register INIT-COMMANDS to be passed to AC_CONFIG_COMMANDS later.
+m4_define([_LT_CONFIG_LIBTOOL_INIT],
+[m4_ifval([$1],
+          [m4_append([_LT_OUTPUT_LIBTOOL_INIT],
+                     [$1
+])])])
+
+# Initialize.
+m4_define([_LT_OUTPUT_LIBTOOL_INIT])
+
+
+# _LT_CONFIG_LIBTOOL([COMMANDS])
+# ------------------------------
+# Register COMMANDS to be passed to AC_CONFIG_COMMANDS later.
+m4_define([_LT_CONFIG_LIBTOOL],
+[m4_ifval([$1],
+          [m4_append([_LT_OUTPUT_LIBTOOL_COMMANDS],
+                     [$1
+])])])
+
+# Initialize.
+m4_define([_LT_OUTPUT_LIBTOOL_COMMANDS])
+
+
+# _LT_CONFIG_SAVE_COMMANDS([COMMANDS], [INIT_COMMANDS])
+# -----------------------------------------------------
+m4_defun([_LT_CONFIG_SAVE_COMMANDS],
+[_LT_CONFIG_LIBTOOL([$1])
+_LT_CONFIG_LIBTOOL_INIT([$2])
+])
+
+
+# _LT_FORMAT_COMMENT([COMMENT])
+# -----------------------------
+# Add leading comment marks to the start of each line, and a trailing
+# full-stop to the whole comment if one is not present already.
+m4_define([_LT_FORMAT_COMMENT],
+[m4_ifval([$1], [
+m4_bpatsubst([m4_bpatsubst([$1], [^ *], [# ])],
+              [['`$\]], [\\\&])]m4_bmatch([$1], [[!?.]$], [], [.])
+)])
+
+
+
+## ------------------------ ##
+## FIXME: Eliminate VARNAME ##
+## ------------------------ ##
+
+
+# _LT_DECL([CONFIGNAME], VARNAME, VALUE, [DESCRIPTION], [IS-TAGGED?])
+# -------------------------------------------------------------------
+# CONFIGNAME is the name given to the value in the libtool script.
+# VARNAME is the (base) name used in the configure script.
+# VALUE may be 0, 1 or 2 for a computed quote escaped value based on
+# VARNAME.  Any other value will be used directly.
+m4_define([_LT_DECL],
+[lt_if_append_uniq([lt_decl_varnames], [$2], [, ],
+    [lt_dict_add_subkey([lt_decl_dict], [$2], [libtool_name],
+	[m4_ifval([$1], [$1], [$2])])
+    lt_dict_add_subkey([lt_decl_dict], [$2], [value], [$3])
+    m4_ifval([$4],
+	[lt_dict_add_subkey([lt_decl_dict], [$2], [description], [$4])])
+    lt_dict_add_subkey([lt_decl_dict], [$2],
+	[tagged?], [m4_ifval([$5], [yes], [no])])])
+])
+
+
+# _LT_TAGDECL([CONFIGNAME], VARNAME, VALUE, [DESCRIPTION])
+# --------------------------------------------------------
+m4_define([_LT_TAGDECL], [_LT_DECL([$1], [$2], [$3], [$4], [yes])])
+
+
+# lt_decl_tag_varnames([SEPARATOR], [VARNAME1...])
+# ------------------------------------------------
+m4_define([lt_decl_tag_varnames],
+[_lt_decl_filter([tagged?], [yes], $@)])
+
+
+# _lt_decl_filter(SUBKEY, VALUE, [SEPARATOR], [VARNAME1..])
+# ---------------------------------------------------------
+m4_define([_lt_decl_filter],
+[m4_case([$#],
+  [0], [m4_fatal([$0: too few arguments: $#])],
+  [1], [m4_fatal([$0: too few arguments: $#: $1])],
+  [2], [lt_dict_filter([lt_decl_dict], [$1], [$2], [], lt_decl_varnames)],
+  [3], [lt_dict_filter([lt_decl_dict], [$1], [$2], [$3], lt_decl_varnames)],
+  [lt_dict_filter([lt_decl_dict], $@)])[]dnl
+])
+
+
+# lt_decl_quote_varnames([SEPARATOR], [VARNAME1...])
+# --------------------------------------------------
+m4_define([lt_decl_quote_varnames],
+[_lt_decl_filter([value], [1], $@)])
+
+
+# lt_decl_dquote_varnames([SEPARATOR], [VARNAME1...])
+# ---------------------------------------------------
+m4_define([lt_decl_dquote_varnames],
+[_lt_decl_filter([value], [2], $@)])
+
+
+# lt_decl_varnames_tagged([SEPARATOR], [VARNAME1...])
+# ---------------------------------------------------
+m4_define([lt_decl_varnames_tagged],
+[m4_assert([$# <= 2])dnl
+_$0(m4_quote(m4_default([$1], [[, ]])),
+    m4_ifval([$2], [[$2]], [m4_dquote(lt_decl_tag_varnames)]),
+    m4_split(m4_normalize(m4_quote(_LT_TAGS)), [ ]))])
+m4_define([_lt_decl_varnames_tagged],
+[m4_ifval([$3], [lt_combine([$1], [$2], [_], $3)])])
+
+
+# lt_decl_all_varnames([SEPARATOR], [VARNAME1...])
+# ------------------------------------------------
+m4_define([lt_decl_all_varnames],
+[_$0(m4_quote(m4_default([$1], [[, ]])),
+     m4_if([$2], [],
+	   m4_quote(lt_decl_varnames),
+	m4_quote(m4_shift($@))))[]dnl
+])
+m4_define([_lt_decl_all_varnames],
+[lt_join($@, lt_decl_varnames_tagged([$1],
+			lt_decl_tag_varnames([[, ]], m4_shift($@))))dnl
+])
+
+
+# _LT_CONFIG_STATUS_DECLARE([VARNAME])
+# ------------------------------------
+# Quote a variable value, and forward it to `config.status' so that its
+# declaration there will have the same value as in `configure'.  VARNAME
+# must have a single quote delimited value for this to work.
+m4_define([_LT_CONFIG_STATUS_DECLARE],
+[$1='`$ECHO "$][$1" | $SED "$delay_single_quote_subst"`'])
+
+
+# _LT_CONFIG_STATUS_DECLARATIONS
+# ------------------------------
+# We delimit libtool config variables with single quotes, so when
+# we write them to config.status, we have to be sure to quote all
+# embedded single quotes properly.  In configure, this macro expands
+# each variable declared with _LT_DECL (and _LT_TAGDECL) into:
+#
+#    <var>='`$ECHO "$<var>" | $SED "$delay_single_quote_subst"`'
+m4_defun([_LT_CONFIG_STATUS_DECLARATIONS],
+[m4_foreach([_lt_var], m4_quote(lt_decl_all_varnames),
+    [m4_n([_LT_CONFIG_STATUS_DECLARE(_lt_var)])])])
+
+
+# _LT_LIBTOOL_TAGS
+# ----------------
+# Output comment and list of tags supported by the script
+m4_defun([_LT_LIBTOOL_TAGS],
+[_LT_FORMAT_COMMENT([The names of the tagged configurations supported by this script])dnl
+available_tags="_LT_TAGS"dnl
+])
+
+
+# _LT_LIBTOOL_DECLARE(VARNAME, [TAG])
+# -----------------------------------
+# Extract the dictionary values for VARNAME (optionally with TAG) and
+# expand to a commented shell variable setting:
+#
+#    # Some comment about what VAR is for.
+#    visible_name=$lt_internal_name
+m4_define([_LT_LIBTOOL_DECLARE],
+[_LT_FORMAT_COMMENT(m4_quote(lt_dict_fetch([lt_decl_dict], [$1],
+					   [description])))[]dnl
+m4_pushdef([_libtool_name],
+    m4_quote(lt_dict_fetch([lt_decl_dict], [$1], [libtool_name])))[]dnl
+m4_case(m4_quote(lt_dict_fetch([lt_decl_dict], [$1], [value])),
+    [0], [_libtool_name=[$]$1],
+    [1], [_libtool_name=$lt_[]$1],
+    [2], [_libtool_name=$lt_[]$1],
+    [_libtool_name=lt_dict_fetch([lt_decl_dict], [$1], [value])])[]dnl
+m4_ifval([$2], [_$2])[]m4_popdef([_libtool_name])[]dnl
+])
+
+
+# _LT_LIBTOOL_CONFIG_VARS
+# -----------------------
+# Produce commented declarations of non-tagged libtool config variables
+# suitable for insertion in the LIBTOOL CONFIG section of the `libtool'
+# script.  Tagged libtool config variables (even for the LIBTOOL CONFIG
+# section) are produced by _LT_LIBTOOL_TAG_VARS.
+m4_defun([_LT_LIBTOOL_CONFIG_VARS],
+[m4_foreach([_lt_var],
+    m4_quote(_lt_decl_filter([tagged?], [no], [], lt_decl_varnames)),
+    [m4_n([_LT_LIBTOOL_DECLARE(_lt_var)])])])
+
+
+# _LT_LIBTOOL_TAG_VARS(TAG)
+# -------------------------
+m4_define([_LT_LIBTOOL_TAG_VARS],
+[m4_foreach([_lt_var], m4_quote(lt_decl_tag_varnames),
+    [m4_n([_LT_LIBTOOL_DECLARE(_lt_var, [$1])])])])
+
+
+# _LT_TAGVAR(VARNAME, [TAGNAME])
+# ------------------------------
+m4_define([_LT_TAGVAR], [m4_ifval([$2], [$1_$2], [$1])])
+
+
+# _LT_CONFIG_COMMANDS
+# -------------------
+# Send accumulated output to $CONFIG_STATUS.  Thanks to the lists of
+# variables for single and double quote escaping we saved from calls
+# to _LT_DECL, we can put quote escaped variables declarations
+# into `config.status', and then the shell code to quote escape them in
+# for loops in `config.status'.  Finally, any additional code accumulated
+# from calls to _LT_CONFIG_LIBTOOL_INIT is expanded.
+m4_defun([_LT_CONFIG_COMMANDS],
+[AC_PROVIDE_IFELSE([LT_OUTPUT],
+	dnl If the libtool generation code has been placed in $CONFIG_LT,
+	dnl instead of duplicating it all over again into config.status,
+	dnl then we will have config.status run $CONFIG_LT later, so it
+	dnl needs to know what name is stored there:
+        [AC_CONFIG_COMMANDS([libtool],
+            [$SHELL $CONFIG_LT || AS_EXIT(1)], [CONFIG_LT='$CONFIG_LT'])],
+    dnl If the libtool generation code is destined for config.status,
+    dnl expand the accumulated commands and init code now:
+    [AC_CONFIG_COMMANDS([libtool],
+        [_LT_OUTPUT_LIBTOOL_COMMANDS], [_LT_OUTPUT_LIBTOOL_COMMANDS_INIT])])
+])#_LT_CONFIG_COMMANDS
+
+
+# Initialize.
+m4_define([_LT_OUTPUT_LIBTOOL_COMMANDS_INIT],
+[
+
+# The HP-UX ksh and POSIX shell print the target directory to stdout
+# if CDPATH is set.
+(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
+
+sed_quote_subst='$sed_quote_subst'
+double_quote_subst='$double_quote_subst'
+delay_variable_subst='$delay_variable_subst'
+_LT_CONFIG_STATUS_DECLARATIONS
+LTCC='$LTCC'
+LTCFLAGS='$LTCFLAGS'
+compiler='$compiler_DEFAULT'
+
+# A function that is used when there is no print builtin or printf.
+func_fallback_echo ()
+{
+  eval 'cat <<_LTECHO_EOF
+\$[]1
+_LTECHO_EOF'
+}
+
+# Quote evaled strings.
+for var in lt_decl_all_varnames([[ \
+]], lt_decl_quote_varnames); do
+    case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in
+    *[[\\\\\\\`\\"\\\$]]*)
+      eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED \\"\\\$sed_quote_subst\\"\\\`\\\\\\""
+      ;;
+    *)
+      eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\""
+      ;;
+    esac
+done
+
+# Double-quote double-evaled strings.
+for var in lt_decl_all_varnames([[ \
+]], lt_decl_dquote_varnames); do
+    case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in
+    *[[\\\\\\\`\\"\\\$]]*)
+      eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED -e \\"\\\$double_quote_subst\\" -e \\"\\\$sed_quote_subst\\" -e \\"\\\$delay_variable_subst\\"\\\`\\\\\\""
+      ;;
+    *)
+      eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\""
+      ;;
+    esac
+done
+
+_LT_OUTPUT_LIBTOOL_INIT
+])
+
+# _LT_GENERATED_FILE_INIT(FILE, [COMMENT])
+# ------------------------------------
+# Generate a child script FILE with all initialization necessary to
+# reuse the environment learned by the parent script, and make the
+# file executable.  If COMMENT is supplied, it is inserted after the
+# `#!' sequence but before initialization text begins.  After this
+# macro, additional text can be appended to FILE to form the body of
+# the child script.  The macro ends with non-zero status if the
+# file could not be fully written (such as if the disk is full).
+m4_ifdef([AS_INIT_GENERATED],
+[m4_defun([_LT_GENERATED_FILE_INIT],[AS_INIT_GENERATED($@)])],
+[m4_defun([_LT_GENERATED_FILE_INIT],
+[m4_require([AS_PREPARE])]dnl
+[m4_pushdef([AS_MESSAGE_LOG_FD])]dnl
+[lt_write_fail=0
+cat >$1 <<_ASEOF || lt_write_fail=1
+#! $SHELL
+# Generated by $as_me.
+$2
+SHELL=\${CONFIG_SHELL-$SHELL}
+export SHELL
+_ASEOF
+cat >>$1 <<\_ASEOF || lt_write_fail=1
+AS_SHELL_SANITIZE
+_AS_PREPARE
+exec AS_MESSAGE_FD>&1
+_ASEOF
+test $lt_write_fail = 0 && chmod +x $1[]dnl
+m4_popdef([AS_MESSAGE_LOG_FD])])])# _LT_GENERATED_FILE_INIT
+
+# LT_OUTPUT
+# ---------
+# This macro allows early generation of the libtool script (before
+# AC_OUTPUT is called), incase it is used in configure for compilation
+# tests.
+AC_DEFUN([LT_OUTPUT],
+[: ${CONFIG_LT=./config.lt}
+AC_MSG_NOTICE([creating $CONFIG_LT])
+_LT_GENERATED_FILE_INIT(["$CONFIG_LT"],
+[# Run this file to recreate a libtool stub with the current configuration.])
+
+cat >>"$CONFIG_LT" <<\_LTEOF
+lt_cl_silent=false
+exec AS_MESSAGE_LOG_FD>>config.log
+{
+  echo
+  AS_BOX([Running $as_me.])
+} >&AS_MESSAGE_LOG_FD
+
+lt_cl_help="\
+\`$as_me' creates a local libtool stub from the current configuration,
+for use in further configure time tests before the real libtool is
+generated.
+
+Usage: $[0] [[OPTIONS]]
+
+  -h, --help      print this help, then exit
+  -V, --version   print version number, then exit
+  -q, --quiet     do not print progress messages
+  -d, --debug     don't remove temporary files
+
+Report bugs to <bug-libtool at gnu.org>."
+
+lt_cl_version="\
+m4_ifset([AC_PACKAGE_NAME], [AC_PACKAGE_NAME ])config.lt[]dnl
+m4_ifset([AC_PACKAGE_VERSION], [ AC_PACKAGE_VERSION])
+configured by $[0], generated by m4_PACKAGE_STRING.
+
+Copyright (C) 2011 Free Software Foundation, Inc.
+This config.lt script is free software; the Free Software Foundation
+gives unlimited permision to copy, distribute and modify it."
+
+while test $[#] != 0
+do
+  case $[1] in
+    --version | --v* | -V )
+      echo "$lt_cl_version"; exit 0 ;;
+    --help | --h* | -h )
+      echo "$lt_cl_help"; exit 0 ;;
+    --debug | --d* | -d )
+      debug=: ;;
+    --quiet | --q* | --silent | --s* | -q )
+      lt_cl_silent=: ;;
+
+    -*) AC_MSG_ERROR([unrecognized option: $[1]
+Try \`$[0] --help' for more information.]) ;;
+
+    *) AC_MSG_ERROR([unrecognized argument: $[1]
+Try \`$[0] --help' for more information.]) ;;
+  esac
+  shift
+done
+
+if $lt_cl_silent; then
+  exec AS_MESSAGE_FD>/dev/null
+fi
+_LTEOF
+
+cat >>"$CONFIG_LT" <<_LTEOF
+_LT_OUTPUT_LIBTOOL_COMMANDS_INIT
+_LTEOF
+
+cat >>"$CONFIG_LT" <<\_LTEOF
+AC_MSG_NOTICE([creating $ofile])
+_LT_OUTPUT_LIBTOOL_COMMANDS
+AS_EXIT(0)
+_LTEOF
+chmod +x "$CONFIG_LT"
+
+# configure is writing to config.log, but config.lt does its own redirection,
+# appending to config.log, which fails on DOS, as config.log is still kept
+# open by configure.  Here we exec the FD to /dev/null, effectively closing
+# config.log, so it can be properly (re)opened and appended to by config.lt.
+lt_cl_success=:
+test "$silent" = yes &&
+  lt_config_lt_args="$lt_config_lt_args --quiet"
+exec AS_MESSAGE_LOG_FD>/dev/null
+$SHELL "$CONFIG_LT" $lt_config_lt_args || lt_cl_success=false
+exec AS_MESSAGE_LOG_FD>>config.log
+$lt_cl_success || AS_EXIT(1)
+])# LT_OUTPUT
+
+
+# _LT_CONFIG(TAG)
+# ---------------
+# If TAG is the built-in tag, create an initial libtool script with a
+# default configuration from the untagged config vars.  Otherwise add code
+# to config.status for appending the configuration named by TAG from the
+# matching tagged config vars.
+m4_defun([_LT_CONFIG],
+[m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+_LT_CONFIG_SAVE_COMMANDS([
+  m4_define([_LT_TAG], m4_if([$1], [], [C], [$1]))dnl
+  m4_if(_LT_TAG, [C], [
+    # See if we are running on zsh, and set the options which allow our
+    # commands through without removal of \ escapes.
+    if test -n "${ZSH_VERSION+set}" ; then
+      setopt NO_GLOB_SUBST
+    fi
+
+    cfgfile="${ofile}T"
+    trap "$RM \"$cfgfile\"; exit 1" 1 2 15
+    $RM "$cfgfile"
+
+    cat <<_LT_EOF >> "$cfgfile"
+#! $SHELL
+
+# `$ECHO "$ofile" | sed 's%^.*/%%'` - Provide generalized library-building support services.
+# Generated automatically by $as_me ($PACKAGE$TIMESTAMP) $VERSION
+# Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`:
+# NOTE: Changes made to this file will be lost: look at ltmain.sh.
+#
+_LT_COPYING
+_LT_LIBTOOL_TAGS
+
+# ### BEGIN LIBTOOL CONFIG
+_LT_LIBTOOL_CONFIG_VARS
+_LT_LIBTOOL_TAG_VARS
+# ### END LIBTOOL CONFIG
+
+_LT_EOF
+
+  case $host_os in
+  aix3*)
+    cat <<\_LT_EOF >> "$cfgfile"
+# AIX sometimes has problems with the GCC collect2 program.  For some
+# reason, if we set the COLLECT_NAMES environment variable, the problems
+# vanish in a puff of smoke.
+if test "X${COLLECT_NAMES+set}" != Xset; then
+  COLLECT_NAMES=
+  export COLLECT_NAMES
+fi
+_LT_EOF
+    ;;
+  esac
+
+  _LT_PROG_LTMAIN
+
+  # We use sed instead of cat because bash on DJGPP gets confused if
+  # if finds mixed CR/LF and LF-only lines.  Since sed operates in
+  # text mode, it properly converts lines to CR/LF.  This bash problem
+  # is reportedly fixed, but why not run on old versions too?
+  sed '$q' "$ltmain" >> "$cfgfile" \
+     || (rm -f "$cfgfile"; exit 1)
+
+  _LT_PROG_REPLACE_SHELLFNS
+
+   mv -f "$cfgfile" "$ofile" ||
+    (rm -f "$ofile" && cp "$cfgfile" "$ofile" && rm -f "$cfgfile")
+  chmod +x "$ofile"
+],
+[cat <<_LT_EOF >> "$ofile"
+
+dnl Unfortunately we have to use $1 here, since _LT_TAG is not expanded
+dnl in a comment (ie after a #).
+# ### BEGIN LIBTOOL TAG CONFIG: $1
+_LT_LIBTOOL_TAG_VARS(_LT_TAG)
+# ### END LIBTOOL TAG CONFIG: $1
+_LT_EOF
+])dnl /m4_if
+],
+[m4_if([$1], [], [
+    PACKAGE='$PACKAGE'
+    VERSION='$VERSION'
+    TIMESTAMP='$TIMESTAMP'
+    RM='$RM'
+    ofile='$ofile'], [])
+])dnl /_LT_CONFIG_SAVE_COMMANDS
+])# _LT_CONFIG
+
+
+# LT_SUPPORTED_TAG(TAG)
+# ---------------------
+# Trace this macro to discover what tags are supported by the libtool
+# --tag option, using:
+#    autoconf --trace 'LT_SUPPORTED_TAG:$1'
+AC_DEFUN([LT_SUPPORTED_TAG], [])
+
+
+# C support is built-in for now
+m4_define([_LT_LANG_C_enabled], [])
+m4_define([_LT_TAGS], [])
+
+
+# LT_LANG(LANG)
+# -------------
+# Enable libtool support for the given language if not already enabled.
+AC_DEFUN([LT_LANG],
+[AC_BEFORE([$0], [LT_OUTPUT])dnl
+m4_case([$1],
+  [C],			[_LT_LANG(C)],
+  [C++],		[_LT_LANG(CXX)],
+  [Go],			[_LT_LANG(GO)],
+  [Java],		[_LT_LANG(GCJ)],
+  [Fortran 77],		[_LT_LANG(F77)],
+  [Fortran],		[_LT_LANG(FC)],
+  [Windows Resource],	[_LT_LANG(RC)],
+  [m4_ifdef([_LT_LANG_]$1[_CONFIG],
+    [_LT_LANG($1)],
+    [m4_fatal([$0: unsupported language: "$1"])])])dnl
+])# LT_LANG
+
+
+# _LT_LANG(LANGNAME)
+# ------------------
+m4_defun([_LT_LANG],
+[m4_ifdef([_LT_LANG_]$1[_enabled], [],
+  [LT_SUPPORTED_TAG([$1])dnl
+  m4_append([_LT_TAGS], [$1 ])dnl
+  m4_define([_LT_LANG_]$1[_enabled], [])dnl
+  _LT_LANG_$1_CONFIG($1)])dnl
+])# _LT_LANG
+
+
+m4_ifndef([AC_PROG_GO], [
+############################################################
+# NOTE: This macro has been submitted for inclusion into   #
+#  GNU Autoconf as AC_PROG_GO.  When it is available in    #
+#  a released version of Autoconf we should remove this    #
+#  macro and use it instead.                               #
+############################################################
+m4_defun([AC_PROG_GO],
+[AC_LANG_PUSH(Go)dnl
+AC_ARG_VAR([GOC],     [Go compiler command])dnl
+AC_ARG_VAR([GOFLAGS], [Go compiler flags])dnl
+_AC_ARG_VAR_LDFLAGS()dnl
+AC_CHECK_TOOL(GOC, gccgo)
+if test -z "$GOC"; then
+  if test -n "$ac_tool_prefix"; then
+    AC_CHECK_PROG(GOC, [${ac_tool_prefix}gccgo], [${ac_tool_prefix}gccgo])
+  fi
+fi
+if test -z "$GOC"; then
+  AC_CHECK_PROG(GOC, gccgo, gccgo, false)
+fi
+])#m4_defun
+])#m4_ifndef
+
+
+# _LT_LANG_DEFAULT_CONFIG
+# -----------------------
+m4_defun([_LT_LANG_DEFAULT_CONFIG],
+[AC_PROVIDE_IFELSE([AC_PROG_CXX],
+  [LT_LANG(CXX)],
+  [m4_define([AC_PROG_CXX], defn([AC_PROG_CXX])[LT_LANG(CXX)])])
+
+AC_PROVIDE_IFELSE([AC_PROG_F77],
+  [LT_LANG(F77)],
+  [m4_define([AC_PROG_F77], defn([AC_PROG_F77])[LT_LANG(F77)])])
+
+AC_PROVIDE_IFELSE([AC_PROG_FC],
+  [LT_LANG(FC)],
+  [m4_define([AC_PROG_FC], defn([AC_PROG_FC])[LT_LANG(FC)])])
+
+dnl The call to [A][M_PROG_GCJ] is quoted like that to stop aclocal
+dnl pulling things in needlessly.
+AC_PROVIDE_IFELSE([AC_PROG_GCJ],
+  [LT_LANG(GCJ)],
+  [AC_PROVIDE_IFELSE([A][M_PROG_GCJ],
+    [LT_LANG(GCJ)],
+    [AC_PROVIDE_IFELSE([LT_PROG_GCJ],
+      [LT_LANG(GCJ)],
+      [m4_ifdef([AC_PROG_GCJ],
+	[m4_define([AC_PROG_GCJ], defn([AC_PROG_GCJ])[LT_LANG(GCJ)])])
+       m4_ifdef([A][M_PROG_GCJ],
+	[m4_define([A][M_PROG_GCJ], defn([A][M_PROG_GCJ])[LT_LANG(GCJ)])])
+       m4_ifdef([LT_PROG_GCJ],
+	[m4_define([LT_PROG_GCJ], defn([LT_PROG_GCJ])[LT_LANG(GCJ)])])])])])
+
+AC_PROVIDE_IFELSE([AC_PROG_GO],
+  [LT_LANG(GO)],
+  [m4_define([AC_PROG_GO], defn([AC_PROG_GO])[LT_LANG(GO)])])
+
+AC_PROVIDE_IFELSE([LT_PROG_RC],
+  [LT_LANG(RC)],
+  [m4_define([LT_PROG_RC], defn([LT_PROG_RC])[LT_LANG(RC)])])
+])# _LT_LANG_DEFAULT_CONFIG
+
+# Obsolete macros:
+AU_DEFUN([AC_LIBTOOL_CXX], [LT_LANG(C++)])
+AU_DEFUN([AC_LIBTOOL_F77], [LT_LANG(Fortran 77)])
+AU_DEFUN([AC_LIBTOOL_FC], [LT_LANG(Fortran)])
+AU_DEFUN([AC_LIBTOOL_GCJ], [LT_LANG(Java)])
+AU_DEFUN([AC_LIBTOOL_RC], [LT_LANG(Windows Resource)])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_LIBTOOL_CXX], [])
+dnl AC_DEFUN([AC_LIBTOOL_F77], [])
+dnl AC_DEFUN([AC_LIBTOOL_FC], [])
+dnl AC_DEFUN([AC_LIBTOOL_GCJ], [])
+dnl AC_DEFUN([AC_LIBTOOL_RC], [])
+
+
+# _LT_TAG_COMPILER
+# ----------------
+m4_defun([_LT_TAG_COMPILER],
+[AC_REQUIRE([AC_PROG_CC])dnl
+
+_LT_DECL([LTCC], [CC], [1], [A C compiler])dnl
+_LT_DECL([LTCFLAGS], [CFLAGS], [1], [LTCC compiler flags])dnl
+_LT_TAGDECL([CC], [compiler], [1], [A language specific compiler])dnl
+_LT_TAGDECL([with_gcc], [GCC], [0], [Is the compiler the GNU compiler?])dnl
+
+# If no C compiler was specified, use CC.
+LTCC=${LTCC-"$CC"}
+
+# If no C compiler flags were specified, use CFLAGS.
+LTCFLAGS=${LTCFLAGS-"$CFLAGS"}
+
+# Allow CC to be a program name with arguments.
+compiler=$CC
+])# _LT_TAG_COMPILER
+
+
+# _LT_COMPILER_BOILERPLATE
+# ------------------------
+# Check for compiler boilerplate output or warnings with
+# the simple compiler test code.
+m4_defun([_LT_COMPILER_BOILERPLATE],
+[m4_require([_LT_DECL_SED])dnl
+ac_outfile=conftest.$ac_objext
+echo "$lt_simple_compile_test_code" >conftest.$ac_ext
+eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
+_lt_compiler_boilerplate=`cat conftest.err`
+$RM conftest*
+])# _LT_COMPILER_BOILERPLATE
+
+
+# _LT_LINKER_BOILERPLATE
+# ----------------------
+# Check for linker boilerplate output or warnings with
+# the simple link test code.
+m4_defun([_LT_LINKER_BOILERPLATE],
+[m4_require([_LT_DECL_SED])dnl
+ac_outfile=conftest.$ac_objext
+echo "$lt_simple_link_test_code" >conftest.$ac_ext
+eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
+_lt_linker_boilerplate=`cat conftest.err`
+$RM -r conftest*
+])# _LT_LINKER_BOILERPLATE
+
+# _LT_REQUIRED_DARWIN_CHECKS
+# -------------------------
+m4_defun_once([_LT_REQUIRED_DARWIN_CHECKS],[
+  case $host_os in
+    rhapsody* | darwin*)
+    AC_CHECK_TOOL([DSYMUTIL], [dsymutil], [:])
+    AC_CHECK_TOOL([NMEDIT], [nmedit], [:])
+    AC_CHECK_TOOL([LIPO], [lipo], [:])
+    AC_CHECK_TOOL([OTOOL], [otool], [:])
+    AC_CHECK_TOOL([OTOOL64], [otool64], [:])
+    _LT_DECL([], [DSYMUTIL], [1],
+      [Tool to manipulate archived DWARF debug symbol files on Mac OS X])
+    _LT_DECL([], [NMEDIT], [1],
+      [Tool to change global to local symbols on Mac OS X])
+    _LT_DECL([], [LIPO], [1],
+      [Tool to manipulate fat objects and archives on Mac OS X])
+    _LT_DECL([], [OTOOL], [1],
+      [ldd/readelf like tool for Mach-O binaries on Mac OS X])
+    _LT_DECL([], [OTOOL64], [1],
+      [ldd/readelf like tool for 64 bit Mach-O binaries on Mac OS X 10.4])
+
+    AC_CACHE_CHECK([for -single_module linker flag],[lt_cv_apple_cc_single_mod],
+      [lt_cv_apple_cc_single_mod=no
+      if test -z "${LT_MULTI_MODULE}"; then
+	# By default we will add the -single_module flag. You can override
+	# by either setting the environment variable LT_MULTI_MODULE
+	# non-empty at configure time, or by adding -multi_module to the
+	# link flags.
+	rm -rf libconftest.dylib*
+	echo "int foo(void){return 1;}" > conftest.c
+	echo "$LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \
+-dynamiclib -Wl,-single_module conftest.c" >&AS_MESSAGE_LOG_FD
+	$LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \
+	  -dynamiclib -Wl,-single_module conftest.c 2>conftest.err
+        _lt_result=$?
+	# If there is a non-empty error log, and "single_module"
+	# appears in it, assume the flag caused a linker warning
+        if test -s conftest.err && $GREP single_module conftest.err; then
+	  cat conftest.err >&AS_MESSAGE_LOG_FD
+	# Otherwise, if the output was created with a 0 exit code from
+	# the compiler, it worked.
+	elif test -f libconftest.dylib && test $_lt_result -eq 0; then
+	  lt_cv_apple_cc_single_mod=yes
+	else
+	  cat conftest.err >&AS_MESSAGE_LOG_FD
+	fi
+	rm -rf libconftest.dylib*
+	rm -f conftest.*
+      fi])
+
+    AC_CACHE_CHECK([for -exported_symbols_list linker flag],
+      [lt_cv_ld_exported_symbols_list],
+      [lt_cv_ld_exported_symbols_list=no
+      save_LDFLAGS=$LDFLAGS
+      echo "_main" > conftest.sym
+      LDFLAGS="$LDFLAGS -Wl,-exported_symbols_list,conftest.sym"
+      AC_LINK_IFELSE([AC_LANG_PROGRAM([],[])],
+	[lt_cv_ld_exported_symbols_list=yes],
+	[lt_cv_ld_exported_symbols_list=no])
+	LDFLAGS="$save_LDFLAGS"
+    ])
+
+    AC_CACHE_CHECK([for -force_load linker flag],[lt_cv_ld_force_load],
+      [lt_cv_ld_force_load=no
+      cat > conftest.c << _LT_EOF
+int forced_loaded() { return 2;}
+_LT_EOF
+      echo "$LTCC $LTCFLAGS -c -o conftest.o conftest.c" >&AS_MESSAGE_LOG_FD
+      $LTCC $LTCFLAGS -c -o conftest.o conftest.c 2>&AS_MESSAGE_LOG_FD
+      echo "$AR cru libconftest.a conftest.o" >&AS_MESSAGE_LOG_FD
+      $AR cru libconftest.a conftest.o 2>&AS_MESSAGE_LOG_FD
+      echo "$RANLIB libconftest.a" >&AS_MESSAGE_LOG_FD
+      $RANLIB libconftest.a 2>&AS_MESSAGE_LOG_FD
+      cat > conftest.c << _LT_EOF
+int main() { return 0;}
+_LT_EOF
+      echo "$LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a" >&AS_MESSAGE_LOG_FD
+      $LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a 2>conftest.err
+      _lt_result=$?
+      if test -s conftest.err && $GREP force_load conftest.err; then
+	cat conftest.err >&AS_MESSAGE_LOG_FD
+      elif test -f conftest && test $_lt_result -eq 0 && $GREP forced_load conftest >/dev/null 2>&1 ; then
+	lt_cv_ld_force_load=yes
+      else
+	cat conftest.err >&AS_MESSAGE_LOG_FD
+      fi
+        rm -f conftest.err libconftest.a conftest conftest.c
+        rm -rf conftest.dSYM
+    ])
+    case $host_os in
+    rhapsody* | darwin1.[[012]])
+      _lt_dar_allow_undefined='${wl}-undefined ${wl}suppress' ;;
+    darwin1.*)
+      _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;;
+    darwin*) # darwin 5.x on
+      # if running on 10.5 or later, the deployment target defaults
+      # to the OS version, if on x86, and 10.4, the deployment
+      # target defaults to 10.4. Don't you love it?
+      case ${MACOSX_DEPLOYMENT_TARGET-10.0},$host in
+	10.0,*86*-darwin8*|10.0,*-darwin[[91]]*)
+	  _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;;
+	10.[[012]]*)
+	  _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;;
+	10.*)
+	  _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;;
+      esac
+    ;;
+  esac
+    if test "$lt_cv_apple_cc_single_mod" = "yes"; then
+      _lt_dar_single_mod='$single_module'
+    fi
+    if test "$lt_cv_ld_exported_symbols_list" = "yes"; then
+      _lt_dar_export_syms=' ${wl}-exported_symbols_list,$output_objdir/${libname}-symbols.expsym'
+    else
+      _lt_dar_export_syms='~$NMEDIT -s $output_objdir/${libname}-symbols.expsym ${lib}'
+    fi
+    if test "$DSYMUTIL" != ":" && test "$lt_cv_ld_force_load" = "no"; then
+      _lt_dsymutil='~$DSYMUTIL $lib || :'
+    else
+      _lt_dsymutil=
+    fi
+    ;;
+  esac
+])
+
+
+# _LT_DARWIN_LINKER_FEATURES([TAG])
+# ---------------------------------
+# Checks for linker and compiler features on darwin
+m4_defun([_LT_DARWIN_LINKER_FEATURES],
+[
+  m4_require([_LT_REQUIRED_DARWIN_CHECKS])
+  _LT_TAGVAR(archive_cmds_need_lc, $1)=no
+  _LT_TAGVAR(hardcode_direct, $1)=no
+  _LT_TAGVAR(hardcode_automatic, $1)=yes
+  _LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported
+  if test "$lt_cv_ld_force_load" = "yes"; then
+    _LT_TAGVAR(whole_archive_flag_spec, $1)='`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience ${wl}-force_load,$conv\"; done; func_echo_all \"$new_convenience\"`'
+    m4_case([$1], [F77], [_LT_TAGVAR(compiler_needs_object, $1)=yes],
+                  [FC],  [_LT_TAGVAR(compiler_needs_object, $1)=yes])
+  else
+    _LT_TAGVAR(whole_archive_flag_spec, $1)=''
+  fi
+  _LT_TAGVAR(link_all_deplibs, $1)=yes
+  _LT_TAGVAR(allow_undefined_flag, $1)="$_lt_dar_allow_undefined"
+  case $cc_basename in
+     ifort*) _lt_dar_can_shared=yes ;;
+     *) _lt_dar_can_shared=$GCC ;;
+  esac
+  if test "$_lt_dar_can_shared" = "yes"; then
+    output_verbose_link_cmd=func_echo_all
+    _LT_TAGVAR(archive_cmds, $1)="\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod${_lt_dsymutil}"
+    _LT_TAGVAR(module_cmds, $1)="\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dsymutil}"
+    _LT_TAGVAR(archive_expsym_cmds, $1)="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring ${_lt_dar_single_mod}${_lt_dar_export_syms}${_lt_dsymutil}"
+    _LT_TAGVAR(module_expsym_cmds, $1)="sed -e 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dar_export_syms}${_lt_dsymutil}"
+    m4_if([$1], [CXX],
+[   if test "$lt_cv_apple_cc_single_mod" != "yes"; then
+      _LT_TAGVAR(archive_cmds, $1)="\$CC -r -keep_private_externs -nostdlib -o \${lib}-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \${lib}-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring${_lt_dsymutil}"
+      _LT_TAGVAR(archive_expsym_cmds, $1)="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -r -keep_private_externs -nostdlib -o \${lib}-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \${lib}-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring${_lt_dar_export_syms}${_lt_dsymutil}"
+    fi
+],[])
+  else
+  _LT_TAGVAR(ld_shlibs, $1)=no
+  fi
+])
+
+# _LT_SYS_MODULE_PATH_AIX([TAGNAME])
+# ----------------------------------
+# Links a minimal program and checks the executable
+# for the system default hardcoded library path. In most cases,
+# this is /usr/lib:/lib, but when the MPI compilers are used
+# the location of the communication and MPI libs are included too.
+# If we don't find anything, use the default library path according
+# to the aix ld manual.
+# Store the results from the different compilers for each TAGNAME.
+# Allow to override them for all tags through lt_cv_aix_libpath.
+m4_defun([_LT_SYS_MODULE_PATH_AIX],
+[m4_require([_LT_DECL_SED])dnl
+if test "${lt_cv_aix_libpath+set}" = set; then
+  aix_libpath=$lt_cv_aix_libpath
+else
+  AC_CACHE_VAL([_LT_TAGVAR([lt_cv_aix_libpath_], [$1])],
+  [AC_LINK_IFELSE([AC_LANG_PROGRAM],[
+  lt_aix_libpath_sed='[
+      /Import File Strings/,/^$/ {
+	  /^0/ {
+	      s/^0  *\([^ ]*\) *$/\1/
+	      p
+	  }
+      }]'
+  _LT_TAGVAR([lt_cv_aix_libpath_], [$1])=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"`
+  # Check for a 64-bit object if we didn't find anything.
+  if test -z "$_LT_TAGVAR([lt_cv_aix_libpath_], [$1])"; then
+    _LT_TAGVAR([lt_cv_aix_libpath_], [$1])=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"`
+  fi],[])
+  if test -z "$_LT_TAGVAR([lt_cv_aix_libpath_], [$1])"; then
+    _LT_TAGVAR([lt_cv_aix_libpath_], [$1])="/usr/lib:/lib"
+  fi
+  ])
+  aix_libpath=$_LT_TAGVAR([lt_cv_aix_libpath_], [$1])
+fi
+])# _LT_SYS_MODULE_PATH_AIX
+
+
+# _LT_SHELL_INIT(ARG)
+# -------------------
+m4_define([_LT_SHELL_INIT],
+[m4_divert_text([M4SH-INIT], [$1
+])])# _LT_SHELL_INIT
+
+
+
+# _LT_PROG_ECHO_BACKSLASH
+# -----------------------
+# Find how we can fake an echo command that does not interpret backslash.
+# In particular, with Autoconf 2.60 or later we add some code to the start
+# of the generated configure script which will find a shell with a builtin
+# printf (which we can use as an echo command).
+m4_defun([_LT_PROG_ECHO_BACKSLASH],
+[ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
+ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO
+ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO$ECHO
+
+AC_MSG_CHECKING([how to print strings])
+# Test print first, because it will be a builtin if present.
+if test "X`( print -r -- -n ) 2>/dev/null`" = X-n && \
+   test "X`print -r -- $ECHO 2>/dev/null`" = "X$ECHO"; then
+  ECHO='print -r --'
+elif test "X`printf %s $ECHO 2>/dev/null`" = "X$ECHO"; then
+  ECHO='printf %s\n'
+else
+  # Use this function as a fallback that always works.
+  func_fallback_echo ()
+  {
+    eval 'cat <<_LTECHO_EOF
+$[]1
+_LTECHO_EOF'
+  }
+  ECHO='func_fallback_echo'
+fi
+
+# func_echo_all arg...
+# Invoke $ECHO with all args, space-separated.
+func_echo_all ()
+{
+    $ECHO "$*" 
+}
+
+case "$ECHO" in
+  printf*) AC_MSG_RESULT([printf]) ;;
+  print*) AC_MSG_RESULT([print -r]) ;;
+  *) AC_MSG_RESULT([cat]) ;;
+esac
+
+m4_ifdef([_AS_DETECT_SUGGESTED],
+[_AS_DETECT_SUGGESTED([
+  test -n "${ZSH_VERSION+set}${BASH_VERSION+set}" || (
+    ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
+    ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO
+    ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO$ECHO
+    PATH=/empty FPATH=/empty; export PATH FPATH
+    test "X`printf %s $ECHO`" = "X$ECHO" \
+      || test "X`print -r -- $ECHO`" = "X$ECHO" )])])
+
+_LT_DECL([], [SHELL], [1], [Shell to use when invoking shell scripts])
+_LT_DECL([], [ECHO], [1], [An echo program that protects backslashes])
+])# _LT_PROG_ECHO_BACKSLASH
+
+
+# _LT_WITH_SYSROOT
+# ----------------
+AC_DEFUN([_LT_WITH_SYSROOT],
+[AC_MSG_CHECKING([for sysroot])
+AC_ARG_WITH([sysroot],
+[  --with-sysroot[=DIR] Search for dependent libraries within DIR
+                        (or the compiler's sysroot if not specified).],
+[], [with_sysroot=no])
+
+dnl lt_sysroot will always be passed unquoted.  We quote it here
+dnl in case the user passed a directory name.
+lt_sysroot=
+case ${with_sysroot} in #(
+ yes)
+   if test "$GCC" = yes; then
+     lt_sysroot=`$CC --print-sysroot 2>/dev/null`
+   fi
+   ;; #(
+ /*)
+   lt_sysroot=`echo "$with_sysroot" | sed -e "$sed_quote_subst"`
+   ;; #(
+ no|'')
+   ;; #(
+ *)
+   AC_MSG_RESULT([${with_sysroot}])
+   AC_MSG_ERROR([The sysroot must be an absolute path.])
+   ;;
+esac
+
+ AC_MSG_RESULT([${lt_sysroot:-no}])
+_LT_DECL([], [lt_sysroot], [0], [The root where to search for ]dnl
+[dependent libraries, and in which our libraries should be installed.])])
+
+# _LT_ENABLE_LOCK
+# ---------------
+m4_defun([_LT_ENABLE_LOCK],
+[AC_ARG_ENABLE([libtool-lock],
+  [AS_HELP_STRING([--disable-libtool-lock],
+    [avoid locking (might break parallel builds)])])
+test "x$enable_libtool_lock" != xno && enable_libtool_lock=yes
+
+# Some flags need to be propagated to the compiler or linker for good
+# libtool support.
+case $host in
+ia64-*-hpux*)
+  # Find out which ABI we are using.
+  echo 'int i;' > conftest.$ac_ext
+  if AC_TRY_EVAL(ac_compile); then
+    case `/usr/bin/file conftest.$ac_objext` in
+      *ELF-32*)
+	HPUX_IA64_MODE="32"
+	;;
+      *ELF-64*)
+	HPUX_IA64_MODE="64"
+	;;
+    esac
+  fi
+  rm -rf conftest*
+  ;;
+*-*-irix6*)
+  # Find out which ABI we are using.
+  echo '[#]line '$LINENO' "configure"' > conftest.$ac_ext
+  if AC_TRY_EVAL(ac_compile); then
+    if test "$lt_cv_prog_gnu_ld" = yes; then
+      case `/usr/bin/file conftest.$ac_objext` in
+	*32-bit*)
+	  LD="${LD-ld} -melf32bsmip"
+	  ;;
+	*N32*)
+	  LD="${LD-ld} -melf32bmipn32"
+	  ;;
+	*64-bit*)
+	  LD="${LD-ld} -melf64bmip"
+	;;
+      esac
+    else
+      case `/usr/bin/file conftest.$ac_objext` in
+	*32-bit*)
+	  LD="${LD-ld} -32"
+	  ;;
+	*N32*)
+	  LD="${LD-ld} -n32"
+	  ;;
+	*64-bit*)
+	  LD="${LD-ld} -64"
+	  ;;
+      esac
+    fi
+  fi
+  rm -rf conftest*
+  ;;
+
+x86_64-*kfreebsd*-gnu|x86_64-*linux*|ppc*-*linux*|powerpc*-*linux*| \
+s390*-*linux*|s390*-*tpf*|sparc*-*linux*)
+  # Find out which ABI we are using.
+  echo 'int i;' > conftest.$ac_ext
+  if AC_TRY_EVAL(ac_compile); then
+    case `/usr/bin/file conftest.o` in
+      *32-bit*)
+	case $host in
+	  x86_64-*kfreebsd*-gnu)
+	    LD="${LD-ld} -m elf_i386_fbsd"
+	    ;;
+	  x86_64-*linux*)
+	    LD="${LD-ld} -m elf_i386"
+	    ;;
+	  ppc64-*linux*|powerpc64-*linux*)
+	    LD="${LD-ld} -m elf32ppclinux"
+	    ;;
+	  s390x-*linux*)
+	    LD="${LD-ld} -m elf_s390"
+	    ;;
+	  sparc64-*linux*)
+	    LD="${LD-ld} -m elf32_sparc"
+	    ;;
+	esac
+	;;
+      *64-bit*)
+	case $host in
+	  x86_64-*kfreebsd*-gnu)
+	    LD="${LD-ld} -m elf_x86_64_fbsd"
+	    ;;
+	  x86_64-*linux*)
+	    LD="${LD-ld} -m elf_x86_64"
+	    ;;
+	  ppc*-*linux*|powerpc*-*linux*)
+	    LD="${LD-ld} -m elf64ppc"
+	    ;;
+	  s390*-*linux*|s390*-*tpf*)
+	    LD="${LD-ld} -m elf64_s390"
+	    ;;
+	  sparc*-*linux*)
+	    LD="${LD-ld} -m elf64_sparc"
+	    ;;
+	esac
+	;;
+    esac
+  fi
+  rm -rf conftest*
+  ;;
+
+*-*-sco3.2v5*)
+  # On SCO OpenServer 5, we need -belf to get full-featured binaries.
+  SAVE_CFLAGS="$CFLAGS"
+  CFLAGS="$CFLAGS -belf"
+  AC_CACHE_CHECK([whether the C compiler needs -belf], lt_cv_cc_needs_belf,
+    [AC_LANG_PUSH(C)
+     AC_LINK_IFELSE([AC_LANG_PROGRAM([[]],[[]])],[lt_cv_cc_needs_belf=yes],[lt_cv_cc_needs_belf=no])
+     AC_LANG_POP])
+  if test x"$lt_cv_cc_needs_belf" != x"yes"; then
+    # this is probably gcc 2.8.0, egcs 1.0 or newer; no need for -belf
+    CFLAGS="$SAVE_CFLAGS"
+  fi
+  ;;
+*-*solaris*)
+  # Find out which ABI we are using.
+  echo 'int i;' > conftest.$ac_ext
+  if AC_TRY_EVAL(ac_compile); then
+    case `/usr/bin/file conftest.o` in
+    *64-bit*)
+      case $lt_cv_prog_gnu_ld in
+      yes*)
+        case $host in
+        i?86-*-solaris*)
+          LD="${LD-ld} -m elf_x86_64"
+          ;;
+        sparc*-*-solaris*)
+          LD="${LD-ld} -m elf64_sparc"
+          ;;
+        esac
+        # GNU ld 2.21 introduced _sol2 emulations.  Use them if available.
+        if ${LD-ld} -V | grep _sol2 >/dev/null 2>&1; then
+          LD="${LD-ld}_sol2"
+        fi
+        ;;
+      *)
+	if ${LD-ld} -64 -r -o conftest2.o conftest.o >/dev/null 2>&1; then
+	  LD="${LD-ld} -64"
+	fi
+	;;
+      esac
+      ;;
+    esac
+  fi
+  rm -rf conftest*
+  ;;
+esac
+
+need_locks="$enable_libtool_lock"
+])# _LT_ENABLE_LOCK
+
+
+# _LT_PROG_AR
+# -----------
+m4_defun([_LT_PROG_AR],
+[AC_CHECK_TOOLS(AR, [ar], false)
+: ${AR=ar}
+: ${AR_FLAGS=cru}
+_LT_DECL([], [AR], [1], [The archiver])
+_LT_DECL([], [AR_FLAGS], [1], [Flags to create an archive])
+
+AC_CACHE_CHECK([for archiver @FILE support], [lt_cv_ar_at_file],
+  [lt_cv_ar_at_file=no
+   AC_COMPILE_IFELSE([AC_LANG_PROGRAM],
+     [echo conftest.$ac_objext > conftest.lst
+      lt_ar_try='$AR $AR_FLAGS libconftest.a @conftest.lst >&AS_MESSAGE_LOG_FD'
+      AC_TRY_EVAL([lt_ar_try])
+      if test "$ac_status" -eq 0; then
+	# Ensure the archiver fails upon bogus file names.
+	rm -f conftest.$ac_objext libconftest.a
+	AC_TRY_EVAL([lt_ar_try])
+	if test "$ac_status" -ne 0; then
+          lt_cv_ar_at_file=@
+        fi
+      fi
+      rm -f conftest.* libconftest.a
+     ])
+  ])
+
+if test "x$lt_cv_ar_at_file" = xno; then
+  archiver_list_spec=
+else
+  archiver_list_spec=$lt_cv_ar_at_file
+fi
+_LT_DECL([], [archiver_list_spec], [1],
+  [How to feed a file listing to the archiver])
+])# _LT_PROG_AR
+
+
+# _LT_CMD_OLD_ARCHIVE
+# -------------------
+m4_defun([_LT_CMD_OLD_ARCHIVE],
+[_LT_PROG_AR
+
+AC_CHECK_TOOL(STRIP, strip, :)
+test -z "$STRIP" && STRIP=:
+_LT_DECL([], [STRIP], [1], [A symbol stripping program])
+
+AC_CHECK_TOOL(RANLIB, ranlib, :)
+test -z "$RANLIB" && RANLIB=:
+_LT_DECL([], [RANLIB], [1],
+    [Commands used to install an old-style archive])
+
+# Determine commands to create old-style static archives.
+old_archive_cmds='$AR $AR_FLAGS $oldlib$oldobjs'
+old_postinstall_cmds='chmod 644 $oldlib'
+old_postuninstall_cmds=
+
+if test -n "$RANLIB"; then
+  case $host_os in
+  openbsd*)
+    old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB -t \$tool_oldlib"
+    ;;
+  *)
+    old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB \$tool_oldlib"
+    ;;
+  esac
+  old_archive_cmds="$old_archive_cmds~\$RANLIB \$tool_oldlib"
+fi
+
+case $host_os in
+  darwin*)
+    lock_old_archive_extraction=yes ;;
+  *)
+    lock_old_archive_extraction=no ;;
+esac
+_LT_DECL([], [old_postinstall_cmds], [2])
+_LT_DECL([], [old_postuninstall_cmds], [2])
+_LT_TAGDECL([], [old_archive_cmds], [2],
+    [Commands used to build an old-style archive])
+_LT_DECL([], [lock_old_archive_extraction], [0],
+    [Whether to use a lock for old archive extraction])
+])# _LT_CMD_OLD_ARCHIVE
+
+
+# _LT_COMPILER_OPTION(MESSAGE, VARIABLE-NAME, FLAGS,
+#		[OUTPUT-FILE], [ACTION-SUCCESS], [ACTION-FAILURE])
+# ----------------------------------------------------------------
+# Check whether the given compiler option works
+AC_DEFUN([_LT_COMPILER_OPTION],
+[m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+m4_require([_LT_DECL_SED])dnl
+AC_CACHE_CHECK([$1], [$2],
+  [$2=no
+   m4_if([$4], , [ac_outfile=conftest.$ac_objext], [ac_outfile=$4])
+   echo "$lt_simple_compile_test_code" > conftest.$ac_ext
+   lt_compiler_flag="$3"
+   # Insert the option either (1) after the last *FLAGS variable, or
+   # (2) before a word containing "conftest.", or (3) at the end.
+   # Note that $ac_compile itself does not contain backslashes and begins
+   # with a dollar sign (not a hyphen), so the echo should work correctly.
+   # The option is referenced via a variable to avoid confusing sed.
+   lt_compile=`echo "$ac_compile" | $SED \
+   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
+   -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \
+   -e 's:$: $lt_compiler_flag:'`
+   (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&AS_MESSAGE_LOG_FD)
+   (eval "$lt_compile" 2>conftest.err)
+   ac_status=$?
+   cat conftest.err >&AS_MESSAGE_LOG_FD
+   echo "$as_me:$LINENO: \$? = $ac_status" >&AS_MESSAGE_LOG_FD
+   if (exit $ac_status) && test -s "$ac_outfile"; then
+     # The compiler can only warn and ignore the option if not recognized
+     # So say no if there are warnings other than the usual output.
+     $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' >conftest.exp
+     $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
+     if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then
+       $2=yes
+     fi
+   fi
+   $RM conftest*
+])
+
+if test x"[$]$2" = xyes; then
+    m4_if([$5], , :, [$5])
+else
+    m4_if([$6], , :, [$6])
+fi
+])# _LT_COMPILER_OPTION
+
+# Old name:
+AU_ALIAS([AC_LIBTOOL_COMPILER_OPTION], [_LT_COMPILER_OPTION])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_LIBTOOL_COMPILER_OPTION], [])
+
+
+# _LT_LINKER_OPTION(MESSAGE, VARIABLE-NAME, FLAGS,
+#                  [ACTION-SUCCESS], [ACTION-FAILURE])
+# ----------------------------------------------------
+# Check whether the given linker option works
+AC_DEFUN([_LT_LINKER_OPTION],
+[m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+m4_require([_LT_DECL_SED])dnl
+AC_CACHE_CHECK([$1], [$2],
+  [$2=no
+   save_LDFLAGS="$LDFLAGS"
+   LDFLAGS="$LDFLAGS $3"
+   echo "$lt_simple_link_test_code" > conftest.$ac_ext
+   if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then
+     # The linker can only warn and ignore the option if not recognized
+     # So say no if there are warnings
+     if test -s conftest.err; then
+       # Append any errors to the config.log.
+       cat conftest.err 1>&AS_MESSAGE_LOG_FD
+       $ECHO "$_lt_linker_boilerplate" | $SED '/^$/d' > conftest.exp
+       $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
+       if diff conftest.exp conftest.er2 >/dev/null; then
+         $2=yes
+       fi
+     else
+       $2=yes
+     fi
+   fi
+   $RM -r conftest*
+   LDFLAGS="$save_LDFLAGS"
+])
+
+if test x"[$]$2" = xyes; then
+    m4_if([$4], , :, [$4])
+else
+    m4_if([$5], , :, [$5])
+fi
+])# _LT_LINKER_OPTION
+
+# Old name:
+AU_ALIAS([AC_LIBTOOL_LINKER_OPTION], [_LT_LINKER_OPTION])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_LIBTOOL_LINKER_OPTION], [])
+
+
+# LT_CMD_MAX_LEN
+#---------------
+AC_DEFUN([LT_CMD_MAX_LEN],
+[AC_REQUIRE([AC_CANONICAL_HOST])dnl
+# find the maximum length of command line arguments
+AC_MSG_CHECKING([the maximum length of command line arguments])
+AC_CACHE_VAL([lt_cv_sys_max_cmd_len], [dnl
+  i=0
+  teststring="ABCD"
+
+  case $build_os in
+  msdosdjgpp*)
+    # On DJGPP, this test can blow up pretty badly due to problems in libc
+    # (any single argument exceeding 2000 bytes causes a buffer overrun
+    # during glob expansion).  Even if it were fixed, the result of this
+    # check would be larger than it should be.
+    lt_cv_sys_max_cmd_len=12288;    # 12K is about right
+    ;;
+
+  gnu*)
+    # Under GNU Hurd, this test is not required because there is
+    # no limit to the length of command line arguments.
+    # Libtool will interpret -1 as no limit whatsoever
+    lt_cv_sys_max_cmd_len=-1;
+    ;;
+
+  cygwin* | mingw* | cegcc*)
+    # On Win9x/ME, this test blows up -- it succeeds, but takes
+    # about 5 minutes as the teststring grows exponentially.
+    # Worse, since 9x/ME are not pre-emptively multitasking,
+    # you end up with a "frozen" computer, even though with patience
+    # the test eventually succeeds (with a max line length of 256k).
+    # Instead, let's just punt: use the minimum linelength reported by
+    # all of the supported platforms: 8192 (on NT/2K/XP).
+    lt_cv_sys_max_cmd_len=8192;
+    ;;
+
+  mint*)
+    # On MiNT this can take a long time and run out of memory.
+    lt_cv_sys_max_cmd_len=8192;
+    ;;
+
+  amigaos*)
+    # On AmigaOS with pdksh, this test takes hours, literally.
+    # So we just punt and use a minimum line length of 8192.
+    lt_cv_sys_max_cmd_len=8192;
+    ;;
+
+  netbsd* | freebsd* | openbsd* | darwin* | dragonfly*)
+    # This has been around since 386BSD, at least.  Likely further.
+    if test -x /sbin/sysctl; then
+      lt_cv_sys_max_cmd_len=`/sbin/sysctl -n kern.argmax`
+    elif test -x /usr/sbin/sysctl; then
+      lt_cv_sys_max_cmd_len=`/usr/sbin/sysctl -n kern.argmax`
+    else
+      lt_cv_sys_max_cmd_len=65536	# usable default for all BSDs
+    fi
+    # And add a safety zone
+    lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4`
+    lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3`
+    ;;
+
+  interix*)
+    # We know the value 262144 and hardcode it with a safety zone (like BSD)
+    lt_cv_sys_max_cmd_len=196608
+    ;;
+
+  os2*)
+    # The test takes a long time on OS/2.
+    lt_cv_sys_max_cmd_len=8192
+    ;;
+
+  osf*)
+    # Dr. Hans Ekkehard Plesser reports seeing a kernel panic running configure
+    # due to this test when exec_disable_arg_limit is 1 on Tru64. It is not
+    # nice to cause kernel panics so lets avoid the loop below.
+    # First set a reasonable default.
+    lt_cv_sys_max_cmd_len=16384
+    #
+    if test -x /sbin/sysconfig; then
+      case `/sbin/sysconfig -q proc exec_disable_arg_limit` in
+        *1*) lt_cv_sys_max_cmd_len=-1 ;;
+      esac
+    fi
+    ;;
+  sco3.2v5*)
+    lt_cv_sys_max_cmd_len=102400
+    ;;
+  sysv5* | sco5v6* | sysv4.2uw2*)
+    kargmax=`grep ARG_MAX /etc/conf/cf.d/stune 2>/dev/null`
+    if test -n "$kargmax"; then
+      lt_cv_sys_max_cmd_len=`echo $kargmax | sed 's/.*[[	 ]]//'`
+    else
+      lt_cv_sys_max_cmd_len=32768
+    fi
+    ;;
+  *)
+    lt_cv_sys_max_cmd_len=`(getconf ARG_MAX) 2> /dev/null`
+    if test -n "$lt_cv_sys_max_cmd_len"; then
+      lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4`
+      lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3`
+    else
+      # Make teststring a little bigger before we do anything with it.
+      # a 1K string should be a reasonable start.
+      for i in 1 2 3 4 5 6 7 8 ; do
+        teststring=$teststring$teststring
+      done
+      SHELL=${SHELL-${CONFIG_SHELL-/bin/sh}}
+      # If test is not a shell built-in, we'll probably end up computing a
+      # maximum length that is only half of the actual maximum length, but
+      # we can't tell.
+      while { test "X"`env echo "$teststring$teststring" 2>/dev/null` \
+	         = "X$teststring$teststring"; } >/dev/null 2>&1 &&
+	      test $i != 17 # 1/2 MB should be enough
+      do
+        i=`expr $i + 1`
+        teststring=$teststring$teststring
+      done
+      # Only check the string length outside the loop.
+      lt_cv_sys_max_cmd_len=`expr "X$teststring" : ".*" 2>&1`
+      teststring=
+      # Add a significant safety factor because C++ compilers can tack on
+      # massive amounts of additional arguments before passing them to the
+      # linker.  It appears as though 1/2 is a usable value.
+      lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 2`
+    fi
+    ;;
+  esac
+])
+if test -n $lt_cv_sys_max_cmd_len ; then
+  AC_MSG_RESULT($lt_cv_sys_max_cmd_len)
+else
+  AC_MSG_RESULT(none)
+fi
+max_cmd_len=$lt_cv_sys_max_cmd_len
+_LT_DECL([], [max_cmd_len], [0],
+    [What is the maximum length of a command?])
+])# LT_CMD_MAX_LEN
+
+# Old name:
+AU_ALIAS([AC_LIBTOOL_SYS_MAX_CMD_LEN], [LT_CMD_MAX_LEN])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_LIBTOOL_SYS_MAX_CMD_LEN], [])
+
+
+# _LT_HEADER_DLFCN
+# ----------------
+m4_defun([_LT_HEADER_DLFCN],
+[AC_CHECK_HEADERS([dlfcn.h], [], [], [AC_INCLUDES_DEFAULT])dnl
+])# _LT_HEADER_DLFCN
+
+
+# _LT_TRY_DLOPEN_SELF (ACTION-IF-TRUE, ACTION-IF-TRUE-W-USCORE,
+#                      ACTION-IF-FALSE, ACTION-IF-CROSS-COMPILING)
+# ----------------------------------------------------------------
+m4_defun([_LT_TRY_DLOPEN_SELF],
+[m4_require([_LT_HEADER_DLFCN])dnl
+if test "$cross_compiling" = yes; then :
+  [$4]
+else
+  lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2
+  lt_status=$lt_dlunknown
+  cat > conftest.$ac_ext <<_LT_EOF
+[#line $LINENO "configure"
+#include "confdefs.h"
+
+#if HAVE_DLFCN_H
+#include <dlfcn.h>
+#endif
+
+#include <stdio.h>
+
+#ifdef RTLD_GLOBAL
+#  define LT_DLGLOBAL		RTLD_GLOBAL
+#else
+#  ifdef DL_GLOBAL
+#    define LT_DLGLOBAL		DL_GLOBAL
+#  else
+#    define LT_DLGLOBAL		0
+#  endif
+#endif
+
+/* We may have to define LT_DLLAZY_OR_NOW in the command line if we
+   find out it does not work in some platform. */
+#ifndef LT_DLLAZY_OR_NOW
+#  ifdef RTLD_LAZY
+#    define LT_DLLAZY_OR_NOW		RTLD_LAZY
+#  else
+#    ifdef DL_LAZY
+#      define LT_DLLAZY_OR_NOW		DL_LAZY
+#    else
+#      ifdef RTLD_NOW
+#        define LT_DLLAZY_OR_NOW	RTLD_NOW
+#      else
+#        ifdef DL_NOW
+#          define LT_DLLAZY_OR_NOW	DL_NOW
+#        else
+#          define LT_DLLAZY_OR_NOW	0
+#        endif
+#      endif
+#    endif
+#  endif
+#endif
+
+/* When -fvisbility=hidden is used, assume the code has been annotated
+   correspondingly for the symbols needed.  */
+#if defined(__GNUC__) && (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3))
+int fnord () __attribute__((visibility("default")));
+#endif
+
+int fnord () { return 42; }
+int main ()
+{
+  void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW);
+  int status = $lt_dlunknown;
+
+  if (self)
+    {
+      if (dlsym (self,"fnord"))       status = $lt_dlno_uscore;
+      else
+        {
+	  if (dlsym( self,"_fnord"))  status = $lt_dlneed_uscore;
+          else puts (dlerror ());
+	}
+      /* dlclose (self); */
+    }
+  else
+    puts (dlerror ());
+
+  return status;
+}]
+_LT_EOF
+  if AC_TRY_EVAL(ac_link) && test -s conftest${ac_exeext} 2>/dev/null; then
+    (./conftest; exit; ) >&AS_MESSAGE_LOG_FD 2>/dev/null
+    lt_status=$?
+    case x$lt_status in
+      x$lt_dlno_uscore) $1 ;;
+      x$lt_dlneed_uscore) $2 ;;
+      x$lt_dlunknown|x*) $3 ;;
+    esac
+  else :
+    # compilation failed
+    $3
+  fi
+fi
+rm -fr conftest*
+])# _LT_TRY_DLOPEN_SELF
+
+
+# LT_SYS_DLOPEN_SELF
+# ------------------
+AC_DEFUN([LT_SYS_DLOPEN_SELF],
+[m4_require([_LT_HEADER_DLFCN])dnl
+if test "x$enable_dlopen" != xyes; then
+  enable_dlopen=unknown
+  enable_dlopen_self=unknown
+  enable_dlopen_self_static=unknown
+else
+  lt_cv_dlopen=no
+  lt_cv_dlopen_libs=
+
+  case $host_os in
+  beos*)
+    lt_cv_dlopen="load_add_on"
+    lt_cv_dlopen_libs=
+    lt_cv_dlopen_self=yes
+    ;;
+
+  mingw* | pw32* | cegcc*)
+    lt_cv_dlopen="LoadLibrary"
+    lt_cv_dlopen_libs=
+    ;;
+
+  cygwin*)
+    lt_cv_dlopen="dlopen"
+    lt_cv_dlopen_libs=
+    ;;
+
+  darwin*)
+  # if libdl is installed we need to link against it
+    AC_CHECK_LIB([dl], [dlopen],
+		[lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"],[
+    lt_cv_dlopen="dyld"
+    lt_cv_dlopen_libs=
+    lt_cv_dlopen_self=yes
+    ])
+    ;;
+
+  *)
+    AC_CHECK_FUNC([shl_load],
+	  [lt_cv_dlopen="shl_load"],
+      [AC_CHECK_LIB([dld], [shl_load],
+	    [lt_cv_dlopen="shl_load" lt_cv_dlopen_libs="-ldld"],
+	[AC_CHECK_FUNC([dlopen],
+	      [lt_cv_dlopen="dlopen"],
+	  [AC_CHECK_LIB([dl], [dlopen],
+		[lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"],
+	    [AC_CHECK_LIB([svld], [dlopen],
+		  [lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-lsvld"],
+	      [AC_CHECK_LIB([dld], [dld_link],
+		    [lt_cv_dlopen="dld_link" lt_cv_dlopen_libs="-ldld"])
+	      ])
+	    ])
+	  ])
+	])
+      ])
+    ;;
+  esac
+
+  if test "x$lt_cv_dlopen" != xno; then
+    enable_dlopen=yes
+  else
+    enable_dlopen=no
+  fi
+
+  case $lt_cv_dlopen in
+  dlopen)
+    save_CPPFLAGS="$CPPFLAGS"
+    test "x$ac_cv_header_dlfcn_h" = xyes && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H"
+
+    save_LDFLAGS="$LDFLAGS"
+    wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\"
+
+    save_LIBS="$LIBS"
+    LIBS="$lt_cv_dlopen_libs $LIBS"
+
+    AC_CACHE_CHECK([whether a program can dlopen itself],
+	  lt_cv_dlopen_self, [dnl
+	  _LT_TRY_DLOPEN_SELF(
+	    lt_cv_dlopen_self=yes, lt_cv_dlopen_self=yes,
+	    lt_cv_dlopen_self=no, lt_cv_dlopen_self=cross)
+    ])
+
+    if test "x$lt_cv_dlopen_self" = xyes; then
+      wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $lt_prog_compiler_static\"
+      AC_CACHE_CHECK([whether a statically linked program can dlopen itself],
+	  lt_cv_dlopen_self_static, [dnl
+	  _LT_TRY_DLOPEN_SELF(
+	    lt_cv_dlopen_self_static=yes, lt_cv_dlopen_self_static=yes,
+	    lt_cv_dlopen_self_static=no,  lt_cv_dlopen_self_static=cross)
+      ])
+    fi
+
+    CPPFLAGS="$save_CPPFLAGS"
+    LDFLAGS="$save_LDFLAGS"
+    LIBS="$save_LIBS"
+    ;;
+  esac
+
+  case $lt_cv_dlopen_self in
+  yes|no) enable_dlopen_self=$lt_cv_dlopen_self ;;
+  *) enable_dlopen_self=unknown ;;
+  esac
+
+  case $lt_cv_dlopen_self_static in
+  yes|no) enable_dlopen_self_static=$lt_cv_dlopen_self_static ;;
+  *) enable_dlopen_self_static=unknown ;;
+  esac
+fi
+_LT_DECL([dlopen_support], [enable_dlopen], [0],
+	 [Whether dlopen is supported])
+_LT_DECL([dlopen_self], [enable_dlopen_self], [0],
+	 [Whether dlopen of programs is supported])
+_LT_DECL([dlopen_self_static], [enable_dlopen_self_static], [0],
+	 [Whether dlopen of statically linked programs is supported])
+])# LT_SYS_DLOPEN_SELF
+
+# Old name:
+AU_ALIAS([AC_LIBTOOL_DLOPEN_SELF], [LT_SYS_DLOPEN_SELF])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_LIBTOOL_DLOPEN_SELF], [])
+
+
+# _LT_COMPILER_C_O([TAGNAME])
+# ---------------------------
+# Check to see if options -c and -o are simultaneously supported by compiler.
+# This macro does not hard code the compiler like AC_PROG_CC_C_O.
+m4_defun([_LT_COMPILER_C_O],
+[m4_require([_LT_DECL_SED])dnl
+m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+m4_require([_LT_TAG_COMPILER])dnl
+AC_CACHE_CHECK([if $compiler supports -c -o file.$ac_objext],
+  [_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)],
+  [_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=no
+   $RM -r conftest 2>/dev/null
+   mkdir conftest
+   cd conftest
+   mkdir out
+   echo "$lt_simple_compile_test_code" > conftest.$ac_ext
+
+   lt_compiler_flag="-o out/conftest2.$ac_objext"
+   # Insert the option either (1) after the last *FLAGS variable, or
+   # (2) before a word containing "conftest.", or (3) at the end.
+   # Note that $ac_compile itself does not contain backslashes and begins
+   # with a dollar sign (not a hyphen), so the echo should work correctly.
+   lt_compile=`echo "$ac_compile" | $SED \
+   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
+   -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \
+   -e 's:$: $lt_compiler_flag:'`
+   (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&AS_MESSAGE_LOG_FD)
+   (eval "$lt_compile" 2>out/conftest.err)
+   ac_status=$?
+   cat out/conftest.err >&AS_MESSAGE_LOG_FD
+   echo "$as_me:$LINENO: \$? = $ac_status" >&AS_MESSAGE_LOG_FD
+   if (exit $ac_status) && test -s out/conftest2.$ac_objext
+   then
+     # The compiler can only warn and ignore the option if not recognized
+     # So say no if there are warnings
+     $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' > out/conftest.exp
+     $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2
+     if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then
+       _LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=yes
+     fi
+   fi
+   chmod u+w . 2>&AS_MESSAGE_LOG_FD
+   $RM conftest*
+   # SGI C++ compiler will create directory out/ii_files/ for
+   # template instantiation
+   test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files
+   $RM out/* && rmdir out
+   cd ..
+   $RM -r conftest
+   $RM conftest*
+])
+_LT_TAGDECL([compiler_c_o], [lt_cv_prog_compiler_c_o], [1],
+	[Does compiler simultaneously support -c and -o options?])
+])# _LT_COMPILER_C_O
+
+
+# _LT_COMPILER_FILE_LOCKS([TAGNAME])
+# ----------------------------------
+# Check to see if we can do hard links to lock some files if needed
+m4_defun([_LT_COMPILER_FILE_LOCKS],
+[m4_require([_LT_ENABLE_LOCK])dnl
+m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+_LT_COMPILER_C_O([$1])
+
+hard_links="nottested"
+if test "$_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)" = no && test "$need_locks" != no; then
+  # do not overwrite the value of need_locks provided by the user
+  AC_MSG_CHECKING([if we can lock with hard links])
+  hard_links=yes
+  $RM conftest*
+  ln conftest.a conftest.b 2>/dev/null && hard_links=no
+  touch conftest.a
+  ln conftest.a conftest.b 2>&5 || hard_links=no
+  ln conftest.a conftest.b 2>/dev/null && hard_links=no
+  AC_MSG_RESULT([$hard_links])
+  if test "$hard_links" = no; then
+    AC_MSG_WARN([`$CC' does not support `-c -o', so `make -j' may be unsafe])
+    need_locks=warn
+  fi
+else
+  need_locks=no
+fi
+_LT_DECL([], [need_locks], [1], [Must we lock files when doing compilation?])
+])# _LT_COMPILER_FILE_LOCKS
+
+
+# _LT_CHECK_OBJDIR
+# ----------------
+m4_defun([_LT_CHECK_OBJDIR],
+[AC_CACHE_CHECK([for objdir], [lt_cv_objdir],
+[rm -f .libs 2>/dev/null
+mkdir .libs 2>/dev/null
+if test -d .libs; then
+  lt_cv_objdir=.libs
+else
+  # MS-DOS does not allow filenames that begin with a dot.
+  lt_cv_objdir=_libs
+fi
+rmdir .libs 2>/dev/null])
+objdir=$lt_cv_objdir
+_LT_DECL([], [objdir], [0],
+         [The name of the directory that contains temporary libtool files])dnl
+m4_pattern_allow([LT_OBJDIR])dnl
+AC_DEFINE_UNQUOTED(LT_OBJDIR, "$lt_cv_objdir/",
+  [Define to the sub-directory in which libtool stores uninstalled libraries.])
+])# _LT_CHECK_OBJDIR
+
+
+# _LT_LINKER_HARDCODE_LIBPATH([TAGNAME])
+# --------------------------------------
+# Check hardcoding attributes.
+m4_defun([_LT_LINKER_HARDCODE_LIBPATH],
+[AC_MSG_CHECKING([how to hardcode library paths into programs])
+_LT_TAGVAR(hardcode_action, $1)=
+if test -n "$_LT_TAGVAR(hardcode_libdir_flag_spec, $1)" ||
+   test -n "$_LT_TAGVAR(runpath_var, $1)" ||
+   test "X$_LT_TAGVAR(hardcode_automatic, $1)" = "Xyes" ; then
+
+  # We can hardcode non-existent directories.
+  if test "$_LT_TAGVAR(hardcode_direct, $1)" != no &&
+     # If the only mechanism to avoid hardcoding is shlibpath_var, we
+     # have to relink, otherwise we might link with an installed library
+     # when we should be linking with a yet-to-be-installed one
+     ## test "$_LT_TAGVAR(hardcode_shlibpath_var, $1)" != no &&
+     test "$_LT_TAGVAR(hardcode_minus_L, $1)" != no; then
+    # Linking always hardcodes the temporary library directory.
+    _LT_TAGVAR(hardcode_action, $1)=relink
+  else
+    # We can link without hardcoding, and we can hardcode nonexisting dirs.
+    _LT_TAGVAR(hardcode_action, $1)=immediate
+  fi
+else
+  # We cannot hardcode anything, or else we can only hardcode existing
+  # directories.
+  _LT_TAGVAR(hardcode_action, $1)=unsupported
+fi
+AC_MSG_RESULT([$_LT_TAGVAR(hardcode_action, $1)])
+
+if test "$_LT_TAGVAR(hardcode_action, $1)" = relink ||
+   test "$_LT_TAGVAR(inherit_rpath, $1)" = yes; then
+  # Fast installation is not supported
+  enable_fast_install=no
+elif test "$shlibpath_overrides_runpath" = yes ||
+     test "$enable_shared" = no; then
+  # Fast installation is not necessary
+  enable_fast_install=needless
+fi
+_LT_TAGDECL([], [hardcode_action], [0],
+    [How to hardcode a shared library path into an executable])
+])# _LT_LINKER_HARDCODE_LIBPATH
+
+
+# _LT_CMD_STRIPLIB
+# ----------------
+m4_defun([_LT_CMD_STRIPLIB],
+[m4_require([_LT_DECL_EGREP])
+striplib=
+old_striplib=
+AC_MSG_CHECKING([whether stripping libraries is possible])
+if test -n "$STRIP" && $STRIP -V 2>&1 | $GREP "GNU strip" >/dev/null; then
+  test -z "$old_striplib" && old_striplib="$STRIP --strip-debug"
+  test -z "$striplib" && striplib="$STRIP --strip-unneeded"
+  AC_MSG_RESULT([yes])
+else
+# FIXME - insert some real tests, host_os isn't really good enough
+  case $host_os in
+  darwin*)
+    if test -n "$STRIP" ; then
+      striplib="$STRIP -x"
+      old_striplib="$STRIP -S"
+      AC_MSG_RESULT([yes])
+    else
+      AC_MSG_RESULT([no])
+    fi
+    ;;
+  *)
+    AC_MSG_RESULT([no])
+    ;;
+  esac
+fi
+_LT_DECL([], [old_striplib], [1], [Commands to strip libraries])
+_LT_DECL([], [striplib], [1])
+])# _LT_CMD_STRIPLIB
+
+
+# _LT_SYS_DYNAMIC_LINKER([TAG])
+# -----------------------------
+# PORTME Fill in your ld.so characteristics
+m4_defun([_LT_SYS_DYNAMIC_LINKER],
+[AC_REQUIRE([AC_CANONICAL_HOST])dnl
+m4_require([_LT_DECL_EGREP])dnl
+m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+m4_require([_LT_DECL_OBJDUMP])dnl
+m4_require([_LT_DECL_SED])dnl
+m4_require([_LT_CHECK_SHELL_FEATURES])dnl
+AC_MSG_CHECKING([dynamic linker characteristics])
+m4_if([$1],
+	[], [
+if test "$GCC" = yes; then
+  case $host_os in
+    darwin*) lt_awk_arg="/^libraries:/,/LR/" ;;
+    *) lt_awk_arg="/^libraries:/" ;;
+  esac
+  case $host_os in
+    mingw* | cegcc*) lt_sed_strip_eq="s,=\([[A-Za-z]]:\),\1,g" ;;
+    *) lt_sed_strip_eq="s,=/,/,g" ;;
+  esac
+  lt_search_path_spec=`$CC -print-search-dirs | awk $lt_awk_arg | $SED -e "s/^libraries://" -e $lt_sed_strip_eq`
+  case $lt_search_path_spec in
+  *\;*)
+    # if the path contains ";" then we assume it to be the separator
+    # otherwise default to the standard path separator (i.e. ":") - it is
+    # assumed that no part of a normal pathname contains ";" but that should
+    # okay in the real world where ";" in dirpaths is itself problematic.
+    lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED 's/;/ /g'`
+    ;;
+  *)
+    lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED "s/$PATH_SEPARATOR/ /g"`
+    ;;
+  esac
+  # Ok, now we have the path, separated by spaces, we can step through it
+  # and add multilib dir if necessary.
+  lt_tmp_lt_search_path_spec=
+  lt_multi_os_dir=`$CC $CPPFLAGS $CFLAGS $LDFLAGS -print-multi-os-directory 2>/dev/null`
+  for lt_sys_path in $lt_search_path_spec; do
+    if test -d "$lt_sys_path/$lt_multi_os_dir"; then
+      lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path/$lt_multi_os_dir"
+    else
+      test -d "$lt_sys_path" && \
+	lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path"
+    fi
+  done
+  lt_search_path_spec=`$ECHO "$lt_tmp_lt_search_path_spec" | awk '
+BEGIN {RS=" "; FS="/|\n";} {
+  lt_foo="";
+  lt_count=0;
+  for (lt_i = NF; lt_i > 0; lt_i--) {
+    if ($lt_i != "" && $lt_i != ".") {
+      if ($lt_i == "..") {
+        lt_count++;
+      } else {
+        if (lt_count == 0) {
+          lt_foo="/" $lt_i lt_foo;
+        } else {
+          lt_count--;
+        }
+      }
+    }
+  }
+  if (lt_foo != "") { lt_freq[[lt_foo]]++; }
+  if (lt_freq[[lt_foo]] == 1) { print lt_foo; }
+}'`
+  # AWK program above erroneously prepends '/' to C:/dos/paths
+  # for these hosts.
+  case $host_os in
+    mingw* | cegcc*) lt_search_path_spec=`$ECHO "$lt_search_path_spec" |\
+      $SED 's,/\([[A-Za-z]]:\),\1,g'` ;;
+  esac
+  sys_lib_search_path_spec=`$ECHO "$lt_search_path_spec" | $lt_NL2SP`
+else
+  sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib"
+fi])
+library_names_spec=
+libname_spec='lib$name'
+soname_spec=
+shrext_cmds=".so"
+postinstall_cmds=
+postuninstall_cmds=
+finish_cmds=
+finish_eval=
+shlibpath_var=
+shlibpath_overrides_runpath=unknown
+version_type=none
+dynamic_linker="$host_os ld.so"
+sys_lib_dlsearch_path_spec="/lib /usr/lib"
+need_lib_prefix=unknown
+hardcode_into_libs=no
+
+# when you set need_version to no, make sure it does not cause -set_version
+# flags to be left without arguments
+need_version=unknown
+
+case $host_os in
+aix3*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a'
+  shlibpath_var=LIBPATH
+
+  # AIX 3 has no versioning support, so we append a major version to the name.
+  soname_spec='${libname}${release}${shared_ext}$major'
+  ;;
+
+aix[[4-9]]*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_lib_prefix=no
+  need_version=no
+  hardcode_into_libs=yes
+  if test "$host_cpu" = ia64; then
+    # AIX 5 supports IA64
+    library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}'
+    shlibpath_var=LD_LIBRARY_PATH
+  else
+    # With GCC up to 2.95.x, collect2 would create an import file
+    # for dependence libraries.  The import file would start with
+    # the line `#! .'.  This would cause the generated library to
+    # depend on `.', always an invalid library.  This was fixed in
+    # development snapshots of GCC prior to 3.0.
+    case $host_os in
+      aix4 | aix4.[[01]] | aix4.[[01]].*)
+      if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)'
+	   echo ' yes '
+	   echo '#endif'; } | ${CC} -E - | $GREP yes > /dev/null; then
+	:
+      else
+	can_build_shared=no
+      fi
+      ;;
+    esac
+    # AIX (on Power*) has no versioning support, so currently we can not hardcode correct
+    # soname into executable. Probably we can add versioning support to
+    # collect2, so additional links can be useful in future.
+    if test "$aix_use_runtimelinking" = yes; then
+      # If using run time linking (on AIX 4.2 or later) use lib<name>.so
+      # instead of lib<name>.a to let people know that these are not
+      # typical AIX shared libraries.
+      library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+    else
+      # We preserve .a as extension for shared libraries through AIX4.2
+      # and later when we are not doing run time linking.
+      library_names_spec='${libname}${release}.a $libname.a'
+      soname_spec='${libname}${release}${shared_ext}$major'
+    fi
+    shlibpath_var=LIBPATH
+  fi
+  ;;
+
+amigaos*)
+  case $host_cpu in
+  powerpc)
+    # Since July 2007 AmigaOS4 officially supports .so libraries.
+    # When compiling the executable, add -use-dynld -Lsobjs: to the compileline.
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+    ;;
+  m68k)
+    library_names_spec='$libname.ixlibrary $libname.a'
+    # Create ${libname}_ixlibrary.a entries in /sys/libs.
+    finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`func_echo_all "$lib" | $SED '\''s%^.*/\([[^/]]*\)\.ixlibrary$%\1%'\''`; test $RM /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done'
+    ;;
+  esac
+  ;;
+
+beos*)
+  library_names_spec='${libname}${shared_ext}'
+  dynamic_linker="$host_os ld.so"
+  shlibpath_var=LIBRARY_PATH
+  ;;
+
+bsdi[[45]]*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir'
+  shlibpath_var=LD_LIBRARY_PATH
+  sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib"
+  sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib"
+  # the default ld.so.conf also contains /usr/contrib/lib and
+  # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow
+  # libtool to hard-code these into programs
+  ;;
+
+cygwin* | mingw* | pw32* | cegcc*)
+  version_type=windows
+  shrext_cmds=".dll"
+  need_version=no
+  need_lib_prefix=no
+
+  case $GCC,$cc_basename in
+  yes,*)
+    # gcc
+    library_names_spec='$libname.dll.a'
+    # DLL is installed to $(libdir)/../bin by postinstall_cmds
+    postinstall_cmds='base_file=`basename \${file}`~
+      dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~
+      dldir=$destdir/`dirname \$dlpath`~
+      test -d \$dldir || mkdir -p \$dldir~
+      $install_prog $dir/$dlname \$dldir/$dlname~
+      chmod a+x \$dldir/$dlname~
+      if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then
+        eval '\''$striplib \$dldir/$dlname'\'' || exit \$?;
+      fi'
+    postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~
+      dlpath=$dir/\$dldll~
+       $RM \$dlpath'
+    shlibpath_overrides_runpath=yes
+
+    case $host_os in
+    cygwin*)
+      # Cygwin DLLs use 'cyg' prefix rather than 'lib'
+      soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}'
+m4_if([$1], [],[
+      sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/lib/w32api"])
+      ;;
+    mingw* | cegcc*)
+      # MinGW DLLs use traditional 'lib' prefix
+      soname_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}'
+      ;;
+    pw32*)
+      # pw32 DLLs use 'pw' prefix rather than 'lib'
+      library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}'
+      ;;
+    esac
+    dynamic_linker='Win32 ld.exe'
+    ;;
+
+  *,cl*)
+    # Native MSVC
+    libname_spec='$name'
+    soname_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}'
+    library_names_spec='${libname}.dll.lib'
+
+    case $build_os in
+    mingw*)
+      sys_lib_search_path_spec=
+      lt_save_ifs=$IFS
+      IFS=';'
+      for lt_path in $LIB
+      do
+        IFS=$lt_save_ifs
+        # Let DOS variable expansion print the short 8.3 style file name.
+        lt_path=`cd "$lt_path" 2>/dev/null && cmd //C "for %i in (".") do @echo %~si"`
+        sys_lib_search_path_spec="$sys_lib_search_path_spec $lt_path"
+      done
+      IFS=$lt_save_ifs
+      # Convert to MSYS style.
+      sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | sed -e 's|\\\\|/|g' -e 's| \\([[a-zA-Z]]\\):| /\\1|g' -e 's|^ ||'`
+      ;;
+    cygwin*)
+      # Convert to unix form, then to dos form, then back to unix form
+      # but this time dos style (no spaces!) so that the unix form looks
+      # like /cygdrive/c/PROGRA~1:/cygdr...
+      sys_lib_search_path_spec=`cygpath --path --unix "$LIB"`
+      sys_lib_search_path_spec=`cygpath --path --dos "$sys_lib_search_path_spec" 2>/dev/null`
+      sys_lib_search_path_spec=`cygpath --path --unix "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"`
+      ;;
+    *)
+      sys_lib_search_path_spec="$LIB"
+      if $ECHO "$sys_lib_search_path_spec" | [$GREP ';[c-zC-Z]:/' >/dev/null]; then
+        # It is most probably a Windows format PATH.
+        sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'`
+      else
+        sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"`
+      fi
+      # FIXME: find the short name or the path components, as spaces are
+      # common. (e.g. "Program Files" -> "PROGRA~1")
+      ;;
+    esac
+
+    # DLL is installed to $(libdir)/../bin by postinstall_cmds
+    postinstall_cmds='base_file=`basename \${file}`~
+      dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~
+      dldir=$destdir/`dirname \$dlpath`~
+      test -d \$dldir || mkdir -p \$dldir~
+      $install_prog $dir/$dlname \$dldir/$dlname'
+    postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~
+      dlpath=$dir/\$dldll~
+       $RM \$dlpath'
+    shlibpath_overrides_runpath=yes
+    dynamic_linker='Win32 link.exe'
+    ;;
+
+  *)
+    # Assume MSVC wrapper
+    library_names_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext} $libname.lib'
+    dynamic_linker='Win32 ld.exe'
+    ;;
+  esac
+  # FIXME: first we should search . and the directory the executable is in
+  shlibpath_var=PATH
+  ;;
+
+darwin* | rhapsody*)
+  dynamic_linker="$host_os dyld"
+  version_type=darwin
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${major}$shared_ext ${libname}$shared_ext'
+  soname_spec='${libname}${release}${major}$shared_ext'
+  shlibpath_overrides_runpath=yes
+  shlibpath_var=DYLD_LIBRARY_PATH
+  shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`'
+m4_if([$1], [],[
+  sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/local/lib"])
+  sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib'
+  ;;
+
+dgux*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  ;;
+
+freebsd* | dragonfly*)
+  # DragonFly does not have aout.  When/if they implement a new
+  # versioning mechanism, adjust this.
+  if test -x /usr/bin/objformat; then
+    objformat=`/usr/bin/objformat`
+  else
+    case $host_os in
+    freebsd[[23]].*) objformat=aout ;;
+    *) objformat=elf ;;
+    esac
+  fi
+  version_type=freebsd-$objformat
+  case $version_type in
+    freebsd-elf*)
+      library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
+      need_version=no
+      need_lib_prefix=no
+      ;;
+    freebsd-*)
+      library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix'
+      need_version=yes
+      ;;
+  esac
+  shlibpath_var=LD_LIBRARY_PATH
+  case $host_os in
+  freebsd2.*)
+    shlibpath_overrides_runpath=yes
+    ;;
+  freebsd3.[[01]]* | freebsdelf3.[[01]]*)
+    shlibpath_overrides_runpath=yes
+    hardcode_into_libs=yes
+    ;;
+  freebsd3.[[2-9]]* | freebsdelf3.[[2-9]]* | \
+  freebsd4.[[0-5]] | freebsdelf4.[[0-5]] | freebsd4.1.1 | freebsdelf4.1.1)
+    shlibpath_overrides_runpath=no
+    hardcode_into_libs=yes
+    ;;
+  *) # from 4.6 on, and DragonFly
+    shlibpath_overrides_runpath=yes
+    hardcode_into_libs=yes
+    ;;
+  esac
+  ;;
+
+gnu*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=no
+  hardcode_into_libs=yes
+  ;;
+
+haiku*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_lib_prefix=no
+  need_version=no
+  dynamic_linker="$host_os runtime_loader"
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  sys_lib_dlsearch_path_spec='/boot/home/config/lib /boot/common/lib /boot/system/lib'
+  hardcode_into_libs=yes
+  ;;
+
+hpux9* | hpux10* | hpux11*)
+  # Give a soname corresponding to the major version so that dld.sl refuses to
+  # link against other versions.
+  version_type=sunos
+  need_lib_prefix=no
+  need_version=no
+  case $host_cpu in
+  ia64*)
+    shrext_cmds='.so'
+    hardcode_into_libs=yes
+    dynamic_linker="$host_os dld.so"
+    shlibpath_var=LD_LIBRARY_PATH
+    shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+    soname_spec='${libname}${release}${shared_ext}$major'
+    if test "X$HPUX_IA64_MODE" = X32; then
+      sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib"
+    else
+      sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64"
+    fi
+    sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
+    ;;
+  hppa*64*)
+    shrext_cmds='.sl'
+    hardcode_into_libs=yes
+    dynamic_linker="$host_os dld.sl"
+    shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH
+    shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+    soname_spec='${libname}${release}${shared_ext}$major'
+    sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64"
+    sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
+    ;;
+  *)
+    shrext_cmds='.sl'
+    dynamic_linker="$host_os dld.sl"
+    shlibpath_var=SHLIB_PATH
+    shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+    soname_spec='${libname}${release}${shared_ext}$major'
+    ;;
+  esac
+  # HP-UX runs *really* slowly unless shared libraries are mode 555, ...
+  postinstall_cmds='chmod 555 $lib'
+  # or fails outright, so override atomically:
+  install_override_mode=555
+  ;;
+
+interix[[3-9]]*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=no
+  hardcode_into_libs=yes
+  ;;
+
+irix5* | irix6* | nonstopux*)
+  case $host_os in
+    nonstopux*) version_type=nonstopux ;;
+    *)
+	if test "$lt_cv_prog_gnu_ld" = yes; then
+		version_type=linux # correct to gnu/linux during the next big refactor
+	else
+		version_type=irix
+	fi ;;
+  esac
+  need_lib_prefix=no
+  need_version=no
+  soname_spec='${libname}${release}${shared_ext}$major'
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}'
+  case $host_os in
+  irix5* | nonstopux*)
+    libsuff= shlibsuff=
+    ;;
+  *)
+    case $LD in # libtool.m4 will add one of these switches to LD
+    *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ")
+      libsuff= shlibsuff= libmagic=32-bit;;
+    *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ")
+      libsuff=32 shlibsuff=N32 libmagic=N32;;
+    *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ")
+      libsuff=64 shlibsuff=64 libmagic=64-bit;;
+    *) libsuff= shlibsuff= libmagic=never-match;;
+    esac
+    ;;
+  esac
+  shlibpath_var=LD_LIBRARY${shlibsuff}_PATH
+  shlibpath_overrides_runpath=no
+  sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}"
+  sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}"
+  hardcode_into_libs=yes
+  ;;
+
+# No shared lib support for Linux oldld, aout, or coff.
+linux*oldld* | linux*aout* | linux*coff*)
+  dynamic_linker=no
+  ;;
+
+# This must be glibc/ELF.
+linux* | k*bsd*-gnu | kopensolaris*-gnu)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=no
+
+  # Some binutils ld are patched to set DT_RUNPATH
+  AC_CACHE_VAL([lt_cv_shlibpath_overrides_runpath],
+    [lt_cv_shlibpath_overrides_runpath=no
+    save_LDFLAGS=$LDFLAGS
+    save_libdir=$libdir
+    eval "libdir=/foo; wl=\"$_LT_TAGVAR(lt_prog_compiler_wl, $1)\"; \
+	 LDFLAGS=\"\$LDFLAGS $_LT_TAGVAR(hardcode_libdir_flag_spec, $1)\""
+    AC_LINK_IFELSE([AC_LANG_PROGRAM([],[])],
+      [AS_IF([ ($OBJDUMP -p conftest$ac_exeext) 2>/dev/null | grep "RUNPATH.*$libdir" >/dev/null],
+	 [lt_cv_shlibpath_overrides_runpath=yes])])
+    LDFLAGS=$save_LDFLAGS
+    libdir=$save_libdir
+    ])
+  shlibpath_overrides_runpath=$lt_cv_shlibpath_overrides_runpath
+
+  # This implies no fast_install, which is unacceptable.
+  # Some rework will be needed to allow for fast_install
+  # before this can be enabled.
+  hardcode_into_libs=yes
+
+  # Append ld.so.conf contents to the search path
+  if test -f /etc/ld.so.conf; then
+    lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \[$]2)); skip = 1; } { if (!skip) print \[$]0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;/^[	 ]*hwcap[	 ]/d;s/[:,	]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;s/"//g;/^$/d' | tr '\n' ' '`
+    sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra"
+  fi
+
+  # We used to test for /lib/ld.so.1 and disable shared libraries on
+  # powerpc, because MkLinux only supported shared libraries with the
+  # GNU dynamic linker.  Since this was broken with cross compilers,
+  # most powerpc-linux boxes support dynamic linking these days and
+  # people can always --disable-shared, the test was removed, and we
+  # assume the GNU/Linux dynamic linker is in use.
+  dynamic_linker='GNU/Linux ld.so'
+  ;;
+
+netbsd*)
+  version_type=sunos
+  need_lib_prefix=no
+  need_version=no
+  if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+    finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
+    dynamic_linker='NetBSD (a.out) ld.so'
+  else
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+    soname_spec='${libname}${release}${shared_ext}$major'
+    dynamic_linker='NetBSD ld.elf_so'
+  fi
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  hardcode_into_libs=yes
+  ;;
+
+newsos6)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  ;;
+
+*nto* | *qnx*)
+  version_type=qnx
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=no
+  hardcode_into_libs=yes
+  dynamic_linker='ldqnx.so'
+  ;;
+
+openbsd*)
+  version_type=sunos
+  sys_lib_dlsearch_path_spec="/usr/lib"
+  need_lib_prefix=no
+  # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs.
+  case $host_os in
+    openbsd3.3 | openbsd3.3.*)	need_version=yes ;;
+    *)				need_version=no  ;;
+  esac
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+  finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
+  shlibpath_var=LD_LIBRARY_PATH
+  if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+    case $host_os in
+      openbsd2.[[89]] | openbsd2.[[89]].*)
+	shlibpath_overrides_runpath=no
+	;;
+      *)
+	shlibpath_overrides_runpath=yes
+	;;
+      esac
+  else
+    shlibpath_overrides_runpath=yes
+  fi
+  ;;
+
+os2*)
+  libname_spec='$name'
+  shrext_cmds=".dll"
+  need_lib_prefix=no
+  library_names_spec='$libname${shared_ext} $libname.a'
+  dynamic_linker='OS/2 ld.exe'
+  shlibpath_var=LIBPATH
+  ;;
+
+osf3* | osf4* | osf5*)
+  version_type=osf
+  need_lib_prefix=no
+  need_version=no
+  soname_spec='${libname}${release}${shared_ext}$major'
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  shlibpath_var=LD_LIBRARY_PATH
+  sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib"
+  sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec"
+  ;;
+
+rdos*)
+  dynamic_linker=no
+  ;;
+
+solaris*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  hardcode_into_libs=yes
+  # ldd complains unless libraries are executable
+  postinstall_cmds='chmod +x $lib'
+  ;;
+
+sunos4*)
+  version_type=sunos
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+  finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  if test "$with_gnu_ld" = yes; then
+    need_lib_prefix=no
+  fi
+  need_version=yes
+  ;;
+
+sysv4 | sysv4.3*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  case $host_vendor in
+    sni)
+      shlibpath_overrides_runpath=no
+      need_lib_prefix=no
+      runpath_var=LD_RUN_PATH
+      ;;
+    siemens)
+      need_lib_prefix=no
+      ;;
+    motorola)
+      need_lib_prefix=no
+      need_version=no
+      shlibpath_overrides_runpath=no
+      sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib'
+      ;;
+  esac
+  ;;
+
+sysv4*MP*)
+  if test -d /usr/nec ;then
+    version_type=linux # correct to gnu/linux during the next big refactor
+    library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}'
+    soname_spec='$libname${shared_ext}.$major'
+    shlibpath_var=LD_LIBRARY_PATH
+  fi
+  ;;
+
+sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
+  version_type=freebsd-elf
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  hardcode_into_libs=yes
+  if test "$with_gnu_ld" = yes; then
+    sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib'
+  else
+    sys_lib_search_path_spec='/usr/ccs/lib /usr/lib'
+    case $host_os in
+      sco3.2v5*)
+        sys_lib_search_path_spec="$sys_lib_search_path_spec /lib"
+	;;
+    esac
+  fi
+  sys_lib_dlsearch_path_spec='/usr/lib'
+  ;;
+
+tpf*)
+  # TPF is a cross-target only.  Preferred cross-host = GNU/Linux.
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=no
+  hardcode_into_libs=yes
+  ;;
+
+uts4*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  ;;
+
+*)
+  dynamic_linker=no
+  ;;
+esac
+AC_MSG_RESULT([$dynamic_linker])
+test "$dynamic_linker" = no && can_build_shared=no
+
+variables_saved_for_relink="PATH $shlibpath_var $runpath_var"
+if test "$GCC" = yes; then
+  variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH"
+fi
+
+if test "${lt_cv_sys_lib_search_path_spec+set}" = set; then
+  sys_lib_search_path_spec="$lt_cv_sys_lib_search_path_spec"
+fi
+if test "${lt_cv_sys_lib_dlsearch_path_spec+set}" = set; then
+  sys_lib_dlsearch_path_spec="$lt_cv_sys_lib_dlsearch_path_spec"
+fi
+
+_LT_DECL([], [variables_saved_for_relink], [1],
+    [Variables whose values should be saved in libtool wrapper scripts and
+    restored at link time])
+_LT_DECL([], [need_lib_prefix], [0],
+    [Do we need the "lib" prefix for modules?])
+_LT_DECL([], [need_version], [0], [Do we need a version for libraries?])
+_LT_DECL([], [version_type], [0], [Library versioning type])
+_LT_DECL([], [runpath_var], [0],  [Shared library runtime path variable])
+_LT_DECL([], [shlibpath_var], [0],[Shared library path variable])
+_LT_DECL([], [shlibpath_overrides_runpath], [0],
+    [Is shlibpath searched before the hard-coded library search path?])
+_LT_DECL([], [libname_spec], [1], [Format of library name prefix])
+_LT_DECL([], [library_names_spec], [1],
+    [[List of archive names.  First name is the real one, the rest are links.
+    The last name is the one that the linker finds with -lNAME]])
+_LT_DECL([], [soname_spec], [1],
+    [[The coded name of the library, if different from the real name]])
+_LT_DECL([], [install_override_mode], [1],
+    [Permission mode override for installation of shared libraries])
+_LT_DECL([], [postinstall_cmds], [2],
+    [Command to use after installation of a shared archive])
+_LT_DECL([], [postuninstall_cmds], [2],
+    [Command to use after uninstallation of a shared archive])
+_LT_DECL([], [finish_cmds], [2],
+    [Commands used to finish a libtool library installation in a directory])
+_LT_DECL([], [finish_eval], [1],
+    [[As "finish_cmds", except a single script fragment to be evaled but
+    not shown]])
+_LT_DECL([], [hardcode_into_libs], [0],
+    [Whether we should hardcode library paths into libraries])
+_LT_DECL([], [sys_lib_search_path_spec], [2],
+    [Compile-time system search path for libraries])
+_LT_DECL([], [sys_lib_dlsearch_path_spec], [2],
+    [Run-time system search path for libraries])
+])# _LT_SYS_DYNAMIC_LINKER
+
+
+# _LT_PATH_TOOL_PREFIX(TOOL)
+# --------------------------
+# find a file program which can recognize shared library
+AC_DEFUN([_LT_PATH_TOOL_PREFIX],
+[m4_require([_LT_DECL_EGREP])dnl
+AC_MSG_CHECKING([for $1])
+AC_CACHE_VAL(lt_cv_path_MAGIC_CMD,
+[case $MAGIC_CMD in
+[[\\/*] |  ?:[\\/]*])
+  lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path.
+  ;;
+*)
+  lt_save_MAGIC_CMD="$MAGIC_CMD"
+  lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
+dnl $ac_dummy forces splitting on constant user-supplied paths.
+dnl POSIX.2 word splitting is done only on the output of word expansions,
+dnl not every word.  This closes a longstanding sh security hole.
+  ac_dummy="m4_if([$2], , $PATH, [$2])"
+  for ac_dir in $ac_dummy; do
+    IFS="$lt_save_ifs"
+    test -z "$ac_dir" && ac_dir=.
+    if test -f $ac_dir/$1; then
+      lt_cv_path_MAGIC_CMD="$ac_dir/$1"
+      if test -n "$file_magic_test_file"; then
+	case $deplibs_check_method in
+	"file_magic "*)
+	  file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"`
+	  MAGIC_CMD="$lt_cv_path_MAGIC_CMD"
+	  if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null |
+	    $EGREP "$file_magic_regex" > /dev/null; then
+	    :
+	  else
+	    cat <<_LT_EOF 1>&2
+
+*** Warning: the command libtool uses to detect shared libraries,
+*** $file_magic_cmd, produces output that libtool cannot recognize.
+*** The result is that libtool may fail to recognize shared libraries
+*** as such.  This will affect the creation of libtool libraries that
+*** depend on shared libraries, but programs linked with such libtool
+*** libraries will work regardless of this problem.  Nevertheless, you
+*** may want to report the problem to your system manager and/or to
+*** bug-libtool at gnu.org
+
+_LT_EOF
+	  fi ;;
+	esac
+      fi
+      break
+    fi
+  done
+  IFS="$lt_save_ifs"
+  MAGIC_CMD="$lt_save_MAGIC_CMD"
+  ;;
+esac])
+MAGIC_CMD="$lt_cv_path_MAGIC_CMD"
+if test -n "$MAGIC_CMD"; then
+  AC_MSG_RESULT($MAGIC_CMD)
+else
+  AC_MSG_RESULT(no)
+fi
+_LT_DECL([], [MAGIC_CMD], [0],
+	 [Used to examine libraries when file_magic_cmd begins with "file"])dnl
+])# _LT_PATH_TOOL_PREFIX
+
+# Old name:
+AU_ALIAS([AC_PATH_TOOL_PREFIX], [_LT_PATH_TOOL_PREFIX])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_PATH_TOOL_PREFIX], [])
+
+
+# _LT_PATH_MAGIC
+# --------------
+# find a file program which can recognize a shared library
+m4_defun([_LT_PATH_MAGIC],
+[_LT_PATH_TOOL_PREFIX(${ac_tool_prefix}file, /usr/bin$PATH_SEPARATOR$PATH)
+if test -z "$lt_cv_path_MAGIC_CMD"; then
+  if test -n "$ac_tool_prefix"; then
+    _LT_PATH_TOOL_PREFIX(file, /usr/bin$PATH_SEPARATOR$PATH)
+  else
+    MAGIC_CMD=:
+  fi
+fi
+])# _LT_PATH_MAGIC
+
+
+# LT_PATH_LD
+# ----------
+# find the pathname to the GNU or non-GNU linker
+AC_DEFUN([LT_PATH_LD],
+[AC_REQUIRE([AC_PROG_CC])dnl
+AC_REQUIRE([AC_CANONICAL_HOST])dnl
+AC_REQUIRE([AC_CANONICAL_BUILD])dnl
+m4_require([_LT_DECL_SED])dnl
+m4_require([_LT_DECL_EGREP])dnl
+m4_require([_LT_PROG_ECHO_BACKSLASH])dnl
+
+AC_ARG_WITH([gnu-ld],
+    [AS_HELP_STRING([--with-gnu-ld],
+	[assume the C compiler uses GNU ld @<:@default=no@:>@])],
+    [test "$withval" = no || with_gnu_ld=yes],
+    [with_gnu_ld=no])dnl
+
+ac_prog=ld
+if test "$GCC" = yes; then
+  # Check if gcc -print-prog-name=ld gives a path.
+  AC_MSG_CHECKING([for ld used by $CC])
+  case $host in
+  *-*-mingw*)
+    # gcc leaves a trailing carriage return which upsets mingw
+    ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;;
+  *)
+    ac_prog=`($CC -print-prog-name=ld) 2>&5` ;;
+  esac
+  case $ac_prog in
+    # Accept absolute paths.
+    [[\\/]]* | ?:[[\\/]]*)
+      re_direlt='/[[^/]][[^/]]*/\.\./'
+      # Canonicalize the pathname of ld
+      ac_prog=`$ECHO "$ac_prog"| $SED 's%\\\\%/%g'`
+      while $ECHO "$ac_prog" | $GREP "$re_direlt" > /dev/null 2>&1; do
+	ac_prog=`$ECHO $ac_prog| $SED "s%$re_direlt%/%"`
+      done
+      test -z "$LD" && LD="$ac_prog"
+      ;;
+  "")
+    # If it fails, then pretend we aren't using GCC.
+    ac_prog=ld
+    ;;
+  *)
+    # If it is relative, then search for the first ld in PATH.
+    with_gnu_ld=unknown
+    ;;
+  esac
+elif test "$with_gnu_ld" = yes; then
+  AC_MSG_CHECKING([for GNU ld])
+else
+  AC_MSG_CHECKING([for non-GNU ld])
+fi
+AC_CACHE_VAL(lt_cv_path_LD,
+[if test -z "$LD"; then
+  lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
+  for ac_dir in $PATH; do
+    IFS="$lt_save_ifs"
+    test -z "$ac_dir" && ac_dir=.
+    if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then
+      lt_cv_path_LD="$ac_dir/$ac_prog"
+      # Check to see if the program is GNU ld.  I'd rather use --version,
+      # but apparently some variants of GNU ld only accept -v.
+      # Break only if it was the GNU/non-GNU ld that we prefer.
+      case `"$lt_cv_path_LD" -v 2>&1 </dev/null` in
+      *GNU* | *'with BFD'*)
+	test "$with_gnu_ld" != no && break
+	;;
+      *)
+	test "$with_gnu_ld" != yes && break
+	;;
+      esac
+    fi
+  done
+  IFS="$lt_save_ifs"
+else
+  lt_cv_path_LD="$LD" # Let the user override the test with a path.
+fi])
+LD="$lt_cv_path_LD"
+if test -n "$LD"; then
+  AC_MSG_RESULT($LD)
+else
+  AC_MSG_RESULT(no)
+fi
+test -z "$LD" && AC_MSG_ERROR([no acceptable ld found in \$PATH])
+_LT_PATH_LD_GNU
+AC_SUBST([LD])
+
+_LT_TAGDECL([], [LD], [1], [The linker used to build libraries])
+])# LT_PATH_LD
+
+# Old names:
+AU_ALIAS([AM_PROG_LD], [LT_PATH_LD])
+AU_ALIAS([AC_PROG_LD], [LT_PATH_LD])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AM_PROG_LD], [])
+dnl AC_DEFUN([AC_PROG_LD], [])
+
+
+# _LT_PATH_LD_GNU
+#- --------------
+m4_defun([_LT_PATH_LD_GNU],
+[AC_CACHE_CHECK([if the linker ($LD) is GNU ld], lt_cv_prog_gnu_ld,
+[# I'd rather use --version here, but apparently some GNU lds only accept -v.
+case `$LD -v 2>&1 </dev/null` in
+*GNU* | *'with BFD'*)
+  lt_cv_prog_gnu_ld=yes
+  ;;
+*)
+  lt_cv_prog_gnu_ld=no
+  ;;
+esac])
+with_gnu_ld=$lt_cv_prog_gnu_ld
+])# _LT_PATH_LD_GNU
+
+
+# _LT_CMD_RELOAD
+# --------------
+# find reload flag for linker
+#   -- PORTME Some linkers may need a different reload flag.
+m4_defun([_LT_CMD_RELOAD],
+[AC_CACHE_CHECK([for $LD option to reload object files],
+  lt_cv_ld_reload_flag,
+  [lt_cv_ld_reload_flag='-r'])
+reload_flag=$lt_cv_ld_reload_flag
+case $reload_flag in
+"" | " "*) ;;
+*) reload_flag=" $reload_flag" ;;
+esac
+reload_cmds='$LD$reload_flag -o $output$reload_objs'
+case $host_os in
+  cygwin* | mingw* | pw32* | cegcc*)
+    if test "$GCC" != yes; then
+      reload_cmds=false
+    fi
+    ;;
+  darwin*)
+    if test "$GCC" = yes; then
+      reload_cmds='$LTCC $LTCFLAGS -nostdlib ${wl}-r -o $output$reload_objs'
+    else
+      reload_cmds='$LD$reload_flag -o $output$reload_objs'
+    fi
+    ;;
+esac
+_LT_TAGDECL([], [reload_flag], [1], [How to create reloadable object files])dnl
+_LT_TAGDECL([], [reload_cmds], [2])dnl
+])# _LT_CMD_RELOAD
+
+
+# _LT_CHECK_MAGIC_METHOD
+# ----------------------
+# how to check for library dependencies
+#  -- PORTME fill in with the dynamic library characteristics
+m4_defun([_LT_CHECK_MAGIC_METHOD],
+[m4_require([_LT_DECL_EGREP])
+m4_require([_LT_DECL_OBJDUMP])
+AC_CACHE_CHECK([how to recognize dependent libraries],
+lt_cv_deplibs_check_method,
+[lt_cv_file_magic_cmd='$MAGIC_CMD'
+lt_cv_file_magic_test_file=
+lt_cv_deplibs_check_method='unknown'
+# Need to set the preceding variable on all platforms that support
+# interlibrary dependencies.
+# 'none' -- dependencies not supported.
+# `unknown' -- same as none, but documents that we really don't know.
+# 'pass_all' -- all dependencies passed with no checks.
+# 'test_compile' -- check by making test program.
+# 'file_magic [[regex]]' -- check by looking for files in library path
+# which responds to the $file_magic_cmd with a given extended regex.
+# If you have `file' or equivalent on your system and you're not sure
+# whether `pass_all' will *always* work, you probably want this one.
+
+case $host_os in
+aix[[4-9]]*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+beos*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+bsdi[[45]]*)
+  lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (shared object|dynamic lib)'
+  lt_cv_file_magic_cmd='/usr/bin/file -L'
+  lt_cv_file_magic_test_file=/shlib/libc.so
+  ;;
+
+cygwin*)
+  # func_win32_libid is a shell function defined in ltmain.sh
+  lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL'
+  lt_cv_file_magic_cmd='func_win32_libid'
+  ;;
+
+mingw* | pw32*)
+  # Base MSYS/MinGW do not provide the 'file' command needed by
+  # func_win32_libid shell function, so use a weaker test based on 'objdump',
+  # unless we find 'file', for example because we are cross-compiling.
+  # func_win32_libid assumes BSD nm, so disallow it if using MS dumpbin.
+  if ( test "$lt_cv_nm_interface" = "BSD nm" && file / ) >/dev/null 2>&1; then
+    lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL'
+    lt_cv_file_magic_cmd='func_win32_libid'
+  else
+    # Keep this pattern in sync with the one in func_win32_libid.
+    lt_cv_deplibs_check_method='file_magic file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)'
+    lt_cv_file_magic_cmd='$OBJDUMP -f'
+  fi
+  ;;
+
+cegcc*)
+  # use the weaker test based on 'objdump'. See mingw*.
+  lt_cv_deplibs_check_method='file_magic file format pe-arm-.*little(.*architecture: arm)?'
+  lt_cv_file_magic_cmd='$OBJDUMP -f'
+  ;;
+
+darwin* | rhapsody*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+freebsd* | dragonfly*)
+  if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then
+    case $host_cpu in
+    i*86 )
+      # Not sure whether the presence of OpenBSD here was a mistake.
+      # Let's accept both of them until this is cleared up.
+      lt_cv_deplibs_check_method='file_magic (FreeBSD|OpenBSD|DragonFly)/i[[3-9]]86 (compact )?demand paged shared library'
+      lt_cv_file_magic_cmd=/usr/bin/file
+      lt_cv_file_magic_test_file=`echo /usr/lib/libc.so.*`
+      ;;
+    esac
+  else
+    lt_cv_deplibs_check_method=pass_all
+  fi
+  ;;
+
+gnu*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+haiku*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+hpux10.20* | hpux11*)
+  lt_cv_file_magic_cmd=/usr/bin/file
+  case $host_cpu in
+  ia64*)
+    lt_cv_deplibs_check_method='file_magic (s[[0-9]][[0-9]][[0-9]]|ELF-[[0-9]][[0-9]]) shared object file - IA64'
+    lt_cv_file_magic_test_file=/usr/lib/hpux32/libc.so
+    ;;
+  hppa*64*)
+    [lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF[ -][0-9][0-9])(-bit)?( [LM]SB)? shared object( file)?[, -]* PA-RISC [0-9]\.[0-9]']
+    lt_cv_file_magic_test_file=/usr/lib/pa20_64/libc.sl
+    ;;
+  *)
+    lt_cv_deplibs_check_method='file_magic (s[[0-9]][[0-9]][[0-9]]|PA-RISC[[0-9]]\.[[0-9]]) shared library'
+    lt_cv_file_magic_test_file=/usr/lib/libc.sl
+    ;;
+  esac
+  ;;
+
+interix[[3-9]]*)
+  # PIC code is broken on Interix 3.x, that's why |\.a not |_pic\.a here
+  lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so|\.a)$'
+  ;;
+
+irix5* | irix6* | nonstopux*)
+  case $LD in
+  *-32|*"-32 ") libmagic=32-bit;;
+  *-n32|*"-n32 ") libmagic=N32;;
+  *-64|*"-64 ") libmagic=64-bit;;
+  *) libmagic=never-match;;
+  esac
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+# This must be glibc/ELF.
+linux* | k*bsd*-gnu | kopensolaris*-gnu)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+netbsd*)
+  if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then
+    lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|_pic\.a)$'
+  else
+    lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so|_pic\.a)$'
+  fi
+  ;;
+
+newos6*)
+  lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (executable|dynamic lib)'
+  lt_cv_file_magic_cmd=/usr/bin/file
+  lt_cv_file_magic_test_file=/usr/lib/libnls.so
+  ;;
+
+*nto* | *qnx*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+openbsd*)
+  if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+    lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|\.so|_pic\.a)$'
+  else
+    lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|_pic\.a)$'
+  fi
+  ;;
+
+osf3* | osf4* | osf5*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+rdos*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+solaris*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+sysv4 | sysv4.3*)
+  case $host_vendor in
+  motorola)
+    lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (shared object|dynamic lib) M[[0-9]][[0-9]]* Version [[0-9]]'
+    lt_cv_file_magic_test_file=`echo /usr/lib/libc.so*`
+    ;;
+  ncr)
+    lt_cv_deplibs_check_method=pass_all
+    ;;
+  sequent)
+    lt_cv_file_magic_cmd='/bin/file'
+    lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[LM]]SB (shared object|dynamic lib )'
+    ;;
+  sni)
+    lt_cv_file_magic_cmd='/bin/file'
+    lt_cv_deplibs_check_method="file_magic ELF [[0-9]][[0-9]]*-bit [[LM]]SB dynamic lib"
+    lt_cv_file_magic_test_file=/lib/libc.so
+    ;;
+  siemens)
+    lt_cv_deplibs_check_method=pass_all
+    ;;
+  pc)
+    lt_cv_deplibs_check_method=pass_all
+    ;;
+  esac
+  ;;
+
+tpf*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+esac
+])
+
+file_magic_glob=
+want_nocaseglob=no
+if test "$build" = "$host"; then
+  case $host_os in
+  mingw* | pw32*)
+    if ( shopt | grep nocaseglob ) >/dev/null 2>&1; then
+      want_nocaseglob=yes
+    else
+      file_magic_glob=`echo aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ | $SED -e "s/\(..\)/s\/[[\1]]\/[[\1]]\/g;/g"`
+    fi
+    ;;
+  esac
+fi
+
+file_magic_cmd=$lt_cv_file_magic_cmd
+deplibs_check_method=$lt_cv_deplibs_check_method
+test -z "$deplibs_check_method" && deplibs_check_method=unknown
+
+_LT_DECL([], [deplibs_check_method], [1],
+    [Method to check whether dependent libraries are shared objects])
+_LT_DECL([], [file_magic_cmd], [1],
+    [Command to use when deplibs_check_method = "file_magic"])
+_LT_DECL([], [file_magic_glob], [1],
+    [How to find potential files when deplibs_check_method = "file_magic"])
+_LT_DECL([], [want_nocaseglob], [1],
+    [Find potential files using nocaseglob when deplibs_check_method = "file_magic"])
+])# _LT_CHECK_MAGIC_METHOD
+
+
+# LT_PATH_NM
+# ----------
+# find the pathname to a BSD- or MS-compatible name lister
+AC_DEFUN([LT_PATH_NM],
+[AC_REQUIRE([AC_PROG_CC])dnl
+AC_CACHE_CHECK([for BSD- or MS-compatible name lister (nm)], lt_cv_path_NM,
+[if test -n "$NM"; then
+  # Let the user override the test.
+  lt_cv_path_NM="$NM"
+else
+  lt_nm_to_check="${ac_tool_prefix}nm"
+  if test -n "$ac_tool_prefix" && test "$build" = "$host"; then
+    lt_nm_to_check="$lt_nm_to_check nm"
+  fi
+  for lt_tmp_nm in $lt_nm_to_check; do
+    lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
+    for ac_dir in $PATH /usr/ccs/bin/elf /usr/ccs/bin /usr/ucb /bin; do
+      IFS="$lt_save_ifs"
+      test -z "$ac_dir" && ac_dir=.
+      tmp_nm="$ac_dir/$lt_tmp_nm"
+      if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext" ; then
+	# Check to see if the nm accepts a BSD-compat flag.
+	# Adding the `sed 1q' prevents false positives on HP-UX, which says:
+	#   nm: unknown option "B" ignored
+	# Tru64's nm complains that /dev/null is an invalid object file
+	case `"$tmp_nm" -B /dev/null 2>&1 | sed '1q'` in
+	*/dev/null* | *'Invalid file or object type'*)
+	  lt_cv_path_NM="$tmp_nm -B"
+	  break
+	  ;;
+	*)
+	  case `"$tmp_nm" -p /dev/null 2>&1 | sed '1q'` in
+	  */dev/null*)
+	    lt_cv_path_NM="$tmp_nm -p"
+	    break
+	    ;;
+	  *)
+	    lt_cv_path_NM=${lt_cv_path_NM="$tmp_nm"} # keep the first match, but
+	    continue # so that we can try to find one that supports BSD flags
+	    ;;
+	  esac
+	  ;;
+	esac
+      fi
+    done
+    IFS="$lt_save_ifs"
+  done
+  : ${lt_cv_path_NM=no}
+fi])
+if test "$lt_cv_path_NM" != "no"; then
+  NM="$lt_cv_path_NM"
+else
+  # Didn't find any BSD compatible name lister, look for dumpbin.
+  if test -n "$DUMPBIN"; then :
+    # Let the user override the test.
+  else
+    AC_CHECK_TOOLS(DUMPBIN, [dumpbin "link -dump"], :)
+    case `$DUMPBIN -symbols /dev/null 2>&1 | sed '1q'` in
+    *COFF*)
+      DUMPBIN="$DUMPBIN -symbols"
+      ;;
+    *)
+      DUMPBIN=:
+      ;;
+    esac
+  fi
+  AC_SUBST([DUMPBIN])
+  if test "$DUMPBIN" != ":"; then
+    NM="$DUMPBIN"
+  fi
+fi
+test -z "$NM" && NM=nm
+AC_SUBST([NM])
+_LT_DECL([], [NM], [1], [A BSD- or MS-compatible name lister])dnl
+
+AC_CACHE_CHECK([the name lister ($NM) interface], [lt_cv_nm_interface],
+  [lt_cv_nm_interface="BSD nm"
+  echo "int some_variable = 0;" > conftest.$ac_ext
+  (eval echo "\"\$as_me:$LINENO: $ac_compile\"" >&AS_MESSAGE_LOG_FD)
+  (eval "$ac_compile" 2>conftest.err)
+  cat conftest.err >&AS_MESSAGE_LOG_FD
+  (eval echo "\"\$as_me:$LINENO: $NM \\\"conftest.$ac_objext\\\"\"" >&AS_MESSAGE_LOG_FD)
+  (eval "$NM \"conftest.$ac_objext\"" 2>conftest.err > conftest.out)
+  cat conftest.err >&AS_MESSAGE_LOG_FD
+  (eval echo "\"\$as_me:$LINENO: output\"" >&AS_MESSAGE_LOG_FD)
+  cat conftest.out >&AS_MESSAGE_LOG_FD
+  if $GREP 'External.*some_variable' conftest.out > /dev/null; then
+    lt_cv_nm_interface="MS dumpbin"
+  fi
+  rm -f conftest*])
+])# LT_PATH_NM
+
+# Old names:
+AU_ALIAS([AM_PROG_NM], [LT_PATH_NM])
+AU_ALIAS([AC_PROG_NM], [LT_PATH_NM])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AM_PROG_NM], [])
+dnl AC_DEFUN([AC_PROG_NM], [])
+
+# _LT_CHECK_SHAREDLIB_FROM_LINKLIB
+# --------------------------------
+# how to determine the name of the shared library
+# associated with a specific link library.
+#  -- PORTME fill in with the dynamic library characteristics
+m4_defun([_LT_CHECK_SHAREDLIB_FROM_LINKLIB],
+[m4_require([_LT_DECL_EGREP])
+m4_require([_LT_DECL_OBJDUMP])
+m4_require([_LT_DECL_DLLTOOL])
+AC_CACHE_CHECK([how to associate runtime and link libraries],
+lt_cv_sharedlib_from_linklib_cmd,
+[lt_cv_sharedlib_from_linklib_cmd='unknown'
+
+case $host_os in
+cygwin* | mingw* | pw32* | cegcc*)
+  # two different shell functions defined in ltmain.sh
+  # decide which to use based on capabilities of $DLLTOOL
+  case `$DLLTOOL --help 2>&1` in
+  *--identify-strict*)
+    lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib
+    ;;
+  *)
+    lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib_fallback
+    ;;
+  esac
+  ;;
+*)
+  # fallback: assume linklib IS sharedlib
+  lt_cv_sharedlib_from_linklib_cmd="$ECHO"
+  ;;
+esac
+])
+sharedlib_from_linklib_cmd=$lt_cv_sharedlib_from_linklib_cmd
+test -z "$sharedlib_from_linklib_cmd" && sharedlib_from_linklib_cmd=$ECHO
+
+_LT_DECL([], [sharedlib_from_linklib_cmd], [1],
+    [Command to associate shared and link libraries])
+])# _LT_CHECK_SHAREDLIB_FROM_LINKLIB
+
+
+# _LT_PATH_MANIFEST_TOOL
+# ----------------------
+# locate the manifest tool
+m4_defun([_LT_PATH_MANIFEST_TOOL],
+[AC_CHECK_TOOL(MANIFEST_TOOL, mt, :)
+test -z "$MANIFEST_TOOL" && MANIFEST_TOOL=mt
+AC_CACHE_CHECK([if $MANIFEST_TOOL is a manifest tool], [lt_cv_path_mainfest_tool],
+  [lt_cv_path_mainfest_tool=no
+  echo "$as_me:$LINENO: $MANIFEST_TOOL '-?'" >&AS_MESSAGE_LOG_FD
+  $MANIFEST_TOOL '-?' 2>conftest.err > conftest.out
+  cat conftest.err >&AS_MESSAGE_LOG_FD
+  if $GREP 'Manifest Tool' conftest.out > /dev/null; then
+    lt_cv_path_mainfest_tool=yes
+  fi
+  rm -f conftest*])
+if test "x$lt_cv_path_mainfest_tool" != xyes; then
+  MANIFEST_TOOL=:
+fi
+_LT_DECL([], [MANIFEST_TOOL], [1], [Manifest tool])dnl
+])# _LT_PATH_MANIFEST_TOOL
+
+
+# LT_LIB_M
+# --------
+# check for math library
+AC_DEFUN([LT_LIB_M],
+[AC_REQUIRE([AC_CANONICAL_HOST])dnl
+LIBM=
+case $host in
+*-*-beos* | *-*-cegcc* | *-*-cygwin* | *-*-haiku* | *-*-pw32* | *-*-darwin*)
+  # These system don't have libm, or don't need it
+  ;;
+*-ncr-sysv4.3*)
+  AC_CHECK_LIB(mw, _mwvalidcheckl, LIBM="-lmw")
+  AC_CHECK_LIB(m, cos, LIBM="$LIBM -lm")
+  ;;
+*)
+  AC_CHECK_LIB(m, cos, LIBM="-lm")
+  ;;
+esac
+AC_SUBST([LIBM])
+])# LT_LIB_M
+
+# Old name:
+AU_ALIAS([AC_CHECK_LIBM], [LT_LIB_M])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_CHECK_LIBM], [])
+
+
+# _LT_COMPILER_NO_RTTI([TAGNAME])
+# -------------------------------
+m4_defun([_LT_COMPILER_NO_RTTI],
+[m4_require([_LT_TAG_COMPILER])dnl
+
+_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=
+
+if test "$GCC" = yes; then
+  case $cc_basename in
+  nvcc*)
+    _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -Xcompiler -fno-builtin' ;;
+  *)
+    _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -fno-builtin' ;;
+  esac
+
+  _LT_COMPILER_OPTION([if $compiler supports -fno-rtti -fno-exceptions],
+    lt_cv_prog_compiler_rtti_exceptions,
+    [-fno-rtti -fno-exceptions], [],
+    [_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)="$_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1) -fno-rtti -fno-exceptions"])
+fi
+_LT_TAGDECL([no_builtin_flag], [lt_prog_compiler_no_builtin_flag], [1],
+	[Compiler flag to turn off builtin functions])
+])# _LT_COMPILER_NO_RTTI
+
+
+# _LT_CMD_GLOBAL_SYMBOLS
+# ----------------------
+m4_defun([_LT_CMD_GLOBAL_SYMBOLS],
+[AC_REQUIRE([AC_CANONICAL_HOST])dnl
+AC_REQUIRE([AC_PROG_CC])dnl
+AC_REQUIRE([AC_PROG_AWK])dnl
+AC_REQUIRE([LT_PATH_NM])dnl
+AC_REQUIRE([LT_PATH_LD])dnl
+m4_require([_LT_DECL_SED])dnl
+m4_require([_LT_DECL_EGREP])dnl
+m4_require([_LT_TAG_COMPILER])dnl
+
+# Check for command to grab the raw symbol name followed by C symbol from nm.
+AC_MSG_CHECKING([command to parse $NM output from $compiler object])
+AC_CACHE_VAL([lt_cv_sys_global_symbol_pipe],
+[
+# These are sane defaults that work on at least a few old systems.
+# [They come from Ultrix.  What could be older than Ultrix?!! ;)]
+
+# Character class describing NM global symbol codes.
+symcode='[[BCDEGRST]]'
+
+# Regexp to match symbols that can be accessed directly from C.
+sympat='\([[_A-Za-z]][[_A-Za-z0-9]]*\)'
+
+# Define system-specific variables.
+case $host_os in
+aix*)
+  symcode='[[BCDT]]'
+  ;;
+cygwin* | mingw* | pw32* | cegcc*)
+  symcode='[[ABCDGISTW]]'
+  ;;
+hpux*)
+  if test "$host_cpu" = ia64; then
+    symcode='[[ABCDEGRST]]'
+  fi
+  ;;
+irix* | nonstopux*)
+  symcode='[[BCDEGRST]]'
+  ;;
+osf*)
+  symcode='[[BCDEGQRST]]'
+  ;;
+solaris*)
+  symcode='[[BDRT]]'
+  ;;
+sco3.2v5*)
+  symcode='[[DT]]'
+  ;;
+sysv4.2uw2*)
+  symcode='[[DT]]'
+  ;;
+sysv5* | sco5v6* | unixware* | OpenUNIX*)
+  symcode='[[ABDT]]'
+  ;;
+sysv4)
+  symcode='[[DFNSTU]]'
+  ;;
+esac
+
+# If we're using GNU nm, then use its standard symbol codes.
+case `$NM -V 2>&1` in
+*GNU* | *'with BFD'*)
+  symcode='[[ABCDGIRSTW]]' ;;
+esac
+
+# Transform an extracted symbol line into a proper C declaration.
+# Some systems (esp. on ia64) link data and code symbols differently,
+# so use this general approach.
+lt_cv_sys_global_symbol_to_cdecl="sed -n -e 's/^T .* \(.*\)$/extern int \1();/p' -e 's/^$symcode* .* \(.*\)$/extern char \1;/p'"
+
+# Transform an extracted symbol line into symbol name and symbol address
+lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([[^ ]]*\)[[ ]]*$/  {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([[^ ]]*\) \([[^ ]]*\)$/  {\"\2\", (void *) \&\2},/p'"
+lt_cv_sys_global_symbol_to_c_name_address_lib_prefix="sed -n -e 's/^: \([[^ ]]*\)[[ ]]*$/  {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([[^ ]]*\) \(lib[[^ ]]*\)$/  {\"\2\", (void *) \&\2},/p' -e 's/^$symcode* \([[^ ]]*\) \([[^ ]]*\)$/  {\"lib\2\", (void *) \&\2},/p'"
+
+# Handle CRLF in mingw tool chain
+opt_cr=
+case $build_os in
+mingw*)
+  opt_cr=`$ECHO 'x\{0,1\}' | tr x '\015'` # option cr in regexp
+  ;;
+esac
+
+# Try without a prefix underscore, then with it.
+for ac_symprfx in "" "_"; do
+
+  # Transform symcode, sympat, and symprfx into a raw symbol and a C symbol.
+  symxfrm="\\1 $ac_symprfx\\2 \\2"
+
+  # Write the raw and C identifiers.
+  if test "$lt_cv_nm_interface" = "MS dumpbin"; then
+    # Fake it for dumpbin and say T for any non-static function
+    # and D for any global variable.
+    # Also find C++ and __fastcall symbols from MSVC++,
+    # which start with @ or ?.
+    lt_cv_sys_global_symbol_pipe="$AWK ['"\
+"     {last_section=section; section=\$ 3};"\
+"     /^COFF SYMBOL TABLE/{for(i in hide) delete hide[i]};"\
+"     /Section length .*#relocs.*(pick any)/{hide[last_section]=1};"\
+"     \$ 0!~/External *\|/{next};"\
+"     / 0+ UNDEF /{next}; / UNDEF \([^|]\)*()/{next};"\
+"     {if(hide[section]) next};"\
+"     {f=0}; \$ 0~/\(\).*\|/{f=1}; {printf f ? \"T \" : \"D \"};"\
+"     {split(\$ 0, a, /\||\r/); split(a[2], s)};"\
+"     s[1]~/^[@?]/{print s[1], s[1]; next};"\
+"     s[1]~prfx {split(s[1],t,\"@\"); print t[1], substr(t[1],length(prfx))}"\
+"     ' prfx=^$ac_symprfx]"
+  else
+    lt_cv_sys_global_symbol_pipe="sed -n -e 's/^.*[[	 ]]\($symcode$symcode*\)[[	 ]][[	 ]]*$ac_symprfx$sympat$opt_cr$/$symxfrm/p'"
+  fi
+  lt_cv_sys_global_symbol_pipe="$lt_cv_sys_global_symbol_pipe | sed '/ __gnu_lto/d'"
+
+  # Check to see that the pipe works correctly.
+  pipe_works=no
+
+  rm -f conftest*
+  cat > conftest.$ac_ext <<_LT_EOF
+#ifdef __cplusplus
+extern "C" {
+#endif
+char nm_test_var;
+void nm_test_func(void);
+void nm_test_func(void){}
+#ifdef __cplusplus
+}
+#endif
+int main(){nm_test_var='a';nm_test_func();return(0);}
+_LT_EOF
+
+  if AC_TRY_EVAL(ac_compile); then
+    # Now try to grab the symbols.
+    nlist=conftest.nm
+    if AC_TRY_EVAL(NM conftest.$ac_objext \| "$lt_cv_sys_global_symbol_pipe" \> $nlist) && test -s "$nlist"; then
+      # Try sorting and uniquifying the output.
+      if sort "$nlist" | uniq > "$nlist"T; then
+	mv -f "$nlist"T "$nlist"
+      else
+	rm -f "$nlist"T
+      fi
+
+      # Make sure that we snagged all the symbols we need.
+      if $GREP ' nm_test_var$' "$nlist" >/dev/null; then
+	if $GREP ' nm_test_func$' "$nlist" >/dev/null; then
+	  cat <<_LT_EOF > conftest.$ac_ext
+/* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests.  */
+#if defined(_WIN32) || defined(__CYGWIN__) || defined(_WIN32_WCE)
+/* DATA imports from DLLs on WIN32 con't be const, because runtime
+   relocations are performed -- see ld's documentation on pseudo-relocs.  */
+# define LT@&t at _DLSYM_CONST
+#elif defined(__osf__)
+/* This system does not cope well with relocations in const data.  */
+# define LT@&t at _DLSYM_CONST
+#else
+# define LT@&t at _DLSYM_CONST const
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+_LT_EOF
+	  # Now generate the symbol file.
+	  eval "$lt_cv_sys_global_symbol_to_cdecl"' < "$nlist" | $GREP -v main >> conftest.$ac_ext'
+
+	  cat <<_LT_EOF >> conftest.$ac_ext
+
+/* The mapping between symbol names and symbols.  */
+LT@&t at _DLSYM_CONST struct {
+  const char *name;
+  void       *address;
+}
+lt__PROGRAM__LTX_preloaded_symbols[[]] =
+{
+  { "@PROGRAM@", (void *) 0 },
+_LT_EOF
+	  $SED "s/^$symcode$symcode* \(.*\) \(.*\)$/  {\"\2\", (void *) \&\2},/" < "$nlist" | $GREP -v main >> conftest.$ac_ext
+	  cat <<\_LT_EOF >> conftest.$ac_ext
+  {0, (void *) 0}
+};
+
+/* This works around a problem in FreeBSD linker */
+#ifdef FREEBSD_WORKAROUND
+static const void *lt_preloaded_setup() {
+  return lt__PROGRAM__LTX_preloaded_symbols;
+}
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+_LT_EOF
+	  # Now try linking the two files.
+	  mv conftest.$ac_objext conftstm.$ac_objext
+	  lt_globsym_save_LIBS=$LIBS
+	  lt_globsym_save_CFLAGS=$CFLAGS
+	  LIBS="conftstm.$ac_objext"
+	  CFLAGS="$CFLAGS$_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)"
+	  if AC_TRY_EVAL(ac_link) && test -s conftest${ac_exeext}; then
+	    pipe_works=yes
+	  fi
+	  LIBS=$lt_globsym_save_LIBS
+	  CFLAGS=$lt_globsym_save_CFLAGS
+	else
+	  echo "cannot find nm_test_func in $nlist" >&AS_MESSAGE_LOG_FD
+	fi
+      else
+	echo "cannot find nm_test_var in $nlist" >&AS_MESSAGE_LOG_FD
+      fi
+    else
+      echo "cannot run $lt_cv_sys_global_symbol_pipe" >&AS_MESSAGE_LOG_FD
+    fi
+  else
+    echo "$progname: failed program was:" >&AS_MESSAGE_LOG_FD
+    cat conftest.$ac_ext >&5
+  fi
+  rm -rf conftest* conftst*
+
+  # Do not use the global_symbol_pipe unless it works.
+  if test "$pipe_works" = yes; then
+    break
+  else
+    lt_cv_sys_global_symbol_pipe=
+  fi
+done
+])
+if test -z "$lt_cv_sys_global_symbol_pipe"; then
+  lt_cv_sys_global_symbol_to_cdecl=
+fi
+if test -z "$lt_cv_sys_global_symbol_pipe$lt_cv_sys_global_symbol_to_cdecl"; then
+  AC_MSG_RESULT(failed)
+else
+  AC_MSG_RESULT(ok)
+fi
+
+# Response file support.
+if test "$lt_cv_nm_interface" = "MS dumpbin"; then
+  nm_file_list_spec='@'
+elif $NM --help 2>/dev/null | grep '[[@]]FILE' >/dev/null; then
+  nm_file_list_spec='@'
+fi
+
+_LT_DECL([global_symbol_pipe], [lt_cv_sys_global_symbol_pipe], [1],
+    [Take the output of nm and produce a listing of raw symbols and C names])
+_LT_DECL([global_symbol_to_cdecl], [lt_cv_sys_global_symbol_to_cdecl], [1],
+    [Transform the output of nm in a proper C declaration])
+_LT_DECL([global_symbol_to_c_name_address],
+    [lt_cv_sys_global_symbol_to_c_name_address], [1],
+    [Transform the output of nm in a C name address pair])
+_LT_DECL([global_symbol_to_c_name_address_lib_prefix],
+    [lt_cv_sys_global_symbol_to_c_name_address_lib_prefix], [1],
+    [Transform the output of nm in a C name address pair when lib prefix is needed])
+_LT_DECL([], [nm_file_list_spec], [1],
+    [Specify filename containing input files for $NM])
+]) # _LT_CMD_GLOBAL_SYMBOLS
+
+
+# _LT_COMPILER_PIC([TAGNAME])
+# ---------------------------
+m4_defun([_LT_COMPILER_PIC],
+[m4_require([_LT_TAG_COMPILER])dnl
+_LT_TAGVAR(lt_prog_compiler_wl, $1)=
+_LT_TAGVAR(lt_prog_compiler_pic, $1)=
+_LT_TAGVAR(lt_prog_compiler_static, $1)=
+
+m4_if([$1], [CXX], [
+  # C++ specific cases for pic, static, wl, etc.
+  if test "$GXX" = yes; then
+    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+    _LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
+
+    case $host_os in
+    aix*)
+      # All AIX code is PIC.
+      if test "$host_cpu" = ia64; then
+	# AIX 5 now supports IA64 processor
+	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      fi
+      ;;
+
+    amigaos*)
+      case $host_cpu in
+      powerpc)
+            # see comment about AmigaOS4 .so support
+            _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+        ;;
+      m68k)
+            # FIXME: we need at least 68020 code to build shared libraries, but
+            # adding the `-m68020' flag to GCC prevents building anything better,
+            # like `-m68040'.
+            _LT_TAGVAR(lt_prog_compiler_pic, $1)='-m68020 -resident32 -malways-restore-a4'
+        ;;
+      esac
+      ;;
+
+    beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*)
+      # PIC is the default for these OSes.
+      ;;
+    mingw* | cygwin* | os2* | pw32* | cegcc*)
+      # This hack is so that the source file can tell whether it is being
+      # built for inclusion in a dll (and should export symbols for example).
+      # Although the cygwin gcc ignores -fPIC, still need this for old-style
+      # (--disable-auto-import) libraries
+      m4_if([$1], [GCJ], [],
+	[_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT'])
+      ;;
+    darwin* | rhapsody*)
+      # PIC is the default on this platform
+      # Common symbols not allowed in MH_DYLIB files
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fno-common'
+      ;;
+    *djgpp*)
+      # DJGPP does not support shared libraries at all
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)=
+      ;;
+    haiku*)
+      # PIC is the default for Haiku.
+      # The "-static" flag exists, but is broken.
+      _LT_TAGVAR(lt_prog_compiler_static, $1)=
+      ;;
+    interix[[3-9]]*)
+      # Interix 3.x gcc -fpic/-fPIC options generate broken code.
+      # Instead, we relocate shared libraries at runtime.
+      ;;
+    sysv4*MP*)
+      if test -d /usr/nec; then
+	_LT_TAGVAR(lt_prog_compiler_pic, $1)=-Kconform_pic
+      fi
+      ;;
+    hpux*)
+      # PIC is the default for 64-bit PA HP-UX, but not for 32-bit
+      # PA HP-UX.  On IA64 HP-UX, PIC is the default but the pic flag
+      # sets the default TLS model and affects inlining.
+      case $host_cpu in
+      hppa*64*)
+	;;
+      *)
+	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+	;;
+      esac
+      ;;
+    *qnx* | *nto*)
+      # QNX uses GNU C++, but need to define -shared option too, otherwise
+      # it will coredump.
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared'
+      ;;
+    *)
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+      ;;
+    esac
+  else
+    case $host_os in
+      aix[[4-9]]*)
+	# All AIX code is PIC.
+	if test "$host_cpu" = ia64; then
+	  # AIX 5 now supports IA64 processor
+	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+	else
+	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-bnso -bI:/lib/syscalls.exp'
+	fi
+	;;
+      chorus*)
+	case $cc_basename in
+	cxch68*)
+	  # Green Hills C++ Compiler
+	  # _LT_TAGVAR(lt_prog_compiler_static, $1)="--no_auto_instantiation -u __main -u __premain -u _abort -r $COOL_DIR/lib/libOrb.a $MVME_DIR/lib/CC/libC.a $MVME_DIR/lib/classix/libcx.s.a"
+	  ;;
+	esac
+	;;
+      mingw* | cygwin* | os2* | pw32* | cegcc*)
+	# This hack is so that the source file can tell whether it is being
+	# built for inclusion in a dll (and should export symbols for example).
+	m4_if([$1], [GCJ], [],
+	  [_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT'])
+	;;
+      dgux*)
+	case $cc_basename in
+	  ec++*)
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+	    ;;
+	  ghcx*)
+	    # Green Hills C++ Compiler
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
+	    ;;
+	  *)
+	    ;;
+	esac
+	;;
+      freebsd* | dragonfly*)
+	# FreeBSD uses GNU C++
+	;;
+      hpux9* | hpux10* | hpux11*)
+	case $cc_basename in
+	  CC*)
+	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive'
+	    if test "$host_cpu" != ia64; then
+	      _LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z'
+	    fi
+	    ;;
+	  aCC*)
+	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive'
+	    case $host_cpu in
+	    hppa*64*|ia64*)
+	      # +Z the default
+	      ;;
+	    *)
+	      _LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z'
+	      ;;
+	    esac
+	    ;;
+	  *)
+	    ;;
+	esac
+	;;
+      interix*)
+	# This is c89, which is MS Visual C++ (no shared libs)
+	# Anyone wants to do a port?
+	;;
+      irix5* | irix6* | nonstopux*)
+	case $cc_basename in
+	  CC*)
+	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
+	    # CC pic flag -KPIC is the default.
+	    ;;
+	  *)
+	    ;;
+	esac
+	;;
+      linux* | k*bsd*-gnu | kopensolaris*-gnu)
+	case $cc_basename in
+	  KCC*)
+	    # KAI C++ Compiler
+	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='--backend -Wl,'
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+	    ;;
+	  ecpc* )
+	    # old Intel C++ for x86_64 which still supported -KPIC.
+	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
+	    ;;
+	  icpc* )
+	    # Intel C++, used to be incompatible with GCC.
+	    # ICC 10 doesn't accept -KPIC any more.
+	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
+	    ;;
+	  pgCC* | pgcpp*)
+	    # Portland Group C++ compiler
+	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fpic'
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+	    ;;
+	  cxx*)
+	    # Compaq C++
+	    # Make sure the PIC flag is empty.  It appears that all Alpha
+	    # Linux and Compaq Tru64 Unix objects are PIC.
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)=
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
+	    ;;
+	  xlc* | xlC* | bgxl[[cC]]* | mpixl[[cC]]*)
+	    # IBM XL 8.0, 9.0 on PPC and BlueGene
+	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-qpic'
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-qstaticlink'
+	    ;;
+	  *)
+	    case `$CC -V 2>&1 | sed 5q` in
+	    *Sun\ C*)
+	      # Sun C++ 5.9
+	      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+	      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+	      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld '
+	      ;;
+	    esac
+	    ;;
+	esac
+	;;
+      lynxos*)
+	;;
+      m88k*)
+	;;
+      mvs*)
+	case $cc_basename in
+	  cxx*)
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-W c,exportall'
+	    ;;
+	  *)
+	    ;;
+	esac
+	;;
+      netbsd*)
+	;;
+      *qnx* | *nto*)
+        # QNX uses GNU C++, but need to define -shared option too, otherwise
+        # it will coredump.
+        _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared'
+        ;;
+      osf3* | osf4* | osf5*)
+	case $cc_basename in
+	  KCC*)
+	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='--backend -Wl,'
+	    ;;
+	  RCC*)
+	    # Rational C++ 2.4.1
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
+	    ;;
+	  cxx*)
+	    # Digital/Compaq C++
+	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	    # Make sure the PIC flag is empty.  It appears that all Alpha
+	    # Linux and Compaq Tru64 Unix objects are PIC.
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)=
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
+	    ;;
+	  *)
+	    ;;
+	esac
+	;;
+      psos*)
+	;;
+      solaris*)
+	case $cc_basename in
+	  CC* | sunCC*)
+	    # Sun C++ 4.2, 5.x and Centerline C++
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld '
+	    ;;
+	  gcx*)
+	    # Green Hills C++ Compiler
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC'
+	    ;;
+	  *)
+	    ;;
+	esac
+	;;
+      sunos4*)
+	case $cc_basename in
+	  CC*)
+	    # Sun C++ 4.x
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+	    ;;
+	  lcc*)
+	    # Lucid
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
+	    ;;
+	  *)
+	    ;;
+	esac
+	;;
+      sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*)
+	case $cc_basename in
+	  CC*)
+	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+	    ;;
+	esac
+	;;
+      tandem*)
+	case $cc_basename in
+	  NCC*)
+	    # NonStop-UX NCC 3.20
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+	    ;;
+	  *)
+	    ;;
+	esac
+	;;
+      vxworks*)
+	;;
+      *)
+	_LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no
+	;;
+    esac
+  fi
+],
+[
+  if test "$GCC" = yes; then
+    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+    _LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
+
+    case $host_os in
+      aix*)
+      # All AIX code is PIC.
+      if test "$host_cpu" = ia64; then
+	# AIX 5 now supports IA64 processor
+	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      fi
+      ;;
+
+    amigaos*)
+      case $host_cpu in
+      powerpc)
+            # see comment about AmigaOS4 .so support
+            _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+        ;;
+      m68k)
+            # FIXME: we need at least 68020 code to build shared libraries, but
+            # adding the `-m68020' flag to GCC prevents building anything better,
+            # like `-m68040'.
+            _LT_TAGVAR(lt_prog_compiler_pic, $1)='-m68020 -resident32 -malways-restore-a4'
+        ;;
+      esac
+      ;;
+
+    beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*)
+      # PIC is the default for these OSes.
+      ;;
+
+    mingw* | cygwin* | pw32* | os2* | cegcc*)
+      # This hack is so that the source file can tell whether it is being
+      # built for inclusion in a dll (and should export symbols for example).
+      # Although the cygwin gcc ignores -fPIC, still need this for old-style
+      # (--disable-auto-import) libraries
+      m4_if([$1], [GCJ], [],
+	[_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT'])
+      ;;
+
+    darwin* | rhapsody*)
+      # PIC is the default on this platform
+      # Common symbols not allowed in MH_DYLIB files
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fno-common'
+      ;;
+
+    haiku*)
+      # PIC is the default for Haiku.
+      # The "-static" flag exists, but is broken.
+      _LT_TAGVAR(lt_prog_compiler_static, $1)=
+      ;;
+
+    hpux*)
+      # PIC is the default for 64-bit PA HP-UX, but not for 32-bit
+      # PA HP-UX.  On IA64 HP-UX, PIC is the default but the pic flag
+      # sets the default TLS model and affects inlining.
+      case $host_cpu in
+      hppa*64*)
+	# +Z the default
+	;;
+      *)
+	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+	;;
+      esac
+      ;;
+
+    interix[[3-9]]*)
+      # Interix 3.x gcc -fpic/-fPIC options generate broken code.
+      # Instead, we relocate shared libraries at runtime.
+      ;;
+
+    msdosdjgpp*)
+      # Just because we use GCC doesn't mean we suddenly get shared libraries
+      # on systems that don't support them.
+      _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no
+      enable_shared=no
+      ;;
+
+    *nto* | *qnx*)
+      # QNX uses GNU C++, but need to define -shared option too, otherwise
+      # it will coredump.
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared'
+      ;;
+
+    sysv4*MP*)
+      if test -d /usr/nec; then
+	_LT_TAGVAR(lt_prog_compiler_pic, $1)=-Kconform_pic
+      fi
+      ;;
+
+    *)
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+      ;;
+    esac
+
+    case $cc_basename in
+    nvcc*) # Cuda Compiler Driver 2.2
+      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Xlinker '
+      if test -n "$_LT_TAGVAR(lt_prog_compiler_pic, $1)"; then
+        _LT_TAGVAR(lt_prog_compiler_pic, $1)="-Xcompiler $_LT_TAGVAR(lt_prog_compiler_pic, $1)"
+      fi
+      ;;
+    esac
+  else
+    # PORTME Check for flag to pass linker flags through the system compiler.
+    case $host_os in
+    aix*)
+      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+      if test "$host_cpu" = ia64; then
+	# AIX 5 now supports IA64 processor
+	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      else
+	_LT_TAGVAR(lt_prog_compiler_static, $1)='-bnso -bI:/lib/syscalls.exp'
+      fi
+      ;;
+
+    mingw* | cygwin* | pw32* | os2* | cegcc*)
+      # This hack is so that the source file can tell whether it is being
+      # built for inclusion in a dll (and should export symbols for example).
+      m4_if([$1], [GCJ], [],
+	[_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT'])
+      ;;
+
+    hpux9* | hpux10* | hpux11*)
+      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+      # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but
+      # not for PA HP-UX.
+      case $host_cpu in
+      hppa*64*|ia64*)
+	# +Z the default
+	;;
+      *)
+	_LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z'
+	;;
+      esac
+      # Is there a better lt_prog_compiler_static that works with the bundled CC?
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive'
+      ;;
+
+    irix5* | irix6* | nonstopux*)
+      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+      # PIC (with -KPIC) is the default.
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
+      ;;
+
+    linux* | k*bsd*-gnu | kopensolaris*-gnu)
+      case $cc_basename in
+      # old Intel for x86_64 which still supported -KPIC.
+      ecc*)
+	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+	_LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
+        ;;
+      # icc used to be incompatible with GCC.
+      # ICC 10 doesn't accept -KPIC any more.
+      icc* | ifort*)
+	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+	_LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
+        ;;
+      # Lahey Fortran 8.1.
+      lf95*)
+	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	_LT_TAGVAR(lt_prog_compiler_pic, $1)='--shared'
+	_LT_TAGVAR(lt_prog_compiler_static, $1)='--static'
+	;;
+      nagfor*)
+	# NAG Fortran compiler
+	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,-Wl,,'
+	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC'
+	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+	;;
+      pgcc* | pgf77* | pgf90* | pgf95* | pgfortran*)
+        # Portland Group compilers (*not* the Pentium gcc compiler,
+	# which looks to be a dead project)
+	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-fpic'
+	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+        ;;
+      ccc*)
+        _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+        # All Alpha code is PIC.
+        _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
+        ;;
+      xl* | bgxl* | bgf* | mpixl*)
+	# IBM XL C 8.0/Fortran 10.1, 11.1 on PPC and BlueGene
+	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-qpic'
+	_LT_TAGVAR(lt_prog_compiler_static, $1)='-qstaticlink'
+	;;
+      *)
+	case `$CC -V 2>&1 | sed 5q` in
+	*Sun\ Ceres\ Fortran* | *Sun*Fortran*\ [[1-7]].* | *Sun*Fortran*\ 8.[[0-3]]*)
+	  # Sun Fortran 8.3 passes all unrecognized flags to the linker
+	  _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+	  _LT_TAGVAR(lt_prog_compiler_wl, $1)=''
+	  ;;
+	*Sun\ F* | *Sun*Fortran*)
+	  _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+	  _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld '
+	  ;;
+	*Sun\ C*)
+	  # Sun C 5.9
+	  _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+	  _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	  ;;
+        *Intel*\ [[CF]]*Compiler*)
+	  _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	  _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
+	  ;;
+	*Portland\ Group*)
+	  _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	  _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fpic'
+	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+	  ;;
+	esac
+	;;
+      esac
+      ;;
+
+    newsos6)
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      ;;
+
+    *nto* | *qnx*)
+      # QNX uses GNU C++, but need to define -shared option too, otherwise
+      # it will coredump.
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared'
+      ;;
+
+    osf3* | osf4* | osf5*)
+      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+      # All OSF/1 code is PIC.
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
+      ;;
+
+    rdos*)
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
+      ;;
+
+    solaris*)
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      case $cc_basename in
+      f77* | f90* | f95* | sunf77* | sunf90* | sunf95*)
+	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ';;
+      *)
+	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,';;
+      esac
+      ;;
+
+    sunos4*)
+      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld '
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC'
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      ;;
+
+    sysv4 | sysv4.2uw2* | sysv4.3*)
+      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      ;;
+
+    sysv4*MP*)
+      if test -d /usr/nec ;then
+	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-Kconform_pic'
+	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      fi
+      ;;
+
+    sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*)
+      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      ;;
+
+    unicos*)
+      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+      _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no
+      ;;
+
+    uts4*)
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      ;;
+
+    *)
+      _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no
+      ;;
+    esac
+  fi
+])
+case $host_os in
+  # For platforms which do not support PIC, -DPIC is meaningless:
+  *djgpp*)
+    _LT_TAGVAR(lt_prog_compiler_pic, $1)=
+    ;;
+  *)
+    _LT_TAGVAR(lt_prog_compiler_pic, $1)="$_LT_TAGVAR(lt_prog_compiler_pic, $1)@&t at m4_if([$1],[],[ -DPIC],[m4_if([$1],[CXX],[ -DPIC],[])])"
+    ;;
+esac
+
+AC_CACHE_CHECK([for $compiler option to produce PIC],
+  [_LT_TAGVAR(lt_cv_prog_compiler_pic, $1)],
+  [_LT_TAGVAR(lt_cv_prog_compiler_pic, $1)=$_LT_TAGVAR(lt_prog_compiler_pic, $1)])
+_LT_TAGVAR(lt_prog_compiler_pic, $1)=$_LT_TAGVAR(lt_cv_prog_compiler_pic, $1)
+
+#
+# Check to make sure the PIC flag actually works.
+#
+if test -n "$_LT_TAGVAR(lt_prog_compiler_pic, $1)"; then
+  _LT_COMPILER_OPTION([if $compiler PIC flag $_LT_TAGVAR(lt_prog_compiler_pic, $1) works],
+    [_LT_TAGVAR(lt_cv_prog_compiler_pic_works, $1)],
+    [$_LT_TAGVAR(lt_prog_compiler_pic, $1)@&t at m4_if([$1],[],[ -DPIC],[m4_if([$1],[CXX],[ -DPIC],[])])], [],
+    [case $_LT_TAGVAR(lt_prog_compiler_pic, $1) in
+     "" | " "*) ;;
+     *) _LT_TAGVAR(lt_prog_compiler_pic, $1)=" $_LT_TAGVAR(lt_prog_compiler_pic, $1)" ;;
+     esac],
+    [_LT_TAGVAR(lt_prog_compiler_pic, $1)=
+     _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no])
+fi
+_LT_TAGDECL([pic_flag], [lt_prog_compiler_pic], [1],
+	[Additional compiler flags for building library objects])
+
+_LT_TAGDECL([wl], [lt_prog_compiler_wl], [1],
+	[How to pass a linker flag through the compiler])
+#
+# Check to make sure the static flag actually works.
+#
+wl=$_LT_TAGVAR(lt_prog_compiler_wl, $1) eval lt_tmp_static_flag=\"$_LT_TAGVAR(lt_prog_compiler_static, $1)\"
+_LT_LINKER_OPTION([if $compiler static flag $lt_tmp_static_flag works],
+  _LT_TAGVAR(lt_cv_prog_compiler_static_works, $1),
+  $lt_tmp_static_flag,
+  [],
+  [_LT_TAGVAR(lt_prog_compiler_static, $1)=])
+_LT_TAGDECL([link_static_flag], [lt_prog_compiler_static], [1],
+	[Compiler flag to prevent dynamic linking])
+])# _LT_COMPILER_PIC
+
+
+# _LT_LINKER_SHLIBS([TAGNAME])
+# ----------------------------
+# See if the linker supports building shared libraries.
+m4_defun([_LT_LINKER_SHLIBS],
+[AC_REQUIRE([LT_PATH_LD])dnl
+AC_REQUIRE([LT_PATH_NM])dnl
+m4_require([_LT_PATH_MANIFEST_TOOL])dnl
+m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+m4_require([_LT_DECL_EGREP])dnl
+m4_require([_LT_DECL_SED])dnl
+m4_require([_LT_CMD_GLOBAL_SYMBOLS])dnl
+m4_require([_LT_TAG_COMPILER])dnl
+AC_MSG_CHECKING([whether the $compiler linker ($LD) supports shared libraries])
+m4_if([$1], [CXX], [
+  _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
+  _LT_TAGVAR(exclude_expsyms, $1)=['_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*']
+  case $host_os in
+  aix[[4-9]]*)
+    # If we're using GNU nm, then we don't want the "-C" option.
+    # -C means demangle to AIX nm, but means don't demangle with GNU nm
+    # Also, AIX nm treats weak defined symbols like other global defined
+    # symbols, whereas GNU nm marks them as "W".
+    if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then
+      _LT_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
+    else
+      _LT_TAGVAR(export_symbols_cmds, $1)='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
+    fi
+    ;;
+  pw32*)
+    _LT_TAGVAR(export_symbols_cmds, $1)="$ltdll_cmds"
+    ;;
+  cygwin* | mingw* | cegcc*)
+    case $cc_basename in
+    cl*)
+      _LT_TAGVAR(exclude_expsyms, $1)='_NULL_IMPORT_DESCRIPTOR|_IMPORT_DESCRIPTOR_.*'
+      ;;
+    *)
+      _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1 DATA/;s/^.*[[ ]]__nm__\([[^ ]]*\)[[ ]][[^ ]]*/\1 DATA/;/^I[[ ]]/d;/^[[AITW]][[ ]]/s/.* //'\'' | sort | uniq > $export_symbols'
+      _LT_TAGVAR(exclude_expsyms, $1)=['[_]+GLOBAL_OFFSET_TABLE_|[_]+GLOBAL__[FID]_.*|[_]+head_[A-Za-z0-9_]+_dll|[A-Za-z0-9_]+_dll_iname']
+      ;;
+    esac
+    ;;
+  *)
+    _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
+    ;;
+  esac
+], [
+  runpath_var=
+  _LT_TAGVAR(allow_undefined_flag, $1)=
+  _LT_TAGVAR(always_export_symbols, $1)=no
+  _LT_TAGVAR(archive_cmds, $1)=
+  _LT_TAGVAR(archive_expsym_cmds, $1)=
+  _LT_TAGVAR(compiler_needs_object, $1)=no
+  _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no
+  _LT_TAGVAR(export_dynamic_flag_spec, $1)=
+  _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
+  _LT_TAGVAR(hardcode_automatic, $1)=no
+  _LT_TAGVAR(hardcode_direct, $1)=no
+  _LT_TAGVAR(hardcode_direct_absolute, $1)=no
+  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
+  _LT_TAGVAR(hardcode_libdir_separator, $1)=
+  _LT_TAGVAR(hardcode_minus_L, $1)=no
+  _LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported
+  _LT_TAGVAR(inherit_rpath, $1)=no
+  _LT_TAGVAR(link_all_deplibs, $1)=unknown
+  _LT_TAGVAR(module_cmds, $1)=
+  _LT_TAGVAR(module_expsym_cmds, $1)=
+  _LT_TAGVAR(old_archive_from_new_cmds, $1)=
+  _LT_TAGVAR(old_archive_from_expsyms_cmds, $1)=
+  _LT_TAGVAR(thread_safe_flag_spec, $1)=
+  _LT_TAGVAR(whole_archive_flag_spec, $1)=
+  # include_expsyms should be a list of space-separated symbols to be *always*
+  # included in the symbol list
+  _LT_TAGVAR(include_expsyms, $1)=
+  # exclude_expsyms can be an extended regexp of symbols to exclude
+  # it will be wrapped by ` (' and `)$', so one must not match beginning or
+  # end of line.  Example: `a|bc|.*d.*' will exclude the symbols `a' and `bc',
+  # as well as any symbol that contains `d'.
+  _LT_TAGVAR(exclude_expsyms, $1)=['_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*']
+  # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out
+  # platforms (ab)use it in PIC code, but their linkers get confused if
+  # the symbol is explicitly referenced.  Since portable code cannot
+  # rely on this symbol name, it's probably fine to never include it in
+  # preloaded symbol tables.
+  # Exclude shared library initialization/finalization symbols.
+dnl Note also adjust exclude_expsyms for C++ above.
+  extract_expsyms_cmds=
+
+  case $host_os in
+  cygwin* | mingw* | pw32* | cegcc*)
+    # FIXME: the MSVC++ port hasn't been tested in a loooong time
+    # When not using gcc, we currently assume that we are using
+    # Microsoft Visual C++.
+    if test "$GCC" != yes; then
+      with_gnu_ld=no
+    fi
+    ;;
+  interix*)
+    # we just hope/assume this is gcc and not c89 (= MSVC++)
+    with_gnu_ld=yes
+    ;;
+  openbsd*)
+    with_gnu_ld=no
+    ;;
+  esac
+
+  _LT_TAGVAR(ld_shlibs, $1)=yes
+
+  # On some targets, GNU ld is compatible enough with the native linker
+  # that we're better off using the native interface for both.
+  lt_use_gnu_ld_interface=no
+  if test "$with_gnu_ld" = yes; then
+    case $host_os in
+      aix*)
+	# The AIX port of GNU ld has always aspired to compatibility
+	# with the native linker.  However, as the warning in the GNU ld
+	# block says, versions before 2.19.5* couldn't really create working
+	# shared libraries, regardless of the interface used.
+	case `$LD -v 2>&1` in
+	  *\ \(GNU\ Binutils\)\ 2.19.5*) ;;
+	  *\ \(GNU\ Binutils\)\ 2.[[2-9]]*) ;;
+	  *\ \(GNU\ Binutils\)\ [[3-9]]*) ;;
+	  *)
+	    lt_use_gnu_ld_interface=yes
+	    ;;
+	esac
+	;;
+      *)
+	lt_use_gnu_ld_interface=yes
+	;;
+    esac
+  fi
+
+  if test "$lt_use_gnu_ld_interface" = yes; then
+    # If archive_cmds runs LD, not CC, wlarc should be empty
+    wlarc='${wl}'
+
+    # Set some defaults for GNU ld with shared library support. These
+    # are reset later if shared libraries are not supported. Putting them
+    # here allows them to be overridden if necessary.
+    runpath_var=LD_RUN_PATH
+    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
+    # ancient GNU ld didn't support --whole-archive et. al.
+    if $LD --help 2>&1 | $GREP 'no-whole-archive' > /dev/null; then
+      _LT_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
+    else
+      _LT_TAGVAR(whole_archive_flag_spec, $1)=
+    fi
+    supports_anon_versioning=no
+    case `$LD -v 2>&1` in
+      *GNU\ gold*) supports_anon_versioning=yes ;;
+      *\ [[01]].* | *\ 2.[[0-9]].* | *\ 2.10.*) ;; # catch versions < 2.11
+      *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ...
+      *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ...
+      *\ 2.11.*) ;; # other 2.11 versions
+      *) supports_anon_versioning=yes ;;
+    esac
+
+    # See if GNU ld supports shared libraries.
+    case $host_os in
+    aix[[3-9]]*)
+      # On AIX/PPC, the GNU linker is very broken
+      if test "$host_cpu" != ia64; then
+	_LT_TAGVAR(ld_shlibs, $1)=no
+	cat <<_LT_EOF 1>&2
+
+*** Warning: the GNU linker, at least up to release 2.19, is reported
+*** to be unable to reliably create shared libraries on AIX.
+*** Therefore, libtool is disabling shared libraries support.  If you
+*** really care for shared libraries, you may want to install binutils
+*** 2.20 or above, or modify your PATH so that a non-GNU linker is found.
+*** You will then need to restart the configuration process.
+
+_LT_EOF
+      fi
+      ;;
+
+    amigaos*)
+      case $host_cpu in
+      powerpc)
+            # see comment about AmigaOS4 .so support
+            _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+            _LT_TAGVAR(archive_expsym_cmds, $1)=''
+        ;;
+      m68k)
+            _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)'
+            _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+            _LT_TAGVAR(hardcode_minus_L, $1)=yes
+        ;;
+      esac
+      ;;
+
+    beos*)
+      if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
+	_LT_TAGVAR(allow_undefined_flag, $1)=unsupported
+	# Joseph Beckenbach <jrb3 at best.com> says some releases of gcc
+	# support --undefined.  This deserves some investigation.  FIXME
+	_LT_TAGVAR(archive_cmds, $1)='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+      else
+	_LT_TAGVAR(ld_shlibs, $1)=no
+      fi
+      ;;
+
+    cygwin* | mingw* | pw32* | cegcc*)
+      # _LT_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless,
+      # as there is no search path for DLLs.
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-all-symbols'
+      _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
+      _LT_TAGVAR(always_export_symbols, $1)=no
+      _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
+      _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1 DATA/;s/^.*[[ ]]__nm__\([[^ ]]*\)[[ ]][[^ ]]*/\1 DATA/;/^I[[ ]]/d;/^[[AITW]][[ ]]/s/.* //'\'' | sort | uniq > $export_symbols'
+      _LT_TAGVAR(exclude_expsyms, $1)=['[_]+GLOBAL_OFFSET_TABLE_|[_]+GLOBAL__[FID]_.*|[_]+head_[A-Za-z0-9_]+_dll|[A-Za-z0-9_]+_dll_iname']
+
+      if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then
+        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+	# If the export-symbols file already is a .def file (1st line
+	# is EXPORTS), use it as is; otherwise, prepend...
+	_LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
+	  cp $export_symbols $output_objdir/$soname.def;
+	else
+	  echo EXPORTS > $output_objdir/$soname.def;
+	  cat $export_symbols >> $output_objdir/$soname.def;
+	fi~
+	$CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+      else
+	_LT_TAGVAR(ld_shlibs, $1)=no
+      fi
+      ;;
+
+    haiku*)
+      _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+      _LT_TAGVAR(link_all_deplibs, $1)=yes
+      ;;
+
+    interix[[3-9]]*)
+      _LT_TAGVAR(hardcode_direct, $1)=no
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+      # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc.
+      # Instead, shared libraries are loaded at an image base (0x10000000 by
+      # default) and relocated if they conflict, which is a slow very memory
+      # consuming and fragmenting process.  To avoid this, we pick a random,
+      # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link
+      # time.  Moving up from 0x10000000 also allows more sbrk(2) space.
+      _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
+      _LT_TAGVAR(archive_expsym_cmds, $1)='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
+      ;;
+
+    gnu* | linux* | tpf* | k*bsd*-gnu | kopensolaris*-gnu)
+      tmp_diet=no
+      if test "$host_os" = linux-dietlibc; then
+	case $cc_basename in
+	  diet\ *) tmp_diet=yes;;	# linux-dietlibc with static linking (!diet-dyn)
+	esac
+      fi
+      if $LD --help 2>&1 | $EGREP ': supported targets:.* elf' > /dev/null \
+	 && test "$tmp_diet" = no
+      then
+	tmp_addflag=' $pic_flag'
+	tmp_sharedflag='-shared'
+	case $cc_basename,$host_cpu in
+        pgcc*)				# Portland Group C compiler
+	  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
+	  tmp_addflag=' $pic_flag'
+	  ;;
+	pgf77* | pgf90* | pgf95* | pgfortran*)
+					# Portland Group f77 and f90 compilers
+	  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
+	  tmp_addflag=' $pic_flag -Mnomain' ;;
+	ecc*,ia64* | icc*,ia64*)	# Intel C compiler on ia64
+	  tmp_addflag=' -i_dynamic' ;;
+	efc*,ia64* | ifort*,ia64*)	# Intel Fortran compiler on ia64
+	  tmp_addflag=' -i_dynamic -nofor_main' ;;
+	ifc* | ifort*)			# Intel Fortran compiler
+	  tmp_addflag=' -nofor_main' ;;
+	lf95*)				# Lahey Fortran 8.1
+	  _LT_TAGVAR(whole_archive_flag_spec, $1)=
+	  tmp_sharedflag='--shared' ;;
+	xl[[cC]]* | bgxl[[cC]]* | mpixl[[cC]]*) # IBM XL C 8.0 on PPC (deal with xlf below)
+	  tmp_sharedflag='-qmkshrobj'
+	  tmp_addflag= ;;
+	nvcc*)	# Cuda Compiler Driver 2.2
+	  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
+	  _LT_TAGVAR(compiler_needs_object, $1)=yes
+	  ;;
+	esac
+	case `$CC -V 2>&1 | sed 5q` in
+	*Sun\ C*)			# Sun C 5.9
+	  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
+	  _LT_TAGVAR(compiler_needs_object, $1)=yes
+	  tmp_sharedflag='-G' ;;
+	*Sun\ F*)			# Sun Fortran 8.3
+	  tmp_sharedflag='-G' ;;
+	esac
+	_LT_TAGVAR(archive_cmds, $1)='$CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+
+        if test "x$supports_anon_versioning" = xyes; then
+          _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~
+	    cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
+	    echo "local: *; };" >> $output_objdir/$libname.ver~
+	    $CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib'
+        fi
+
+	case $cc_basename in
+	xlf* | bgf* | bgxlf* | mpixlf*)
+	  # IBM XL Fortran 10.1 on PPC cannot create shared libs itself
+	  _LT_TAGVAR(whole_archive_flag_spec, $1)='--whole-archive$convenience --no-whole-archive'
+	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+	  _LT_TAGVAR(archive_cmds, $1)='$LD -shared $libobjs $deplibs $linker_flags -soname $soname -o $lib'
+	  if test "x$supports_anon_versioning" = xyes; then
+	    _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~
+	      cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
+	      echo "local: *; };" >> $output_objdir/$libname.ver~
+	      $LD -shared $libobjs $deplibs $linker_flags -soname $soname -version-script $output_objdir/$libname.ver -o $lib'
+	  fi
+	  ;;
+	esac
+      else
+        _LT_TAGVAR(ld_shlibs, $1)=no
+      fi
+      ;;
+
+    netbsd*)
+      if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
+	_LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib'
+	wlarc=
+      else
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+      fi
+      ;;
+
+    solaris*)
+      if $LD -v 2>&1 | $GREP 'BFD 2\.8' > /dev/null; then
+	_LT_TAGVAR(ld_shlibs, $1)=no
+	cat <<_LT_EOF 1>&2
+
+*** Warning: The releases 2.8.* of the GNU linker cannot reliably
+*** create shared libraries on Solaris systems.  Therefore, libtool
+*** is disabling shared libraries support.  We urge you to upgrade GNU
+*** binutils to release 2.9.1 or newer.  Another option is to modify
+*** your PATH or compiler configuration so that the native linker is
+*** used, and then restart.
+
+_LT_EOF
+      elif $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+      else
+	_LT_TAGVAR(ld_shlibs, $1)=no
+      fi
+      ;;
+
+    sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX*)
+      case `$LD -v 2>&1` in
+        *\ [[01]].* | *\ 2.[[0-9]].* | *\ 2.1[[0-5]].*)
+	_LT_TAGVAR(ld_shlibs, $1)=no
+	cat <<_LT_EOF 1>&2
+
+*** Warning: Releases of the GNU linker prior to 2.16.91.0.3 can not
+*** reliably create shared libraries on SCO systems.  Therefore, libtool
+*** is disabling shared libraries support.  We urge you to upgrade GNU
+*** binutils to release 2.16.91.0.3 or newer.  Another option is to modify
+*** your PATH or compiler configuration so that the native linker is
+*** used, and then restart.
+
+_LT_EOF
+	;;
+	*)
+	  # For security reasons, it is highly recommended that you always
+	  # use absolute paths for naming shared libraries, and exclude the
+	  # DT_RUNPATH tag from executables and libraries.  But doing so
+	  # requires that you compile everything twice, which is a pain.
+	  if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+	    _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+	  else
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	  fi
+	;;
+      esac
+      ;;
+
+    sunos4*)
+      _LT_TAGVAR(archive_cmds, $1)='$LD -assert pure-text -Bshareable -o $lib $libobjs $deplibs $linker_flags'
+      wlarc=
+      _LT_TAGVAR(hardcode_direct, $1)=yes
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    *)
+      if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+      else
+	_LT_TAGVAR(ld_shlibs, $1)=no
+      fi
+      ;;
+    esac
+
+    if test "$_LT_TAGVAR(ld_shlibs, $1)" = no; then
+      runpath_var=
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
+      _LT_TAGVAR(export_dynamic_flag_spec, $1)=
+      _LT_TAGVAR(whole_archive_flag_spec, $1)=
+    fi
+  else
+    # PORTME fill in a description of your system's linker (not GNU ld)
+    case $host_os in
+    aix3*)
+      _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
+      _LT_TAGVAR(always_export_symbols, $1)=yes
+      _LT_TAGVAR(archive_expsym_cmds, $1)='$LD -o $output_objdir/$soname $libobjs $deplibs $linker_flags -bE:$export_symbols -T512 -H512 -bM:SRE~$AR $AR_FLAGS $lib $output_objdir/$soname'
+      # Note: this linker hardcodes the directories in LIBPATH if there
+      # are no directories specified by -L.
+      _LT_TAGVAR(hardcode_minus_L, $1)=yes
+      if test "$GCC" = yes && test -z "$lt_prog_compiler_static"; then
+	# Neither direct hardcoding nor static linking is supported with a
+	# broken collect2.
+	_LT_TAGVAR(hardcode_direct, $1)=unsupported
+      fi
+      ;;
+
+    aix[[4-9]]*)
+      if test "$host_cpu" = ia64; then
+	# On IA64, the linker does run time linking by default, so we don't
+	# have to do anything special.
+	aix_use_runtimelinking=no
+	exp_sym_flag='-Bexport'
+	no_entry_flag=""
+      else
+	# If we're using GNU nm, then we don't want the "-C" option.
+	# -C means demangle to AIX nm, but means don't demangle with GNU nm
+	# Also, AIX nm treats weak defined symbols like other global
+	# defined symbols, whereas GNU nm marks them as "W".
+	if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then
+	  _LT_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
+	else
+	  _LT_TAGVAR(export_symbols_cmds, $1)='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
+	fi
+	aix_use_runtimelinking=no
+
+	# Test if we are trying to use run time linking or normal
+	# AIX style linking. If -brtl is somewhere in LDFLAGS, we
+	# need to do runtime linking.
+	case $host_os in aix4.[[23]]|aix4.[[23]].*|aix[[5-9]]*)
+	  for ld_flag in $LDFLAGS; do
+	  if (test $ld_flag = "-brtl" || test $ld_flag = "-Wl,-brtl"); then
+	    aix_use_runtimelinking=yes
+	    break
+	  fi
+	  done
+	  ;;
+	esac
+
+	exp_sym_flag='-bexport'
+	no_entry_flag='-bnoentry'
+      fi
+
+      # When large executables or shared objects are built, AIX ld can
+      # have problems creating the table of contents.  If linking a library
+      # or program results in "error TOC overflow" add -mminimal-toc to
+      # CXXFLAGS/CFLAGS for g++/gcc.  In the cases where that is not
+      # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS.
+
+      _LT_TAGVAR(archive_cmds, $1)=''
+      _LT_TAGVAR(hardcode_direct, $1)=yes
+      _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
+      _LT_TAGVAR(hardcode_libdir_separator, $1)=':'
+      _LT_TAGVAR(link_all_deplibs, $1)=yes
+      _LT_TAGVAR(file_list_spec, $1)='${wl}-f,'
+
+      if test "$GCC" = yes; then
+	case $host_os in aix4.[[012]]|aix4.[[012]].*)
+	# We only want to do this on AIX 4.2 and lower, the check
+	# below for broken collect2 doesn't work under 4.3+
+	  collect2name=`${CC} -print-prog-name=collect2`
+	  if test -f "$collect2name" &&
+	   strings "$collect2name" | $GREP resolve_lib_name >/dev/null
+	  then
+	  # We have reworked collect2
+	  :
+	  else
+	  # We have old collect2
+	  _LT_TAGVAR(hardcode_direct, $1)=unsupported
+	  # It fails to find uninstalled libraries when the uninstalled
+	  # path is not listed in the libpath.  Setting hardcode_minus_L
+	  # to unsupported forces relinking
+	  _LT_TAGVAR(hardcode_minus_L, $1)=yes
+	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+	  _LT_TAGVAR(hardcode_libdir_separator, $1)=
+	  fi
+	  ;;
+	esac
+	shared_flag='-shared'
+	if test "$aix_use_runtimelinking" = yes; then
+	  shared_flag="$shared_flag "'${wl}-G'
+	fi
+      else
+	# not using gcc
+	if test "$host_cpu" = ia64; then
+	# VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release
+	# chokes on -Wl,-G. The following line is correct:
+	  shared_flag='-G'
+	else
+	  if test "$aix_use_runtimelinking" = yes; then
+	    shared_flag='${wl}-G'
+	  else
+	    shared_flag='${wl}-bM:SRE'
+	  fi
+	fi
+      fi
+
+      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-bexpall'
+      # It seems that -bexpall does not export symbols beginning with
+      # underscore (_), so it is better to generate a list of symbols to export.
+      _LT_TAGVAR(always_export_symbols, $1)=yes
+      if test "$aix_use_runtimelinking" = yes; then
+	# Warning - without using the other runtime loading flags (-brtl),
+	# -berok will link without error, but may produce a broken library.
+	_LT_TAGVAR(allow_undefined_flag, $1)='-berok'
+        # Determine the default libpath from the value encoded in an
+        # empty executable.
+        _LT_SYS_MODULE_PATH_AIX([$1])
+        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
+        _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then func_echo_all "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag"
+      else
+	if test "$host_cpu" = ia64; then
+	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $libdir:/usr/lib:/lib'
+	  _LT_TAGVAR(allow_undefined_flag, $1)="-z nodefs"
+	  _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols"
+	else
+	 # Determine the default libpath from the value encoded in an
+	 # empty executable.
+	 _LT_SYS_MODULE_PATH_AIX([$1])
+	 _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
+	  # Warning - without using the other run time loading flags,
+	  # -berok will link without error, but may produce a broken library.
+	  _LT_TAGVAR(no_undefined_flag, $1)=' ${wl}-bernotok'
+	  _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-berok'
+	  if test "$with_gnu_ld" = yes; then
+	    # We only use this code for GNU lds that support --whole-archive.
+	    _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive$convenience ${wl}--no-whole-archive'
+	  else
+	    # Exported symbols can be pulled into shared objects from archives
+	    _LT_TAGVAR(whole_archive_flag_spec, $1)='$convenience'
+	  fi
+	  _LT_TAGVAR(archive_cmds_need_lc, $1)=yes
+	  # This is similar to how AIX traditionally builds its shared libraries.
+	  _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname'
+	fi
+      fi
+      ;;
+
+    amigaos*)
+      case $host_cpu in
+      powerpc)
+            # see comment about AmigaOS4 .so support
+            _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+            _LT_TAGVAR(archive_expsym_cmds, $1)=''
+        ;;
+      m68k)
+            _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)'
+            _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+            _LT_TAGVAR(hardcode_minus_L, $1)=yes
+        ;;
+      esac
+      ;;
+
+    bsdi[[45]]*)
+      _LT_TAGVAR(export_dynamic_flag_spec, $1)=-rdynamic
+      ;;
+
+    cygwin* | mingw* | pw32* | cegcc*)
+      # When not using gcc, we currently assume that we are using
+      # Microsoft Visual C++.
+      # hardcode_libdir_flag_spec is actually meaningless, as there is
+      # no search path for DLLs.
+      case $cc_basename in
+      cl*)
+	# Native MSVC
+	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)=' '
+	_LT_TAGVAR(allow_undefined_flag, $1)=unsupported
+	_LT_TAGVAR(always_export_symbols, $1)=yes
+	_LT_TAGVAR(file_list_spec, $1)='@'
+	# Tell ltmain to make .lib files, not .a files.
+	libext=lib
+	# Tell ltmain to make .dll files, not .so files.
+	shrext_cmds=".dll"
+	# FIXME: Setting linknames here is a bad hack.
+	_LT_TAGVAR(archive_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-dll~linknames='
+	_LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
+	    sed -n -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' -e '1\\\!p' < $export_symbols > $output_objdir/$soname.exp;
+	  else
+	    sed -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' < $export_symbols > $output_objdir/$soname.exp;
+	  fi~
+	  $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~
+	  linknames='
+	# The linker will not automatically build a static lib if we build a DLL.
+	# _LT_TAGVAR(old_archive_from_new_cmds, $1)='true'
+	_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
+	_LT_TAGVAR(exclude_expsyms, $1)='_NULL_IMPORT_DESCRIPTOR|_IMPORT_DESCRIPTOR_.*'
+	_LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1,DATA/'\'' | $SED -e '\''/^[[AITW]][[ ]]/s/.*[[ ]]//'\'' | sort | uniq > $export_symbols'
+	# Don't use ranlib
+	_LT_TAGVAR(old_postinstall_cmds, $1)='chmod 644 $oldlib'
+	_LT_TAGVAR(postlink_cmds, $1)='lt_outputfile="@OUTPUT@"~
+	  lt_tool_outputfile="@TOOL_OUTPUT@"~
+	  case $lt_outputfile in
+	    *.exe|*.EXE) ;;
+	    *)
+	      lt_outputfile="$lt_outputfile.exe"
+	      lt_tool_outputfile="$lt_tool_outputfile.exe"
+	      ;;
+	  esac~
+	  if test "$MANIFEST_TOOL" != ":" && test -f "$lt_outputfile.manifest"; then
+	    $MANIFEST_TOOL -manifest "$lt_tool_outputfile.manifest" -outputresource:"$lt_tool_outputfile" || exit 1;
+	    $RM "$lt_outputfile.manifest";
+	  fi'
+	;;
+      *)
+	# Assume MSVC wrapper
+	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)=' '
+	_LT_TAGVAR(allow_undefined_flag, $1)=unsupported
+	# Tell ltmain to make .lib files, not .a files.
+	libext=lib
+	# Tell ltmain to make .dll files, not .so files.
+	shrext_cmds=".dll"
+	# FIXME: Setting linknames here is a bad hack.
+	_LT_TAGVAR(archive_cmds, $1)='$CC -o $lib $libobjs $compiler_flags `func_echo_all "$deplibs" | $SED '\''s/ -lc$//'\''` -link -dll~linknames='
+	# The linker will automatically build a .lib file if we build a DLL.
+	_LT_TAGVAR(old_archive_from_new_cmds, $1)='true'
+	# FIXME: Should let the user specify the lib program.
+	_LT_TAGVAR(old_archive_cmds, $1)='lib -OUT:$oldlib$oldobjs$old_deplibs'
+	_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
+	;;
+      esac
+      ;;
+
+    darwin* | rhapsody*)
+      _LT_DARWIN_LINKER_FEATURES($1)
+      ;;
+
+    dgux*)
+      _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor
+    # support.  Future versions do this automatically, but an explicit c++rt0.o
+    # does not break anything, and helps significantly (at the cost of a little
+    # extra space).
+    freebsd2.2*)
+      _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags /usr/lib/c++rt0.o'
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+      _LT_TAGVAR(hardcode_direct, $1)=yes
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    # Unfortunately, older versions of FreeBSD 2 do not have this feature.
+    freebsd2.*)
+      _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'
+      _LT_TAGVAR(hardcode_direct, $1)=yes
+      _LT_TAGVAR(hardcode_minus_L, $1)=yes
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    # FreeBSD 3 and greater uses gcc -shared to do shared libraries.
+    freebsd* | dragonfly*)
+      _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+      _LT_TAGVAR(hardcode_direct, $1)=yes
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    hpux9*)
+      if test "$GCC" = yes; then
+	_LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -shared $pic_flag ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+      else
+	_LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+      fi
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
+      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+      _LT_TAGVAR(hardcode_direct, $1)=yes
+
+      # hardcode_minus_L: Not really in the search PATH,
+      # but as the default location of the library.
+      _LT_TAGVAR(hardcode_minus_L, $1)=yes
+      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+      ;;
+
+    hpux10*)
+      if test "$GCC" = yes && test "$with_gnu_ld" = no; then
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
+      else
+	_LT_TAGVAR(archive_cmds, $1)='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags'
+      fi
+      if test "$with_gnu_ld" = no; then
+	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
+	_LT_TAGVAR(hardcode_libdir_separator, $1)=:
+	_LT_TAGVAR(hardcode_direct, $1)=yes
+	_LT_TAGVAR(hardcode_direct_absolute, $1)=yes
+	_LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+	# hardcode_minus_L: Not really in the search PATH,
+	# but as the default location of the library.
+	_LT_TAGVAR(hardcode_minus_L, $1)=yes
+      fi
+      ;;
+
+    hpux11*)
+      if test "$GCC" = yes && test "$with_gnu_ld" = no; then
+	case $host_cpu in
+	hppa*64*)
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
+	  ;;
+	ia64*)
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
+	  ;;
+	*)
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
+	  ;;
+	esac
+      else
+	case $host_cpu in
+	hppa*64*)
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
+	  ;;
+	ia64*)
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
+	  ;;
+	*)
+	m4_if($1, [], [
+	  # Older versions of the 11.00 compiler do not understand -b yet
+	  # (HP92453-01 A.11.01.20 doesn't, HP92453-01 B.11.X.35175-35176.GP does)
+	  _LT_LINKER_OPTION([if $CC understands -b],
+	    _LT_TAGVAR(lt_cv_prog_compiler__b, $1), [-b],
+	    [_LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'],
+	    [_LT_TAGVAR(archive_cmds, $1)='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags'])],
+	  [_LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'])
+	  ;;
+	esac
+      fi
+      if test "$with_gnu_ld" = no; then
+	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
+	_LT_TAGVAR(hardcode_libdir_separator, $1)=:
+
+	case $host_cpu in
+	hppa*64*|ia64*)
+	  _LT_TAGVAR(hardcode_direct, $1)=no
+	  _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+	  ;;
+	*)
+	  _LT_TAGVAR(hardcode_direct, $1)=yes
+	  _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
+	  _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+
+	  # hardcode_minus_L: Not really in the search PATH,
+	  # but as the default location of the library.
+	  _LT_TAGVAR(hardcode_minus_L, $1)=yes
+	  ;;
+	esac
+      fi
+      ;;
+
+    irix5* | irix6* | nonstopux*)
+      if test "$GCC" = yes; then
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+	# Try to use the -exported_symbol ld option, if it does not
+	# work, assume that -exports_file does not work either and
+	# implicitly export all symbols.
+	# This should be the same for all languages, so no per-tag cache variable.
+	AC_CACHE_CHECK([whether the $host_os linker accepts -exported_symbol],
+	  [lt_cv_irix_exported_symbol],
+	  [save_LDFLAGS="$LDFLAGS"
+	   LDFLAGS="$LDFLAGS -shared ${wl}-exported_symbol ${wl}foo ${wl}-update_registry ${wl}/dev/null"
+	   AC_LINK_IFELSE(
+	     [AC_LANG_SOURCE(
+	        [AC_LANG_CASE([C], [[int foo (void) { return 0; }]],
+			      [C++], [[int foo (void) { return 0; }]],
+			      [Fortran 77], [[
+      subroutine foo
+      end]],
+			      [Fortran], [[
+      subroutine foo
+      end]])])],
+	      [lt_cv_irix_exported_symbol=yes],
+	      [lt_cv_irix_exported_symbol=no])
+           LDFLAGS="$save_LDFLAGS"])
+	if test "$lt_cv_irix_exported_symbol" = yes; then
+          _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations ${wl}-exports_file ${wl}$export_symbols -o $lib'
+	fi
+      else
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -exports_file $export_symbols -o $lib'
+      fi
+      _LT_TAGVAR(archive_cmds_need_lc, $1)='no'
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+      _LT_TAGVAR(inherit_rpath, $1)=yes
+      _LT_TAGVAR(link_all_deplibs, $1)=yes
+      ;;
+
+    netbsd*)
+      if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
+	_LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'  # a.out
+      else
+	_LT_TAGVAR(archive_cmds, $1)='$LD -shared -o $lib $libobjs $deplibs $linker_flags'      # ELF
+      fi
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+      _LT_TAGVAR(hardcode_direct, $1)=yes
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    newsos6)
+      _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+      _LT_TAGVAR(hardcode_direct, $1)=yes
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    *nto* | *qnx*)
+      ;;
+
+    openbsd*)
+      if test -f /usr/libexec/ld.so; then
+	_LT_TAGVAR(hardcode_direct, $1)=yes
+	_LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+	_LT_TAGVAR(hardcode_direct_absolute, $1)=yes
+	if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
+	  _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-retain-symbols-file,$export_symbols'
+	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+	  _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+	else
+	  case $host_os in
+	   openbsd[[01]].* | openbsd2.[[0-7]] | openbsd2.[[0-7]].*)
+	     _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'
+	     _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+	     ;;
+	   *)
+	     _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
+	     _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+	     ;;
+	  esac
+	fi
+      else
+	_LT_TAGVAR(ld_shlibs, $1)=no
+      fi
+      ;;
+
+    os2*)
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+      _LT_TAGVAR(hardcode_minus_L, $1)=yes
+      _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
+      _LT_TAGVAR(archive_cmds, $1)='$ECHO "LIBRARY $libname INITINSTANCE" > $output_objdir/$libname.def~$ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~echo DATA >> $output_objdir/$libname.def~echo " SINGLE NONSHARED" >> $output_objdir/$libname.def~echo EXPORTS >> $output_objdir/$libname.def~emxexp $libobjs >> $output_objdir/$libname.def~$CC -Zdll -Zcrtdll -o $lib $libobjs $deplibs $compiler_flags $output_objdir/$libname.def'
+      _LT_TAGVAR(old_archive_from_new_cmds, $1)='emximp -o $output_objdir/$libname.a $output_objdir/$libname.def'
+      ;;
+
+    osf3*)
+      if test "$GCC" = yes; then
+	_LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+      else
+	_LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*'
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
+      fi
+      _LT_TAGVAR(archive_cmds_need_lc, $1)='no'
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+      ;;
+
+    osf4* | osf5*)	# as osf3* with the addition of -msym flag
+      if test "$GCC" = yes; then
+	_LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $pic_flag $libobjs $deplibs $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+      else
+	_LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*'
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -msym -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; printf "%s\\n" "-hidden">> $lib.exp~
+	$CC -shared${allow_undefined_flag} ${wl}-input ${wl}$lib.exp $compiler_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && $ECHO "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib~$RM $lib.exp'
+
+	# Both c and cxx compiler support -rpath directly
+	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir'
+      fi
+      _LT_TAGVAR(archive_cmds_need_lc, $1)='no'
+      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+      ;;
+
+    solaris*)
+      _LT_TAGVAR(no_undefined_flag, $1)=' -z defs'
+      if test "$GCC" = yes; then
+	wlarc='${wl}'
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag ${wl}-z ${wl}text ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
+	  $CC -shared $pic_flag ${wl}-z ${wl}text ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp'
+      else
+	case `$CC -V 2>&1` in
+	*"Compilers 5.0"*)
+	  wlarc=''
+	  _LT_TAGVAR(archive_cmds, $1)='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags'
+	  _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
+	  $LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$RM $lib.exp'
+	  ;;
+	*)
+	  wlarc='${wl}'
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $compiler_flags'
+	  _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
+	  $CC -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp'
+	  ;;
+	esac
+      fi
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      case $host_os in
+      solaris2.[[0-5]] | solaris2.[[0-5]].*) ;;
+      *)
+	# The compiler driver will combine and reorder linker options,
+	# but understands `-z linker_flag'.  GCC discards it without `$wl',
+	# but is careful enough not to reorder.
+	# Supported since Solaris 2.6 (maybe 2.5.1?)
+	if test "$GCC" = yes; then
+	  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract'
+	else
+	  _LT_TAGVAR(whole_archive_flag_spec, $1)='-z allextract$convenience -z defaultextract'
+	fi
+	;;
+      esac
+      _LT_TAGVAR(link_all_deplibs, $1)=yes
+      ;;
+
+    sunos4*)
+      if test "x$host_vendor" = xsequent; then
+	# Use $CC to link under sequent, because it throws in some extra .o
+	# files that make .init and .fini sections work.
+	_LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h $soname -o $lib $libobjs $deplibs $compiler_flags'
+      else
+	_LT_TAGVAR(archive_cmds, $1)='$LD -assert pure-text -Bstatic -o $lib $libobjs $deplibs $linker_flags'
+      fi
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+      _LT_TAGVAR(hardcode_direct, $1)=yes
+      _LT_TAGVAR(hardcode_minus_L, $1)=yes
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    sysv4)
+      case $host_vendor in
+	sni)
+	  _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+	  _LT_TAGVAR(hardcode_direct, $1)=yes # is this really true???
+	;;
+	siemens)
+	  ## LD is ld it makes a PLAMLIB
+	  ## CC just makes a GrossModule.
+	  _LT_TAGVAR(archive_cmds, $1)='$LD -G -o $lib $libobjs $deplibs $linker_flags'
+	  _LT_TAGVAR(reload_cmds, $1)='$CC -r -o $output$reload_objs'
+	  _LT_TAGVAR(hardcode_direct, $1)=no
+        ;;
+	motorola)
+	  _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+	  _LT_TAGVAR(hardcode_direct, $1)=no #Motorola manual says yes, but my tests say they lie
+	;;
+      esac
+      runpath_var='LD_RUN_PATH'
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    sysv4.3*)
+      _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      _LT_TAGVAR(export_dynamic_flag_spec, $1)='-Bexport'
+      ;;
+
+    sysv4*MP*)
+      if test -d /usr/nec; then
+	_LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+	_LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+	runpath_var=LD_RUN_PATH
+	hardcode_runpath_var=yes
+	_LT_TAGVAR(ld_shlibs, $1)=yes
+      fi
+      ;;
+
+    sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[[01]].[[10]]* | unixware7* | sco3.2v5.0.[[024]]*)
+      _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
+      _LT_TAGVAR(archive_cmds_need_lc, $1)=no
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      runpath_var='LD_RUN_PATH'
+
+      if test "$GCC" = yes; then
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+      else
+	_LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+      fi
+      ;;
+
+    sysv5* | sco3.2v5* | sco5v6*)
+      # Note: We can NOT use -z defs as we might desire, because we do not
+      # link with -lc, and that would cause any symbols used from libc to
+      # always be unresolved, which means just about no library would
+      # ever link correctly.  If we're not using GNU ld we use -z text
+      # though, which does catch some bad symbols but isn't as heavy-handed
+      # as -z defs.
+      _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
+      _LT_TAGVAR(allow_undefined_flag, $1)='${wl}-z,nodefs'
+      _LT_TAGVAR(archive_cmds_need_lc, $1)=no
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R,$libdir'
+      _LT_TAGVAR(hardcode_libdir_separator, $1)=':'
+      _LT_TAGVAR(link_all_deplibs, $1)=yes
+      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Bexport'
+      runpath_var='LD_RUN_PATH'
+
+      if test "$GCC" = yes; then
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+      else
+	_LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+      fi
+      ;;
+
+    uts4*)
+      _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    *)
+      _LT_TAGVAR(ld_shlibs, $1)=no
+      ;;
+    esac
+
+    if test x$host_vendor = xsni; then
+      case $host in
+      sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*)
+	_LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Blargedynsym'
+	;;
+      esac
+    fi
+  fi
+])
+AC_MSG_RESULT([$_LT_TAGVAR(ld_shlibs, $1)])
+test "$_LT_TAGVAR(ld_shlibs, $1)" = no && can_build_shared=no
+
+_LT_TAGVAR(with_gnu_ld, $1)=$with_gnu_ld
+
+_LT_DECL([], [libext], [0], [Old archive suffix (normally "a")])dnl
+_LT_DECL([], [shrext_cmds], [1], [Shared library suffix (normally ".so")])dnl
+_LT_DECL([], [extract_expsyms_cmds], [2],
+    [The commands to extract the exported symbol list from a shared archive])
+
+#
+# Do we need to explicitly link libc?
+#
+case "x$_LT_TAGVAR(archive_cmds_need_lc, $1)" in
+x|xyes)
+  # Assume -lc should be added
+  _LT_TAGVAR(archive_cmds_need_lc, $1)=yes
+
+  if test "$enable_shared" = yes && test "$GCC" = yes; then
+    case $_LT_TAGVAR(archive_cmds, $1) in
+    *'~'*)
+      # FIXME: we may have to deal with multi-command sequences.
+      ;;
+    '$CC '*)
+      # Test whether the compiler implicitly links with -lc since on some
+      # systems, -lgcc has to come before -lc. If gcc already passes -lc
+      # to ld, don't add -lc before -lgcc.
+      AC_CACHE_CHECK([whether -lc should be explicitly linked in],
+	[lt_cv_]_LT_TAGVAR(archive_cmds_need_lc, $1),
+	[$RM conftest*
+	echo "$lt_simple_compile_test_code" > conftest.$ac_ext
+
+	if AC_TRY_EVAL(ac_compile) 2>conftest.err; then
+	  soname=conftest
+	  lib=conftest
+	  libobjs=conftest.$ac_objext
+	  deplibs=
+	  wl=$_LT_TAGVAR(lt_prog_compiler_wl, $1)
+	  pic_flag=$_LT_TAGVAR(lt_prog_compiler_pic, $1)
+	  compiler_flags=-v
+	  linker_flags=-v
+	  verstring=
+	  output_objdir=.
+	  libname=conftest
+	  lt_save_allow_undefined_flag=$_LT_TAGVAR(allow_undefined_flag, $1)
+	  _LT_TAGVAR(allow_undefined_flag, $1)=
+	  if AC_TRY_EVAL(_LT_TAGVAR(archive_cmds, $1) 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1)
+	  then
+	    lt_cv_[]_LT_TAGVAR(archive_cmds_need_lc, $1)=no
+	  else
+	    lt_cv_[]_LT_TAGVAR(archive_cmds_need_lc, $1)=yes
+	  fi
+	  _LT_TAGVAR(allow_undefined_flag, $1)=$lt_save_allow_undefined_flag
+	else
+	  cat conftest.err 1>&5
+	fi
+	$RM conftest*
+	])
+      _LT_TAGVAR(archive_cmds_need_lc, $1)=$lt_cv_[]_LT_TAGVAR(archive_cmds_need_lc, $1)
+      ;;
+    esac
+  fi
+  ;;
+esac
+
+_LT_TAGDECL([build_libtool_need_lc], [archive_cmds_need_lc], [0],
+    [Whether or not to add -lc for building shared libraries])
+_LT_TAGDECL([allow_libtool_libs_with_static_runtimes],
+    [enable_shared_with_static_runtimes], [0],
+    [Whether or not to disallow shared libs when runtime libs are static])
+_LT_TAGDECL([], [export_dynamic_flag_spec], [1],
+    [Compiler flag to allow reflexive dlopens])
+_LT_TAGDECL([], [whole_archive_flag_spec], [1],
+    [Compiler flag to generate shared objects directly from archives])
+_LT_TAGDECL([], [compiler_needs_object], [1],
+    [Whether the compiler copes with passing no objects directly])
+_LT_TAGDECL([], [old_archive_from_new_cmds], [2],
+    [Create an old-style archive from a shared archive])
+_LT_TAGDECL([], [old_archive_from_expsyms_cmds], [2],
+    [Create a temporary old-style archive to link instead of a shared archive])
+_LT_TAGDECL([], [archive_cmds], [2], [Commands used to build a shared archive])
+_LT_TAGDECL([], [archive_expsym_cmds], [2])
+_LT_TAGDECL([], [module_cmds], [2],
+    [Commands used to build a loadable module if different from building
+    a shared archive.])
+_LT_TAGDECL([], [module_expsym_cmds], [2])
+_LT_TAGDECL([], [with_gnu_ld], [1],
+    [Whether we are building with GNU ld or not])
+_LT_TAGDECL([], [allow_undefined_flag], [1],
+    [Flag that allows shared libraries with undefined symbols to be built])
+_LT_TAGDECL([], [no_undefined_flag], [1],
+    [Flag that enforces no undefined symbols])
+_LT_TAGDECL([], [hardcode_libdir_flag_spec], [1],
+    [Flag to hardcode $libdir into a binary during linking.
+    This must work even if $libdir does not exist])
+_LT_TAGDECL([], [hardcode_libdir_separator], [1],
+    [Whether we need a single "-rpath" flag with a separated argument])
+_LT_TAGDECL([], [hardcode_direct], [0],
+    [Set to "yes" if using DIR/libNAME${shared_ext} during linking hardcodes
+    DIR into the resulting binary])
+_LT_TAGDECL([], [hardcode_direct_absolute], [0],
+    [Set to "yes" if using DIR/libNAME${shared_ext} during linking hardcodes
+    DIR into the resulting binary and the resulting library dependency is
+    "absolute", i.e impossible to change by setting ${shlibpath_var} if the
+    library is relocated])
+_LT_TAGDECL([], [hardcode_minus_L], [0],
+    [Set to "yes" if using the -LDIR flag during linking hardcodes DIR
+    into the resulting binary])
+_LT_TAGDECL([], [hardcode_shlibpath_var], [0],
+    [Set to "yes" if using SHLIBPATH_VAR=DIR during linking hardcodes DIR
+    into the resulting binary])
+_LT_TAGDECL([], [hardcode_automatic], [0],
+    [Set to "yes" if building a shared library automatically hardcodes DIR
+    into the library and all subsequent libraries and executables linked
+    against it])
+_LT_TAGDECL([], [inherit_rpath], [0],
+    [Set to yes if linker adds runtime paths of dependent libraries
+    to runtime path list])
+_LT_TAGDECL([], [link_all_deplibs], [0],
+    [Whether libtool must link a program against all its dependency libraries])
+_LT_TAGDECL([], [always_export_symbols], [0],
+    [Set to "yes" if exported symbols are required])
+_LT_TAGDECL([], [export_symbols_cmds], [2],
+    [The commands to list exported symbols])
+_LT_TAGDECL([], [exclude_expsyms], [1],
+    [Symbols that should not be listed in the preloaded symbols])
+_LT_TAGDECL([], [include_expsyms], [1],
+    [Symbols that must always be exported])
+_LT_TAGDECL([], [prelink_cmds], [2],
+    [Commands necessary for linking programs (against libraries) with templates])
+_LT_TAGDECL([], [postlink_cmds], [2],
+    [Commands necessary for finishing linking programs])
+_LT_TAGDECL([], [file_list_spec], [1],
+    [Specify filename containing input files])
+dnl FIXME: Not yet implemented
+dnl _LT_TAGDECL([], [thread_safe_flag_spec], [1],
+dnl    [Compiler flag to generate thread safe objects])
+])# _LT_LINKER_SHLIBS
+
+
+# _LT_LANG_C_CONFIG([TAG])
+# ------------------------
+# Ensure that the configuration variables for a C compiler are suitably
+# defined.  These variables are subsequently used by _LT_CONFIG to write
+# the compiler configuration to `libtool'.
+m4_defun([_LT_LANG_C_CONFIG],
+[m4_require([_LT_DECL_EGREP])dnl
+lt_save_CC="$CC"
+AC_LANG_PUSH(C)
+
+# Source file extension for C test sources.
+ac_ext=c
+
+# Object file extension for compiled C test sources.
+objext=o
+_LT_TAGVAR(objext, $1)=$objext
+
+# Code to be used in simple compile tests
+lt_simple_compile_test_code="int some_variable = 0;"
+
+# Code to be used in simple link tests
+lt_simple_link_test_code='int main(){return(0);}'
+
+_LT_TAG_COMPILER
+# Save the default compiler, since it gets overwritten when the other
+# tags are being tested, and _LT_TAGVAR(compiler, []) is a NOP.
+compiler_DEFAULT=$CC
+
+# save warnings/boilerplate of simple test code
+_LT_COMPILER_BOILERPLATE
+_LT_LINKER_BOILERPLATE
+
+## CAVEAT EMPTOR:
+## There is no encapsulation within the following macros, do not change
+## the running order or otherwise move them around unless you know exactly
+## what you are doing...
+if test -n "$compiler"; then
+  _LT_COMPILER_NO_RTTI($1)
+  _LT_COMPILER_PIC($1)
+  _LT_COMPILER_C_O($1)
+  _LT_COMPILER_FILE_LOCKS($1)
+  _LT_LINKER_SHLIBS($1)
+  _LT_SYS_DYNAMIC_LINKER($1)
+  _LT_LINKER_HARDCODE_LIBPATH($1)
+  LT_SYS_DLOPEN_SELF
+  _LT_CMD_STRIPLIB
+
+  # Report which library types will actually be built
+  AC_MSG_CHECKING([if libtool supports shared libraries])
+  AC_MSG_RESULT([$can_build_shared])
+
+  AC_MSG_CHECKING([whether to build shared libraries])
+  test "$can_build_shared" = "no" && enable_shared=no
+
+  # On AIX, shared libraries and static libraries use the same namespace, and
+  # are all built from PIC.
+  case $host_os in
+  aix3*)
+    test "$enable_shared" = yes && enable_static=no
+    if test -n "$RANLIB"; then
+      archive_cmds="$archive_cmds~\$RANLIB \$lib"
+      postinstall_cmds='$RANLIB $lib'
+    fi
+    ;;
+
+  aix[[4-9]]*)
+    if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then
+      test "$enable_shared" = yes && enable_static=no
+    fi
+    ;;
+  esac
+  AC_MSG_RESULT([$enable_shared])
+
+  AC_MSG_CHECKING([whether to build static libraries])
+  # Make sure either enable_shared or enable_static is yes.
+  test "$enable_shared" = yes || enable_static=yes
+  AC_MSG_RESULT([$enable_static])
+
+  _LT_CONFIG($1)
+fi
+AC_LANG_POP
+CC="$lt_save_CC"
+])# _LT_LANG_C_CONFIG
+
+
+# _LT_LANG_CXX_CONFIG([TAG])
+# --------------------------
+# Ensure that the configuration variables for a C++ compiler are suitably
+# defined.  These variables are subsequently used by _LT_CONFIG to write
+# the compiler configuration to `libtool'.
+m4_defun([_LT_LANG_CXX_CONFIG],
+[m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+m4_require([_LT_DECL_EGREP])dnl
+m4_require([_LT_PATH_MANIFEST_TOOL])dnl
+if test -n "$CXX" && ( test "X$CXX" != "Xno" &&
+    ( (test "X$CXX" = "Xg++" && `g++ -v >/dev/null 2>&1` ) ||
+    (test "X$CXX" != "Xg++"))) ; then
+  AC_PROG_CXXCPP
+else
+  _lt_caught_CXX_error=yes
+fi
+
+AC_LANG_PUSH(C++)
+_LT_TAGVAR(archive_cmds_need_lc, $1)=no
+_LT_TAGVAR(allow_undefined_flag, $1)=
+_LT_TAGVAR(always_export_symbols, $1)=no
+_LT_TAGVAR(archive_expsym_cmds, $1)=
+_LT_TAGVAR(compiler_needs_object, $1)=no
+_LT_TAGVAR(export_dynamic_flag_spec, $1)=
+_LT_TAGVAR(hardcode_direct, $1)=no
+_LT_TAGVAR(hardcode_direct_absolute, $1)=no
+_LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
+_LT_TAGVAR(hardcode_libdir_separator, $1)=
+_LT_TAGVAR(hardcode_minus_L, $1)=no
+_LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported
+_LT_TAGVAR(hardcode_automatic, $1)=no
+_LT_TAGVAR(inherit_rpath, $1)=no
+_LT_TAGVAR(module_cmds, $1)=
+_LT_TAGVAR(module_expsym_cmds, $1)=
+_LT_TAGVAR(link_all_deplibs, $1)=unknown
+_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
+_LT_TAGVAR(reload_flag, $1)=$reload_flag
+_LT_TAGVAR(reload_cmds, $1)=$reload_cmds
+_LT_TAGVAR(no_undefined_flag, $1)=
+_LT_TAGVAR(whole_archive_flag_spec, $1)=
+_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no
+
+# Source file extension for C++ test sources.
+ac_ext=cpp
+
+# Object file extension for compiled C++ test sources.
+objext=o
+_LT_TAGVAR(objext, $1)=$objext
+
+# No sense in running all these tests if we already determined that
+# the CXX compiler isn't working.  Some variables (like enable_shared)
+# are currently assumed to apply to all compilers on this platform,
+# and will be corrupted by setting them based on a non-working compiler.
+if test "$_lt_caught_CXX_error" != yes; then
+  # Code to be used in simple compile tests
+  lt_simple_compile_test_code="int some_variable = 0;"
+
+  # Code to be used in simple link tests
+  lt_simple_link_test_code='int main(int, char *[[]]) { return(0); }'
+
+  # ltmain only uses $CC for tagged configurations so make sure $CC is set.
+  _LT_TAG_COMPILER
+
+  # save warnings/boilerplate of simple test code
+  _LT_COMPILER_BOILERPLATE
+  _LT_LINKER_BOILERPLATE
+
+  # Allow CC to be a program name with arguments.
+  lt_save_CC=$CC
+  lt_save_CFLAGS=$CFLAGS
+  lt_save_LD=$LD
+  lt_save_GCC=$GCC
+  GCC=$GXX
+  lt_save_with_gnu_ld=$with_gnu_ld
+  lt_save_path_LD=$lt_cv_path_LD
+  if test -n "${lt_cv_prog_gnu_ldcxx+set}"; then
+    lt_cv_prog_gnu_ld=$lt_cv_prog_gnu_ldcxx
+  else
+    $as_unset lt_cv_prog_gnu_ld
+  fi
+  if test -n "${lt_cv_path_LDCXX+set}"; then
+    lt_cv_path_LD=$lt_cv_path_LDCXX
+  else
+    $as_unset lt_cv_path_LD
+  fi
+  test -z "${LDCXX+set}" || LD=$LDCXX
+  CC=${CXX-"c++"}
+  CFLAGS=$CXXFLAGS
+  compiler=$CC
+  _LT_TAGVAR(compiler, $1)=$CC
+  _LT_CC_BASENAME([$compiler])
+
+  if test -n "$compiler"; then
+    # We don't want -fno-exception when compiling C++ code, so set the
+    # no_builtin_flag separately
+    if test "$GXX" = yes; then
+      _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -fno-builtin'
+    else
+      _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=
+    fi
+
+    if test "$GXX" = yes; then
+      # Set up default GNU C++ configuration
+
+      LT_PATH_LD
+
+      # Check if GNU C++ uses GNU ld as the underlying linker, since the
+      # archiving commands below assume that GNU ld is being used.
+      if test "$with_gnu_ld" = yes; then
+        _LT_TAGVAR(archive_cmds, $1)='$CC $pic_flag -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib'
+        _LT_TAGVAR(archive_expsym_cmds, $1)='$CC $pic_flag -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+
+        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+        _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
+
+        # If archive_cmds runs LD, not CC, wlarc should be empty
+        # XXX I think wlarc can be eliminated in ltcf-cxx, but I need to
+        #     investigate it a little bit more. (MM)
+        wlarc='${wl}'
+
+        # ancient GNU ld didn't support --whole-archive et. al.
+        if eval "`$CC -print-prog-name=ld` --help 2>&1" |
+	  $GREP 'no-whole-archive' > /dev/null; then
+          _LT_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
+        else
+          _LT_TAGVAR(whole_archive_flag_spec, $1)=
+        fi
+      else
+        with_gnu_ld=no
+        wlarc=
+
+        # A generic and very simple default shared library creation
+        # command for GNU C++ for the case where it uses the native
+        # linker, instead of GNU ld.  If possible, this setting should
+        # overridden to take advantage of the native linker features on
+        # the platform it is being used on.
+        _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib'
+      fi
+
+      # Commands to make compiler produce verbose output that lists
+      # what "hidden" libraries, object files and flags are used when
+      # linking a shared library.
+      output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"'
+
+    else
+      GXX=no
+      with_gnu_ld=no
+      wlarc=
+    fi
+
+    # PORTME: fill in a description of your system's C++ link characteristics
+    AC_MSG_CHECKING([whether the $compiler linker ($LD) supports shared libraries])
+    _LT_TAGVAR(ld_shlibs, $1)=yes
+    case $host_os in
+      aix3*)
+        # FIXME: insert proper C++ library support
+        _LT_TAGVAR(ld_shlibs, $1)=no
+        ;;
+      aix[[4-9]]*)
+        if test "$host_cpu" = ia64; then
+          # On IA64, the linker does run time linking by default, so we don't
+          # have to do anything special.
+          aix_use_runtimelinking=no
+          exp_sym_flag='-Bexport'
+          no_entry_flag=""
+        else
+          aix_use_runtimelinking=no
+
+          # Test if we are trying to use run time linking or normal
+          # AIX style linking. If -brtl is somewhere in LDFLAGS, we
+          # need to do runtime linking.
+          case $host_os in aix4.[[23]]|aix4.[[23]].*|aix[[5-9]]*)
+	    for ld_flag in $LDFLAGS; do
+	      case $ld_flag in
+	      *-brtl*)
+	        aix_use_runtimelinking=yes
+	        break
+	        ;;
+	      esac
+	    done
+	    ;;
+          esac
+
+          exp_sym_flag='-bexport'
+          no_entry_flag='-bnoentry'
+        fi
+
+        # When large executables or shared objects are built, AIX ld can
+        # have problems creating the table of contents.  If linking a library
+        # or program results in "error TOC overflow" add -mminimal-toc to
+        # CXXFLAGS/CFLAGS for g++/gcc.  In the cases where that is not
+        # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS.
+
+        _LT_TAGVAR(archive_cmds, $1)=''
+        _LT_TAGVAR(hardcode_direct, $1)=yes
+        _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
+        _LT_TAGVAR(hardcode_libdir_separator, $1)=':'
+        _LT_TAGVAR(link_all_deplibs, $1)=yes
+        _LT_TAGVAR(file_list_spec, $1)='${wl}-f,'
+
+        if test "$GXX" = yes; then
+          case $host_os in aix4.[[012]]|aix4.[[012]].*)
+          # We only want to do this on AIX 4.2 and lower, the check
+          # below for broken collect2 doesn't work under 4.3+
+	  collect2name=`${CC} -print-prog-name=collect2`
+	  if test -f "$collect2name" &&
+	     strings "$collect2name" | $GREP resolve_lib_name >/dev/null
+	  then
+	    # We have reworked collect2
+	    :
+	  else
+	    # We have old collect2
+	    _LT_TAGVAR(hardcode_direct, $1)=unsupported
+	    # It fails to find uninstalled libraries when the uninstalled
+	    # path is not listed in the libpath.  Setting hardcode_minus_L
+	    # to unsupported forces relinking
+	    _LT_TAGVAR(hardcode_minus_L, $1)=yes
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+	    _LT_TAGVAR(hardcode_libdir_separator, $1)=
+	  fi
+          esac
+          shared_flag='-shared'
+	  if test "$aix_use_runtimelinking" = yes; then
+	    shared_flag="$shared_flag "'${wl}-G'
+	  fi
+        else
+          # not using gcc
+          if test "$host_cpu" = ia64; then
+	  # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release
+	  # chokes on -Wl,-G. The following line is correct:
+	  shared_flag='-G'
+          else
+	    if test "$aix_use_runtimelinking" = yes; then
+	      shared_flag='${wl}-G'
+	    else
+	      shared_flag='${wl}-bM:SRE'
+	    fi
+          fi
+        fi
+
+        _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-bexpall'
+        # It seems that -bexpall does not export symbols beginning with
+        # underscore (_), so it is better to generate a list of symbols to
+	# export.
+        _LT_TAGVAR(always_export_symbols, $1)=yes
+        if test "$aix_use_runtimelinking" = yes; then
+          # Warning - without using the other runtime loading flags (-brtl),
+          # -berok will link without error, but may produce a broken library.
+          _LT_TAGVAR(allow_undefined_flag, $1)='-berok'
+          # Determine the default libpath from the value encoded in an empty
+          # executable.
+          _LT_SYS_MODULE_PATH_AIX([$1])
+          _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
+
+          _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then func_echo_all "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag"
+        else
+          if test "$host_cpu" = ia64; then
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $libdir:/usr/lib:/lib'
+	    _LT_TAGVAR(allow_undefined_flag, $1)="-z nodefs"
+	    _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols"
+          else
+	    # Determine the default libpath from the value encoded in an
+	    # empty executable.
+	    _LT_SYS_MODULE_PATH_AIX([$1])
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
+	    # Warning - without using the other run time loading flags,
+	    # -berok will link without error, but may produce a broken library.
+	    _LT_TAGVAR(no_undefined_flag, $1)=' ${wl}-bernotok'
+	    _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-berok'
+	    if test "$with_gnu_ld" = yes; then
+	      # We only use this code for GNU lds that support --whole-archive.
+	      _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive$convenience ${wl}--no-whole-archive'
+	    else
+	      # Exported symbols can be pulled into shared objects from archives
+	      _LT_TAGVAR(whole_archive_flag_spec, $1)='$convenience'
+	    fi
+	    _LT_TAGVAR(archive_cmds_need_lc, $1)=yes
+	    # This is similar to how AIX traditionally builds its shared
+	    # libraries.
+	    _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname'
+          fi
+        fi
+        ;;
+
+      beos*)
+	if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
+	  _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
+	  # Joseph Beckenbach <jrb3 at best.com> says some releases of gcc
+	  # support --undefined.  This deserves some investigation.  FIXME
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+	else
+	  _LT_TAGVAR(ld_shlibs, $1)=no
+	fi
+	;;
+
+      chorus*)
+        case $cc_basename in
+          *)
+	  # FIXME: insert proper C++ library support
+	  _LT_TAGVAR(ld_shlibs, $1)=no
+	  ;;
+        esac
+        ;;
+
+      cygwin* | mingw* | pw32* | cegcc*)
+	case $GXX,$cc_basename in
+	,cl* | no,cl*)
+	  # Native MSVC
+	  # hardcode_libdir_flag_spec is actually meaningless, as there is
+	  # no search path for DLLs.
+	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=' '
+	  _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
+	  _LT_TAGVAR(always_export_symbols, $1)=yes
+	  _LT_TAGVAR(file_list_spec, $1)='@'
+	  # Tell ltmain to make .lib files, not .a files.
+	  libext=lib
+	  # Tell ltmain to make .dll files, not .so files.
+	  shrext_cmds=".dll"
+	  # FIXME: Setting linknames here is a bad hack.
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-dll~linknames='
+	  _LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
+	      $SED -n -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' -e '1\\\!p' < $export_symbols > $output_objdir/$soname.exp;
+	    else
+	      $SED -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' < $export_symbols > $output_objdir/$soname.exp;
+	    fi~
+	    $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~
+	    linknames='
+	  # The linker will not automatically build a static lib if we build a DLL.
+	  # _LT_TAGVAR(old_archive_from_new_cmds, $1)='true'
+	  _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
+	  # Don't use ranlib
+	  _LT_TAGVAR(old_postinstall_cmds, $1)='chmod 644 $oldlib'
+	  _LT_TAGVAR(postlink_cmds, $1)='lt_outputfile="@OUTPUT@"~
+	    lt_tool_outputfile="@TOOL_OUTPUT@"~
+	    case $lt_outputfile in
+	      *.exe|*.EXE) ;;
+	      *)
+		lt_outputfile="$lt_outputfile.exe"
+		lt_tool_outputfile="$lt_tool_outputfile.exe"
+		;;
+	    esac~
+	    func_to_tool_file "$lt_outputfile"~
+	    if test "$MANIFEST_TOOL" != ":" && test -f "$lt_outputfile.manifest"; then
+	      $MANIFEST_TOOL -manifest "$lt_tool_outputfile.manifest" -outputresource:"$lt_tool_outputfile" || exit 1;
+	      $RM "$lt_outputfile.manifest";
+	    fi'
+	  ;;
+	*)
+	  # g++
+	  # _LT_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless,
+	  # as there is no search path for DLLs.
+	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+	  _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-all-symbols'
+	  _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
+	  _LT_TAGVAR(always_export_symbols, $1)=no
+	  _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
+
+	  if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then
+	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+	    # If the export-symbols file already is a .def file (1st line
+	    # is EXPORTS), use it as is; otherwise, prepend...
+	    _LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
+	      cp $export_symbols $output_objdir/$soname.def;
+	    else
+	      echo EXPORTS > $output_objdir/$soname.def;
+	      cat $export_symbols >> $output_objdir/$soname.def;
+	    fi~
+	    $CC -shared -nostdlib $output_objdir/$soname.def $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+	  else
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	  fi
+	  ;;
+	esac
+	;;
+      darwin* | rhapsody*)
+        _LT_DARWIN_LINKER_FEATURES($1)
+	;;
+
+      dgux*)
+        case $cc_basename in
+          ec++*)
+	    # FIXME: insert proper C++ library support
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	    ;;
+          ghcx*)
+	    # Green Hills C++ Compiler
+	    # FIXME: insert proper C++ library support
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	    ;;
+          *)
+	    # FIXME: insert proper C++ library support
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	    ;;
+        esac
+        ;;
+
+      freebsd2.*)
+        # C++ shared libraries reported to be fairly broken before
+	# switch to ELF
+        _LT_TAGVAR(ld_shlibs, $1)=no
+        ;;
+
+      freebsd-elf*)
+        _LT_TAGVAR(archive_cmds_need_lc, $1)=no
+        ;;
+
+      freebsd* | dragonfly*)
+        # FreeBSD 3 and later use GNU C++ and GNU ld with standard ELF
+        # conventions
+        _LT_TAGVAR(ld_shlibs, $1)=yes
+        ;;
+
+      gnu*)
+        ;;
+
+      haiku*)
+        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+        _LT_TAGVAR(link_all_deplibs, $1)=yes
+        ;;
+
+      hpux9*)
+        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
+        _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+        _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+        _LT_TAGVAR(hardcode_direct, $1)=yes
+        _LT_TAGVAR(hardcode_minus_L, $1)=yes # Not in the search PATH,
+				             # but as the default
+				             # location of the library.
+
+        case $cc_basename in
+          CC*)
+            # FIXME: insert proper C++ library support
+            _LT_TAGVAR(ld_shlibs, $1)=no
+            ;;
+          aCC*)
+            _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -b ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+            # Commands to make compiler produce verbose output that lists
+            # what "hidden" libraries, object files and flags are used when
+            # linking a shared library.
+            #
+            # There doesn't appear to be a way to prevent this compiler from
+            # explicitly linking system object files so we need to strip them
+            # from the output so that they don't get included in the library
+            # dependencies.
+            output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $EGREP "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"'
+            ;;
+          *)
+            if test "$GXX" = yes; then
+              _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -shared -nostdlib $pic_flag ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+            else
+              # FIXME: insert proper C++ library support
+              _LT_TAGVAR(ld_shlibs, $1)=no
+            fi
+            ;;
+        esac
+        ;;
+
+      hpux10*|hpux11*)
+        if test $with_gnu_ld = no; then
+	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
+	  _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+
+          case $host_cpu in
+            hppa*64*|ia64*)
+              ;;
+            *)
+	      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+              ;;
+          esac
+        fi
+        case $host_cpu in
+          hppa*64*|ia64*)
+            _LT_TAGVAR(hardcode_direct, $1)=no
+            _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+            ;;
+          *)
+            _LT_TAGVAR(hardcode_direct, $1)=yes
+            _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
+            _LT_TAGVAR(hardcode_minus_L, $1)=yes # Not in the search PATH,
+					         # but as the default
+					         # location of the library.
+            ;;
+        esac
+
+        case $cc_basename in
+          CC*)
+	    # FIXME: insert proper C++ library support
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	    ;;
+          aCC*)
+	    case $host_cpu in
+	      hppa*64*)
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	        ;;
+	      ia64*)
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	        ;;
+	      *)
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	        ;;
+	    esac
+	    # Commands to make compiler produce verbose output that lists
+	    # what "hidden" libraries, object files and flags are used when
+	    # linking a shared library.
+	    #
+	    # There doesn't appear to be a way to prevent this compiler from
+	    # explicitly linking system object files so we need to strip them
+	    # from the output so that they don't get included in the library
+	    # dependencies.
+	    output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $GREP "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"'
+	    ;;
+          *)
+	    if test "$GXX" = yes; then
+	      if test $with_gnu_ld = no; then
+	        case $host_cpu in
+	          hppa*64*)
+	            _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	            ;;
+	          ia64*)
+	            _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $pic_flag ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	            ;;
+	          *)
+	            _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	            ;;
+	        esac
+	      fi
+	    else
+	      # FIXME: insert proper C++ library support
+	      _LT_TAGVAR(ld_shlibs, $1)=no
+	    fi
+	    ;;
+        esac
+        ;;
+
+      interix[[3-9]]*)
+	_LT_TAGVAR(hardcode_direct, $1)=no
+	_LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+	_LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+	# Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc.
+	# Instead, shared libraries are loaded at an image base (0x10000000 by
+	# default) and relocated if they conflict, which is a slow very memory
+	# consuming and fragmenting process.  To avoid this, we pick a random,
+	# 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link
+	# time.  Moving up from 0x10000000 also allows more sbrk(2) space.
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
+	;;
+      irix5* | irix6*)
+        case $cc_basename in
+          CC*)
+	    # SGI C++
+	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared -all -multigot $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
+
+	    # Archives containing C++ object files must be created using
+	    # "CC -ar", where "CC" is the IRIX C++ compiler.  This is
+	    # necessary to make sure instantiated templates are included
+	    # in the archive.
+	    _LT_TAGVAR(old_archive_cmds, $1)='$CC -ar -WR,-u -o $oldlib $oldobjs'
+	    ;;
+          *)
+	    if test "$GXX" = yes; then
+	      if test "$with_gnu_ld" = no; then
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+	      else
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` -o $lib'
+	      fi
+	    fi
+	    _LT_TAGVAR(link_all_deplibs, $1)=yes
+	    ;;
+        esac
+        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+        _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+        _LT_TAGVAR(inherit_rpath, $1)=yes
+        ;;
+
+      linux* | k*bsd*-gnu | kopensolaris*-gnu)
+        case $cc_basename in
+          KCC*)
+	    # Kuck and Associates, Inc. (KAI) C++ Compiler
+
+	    # KCC will only create a shared library if the output file
+	    # ends with ".so" (or ".sl" for HP-UX), so rename the library
+	    # to its proper name (with version) after linking.
+	    _LT_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib'
+	    _LT_TAGVAR(archive_expsym_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib ${wl}-retain-symbols-file,$export_symbols; mv \$templib $lib'
+	    # Commands to make compiler produce verbose output that lists
+	    # what "hidden" libraries, object files and flags are used when
+	    # linking a shared library.
+	    #
+	    # There doesn't appear to be a way to prevent this compiler from
+	    # explicitly linking system object files so we need to strip them
+	    # from the output so that they don't get included in the library
+	    # dependencies.
+	    output_verbose_link_cmd='templist=`$CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1 | $GREP "ld"`; rm -f libconftest$shared_ext; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"'
+
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
+
+	    # Archives containing C++ object files must be created using
+	    # "CC -Bstatic", where "CC" is the KAI C++ compiler.
+	    _LT_TAGVAR(old_archive_cmds, $1)='$CC -Bstatic -o $oldlib $oldobjs'
+	    ;;
+	  icpc* | ecpc* )
+	    # Intel C++
+	    with_gnu_ld=yes
+	    # version 8.0 and above of icpc choke on multiply defined symbols
+	    # if we add $predep_objects and $postdep_objects, however 7.1 and
+	    # earlier do not add the objects themselves.
+	    case `$CC -V 2>&1` in
+	      *"Version 7."*)
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib'
+		_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+		;;
+	      *)  # Version 8.0 or newer
+	        tmp_idyn=
+	        case $host_cpu in
+		  ia64*) tmp_idyn=' -i_dynamic';;
+		esac
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+		_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+		;;
+	    esac
+	    _LT_TAGVAR(archive_cmds_need_lc, $1)=no
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
+	    _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive$convenience ${wl}--no-whole-archive'
+	    ;;
+          pgCC* | pgcpp*)
+            # Portland Group C++ compiler
+	    case `$CC -V` in
+	    *pgCC\ [[1-5]].* | *pgcpp\ [[1-5]].*)
+	      _LT_TAGVAR(prelink_cmds, $1)='tpldir=Template.dir~
+		rm -rf $tpldir~
+		$CC --prelink_objects --instantiation_dir $tpldir $objs $libobjs $compile_deplibs~
+		compile_command="$compile_command `find $tpldir -name \*.o | sort | $NL2SP`"'
+	      _LT_TAGVAR(old_archive_cmds, $1)='tpldir=Template.dir~
+		rm -rf $tpldir~
+		$CC --prelink_objects --instantiation_dir $tpldir $oldobjs$old_deplibs~
+		$AR $AR_FLAGS $oldlib$oldobjs$old_deplibs `find $tpldir -name \*.o | sort | $NL2SP`~
+		$RANLIB $oldlib'
+	      _LT_TAGVAR(archive_cmds, $1)='tpldir=Template.dir~
+		rm -rf $tpldir~
+		$CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~
+		$CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | sort | $NL2SP` $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib'
+	      _LT_TAGVAR(archive_expsym_cmds, $1)='tpldir=Template.dir~
+		rm -rf $tpldir~
+		$CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~
+		$CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | sort | $NL2SP` $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib'
+	      ;;
+	    *) # Version 6 and above use weak symbols
+	      _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib'
+	      _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib'
+	      ;;
+	    esac
+
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}--rpath ${wl}$libdir'
+	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
+	    _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
+            ;;
+	  cxx*)
+	    # Compaq C++
+	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib'
+	    _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname  -o $lib ${wl}-retain-symbols-file $wl$export_symbols'
+
+	    runpath_var=LD_RUN_PATH
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir'
+	    _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+
+	    # Commands to make compiler produce verbose output that lists
+	    # what "hidden" libraries, object files and flags are used when
+	    # linking a shared library.
+	    #
+	    # There doesn't appear to be a way to prevent this compiler from
+	    # explicitly linking system object files so we need to strip them
+	    # from the output so that they don't get included in the library
+	    # dependencies.
+	    output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld"`; templist=`func_echo_all "$templist" | $SED "s/\(^.*ld.*\)\( .*ld .*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "X$list" | $Xsed'
+	    ;;
+	  xl* | mpixl* | bgxl*)
+	    # IBM XL 8.0 on PPC, with GNU ld
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
+	    _LT_TAGVAR(archive_cmds, $1)='$CC -qmkshrobj $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+	    if test "x$supports_anon_versioning" = xyes; then
+	      _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~
+		cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
+		echo "local: *; };" >> $output_objdir/$libname.ver~
+		$CC -qmkshrobj $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib'
+	    fi
+	    ;;
+	  *)
+	    case `$CC -V 2>&1 | sed 5q` in
+	    *Sun\ C*)
+	      # Sun C++ 5.9
+	      _LT_TAGVAR(no_undefined_flag, $1)=' -zdefs'
+	      _LT_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	      _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file ${wl}$export_symbols'
+	      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+	      _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
+	      _LT_TAGVAR(compiler_needs_object, $1)=yes
+
+	      # Not sure whether something based on
+	      # $CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1
+	      # would be better.
+	      output_verbose_link_cmd='func_echo_all'
+
+	      # Archives containing C++ object files must be created using
+	      # "CC -xar", where "CC" is the Sun C++ compiler.  This is
+	      # necessary to make sure instantiated templates are included
+	      # in the archive.
+	      _LT_TAGVAR(old_archive_cmds, $1)='$CC -xar -o $oldlib $oldobjs'
+	      ;;
+	    esac
+	    ;;
+	esac
+	;;
+
+      lynxos*)
+        # FIXME: insert proper C++ library support
+	_LT_TAGVAR(ld_shlibs, $1)=no
+	;;
+
+      m88k*)
+        # FIXME: insert proper C++ library support
+        _LT_TAGVAR(ld_shlibs, $1)=no
+	;;
+
+      mvs*)
+        case $cc_basename in
+          cxx*)
+	    # FIXME: insert proper C++ library support
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	    ;;
+	  *)
+	    # FIXME: insert proper C++ library support
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	    ;;
+	esac
+	;;
+
+      netbsd*)
+        if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
+	  _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable  -o $lib $predep_objects $libobjs $deplibs $postdep_objects $linker_flags'
+	  wlarc=
+	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+	  _LT_TAGVAR(hardcode_direct, $1)=yes
+	  _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+	fi
+	# Workaround some broken pre-1.5 toolchains
+	output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP conftest.$objext | $SED -e "s:-lgcc -lc -lgcc::"'
+	;;
+
+      *nto* | *qnx*)
+        _LT_TAGVAR(ld_shlibs, $1)=yes
+	;;
+
+      openbsd2*)
+        # C++ shared libraries are fairly broken
+	_LT_TAGVAR(ld_shlibs, $1)=no
+	;;
+
+      openbsd*)
+	if test -f /usr/libexec/ld.so; then
+	  _LT_TAGVAR(hardcode_direct, $1)=yes
+	  _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+	  _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib'
+	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+	  if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+	    _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file,$export_symbols -o $lib'
+	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+	    _LT_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
+	  fi
+	  output_verbose_link_cmd=func_echo_all
+	else
+	  _LT_TAGVAR(ld_shlibs, $1)=no
+	fi
+	;;
+
+      osf3* | osf4* | osf5*)
+        case $cc_basename in
+          KCC*)
+	    # Kuck and Associates, Inc. (KAI) C++ Compiler
+
+	    # KCC will only create a shared library if the output file
+	    # ends with ".so" (or ".sl" for HP-UX), so rename the library
+	    # to its proper name (with version) after linking.
+	    _LT_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo "$lib" | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib'
+
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+	    _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+
+	    # Archives containing C++ object files must be created using
+	    # the KAI C++ compiler.
+	    case $host in
+	      osf3*) _LT_TAGVAR(old_archive_cmds, $1)='$CC -Bstatic -o $oldlib $oldobjs' ;;
+	      *) _LT_TAGVAR(old_archive_cmds, $1)='$CC -o $oldlib $oldobjs' ;;
+	    esac
+	    ;;
+          RCC*)
+	    # Rational C++ 2.4.1
+	    # FIXME: insert proper C++ library support
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	    ;;
+          cxx*)
+	    case $host in
+	      osf3*)
+	        _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $soname `test -n "$verstring" && func_echo_all "${wl}-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
+	        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+		;;
+	      *)
+	        _LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*'
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
+	        _LT_TAGVAR(archive_expsym_cmds, $1)='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done~
+	          echo "-hidden">> $lib.exp~
+	          $CC -shared$allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname ${wl}-input ${wl}$lib.exp  `test -n "$verstring" && $ECHO "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib~
+	          $RM $lib.exp'
+	        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir'
+		;;
+	    esac
+
+	    _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+
+	    # Commands to make compiler produce verbose output that lists
+	    # what "hidden" libraries, object files and flags are used when
+	    # linking a shared library.
+	    #
+	    # There doesn't appear to be a way to prevent this compiler from
+	    # explicitly linking system object files so we need to strip them
+	    # from the output so that they don't get included in the library
+	    # dependencies.
+	    output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld" | $GREP -v "ld:"`; templist=`func_echo_all "$templist" | $SED "s/\(^.*ld.*\)\( .*ld.*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"'
+	    ;;
+	  *)
+	    if test "$GXX" = yes && test "$with_gnu_ld" = no; then
+	      _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
+	      case $host in
+	        osf3*)
+	          _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+		  ;;
+	        *)
+	          _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+		  ;;
+	      esac
+
+	      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+	      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+
+	      # Commands to make compiler produce verbose output that lists
+	      # what "hidden" libraries, object files and flags are used when
+	      # linking a shared library.
+	      output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"'
+
+	    else
+	      # FIXME: insert proper C++ library support
+	      _LT_TAGVAR(ld_shlibs, $1)=no
+	    fi
+	    ;;
+        esac
+        ;;
+
+      psos*)
+        # FIXME: insert proper C++ library support
+        _LT_TAGVAR(ld_shlibs, $1)=no
+        ;;
+
+      sunos4*)
+        case $cc_basename in
+          CC*)
+	    # Sun C++ 4.x
+	    # FIXME: insert proper C++ library support
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	    ;;
+          lcc*)
+	    # Lucid
+	    # FIXME: insert proper C++ library support
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	    ;;
+          *)
+	    # FIXME: insert proper C++ library support
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	    ;;
+        esac
+        ;;
+
+      solaris*)
+        case $cc_basename in
+          CC* | sunCC*)
+	    # Sun C++ 4.2, 5.x and Centerline C++
+            _LT_TAGVAR(archive_cmds_need_lc,$1)=yes
+	    _LT_TAGVAR(no_undefined_flag, $1)=' -zdefs'
+	    _LT_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag}  -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	    _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
+	      $CC -G${allow_undefined_flag} ${wl}-M ${wl}$lib.exp -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp'
+
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+	    _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+	    case $host_os in
+	      solaris2.[[0-5]] | solaris2.[[0-5]].*) ;;
+	      *)
+		# The compiler driver will combine and reorder linker options,
+		# but understands `-z linker_flag'.
+	        # Supported since Solaris 2.6 (maybe 2.5.1?)
+		_LT_TAGVAR(whole_archive_flag_spec, $1)='-z allextract$convenience -z defaultextract'
+	        ;;
+	    esac
+	    _LT_TAGVAR(link_all_deplibs, $1)=yes
+
+	    output_verbose_link_cmd='func_echo_all'
+
+	    # Archives containing C++ object files must be created using
+	    # "CC -xar", where "CC" is the Sun C++ compiler.  This is
+	    # necessary to make sure instantiated templates are included
+	    # in the archive.
+	    _LT_TAGVAR(old_archive_cmds, $1)='$CC -xar -o $oldlib $oldobjs'
+	    ;;
+          gcx*)
+	    # Green Hills C++ Compiler
+	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib'
+
+	    # The C++ compiler must be used to create the archive.
+	    _LT_TAGVAR(old_archive_cmds, $1)='$CC $LDFLAGS -archive -o $oldlib $oldobjs'
+	    ;;
+          *)
+	    # GNU C++ compiler with Solaris linker
+	    if test "$GXX" = yes && test "$with_gnu_ld" = no; then
+	      _LT_TAGVAR(no_undefined_flag, $1)=' ${wl}-z ${wl}defs'
+	      if $CC --version | $GREP -v '^2\.7' > /dev/null; then
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib'
+	        _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
+		  $CC -shared $pic_flag -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp'
+
+	        # Commands to make compiler produce verbose output that lists
+	        # what "hidden" libraries, object files and flags are used when
+	        # linking a shared library.
+	        output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"'
+	      else
+	        # g++ 2.7 appears to require `-G' NOT `-shared' on this
+	        # platform.
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -G -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib'
+	        _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
+		  $CC -G -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp'
+
+	        # Commands to make compiler produce verbose output that lists
+	        # what "hidden" libraries, object files and flags are used when
+	        # linking a shared library.
+	        output_verbose_link_cmd='$CC -G $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"'
+	      fi
+
+	      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $wl$libdir'
+	      case $host_os in
+		solaris2.[[0-5]] | solaris2.[[0-5]].*) ;;
+		*)
+		  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract'
+		  ;;
+	      esac
+	    fi
+	    ;;
+        esac
+        ;;
+
+    sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[[01]].[[10]]* | unixware7* | sco3.2v5.0.[[024]]*)
+      _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
+      _LT_TAGVAR(archive_cmds_need_lc, $1)=no
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      runpath_var='LD_RUN_PATH'
+
+      case $cc_basename in
+        CC*)
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	  _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	  ;;
+	*)
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	  _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	  ;;
+      esac
+      ;;
+
+      sysv5* | sco3.2v5* | sco5v6*)
+	# Note: We can NOT use -z defs as we might desire, because we do not
+	# link with -lc, and that would cause any symbols used from libc to
+	# always be unresolved, which means just about no library would
+	# ever link correctly.  If we're not using GNU ld we use -z text
+	# though, which does catch some bad symbols but isn't as heavy-handed
+	# as -z defs.
+	_LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
+	_LT_TAGVAR(allow_undefined_flag, $1)='${wl}-z,nodefs'
+	_LT_TAGVAR(archive_cmds_need_lc, $1)=no
+	_LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R,$libdir'
+	_LT_TAGVAR(hardcode_libdir_separator, $1)=':'
+	_LT_TAGVAR(link_all_deplibs, $1)=yes
+	_LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Bexport'
+	runpath_var='LD_RUN_PATH'
+
+	case $cc_basename in
+          CC*)
+	    _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	    _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	    _LT_TAGVAR(old_archive_cmds, $1)='$CC -Tprelink_objects $oldobjs~
+	      '"$_LT_TAGVAR(old_archive_cmds, $1)"
+	    _LT_TAGVAR(reload_cmds, $1)='$CC -Tprelink_objects $reload_objs~
+	      '"$_LT_TAGVAR(reload_cmds, $1)"
+	    ;;
+	  *)
+	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	    _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	    ;;
+	esac
+      ;;
+
+      tandem*)
+        case $cc_basename in
+          NCC*)
+	    # NonStop-UX NCC 3.20
+	    # FIXME: insert proper C++ library support
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	    ;;
+          *)
+	    # FIXME: insert proper C++ library support
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	    ;;
+        esac
+        ;;
+
+      vxworks*)
+        # FIXME: insert proper C++ library support
+        _LT_TAGVAR(ld_shlibs, $1)=no
+        ;;
+
+      *)
+        # FIXME: insert proper C++ library support
+        _LT_TAGVAR(ld_shlibs, $1)=no
+        ;;
+    esac
+
+    AC_MSG_RESULT([$_LT_TAGVAR(ld_shlibs, $1)])
+    test "$_LT_TAGVAR(ld_shlibs, $1)" = no && can_build_shared=no
+
+    _LT_TAGVAR(GCC, $1)="$GXX"
+    _LT_TAGVAR(LD, $1)="$LD"
+
+    ## CAVEAT EMPTOR:
+    ## There is no encapsulation within the following macros, do not change
+    ## the running order or otherwise move them around unless you know exactly
+    ## what you are doing...
+    _LT_SYS_HIDDEN_LIBDEPS($1)
+    _LT_COMPILER_PIC($1)
+    _LT_COMPILER_C_O($1)
+    _LT_COMPILER_FILE_LOCKS($1)
+    _LT_LINKER_SHLIBS($1)
+    _LT_SYS_DYNAMIC_LINKER($1)
+    _LT_LINKER_HARDCODE_LIBPATH($1)
+
+    _LT_CONFIG($1)
+  fi # test -n "$compiler"
+
+  CC=$lt_save_CC
+  CFLAGS=$lt_save_CFLAGS
+  LDCXX=$LD
+  LD=$lt_save_LD
+  GCC=$lt_save_GCC
+  with_gnu_ld=$lt_save_with_gnu_ld
+  lt_cv_path_LDCXX=$lt_cv_path_LD
+  lt_cv_path_LD=$lt_save_path_LD
+  lt_cv_prog_gnu_ldcxx=$lt_cv_prog_gnu_ld
+  lt_cv_prog_gnu_ld=$lt_save_with_gnu_ld
+fi # test "$_lt_caught_CXX_error" != yes
+
+AC_LANG_POP
+])# _LT_LANG_CXX_CONFIG
+
+
+# _LT_FUNC_STRIPNAME_CNF
+# ----------------------
+# func_stripname_cnf prefix suffix name
+# strip PREFIX and SUFFIX off of NAME.
+# PREFIX and SUFFIX must not contain globbing or regex special
+# characters, hashes, percent signs, but SUFFIX may contain a leading
+# dot (in which case that matches only a dot).
+#
+# This function is identical to the (non-XSI) version of func_stripname,
+# except this one can be used by m4 code that may be executed by configure,
+# rather than the libtool script.
+m4_defun([_LT_FUNC_STRIPNAME_CNF],[dnl
+AC_REQUIRE([_LT_DECL_SED])
+AC_REQUIRE([_LT_PROG_ECHO_BACKSLASH])
+func_stripname_cnf ()
+{
+  case ${2} in
+  .*) func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%\\\\${2}\$%%"`;;
+  *)  func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%${2}\$%%"`;;
+  esac
+} # func_stripname_cnf
+])# _LT_FUNC_STRIPNAME_CNF
+
+# _LT_SYS_HIDDEN_LIBDEPS([TAGNAME])
+# ---------------------------------
+# Figure out "hidden" library dependencies from verbose
+# compiler output when linking a shared library.
+# Parse the compiler output and extract the necessary
+# objects, libraries and library flags.
+m4_defun([_LT_SYS_HIDDEN_LIBDEPS],
+[m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+AC_REQUIRE([_LT_FUNC_STRIPNAME_CNF])dnl
+# Dependencies to place before and after the object being linked:
+_LT_TAGVAR(predep_objects, $1)=
+_LT_TAGVAR(postdep_objects, $1)=
+_LT_TAGVAR(predeps, $1)=
+_LT_TAGVAR(postdeps, $1)=
+_LT_TAGVAR(compiler_lib_search_path, $1)=
+
+dnl we can't use the lt_simple_compile_test_code here,
+dnl because it contains code intended for an executable,
+dnl not a library.  It's possible we should let each
+dnl tag define a new lt_????_link_test_code variable,
+dnl but it's only used here...
+m4_if([$1], [], [cat > conftest.$ac_ext <<_LT_EOF
+int a;
+void foo (void) { a = 0; }
+_LT_EOF
+], [$1], [CXX], [cat > conftest.$ac_ext <<_LT_EOF
+class Foo
+{
+public:
+  Foo (void) { a = 0; }
+private:
+  int a;
+};
+_LT_EOF
+], [$1], [F77], [cat > conftest.$ac_ext <<_LT_EOF
+      subroutine foo
+      implicit none
+      integer*4 a
+      a=0
+      return
+      end
+_LT_EOF
+], [$1], [FC], [cat > conftest.$ac_ext <<_LT_EOF
+      subroutine foo
+      implicit none
+      integer a
+      a=0
+      return
+      end
+_LT_EOF
+], [$1], [GCJ], [cat > conftest.$ac_ext <<_LT_EOF
+public class foo {
+  private int a;
+  public void bar (void) {
+    a = 0;
+  }
+};
+_LT_EOF
+], [$1], [GO], [cat > conftest.$ac_ext <<_LT_EOF
+package foo
+func foo() {
+}
+_LT_EOF
+])
+
+_lt_libdeps_save_CFLAGS=$CFLAGS
+case "$CC $CFLAGS " in #(
+*\ -flto*\ *) CFLAGS="$CFLAGS -fno-lto" ;;
+*\ -fwhopr*\ *) CFLAGS="$CFLAGS -fno-whopr" ;;
+*\ -fuse-linker-plugin*\ *) CFLAGS="$CFLAGS -fno-use-linker-plugin" ;;
+esac
+
+dnl Parse the compiler output and extract the necessary
+dnl objects, libraries and library flags.
+if AC_TRY_EVAL(ac_compile); then
+  # Parse the compiler output and extract the necessary
+  # objects, libraries and library flags.
+
+  # Sentinel used to keep track of whether or not we are before
+  # the conftest object file.
+  pre_test_object_deps_done=no
+
+  for p in `eval "$output_verbose_link_cmd"`; do
+    case ${prev}${p} in
+
+    -L* | -R* | -l*)
+       # Some compilers place space between "-{L,R}" and the path.
+       # Remove the space.
+       if test $p = "-L" ||
+          test $p = "-R"; then
+	 prev=$p
+	 continue
+       fi
+
+       # Expand the sysroot to ease extracting the directories later.
+       if test -z "$prev"; then
+         case $p in
+         -L*) func_stripname_cnf '-L' '' "$p"; prev=-L; p=$func_stripname_result ;;
+         -R*) func_stripname_cnf '-R' '' "$p"; prev=-R; p=$func_stripname_result ;;
+         -l*) func_stripname_cnf '-l' '' "$p"; prev=-l; p=$func_stripname_result ;;
+         esac
+       fi
+       case $p in
+       =*) func_stripname_cnf '=' '' "$p"; p=$lt_sysroot$func_stripname_result ;;
+       esac
+       if test "$pre_test_object_deps_done" = no; then
+	 case ${prev} in
+	 -L | -R)
+	   # Internal compiler library paths should come after those
+	   # provided the user.  The postdeps already come after the
+	   # user supplied libs so there is no need to process them.
+	   if test -z "$_LT_TAGVAR(compiler_lib_search_path, $1)"; then
+	     _LT_TAGVAR(compiler_lib_search_path, $1)="${prev}${p}"
+	   else
+	     _LT_TAGVAR(compiler_lib_search_path, $1)="${_LT_TAGVAR(compiler_lib_search_path, $1)} ${prev}${p}"
+	   fi
+	   ;;
+	 # The "-l" case would never come before the object being
+	 # linked, so don't bother handling this case.
+	 esac
+       else
+	 if test -z "$_LT_TAGVAR(postdeps, $1)"; then
+	   _LT_TAGVAR(postdeps, $1)="${prev}${p}"
+	 else
+	   _LT_TAGVAR(postdeps, $1)="${_LT_TAGVAR(postdeps, $1)} ${prev}${p}"
+	 fi
+       fi
+       prev=
+       ;;
+
+    *.lto.$objext) ;; # Ignore GCC LTO objects
+    *.$objext)
+       # This assumes that the test object file only shows up
+       # once in the compiler output.
+       if test "$p" = "conftest.$objext"; then
+	 pre_test_object_deps_done=yes
+	 continue
+       fi
+
+       if test "$pre_test_object_deps_done" = no; then
+	 if test -z "$_LT_TAGVAR(predep_objects, $1)"; then
+	   _LT_TAGVAR(predep_objects, $1)="$p"
+	 else
+	   _LT_TAGVAR(predep_objects, $1)="$_LT_TAGVAR(predep_objects, $1) $p"
+	 fi
+       else
+	 if test -z "$_LT_TAGVAR(postdep_objects, $1)"; then
+	   _LT_TAGVAR(postdep_objects, $1)="$p"
+	 else
+	   _LT_TAGVAR(postdep_objects, $1)="$_LT_TAGVAR(postdep_objects, $1) $p"
+	 fi
+       fi
+       ;;
+
+    *) ;; # Ignore the rest.
+
+    esac
+  done
+
+  # Clean up.
+  rm -f a.out a.exe
+else
+  echo "libtool.m4: error: problem compiling $1 test program"
+fi
+
+$RM -f confest.$objext
+CFLAGS=$_lt_libdeps_save_CFLAGS
+
+# PORTME: override above test on systems where it is broken
+m4_if([$1], [CXX],
+[case $host_os in
+interix[[3-9]]*)
+  # Interix 3.5 installs completely hosed .la files for C++, so rather than
+  # hack all around it, let's just trust "g++" to DTRT.
+  _LT_TAGVAR(predep_objects,$1)=
+  _LT_TAGVAR(postdep_objects,$1)=
+  _LT_TAGVAR(postdeps,$1)=
+  ;;
+
+linux*)
+  case `$CC -V 2>&1 | sed 5q` in
+  *Sun\ C*)
+    # Sun C++ 5.9
+
+    # The more standards-conforming stlport4 library is
+    # incompatible with the Cstd library. Avoid specifying
+    # it if it's in CXXFLAGS. Ignore libCrun as
+    # -library=stlport4 depends on it.
+    case " $CXX $CXXFLAGS " in
+    *" -library=stlport4 "*)
+      solaris_use_stlport4=yes
+      ;;
+    esac
+
+    if test "$solaris_use_stlport4" != yes; then
+      _LT_TAGVAR(postdeps,$1)='-library=Cstd -library=Crun'
+    fi
+    ;;
+  esac
+  ;;
+
+solaris*)
+  case $cc_basename in
+  CC* | sunCC*)
+    # The more standards-conforming stlport4 library is
+    # incompatible with the Cstd library. Avoid specifying
+    # it if it's in CXXFLAGS. Ignore libCrun as
+    # -library=stlport4 depends on it.
+    case " $CXX $CXXFLAGS " in
+    *" -library=stlport4 "*)
+      solaris_use_stlport4=yes
+      ;;
+    esac
+
+    # Adding this requires a known-good setup of shared libraries for
+    # Sun compiler versions before 5.6, else PIC objects from an old
+    # archive will be linked into the output, leading to subtle bugs.
+    if test "$solaris_use_stlport4" != yes; then
+      _LT_TAGVAR(postdeps,$1)='-library=Cstd -library=Crun'
+    fi
+    ;;
+  esac
+  ;;
+esac
+])
+
+case " $_LT_TAGVAR(postdeps, $1) " in
+*" -lc "*) _LT_TAGVAR(archive_cmds_need_lc, $1)=no ;;
+esac
+ _LT_TAGVAR(compiler_lib_search_dirs, $1)=
+if test -n "${_LT_TAGVAR(compiler_lib_search_path, $1)}"; then
+ _LT_TAGVAR(compiler_lib_search_dirs, $1)=`echo " ${_LT_TAGVAR(compiler_lib_search_path, $1)}" | ${SED} -e 's! -L! !g' -e 's!^ !!'`
+fi
+_LT_TAGDECL([], [compiler_lib_search_dirs], [1],
+    [The directories searched by this compiler when creating a shared library])
+_LT_TAGDECL([], [predep_objects], [1],
+    [Dependencies to place before and after the objects being linked to
+    create a shared library])
+_LT_TAGDECL([], [postdep_objects], [1])
+_LT_TAGDECL([], [predeps], [1])
+_LT_TAGDECL([], [postdeps], [1])
+_LT_TAGDECL([], [compiler_lib_search_path], [1],
+    [The library search path used internally by the compiler when linking
+    a shared library])
+])# _LT_SYS_HIDDEN_LIBDEPS
+
+
+# _LT_LANG_F77_CONFIG([TAG])
+# --------------------------
+# Ensure that the configuration variables for a Fortran 77 compiler are
+# suitably defined.  These variables are subsequently used by _LT_CONFIG
+# to write the compiler configuration to `libtool'.
+m4_defun([_LT_LANG_F77_CONFIG],
+[AC_LANG_PUSH(Fortran 77)
+if test -z "$F77" || test "X$F77" = "Xno"; then
+  _lt_disable_F77=yes
+fi
+
+_LT_TAGVAR(archive_cmds_need_lc, $1)=no
+_LT_TAGVAR(allow_undefined_flag, $1)=
+_LT_TAGVAR(always_export_symbols, $1)=no
+_LT_TAGVAR(archive_expsym_cmds, $1)=
+_LT_TAGVAR(export_dynamic_flag_spec, $1)=
+_LT_TAGVAR(hardcode_direct, $1)=no
+_LT_TAGVAR(hardcode_direct_absolute, $1)=no
+_LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
+_LT_TAGVAR(hardcode_libdir_separator, $1)=
+_LT_TAGVAR(hardcode_minus_L, $1)=no
+_LT_TAGVAR(hardcode_automatic, $1)=no
+_LT_TAGVAR(inherit_rpath, $1)=no
+_LT_TAGVAR(module_cmds, $1)=
+_LT_TAGVAR(module_expsym_cmds, $1)=
+_LT_TAGVAR(link_all_deplibs, $1)=unknown
+_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
+_LT_TAGVAR(reload_flag, $1)=$reload_flag
+_LT_TAGVAR(reload_cmds, $1)=$reload_cmds
+_LT_TAGVAR(no_undefined_flag, $1)=
+_LT_TAGVAR(whole_archive_flag_spec, $1)=
+_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no
+
+# Source file extension for f77 test sources.
+ac_ext=f
+
+# Object file extension for compiled f77 test sources.
+objext=o
+_LT_TAGVAR(objext, $1)=$objext
+
+# No sense in running all these tests if we already determined that
+# the F77 compiler isn't working.  Some variables (like enable_shared)
+# are currently assumed to apply to all compilers on this platform,
+# and will be corrupted by setting them based on a non-working compiler.
+if test "$_lt_disable_F77" != yes; then
+  # Code to be used in simple compile tests
+  lt_simple_compile_test_code="\
+      subroutine t
+      return
+      end
+"
+
+  # Code to be used in simple link tests
+  lt_simple_link_test_code="\
+      program t
+      end
+"
+
+  # ltmain only uses $CC for tagged configurations so make sure $CC is set.
+  _LT_TAG_COMPILER
+
+  # save warnings/boilerplate of simple test code
+  _LT_COMPILER_BOILERPLATE
+  _LT_LINKER_BOILERPLATE
+
+  # Allow CC to be a program name with arguments.
+  lt_save_CC="$CC"
+  lt_save_GCC=$GCC
+  lt_save_CFLAGS=$CFLAGS
+  CC=${F77-"f77"}
+  CFLAGS=$FFLAGS
+  compiler=$CC
+  _LT_TAGVAR(compiler, $1)=$CC
+  _LT_CC_BASENAME([$compiler])
+  GCC=$G77
+  if test -n "$compiler"; then
+    AC_MSG_CHECKING([if libtool supports shared libraries])
+    AC_MSG_RESULT([$can_build_shared])
+
+    AC_MSG_CHECKING([whether to build shared libraries])
+    test "$can_build_shared" = "no" && enable_shared=no
+
+    # On AIX, shared libraries and static libraries use the same namespace, and
+    # are all built from PIC.
+    case $host_os in
+      aix3*)
+        test "$enable_shared" = yes && enable_static=no
+        if test -n "$RANLIB"; then
+          archive_cmds="$archive_cmds~\$RANLIB \$lib"
+          postinstall_cmds='$RANLIB $lib'
+        fi
+        ;;
+      aix[[4-9]]*)
+	if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then
+	  test "$enable_shared" = yes && enable_static=no
+	fi
+        ;;
+    esac
+    AC_MSG_RESULT([$enable_shared])
+
+    AC_MSG_CHECKING([whether to build static libraries])
+    # Make sure either enable_shared or enable_static is yes.
+    test "$enable_shared" = yes || enable_static=yes
+    AC_MSG_RESULT([$enable_static])
+
+    _LT_TAGVAR(GCC, $1)="$G77"
+    _LT_TAGVAR(LD, $1)="$LD"
+
+    ## CAVEAT EMPTOR:
+    ## There is no encapsulation within the following macros, do not change
+    ## the running order or otherwise move them around unless you know exactly
+    ## what you are doing...
+    _LT_COMPILER_PIC($1)
+    _LT_COMPILER_C_O($1)
+    _LT_COMPILER_FILE_LOCKS($1)
+    _LT_LINKER_SHLIBS($1)
+    _LT_SYS_DYNAMIC_LINKER($1)
+    _LT_LINKER_HARDCODE_LIBPATH($1)
+
+    _LT_CONFIG($1)
+  fi # test -n "$compiler"
+
+  GCC=$lt_save_GCC
+  CC="$lt_save_CC"
+  CFLAGS="$lt_save_CFLAGS"
+fi # test "$_lt_disable_F77" != yes
+
+AC_LANG_POP
+])# _LT_LANG_F77_CONFIG
+
+
+# _LT_LANG_FC_CONFIG([TAG])
+# -------------------------
+# Ensure that the configuration variables for a Fortran compiler are
+# suitably defined.  These variables are subsequently used by _LT_CONFIG
+# to write the compiler configuration to `libtool'.
+m4_defun([_LT_LANG_FC_CONFIG],
+[AC_LANG_PUSH(Fortran)
+
+if test -z "$FC" || test "X$FC" = "Xno"; then
+  _lt_disable_FC=yes
+fi
+
+_LT_TAGVAR(archive_cmds_need_lc, $1)=no
+_LT_TAGVAR(allow_undefined_flag, $1)=
+_LT_TAGVAR(always_export_symbols, $1)=no
+_LT_TAGVAR(archive_expsym_cmds, $1)=
+_LT_TAGVAR(export_dynamic_flag_spec, $1)=
+_LT_TAGVAR(hardcode_direct, $1)=no
+_LT_TAGVAR(hardcode_direct_absolute, $1)=no
+_LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
+_LT_TAGVAR(hardcode_libdir_separator, $1)=
+_LT_TAGVAR(hardcode_minus_L, $1)=no
+_LT_TAGVAR(hardcode_automatic, $1)=no
+_LT_TAGVAR(inherit_rpath, $1)=no
+_LT_TAGVAR(module_cmds, $1)=
+_LT_TAGVAR(module_expsym_cmds, $1)=
+_LT_TAGVAR(link_all_deplibs, $1)=unknown
+_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
+_LT_TAGVAR(reload_flag, $1)=$reload_flag
+_LT_TAGVAR(reload_cmds, $1)=$reload_cmds
+_LT_TAGVAR(no_undefined_flag, $1)=
+_LT_TAGVAR(whole_archive_flag_spec, $1)=
+_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no
+
+# Source file extension for fc test sources.
+ac_ext=${ac_fc_srcext-f}
+
+# Object file extension for compiled fc test sources.
+objext=o
+_LT_TAGVAR(objext, $1)=$objext
+
+# No sense in running all these tests if we already determined that
+# the FC compiler isn't working.  Some variables (like enable_shared)
+# are currently assumed to apply to all compilers on this platform,
+# and will be corrupted by setting them based on a non-working compiler.
+if test "$_lt_disable_FC" != yes; then
+  # Code to be used in simple compile tests
+  lt_simple_compile_test_code="\
+      subroutine t
+      return
+      end
+"
+
+  # Code to be used in simple link tests
+  lt_simple_link_test_code="\
+      program t
+      end
+"
+
+  # ltmain only uses $CC for tagged configurations so make sure $CC is set.
+  _LT_TAG_COMPILER
+
+  # save warnings/boilerplate of simple test code
+  _LT_COMPILER_BOILERPLATE
+  _LT_LINKER_BOILERPLATE
+
+  # Allow CC to be a program name with arguments.
+  lt_save_CC="$CC"
+  lt_save_GCC=$GCC
+  lt_save_CFLAGS=$CFLAGS
+  CC=${FC-"f95"}
+  CFLAGS=$FCFLAGS
+  compiler=$CC
+  GCC=$ac_cv_fc_compiler_gnu
+
+  _LT_TAGVAR(compiler, $1)=$CC
+  _LT_CC_BASENAME([$compiler])
+
+  if test -n "$compiler"; then
+    AC_MSG_CHECKING([if libtool supports shared libraries])
+    AC_MSG_RESULT([$can_build_shared])
+
+    AC_MSG_CHECKING([whether to build shared libraries])
+    test "$can_build_shared" = "no" && enable_shared=no
+
+    # On AIX, shared libraries and static libraries use the same namespace, and
+    # are all built from PIC.
+    case $host_os in
+      aix3*)
+        test "$enable_shared" = yes && enable_static=no
+        if test -n "$RANLIB"; then
+          archive_cmds="$archive_cmds~\$RANLIB \$lib"
+          postinstall_cmds='$RANLIB $lib'
+        fi
+        ;;
+      aix[[4-9]]*)
+	if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then
+	  test "$enable_shared" = yes && enable_static=no
+	fi
+        ;;
+    esac
+    AC_MSG_RESULT([$enable_shared])
+
+    AC_MSG_CHECKING([whether to build static libraries])
+    # Make sure either enable_shared or enable_static is yes.
+    test "$enable_shared" = yes || enable_static=yes
+    AC_MSG_RESULT([$enable_static])
+
+    _LT_TAGVAR(GCC, $1)="$ac_cv_fc_compiler_gnu"
+    _LT_TAGVAR(LD, $1)="$LD"
+
+    ## CAVEAT EMPTOR:
+    ## There is no encapsulation within the following macros, do not change
+    ## the running order or otherwise move them around unless you know exactly
+    ## what you are doing...
+    _LT_SYS_HIDDEN_LIBDEPS($1)
+    _LT_COMPILER_PIC($1)
+    _LT_COMPILER_C_O($1)
+    _LT_COMPILER_FILE_LOCKS($1)
+    _LT_LINKER_SHLIBS($1)
+    _LT_SYS_DYNAMIC_LINKER($1)
+    _LT_LINKER_HARDCODE_LIBPATH($1)
+
+    _LT_CONFIG($1)
+  fi # test -n "$compiler"
+
+  GCC=$lt_save_GCC
+  CC=$lt_save_CC
+  CFLAGS=$lt_save_CFLAGS
+fi # test "$_lt_disable_FC" != yes
+
+AC_LANG_POP
+])# _LT_LANG_FC_CONFIG
+
+
+# _LT_LANG_GCJ_CONFIG([TAG])
+# --------------------------
+# Ensure that the configuration variables for the GNU Java Compiler compiler
+# are suitably defined.  These variables are subsequently used by _LT_CONFIG
+# to write the compiler configuration to `libtool'.
+m4_defun([_LT_LANG_GCJ_CONFIG],
+[AC_REQUIRE([LT_PROG_GCJ])dnl
+AC_LANG_SAVE
+
+# Source file extension for Java test sources.
+ac_ext=java
+
+# Object file extension for compiled Java test sources.
+objext=o
+_LT_TAGVAR(objext, $1)=$objext
+
+# Code to be used in simple compile tests
+lt_simple_compile_test_code="class foo {}"
+
+# Code to be used in simple link tests
+lt_simple_link_test_code='public class conftest { public static void main(String[[]] argv) {}; }'
+
+# ltmain only uses $CC for tagged configurations so make sure $CC is set.
+_LT_TAG_COMPILER
+
+# save warnings/boilerplate of simple test code
+_LT_COMPILER_BOILERPLATE
+_LT_LINKER_BOILERPLATE
+
+# Allow CC to be a program name with arguments.
+lt_save_CC=$CC
+lt_save_CFLAGS=$CFLAGS
+lt_save_GCC=$GCC
+GCC=yes
+CC=${GCJ-"gcj"}
+CFLAGS=$GCJFLAGS
+compiler=$CC
+_LT_TAGVAR(compiler, $1)=$CC
+_LT_TAGVAR(LD, $1)="$LD"
+_LT_CC_BASENAME([$compiler])
+
+# GCJ did not exist at the time GCC didn't implicitly link libc in.
+_LT_TAGVAR(archive_cmds_need_lc, $1)=no
+
+_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
+_LT_TAGVAR(reload_flag, $1)=$reload_flag
+_LT_TAGVAR(reload_cmds, $1)=$reload_cmds
+
+## CAVEAT EMPTOR:
+## There is no encapsulation within the following macros, do not change
+## the running order or otherwise move them around unless you know exactly
+## what you are doing...
+if test -n "$compiler"; then
+  _LT_COMPILER_NO_RTTI($1)
+  _LT_COMPILER_PIC($1)
+  _LT_COMPILER_C_O($1)
+  _LT_COMPILER_FILE_LOCKS($1)
+  _LT_LINKER_SHLIBS($1)
+  _LT_LINKER_HARDCODE_LIBPATH($1)
+
+  _LT_CONFIG($1)
+fi
+
+AC_LANG_RESTORE
+
+GCC=$lt_save_GCC
+CC=$lt_save_CC
+CFLAGS=$lt_save_CFLAGS
+])# _LT_LANG_GCJ_CONFIG
+
+
+# _LT_LANG_GO_CONFIG([TAG])
+# --------------------------
+# Ensure that the configuration variables for the GNU Go compiler
+# are suitably defined.  These variables are subsequently used by _LT_CONFIG
+# to write the compiler configuration to `libtool'.
+m4_defun([_LT_LANG_GO_CONFIG],
+[AC_REQUIRE([LT_PROG_GO])dnl
+AC_LANG_SAVE
+
+# Source file extension for Go test sources.
+ac_ext=go
+
+# Object file extension for compiled Go test sources.
+objext=o
+_LT_TAGVAR(objext, $1)=$objext
+
+# Code to be used in simple compile tests
+lt_simple_compile_test_code="package main; func main() { }"
+
+# Code to be used in simple link tests
+lt_simple_link_test_code='package main; func main() { }'
+
+# ltmain only uses $CC for tagged configurations so make sure $CC is set.
+_LT_TAG_COMPILER
+
+# save warnings/boilerplate of simple test code
+_LT_COMPILER_BOILERPLATE
+_LT_LINKER_BOILERPLATE
+
+# Allow CC to be a program name with arguments.
+lt_save_CC=$CC
+lt_save_CFLAGS=$CFLAGS
+lt_save_GCC=$GCC
+GCC=yes
+CC=${GOC-"gccgo"}
+CFLAGS=$GOFLAGS
+compiler=$CC
+_LT_TAGVAR(compiler, $1)=$CC
+_LT_TAGVAR(LD, $1)="$LD"
+_LT_CC_BASENAME([$compiler])
+
+# Go did not exist at the time GCC didn't implicitly link libc in.
+_LT_TAGVAR(archive_cmds_need_lc, $1)=no
+
+_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
+_LT_TAGVAR(reload_flag, $1)=$reload_flag
+_LT_TAGVAR(reload_cmds, $1)=$reload_cmds
+
+## CAVEAT EMPTOR:
+## There is no encapsulation within the following macros, do not change
+## the running order or otherwise move them around unless you know exactly
+## what you are doing...
+if test -n "$compiler"; then
+  _LT_COMPILER_NO_RTTI($1)
+  _LT_COMPILER_PIC($1)
+  _LT_COMPILER_C_O($1)
+  _LT_COMPILER_FILE_LOCKS($1)
+  _LT_LINKER_SHLIBS($1)
+  _LT_LINKER_HARDCODE_LIBPATH($1)
+
+  _LT_CONFIG($1)
+fi
+
+AC_LANG_RESTORE
+
+GCC=$lt_save_GCC
+CC=$lt_save_CC
+CFLAGS=$lt_save_CFLAGS
+])# _LT_LANG_GO_CONFIG
+
+
+# _LT_LANG_RC_CONFIG([TAG])
+# -------------------------
+# Ensure that the configuration variables for the Windows resource compiler
+# are suitably defined.  These variables are subsequently used by _LT_CONFIG
+# to write the compiler configuration to `libtool'.
+m4_defun([_LT_LANG_RC_CONFIG],
+[AC_REQUIRE([LT_PROG_RC])dnl
+AC_LANG_SAVE
+
+# Source file extension for RC test sources.
+ac_ext=rc
+
+# Object file extension for compiled RC test sources.
+objext=o
+_LT_TAGVAR(objext, $1)=$objext
+
+# Code to be used in simple compile tests
+lt_simple_compile_test_code='sample MENU { MENUITEM "&Soup", 100, CHECKED }'
+
+# Code to be used in simple link tests
+lt_simple_link_test_code="$lt_simple_compile_test_code"
+
+# ltmain only uses $CC for tagged configurations so make sure $CC is set.
+_LT_TAG_COMPILER
+
+# save warnings/boilerplate of simple test code
+_LT_COMPILER_BOILERPLATE
+_LT_LINKER_BOILERPLATE
+
+# Allow CC to be a program name with arguments.
+lt_save_CC="$CC"
+lt_save_CFLAGS=$CFLAGS
+lt_save_GCC=$GCC
+GCC=
+CC=${RC-"windres"}
+CFLAGS=
+compiler=$CC
+_LT_TAGVAR(compiler, $1)=$CC
+_LT_CC_BASENAME([$compiler])
+_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=yes
+
+if test -n "$compiler"; then
+  :
+  _LT_CONFIG($1)
+fi
+
+GCC=$lt_save_GCC
+AC_LANG_RESTORE
+CC=$lt_save_CC
+CFLAGS=$lt_save_CFLAGS
+])# _LT_LANG_RC_CONFIG
+
+
+# LT_PROG_GCJ
+# -----------
+AC_DEFUN([LT_PROG_GCJ],
+[m4_ifdef([AC_PROG_GCJ], [AC_PROG_GCJ],
+  [m4_ifdef([A][M_PROG_GCJ], [A][M_PROG_GCJ],
+    [AC_CHECK_TOOL(GCJ, gcj,)
+      test "x${GCJFLAGS+set}" = xset || GCJFLAGS="-g -O2"
+      AC_SUBST(GCJFLAGS)])])[]dnl
+])
+
+# Old name:
+AU_ALIAS([LT_AC_PROG_GCJ], [LT_PROG_GCJ])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([LT_AC_PROG_GCJ], [])
+
+
+# LT_PROG_GO
+# ----------
+AC_DEFUN([LT_PROG_GO],
+[AC_CHECK_TOOL(GOC, gccgo,)
+])
+
+
+# LT_PROG_RC
+# ----------
+AC_DEFUN([LT_PROG_RC],
+[AC_CHECK_TOOL(RC, windres,)
+])
+
+# Old name:
+AU_ALIAS([LT_AC_PROG_RC], [LT_PROG_RC])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([LT_AC_PROG_RC], [])
+
+
+# _LT_DECL_EGREP
+# --------------
+# If we don't have a new enough Autoconf to choose the best grep
+# available, choose the one first in the user's PATH.
+m4_defun([_LT_DECL_EGREP],
+[AC_REQUIRE([AC_PROG_EGREP])dnl
+AC_REQUIRE([AC_PROG_FGREP])dnl
+test -z "$GREP" && GREP=grep
+_LT_DECL([], [GREP], [1], [A grep program that handles long lines])
+_LT_DECL([], [EGREP], [1], [An ERE matcher])
+_LT_DECL([], [FGREP], [1], [A literal string matcher])
+dnl Non-bleeding-edge autoconf doesn't subst GREP, so do it here too
+AC_SUBST([GREP])
+])
+
+
+# _LT_DECL_OBJDUMP
+# --------------
+# If we don't have a new enough Autoconf to choose the best objdump
+# available, choose the one first in the user's PATH.
+m4_defun([_LT_DECL_OBJDUMP],
+[AC_CHECK_TOOL(OBJDUMP, objdump, false)
+test -z "$OBJDUMP" && OBJDUMP=objdump
+_LT_DECL([], [OBJDUMP], [1], [An object symbol dumper])
+AC_SUBST([OBJDUMP])
+])
+
+# _LT_DECL_DLLTOOL
+# ----------------
+# Ensure DLLTOOL variable is set.
+m4_defun([_LT_DECL_DLLTOOL],
+[AC_CHECK_TOOL(DLLTOOL, dlltool, false)
+test -z "$DLLTOOL" && DLLTOOL=dlltool
+_LT_DECL([], [DLLTOOL], [1], [DLL creation program])
+AC_SUBST([DLLTOOL])
+])
+
+# _LT_DECL_SED
+# ------------
+# Check for a fully-functional sed program, that truncates
+# as few characters as possible.  Prefer GNU sed if found.
+m4_defun([_LT_DECL_SED],
+[AC_PROG_SED
+test -z "$SED" && SED=sed
+Xsed="$SED -e 1s/^X//"
+_LT_DECL([], [SED], [1], [A sed program that does not truncate output])
+_LT_DECL([], [Xsed], ["\$SED -e 1s/^X//"],
+    [Sed that helps us avoid accidentally triggering echo(1) options like -n])
+])# _LT_DECL_SED
+
+m4_ifndef([AC_PROG_SED], [
+############################################################
+# NOTE: This macro has been submitted for inclusion into   #
+#  GNU Autoconf as AC_PROG_SED.  When it is available in   #
+#  a released version of Autoconf we should remove this    #
+#  macro and use it instead.                               #
+############################################################
+
+m4_defun([AC_PROG_SED],
+[AC_MSG_CHECKING([for a sed that does not truncate output])
+AC_CACHE_VAL(lt_cv_path_SED,
+[# Loop through the user's path and test for sed and gsed.
+# Then use that list of sed's as ones to test for truncation.
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  for lt_ac_prog in sed gsed; do
+    for ac_exec_ext in '' $ac_executable_extensions; do
+      if $as_executable_p "$as_dir/$lt_ac_prog$ac_exec_ext"; then
+        lt_ac_sed_list="$lt_ac_sed_list $as_dir/$lt_ac_prog$ac_exec_ext"
+      fi
+    done
+  done
+done
+IFS=$as_save_IFS
+lt_ac_max=0
+lt_ac_count=0
+# Add /usr/xpg4/bin/sed as it is typically found on Solaris
+# along with /bin/sed that truncates output.
+for lt_ac_sed in $lt_ac_sed_list /usr/xpg4/bin/sed; do
+  test ! -f $lt_ac_sed && continue
+  cat /dev/null > conftest.in
+  lt_ac_count=0
+  echo $ECHO_N "0123456789$ECHO_C" >conftest.in
+  # Check for GNU sed and select it if it is found.
+  if "$lt_ac_sed" --version 2>&1 < /dev/null | grep 'GNU' > /dev/null; then
+    lt_cv_path_SED=$lt_ac_sed
+    break
+  fi
+  while true; do
+    cat conftest.in conftest.in >conftest.tmp
+    mv conftest.tmp conftest.in
+    cp conftest.in conftest.nl
+    echo >>conftest.nl
+    $lt_ac_sed -e 's/a$//' < conftest.nl >conftest.out || break
+    cmp -s conftest.out conftest.nl || break
+    # 10000 chars as input seems more than enough
+    test $lt_ac_count -gt 10 && break
+    lt_ac_count=`expr $lt_ac_count + 1`
+    if test $lt_ac_count -gt $lt_ac_max; then
+      lt_ac_max=$lt_ac_count
+      lt_cv_path_SED=$lt_ac_sed
+    fi
+  done
+done
+])
+SED=$lt_cv_path_SED
+AC_SUBST([SED])
+AC_MSG_RESULT([$SED])
+])#AC_PROG_SED
+])#m4_ifndef
+
+# Old name:
+AU_ALIAS([LT_AC_PROG_SED], [AC_PROG_SED])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([LT_AC_PROG_SED], [])
+
+
+# _LT_CHECK_SHELL_FEATURES
+# ------------------------
+# Find out whether the shell is Bourne or XSI compatible,
+# or has some other useful features.
+m4_defun([_LT_CHECK_SHELL_FEATURES],
+[AC_MSG_CHECKING([whether the shell understands some XSI constructs])
+# Try some XSI features
+xsi_shell=no
+( _lt_dummy="a/b/c"
+  test "${_lt_dummy##*/},${_lt_dummy%/*},${_lt_dummy#??}"${_lt_dummy%"$_lt_dummy"}, \
+      = c,a/b,b/c, \
+    && eval 'test $(( 1 + 1 )) -eq 2 \
+    && test "${#_lt_dummy}" -eq 5' ) >/dev/null 2>&1 \
+  && xsi_shell=yes
+AC_MSG_RESULT([$xsi_shell])
+_LT_CONFIG_LIBTOOL_INIT([xsi_shell='$xsi_shell'])
+
+AC_MSG_CHECKING([whether the shell understands "+="])
+lt_shell_append=no
+( foo=bar; set foo baz; eval "$[1]+=\$[2]" && test "$foo" = barbaz ) \
+    >/dev/null 2>&1 \
+  && lt_shell_append=yes
+AC_MSG_RESULT([$lt_shell_append])
+_LT_CONFIG_LIBTOOL_INIT([lt_shell_append='$lt_shell_append'])
+
+if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then
+  lt_unset=unset
+else
+  lt_unset=false
+fi
+_LT_DECL([], [lt_unset], [0], [whether the shell understands "unset"])dnl
+
+# test EBCDIC or ASCII
+case `echo X|tr X '\101'` in
+ A) # ASCII based system
+    # \n is not interpreted correctly by Solaris 8 /usr/ucb/tr
+  lt_SP2NL='tr \040 \012'
+  lt_NL2SP='tr \015\012 \040\040'
+  ;;
+ *) # EBCDIC based system
+  lt_SP2NL='tr \100 \n'
+  lt_NL2SP='tr \r\n \100\100'
+  ;;
+esac
+_LT_DECL([SP2NL], [lt_SP2NL], [1], [turn spaces into newlines])dnl
+_LT_DECL([NL2SP], [lt_NL2SP], [1], [turn newlines into spaces])dnl
+])# _LT_CHECK_SHELL_FEATURES
+
+
+# _LT_PROG_FUNCTION_REPLACE (FUNCNAME, REPLACEMENT-BODY)
+# ------------------------------------------------------
+# In `$cfgfile', look for function FUNCNAME delimited by `^FUNCNAME ()$' and
+# '^} FUNCNAME ', and replace its body with REPLACEMENT-BODY.
+m4_defun([_LT_PROG_FUNCTION_REPLACE],
+[dnl {
+sed -e '/^$1 ()$/,/^} # $1 /c\
+$1 ()\
+{\
+m4_bpatsubsts([$2], [$], [\\], [^\([	 ]\)], [\\\1])
+} # Extended-shell $1 implementation' "$cfgfile" > $cfgfile.tmp \
+  && mv -f "$cfgfile.tmp" "$cfgfile" \
+    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
+test 0 -eq $? || _lt_function_replace_fail=:
+])
+
+
+# _LT_PROG_REPLACE_SHELLFNS
+# -------------------------
+# Replace existing portable implementations of several shell functions with
+# equivalent extended shell implementations where those features are available..
+m4_defun([_LT_PROG_REPLACE_SHELLFNS],
+[if test x"$xsi_shell" = xyes; then
+  _LT_PROG_FUNCTION_REPLACE([func_dirname], [dnl
+    case ${1} in
+      */*) func_dirname_result="${1%/*}${2}" ;;
+      *  ) func_dirname_result="${3}" ;;
+    esac])
+
+  _LT_PROG_FUNCTION_REPLACE([func_basename], [dnl
+    func_basename_result="${1##*/}"])
+
+  _LT_PROG_FUNCTION_REPLACE([func_dirname_and_basename], [dnl
+    case ${1} in
+      */*) func_dirname_result="${1%/*}${2}" ;;
+      *  ) func_dirname_result="${3}" ;;
+    esac
+    func_basename_result="${1##*/}"])
+
+  _LT_PROG_FUNCTION_REPLACE([func_stripname], [dnl
+    # pdksh 5.2.14 does not do ${X%$Y} correctly if both X and Y are
+    # positional parameters, so assign one to ordinary parameter first.
+    func_stripname_result=${3}
+    func_stripname_result=${func_stripname_result#"${1}"}
+    func_stripname_result=${func_stripname_result%"${2}"}])
+
+  _LT_PROG_FUNCTION_REPLACE([func_split_long_opt], [dnl
+    func_split_long_opt_name=${1%%=*}
+    func_split_long_opt_arg=${1#*=}])
+
+  _LT_PROG_FUNCTION_REPLACE([func_split_short_opt], [dnl
+    func_split_short_opt_arg=${1#??}
+    func_split_short_opt_name=${1%"$func_split_short_opt_arg"}])
+
+  _LT_PROG_FUNCTION_REPLACE([func_lo2o], [dnl
+    case ${1} in
+      *.lo) func_lo2o_result=${1%.lo}.${objext} ;;
+      *)    func_lo2o_result=${1} ;;
+    esac])
+
+  _LT_PROG_FUNCTION_REPLACE([func_xform], [    func_xform_result=${1%.*}.lo])
+
+  _LT_PROG_FUNCTION_REPLACE([func_arith], [    func_arith_result=$(( $[*] ))])
+
+  _LT_PROG_FUNCTION_REPLACE([func_len], [    func_len_result=${#1}])
+fi
+
+if test x"$lt_shell_append" = xyes; then
+  _LT_PROG_FUNCTION_REPLACE([func_append], [    eval "${1}+=\\${2}"])
+
+  _LT_PROG_FUNCTION_REPLACE([func_append_quoted], [dnl
+    func_quote_for_eval "${2}"
+dnl m4 expansion turns \\\\ into \\, and then the shell eval turns that into \
+    eval "${1}+=\\\\ \\$func_quote_for_eval_result"])
+
+  # Save a `func_append' function call where possible by direct use of '+='
+  sed -e 's%func_append \([[a-zA-Z_]]\{1,\}\) "%\1+="%g' $cfgfile > $cfgfile.tmp \
+    && mv -f "$cfgfile.tmp" "$cfgfile" \
+      || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
+  test 0 -eq $? || _lt_function_replace_fail=:
+else
+  # Save a `func_append' function call even when '+=' is not available
+  sed -e 's%func_append \([[a-zA-Z_]]\{1,\}\) "%\1="$\1%g' $cfgfile > $cfgfile.tmp \
+    && mv -f "$cfgfile.tmp" "$cfgfile" \
+      || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
+  test 0 -eq $? || _lt_function_replace_fail=:
+fi
+
+if test x"$_lt_function_replace_fail" = x":"; then
+  AC_MSG_WARN([Unable to substitute extended shell functions in $ofile])
+fi
+])
+
+# _LT_PATH_CONVERSION_FUNCTIONS
+# -----------------------------
+# Determine which file name conversion functions should be used by
+# func_to_host_file (and, implicitly, by func_to_host_path).  These are needed
+# for certain cross-compile configurations and native mingw.
+m4_defun([_LT_PATH_CONVERSION_FUNCTIONS],
+[AC_REQUIRE([AC_CANONICAL_HOST])dnl
+AC_REQUIRE([AC_CANONICAL_BUILD])dnl
+AC_MSG_CHECKING([how to convert $build file names to $host format])
+AC_CACHE_VAL(lt_cv_to_host_file_cmd,
+[case $host in
+  *-*-mingw* )
+    case $build in
+      *-*-mingw* ) # actually msys
+        lt_cv_to_host_file_cmd=func_convert_file_msys_to_w32
+        ;;
+      *-*-cygwin* )
+        lt_cv_to_host_file_cmd=func_convert_file_cygwin_to_w32
+        ;;
+      * ) # otherwise, assume *nix
+        lt_cv_to_host_file_cmd=func_convert_file_nix_to_w32
+        ;;
+    esac
+    ;;
+  *-*-cygwin* )
+    case $build in
+      *-*-mingw* ) # actually msys
+        lt_cv_to_host_file_cmd=func_convert_file_msys_to_cygwin
+        ;;
+      *-*-cygwin* )
+        lt_cv_to_host_file_cmd=func_convert_file_noop
+        ;;
+      * ) # otherwise, assume *nix
+        lt_cv_to_host_file_cmd=func_convert_file_nix_to_cygwin
+        ;;
+    esac
+    ;;
+  * ) # unhandled hosts (and "normal" native builds)
+    lt_cv_to_host_file_cmd=func_convert_file_noop
+    ;;
+esac
+])
+to_host_file_cmd=$lt_cv_to_host_file_cmd
+AC_MSG_RESULT([$lt_cv_to_host_file_cmd])
+_LT_DECL([to_host_file_cmd], [lt_cv_to_host_file_cmd],
+         [0], [convert $build file names to $host format])dnl
+
+AC_MSG_CHECKING([how to convert $build file names to toolchain format])
+AC_CACHE_VAL(lt_cv_to_tool_file_cmd,
+[#assume ordinary cross tools, or native build.
+lt_cv_to_tool_file_cmd=func_convert_file_noop
+case $host in
+  *-*-mingw* )
+    case $build in
+      *-*-mingw* ) # actually msys
+        lt_cv_to_tool_file_cmd=func_convert_file_msys_to_w32
+        ;;
+    esac
+    ;;
+esac
+])
+to_tool_file_cmd=$lt_cv_to_tool_file_cmd
+AC_MSG_RESULT([$lt_cv_to_tool_file_cmd])
+_LT_DECL([to_tool_file_cmd], [lt_cv_to_tool_file_cmd],
+         [0], [convert $build files to toolchain format])dnl
+])# _LT_PATH_CONVERSION_FUNCTIONS
diff --git a/m4/ltoptions.m4 b/m4/ltoptions.m4
new file mode 100644
index 0000000..5d9acd8
--- /dev/null
+++ b/m4/ltoptions.m4
@@ -0,0 +1,384 @@
+# Helper functions for option handling.                    -*- Autoconf -*-
+#
+#   Copyright (C) 2004, 2005, 2007, 2008, 2009 Free Software Foundation,
+#   Inc.
+#   Written by Gary V. Vaughan, 2004
+#
+# This file is free software; the Free Software Foundation gives
+# unlimited permission to copy and/or distribute it, with or without
+# modifications, as long as this notice is preserved.
+
+# serial 7 ltoptions.m4
+
+# This is to help aclocal find these macros, as it can't see m4_define.
+AC_DEFUN([LTOPTIONS_VERSION], [m4_if([1])])
+
+
+# _LT_MANGLE_OPTION(MACRO-NAME, OPTION-NAME)
+# ------------------------------------------
+m4_define([_LT_MANGLE_OPTION],
+[[_LT_OPTION_]m4_bpatsubst($1__$2, [[^a-zA-Z0-9_]], [_])])
+
+
+# _LT_SET_OPTION(MACRO-NAME, OPTION-NAME)
+# ---------------------------------------
+# Set option OPTION-NAME for macro MACRO-NAME, and if there is a
+# matching handler defined, dispatch to it.  Other OPTION-NAMEs are
+# saved as a flag.
+m4_define([_LT_SET_OPTION],
+[m4_define(_LT_MANGLE_OPTION([$1], [$2]))dnl
+m4_ifdef(_LT_MANGLE_DEFUN([$1], [$2]),
+        _LT_MANGLE_DEFUN([$1], [$2]),
+    [m4_warning([Unknown $1 option `$2'])])[]dnl
+])
+
+
+# _LT_IF_OPTION(MACRO-NAME, OPTION-NAME, IF-SET, [IF-NOT-SET])
+# ------------------------------------------------------------
+# Execute IF-SET if OPTION is set, IF-NOT-SET otherwise.
+m4_define([_LT_IF_OPTION],
+[m4_ifdef(_LT_MANGLE_OPTION([$1], [$2]), [$3], [$4])])
+
+
+# _LT_UNLESS_OPTIONS(MACRO-NAME, OPTION-LIST, IF-NOT-SET)
+# -------------------------------------------------------
+# Execute IF-NOT-SET unless all options in OPTION-LIST for MACRO-NAME
+# are set.
+m4_define([_LT_UNLESS_OPTIONS],
+[m4_foreach([_LT_Option], m4_split(m4_normalize([$2])),
+	    [m4_ifdef(_LT_MANGLE_OPTION([$1], _LT_Option),
+		      [m4_define([$0_found])])])[]dnl
+m4_ifdef([$0_found], [m4_undefine([$0_found])], [$3
+])[]dnl
+])
+
+
+# _LT_SET_OPTIONS(MACRO-NAME, OPTION-LIST)
+# ----------------------------------------
+# OPTION-LIST is a space-separated list of Libtool options associated
+# with MACRO-NAME.  If any OPTION has a matching handler declared with
+# LT_OPTION_DEFINE, dispatch to that macro; otherwise complain about
+# the unknown option and exit.
+m4_defun([_LT_SET_OPTIONS],
+[# Set options
+m4_foreach([_LT_Option], m4_split(m4_normalize([$2])),
+    [_LT_SET_OPTION([$1], _LT_Option)])
+
+m4_if([$1],[LT_INIT],[
+  dnl
+  dnl Simply set some default values (i.e off) if boolean options were not
+  dnl specified:
+  _LT_UNLESS_OPTIONS([LT_INIT], [dlopen], [enable_dlopen=no
+  ])
+  _LT_UNLESS_OPTIONS([LT_INIT], [win32-dll], [enable_win32_dll=no
+  ])
+  dnl
+  dnl If no reference was made to various pairs of opposing options, then
+  dnl we run the default mode handler for the pair.  For example, if neither
+  dnl `shared' nor `disable-shared' was passed, we enable building of shared
+  dnl archives by default:
+  _LT_UNLESS_OPTIONS([LT_INIT], [shared disable-shared], [_LT_ENABLE_SHARED])
+  _LT_UNLESS_OPTIONS([LT_INIT], [static disable-static], [_LT_ENABLE_STATIC])
+  _LT_UNLESS_OPTIONS([LT_INIT], [pic-only no-pic], [_LT_WITH_PIC])
+  _LT_UNLESS_OPTIONS([LT_INIT], [fast-install disable-fast-install],
+  		   [_LT_ENABLE_FAST_INSTALL])
+  ])
+])# _LT_SET_OPTIONS
+
+
+## --------------------------------- ##
+## Macros to handle LT_INIT options. ##
+## --------------------------------- ##
+
+# _LT_MANGLE_DEFUN(MACRO-NAME, OPTION-NAME)
+# -----------------------------------------
+m4_define([_LT_MANGLE_DEFUN],
+[[_LT_OPTION_DEFUN_]m4_bpatsubst(m4_toupper([$1__$2]), [[^A-Z0-9_]], [_])])
+
+
+# LT_OPTION_DEFINE(MACRO-NAME, OPTION-NAME, CODE)
+# -----------------------------------------------
+m4_define([LT_OPTION_DEFINE],
+[m4_define(_LT_MANGLE_DEFUN([$1], [$2]), [$3])[]dnl
+])# LT_OPTION_DEFINE
+
+
+# dlopen
+# ------
+LT_OPTION_DEFINE([LT_INIT], [dlopen], [enable_dlopen=yes
+])
+
+AU_DEFUN([AC_LIBTOOL_DLOPEN],
+[_LT_SET_OPTION([LT_INIT], [dlopen])
+AC_DIAGNOSE([obsolete],
+[$0: Remove this warning and the call to _LT_SET_OPTION when you
+put the `dlopen' option into LT_INIT's first parameter.])
+])
+
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_LIBTOOL_DLOPEN], [])
+
+
+# win32-dll
+# ---------
+# Declare package support for building win32 dll's.
+LT_OPTION_DEFINE([LT_INIT], [win32-dll],
+[enable_win32_dll=yes
+
+case $host in
+*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-cegcc*)
+  AC_CHECK_TOOL(AS, as, false)
+  AC_CHECK_TOOL(DLLTOOL, dlltool, false)
+  AC_CHECK_TOOL(OBJDUMP, objdump, false)
+  ;;
+esac
+
+test -z "$AS" && AS=as
+_LT_DECL([], [AS],      [1], [Assembler program])dnl
+
+test -z "$DLLTOOL" && DLLTOOL=dlltool
+_LT_DECL([], [DLLTOOL], [1], [DLL creation program])dnl
+
+test -z "$OBJDUMP" && OBJDUMP=objdump
+_LT_DECL([], [OBJDUMP], [1], [Object dumper program])dnl
+])# win32-dll
+
+AU_DEFUN([AC_LIBTOOL_WIN32_DLL],
+[AC_REQUIRE([AC_CANONICAL_HOST])dnl
+_LT_SET_OPTION([LT_INIT], [win32-dll])
+AC_DIAGNOSE([obsolete],
+[$0: Remove this warning and the call to _LT_SET_OPTION when you
+put the `win32-dll' option into LT_INIT's first parameter.])
+])
+
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_LIBTOOL_WIN32_DLL], [])
+
+
+# _LT_ENABLE_SHARED([DEFAULT])
+# ----------------------------
+# implement the --enable-shared flag, and supports the `shared' and
+# `disable-shared' LT_INIT options.
+# DEFAULT is either `yes' or `no'.  If omitted, it defaults to `yes'.
+m4_define([_LT_ENABLE_SHARED],
+[m4_define([_LT_ENABLE_SHARED_DEFAULT], [m4_if($1, no, no, yes)])dnl
+AC_ARG_ENABLE([shared],
+    [AS_HELP_STRING([--enable-shared@<:@=PKGS@:>@],
+	[build shared libraries @<:@default=]_LT_ENABLE_SHARED_DEFAULT[@:>@])],
+    [p=${PACKAGE-default}
+    case $enableval in
+    yes) enable_shared=yes ;;
+    no) enable_shared=no ;;
+    *)
+      enable_shared=no
+      # Look at the argument we got.  We use all the common list separators.
+      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
+      for pkg in $enableval; do
+	IFS="$lt_save_ifs"
+	if test "X$pkg" = "X$p"; then
+	  enable_shared=yes
+	fi
+      done
+      IFS="$lt_save_ifs"
+      ;;
+    esac],
+    [enable_shared=]_LT_ENABLE_SHARED_DEFAULT)
+
+    _LT_DECL([build_libtool_libs], [enable_shared], [0],
+	[Whether or not to build shared libraries])
+])# _LT_ENABLE_SHARED
+
+LT_OPTION_DEFINE([LT_INIT], [shared], [_LT_ENABLE_SHARED([yes])])
+LT_OPTION_DEFINE([LT_INIT], [disable-shared], [_LT_ENABLE_SHARED([no])])
+
+# Old names:
+AC_DEFUN([AC_ENABLE_SHARED],
+[_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[shared])
+])
+
+AC_DEFUN([AC_DISABLE_SHARED],
+[_LT_SET_OPTION([LT_INIT], [disable-shared])
+])
+
+AU_DEFUN([AM_ENABLE_SHARED], [AC_ENABLE_SHARED($@)])
+AU_DEFUN([AM_DISABLE_SHARED], [AC_DISABLE_SHARED($@)])
+
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AM_ENABLE_SHARED], [])
+dnl AC_DEFUN([AM_DISABLE_SHARED], [])
+
+
+
+# _LT_ENABLE_STATIC([DEFAULT])
+# ----------------------------
+# implement the --enable-static flag, and support the `static' and
+# `disable-static' LT_INIT options.
+# DEFAULT is either `yes' or `no'.  If omitted, it defaults to `yes'.
+m4_define([_LT_ENABLE_STATIC],
+[m4_define([_LT_ENABLE_STATIC_DEFAULT], [m4_if($1, no, no, yes)])dnl
+AC_ARG_ENABLE([static],
+    [AS_HELP_STRING([--enable-static@<:@=PKGS@:>@],
+	[build static libraries @<:@default=]_LT_ENABLE_STATIC_DEFAULT[@:>@])],
+    [p=${PACKAGE-default}
+    case $enableval in
+    yes) enable_static=yes ;;
+    no) enable_static=no ;;
+    *)
+     enable_static=no
+      # Look at the argument we got.  We use all the common list separators.
+      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
+      for pkg in $enableval; do
+	IFS="$lt_save_ifs"
+	if test "X$pkg" = "X$p"; then
+	  enable_static=yes
+	fi
+      done
+      IFS="$lt_save_ifs"
+      ;;
+    esac],
+    [enable_static=]_LT_ENABLE_STATIC_DEFAULT)
+
+    _LT_DECL([build_old_libs], [enable_static], [0],
+	[Whether or not to build static libraries])
+])# _LT_ENABLE_STATIC
+
+LT_OPTION_DEFINE([LT_INIT], [static], [_LT_ENABLE_STATIC([yes])])
+LT_OPTION_DEFINE([LT_INIT], [disable-static], [_LT_ENABLE_STATIC([no])])
+
+# Old names:
+AC_DEFUN([AC_ENABLE_STATIC],
+[_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[static])
+])
+
+AC_DEFUN([AC_DISABLE_STATIC],
+[_LT_SET_OPTION([LT_INIT], [disable-static])
+])
+
+AU_DEFUN([AM_ENABLE_STATIC], [AC_ENABLE_STATIC($@)])
+AU_DEFUN([AM_DISABLE_STATIC], [AC_DISABLE_STATIC($@)])
+
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AM_ENABLE_STATIC], [])
+dnl AC_DEFUN([AM_DISABLE_STATIC], [])
+
+
+
+# _LT_ENABLE_FAST_INSTALL([DEFAULT])
+# ----------------------------------
+# implement the --enable-fast-install flag, and support the `fast-install'
+# and `disable-fast-install' LT_INIT options.
+# DEFAULT is either `yes' or `no'.  If omitted, it defaults to `yes'.
+m4_define([_LT_ENABLE_FAST_INSTALL],
+[m4_define([_LT_ENABLE_FAST_INSTALL_DEFAULT], [m4_if($1, no, no, yes)])dnl
+AC_ARG_ENABLE([fast-install],
+    [AS_HELP_STRING([--enable-fast-install@<:@=PKGS@:>@],
+    [optimize for fast installation @<:@default=]_LT_ENABLE_FAST_INSTALL_DEFAULT[@:>@])],
+    [p=${PACKAGE-default}
+    case $enableval in
+    yes) enable_fast_install=yes ;;
+    no) enable_fast_install=no ;;
+    *)
+      enable_fast_install=no
+      # Look at the argument we got.  We use all the common list separators.
+      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
+      for pkg in $enableval; do
+	IFS="$lt_save_ifs"
+	if test "X$pkg" = "X$p"; then
+	  enable_fast_install=yes
+	fi
+      done
+      IFS="$lt_save_ifs"
+      ;;
+    esac],
+    [enable_fast_install=]_LT_ENABLE_FAST_INSTALL_DEFAULT)
+
+_LT_DECL([fast_install], [enable_fast_install], [0],
+	 [Whether or not to optimize for fast installation])dnl
+])# _LT_ENABLE_FAST_INSTALL
+
+LT_OPTION_DEFINE([LT_INIT], [fast-install], [_LT_ENABLE_FAST_INSTALL([yes])])
+LT_OPTION_DEFINE([LT_INIT], [disable-fast-install], [_LT_ENABLE_FAST_INSTALL([no])])
+
+# Old names:
+AU_DEFUN([AC_ENABLE_FAST_INSTALL],
+[_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[fast-install])
+AC_DIAGNOSE([obsolete],
+[$0: Remove this warning and the call to _LT_SET_OPTION when you put
+the `fast-install' option into LT_INIT's first parameter.])
+])
+
+AU_DEFUN([AC_DISABLE_FAST_INSTALL],
+[_LT_SET_OPTION([LT_INIT], [disable-fast-install])
+AC_DIAGNOSE([obsolete],
+[$0: Remove this warning and the call to _LT_SET_OPTION when you put
+the `disable-fast-install' option into LT_INIT's first parameter.])
+])
+
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_ENABLE_FAST_INSTALL], [])
+dnl AC_DEFUN([AM_DISABLE_FAST_INSTALL], [])
+
+
+# _LT_WITH_PIC([MODE])
+# --------------------
+# implement the --with-pic flag, and support the `pic-only' and `no-pic'
+# LT_INIT options.
+# MODE is either `yes' or `no'.  If omitted, it defaults to `both'.
+m4_define([_LT_WITH_PIC],
+[AC_ARG_WITH([pic],
+    [AS_HELP_STRING([--with-pic@<:@=PKGS@:>@],
+	[try to use only PIC/non-PIC objects @<:@default=use both@:>@])],
+    [lt_p=${PACKAGE-default}
+    case $withval in
+    yes|no) pic_mode=$withval ;;
+    *)
+      pic_mode=default
+      # Look at the argument we got.  We use all the common list separators.
+      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
+      for lt_pkg in $withval; do
+	IFS="$lt_save_ifs"
+	if test "X$lt_pkg" = "X$lt_p"; then
+	  pic_mode=yes
+	fi
+      done
+      IFS="$lt_save_ifs"
+      ;;
+    esac],
+    [pic_mode=default])
+
+test -z "$pic_mode" && pic_mode=m4_default([$1], [default])
+
+_LT_DECL([], [pic_mode], [0], [What type of objects to build])dnl
+])# _LT_WITH_PIC
+
+LT_OPTION_DEFINE([LT_INIT], [pic-only], [_LT_WITH_PIC([yes])])
+LT_OPTION_DEFINE([LT_INIT], [no-pic], [_LT_WITH_PIC([no])])
+
+# Old name:
+AU_DEFUN([AC_LIBTOOL_PICMODE],
+[_LT_SET_OPTION([LT_INIT], [pic-only])
+AC_DIAGNOSE([obsolete],
+[$0: Remove this warning and the call to _LT_SET_OPTION when you
+put the `pic-only' option into LT_INIT's first parameter.])
+])
+
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_LIBTOOL_PICMODE], [])
+
+## ----------------- ##
+## LTDL_INIT Options ##
+## ----------------- ##
+
+m4_define([_LTDL_MODE], [])
+LT_OPTION_DEFINE([LTDL_INIT], [nonrecursive],
+		 [m4_define([_LTDL_MODE], [nonrecursive])])
+LT_OPTION_DEFINE([LTDL_INIT], [recursive],
+		 [m4_define([_LTDL_MODE], [recursive])])
+LT_OPTION_DEFINE([LTDL_INIT], [subproject],
+		 [m4_define([_LTDL_MODE], [subproject])])
+
+m4_define([_LTDL_TYPE], [])
+LT_OPTION_DEFINE([LTDL_INIT], [installable],
+		 [m4_define([_LTDL_TYPE], [installable])])
+LT_OPTION_DEFINE([LTDL_INIT], [convenience],
+		 [m4_define([_LTDL_TYPE], [convenience])])
diff --git a/m4/ltsugar.m4 b/m4/ltsugar.m4
new file mode 100644
index 0000000..9000a05
--- /dev/null
+++ b/m4/ltsugar.m4
@@ -0,0 +1,123 @@
+# ltsugar.m4 -- libtool m4 base layer.                         -*-Autoconf-*-
+#
+# Copyright (C) 2004, 2005, 2007, 2008 Free Software Foundation, Inc.
+# Written by Gary V. Vaughan, 2004
+#
+# This file is free software; the Free Software Foundation gives
+# unlimited permission to copy and/or distribute it, with or without
+# modifications, as long as this notice is preserved.
+
+# serial 6 ltsugar.m4
+
+# This is to help aclocal find these macros, as it can't see m4_define.
+AC_DEFUN([LTSUGAR_VERSION], [m4_if([0.1])])
+
+
+# lt_join(SEP, ARG1, [ARG2...])
+# -----------------------------
+# Produce ARG1SEPARG2...SEPARGn, omitting [] arguments and their
+# associated separator.
+# Needed until we can rely on m4_join from Autoconf 2.62, since all earlier
+# versions in m4sugar had bugs.
+m4_define([lt_join],
+[m4_if([$#], [1], [],
+       [$#], [2], [[$2]],
+       [m4_if([$2], [], [], [[$2]_])$0([$1], m4_shift(m4_shift($@)))])])
+m4_define([_lt_join],
+[m4_if([$#$2], [2], [],
+       [m4_if([$2], [], [], [[$1$2]])$0([$1], m4_shift(m4_shift($@)))])])
+
+
+# lt_car(LIST)
+# lt_cdr(LIST)
+# ------------
+# Manipulate m4 lists.
+# These macros are necessary as long as will still need to support
+# Autoconf-2.59 which quotes differently.
+m4_define([lt_car], [[$1]])
+m4_define([lt_cdr],
+[m4_if([$#], 0, [m4_fatal([$0: cannot be called without arguments])],
+       [$#], 1, [],
+       [m4_dquote(m4_shift($@))])])
+m4_define([lt_unquote], $1)
+
+
+# lt_append(MACRO-NAME, STRING, [SEPARATOR])
+# ------------------------------------------
+# Redefine MACRO-NAME to hold its former content plus `SEPARATOR'`STRING'.
+# Note that neither SEPARATOR nor STRING are expanded; they are appended
+# to MACRO-NAME as is (leaving the expansion for when MACRO-NAME is invoked).
+# No SEPARATOR is output if MACRO-NAME was previously undefined (different
+# than defined and empty).
+#
+# This macro is needed until we can rely on Autoconf 2.62, since earlier
+# versions of m4sugar mistakenly expanded SEPARATOR but not STRING.
+m4_define([lt_append],
+[m4_define([$1],
+	   m4_ifdef([$1], [m4_defn([$1])[$3]])[$2])])
+
+
+
+# lt_combine(SEP, PREFIX-LIST, INFIX, SUFFIX1, [SUFFIX2...])
+# ----------------------------------------------------------
+# Produce a SEP delimited list of all paired combinations of elements of
+# PREFIX-LIST with SUFFIX1 through SUFFIXn.  Each element of the list
+# has the form PREFIXmINFIXSUFFIXn.
+# Needed until we can rely on m4_combine added in Autoconf 2.62.
+m4_define([lt_combine],
+[m4_if(m4_eval([$# > 3]), [1],
+       [m4_pushdef([_Lt_sep], [m4_define([_Lt_sep], m4_defn([lt_car]))])]]dnl
+[[m4_foreach([_Lt_prefix], [$2],
+	     [m4_foreach([_Lt_suffix],
+		]m4_dquote(m4_dquote(m4_shift(m4_shift(m4_shift($@)))))[,
+	[_Lt_sep([$1])[]m4_defn([_Lt_prefix])[$3]m4_defn([_Lt_suffix])])])])])
+
+
+# lt_if_append_uniq(MACRO-NAME, VARNAME, [SEPARATOR], [UNIQ], [NOT-UNIQ])
+# -----------------------------------------------------------------------
+# Iff MACRO-NAME does not yet contain VARNAME, then append it (delimited
+# by SEPARATOR if supplied) and expand UNIQ, else NOT-UNIQ.
+m4_define([lt_if_append_uniq],
+[m4_ifdef([$1],
+	  [m4_if(m4_index([$3]m4_defn([$1])[$3], [$3$2$3]), [-1],
+		 [lt_append([$1], [$2], [$3])$4],
+		 [$5])],
+	  [lt_append([$1], [$2], [$3])$4])])
+
+
+# lt_dict_add(DICT, KEY, VALUE)
+# -----------------------------
+m4_define([lt_dict_add],
+[m4_define([$1($2)], [$3])])
+
+
+# lt_dict_add_subkey(DICT, KEY, SUBKEY, VALUE)
+# --------------------------------------------
+m4_define([lt_dict_add_subkey],
+[m4_define([$1($2:$3)], [$4])])
+
+
+# lt_dict_fetch(DICT, KEY, [SUBKEY])
+# ----------------------------------
+m4_define([lt_dict_fetch],
+[m4_ifval([$3],
+	m4_ifdef([$1($2:$3)], [m4_defn([$1($2:$3)])]),
+    m4_ifdef([$1($2)], [m4_defn([$1($2)])]))])
+
+
+# lt_if_dict_fetch(DICT, KEY, [SUBKEY], VALUE, IF-TRUE, [IF-FALSE])
+# -----------------------------------------------------------------
+m4_define([lt_if_dict_fetch],
+[m4_if(lt_dict_fetch([$1], [$2], [$3]), [$4],
+	[$5],
+    [$6])])
+
+
+# lt_dict_filter(DICT, [SUBKEY], VALUE, [SEPARATOR], KEY, [...])
+# --------------------------------------------------------------
+m4_define([lt_dict_filter],
+[m4_if([$5], [], [],
+  [lt_join(m4_quote(m4_default([$4], [[, ]])),
+           lt_unquote(m4_split(m4_normalize(m4_foreach(_Lt_key, lt_car([m4_shiftn(4, $@)]),
+		      [lt_if_dict_fetch([$1], _Lt_key, [$2], [$3], [_Lt_key ])])))))])[]dnl
+])
diff --git a/m4/ltversion.m4 b/m4/ltversion.m4
new file mode 100644
index 0000000..07a8602
--- /dev/null
+++ b/m4/ltversion.m4
@@ -0,0 +1,23 @@
+# ltversion.m4 -- version numbers			-*- Autoconf -*-
+#
+#   Copyright (C) 2004 Free Software Foundation, Inc.
+#   Written by Scott James Remnant, 2004
+#
+# This file is free software; the Free Software Foundation gives
+# unlimited permission to copy and/or distribute it, with or without
+# modifications, as long as this notice is preserved.
+
+# @configure_input@
+
+# serial 3337 ltversion.m4
+# This file is part of GNU Libtool
+
+m4_define([LT_PACKAGE_VERSION], [2.4.2])
+m4_define([LT_PACKAGE_REVISION], [1.3337])
+
+AC_DEFUN([LTVERSION_VERSION],
+[macro_version='2.4.2'
+macro_revision='1.3337'
+_LT_DECL(, macro_version, 0, [Which release of libtool.m4 was used?])
+_LT_DECL(, macro_revision, 0)
+])
diff --git a/m4/lt~obsolete.m4 b/m4/lt~obsolete.m4
new file mode 100644
index 0000000..c573da9
--- /dev/null
+++ b/m4/lt~obsolete.m4
@@ -0,0 +1,98 @@
+# lt~obsolete.m4 -- aclocal satisfying obsolete definitions.    -*-Autoconf-*-
+#
+#   Copyright (C) 2004, 2005, 2007, 2009 Free Software Foundation, Inc.
+#   Written by Scott James Remnant, 2004.
+#
+# This file is free software; the Free Software Foundation gives
+# unlimited permission to copy and/or distribute it, with or without
+# modifications, as long as this notice is preserved.
+
+# serial 5 lt~obsolete.m4
+
+# These exist entirely to fool aclocal when bootstrapping libtool.
+#
+# In the past libtool.m4 has provided macros via AC_DEFUN (or AU_DEFUN)
+# which have later been changed to m4_define as they aren't part of the
+# exported API, or moved to Autoconf or Automake where they belong.
+#
+# The trouble is, aclocal is a bit thick.  It'll see the old AC_DEFUN
+# in /usr/share/aclocal/libtool.m4 and remember it, then when it sees us
+# using a macro with the same name in our local m4/libtool.m4 it'll
+# pull the old libtool.m4 in (it doesn't see our shiny new m4_define
+# and doesn't know about Autoconf macros at all.)
+#
+# So we provide this file, which has a silly filename so it's always
+# included after everything else.  This provides aclocal with the
+# AC_DEFUNs it wants, but when m4 processes it, it doesn't do anything
+# because those macros already exist, or will be overwritten later.
+# We use AC_DEFUN over AU_DEFUN for compatibility with aclocal-1.6. 
+#
+# Anytime we withdraw an AC_DEFUN or AU_DEFUN, remember to add it here.
+# Yes, that means every name once taken will need to remain here until
+# we give up compatibility with versions before 1.7, at which point
+# we need to keep only those names which we still refer to.
+
+# This is to help aclocal find these macros, as it can't see m4_define.
+AC_DEFUN([LTOBSOLETE_VERSION], [m4_if([1])])
+
+m4_ifndef([AC_LIBTOOL_LINKER_OPTION],	[AC_DEFUN([AC_LIBTOOL_LINKER_OPTION])])
+m4_ifndef([AC_PROG_EGREP],		[AC_DEFUN([AC_PROG_EGREP])])
+m4_ifndef([_LT_AC_PROG_ECHO_BACKSLASH],	[AC_DEFUN([_LT_AC_PROG_ECHO_BACKSLASH])])
+m4_ifndef([_LT_AC_SHELL_INIT],		[AC_DEFUN([_LT_AC_SHELL_INIT])])
+m4_ifndef([_LT_AC_SYS_LIBPATH_AIX],	[AC_DEFUN([_LT_AC_SYS_LIBPATH_AIX])])
+m4_ifndef([_LT_PROG_LTMAIN],		[AC_DEFUN([_LT_PROG_LTMAIN])])
+m4_ifndef([_LT_AC_TAGVAR],		[AC_DEFUN([_LT_AC_TAGVAR])])
+m4_ifndef([AC_LTDL_ENABLE_INSTALL],	[AC_DEFUN([AC_LTDL_ENABLE_INSTALL])])
+m4_ifndef([AC_LTDL_PREOPEN],		[AC_DEFUN([AC_LTDL_PREOPEN])])
+m4_ifndef([_LT_AC_SYS_COMPILER],	[AC_DEFUN([_LT_AC_SYS_COMPILER])])
+m4_ifndef([_LT_AC_LOCK],		[AC_DEFUN([_LT_AC_LOCK])])
+m4_ifndef([AC_LIBTOOL_SYS_OLD_ARCHIVE],	[AC_DEFUN([AC_LIBTOOL_SYS_OLD_ARCHIVE])])
+m4_ifndef([_LT_AC_TRY_DLOPEN_SELF],	[AC_DEFUN([_LT_AC_TRY_DLOPEN_SELF])])
+m4_ifndef([AC_LIBTOOL_PROG_CC_C_O],	[AC_DEFUN([AC_LIBTOOL_PROG_CC_C_O])])
+m4_ifndef([AC_LIBTOOL_SYS_HARD_LINK_LOCKS], [AC_DEFUN([AC_LIBTOOL_SYS_HARD_LINK_LOCKS])])
+m4_ifndef([AC_LIBTOOL_OBJDIR],		[AC_DEFUN([AC_LIBTOOL_OBJDIR])])
+m4_ifndef([AC_LTDL_OBJDIR],		[AC_DEFUN([AC_LTDL_OBJDIR])])
+m4_ifndef([AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH], [AC_DEFUN([AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH])])
+m4_ifndef([AC_LIBTOOL_SYS_LIB_STRIP],	[AC_DEFUN([AC_LIBTOOL_SYS_LIB_STRIP])])
+m4_ifndef([AC_PATH_MAGIC],		[AC_DEFUN([AC_PATH_MAGIC])])
+m4_ifndef([AC_PROG_LD_GNU],		[AC_DEFUN([AC_PROG_LD_GNU])])
+m4_ifndef([AC_PROG_LD_RELOAD_FLAG],	[AC_DEFUN([AC_PROG_LD_RELOAD_FLAG])])
+m4_ifndef([AC_DEPLIBS_CHECK_METHOD],	[AC_DEFUN([AC_DEPLIBS_CHECK_METHOD])])
+m4_ifndef([AC_LIBTOOL_PROG_COMPILER_NO_RTTI], [AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_NO_RTTI])])
+m4_ifndef([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE], [AC_DEFUN([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE])])
+m4_ifndef([AC_LIBTOOL_PROG_COMPILER_PIC], [AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_PIC])])
+m4_ifndef([AC_LIBTOOL_PROG_LD_SHLIBS],	[AC_DEFUN([AC_LIBTOOL_PROG_LD_SHLIBS])])
+m4_ifndef([AC_LIBTOOL_POSTDEP_PREDEP],	[AC_DEFUN([AC_LIBTOOL_POSTDEP_PREDEP])])
+m4_ifndef([LT_AC_PROG_EGREP],		[AC_DEFUN([LT_AC_PROG_EGREP])])
+m4_ifndef([LT_AC_PROG_SED],		[AC_DEFUN([LT_AC_PROG_SED])])
+m4_ifndef([_LT_CC_BASENAME],		[AC_DEFUN([_LT_CC_BASENAME])])
+m4_ifndef([_LT_COMPILER_BOILERPLATE],	[AC_DEFUN([_LT_COMPILER_BOILERPLATE])])
+m4_ifndef([_LT_LINKER_BOILERPLATE],	[AC_DEFUN([_LT_LINKER_BOILERPLATE])])
+m4_ifndef([_AC_PROG_LIBTOOL],		[AC_DEFUN([_AC_PROG_LIBTOOL])])
+m4_ifndef([AC_LIBTOOL_SETUP],		[AC_DEFUN([AC_LIBTOOL_SETUP])])
+m4_ifndef([_LT_AC_CHECK_DLFCN],		[AC_DEFUN([_LT_AC_CHECK_DLFCN])])
+m4_ifndef([AC_LIBTOOL_SYS_DYNAMIC_LINKER],	[AC_DEFUN([AC_LIBTOOL_SYS_DYNAMIC_LINKER])])
+m4_ifndef([_LT_AC_TAGCONFIG],		[AC_DEFUN([_LT_AC_TAGCONFIG])])
+m4_ifndef([AC_DISABLE_FAST_INSTALL],	[AC_DEFUN([AC_DISABLE_FAST_INSTALL])])
+m4_ifndef([_LT_AC_LANG_CXX],		[AC_DEFUN([_LT_AC_LANG_CXX])])
+m4_ifndef([_LT_AC_LANG_F77],		[AC_DEFUN([_LT_AC_LANG_F77])])
+m4_ifndef([_LT_AC_LANG_GCJ],		[AC_DEFUN([_LT_AC_LANG_GCJ])])
+m4_ifndef([AC_LIBTOOL_LANG_C_CONFIG],	[AC_DEFUN([AC_LIBTOOL_LANG_C_CONFIG])])
+m4_ifndef([_LT_AC_LANG_C_CONFIG],	[AC_DEFUN([_LT_AC_LANG_C_CONFIG])])
+m4_ifndef([AC_LIBTOOL_LANG_CXX_CONFIG],	[AC_DEFUN([AC_LIBTOOL_LANG_CXX_CONFIG])])
+m4_ifndef([_LT_AC_LANG_CXX_CONFIG],	[AC_DEFUN([_LT_AC_LANG_CXX_CONFIG])])
+m4_ifndef([AC_LIBTOOL_LANG_F77_CONFIG],	[AC_DEFUN([AC_LIBTOOL_LANG_F77_CONFIG])])
+m4_ifndef([_LT_AC_LANG_F77_CONFIG],	[AC_DEFUN([_LT_AC_LANG_F77_CONFIG])])
+m4_ifndef([AC_LIBTOOL_LANG_GCJ_CONFIG],	[AC_DEFUN([AC_LIBTOOL_LANG_GCJ_CONFIG])])
+m4_ifndef([_LT_AC_LANG_GCJ_CONFIG],	[AC_DEFUN([_LT_AC_LANG_GCJ_CONFIG])])
+m4_ifndef([AC_LIBTOOL_LANG_RC_CONFIG],	[AC_DEFUN([AC_LIBTOOL_LANG_RC_CONFIG])])
+m4_ifndef([_LT_AC_LANG_RC_CONFIG],	[AC_DEFUN([_LT_AC_LANG_RC_CONFIG])])
+m4_ifndef([AC_LIBTOOL_CONFIG],		[AC_DEFUN([AC_LIBTOOL_CONFIG])])
+m4_ifndef([_LT_AC_FILE_LTDLL_C],	[AC_DEFUN([_LT_AC_FILE_LTDLL_C])])
+m4_ifndef([_LT_REQUIRED_DARWIN_CHECKS],	[AC_DEFUN([_LT_REQUIRED_DARWIN_CHECKS])])
+m4_ifndef([_LT_AC_PROG_CXXCPP],		[AC_DEFUN([_LT_AC_PROG_CXXCPP])])
+m4_ifndef([_LT_PREPARE_SED_QUOTE_VARS],	[AC_DEFUN([_LT_PREPARE_SED_QUOTE_VARS])])
+m4_ifndef([_LT_PROG_ECHO_BACKSLASH],	[AC_DEFUN([_LT_PROG_ECHO_BACKSLASH])])
+m4_ifndef([_LT_PROG_F77],		[AC_DEFUN([_LT_PROG_F77])])
+m4_ifndef([_LT_PROG_FC],		[AC_DEFUN([_LT_PROG_FC])])
+m4_ifndef([_LT_PROG_CXX],		[AC_DEFUN([_LT_PROG_CXX])])
diff --git a/aclocal.m4 b/m4/mapserver.m4
similarity index 94%
copy from aclocal.m4
copy to m4/mapserver.m4
index 377a65c..43f1118 100644
--- a/aclocal.m4
+++ b/m4/mapserver.m4
@@ -1,10 +1,20 @@
+AC_DEFUN([PROG_CXX_WORKS],
+[AC_REQUIRE([AC_PROG_CXX])dnl
+AC_CACHE_CHECK([whether the C++ compiler works],
+               [rw_cv_prog_cxx_works],
+               [AC_LANG_PUSH([C++])
+                AC_LINK_IFELSE([AC_LANG_PROGRAM([], [])],
+                               [],
+                               [AC_MSG_ERROR([$CXX cannot compile])])
+                AC_LANG_POP([C++])])
+])
 
 dnl
 dnl AC_EXPAND_PATH(path, variable)
 dnl
 dnl expands path to an absolute path and assigns it to variable
 dnl
-AC_DEFUN(AC_EXPAND_PATH,[
+AC_DEFUN([AC_EXPAND_PATH],[
   if test -z "$1" || echo "$1" | grep '^/' >/dev/null ; then
     $2="$1"
   else
@@ -19,7 +29,7 @@ dnl
 dnl parse a --with-lib=[static,]/path/to/lib string, and set out_libpath 
 dnl with the library path, and out_isstatic=yes if "static," was there.
 dnl
-AC_DEFUN(AC_PARSE_WITH_LIB_STATIC,[
+AC_DEFUN([AC_PARSE_WITH_LIB_STATIC],[
   if echo "$1" | grep '^static,' >/dev/null ; then
     $2=`echo "$1" | sed "s/^static,//"`
     $3=yes
@@ -30,7 +40,7 @@ AC_DEFUN(AC_PARSE_WITH_LIB_STATIC,[
 ])
 
 
-AC_DEFUN(AC_COMPILER_PIC,
+AC_DEFUN([AC_COMPILER_PIC],
 [
 	echo 'void f(){}' > conftest.c
 	if test -z "`${CC} -fPIC -c conftest.c 2>&1`"; then
@@ -49,7 +59,7 @@ dnl check for -R, etc. switch
 dnl 
 dnl This was borrowed and adapted from the PHP configure.in script
 dnl
-AC_DEFUN(AC_RUNPATH_SWITCH,
+AC_DEFUN([AC_RUNPATH_SWITCH],
 [
   AC_MSG_CHECKING(if compiler supports -R)
   AC_CACHE_VAL(php_cv_cc_dashr,[
@@ -102,7 +112,7 @@ dnl AC_PHP_ONCE(namespace, variable, code)
 dnl
 dnl execute code, if variable is not set in namespace
 dnl
-AC_DEFUN(AC_PHP_ONCE,[
+AC_DEFUN([AC_PHP_ONCE],[
   unique=`echo $ac_n "$2$ac_c" | tr -c -d a-zA-Z0-9`
   cmd="echo $ac_n \"\$$1$unique$ac_c\""
   if test -n "$unique" && test "`eval $cmd`" = "" ; then
@@ -117,7 +127,7 @@ dnl
 dnl add a library to linkpath/runpath stored in RPATH 
 dnl works together with AC_RUNPATH_SWITCH()
 dnl
-AC_DEFUN(AC_ADD_RUNPATH,[
+AC_DEFUN([AC_ADD_RUNPATH],[
   if test "$1" != "/usr/lib"; then
     AC_EXPAND_PATH($1, ai_p)
     AC_PHP_ONCE(LIBPATH, $ai_p, [
@@ -138,7 +148,7 @@ dnl Try to find something to link shared libraries with.  Use "c++ -shared"
 dnl in preference to "ld -shared" because it will link in required c++
 dnl run time support for us. 
 dnl
-AC_DEFUN(AC_LD_SHARED,
+AC_DEFUN([AC_LD_SHARED],
 [
 
   echo 'void g(); int main(){ g(); return 0; }' > conftest1.c
@@ -292,7 +302,7 @@ dnl this is to use our normal LD_SHARED stuff for everything
 dnl except MacOSX.
 dnl
 
-AC_DEFUN(AC_PHP_LD_SHARED,[
+AC_DEFUN([AC_PHP_LD_SHARED],[
 
 
   AC_LD_SHARED()
@@ -318,7 +328,7 @@ dnl This is the preferred macro for the PHP module, but if perl is not
 dnl available then we can always fallback on AC_LD_SHARED above.
 dnl
 
-AC_DEFUN(AC_LD_SHARED_FROM_PERL,
+AC_DEFUN([AC_LD_SHARED_FROM_PERL],
 [
 #
 # The following is a massive hack.  It tries to steal the
diff --git a/mapagg.cpp b/mapagg.cpp
index 5ae1102..7d837f5 100644
--- a/mapagg.cpp
+++ b/mapagg.cpp
@@ -37,7 +37,6 @@
 #include "renderers/agg/include/agg_math_stroke.h"
 #include "renderers/agg/include/agg_scanline_p.h"
 #include "renderers/agg/include/agg_scanline_u.h"
-#include "renderers/agg/include/agg_scanline_bin.h"
 #include "renderers/agg/include/agg_rasterizer_scanline_aa.h"
 #include "renderers/agg/include/agg_span_pattern_rgba.h"
 #include "renderers/agg/include/agg_span_allocator.h"
@@ -52,9 +51,8 @@
 #include "renderers/agg/include/agg_font_freetype.h"
 #include "renderers/agg/include/agg_conv_contour.h"
 #include "renderers/agg/include/agg_ellipse.h"
+#include "renderers/agg/include/agg_gamma_functions.h"
 
-#include "renderers/agg/include/agg_scanline_boolean_algebra.h"
-#include "renderers/agg/include/agg_scanline_storage_aa.h"
 #include "renderers/agg/include/agg_rasterizer_outline_aa.h"
 #include "renderers/agg/include/agg_renderer_outline_aa.h"
 #include "renderers/agg/include/agg_renderer_outline_image.h"
@@ -71,11 +69,7 @@
 #include "renderers/agg/include/agg_rasterizer_outline.h"
 #endif
 
-#ifdef CPL_MSB
-typedef mapserver::order_argb band_order;
-#else
 typedef mapserver::order_bgra band_order;
-#endif
 
 #define AGG_LINESPACE 1.33
 
@@ -84,6 +78,7 @@ typedef mapserver::rgba8 color_type;
 typedef mapserver::pixel32_type pixel_type;
 
 typedef mapserver::blender_rgba_pre<color_type, band_order> blender_pre;
+
 typedef mapserver::pixfmt_alpha_blend_rgba<blender_pre, mapserver::rendering_buffer, pixel_type> pixel_format;
 typedef mapserver::rendering_buffer rendering_buffer;
 typedef mapserver::renderer_base<pixel_format> renderer_base;
@@ -99,984 +94,1165 @@ typedef mapserver::rasterizer_outline<renderer_primitives> rasterizer_outline;
 #endif
 static color_type AGG_NO_COLOR = color_type(0, 0, 0, 0);
 
-const mapserver::int8u* rasterfonts[]= { 
-        mapserver::mcs5x10_mono, /*gd tiny. gse5x7 is a bit less high than gd tiny*/
-        mapserver::mcs5x11_mono, /*gd small*/
-        mapserver::mcs6x11_mono, /*gd medium*/
-        mapserver::mcs7x12_mono_low, /*gd large*/
-        mapserver::mcs7x12_mono_high /*gd huge*/
+const mapserver::int8u* rasterfonts[]= {
+  mapserver::mcs5x10_mono, /*gd tiny. gse5x7 is a bit less high than gd tiny*/
+  mapserver::mcs5x11_mono, /*gd small*/
+  mapserver::mcs6x11_mono, /*gd medium*/
+  mapserver::mcs7x12_mono_low, /*gd large*/
+  mapserver::mcs7x12_mono_high /*gd huge*/
 };
 
 fontMetrics rasterfont_sizes[] = {
-        {5,mapserver::mcs5x10_mono[0]},
-        {5,mapserver::mcs5x11_mono[0]},
-        {6,mapserver::mcs6x11_mono[0]},
-        {7,mapserver::mcs7x12_mono_low[0]}, 
-        {7,mapserver::mcs7x12_mono_high[0]}
+  {5,mapserver::mcs5x10_mono[0]},
+  {5,mapserver::mcs5x11_mono[0]},
+  {6,mapserver::mcs6x11_mono[0]},
+  {7,mapserver::mcs7x12_mono_low[0]},
+  {7,mapserver::mcs7x12_mono_high[0]}
 };
 
 #define aggColor(c) mapserver::rgba8_pre(c->red, c->green, c->blue, c->alpha)
 
-class aggRendererCache {
+class aggRendererCache
+{
 public:
-	font_engine_type m_feng;
-	font_manager_type m_fman;
-	aggRendererCache(): m_fman(m_feng){}
+  font_engine_type m_feng;
+  font_manager_type m_fman;
+  aggRendererCache(): m_fman(m_feng) {}
 };
 
-class AGG2Renderer {
+class AGG2Renderer
+{
 public:
 
-   AGG2Renderer()
+  AGG2Renderer()
 #ifdef AGG_ALIASED_ENABLED
-      :
-   m_renderer_primitives(m_renderer_base),
-   m_rasterizer_primitives(m_renderer_primitives)
+    :
+    m_renderer_primitives(m_renderer_base),
+    m_rasterizer_primitives(m_renderer_primitives)
 #endif
-   {}
+  {}
 
-   band_type* buffer;
-   rendering_buffer m_rendering_buffer;
-   pixel_format m_pixel_format;
-   renderer_base m_renderer_base;
-   renderer_scanline m_renderer_scanline;
+  band_type* buffer;
+  rendering_buffer m_rendering_buffer;
+  pixel_format m_pixel_format;
+  renderer_base m_renderer_base;
+  renderer_scanline m_renderer_scanline;
 #ifdef AGG_ALIASED_ENABLED
-   renderer_primitives m_renderer_primitives;
-   rasterizer_outline m_rasterizer_primitives;
+  renderer_primitives m_renderer_primitives;
+  rasterizer_outline m_rasterizer_primitives;
 #endif
-   rasterizer_scanline m_rasterizer_aa;
-   mapserver::scanline_p8 sl_poly; /*packed scanlines, works faster when the area is larger
+  rasterizer_scanline m_rasterizer_aa;
+  rasterizer_scanline m_rasterizer_aa_gamma;
+  mapserver::scanline_p8 sl_poly; /*packed scanlines, works faster when the area is larger
     than the perimeter, in number of pixels*/
-   mapserver::scanline_u8 sl_line; /*unpacked scanlines, works faster if the area is roughly
+  mapserver::scanline_u8 sl_line; /*unpacked scanlines, works faster if the area is roughly
     equal to the perimeter, in number of pixels*/
-   mapserver::scanline_bin m_sl_bin;
-   bool use_alpha;
+  bool use_alpha;
 };
 
 #define AGG_RENDERER(image) ((AGG2Renderer*) (image)->img.plugin)
 
 template<class VertexSource>
-static void applyCJC(VertexSource &stroke, int caps, int joins) {
-   switch (joins) {
-      case MS_CJC_NONE:
-      case MS_CJC_ROUND:
-         stroke.line_join(mapserver::round_join);
-         break;
-      case MS_CJC_MITER:
-         stroke.line_join(mapserver::miter_join);
-         break;
-      case MS_CJC_BEVEL:
-         stroke.line_join(mapserver::bevel_join);
-         break;
-   }
-   switch (caps) {
-      case MS_CJC_BUTT:
-      case MS_CJC_NONE:
-         stroke.line_cap(mapserver::butt_cap);
-         break;
-      case MS_CJC_ROUND:
-         stroke.line_cap(mapserver::round_cap);
-         break;
-      case MS_CJC_SQUARE:
-         stroke.line_cap(mapserver::square_cap);
-         break;
-   }
+static void applyCJC(VertexSource &stroke, int caps, int joins)
+{
+  switch (joins) {
+    case MS_CJC_ROUND:
+      stroke.line_join(mapserver::round_join);
+      break;
+    case MS_CJC_MITER:
+      stroke.line_join(mapserver::miter_join);
+      break;
+    case MS_CJC_BEVEL:
+    case MS_CJC_NONE:
+      stroke.line_join(mapserver::bevel_join);
+      break;
+  }
+  switch (caps) {
+    case MS_CJC_BUTT:
+    case MS_CJC_NONE:
+      stroke.line_cap(mapserver::butt_cap);
+      break;
+    case MS_CJC_ROUND:
+      stroke.line_cap(mapserver::round_cap);
+      break;
+    case MS_CJC_SQUARE:
+      stroke.line_cap(mapserver::square_cap);
+      break;
+  }
 }
 
-int agg2RenderLine(imageObj *img, shapeObj *p, strokeStyleObj *style) {
+inline int aggLoadFont(aggRendererCache *cache, char *font, double size)
+{
+  if(!cache->m_feng.name() || strcmp(cache->m_feng.name(),font)) {
+    if (!cache->m_feng.load_font(font, 0, mapserver::glyph_ren_outline)) {
+      msSetError(MS_TTFERR, "AGG error loading font (%s)", "aggLoadFont()", font);
+      return MS_FAILURE;
+    }
+    if(!cache->m_feng.hinting())
+      cache->m_feng.hinting(true);
+    if(cache->m_feng.resolution() != 96)
+      cache->m_feng.resolution(96);
+    if(!cache->m_feng.flip_y())
+      cache->m_feng.flip_y(true);
+    cache->m_feng.height(size);
+  } else {
+    if(cache->m_feng.height()!=size)
+      cache->m_feng.height(size);
+  }
+  return MS_SUCCESS;
+}
+
+int agg2RenderLine(imageObj *img, shapeObj *p, strokeStyleObj *style)
+{
 
-   AGG2Renderer *r = AGG_RENDERER(img);
-   line_adaptor lines = line_adaptor(p);
+  AGG2Renderer *r = AGG_RENDERER(img);
+  line_adaptor lines = line_adaptor(p);
 
 #ifdef AGG_ALIASED_ENABLED
-   r->m_rasterizer_primitives.reset();
-   r->m_renderer_primitives.line_color(aggColor(style->color));
-   r->m_rasterizer_primitives.add_path(lines);
-   return MS_SUCCESS;
+  r->m_rasterizer_primitives.reset();
+  r->m_renderer_primitives.line_color(aggColor(style->color));
+  r->m_rasterizer_primitives.add_path(lines);
+  return MS_SUCCESS;
 #endif
 
-   r->m_rasterizer_aa.reset();
-   r->m_rasterizer_aa.filling_rule(mapserver::fill_non_zero);
-   r->m_renderer_scanline.color(aggColor(style->color));
-
-   if (style->patternlength <= 0) {
-      mapserver::conv_stroke<line_adaptor> stroke(lines);
-      stroke.width(style->width);
-      if(style->width>1)
-         applyCJC(stroke, style->linecap, style->linejoin);
-      r->m_rasterizer_aa.add_path(stroke);
-   } else {
-      mapserver::conv_dash<line_adaptor> dash(lines);
-      mapserver::conv_stroke<mapserver::conv_dash<line_adaptor> > stroke_dash(dash);
-      for (int i = 0; i < style->patternlength; i += 2) {
-
-         if (i < style->patternlength - 1) {
-
-            dash.add_dash(MS_MAX(1,MS_NINT(style->pattern[i])),
-                    MS_MAX(1,MS_NINT(style->pattern[i + 1])));
-         }
+  r->m_rasterizer_aa.reset();
+  r->m_rasterizer_aa.filling_rule(mapserver::fill_non_zero);
+  r->m_renderer_scanline.color(aggColor(style->color));
+
+  if (style->patternlength <= 0) {
+    mapserver::conv_stroke<line_adaptor> stroke(lines);
+    stroke.width(style->width);
+    if(style->width>1) {
+      applyCJC(stroke, style->linecap, style->linejoin);
+    } else {
+      stroke.inner_join(mapserver::inner_bevel);
+      stroke.line_join(mapserver::bevel_join);
+    }
+    r->m_rasterizer_aa.add_path(stroke);
+  } else {
+    mapserver::conv_dash<line_adaptor> dash(lines);
+    mapserver::conv_stroke<mapserver::conv_dash<line_adaptor> > stroke_dash(dash);
+    int patt_length = 0;
+    for (int i = 0; i < style->patternlength; i += 2) {
+      if (i < style->patternlength - 1) {
+        dash.add_dash(MS_MAX(1,MS_NINT(style->pattern[i])),
+                      MS_MAX(1,MS_NINT(style->pattern[i + 1])));
+        if(style->patternoffset) {
+          patt_length += MS_MAX(1,MS_NINT(style->pattern[i])) +
+                         MS_MAX(1,MS_NINT(style->pattern[i + 1]));
+        }
       }
-      stroke_dash.width(style->width);
-      if(style->width>1)
-         applyCJC(stroke_dash, style->linecap, style->linejoin);
-      r->m_rasterizer_aa.add_path(stroke_dash);
-   }
-   mapserver::render_scanlines(r->m_rasterizer_aa, r->sl_line, r->m_renderer_scanline);
-   return MS_SUCCESS;
+    }
+    if(style->patternoffset > 0) {
+      dash.dash_start(patt_length - style->patternoffset);
+    }
+    stroke_dash.width(style->width);
+    if(style->width>1) {
+      applyCJC(stroke_dash, style->linecap, style->linejoin);
+    } else {
+      stroke_dash.inner_join(mapserver::inner_bevel);
+      stroke_dash.line_join(mapserver::bevel_join);
+    }
+    r->m_rasterizer_aa.add_path(stroke_dash);
+  }
+  mapserver::render_scanlines(r->m_rasterizer_aa, r->sl_line, r->m_renderer_scanline);
+  return MS_SUCCESS;
 }
 
-int agg2RenderLineTiled(imageObj *img, shapeObj *p, imageObj * tile) {
+int agg2RenderLineTiled(imageObj *img, shapeObj *p, imageObj * tile)
+{
+
+  mapserver::pattern_filter_bilinear_rgba8 fltr;
+  typedef mapserver::line_image_pattern<mapserver::pattern_filter_bilinear_rgba8> pattern_type;
+  typedef mapserver::renderer_outline_image<renderer_base, pattern_type> renderer_img_type;
+  typedef mapserver::rasterizer_outline_aa<renderer_img_type, mapserver::line_coord_sat> rasterizer_img_type;
+  pattern_type patt(fltr);
 
-   mapserver::pattern_filter_bilinear_rgba8 fltr;
-   typedef mapserver::line_image_pattern<mapserver::pattern_filter_bilinear_rgba8> pattern_type;
-   typedef mapserver::renderer_outline_image<renderer_base, pattern_type> renderer_img_type;
-   typedef mapserver::rasterizer_outline_aa<renderer_img_type, mapserver::line_coord_sat> rasterizer_img_type;
-   pattern_type patt(fltr);  
+  AGG2Renderer *r = AGG_RENDERER(img);
+  AGG2Renderer *tileRenderer = AGG_RENDERER(tile);
 
-   AGG2Renderer *r = AGG_RENDERER(img);
-   AGG2Renderer *tileRenderer = AGG_RENDERER(tile);
-   
-   line_adaptor lines(p);
+  line_adaptor lines(p);
 
-   patt.create(tileRenderer->m_pixel_format);
-   renderer_img_type ren_img(r->m_renderer_base, patt);
-   rasterizer_img_type ras_img(ren_img);
-   ras_img.add_path(lines);
-   return MS_SUCCESS;
+  patt.create(tileRenderer->m_pixel_format);
+  renderer_img_type ren_img(r->m_renderer_base, patt);
+  rasterizer_img_type ras_img(ren_img);
+  ras_img.add_path(lines);
+  return MS_SUCCESS;
 }
 
-int agg2RenderPolygon(imageObj *img, shapeObj *p, colorObj * color) {
-   AGG2Renderer *r = AGG_RENDERER(img);
-   polygon_adaptor polygons(p);
-   r->m_rasterizer_aa.reset();
-   r->m_rasterizer_aa.filling_rule(mapserver::fill_even_odd);
-   r->m_rasterizer_aa.add_path(polygons);
-   r->m_renderer_scanline.color(aggColor(color));
-   mapserver::render_scanlines(r->m_rasterizer_aa, r->sl_poly, r->m_renderer_scanline);
-   return MS_SUCCESS;
+int agg2RenderPolygon(imageObj *img, shapeObj *p, colorObj * color)
+{
+  AGG2Renderer *r = AGG_RENDERER(img);
+  polygon_adaptor polygons(p);
+  r->m_rasterizer_aa_gamma.reset();
+  r->m_rasterizer_aa_gamma.filling_rule(mapserver::fill_even_odd);
+  r->m_rasterizer_aa_gamma.add_path(polygons);
+  r->m_renderer_scanline.color(aggColor(color));
+  mapserver::render_scanlines(r->m_rasterizer_aa_gamma, r->sl_poly, r->m_renderer_scanline);
+  return MS_SUCCESS;
 }
 
-int agg2RenderPolygonTiled(imageObj *img, shapeObj *p, imageObj * tile) {
-    assert(img->format->renderer == tile->format->renderer);
-    
-    AGG2Renderer *r = AGG_RENDERER(img);
-    AGG2Renderer *tileRenderer = AGG_RENDERER(tile);
-    polygon_adaptor polygons(p);
-    typedef mapserver::wrap_mode_repeat wrap_type;
-    typedef mapserver::image_accessor_wrap<pixel_format,wrap_type,wrap_type> img_source_type;
-    typedef mapserver::span_pattern_rgba<img_source_type> span_gen_type;
-    mapserver::span_allocator<mapserver::rgba8> sa;
-    r->m_rasterizer_aa.reset();
-    r->m_rasterizer_aa.filling_rule(mapserver::fill_even_odd);
-    img_source_type img_src(tileRenderer->m_pixel_format);
-    span_gen_type sg(img_src, 0, 0);
-    r->m_rasterizer_aa.add_path(polygons);
-    mapserver::render_scanlines_aa(r->m_rasterizer_aa, r->sl_poly, r->m_renderer_base, sa , sg);
-    return MS_SUCCESS;
+int agg2RenderPolygonTiled(imageObj *img, shapeObj *p, imageObj * tile)
+{
+  assert(img->format->renderer == tile->format->renderer);
+
+  AGG2Renderer *r = AGG_RENDERER(img);
+  AGG2Renderer *tileRenderer = AGG_RENDERER(tile);
+  polygon_adaptor polygons(p);
+  typedef mapserver::wrap_mode_repeat wrap_type;
+  typedef mapserver::image_accessor_wrap<pixel_format,wrap_type,wrap_type> img_source_type;
+  typedef mapserver::span_pattern_rgba<img_source_type> span_gen_type;
+  mapserver::span_allocator<mapserver::rgba8> sa;
+  r->m_rasterizer_aa.reset();
+  r->m_rasterizer_aa.filling_rule(mapserver::fill_even_odd);
+  img_source_type img_src(tileRenderer->m_pixel_format);
+  span_gen_type sg(img_src, 0, 0);
+  r->m_rasterizer_aa.add_path(polygons);
+  mapserver::render_scanlines_aa(r->m_rasterizer_aa, r->sl_poly, r->m_renderer_base, sa , sg);
+  return MS_SUCCESS;
 }
 
-int agg2RenderGlyphs(imageObj *img, double x, double y, labelStyleObj *style, char *text) {
-   AGG2Renderer *r = AGG_RENDERER(img);
-   aggRendererCache *cache = (aggRendererCache*)MS_RENDERER_CACHE(MS_IMAGE_RENDERER(img));
-   if (!cache->m_feng.load_font(style->font, 0, mapserver::glyph_ren_outline)) {
-      msSetError(MS_TTFERR, "AGG error loading font (%s)", "agg2RenderGlyphs()", style->font);
-      return MS_FAILURE;
-   }
-   r->m_rasterizer_aa.filling_rule(mapserver::fill_non_zero);
-
-   const mapserver::glyph_cache* glyph;
-   int unicode;
-   //cache->m_feng.hinting(true);
-   cache->m_feng.height(style->size);
-   cache->m_feng.resolution(96);
-   cache->m_feng.flip_y(true);
-   font_curve_type m_curves(cache->m_fman.path_adaptor());
-   mapserver::trans_affine mtx;
-   mtx *= mapserver::trans_affine_translation(-x, -y);
-   /*agg angles are antitrigonometric*/
-   mtx *= mapserver::trans_affine_rotation(-style->rotation);
-   mtx *= mapserver::trans_affine_translation(x, y);
-
-   double fx = x, fy = y;
-   const char *utfptr = text;
-   mapserver::path_storage glyphs;
-
-   //first render all the glyphs to a path
-   while (*utfptr) {
-      if (*utfptr == '\r') {
-         fx = x;
-         utfptr++;
-         continue;
-      }
-      if (*utfptr == '\n') {
-         fx = x;
-         fy += ceil(style->size * AGG_LINESPACE);
-         utfptr++;
-         continue;
-      }
-      utfptr += msUTF8ToUniChar(utfptr, &unicode);
-      glyph = cache->m_fman.glyph(unicode);
-      ;
-      if (glyph) {
-         //cache->m_fman.add_kerning(&fx, &fy);
-    	 cache->m_fman.init_embedded_adaptors(glyph, fx, fy);
-         mapserver::conv_transform<font_curve_type, mapserver::trans_affine> trans_c(m_curves, mtx);
-         glyphs.concat_path(trans_c);
-         fx += glyph->advance_x;
-         fy += glyph->advance_y;
+int agg2RenderGlyphs(imageObj *img, double x, double y, labelStyleObj *style, char *text)
+{
+  AGG2Renderer *r = AGG_RENDERER(img);
+  aggRendererCache *cache = (aggRendererCache*)MS_RENDERER_CACHE(MS_IMAGE_RENDERER(img));
+  if(aggLoadFont(cache,style->fonts[0],style->size) == MS_FAILURE)
+    return MS_FAILURE;
+  r->m_rasterizer_aa.filling_rule(mapserver::fill_non_zero);
+
+  int curfontidx = 0;
+  const mapserver::glyph_cache* glyph;
+  int unicode;
+  font_curve_type m_curves(cache->m_fman.path_adaptor());
+  mapserver::trans_affine mtx;
+  mtx *= mapserver::trans_affine_translation(-x, -y);
+  /*agg angles are antitrigonometric*/
+  mtx *= mapserver::trans_affine_rotation(-style->rotation);
+  mtx *= mapserver::trans_affine_translation(x, y);
+
+  double fx = x, fy = y;
+  const char *utfptr = text;
+  mapserver::path_storage glyphs;
+
+  //first render all the glyphs to a path
+  while (*utfptr) {
+    if (*utfptr == '\r') {
+      fx = x;
+      utfptr++;
+      continue;
+    }
+    if (*utfptr == '\n') {
+      fx = x;
+      fy += ceil(style->size * AGG_LINESPACE);
+      utfptr++;
+      continue;
+    }
+    utfptr += msUTF8ToUniChar(utfptr, &unicode);
+    if(curfontidx != 0) {
+      if(aggLoadFont(cache,style->fonts[0],style->size) == MS_FAILURE)
+        return MS_FAILURE;
+      curfontidx = 0;
+    }
+
+    glyph = cache->m_fman.glyph(unicode);
+
+    if(!glyph || glyph->glyph_index == 0) {
+      int i;
+      for(i=1; i<style->numfonts; i++) {
+        if(aggLoadFont(cache,style->fonts[i],style->size) == MS_FAILURE)
+          return MS_FAILURE;
+        curfontidx = i;
+        glyph = cache->m_fman.glyph(unicode);
+        if(glyph && glyph->glyph_index != 0) {
+          break;
+        }
       }
-   }
-   
-   if (style->outlinewidth) {
-      r->m_rasterizer_aa.reset();
-      r->m_rasterizer_aa.filling_rule(mapserver::fill_non_zero);
-      mapserver::conv_contour<mapserver::path_storage> cc(glyphs);
-      cc.width(style->outlinewidth + 1);
-      r->m_rasterizer_aa.add_path(cc);
-      r->m_renderer_scanline.color(aggColor(style->outlinecolor));
-      mapserver::render_scanlines(r->m_rasterizer_aa, r->sl_line, r->m_renderer_scanline);
-   }
-   if (style->color) {
-      r->m_rasterizer_aa.reset();
-      r->m_rasterizer_aa.filling_rule(mapserver::fill_non_zero);
-      r->m_rasterizer_aa.add_path(glyphs);
-      r->m_renderer_scanline.color(aggColor(style->color));
-      mapserver::render_scanlines(r->m_rasterizer_aa, r->sl_line, r->m_renderer_scanline);
-   }
-   
-   return MS_SUCCESS;
+    }
 
-}
 
-int agg2RenderBitmapGlyphs(imageObj *img, double x, double y, labelStyleObj *style, char *text) {
-	typedef mapserver::glyph_raster_bin<color_type> glyph_gen;
-	int size = MS_NINT(style->size);
-	if(size<0 || size>4) {
-		msSetError(MS_RENDERERERR,"invalid bitmap font size", "agg2RenderBitmapGlyphs()");
-		return MS_FAILURE;
-	}
-	AGG2Renderer *r = AGG_RENDERER(img);
-	glyph_gen glyph(0);
-	mapserver::renderer_raster_htext_solid<renderer_base, glyph_gen> rt(r->m_renderer_base, glyph);
-	glyph.font(rasterfonts[size]);
-	int numlines=0;
-	char **lines;
-	/*masking out the out-of-range character codes*/
-	int len;
-	int cc_start = rasterfonts[size][2];
-	int cc_end = cc_start + rasterfonts[size][3];
-	if(msCountChars(text,'\n')) {
-		if((lines = msStringSplit((const char*)text, '\n', &(numlines))) == NULL)
-			return(-1);
-	} else {
-		lines = &text;
-		numlines = 1;
-	}
-	y -= glyph.base_line();
-	for(int n=0;n<numlines;n++) {
-		len = strlen(lines[n]);
-		for (int i = 0; i < len; i++)
-		if (lines[n][i] < cc_start || lines[n][i] > cc_end)
-			lines[n][i] = '.';
-		if(style->outlinewidth > 0) {
-		   rt.color(aggColor(style->outlinecolor));
-			for(int i=-1;i<=1;i++) {
-				for(int j=-1;j<=1;j++) {
-					if(i||j) {
-						rt.render_text(x+i, y+j, lines[n], true);
-					}
-				}
-			}
-		}
-		assert(style->color);
-		rt.color(aggColor(style->color));
-		rt.render_text(x, y, lines[n], true);
-		y += glyph.height();
-	}
-	if(*lines != text)
-		msFreeCharArray(lines, numlines);
-	return MS_SUCCESS;
-	return MS_SUCCESS;
-}
+    if (glyph) {
+      //cache->m_fman.add_kerning(&fx, &fy);
+      cache->m_fman.init_embedded_adaptors(glyph, fx, fy);
+      mapserver::conv_transform<font_curve_type, mapserver::trans_affine> trans_c(m_curves, mtx);
+      glyphs.concat_path(trans_c);
+      fx += glyph->advance_x;
+      fy += glyph->advance_y;
+    }
+  }
+
+  if (style->outlinewidth) {
+    r->m_rasterizer_aa.reset();
+    r->m_rasterizer_aa.filling_rule(mapserver::fill_non_zero);
+    mapserver::conv_contour<mapserver::path_storage> cc(glyphs);
+    cc.width(style->outlinewidth + 1);
+    r->m_rasterizer_aa.add_path(cc);
+    r->m_renderer_scanline.color(aggColor(style->outlinecolor));
+    mapserver::render_scanlines(r->m_rasterizer_aa, r->sl_line, r->m_renderer_scanline);
+  }
+  if (style->color) {
+    r->m_rasterizer_aa.reset();
+    r->m_rasterizer_aa.filling_rule(mapserver::fill_non_zero);
+    r->m_rasterizer_aa.add_path(glyphs);
+    r->m_renderer_scanline.color(aggColor(style->color));
+    mapserver::render_scanlines(r->m_rasterizer_aa, r->sl_line, r->m_renderer_scanline);
+  }
+
+  return MS_SUCCESS;
 
-int agg2RenderGlyphsLine(imageObj *img, labelPathObj *labelpath, labelStyleObj *style, char *text) {
-	msSetError(MS_AGGERR,"renderGlyphsLine not implemented","agg2RenderGlyphsLineLine()");
-	return MS_FAILURE;
 }
 
-static mapserver::path_storage imageVectorSymbolAGG(symbolObj *symbol) {
-    mapserver::path_storage path;
-    bool is_new=true;
-    for(int i=0;i < symbol->numpoints;i++) {
-        if((symbol->points[i].x == -99) && (symbol->points[i].y == -99)) { // (PENUP) 
-            is_new=true;
-        } else {
-            if(is_new) {
-                path.move_to(symbol->points[i].x,symbol->points[i].y);
-                is_new=false;                         
-            }
-            else {
-                path.line_to(symbol->points[i].x,symbol->points[i].y);
-            }
+int agg2RenderBitmapGlyphs(imageObj *img, double x, double y, labelStyleObj *style, char *text)
+{
+  typedef mapserver::glyph_raster_bin<color_type> glyph_gen;
+  int size = MS_NINT(style->size);
+  if(size<0 || size>4) {
+    msSetError(MS_RENDERERERR,"invalid bitmap font size", "agg2RenderBitmapGlyphs()");
+    return MS_FAILURE;
+  }
+  AGG2Renderer *r = AGG_RENDERER(img);
+  glyph_gen glyph(0);
+  mapserver::renderer_raster_htext_solid<renderer_base, glyph_gen> rt(r->m_renderer_base, glyph);
+  glyph.font(rasterfonts[size]);
+  int numlines=0;
+  char **lines;
+  /*masking out the out-of-range character codes*/
+  int len;
+  int cc_start = rasterfonts[size][2];
+  int cc_end = cc_start + rasterfonts[size][3];
+  if(msCountChars(text,'\n')) {
+    if((lines = msStringSplit((const char*)text, '\n', &(numlines))) == NULL)
+      return(-1);
+  } else {
+    lines = &text;
+    numlines = 1;
+  }
+  y -= glyph.base_line();
+  for(int n=0; n<numlines; n++) {
+    len = strlen(lines[n]);
+    for (int i = 0; i < len; i++)
+      if (lines[n][i] < cc_start || lines[n][i] > cc_end)
+        lines[n][i] = '.';
+    if(style->outlinewidth > 0) {
+      rt.color(aggColor(style->outlinecolor));
+      for(int i=-1; i<=1; i++) {
+        for(int j=-1; j<=1; j++) {
+          if(i||j) {
+            rt.render_text(x+i, y+j, lines[n], true);
+          }
         }
-    }         
-    return path;
+      }
+    }
+    assert(style->color);
+    rt.color(aggColor(style->color));
+    rt.render_text(x, y, lines[n], true);
+    y += glyph.height();
+  }
+  if(*lines != text)
+    msFreeCharArray(lines, numlines);
+  return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
+int agg2RenderGlyphsLine(imageObj *img, labelPathObj *labelpath, labelStyleObj *style, char *text)
+{
+  AGG2Renderer *r = AGG_RENDERER(img);
+  aggRendererCache *cache = (aggRendererCache*)MS_RENDERER_CACHE(MS_IMAGE_RENDERER(img));
+  if(aggLoadFont(cache,style->fonts[0],style->size) == MS_FAILURE)
+    return MS_FAILURE;
+  r->m_rasterizer_aa.filling_rule(mapserver::fill_non_zero);
 
-int agg2RenderVectorSymbol(imageObj *img, double x, double y,
-        symbolObj *symbol, symbolStyleObj * style) {
-    AGG2Renderer *r = AGG_RENDERER(img);
-    double ox = symbol->sizex * 0.5;
-    double oy = symbol->sizey * 0.5;
+  const mapserver::glyph_cache* glyph;
+  int unicode;
+  int curfontidx = 0;
+  font_curve_type m_curves(cache->m_fman.path_adaptor());
 
-    mapserver::path_storage path = imageVectorSymbolAGG(symbol);
+  mapserver::path_storage glyphs;
+
+  for (int i = 0; i < labelpath->path.numpoints; i++) {
+    assert(text);
     mapserver::trans_affine mtx;
-    mtx *= mapserver::trans_affine_translation(-ox,-oy);
-    mtx *= mapserver::trans_affine_scaling(style->scale);
-    mtx *= mapserver::trans_affine_rotation(-style->rotation);
-    mtx *= mapserver::trans_affine_translation(x, y);
-    path.transform(mtx);
-    if (style->color) {
-        r->m_rasterizer_aa.reset();
-        r->m_rasterizer_aa.filling_rule(mapserver::fill_even_odd);
-        r->m_rasterizer_aa.add_path(path);
-        r->m_renderer_scanline.color(aggColor(style->color));
-        mapserver::render_scanlines(r->m_rasterizer_aa, r->sl_poly, r->m_renderer_scanline);
+    mtx *= mapserver::trans_affine_translation(-labelpath->path.point[i].x,-labelpath->path.point[i].y);
+    mtx *= mapserver::trans_affine_rotation(-labelpath->angles[i]);
+    mtx *= mapserver::trans_affine_translation(labelpath->path.point[i].x,labelpath->path.point[i].y);
+    text += msUTF8ToUniChar(text, &unicode);
+
+    if(curfontidx != 0) {
+      if(aggLoadFont(cache,style->fonts[0],style->size) == MS_FAILURE)
+        return MS_FAILURE;
+      curfontidx = 0;
+    }
+
+    glyph = cache->m_fman.glyph(unicode);
+
+    if(!glyph || glyph->glyph_index == 0) {
+      int i;
+      for(i=1; i<style->numfonts; i++) {
+        if(aggLoadFont(cache,style->fonts[i],style->size) == MS_FAILURE)
+          return MS_FAILURE;
+        curfontidx = i;
+        glyph = cache->m_fman.glyph(unicode);
+        if(glyph && glyph->glyph_index != 0) {
+          break;
+        }
+      }
     }
-    if(style->outlinecolor) {
-        r->m_rasterizer_aa.reset();
-        r->m_rasterizer_aa.filling_rule(mapserver::fill_non_zero); 
-        r->m_renderer_scanline.color(aggColor(style->outlinecolor));
-        mapserver::conv_stroke<mapserver::path_storage> stroke(path);
-        stroke.width(style->outlinewidth);
-        r->m_rasterizer_aa.add_path(stroke);
-        mapserver::render_scanlines(r->m_rasterizer_aa, r->sl_poly, r->m_renderer_scanline);
+    if (glyph) {
+      cache->m_fman.init_embedded_adaptors(glyph, labelpath->path.point[i].x,labelpath->path.point[i].y);
+      mapserver::conv_transform<font_curve_type, mapserver::trans_affine> trans_c(m_curves, mtx);
+      glyphs.concat_path(trans_c);
     }
-    return MS_SUCCESS;
+  }
+
+  if (style->outlinewidth) {
+    r->m_rasterizer_aa.reset();
+    r->m_rasterizer_aa.filling_rule(mapserver::fill_non_zero);
+    mapserver::conv_contour<mapserver::path_storage> cc(glyphs);
+    cc.width(style->outlinewidth + 1);
+    r->m_rasterizer_aa.add_path(cc);
+    r->m_renderer_scanline.color(aggColor(style->outlinecolor));
+    mapserver::render_scanlines(r->m_rasterizer_aa, r->sl_line, r->m_renderer_scanline);
+  }
+  if (style->color) {
+    r->m_rasterizer_aa.reset();
+    r->m_rasterizer_aa.filling_rule(mapserver::fill_non_zero);
+    r->m_rasterizer_aa.add_path(glyphs);
+    r->m_renderer_scanline.color(aggColor(style->color));
+    mapserver::render_scanlines(r->m_rasterizer_aa, r->sl_line, r->m_renderer_scanline);
+  }
+
+  return MS_SUCCESS;
 }
 
-int agg2RenderPixmapSymbol(imageObj *img, double x, double y, symbolObj *symbol, symbolStyleObj * style) {
-	AGG2Renderer *r = AGG_RENDERER(img);
-	pixel_format pf;
-   rendering_buffer b;
-	rasterBufferObj *pixmap = symbol->pixmap_buffer;
-	assert(pixmap->type == MS_BUFFER_BYTE_RGBA);
-    if(!symbol->renderer_cache) {
-        band_type *data = (band_type*)msSmallMalloc(pixmap->width*pixmap->height*4*sizeof(band_type));
-        for(unsigned int row=0; row<pixmap->height;row++) {
-           unsigned char *a = pixmap->data.rgba.a + row * pixmap->data.rgba.row_step;
-           unsigned char *r = pixmap->data.rgba.r + row * pixmap->data.rgba.row_step;
-           unsigned char *g = pixmap->data.rgba.g + row * pixmap->data.rgba.row_step;
-           unsigned char *b = pixmap->data.rgba.b + row * pixmap->data.rgba.row_step;
-           band_type* pixptr = data + row * pixmap->width * 4;
-           for(unsigned int col=0;col<pixmap->width;col++) {
-              pixptr[band_order::A] = *a;
-              pixptr[band_order::G] = *g;
-              pixptr[band_order::B] = *b;
-              pixptr[band_order::R] = *r;
-              pixptr+=4;
-              a += pixmap->data.rgba.pixel_step;
-              r += pixmap->data.rgba.pixel_step;
-              g += pixmap->data.rgba.pixel_step;
-              b += pixmap->data.rgba.pixel_step;                                          
-           }
-        }
-        //memcpy(data,pixmap->data.rgba.pixels,pixmap->width*pixmap->height*4);
-        rendering_buffer *b = new rendering_buffer(data, pixmap->width, pixmap->height, (int)pixmap->width*4);
-        symbol->renderer_cache = (void*)b;
-        pf.attach(*b);
-        pf.premultiply();
+static mapserver::path_storage imageVectorSymbolAGG(symbolObj *symbol)
+{
+  mapserver::path_storage path;
+  bool is_new=true;
+  for(int i=0; i < symbol->numpoints; i++) {
+    if((symbol->points[i].x == -99) && (symbol->points[i].y == -99)) { // (PENUP)
+      is_new=true;
     } else {
-        rendering_buffer *b = (rendering_buffer*)symbol->renderer_cache;
-        pf.attach(*b);
+      if(is_new) {
+        path.move_to(symbol->points[i].x,symbol->points[i].y);
+        is_new=false;
+      } else {
+        path.line_to(symbol->points[i].x,symbol->points[i].y);
+      }
     }
+  }
+  return path;
+}
 
-	r->m_rasterizer_aa.reset();
-	r->m_rasterizer_aa.filling_rule(mapserver::fill_non_zero);
-	if( (style->rotation != 0 && style->rotation != MS_PI*2.)|| style->scale != 1) {
-		mapserver::trans_affine image_mtx;
-		image_mtx *= mapserver::trans_affine_translation(-(pf.width()/2.),-(pf.height()/2.));
-		/*agg angles are antitrigonometric*/
-		image_mtx *= mapserver::trans_affine_rotation(-style->rotation);
-		image_mtx *= mapserver::trans_affine_scaling(style->scale);
-
-
-
-		image_mtx *= mapserver::trans_affine_translation(x,y);
-		image_mtx.invert();
-		typedef mapserver::span_interpolator_linear<> interpolator_type;
-		interpolator_type interpolator(image_mtx);
-		mapserver::span_allocator<color_type> sa;
-
-		// "hardcoded" bilinear filter
-		//------------------------------------------
-		typedef mapserver::span_image_filter_rgba_bilinear_clip<pixel_format, interpolator_type> span_gen_type;
-		span_gen_type sg(pf, mapserver::rgba(0,0,0,0), interpolator);
-		mapserver::path_storage pixmap_bbox;
-		int ims_2 = MS_NINT(MS_MAX(pixmap->width,pixmap->height)*style->scale*1.415)/2+1;
-
-		pixmap_bbox.move_to(x-ims_2,y-ims_2);
-		pixmap_bbox.line_to(x+ims_2,y-ims_2);
-		pixmap_bbox.line_to(x+ims_2,y+ims_2);
-		pixmap_bbox.line_to(x-ims_2,y+ims_2);
-
-		r->m_rasterizer_aa.add_path(pixmap_bbox);
-		mapserver::render_scanlines_aa(r->m_rasterizer_aa, r->sl_poly, r->m_renderer_base, sa, sg);
-	}
-	else {
-		//just copy the image at the correct location (we place the pixmap on 
-		//the nearest integer pixel to avoid blurring)
-		r->m_renderer_base.blend_from(pf,0,MS_NINT(x-pixmap->width/2.),MS_NINT(y-pixmap->height/2.));
-	}
-	return MS_SUCCESS;
+
+int agg2RenderVectorSymbol(imageObj *img, double x, double y,
+                           symbolObj *symbol, symbolStyleObj * style)
+{
+  AGG2Renderer *r = AGG_RENDERER(img);
+  double ox = symbol->sizex * 0.5;
+  double oy = symbol->sizey * 0.5;
+
+  mapserver::path_storage path = imageVectorSymbolAGG(symbol);
+  mapserver::trans_affine mtx;
+  mtx *= mapserver::trans_affine_translation(-ox,-oy);
+  mtx *= mapserver::trans_affine_scaling(style->scale);
+  mtx *= mapserver::trans_affine_rotation(-style->rotation);
+  mtx *= mapserver::trans_affine_translation(x, y);
+  path.transform(mtx);
+  if (style->color) {
+    r->m_rasterizer_aa.reset();
+    r->m_rasterizer_aa.filling_rule(mapserver::fill_even_odd);
+    r->m_rasterizer_aa.add_path(path);
+    r->m_renderer_scanline.color(aggColor(style->color));
+    mapserver::render_scanlines(r->m_rasterizer_aa, r->sl_poly, r->m_renderer_scanline);
+  }
+  if(style->outlinecolor) {
+    r->m_rasterizer_aa.reset();
+    r->m_rasterizer_aa.filling_rule(mapserver::fill_non_zero);
+    r->m_renderer_scanline.color(aggColor(style->outlinecolor));
+    mapserver::conv_stroke<mapserver::path_storage> stroke(path);
+    stroke.width(style->outlinewidth);
+    r->m_rasterizer_aa.add_path(stroke);
+    mapserver::render_scanlines(r->m_rasterizer_aa, r->sl_poly, r->m_renderer_scanline);
+  }
+  return MS_SUCCESS;
+}
+
+int agg2RenderPixmapSymbol(imageObj *img, double x, double y, symbolObj *symbol, symbolStyleObj * style)
+{
+  AGG2Renderer *r = AGG_RENDERER(img);
+  rasterBufferObj *pixmap = symbol->pixmap_buffer;
+  assert(pixmap->type == MS_BUFFER_BYTE_RGBA);
+  rendering_buffer b(pixmap->data.rgba.pixels,pixmap->width,pixmap->height,pixmap->data.rgba.row_step);
+  pixel_format pf(b);
+
+  r->m_rasterizer_aa.reset();
+  r->m_rasterizer_aa.filling_rule(mapserver::fill_non_zero);
+  if ( (style->rotation != 0 && style->rotation != MS_PI*2.)|| style->scale != 1) {
+    mapserver::trans_affine image_mtx;
+    image_mtx *= mapserver::trans_affine_translation(-(pf.width()/2.),-(pf.height()/2.));
+    /*agg angles are antitrigonometric*/
+    image_mtx *= mapserver::trans_affine_rotation(-style->rotation);
+    image_mtx *= mapserver::trans_affine_scaling(style->scale);
+
+
+
+    image_mtx *= mapserver::trans_affine_translation(x,y);
+    image_mtx.invert();
+    typedef mapserver::span_interpolator_linear<> interpolator_type;
+    interpolator_type interpolator(image_mtx);
+    mapserver::span_allocator<color_type> sa;
+
+    // "hardcoded" bilinear filter
+    //------------------------------------------
+    typedef mapserver::span_image_filter_rgba_bilinear_clip<pixel_format, interpolator_type> span_gen_type;
+    span_gen_type sg(pf, mapserver::rgba(0,0,0,0), interpolator);
+    mapserver::path_storage pixmap_bbox;
+    int ims_2 = MS_NINT(MS_MAX(pixmap->width,pixmap->height)*style->scale*1.415)/2+1;
+
+    pixmap_bbox.move_to(x-ims_2,y-ims_2);
+    pixmap_bbox.line_to(x+ims_2,y-ims_2);
+    pixmap_bbox.line_to(x+ims_2,y+ims_2);
+    pixmap_bbox.line_to(x-ims_2,y+ims_2);
+
+    r->m_rasterizer_aa.add_path(pixmap_bbox);
+    mapserver::render_scanlines_aa(r->m_rasterizer_aa, r->sl_poly, r->m_renderer_base, sa, sg);
+  } else {
+    //just copy the image at the correct location (we place the pixmap on
+    //the nearest integer pixel to avoid blurring)
+    r->m_renderer_base.blend_from(pf,0,MS_NINT(x-pixmap->width/2.),MS_NINT(y-pixmap->height/2.));
+  }
+  return MS_SUCCESS;
 }
 
 int agg2RenderEllipseSymbol(imageObj *image, double x, double y,
-        symbolObj *symbol, symbolStyleObj * style) {
-	AGG2Renderer *r = AGG_RENDERER(image);
-	mapserver::path_storage path;
-	mapserver::ellipse ellipse(x,y,symbol->sizex*style->scale/2,symbol->sizey*style->scale/2);
-	path.concat_path(ellipse);
-	if( style->rotation != 0) {
-		mapserver::trans_affine mtx;
-		mtx *= mapserver::trans_affine_translation(-x,-y);
-		/*agg angles are antitrigonometric*/
-		mtx *= mapserver::trans_affine_rotation(-style->rotation);
-		mtx *= mapserver::trans_affine_translation(x,y);
-		path.transform(mtx);
-	}
-	
-	if(style->color) {
-		r->m_rasterizer_aa.reset();
-		r->m_rasterizer_aa.filling_rule(mapserver::fill_even_odd);
-		r->m_rasterizer_aa.add_path(path);
-		r->m_renderer_scanline.color(aggColor(style->color));
-		mapserver::render_scanlines(r->m_rasterizer_aa, r->sl_line, r->m_renderer_scanline);
-	}
-	if(style->outlinewidth) {
-		r->m_rasterizer_aa.reset();
-		r->m_rasterizer_aa.filling_rule(mapserver::fill_non_zero);
-		mapserver::conv_stroke<mapserver::path_storage> stroke(path);
-		stroke.width(style->outlinewidth);
-		r->m_rasterizer_aa.add_path(stroke);
-		r->m_renderer_scanline.color(aggColor(style->outlinecolor));
-		mapserver::render_scanlines(r->m_rasterizer_aa, r->sl_poly, r->m_renderer_scanline);				
-	}
-	return MS_SUCCESS;
+                            symbolObj *symbol, symbolStyleObj * style)
+{
+  AGG2Renderer *r = AGG_RENDERER(image);
+  mapserver::path_storage path;
+  mapserver::ellipse ellipse(x,y,symbol->sizex*style->scale/2,symbol->sizey*style->scale/2);
+  path.concat_path(ellipse);
+  if( style->rotation != 0) {
+    mapserver::trans_affine mtx;
+    mtx *= mapserver::trans_affine_translation(-x,-y);
+    /*agg angles are antitrigonometric*/
+    mtx *= mapserver::trans_affine_rotation(-style->rotation);
+    mtx *= mapserver::trans_affine_translation(x,y);
+    path.transform(mtx);
+  }
+
+  if(style->color) {
+    r->m_rasterizer_aa.reset();
+    r->m_rasterizer_aa.filling_rule(mapserver::fill_even_odd);
+    r->m_rasterizer_aa.add_path(path);
+    r->m_renderer_scanline.color(aggColor(style->color));
+    mapserver::render_scanlines(r->m_rasterizer_aa, r->sl_line, r->m_renderer_scanline);
+  }
+  if(style->outlinewidth) {
+    r->m_rasterizer_aa.reset();
+    r->m_rasterizer_aa.filling_rule(mapserver::fill_non_zero);
+    mapserver::conv_stroke<mapserver::path_storage> stroke(path);
+    stroke.width(style->outlinewidth);
+    r->m_rasterizer_aa.add_path(stroke);
+    r->m_renderer_scanline.color(aggColor(style->outlinecolor));
+    mapserver::render_scanlines(r->m_rasterizer_aa, r->sl_poly, r->m_renderer_scanline);
+  }
+  return MS_SUCCESS;
 }
 
 int agg2RenderTruetypeSymbol(imageObj *img, double x, double y,
-        symbolObj *symbol, symbolStyleObj * style) {
-   AGG2Renderer *r = AGG_RENDERER(img);
-   aggRendererCache *cache = (aggRendererCache*)MS_RENDERER_CACHE(MS_IMAGE_RENDERER(img));
-   if (!cache->m_feng.load_font(symbol->full_font_path, 0, mapserver::glyph_ren_outline)) {
-      msSetError(MS_TTFERR, "AGG error loading font (%s)", "agg2RenderTruetypeSymbol()", symbol->full_font_path);
-      return MS_FAILURE;
-   }
-
-   int unicode;
-   cache->m_feng.hinting(true);
-   cache->m_feng.height(style->scale);
-   cache->m_feng.resolution(96);
-   cache->m_feng.flip_y(true);
-   font_curve_type m_curves(cache->m_fman.path_adaptor());
-	
-	msUTF8ToUniChar(symbol->character, &unicode);
-	const mapserver::glyph_cache* glyph = cache->m_fman.glyph(unicode);
-	double ox = (glyph->bounds.x1 + glyph->bounds.x2) / 2.;
-	double oy = (glyph->bounds.y1 + glyph->bounds.y2) / 2.;
-	
-	mapserver::trans_affine mtx = mapserver::trans_affine_translation(-ox, -oy);
-	if(style->rotation)
-		mtx *= mapserver::trans_affine_rotation(-style->rotation);
-	mtx *= mapserver::trans_affine_translation(x, y);
-	
-	mapserver::path_storage glyphs;
-
-   cache->m_fman.init_embedded_adaptors(glyph, 0,0);
-         mapserver::conv_transform<font_curve_type, mapserver::trans_affine> trans_c(m_curves, mtx);
-         glyphs.concat_path(trans_c);
-   if (style->outlinecolor) {
-      r->m_rasterizer_aa.reset();
-      r->m_rasterizer_aa.filling_rule(mapserver::fill_non_zero);
-      mapserver::conv_contour<mapserver::path_storage> cc(glyphs);
-      cc.auto_detect_orientation(true);
-      cc.width(style->outlinewidth + 1);
-      r->m_rasterizer_aa.add_path(cc);
-      r->m_renderer_scanline.color(aggColor(style->outlinecolor));
-      mapserver::render_scanlines(r->m_rasterizer_aa, r->sl_line, r->m_renderer_scanline);
-   }
-
-   if (style->color) {
-      r->m_rasterizer_aa.reset();
-      r->m_rasterizer_aa.filling_rule(mapserver::fill_non_zero);
-      r->m_rasterizer_aa.add_path(glyphs);
-      r->m_renderer_scanline.color(aggColor(style->color));
-      mapserver::render_scanlines(r->m_rasterizer_aa, r->sl_line, r->m_renderer_scanline);
-   }
-   return MS_SUCCESS;
+                             symbolObj *symbol, symbolStyleObj * style)
+{
+  AGG2Renderer *r = AGG_RENDERER(img);
+  aggRendererCache *cache = (aggRendererCache*)MS_RENDERER_CACHE(MS_IMAGE_RENDERER(img));
+  if(aggLoadFont(cache,symbol->full_font_path,style->scale) == MS_FAILURE)
+    return MS_FAILURE;
+
+  int unicode;
+  font_curve_type m_curves(cache->m_fman.path_adaptor());
+
+  msUTF8ToUniChar(symbol->character, &unicode);
+  const mapserver::glyph_cache* glyph = cache->m_fman.glyph(unicode);
+  double ox = (glyph->bounds.x1 + glyph->bounds.x2) / 2.;
+  double oy = (glyph->bounds.y1 + glyph->bounds.y2) / 2.;
+
+  mapserver::trans_affine mtx = mapserver::trans_affine_translation(-ox, -oy);
+  if(style->rotation)
+    mtx *= mapserver::trans_affine_rotation(-style->rotation);
+  mtx *= mapserver::trans_affine_translation(x, y);
+
+  mapserver::path_storage glyphs;
+
+  cache->m_fman.init_embedded_adaptors(glyph, 0,0);
+  mapserver::conv_transform<font_curve_type, mapserver::trans_affine> trans_c(m_curves, mtx);
+  glyphs.concat_path(trans_c);
+  if (style->outlinecolor) {
+    r->m_rasterizer_aa.reset();
+    r->m_rasterizer_aa.filling_rule(mapserver::fill_non_zero);
+    mapserver::conv_contour<mapserver::path_storage> cc(glyphs);
+    cc.auto_detect_orientation(true);
+    cc.width(style->outlinewidth + 1);
+    r->m_rasterizer_aa.add_path(cc);
+    r->m_renderer_scanline.color(aggColor(style->outlinecolor));
+    mapserver::render_scanlines(r->m_rasterizer_aa, r->sl_line, r->m_renderer_scanline);
+  }
+
+  if (style->color) {
+    r->m_rasterizer_aa.reset();
+    r->m_rasterizer_aa.filling_rule(mapserver::fill_non_zero);
+    r->m_rasterizer_aa.add_path(glyphs);
+    r->m_renderer_scanline.color(aggColor(style->color));
+    mapserver::render_scanlines(r->m_rasterizer_aa, r->sl_line, r->m_renderer_scanline);
+  }
+  return MS_SUCCESS;
 
 }
 
-int agg2RenderTile(imageObj *img, imageObj *tile, double x, double y) {
-   /*
-   AGG2Renderer *imgRenderer = agg2GetRenderer(img);
-   AGG2Renderer *tileRenderer = agg2GetRenderer(tile);
-   */
-   return MS_FAILURE;
+int agg2RenderTile(imageObj *img, imageObj *tile, double x, double y)
+{
+  /*
+  AGG2Renderer *imgRenderer = agg2GetRenderer(img);
+  AGG2Renderer *tileRenderer = agg2GetRenderer(tile);
+  */
+  return MS_FAILURE;
 }
 
-int aggInitializeRasterBuffer(rasterBufferObj *rb, int width, int height, int mode) {
-	rb->type = MS_BUFFER_BYTE_RGBA;
-	rb->data.rgba.pixel_step = 4;
-	rb->data.rgba.row_step = rb->data.rgba.pixel_step * width;
-	rb->width = width;
-	rb->height = height;
-	int nBytes = rb->data.rgba.row_step * height;
-	rb->data.rgba.pixels = (band_type*)msSmallCalloc(nBytes,sizeof(band_type));
-	rb->data.rgba.r = &(rb->data.rgba.pixels[band_order::R]);
-	rb->data.rgba.g = &(rb->data.rgba.pixels[band_order::G]);
-	rb->data.rgba.b = &(rb->data.rgba.pixels[band_order::B]);
-	if(mode == MS_IMAGEMODE_RGBA) {
-	   rb->data.rgba.a = &(rb->data.rgba.pixels[band_order::A]);
-	}
-	return MS_SUCCESS;
+int aggInitializeRasterBuffer(rasterBufferObj *rb, int width, int height, int mode)
+{
+  rb->type = MS_BUFFER_BYTE_RGBA;
+  rb->data.rgba.pixel_step = 4;
+  rb->data.rgba.row_step = rb->data.rgba.pixel_step * width;
+  rb->width = width;
+  rb->height = height;
+  int nBytes = rb->data.rgba.row_step * height;
+  rb->data.rgba.pixels = (band_type*)msSmallCalloc(nBytes,sizeof(band_type));
+  rb->data.rgba.r = &(rb->data.rgba.pixels[band_order::R]);
+  rb->data.rgba.g = &(rb->data.rgba.pixels[band_order::G]);
+  rb->data.rgba.b = &(rb->data.rgba.pixels[band_order::B]);
+  if(mode == MS_IMAGEMODE_RGBA) {
+    rb->data.rgba.a = &(rb->data.rgba.pixels[band_order::A]);
+  }
+  return MS_SUCCESS;
 }
 
 
 
-int aggGetRasterBufferHandle(imageObj *img, rasterBufferObj * rb) {
-   AGG2Renderer *r = AGG_RENDERER(img);
-   rb->type =MS_BUFFER_BYTE_RGBA;
-   rb->data.rgba.pixels = r->buffer;
-   rb->data.rgba.row_step = r->m_rendering_buffer.stride();
-   rb->data.rgba.pixel_step = 4;
-   rb->width = r->m_rendering_buffer.width();
-   rb->height = r->m_rendering_buffer.height();
-   rb->data.rgba.r = &(r->buffer[band_order::R]);
-   rb->data.rgba.g = &(r->buffer[band_order::G]);
-   rb->data.rgba.b = &(r->buffer[band_order::B]);
-   if(r->use_alpha)
-      rb->data.rgba.a = &(r->buffer[band_order::A]);
-   else
-      rb->data.rgba.a = NULL;
-   return MS_SUCCESS;
+int aggGetRasterBufferHandle(imageObj *img, rasterBufferObj * rb)
+{
+  AGG2Renderer *r = AGG_RENDERER(img);
+  rb->type =MS_BUFFER_BYTE_RGBA;
+  rb->data.rgba.pixels = r->buffer;
+  rb->data.rgba.row_step = r->m_rendering_buffer.stride();
+  rb->data.rgba.pixel_step = 4;
+  rb->width = r->m_rendering_buffer.width();
+  rb->height = r->m_rendering_buffer.height();
+  rb->data.rgba.r = &(r->buffer[band_order::R]);
+  rb->data.rgba.g = &(r->buffer[band_order::G]);
+  rb->data.rgba.b = &(r->buffer[band_order::B]);
+  if(r->use_alpha)
+    rb->data.rgba.a = &(r->buffer[band_order::A]);
+  else
+    rb->data.rgba.a = NULL;
+  return MS_SUCCESS;
 }
 
-int aggGetRasterBufferCopy(imageObj *img, rasterBufferObj *rb) {
-   AGG2Renderer *r = AGG_RENDERER(img);
-   aggInitializeRasterBuffer(rb, img->width, img->height, MS_IMAGEMODE_RGBA);
-   int nBytes = r->m_rendering_buffer.stride()*r->m_rendering_buffer.height();
-   memcpy(rb->data.rgba.pixels,r->buffer, nBytes);
-   return MS_SUCCESS;
+int aggGetRasterBufferCopy(imageObj *img, rasterBufferObj *rb)
+{
+  AGG2Renderer *r = AGG_RENDERER(img);
+  aggInitializeRasterBuffer(rb, img->width, img->height, MS_IMAGEMODE_RGBA);
+  int nBytes = r->m_rendering_buffer.stride()*r->m_rendering_buffer.height();
+  memcpy(rb->data.rgba.pixels,r->buffer, nBytes);
+  return MS_SUCCESS;
 }
 
 
 
 int agg2MergeRasterBuffer(imageObj *dest, rasterBufferObj *overlay, double opacity, int srcX, int srcY,
-      int dstX, int dstY, int width, int height) {
-   assert(overlay->type == MS_BUFFER_BYTE_RGBA);
-   rendering_buffer b(overlay->data.rgba.pixels, overlay->width, overlay->height, overlay->data.rgba.row_step);
-   pixel_format pf(b);
-   AGG2Renderer *r = AGG_RENDERER(dest);
-   mapserver::rect_base<int> src_rect(srcX,srcY,srcX+width,srcY+height);
-   r->m_renderer_base.blend_from(pf,&src_rect, dstX-srcX, dstY-srcY, unsigned(opacity * 255));
-   return MS_SUCCESS;
+                          int dstX, int dstY, int width, int height)
+{
+  assert(overlay->type == MS_BUFFER_BYTE_RGBA);
+  rendering_buffer b(overlay->data.rgba.pixels, overlay->width, overlay->height, overlay->data.rgba.row_step);
+  pixel_format pf(b);
+  AGG2Renderer *r = AGG_RENDERER(dest);
+  mapserver::rect_base<int> src_rect(srcX,srcY,srcX+width,srcY+height);
+  r->m_renderer_base.blend_from(pf,&src_rect, dstX-srcX, dstY-srcY, unsigned(opacity * 255));
+  return MS_SUCCESS;
 }
 
 /* image i/o */
-imageObj *agg2CreateImage(int width, int height, outputFormatObj *format, colorObj * bg) {
-   imageObj *image = NULL;
-   if (format->imagemode != MS_IMAGEMODE_RGB && format->imagemode != MS_IMAGEMODE_RGBA) {
-      msSetError(MS_MISCERR,
-              "AGG2 driver only supports RGB or RGBA pixel models.", "agg2CreateImage()");
-      return image;
-   }
-   image = (imageObj *) calloc(1, sizeof (imageObj));
-   MS_CHECK_ALLOC(image, sizeof (imageObj), NULL);
-   AGG2Renderer *r = new AGG2Renderer();
-
-   r->buffer = (band_type*)malloc(width * height * 4 * sizeof(band_type));
-   if (r->buffer == NULL)
-   {
-       msSetError(MS_MEMERR, "%s: %d: Out of memory allocating %u bytes.\n", "agg2CreateImage()",
-                  __FILE__, __LINE__, width * height * 4 * sizeof(band_type));
-       free(image);
-       return NULL; 
-   }
-   r->m_rendering_buffer.attach(r->buffer, width, height, width * 4);
-   r->m_pixel_format.attach(r->m_rendering_buffer);
-   r->m_renderer_base.attach(r->m_pixel_format);
-   r->m_renderer_scanline.attach(r->m_renderer_base);
-   if( bg && !format->transparent )
-      r->m_renderer_base.clear(aggColor(bg));
-   else
-      r->m_renderer_base.clear(AGG_NO_COLOR);
-
-   if (!bg || format->transparent || format->imagemode == MS_IMAGEMODE_RGBA ) {
-      r->use_alpha = true;
-   } else {
-      r->use_alpha = false;
-   }
-   image->img.plugin = (void*) r;
-
-   return image;
+imageObj *agg2CreateImage(int width, int height, outputFormatObj *format, colorObj * bg)
+{
+  imageObj *image = NULL;
+  if (format->imagemode != MS_IMAGEMODE_RGB && format->imagemode != MS_IMAGEMODE_RGBA) {
+    msSetError(MS_MISCERR,
+               "AGG2 driver only supports RGB or RGBA pixel models.", "agg2CreateImage()");
+    return image;
+  }
+  image = (imageObj *) calloc(1, sizeof (imageObj));
+  MS_CHECK_ALLOC(image, sizeof (imageObj), NULL);
+  AGG2Renderer *r = new AGG2Renderer();
+
+  r->buffer = (band_type*)malloc(width * height * 4 * sizeof(band_type));
+  if (r->buffer == NULL) {
+    msSetError(MS_MEMERR, "%s: %d: Out of memory allocating %u bytes.\n", "agg2CreateImage()",
+               __FILE__, __LINE__, width * height * 4 * sizeof(band_type));
+    free(image);
+    return NULL;
+  }
+  r->m_rendering_buffer.attach(r->buffer, width, height, width * 4);
+  r->m_pixel_format.attach(r->m_rendering_buffer);
+  r->m_renderer_base.attach(r->m_pixel_format);
+  r->m_renderer_scanline.attach(r->m_renderer_base);
+  double gamma = atof(msGetOutputFormatOption( format, "GAMMA", "0.75" ));
+  if(gamma > 0.0 && gamma < 1.0) {
+    r->m_rasterizer_aa_gamma.gamma(mapserver::gamma_linear(0.0,gamma));
+  }
+  if( bg && !format->transparent )
+    r->m_renderer_base.clear(aggColor(bg));
+  else
+    r->m_renderer_base.clear(AGG_NO_COLOR);
+
+  if (!bg || format->transparent || format->imagemode == MS_IMAGEMODE_RGBA ) {
+    r->use_alpha = true;
+  } else {
+    r->use_alpha = false;
+  }
+  image->img.plugin = (void*) r;
+
+  return image;
 }
 
-int agg2SaveImage(imageObj *img, FILE *fp, outputFormatObj * format) {
-   msSetError(MS_MISCERR, "AGG2 does not support direct image saving", "agg2SaveImage()");
+int agg2SaveImage(imageObj *img, mapObj* map, FILE *fp, outputFormatObj * format)
+{
+  msSetError(MS_MISCERR, "AGG2 does not support direct image saving", "agg2SaveImage()");
 
-   return MS_FAILURE;
+  return MS_FAILURE;
 }
 /*...*/
 
 /* helper functions */
-int agg2GetTruetypeTextBBox(rendererVTableObj *renderer, char *font, double size, char *string,
-        rectObj *rect, double **advances) {
-   
-   aggRendererCache *cache = (aggRendererCache*)MS_RENDERER_CACHE(renderer);
-   if (!cache->m_feng.load_font(font, 0, mapserver::glyph_ren_outline)) {
-      msSetError(MS_TTFERR, "AGG error loading font (%s)", "agg2GetTruetypeTextBBox()", font);
-      return MS_FAILURE;
-   }
-   cache->m_feng.hinting(true);
-   cache->m_feng.height(size);
-   cache->m_feng.resolution(96);
-   cache->m_feng.flip_y(true);
-   int unicode, curGlyph = 1, numglyphs = 0;
-   if (advances) {
-      numglyphs = msGetNumGlyphs(string);
-   }
-   const mapserver::glyph_cache* glyph;
-   string += msUTF8ToUniChar(string, &unicode);
-   glyph = cache->m_fman.glyph(unicode);
-   if (glyph) {
-      rect->minx = glyph->bounds.x1;
-      rect->maxx = glyph->bounds.x2;
-      rect->miny = glyph->bounds.y1;
-      rect->maxy = glyph->bounds.y2;
-   } else
+int agg2GetTruetypeTextBBox(rendererVTableObj *renderer, char **fonts, int numfonts, double size, char *string,
+                            rectObj *rect, double **advances,int bAdjustBaseline)
+{
+
+  aggRendererCache *cache = (aggRendererCache*)MS_RENDERER_CACHE(renderer);
+  if(aggLoadFont(cache,fonts[0],size) == MS_FAILURE)
+    return MS_FAILURE;
+  int curfontidx = 0;
+
+  int unicode, curGlyph = 1, numglyphs = 0;
+  if (advances) {
+    numglyphs = msGetNumGlyphs(string);
+  }
+  const mapserver::glyph_cache* glyph;
+  string += msUTF8ToUniChar(string, &unicode);
+
+  if(curfontidx != 0) {
+    if(aggLoadFont(cache,fonts[0],size) == MS_FAILURE)
       return MS_FAILURE;
-   if (advances) {
-      *advances = (double*) malloc(numglyphs * sizeof (double));
-      MS_CHECK_ALLOC(*advances, numglyphs * sizeof (double), MS_FAILURE);
-      (*advances)[0] = glyph->advance_x;
-   }
-   double fx = glyph->advance_x, fy = glyph->advance_y;
-   while (*string) {
-      if (advances) {
-         if (*string == '\r' || *string == '\n')
-            (*advances)[curGlyph++] = -fx;
-      }
-      if (*string == '\r') {
-         fx = 0;
-         string++;
-         continue;
+    curfontidx = 0;
+  }
+  glyph = cache->m_fman.glyph(unicode);
+  if(!glyph || glyph->glyph_index == 0) {
+    int i;
+    for(i=1; i<numfonts; i++) {
+      if(aggLoadFont(cache,fonts[i],size) == MS_FAILURE)
+        return MS_FAILURE;
+      curfontidx = i;
+      glyph = cache->m_fman.glyph(unicode);
+      if(glyph && glyph->glyph_index != 0) {
+        break;
       }
-      if (*string == '\n') {
-         fx = 0;
-         fy += ceil(size * AGG_LINESPACE);
-         string++;
-         continue;
+    }
+  }
+  if (glyph) {
+    rect->minx = glyph->bounds.x1;
+    rect->maxx = glyph->bounds.x2;
+    rect->miny = glyph->bounds.y1;
+    rect->maxy = bAdjustBaseline?1:glyph->bounds.y2;
+  } else
+    return MS_FAILURE;
+  if (advances) {
+    *advances = (double*) malloc(numglyphs * sizeof (double));
+    MS_CHECK_ALLOC(*advances, numglyphs * sizeof (double), MS_FAILURE);
+    (*advances)[0] = glyph->advance_x;
+  }
+  double fx = glyph->advance_x, fy = glyph->advance_y;
+  while (*string) {
+    if (advances) {
+      if (*string == '\r' || *string == '\n')
+        (*advances)[curGlyph++] = -fx;
+    }
+    if (*string == '\r') {
+      fx = 0;
+      string++;
+      continue;
+    }
+    if (*string == '\n') {
+      fx = 0;
+      fy += ceil(size * AGG_LINESPACE);
+      string++;
+      continue;
+    }
+    string += msUTF8ToUniChar(string, &unicode);
+    if(curfontidx != 0) {
+      if(aggLoadFont(cache,fonts[0],size) == MS_FAILURE)
+        return MS_FAILURE;
+      curfontidx = 0;
+    }
+    glyph = cache->m_fman.glyph(unicode);
+    if(!glyph || glyph->glyph_index == 0) {
+      int i;
+      for(i=1; i<numfonts; i++) {
+        if(aggLoadFont(cache,fonts[i],size) == MS_FAILURE)
+          return MS_FAILURE;
+        curfontidx = i;
+        glyph = cache->m_fman.glyph(unicode);
+        if(glyph && glyph->glyph_index != 0) {
+          break;
+        }
       }
-      string += msUTF8ToUniChar(string, &unicode);
-      glyph = cache->m_fman.glyph(unicode);
-      if (glyph) {
-         rect->minx = MS_MIN(rect->minx, fx+glyph->bounds.x1);
-         rect->miny = MS_MIN(rect->miny, fy+glyph->bounds.y1);
-         rect->maxx = MS_MAX(rect->maxx, fx+glyph->bounds.x2);
-         rect->maxy = MS_MAX(rect->maxy, fy+glyph->bounds.y2);
-
-         fx += glyph->advance_x;
-         fy += glyph->advance_y;
-         if (advances) {
-            (*advances)[curGlyph++] = glyph->advance_x;
-         }
+    }
+    if (glyph) {
+      rect->minx = MS_MIN(rect->minx, fx+glyph->bounds.x1);
+      rect->miny = MS_MIN(rect->miny, fy+glyph->bounds.y1);
+      rect->maxx = MS_MAX(rect->maxx, fx+glyph->bounds.x2);
+      rect->maxy = MS_MAX(rect->maxy, fy+(bAdjustBaseline?1:glyph->bounds.y2));
+
+      fx += glyph->advance_x;
+      fy += glyph->advance_y;
+      if (advances) {
+        (*advances)[curGlyph++] = glyph->advance_x;
       }
-   }
-   return MS_SUCCESS;
+    }
+  }
+  return MS_SUCCESS;
 }
 
-int agg2StartNewLayer(imageObj *img, mapObj*map, layerObj *layer) {
-	return MS_SUCCESS;
+int agg2StartNewLayer(imageObj *img, mapObj*map, layerObj *layer)
+{
+  return MS_SUCCESS;
 }
 
-int agg2CloseNewLayer(imageObj *img, mapObj *map, layerObj *layer) {
-	return MS_SUCCESS;
+int agg2CloseNewLayer(imageObj *img, mapObj *map, layerObj *layer)
+{
+  return MS_SUCCESS;
 }
 
-int agg2FreeImage(imageObj * image) {
-   AGG2Renderer *r = AGG_RENDERER(image);
-   free(r->buffer);
-   delete r;
-   image->img.plugin = NULL;
-   return MS_SUCCESS;
+int agg2FreeImage(imageObj * image)
+{
+  AGG2Renderer *r = AGG_RENDERER(image);
+  free(r->buffer);
+  delete r;
+  image->img.plugin = NULL;
+  return MS_SUCCESS;
 }
 
-int agg2FreeSymbol(symbolObj * symbol) {
-	switch(symbol->type) {
-	case MS_SYMBOL_PIXMAP:
-	   if(symbol->renderer_cache) {
-	      rendering_buffer *rb = (rendering_buffer*)symbol->renderer_cache;
-	      free(rb->buf());
-	      delete (rendering_buffer*)symbol->renderer_cache;
-	   }
-	   symbol->renderer_cache = NULL;
-	   break;
-	}
-	return MS_SUCCESS;
-
+int agg2FreeSymbol(symbolObj * symbol)
+{
+  return MS_SUCCESS;
 }
 
-int agg2InitCache(void **vcache) {
-	aggRendererCache *cache = new aggRendererCache();
-	*vcache = (void*)cache;
-	return MS_SUCCESS;
+int agg2InitCache(void **vcache)
+{
+  aggRendererCache *cache = new aggRendererCache();
+  *vcache = (void*)cache;
+  return MS_SUCCESS;
 }
 
-int agg2Cleanup(void *vcache) {
-	aggRendererCache *cache = (aggRendererCache*)vcache;
-	delete cache;
-	return MS_SUCCESS;
+int agg2Cleanup(void *vcache)
+{
+  aggRendererCache *cache = (aggRendererCache*)vcache;
+  delete cache;
+  return MS_SUCCESS;
 }
 
 
-// ------------------------------------------------------------------------ 
-// Function to create a custom hatch symbol based on an arbitrary angle. 
 // ------------------------------------------------------------------------
-static mapserver::path_storage createHatch(int sx, int sy, double angle, double step)
+// Function to create a custom hatch symbol based on an arbitrary angle.
+// ------------------------------------------------------------------------
+static mapserver::path_storage createHatch(double ox, double oy,
+    double rx, double ry,
+    int sx, int sy, double angle, double step)
 {
-    mapserver::path_storage path;
-    //path.start_new_path();
-    //restrict the angle to [0 180[
-    angle = fmod(angle, 360.0);
-    if(angle < 0) angle += 360;
-    if(angle >= 180) angle -= 180;
-
-    //treat 2 easy cases which would cause divide by 0 in generic case
-    if(angle==0) {
-        for(double y=step/2.0;y<sy;y+=step) {
-            path.move_to(0,y);
-            path.line_to(sx,y);
-        }
-        return path;
+  mapserver::path_storage path;
+  //restrict the angle to [0 180[, i.e ]-pi/2,pi/2] in radians
+  angle = fmod(angle, 360.0);
+  if(angle < 0) angle += 360;
+  if(angle >= 180) angle -= 180;
+
+  //treat 2 easy cases which would cause divide by 0 in generic case
+  if(angle==0) {
+    double y0 = step-fmod(oy-ry,step);
+    if((oy - ry) < 0) {
+      y0 -= step;
     }
-    if(angle==90) {
-        for(double x=step/2.0;x<sx;x+=step) {
-            path.move_to(x,0);
-            path.line_to(x,sy);
-        }
-        return path;
+    for(double y=y0; y<sy; y+=step) {
+      path.move_to(0,y);
+      path.line_to(sx,y);
     }
-
-
-    double theta = (90-angle)*MS_DEG_TO_RAD;
-    double ct = cos(theta);
-    double st = sin(theta);
-    double rmax = sqrt((double)sx*sx+sy*sy);
-
-    //parametrize each line as r = x.cos(theta) + y.sin(theta)
-    for(double r=(angle<90)?step/2.:-rmax;r<rmax;r+=step) {
-        int inter=0;
-        double x,y;
-        double pt[8]; //array to store the coordinates of intersection of the line with the sides
-        //in the general case there will only be two intersections
-        //so pt[4] should be sufficient to store the coordinates of the intersection,
-        //but we allocate pt[8] to treat the special and rare/unfortunate case when the
-        //line is a perfect diagonal (and therfore intersects all four sides)
-        //note that the order for testing is important in this case so that the first
-        //two intersection points actually correspond to the diagonal and not a degenerate line
-        
-        //test for intersection with each side
-
-        y=r/st;x=0; // test for intersection with top of image
-        if(y>=0&&y<=sy) {
-            pt[2*inter]=x;pt[2*inter+1]=y;
-            inter++;
-        }     
-        x=sx;y=(r-sx*ct)/st;// test for intersection with bottom of image
-        if(y>=0&&y<=sy) {
-            pt[2*inter]=x;pt[2*inter+1]=y;
-            inter++;
-        }
-        y=0;x=r/ct;// test for intersection with left of image
-        if(x>=0&&x<=sx) {
-            pt[2*inter]=x;pt[2*inter+1]=y;
-            inter++;
-        }
-        y=sy;x=(r-sy*st)/ct;// test for intersection with right of image
-        if(x>=0&&x<=sx) {
-            pt[2*inter]=x;pt[2*inter+1]=y;
-            inter++;
-        }
-        if(inter==2 && (pt[0]!=pt[2] || pt[1]!=pt[3])) { 
-            //the line intersects with two sides of the image, it should therefore be drawn
-            path.move_to(pt[0],pt[1]);
-            path.line_to(pt[2],pt[3]);
-        }
+    return path;
+  }
+  if(angle==90) {
+    double x0 = step-fmod(ox-rx,step);
+    if((ox - rx) < 0) {
+      x0 -= step;
+    }
+    for(double x=x0; x<sx; x+=step) {
+      path.move_to(x,0);
+      path.line_to(x,sy);
     }
     return path;
+  }
+
+
+  double theta = (90-angle)*MS_DEG_TO_RAD; /* theta in ]-pi/2 , pi/2] */
+  double ct = cos(theta);
+  double st = sin(theta);
+  double invct = 1.0/ct;
+  double invst = 1.0/st;
+  double r0; /* distance from first hatch line to the top-left (if angle in  0,pi/2)
+                  or bottom-left (if angle in -pi/2,0) corner of the hatch bbox */
+  double rmax = sqrt((double)(sx*sx+sy*sy)); /* distance to the furthest hatch we will have to create
+TODO: this could be optimized for bounding boxes where width is very different than height for
+certain hatch angles */
+  double rref= rx*ct + ry*st; /* distance to the line passing through the refpoint, origin is
+                                   (0,0) of the imageObj */
+  double rcorner; /* distance to the line passing through the topleft or bottomleft corner
+                       of the hatch bbox (origin is (0,0) of imageObj) */
+
+  /* calculate the distance from the refpoint to the top right of the path */
+  if(angle < 90) {
+    rcorner = ox*ct + oy*st;
+    r0 = step - fmod(rcorner-rref,step);
+    if(rcorner-rref<0) r0 -= step;
+  } else {
+    rcorner = ox*ct + (oy+sy)*st;
+    r0 = step - fmod(rcorner-rref,step);
+    if(rcorner-rref<0) r0 -= step;
+    st = -st;
+    invst = -invst;
+  }
+
+
+  //parametrize each line as r = x.cos(theta) + y.sin(theta)
+  for(double r=r0; r<rmax; r+=step) {
+    int inter=0;
+    double x,y;
+    double pt[4]; //array to store the coordinates of intersection of the line with the sides
+    //in the general case there will only be two intersections
+    //so pt[4] should be sufficient to store the coordinates of the intersection,
+    //but we allocate pt[8] to treat the special and rare/unfortunate case when the
+    //line is a perfect diagonal (and therfore intersects all four sides)
+    //note that the order for testing is important in this case so that the first
+    //two intersection points actually correspond to the diagonal and not a degenerate line
+
+    //test for intersection with each side
+
+    y=r*invst;
+    x=0; // test for intersection with left of image
+    if(y>=0&&y<=sy) {
+      pt[2*inter]=x;
+      pt[2*inter+1]=y;
+      inter++;
+    }
+    x=sx;
+    y=(r-sx*ct)*invst;// test for intersection with right of image
+    if(y>=0&&y<=sy) {
+      pt[2*inter]=x;
+      pt[2*inter+1]=y;
+      inter++;
+    }
+    if(inter<2) {
+      y=0;
+      x=r*invct;// test for intersection with top of image
+      if(x>=0&&x<=sx) {
+        pt[2*inter]=x;
+        pt[2*inter+1]=y;
+        inter++;
+      }
+    }
+    if(inter<2) {
+      y=sy;
+      x=(r-sy*st)*invct;// test for intersection with bottom of image
+      if(x>=0&&x<=sx) {
+        pt[2*inter]=x;
+        pt[2*inter+1]=y;
+        inter++;
+      }
+    }
+    if(inter==2 && (pt[0]!=pt[2] || pt[1]!=pt[3])) {
+      //the line intersects with two sides of the image, it should therefore be drawn
+      if(angle<90) {
+        path.move_to(pt[0],pt[1]);
+        path.line_to(pt[2],pt[3]);
+      } else {
+        path.move_to(pt[0],sy-pt[1]);
+        path.line_to(pt[2],sy-pt[3]);
+      }
+    }
+  }
+  return path;
 }
 
-int agg2RenderPolygonHatched(imageObj *img, shapeObj *poly, double spacing, double width, double angle, colorObj *color) {
-   
-   msComputeBounds(poly);
-
-   /* 
-    * we create a hatch pattern that is the size of the shapeObj's bounds, expanded by the width 
-    * of the stroke we want to apply to the lines to account for end-caps artifacts
-    */
-   int pw=(int)(poly->bounds.maxx-poly->bounds.minx+width*2)+1;
-   int ph=(int)(poly->bounds.maxy-poly->bounds.miny+width*2)+1;
-
-   //create a rectangular hatch of size pw,ph starting at 0,0
-   //the created hatch is of the size of the shape's bounding box
-   mapserver::path_storage hatch = createHatch(pw,ph,angle,spacing);
-   
-   //translate the hatch so it overlaps the current shape
-   hatch.transform(mapserver::trans_affine_translation(poly->bounds.minx-width,poly->bounds.miny-width));
-
-
-
-   //render the hatch clipped by the shape
-   mapserver::conv_stroke <mapserver::path_storage > stroke(hatch);
-   stroke.width(width);
-   stroke.line_cap(mapserver::butt_cap);
-   
-   polygon_adaptor polygons(poly);
-   
-	AGG2Renderer *r = AGG_RENDERER(img);
-   
-   mapserver::rasterizer_scanline_aa<> ras1,ras2;
-   mapserver::scanline_storage_aa8 storage;
-   mapserver::scanline_storage_aa8 storage1;
-   mapserver::scanline_storage_aa8 storage2;
-   mapserver::scanline_p8 sl1,sl2;
-   ras1.filling_rule(mapserver::fill_non_zero);
-   ras1.add_path(stroke);                    
-   mapserver::render_scanlines(ras1, r->sl_line, storage1);
-   ras2.filling_rule(mapserver::fill_even_odd);
-   ras2.add_path(polygons);
-   mapserver::render_scanlines(ras2,r->sl_poly,storage2);
-   mapserver::sbool_combine_shapes_aa(mapserver::sbool_and, storage1, storage2, sl1, sl2, r->sl_line, storage);
-   r->m_renderer_scanline.color(aggColor(color));
-   mapserver::render_scanlines ( storage, r->sl_poly, r->m_renderer_scanline );
-   return MS_SUCCESS;
-
-}
-
-int msHatchPolygon(imageObj *img, shapeObj *poly, double spacing, double width, double angle, colorObj *color) {
-   assert(MS_RENDERER_PLUGIN(img->format));
-   msComputeBounds(poly);
-   int pw=(int)(poly->bounds.maxx-poly->bounds.minx+width*2)+1;
-   int ph=(int)(poly->bounds.maxy-poly->bounds.miny+width*2)+1;
-   mapserver::path_storage lines = createHatch(pw,ph, angle, spacing);
-   lines.transform(mapserver::trans_affine_translation(poly->bounds.minx-width,poly->bounds.miny-width));
-   polygon_adaptor polygons(poly);
-   shapeObj shape;
-   msInitShape(&shape);
-   int allocated = 20;
-   lineObj line;
-   shape.line = &line;
-   shape.numlines = 1;
-   shape.line[0].point = (pointObj*)msSmallCalloc(allocated,sizeof(pointObj));
-   shape.line[0].numpoints = 0;
-   mapserver::conv_stroke<mapserver::path_storage> stroke(lines);
-   stroke.width(width);
-   stroke.line_cap(mapserver::butt_cap);
-   //mapserver::conv_clipper<mapserver::path_storage,polygon_adaptor> clipper(*lines,polygons, mapserver::clipper_and);
-   //mapserver::conv_clipper<polygon_adaptor,mapserver::path_storage> clipper(polygons,lines, mapserver::clipper_and);
-   mapserver::conv_clipper<polygon_adaptor,mapserver::conv_stroke<mapserver::path_storage> > clipper(polygons,stroke, mapserver::clipper_and); 
-   clipper.rewind(0);
-   
-   double x=0,y=0;
-   unsigned int cmd, prevCmd=-1;
-   while((cmd = clipper.vertex(&x,&y)) != mapserver::path_cmd_stop) {
+template<class VertexSource> void renderPolygonHatches(imageObj *img,VertexSource &clipper, colorObj *color)
+{
+  if(img->format->renderer == MS_RENDER_WITH_AGG) {
+    AGG2Renderer *r = AGG_RENDERER(img);
+    r->m_rasterizer_aa_gamma.reset();
+    r->m_rasterizer_aa_gamma.filling_rule(mapserver::fill_non_zero);
+    r->m_rasterizer_aa_gamma.add_path(clipper);
+    r->m_renderer_scanline.color(aggColor(color));
+    mapserver::render_scanlines(r->m_rasterizer_aa_gamma, r->sl_poly, r->m_renderer_scanline);
+  } else {
+    shapeObj shape;
+    msInitShape(&shape);
+    int allocated = 20;
+    lineObj line;
+    shape.line = &line;
+    shape.numlines = 1;
+    shape.line[0].point = (pointObj*)msSmallCalloc(allocated,sizeof(pointObj));
+    shape.line[0].numpoints = 0;
+    double x=0,y=0;
+    unsigned int cmd;
+    clipper.rewind(0);
+    while((cmd = clipper.vertex(&x,&y)) != mapserver::path_cmd_stop) {
       switch(cmd) {
-      case mapserver::path_cmd_line_to:
-         if(shape.line[0].numpoints == allocated) {
+        case mapserver::path_cmd_line_to:
+          if(shape.line[0].numpoints == allocated) {
             allocated *= 2;
             shape.line[0].point = (pointObj*)msSmallRealloc(shape.line[0].point, allocated*sizeof(pointObj));
-         }
-         shape.line[0].point[shape.line[0].numpoints].x = x;
-         shape.line[0].point[shape.line[0].numpoints].y = y;
-         shape.line[0].numpoints++;
-         break;
-      case mapserver::path_cmd_move_to:
-         //assert(shape.line[0].numpoints <= 1 || prevCmd == mapserver::path_cmd_line_to);
-         shape.line[0].point[0].x = x;
-         shape.line[0].point[0].y = y;
-         shape.line[0].numpoints = 1;
-         break;
-      case mapserver::path_cmd_end_poly|mapserver::path_flags_close:
-         if(shape.line[0].numpoints > 2) {
+          }
+          shape.line[0].point[shape.line[0].numpoints].x = x;
+          shape.line[0].point[shape.line[0].numpoints].y = y;
+          shape.line[0].numpoints++;
+          break;
+        case mapserver::path_cmd_move_to:
+          shape.line[0].point[0].x = x;
+          shape.line[0].point[0].y = y;
+          shape.line[0].numpoints = 1;
+          break;
+        case mapserver::path_cmd_end_poly|mapserver::path_flags_close:
+          if(shape.line[0].numpoints > 2) {
             MS_IMAGE_RENDERER(img)->renderPolygon(img,&shape,color);
-         }
-         break;
-      default:
-         assert(0); //WTF?
+          }
+          break;
+        default:
+          assert(0); //WTF?
       }
-      prevCmd = cmd;
-   }
-   free(shape.line[0].point);
-   //assert(prevCmd == mapserver::path_cmd_line_to);
-   //delete lines;
-   return MS_SUCCESS;
+    }
+    free(shape.line[0].point);
+  }
 }
 
+int msHatchPolygon(imageObj *img, shapeObj *poly, double spacing, double width, double *pattern, int patternlength, double angle, colorObj *color)
+{
+  assert(MS_RENDERER_PLUGIN(img->format));
+  msComputeBounds(poly);
+
+  /* amount we should expand the bounding box by */
+  double exp = width * 0.7072;
+
+  /* width and height of the bounding box we will be creating the hatch in */
+  int pw=(int)(poly->bounds.maxx-poly->bounds.minx+exp*2)+1;
+  int ph=(int)(poly->bounds.maxy-poly->bounds.miny+exp*2)+1;
+
+  /* position of the top-left corner of the bounding box */
+  double ox = poly->bounds.minx - exp;
+  double oy = poly->bounds.miny - exp;
+
+  //create a rectangular hatch of size pw,ph starting at 0,0
+  //the created hatch is of the size of the shape's bounding box
+  mapserver::path_storage hatch = createHatch(ox,oy,
+                                  img->refpt.x,img->refpt.y,pw,ph,angle,spacing);
+  if(hatch.total_vertices()<=0) return MS_SUCCESS;
+
+  //translate the hatch so it overlaps the current shape
+  hatch.transform(mapserver::trans_affine_translation(ox,oy));
+
+  polygon_adaptor polygons(poly);
+
+
+
+  if(patternlength>1) {
+    //dash the hatch and render it clipped by the shape
+    mapserver::conv_dash<mapserver::path_storage > dash(hatch);
+    mapserver::conv_stroke<mapserver::conv_dash<mapserver::path_storage> > stroke(dash);
+    for (int i=0; i<patternlength; i+=2) {
+      if (i < patternlength-1) {
+        dash.add_dash(pattern[i], pattern[i+1]);
+      }
+    }
+    stroke.width(width);
+    stroke.line_cap(mapserver::butt_cap);
+    mapserver::conv_clipper<polygon_adaptor,mapserver::conv_stroke<mapserver::conv_dash<mapserver::path_storage> > > clipper(polygons,stroke, mapserver::clipper_and);
+    renderPolygonHatches(img,clipper,color);
+  } else {
+    //render the hatch clipped by the shape
+    mapserver::conv_stroke <mapserver::path_storage > stroke(hatch);
+    stroke.width(width);
+    stroke.line_cap(mapserver::butt_cap);
+    mapserver::conv_clipper<polygon_adaptor,mapserver::conv_stroke<mapserver::path_storage> > clipper(polygons,stroke, mapserver::clipper_and);
+    renderPolygonHatches(img,clipper,color);
+  }
+
+
+  //assert(prevCmd == mapserver::path_cmd_line_to);
+  //delete lines;
+  return MS_SUCCESS;
+}
+
+
+int msPopulateRendererVTableAGG(rendererVTableObj * renderer)
+{
+  renderer->supports_transparent_layers = 0;
+  renderer->supports_pixel_buffer = 1;
+  renderer->use_imagecache = 0;
+  renderer->supports_clipping = 0;
+  renderer->supports_svg = 0;
+  renderer->default_transform_mode = MS_TRANSFORM_SIMPLIFY;
+  agg2InitCache(&(MS_RENDERER_CACHE(renderer)));
+  renderer->cleanup = agg2Cleanup;
+  renderer->renderLine = &agg2RenderLine;
+
+  renderer->renderPolygon = &agg2RenderPolygon;
+  renderer->renderPolygonTiled = &agg2RenderPolygonTiled;
+  renderer->renderLineTiled = &agg2RenderLineTiled;
+
+  renderer->renderGlyphs = &agg2RenderGlyphs;
+  renderer->renderGlyphsLine = &agg2RenderGlyphsLine;
+  renderer->renderBitmapGlyphs = &agg2RenderBitmapGlyphs;
 
-int msPopulateRendererVTableAGG(rendererVTableObj * renderer) {
-   renderer->supports_transparent_layers = 0;
-   renderer->supports_pixel_buffer = 1;
-   renderer->use_imagecache = 0;
-   renderer->supports_clipping = 0;
-   renderer->default_transform_mode = MS_TRANSFORM_SIMPLIFY;
-   
-   agg2InitCache(&(MS_RENDERER_CACHE(renderer)));
-   renderer->cleanup = agg2Cleanup;
-   renderer->renderLine = &agg2RenderLine;
+  renderer->renderVectorSymbol = &agg2RenderVectorSymbol;
 
-   renderer->renderPolygon = &agg2RenderPolygon;
-   renderer->renderPolygonTiled = &agg2RenderPolygonTiled;
-   renderer->renderPolygonHatched = &agg2RenderPolygonHatched;
-   renderer->renderLineTiled = &agg2RenderLineTiled;
+  renderer->renderPixmapSymbol = &agg2RenderPixmapSymbol;
 
-   renderer->renderGlyphs = &agg2RenderGlyphs;
-   renderer->renderBitmapGlyphs = &agg2RenderBitmapGlyphs;
-      
-   renderer->renderVectorSymbol = &agg2RenderVectorSymbol;
+  renderer->renderEllipseSymbol = &agg2RenderEllipseSymbol;
 
-   renderer->renderPixmapSymbol = &agg2RenderPixmapSymbol;
+  renderer->renderTruetypeSymbol = &agg2RenderTruetypeSymbol;
 
-   renderer->renderEllipseSymbol = &agg2RenderEllipseSymbol;
+  renderer->renderTile = &agg2RenderTile;
 
-   renderer->renderTruetypeSymbol = &agg2RenderTruetypeSymbol;
+  renderer->getRasterBufferHandle = &aggGetRasterBufferHandle;
+  renderer->getRasterBufferCopy = aggGetRasterBufferCopy;
+  renderer->initializeRasterBuffer = aggInitializeRasterBuffer;
 
-   renderer->renderTile = &agg2RenderTile;
+  renderer->mergeRasterBuffer = &agg2MergeRasterBuffer;
+  renderer->loadImageFromFile = msLoadMSRasterBufferFromFile;
+  renderer->createImage = &agg2CreateImage;
+  renderer->saveImage = &agg2SaveImage;
 
-   renderer->getRasterBufferHandle = &aggGetRasterBufferHandle;
-   renderer->getRasterBufferCopy = aggGetRasterBufferCopy;
-   renderer->initializeRasterBuffer = aggInitializeRasterBuffer;
+  renderer->getTruetypeTextBBox = &agg2GetTruetypeTextBBox;
 
-   renderer->mergeRasterBuffer = &agg2MergeRasterBuffer;
-   renderer->loadImageFromFile = msLoadMSRasterBufferFromFile;
-   renderer->createImage = &agg2CreateImage;
-   renderer->saveImage = &agg2SaveImage;
+  renderer->startLayer = &agg2StartNewLayer;
+  renderer->endLayer = &agg2CloseNewLayer;
 
-   renderer->getTruetypeTextBBox = &agg2GetTruetypeTextBBox;
+  renderer->freeImage = &agg2FreeImage;
+  renderer->freeSymbol = &agg2FreeSymbol;
+  renderer->cleanup = agg2Cleanup;
 
-   renderer->startLayer = &agg2StartNewLayer;
-   renderer->endLayer = &agg2CloseNewLayer;
+  renderer->supports_bitmap_fonts = 1;
+  for(int i=0; i<5; i++) {
+    renderer->bitmapFontMetrics[i] = &(rasterfont_sizes[i]);
+  }
 
-   renderer->freeImage = &agg2FreeImage;
-   renderer->freeSymbol = &agg2FreeSymbol;
-   renderer->cleanup = agg2Cleanup;
-   
-   renderer->supports_bitmap_fonts = 1;
-   for(int i=0;i<5;i++) {
-	   renderer->bitmapFontMetrics[i] = &(rasterfont_sizes[i]);
-   }
-   
-   return MS_SUCCESS;
+  return MS_SUCCESS;
 }
diff --git a/mapagg.h b/mapagg.h
index 24ede93..3ad4594 100644
--- a/mapagg.h
+++ b/mapagg.h
@@ -3,7 +3,7 @@
  *
  * Project:  MapServer
  * Purpose:  AGG template library types.
- * Author:   John Novak (jnovak at novacell.com) 
+ * Author:   John Novak (jnovak at novacell.com)
  *
  ******************************************************************************
  * Copyright (c) 1996-2007 Regents of the University of Minnesota.
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -33,157 +33,151 @@
  * interface to a shapeObj representing lines, providing the functions
  * needed by the agg rasterizer. treats shapeObjs with multiple linestrings.
  */
-class line_adaptor {
+class line_adaptor
+{
 public:
-    line_adaptor(shapeObj *shape):s(shape)
-    {
-        m_line=s->line; /*first line*/
-        m_point=m_line->point; /*current vertex is first vertex of first line*/
-        m_lend=&(s->line[s->numlines]); /*pointer to after last line*/
-        m_pend=&(m_line->point[m_line->numpoints]); /*pointer to after last vertex of first line*/
-    }
-    
-    /* a class with virtual functions should also provide a virtual destructor */
-    virtual ~line_adaptor() {}
-    
-    void rewind(unsigned) {
-        m_line=s->line; /*first line*/
-        m_point=m_line->point; /*current vertex is first vertex of first line*/
-        m_pend=&(m_line->point[m_line->numpoints]); /*pointer to after last vertex of first line*/
+  line_adaptor(shapeObj *shape):s(shape) {
+    m_line=s->line; /*first line*/
+    m_point=m_line->point; /*current vertex is first vertex of first line*/
+    m_lend=&(s->line[s->numlines]); /*pointer to after last line*/
+    m_pend=&(m_line->point[m_line->numpoints]); /*pointer to after last vertex of first line*/
+  }
+
+  /* a class with virtual functions should also provide a virtual destructor */
+  virtual ~line_adaptor() {}
+
+  void rewind(unsigned) {
+    m_line=s->line; /*first line*/
+    m_point=m_line->point; /*current vertex is first vertex of first line*/
+    m_pend=&(m_line->point[m_line->numpoints]); /*pointer to after last vertex of first line*/
+  }
+
+  virtual unsigned vertex(double* x, double* y) {
+    if(m_point < m_pend) {
+      /*here we treat the case where a real vertex is returned*/
+      bool first = m_point == m_line->point; /*is this the first vertex of a line*/
+      *x = m_point->x;
+      *y = m_point->y;
+      m_point++;
+      return first ? mapserver::path_cmd_move_to : mapserver::path_cmd_line_to;
     }
-    
-    virtual unsigned vertex(double* x, double* y)
-    {
-        if(m_point < m_pend)
-        {
-            /*here we treat the case where a real vertex is returned*/
-            bool first = m_point == m_line->point; /*is this the first vertex of a line*/
-            *x = m_point->x;
-            *y = m_point->y;
-            m_point++;
-            return first ? mapserver::path_cmd_move_to : mapserver::path_cmd_line_to;
-        }
-        /*if here, we're at the end of a line*/
-        m_line++;
-        *x = *y = 0.0;
-        if(m_line>=m_lend) /*is this the last line of the shapObj. normally, 
+    /*if here, we're at the end of a line*/
+    m_line++;
+    *x = *y = 0.0;
+    if(m_line>=m_lend) /*is this the last line of the shapObj. normally,
         (m_line==m_lend) should be a sufficient test, as the caller should not call
         this function if a previous call returned path_cmd_stop.*/
-            return mapserver::path_cmd_stop; /*no more points to process*/
-        
-        /*if here, there are more lines in the shapeObj, continue with next one*/
-        m_point=m_line->point; /*pointer to first point of next line*/
-        m_pend=&(m_line->point[m_line->numpoints]); /*pointer to after last point of next line*/
-       
-        return vertex(x,y); /*this will return the first point of the next line*/
-    }
+      return mapserver::path_cmd_stop; /*no more points to process*/
+
+    /*if here, there are more lines in the shapeObj, continue with next one*/
+    m_point=m_line->point; /*pointer to first point of next line*/
+    m_pend=&(m_line->point[m_line->numpoints]); /*pointer to after last point of next line*/
+
+    return vertex(x,y); /*this will return the first point of the next line*/
+  }
 private:
-    shapeObj *s;
-    lineObj *m_line, /*current line pointer*/
-    *m_lend; /*points to after the last line*/
-    pointObj *m_point, /*current point*/
-    *m_pend; /*points to after last point of current line*/
+  shapeObj *s;
+  lineObj *m_line, /*current line pointer*/
+          *m_lend; /*points to after the last line*/
+  pointObj *m_point, /*current point*/
+           *m_pend; /*points to after last point of current line*/
 };
 
-class offset_line_adaptor: public line_adaptor  {
+class offset_line_adaptor: public line_adaptor
+{
 public:
-    offset_line_adaptor(shapeObj *shape, double ox, double oy):line_adaptor(shape),ox(ox),oy(oy)
-    {
-    }
-    
-    unsigned vertex(double* x, double* y)
-    {
-        unsigned ret = line_adaptor::vertex(x,y);
-        *x+=ox;
-        *y+=oy;
-        return ret;
-    }
+  offset_line_adaptor(shapeObj *shape, double ox, double oy):line_adaptor(shape),ox(ox),oy(oy) {
+  }
+
+  unsigned vertex(double* x, double* y) {
+    unsigned ret = line_adaptor::vertex(x,y);
+    *x+=ox;
+    *y+=oy;
+    return ret;
+  }
 private:
-    double ox,oy;
+  double ox,oy;
 };
 
 
 
-class polygon_adaptor {
+class polygon_adaptor
+{
 public:
-    polygon_adaptor(shapeObj *shape):s(shape),m_stop(false)
-    {
-        m_line=s->line; /*first lines*/
-        m_point=m_line->point; /*first vertex of first line*/
-        m_lend=&(s->line[s->numlines]); /*pointer to after last line*/
-        m_pend=&(m_line->point[m_line->numpoints]); /*pointer to after last vertex of first line*/
-    }
-    
-    /* a class with virtual functions should also provide a virtual destructor */
-    virtual ~polygon_adaptor() {}
-    
-    void rewind(unsigned) {
-        /*reset pointers*/
-        m_stop=false;
-        m_line=s->line;
-        m_point=m_line->point;
-        m_pend=&(m_line->point[m_line->numpoints]);
+  polygon_adaptor(shapeObj *shape):s(shape),m_stop(false) {
+    m_line=s->line; /*first lines*/
+    m_point=m_line->point; /*first vertex of first line*/
+    m_lend=&(s->line[s->numlines]); /*pointer to after last line*/
+    m_pend=&(m_line->point[m_line->numpoints]); /*pointer to after last vertex of first line*/
+  }
+
+  /* a class with virtual functions should also provide a virtual destructor */
+  virtual ~polygon_adaptor() {}
+
+  void rewind(unsigned) {
+    /*reset pointers*/
+    m_stop=false;
+    m_line=s->line;
+    m_point=m_line->point;
+    m_pend=&(m_line->point[m_line->numpoints]);
+  }
+
+  virtual unsigned vertex(double* x, double* y) {
+    if(m_point < m_pend) {
+      /*if here, we have a real vertex*/
+      bool first = m_point == m_line->point;
+      *x = m_point->x;
+      *y = m_point->y;
+      m_point++;
+      return first ? mapserver::path_cmd_move_to : mapserver::path_cmd_line_to;
     }
-    
-    virtual unsigned vertex(double* x, double* y)
-    {
-        if(m_point < m_pend)
-        {
-            /*if here, we have a real vertex*/
-            bool first = m_point == m_line->point;
-            *x = m_point->x;
-            *y = m_point->y;
-            m_point++;
-            return first ? mapserver::path_cmd_move_to : mapserver::path_cmd_line_to;
-        }
-        *x = *y = 0.0;
-        if(!m_stop) {
-            /*if here, we're after the last vertex of the current line
-             * we return the command to close the current polygon*/
-            m_line++;
-            if(m_line>=m_lend) {
-                /*if here, we've finished all the vertexes of the shape.
-                 * we still return the command to close the current polygon,
-                 * but set m_stop so the subsequent call to vertex() will return
-                 * the stop command*/
-                m_stop=true;
-                return mapserver::path_cmd_end_poly;
-            }
-            /*if here, there's another line in the shape, so we set the pointers accordingly
-             * and return the command to close the current polygon*/
-            m_point=m_line->point; /*first vertex of next line*/
-            m_pend=&(m_line->point[m_line->numpoints]); /*pointer to after last vertex of next line*/
-            return mapserver::path_cmd_end_poly;
-        }
-        /*if here, a previous call to vertex informed us that we'd consumed all the vertexes
-         * of the shape. return the command to stop processing this shape*/
-        return mapserver::path_cmd_stop;
+    *x = *y = 0.0;
+    if(!m_stop) {
+      /*if here, we're after the last vertex of the current line
+       * we return the command to close the current polygon*/
+      m_line++;
+      if(m_line>=m_lend) {
+        /*if here, we've finished all the vertexes of the shape.
+         * we still return the command to close the current polygon,
+         * but set m_stop so the subsequent call to vertex() will return
+         * the stop command*/
+        m_stop=true;
+        return mapserver::path_cmd_end_poly;
+      }
+      /*if here, there's another line in the shape, so we set the pointers accordingly
+       * and return the command to close the current polygon*/
+      m_point=m_line->point; /*first vertex of next line*/
+      m_pend=&(m_line->point[m_line->numpoints]); /*pointer to after last vertex of next line*/
+      return mapserver::path_cmd_end_poly;
     }
+    /*if here, a previous call to vertex informed us that we'd consumed all the vertexes
+     * of the shape. return the command to stop processing this shape*/
+    return mapserver::path_cmd_stop;
+  }
 private:
-    shapeObj *s;
-    double ox,oy;
-    lineObj *m_line, /*pointer to current line*/
-    *m_lend; /*pointer to after last line of the shape*/
-    pointObj *m_point, /*pointer to current vertex*/
-    *m_pend; /*pointer to after last vertex of current line*/
-    bool m_stop; /*should next call return stop command*/ 
+  shapeObj *s;
+  double ox,oy;
+  lineObj *m_line, /*pointer to current line*/
+          *m_lend; /*pointer to after last line of the shape*/
+  pointObj *m_point, /*pointer to current vertex*/
+           *m_pend; /*pointer to after last vertex of current line*/
+  bool m_stop; /*should next call return stop command*/
 };
 
-class offset_polygon_adaptor: public polygon_adaptor  {
+class offset_polygon_adaptor: public polygon_adaptor
+{
 public:
-    offset_polygon_adaptor(shapeObj *shape, double ox, double oy):polygon_adaptor(shape),ox(ox),oy(oy)
-    {
-    }
-    
-    unsigned vertex(double* x, double* y)
-    {
-        unsigned ret = polygon_adaptor::vertex(x,y);
-        *x+=ox;
-        *y+=oy;
-        return ret;
-    }
+  offset_polygon_adaptor(shapeObj *shape, double ox, double oy):polygon_adaptor(shape),ox(ox),oy(oy) {
+  }
+
+  unsigned vertex(double* x, double* y) {
+    unsigned ret = polygon_adaptor::vertex(x,y);
+    *x+=ox;
+    *y+=oy;
+    return ret;
+  }
 private:
-    double ox,oy;
+  double ox,oy;
 };
 
 
diff --git a/mapaxisorder.csv b/mapaxisorder.csv
index 1c5bb15..5127d2b 100755
--- a/mapaxisorder.csv
+++ b/mapaxisorder.csv
@@ -1426,6 +1426,89 @@ epsg_code
 5273
 5274
 5275
+5323
+5324
+5340
+5342
+5343
+5344
+5345
+5346
+5347
+5348
+5349
+5353
+5354
+5359
+5360
+5364
+5365
+5367
+5370
+5371
+5372
+5373
+5380
+5381
+5392
+5393
+5451
+5464
+5467
+5479
+5480
+5481
+5482
+5488
+5489
+5513
+5515
+5518
+5519
+5520
+5524
+5527
+5545
+5546
+5560
+5561
+5562
+5563
+5564
+5565
+5566
+5567
+5568
+5569
+5570
+5571
+5572
+5573
+5574
+5575
+5576
+5577
+5578
+5579
+5580
+5581
+5582
+5583
+5588
+5592
+5593
+5632
+5633
+5634
+5635
+5636
+5637
+5638
+5639
+5651
+5652
+5653
+5681
 5801
 5802
 5803
@@ -1439,6 +1522,7 @@ epsg_code
 5814
 5815
 5816
+5830
 20004
 20005
 20006
diff --git a/mapaxisorder.h b/mapaxisorder.h
index 2b613ca..4321bcb 100644
--- a/mapaxisorder.h
+++ b/mapaxisorder.h
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id$
+ * $Id: $
  *
  * Project:  MapServer
  * Purpose:  Axis lookup table
@@ -14,7 +14,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -25,1727 +25,4116 @@
  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  * DEALINGS IN THE SOFTWARE.
  ****************************************************************************/
- 
+
 /*
  * Generated file
  *
  * This file was generated from by means of a script. Do not edit manually.
  */
- 
+
 #ifdef __cplusplus
 extern "C" {
 #endif
- 
-static struct axisOrientationEpsgCodes_s {
-	int	code;
-} axisOrientationEpsgCodes[] = {
-  4326,
-  4258,
-  31466,
-  31467,
-  31468,
-  31469,
-  2166,
-  2167,
-  2168,
-  2036,
-  2044,
-  2045,
-  2065,
-  2081,
-  2082,
-  2083,
-  2085,
-  2086,
-  2091,
-  2092,
-  2093,
-  2096,
-  2097,
-  2098,
-  2105,
-  2106,
-  2107,
-  2108,
-  2109,
-  2110,
-  2111,
-  2112,
-  2113,
-  2114,
-  2115,
-  2116,
-  2117,
-  2118,
-  2119,
-  2120,
-  2121,
-  2122,
-  2123,
-  2124,
-  2125,
-  2126,
-  2127,
-  2128,
-  2129,
-  2130,
-  2131,
-  2132,
-  2169,
-  2170,
-  2171,
-  2172,
-  2173,
-  2174,
-  2175,
-  2176,
-  2177,
-  2178,
-  2179,
-  2180,
-  2193,
-  2199,
-  2200,
-  2206,
-  2207,
-  2208,
-  2209,
-  2210,
-  2211,
-  2212,
-  2319,
-  2320,
-  2321,
-  2322,
-  2323,
-  2324,
-  2325,
-  2326,
-  2327,
-  2328,
-  2329,
-  2330,
-  2331,
-  2332,
-  2333,
-  2334,
-  2335,
-  2336,
-  2337,
-  2338,
-  2339,
-  2340,
-  2341,
-  2342,
-  2343,
-  2344,
-  2345,
-  2346,
-  2347,
-  2348,
-  2349,
-  2350,
-  2351,
-  2352,
-  2353,
-  2354,
-  2355,
-  2356,
-  2357,
-  2358,
-  2359,
-  2360,
-  2361,
-  2362,
-  2363,
-  2364,
-  2365,
-  2366,
-  2367,
-  2368,
-  2369,
-  2370,
-  2371,
-  2372,
-  2373,
-  2374,
-  2375,
-  2376,
-  2377,
-  2378,
-  2379,
-  2380,
-  2381,
-  2382,
-  2383,
-  2384,
-  2385,
-  2386,
-  2387,
-  2388,
-  2389,
-  2390,
-  2391,
-  2392,
-  2393,
-  2394,
-  2395,
-  2396,
-  2397,
-  2398,
-  2399,
-  2400,
-  2401,
-  2402,
-  2403,
-  2404,
-  2405,
-  2406,
-  2407,
-  2408,
-  2409,
-  2410,
-  2411,
-  2412,
-  2413,
-  2414,
-  2415,
-  2416,
-  2417,
-  2418,
-  2419,
-  2420,
-  2421,
-  2422,
-  2423,
-  2424,
-  2425,
-  2426,
-  2427,
-  2428,
-  2429,
-  2430,
-  2431,
-  2432,
-  2433,
-  2434,
-  2435,
-  2436,
-  2437,
-  2438,
-  2439,
-  2440,
-  2441,
-  2442,
-  2443,
-  2444,
-  2445,
-  2446,
-  2447,
-  2448,
-  2449,
-  2450,
-  2451,
-  2452,
-  2453,
-  2454,
-  2455,
-  2456,
-  2457,
-  2458,
-  2459,
-  2460,
-  2461,
-  2462,
-  2463,
-  2464,
-  2465,
-  2466,
-  2467,
-  2468,
-  2469,
-  2470,
-  2471,
-  2472,
-  2473,
-  2474,
-  2475,
-  2476,
-  2477,
-  2478,
-  2479,
-  2480,
-  2481,
-  2482,
-  2483,
-  2484,
-  2485,
-  2486,
-  2487,
-  2488,
-  2489,
-  2490,
-  2491,
-  2492,
-  2493,
-  2494,
-  2495,
-  2496,
-  2497,
-  2498,
-  2499,
-  2500,
-  2501,
-  2502,
-  2503,
-  2504,
-  2505,
-  2506,
-  2507,
-  2508,
-  2509,
-  2510,
-  2511,
-  2512,
-  2513,
-  2514,
-  2515,
-  2516,
-  2517,
-  2518,
-  2519,
-  2520,
-  2521,
-  2522,
-  2523,
-  2524,
-  2525,
-  2526,
-  2527,
-  2528,
-  2529,
-  2530,
-  2531,
-  2532,
-  2533,
-  2534,
-  2535,
-  2536,
-  2537,
-  2538,
-  2539,
-  2540,
-  2541,
-  2542,
-  2543,
-  2544,
-  2545,
-  2546,
-  2547,
-  2548,
-  2549,
-  2551,
-  2552,
-  2553,
-  2554,
-  2555,
-  2556,
-  2557,
-  2558,
-  2559,
-  2560,
-  2561,
-  2562,
-  2563,
-  2564,
-  2565,
-  2566,
-  2567,
-  2568,
-  2569,
-  2570,
-  2571,
-  2572,
-  2573,
-  2574,
-  2575,
-  2576,
-  2577,
-  2578,
-  2579,
-  2580,
-  2581,
-  2582,
-  2583,
-  2584,
-  2585,
-  2586,
-  2587,
-  2588,
-  2589,
-  2590,
-  2591,
-  2592,
-  2593,
-  2594,
-  2595,
-  2596,
-  2597,
-  2598,
-  2599,
-  2600,
-  2601,
-  2602,
-  2603,
-  2604,
-  2605,
-  2606,
-  2607,
-  2608,
-  2609,
-  2610,
-  2611,
-  2612,
-  2613,
-  2614,
-  2615,
-  2616,
-  2617,
-  2618,
-  2619,
-  2620,
-  2621,
-  2622,
-  2623,
-  2624,
-  2625,
-  2626,
-  2627,
-  2628,
-  2629,
-  2630,
-  2631,
-  2632,
-  2633,
-  2634,
-  2635,
-  2636,
-  2637,
-  2638,
-  2639,
-  2640,
-  2641,
-  2642,
-  2643,
-  2644,
-  2645,
-  2646,
-  2647,
-  2648,
-  2649,
-  2650,
-  2651,
-  2652,
-  2653,
-  2654,
-  2655,
-  2656,
-  2657,
-  2658,
-  2659,
-  2660,
-  2661,
-  2662,
-  2663,
-  2664,
-  2665,
-  2666,
-  2667,
-  2668,
-  2669,
-  2670,
-  2671,
-  2672,
-  2673,
-  2674,
-  2675,
-  2676,
-  2677,
-  2678,
-  2679,
-  2680,
-  2681,
-  2682,
-  2683,
-  2684,
-  2685,
-  2686,
-  2687,
-  2688,
-  2689,
-  2690,
-  2691,
-  2692,
-  2693,
-  2694,
-  2695,
-  2696,
-  2697,
-  2698,
-  2699,
-  2700,
-  2701,
-  2702,
-  2703,
-  2704,
-  2705,
-  2706,
-  2707,
-  2708,
-  2709,
-  2710,
-  2711,
-  2712,
-  2713,
-  2714,
-  2715,
-  2716,
-  2717,
-  2718,
-  2719,
-  2720,
-  2721,
-  2722,
-  2723,
-  2724,
-  2725,
-  2726,
-  2727,
-  2728,
-  2729,
-  2730,
-  2731,
-  2732,
-  2733,
-  2734,
-  2735,
-  2738,
-  2739,
-  2740,
-  2741,
-  2742,
-  2743,
-  2744,
-  2745,
-  2746,
-  2747,
-  2748,
-  2749,
-  2750,
-  2751,
-  2752,
-  2753,
-  2754,
-  2755,
-  2756,
-  2757,
-  2758,
-  2935,
-  2936,
-  2937,
-  2938,
-  2939,
-  2940,
-  2941,
-  2953,
-  2963,
-  3006,
-  3007,
-  3008,
-  3009,
-  3010,
-  3011,
-  3012,
-  3013,
-  3014,
-  3015,
-  3016,
-  3017,
-  3018,
-  3019,
-  3020,
-  3021,
-  3022,
-  3023,
-  3024,
-  3025,
-  3026,
-  3027,
-  3028,
-  3029,
-  3030,
-  3034,
-  3035,
-  3038,
-  3039,
-  3040,
-  3041,
-  3042,
-  3043,
-  3044,
-  3045,
-  3046,
-  3047,
-  3048,
-  3049,
-  3050,
-  3051,
-  3058,
-  3059,
-  3068,
-  3114,
-  3115,
-  3116,
-  3117,
-  3118,
-  3120,
-  3126,
-  3127,
-  3128,
-  3129,
-  3130,
-  3131,
-  3132,
-  3133,
-  3134,
-  3135,
-  3136,
-  3137,
-  3138,
-  3139,
-  3140,
-  3146,
-  3147,
-  3150,
-  3151,
-  3152,
-  3300,
-  3301,
-  3328,
-  3329,
-  3330,
-  3331,
-  3332,
-  3333,
-  3334,
-  3335,
-  3346,
-  3350,
-  3351,
-  3352,
-  3366,
-  3386,
-  3387,
-  3388,
-  3389,
-  3390,
-  3396,
-  3397,
-  3398,
-  3399,
-  3407,
-  3414,
-  3416,
-  3764,
-  3788,
-  3789,
-  3790,
-  3791,
-  3793,
-  3795,
-  3796,
-  3819,
-  3821,
-  3823,
-  3824,
-  3833,
-  3834,
-  3835,
-  3836,
-  3837,
-  3838,
-  3839,
-  3840,
-  3841,
-  3842,
-  3843,
-  3844,
-  3845,
-  3846,
-  3847,
-  3848,
-  3849,
-  3850,
-  3851,
-  3852,
-  3854,
-  3873,
-  3874,
-  3875,
-  3876,
-  3877,
-  3878,
-  3879,
-  3880,
-  3881,
-  3882,
-  3883,
-  3884,
-  3885,
-  3888,
-  3889,
-  3906,
-  3907,
-  3908,
-  3909,
-  3910,
-  3911,
-  4001,
-  4002,
-  4003,
-  4004,
-  4005,
-  4006,
-  4007,
-  4008,
-  4009,
-  4010,
-  4011,
-  4012,
-  4013,
-  4014,
-  4015,
-  4016,
-  4017,
-  4018,
-  4019,
-  4020,
-  4021,
-  4022,
-  4023,
-  4024,
-  4025,
-  4026,
-  4027,
-  4028,
-  4029,
-  4030,
-  4031,
-  4032,
-  4033,
-  4034,
-  4035,
-  4036,
-  4037,
-  4038,
-  4040,
-  4041,
-  4042,
-  4043,
-  4044,
-  4045,
-  4046,
-  4047,
-  4052,
-  4053,
-  4054,
-  4055,
-  4074,
-  4075,
-  4080,
-  4081,
-  4120,
-  4121,
-  4122,
-  4123,
-  4124,
-  4125,
-  4126,
-  4127,
-  4128,
-  4129,
-  4130,
-  4131,
-  4132,
-  4133,
-  4134,
-  4135,
-  4136,
-  4137,
-  4138,
-  4139,
-  4140,
-  4141,
-  4142,
-  4143,
-  4144,
-  4145,
-  4146,
-  4147,
-  4148,
-  4149,
-  4150,
-  4151,
-  4152,
-  4153,
-  4154,
-  4155,
-  4156,
-  4157,
-  4158,
-  4159,
-  4160,
-  4161,
-  4162,
-  4163,
-  4164,
-  4165,
-  4166,
-  4167,
-  4168,
-  4169,
-  4170,
-  4171,
-  4172,
-  4173,
-  4174,
-  4175,
-  4176,
-  4178,
-  4179,
-  4180,
-  4181,
-  4182,
-  4183,
-  4184,
-  4185,
-  4188,
-  4189,
-  4190,
-  4191,
-  4192,
-  4193,
-  4194,
-  4195,
-  4196,
-  4197,
-  4198,
-  4199,
-  4200,
-  4201,
-  4202,
-  4203,
-  4204,
-  4205,
-  4206,
-  4207,
-  4208,
-  4209,
-  4210,
-  4211,
-  4212,
-  4213,
-  4214,
-  4215,
-  4216,
-  4218,
-  4219,
-  4220,
-  4221,
-  4222,
-  4223,
-  4224,
-  4225,
-  4226,
-  4227,
-  4228,
-  4229,
-  4230,
-  4231,
-  4232,
-  4233,
-  4234,
-  4235,
-  4236,
-  4237,
-  4238,
-  4239,
-  4240,
-  4241,
-  4242,
-  4243,
-  4244,
-  4245,
-  4246,
-  4247,
-  4248,
-  4249,
-  4250,
-  4251,
-  4252,
-  4253,
-  4254,
-  4255,
-  4256,
-  4257,
-  4259,
-  4260,
-  4261,
-  4262,
-  4263,
-  4264,
-  4265,
-  4266,
-  4267,
-  4268,
-  4269,
-  4270,
-  4271,
-  4272,
-  4273,
-  4274,
-  4275,
-  4276,
-  4277,
-  4278,
-  4279,
-  4280,
-  4281,
-  4282,
-  4283,
-  4284,
-  4285,
-  4286,
-  4287,
-  4288,
-  4289,
-  4291,
-  4292,
-  4293,
-  4294,
-  4295,
-  4296,
-  4297,
-  4298,
-  4299,
-  4300,
-  4301,
-  4302,
-  4303,
-  4304,
-  4306,
-  4307,
-  4308,
-  4309,
-  4310,
-  4311,
-  4312,
-  4313,
-  4314,
-  4315,
-  4316,
-  4317,
-  4318,
-  4319,
-  4322,
-  4324,
-  4327,
-  4329,
-  4339,
-  4341,
-  4343,
-  4345,
-  4347,
-  4349,
-  4351,
-  4353,
-  4355,
-  4357,
-  4359,
-  4361,
-  4363,
-  4365,
-  4367,
-  4369,
-  4371,
-  4373,
-  4375,
-  4377,
-  4379,
-  4381,
-  4383,
-  4386,
-  4388,
-  4417,
-  4434,
-  4463,
-  4466,
-  4469,
-  4470,
-  4472,
-  4475,
-  4480,
-  4482,
-  4483,
-  4490,
-  4491,
-  4492,
-  4493,
-  4494,
-  4495,
-  4496,
-  4497,
-  4498,
-  4499,
-  4500,
-  4501,
-  4502,
-  4503,
-  4504,
-  4505,
-  4506,
-  4507,
-  4508,
-  4509,
-  4510,
-  4511,
-  4512,
-  4513,
-  4514,
-  4515,
-  4516,
-  4517,
-  4518,
-  4519,
-  4520,
-  4521,
-  4522,
-  4523,
-  4524,
-  4525,
-  4526,
-  4527,
-  4528,
-  4529,
-  4530,
-  4531,
-  4532,
-  4533,
-  4534,
-  4535,
-  4536,
-  4537,
-  4538,
-  4539,
-  4540,
-  4541,
-  4542,
-  4543,
-  4544,
-  4545,
-  4546,
-  4547,
-  4548,
-  4549,
-  4550,
-  4551,
-  4552,
-  4553,
-  4554,
-  4555,
-  4557,
-  4558,
-  4568,
-  4569,
-  4570,
-  4571,
-  4572,
-  4573,
-  4574,
-  4575,
-  4576,
-  4577,
-  4578,
-  4579,
-  4580,
-  4581,
-  4582,
-  4583,
-  4584,
-  4585,
-  4586,
-  4587,
-  4588,
-  4589,
-  4600,
-  4601,
-  4602,
-  4603,
-  4604,
-  4605,
-  4606,
-  4607,
-  4608,
-  4609,
-  4610,
-  4611,
-  4612,
-  4613,
-  4614,
-  4615,
-  4616,
-  4617,
-  4618,
-  4619,
-  4620,
-  4621,
-  4622,
-  4623,
-  4624,
-  4625,
-  4626,
-  4627,
-  4628,
-  4629,
-  4630,
-  4631,
-  4632,
-  4633,
-  4634,
-  4635,
-  4636,
-  4637,
-  4638,
-  4639,
-  4640,
-  4641,
-  4642,
-  4643,
-  4644,
-  4645,
-  4646,
-  4652,
-  4653,
-  4654,
-  4655,
-  4656,
-  4657,
-  4658,
-  4659,
-  4660,
-  4661,
-  4662,
-  4663,
-  4664,
-  4665,
-  4666,
-  4667,
-  4668,
-  4669,
-  4670,
-  4671,
-  4672,
-  4673,
-  4674,
-  4675,
-  4676,
-  4677,
-  4678,
-  4679,
-  4680,
-  4681,
-  4682,
-  4683,
-  4684,
-  4685,
-  4686,
-  4687,
-  4688,
-  4689,
-  4690,
-  4691,
-  4692,
-  4693,
-  4694,
-  4695,
-  4696,
-  4697,
-  4698,
-  4699,
-  4700,
-  4701,
-  4702,
-  4703,
-  4704,
-  4705,
-  4706,
-  4707,
-  4708,
-  4709,
-  4710,
-  4711,
-  4712,
-  4713,
-  4714,
-  4715,
-  4716,
-  4717,
-  4718,
-  4719,
-  4720,
-  4721,
-  4722,
-  4723,
-  4724,
-  4725,
-  4726,
-  4727,
-  4728,
-  4729,
-  4730,
-  4731,
-  4732,
-  4733,
-  4734,
-  4735,
-  4736,
-  4737,
-  4738,
-  4739,
-  4740,
-  4741,
-  4742,
-  4743,
-  4744,
-  4745,
-  4746,
-  4747,
-  4748,
-  4749,
-  4750,
-  4751,
-  4752,
-  4753,
-  4754,
-  4755,
-  4756,
-  4757,
-  4758,
-  4759,
-  4760,
-  4761,
-  4762,
-  4763,
-  4764,
-  4765,
-  4766,
-  4767,
-  4768,
-  4769,
-  4770,
-  4771,
-  4772,
-  4773,
-  4774,
-  4775,
-  4776,
-  4777,
-  4778,
-  4779,
-  4780,
-  4781,
-  4782,
-  4783,
-  4784,
-  4785,
-  4786,
-  4787,
-  4788,
-  4789,
-  4790,
-  4791,
-  4792,
-  4793,
-  4794,
-  4795,
-  4796,
-  4797,
-  4798,
-  4799,
-  4800,
-  4801,
-  4802,
-  4803,
-  4804,
-  4805,
-  4806,
-  4807,
-  4808,
-  4809,
-  4810,
-  4811,
-  4812,
-  4813,
-  4814,
-  4815,
-  4816,
-  4817,
-  4818,
-  4819,
-  4820,
-  4821,
-  4822,
-  4823,
-  4824,
-  4839,
-  4855,
-  4856,
-  4857,
-  4858,
-  4859,
-  4860,
-  4861,
-  4862,
-  4863,
-  4864,
-  4865,
-  4866,
-  4867,
-  4868,
-  4869,
-  4870,
-  4871,
-  4872,
-  4873,
-  4874,
-  4875,
-  4876,
-  4877,
-  4878,
-  4879,
-  4880,
-  4883,
-  4885,
-  4887,
-  4889,
-  4891,
-  4893,
-  4895,
-  4898,
-  4900,
-  4901,
-  4902,
-  4903,
-  4904,
-  4907,
-  4909,
-  4921,
-  4923,
-  4925,
-  4927,
-  4929,
-  4931,
-  4933,
-  4935,
-  4937,
-  4939,
-  4941,
-  4943,
-  4945,
-  4947,
-  4949,
-  4951,
-  4953,
-  4955,
-  4957,
-  4959,
-  4961,
-  4963,
-  4965,
-  4967,
-  4969,
-  4971,
-  4973,
-  4975,
-  4977,
-  4979,
-  4981,
-  4983,
-  4985,
-  4987,
-  4989,
-  4991,
-  4993,
-  4995,
-  4997,
-  4999,
-  5012,
-  5013,
-  5017,
-  5048,
-  5105,
-  5106,
-  5107,
-  5108,
-  5109,
-  5110,
-  5111,
-  5112,
-  5113,
-  5114,
-  5115,
-  5116,
-  5117,
-  5118,
-  5119,
-  5120,
-  5121,
-  5122,
-  5123,
-  5124,
-  5125,
-  5126,
-  5127,
-  5128,
-  5129,
-  5130,
-  5132,
-  5167,
-  5168,
-  5169,
-  5170,
-  5171,
-  5172,
-  5173,
-  5174,
-  5175,
-  5176,
-  5177,
-  5178,
-  5179,
-  5180,
-  5181,
-  5182,
-  5183,
-  5184,
-  5185,
-  5186,
-  5187,
-  5188,
-  5224,
-  5228,
-  5229,
-  5233,
-  5245,
-  5246,
-  5251,
-  5252,
-  5253,
-  5254,
-  5255,
-  5256,
-  5257,
-  5258,
-  5259,
-  5263,
-  5264,
-  5269,
-  5270,
-  5271,
-  5272,
-  5273,
-  5274,
-  5275,
-  5801,
-  5802,
-  5803,
-  5804,
-  5808,
-  5809,
-  5810,
-  5811,
-  5812,
-  5813,
-  5814,
-  5815,
-  5816,
-  20004,
-  20005,
-  20006,
-  20007,
-  20008,
-  20009,
-  20010,
-  20011,
-  20012,
-  20013,
-  20014,
-  20015,
-  20016,
-  20017,
-  20018,
-  20019,
-  20020,
-  20021,
-  20022,
-  20023,
-  20024,
-  20025,
-  20026,
-  20027,
-  20028,
-  20029,
-  20030,
-  20031,
-  20032,
-  20064,
-  20065,
-  20066,
-  20067,
-  20068,
-  20069,
-  20070,
-  20071,
-  20072,
-  20073,
-  20074,
-  20075,
-  20076,
-  20077,
-  20078,
-  20079,
-  20080,
-  20081,
-  20082,
-  20083,
-  20084,
-  20085,
-  20086,
-  20087,
-  20088,
-  20089,
-  20090,
-  20091,
-  20092,
-  21413,
-  21414,
-  21415,
-  21416,
-  21417,
-  21418,
-  21419,
-  21420,
-  21421,
-  21422,
-  21423,
-  21453,
-  21454,
-  21455,
-  21456,
-  21457,
-  21458,
-  21459,
-  21460,
-  21461,
-  21462,
-  21463,
-  21473,
-  21474,
-  21475,
-  21476,
-  21477,
-  21478,
-  21479,
-  21480,
-  21481,
-  21482,
-  21483,
-  21896,
-  21897,
-  21898,
-  21899,
-  22171,
-  22172,
-  22173,
-  22174,
-  22175,
-  22176,
-  22177,
-  22181,
-  22182,
-  22183,
-  22184,
-  22185,
-  22186,
-  22187,
-  22191,
-  22192,
-  22193,
-  22194,
-  22195,
-  22196,
-  22197,
-  25884,
-  27205,
-  27206,
-  27207,
-  27208,
-  27209,
-  27210,
-  27211,
-  27212,
-  27213,
-  27214,
-  27215,
-  27216,
-  27217,
-  27218,
-  27219,
-  27220,
-  27221,
-  27222,
-  27223,
-  27224,
-  27225,
-  27226,
-  27227,
-  27228,
-  27229,
-  27230,
-  27231,
-  27232,
-  27391,
-  27392,
-  27393,
-  27394,
-  27395,
-  27396,
-  27397,
-  27398,
-  27492,
-  28402,
-  28403,
-  28404,
-  28405,
-  28406,
-  28407,
-  28408,
-  28409,
-  28410,
-  28411,
-  28412,
-  28413,
-  28414,
-  28415,
-  28416,
-  28417,
-  28418,
-  28419,
-  28420,
-  28421,
-  28422,
-  28423,
-  28424,
-  28425,
-  28426,
-  28427,
-  28428,
-  28429,
-  28430,
-  28431,
-  28432,
-  28462,
-  28463,
-  28464,
-  28465,
-  28466,
-  28467,
-  28468,
-  28469,
-  28470,
-  28471,
-  28472,
-  28473,
-  28474,
-  28475,
-  28476,
-  28477,
-  28478,
-  28479,
-  28480,
-  28481,
-  28482,
-  28483,
-  28484,
-  28485,
-  28486,
-  28487,
-  28488,
-  28489,
-  28490,
-  28491,
-  28492,
-  29701,
-  29702,
-  30161,
-  30162,
-  30163,
-  30164,
-  30165,
-  30166,
-  30167,
-  30168,
-  30169,
-  30170,
-  30171,
-  30172,
-  30173,
-  30174,
-  30175,
-  30176,
-  30177,
-  30178,
-  30179,
-  30800,
-  31251,
-  31252,
-  31253,
-  31254,
-  31255,
-  31256,
-  31257,
-  31258,
-  31259,
-  31275,
-  31276,
-  31277,
-  31278,
-  31279,
-  31281,
-  31282,
-  31283,
-  31284,
-  31285,
-  31286,
-  31287,
-  31288,
-  31289,
-  31290,
-  31700,
-};
- 
-#define AXIS_ORIENTATION_TABLE_SIZE 1703
- 
+
+  static unsigned char axisOrientationEpsgCodes[] = {
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 1 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 1 << 5 | 1 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 1 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 1 << 6 | 1 << 5 | 0 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 1 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 0 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 1 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 1 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 0 << 5 | 0 << 4 | 1 << 3 | 1 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 1 << 3 | 1 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 1 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 0 << 5 | 0 << 4 | 1 << 3 | 1 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 1 << 5 | 1 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 1 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 1 << 0,
+    0 << 7 | 1 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 1 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 1 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 1 << 4 | 1 << 3 | 0 << 2 | 1 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 0 << 6 | 1 << 5 | 0 << 4 | 1 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 1 << 6 | 0 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 1 << 3 | 1 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 0 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 0 << 3 | 0 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 0 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 0 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 0 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 0 << 5 | 1 << 4 | 0 << 3 | 1 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 1 << 1 | 0 << 0,
+    1 << 7 | 0 << 6 | 1 << 5 | 0 << 4 | 1 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 0 << 6 | 1 << 5 | 0 << 4 | 1 << 3 | 0 << 2 | 1 << 1 | 0 << 0,
+    1 << 7 | 0 << 6 | 1 << 5 | 0 << 4 | 1 << 3 | 0 << 2 | 1 << 1 | 0 << 0,
+    1 << 7 | 0 << 6 | 1 << 5 | 0 << 4 | 1 << 3 | 0 << 2 | 1 << 1 | 0 << 0,
+    1 << 7 | 0 << 6 | 1 << 5 | 0 << 4 | 1 << 3 | 0 << 2 | 1 << 1 | 0 << 0,
+    1 << 7 | 0 << 6 | 1 << 5 | 0 << 4 | 1 << 3 | 0 << 2 | 1 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 1 << 4 | 0 << 3 | 1 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 1 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 1 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 1 << 6 | 1 << 5 | 0 << 4 | 0 << 3 | 1 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 1 << 3 | 0 << 2 | 0 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 1 << 3 | 1 << 2 | 0 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 1 << 6 | 1 << 5 | 0 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 1 << 0,
+    1 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 0 << 6 | 1 << 5 | 0 << 4 | 1 << 3 | 0 << 2 | 0 << 1 | 1 << 0,
+    1 << 7 | 0 << 6 | 1 << 5 | 0 << 4 | 1 << 3 | 0 << 2 | 1 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 0 << 3 | 1 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 1 << 5 | 0 << 4 | 1 << 3 | 0 << 2 | 0 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 0 << 6 | 1 << 5 | 0 << 4 | 1 << 3 | 0 << 2 | 1 << 1 | 0 << 0,
+    1 << 7 | 0 << 6 | 1 << 5 | 0 << 4 | 1 << 3 | 0 << 2 | 1 << 1 | 0 << 0,
+    1 << 7 | 0 << 6 | 1 << 5 | 0 << 4 | 1 << 3 | 0 << 2 | 1 << 1 | 0 << 0,
+    1 << 7 | 0 << 6 | 1 << 5 | 0 << 4 | 1 << 3 | 0 << 2 | 1 << 1 | 0 << 0,
+    1 << 7 | 0 << 6 | 1 << 5 | 0 << 4 | 1 << 3 | 0 << 2 | 1 << 1 | 0 << 0,
+    1 << 7 | 0 << 6 | 1 << 5 | 0 << 4 | 1 << 3 | 0 << 2 | 1 << 1 | 0 << 0,
+    1 << 7 | 0 << 6 | 1 << 5 | 0 << 4 | 1 << 3 | 0 << 2 | 1 << 1 | 0 << 0,
+    1 << 7 | 0 << 6 | 1 << 5 | 0 << 4 | 1 << 3 | 0 << 2 | 1 << 1 | 0 << 0,
+    1 << 7 | 0 << 6 | 1 << 5 | 0 << 4 | 1 << 3 | 0 << 2 | 1 << 1 | 0 << 0,
+    1 << 7 | 0 << 6 | 1 << 5 | 0 << 4 | 1 << 3 | 0 << 2 | 1 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 1 << 5 | 1 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 1 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 1 << 4 | 0 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 1 << 5 | 1 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 1 << 1 | 0 << 0,
+    0 << 7 | 1 << 6 | 1 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 1 << 4 | 1 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 0 << 5 | 1 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 1 << 2 | 1 << 1 | 0 << 0,
+    1 << 7 | 0 << 6 | 1 << 5 | 1 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 1 << 5 | 1 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 1 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 1 << 3 | 0 << 2 | 0 << 1 | 1 << 0,
+    1 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 0 << 5 | 0 << 4 | 1 << 3 | 0 << 2 | 1 << 1 | 0 << 0,
+    1 << 7 | 0 << 6 | 0 << 5 | 1 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 1 << 2 | 1 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 1 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 1 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 1 << 0,
+    0 << 7 | 1 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 1 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 1 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 1 << 6 | 1 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    1 << 7 | 1 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 1 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 1 << 5 | 1 << 4 | 1 << 3 | 1 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 1 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0,
+    0 << 7 | 0 << 6 | 0 << 5 | 0 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0
+  };
+
 #ifdef __cplusplus
 }
 #endif
diff --git a/mapaxisorder.sh b/mapaxisorder.sh
index 0d2d6ce..e744ef0 100755
--- a/mapaxisorder.sh
+++ b/mapaxisorder.sh
@@ -2,9 +2,32 @@
 INFILE="./mapaxisorder.csv"
 OUTFILE="./mapaxisorder.h"
 
-# create array of elements from $INFILE
-unset ARRAY i
-while read -r LINE; do ARRAY[i++]=$LINE; done < $INFILE
+# define an array 8x4096 filled with 0
+unset ARRAY
+declare -a ARRAY
+for i in {0..4095}
+do
+	ARRAY[$i]="00000000"
+done
+	
+# fill array from $INFILE
+while read -r LINE
+do
+	# numeric values only
+	if [ "$LINE" -eq "$LINE" ] 2>/dev/null
+	then
+		let row=$(( $LINE / 8 ))
+		let index=$(( $LINE % 8 ))
+		unset tmp
+
+		if [ $index -gt 0 ]
+		then
+			tmp=${ARRAY[$row]:0:$(( $index ))}
+		fi
+
+		ARRAY[$row]=${tmp}1${ARRAY[$row]:$(( $index+1 ))}
+	fi
+done < $INFILE
 
 print_header ()
 {
@@ -53,28 +76,27 @@ print_comment ()
 
 print_body ()
 {
-	
 	echo '#ifdef __cplusplus'
 	echo 'extern "C" '{
 	echo '#endif'
 	echo ' '
-	echo 'static struct axisOrientationEpsgCodes_s {'
-	echo '	int	code;'
-	echo '} axisOrientationEpsgCodes[] = {'
+	echo 'static unsigned char axisOrientationEpsgCodes[] = {'
    
-	# unset first array element
-   unset ARRAY[0]
-   # traverse array and print out elements
-        let count=0
-	for x in "${ARRAY[@]}"; do
-		echo "  ${x},"
-		((count++))
+	# traverse array and print out elements
+	for i in {0..4095}
+	do
+		echo -n "        ${ARRAY[$i]:7:1} << 7 | ${ARRAY[$i]:6:1} << 6 | ${ARRAY[$i]:5:1} << 5 | ${ARRAY[$i]:4:1} << 4 | ${ARRAY[$i]:3:1} << 3 | ${ARRAY[$i]:2:1} << 2 | ${ARRAY[$i]:1:1} << 1 | ${ARRAY[$i]:0:1} << 0"
+		if [ $i -le 4094 ]
+		then
+			echo ,
+		else
+			echo
+		fi
 	done
 
 	echo '};'
-   echo ' '
-	echo '#define AXIS_ORIENTATION_TABLE_SIZE '${count}
-   echo ' '
+	echo ' '
+
 	echo '#ifdef __cplusplus'
 	echo '}'
 	echo '#endif'
@@ -85,4 +107,4 @@ print_header > ./$OUTFILE
 print_comment >> ./$OUTFILE
 print_body >> ./$OUTFILE
 
-exit 0
\ No newline at end of file
+exit 0
diff --git a/mapbits.c b/mapbits.c
index 5501ac4..7ca30ed 100644
--- a/mapbits.c
+++ b/mapbits.c
@@ -5,12 +5,12 @@
  * Purpose:  Implementation of bit array functions.
  * Author:   Steve Lime and the MapServer team.
  *
- * Notes: Derived from code placed in the public domain by Bob Stout, for more 
+ * Notes: Derived from code placed in the public domain by Bob Stout, for more
  * information see http://c.snippets.org/snip_lister.php?fname=bitarray.c.
  *
  ******************************************************************************
  * Copyright (c) 1996-2005 Regents of the University of Minnesota.
- 
+
  * Permission is hereby granted, free of charge, to any person obtaining a
  * copy of this software and associated documentation files (the "Software"),
  * to deal in the Software without restriction, including without limitation
@@ -18,7 +18,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -32,12 +32,12 @@
 
 #include "mapserver.h"
 
-MS_CVSID("$Id$")
+
 
 #include <limits.h>
 
-/* 
- * Hardcoded size of our bit array. 
+/*
+ * Hardcoded size of our bit array.
  * See function msGetNextBit for another hardcoded value.
  */
 
@@ -51,7 +51,7 @@ size_t msGetBitArraySize(int numbits)
 ms_bitarray msAllocBitArray(int numbits)
 {
   ms_bitarray array = calloc((numbits + MS_ARRAY_BIT - 1) / MS_ARRAY_BIT, MS_ARRAY_BIT);
-  
+
   return(array);
 }
 
@@ -68,7 +68,8 @@ int msGetBit(ms_bitarray array, int index)
 ** If hits end of bitmap without finding set bit, will return -1.
 **
 */
-int msGetNextBit(ms_bitarray array, int i, int size) { 
+int msGetNextBit(ms_bitarray array, int i, int size)
+{
 
   register ms_uint32 b;
 
@@ -80,36 +81,34 @@ int msGetNextBit(ms_bitarray array, int i, int size) {
       if( b & ( 1 << (i % MS_ARRAY_BIT)) ) {
         /* There is something at this bit! */
         return i;
-      }
-      else {
+      } else {
         i++;
       }
-    }
-    else {
+    } else {
       /* Nothing in this byte, move to start of next byte */
       i += MS_ARRAY_BIT - (i % MS_ARRAY_BIT);
     }
   }
-  
+
   /* Got to the last byte with no hits! */
   return -1;
 }
-  
+
 void msSetBit(ms_bitarray array, int index, int value)
 {
   array += index / MS_ARRAY_BIT;
   if (value)
     *array |= 1 << (index % MS_ARRAY_BIT);           /* set bit */
-  else    
+  else
     *array &= ~(1 << (index % MS_ARRAY_BIT));        /* clear bit */
 }
-  
+
 void msSetAllBits(ms_bitarray array, int numbits, int value)
 {
   if (value)
-      memset(array, 0xff, ((numbits + 7) / 8) ); /* set bit */
-  else    
-      memset(array, 0x0,  ((numbits + 7) / 8) ); /* clear bit */
+    memset(array, 0xff, ((numbits + 7) / 8) ); /* set bit */
+  else
+    memset(array, 0x0,  ((numbits + 7) / 8) ); /* clear bit */
 }
 
 void msFlipBit(ms_bitarray array, int index)
diff --git a/mapcairo.c b/mapcairo.c
index 8ea2d84..99e8b56 100644
--- a/mapcairo.c
+++ b/mapcairo.c
@@ -39,6 +39,15 @@
 #include <cairo/cairo-svg.h>
 #endif
 
+#ifdef USE_SVG_CAIRO
+#include <svg-cairo.h>
+#endif
+
+#ifdef USE_GDAL
+#include <cpl_string.h>
+#include <gdal.h>
+#endif
+
 # include <cairo-ft.h>
 /*
 #include <pango/pangocairo.h>
@@ -52,63 +61,67 @@
 
 typedef struct facecacheObj faceCacheObj;
 struct facecacheObj {
-    cairo_font_face_t *face;
-    FT_Face ftface;
-    char *path;
-    faceCacheObj *next;
-    cairo_user_data_key_t facekey;
+  cairo_font_face_t *face;
+  FT_Face ftface;
+  char *path;
+  faceCacheObj *next;
+  cairo_user_data_key_t facekey;
 };
 
-int freeFaceCache(faceCacheObj *fc) {
-    //printf("***\nface has %d references\n***\n",cairo_font_face_get_reference_count(fc->face));
-    cairo_font_face_destroy(fc->face);
-    free(fc->path);
-    return MS_SUCCESS;
+int freeFaceCache(faceCacheObj *fc)
+{
+  /* printf("***\nface %s has %d cairo references\n***\n",fc->path,cairo_font_face_get_reference_count(fc->face)); */
+  cairo_font_face_destroy(fc->face);
+  FT_Done_Face(fc->ftface);
+  free(fc->path);
+  return MS_SUCCESS;
 }
 
 typedef struct {
-    faceCacheObj *facecache;
-    FT_Library library;
-    /* dummy surface and context */
-    unsigned char dummydata[4];
-    cairo_surface_t *dummysurface;
-    cairo_t *dummycr;
+  faceCacheObj *facecache;
+  FT_Library library;
+  /* dummy surface and context */
+  unsigned char dummydata[4];
+  cairo_surface_t *dummysurface;
+  cairo_t *dummycr;
 } cairoCacheData;
 
-void initializeCache(void **vcache) {
-   cairoCacheData *cache = (cairoCacheData*)malloc(sizeof(cairoCacheData));
-   *vcache = cache;
-       
-    cache->facecache = NULL;
-    FT_Init_FreeType(&(cache->library));
-    /* dummy surface and context */
-    cache->dummysurface = cairo_image_surface_create_for_data(cache->dummydata, CAIRO_FORMAT_ARGB32, 1,1,4);
-    cache->dummycr = cairo_create(cache->dummysurface);
-}
-
-int cleanupCairo(void *cache) {
-    cairoCacheData *ccache = (cairoCacheData*)cache;
-    
-    if(ccache->dummycr) {
-        cairo_destroy(ccache->dummycr);
-    }
-    if(ccache->dummysurface) {
-        cairo_surface_destroy(ccache->dummysurface);
-    }
-    if(ccache->facecache) {
-        faceCacheObj *next,*cur;
-        cur = ccache->facecache;
-        do {
-            next = cur->next;
-            freeFaceCache(cur);
-            free(cur);
-            cur=next;
-        } while(cur);
-    }
-    if(ccache->library)
-        FT_Done_FreeType(ccache->library);
-    free(ccache);
-    return MS_SUCCESS;
+void initializeCache(void **vcache)
+{
+  cairoCacheData *cache = (cairoCacheData*)malloc(sizeof(cairoCacheData));
+  *vcache = cache;
+
+  cache->facecache = NULL;
+  FT_Init_FreeType(&(cache->library));
+  /* dummy surface and context */
+  cache->dummysurface = cairo_image_surface_create_for_data(cache->dummydata, CAIRO_FORMAT_ARGB32, 1,1,4);
+  cache->dummycr = cairo_create(cache->dummysurface);
+}
+
+int cleanupCairo(void *cache)
+{
+  cairoCacheData *ccache = (cairoCacheData*)cache;
+
+  if(ccache->dummycr) {
+    cairo_destroy(ccache->dummycr);
+  }
+  if(ccache->dummysurface) {
+    cairo_surface_destroy(ccache->dummysurface);
+  }
+  if(ccache->facecache) {
+    faceCacheObj *next,*cur;
+    cur = ccache->facecache;
+    do {
+      next = cur->next;
+      freeFaceCache(cur);
+      free(cur);
+      cur=next;
+    } while(cur);
+  }
+  if(ccache->library)
+    FT_Done_FreeType(ccache->library);
+  free(ccache);
+  return MS_SUCCESS;
 }
 
 
@@ -116,759 +129,1173 @@ int cleanupCairo(void *cache) {
 
 
 typedef struct {
-    cairo_surface_t *surface;
-    cairo_t *cr;
-    bufferObj *outputStream;
-    int use_alpha;
+  cairo_surface_t *surface;
+  cairo_t *cr;
+  bufferObj *outputStream;
+  int use_alpha;
 } cairo_renderer;
 
 
 #define CAIRO_RENDERER(im) ((cairo_renderer*)(im->img.plugin))
 
 
-int freeImageCairo(imageObj *img) {
-    cairo_renderer *r = CAIRO_RENDERER(img);
-    if(r) {
-        cairo_destroy(r->cr);
-        cairo_surface_finish(r->surface);
-        cairo_surface_destroy(r->surface);
-        if(r->outputStream) {
-            msBufferFree(r->outputStream);
-            free(r->outputStream);
-        }
-        free(r);
+int freeImageCairo(imageObj *img)
+{
+  cairo_renderer *r = CAIRO_RENDERER(img);
+  if(r) {
+    cairo_destroy(r->cr);
+    cairo_surface_finish(r->surface);
+    cairo_surface_destroy(r->surface);
+    if(r->outputStream) {
+      msBufferFree(r->outputStream);
+      free(r->outputStream);
     }
-    return MS_SUCCESS;
+    free(r);
+  }
+  return MS_SUCCESS;
 }
 
 
-faceCacheObj *getFontFace(cairoCacheData *cache, char *font) {
-    faceCacheObj *newface = NULL;
-    faceCacheObj *cur=cache->facecache;
-    while(cur) {
-        if(!strcmp(cur->path,font))
-            return cur;
-        cur = cur->next;
-    }
-    newface = malloc(sizeof(faceCacheObj));
-    
-    if(FT_New_Face(cache->library, font, 0, &(newface->ftface))) {
-        msSetError(MS_RENDERERERR,"Freetype failed to open font %s","getFontFace()",font);
-        free(newface);
-        return NULL;
-    }
-    newface->next = cache->facecache;
-    cache->facecache = newface;
-    newface->face = cairo_ft_font_face_create_for_ft_face(newface->ftface, 0);
-
-    cairo_font_face_set_user_data (newface->face, &newface->facekey,
-            &(newface->ftface), (cairo_destroy_func_t) FT_Done_Face);
-
-    newface->path = msStrdup(font);
-    return newface;
+faceCacheObj *getFontFace(cairoCacheData *cache, const char *font)
+{
+  faceCacheObj *newface = NULL;
+  faceCacheObj *cur=cache->facecache;
+  while(cur) {
+    if(!strcmp(cur->path,font))
+      return cur;
+    cur = cur->next;
+  }
+  newface = malloc(sizeof(faceCacheObj));
+
+  if(FT_New_Face(cache->library, font, 0, &(newface->ftface))) {
+    msSetError(MS_RENDERERERR,"Freetype failed to open font %s","getFontFace()",font);
+    free(newface);
+    return NULL;
+  }
+  newface->next = cache->facecache;
+  cache->facecache = newface;
+  newface->face = cairo_ft_font_face_create_for_ft_face(newface->ftface, 0);
+
+  cairo_font_face_set_user_data (newface->face, &newface->facekey,
+                                 &(newface->ftface), (cairo_destroy_func_t) NULL); // we call FT_Done_Face ourselves in freeFaceCache
+
+  newface->path = msStrdup(font);
+  return newface;
 }
 
 #define msCairoSetSourceColor(cr, c) cairo_set_source_rgba((cr),(c)->red/255.0,(c)->green/255.0,(c)->blue/255.0,(c)->alpha/255.0);
 
-int renderLineCairo(imageObj *img, shapeObj *p, strokeStyleObj *stroke) {
-    int i,j;
-    cairo_renderer *r = CAIRO_RENDERER(img);
-    assert(stroke->color);
-    cairo_new_path(r->cr);
-    msCairoSetSourceColor(r->cr,stroke->color);
-    for(i=0;i<p->numlines;i++) {
-        lineObj *l = &(p->line[i]);
-        cairo_move_to(r->cr,l->point[0].x,l->point[0].y);
-        for(j=1;j<l->numpoints;j++) {
-            cairo_line_to(r->cr,l->point[j].x,l->point[j].y);
-        }
-    }
-    if(stroke->patternlength>0) {
-        cairo_set_dash(r->cr,stroke->pattern,stroke->patternlength,0);
-    }
-    switch(stroke->linecap) {
-        case MS_CJC_BUTT:
-            cairo_set_line_cap(r->cr,CAIRO_LINE_CAP_BUTT);
-            break;
-        case MS_CJC_SQUARE:
-            cairo_set_line_cap(r->cr,CAIRO_LINE_CAP_SQUARE);
-            break;
-        case MS_CJC_ROUND:
-        case MS_CJC_NONE:
-        default:
-            cairo_set_line_cap(r->cr,CAIRO_LINE_CAP_ROUND);
+int renderLineCairo(imageObj *img, shapeObj *p, strokeStyleObj *stroke)
+{
+  int i,j;
+  cairo_renderer *r = CAIRO_RENDERER(img);
+  assert(stroke->color);
+  cairo_new_path(r->cr);
+  msCairoSetSourceColor(r->cr,stroke->color);
+  for(i=0; i<p->numlines; i++) {
+    lineObj *l = &(p->line[i]);
+    cairo_move_to(r->cr,l->point[0].x,l->point[0].y);
+    for(j=1; j<l->numpoints; j++) {
+      cairo_line_to(r->cr,l->point[j].x,l->point[j].y);
     }
-    cairo_set_line_width (r->cr, stroke->width);
-    cairo_stroke (r->cr);
-    if(stroke->patternlength>0) {
-        cairo_set_dash(r->cr,stroke->pattern,0,0);
-    }
-    return MS_SUCCESS;
+  }
+  if(stroke->patternlength>0) {
+    cairo_set_dash(r->cr,stroke->pattern,stroke->patternlength,-stroke->patternoffset);
+  }
+  switch(stroke->linecap) {
+    case MS_CJC_BUTT:
+      cairo_set_line_cap(r->cr,CAIRO_LINE_CAP_BUTT);
+      break;
+    case MS_CJC_SQUARE:
+      cairo_set_line_cap(r->cr,CAIRO_LINE_CAP_SQUARE);
+      break;
+    case MS_CJC_ROUND:
+    case MS_CJC_NONE:
+    default:
+      cairo_set_line_cap(r->cr,CAIRO_LINE_CAP_ROUND);
+  }
+  cairo_set_line_width (r->cr, stroke->width);
+  cairo_stroke (r->cr);
+  if(stroke->patternlength>0) {
+    cairo_set_dash(r->cr,stroke->pattern,0,0);
+  }
+  return MS_SUCCESS;
 }
 
-int renderPolygonCairo(imageObj *img, shapeObj *p, colorObj *c) {
-    cairo_renderer *r = CAIRO_RENDERER(img);
-    int i,j;
-    cairo_new_path(r->cr);
-    cairo_set_fill_rule(r->cr,CAIRO_FILL_RULE_EVEN_ODD);
-    msCairoSetSourceColor(r->cr,c);
-    for(i=0;i<p->numlines;i++) {
-        lineObj *l = &(p->line[i]);
-        cairo_move_to(r->cr,l->point[0].x,l->point[0].y);
-        for(j=1;j<l->numpoints;j++) {
-            cairo_line_to(r->cr,l->point[j].x,l->point[j].y);
-        }
-        cairo_close_path(r->cr);
+int renderPolygonCairo(imageObj *img, shapeObj *p, colorObj *c)
+{
+  cairo_renderer *r = CAIRO_RENDERER(img);
+  int i,j;
+  cairo_new_path(r->cr);
+  cairo_set_fill_rule(r->cr,CAIRO_FILL_RULE_EVEN_ODD);
+  msCairoSetSourceColor(r->cr,c);
+  for(i=0; i<p->numlines; i++) {
+    lineObj *l = &(p->line[i]);
+    cairo_move_to(r->cr,l->point[0].x,l->point[0].y);
+    for(j=1; j<l->numpoints; j++) {
+      cairo_line_to(r->cr,l->point[j].x,l->point[j].y);
     }
-    cairo_fill(r->cr);
-    return MS_SUCCESS;
+    cairo_close_path(r->cr);
+  }
+  cairo_fill(r->cr);
+  return MS_SUCCESS;
 }
 
-int renderPolygonTiledCairo(imageObj *img, shapeObj *p,  imageObj *tile) {
-    int i,j;
-    cairo_renderer *r = CAIRO_RENDERER(img);
-    cairo_renderer *tileRenderer = CAIRO_RENDERER(tile);
-    cairo_pattern_t *pattern = cairo_pattern_create_for_surface(tileRenderer->surface);
-    cairo_pattern_set_extend(pattern, CAIRO_EXTEND_REPEAT);
-    
-    cairo_set_source(r->cr, pattern);
-    for (i = 0; i < p->numlines; i++) {
-      lineObj *l = &(p->line[i]);
-      cairo_move_to(r->cr, l->point[0].x, l->point[0].y);
-      for (j = 1; j < l->numpoints; j++) {
-        cairo_line_to(r->cr, l->point[j].x, l->point[j].y);
-      }
-      //cairo_close_path(r->cr);
+int renderPolygonTiledCairo(imageObj *img, shapeObj *p,  imageObj *tile)
+{
+  int i,j;
+  cairo_renderer *r = CAIRO_RENDERER(img);
+  cairo_renderer *tileRenderer = CAIRO_RENDERER(tile);
+  cairo_pattern_t *pattern = cairo_pattern_create_for_surface(tileRenderer->surface);
+  cairo_pattern_set_extend(pattern, CAIRO_EXTEND_REPEAT);
+
+  cairo_set_source(r->cr, pattern);
+  for (i = 0; i < p->numlines; i++) {
+    lineObj *l = &(p->line[i]);
+    cairo_move_to(r->cr, l->point[0].x, l->point[0].y);
+    for (j = 1; j < l->numpoints; j++) {
+      cairo_line_to(r->cr, l->point[j].x, l->point[j].y);
     }
-    cairo_fill(r->cr);
-    cairo_pattern_destroy(pattern);
-    return MS_SUCCESS;
+    /* cairo_close_path(r->cr); */
+  }
+  cairo_fill(r->cr);
+  cairo_pattern_destroy(pattern);
+  return MS_SUCCESS;
 }
 
-cairo_surface_t *createSurfaceFromBuffer(rasterBufferObj *b) {
-    assert(b->type == MS_BUFFER_BYTE_RGBA);
-    return cairo_image_surface_create_for_data (b->data.rgba.pixels,
-                                                CAIRO_FORMAT_ARGB32,
-                                                b->width,
-                                                b->height,
-                                                b->data.rgba.row_step);
+cairo_surface_t *createSurfaceFromBuffer(rasterBufferObj *b)
+{
+  assert(b->type == MS_BUFFER_BYTE_RGBA);
+  return cairo_image_surface_create_for_data (b->data.rgba.pixels,
+         CAIRO_FORMAT_ARGB32,
+         b->width,
+         b->height,
+         b->data.rgba.row_step);
 }
 
 
 int renderPixmapSymbolCairo(imageObj *img, double x, double y,symbolObj *symbol,
-                            symbolStyleObj *style) {
-   cairo_renderer *r = CAIRO_RENDERER(img);
-   cairo_surface_t *im;
-   rasterBufferObj *b = symbol->pixmap_buffer;
-   assert(b);
-   if(!symbol->renderer_cache) {
-      symbol->renderer_cache = (void*)createSurfaceFromBuffer(b);
-   }
-   assert(symbol->renderer_cache);
-   im=(cairo_surface_t*)symbol->renderer_cache;
-   cairo_save(r->cr);
-   if(style->rotation != 0 || style-> scale != 1) {
-      cairo_translate (r->cr, x,y);
-      cairo_rotate (r->cr, -style->rotation);
-      cairo_scale  (r->cr, style->scale,style->scale);
-      cairo_translate (r->cr, -0.5*b->width, -0.5*b->height);
-   } else {
-       cairo_translate (r->cr, MS_NINT(x-0.5*b->width),MS_NINT(y-0.5*b->height));
-   }
-   cairo_set_source_surface (r->cr, im, 0, 0);
-   cairo_paint (r->cr);
-   cairo_restore(r->cr);
-   return MS_SUCCESS;
+                            symbolStyleObj *style)
+{
+  cairo_renderer *r = CAIRO_RENDERER(img);
+  cairo_surface_t *im;
+  rasterBufferObj *b = symbol->pixmap_buffer;
+  assert(b);
+  if(!symbol->renderer_cache) {
+    symbol->renderer_cache = (void*)createSurfaceFromBuffer(b);
+  }
+  assert(symbol->renderer_cache);
+  im=(cairo_surface_t*)symbol->renderer_cache;
+  cairo_save(r->cr);
+  if(style->rotation != 0 || style->scale != 1) {
+    cairo_translate (r->cr, x,y);
+    cairo_rotate (r->cr, -style->rotation);
+    cairo_scale  (r->cr, style->scale,style->scale);
+    cairo_translate (r->cr, -0.5*b->width, -0.5*b->height);
+  } else {
+    cairo_translate (r->cr, MS_NINT(x-0.5*b->width),MS_NINT(y-0.5*b->height));
+  }
+  cairo_set_source_surface (r->cr, im, 0, 0);
+  cairo_paint (r->cr);
+  cairo_restore(r->cr);
+  return MS_SUCCESS;
 }
 
 int renderVectorSymbolCairo(imageObj *img, double x, double y, symbolObj *symbol,
-                            symbolStyleObj *style) {
-    cairo_renderer *r = CAIRO_RENDERER(img);
-    double ox=symbol->sizex*0.5,oy=symbol->sizey*0.5;
-    int is_new = 1,i;
-    cairo_new_path(r->cr);
-    cairo_save(r->cr);
-    cairo_translate(r->cr,x,y);
-    cairo_scale(r->cr,style->scale,style->scale);
-    cairo_rotate(r->cr,-style->rotation);
-    cairo_translate(r->cr,-ox,-oy);
-    for (i = 0; i < symbol->numpoints; i++) {
-        if ((symbol->points[i].x == -99) && (symbol->points[i].y == -99)) { // (PENUP)
-            is_new = 1;
-        } else {
-            if (is_new) {
-                cairo_move_to(r->cr,symbol->points[i].x,symbol->points[i].y);
-                is_new = 0;
-            } else {
-                cairo_line_to(r->cr,symbol->points[i].x,symbol->points[i].y);
-            }
-        }
-    }
-    cairo_restore(r->cr);
-    if(style->color) {
-        msCairoSetSourceColor(r->cr,style->color);
-        cairo_fill_preserve(r->cr);
-    }
-    if(style->outlinewidth>0) {
-        msCairoSetSourceColor(r->cr,style->outlinecolor);
-        cairo_set_line_width (r->cr, style->outlinewidth);
-        cairo_stroke_preserve(r->cr);
+                            symbolStyleObj *style)
+{
+  cairo_renderer *r = CAIRO_RENDERER(img);
+  double ox=symbol->sizex*0.5,oy=symbol->sizey*0.5;
+  int is_new = 1,i;
+  cairo_new_path(r->cr);
+  cairo_save(r->cr);
+  cairo_translate(r->cr,x,y);
+  cairo_scale(r->cr,style->scale,style->scale);
+  cairo_rotate(r->cr,-style->rotation);
+  cairo_translate(r->cr,-ox,-oy);
+  for (i = 0; i < symbol->numpoints; i++) {
+    if ((symbol->points[i].x == -99) && (symbol->points[i].y == -99)) { /* (PENUP) */
+      is_new = 1;
+    } else {
+      if (is_new) {
+        cairo_move_to(r->cr,symbol->points[i].x,symbol->points[i].y);
+        is_new = 0;
+      } else {
+        cairo_line_to(r->cr,symbol->points[i].x,symbol->points[i].y);
+      }
     }
-    cairo_new_path(r->cr);
-    return MS_SUCCESS;
+  }
+  cairo_restore(r->cr);
+  if(style->color) {
+    msCairoSetSourceColor(r->cr,style->color);
+    cairo_fill_preserve(r->cr);
+  }
+  if(style->outlinewidth>0) {
+    msCairoSetSourceColor(r->cr,style->outlinecolor);
+    cairo_set_line_width (r->cr, style->outlinewidth);
+    cairo_stroke_preserve(r->cr);
+  }
+  cairo_new_path(r->cr);
+  return MS_SUCCESS;
+}
+
+#ifdef USE_SVG_CAIRO
+struct svg_symbol_cache {
+  rasterBufferObj pixmap_buffer;
+  svg_cairo_t *svgc;
+  double scale,rotation;
+} ;
+#endif
+
+int renderSVGSymbolCairo(imageObj *img, double x, double y, symbolObj *symbol,
+                         symbolStyleObj *style)
+{
+#ifdef USE_SVG_CAIRO
+  cairo_renderer *r = CAIRO_RENDERER(img);
+  //double ox=symbol->sizex*0.5,oy=symbol->sizey*0.5;
+
+  svg_cairo_status_t status;
+  struct svg_symbol_cache *cache;
+
+  msPreloadSVGSymbol(symbol);
+  assert(symbol->renderer_cache);
+  cache = symbol->renderer_cache;
+
+  cairo_save(r->cr);
+  cairo_translate(r->cr,x,y);
+  cairo_scale(r->cr,style->scale,style->scale);
+
+  if (style->rotation != 0) {
+    cairo_rotate(r->cr, -style->rotation);
+    cairo_translate (r->cr, -(int)(symbol->sizex/2), -(int)(symbol->sizey/2));
+  } else
+    cairo_translate (r->cr, -(int)(symbol->sizex/2), -(int)(symbol->sizey/2));
+
+  status = svg_cairo_render(cache->svgc, r->cr);
+  cairo_restore(r->cr);
+  return MS_SUCCESS;
+
+#else
+  msSetError(MS_MISCERR, "SVG Symbols requested but is not built with libsvgcairo",
+             "renderSVGSymbolCairo()");
+  return MS_FAILURE;
+#endif
 }
 
 int renderTruetypeSymbolCairo(imageObj *img, double x, double y, symbolObj *symbol,
-                              symbolStyleObj *s) {
-   int unicode;
-   cairo_glyph_t glyph;
-   cairo_text_extents_t extents;
+                              symbolStyleObj *s)
+{
+  int unicode;
+  cairo_glyph_t glyph;
+  cairo_text_extents_t extents;
 
-   cairo_matrix_t trans;
-   double ox,oy;
-   cairoCacheData *cache = MS_IMAGE_RENDERER_CACHE(img);
-   cairo_renderer *r = CAIRO_RENDERER(img);
-   faceCacheObj *face = getFontFace(cache,symbol->full_font_path);
+  cairo_matrix_t trans;
+  double ox,oy;
+  cairoCacheData *cache = MS_IMAGE_RENDERER_CACHE(img);
+  cairo_renderer *r = CAIRO_RENDERER(img);
+  faceCacheObj *face = getFontFace(cache,symbol->full_font_path);
 
-   if(!face) return MS_FAILURE;
+  if(!face) return MS_FAILURE;
 
-   cairo_save(r->cr); 
-   cairo_set_font_face(r->cr,face->face);
-   cairo_set_font_size(r->cr,s->scale*96/72.0);
+  cairo_save(r->cr);
+  cairo_set_font_face(r->cr,face->face);
+  cairo_set_font_size(r->cr,s->scale*96/72.0);
 
 
-   msUTF8ToUniChar(symbol->character, &unicode);
-   glyph.index = FT_Get_Char_Index(face->ftface, unicode);
-   glyph.x=0;
-   glyph.y=0;
-   cairo_glyph_extents(r->cr,&glyph,1,&extents);
-   ox=extents.x_bearing+extents.width/2.;
-   oy=extents.y_bearing+extents.height/2.;
+  msUTF8ToUniChar(symbol->character, &unicode);
+  glyph.index = FT_Get_Char_Index(face->ftface, unicode);
+  glyph.x=0;
+  glyph.y=0;
+  cairo_glyph_extents(r->cr,&glyph,1,&extents);
+  ox=extents.x_bearing+extents.width/2.;
+  oy=extents.y_bearing+extents.height/2.;
 
 
 
-   cairo_matrix_init_rotate(&trans,-s->rotation);
+  cairo_matrix_init_rotate(&trans,-s->rotation);
 
-   cairo_matrix_transform_point(&trans,&ox,&oy);
-   //cairo_translate(cr,-extents.width/2,-extents.height/2);
+  cairo_matrix_transform_point(&trans,&ox,&oy);
+  /* cairo_translate(cr,-extents.width/2,-extents.height/2); */
 
-   cairo_translate(r->cr,x-ox,y-oy);
-   cairo_rotate(r->cr, -s->rotation);
+  cairo_translate(r->cr,x-ox,y-oy);
+  cairo_rotate(r->cr, -s->rotation);
 
-   cairo_glyph_path(r->cr,&glyph,1);
+  cairo_glyph_path(r->cr,&glyph,1);
 
-   if (s->outlinewidth) {
-      msCairoSetSourceColor(r->cr, s->outlinecolor);
-      cairo_set_line_width(r->cr, s->outlinewidth + 1);
-      cairo_stroke_preserve(r->cr);
-   }
-   if(s->color) {
-       msCairoSetSourceColor(r->cr, s->color);
-       cairo_fill_preserve(r->cr);
-   }
-   cairo_new_path(r->cr);
-   cairo_restore(r->cr);
-   return MS_SUCCESS;
+  if (s->outlinewidth) {
+    msCairoSetSourceColor(r->cr, s->outlinecolor);
+    cairo_set_line_width(r->cr, s->outlinewidth + 1);
+    cairo_stroke_preserve(r->cr);
+  }
+  if(s->color) {
+    msCairoSetSourceColor(r->cr, s->color);
+    cairo_fill_preserve(r->cr);
+  }
+  cairo_new_path(r->cr);
+  cairo_restore(r->cr);
+  return MS_SUCCESS;
 }
 
-int renderTileCairo(imageObj *img, imageObj *tile, double x, double y) {
-    cairo_renderer *r = CAIRO_RENDERER(img);
-    cairo_surface_t *im = CAIRO_RENDERER(tile)->surface;
-    int w = cairo_image_surface_get_width (im);
-    int h = cairo_image_surface_get_height (im);
-    cairo_save(r->cr);
-    cairo_translate(r->cr, MS_NINT(x-0.5 * w), MS_NINT(y -0.5 * h));
-    cairo_set_source_surface(r->cr, im, 0, 0);
-    cairo_pattern_set_filter (cairo_get_source (r->cr), CAIRO_FILTER_NEAREST);
-    cairo_paint(r->cr);
-    cairo_restore(r->cr);
-    return MS_SUCCESS;
+int renderTileCairo(imageObj *img, imageObj *tile, double x, double y)
+{
+  cairo_renderer *r = CAIRO_RENDERER(img);
+  cairo_surface_t *im = CAIRO_RENDERER(tile)->surface;
+  int w = cairo_image_surface_get_width (im);
+  int h = cairo_image_surface_get_height (im);
+  cairo_save(r->cr);
+  cairo_translate(r->cr, MS_NINT(x-0.5 * w), MS_NINT(y -0.5 * h));
+  cairo_set_source_surface(r->cr, im, 0, 0);
+  cairo_pattern_set_filter (cairo_get_source (r->cr), CAIRO_FILTER_NEAREST);
+  cairo_paint(r->cr);
+  cairo_restore(r->cr);
+  return MS_SUCCESS;
 }
 
 #define CAIROLINESPACE 1.33
 
-int getTruetypeTextBBoxCairo(rendererVTableObj *renderer, char *font, double size, char *text, rectObj *rect, double **advances) {
-    
-    
-    cairoCacheData *cache = MS_RENDERER_CACHE(renderer);
-    faceCacheObj *face = getFontFace(cache,font);
- 
-    char *utfptr=text;
-    int i,has_kerning,unicode;
-    unsigned long previdx=0;
-    int numglyphs = msGetNumGlyphs(text);
-    cairo_glyph_t glyph;
-    cairo_text_extents_t extents;
-    double px=0,py=0;
-
-    if(face == NULL) {
-        return MS_FAILURE;
+int getTruetypeTextBBoxCairo(rendererVTableObj *renderer, char **fonts, int numfonts, double size,
+                             char *text, rectObj *rect, double **advances, int bAdjustBaseline)
+{
+  cairoCacheData *cache = MS_RENDERER_CACHE(renderer);
+  faceCacheObj* face = getFontFace(cache,fonts[0]);
+
+  int curfontidx = 0;
+  char *utfptr=text;
+  int i,unicode;
+  unsigned long previdx=0;
+  faceCacheObj* prevface = face;
+  int numglyphs = msGetNumGlyphs(text);
+  cairo_glyph_t glyph;
+  cairo_text_extents_t extents;
+  double px=0,py=0;
+
+  if(face == NULL) {
+    return MS_FAILURE;
+  }
+
+  cairo_set_font_face(cache->dummycr,face->face);
+  cairo_set_font_size(cache->dummycr,size*96/72.0);
+
+  if(advances != NULL) {
+    *advances = (double*)malloc(numglyphs*sizeof(double));
+  }
+
+  for(i=0; i<numglyphs; i++) {
+    utfptr+=msUTF8ToUniChar(utfptr, &unicode);
+    glyph.x=px;
+    glyph.y=py;
+    if(unicode=='\n') {
+      py += ceil(size*CAIROLINESPACE);
+      px = 0;
+      previdx=0;
+      continue;
     }
 
-    cairo_set_font_face(cache->dummycr,face->face);
-    cairo_set_font_size(cache->dummycr,size*96/72.0);
-
-    has_kerning = FT_HAS_KERNING((face->ftface));
-
-    if(advances != NULL) {
-        *advances = (double*)malloc(numglyphs*sizeof(double));
+    if (curfontidx != 0) {
+      face = getFontFace(cache, fonts[0]);
+      cairo_set_font_face(cache->dummycr, face->face);
+      curfontidx = 0;
     }
 
-    for(i=0;i<numglyphs;i++) {
-        utfptr+=msUTF8ToUniChar(utfptr, &unicode);
-        glyph.x=px;
-        glyph.y=py;
-        if(unicode=='\n') {
-            py += ceil(size*CAIROLINESPACE);
-            px = 0;
-            previdx=0;
-            continue;
-        }
+    glyph.index = FT_Get_Char_Index(face->ftface, unicode);
+
+    if (glyph.index == 0) {
+      int j;
+      for (j = 1; j < numfonts; j++) {
+        curfontidx = j;
+        face = getFontFace(cache, fonts[j]);
         glyph.index = FT_Get_Char_Index(face->ftface, unicode);
-        if( has_kerning && previdx ) {
-            FT_Vector delta;
-            FT_Get_Kerning( face->ftface, previdx, glyph.index, FT_KERNING_DEFAULT, &delta );
-            px += delta.x / 64.;
-        }
-        cairo_glyph_extents(cache->dummycr,&glyph,1,&extents);
-        
-        if(i==0) {
-            rect->minx = px+extents.x_bearing;
-            rect->miny = py+extents.y_bearing;
-            rect->maxx = px+extents.x_bearing+extents.width;
-            rect->maxy = py+extents.y_bearing+extents.height;
-        } else {
-            rect->minx = MS_MIN(rect->minx,px+extents.x_bearing);
-            rect->miny = MS_MIN(rect->miny,py+extents.y_bearing);
-            rect->maxy = MS_MAX(rect->maxy,py+extents.y_bearing+extents.height);
-            rect->maxx = MS_MAX(rect->maxx,px+extents.x_bearing+extents.width);
+        if (glyph.index != 0) {
+          cairo_set_font_face(cache->dummycr, face->face);
+          break;
         }
-        if(advances!=NULL)
-            (*advances)[i]=extents.x_advance;
-        px += extents.x_advance;
-        previdx=glyph.index;
+      }
     }
-    /*
-    rect->minx = 0;
-    rect->miny = 0;
-    rect->maxx = 1;
-    rect->maxy = 1;
-    */
-    return MS_SUCCESS;
-}
 
-int renderGlyphsCairo(imageObj *img,double x, double y, labelStyleObj *style, char *text) {
-    cairo_renderer *r = CAIRO_RENDERER(img);
-    cairoCacheData *cache = MS_IMAGE_RENDERER_CACHE(img);
-    faceCacheObj *face = getFontFace(cache,style->font);
-
-    char *utfptr=text;
-    int i,has_kerning,unicode;
-    unsigned long previdx=0;
-    int numglyphs = msGetNumGlyphs(text);
-    cairo_glyph_t glyph;
-    cairo_text_extents_t extents;
-    double px=0,py=0;
-
-    if(face == NULL) {
-        return MS_FAILURE;
+    if( FT_HAS_KERNING((prevface->ftface)) && previdx ) {
+      FT_Vector delta;
+      FT_Get_Kerning( prevface->ftface, previdx, glyph.index, FT_KERNING_DEFAULT, &delta );
+      px += delta.x / 64.;
     }
+    cairo_glyph_extents(cache->dummycr,&glyph,1,&extents);
 
-    cairo_set_font_face(r->cr,face->face);
-    cairo_set_font_size(r->cr,style->size*96/72.0);
+    if(i==0) {
+      rect->minx = px+extents.x_bearing;
+      rect->miny = py+extents.y_bearing;
+      rect->maxx = px+extents.x_bearing+extents.width;
+      rect->maxy = py+(bAdjustBaseline?1:(extents.y_bearing+extents.height));
+    } else {
+      rect->minx = MS_MIN(rect->minx,px+extents.x_bearing);
+      rect->miny = MS_MIN(rect->miny,py+extents.y_bearing);
+      rect->maxy = MS_MAX(rect->maxy,py+(bAdjustBaseline?1:(extents.y_bearing+extents.height)));
+      rect->maxx = MS_MAX(rect->maxx,px+extents.x_bearing+extents.width);
+    }
+    if(advances!=NULL)
+      (*advances)[i]=extents.x_advance;
+    px += extents.x_advance;
+    previdx=glyph.index;
+    prevface = face;
+  }
+  return MS_SUCCESS;
+}
 
-    cairo_save(r->cr);
-    cairo_translate(r->cr,MS_NINT(x),MS_NINT(y));
-    if(style->rotation != 0.0)
-       cairo_rotate(r->cr, -style->rotation);
-
-    has_kerning = FT_HAS_KERNING((face->ftface));
-    for(i=0;i<numglyphs;i++) {
-        utfptr+=msUTF8ToUniChar(utfptr, &unicode);
-        glyph.x=px;
-        glyph.y=py;
-        if(unicode=='\n') {
-            py += ceil(style->size*CAIROLINESPACE);
-            px = 0;
-            previdx=0;
-            continue;
-        }
+int renderGlyphsCairo(imageObj *img,double x, double y, labelStyleObj *style, char *text)
+{
+  cairo_renderer *r = CAIRO_RENDERER(img);
+  cairoCacheData *cache = MS_IMAGE_RENDERER_CACHE(img);
+  faceCacheObj* face = getFontFace(cache,style->fonts[0]);
+
+  int curfontidx = 0;
+  char *utfptr=text;
+  int i,unicode;
+  unsigned long previdx=0;
+  faceCacheObj* prevface = face;
+  int numglyphs = msGetNumGlyphs(text);
+  cairo_glyph_t glyph;
+  cairo_text_extents_t extents;
+  double px=0,py=0;
+
+  if(face == NULL) {
+    return MS_FAILURE;
+  }
+
+  cairo_set_font_face(r->cr,face->face);
+  cairo_set_font_size(r->cr,style->size*96/72.0);
+
+  cairo_save(r->cr);
+  cairo_translate(r->cr,MS_NINT(x),MS_NINT(y));
+  if(style->rotation != 0.0)
+    cairo_rotate(r->cr, -style->rotation);
+
+  for(i=0; i<numglyphs; i++) {
+    utfptr+=msUTF8ToUniChar(utfptr, &unicode);
+    glyph.x=px;
+    glyph.y=py;
+    if(unicode=='\n') {
+      py += ceil(style->size*CAIROLINESPACE);
+      px = 0;
+      previdx=0;
+      continue;
+    }
+    if(curfontidx != 0) {
+      face = getFontFace(cache,style->fonts[0]);
+      cairo_set_font_face(r->cr,face->face);
+      curfontidx = 0;
+    }
+    glyph.index = FT_Get_Char_Index(face->ftface, unicode);
+    if(glyph.index == 0) {
+      int j;
+      for(j=1; j<style->numfonts; j++) {
+        curfontidx = j;
+        face = getFontFace(cache,style->fonts[j]);
         glyph.index = FT_Get_Char_Index(face->ftface, unicode);
-        if( has_kerning && previdx ) {
-            FT_Vector delta;
-            FT_Get_Kerning( face->ftface, previdx, glyph.index, FT_KERNING_DEFAULT, &delta );
-            px += delta.x / 64.;
+        if(glyph.index != 0) {
+          cairo_set_font_face(r->cr,face->face);
+          break;
         }
-        cairo_glyph_extents(r->cr,&glyph,1,&extents);
-        cairo_glyph_path(r->cr,&glyph,1);
-        px += extents.x_advance;
-        previdx=glyph.index;
+      }
     }
 
-    if (style->outlinewidth > 0) {
-        cairo_save(r->cr);
-        msCairoSetSourceColor(r->cr, style->outlinecolor);
-        cairo_set_line_width(r->cr, style->outlinewidth + 1);
-        cairo_stroke_preserve(r->cr);
-        cairo_restore(r->cr);
+    if(  FT_HAS_KERNING((prevface->ftface)) && previdx ) {
+      FT_Vector delta;
+      FT_Get_Kerning( prevface->ftface, previdx, glyph.index, FT_KERNING_DEFAULT, &delta );
+      px += delta.x / 64.;
     }
-    if(style->color) {
-        msCairoSetSourceColor(r->cr, style->color);
-        cairo_fill(r->cr);
-    }
-    cairo_new_path(r->cr);
+    cairo_glyph_extents(r->cr,&glyph,1,&extents);
+    cairo_glyph_path(r->cr,&glyph,1);
+    px += extents.x_advance;
+    previdx=glyph.index;
+    prevface=face;
+  }
+
+  if (style->outlinewidth > 0) {
+    cairo_save(r->cr);
+    msCairoSetSourceColor(r->cr, style->outlinecolor);
+    cairo_set_line_width(r->cr, style->outlinewidth + 1);
+    cairo_stroke_preserve(r->cr);
     cairo_restore(r->cr);
-    return MS_SUCCESS;
+  }
+  if(style->color) {
+    msCairoSetSourceColor(r->cr, style->color);
+    cairo_fill(r->cr);
+  }
+  cairo_new_path(r->cr);
+  cairo_restore(r->cr);
+  return MS_SUCCESS;
 }
 
 
-cairo_status_t _stream_write_fn(void *b, const unsigned char *data, unsigned int length) {
-    msBufferAppend((bufferObj*)b,(void*)data,length);
-    return CAIRO_STATUS_SUCCESS;
+cairo_status_t _stream_write_fn(void *b, const unsigned char *data, unsigned int length)
+{
+  msBufferAppend((bufferObj*)b,(void*)data,length);
+  return CAIRO_STATUS_SUCCESS;
 }
 
-imageObj* createImageCairo(int width, int height, outputFormatObj *format,colorObj* bg) {
-    imageObj *image = NULL;
-    cairo_renderer *r=NULL;
-    if (format->imagemode != MS_IMAGEMODE_RGB && format->imagemode!= MS_IMAGEMODE_RGBA) {
-        msSetError(MS_MISCERR,
-                   "Cairo driver only supports RGB or RGBA pixel models.","msImageCreateCairo()");
-        return image;
-    }
-    if (width > 0 && height > 0) {
-        image = (imageObj *) calloc(1, sizeof(imageObj));
-        r = (cairo_renderer*)calloc(1,sizeof(cairo_renderer));
-        if(!strcasecmp(format->driver,"cairo/pdf")) {
-            r->outputStream = (bufferObj*)malloc(sizeof(bufferObj));
-            msBufferInit(r->outputStream);
-            r->surface = cairo_pdf_surface_create_for_stream(
-                    _stream_write_fn,
-                    r->outputStream,
-                    width,height);
-        } else if(!strcasecmp(format->driver,"cairo/svg")) {
-            r->outputStream = (bufferObj*)malloc(sizeof(bufferObj));
-            msBufferInit(r->outputStream);
-            r->surface = cairo_svg_surface_create_for_stream(
-                    _stream_write_fn,
-                    r->outputStream,
-                    width,height);
-        } else if(!strcasecmp(format->driver,"cairo/winGDI") && format->device) {
+imageObj* createImageCairo(int width, int height, outputFormatObj *format,colorObj* bg)
+{
+  imageObj *image = NULL;
+  cairo_renderer *r=NULL;
+  if (format->imagemode != MS_IMAGEMODE_RGB && format->imagemode!= MS_IMAGEMODE_RGBA) {
+    msSetError(MS_MISCERR,
+               "Cairo driver only supports RGB or RGBA pixel models.","msImageCreateCairo()");
+    return image;
+  }
+  if (width > 0 && height > 0) {
+    image = (imageObj *) calloc(1, sizeof(imageObj));
+    r = (cairo_renderer*)calloc(1,sizeof(cairo_renderer));
+    if(!strcasecmp(format->driver,"cairo/pdf")) {
+      r->outputStream = (bufferObj*)malloc(sizeof(bufferObj));
+      msBufferInit(r->outputStream);
+      r->surface = cairo_pdf_surface_create_for_stream(
+                     _stream_write_fn,
+                     r->outputStream,
+                     width,height);
+    } else if(!strcasecmp(format->driver,"cairo/svg")) {
+      r->outputStream = (bufferObj*)malloc(sizeof(bufferObj));
+      msBufferInit(r->outputStream);
+      r->surface = cairo_svg_surface_create_for_stream(
+                     _stream_write_fn,
+                     r->outputStream,
+                     width,height);
+    } else if(!strcasecmp(format->driver,"cairo/winGDI") && format->device) {
 #if CAIRO_HAS_WIN32_SURFACE
-            r->outputStream = NULL;
-            r->surface = cairo_win32_surface_create(format->device);
+      r->outputStream = NULL;
+      r->surface = cairo_win32_surface_create(format->device);
 #else
-            msSetError(MS_RENDERERERR, "Cannot create cairo image. Cairo was not compiled with support for the win32 backend.",
-             "msImageCreateCairo()");
+      msSetError(MS_RENDERERERR, "Cannot create cairo image. Cairo was not compiled with support for the win32 backend.",
+                 "msImageCreateCairo()");
 #endif
-        } else if(!strcasecmp(format->driver,"cairo/winGDIPrint") && format->device) {
+    } else if(!strcasecmp(format->driver,"cairo/winGDIPrint") && format->device) {
 #if CAIRO_HAS_WIN32_SURFACE
-            r->outputStream = NULL;
-            r->surface = cairo_win32_printing_surface_create(format->device);
+      r->outputStream = NULL;
+      r->surface = cairo_win32_printing_surface_create(format->device);
 #else
-            msSetError(MS_RENDERERERR, "Cannot create cairo image. Cairo was not compiled with support for the win32 backend.",
-             "msImageCreateCairo()");
+      msSetError(MS_RENDERERERR, "Cannot create cairo image. Cairo was not compiled with support for the win32 backend.",
+                 "msImageCreateCairo()");
 #endif
-        } else {
-            r->outputStream = NULL;
-            r->surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32, width, height);
-        }
-        r->cr = cairo_create(r->surface);
-        if(format->transparent || !bg || !MS_VALID_COLOR(*bg)) {
-           r->use_alpha = 1;
-           cairo_set_source_rgba (r->cr, 0,0,0,0);
-        } else {
-           r->use_alpha = 0;
-           msCairoSetSourceColor(r->cr,bg);
-        }
-        cairo_save (r->cr);
-        cairo_set_operator (r->cr, CAIRO_OPERATOR_SOURCE);
-        cairo_paint (r->cr);
-        cairo_restore (r->cr);
-
-        cairo_set_line_cap (r->cr,CAIRO_LINE_CAP_ROUND);
-        cairo_set_line_join(r->cr,CAIRO_LINE_JOIN_ROUND);
-        image->img.plugin = (void*)r;
     } else {
-       msSetError(MS_RENDERERERR, "Cannot create cairo image of size %dx%d.",
-                  "msImageCreateCairo()", width, height);
+      r->outputStream = NULL;
+      r->surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32, width, height);
     }
-    return image;
+    r->cr = cairo_create(r->surface);
+    if(format->transparent || !bg || !MS_VALID_COLOR(*bg)) {
+      r->use_alpha = 1;
+      cairo_set_source_rgba (r->cr, 0,0,0,0);
+    } else {
+      r->use_alpha = 0;
+      msCairoSetSourceColor(r->cr,bg);
+    }
+    cairo_save (r->cr);
+    cairo_set_operator (r->cr, CAIRO_OPERATOR_SOURCE);
+    cairo_paint (r->cr);
+    cairo_restore (r->cr);
+
+    cairo_set_line_cap (r->cr,CAIRO_LINE_CAP_ROUND);
+    cairo_set_line_join(r->cr,CAIRO_LINE_JOIN_ROUND);
+    image->img.plugin = (void*)r;
+  } else {
+    msSetError(MS_RENDERERERR, "Cannot create cairo image of size %dx%d.",
+               "msImageCreateCairo()", width, height);
+  }
+  return image;
 }
 
-int saveImageCairo(imageObj *img, FILE *fp, outputFormatObj *format) {
-    cairo_renderer *r = CAIRO_RENDERER(img);
-    if(!strcasecmp(img->format->driver,"cairo/pdf") || !strcasecmp(img->format->driver,"cairo/svg")) {
-        cairo_surface_finish (r->surface);
-        fwrite(r->outputStream->data,r->outputStream->size,1,fp);
-    } else {
-        // not supported
+/* msSaveImagePostPDFProcessing() will call the GDAL PDF driver to add geospatial */
+/* information to the regular PDF generated by cairo. This is only triggered if the */
+/* GEO_ENCODING outputformat option is set (to ISO32000 or OGC_BP). Additionnal */
+/* options can be provided by specifying outputformat options starting with */
+/* METADATA_ITEM: prefix. For example METADATA_ITEM:PRODUCER=MapServer */
+/* Those options are AUTHOR, CREATOR, CREATION_DATE, KEYWORDS, PRODUCER, SUBJECT, TITLE */
+/* See http://gdal.org/frmt_pdf.html documentation. */
+
+static void msTransformToGeospatialPDF(imageObj *img, mapObj *map, cairo_renderer *r)
+{
+  /* We need a GDAL 2.0 PDF driver at runtime, but as far as the C API is concerned, GDAL 1.9 is */
+  /* largely sufficient. */
+#if defined(USE_GDAL) && defined(GDAL_VERSION_NUM) && GDAL_VERSION_NUM >= 1900
+  GDALDatasetH hDS = NULL;
+  const char* pszGEO_ENCODING = NULL;
+  GDALDriverH hPDFDriver = NULL;
+  const char* pszVirtualIO = NULL;
+  int bVirtualIO = FALSE;
+  char* pszTmpFilename = NULL;
+  VSILFILE* fp = NULL;
+
+  if (map == NULL)
+    return;
+
+  pszGEO_ENCODING = msGetOutputFormatOption(img->format, "GEO_ENCODING", NULL);
+  if (pszGEO_ENCODING == NULL)
+    return;
+
+  msGDALInitialize();
+
+  hPDFDriver = GDALGetDriverByName("PDF");
+  if (hPDFDriver == NULL)
+    return;
+
+  /* When compiled against libpoppler, the PDF driver is VirtualIO capable */
+  /* but not, when it is compiled against libpodofo. */
+  pszVirtualIO = GDALGetMetadataItem( hPDFDriver, GDAL_DCAP_VIRTUALIO, NULL );
+  if (pszVirtualIO)
+    bVirtualIO = CSLTestBoolean(pszVirtualIO);
+
+  if (bVirtualIO)
+    pszTmpFilename = msTmpFile(map, NULL, "/vsimem/mscairopdf/", "pdf");
+  else
+    pszTmpFilename = msTmpFile(map, map->mappath, NULL, "pdf");
+
+  /* Copy content of outputStream buffer into file */
+  fp = VSIFOpenL(pszTmpFilename, "wb");
+  if (fp == NULL) {
+    msFree(pszTmpFilename);
+    return;
+  }
+  VSIFWriteL(r->outputStream->data, 1, r->outputStream->size, fp);
+  VSIFCloseL(fp);
+  fp = NULL;
+
+  hDS = GDALOpen(pszTmpFilename, GA_Update);
+  if ( hDS != NULL ) {
+    char* pszWKT = msProjectionObj2OGCWKT( &(map->projection) );
+    if( pszWKT != NULL ) {
+      double adfGeoTransform[6];
+      int i;
+
+      /* Add user-specified options */
+      for( i = 0; i < img->format->numformatoptions; i++ ) {
+        const char* pszOption = img->format->formatoptions[i];
+        if( strncasecmp(pszOption,"METADATA_ITEM:",14) == 0 ) {
+          char* pszKey = NULL;
+          const char* pszValue = CPLParseNameValue(pszOption + 14,
+                                 &pszKey);
+          if( pszKey != NULL ) {
+            GDALSetMetadataItem(hDS, pszKey, pszValue, NULL);
+            CPLFree(pszKey);
+          }
+        }
+      }
+
+      /* We need to rescale the geotransform because GDAL will not necessary */
+      /* open the PDF with the DPI that was used to generate it */
+      memcpy(adfGeoTransform, map->gt.geotransform, 6 * sizeof(double));
+      adfGeoTransform[1] = adfGeoTransform[1] * map->width / GDALGetRasterXSize(hDS);
+      adfGeoTransform[5] = adfGeoTransform[5] * map->height / GDALGetRasterYSize(hDS);
+      GDALSetGeoTransform(hDS, adfGeoTransform);
+      GDALSetProjection(hDS, pszWKT);
+
+      msFree( pszWKT );
+      pszWKT = NULL;
+
+      CPLSetThreadLocalConfigOption("GDAL_PDF_GEO_ENCODING", pszGEO_ENCODING);
+
+      GDALClose(hDS);
+      hDS = NULL;
+
+      CPLSetThreadLocalConfigOption("GDAL_PDF_GEO_ENCODING", NULL);
+
+      /* We need to replace the buffer with the content of the GDAL file */
+      fp = VSIFOpenL(pszTmpFilename, "rb");
+      if( fp != NULL ) {
+        int nFileSize;
+
+        VSIFSeekL(fp, 0, SEEK_END);
+        nFileSize = (int)VSIFTellL(fp);
+
+        msBufferResize(r->outputStream, nFileSize);
+
+        VSIFSeekL(fp, 0, SEEK_SET);
+        VSIFReadL(r->outputStream->data, 1, nFileSize, fp);
+
+        r->outputStream->size = nFileSize;
+
+        VSIFCloseL(fp);
+        fp = NULL;
+      }
     }
-    return MS_SUCCESS;
+  }
+
+  if ( hDS != NULL )
+    GDALClose(hDS);
+
+  VSIUnlink(pszTmpFilename);
+
+  msFree(pszTmpFilename);
+#endif
+}
+
+int saveImageCairo(imageObj *img, mapObj *map, FILE *fp, outputFormatObj *format)
+{
+  cairo_renderer *r = CAIRO_RENDERER(img);
+  if(!strcasecmp(img->format->driver,"cairo/pdf") || !strcasecmp(img->format->driver,"cairo/svg")) {
+    cairo_surface_finish (r->surface);
+
+    if (map != NULL && !strcasecmp(img->format->driver,"cairo/pdf"))
+      msTransformToGeospatialPDF(img, map, r);
+
+    fwrite(r->outputStream->data,r->outputStream->size,1,fp);
+  } else {
+    /* not supported */
+  }
+  return MS_SUCCESS;
+}
+
+unsigned char* saveImageBufferCairo(imageObj *img, int *size_ptr, outputFormatObj *format)
+{
+  cairo_renderer *r = CAIRO_RENDERER(img);
+  unsigned char *data;
+  assert(!strcasecmp(img->format->driver,"cairo/pdf") || !strcasecmp(img->format->driver,"cairo/svg"));
+  cairo_surface_finish (r->surface);
+  data = msSmallMalloc(r->outputStream->size);
+  memcpy(data,r->outputStream->data,r->outputStream->size);
+  *size_ptr = (int)r->outputStream->size;
+  return data;
 }
 
 void *msCreateTileEllipseCairo(double width, double height, double angle,
-                               colorObj *c, colorObj *bc, colorObj *oc, double ow) {
-    double s = (MS_MAX(width,height)+ow)*1.5;
-    cairo_surface_t *surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32,
-                                                           s,s);
-    cairo_t *cr = cairo_create(surface);
-    //cairo_set_line_cap(cr, CAIRO_LINE_CAP_ROUND);
-    //cairo_set_line_join(cr, CAIRO_LINE_JOIN_ROUND);
-    if (bc && MS_VALID_COLOR(*bc)) {
-        msCairoSetSourceColor(cr, bc);
-        cairo_paint(cr);
-    }
-    cairo_save(cr);
-    cairo_translate(cr,s/2,s/2);
-    cairo_rotate(cr, -angle);
-    cairo_scale(cr, width/2,height/2);
-    cairo_arc(cr, 0, 0, 1, 0, 2 * MS_PI);
-    cairo_restore(cr);
-    if (c != NULL && MS_VALID_COLOR(*c)) {
-        msCairoSetSourceColor(cr, c);
-        cairo_fill_preserve(cr);
-    }
-    if (oc != NULL && MS_VALID_COLOR(*oc)) {
-        cairo_set_line_width(cr, ow);
-        msCairoSetSourceColor(cr, oc);
-        cairo_stroke_preserve(cr);
-    }
-    cairo_new_path(cr);
-    cairo_destroy(cr);
-    return surface;
+                               colorObj *c, colorObj *bc, colorObj *oc, double ow)
+{
+  double s = (MS_MAX(width,height)+ow)*1.5;
+  cairo_surface_t *surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32,
+                             s,s);
+  cairo_t *cr = cairo_create(surface);
+  /* cairo_set_line_cap(cr, CAIRO_LINE_CAP_ROUND); */
+  /* cairo_set_line_join(cr, CAIRO_LINE_JOIN_ROUND); */
+  if (bc && MS_VALID_COLOR(*bc)) {
+    msCairoSetSourceColor(cr, bc);
+    cairo_paint(cr);
+  }
+  cairo_save(cr);
+  cairo_translate(cr,s/2,s/2);
+  cairo_rotate(cr, -angle);
+  cairo_scale(cr, width/2,height/2);
+  cairo_arc(cr, 0, 0, 1, 0, 2 * MS_PI);
+  cairo_restore(cr);
+  if (c != NULL && MS_VALID_COLOR(*c)) {
+    msCairoSetSourceColor(cr, c);
+    cairo_fill_preserve(cr);
+  }
+  if (oc != NULL && MS_VALID_COLOR(*oc)) {
+    cairo_set_line_width(cr, ow);
+    msCairoSetSourceColor(cr, oc);
+    cairo_stroke_preserve(cr);
+  }
+  cairo_new_path(cr);
+  cairo_destroy(cr);
+  return surface;
 
 }
 
 int renderEllipseSymbolCairo(imageObj *img, double x, double y, symbolObj *symbol,
-                             symbolStyleObj *style) {
-    cairo_renderer *r = CAIRO_RENDERER(img);
-    
-    cairo_save(r->cr);
-    cairo_set_line_cap(r->cr, CAIRO_LINE_CAP_BUTT);
-    cairo_set_line_join(r->cr, CAIRO_LINE_JOIN_MITER);
-    cairo_translate(r->cr,x,y);
-    cairo_rotate(r->cr,-style->rotation);
-    cairo_scale(r->cr,symbol->sizex*style->scale/2,symbol->sizey*style->scale/2);
-    cairo_arc (r->cr, 0,0,1, 0, 2 * MS_PI);
-    cairo_restore(r->cr);
-    if(style->color) {
-        msCairoSetSourceColor(r->cr, style->color);
-        cairo_fill_preserve(r->cr);
-    }
-    if(style->outlinewidth > 0) {
-        cairo_set_line_width (r->cr, style->outlinewidth);
-        msCairoSetSourceColor(r->cr, style->outlinecolor);
-        cairo_stroke_preserve(r->cr);
-    }
-    cairo_new_path(r->cr);
-    return MS_SUCCESS;
+                             symbolStyleObj *style)
+{
+  cairo_renderer *r = CAIRO_RENDERER(img);
+
+  cairo_save(r->cr);
+  cairo_set_line_cap(r->cr, CAIRO_LINE_CAP_BUTT);
+  cairo_set_line_join(r->cr, CAIRO_LINE_JOIN_MITER);
+  cairo_translate(r->cr,x,y);
+  cairo_rotate(r->cr,-style->rotation);
+  cairo_scale(r->cr,symbol->sizex*style->scale/2,symbol->sizey*style->scale/2);
+  cairo_arc (r->cr, 0,0,1, 0, 2 * MS_PI);
+  cairo_restore(r->cr);
+  if(style->color) {
+    msCairoSetSourceColor(r->cr, style->color);
+    cairo_fill_preserve(r->cr);
+  }
+  if(style->outlinewidth > 0) {
+    cairo_set_line_width (r->cr, style->outlinewidth);
+    msCairoSetSourceColor(r->cr, style->outlinecolor);
+    cairo_stroke_preserve(r->cr);
+  }
+  cairo_new_path(r->cr);
+  return MS_SUCCESS;
 }
 
 
 
-int startLayerVectorCairo(imageObj *img, mapObj *map, layerObj *layer) {
-   cairo_renderer *r = CAIRO_RENDERER(img);
-   cairo_push_group (r->cr);
-   return MS_SUCCESS;
+int startLayerVectorCairo(imageObj *img, mapObj *map, layerObj *layer)
+{
+  if(layer->opacity<100) {
+    cairo_renderer *r = CAIRO_RENDERER(img);
+    cairo_push_group (r->cr);
+  }
+  return MS_SUCCESS;
 }
 
-int closeLayerVectorCairo(imageObj *img, mapObj *map, layerObj *layer) {
-   cairo_renderer *r = CAIRO_RENDERER(img);
-   cairo_pop_group_to_source (r->cr);
-   cairo_paint_with_alpha (r->cr, layer->opacity*0.01);
-   return MS_SUCCESS;
+int closeLayerVectorCairo(imageObj *img, mapObj *map, layerObj *layer)
+{
+  if(layer->opacity<100) {
+    cairo_renderer *r = CAIRO_RENDERER(img);
+    cairo_pop_group_to_source (r->cr);
+    cairo_paint_with_alpha (r->cr, layer->opacity*0.01);
+  }
+  return MS_SUCCESS;
 }
 
-int startLayerRasterCairo(imageObj *img, mapObj *map, layerObj *layer) {
-    return MS_SUCCESS;
+int startLayerRasterCairo(imageObj *img, mapObj *map, layerObj *layer)
+{
+  return MS_SUCCESS;
 }
 
-int closeLayerRasterCairo(imageObj *img, mapObj *map, layerObj *layer) {
-    return MS_SUCCESS;
+int closeLayerRasterCairo(imageObj *img, mapObj *map, layerObj *layer)
+{
+  return MS_SUCCESS;
 }
 
 
-int getRasterBufferHandleCairo(imageObj *img, rasterBufferObj *rb) {
+int getRasterBufferHandleCairo(imageObj *img, rasterBufferObj *rb)
+{
   unsigned char *pb;
-    cairo_renderer *r = CAIRO_RENDERER(img);
-    rb->type = MS_BUFFER_BYTE_RGBA;
-    pb = cairo_image_surface_get_data(r->surface);
-    rb->data.rgba.pixels = pb;
-    rb->data.rgba.row_step = cairo_image_surface_get_stride(r->surface);
-    rb->data.rgba.pixel_step=4;
-    rb->width = cairo_image_surface_get_width(r->surface);
-    rb->height = cairo_image_surface_get_height(r->surface);
-    rb->data.rgba.r = &(pb[2]);
-    rb->data.rgba.g = &(pb[1]);
-    rb->data.rgba.b = &(pb[0]);
-    if(r->use_alpha)
-       rb->data.rgba.a = &(pb[3]);
-    else
-       rb->data.rgba.a = NULL;
-    return MS_SUCCESS;
+  cairo_renderer *r = CAIRO_RENDERER(img);
+  rb->type = MS_BUFFER_BYTE_RGBA;
+  pb = cairo_image_surface_get_data(r->surface);
+  rb->data.rgba.pixels = pb;
+  rb->data.rgba.row_step = cairo_image_surface_get_stride(r->surface);
+  rb->data.rgba.pixel_step=4;
+  rb->width = cairo_image_surface_get_width(r->surface);
+  rb->height = cairo_image_surface_get_height(r->surface);
+  rb->data.rgba.r = &(pb[2]);
+  rb->data.rgba.g = &(pb[1]);
+  rb->data.rgba.b = &(pb[0]);
+  if(r->use_alpha)
+    rb->data.rgba.a = &(pb[3]);
+  else
+    rb->data.rgba.a = NULL;
+  return MS_SUCCESS;
 }
 
-int getRasterBufferCopyCairo(imageObj *img, rasterBufferObj *rb) {
-    cairo_renderer *r = CAIRO_RENDERER(img);
-    unsigned char *pb;
-    rb->type = MS_BUFFER_BYTE_RGBA;
-    rb->data.rgba.row_step = cairo_image_surface_get_stride(r->surface);
-    rb->data.rgba.pixel_step=4;
-    rb->width = cairo_image_surface_get_width(r->surface);
-    rb->height = cairo_image_surface_get_height(r->surface);
-    pb = (unsigned char*)malloc(rb->height * rb->data.rgba.row_step * sizeof(unsigned char*));
-    memcpy(pb,cairo_image_surface_get_data(r->surface),rb->height * rb->data.rgba.row_step);
-    rb->data.rgba.pixels = pb;
-    rb->data.rgba.r = &(pb[2]);
-    rb->data.rgba.g = &(pb[1]);
-    rb->data.rgba.b = &(pb[0]);
-    if(r->use_alpha)
-       rb->data.rgba.a = &(pb[3]);
-    else
-       rb->data.rgba.a = NULL;
-    return MS_SUCCESS;
+int getRasterBufferCopyCairo(imageObj *img, rasterBufferObj *rb)
+{
+  cairo_renderer *r = CAIRO_RENDERER(img);
+  unsigned char *pb;
+  rb->type = MS_BUFFER_BYTE_RGBA;
+  rb->data.rgba.row_step = cairo_image_surface_get_stride(r->surface);
+  rb->data.rgba.pixel_step=4;
+  rb->width = cairo_image_surface_get_width(r->surface);
+  rb->height = cairo_image_surface_get_height(r->surface);
+  pb = (unsigned char*)malloc(rb->height * rb->data.rgba.row_step * sizeof(unsigned char*));
+  memcpy(pb,cairo_image_surface_get_data(r->surface),rb->height * rb->data.rgba.row_step);
+  rb->data.rgba.pixels = pb;
+  rb->data.rgba.r = &(pb[2]);
+  rb->data.rgba.g = &(pb[1]);
+  rb->data.rgba.b = &(pb[0]);
+  if(r->use_alpha)
+    rb->data.rgba.a = &(pb[3]);
+  else
+    rb->data.rgba.a = NULL;
+  return MS_SUCCESS;
 }
 
 
 
 int mergeRasterBufferCairo(imageObj *img, rasterBufferObj *rb, double opacity,
-                           int srcX, int srcY, int dstX, int dstY, 
-                           int width, int height) {
-    cairo_surface_t *src;
-    cairo_renderer *r;
-    //not implemented for src,dst,width and height;
-    if(!rb->type == MS_BUFFER_BYTE_RGBA) {
-        return MS_FAILURE;
-    }
-    r = CAIRO_RENDERER(img);
-
-    src = cairo_image_surface_create_for_data(rb->data.rgba.pixels,CAIRO_FORMAT_ARGB32,
-                                              rb->width,rb->height,
-                                              rb->data.rgba.row_step);
-    
-    if(dstX||dstY||srcX||srcY||width!=img->width||height!=img->height) {
-        cairo_set_source_surface (r->cr, src, dstX - srcX, dstY - srcY);
-        cairo_rectangle (r->cr, dstX, dstY, width, height);
-        cairo_fill (r->cr);
-    } else {
-        cairo_set_source_surface (r->cr,src,0,0);
-        cairo_paint_with_alpha(r->cr,opacity);
-    }
-    cairo_surface_finish(src);
-    cairo_surface_destroy(src);
-    return MS_SUCCESS;
+                           int srcX, int srcY, int dstX, int dstY,
+                           int width, int height)
+{
+  cairo_surface_t *src;
+  cairo_renderer *r;
+  /* not implemented for src,dst,width and height */
+  if(!rb->type == MS_BUFFER_BYTE_RGBA) {
+    return MS_FAILURE;
+  }
+  r = CAIRO_RENDERER(img);
+
+  src = cairo_image_surface_create_for_data(rb->data.rgba.pixels,CAIRO_FORMAT_ARGB32,
+        rb->width,rb->height,
+        rb->data.rgba.row_step);
+
+  if(dstX||dstY||srcX||srcY||width!=img->width||height!=img->height) {
+    cairo_set_source_surface (r->cr, src, dstX - srcX, dstY - srcY);
+    cairo_rectangle (r->cr, dstX, dstY, width, height);
+    cairo_fill (r->cr);
+  } else {
+    cairo_set_source_surface (r->cr,src,0,0);
+    cairo_paint_with_alpha(r->cr,opacity);
+  }
+  cairo_surface_finish(src);
+  cairo_surface_destroy(src);
+  return MS_SUCCESS;
 }
 
-int freeSymbolCairo(symbolObj *s) {
-    if(!s->renderer_cache)
-        return MS_SUCCESS;
-    switch(s->type) {
+int freeSymbolCairo(symbolObj *s)
+{
+  if(!s->renderer_cache)
+    return MS_SUCCESS;
+  switch(s->type) {
     case MS_SYMBOL_VECTOR:
-        cairo_path_destroy(s->renderer_cache);
-        break;
+      cairo_path_destroy(s->renderer_cache);
+      break;
     case MS_SYMBOL_PIXMAP:
-        cairo_surface_finish(s->renderer_cache);
-        cairo_surface_destroy(s->renderer_cache);
-        break;
+      cairo_surface_destroy(s->renderer_cache);
+      break;
+    case MS_SYMBOL_SVG: {
+#ifdef USE_SVG_CAIRO
+      struct svg_symbol_cache *cache = s->renderer_cache;
+      assert(cache->svgc);
+      svg_cairo_destroy(cache->svgc);
+      msFree(s->renderer_cache);
+#endif
     }
-    s->renderer_cache=NULL;
+    break;
+  }
+  s->renderer_cache=NULL;
+  return MS_SUCCESS;
+}
+
+int initializeRasterBufferCairo(rasterBufferObj *rb, int width, int height, int mode)
+{
+  rb->type = MS_BUFFER_BYTE_RGBA;
+  rb->width = width;
+  rb->height = height;
+  rb->data.rgba.pixel_step = 4;
+  rb->data.rgba.row_step = width * 4;
+  rb->data.rgba.pixels = (unsigned char*)calloc(width*height*4,sizeof(unsigned char));
+  rb->data.rgba.r = &(rb->data.rgba.pixels[2]);
+  rb->data.rgba.g = &(rb->data.rgba.pixels[1]);
+  rb->data.rgba.b = &(rb->data.rgba.pixels[0]);
+  rb->data.rgba.a = &(rb->data.rgba.pixels[3]);
+  return MS_SUCCESS;
+}
+
+
+int msPreloadSVGSymbol(symbolObj *symbol)
+{
+#ifdef USE_SVG_CAIRO
+  int status;
+  unsigned int svg_width, svg_height;
+  struct svg_symbol_cache *cache;
+
+  if(!symbol->renderer_cache) {
+    cache = msSmallCalloc(1,sizeof(struct svg_symbol_cache));
+  } else {
+    cache = symbol->renderer_cache;
+  }
+  if(cache->svgc)
     return MS_SUCCESS;
+
+  if (!symbol->svg_text) {
+    FILE *stream;
+    long int file_len;
+
+    if ((stream = fopen(symbol->full_pixmap_path, "rb")) == NULL) {
+      msSetError(MS_IOERR, "Could not open svg file %s", "msPreloadSVGSymbol()",symbol->full_pixmap_path);
+      return (MS_FAILURE);
+    }
+    fseek(stream, 0, SEEK_END);
+    file_len = ftell(stream);
+    rewind(stream);
+    symbol->svg_text = (char*) msSmallMalloc(sizeof (char) * file_len);
+    if (1 != fread(symbol->svg_text, file_len, 1, stream)) {
+      msSetError(MS_IOERR, "failed to read %d bytes from svg file %s", "loadSymbol()", file_len, symbol->full_pixmap_path);
+      free(symbol->svg_text);
+      return MS_FAILURE;
+    }
+    symbol->svg_text[file_len - 1] = '\0';
+    fclose(stream);
+  }
+
+  status = svg_cairo_create(&cache->svgc);
+  if (status) {
+    msSetError(MS_RENDERERERR, "problem creating cairo svg", "msPreloadSVGSymbol()");
+    return MS_FAILURE;
+  }
+  status = svg_cairo_parse_buffer(cache->svgc, symbol->svg_text, strlen(symbol->svg_text));
+  if (status) {
+    msSetError(MS_RENDERERERR, "problem parsing svg symbol", "msPreloadSVGSymbol()");
+    return MS_FAILURE;
+  }
+  svg_cairo_get_size (cache->svgc, &svg_width, &svg_height);
+  if (svg_width == 0 || svg_height == 0) {
+    msSetError(MS_RENDERERERR, "problem parsing svg symbol", "msPreloadSVGSymbol()");
+    return MS_FAILURE;
+  }
+
+  symbol->sizex = svg_width;
+  symbol->sizey = svg_height;
+  symbol->renderer_cache = cache;
+
+  return MS_SUCCESS;
+
+#else
+  msSetError(MS_MISCERR, "SVG Symbols requested but is not built with libsvgcairo",
+             "msPreloadSVGSymbol()");
+  return MS_FAILURE;
+#endif
+}
+
+
+
+int msRenderRasterizedSVGSymbol(imageObj *img, double x, double y, symbolObj *symbol, symbolStyleObj *style)
+{
+
+#ifdef USE_SVG_CAIRO
+  struct svg_symbol_cache *svg_cache;
+  symbolStyleObj pixstyle;
+  symbolObj pixsymbol;
+
+  //already rendered at the right size and scale? return
+  if(MS_SUCCESS != msPreloadSVGSymbol(symbol))
+    return MS_FAILURE;
+  svg_cache = (struct svg_symbol_cache*) symbol->renderer_cache;
+
+  if(svg_cache->scale != style->scale || svg_cache->rotation != style->rotation) {
+    cairo_t *cr;
+    cairo_surface_t *surface;
+    unsigned char *pb;
+    int width, height, surface_w, surface_h;
+    /* need to recompute the pixmap */
+    msFreeRasterBuffer(&svg_cache->pixmap_buffer);
+
+    //increase pixmap size to accomodate scaling/rotation
+    if (style->scale != 1.0) {
+      width = surface_w = (symbol->sizex * style->scale + 0.5);
+      height = surface_h = (symbol->sizey * style->scale + 0.5);
+    } else {
+      width = surface_w = symbol->sizex;
+      height = surface_h = symbol->sizey;
+    }
+    if (style->rotation != 0) {
+      surface_w = MS_NINT(width * 1.415);
+      surface_h = MS_NINT(height * 1.415);
+    }
+
+    surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, surface_w, surface_h);
+    cr = cairo_create(surface);
+
+    if (style->rotation != 0) {
+      cairo_translate(cr, surface_w / 2, surface_h / 2);
+      cairo_rotate(cr, -style->rotation);
+      cairo_translate(cr, -width / 2, -height / 2);
+    }
+    if (style->scale != 1.0) {
+      cairo_scale(cr, style->scale, style->scale);
+    }
+    if(svg_cairo_render(svg_cache->svgc, cr) != SVG_CAIRO_STATUS_SUCCESS) {
+      return MS_FAILURE;
+    }
+    pb = cairo_image_surface_get_data(surface);
+
+    //set up raster
+    initializeRasterBufferCairo(&svg_cache->pixmap_buffer, surface_w, surface_h, 0);
+    memcpy(svg_cache->pixmap_buffer.data.rgba.pixels, pb, surface_w * surface_h * 4 * sizeof (unsigned char));
+    svg_cache->scale = style->scale;
+    svg_cache->rotation = style->rotation;
+    cairo_destroy(cr);
+    cairo_surface_destroy(surface);
+  }
+  assert(svg_cache->pixmap_buffer.height && svg_cache->pixmap_buffer.width);
+
+  pixstyle = *style;
+  pixstyle.rotation = 0.0;
+  pixstyle.scale = 1.0;
+
+  pixsymbol.pixmap_buffer = &svg_cache->pixmap_buffer;
+  pixsymbol.type = MS_SYMBOL_PIXMAP;
+
+  MS_IMAGE_RENDERER(img)->renderPixmapSymbol(img,x,y,&pixsymbol,&pixstyle);
+  MS_IMAGE_RENDERER(img)->freeSymbol(&pixsymbol);
+  return MS_SUCCESS;
+#else
+  msSetError(MS_MISCERR, "SVG Symbols requested but MapServer is not built with libsvgcairo",
+             "renderSVGSymbolCairo()");
+  return MS_FAILURE;
+#endif
 }
 
-int initializeRasterBufferCairo(rasterBufferObj *rb, int width, int height, int mode) {
-    rb->type = MS_BUFFER_BYTE_RGBA;
-    rb->width = width;
-    rb->height = height;
-    rb->data.rgba.pixel_step = 4;
-    rb->data.rgba.row_step = width * 4;
-    rb->data.rgba.pixels = (unsigned char*)calloc(width*height*4,sizeof(unsigned char));
-    rb->data.rgba.r = &(rb->data.rgba.pixels[2]);
-    rb->data.rgba.g = &(rb->data.rgba.pixels[1]);
-    rb->data.rgba.b = &(rb->data.rgba.pixels[0]);
-    rb->data.rgba.a = &(rb->data.rgba.pixels[3]);
-   return MS_SUCCESS;
+void msCairoCleanup() {
+   cairo_debug_reset_static_data();
 }
 
 #endif /*USE_CAIRO*/
 
 
-int msPopulateRendererVTableCairoRaster( rendererVTableObj *renderer ) {
+int msPopulateRendererVTableCairoRaster( rendererVTableObj *renderer )
+{
 #ifdef USE_CAIRO
-    renderer->supports_pixel_buffer=1;
-    renderer->supports_transparent_layers = 0;
-    renderer->default_transform_mode = MS_TRANSFORM_SIMPLIFY;
-    initializeCache(&MS_RENDERER_CACHE(renderer));
-    renderer->startLayer = startLayerRasterCairo;
-    renderer->endLayer = closeLayerRasterCairo;
-    renderer->renderLineTiled = NULL;
-    renderer->renderLine=&renderLineCairo;
-    renderer->createImage=&createImageCairo;
-    renderer->saveImage=&saveImageCairo;
-    renderer->getRasterBufferHandle=&getRasterBufferHandleCairo;
-    renderer->getRasterBufferCopy=&getRasterBufferCopyCairo;
-    renderer->renderPolygon=&renderPolygonCairo;
-    renderer->renderGlyphs=&renderGlyphsCairo;
-    renderer->freeImage=&freeImageCairo;
-    renderer->renderEllipseSymbol = &renderEllipseSymbolCairo;
-    renderer->renderVectorSymbol = &renderVectorSymbolCairo;
-    renderer->renderTruetypeSymbol = &renderTruetypeSymbolCairo;
-    renderer->renderPixmapSymbol = &renderPixmapSymbolCairo;
-    renderer->mergeRasterBuffer = &mergeRasterBufferCairo;
-    renderer->getTruetypeTextBBox = &getTruetypeTextBBoxCairo;
-    renderer->renderTile = &renderTileCairo;
-    renderer->loadImageFromFile = &msLoadMSRasterBufferFromFile;
-    renderer->renderPolygonTiled = &renderPolygonTiledCairo;
-    renderer->freeSymbol = &freeSymbolCairo;
-    renderer->cleanup = &cleanupCairo;
-    return MS_SUCCESS;
+  renderer->supports_pixel_buffer=1;
+  renderer->supports_transparent_layers = 0;
+  renderer->supports_svg = 1;
+  renderer->default_transform_mode = MS_TRANSFORM_SIMPLIFY;
+  initializeCache(&MS_RENDERER_CACHE(renderer));
+  renderer->startLayer = startLayerRasterCairo;
+  renderer->endLayer = closeLayerRasterCairo;
+  renderer->renderLineTiled = NULL;
+  renderer->renderLine=&renderLineCairo;
+  renderer->createImage=&createImageCairo;
+  renderer->saveImage=&saveImageCairo;
+  renderer->getRasterBufferHandle=&getRasterBufferHandleCairo;
+  renderer->getRasterBufferCopy=&getRasterBufferCopyCairo;
+  renderer->renderPolygon=&renderPolygonCairo;
+  renderer->renderGlyphs=&renderGlyphsCairo;
+  renderer->freeImage=&freeImageCairo;
+  renderer->renderEllipseSymbol = &renderEllipseSymbolCairo;
+  renderer->renderVectorSymbol = &renderVectorSymbolCairo;
+  renderer->renderTruetypeSymbol = &renderTruetypeSymbolCairo;
+  renderer->renderSVGSymbol = &renderSVGSymbolCairo;
+  renderer->renderPixmapSymbol = &renderPixmapSymbolCairo;
+  renderer->mergeRasterBuffer = &mergeRasterBufferCairo;
+  renderer->getTruetypeTextBBox = &getTruetypeTextBBoxCairo;
+  renderer->renderTile = &renderTileCairo;
+  renderer->loadImageFromFile = &msLoadMSRasterBufferFromFile;
+  renderer->renderPolygonTiled = &renderPolygonTiledCairo;
+  renderer->freeSymbol = &freeSymbolCairo;
+  renderer->cleanup = &cleanupCairo;
+  return MS_SUCCESS;
 #else
-    msSetError(MS_MISCERR, "Cairo Driver requested but is not built in", 
-            "msPopulateRendererVTableCairoRaster()");
-    return MS_FAILURE;
+  msSetError(MS_MISCERR, "Cairo Driver requested but MapServer is not built in",
+             "msPopulateRendererVTableCairoRaster()");
+  return MS_FAILURE;
 #endif
 }
 
-inline int populateRendererVTableCairoVector( rendererVTableObj *renderer ) {
+inline int populateRendererVTableCairoVector( rendererVTableObj *renderer )
+{
 #ifdef USE_CAIRO
-    renderer->use_imagecache=0;
-    renderer->supports_pixel_buffer=0;
-    renderer->supports_transparent_layers = 1;
-    renderer->default_transform_mode = MS_TRANSFORM_SIMPLIFY;
-    initializeCache(&MS_RENDERER_CACHE(renderer));
-    renderer->startLayer = startLayerVectorCairo;
-    renderer->endLayer = closeLayerVectorCairo;
-    renderer->renderLine=&renderLineCairo;
-    renderer->renderLineTiled = NULL;
-    renderer->createImage=&createImageCairo;
-    renderer->saveImage=&saveImageCairo;
-    renderer->getRasterBufferHandle=&getRasterBufferHandleCairo;
-    renderer->renderPolygon=&renderPolygonCairo;
-    renderer->renderGlyphs=&renderGlyphsCairo;
-    renderer->freeImage=&freeImageCairo;
-    renderer->renderEllipseSymbol = &renderEllipseSymbolCairo;
-    renderer->renderVectorSymbol = &renderVectorSymbolCairo;
-    renderer->renderTruetypeSymbol = &renderTruetypeSymbolCairo;
-    renderer->renderPixmapSymbol = &renderPixmapSymbolCairo;
-    renderer->loadImageFromFile = &msLoadMSRasterBufferFromFile;
-    renderer->mergeRasterBuffer = &mergeRasterBufferCairo;
-    renderer->initializeRasterBuffer = initializeRasterBufferCairo;
-    renderer->getTruetypeTextBBox = &getTruetypeTextBBoxCairo;
-    renderer->renderTile = &renderTileCairo;
-    renderer->renderPolygonTiled = &renderPolygonTiledCairo;
-    renderer->freeSymbol = &freeSymbolCairo;
-    renderer->cleanup = &cleanupCairo;
-    return MS_SUCCESS;
+  renderer->use_imagecache=0;
+  renderer->supports_pixel_buffer=0;
+  renderer->supports_transparent_layers = 1;
+  renderer->supports_svg = 1;
+  renderer->default_transform_mode = MS_TRANSFORM_SIMPLIFY;
+  initializeCache(&MS_RENDERER_CACHE(renderer));
+  renderer->startLayer = startLayerVectorCairo;
+  renderer->endLayer = closeLayerVectorCairo;
+  renderer->renderLine=&renderLineCairo;
+  renderer->renderLineTiled = NULL;
+  renderer->createImage=&createImageCairo;
+  renderer->saveImage=&saveImageCairo;
+  renderer->saveImageBuffer = &saveImageBufferCairo;
+  renderer->getRasterBufferHandle=&getRasterBufferHandleCairo;
+  renderer->renderPolygon=&renderPolygonCairo;
+  renderer->renderGlyphs=&renderGlyphsCairo;
+  renderer->freeImage=&freeImageCairo;
+  renderer->renderEllipseSymbol = &renderEllipseSymbolCairo;
+  renderer->renderVectorSymbol = &renderVectorSymbolCairo;
+  renderer->renderTruetypeSymbol = &renderTruetypeSymbolCairo;
+  renderer->renderSVGSymbol = &renderSVGSymbolCairo;
+  renderer->renderPixmapSymbol = &renderPixmapSymbolCairo;
+  renderer->loadImageFromFile = &msLoadMSRasterBufferFromFile;
+  renderer->mergeRasterBuffer = &mergeRasterBufferCairo;
+  renderer->initializeRasterBuffer = initializeRasterBufferCairo;
+  renderer->getTruetypeTextBBox = &getTruetypeTextBBoxCairo;
+  renderer->renderTile = &renderTileCairo;
+  renderer->renderPolygonTiled = &renderPolygonTiledCairo;
+  renderer->freeSymbol = &freeSymbolCairo;
+  renderer->cleanup = &cleanupCairo;
+  return MS_SUCCESS;
 #else
-    msSetError(MS_MISCERR, "Cairo Driver requested but is not built in", 
-            "msPopulateRendererVTableCairoRaster()");
-    return MS_FAILURE;
+  msSetError(MS_MISCERR, "Cairo Driver requested but MapServer is not built in",
+             "msPopulateRendererVTableCairoRaster()");
+  return MS_FAILURE;
 #endif
 }
 
-int msPopulateRendererVTableCairoSVG( rendererVTableObj *renderer ) {
-    return populateRendererVTableCairoVector(renderer);
+int msPopulateRendererVTableCairoSVG( rendererVTableObj *renderer )
+{
+  return populateRendererVTableCairoVector(renderer);
 }
-int msPopulateRendererVTableCairoPDF( rendererVTableObj *renderer ) {
-    return populateRendererVTableCairoVector(renderer);
+int msPopulateRendererVTableCairoPDF( rendererVTableObj *renderer )
+{
+  return populateRendererVTableCairoVector(renderer);
 }
 
diff --git a/mapchart.c b/mapchart.c
index d4963ee..bcbf257 100644
--- a/mapchart.c
+++ b/mapchart.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -30,7 +30,7 @@
 
 #include "mapserver.h"
 
-MS_CVSID("$Id$")
+
 
 #define MS_CHART_TYPE_PIE 1
 #define MS_CHART_TYPE_BAR 2
@@ -43,510 +43,516 @@ MS_CVSID("$Id$")
 
 /*
 ** find a point on a shape. check if it fits in image
-** returns 
+** returns
 **  MS_SUCCESS and point coordinates in 'p' if chart fits in image
 **  MS_FAILURE if no point could be found
 */
-int findChartPoint(mapObj *map, shapeObj *shape, int width, int height, pointObj *center) {
-    int middle,numpoints,idx,offset;
-    double invcellsize = 1.0/map->cellsize; /*speed up MAP2IMAGE_X/Y_IC_DBL*/
-    switch(shape->type) {
-        case MS_SHAPE_POINT:
-            center->x=MS_MAP2IMAGE_X_IC_DBL(shape->line[0].point[0].x, map->extent.minx, invcellsize);
-            center->y=MS_MAP2IMAGE_Y_IC_DBL(shape->line[0].point[0].y, map->extent.maxy, invcellsize);
-            
-            if(MS_CHART_FITS(center->x,center->y,width,height,map->width,map->height))
-                return MS_SUCCESS;
-            else
-                return MS_FAILURE;
-            break;
-        case MS_SHAPE_LINE:
-            /*loop through line segments starting from middle (alternate between before and after middle point)
-            **first segment that fits is chosen
-            */
-            middle=shape->line[0].numpoints/2; /*start with middle segment of line*/
-            numpoints=shape->line[0].numpoints;
-            for(offset=1;offset<=middle;offset++) {
-                idx=middle+offset;
-                if(idx<numpoints) {
-                    center->x=(shape->line[0].point[idx-1].x+shape->line[0].point[idx].x)/2.;
-                    center->y=(shape->line[0].point[idx-1].y+shape->line[0].point[idx].y)/2.;
-                    center->x=MS_MAP2IMAGE_X_IC_DBL(center->x, map->extent.minx, invcellsize);
-                    center->y=MS_MAP2IMAGE_Y_IC_DBL(center->y, map->extent.maxy, invcellsize);
-
-                    if(MS_CHART_FITS(center->x,center->y,width,height,map->width,map->height))
-                        return MS_SUCCESS;
-                    
-                    break;
-                }
-                idx=middle-offset;
-                if(idx>=0) {
-                    center->x=(shape->line[0].point[idx].x+shape->line[0].point[idx+1].x)/2;
-                    center->y=(shape->line[0].point[idx].y+shape->line[0].point[idx+1].y)/2;
-                    center->x=MS_MAP2IMAGE_X_IC_DBL(center->x, map->extent.minx, invcellsize);
-                    center->y=MS_MAP2IMAGE_Y_IC_DBL(center->y, map->extent.maxy, invcellsize);
-                    
-                    if(MS_CHART_FITS(center->x,center->y,width,height,map->width,map->height))
-                        return MS_SUCCESS;
-                    break;
-                }
-            }
-            return MS_FAILURE;
-        break;
-        case MS_SHAPE_POLYGON:
-            msPolygonLabelPoint(shape, center, -1);
-            center->x=MS_MAP2IMAGE_X_IC_DBL(center->x, map->extent.minx, invcellsize);
-            center->y=MS_MAP2IMAGE_Y_IC_DBL(center->y, map->extent.maxy, invcellsize);
-            
-            if(MS_CHART_FITS(center->x,center->y,width,height,map->width,map->height))
-                return MS_SUCCESS;
-            else
-                return MS_FAILURE;
-            break;
-        default:
-            return MS_FAILURE;
-    }
+int findChartPoint(mapObj *map, shapeObj *shape, int width, int height, pointObj *center)
+{
+  int middle,numpoints,idx,offset;
+  double invcellsize = 1.0/map->cellsize; /*speed up MAP2IMAGE_X/Y_IC_DBL*/
+  switch(shape->type) {
+    case MS_SHAPE_POINT:
+      center->x=MS_MAP2IMAGE_X_IC_DBL(shape->line[0].point[0].x, map->extent.minx, invcellsize);
+      center->y=MS_MAP2IMAGE_Y_IC_DBL(shape->line[0].point[0].y, map->extent.maxy, invcellsize);
+
+      if(MS_CHART_FITS(center->x,center->y,width,height,map->width,map->height))
+        return MS_SUCCESS;
+      else
+        return MS_FAILURE;
+      break;
+    case MS_SHAPE_LINE:
+      /*loop through line segments starting from middle (alternate between before and after middle point)
+      **first segment that fits is chosen
+      */
+      middle=shape->line[0].numpoints/2; /*start with middle segment of line*/
+      numpoints=shape->line[0].numpoints;
+      for(offset=1; offset<=middle; offset++) {
+        idx=middle+offset;
+        if(idx<numpoints) {
+          center->x=(shape->line[0].point[idx-1].x+shape->line[0].point[idx].x)/2.;
+          center->y=(shape->line[0].point[idx-1].y+shape->line[0].point[idx].y)/2.;
+          center->x=MS_MAP2IMAGE_X_IC_DBL(center->x, map->extent.minx, invcellsize);
+          center->y=MS_MAP2IMAGE_Y_IC_DBL(center->y, map->extent.maxy, invcellsize);
+
+          if(MS_CHART_FITS(center->x,center->y,width,height,map->width,map->height))
+            return MS_SUCCESS;
+
+          break;
+        }
+        idx=middle-offset;
+        if(idx>=0) {
+          center->x=(shape->line[0].point[idx].x+shape->line[0].point[idx+1].x)/2;
+          center->y=(shape->line[0].point[idx].y+shape->line[0].point[idx+1].y)/2;
+          center->x=MS_MAP2IMAGE_X_IC_DBL(center->x, map->extent.minx, invcellsize);
+          center->y=MS_MAP2IMAGE_Y_IC_DBL(center->y, map->extent.maxy, invcellsize);
+
+          if(MS_CHART_FITS(center->x,center->y,width,height,map->width,map->height))
+            return MS_SUCCESS;
+          break;
+        }
+      }
+      return MS_FAILURE;
+      break;
+    case MS_SHAPE_POLYGON:
+      msPolygonLabelPoint(shape, center, -1);
+      center->x=MS_MAP2IMAGE_X_IC_DBL(center->x, map->extent.minx, invcellsize);
+      center->y=MS_MAP2IMAGE_Y_IC_DBL(center->y, map->extent.maxy, invcellsize);
+
+      if(MS_CHART_FITS(center->x,center->y,width,height,map->width,map->height))
+        return MS_SUCCESS;
+      else
+        return MS_FAILURE;
+      break;
+    default:
+      return MS_FAILURE;
+  }
 }
 
 void drawRectangle(mapObj *map, imageObj *image, float mx, float my, float Mx, float My,
-        styleObj *style) {
-	shapeObj shape;
-	lineObj line;
-	pointObj point[5];
-	line.point = point;
-	line.numpoints = 5;
-	shape.line = &line;
-	shape.numlines = 1;
-	
-	point[0].x = point[4].x = point[3].x = mx;
-	point[0].y = point[4].y = point[1].y = my;
-	point[1].x = point[2].x = Mx;
-	point[2].y = point[3].y = My;
-	
-	msDrawShadeSymbol(&map->symbolset,image,&shape,style,1.0);
+                   styleObj *style)
+{
+  shapeObj shape;
+  lineObj line;
+  pointObj point[5];
+  line.point = point;
+  line.numpoints = 5;
+  shape.line = &line;
+  shape.numlines = 1;
+
+  point[0].x = point[4].x = point[3].x = mx;
+  point[0].y = point[4].y = point[1].y = my;
+  point[1].x = point[2].x = Mx;
+  point[2].y = point[3].y = My;
+
+  msDrawShadeSymbol(&map->symbolset,image,&shape,style,1.0);
 }
 
 int msDrawVBarChart(mapObj *map, imageObj *image, pointObj *center,
-        float *values, styleObj **styles, int numvalues,            
-        float barWidth)
+                    float *values, styleObj **styles, int numvalues,
+                    float barWidth)
 {
 
-    int c;
-    float left,bottom,cur; /*shortcut to pixel boundaries of the chart*/
-    float height = 0; 
+  int c;
+  float left,bottom,cur; /*shortcut to pixel boundaries of the chart*/
+  float height = 0;
 
-    for(c=0;c<numvalues;c++)
-    {
-        height += values[c];
-    }
+  for(c=0; c<numvalues; c++) {
+    height += values[c];
+  }
 
-    cur = bottom = center->y+height/2.;
-    left = center->x-barWidth/2.;
-     
-    for(c=0;c<numvalues;c++)
-    {
-        drawRectangle(map, image, left, cur, left+barWidth, cur-values[c], styles[c]);
-        cur -= values[c];
-    }
-    return MS_SUCCESS;
+  cur = bottom = center->y+height/2.;
+  left = center->x-barWidth/2.;
+
+  for(c=0; c<numvalues; c++) {
+    drawRectangle(map, image, left, cur, left+barWidth, cur-values[c], styles[c]);
+    cur -= values[c];
+  }
+  return MS_SUCCESS;
 }
 
 
 int msDrawBarChart(mapObj *map, imageObj *image, pointObj *center,
-        float *values, styleObj **styles, int numvalues,            
-        float width, float height, float *maxVal, float *minVal, float barWidth)
+                   float *values, styleObj **styles, int numvalues,
+                   float width, float height, float *maxVal, float *minVal, float barWidth)
 {
 
-    float upperLimit,lowerLimit;
-    float shapeMaxVal,shapeMinVal,pixperval;
-    int c;
-    float vertOrigin,vertOriginClipped,horizStart,y;
-    float left,top,bottom; /*shortcut to pixel boundaries of the chart*/
-    
-    top=center->y-height/2.;
-    bottom=center->y+height/2.;
-    left=center->x-width/2.;
-
-    shapeMaxVal=shapeMinVal=values[0];
-    for(c=1;c<numvalues;c++)
-    {
-        if(maxVal==NULL || minVal==NULL) { /*compute bounds if not specified*/
-            if(values[c]>shapeMaxVal)
-                shapeMaxVal=values[c];
-            if(values[c]<shapeMinVal)
-                shapeMinVal=values[c];
-        }
+  float upperLimit,lowerLimit;
+  float shapeMaxVal,shapeMinVal,pixperval;
+  int c;
+  float vertOrigin,vertOriginClipped,horizStart,y;
+  float left,top,bottom; /*shortcut to pixel boundaries of the chart*/
+
+  top=center->y-height/2.;
+  bottom=center->y+height/2.;
+  left=center->x-width/2.;
+
+  shapeMaxVal=shapeMinVal=values[0];
+  for(c=1; c<numvalues; c++) {
+    if(maxVal==NULL || minVal==NULL) { /*compute bounds if not specified*/
+      if(values[c]>shapeMaxVal)
+        shapeMaxVal=values[c];
+      if(values[c]<shapeMinVal)
+        shapeMinVal=values[c];
     }
-    
-    /*
-     * use specified bounds if wanted
-     * if not, always show the origin
-     */
-    upperLimit = (maxVal!=NULL)? *maxVal : MS_MAX(shapeMaxVal,0);
-    lowerLimit = (minVal!=NULL)? *minVal : MS_MIN(shapeMinVal,0);
-    if(upperLimit==lowerLimit) {
-      /* treat the case where we would have an unspecified behavior */
-      upperLimit+=0.5;
-      lowerLimit-=0.5;
-    }
-    
-    pixperval=(float)height/(upperLimit-lowerLimit);
-    vertOrigin=bottom+lowerLimit*pixperval;
-    vertOriginClipped=(vertOrigin<top) ? top : 
-                        (vertOrigin>bottom) ? bottom : vertOrigin;
-    horizStart=left;
-    /*
-    color = gdImageColorAllocate(image->img.gd, 0,0,0);
-    gdImageRectangle(image->img.gd, left-1,top-1, center.x+width/2.+1,bottom+1,color);
-    */
-    for(c=0;c<numvalues;c++)
-    {
-        int barHeight=values[c]*pixperval;
-        /*clip bars*/
-        y=((vertOrigin-barHeight)<top) ? top : 
-            (vertOrigin-barHeight>bottom) ? bottom : vertOrigin-barHeight;
-        if(y!=vertOriginClipped) { /*don't draw bars of height == 0 (i.e. either values==0, or clipped)*/
-            if(values[c]>0) 
-                drawRectangle(map, image, horizStart, y, horizStart+barWidth-1, vertOriginClipped, styles[c]);
-            else
-                drawRectangle(map,image, horizStart, vertOriginClipped, horizStart+barWidth-1 , y, styles[c]);
-        }
-        horizStart+=barWidth;
+  }
+
+  /*
+   * use specified bounds if wanted
+   * if not, always show the origin
+   */
+  upperLimit = (maxVal!=NULL)? *maxVal : MS_MAX(shapeMaxVal,0);
+  lowerLimit = (minVal!=NULL)? *minVal : MS_MIN(shapeMinVal,0);
+  if(upperLimit==lowerLimit) {
+    /* treat the case where we would have an unspecified behavior */
+    upperLimit+=0.5;
+    lowerLimit-=0.5;
+  }
+
+  pixperval=(float)height/(upperLimit-lowerLimit);
+  vertOrigin=bottom+lowerLimit*pixperval;
+  vertOriginClipped=(vertOrigin<top) ? top :
+                    (vertOrigin>bottom) ? bottom : vertOrigin;
+  horizStart=left;
+  /*
+  color = gdImageColorAllocate(image->img.gd, 0,0,0);
+  gdImageRectangle(image->img.gd, left-1,top-1, center.x+width/2.+1,bottom+1,color);
+  */
+  for(c=0; c<numvalues; c++) {
+    int barHeight=values[c]*pixperval;
+    /*clip bars*/
+    y=((vertOrigin-barHeight)<top) ? top :
+      (vertOrigin-barHeight>bottom) ? bottom : vertOrigin-barHeight;
+    if(y!=vertOriginClipped) { /*don't draw bars of height == 0 (i.e. either values==0, or clipped)*/
+      if(values[c]>0)
+        drawRectangle(map, image, horizStart, y, horizStart+barWidth-1, vertOriginClipped, styles[c]);
+      else
+        drawRectangle(map,image, horizStart, vertOriginClipped, horizStart+barWidth-1 , y, styles[c]);
     }
-    return MS_SUCCESS;
+    horizStart+=barWidth;
+  }
+  return MS_SUCCESS;
 }
 
 int msDrawPieChart(mapObj *map, imageObj *image,
-        pointObj *center, float diameter,
-        float *values, styleObj **styles, int numvalues)
+                   pointObj *center, float diameter,
+                   float *values, styleObj **styles, int numvalues)
 {
-    int i;
-    double dTotal=0.,start=0;
+  int i;
+  double dTotal=0.,start=0;
 
-    for(i=0;i<numvalues;i++)
-    {
-        if(values[i]<0.) {
-            msSetError(MS_MISCERR, "cannot draw pie charts for negative values", "msDrawPieChart()");
-            return MS_FAILURE;
-        }
-        dTotal+=values[i];
+  for(i=0; i<numvalues; i++) {
+    if(values[i]<0.) {
+      msSetError(MS_MISCERR, "cannot draw pie charts for negative values", "msDrawPieChart()");
+      return MS_FAILURE;
     }
-
-    for(i=0; i < numvalues; i++)
-    {
-        float angle = values[i];
-        if(angle==0) continue; /*no need to draw. causes artifacts with outlines*/
-        angle*=360.0/dTotal;
-        msDrawPieSlice(&map->symbolset,image, center, styles[i], diameter/2., start, start+angle);
-        
-        start+=angle;
-    }
-    return MS_SUCCESS;
+    dTotal+=values[i];
+  }
+
+  for(i=0; i < numvalues; i++) {
+    float angle = values[i];
+    if(angle==0) continue; /*no need to draw. causes artifacts with outlines*/
+    angle*=360.0/dTotal;
+    msDrawPieSlice(&map->symbolset,image, center, styles[i], diameter/2., start, start+angle);
+
+    start+=angle;
+  }
+  return MS_SUCCESS;
 }
 
-int getNextShape(mapObj *map, layerObj *layer, float *values, styleObj **styles, shapeObj *shape) {
-    int status;
-    int c;
-    status = msLayerNextShape(layer, shape);
-    if(status == MS_SUCCESS) {
+int getNextShape(mapObj *map, layerObj *layer, float *values, int *nvalues, styleObj **styles, shapeObj *shape)
+{
+  int status;
+  int c;
+  status = msLayerNextShape(layer, shape);
+  if(status == MS_SUCCESS) {
 #ifdef USE_PROJ
-        if(layer->project && msProjectionsDiffer(&(layer->projection), &(map->projection)))
-            msProjectShape(&layer->projection, &map->projection, shape);
-        else
-            layer->project = MS_FALSE;
+    if(layer->project && msProjectionsDiffer(&(layer->projection), &(map->projection)))
+      msProjectShape(&layer->projection, &map->projection, shape);
+    else
+      layer->project = MS_FALSE;
 #endif
 
-        if(msBindLayerToShape(layer, shape, MS_FALSE) != MS_SUCCESS)
-            return MS_FAILURE; /* error message is set in msBindLayerToShape() */
+    if(msBindLayerToShape(layer, shape, MS_DRAWMODE_FEATURES|MS_DRAWMODE_LABELS) != MS_SUCCESS)
+      return MS_FAILURE; /* error message is set in msBindLayerToShape() */
 
-        for(c=0;c<layer->numclasses;c++)
-        {
-            values[c]=(layer->class[c]->styles[0]->size);
-            styles[c]=layer->class[c]->styles[0];
-        }
+    *nvalues = 0;
+    for(c=0; c<layer->numclasses; c++) {
+      if(msEvalExpression(layer, shape, &(layer->class[c]->expression), layer->classitemindex) == MS_TRUE) {
+        values[*nvalues]=(layer->class[c]->styles[0]->size);
+        styles[*nvalues]=layer->class[c]->styles[0];
+        (*nvalues)++;
+      }
     }
-    return status;
+  }
+  return status;
 }
 
 /* eventually add a class to the layer to get the diameter from an attribute */
-int pieLayerProcessDynamicDiameter(layerObj *layer) {
-    const char *chartRangeProcessingKey=NULL;
-    char *attrib;
-    float mindiameter=-1, maxdiameter, minvalue, maxvalue;
-    classObj *newclass;
-    styleObj *newstyle;
-    const char *chartSizeProcessingKey=msLayerGetProcessingKey( layer,"CHART_SIZE" );
-    if(chartSizeProcessingKey != NULL)
-        return MS_FALSE;
-    chartRangeProcessingKey=msLayerGetProcessingKey( layer,"CHART_SIZE_RANGE" );
-    if(chartRangeProcessingKey==NULL)
-        return MS_FALSE;
-    attrib = msSmallMalloc(strlen(chartRangeProcessingKey)+1);
-    switch(sscanf(chartRangeProcessingKey,"%s %f %f %f %f",attrib,
-                &mindiameter,&maxdiameter,&minvalue,&maxvalue))
-    {
-        case 1: /*we only have the attribute*/
-        case 5: /*we have the attribute and the four range values*/
-            break;
-        default:
-            free(attrib);
-            msSetError(MS_MISCERR, "Chart Layer format error for processing key \"CHART_RANGE\"", "msDrawChartLayer()");
-            return MS_FAILURE;
-    }
-    /*create a new class in the layer containing the wanted attribute
-     * as the SIZE of its first STYLE*/
-    newclass=msGrowLayerClasses(layer);
-    if(newclass==NULL) {
-        free(attrib);
-        return MS_FAILURE;
-    }
-    initClass(newclass);
-    layer->numclasses++;
-
-    /*create and attach a new styleObj to our temp class
-     * and bind the wanted attribute to its SIZE
-     */
-    newstyle=msGrowClassStyles(newclass);
-    if(newstyle==NULL) {
-        free(attrib);
-        return MS_FAILURE;
-    }
-    initStyle(newstyle);
-    newclass->numstyles++;
-    newclass->name=(char*)msStrdup("__MS_SIZE_ATTRIBUTE_");
-    newstyle->bindings[MS_STYLE_BINDING_SIZE].item=msStrdup(attrib);
-    newstyle->numbindings++;
+int pieLayerProcessDynamicDiameter(layerObj *layer)
+{
+  const char *chartRangeProcessingKey=NULL;
+  char *attrib;
+  float mindiameter=-1, maxdiameter, minvalue, maxvalue;
+  classObj *newclass;
+  styleObj *newstyle;
+  const char *chartSizeProcessingKey=msLayerGetProcessingKey( layer,"CHART_SIZE" );
+  if(chartSizeProcessingKey != NULL)
+    return MS_FALSE;
+  chartRangeProcessingKey=msLayerGetProcessingKey( layer,"CHART_SIZE_RANGE" );
+  if(chartRangeProcessingKey==NULL)
+    return MS_FALSE;
+  attrib = msSmallMalloc(strlen(chartRangeProcessingKey)+1);
+  switch(sscanf(chartRangeProcessingKey,"%s %f %f %f %f",attrib,
+                &mindiameter,&maxdiameter,&minvalue,&maxvalue)) {
+    case 1: /*we only have the attribute*/
+    case 5: /*we have the attribute and the four range values*/
+      break;
+    default:
+      free(attrib);
+      msSetError(MS_MISCERR, "Chart Layer format error for processing key \"CHART_RANGE\"", "msDrawChartLayer()");
+      return MS_FAILURE;
+  }
+  /*create a new class in the layer containing the wanted attribute
+   * as the SIZE of its first STYLE*/
+  newclass=msGrowLayerClasses(layer);
+  if(newclass==NULL) {
+    free(attrib);
+    return MS_FAILURE;
+  }
+  initClass(newclass);
+  layer->numclasses++;
+
+  /*create and attach a new styleObj to our temp class
+   * and bind the wanted attribute to its SIZE
+   */
+  newstyle=msGrowClassStyles(newclass);
+  if(newstyle==NULL) {
     free(attrib);
+    return MS_FAILURE;
+  }
+  initStyle(newstyle);
+  newclass->numstyles++;
+  newclass->name=(char*)msStrdup("__MS_SIZE_ATTRIBUTE_");
+  newstyle->bindings[MS_STYLE_BINDING_SIZE].item=msStrdup(attrib);
+  newstyle->numbindings++;
+  free(attrib);
 
-    return MS_TRUE;
+  return MS_TRUE;
 
 }
 
 
 int msDrawPieChartLayer(mapObj *map, layerObj *layer, imageObj *image)
 {
-    shapeObj    shape;
-    int         status=MS_SUCCESS;
-    const char *chartRangeProcessingKey=NULL;
-    const char *chartSizeProcessingKey=msLayerGetProcessingKey( layer,"CHART_SIZE" );
-    float diameter, mindiameter=-1, maxdiameter, minvalue, maxvalue;
-    float *values;
-    styleObj **styles;
-    pointObj center;
-    int numvalues = layer->numclasses; //the number of classes to represent in the graph
-    if(chartSizeProcessingKey==NULL)
-    {
-        chartRangeProcessingKey=msLayerGetProcessingKey( layer,"CHART_SIZE_RANGE" );
-        if(chartRangeProcessingKey==NULL)
-            diameter=20;
-        else {
-            sscanf(chartRangeProcessingKey,"%*s %f %f %f %f",
-                &mindiameter,&maxdiameter,&minvalue,&maxvalue);
-        }
+  shapeObj    shape;
+  int         status=MS_SUCCESS;
+  const char *chartRangeProcessingKey=NULL;
+  const char *chartSizeProcessingKey=msLayerGetProcessingKey( layer,"CHART_SIZE" );
+  float diameter, mindiameter=-1, maxdiameter, minvalue, maxvalue, exponent=0;
+  float *values;
+  styleObj **styles;
+  pointObj center;
+  int numvalues = layer->numclasses; /* the number of classes to represent in the graph */
+  int numvalues_for_shape = 0;
+
+  if(chartSizeProcessingKey==NULL) {
+    chartRangeProcessingKey=msLayerGetProcessingKey( layer,"CHART_SIZE_RANGE" );
+    if(chartRangeProcessingKey==NULL)
+      diameter=20;
+    else {
+      sscanf(chartRangeProcessingKey,"%*s %f %f %f %f %f",
+             &mindiameter,&maxdiameter,&minvalue,&maxvalue,&exponent);
     }
-    else
-    {
-        if(sscanf(chartSizeProcessingKey ,"%f",&diameter)!=1) {
-            msSetError(MS_MISCERR, "msDrawChart format error for processing key \"CHART_SIZE\"", "msDrawPieChartLayer()");
-            return MS_FAILURE;
-        }
+  } else {
+    if(sscanf(chartSizeProcessingKey ,"%f",&diameter)!=1) {
+      msSetError(MS_MISCERR, "msDrawChart format error for processing key \"CHART_SIZE\"", "msDrawPieChartLayer()");
+      return MS_FAILURE;
     }
-    /* step through the target shapes */
-    msInitShape(&shape);
-
-    values=(float*)calloc(numvalues,sizeof(float));
-    MS_CHECK_ALLOC(values, numvalues*sizeof(float), MS_FAILURE);
-    styles = (styleObj**)malloc((numvalues)*sizeof(styleObj*));
-    if (styles == NULL)
-    {
-        msSetError(MS_MEMERR, "%s: %d: Out of memory allocating %u bytes.\n", "msDrawPieChartLayer()",
-                   __FILE__, __LINE__, numvalues*sizeof(styleObj*)); 
-        free(values);
-        return MS_FAILURE;
+  }
+  /* step through the target shapes */
+  msInitShape(&shape);
+
+  values=(float*)calloc(numvalues,sizeof(float));
+  MS_CHECK_ALLOC(values, numvalues*sizeof(float), MS_FAILURE);
+  styles = (styleObj**)malloc((numvalues)*sizeof(styleObj*));
+  if (styles == NULL) {
+    msSetError(MS_MEMERR, "%s: %d: Out of memory allocating %u bytes.\n", "msDrawPieChartLayer()",
+               __FILE__, __LINE__, numvalues*sizeof(styleObj*));
+    free(values);
+    return MS_FAILURE;
+  }
+
+  while(MS_SUCCESS == getNextShape(map,layer,values,&numvalues_for_shape,styles,&shape)) {
+    if(chartRangeProcessingKey!=NULL)
+      numvalues_for_shape--;
+    if(numvalues_for_shape == 0) {
+      msFreeShape(&shape);
+      continue;
     }
-
-    if(chartRangeProcessingKey!=NULL) 
-        numvalues--;
-    while(MS_SUCCESS == getNextShape(map,layer,values,styles,&shape)) {
-        msDrawStartShape(map, layer, image, &shape);
-        if(chartRangeProcessingKey!=NULL) {
-            diameter = values[numvalues];
-            if(mindiameter>=0) {
-                if(diameter<=minvalue)
-                    diameter=mindiameter;
-                else if(diameter>=maxvalue)
-                    diameter=maxdiameter;
-                else {
-                    diameter=MS_NINT(
-                            mindiameter+
-                            ((diameter-minvalue)/(maxvalue-minvalue))*
-                            (maxdiameter-mindiameter)
-                    );
-                }
-            }
-        }
-        if(findChartPoint(map, &shape, diameter, diameter, &center) == MS_SUCCESS) {
-            status = msDrawPieChart(map,image, &center, diameter,
-                values,styles,numvalues);
+    msDrawStartShape(map, layer, image, &shape);
+    if(chartRangeProcessingKey!=NULL) {
+      diameter = values[numvalues_for_shape];
+      if(mindiameter>=0) {
+        if(diameter<=minvalue)
+          diameter=mindiameter;
+        else if(diameter>=maxvalue)
+          diameter=maxdiameter;
+        else {
+          if (exponent <= 0)
+            diameter=MS_NINT(
+                       mindiameter+
+                       ((diameter-minvalue)/(maxvalue-minvalue))*
+                       (maxdiameter-mindiameter)
+                     );
+          else
+            diameter=MS_NINT(
+                       mindiameter+
+                       pow((diameter-minvalue)/(maxvalue-minvalue),1.0/exponent)*
+                       (maxdiameter-mindiameter)
+                     );
         }
-        msDrawEndShape(map,layer,image,&shape);
-        msFreeShape(&shape);
+      }
     }
-    free(values);
-    free(styles);
-    return status;
+    if(findChartPoint(map, &shape, diameter, diameter, &center) == MS_SUCCESS) {
+      status = msDrawPieChart(map,image, &center, diameter,
+                              values,styles,numvalues_for_shape);
+    }
+    msDrawEndShape(map,layer,image,&shape);
+    msFreeShape(&shape);
+  }
+  free(values);
+  free(styles);
+  return status;
 }
 
 int msDrawVBarChartLayer(mapObj *map, layerObj *layer, imageObj *image)
 {
-    shapeObj    shape;
-    int         status=MS_SUCCESS;
-    const char *chartSizeProcessingKey=msLayerGetProcessingKey( layer,"CHART_SIZE" );
-    const char *chartScaleProcessingKey=msLayerGetProcessingKey( layer,"CHART_SCALE" );
-    float barWidth,scale=1.0;
-    float *values;
-    styleObj **styles;
-    pointObj center;
-    int numvalues = layer->numclasses; 
-    if(chartSizeProcessingKey==NULL)
-    {
-        barWidth=20;
+  shapeObj    shape;
+  int         status=MS_SUCCESS;
+  const char *chartSizeProcessingKey=msLayerGetProcessingKey( layer,"CHART_SIZE" );
+  const char *chartScaleProcessingKey=msLayerGetProcessingKey( layer,"CHART_SCALE" );
+  float barWidth,scale=1.0;
+  float *values;
+  styleObj **styles;
+  pointObj center;
+  int numvalues = layer->numclasses;
+  int numvalues_for_shape;
+  if(chartSizeProcessingKey==NULL) {
+    barWidth=20;
+  } else {
+    if(sscanf(chartSizeProcessingKey ,"%f",&barWidth) != 1) {
+      msSetError(MS_MISCERR, "msDrawChart format error for processing key \"CHART_SIZE\"", "msDrawVBarChartLayer()");
+      return MS_FAILURE;
     }
-    else
-    {
-        if(sscanf(chartSizeProcessingKey ,"%f",&barWidth) != 1) {
-            msSetError(MS_MISCERR, "msDrawChart format error for processing key \"CHART_SIZE\"", "msDrawVBarChartLayer()");
-            return MS_FAILURE;
-        }
+  }
+
+  if(chartScaleProcessingKey) {
+    if(sscanf(chartScaleProcessingKey,"%f",&scale)!=1) {
+      msSetError(MS_MISCERR, "Error reading value for processing key \"CHART_SCALE\"", "msDrawVBarChartLayer()");
+      return MS_FAILURE;
     }
+  }
+  msInitShape(&shape);
+
+  values=(float*)calloc(numvalues,sizeof(float));
+  MS_CHECK_ALLOC(values, numvalues*sizeof(float), MS_FAILURE);
+  styles = (styleObj**)malloc(numvalues*sizeof(styleObj*));
+  if (styles == NULL) {
+    msSetError(MS_MEMERR, "%s: %d: Out of memory allocating %u bytes.\n", "msDrawVBarChartLayer()",
+               __FILE__, __LINE__, numvalues*sizeof(styleObj*));
+    free(values);
+    return MS_FAILURE;
+  }
 
-    if(chartScaleProcessingKey){
-        if(sscanf(chartScaleProcessingKey,"%f",&scale)!=1) {
-            msSetError(MS_MISCERR, "Error reading value for processing key \"CHART_SCALE\"", "msDrawVBarChartLayer()");
-            return MS_FAILURE;
-        }
+  while(MS_SUCCESS == getNextShape(map,layer,values,&numvalues_for_shape,styles,&shape)) {
+    int i;
+    double h=0;
+    if(numvalues_for_shape == 0) {
+      continue;
     }
-    msInitShape(&shape);
-
-    values=(float*)calloc(numvalues,sizeof(float));
-    MS_CHECK_ALLOC(values, numvalues*sizeof(float), MS_FAILURE);
-    styles = (styleObj**)malloc(numvalues*sizeof(styleObj*));
-    if (styles == NULL)
-    {
-        msSetError(MS_MEMERR, "%s: %d: Out of memory allocating %u bytes.\n", "msDrawVBarChartLayer()",
-                   __FILE__, __LINE__, numvalues*sizeof(styleObj*)); 
-        free(values);
-        return MS_FAILURE;
+    for(i=0; i<numvalues_for_shape; i++) {
+      values[i]*=scale;
+      h += values[i];
     }
-
-    while(MS_SUCCESS == getNextShape(map,layer,values,styles,&shape)) {
-        int i;
-        double h=0;
-        for(i=0;i<numvalues;i++) {
-            values[i]*=scale;
-            h += values[i];
-        }
-        msDrawStartShape(map, layer, image, &shape);
-        if(findChartPoint(map, &shape, barWidth,h, &center)==MS_SUCCESS) {
-            status = msDrawVBarChart(map,image,
-                &center,
-                values, styles, numvalues,
-                barWidth);
-        }
-        msDrawEndShape(map,layer,image,&shape);
-        msFreeShape(&shape);
+    msDrawStartShape(map, layer, image, &shape);
+    if(findChartPoint(map, &shape, barWidth,h, &center)==MS_SUCCESS) {
+      status = msDrawVBarChart(map,image,
+                               &center,
+                               values, styles, numvalues_for_shape,
+                               barWidth);
     }
-    free(values);
-    free(styles);
-    return status;
+    msDrawEndShape(map,layer,image,&shape);
+    msFreeShape(&shape);
+  }
+  free(values);
+  free(styles);
+  return status;
 }
 
 
 int msDrawBarChartLayer(mapObj *map, layerObj *layer, imageObj *image)
 {
-    shapeObj    shape;
-    int         status=MS_SUCCESS;
-    const char *chartSizeProcessingKey=msLayerGetProcessingKey( layer,"CHART_SIZE" );
-    const char *barMax=msLayerGetProcessingKey( layer,"CHART_BAR_MAXVAL" );
-    const char *barMin=msLayerGetProcessingKey( layer,"CHART_BAR_MINVAL" );
-    float width,height;
-    float barWidth;
-    float *values;
-    styleObj **styles;
-    pointObj center;
-    float barMaxVal,barMinVal;
-    int numvalues = layer->numclasses; 
-    if(chartSizeProcessingKey==NULL)
-    {
-        width=height=20;
-    }
-    else
-    {
-        switch(sscanf(chartSizeProcessingKey ,"%f %f",&width,&height)) {
-            case 2:
-                break;
-            case 1:
-                height = width;
-                break;
-            default:
-                msSetError(MS_MISCERR, "msDrawChart format error for processing key \"CHART_SIZE\"", "msDrawBarChartLayer()");
-                return MS_FAILURE;
-        }
-    }
-
-    if(barMax){
-        if(sscanf(barMax,"%f",&barMaxVal)!=1) {
-            msSetError(MS_MISCERR, "Error reading value for processing key \"CHART_BAR_MAXVAL\"", "msDrawBarChartLayer()");
-            return MS_FAILURE;
-        }
-    }
-    if(barMin) {
-        if(sscanf(barMin,"%f",&barMinVal)!=1) {
-            msSetError(MS_MISCERR, "Error reading value for processing key \"CHART_BAR_MINVAL\"", "msDrawBarChartLayer()");
-            return MS_FAILURE;
-        }
-    }
-    if(barMin && barMax && barMinVal>=barMaxVal) {
-        msSetError(MS_MISCERR, "\"CHART_BAR_MINVAL\" must be less than \"CHART_BAR_MAXVAL\"", "msDrawBarChartLayer()");
-        return MS_FAILURE;
-    }
-    barWidth=(float)width/(float)layer->numclasses;
-    if(!barWidth)
-    {
-        msSetError(MS_MISCERR, "Specified width of chart too small to fit given number of classes", "msDrawBarChartLayer()");
+  shapeObj    shape;
+  int         status=MS_SUCCESS;
+  const char *chartSizeProcessingKey=msLayerGetProcessingKey( layer,"CHART_SIZE" );
+  const char *barMax=msLayerGetProcessingKey( layer,"CHART_BAR_MAXVAL" );
+  const char *barMin=msLayerGetProcessingKey( layer,"CHART_BAR_MINVAL" );
+  float width,height;
+  float barWidth;
+  float *values;
+  styleObj **styles;
+  pointObj center;
+  float barMaxVal,barMinVal;
+  int numvalues = layer->numclasses;
+  int numvalues_for_shape;
+  if(chartSizeProcessingKey==NULL) {
+    width=height=20;
+  } else {
+    switch(sscanf(chartSizeProcessingKey ,"%f %f",&width,&height)) {
+      case 2:
+        break;
+      case 1:
+        height = width;
+        break;
+      default:
+        msSetError(MS_MISCERR, "msDrawChart format error for processing key \"CHART_SIZE\"", "msDrawBarChartLayer()");
         return MS_FAILURE;
     }
+  }
 
-    msInitShape(&shape);
-
-    values=(float*)calloc(numvalues,sizeof(float));
-    MS_CHECK_ALLOC(values, numvalues*sizeof(float), MS_FAILURE);
-    styles = (styleObj**)malloc(numvalues*sizeof(styleObj*));
-    if (styles == NULL)
-    {
-        msSetError(MS_MEMERR, "%s: %d: Out of memory allocating %u bytes.\n", "msDrawBarChartLayer()",
-                   __FILE__, __LINE__, numvalues*sizeof(styleObj*)); 
-        free(values);
-        return MS_FAILURE;
+  if(barMax) {
+    if(sscanf(barMax,"%f",&barMaxVal)!=1) {
+      msSetError(MS_MISCERR, "Error reading value for processing key \"CHART_BAR_MAXVAL\"", "msDrawBarChartLayer()");
+      return MS_FAILURE;
     }
-
-    while(MS_SUCCESS == getNextShape(map,layer,values,styles,&shape)) {
-        msDrawStartShape(map, layer, image, &shape);
-        if(findChartPoint(map, &shape, width,height, &center)==MS_SUCCESS) {
-            status = msDrawBarChart(map,image,
-                &center,
-                values, styles, numvalues,
-                width,height,
-                (barMax!=NULL)?&barMaxVal:NULL,
-                (barMin!=NULL)?&barMinVal:NULL,
-                barWidth);
-        }
-        msDrawEndShape(map,layer,image,&shape);
-        msFreeShape(&shape);
+  }
+  if(barMin) {
+    if(sscanf(barMin,"%f",&barMinVal)!=1) {
+      msSetError(MS_MISCERR, "Error reading value for processing key \"CHART_BAR_MINVAL\"", "msDrawBarChartLayer()");
+      return MS_FAILURE;
     }
+  }
+  if(barMin && barMax && barMinVal>=barMaxVal) {
+    msSetError(MS_MISCERR, "\"CHART_BAR_MINVAL\" must be less than \"CHART_BAR_MAXVAL\"", "msDrawBarChartLayer()");
+    return MS_FAILURE;
+  }
+  barWidth=(float)width/(float)layer->numclasses;
+  if(!barWidth) {
+    msSetError(MS_MISCERR, "Specified width of chart too small to fit given number of classes", "msDrawBarChartLayer()");
+    return MS_FAILURE;
+  }
+
+  msInitShape(&shape);
+
+  values=(float*)calloc(numvalues,sizeof(float));
+  MS_CHECK_ALLOC(values, numvalues*sizeof(float), MS_FAILURE);
+  styles = (styleObj**)malloc(numvalues*sizeof(styleObj*));
+  if (styles == NULL) {
+    msSetError(MS_MEMERR, "%s: %d: Out of memory allocating %u bytes.\n", "msDrawBarChartLayer()",
+               __FILE__, __LINE__, numvalues*sizeof(styleObj*));
     free(values);
-    free(styles);
-    return status;
+    return MS_FAILURE;
+  }
+
+  while(MS_SUCCESS == getNextShape(map,layer,values,&numvalues_for_shape,styles,&shape)) {
+    if(numvalues_for_shape == 0 ) continue;
+    msDrawStartShape(map, layer, image, &shape);
+    if(findChartPoint(map, &shape, width,height, &center)==MS_SUCCESS) {
+      status = msDrawBarChart(map,image,
+                              &center,
+                              values, styles, numvalues_for_shape,
+                              width,height,
+                              (barMax!=NULL)?&barMaxVal:NULL,
+                              (barMin!=NULL)?&barMinVal:NULL,
+                              barWidth);
+    }
+    msDrawEndShape(map,layer,image,&shape);
+    msFreeShape(&shape);
+  }
+  free(values);
+  free(styles);
+  return status;
 }
 
 /**
@@ -555,88 +561,79 @@ int msDrawBarChartLayer(mapObj *map, layerObj *layer, imageObj *image)
 int msDrawChartLayer(mapObj *map, layerObj *layer, imageObj *image)
 {
 
-    rectObj     searchrect;
-    const char *chartTypeProcessingKey=msLayerGetProcessingKey( layer,"CHART_TYPE" );
-    int chartType=MS_CHART_TYPE_PIE;
-    int status = MS_FAILURE;
-    
-    if (image && map && layer)
-    {
-        if( !(MS_RENDERER_PLUGIN(image->format) )) {
-            msSetError(MS_MISCERR, "chart drawing currently only supports GD and AGG renderers", "msDrawChartLayer()");
-            return MS_FAILURE;
-        }
-        
-        if( layer->numclasses < 2 ) {
-            msSetError(MS_MISCERR,"chart drawing requires at least 2 classes in layer", "msDrawChartLayer()");
-            return MS_FAILURE;
-        }
-    
-        if(chartTypeProcessingKey!=NULL) {
-            if( strcasecmp(chartTypeProcessingKey,"PIE") == 0 ) {
-                chartType=MS_CHART_TYPE_PIE;
-            }
-            else if( strcasecmp(chartTypeProcessingKey,"BAR") == 0 ) {
-                chartType=MS_CHART_TYPE_BAR;
-            }
-            else if( strcasecmp(chartTypeProcessingKey,"VBAR") == 0 ) {
-                chartType=MS_CHART_TYPE_VBAR;
-            }
-            else {
-                msSetError(MS_MISCERR,"unknown chart type for processing key \"CHART_TYPE\", must be one of \"PIE\" or \"BAR\"", "msDrawChartLayer()");
-                return MS_FAILURE;
-            }
-        }
-        if(chartType == MS_CHART_TYPE_PIE) {
-            pieLayerProcessDynamicDiameter(layer);
-        }
-            
-        /* open this layer */
-        status = msLayerOpen(layer);
-        if(status != MS_SUCCESS) return MS_FAILURE;
-    
-        status = msLayerWhichItems(layer, MS_FALSE, NULL);
-        if(status != MS_SUCCESS) {
-            msLayerClose(layer);
-            return MS_FAILURE;
-        }
-        /* identify target shapes */
-        if(layer->transform == MS_TRUE)
-            searchrect = map->extent;
-        else {
-            searchrect.minx = searchrect.miny = 0;
-            searchrect.maxx = map->width-1;
-            searchrect.maxy = map->height-1;
-        }
-    
-    #ifdef USE_PROJ
-        if((map->projection.numargs > 0) && (layer->projection.numargs > 0))
-            msProjectRect(&map->projection, &layer->projection, &searchrect); /* project the searchrect to source coords */
-    #endif
-        
-        status = msLayerWhichShapes(layer, searchrect, MS_FALSE);
-        if(status == MS_DONE) { /* no overlap */
-            msLayerClose(layer);
-            return MS_SUCCESS;
-        } else if(status != MS_SUCCESS) {
-            msLayerClose(layer);
-            return MS_FAILURE;
-        }
-        switch(chartType) {
-            case MS_CHART_TYPE_PIE:
-                status = msDrawPieChartLayer(map, layer, image);
-                break;
-            case MS_CHART_TYPE_BAR:
-                status = msDrawBarChartLayer(map, layer, image);
-                break;
-            case MS_CHART_TYPE_VBAR:
-                status = msDrawVBarChartLayer(map, layer, image);
-                break;
-            default:
-                return MS_FAILURE;/*shouldn't be here anyways*/
-        }
-    
-        msLayerClose(layer);  
+  rectObj     searchrect;
+  const char *chartTypeProcessingKey=msLayerGetProcessingKey( layer,"CHART_TYPE" );
+  int chartType=MS_CHART_TYPE_PIE;
+  int status = MS_FAILURE;
+
+  if (image && map && layer) {
+    if( !(MS_RENDERER_PLUGIN(image->format) )) {
+      msSetError(MS_MISCERR, "chart drawing currently only supports GD and AGG renderers", "msDrawChartLayer()");
+      return MS_FAILURE;
+    }
+
+    if(chartTypeProcessingKey!=NULL) {
+      if( strcasecmp(chartTypeProcessingKey,"PIE") == 0 ) {
+        chartType=MS_CHART_TYPE_PIE;
+      } else if( strcasecmp(chartTypeProcessingKey,"BAR") == 0 ) {
+        chartType=MS_CHART_TYPE_BAR;
+      } else if( strcasecmp(chartTypeProcessingKey,"VBAR") == 0 ) {
+        chartType=MS_CHART_TYPE_VBAR;
+      } else {
+        msSetError(MS_MISCERR,"unknown chart type for processing key \"CHART_TYPE\", must be one of \"PIE\" or \"BAR\"", "msDrawChartLayer()");
+        return MS_FAILURE;
+      }
+    }
+    if(chartType == MS_CHART_TYPE_PIE) {
+      pieLayerProcessDynamicDiameter(layer);
+    }
+
+    /* open this layer */
+    status = msLayerOpen(layer);
+    if(status != MS_SUCCESS) return MS_FAILURE;
+
+    status = msLayerWhichItems(layer, MS_FALSE, NULL);
+    if(status != MS_SUCCESS) {
+      msLayerClose(layer);
+      return MS_FAILURE;
     }
-    return status;
+    /* identify target shapes */
+    if(layer->transform == MS_TRUE)
+      searchrect = map->extent;
+    else {
+      searchrect.minx = searchrect.miny = 0;
+      searchrect.maxx = map->width-1;
+      searchrect.maxy = map->height-1;
+    }
+
+#ifdef USE_PROJ
+    if((map->projection.numargs > 0) && (layer->projection.numargs > 0))
+      msProjectRect(&map->projection, &layer->projection, &searchrect); /* project the searchrect to source coords */
+#endif
+
+    status = msLayerWhichShapes(layer, searchrect, MS_FALSE);
+    if(status == MS_DONE) { /* no overlap */
+      msLayerClose(layer);
+      return MS_SUCCESS;
+    } else if(status != MS_SUCCESS) {
+      msLayerClose(layer);
+      return MS_FAILURE;
+    }
+    switch(chartType) {
+      case MS_CHART_TYPE_PIE:
+        status = msDrawPieChartLayer(map, layer, image);
+        break;
+      case MS_CHART_TYPE_BAR:
+        status = msDrawBarChartLayer(map, layer, image);
+        break;
+      case MS_CHART_TYPE_VBAR:
+        status = msDrawVBarChartLayer(map, layer, image);
+        break;
+      default:
+        return MS_FAILURE;/*shouldn't be here anyways*/
+    }
+
+    msLayerClose(layer);
+  }
+  return status;
 }
diff --git a/mapcluster.c b/mapcluster.c
index 945292f..04c6b7c 100644
--- a/mapcluster.c
+++ b/mapcluster.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -33,7 +33,7 @@
 #include <assert.h>
 #include "mapserver.h"
 
-MS_CVSID("$Id$")
+
 
 
 #ifdef USE_CLUSTER_PLUGIN
@@ -63,72 +63,72 @@ typedef int (*clusterCompareRegionFunc)(clusterInfo* current, clusterInfo* other
 #define TREE_MAX_DEPTH  10
 
 /* cluster data */
-struct cluster_info
-{
-    double x;    /* x position of the current point */
-    double y;    /* y position of the current point */
-    double avgx; /* average x positions of this cluster */
-    double avgy; /* average y positions of this cluster */
-    double varx; /* variance of the x positions of this cluster */
-    double vary; /* variance of the y positions of this cluster */
-    shapeObj shape; /* current shape */
-    rectObj bounds; /* clustering region */
-    /* number of the neighbouring shapes */
-    int numsiblings;
-    /* diagnostics */
-    int numcollected;
-    int numremoved;
-    int index;
-    /* collection of the siblings */
-    clusterInfo* siblings;
-    /* next shape in the linked list */
-    clusterInfo* next;
-    /* current group */
-    char* group;
-    int filter;
+struct cluster_info {
+  double x;    /* x position of the current point */
+  double y;    /* y position of the current point */
+  double avgx; /* average x positions of this cluster */
+  double avgy; /* average y positions of this cluster */
+  double varx; /* variance of the x positions of this cluster */
+  double vary; /* variance of the y positions of this cluster */
+  shapeObj shape; /* current shape */
+  rectObj bounds; /* clustering region */
+  /* number of the neighbouring shapes */
+  int numsiblings;
+  /* diagnostics */
+  int numcollected;
+  int numremoved;
+  int index;
+  clusterTreeNode* node;
+  /* collection of the siblings */
+  clusterInfo* siblings;
+  /* next shape in the linked list */
+  clusterInfo* next;
+  /* current group */
+  char* group;
+  int filter;
 };
 
 /* quadtree node */
-struct cluster_tree_node 
-{
-    /* area covered by this node */
-    rectObj rect;
-    /* linked list of the shapes stored at this node. */
-    int numshapes;
-    int index;
-    int position;
-    clusterInfo* shapes;
-    /* quad tree subnodes */
-    clusterTreeNode* subnode[4];
+struct cluster_tree_node {
+  /* area covered by this node */
+  rectObj rect;
+  /* linked list of the shapes stored at this node. */
+  int numshapes;
+  int index;
+  int position;
+  clusterInfo* shapes;
+  /* quad tree subnodes */
+  clusterTreeNode* subnode[4];
 };
 
 /* layeinfo */
-struct cluster_layer_info
-{
-    /* array of features (finalized clusters) */
-    clusterInfo* finalized;
-    clusterInfo* finalizedSiblings;
-    clusterInfo* filtered;
-    int numFeatures;
-    int numFinalized;
-    int numFinalizedSiblings;
-    int numFiltered;
-    /* variables for collecting the best cluster and iterating with NextShape */
-    clusterInfo* current;
-    double rank;
-    /* root node of the quad tree */
-    clusterTreeNode* root;
-    int numNodes;
-    clusterTreeNode* finalizedNodes;
-    int numFinalizedNodes;
-    /* map extent used for building cluster data */
-    rectObj searchRect;
-    /* source layer parameters */
-    layerObj srcLayer;
-    /* distance comparator function */
-    clusterCompareRegionFunc fnCompare;
-    /* diagnostics */
-    int depth;
+struct cluster_layer_info {
+  /* array of features (finalized clusters) */
+  clusterInfo* finalized;
+  clusterInfo* finalizedSiblings;
+  clusterInfo* filtered;
+  int numFeatures;
+  int numFinalized;
+  int numFinalizedSiblings;
+  int numFiltered;
+  /* variables for collecting the best cluster and iterating with NextShape */
+  clusterInfo* current;
+  /* check whether all shapes should be returned behind a cluster */
+  int get_all_shapes;
+  double rank;
+  /* root node of the quad tree */
+  clusterTreeNode* root;
+  int numNodes;
+  clusterTreeNode* finalizedNodes;
+  int numFinalizedNodes;
+  /* map extent used for building cluster data */
+  rectObj searchRect;
+  /* source layer parameters */
+  layerObj srcLayer;
+  /* distance comparator function */
+  clusterCompareRegionFunc fnCompare;
+  /* diagnostics */
+  int depth;
 };
 
 
@@ -137,1220 +137,1166 @@ extern int yyparse(parseObj *p);
 /* evaluate the filter expression */
 int msClusterEvaluateFilter(expressionObj* expression, shapeObj *shape)
 {
-    if (expression->type == MS_EXPRESSION)
-    {
+  if (expression->type == MS_EXPRESSION) {
+    int status;
+    parseObj p;
+
+    p.shape = shape;
+    p.expr = expression;
+    p.expr->curtoken = p.expr->tokens; /* reset */
+    p.type = MS_PARSE_TYPE_BOOLEAN;
+
+    status = yyparse(&p);
+
+    if (status != 0) {
+      msSetError(MS_PARSEERR, "Failed to parse expression: %s", "msClusterEvaluateFilter", expression->string);
+      return 0;
+    }
+
+    return p.result.intval;
+  }
+
+  return 0;
+}
+
+/* get the group text when creating the clusters */
+char *msClusterGetGroupText(expressionObj* expression, shapeObj *shape)
+{
+  char *tmpstr=NULL;
+
+  if(expression->string) {
+    switch(expression->type) {
+      case(MS_STRING):
+        tmpstr = msStrdup(expression->string);
+        break;
+      case(MS_EXPRESSION): {
         int status;
         parseObj p;
 
         p.shape = shape;
         p.expr = expression;
         p.expr->curtoken = p.expr->tokens; /* reset */
-        p.type = MS_PARSE_TYPE_BOOLEAN;
+        p.type = MS_PARSE_TYPE_STRING;
 
         status = yyparse(&p);
 
         if (status != 0) {
-            msSetError(MS_PARSEERR, "Failed to parse expression: %s", "msClusterEvaluateFilter", expression->string);
-            return 0;
+          msSetError(MS_PARSEERR, "Failed to process text expression: %s", "msClusterGetGroupText", expression->string);
+          return NULL;
         }
 
-        return p.result.intval;
+        tmpstr = p.result.strval;
+        break;
+      }
+      default:
+        break;
     }
+  }
 
-    return 0;
+  return(tmpstr);
 }
 
-/* get the group text when creating the clusters */
-char *msClusterGetGroupText(expressionObj* expression, shapeObj *shape)
+int CompareEllipseRegion(clusterInfo* current, clusterInfo* other)
 {
-    char *tmpstr=NULL;
-
-    if(expression->string) 
-    {
-        switch(expression->type) 
-        {
-        case(MS_STRING):
-            tmpstr = msStrdup(expression->string);
-            break;
-        case(MS_EXPRESSION):
-        {
-            int status;
-            parseObj p;
-
-            p.shape = shape;
-            p.expr = expression;
-            p.expr->curtoken = p.expr->tokens; /* reset */
-            p.type = MS_PARSE_TYPE_STRING;
-
-            status = yyparse(&p);
-
-            if (status != 0) 
-            {
-                msSetError(MS_PARSEERR, "Failed to process text expression: %s", "msClusterGetGroupText", expression->string);
-                return NULL;
-            }
+  if (current->group && other->group && !EQUAL(current->group, other->group))
+    return MS_FALSE;
 
-            tmpstr = p.result.strval;        
-            break;
-        }
-        default:
-           break;
-        }
-    }
-
-    return(tmpstr);
-}
+  if ((other->x - current->x) * (other->x - current->x) /
+      ((current->bounds.maxx - current->x) * (current->bounds.maxx - current->x)) +
+      (other->y - current->y) * (other->y - current->y) /
+      ((current->bounds.maxy - current->y) * (current->bounds.maxy - current->y)) > 1)
+    return MS_FALSE;
 
-int CompareEllipseRegion(clusterInfo* current, clusterInfo* other)
-{  
-    if (current->group && other->group && !EQUAL(current->group, other->group))
-        return MS_FALSE;
-    
-    if ((other->x - current->x) * (other->x - current->x) / 
-        ((current->bounds.maxx - current->x) * (current->bounds.maxx - current->x)) + 
-        (other->y - current->y) * (other->y - current->y) / 
-        ((current->bounds.maxy - current->y) * (current->bounds.maxy - current->y)) > 1)
-        return MS_FALSE;
-
-    return MS_TRUE;
+  return MS_TRUE;
 }
 
 int CompareRectangleRegion(clusterInfo* current, clusterInfo* other)
 {
-    if (current->group && other->group && !EQUAL(current->group, other->group))
-        return MS_FALSE;
-    
-    if (other->x < current->bounds.minx)
-        return MS_FALSE;
-    if (other->x > current->bounds.maxx)
-        return MS_FALSE;
-    if (other->y < current->bounds.miny)
-        return MS_FALSE;
-    if (other->y > current->bounds.maxy)
-        return MS_FALSE;
-
-    return MS_TRUE;
+  if (current->group && other->group && !EQUAL(current->group, other->group))
+    return MS_FALSE;
+
+  if (other->x < current->bounds.minx)
+    return MS_FALSE;
+  if (other->x > current->bounds.maxx)
+    return MS_FALSE;
+  if (other->y < current->bounds.miny)
+    return MS_FALSE;
+  if (other->y > current->bounds.maxy)
+    return MS_FALSE;
+
+  return MS_TRUE;
 }
 
 static void treeSplitBounds( rectObj *in, rectObj *out1, rectObj *out2)
 {
-    double range;
-
-    /* -------------------------------------------------------------------- */
-    /*      The output bounds will be very similar to the input bounds,     */
-    /*      so just copy over to start.                                     */
-    /* -------------------------------------------------------------------- */
-    memcpy(out1, in, sizeof(rectObj));
-    memcpy(out2, in, sizeof(rectObj));
-
-    /* -------------------------------------------------------------------- */
-    /*      Split in X direction.                                           */
-    /* -------------------------------------------------------------------- */
-    if((in->maxx - in->minx) > (in->maxy - in->miny)) 
-    {
-        range = in->maxx - in->minx;
-
-        out1->maxx = in->minx + range * SPLITRATIO;
-        out2->minx = in->maxx - range * SPLITRATIO;
-    }
+  double range;
 
-    /* -------------------------------------------------------------------- */
-    /*      Otherwise split in Y direction.                                 */
-    /* -------------------------------------------------------------------- */
-    else 
-    {
-        range = in->maxy - in->miny;
+  /* -------------------------------------------------------------------- */
+  /*      The output bounds will be very similar to the input bounds,     */
+  /*      so just copy over to start.                                     */
+  /* -------------------------------------------------------------------- */
+  memcpy(out1, in, sizeof(rectObj));
+  memcpy(out2, in, sizeof(rectObj));
 
-        out1->maxy = in->miny + range * SPLITRATIO;
-        out2->miny = in->maxy - range * SPLITRATIO;
-    }
+  /* -------------------------------------------------------------------- */
+  /*      Split in X direction.                                           */
+  /* -------------------------------------------------------------------- */
+  if((in->maxx - in->minx) > (in->maxy - in->miny)) {
+    range = in->maxx - in->minx;
+
+    out1->maxx = in->minx + range * SPLITRATIO;
+    out2->minx = in->maxx - range * SPLITRATIO;
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Otherwise split in Y direction.                                 */
+  /* -------------------------------------------------------------------- */
+  else {
+    range = in->maxy - in->miny;
+
+    out1->maxy = in->miny + range * SPLITRATIO;
+    out2->miny = in->maxy - range * SPLITRATIO;
+  }
 }
 
 /* alloc memory for a new tentative cluster */
 static clusterInfo *clusterInfoCreate(msClusterLayerInfo* layerinfo)
 {
-    clusterInfo* feature = (clusterInfo*)msSmallMalloc(sizeof(clusterInfo));
-    msInitShape(&feature->shape);
-    feature->numsiblings = 0;
-    feature->numcollected = 0;
-    feature->numremoved = 0;
-    feature->next = NULL;
-    feature->group = NULL;
-    feature->siblings = NULL;
-    feature->index = layerinfo->numFeatures;
-    feature->filter = -1; // not yet calculated
-    ++layerinfo->numFeatures;
-    return feature;
+  clusterInfo* feature = (clusterInfo*)msSmallMalloc(sizeof(clusterInfo));
+  msInitShape(&feature->shape);
+  feature->numsiblings = 0;
+  feature->numcollected = 0;
+  feature->numremoved = 0;
+  feature->next = NULL;
+  feature->group = NULL;
+  feature->node = NULL;
+  feature->siblings = NULL;
+  feature->index = layerinfo->numFeatures;
+  feature->filter = -1; /* not yet calculated */
+  ++layerinfo->numFeatures;
+  return feature;
 }
 
 /* destroy memory of the cluster list */
 static void clusterInfoDestroyList(msClusterLayerInfo* layerinfo, clusterInfo* feature)
 {
-    clusterInfo* s = feature;
-    clusterInfo* next;
-    /* destroy the shapes added to this node */
-    while (s)
-    {
-        next = s->next;
-        if (s->siblings)
-        {
-            clusterInfoDestroyList(layerinfo, s->siblings);
-        }
-        msFreeShape(&s->shape);
-        msFree(s->group);
-        msFree(s);
-        --layerinfo->numFeatures;
-        s = next;
+  clusterInfo* s = feature;
+  clusterInfo* next;
+  /* destroy the shapes added to this node */
+  while (s) {
+    next = s->next;
+    if (s->siblings) {
+      clusterInfoDestroyList(layerinfo, s->siblings);
     }
+    msFreeShape(&s->shape);
+    msFree(s->group);
+    msFree(s);
+    --layerinfo->numFeatures;
+    s = next;
+  }
 }
 
 /* alloc memory for a new treenode */
 static clusterTreeNode *clusterTreeNodeCreate(msClusterLayerInfo* layerinfo, rectObj rect)
 {
-    clusterTreeNode* node = (clusterTreeNode*)msSmallMalloc(sizeof(clusterTreeNode));
-    node->rect = rect;
-    node->numshapes = 0;
-    node->shapes = NULL;
-    node->subnode[0] = node->subnode[1] = node->subnode[2] = node->subnode[3] = NULL;
-    node->index = layerinfo->numNodes;
-    node->position = 0;
-    ++layerinfo->numNodes;
-    return node;
+  clusterTreeNode* node = (clusterTreeNode*)msSmallMalloc(sizeof(clusterTreeNode));
+  node->rect = rect;
+  node->numshapes = 0;
+  node->shapes = NULL;
+  node->subnode[0] = node->subnode[1] = node->subnode[2] = node->subnode[3] = NULL;
+  node->index = layerinfo->numNodes;
+  node->position = 0;
+  ++layerinfo->numNodes;
+  return node;
 }
 
 /* traverse the quadtree and destroy all sub elements */
 static void clusterTreeNodeDestroy(msClusterLayerInfo* layerinfo, clusterTreeNode *node)
 {
-    int i;
-    /* destroy the shapes added to this node */
-    clusterInfoDestroyList(layerinfo, node->shapes);
-
-    /* Recurse to subnodes if they exist */
-    for (i = 0; i < 4; i++)
-    {
-        if (node->subnode[i])
-            clusterTreeNodeDestroy(layerinfo, node->subnode[i]);
-    }
-
-    msFree(node);
-    --layerinfo->numNodes;
+  int i;
+  /* destroy the shapes added to this node */
+  clusterInfoDestroyList(layerinfo, node->shapes);
+
+  /* Recurse to subnodes if they exist */
+  for (i = 0; i < 4; i++) {
+    if (node->subnode[i])
+      clusterTreeNodeDestroy(layerinfo, node->subnode[i]);
+  }
+
+  msFree(node);
+  --layerinfo->numNodes;
 }
 
 /* destroy memory of the cluster finalized list (without recursion) */
 static void clusterTreeNodeDestroyList(msClusterLayerInfo* layerinfo, clusterTreeNode *node)
 {
-    clusterTreeNode* n = node;
-    clusterTreeNode* next;
-    /* destroy the list of nodes */
-    while (n)
-    {
-        next = n->subnode[0];
-        n->subnode[0] = NULL;
-        clusterTreeNodeDestroy(layerinfo, n);
-        --layerinfo->numFinalizedNodes;
-        n = next;
-    }
+  clusterTreeNode* n = node;
+  clusterTreeNode* next;
+  /* destroy the list of nodes */
+  while (n) {
+    next = n->subnode[0];
+    n->subnode[0] = NULL;
+    clusterTreeNodeDestroy(layerinfo, n);
+    --layerinfo->numFinalizedNodes;
+    n = next;
+  }
 }
 
 void clusterDestroyData(msClusterLayerInfo *layerinfo)
 {
-    if (layerinfo->finalized)
-    {
-        clusterInfoDestroyList(layerinfo, layerinfo->finalized);
-        layerinfo->finalized = NULL;
-    }
-    layerinfo->numFinalized = 0;
-    
-    if (layerinfo->finalizedSiblings)
-    {
-        clusterInfoDestroyList(layerinfo, layerinfo->finalizedSiblings);
-        layerinfo->finalizedSiblings = NULL;
-    }
-    layerinfo->numFinalizedSiblings = 0;
+  if (layerinfo->finalized) {
+    clusterInfoDestroyList(layerinfo, layerinfo->finalized);
+    layerinfo->finalized = NULL;
+  }
+  layerinfo->numFinalized = 0;
 
-    if (layerinfo->filtered)
-    {
-        clusterInfoDestroyList(layerinfo, layerinfo->filtered);
-        layerinfo->filtered = NULL;
-    }
-    layerinfo->numFiltered = 0;
+  if (layerinfo->finalizedSiblings) {
+    clusterInfoDestroyList(layerinfo, layerinfo->finalizedSiblings);
+    layerinfo->finalizedSiblings = NULL;
+  }
+  layerinfo->numFinalizedSiblings = 0;
 
-    if (layerinfo->finalizedNodes)
-    {
-        clusterTreeNodeDestroyList(layerinfo, layerinfo->finalizedNodes);
-        layerinfo->finalizedNodes = NULL;
-    }
+  if (layerinfo->filtered) {
+    clusterInfoDestroyList(layerinfo, layerinfo->filtered);
+    layerinfo->filtered = NULL;
+  }
+  layerinfo->numFiltered = 0;
 
-    layerinfo->numFinalizedNodes = 0;
+  if (layerinfo->finalizedNodes) {
+    clusterTreeNodeDestroyList(layerinfo, layerinfo->finalizedNodes);
+    layerinfo->finalizedNodes = NULL;
+  }
 
-    if (layerinfo->root)
-    {
-        clusterTreeNodeDestroy(layerinfo, layerinfo->root);
-        layerinfo->root = NULL;
-    }
+  layerinfo->numFinalizedNodes = 0;
 
-    layerinfo->numNodes = 0;
+  if (layerinfo->root) {
+    clusterTreeNodeDestroy(layerinfo, layerinfo->root);
+    layerinfo->root = NULL;
+  }
+
+  layerinfo->numNodes = 0;
 }
 
-/* traverse the quadtree to find the neighbouring shapes and update some data 
+/* traverse the quadtree to find the neighbouring shapes and update some data
 on the related shapes (when adding a new feature)*/
-static void findRelatedShapes(msClusterLayerInfo* layerinfo, 
+static void findRelatedShapes(msClusterLayerInfo* layerinfo,
                               clusterTreeNode *node, clusterInfo* current)
 {
-    int i;
-    clusterInfo* s; 
-    
-    /* -------------------------------------------------------------------- */
-    /*      Does this node overlap the area of interest at all?  If not,    */
-    /*      return without adding to the list at all.                       */
-    /* -------------------------------------------------------------------- */
-    if(!msRectOverlap(&node->rect, &current->bounds))
+  int i;
+  clusterInfo* s;
+
+  /* -------------------------------------------------------------------- */
+  /*      Does this node overlap the area of interest at all?  If not,    */
+  /*      return without adding to the list at all.                       */
+  /* -------------------------------------------------------------------- */
+  if(!msRectOverlap(&node->rect, &current->bounds))
     return;
 
-    /* Modify the feature count of the related shapes */
-    s = node->shapes;
-    while (s)
-    {
-        if (layerinfo->fnCompare(current, s))
-        {
-            ++current->numsiblings;
-            /* calculating the average positions */
-            current->avgx = (current->avgx * current->numsiblings + s->x) / (current->numsiblings + 1);
-            current->avgy = (current->avgy * current->numsiblings + s->y) / (current->numsiblings + 1);
-            /* calculating the variance */
-            current->varx = current->varx * current->numsiblings / (current->numsiblings + 1) + 
-                        (s->x - current->avgx) * (s->x - current->avgx) / (current->numsiblings + 1);
-            current->vary = current->vary * current->numsiblings / (current->numsiblings + 1) + 
-                        (s->y - current->avgy) * (s->y - current->avgy) / (current->numsiblings + 1);
-
-            if (layerinfo->fnCompare(s, current))
-            {
-                /* this feature falls into the region of the other as well */
-                ++s->numsiblings;
-                /* calculating the average positions */
-                s->avgx = (s->avgx * s->numsiblings + current->x) / (s->numsiblings + 1);
-                s->avgy = (s->avgy * s->numsiblings + current->y) / (s->numsiblings + 1);
-                /* calculating the variance */
-                s->varx = s->varx * s->numsiblings / (s->numsiblings + 1) + 
-                            (current->x - s->avgx) * (current->x - s->avgx) / (s->numsiblings + 1);
-                s->vary = s->vary * s->numsiblings / (s->numsiblings + 1) + 
-                            (current->y - s->avgy) * (current->y - s->avgy) / (s->numsiblings + 1);
-            }
-        }
-        s = s->next;
+  /* Modify the feature count of the related shapes */
+  s = node->shapes;
+  while (s) {
+    if (layerinfo->fnCompare(current, s)) {
+      ++current->numsiblings;
+      /* calculating the average positions */
+      current->avgx = (current->avgx * current->numsiblings + s->x) / (current->numsiblings + 1);
+      current->avgy = (current->avgy * current->numsiblings + s->y) / (current->numsiblings + 1);
+      /* calculating the variance */
+      current->varx = current->varx * current->numsiblings / (current->numsiblings + 1) +
+                      (s->x - current->avgx) * (s->x - current->avgx) / (current->numsiblings + 1);
+      current->vary = current->vary * current->numsiblings / (current->numsiblings + 1) +
+                      (s->y - current->avgy) * (s->y - current->avgy) / (current->numsiblings + 1);
+
+      if (layerinfo->fnCompare(s, current)) {
+        /* this feature falls into the region of the other as well */
+        ++s->numsiblings;
+        /* calculating the average positions */
+        s->avgx = (s->avgx * s->numsiblings + current->x) / (s->numsiblings + 1);
+        s->avgy = (s->avgy * s->numsiblings + current->y) / (s->numsiblings + 1);
+        /* calculating the variance */
+        s->varx = s->varx * s->numsiblings / (s->numsiblings + 1) +
+                  (current->x - s->avgx) * (current->x - s->avgx) / (s->numsiblings + 1);
+        s->vary = s->vary * s->numsiblings / (s->numsiblings + 1) +
+                  (current->y - s->avgy) * (current->y - s->avgy) / (s->numsiblings + 1);
+      }
     }
+    s = s->next;
+  }
 
-    if (node->subnode[0] == NULL)
-        return;
+  if (node->subnode[0] == NULL)
+    return;
 
-    /* Recurse to subnodes if they exist */
-    for (i = 0; i < 4; i++)
-    {
-        if (node->subnode[i])
-            findRelatedShapes(layerinfo, node->subnode[i], current);
-    }
+  /* Recurse to subnodes if they exist */
+  for (i = 0; i < 4; i++) {
+    if (node->subnode[i])
+      findRelatedShapes(layerinfo, node->subnode[i], current);
+  }
 }
 
-/* traverse the quadtree to find the neighbouring shapes and update some data 
+/* traverse the quadtree to find the neighbouring shapes and update some data
 on the related shapes (when removing a feature) */
 static void findRelatedShapesRemove(msClusterLayerInfo* layerinfo, clusterTreeNode *node, clusterInfo* current)
 {
-    int i;
-    clusterInfo* s; 
-    
-    /* -------------------------------------------------------------------- */
-    /*      Does this node overlap the area of interest at all?  If not,    */
-    /*      return without adding to the list at all.                       */
-    /* -------------------------------------------------------------------- */
-    if(!msRectOverlap(&node->rect, &current->bounds))
-    return;
+  int i;
+  clusterInfo* s;
 
-    /* Modify the feature count of the related shapes */
-    s = node->shapes;
-    while (s)
-    {
-        if (layerinfo->fnCompare(current, s))
-        {
-            if (s->numsiblings > 0)
-            {
-                /* calculating the average positions */
-                s->avgx = (s->avgx * (s->numsiblings + 1) - current->x) / s->numsiblings;
-                s->avgy = (s->avgy * (s->numsiblings + 1) - current->y) / s->numsiblings;
-                /* calculating the variance */
-                s->varx = (s->varx - (current->x - s->avgx) * (current->x - s->avgx) / s->numsiblings) * 
-                                                    (s->numsiblings + 1) / s->numsiblings;
-                s->vary = (s->vary - (current->y - s->avgy) * (current->y - s->avgy) / s->numsiblings) * 
-                                                    (s->numsiblings + 1) / s->numsiblings;
-                --s->numsiblings;
-                ++s->numremoved;
-            }
-        }
-        s = s->next;
-    }
+  /* -------------------------------------------------------------------- */
+  /*      Does this node overlap the area of interest at all?  If not,    */
+  /*      return without adding to the list at all.                       */
+  /* -------------------------------------------------------------------- */
+  if(!msRectOverlap(&node->rect, &current->bounds))
+    return;
 
-    /* Recurse to subnodes if they exist */
-    for (i = 0; i < 4; i++)
-    {
-        if (node->subnode[i])
-            findRelatedShapesRemove(layerinfo, node->subnode[i], current);
+  /* Modify the feature count of the related shapes */
+  s = node->shapes;
+  while (s) {
+    if (layerinfo->fnCompare(current, s)) {
+      if (s->numsiblings > 0) {
+        /* calculating the average positions */
+        s->avgx = (s->avgx * (s->numsiblings + 1) - current->x) / s->numsiblings;
+        s->avgy = (s->avgy * (s->numsiblings + 1) - current->y) / s->numsiblings;
+        /* calculating the variance */
+        s->varx = (s->varx - (current->x - s->avgx) * (current->x - s->avgx) / s->numsiblings) *
+                  (s->numsiblings + 1) / s->numsiblings;
+        s->vary = (s->vary - (current->y - s->avgy) * (current->y - s->avgy) / s->numsiblings) *
+                  (s->numsiblings + 1) / s->numsiblings;
+        --s->numsiblings;
+        ++s->numremoved;
+      }
     }
+    s = s->next;
+  }
+
+  /* Recurse to subnodes if they exist */
+  for (i = 0; i < 4; i++) {
+    if (node->subnode[i])
+      findRelatedShapesRemove(layerinfo, node->subnode[i], current);
+  }
 }
 
 /* setting the aggregated attributes */
 static void InitShapeAttributes(layerObj* layer, clusterInfo* base)
 {
-    int i;
-    int* itemindexes = layer->iteminfo;
-
-    for (i = 0; i < layer->numitems; i++)
-    {
-        if (base->shape.numvalues <= i)
-            break;
-
-        if (itemindexes[i] == MSCLUSTER_FEATURECOUNTINDEX)
-        {
-            if (base->shape.values[i])
-                msFree(base->shape.values[i]);
-
-            base->shape.values[i] = msIntToString(base->numsiblings + 1);
-        }
-        else if (itemindexes[i] == MSCLUSTER_GROUPINDEX)
-        {
-            if (base->shape.values[i])
-                msFree(base->shape.values[i]);
-
-            if (base->group) 
-                base->shape.values[i] = msStrdup(base->group);
-            else
-                base->shape.values[i] = msStrdup("");
-        }
-        else if (EQUALN(layer->items[i], "Count:", 6))
-        {
-            if (base->shape.values[i])
-                msFree(base->shape.values[i]);
-
-            base->shape.values[i] = msStrdup("1"); // initial count 
-        }
+  int i;
+  int* itemindexes = layer->iteminfo;
+
+  for (i = 0; i < layer->numitems; i++) {
+    if (base->shape.numvalues <= i)
+      break;
+
+    if (itemindexes[i] == MSCLUSTER_FEATURECOUNTINDEX) {
+      if (base->shape.values[i])
+        msFree(base->shape.values[i]);
+
+      base->shape.values[i] = msIntToString(base->numsiblings + 1);
+    } else if (itemindexes[i] == MSCLUSTER_GROUPINDEX) {
+      if (base->shape.values[i])
+        msFree(base->shape.values[i]);
+
+      if (base->group)
+        base->shape.values[i] = msStrdup(base->group);
+      else
+        base->shape.values[i] = msStrdup("");
+    } else if (EQUALN(layer->items[i], "Count:", 6)) {
+      if (base->shape.values[i])
+        msFree(base->shape.values[i]);
+
+      base->shape.values[i] = msStrdup("1"); /* initial count */
     }
+  }
 }
 
 /* update the shape attributes (aggregate) */
 static void UpdateShapeAttributes(layerObj* layer, clusterInfo* base, clusterInfo* current)
 {
-    int i;
-    int* itemindexes = layer->iteminfo;
+  int i;
+  int* itemindexes = layer->iteminfo;
 
-    for (i = 0; i < layer->numitems; i++)
-    {
-        if (base->shape.numvalues <= i)
-            break;
+  for (i = 0; i < layer->numitems; i++) {
+    if (base->shape.numvalues <= i)
+      break;
 
-        if (itemindexes[i] == MSCLUSTER_FEATURECOUNTINDEX || 
-            itemindexes[i] == MSCLUSTER_GROUPINDEX)
-            continue;
+    if (itemindexes[i] == MSCLUSTER_FEATURECOUNTINDEX ||
+        itemindexes[i] == MSCLUSTER_GROUPINDEX)
+      continue;
 
-        if (current->shape.numvalues <= i)
-            break;
-        
-        if (current->shape.values[i])
-        {
-            if (EQUALN(layer->items[i], "Min:", 4))
-            {
-                if (strcasecmp(base->shape.values[i], current->shape.values[i]) > 0)
-                {
-                    msFree(base->shape.values[i]);
-                    base->shape.values[i] = msStrdup(current->shape.values[i]);
-                }
-            }
-            else if (EQUALN(layer->items[i], "Max:", 4))
-            {
-                if (strcasecmp(base->shape.values[i], current->shape.values[i]) < 0)
-                {
-                    msFree(base->shape.values[i]);
-                    base->shape.values[i] = msStrdup(current->shape.values[i]);
-                }
-            }
-            else if (EQUALN(layer->items[i], "Sum:", 4))
-            {
-                double sum = atof(base->shape.values[i]) + atof(current->shape.values[i]);
-                msFree(base->shape.values[i]);
-                base->shape.values[i] = msDoubleToString(sum, MS_FALSE);
-            }
-            else if (EQUALN(layer->items[i], "Count:", 6))
-            {
-                int count = atoi(base->shape.values[i]) + 1;
-                msFree(base->shape.values[i]);
-                base->shape.values[i] = msIntToString(count);
-            }
-            else if (!EQUAL(base->shape.values[i], current->shape.values[i]) 
-                     && !EQUAL(base->shape.values[i], ""))
-            {
-                /* clear the value if that doesn't match */
-                msFree(base->shape.values[i]);
-                base->shape.values[i] = msStrdup("");
-            }
+    if (current->shape.numvalues <= i)
+      break;
+
+    if (current->shape.values[i]) {
+      if (EQUALN(layer->items[i], "Min:", 4)) {
+        if (strcasecmp(base->shape.values[i], current->shape.values[i]) > 0) {
+          msFree(base->shape.values[i]);
+          base->shape.values[i] = msStrdup(current->shape.values[i]);
+        }
+      } else if (EQUALN(layer->items[i], "Max:", 4)) {
+        if (strcasecmp(base->shape.values[i], current->shape.values[i]) < 0) {
+          msFree(base->shape.values[i]);
+          base->shape.values[i] = msStrdup(current->shape.values[i]);
         }
+      } else if (EQUALN(layer->items[i], "Sum:", 4)) {
+        double sum = atof(base->shape.values[i]) + atof(current->shape.values[i]);
+        msFree(base->shape.values[i]);
+        base->shape.values[i] = msDoubleToString(sum, MS_FALSE);
+      } else if (EQUALN(layer->items[i], "Count:", 6)) {
+        int count = atoi(base->shape.values[i]) + 1;
+        msFree(base->shape.values[i]);
+        base->shape.values[i] = msIntToString(count);
+      } else if (!EQUAL(base->shape.values[i], current->shape.values[i])
+                 && !EQUAL(base->shape.values[i], "")) {
+        /* clear the value if that doesn't match */
+        msFree(base->shape.values[i]);
+        base->shape.values[i] = msStrdup("");
+      }
     }
+  }
 }
 
 static int BuildFeatureAttributes(layerObj* layer, msClusterLayerInfo* layerinfo, shapeObj* shape)
 {
-    char** values;
-    int i;
-    int* itemindexes = layer->iteminfo;
-    
-    if (layer->numitems == layerinfo->srcLayer.numitems)
-        return MS_SUCCESS; /* we don't have custom attributes, no need to reconstruct the array */
-
-    values = msSmallMalloc(sizeof(char*) * (layer->numitems));
-    
-    for (i = 0; i < layer->numitems; i++)
-    {
-        if (itemindexes[i] == MSCLUSTER_FEATURECOUNTINDEX)
-        {
-            values[i] = NULL; // not yet assigned
-        }
-        else if (itemindexes[i] == MSCLUSTER_GROUPINDEX)
-        {
-            values[i] = NULL; // not yet assigned
-        }
-        else if (shape->values[itemindexes[i]])
-            values[i] = msStrdup(shape->values[itemindexes[i]]);
-        else
-            values[i] = msStrdup("");
-    }
+  char** values;
+  int i;
+  int* itemindexes = layer->iteminfo;
+
+  if (layer->numitems == layerinfo->srcLayer.numitems)
+    return MS_SUCCESS; /* we don't have custom attributes, no need to reconstruct the array */
+
+  values = msSmallMalloc(sizeof(char*) * (layer->numitems));
+
+  for (i = 0; i < layer->numitems; i++) {
+    if (itemindexes[i] == MSCLUSTER_FEATURECOUNTINDEX) {
+      values[i] = NULL; /* not yet assigned */
+    } else if (itemindexes[i] == MSCLUSTER_GROUPINDEX) {
+      values[i] = NULL; /* not yet assigned */
+    } else if (shape->values[itemindexes[i]])
+      values[i] = msStrdup(shape->values[itemindexes[i]]);
+    else
+      values[i] = msStrdup("");
+  }
 
-    if (shape->values)
-        msFreeCharArray(shape->values, shape->numvalues);
+  if (shape->values)
+    msFreeCharArray(shape->values, shape->numvalues);
 
-    shape->values = values;
-    shape->numvalues = layer->numitems;
+  shape->values = values;
+  shape->numvalues = layer->numitems;
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 /* traverse the quadtree to find the best renking cluster */
 static void findBestCluster(layerObj* layer, msClusterLayerInfo* layerinfo, clusterTreeNode *node)
 {
-    int i;
-    double rank;
-    clusterInfo* s = node->shapes;
-    while (s)
-    {
-        if (s->filter < 0 && layer->cluster.filter.string != NULL)
-        {
-            InitShapeAttributes(layer, s);
-            s->filter = msClusterEvaluateFilter(&layer->cluster.filter, &s->shape);
-        }
-        
-        if (s->numsiblings == 0 || s->filter == 0)
-        {
-            /* individual or filtered shapes must be removed for sure */
-            layerinfo->current = s;
-            return;
-        }
-        
-        /* calculating the rank */
-        rank = (s->x - s->avgx) * (s->x - s->avgx) + (s->y - s->avgy) * (s->y - s->avgy) /*+ s->varx + s->vary*/ + (double)1/ (1 + s->numsiblings);
-        
-        if (rank < layerinfo->rank)
-        {
-            layerinfo->current = s;
-            layerinfo->rank = rank;
-        }
-        s = s->next;
+  int i;
+  double rank;
+  clusterInfo* s = node->shapes;
+  while (s) {
+    if (s->filter < 0 && layer->cluster.filter.string != NULL) {
+      InitShapeAttributes(layer, s);
+      s->filter = msClusterEvaluateFilter(&layer->cluster.filter, &s->shape);
     }
 
-    /* Recurse to subnodes if they exist */
-    for (i = 0; i < 4; i++)
-    {
-        if (node->subnode[i])
-            findBestCluster(layer, layerinfo, node->subnode[i]);
+    if (s->numsiblings == 0 || s->filter == 0) {
+      /* individual or filtered shapes must be removed for sure */
+      layerinfo->current = s;
+      return;
     }
+
+    /* calculating the rank */
+    rank = (s->x - s->avgx) * (s->x - s->avgx) + (s->y - s->avgy) * (s->y - s->avgy) /*+ s->varx + s->vary*/ + (double)1/ (1 + s->numsiblings);
+
+    if (rank < layerinfo->rank) {
+      layerinfo->current = s;
+      layerinfo->rank = rank;
+    }
+    s = s->next;
+  }
+
+  /* Recurse to subnodes if they exist */
+  for (i = 0; i < 4; i++) {
+    if (node->subnode[i])
+      findBestCluster(layer, layerinfo, node->subnode[i]);
+  }
 }
 
 /* adding the shape based on the shape bounds (point) */
 static int treeNodeAddShape(msClusterLayerInfo* layerinfo, clusterTreeNode* node, clusterInfo* shape, int depth)
 {
-    int i; 
-
-    /* -------------------------------------------------------------------- */
-    /*      If there are subnodes, then consider whether this object        */
-    /*      will fit in them.                                               */
-    /* -------------------------------------------------------------------- */
-    if( depth > 1 && node->subnode[0] != NULL ) 
-    {
-        for(i = 0; i < 4; i++ ) 
-        {
-            if( msRectContained(&shape->shape.bounds, &node->subnode[i]->rect)) 
-            {
-                return treeNodeAddShape( layerinfo, node->subnode[i], shape, depth-1);
-            }
-        }
+  int i;
+
+  /* -------------------------------------------------------------------- */
+  /*      If there are subnodes, then consider whether this object        */
+  /*      will fit in them.                                               */
+  /* -------------------------------------------------------------------- */
+  if( depth > 1 && node->subnode[0] != NULL ) {
+    for(i = 0; i < 4; i++ ) {
+      if( msRectContained(&shape->shape.bounds, &node->subnode[i]->rect)) {
+        return treeNodeAddShape( layerinfo, node->subnode[i], shape, depth-1);
+      }
     }
+  }
 
   /* -------------------------------------------------------------------- */
   /*      Otherwise, consider creating four subnodes if could fit into    */
   /*      them, and adding to the appropriate subnode.                    */
   /* -------------------------------------------------------------------- */
-    else if( depth > 1 && node->subnode[0] == NULL ) 
-    {
-        rectObj half1, half2, quad1, quad2, quad3, quad4;
-        int subnode = -1;
-
-        treeSplitBounds(&node->rect, &half1, &half2);
-        treeSplitBounds(&half1, &quad1, &quad2);
-        treeSplitBounds(&half2, &quad3, &quad4);
-
-        if(msRectContained(&shape->shape.bounds, &quad1))
-            subnode = 0;
-        else if(msRectContained(&shape->shape.bounds, &quad2))
-            subnode = 1;
-        else if(msRectContained(&shape->shape.bounds, &quad3))
-            subnode = 2;
-        else if(msRectContained(&shape->shape.bounds, &quad4))
-            subnode = 3;
-
-        if (subnode >= 0)
-        {
-            if ((node->subnode[0] = clusterTreeNodeCreate(layerinfo, quad1)) == NULL)
-                return MS_FAILURE;
-            node->subnode[0]->position = node->position * 4;
-
-            if ((node->subnode[1] = clusterTreeNodeCreate(layerinfo, quad2)) == NULL)
-                return MS_FAILURE;
-            node->subnode[1]->position = node->position * 4 + 1;
-
-            if ((node->subnode[2] = clusterTreeNodeCreate(layerinfo, quad3)) == NULL)
-                return MS_FAILURE;
-            node->subnode[2]->position = node->position * 4 + 2;
-
-            if ((node->subnode[3] = clusterTreeNodeCreate(layerinfo, quad4)) == NULL)
-                return MS_FAILURE;
-            node->subnode[3]->position = node->position * 4 + 3;
-
-            /* add to subnode */
-            return treeNodeAddShape(layerinfo, node->subnode[subnode], shape, depth-1);
-        }
+  else if( depth > 1 && node->subnode[0] == NULL ) {
+    rectObj half1, half2, quad1, quad2, quad3, quad4;
+    int subnode = -1;
+
+    treeSplitBounds(&node->rect, &half1, &half2);
+    treeSplitBounds(&half1, &quad1, &quad2);
+    treeSplitBounds(&half2, &quad3, &quad4);
+
+    if(msRectContained(&shape->shape.bounds, &quad1))
+      subnode = 0;
+    else if(msRectContained(&shape->shape.bounds, &quad2))
+      subnode = 1;
+    else if(msRectContained(&shape->shape.bounds, &quad3))
+      subnode = 2;
+    else if(msRectContained(&shape->shape.bounds, &quad4))
+      subnode = 3;
+
+    if (subnode >= 0) {
+      if ((node->subnode[0] = clusterTreeNodeCreate(layerinfo, quad1)) == NULL)
+        return MS_FAILURE;
+      node->subnode[0]->position = node->position * 4;
+
+      if ((node->subnode[1] = clusterTreeNodeCreate(layerinfo, quad2)) == NULL)
+        return MS_FAILURE;
+      node->subnode[1]->position = node->position * 4 + 1;
+
+      if ((node->subnode[2] = clusterTreeNodeCreate(layerinfo, quad3)) == NULL)
+        return MS_FAILURE;
+      node->subnode[2]->position = node->position * 4 + 2;
+
+      if ((node->subnode[3] = clusterTreeNodeCreate(layerinfo, quad4)) == NULL)
+        return MS_FAILURE;
+      node->subnode[3]->position = node->position * 4 + 3;
+
+      /* add to subnode */
+      return treeNodeAddShape(layerinfo, node->subnode[subnode], shape, depth-1);
     }
+  }
 
-    /* found the right place, add this shape to the node */
-    node->numshapes++;
-    shape->next = node->shapes;
-    node->shapes = shape;
+  /* found the right place, add this shape to the node */
+  node->numshapes++;
+  shape->next = node->shapes;
+  node->shapes = shape;
+  shape->node = node;
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 /* collecting the cluster shapes, returns true if this subnode must be removed */
 static int collectClusterShapes(msClusterLayerInfo* layerinfo, clusterTreeNode *node, clusterInfo* current)
 {
-    int i;
-    clusterInfo* prev = NULL;
-    clusterInfo* s = node->shapes;
-
-    if(!msRectOverlap(&node->rect, &current->bounds))
-    return (!node->shapes && !node->subnode[0] && !node->subnode[1] 
-                 && !node->subnode[2] && !node->subnode[3]);
-
-    /* removing the shapes from this node if overlap with the cluster */
-    while (s)
-    {
-        if (layerinfo->fnCompare(current, s))
-        {
-            if (s != current && current->filter == 0)
-            {
-                /* skip siblings of the filtered shapes */
-                prev = s;
-                s = prev->next;
-                continue;
-            }
-            
-            /* removing from the list */
-            if (!prev)
-                node->shapes = s->next;
-            else
-                prev->next = s->next;
-
-            ++current->numcollected;
-
-            /* adding the shape to the finalization list */
-            if (s == current)
-            {
-                if (s->filter)
-                {
-                    s->next = layerinfo->finalized;
-                    layerinfo->finalized = s;
-                    ++layerinfo->numFinalized;
-                }
-                else
-                {
-                    /* this shape is filtered */
-                    s->next = layerinfo->filtered;
-                    layerinfo->filtered = s;
-                    ++layerinfo->numFiltered;
-                }
-            }
-            else
-            {
-                s->next = layerinfo->finalizedSiblings;
-                layerinfo->finalizedSiblings = s;
-                ++layerinfo->numFinalizedSiblings;
-            }
-
-            if (!prev)
-                s = node->shapes;
-            else
-                s = prev->next;
-        }
-        else
-        {
-            prev = s;
-            s = prev->next;
+  int i;
+  clusterInfo* prev = NULL;
+  clusterInfo* s = node->shapes;
+
+  if(!msRectOverlap(&node->rect, &current->bounds))
+    return (!node->shapes && !node->subnode[0] && !node->subnode[1]
+            && !node->subnode[2] && !node->subnode[3]);
+
+  /* removing the shapes from this node if overlap with the cluster */
+  while (s) {
+    if (s == current || layerinfo->fnCompare(current, s)) {
+      if (s != current && current->filter == 0) {
+        /* skip siblings of the filtered shapes */
+        prev = s;
+        s = prev->next;
+        continue;
+      }
+
+      /* removing from the list */
+      if (!prev)
+        node->shapes = s->next;
+      else
+        prev->next = s->next;
+
+      ++current->numcollected;
+
+      /* adding the shape to the finalization list */
+      if (s == current) {
+        if (s->filter) {
+          s->next = layerinfo->finalized;
+          layerinfo->finalized = s;
+          ++layerinfo->numFinalized;
+        } else {
+          /* this shape is filtered */
+          s->next = layerinfo->filtered;
+          layerinfo->filtered = s;
+          ++layerinfo->numFiltered;
         }
+      } else {
+        s->next = layerinfo->finalizedSiblings;
+        layerinfo->finalizedSiblings = s;
+        ++layerinfo->numFinalizedSiblings;
+      }
+
+      if (!prev)
+        s = node->shapes;
+      else
+        s = prev->next;
+    } else {
+      prev = s;
+      s = prev->next;
     }
-
-    /* Recurse to subnodes if they exist */
-    for (i = 0; i < 4; i++)
-    {
-        if (node->subnode[i] && collectClusterShapes(layerinfo, node->subnode[i], current))
-        {
-            /* placing this empty node to the finalization queue */
-            node->subnode[i]->subnode[0] = layerinfo->finalizedNodes;
-            layerinfo->finalizedNodes = node->subnode[i];
-            node->subnode[i] = NULL;
-            ++layerinfo->numFinalizedNodes;
-        }
+  }
+
+  /* Recurse to subnodes if they exist */
+  for (i = 0; i < 4; i++) {
+    if (node->subnode[i] && collectClusterShapes(layerinfo, node->subnode[i], current)) {
+      /* placing this empty node to the finalization queue */
+      node->subnode[i]->subnode[0] = layerinfo->finalizedNodes;
+      layerinfo->finalizedNodes = node->subnode[i];
+      node->subnode[i] = NULL;
+      ++layerinfo->numFinalizedNodes;
     }
+  }
 
-    /* returns true is this subnode must be removed */
-    return (!node->shapes && !node->subnode[0] && !node->subnode[1] 
-                 && !node->subnode[2] && !node->subnode[3]);
+  /* returns true is this subnode must be removed */
+  return (!node->shapes && !node->subnode[0] && !node->subnode[1]
+          && !node->subnode[2] && !node->subnode[3]);
 }
 
 int selectClusterShape(layerObj* layer, long shapeindex)
 {
-	int i;
-    clusterInfo* current;
-    msClusterLayerInfo* layerinfo = (msClusterLayerInfo*)layer->layerinfo;
-
-    if (!layerinfo)
-    {
-        msSetError(MS_MISCERR, "Layer not open: %s", layer->name);
-        return MS_FAILURE;
-    }
-
-    i = 0;
-    current = layerinfo->finalized;
-    while (current && i < shapeindex)
-    {
-        ++i;
-        current = current->next;
-    }
-
-    current->next = current->siblings;
-    layerinfo->current = current;
-    current->shape.line[0].point[0].x = current->shape.bounds.minx = current->shape.bounds.maxx = current->avgx;
-    current->shape.line[0].point[0].y = current->shape.bounds.miny = current->shape.bounds.maxy = current->avgy;
-
-    return MS_SUCCESS;
+  int i;
+  clusterInfo* current;
+  msClusterLayerInfo* layerinfo = (msClusterLayerInfo*)layer->layerinfo;
+
+  if (!layerinfo) {
+    msSetError(MS_MISCERR, "Layer not open: %s", "selectClusterShape()", layer->name);
+    return MS_FAILURE;
+  }
+
+  i = 0;
+  current = layerinfo->finalized;
+  while (current && i < shapeindex) {
+    ++i;
+    current = current->next;
+  }
+
+  current->next = current->siblings;
+  layerinfo->current = current;
+  current->shape.line[0].point[0].x = current->shape.bounds.minx = current->shape.bounds.maxx = current->avgx;
+  current->shape.line[0].point[0].y = current->shape.bounds.miny = current->shape.bounds.maxy = current->avgy;
+
+  return MS_SUCCESS;
 }
 
 /* update the parameters from the related shapes */
 #ifndef NDEBUG
 static void UpdateClusterParameters(msClusterLayerInfo* layerinfo, clusterTreeNode *node, clusterInfo *shape)
 {
-    int i;
-    clusterInfo* s = node->shapes;
-
-    while (s)
-    {
-        if (layerinfo->fnCompare(shape, s))
-        {
-            shape->avgx += s->x;
-            shape->avgy += s->y;
-            ++shape->numsiblings;
-        }
-        s = s->next;
-    }
-
-     /* Recurse to subnodes if they exist */
-    for (i = 0; i < 4; i++)
-    {
-        if (node->subnode[i])
-            UpdateClusterParameters(layerinfo, node->subnode[i], shape);
+  int i;
+  clusterInfo* s = node->shapes;
+
+  while (s) {
+    if (layerinfo->fnCompare(shape, s)) {
+      shape->avgx += s->x;
+      shape->avgy += s->y;
+      ++shape->numsiblings;
     }
+    s = s->next;
+  }
+
+  /* Recurse to subnodes if they exist */
+  for (i = 0; i < 4; i++) {
+    if (node->subnode[i])
+      UpdateClusterParameters(layerinfo, node->subnode[i], shape);
+  }
 }
 
 /* check for the validity of the clusters added to the tree (for debug purposes) */
 static int ValidateTree(msClusterLayerInfo* layerinfo, clusterTreeNode *node)
 {
-    int i;
-    int isValid = MS_TRUE;
-    
-    clusterInfo* s = node->shapes;
-    while (s)
-    {
-        double avgx = s->avgx;
-        double avgy = s->avgy;
-        int numsiblings = s->numsiblings;
-
-        s->avgx = 0;
-        s->avgy = 0;
-        s->numsiblings = 0;
-
-        UpdateClusterParameters(layerinfo, layerinfo->root, s);
-
-        if (numsiblings + 1 != s->numsiblings)
-            isValid = MS_FALSE;
-        else if ((avgx * s->numsiblings - s->avgx) / s->avgx > 0.000001)
-            isValid = MS_FALSE;
-        else if ((avgy * s->numsiblings - s->avgy) / s->avgy > 0.000001)
-            isValid = MS_FALSE;
-        
-        s->avgx = avgx;
-        s->avgy = avgy;
-        s->numsiblings = numsiblings;
-
-        if (isValid == MS_FALSE)
-            return MS_FALSE;
-
-        s = s->next;
-    }
-
-    /* Recurse to subnodes if they exist */
-    for (i = 0; i < 4; i++)
-    {
-        if (node->subnode[i] && ValidateTree(layerinfo, node->subnode[i]) == MS_FALSE)
-            return MS_FALSE;
-    }
-
-    /* returns true if this node contains only valid clusters */
-    return MS_TRUE;
+  int i;
+  int isValid = MS_TRUE;
+
+  clusterInfo* s = node->shapes;
+  while (s) {
+    double avgx = s->avgx;
+    double avgy = s->avgy;
+    int numsiblings = s->numsiblings;
+
+    s->avgx = 0;
+    s->avgy = 0;
+    s->numsiblings = 0;
+
+    UpdateClusterParameters(layerinfo, layerinfo->root, s);
+
+    if (numsiblings + 1 != s->numsiblings)
+      isValid = MS_FALSE;
+    else if ((avgx * s->numsiblings - s->avgx) / s->avgx > 0.000001)
+      isValid = MS_FALSE;
+    else if ((avgy * s->numsiblings - s->avgy) / s->avgy > 0.000001)
+      isValid = MS_FALSE;
+
+    s->avgx = avgx;
+    s->avgy = avgy;
+    s->numsiblings = numsiblings;
+
+    if (isValid == MS_FALSE)
+      return MS_FALSE;
+
+    s = s->next;
+  }
+
+  /* Recurse to subnodes if they exist */
+  for (i = 0; i < 4; i++) {
+    if (node->subnode[i] && ValidateTree(layerinfo, node->subnode[i]) == MS_FALSE)
+      return MS_FALSE;
+  }
+
+  /* returns true if this node contains only valid clusters */
+  return MS_TRUE;
 }
 #endif
 
 /* rebuild the clusters according to the current extent */
 int RebuildClusters(layerObj *layer, int isQuery)
 {
-    mapObj* map;
-	layerObj* srcLayer;
-    double distance, maxDistanceX, maxDistanceY, cellSizeX, cellSizeY;
-    rectObj searchrect;
-    int status;
-    clusterInfo* current;
-    int depth;
+  mapObj* map;
+  layerObj* srcLayer;
+  double distance, maxDistanceX, maxDistanceY, cellSizeX, cellSizeY;
+  rectObj searchrect;
+  int status;
+  clusterInfo* current;
+  int depth;
 #ifdef USE_CLUSTER_EXTERNAL
-    int layerIndex;
+  int layerIndex;
 #endif
 
-    msClusterLayerInfo* layerinfo = layer->layerinfo;
-
-    if (!layerinfo)
-    {
-        msSetError(MS_MISCERR, "Layer is not open: %s", layer->name);
-        return MS_FAILURE;
-    }
-    
-    if (!layer->map)
-    {
-        msSetError(MS_MISCERR, "No map associated with this layer: %s", layer->name);
-        return MS_FAILURE;
-    }
-
-	map = layer->map;
-
-    layerinfo->current = layerinfo->finalized; /* restart */
-
-    /* identify the current extent */
-    if(layer->transform == MS_TRUE)
-        searchrect = map->extent;
-    else 
-    {
-        searchrect.minx = searchrect.miny = 0;
-        searchrect.maxx = map->width-1;
-        searchrect.maxy = map->height-1;
-    }
-
-    if (searchrect.minx == layerinfo->searchRect.minx &&
-        searchrect.miny == layerinfo->searchRect.miny &&
-        searchrect.maxx == layerinfo->searchRect.maxx &&
-        searchrect.maxy == layerinfo->searchRect.maxy)
-    {
-        /* already built */
-        return MS_SUCCESS;
-    }
+  msClusterLayerInfo* layerinfo = layer->layerinfo;
+
+  if (!layerinfo) {
+    msSetError(MS_MISCERR, "Layer is not open: %s", "RebuildClusters()", layer->name);
+    return MS_FAILURE;
+  }
+
+  if (!layer->map) {
+    msSetError(MS_MISCERR, "No map associated with this layer: %s", "RebuildClusters()", layer->name);
+    return MS_FAILURE;
+  }
+
+  if (layer->debug >= MS_DEBUGLEVEL_VVV)
+    msDebug("Clustering started.\n");
+
+  map = layer->map;
+
+  layerinfo->current = layerinfo->finalized; /* restart */
+
+  /* check whether all shapes should be returned from a query */
+  if(msLayerGetProcessingKey(layer, "CLUSTER_GET_ALL_SHAPES") != NULL)
+    layerinfo->get_all_shapes = MS_TRUE;
+  else
+    layerinfo->get_all_shapes = MS_FALSE;
+
+  /* identify the current extent */
+  if(layer->transform == MS_TRUE)
+    searchrect = map->extent;
+  else {
+    searchrect.minx = searchrect.miny = 0;
+    searchrect.maxx = map->width-1;
+    searchrect.maxy = map->height-1;
+  }
+
+  if (searchrect.minx == layerinfo->searchRect.minx &&
+      searchrect.miny == layerinfo->searchRect.miny &&
+      searchrect.maxx == layerinfo->searchRect.maxx &&
+      searchrect.maxy == layerinfo->searchRect.maxy) {
+    /* already built */
+    return MS_SUCCESS;
+  }
 
-    /* destroy previous data*/
-    clusterDestroyData(layerinfo);
+  /* destroy previous data*/
+  clusterDestroyData(layerinfo);
 
-    layerinfo->searchRect = searchrect;
+  layerinfo->searchRect = searchrect;
 
-   /* reproject the rectangle to layer coordinates */
+  /* reproject the rectangle to layer coordinates */
 #ifdef USE_PROJ
   if((map->projection.numargs > 0) && (layer->projection.numargs > 0))
     msProjectRect(&map->projection, &layer->projection, &searchrect); /* project the searchrect to source coords */
 #endif
 
-    /* determine the compare method */
-    layerinfo->fnCompare = CompareRectangleRegion;
-    if (layer->cluster.region)
-	{
-        if (EQUAL(layer->cluster.region, "ellipse"))
-            layerinfo->fnCompare = CompareEllipseRegion;
-    }
-
-    /* trying to find a reasonable quadtree depth */
-    depth = 0;
-    distance = layer->cluster.maxdistance;
-    while ((distance < map->width || distance < map->height) && depth <= TREE_MAX_DEPTH)
-    {
-        distance *= 2;
-        ++depth;
-    }
-
-    layerinfo->depth = depth;
-
-    cellSizeX = MS_CELLSIZE(searchrect.minx, searchrect.maxx, map->width); 
-    cellSizeY = MS_CELLSIZE(searchrect.miny, searchrect.maxy, map->height);
-            
-    maxDistanceX = layer->cluster.maxdistance * cellSizeX; 
-    maxDistanceY = layer->cluster.maxdistance * cellSizeY;
-
-    /* increase the search rectangle so that the neighbouring shapes are also retrieved */
-    searchrect.minx -= layer->cluster.buffer * cellSizeX;
-    searchrect.maxx += layer->cluster.buffer * cellSizeX;
-    searchrect.miny -= layer->cluster.buffer * cellSizeY;
-    searchrect.maxy += layer->cluster.buffer * cellSizeY;
-
-    /* create the root node */
-    if (layerinfo->root)
-        clusterTreeNodeDestroy(layerinfo, layerinfo->root);
-    layerinfo->root = clusterTreeNodeCreate(layerinfo, searchrect);
-
-    srcLayer = &layerinfo->srcLayer;
-
-    /* start retrieving the shapes */
-    status = msLayerWhichShapes(srcLayer, searchrect, isQuery);
-	if(status == MS_DONE) 
-	{ /* no overlap */
-        return MS_SUCCESS;
-	} 
-	else if(status != MS_SUCCESS) 
-	{
-        return MS_FAILURE;
-	}
+  /* determine the compare method */
+  layerinfo->fnCompare = CompareRectangleRegion;
+  if (layer->cluster.region) {
+    if (EQUAL(layer->cluster.region, "ellipse"))
+      layerinfo->fnCompare = CompareEllipseRegion;
+  }
+
+  /* trying to find a reasonable quadtree depth */
+  depth = 0;
+  distance = layer->cluster.maxdistance;
+  while ((distance < map->width || distance < map->height) && depth <= TREE_MAX_DEPTH) {
+    distance *= 2;
+    ++depth;
+  }
+
+  layerinfo->depth = depth;
+
+  cellSizeX = MS_CELLSIZE(searchrect.minx, searchrect.maxx, map->width);
+  cellSizeY = MS_CELLSIZE(searchrect.miny, searchrect.maxy, map->height);
+
+  maxDistanceX = layer->cluster.maxdistance * cellSizeX;
+  maxDistanceY = layer->cluster.maxdistance * cellSizeY;
+
+  /* increase the search rectangle so that the neighbouring shapes are also retrieved */
+  searchrect.minx -= layer->cluster.buffer * cellSizeX;
+  searchrect.maxx += layer->cluster.buffer * cellSizeX;
+  searchrect.miny -= layer->cluster.buffer * cellSizeY;
+  searchrect.maxy += layer->cluster.buffer * cellSizeY;
+
+  /* create the root node */
+  if (layerinfo->root)
+    clusterTreeNodeDestroy(layerinfo, layerinfo->root);
+  layerinfo->root = clusterTreeNodeCreate(layerinfo, searchrect);
+
+  srcLayer = &layerinfo->srcLayer;
+
+  /* start retrieving the shapes */
+  status = msLayerWhichShapes(srcLayer, searchrect, isQuery);
+  if(status == MS_DONE) {
+    /* no overlap */
+    return MS_SUCCESS;
+  } else if(status != MS_SUCCESS) {
+    return MS_FAILURE;
+  }
 
-	/* step through the source shapes and populate the quadtree with the tentative clusters */
-    if ((current = clusterInfoCreate(layerinfo)) == NULL)
-        return MS_FAILURE;
+  /* step through the source shapes and populate the quadtree with the tentative clusters */
+  if ((current = clusterInfoCreate(layerinfo)) == NULL)
+    return MS_FAILURE;
 
-	while((status = msLayerNextShape(srcLayer, &current->shape)) == MS_SUCCESS) 
-	{
+  while((status = msLayerNextShape(srcLayer, &current->shape)) == MS_SUCCESS) {
 #if defined(USE_PROJ) && defined(USE_CLUSTER_EXTERNAL)
-		/* transform the shape to the projection of this layer */
-		if(srcLayer->transform == MS_TRUE && srcLayer->project && layer->transform == MS_TRUE && layer->project &&msProjectionsDiffer(&(srcLayer->projection), &(layer->projection)))
-			msProjectShape(&srcLayer->projection, &layer->projection, &current->shape);
+    /* transform the shape to the projection of this layer */
+    if(srcLayer->transform == MS_TRUE && srcLayer->project && layer->transform == MS_TRUE && layer->project &&msProjectionsDiffer(&(srcLayer->projection), &(layer->projection)))
+      msProjectShape(&srcLayer->projection, &layer->projection, &current->shape);
 #endif
-		/* set up positions and variance */
-        current->avgx = current->x = current->shape.bounds.minx;
-        current->avgy = current->y = current->shape.bounds.miny;
-        current->varx = current->vary = 0;
-        /* set up the area of interest when searching for the neighboring shapes */
-        current->bounds.minx = current->x - maxDistanceX;
-        current->bounds.miny = current->y - maxDistanceY;
-        current->bounds.maxx = current->x + maxDistanceX;
-        current->bounds.maxy = current->y + maxDistanceY;
-
-        /* if the shape doesn't overlap we must skip it to avoid further issues */
-        if(!msRectOverlap(&searchrect, &current->bounds))
-        {
-            msFreeShape(&current->shape);
-            msInitShape(&current->shape);
-
-            msDebug("Skipping an invalid shape falling outside of the given extent\n");
-            continue;
-        }
+    /* set up positions and variance */
+    current->avgx = current->x = current->shape.bounds.minx;
+    current->avgy = current->y = current->shape.bounds.miny;
+    current->varx = current->vary = 0;
+    /* set up the area of interest when searching for the neighboring shapes */
+    current->bounds.minx = current->x - maxDistanceX;
+    current->bounds.miny = current->y - maxDistanceY;
+    current->bounds.maxx = current->x + maxDistanceX;
+    current->bounds.maxy = current->y + maxDistanceY;
+
+    /* if the shape doesn't overlap we must skip it to avoid further issues */
+    if(!msRectOverlap(&searchrect, &current->bounds)) {
+      msFreeShape(&current->shape);
+      msInitShape(&current->shape);
+
+      msDebug("Skipping an invalid shape falling outside of the given extent\n");
+      continue;
+    }
 
-        /* construct the item array */
-        if (layer->iteminfo)
-            BuildFeatureAttributes(layer, layerinfo, &current->shape);
+    /* construct the item array */
+    if (layer->iteminfo)
+      BuildFeatureAttributes(layer, layerinfo, &current->shape);
 
-        /* evaluate the group expression */
-        if (layer->cluster.group.string)
-            current->group = msClusterGetGroupText(&layer->cluster.group, &current->shape);
+    /* evaluate the group expression */
+    if (layer->cluster.group.string)
+      current->group = msClusterGetGroupText(&layer->cluster.group, &current->shape);
 
-        /*start a query for the related shapes */
-        findRelatedShapes(layerinfo, layerinfo->root, current);
+    /*start a query for the related shapes */
+    findRelatedShapes(layerinfo, layerinfo->root, current);
 
-        /* add this shape to the tree */
-        if (treeNodeAddShape(layerinfo, layerinfo->root, current, depth) != MS_SUCCESS)
-        {
-            clusterInfoDestroyList(layerinfo, current);
-            return MS_FAILURE;
-        }
-            
-		if ((current = clusterInfoCreate(layerinfo)) == NULL)
-        {
-            clusterInfoDestroyList(layerinfo, current);
-            return MS_FAILURE;
-        }
-	}
+    /* add this shape to the tree */
+    if (treeNodeAddShape(layerinfo, layerinfo->root, current, depth) != MS_SUCCESS) {
+      clusterInfoDestroyList(layerinfo, current);
+      return MS_FAILURE;
+    }
+
+    if ((current = clusterInfoCreate(layerinfo)) == NULL) {
+      clusterInfoDestroyList(layerinfo, current);
+      return MS_FAILURE;
+    }
+  }
 
-    clusterInfoDestroyList(layerinfo, current);
+  clusterInfoDestroyList(layerinfo, current);
 
-    while (layerinfo->root)
-    {
+  while (layerinfo->root) {
 #ifdef TESTCOUNT
-        int n;
-        double avgx, avgy;
+    int n;
+    double avgx, avgy;
 #endif
-        
-        /* pick up the best cluster from the tree and do the finalization */
-        /* the initial rank must be big enough */
-        layerinfo->rank = (searchrect.maxx - searchrect.minx) * (searchrect.maxx - searchrect.minx) +
-                            (searchrect.maxy - searchrect.miny) * (searchrect.maxy - searchrect.miny) + 1;
 
-        layerinfo->current = NULL;
-        findBestCluster(layer, layerinfo, layerinfo->root);
+    /* pick up the best cluster from the tree and do the finalization */
+    /* the initial rank must be big enough */
+    layerinfo->rank = (searchrect.maxx - searchrect.minx) * (searchrect.maxx - searchrect.minx) +
+                      (searchrect.maxy - searchrect.miny) * (searchrect.maxy - searchrect.miny) + 1;
+
+    layerinfo->current = NULL;
+    findBestCluster(layer, layerinfo, layerinfo->root);
 
-        if (layerinfo->current == NULL)
-            break; /* completed */
+    if (layerinfo->current == NULL) {
+      if (layer->debug >= MS_DEBUGLEVEL_VVV)
+        msDebug("Clustering terminated.\n");
+      break; /* completed */
+    }
+
+    /* Update the feature count of the shape */
+    InitShapeAttributes(layer, layerinfo->current);
+
+    /* collecting the shapes of the cluster */
+    collectClusterShapes(layerinfo, layerinfo->root, layerinfo->current);
+
+    if (layer->debug >= MS_DEBUGLEVEL_VVV) {
+      msDebug("processing cluster %p: rank=%lf fcount=%d ncoll=%d nfin=%d nfins=%d nflt=%d bounds={%lf %lf %lf %lf}\n", layerinfo->current, layerinfo->rank, layerinfo->current->numsiblings + 1,
+              layerinfo->current->numcollected, layerinfo->numFinalized, layerinfo->numFinalizedSiblings,
+              layerinfo->numFiltered, layerinfo->current->bounds.minx, layerinfo->current->bounds.miny,
+              layerinfo->current->bounds.maxx, layerinfo->current->bounds.maxy);
+      if (layerinfo->current->node) {
+        char pszBuffer[TREE_MAX_DEPTH + 1];
+        clusterTreeNode* node = layerinfo->current->node;
+        int position = node->position;
+        int i = 1;
+        while (position > 0 && i <= TREE_MAX_DEPTH) {
+          pszBuffer[TREE_MAX_DEPTH - i] = '0' + (position % 4);
+          position = position >> 2;
+          ++i;
+        }
+        pszBuffer[TREE_MAX_DEPTH] = 0;
 
-        /* Update the feature count of the shape */
-        InitShapeAttributes(layer, layerinfo->current);
-        
-        /* collecting the shapes of the cluster */
-        collectClusterShapes(layerinfo, layerinfo->root, layerinfo->current);
+        msDebug(" ->node %p: count=%d index=%d pos=%s subn={%p %p %p %p} rect={%lf %lf %lf %lf}\n",
+                node, node->numshapes, node->index, pszBuffer + TREE_MAX_DEPTH - i + 1,
+                node->subnode[0], node->subnode[1], node->subnode[2], node->subnode[3],
+                node->rect.minx, node->rect.miny, node->rect.maxx, node->rect.maxy);
+      }
+    }
 
 #ifdef TESTCOUNT
-        avgx = layerinfo->current->x;
-        avgy = layerinfo->current->y;
-        n = 0;
+    avgx = layerinfo->current->x;
+    avgy = layerinfo->current->y;
+    n = 0;
 #endif
 
-        if (layerinfo->current->numsiblings > 0)
-        {
-            /* update the parameters due to the shape removal */
-            findRelatedShapesRemove(layerinfo, layerinfo->root, layerinfo->current);
-
-            if (layerinfo->current->filter == 0)
-            {
-                /* filtered shapes has no siblings */
-                layerinfo->current->numsiblings = 0;
-                layerinfo->current->avgx = layerinfo->current->x;
-                layerinfo->current->avgy = layerinfo->current->y;
-            }
-    
-            /* update the parameters of the related shapes if any */
-            if (layerinfo->finalizedSiblings)
-            {
-                current = layerinfo->finalizedSiblings;
-                while(current)
-                {
-                    /* update the parameters due to the shape removal */
-                    findRelatedShapesRemove(layerinfo, layerinfo->root, current);
-                    UpdateShapeAttributes(layer, layerinfo->current, current);
+    if (layerinfo->current->numsiblings > 0) {
+      /* update the parameters due to the shape removal */
+      findRelatedShapesRemove(layerinfo, layerinfo->root, layerinfo->current);
+
+      if (layerinfo->current->filter == 0) {
+        /* filtered shapes has no siblings */
+        layerinfo->current->numsiblings = 0;
+        layerinfo->current->avgx = layerinfo->current->x;
+        layerinfo->current->avgy = layerinfo->current->y;
+      }
+
+      /* update the parameters of the related shapes if any */
+      if (layerinfo->finalizedSiblings) {
+        current = layerinfo->finalizedSiblings;
+        while(current) {
+          /* update the parameters due to the shape removal */
+          findRelatedShapesRemove(layerinfo, layerinfo->root, current);
+          UpdateShapeAttributes(layer, layerinfo->current, current);
 #ifdef TESTCOUNT
-                    avgx += current->x;
-                    avgy += current->y;
-                    ++n;
+          avgx += current->x;
+          avgy += current->y;
+          ++n;
 #endif
-                    current = current->next;
-                }
-
-                /* preserve the clustered siblings for later use */
-                layerinfo->current->siblings = layerinfo->finalizedSiblings;
-                layerinfo->finalizedSiblings = NULL;
+          /* setting the average position to the same value */
+          current->avgx = layerinfo->current->avgx;
+          current->avgy = layerinfo->current->avgy;
+
+          if (current->next == NULL) {
+            if (layerinfo->get_all_shapes == MS_TRUE) {
+              /* insert the siblings into the finalization list */
+              current->next = layerinfo->finalized;
+              layerinfo->finalized = layerinfo->finalizedSiblings;
+            } else {
+              /* preserve the clustered siblings for later use */
+              layerinfo->current->siblings = layerinfo->finalizedSiblings;
             }
+            break;
+          }
+
+          current = current->next;
         }
 
+        layerinfo->finalizedSiblings = NULL;
+      }
+    }
+
 #ifdef TESTCOUNT
-        avgx /= (n + 1);
-        avgy /= (n + 1);
+    avgx /= (n + 1);
+    avgy /= (n + 1);
 
-        if (layerinfo->current->numsiblings != n)
-            layerinfo->current->numsiblings = n;
+    if (layerinfo->current->numsiblings != n)
+      layerinfo->current->numsiblings = n;
 
-        if (fabs(layerinfo->current->avgx - avgx) / avgx > 0.000000001 ||
-            fabs(layerinfo->current->avgy - avgy) / avgy > 0.000000001)
-        {
-            layerinfo->current->avgx = avgx;
-            layerinfo->current->avgy = avgy;
-        }
-#endif
+    if (fabs(layerinfo->current->avgx - avgx) / avgx > 0.000000001 ||
+        fabs(layerinfo->current->avgy - avgy) / avgy > 0.000000001) {
+      layerinfo->current->avgx = avgx;
+      layerinfo->current->avgy = avgy;
     }
+#endif
+  }
 
-    /* set the pointer to the first shape */
-    layerinfo->current = layerinfo->finalized;
+  /* set the pointer to the first shape */
+  layerinfo->current = layerinfo->finalized;
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 /* Close the the combined layer */
 int msClusterLayerClose(layerObj *layer)
-{   
-    msClusterLayerInfo* layerinfo = (msClusterLayerInfo*)layer->layerinfo;
+{
+  msClusterLayerInfo* layerinfo = (msClusterLayerInfo*)layer->layerinfo;
 
-    if (!layerinfo)
-        return MS_SUCCESS;
+  if (!layerinfo)
+    return MS_SUCCESS;
 
-    clusterDestroyData(layerinfo);
+  clusterDestroyData(layerinfo);
 
-    msLayerClose(&layerinfo->srcLayer);
-    freeLayer(&layerinfo->srcLayer);
+  msLayerClose(&layerinfo->srcLayer);
+  freeLayer(&layerinfo->srcLayer);
 
-    msFree(layerinfo);
-    layer->layerinfo = NULL;
+  msFree(layerinfo);
+  layer->layerinfo = NULL;
 
 #ifndef USE_CLUSTER_EXTERNAL
-    /* switch back to the source layer vtable */
-    msInitializeVirtualTable(layer);
+  /* switch back to the source layer vtable */
+  msInitializeVirtualTable(layer);
 #endif
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 /* Return MS_TRUE if layer is open, MS_FALSE otherwise. */
 int msClusterLayerIsOpen(layerObj *layer)
 {
-    if (layer->layerinfo)
-        return(MS_TRUE);
-    else
-        return(MS_FALSE);
+  if (layer->layerinfo)
+    return(MS_TRUE);
+  else
+    return(MS_FALSE);
 }
 
 /* Free the itemindexes array in a layer. */
 void msClusterLayerFreeItemInfo(layerObj *layer)
 {
-    msFree(layer->iteminfo);
-    layer->iteminfo = NULL;
+  msFree(layer->iteminfo);
+  layer->iteminfo = NULL;
 }
 
 
 /* allocate the iteminfo index array - same order as the item list */
 int msClusterLayerInitItemInfo(layerObj *layer)
 {
-    int i, numitems;
-    int *itemindexes;
+  int i, numitems;
+  int *itemindexes;
 
-    msClusterLayerInfo* layerinfo = (msClusterLayerInfo*)layer->layerinfo;
+  msClusterLayerInfo* layerinfo = (msClusterLayerInfo*)layer->layerinfo;
 
-    if(layer->numitems == 0) 
-    {
-        return MS_SUCCESS;
-    }
+  if(layer->numitems == 0) {
+    return MS_SUCCESS;
+  }
 
-    if (!layerinfo)
-        return MS_FAILURE;
+  if (!layerinfo)
+    return MS_FAILURE;
 
-    /* Cleanup any previous item selection */
-    msClusterLayerFreeItemInfo(layer);
-
-    layer->iteminfo = (int *) msSmallMalloc(sizeof(int) * layer->numitems);
-    
-    itemindexes = layer->iteminfo;
-
-    /* check whether we require attributes from the source layers also */
-    numitems = 0;
-    for (i = 0; i < layer->numitems; i++)
-    {
-        if (EQUAL(layer->items[i], MSCLUSTER_FEATURECOUNT))
-            itemindexes[i] = MSCLUSTER_FEATURECOUNTINDEX;
-        else if (EQUAL(layer->items[i], MSCLUSTER_GROUP))
-            itemindexes[i] = MSCLUSTER_GROUPINDEX;
-        else
-            itemindexes[i] = numitems++;
-    }
+  /* Cleanup any previous item selection */
+  msClusterLayerFreeItemInfo(layer);
 
-    msLayerFreeItemInfo(&layerinfo->srcLayer);
-    if(layerinfo->srcLayer.items) 
-    {
-        msFreeCharArray(layerinfo->srcLayer.items, layerinfo->srcLayer.numitems);
-        layerinfo->srcLayer.items = NULL;
-        layerinfo->srcLayer.numitems = 0;
-    }
+  layer->iteminfo = (int *) msSmallMalloc(sizeof(int) * layer->numitems);
 
-    if (numitems > 0)
-    {
-        /* now allocate and set the layer item parameters  */
-        layerinfo->srcLayer.items = (char **)msSmallMalloc(sizeof(char *)*numitems);
-        layerinfo->srcLayer.numitems = numitems;
-        
-        for (i = 0; i < layer->numitems; i++)
-        {
-            if (itemindexes[i] >= 0)
-            {
-                if (EQUALN(layer->items[i], "Min:", 4))
-                    layerinfo->srcLayer.items[itemindexes[i]] = msStrdup(layer->items[i] + 4);
-                else if (EQUALN(layer->items[i], "Max:", 4))
-                    layerinfo->srcLayer.items[itemindexes[i]] = msStrdup(layer->items[i] + 4);
-                else if (EQUALN(layer->items[i], "Sum:", 4))
-                    layerinfo->srcLayer.items[itemindexes[i]] = msStrdup(layer->items[i] + 4);
-                else if (EQUALN(layer->items[i], "Count:", 6))
-                    layerinfo->srcLayer.items[itemindexes[i]] = msStrdup(layer->items[i] + 6);
-                else
-                    layerinfo->srcLayer.items[itemindexes[i]] = msStrdup(layer->items[i]);
-            }   
-        }
+  itemindexes = layer->iteminfo;
 
-        if (msLayerInitItemInfo(&layerinfo->srcLayer) != MS_SUCCESS)
-            return MS_FAILURE;
+  /* check whether we require attributes from the source layers also */
+  numitems = 0;
+  for (i = 0; i < layer->numitems; i++) {
+    if (EQUAL(layer->items[i], MSCLUSTER_FEATURECOUNT))
+      itemindexes[i] = MSCLUSTER_FEATURECOUNTINDEX;
+    else if (EQUAL(layer->items[i], MSCLUSTER_GROUP))
+      itemindexes[i] = MSCLUSTER_GROUPINDEX;
+    else
+      itemindexes[i] = numitems++;
+  }
+
+  msLayerFreeItemInfo(&layerinfo->srcLayer);
+  if(layerinfo->srcLayer.items) {
+    msFreeCharArray(layerinfo->srcLayer.items, layerinfo->srcLayer.numitems);
+    layerinfo->srcLayer.items = NULL;
+    layerinfo->srcLayer.numitems = 0;
+  }
+
+  if (numitems > 0) {
+    /* now allocate and set the layer item parameters  */
+    layerinfo->srcLayer.items = (char **)msSmallMalloc(sizeof(char *)*numitems);
+    layerinfo->srcLayer.numitems = numitems;
+
+    for (i = 0; i < layer->numitems; i++) {
+      if (itemindexes[i] >= 0) {
+        if (EQUALN(layer->items[i], "Min:", 4))
+          layerinfo->srcLayer.items[itemindexes[i]] = msStrdup(layer->items[i] + 4);
+        else if (EQUALN(layer->items[i], "Max:", 4))
+          layerinfo->srcLayer.items[itemindexes[i]] = msStrdup(layer->items[i] + 4);
+        else if (EQUALN(layer->items[i], "Sum:", 4))
+          layerinfo->srcLayer.items[itemindexes[i]] = msStrdup(layer->items[i] + 4);
+        else if (EQUALN(layer->items[i], "Count:", 6))
+          layerinfo->srcLayer.items[itemindexes[i]] = msStrdup(layer->items[i] + 6);
+        else
+          layerinfo->srcLayer.items[itemindexes[i]] = msStrdup(layer->items[i]);
+      }
     }
 
-    return MS_SUCCESS;
+    if (msLayerInitItemInfo(&layerinfo->srcLayer) != MS_SUCCESS)
+      return MS_FAILURE;
+  }
+
+  return MS_SUCCESS;
 }
 
 /* Execute a query for this layer */
 int msClusterLayerWhichShapes(layerObj *layer, rectObj rect, int isQuery)
 {
-    /* rebuild the cluster database */
+  /* rebuild the cluster database */
   return RebuildClusters(layer, isQuery);
 }
 
 static int prepareShape(layerObj* layer, msClusterLayerInfo* layerinfo, clusterInfo* current, shapeObj* shape)
 {
-    if (msCopyShape(&(current->shape), shape) != MS_SUCCESS) 
-    {
-        msSetError(MS_SHPERR, "Cannot retrieve inline shape. There some problem with the shape", "msClusterLayerNextShape()");
-        return MS_FAILURE;
-    }
+  if (msCopyShape(&(current->shape), shape) != MS_SUCCESS) {
+    msSetError(MS_SHPERR, "Cannot retrieve inline shape. There some problem with the shape", "msClusterLayerNextShape()");
+    return MS_FAILURE;
+  }
 
-    /* update the positions of the cluster shape */
-    shape->line[0].point[0].x = shape->bounds.minx = shape->bounds.maxx = current->avgx;
-    shape->line[0].point[0].y = shape->bounds.miny = shape->bounds.maxy = current->avgy;
+  /* update the positions of the cluster shape */
+  shape->line[0].point[0].x = shape->bounds.minx = shape->bounds.maxx = current->avgx;
+  shape->line[0].point[0].y = shape->bounds.miny = shape->bounds.maxy = current->avgy;
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 /* Execute a query on the DB based on fid. */
 int msClusterLayerGetShape(layerObj *layer, shapeObj *shape, resultObj *record)
 {
-	clusterInfo* current;
-    msClusterLayerInfo* layerinfo = (msClusterLayerInfo*)layer->layerinfo;
-
-    if (!layerinfo)
-    {
-        msSetError(MS_MISCERR, "Layer not open: %s", layer->name);
-        return MS_FAILURE;
-    }
-
-    current = layerinfo->finalized;
-    while (current)
-    {
-        if (record->shapeindex == current->shape.index && 
-            record->tileindex == current->shape.tileindex)
-            break;
-        current = current->next;
-    }
-
-    if (current == NULL) 
-    {
-        msSetError(MS_SHPERR, "No feature with this index.", "msClusterLayerGetShape()");
-        return MS_FAILURE;
-    } 
-
-    return prepareShape(layer, layerinfo, current, shape);
+  clusterInfo* current;
+  msClusterLayerInfo* layerinfo = (msClusterLayerInfo*)layer->layerinfo;
+
+  if (!layerinfo) {
+    msSetError(MS_MISCERR, "Layer not open: %s", "msClusterLayerGetShape()", layer->name);
+    return MS_FAILURE;
+  }
+
+  current = layerinfo->finalized;
+  while (current) {
+    if (record->shapeindex == current->shape.index &&
+        record->tileindex == current->shape.tileindex)
+      break;
+    current = current->next;
+  }
+
+  if (current == NULL) {
+    msSetError(MS_SHPERR, "No feature with this index.", "msClusterLayerGetShape()");
+    return MS_FAILURE;
+  }
+
+  return prepareShape(layer, layerinfo, current, shape);
 }
 
 /* find the next shape with the appropriate shape type */
@@ -1358,177 +1304,172 @@ int msClusterLayerGetShape(layerObj *layer, shapeObj *shape, resultObj *record)
 /* MS_DONE => no more data */
 int msClusterLayerNextShape(layerObj *layer, shapeObj *shape)
 {
-    int rv;
-    msClusterLayerInfo* layerinfo = (msClusterLayerInfo*)layer->layerinfo;
+  int rv;
+  msClusterLayerInfo* layerinfo = (msClusterLayerInfo*)layer->layerinfo;
 
-    if (!layerinfo)
-    {
-        msSetError(MS_MISCERR, "Layer not open: %s", layer->name);
-        return MS_FAILURE;
-    }
+  if (!layerinfo) {
+    msSetError(MS_MISCERR, "Layer not open: %s", "msClusterLayerNextShape()", layer->name);
+    return MS_FAILURE;
+  }
+
+  if (!layerinfo->current)
+    return MS_DONE;
 
-    if (!layerinfo->current)
-        return MS_DONE;
+  rv = prepareShape(layer, layerinfo, layerinfo->current, shape);
 
-    rv = prepareShape(layer, layerinfo, layerinfo->current, shape);
-    
-    layerinfo->current = layerinfo->current->next;
-    
-    return rv;
+  layerinfo->current = layerinfo->current->next;
+
+  return rv;
 }
 
 /* Query for the items collection */
 int msClusterLayerGetItems(layerObj *layer)
 {
-    /* we support certain built in attributes */
-    layer->numitems = MSCLUSTER_NUMITEMS;
-    layer->items = msSmallMalloc(sizeof(char*) * (layer->numitems));
-    layer->items[0] = msStrdup(MSCLUSTER_FEATURECOUNT);
-    layer->items[1] = msStrdup(MSCLUSTER_GROUP);
-    
-    return msClusterLayerInitItemInfo(layer);
+  /* we support certain built in attributes */
+  layer->numitems = MSCLUSTER_NUMITEMS;
+  layer->items = msSmallMalloc(sizeof(char*) * (layer->numitems));
+  layer->items[0] = msStrdup(MSCLUSTER_FEATURECOUNT);
+  layer->items[1] = msStrdup(MSCLUSTER_GROUP);
+
+  return msClusterLayerInitItemInfo(layer);
 }
 
 
 int msClusterLayerGetNumFeatures(layerObj *layer)
 {
-    msClusterLayerInfo* layerinfo = (msClusterLayerInfo*)layer->layerinfo;
+  msClusterLayerInfo* layerinfo = (msClusterLayerInfo*)layer->layerinfo;
 
-    if (!layerinfo)
-        return -1;
+  if (!layerinfo)
+    return -1;
 
-    return layerinfo->numFinalized;
+  return layerinfo->numFinalized;
 }
 
 static int msClusterLayerGetAutoStyle(mapObj *map, layerObj *layer, classObj *c,
-                                  shapeObj* shape)
+                                      shapeObj* shape)
 {
-    /* TODO */
-    return MS_SUCCESS;
+  /* TODO */
+  return MS_SUCCESS;
 }
 
 msClusterLayerInfo* msClusterInitialize(layerObj *layer)
 {
-    msClusterLayerInfo *layerinfo =(msClusterLayerInfo*)msSmallMalloc(sizeof(msClusterLayerInfo));
-    
-    layer->layerinfo = layerinfo;
-    
-    layerinfo->searchRect.minx = -1;
-    layerinfo->searchRect.miny = -1;
-    layerinfo->searchRect.maxx = -1;
-    layerinfo->searchRect.maxy = -1;
+  msClusterLayerInfo *layerinfo =(msClusterLayerInfo*)msSmallMalloc(sizeof(msClusterLayerInfo));
 
-    layerinfo->root = NULL;
+  layer->layerinfo = layerinfo;
 
-    layerinfo->numFeatures = 0;
-    layerinfo->numNodes = 0;
+  layerinfo->searchRect.minx = -1;
+  layerinfo->searchRect.miny = -1;
+  layerinfo->searchRect.maxx = -1;
+  layerinfo->searchRect.maxy = -1;
 
-    layerinfo->finalized = NULL;
-    layerinfo->numFinalized = 0;
-    layerinfo->finalizedSiblings = NULL;
-    layerinfo->numFinalizedSiblings = 0;
-    layerinfo->filtered = NULL;
-    layerinfo->numFiltered = 0;  
+  layerinfo->root = NULL;
 
-    layerinfo->finalizedNodes = NULL;
-    layerinfo->numFinalizedNodes = 0;
+  layerinfo->get_all_shapes = MS_FALSE;
+
+  layerinfo->numFeatures = 0;
+  layerinfo->numNodes = 0;
+
+  layerinfo->finalized = NULL;
+  layerinfo->numFinalized = 0;
+  layerinfo->finalizedSiblings = NULL;
+  layerinfo->numFinalizedSiblings = 0;
+  layerinfo->filtered = NULL;
+  layerinfo->numFiltered = 0;
+
+  layerinfo->finalizedNodes = NULL;
+  layerinfo->numFinalizedNodes = 0;
 
-    return layerinfo;
+  return layerinfo;
 }
 
 int msClusterLayerOpen(layerObj *layer)
 {
-    msClusterLayerInfo* layerinfo;
-    
-    if (layer->type != MS_LAYER_POINT)
-    {
-        msSetError(MS_MISCERR, "Only point layers are supported for clustering: %s", layer->name);
-        return MS_FAILURE;
-    }
+  msClusterLayerInfo* layerinfo;
 
-    if (!layer->map)
-        return MS_FAILURE;
+  if (layer->type != MS_LAYER_POINT) {
+    msSetError(MS_MISCERR, "Only point layers are supported for clustering: %s", "msClusterLayerOpen()", layer->name);
+    return MS_FAILURE;
+  }
 
-    if (layer->layerinfo)
-        return MS_SUCCESS;  // already open
-    
-    layerinfo = msClusterInitialize(layer);
+  if (!layer->map)
+    return MS_FAILURE;
 
-    if (!layer->layerinfo)
-        return MS_FAILURE;
+  if (layer->layerinfo)
+    return MS_SUCCESS;  /* already open */
 
-    /* prepare the source layer */
-    if(initLayer(&layerinfo->srcLayer, layer->map) == -1) 
-		return MS_FAILURE;
+  layerinfo = msClusterInitialize(layer);
+
+  if (!layer->layerinfo)
+    return MS_FAILURE;
+
+  /* prepare the source layer */
+  if(initLayer(&layerinfo->srcLayer, layer->map) == -1)
+    return MS_FAILURE;
 
 #ifdef USE_CLUSTER_EXTERNAL
-    if (!layer->map)
-        return MS_FAILURE;
+  if (!layer->map)
+    return MS_FAILURE;
 
-    layerIndex = msGetLayerIndex(layer->map, layer->connection);
+  layerIndex = msGetLayerIndex(layer->map, layer->connection);
 
-    if (layerIndex < 0 && layerIndex >= layer->map->numlayers)
-    {
-        msSetError(MS_MISCERR, "No source layers specified in layer: %s", layer->name);
-        return MS_FAILURE;
-    }
+  if (layerIndex < 0 && layerIndex >= layer->map->numlayers) {
+    msSetError(MS_MISCERR, "No source layers specified in layer: %s", "msClusterLayerOpen()", layer->name);
+    return MS_FAILURE;
+  }
 
-    if (layer->map->layers[layerIndex]->type != MS_LAYER_POINT)
-    {
-        msSetError(MS_MISCERR, "Only point layers are supported for cluster data source: %s", layer->name);
-        return MS_FAILURE;
-    }
+  if (layer->map->layers[layerIndex]->type != MS_LAYER_POINT) {
+    msSetError(MS_MISCERR, "Only point layers are supported for cluster data source: %s", "msClusterLayerOpen()", layer->name);
+    return MS_FAILURE;
+  }
 
-    if (msCopyLayer(&layerinfo->srcLayer, layer->map->layers[layerIndex]) != MS_SUCCESS)
-		return(MS_FAILURE);
+  if (msCopyLayer(&layerinfo->srcLayer, layer->map->layers[layerIndex]) != MS_SUCCESS)
+    return(MS_FAILURE);
 #else
-    /* hook the vtable to this driver, will be restored in LayerClose*/
-    if (!layer->vtable)
-    {
-        if (msInitializeVirtualTable(layer) != MS_SUCCESS)
-            return MS_FAILURE;
-    }
-    msClusterLayerCopyVirtualTable(layer->vtable);
-
-    if (msCopyLayer(&layerinfo->srcLayer, layer) != MS_SUCCESS)
-		return(MS_FAILURE);
+  /* hook the vtable to this driver, will be restored in LayerClose*/
+  if (!layer->vtable) {
+    if (msInitializeVirtualTable(layer) != MS_SUCCESS)
+      return MS_FAILURE;
+  }
+  msClusterLayerCopyVirtualTable(layer->vtable);
+
+  if (msCopyLayer(&layerinfo->srcLayer, layer) != MS_SUCCESS)
+    return(MS_FAILURE);
 #endif
 
-    /* disable the connection pool for this layer */
-    msLayerSetProcessingKey(&layerinfo->srcLayer, "CLOSE_CONNECTION", "ALWAYS");
+  /* disable the connection pool for this layer */
+  msLayerSetProcessingKey(&layerinfo->srcLayer, "CLOSE_CONNECTION", "ALWAYS");
 
-    /* open the source layer */
-    if ( !layerinfo->srcLayer.vtable) 
-    {
-        if (msInitializeVirtualTable(&layerinfo->srcLayer) != MS_SUCCESS)
-            return MS_FAILURE;
-    }
+  /* open the source layer */
+  if ( !layerinfo->srcLayer.vtable) {
+    if (msInitializeVirtualTable(&layerinfo->srcLayer) != MS_SUCCESS)
+      return MS_FAILURE;
+  }
 
-    if (layerinfo->srcLayer.vtable->LayerOpen(&layerinfo->srcLayer) != MS_SUCCESS)
-    {
-        return MS_FAILURE;
-    }
+  if (layerinfo->srcLayer.vtable->LayerOpen(&layerinfo->srcLayer) != MS_SUCCESS) {
+    return MS_FAILURE;
+  }
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 void msClusterLayerCopyVirtualTable(layerVTableObj* vtable)
 {
-    vtable->LayerInitItemInfo = msClusterLayerInitItemInfo;
-    vtable->LayerFreeItemInfo = msClusterLayerFreeItemInfo;
-    vtable->LayerOpen = msClusterLayerOpen;
-    vtable->LayerIsOpen = msClusterLayerIsOpen;
-    vtable->LayerWhichShapes = msClusterLayerWhichShapes;
-    vtable->LayerNextShape = msClusterLayerNextShape;
-    vtable->LayerGetShape = msClusterLayerGetShape;
-
-    vtable->LayerClose = msClusterLayerClose;
-
-    vtable->LayerGetItems = msClusterLayerGetItems;
-    vtable->LayerCloseConnection = msClusterLayerClose;
-    
-    vtable->LayerGetNumFeatures = msClusterLayerGetNumFeatures;
-    vtable->LayerGetAutoStyle = msClusterLayerGetAutoStyle;
+  vtable->LayerInitItemInfo = msClusterLayerInitItemInfo;
+  vtable->LayerFreeItemInfo = msClusterLayerFreeItemInfo;
+  vtable->LayerOpen = msClusterLayerOpen;
+  vtable->LayerIsOpen = msClusterLayerIsOpen;
+  vtable->LayerWhichShapes = msClusterLayerWhichShapes;
+  vtable->LayerNextShape = msClusterLayerNextShape;
+  vtable->LayerGetShape = msClusterLayerGetShape;
+
+  vtable->LayerClose = msClusterLayerClose;
+
+  vtable->LayerGetItems = msClusterLayerGetItems;
+  vtable->LayerCloseConnection = msClusterLayerClose;
+
+  vtable->LayerGetNumFeatures = msClusterLayerGetNumFeatures;
+  vtable->LayerGetAutoStyle = msClusterLayerGetAutoStyle;
 }
 
 #ifdef USE_CLUSTER_PLUGIN
@@ -1536,12 +1477,12 @@ void msClusterLayerCopyVirtualTable(layerVTableObj* vtable)
 MS_DLL_EXPORT  int
 PluginInitializeVirtualTable(layerVTableObj* vtable, layerObj *layer)
 {
-    assert(layer != NULL);
-    assert(vtable != NULL);
+  assert(layer != NULL);
+  assert(vtable != NULL);
 
-    msClusterLayerCopyVirtualTable(vtable);
+  msClusterLayerCopyVirtualTable(vtable);
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 #endif
@@ -1549,10 +1490,10 @@ PluginInitializeVirtualTable(layerVTableObj* vtable, layerObj *layer)
 int
 msClusterLayerInitializeVirtualTable(layerObj *layer)
 {
-    assert(layer != NULL);
-    assert(layer->vtable != NULL);
+  assert(layer != NULL);
+  assert(layer->vtable != NULL);
 
-    msClusterLayerCopyVirtualTable(layer->vtable);
+  msClusterLayerCopyVirtualTable(layer->vtable);
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
diff --git a/mapcontext.c b/mapcontext.c
index 33a2a77..a47770c 100644
--- a/mapcontext.c
+++ b/mapcontext.c
@@ -14,21 +14,21 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
+ *
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  ****************************************************************************/
 
 #include "mapserver.h"
 
-MS_CVSID("$Id$")
+
 
 #if defined(USE_WMS_LYR) && defined(USE_OGR)
 
@@ -48,20 +48,18 @@ char * msGetMapContextFileText(char *filename)
 {
   char *pszBuffer;
   FILE *stream;
-  int	 nLength;
- 
+  int  nLength;
+
   /* open file */
   if(filename != NULL && strlen(filename) > 0) {
-      stream = fopen(filename, "rb");
-      if(!stream) {
-          msSetError(MS_IOERR, "(%s)", "msGetMapContextFileText()", filename);
-          return NULL;
-      }
-  }
-  else
-  {
+    stream = fopen(filename, "rb");
+    if(!stream) {
       msSetError(MS_IOERR, "(%s)", "msGetMapContextFileText()", filename);
       return NULL;
+    }
+  } else {
+    msSetError(MS_IOERR, "(%s)", "msGetMapContextFileText()", filename);
+    return NULL;
   }
 
   fseek( stream, 0, SEEK_END );
@@ -69,19 +67,17 @@ char * msGetMapContextFileText(char *filename)
   fseek( stream, 0, SEEK_SET );
 
   pszBuffer = (char *) malloc(nLength+1);
-  if( pszBuffer == NULL )
-  {
-      msSetError(MS_MEMERR, "(%s)", "msGetMapContextFileText()", filename);
-      fclose( stream );
-      return NULL;
+  if( pszBuffer == NULL ) {
+    msSetError(MS_MEMERR, "(%s)", "msGetMapContextFileText()", filename);
+    fclose( stream );
+    return NULL;
   }
-  
-  if(fread( pszBuffer, nLength, 1, stream ) == 0 &&  !feof(stream))
-  {
-      free( pszBuffer );
-      fclose( stream );
-      msSetError(MS_IOERR, "(%s)", "msGetMapContextFileText()", filename);
-      return NULL;
+
+  if(fread( pszBuffer, nLength, 1, stream ) == 0 &&  !feof(stream)) {
+    free( pszBuffer );
+    fclose( stream );
+    msSetError(MS_IOERR, "(%s)", "msGetMapContextFileText()", filename);
+    return NULL;
   }
   pszBuffer[nLength] = '\0';
 
@@ -99,26 +95,20 @@ char * msGetMapContextFileText(char *filename)
 **Get the xml value and put it in the hash table
 **
 */
-int msGetMapContextXMLHashValue( CPLXMLNode *psRoot, const char *pszXMLPath, 
+int msGetMapContextXMLHashValue( CPLXMLNode *psRoot, const char *pszXMLPath,
                                  hashTableObj *metadata, char *pszMetadata )
 {
   char *pszValue;
 
   pszValue = (char*)CPLGetXMLValue( psRoot, pszXMLPath, NULL);
-  if(pszValue != NULL)
-  {
-      if( metadata != NULL )
-      {
-          msInsertHashTable(metadata, pszMetadata, pszValue );
-      }
-      else
-      {
-          return MS_FAILURE;
-      }
-  }
-  else
-  {
+  if(pszValue != NULL) {
+    if( metadata != NULL ) {
+      msInsertHashTable(metadata, pszMetadata, pszValue );
+    } else {
       return MS_FAILURE;
+    }
+  } else {
+    return MS_FAILURE;
   }
 
   return MS_SUCCESS;
@@ -130,29 +120,23 @@ int msGetMapContextXMLHashValue( CPLXMLNode *psRoot, const char *pszXMLPath,
 **Get the xml value and put it in the hash table
 **
 */
-int msGetMapContextXMLHashValueDecode( CPLXMLNode *psRoot, 
-                                       const char *pszXMLPath, 
-                                       hashTableObj *metadata, 
+int msGetMapContextXMLHashValueDecode( CPLXMLNode *psRoot,
+                                       const char *pszXMLPath,
+                                       hashTableObj *metadata,
                                        char *pszMetadata )
 {
   char *pszValue;
 
   pszValue = (char*)CPLGetXMLValue( psRoot, pszXMLPath, NULL);
-  if(pszValue != NULL)
-  {
-      if( metadata != NULL )
-      {
-          msDecodeHTMLEntities(pszValue);
-          msInsertHashTable(metadata, pszMetadata, pszValue );
-      }
-      else
-      {
-          return MS_FAILURE;
-      }
-  }
-  else
-  {
+  if(pszValue != NULL) {
+    if( metadata != NULL ) {
+      msDecodeHTMLEntities(pszValue);
+      msInsertHashTable(metadata, pszMetadata, pszValue );
+    } else {
       return MS_FAILURE;
+    }
+  } else {
+    return MS_FAILURE;
   }
 
   return MS_SUCCESS;
@@ -165,26 +149,20 @@ int msGetMapContextXMLHashValueDecode( CPLXMLNode *psRoot,
 **Get the xml value and put it in the string field
 **
 */
-int msGetMapContextXMLStringValue( CPLXMLNode *psRoot, char *pszXMLPath, 
+int msGetMapContextXMLStringValue( CPLXMLNode *psRoot, char *pszXMLPath,
                                    char **pszField)
 {
   char *pszValue;
 
   pszValue = (char*)CPLGetXMLValue( psRoot, pszXMLPath, NULL);
-  if(pszValue != NULL)
-  {
-      if( pszField != NULL )
-      {
-           *pszField = msStrdup(pszValue);
-      }
-      else
-      {
-          return MS_FAILURE;
-      }
-  }
-  else
-  {
+  if(pszValue != NULL) {
+    if( pszField != NULL ) {
+      *pszField = msStrdup(pszValue);
+    } else {
       return MS_FAILURE;
+    }
+  } else {
+    return MS_FAILURE;
   }
 
   return MS_SUCCESS;
@@ -197,27 +175,21 @@ int msGetMapContextXMLStringValue( CPLXMLNode *psRoot, char *pszXMLPath,
 **Get the xml value and put it in the string field
 **
 */
-int msGetMapContextXMLStringValueDecode( CPLXMLNode *psRoot, char *pszXMLPath, 
-                                         char **pszField)
+int msGetMapContextXMLStringValueDecode( CPLXMLNode *psRoot, char *pszXMLPath,
+    char **pszField)
 {
   char *pszValue;
 
   pszValue = (char*)CPLGetXMLValue( psRoot, pszXMLPath, NULL);
-  if(pszValue != NULL)
-  {
-      if( pszField != NULL )
-      {
-          msDecodeHTMLEntities(pszValue);
-          *pszField = msStrdup(pszValue);
-      }
-      else
-      {
-          return MS_FAILURE;
-      }
-  }
-  else
-  {
+  if(pszValue != NULL) {
+    if( pszField != NULL ) {
+      msDecodeHTMLEntities(pszValue);
+      *pszField = msStrdup(pszValue);
+    } else {
       return MS_FAILURE;
+    }
+  } else {
+    return MS_FAILURE;
   }
 
   return MS_SUCCESS;
@@ -230,26 +202,20 @@ int msGetMapContextXMLStringValueDecode( CPLXMLNode *psRoot, char *pszXMLPath,
 **Get the xml value and put it in the string field
 **
 */
-int msGetMapContextXMLFloatValue( CPLXMLNode *psRoot, char *pszXMLPath, 
-                                        double *pszField)
+int msGetMapContextXMLFloatValue( CPLXMLNode *psRoot, char *pszXMLPath,
+                                  double *pszField)
 {
   char *pszValue;
 
   pszValue = (char*)CPLGetXMLValue( psRoot, pszXMLPath, NULL);
-  if(pszValue != NULL)
-  {
-      if( pszField != NULL )
-      {
-          *pszField = atof(pszValue);
-      }
-      else
-      {
-          return MS_FAILURE;
-      }
-  }
-  else
-  {
+  if(pszValue != NULL) {
+    if( pszField != NULL ) {
+      *pszField = atof(pszValue);
+    } else {
       return MS_FAILURE;
+    }
+  } else {
+    return MS_FAILURE;
   }
 
   return MS_SUCCESS;
@@ -261,13 +227,13 @@ int msGetMapContextXMLFloatValue( CPLXMLNode *psRoot, char *pszXMLPath,
 ** Take a Node and get the width, height, format and href from it.
 ** Then put this info in metadatas.
 */
-int msLoadMapContextURLELements( CPLXMLNode *psRoot, hashTableObj *metadata, 
+int msLoadMapContextURLELements( CPLXMLNode *psRoot, hashTableObj *metadata,
                                  const char *pszMetadataRoot)
 {
   char *pszMetadataName;
 
   if( psRoot == NULL || metadata == NULL || pszMetadataRoot == NULL )
-      return MS_FAILURE;
+    return MS_FAILURE;
 
   pszMetadataName = (char*) malloc( strlen(pszMetadataRoot) + 10 );
 
@@ -281,7 +247,7 @@ int msLoadMapContextURLELements( CPLXMLNode *psRoot, hashTableObj *metadata,
   msGetMapContextXMLHashValue( psRoot, "format", metadata, pszMetadataName );
 
   sprintf( pszMetadataName, "%s_href", pszMetadataRoot );
-  msGetMapContextXMLHashValue( psRoot, "OnlineResource.xlink:href", metadata, 
+  msGetMapContextXMLHashValue( psRoot, "OnlineResource.xlink:href", metadata,
                                pszMetadataName );
 
   free(pszMetadataName);
@@ -295,41 +261,37 @@ int msLoadMapContextURLELements( CPLXMLNode *psRoot, hashTableObj *metadata,
 ** psRoot should be set to keywordlist
 */
 int msLoadMapContextListInMetadata( CPLXMLNode *psRoot, hashTableObj *metadata,
-                                    char *pszXMLName, char *pszMetadataName, 
+                                    char *pszXMLName, char *pszMetadataName,
                                     char *pszHashDelimiter)
 {
   char *pszHash, *pszXMLValue, *pszMetadata;
 
-  if(psRoot == NULL || psRoot->psChild == NULL || 
-     metadata == NULL || pszMetadataName == NULL || pszXMLName == NULL)
-      return MS_FAILURE;
+  if(psRoot == NULL || psRoot->psChild == NULL ||
+      metadata == NULL || pszMetadataName == NULL || pszXMLName == NULL)
+    return MS_FAILURE;
 
   /* Pass from KeywordList to Keyword level */
   psRoot = psRoot->psChild;
 
   /* Loop on all elements and append keywords to the hash table */
-  while (psRoot)
-  {
-      if (psRoot->psChild && strcasecmp(psRoot->pszValue, pszXMLName) == 0)
-      {
-          pszXMLValue = psRoot->psChild->pszValue;
-          pszHash = msLookupHashTable(metadata, pszMetadataName);
-          if (pszHash != NULL)
-          {
-              pszMetadata = (char*)malloc(strlen(pszHash)+
-                                          strlen(pszXMLValue)+2);
-              if(pszHashDelimiter == NULL)
-                  sprintf( pszMetadata, "%s%s", pszHash, pszXMLValue );
-              else
-                  sprintf( pszMetadata, "%s%s%s", pszHash, pszHashDelimiter, 
-                           pszXMLValue );
-              msInsertHashTable(metadata, pszMetadataName, pszMetadata);
-              free(pszMetadata);
-          }
-          else
-              msInsertHashTable(metadata, pszMetadataName, pszXMLValue);
-      }
-      psRoot = psRoot->psNext;   
+  while (psRoot) {
+    if (psRoot->psChild && strcasecmp(psRoot->pszValue, pszXMLName) == 0) {
+      pszXMLValue = psRoot->psChild->pszValue;
+      pszHash = msLookupHashTable(metadata, pszMetadataName);
+      if (pszHash != NULL) {
+        pszMetadata = (char*)malloc(strlen(pszHash)+
+                                    strlen(pszXMLValue)+2);
+        if(pszHashDelimiter == NULL)
+          sprintf( pszMetadata, "%s%s", pszHash, pszXMLValue );
+        else
+          sprintf( pszMetadata, "%s%s%s", pszHash, pszHashDelimiter,
+                   pszXMLValue );
+        msInsertHashTable(metadata, pszMetadataName, pszMetadata);
+        free(pszMetadata);
+      } else
+        msInsertHashTable(metadata, pszMetadataName, pszXMLValue);
+    }
+    psRoot = psRoot->psNext;
   }
 
   return MS_SUCCESS;
@@ -342,40 +304,40 @@ int msLoadMapContextListInMetadata( CPLXMLNode *psRoot, hashTableObj *metadata,
 */
 int msLoadMapContextContactInfo( CPLXMLNode *psRoot, hashTableObj *metadata )
 {
-    if(psRoot == NULL || metadata == NULL)
-        return MS_FAILURE;
+  if(psRoot == NULL || metadata == NULL)
+    return MS_FAILURE;
 
-    /* Contact Person primary */
-    msGetMapContextXMLHashValue(psRoot, 
-                              "ContactPersonPrimary.ContactPerson", 
+  /* Contact Person primary */
+  msGetMapContextXMLHashValue(psRoot,
+                              "ContactPersonPrimary.ContactPerson",
                               metadata, "wms_contactperson");
-  msGetMapContextXMLHashValue(psRoot, 
-                              "ContactPersonPrimary.ContactOrganization", 
+  msGetMapContextXMLHashValue(psRoot,
+                              "ContactPersonPrimary.ContactOrganization",
                               metadata, "wms_contactorganization");
   /* Contact Position */
-  msGetMapContextXMLHashValue(psRoot, 
-                              "ContactPosition", 
+  msGetMapContextXMLHashValue(psRoot,
+                              "ContactPosition",
                               metadata, "wms_contactposition");
   /* Contact Address */
-  msGetMapContextXMLHashValue(psRoot, "ContactAddress.AddressType", 
+  msGetMapContextXMLHashValue(psRoot, "ContactAddress.AddressType",
                               metadata, "wms_addresstype");
-  msGetMapContextXMLHashValue(psRoot, "ContactAddress.Address", 
+  msGetMapContextXMLHashValue(psRoot, "ContactAddress.Address",
                               metadata, "wms_address");
-  msGetMapContextXMLHashValue(psRoot, "ContactAddress.City", 
+  msGetMapContextXMLHashValue(psRoot, "ContactAddress.City",
                               metadata, "wms_city");
-  msGetMapContextXMLHashValue(psRoot, "ContactAddress.StateOrProvince", 
+  msGetMapContextXMLHashValue(psRoot, "ContactAddress.StateOrProvince",
                               metadata, "wms_stateorprovince");
-  msGetMapContextXMLHashValue(psRoot, "ContactAddress.PostCode", 
+  msGetMapContextXMLHashValue(psRoot, "ContactAddress.PostCode",
                               metadata, "wms_postcode");
-  msGetMapContextXMLHashValue(psRoot, "ContactAddress.Country", 
+  msGetMapContextXMLHashValue(psRoot, "ContactAddress.Country",
                               metadata, "wms_country");
 
   /* Others */
-  msGetMapContextXMLHashValue(psRoot, "ContactVoiceTelephone", 
+  msGetMapContextXMLHashValue(psRoot, "ContactVoiceTelephone",
                               metadata, "wms_contactvoicetelephone");
-  msGetMapContextXMLHashValue(psRoot, "ContactFacsimileTelephone", 
+  msGetMapContextXMLHashValue(psRoot, "ContactFacsimileTelephone",
                               metadata, "wms_contactfacsimiletelephone");
-  msGetMapContextXMLHashValue(psRoot, "ContactElectronicMailAddress", 
+  msGetMapContextXMLHashValue(psRoot, "ContactElectronicMailAddress",
                               metadata, "wms_contactelectronicmailaddress");
 
   return MS_SUCCESS;
@@ -390,41 +352,36 @@ int msLoadMapContextLayerFormat(CPLXMLNode *psFormat, layerObj *layer)
 {
   char *pszValue, *pszValue1, *pszHash;
 
-  if(psFormat->psChild != NULL && 
-     strcasecmp(psFormat->pszValue, "Format") == 0 )
-  {
-      if(psFormat->psChild->psNext == NULL)
-          pszValue = psFormat->psChild->pszValue;
-      else
-          pszValue = psFormat->psChild->psNext->pszValue;
-  }
-  else
-      pszValue = NULL;
-
-  if(pszValue != NULL && strcasecmp(pszValue, "") != 0)
-  {
-      /* wms_format */
-      pszValue1 = (char*)CPLGetXMLValue(psFormat, 
-                                        "current", NULL);
-      if(pszValue1 != NULL && 
-         (strcasecmp(pszValue1, "1") == 0 || strcasecmp(pszValue1, "true")==0))
-          msInsertHashTable(&(layer->metadata), 
-                            "wms_format", pszValue);
-      /* wms_formatlist */
-      pszHash = msLookupHashTable(&(layer->metadata), 
-                                  "wms_formatlist");
-      if(pszHash != NULL)
-      {
-          pszValue1 = (char*)malloc(strlen(pszHash)+
-                                    strlen(pszValue)+2);
-          sprintf(pszValue1, "%s,%s", pszHash, pszValue);
-          msInsertHashTable(&(layer->metadata), 
-                            "wms_formatlist", pszValue1);
-          free(pszValue1);
-      }
-      else
-          msInsertHashTable(&(layer->metadata), 
-                            "wms_formatlist", pszValue);
+  if(psFormat->psChild != NULL &&
+      strcasecmp(psFormat->pszValue, "Format") == 0 ) {
+    if(psFormat->psChild->psNext == NULL)
+      pszValue = psFormat->psChild->pszValue;
+    else
+      pszValue = psFormat->psChild->psNext->pszValue;
+  } else
+    pszValue = NULL;
+
+  if(pszValue != NULL && strcasecmp(pszValue, "") != 0) {
+    /* wms_format */
+    pszValue1 = (char*)CPLGetXMLValue(psFormat,
+                                      "current", NULL);
+    if(pszValue1 != NULL &&
+        (strcasecmp(pszValue1, "1") == 0 || strcasecmp(pszValue1, "true")==0))
+      msInsertHashTable(&(layer->metadata),
+                        "wms_format", pszValue);
+    /* wms_formatlist */
+    pszHash = msLookupHashTable(&(layer->metadata),
+                                "wms_formatlist");
+    if(pszHash != NULL) {
+      pszValue1 = (char*)malloc(strlen(pszHash)+
+                                strlen(pszValue)+2);
+      sprintf(pszValue1, "%s,%s", pszHash, pszValue);
+      msInsertHashTable(&(layer->metadata),
+                        "wms_formatlist", pszValue1);
+      free(pszValue1);
+    } else
+      msInsertHashTable(&(layer->metadata),
+                        "wms_formatlist", pszValue);
   }
 
   /* Make sure selected format is supported or select another
@@ -435,59 +392,56 @@ int msLoadMapContextLayerFormat(CPLXMLNode *psFormat, layerObj *layer)
   pszValue = msLookupHashTable(&(layer->metadata), "wms_format");
 
   if (
-#ifndef USE_GD_PNG
-      strcasecmp(pszValue, "image/png") == 0 || 
-      strcasecmp(pszValue, "PNG") == 0 ||
+#if !(defined USE_GD_PNG || defined USE_PNG)
+    strcasecmp(pszValue, "image/png") == 0 ||
+    strcasecmp(pszValue, "PNG") == 0 ||
 #endif
-#ifndef USE_GD_JPEG
-      strcasecmp(pszValue, "image/jpeg") == 0 || 
-      strcasecmp(pszValue, "JPEG") == 0 ||
+#if !(defined USE_GD_JPEG || defined USE_JPEG)
+    strcasecmp(pszValue, "image/jpeg") == 0 ||
+    strcasecmp(pszValue, "JPEG") == 0 ||
 #endif
 #ifndef USE_GD_GIF
-      strcasecmp(pszValue, "image/gif") == 0 || 
-      strcasecmp(pszValue, "GIF") == 0 ||
+    strcasecmp(pszValue, "image/gif") == 0 ||
+    strcasecmp(pszValue, "GIF") == 0 ||
 #endif
-      0 )
-  {
-      char **papszList=NULL;
-      int i, numformats=0;
-
-      pszValue = msLookupHashTable(&(layer->metadata), 
-                                   "wms_formatlist");
-
-      papszList = msStringSplit(pszValue, ',', &numformats);
-      for(i=0; i < numformats; i++)
-      {
-          if (
-#ifdef USE_GD_PNG
-              strcasecmp(papszList[i], "image/png") == 0 || 
-              strcasecmp(papszList[i], "PNG") == 0 ||
+    0 ) {
+    char **papszList=NULL;
+    int i, numformats=0;
+
+    pszValue = msLookupHashTable(&(layer->metadata),
+                                 "wms_formatlist");
+
+    papszList = msStringSplit(pszValue, ',', &numformats);
+    for(i=0; i < numformats; i++) {
+      if (
+#if (defined USE_GD_PNG || defined USE_PNG)
+        strcasecmp(papszList[i], "image/png") == 0 ||
+        strcasecmp(papszList[i], "PNG") == 0 ||
 #endif
-#ifdef USE_GD_JPEG
-              strcasecmp(papszList[i], "image/jpeg") == 0 || 
-              strcasecmp(papszList[i], "JPEG") == 0 ||
+#if (defined USE_GD_JPEG || defined USE_JPEG)
+        strcasecmp(papszList[i], "image/jpeg") == 0 ||
+        strcasecmp(papszList[i], "JPEG") == 0 ||
 #endif
 #ifdef USE_GD_GIF
-              strcasecmp(papszList[i], "image/gif") == 0 || 
-              strcasecmp(papszList[i], "GIF") == 0 ||
+        strcasecmp(papszList[i], "image/gif") == 0 ||
+        strcasecmp(papszList[i], "GIF") == 0 ||
 #endif
-              0 )
-          {
-              /* Found a match */
-              msInsertHashTable(&(layer->metadata), 
-                                "wms_format", papszList[i]);
-              break;
-          }
+        0 ) {
+        /* Found a match */
+        msInsertHashTable(&(layer->metadata),
+                          "wms_format", papszList[i]);
+        break;
       }
-      if(papszList)
-          msFreeCharArray(papszList, numformats);
+    }
+    if(papszList)
+      msFreeCharArray(papszList, numformats);
 
   } /* end if unsupported format */
 
   return MS_SUCCESS;
 }
 
-int msLoadMapContextLayerStyle(CPLXMLNode *psStyle, layerObj *layer, 
+int msLoadMapContextLayerStyle(CPLXMLNode *psStyle, layerObj *layer,
                                int nStyle)
 {
   char *pszValue, *pszValue1, *pszValue2;
@@ -495,52 +449,48 @@ int msLoadMapContextLayerStyle(CPLXMLNode *psStyle, layerObj *layer,
   CPLXMLNode *psStyleSLDBody;
 
   pszStyleName =(char*)CPLGetXMLValue(psStyle,"Name",NULL);
-  if(pszStyleName == NULL)
-  {
-       pszStyleName = (char*)malloc(15);
-       sprintf(pszStyleName, "Style{%d}", nStyle);
-  }
-  else
-      pszStyleName = msStrdup(pszStyleName);
+  if(pszStyleName == NULL) {
+    pszStyleName = (char*)malloc(20);
+    sprintf(pszStyleName, "Style{%d}", nStyle);
+  } else
+    pszStyleName = msStrdup(pszStyleName);
 
   /* wms_style */
   pszValue = (char*)CPLGetXMLValue(psStyle,"current",NULL);
-  if(pszValue != NULL && 
-     (strcasecmp(pszValue, "1") == 0 || 
-      strcasecmp(pszValue, "true") == 0))
-      msInsertHashTable(&(layer->metadata), 
-                        "wms_style", pszStyleName);
+  if(pszValue != NULL &&
+      (strcasecmp(pszValue, "1") == 0 ||
+       strcasecmp(pszValue, "true") == 0))
+    msInsertHashTable(&(layer->metadata),
+                      "wms_style", pszStyleName);
   /* wms_stylelist */
-  pszHash = msLookupHashTable(&(layer->metadata), 
+  pszHash = msLookupHashTable(&(layer->metadata),
                               "wms_stylelist");
-  if(pszHash != NULL)
-  {
-      pszValue1 = (char*)malloc(strlen(pszHash)+
-                                strlen(pszStyleName)+2);
-      sprintf(pszValue1, "%s,%s", pszHash, pszStyleName);
-      msInsertHashTable(&(layer->metadata), 
-                        "wms_stylelist", pszValue1);
-      free(pszValue1);
-  }
-  else
-      msInsertHashTable(&(layer->metadata), 
-                        "wms_stylelist", pszStyleName);
+  if(pszHash != NULL) {
+    pszValue1 = (char*)malloc(strlen(pszHash)+
+                              strlen(pszStyleName)+2);
+    sprintf(pszValue1, "%s,%s", pszHash, pszStyleName);
+    msInsertHashTable(&(layer->metadata),
+                      "wms_stylelist", pszValue1);
+    free(pszValue1);
+  } else
+    msInsertHashTable(&(layer->metadata),
+                      "wms_stylelist", pszStyleName);
 
   /* Title */
   pszStyle = (char*)malloc(strlen(pszStyleName)+20);
   sprintf(pszStyle,"wms_style_%s_title",pszStyleName);
 
-  if( msGetMapContextXMLHashValue(psStyle, "Title", &(layer->metadata), 
+  if( msGetMapContextXMLHashValue(psStyle, "Title", &(layer->metadata),
                                   pszStyle) == MS_FAILURE )
-      msInsertHashTable(&(layer->metadata), pszStyle, layer->name);
+    msInsertHashTable(&(layer->metadata), pszStyle, layer->name);
 
   free(pszStyle);
 
   /* SLD */
   pszStyle = (char*)malloc(strlen(pszStyleName)+15);
   sprintf(pszStyle, "wms_style_%s_sld", pszStyleName);
-  
-  msGetMapContextXMLHashValueDecode( psStyle, "SLD.OnlineResource.xlink:href", 
+
+  msGetMapContextXMLHashValueDecode( psStyle, "SLD.OnlineResource.xlink:href",
                                      &(layer->metadata), pszStyle );
   free(pszStyle);
 
@@ -554,21 +504,19 @@ int msLoadMapContextLayerStyle(CPLXMLNode *psStyle, layerObj *layer,
   if (psStyleSLDBody == NULL)
     psStyleSLDBody = CPLGetXMLNode(psStyle, "SLD.sld:StyledLayerDescriptor");
 
-  if(psStyleSLDBody != NULL && &(layer->metadata) != NULL)
-  {
-      pszValue = CPLSerializeXMLTree(psStyleSLDBody);
-      if(pszValue != NULL)
-      {
-          /* Before including SLDBody in the mapfile, we must replace the */
-          /* double quote for single quote. This is to prevent having this: */
-          /* "metadata" "<string attriute="ttt">" */
-          char *c;
-          for(c=pszValue; *c != '\0'; c++)
-              if(*c == '"')
-                  *c = '\'';
-          msInsertHashTable(&(layer->metadata), pszStyle, pszValue );
-          msFree(pszValue);
-      }
+  if(psStyleSLDBody != NULL && &(layer->metadata) != NULL) {
+    pszValue = CPLSerializeXMLTree(psStyleSLDBody);
+    if(pszValue != NULL) {
+      /* Before including SLDBody in the mapfile, we must replace the */
+      /* double quote for single quote. This is to prevent having this: */
+      /* "metadata" "<string attriute="ttt">" */
+      char *c;
+      for(c=pszValue; *c != '\0'; c++)
+        if(*c == '"')
+          *c = '\'';
+      msInsertHashTable(&(layer->metadata), pszStyle, pszValue );
+      msFree(pszValue);
+    }
   }
 
   free(pszStyle);
@@ -578,7 +526,7 @@ int msLoadMapContextLayerStyle(CPLXMLNode *psStyle, layerObj *layer,
 
   sprintf( pszStyle, "wms_style_%s_legendurl",
            pszStyleName);
-  msLoadMapContextURLELements( CPLGetXMLNode(psStyle, "LegendURL"), 
+  msLoadMapContextURLELements( CPLGetXMLNode(psStyle, "LegendURL"),
                                &(layer->metadata), pszStyle );
 
   free(pszStyle);
@@ -588,46 +536,42 @@ int msLoadMapContextLayerStyle(CPLXMLNode *psStyle, layerObj *layer,
   /*  */
   /* Add the stylelist to the layer connection */
   /*  */
-  if(msLookupHashTable(&(layer->metadata), 
-                       "wms_stylelist") == NULL)
-  {
-      if(layer->connection)
-          pszValue = msStrdup(layer->connection);
-      else
-          pszValue = msStrdup( "" ); 
-      pszValue1 = strstr(pszValue, "STYLELIST=");
-      if(pszValue1 != NULL)
-      {                          
-          pszValue1 += 10;
-          pszValue2 = strchr(pszValue, '&');
-          if(pszValue2 != NULL)
-              pszValue1[pszValue2-pszValue1] = '\0';
-          msInsertHashTable(&(layer->metadata), "wms_stylelist",
-                            pszValue1);
-      }
-      free(pszValue);
+  if(msLookupHashTable(&(layer->metadata),
+                       "wms_stylelist") == NULL) {
+    if(layer->connection)
+      pszValue = msStrdup(layer->connection);
+    else
+      pszValue = msStrdup( "" );
+    pszValue1 = strstr(pszValue, "STYLELIST=");
+    if(pszValue1 != NULL) {
+      pszValue1 += 10;
+      pszValue2 = strchr(pszValue, '&');
+      if(pszValue2 != NULL)
+        pszValue1[pszValue2-pszValue1] = '\0';
+      msInsertHashTable(&(layer->metadata), "wms_stylelist",
+                        pszValue1);
+    }
+    free(pszValue);
   }
 
   /*  */
   /* Add the style to the layer connection */
   /*  */
-  if(msLookupHashTable(&(layer->metadata), "wms_style") == NULL)
-  {
-      if(layer->connection)
-          pszValue = msStrdup(layer->connection);
-      else
-          pszValue = msStrdup( "" ); 
-      pszValue1 = strstr(pszValue, "STYLE=");
-      if(pszValue1 != NULL)
-      {                          
-          pszValue1 += 6;
-          pszValue2 = strchr(pszValue, '&');
-          if(pszValue2 != NULL)
-              pszValue1[pszValue2-pszValue1] = '\0';
-          msInsertHashTable(&(layer->metadata), "wms_style",
-                            pszValue1);
-      }
-      free(pszValue);
+  if(msLookupHashTable(&(layer->metadata), "wms_style") == NULL) {
+    if(layer->connection)
+      pszValue = msStrdup(layer->connection);
+    else
+      pszValue = msStrdup( "" );
+    pszValue1 = strstr(pszValue, "STYLE=");
+    if(pszValue1 != NULL) {
+      pszValue1 += 6;
+      pszValue2 = strchr(pszValue, '&');
+      if(pszValue2 != NULL)
+        pszValue1[pszValue2-pszValue1] = '\0';
+      msInsertHashTable(&(layer->metadata), "wms_style",
+                        pszValue1);
+    }
+    free(pszValue);
   }
 
   return MS_SUCCESS;
@@ -635,44 +579,40 @@ int msLoadMapContextLayerStyle(CPLXMLNode *psStyle, layerObj *layer,
 
 int msLoadMapContextLayerDimension(CPLXMLNode *psDimension, layerObj *layer)
 {
-    char *pszValue, *pszHash;
+  char *pszValue, *pszHash;
   char *pszDimension=NULL, *pszDimensionName=NULL;
 
   pszDimensionName =(char*)CPLGetXMLValue(psDimension,"name",NULL);
-  if(pszDimensionName == NULL)
-  {
-      return MS_FALSE;
-  }
-  else
-      pszDimensionName = msStrdup(pszDimensionName);
+  if(pszDimensionName == NULL) {
+    return MS_FALSE;
+  } else
+    pszDimensionName = msStrdup(pszDimensionName);
 
   pszDimension = (char*)malloc(strlen(pszDimensionName)+50);
 
   /* wms_dimension: This is the current dimension */
   pszValue = (char*)CPLGetXMLValue(psDimension, "current", NULL);
-  if(pszValue != NULL && (strcasecmp(pszValue, "1") == 0 || 
+  if(pszValue != NULL && (strcasecmp(pszValue, "1") == 0 ||
                           strcasecmp(pszValue, "true") == 0))
-      msInsertHashTable(&(layer->metadata), 
-                        "wms_dimension", pszDimensionName);
+    msInsertHashTable(&(layer->metadata),
+                      "wms_dimension", pszDimensionName);
   /* wms_dimensionlist */
-  pszHash = msLookupHashTable(&(layer->metadata), 
+  pszHash = msLookupHashTable(&(layer->metadata),
                               "wms_dimensionlist");
-  if(pszHash != NULL)
-  {
-      pszValue = (char*)malloc(strlen(pszHash)+
-                                strlen(pszDimensionName)+2);
-      sprintf(pszValue, "%s,%s", pszHash, pszDimensionName);
-      msInsertHashTable(&(layer->metadata), 
-                        "wms_dimensionlist", pszValue);
-      free(pszValue);
-  }
-  else
-      msInsertHashTable(&(layer->metadata), 
-                        "wms_dimensionlist", pszDimensionName);
+  if(pszHash != NULL) {
+    pszValue = (char*)malloc(strlen(pszHash)+
+                             strlen(pszDimensionName)+2);
+    sprintf(pszValue, "%s,%s", pszHash, pszDimensionName);
+    msInsertHashTable(&(layer->metadata),
+                      "wms_dimensionlist", pszValue);
+    free(pszValue);
+  } else
+    msInsertHashTable(&(layer->metadata),
+                      "wms_dimensionlist", pszDimensionName);
 
   /* Units */
   sprintf(pszDimension, "wms_dimension_%s_units", pszDimensionName);
-  msGetMapContextXMLHashValue(psDimension, "units", &(layer->metadata), 
+  msGetMapContextXMLHashValue(psDimension, "units", &(layer->metadata),
                               pszDimension);
 
   /* UnitSymbol */
@@ -685,8 +625,8 @@ int msLoadMapContextLayerDimension(CPLXMLNode *psDimension, layerObj *layer)
   msGetMapContextXMLHashValue(psDimension, "userValue", &(layer->metadata),
                               pszDimension);
   if(strcasecmp(pszDimensionName, "time") == 0)
-      msGetMapContextXMLHashValue(psDimension, "userValue", &(layer->metadata),
-                                  "wms_time");
+    msGetMapContextXMLHashValue(psDimension, "userValue", &(layer->metadata),
+                                "wms_time");
 
   /* default */
   sprintf(pszDimension, "wms_dimension_%s_default", pszDimensionName);
@@ -717,8 +657,8 @@ int msLoadMapContextLayerDimension(CPLXMLNode *psDimension, layerObj *layer)
 **
 ** Load the General block of the mapcontext document
 */
-int msLoadMapContextGeneral(mapObj *map, CPLXMLNode *psGeneral, 
-                            CPLXMLNode *psMapContext, int nVersion, 
+int msLoadMapContextGeneral(mapObj *map, CPLXMLNode *psGeneral,
+                            CPLXMLNode *psMapContext, int nVersion,
                             char *filename)
 {
 
@@ -726,153 +666,131 @@ int msLoadMapContextGeneral(mapObj *map, CPLXMLNode *psGeneral,
   char *pszValue, *pszValue1, *pszValue2;
 
   /* Projection */
-  pszValue = (char*)CPLGetXMLValue(psGeneral, 
+  pszValue = (char*)CPLGetXMLValue(psGeneral,
                                    "BoundingBox.SRS", NULL);
-  if(pszValue != NULL)
-  {
-      if(strncasecmp(pszValue, "AUTO:", 5) == 0)
-      {
-          pszProj = msStrdup(pszValue);
-      }
-      else
-      {
-          pszProj = (char*) malloc(sizeof(char)*(strlen(pszValue)+10));
-          sprintf(pszProj, "init=epsg:%s", pszValue+5);
-      }
+  if(pszValue != NULL) {
+    if(strncasecmp(pszValue, "AUTO:", 5) == 0) {
+      pszProj = msStrdup(pszValue);
+    } else {
+      pszProj = (char*) malloc(sizeof(char)*(strlen(pszValue)+10));
+      sprintf(pszProj, "init=epsg:%s", pszValue+5);
+    }
 
-      msInitProjection(&map->projection);
-      map->projection.args[map->projection.numargs] = msStrdup(pszProj);
-      map->projection.numargs++;
-      msProcessProjection(&map->projection);
-
-      if( (map->units = GetMapserverUnitUsingProj(&(map->projection))) == -1)
-      {
-          free(pszProj);
-          msSetError( MS_MAPCONTEXTERR, 
-                      "Unable to set units for projection '%s'",
-                      "msLoadMapContext()", pszProj );
-          return MS_FAILURE;
-      }
+    msInitProjection(&map->projection);
+    map->projection.args[map->projection.numargs] = msStrdup(pszProj);
+    map->projection.numargs++;
+    msProcessProjection(&map->projection);
+
+    if( (map->units = GetMapserverUnitUsingProj(&(map->projection))) == -1) {
       free(pszProj);
-  }
-  else
-  {
-      msDebug("Mandatory data General.BoundingBox.SRS missing in %s.",
-              filename);
+      msSetError( MS_MAPCONTEXTERR,
+                  "Unable to set units for projection '%s'",
+                  "msLoadMapContext()", pszProj );
+      return MS_FAILURE;
+    }
+    free(pszProj);
+  } else {
+    msDebug("Mandatory data General.BoundingBox.SRS missing in %s.",
+            filename);
   }
 
   /* Extent */
   if( msGetMapContextXMLFloatValue(psGeneral, "BoundingBox.minx",
-                                   &(map->extent.minx)) == MS_FAILURE)
-  {
-      msDebug("Mandatory data General.BoundingBox.minx missing in %s.",
-              filename);
+                                   &(map->extent.minx)) == MS_FAILURE) {
+    msDebug("Mandatory data General.BoundingBox.minx missing in %s.",
+            filename);
   }
   if( msGetMapContextXMLFloatValue(psGeneral, "BoundingBox.miny",
-                               &(map->extent.miny)) == MS_FAILURE)
-  {
-      msDebug("Mandatory data General.BoundingBox.miny missing in %s.",
-              filename);
+                                   &(map->extent.miny)) == MS_FAILURE) {
+    msDebug("Mandatory data General.BoundingBox.miny missing in %s.",
+            filename);
   }
   if( msGetMapContextXMLFloatValue(psGeneral, "BoundingBox.maxx",
-                               &(map->extent.maxx)) == MS_FAILURE)
-  {
-      msDebug("Mandatory data General.BoundingBox.maxx missing in %s.",
-              filename);
+                                   &(map->extent.maxx)) == MS_FAILURE) {
+    msDebug("Mandatory data General.BoundingBox.maxx missing in %s.",
+            filename);
   }
   if( msGetMapContextXMLFloatValue(psGeneral, "BoundingBox.maxy",
-                               &(map->extent.maxy)) == MS_FAILURE)
-  {
-      msDebug("Mandatory data General.BoundingBox.maxy missing in %s.",
-              filename);
+                                   &(map->extent.maxy)) == MS_FAILURE) {
+    msDebug("Mandatory data General.BoundingBox.maxy missing in %s.",
+            filename);
   }
 
   /* Title */
-  if( msGetMapContextXMLHashValue(psGeneral, "Title", 
-                              &(map->web.metadata), "wms_title") == MS_FAILURE)
-  {
-      if ( nVersion >= OWS_1_0_0 )
-         msDebug("Mandatory data General.Title missing in %s.", filename);
-      else
-      {
-          if( msGetMapContextXMLHashValue(psGeneral, "gml:name", 
-                             &(map->web.metadata), "wms_title") == MS_FAILURE )
-          {
-              if( nVersion < OWS_0_1_7 )
-                msDebug("Mandatory data General.Title missing in %s.", filename);
-              else
-                msDebug("Mandatory data General.gml:name missing in %s.", 
-                        filename);
-          }
+  if( msGetMapContextXMLHashValue(psGeneral, "Title",
+                                  &(map->web.metadata), "wms_title") == MS_FAILURE) {
+    if ( nVersion >= OWS_1_0_0 )
+      msDebug("Mandatory data General.Title missing in %s.", filename);
+    else {
+      if( msGetMapContextXMLHashValue(psGeneral, "gml:name",
+                                      &(map->web.metadata), "wms_title") == MS_FAILURE ) {
+        if( nVersion < OWS_0_1_7 )
+          msDebug("Mandatory data General.Title missing in %s.", filename);
+        else
+          msDebug("Mandatory data General.gml:name missing in %s.",
+                  filename);
       }
+    }
   }
 
   /* Name */
-  if( nVersion >= OWS_1_0_0 )
-  {
-      pszValue = (char*)CPLGetXMLValue(psMapContext, 
-                                       "id", NULL);
-      if (pszValue)
-        map->name = msStrdup(pszValue);
-  }
-  else
-  {
-      if(msGetMapContextXMLStringValue(psGeneral, "Name", 
-                                       &(map->name)) == MS_FAILURE)
-      {
-          msGetMapContextXMLStringValue(psGeneral, "gml:name", 
-                                        &(map->name));
-      }
+  if( nVersion >= OWS_1_0_0 ) {
+    pszValue = (char*)CPLGetXMLValue(psMapContext,
+                                     "id", NULL);
+    if (pszValue)
+      map->name = msStrdup(pszValue);
+  } else {
+    if(msGetMapContextXMLStringValue(psGeneral, "Name",
+                                     &(map->name)) == MS_FAILURE) {
+      msGetMapContextXMLStringValue(psGeneral, "gml:name",
+                                    &(map->name));
+    }
   }
   /* Keyword */
-  if( nVersion >= OWS_1_0_0 )
-  {
-      msLoadMapContextListInMetadata( 
-          CPLGetXMLNode(psGeneral, "KeywordList"),
-          &(map->web.metadata), "KEYWORD", "wms_keywordlist", "," );
-  }
-  else
-    msGetMapContextXMLHashValue(psGeneral, "Keywords", 
+  if( nVersion >= OWS_1_0_0 ) {
+    msLoadMapContextListInMetadata(
+      CPLGetXMLNode(psGeneral, "KeywordList"),
+      &(map->web.metadata), "KEYWORD", "wms_keywordlist", "," );
+  } else
+    msGetMapContextXMLHashValue(psGeneral, "Keywords",
                                 &(map->web.metadata), "wms_keywordlist");
 
   /* Window */
   pszValue1 = (char*)CPLGetXMLValue(psGeneral,"Window.width",NULL);
   pszValue2 = (char*)CPLGetXMLValue(psGeneral,"Window.height",NULL);
-  if(pszValue1 != NULL && pszValue2 != NULL)
-  {
-      map->width = atoi(pszValue1);
-      map->height = atoi(pszValue2);
+  if(pszValue1 != NULL && pszValue2 != NULL) {
+    map->width = atoi(pszValue1);
+    map->height = atoi(pszValue2);
   }
 
   /* Abstract */
-  if( msGetMapContextXMLHashValue( psGeneral, 
-                                   "Abstract", &(map->web.metadata), 
-                                   "wms_abstract") == MS_FAILURE )
-  {
-      msGetMapContextXMLHashValue( psGeneral, "gml:description", 
-                                   &(map->web.metadata), "wms_abstract");
+  if( msGetMapContextXMLHashValue( psGeneral,
+                                   "Abstract", &(map->web.metadata),
+                                   "wms_abstract") == MS_FAILURE ) {
+    msGetMapContextXMLHashValue( psGeneral, "gml:description",
+                                 &(map->web.metadata), "wms_abstract");
   }
 
   /* DataURL */
-  msGetMapContextXMLHashValueDecode(psGeneral, 
-                                   "DataURL.OnlineResource.xlink:href",
-                                   &(map->web.metadata), "wms_dataurl");
+  msGetMapContextXMLHashValueDecode(psGeneral,
+                                    "DataURL.OnlineResource.xlink:href",
+                                    &(map->web.metadata), "wms_dataurl");
 
   /* LogoURL */
   /* The logourl have a width, height, format and an URL */
-  msLoadMapContextURLELements( CPLGetXMLNode(psGeneral, "LogoURL"), 
+  msLoadMapContextURLELements( CPLGetXMLNode(psGeneral, "LogoURL"),
                                &(map->web.metadata), "wms_logourl" );
 
   /* DescriptionURL */
   /* The descriptionurl have a width, height, format and an URL */
-  msLoadMapContextURLELements( CPLGetXMLNode(psGeneral, 
-                                             "DescriptionURL"), 
+  msLoadMapContextURLELements( CPLGetXMLNode(psGeneral,
+                               "DescriptionURL"),
                                &(map->web.metadata), "wms_descriptionurl" );
 
   /* Contact Info */
-  msLoadMapContextContactInfo( 
-      CPLGetXMLNode(psGeneral, "ContactInformation"), 
-      &(map->web.metadata) );
+  msLoadMapContextContactInfo(
+    CPLGetXMLNode(psGeneral, "ContactInformation"),
+    &(map->web.metadata) );
 
   return MS_SUCCESS;
 }
@@ -896,7 +814,7 @@ int msLoadMapContextLayer(mapObj *map, CPLXMLNode *psLayer, int nVersion,
   /* Init new layer */
   if(msGrowMapLayers(map) == NULL)
     return MS_FAILURE;
-  
+
   layer = (GET_LAYER(map, map->numlayers));
   initLayer(layer, map);
   layer->map = (mapObj *)map;
@@ -905,269 +823,220 @@ int msLoadMapContextLayer(mapObj *map, CPLXMLNode *psLayer, int nVersion,
   GET_LAYER(map, map->numlayers)->index = map->numlayers;
   map->layerorder[map->numlayers] = map->numlayers;
   map->numlayers++;
-  
-  
+
+
   /* Status */
   pszValue = (char*)CPLGetXMLValue(psLayer, "hidden", "1");
-  if((pszValue != NULL) && (atoi(pszValue) == 0 && 
+  if((pszValue != NULL) && (atoi(pszValue) == 0 &&
                             !strcasecmp(pszValue, "true") == 0))
-      layer->status = MS_ON;
+    layer->status = MS_ON;
   else
-      layer->status = MS_OFF;
+    layer->status = MS_OFF;
 
   /* Queryable */
   pszValue = (char*)CPLGetXMLValue(psLayer, "queryable", "0");
-  if(pszValue !=NULL && (atoi(pszValue) == 1  || 
+  if(pszValue !=NULL && (atoi(pszValue) == 1  ||
                          strcasecmp(pszValue, "true") == 0))
-      layer->template = msStrdup("ttt");
+    layer->template = msStrdup("ttt");
 
   /* Name and Title */
   pszValue = (char*)CPLGetXMLValue(psLayer, "Name", NULL);
-  if(pszValue != NULL)
-  {
-      msInsertHashTable( &(layer->metadata), "wms_name", pszValue );
-
-      if (unique_layer_names)
-      {
-          pszName = (char*)malloc(sizeof(char)*(strlen(pszValue)+10));
-          sprintf(pszName, "l%d:%s", layer->index, pszValue);
-          layer->name = msStrdup(pszName);
-          free(pszName);
-      }
-      else
-        layer->name  = msStrdup(pszValue);
-  }
-  else
-  {
-      pszName = (char*)malloc(sizeof(char)*10);
-      sprintf(pszName, "l%d:", layer->index);
+  if(pszValue != NULL) {
+    msInsertHashTable( &(layer->metadata), "wms_name", pszValue );
+
+    if (unique_layer_names) {
+      pszName = (char*)malloc(sizeof(char)*(strlen(pszValue)+15));
+      sprintf(pszName, "l%d:%s", layer->index, pszValue);
       layer->name = msStrdup(pszName);
       free(pszName);
-  }
-
-  if(msGetMapContextXMLHashValue(psLayer, "Title", &(layer->metadata), 
-                                 "wms_title") == MS_FAILURE)
-  {
-      if(msGetMapContextXMLHashValue(psLayer, "Server.title", 
-                          &(layer->metadata), "wms_title") == MS_FAILURE)
-      {
-          msDebug("Mandatory data Layer.Title missing in %s.", filename);
-      }
+    } else
+      layer->name  = msStrdup(pszValue);
+  } else {
+    pszName = (char*)malloc(sizeof(char)*15);
+    sprintf(pszName, "l%d:", layer->index);
+    layer->name = msStrdup(pszName);
+    free(pszName);
+  }
+
+  if(msGetMapContextXMLHashValue(psLayer, "Title", &(layer->metadata),
+                                 "wms_title") == MS_FAILURE) {
+    if(msGetMapContextXMLHashValue(psLayer, "Server.title",
+                                   &(layer->metadata), "wms_title") == MS_FAILURE) {
+      msDebug("Mandatory data Layer.Title missing in %s.", filename);
+    }
   }
 
   /* Server Title */
   msGetMapContextXMLHashValue(psLayer, "Server.title", &(layer->metadata),  "wms_server_title");
 
   /* Abstract */
-  msGetMapContextXMLHashValue(psLayer, "Abstract", &(layer->metadata), 
+  msGetMapContextXMLHashValue(psLayer, "Abstract", &(layer->metadata),
                               "wms_abstract");
 
   /* DataURL */
-  if(nVersion <= OWS_0_1_4)
-  {
-      msGetMapContextXMLHashValueDecode(psLayer, 
-                                        "DataURL.OnlineResource.xlink:href",
-                                        &(layer->metadata), "wms_dataurl");
-  }
-  else
-  {
-      /* The DataURL have a width, height, format and an URL */
-      /* Width and height are not used, but they are included to */
-      /* be consistent with the spec. */
-      msLoadMapContextURLELements( CPLGetXMLNode(psLayer, "DataURL"), 
-                                           &(layer->metadata), "wms_dataurl" );
+  if(nVersion <= OWS_0_1_4) {
+    msGetMapContextXMLHashValueDecode(psLayer,
+                                      "DataURL.OnlineResource.xlink:href",
+                                      &(layer->metadata), "wms_dataurl");
+  } else {
+    /* The DataURL have a width, height, format and an URL */
+    /* Width and height are not used, but they are included to */
+    /* be consistent with the spec. */
+    msLoadMapContextURLELements( CPLGetXMLNode(psLayer, "DataURL"),
+                                 &(layer->metadata), "wms_dataurl" );
   }
 
   /* The MetadataURL have a width, height, format and an URL */
   /* Width and height are not used, but they are included to */
   /* be consistent with the spec. */
-  msLoadMapContextURLELements( CPLGetXMLNode(psLayer, "MetadataURL"), 
-                                       &(layer->metadata), "wms_metadataurl" );
+  msLoadMapContextURLELements( CPLGetXMLNode(psLayer, "MetadataURL"),
+                               &(layer->metadata), "wms_metadataurl" );
 
 
   /* MinScale && MaxScale */
   pszValue = (char*)CPLGetXMLValue(psLayer, "sld:MinScaleDenominator", NULL);
-  if(pszValue != NULL)
-  {
-      layer->minscaledenom = atof(pszValue);
+  if(pszValue != NULL) {
+    layer->minscaledenom = atof(pszValue);
   }
 
   pszValue = (char*)CPLGetXMLValue(psLayer, "sld:MaxScaleDenominator", NULL);
-  if(pszValue != NULL)
-  {
-      layer->maxscaledenom = atof(pszValue);
+  if(pszValue != NULL) {
+    layer->maxscaledenom = atof(pszValue);
   }
 
   /*  */
   /* Server */
   /*  */
-  if(nVersion >= OWS_0_1_4)
-  {
-      if(msGetMapContextXMLStringValueDecode(psLayer, 
-                                          "Server.OnlineResource.xlink:href",
-                                          &(layer->connection)) == MS_FAILURE)
-      {
-          msSetError(MS_MAPCONTEXTERR, 
-              "Mandatory data Server.OnlineResource.xlink:href missing in %s.",
-                     "msLoadMapContext()", filename);
-          return MS_FAILURE;
-      }
-      else
-      {
-          msGetMapContextXMLHashValueDecode(psLayer, 
-                                          "Server.OnlineResource.xlink:href", 
-                                     &(layer->metadata), "wms_onlineresource");
-          layer->connectiontype = MS_WMS;
-      }
-  }
-  else
-  {
-      if(msGetMapContextXMLStringValueDecode(psLayer, 
-                                             "Server.onlineResource", 
-                                           &(layer->connection)) == MS_FAILURE)
-      {
-          msSetError(MS_MAPCONTEXTERR, 
-                     "Mandatory data Server.onlineResource missing in %s.",
-                     "msLoadMapContext()", filename);
-          return MS_FAILURE;
-      }
-      else
-      {
-          msGetMapContextXMLHashValueDecode(psLayer, "Server.onlineResource", 
-                                     &(layer->metadata), "wms_onlineresource");
-          layer->connectiontype = MS_WMS;
-      }
+  if(nVersion >= OWS_0_1_4) {
+    if(msGetMapContextXMLStringValueDecode(psLayer,
+                                           "Server.OnlineResource.xlink:href",
+                                           &(layer->connection)) == MS_FAILURE) {
+      msSetError(MS_MAPCONTEXTERR,
+                 "Mandatory data Server.OnlineResource.xlink:href missing in %s.",
+                 "msLoadMapContext()", filename);
+      return MS_FAILURE;
+    } else {
+      msGetMapContextXMLHashValueDecode(psLayer,
+                                        "Server.OnlineResource.xlink:href",
+                                        &(layer->metadata), "wms_onlineresource");
+      layer->connectiontype = MS_WMS;
+    }
+  } else {
+    if(msGetMapContextXMLStringValueDecode(psLayer,
+                                           "Server.onlineResource",
+                                           &(layer->connection)) == MS_FAILURE) {
+      msSetError(MS_MAPCONTEXTERR,
+                 "Mandatory data Server.onlineResource missing in %s.",
+                 "msLoadMapContext()", filename);
+      return MS_FAILURE;
+    } else {
+      msGetMapContextXMLHashValueDecode(psLayer, "Server.onlineResource",
+                                        &(layer->metadata), "wms_onlineresource");
+      layer->connectiontype = MS_WMS;
+    }
   }
 
-  if(nVersion >= OWS_0_1_4)
-  {
-      if(msGetMapContextXMLHashValue(psLayer, "Server.version", 
-                      &(layer->metadata), "wms_server_version") == MS_FAILURE)
-      {
-          msSetError(MS_MAPCONTEXTERR, 
-                     "Mandatory data Server.version missing in %s.",
-                     "msLoadMapContext()", filename);
-          return MS_FAILURE;
-      }
-  }
-  else
-  {
-      if(msGetMapContextXMLHashValue(psLayer, "Server.wmtver", 
-                      &(layer->metadata), "wms_server_version") == MS_FAILURE)
-      {
-          msSetError(MS_MAPCONTEXTERR, 
-                     "Mandatory data Server.wmtver missing in %s.",
-                     "msLoadMapContext()", filename);
-          return MS_FAILURE;
-      }
+  if(nVersion >= OWS_0_1_4) {
+    if(msGetMapContextXMLHashValue(psLayer, "Server.version",
+                                   &(layer->metadata), "wms_server_version") == MS_FAILURE) {
+      msSetError(MS_MAPCONTEXTERR,
+                 "Mandatory data Server.version missing in %s.",
+                 "msLoadMapContext()", filename);
+      return MS_FAILURE;
+    }
+  } else {
+    if(msGetMapContextXMLHashValue(psLayer, "Server.wmtver",
+                                   &(layer->metadata), "wms_server_version") == MS_FAILURE) {
+      msSetError(MS_MAPCONTEXTERR,
+                 "Mandatory data Server.wmtver missing in %s.",
+                 "msLoadMapContext()", filename);
+      return MS_FAILURE;
+    }
   }
 
   /* Projection */
-  msLoadMapContextListInMetadata( psLayer, &(layer->metadata), 
+  msLoadMapContextListInMetadata( psLayer, &(layer->metadata),
                                   "SRS", "wms_srs", " " );
 
   pszHash = msLookupHashTable(&(layer->metadata), "wms_srs");
-  if(((pszHash == NULL) || (strcasecmp(pszHash, "") == 0)) && 
-     map->projection.numargs != 0)
-  {
-      pszProj = map->projection.args[map->projection.numargs-1];
-
-      if(pszProj != NULL)
-      {
-          if(strncasecmp(pszProj, "AUTO:", 5) == 0)
-          {
-              msInsertHashTable(&(layer->metadata),"wms_srs", pszProj);
-          }
-          else
-          {
-              if(strlen(pszProj) > 10)
-              {
-                  pszProj = (char*) malloc(sizeof(char) * (strlen(pszProj)));
-                  sprintf( pszProj, "EPSG:%s", 
-                           map->projection.args[map->projection.numargs-1]+10);
-                  msInsertHashTable(&(layer->metadata),"wms_srs", pszProj);
-              }
-              else
-              {
-                  msDebug("Unable to set data for layer wms_srs from this"
-                          " value %s.", 
-                          pszProj);
-              }
-          }
+  if(((pszHash == NULL) || (strcasecmp(pszHash, "") == 0)) &&
+      map->projection.numargs != 0) {
+    pszProj = map->projection.args[map->projection.numargs-1];
+
+    if(pszProj != NULL) {
+      if(strncasecmp(pszProj, "AUTO:", 5) == 0) {
+        msInsertHashTable(&(layer->metadata),"wms_srs", pszProj);
+      } else {
+        if(strlen(pszProj) > 10) {
+          pszProj = (char*) malloc(sizeof(char) * (strlen(pszProj)));
+          sprintf( pszProj, "EPSG:%s",
+                   map->projection.args[map->projection.numargs-1]+10);
+          msInsertHashTable(&(layer->metadata),"wms_srs", pszProj);
+        } else {
+          msDebug("Unable to set data for layer wms_srs from this"
+                  " value %s.",
+                  pszProj);
+        }
       }
+    }
   }
 
   /*  */
   /* Format */
   /*  */
-  if( nVersion >= OWS_0_1_4 )
-  {
-      psFormatList = CPLGetXMLNode(psLayer, "FormatList");
-  }
-  else
-  {
-      psFormatList = psLayer;
+  if( nVersion >= OWS_0_1_4 ) {
+    psFormatList = CPLGetXMLNode(psLayer, "FormatList");
+  } else {
+    psFormatList = psLayer;
   }
 
-  if(psFormatList != NULL)
-  {
-      for(psFormat = psFormatList->psChild; 
-          psFormat != NULL; 
-          psFormat = psFormat->psNext)
-      {
-          msLoadMapContextLayerFormat(psFormat, layer);
-      }
-                   
+  if(psFormatList != NULL) {
+    for(psFormat = psFormatList->psChild;
+        psFormat != NULL;
+        psFormat = psFormat->psNext) {
+      msLoadMapContextLayerFormat(psFormat, layer);
+    }
+
   } /* end FormatList parsing */
 
   /* Style */
-  if( nVersion >= OWS_0_1_4 )
-  {
-      psStyleList = CPLGetXMLNode(psLayer, "StyleList");
-  }
-  else
-  {
-      psStyleList = psLayer;
-  }
-
-  if(psStyleList != NULL)
-  {
-      nStyle = 0;
-      for(psStyle = psStyleList->psChild; 
-          psStyle != NULL; 
-          psStyle = psStyle->psNext)
-      {
-          if(strcasecmp(psStyle->pszValue, "Style") == 0)
-          {
-              nStyle++;
-              msLoadMapContextLayerStyle(psStyle, layer, nStyle);
-          }
+  if( nVersion >= OWS_0_1_4 ) {
+    psStyleList = CPLGetXMLNode(psLayer, "StyleList");
+  } else {
+    psStyleList = psLayer;
+  }
+
+  if(psStyleList != NULL) {
+    nStyle = 0;
+    for(psStyle = psStyleList->psChild;
+        psStyle != NULL;
+        psStyle = psStyle->psNext) {
+      if(strcasecmp(psStyle->pszValue, "Style") == 0) {
+        nStyle++;
+        msLoadMapContextLayerStyle(psStyle, layer, nStyle);
       }
+    }
   }
 
   /* Dimension */
   psDimensionList = CPLGetXMLNode(psLayer, "DimensionList");
-  if(psDimensionList != NULL)
-  {
-      for(psDimension = psDimensionList->psChild; 
-          psDimension != NULL; 
-          psDimension = psDimension->psNext)
-      {
-          if(strcasecmp(psDimension->pszValue, "Dimension") == 0)
-          {
-              msLoadMapContextLayerDimension(psDimension, layer);
-          }
+  if(psDimensionList != NULL) {
+    for(psDimension = psDimensionList->psChild;
+        psDimension != NULL;
+        psDimension = psDimension->psNext) {
+      if(strcasecmp(psDimension->pszValue, "Dimension") == 0) {
+        msLoadMapContextLayerDimension(psDimension, layer);
       }
+    }
   }
- 
+
   /* Extension */
   psExtension = CPLGetXMLNode(psLayer, "Extension");
   if (psExtension != NULL) {
-      pszValue = (char*)CPLGetXMLValue(psExtension, "ol:opacity", NULL);
-      if(pszValue != NULL)
-      {
-          layer->opacity = atof(pszValue)*100;
-      } 
+    pszValue = (char*)CPLGetXMLValue(psExtension, "ol:opacity", NULL);
+    if(pszValue != NULL) {
+      layer->opacity = atof(pszValue)*100;
+    }
   }
 
   return MS_SUCCESS;
@@ -1187,35 +1056,31 @@ int msLoadMapContextLayer(mapObj *map, CPLXMLNode *psLayer, int nVersion,
 int msLoadMapContextURL(mapObj *map, char *urlfilename, int unique_layer_names)
 {
 #if defined(USE_WMS_LYR) && defined(USE_OGR)
-    char *pszTmpFile = NULL;
-    int status = 0;
-
-    if (!map || !urlfilename)
-    {
-        msSetError(MS_MAPCONTEXTERR, 
-                   "Invalid map or url given.",
-                   "msGetMapContextURL()");
-        return MS_FAILURE;
-    }
-    
-    pszTmpFile = msTmpFile(map, map->mappath, NULL, "context.xml");
-    if (msHTTPGetFile(urlfilename, pszTmpFile, &status,-1, 0, 0) ==  MS_SUCCESS)
-    {
-        return msLoadMapContext(map, pszTmpFile, unique_layer_names);
-    }
-    else
-    {
-        msSetError(MS_MAPCONTEXTERR, 
-                   "Could not open context file %s.",
-                   "msGetMapContextURL()", urlfilename);
-        return MS_FAILURE;
-    }
-    
-#else
-    msSetError(MS_MAPCONTEXTERR, 
-               "Not implemented since Map Context is not enabled.",
+  char *pszTmpFile = NULL;
+  int status = 0;
+
+  if (!map || !urlfilename) {
+    msSetError(MS_MAPCONTEXTERR,
+               "Invalid map or url given.",
                "msGetMapContextURL()");
     return MS_FAILURE;
+  }
+
+  pszTmpFile = msTmpFile(map, map->mappath, NULL, "context.xml");
+  if (msHTTPGetFile(urlfilename, pszTmpFile, &status,-1, 0, 0) ==  MS_SUCCESS) {
+    return msLoadMapContext(map, pszTmpFile, unique_layer_names);
+  } else {
+    msSetError(MS_MAPCONTEXTERR,
+               "Could not open context file %s.",
+               "msGetMapContextURL()", urlfilename);
+    return MS_FAILURE;
+  }
+
+#else
+  msSetError(MS_MAPCONTEXTERR,
+             "Not implemented since Map Context is not enabled.",
+             "msGetMapContextURL()");
+  return MS_FAILURE;
 #endif
 }
 /* msLoadMapContext()
@@ -1225,7 +1090,7 @@ int msLoadMapContextURL(mapObj *map, char *urlfilename, int unique_layer_names)
 ** Take as first map object and a file in arguments
 ** If The 2nd aregument unique_layer_names is set to MS_TRUE, the layer
 ** name created would be unique and be prefixed with an l plus the layers's index
-** (eg l:1:park. l:2:road ...). If It is set to MS_FALSE, the layer name 
+** (eg l:1:park. l:2:road ...). If It is set to MS_FALSE, the layer name
 ** would be the same name as the layer name in the context
 */
 int msLoadMapContext(mapObj *map, char *filename, int unique_layer_names)
@@ -1240,25 +1105,24 @@ int msLoadMapContext(mapObj *map, char *filename, int unique_layer_names)
   /*  */
   /* Load the raw XML file */
   /*  */
-  
+
   pszWholeText = msGetMapContextFileText(
-      msBuildPath(szPath, map->mappath, filename));
-  if(pszWholeText == NULL)
-  {
-      msSetError( MS_MAPCONTEXTERR, "Unable to read %s", 
-                  "msLoadMapContext()", filename );
-      return MS_FAILURE;
+                   msBuildPath(szPath, map->mappath, filename));
+  if(pszWholeText == NULL) {
+    msSetError( MS_MAPCONTEXTERR, "Unable to read %s",
+                "msLoadMapContext()", filename );
+    return MS_FAILURE;
   }
 
   if( ( strstr( pszWholeText, "<WMS_Viewer_Context" ) == NULL ) &&
       ( strstr( pszWholeText, "<View_Context" ) == NULL ) &&
       ( strstr( pszWholeText, "<ViewContext" ) == NULL ) )
-    
+
   {
-      free( pszWholeText );
-      msSetError( MS_MAPCONTEXTERR, "Not a Map Context file (%s)", 
-                  "msLoadMapContext()", filename );
-      return MS_FAILURE;
+    free( pszWholeText );
+    msSetError( MS_MAPCONTEXTERR, "Not a Map Context file (%s)",
+                "msLoadMapContext()", filename );
+    return MS_FAILURE;
   }
 
   /*  */
@@ -1268,14 +1132,13 @@ int msLoadMapContext(mapObj *map, char *filename, int unique_layer_names)
   free( pszWholeText );
 
   /* We assume parser will report errors via CPL. */
-  if( psRoot == NULL )
-  {
-      msSetError( MS_MAPCONTEXTERR, "Invalid XML file (%s)", 
-                  "msLoadMapContext()", filename );
-      if(psRoot != NULL)
-          CPLDestroyXMLNode(psRoot);
+  if( psRoot == NULL ) {
+    msSetError( MS_MAPCONTEXTERR, "Invalid XML file (%s)",
+                "msLoadMapContext()", filename );
+    if(psRoot != NULL)
+      CPLDestroyXMLNode(psRoot);
 
-      return MS_FAILURE;
+    return MS_FAILURE;
   }
 
   /*  */
@@ -1283,45 +1146,38 @@ int msLoadMapContext(mapObj *map, char *filename, int unique_layer_names)
   /*  */
   psChild = psRoot;
   psMapContext = NULL;
-  while( psChild != NULL )
-  {
-      if( psChild->eType == CXT_Element && 
-          (EQUAL(psChild->pszValue,"WMS_Viewer_Context") ||
-           EQUAL(psChild->pszValue,"View_Context") ||
-           EQUAL(psChild->pszValue,"ViewContext")) )
-      {
-          psMapContext = psChild;
-          break;
-      }
-      else
-      {
-          psChild = psChild->psNext;
-      }
+  while( psChild != NULL ) {
+    if( psChild->eType == CXT_Element &&
+        (EQUAL(psChild->pszValue,"WMS_Viewer_Context") ||
+         EQUAL(psChild->pszValue,"View_Context") ||
+         EQUAL(psChild->pszValue,"ViewContext")) ) {
+      psMapContext = psChild;
+      break;
+    } else {
+      psChild = psChild->psNext;
+    }
   }
 
-  if( psMapContext == NULL )
-  {
-      CPLDestroyXMLNode(psRoot);
-      msSetError( MS_MAPCONTEXTERR, "Invalid Map Context File (%s)", 
-                  "msLoadMapContext()", filename );
-      return MS_FAILURE;
+  if( psMapContext == NULL ) {
+    CPLDestroyXMLNode(psRoot);
+    msSetError( MS_MAPCONTEXTERR, "Invalid Map Context File (%s)",
+                "msLoadMapContext()", filename );
+    return MS_FAILURE;
   }
 
   /* Fetch document version number */
-  pszValue = (char*)CPLGetXMLValue(psMapContext, 
+  pszValue = (char*)CPLGetXMLValue(psMapContext,
                                    "version", NULL);
-  if( !pszValue )
-  {
-      msDebug( "msLoadMapContext(): Mandatory data version missing in %s, assuming 0.1.4.",
-               filename );
-      pszValue = "0.1.4";
+  if( !pszValue ) {
+    msDebug( "msLoadMapContext(): Mandatory data version missing in %s, assuming 0.1.4.",
+             filename );
+    pszValue = "0.1.4";
   }
 
   nVersion = msOWSParseVersionString(pszValue);
 
   /* Make sure this is a supported version */
-  switch (nVersion)
-  {
+  switch (nVersion) {
     case OWS_0_1_2:
     case OWS_0_1_4:
     case OWS_0_1_7:
@@ -1331,7 +1187,7 @@ int msLoadMapContext(mapObj *map, char *filename, int unique_layer_names)
       break;
     default:
       /* Not a supported version */
-      msSetError(MS_MAPCONTEXTERR, 
+      msSetError(MS_MAPCONTEXTERR,
                  "This version of Map Context is not supported (%s).",
                  "msLoadMapContext()", pszValue);
       CPLDestroyXMLNode(psRoot);
@@ -1342,56 +1198,48 @@ int msLoadMapContext(mapObj *map, char *filename, int unique_layer_names)
   msInsertHashTable( &(map->web.metadata), "wms_context_version",
                      msOWSGetVersionString(nVersion, szVersionBuf));
 
-  if( nVersion >= OWS_0_1_7 && nVersion < OWS_1_0_0)
-  {
-      if( msGetMapContextXMLHashValue(psMapContext, "fid", 
-                           &(map->web.metadata), "wms_context_fid") == MS_FAILURE )
-      {
-          msDebug("Mandatory data fid missing in %s.", filename);
-      }
+  if( nVersion >= OWS_0_1_7 && nVersion < OWS_1_0_0) {
+    if( msGetMapContextXMLHashValue(psMapContext, "fid",
+                                    &(map->web.metadata), "wms_context_fid") == MS_FAILURE ) {
+      msDebug("Mandatory data fid missing in %s.", filename);
+    }
   }
 
   /*  */
   /* Load the General bloc */
   /*  */
   psChild = CPLGetXMLNode( psMapContext, "General" );
-  if( psChild == NULL )
-  {
-      CPLDestroyXMLNode(psRoot);
-      msSetError(MS_MAPCONTEXTERR, 
-                 "The Map Context document provided (%s) does not contain any "
-                 "General elements.",
-                 "msLoadMapContext()", filename);
-      return MS_FAILURE;
+  if( psChild == NULL ) {
+    CPLDestroyXMLNode(psRoot);
+    msSetError(MS_MAPCONTEXTERR,
+               "The Map Context document provided (%s) does not contain any "
+               "General elements.",
+               "msLoadMapContext()", filename);
+    return MS_FAILURE;
   }
 
-  if( msLoadMapContextGeneral(map, psChild, psMapContext, 
-                              nVersion, filename) == MS_FAILURE )
-  {
-      CPLDestroyXMLNode(psRoot);
-      return MS_FAILURE;
+  if( msLoadMapContextGeneral(map, psChild, psMapContext,
+                              nVersion, filename) == MS_FAILURE ) {
+    CPLDestroyXMLNode(psRoot);
+    return MS_FAILURE;
   }
 
   /*  */
   /* Load the bloc LayerList */
   /*  */
   psLayerList = CPLGetXMLNode(psMapContext, "LayerList");
-  if( psLayerList != NULL )
-  {
-      for(psLayer = psLayerList->psChild; 
-          psLayer != NULL; 
-          psLayer = psLayer->psNext)
-      {
-          if(EQUAL(psLayer->pszValue, "Layer"))
-          {
-              if( msLoadMapContextLayer(map, psLayer, nVersion, 
-                                        filename, unique_layer_names) == MS_FAILURE )
-              {
-                  CPLDestroyXMLNode(psRoot);
-                  return MS_FAILURE;
-              }
-          }/* end Layer parsing */
-      }/* for */
+  if( psLayerList != NULL ) {
+    for(psLayer = psLayerList->psChild;
+        psLayer != NULL;
+        psLayer = psLayer->psNext) {
+      if(EQUAL(psLayer->pszValue, "Layer")) {
+        if( msLoadMapContextLayer(map, psLayer, nVersion,
+                                  filename, unique_layer_names) == MS_FAILURE ) {
+          CPLDestroyXMLNode(psRoot);
+          return MS_FAILURE;
+        }
+      }/* end Layer parsing */
+    }/* for */
   }
 
   CPLDestroyXMLNode(psRoot);
@@ -1399,7 +1247,7 @@ int msLoadMapContext(mapObj *map, char *filename, int unique_layer_names)
   return MS_SUCCESS;
 
 #else
-  msSetError(MS_MAPCONTEXTERR, 
+  msSetError(MS_MAPCONTEXTERR,
              "Not implemented since Map Context is not enabled.",
              "msGetMapContext()");
   return MS_FAILURE;
@@ -1427,11 +1275,9 @@ int msSaveMapContext(mapObj *map, char *filename)
       msSetError(MS_IOERR, "(%s)", "msSaveMapContext()", filename);
       return(MS_FAILURE);
     }
-  }
-  else
-  {
-      msSetError(MS_IOERR, "Filename is undefined.", "msSaveMapContext()");
-      return MS_FAILURE;
+  } else {
+    msSetError(MS_IOERR, "Filename is undefined.", "msSaveMapContext()");
+    return MS_FAILURE;
   }
 
   nStatus = msWriteMapContext(map, stream);
@@ -1440,7 +1286,7 @@ int msSaveMapContext(mapObj *map, char *filename)
 
   return nStatus;
 #else
-  msSetError(MS_MAPCONTEXTERR, 
+  msSetError(MS_MAPCONTEXTERR,
              "Not implemented since Map Context is not enabled.",
              "msSaveMapContext()");
   return MS_FAILURE;
@@ -1471,12 +1317,11 @@ int msWriteMapContext(mapObj *map, FILE *stream)
 
   nVersion = msOWSParseVersionString(version);
   if (nVersion == OWS_VERSION_BADFORMAT)
-      return MS_FAILURE;  /* msSetError() already called. */
+    return MS_FAILURE;  /* msSetError() already called. */
 
   /* Make sure this is a supported version */
   /* Note that we don't write 0.1.2 even if we read it. */
-  switch (nVersion)
-  {
+  switch (nVersion) {
     case OWS_0_1_4:
     case OWS_0_1_7:
     case OWS_1_0_0:
@@ -1485,78 +1330,68 @@ int msWriteMapContext(mapObj *map, FILE *stream)
       break;
     default:
       /* Not a supported version */
-      msSetError(MS_MAPCONTEXTERR, 
+      msSetError(MS_MAPCONTEXTERR,
                  "This version of Map Context is not supported (%s).",
                  "msSaveMapContext()", version);
       return MS_FAILURE;
   }
 
   /* file header */
-  msOWSPrintEncodeMetadata(stream, &(map->web.metadata), 
-                     NULL, "wms_encoding", OWS_NOERR,
-                "<?xml version='1.0' encoding=\"%s\" standalone=\"no\" ?>\n",
-                    "ISO-8859-1");
+  msOWSPrintEncodeMetadata(stream, &(map->web.metadata),
+                           NULL, "wms_encoding", OWS_NOERR,
+                           "<?xml version='1.0' encoding=\"%s\" standalone=\"no\" ?>\n",
+                           "ISO-8859-1");
 
   /* set the WMS_Viewer_Context information */
   pszEncodedVal = msEncodeHTMLEntities(version);
-  if(nVersion >= OWS_1_0_0)
-  {
-      msIO_fprintf( stream, "<ViewContext version=\"%s\"", pszEncodedVal );
-  }
-  else if(nVersion >= OWS_0_1_7)
-  {
-      msIO_fprintf( stream, "<View_Context version=\"%s\"", pszEncodedVal );
-      
-  }
-  else /* 0.1.4 */
-  {
-      msIO_fprintf( stream, "<WMS_Viewer_Context version=\"%s\"", pszEncodedVal );
+  if(nVersion >= OWS_1_0_0) {
+    msIO_fprintf( stream, "<ViewContext version=\"%s\"", pszEncodedVal );
+  } else if(nVersion >= OWS_0_1_7) {
+    msIO_fprintf( stream, "<View_Context version=\"%s\"", pszEncodedVal );
+
+  } else { /* 0.1.4 */
+    msIO_fprintf( stream, "<WMS_Viewer_Context version=\"%s\"", pszEncodedVal );
   }
   msFree(pszEncodedVal);
 
-  if ( nVersion >= OWS_0_1_7 && nVersion < OWS_1_0_0 )
-  {
-      msOWSPrintEncodeMetadata(stream, &(map->web.metadata), NULL, 
-                               "wms_context_fid", OWS_NOERR," fid=\"%s\"","0");
+  if ( nVersion >= OWS_0_1_7 && nVersion < OWS_1_0_0 ) {
+    msOWSPrintEncodeMetadata(stream, &(map->web.metadata), NULL,
+                             "wms_context_fid", OWS_NOERR," fid=\"%s\"","0");
   }
   if ( nVersion >= OWS_1_0_0 )
-      msOWSPrintEncodeParam(stream, "MAP.NAME", map->name, OWS_NOERR, 
-                            " id=\"%s\"", NULL);
+    msOWSPrintEncodeParam(stream, "MAP.NAME", map->name, OWS_NOERR,
+                          " id=\"%s\"", NULL);
 
   msIO_fprintf( stream, " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"");
   msIO_fprintf( stream, " xmlns:ogc=\"http://www.opengis.net/ogc\"");
 
-  if( nVersion >= OWS_0_1_7 && nVersion < OWS_1_0_0 )
-  {
-      msIO_fprintf( stream, " xmlns:gml=\"http://www.opengis.net/gml\"");
-  }
-  if( nVersion >= OWS_1_0_0 )
-  {
-      msIO_fprintf( stream, " xmlns:xlink=\"http://www.w3.org/1999/xlink\"");
-      msIO_fprintf( stream, " xmlns=\"http://www.opengis.net/context\"");
-      msIO_fprintf( stream, " xmlns:sld=\"http://www.opengis.net/sld\"");
-      pszEncodedVal = msEncodeHTMLEntities(msOWSGetSchemasLocation(map));
-      if( nVersion >= OWS_1_1_0 )
-          msIO_fprintf( stream, 
-                        " xsi:schemaLocation=\"http://www.opengis.net/context %s/context/1.1.0/context.xsd\">\n",
-                        pszEncodedVal);
-      else
-          msIO_fprintf( stream, 
-                        " xsi:schemaLocation=\"http://www.opengis.net/context %s/context/1.0.0/context.xsd\">\n",
-                        pszEncodedVal);
-      msFree(pszEncodedVal);
-  }
-  else
-  {
-      msIO_fprintf( stream, " xmlns:xlink=\"http://www.w3.org/TR/xlink\"");
-
-      pszEncodedVal = msEncodeHTMLEntities(msOWSGetSchemasLocation(map));
-      msIO_fprintf( stream, " xsi:noNamespaceSchemaLocation=\"%s/contexts/",
-               pszEncodedVal );
-      msFree(pszEncodedVal);
-      pszEncodedVal = msEncodeHTMLEntities(msOWSGetSchemasLocation(map));
-      msIO_fprintf( stream, "%s/context.xsd\">\n", pszEncodedVal);
-      msFree(pszEncodedVal);
+  if( nVersion >= OWS_0_1_7 && nVersion < OWS_1_0_0 ) {
+    msIO_fprintf( stream, " xmlns:gml=\"http://www.opengis.net/gml\"");
+  }
+  if( nVersion >= OWS_1_0_0 ) {
+    msIO_fprintf( stream, " xmlns:xlink=\"http://www.w3.org/1999/xlink\"");
+    msIO_fprintf( stream, " xmlns=\"http://www.opengis.net/context\"");
+    msIO_fprintf( stream, " xmlns:sld=\"http://www.opengis.net/sld\"");
+    pszEncodedVal = msEncodeHTMLEntities(msOWSGetSchemasLocation(map));
+    if( nVersion >= OWS_1_1_0 )
+      msIO_fprintf( stream,
+                    " xsi:schemaLocation=\"http://www.opengis.net/context %s/context/1.1.0/context.xsd\">\n",
+                    pszEncodedVal);
+    else
+      msIO_fprintf( stream,
+                    " xsi:schemaLocation=\"http://www.opengis.net/context %s/context/1.0.0/context.xsd\">\n",
+                    pszEncodedVal);
+    msFree(pszEncodedVal);
+  } else {
+    msIO_fprintf( stream, " xmlns:xlink=\"http://www.w3.org/TR/xlink\"");
+
+    pszEncodedVal = msEncodeHTMLEntities(msOWSGetSchemasLocation(map));
+    msIO_fprintf( stream, " xsi:noNamespaceSchemaLocation=\"%s/contexts/",
+                  pszEncodedVal );
+    msFree(pszEncodedVal);
+    pszEncodedVal = msEncodeHTMLEntities(msOWSGetSchemasLocation(map));
+    msIO_fprintf( stream, "%s/context.xsd\">\n", pszEncodedVal);
+    msFree(pszEncodedVal);
   }
 
   /* set the General information */
@@ -1564,111 +1399,100 @@ int msWriteMapContext(mapObj *map, FILE *stream)
 
   /* Window */
   if( map->width != -1 || map->height != -1 )
-      msIO_fprintf( stream, "    <Window width=\"%d\" height=\"%d\"/>\n", 
-               map->width, map->height );
+    msIO_fprintf( stream, "    <Window width=\"%d\" height=\"%d\"/>\n",
+                  map->width, map->height );
 
   /* Bounding box corners and spatial reference system */
   if(tabspace)
-      free(tabspace);
+    free(tabspace);
   tabspace = msStrdup("    ");
   value = msOWSGetEPSGProj(&(map->projection), &(map->web.metadata), "MO", MS_TRUE);
-  msIO_fprintf( stream, 
-          "%s<!-- Bounding box corners and spatial reference system -->\n", 
-           tabspace );
+  msIO_fprintf( stream,
+                "%s<!-- Bounding box corners and spatial reference system -->\n",
+                tabspace );
   if(!value || (strcasecmp(value, "(null)") == 0))
-      msIO_fprintf(stream, "<!-- WARNING: Mandatory data 'projection' was missing in this context. -->\n");
+    msIO_fprintf(stream, "<!-- WARNING: Mandatory data 'projection' was missing in this context. -->\n");
 
   pszEncodedVal = msEncodeHTMLEntities(value);
-  msIO_fprintf( stream, "%s<BoundingBox SRS=\"%s\" minx=\"%f\" miny=\"%f\" maxx=\"%f\" maxy=\"%f\"/>\n", 
-           tabspace, pszEncodedVal, map->extent.minx, map->extent.miny, 
-           map->extent.maxx, map->extent.maxy );
+  msIO_fprintf( stream, "%s<BoundingBox SRS=\"%s\" minx=\"%f\" miny=\"%f\" maxx=\"%f\" maxy=\"%f\"/>\n",
+                tabspace, pszEncodedVal, map->extent.minx, map->extent.miny,
+                map->extent.maxx, map->extent.maxy );
   msFree(pszEncodedVal);
 
   /* Title, name */
-  if( nVersion >= OWS_0_1_7 && nVersion < OWS_1_0_0 )
-  {
-      msOWSPrintEncodeParam(stream, "MAP.NAME", map->name, OWS_NOERR, 
-                            "    <gml:name>%s</gml:name>\n", NULL);
-  }
-  else 
-  {
-      if (nVersion < OWS_0_1_7)
-          msOWSPrintEncodeParam(stream, "MAP.NAME", map->name, OWS_NOERR, 
-                                "    <Name>%s</Name>\n", NULL);
+  if( nVersion >= OWS_0_1_7 && nVersion < OWS_1_0_0 ) {
+    msOWSPrintEncodeParam(stream, "MAP.NAME", map->name, OWS_NOERR,
+                          "    <gml:name>%s</gml:name>\n", NULL);
+  } else {
+    if (nVersion < OWS_0_1_7)
+      msOWSPrintEncodeParam(stream, "MAP.NAME", map->name, OWS_NOERR,
+                            "    <Name>%s</Name>\n", NULL);
 
-      msIO_fprintf( stream, "%s<!-- Title of Context -->\n", tabspace );
-      msOWSPrintEncodeMetadata(stream, &(map->web.metadata), 
-                               NULL, "wms_title", OWS_WARN,
-                               "    <Title>%s</Title>\n", map->name);
+    msIO_fprintf( stream, "%s<!-- Title of Context -->\n", tabspace );
+    msOWSPrintEncodeMetadata(stream, &(map->web.metadata),
+                             NULL, "wms_title", OWS_WARN,
+                             "    <Title>%s</Title>\n", map->name);
   }
 
   /* keyword */
-  if (nVersion >= OWS_1_0_0)
-  {
-      if (msLookupHashTable(&(map->web.metadata),"wms_keywordlist")!=NULL)
-      {
-          char **papszKeywords;
-          int nKeywords, iKey;
-
-          pszValue = msLookupHashTable(&(map->web.metadata), 
-                                       "wms_keywordlist");
-          papszKeywords = msStringSplit(pszValue, ',', &nKeywords);
-          if(nKeywords > 0 && papszKeywords)
-          {
-              msIO_fprintf( stream, "    <KeywordList>\n");
-              for(iKey=0; iKey<nKeywords; iKey++)
-              {
-                  pszEncodedVal = msEncodeHTMLEntities(papszKeywords[iKey]);
-                  msIO_fprintf( stream, "      <Keyword>%s</Keyword>\n", 
-                          pszEncodedVal);
-                  msFree(pszEncodedVal);
-              }
-              msIO_fprintf( stream, "    </KeywordList>\n");
-          }
+  if (nVersion >= OWS_1_0_0) {
+    if (msLookupHashTable(&(map->web.metadata),"wms_keywordlist")!=NULL) {
+      char **papszKeywords;
+      int nKeywords, iKey;
+
+      pszValue = msLookupHashTable(&(map->web.metadata),
+                                   "wms_keywordlist");
+      papszKeywords = msStringSplit(pszValue, ',', &nKeywords);
+      if(nKeywords > 0 && papszKeywords) {
+        msIO_fprintf( stream, "    <KeywordList>\n");
+        for(iKey=0; iKey<nKeywords; iKey++) {
+          pszEncodedVal = msEncodeHTMLEntities(papszKeywords[iKey]);
+          msIO_fprintf( stream, "      <Keyword>%s</Keyword>\n",
+                        pszEncodedVal);
+          msFree(pszEncodedVal);
+        }
+        msIO_fprintf( stream, "    </KeywordList>\n");
       }
-  }
-  else
-    msOWSPrintEncodeMetadataList(stream, &(map->web.metadata), NULL, 
-                                 "wms_keywordlist", 
+    }
+  } else
+    msOWSPrintEncodeMetadataList(stream, &(map->web.metadata), NULL,
+                                 "wms_keywordlist",
                                  "    <Keywords>\n", "    </Keywords>\n",
                                  "      %s\n", NULL);
 
   /* abstract */
-  if( nVersion >= OWS_0_1_7 && nVersion < OWS_1_0_0 )
-  {
-      msOWSPrintEncodeMetadata(stream, &(map->web.metadata), 
-                               NULL, "wms_abstract", OWS_NOERR,
-                         "    <gml:description>%s</gml:description>\n", NULL);
-  }
-  else
-  {
-      msOWSPrintEncodeMetadata(stream, &(map->web.metadata), 
-                               NULL, "wms_abstract", OWS_NOERR,
-                               "    <Abstract>%s</Abstract>\n", NULL);
+  if( nVersion >= OWS_0_1_7 && nVersion < OWS_1_0_0 ) {
+    msOWSPrintEncodeMetadata(stream, &(map->web.metadata),
+                             NULL, "wms_abstract", OWS_NOERR,
+                             "    <gml:description>%s</gml:description>\n", NULL);
+  } else {
+    msOWSPrintEncodeMetadata(stream, &(map->web.metadata),
+                             NULL, "wms_abstract", OWS_NOERR,
+                             "    <Abstract>%s</Abstract>\n", NULL);
   }
 
   /* LogoURL */
   /* The LogoURL have a width, height, format and an URL */
-  msOWSPrintURLType(stream, &(map->web.metadata), "MO", "logourl", 
-                    OWS_NOERR, NULL, "LogoURL", NULL, " width=\"%s\"", 
-                    " height=\"%s\""," format=\"%s\"", 
-          "      <OnlineResource xlink:type=\"simple\" xlink:href=\"%s\"/>\n", 
-                    MS_FALSE, MS_FALSE, MS_FALSE, MS_FALSE, MS_TRUE, 
+  msOWSPrintURLType(stream, &(map->web.metadata), "MO", "logourl",
+                    OWS_NOERR, NULL, "LogoURL", NULL, " width=\"%s\"",
+                    " height=\"%s\""," format=\"%s\"",
+                    "      <OnlineResource xlink:type=\"simple\" xlink:href=\"%s\"/>\n",
+                    MS_FALSE, MS_FALSE, MS_FALSE, MS_FALSE, MS_TRUE,
                     NULL, NULL, NULL, NULL, NULL, "    ");
 
   /* DataURL */
-  msOWSPrintEncodeMetadata(stream, &(map->web.metadata), 
+  msOWSPrintEncodeMetadata(stream, &(map->web.metadata),
                            NULL, "wms_dataurl", OWS_NOERR,
-                "    <DataURL>\n      <OnlineResource xlink:type=\"simple\" xlink:href=\"%s\"/>\n    </DataURL>\n", NULL);
+                           "    <DataURL>\n      <OnlineResource xlink:type=\"simple\" xlink:href=\"%s\"/>\n    </DataURL>\n", NULL);
 
   /* DescriptionURL */
   /* The DescriptionURL have a width, height, format and an URL */
   /* The metadata is structured like this: "width height format url" */
-  msOWSPrintURLType(stream, &(map->web.metadata), "MO", "descriptionurl", 
-                    OWS_NOERR, NULL, "DescriptionURL", NULL, " width=\"%s\"", 
-                    " height=\"%s\""," format=\"%s\"", 
-          "      <OnlineResource xlink:type=\"simple\" xlink:href=\"%s\"/>\n", 
-                    MS_FALSE, MS_FALSE, MS_FALSE, MS_FALSE, MS_TRUE, 
+  msOWSPrintURLType(stream, &(map->web.metadata), "MO", "descriptionurl",
+                    OWS_NOERR, NULL, "DescriptionURL", NULL, " width=\"%s\"",
+                    " height=\"%s\""," format=\"%s\"",
+                    "      <OnlineResource xlink:type=\"simple\" xlink:href=\"%s\"/>\n",
+                    MS_FALSE, MS_FALSE, MS_FALSE, MS_FALSE, MS_TRUE,
                     NULL, NULL, NULL, NULL, NULL, "    ");
 
   /* Contact Info */
@@ -1682,515 +1506,468 @@ int msWriteMapContext(mapObj *map, FILE *stream)
   msIO_fprintf(stream, "  <LayerList>\n");
 
   /* Loop on all layer   */
-  for(i=0; i<map->numlayers; i++)
-  {
-      if(GET_LAYER(map, i)->status != MS_DELETE && GET_LAYER(map, i)->connectiontype == MS_WMS)
-      {
-          if(GET_LAYER(map, i)->status == MS_OFF)
-              nValue = 1;
-          else
-              nValue = 0;
-          msIO_fprintf(stream, "    <Layer queryable=\"%d\" hidden=\"%d\">\n", 
-                  msIsLayerQueryable(GET_LAYER(map, i)), nValue);
-
-          /*  */
-          /* Server definition */
-          /*  */
-          if(nVersion < OWS_1_0_0 )
-              msOWSPrintEncodeMetadata(stream, &(GET_LAYER(map, i)->metadata), 
-                                       NULL, "wms_server_version", OWS_WARN,
-                             "      <Server service=\"WMS\" version=\"%s\" ",
-                                       "1.0.0");
-          else
-              msOWSPrintEncodeMetadata(stream, &(GET_LAYER(map, i)->metadata), 
-                                       NULL, "wms_server_version", OWS_WARN,
-                          "      <Server service=\"OGC:WMS\" version=\"%s\" ",
-                                       "1.0.0");
-
-          if(msOWSLookupMetadata(&(GET_LAYER(map, i)->metadata), "MO", "server_title"))
-              msOWSPrintEncodeMetadata(stream, &(GET_LAYER(map, i)->metadata),
-                                       NULL, "wms_server_title", OWS_NOERR,
-                                       "title=\"%s\">\n", "");
-
-          else if(GET_LAYER(map, i)->name)
-              msOWSPrintEncodeMetadata(stream, &(GET_LAYER(map, i)->metadata), 
-                                       NULL, "wms_title", OWS_NOERR, 
-                                       "title=\"%s\">\n", GET_LAYER(map, i)->name);
-          else
-          {
-              msOWSPrintEncodeMetadata(stream, &(GET_LAYER(map, i)->metadata), 
-                                       NULL, "wms_title", OWS_NOERR, 
-                                       "title=\"%s\">\n", "");
+  for(i=0; i<map->numlayers; i++) {
+    if(GET_LAYER(map, i)->status != MS_DELETE && GET_LAYER(map, i)->connectiontype == MS_WMS) {
+      if(GET_LAYER(map, i)->status == MS_OFF)
+        nValue = 1;
+      else
+        nValue = 0;
+      msIO_fprintf(stream, "    <Layer queryable=\"%d\" hidden=\"%d\">\n",
+                   msIsLayerQueryable(GET_LAYER(map, i)), nValue);
+
+      /*  */
+      /* Server definition */
+      /*  */
+      if(nVersion < OWS_1_0_0 )
+        msOWSPrintEncodeMetadata(stream, &(GET_LAYER(map, i)->metadata),
+                                 NULL, "wms_server_version", OWS_WARN,
+                                 "      <Server service=\"WMS\" version=\"%s\" ",
+                                 "1.0.0");
+      else
+        msOWSPrintEncodeMetadata(stream, &(GET_LAYER(map, i)->metadata),
+                                 NULL, "wms_server_version", OWS_WARN,
+                                 "      <Server service=\"OGC:WMS\" version=\"%s\" ",
+                                 "1.0.0");
+
+      if(msOWSLookupMetadata(&(GET_LAYER(map, i)->metadata), "MO", "server_title"))
+        msOWSPrintEncodeMetadata(stream, &(GET_LAYER(map, i)->metadata),
+                                 NULL, "wms_server_title", OWS_NOERR,
+                                 "title=\"%s\">\n", "");
+
+      else if(GET_LAYER(map, i)->name)
+        msOWSPrintEncodeMetadata(stream, &(GET_LAYER(map, i)->metadata),
+                                 NULL, "wms_title", OWS_NOERR,
+                                 "title=\"%s\">\n", GET_LAYER(map, i)->name);
+      else {
+        msOWSPrintEncodeMetadata(stream, &(GET_LAYER(map, i)->metadata),
+                                 NULL, "wms_title", OWS_NOERR,
+                                 "title=\"%s\">\n", "");
+      }
+
+      /* Get base url of the online resource to be the default value */
+      if(GET_LAYER(map, i)->connection)
+        pszValue = msStrdup( GET_LAYER(map, i)->connection );
+      else
+        pszValue = msStrdup( "" );
+      pszChar = strchr(pszValue, '?');
+      if( pszChar )
+        pszValue[pszChar - pszValue] = '\0';
+      if(msOWSPrintEncodeMetadata(stream, &(GET_LAYER(map, i)->metadata),
+                                  NULL, "wms_onlineresource", OWS_WARN,
+                                  "        <OnlineResource xlink:type=\"simple\" xlink:href=\"%s\"/>\n",
+                                  pszValue) == OWS_WARN)
+        msIO_fprintf(stream, "<!-- wms_onlineresource not set, using base URL"
+                     " , but probably not what you want -->\n");
+      msIO_fprintf(stream, "      </Server>\n");
+      if(pszValue)
+        free(pszValue);
+
+      /*  */
+      /* Layer information */
+      /*  */
+      msOWSPrintEncodeMetadata(stream, &(GET_LAYER(map, i)->metadata),
+                               NULL, "wms_name", OWS_WARN,
+                               "      <Name>%s</Name>\n",
+                               GET_LAYER(map, i)->name);
+      msOWSPrintEncodeMetadata(stream, &(GET_LAYER(map, i)->metadata),
+                               NULL, "wms_title", OWS_WARN,
+                               "      <Title>%s</Title>\n",
+                               GET_LAYER(map, i)->name);
+      msOWSPrintEncodeMetadata(stream, &(GET_LAYER(map, i)->metadata),
+                               NULL, "wms_abstract", OWS_NOERR,
+                               "      <Abstract>%s</Abstract>\n",
+                               NULL);
+
+      /* DataURL */
+      if(nVersion <= OWS_0_1_4) {
+        msOWSPrintEncodeMetadata(stream, &(GET_LAYER(map, i)->metadata),
+                                 NULL, "wms_dataurl", OWS_NOERR,
+                                 "      <DataURL>%s</DataURL>\n",
+                                 NULL);
+      } else {
+        /* The DataURL have a width, height, format and an URL */
+        /* The metadata will be structured like this:  */
+        /* "width height format url" */
+        /* Note: in version 0.1.7 the width and height are not included  */
+        /* in the Context file, but they are included in the metadata for */
+        /* for consistency with the URLType. */
+        msOWSPrintURLType(stream, &(GET_LAYER(map, i)->metadata), "MO",
+                          "dataurl", OWS_NOERR, NULL, "DataURL", NULL,
+                          " width=\"%s\"", " height=\"%s\"",
+                          " format=\"%s\"",
+                          "        <OnlineResource xlink:type=\"simple\""
+                          " xlink:href=\"%s\"/>\n",
+                          MS_FALSE, MS_FALSE, MS_FALSE, MS_FALSE,
+                          MS_TRUE, NULL, NULL, NULL,NULL,NULL, "      ");
+      }
+
+      /* MetadataURL */
+      /* The MetadataURL have a width, height, format and an URL */
+      /* The metadata will be structured like this:  */
+      /* "width height format url" */
+      msOWSPrintURLType(stream, &(GET_LAYER(map, i)->metadata), "MO",
+                        "metadataurl", OWS_NOERR, NULL, "MetadataURL",NULL,
+                        " width=\"%s\"", " height=\"%s\""," format=\"%s\"",
+                        "        <OnlineResource xlink:type=\"simple\""
+                        " xlink:href=\"%s\"/>\n",
+                        MS_FALSE, MS_FALSE, MS_FALSE, MS_FALSE,
+                        MS_TRUE, NULL, NULL, NULL, NULL, NULL, "      ");
+
+      /* MinScale && MaxScale */
+      if(nVersion >= OWS_1_1_0 && GET_LAYER(map, i)->minscaledenom > 0)
+        msIO_fprintf(stream,
+                     "      <sld:MinScaleDenominator>%g</sld:MinScaleDenominator>\n",
+                     GET_LAYER(map, i)->minscaledenom);
+      if(nVersion >= OWS_1_1_0 && GET_LAYER(map, i)->maxscaledenom > 0)
+        msIO_fprintf(stream,
+                     "      <sld:MaxScaleDenominator>%g</sld:MaxScaleDenominator>\n",
+                     GET_LAYER(map, i)->maxscaledenom);
+
+      /* Layer SRS */
+      pszValue = (char*)msOWSGetEPSGProj(&(GET_LAYER(map, i)->projection),
+                                         &(GET_LAYER(map, i)->metadata),
+                                         "MO", MS_FALSE);
+      if(pszValue && (strcasecmp(pszValue, "(null)") != 0)) {
+        pszEncodedVal = msEncodeHTMLEntities(pszValue);
+        msIO_fprintf(stream, "      <SRS>%s</SRS>\n", pszEncodedVal);
+        msFree(pszEncodedVal);
+      }
+
+      /* Format */
+      if(msLookupHashTable(&(GET_LAYER(map, i)->metadata),"wms_formatlist")==NULL &&
+          msLookupHashTable(&(GET_LAYER(map, i)->metadata),"wms_format")==NULL) {
+        pszURL = NULL;
+        if(GET_LAYER(map, i)->connection)
+          pszURL = msStrdup( GET_LAYER(map, i)->connection );
+        else
+          pszURL = msStrdup( "" );
+        pszValue = pszURL;
+        pszValue = strstr( pszValue, "FORMAT=" );
+        if( pszValue ) {
+          pszValue += 7;
+          pszChar = strchr(pszValue, '&');
+          if( pszChar )
+            pszValue[pszChar - pszValue] = '\0';
+          if(strcasecmp(pszValue, "") != 0) {
+            pszEncodedVal = msEncodeHTMLEntities(pszValue);
+            msIO_fprintf( stream, "      <FormatList>\n");
+            msIO_fprintf(stream,"        <Format>%s</Format>\n",pszValue);
+            msIO_fprintf( stream, "      </FormatList>\n");
+            msFree(pszEncodedVal);
+          }
+        }
+        if(pszURL)
+          free(pszURL);
+      } else {
+        char **papszFormats;
+        int numFormats, nForm;
+
+        pszValue = msLookupHashTable(&(GET_LAYER(map, i)->metadata),
+                                     "wms_formatlist");
+        if(!pszValue)
+          pszValue = msLookupHashTable(&(GET_LAYER(map, i)->metadata),
+                                       "wms_format");
+        pszCurrent = msLookupHashTable(&(GET_LAYER(map, i)->metadata),
+                                       "wms_format");
+
+        papszFormats = msStringSplit(pszValue, ',', &numFormats);
+        if(numFormats > 0 && papszFormats) {
+          msIO_fprintf( stream, "      <FormatList>\n");
+          for(nForm=0; nForm<numFormats; nForm++) {
+            pszEncodedVal =msEncodeHTMLEntities(papszFormats[nForm]);
+            if(pszCurrent && (strcasecmp(papszFormats[nForm],
+                                         pszCurrent) == 0))
+              msIO_fprintf( stream,
+                            "        <Format current=\"1\">%s</Format>\n",
+                            pszEncodedVal);
+            else
+              msIO_fprintf( stream, "        <Format>%s</Format>\n",
+                            pszEncodedVal);
+            msFree(pszEncodedVal);
           }
+          msIO_fprintf( stream, "      </FormatList>\n");
+        }
+        if(papszFormats)
+          msFreeCharArray(papszFormats, numFormats);
+      }
+      /* Style */
+      /* First check the stylelist */
+      pszValue = msLookupHashTable(&(GET_LAYER(map, i)->metadata),
+                                   "wms_stylelist");
+      if(pszValue == NULL || strlen(msStringTrimLeft(pszValue)) < 1) {
+        /* Check if the style is in the connection URL */
+        pszURL = "";
+        if(GET_LAYER(map, i)->connection)
+          pszURL = msStrdup( GET_LAYER(map, i)->connection );
+        else
+          pszURL = msStrdup( "" );
+        pszValue = pszURL;
+        /* Grab the STYLES in the URL */
+        pszValue = strstr( pszValue, "STYLES=" );
+        if( pszValue ) {
+          pszValue += 7;
+          pszChar = strchr(pszValue, '&');
+          if( pszChar )
+            pszValue[pszChar - pszValue] = '\0';
 
-          /* Get base url of the online resource to be the default value */
+          /* Check the SLD string from the URL */
           if(GET_LAYER(map, i)->connection)
-              pszValue = msStrdup( GET_LAYER(map, i)->connection );
+            pszSLD2 = msStrdup(GET_LAYER(map, i)->connection);
           else
-              pszValue = msStrdup( "" );
-          pszChar = strchr(pszValue, '?');
-          if( pszChar )
-              pszValue[pszChar - pszValue] = '\0';
-          if(msOWSPrintEncodeMetadata(stream, &(GET_LAYER(map, i)->metadata), 
-                                      NULL, "wms_onlineresource", OWS_WARN, 
-         "        <OnlineResource xlink:type=\"simple\" xlink:href=\"%s\"/>\n",
-                                      pszValue) == OWS_WARN)
-              msIO_fprintf(stream, "<!-- wms_onlineresource not set, using base URL"
-                      " , but probably not what you want -->\n");
-          msIO_fprintf(stream, "      </Server>\n");
-          if(pszValue)
-              free(pszValue);
-
-          /*  */
-          /* Layer information */
-          /*  */
-          msOWSPrintEncodeMetadata(stream, &(GET_LAYER(map, i)->metadata), 
-                             NULL, "wms_name", OWS_WARN, 
-                             "      <Name>%s</Name>\n", 
-                             GET_LAYER(map, i)->name);
-          msOWSPrintEncodeMetadata(stream, &(GET_LAYER(map, i)->metadata), 
-                             NULL, "wms_title", OWS_WARN, 
-                             "      <Title>%s</Title>\n", 
-                             GET_LAYER(map, i)->name);
-          msOWSPrintEncodeMetadata(stream, &(GET_LAYER(map, i)->metadata), 
-                             NULL, "wms_abstract", OWS_NOERR, 
-                             "      <Abstract>%s</Abstract>\n", 
-                             NULL);
-
-          /* DataURL */
-          if(nVersion <= OWS_0_1_4)
-          {
-              msOWSPrintEncodeMetadata(stream, &(GET_LAYER(map, i)->metadata), 
-                                 NULL, "wms_dataurl", OWS_NOERR, 
-                                 "      <DataURL>%s</DataURL>\n", 
-                                 NULL);
+            pszSLD2 = msStrdup( "" );
+          if(pszSLD2) {
+            pszSLD = strstr(pszSLD2, "SLD=");
+            pszSLDBody = strstr(pszSLD2, "SLD_BODY=");
+          } else {
+            pszSLD = NULL;
+            pszSLDBody = NULL;
           }
-          else
-          {
-              /* The DataURL have a width, height, format and an URL */
-              /* The metadata will be structured like this:  */
-              /* "width height format url" */
-              /* Note: in version 0.1.7 the width and height are not included  */
-              /* in the Context file, but they are included in the metadata for */
-              /* for consistency with the URLType. */
-              msOWSPrintURLType(stream, &(GET_LAYER(map, i)->metadata), "MO", 
-                                "dataurl", OWS_NOERR, NULL, "DataURL", NULL, 
-                                " width=\"%s\"", " height=\"%s\"",
-                                " format=\"%s\"", 
-                                "        <OnlineResource xlink:type=\"simple\""
-                                " xlink:href=\"%s\"/>\n", 
-                                MS_FALSE, MS_FALSE, MS_FALSE, MS_FALSE, 
-                                MS_TRUE, NULL, NULL, NULL,NULL,NULL, "      ");
+          /* Check SLD */
+          if( pszSLD ) {
+            pszChar = strchr(pszSLD, '&');
+            if( pszChar )
+              pszSLD[pszChar - pszSLD] = '\0';
+            pszSLD += 4;
           }
-
-          /* MetadataURL */
-          /* The MetadataURL have a width, height, format and an URL */
-          /* The metadata will be structured like this:  */
-          /* "width height format url" */
-          msOWSPrintURLType(stream, &(GET_LAYER(map, i)->metadata), "MO", 
-                            "metadataurl", OWS_NOERR, NULL, "MetadataURL",NULL,
-                            " width=\"%s\"", " height=\"%s\""," format=\"%s\"",
-                            "        <OnlineResource xlink:type=\"simple\""
-                            " xlink:href=\"%s\"/>\n", 
-                            MS_FALSE, MS_FALSE, MS_FALSE, MS_FALSE, 
-                            MS_TRUE, NULL, NULL, NULL, NULL, NULL, "      ");
-
-          /* MinScale && MaxScale */
-          if(nVersion >= OWS_1_1_0 && GET_LAYER(map, i)->minscaledenom > 0)
-              msIO_fprintf(stream, 
-               "      <sld:MinScaleDenominator>%g</sld:MinScaleDenominator>\n",
-                           GET_LAYER(map, i)->minscaledenom);
-          if(nVersion >= OWS_1_1_0 && GET_LAYER(map, i)->maxscaledenom > 0)
-              msIO_fprintf(stream, 
-               "      <sld:MaxScaleDenominator>%g</sld:MaxScaleDenominator>\n",
-                           GET_LAYER(map, i)->maxscaledenom);
-
-          /* Layer SRS */
-          pszValue = (char*)msOWSGetEPSGProj(&(GET_LAYER(map, i)->projection), 
-                                             &(GET_LAYER(map, i)->metadata),
-                                             "MO", MS_FALSE);
-          if(pszValue && (strcasecmp(pszValue, "(null)") != 0))
-          {
+          /* Check SLDBody  */
+          if( pszSLDBody ) {
+            pszChar = strchr(pszSLDBody, '&');
+            if( pszChar )
+              pszSLDBody[pszChar - pszSLDBody] = '\0';
+            pszSLDBody += 9;
+          }
+          if( (pszValue && (strcasecmp(pszValue, "") != 0)) ||
+              (pszSLD && (strcasecmp(pszSLD, "") != 0)) ||
+              (pszSLDBody && (strcasecmp(pszSLDBody, "") != 0))) {
+            /* Write Name and Title */
+            msIO_fprintf( stream, "      <StyleList>\n");
+            msIO_fprintf( stream, "        <Style current=\"1\">\n");
+            if( pszValue && (strcasecmp(pszValue, "") != 0)) {
               pszEncodedVal = msEncodeHTMLEntities(pszValue);
-              msIO_fprintf(stream, "      <SRS>%s</SRS>\n", pszEncodedVal);
+              msIO_fprintf(stream, "          <Name>%s</Name>\n",
+                           pszEncodedVal);
+              msIO_fprintf(stream,"          <Title>%s</Title>\n",
+                           pszEncodedVal);
               msFree(pszEncodedVal);
+            }
+            /* Write the SLD string from the URL */
+            if( pszSLD && (strcasecmp(pszSLD, "") != 0)) {
+              pszEncodedVal = msEncodeHTMLEntities(pszSLD);
+              msIO_fprintf( stream, "          <SLD>\n" );
+              msIO_fprintf( stream,
+                            "            <OnlineResource xlink:type=\"simple\" ");
+              msIO_fprintf(stream,"xlink:href=\"%s\"/>",
+                           pszEncodedVal);
+              msIO_fprintf( stream, "          </SLD>\n" );
+              free(pszEncodedVal);
+            } else if(pszSLDBody && (strcasecmp(pszSLDBody, "") != 0)) {
+              msIO_fprintf( stream, "          <SLD>\n" );
+              msIO_fprintf( stream, "            %s\n",pszSLDBody);
+              msIO_fprintf( stream, "          </SLD>\n" );
+            }
+            msIO_fprintf( stream, "        </Style>\n");
+            msIO_fprintf( stream, "      </StyleList>\n");
           }
-
-          /* Format */
-          if(msLookupHashTable(&(GET_LAYER(map, i)->metadata),"wms_formatlist")==NULL && 
-             msLookupHashTable(&(GET_LAYER(map, i)->metadata),"wms_format")==NULL)
-          {
-              pszURL = NULL;
-              if(GET_LAYER(map, i)->connection)
-                  pszURL = msStrdup( GET_LAYER(map, i)->connection );
-              else
-                  pszURL = msStrdup( "" );
-              pszValue = pszURL;
-              pszValue = strstr( pszValue, "FORMAT=" );
-              if( pszValue )
-              {
-                  pszValue += 7;
-                  pszChar = strchr(pszValue, '&');
-                  if( pszChar )
-                      pszValue[pszChar - pszValue] = '\0';
-                  if(strcasecmp(pszValue, "") != 0)
-                  {
-                      pszEncodedVal = msEncodeHTMLEntities(pszValue);
-                      msIO_fprintf( stream, "      <FormatList>\n");
-                      msIO_fprintf(stream,"        <Format>%s</Format>\n",pszValue);
-                      msIO_fprintf( stream, "      </FormatList>\n");
-                      msFree(pszEncodedVal);
-                  }
-              }
-              if(pszURL)
-                  free(pszURL);
-          }
-          else
-          {
-              char **papszFormats;
-              int numFormats, nForm;
-
-              pszValue = msLookupHashTable(&(GET_LAYER(map, i)->metadata), 
-                                           "wms_formatlist");
-              if(!pszValue)
-                  pszValue = msLookupHashTable(&(GET_LAYER(map, i)->metadata), 
-                                               "wms_format");
-              pszCurrent = msLookupHashTable(&(GET_LAYER(map, i)->metadata), 
-                                             "wms_format");
-
-              papszFormats = msStringSplit(pszValue, ',', &numFormats);
-              if(numFormats > 0 && papszFormats)
-              {
-                  msIO_fprintf( stream, "      <FormatList>\n");
-                  for(nForm=0; nForm<numFormats; nForm++)
-                  {
-                      pszEncodedVal =msEncodeHTMLEntities(papszFormats[nForm]);
-                      if(pszCurrent && (strcasecmp(papszFormats[nForm], 
-                                                   pszCurrent) == 0))
-                          msIO_fprintf( stream,
-                                 "        <Format current=\"1\">%s</Format>\n",
-                                   pszEncodedVal);
-                      else
-                          msIO_fprintf( stream, "        <Format>%s</Format>\n", 
-                                   pszEncodedVal);
-                      msFree(pszEncodedVal);
-                  }
-                  msIO_fprintf( stream, "      </FormatList>\n");
-              }
-              if(papszFormats)
-                  msFreeCharArray(papszFormats, numFormats);
-          }
-          /* Style */
-          /* First check the stylelist */
-          pszValue = msLookupHashTable(&(GET_LAYER(map, i)->metadata), 
-                                       "wms_stylelist");
-          if(pszValue == NULL || strlen(msStringTrimLeft(pszValue)) < 1)
-          {
-              /* Check if the style is in the connection URL */
-              pszURL = "";
-              if(GET_LAYER(map, i)->connection)
-                  pszURL = msStrdup( GET_LAYER(map, i)->connection );
-              else
-                  pszURL = msStrdup( "" );
-              pszValue = pszURL;
-              /* Grab the STYLES in the URL */
-              pszValue = strstr( pszValue, "STYLES=" );
-              if( pszValue )
-              {
-                  pszValue += 7;
-                  pszChar = strchr(pszValue, '&');
-                  if( pszChar )
-                      pszValue[pszChar - pszValue] = '\0';
-
-                  /* Check the SLD string from the URL */
-                  if(GET_LAYER(map, i)->connection)
-                      pszSLD2 = msStrdup(GET_LAYER(map, i)->connection);
-                  else
-                      pszSLD2 = msStrdup( "" );
-                  if(pszSLD2)
-                  {
-                      pszSLD = strstr(pszSLD2, "SLD=");
-                      pszSLDBody = strstr(pszSLD2, "SLD_BODY=");
-                  }
-                  else
-                  {
-                      pszSLD = NULL;
-                      pszSLDBody = NULL;
-                  }
-                  /* Check SLD */
-                  if( pszSLD )
-                  {
-                      pszChar = strchr(pszSLD, '&');
-                      if( pszChar )
-                          pszSLD[pszChar - pszSLD] = '\0';
-                      pszSLD += 4;
-                  }
-                  /* Check SLDBody  */
-                  if( pszSLDBody )
-                  {
-                      pszChar = strchr(pszSLDBody, '&');
-                      if( pszChar )
-                          pszSLDBody[pszChar - pszSLDBody] = '\0';
-                      pszSLDBody += 9;
-                  }
-                  if( (pszValue && (strcasecmp(pszValue, "") != 0)) || 
-                      (pszSLD && (strcasecmp(pszSLD, "") != 0)) || 
-                      (pszSLDBody && (strcasecmp(pszSLDBody, "") != 0)))
-                  {
-                      /* Write Name and Title */
-                      msIO_fprintf( stream, "      <StyleList>\n");
-                      msIO_fprintf( stream, "        <Style current=\"1\">\n");
-                      if( pszValue && (strcasecmp(pszValue, "") != 0))
-                      {
-                          pszEncodedVal = msEncodeHTMLEntities(pszValue);
-                          msIO_fprintf(stream, "          <Name>%s</Name>\n", 
-                                  pszEncodedVal);
-                          msIO_fprintf(stream,"          <Title>%s</Title>\n",
-                                  pszEncodedVal);
-                          msFree(pszEncodedVal);
-                      }
-                      /* Write the SLD string from the URL */
-                      if( pszSLD && (strcasecmp(pszSLD, "") != 0))
-                      {
-                          pszEncodedVal = msEncodeHTMLEntities(pszSLD);
-                          msIO_fprintf( stream, "          <SLD>\n" );
-                          msIO_fprintf( stream, 
-                         "            <OnlineResource xlink:type=\"simple\" ");
-                          msIO_fprintf(stream,"xlink:href=\"%s\"/>", 
-                                       pszEncodedVal);
-                          msIO_fprintf( stream, "          </SLD>\n" );
-                          free(pszEncodedVal);
-                      }
-                      else if(pszSLDBody && (strcasecmp(pszSLDBody, "") != 0))
-                      {
-                          msIO_fprintf( stream, "          <SLD>\n" );
-                          msIO_fprintf( stream, "            %s\n",pszSLDBody);
-                          msIO_fprintf( stream, "          </SLD>\n" );
-                      }
-                      msIO_fprintf( stream, "        </Style>\n");
-                      msIO_fprintf( stream, "      </StyleList>\n");
-                  }
-                  if(pszSLD2)
-                  {
-                      free(pszSLD2);
-                      pszSLD2 = NULL;
-                  }
-              }
-              if(pszURL)
-              {
-                  free(pszURL);
-                  pszURL = NULL;
-              }
+          if(pszSLD2) {
+            free(pszSLD2);
+            pszSLD2 = NULL;
           }
+        }
+        if(pszURL) {
+          free(pszURL);
+          pszURL = NULL;
+        }
+      } else {
+        /* If the style information is not in the connection URL, */
+        /* read the metadata. */
+        pszValue = msLookupHashTable(&(GET_LAYER(map, i)->metadata),
+                                     "wms_stylelist");
+        pszCurrent = msLookupHashTable(&(GET_LAYER(map, i)->metadata),
+                                       "wms_style");
+        msIO_fprintf( stream, "      <StyleList>\n");
+        /* Loop in each style in the style list */
+        while(pszValue != NULL) {
+          pszStyle = msStrdup(pszValue);
+          pszChar = strchr(pszStyle, ',');
+          if(pszChar != NULL)
+            pszStyle[pszChar - pszStyle] = '\0';
+          if(strcasecmp(pszStyle, "") == 0)
+            continue;
+
+          if(pszCurrent && (strcasecmp(pszStyle, pszCurrent) == 0))
+            msIO_fprintf( stream,"        <Style current=\"1\">\n" );
           else
-          {
-              /* If the style information is not in the connection URL, */
-              /* read the metadata. */
-              pszValue = msLookupHashTable(&(GET_LAYER(map, i)->metadata), 
-                                           "wms_stylelist");
-              pszCurrent = msLookupHashTable(&(GET_LAYER(map, i)->metadata), 
-                                             "wms_style");
-              msIO_fprintf( stream, "      <StyleList>\n");
-              /* Loop in each style in the style list */
-              while(pszValue != NULL)
-              {
-                  pszStyle = msStrdup(pszValue);
-                  pszChar = strchr(pszStyle, ',');
-                  if(pszChar != NULL)
-                      pszStyle[pszChar - pszStyle] = '\0';
-                  if(strcasecmp(pszStyle, "") == 0)
-                      continue;
-
-                  if(pszCurrent && (strcasecmp(pszStyle, pszCurrent) == 0))
-                      msIO_fprintf( stream,"        <Style current=\"1\">\n" );
-                  else
-                      msIO_fprintf( stream, "        <Style>\n" );
-
-                  /* Write SLDURL if it is in the metadata */
-                  pszStyleItem = (char*)malloc(strlen(pszStyle)+10+10);
-                  sprintf(pszStyleItem, "wms_style_%s_sld", pszStyle);
-                  if(msLookupHashTable(&(GET_LAYER(map, i)->metadata),
-                                       pszStyleItem) != NULL)
-                  {
-                      msIO_fprintf(stream, "          <SLD>\n");
-                      msOWSPrintEncodeMetadata(stream, 
-                                               &(GET_LAYER(map, i)->metadata),
-                                               NULL, pszStyleItem, 
-                                               OWS_NOERR, 
-     "            <OnlineResource xlink:type=\"simple\" xlink:href=\"%s\"/>\n",
-                                               NULL);
-                      msIO_fprintf(stream, "          </SLD>\n");
-                      free(pszStyleItem);
-                  }
-                  else
-                  {
-                      /* If the URL is not there, check for SLDBody */
-                      sprintf(pszStyleItem, "wms_style_%s_sld_body", pszStyle);
-                      if(msLookupHashTable(&(GET_LAYER(map, i)->metadata),
-                                           pszStyleItem) != NULL)
-                      {
-                          msIO_fprintf(stream, "          <SLD>\n");
-                          msOWSPrintMetadata(stream,&(GET_LAYER(map, i)->metadata),
-                                             NULL, pszStyleItem, OWS_NOERR, 
-                                             "            %s\n", NULL);
-                          msIO_fprintf(stream, "          </SLD>\n");
-                          free(pszStyleItem);
-                      }
-                      else
-                      {
-                          /* If the SLD is not specified, then write the */
-                          /* name, Title and LegendURL */
-                          free(pszStyleItem);
-                          /* Name */
-                          pszEncodedVal = msEncodeHTMLEntities(pszStyle);
-                          msIO_fprintf(stream, "          <Name>%s</Name>\n", 
-                                       pszEncodedVal);
-                          msFree(pszEncodedVal);
-                          pszStyleItem = (char*)malloc(strlen(pszStyle)+10+8);
-                          sprintf(pszStyleItem, "wms_style_%s_title",pszStyle);
-                          /* Title */
-                          msOWSPrintEncodeMetadata(stream, 
-                                                   &(GET_LAYER(map, i)->metadata), 
-                                                   NULL, pszStyleItem, 
-                                                   OWS_NOERR, 
-                                        "          <Title>%s</Title>\n",
-                                                   NULL);
-                          free(pszStyleItem);
-
-                          /* LegendURL */
-                          pszStyleItem = (char*)malloc(strlen(pszStyle)+10+20);
-                          sprintf(pszStyleItem, "style_%s_legendurl",
-                                  pszStyle);
-                          msOWSPrintURLType(stream, &(GET_LAYER(map, i)->metadata),
-                                            "M", pszStyleItem, OWS_NOERR, NULL,
-                                            "LegendURL", NULL, " width=\"%s\"",
-                                            " height=\"%s\""," format=\"%s\"",
-                                            "            <OnlineResource "
-                                            "xlink:type=\"simple\""
-                                            " xlink:href=\"%s\"/>\n          ",
-                                            MS_FALSE, MS_FALSE, MS_FALSE, 
-                                            MS_FALSE, MS_TRUE, NULL, NULL, 
-                                            NULL, NULL, NULL, "          ");
-                          free(pszStyleItem);
-                      }
-                  }
-
-                  msIO_fprintf( stream,"        </Style>\n" );
- 
-                  free(pszStyle);
-                  pszValue = strchr(pszValue, ',');
-                  if(pszValue)  
-                      pszValue++;
-              }
-              msIO_fprintf( stream, "      </StyleList>\n");
+            msIO_fprintf( stream, "        <Style>\n" );
+
+          /* Write SLDURL if it is in the metadata */
+          pszStyleItem = (char*)malloc(strlen(pszStyle)+10+10);
+          sprintf(pszStyleItem, "wms_style_%s_sld", pszStyle);
+          if(msLookupHashTable(&(GET_LAYER(map, i)->metadata),
+                               pszStyleItem) != NULL) {
+            msIO_fprintf(stream, "          <SLD>\n");
+            msOWSPrintEncodeMetadata(stream,
+                                     &(GET_LAYER(map, i)->metadata),
+                                     NULL, pszStyleItem,
+                                     OWS_NOERR,
+                                     "            <OnlineResource xlink:type=\"simple\" xlink:href=\"%s\"/>\n",
+                                     NULL);
+            msIO_fprintf(stream, "          </SLD>\n");
+            free(pszStyleItem);
+          } else {
+            /* If the URL is not there, check for SLDBody */
+            sprintf(pszStyleItem, "wms_style_%s_sld_body", pszStyle);
+            if(msLookupHashTable(&(GET_LAYER(map, i)->metadata),
+                                 pszStyleItem) != NULL) {
+              msIO_fprintf(stream, "          <SLD>\n");
+              msOWSPrintMetadata(stream,&(GET_LAYER(map, i)->metadata),
+                                 NULL, pszStyleItem, OWS_NOERR,
+                                 "            %s\n", NULL);
+              msIO_fprintf(stream, "          </SLD>\n");
+              free(pszStyleItem);
+            } else {
+              /* If the SLD is not specified, then write the */
+              /* name, Title and LegendURL */
+              free(pszStyleItem);
+              /* Name */
+              pszEncodedVal = msEncodeHTMLEntities(pszStyle);
+              msIO_fprintf(stream, "          <Name>%s</Name>\n",
+                           pszEncodedVal);
+              msFree(pszEncodedVal);
+              pszStyleItem = (char*)malloc(strlen(pszStyle)+10+8);
+              sprintf(pszStyleItem, "wms_style_%s_title",pszStyle);
+              /* Title */
+              msOWSPrintEncodeMetadata(stream,
+                                       &(GET_LAYER(map, i)->metadata),
+                                       NULL, pszStyleItem,
+                                       OWS_NOERR,
+                                       "          <Title>%s</Title>\n",
+                                       NULL);
+              free(pszStyleItem);
+
+              /* LegendURL */
+              pszStyleItem = (char*)malloc(strlen(pszStyle)+10+20);
+              sprintf(pszStyleItem, "style_%s_legendurl",
+                      pszStyle);
+              msOWSPrintURLType(stream, &(GET_LAYER(map, i)->metadata),
+                                "M", pszStyleItem, OWS_NOERR, NULL,
+                                "LegendURL", NULL, " width=\"%s\"",
+                                " height=\"%s\""," format=\"%s\"",
+                                "            <OnlineResource "
+                                "xlink:type=\"simple\""
+                                " xlink:href=\"%s\"/>\n          ",
+                                MS_FALSE, MS_FALSE, MS_FALSE,
+                                MS_FALSE, MS_TRUE, NULL, NULL,
+                                NULL, NULL, NULL, "          ");
+              free(pszStyleItem);
+            }
           }
 
-          /* Dimension element */;
-          pszCurrent = NULL;
-
-          pszValue = msLookupHashTable(&(GET_LAYER(map, i)->metadata), 
-                                       "wms_dimensionlist");
-          pszCurrent = msLookupHashTable(&(GET_LAYER(map, i)->metadata), 
-                                         "wms_dimension");
-          while(pszValue != NULL)
-          {
-              /* Extract the dimension name from the list */
-              pszDimension = msStrdup(pszValue);
-              pszChar = strchr(pszDimension, ',');
-              if(pszChar != NULL)
-                  pszDimension[pszChar - pszDimension] = '\0';
-              if(strcasecmp(pszDimension, "") == 0)
-              {
-                  free(pszDimension);
-                  pszValue = strchr(pszValue, ',');
-                  if(pszValue)  
-                      pszValue++;
-                  continue;
-              }
-
-              /* From the dimension list, extract the required dimension */
-              msOWSGetDimensionInfo(GET_LAYER(map, i), pszDimension, 
-                                    &pszDimUserValue, &pszDimUnits, 
-                                    &pszDimDefault, &pszDimNearValue, 
-                                    &pszDimUnitSymbol, &pszDimMultiValue);
-
-              if(pszDimUserValue == NULL || pszDimUnits == NULL || 
-                 pszDimUnitSymbol == NULL)
-              {
-                  free(pszDimension);
-                  pszValue = strchr(pszValue, ',');
-                  if(pszValue)  
-                      pszValue++;
-                  continue;
-              }
-
-              if(!bDimensionList)
-              {
-                  bDimensionList = 1;
-                  msIO_fprintf( stream, "      <DimensionList>\n");
-              }
-
-              /* name */
-              msIO_fprintf( stream, "        <Dimension name=\"%s\"", 
-                            pszDimension);
-              /* units */
-              msIO_fprintf( stream, " units=\"%s\"",      pszDimUnits);
-              /* unitSymbol */
-              msIO_fprintf( stream, " unitSymbol=\"%s\"", pszDimUnitSymbol);
-              /* userValue */
-              msIO_fprintf( stream, " userValue=\"%s\"",  pszDimUserValue);
-              /* default */
-              if(pszDimDefault)
-                  msIO_fprintf( stream, " default=\"%s\"", pszDimDefault);
-              /* multipleValues */
-              if(pszDimMultiValue)
-                  msIO_fprintf(stream, " multipleValues=\"%s\"", 
-                               pszDimMultiValue);
-              /* nearestValue */
-              if(pszDimNearValue)
-                  msIO_fprintf( stream," nearestValue=\"%s\"",pszDimNearValue);
-      
-              if(pszCurrent && strcasecmp(pszDimension, pszCurrent) == 0)
-                  msIO_fprintf( stream, " current=\"1\"");
-
-              msIO_fprintf( stream, "/>\n");
-
-              free(pszDimension);
-              pszValue = strchr(pszValue, ',');
-              if(pszValue)  
-                  pszValue++;
-          }
+          msIO_fprintf( stream,"        </Style>\n" );
 
-          if(bDimensionList)
-          {
-              msIO_fprintf( stream, "      </DimensionList>\n");
-              bDimensionList = 0;
-          }
+          free(pszStyle);
+          pszValue = strchr(pszValue, ',');
+          if(pszValue)
+            pszValue++;
+        }
+        msIO_fprintf( stream, "      </StyleList>\n");
+      }
 
-          msIO_fprintf(stream, "    </Layer>\n");
+      /* Dimension element */;
+      pszCurrent = NULL;
+
+      pszValue = msLookupHashTable(&(GET_LAYER(map, i)->metadata),
+                                   "wms_dimensionlist");
+      pszCurrent = msLookupHashTable(&(GET_LAYER(map, i)->metadata),
+                                     "wms_dimension");
+      while(pszValue != NULL) {
+        /* Extract the dimension name from the list */
+        pszDimension = msStrdup(pszValue);
+        pszChar = strchr(pszDimension, ',');
+        if(pszChar != NULL)
+          pszDimension[pszChar - pszDimension] = '\0';
+        if(strcasecmp(pszDimension, "") == 0) {
+          free(pszDimension);
+          pszValue = strchr(pszValue, ',');
+          if(pszValue)
+            pszValue++;
+          continue;
+        }
+
+        /* From the dimension list, extract the required dimension */
+        msOWSGetDimensionInfo(GET_LAYER(map, i), pszDimension,
+                              &pszDimUserValue, &pszDimUnits,
+                              &pszDimDefault, &pszDimNearValue,
+                              &pszDimUnitSymbol, &pszDimMultiValue);
+
+        if(pszDimUserValue == NULL || pszDimUnits == NULL ||
+            pszDimUnitSymbol == NULL) {
+          free(pszDimension);
+          pszValue = strchr(pszValue, ',');
+          if(pszValue)
+            pszValue++;
+          continue;
+        }
+
+        if(!bDimensionList) {
+          bDimensionList = 1;
+          msIO_fprintf( stream, "      <DimensionList>\n");
+        }
+
+        /* name */
+        msIO_fprintf( stream, "        <Dimension name=\"%s\"",
+                      pszDimension);
+        /* units */
+        msIO_fprintf( stream, " units=\"%s\"",      pszDimUnits);
+        /* unitSymbol */
+        msIO_fprintf( stream, " unitSymbol=\"%s\"", pszDimUnitSymbol);
+        /* userValue */
+        msIO_fprintf( stream, " userValue=\"%s\"",  pszDimUserValue);
+        /* default */
+        if(pszDimDefault)
+          msIO_fprintf( stream, " default=\"%s\"", pszDimDefault);
+        /* multipleValues */
+        if(pszDimMultiValue)
+          msIO_fprintf(stream, " multipleValues=\"%s\"",
+                       pszDimMultiValue);
+        /* nearestValue */
+        if(pszDimNearValue)
+          msIO_fprintf( stream," nearestValue=\"%s\"",pszDimNearValue);
+
+        if(pszCurrent && strcasecmp(pszDimension, pszCurrent) == 0)
+          msIO_fprintf( stream, " current=\"1\"");
+
+        msIO_fprintf( stream, "/>\n");
+
+        free(pszDimension);
+        pszValue = strchr(pszValue, ',');
+        if(pszValue)
+          pszValue++;
+      }
+
+      if(bDimensionList) {
+        msIO_fprintf( stream, "      </DimensionList>\n");
+        bDimensionList = 0;
       }
+
+      msIO_fprintf(stream, "    </Layer>\n");
+    }
   }
 
   /* Close layer list */
   msIO_fprintf(stream, "  </LayerList>\n");
   /* Close Map Context */
 
-  if(nVersion >= OWS_1_0_0)
-  {
-      msIO_fprintf(stream, "</ViewContext>\n");
-  }
-  else if(nVersion >= OWS_0_1_7)
-  {
-      msIO_fprintf(stream, "</View_Context>\n");
-  }
-  else /* 0.1.4 */
-  {
-      msIO_fprintf(stream, "</WMS_Viewer_Context>\n");
+  if(nVersion >= OWS_1_0_0) {
+    msIO_fprintf(stream, "</ViewContext>\n");
+  } else if(nVersion >= OWS_0_1_7) {
+    msIO_fprintf(stream, "</View_Context>\n");
+  } else { /* 0.1.4 */
+    msIO_fprintf(stream, "</WMS_Viewer_Context>\n");
   }
 
   return MS_SUCCESS;
 #else
-  msSetError(MS_MAPCONTEXTERR, 
+  msSetError(MS_MAPCONTEXTERR,
              "Not implemented since Map Context is not enabled.",
              "msWriteMapContext()");
   return MS_FAILURE;
diff --git a/mapcopy.c b/mapcopy.c
index 0191095..f531616 100644
--- a/mapcopy.c
+++ b/mapcopy.c
@@ -5,14 +5,14 @@
  * Purpose: Functions to allow copying/cloning of maps
  * Author:  Sean Gillies, sgillies at frii.com
  *
- * Notes: 
- * These functions are not in mapfile.c because that file is 
+ * Notes:
+ * These functions are not in mapfile.c because that file is
  * cumbersome enough as it is.  There is agreement that this code and
- * that in mapfile.c should eventually be split up by object into 
- * mapobj.c, layerobj.c, etc.  Or something like that.  
+ * that in mapfile.c should eventually be split up by object into
+ * mapobj.c, layerobj.c, etc.  Or something like that.
  *
  * Unit tests are written in Python using PyUnit and are in
- * mapscript/python/tests/testCopyMap.py.  The tests can be 
+ * mapscript/python/tests/testCopyMap.py.  The tests can be
  * executed from the python directory as
  *
  *   python2 tests/testCopyMap.py
@@ -29,7 +29,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -45,7 +45,7 @@
 #include "mapserver.h"
 #include "mapsymbol.h"
 
-MS_CVSID("$Id$")
+
 
 #include "mapcopy.h"
 
@@ -55,24 +55,26 @@ MS_CVSID("$Id$")
  * Copy a projectionObj                                                *
  **********************************************************************/
 
-int msCopyProjection(projectionObj *dst, projectionObj *src) {
+int msCopyProjection(projectionObj *dst, projectionObj *src)
+{
 
 #ifdef USE_PROJ
-    int i;
-    
-    MS_COPYSTELEM(numargs);
+  int i;
 
-    for (i = 0; i < dst->numargs; i++) {
-        /* Our destination consists of unallocated pointers */
-        dst->args[i] = msStrdup(src->args[i]);
-    }
-    if (dst->numargs != 0) {
-        if (msProcessProjection(dst) != MS_SUCCESS)
-            return MS_FAILURE;
+  MS_COPYSTELEM(numargs);
 
-    }
+  for (i = 0; i < dst->numargs; i++) {
+    /* Our destination consists of unallocated pointers */
+    dst->args[i] = msStrdup(src->args[i]);
+  }
+  if (dst->numargs != 0) {
+    if (msProcessProjection(dst) != MS_SUCCESS)
+      return MS_FAILURE;
+
+  }
 #endif
-    return MS_SUCCESS;
+  MS_COPYSTELEM(wellknownprojection);
+  return MS_SUCCESS;
 }
 
 /***********************************************************************
@@ -80,16 +82,17 @@ int msCopyProjection(projectionObj *dst, projectionObj *src) {
  *                                                                     *
  * Copy a lineObj, using msCopyPoint()                                 *
  **********************************************************************/
-int msCopyLine(lineObj *dst, lineObj *src) {
-  
-    int i;
+int msCopyLine(lineObj *dst, lineObj *src)
+{
 
-    dst->numpoints = src->numpoints;
-    for (i = 0; i < dst->numpoints; i++) {
-        MS_COPYPOINT(&(dst->point[i]), &(src->point[i]));
-    }
+  int i;
+
+  dst->numpoints = src->numpoints;
+  for (i = 0; i < dst->numpoints; i++) {
+    MS_COPYPOINT(&(dst->point[i]), &(src->point[i]));
+  }
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 /***********************************************************************
@@ -126,15 +129,16 @@ int msCopyShapeObj(shapeObj *dst, shapeObj *src) {
  * Copy an itemObj                                                     *
  **********************************************************************/
 
-int msCopyItem(itemObj *dst, itemObj *src) {
-    
-    MS_COPYSTRING(dst->name, src->name);
-    MS_COPYSTELEM(type);
-    MS_COPYSTELEM(index);
-    MS_COPYSTELEM(size);
-    MS_COPYSTELEM(numdecimals);
+int msCopyItem(itemObj *dst, itemObj *src)
+{
+
+  MS_COPYSTRING(dst->name, src->name);
+  MS_COPYSTELEM(type);
+  MS_COPYSTELEM(index);
+  MS_COPYSTELEM(size);
+  MS_COPYSTELEM(numdecimals);
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 /***********************************************************************
@@ -143,16 +147,17 @@ int msCopyItem(itemObj *dst, itemObj *src) {
  * Copy a hashTableObj, using msInsertHashTable()                      *
  **********************************************************************/
 
-int msCopyHashTable(hashTableObj *dst, hashTableObj *src) {
-    const char *key=NULL;
-    while (1) {
-        key = msNextKeyFromHashTable(src, key);
-        if (!key) 
-            break;
-        else 
-            msInsertHashTable(dst, key, msLookupHashTable(src, key));
-    }
-    return MS_SUCCESS;
+int msCopyHashTable(hashTableObj *dst, hashTableObj *src)
+{
+  const char *key=NULL;
+  while (1) {
+    key = msNextKeyFromHashTable(src, key);
+    if (!key)
+      break;
+    else
+      msInsertHashTable(dst, key, msLookupHashTable(src, key));
+  }
+  return MS_SUCCESS;
 }
 
 /***********************************************************************
@@ -164,18 +169,18 @@ int msCopyHashTable(hashTableObj *dst, hashTableObj *src) {
 int msCopyFontSet(fontSetObj *dst, fontSetObj *src, mapObj *map)
 {
 
-    MS_COPYSTRING(dst->filename, src->filename);
-    MS_COPYSTELEM(numfonts);
-    if (&(src->fonts)) {
-        /* if (!dst->fonts) */
-        /* dst->fonts = msCreateHashTable(); */
-        if (msCopyHashTable(&(dst->fonts), &(src->fonts)) != MS_SUCCESS)
-            return MS_FAILURE;
-    }
+  MS_COPYSTRING(dst->filename, src->filename);
+  MS_COPYSTELEM(numfonts);
+  if (&(src->fonts)) {
+    /* if (!dst->fonts) */
+    /* dst->fonts = msCreateHashTable(); */
+    if (msCopyHashTable(&(dst->fonts), &(src->fonts)) != MS_SUCCESS)
+      return MS_FAILURE;
+  }
 
-    dst->map = map;
+  dst->map = map;
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 /***********************************************************************
@@ -186,11 +191,11 @@ int msCopyFontSet(fontSetObj *dst, fontSetObj *src, mapObj *map)
 
 int msCopyExpression(expressionObj *dst, expressionObj *src)
 {
-    MS_COPYSTRING(dst->string, src->string);
-    MS_COPYSTELEM(type);
-    dst->compiled = MS_FALSE;
+  MS_COPYSTRING(dst->string, src->string);
+  MS_COPYSTELEM(type);
+  dst->compiled = MS_FALSE;
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 /***********************************************************************
@@ -201,30 +206,30 @@ int msCopyExpression(expressionObj *dst, expressionObj *src)
 
 int msCopyJoin(joinObj *dst, joinObj *src)
 {
-    MS_COPYSTRING(dst->name, src->name);
+  MS_COPYSTRING(dst->name, src->name);
 
-    /* makes no sense to copy the items or values
-       since they are runtime additions to the mapfile */
+  /* makes no sense to copy the items or values
+     since they are runtime additions to the mapfile */
 
-    MS_COPYSTRING(dst->table, src->table);
-    MS_COPYSTRING(dst->from, src->from);
-    MS_COPYSTRING(dst->to, src->to);
-    MS_COPYSTRING(dst->header, src->header);
+  MS_COPYSTRING(dst->table, src->table);
+  MS_COPYSTRING(dst->from, src->from);
+  MS_COPYSTRING(dst->to, src->to);
+  MS_COPYSTRING(dst->header, src->header);
 #ifndef __cplusplus
-    MS_COPYSTRING(dst->template, src->template);
+  MS_COPYSTRING(dst->template, src->template);
 #else
-    MS_COPYSTRING(dst->_template, src->_template);
+  MS_COPYSTRING(dst->_template, src->_template);
 #endif
-    MS_COPYSTRING(dst->footer, src->footer);
-    dst->type = src->type;
-    MS_COPYSTRING(dst->connection, src->connection);
+  MS_COPYSTRING(dst->footer, src->footer);
+  dst->type = src->type;
+  MS_COPYSTRING(dst->connection, src->connection);
 
-    MS_COPYSTELEM(connectiontype);
+  MS_COPYSTELEM(connectiontype);
 
-    /* TODO: need to handle joininfo (probably should be just set to NULL) */
-    dst->joininfo = NULL;
+  /* TODO: need to handle joininfo (probably should be just set to NULL) */
+  dst->joininfo = NULL;
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 /***********************************************************************
@@ -233,24 +238,65 @@ int msCopyJoin(joinObj *dst, joinObj *src)
  * Copy a queryMapObj, using msCopyColor()                             *
  **********************************************************************/
 
-int msCopyQueryMap(queryMapObj *dst, queryMapObj *src) 
+int msCopyQueryMap(queryMapObj *dst, queryMapObj *src)
 {
-    MS_COPYSTELEM(height);
-    MS_COPYSTELEM(width);
-    MS_COPYSTELEM(status);
-    MS_COPYSTELEM(style);
-    MS_COPYCOLOR(&(dst->color), &(src->color));
+  MS_COPYSTELEM(height);
+  MS_COPYSTELEM(width);
+  MS_COPYSTELEM(status);
+  MS_COPYSTELEM(style);
+  MS_COPYCOLOR(&(dst->color), &(src->color));
 
   return MS_SUCCESS;
 }
 
+
+/***********************************************************************
+ * msCopyLeader()                                                      *
+ *                                                                     *
+ * Copy a labelLeaderObj, using msCopyStyle()                          *
+ **********************************************************************/
+
+int msCopyLeader(labelLeaderObj *dst, labelLeaderObj *src)
+{
+  int i;
+  MS_COPYSTELEM(gridstep);
+  MS_COPYSTELEM(maxdistance);
+  /*
+   ** now the styles
+   */
+
+  /* free any previous styles on the dst label */
+  for(i=0; i<dst->numstyles; i++) { /* each style */
+    if (dst->styles[i]!=NULL) {
+      if( freeStyle(dst->styles[i]) == MS_SUCCESS ) msFree(dst->styles[i]);
+    }
+  }
+  msFree(dst->styles);
+  dst->numstyles = 0;
+
+  for (i = 0; i < src->numstyles; i++) {
+    if (msGrowLeaderStyles(dst) == NULL)
+      return MS_FAILURE;
+    if (initStyle(dst->styles[i]) != MS_SUCCESS) {
+      msSetError(MS_MEMERR, "Failed to init style.", "msCopyLabel()");
+      return MS_FAILURE;
+    }
+    if (msCopyStyle(dst->styles[i], src->styles[i]) != MS_SUCCESS) {
+      msSetError(MS_MEMERR, "Failed to copy style.", "msCopyLabel()");
+      return MS_FAILURE;
+    }
+    dst->numstyles++;
+  }
+  return MS_SUCCESS;
+}
+
 /***********************************************************************
  * msCopyLabel()                                                       *
  *                                                                     *
  * Copy a labelObj, using msCopyColor() and msCopyStyle()              *
  **********************************************************************/
 
-int msCopyLabel(labelObj *dst, labelObj *src) 
+int msCopyLabel(labelObj *dst, labelObj *src)
 {
   int i;
 
@@ -277,14 +323,14 @@ int msCopyLabel(labelObj *dst, labelObj *src)
   MS_COPYSTELEM(offsetx);
   MS_COPYSTELEM(offsety);
   MS_COPYSTELEM(angle);
-  MS_COPYSTELEM(anglemode);    
+  MS_COPYSTELEM(anglemode);
   MS_COPYSTELEM(buffer);
   MS_COPYSTELEM(antialias);
   MS_COPYSTELEM(wrap);
   MS_COPYSTELEM(align);
   MS_COPYSTELEM(maxlength);
   MS_COPYSTELEM(minfeaturesize);
-    
+
   MS_COPYSTELEM(minscaledenom);
   MS_COPYSTELEM(maxscaledenom);
 
@@ -298,13 +344,14 @@ int msCopyLabel(labelObj *dst, labelObj *src)
   MS_COPYSTRING(dst->encoding, src->encoding);
 
   MS_COPYSTELEM(outlinewidth);
+  MS_COPYSTELEM(space_size_10);
 
-  /* 
-  ** now the styles 
+  /*
+  ** now the styles
   */
 
   /* free any previous styles on the dst label */
-  for(i=0;i<dst->numstyles;i++) { /* each style */
+  for(i=0; i<dst->numstyles; i++) { /* each style */
     if (dst->styles[i]!=NULL) {
       if( freeStyle(dst->styles[i]) == MS_SUCCESS ) msFree(dst->styles[i]);
     }
@@ -326,6 +373,13 @@ int msCopyLabel(labelObj *dst, labelObj *src)
     dst->numstyles++;
   }
 
+  /*
+  ** other book keeping information (RFC77 TODO)
+  */
+  MS_COPYSTELEM(status);
+  MS_COPYSTRING(dst->annotext, src->annotext);
+
+  msCopyLeader(&(dst->leader),&(src->leader));
 
   return MS_SUCCESS;
 }
@@ -337,41 +391,41 @@ int msCopyLabel(labelObj *dst, labelObj *src)
  * msCopyHashTable()                                                   *
  **********************************************************************/
 
-int msCopyWeb(webObj *dst, webObj *src, mapObj *map) 
+int msCopyWeb(webObj *dst, webObj *src, mapObj *map)
 {
 
-    MS_COPYSTRING(dst->log, src->log);
-    MS_COPYSTRING(dst->imagepath, src->imagepath);
-    MS_COPYSTRING(dst->imageurl, src->imageurl);
-    dst->map = map;
+  MS_COPYSTRING(dst->log, src->log);
+  MS_COPYSTRING(dst->imagepath, src->imagepath);
+  MS_COPYSTRING(dst->imageurl, src->imageurl);
+  dst->map = map;
 #ifndef __cplusplus
-    MS_COPYSTRING(dst->template, src->template);
+  MS_COPYSTRING(dst->template, src->template);
 #else
-    MS_COPYSTRING(dst->_template, src->_template);
+  MS_COPYSTRING(dst->_template, src->_template);
 #endif
-    MS_COPYSTRING(dst->header, src->header);
-    MS_COPYSTRING(dst->footer, src->footer);
-    MS_COPYSTRING(dst->empty, src->empty);
-    MS_COPYSTRING(dst->error, src->error);
-
-    MS_COPYRECT(&(dst->extent), &(src->extent));
-
-    MS_COPYSTELEM(minscaledenom);
-    MS_COPYSTELEM(maxscaledenom);
-    MS_COPYSTRING(dst->mintemplate, src->mintemplate);
-    MS_COPYSTRING(dst->maxtemplate, src->maxtemplate);
-
-    if (&(src->metadata)) {
-        /* dst->metadata = msCreateHashTable(); */
-        if (msCopyHashTable(&(dst->metadata), &(src->metadata)) != MS_SUCCESS)
-            return MS_FAILURE;
-    }
+  MS_COPYSTRING(dst->header, src->header);
+  MS_COPYSTRING(dst->footer, src->footer);
+  MS_COPYSTRING(dst->empty, src->empty);
+  MS_COPYSTRING(dst->error, src->error);
+
+  MS_COPYRECT(&(dst->extent), &(src->extent));
+
+  MS_COPYSTELEM(minscaledenom);
+  MS_COPYSTELEM(maxscaledenom);
+  MS_COPYSTRING(dst->mintemplate, src->mintemplate);
+  MS_COPYSTRING(dst->maxtemplate, src->maxtemplate);
+
+  if (&(src->metadata)) {
+    /* dst->metadata = msCreateHashTable(); */
+    if (msCopyHashTable(&(dst->metadata), &(src->metadata)) != MS_SUCCESS)
+      return MS_FAILURE;
+  }
 
-    MS_COPYSTRING(dst->queryformat, src->queryformat);
-    MS_COPYSTRING(dst->legendformat, src->legendformat);
-    MS_COPYSTRING(dst->browseformat, src->browseformat);
+  MS_COPYSTRING(dst->queryformat, src->queryformat);
+  MS_COPYSTRING(dst->legendformat, src->legendformat);
+  MS_COPYSTRING(dst->browseformat, src->browseformat);
 
-    return MS_SUCCESS ;
+  return MS_SUCCESS ;
 }
 
 /***********************************************************************
@@ -380,7 +434,7 @@ int msCopyWeb(webObj *dst, webObj *src, mapObj *map)
  * Copy a styleObj, using msCopyColor()                                *
  **********************************************************************/
 
-int msCopyStyle(styleObj *dst, styleObj *src) 
+int msCopyStyle(styleObj *dst, styleObj *src)
 {
   int i;
 
@@ -390,45 +444,46 @@ int msCopyStyle(styleObj *dst, styleObj *src)
   }
   MS_COPYSTELEM(numbindings);
 
-    MS_COPYCOLOR(&(dst->color), &(src->color));
-    MS_COPYCOLOR(&(dst->outlinecolor),&(src->outlinecolor));
-    MS_COPYCOLOR(&(dst->backgroundcolor), &(src->backgroundcolor));
-   
-    MS_COPYCOLOR(&(dst->mincolor), &(src->mincolor));
-    MS_COPYCOLOR(&(dst->maxcolor), &(src->maxcolor));
-
-    MS_COPYSTRING(dst->symbolname, src->symbolname);
-    MS_COPYSTELEM(patternlength);
-    for(i=0;i<src->patternlength;i++)
-        dst->pattern[i]=src->pattern[i];
-    MS_COPYSTELEM(gap);
-    MS_COPYSTELEM(linejoin);
-    MS_COPYSTELEM(linejoinmaxsize);
-    MS_COPYSTELEM(linecap);
-    MS_COPYSTELEM(symbol);
-    MS_COPYSTELEM(size);
-    MS_COPYSTELEM(minsize);
-    MS_COPYSTELEM(maxsize);
-    MS_COPYSTELEM(width);
-    MS_COPYSTELEM(minwidth);
-    MS_COPYSTELEM(maxwidth);
-    MS_COPYSTELEM(offsetx);
-    MS_COPYSTELEM(offsety);
-    MS_COPYSTELEM(antialias);
-    MS_COPYSTELEM(angle);
-    MS_COPYSTELEM(minvalue);
-    MS_COPYSTELEM(maxvalue);
-    MS_COPYSTELEM(opacity);
-    MS_COPYSTRING(dst->_geomtransform.string, src->_geomtransform.string);
-    MS_COPYSTELEM(_geomtransform.type);
-    MS_COPYSTRING(dst->rangeitem, src->rangeitem);
-    MS_COPYSTELEM(rangeitemindex);
-    MS_COPYSTELEM(outlinewidth);
-    MS_COPYSTELEM(minscaledenom);
-    MS_COPYSTELEM(maxscaledenom);
-    /* TODO: add copy for bindings */
-
-    return MS_SUCCESS;
+  MS_COPYCOLOR(&(dst->color), &(src->color));
+  MS_COPYCOLOR(&(dst->outlinecolor),&(src->outlinecolor));
+  MS_COPYCOLOR(&(dst->backgroundcolor), &(src->backgroundcolor));
+
+  MS_COPYCOLOR(&(dst->mincolor), &(src->mincolor));
+  MS_COPYCOLOR(&(dst->maxcolor), &(src->maxcolor));
+
+  MS_COPYSTRING(dst->symbolname, src->symbolname);
+  MS_COPYSTELEM(patternlength);
+  for(i=0; i<src->patternlength; i++)
+    dst->pattern[i]=src->pattern[i];
+  MS_COPYSTELEM(initialgap);
+  MS_COPYSTELEM(gap);
+  MS_COPYSTELEM(linejoin);
+  MS_COPYSTELEM(linejoinmaxsize);
+  MS_COPYSTELEM(linecap);
+  MS_COPYSTELEM(symbol);
+  MS_COPYSTELEM(size);
+  MS_COPYSTELEM(minsize);
+  MS_COPYSTELEM(maxsize);
+  MS_COPYSTELEM(width);
+  MS_COPYSTELEM(minwidth);
+  MS_COPYSTELEM(maxwidth);
+  MS_COPYSTELEM(offsetx);
+  MS_COPYSTELEM(offsety);
+  MS_COPYSTELEM(antialias);
+  MS_COPYSTELEM(angle);
+  MS_COPYSTELEM(minvalue);
+  MS_COPYSTELEM(maxvalue);
+  MS_COPYSTELEM(opacity);
+  MS_COPYSTRING(dst->_geomtransform.string, src->_geomtransform.string);
+  MS_COPYSTELEM(_geomtransform.type);
+  MS_COPYSTRING(dst->rangeitem, src->rangeitem);
+  MS_COPYSTELEM(rangeitemindex);
+  MS_COPYSTELEM(outlinewidth);
+  MS_COPYSTELEM(minscaledenom);
+  MS_COPYSTELEM(maxscaledenom);
+  /* TODO: add copy for bindings */
+
+  return MS_SUCCESS;
 }
 
 /***********************************************************************
@@ -438,102 +493,114 @@ int msCopyStyle(styleObj *dst, styleObj *src)
  * msCopyLabel(), msCreateHashTable(), msCopyHashTable()               *
  **********************************************************************/
 
-int msCopyClass(classObj *dst, classObj *src, layerObj *layer) 
+int msCopyClass(classObj *dst, classObj *src, layerObj *layer)
 {
-    int i, return_value;
+  int i, return_value;
 
-    return_value = msCopyExpression(&(dst->expression),&(src->expression));
-    if (return_value != MS_SUCCESS) {
-        msSetError(MS_MEMERR, "Failed to copy expression.", "msCopyClass()");
-        return MS_FAILURE;
-    }
+  return_value = msCopyExpression(&(dst->expression),&(src->expression));
+  if (return_value != MS_SUCCESS) {
+    msSetError(MS_MEMERR, "Failed to copy expression.", "msCopyClass()");
+    return MS_FAILURE;
+  }
 
-    MS_COPYSTELEM(status);
+  MS_COPYSTELEM(status);
 
-    /* free any previous styles on the dst layer */
-    for(i=0;i<dst->numstyles;i++) { /* each style */
-      if (dst->styles[i]!=NULL) {
-    	if( freeStyle(dst->styles[i]) == MS_SUCCESS ) {
-          msFree(dst->styles[i]);
-	}
+  /* free any previous styles on the dst layer */
+  for(i=0; i<dst->numstyles; i++) { /* each style */
+    if (dst->styles[i]!=NULL) {
+      if( freeStyle(dst->styles[i]) == MS_SUCCESS ) {
+        msFree(dst->styles[i]);
       }
     }
-    msFree(dst->styles);
-    dst->numstyles = 0;
-
-    for (i = 0; i < src->numstyles; i++) {
-        if (msGrowClassStyles(dst) == NULL)
-            return MS_FAILURE;
-        if (initStyle(dst->styles[i]) != MS_SUCCESS) {
-            msSetError(MS_MEMERR, "Failed to init style.", "msCopyClass()");
-            return MS_FAILURE;
-        }
-        if (msCopyStyle(dst->styles[i], src->styles[i]) != MS_SUCCESS) {
-            msSetError(MS_MEMERR, "Failed to copy style.", "msCopyClass()");
-            return MS_FAILURE;
-        }
-
-        dst->numstyles++;
-    }
+  }
+  msFree(dst->styles);
+  dst->numstyles = 0;
 
-    if (msCopyLabel(&(dst->label), &(src->label)) != MS_SUCCESS) {
-        msSetError(MS_MEMERR, "Failed to copy label.", "msCopyClass()");
-        return MS_FAILURE;
+  for (i = 0; i < src->numstyles; i++) {
+    if (msGrowClassStyles(dst) == NULL)
+      return MS_FAILURE;
+    if (initStyle(dst->styles[i]) != MS_SUCCESS) {
+      msSetError(MS_MEMERR, "Failed to init style.", "msCopyClass()");
+      return MS_FAILURE;
+    }
+    if (msCopyStyle(dst->styles[i], src->styles[i]) != MS_SUCCESS) {
+      msSetError(MS_MEMERR, "Failed to copy style.", "msCopyClass()");
+      return MS_FAILURE;
     }
 
-    MS_COPYSTRING(dst->keyimage, src->keyimage);
-    MS_COPYSTRING(dst->name, src->name);
-    MS_COPYSTRING(dst->title, src->title);
-    MS_COPYSTRING(dst->group, src->group);
-    
-    if (msCopyExpression(&(dst->text), &(src->text)) != MS_SUCCESS) {
-        msSetError(MS_MEMERR, "Failed to copy text.", "msCopyClass()");
-        return MS_FAILURE;
+    dst->numstyles++;
+  }
+
+  for (i=0; i<src->numlabels; i++) {
+    if (msGrowClassLabels(dst) == NULL)
+      return MS_FAILURE;
+    initLabel(dst->labels[i]);
+    if (msCopyLabel(dst->labels[i], src->labels[i]) != MS_SUCCESS) {
+      msSetError(MS_MEMERR, "Failed to copy label.", "msCopyClass()");
+      return MS_FAILURE;
     }
 
+    dst->numlabels++;
+  }
+  MS_COPYSTELEM(numlabels);
+
+  msCopyLeader(&(dst->leader),&(src->leader));
+
+  MS_COPYSTRING(dst->keyimage, src->keyimage);
+  MS_COPYSTRING(dst->name, src->name);
+  MS_COPYSTRING(dst->title, src->title);
+  MS_COPYSTRING(dst->group, src->group);
+
+  if (msCopyExpression(&(dst->text), &(src->text)) != MS_SUCCESS) {
+    msSetError(MS_MEMERR, "Failed to copy text.", "msCopyClass()");
+    return MS_FAILURE;
+  }
+
 #ifndef __cplusplus
-    MS_COPYSTRING(dst->template, src->template);
+  MS_COPYSTRING(dst->template, src->template);
 #else
-    MS_COPYSTRING(dst->_template, src->_template);
+  MS_COPYSTRING(dst->_template, src->_template);
 #endif
-    MS_COPYSTELEM(type);
+  MS_COPYSTELEM(type);
 
-    if (&(src->metadata) != NULL) {
-        /* dst->metadata = msCreateHashTable(); */
-        msCopyHashTable(&(dst->metadata), &(src->metadata));
-    }
+  if (&(src->metadata) != NULL) {
+    /* dst->metadata = msCreateHashTable(); */
+    msCopyHashTable(&(dst->metadata), &(src->metadata));
+  }
 
-    MS_COPYSTELEM(minscaledenom);
-    MS_COPYSTELEM(maxscaledenom);
-    MS_COPYSTELEM(layer);
-    MS_COPYSTELEM(debug);
+  MS_COPYSTELEM(minscaledenom);
+  MS_COPYSTELEM(maxscaledenom);
+  MS_COPYSTELEM(layer);
+  MS_COPYSTELEM(debug);
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
-int msCopyCluster(clusterObj *dst, clusterObj *src) 
+int msCopyCluster(clusterObj *dst, clusterObj *src)
 {
-    int return_value;
+  int return_value;
 
-    MS_COPYSTELEM(maxdistance);
-    MS_COPYSTELEM(buffer);
-    MS_COPYSTRING(dst->region, src->region);
-    
-    return_value = msCopyExpression(&(dst->group),&(src->group));
-    if (return_value != MS_SUCCESS) {
-        msSetError(MS_MEMERR, "Failed to copy cluster group.", "msCopyCluster()");
-        return MS_FAILURE;
-    }
+  MS_COPYSTELEM(maxdistance);
+  MS_COPYSTELEM(buffer);
+  MS_COPYSTRING(dst->region, src->region);
 
-    return_value = msCopyExpression(&(dst->filter),&(src->filter));
-    if (return_value != MS_SUCCESS) {
-        msSetError(MS_MEMERR, "Failed to copy cluster filter.", "msCopyCluster()");
-        return MS_FAILURE;
-    }
+  return_value = msCopyExpression(&(dst->group),&(src->group));
+  if (return_value != MS_SUCCESS) {
+    msSetError(MS_MEMERR, "Failed to copy cluster group.", "msCopyCluster()");
+    return MS_FAILURE;
+  }
 
-    return MS_SUCCESS;
+  return_value = msCopyExpression(&(dst->filter),&(src->filter));
+  if (return_value != MS_SUCCESS) {
+    msSetError(MS_MEMERR, "Failed to copy cluster filter.", "msCopyCluster()");
+    return MS_FAILURE;
+  }
+
+  return MS_SUCCESS;
 }
 
+#ifdef why_on_earth_would_you_copy_a_labelcache
+
 /***********************************************************************
  * msCopyLabelCacheMember()                                            *
  *                                                                     *
@@ -543,29 +610,32 @@ int msCopyCluster(clusterObj *dst, clusterObj *src)
  * make exact copies, this method might not get much use.              *
  **********************************************************************/
 
-int msCopyLabelCacheMember(labelCacheMemberObj *dst,
-                           labelCacheMemberObj *src)
+int msCopyLabelCacheMember(labelCacheMemberObj *dst, labelCacheMemberObj *src)
 {
-    int i;
+  int i;
 
-    MS_COPYSTRING(dst->text, src->text);
-    MS_COPYSTELEM(featuresize);
-    MS_COPYSTELEM(numstyles);
+  MS_COPYSTELEM(featuresize);
 
-    for (i = 0; i < dst->numstyles; i++) {
-        msCopyStyle(&(dst->styles[i]), &(src->styles[i]));
-    }
+  MS_COPYSTELEM(numstyles);
+  for (i = 0; i < dst->numstyles; i++) {
+    msCopyStyle(&(dst->styles[i]), &(src->styles[i]));
+  }
+
+  MS_COPYSTELEM(numlabels);
+  dst->labels = (labelObj *) msSmallMalloc(sizeof(labelObj)*dst->numlabels);
+  for (i = 0; i < dst->numlabels; i++) {
+    msCopyLabel(&(dst->labels[i]), &(src->labels[i]));
+  }
 
-    msCopyLabel(&(dst->label), &(src->label));
-    MS_COPYSTELEM(layerindex);
-    MS_COPYSTELEM(classindex);
-    MS_COPYSTELEM(tileindex);
-    MS_COPYSTELEM(shapeindex);
-    MS_COPYPOINT(&(dst->point), &(src->point));
-    /* msCopyShape(&(dst->poly), &(src->poly)); */
-    MS_COPYSTELEM(status);
+  MS_COPYSTELEM(layerindex);
+  MS_COPYSTELEM(classindex);
+  MS_COPYSTELEM(tileindex);
+  MS_COPYSTELEM(shapeindex);
+  MS_COPYPOINT(&(dst->point), &(src->point));
+  /* msCopyShape(&(dst->poly), &(src->poly)); */
+  MS_COPYSTELEM(status);
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 /***********************************************************************
@@ -575,80 +645,82 @@ int msCopyLabelCacheMember(labelCacheMemberObj *dst,
  **********************************************************************/
 
 int msCopyMarkerCacheMember(markerCacheMemberObj *dst,
-                            markerCacheMemberObj *src) 
-{  
-    MS_COPYSTELEM(id);
-  
-    /* msCopyShape(&(dst->poly), &(src->poly)); */
-    return MS_SUCCESS;
+                            markerCacheMemberObj *src)
+{
+  MS_COPYSTELEM(id);
+
+  /* msCopyShape(&(dst->poly), &(src->poly)); */
+  return MS_SUCCESS;
 }
 
 /***********************************************************************
  * msCopyLabelCacheSlot()                                                  *
  **********************************************************************/
 
-int msCopyLabelCacheSlot(labelCacheSlotObj *dst, labelCacheSlotObj *src) 
+int msCopyLabelCacheSlot(labelCacheSlotObj *dst, labelCacheSlotObj *src)
 {
-    int i;
+  int i;
 
-    for (i = 0; i < dst->numlabels; i++) {
-        msCopyLabelCacheMember(&(dst->labels[i]), &(src->labels[i]));
-    }
-    MS_COPYSTELEM(cachesize);
-    MS_COPYSTELEM(nummarkers);
-    for (i = 0; i < dst->nummarkers; i++) {
-        msCopyMarkerCacheMember(&(dst->markers[i]), &(src->markers[i]));
-    }
-    MS_COPYSTELEM(markercachesize);
+  for (i = 0; i < dst->numlabels; i++) {
+    msCopyLabelCacheMember(&(dst->labels[i]), &(src->labels[i]));
+  }
+  MS_COPYSTELEM(cachesize);
+  MS_COPYSTELEM(nummarkers);
+  for (i = 0; i < dst->nummarkers; i++) {
+    msCopyMarkerCacheMember(&(dst->markers[i]), &(src->markers[i]));
+  }
+  MS_COPYSTELEM(markercachesize);
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 /***********************************************************************
  * msCopyLabelCache()                                                  *
  **********************************************************************/
 
-int msCopyLabelCache(labelCacheObj *dst, labelCacheObj *src) 
+int msCopyLabelCache(labelCacheObj *dst, labelCacheObj *src)
 {
-    int p;
-    MS_COPYSTELEM(numlabels);
+  int p;
+  MS_COPYSTELEM(numlabels);
 
-    for (p=0; p<MS_MAX_LABEL_PRIORITY; p++) {
-        msCopyLabelCacheSlot(&(dst->slots[p]), &(src->slots[p]));
-    }
+  for (p=0; p<MS_MAX_LABEL_PRIORITY; p++) {
+    msCopyLabelCacheSlot(&(dst->slots[p]), &(src->slots[p]));
+  }
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
+#endif
+
 /***********************************************************************
  * msCopyResult()                                                      *
  **********************************************************************/
 
 int msCopyResult(resultObj *dst, resultObj *src)
 {
-    MS_COPYSTELEM(shapeindex);
-    MS_COPYSTELEM(tileindex);
-    MS_COPYSTELEM(classindex);
-    MS_COPYSTELEM(resultindex);
+  MS_COPYSTELEM(shapeindex);
+  MS_COPYSTELEM(tileindex);
+  MS_COPYSTELEM(classindex);
+  MS_COPYSTELEM(resultindex);
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 /***********************************************************************
  * msCopyResultCache()                                                 *
  **********************************************************************/
 
-int msCopyResultCache(resultCacheObj *dst, resultCacheObj *src) 
+int msCopyResultCache(resultCacheObj *dst, resultCacheObj *src)
 {
-    int i;
-    MS_COPYSTELEM(cachesize);
-    MS_COPYSTELEM(numresults);
-    for (i = 0; i < dst->numresults; i++) {
-        msCopyResult(&(dst->results[i]), &(src->results[i]));
-    }
-    MS_COPYRECT(&(dst->bounds), &(src->bounds));
+  int i;
+  MS_COPYSTELEM(cachesize);
+  MS_COPYSTELEM(numresults);
+  for (i = 0; i < dst->numresults; i++) {
+    msCopyResult(&(dst->results[i]), &(src->results[i]));
+  }
+  MS_COPYRECT(&(dst->bounds), &(src->bounds));
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 /***********************************************************************
@@ -662,27 +734,27 @@ int msCopyReferenceMap(referenceMapObj *dst, referenceMapObj *src,
                        mapObj *map)
 {
 
-    initReferenceMap(dst);
+  initReferenceMap(dst);
 
-    MS_COPYRECT(&(dst->extent), &(src->extent));
+  MS_COPYRECT(&(dst->extent), &(src->extent));
 
-    MS_COPYSTELEM(height);
-    MS_COPYSTELEM(width);
+  MS_COPYSTELEM(height);
+  MS_COPYSTELEM(width);
 
 
-    MS_COPYCOLOR(&(dst->color), &(src->color));
-    MS_COPYCOLOR(&(dst->outlinecolor),&(src->outlinecolor));
-    MS_COPYSTRING(dst->image, src->image);
+  MS_COPYCOLOR(&(dst->color), &(src->color));
+  MS_COPYCOLOR(&(dst->outlinecolor),&(src->outlinecolor));
+  MS_COPYSTRING(dst->image, src->image);
 
-    MS_COPYSTELEM(status);
-    MS_COPYSTELEM(marker);
-    MS_COPYSTRING(dst->markername, src->markername);
-    MS_COPYSTELEM(markersize);
-    MS_COPYSTELEM(minboxsize);
-    MS_COPYSTELEM(maxboxsize);
-    dst->map = map;
+  MS_COPYSTELEM(status);
+  MS_COPYSTELEM(marker);
+  MS_COPYSTRING(dst->markername, src->markername);
+  MS_COPYSTELEM(markersize);
+  MS_COPYSTELEM(minboxsize);
+  MS_COPYSTELEM(maxboxsize);
+  dst->map = map;
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 /***********************************************************************
@@ -695,33 +767,33 @@ int msCopyReferenceMap(referenceMapObj *dst, referenceMapObj *src,
 int msCopyScalebar(scalebarObj *dst, scalebarObj *src)
 {
 
-    initScalebar(dst);
+  initScalebar(dst);
 
-    MS_COPYCOLOR(&(dst->imagecolor), &(src->imagecolor));
-    MS_COPYSTELEM(height);
-    MS_COPYSTELEM(width);
-    MS_COPYSTELEM(style);
-    MS_COPYSTELEM(intervals);
+  MS_COPYCOLOR(&(dst->imagecolor), &(src->imagecolor));
+  MS_COPYSTELEM(height);
+  MS_COPYSTELEM(width);
+  MS_COPYSTELEM(style);
+  MS_COPYSTELEM(intervals);
 
-    if (msCopyLabel(&(dst->label), &(src->label)) != MS_SUCCESS) {
-        msSetError(MS_MEMERR, "Failed to copy label.","msCopyScalebar()");
-        return MS_FAILURE;
-    }
+  if (msCopyLabel(&(dst->label), &(src->label)) != MS_SUCCESS) {
+    msSetError(MS_MEMERR, "Failed to copy label.","msCopyScalebar()");
+    return MS_FAILURE;
+  }
 
-    MS_COPYCOLOR(&(dst->color), &(src->color));
-    MS_COPYCOLOR(&(dst->backgroundcolor), &(src->backgroundcolor));
+  MS_COPYCOLOR(&(dst->color), &(src->color));
+  MS_COPYCOLOR(&(dst->backgroundcolor), &(src->backgroundcolor));
 
-    MS_COPYCOLOR(&(dst->outlinecolor), &(src->outlinecolor));
+  MS_COPYCOLOR(&(dst->outlinecolor), &(src->outlinecolor));
 
-    MS_COPYSTELEM(units);
-    MS_COPYSTELEM(status);
-    MS_COPYSTELEM(position);
-    MS_COPYSTELEM(transparent);
-    MS_COPYSTELEM(interlace);
-    MS_COPYSTELEM(postlabelcache);
-    MS_COPYSTELEM(align);
+  MS_COPYSTELEM(units);
+  MS_COPYSTELEM(status);
+  MS_COPYSTELEM(position);
+  MS_COPYSTELEM(transparent);
+  MS_COPYSTELEM(interlace);
+  MS_COPYSTELEM(postlabelcache);
+  MS_COPYSTELEM(align);
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 /***********************************************************************
@@ -732,40 +804,40 @@ int msCopyScalebar(scalebarObj *dst, scalebarObj *src)
 
 int msCopyLegend(legendObj *dst, legendObj *src, mapObj *map)
 {
-    int return_value;
+  int return_value;
 
-    MS_COPYCOLOR(&(dst->imagecolor), &(src->imagecolor));
+  MS_COPYCOLOR(&(dst->imagecolor), &(src->imagecolor));
 
-    return_value = msCopyLabel(&(dst->label), &(src->label));
-    if (return_value != MS_SUCCESS) {
-        msSetError(MS_MEMERR, "Failed to copy label.",
-            "msCopyLegend()");
-        return MS_FAILURE;
-    }
+  return_value = msCopyLabel(&(dst->label), &(src->label));
+  if (return_value != MS_SUCCESS) {
+    msSetError(MS_MEMERR, "Failed to copy label.",
+               "msCopyLegend()");
+    return MS_FAILURE;
+  }
 
-    MS_COPYSTELEM(keysizex);
-    MS_COPYSTELEM(keysizey);
-    MS_COPYSTELEM(keyspacingx);
-    MS_COPYSTELEM(keyspacingy);
+  MS_COPYSTELEM(keysizex);
+  MS_COPYSTELEM(keysizey);
+  MS_COPYSTELEM(keyspacingx);
+  MS_COPYSTELEM(keyspacingy);
 
-    MS_COPYCOLOR(&(dst->outlinecolor),&(src->outlinecolor));
+  MS_COPYCOLOR(&(dst->outlinecolor),&(src->outlinecolor));
 
-    MS_COPYSTELEM(status);
-    MS_COPYSTELEM(height);
-    MS_COPYSTELEM(width);
-    MS_COPYSTELEM(position);
-    MS_COPYSTELEM(transparent);
-    MS_COPYSTELEM(interlace);
-    MS_COPYSTELEM(postlabelcache);
+  MS_COPYSTELEM(status);
+  MS_COPYSTELEM(height);
+  MS_COPYSTELEM(width);
+  MS_COPYSTELEM(position);
+  MS_COPYSTELEM(transparent);
+  MS_COPYSTELEM(interlace);
+  MS_COPYSTELEM(postlabelcache);
 
 #ifndef __cplusplus
-    MS_COPYSTRING(dst->template, src->template);
+  MS_COPYSTRING(dst->template, src->template);
 #else
-    MS_COPYSTRING(dst->_template, src->_template);
+  MS_COPYSTRING(dst->_template, src->_template);
 #endif
-    dst->map = map;
+  dst->map = map;
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 /***********************************************************************
@@ -780,147 +852,147 @@ int msCopyLegend(legendObj *dst, legendObj *src, mapObj *map)
 
 int msCopyLayer(layerObj *dst, layerObj *src)
 {
-    int i, return_value;
-    featureListNodeObjPtr current;
+  int i, return_value;
+  featureListNodeObjPtr current;
 
-    MS_COPYSTELEM(index);
-    MS_COPYSTRING(dst->classitem, src->classitem);
+  MS_COPYSTELEM(index);
+  MS_COPYSTRING(dst->classitem, src->classitem);
 
-    MS_COPYSTELEM(classitemindex);
+  MS_COPYSTELEM(classitemindex);
 
-    for (i = 0; i < src->numclasses; i++) {
-        if (msGrowLayerClasses(dst) == NULL)
-            return MS_FAILURE;
+  for (i = 0; i < src->numclasses; i++) {
+    if (msGrowLayerClasses(dst) == NULL)
+      return MS_FAILURE;
 #ifndef __cplusplus
-        initClass(dst->class[i]);
-        return_value = msCopyClass(dst->class[i], src->class[i], dst);
+    initClass(dst->class[i]);
+    return_value = msCopyClass(dst->class[i], src->class[i], dst);
 #else
-        initClass(dst->_class[i]);
-        return_value = msCopyClass(dst->_class[i], src->_class[i], dst);
+    initClass(dst->_class[i]);
+    return_value = msCopyClass(dst->_class[i], src->_class[i], dst);
 #endif
-        if (return_value != MS_SUCCESS) {
-            msSetError(MS_MEMERR, "Failed to copy class.", "msCopyLayer()");
-            return MS_FAILURE;
-        }
-        dst->numclasses++;
+    if (return_value != MS_SUCCESS) {
+      msSetError(MS_MEMERR, "Failed to copy class.", "msCopyLayer()");
+      return MS_FAILURE;
     }
-    MS_COPYSTRING(dst->header, src->header);
-    MS_COPYSTRING(dst->footer, src->footer);
+    dst->numclasses++;
+  }
+  MS_COPYSTRING(dst->header, src->header);
+  MS_COPYSTRING(dst->footer, src->footer);
 #ifndef __cplusplus
-    MS_COPYSTRING(dst->template, src->template);
+  MS_COPYSTRING(dst->template, src->template);
 #else
-    MS_COPYSTRING(dst->_template, src->_template);
+  MS_COPYSTRING(dst->_template, src->_template);
 #endif
 
-    MS_COPYSTRING(dst->name, src->name); 
-    MS_COPYSTRING(dst->group, src->group); 
-    MS_COPYSTRING(dst->data, src->data); 
-    
-    MS_COPYSTELEM(status);
-    MS_COPYSTELEM(type);
-    MS_COPYSTELEM(annotate);
-    MS_COPYSTELEM(tolerance);
-    MS_COPYSTELEM(toleranceunits);
-    MS_COPYSTELEM(symbolscaledenom);
-    MS_COPYSTELEM(scalefactor);
-    MS_COPYSTELEM(minscaledenom);
-    MS_COPYSTELEM(maxscaledenom);
+  MS_COPYSTRING(dst->name, src->name);
+  MS_COPYSTRING(dst->group, src->group);
+  MS_COPYSTRING(dst->data, src->data);
 
-    MS_COPYSTELEM(labelminscaledenom);
-    MS_COPYSTELEM(labelmaxscaledenom);
-    MS_COPYSTELEM(mingeowidth);
-    MS_COPYSTELEM(maxgeowidth);
+  MS_COPYSTELEM(status);
+  MS_COPYSTELEM(type);
+  MS_COPYSTELEM(annotate);
+  MS_COPYSTELEM(tolerance);
+  MS_COPYSTELEM(toleranceunits);
+  MS_COPYSTELEM(symbolscaledenom);
+  MS_COPYSTELEM(scalefactor);
+  MS_COPYSTELEM(minscaledenom);
+  MS_COPYSTELEM(maxscaledenom);
 
-    MS_COPYSTELEM(sizeunits);
-    MS_COPYSTELEM(maxfeatures);
+  MS_COPYSTELEM(labelminscaledenom);
+  MS_COPYSTELEM(labelmaxscaledenom);
+  MS_COPYSTELEM(mingeowidth);
+  MS_COPYSTELEM(maxgeowidth);
 
-    MS_COPYCOLOR(&(dst->offsite), &(src->offsite));
+  MS_COPYSTELEM(sizeunits);
+  MS_COPYSTELEM(maxfeatures);
 
-    MS_COPYSTELEM(transform);
-    MS_COPYSTELEM(labelcache);
-    MS_COPYSTELEM(postlabelcache); 
+  MS_COPYCOLOR(&(dst->offsite), &(src->offsite));
 
-    MS_COPYSTRING(dst->labelitem, src->labelitem);
-    MS_COPYSTELEM(labelitemindex);
+  MS_COPYSTELEM(transform);
+  MS_COPYSTELEM(labelcache);
+  MS_COPYSTELEM(postlabelcache);
 
-    MS_COPYSTRING(dst->tileitem, src->tileitem);
-    MS_COPYSTELEM(tileitemindex);
+  MS_COPYSTRING(dst->labelitem, src->labelitem);
+  MS_COPYSTELEM(labelitemindex);
 
-    MS_COPYSTRING(dst->tileindex, src->tileindex); 
+  MS_COPYSTRING(dst->tileitem, src->tileitem);
+  MS_COPYSTELEM(tileitemindex);
 
-    return_value = msCopyProjection(&(dst->projection),&(src->projection));
-    if (return_value != MS_SUCCESS) {
-        msSetError(MS_MEMERR, "Failed to copy projection.", "msCopyLayer()");
-        return MS_FAILURE;
-    }
+  MS_COPYSTRING(dst->tileindex, src->tileindex);
 
-    return_value = msCopyCluster(&(dst->cluster),&(src->cluster));
-    if (return_value != MS_SUCCESS) {
-        return MS_FAILURE;
-    }
+  return_value = msCopyProjection(&(dst->projection),&(src->projection));
+  if (return_value != MS_SUCCESS) {
+    msSetError(MS_MEMERR, "Failed to copy projection.", "msCopyLayer()");
+    return MS_FAILURE;
+  }
 
-    MS_COPYSTELEM(project); 
-    MS_COPYSTELEM(units); 
+  return_value = msCopyCluster(&(dst->cluster),&(src->cluster));
+  if (return_value != MS_SUCCESS) {
+    return MS_FAILURE;
+  }
 
-    current = src->features;
-    while(current != NULL) {
-        insertFeatureList(&(dst->features), &(current->shape));
-        current = current->next;
-    }
+  MS_COPYSTELEM(project);
+  MS_COPYSTELEM(units);
 
-    MS_COPYSTRING(dst->connection, src->connection);
-    MS_COPYSTELEM(connectiontype);
+  current = src->features;
+  while(current != NULL) {
+    insertFeatureList(&(dst->features), &(current->shape));
+    current = current->next;
+  }
 
-    MS_COPYSTRING(dst->plugin_library, src->plugin_library);
-    MS_COPYSTRING(dst->plugin_library_original, src->plugin_library_original);
-        
-    /* Do not copy *layerinfo, items, or iteminfo. these are all initialized
-       when the copied layer is opened */
+  MS_COPYSTRING(dst->connection, src->connection);
+  MS_COPYSTELEM(connectiontype);
 
-    return_value = msCopyExpression(&(dst->filter), &(src->filter));
-    if (return_value != MS_SUCCESS) {
-        msSetError(MS_MEMERR, "Failed to copy filter.", "msCopyLayer()");
-        return MS_FAILURE;
-    }
+  MS_COPYSTRING(dst->plugin_library, src->plugin_library);
+  MS_COPYSTRING(dst->plugin_library_original, src->plugin_library_original);
 
-    MS_COPYSTRING(dst->filteritem, src->filteritem);
-    MS_COPYSTELEM(filteritemindex);
+  /* Do not copy *layerinfo, items, or iteminfo. these are all initialized
+     when the copied layer is opened */
 
-    MS_COPYSTRING(dst->styleitem, src->styleitem); 
-    MS_COPYSTELEM(styleitemindex);
+  return_value = msCopyExpression(&(dst->filter), &(src->filter));
+  if (return_value != MS_SUCCESS) {
+    msSetError(MS_MEMERR, "Failed to copy filter.", "msCopyLayer()");
+    return MS_FAILURE;
+  }
 
-    MS_COPYSTRING(dst->requires, src->requires); 
-    MS_COPYSTRING(dst->labelrequires, src->labelrequires);
+  MS_COPYSTRING(dst->filteritem, src->filteritem);
+  MS_COPYSTELEM(filteritemindex);
 
-    if (&(src->metadata)) {
-        msCopyHashTable(&(dst->metadata), &(src->metadata));
-    }
+  MS_COPYSTRING(dst->styleitem, src->styleitem);
+  MS_COPYSTELEM(styleitemindex);
 
-    MS_COPYSTELEM(opacity);
-    MS_COPYSTELEM(dump);
-    MS_COPYSTELEM(debug);
+  MS_COPYSTRING(dst->requires, src->requires);
+  MS_COPYSTRING(dst->labelrequires, src->labelrequires);
 
-    /* No need to copy the numprocessing member, as it is incremented by
-       msLayerAddProcessing */
-    for (i = 0; i < src->numprocessing; i++) 
-    {
-        msLayerAddProcessing(dst, msLayerGetProcessing(src, i));
-    }
+  if (&(src->metadata)) {
+    msCopyHashTable(&(dst->metadata), &(src->metadata));
+  }
 
-    MS_COPYSTELEM(numjoins);
+  MS_COPYSTELEM(opacity);
+  MS_COPYSTELEM(dump);
+  MS_COPYSTELEM(debug);
 
-    for (i = 0; i < dst->numjoins; i++) {
-        initJoin(&(dst->joins[i]));
-        return_value = msCopyJoin(&(dst->joins[i]), &(src->joins[i]));
-        if (return_value != MS_SUCCESS)
-            return MS_FAILURE;
-    }
+  /* No need to copy the numprocessing member, as it is incremented by
+     msLayerAddProcessing */
+  for (i = 0; i < src->numprocessing; i++) {
+    msLayerAddProcessing(dst, msLayerGetProcessing(src, i));
+  }
+
+  MS_COPYSTELEM(numjoins);
 
-    MS_COPYRECT(&(dst->extent), &(src->extent));
-    
-    MS_COPYSTRING(dst->classgroup, src->classgroup); 
+  for (i = 0; i < dst->numjoins; i++) {
+    initJoin(&(dst->joins[i]));
+    return_value = msCopyJoin(&(dst->joins[i]), &(src->joins[i]));
+    if (return_value != MS_SUCCESS)
+      return MS_FAILURE;
+  }
+
+  MS_COPYRECT(&(dst->extent), &(src->extent));
+
+  MS_COPYSTRING(dst->classgroup, src->classgroup);
+  MS_COPYSTRING(dst->mask, src->mask);
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 /***********************************************************************
@@ -934,132 +1006,132 @@ int msCopyLayer(layerObj *dst, layerObj *src)
 
 int msCopyMap(mapObj *dst, mapObj *src)
 {
-    int i, return_value;
-    outputFormatObj *format;
-
-    MS_COPYSTRING(dst->name, src->name); 
-    MS_COPYSTELEM(status);
-    MS_COPYSTELEM(height);
-    MS_COPYSTELEM(width);
-
-    for (i = 0; i < src->numlayers; i++) {
-        if (msGrowMapLayers(dst) == NULL)
-            return MS_FAILURE;
-        initLayer((GET_LAYER(dst, i)), dst);
-
-        return_value = msCopyLayer((GET_LAYER(dst, i)), (GET_LAYER(src, i)));
-        if (return_value != MS_SUCCESS) {
-            msSetError(MS_MEMERR, "Failed to copy layer.", "msCopyMap()");
-            return MS_FAILURE;
-        }
-        dst->numlayers++;
-    }
-    
-    return_value = msCopyFontSet(&(dst->fontset), &(src->fontset), dst);
+  int i, return_value;
+  outputFormatObj *format;
+
+  MS_COPYSTRING(dst->name, src->name);
+  MS_COPYSTELEM(status);
+  MS_COPYSTELEM(height);
+  MS_COPYSTELEM(width);
+  MS_COPYSTELEM(maxsize);
+
+  for (i = 0; i < src->numlayers; i++) {
+    if (msGrowMapLayers(dst) == NULL)
+      return MS_FAILURE;
+    initLayer((GET_LAYER(dst, i)), dst);
+
+    return_value = msCopyLayer((GET_LAYER(dst, i)), (GET_LAYER(src, i)));
     if (return_value != MS_SUCCESS) {
-        msSetError(MS_MEMERR, "Failed to copy fontset.", "msCopyMap()");
-        return MS_FAILURE;
-    }
-    
-    return_value = msCopySymbolSet(&(dst->symbolset), &(src->symbolset), dst);
-    if(return_value != MS_SUCCESS) {
-        msSetError(MS_MEMERR, "Failed to copy symbolset.", "msCopyMap()");
-        return MS_FAILURE;
+      msSetError(MS_MEMERR, "Failed to copy layer.", "msCopyMap()");
+      return MS_FAILURE;
     }
+    dst->numlayers++;
+  }
 
-    /* msCopyLabelCache(&(dst->labelcache), &(src->labelcache)); */
-    MS_COPYSTELEM(transparent);
-    MS_COPYSTELEM(interlace);
-    MS_COPYSTELEM(imagequality);
-
-    MS_COPYRECT(&(dst->extent), &(src->extent));
+  return_value = msCopyFontSet(&(dst->fontset), &(src->fontset), dst);
+  if (return_value != MS_SUCCESS) {
+    msSetError(MS_MEMERR, "Failed to copy fontset.", "msCopyMap()");
+    return MS_FAILURE;
+  }
 
-    MS_COPYSTELEM(cellsize);
-    MS_COPYSTELEM(units);
-    MS_COPYSTELEM(scaledenom);
-    MS_COPYSTELEM(defresolution);
-    MS_COPYSTELEM(resolution);
-    MS_COPYSTRING(dst->shapepath, src->shapepath); 
-    MS_COPYSTRING(dst->mappath, src->mappath); 
+  return_value = msCopySymbolSet(&(dst->symbolset), &(src->symbolset), dst);
+  if(return_value != MS_SUCCESS) {
+    msSetError(MS_MEMERR, "Failed to copy symbolset.", "msCopyMap()");
+    return MS_FAILURE;
+  }
 
-    MS_COPYCOLOR(&(dst->imagecolor), &(src->imagecolor));
+  /* msCopyLabelCache(&(dst->labelcache), &(src->labelcache)); */
+  MS_COPYSTELEM(transparent);
+  MS_COPYSTELEM(interlace);
+  MS_COPYSTELEM(imagequality);
 
-    /* clear existing destination format list */
-    if( dst->outputformat && --dst->outputformat->refcount < 1 )
-    {
-        msFreeOutputFormat( dst->outputformat );
-        dst->outputformat = NULL;
-    }
+  MS_COPYRECT(&(dst->extent), &(src->extent));
 
-    for(i=0; i < dst->numoutputformats; i++ ) {
-        if( --dst->outputformatlist[i]->refcount < 1 )
-            msFreeOutputFormat( dst->outputformatlist[i] );
-    }
-    if( dst->outputformatlist != NULL )
-        msFree( dst->outputformatlist );
-    dst->outputformatlist = NULL;
-    dst->outputformat = NULL;
-    dst->numoutputformats = 0;
+  MS_COPYSTELEM(cellsize);
+  MS_COPYSTELEM(units);
+  MS_COPYSTELEM(scaledenom);
+  MS_COPYSTELEM(defresolution);
+  MS_COPYSTELEM(resolution);
+  MS_COPYSTRING(dst->shapepath, src->shapepath);
+  MS_COPYSTRING(dst->mappath, src->mappath);
 
-    for (i = 0; i < src->numoutputformats; i++)
-        msAppendOutputFormat( dst, 
-        msCloneOutputFormat( src->outputformatlist[i]) );
+  MS_COPYCOLOR(&(dst->imagecolor), &(src->imagecolor));
 
-    /* set the active output format */
-    MS_COPYSTRING(dst->imagetype, src->imagetype); 
-    format = msSelectOutputFormat( dst, dst->imagetype );
-    msApplyOutputFormat(&(dst->outputformat), format, MS_NOOVERRIDE, 
-        MS_NOOVERRIDE, MS_NOOVERRIDE );
+  /* clear existing destination format list */
+  if( dst->outputformat && --dst->outputformat->refcount < 1 ) {
+    msFreeOutputFormat( dst->outputformat );
+    dst->outputformat = NULL;
+  }
 
-    return_value = msCopyProjection(&(dst->projection),&(src->projection));
-    if (return_value != MS_SUCCESS) {
-        msSetError(MS_MEMERR, "Failed to copy projection.", "msCopyMap()");
-        return MS_FAILURE;
-    }
+  for(i=0; i < dst->numoutputformats; i++ ) {
+    if( --dst->outputformatlist[i]->refcount < 1 )
+      msFreeOutputFormat( dst->outputformatlist[i] );
+  }
+  if( dst->outputformatlist != NULL )
+    msFree( dst->outputformatlist );
+  dst->outputformatlist = NULL;
+  dst->outputformat = NULL;
+  dst->numoutputformats = 0;
+
+  for (i = 0; i < src->numoutputformats; i++)
+    msAppendOutputFormat( dst,
+                          msCloneOutputFormat( src->outputformatlist[i]) );
+
+  /* set the active output format */
+  MS_COPYSTRING(dst->imagetype, src->imagetype);
+  format = msSelectOutputFormat( dst, dst->imagetype );
+  msApplyOutputFormat(&(dst->outputformat), format, MS_NOOVERRIDE,
+                      MS_NOOVERRIDE, MS_NOOVERRIDE );
+
+  return_value = msCopyProjection(&(dst->projection),&(src->projection));
+  if (return_value != MS_SUCCESS) {
+    msSetError(MS_MEMERR, "Failed to copy projection.", "msCopyMap()");
+    return MS_FAILURE;
+  }
 
-    /* No need to copy latlon projection */
+  /* No need to copy latlon projection */
 
-    return_value = msCopyReferenceMap(&(dst->reference),&(src->reference),
-        dst);
-    if (return_value != MS_SUCCESS) {
-        msSetError(MS_MEMERR, "Failed to copy reference.", "msCopyMap()");
-        return MS_FAILURE;
-    }
+  return_value = msCopyReferenceMap(&(dst->reference),&(src->reference),
+                                    dst);
+  if (return_value != MS_SUCCESS) {
+    msSetError(MS_MEMERR, "Failed to copy reference.", "msCopyMap()");
+    return MS_FAILURE;
+  }
 
-    return_value = msCopyScalebar(&(dst->scalebar), &(src->scalebar));
-    if (return_value != MS_SUCCESS) {
-        msSetError(MS_MEMERR, "Failed to copy scalebar.", "msCopyMap()");
-        return MS_FAILURE;
-    }
+  return_value = msCopyScalebar(&(dst->scalebar), &(src->scalebar));
+  if (return_value != MS_SUCCESS) {
+    msSetError(MS_MEMERR, "Failed to copy scalebar.", "msCopyMap()");
+    return MS_FAILURE;
+  }
 
-    return_value = msCopyLegend(&(dst->legend), &(src->legend),dst);
-    if (return_value != MS_SUCCESS) {
-        msSetError(MS_MEMERR, "Failed to copy legend.", "msCopyMap()");
-        return MS_FAILURE;
-    }
+  return_value = msCopyLegend(&(dst->legend), &(src->legend),dst);
+  if (return_value != MS_SUCCESS) {
+    msSetError(MS_MEMERR, "Failed to copy legend.", "msCopyMap()");
+    return MS_FAILURE;
+  }
 
-    return_value = msCopyQueryMap(&(dst->querymap), &(src->querymap));
-    if (return_value != MS_SUCCESS) {
-        msSetError(MS_MEMERR, "Failed to copy querymap.", "msCopyMap()");
-        return MS_FAILURE;
-    }
+  return_value = msCopyQueryMap(&(dst->querymap), &(src->querymap));
+  if (return_value != MS_SUCCESS) {
+    msSetError(MS_MEMERR, "Failed to copy querymap.", "msCopyMap()");
+    return MS_FAILURE;
+  }
 
-    return_value = msCopyWeb(&(dst->web), &(src->web), dst);
-    if (return_value != MS_SUCCESS) {
-        msSetError(MS_MEMERR, "Failed to copy web.", "msCopyMap()");
-        return MS_FAILURE;
-    }
+  return_value = msCopyWeb(&(dst->web), &(src->web), dst);
+  if (return_value != MS_SUCCESS) {
+    msSetError(MS_MEMERR, "Failed to copy web.", "msCopyMap()");
+    return MS_FAILURE;
+  }
 
-    for (i = 0; i < dst->numlayers; i++) {
-        MS_COPYSTELEM(layerorder[i]);
-    }
-    MS_COPYSTELEM(debug);
-    MS_COPYSTRING(dst->datapattern, src->datapattern);
-    MS_COPYSTRING(dst->templatepattern, src->templatepattern);   
+  for (i = 0; i < dst->numlayers; i++) {
+    MS_COPYSTELEM(layerorder[i]);
+  }
+  MS_COPYSTELEM(debug);
+  MS_COPYSTRING(dst->datapattern, src->datapattern);
+  MS_COPYSTRING(dst->templatepattern, src->templatepattern);
 
-    if( msCopyHashTable( &(dst->configoptions), &(src->configoptions) ) != MS_SUCCESS )
-        return MS_FAILURE;
+  if( msCopyHashTable( &(dst->configoptions), &(src->configoptions) ) != MS_SUCCESS )
+    return MS_FAILURE;
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
diff --git a/mapcopy.h b/mapcopy.h
index 6a4597c..a973898 100644
--- a/mapcopy.h
+++ b/mapcopy.h
@@ -2,10 +2,10 @@
  * $Id$
  *
  * Project:  MapServer
- * Purpose:  Declarations related to copyng mapObjs.  Provided by Mladen Turk 
- *           for resolution of bug 701 
+ * Purpose:  Declarations related to copyng mapObjs.  Provided by Mladen Turk
+ *           for resolution of bug 701
  *           http://mapserver.gis.umn.edu/bugs/show_bug.cgi?id=701.
- * Author:   Mladen Turk (and Sean Gilles?) 
+ * Author:   Mladen Turk (and Sean Gilles?)
  *
  ******************************************************************************
  * Copyright (c) 1996-2005 Regents of the University of Minnesota.
@@ -17,7 +17,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -35,7 +35,7 @@
 #define MS_COPYSTELEM(_name) (dst)->/**/_name = (src)->/**/_name
 
 #define MS_MACROBEGIN              do {
-#define MS_MACROEND                } while (0) 
+#define MS_MACROEND                } while (0)
 
 #define MS_COPYRECT(_dst, _src)       \
     MS_MACROBEGIN                     \
@@ -60,6 +60,7 @@
     MS_MACROEND
 #endif
 
+#ifdef USE_GD
 #define MS_COPYCOLOR(_dst, _src)      \
     MS_MACROBEGIN                     \
         (_dst)->pen   = (_src)->pen;  \
@@ -68,6 +69,15 @@
         (_dst)->blue  = (_src)->blue; \
         (_dst)->alpha  = (_src)->alpha; \
     MS_MACROEND
+#else
+#define MS_COPYCOLOR(_dst, _src)      \
+    MS_MACROBEGIN                     \
+        (_dst)->red   = (_src)->red;  \
+        (_dst)->green = (_src)->green;\
+        (_dst)->blue  = (_src)->blue; \
+        (_dst)->alpha  = (_src)->alpha; \
+    MS_MACROEND
+#endif
 
 #define MS_COPYSTRING(_dst, _src)     \
     MS_MACROBEGIN                     \
diff --git a/mapcpl.c b/mapcpl.c
index c33846b..1e09a24 100644
--- a/mapcpl.c
+++ b/mapcpl.c
@@ -1,15 +1,15 @@
 /******************************************************************************
- * $Id$ 
+ * $Id$
  *
  * Project:  MapServer
- * Purpose:  Functions copied from GDAL's CPL. This file contain utility 
+ * Purpose:  Functions copied from GDAL's CPL. This file contain utility
  *           functions that come from the GDAL/OGR cpl library. The idea
  *           behind it is to have access in mapserver to all these
  *           utilities, without being constrained to link with GDAL/OGR.
  * Author:   Y. Assefa, DM Solutions Group (assefa at dmsolutions.ca)
- * 
- * 
- * Note: 
+ *
+ *
+ * Note:
  * Names of functions used here are the same as those in the cpl
  * library with the exception the the CPL prefix is changed to ms
  * (eg : CPLGetBasename() would become msGetBasename())
@@ -24,7 +24,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -41,11 +41,11 @@
 #include <assert.h>
 #include "mapserver.h"
 
-MS_CVSID("$Id$")
+
 
 /* should be size of largest possible filename */
 #define MS_PATH_BUF_SIZE 2048
-static char     szStaticResult[MS_PATH_BUF_SIZE]; 
+static char     szStaticResult[MS_PATH_BUF_SIZE];
 
 
 /************************************************************************/
@@ -55,15 +55,15 @@ static char     szStaticResult[MS_PATH_BUF_SIZE];
 static int msFindFilenameStart( const char * pszFilename )
 
 {
-    int         iFileStart;
+  int         iFileStart;
 
-    for( iFileStart = strlen(pszFilename);
-         iFileStart > 0
-             && pszFilename[iFileStart-1] != '/'
-             && pszFilename[iFileStart-1] != '\\';
-         iFileStart-- ) {}
+  for( iFileStart = strlen(pszFilename);
+       iFileStart > 0
+       && pszFilename[iFileStart-1] != '/'
+       && pszFilename[iFileStart-1] != '\\';
+       iFileStart-- ) {}
 
-    return iFileStart;
+  return iFileStart;
 }
 
 /************************************************************************/
@@ -93,23 +93,23 @@ static int msFindFilenameStart( const char * pszFilename )
 const char *msGetBasename( const char *pszFullFilename )
 
 {
-    int iFileStart = msFindFilenameStart( pszFullFilename );
-    int iExtStart, nLength;
+  int iFileStart = msFindFilenameStart( pszFullFilename );
+  int iExtStart, nLength;
 
-    for( iExtStart = strlen(pszFullFilename);
-         iExtStart > iFileStart && pszFullFilename[iExtStart] != '.';
-         iExtStart-- ) {}
+  for( iExtStart = strlen(pszFullFilename);
+       iExtStart > iFileStart && pszFullFilename[iExtStart] != '.';
+       iExtStart-- ) {}
 
-    if( iExtStart == iFileStart )
-        iExtStart = strlen(pszFullFilename);
+  if( iExtStart == iFileStart )
+    iExtStart = strlen(pszFullFilename);
 
-    nLength = iExtStart - iFileStart;
+  nLength = iExtStart - iFileStart;
 
-    assert( nLength < MS_PATH_BUF_SIZE );
+  assert( nLength < MS_PATH_BUF_SIZE );
 
-    strlcpy( szStaticResult, pszFullFilename + iFileStart, nLength+1 );
+  strlcpy( szStaticResult, pszFullFilename + iFileStart, nLength+1 );
 
-    return szStaticResult;
+  return szStaticResult;
 }
 
 /* Id: GDAL/port/cplgetsymbol.cpp,v 1.14 2004/11/11 20:40:38 fwarmerdam Exp */
@@ -141,14 +141,14 @@ const char *msGetBasename( const char *pszFullFilename )
  * Currently msGetSymbol() doesn't try to:
  * <ul>
  *  <li> prevent the reference count on the library from going up
- *    for every request, or given any opportunity to unload      
- *    the library.                                            
- *  <li> Attempt to look for the library in non-standard         
- *    locations.                                              
- *  <li> Attempt to try variations on the symbol name, like      
+ *    for every request, or given any opportunity to unload
+ *    the library.
+ *  <li> Attempt to look for the library in non-standard
+ *    locations.
+ *  <li> Attempt to try variations on the symbol name, like
  *    pre-prending or post-pending an underscore.
  * </ul>
- * 
+ *
  * Some of these issues may be worked on in the future.
  *
  * @param pszLibrary the name of the shared library or DLL containing
@@ -161,43 +161,41 @@ const char *msGetBasename( const char *pszFullFilename )
 
 void *msGetSymbol( const char * pszLibrary, const char * pszSymbolName )
 {
-    void        *pLibrary;
-    void        *pSymbol;
-
-    pLibrary = dlopen(pszLibrary, RTLD_LAZY);
-    if( pLibrary == NULL )
-    {
-        msSetError(MS_MISCERR, 
-                   "Dynamic loading failed: %s",
-                   "msGetSymbol()", dlerror());
-        return NULL;
-    }
+  void        *pLibrary;
+  void        *pSymbol;
+
+  pLibrary = dlopen(pszLibrary, RTLD_LAZY);
+  if( pLibrary == NULL ) {
+    msSetError(MS_MISCERR,
+               "Dynamic loading failed: %s",
+               "msGetSymbol()", dlerror());
+    return NULL;
+  }
 
-    pSymbol = dlsym( pLibrary, pszSymbolName );
+  pSymbol = dlsym( pLibrary, pszSymbolName );
 
 #if (defined(__APPLE__) && defined(__MACH__))
-    /* On mach-o systems, C symbols have a leading underscore and depending
-     * on how dlcompat is configured it may or may not add the leading
-     * underscore.  So if dlsym() fails add an underscore and try again.
-     */
-    if( pSymbol == NULL )
-    {
-        char withUnder[strlen(pszSymbolName) + 2];
-        withUnder[0] = '_'; withUnder[1] = 0;
-        strcat(withUnder, pszSymbolName);
-        pSymbol = dlsym( pLibrary, withUnder );
-    }
+  /* On mach-o systems, C symbols have a leading underscore and depending
+   * on how dlcompat is configured it may or may not add the leading
+   * underscore.  So if dlsym() fails add an underscore and try again.
+   */
+  if( pSymbol == NULL ) {
+    char withUnder[strlen(pszSymbolName) + 2];
+    withUnder[0] = '_';
+    withUnder[1] = 0;
+    strcat(withUnder, pszSymbolName);
+    pSymbol = dlsym( pLibrary, withUnder );
+  }
 #endif
 
-    if( pSymbol == NULL )
-    {
-        msSetError(MS_MISCERR, 
-                   "Dynamic loading failed: %s",
-                   "msGetSymbol()", dlerror());
-        return NULL;
-    }
-    
-    return( pSymbol );
+  if( pSymbol == NULL ) {
+    msSetError(MS_MISCERR,
+               "Dynamic loading failed: %s",
+               "msGetSymbol()", dlerror());
+    return NULL;
+  }
+
+  return( pSymbol );
 }
 
 #endif /* def __unix__ && defined(HAVE_DLFCN_H) */
@@ -217,29 +215,27 @@ void *msGetSymbol( const char * pszLibrary, const char * pszSymbolName )
 
 void *msGetSymbol( const char * pszLibrary, const char * pszSymbolName )
 {
-    void        *pLibrary;
-    void        *pSymbol;
-
-    pLibrary = LoadLibrary(pszLibrary);
-    if( pLibrary == NULL )
-    {
-        msSetError(MS_MISCERR, 
-                  "Can't load requested dynamic library: %s", 
-                   "msGetSymbol()", pszLibrary);
-        return NULL;
-    }
-
-    pSymbol = (void *) GetProcAddress( (HINSTANCE) pLibrary, pszSymbolName );
-
-    if( pSymbol == NULL )
-    {
-        msSetError(MS_MISCERR, 
-            "Can't find requested entry point: %s in lib %s",
-                   "msGetSymbol()", pszSymbolName, pLibrary);
-        return NULL;
-    }
-    
-    return( pSymbol );
+  void        *pLibrary;
+  void        *pSymbol;
+
+  pLibrary = LoadLibrary(pszLibrary);
+  if( pLibrary == NULL ) {
+    msSetError(MS_MISCERR,
+               "Can't load requested dynamic library: %s",
+               "msGetSymbol()", pszLibrary);
+    return NULL;
+  }
+
+  pSymbol = (void *) GetProcAddress( (HINSTANCE) pLibrary, pszSymbolName );
+
+  if( pSymbol == NULL ) {
+    msSetError(MS_MISCERR,
+               "Can't find requested entry point: %s in lib %s",
+               "msGetSymbol()", pszSymbolName, pLibrary);
+    return NULL;
+  }
+
+  return( pSymbol );
 }
 
 #endif /* def _WIN32 */
@@ -258,9 +254,9 @@ void *msGetSymbol( const char * pszLibrary, const char * pszSymbolName )
 
 void *msGetSymbol(const char *pszLibrary, const char *pszEntryPoint)
 {
-    msSetError(MS_MISCERR, 
-               "msGetSymbol(%s,%s) called.  Failed as this is stub implementation.",  
-               "msGetSymbol()", pszLibrary, pszEntryPoint);
-    return NULL;
+  msSetError(MS_MISCERR,
+             "msGetSymbol(%s,%s) called.  Failed as this is stub implementation.",
+             "msGetSymbol()", pszLibrary, pszEntryPoint);
+  return NULL;
 }
 #endif
diff --git a/mapcrypto.c b/mapcrypto.c
index 37f0ae3..0e665c9 100644
--- a/mapcrypto.c
+++ b/mapcrypto.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -34,21 +34,21 @@
 
 #include "mapserver.h"
 
-MS_CVSID("$Id$")
+
 
 
 /**********************************************************************
- * encipher() and decipher() from the Tiny Encryption Algorithm (TEA) 
+ * encipher() and decipher() from the Tiny Encryption Algorithm (TEA)
  * website at:
  *   http://www.simonshepherd.supanet.com/tea.htm
  *
- * TEA was developed and placed in the public domain by David Wheeler 
+ * TEA was developed and placed in the public domain by David Wheeler
  * and Roger Needham at the Computer Laboratory of Cambridge University.
  *
  * The source below came with the following public domain notice:
  *
  *   "Please feel free to use any of this code in your applications.
- *    The TEA algorithm (including new-variant TEA) has been placed 
+ *    The TEA algorithm (including new-variant TEA) has been placed
  *    in the public domain, as have my assembly language implementations."
  *
  * ... and the following usage notes:
@@ -62,59 +62,59 @@ MS_CVSID("$Id$")
  *                const unsigned long * const k);
  *
  * TEA takes 64 bits of data in v[0] and v[1], and 128 bits of key in
- * k[0] - k[3]. The result is returned in w[0] and w[1]. Returning the 
- * result separately makes implementation of cipher modes other than 
+ * k[0] - k[3]. The result is returned in w[0] and w[1]. Returning the
+ * result separately makes implementation of cipher modes other than
  * Electronic Code Book a little bit easier.
  *
  * TEA can be operated in any of the modes of DES.
  *
- * n is the number of iterations. 32 is ample, 16 is sufficient, as few 
- * as eight should be OK for most applications, especially ones where 
- * the data age quickly (real-time video, for example). The algorithm 
- * achieves good dispersion after six iterations. The iteration count 
+ * n is the number of iterations. 32 is ample, 16 is sufficient, as few
+ * as eight should be OK for most applications, especially ones where
+ * the data age quickly (real-time video, for example). The algorithm
+ * achieves good dispersion after six iterations. The iteration count
  * can be made variable if required.
  *
- * Note this algorithm is optimised for 32-bit CPUs with fast shift 
- * capabilities. It can very easily be ported to assembly language 
+ * Note this algorithm is optimised for 32-bit CPUs with fast shift
+ * capabilities. It can very easily be ported to assembly language
  * on most CPUs.
  *
- * delta is chosen to be the Golden ratio ((5/4)1/2 - 1/2 ~ 0.618034) 
+ * delta is chosen to be the Golden ratio ((5/4)1/2 - 1/2 ~ 0.618034)
  * multiplied by 232. On entry to decipher(), sum is set to be delta * n.
  * Which way round you call the functions is arbitrary: DK(EK(P)) = EK(DK(P))
- * where EK and DK are encryption and decryption under key K respectively. 
+ * where EK and DK are encryption and decryption under key K respectively.
  *
  **********************************************************************/
 
 static void encipher(const ms_uint32 *const v, ms_uint32 *const w,
                      const ms_uint32 *const k)
 {
-   register ms_uint32   y=v[0],z=v[1],sum=0,delta=0x9E3779B9,n=32;
+  register ms_uint32   y=v[0],z=v[1],sum=0,delta=0x9E3779B9,n=32;
 
-   while(n-->0)
-   {
-      y += ((z << 4 ^ z >> 5) + z) ^ (sum + k[sum&3]);
-      sum += delta;
-      z += ((y << 4 ^ y >> 5) + y) ^ (sum + k[sum>>11 & 3]);
-   }
+  while(n-->0) {
+    y += ((z << 4 ^ z >> 5) + z) ^ (sum + k[sum&3]);
+    sum += delta;
+    z += ((y << 4 ^ y >> 5) + y) ^ (sum + k[sum>>11 & 3]);
+  }
 
-   w[0]=y; w[1]=z;
+  w[0]=y;
+  w[1]=z;
 }
 
 static void decipher(const ms_uint32 *const v, ms_uint32 *const w,
                      const ms_uint32 *const k)
 {
-   register ms_uint32       y=v[0],z=v[1],sum=0xC6EF3720, delta=0x9E3779B9,n=32;
-
-   /* sum = delta<<5, in general sum = delta * n */
-
-   while(n-->0)
-   {
-      z -= ((y << 4 ^ y >> 5) + y) ^ (sum + k[sum>>11 & 3]);
-      sum -= delta;
-      y -= ((z << 4 ^ z >> 5) + z) ^ (sum + k[sum&3]);
-   }
-   
-   w[0]=y; w[1]=z;
+  register ms_uint32       y=v[0],z=v[1],sum=0xC6EF3720, delta=0x9E3779B9,n=32;
+
+  /* sum = delta<<5, in general sum = delta * n */
+
+  while(n-->0) {
+    z -= ((y << 4 ^ y >> 5) + y) ^ (sum + k[sum>>11 & 3]);
+    sum -= delta;
+    y -= ((z << 4 ^ z >> 5) + z) ^ (sum + k[sum&3]);
+  }
+
+  w[0]=y;
+  w[1]=z;
 }
 
 /**********************************************************************
@@ -127,15 +127,14 @@ static void decipher(const ms_uint32 *const v, ms_uint32 *const w,
  **********************************************************************/
 void msHexEncode(const unsigned char *in, char *out, int numbytes)
 {
-    char *hex = "0123456789ABCDEF";
-
-    while (numbytes-- > 0)
-    {
-        *out++ = hex[*in/16];
-        *out++ = hex[*in%16];
-        in++;
-    }
-    *out = '\0';
+  char *hex = "0123456789ABCDEF";
+
+  while (numbytes-- > 0) {
+    *out++ = hex[*in/16];
+    *out++ = hex[*in%16];
+    in++;
+  }
+  *out = '\0';
 }
 
 /**********************************************************************
@@ -149,33 +148,32 @@ void msHexEncode(const unsigned char *in, char *out, int numbytes)
  * out[] should be preallocated by the caller to be large enough to hold
  * the resulting bytes.
  *
- * Returns the number of bytes written to out[] which may be different from 
+ * Returns the number of bytes written to out[] which may be different from
  * numchars/2 if an error or a '\0' is encountered.
  **********************************************************************/
 int msHexDecode(const char *in, unsigned char *out, int numchars)
 {
-    int numbytes_out = 0;
+  int numbytes_out = 0;
 
-    /* Make sure numchars is even */
-    numchars = (numchars/2) * 2;
+  /* Make sure numchars is even */
+  numchars = (numchars/2) * 2;
 
-    if (numchars < 2)
-        numchars = -1; /* Will result in this value being ignored in the loop*/
+  if (numchars < 2)
+    numchars = -1; /* Will result in this value being ignored in the loop*/
 
-    while (*in != '\0' && *(in+1) != '\0' && numchars != 0)
-    {
-        *out = 0x10 * (*in >= 'A' ? ((*in & 0xdf) - 'A')+10 : (*in - '0'));
-        in++;
-        *out += (*in >= 'A' ? ((*in & 0xdf) - 'A')+10 : (*in - '0'));
-        in++;
+  while (*in != '\0' && *(in+1) != '\0' && numchars != 0) {
+    *out = 0x10 * (*in >= 'A' ? ((*in & 0xdf) - 'A')+10 : (*in - '0'));
+    in++;
+    *out += (*in >= 'A' ? ((*in & 0xdf) - 'A')+10 : (*in - '0'));
+    in++;
 
-        out++;
-        numbytes_out++;
+    out++;
+    numbytes_out++;
 
-        numchars -= 2;
-    }
+    numchars -= 2;
+  }
 
-    return numbytes_out;
+  return numbytes_out;
 }
 
 
@@ -189,22 +187,22 @@ int msHexDecode(const char *in, unsigned char *out, int numchars)
 
 int msGenerateEncryptionKey(unsigned char *k)
 {
-    int i;
+  int i;
 
-    /* Use current time as seed for rand() */
-    srand( (unsigned int) time( NULL ));
+  /* Use current time as seed for rand() */
+  srand( (unsigned int) time( NULL ));
 
-    for(i=0; i<MS_ENCRYPTION_KEY_SIZE; i++)
-        k[i] = (unsigned char)rand();
+  for(i=0; i<MS_ENCRYPTION_KEY_SIZE; i++)
+    k[i] = (unsigned char)rand();
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 /**********************************************************************
  *                       msReadEncryptionKeyFromFile()
  *
  * Read and decode hex-encoded encryption key from file and returns the
- * key in the 'unsigned char k[MS_ENCRYPTION_KEY_SIZE]' buffer that is 
+ * key in the 'unsigned char k[MS_ENCRYPTION_KEY_SIZE]' buffer that is
  * provided by the caller.
  *
  * Returns MS_SUCCESS/MS_FAILURE.
@@ -212,39 +210,37 @@ int msGenerateEncryptionKey(unsigned char *k)
 
 int msReadEncryptionKeyFromFile(const char *keyfile, unsigned char *k)
 {
-    FILE *fp;
-    char szBuf[100];
-    int numchars;
-
-    if ((fp = fopen(keyfile, "rt")) == NULL)
-    {
-        msSetError(MS_MISCERR, "Cannot open key file.",
-                   "msReadEncryptionKeyFromFile()");
-        return MS_FAILURE;
-    }
-
-    numchars = fread(szBuf, sizeof(unsigned char), MS_ENCRYPTION_KEY_SIZE*2, fp);
-    fclose(fp);
-    szBuf[MS_ENCRYPTION_KEY_SIZE*2] = '\0';
-
-    if (numchars != MS_ENCRYPTION_KEY_SIZE*2)
-    {
-        msSetError(MS_MISCERR, "Invalid key file, got %d chars, expected %d.",
-                   "msReadEncryptionKeyFromFile()", 
-                   numchars, MS_ENCRYPTION_KEY_SIZE*2);
-        return MS_FAILURE;
-    }
-
-    msHexDecode(szBuf, k, MS_ENCRYPTION_KEY_SIZE*2);
-
-    return MS_SUCCESS;
+  FILE *fp;
+  char szBuf[100];
+  int numchars;
+
+  if ((fp = fopen(keyfile, "rt")) == NULL) {
+    msSetError(MS_MISCERR, "Cannot open key file.",
+               "msReadEncryptionKeyFromFile()");
+    return MS_FAILURE;
+  }
+
+  numchars = fread(szBuf, sizeof(unsigned char), MS_ENCRYPTION_KEY_SIZE*2, fp);
+  fclose(fp);
+  szBuf[MS_ENCRYPTION_KEY_SIZE*2] = '\0';
+
+  if (numchars != MS_ENCRYPTION_KEY_SIZE*2) {
+    msSetError(MS_MISCERR, "Invalid key file, got %d chars, expected %d.",
+               "msReadEncryptionKeyFromFile()",
+               numchars, MS_ENCRYPTION_KEY_SIZE*2);
+    return MS_FAILURE;
+  }
+
+  msHexDecode(szBuf, k, MS_ENCRYPTION_KEY_SIZE*2);
+
+  return MS_SUCCESS;
 }
 
 /**********************************************************************
  *                       msLoadEncryptionKey()
  *
  * Load and decode hex-encoded encryption key from file and returns the
- * key in the 'unsigned char k[MS_ENCRYPTION_KEY_SIZE]' buffer that is 
+ * key in the 'unsigned char k[MS_ENCRYPTION_KEY_SIZE]' buffer that is
  * provided by the caller.
  *
  * The first time that msLoadEncryptionKey() is called for a given mapObj
@@ -260,42 +256,38 @@ int msReadEncryptionKeyFromFile(const char *keyfile, unsigned char *k)
 
 static int msLoadEncryptionKey(mapObj *map)
 {
-    const char *keyfile;
+  const char *keyfile;
 
-    if (map == NULL)
-    {
-        msSetError(MS_MISCERR, "NULL MapObj.", "msLoadEncryptionKey()");
-        return MS_FAILURE;
-    }
+  if (map == NULL) {
+    msSetError(MS_MISCERR, "NULL MapObj.", "msLoadEncryptionKey()");
+    return MS_FAILURE;
+  }
 
-    if (map->encryption_key_loaded) 
-        return MS_SUCCESS;  /* Already loaded */
+  if (map->encryption_key_loaded)
+    return MS_SUCCESS;  /* Already loaded */
 
-    keyfile = msGetConfigOption(map, "MS_ENCRYPTION_KEY");
+  keyfile = msGetConfigOption(map, "MS_ENCRYPTION_KEY");
 
-    if (keyfile == NULL)
-        keyfile = getenv("MS_ENCRYPTION_KEY");
+  if (keyfile == NULL)
+    keyfile = getenv("MS_ENCRYPTION_KEY");
 
-    if (keyfile && 
-        msReadEncryptionKeyFromFile(keyfile,map->encryption_key) == MS_SUCCESS)
-    {
-        map->encryption_key_loaded = MS_TRUE;
-    }
-    else
-    {
-        msSetError(MS_MISCERR, "Failed reading encryption key. Make sure "
-                   "MS_ENCRYPTION_KEY is set and points to a valid key file.", 
-                   "msLoadEncryptionKey()");
-        return MS_FAILURE;
-    }
+  if (keyfile &&
+      msReadEncryptionKeyFromFile(keyfile,map->encryption_key) == MS_SUCCESS) {
+    map->encryption_key_loaded = MS_TRUE;
+  } else {
+    msSetError(MS_MISCERR, "Failed reading encryption key. Make sure "
+               "MS_ENCRYPTION_KEY is set and points to a valid key file.",
+               "msLoadEncryptionKey()");
+    return MS_FAILURE;
+  }
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 /**********************************************************************
  *                        msEncryptStringWithKey()
  *
- * Encrypts and hex-encodes the contents of string in[] and returns the 
+ * Encrypts and hex-encodes the contents of string in[] and returns the
  * result in out[] which should have been pre-allocated by the caller
  * to be at least twice the size of in[] + 16+1 bytes (for padding + '\0').
  *
@@ -303,61 +295,57 @@ static int msLoadEncryptionKey(mapObj *map)
 
 void msEncryptStringWithKey(const unsigned char *key, const char *in, char *out)
 {
-    ms_uint32 v[4], w[4];
-    const ms_uint32 *k;
-    int last_block = MS_FALSE;
-    
-    /* Casting the key this way is safe only as long as longs are 4 bytes
-     * on this platform */
-    assert(sizeof(ms_uint32) == 4);
-    k = (const ms_uint32 *) key;
-    
-    while(!last_block)
-    {
-        int i, j;
-        /* encipher() takes v[2] (64 bits) as input. 
-         * Copy bytes from in[] to the v[2] input array (pair of 4 bytes)
-         * v[] is padded with zeros if string doesn't align with 8 bytes
-         */
-        v[0] = 0;
-        v[1] = 0;
-        for(i=0; !last_block && i<2; i++)
-        {
-            for(j=0; j<4; j++)
-            {
-                if (*in == '\0')
-                {
-                    last_block = MS_TRUE;
-                    break;
-                }
-
-                v[i] |= *in << (j*8);
-                in++;
-            }
+  ms_uint32 v[4], w[4];
+  const ms_uint32 *k;
+  int last_block = MS_FALSE;
+
+  /* Casting the key this way is safe only as long as longs are 4 bytes
+   * on this platform */
+  assert(sizeof(ms_uint32) == 4);
+  k = (const ms_uint32 *) key;
+
+  while(!last_block) {
+    int i, j;
+    /* encipher() takes v[2] (64 bits) as input.
+     * Copy bytes from in[] to the v[2] input array (pair of 4 bytes)
+     * v[] is padded with zeros if string doesn't align with 8 bytes
+     */
+    v[0] = 0;
+    v[1] = 0;
+    for(i=0; !last_block && i<2; i++) {
+      for(j=0; j<4; j++) {
+        if (*in == '\0') {
+          last_block = MS_TRUE;
+          break;
         }
 
-        if (*in == '\0')
-            last_block = MS_TRUE;
+        v[i] |= *in << (j*8);
+        in++;
+      }
+    }
 
-        /* Do the actual encryption */
-        encipher(v, w, k);
+    if (*in == '\0')
+      last_block = MS_TRUE;
 
-        /* Append hex-encoded bytes to output, 4 bytes at a time */
-        msHexEncode((unsigned char *)w, out, 4);
-        out += 8;
-        msHexEncode((unsigned char *)(w+1), out, 4);
-        out += 8;
+    /* Do the actual encryption */
+    encipher(v, w, k);
 
-    }
+    /* Append hex-encoded bytes to output, 4 bytes at a time */
+    msHexEncode((unsigned char *)w, out, 4);
+    out += 8;
+    msHexEncode((unsigned char *)(w+1), out, 4);
+    out += 8;
+
+  }
 
-    /* Make sure output is 0-terminated */
-    *out = '\0';
+  /* Make sure output is 0-terminated */
+  *out = '\0';
 }
 
 /**********************************************************************
  *                        msDecryptStringWithKey()
  *
- * Hex-decodes and then decrypts the contents of string in[] and returns the 
+ * Hex-decodes and then decrypts the contents of string in[] and returns the
  * result in out[] which should have been pre-allocated by the caller
  * to be at least half the size of in[].
  *
@@ -365,60 +353,57 @@ void msEncryptStringWithKey(const unsigned char *key, const char *in, char *out)
 
 void msDecryptStringWithKey(const unsigned char *key, const char *in, char *out)
 {
-    ms_uint32 v[4], w[4];
-    const ms_uint32 *k;
-    int last_block = MS_FALSE;
-    
-    /* Casting the key this way is safe only as long as longs are 4 bytes
-     * on this platform */
-    assert(sizeof(ms_uint32) == 4);
-    k = (const ms_uint32 *) key;
-    
-    while(!last_block)
-    {
-        int i;
-        /* decipher() takes v[2] (64 bits) as input. 
-         * Copy bytes from in[] to the v[2] input array (pair of 4 bytes)
-         * v[] is padded with zeros if string doesn't align with 8 bytes
-         */
-        v[0] = 0;
-        v[1] = 0;
-
-        if (msHexDecode(in, (unsigned char *)v, 8) != 4)
-            last_block = MS_TRUE;
-        else
-        {
-            in += 8;
-            if (msHexDecode(in, (unsigned char *)(v+1), 8) != 4)
-                last_block = MS_TRUE;
-            else
-                in += 8;
-        }
+  ms_uint32 v[4], w[4];
+  const ms_uint32 *k;
+  int last_block = MS_FALSE;
 
-        /* Do the actual decryption */
-        decipher(v, w, k);
+  /* Casting the key this way is safe only as long as longs are 4 bytes
+   * on this platform */
+  assert(sizeof(ms_uint32) == 4);
+  k = (const ms_uint32 *) key;
 
-        /* Copy the results to out[] */
-        for(i=0; i<2; i++)
-        {
-            *out++ = (w[i] & 0x000000ff);
-            *out++ = (w[i] & 0x0000ff00) >> 8;
-            *out++ = (w[i] & 0x00ff0000) >> 16;
-            *out++ = (w[i] & 0xff000000) >> 24;
-        }
+  while(!last_block) {
+    int i;
+    /* decipher() takes v[2] (64 bits) as input.
+     * Copy bytes from in[] to the v[2] input array (pair of 4 bytes)
+     * v[] is padded with zeros if string doesn't align with 8 bytes
+     */
+    v[0] = 0;
+    v[1] = 0;
+
+    if (msHexDecode(in, (unsigned char *)v, 8) != 4)
+      last_block = MS_TRUE;
+    else {
+      in += 8;
+      if (msHexDecode(in, (unsigned char *)(v+1), 8) != 4)
+        last_block = MS_TRUE;
+      else
+        in += 8;
+    }
+
+    /* Do the actual decryption */
+    decipher(v, w, k);
 
-        if (*in == '\0')
-            last_block = MS_TRUE;
+    /* Copy the results to out[] */
+    for(i=0; i<2; i++) {
+      *out++ = (w[i] & 0x000000ff);
+      *out++ = (w[i] & 0x0000ff00) >> 8;
+      *out++ = (w[i] & 0x00ff0000) >> 16;
+      *out++ = (w[i] & 0xff000000) >> 24;
     }
 
-    /* Make sure output is 0-terminated */
-    *out = '\0';
+    if (*in == '\0')
+      last_block = MS_TRUE;
+  }
+
+  /* Make sure output is 0-terminated */
+  *out = '\0';
 }
 
 /**********************************************************************
  *                        msDecryptStringTokens()
  *
- * Returns a newly allocated string (to be msFree'd by the caller) in 
+ * Returns a newly allocated string (to be msFree'd by the caller) in
  * which all occurences of encrypted strings delimited by {...} have
  * been decrypted.
  *
@@ -426,206 +411,188 @@ void msDecryptStringWithKey(const unsigned char *key, const char *in, char *out)
 
 char *msDecryptStringTokens(mapObj *map, const char *in)
 {
-    char *outbuf, *out;
+  char *outbuf, *out;
+
+  if (map == NULL) {
+    msSetError(MS_MISCERR, "NULL MapObj.", "msLoadEncryptionKey()");
+    return NULL;
+  }
+
+  /* Start with a copy of the string. Decryption can only result in
+   * a string with the same or shorter length */
+  if ((outbuf = (char *)malloc((strlen(in)+1)*sizeof(char))) == NULL) {
+    msSetError(MS_MEMERR, NULL, "msDecryptStringTokens()");
+    return NULL;
+  }
+  out = outbuf;
+
+  while(*in != '\0') {
+    if (*in == '{') {
+      /* Possibly beginning of a token, look for closing bracket
+      ** and make sure all chars in between are valid hex encoding chars
+      */
+      const char *pszStart, *pszEnd;
+      int valid_token = MS_FALSE;
+
+      pszStart = in+1;
+      if ( (pszEnd = strchr(pszStart, '}')) != NULL &&
+           pszEnd - pszStart > 1) {
+        const char *pszTmp;
+        valid_token = MS_TRUE;
+        for(pszTmp = pszStart; pszTmp < pszEnd; pszTmp++) {
+          if (!isxdigit(*pszTmp)) {
+            valid_token = MS_FALSE;
+            break;
+          }
+        }
+      }
 
-    if (map == NULL)
-    {
-        msSetError(MS_MISCERR, "NULL MapObj.", "msLoadEncryptionKey()");
-        return NULL;
-    }
+      if (valid_token) {
+        /* Go ahead and decrypt the token */
+        char *pszTmp;
 
-    /* Start with a copy of the string. Decryption can only result in 
-     * a string with the same or shorter length */
-    if ((outbuf = (char *)malloc((strlen(in)+1)*sizeof(char))) == NULL)
-    {
-        msSetError(MS_MEMERR, NULL, "msDecryptStringTokens()");
-        return NULL;
-    }
-    out = outbuf;
-
-    while(*in != '\0')
-    {
-        if (*in == '{')
-        {
-            /* Possibly beginning of a token, look for closing bracket 
-            ** and make sure all chars in between are valid hex encoding chars
-            */
-            const char *pszStart, *pszEnd;
-            int valid_token = MS_FALSE;
-
-            pszStart = in+1;
-            if ( (pszEnd = strchr(pszStart, '}')) != NULL &&
-                 pszEnd - pszStart > 1)
-            {
-                const char *pszTmp;
-                valid_token = MS_TRUE;
-                for(pszTmp = pszStart; pszTmp < pszEnd; pszTmp++)
-                {
-                    if (!isxdigit(*pszTmp))
-                    {
-                        valid_token = MS_FALSE;
-                        break;
-                    }
-                }
-            }
-
-            if (valid_token)
-            {
-                /* Go ahead and decrypt the token */
-                char *pszTmp;
-
-                /* Make sure encryption key is loaded. We do this here instead
-                 * of at the beginning of the function to avoid loading the
-                 * key unless ready necessary. This is a very cheap call if
-                 * the key is already loaded
-                 */
-                if (msLoadEncryptionKey(map) != MS_SUCCESS)
-                    return NULL;
-
-                pszTmp = (char*)malloc( (pszEnd-pszStart+1)*sizeof(char));
-                strlcpy(pszTmp, pszStart, (pszEnd-pszStart)+1);
-
-                msDecryptStringWithKey(map->encryption_key, pszTmp, out);
-                
-                out += strlen(out);
-                in = pszEnd+1;
-                free(pszTmp);
-            }
-            else
-            {
-                /* Not a valid token, just copy the '{' and keep going */
-                *out++ = *in++;
-            }
-        }
-        else
-        {
-            /* Just copy any other chars */
-            *out++ = *in++;
-        }
+        /* Make sure encryption key is loaded. We do this here instead
+         * of at the beginning of the function to avoid loading the
+         * key unless ready necessary. This is a very cheap call if
+         * the key is already loaded
+         */
+        if (msLoadEncryptionKey(map) != MS_SUCCESS)
+          return NULL;
+
+        pszTmp = (char*)malloc( (pszEnd-pszStart+1)*sizeof(char));
+        strlcpy(pszTmp, pszStart, (pszEnd-pszStart)+1);
+
+        msDecryptStringWithKey(map->encryption_key, pszTmp, out);
+
+        out += strlen(out);
+        in = pszEnd+1;
+        free(pszTmp);
+      } else {
+        /* Not a valid token, just copy the '{' and keep going */
+        *out++ = *in++;
+      }
+    } else {
+      /* Just copy any other chars */
+      *out++ = *in++;
     }
-    *out = '\0';
+  }
+  *out = '\0';
 
-    return outbuf;
+  return outbuf;
 }
 
 
 #ifdef TEST_MAPCRYPTO
 
-/* Test for mapcrypto.c functions. To run these tests, use the following 
+/* Test for mapcrypto.c functions. To run these tests, use the following
 ** Makefile directive:
 
 test_mapcrypto: $(LIBMAP_STATIC) mapcrypto.c
-	$(CC) $(CFLAGS) mapcrypto.c -DTEST_MAPCRYPTO $(EXE_LDFLAGS) -o test_mapcrypto
+  $(CC) $(CFLAGS) mapcrypto.c -DTEST_MAPCRYPTO $(EXE_LDFLAGS) -o test_mapcrypto
 
 **
 */
 int main(int argc, char *argv[])
 {
-    const unsigned char bytes_in[] = {0x12, 0x34, 0xff, 0x00, 0x44, 0x22};
-    unsigned char bytes_out[8], encryption_key[MS_ENCRYPTION_KEY_SIZE*2+1];
-    char string_buf[256], string_buf2[256];
-    int numbytes = 0;
-
-    /* 
-    ** Test msHexEncode() 
-    */
-    msHexEncode(bytes_in, string_buf, 6);
-    printf("msHexEncode returned '%s'\n", string_buf);
-
-    /*
-    ** Test msHexDecode() 
-    */
-    memset(bytes_out, 0, 8);
-    numbytes = msHexDecode(string_buf, bytes_out, -1);
-    printf("msHexDecode(%s, -1) = %d, bytes_out = %x, %x, %x, %x, %x, %x, %x, %x\n", 
-           string_buf, numbytes, 
-           bytes_out[0], bytes_out[1], bytes_out[2], bytes_out[3], 
-           bytes_out[4], bytes_out[5], bytes_out[6], bytes_out[7]);
-
-    memset(bytes_out, 0, 8);
-    numbytes = msHexDecode(string_buf, bytes_out, 4);
-    printf("msHexDecode(%s, 4) = %d, bytes_out = %x, %x, %x, %x, %x, %x, %x, %x\n", 
-           string_buf, numbytes, 
-           bytes_out[0], bytes_out[1], bytes_out[2], bytes_out[3], 
-           bytes_out[4], bytes_out[5], bytes_out[6], bytes_out[7]);
-
-    memset(bytes_out, 0, 8);
-    numbytes = msHexDecode(string_buf, bytes_out, 20);
-    printf("msHexDecode(%s, 20) = %d, bytes_out = %x, %x, %x, %x, %x, %x, %x, %x\n", 
-           string_buf, numbytes, 
-           bytes_out[0], bytes_out[1], bytes_out[2], bytes_out[3], 
-           bytes_out[4], bytes_out[5], bytes_out[6], bytes_out[7]);
-
-    /*
-    ** Test loading encryption key 
-    */
-    if (msReadEncryptionKeyFromFile("/tmp/test.key", encryption_key) != MS_SUCCESS)
-    {
-        printf("msReadEncryptionKeyFromFile() = MS_FAILURE\n");
-        printf("Aborting tests!\n");
-        msWriteError(stderr);
-        return -1;
-    }
-    else
-    {
-        msHexEncode(encryption_key, string_buf, MS_ENCRYPTION_KEY_SIZE);
-        printf("msReadEncryptionKeyFromFile() returned '%s'\n", string_buf);
-    }
-
-    /*
-    ** Test Encryption/Decryption
-    */
-
-    /* First with an 8 bytes input string (test boundaries) */
-    msEncryptStringWithKey(encryption_key, "test1234", string_buf);
-    printf("msEncryptStringWithKey('test1234') returned '%s'\n", string_buf);
-
-    msDecryptStringWithKey(encryption_key, string_buf, string_buf2);
-    printf("msDecryptStringWithKey('%s') returned '%s'\n", string_buf, string_buf2);
-
-    /* Next with an 1 byte input string */
-    msEncryptStringWithKey(encryption_key, "t", string_buf);
-    printf("msEncryptStringWithKey('t') returned '%s'\n", string_buf);
-
-    msDecryptStringWithKey(encryption_key, string_buf, string_buf2);
-    printf("msDecryptStringWithKey('%s') returned '%s'\n", string_buf, string_buf2);
-
-    /* Next with an 12 bytes input string */
-    msEncryptStringWithKey(encryption_key, "test123456", string_buf);
-    printf("msEncryptStringWithKey('test123456') returned '%s'\n", string_buf);
-
-    msDecryptStringWithKey(encryption_key, string_buf, string_buf2);
-    printf("msDecryptStringWithKey('%s') returned '%s'\n", string_buf, string_buf2);
-
-    /*
-    ** Test decryption with tokens
-    */
-    {
-        char *pszBuf;
-        mapObj *map;
-        /* map = msNewMapObj(); */
-        map = msLoadMap("/tmp/test.map", NULL);
-
-        sprintf(string_buf2, "string with a {%s} encrypted token", string_buf);
-    
-        pszBuf = msDecryptStringTokens(map, string_buf2);
-        if (pszBuf == NULL)
-        {
-            printf("msDecryptStringTokens() failed.\n");
-            printf("Aborting tests!\n");
-            msWriteError(stderr);
-            return -1;
-        }
-        else
-        {
-            printf("msDecryptStringTokens('%s') returned '%s'\n", 
-                   string_buf2, pszBuf);
-        }
-        msFree(pszBuf);
-        msFreeMap(map);
+  const unsigned char bytes_in[] = {0x12, 0x34, 0xff, 0x00, 0x44, 0x22};
+  unsigned char bytes_out[8], encryption_key[MS_ENCRYPTION_KEY_SIZE*2+1];
+  char string_buf[256], string_buf2[256];
+  int numbytes = 0;
+
+  /*
+  ** Test msHexEncode()
+  */
+  msHexEncode(bytes_in, string_buf, 6);
+  printf("msHexEncode returned '%s'\n", string_buf);
+
+  /*
+  ** Test msHexDecode()
+  */
+  memset(bytes_out, 0, 8);
+  numbytes = msHexDecode(string_buf, bytes_out, -1);
+  printf("msHexDecode(%s, -1) = %d, bytes_out = %x, %x, %x, %x, %x, %x, %x, %x\n",
+         string_buf, numbytes,
+         bytes_out[0], bytes_out[1], bytes_out[2], bytes_out[3],
+         bytes_out[4], bytes_out[5], bytes_out[6], bytes_out[7]);
+
+  memset(bytes_out, 0, 8);
+  numbytes = msHexDecode(string_buf, bytes_out, 4);
+  printf("msHexDecode(%s, 4) = %d, bytes_out = %x, %x, %x, %x, %x, %x, %x, %x\n",
+         string_buf, numbytes,
+         bytes_out[0], bytes_out[1], bytes_out[2], bytes_out[3],
+         bytes_out[4], bytes_out[5], bytes_out[6], bytes_out[7]);
+
+  memset(bytes_out, 0, 8);
+  numbytes = msHexDecode(string_buf, bytes_out, 20);
+  printf("msHexDecode(%s, 20) = %d, bytes_out = %x, %x, %x, %x, %x, %x, %x, %x\n",
+         string_buf, numbytes,
+         bytes_out[0], bytes_out[1], bytes_out[2], bytes_out[3],
+         bytes_out[4], bytes_out[5], bytes_out[6], bytes_out[7]);
+
+  /*
+  ** Test loading encryption key
+  */
+  if (msReadEncryptionKeyFromFile("/tmp/test.key", encryption_key) != MS_SUCCESS) {
+    printf("msReadEncryptionKeyFromFile() = MS_FAILURE\n");
+    printf("Aborting tests!\n");
+    msWriteError(stderr);
+    return -1;
+  } else {
+    msHexEncode(encryption_key, string_buf, MS_ENCRYPTION_KEY_SIZE);
+    printf("msReadEncryptionKeyFromFile() returned '%s'\n", string_buf);
+  }
+
+  /*
+  ** Test Encryption/Decryption
+  */
+
+  /* First with an 8 bytes input string (test boundaries) */
+  msEncryptStringWithKey(encryption_key, "test1234", string_buf);
+  printf("msEncryptStringWithKey('test1234') returned '%s'\n", string_buf);
+
+  msDecryptStringWithKey(encryption_key, string_buf, string_buf2);
+  printf("msDecryptStringWithKey('%s') returned '%s'\n", string_buf, string_buf2);
+
+  /* Next with an 1 byte input string */
+  msEncryptStringWithKey(encryption_key, "t", string_buf);
+  printf("msEncryptStringWithKey('t') returned '%s'\n", string_buf);
+
+  msDecryptStringWithKey(encryption_key, string_buf, string_buf2);
+  printf("msDecryptStringWithKey('%s') returned '%s'\n", string_buf, string_buf2);
+
+  /* Next with an 12 bytes input string */
+  msEncryptStringWithKey(encryption_key, "test123456", string_buf);
+  printf("msEncryptStringWithKey('test123456') returned '%s'\n", string_buf);
+
+  msDecryptStringWithKey(encryption_key, string_buf, string_buf2);
+  printf("msDecryptStringWithKey('%s') returned '%s'\n", string_buf, string_buf2);
+
+  /*
+  ** Test decryption with tokens
+  */
+  {
+    char *pszBuf;
+    mapObj *map;
+    /* map = msNewMapObj(); */
+    map = msLoadMap("/tmp/test.map", NULL);
+
+    sprintf(string_buf2, "string with a {%s} encrypted token", string_buf);
+
+    pszBuf = msDecryptStringTokens(map, string_buf2);
+    if (pszBuf == NULL) {
+      printf("msDecryptStringTokens() failed.\n");
+      printf("Aborting tests!\n");
+      msWriteError(stderr);
+      return -1;
+    } else {
+      printf("msDecryptStringTokens('%s') returned '%s'\n",
+             string_buf2, pszBuf);
     }
+    msFree(pszBuf);
+    msFreeMap(map);
+  }
 
-    return 0;
+  return 0;
 }
 
 
diff --git a/mapdebug.c b/mapdebug.c
index a363f83..7bc817b 100644
--- a/mapdebug.c
+++ b/mapdebug.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -48,16 +48,17 @@
 #include <windows.h> /* OutputDebugStringA() */
 #endif
 
-MS_CVSID("$Id$")
+
 
 
 #ifndef USE_THREAD
 
 debugInfoObj *msGetDebugInfoObj()
 {
-    static debugInfoObj debuginfo = {MS_DEBUGLEVEL_ERRORSONLY,
-                                     MS_DEBUGMODE_OFF, NULL, NULL };
-    return &debuginfo;
+  static debugInfoObj debuginfo = {MS_DEBUGLEVEL_ERRORSONLY,
+                                   MS_DEBUGMODE_OFF, NULL, NULL
+                                  };
+  return &debuginfo;
 }
 
 #else
@@ -66,61 +67,57 @@ static debugInfoObj *debuginfo_list = NULL;
 
 debugInfoObj *msGetDebugInfoObj()
 {
-    debugInfoObj *link;
-    int          thread_id;
-    debugInfoObj *ret_obj;
-    
-    msAcquireLock( TLOCK_DEBUGOBJ );
-    
-    thread_id = msGetThreadId();
+  debugInfoObj *link;
+  int          thread_id;
+  debugInfoObj *ret_obj;
 
-    /* find link for this thread */
-    
-    for( link = debuginfo_list; 
-         link != NULL && link->thread_id != thread_id
-             && link->next != NULL && link->next->thread_id != thread_id;
-         link = link->next ) {}
+  msAcquireLock( TLOCK_DEBUGOBJ );
 
-    /* If the target thread link is already at the head of the list were ok */
-    if( debuginfo_list != NULL && debuginfo_list->thread_id == thread_id )
-    {
-    }
+  thread_id = msGetThreadId();
 
-    /* We don't have one ... initialize one. */
-    else if( link == NULL || link->next == NULL )
-    {
-        debugInfoObj *new_link;
-
-        new_link = (debugInfoObj *) malloc(sizeof(debugInfoObj));
-        if (new_link != NULL) 
-        {
-            new_link->next = debuginfo_list;
-            new_link->thread_id = thread_id;
-            new_link->global_debug_level = MS_DEBUGLEVEL_ERRORSONLY;
-            new_link->debug_mode = MS_DEBUGMODE_OFF;
-            new_link->errorfile = NULL;
-            new_link->fp = NULL;
-        } else
-            msSetError(MS_MEMERR, "Out of memory allocating %u bytes.\n", "msGetDebugInfoObj()", sizeof(debugInfoObj));
-
-        debuginfo_list = new_link;
-    }
+  /* find link for this thread */
 
-    /* If the link is not already at the head of the list, promote it */
-    else if( link != NULL && link->next != NULL )
-    {
-        debugInfoObj *target = link->next;
+  for( link = debuginfo_list;
+       link != NULL && link->thread_id != thread_id
+       && link->next != NULL && link->next->thread_id != thread_id;
+       link = link->next ) {}
 
-        link->next = link->next->next;
-        target->next = debuginfo_list;
-        debuginfo_list = target;
-    }
+  /* If the target thread link is already at the head of the list were ok */
+  if( debuginfo_list != NULL && debuginfo_list->thread_id == thread_id ) {
+  }
+
+  /* We don't have one ... initialize one. */
+  else if( link == NULL || link->next == NULL ) {
+    debugInfoObj *new_link;
+
+    new_link = (debugInfoObj *) malloc(sizeof(debugInfoObj));
+    if (new_link != NULL) {
+      new_link->next = debuginfo_list;
+      new_link->thread_id = thread_id;
+      new_link->global_debug_level = MS_DEBUGLEVEL_ERRORSONLY;
+      new_link->debug_mode = MS_DEBUGMODE_OFF;
+      new_link->errorfile = NULL;
+      new_link->fp = NULL;
+    } else
+      msSetError(MS_MEMERR, "Out of memory allocating %u bytes.\n", "msGetDebugInfoObj()", sizeof(debugInfoObj));
+
+    debuginfo_list = new_link;
+  }
+
+  /* If the link is not already at the head of the list, promote it */
+  else if( link != NULL && link->next != NULL ) {
+    debugInfoObj *target = link->next;
 
-    ret_obj = debuginfo_list;
+    link->next = link->next->next;
+    target->next = debuginfo_list;
+    debuginfo_list = target;
+  }
+
+  ret_obj = debuginfo_list;
 
-    msReleaseLock( TLOCK_DEBUGOBJ ); 
+  msReleaseLock( TLOCK_DEBUGOBJ );
 
-    return ret_obj;
+  return ret_obj;
 }
 #endif
 
@@ -129,7 +126,7 @@ debugInfoObj *msGetDebugInfoObj()
 **
 ** Set output target, ready to write to it, open file if necessary
 **
-** If pszRelToPath != NULL then we will try to make the value relative to 
+** If pszRelToPath != NULL then we will try to make the value relative to
 ** this path if it is not absolute already and it's not one of the special
 ** values (stderr, stdout, windowsdebug)
 **
@@ -137,73 +134,59 @@ debugInfoObj *msGetDebugInfoObj()
 */
 int msSetErrorFile(const char *pszErrorFile, const char *pszRelToPath)
 {
-    char extended_path[MS_MAXPATHLEN];
-    debugInfoObj *debuginfo = msGetDebugInfoObj();
-
-    if (strcmp(pszErrorFile, "stderr") != 0 &&
-        strcmp(pszErrorFile, "stdout") != 0 &&
-        strcmp(pszErrorFile, "windowsdebug") != 0)
-    {
-        /* Try to make the path relative */
-        if(msBuildPath(extended_path, pszRelToPath, pszErrorFile) == NULL)
-            return MS_FAILURE;
-        pszErrorFile = extended_path;
-    }
+  char extended_path[MS_MAXPATHLEN];
+  debugInfoObj *debuginfo = msGetDebugInfoObj();
+
+  if (strcmp(pszErrorFile, "stderr") != 0 &&
+      strcmp(pszErrorFile, "stdout") != 0 &&
+      strcmp(pszErrorFile, "windowsdebug") != 0) {
+    /* Try to make the path relative */
+    if(msBuildPath(extended_path, pszRelToPath, pszErrorFile) == NULL)
+      return MS_FAILURE;
+    pszErrorFile = extended_path;
+  }
 
-    if (debuginfo && debuginfo->errorfile && pszErrorFile &&
-        strcmp(debuginfo->errorfile, pszErrorFile) == 0)
-    {
-        /* Nothing to do, already writing to the right place */
-        return MS_SUCCESS;
-    }
+  if (debuginfo && debuginfo->errorfile && pszErrorFile &&
+      strcmp(debuginfo->errorfile, pszErrorFile) == 0) {
+    /* Nothing to do, already writing to the right place */
+    return MS_SUCCESS;
+  }
 
-    /* Close current output file if any */
-    msCloseErrorFile();
+  /* Close current output file if any */
+  msCloseErrorFile();
 
-    /* NULL or empty target will just close current output and return */
-    if (pszErrorFile == NULL || *pszErrorFile == '\0')
-        return MS_SUCCESS;  
+  /* NULL or empty target will just close current output and return */
+  if (pszErrorFile == NULL || *pszErrorFile == '\0')
+    return MS_SUCCESS;
 
-    if (strcmp(pszErrorFile, "stderr") == 0)
-    {
-        debuginfo->fp = stderr;
-        debuginfo->errorfile = msStrdup(pszErrorFile);
-        debuginfo->debug_mode = MS_DEBUGMODE_STDERR;
-#if defined(NEED_NONBLOCKING_STDERR) && !defined(USE_MAPIO) && !defined(_WIN32)
-        fcntl(fileno(stderr), F_SETFL, O_NONBLOCK);
-        nonblocking_set = 1;
-#endif
-    }
-    else if (strcmp(pszErrorFile, "stdout") == 0)
-    {
-        debuginfo->fp = stdout;
-        debuginfo->errorfile = msStrdup(pszErrorFile);
-        debuginfo->debug_mode = MS_DEBUGMODE_STDOUT;
-    }
-    else if (strcmp(pszErrorFile, "windowsdebug") == 0)
-    {
+  if (strcmp(pszErrorFile, "stderr") == 0) {
+    debuginfo->fp = stderr;
+    debuginfo->errorfile = msStrdup(pszErrorFile);
+    debuginfo->debug_mode = MS_DEBUGMODE_STDERR;
+  } else if (strcmp(pszErrorFile, "stdout") == 0) {
+    debuginfo->fp = stdout;
+    debuginfo->errorfile = msStrdup(pszErrorFile);
+    debuginfo->debug_mode = MS_DEBUGMODE_STDOUT;
+  } else if (strcmp(pszErrorFile, "windowsdebug") == 0) {
 #ifdef _WIN32
-        debuginfo->errorfile = msStrdup(pszErrorFile);
-        debuginfo->fp = NULL;
-        debuginfo->debug_mode = MS_DEBUGMODE_WINDOWSDEBUG;
+    debuginfo->errorfile = msStrdup(pszErrorFile);
+    debuginfo->fp = NULL;
+    debuginfo->debug_mode = MS_DEBUGMODE_WINDOWSDEBUG;
 #else
-        msSetError(MS_MISCERR, "'MS_ERRORFILE windowsdebug' is available only on Windows platforms.", "msSetErrorFile()");
-        return MS_FAILURE;
+    msSetError(MS_MISCERR, "'MS_ERRORFILE windowsdebug' is available only on Windows platforms.", "msSetErrorFile()");
+    return MS_FAILURE;
 #endif
+  } else {
+    debuginfo->fp = fopen(pszErrorFile, "a");
+    if (debuginfo->fp == NULL) {
+      msSetError(MS_MISCERR, "Failed to open MS_ERRORFILE %s", "msSetErrorFile()", pszErrorFile);
+      return MS_FAILURE;
     }
-    else 
-    {
-        debuginfo->fp = fopen(pszErrorFile, "a");
-        if (debuginfo->fp == NULL)
-        {
-            msSetError(MS_MISCERR, "Failed to open MS_ERRORFILE %s", "msSetErrorFile()", pszErrorFile);
-            return MS_FAILURE;
-        }
-        debuginfo->errorfile = msStrdup(pszErrorFile);
-        debuginfo->debug_mode = MS_DEBUGMODE_FILE;
-    }
+    debuginfo->errorfile = msStrdup(pszErrorFile);
+    debuginfo->debug_mode = MS_DEBUGMODE_FILE;
+  }
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 /* msCloseErrorFile()
@@ -212,24 +195,23 @@ int msSetErrorFile(const char *pszErrorFile, const char *pszRelToPath)
 */
 void msCloseErrorFile()
 {
-    debugInfoObj *debuginfo = msGetDebugInfoObj();
+  debugInfoObj *debuginfo = msGetDebugInfoObj();
 
-    if (debuginfo && debuginfo->debug_mode != MS_DEBUGMODE_OFF)
-    {
-        if (debuginfo->fp && debuginfo->debug_mode == MS_DEBUGMODE_FILE)
-            fclose(debuginfo->fp);
+  if (debuginfo && debuginfo->debug_mode != MS_DEBUGMODE_OFF) {
+    if (debuginfo->fp && debuginfo->debug_mode == MS_DEBUGMODE_FILE)
+      fclose(debuginfo->fp);
 
-        if (debuginfo->fp && (debuginfo->debug_mode == MS_DEBUGMODE_STDERR ||
-                              debuginfo->debug_mode == MS_DEBUGMODE_STDOUT))
-            fflush(debuginfo->fp); /* just flush stderr or stdout */
+    if (debuginfo->fp && (debuginfo->debug_mode == MS_DEBUGMODE_STDERR ||
+                          debuginfo->debug_mode == MS_DEBUGMODE_STDOUT))
+      fflush(debuginfo->fp); /* just flush stderr or stdout */
 
-        debuginfo->fp = NULL;
+    debuginfo->fp = NULL;
 
-        msFree(debuginfo->errorfile);
-        debuginfo->errorfile = NULL;
+    msFree(debuginfo->errorfile);
+    debuginfo->errorfile = NULL;
 
-        debuginfo->debug_mode = MS_DEBUGMODE_OFF;
-    }
+    debuginfo->debug_mode = MS_DEBUGMODE_OFF;
+  }
 }
 
 
@@ -242,35 +224,35 @@ void msCloseErrorFile()
 */
 const char *msGetErrorFile()
 {
-    debugInfoObj *debuginfo = msGetDebugInfoObj();
+  debugInfoObj *debuginfo = msGetDebugInfoObj();
 
-    if (debuginfo)
-        return debuginfo->errorfile;
-    
-    return NULL;
+  if (debuginfo)
+    return debuginfo->errorfile;
+
+  return NULL;
 }
 
 /* Set/Get the current global debug level value, used as default value for
-** new map and layer objects and to control msDebug() calls outside of 
+** new map and layer objects and to control msDebug() calls outside of
 ** the context of mapObj or layerObj.
 **
 */
 void msSetGlobalDebugLevel(int level)
 {
-    debugInfoObj *debuginfo = msGetDebugInfoObj();
+  debugInfoObj *debuginfo = msGetDebugInfoObj();
 
-    if (debuginfo)
-        debuginfo->global_debug_level = (debugLevel)level;
+  if (debuginfo)
+    debuginfo->global_debug_level = (debugLevel)level;
 }
 
 debugLevel msGetGlobalDebugLevel()
 {
-    debugInfoObj *debuginfo = msGetDebugInfoObj();
+  debugInfoObj *debuginfo = msGetDebugInfoObj();
 
-    if (debuginfo)
-        return debuginfo->global_debug_level;
+  if (debuginfo)
+    return debuginfo->global_debug_level;
 
-    return MS_DEBUGLEVEL_ERRORSONLY;
+  return MS_DEBUGLEVEL_ERRORSONLY;
 }
 
 
@@ -282,18 +264,17 @@ debugLevel msGetGlobalDebugLevel()
 */
 int msDebugInitFromEnv()
 {
-    const char *val;
+  const char *val;
 
-    if( (val=getenv( "MS_ERRORFILE" )) != NULL )
-    {
-        if ( msSetErrorFile(val, NULL) != MS_SUCCESS )
-            return MS_FAILURE;
-    }
-    
-    if( (val=getenv( "MS_DEBUGLEVEL" )) != NULL )
-        msSetGlobalDebugLevel(atoi(val));
+  if( (val=getenv( "MS_ERRORFILE" )) != NULL ) {
+    if ( msSetErrorFile(val, NULL) != MS_SUCCESS )
+      return MS_FAILURE;
+  }
 
-    return MS_SUCCESS;
+  if( (val=getenv( "MS_DEBUGLEVEL" )) != NULL )
+    msSetGlobalDebugLevel(atoi(val));
+
+  return MS_SUCCESS;
 }
 
 
@@ -303,38 +284,35 @@ int msDebugInitFromEnv()
 */
 void msDebugCleanup()
 {
-    /* make sure file is closed */
-    msCloseErrorFile();
+  /* make sure file is closed */
+  msCloseErrorFile();
 
 #ifdef USE_THREAD
   {
-      int  thread_id = msGetThreadId();
-      debugInfoObj *link;
-
-      msAcquireLock( TLOCK_DEBUGOBJ );
-      
-      /* find link for this thread */
-    
-      for( link = debuginfo_list; 
-           link != NULL && link->thread_id != thread_id
-               && link->next != NULL && link->next->thread_id != thread_id;
-           link = link->next ) {}
-      
-      if( link->thread_id == thread_id )
-      { 
-          /* presumably link is at head of list.  */
-          if( debuginfo_list == link )
-              debuginfo_list = link->next;
-
-          free( link );
-      }
-      else if( link->next != NULL && link->next->thread_id == thread_id )
-      {
-          debugInfoObj *next_link = link->next;
-          link->next = link->next->next;
-          free( next_link );
-      }
-      msReleaseLock( TLOCK_DEBUGOBJ );
+    int  thread_id = msGetThreadId();
+    debugInfoObj *link;
+
+    msAcquireLock( TLOCK_DEBUGOBJ );
+
+    /* find link for this thread */
+
+    for( link = debuginfo_list;
+         link != NULL && link->thread_id != thread_id
+         && link->next != NULL && link->next->thread_id != thread_id;
+         link = link->next ) {}
+
+    if( link->thread_id == thread_id ) {
+      /* presumably link is at head of list.  */
+      if( debuginfo_list == link )
+        debuginfo_list = link->next;
+
+      free( link );
+    } else if( link->next != NULL && link->next->thread_id == thread_id ) {
+      debugInfoObj *next_link = link->next;
+      link->next = link->next->next;
+      free( next_link );
+    }
+    msReleaseLock( TLOCK_DEBUGOBJ );
   }
 #endif
 
@@ -342,54 +320,52 @@ void msDebugCleanup()
 
 /* msDebug()
 **
-** Outputs/logs messages to the MS_ERRORFILE if one is set 
+** Outputs/logs messages to the MS_ERRORFILE if one is set
 ** (see msSetErrorFile())
 **
 */
 void msDebug( const char * pszFormat, ... )
 {
-    va_list args;
-    debugInfoObj *debuginfo = msGetDebugInfoObj();
+  va_list args;
+  debugInfoObj *debuginfo = msGetDebugInfoObj();
 
-    if (debuginfo == NULL || debuginfo->debug_mode == MS_DEBUGMODE_OFF)
-        return;  /* Don't waste time here! */
+  if (debuginfo == NULL || debuginfo->debug_mode == MS_DEBUGMODE_OFF)
+    return;  /* Don't waste time here! */
 
-    if (debuginfo->fp)
-    {
-        /* Writing to a stdio file handle */
+  if (debuginfo->fp) {
+    /* Writing to a stdio file handle */
 
 #if defined(USE_FASTCGI)
-        /* It seems the FastCGI stuff inserts a timestamp anyways, so  */
-        /* we might as well skip this one if writing to stderr w/ FastCGI. */
-        if (debuginfo->debug_mode != MS_DEBUGMODE_STDERR)
+    /* It seems the FastCGI stuff inserts a timestamp anyways, so  */
+    /* we might as well skip this one if writing to stderr w/ FastCGI. */
+    if (debuginfo->debug_mode != MS_DEBUGMODE_STDERR)
 #endif
-        {
-            struct mstimeval tv;
-            time_t t;
-            msGettimeofday(&tv, NULL);
-            t = tv.tv_sec;
-            msIO_fprintf(debuginfo->fp, "[%s].%ld ", 
-                         msStringChop(ctime(&t)), (long)tv.tv_usec);
-        }
-
-        va_start(args, pszFormat);
-        msIO_vfprintf(debuginfo->fp, pszFormat, args);
-        va_end(args);
+    {
+      struct mstimeval tv;
+      time_t t;
+      msGettimeofday(&tv, NULL);
+      t = tv.tv_sec;
+      msIO_fprintf(debuginfo->fp, "[%s].%ld ",
+                   msStringChop(ctime(&t)), (long)tv.tv_usec);
     }
+
+    va_start(args, pszFormat);
+    msIO_vfprintf(debuginfo->fp, pszFormat, args);
+    va_end(args);
+  }
 #ifdef _WIN32
-    else if (debuginfo->debug_mode == MS_DEBUGMODE_WINDOWSDEBUG)
-    {
-        /* Writing to Windows Debug Console */
+  else if (debuginfo->debug_mode == MS_DEBUGMODE_WINDOWSDEBUG) {
+    /* Writing to Windows Debug Console */
 
-        char szMessage[MESSAGELENGTH];
+    char szMessage[MESSAGELENGTH];
 
-        va_start(args, pszFormat);
-        vsnprintf( szMessage, MESSAGELENGTH, pszFormat, args );
-        va_end(args);
+    va_start(args, pszFormat);
+    vsnprintf( szMessage, MESSAGELENGTH, pszFormat, args );
+    va_end(args);
 
-        szMessage[MESSAGELENGTH-1] = '\0';
-        OutputDebugStringA(szMessage);
-    }
+    szMessage[MESSAGELENGTH-1] = '\0';
+    OutputDebugStringA(szMessage);
+  }
 #endif
 
 }
diff --git a/mapdraw.c b/mapdraw.c
index 839168e..ea6a0d4 100644
--- a/mapdraw.c
+++ b/mapdraw.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -28,35 +28,45 @@
  *****************************************************************************/
 
 #include <assert.h>
+#include <math.h>
 #include "mapserver.h"
 #include "maptime.h"
 #include "mapcopy.h"
 
-MS_CVSID("$Id$")
 
+
+#ifdef USE_GD
 /*
  * Functions to reset any pen (color index) values previously set. Used primarily to reset things when
  * using MapScript to create multiple images. How the pen values are set is irrelevant (definitely output
  * format type specific) which is why this function is here instead of the GD, PDF or SWF source files.
 */
-void msClearLayerPenValues(layerObj *layer) {
-  int i, j;  
+void msClearLayerPenValues(layerObj *layer)
+{
+  int i, j, k;
 
   for(i=0; i<layer->numclasses; i++) {
-    layer->class[i]->label.color.pen = MS_PEN_UNSET; /* set in MSXXDrawText function */
-    layer->class[i]->label.outlinecolor.pen = MS_PEN_UNSET;
-    layer->class[i]->label.shadowcolor.pen = MS_PEN_UNSET;
-    /* TODO: deal with label styles here */
+    for(j=0; j<layer->class[i]->numlabels; j++) {
+      layer->class[i]->labels[j]->color.pen = MS_PEN_UNSET; /* set in MSXXDrawText function */
+      layer->class[i]->labels[j]->outlinecolor.pen = MS_PEN_UNSET;
+      layer->class[i]->labels[j]->shadowcolor.pen = MS_PEN_UNSET;
+      for(k=0; k<layer->class[i]->labels[j]->numstyles; k++) {
+        layer->class[i]->labels[j]->styles[k]->backgroundcolor.pen = MS_PEN_UNSET; /* set in various symbol drawing functions */
+        layer->class[i]->labels[j]->styles[k]->color.pen = MS_PEN_UNSET;
+        layer->class[i]->labels[j]->styles[k]->outlinecolor.pen = MS_PEN_UNSET;
+      }
+    }
 
     for(j=0; j<layer->class[i]->numstyles; j++) {
       layer->class[i]->styles[j]->backgroundcolor.pen = MS_PEN_UNSET; /* set in various symbol drawing functions */
       layer->class[i]->styles[j]->color.pen = MS_PEN_UNSET;
-      layer->class[i]->styles[j]->outlinecolor.pen = MS_PEN_UNSET; 
+      layer->class[i]->styles[j]->outlinecolor.pen = MS_PEN_UNSET;
     }
   }
 }
 
-void msClearScalebarPenValues(scalebarObj *scalebar) {
+void msClearScalebarPenValues(scalebarObj *scalebar)
+{
   if (scalebar) {
     scalebar->color.pen = MS_PEN_UNSET;
     scalebar->backgroundcolor.pen = MS_PEN_UNSET;
@@ -70,7 +80,8 @@ void msClearScalebarPenValues(scalebarObj *scalebar) {
   }
 }
 
-void msClearLegendPenValues(legendObj *legend) {
+void msClearLegendPenValues(legendObj *legend)
+{
   if (legend) {
     legend->outlinecolor.pen = MS_PEN_UNSET;
     legend->imagecolor.pen = MS_PEN_UNSET;
@@ -82,7 +93,8 @@ void msClearLegendPenValues(legendObj *legend) {
   }
 }
 
-void msClearReferenceMapPenValues(referenceMapObj *referencemap) {
+void msClearReferenceMapPenValues(referenceMapObj *referencemap)
+{
   if (referencemap) {
     referencemap->outlinecolor.pen = MS_PEN_UNSET;
     referencemap->color.pen = MS_PEN_UNSET;
@@ -90,13 +102,15 @@ void msClearReferenceMapPenValues(referenceMapObj *referencemap) {
 }
 
 
-void msClearQueryMapPenValues(queryMapObj *querymap) {
+void msClearQueryMapPenValues(queryMapObj *querymap)
+{
   if (querymap)
     querymap->color.pen = MS_PEN_UNSET;
 }
 
 
-void msClearPenValues(mapObj *map) {
+void msClearPenValues(mapObj *map)
+{
   int i;
 
   for(i=0; i<map->numlayers; i++)
@@ -106,8 +120,9 @@ void msClearPenValues(mapObj *map) {
   msClearScalebarPenValues(&(map->scalebar));
   msClearReferenceMapPenValues(&(map->reference));
   msClearQueryMapPenValues(&(map->querymap));
-  
+
 }
+#endif
 
 /* msPrepareImage()
  *
@@ -117,135 +132,135 @@ void msClearPenValues(mapObj *map) {
  * msMapRestoreRealExtent() once they are done with the image.
  * This should be set to MS_TRUE only when called from msDrawMap(), see bug 945.
  */
-imageObj *msPrepareImage(mapObj *map, int allow_nonsquare) 
+imageObj *msPrepareImage(mapObj *map, int allow_nonsquare)
 {
-    int i, status;
-    imageObj *image=NULL;
-    double geo_cellsize;
+  int i, status;
+  imageObj *image=NULL;
+  double geo_cellsize;
 
-    if(map->width == -1 || map->height == -1) {
-        msSetError(MS_MISCERR, "Image dimensions not specified.", "msPrepareImage()");
-        return(NULL);
+  if(map->width == -1 || map->height == -1) {
+    msSetError(MS_MISCERR, "Image dimensions not specified.", "msPrepareImage()");
+    return(NULL);
+  }
+
+  msInitLabelCache(&(map->labelcache)); /* this clears any previously allocated cache */
+
+  /* clear any previously created mask layer images */
+  for(i=0; i<map->numlayers; i++) {
+    if(GET_LAYER(map, i)->maskimage) {
+      msFreeImage(GET_LAYER(map, i)->maskimage);
+      GET_LAYER(map, i)->maskimage = NULL;
     }
+  }
 
-    msInitLabelCache(&(map->labelcache)); /* this clears any previously allocated cache */
+  status = msValidateContexts(map); /* make sure there are no recursive REQUIRES or LABELREQUIRES expressions */
+  if(status != MS_SUCCESS) return NULL;
 
-    status = msValidateContexts(map); /* make sure there are no recursive REQUIRES or LABELREQUIRES expressions */
-    if(status != MS_SUCCESS) return NULL;
+  if(!map->outputformat) {
+    msSetError(MS_GDERR, "Map outputformat not set!", "msPrepareImage()");
+    return(NULL);
+  } else if (MS_RENDERER_PLUGIN(map->outputformat)) {
+    rendererVTableObj *renderer = map->outputformat->vtable;
+    colorObj *bg = &map->imagecolor;
+    map->imagecolor.alpha=255;
+    if(map->transparent == MS_TRUE) {
+      /* don't set the image color */
+      bg = NULL;
+    }
+    image = renderer->createImage(map->width, map->height, map->outputformat,bg);
+    if (image == NULL)
+      return(NULL);
+    image->format = map->outputformat;
+    image->format->refcount++;
+    image->width = map->width;
+    image->height = map->height;
+
+    image->resolution = map->resolution;
+    image->resolutionfactor = map->resolution/map->defresolution;
+    if (map->web.imagepath)
+      image->imagepath = msStrdup(map->web.imagepath);
+    if (map->web.imageurl)
+      image->imageurl = msStrdup(map->web.imageurl);
+
+  } else if( MS_RENDERER_IMAGEMAP(map->outputformat) ) {
+    image = msImageCreateIM(map->width, map->height, map->outputformat,
+                            map->web.imagepath, map->web.imageurl, map->resolution, map->defresolution);
+  } else if( MS_RENDERER_RAWDATA(map->outputformat) ) {
+    image = msImageCreate(map->width, map->height, map->outputformat,
+                          map->web.imagepath, map->web.imageurl, map->resolution, map->defresolution, &map->imagecolor);
+  } else {
+    image = NULL;
+  }
 
-    if(!map->outputformat) {
-        msSetError(MS_GDERR, "Map outputformat not set!", "msPrepareImage()");
-        return(NULL);
-    }
-    else if (MS_RENDERER_PLUGIN(map->outputformat)) {
-        rendererVTableObj *renderer = map->outputformat->vtable;
-        colorObj *bg = &map->imagecolor;
-        map->imagecolor.alpha=255;
-        if(map->transparent == MS_TRUE) {
-           //don't set the image color
-           bg = NULL;
-        }
-        image = renderer->createImage(map->width, map->height, map->outputformat,bg);
-        if (image == NULL)
-            return(NULL);
-        image->format = map->outputformat;
-        image->format->refcount++;
-        image->width = map->width;
-        image->height = map->height;
-
-        image->resolution = map->resolution;
-        image->resolutionfactor = map->resolution/map->defresolution;
-        if (map->web.imagepath)
-            image->imagepath = msStrdup(map->web.imagepath);
-        if (map->web.imageurl)
-            image->imageurl = msStrdup(map->web.imageurl);
-
-	}
-    else if( MS_RENDERER_IMAGEMAP(map->outputformat) )
-    {
-        image = msImageCreateIM(map->width, map->height, map->outputformat, 
-				map->web.imagepath, map->web.imageurl, map->resolution, map->defresolution);        
-        if( image != NULL ) msImageInitIM( image );
-    }
-    else if( MS_RENDERER_RAWDATA(map->outputformat) )
-    {
-        image = msImageCreate(map->width, map->height, map->outputformat,
-                              map->web.imagepath, map->web.imageurl, map->resolution, map->defresolution, &map->imagecolor);
-    }
-    else
-    {
-        image = NULL;
-    }
-  
-    if(!image) {
-        msSetError(MS_GDERR, "Unable to initialize image.", "msPrepareImage()");
-        return(NULL);
-    }
+  if(!image) {
+    msSetError(MS_GDERR, "Unable to initialize image.", "msPrepareImage()");
+    return(NULL);
+  }
 
-    /*
-     * If we want to support nonsquare pixels, note that now, otherwise
-     * adjust the extent size to have square pixels.
-     *
-     * If allow_nonsquare is set to MS_TRUE then the caller should call
-     * msMapRestoreRealExtent() once they are done with the image.
-     * This should be set to MS_TRUE only when called from msDrawMap(), see bug 945.
-     */
-    if( allow_nonsquare && msTestConfigOption( map, "MS_NONSQUARE", MS_FALSE ) )
-    {
-        double cellsize_x = (map->extent.maxx - map->extent.minx)/map->width;
-        double cellsize_y = (map->extent.maxy - map->extent.miny)/map->height;
-
-        if( cellsize_y != 0.0 
-            && (fabs(cellsize_x/cellsize_y) > 1.00001
-                || fabs(cellsize_x/cellsize_y) < 0.99999) )
-        {
-            map->gt.need_geotransform = MS_TRUE;
-            if (map->debug)
-                msDebug( "msDrawMap(): kicking into non-square pixel preserving mode.\n" );
-        }
-        map->cellsize = (cellsize_x*0.5 + cellsize_y*0.5);
-    }
-    else
-        map->cellsize = msAdjustExtent(&(map->extent),map->width,map->height);
+  /*
+   * If we want to support nonsquare pixels, note that now, otherwise
+   * adjust the extent size to have square pixels.
+   *
+   * If allow_nonsquare is set to MS_TRUE then the caller should call
+   * msMapRestoreRealExtent() once they are done with the image.
+   * This should be set to MS_TRUE only when called from msDrawMap(), see bug 945.
+   */
+  if( allow_nonsquare && msTestConfigOption( map, "MS_NONSQUARE", MS_FALSE ) ) {
+    double cellsize_x = (map->extent.maxx - map->extent.minx)/map->width;
+    double cellsize_y = (map->extent.maxy - map->extent.miny)/map->height;
+
+    if( cellsize_y != 0.0
+        && (fabs(cellsize_x/cellsize_y) > 1.00001
+            || fabs(cellsize_x/cellsize_y) < 0.99999) ) {
+      map->gt.need_geotransform = MS_TRUE;
+      if (map->debug)
+        msDebug( "msDrawMap(): kicking into non-square pixel preserving mode.\n" );
+    }
+    map->cellsize = (cellsize_x*0.5 + cellsize_y*0.5);
+  } else
+    map->cellsize = msAdjustExtent(&(map->extent),map->width,map->height);
+
+  status = msCalculateScale(map->extent,map->units,map->width,map->height, map->resolution, &map->scaledenom);
+  if(status != MS_SUCCESS) {
+    msFreeImage(image);
+    return(NULL);
+  }
 
-    status = msCalculateScale(map->extent,map->units,map->width,map->height, map->resolution, &map->scaledenom);
-    if(status != MS_SUCCESS) {
-        msFreeImage(image);
-        return(NULL);
-    }
+  /* update geotransform based on adjusted extent. */
+  msMapComputeGeotransform( map );
 
-   /* update geotransform based on adjusted extent. */
-    msMapComputeGeotransform( map );
+  /* Do we need to fake out stuff for rotated support? */
+  if( map->gt.need_geotransform )
+    msMapSetFakedExtent( map );
 
-    /* Do we need to fake out stuff for rotated support? */
-    if( map->gt.need_geotransform )
-        msMapSetFakedExtent( map );
+  /* We will need a cellsize that represents a real georeferenced */
+  /* coordinate cellsize here, so compute it from saved extents.   */
 
-    /* We will need a cellsize that represents a real georeferenced */
-    /* coordinate cellsize here, so compute it from saved extents.   */
+  geo_cellsize = map->cellsize;
+  if( map->gt.need_geotransform == MS_TRUE ) {
+    double cellsize_x = (map->saved_extent.maxx - map->saved_extent.minx)
+                        / map->width;
+    double cellsize_y = (map->saved_extent.maxy - map->saved_extent.miny)
+                        / map->height;
 
-    geo_cellsize = map->cellsize;
-    if( map->gt.need_geotransform == MS_TRUE ) {
-        double cellsize_x = (map->saved_extent.maxx - map->saved_extent.minx)
-            / map->width;
-        double cellsize_y = (map->saved_extent.maxy - map->saved_extent.miny)
-            / map->height;
+    geo_cellsize = sqrt(cellsize_x*cellsize_x + cellsize_y*cellsize_y)
+                   / sqrt(2.0);
+  }
 
-        geo_cellsize = sqrt(cellsize_x*cellsize_x + cellsize_y*cellsize_y)
-            / sqrt(2.0);
-    } 
+  /* compute layer scale factors now */
+  for(i=0; i<map->numlayers; i++) {
+    if(GET_LAYER(map, i)->sizeunits != MS_PIXELS)
+      GET_LAYER(map, i)->scalefactor = (msInchesPerUnit(GET_LAYER(map, i)->sizeunits,0)/msInchesPerUnit(map->units,0)) / geo_cellsize;
+    else if(GET_LAYER(map, i)->symbolscaledenom > 0 && map->scaledenom > 0)
+      GET_LAYER(map, i)->scalefactor = GET_LAYER(map, i)->symbolscaledenom/map->scaledenom*map->resolution/map->defresolution;
+    else
+      GET_LAYER(map, i)->scalefactor = map->resolution/map->defresolution;
+  }
 
-    /* compute layer scale factors now */
-    for(i=0;i<map->numlayers; i++) {
-      if(GET_LAYER(map, i)->sizeunits != MS_PIXELS)
-        GET_LAYER(map, i)->scalefactor = (msInchesPerUnit(GET_LAYER(map, i)->sizeunits,0)/msInchesPerUnit(map->units,0)) / geo_cellsize;
-      else if(GET_LAYER(map, i)->symbolscaledenom > 0 && map->scaledenom > 0)
-        GET_LAYER(map, i)->scalefactor = GET_LAYER(map, i)->symbolscaledenom/map->scaledenom*map->resolution/map->defresolution;
-      else
-        GET_LAYER(map, i)->scalefactor = map->resolution/map->defresolution;
-    }
+  image->refpt.x = MS_MAP2IMAGE_X_IC_DBL(0, map->extent.minx, 1.0/map->cellsize);
+  image->refpt.y = MS_MAP2IMAGE_Y_IC_DBL(0, map->extent.maxy, 1.0/map->cellsize);
 
-    return image;
+  return image;
 }
 
 
@@ -254,7 +269,7 @@ imageObj *msPrepareImage(mapObj *map, int allow_nonsquare)
  * The type of the image created is based on the imagetype parameter in the map file.
  *
  * mapObj *map - map object loaded in MapScript or via a mapfile to use
- * int querymap - is this map the result of a query operation, MS_TRUE|MS_FALSE 
+ * int querymap - is this map the result of a query operation, MS_TRUE|MS_FALSE
 */
 imageObj *msDrawMap(mapObj *map, int querymap)
 {
@@ -288,9 +303,9 @@ imageObj *msDrawMap(mapObj *map, int querymap)
   }
 
   if( map->debug >= MS_DEBUGLEVEL_DEBUG )
-      msDebug( "msDrawMap(): rendering using outputformat named %s (%s).\n",
-               map->outputformat->name, 
-               map->outputformat->driver );
+    msDebug( "msDrawMap(): rendering using outputformat named %s (%s).\n",
+             map->outputformat->name,
+             map->outputformat->driver );
 
 #if defined(USE_WMS_LYR) || defined(USE_WFS_LYR)
 
@@ -299,14 +314,14 @@ imageObj *msDrawMap(mapObj *map, int querymap)
 
   /* How many OWS (WMS/WFS) layers do we have to draw?
    * Note: numOWSLayers is the number of actual layers and numOWSRequests is
-   * the number of HTTP requests which could be lower if multiple layers 
+   * the number of HTTP requests which could be lower if multiple layers
    * are merged into the same request.
    */
   numOWSLayers=0;
   for(i=0; i<map->numlayers; i++) {
-    if(map->layerorder[i] != -1 && 
-       msLayerIsVisible(map, GET_LAYER(map,map->layerorder[i])))
-        numOWSLayers++;
+    if(map->layerorder[i] != -1 &&
+        msLayerIsVisible(map, GET_LAYER(map,map->layerorder[i])))
+      numOWSLayers++;
   }
 
 
@@ -331,7 +346,7 @@ imageObj *msDrawMap(mapObj *map, int querymap)
 
 #ifdef USE_WMS_LYR
       if(lp->connectiontype == MS_WMS) {
-        if(msPrepareWMSLayerRequest(map->layerorder[i], map, lp, lastconnectiontype, &sLastWMSParams, pasOWSReqInfo, &numOWSRequests) == MS_FAILURE) {
+        if(msPrepareWMSLayerRequest(map->layerorder[i], map, lp, 1, lastconnectiontype, &sLastWMSParams, 0, 0, 0, NULL, pasOWSReqInfo, &numOWSRequests) == MS_FAILURE) {
           msFreeWmsParamsObj(&sLastWMSParams);
           msFreeImage(image);
           msFree(pasOWSReqInfo);
@@ -355,7 +370,7 @@ imageObj *msDrawMap(mapObj *map, int querymap)
     }
 
 #ifdef USE_WMS_LYR
-  msFreeWmsParamsObj(&sLastWMSParams);
+    msFreeWmsParamsObj(&sLastWMSParams);
 #endif
   } /* if numOWSLayers > 0 */
 
@@ -367,7 +382,7 @@ imageObj *msDrawMap(mapObj *map, int querymap)
 
   if(map->debug >= MS_DEBUGLEVEL_TUNING) {
     msGettimeofday(&endtime, NULL);
-    msDebug("msDrawMap(): WMS/WFS set-up and query, %.3fs\n", 
+    msDebug("msDrawMap(): WMS/WFS set-up and query, %.3fs\n",
             (endtime.tv_sec+endtime.tv_usec/1.0e6)-
             (starttime.tv_sec+starttime.tv_usec/1.0e6) );
   }
@@ -388,16 +403,16 @@ imageObj *msDrawMap(mapObj *map, int querymap)
       if(!msLayerIsVisible(map, lp)) continue;
 
       if(lp->connectiontype == MS_WMS) {
-#ifdef USE_WMS_LYR 
+#ifdef USE_WMS_LYR
         if(MS_RENDERER_PLUGIN(image->format) || MS_RENDERER_RAWDATA(image->format))
           status = msDrawWMSLayerLow(map->layerorder[i], pasOWSReqInfo, numOWSRequests,  map, lp, image);
         else {
           msSetError(MS_WMSCONNERR, "Output format '%s' doesn't support WMS layers.", "msDrawMap()", image->format->name);
           status = MS_FAILURE;
         }
-                
+
         if(status == MS_FAILURE) {
-          msSetError(MS_WMSCONNERR, 
+          msSetError(MS_WMSCONNERR,
                      "Failed to draw WMS layer named '%s'. This most likely happened because "
                      "the remote WMS server returned an invalid image, and XML exception "
                      "or another unexpected result in response to the GetMap request. Also check "
@@ -436,7 +451,7 @@ imageObj *msDrawMap(mapObj *map, int querymap)
 
     if(map->debug >= MS_DEBUGLEVEL_TUNING || lp->debug >= MS_DEBUGLEVEL_TUNING) {
       msGettimeofday(&endtime, NULL);
-      msDebug("msDrawMap(): Layer %d (%s), %.3fs\n", 
+      msDebug("msDrawMap(): Layer %d (%s), %.3fs\n",
               map->layerorder[i], lp->name?lp->name:"(null)",
               (endtime.tv_sec+endtime.tv_usec/1.0e6)-
               (starttime.tv_sec+starttime.tv_usec/1.0e6) );
@@ -452,8 +467,8 @@ imageObj *msDrawMap(mapObj *map, int querymap)
 
 
     if(MS_SUCCESS != msEmbedScalebar(map, image)) {
-    	msFreeImage( image );
-    	return NULL;
+      msFreeImage( image );
+      return NULL;
     }
 
 
@@ -461,13 +476,11 @@ imageObj *msDrawMap(mapObj *map, int querymap)
       msMapSetFakedExtent(map);
   }
 
-  if(map->legend.status == MS_EMBED && !map->legend.postlabelcache)
-  {
-      if( msEmbedLegend(map, image) != MS_SUCCESS )
-      {
-          msFreeImage( image );
-          return NULL;
-      }
+  if(map->legend.status == MS_EMBED && !map->legend.postlabelcache) {
+    if( msEmbedLegend(map, image) != MS_SUCCESS ) {
+      msFreeImage( image );
+      return NULL;
+    }
   }
 
   if(map->debug >= MS_DEBUGLEVEL_TUNING) msGettimeofday(&starttime, NULL);
@@ -485,7 +498,7 @@ imageObj *msDrawMap(mapObj *map, int querymap)
 
   if(map->debug >= MS_DEBUGLEVEL_TUNING) {
     msGettimeofday(&endtime, NULL);
-    msDebug("msDrawMap(): Drawing Label Cache, %.3fs\n", 
+    msDebug("msDrawMap(): Drawing Label Cache, %.3fs\n",
             (endtime.tv_sec+endtime.tv_usec/1.0e6)-
             (starttime.tv_sec+starttime.tv_usec/1.0e6) );
   }
@@ -500,7 +513,7 @@ imageObj *msDrawMap(mapObj *map, int querymap)
     if(map->debug >= MS_DEBUGLEVEL_TUNING || lp->debug >= MS_DEBUGLEVEL_TUNING) msGettimeofday(&starttime, NULL);
 
     if(lp->connectiontype == MS_WMS) {
-#ifdef USE_WMS_LYR 
+#ifdef USE_WMS_LYR
       if(MS_RENDERER_PLUGIN(image->format) || MS_RENDERER_RAWDATA(image->format))
         status = msDrawWMSLayerLow(map->layerorder[i], pasOWSReqInfo, numOWSRequests, map, lp, image);
 
@@ -527,14 +540,14 @@ imageObj *msDrawMap(mapObj *map, int querymap)
 
     if(map->debug >= MS_DEBUGLEVEL_TUNING || lp->debug >= MS_DEBUGLEVEL_TUNING) {
       msGettimeofday(&endtime, NULL);
-      msDebug("msDrawMap(): Layer %d (%s), %.3fs\n", 
+      msDebug("msDrawMap(): Layer %d (%s), %.3fs\n",
               map->layerorder[i], lp->name?lp->name:"(null)",
               (endtime.tv_sec+endtime.tv_usec/1.0e6)-
               (starttime.tv_sec+starttime.tv_usec/1.0e6) );
     }
 
   }
-  
+
   /* Do we need to fake out stuff for rotated support? */
   /* This really needs to be done on every preceeding exit point too... */
   if(map->gt.need_geotransform)
@@ -542,24 +555,24 @@ imageObj *msDrawMap(mapObj *map, int querymap)
 
   if(map->legend.status == MS_EMBED && map->legend.postlabelcache)
     msEmbedLegend(map, image); /* TODO */
-  
+
   if(map->scalebar.status == MS_EMBED && map->scalebar.postlabelcache) {
-	
-	  /* We need to temporarily restore the original extent for drawing */
-	  /* the scalebar as it uses the extent to recompute cellsize. */
-	  if(map->gt.need_geotransform)
-		msMapRestoreRealExtent(map);
-	
-	
-	  if(MS_SUCCESS != msEmbedScalebar(map, image)) {
-		msFreeImage( image );
-		return NULL;
-	  }
-	
-	
-	  if(map->gt.need_geotransform)
-		msMapSetFakedExtent(map);
-	}
+
+    /* We need to temporarily restore the original extent for drawing */
+    /* the scalebar as it uses the extent to recompute cellsize. */
+    if(map->gt.need_geotransform)
+      msMapRestoreRealExtent(map);
+
+
+    if(MS_SUCCESS != msEmbedScalebar(map, image)) {
+      msFreeImage( image );
+      return NULL;
+    }
+
+
+    if(map->gt.need_geotransform)
+      msMapSetFakedExtent(map);
+  }
 
 #if defined(USE_WMS_LYR) || defined(USE_WFS_LYR)
   /* Cleanup WMS/WFS Request stuff */
@@ -571,7 +584,7 @@ imageObj *msDrawMap(mapObj *map, int querymap)
 
   if(map->debug >= MS_DEBUGLEVEL_TUNING) {
     msGettimeofday(&mapendtime, NULL);
-    msDebug("msDrawMap() total time: %.3fs\n", 
+    msDebug("msDrawMap() total time: %.3fs\n",
             (mapendtime.tv_sec+mapendtime.tv_usec/1.0e6)-
             (mapstarttime.tv_sec+mapstarttime.tv_usec/1.0e6) );
   }
@@ -581,7 +594,7 @@ imageObj *msDrawMap(mapObj *map, int querymap)
 
 /*
  * Test whether a layer should be drawn or not in the current map view and
- * at the current scale.  
+ * at the current scale.
  * Returns TRUE if layer is visible, FALSE if not.
 */
 int msLayerIsVisible(mapObj *map, layerObj *layer)
@@ -594,19 +607,19 @@ int msLayerIsVisible(mapObj *map, layerObj *layer)
   if(layer->type == MS_LAYER_QUERY || layer->type == MS_LAYER_TILEINDEX) return(MS_FALSE);
   if((layer->status != MS_ON) && (layer->status != MS_DEFAULT)) return(MS_FALSE);
 
-  /* Only return MS_FALSE if it is definitely false. Sometimes it will return MS_UNKNOWN, which we 
+  /* Only return MS_FALSE if it is definitely false. Sometimes it will return MS_UNKNOWN, which we
   ** consider true, for this use case (it might be visible, try and draw it, see what happens). */
   if ( msExtentsOverlap(map, layer) == MS_FALSE ) {
     if( layer->debug >= MS_DEBUGLEVEL_V ) {
       msDebug("msLayerIsVisible(): Skipping layer (%s) because LAYER.EXTENT does not intersect MAP.EXTENT\n", layer->name);
     }
-    return(MS_FALSE);  
+    return(MS_FALSE);
   }
-  
+
   if(msEvalContext(map, layer, layer->requires) == MS_FALSE) return(MS_FALSE);
 
   if(map->scaledenom > 0) {
-    
+
     /* layer scale boundaries should be checked first */
     if((layer->maxscaledenom > 0) && (map->scaledenom > layer->maxscaledenom)) {
       if( layer->debug >= MS_DEBUGLEVEL_V ) {
@@ -630,7 +643,7 @@ int msLayerIsVisible(mapObj *map, layerObj *layer)
           continue; /* can skip this one, next class */
 
         break; /* can't skip this class (or layer for that matter) */
-      } 
+      }
       if(i == layer->numclasses) {
         if( layer->debug >= MS_DEBUGLEVEL_V ) {
           msDebug("msLayerIsVisible(): Skipping layer (%s) because no CLASS in the layer is in-scale for this MAP scale\n", layer->name);
@@ -642,18 +655,18 @@ int msLayerIsVisible(mapObj *map, layerObj *layer)
   }
 
   if (layer->maxscaledenom <= 0 && layer->minscaledenom <= 0) {
-      if((layer->maxgeowidth > 0) && ((map->extent.maxx - map->extent.minx) > layer->maxgeowidth)) {
-        if( layer->debug >= MS_DEBUGLEVEL_V ) {
-          msDebug("msLayerIsVisible(): Skipping layer (%s) because LAYER width is much smaller than map width\n", layer->name);
-        }
-        return(MS_FALSE);
+    if((layer->maxgeowidth > 0) && ((map->extent.maxx - map->extent.minx) > layer->maxgeowidth)) {
+      if( layer->debug >= MS_DEBUGLEVEL_V ) {
+        msDebug("msLayerIsVisible(): Skipping layer (%s) because LAYER width is much smaller than map width\n", layer->name);
       }
-      if((layer->mingeowidth > 0) && ((map->extent.maxx - map->extent.minx) < layer->mingeowidth)) {
-        if( layer->debug >= MS_DEBUGLEVEL_V ) {
-          msDebug("msLayerIsVisible(): Skipping layer (%s) because LAYER width is much larger than map width\n", layer->name);
-        }
-        return(MS_FALSE);
+      return(MS_FALSE);
+    }
+    if((layer->mingeowidth > 0) && ((map->extent.maxx - map->extent.minx) < layer->mingeowidth)) {
+      if( layer->debug >= MS_DEBUGLEVEL_V ) {
+        msDebug("msLayerIsVisible(): Skipping layer (%s) because LAYER width is much larger than map width\n", layer->name);
       }
+      return(MS_FALSE);
+    }
   }
 
   return MS_TRUE;  /* All tests passed.  Layer is visible. */
@@ -668,9 +681,10 @@ int msDrawLayer(mapObj *map, layerObj *layer, imageObj *image)
   int retcode=MS_SUCCESS;
   int originalopacity = layer->opacity;
   const char *alternativeFomatString = NULL;
+  layerObj *maskLayer = NULL;
 
   if(!msLayerIsVisible(map, layer))
-    return MS_SUCCESS;  
+    return MS_SUCCESS;
 
   if(layer->opacity == 0) return MS_SUCCESS; /* layer is completely transparent, skip it */
 
@@ -678,46 +692,112 @@ int msDrawLayer(mapObj *map, layerObj *layer, imageObj *image)
      layer->project true to recheck projection needs (Bug #673) */
   layer->project = MS_TRUE;
 
+  if(layer->mask) {
+    int maskLayerIdx;
+    /* render the mask layer in its own imageObj */
+    if(!MS_IMAGE_RENDERER(image)->supports_pixel_buffer) {
+      msSetError(MS_MISCERR, "Layer (%s) references references a mask layer, but the selected renderer does not support them", "msDrawLayer()",
+                 layer->name);
+      return (MS_FAILURE);
+    }
+    maskLayerIdx = msGetLayerIndex(map,layer->mask);
+    if(maskLayerIdx == -1) {
+      msSetError(MS_MISCERR, "Layer (%s) references unknown mask layer (%s)", "msDrawLayer()",
+                 layer->name,layer->mask);
+      return (MS_FAILURE);
+    }
+    maskLayer = GET_LAYER(map, maskLayerIdx);
+    if(!maskLayer->maskimage) {
+      int i;
+      int origstatus, origlabelcache;
+      altFormat =  msSelectOutputFormat(map, "png24");
+      msInitializeRendererVTable(altFormat);
+      /* TODO: check the png24 format hasn't been tampered with, i.e. it's agg */
+      maskLayer->maskimage= msImageCreate(image->width, image->height,altFormat,
+                                          image->imagepath, image->imageurl, map->resolution, map->defresolution, NULL);
+      if (!maskLayer->maskimage) {
+        msSetError(MS_MISCERR, "Unable to initialize mask image.", "msDrawLayer()");
+        return (MS_FAILURE);
+      }
+
+      /*
+       * force the masked layer to status on, and turn off the labelcache so that
+       * eventual labels are added to the temporary image instead of being added
+       * to the labelcache
+       */
+      origstatus = maskLayer->status;
+      origlabelcache = maskLayer->labelcache;
+      maskLayer->status = MS_ON;
+      maskLayer->labelcache = MS_OFF;
+
+      /* draw the mask layer in the temporary image */
+      retcode = msDrawLayer(map, maskLayer, maskLayer->maskimage);
+      maskLayer->status = origstatus;
+      maskLayer->labelcache = origlabelcache;
+      if(retcode != MS_SUCCESS) {
+        return MS_FAILURE;
+      }
+      /*
+       * hack to work around bug #3834: if we have use an alternate renderer, the symbolset may contain
+       * symbols that reference it. We want to remove those references before the altFormat is destroyed
+       * to avoid a segfault and/or a leak, and so the the main renderer doesn't pick the cache up thinking
+       * it's for him.
+       */
+      for(i=0; i<map->symbolset.numsymbols; i++) {
+        if (map->symbolset.symbol[i]!=NULL) {
+          symbolObj *s = map->symbolset.symbol[i];
+          if(s->renderer == MS_IMAGE_RENDERER(maskLayer->maskimage)) {
+            MS_IMAGE_RENDERER(maskLayer->maskimage)->freeSymbol(s);
+            s->renderer = NULL;
+          }
+        }
+      }
+      /* set the imagetype from the original outputformat back (it was removed by msSelectOutputFormat() */
+      msFree(map->imagetype);
+      map->imagetype = msStrdup(image->format->name);
+    }
+
+  }
+  altFormat = NULL;
   /* inform the rendering device that layer draw is starting. */
   msImageStartLayer(map, layer, image);
 
+
   /*check if an alternative renderer should be used for this layer*/
   alternativeFomatString = msLayerGetProcessingKey( layer, "RENDERER");
-  if (MS_RENDERER_PLUGIN(image_draw->format) && alternativeFomatString!=NULL && 
-      (altFormat=  msSelectOutputFormat(map, alternativeFomatString)))
-  {
-      rendererVTableObj *renderer=NULL; 
-      msInitializeRendererVTable(altFormat);
-
-      image_draw = msImageCreate(image->width, image->height,
-                                 altFormat, image->imagepath, image->imageurl, map->resolution, map->defresolution, &map->imagecolor);
-      renderer = MS_IMAGE_RENDERER(image_draw);
-      renderer->startLayer(image_draw,map,layer);
-  }
-  else if (MS_RENDERER_PLUGIN(image_draw->format)) {
-	    rendererVTableObj *renderer = MS_IMAGE_RENDERER(image_draw);
-		if (layer->opacity > 0 && layer->opacity < 100) {
-			if (!renderer->supports_transparent_layers) {
-				image_draw = msImageCreate(image->width, image->height,
-						image->format, image->imagepath, image->imageurl, map->resolution, map->defresolution, NULL);
-				if (!image_draw) {
-					msSetError(MS_MISCERR, "Unable to initialize temporary transparent image.",
-							"msDrawLayer()");
-					return (MS_FAILURE);
-				}
-				/* set opacity to full, as the renderer should be rendering a fully opaque image */
-				layer->opacity=100;
-				renderer->startLayer(image_draw,map,layer);
-			} 
-		}
-  }
-  /* 
-  ** redirect procesing of some layer types. 
+  if (MS_RENDERER_PLUGIN(image_draw->format) && alternativeFomatString!=NULL &&
+      (altFormat=  msSelectOutputFormat(map, alternativeFomatString))) {
+    rendererVTableObj *renderer=NULL;
+    msInitializeRendererVTable(altFormat);
+
+    image_draw = msImageCreate(image->width, image->height,
+                               altFormat, image->imagepath, image->imageurl, map->resolution, map->defresolution, &map->imagecolor);
+    renderer = MS_IMAGE_RENDERER(image_draw);
+    renderer->startLayer(image_draw,map,layer);
+  } else if (MS_RENDERER_PLUGIN(image_draw->format)) {
+    rendererVTableObj *renderer = MS_IMAGE_RENDERER(image_draw);
+    if (layer->mask || (layer->opacity > 0 && layer->opacity < 100)) {
+      if (!renderer->supports_transparent_layers) {
+        image_draw = msImageCreate(image->width, image->height,
+                                   image->format, image->imagepath, image->imageurl, map->resolution, map->defresolution, NULL);
+        if (!image_draw) {
+          msSetError(MS_MISCERR, "Unable to initialize temporary transparent image.",
+                     "msDrawLayer()");
+          return (MS_FAILURE);
+        }
+        /* set opacity to full, as the renderer should be rendering a fully opaque image */
+        layer->opacity=100;
+        renderer->startLayer(image_draw,map,layer);
+      }
+    }
+  }
+  /*
+  ** redirect procesing of some layer types.
   */
   if(layer->connectiontype == MS_WMS) {
 #ifdef USE_WMS_LYR
     retcode = msDrawWMSLayer(map, layer, image_draw);
-#else  
+#else
     retcode = MS_FAILURE;
 #endif
   } else if(layer->type == MS_LAYER_RASTER) {
@@ -728,53 +808,92 @@ int msDrawLayer(mapObj *map, layerObj *layer, imageObj *image)
     retcode = msDrawVectorLayer(map, layer, image_draw);
   }
 
-  if (altFormat)
-  {
-      rendererVTableObj *renderer = MS_IMAGE_RENDERER(image);
-      rendererVTableObj *altrenderer = MS_IMAGE_RENDERER(image_draw);
-      rasterBufferObj rb;
-      int i;
-      memset(&rb,0,sizeof(rasterBufferObj));
+  if (altFormat) {
+    rendererVTableObj *renderer = MS_IMAGE_RENDERER(image);
+    rendererVTableObj *altrenderer = MS_IMAGE_RENDERER(image_draw);
+    rasterBufferObj rb;
+    int i;
+    memset(&rb,0,sizeof(rasterBufferObj));
 
-      altrenderer->endLayer(image_draw,map,layer);
+    altrenderer->endLayer(image_draw,map,layer);
 
-      altrenderer->getRasterBufferHandle(image_draw,&rb);
-      renderer->mergeRasterBuffer(image,&rb,layer->opacity*0.01,0,0,0,0,rb.width,rb.height);  
-      
-      /* 
-       * hack to work around bug #3834: if we have use an alternate renderer, the symbolset may contain
-       * symbols that reference it. We want to remove those references before the altFormat is destroyed
-       * to avoid a segfault and/or a leak, and so the the main renderer doesn't pick the cache up thinking
-       * it's for him.
-       */
-      for(i=0; i<map->symbolset.numsymbols; i++) {
-         if (map->symbolset.symbol[i]!=NULL) {
-            symbolObj *s = map->symbolset.symbol[i];
-            if(s->renderer == altrenderer) {
-	            altrenderer->freeSymbol(s);
-               s->renderer = NULL;
+    altrenderer->getRasterBufferHandle(image_draw,&rb);
+    renderer->mergeRasterBuffer(image,&rb,layer->opacity*0.01,0,0,0,0,rb.width,rb.height);
+
+    /*
+     * hack to work around bug #3834: if we have use an alternate renderer, the symbolset may contain
+     * symbols that reference it. We want to remove those references before the altFormat is destroyed
+     * to avoid a segfault and/or a leak, and so the the main renderer doesn't pick the cache up thinking
+     * it's for him.
+     */
+    for(i=0; i<map->symbolset.numsymbols; i++) {
+      if (map->symbolset.symbol[i]!=NULL) {
+        symbolObj *s = map->symbolset.symbol[i];
+        if(s->renderer == altrenderer) {
+          altrenderer->freeSymbol(s);
+          s->renderer = NULL;
+        }
+      }
+    }
+    msFreeImage(image_draw);
+
+    /* set the imagetype from the original outputformat back (it was removed by msSelectOutputFormat() */
+    msFree(map->imagetype);
+    map->imagetype = msStrdup(image->format->name);
+  } else if( image != image_draw) {
+    rendererVTableObj *renderer = MS_IMAGE_RENDERER(image_draw);
+    rasterBufferObj rb;
+    memset(&rb,0,sizeof(rasterBufferObj));
+
+    renderer->endLayer(image_draw,map,layer);
+    layer->opacity = originalopacity;
+
+    renderer->getRasterBufferHandle(image_draw,&rb);
+    if(maskLayer && maskLayer->maskimage) {
+      rasterBufferObj mask;
+      unsigned int row,col;
+      memset(&mask,0,sizeof(rasterBufferObj));
+      MS_IMAGE_RENDERER(maskLayer->maskimage)->getRasterBufferHandle(maskLayer->maskimage,&mask);
+      /* modify the pixels of the overlay */
+
+      if(rb.type == MS_BUFFER_BYTE_RGBA) {
+        for(row=0; row<rb.height; row++) {
+          unsigned char *ma,*a,*r,*g,*b;
+          r=rb.data.rgba.r+row*rb.data.rgba.row_step;
+          g=rb.data.rgba.g+row*rb.data.rgba.row_step;
+          b=rb.data.rgba.b+row*rb.data.rgba.row_step;
+          a=rb.data.rgba.a+row*rb.data.rgba.row_step;
+          ma=mask.data.rgba.a+row*mask.data.rgba.row_step;
+          for(col=0; col<rb.width; col++) {
+            if(*ma == 0) {
+              *a = *r = *g = *b = 0;
             }
-         }
+            a+=rb.data.rgba.pixel_step;
+            r+=rb.data.rgba.pixel_step;
+            g+=rb.data.rgba.pixel_step;
+            b+=rb.data.rgba.pixel_step;
+            ma+=mask.data.rgba.pixel_step;
+          }
+        }
+#ifdef USE_GD
+      } else if(rb.type == MS_BUFFER_GD) {
+        for(row=0; row<rb.height; row++) {
+          unsigned char *ma;
+          ma=mask.data.rgba.a+row*mask.data.rgba.row_step;
+          for(col=0; col<rb.width; col++) {
+            if(*ma == 0) {
+              gdImageSetPixel(rb.data.gd_img,col,row,0);
+            }
+            ma+=mask.data.rgba.pixel_step;
+          }
+        }
+#endif
       }
-      msFreeImage(image_draw);
-
-      /* set the imagetype from the original outputformat back (it was removed by msSelectOutputFormat() */
-      msFree(map->imagetype);
-      map->imagetype = msStrdup(image->format->name);
+    }
+    renderer->mergeRasterBuffer(image,&rb,layer->opacity*0.01,0,0,0,0,rb.width,rb.height);
+    msFreeImage(image_draw);
   }
-  else if( image != image_draw) {
-	  rendererVTableObj *renderer = MS_IMAGE_RENDERER(image_draw);
-	  rasterBufferObj rb;
-	  memset(&rb,0,sizeof(rasterBufferObj));
-
-	  renderer->endLayer(image_draw,map,layer);
-	  layer->opacity = originalopacity;
 
-	  renderer->getRasterBufferHandle(image_draw,&rb);
-	  renderer->mergeRasterBuffer(image,&rb,layer->opacity*0.01,0,0,0,0,rb.width,rb.height);  
-	  msFreeImage(image_draw);
-  }
-  
   msImageEndLayer(map,layer,image);
   return(retcode);
 }
@@ -782,6 +901,7 @@ int msDrawLayer(mapObj *map, layerObj *layer, imageObj *image)
 int msDrawVectorLayer(mapObj *map, layerObj *layer, imageObj *image)
 {
   int         status, retcode=MS_SUCCESS;
+  int         drawmode=MS_DRAWMODE_FEATURES;
   char        annotate=MS_TRUE;
   shapeObj    shape;
   rectObj     searchrect;
@@ -796,8 +916,8 @@ int msDrawVectorLayer(mapObj *map, layerObj *layer, imageObj *image)
 
   if (image)
     maxfeatures=msLayerGetMaxFeaturesToDraw(layer, image->format);
-  
-  //TODO TBT: draw as raster layer in vector renderers
+
+  /* TODO TBT: draw as raster layer in vector renderers */
 
   annotate = msEvalContext(map, layer, layer->labelrequires);
   if(map->scaledenom > 0) {
@@ -805,21 +925,23 @@ int msDrawVectorLayer(mapObj *map, layerObj *layer, imageObj *image)
     if((layer->labelminscaledenom != -1) && (map->scaledenom < layer->labelminscaledenom)) annotate = MS_FALSE;
   }
 
+#ifdef USE_GD
   /* reset layer pen values just in case the map has been previously processed */
   msClearLayerPenValues(layer);
-  
+#endif
+
   /* open this layer */
   status = msLayerOpen(layer);
   if(status != MS_SUCCESS) return MS_FAILURE;
-  
+
   /* build item list */
-    status = msLayerWhichItems(layer, MS_FALSE, NULL);
+  status = msLayerWhichItems(layer, MS_FALSE, NULL);
 
   if(status != MS_SUCCESS) {
     msLayerClose(layer);
     return MS_FAILURE;
   }
-  
+
   /* identify target shapes */
   if(layer->transform == MS_TRUE)
     searchrect = map->extent;
@@ -828,12 +950,12 @@ int msDrawVectorLayer(mapObj *map, layerObj *layer, imageObj *image)
     searchrect.maxx = map->width-1;
     searchrect.maxy = map->height-1;
   }
-  
+
 #ifdef USE_PROJ
   if((map->projection.numargs > 0) && (layer->projection.numargs > 0))
     msProjectRect(&map->projection, &layer->projection, &searchrect); /* project the searchrect to source coords */
 #endif
-    
+
   status = msLayerWhichShapes(layer, searchrect, MS_FALSE);
   if(status == MS_DONE) { /* no overlap */
     msLayerClose(layer);
@@ -842,126 +964,131 @@ int msDrawVectorLayer(mapObj *map, layerObj *layer, imageObj *image)
     msLayerClose(layer);
     return MS_FAILURE;
   }
-  
+
   /* step through the target shapes */
   msInitShape(&shape);
-  
+
   nclasses = 0;
   classgroup = NULL;
-  if (layer->classgroup && layer->numclasses > 0)
-      classgroup = msAllocateValidClassGroups(layer, &nclasses);
+  if(layer->classgroup && layer->numclasses > 0)
+    classgroup = msAllocateValidClassGroups(layer, &nclasses);
+
+  if(layer->minfeaturesize > 0)
+    minfeaturesize = Pix2LayerGeoref(map, layer, layer->minfeaturesize);
 
-  if (layer->minfeaturesize > 0)
-      minfeaturesize = Pix2LayerGeoref(map, layer, layer->minfeaturesize);
-  
   while((status = msLayerNextShape(layer, &shape)) == MS_SUCCESS) {
 
-      /* Check if the shape size is ok to be drawn */
-      if ((shape.type == MS_SHAPE_LINE || shape.type == MS_SHAPE_POLYGON) && (minfeaturesize > 0) && 
-          (msShapeCheckSize(&shape, minfeaturesize) == MS_FALSE))
-      {
-          if( layer->debug >= MS_DEBUGLEVEL_V )
-              msDebug("msDrawVectorLayer(): Skipping shape (%d) because LAYER::MINFEATURESIZE is bigger than shape size\n", shape.index);
-          msFreeShape(&shape);
-          continue;
-      }
-      
-      shape.classindex = msShapeGetClass(layer, map, &shape, classgroup, nclasses);
+    /* Check if the shape size is ok to be drawn */
+    if((shape.type == MS_SHAPE_LINE || shape.type == MS_SHAPE_POLYGON) && (minfeaturesize > 0) && (msShapeCheckSize(&shape, minfeaturesize) == MS_FALSE)) {
+      if(layer->debug >= MS_DEBUGLEVEL_V)
+        msDebug("msDrawVectorLayer(): Skipping shape (%d) because LAYER::MINFEATURESIZE is bigger than shape size\n", shape.index);
+      msFreeShape(&shape);
+      continue;
+    }
+
+    shape.classindex = msShapeGetClass(layer, map, &shape, classgroup, nclasses);
     if((shape.classindex == -1) || (layer->class[shape.classindex]->status == MS_OFF)) {
-       msFreeShape(&shape);
-       continue;
+      msFreeShape(&shape);
+      continue;
     }
-  
-    if (maxfeatures >=0 && featuresdrawn >= maxfeatures)
-    {
-        status = MS_DONE;
-        break;
+
+    if(maxfeatures >=0 && featuresdrawn >= maxfeatures) {
+      status = MS_DONE;
+      break;
     }
     featuresdrawn++;
 
     cache = MS_FALSE;
-    if(layer->type == MS_LAYER_LINE && (layer->class[shape.classindex]->numstyles > 1 || (layer->class[shape.classindex]->numstyles == 1 && layer->class[shape.classindex]->styles[0]->outlinewidth>0))) {
+    if(layer->type == MS_LAYER_LINE && (layer->class[shape.classindex]->numstyles > 1 || (layer->class[shape.classindex]->numstyles == 1 && layer->class[shape.classindex]->styles[0]->outlinewidth > 0))) {
       int i;
       cache = MS_TRUE; /* only line layers with multiple styles need be cached (I don't think POLYLINE layers need caching - SDL) */
 
       /* we can't handle caching with attribute binding other than for the first style (#3976) */
-      for(i=1;i<layer->class[shape.classindex]->numstyles; i++) {
+      for(i=1; i<layer->class[shape.classindex]->numstyles; i++) {
         if(layer->class[shape.classindex]->styles[i]->numbindings > 0) cache = MS_FALSE;
       }
     }
-         
+
     /* With 'STYLEITEM AUTO', we will have the datasource fill the class' */
     /* style parameters for this shape. */
     if(layer->styleitem) {
-        if(strcasecmp(layer->styleitem, "AUTO") == 0) {
-            if (msLayerGetAutoStyle(map, layer, layer->class[shape.classindex], &shape) != MS_SUCCESS) {
-                retcode = MS_FAILURE;
-                break;
-            }
+      if(strcasecmp(layer->styleitem, "AUTO") == 0) {
+        if(msLayerGetAutoStyle(map, layer, layer->class[shape.classindex], &shape) != MS_SUCCESS) {
+          retcode = MS_FAILURE;
+          break;
         }
-        else {
-            /* Generic feature style handling as per RFC-61 */
-            if (msLayerGetFeatureStyle(map, layer, layer->class[shape.classindex], &shape) != MS_SUCCESS) {
-                retcode = MS_FAILURE;
-                break;
-            }
+      } else {
+        /* Generic feature style handling as per RFC-61 */
+        if(msLayerGetFeatureStyle(map, layer, layer->class[shape.classindex], &shape) != MS_SUCCESS) {
+          retcode = MS_FAILURE;
+          break;
         }
+      }
 
       /* __TODO__ For now, we can't cache features with 'AUTO' style */
       cache = MS_FALSE;
     }
-  
-    if(annotate && (layer->class[shape.classindex]->text.string || layer->labelitem) && layer->class[shape.classindex]->label.size != -1)
-      shape.text = msShapeGetAnnotation(layer, &shape);
 
+    /* RFC77 TODO: check return value, may need a more sophisticated if-then test. */
+    if(annotate && layer->class[shape.classindex]->numlabels > 0) {
+      msShapeGetAnnotation(layer, &shape);
+      drawmode |= MS_DRAWMODE_LABELS;
+      if (msLayerGetProcessingKey(layer, "LABEL_NO_CLIP")) {
+        drawmode |= MS_DRAWMODE_UNCLIPPEDLABELS;
+      }
+    }
+
+    if (layer->type == MS_LAYER_LINE && msLayerGetProcessingKey(layer, "POLYLINE_NO_CLIP")) {
+      drawmode |= MS_DRAWMODE_UNCLIPPEDLINES;
+    }
     
     if (cache) {
       styleObj *pStyle = layer->class[shape.classindex]->styles[0];
       colorObj tmp;
       if (pStyle->outlinewidth > 0) {
-          /* 
-           * RFC 49 implementation
-           * if an outlinewidth is used:
-           *  - augment the style's width to account for the outline width
-           *  - swap the style color and outlinecolor
-           *  - draw the shape (the outline) in the first pass of the
-           *    caching mechanism
-           */
-          
-          /* adapt width (must take scalefactor into account) */
-          pStyle->width += (pStyle->outlinewidth / (layer->scalefactor/image->resolutionfactor)) * 2;
-          pStyle->minwidth += pStyle->outlinewidth * 2;
-          pStyle->maxwidth += pStyle->outlinewidth * 2;
-          pStyle->size += (pStyle->outlinewidth/layer->scalefactor*(map->resolution/map->defresolution));
-
-          /*swap color and outlinecolor*/
-          tmp = pStyle->color;
-          pStyle->color = pStyle->outlinecolor;
-          pStyle->outlinecolor = tmp;
-      }
-      status = msDrawShape(map, layer, &shape, image, 0, MS_FALSE); /* draw a single style */
+        /*
+         * RFC 49 implementation
+         * if an outlinewidth is used:
+         *  - augment the style's width to account for the outline width
+         *  - swap the style color and outlinecolor
+         *  - draw the shape (the outline) in the first pass of the
+         *    caching mechanism
+         */
+
+        /* adapt width (must take scalefactor into account) */
+        pStyle->width += (pStyle->outlinewidth / (layer->scalefactor/image->resolutionfactor)) * 2;
+        pStyle->minwidth += pStyle->outlinewidth * 2;
+        pStyle->maxwidth += pStyle->outlinewidth * 2;
+        pStyle->size += (pStyle->outlinewidth/layer->scalefactor*(map->resolution/map->defresolution));
+
+        /*swap color and outlinecolor*/
+        tmp = pStyle->color;
+        pStyle->color = pStyle->outlinecolor;
+        pStyle->outlinecolor = tmp;
+      }
+      status = msDrawShape(map, layer, &shape, image, 0, drawmode|MS_DRAWMODE_SINGLESTYLE); /* draw a single style */
       if (pStyle->outlinewidth > 0) {
-          /*
-           * RFC 49 implementation: switch back the styleobj to its
-           * original state, so the line fill will be drawn in the
-           * second pass of the caching mechanism
-           */
-          
-          /* reset widths to original state */
-          pStyle->width -= (pStyle->outlinewidth / (layer->scalefactor/image->resolutionfactor)) * 2;
-          pStyle->minwidth -= pStyle->outlinewidth * 2;
-          pStyle->maxwidth -= pStyle->outlinewidth * 2;
-          pStyle->size -= (pStyle->outlinewidth/layer->scalefactor*(map->resolution/map->defresolution));
-
-          /*reswap colors to original state*/
-          tmp = pStyle->color;
-          pStyle->color = pStyle->outlinecolor;
-          pStyle->outlinecolor = tmp;
+        /*
+         * RFC 49 implementation: switch back the styleobj to its
+         * original state, so the line fill will be drawn in the
+         * second pass of the caching mechanism
+         */
+
+        /* reset widths to original state */
+        pStyle->width -= (pStyle->outlinewidth / (layer->scalefactor/image->resolutionfactor)) * 2;
+        pStyle->minwidth -= pStyle->outlinewidth * 2;
+        pStyle->maxwidth -= pStyle->outlinewidth * 2;
+        pStyle->size -= (pStyle->outlinewidth/layer->scalefactor*(map->resolution/map->defresolution));
+
+        /*reswap colors to original state*/
+        tmp = pStyle->color;
+        pStyle->color = pStyle->outlinecolor;
+        pStyle->outlinecolor = tmp;
       }
     }
 
     else
-      status = msDrawShape(map, layer, &shape, image, -1, MS_FALSE); /* all styles  */
+      status = msDrawShape(map, layer, &shape, image, -1, drawmode); /* all styles  */
     if(status != MS_SUCCESS) {
       msFreeShape(&shape);
       retcode = MS_FAILURE;
@@ -972,27 +1099,31 @@ int msDrawVectorLayer(mapObj *map, layerObj *layer, imageObj *image)
       msFreeShape(&shape);
       continue;
     }
-  
+
     if(cache) {
       if(insertFeatureList(&shpcache, &shape) == NULL) {
         retcode = MS_FAILURE; /* problem adding to the cache */
         break;
       }
-    }  
+    }
 
     maxnumstyles = MS_MAX(maxnumstyles, layer->class[shape.classindex]->numstyles);
     msFreeShape(&shape);
   }
-    
+
   if (classgroup)
     msFree(classgroup);
 
-  if(status != MS_DONE) {
+  if(status != MS_DONE || retcode == MS_FAILURE) {
     msLayerClose(layer);
+    if(shpcache) {
+      freeFeatureList(shpcache);
+      shpcache = NULL;
+    }
     return MS_FAILURE;
   }
-  
-  if(shpcache) {
+
+  if(shpcache && MS_DRAW_FEATURES(drawmode)) {
     int s;
     for(s=0; s<maxnumstyles; s++) {
       for(current=shpcache; current; current=current->next) {
@@ -1007,61 +1138,71 @@ int msDrawVectorLayer(mapObj *map, layerObj *layer, imageObj *image)
               continue;
           }
           if(s==0 && pStyle->outlinewidth>0 && MS_VALID_COLOR(pStyle->color)) {
-            msDrawLineSymbol(&map->symbolset, image, &current->shape, pStyle, layer->scalefactor);  
+            msDrawLineSymbol(&map->symbolset, image, &current->shape, pStyle, layer->scalefactor);
           } else if(s>0) {
-             if (pStyle->outlinewidth > 0 && MS_VALID_COLOR(pStyle->outlinecolor)) {
-                colorObj tmp;
-                /* 
-                 * RFC 49 implementation
-                 * if an outlinewidth is used:
-                 *  - augment the style's width to account for the outline width
-                 *  - swap the style color and outlinecolor
-                 *  - draw the shape (the outline) in the first pass of the
-                 *    caching mechanism
-                 */
-
-                /* adapt width (must take scalefactor into account) */
-                pStyle->width += (pStyle->outlinewidth / (layer->scalefactor/image->resolutionfactor)) * 2;
-                pStyle->minwidth += pStyle->outlinewidth * 2;
-                pStyle->maxwidth += pStyle->outlinewidth * 2;
-                pStyle->size += (pStyle->outlinewidth/layer->scalefactor*(map->resolution/map->defresolution));
-
-                /*swap color and outlinecolor*/
-                tmp = pStyle->color;
-                pStyle->color = pStyle->outlinecolor;
-                pStyle->outlinecolor = tmp;
-                msDrawLineSymbol(&map->symbolset, image, &current->shape, pStyle, layer->scalefactor);
-                /*
-                 * RFC 49 implementation: switch back the styleobj to its
-                 * original state, so the line fill will be drawn in the
-                 * second pass of the caching mechanism
-                 */
-
-                /* reset widths to original state */
-                pStyle->width -= (pStyle->outlinewidth / (layer->scalefactor/image->resolutionfactor)) * 2;
-                pStyle->minwidth -= pStyle->outlinewidth * 2;
-                pStyle->maxwidth -= pStyle->outlinewidth * 2;
-                pStyle->size -= (pStyle->outlinewidth/layer->scalefactor*(map->resolution/map->defresolution));
-
-                /*reswap colors to original state*/
-                tmp = pStyle->color;
-                pStyle->color = pStyle->outlinecolor;
-                pStyle->outlinecolor = tmp;
-             }
-             if(MS_VALID_COLOR(pStyle->color))
-               msDrawLineSymbol(&map->symbolset, image, &current->shape, pStyle, layer->scalefactor);
-         }
-       }
-     }
+            if (pStyle->outlinewidth > 0 && MS_VALID_COLOR(pStyle->outlinecolor)) {
+              colorObj tmp;
+              /*
+               * RFC 49 implementation
+               * if an outlinewidth is used:
+               *  - augment the style's width to account for the outline width
+               *  - swap the style color and outlinecolor
+               *  - draw the shape (the outline) in the first pass of the
+               *    caching mechanism
+               */
+
+              /* adapt width (must take scalefactor into account) */
+              pStyle->width += (pStyle->outlinewidth / (layer->scalefactor/image->resolutionfactor)) * 2;
+              pStyle->minwidth += pStyle->outlinewidth * 2;
+              pStyle->maxwidth += pStyle->outlinewidth * 2;
+              pStyle->size += (pStyle->outlinewidth/layer->scalefactor*(map->resolution/map->defresolution));
+
+              /*swap color and outlinecolor*/
+              tmp = pStyle->color;
+              pStyle->color = pStyle->outlinecolor;
+              pStyle->outlinecolor = tmp;
+              msDrawLineSymbol(&map->symbolset, image, &current->shape, pStyle, layer->scalefactor);
+              /*
+               * RFC 49 implementation: switch back the styleobj to its
+               * original state, so the line fill will be drawn in the
+               * second pass of the caching mechanism
+               */
+
+              /* reset widths to original state */
+              pStyle->width -= (pStyle->outlinewidth / (layer->scalefactor/image->resolutionfactor)) * 2;
+              pStyle->minwidth -= pStyle->outlinewidth * 2;
+              pStyle->maxwidth -= pStyle->outlinewidth * 2;
+              pStyle->size -= (pStyle->outlinewidth/layer->scalefactor*(map->resolution/map->defresolution));
+
+              /*reswap colors to original state*/
+              tmp = pStyle->color;
+              pStyle->color = pStyle->outlinecolor;
+              pStyle->outlinecolor = tmp;
+            }
+            /* draw a valid line, i.e. one with a color defined or of type pixmap*/
+            if(MS_VALID_COLOR(pStyle->color) || 
+                    (
+                      pStyle->symbol<map->symbolset.numsymbols &&
+                      ( 
+                        map->symbolset.symbol[pStyle->symbol]->type == MS_SYMBOL_PIXMAP ||
+                        map->symbolset.symbol[pStyle->symbol]->type == MS_SYMBOL_SVG
+                      )
+                    )
+              ) {
+              msDrawLineSymbol(&map->symbolset, image, &current->shape, pStyle, layer->scalefactor);
+            }
+          }
+        }
+      }
     }
-    
+
     freeFeatureList(shpcache);
-    shpcache = NULL;  
+    shpcache = NULL;
   }
 
-  msLayerClose(layer);  
+  msLayerClose(layer);
   return MS_SUCCESS;
-  
+
 }
 
 /*
@@ -1071,6 +1212,7 @@ int msDrawQueryLayer(mapObj *map, layerObj *layer, imageObj *image)
 {
   int i, status;
   char annotate=MS_TRUE, cache=MS_FALSE;
+  int drawmode = MS_DRAWMODE_FEATURES|MS_DRAWMODE_QUERY;
   shapeObj shape;
   int maxnumstyles=1;
 
@@ -1095,49 +1237,51 @@ int msDrawQueryLayer(mapObj *map, layerObj *layer, imageObj *image)
   }
 
   /*
-  ** Certain query map styles require us to render all features only (MS_NORMAL) or first (MS_HILITE). With 
+  ** Certain query map styles require us to render all features only (MS_NORMAL) or first (MS_HILITE). With
   ** single-pass queries we have to make a copy of the layer and work from it instead.
   */
   if(map->querymap.style == MS_NORMAL || map->querymap.style == MS_HILITE) {
     layerObj tmp_layer;
 
-    if(initLayer(&tmp_layer, map) == -1) 
-		return(MS_FAILURE);
+    if(initLayer(&tmp_layer, map) == -1)
+      return(MS_FAILURE);
 
-	if (msCopyLayer(&tmp_layer, layer) != MS_SUCCESS)
-		return(MS_FAILURE);
+    if (msCopyLayer(&tmp_layer, layer) != MS_SUCCESS)
+      return(MS_FAILURE);
 
     /* disable the connection pool for this layer */
     msLayerSetProcessingKey(&tmp_layer, "CLOSE_CONNECTION", "ALWAYS");
 
     status = msDrawLayer(map, &tmp_layer, image);
 
-	freeLayer(&tmp_layer);
+    freeLayer(&tmp_layer);
 
     if(map->querymap.style == MS_NORMAL || status != MS_SUCCESS) return(status);
   }
 
+#ifdef USE_GD
   /* reset layer pen values just in case the map has been previously processed */
   msClearLayerPenValues(layer);
+#endif
 
   /* if MS_HILITE, alter the one style (always at least 1 style), and set a MINDISTANCE for the labelObj to avoid duplicates */
   if(map->querymap.style == MS_HILITE) {
     if (layer->numclasses > 0) {
-        colorbuffer = (colorObj*)malloc(layer->numclasses*sizeof(colorObj));
-        mindistancebuffer = (int*)malloc(layer->numclasses*sizeof(int));
+      colorbuffer = (colorObj*)malloc(layer->numclasses*sizeof(colorObj));
+      mindistancebuffer = (int*)malloc(layer->numclasses*sizeof(int));
 
-        if (colorbuffer == NULL || mindistancebuffer == NULL) {
-            msSetError(MS_MEMERR, "Failed to allocate memory for colorbuffer/mindistancebuffer", "msDrawQueryLayer()");
-            return MS_FAILURE;
-        }
+      if (colorbuffer == NULL || mindistancebuffer == NULL) {
+        msSetError(MS_MEMERR, "Failed to allocate memory for colorbuffer/mindistancebuffer", "msDrawQueryLayer()");
+        return MS_FAILURE;
+      }
     }
 
     for(i=0; i<layer->numclasses; i++) {
       if(layer->type == MS_LAYER_POLYGON) { /* alter BOTTOM style since that's almost always the fill */
-	if (layer->class[i]->styles == NULL) {
-           msSetError(MS_MISCERR, "Don't know how to draw class %s of layer %s without a style definition.", "msDrawQueryLayer()", layer->class[i]->name, layer->name);
-           return(MS_FAILURE);
-	}
+        if (layer->class[i]->styles == NULL) {
+          msSetError(MS_MISCERR, "Don't know how to draw class %s of layer %s without a style definition.", "msDrawQueryLayer()", layer->class[i]->name, layer->name);
+          return(MS_FAILURE);
+        }
         if(MS_VALID_COLOR(layer->class[i]->styles[0]->color)) {
           colorbuffer[i] = layer->class[i]->styles[0]->color; /* save the color from the BOTTOM style */
           layer->class[i]->styles[0]->color = map->querymap.color;
@@ -1150,13 +1294,16 @@ int msDrawQueryLayer(mapObj *map, layerObj *layer, imageObj *image)
           colorbuffer[i] = layer->class[i]->styles[layer->class[i]->numstyles-1]->color; /* save the color from the TOP style */
           layer->class[i]->styles[layer->class[i]->numstyles-1]->color = map->querymap.color;
         } else if(MS_VALID_COLOR(layer->class[i]->styles[layer->class[i]->numstyles-1]->outlinecolor)) {
-	  colorbuffer[i] = layer->class[i]->styles[layer->class[i]->numstyles-1]->outlinecolor; /* if no color, save the outlinecolor from the TOP style */
+          colorbuffer[i] = layer->class[i]->styles[layer->class[i]->numstyles-1]->outlinecolor; /* if no color, save the outlinecolor from the TOP style */
           layer->class[i]->styles[layer->class[i]->numstyles-1]->outlinecolor = map->querymap.color;
         }
       }
 
-      mindistancebuffer[i] = layer->class[i]->label.mindistance;
-      layer->class[i]->label.mindistance = MS_MAX(0, layer->class[i]->label.mindistance);
+      mindistancebuffer[i] = -1; /* RFC77 TODO: only using the first label, is that cool? */
+      if(layer->class[i]->numlabels > 0) {
+        mindistancebuffer[i] = layer->class[i]->labels[0]->mindistance;
+        layer->class[i]->labels[0]->mindistance = MS_MAX(0, layer->class[i]->labels[0]->mindistance);
+      }
     }
   }
 
@@ -1177,29 +1324,34 @@ int msDrawQueryLayer(mapObj *map, layerObj *layer, imageObj *image)
     shape.classindex = layer->resultcache->results[i].classindex;
     /* classindex may be -1 here if there was a template at the top level
      * in this layer and the current shape selected even if it didn't
-     * match any class 
+     * match any class
      *
-     * FrankW: classindex is also sometimes 0 even if there are no classes, so 
+     * FrankW: classindex is also sometimes 0 even if there are no classes, so
      * we are careful not to use out of range class values as an index.
      */
-    if(shape.classindex==-1 
-       || shape.classindex >= layer->numclasses
-       || layer->class[shape.classindex]->status == MS_OFF) {
+    if(shape.classindex==-1
+        || shape.classindex >= layer->numclasses
+        || layer->class[shape.classindex]->status == MS_OFF) {
       msFreeShape(&shape);
       continue;
     }
 
     cache = MS_FALSE;
-    if(layer->type == MS_LAYER_LINE && layer->class[shape.classindex]->numstyles > 1) 
+    if(layer->type == MS_LAYER_LINE && layer->class[shape.classindex]->numstyles > 1)
       cache = MS_TRUE; /* only line layers with multiple styles need be cached (I don't think POLYLINE layers need caching - SDL) */
 
-    if(annotate && (layer->class[shape.classindex]->text.string || layer->labelitem) && layer->class[shape.classindex]->label.size != -1)
-      shape.text = msShapeGetAnnotation(layer, &shape);
+    /* RFC 77 TODO: check return value for msShapeGetAnnotation() */
+    if(annotate && layer->class[shape.classindex]->numlabels > 0) {
+      msShapeGetAnnotation(layer, &shape);
+      drawmode |= MS_DRAWMODE_LABELS;
+    }
 
-    if(cache)
-      status = msDrawShape(map, layer, &shape, image, 0, MS_TRUE); /* draw only the first style */
+    if(cache) {
+      drawmode |= MS_DRAWMODE_SINGLESTYLE;
+      status = msDrawShape(map, layer, &shape, image, 0, drawmode); /* draw only the first style */
+    }
     else
-      status = msDrawShape(map, layer, &shape, image, -1, MS_TRUE); /* all styles  */
+      status = msDrawShape(map, layer, &shape, image, -1, drawmode); /* all styles  */
     if(status != MS_SUCCESS) {
       msLayerClose(layer);
       msFree(colorbuffer);
@@ -1222,9 +1374,9 @@ int msDrawQueryLayer(mapObj *map, layerObj *layer, imageObj *image)
 
   if(shpcache) {
     int s;
-  
+
     for(s=1; s<maxnumstyles; s++) {
-      for(current=shpcache; current; current=current->next) {        
+      for(current=shpcache; current; current=current->next) {
         if(layer->class[current->shape.classindex]->numstyles > s) {
           styleObj *curStyle = layer->class[current->shape.classindex]->styles[s];
           if(map->scaledenom > 0) {
@@ -1233,39 +1385,39 @@ int msDrawQueryLayer(mapObj *map, layerObj *layer, imageObj *image)
             if((curStyle->minscaledenom != -1) && (map->scaledenom < curStyle->minscaledenom))
               continue;
           }
-	      msDrawLineSymbol(&map->symbolset, image, &current->shape, (layer->class[current->shape.classindex]->styles[s]), layer->scalefactor);
+          msDrawLineSymbol(&map->symbolset, image, &current->shape, (layer->class[current->shape.classindex]->styles[s]), layer->scalefactor);
         }
       }
     }
-    
+
     freeFeatureList(shpcache);
-    shpcache = NULL;  
+    shpcache = NULL;
   }
 
   /* if MS_HILITE, restore color and mindistance values */
   if(map->querymap.style == MS_HILITE) {
     for(i=0; i<layer->numclasses; i++) {
       if(layer->type == MS_LAYER_POLYGON) {
-	if(MS_VALID_COLOR(layer->class[i]->styles[0]->color))
+        if(MS_VALID_COLOR(layer->class[i]->styles[0]->color))
           layer->class[i]->styles[0]->color = colorbuffer[i];
         else if(MS_VALID_COLOR(layer->class[i]->styles[0]->outlinecolor))
           layer->class[i]->styles[0]->outlinecolor = colorbuffer[i]; /* if no color, restore outlinecolor for the BOTTOM style */
       } else {
         if(MS_VALID_COLOR(layer->class[i]->styles[layer->class[i]->numstyles-1]->color))
-          layer->class[i]->styles[layer->class[i]->numstyles-1]->color = colorbuffer[i];        
+          layer->class[i]->styles[layer->class[i]->numstyles-1]->color = colorbuffer[i];
         else if(MS_VALID_COLOR(layer->class[i]->styles[layer->class[i]->numstyles-1]->outlinecolor))
-	  layer->class[i]->styles[layer->class[i]->numstyles-1]->outlinecolor = colorbuffer[i]; /* if no color, restore outlinecolor for the TOP style */
+          layer->class[i]->styles[layer->class[i]->numstyles-1]->outlinecolor = colorbuffer[i]; /* if no color, restore outlinecolor for the TOP style */
       }
-    
-      layer->class[i]->label.mindistance = mindistancebuffer[i];
+
+      if(layer->class[i]->numlabels > 0)
+        layer->class[i]->labels[0]->mindistance = mindistancebuffer[i]; /* RFC77 TODO: again, only using the first label, is that cool? */
+
     }
 
     msFree(colorbuffer);
     msFree(mindistancebuffer);
   }
 
-  /* msLayerClose(layer); */
-
   return(MS_SUCCESS);
 }
 
@@ -1273,70 +1425,62 @@ int msDrawQueryLayer(mapObj *map, layerObj *layer, imageObj *image)
  * msDrawRasterLayerPlugin()
  */
 
-static int 
-msDrawRasterLayerPlugin( mapObj *map, layerObj *layer, imageObj *image) 
+static int
+msDrawRasterLayerPlugin( mapObj *map, layerObj *layer, imageObj *image)
 
 {
-    rendererVTableObj *renderer = MS_IMAGE_RENDERER(image);
-    rasterBufferObj  *rb = msSmallCalloc(1,sizeof(rasterBufferObj));
-    int ret;
-    if( renderer->supports_pixel_buffer )
-    {
-    	if (MS_SUCCESS != renderer->getRasterBufferHandle( image, rb )) {
-    		msSetError(MS_MISCERR,"renderer failed to extract raster buffer","msDrawRasterLayer()");
-    		return MS_FAILURE;
-    	}
-        ret = msDrawRasterLayerLow( map, layer, image, rb );
+  rendererVTableObj *renderer = MS_IMAGE_RENDERER(image);
+  rasterBufferObj  *rb = msSmallCalloc(1,sizeof(rasterBufferObj));
+  int ret;
+  if( renderer->supports_pixel_buffer ) {
+    if (MS_SUCCESS != renderer->getRasterBufferHandle( image, rb )) {
+      msSetError(MS_MISCERR,"renderer failed to extract raster buffer","msDrawRasterLayer()");
+      return MS_FAILURE;
     }
-    else
-    {
-        if (MS_SUCCESS != renderer->initializeRasterBuffer( rb, image->width, image->height, MS_IMAGEMODE_RGBA )) {
-        	msSetError(MS_MISCERR,"renderer failed to create raster buffer","msDrawRasterLayer()");
-        	return MS_FAILURE;
-        }
-        
-        ret = msDrawRasterLayerLow( map, layer, image, rb );
-        
-        if( ret == 0 )
-        {
-        	renderer->mergeRasterBuffer( image, rb, 1.0, 0, 0, 0, 0, rb->width, rb->height );
-        }
+    ret = msDrawRasterLayerLow( map, layer, image, rb );
+  } else {
+    if (MS_SUCCESS != renderer->initializeRasterBuffer( rb, image->width, image->height, MS_IMAGEMODE_RGBA )) {
+      msSetError(MS_MISCERR,"renderer failed to create raster buffer","msDrawRasterLayer()");
+      return MS_FAILURE;
+    }
+
+    ret = msDrawRasterLayerLow( map, layer, image, rb );
 
-	msFreeRasterBuffer(rb);
+    if( ret == 0 ) {
+      renderer->mergeRasterBuffer( image, rb, 1.0, 0, 0, 0, 0, rb->width, rb->height );
     }
+
+    msFreeRasterBuffer(rb);
+  }
 #define RB_GET_R(rb,x,y) *((rb)->data.rgba.r + (x) * (rb)->data.rgba.pixel_step + (y) * (rb)->data.rgba.row_step)
 #define RB_GET_G(rb,x,y) *((rb)->data.rgba.g + (x) * (rb)->data.rgba.pixel_step + (y) * (rb)->data.rgba.row_step)
 #define RB_GET_B(rb,x,y) *((rb)->data.rgba.b + (x) * (rb)->data.rgba.pixel_step + (y) * (rb)->data.rgba.row_step)
 #define RB_GET_A(rb,x,y) *((rb)->data.rgba.a + (x) * (rb)->data.rgba.pixel_step + (y) * (rb)->data.rgba.row_step)
 
-    free(rb);         
-	
-    return ret;
+  free(rb);
+
+  return ret;
 }
 
 /**
  * Generic function to render raster layers.
  */
-int msDrawRasterLayer(mapObj *map, layerObj *layer, imageObj *image) 
+int msDrawRasterLayer(mapObj *map, layerObj *layer, imageObj *image)
 {
-    if (image && map && layer)
-    {
-        if( MS_RENDERER_PLUGIN(image->format) )
-        {
-           return msDrawRasterLayerPlugin(map, layer, image);
-        }
-        else if( MS_RENDERER_RAWDATA(image->format) )
-            return msDrawRasterLayerLow(map, layer, image, NULL);
-    }
+  if (image && map && layer) {
+    if( MS_RENDERER_PLUGIN(image->format) ) {
+      return msDrawRasterLayerPlugin(map, layer, image);
+    } else if( MS_RENDERER_RAWDATA(image->format) )
+      return msDrawRasterLayerLow(map, layer, image, NULL);
+  }
 
-    return MS_FAILURE;
+  return MS_FAILURE;
 }
 
-
 /**
  * msDrawWMSLayer()
  *
- * Draw a single WMS layer.  
+ * Draw a single WMS layer.
  * Multiple WMS layers in a map are preloaded and then drawn using
  * msDrawWMSLayerLow()
  */
@@ -1344,947 +1488,771 @@ int msDrawRasterLayer(mapObj *map, layerObj *layer, imageObj *image)
 #ifdef USE_WMS_LYR
 int msDrawWMSLayer(mapObj *map, layerObj *layer, imageObj *image)
 {
-    int nStatus = MS_FAILURE;
-
-    if (image && map && layer)
-    {
-/* ------------------------------------------------------------------
- * Start by downloading the layer
- * ------------------------------------------------------------------ */
-        httpRequestObj asReqInfo[2];
-        int numReq = 0;
-
-        msHTTPInitRequestObj(asReqInfo, 2);
-
-        if ( msPrepareWMSLayerRequest(1, map, layer,
-                                      0, NULL,
-                                      asReqInfo, &numReq) == MS_FAILURE  ||
-             msOWSExecuteRequests(asReqInfo, numReq, map, MS_TRUE) == MS_FAILURE )
-        {
-            return MS_FAILURE;
-        }
+  int nStatus = MS_FAILURE;
 
-/* ------------------------------------------------------------------
- * Then draw layer based on output format
- * ------------------------------------------------------------------ */
-        if( MS_RENDERER_PLUGIN(image->format) )
-            nStatus = msDrawWMSLayerLow(1, asReqInfo, numReq,
-                                        map, layer, image) ;
-        else if( MS_RENDERER_RAWDATA(image->format) )
-            nStatus = msDrawWMSLayerLow(1, asReqInfo, numReq,
-                                        map, layer, image) ;
+  if (image && map && layer) {
+    /* ------------------------------------------------------------------
+     * Start by downloading the layer
+     * ------------------------------------------------------------------ */
+    httpRequestObj asReqInfo[2];
+    int numReq = 0;
 
-        else
-        {
-            msSetError(MS_WMSCONNERR, 
-                       "Output format '%s' doesn't support WMS layers.", 
-                       "msDrawWMSLayer()", image->format->name);
-            nStatus = MS_SUCCESS; /* Should we fail if output doesn't support WMS? */
-        }
-        /* Cleanup */
-        msHTTPFreeRequestObj(asReqInfo, numReq);
+    msHTTPInitRequestObj(asReqInfo, 2);
+
+    if ( msPrepareWMSLayerRequest(1, map, layer, 1,
+                                  0, NULL, 0, 0, 0, NULL,
+                                  asReqInfo, &numReq) == MS_FAILURE  ||
+         msOWSExecuteRequests(asReqInfo, numReq, map, MS_TRUE) == MS_FAILURE ) {
+      return MS_FAILURE;
     }
 
-    return nStatus;
+    /* ------------------------------------------------------------------
+     * Then draw layer based on output format
+     * ------------------------------------------------------------------ */
+    if( MS_RENDERER_PLUGIN(image->format) )
+      nStatus = msDrawWMSLayerLow(1, asReqInfo, numReq,
+                                  map, layer, image) ;
+    else if( MS_RENDERER_RAWDATA(image->format) )
+      nStatus = msDrawWMSLayerLow(1, asReqInfo, numReq,
+                                  map, layer, image) ;
+
+    else {
+      msSetError(MS_WMSCONNERR,
+                 "Output format '%s' doesn't support WMS layers.",
+                 "msDrawWMSLayer()", image->format->name);
+      nStatus = MS_SUCCESS; /* Should we fail if output doesn't support WMS? */
+    }
+    /* Cleanup */
+    msHTTPFreeRequestObj(asReqInfo, numReq);
+  }
+
+  return nStatus;
 }
 #endif
 
-
-/*
-** Function to render an individual shape, the style variable enables/disables the drawing of a single style
-** versus a single style. This is necessary when drawing entire layers as proper overlay can only be achived
-** through caching. "querymapMode" parameter is used to tell msBindLayerToShape to not override the 
-** QUERYMAP HILITE color.
-*/
-int msDrawShape(mapObj *map, layerObj *layer, shapeObj *shape, imageObj *image, int style, int querymapMode)
+int circleLayerDrawShape(mapObj *map, imageObj *image, layerObj *layer, shapeObj *shape)
 {
-  int i,j,c,s;
-  rectObj cliprect;
-  pointObj annopnt, *point;
-  double** angles = NULL, **lengths = NULL;
-  int bLabelNoClip = MS_FALSE;
-  int annocallret = MS_FAILURE; /* Retvals for find-label-pnt calls */
-  
-  int hasGeomTransform = MS_FALSE;
-  shapeObj nonClippedShape;
-  
-  pointObj center; /* circle origin */
-  double r; /* circle radius */
-  int csz; /* clip over size */
-  double buffer;
-  int minfeaturesize;
-  int numpaths = 1, numpoints = 1, numRegularLines = 0;
+  pointObj center;
+  double r;
+  int s;
+  int c = shape->classindex;
 
-  labelPathObj **annopaths = NULL; /* Curved label path. Bug #1620 implementation */
-  pointObj     **annopoints = NULL;
-  int           *regularLines = NULL;
-
-  /* set clipping rectangle just a bit larger than the map extent */
-/* Steve's original code 
-  cliprect.minx = map->extent.minx - 2*map->cellsize; 
-  cliprect.miny = map->extent.miny - 2*map->cellsize;
-  cliprect.maxx = map->extent.maxx + 2*map->cellsize;
-  cliprect.maxy = map->extent.maxy + 2*map->cellsize;
-*/
+  if (shape->numlines != 1) return (MS_SUCCESS); /* invalid shape */
+  if (shape->line[0].numpoints != 2) return (MS_SUCCESS); /* invalid shape */
 
-  msDrawStartShape(map, layer, image, shape);
+  center.x = (shape->line[0].point[0].x + shape->line[0].point[1].x) / 2.0;
+  center.y = (shape->line[0].point[0].y + shape->line[0].point[1].y) / 2.0;
+  r = MS_ABS(center.x - shape->line[0].point[0].x);
+  if (r == 0)
+    r = MS_ABS(center.y - shape->line[0].point[0].y);
+  if (r == 0)
+    return (MS_SUCCESS);
 
-  c = shape->classindex;
+  if (layer->transform == MS_TRUE) {
 
-  /* Before we do anything else, we will check for a rangeitem.
-     If its there, we need to change the style's color to map
-     the range to the shape */
-  for(s=0; s<layer->class[c]->numstyles; s++) {
-	styleObj *style = layer->class[c]->styles[s];
-    if(style->rangeitem !=  NULL)
-      msShapeToRange((layer->class[c]->styles[s]), shape);
-    
-    
-  }
-  
-  /* adjust the clipping rectangle so that clipped polygon shapes with thick lines
-   * do not enter the image */
-  if(layer->class[c]->numstyles > 0 && layer->class[c]->styles[0] != NULL) {
-      double maxsize,maxunscaledsize;
-      symbolObj *symbol;
-      styleObj *style = layer->class[c]->styles[0];
-      if (!MS_IS_VALID_ARRAY_INDEX(style->symbol, map->symbolset.numsymbols)) {
-          msSetError(MS_SYMERR, "Invalid symbol index: %d", "msDrawShape()", style->symbol);
-          return MS_FAILURE;
-      }
-      symbol = map->symbolset.symbol[style->symbol];
-      if(symbol->type == MS_SYMBOL_PIXMAP) {
-    	  if(MS_SUCCESS != msPreloadImageSymbol(MS_MAP_RENDERER(map),symbol))
-    		  return MS_FAILURE;
-      }
-      maxsize = MS_MAX(
-          msSymbolGetDefaultSize(symbol),MS_MAX(style->size,style->width)
-      );
-      maxunscaledsize = MS_MAX( style->minsize,
-                                style->minwidth);
-      csz = MS_NINT(MS_MAX(maxsize*layer->scalefactor,maxunscaledsize)+1);
-  } else {
-      csz = 0;
-  }
-  cliprect.minx = map->extent.minx - csz*map->cellsize;
-  cliprect.miny = map->extent.miny - csz*map->cellsize;
-  cliprect.maxx = map->extent.maxx + csz*map->cellsize;
-  cliprect.maxy = map->extent.maxy + csz*map->cellsize;
-  minfeaturesize = layer->class[c]->label.minfeaturesize*image->resolutionfactor;
+#ifdef USE_PROJ
+    if (layer->project && msProjectionsDiffer(&(layer->projection), &(map->projection)))
+      msProjectPoint(&layer->projection, &map->projection, &center);
+    else
+      layer->project = MS_FALSE;
+#endif
 
-  if(msBindLayerToShape(layer, shape, querymapMode) != MS_SUCCESS)
-    return MS_FAILURE; /* error message is set in msBindLayerToShape() */
-  
-  if(shape->text && (layer->class[c]->label.encoding || layer->class[c]->label.wrap
-          ||layer->class[c]->label.maxlength)) {
-      char *newtext=msTransformLabelText(map,image,&(layer->class[c]->label),shape->text);
-      free(shape->text);
-      shape->text = newtext;
+    center.x = MS_MAP2IMAGE_X(center.x, map->extent.minx, map->cellsize);
+    center.y = MS_MAP2IMAGE_Y(center.y, map->extent.maxy, map->cellsize);
+    r /= map->cellsize;
+  } else
+    msOffsetPointRelativeTo(&center, layer);
+
+  for (s = 0; s < layer->class[c]->numstyles; s++) {
+    if (msScaleInBounds(map->scaledenom,
+                        layer->class[c]->styles[s]->minscaledenom,
+                        layer->class[c]->styles[s]->maxscaledenom))
+      msCircleDrawShadeSymbol(&map->symbolset, image, &center, r,
+                              layer->class[c]->styles[s], layer->scalefactor);
   }
+  return MS_SUCCESS;
+  /* TODO: need to handle circle annotation */
+}
 
-  switch(layer->type) {
-  case MS_LAYER_CIRCLE:
-    if(shape->numlines != 1) return(MS_SUCCESS); /* invalid shape */
-    if(shape->line[0].numpoints != 2) return(MS_SUCCESS); /* invalid shape */
-
-    center.x = (shape->line[0].point[0].x + shape->line[0].point[1].x)/2.0;
-    center.y = (shape->line[0].point[0].y + shape->line[0].point[1].y)/2.0;
-    r = MS_ABS(center.x - shape->line[0].point[0].x);
-    if(r == 0)
-       r = MS_ABS(center.y - shape->line[0].point[0].y);
-    if(r == 0)
-       return(MS_SUCCESS);
-
-    if(layer->transform == MS_TRUE) {
+int annotationLayerDrawShape(mapObj *map, imageObj *image, layerObj *layer, shapeObj *shape)
+{
+  int c = shape->classindex;
+  rectObj cliprect;
+  labelObj *label;
+  double minfeaturesize;
+  labelPathObj **annopaths = NULL; /* Curved label path. Bug #1620 implementation */
+  pointObj **annopoints = NULL;
+  pointObj annopnt;
+  pointObj *point;
+  int *regularLines = NULL;
+  double** angles = NULL, **lengths = NULL;
+  int ret = MS_SUCCESS;
+  int numpaths = 1, numpoints = 1, numRegularLines = 0, i,j,s;
+  if (layer->class[c]->numlabels == 0) return (MS_SUCCESS); /* nothing to draw (RFC77 TDOO: could expand this test) */
+  if (layer->class[c]->numlabels > 1) {
+    msSetError(MS_MISCERR, "Multiple labels not supported on annotation layers.", "annotationLayerDrawShape()");
+    return MS_FAILURE;
+  }
 
-#ifdef USE_PROJ
-      if(layer->project && msProjectionsDiffer(&(layer->projection), &(map->projection)))
-        msProjectPoint(&layer->projection, &map->projection, &center);
-      else
-        layer->project = MS_FALSE;
-#endif
+  cliprect.minx = cliprect.miny = 0;
+  cliprect.maxx = image->width;
+  cliprect.maxy = image->height;
 
-      center.x = MS_MAP2IMAGE_X(center.x, map->extent.minx, map->cellsize);
-      center.y = MS_MAP2IMAGE_Y(center.y, map->extent.maxy, map->cellsize);
-      r /= map->cellsize;      
-    } else
-      msOffsetPointRelativeTo(&center, layer);
-
-    /* shade symbol drawing will call outline function if color not set */
-    for(s=0; s<layer->class[c]->numstyles; s++) {
-      styleObj *curStyle = layer->class[c]->styles[s];
-      if(map->scaledenom > 0) {
-        if((curStyle->maxscaledenom != -1) && (map->scaledenom >= curStyle->maxscaledenom))
-          continue;
-        if((curStyle->minscaledenom != -1) && (map->scaledenom < curStyle->minscaledenom))
-          continue;
-      }
-      msCircleDrawShadeSymbol(&map->symbolset, image, &center, r, curStyle, layer->scalefactor);
-    }
 
-    /* TO DO: need to handle circle annotation */
 
-    break;
-  case MS_LAYER_ANNOTATION:
-    if(!shape->text) return(MS_SUCCESS); /* nothing to draw */
+  /* annotation layers can only have one layer, don't treat the multi layer case */
+  label = layer->class[c]->labels[0]; /* for brevity */
+  minfeaturesize = label->minfeaturesize * image->resolutionfactor;
 
-#ifdef USE_PROJ
-    if(layer->transform == MS_TRUE && layer->project && msProjectionsDiffer(&(layer->projection), &(map->projection)))
-      msProjectShape(&layer->projection, &map->projection, shape);
-    else
-      layer->project = MS_FALSE;
-#endif
 
-    switch(shape->type) {
+  switch (shape->type) {
     case(MS_SHAPE_LINE):
 
-      /* No-clip labeling support. For lines we copy the shape, though this is */
-      /* inefficient. msPolylineLabelPath/msPolylineLabelPoint require that    */
-      /* the shape is transformed prior to calling them                        */
-      if(msLayerGetProcessingKey(layer, "LABEL_NO_CLIP") != NULL) {
-        shapeObj annoshape;
-        bLabelNoClip = MS_TRUE;
-
-        msInitShape(&annoshape);
-        msCopyShape(shape, &annoshape);
-        msTransformShape(&annoshape, map->extent, map->cellsize, image);
-
-        if(layer->class[c]->label.anglemode == MS_FOLLOW ) {
-          if (layer->class[c]->label.type != MS_TRUETYPE) {
-            msSetError(MS_MISCERR, "Angle mode 'FOLLOW' is supported only with truetype fonts.", "msDrawShape()");
-            return(MS_FAILURE);
-          }
-          annopaths = msPolylineLabelPath(map,image,&annoshape, minfeaturesize, &(map->fontset), shape->text, &(layer->class[c]->label), layer->scalefactor, &numpaths, &regularLines, &numRegularLines);
-        } else {
-            annopoints = msPolylineLabelPoint(&annoshape, minfeaturesize, (layer->class[c]->label).repeatdistance, &angles, &lengths, &numpoints, layer->class[c]->label.anglemode);
+      if (label->anglemode == MS_FOLLOW) { /* bug #1620 implementation */
+#ifndef NDEBUG
+        /* this test should already occur at the parser level in loadLabel() */
+        if (label->type != MS_TRUETYPE) {
+          msSetError(MS_MISCERR, "Angle mode 'FOLLOW' is supported only with truetype fonts.", "annotationLayerDrawShape()");
+          return (MS_FAILURE);
         }
-        
-        msFreeShape(&annoshape);
-      }
-    
-      if(layer->transform == MS_TRUE) {
-        msClipPolylineRect(shape, cliprect);
-        if(shape->numlines == 0) return(MS_SUCCESS);
-        msTransformShape(shape, map->extent, map->cellsize, image);
-      } else
-        msOffsetShapeRelativeTo(shape, layer);
-
-      
-      if (layer->class[c]->label.anglemode == MS_FOLLOW) 
-      {
-        if (layer->class[c]->label.type != MS_TRUETYPE) {
-          msSetError(MS_MISCERR, "Angle mode 'FOLLOW' is supported only with truetype fonts.", "msDrawShape()");
-          return(MS_FAILURE);
-        }
-        /* Determine the label path if it has not been computed above */
-        if (bLabelNoClip == MS_FALSE) {
-          if ( annopaths ) {
-            for (j = 0; j<numpaths;j++)
-              if (annopaths[j])
-                msFreeLabelPathObj(annopaths[j]);
-            free(annopaths);
-            annopaths = NULL;
-          }
-          if ( regularLines ) {
-            free(regularLines);
-            regularLines =  NULL;
-          }
-          annopaths = msPolylineLabelPath(map,image,shape, minfeaturesize, &(map->fontset), shape->text, &(layer->class[c]->label), layer->scalefactor, &numpaths, &regularLines, &numRegularLines);
+#endif
+        if(!layer->labelcache) {
+          msSetError(MS_MISCERR, "Angle mode 'FOLLOW' is supported only with LABELCACHE ON", "annotationLayerDrawShape()");
+          return (MS_FAILURE);
         }
+        annopaths = msPolylineLabelPath(map, image, shape, minfeaturesize, &(map->fontset),
+                                        label->annotext, label, layer->scalefactor, &numpaths, &regularLines, &numRegularLines);
 
-        for (i = 0; i < numpaths; i++)
-        {
-          /* Bug #1620 implementation */
-          if(layer->class[c]->label.anglemode == MS_FOLLOW) {
-            if (layer->class[c]->label.type != MS_TRUETYPE) {
-              msSetError(MS_MISCERR, "Angle mode 'FOLLOW' is supported only with truetype fonts.", "msDrawShape()");
-              return(MS_FAILURE);
-            }
-            layer->class[c]->label.position = MS_CC; /* Force all label positions to MS_CC regardless if a path is computed */
+        for (i = 0; i < numpaths; i++) {
+          label->position = MS_CC; /* force label position to MS_CC regardless if a path is computed (WHY HERE?) */
 
-            if( annopaths[i] ) {
-              labelObj label = layer->class[c]->label;
-                
-              if(layer->labelcache) {
-                if(msAddLabel(map, layer->index, c, shape, NULL, annopaths[i], shape->text, -1, &label) != MS_SUCCESS) return(MS_FAILURE);
-              } else {
-                /* FIXME: Not sure how this should work with the label path yet */
-                /*
-                  if(MS_VALID_COLOR(layer->class[c]->styles[0]->color)) {
-                  for(s=0; s<layer->class[c]->numstyles; s++)
-                  msDrawMarkerSymbol(&map->symbolset, image, &(label_line->point[0]), (layer->class[c]->styles[s]), layer->scalefactor);
-                  }
-                */
-                /* FIXME: need to call msDrawTextLineGD() from here eventually */
-                /* msDrawLabel(image, label_line->point[0], shape->text, &label, &map->fontset, layer->scalefactor); */
-                msFreeLabelPathObj(annopaths[i]);
-                annopaths[i] = NULL;                
-              }
+          if (annopaths[i]) {
+            if (msAddLabel(map, label, layer->index, c, shape, NULL, annopaths[i], -1) != MS_SUCCESS) {
+              ret = MS_FAILURE;
+              goto anno_cleanup_line;
             }
           }
         }
 
         /* handle regular lines that have to be drawn with the regular algorithm */
-        if (numRegularLines > 0)
-        {
-
-          annopoints = msPolylineLabelPointExtended(shape, minfeaturesize, (layer->class[c]->label).repeatdistance, &angles, &lengths, &numpoints, regularLines, numRegularLines, MS_FALSE);
-          
-          for (i = 0; i < numpoints; i++)
-            {
-              labelObj label = layer->class[c]->label;
-              
-              if(label.angle != 0)
-                label.angle -= map->gt.rotation_angle;
-              
-              if(label.anglemode != MS_NONE) label.angle = *angles[i];
-              
-              if(layer->labelcache) {
-                if(msAddLabel(map, layer->index, c, shape, annopoints[i], NULL, shape->text, *lengths[i], &label) != MS_SUCCESS) return(MS_FAILURE);
-              } else
-                msDrawLabel(map, image, *annopoints[i], shape->text, &label, layer->scalefactor);
+        if (numRegularLines > 0) {
+          annopoints = msPolylineLabelPointExtended(shape, minfeaturesize, label->repeatdistance,
+                       &angles, &lengths, &numpoints, regularLines, numRegularLines, MS_FALSE);
+
+          for (i = 0; i < numpoints; i++) {
+            label->angle = *angles[i];
+            if (msAddLabel(map, label, layer->index, c, shape, annopoints[i], NULL, *lengths[i]) != MS_SUCCESS) {
+              ret = MS_FAILURE;
+              goto anno_cleanup_line;
             }
+          }
         }
-
       } else {
-          /* Regular labels: Only attempt to find the label point if we have not */
-          /* succesfully calculated it previously                                */
-          if ( !(bLabelNoClip == MS_TRUE && annopoints) ) {
-            if ( annopoints ) {
-              for (j = 0; j<numpoints;j++) {
-                if (annopoints[j])
-                  free(annopoints[j]);
-                if (angles[j])
-                  free(angles[j]);
-                if (lengths[j])
-                  free(lengths[j]);
+        int s;
+        annopoints = msPolylineLabelPoint(shape, minfeaturesize, label->repeatdistance, &angles, &lengths, &numpoints, label->anglemode);
+
+        if (label->angle != 0)
+          label->angle -= map->gt.rotation_angle; /* apply rotation angle */
+
+        for (i = 0; i < numpoints; i++) {
+          if (label->anglemode != MS_NONE) label->angle = *angles[i]; /* angle derived from line overrides even the rotation value. */
+
+          if (layer->labelcache) {
+            if (msAddLabel(map, label, layer->index, c, shape, annopoints[i], NULL, *lengths[i]) != MS_SUCCESS) return (MS_FAILURE);
+          } else {
+            if (layer->class[c]->numstyles > 0 && MS_VALID_COLOR(layer->class[c]->styles[0]->color)) {
+              for (s = 0; s < layer->class[c]->numstyles; s++) {
+                if (msScaleInBounds(map->scaledenom, layer->class[c]->styles[s]->minscaledenom, layer->class[c]->styles[s]->maxscaledenom))
+                  msDrawMarkerSymbol(&map->symbolset, image, annopoints[i], layer->class[c]->styles[s], layer->scalefactor);
               }
-              free(lengths);
-              free(angles);
-              free(annopoints);
-              annopoints = NULL;
-              angles = NULL;
-              lengths = NULL;
             }
-            annopoints = msPolylineLabelPoint(shape, minfeaturesize, (layer->class[c]->label).repeatdistance, &angles, &lengths, &numpoints, layer->class[c]->label.anglemode);
+            msDrawLabel(map, image, *annopoints[i], label->annotext, label, layer->scalefactor);
           }
-          
-          for (i = 0; i < numpoints; i++) {
-              labelObj label = layer->class[c]->label;
-              
-              if(label.angle != 0)
-                label.angle -= map->gt.rotation_angle;
-              
-              /* Angle derived from line overrides even the rotation value. */
-              if(label.anglemode != MS_NONE) label.angle = *angles[i];
-              
-              if(layer->labelcache) {
-                if(msAddLabel(map, layer->index, c, shape, annopoints[i], NULL, shape->text, *lengths[i], &label) != MS_SUCCESS) return(MS_FAILURE);
-              } else {
-                if(layer->class[c]->numstyles > 0 && MS_VALID_COLOR(layer->class[c]->styles[0]->color)) {
-                  for(s=0; s<layer->class[c]->numstyles; s++) {
-                    styleObj *curStyle = layer->class[c]->styles[s];
-                    if(map->scaledenom > 0) {
-                      if((curStyle->maxscaledenom != -1) && (map->scaledenom >= curStyle->maxscaledenom))
-                        continue;
-                      if((curStyle->minscaledenom != -1) && (map->scaledenom < curStyle->minscaledenom))
-                        continue;
-                    }
-                    msDrawMarkerSymbol(&map->symbolset, image,  annopoints[i], curStyle, layer->scalefactor);
-                  }
-                }
-                msDrawLabel(map, image, *annopoints[i], shape->text, &label, layer->scalefactor);
-              }
-            }
-      }
-      
-      if ( annopaths ) {
-        free(annopaths);
-        annopaths = NULL;
+        }
       }
-      
-      if ( regularLines ) {
-        free(regularLines);
-        regularLines =  NULL;
-      }
-      
-      if ( annopoints ) {
-        for (j = 0; j<numpoints;j++) {
-          if (annopoints[j])
-            free(annopoints[j]);
-          if (angles[j])
-            free(angles[j]);
-          if (lengths[j])
-            free(lengths[j]);
+
+anno_cleanup_line:
+      msFree(annopaths);
+      msFree(regularLines);
+
+      if (annopoints) {
+        for (i = 0; i < numpoints; i++) {
+          if (annopoints[i]) free(annopoints[i]);
+          if (angles[i]) free(angles[i]);
+          if (lengths[i]) free(lengths[i]);
         }
         free(angles);
         free(annopoints);
         free(lengths);
-        annopoints = NULL;
-        angles = NULL;
-        lengths = NULL;
       }
-  
-      break;
+      return ret;
     case(MS_SHAPE_POLYGON):
-      /* No-clip labeling support */
-      if(shape->text && msLayerGetProcessingKey(layer, "LABEL_NO_CLIP") != NULL) {
-        bLabelNoClip = MS_TRUE;
-        if (minfeaturesize > 0)
-          annocallret = msPolygonLabelPoint(shape, &annopnt, map->cellsize*minfeaturesize);
-        else
-          annocallret = msPolygonLabelPoint(shape, &annopnt, -1);
 
-        annopnt.x = MS_MAP2IMAGE_X(annopnt.x, map->extent.minx, map->cellsize);
-        annopnt.y = MS_MAP2IMAGE_Y(annopnt.y, map->extent.maxy, map->cellsize);
-      }
-
-      if(layer->transform == MS_TRUE) {
-        msClipPolygonRect(shape, cliprect);
-        if(shape->numlines == 0) return(MS_SUCCESS);
-        msTransformShape(shape, map->extent, map->cellsize, image);
-      } else
-	msOffsetShapeRelativeTo(shape, layer);
-
-      if ((bLabelNoClip == MS_TRUE && annocallret == MS_SUCCESS) ||
-          (msPolygonLabelPoint(shape, &annopnt, minfeaturesize) == MS_SUCCESS)) {
-        labelObj label = layer->class[c]->label;
-
-        if(label.angle != 0)
-          label.angle -= map->gt.rotation_angle;
-
-        if(layer->labelcache) {
-          /*compute the bounds. Previous bounds were calculated on a non transformed shape*/
-          if (bLabelNoClip == MS_TRUE)
-            msComputeBounds(shape);
-          if(msAddLabel(map, layer->index, c, shape, &annopnt, NULL, shape->text, MS_MIN(shape->bounds.maxx-shape->bounds.minx,shape->bounds.maxy-shape->bounds.miny), &label) != MS_SUCCESS) return(MS_FAILURE);
-        } else {
-	  if(layer->class[c]->numstyles > 0 && MS_VALID_COLOR(layer->class[c]->styles[0]->color)) {
-        for(s=0; s<layer->class[c]->numstyles; s++) {
-          styleObj *curStyle = layer->class[c]->styles[s];
-          if(map->scaledenom > 0) {
-            if((curStyle->maxscaledenom != -1) && (map->scaledenom >= curStyle->maxscaledenom))
-              continue;
-            if((curStyle->minscaledenom != -1) && (map->scaledenom < curStyle->minscaledenom))
-              continue;
+      if (msPolygonLabelPoint(shape, &annopnt, minfeaturesize) == MS_SUCCESS) {
+        if(annopnt.x>0 && annopnt.y >0 && annopnt.x <= image->width && annopnt.y<=image->height) {
+          if (label->angle != 0)
+            label->angle -= map->gt.rotation_angle; /* TODO: isn't this a bug, the label angle will be changed at each feature ? */
+          if(layer->labelcache) {
+            if (msAddLabel(map, label, layer->index, c, shape, &annopnt, NULL,
+                           MS_MIN(shape->bounds.maxx - shape->bounds.minx, shape->bounds.maxy - shape->bounds.miny)) != MS_SUCCESS) {
+              return (MS_FAILURE);
+            }
+          } else {
+            if (layer->class[c]->numstyles > 0 && MS_VALID_COLOR(layer->class[c]->styles[0]->color)) {
+              for (i = 0; i < layer->class[c]->numstyles; i++) {
+                if (msScaleInBounds(map->scaledenom, layer->class[c]->styles[i]->minscaledenom, layer->class[c]->styles[i]->maxscaledenom))
+                  msDrawMarkerSymbol(&map->symbolset, image, &annopnt, layer->class[c]->styles[i], layer->scalefactor);
+              }
+            }
+            msDrawLabel(map, image, annopnt, label->annotext, label, layer->scalefactor);
           }
-	      msDrawMarkerSymbol(&map->symbolset, image, &annopnt, curStyle, layer->scalefactor);
-        }
-	  }
-	  msDrawLabel(map, image, annopnt, shape->text, &label, layer->scalefactor);
         }
       }
       break;
     default: /* points and anything with out a proper type */
-      for(j=0; j<shape->numlines;j++) {
-	for(i=0; i<shape->line[j].numpoints;i++) {
-          labelObj label = layer->class[c]->label;
-
-	  point = &(shape->line[j].point[i]);
-
-	  if(layer->transform == MS_TRUE) {
-	    if(!msPointInRect(point, &map->extent)) return(MS_SUCCESS);
-	    point->x = MS_MAP2IMAGE_X(point->x, map->extent.minx, map->cellsize);
-	    point->y = MS_MAP2IMAGE_Y(point->y, map->extent.maxy, map->cellsize);
-	  } else
-            msOffsetPointRelativeTo(point, layer);
-
-          if(label.angle != 0)
-            label.angle -= map->gt.rotation_angle;
-
-	  if(shape->text) {
-	    if(layer->labelcache) {
-	      if(msAddLabel(map, layer->index, c, shape, point, NULL, shape->text, -1, &label) != MS_SUCCESS) return(MS_FAILURE);
-	    } else {
-	      if(layer->class[c]->numstyles > 0 && MS_VALID_COLOR(layer->class[c]->styles[0]->color)) {
-            for(s=0; s<layer->class[c]->numstyles; s++) {
-              styleObj *curStyle = layer->class[c]->styles[s];
-              if(map->scaledenom > 0) {
-                if((curStyle->maxscaledenom != -1) && (map->scaledenom >= curStyle->maxscaledenom))
-                  continue;
-                if((curStyle->minscaledenom != -1) && (map->scaledenom < curStyle->minscaledenom))
-                  continue;
+      if (label->angle != 0) label->angle -= map->gt.rotation_angle;
+      for (j = 0; j < shape->numlines; j++) {
+        for (i = 0; i < shape->line[j].numpoints; i++) {
+          point = &(shape->line[j].point[i]);
+          if (!msPointInRect(point, &cliprect)) continue;
+          if (layer->labelcache) {
+            if (msAddLabel(map, label, layer->index, c, shape, point, NULL, -1) != MS_SUCCESS) return (MS_FAILURE);
+          } else {
+            if (layer->class[c]->numstyles > 0 && MS_VALID_COLOR(layer->class[c]->styles[0]->color)) {
+              for (s = 0; s < layer->class[c]->numstyles; s++) {
+                if (msScaleInBounds(map->scaledenom, layer->class[c]->styles[s]->minscaledenom, layer->class[c]->styles[s]->maxscaledenom))
+                  msDrawMarkerSymbol(&map->symbolset, image, point, layer->class[c]->styles[s], layer->scalefactor);
               }
-	          msDrawMarkerSymbol(&map->symbolset, image, point, curStyle, layer->scalefactor);
             }
-	      }
-	      msDrawLabel(map, image, *point, shape->text, &label, layer->scalefactor);
-	    }
-	  }
-	}
+            msDrawLabel(map, image, *point, label->annotext, label, layer->scalefactor);
+          }
+        }
       }
-    }
-    break;  /* end MS_LAYER_ANNOTATION */
+  }
+  return MS_SUCCESS;
+}
 
-  case MS_LAYER_POINT:
-  case MS_LAYER_RASTER:
+int pointLayerDrawShape(mapObj *map, imageObj *image, layerObj *layer, shapeObj *shape, int drawmode)
+{
+  int l, c = shape->classindex, j, i, s;
+  pointObj *point;
 
 #ifdef USE_PROJ
-    if(layer->transform == MS_TRUE && layer->project && msProjectionsDiffer(&(layer->projection), &(map->projection)))
-      msProjectShape(&layer->projection, &map->projection, shape);
-    else
-      layer->project = MS_FALSE;
+  if (layer->project && layer->transform == MS_TRUE && msProjectionsDiffer(&(layer->projection), &(map->projection)))
+    msProjectShape(&layer->projection, &map->projection, shape);
+  else
+    layer->project = MS_FALSE;
 #endif
 
-    for(j=0; j<shape->numlines;j++) {
-      for(i=0; i<shape->line[j].numpoints;i++) {
-	point = &(shape->line[j].point[i]);
-
-	if(layer->transform == MS_TRUE) {
-	  if(!msPointInRect(point, &map->extent)) continue; /* next point */
-          msTransformPoint(point, &map->extent, map->cellsize, image);
-	} else
-          msOffsetPointRelativeTo(point, layer);
+  for (l = 0; l < layer->class[c]->numlabels; l++)
+    if (layer->class[c]->labels[l]->angle != 0) layer->class[c]->labels[l]->angle -= map->gt.rotation_angle; /* TODO: is this right???? */
 
-        for(s=0; s<layer->class[c]->numstyles; s++) {
-          styleObj *curStyle = layer->class[c]->styles[s];
-          if(map->scaledenom > 0) {
-            if((curStyle->maxscaledenom != -1) && (map->scaledenom >= curStyle->maxscaledenom))
-              continue;
-            if((curStyle->minscaledenom != -1) && (map->scaledenom < curStyle->minscaledenom))
-              continue;
-	  }
-          msDrawMarkerSymbol(&map->symbolset, image, point, (layer->class[c]->styles[s]), layer->scalefactor);
+  for (j = 0; j < shape->numlines; j++) {
+    for (i = 0; i < shape->line[j].numpoints; i++) {
+      point = &(shape->line[j].point[i]);
+      if (layer->transform == MS_TRUE) {
+        if (!msPointInRect(point, &map->extent)) continue; /* next point */
+        msTransformPoint(point, &map->extent, map->cellsize, image);
+      } else
+        msOffsetPointRelativeTo(point, layer);
+
+      if(MS_DRAW_FEATURES(drawmode)) {
+        for (s = 0; s < layer->class[c]->numstyles; s++) {
+          if (msScaleInBounds(map->scaledenom,
+              layer->class[c]->styles[s]->minscaledenom,
+              layer->class[c]->styles[s]->maxscaledenom))
+            msDrawMarkerSymbol(&map->symbolset, image, point, layer->class[c]->styles[s], layer->scalefactor);
         }
-
-	if(shape->text) {
-          labelObj label = layer->class[c]->label;
-
-          if(label.angle != 0)
-            label.angle -= map->gt.rotation_angle;
-
-	  if(layer->labelcache) {
-	    if(msAddLabel(map, layer->index, c, shape, point, NULL, shape->text, -1, &label) != MS_SUCCESS) return(MS_FAILURE);
-	  } else
-	    msDrawLabel(map, image, *point, shape->text, &label, layer->scalefactor);
-	}
       }
-    }
-    break; /* end MS_LAYER_POINT */
-
-  case MS_LAYER_LINE:    
-    if(shape->type != MS_SHAPE_POLYGON && shape->type != MS_SHAPE_LINE) {
-      msSetError(MS_MISCERR, "Only polygon or line shapes can be drawn using a line layer definition.", "msDrawShape()");
-      return(MS_FAILURE);
-    }
-
-#ifdef USE_PROJ
-    if(layer->transform == MS_TRUE && layer->project && msProjectionsDiffer(&(layer->projection), &(map->projection)))
-      msProjectShape(&layer->projection, &map->projection, shape);
-    else
-      layer->project = MS_FALSE;
-#endif
-
-    /* No-clip labeling support. For lines we copy the shape, though this is */
-    /* inefficient. msPolylineLabelPath/msPolylineLabelPoint require that    */
-    /* the shape is transformed prior to calling them                        */
-    if(shape->text && msLayerGetProcessingKey(layer, "LABEL_NO_CLIP") != NULL) {
-      shapeObj annoshape;
-      bLabelNoClip = MS_TRUE;
-
-      msInitShape(&annoshape);
-      msCopyShape(shape, &annoshape);
-      msTransformShape(&annoshape, map->extent, map->cellsize, image);
-
-      if(layer->class[c]->label.anglemode == MS_FOLLOW) {
-        if (layer->class[c]->label.type != MS_TRUETYPE) {
-           msSetError(MS_MISCERR, "Angle mode 'FOLLOW' is supported only with truetype fonts.", "msDrawShape()");
-           return(MS_FAILURE);
+      if(MS_DRAW_LABELS(drawmode)) {
+        if (layer->labelcache) {
+          if (msAddLabelGroup(map, layer->index, c, shape, point, -1) != MS_SUCCESS) return (MS_FAILURE);
+        } else {
+          for (l = 0; l < layer->class[c]->numlabels; l++)
+            msDrawLabel(map, image, *point, layer->class[c]->labels[l]->annotext, layer->class[c]->labels[l], layer->scalefactor);
         }
-        annopaths = msPolylineLabelPath(map,image,&annoshape, minfeaturesize, &(map->fontset), shape->text, &(layer->class[c]->label), layer->scalefactor, &numpaths, &regularLines, &numRegularLines);
-      } else {
-        annopoints = msPolylineLabelPoint(&annoshape, minfeaturesize, (layer->class[c]->label).repeatdistance, &angles, &lengths, &numpoints, layer->class[c]->label.anglemode);
-      }
-      msFreeShape(&annoshape);
-    }
-
-    for(s=0;s<layer->class[c]->numstyles;s++){
-      if(layer->class[c]->styles[s]->_geomtransform.type != MS_GEOMTRANSFORM_NONE) {
-        hasGeomTransform = MS_TRUE;
-        break;
       }
     }
+  }
+  return MS_SUCCESS;
+}
 
-    if(hasGeomTransform) {
-      msInitShape(&nonClippedShape);
-      msCopyShape(shape,&nonClippedShape);
-    }
-
-    if(layer->transform == MS_TRUE) {
-        if(shape->type == MS_SHAPE_POLYGON)
-          msClipPolygonRect(shape, cliprect);
-        else
-          msClipPolylineRect(shape, cliprect);
-      if(shape->numlines == 0) {
-        if(hasGeomTransform)
-          msFreeShape(&nonClippedShape);   
-        return(MS_SUCCESS);
-      }
-      msTransformShape(shape, map->extent, map->cellsize, image);
-      if(hasGeomTransform)
-        msTransformShape(&nonClippedShape, map->extent, map->cellsize, image);
-    } else {
-      msOffsetShapeRelativeTo(shape, layer);
-    }
-    
-    if(hasGeomTransform)
-      msOffsetShapeRelativeTo(&nonClippedShape, layer);
-	
-    /*RFC48: loop through the styles, and pass off to the type-specific
-    function if the style has an appropriate type*/
-    for(s=0; s<layer->class[c]->numstyles; s++) {
-      styleObj *curStyle = layer->class[c]->styles[s];
-      if(map->scaledenom > 0) {
-        if((curStyle->maxscaledenom != -1) && (map->scaledenom >= curStyle->maxscaledenom))
-          continue;
-        if((curStyle->minscaledenom != -1) && (map->scaledenom < curStyle->minscaledenom))
-          continue;
+int lineLayerDrawShape(mapObj *map, imageObj *image, layerObj *layer, shapeObj *shape,
+                       shapeObj *anno_shape, shapeObj *unclipped_shape, int style, int drawmode)
+{
+  int c = shape->classindex;
+  double minfeaturesize;
+  labelPathObj **annopaths = NULL; /* Curved label path. Bug #1620 implementation */
+  pointObj **annopoints = NULL;
+  int *regularLines = NULL;
+  double** angles = NULL, **lengths = NULL;
+  int ret = MS_SUCCESS;
+  int numpaths = 1, numpoints = 1, numRegularLines = 0, i, j, s, l = 0;
+
+  /* RFC48: loop through the styles, and pass off to the type-specific
+  function if the style has an appropriate type */
+  if(MS_DRAW_FEATURES(drawmode)) {
+    for (s = 0; s < layer->class[c]->numstyles; s++) {
+      if (msScaleInBounds(map->scaledenom,
+          layer->class[c]->styles[s]->minscaledenom,
+          layer->class[c]->styles[s]->maxscaledenom)) {
+        if (layer->class[c]->styles[s]->_geomtransform.type != MS_GEOMTRANSFORM_NONE)
+          msDrawTransformedShape(map, &map->symbolset, image, unclipped_shape, layer->class[c]->styles[s], layer->scalefactor);
+        else if (!MS_DRAW_SINGLESTYLE(drawmode) || s == style)
+          msDrawLineSymbol(&map->symbolset, image, shape, layer->class[c]->styles[s], layer->scalefactor);
       }
-      if(curStyle->_geomtransform.type != MS_GEOMTRANSFORM_NONE)
-        msDrawTransformedShape(map, &map->symbolset, image, &nonClippedShape, curStyle, layer->scalefactor);
-      else if(style==-1 || s==style)
-        msDrawLineSymbol(&map->symbolset, image, shape, curStyle, layer->scalefactor);
     }
-    
-    /*RFC48: free non clipped shape if it was previously alloced/used*/
-    if(hasGeomTransform)
-      msFreeShape(&nonClippedShape);
-    
-    if(shape->text) {
+  }
+  
+  if(MS_DRAW_LABELS(drawmode)) {
+    for (l = 0; l < layer->class[c]->numlabels; l++) {
+      labelObj *label = layer->class[c]->labels[l];
+      minfeaturesize = label->minfeaturesize * image->resolutionfactor;
 
-      if (layer->class[c]->label.anglemode == MS_FOLLOW) 
-      {
-        if (layer->class[c]->label.type != MS_TRUETYPE) {
+      if (label->anglemode == MS_FOLLOW) { /* bug #1620 implementation */
+        if (label->type != MS_TRUETYPE) {
           msSetError(MS_MISCERR, "Angle mode 'FOLLOW' is supported only with truetype fonts.", "msDrawShape()");
-          return(MS_FAILURE);
+          ret = MS_FAILURE;
+          goto line_cleanup;
         }
-        /* Determine the label path if it has not been computed above */
-        if (bLabelNoClip == MS_FALSE) {
-          if ( annopaths ) {
-            for (j = 0; j<numpaths;j++)
-              if (annopaths[j])
-                msFreeLabelPathObj(annopaths[j]);
-            free(annopaths);
-            annopaths = NULL;
-          }
-          if ( regularLines ) {
-            free(regularLines);
-            regularLines =  NULL;
-          }
-          annopaths = msPolylineLabelPath(map,image,shape, minfeaturesize, &(map->fontset), shape->text, &(layer->class[c]->label), layer->scalefactor, &numpaths, &regularLines, &numRegularLines);
-        }
-
-        for (i = 0; i < numpaths; i++)
-        {
-          /* Bug #1620 implementation */
-            if(layer->class[c]->label.anglemode == MS_FOLLOW) {
-            labelObj label;
-
-            if (layer->class[c]->label.type != MS_TRUETYPE) {
-              msSetError(MS_MISCERR, "Angle mode 'FOLLOW' is supported only with truetype fonts.", "msDrawShape()");
-              return(MS_FAILURE);
-            }
+        annopaths = msPolylineLabelPath(map, image, anno_shape, minfeaturesize, &(map->fontset),
+                                        label->annotext, label, layer->scalefactor, &numpaths, &regularLines, &numRegularLines);
 
-            layer->class[c]->label.position = MS_CC; /* Force all label positions to MS_CC regardless if a path is computed */
+        for (i = 0; i < numpaths; i++) {
+          label->position = MS_CC; /* force all label positions to MS_CC regardless if a path is computed */
 
-            label = layer->class[c]->label;
-            
-            if(layer->labelcache) {
-              if(msAddLabel(map, layer->index, c, shape, NULL, annopaths[i], shape->text, -1, &label) != MS_SUCCESS) return(MS_FAILURE);
+          if (annopaths[i]) {
+            if (layer->labelcache) {
+              if (msAddLabel(map, label, layer->index, c, anno_shape, NULL, annopaths[i], -1) != MS_SUCCESS) {
+                ret = MS_FAILURE;
+                goto line_cleanup;
+              }
             } else {
-              /* FIXME: need to call msDrawTextLineGD() from here eventually */
-              /* msDrawLabel(image, label_line->point[0], shape->text, &label, &map->fontset, layer->scalefactor); */
+              /* TODO: handle drawing curved labels outside the cache */
               msFreeLabelPathObj(annopaths[i]);
               annopaths[i] = NULL;
             }
           }
         }
+
         /* handle regular lines that have to be drawn with the regular algorithm */
-        if (numRegularLines > 0)
-        {
-
-          annopoints = msPolylineLabelPointExtended(shape, minfeaturesize, (layer->class[c]->label).repeatdistance, &angles, &lengths, &numpoints, regularLines, numRegularLines, MS_FALSE);
-          
-          for (i = 0; i < numpoints; i++)
-          {
-            labelObj label = layer->class[c]->label;
-            
-            if(label.angle != 0)
-              label.angle -= map->gt.rotation_angle;
-            
-            if(label.anglemode != MS_NONE) label.angle = *angles[i];
-            
-            if(layer->labelcache) {
-              if(msAddLabel(map, layer->index, c, shape, annopoints[i], NULL, shape->text, *lengths[i], &label) != MS_SUCCESS) return(MS_FAILURE);
-            } else
-              msDrawLabel(map, image, *annopoints[i], shape->text, &label, layer->scalefactor);
+        if (numRegularLines > 0) {
+          annopoints = msPolylineLabelPointExtended(anno_shape, minfeaturesize, label->repeatdistance,
+                       &angles, &lengths, &numpoints, regularLines, numRegularLines, MS_FALSE);
+
+          for (i = 0; i < numpoints; i++) {
+            label->angle = *angles[i];
+            if (layer->labelcache) {
+              if (msAddLabel(map, label, layer->index, c, anno_shape, annopoints[i], NULL, *lengths[i]) != MS_SUCCESS) {
+                ret = MS_FAILURE;
+                goto line_cleanup;
+              }
+            } else {
+              msDrawLabel(map, image, *annopoints[i], label->annotext, label, layer->scalefactor);
+            }
           }
         }
       } else {
-        if ( !(bLabelNoClip == MS_TRUE && annopoints) ) {
-          if ( annopoints ) {
-            for (j = 0; j<numpoints;j++) {
-              if (annopoints[j])
-                free(annopoints[j]);
-              if (angles[j])
-                free(angles[j]);
-              if (lengths[j])
-                free(lengths[j]);
+        annopoints = msPolylineLabelPoint(anno_shape, minfeaturesize, label->repeatdistance, &angles,
+                                          &lengths, &numpoints, label->anglemode);
+
+        if (label->angle != 0)
+          label->angle -= map->gt.rotation_angle; /* apply rotation angle */
+
+        for (i = 0; i < numpoints; i++) {
+          if (label->anglemode != MS_NONE) label->angle = *angles[i]; /* angle derived from line overrides even the rotation value. */
+
+          if (layer->labelcache) {
+            if (msAddLabel(map, label, layer->index, c, anno_shape, annopoints[i], NULL, *lengths[i]) != MS_SUCCESS) {
+              ret = MS_FAILURE;
+              goto line_cleanup;
             }
-            free(lengths);
-            free(angles);
-            free(annopoints);
-            annopoints = NULL;
-            angles = NULL;
-            lengths = NULL;
+          } else {
+            msDrawLabel(map, image, *annopoints[i], label->annotext, label, layer->scalefactor);
           }
-          annopoints = msPolylineLabelPoint(shape, minfeaturesize, (layer->class[c]->label).repeatdistance, &angles, &lengths, &numpoints, layer->class[c]->label.anglemode);
         }
+      }
 
-        for (i = 0; i < numpoints; i++) {
-          labelObj label = layer->class[c]->label;
-          
-          if(label.angle != 0)
-            label.angle -= map->gt.rotation_angle;
-          
-          if(label.anglemode != MS_NONE) label.angle = *angles[i];
-          
-          if(layer->labelcache) {
-            if(msAddLabel(map, layer->index, c, shape, annopoints[i], NULL, shape->text, *lengths[i], &label) != MS_SUCCESS) return(MS_FAILURE);
-          } else
-            msDrawLabel(map, image, *annopoints[i], shape->text, &label, layer->scalefactor);
+line_cleanup:
+      /* clean up and reset */
+      if (annopaths) {
+        free(annopaths);
+        annopaths = NULL;
+      }
+
+      if (regularLines) {
+        free(regularLines);
+        regularLines = NULL;
+      }
+
+      if (annopoints) {
+        for (j = 0; j < numpoints; j++) {
+          if (annopoints[j]) free(annopoints[j]);
+          if (angles[j]) free(angles[j]);
+          if (lengths[j]) free(lengths[j]);
         }
+        free(angles);
+        free(annopoints);
+        free(lengths);
+        annopoints = NULL;
+        angles = NULL;
+        lengths = NULL;
+      }
+      if (ret == MS_FAILURE) {
+        break; /* from the label looping */
+      }
+    } /* next label */
+  }
+
+  return ret;
+
+}
+
+int polygonLayerDrawShape(mapObj *map, imageObj *image, layerObj *layer,
+                          shapeObj *shape, shapeObj *anno_shape, shapeObj *unclipped_shape, int drawmode)
+{
+
+  int c = shape->classindex;
+  pointObj annopnt;
+  int i;
+
+  if(MS_DRAW_FEATURES(drawmode)) {
+    for (i = 0; i < layer->class[c]->numstyles; i++) {
+      if (msScaleInBounds(map->scaledenom, layer->class[c]->styles[i]->minscaledenom,
+                          layer->class[c]->styles[i]->maxscaledenom)) {
+        if (layer->class[c]->styles[i]->_geomtransform.type == MS_GEOMTRANSFORM_NONE)
+          msDrawShadeSymbol(&map->symbolset, image, shape, layer->class[c]->styles[i], layer->scalefactor);
+        else
+          msDrawTransformedShape(map, &map->symbolset, image, unclipped_shape,
+                                 layer->class[c]->styles[i], layer->scalefactor);
       }
     }
+  }
 
-    if ( annopaths ) {
-      free(annopaths);
-      annopaths = NULL;
+  if(MS_DRAW_LABELS(drawmode)) {
+    if (layer->class[c]->numlabels > 0) {
+      double minfeaturesize = layer->class[c]->labels[0]->minfeaturesize * image->resolutionfactor;
+      if (msPolygonLabelPoint(anno_shape, &annopnt, minfeaturesize) == MS_SUCCESS) {
+        for (i = 0; i < layer->class[c]->numlabels; i++)
+          if (layer->class[c]->labels[i]->angle != 0) layer->class[c]->labels[i]->angle -= map->gt.rotation_angle; /* TODO: is this correct ??? */
+        if (layer->labelcache) {
+          if (msAddLabelGroup(map, layer->index, c, anno_shape, &annopnt,
+                              MS_MIN(shape->bounds.maxx - shape->bounds.minx, shape->bounds.maxy - shape->bounds.miny)) != MS_SUCCESS) {
+            return MS_FAILURE;
+          }
+        } else {
+          for (i = 0; i < layer->class[c]->numlabels; i++)
+            msDrawLabel(map, image, annopnt, layer->class[c]->labels[i]->annotext,
+                        layer->class[c]->labels[i], layer->scalefactor);
+        }
+      }
     }
+  }
+  return MS_SUCCESS;
+}
+
+/*
+** Function to render an individual shape, the style variable enables/disables the drawing of a single style
+** versus a single style. This is necessary when drawing entire layers as proper overlay can only be achived
+** through caching. "querymapMode" parameter is used to tell msBindLayerToShape to not override the
+** QUERYMAP HILITE color.
+*/
+int msDrawShape(mapObj *map, layerObj *layer, shapeObj *shape, imageObj *image, int style, int drawmode)
+{
+  int c,s,ret=MS_SUCCESS;
+  shapeObj *anno_shape, *unclipped_shape = shape;
+  int bNeedUnclippedShape = MS_FALSE;
+  int bNeedUnclippedAnnoShape = MS_FALSE;
+  int bShapeNeedsClipping = MS_TRUE;
+
+  if(shape->numlines == 0 || shape->type == MS_SHAPE_NULL) return MS_SUCCESS;
+
+  msDrawStartShape(map, layer, image, shape);
+  c = shape->classindex;
+
+  /* Before we do anything else, we will check for a rangeitem.
+     If its there, we need to change the style's color to map
+     the range to the shape */
+  for(s=0; s<layer->class[c]->numstyles; s++) {
+    styleObj *style = layer->class[c]->styles[s];
+    if(style->rangeitem !=  NULL)
+      msShapeToRange((layer->class[c]->styles[s]), shape);
+  }
+
+  /* circle and point layers go through their own treatment */
+  if(layer->type == MS_LAYER_CIRCLE) {
+    if(msBindLayerToShape(layer, shape, drawmode) != MS_SUCCESS) return MS_FAILURE;
+    ret = circleLayerDrawShape(map,image,layer,shape);
+    msDrawEndShape(map,layer,image,shape);
+    return ret;
+  } else if(layer->type == MS_LAYER_POINT || layer->type == MS_LAYER_RASTER) {
+    if(msBindLayerToShape(layer, shape, drawmode) != MS_SUCCESS) return MS_FAILURE;
+    ret = pointLayerDrawShape(map,image,layer,shape,drawmode);
+    msDrawEndShape(map,layer,image,shape);
+    return ret;
+  }
+
+  if (layer->type == MS_LAYER_POLYGON && shape->type != MS_SHAPE_POLYGON) {
+    msSetError(MS_MISCERR, "Only polygon shapes can be drawn using a polygon layer definition.", "polygonLayerDrawShape()");
+    return (MS_FAILURE);
+  }
+  if (layer->type == MS_LAYER_LINE && shape->type != MS_SHAPE_POLYGON && shape->type != MS_SHAPE_LINE) {
+    msSetError(MS_MISCERR, "Only polygon or line shapes can be drawn using a line layer definition.", "msDrawShape()");
+    return (MS_FAILURE);
+  }
 
-    if ( regularLines ) {
-      free(regularLines);
-      regularLines =  NULL;
+#ifdef USE_PROJ
+  if (layer->project && layer->transform == MS_TRUE && msProjectionsDiffer(&(layer->projection), &(map->projection)))
+    msProjectShape(&layer->projection, &map->projection, shape);
+  else
+    layer->project = MS_FALSE;
+#endif
+
+  /* check if we'll need the unclipped shape */
+  if (shape->type != MS_SHAPE_POINT) {
+    if(MS_DRAW_FEATURES(drawmode)) {
+      for (s = 0; s < layer->class[c]->numstyles; s++) {
+        styleObj *style = layer->class[c]->styles[s];
+        if (style->_geomtransform.type != MS_GEOMTRANSFORM_NONE)
+          bNeedUnclippedShape = MS_TRUE;
+      }
     }
-    
-    if ( annopoints ) {
-      for (j = 0; j<numpoints;j++) {
-        if (annopoints[j])
-          free(annopoints[j]);
-        if (angles[j])
-          free(angles[j]);
-        if (lengths[j])
-          free(lengths[j]);
-      }
-      free(angles);
-      free(annopoints);
-      free(lengths);
-      annopoints = NULL;
-      angles = NULL;
-      lengths = NULL;
-    }
-
-    break;
-
-  case MS_LAYER_POLYGON:
-    if(shape->type != MS_SHAPE_POLYGON) {
-      msSetError(MS_MISCERR, "Only polygon shapes can be drawn using a POLYGON layer definition.", "msDrawShape()");
-      return(MS_FAILURE);
+    /* check if we need to clip the shape */
+    if (shape->bounds.minx < map->extent.minx ||
+        shape->bounds.miny < map->extent.miny ||
+        shape->bounds.maxx > map->extent.maxx ||
+        shape->bounds.maxy > map->extent.maxy) {
+      bShapeNeedsClipping = MS_TRUE;
+    }
+   
+    if(MS_DRAW_LABELS(drawmode) && MS_DRAW_UNCLIPPED_LABELS(drawmode)) {
+      bNeedUnclippedAnnoShape = MS_TRUE;
+      bNeedUnclippedShape = MS_TRUE;
     }
 
-#ifdef USE_PROJ
-    if(layer->transform == MS_TRUE && layer->project && msProjectionsDiffer(&(layer->projection), &(map->projection))) {
-      if(msProjectShape(&layer->projection, &map->projection, shape) == MS_FAILURE ) {
-#ifdef notdef 
-        msSetError(MS_PROJERR, "Reprojecting a shape failed.", "msDrawShape()" );
+    if(MS_DRAW_UNCLIPPED_LINES(drawmode)) {
+      bShapeNeedsClipping = MS_FALSE;
+    }
+  } else {
+    bShapeNeedsClipping = MS_FALSE;
+  }
+
+  if(layer->transform == MS_TRUE && bShapeNeedsClipping) {
+    /* compute the size of the clipping buffer, in pixels. This buffer must account
+     for the size of symbols drawn to avoid artifacts around the image edges */
+    int clip_buf = 0;
+    int s;
+    rectObj cliprect;
+    for (s=0;s<layer->class[c]->numstyles;s++) {
+      double maxsize, maxunscaledsize;
+      symbolObj *symbol;
+      styleObj *style = layer->class[c]->styles[s];
+      if (!MS_IS_VALID_ARRAY_INDEX(style->symbol, map->symbolset.numsymbols)) {
+        msSetError(MS_SYMERR, "Invalid symbol index: %d", "msDrawShape()", style->symbol);
         return MS_FAILURE;
+      }
+      symbol = map->symbolset.symbol[style->symbol];
+      if (symbol->type == MS_SYMBOL_PIXMAP) {
+        if (MS_SUCCESS != msPreloadImageSymbol(MS_MAP_RENDERER(map), symbol))
+          return MS_FAILURE;
+      } else if (symbol->type == MS_SYMBOL_SVG) {
+#ifdef USE_SVG_CAIRO
+        if (MS_SUCCESS != msPreloadSVGSymbol(symbol))
+          return MS_FAILURE;
 #else
-        return MS_SUCCESS;
+        msSetError(MS_SYMERR, "SVG symbol support is not enabled.", "msDrawShape()");
+        return MS_FAILURE;
 #endif
       }
-    } else
-      layer->project = MS_FALSE;
-#endif
-
-    /* No-clip labeling support */
-    if(shape->text && msLayerGetProcessingKey(layer, "LABEL_NO_CLIP") != NULL) {
-      bLabelNoClip = MS_TRUE;
-      if (layer->class[c]->label.minfeaturesize > 0)
-        annocallret = msPolygonLabelPoint(shape, &annopnt, map->cellsize*minfeaturesize);
-      else
-        annocallret = msPolygonLabelPoint(shape, &annopnt, -1);
-
-      annopnt.x = MS_MAP2IMAGE_X(annopnt.x, map->extent.minx, map->cellsize);
-      annopnt.y = MS_MAP2IMAGE_Y(annopnt.y, map->extent.maxy, map->cellsize);
+      maxsize = MS_MAX(msSymbolGetDefaultSize(symbol), MS_MAX(style->size, style->width));
+      maxunscaledsize = MS_MAX(style->minsize*image->resolutionfactor, style->minwidth*image->resolutionfactor);
+      clip_buf = MS_MAX(clip_buf,MS_NINT(MS_MAX(maxsize * layer->scalefactor, maxunscaledsize) + 1));
     }
 
-    for(s=0;s<layer->class[c]->numstyles;s++){
-      if(layer->class[c]->styles[s]->_geomtransform.type != MS_GEOMTRANSFORM_NONE) {
-        hasGeomTransform = MS_TRUE;
-        break;
+
+    /* if we need a copy of the unclipped shape, transform first, then clip to avoid transforming twice */
+    if(bNeedUnclippedShape) {
+      msTransformShape(shape, map->extent, map->cellsize, image);
+      if(shape->numlines == 0) return MS_SUCCESS;
+      msComputeBounds(shape);
+
+      /* TODO: there's an optimization here that can be implemented:
+         - no need to allocate unclipped_shape for each call to this function
+         - the calls to msClipXXXRect will discard the original lineObjs, whereas
+           we have just copied them because they where needed. These two functions
+           could be changed so they are instructed not to free the original lineObjs. */
+      unclipped_shape = (shapeObj *) msSmallMalloc(sizeof (shapeObj));
+      msInitShape(unclipped_shape);
+      msCopyShape(shape, unclipped_shape);
+      if(shape->type == MS_SHAPE_POLYGON) {
+         /* #179: additional buffer for polygons */
+         clip_buf += 2;
       }
-    }
 
-    if(hasGeomTransform) {
-      msInitShape(&nonClippedShape);
-      msCopyShape(shape,&nonClippedShape);
+      cliprect.minx = cliprect.miny = -clip_buf;
+      cliprect.maxx = image->width + clip_buf;
+      cliprect.maxy = image->height + clip_buf;
+      if(shape->type == MS_SHAPE_POLYGON) {
+        msClipPolygonRect(shape, cliprect);
+      } else {
+        assert(shape->type == MS_SHAPE_LINE);
+        msClipPolylineRect(shape, cliprect);
+      }
+      if(bNeedUnclippedAnnoShape) {
+        anno_shape = unclipped_shape;
+      } else {
+        anno_shape = shape;
+      }
+    } else {
+      /* clip first, then transform. This means we are clipping in geographical space */
+      double clip_buf_d;
+      if(shape->type == MS_SHAPE_POLYGON) {
+         /*
+          * add a small buffer around the cliping rectangle to
+          * avoid lines around the edges : #179
+          */
+         clip_buf += 2;
+      }
+      clip_buf_d = clip_buf * map->cellsize;
+      cliprect.minx = map->extent.minx - clip_buf_d;
+      cliprect.miny = map->extent.miny - clip_buf_d;
+      cliprect.maxx = map->extent.maxx + clip_buf_d;
+      cliprect.maxy = map->extent.maxy + clip_buf_d;
+      if(shape->type == MS_SHAPE_POLYGON) {
+        msClipPolygonRect(shape, cliprect);
+      } else {
+        assert(shape->type == MS_SHAPE_LINE);
+        msClipPolylineRect(shape, cliprect);
+      }
+      msTransformShape(shape, map->extent, map->cellsize, image);
+      msComputeBounds(shape);
+      anno_shape = shape;
     }
 
-    if(layer->transform == MS_TRUE) {
-      /*
-       * add a small buffer around the cliping rectangle to
-       * avoid lines around the edges : Bug 179
-       */
-      buffer = (map->extent.maxx -  map->extent.minx)/map->width;
-      buffer = buffer *2;
-      cliprect.minx -= buffer;
-      cliprect.miny -= buffer;
-      cliprect.maxx += buffer;
-      cliprect.maxy += buffer;
-
-      msClipPolygonRect(shape, cliprect);
-      if(shape->numlines == 0) {
-        if(hasGeomTransform)
-          msFreeShape(&nonClippedShape);   
-        return(MS_SUCCESS);
-      }
+  } else {
+    /* the shape is fully in the map extent,
+     * or is a point type layer where out of bounds points are treated differently*/
+    if (layer->transform == MS_TRUE) {
       msTransformShape(shape, map->extent, map->cellsize, image);
-      if(hasGeomTransform)
-        msTransformShape(&nonClippedShape, map->extent, map->cellsize, image);
+      msComputeBounds(shape);
     } else {
       msOffsetShapeRelativeTo(shape, layer);
-      if(hasGeomTransform)
-        msTransformShape(&nonClippedShape, map->extent, map->cellsize, image);
-    }
- 
-    for(s=0; s<layer->class[c]->numstyles; s++) {
-      styleObj *curStyle = layer->class[c]->styles[s];
-      if(map->scaledenom > 0) {
-        if((curStyle->maxscaledenom != -1) && (map->scaledenom >= curStyle->maxscaledenom))
-          continue;
-        if((curStyle->minscaledenom != -1) && (map->scaledenom < curStyle->minscaledenom))
-          continue;
-      }
-      if(curStyle->_geomtransform.type == MS_GEOMTRANSFORM_NONE)
-    	msDrawShadeSymbol(&map->symbolset, image, shape, curStyle, layer->scalefactor);
-      else
-    	msDrawTransformedShape(map, &map->symbolset, image, &nonClippedShape, curStyle, layer->scalefactor);
     }
-    if(hasGeomTransform)
-      msFreeShape(&nonClippedShape);
-
-    if(shape->text) {
-      if((bLabelNoClip == MS_TRUE && annocallret == MS_SUCCESS) ||
-         (msPolygonLabelPoint(shape, &annopnt, minfeaturesize) == MS_SUCCESS)) {
-        labelObj label = layer->class[c]->label;
-
-        if(label.angle != 0)
-          label.angle -= map->gt.rotation_angle;
+    anno_shape = shape;
+  }
+  if(shape->numlines == 0) {
+    ret = MS_SUCCESS; /* error message is set in msBindLayerToShape() */
+    goto draw_shape_cleanup;
+  }
 
-	if(layer->labelcache) {
-          /*compute the bounds. Previous bounds were calculated on a non transformed shape*/
-        if (bLabelNoClip == MS_TRUE)
-          msComputeBounds(shape);
-	  if(msAddLabel(map, layer->index, c, shape, &annopnt, NULL, shape->text, MS_MIN(shape->bounds.maxx-shape->bounds.minx,shape->bounds.maxy-shape->bounds.miny), &label) != MS_SUCCESS) return(MS_FAILURE);
-	} else
-	  msDrawLabel(map, image, annopnt, shape->text, &label, layer->scalefactor);
-      }
-    }
-    break;
-  default:
-    msSetError(MS_MISCERR, "Unknown layer type.", "msDrawShape()");
-    return(MS_FAILURE);
+  if(msBindLayerToShape(layer, shape, drawmode) != MS_SUCCESS) {
+    ret = MS_FAILURE; /* error message is set in msBindLayerToShape() */
+    goto draw_shape_cleanup;
   }
 
+  switch(layer->type) {
+    case MS_LAYER_ANNOTATION:
+      if(MS_DRAW_LABELS(drawmode))
+        ret = annotationLayerDrawShape(map, image, layer, anno_shape);
+      else
+        ret = MS_SUCCESS;
+      break;
+    case MS_LAYER_LINE:
+      ret = lineLayerDrawShape(map, image, layer, shape, anno_shape, unclipped_shape, style, drawmode);
+      break;
+    case MS_LAYER_POLYGON:
+      ret = polygonLayerDrawShape(map, image, layer, shape, anno_shape, unclipped_shape, drawmode);
+      break;
+    case MS_LAYER_POINT:
+    case MS_LAYER_RASTER:
+      assert(0); //bug !
+    default:
+      msSetError(MS_MISCERR, "Unknown layer type.", "msDrawShape()");
+      ret = MS_FAILURE;
+  }
 
-  return(MS_SUCCESS);
+draw_shape_cleanup:
+  msDrawEndShape(map,layer,image,shape);
+  if(unclipped_shape != shape) {
+    msFreeShape(unclipped_shape);
+    msFree(unclipped_shape);
+  }
+  return ret;
 }
 
 /*
 ** Function to render an individual point, used as a helper function for mapscript only. Since a point
 ** can't carry attributes you can't do attribute based font size or angle.
 */
-int msDrawPoint(mapObj *map, layerObj *layer, pointObj *point, imageObj *image, 
-                int classindex, char *labeltext)
+int msDrawPoint(mapObj *map, layerObj *layer, pointObj *point, imageObj *image, int classindex, char *labeltext)
 {
   int s;
-  char *newtext;
   classObj *theclass=layer->class[classindex];
-  labelObj *label=&(theclass->label);
- 
+  labelObj *label=NULL;
+
 #ifdef USE_PROJ
   if(layer->transform == MS_TRUE && layer->project && msProjectionsDiffer(&(layer->projection), &(map->projection)))
     msProjectPoint(&layer->projection, &map->projection, point);
   else
     layer->project = MS_FALSE;
 #endif
-  
-  /* apply wrap character and encoding to the label text */
-  if(labeltext &&(label->encoding || label->wrap || label->maxlength))
-      newtext = msTransformLabelText(map,image,label,labeltext);
-  else
-      newtext=labeltext;
+
+  if(labeltext && theclass->numlabels > 0) {
+    label = theclass->labels[0];
+
+    msFree(label->annotext); /* free any previously allocated annotation text */
+    if(labeltext && (label->encoding || label->wrap || label->maxlength))
+      label->annotext = msTransformLabelText(map,label,labeltext); /* apply wrap character and encoding to the label text */
+    else
+      label->annotext = msStrdup(labeltext);
+  }
+
   switch(layer->type) {
-  case MS_LAYER_ANNOTATION:
-    if(layer->transform == MS_TRUE) {
-      if(!msPointInRect(point, &map->extent)) return(0);
-      point->x = MS_MAP2IMAGE_X(point->x, map->extent.minx, map->cellsize);
-      point->y = MS_MAP2IMAGE_Y(point->y, map->extent.maxy, map->cellsize);
-    } else
-      msOffsetPointRelativeTo(point, layer);
-
-    if(labeltext) {
-      if(layer->labelcache) {
-        if(msAddLabel(map, layer->index, classindex, NULL, point, NULL, newtext, -1, NULL) != MS_SUCCESS) return(MS_FAILURE);
-      } else {
-	if(theclass->numstyles > 0 && MS_VALID_COLOR(theclass->styles[0]->color)) {
-      for(s=0; s<theclass->numstyles; s++) {
-        styleObj *curStyle = theclass->styles[s];
-        if(map->scaledenom > 0) {
-        if((curStyle->maxscaledenom != -1) && (map->scaledenom >= curStyle->maxscaledenom))
-          continue;
-        if((curStyle->minscaledenom != -1) && (map->scaledenom < curStyle->minscaledenom))
-          continue;
+    case MS_LAYER_ANNOTATION:
+      if(layer->transform == MS_TRUE) {
+        if(!msPointInRect(point, &map->extent)) return(0);
+        point->x = MS_MAP2IMAGE_X(point->x, map->extent.minx, map->cellsize);
+        point->y = MS_MAP2IMAGE_Y(point->y, map->extent.maxy, map->cellsize);
+      } else
+        msOffsetPointRelativeTo(point, layer);
+
+      if(labeltext) {
+        if(layer->labelcache) {
+          if(msAddLabel(map, label, layer->index, classindex, NULL, point, NULL, -1) != MS_SUCCESS) return(MS_FAILURE);
+        } else {
+          if(theclass->numstyles > 0 && MS_VALID_COLOR(theclass->styles[0]->color)) {
+            for(s=0; s<theclass->numstyles; s++) {
+              if(msScaleInBounds(map->scaledenom, theclass->styles[s]->minscaledenom, theclass->styles[s]->maxscaledenom))
+                msDrawMarkerSymbol(&map->symbolset, image, point, theclass->styles[s], layer->scalefactor);
+            }
+          }
+          msDrawLabel(map, image, *point, label->annotext, label, layer->scalefactor);
         }
-  	    msDrawMarkerSymbol(&map->symbolset, image, point, (curStyle), layer->scalefactor);
-      }
-	}
-	msDrawLabel(map, image, *point, newtext, label, layer->scalefactor);
       }
-    }
-    break;
+      break;
 
-  case MS_LAYER_POINT:
-    if(layer->transform == MS_TRUE) {
-      if(!msPointInRect(point, &map->extent)) return(0);
-      point->x = MS_MAP2IMAGE_X(point->x, map->extent.minx, map->cellsize);
-      point->y = MS_MAP2IMAGE_Y(point->y, map->extent.maxy, map->cellsize);
-    } else
-      msOffsetPointRelativeTo(point, layer);
+    case MS_LAYER_POINT:
+      if(layer->transform == MS_TRUE) {
+        if(!msPointInRect(point, &map->extent)) return(0);
+        point->x = MS_MAP2IMAGE_X(point->x, map->extent.minx, map->cellsize);
+        point->y = MS_MAP2IMAGE_Y(point->y, map->extent.maxy, map->cellsize);
+      } else
+        msOffsetPointRelativeTo(point, layer);
 
-    for(s=0; s<theclass->numstyles; s++) {
-      styleObj *curStyle = theclass->styles[s];
-      if(map->scaledenom > 0) {
-        if((curStyle->maxscaledenom != -1) && (map->scaledenom >= curStyle->maxscaledenom))
-          continue;
-        if((curStyle->minscaledenom != -1) && (map->scaledenom < curStyle->minscaledenom))
-          continue;
+      for(s=0; s<theclass->numstyles; s++) {
+        if(msScaleInBounds(map->scaledenom, theclass->styles[s]->minscaledenom, theclass->styles[s]->maxscaledenom))
+          msDrawMarkerSymbol(&map->symbolset, image, point, theclass->styles[s], layer->scalefactor);
       }
-      msDrawMarkerSymbol(&map->symbolset, image, point, (curStyle), layer->scalefactor);
-    }
-    if(labeltext) {
-      if(layer->labelcache) {
-        if(msAddLabel(map, layer->index, classindex, NULL, point, NULL, newtext, -1,NULL) != MS_SUCCESS) return(MS_FAILURE);
-      } else
-	msDrawLabel(map, image, *point, newtext, label, layer->scalefactor);
-    }
-    break;
-  default:
-    break; /* don't do anything with layer of other types */
+      if(labeltext) {
+        if(layer->labelcache) {
+          if(msAddLabel(map, label, layer->index, classindex, NULL, point, NULL, -1) != MS_SUCCESS) return(MS_FAILURE);
+        } else
+          msDrawLabel(map, image, *point, label->annotext, label, layer->scalefactor);
+      }
+      break;
+    default:
+      break; /* don't do anything with layer of other types */
   }
-  
-  if(newtext!=labeltext) /*free the transformed text if necessary*/
-    free(newtext);
 
   return(MS_SUCCESS); /* all done, no cleanup */
 }
@@ -2298,6 +2266,7 @@ int msDrawLabel(mapObj *map, imageObj *image, pointObj labelPnt, char *string, l
   lineObj labelPolyLine;
   pointObj labelPolyPoints[5];
   int needLabelPoly=MS_TRUE;
+  int needLabelPoint=MS_TRUE;
 
   int label_offset_x, label_offset_y;
   double size;
@@ -2305,8 +2274,8 @@ int msDrawLabel(mapObj *map, imageObj *image, pointObj labelPnt, char *string, l
 
   if(!string) return MS_SUCCESS; /* not an error, just don't need to do anything more */
   if(strlen(string) == 0) return MS_SUCCESS; /* not an error, just don't need to do anything more */
+  if(label->status == MS_OFF) return(MS_SUCCESS); /* not an error */
 
-  
 
   if(label->type == MS_TRUETYPE) {
     size = label->size * scalefactor;
@@ -2323,18 +2292,13 @@ int msDrawLabel(mapObj *map, imageObj *image, pointObj labelPnt, char *string, l
 
   if(label->position != MS_XY) {
     pointObj p;
-    int needLabelPoint=MS_TRUE;
 
     if(label->numstyles > 0) {
       int i;
 
       for(i=0; i<label->numstyles; i++) {
         if(label->styles[i]->_geomtransform.type == MS_GEOMTRANSFORM_LABELPOINT) {
-          if(needLabelPoint) {
-            p = get_metrics_line(&labelPnt, label->position, r, label_offset_x, label_offset_y, label->angle, 0, NULL);
-            needLabelPoint = MS_FALSE; /* don't re-compute */
-          } 
-          msDrawMarkerSymbol(&map->symbolset, image, &p, label->styles[i], scalefactor);
+          msDrawMarkerSymbol(&map->symbolset, image, &labelPnt, label->styles[i], scalefactor);
         } else if(label->styles[i]->_geomtransform.type == MS_GEOMTRANSFORM_LABELPOLY) {
           if(needLabelPoly) {
             labelPoly.line = &labelPolyLine; /* setup the label polygon structure */
@@ -2392,46 +2356,438 @@ int msDrawLabel(mapObj *map, imageObj *image, pointObj labelPnt, char *string, l
   return MS_SUCCESS;
 }
 
+/* private shortcut function to try a leader offsetted label */
+void offsetAndTest(imageObj*image, mapObj *map, labelCacheMemberObj *cachePtr, double ox, double oy,
+                   int priority, int label_idx, shapeObj *unoffsetedpoly)
+{
+  /* offset cachePtr->poly and cachePtr->point */
+  int i,j;
+  for(i=cachePtr->poly->numlines-1; i>=0; i--) {
+    for(j=cachePtr->poly->line[i].numpoints-1; j>=0; j--) {
+      cachePtr->poly->line[i].point[j].x = unoffsetedpoly->line[i].point[j].x + ox;
+      cachePtr->poly->line[i].point[j].y = unoffsetedpoly->line[i].point[j].y + oy;
+    }
+  }
+  cachePtr->poly->bounds.minx = unoffsetedpoly->bounds.minx + ox;
+  cachePtr->poly->bounds.miny = unoffsetedpoly->bounds.miny + oy;
+  cachePtr->poly->bounds.maxx = unoffsetedpoly->bounds.maxx + ox;
+  cachePtr->poly->bounds.maxy = unoffsetedpoly->bounds.maxy + oy;
+
+  cachePtr->point.x = cachePtr->leaderline->point[0].x + ox;
+  cachePtr->point.y = cachePtr->leaderline->point[0].y + oy;
+
+  /* set the second point of the leader line */
+  cachePtr->leaderline->point[1].x = cachePtr->point.x;
+  cachePtr->leaderline->point[1].y = cachePtr->point.y;
+
+  /* compute leader line bbox */
+  if(ox>0) {
+    cachePtr->leaderbbox->minx = cachePtr->leaderline->point[0].x;
+    cachePtr->leaderbbox->maxx = cachePtr->point.x;
+  } else {
+    cachePtr->leaderbbox->maxx = cachePtr->leaderline->point[0].x;
+    cachePtr->leaderbbox->minx = cachePtr->point.x;
+  }
+  if(oy>0) {
+    cachePtr->leaderbbox->miny = cachePtr->leaderline->point[0].y;
+    cachePtr->leaderbbox->maxy = cachePtr->point.y;
+  } else {
+    cachePtr->leaderbbox->maxy = cachePtr->leaderline->point[0].y;
+    cachePtr->leaderbbox->miny = cachePtr->point.y;
+  }
+  cachePtr->status = msTestLabelCacheCollisions(map, cachePtr, cachePtr->poly, cachePtr->labels[0].mindistance,priority,-label_idx);
+  if(cachePtr->status) {
+    int ll;
+    for(ll=0; ll<cachePtr->numlabels; ll++) {
+      cachePtr->labels[ll].annopoint.x += ox;
+      cachePtr->labels[ll].annopoint.y += oy;
+      if(cachePtr->labels[ll].annopoly) {
+        for(i=0; i<5; i++) {
+          cachePtr->labels[ll].annopoly->line[0].point[i].x += ox;
+          cachePtr->labels[ll].annopoly->line[0].point[i].y += oy;
+        }
+      }
+    }
+  }
+}
+
+int msDrawOffsettedLabels(imageObj *image, mapObj *map, int priority)
+{
+  int retval = MS_SUCCESS;
+  int l;
+  labelCacheObj *labelcache = &(map->labelcache);
+  labelCacheSlotObj *cacheslot;
+  labelCacheMemberObj *cachePtr;
+  assert(MS_RENDERER_PLUGIN(image->format));
+  cacheslot = &(labelcache->slots[priority]);
+  for(l=cacheslot->numlabels-1; l>=0; l--) {
+    cachePtr = &(cacheslot->labels[l]); /* point to right spot in the label cache */
+    if(cachePtr->status == MS_FALSE && !cachePtr->labelpath && cachePtr->poly) {
+      /* only test regular labels that have had their bounding box computed
+       and that haven't been rendered  */
+      classObj *classPtr = (GET_CLASS(map,cachePtr->layerindex,cachePtr->classindex));
+      layerObj *layerPtr = (GET_LAYER(map,cachePtr->layerindex));
+      if(classPtr->leader.maxdistance) { /* only test labels that can be offsetted */
+        shapeObj origPoly;
+        int steps,i;
+        if(cachePtr->point.x < labelcache->gutter ||
+            cachePtr->point.y < labelcache->gutter ||
+            cachePtr->point.x >= image->width - labelcache->gutter ||
+            cachePtr->point.y >= image->height - labelcache->gutter) {
+          /* don't look for leaders if point is in edge buffer as the leader line would end up chopped off */
+          continue;
+        }
+
+        /* TODO: check the cachePtr->point doesn't intersect a rendered label before event trying to offset ?*/
+
+        /* TODO: if the entry has a single label and it has position != CC,
+         * recompute the cachePtr->poly and labelPtr->annopoint using POSITION CC */
+        msInitShape(&origPoly);
+        msCopyShape(cachePtr->poly,&origPoly);
+
+        cachePtr->leaderline = msSmallMalloc(sizeof(lineObj));
+        cachePtr->leaderline->numpoints = 2;
+        cachePtr->leaderline->point = msSmallMalloc(2*sizeof(pointObj));
+        cachePtr->leaderline->point[0] = cachePtr->point;
+        cachePtr->leaderbbox = msSmallMalloc(sizeof(rectObj));
+
+        steps = classPtr->leader.maxdistance / classPtr->leader.gridstep;
+
+#define x0 (cachePtr->leaderline->point[0].x)
+#define y0 (cachePtr->leaderline->point[0].y)
+#define gridstepsc (classPtr->leader.gridstep)
+
+
+#define otest(ox,oy) if((x0+(ox)) >= labelcache->gutter &&\
+                  (y0+(oy)) >= labelcache->gutter &&\
+                  (x0+(ox)) < image->width + labelcache->gutter &&\
+                  (y0+(oy)) < image->height + labelcache->gutter) {\
+                     offsetAndTest(image,map,cachePtr,(ox),(oy),priority,l,&origPoly); \
+                     if(cachePtr->status) break;\
+                  }
+
+        /* loop through possible offsetted positions */
+        for(i=1; i<=steps; i++) {
+
+
+
+
+          /* test the intermediate points on the ring */
+
+          /* (points marked "0" are the ones being tested)
+
+             X00X00X
+             0XXXXX0
+             0XXXXX0
+             XXX.XXX
+             0XXXXX0
+             0XXXXX0
+             X00X00X
+          */
+          int j;
+          for(j=1; j<i-1; j++) {
+            /* test the right positions */
+            otest(i*gridstepsc,j * gridstepsc);
+            otest(i*gridstepsc,- j * gridstepsc);
+            /* test the left positions */
+            otest(- i*gridstepsc,j * gridstepsc);
+            otest(- i*gridstepsc,- j * gridstepsc);
+            /* test the top positions */
+            otest(j*gridstepsc,- i * gridstepsc);
+            otest(- j *gridstepsc,- i * gridstepsc);
+            /* test the bottom positions */
+            otest(j*gridstepsc,i * gridstepsc);
+            otest(- j *gridstepsc,i * gridstepsc);
+          }
+          if(j<(i-1)) break;
+
+          otest(i*gridstepsc,i*gridstepsc);
+          otest(-i*gridstepsc,-i*gridstepsc);
+          otest(i*gridstepsc,-i*gridstepsc);
+          otest(-i*gridstepsc,i*gridstepsc);
+
+
+          /* test the intermediate points on the ring */
+
+          /* (points marked "0" are the ones being tested)
+
+             X00X00X
+             0XXXXX0
+             0XXXXX0
+             XXX.XXX
+             0XXXXX0
+             0XXXXX0
+             X00X00X
+
+          */
+
+          /* test the extreme diagonal points */
+
+          /* (points marked "0" are the ones being tested)
+
+             0XXXXX0
+             XXXXXXX
+             XXXXXXX
+             XXX.XXX
+             XXXXXXX
+             XXXXXXX
+             0XXXXX0
+
+             (x0+i*gridstep, y0+i*gridstep), pos lr
+             (x0-i*gridstep, y0-i*gridstep), pos ul
+             (x0+i*gridstep, y0-i*gridstep), pos ur
+             (x0-i*gridstep, y0+i*gridstep), pos ll
+
+          */
+
+          /* test the 4 cardinal points on the ring */
+
+          /* (points marked "0" are the ones being tested)
+
+             XXX0XXX
+             XXXXXXX
+             XXXXXXX
+             0XX.XX0
+             XXXXXXX
+             XXXXXXX
+             XXX0XXX
+
+           * (x0+i*gridtep,y0), pos cr
+
+           * (x0-i*gridstep,y0), pos cl
+           * (x0,y0-i*gridstep), pos uc
+           * (x0,y0+i*gridstep), pos lc
+           */
+          otest(i*gridstepsc,0);
+          otest(-i*gridstepsc,0);
+          otest(0,-i*gridstepsc);
+          otest(0,i*gridstepsc);
+        }
+        if(cachePtr->status) {
+          int ll;
+          shapeObj labelLeader; /* label polygon (bounding box, possibly rotated) */
+          labelLeader.line = cachePtr->leaderline; /* setup the label polygon structure */
+          labelLeader.numlines = 1;
+
+          for(ll=0; ll<classPtr->leader.numstyles; ll++) {
+            msDrawLineSymbol(&map->symbolset, image,&labelLeader , classPtr->leader.styles[ll], layerPtr->scalefactor);
+          }
+          for(ll=0; ll<cachePtr->numlabels; ll++) {
+            labelObj *labelPtr = &(cachePtr->labels[ll]);
+
+            /* here's where we draw the label styles */
+            if(labelPtr->numstyles > 0) {
+              for(i=0; i<labelPtr->numstyles; i++) {
+                if(labelPtr->styles[i]->_geomtransform.type == MS_GEOMTRANSFORM_LABELPOINT)
+                  msDrawMarkerSymbol(&map->symbolset, image, &(cachePtr->point), labelPtr->styles[i], layerPtr->scalefactor);
+                else if(labelPtr->styles[i]->_geomtransform.type == MS_GEOMTRANSFORM_LABELPOLY) {
+                  msDrawShadeSymbol(&map->symbolset, image, labelPtr->annopoly, labelPtr->styles[i], layerPtr->scalefactor);
+                } else {
+                  msSetError(MS_MISCERR,"Labels only support LABELPNT and LABELPOLY GEOMTRANSFORMS", "msDrawOffsettedLabels()");
+                  return MS_FAILURE;
+                }
+              }
+            }
+            if(labelPtr->annotext)
+              msDrawText(image, labelPtr->annopoint, labelPtr->annotext, labelPtr, &(map->fontset), layerPtr->scalefactor); /* actually draw the label */
+          }
+          /* TODO: draw cachePtr->marker, but where ? */
+
+          /*
+           styleObj tstyle;
+           static int foo =0;
+           if(!foo) {
+              srand(time(NULL));
+              foo = 1;
+              initStyle(&tstyle);
+              tstyle.width = 1;
+              tstyle.color.alpha = 255;
+           }
+           tstyle.color.red = random()%255;
+           tstyle.color.green = random()%255;
+           tstyle.color.blue =random()%255;
+           msDrawLineSymbol(&map->symbolset, image, cachePtr->poly, &tstyle, layerPtr->scalefactor);
+          */
+
+        } else {
+          msFree(cachePtr->leaderline->point);
+          msFree(cachePtr->leaderline);
+          msFree(cachePtr->leaderbbox);
+          cachePtr->leaderline = NULL;
+        }
+        msFreeShape(&origPoly);
+      }
+    }
+  }
+
+
+  return retval;
+}
+
+int computeMarkerPoly(mapObj *map, imageObj *image, labelCacheMemberObj *cachePtr,
+                      labelCacheSlotObj *cacheslot, shapeObj *markerPoly)
+{
+  layerObj *layerPtr = (GET_LAYER(map, cachePtr->layerindex));
+  if(layerPtr->type == MS_LAYER_ANNOTATION && cachePtr->numstyles > 0) {
+    /* TODO: at the moment only checks the bottom (first) marker style since it *should* be the
+       largest, perhaps we should check all of them and build a composite size */
+    double marker_width,marker_height;
+    pointObj *point = markerPoly->line[0].point;
+    if(msGetMarkerSize(&map->symbolset, &(cachePtr->styles[0]), &marker_width, &marker_height, layerPtr->scalefactor) != MS_SUCCESS)
+      return MS_FAILURE;
+    markerPoly->numlines = 1;
+    markerPoly->bounds.minx = cachePtr->point.x - .5 * marker_width;
+    markerPoly->bounds.miny = cachePtr->point.y - .5 * marker_height;
+    markerPoly->bounds.maxx = markerPoly->bounds.minx + marker_width;
+    markerPoly->bounds.maxy = markerPoly->bounds.miny + marker_height;
+    point[0].x = markerPoly->bounds.minx;
+    point[0].y = markerPoly->bounds.miny;
+    point[1].x = markerPoly->bounds.minx;
+    point[1].y = markerPoly->bounds.maxy;
+    point[2].x = markerPoly->bounds.maxx;
+    point[2].y = markerPoly->bounds.maxy;
+    point[3].x = markerPoly->bounds.maxx;
+    point[3].y = markerPoly->bounds.miny;
+    point[4].x = markerPoly->bounds.minx;
+    point[4].y = markerPoly->bounds.miny;
+  }
+  return MS_SUCCESS;
+}
+
+void fastComputeBounds(shapeObj *shape)
+{
+  int i,j;
+  shape->bounds.minx = shape->bounds.maxx = shape->line[0].point[0].x;
+  shape->bounds.miny = shape->bounds.maxy = shape->line[0].point[0].y;
+
+
+  for( i=0; i<shape->numlines; i++ ) {
+    for( j=0; j<shape->line[i].numpoints; j++ ) {
+      shape->bounds.minx = MS_MIN(shape->bounds.minx, shape->line[i].point[j].x);
+      shape->bounds.maxx = MS_MAX(shape->bounds.maxx, shape->line[i].point[j].x);
+      shape->bounds.miny = MS_MIN(shape->bounds.miny, shape->line[i].point[j].y);
+      shape->bounds.maxy = MS_MAX(shape->bounds.maxy, shape->line[i].point[j].y);
+    }
+  }
+}
+
+int computeLabelMarkerPoly(mapObj *map, imageObj *img, labelCacheMemberObj *cachePtr,
+                           labelObj *label, shapeObj *markerPoly)
+{
+  int i;
+  layerObj *layerPtr = (GET_LAYER(map, cachePtr->layerindex));
+  markerPoly->numlines = 0;
+  for (i=0; i<label->numstyles; i++) {
+    styleObj *style = label->styles[i];
+    if(style->_geomtransform.type == MS_GEOMTRANSFORM_LABELPOINT &&
+        style->symbol < map->symbolset.numsymbols && style->symbol > 0) {
+      double sx,sy;
+      pointObj *point;
+      int p;
+      double aox,aoy;
+      symbolObj *symbol = map->symbolset.symbol[style->symbol];
+      if(msGetMarkerSize(&map->symbolset, style, &sx, &sy, layerPtr->scalefactor) != MS_SUCCESS)
+        return MS_FAILURE;
+      point = markerPoly->line[0].point;
+      point[0].x = sx / 2.0;
+      point[0].y = sy / 2.0;
+      point[1].x =  point[0].x;
+      point[1].y = -point[0].y;
+      point[2].x = -point[0].x;
+      point[2].y = -point[0].y;
+      point[3].x = -point[0].x;
+      point[3].y =  point[0].y;
+      point[4].x =  point[0].x;
+      point[4].y =  point[0].y;
+      if(symbol->anchorpoint_x != 0.5 || symbol->anchorpoint_y != 0.5) {
+        aox = (0.5 - symbol->anchorpoint_x) * sx;
+        aoy = (0.5 - symbol->anchorpoint_y) * sy;
+        for(p=0; p<5; p++) {
+          point[p].x += aox;
+          point[p].y += aoy;
+        }
+      }
+      if(style->angle) {
+        double rot = -style->angle * MS_DEG_TO_RAD;
+        double sina = sin(rot);
+        double cosa = cos(rot);
+        for(p=0; p<5; p++) {
+          double tmpx = point[p].x;
+          point[p].x = point[p].x * cosa - point[p].y * sina;
+          point[p].y = tmpx * sina + point[p].y * cosa;
+        }
+      }
+      aox = cachePtr->point.x + style->offsetx * layerPtr->scalefactor;
+      aoy = cachePtr->point.y + style->offsety * layerPtr->scalefactor;
+      for(p=0; p<5; p++) {
+        point[p].x += aox;
+        point[p].y += aoy;
+      }
+      markerPoly->numlines = 1;
+      fastComputeBounds(markerPoly);
+      break;
+    }
+  }
+  return MS_SUCCESS;
+}
+
 int msDrawLabelCache(imageObj *image, mapObj *map)
 {
   int nReturnVal = MS_SUCCESS;
 
   if(image) {
-    if(MS_RENDERER_PLUGIN(image->format)) {          
-      pointObj p;
-      int i, l, priority;
+    if(MS_RENDERER_PLUGIN(image->format)) {
+      int i, l, ll, priority;
       rectObj r;
+      shapeObj marker_poly;
+      lineObj  marker_line;
+      pointObj marker_points[5];
+      shapeObj label_marker_poly;
+      lineObj  label_marker_line;
+      pointObj label_marker_points[5];
+      shapeObj metrics_poly;
+      lineObj metrics_line;
+      pointObj metrics_points[5];
+
+      double marker_offset_x, marker_offset_y;
+      int label_offset_x, label_offset_y;
+      int label_mindistance=-1, label_buffer=0;
+      const char *value;
 
-      shapeObj labelPoly; /* label polygon (bounding box, possibly rotated) */
-      lineObj labelPolyLine;
-      pointObj labelPolyPoints[5];
-      int drawLabelPoly=MS_FALSE;
-
-      markerCacheMemberObj *markerPtr=NULL; /* for santity */
-      labelCacheMemberObj *cachePtr=NULL;      
+      labelCacheMemberObj *cachePtr=NULL;
       layerObj *layerPtr=NULL;
+      classObj *classPtr=NULL;
       labelObj *labelPtr=NULL;
 
-      int marker_width, marker_height;
-      int marker_offset_x, marker_offset_y, label_offset_x, label_offset_y;
-      rectObj marker_rect = {0,0,0,0};
-      int label_mindistance=-1,
-      label_buffer=0, map_edge_buffer=0;
-
-      const char *value;
-
-      labelPoly.line = &labelPolyLine; /* setup the label polygon structure */
-      labelPoly.numlines = 1;
-      labelPoly.line->point = labelPolyPoints;
-      labelPoly.line->numpoints = 5;
+      /* holds the contour of the label styles that correspond to markers */
+      marker_line.point = marker_points;
+      marker_line.numpoints = 5;
+      msInitShape(&marker_poly);
+      marker_poly.line = &marker_line;
+      marker_poly.numlines = 0;
+      marker_poly.type = MS_SHAPE_POLYGON;
+
+      label_marker_line.point = label_marker_points;
+      label_marker_line.numpoints = 5;
+      msInitShape(&label_marker_poly);
+      label_marker_poly.line = &label_marker_line;
+      label_marker_poly.numlines = 0;
+      label_marker_poly.type = MS_SHAPE_POLYGON;
+
+      metrics_line.point = metrics_points;
+      metrics_line.numpoints = 5;
+      msInitShape(&metrics_poly);
+      metrics_poly.line = &metrics_line;
+      metrics_poly.numlines = 1;
+      metrics_poly.type = MS_SHAPE_POLYGON;
 
       /* Look for labelcache_map_edge_buffer map metadata
        * If set then the value defines a buffer (in pixels) along the edge of the
        * map image where labels can't fall
        */
       if((value = msLookupHashTable(&(map->web.metadata), "labelcache_map_edge_buffer")) != NULL) {
-        map_edge_buffer = MS_ABS(atoi(value));
-        if(map->debug) msDebug("msDrawLabelCache(): labelcache_map_edge_buffer = %d\n", map_edge_buffer);
+        map->labelcache.gutter = MS_ABS(atoi(value));
+        if(map->debug) msDebug("msDrawLabelCache(): labelcache_map_edge_buffer = %d\n", map->labelcache.gutter);
       }
 
       for(priority=MS_MAX_LABEL_PRIORITY-1; priority>=0; priority--) {
@@ -2442,351 +2798,491 @@ int msDrawLabelCache(imageObj *image, mapObj *map)
           double scalefactor,size;
           cachePtr = &(cacheslot->labels[l]); /* point to right spot in the label cache */
 
-          markerPtr = NULL;
-          if(cachePtr->markerid != -1) markerPtr = &(cacheslot->markers[cachePtr->markerid]); /* point to the right sport in the marker cache (if available) */
-
           layerPtr = (GET_LAYER(map, cachePtr->layerindex)); /* set a couple of other pointers, avoids nasty references */
-          labelPtr = &(cachePtr->label);
-
-          if(!cachePtr->text || strlen(cachePtr->text) == 0) {
-            if(layerPtr->type == MS_LAYER_ANNOTATION && cachePtr->numstyles > 0) { /* there might be a marker to be added to the image */
-              /* TODO: at the moment only checks the bottom (e.g. first) marker style, perhaps should check all of them */
-              cachePtr->status = MS_TRUE;
-              if(msGetMarkerSize(&map->symbolset, &(cachePtr->styles[0]), &marker_width, &marker_height, layerPtr->scalefactor) != MS_SUCCESS)
-                return MS_FAILURE;
-
-              marker_rect.minx = MS_NINT(cachePtr->point.x - .5 * marker_width);
-              marker_rect.miny = MS_NINT(cachePtr->point.y - .5 * marker_height);
-              marker_rect.maxx = marker_rect.minx + (marker_width-1);
-              marker_rect.maxy = marker_rect.miny + (marker_height-1); 
-              msRectToPolygon(marker_rect, cachePtr->poly);
-                 
-              if(!labelPtr->force)
-                msTestLabelCacheCollisions(&(map->labelcache), labelPtr, image->width, image->height, (map_edge_buffer-label_buffer), cachePtr, priority, l, label_mindistance, 0);
-                 
-              if(cachePtr->status == MS_FALSE)
-                continue;
+          classPtr = (GET_CLASS(map, cachePtr->layerindex, cachePtr->classindex));
 
-              /* here's where we draw the label styles */
-              if(cachePtr->label.numstyles > 0) {
-                for(i=0; i<cachePtr->label.numstyles; i++) {
-                  if(cachePtr->label.styles[i]->_geomtransform.type == MS_GEOMTRANSFORM_LABELPOINT)
-                    msDrawMarkerSymbol(&map->symbolset, image, &(cachePtr->point), cachePtr->label.styles[i], layerPtr->scalefactor);
-                  else if(cachePtr->label.styles[i]->_geomtransform.type == MS_GEOMTRANSFORM_LABELPOLY) {
-                    msDrawShadeSymbol(&map->symbolset, image, &labelPoly, cachePtr->label.styles[i], layerPtr->scalefactor);
-                  } else {
-                    /* TODO: need error msg about unsupported geomtransform */
-                    return MS_FAILURE;
-                  }
-                }
-              }
+          if (layerPtr->type == MS_LAYER_ANNOTATION && (cachePtr->numlabels > 1 || classPtr->leader.maxdistance)) {
+            msSetError(MS_MISCERR, "Multiple Labels and/or LEADERs are not supported with annotation layers", "msDrawLabelCache()");
+            return MS_FAILURE;
+          }
+
+          /* TODO: classes with a labelpath do not respect multi label rendering */
+          if(cachePtr->labelpath) { /* path-based label */
+            labelPtr = &(cachePtr->labels[0]);
+
+            if(labelPtr->status != MS_ON) continue; /* skip this label */
+            if(!labelPtr->annotext) continue; /* skip this label, nothing to with curved labels when there is nothing to draw */
+
+            /* path-following labels *must* be TRUETYPE */
+            size = labelPtr->size * layerPtr->scalefactor;
+            size = MS_MAX(size, labelPtr->minsize*image->resolutionfactor);
+            size = MS_MIN(size, labelPtr->maxsize*image->resolutionfactor);
+            scalefactor = size / labelPtr->size;
+
+            label_buffer = (labelPtr->buffer*image->resolutionfactor);
+            label_mindistance = (labelPtr->mindistance*image->resolutionfactor);
 
-              if(layerPtr->type == MS_LAYER_ANNOTATION && cachePtr->numstyles > 0) { /* need to draw a marker */
-                for(i=0; i<cachePtr->numstyles; i++)
-                  msDrawMarkerSymbol(&map->symbolset, image, &(cachePtr->point), &(cachePtr->styles[i]), layerPtr->scalefactor);
-              }
-            }
-          } else {
 
-            if(labelPtr->type == MS_TRUETYPE) {
-              size = labelPtr->size * layerPtr->scalefactor;
-              size = MS_MAX(size, labelPtr->minsize*image->resolutionfactor);
-              size = MS_MIN(size, labelPtr->maxsize*image->resolutionfactor);
-              scalefactor = size / labelPtr->size;
+            /* compare against image bounds, rendered labels and markers (sets cachePtr->status), if FORCE=TRUE then skip it */
+            cachePtr->status = MS_TRUE;
+            assert(cachePtr->poly == NULL);
+
+            if(!labelPtr->force)
+              cachePtr->status = msTestLabelCacheCollisions(map,cachePtr,&cachePtr->labelpath->bounds,label_mindistance,priority,l);
+
+
+            if(!cachePtr->status) {
+              msFreeShape(&cachePtr->labelpath->bounds);
+              continue;
             } else {
-              size = labelPtr->size;
-              scalefactor = 1; /* can't scale bitmap fonts */
+              /* take ownership of cachePtr->poly*/
+              cachePtr->poly = (shapeObj*)msSmallMalloc(sizeof(shapeObj));
+              msInitShape(cachePtr->poly);
+              cachePtr->poly->type = MS_SHAPE_POLYGON;
+              cachePtr->poly->numlines = cachePtr->labelpath->bounds.numlines;
+              cachePtr->poly->line = cachePtr->labelpath->bounds.line;
+              cachePtr->labelpath->bounds.numlines = 0;
+              cachePtr->labelpath->bounds.line = NULL;
+              cachePtr->poly->bounds.minx = cachePtr->labelpath->bounds.bounds.minx;
+              cachePtr->poly->bounds.miny = cachePtr->labelpath->bounds.bounds.miny;
+              cachePtr->poly->bounds.maxx = cachePtr->labelpath->bounds.bounds.maxx;
+              cachePtr->poly->bounds.maxy = cachePtr->labelpath->bounds.bounds.maxy;
+              msFreeShape(&cachePtr->labelpath->bounds);
             }
-            if(msGetLabelSize(map,labelPtr,cachePtr->text,size,&r,NULL) != MS_SUCCESS)
-              return MS_FAILURE;
-             
-            /* adjust the baseline (see #1449) */
-            if(labelPtr->type == MS_TRUETYPE) {
-              int nNewlines = msCountChars(cachePtr->text,'\n');
-              if(!nNewlines) {
-                labelPtr->offsety += MS_NINT((((r.miny + r.maxy) + size) / 2.0)/scalefactor);
-                labelPtr->offsetx += MS_NINT((r.minx / 2)/scalefactor);
-              } else {
-                rectObj rect2; /* bbox of first line only */
-                char *firstLine = msGetFirstLine(cachePtr->text);
-                msGetLabelSize(map,labelPtr,firstLine,size,&rect2,NULL);
-                labelPtr->offsety += (MS_NINT(((rect2.miny+rect2.maxy) + size) / 2))/scalefactor;
-                labelPtr->offsetx += (MS_NINT(rect2.minx / 2))/scalefactor;
-                free(firstLine);
+
+            msDrawTextLine(image, labelPtr->annotext, labelPtr, cachePtr->labelpath, &(map->fontset), layerPtr->scalefactor); /* Draw the curved label */
+
+          } else { /* point-based label */
+            scalefactor = layerPtr->scalefactor; /* FIXME avoid compiler warning, see also #4408  */
+            marker_offset_x = marker_offset_y = 0; /* assume no marker */
+
+            /* compute label bbox of a marker used in an annotation layer and/or
+             * the offset needed for point layer with markerPtr */
+            marker_poly.numlines = 0;
+            if(layerPtr->type == MS_LAYER_ANNOTATION) {
+              if(computeMarkerPoly(map,image,cachePtr,cacheslot,&marker_poly)!=MS_SUCCESS) return MS_FAILURE;
+              if(marker_poly.numlines) {
+                marker_offset_x = (marker_poly.bounds.maxx-marker_poly.bounds.minx)/2.0;
+                marker_offset_y = (marker_poly.bounds.maxy-marker_poly.bounds.miny)/2.0;
+                /* if this is an annotation layer, transfer the markerPoly */
+                if( MS_OFF == msTestLabelCacheCollisions(map, cachePtr, &marker_poly, 0,priority, l)) {
+                  continue; /* the marker collided, no point continuing */
+                }
               }
+            } else if (layerPtr->type == MS_LAYER_POINT && cachePtr->markerid!=-1) { /* there is a marker already in the image that we need to account for */
+              markerCacheMemberObj *markerPtr = &(cacheslot->markers[cachePtr->markerid]); /* point to the right spot in the marker cache*/
+              marker_offset_x = (markerPtr->poly->bounds.maxx-markerPtr->poly->bounds.minx)/2.0;
+              marker_offset_y = (markerPtr->poly->bounds.maxy-markerPtr->poly->bounds.miny)/2.0;
             }
-   
-            drawLabelPoly = MS_FALSE;
-            for(i=0; i<labelPtr->numstyles; i++) {
-              if(labelPtr->styles[i]->_geomtransform.type == MS_GEOMTRANSFORM_LABELPOLY) {
-                drawLabelPoly = MS_TRUE;
-                break;
+
+
+            /*
+            ** all other cases *could* have multiple labels defined
+            */
+            cachePtr->status = MS_OFF; /* assume this cache element *can't* be placed */
+            for(ll=0; ll<cachePtr->numlabels; ll++) { /* RFC 77 TODO: Still may want to step through backwards... */
+              int label_marker_status = MS_ON;
+              labelPtr = &(cachePtr->labels[ll]);
+              labelPtr->status = MS_OFF;
+
+              /* first check if there's anything to do with this label */
+              if(!labelPtr->annotext) {
+                int s;
+                for(s=0; s<labelPtr->numstyles; s++) {
+                  if(labelPtr->styles[s]->_geomtransform.type == MS_GEOMTRANSFORM_LABELPOINT)
+                    break;
+                }
+                if(s == labelPtr->numstyles) {
+                  /* no label text, and no markers to render, skip this label */
+                  labelPtr->status = MS_ON;
+                  continue;
+                }
               }
-            }
-   
-            label_offset_x = labelPtr->offsetx*scalefactor;
-            label_offset_y = labelPtr->offsety*scalefactor;
-            label_buffer = MS_NINT(labelPtr->buffer*image->resolutionfactor);
-            label_mindistance = MS_NINT(labelPtr->mindistance*image->resolutionfactor);
-             
-            /* if cachePtr->featuresize is set to -1, this check has been done in msPolylineLabelPath() */
-            if(labelPtr->autominfeaturesize && (cachePtr->featuresize != -1) && ((r.maxx-r.minx) > cachePtr->featuresize))
-              continue; /* label too large relative to the feature */
-   
-            marker_offset_x = marker_offset_y = 0; /* assume no marker */
-            marker_width = marker_height = 0;
-            if(layerPtr->type == MS_LAYER_ANNOTATION && cachePtr->numstyles > 0) { /* there might be a marker added to the image */
-   
-              /* TODO: at the moment only checks the bottom (first) marker style, perhaps should check all of them */
-              if(msGetMarkerSize(&map->symbolset, &(cachePtr->styles[0]), &marker_width, &marker_height, layerPtr->scalefactor) != MS_SUCCESS)
-                return MS_FAILURE;
-   
-              marker_offset_x = MS_NINT(marker_width/2.0);
-              marker_offset_y = MS_NINT(marker_height/2.0);
-   
-              marker_rect.minx = MS_NINT(cachePtr->point.x - .5 * marker_width);
-              marker_rect.miny = MS_NINT(cachePtr->point.y - .5 * marker_height);
-              marker_rect.maxx = marker_rect.minx + (marker_width-1);
-              marker_rect.maxy = marker_rect.miny + (marker_height-1); 
-            } else if (layerPtr->type == MS_LAYER_POINT) { /* there is a marker already in the image */
-              marker_rect = markerPtr->poly->bounds;
-              marker_width = marker_rect.maxx - marker_rect.minx;
-              marker_height = marker_rect.maxy - marker_rect.miny;
-              marker_offset_x = MS_NINT(marker_width/2.0);
-              marker_offset_y = MS_NINT(marker_height/2.0);
-            }
 
-            /* TODO: might need this in the no text/empty text section above */
-            if(labelPtr->numstyles > 0) {
-              int temp_marker_width, temp_marker_height;
+              /* compute the poly of the label styles */
+              if(computeLabelMarkerPoly(map,image,cachePtr,labelPtr,&label_marker_poly)!=MS_SUCCESS) return MS_FAILURE;
+              if(label_marker_poly.numlines) {
+                if(cachePtr->numlabels > 1) { /* FIXME this test doesn't seem right, should probably check if we have an annotation layer with a regular style defined */
+                  marker_offset_x = (label_marker_poly.bounds.maxx-label_marker_poly.bounds.minx)/2.0;
+                  marker_offset_y = (label_marker_poly.bounds.maxy-label_marker_poly.bounds.miny)/2.0;
+                } else {
+                  /* we might be using an old style behavior with a markerPtr */
+                  marker_offset_x = MS_MAX(marker_offset_x,(label_marker_poly.bounds.maxx-label_marker_poly.bounds.minx)/2.0);
+                  marker_offset_y = MS_MAX(marker_offset_y,(label_marker_poly.bounds.maxy-label_marker_poly.bounds.miny)/2.0);
+                }
+                /* add marker to cachePtr->poly */
+                if(labelPtr->force != MS_TRUE) {
+                  label_marker_status = msTestLabelCacheCollisions(map, cachePtr,&label_marker_poly, 0,priority, l);
+                }
+                if(label_marker_status == MS_OFF &&
+                    !(labelPtr->force || classPtr->leader.maxdistance))
+                  break; /* the marker collided, break from multi-label loop */
+              }
 
-	      for(i=0; i<labelPtr->numstyles; i++) {
-                /* TODO: at the moment only checks the bottom (first) label style, perhaps should check all of them */
-		if(labelPtr->styles[i]->_geomtransform.type == MS_GEOMTRANSFORM_LABELPOINT) {
-                  if(msGetMarkerSize(&map->symbolset, labelPtr->styles[i], &temp_marker_width, &temp_marker_height, layerPtr->scalefactor) != MS_SUCCESS)
-		    return MS_FAILURE;
-                  break;
-		}
-	      }
 
-	      if(temp_marker_width > marker_width || temp_marker_height > marker_height) {
-                marker_width = temp_marker_width;
-		marker_height = temp_marker_height;
+              if(labelPtr->annotext) {
+                /* compute label size */
+                if(labelPtr->type == MS_TRUETYPE) {
+                  size = labelPtr->size * layerPtr->scalefactor;
+                  size = MS_MAX(size, labelPtr->minsize*image->resolutionfactor);
+                  size = MS_MIN(size, labelPtr->maxsize*image->resolutionfactor);
+                  scalefactor = size / labelPtr->size;
+                } else {
+                  size = labelPtr->size;
+                  scalefactor = 1;
+                }
+                if(msGetLabelSize(map, labelPtr, labelPtr->annotext, size, &r, NULL) != MS_SUCCESS)
+                  return MS_FAILURE;
+                /* if our label has an outline, adjust the marker offset so the outlinecolor does
+                 * not bleed into the marker */
+                if(marker_offset_x && MS_VALID_COLOR(labelPtr->outlinecolor)) {
+                  marker_offset_x += labelPtr->outlinewidth/2.0;
+                  marker_offset_y += labelPtr->outlinewidth/2.0;
+                }
 
-		marker_offset_x = MS_NINT(marker_width/2.0);
-		marker_offset_y = MS_NINT(marker_height/2.0);
+                if(labelPtr->autominfeaturesize && (cachePtr->featuresize != -1) && ((r.maxx-r.minx) > cachePtr->featuresize)) {
+                  /* label too large relative to the feature */
+                  /* this label cannot be rendered, go on to next cachePtr */
+                  break;
+                  /* TODO: treat the case with multiple labels and/or leader lines */
+                }
 
-		marker_rect.minx = MS_NINT(cachePtr->point.x - .5 * marker_width) - labelPtr->buffer;
-		marker_rect.miny = MS_NINT(cachePtr->point.y - .5 * marker_height) - labelPtr->buffer;
-		marker_rect.maxx = MS_NINT(cachePtr->point.x + .5 * marker_width) + labelPtr->buffer; // marker_rect.minx + (marker_width-1) + labelPtr->buffer;
-		marker_rect.maxy = MS_NINT(cachePtr->point.y + .5 * marker_height) + labelPtr->buffer; // marker_rect.miny + (marker_height-1) + labelPtr->buffer;
-	      }
-            }
+                /* apply offset and buffer settings */
+                label_offset_x = labelPtr->offsetx*scalefactor;
+                label_offset_y = labelPtr->offsety*scalefactor;
+                label_buffer = (labelPtr->buffer*image->resolutionfactor);
+                label_mindistance = (labelPtr->mindistance*image->resolutionfactor);
+
+#ifdef oldcode
+                /* adjust the baseline (see #1449) */
+                if(labelPtr->type == MS_TRUETYPE) {
+                  char *lastline = strrchr(labelPtr->annotext,'\n');
+                  if(!lastline || !*(++lastline)) {
+                    label_offset_y += ((r.miny + r.maxy) + size) / 2.0;
+                  } else {
+                    rectObj rect2; /* bbox of first line only */
+                    msGetLabelSize(map, labelPtr, lastline, size, &rect2, NULL);
+                    label_offset_y += ((rect2.miny+rect2.maxy) + size) / 2.0;
+                  }
+                }
+#endif
 
-            /* handle path following labels first (position does not matter) */
-            if(cachePtr->labelpath) {
-              cachePtr->status = MS_TRUE;
-   
-              /* Copy the bounds into the cache's polygon */
-              msCopyShape(&(cachePtr->labelpath->bounds), cachePtr->poly);
-              msFreeShape(&(cachePtr->labelpath->bounds));
-   
-              /* Compare against image bounds, rendered labels and markers (sets cachePtr->status), if FORCE=TRUE then skip it */
-              if(!labelPtr->force)
-                msTestLabelCacheCollisions(&(map->labelcache), labelPtr, image->width, image->height, (map_edge_buffer-label_buffer), cachePtr, priority, l, label_mindistance, (r.maxx-r.minx));
-            } else {
 
-              if(labelPtr->position == MS_AUTO) {
+                /* compute the label annopoly  if we need to render the background billboard */
+                if(labelPtr->numstyles > 0) {
+                  for(i=0; i<labelPtr->numstyles; i++) {
+                    if(labelPtr->styles[i]->_geomtransform.type == MS_GEOMTRANSFORM_LABELPOLY) {
+                      /* initialize the annotation polygon */
+                      labelPtr->annopoly = (shapeObj *) msSmallMalloc(sizeof(shapeObj));
+                      msInitShape(labelPtr->annopoly);
+                      labelPtr->annopoly->line = (lineObj *) malloc(sizeof(lineObj));
+                      labelPtr->annopoly->numlines = 1;
+                      labelPtr->annopoly->line->point =  (pointObj *) malloc(5*sizeof(pointObj));
+                      labelPtr->annopoly->line->numpoints = 5;
+                      break;
+                    }
+                  }
+                }
+              }
+
+              /* TODO: no point in using auto positionning if the marker cannot be placed? */
+              if(labelPtr->annotext && labelPtr->position == MS_AUTO) {
+                /* no point in using auto positionning if the marker cannot be placed */
                 int positions[MS_POSITIONS_LENGTH], npositions=0;
-   
+
                 /*
                 ** If the ANNOTATION has an associated marker then the position is handled like a point regardless of underlying shape type. (#2993)
                 **   (Note: might be able to re-order this for more speed.)
                 */
-                if(layerPtr->type == MS_LAYER_POLYGON || (layerPtr->type == MS_LAYER_ANNOTATION && cachePtr->shapetype == MS_SHAPE_POLYGON && cachePtr->numstyles == 0)) {
-                  positions[0]=MS_CC; positions[1]=MS_UC; positions[2]=MS_LC; positions[3]=MS_CL; positions[4]=MS_CR;
+                if((layerPtr->type == MS_LAYER_POLYGON && marker_offset_x==0 )|| (layerPtr->type == MS_LAYER_ANNOTATION && cachePtr->shapetype == MS_SHAPE_POLYGON && cachePtr->numstyles == 0)) {
+                  positions[0]=MS_CC;
+                  positions[1]=MS_UC;
+                  positions[2]=MS_LC;
+                  positions[3]=MS_CL;
+                  positions[4]=MS_CR;
                   npositions = 5;
-                } else if(layerPtr->type == MS_LAYER_LINE || (layerPtr->type == MS_LAYER_ANNOTATION && cachePtr->shapetype == MS_SHAPE_LINE && cachePtr->numstyles == 0)) {
-                  positions[0]=MS_UC; positions[1]=MS_LC; positions[2]=MS_CC;
+                } else if((layerPtr->type == MS_LAYER_LINE && marker_offset_x == 0) || (layerPtr->type == MS_LAYER_ANNOTATION && cachePtr->shapetype == MS_SHAPE_LINE && cachePtr->numstyles == 0)) {
+                  positions[0]=MS_UC;
+                  positions[1]=MS_LC;
+                  positions[2]=MS_CC;
                   npositions = 3;
                 } else {
-                  positions[0]=MS_UL; positions[1]=MS_LR; positions[2]=MS_UR; positions[3]=MS_LL; positions[4]=MS_CR; positions[5]=MS_CL; positions[6]=MS_UC; positions[7]=MS_LC;
+                  positions[0]=MS_UL;
+                  positions[1]=MS_LR;
+                  positions[2]=MS_UR;
+                  positions[3]=MS_LL;
+                  positions[4]=MS_CR;
+                  positions[5]=MS_CL;
+                  positions[6]=MS_UC;
+                  positions[7]=MS_LC;
                   npositions = 8;
                 }
-   
+
                 for(i=0; i<npositions; i++) {
-                  msFreeShape(cachePtr->poly);
-                  cachePtr->status = MS_TRUE; /* assume label *can* be drawn */
-   
-                  p = get_metrics(&(cachePtr->point), positions[i], r, (marker_offset_x + label_offset_x), (marker_offset_y + label_offset_y), labelPtr->angle, label_buffer, cachePtr->poly);
+                  // RFC 77 TODO: take label_marker_offset_x/y into account
+                  labelPtr->annopoint = get_metrics_line(&(cachePtr->point), positions[i], r,
+                                                         marker_offset_x + label_offset_x, marker_offset_y + label_offset_y,
+                                                         labelPtr->angle, label_buffer, &metrics_line);
+                  fastComputeBounds(&metrics_poly);
+
+                  if(labelPtr->force == MS_OFF) {
+                    /* check for collisions inside the label group */
+                    if(cachePtr->poly && cachePtr->poly->numlines && intersectLabelPolygons(&metrics_poly, cachePtr->poly) == MS_TRUE) {
+                      /* there was a self intersection */
+                      continue; /* next position, labelPtr->status is left to MS_OFF */
+                    }
+                  }
 
-                  if(marker_width > 0 && marker_height > 0)
-                    msRectToPolygon(marker_rect, cachePtr->poly); /* save marker bounding polygon */
-   
-                  /* Compare against image bounds, rendered labels and markers (sets cachePtr->status) */
-                  msTestLabelCacheCollisions(&(map->labelcache), labelPtr, image->width, image->height, (map_edge_buffer-label_buffer), cachePtr, priority, l, label_mindistance, (r.maxx-r.minx));
+                  labelPtr->status = msTestLabelCacheCollisions(map, cachePtr,&metrics_poly, label_mindistance,priority, l);
 
                   /* found a suitable place for this label */
-                  if(cachePtr->status) {
-                    if(drawLabelPoly) 
-                      get_metrics_line(&(cachePtr->point), positions[i], r, (marker_offset_x + label_offset_x), (marker_offset_y + label_offset_y), labelPtr->angle, 1, labelPoly.line);
+                  if(labelPtr->status == MS_TRUE || (i==(npositions-1) && labelPtr->force == MS_ON)) {
+                    labelPtr->status = MS_TRUE; /* set to true in case we are forcing it */
+                    if(labelPtr->annopoly) get_metrics_line(&(cachePtr->point), positions[i], r,
+                                                              marker_offset_x + label_offset_x, marker_offset_y + label_offset_y,
+                                                              labelPtr->angle, 1, labelPtr->annopoly->line);
                     break; /* ...out of position loop */
                   }
                 } /* next position */
-   
-                if(labelPtr->force) {
-                  /* label polygon wasn't initialized if no non-coliding position was found */
-                  if(!cachePtr->status && drawLabelPoly) 
-                    get_metrics_line(&(cachePtr->point), positions[npositions-1], r, (marker_offset_x + label_offset_x), (marker_offset_y + label_offset_y), labelPtr->angle, 1, labelPoly.line);
-                  cachePtr->status = MS_TRUE; /* draw in spite of collisions based on last position, need a *best* position */
+
+                /* if position auto didn't manage to find a position, but we have leader configured
+                 * for the class, then we want to compute the label poly anyways */
+                if(classPtr->leader.maxdistance && labelPtr->status == MS_FALSE) {
+                  labelPtr->annopoint = get_metrics_line(&(cachePtr->point), MS_CC, r,
+                                                         marker_offset_x + label_offset_x, marker_offset_y + label_offset_y,
+                                                         labelPtr->angle, label_buffer, &metrics_line);
+                  if(labelPtr->annopoly) get_metrics_line(&(cachePtr->point), MS_CC, r,
+                                                            marker_offset_x + label_offset_x, marker_offset_y + label_offset_y,
+                                                            labelPtr->angle, 1, labelPtr->annopoly->line);
+                  fastComputeBounds(&metrics_poly);
                 }
-   
               } else { /* explicit position */
-                cachePtr->status = MS_TRUE; /* assume label *can* be drawn */
 
-                if(labelPtr->position == MS_CC) { /* don't need the marker_offset */
-                  p = get_metrics(&(cachePtr->point), labelPtr->position, r, label_offset_x, label_offset_y, labelPtr->angle, label_buffer, cachePtr->poly);
-                  if(drawLabelPoly) get_metrics_line(&(cachePtr->point), labelPtr->position, r, label_offset_x, label_offset_y, labelPtr->angle, 1, labelPoly.line);
+                if(labelPtr->annotext) {
+                  if(labelPtr->position == MS_CC) { /* don't need the marker_offset */
+                    labelPtr->annopoint = get_metrics_line(&(cachePtr->point), labelPtr->position, r,
+                                                           label_offset_x, label_offset_y, labelPtr->angle, label_buffer, &metrics_line);
+                    if(labelPtr->annopoly) get_metrics_line(&(cachePtr->point), labelPtr->position, r,
+                                                              label_offset_x, label_offset_y, labelPtr->angle, 1, labelPtr->annopoly->line);
+                  } else {
+                    labelPtr->annopoint = get_metrics_line(&(cachePtr->point), labelPtr->position, r,
+                                                           marker_offset_x + label_offset_x, marker_offset_y + label_offset_y,
+                                                           labelPtr->angle, label_buffer, &metrics_line);
+                    if(labelPtr->annopoly) get_metrics_line(&(cachePtr->point), labelPtr->position, r,
+                                                              marker_offset_x + label_offset_x, marker_offset_y + label_offset_y,
+                                                              labelPtr->angle, 1, labelPtr->annopoly->line);
+                  }
+                  fastComputeBounds(&metrics_poly);
+
+                  if(labelPtr->force == MS_ON) {
+                    labelPtr->status = MS_ON;
+                  } else {
+                    if(labelPtr->force == MS_OFF) {
+                      /* check for collisions inside the label group unless the label is FORCE GROUP */
+                      if(cachePtr->poly && cachePtr->poly->numlines && intersectLabelPolygons(&metrics_poly, cachePtr->poly) == MS_TRUE) {
+                        break; /* collision within the group */
+                      }
+                    }
+                    /* TODO: in case we have leader lines and multiple labels, there's no use in testing for labelcache collisions
+                    * once a first collision has been found. we only need to know that the label group has collided, and the
+                    * poly of the whole label group: if(label_group) testLabelCacheCollisions */
+                    labelPtr->status = msTestLabelCacheCollisions(map, cachePtr,&metrics_poly, label_mindistance, priority, l);
+                  }
                 } else {
-                  p = get_metrics(&(cachePtr->point), labelPtr->position, r, (marker_offset_x + label_offset_x), (marker_offset_y + label_offset_y), labelPtr->angle, label_buffer, cachePtr->poly);
-                  if(drawLabelPoly) get_metrics_line(&(cachePtr->point), labelPtr->position, r, (marker_offset_x + label_offset_x), (marker_offset_y + label_offset_y), labelPtr->angle, 1, labelPoly.line);
+                  labelPtr->status = MS_ON;
                 }
+              } /* end POSITION AUTO vs Fixed POSITION */
 
-                if(marker_width > 0 && marker_height > 0)
-                  msRectToPolygon(marker_rect, cachePtr->poly); /* save marker bounding polygon, part of overlap tests (TODO: might need to do something similar with label styles?) */
-
-                /* Compare against image bounds, rendered labels and markers (sets cachePtr->status), if FORCE=TRUE then skip the test */
-                if(!labelPtr->force)
-                  msTestLabelCacheCollisions(&(map->labelcache), labelPtr, image->width, image->height, (map_edge_buffer-label_buffer), cachePtr, priority, l, label_mindistance, (r.maxx-r.minx));  
+              if((!labelPtr->status || !label_marker_status) && classPtr->leader.maxdistance == 0) {
+                labelPtr->status = MS_OFF;
+                break; /* no point looking at more labels, unless their is a leader defined, in which
+                case we still want to compute the full cachePtr->poly to be used for offset tests */
+              } else {
+                if(!cachePtr->poly) {
+                  cachePtr->poly = (shapeObj*)msSmallMalloc(sizeof(shapeObj));
+                  msInitShape(cachePtr->poly);
+                }
+                if(labelPtr->annotext) {
+                  msAddLine(cachePtr->poly, metrics_poly.line);
+                }
+                if(label_marker_poly.numlines) {
+                  msAddLine(cachePtr->poly, label_marker_poly.line);
+                }
+                if(!label_marker_status)
+                  labelPtr->status = MS_OFF;
               }
-            } /* end (not) POSITION FOLLOW/AUTO */
-   
-            if(!cachePtr->status)
-              continue; /* next label */
+            } /* next label in the group */
 
-            /* here's where we draw the label styles */
-            if(!cachePtr->labelpath && cachePtr->label.numstyles > 0) {
-              for(i=0; i<cachePtr->label.numstyles; i++) {
-                if(cachePtr->label.styles[i]->_geomtransform.type == MS_GEOMTRANSFORM_LABELPOINT)
-                  msDrawMarkerSymbol(&map->symbolset, image, &(cachePtr->point), cachePtr->label.styles[i], layerPtr->scalefactor);
-                else if(cachePtr->label.styles[i]->_geomtransform.type == MS_GEOMTRANSFORM_LABELPOLY) {
-                  msDrawShadeSymbol(&map->symbolset, image, &labelPoly, cachePtr->label.styles[i], layerPtr->scalefactor);
-                } else {
-                  /* TODO: need error msg about unsupported geomtransform */
-                  return MS_FAILURE;
+
+            /*
+             * cachePtr->status can be set to ON only if all it's labels didn't collide
+             */
+            cachePtr->status = MS_ON;
+            for(ll=0; ll<cachePtr->numlabels; ll++) {
+              if(cachePtr->labels[ll].status == MS_OFF) {
+                cachePtr->status = MS_OFF;
+                break;
+              }
+            }
+            if(cachePtr->status == MS_ON || classPtr->leader.maxdistance) {
+              /* add the marker polygon if we have one */
+              if(marker_poly.numlines) {
+                if(!cachePtr->poly) {
+                  cachePtr->poly = (shapeObj*)msSmallMalloc(sizeof(shapeObj));
+                  msInitShape(cachePtr->poly);
                 }
+                msAddLine(cachePtr->poly, marker_poly.line);
               }
+              if(cachePtr->poly)
+                msComputeBounds(cachePtr->poly);
             }
-   
+
+            if(cachePtr->status == MS_OFF)
+              continue; /* next label, as we had a collision */
+
+
             if(layerPtr->type == MS_LAYER_ANNOTATION && cachePtr->numstyles > 0) { /* need to draw a marker */
               for(i=0; i<cachePtr->numstyles; i++)
                 msDrawMarkerSymbol(&map->symbolset, image, &(cachePtr->point), &(cachePtr->styles[i]), layerPtr->scalefactor);
             }
-   
-            if(cachePtr->labelpath) {
-              msDrawTextLine(image, cachePtr->text, labelPtr, cachePtr->labelpath, &(map->fontset), layerPtr->scalefactor); /* Draw the curved label */
-            } else {
-              msDrawText(image, p, cachePtr->text, labelPtr, &(map->fontset), layerPtr->scalefactor); /* actually draw the label */
+
+            for(ll=0; ll<cachePtr->numlabels; ll++) {
+              labelPtr = &(cachePtr->labels[ll]);
+
+              /* here's where we draw the label styles */
+              if(labelPtr->numstyles > 0) {
+                for(i=0; i<labelPtr->numstyles; i++) {
+                  if(labelPtr->styles[i]->_geomtransform.type == MS_GEOMTRANSFORM_LABELPOINT)
+                    msDrawMarkerSymbol(&map->symbolset, image, &(cachePtr->point), labelPtr->styles[i], layerPtr->scalefactor);
+                  else if(labelPtr->styles[i]->_geomtransform.type == MS_GEOMTRANSFORM_LABELPOLY && labelPtr->annotext) {
+                    msDrawShadeSymbol(&map->symbolset, image, labelPtr->annopoly, labelPtr->styles[i], scalefactor); /* FIXME: scalefactor here should be adjusted by the label minsize/maxsize adjustments of each label, not only the last one. see #4408 */
+                  } else {
+                    msSetError(MS_MISCERR,"Labels only support LABELPNT and LABELPOLY GEOMTRANSFORMS", "msDrawLabelCAche()");
+                    return MS_FAILURE;
+                  }
+                }
+              }
+              if(labelPtr->annotext)
+                msDrawText(image, labelPtr->annopoint, labelPtr->annotext, labelPtr, &(map->fontset), layerPtr->scalefactor); /* actually draw the label */
             }
-          }
-	} /* next label */
+          } /* end else */
+        } /* next label(group) from cacheslot */
+        msDrawOffsettedLabels(image, map, priority);
       } /* next priority */
+#ifdef TBDEBUG
+      styleObj tstyle;
+      initStyle(&tstyle);
+      tstyle.width = 1;
+      tstyle.color.alpha = 255;
+      tstyle.color.red = 255;
+      tstyle.color.green = 0;
+      tstyle.color.blue = 0;
+      for(priority=MS_MAX_LABEL_PRIORITY-1; priority>=0; priority--) {
+        labelCacheSlotObj *cacheslot;
+        cacheslot = &(map->labelcache.slots[priority]);
 
-      return MS_SUCCESS; /* necessary? */
-    } else if( MS_RENDERER_IMAGEMAP(image->format) )
-      nReturnVal = msDrawLabelCacheIM(image, map);
+        for(l=cacheslot->numlabels-1; l>=0; l--) {
+          cachePtr = &(cacheslot->labels[l]); /* point to right spot in the label cache */
+          /*
+          assert((cachePtr->poly == NULL && cachePtr->status == MS_OFF) ||
+                  (cachePtr->poly && (cachePtr->status == MS_ON));
+           */
+          if(cachePtr->status) {
+            msDrawLineSymbol(&map->symbolset, image, cachePtr->poly, &tstyle, layerPtr->scalefactor);
+          }
+        }
+      }
+#endif
 
+      return MS_SUCCESS; /* necessary? */
+    }
   }
 
   return nReturnVal;
 }
 
+
 /**
- * Generic function to tell the underline device that layer 
+ * Generic function to tell the underline device that layer
  * drawing is stating
  */
 
 void msImageStartLayer(mapObj *map, layerObj *layer, imageObj *image)
 {
-    if (image)
-    {
-        if( MS_RENDERER_PLUGIN(image->format) ) {
-           char *approximation_scale = msLayerGetProcessingKey( layer, "APPROXIMATION_SCALE" );
-           if(approximation_scale) {
-              if(!strncasecmp(approximation_scale,"ROUND",5)) {
-                 MS_IMAGE_RENDERER(image)->transform_mode = MS_TRANSFORM_ROUND;
-              } else if(!strncasecmp(approximation_scale,"FULL",4)) {
-                 MS_IMAGE_RENDERER(image)->transform_mode = MS_TRANSFORM_FULLRESOLUTION;
-              } else if(!strncasecmp(approximation_scale,"SIMPLIFY",8)) {
-                 MS_IMAGE_RENDERER(image)->transform_mode = MS_TRANSFORM_SIMPLIFY;
-              } else {
-                 MS_IMAGE_RENDERER(image)->transform_mode = MS_TRANSFORM_SNAPTOGRID;
-                 MS_IMAGE_RENDERER(image)->approximation_scale = atof(approximation_scale);
-              }
-           } else {
-              MS_IMAGE_RENDERER(image)->transform_mode = MS_IMAGE_RENDERER(image)->default_transform_mode;
-              MS_IMAGE_RENDERER(image)->approximation_scale = MS_IMAGE_RENDERER(image)->default_approximation_scale;
-           }
-           MS_IMAGE_RENDERER(image)->startLayer(image, map, layer);
+  if (image) {
+    if( MS_RENDERER_PLUGIN(image->format) ) {
+      char *approximation_scale = msLayerGetProcessingKey( layer, "APPROXIMATION_SCALE" );
+      if(approximation_scale) {
+        if(!strncasecmp(approximation_scale,"ROUND",5)) {
+          MS_IMAGE_RENDERER(image)->transform_mode = MS_TRANSFORM_ROUND;
+        } else if(!strncasecmp(approximation_scale,"FULL",4)) {
+          MS_IMAGE_RENDERER(image)->transform_mode = MS_TRANSFORM_FULLRESOLUTION;
+        } else if(!strncasecmp(approximation_scale,"SIMPLIFY",8)) {
+          MS_IMAGE_RENDERER(image)->transform_mode = MS_TRANSFORM_SIMPLIFY;
+        } else {
+          MS_IMAGE_RENDERER(image)->transform_mode = MS_TRANSFORM_SNAPTOGRID;
+          MS_IMAGE_RENDERER(image)->approximation_scale = atof(approximation_scale);
         }
-        else if( MS_RENDERER_IMAGEMAP(image->format) )
-            msImageStartLayerIM(map, layer, image);
+      } else {
+        MS_IMAGE_RENDERER(image)->transform_mode = MS_IMAGE_RENDERER(image)->default_transform_mode;
+        MS_IMAGE_RENDERER(image)->approximation_scale = MS_IMAGE_RENDERER(image)->default_approximation_scale;
+      }
+      MS_IMAGE_RENDERER(image)->startLayer(image, map, layer);
+    } else if( MS_RENDERER_IMAGEMAP(image->format) )
+      msImageStartLayerIM(map, layer, image);
 
-    }
+  }
 }
 
 
 /**
- * Generic function to tell the underline device that layer 
+ * Generic function to tell the underline device that layer
  * drawing is ending
  */
 
 void msImageEndLayer(mapObj *map, layerObj *layer, imageObj *image)
 {
-    if(image) {
-        if( MS_RENDERER_PLUGIN(image->format) ) {
-            MS_IMAGE_RENDERER(image)->endLayer(image,map,layer);
-        }
+  if(image) {
+    if( MS_RENDERER_PLUGIN(image->format) ) {
+      MS_IMAGE_RENDERER(image)->endLayer(image,map,layer);
     }
+  }
 }
 
 /**
- * Generic function to tell the underline device that shape 
+ * Generic function to tell the underline device that shape
  * drawing is stating
  */
 
 void msDrawStartShape(mapObj *map, layerObj *layer, imageObj *image,
                       shapeObj *shape)
 {
-    if (image)
-    {
-    	if(MS_RENDERER_PLUGIN(image->format))
-		{
-		  if (image->format->vtable->startShape)
-			image->format->vtable->startShape(image, shape);
-		}
-
-        
+  if (image) {
+    if(MS_RENDERER_PLUGIN(image->format)) {
+      if (image->format->vtable->startShape)
+        image->format->vtable->startShape(image, shape);
     }
+
+
+  }
 }
 
 
 /**
- * Generic function to tell the underline device that shape 
+ * Generic function to tell the underline device that shape
  * drawing is ending
  */
 
-void msDrawEndShape(mapObj *map, layerObj *layer, imageObj *image, 
+void msDrawEndShape(mapObj *map, layerObj *layer, imageObj *image,
                     shapeObj *shape)
 {
-    if(MS_RENDERER_PLUGIN(image->format))
-    {
-      if (image->format->vtable->endShape)
-        image->format->vtable->endShape(image, shape);
-    }
+  if(MS_RENDERER_PLUGIN(image->format)) {
+    if (image->format->vtable->endShape)
+      image->format->vtable->endShape(image, shape);
+  }
 }
 /**
- * take the value from the shape and use it to change the 
+ * take the value from the shape and use it to change the
  * color in the style to match the range map
  */
 int msShapeToRange(styleObj *style, shapeObj *shape)
@@ -2797,10 +3293,9 @@ int msShapeToRange(styleObj *style, shapeObj *shape)
   /*first, get the value of the rangeitem, which should*/
   /*evaluate to a double*/
   fieldStr = shape->values[style->rangeitemindex];
-  if (fieldStr == NULL) /*if there's not value, bail*/
-    {
-      return MS_FAILURE;
-    }
+  if (fieldStr == NULL) { /*if there's not value, bail*/
+    return MS_FAILURE;
+  }
   fieldVal = 0.0;
   fieldVal = atof(fieldStr); /*faith that it's ok -- */
   /*should switch to strtod*/
@@ -2808,8 +3303,8 @@ int msShapeToRange(styleObj *style, shapeObj *shape)
 }
 
 /**
- * Allow direct mapping of a value so that mapscript can use the 
- * Ranges.  The styls passed in is updated to reflect the right color 
+ * Allow direct mapping of a value so that mapscript can use the
+ * Ranges.  The styls passed in is updated to reflect the right color
  * based on the fieldVal
  */
 int msValueToRange(styleObj *style, double fieldVal)
@@ -2819,14 +3314,16 @@ int msValueToRange(styleObj *style, double fieldVal)
 
   range = style->maxvalue - style->minvalue;
   scaledVal = (fieldVal - style->minvalue)/range;
-  
+
   /*At this point, we know where on the range we need to be*/
   /*However, we don't know how to map it yet, since RGB(A) can */
   /*Go up or down*/
   style->color.red = (int)(MS_MAX(0,(MS_MIN(255, (style->mincolor.red + ((style->maxcolor.red - style->mincolor.red) * scaledVal))))));
   style->color.green = (int)(MS_MAX(0,(MS_MIN(255,(style->mincolor.green + ((style->maxcolor.green - style->mincolor.green) * scaledVal))))));
   style->color.blue = (int)(MS_MAX(0,(MS_MIN(255,(style->mincolor.blue + ((style->maxcolor.blue - style->mincolor.blue) * scaledVal))))));
+#ifdef USE_GD
   style->color.pen = MS_PEN_UNSET; /*so it will recalculate pen*/
+#endif
 
   /*( "msMapRange(): %i %i %i", style->color.red , style->color.green, style->color.blue);*/
 
diff --git a/mapdrawgdal.c b/mapdrawgdal.c
index c673259..11ef598 100644
--- a/mapdrawgdal.c
+++ b/mapdrawgdal.c
@@ -2,8 +2,8 @@
  * $Id$
  *
  * Project:  MapServer
- * Purpose:  Code for drawing GDAL raster layers.  Called from 
- *           msDrawRasterLayerLow() in mapraster.c.  
+ * Purpose:  Code for drawing GDAL raster layers.  Called from
+ *           msDrawRasterLayerLow() in mapraster.c.
  * Author:   Frank Warmerdam, warmerdam at pobox.com
  *
  ******************************************************************************
@@ -16,7 +16,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -33,7 +33,7 @@
 #include "mapresample.h"
 #include "mapthread.h"
 
-MS_CVSID("$Id$")
+
 
 extern int InvGeoTransform( double *gt_in, double *gt_out );
 
@@ -45,49 +45,42 @@ extern int InvGeoTransform( double *gt_in, double *gt_out );
 #include "gdal.h"
 #include "cpl_string.h"
 
-#if GDAL_VERSION_NUM > 1174
-#  define ENABLE_DITHER
-#endif
-
-#ifdef ENABLE_DITHER
 #include "gdal_alg.h"
-#endif
 
 static int
 LoadGDALImages( GDALDatasetH hDS, int band_numbers[4], int band_count,
-		layerObj *layer, 
-		int src_xoff, int src_yoff, int src_xsize, int src_ysize, 
-		GByte *pabyBuffer,
-		int dst_xsize, int dst_ysize,
-                int *pbHaveRGBNoData, 
+                layerObj *layer,
+                int src_xoff, int src_yoff, int src_xsize, int src_ysize,
+                GByte *pabyBuffer,
+                int dst_xsize, int dst_ysize,
+                int *pbHaveRGBNoData,
                 int *pnNoData1, int *pnNoData2, int *pnNoData3 );
-static int 
+static int
 msDrawRasterLayerGDAL_RawMode(
-    mapObj *map, layerObj *layer, imageObj *image, GDALDatasetH hDS, 
-    int src_xoff, int src_yoff, int src_xsize, int src_ysize,
-    int dst_xoff, int dst_yoff, int dst_xsize, int dst_ysize );
+  mapObj *map, layerObj *layer, imageObj *image, GDALDatasetH hDS,
+  int src_xoff, int src_yoff, int src_xsize, int src_ysize,
+  int dst_xoff, int dst_yoff, int dst_xsize, int dst_ysize );
 
-static int 
+static int
 msDrawRasterLayerGDAL_16BitClassification(
-    mapObj *map, layerObj *layer, rasterBufferObj *rb,
-    GDALDatasetH hDS, GDALRasterBandH hBand,
-    int src_xoff, int src_yoff, int src_xsize, int src_ysize,
-    int dst_xoff, int dst_yoff, int dst_xsize, int dst_ysize );
+  mapObj *map, layerObj *layer, rasterBufferObj *rb,
+  GDALDatasetH hDS, GDALRasterBandH hBand,
+  int src_xoff, int src_yoff, int src_xsize, int src_ysize,
+  int dst_xoff, int dst_yoff, int dst_xsize, int dst_ysize );
 
-
-#ifdef ENABLE_DITHER
+#ifdef USE_GD
 static void Dither24to8( GByte *pabyRed, GByte *pabyGreen, GByte *pabyBlue,
-                         GByte *pabyDithered, int xsize, int ysize, 
+                         GByte *pabyDithered, int xsize, int ysize,
                          int bTransparent, colorObj transparentColor,
                          gdImagePtr gdImg );
-#endif
-
 /*
  * Stuff for allocating color cubes, and mapping between RGB values and
  * the corresponding color cube index.
  */
 
 static int allocColorCube(mapObj *map, gdImagePtr img, int *panColorCube);
+#endif
+
 
 #define RED_LEVELS 5
 #define RED_DIV 52
@@ -102,7 +95,7 @@ static int allocColorCube(mapObj *map, gdImagePtr img, int *panColorCube);
 #define RGB_INDEX(r,g,b) RGB_LEVEL_INDEX(((r)/RED_DIV),((g)/GREEN_DIV),((b)/BLUE_DIV))
 
 /*
- * rasterBufferObj setting macros. 
+ * rasterBufferObj setting macros.
  */
 
 
@@ -111,1023 +104,939 @@ static int allocColorCube(mapObj *map, gdImagePtr img, int *panColorCube);
 /*                       msDrawRasterLayerGDAL()                        */
 /************************************************************************/
 
-int msDrawRasterLayerGDAL(mapObj *map, layerObj *layer, imageObj *image, 
+int msDrawRasterLayerGDAL(mapObj *map, layerObj *layer, imageObj *image,
                           rasterBufferObj *rb, void *hDSVoid )
 
 {
-    int i,j, k; /* loop counters */
-    int cmap[MAXCOLORS], cmap_set = FALSE;
-    unsigned char rb_cmap[4][MAXCOLORS];
-    double adfGeoTransform[6], adfInvGeoTransform[6];
-    int	dst_xoff, dst_yoff, dst_xsize, dst_ysize;
-    int	src_xoff, src_yoff, src_xsize, src_ysize;
-    int   anColorCube[256];
-    double llx, lly, urx, ury;
-    rectObj copyRect, mapRect;
-    unsigned char *pabyRaw1=NULL, *pabyRaw2=NULL, *pabyRaw3=NULL, 
-        *pabyRawAlpha = NULL;
-    int classified = FALSE;
-    int red_band=0, green_band=0, blue_band=0, alpha_band=0, cmt=0;
-    int band_count, band_numbers[4];
-    GDALDatasetH hDS = hDSVoid;
-    GDALColorTableH hColorMap;
-    GDALRasterBandH hBand1=NULL, hBand2=NULL, hBand3=NULL, hBandAlpha=NULL;
-    int bHaveRGBNoData = FALSE;
-    int nNoData1=-1,nNoData2=-1,nNoData3=-1;
-    
-    /*only support rawdata and pluggable renderers*/
-    assert(MS_RENDERER_RAWDATA(image->format) || (MS_RENDERER_PLUGIN(image->format) && rb));
-    
-    /*make sure we don't have a truecolor gd image*/
-    assert(!rb || rb->type != MS_BUFFER_GD || !gdImageTrueColor(rb->data.gd_img));
-
-    memset( cmap, 0xff, MAXCOLORS * sizeof(int) );
-    memset( rb_cmap, 0, sizeof(rb_cmap) );
-
-/* -------------------------------------------------------------------- */
-/*      Test the image format instead of the map format.                */
-/*      Normally the map format and the image format should be the      */
-/*      same but In somes cases like swf and pdf support, a temporary   */
-/*      GD image object is created and used to render raster layers     */
-/*      and then dumped into the SWF or the PDF file.                   */
-/* -------------------------------------------------------------------- */
-  
-
-    src_xsize = GDALGetRasterXSize( hDS );
-    src_ysize = GDALGetRasterYSize( hDS );
+  int i,j, k; /* loop counters */
+  int cmap[MAXCOLORS];
+#ifndef NDEBUG
+  int cmap_set = FALSE;
+#endif
+  unsigned char rb_cmap[4][MAXCOLORS];
+  double adfGeoTransform[6], adfInvGeoTransform[6];
+  int dst_xoff, dst_yoff, dst_xsize, dst_ysize;
+  int src_xoff, src_yoff, src_xsize, src_ysize;
+  double llx, lly, urx, ury;
+  rectObj copyRect, mapRect;
+  unsigned char *pabyRaw1=NULL, *pabyRaw2=NULL, *pabyRaw3=NULL,
+                 *pabyRawAlpha = NULL;
+  int classified = FALSE;
+  int red_band=0, green_band=0, blue_band=0, alpha_band=0;
+  int band_count, band_numbers[4];
+  GDALDatasetH hDS = hDSVoid;
+  GDALColorTableH hColorMap;
+  GDALRasterBandH hBand1=NULL, hBand2=NULL, hBand3=NULL, hBandAlpha=NULL;
+  int bHaveRGBNoData = FALSE;
+  int nNoData1=-1,nNoData2=-1,nNoData3=-1;
+#ifdef USE_GD
+  int   anColorCube[256];
+  int cmt=0;
+  /*make sure we don't have a truecolor gd image*/
+  assert(!rb || rb->type != MS_BUFFER_GD || !gdImageTrueColor(rb->data.gd_img));
+#endif
 
-    /*
-     * If the RAW_WINDOW attribute is set, use that to establish what to
-     * load.  This is normally just set by the mapresample.c module to avoid
-     * problems with rotated maps.
-     */
+  /*only support rawdata and pluggable renderers*/
+  assert(MS_RENDERER_RAWDATA(image->format) || (MS_RENDERER_PLUGIN(image->format) && rb));
+
+
+  memset( cmap, 0xff, MAXCOLORS * sizeof(int) );
+  memset( rb_cmap, 0, sizeof(rb_cmap) );
+
+  /* -------------------------------------------------------------------- */
+  /*      Test the image format instead of the map format.                */
+  /*      Normally the map format and the image format should be the      */
+  /*      same but In somes cases like swf and pdf support, a temporary   */
+  /*      GD image object is created and used to render raster layers     */
+  /*      and then dumped into the SWF or the PDF file.                   */
+  /* -------------------------------------------------------------------- */
 
-    if( CSLFetchNameValue( layer->processing, "RAW_WINDOW" ) != NULL )
-    {
-        char **papszTokens = 
-            CSLTokenizeString( 
-                CSLFetchNameValue( layer->processing, "RAW_WINDOW" ) );
-      
-        if( layer->debug )
-            msDebug( "msDrawGDAL(%s): using RAW_WINDOW=%s, dst=0,0,%d,%d\n",
-                     layer->name,
-                     CSLFetchNameValue( layer->processing, "RAW_WINDOW" ),
-                     image->width, image->height );
-
-        if( CSLCount(papszTokens) != 4 )
-        {
-            CSLDestroy( papszTokens );
-            msSetError( MS_IMGERR, "RAW_WINDOW PROCESSING directive corrupt.",
-                        "msDrawGDAL()" );
-            return -1;
-        }
 
-        src_xoff = atoi(papszTokens[0]);
-        src_yoff = atoi(papszTokens[1]);
-        src_xsize = atoi(papszTokens[2]);
-        src_ysize = atoi(papszTokens[3]);
+  src_xsize = GDALGetRasterXSize( hDS );
+  src_ysize = GDALGetRasterYSize( hDS );
 
-        dst_xoff = 0;
-        dst_yoff = 0;
-        dst_xsize = image->width;
-        dst_ysize = image->height;
+  /*
+   * If the RAW_WINDOW attribute is set, use that to establish what to
+   * load.  This is normally just set by the mapresample.c module to avoid
+   * problems with rotated maps.
+   */
 
-        CSLDestroy( papszTokens );
+  if( CSLFetchNameValue( layer->processing, "RAW_WINDOW" ) != NULL ) {
+    char **papszTokens =
+      CSLTokenizeString(
+        CSLFetchNameValue( layer->processing, "RAW_WINDOW" ) );
+
+    if( layer->debug )
+      msDebug( "msDrawGDAL(%s): using RAW_WINDOW=%s, dst=0,0,%d,%d\n",
+               layer->name,
+               CSLFetchNameValue( layer->processing, "RAW_WINDOW" ),
+               image->width, image->height );
+
+    if( CSLCount(papszTokens) != 4 ) {
+      CSLDestroy( papszTokens );
+      msSetError( MS_IMGERR, "RAW_WINDOW PROCESSING directive corrupt.",
+                  "msDrawGDAL()" );
+      return -1;
     }
 
-    /*
-     * Compute the georeferenced window of overlap, and do nothing if there
-     * is no overlap between the map extents, and the file we are operating on.
-     */
-    else if( layer->transform )
-    {
-        int dst_lrx, dst_lry;
-        
-        if( layer->debug )
-            msDebug( "msDrawRasterLayerGDAL(): Entering transform.\n" );
-
-        msGetGDALGeoTransform( hDS, map, layer, adfGeoTransform );
-        InvGeoTransform( adfGeoTransform, adfInvGeoTransform );
-      
-        mapRect = map->extent;
-      
-        mapRect.minx -= map->cellsize*0.5;
-        mapRect.maxx += map->cellsize*0.5;
-        mapRect.miny -= map->cellsize*0.5;
-        mapRect.maxy += map->cellsize*0.5;
-      
-        copyRect = mapRect;
-      
-        if( copyRect.minx < GEO_TRANS(adfGeoTransform,0,src_ysize) )
-            copyRect.minx = GEO_TRANS(adfGeoTransform,0,src_ysize);
-        if( copyRect.maxx > GEO_TRANS(adfGeoTransform,src_xsize,0) )
-            copyRect.maxx = GEO_TRANS(adfGeoTransform,src_xsize,0);
-
-        if( copyRect.miny < GEO_TRANS(adfGeoTransform+3,0,src_ysize) )
-            copyRect.miny = GEO_TRANS(adfGeoTransform+3,0,src_ysize);
-        if( copyRect.maxy > GEO_TRANS(adfGeoTransform+3,src_xsize,0) )
-            copyRect.maxy = GEO_TRANS(adfGeoTransform+3,src_xsize,0);
-      
-        if( copyRect.minx >= copyRect.maxx || copyRect.miny >= copyRect.maxy )
-        {
-            if( layer->debug )
-                msDebug( "msDrawRasterLayerGDAL(): Error in overlap calculation.\n" );
-            return 0;
-        }
+    src_xoff = atoi(papszTokens[0]);
+    src_yoff = atoi(papszTokens[1]);
+    src_xsize = atoi(papszTokens[2]);
+    src_ysize = atoi(papszTokens[3]);
 
-        /*
-         * Copy the source and destination raster coordinates.
-         */
-        llx = GEO_TRANS(adfInvGeoTransform+0,copyRect.minx,copyRect.miny);
-        lly = GEO_TRANS(adfInvGeoTransform+3,copyRect.minx,copyRect.miny);
-        urx = GEO_TRANS(adfInvGeoTransform+0,copyRect.maxx,copyRect.maxy);
-        ury = GEO_TRANS(adfInvGeoTransform+3,copyRect.maxx,copyRect.maxy);
-      
-        src_xoff = MAX(0,(int) floor(llx+0.5));
-        src_yoff = MAX(0,(int) floor(ury+0.5));
-        src_xsize = MIN(MAX(0,(int) (urx - llx + 0.5)),
-                        GDALGetRasterXSize(hDS) - src_xoff);
-        src_ysize = MIN(MAX(0,(int) (lly - ury + 0.5)),
-                        GDALGetRasterYSize(hDS) - src_yoff);
-
-       /* We want very small windows to use at least one source pixel (#4172) */
-       if( src_xsize == 0 && (urx - llx) > 0.0 ) 
-       {
-           src_xsize = 1;
-	   src_xoff = MIN(src_xoff,GDALGetRasterXSize(hDS)-1);
-       }
-       if( src_ysize == 0 && (lly - ury) > 0.0 )
-       {
-           src_ysize = 1;
-	   src_yoff = MIN(src_yoff,GDALGetRasterYSize(hDS)-1);
-       }
-
-        if( src_xsize == 0 || src_ysize == 0 )
-        {
-            if( layer->debug )
-                msDebug( "msDrawRasterLayerGDAL(): no apparent overlap between map view and this window(1).\n" );
-            return 0;
-        }
+    dst_xoff = 0;
+    dst_yoff = 0;
+    dst_xsize = image->width;
+    dst_ysize = image->height;
 
-        if (map->cellsize == 0)
-        {
-            if( layer->debug )
-                msDebug( "msDrawRasterLayerGDAL(): Cellsize can't be 0.\n" );
-            return 0;
-        }
+    CSLDestroy( papszTokens );
+  }
 
-        dst_xoff = (int) ((copyRect.minx - mapRect.minx) / map->cellsize);
-        dst_yoff = (int) ((mapRect.maxy - copyRect.maxy) / map->cellsize);
-
-        dst_lrx = (int) ((copyRect.maxx - mapRect.minx) / map->cellsize + 0.5);
-        dst_lry = (int) ((mapRect.maxy - copyRect.miny) / map->cellsize + 0.5);
-        dst_lrx = MAX(0,MIN(image->width,dst_lrx));
-        dst_lry = MAX(0,MIN(image->height,dst_lry));
-      
-        dst_xsize = MAX(0,MIN(image->width,dst_lrx - dst_xoff));
-        dst_ysize = MAX(0,MIN(image->height,dst_lry - dst_yoff));
-
-        if( dst_xsize == 0 || dst_ysize == 0 )
-        {
-            if( layer->debug )
-                msDebug( "msDrawRasterLayerGDAL(): no apparent overlap between map view and this window(2).\n" );
-            return 0;
-        }
+  /*
+   * Compute the georeferenced window of overlap, and do nothing if there
+   * is no overlap between the map extents, and the file we are operating on.
+   */
+  else if( layer->transform ) {
+    int dst_lrx, dst_lry;
 
-        if( layer->debug )
-            msDebug( "msDrawRasterLayerGDAL(): src=%d,%d,%d,%d, dst=%d,%d,%d,%d\n", 
-                     src_xoff, src_yoff, src_xsize, src_ysize, 
-                     dst_xoff, dst_yoff, dst_xsize, dst_ysize );
-#ifndef notdef
-        if( layer->debug )
-        {
-            double d_src_xoff, d_src_yoff, geo_x, geo_y;
-
-            geo_x = mapRect.minx + dst_xoff * map->cellsize;
-            geo_y = mapRect.maxy - dst_yoff * map->cellsize;
-
-            d_src_xoff = (geo_x - adfGeoTransform[0]) / adfGeoTransform[1];
-            d_src_yoff = (geo_y - adfGeoTransform[3]) / adfGeoTransform[5];
-          
-            msDebug( "msDrawRasterLayerGDAL(): source raster PL (%.3f,%.3f) for dst PL (%d,%d).\n",
-                     d_src_xoff, d_src_yoff,
-                     dst_xoff, dst_yoff );
-        }
-#endif
+    if( layer->debug )
+      msDebug( "msDrawRasterLayerGDAL(): Entering transform.\n" );
+
+    msGetGDALGeoTransform( hDS, map, layer, adfGeoTransform );
+    InvGeoTransform( adfGeoTransform, adfInvGeoTransform );
+
+    mapRect = map->extent;
+
+    mapRect.minx -= map->cellsize*0.5;
+    mapRect.maxx += map->cellsize*0.5;
+    mapRect.miny -= map->cellsize*0.5;
+    mapRect.maxy += map->cellsize*0.5;
+
+    copyRect = mapRect;
+
+    if( copyRect.minx < GEO_TRANS(adfGeoTransform,0,src_ysize) )
+      copyRect.minx = GEO_TRANS(adfGeoTransform,0,src_ysize);
+    if( copyRect.maxx > GEO_TRANS(adfGeoTransform,src_xsize,0) )
+      copyRect.maxx = GEO_TRANS(adfGeoTransform,src_xsize,0);
+
+    if( copyRect.miny < GEO_TRANS(adfGeoTransform+3,0,src_ysize) )
+      copyRect.miny = GEO_TRANS(adfGeoTransform+3,0,src_ysize);
+    if( copyRect.maxy > GEO_TRANS(adfGeoTransform+3,src_xsize,0) )
+      copyRect.maxy = GEO_TRANS(adfGeoTransform+3,src_xsize,0);
+
+    if( copyRect.minx >= copyRect.maxx || copyRect.miny >= copyRect.maxy ) {
+      if( layer->debug )
+        msDebug( "msDrawRasterLayerGDAL(): Error in overlap calculation.\n" );
+      return 0;
     }
 
     /*
-     * If layer transforms are turned off, just map 1:1.
+     * Copy the source and destination raster coordinates.
      */
-    else
-    {
-        dst_xoff = src_xoff = 0;
-        dst_yoff = src_yoff = 0;
-        dst_xsize = src_xsize = MIN(image->width,src_xsize);
-        dst_ysize = src_ysize = MIN(image->height,src_ysize);
+    llx = GEO_TRANS(adfInvGeoTransform+0,copyRect.minx,copyRect.miny);
+    lly = GEO_TRANS(adfInvGeoTransform+3,copyRect.minx,copyRect.miny);
+    urx = GEO_TRANS(adfInvGeoTransform+0,copyRect.maxx,copyRect.maxy);
+    ury = GEO_TRANS(adfInvGeoTransform+3,copyRect.maxx,copyRect.maxy);
+
+    src_xoff = MAX(0,(int) floor(llx+0.5));
+    src_yoff = MAX(0,(int) floor(ury+0.5));
+    src_xsize = MIN(MAX(0,(int) (urx - llx + 0.5)),
+                    GDALGetRasterXSize(hDS) - src_xoff);
+    src_ysize = MIN(MAX(0,(int) (lly - ury + 0.5)),
+                    GDALGetRasterYSize(hDS) - src_yoff);
+
+    /* We want very small windows to use at least one source pixel (#4172) */
+    if( src_xsize == 0 && (urx - llx) > 0.0 ) {
+      src_xsize = 1;
+      src_xoff = MIN(src_xoff,GDALGetRasterXSize(hDS)-1);
+    }
+    if( src_ysize == 0 && (lly - ury) > 0.0 ) {
+      src_ysize = 1;
+      src_yoff = MIN(src_yoff,GDALGetRasterYSize(hDS)-1);
     }
 
-    /*
-     * In RAWDATA mode we don't fool with colors.  Do the raw processing, 
-     * and return from the function early.
-     */
-    if( MS_RENDERER_RAWDATA( image->format ) )
-    {
-        return msDrawRasterLayerGDAL_RawMode( 
-            map, layer, image, hDS, 
-            src_xoff, src_yoff, src_xsize, src_ysize, 
-            dst_xoff, dst_yoff, dst_xsize, dst_ysize );
+    if( src_xsize == 0 || src_ysize == 0 ) {
+      if( layer->debug )
+        msDebug( "msDrawRasterLayerGDAL(): no apparent overlap between map view and this window(1).\n" );
+      return 0;
     }
-  
-    /*
-     * Is this image classified?  We consider it classified if there are
-     * classes with an expression string *or* a color range.  We don't want
-     * to treat the raster as classified if there is just a bogus class here
-     * to force inclusion in the legend.
-     */
-    for( i = 0; i < layer->numclasses; i++ )
-    {
-        int s;
-
-        /* change colour based on colour range? */
-        for(s=0; s<layer->class[i]->numstyles; s++)
-        {
-            if( MS_VALID_COLOR(layer->class[i]->styles[s]->mincolor)
-                && MS_VALID_COLOR(layer->class[i]->styles[s]->maxcolor) )
-            {
-                classified = TRUE;
-                break;
-            }
-        }
-      
-        if( layer->class[i]->expression.string != NULL )
-        {
-            classified = TRUE;
-            break;
-        }
+
+    if (map->cellsize == 0) {
+      if( layer->debug )
+        msDebug( "msDrawRasterLayerGDAL(): Cellsize can't be 0.\n" );
+      return 0;
     }
 
-    /*
-     * Set up the band selection.  We look for a BANDS directive in the 
-     * the PROCESSING options.  If not found we default to red=1 or
-     * red=1,green=2,blue=3 or red=1,green=2,blue=3,alpha=4. 
-     */
+    dst_xoff = (int) ((copyRect.minx - mapRect.minx) / map->cellsize);
+    dst_yoff = (int) ((mapRect.maxy - copyRect.maxy) / map->cellsize);
 
-    if( CSLFetchNameValue( layer->processing, "BANDS" ) == NULL )
-    {
-        red_band = 1;
-
-        if( GDALGetRasterCount( hDS ) >= 4 
-            && GDALGetRasterColorInterpretation( 
-                GDALGetRasterBand( hDS, 4 ) ) == GCI_AlphaBand )
-            alpha_band = 4;
-      
-        if( GDALGetRasterCount( hDS ) >= 3 )
-        {
-            green_band = 2;
-            blue_band = 3;
-        }
+    dst_lrx = (int) ((copyRect.maxx - mapRect.minx) / map->cellsize + 0.5);
+    dst_lry = (int) ((mapRect.maxy - copyRect.miny) / map->cellsize + 0.5);
+    dst_lrx = MAX(0,MIN(image->width,dst_lrx));
+    dst_lry = MAX(0,MIN(image->height,dst_lry));
 
-        if( GDALGetRasterCount( hDS ) == 2 
-            && GDALGetRasterColorInterpretation( 
-                GDALGetRasterBand( hDS, 2 ) ) == GCI_AlphaBand )
-            alpha_band = 2;
-      
-        hBand1 = GDALGetRasterBand( hDS, red_band );
-        if( classified 
-            || GDALGetRasterColorTable( hBand1 ) != NULL )
-        {
-            alpha_band = 0;
-            green_band = 0;
-            blue_band = 0;
-        }
+    dst_xsize = MAX(0,MIN(image->width,dst_lrx - dst_xoff));
+    dst_ysize = MAX(0,MIN(image->height,dst_lry - dst_yoff));
+
+    if( dst_xsize == 0 || dst_ysize == 0 ) {
+      if( layer->debug )
+        msDebug( "msDrawRasterLayerGDAL(): no apparent overlap between map view and this window(2).\n" );
+      return 0;
     }
-    else
-    {
-        int *band_list;
-
-        band_list = msGetGDALBandList( layer, hDS, 4, &band_count );
-        if( band_list == NULL )
-            return -1;
-      
-        if( band_count > 0 )
-            red_band = band_list[0];
-        else
-            red_band = 0;
-        if( band_count > 2 )
-        {
-            green_band = band_list[1];
-            blue_band = band_list[2];
-        }
-        else	
-        {
-            green_band = 0;
-            blue_band = 0;
-        }
 
-        if( band_count > 3 )
-            alpha_band = band_list[3];
-        else
-            alpha_band = 0;
+    if( layer->debug )
+      msDebug( "msDrawRasterLayerGDAL(): src=%d,%d,%d,%d, dst=%d,%d,%d,%d\n",
+               src_xoff, src_yoff, src_xsize, src_ysize,
+               dst_xoff, dst_yoff, dst_xsize, dst_ysize );
+#ifndef notdef
+    if( layer->debug ) {
+      double d_src_xoff, d_src_yoff, geo_x, geo_y;
 
-        free( band_list );
-    }
+      geo_x = mapRect.minx + dst_xoff * map->cellsize;
+      geo_y = mapRect.maxy - dst_yoff * map->cellsize;
 
-    band_numbers[0] = red_band;
-    band_numbers[1] = green_band;
-    band_numbers[2] = blue_band;
-    band_numbers[3] = 0;
-  
-    if( blue_band != 0 && alpha_band != 0 )
-    {
-        band_numbers[3] = alpha_band;
-        band_count = 4;
+      d_src_xoff = (geo_x - adfGeoTransform[0]) / adfGeoTransform[1];
+      d_src_yoff = (geo_y - adfGeoTransform[3]) / adfGeoTransform[5];
+
+      msDebug( "msDrawRasterLayerGDAL(): source raster PL (%.3f,%.3f) for dst PL (%d,%d).\n",
+               d_src_xoff, d_src_yoff,
+               dst_xoff, dst_yoff );
     }
-    else if( blue_band != 0 && alpha_band == 0 )
-        band_count = 3;
-    else if( alpha_band != 0 )
-    {
-        band_numbers[1] = alpha_band;
-        band_count = 2;
+#endif
+  }
+
+  /*
+   * If layer transforms are turned off, just map 1:1.
+   */
+  else {
+    dst_xoff = src_xoff = 0;
+    dst_yoff = src_yoff = 0;
+    dst_xsize = src_xsize = MIN(image->width,src_xsize);
+    dst_ysize = src_ysize = MIN(image->height,src_ysize);
+  }
+
+  /*
+   * In RAWDATA mode we don't fool with colors.  Do the raw processing,
+   * and return from the function early.
+   */
+  if( MS_RENDERER_RAWDATA( image->format ) ) {
+    return msDrawRasterLayerGDAL_RawMode(
+             map, layer, image, hDS,
+             src_xoff, src_yoff, src_xsize, src_ysize,
+             dst_xoff, dst_yoff, dst_xsize, dst_ysize );
+  }
+
+  /*
+   * Is this image classified?  We consider it classified if there are
+   * classes with an expression string *or* a color range.  We don't want
+   * to treat the raster as classified if there is just a bogus class here
+   * to force inclusion in the legend.
+   */
+  for( i = 0; i < layer->numclasses; i++ ) {
+    int s;
+
+    /* change colour based on colour range? */
+    for(s=0; s<layer->class[i]->numstyles; s++) {
+      if( MS_VALID_COLOR(layer->class[i]->styles[s]->mincolor)
+          && MS_VALID_COLOR(layer->class[i]->styles[s]->maxcolor) ) {
+        classified = TRUE;
+        break;
+      }
+    }
+
+    if( layer->class[i]->expression.string != NULL ) {
+      classified = TRUE;
+      break;
+    }
+  }
+
+  /*
+   * Set up the band selection.  We look for a BANDS directive in the
+   * the PROCESSING options.  If not found we default to red=1 or
+   * red=1,green=2,blue=3 or red=1,green=2,blue=3,alpha=4.
+   */
+
+  if( CSLFetchNameValue( layer->processing, "BANDS" ) == NULL ) {
+    red_band = 1;
+
+    if( GDALGetRasterCount( hDS ) >= 4
+        && GDALGetRasterColorInterpretation(
+          GDALGetRasterBand( hDS, 4 ) ) == GCI_AlphaBand )
+      alpha_band = 4;
+
+    if( GDALGetRasterCount( hDS ) >= 3 ) {
+      green_band = 2;
+      blue_band = 3;
+    }
+
+    if( GDALGetRasterCount( hDS ) == 2
+        && GDALGetRasterColorInterpretation(
+          GDALGetRasterBand( hDS, 2 ) ) == GCI_AlphaBand )
+      alpha_band = 2;
+
+    hBand1 = GDALGetRasterBand( hDS, red_band );
+    if( classified
+        || GDALGetRasterColorTable( hBand1 ) != NULL ) {
+      alpha_band = 0;
+      green_band = 0;
+      blue_band = 0;
     }
+  } else {
+    int *band_list;
+
+    band_list = msGetGDALBandList( layer, hDS, 4, &band_count );
+    if( band_list == NULL )
+      return -1;
+
+    if( band_count > 0 )
+      red_band = band_list[0];
     else
-        band_count = 1;
-  
-    if( layer->debug > 1 || (layer->debug > 0 && green_band != 0) )
-    {
-        msDebug( "msDrawRasterLayerGDAL(): red,green,blue,alpha bands = %d,%d,%d,%d\n", 
-                 red_band, green_band, blue_band, alpha_band );
+      red_band = 0;
+    if( band_count > 2 ) {
+      green_band = band_list[1];
+      blue_band = band_list[2];
+    } else {
+      green_band = 0;
+      blue_band = 0;
     }
 
-    /*
-     * Get band handles for PC256, RGB or RGBA cases.
-     */
+    if( band_count > 3 )
+      alpha_band = band_list[3];
+    else
+      alpha_band = 0;
+
+    free( band_list );
+  }
+
+  band_numbers[0] = red_band;
+  band_numbers[1] = green_band;
+  band_numbers[2] = blue_band;
+  band_numbers[3] = 0;
+
+  if( blue_band != 0 && alpha_band != 0 ) {
+    band_numbers[3] = alpha_band;
+    band_count = 4;
+  } else if( blue_band != 0 && alpha_band == 0 )
+    band_count = 3;
+  else if( alpha_band != 0 ) {
+    band_numbers[1] = alpha_band;
+    band_count = 2;
+  } else
+    band_count = 1;
+
+  if( layer->debug > 1 || (layer->debug > 0 && green_band != 0) ) {
+    msDebug( "msDrawRasterLayerGDAL(): red,green,blue,alpha bands = %d,%d,%d,%d\n",
+             red_band, green_band, blue_band, alpha_band );
+  }
+
+  /*
+   * Get band handles for PC256, RGB or RGBA cases.
+   */
+  hBand1 = GDALGetRasterBand( hDS, red_band );
+  if( hBand1 == NULL )
+    return -1;
+
+  hBand2 = hBand3 = hBandAlpha = NULL;
+
+  if( green_band != 0 ) {
     hBand1 = GDALGetRasterBand( hDS, red_band );
-    if( hBand1 == NULL )
-        return -1;
+    hBand2 = GDALGetRasterBand( hDS, green_band );
+    hBand3 = GDALGetRasterBand( hDS, blue_band );
+    if( hBand1 == NULL || hBand2 == NULL || hBand3 == NULL )
+      return -1;
+  }
+
+  if( alpha_band != 0 )
+    hBandAlpha = GDALGetRasterBand( hDS, alpha_band );
+
+#ifdef USE_GD
+  /*
+   * Wipe pen indicators for all our layer class colors if they exist.
+   * Sometimes temporary gdImg'es are used in which case previously allocated
+   * pens won't generally apply.  See Bug 504.
+   */
+  if( rb->type == MS_BUFFER_GD ) {
+    int iClass;
+    int iStyle;
+    for( iClass = 0; iClass < layer->numclasses; iClass++ ) {
+      for (iStyle=0; iStyle<layer->class[iClass]->numstyles; iStyle++)
+        layer->class[iClass]->styles[iStyle]->color.pen = MS_PEN_UNSET;
+    }
+  }
+#endif
 
-    hBand2 = hBand3 = hBandAlpha = NULL;
+  /*
+   * The logic for a classification rendering of non-8bit raster bands
+   * is sufficiently different than the normal mechanism of loading
+   * into an 8bit buffer, that we isolate it into it's own subfunction.
+   */
+  if( classified
+      && hBand1 != NULL && GDALGetRasterDataType( hBand1 ) != GDT_Byte ) {
+    return msDrawRasterLayerGDAL_16BitClassification(
+             map, layer, rb, hDS, hBand1,
+             src_xoff, src_yoff, src_xsize, src_ysize,
+             dst_xoff, dst_yoff, dst_xsize, dst_ysize );
+  }
+
+  /*
+   * Get colormap for this image.  If there isn't one, and we have only
+   * one band create a greyscale colormap.
+   */
+  if( hBand2 != NULL )
+    hColorMap = NULL;
+  else {
+    hColorMap = GDALGetRasterColorTable( hBand1 );
+    if( hColorMap != NULL )
+      hColorMap = GDALCloneColorTable( hColorMap );
+    else if( hBand2 == NULL ) {
+      hColorMap = GDALCreateColorTable( GPI_RGB );
 
-    if( green_band != 0 )
-    {
-        hBand1 = GDALGetRasterBand( hDS, red_band );
-        hBand2 = GDALGetRasterBand( hDS, green_band );
-        hBand3 = GDALGetRasterBand( hDS, blue_band );
-        if( hBand1 == NULL || hBand2 == NULL || hBand3 == NULL )
-            return -1;
-    }
+      for( i = 0; i < 256; i++ ) {
+        colorObj pixel;
+        GDALColorEntry sEntry;
 
-    if( alpha_band != 0 )
-        hBandAlpha = GDALGetRasterBand( hDS, alpha_band );
+        pixel.red = i;
+        pixel.green = i;
+        pixel.blue = i;
+#ifdef USE_GD
+        pixel.pen = i;
+#endif
 
-    /*
-     * Wipe pen indicators for all our layer class colors if they exist.  
-     * Sometimes temporary gdImg'es are used in which case previously allocated
-     * pens won't generally apply.  See Bug 504.
-     */
-    if( rb->type == MS_BUFFER_GD )
-    {
-        int iClass;
-        int iStyle;
-        for( iClass = 0; iClass < layer->numclasses; iClass++ )
-        {
-            for (iStyle=0; iStyle<layer->class[iClass]->numstyles; iStyle++)
-                layer->class[iClass]->styles[iStyle]->color.pen = MS_PEN_UNSET;
+        if(MS_COMPARE_COLORS(pixel, layer->offsite)) {
+          sEntry.c1 = 0;
+          sEntry.c2 = 0;
+          sEntry.c3 = 0;
+          sEntry.c4 = 0; /* alpha set to zero */
+        } else if( rb->type != MS_BUFFER_GD ) {
+          sEntry.c1 = i;
+          sEntry.c2 = i;
+          sEntry.c3 = i;
+          sEntry.c4 = 255;
+        } else {
+          /*
+          ** This special calculation is intended to use only 128
+          ** unique colors for greyscale in non-truecolor mode.
+          */
+
+          sEntry.c1 = i - i%2;
+          sEntry.c2 = i - i%2;
+          sEntry.c3 = i - i%2;
+          sEntry.c4 = 255;
         }
+
+        GDALSetColorEntry( hColorMap, i, &sEntry );
+      }
     }
 
     /*
-     * The logic for a classification rendering of non-8bit raster bands
-     * is sufficiently different than the normal mechanism of loading
-     * into an 8bit buffer, that we isolate it into it's own subfunction.
-     */
-    if( classified 
-        && hBand1 != NULL && GDALGetRasterDataType( hBand1 ) != GDT_Byte ) 
+    ** If we have a known NODATA value, mark it now as transparent.
+    */
     {
-        return msDrawRasterLayerGDAL_16BitClassification( 
-            map, layer, rb, hDS, hBand1,
-            src_xoff, src_yoff, src_xsize, src_ysize, 
-            dst_xoff, dst_yoff, dst_xsize, dst_ysize );
+      int    bGotNoData;
+      double dfNoDataValue = msGetGDALNoDataValue( layer, hBand1,
+                             &bGotNoData);
+
+      if( bGotNoData && dfNoDataValue >= 0
+          && dfNoDataValue < GDALGetColorEntryCount( hColorMap ) ) {
+        GDALColorEntry sEntry;
+
+        memcpy( &sEntry,
+                GDALGetColorEntry( hColorMap, (int) dfNoDataValue ),
+                sizeof(GDALColorEntry) );
+
+        sEntry.c4 = 0;
+        GDALSetColorEntry( hColorMap, (int) dfNoDataValue, &sEntry );
+      }
     }
+  }
 
-    /*
-     * Get colormap for this image.  If there isn't one, and we have only
-     * one band create a greyscale colormap. 
-     */
-    if( hBand2 != NULL )
-        hColorMap = NULL;
-    else
-    {
-        hColorMap = GDALGetRasterColorTable( hBand1 );
-        if( hColorMap != NULL )
-            hColorMap = GDALCloneColorTable( hColorMap );
-        else if( hBand2 == NULL )
-        {
-            hColorMap = GDALCreateColorTable( GPI_RGB );
-          
-            for( i = 0; i < 256; i++ )
-            {
-                colorObj pixel;
-                GDALColorEntry sEntry;
-
-                pixel.red = i;
-                pixel.green = i;
-                pixel.blue = i;
-                pixel.pen = i;
-              
-                if(MS_COMPARE_COLORS(pixel, layer->offsite))
-                {
-                    sEntry.c1 = 0;
-                    sEntry.c2 = 0;
-                    sEntry.c3 = 0;
-                    sEntry.c4 = 0; /* alpha set to zero */
-                }
-                else if( rb->type != MS_BUFFER_GD )
-                {
-                    sEntry.c1 = i;
-                    sEntry.c2 = i;
-                    sEntry.c3 = i;
-                    sEntry.c4 = 255;
-                }
-                else
-                {
-                    /*
-                    ** This special calculation is intended to use only 128
-                    ** unique colors for greyscale in non-truecolor mode.
-                    */
-
-                    sEntry.c1 = i - i%2;
-                    sEntry.c2 = i - i%2;
-                    sEntry.c3 = i - i%2;
-                    sEntry.c4 = 255;
-                }
-                  
-                GDALSetColorEntry( hColorMap, i, &sEntry );
+  /*
+   * Setup the mapping between source eight bit pixel values, and the
+   * output images color table.  There are two general cases, where the
+   * class colors are provided by the MAP file, or where we use the native
+   * color table.
+   */
+  if( classified ) {
+    int c, color_count;
+
+#ifndef NDEBUG
+    cmap_set = TRUE;
+#endif
+
+    if( hColorMap == NULL ) {
+      msSetError(MS_IOERR,
+                 "Attempt to classify 24bit image, this is unsupported.",
+                 "drawGDAL()");
+      return -1;
+    }
+
+    color_count = MIN(256,GDALGetColorEntryCount(hColorMap));
+    for(i=0; i < color_count; i++) {
+      colorObj pixel;
+      int colormap_index;
+      GDALColorEntry sEntry;
+
+      GDALGetColorEntryAsRGB( hColorMap, i, &sEntry );
+
+      pixel.red = sEntry.c1;
+      pixel.green = sEntry.c2;
+      pixel.blue = sEntry.c3;
+      colormap_index = i;
+
+      if(!MS_COMPARE_COLORS(pixel, layer->offsite)) {
+        c = msGetClass(layer, &pixel, colormap_index);
+
+        if(c == -1) { /* doesn't belong to any class, so handle like offsite*/
+          if( rb->type == MS_BUFFER_GD )
+            cmap[i] = -1;
+        } else {
+          int s;
+
+          /* change colour based on colour range?  Currently we
+             only address the greyscale case properly. */
+
+          for(s=0; s<layer->class[c]->numstyles; s++) {
+            if( MS_VALID_COLOR(layer->class[c]->styles[s]->mincolor)
+                && MS_VALID_COLOR(layer->class[c]->styles[s]->maxcolor) )
+              msValueToRange(layer->class[c]->styles[s],
+                             sEntry.c1 );
+          }
+#ifdef USE_GD
+          if( rb->type == MS_BUFFER_GD ) {
+            RESOLVE_PEN_GD(rb->data.gd_img, layer->class[c]->styles[0]->color);
+            if( MS_TRANSPARENT_COLOR(layer->class[c]->styles[0]->color) )
+              cmap[i] = -1;
+            else if( MS_VALID_COLOR(layer->class[c]->styles[0]->color)) {
+              /* use class color */
+              cmap[i] = layer->class[c]->styles[0]->color.pen;
+            } else /* Use raster color */
+              cmap[i] = msAddColorGD(map, rb->data.gd_img, cmt,
+                                     pixel.red, pixel.green, pixel.blue);
+          } else if( rb->type == MS_BUFFER_BYTE_RGBA )
+#endif
+          {
+            if( MS_TRANSPARENT_COLOR(layer->class[c]->styles[0]->color))
+              /* leave it transparent */;
+
+            else if( MS_VALID_COLOR(layer->class[c]->styles[0]->color)) {
+              rb_cmap[0][i] = layer->class[c]->styles[0]->color.red;
+              rb_cmap[1][i] = layer->class[c]->styles[0]->color.green;
+              rb_cmap[2][i] = layer->class[c]->styles[0]->color.blue;
+              rb_cmap[3][i] = (255*layer->class[c]->styles[0]->opacity / 100);
             }
-        }
 
-        /* 
-        ** If we have a known NODATA value, mark it now as transparent. 
-        */
-        {
-            int    bGotNoData;
-            double dfNoDataValue = msGetGDALNoDataValue( layer, hBand1, 
-                                                         &bGotNoData);
-
-            if( bGotNoData && dfNoDataValue >= 0 
-                && dfNoDataValue < GDALGetColorEntryCount( hColorMap ) )
-            {
-                GDALColorEntry sEntry;
-              
-                memcpy( &sEntry, 
-                        GDALGetColorEntry( hColorMap, (int) dfNoDataValue ),
-                        sizeof(GDALColorEntry) );
-
-                sEntry.c4 = 0;
-                GDALSetColorEntry( hColorMap, (int) dfNoDataValue, &sEntry );
+            else { /* Use raster color */
+              rb_cmap[0][i] = pixel.red;
+              rb_cmap[1][i] = pixel.green;
+              rb_cmap[2][i] = pixel.blue;
+              rb_cmap[3][i] = 255;
             }
+          }
         }
+#ifdef USE_GD
+      } else {
+        if( rb->type == MS_BUFFER_GD )
+          cmap[i] = -1;
+#endif
+      }
     }
+#ifdef USE_GD
+  } else if( hColorMap != NULL && rb->type == MS_BUFFER_GD ) {
+    int color_count;
+#ifndef NDEBUG
+    cmap_set = TRUE;
+#endif
 
-    /*
-     * Setup the mapping between source eight bit pixel values, and the
-     * output images color table.  There are two general cases, where the
-     * class colors are provided by the MAP file, or where we use the native
-     * color table.
-     */
-    if( classified ) {
-        int c, color_count;
+    color_count = MIN(256,GDALGetColorEntryCount(hColorMap));
 
-        cmap_set = TRUE;
+    for(i=0; i < color_count; i++) {
+      GDALColorEntry sEntry;
 
-        if( hColorMap == NULL )
-        {
-            msSetError(MS_IOERR, 
-                       "Attempt to classify 24bit image, this is unsupported.",
-                       "drawGDAL()");
-            return -1;
-        }
+      GDALGetColorEntryAsRGB( hColorMap, i, &sEntry );
 
-        color_count = MIN(256,GDALGetColorEntryCount(hColorMap));
-        for(i=0; i < color_count; i++) {
-            colorObj pixel;
-            GDALColorEntry sEntry;
-
-            GDALGetColorEntryAsRGB( hColorMap, i, &sEntry );
-            
-            pixel.red = sEntry.c1;
-            pixel.green = sEntry.c2;
-            pixel.blue = sEntry.c3;
-            pixel.pen = i;
-        
-            if(!MS_COMPARE_COLORS(pixel, layer->offsite))
-            {
-                c = msGetClass(layer, &pixel);
-            
-                if(c == -1)/* doesn't belong to any class, so handle like offsite*/
-                {
-                    if( rb->type == MS_BUFFER_GD )
-                        cmap[i] = -1;
-                }
-                else
-                {
-                    int s;
-                
-                    /* change colour based on colour range?  Currently we 
-                       only address the greyscale case properly. */
-
-                    for(s=0; s<layer->class[c]->numstyles; s++)
-                    {
-                        if( MS_VALID_COLOR(layer->class[c]->styles[s]->mincolor)
-                            && MS_VALID_COLOR(layer->class[c]->styles[s]->maxcolor) )
-                            msValueToRange(layer->class[c]->styles[s],
-                                           sEntry.c1 );
-                    }
-
-                    if( rb->type == MS_BUFFER_GD )
-                    {
-                        RESOLVE_PEN_GD(rb->data.gd_img, layer->class[c]->styles[0]->color);
-                        if( MS_TRANSPARENT_COLOR(layer->class[c]->styles[0]->color) )
-                            cmap[i] = -1;
-                        else if( MS_VALID_COLOR(layer->class[c]->styles[0]->color))
-                        {
-                            /* use class color */
-                            cmap[i] = layer->class[c]->styles[0]->color.pen;
-                        }
-                        else /* Use raster color */
-                            cmap[i] = msAddColorGD(map, rb->data.gd_img, cmt,
-                                                   pixel.red, pixel.green, pixel.blue);
-                    }
-                    else if( rb->type == MS_BUFFER_BYTE_RGBA )
-                    {
-                        if( MS_TRANSPARENT_COLOR(layer->class[c]->styles[0]->color))
-                            /* leave it transparent */;
-
-                        else if( MS_VALID_COLOR(layer->class[c]->styles[0]->color))
-                        {
-                            rb_cmap[0][i] = layer->class[c]->styles[0]->color.red;
-                            rb_cmap[1][i] = layer->class[c]->styles[0]->color.green;
-                            rb_cmap[2][i] = layer->class[c]->styles[0]->color.blue;
-                            rb_cmap[3][i] = (255*layer->class[c]->styles[0]->opacity / 100);
-                        }
-
-                        else /* Use raster color */
-                        {
-                            rb_cmap[0][i] = pixel.red;
-                            rb_cmap[1][i] = pixel.green;
-                            rb_cmap[2][i] = pixel.blue;
-                            rb_cmap[3][i] = 255;
-                        }
-                    }
-                }
-            } else {
-                if( rb->type == MS_BUFFER_GD )
-                    cmap[i] = -1;
-            }
-        }
-    } else if( hColorMap != NULL && rb->type == MS_BUFFER_GD ) {
-        int color_count;
-        cmap_set = TRUE;
-
-        color_count = MIN(256,GDALGetColorEntryCount(hColorMap));
-
-        for(i=0; i < color_count; i++) {
-            GDALColorEntry sEntry;
-
-            GDALGetColorEntryAsRGB( hColorMap, i, &sEntry );
-
-            if( sEntry.c4 != 0 
-                && (!MS_VALID_COLOR( layer->offsite )
-                    || layer->offsite.red != sEntry.c1
-                    || layer->offsite.green != sEntry.c2
-                    || layer->offsite.blue != sEntry.c3 ) )
-                cmap[i] = msAddColorGD(map, rb->data.gd_img, cmt, 
-                                       sEntry.c1, sEntry.c2, sEntry.c3);
-            else
-                cmap[i] = -1;
-        }
-    }
-    else if( hBand2 == NULL && hColorMap != NULL && rb->type == MS_BUFFER_BYTE_RGBA )
-    {
-        int color_count;
-        cmap_set = TRUE;
-
-        color_count = MIN(256,GDALGetColorEntryCount(hColorMap));
-
-        for(i=0; i < color_count; i++) {
-            GDALColorEntry sEntry;
-          
-            GDALGetColorEntryAsRGB( hColorMap, i, &sEntry );
-
-            if( sEntry.c4 != 0 
-                && (!MS_VALID_COLOR( layer->offsite )
-                    || layer->offsite.red != sEntry.c1
-                    || layer->offsite.green != sEntry.c2
-                    || layer->offsite.blue != sEntry.c3 ) )
-            {
-                rb_cmap[0][i] = sEntry.c1;
-                rb_cmap[1][i] = sEntry.c2;
-                rb_cmap[2][i] = sEntry.c3;
-                rb_cmap[3][i] = sEntry.c4;
-            }
-        }
-    }
-    else if( rb->type == MS_BUFFER_GD )
-    {
-        allocColorCube( map, rb->data.gd_img, anColorCube );
+      if( sEntry.c4 != 0
+          && (!MS_VALID_COLOR( layer->offsite )
+              || layer->offsite.red != sEntry.c1
+              || layer->offsite.green != sEntry.c2
+              || layer->offsite.blue != sEntry.c3 ) )
+        cmap[i] = msAddColorGD(map, rb->data.gd_img, cmt,
+                               sEntry.c1, sEntry.c2, sEntry.c3);
+      else
+        cmap[i] = -1;
     }
+#endif
+  } else if( hBand2 == NULL && hColorMap != NULL && rb->type == MS_BUFFER_BYTE_RGBA ) {
+    int color_count;
+#ifndef NDEBUG
+    cmap_set = TRUE;
+#endif
 
-    /*
-     * Allocate imagery buffers.
-     */
-    pabyRaw1 = (unsigned char *) malloc(dst_xsize * dst_ysize * band_count);
-    if( pabyRaw1 == NULL )
-    {
-        msSetError(MS_MEMERR, "Allocating work image of size %dx%dx%d failed.",
-                   "msDrawRasterLayerGDAL()", dst_xsize, dst_ysize, band_count );
+    color_count = MIN(256,GDALGetColorEntryCount(hColorMap));
+
+    for(i=0; i < color_count; i++) {
+      GDALColorEntry sEntry;
+
+      GDALGetColorEntryAsRGB( hColorMap, i, &sEntry );
+
+      if( sEntry.c4 != 0
+          && (!MS_VALID_COLOR( layer->offsite )
+              || layer->offsite.red != sEntry.c1
+              || layer->offsite.green != sEntry.c2
+              || layer->offsite.blue != sEntry.c3 ) ) {
+        rb_cmap[0][i] = sEntry.c1;
+        rb_cmap[1][i] = sEntry.c2;
+        rb_cmap[2][i] = sEntry.c3;
+        rb_cmap[3][i] = sEntry.c4;
+      }
+    }
+  }
+#ifdef USE_GD
+  else if( rb->type == MS_BUFFER_GD ) {
+    allocColorCube( map, rb->data.gd_img, anColorCube );
+  }
+#endif
+
+  /*
+   * Allocate imagery buffers.
+   */
+  pabyRaw1 = (unsigned char *) malloc(dst_xsize * dst_ysize * band_count);
+  if( pabyRaw1 == NULL ) {
+    msSetError(MS_MEMERR, "Allocating work image of size %dx%dx%d failed.",
+               "msDrawRasterLayerGDAL()", dst_xsize, dst_ysize, band_count );
+    return -1;
+  }
+
+  if( hBand2 != NULL && hBand3 != NULL ) {
+    pabyRaw2 = pabyRaw1 + dst_xsize * dst_ysize * 1;
+    pabyRaw3 = pabyRaw1 + dst_xsize * dst_ysize * 2;
+  }
+
+  if( hBandAlpha != NULL ) {
+    if( hBand2 != NULL )
+      pabyRawAlpha = pabyRaw1 + dst_xsize * dst_ysize * 3;
+    else
+      pabyRawAlpha = pabyRaw1 + dst_xsize * dst_ysize * 1;
+  }
+
+  /*
+   * Load image data into buffers with scaling, etc.
+   */
+  if( LoadGDALImages( hDS, band_numbers, band_count, layer,
+                      src_xoff, src_yoff, src_xsize, src_ysize,
+                      pabyRaw1, dst_xsize, dst_ysize,
+                      &bHaveRGBNoData,
+                      &nNoData1, &nNoData2, &nNoData3 ) == -1 ) {
+    free( pabyRaw1 );
+    return -1;
+  }
+
+  if( bHaveRGBNoData && layer->debug )
+    msDebug( "msDrawGDAL(): using RGB nodata values from GDAL dataset.\n" );
+
+  /* -------------------------------------------------------------------- */
+  /*      If there was no alpha band, but we have a dataset level mask    */
+  /*      load it as massage it so it will function as our alpha for      */
+  /*      transparency purposes.                                          */
+  /* -------------------------------------------------------------------- */
+  if( hBandAlpha == NULL ) {
+    int nMaskFlags = GDALGetMaskFlags(hBand1);
+
+    if( (CSLFetchNameValue( layer->processing, "BANDS" ) == NULL ) &&
+        (nMaskFlags & GMF_PER_DATASET) != 0 &&
+        (nMaskFlags & (GMF_NODATA|GMF_ALL_VALID)) == 0 ) {
+      CPLErr eErr;
+
+      if( layer->debug )
+        msDebug( "msDrawGDAL(): using GDAL mask band for alpha.\n" );
+
+      band_count++;
+
+      pabyRaw1 = (unsigned char *)
+                 realloc(pabyRaw1,dst_xsize * dst_ysize * band_count);
+
+      if( pabyRaw1 == NULL ) {
+        msSetError(MS_MEMERR,
+                   "Allocating work image of size %dx%dx%d failed.",
+                   "msDrawRasterLayerGDAL()",
+                   dst_xsize, dst_ysize, band_count );
         return -1;
-    }
+      }
 
-    if( hBand2 != NULL && hBand3 != NULL )
-    {
+      if( hBand2 != NULL ) {
         pabyRaw2 = pabyRaw1 + dst_xsize * dst_ysize * 1;
         pabyRaw3 = pabyRaw1 + dst_xsize * dst_ysize * 2;
-    }
+        pabyRawAlpha = pabyRaw1 + dst_xsize * dst_ysize * 3;
+      } else {
+        pabyRawAlpha = pabyRaw1 + dst_xsize * dst_ysize * 1;
+      }
 
-    if( hBandAlpha != NULL )
-    {
-        if( hBand2 != NULL )
-            pabyRawAlpha = pabyRaw1 + dst_xsize * dst_ysize * 3;
-        else
-            pabyRawAlpha = pabyRaw1 + dst_xsize * dst_ysize * 1;
-    }
+      hBandAlpha = GDALGetMaskBand(hBand1);
 
-    /*
-     * Load image data into buffers with scaling, etc.
-     */
-    if( LoadGDALImages( hDS, band_numbers, band_count, layer, 
-                        src_xoff, src_yoff, src_xsize, src_ysize, 
-                        pabyRaw1, dst_xsize, dst_ysize,
-                        &bHaveRGBNoData, 
-                        &nNoData1, &nNoData2, &nNoData3 ) == -1 )
-    {
+      eErr = GDALRasterIO( hBandAlpha, GF_Read,
+                           src_xoff, src_yoff, src_xsize, src_ysize,
+                           pabyRawAlpha, dst_xsize, dst_ysize, GDT_Byte, 0,0);
+
+      if( eErr != CE_None ) {
+        msSetError( MS_IOERR, "GDALRasterIO() failed: %s",
+                    "drawGDAL()", CPLGetLastErrorMsg() );
         free( pabyRaw1 );
         return -1;
-    }
-
-    if( bHaveRGBNoData && layer->debug )
-        msDebug( "msDrawGDAL(): using RGB nodata values from GDAL dataset.\n" );
-
-/* -------------------------------------------------------------------- */
-/*      If there was no alpha band, but we have a dataset level mask    */
-/*      load it as massage it so it will function as our alpha for      */
-/*      transparency purposes.                                          */
-/* -------------------------------------------------------------------- */
-#if defined(GDAL_VERSION_NUM) && GDAL_VERSION_NUM >= 1500 
-    if( hBandAlpha == NULL )
-    {
-        int nMaskFlags = GDALGetMaskFlags(hBand1); 
-   
-        if( (CSLFetchNameValue( layer->processing, "BANDS" ) == NULL ) && 
-            (nMaskFlags & GMF_PER_DATASET) != 0 && 
-            (nMaskFlags & (GMF_NODATA|GMF_ALL_VALID)) == 0 ) 
-        { 
-            CPLErr eErr; 
-
-            if( layer->debug )
-                msDebug( "msDrawGDAL(): using GDAL mask band for alpha.\n" );
- 		 
-            band_count++;
-
-            pabyRaw1 = (unsigned char *) 
-                realloc(pabyRaw1,dst_xsize * dst_ysize * band_count);
-            
-            if( pabyRaw1 == NULL ) 
-            { 
-                msSetError(MS_MEMERR, 
-                           "Allocating work image of size %dx%dx%d failed.", 
-                           "msDrawRasterLayerGDAL()", 
-                           dst_xsize, dst_ysize, band_count ); 
-                return -1; 
-            } 
-
-            if( hBand2 != NULL )
-            {
-                pabyRaw2 = pabyRaw1 + dst_xsize * dst_ysize * 1;
-                pabyRaw3 = pabyRaw1 + dst_xsize * dst_ysize * 2;
-                pabyRawAlpha = pabyRaw1 + dst_xsize * dst_ysize * 3;
-            }
-            else
-            {
-                pabyRawAlpha = pabyRaw1 + dst_xsize * dst_ysize * 1;
-            }
+      }
+
+      /* In case the mask is not an alpha channel, expand values of 1 to 255, */
+      /* so we can deal as it was an alpha band afterwards */
+      if ((nMaskFlags & GMF_ALPHA) == 0) {
+        for(i=0; i<dst_xsize * dst_ysize; i++)
+          if (pabyRawAlpha[i])
+            pabyRawAlpha[i] = 255;
+      }
+    }
+  }
+
+#ifdef USE_GD
+  /* -------------------------------------------------------------------- */
+  /*      Single band plus colormap with alpha blending to 8bit.          */
+  /* -------------------------------------------------------------------- */
+  if( hBand2 == NULL && rb->type == MS_BUFFER_GD && hBandAlpha != NULL ) {
+    assert( cmap_set );
+    k = 0;
 
-            hBandAlpha = GDALGetMaskBand(hBand1); 
- 		 
-            eErr = GDALRasterIO( hBandAlpha, GF_Read,  
-                                 src_xoff, src_yoff, src_xsize, src_ysize,  
-                                 pabyRawAlpha, dst_xsize, dst_ysize, GDT_Byte, 0,0); 
- 		 
-            if( eErr != CE_None ) 
-            { 
-                msSetError( MS_IOERR, "GDALRasterIO() failed: %s",  
-                            "drawGDAL()", CPLGetLastErrorMsg() ); 
-                free( pabyRaw1 ); 
-                return -1; 
-            } 
- 		 
-            /* In case the mask is not an alpha channel, expand values of 1 to 255, */ 
-            /* so we can deal as it was an alpha band afterwards */ 
-            if ((nMaskFlags & GMF_ALPHA) == 0) 
-            { 
-                for(i=0;i<dst_xsize * dst_ysize;i++) 
-                    if (pabyRawAlpha[i]) 
-                        pabyRawAlpha[i] = 255; 
-            } 
-        } 
-    }
-#endif /* defined(GDAL_VERSION_NUM) && GDAL_VERSION_NUM >= 1500 */
+    for( i = dst_yoff; i < dst_yoff + dst_ysize; i++ ) {
+      int result, alpha;
 
-/* -------------------------------------------------------------------- */
-/*      Single band plus colormap with alpha blending to 8bit.          */
-/* -------------------------------------------------------------------- */
-    if( hBand2 == NULL && rb->type == MS_BUFFER_GD && hBandAlpha != NULL )
-    {
-        assert( cmap_set );
-        k = 0;
+      for( j = dst_xoff; j < dst_xoff + dst_xsize; j++ ) {
+        alpha = pabyRawAlpha[k];
 
-        for( i = dst_yoff; i < dst_yoff + dst_ysize; i++ )
-        {
-            int	result, alpha;
-          
-            for( j = dst_xoff; j < dst_xoff + dst_xsize; j++ )
-            {
-                alpha = pabyRawAlpha[k];
+        result = cmap[pabyRaw1[k++]];
 
-                result = cmap[pabyRaw1[k++]];
+        /*
+        ** We don't do alpha blending in non-truecolor mode, just
+        ** threshold the point on/off at alpha=128.
+        */
 
-                /* 
-                ** We don't do alpha blending in non-truecolor mode, just
-                ** threshold the point on/off at alpha=128.
-                */
+        if( result != -1 && alpha >= 128 )
+          rb->data.gd_img->pixels[i][j] = result;
+      }
+    }
 
-                if( result != -1 && alpha >= 128 )
-                    rb->data.gd_img->pixels[i][j] = result;
-            }
-        }
+    assert( k == dst_xsize * dst_ysize );
+  }
 
-        assert( k == dst_xsize * dst_ysize );
-    }
+  /* -------------------------------------------------------------------- */
+  /*      Single band plus colormap (no alpha) to 8bit.                   */
+  /* -------------------------------------------------------------------- */
+  else if( hBand2 == NULL  && rb->type == MS_BUFFER_GD ) {
+    assert( cmap_set );
+    k = 0;
 
-/* -------------------------------------------------------------------- */
-/*      Single band plus colormap (no alpha) to 8bit.                   */
-/* -------------------------------------------------------------------- */
-    else if( hBand2 == NULL  && rb->type == MS_BUFFER_GD )
-    {
-        assert( cmap_set );
-        k = 0;
+    for( i = dst_yoff; i < dst_yoff + dst_ysize; i++ ) {
+      int result;
 
-        for( i = dst_yoff; i < dst_yoff + dst_ysize; i++ )
-        {
-            int	result;
-          
-            for( j = dst_xoff; j < dst_xoff + dst_xsize; j++ )
-            {
-                result = cmap[pabyRaw1[k++]];
-                if( result != -1 )
-                {
-                    rb->data.gd_img->pixels[i][j] = result;
-                }
-            }
+      for( j = dst_xoff; j < dst_xoff + dst_xsize; j++ ) {
+        result = cmap[pabyRaw1[k++]];
+        if( result != -1 ) {
+          rb->data.gd_img->pixels[i][j] = result;
         }
-
-        assert( k == dst_xsize * dst_ysize );
+      }
     }
 
-/* -------------------------------------------------------------------- */
-/*      Single band plus colormap and alpha to truecolor. (RB)          */
-/* -------------------------------------------------------------------- */
-    else if( hBand2 == NULL && rb->type == MS_BUFFER_BYTE_RGBA && hBandAlpha != NULL )
-    {
-        assert( cmap_set );
+    assert( k == dst_xsize * dst_ysize );
+  } else
+#endif
 
-        k = 0;
-        for( i = dst_yoff; i < dst_yoff + dst_ysize; i++ )
-        {
-            for( j = dst_xoff; j < dst_xoff + dst_xsize; j++ )
-            {
-                int	src_pixel, src_alpha, cmap_alpha, merged_alpha;
-
-                src_pixel = pabyRaw1[k];
-                src_alpha = pabyRawAlpha[k];
-                cmap_alpha = rb_cmap[3][src_pixel];
-
-                merged_alpha = (src_alpha * cmap_alpha) / 255;
-
-                if( merged_alpha < 2 )
-                    /* do nothing - transparent */;
-                else if( merged_alpha > 253 )
-                {
-                    RB_SET_PIXEL( rb, j, i, 
-                                  rb_cmap[0][src_pixel], 
-                                  rb_cmap[1][src_pixel], 
-                                  rb_cmap[2][src_pixel], 
-                                  cmap_alpha );
-                }
-                else
-                {
-                    RB_MIX_PIXEL( rb, j, i, 
-                                  rb_cmap[0][src_pixel], 
-                                  rb_cmap[1][src_pixel], 
-                                  rb_cmap[2][src_pixel], 
-                                  merged_alpha );
-                }
-                k++;
-            }
+    /* -------------------------------------------------------------------- */
+    /*      Single band plus colormap and alpha to truecolor. (RB)          */
+    /* -------------------------------------------------------------------- */
+    if( hBand2 == NULL && rb->type == MS_BUFFER_BYTE_RGBA && hBandAlpha != NULL ) {
+      assert( cmap_set );
+
+      k = 0;
+      for( i = dst_yoff; i < dst_yoff + dst_ysize; i++ ) {
+        for( j = dst_xoff; j < dst_xoff + dst_xsize; j++ ) {
+          int src_pixel, src_alpha, cmap_alpha, merged_alpha;
+
+          src_pixel = pabyRaw1[k];
+          src_alpha = pabyRawAlpha[k];
+          cmap_alpha = rb_cmap[3][src_pixel];
+
+          merged_alpha = (src_alpha * cmap_alpha) / 255;
+
+          if( merged_alpha < 2 )
+            /* do nothing - transparent */;
+          else if( merged_alpha > 253 ) {
+            RB_SET_PIXEL( rb, j, i,
+                          rb_cmap[0][src_pixel],
+                          rb_cmap[1][src_pixel],
+                          rb_cmap[2][src_pixel],
+                          cmap_alpha );
+          } else {
+            RB_MIX_PIXEL( rb, j, i,
+                          rb_cmap[0][src_pixel],
+                          rb_cmap[1][src_pixel],
+                          rb_cmap[2][src_pixel],
+                          merged_alpha );
+          }
+          k++;
         }
-    }
+      }
+    }
+
+  /* -------------------------------------------------------------------- */
+  /*      Single band plus colormap (no alpha) to truecolor (RB)          */
+  /* -------------------------------------------------------------------- */
+    else if( hBand2 == NULL && rb->type == MS_BUFFER_BYTE_RGBA ) {
+      assert( cmap_set );
+
+      k = 0;
+      for( i = dst_yoff; i < dst_yoff + dst_ysize; i++ ) {
+        for( j = dst_xoff; j < dst_xoff + dst_xsize; j++ ) {
+          int src_pixel = pabyRaw1[k++];
+
+          if( rb_cmap[3][src_pixel] > 253 ) {
+            RB_SET_PIXEL( rb, j, i,
+                          rb_cmap[0][src_pixel],
+                          rb_cmap[1][src_pixel],
+                          rb_cmap[2][src_pixel],
+                          rb_cmap[3][src_pixel] );
+          } else if( rb_cmap[3][src_pixel] > 1 ) {
+            RB_MIX_PIXEL( rb, j, i,
+                          rb_cmap[0][src_pixel],
+                          rb_cmap[1][src_pixel],
+                          rb_cmap[2][src_pixel],
+                          rb_cmap[3][src_pixel] );
+          }
+        }
+      }
+    }
+
+  /* -------------------------------------------------------------------- */
+  /*      Input is 3 band RGB.  Alpha blending is mixed into the loop     */
+  /*      since this case is less commonly used and has lots of other     */
+  /*      overhead. (RB)                                                  */
+  /* -------------------------------------------------------------------- */
+    else if( hBand3 != NULL && rb->type == MS_BUFFER_BYTE_RGBA ) {
+      k = 0;
+      for( i = dst_yoff; i < dst_yoff + dst_ysize; i++ ) {
+        for( j = dst_xoff; j < dst_xoff + dst_xsize; j++, k++ ) {
+          if( MS_VALID_COLOR( layer->offsite )
+              && pabyRaw1[k] == layer->offsite.red
+              && pabyRaw2[k] == layer->offsite.green
+              && pabyRaw3[k] == layer->offsite.blue )
+            continue;
 
-/* -------------------------------------------------------------------- */
-/*      Single band plus colormap (no alpha) to truecolor (RB)          */
-/* -------------------------------------------------------------------- */
-    else if( hBand2 == NULL && rb->type == MS_BUFFER_BYTE_RGBA )
-    {
-        assert( cmap_set );
+          if( bHaveRGBNoData
+              && pabyRaw1[k] == nNoData1
+              && pabyRaw2[k] == nNoData2
+              && pabyRaw3[k] == nNoData3 )
+            continue;
 
-        k = 0;
-        for( i = dst_yoff; i < dst_yoff + dst_ysize; i++ )
-        {
-            for( j = dst_xoff; j < dst_xoff + dst_xsize; j++ )
-            {
-                int src_pixel = pabyRaw1[k++];
-
-                if( rb_cmap[3][src_pixel] > 253 )
-                {
-                    RB_SET_PIXEL( rb, j, i, 
-                                  rb_cmap[0][src_pixel], 
-                                  rb_cmap[1][src_pixel], 
-                                  rb_cmap[2][src_pixel], 
-                                  rb_cmap[3][src_pixel] );
-                }                  
-                else if( rb_cmap[3][src_pixel] > 1 )
-                {
-                    RB_MIX_PIXEL( rb, j, i, 
-                                  rb_cmap[0][src_pixel], 
-                                  rb_cmap[1][src_pixel], 
-                                  rb_cmap[2][src_pixel], 
-                                  rb_cmap[3][src_pixel] );
-                }                  
-            }
+          if( pabyRawAlpha == NULL || pabyRawAlpha[k] == 255 ) {
+            RB_SET_PIXEL( rb, j, i,
+                          pabyRaw1[k],
+                          pabyRaw2[k],
+                          pabyRaw3[k],
+                          255 );
+          } else if( pabyRawAlpha[k] != 0 ) {
+            RB_MIX_PIXEL( rb, j, i,
+                          pabyRaw1[k],
+                          pabyRaw2[k],
+                          pabyRaw3[k],
+                          pabyRawAlpha[k] );
+          }
+        }
+      }
+    }
+
+#ifdef USE_GD
+  /* -------------------------------------------------------------------- */
+  /*      Input is 3 band RGB.  Alpha blending is mixed into the loop     */
+  /*      since this case is less commonly used and has lots of other     */
+  /*      overhead. (GD)                                                  */
+  /* -------------------------------------------------------------------- */
+    else if( hBand3 != NULL && rb->type == MS_BUFFER_GD ) {
+      /* Dithered 24bit to 8bit conversion */
+      if( CSLFetchBoolean( layer->processing, "DITHER", FALSE ) ) {
+        unsigned char *pabyDithered;
+
+        pabyDithered = (unsigned char *) malloc(dst_xsize * dst_ysize);
+        if( pabyDithered == NULL ) {
+          msSetError(MS_MEMERR, "Allocating work image of size %dx%d failed.",
+                     "msDrawRasterLayerGDAL()", dst_xsize, dst_ysize );
+          return -1;
         }
-    }
 
-/* -------------------------------------------------------------------- */
-/*      Input is 3 band RGB.  Alpha blending is mixed into the loop     */
-/*      since this case is less commonly used and has lots of other     */
-/*      overhead. (RB)                                                  */
-/* -------------------------------------------------------------------- */
-    else if( hBand3 != NULL && rb->type == MS_BUFFER_BYTE_RGBA )
-    {
+        Dither24to8( pabyRaw1, pabyRaw2, pabyRaw3, pabyDithered,
+                     dst_xsize, dst_ysize, image->format->transparent,
+                     map->imagecolor, rb->data.gd_img );
+
         k = 0;
-        for( i = dst_yoff; i < dst_yoff + dst_ysize; i++ )
-        {
-            for( j = dst_xoff; j < dst_xoff + dst_xsize; j++, k++ )
-            {
-                if( MS_VALID_COLOR( layer->offsite )
-                    && pabyRaw1[k] == layer->offsite.red
-                    && pabyRaw2[k] == layer->offsite.green
-                    && pabyRaw3[k] == layer->offsite.blue )
-                    continue;
-
-                if( bHaveRGBNoData 
-                    && pabyRaw1[k] == nNoData1 
-                    && pabyRaw2[k] == nNoData2 
-                    && pabyRaw3[k] == nNoData3 )
-                    continue;
-
-                if( pabyRawAlpha == NULL || pabyRawAlpha[k] == 255 )
-                {
-                    RB_SET_PIXEL( rb, j, i, 
-                                  pabyRaw1[k],
-                                  pabyRaw2[k],
-                                  pabyRaw3[k],
-                                  255 );
-                }
-                else if( pabyRawAlpha[k] != 0 )
-                {
-                    RB_MIX_PIXEL( rb, j, i, 
-                                  pabyRaw1[k],
-                                  pabyRaw2[k],
-                                  pabyRaw3[k],
-                                  pabyRawAlpha[k] );
-                }
-            }
+        for( i = dst_yoff; i < dst_yoff + dst_ysize; i++ ) {
+          for( j = dst_xoff; j < dst_xoff + dst_xsize; j++, k++ ) {
+            if( MS_VALID_COLOR( layer->offsite )
+                && pabyRaw1[k] == layer->offsite.red
+                && pabyRaw2[k] == layer->offsite.green
+                && pabyRaw3[k] == layer->offsite.blue )
+              continue;
+
+            if( bHaveRGBNoData
+                && pabyRaw1[k] == nNoData1
+                && pabyRaw2[k] == nNoData2
+                && pabyRaw3[k] == nNoData3 )
+              continue;
+
+            if( pabyRawAlpha != NULL && pabyRawAlpha[k] == 0 )
+              continue;
+
+            rb->data.gd_img->pixels[i][j] = pabyDithered[k];
+          }
         }
-    }
 
-/* -------------------------------------------------------------------- */
-/*      Input is 3 band RGB.  Alpha blending is mixed into the loop     */
-/*      since this case is less commonly used and has lots of other     */
-/*      overhead. (GD)                                                  */
-/* -------------------------------------------------------------------- */
-    else if( hBand3 != NULL && rb->type == MS_BUFFER_GD )
-    {
-        /* Dithered 24bit to 8bit conversion */
-        if( CSLFetchBoolean( layer->processing, "DITHER", FALSE ) )
-        {
-#ifdef ENABLE_DITHER
-            unsigned char *pabyDithered;
-
-            pabyDithered = (unsigned char *) malloc(dst_xsize * dst_ysize);
-            if( pabyDithered == NULL )
-            {
-                msSetError(MS_MEMERR, "Allocating work image of size %dx%d failed.",
-                           "msDrawRasterLayerGDAL()", dst_xsize, dst_ysize );
-                return -1;
-            }
-          
-            Dither24to8( pabyRaw1, pabyRaw2, pabyRaw3, pabyDithered,
-                         dst_xsize, dst_ysize, image->format->transparent, 
-                         map->imagecolor, rb->data.gd_img );
-
-            k = 0;
-            for( i = dst_yoff; i < dst_yoff + dst_ysize; i++ )
-            {
-                for( j = dst_xoff; j < dst_xoff + dst_xsize; j++, k++ )
-                {
-                    if( MS_VALID_COLOR( layer->offsite )
-                        && pabyRaw1[k] == layer->offsite.red
-                        && pabyRaw2[k] == layer->offsite.green
-                        && pabyRaw3[k] == layer->offsite.blue )
-                        continue;
-
-                    if( bHaveRGBNoData 
-                        && pabyRaw1[k] == nNoData1 
-                        && pabyRaw2[k] == nNoData2 
-                        && pabyRaw3[k] == nNoData3 )
-                        continue;
-
-                    if( pabyRawAlpha != NULL && pabyRawAlpha[k] == 0 )
-                        continue;
-
-                    rb->data.gd_img->pixels[i][j] = pabyDithered[k];
-                }
-            }
-          
-            free( pabyDithered );
-#else
-            msSetError( MS_IMGERR, 
-                        "DITHER not supported in this build.  Update to latest GDAL, and define the ENABLE_DITHER macro.", "drawGDAL()" );
-            return -1;
-#endif 
-        }
+        free( pabyDithered );
+      }
 
-        /* Color cubed 24bit to 8bit conversion. */
-        else if( rb->type == MS_BUFFER_GD )
-        {
-            k = 0;
-            for( i = dst_yoff; i < dst_yoff + dst_ysize; i++ )
-            {
-                for( j = dst_xoff; j < dst_xoff + dst_xsize; j++, k++ )
-                {
-                    int	cc_index;
-                  
-                    if( MS_VALID_COLOR( layer->offsite )
-                        && pabyRaw1[k] == layer->offsite.red
-                        && pabyRaw2[k] == layer->offsite.green
-                        && pabyRaw3[k] == layer->offsite.blue )
-                        continue;
-                  
-                    if( bHaveRGBNoData 
-                        && pabyRaw1[k] == nNoData1 
-                        && pabyRaw2[k] == nNoData2 
-                        && pabyRaw3[k] == nNoData3 )
-                        continue;
-
-                    if( pabyRawAlpha != NULL && pabyRawAlpha[k] == 0 )
-                        continue;
-
-                    cc_index= RGB_INDEX(pabyRaw1[k],pabyRaw2[k],pabyRaw3[k]);
-                    rb->data.gd_img->pixels[i][j] = anColorCube[cc_index];
-                }
-            }
-        }
-        else {
-            msSetError(MS_MISCERR,"Unsupported raster configuration","msDrawRasterLayerGDAL()");
-            return MS_FAILURE;
+      /* Color cubed 24bit to 8bit conversion. */
+      else if( rb->type == MS_BUFFER_GD ) {
+        k = 0;
+        for( i = dst_yoff; i < dst_yoff + dst_ysize; i++ ) {
+          for( j = dst_xoff; j < dst_xoff + dst_xsize; j++, k++ ) {
+            int cc_index;
+
+            if( MS_VALID_COLOR( layer->offsite )
+                && pabyRaw1[k] == layer->offsite.red
+                && pabyRaw2[k] == layer->offsite.green
+                && pabyRaw3[k] == layer->offsite.blue )
+              continue;
+
+            if( bHaveRGBNoData
+                && pabyRaw1[k] == nNoData1
+                && pabyRaw2[k] == nNoData2
+                && pabyRaw3[k] == nNoData3 )
+              continue;
+
+            if( pabyRawAlpha != NULL && pabyRawAlpha[k] == 0 )
+              continue;
+
+            cc_index= RGB_INDEX(pabyRaw1[k],pabyRaw2[k],pabyRaw3[k]);
+            rb->data.gd_img->pixels[i][j] = anColorCube[cc_index];
+          }
         }
+      } else {
+        msSetError(MS_MISCERR,"Unsupported raster configuration","msDrawRasterLayerGDAL()");
+        return MS_FAILURE;
+      }
     }
+#endif
 
-    /*
-    ** Cleanup
-    */
+  /*
+  ** Cleanup
+  */
 
-    free( pabyRaw1 );
+  free( pabyRaw1 );
 
-    if( hColorMap != NULL )
-        GDALDestroyColorTable( hColorMap );
+  if( hColorMap != NULL )
+    GDALDestroyColorTable( hColorMap );
 
-    return 0;
+  return 0;
 }
 
 /************************************************************************/
@@ -1137,72 +1046,68 @@ int msDrawRasterLayerGDAL(mapObj *map, layerObj *layer, imageObj *image,
 static int ParseDefaultLUT( const char *lut_def, GByte *lut )
 
 {
-    const char *lut_read;
-    int last_in=0, last_out=0, all_done=FALSE;
-
-/* -------------------------------------------------------------------- */
-/*      Parse definition, applying to lut on the fly.                   */
-/* -------------------------------------------------------------------- */
-    lut_read = lut_def;
-    while( !all_done )
-    {
-        int this_in=0, this_out=0;
-        int lut_i;
-
-        while( isspace(*lut_read) )
-            lut_read++;
-
-        /* if we are at end, assum 255:255 */
-        if( *lut_read == '\0' )
-        {
-            all_done = TRUE;
-            if ( last_in != 255 ){
-            	this_in = 255;
-            	this_out = 255;
-            }
-        }
-
-        /* otherwise read "in:out", and skip past */
-        else
-        {
-            this_in = atoi(lut_read);
-            while( *lut_read != ':' && *lut_read )
-                lut_read++;
-            if( *lut_read == ':' )
-                lut_read++;
-            while( isspace(*lut_read) )
-                lut_read++;
-            this_out = atoi(lut_read);
-            while( *lut_read && *lut_read != ',' && *lut_read != '\n' )
-                lut_read++;
-            if( *lut_read == ',' || *lut_read == '\n' )
-                lut_read++;
-            while( isspace(*lut_read) )
-                lut_read++;
-        }
-
-        this_in = MAX(0,MIN(255,this_in));
-        this_out = MAX(0,MIN(255,this_out));
-
-        /* apply linear values from last in:out to this in:out */
-        for( lut_i = last_in; lut_i <= this_in; lut_i++ )
-        {
-            double ratio;
-
-            if( last_in == this_in )
-                ratio = 1.0;
-            else
-                ratio = (lut_i - last_in) / (double) (this_in - last_in);
-            
-            lut[lut_i] = (int) 
-                floor(((1.0 - ratio)*last_out + ratio*this_out) + 0.5);
-        }
-        
-        last_in = this_in;
-        last_out = this_out;
-    }
-
-    return 0;
+  const char *lut_read;
+  int last_in=0, last_out=0, all_done=FALSE;
+
+  /* -------------------------------------------------------------------- */
+  /*      Parse definition, applying to lut on the fly.                   */
+  /* -------------------------------------------------------------------- */
+  lut_read = lut_def;
+  while( !all_done ) {
+    int this_in=0, this_out=0;
+    int lut_i;
+
+    while( isspace(*lut_read) )
+      lut_read++;
+
+    /* if we are at end, assum 255:255 */
+    if( *lut_read == '\0' ) {
+      all_done = TRUE;
+      if ( last_in != 255 ) {
+        this_in = 255;
+        this_out = 255;
+      }
+    }
+
+    /* otherwise read "in:out", and skip past */
+    else {
+      this_in = atoi(lut_read);
+      while( *lut_read != ':' && *lut_read )
+        lut_read++;
+      if( *lut_read == ':' )
+        lut_read++;
+      while( isspace(*lut_read) )
+        lut_read++;
+      this_out = atoi(lut_read);
+      while( *lut_read && *lut_read != ',' && *lut_read != '\n' )
+        lut_read++;
+      if( *lut_read == ',' || *lut_read == '\n' )
+        lut_read++;
+      while( isspace(*lut_read) )
+        lut_read++;
+    }
+
+    this_in = MAX(0,MIN(255,this_in));
+    this_out = MAX(0,MIN(255,this_out));
+
+    /* apply linear values from last in:out to this in:out */
+    for( lut_i = last_in; lut_i <= this_in; lut_i++ ) {
+      double ratio;
+
+      if( last_in == this_in )
+        ratio = 1.0;
+      else
+        ratio = (lut_i - last_in) / (double) (this_in - last_in);
+
+      lut[lut_i] = (int)
+                   floor(((1.0 - ratio)*last_out + ratio*this_out) + 0.5);
+    }
+
+    last_in = this_in;
+    last_out = this_out;
+  }
+
+  return 0;
 }
 
 /************************************************************************/
@@ -1212,46 +1117,43 @@ static int ParseDefaultLUT( const char *lut_def, GByte *lut )
 static int LutFromGimpLine( char *lut_line, GByte *lut )
 
 {
-    char wrkLUTDef[1000];
-    int  i, count = 0;
-    char **tokens;
-
-    /* cleanup white space at end of line (DOS LF, etc) */
-    i = strlen(lut_line) - 1;
-    while( i > 0 && isspace(lut_line[i]) )
-        lut_line[i--] = '\0';
-
-    while( *lut_line == 10 || *lut_line == 13 )
-        lut_line++;
-    
-    /* tokenize line */
-    tokens = CSLTokenizeString( lut_line );
-    if( CSLCount(tokens) != 17 * 2 )
-    {
-        CSLDestroy( tokens );
-        msSetError(MS_MISCERR, 
-                   "GIMP curve file appears corrupt.", 
-                   "LutFromGimpLine()" );
-        return -1;
-    }
+  char wrkLUTDef[1000];
+  int  i, count = 0;
+  char **tokens;
 
-    /* Convert to our own format */
-    wrkLUTDef[0] = '\0';
-    for( i = 0; i < 17; i++ )
-    {
-        if( atoi(tokens[i*2]) >= 0 )
-        {
-            if( count++ > 0 )
-                strlcat( wrkLUTDef, ",", sizeof(wrkLUTDef));
+  /* cleanup white space at end of line (DOS LF, etc) */
+  i = strlen(lut_line) - 1;
+  while( i > 0 && isspace(lut_line[i]) )
+    lut_line[i--] = '\0';
 
-            snprintf( wrkLUTDef + strlen(wrkLUTDef), sizeof(wrkLUTDef)-strlen(wrkLUTDef), 
-                      "%s:%s", tokens[i*2], tokens[i*2+1] );
-        }
-    }
+  while( *lut_line == 10 || *lut_line == 13 )
+    lut_line++;
 
+  /* tokenize line */
+  tokens = CSLTokenizeString( lut_line );
+  if( CSLCount(tokens) != 17 * 2 ) {
     CSLDestroy( tokens );
+    msSetError(MS_MISCERR,
+               "GIMP curve file appears corrupt.",
+               "LutFromGimpLine()" );
+    return -1;
+  }
 
-    return ParseDefaultLUT( wrkLUTDef, lut );
+  /* Convert to our own format */
+  wrkLUTDef[0] = '\0';
+  for( i = 0; i < 17; i++ ) {
+    if( atoi(tokens[i*2]) >= 0 ) {
+      if( count++ > 0 )
+        strlcat( wrkLUTDef, ",", sizeof(wrkLUTDef));
+
+      snprintf( wrkLUTDef + strlen(wrkLUTDef), sizeof(wrkLUTDef)-strlen(wrkLUTDef),
+                "%s:%s", tokens[i*2], tokens[i*2+1] );
+    }
+  }
+
+  CSLDestroy( tokens );
+
+  return ParseDefaultLUT( wrkLUTDef, lut );
 }
 
 /************************************************************************/
@@ -1263,44 +1165,41 @@ static int LutFromGimpLine( char *lut_line, GByte *lut )
 static int ParseGimpLUT( const char *lut_def, GByte *lut, int iColorIndex )
 
 {
-    int i;
-    GByte lutValue[256];
-    GByte lutColorBand[256];
-    char **lines = 
-        CSLTokenizeStringComplex( lut_def, "\n", FALSE, FALSE );
-
-    if( !EQUALN(lines[0],"# GIMP Curves File",18) 
-        || CSLCount(lines) < 6 )
-    {
-        msSetError(MS_MISCERR, 
-                   "GIMP curve file appears corrupt.", 
-                   "ParseGimpLUT()" );
-        return -1;
-    }
+  int i;
+  GByte lutValue[256];
+  GByte lutColorBand[256];
+  char **lines =
+    CSLTokenizeStringComplex( lut_def, "\n", FALSE, FALSE );
+
+  if( !EQUALN(lines[0],"# GIMP Curves File",18)
+      || CSLCount(lines) < 6 ) {
+    msSetError(MS_MISCERR,
+               "GIMP curve file appears corrupt.",
+               "ParseGimpLUT()" );
+    return -1;
+  }
 
-    /*
-     * Convert the overall curve, and the color band specific curve into LUTs.
-     */
-    if( LutFromGimpLine( lines[1], lutValue ) != 0 
-        || LutFromGimpLine( lines[iColorIndex + 1], lutColorBand ) != 0 )
-    {
-        CSLDestroy( lines );
-        return -1;
-    }
+  /*
+   * Convert the overall curve, and the color band specific curve into LUTs.
+   */
+  if( LutFromGimpLine( lines[1], lutValue ) != 0
+      || LutFromGimpLine( lines[iColorIndex + 1], lutColorBand ) != 0 ) {
     CSLDestroy( lines );
+    return -1;
+  }
+  CSLDestroy( lines );
 
-    /*
-     * Compose the two luts as if the raw value passed through the color band
-     * specific lut, and then the general value lut.  Usually one or the
-     * other will be the identity mapping, but not always.
-     */
-    
-    for( i = 0; i < 256; i++ )
-    {
-        lut[i] = lutValue[lutColorBand[i]];
-    }
-    
-    return 0;
+  /*
+   * Compose the two luts as if the raw value passed through the color band
+   * specific lut, and then the general value lut.  Usually one or the
+   * other will be the identity mapping, but not always.
+   */
+
+  for( i = 0; i < 256; i++ ) {
+    lut[i] = lutValue[lutColorBand[i]];
+  }
+
+  return 0;
 }
 
 /************************************************************************/
@@ -1309,83 +1208,77 @@ static int ParseGimpLUT( const char *lut_def, GByte *lut, int iColorIndex )
 /*      Apply a LUT according to RFC 21.                                */
 /************************************************************************/
 
-static int ApplyLUT( int iColorIndex, layerObj *layer, 
+static int ApplyLUT( int iColorIndex, layerObj *layer,
                      GByte *buffer, int buf_xsize, int buf_ysize )
 
 {
-    const char *lut_def;
-    char key[20], lut_def_fromfile[2500];
-    GByte lut[256];
-    int   err, i;
-
-/* -------------------------------------------------------------------- */
-/*      Get lut specifier from processing directives.  Do nothing if    */
-/*      none are found.                                                 */
-/* -------------------------------------------------------------------- */
-    sprintf( key, "LUT_%d", iColorIndex );
-    lut_def = msLayerGetProcessingKey( layer, key );
-    if( lut_def == NULL )
-        lut_def = msLayerGetProcessingKey( layer, "LUT" );
-    if( lut_def == NULL )
-        return 0;
-
-/* -------------------------------------------------------------------- */
-/*      Does this look like a file?  If so, read it into memory.        */
-/* -------------------------------------------------------------------- */
-    if( strspn(lut_def,"0123456789:, ") != strlen(lut_def) )
-    {
-        FILE *fp;
-        char path[MS_MAXPATHLEN];
-        int len;
-        msBuildPath(path, layer->map->mappath, lut_def);
-        fp = fopen( path, "rb" );
-        if( fp == NULL )
-        {
-            msSetError(MS_IOERR, 
-                       "Failed to open LUT file '%s'.",
-                       "drawGDAL()", path );
-            return -1;
-        }
-        
-        len = fread( lut_def_fromfile, 1, sizeof(lut_def_fromfile), fp );
-        fclose( fp );
-
-        if( len == sizeof(lut_def_fromfile) )
-        {
-            msSetError(MS_IOERR, 
-                       "LUT definition from file %s longer than maximum buffer size (%d bytes).",
-                       "drawGDAL()", 
-                       path, sizeof(lut_def_fromfile) );
-            return -1;
-        }
-        
-        lut_def_fromfile[len] = '\0';
-
-        lut_def = lut_def_fromfile;
-    } 
-
-/* -------------------------------------------------------------------- */
-/*      Parse the LUT description.                                      */
-/* -------------------------------------------------------------------- */
-    if( EQUALN(lut_def,"# GIMP",6) )
-    {
-        err = ParseGimpLUT( lut_def, lut, iColorIndex );
-    }
-    else
-    {
-        err = ParseDefaultLUT( lut_def, lut );
-    }
-
-    if( err != 0 )
-        return err;
-
-/* -------------------------------------------------------------------- */
-/*      Apply LUT.                                                      */
-/* -------------------------------------------------------------------- */
-    for( i = buf_xsize * buf_ysize - 1; i >= 0; i-- )
-        buffer[i] = lut[buffer[i]];
-
+  const char *lut_def;
+  char key[20], lut_def_fromfile[2500];
+  GByte lut[256];
+  int   err, i;
+
+  /* -------------------------------------------------------------------- */
+  /*      Get lut specifier from processing directives.  Do nothing if    */
+  /*      none are found.                                                 */
+  /* -------------------------------------------------------------------- */
+  sprintf( key, "LUT_%d", iColorIndex );
+  lut_def = msLayerGetProcessingKey( layer, key );
+  if( lut_def == NULL )
+    lut_def = msLayerGetProcessingKey( layer, "LUT" );
+  if( lut_def == NULL )
     return 0;
+
+  /* -------------------------------------------------------------------- */
+  /*      Does this look like a file?  If so, read it into memory.        */
+  /* -------------------------------------------------------------------- */
+  if( strspn(lut_def,"0123456789:, ") != strlen(lut_def) ) {
+    FILE *fp;
+    char path[MS_MAXPATHLEN];
+    int len;
+    msBuildPath(path, layer->map->mappath, lut_def);
+    fp = fopen( path, "rb" );
+    if( fp == NULL ) {
+      msSetError(MS_IOERR,
+                 "Failed to open LUT file '%s'.",
+                 "drawGDAL()", path );
+      return -1;
+    }
+
+    len = fread( lut_def_fromfile, 1, sizeof(lut_def_fromfile), fp );
+    fclose( fp );
+
+    if( len == sizeof(lut_def_fromfile) ) {
+      msSetError(MS_IOERR,
+                 "LUT definition from file %s longer than maximum buffer size (%d bytes).",
+                 "drawGDAL()",
+                 path, sizeof(lut_def_fromfile) );
+      return -1;
+    }
+
+    lut_def_fromfile[len] = '\0';
+
+    lut_def = lut_def_fromfile;
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Parse the LUT description.                                      */
+  /* -------------------------------------------------------------------- */
+  if( EQUALN(lut_def,"# GIMP",6) ) {
+    err = ParseGimpLUT( lut_def, lut, iColorIndex );
+  } else {
+    err = ParseDefaultLUT( lut_def, lut );
+  }
+
+  if( err != 0 )
+    return err;
+
+  /* -------------------------------------------------------------------- */
+  /*      Apply LUT.                                                      */
+  /* -------------------------------------------------------------------- */
+  for( i = buf_xsize * buf_ysize - 1; i >= 0; i-- )
+    buffer[i] = lut[buffer[i]];
+
+  return 0;
 }
 
 /************************************************************************/
@@ -1398,264 +1291,246 @@ static int ApplyLUT( int iColorIndex, layerObj *layer,
 
 static int
 LoadGDALImages( GDALDatasetH hDS, int band_numbers[4], int band_count,
-		layerObj *layer, 
-		int src_xoff, int src_yoff, int src_xsize, int src_ysize, 
-		GByte *pabyWholeBuffer,
-		int dst_xsize, int dst_ysize,
-                int *pbHaveRGBNoData, 
+                layerObj *layer,
+                int src_xoff, int src_yoff, int src_xsize, int src_ysize,
+                GByte *pabyWholeBuffer,
+                int dst_xsize, int dst_ysize,
+                int *pbHaveRGBNoData,
                 int *pnNoData1, int *pnNoData2, int *pnNoData3 )
-    
+
 {
-    int    iColorIndex, result_code=0;
-    CPLErr eErr;
-    float *pafWholeRawData;
-
-/* -------------------------------------------------------------------- */
-/*      If we have no alpha band, but we do have three input            */
-/*      bands, then check for nodata values.  If we only have one       */
-/*      input band, then nodata will already have been adderssed as     */
-/*      part of the real or manufactured color table.                   */
-/* -------------------------------------------------------------------- */
-    if( band_count == 3 )
-    {
-        *pnNoData1 = (int) 
-            msGetGDALNoDataValue( layer, 
-                                  GDALGetRasterBand(hDS,band_numbers[0]), 
-                                  pbHaveRGBNoData);
-
-        if( *pbHaveRGBNoData )
-            *pnNoData2 = (int) 
-                msGetGDALNoDataValue( layer, 
-                                  GDALGetRasterBand(hDS,band_numbers[1]), 
-                                  pbHaveRGBNoData);
-        if( *pbHaveRGBNoData )
-            *pnNoData3 = (int) 
-                msGetGDALNoDataValue( layer, 
-                                  GDALGetRasterBand(hDS,band_numbers[2]), 
-                                  pbHaveRGBNoData);
+  int    iColorIndex, result_code=0;
+  CPLErr eErr;
+  float *pafWholeRawData;
+
+  /* -------------------------------------------------------------------- */
+  /*      If we have no alpha band, but we do have three input            */
+  /*      bands, then check for nodata values.  If we only have one       */
+  /*      input band, then nodata will already have been adderssed as     */
+  /*      part of the real or manufactured color table.                   */
+  /* -------------------------------------------------------------------- */
+  if( band_count == 3 ) {
+    *pnNoData1 = (int)
+                 msGetGDALNoDataValue( layer,
+                                       GDALGetRasterBand(hDS,band_numbers[0]),
+                                       pbHaveRGBNoData);
+
+    if( *pbHaveRGBNoData )
+      *pnNoData2 = (int)
+                   msGetGDALNoDataValue( layer,
+                                         GDALGetRasterBand(hDS,band_numbers[1]),
+                                         pbHaveRGBNoData);
+    if( *pbHaveRGBNoData )
+      *pnNoData3 = (int)
+                   msGetGDALNoDataValue( layer,
+                                         GDALGetRasterBand(hDS,band_numbers[2]),
+                                         pbHaveRGBNoData);
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Are we doing a simple, non-scaling case?  If so, read directly  */
+  /*      and return.                                                     */
+  /* -------------------------------------------------------------------- */
+  if( CSLFetchNameValue( layer->processing, "SCALE" ) == NULL
+      && CSLFetchNameValue( layer->processing, "SCALE_1" ) == NULL
+      && CSLFetchNameValue( layer->processing, "SCALE_2" ) == NULL
+      && CSLFetchNameValue( layer->processing, "SCALE_3" ) == NULL
+      && CSLFetchNameValue( layer->processing, "SCALE_4" ) == NULL ) {
+    eErr = GDALDatasetRasterIO( hDS, GF_Read,
+                                src_xoff, src_yoff, src_xsize, src_ysize,
+                                pabyWholeBuffer,
+                                dst_xsize, dst_ysize, GDT_Byte,
+                                band_count, band_numbers,
+                                0,0,0);
+
+    if( eErr != CE_None ) {
+      msSetError( MS_IOERR,
+                  "GDALDatasetRasterIO() failed: %s",
+                  "drawGDAL()",
+                  CPLGetLastErrorMsg() );
+      return -1;
+    }
+
+    for( iColorIndex = 0;
+         iColorIndex < band_count && result_code == 0; iColorIndex++ ) {
+      result_code = ApplyLUT( iColorIndex+1, layer,
+                              pabyWholeBuffer
+                              + dst_xsize*dst_ysize*iColorIndex,
+                              dst_xsize, dst_ysize );
     }
 
-/* -------------------------------------------------------------------- */
-/*      Are we doing a simple, non-scaling case?  If so, read directly  */
-/*      and return.                                                     */
-/* -------------------------------------------------------------------- */
-    if( CSLFetchNameValue( layer->processing, "SCALE" ) == NULL
-	&& CSLFetchNameValue( layer->processing, "SCALE_1" ) == NULL
-	&& CSLFetchNameValue( layer->processing, "SCALE_2" ) == NULL
-	&& CSLFetchNameValue( layer->processing, "SCALE_3" ) == NULL
-	&& CSLFetchNameValue( layer->processing, "SCALE_4" ) == NULL )
-    {
-        eErr = GDALDatasetRasterIO( hDS, GF_Read, 
-				    src_xoff, src_yoff, src_xsize, src_ysize, 
-				    pabyWholeBuffer, 
-				    dst_xsize, dst_ysize, GDT_Byte,
-				    band_count, band_numbers,
-				    0,0,0);
-
-        if( eErr != CE_None )
-	{
-            msSetError( MS_IOERR, 
-                        "GDALDatasetRasterIO() failed: %s", 
-                        "drawGDAL()",
-                        CPLGetLastErrorMsg() );
-	    return -1;
-	}
-
-	for( iColorIndex = 0; 
-	     iColorIndex < band_count && result_code == 0; iColorIndex++ )
-	{
-	    result_code = ApplyLUT( iColorIndex+1, layer, 
-				    pabyWholeBuffer 
-				    + dst_xsize*dst_ysize*iColorIndex, 
-				    dst_xsize, dst_ysize );
-	}
-	
-	return result_code;
-    }
+    return result_code;
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Disable use of nodata if we are doing scaling.                  */
+  /* -------------------------------------------------------------------- */
+  *pbHaveRGBNoData = FALSE;
+
+  /* -------------------------------------------------------------------- */
+  /*      We need to do some scaling.  Will load into either a 16bit      */
+  /*      unsigned or a floating point buffer depending on the source     */
+  /*      data.  We offer a special case for 16U data because it is       */
+  /*      common and it is a substantial win to avoid alot of floating    */
+  /*      point operations on it.                                         */
+  /* -------------------------------------------------------------------- */
+  /* TODO */
+
+  /* -------------------------------------------------------------------- */
+  /*      Allocate the raw imagery buffer, and load into it (band         */
+  /*      interleaved).                                                   */
+  /* -------------------------------------------------------------------- */
+  pafWholeRawData =
+    (float *) malloc(sizeof(float) * dst_xsize * dst_ysize * band_count );
+
+  if( pafWholeRawData == NULL ) {
+    msSetError(MS_MEMERR,
+               "Allocating work float image of size %dx%dx%d failed.",
+               "msDrawRasterLayerGDAL()",
+               dst_xsize, dst_ysize, band_count );
+    return -1;
+  }
 
-/* -------------------------------------------------------------------- */
-/*      Disable use of nodata if we are doing scaling.                  */
-/* -------------------------------------------------------------------- */
-    *pbHaveRGBNoData = FALSE;
-
-/* -------------------------------------------------------------------- */
-/*      We need to do some scaling.  Will load into either a 16bit      */
-/*      unsigned or a floating point buffer depending on the source     */
-/*      data.  We offer a special case for 16U data because it is       */
-/*      common and it is a substantial win to avoid alot of floating    */
-/*      point operations on it.                                         */
-/* -------------------------------------------------------------------- */
-    /* TODO */
-
-/* -------------------------------------------------------------------- */
-/*      Allocate the raw imagery buffer, and load into it (band         */
-/*      interleaved).                                                   */
-/* -------------------------------------------------------------------- */
-    pafWholeRawData = 
-        (float *) malloc(sizeof(float) * dst_xsize * dst_ysize * band_count );
-
-    if( pafWholeRawData == NULL )
-    {
-        msSetError(MS_MEMERR, 
-                   "Allocating work float image of size %dx%dx%d failed.",
-                   "msDrawRasterLayerGDAL()", 
-                   dst_xsize, dst_ysize, band_count );
-        return -1;
+  eErr = GDALDatasetRasterIO(
+           hDS, GF_Read,
+           src_xoff, src_yoff, src_xsize, src_ysize,
+           pafWholeRawData, dst_xsize, dst_ysize, GDT_Float32,
+           band_count, band_numbers,
+           0, 0, 0 );
+
+  if( eErr != CE_None ) {
+    msSetError( MS_IOERR, "GDALDatasetRasterIO() failed: %s",
+                "drawGDAL()",
+                CPLGetLastErrorMsg() );
+
+    free( pafWholeRawData );
+    return -1;
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Fetch the scale processing option.                              */
+  /* -------------------------------------------------------------------- */
+  for( iColorIndex = 0; iColorIndex < band_count; iColorIndex++ ) {
+    unsigned char *pabyBuffer;
+    double dfScaleMin=0.0, dfScaleMax=255.0, dfScaleRatio, dfNoDataValue;
+    const char *pszScaleInfo;
+    float *pafRawData;
+    int   nPixelCount = dst_xsize * dst_ysize, i, bGotNoData = FALSE;
+    GDALRasterBandH hBand =GDALGetRasterBand(hDS,band_numbers[iColorIndex]);
+    pszScaleInfo = CSLFetchNameValue( layer->processing, "SCALE" );
+    if( pszScaleInfo == NULL ) {
+      char szBandScalingName[20];
+
+      sprintf( szBandScalingName, "SCALE_%d", iColorIndex+1 );
+      pszScaleInfo = CSLFetchNameValue( layer->processing,
+                                        szBandScalingName);
     }
-	
-    eErr = GDALDatasetRasterIO( 
-        hDS, GF_Read, 
-        src_xoff, src_yoff, src_xsize, src_ysize, 
-        pafWholeRawData, dst_xsize, dst_ysize, GDT_Float32, 
-        band_count, band_numbers,
-        0, 0, 0 );
-    
-    if( eErr != CE_None )
-    {
-        msSetError( MS_IOERR, "GDALDatasetRasterIO() failed: %s", 
-                    "drawGDAL()",
-                    CPLGetLastErrorMsg() );
-        
+
+    if( pszScaleInfo != NULL ) {
+      char **papszTokens;
+
+      papszTokens = CSLTokenizeStringComplex( pszScaleInfo, " ,",
+                                              FALSE, FALSE );
+      if( CSLCount(papszTokens) == 1
+          && EQUAL(papszTokens[0],"AUTO") ) {
+        dfScaleMin = dfScaleMax = 0.0;
+      } else if( CSLCount(papszTokens) != 2 ) {
         free( pafWholeRawData );
+        msSetError( MS_MISCERR,
+                    "SCALE PROCESSING option unparsable for layer %s.",
+                    "msDrawGDAL()",
+                    layer->name );
         return -1;
+      } else {
+        dfScaleMin = atof(papszTokens[0]);
+        dfScaleMax = atof(papszTokens[1]);
+      }
+      CSLDestroy( papszTokens );
     }
 
-/* -------------------------------------------------------------------- */
-/*      Fetch the scale processing option.                              */
-/* -------------------------------------------------------------------- */
-    for( iColorIndex = 0; iColorIndex < band_count; iColorIndex++ )
-    {
-	unsigned char *pabyBuffer;
-	double dfScaleMin=0.0, dfScaleMax=255.0, dfScaleRatio, dfNoDataValue;
-	const char *pszScaleInfo;
-	float *pafRawData;
-	int   nPixelCount = dst_xsize * dst_ysize, i, bGotNoData = FALSE;
-	GDALRasterBandH hBand =GDALGetRasterBand(hDS,band_numbers[iColorIndex]);
-	pszScaleInfo = CSLFetchNameValue( layer->processing, "SCALE" );
-	if( pszScaleInfo == NULL )
-        {
-	    char szBandScalingName[20];
-	    
-	    sprintf( szBandScalingName, "SCALE_%d", iColorIndex+1 );
-	    pszScaleInfo = CSLFetchNameValue( layer->processing, 
-					      szBandScalingName);
-        }
-	
-	if( pszScaleInfo != NULL )
-        {
-	    char **papszTokens;
-	    
-	    papszTokens = CSLTokenizeStringComplex( pszScaleInfo, " ,", 
-						    FALSE, FALSE );
-	    if( CSLCount(papszTokens) == 1
-		&& EQUAL(papszTokens[0],"AUTO") )
-            {
-		dfScaleMin = dfScaleMax = 0.0;
-            }
-	    else if( CSLCount(papszTokens) != 2 )
-            {
-                free( pafWholeRawData );
-		msSetError( MS_MISCERR, 
-			    "SCALE PROCESSING option unparsable for layer %s.",
-                            "msDrawGDAL()",
-			    layer->name );
-		return -1;
-            }
-	    else
-            {
-		dfScaleMin = atof(papszTokens[0]);
-		dfScaleMax = atof(papszTokens[1]);
-            }
-	    CSLDestroy( papszTokens );
-        }
-    
-/* -------------------------------------------------------------------- */
-/*      If we are using autoscaling, then compute the max and min       */
-/*      now.  Perhaps we should eventually honour the offsite value     */
-/*      as a nodata value, or get it from GDAL.                         */
-/* -------------------------------------------------------------------- */
-	pafRawData = pafWholeRawData + iColorIndex * dst_xsize * dst_ysize;
-
-        dfNoDataValue = msGetGDALNoDataValue( layer, hBand, &bGotNoData );
-
-	if( dfScaleMin == dfScaleMax )
-        {
-            int bMinMaxSet = 0;
-            
-            /* we force assignment to a float rather than letting pafRawData[i]
-               get promoted to double later to avoid float precision issues. */
-            float fNoDataValue = (float) dfNoDataValue; 
-
-	    for( i = 0; i < nPixelCount; i++ )
-            {
-                if( bGotNoData && pafRawData[i] == fNoDataValue )
-                    continue;
-
-                if( !bMinMaxSet )
-                {
-                    dfScaleMin = dfScaleMax = pafRawData[i];
-                    bMinMaxSet = TRUE;
-                }
-
-		dfScaleMin = MIN(dfScaleMin,pafRawData[i]);
-		dfScaleMax = MAX(dfScaleMax,pafRawData[i]);
-            }
+    /* -------------------------------------------------------------------- */
+    /*      If we are using autoscaling, then compute the max and min       */
+    /*      now.  Perhaps we should eventually honour the offsite value     */
+    /*      as a nodata value, or get it from GDAL.                         */
+    /* -------------------------------------------------------------------- */
+    pafRawData = pafWholeRawData + iColorIndex * dst_xsize * dst_ysize;
 
-	    if( dfScaleMin == dfScaleMax )
-                dfScaleMax = dfScaleMin + 1.0;
-        }
-	
-	if( layer->debug > 0 )
-            msDebug( "msDrawGDAL(%s): scaling to 8bit, src range=%g,%g\n",
-                     layer->name, dfScaleMin, dfScaleMax );
-	
-/* -------------------------------------------------------------------- */
-/*      Now process the data.                                           */
-/* -------------------------------------------------------------------- */
-	dfScaleRatio = 256.0 / (dfScaleMax - dfScaleMin);
-	pabyBuffer = pabyWholeBuffer + iColorIndex * nPixelCount;
-
-	for( i = 0; i < nPixelCount; i++ )
-        {
-	    float fScaledValue = (float) ((pafRawData[i]-dfScaleMin)*dfScaleRatio);
-	    
-	    if( fScaledValue < 0.0 )
-                pabyBuffer[i] = 0;
-	    else if( fScaledValue > 255.0 )
-                pabyBuffer[i] = 255;
-	    else
-                pabyBuffer[i] = (int) fScaledValue;
-        }
-	
-/* -------------------------------------------------------------------- */
-/*      Report a warning if NODATA keyword was applied.  We are         */
-/*      unable to utilize it since we can't return any pixels marked    */
-/*      as nodata from this function.  Need to fix someday.             */
-/* -------------------------------------------------------------------- */
-	if( bGotNoData )
-            msDebug( "LoadGDALImage(%s): NODATA value %g in GDAL\n"
-                     "file or PROCESSING directive largely ignored.  Not yet fully supported for\n"
-                     "unclassified scaled data.  The NODATA value is excluded from auto-scaling\n"
-                     "min/max computation, but will not be transparent.\n",
-                     layer->name, dfNoDataValue );
-	
-/* -------------------------------------------------------------------- */
-/*      Apply LUT if there is one.                                      */
-/* -------------------------------------------------------------------- */
-	result_code = ApplyLUT( iColorIndex+1, layer, 
-				pabyBuffer, dst_xsize, dst_ysize );;
-	if( result_code == -1 )
-        {
-            free( pafWholeRawData );
-            return result_code;
+    dfNoDataValue = msGetGDALNoDataValue( layer, hBand, &bGotNoData );
+
+    if( dfScaleMin == dfScaleMax ) {
+      int bMinMaxSet = 0;
+
+      /* we force assignment to a float rather than letting pafRawData[i]
+         get promoted to double later to avoid float precision issues. */
+      float fNoDataValue = (float) dfNoDataValue;
+
+      for( i = 0; i < nPixelCount; i++ ) {
+        if( bGotNoData && pafRawData[i] == fNoDataValue )
+          continue;
+
+        if( !bMinMaxSet ) {
+          dfScaleMin = dfScaleMax = pafRawData[i];
+          bMinMaxSet = TRUE;
         }
-    }
 
-    free( pafWholeRawData );
+        dfScaleMin = MIN(dfScaleMin,pafRawData[i]);
+        dfScaleMax = MAX(dfScaleMax,pafRawData[i]);
+      }
 
-    return result_code;
+      if( dfScaleMin == dfScaleMax )
+        dfScaleMax = dfScaleMin + 1.0;
+    }
+
+    if( layer->debug > 0 )
+      msDebug( "msDrawGDAL(%s): scaling to 8bit, src range=%g,%g\n",
+               layer->name, dfScaleMin, dfScaleMax );
+
+    /* -------------------------------------------------------------------- */
+    /*      Now process the data.                                           */
+    /* -------------------------------------------------------------------- */
+    dfScaleRatio = 256.0 / (dfScaleMax - dfScaleMin);
+    pabyBuffer = pabyWholeBuffer + iColorIndex * nPixelCount;
+
+    for( i = 0; i < nPixelCount; i++ ) {
+      float fScaledValue = (float) ((pafRawData[i]-dfScaleMin)*dfScaleRatio);
+
+      if( fScaledValue < 0.0 )
+        pabyBuffer[i] = 0;
+      else if( fScaledValue > 255.0 )
+        pabyBuffer[i] = 255;
+      else
+        pabyBuffer[i] = (int) fScaledValue;
+    }
+
+    /* -------------------------------------------------------------------- */
+    /*      Report a warning if NODATA keyword was applied.  We are         */
+    /*      unable to utilize it since we can't return any pixels marked    */
+    /*      as nodata from this function.  Need to fix someday.             */
+    /* -------------------------------------------------------------------- */
+    if( bGotNoData )
+      msDebug( "LoadGDALImage(%s): NODATA value %g in GDAL\n"
+               "file or PROCESSING directive largely ignored.  Not yet fully supported for\n"
+               "unclassified scaled data.  The NODATA value is excluded from auto-scaling\n"
+               "min/max computation, but will not be transparent.\n",
+               layer->name, dfNoDataValue );
+
+    /* -------------------------------------------------------------------- */
+    /*      Apply LUT if there is one.                                      */
+    /* -------------------------------------------------------------------- */
+    result_code = ApplyLUT( iColorIndex+1, layer,
+                            pabyBuffer, dst_xsize, dst_ysize );;
+    if( result_code == -1 ) {
+      free( pafWholeRawData );
+      return result_code;
+    }
+  }
+
+  free( pafWholeRawData );
+
+  return result_code;
 }
 
+#ifdef USE_GD
 /************************************************************************/
 /*                           allocColorCube()                           */
 /*                                                                      */
@@ -1666,44 +1541,39 @@ LoadGDALImages( GDALDatasetH hDS, int band_numbers[4], int band_count,
 static int allocColorCube(mapObj *map, gdImagePtr img, int *panColorCube)
 
 {
-    int	 r, g, b;
-    int i = 0;
-    int nGreyColors = 32;
-    int nSpaceGreyColors = 8;
-    int iColors = 0;
-    int	red, green, blue;
-
-    for( r = 0; r < RED_LEVELS; r++ )
-    {
-        for( g = 0; g < GREEN_LEVELS; g++ )
-        {
-            for( b = 0; b < BLUE_LEVELS; b++ )
-            {                
-                red = MS_MIN(255,r * (255 / (RED_LEVELS-1)));
-                green = MS_MIN(255,g * (255 / (GREEN_LEVELS-1)));
-                blue = MS_MIN(255,b * (255 / (BLUE_LEVELS-1)));
-
-                panColorCube[RGB_LEVEL_INDEX(r,g,b)] = 
-                    msAddColorGD(map, img, 1, red, green, blue );
-                iColors++;
-            }
-        }
-    }
-/* -------------------------------------------------------------------- */
-/*      Adding 32 grey colors                                           */
-/* -------------------------------------------------------------------- */
-    for (i=0; i<nGreyColors; i++)
-    {
-        red = i*nSpaceGreyColors;
-        green = red;
-        blue = red;
-        if(iColors < 256)
-        {
-            panColorCube[iColors] = msAddColorGD(map,img,1,red,green,blue);
-            iColors++;
-        }
-    }
-    return MS_SUCCESS;
+  int  r, g, b;
+  int i = 0;
+  int nGreyColors = 32;
+  int nSpaceGreyColors = 8;
+  int iColors = 0;
+  int red, green, blue;
+
+  for( r = 0; r < RED_LEVELS; r++ ) {
+    for( g = 0; g < GREEN_LEVELS; g++ ) {
+      for( b = 0; b < BLUE_LEVELS; b++ ) {
+        red = MS_MIN(255,r * (255 / (RED_LEVELS-1)));
+        green = MS_MIN(255,g * (255 / (GREEN_LEVELS-1)));
+        blue = MS_MIN(255,b * (255 / (BLUE_LEVELS-1)));
+
+        panColorCube[RGB_LEVEL_INDEX(r,g,b)] =
+          msAddColorGD(map, img, 1, red, green, blue );
+        iColors++;
+      }
+    }
+  }
+  /* -------------------------------------------------------------------- */
+  /*      Adding 32 grey colors                                           */
+  /* -------------------------------------------------------------------- */
+  for (i=0; i<nGreyColors; i++) {
+    red = i*nSpaceGreyColors;
+    green = red;
+    blue = red;
+    if(iColors < 256) {
+      panColorCube[iColors] = msAddColorGD(map,img,1,red,green,blue);
+      iColors++;
+    }
+  }
+  return MS_SUCCESS;
 }
 
 /************************************************************************/
@@ -1712,116 +1582,100 @@ static int allocColorCube(mapObj *map, gdImagePtr img, int *panColorCube)
 /*      Wrapper for GDAL dithering algorithm.                           */
 /************************************************************************/
 
-#ifdef ENABLE_DITHER
-
-#if GDAL_VERSION_NUM <= 1240 
-static int CPLPrintPointer( char *buffer, void *pData, int nMax )
-
-{
-#ifdef WIN32
-    sprintf( buffer, "%ld", (long) pData );
-#else
-    sprintf( buffer, "%p", pData );
-#endif
-
-    return strlen( buffer );
-}
-#endif /* GDAL_VERSION_NUM <= 1240 */
-
 static void Dither24to8( GByte *pabyRed, GByte *pabyGreen, GByte *pabyBlue,
-                         GByte *pabyDithered, int xsize, int ysize, 
+                         GByte *pabyDithered, int xsize, int ysize,
                          int bTransparent, colorObj transparent,
                          gdImagePtr gdImg )
 
 {
-    GDALDatasetH hDS;
-    GDALDriverH  hDriver;
-    char **papszBandOptions = NULL;
-    char szDataPointer[120];
-    GDALColorTableH hCT;
-    int c;
-
-/* -------------------------------------------------------------------- */
-/*      Create the "memory" GDAL dataset referencing our working        */
-/*      arrays.                                                         */
-/* -------------------------------------------------------------------- */
-    hDriver = GDALGetDriverByName( "MEM" );
-    if( hDriver == NULL )
-        return;
-
-    hDS = GDALCreate( hDriver, "TempDitherDS", xsize, ysize, 0, GDT_Byte, 
-                      NULL );
-
-    /* Add Red Band */
-    memset( szDataPointer, 0, sizeof(szDataPointer) );
-    CPLPrintPointer( szDataPointer, pabyRed, sizeof(szDataPointer) );
-    papszBandOptions = CSLSetNameValue( papszBandOptions, "DATAPOINTER", 
-                                        szDataPointer );
-    GDALAddBand( hDS, GDT_Byte, papszBandOptions );
-                                        
-    /* Add Green Band */
-    memset( szDataPointer, 0, sizeof(szDataPointer) );
-    CPLPrintPointer( szDataPointer, pabyGreen, sizeof(szDataPointer) );
-    papszBandOptions = CSLSetNameValue( papszBandOptions, "DATAPOINTER", 
-                                        szDataPointer );
-    GDALAddBand( hDS, GDT_Byte, papszBandOptions );
-                                        
-    /* Add Blue Band */
-    memset( szDataPointer, 0, sizeof(szDataPointer) );
-    CPLPrintPointer( szDataPointer, pabyBlue, sizeof(szDataPointer) );
-    papszBandOptions = CSLSetNameValue( papszBandOptions, "DATAPOINTER", 
-                                        szDataPointer );
-    GDALAddBand( hDS, GDT_Byte, papszBandOptions );
-                                        
-    /* Add Dithered Band */
-    memset( szDataPointer, 0, sizeof(szDataPointer) );
-    CPLPrintPointer( szDataPointer, pabyDithered, sizeof(szDataPointer) );
-    papszBandOptions = CSLSetNameValue( papszBandOptions, "DATAPOINTER", 
-                                        szDataPointer );
-    GDALAddBand( hDS, GDT_Byte, papszBandOptions );
-
-    CSLDestroy( papszBandOptions );
-                                        
-/* -------------------------------------------------------------------- */
-/*      Create the color table.                                         */
-/* -------------------------------------------------------------------- */
-    hCT = GDALCreateColorTable( GPI_RGB );
-
-    for (c = 0; c < gdImg->colorsTotal; c++) 
-    {
-        GDALColorEntry sEntry;
-              
-        sEntry.c1 = gdImg->red[c];
-        sEntry.c2 = gdImg->green[c];
-        sEntry.c3 = gdImg->blue[c];
-
-        if( bTransparent 
-            && transparent.red == sEntry.c1
-            && transparent.green == sEntry.c2
-            && transparent.blue == sEntry.c3 )
-            sEntry.c4 = 0;
-        else
-            sEntry.c4 = 255;
-        
-        GDALSetColorEntry( hCT, c, &sEntry );
-    }
-
-/* -------------------------------------------------------------------- */
-/*      Perform dithering.                                              */
-/* -------------------------------------------------------------------- */
-    GDALDitherRGB2PCT( GDALGetRasterBand( hDS, 1 ),
-                       GDALGetRasterBand( hDS, 2 ),
-                       GDALGetRasterBand( hDS, 3 ),
-                       GDALGetRasterBand( hDS, 4 ),
-                       hCT, NULL, NULL );
-
-/* -------------------------------------------------------------------- */
-/*      Cleanup.                                                        */
-/* -------------------------------------------------------------------- */
-    GDALDestroyColorTable( hCT );
-    GDALClose( hDS );
+  GDALDatasetH hDS;
+  GDALDriverH  hDriver;
+  char **papszBandOptions = NULL;
+  char szDataPointer[120];
+  GDALColorTableH hCT;
+  int c;
+
+  /* -------------------------------------------------------------------- */
+  /*      Create the "memory" GDAL dataset referencing our working        */
+  /*      arrays.                                                         */
+  /* -------------------------------------------------------------------- */
+  hDriver = GDALGetDriverByName( "MEM" );
+  if( hDriver == NULL )
+    return;
+
+  hDS = GDALCreate( hDriver, "TempDitherDS", xsize, ysize, 0, GDT_Byte,
+                    NULL );
+
+  /* Add Red Band */
+  memset( szDataPointer, 0, sizeof(szDataPointer) );
+  CPLPrintPointer( szDataPointer, pabyRed, sizeof(szDataPointer) );
+  papszBandOptions = CSLSetNameValue( papszBandOptions, "DATAPOINTER",
+                                      szDataPointer );
+  GDALAddBand( hDS, GDT_Byte, papszBandOptions );
+
+  /* Add Green Band */
+  memset( szDataPointer, 0, sizeof(szDataPointer) );
+  CPLPrintPointer( szDataPointer, pabyGreen, sizeof(szDataPointer) );
+  papszBandOptions = CSLSetNameValue( papszBandOptions, "DATAPOINTER",
+                                      szDataPointer );
+  GDALAddBand( hDS, GDT_Byte, papszBandOptions );
+
+  /* Add Blue Band */
+  memset( szDataPointer, 0, sizeof(szDataPointer) );
+  CPLPrintPointer( szDataPointer, pabyBlue, sizeof(szDataPointer) );
+  papszBandOptions = CSLSetNameValue( papszBandOptions, "DATAPOINTER",
+                                      szDataPointer );
+  GDALAddBand( hDS, GDT_Byte, papszBandOptions );
+
+  /* Add Dithered Band */
+  memset( szDataPointer, 0, sizeof(szDataPointer) );
+  CPLPrintPointer( szDataPointer, pabyDithered, sizeof(szDataPointer) );
+  papszBandOptions = CSLSetNameValue( papszBandOptions, "DATAPOINTER",
+                                      szDataPointer );
+  GDALAddBand( hDS, GDT_Byte, papszBandOptions );
+
+  CSLDestroy( papszBandOptions );
+
+  /* -------------------------------------------------------------------- */
+  /*      Create the color table.                                         */
+  /* -------------------------------------------------------------------- */
+  hCT = GDALCreateColorTable( GPI_RGB );
+
+  for (c = 0; c < gdImg->colorsTotal; c++) {
+    GDALColorEntry sEntry;
+
+    sEntry.c1 = gdImg->red[c];
+    sEntry.c2 = gdImg->green[c];
+    sEntry.c3 = gdImg->blue[c];
+
+    if( bTransparent
+        && transparent.red == sEntry.c1
+        && transparent.green == sEntry.c2
+        && transparent.blue == sEntry.c3 )
+      sEntry.c4 = 0;
+    else
+      sEntry.c4 = 255;
+
+    GDALSetColorEntry( hCT, c, &sEntry );
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Perform dithering.                                              */
+  /* -------------------------------------------------------------------- */
+  GDALDitherRGB2PCT( GDALGetRasterBand( hDS, 1 ),
+                     GDALGetRasterBand( hDS, 2 ),
+                     GDALGetRasterBand( hDS, 3 ),
+                     GDALGetRasterBand( hDS, 4 ),
+                     hCT, NULL, NULL );
+
+  /* -------------------------------------------------------------------- */
+  /*      Cleanup.                                                        */
+  /* -------------------------------------------------------------------- */
+  GDALDestroyColorTable( hCT );
+  GDALClose( hDS );
 }
-#endif /* def ENABLE_DITHER */
+#endif
+
 
 /************************************************************************/
 /*                       msGetGDALGeoTransform()                        */
@@ -1831,140 +1685,176 @@ static void Dither24to8( GByte *pabyRed, GByte *pabyGreen, GByte *pabyBlue,
 /*      before this function is called.                                 */
 /************************************************************************/
 
-int msGetGDALGeoTransform( GDALDatasetH hDS, mapObj *map, layerObj *layer, 
+int msGetGDALGeoTransform( GDALDatasetH hDS, mapObj *map, layerObj *layer,
                            double *padfGeoTransform )
 
 {
-    const char *extent_priority = NULL;
-    const char *value;
-    rectObj  rect;
-
-/* -------------------------------------------------------------------- */
-/*      some GDAL drivers (ie. GIF) don't set geotransform on failure.  */
-/* -------------------------------------------------------------------- */
-    padfGeoTransform[0] = 0.0;
-    padfGeoTransform[1] = 1.0;
-    padfGeoTransform[2] = 0.0;
-    padfGeoTransform[3] = GDALGetRasterYSize(hDS);
-    padfGeoTransform[4] = 0.0;
-    padfGeoTransform[5] = -1.0;
-    
-/* -------------------------------------------------------------------- */
-/*      Do we want to override GDAL with a worldfile if one is present? */
-/* -------------------------------------------------------------------- */
-    extent_priority = CSLFetchNameValue( layer->processing, 
-                                         "EXTENT_PRIORITY" );
-
-    if( extent_priority != NULL
-        && EQUALN(extent_priority,"WORLD",5) )
-    {
-        if( GDALGetDescription(hDS) != NULL 
-            && GDALReadWorldFile(GDALGetDescription(hDS), "wld", 
-                                 padfGeoTransform) )
-        {
-            return MS_SUCCESS;
+  const char *extent_priority = NULL;
+  const char *value;
+  const char *gdalDesc;
+  const char *fullPath;
+  char *fileExtension = NULL;
+  char szPath[MS_MAXPATHLEN];
+  int fullPathLen;
+  int success = 0;
+  rectObj  rect;
+
+  /* -------------------------------------------------------------------- */
+  /*      some GDAL drivers (ie. GIF) don't set geotransform on failure.  */
+  /* -------------------------------------------------------------------- */
+  padfGeoTransform[0] = 0.0;
+  padfGeoTransform[1] = 1.0;
+  padfGeoTransform[2] = 0.0;
+  padfGeoTransform[3] = GDALGetRasterYSize(hDS);
+  padfGeoTransform[4] = 0.0;
+  padfGeoTransform[5] = -1.0;
+
+  /* -------------------------------------------------------------------- */
+  /*      Do we want to override GDAL with a worldfile if one is present? */
+  /* -------------------------------------------------------------------- */
+  extent_priority = CSLFetchNameValue( layer->processing,
+                                       "EXTENT_PRIORITY" );
+
+  if( extent_priority != NULL
+      && EQUALN(extent_priority,"WORLD",5) ) {
+    /* is there a user configured worldfile? */
+    value = CSLFetchNameValue( layer->processing, "WORLDFILE" );
+
+    if( value != NULL ) {
+      /* at this point, fullPath may be a filePath or path only */
+      fullPath = msBuildPath(szPath, map->mappath, value);
+
+      /* fullPath is a path only, so let's append the dataset filename */
+      if( strrchr(szPath,'.') == NULL ) {
+        fullPathLen = strlen(fullPath);
+        gdalDesc = msStripPath((char*)GDALGetDescription(hDS));
+
+        if ( (fullPathLen + strlen(gdalDesc)) < MS_MAXPATHLEN ) {
+          strcpy((char*)(fullPath + fullPathLen), gdalDesc);
+        } else {
+          msDebug("Path length to alternative worldfile exceeds MS_MAXPATHLEN.\n");
+          fullPath = NULL;
         }
+      }
+      /* fullPath has a filename included, so get the extension */
+      else {
+        fileExtension = msStrdup(strrchr(szPath,'.') + 1);
+      }
+    }
+    /* common behaviour with worldfile generated from basename + .wld */
+    else {
+      fullPath = GDALGetDescription(hDS);
+      fileExtension = msStrdup("wld");
     }
 
-/* -------------------------------------------------------------------- */
-/*      Try GDAL.                                                       */
-/*                                                                      */
-/*      Make sure that ymax is always at the top, and ymin at the       */
-/*      bottom ... that is flip any files without the usual             */
-/*      orientation.  This is intended to enable display of "raw"       */
-/*      files with no coordinate system otherwise they break down in    */
-/*      many ways.                                                      */
-/* -------------------------------------------------------------------- */
-    if (GDALGetGeoTransform( hDS, padfGeoTransform ) == CE_None )
-    {
-        if( padfGeoTransform[5] == 1.0 && padfGeoTransform[3] == 0.0 )
-        {
-            padfGeoTransform[5] = -1.0;
-            padfGeoTransform[3] = GDALGetRasterYSize(hDS);
-        }
+    if( fullPath )
+      success = GDALReadWorldFile(fullPath, fileExtension, padfGeoTransform);
 
-        return MS_SUCCESS;
+    if( success && layer->debug >= MS_DEBUGLEVEL_VVV ) {
+      msDebug("Worldfile location: %s.\n", fullPath);
+    } else if( layer->debug >= MS_DEBUGLEVEL_VVV ) {
+      msDebug("Failed using worldfile location: %s.\n", fullPath);
     }
 
-/* -------------------------------------------------------------------- */
-/*      Try worldfile.                                                  */
-/* -------------------------------------------------------------------- */
-    if( GDALGetDescription(hDS) != NULL 
-        && GDALReadWorldFile(GDALGetDescription(hDS), "wld", 
-                             padfGeoTransform) )
-    {
-        return MS_SUCCESS;
-    }
+    msFree(fileExtension);
 
-/* -------------------------------------------------------------------- */
-/*      Do we have the extent keyword on the layer?  We only use        */
-/*      this if we have a single raster associated with the layer as    */
-/*      opposed to a tile index.                                        */
-/*                                                                      */
-/*      Arguably this ought to take priority over all the other         */
-/*      stuff.                                                          */
-/* -------------------------------------------------------------------- */
-    if (MS_VALID_EXTENT(layer->extent) && layer->data != NULL)
-    {
-        rect = layer->extent;
-
-        padfGeoTransform[0] = rect.minx;
-        padfGeoTransform[1] = (rect.maxx - rect.minx) /
-            (double) GDALGetRasterXSize( hDS );
-        padfGeoTransform[2] = 0;
-        padfGeoTransform[3] = rect.maxy;
-        padfGeoTransform[4] = 0;
-        padfGeoTransform[5] = (rect.miny - rect.maxy) /
-            (double) GDALGetRasterYSize( hDS );
-        
-        return MS_SUCCESS;
+    if( success )
+      return MS_SUCCESS;
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Try GDAL.                                                       */
+  /*                                                                      */
+  /*      Make sure that ymax is always at the top, and ymin at the       */
+  /*      bottom ... that is flip any files without the usual             */
+  /*      orientation.  This is intended to enable display of "raw"       */
+  /*      files with no coordinate system otherwise they break down in    */
+  /*      many ways.                                                      */
+  /* -------------------------------------------------------------------- */
+  if (GDALGetGeoTransform( hDS, padfGeoTransform ) == CE_None ) {
+    if( padfGeoTransform[5] == 1.0 && padfGeoTransform[3] == 0.0 ) {
+      padfGeoTransform[5] = -1.0;
+      padfGeoTransform[3] = GDALGetRasterYSize(hDS);
     }
 
-/* -------------------------------------------------------------------- */
-/*      Try OWS extent metadata.  We only try this if we know there     */
-/*      is metadata so that we don't end up going into the layer        */
-/*      getextent function which will in turn reopen the file with      */
-/*      potential performance and locking problems.                     */
-/* -------------------------------------------------------------------- */
+    return MS_SUCCESS;
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Try worldfile.                                                  */
+  /* -------------------------------------------------------------------- */
+  if( GDALGetDescription(hDS) != NULL
+      && GDALReadWorldFile(GDALGetDescription(hDS), "wld",
+                           padfGeoTransform) ) {
+    return MS_SUCCESS;
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Do we have the extent keyword on the layer?  We only use        */
+  /*      this if we have a single raster associated with the layer as    */
+  /*      opposed to a tile index.                                        */
+  /*                                                                      */
+  /*      Arguably this ought to take priority over all the other         */
+  /*      stuff.                                                          */
+  /* -------------------------------------------------------------------- */
+  if (MS_VALID_EXTENT(layer->extent) && layer->data != NULL) {
+    rect = layer->extent;
+
+    padfGeoTransform[0] = rect.minx;
+    padfGeoTransform[1] = (rect.maxx - rect.minx) /
+                          (double) GDALGetRasterXSize( hDS );
+    padfGeoTransform[2] = 0;
+    padfGeoTransform[3] = rect.maxy;
+    padfGeoTransform[4] = 0;
+    padfGeoTransform[5] = (rect.miny - rect.maxy) /
+                          (double) GDALGetRasterYSize( hDS );
+
+    return MS_SUCCESS;
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Try OWS extent metadata.  We only try this if we know there     */
+  /*      is metadata so that we don't end up going into the layer        */
+  /*      getextent function which will in turn reopen the file with      */
+  /*      potential performance and locking problems.                     */
+  /* -------------------------------------------------------------------- */
 #if defined(USE_WMS_SVR) || defined (USE_WFS_SVR)
-    if ((value = msOWSLookupMetadata(&(layer->metadata), "MFCO", "extent"))
-        != NULL)
-    {
-        int success;
-
-        msReleaseLock( TLOCK_GDAL );
-        success = msOWSGetLayerExtent( map, layer, "MFCO", &rect );
-        msAcquireLock( TLOCK_GDAL );
-
-        if( success == MS_SUCCESS )
-        {
-            padfGeoTransform[0] = rect.minx;
-            padfGeoTransform[1] = (rect.maxx - rect.minx) /
-                (double) GDALGetRasterXSize( hDS );
-            padfGeoTransform[2] = 0;
-            padfGeoTransform[3] = rect.maxy;
-            padfGeoTransform[4] = 0;
-            padfGeoTransform[5] = (rect.miny - rect.maxy) /
-                (double) GDALGetRasterYSize( hDS );
-            
-            return MS_SUCCESS;
-        }
-    }
+  if ((value = msOWSLookupMetadata(&(layer->metadata), "MFCO", "extent"))
+      != NULL) {
+    int success;
+
+    msReleaseLock( TLOCK_GDAL );
+    success = msOWSGetLayerExtent( map, layer, "MFCO", &rect );
+    msAcquireLock( TLOCK_GDAL );
+
+    if( success == MS_SUCCESS ) {
+      padfGeoTransform[0] = rect.minx;
+      padfGeoTransform[1] = (rect.maxx - rect.minx) /
+                            (double) GDALGetRasterXSize( hDS );
+      padfGeoTransform[2] = 0;
+      padfGeoTransform[3] = rect.maxy;
+      padfGeoTransform[4] = 0;
+      padfGeoTransform[5] = (rect.miny - rect.maxy) /
+                            (double) GDALGetRasterYSize( hDS );
+
+      return MS_SUCCESS;
+    }
+  }
 #endif
 
-/* -------------------------------------------------------------------- */
-/*      We didn't find any info ... use the default.                    */
-/*      Reset our default geotransform.  GDALGetGeoTransform() may      */
-/*      have altered it even if GDALGetGeoTransform() failed.           */
-/* -------------------------------------------------------------------- */
-    padfGeoTransform[0] = 0.0;
-    padfGeoTransform[1] = 1.0;
-    padfGeoTransform[2] = 0.0;
-    padfGeoTransform[3] = GDALGetRasterYSize(hDS);
-    padfGeoTransform[4] = 0.0;
-    padfGeoTransform[5] = -1.0;
-    
-    return MS_FAILURE;
+  /* -------------------------------------------------------------------- */
+  /*      We didn't find any info ... use the default.                    */
+  /*      Reset our default geotransform.  GDALGetGeoTransform() may      */
+  /*      have altered it even if GDALGetGeoTransform() failed.           */
+  /* -------------------------------------------------------------------- */
+  padfGeoTransform[0] = 0.0;
+  padfGeoTransform[1] = 1.0;
+  padfGeoTransform[2] = 0.0;
+  padfGeoTransform[3] = GDALGetRasterYSize(hDS);
+  padfGeoTransform[4] = 0.0;
+  padfGeoTransform[5] = -1.0;
+
+  return MS_FAILURE;
 }
 
 /************************************************************************/
@@ -1973,225 +1863,188 @@ int msGetGDALGeoTransform( GDALDatasetH hDS, mapObj *map, layerObj *layer,
 /*      Handle the loading and application of data in rawmode.          */
 /************************************************************************/
 
-static int 
+static int
 msDrawRasterLayerGDAL_RawMode(
-    mapObj *map, layerObj *layer, imageObj *image, GDALDatasetH hDS, 
-    int src_xoff, int src_yoff, int src_xsize, int src_ysize,
-    int dst_xoff, int dst_yoff, int dst_xsize, int dst_ysize )
+  mapObj *map, layerObj *layer, imageObj *image, GDALDatasetH hDS,
+  int src_xoff, int src_yoff, int src_xsize, int src_ysize,
+  int dst_xoff, int dst_yoff, int dst_xsize, int dst_ysize )
 
 {
-    void *pBuffer;
-    GDALDataType eDataType;
-    int *band_list, band_count;
-    int  i, j, k, band;
-    CPLErr eErr;
-    float *f_nodatas = NULL;
-    unsigned char *b_nodatas = NULL;
-    GInt16 *i_nodatas = NULL;
-    int got_nodata=FALSE;
-
-    if( image->format->bands > 256 )
-    {
-        msSetError( MS_IMGERR, "Too many bands (more than 256).",
-                    "msDrawRasterLayerGDAL_RawMode()" );
-        return -1;
-    }
-
-/* -------------------------------------------------------------------- */
-/*      We need at least GDAL 1.2.0 for the DatasetRasterIO             */
-/*      function.                                                       */
-/* -------------------------------------------------------------------- */
-#if !defined(GDAL_VERSION_NUM) || GDAL_VERSION_NUM < 1200
-    msSetError(MS_IMGERR, 
-               "RAWMODE raster support requires GDAL 1.2.0 or newer.", 
-               "msDrawRasterLayerGDAL_RawMode()" );
-    free( pBuffer );
+  void *pBuffer;
+  GDALDataType eDataType;
+  int *band_list, band_count;
+  int  i, j, k, band;
+  CPLErr eErr;
+  float *f_nodatas = NULL;
+  unsigned char *b_nodatas = NULL;
+  GInt16 *i_nodatas = NULL;
+  int got_nodata=FALSE;
+
+  if( image->format->bands > 256 ) {
+    msSetError( MS_IMGERR, "Too many bands (more than 256).",
+                "msDrawRasterLayerGDAL_RawMode()" );
+    return -1;
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      What data type do we need?                                      */
+  /* -------------------------------------------------------------------- */
+  if( image->format->imagemode == MS_IMAGEMODE_INT16 )
+    eDataType = GDT_Int16;
+  else if( image->format->imagemode == MS_IMAGEMODE_FLOAT32 )
+    eDataType = GDT_Float32;
+  else if( image->format->imagemode == MS_IMAGEMODE_BYTE )
+    eDataType = GDT_Byte;
+  else
     return -1;
-#endif
-
-/* -------------------------------------------------------------------- */
-/*      What data type do we need?                                      */
-/* -------------------------------------------------------------------- */
-    if( image->format->imagemode == MS_IMAGEMODE_INT16 )
-        eDataType = GDT_Int16;
-    else if( image->format->imagemode == MS_IMAGEMODE_FLOAT32 )
-        eDataType = GDT_Float32;
-    else if( image->format->imagemode == MS_IMAGEMODE_BYTE )
-        eDataType = GDT_Byte;
-    else
-        return -1;
-
-/* -------------------------------------------------------------------- */
-/*      Work out the band list.                                         */
-/* -------------------------------------------------------------------- */
-    band_list = msGetGDALBandList( layer, hDS, image->format->bands, 
-                                   &band_count );
-    if( band_list == NULL )
-        return -1;
-
-    if( band_count != image->format->bands )
-    {
-        free( band_list );
-        msSetError( MS_IMGERR, "BANDS PROCESSING directive has wrong number of bands, expected %d, got %d.",
-                    "msDrawRasterLayerGDAL_RawMode()",
-                    image->format->bands, band_count );
-        return -1;
-    }
 
-/* -------------------------------------------------------------------- */
-/*      Do we have nodata values?                                       */
-/* -------------------------------------------------------------------- */
-    f_nodatas = (float *) calloc(sizeof(float),band_count);
-    if (f_nodatas == NULL) 
-    {
-        msSetError(MS_MEMERR, "%s: %d: Out of memory allocating %u bytes.\n", "msDrawRasterLayerGDAL_RawMode()",
-                   __FILE__, __LINE__, sizeof(float)*band_count); 
-        free( band_list );
-        return -1;
-    }
+  /* -------------------------------------------------------------------- */
+  /*      Work out the band list.                                         */
+  /* -------------------------------------------------------------------- */
+  band_list = msGetGDALBandList( layer, hDS, image->format->bands,
+                                 &band_count );
+  if( band_list == NULL )
+    return -1;
 
-    if( band_count <= 3
-        && (layer->offsite.red != -1
-            || layer->offsite.green != -1
-            || layer->offsite.blue != -1) )
-    {
-        if( band_count > 0 )
-            f_nodatas[0] = layer->offsite.red;
-        if( band_count > 1 )
-            f_nodatas[1] = layer->offsite.green;
-        if( band_count > 2 )
-            f_nodatas[2] = layer->offsite.blue;
-        got_nodata = TRUE;
-    }
+  if( band_count != image->format->bands ) {
+    free( band_list );
+    msSetError( MS_IMGERR, "BANDS PROCESSING directive has wrong number of bands, expected %d, got %d.",
+                "msDrawRasterLayerGDAL_RawMode()",
+                image->format->bands, band_count );
+    return -1;
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Do we have nodata values?                                       */
+  /* -------------------------------------------------------------------- */
+  f_nodatas = (float *) calloc(sizeof(float),band_count);
+  if (f_nodatas == NULL) {
+    msSetError(MS_MEMERR, "%s: %d: Out of memory allocating %u bytes.\n", "msDrawRasterLayerGDAL_RawMode()",
+               __FILE__, __LINE__, sizeof(float)*band_count);
+    free( band_list );
+    return -1;
+  }
+
+  if( band_count <= 3
+      && (layer->offsite.red != -1
+          || layer->offsite.green != -1
+          || layer->offsite.blue != -1) ) {
+    if( band_count > 0 )
+      f_nodatas[0] = layer->offsite.red;
+    if( band_count > 1 )
+      f_nodatas[1] = layer->offsite.green;
+    if( band_count > 2 )
+      f_nodatas[2] = layer->offsite.blue;
+    got_nodata = TRUE;
+  }
+
+  if( !got_nodata ) {
+    got_nodata = TRUE;
+    for( band = 0; band < band_count && got_nodata; band++ ) {
+      f_nodatas[band] = msGetGDALNoDataValue(
+                          layer, GDALGetRasterBand(hDS,band_list[band]), &got_nodata );
+    }
+  }
+
+  if( !got_nodata ) {
+    msFree( f_nodatas );
+    f_nodatas = NULL;
+  } else if( eDataType == GDT_Byte ) {
+    b_nodatas = (unsigned char *) f_nodatas;
+    for( band = 0; band < band_count; band++ )
+      b_nodatas[band] = (unsigned char) f_nodatas[band];
+  } else if( eDataType == GDT_Int16 ) {
+    i_nodatas = (GInt16 *) f_nodatas;
+    for( band = 0; band < band_count; band++ )
+      i_nodatas[band] = (GInt16) f_nodatas[band];
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Allocate buffer, and read data into it.                         */
+  /* -------------------------------------------------------------------- */
+  pBuffer = malloc(dst_xsize * dst_ysize * image->format->bands
+                   * (GDALGetDataTypeSize(eDataType)/8) );
+  if( pBuffer == NULL ) {
+    msSetError(MS_MEMERR,
+               "Allocating work image of size %dx%d failed.",
+               "msDrawRasterLayerGDAL()", dst_xsize, dst_ysize );
+    return -1;
+  }
+
+  eErr = GDALDatasetRasterIO( hDS, GF_Read,
+                              src_xoff, src_yoff, src_xsize, src_ysize,
+                              pBuffer, dst_xsize, dst_ysize, eDataType,
+                              image->format->bands, band_list,
+                              0, 0, 0 );
+  free( band_list );
+
+  if( eErr != CE_None ) {
+    msSetError( MS_IOERR, "GDALRasterIO() failed: %s",
+                "msDrawRasterLayerGDAL_RawMode()", CPLGetLastErrorMsg() );
+    free( pBuffer );
+    free( f_nodatas );
+    return -1;
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Transfer the data to the imageObj.                              */
+  /* -------------------------------------------------------------------- */
+  k = 0;
+  for( band = 0; band < image->format->bands; band++ ) {
+    for( i = dst_yoff; i < dst_yoff + dst_ysize; i++ ) {
+      if( image->format->imagemode == MS_IMAGEMODE_INT16 ) {
+        for( j = dst_xoff; j < dst_xoff + dst_xsize; j++ ) {
+          int off = j + i * image->width
+                    + band*image->width*image->height;
+          int off_mask = j + i * image->width;
+
+          if( i_nodatas
+              && ((GInt16 *) pBuffer)[k] == i_nodatas[band] ) {
+            k++;
+            continue;
+          }
 
-    if( !got_nodata )
-    {
-        got_nodata = TRUE;
-        for( band = 0; band < band_count && got_nodata; band++ )
-        {
-            f_nodatas[band] = msGetGDALNoDataValue( 
-                layer, GDALGetRasterBand(hDS,band_list[band]), &got_nodata );
+          image->img.raw_16bit[off] = ((GInt16 *) pBuffer)[k++];
+          MS_SET_BIT(image->img_mask,off_mask);
         }
-    }
-    
-    if( !got_nodata )
-    {
-        msFree( f_nodatas );
-        f_nodatas = NULL;
-    }
-    else if( eDataType == GDT_Byte )
-    {
-        b_nodatas = (unsigned char *) f_nodatas;
-        for( band = 0; band < band_count; band++ )
-            b_nodatas[band] = (unsigned char) f_nodatas[band];
-    }
-    else if( eDataType == GDT_Int16 )
-    {
-        i_nodatas = (GInt16 *) f_nodatas;
-        for( band = 0; band < band_count; band++ )
-            i_nodatas[band] = (GInt16) f_nodatas[band];
-    }
-
-/* -------------------------------------------------------------------- */
-/*      Allocate buffer, and read data into it.                         */
-/* -------------------------------------------------------------------- */
-    pBuffer = malloc(dst_xsize * dst_ysize * image->format->bands
-                     * (GDALGetDataTypeSize(eDataType)/8) );
-    if( pBuffer == NULL )
-    {
-        msSetError(MS_MEMERR, 
-                   "Allocating work image of size %dx%d failed.",
-                   "msDrawRasterLayerGDAL()", dst_xsize, dst_ysize );
-        return -1;
-    }
-
-    eErr = GDALDatasetRasterIO( hDS, GF_Read,  
-                                src_xoff, src_yoff, src_xsize, src_ysize, 
-                                pBuffer, dst_xsize, dst_ysize, eDataType, 
-                                image->format->bands, band_list,
-                                0, 0, 0 );
-    free( band_list );
+      } else if( image->format->imagemode == MS_IMAGEMODE_FLOAT32 ) {
+        for( j = dst_xoff; j < dst_xoff + dst_xsize; j++ ) {
+          int off = j + i * image->width
+                    + band*image->width*image->height;
+          int off_mask = j + i * image->width;
+
+          if( f_nodatas
+              && ((float *) pBuffer)[k] == f_nodatas[band] ) {
+            k++;
+            continue;
+          }
 
-    if( eErr != CE_None )
-    {
-        msSetError( MS_IOERR, "GDALRasterIO() failed: %s", 
-                    "msDrawRasterLayerGDAL_RawMode()", CPLGetLastErrorMsg() );
-        free( pBuffer );
-        free( f_nodatas );
-        return -1;
-    }
+          image->img.raw_float[off] = ((float *) pBuffer)[k++];
+          MS_SET_BIT(image->img_mask,off_mask);
+        }
+      } else if( image->format->imagemode == MS_IMAGEMODE_BYTE ) {
+        for( j = dst_xoff; j < dst_xoff + dst_xsize; j++ ) {
+          int off = j + i * image->width
+                    + band*image->width*image->height;
+          int off_mask = j + i * image->width;
+
+          if( b_nodatas
+              && ((unsigned char *) pBuffer)[k] == b_nodatas[band] ) {
+            k++;
+            continue;
+          }
 
-/* -------------------------------------------------------------------- */
-/*      Transfer the data to the imageObj.                              */
-/* -------------------------------------------------------------------- */
-    k = 0;
-    for( band = 0; band < image->format->bands; band++ )
-    {
-        for( i = dst_yoff; i < dst_yoff + dst_ysize; i++ )
-        {
-            if( image->format->imagemode == MS_IMAGEMODE_INT16 )
-            {
-                for( j = dst_xoff; j < dst_xoff + dst_xsize; j++ )
-                {
-                    int off = j + i * image->width
-                        + band*image->width*image->height;
-                    int off_mask = j + i * image->width;
-
-                    if( i_nodatas 
-                        && ((GInt16 *) pBuffer)[k] == i_nodatas[band] )
-                    {
-                        k++;
-                        continue;
-                    }
-
-                    image->img.raw_16bit[off] = ((GInt16 *) pBuffer)[k++];
-                    MS_SET_BIT(image->img_mask,off_mask);
-                }
-            }
-            else if( image->format->imagemode == MS_IMAGEMODE_FLOAT32 )
-            {
-                for( j = dst_xoff; j < dst_xoff + dst_xsize; j++ )
-                {
-                    int off = j + i * image->width
-                        + band*image->width*image->height;
-                    int off_mask = j + i * image->width;
-
-                    if( f_nodatas 
-                        && ((float *) pBuffer)[k] == f_nodatas[band] )
-                    {
-                        k++;
-                        continue;
-                    }
-
-                    image->img.raw_float[off] = ((float *) pBuffer)[k++];
-                    MS_SET_BIT(image->img_mask,off_mask);
-                }
-            }
-            else if( image->format->imagemode == MS_IMAGEMODE_BYTE )
-            {
-                for( j = dst_xoff; j < dst_xoff + dst_xsize; j++ )
-                {
-                    int off = j + i * image->width
-                        + band*image->width*image->height;
-                    int off_mask = j + i * image->width;
-
-                    if( b_nodatas 
-                        && ((unsigned char *) pBuffer)[k] == b_nodatas[band] )
-                    {
-                        k++;
-                        continue;
-                    }
-
-                    image->img.raw_byte[off] = ((unsigned char *) pBuffer)[k++];
-                    MS_SET_BIT(image->img_mask,off_mask);
-                }
-            }
+          image->img.raw_byte[off] = ((unsigned char *) pBuffer)[k++];
+          MS_SET_BIT(image->img_mask,off_mask);
         }
+      }
     }
+  }
 
-    free( pBuffer );
+  free( pBuffer );
+  free( f_nodatas );
 
-    return 0;
+  return 0;
 }
 
 /************************************************************************/
@@ -2206,343 +2059,306 @@ msDrawRasterLayerGDAL_RawMode(
 /*      the 16bit cases at the cost of some complication.               */
 /************************************************************************/
 
-static int 
+static int
 msDrawRasterLayerGDAL_16BitClassification(
-    mapObj *map, layerObj *layer, rasterBufferObj *rb,
-    GDALDatasetH hDS, GDALRasterBandH hBand,
-    int src_xoff, int src_yoff, int src_xsize, int src_ysize,
-    int dst_xoff, int dst_yoff, int dst_xsize, int dst_ysize )
+  mapObj *map, layerObj *layer, rasterBufferObj *rb,
+  GDALDatasetH hDS, GDALRasterBandH hBand,
+  int src_xoff, int src_yoff, int src_xsize, int src_ysize,
+  int dst_xoff, int dst_yoff, int dst_xsize, int dst_ysize )
 
 {
-    float *pafRawData;
-    double dfScaleMin=0.0, dfScaleMax=0.0, dfScaleRatio;
-    int   nPixelCount = dst_xsize * dst_ysize, i, nBucketCount=0;
-    GDALDataType eDataType;
-    float fDataMin=0.0, fDataMax=255.0, fNoDataValue;
-    const char *pszScaleInfo;
-    const char *pszBuckets;
-    int  bUseIntegers = FALSE;
-    int  *cmap, c, j, k, bGotNoData = FALSE, bGotFirstValue;
-    unsigned char *rb_cmap[4];
-    CPLErr eErr;
-
-    assert( rb->type == MS_BUFFER_GD || rb->type == MS_BUFFER_BYTE_RGBA );
-
-/* ==================================================================== */
-/*      Read the requested data in one gulp into a floating point       */
-/*      buffer.                                                         */
-/* ==================================================================== */
-    pafRawData = (float *) malloc(sizeof(float) * dst_xsize * dst_ysize );
-    if( pafRawData == NULL )
-    {
-        msSetError( MS_MEMERR, "Out of memory allocating working buffer.",
-                    "msDrawRasterLayerGDAL_16BitClassification()" );
-        return -1;
-    }
-    
-    eErr = GDALRasterIO( hBand, GF_Read, 
-                         src_xoff, src_yoff, src_xsize, src_ysize, 
-                         pafRawData, dst_xsize, dst_ysize, GDT_Float32, 0, 0 );
-    
-    if( eErr != CE_None )
-    {
-        free( pafRawData );
-        msSetError( MS_IOERR, "GDALRasterIO() failed: %s", 
-                    "msDrawRasterLayerGDAL_16BitClassification()",
-                    CPLGetLastErrorMsg() );
-        return -1;
-    }
-
-    fNoDataValue = (float) msGetGDALNoDataValue( layer, hBand, &bGotNoData );
-
-/* ==================================================================== */
-/*      Determine scaling.                                              */
-/* ==================================================================== */
-    eDataType = GDALGetRasterDataType( hBand );
-
-/* -------------------------------------------------------------------- */
-/*      Scan for absolute min/max of this block.                        */
-/* -------------------------------------------------------------------- */
-    bGotFirstValue = FALSE;
-    
-    for( i = 1; i < nPixelCount; i++ )
-    {
-        if( bGotNoData && pafRawData[i] == fNoDataValue )
-            continue;
-
-        if( !bGotFirstValue )
-        {
-            fDataMin = fDataMax = pafRawData[i];
-            bGotFirstValue = TRUE;
-        }
-        else
-        {
-            fDataMin = MIN(fDataMin,pafRawData[i]);
-            fDataMax = MAX(fDataMax,pafRawData[i]);
-        }
-    }
-
-/* -------------------------------------------------------------------- */
-/*      Fetch the scale processing option.                              */
-/* -------------------------------------------------------------------- */
-    pszBuckets = CSLFetchNameValue( layer->processing, "SCALE_BUCKETS" );
-    pszScaleInfo = CSLFetchNameValue( layer->processing, "SCALE" );
-
-    if( pszScaleInfo != NULL )
-    {
-        char **papszTokens;
-
-        papszTokens = CSLTokenizeStringComplex( pszScaleInfo, " ,", 
-                                                FALSE, FALSE );
-        if( CSLCount(papszTokens) == 1
-            && EQUAL(papszTokens[0],"AUTO") )
-        {
-            dfScaleMin = dfScaleMax = 0.0;
-        }
-        else if( CSLCount(papszTokens) != 2 )
-        {
-            free( pafRawData );
-            msSetError( MS_MISCERR, 
-                        "SCALE PROCESSING option unparsable for layer %s.",
-                        "msDrawGDAL()",
-                        layer->name );
-            return -1;
-        }
-        else
-        {
-            dfScaleMin = atof(papszTokens[0]);
-            dfScaleMax = atof(papszTokens[1]);
-        }
-        CSLDestroy( papszTokens );
-    }
-
-/* -------------------------------------------------------------------- */
-/*      Special integer cases for scaling.                              */
-/*                                                                      */
-/*      TODO: Treat Int32 and UInt32 case the same way *if* the min     */
-/*      and max are less than 65536 apart.                              */
-/* -------------------------------------------------------------------- */
-    if( eDataType == GDT_Byte || eDataType == GDT_Int16 
-        || eDataType == GDT_UInt16 )
-    {
-        if( pszScaleInfo == NULL )
-        {
-            dfScaleMin = fDataMin - 0.5;
-            dfScaleMax = fDataMax + 0.5;
-        }
-
-        if( pszBuckets == NULL )
-        {
-            nBucketCount = (int) floor(fDataMax - fDataMin + 1.1);
-            bUseIntegers = TRUE;
-        }
-    }
+  float *pafRawData;
+  double dfScaleMin=0.0, dfScaleMax=0.0, dfScaleRatio;
+  int   nPixelCount = dst_xsize * dst_ysize, i, nBucketCount=0;
+  GDALDataType eDataType;
+  float fDataMin=0.0, fDataMax=255.0, fNoDataValue;
+  const char *pszScaleInfo;
+  const char *pszBuckets;
+  int  *cmap, c, j, k, bGotNoData = FALSE, bGotFirstValue;
+  unsigned char *rb_cmap[4];
+  CPLErr eErr;
+
+  assert( rb->type == MS_BUFFER_GD || rb->type == MS_BUFFER_BYTE_RGBA );
+
+  /* ==================================================================== */
+  /*      Read the requested data in one gulp into a floating point       */
+  /*      buffer.                                                         */
+  /* ==================================================================== */
+  pafRawData = (float *) malloc(sizeof(float) * dst_xsize * dst_ysize );
+  if( pafRawData == NULL ) {
+    msSetError( MS_MEMERR, "Out of memory allocating working buffer.",
+                "msDrawRasterLayerGDAL_16BitClassification()" );
+    return -1;
+  }
 
-/* -------------------------------------------------------------------- */
-/*      General case if no scaling values provided in mapfile.          */
-/* -------------------------------------------------------------------- */
-    else if( dfScaleMin == 0.0 && dfScaleMax == 0.0 )
-    {
-        double dfEpsilon = (fDataMax - fDataMin) / (65536*2);
-        dfScaleMin = fDataMin - dfEpsilon;
-        dfScaleMax = fDataMax + dfEpsilon;
-    }
+  eErr = GDALRasterIO( hBand, GF_Read,
+                       src_xoff, src_yoff, src_xsize, src_ysize,
+                       pafRawData, dst_xsize, dst_ysize, GDT_Float32, 0, 0 );
 
-/* -------------------------------------------------------------------- */
-/*      How many buckets?  Only set if we don't already have a value.   */
-/* -------------------------------------------------------------------- */
-    if( pszBuckets == NULL )
-    {
-        if( nBucketCount == 0 )
-            nBucketCount = 65536;
-    }
-    else
-    {
-        nBucketCount = atoi(pszBuckets);
-        if( nBucketCount < 2 )
-        {
-            free( pafRawData );
-            msSetError( MS_MISCERR, 
-                        "SCALE_BUCKETS PROCESSING option is not a value of 2 or more: %s.",
-                        "msDrawRasterLayerGDAL_16BitClassification()",
-                        pszBuckets );
-            return -1;
+  if( eErr != CE_None ) {
+    free( pafRawData );
+    msSetError( MS_IOERR, "GDALRasterIO() failed: %s",
+                "msDrawRasterLayerGDAL_16BitClassification()",
+                CPLGetLastErrorMsg() );
+    return -1;
+  }
+
+  fNoDataValue = (float) msGetGDALNoDataValue( layer, hBand, &bGotNoData );
+
+  /* ==================================================================== */
+  /*      Determine scaling.                                              */
+  /* ==================================================================== */
+  eDataType = GDALGetRasterDataType( hBand );
+
+  /* -------------------------------------------------------------------- */
+  /*      Scan for absolute min/max of this block.                        */
+  /* -------------------------------------------------------------------- */
+  bGotFirstValue = FALSE;
+
+  for( i = 1; i < nPixelCount; i++ ) {
+    if( bGotNoData && pafRawData[i] == fNoDataValue )
+      continue;
+
+    if( !bGotFirstValue ) {
+      fDataMin = fDataMax = pafRawData[i];
+      bGotFirstValue = TRUE;
+    } else {
+      fDataMin = MIN(fDataMin,pafRawData[i]);
+      fDataMax = MAX(fDataMax,pafRawData[i]);
+    }
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Fetch the scale processing option.                              */
+  /* -------------------------------------------------------------------- */
+  pszBuckets = CSLFetchNameValue( layer->processing, "SCALE_BUCKETS" );
+  pszScaleInfo = CSLFetchNameValue( layer->processing, "SCALE" );
+
+  if( pszScaleInfo != NULL ) {
+    char **papszTokens;
+
+    papszTokens = CSLTokenizeStringComplex( pszScaleInfo, " ,",
+                                            FALSE, FALSE );
+    if( CSLCount(papszTokens) == 1
+        && EQUAL(papszTokens[0],"AUTO") ) {
+      dfScaleMin = dfScaleMax = 0.0;
+    } else if( CSLCount(papszTokens) != 2 ) {
+      free( pafRawData );
+      msSetError( MS_MISCERR,
+                  "SCALE PROCESSING option unparsable for layer %s.",
+                  "msDrawGDAL()",
+                  layer->name );
+      return -1;
+    } else {
+      dfScaleMin = atof(papszTokens[0]);
+      dfScaleMax = atof(papszTokens[1]);
+    }
+    CSLDestroy( papszTokens );
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Special integer cases for scaling.                              */
+  /*                                                                      */
+  /*      TODO: Treat Int32 and UInt32 case the same way *if* the min     */
+  /*      and max are less than 65536 apart.                              */
+  /* -------------------------------------------------------------------- */
+  if( eDataType == GDT_Byte || eDataType == GDT_Int16
+      || eDataType == GDT_UInt16 ) {
+    if( pszScaleInfo == NULL ) {
+      dfScaleMin = fDataMin - 0.5;
+      dfScaleMax = fDataMax + 0.5;
+    }
+
+    if( pszBuckets == NULL ) {
+      nBucketCount = (int) floor(fDataMax - fDataMin + 1.1);
+    }
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      General case if no scaling values provided in mapfile.          */
+  /* -------------------------------------------------------------------- */
+  else if( dfScaleMin == 0.0 && dfScaleMax == 0.0 ) {
+    double dfEpsilon = (fDataMax - fDataMin) / (65536*2);
+    dfScaleMin = fDataMin - dfEpsilon;
+    dfScaleMax = fDataMax + dfEpsilon;
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      How many buckets?  Only set if we don't already have a value.   */
+  /* -------------------------------------------------------------------- */
+  if( pszBuckets == NULL ) {
+    if( nBucketCount == 0 )
+      nBucketCount = 65536;
+  } else {
+    nBucketCount = atoi(pszBuckets);
+    if( nBucketCount < 2 ) {
+      free( pafRawData );
+      msSetError( MS_MISCERR,
+                  "SCALE_BUCKETS PROCESSING option is not a value of 2 or more: %s.",
+                  "msDrawRasterLayerGDAL_16BitClassification()",
+                  pszBuckets );
+      return -1;
+    }
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Compute scaling ratio.                                          */
+  /* -------------------------------------------------------------------- */
+  if( dfScaleMax == dfScaleMin )
+    dfScaleMax = dfScaleMin + 1.0;
+
+  dfScaleRatio = nBucketCount / (dfScaleMax - dfScaleMin);
+
+  if( layer->debug > 0 )
+    msDebug( "msDrawRasterGDAL_16BitClassification(%s):\n"
+             "  scaling to %d buckets from range=%g,%g.\n",
+             layer->name, nBucketCount, dfScaleMin, dfScaleMax );
+
+  /* ==================================================================== */
+  /*      Compute classification lookup table.                            */
+  /* ==================================================================== */
+
+  cmap = (int *) msSmallCalloc(sizeof(int),nBucketCount);
+  rb_cmap[0] = (unsigned char *) msSmallCalloc(1,nBucketCount);
+  rb_cmap[1] = (unsigned char *) msSmallCalloc(1,nBucketCount);
+  rb_cmap[2] = (unsigned char *) msSmallCalloc(1,nBucketCount);
+  rb_cmap[3] = (unsigned char *) msSmallCalloc(1,nBucketCount);
+
+  for(i=0; i < nBucketCount; i++) {
+    double dfOriginalValue;
+
+    cmap[i] = -1;
+
+    dfOriginalValue = (i+0.5) / dfScaleRatio + dfScaleMin;
+
+    c = msGetClass_FloatRGB(layer, (float) dfOriginalValue, -1, -1, -1);
+    if( c != -1 ) {
+      int s;
+
+      /* change colour based on colour range? */
+      for(s=0; s<layer->class[c]->numstyles; s++) {
+        if( MS_VALID_COLOR(layer->class[c]->styles[s]->mincolor)
+            && MS_VALID_COLOR(layer->class[c]->styles[s]->maxcolor) )
+          msValueToRange(layer->class[c]->styles[s],dfOriginalValue);
+      }
+#ifdef USE_GD
+      if(rb->type == MS_BUFFER_GD) {
+        RESOLVE_PEN_GD(rb->data.gd_img, layer->class[c]->styles[0]->color);
+        if( MS_TRANSPARENT_COLOR(layer->class[c]->styles[0]->color) )
+          cmap[i] = -1;
+        else if( MS_VALID_COLOR(layer->class[c]->styles[0]->color)) {
+          /* use class color */
+          cmap[i] = layer->class[c]->styles[0]->color.pen;
         }
-    }
-
-/* -------------------------------------------------------------------- */
-/*      Compute scaling ratio.                                          */
-/* -------------------------------------------------------------------- */
-    if( dfScaleMax == dfScaleMin )
-        dfScaleMax = dfScaleMin + 1.0;
-
-    dfScaleRatio = nBucketCount / (dfScaleMax - dfScaleMin);
-
-    if( layer->debug > 0 )
-        msDebug( "msDrawRasterGDAL_16BitClassification(%s):\n"
-                 "  scaling to %d buckets from range=%g,%g.\n",
-                 layer->name, nBucketCount, dfScaleMin, dfScaleMax );
-
-/* ==================================================================== */
-/*      Compute classification lookup table.                            */
-/* ==================================================================== */
-
-    cmap = (int *) msSmallCalloc(sizeof(int),nBucketCount);
-    rb_cmap[0] = (unsigned char *) msSmallCalloc(1,nBucketCount);
-    rb_cmap[1] = (unsigned char *) msSmallCalloc(1,nBucketCount);
-    rb_cmap[2] = (unsigned char *) msSmallCalloc(1,nBucketCount);
-    rb_cmap[3] = (unsigned char *) msSmallCalloc(1,nBucketCount);
-
-    for(i=0; i < nBucketCount; i++) 
-    {
-        double dfOriginalValue;
-
-        cmap[i] = -1;
-
-        dfOriginalValue = (i+0.5) / dfScaleRatio + dfScaleMin;
-            
-        c = msGetClass_FloatRGB(layer, (float) dfOriginalValue, -1, -1, -1);
-        if( c != -1 )
-        {
-            int s;
-
-            /* change colour based on colour range? */
-            for(s=0; s<layer->class[c]->numstyles; s++)
-            {
-                if( MS_VALID_COLOR(layer->class[c]->styles[s]->mincolor)
-                    && MS_VALID_COLOR(layer->class[c]->styles[s]->maxcolor) )
-                    msValueToRange(layer->class[c]->styles[s],dfOriginalValue);
-            }
-            if(rb->type == MS_BUFFER_GD) {
-            	RESOLVE_PEN_GD(rb->data.gd_img, layer->class[c]->styles[0]->color);
-                if( MS_TRANSPARENT_COLOR(layer->class[c]->styles[0]->color) )
-                    cmap[i] = -1;
-                else if( MS_VALID_COLOR(layer->class[c]->styles[0]->color))
-                {
-                    /* use class color */
-                    cmap[i] = layer->class[c]->styles[0]->color.pen;
-                }
-            }
-            else if( rb->type == MS_BUFFER_BYTE_RGBA )
-            {
-                if( MS_TRANSPARENT_COLOR(layer->class[c]->styles[0]->color) )
-                {
-                    /* leave it transparent */
-                }
-                else if( MS_VALID_COLOR(layer->class[c]->styles[0]->color))
-                {
-                    /* use class color */
-                    rb_cmap[0][i] = layer->class[c]->styles[0]->color.red;
-                    rb_cmap[1][i] = layer->class[c]->styles[0]->color.green;
-                    rb_cmap[2][i] = layer->class[c]->styles[0]->color.blue;
-                    rb_cmap[3][i] = (255*layer->class[c]->styles[0]->opacity / 100);
-                }
-            }
+      } else
+#endif
+        if( rb->type == MS_BUFFER_BYTE_RGBA ) {
+          if( MS_TRANSPARENT_COLOR(layer->class[c]->styles[0]->color) ) {
+            /* leave it transparent */
+          } else if( MS_VALID_COLOR(layer->class[c]->styles[0]->color)) {
+            /* use class color */
+            rb_cmap[0][i] = layer->class[c]->styles[0]->color.red;
+            rb_cmap[1][i] = layer->class[c]->styles[0]->color.green;
+            rb_cmap[2][i] = layer->class[c]->styles[0]->color.blue;
+            rb_cmap[3][i] = (255*layer->class[c]->styles[0]->opacity / 100);
+          }
         }
     }
-    
-/* ==================================================================== */
-/*      Now process the data, applying to the working imageObj.         */
-/* ==================================================================== */
-    k = 0;
-
-    for( i = dst_yoff; i < dst_yoff + dst_ysize; i++ )
-    {
-        int	result;
-        
-        for( j = dst_xoff; j < dst_xoff + dst_xsize; j++ )
-        {
-            float fRawValue = pafRawData[k++];
-            int   iMapIndex;
-
-            /* 
-             * Skip nodata pixels ... no processing.
-             */
-            if( bGotNoData && fRawValue == fNoDataValue )
-            {
-                continue;
-            }
-            
-            /*
-             * The funny +1/-1 is to avoid odd rounding around zero.
-             * We could use floor() but sometimes it is expensive. 
-             */
-            iMapIndex = (int) ((fRawValue - dfScaleMin) * dfScaleRatio+1)-1;
-
-            if( iMapIndex >= nBucketCount || iMapIndex < 0 )
-            {
-                continue;
-            }
-
-            if( rb->type == MS_BUFFER_GD )
-            {
-                result = cmap[iMapIndex];
-                if( result == -1 )
-                    continue;
-
-                rb->data.gd_img->pixels[i][j] = result;
-            }
-            else if( rb->type == MS_BUFFER_BYTE_RGBA )
-            {
-                /* currently we never have partial alpha so keep simple */
-                if( rb_cmap[3][iMapIndex] > 0 )
-                    RB_SET_PIXEL( rb, j, i, 
-                                  rb_cmap[0][iMapIndex], 
-                                  rb_cmap[1][iMapIndex], 
-                                  rb_cmap[2][iMapIndex], 
-                                  rb_cmap[3][iMapIndex] );
-            }
+  }
+
+  /* ==================================================================== */
+  /*      Now process the data, applying to the working imageObj.         */
+  /* ==================================================================== */
+  k = 0;
+
+  for( i = dst_yoff; i < dst_yoff + dst_ysize; i++ ) {
+    for( j = dst_xoff; j < dst_xoff + dst_xsize; j++ ) {
+      float fRawValue = pafRawData[k++];
+      int   iMapIndex;
+
+      /*
+       * Skip nodata pixels ... no processing.
+       */
+      if( bGotNoData && fRawValue == fNoDataValue ) {
+        continue;
+      }
+
+      /*
+       * The funny +1/-1 is to avoid odd rounding around zero.
+       * We could use floor() but sometimes it is expensive.
+       */
+      iMapIndex = (int) ((fRawValue - dfScaleMin) * dfScaleRatio+1)-1;
+
+      if( iMapIndex >= nBucketCount || iMapIndex < 0 ) {
+        continue;
+      }
+#ifdef USE_GD
+      if( rb->type == MS_BUFFER_GD ) {
+        int result = cmap[iMapIndex];
+        if( result == -1 )
+          continue;
+
+        rb->data.gd_img->pixels[i][j] = result;
+      } else
+#endif
+        if( rb->type == MS_BUFFER_BYTE_RGBA ) {
+          /* currently we never have partial alpha so keep simple */
+          if( rb_cmap[3][iMapIndex] > 0 )
+            RB_SET_PIXEL( rb, j, i,
+                          rb_cmap[0][iMapIndex],
+                          rb_cmap[1][iMapIndex],
+                          rb_cmap[2][iMapIndex],
+                          rb_cmap[3][iMapIndex] );
         }
     }
+  }
 
-/* -------------------------------------------------------------------- */
-/*      Cleanup                                                         */
-/* -------------------------------------------------------------------- */
-    free( pafRawData );
-    free( cmap );
-    free( rb_cmap[0] );
-    free( rb_cmap[1] );
-    free( rb_cmap[2] );
-    free( rb_cmap[3] );
+  /* -------------------------------------------------------------------- */
+  /*      Cleanup                                                         */
+  /* -------------------------------------------------------------------- */
+  free( pafRawData );
+  free( cmap );
+  free( rb_cmap[0] );
+  free( rb_cmap[1] );
+  free( rb_cmap[2] );
+  free( rb_cmap[3] );
 
-    assert( k == dst_xsize * dst_ysize );
+  assert( k == dst_xsize * dst_ysize );
 
-    return 0;
+  return 0;
 }
 
 /************************************************************************/
 /*                          msGetGDALNoDataValue()                      */
 /************************************************************************/
-double 
+double
 msGetGDALNoDataValue( layerObj *layer, void *hBand, int *pbGotNoData )
 
 {
-    const char *pszNODATAOpt;
-
-    *pbGotNoData = FALSE;
-
-/* -------------------------------------------------------------------- */
-/*      Check for a NODATA setting in the .map file.                    */
-/* -------------------------------------------------------------------- */
-    pszNODATAOpt = CSLFetchNameValue(layer->processing,"NODATA");
-    if( pszNODATAOpt != NULL )
-    {
-        if( EQUAL(pszNODATAOpt,"OFF") || strlen(pszNODATAOpt) == 0 )
-            return -1234567.0;
-        if( !EQUAL(pszNODATAOpt,"AUTO") )
-        {
-            *pbGotNoData = TRUE;
-            return atof(pszNODATAOpt);
-        }
-    }
-    
-/* -------------------------------------------------------------------- */
-/*      Check for a NODATA setting on the raw file.                     */
-/* -------------------------------------------------------------------- */
-    if( hBand == NULL )
-        return -1234567.0;
-    else
-        return GDALGetRasterNoDataValue( hBand, pbGotNoData );
+  const char *pszNODATAOpt;
+
+  *pbGotNoData = FALSE;
+
+  /* -------------------------------------------------------------------- */
+  /*      Check for a NODATA setting in the .map file.                    */
+  /* -------------------------------------------------------------------- */
+  pszNODATAOpt = CSLFetchNameValue(layer->processing,"NODATA");
+  if( pszNODATAOpt != NULL ) {
+    if( EQUAL(pszNODATAOpt,"OFF") || strlen(pszNODATAOpt) == 0 )
+      return -1234567.0;
+    if( !EQUAL(pszNODATAOpt,"AUTO") ) {
+      *pbGotNoData = TRUE;
+      return atof(pszNODATAOpt);
+    }
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Check for a NODATA setting on the raw file.                     */
+  /* -------------------------------------------------------------------- */
+  if( hBand == NULL )
+    return -1234567.0;
+  else
+    return GDALGetRasterNoDataValue( hBand, pbGotNoData );
 }
 
 /************************************************************************/
@@ -2555,88 +2371,80 @@ msGetGDALNoDataValue( layerObj *layer, void *hBand, int *pbGotNoData )
 /*      returns malloc() list of band numbers (*band_count long).       */
 /************************************************************************/
 
-int *msGetGDALBandList( layerObj *layer, void *hDS, 
+int *msGetGDALBandList( layerObj *layer, void *hDS,
                         int max_bands, int *band_count )
 
 {
-    int i, file_bands;
-    int *band_list = NULL;
-
-    file_bands = GDALGetRasterCount( hDS );
-    if( file_bands == 0 )
-    {
-        msSetError( MS_IMGERR, 
-                    "Attempt to operate on GDAL file with no bands, layer=%s.",
-                    "msGetGDALBandList()", 
-                    layer->name );
-        
-        return NULL;
-    }
-
-/* -------------------------------------------------------------------- */
-/*      Use all (or first) bands.                                       */
-/* -------------------------------------------------------------------- */
-    if( CSLFetchNameValue( layer->processing, "BANDS" ) == NULL )
-    {
-        if( max_bands > 0 )
-            *band_count = MIN(file_bands,max_bands);
-        else
-            *band_count = file_bands;
-
-        band_list = (int *) malloc(sizeof(int) * *band_count );
-        MS_CHECK_ALLOC(band_list, sizeof(int) * *band_count, NULL);
-
-        for( i = 0; i < *band_count; i++ )
-            band_list[i] = i+1;
-        return band_list;
-    }
-
-/* -------------------------------------------------------------------- */
-/*      get bands from BANDS processing directive.                      */
-/* -------------------------------------------------------------------- */
+  int i, file_bands;
+  int *band_list = NULL;
+
+  file_bands = GDALGetRasterCount( hDS );
+  if( file_bands == 0 ) {
+    msSetError( MS_IMGERR,
+                "Attempt to operate on GDAL file with no bands, layer=%s.",
+                "msGetGDALBandList()",
+                layer->name );
+
+    return NULL;
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Use all (or first) bands.                                       */
+  /* -------------------------------------------------------------------- */
+  if( CSLFetchNameValue( layer->processing, "BANDS" ) == NULL ) {
+    if( max_bands > 0 )
+      *band_count = MIN(file_bands,max_bands);
     else
-    {
-        char **papszItems = CSLTokenizeStringComplex( 
-            CSLFetchNameValue(layer->processing,"BANDS"), " ,", FALSE, FALSE );
-
-        if( CSLCount(papszItems) == 0 )
-        {
-            CSLDestroy( papszItems );
-            msSetError( MS_IMGERR, "BANDS PROCESSING directive has no items.",
-                        "msGetGDALBandList()" );
-            return NULL;
-        }
-        else if( max_bands != 0 && CSLCount(papszItems) > max_bands )
-        {
-            msSetError( MS_IMGERR, "BANDS PROCESSING directive has wrong number of bands, expected at most %d, got %d.",
-                        "msGetGDALBandList()",
-                        max_bands, CSLCount(papszItems) );
-            CSLDestroy( papszItems );
-            return NULL;
-        }
-
-        *band_count = CSLCount(papszItems);
-        band_list = (int *) malloc(sizeof(int) * *band_count);
-        MS_CHECK_ALLOC(band_list, sizeof(int) * *band_count, NULL);
-
-        for( i = 0; i < *band_count; i++ )
-        {
-            band_list[i] = atoi(papszItems[i]);
-            if( band_list[i] < 1 || band_list[i] > GDALGetRasterCount(hDS) )
-            {
-                msSetError( MS_IMGERR, 
-                            "BANDS PROCESSING directive includes illegal band '%s', should be from 1 to %d.", 
-                            "msGetGDALBandList()",
-                            papszItems[i], GDALGetRasterCount(hDS) );
-                CSLDestroy( papszItems );
-                CPLFree( band_list );
-                return NULL;
-            }
-        }
+      *band_count = file_bands;
+
+    band_list = (int *) malloc(sizeof(int) * *band_count );
+    MS_CHECK_ALLOC(band_list, sizeof(int) * *band_count, NULL);
+
+    for( i = 0; i < *band_count; i++ )
+      band_list[i] = i+1;
+    return band_list;
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      get bands from BANDS processing directive.                      */
+  /* -------------------------------------------------------------------- */
+  else {
+    char **papszItems = CSLTokenizeStringComplex(
+                          CSLFetchNameValue(layer->processing,"BANDS"), " ,", FALSE, FALSE );
+
+    if( CSLCount(papszItems) == 0 ) {
+      CSLDestroy( papszItems );
+      msSetError( MS_IMGERR, "BANDS PROCESSING directive has no items.",
+                  "msGetGDALBandList()" );
+      return NULL;
+    } else if( max_bands != 0 && CSLCount(papszItems) > max_bands ) {
+      msSetError( MS_IMGERR, "BANDS PROCESSING directive has wrong number of bands, expected at most %d, got %d.",
+                  "msGetGDALBandList()",
+                  max_bands, CSLCount(papszItems) );
+      CSLDestroy( papszItems );
+      return NULL;
+    }
+
+    *band_count = CSLCount(papszItems);
+    band_list = (int *) malloc(sizeof(int) * *band_count);
+    MS_CHECK_ALLOC(band_list, sizeof(int) * *band_count, NULL);
+
+    for( i = 0; i < *band_count; i++ ) {
+      band_list[i] = atoi(papszItems[i]);
+      if( band_list[i] < 1 || band_list[i] > GDALGetRasterCount(hDS) ) {
+        msSetError( MS_IMGERR,
+                    "BANDS PROCESSING directive includes illegal band '%s', should be from 1 to %d.",
+                    "msGetGDALBandList()",
+                    papszItems[i], GDALGetRasterCount(hDS) );
         CSLDestroy( papszItems );
-
-        return band_list;
+        CPLFree( band_list );
+        return NULL;
+      }
     }
+    CSLDestroy( papszItems );
+
+    return band_list;
+  }
 }
 
 #endif /* def USE_GDAL */
diff --git a/mapdummyrenderer.c b/mapdummyrenderer.c
index 72b8179..2092205 100644
--- a/mapdummyrenderer.c
+++ b/mapdummyrenderer.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -29,232 +29,270 @@
 
 #include "mapserver.h"
 
-int renderLineDummy(imageObj *img, shapeObj *p, strokeStyleObj *style) {
-    msSetError(MS_RENDERERERR,"renderLine not implemented","renderLine()");
-    return MS_FAILURE;
+int renderLineDummy(imageObj *img, shapeObj *p, strokeStyleObj *style)
+{
+  msSetError(MS_RENDERERERR,"renderLine not implemented","renderLine()");
+  return MS_FAILURE;
 }
 
-int renderPolygonDummy(imageObj *img, shapeObj *p, colorObj *color) {
-    msSetError(MS_RENDERERERR,"renderPolygon not implemented","renderPolygon()");
-    return MS_FAILURE;
+int renderPolygonDummy(imageObj *img, shapeObj *p, colorObj *color)
+{
+  msSetError(MS_RENDERERERR,"renderPolygon not implemented","renderPolygon()");
+  return MS_FAILURE;
 }
 
-int renderPolygonTiledDummy(imageObj *img, shapeObj *p, imageObj *tile) {
-    msSetError(MS_RENDERERERR,"renderPolygonTiled not implemented","renderPolygonTiled()");
-    return MS_FAILURE;
+int renderPolygonTiledDummy(imageObj *img, shapeObj *p, imageObj *tile)
+{
+  msSetError(MS_RENDERERERR,"renderPolygonTiled not implemented","renderPolygonTiled()");
+  return MS_FAILURE;
 }
 
-int renderLineTiledDummy(imageObj *img, shapeObj *p, imageObj *tile) {
-    msSetError(MS_RENDERERERR,"renderLineTiled not implemented","renderLineTiled()");
-    return MS_FAILURE;
+int renderLineTiledDummy(imageObj *img, shapeObj *p, imageObj *tile)
+{
+  msSetError(MS_RENDERERERR,"renderLineTiled not implemented","renderLineTiled()");
+  return MS_FAILURE;
 }
 
 int renderRasterGlyphsDummy(imageObj *img, double x, double y, int fontIndex,
-        colorObj *color, char* text) {
-    msSetError(MS_RENDERERERR,"renderRasterGlyphs not implemented","renderRasterGlyphs()");
-    return MS_FAILURE;
+                            colorObj *color, char* text)
+{
+  msSetError(MS_RENDERERERR,"renderRasterGlyphs not implemented","renderRasterGlyphs()");
+  return MS_FAILURE;
 }
 
 int renderGlyphsDummy(imageObj *img, double x, double y,
-        labelStyleObj *style, char *text) {
-    msSetError(MS_RENDERERERR,"renderGlyphs not implemented","renderGlyphs()");
-    return MS_FAILURE;
+                      labelStyleObj *style, char *text)
+{
+  msSetError(MS_RENDERERERR,"renderGlyphs not implemented","renderGlyphs()");
+  return MS_FAILURE;
 }
 
 int renderGlyphsLineDummy(imageObj *img,labelPathObj *labelpath,
-        labelStyleObj *style, char *text) {
-    msSetError(MS_RENDERERERR,"renderGlyphsLine not implemented","renderGlyphsLine()");
-    return MS_FAILURE;
+                          labelStyleObj *style, char *text)
+{
+  msSetError(MS_RENDERERERR,"renderGlyphsLine not implemented","renderGlyphsLine()");
+  return MS_FAILURE;
 }
 
 int renderVectorSymbolDummy(imageObj *img, double x, double y,
-        symbolObj *symbol, symbolStyleObj *style) {
-    msSetError(MS_RENDERERERR,"renderVectorSymbol not implemented","renderVectorSymbol()");
-    return MS_FAILURE;
+                            symbolObj *symbol, symbolStyleObj *style)
+{
+  msSetError(MS_RENDERERERR,"renderVectorSymbol not implemented","renderVectorSymbol()");
+  return MS_FAILURE;
 }
 
 void* createVectorSymbolTileDummy(int width, int height,
-        symbolObj *symbol, symbolStyleObj *style) {
-    msSetError(MS_RENDERERERR,"createVectorSymbolTile not implemented","createVectorSymbolTile()");
-    return NULL;
+                                  symbolObj *symbol, symbolStyleObj *style)
+{
+  msSetError(MS_RENDERERERR,"createVectorSymbolTile not implemented","createVectorSymbolTile()");
+  return NULL;
 }
 
 int renderPixmapSymbolDummy(imageObj *img, double x, double y,
-        symbolObj *symbol, symbolStyleObj *style) {
-    msSetError(MS_RENDERERERR,"renderLine not implemented","renderLine()");
-    return MS_FAILURE;
+                            symbolObj *symbol, symbolStyleObj *style)
+{
+  msSetError(MS_RENDERERERR,"renderLine not implemented","renderLine()");
+  return MS_FAILURE;
 }
 
 void* createPixmapSymbolTileDummy(int width, int height,
-        symbolObj *symbol, symbolStyleObj *style) {
-    msSetError(MS_RENDERERERR,"renderLine not implemented","renderLine()");
-    return NULL;
+                                  symbolObj *symbol, symbolStyleObj *style)
+{
+  msSetError(MS_RENDERERERR,"renderLine not implemented","renderLine()");
+  return NULL;
 }
 
-int renderEllipseSymbolDummy(imageObj *image, double x, double y, 
-        symbolObj *symbol, symbolStyleObj *style) {
-    msSetError(MS_RENDERERERR,"renderLine not implemented","renderLine()");
-    return MS_FAILURE;
+int renderEllipseSymbolDummy(imageObj *image, double x, double y,
+                             symbolObj *symbol, symbolStyleObj *style)
+{
+  msSetError(MS_RENDERERERR,"renderLine not implemented","renderLine()");
+  return MS_FAILURE;
 }
 
 void* createEllipseSymbolTileDummy(int width, int height,
-        symbolObj *symbol, symbolStyleObj *style) {
-    msSetError(MS_RENDERERERR,"renderLine not implemented","renderLine()");
-    return NULL;
+                                   symbolObj *symbol, symbolStyleObj *style)
+{
+  msSetError(MS_RENDERERERR,"renderLine not implemented","renderLine()");
+  return NULL;
 }
 
 int renderTruetypeSymbolDummy(imageObj *img, double x, double y,
-        symbolObj *symbol, symbolStyleObj *style) {
-    msSetError(MS_RENDERERERR,"renderLine not implemented","renderLine()");
-    return MS_FAILURE;
+                              symbolObj *symbol, symbolStyleObj *style)
+{
+  msSetError(MS_RENDERERERR,"renderLine not implemented","renderLine()");
+  return MS_FAILURE;
 }
 
 void* createTruetypeSymbolTileDummy(int width, int height,
-        symbolObj *symbol, symbolStyleObj *style) {
-    msSetError(MS_RENDERERERR,"renderLine not implemented","renderLine()");
-    return NULL;
+                                    symbolObj *symbol, symbolStyleObj *style)
+{
+  msSetError(MS_RENDERERERR,"renderLine not implemented","renderLine()");
+  return NULL;
 }
 
-int renderTileDummy(imageObj *img, imageObj *tile, double x, double y) {
-    msSetError(MS_RENDERERERR,"renderLine not implemented","renderLine()");
-    return MS_FAILURE;
+int renderTileDummy(imageObj *img, imageObj *tile, double x, double y)
+{
+  msSetError(MS_RENDERERERR,"renderLine not implemented","renderLine()");
+  return MS_FAILURE;
 }
 
-rasterBufferObj* loadImageFromFileDummy(char *path) {
-    msSetError(MS_RENDERERERR,"loadImageFromFile not implemented","loadImageFromFile()");
-    return NULL;
+rasterBufferObj* loadImageFromFileDummy(char *path)
+{
+  msSetError(MS_RENDERERERR,"loadImageFromFile not implemented","loadImageFromFile()");
+  return NULL;
 }
 
 
-int getRasterBufferHandleDummy(imageObj *img, rasterBufferObj *rb) {
-    msSetError(MS_RENDERERERR,"renderLine not implemented","renderLine()");
-    return MS_FAILURE;
+int getRasterBufferHandleDummy(imageObj *img, rasterBufferObj *rb)
+{
+  msSetError(MS_RENDERERERR,"renderLine not implemented","renderLine()");
+  return MS_FAILURE;
 }
 
-int getRasterBufferCopyDummy(imageObj *img, rasterBufferObj *rb) {
-    msSetError(MS_RENDERERERR,"getRasterBufferCopy not implemented","getRasterBufferCopy()");
-    return MS_FAILURE;
+int getRasterBufferCopyDummy(imageObj *img, rasterBufferObj *rb)
+{
+  msSetError(MS_RENDERERERR,"getRasterBufferCopy not implemented","getRasterBufferCopy()");
+  return MS_FAILURE;
 }
 
-rasterBufferObj* createRasterBufferDummy(int width, int height) {
-    msSetError(MS_RENDERERERR,"createRasterBuffer not implemented","createRasterBuffer()");
-    return NULL;
+rasterBufferObj* createRasterBufferDummy(int width, int height)
+{
+  msSetError(MS_RENDERERERR,"createRasterBuffer not implemented","createRasterBuffer()");
+  return NULL;
 }
 
-int mergeRasterBufferDummy(imageObj *dest, rasterBufferObj *overlay, double opacity, int srcX, int srcY, int dstX, int dstY, int width, int height) {
-    msSetError(MS_RENDERERERR,"mergeRasterBuffer not implemented","mergeRasterBuffer()");
-    return MS_FAILURE;
+int mergeRasterBufferDummy(imageObj *dest, rasterBufferObj *overlay, double opacity, int srcX, int srcY, int dstX, int dstY, int width, int height)
+{
+  msSetError(MS_RENDERERERR,"mergeRasterBuffer not implemented","mergeRasterBuffer()");
+  return MS_FAILURE;
 }
 
-int initializeRasterBufferDummy(rasterBufferObj *rb, int width, int height, int mode) {
-    msSetError(MS_RENDERERERR,"initializeRasterBuffer not implemented","initializeRasterBuffer()");
-    return MS_FAILURE;
+int initializeRasterBufferDummy(rasterBufferObj *rb, int width, int height, int mode)
+{
+  msSetError(MS_RENDERERERR,"initializeRasterBuffer not implemented","initializeRasterBuffer()");
+  return MS_FAILURE;
 }
 
 
 
 /* image i/o */
-imageObj* createImageDummy(int width, int height, outputFormatObj *format, colorObj* bg) {
-    msSetError(MS_RENDERERERR,"createImage not implemented","createImage()");
-    return NULL;
+imageObj* createImageDummy(int width, int height, outputFormatObj *format, colorObj* bg)
+{
+  msSetError(MS_RENDERERERR,"createImage not implemented","createImage()");
+  return NULL;
 }
 
-int saveImageDummy(imageObj *img, FILE *fp, outputFormatObj *format) {
-    msSetError(MS_RENDERERERR,"saveImage not implemented","saveImage()");
-    return MS_FAILURE;
+int saveImageDummy(imageObj *img, mapObj *map, FILE *fp, outputFormatObj *format)
+{
+  msSetError(MS_RENDERERERR,"saveImage not implemented","saveImage()");
+  return MS_FAILURE;
 }
 /*...*/
 
 /* helper functions */
-int getTruetypeTextBBoxDummy(rendererVTableObj *renderer, char *font, double size, char *string,rectObj *rect, double **advances) {
-    msSetError(MS_RENDERERERR,"getTruetypeTextBBox not implemented","getTruetypeTextBBox()");
-    return MS_FAILURE;
-}
-
-int startLayerDummy(imageObj *img, mapObj *map, layerObj *layer) {
-    msSetError(MS_RENDERERERR,"startLayer not implemented","startLayer()");
-    return MS_FAILURE;
-}
-
-int endLayerDummy(imageObj *img, mapObj *map, layerObj *layer) {
-    msSetError(MS_RENDERERERR,"endLayer not implemented","endLayer()");
-    return MS_FAILURE;
-}
-
-int startShapeDummy(imageObj *img, shapeObj *shape) {
-    msSetError(MS_RENDERERERR,"startShape not implemented","startShape()");
-    return MS_FAILURE;
-}
-
-int endShapeDummy(imageObj *img, shapeObj *shape) {
-    msSetError(MS_RENDERERERR,"endShape not implemented","endShape()");
-    return MS_FAILURE;
-}
-
-int setClipDummy(imageObj *img, rectObj clipRect) {
-    msSetError(MS_RENDERERERR,"renderLine not implemented","renderLine()");
-    return MS_FAILURE;
-}
-int resetClipDummy(imageObj *img) {
-    msSetError(MS_RENDERERERR,"resetClip not implemented","resetClip()");
-    return MS_FAILURE;
-}
-
-int freeImageDummy(imageObj *image) {
-    msSetError(MS_RENDERERERR,"freeImage not implemented","freeImage()");
-    return MS_FAILURE;
-}
-
-int freeTileDummy(imageObj *tile) {
-    msSetError(MS_RENDERERERR,"freeTile not implemented","freeTile()");
-    return MS_FAILURE;
-}
-
-int freeSymbolDummy(symbolObj *symbol) {
-    msSetError(MS_RENDERERERR,"freeSymbol not implemented","freeSymbol()");
-    return MS_FAILURE;
-}
-
-int cleanupDummy(void *renderer_data) {
-    return MS_SUCCESS;
-}
-
-int msInitializeDummyRenderer(rendererVTableObj *renderer) {
-    
-    renderer->use_imagecache = 0;
-    renderer->supports_pixel_buffer = 0;
-    renderer->supports_transparent_layers = 0;
-    renderer->supports_clipping = 0;
-    renderer->supports_bitmap_fonts = 0;
-    renderer->renderer_data = NULL;
-    renderer->transform_mode = MS_TRANSFORM_SIMPLIFY;
-    renderer->startLayer = &startLayerDummy;
-    renderer->endLayer = &endLayerDummy;
-    renderer->renderLine=&renderLineDummy;
-    renderer->renderLineTiled = NULL;
-    renderer->createImage=&createImageDummy;
-    renderer->saveImage=&saveImageDummy;
-    renderer->getRasterBufferHandle=&getRasterBufferHandleDummy;
-    renderer->getRasterBufferCopy=getRasterBufferCopyDummy;
-    renderer->initializeRasterBuffer=initializeRasterBufferDummy;
-    renderer->renderPolygon=&renderPolygonDummy;
-    renderer->renderGlyphs=&renderGlyphsDummy;
-    renderer->renderBitmapGlyphs = &renderGlyphsDummy;
-    renderer->freeImage=&freeImageDummy;
-    renderer->renderEllipseSymbol = &renderEllipseSymbolDummy;
-    renderer->renderVectorSymbol = &renderVectorSymbolDummy;
-    renderer->renderTruetypeSymbol = &renderTruetypeSymbolDummy;
-    renderer->renderPixmapSymbol = &renderPixmapSymbolDummy;
-    renderer->mergeRasterBuffer = &mergeRasterBufferDummy;
-    renderer->getTruetypeTextBBox = &getTruetypeTextBBoxDummy;
-    renderer->renderTile = &renderTileDummy;
-    renderer->renderPolygonTiled = &renderPolygonTiledDummy;
-    renderer->freeSymbol = &freeSymbolDummy;
-    renderer->cleanup = &cleanupDummy;
-    renderer->startShape = NULL;
-    renderer->endShape = NULL;
-    renderer->renderPolygonHatched = NULL;
-    return MS_SUCCESS;
+int getTruetypeTextBBoxDummy(rendererVTableObj *renderer, char **fonts, int numfonts, double size,
+                             char *string,rectObj *rect, double **advances, int bAdjustBaseline)
+{
+  msSetError(MS_RENDERERERR,"getTruetypeTextBBox not implemented","getTruetypeTextBBox()");
+  return MS_FAILURE;
+}
+
+int startLayerDummy(imageObj *img, mapObj *map, layerObj *layer)
+{
+  msSetError(MS_RENDERERERR,"startLayer not implemented","startLayer()");
+  return MS_FAILURE;
+}
+
+int endLayerDummy(imageObj *img, mapObj *map, layerObj *layer)
+{
+  msSetError(MS_RENDERERERR,"endLayer not implemented","endLayer()");
+  return MS_FAILURE;
+}
+
+int startShapeDummy(imageObj *img, shapeObj *shape)
+{
+  msSetError(MS_RENDERERERR,"startShape not implemented","startShape()");
+  return MS_FAILURE;
+}
+
+int endShapeDummy(imageObj *img, shapeObj *shape)
+{
+  msSetError(MS_RENDERERERR,"endShape not implemented","endShape()");
+  return MS_FAILURE;
+}
+
+int setClipDummy(imageObj *img, rectObj clipRect)
+{
+  msSetError(MS_RENDERERERR,"renderLine not implemented","renderLine()");
+  return MS_FAILURE;
+}
+int resetClipDummy(imageObj *img)
+{
+  msSetError(MS_RENDERERERR,"resetClip not implemented","resetClip()");
+  return MS_FAILURE;
+}
+
+int freeImageDummy(imageObj *image)
+{
+  msSetError(MS_RENDERERERR,"freeImage not implemented","freeImage()");
+  return MS_FAILURE;
+}
+
+int freeTileDummy(imageObj *tile)
+{
+  msSetError(MS_RENDERERERR,"freeTile not implemented","freeTile()");
+  return MS_FAILURE;
+}
+
+int freeSymbolDummy(symbolObj *symbol)
+{
+  msSetError(MS_RENDERERERR,"freeSymbol not implemented","freeSymbol()");
+  return MS_FAILURE;
+}
+
+int cleanupDummy(void *renderer_data)
+{
+  return MS_SUCCESS;
+}
+
+int msInitializeDummyRenderer(rendererVTableObj *renderer)
+{
+
+  renderer->use_imagecache = 0;
+  renderer->supports_pixel_buffer = 0;
+  renderer->supports_transparent_layers = 0;
+  renderer->supports_clipping = 0;
+  renderer->supports_bitmap_fonts = 0;
+  renderer->supports_svg = 0;
+  renderer->renderer_data = NULL;
+  renderer->transform_mode = MS_TRANSFORM_SIMPLIFY;
+  renderer->startLayer = &startLayerDummy;
+  renderer->endLayer = &endLayerDummy;
+  renderer->renderLine=&renderLineDummy;
+  renderer->renderLineTiled = NULL;
+  renderer->createImage=&createImageDummy;
+  renderer->saveImage=&saveImageDummy;
+  renderer->getRasterBufferHandle=&getRasterBufferHandleDummy;
+  renderer->getRasterBufferCopy=getRasterBufferCopyDummy;
+  renderer->initializeRasterBuffer=initializeRasterBufferDummy;
+  renderer->renderPolygon=&renderPolygonDummy;
+  renderer->renderGlyphs=&renderGlyphsDummy;
+  renderer->renderGlyphsLine = NULL;
+  renderer->renderBitmapGlyphs = &renderGlyphsDummy;
+  renderer->freeImage=&freeImageDummy;
+  renderer->renderEllipseSymbol = &renderEllipseSymbolDummy;
+  renderer->renderVectorSymbol = &renderVectorSymbolDummy;
+  renderer->renderTruetypeSymbol = &renderTruetypeSymbolDummy;
+  renderer->renderPixmapSymbol = &renderPixmapSymbolDummy;
+  renderer->mergeRasterBuffer = &mergeRasterBufferDummy;
+  renderer->getTruetypeTextBBox = &getTruetypeTextBBoxDummy;
+  renderer->renderTile = &renderTileDummy;
+  renderer->renderPolygonTiled = &renderPolygonTiledDummy;
+  renderer->freeSymbol = &freeSymbolDummy;
+  renderer->cleanup = &cleanupDummy;
+  renderer->startShape = NULL;
+  renderer->endShape = NULL;
+  return MS_SUCCESS;
 }
 
 
diff --git a/mapentities.h b/mapentities.h
index e67d4cb..dc28bed 100644
--- a/mapentities.h
+++ b/mapentities.h
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -41,263 +41,263 @@
 extern "C" {
 #endif
 
-static struct mapentities_s {
-	char	*name;
-	int	value;
-} mapentities[] = {
-	{"AElig", 198},
-	{"Aacute", 193},
-	{"Acirc", 194},
-	{"Agrave", 192},
-	{"Alpha", 913},
-	{"Aring", 197},
-	{"Atilde", 195},
-	{"Auml", 196},
-	{"Beta", 914},
-	{"Ccedil", 199},
-	{"Chi", 935},
-	{"Dagger", 8225},
-	{"Delta", 916},
-	{"ETH", 208},
-	{"Eacute", 201},
-	{"Ecirc", 202},
-	{"Egrave", 200},
-	{"Epsilon", 917},
-	{"Eta", 919},
-	{"Euml", 203},
-	{"Gamma", 915},
-	{"Iacute", 205},
-	{"Icirc", 206},
-	{"Igrave", 204},
-	{"Iota", 921},
-	{"Iuml", 207},
-	{"Kappa", 922},
-	{"Lambda", 923},
-	{"Mu", 924},
-	{"Ntilde", 209},
-	{"Nu", 925},
-	{"OElig", 338},
-	{"Oacute", 211},
-	{"Ocirc", 212},
-	{"Ograve", 210},
-	{"Omega", 937},
-	{"Omicron", 927},
-	{"Oslash", 216},
-	{"Otilde", 213},
-	{"Ouml", 214},
-	{"Phi", 934},
-	{"Pi", 928},
-	{"Prime", 8243},
-	{"Psi", 936},
-	{"Rho", 929},
-	{"Scaron", 352},
-	{"Sigma", 931},
-	{"THORN", 222},
-	{"Tau", 932},
-	{"Theta", 920},
-	{"Uacute", 218},
-	{"Ucirc", 219},
-	{"Ugrave", 217},
-	{"Upsilon", 933},
-	{"Uuml", 220},
-	{"Xi", 926},
-	{"Yacute", 221},
-	{"Yuml", 376},
-	{"Zeta", 918},
-	{"aacute", 225},
-	{"acirc", 226},
-	{"acute", 180},
-	{"aelig", 230},
-	{"agrave", 224},
-	{"alefsym", 8501},
-	{"alpha", 945},
-	{"amp", 38},
-	{"and", 8743},
-	{"ang", 8736},
-	{"aring", 229},
-	{"asymp", 8776},
-	{"atilde", 227},
-	{"auml", 228},
-	{"bdquo", 8222},
-	{"beta", 946},
-	{"brvbar", 166},
-	{"bull", 8226},
-	{"cap", 8745},
-	{"ccedil", 231},
-	{"cedil", 184},
-	{"cent", 162},
-	{"chi", 967},
-	{"circ", 710},
-	{"clubs", 9827},
-	{"cong", 8773},
-	{"copy", 169},
-	{"crarr", 8629},
-	{"cup", 8746},
-	{"curren", 164},
-	{"dArr", 8659},
-	{"dagger", 8224},
-	{"darr", 8595},
-	{"deg", 176},
-	{"delta", 948},
-	{"diams", 9830},
-	{"divide", 247},
-	{"eacute", 233},
-	{"ecirc", 234},
-	{"egrave", 232},
-	{"empty", 8709},
-	{"emsp", 8195},
-	{"ensp", 8194},
-	{"epsilon", 949},
-	{"equiv", 8801},
-	{"eta", 951},
-	{"eth", 240},
-	{"euml", 235},
-	{"euro", 8364},
-	{"exist", 8707},
-	{"fnof", 402},
-	{"forall", 8704},
-	{"frac12", 189},
-	{"frac14", 188},
-	{"frac34", 190},
-	{"frasl", 8260},
-	{"gamma", 947},
-	{"ge", 8805},
-	{"gt", 62},
-	{"hArr", 8660},
-	{"harr", 8596},
-	{"hearts", 9829},
-	{"hellip", 8230},
-	{"iacute", 237},
-	{"icirc", 238},
-	{"iexcl", 161},
-	{"igrave", 236},
-	{"image", 8465},
-	{"infin", 8734},
-	{"int", 8747},
-	{"iota", 953},
-	{"iquest", 191},
-	{"isin", 8712},
-	{"iuml", 239},
-	{"kappa", 954},
-	{"lArr", 8656},
-	{"lambda", 955},
-	{"lang", 9001},
-	{"laquo", 171},
-	{"larr", 8592},
-	{"lceil", 8968},
-	{"ldquo", 8220},
-	{"le", 8804},
-	{"lfloor", 8970},
-	{"lowast", 8727},
-	{"loz", 9674},
-	{"lrm", 8206},
-	{"lsaquo", 8249},
-	{"lsquo", 8216},
-	{"lt", 60},
-	{"macr", 175},
-	{"mdash", 8212},
-	{"micro", 181},
-	{"middot", 183},
-	{"minus", 8722},
-	{"mu", 956},
-	{"nabla", 8711},
-	{"nbsp", 160},
-	{"ndash", 8211},
-	{"ne", 8800},
-	{"ni", 8715},
-	{"not", 172},
-	{"notin", 8713},
-	{"nsub", 8836},
-	{"ntilde", 241},
-	{"nu", 957},
-	{"oacute", 243},
-	{"ocirc", 244},
-	{"oelig", 339},
-	{"ograve", 242},
-	{"oline", 8254},
-	{"omega", 969},
-	{"omicron", 959},
-	{"oplus", 8853},
-	{"or", 8744},
-	{"ordf", 170},
-	{"ordm", 186},
-	{"oslash", 248},
-	{"otilde", 245},
-	{"otimes", 8855},
-	{"ouml", 246},
-	{"para", 182},
-	{"part", 8706},
-	{"permil", 8240},
-	{"perp", 8869},
-	{"phi", 966},
-	{"pi", 960},
-	{"piv", 982},
-	{"plusmn", 177},
-	{"pound", 163},
-	{"prime", 8242},
-	{"prod", 8719},
-	{"prop", 8733},
-	{"psi", 968},
-	{"quot", 34},
-	{"rArr", 8658},
-	{"radic", 8730},
-	{"rang", 9002},
-	{"raquo", 187},
-	{"rarr", 8594},
-	{"rceil", 8969},
-	{"rdquo", 8221},
-	{"real", 8476},
-	{"reg", 174},
-	{"rfloor", 8971},
-	{"rho", 961},
-	{"rlm", 8207},
-	{"rsaquo", 8250},
-	{"rsquo", 8217},
-	{"sbquo", 8218},
-	{"scaron", 353},
-	{"sdot", 8901},
-	{"sect", 167},
-	{"shy", 173},
-	{"sigma", 963},
-	{"sigmaf", 962},
-	{"sim", 8764},
-	{"spades", 9824},
-	{"sub", 8834},
-	{"sube", 8838},
-	{"sum", 8721},
-	{"sup", 8835},
-	{"sup1", 185},
-	{"sup2", 178},
-	{"sup3", 179},
-	{"supe", 8839},
-	{"szlig", 223},
-	{"tau", 964},
-	{"there4", 8756},
-	{"theta", 952},
-	{"thetasym", 977},
-	{"thinsp", 8201},
-	{"thorn", 254},
-	{"tilde", 732},
-	{"times", 215},
-	{"trade", 8482},
-	{"uArr", 8657},
-	{"uacute", 250},
-	{"uarr", 8593},
-	{"ucirc", 251},
-	{"ugrave", 249},
-	{"uml", 168},
-	{"upsih", 978},
-	{"upsilon", 965},
-	{"uuml", 252},
-	{"weierp", 8472},
-	{"xi", 958},
-	{"yacute", 253},
-	{"yen", 165},
-	{"yuml", 255},
-	{"zeta", 950},
-	{"zwj", 8205},
-	{"zwnj", 8204},
-};
+  static struct mapentities_s {
+    char  *name;
+    int value;
+  } mapentities[] = {
+    {"AElig", 198},
+    {"Aacute", 193},
+    {"Acirc", 194},
+    {"Agrave", 192},
+    {"Alpha", 913},
+    {"Aring", 197},
+    {"Atilde", 195},
+    {"Auml", 196},
+    {"Beta", 914},
+    {"Ccedil", 199},
+    {"Chi", 935},
+    {"Dagger", 8225},
+    {"Delta", 916},
+    {"ETH", 208},
+    {"Eacute", 201},
+    {"Ecirc", 202},
+    {"Egrave", 200},
+    {"Epsilon", 917},
+    {"Eta", 919},
+    {"Euml", 203},
+    {"Gamma", 915},
+    {"Iacute", 205},
+    {"Icirc", 206},
+    {"Igrave", 204},
+    {"Iota", 921},
+    {"Iuml", 207},
+    {"Kappa", 922},
+    {"Lambda", 923},
+    {"Mu", 924},
+    {"Ntilde", 209},
+    {"Nu", 925},
+    {"OElig", 338},
+    {"Oacute", 211},
+    {"Ocirc", 212},
+    {"Ograve", 210},
+    {"Omega", 937},
+    {"Omicron", 927},
+    {"Oslash", 216},
+    {"Otilde", 213},
+    {"Ouml", 214},
+    {"Phi", 934},
+    {"Pi", 928},
+    {"Prime", 8243},
+    {"Psi", 936},
+    {"Rho", 929},
+    {"Scaron", 352},
+    {"Sigma", 931},
+    {"THORN", 222},
+    {"Tau", 932},
+    {"Theta", 920},
+    {"Uacute", 218},
+    {"Ucirc", 219},
+    {"Ugrave", 217},
+    {"Upsilon", 933},
+    {"Uuml", 220},
+    {"Xi", 926},
+    {"Yacute", 221},
+    {"Yuml", 376},
+    {"Zeta", 918},
+    {"aacute", 225},
+    {"acirc", 226},
+    {"acute", 180},
+    {"aelig", 230},
+    {"agrave", 224},
+    {"alefsym", 8501},
+    {"alpha", 945},
+    {"amp", 38},
+    {"and", 8743},
+    {"ang", 8736},
+    {"aring", 229},
+    {"asymp", 8776},
+    {"atilde", 227},
+    {"auml", 228},
+    {"bdquo", 8222},
+    {"beta", 946},
+    {"brvbar", 166},
+    {"bull", 8226},
+    {"cap", 8745},
+    {"ccedil", 231},
+    {"cedil", 184},
+    {"cent", 162},
+    {"chi", 967},
+    {"circ", 710},
+    {"clubs", 9827},
+    {"cong", 8773},
+    {"copy", 169},
+    {"crarr", 8629},
+    {"cup", 8746},
+    {"curren", 164},
+    {"dArr", 8659},
+    {"dagger", 8224},
+    {"darr", 8595},
+    {"deg", 176},
+    {"delta", 948},
+    {"diams", 9830},
+    {"divide", 247},
+    {"eacute", 233},
+    {"ecirc", 234},
+    {"egrave", 232},
+    {"empty", 8709},
+    {"emsp", 8195},
+    {"ensp", 8194},
+    {"epsilon", 949},
+    {"equiv", 8801},
+    {"eta", 951},
+    {"eth", 240},
+    {"euml", 235},
+    {"euro", 8364},
+    {"exist", 8707},
+    {"fnof", 402},
+    {"forall", 8704},
+    {"frac12", 189},
+    {"frac14", 188},
+    {"frac34", 190},
+    {"frasl", 8260},
+    {"gamma", 947},
+    {"ge", 8805},
+    {"gt", 62},
+    {"hArr", 8660},
+    {"harr", 8596},
+    {"hearts", 9829},
+    {"hellip", 8230},
+    {"iacute", 237},
+    {"icirc", 238},
+    {"iexcl", 161},
+    {"igrave", 236},
+    {"image", 8465},
+    {"infin", 8734},
+    {"int", 8747},
+    {"iota", 953},
+    {"iquest", 191},
+    {"isin", 8712},
+    {"iuml", 239},
+    {"kappa", 954},
+    {"lArr", 8656},
+    {"lambda", 955},
+    {"lang", 9001},
+    {"laquo", 171},
+    {"larr", 8592},
+    {"lceil", 8968},
+    {"ldquo", 8220},
+    {"le", 8804},
+    {"lfloor", 8970},
+    {"lowast", 8727},
+    {"loz", 9674},
+    {"lrm", 8206},
+    {"lsaquo", 8249},
+    {"lsquo", 8216},
+    {"lt", 60},
+    {"macr", 175},
+    {"mdash", 8212},
+    {"micro", 181},
+    {"middot", 183},
+    {"minus", 8722},
+    {"mu", 956},
+    {"nabla", 8711},
+    {"nbsp", 160},
+    {"ndash", 8211},
+    {"ne", 8800},
+    {"ni", 8715},
+    {"not", 172},
+    {"notin", 8713},
+    {"nsub", 8836},
+    {"ntilde", 241},
+    {"nu", 957},
+    {"oacute", 243},
+    {"ocirc", 244},
+    {"oelig", 339},
+    {"ograve", 242},
+    {"oline", 8254},
+    {"omega", 969},
+    {"omicron", 959},
+    {"oplus", 8853},
+    {"or", 8744},
+    {"ordf", 170},
+    {"ordm", 186},
+    {"oslash", 248},
+    {"otilde", 245},
+    {"otimes", 8855},
+    {"ouml", 246},
+    {"para", 182},
+    {"part", 8706},
+    {"permil", 8240},
+    {"perp", 8869},
+    {"phi", 966},
+    {"pi", 960},
+    {"piv", 982},
+    {"plusmn", 177},
+    {"pound", 163},
+    {"prime", 8242},
+    {"prod", 8719},
+    {"prop", 8733},
+    {"psi", 968},
+    {"quot", 34},
+    {"rArr", 8658},
+    {"radic", 8730},
+    {"rang", 9002},
+    {"raquo", 187},
+    {"rarr", 8594},
+    {"rceil", 8969},
+    {"rdquo", 8221},
+    {"real", 8476},
+    {"reg", 174},
+    {"rfloor", 8971},
+    {"rho", 961},
+    {"rlm", 8207},
+    {"rsaquo", 8250},
+    {"rsquo", 8217},
+    {"sbquo", 8218},
+    {"scaron", 353},
+    {"sdot", 8901},
+    {"sect", 167},
+    {"shy", 173},
+    {"sigma", 963},
+    {"sigmaf", 962},
+    {"sim", 8764},
+    {"spades", 9824},
+    {"sub", 8834},
+    {"sube", 8838},
+    {"sum", 8721},
+    {"sup", 8835},
+    {"sup1", 185},
+    {"sup2", 178},
+    {"sup3", 179},
+    {"supe", 8839},
+    {"szlig", 223},
+    {"tau", 964},
+    {"there4", 8756},
+    {"theta", 952},
+    {"thetasym", 977},
+    {"thinsp", 8201},
+    {"thorn", 254},
+    {"tilde", 732},
+    {"times", 215},
+    {"trade", 8482},
+    {"uArr", 8657},
+    {"uacute", 250},
+    {"uarr", 8593},
+    {"ucirc", 251},
+    {"ugrave", 249},
+    {"uml", 168},
+    {"upsih", 978},
+    {"upsilon", 965},
+    {"uuml", 252},
+    {"weierp", 8472},
+    {"xi", 958},
+    {"yacute", 253},
+    {"yen", 165},
+    {"yuml", 255},
+    {"zeta", 950},
+    {"zwj", 8205},
+    {"zwnj", 8204},
+  };
 
 #define MAP_ENTITY_NAME_LENGTH_MAX 8
 #define MAP_NR_OF_ENTITIES 252
diff --git a/maperror.c b/maperror.c
index 9a49db6..8d924b6 100644
--- a/maperror.c
+++ b/maperror.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -32,8 +32,6 @@
 #include "mapthread.h"
 #include "maptime.h"
 
-#include "gdfonts.h"
-
 #include <time.h>
 #ifndef _WIN32
 #include <sys/time.h>
@@ -41,125 +39,121 @@
 #endif
 #include <stdarg.h>
 
-MS_CVSID("$Id$")
+
 
 static char *ms_errorCodes[MS_NUMERRORCODES] = {"",
-						"Unable to access file.",
-						"Memory allocation error.",
-						"Incorrect data type.",
-						"Symbol definition error.",
-						"Regular expression error.",
-						"TrueType Font error.",
-						"DBASE file error.",
-						"GD library error.",
-						"Unknown identifier.",
-						"Premature End-of-File.",
-						"Projection library error.",
-						"General error message.",
-						"CGI error.",
-						"Web application error.",
-						"Image handling error.",
-						"Hash table error.",
-						"Join error.",
-						"Search returned no results.",
-						"Shapefile error.",
-						"Expression parser error.",
-						"SDE error.",
-						"OGR error.",
-						"Query error.",
-						"WMS server error.",
-						"WMS connection error.",
-						"OracleSpatial error.",
-						"WFS server error.",
-						"WFS connection error.",
-						"WMS Map Context error.",
-						"HTTP request error.",
-						"Child array error.",
-						"WCS server error.",
-						"GEOS library error.",
-						"Invalid rectangle.",
-						"Date/time error.",
-						"GML encoding error.",
-						"SOS server error.",
-						"NULL parent pointer error.",
-						"AGG library error.",
-						"OWS error.",
-						"OpenGL renderer error.",
-						"Renderer error."
-};
+    "Unable to access file.",
+    "Memory allocation error.",
+    "Incorrect data type.",
+    "Symbol definition error.",
+    "Regular expression error.",
+    "TrueType Font error.",
+    "DBASE file error.",
+    "GD library error.",
+    "Unknown identifier.",
+    "Premature End-of-File.",
+    "Projection library error.",
+    "General error message.",
+    "CGI error.",
+    "Web application error.",
+    "Image handling error.",
+    "Hash table error.",
+    "Join error.",
+    "Search returned no results.",
+    "Shapefile error.",
+    "Expression parser error.",
+    "SDE error.",
+    "OGR error.",
+    "Query error.",
+    "WMS server error.",
+    "WMS connection error.",
+    "OracleSpatial error.",
+    "WFS server error.",
+    "WFS connection error.",
+    "WMS Map Context error.",
+    "HTTP request error.",
+    "Child array error.",
+    "WCS server error.",
+    "GEOS library error.",
+    "Invalid rectangle.",
+    "Date/time error.",
+    "GML encoding error.",
+    "SOS server error.",
+    "NULL parent pointer error.",
+    "AGG library error.",
+    "OWS error.",
+    "OpenGL renderer error.",
+    "Renderer error."
+                                               };
 
 #ifndef USE_THREAD
 
 errorObj *msGetErrorObj()
 {
-    static errorObj ms_error = {MS_NOERR, "", "", MS_FALSE, NULL};
+  static errorObj ms_error = {MS_NOERR, "", "", MS_FALSE, NULL};
 
-    return &ms_error;
+  return &ms_error;
 }
 #endif
 
 #ifdef USE_THREAD
 
-typedef struct te_info
-{
-    struct te_info *next;
-    int             thread_id;
-    errorObj        ms_error;
+typedef struct te_info {
+  struct te_info *next;
+  int             thread_id;
+  errorObj        ms_error;
 } te_info_t;
 
 static te_info_t *error_list = NULL;
 
 errorObj *msGetErrorObj()
 {
-    te_info_t *link;
-    int        thread_id;
-    errorObj   *ret_obj;
-    
-    msAcquireLock( TLOCK_ERROROBJ );
-    
-    thread_id = msGetThreadId();
+  te_info_t *link;
+  int        thread_id;
+  errorObj   *ret_obj;
 
-    /* find link for this thread */
-    
-    for( link = error_list; 
-         link != NULL && link->thread_id != thread_id
-             && link->next != NULL && link->next->thread_id != thread_id;
-         link = link->next ) {}
+  msAcquireLock( TLOCK_ERROROBJ );
 
-    /* If the target thread link is already at the head of the list were ok */
-    if( error_list != NULL && error_list->thread_id == thread_id )
-    {
-    }
+  thread_id = msGetThreadId();
 
-    /* We don't have one ... initialize one. */
-    else if( link == NULL || link->next == NULL )
-    {
-        te_info_t *new_link;
-        errorObj   error_obj = { MS_NOERR, "", "", NULL };
+  /* find link for this thread */
 
-        new_link = (te_info_t *) malloc(sizeof(te_info_t));
-        new_link->next = error_list;
-        new_link->thread_id = thread_id;
-        new_link->ms_error = error_obj;
+  for( link = error_list;
+       link != NULL && link->thread_id != thread_id
+       && link->next != NULL && link->next->thread_id != thread_id;
+       link = link->next ) {}
 
-        error_list = new_link;
-    }
+  /* If the target thread link is already at the head of the list were ok */
+  if( error_list != NULL && error_list->thread_id == thread_id ) {
+  }
 
-    /* If the link is not already at the head of the list, promote it */
-    else if( link != NULL && link->next != NULL )
-    {
-        te_info_t *target = link->next;
+  /* We don't have one ... initialize one. */
+  else if( link == NULL || link->next == NULL ) {
+    te_info_t *new_link;
+    errorObj   error_obj = { MS_NOERR, "", "", 0 };
 
-        link->next = link->next->next;
-        target->next = error_list;
-        error_list = target;
-    }
+    new_link = (te_info_t *) malloc(sizeof(te_info_t));
+    new_link->next = error_list;
+    new_link->thread_id = thread_id;
+    new_link->ms_error = error_obj;
+
+    error_list = new_link;
+  }
+
+  /* If the link is not already at the head of the list, promote it */
+  else if( link != NULL && link->next != NULL ) {
+    te_info_t *target = link->next;
+
+    link->next = link->next->next;
+    target->next = error_list;
+    error_list = target;
+  }
 
-    ret_obj = &(error_list->ms_error);
+  ret_obj = &(error_list->ms_error);
 
-    msReleaseLock( TLOCK_ERROROBJ ); 
+  msReleaseLock( TLOCK_ERROROBJ );
 
-    return ret_obj;
+  return ret_obj;
 }
 #endif
 
@@ -174,7 +168,7 @@ errorObj *msGetErrorObj()
 ** and never changes.
 ** A new errorObj is always inserted after the head, and only if the
 ** head of the list already contains some information.  i.e. If the static
-** errorObj at the head of the list is empty then it is returned directly, 
+** errorObj at the head of the list is empty then it is returned directly,
 ** otherwise a new object is inserted after the head and the data that was in
 ** the head is moved to the new errorObj, freeing the head errorObj to receive
 ** the new error information.
@@ -184,33 +178,31 @@ static errorObj *msInsertErrorObj(void)
   errorObj *ms_error;
   ms_error = msGetErrorObj();
 
-  if (ms_error->code != MS_NOERR)
-  {
-      /* Head of the list already in use, insert a new errorObj after the head
-       * and move head contents to this new errorObj, freeing the errorObj
-       * for reuse.
-       */
-      errorObj *new_error;
-      new_error = (errorObj *)malloc(sizeof(errorObj));
-
-      /* Note: if malloc() failed then we simply do nothing and the head will
-       * be overwritten by the caller... we cannot produce an error here 
-       * since we are already inside a msSetError() call.
-       */
-      if (new_error)
-      {
-          new_error->next = ms_error->next;
-          new_error->code = ms_error->code;
-          new_error->isreported = ms_error->isreported;
-          strlcpy(new_error->routine, ms_error->routine, sizeof(new_error->routine));
-          strlcpy(new_error->message, ms_error->message, sizeof(new_error->message));
-
-          ms_error->next = new_error;
-          ms_error->code = MS_NOERR;
-          ms_error->isreported = MS_FALSE;
-          ms_error->routine[0] = '\0';
-          ms_error->message[0] = '\0';
-      }
+  if (ms_error->code != MS_NOERR) {
+    /* Head of the list already in use, insert a new errorObj after the head
+     * and move head contents to this new errorObj, freeing the errorObj
+     * for reuse.
+     */
+    errorObj *new_error;
+    new_error = (errorObj *)malloc(sizeof(errorObj));
+
+    /* Note: if malloc() failed then we simply do nothing and the head will
+     * be overwritten by the caller... we cannot produce an error here
+     * since we are already inside a msSetError() call.
+     */
+    if (new_error) {
+      new_error->next = ms_error->next;
+      new_error->code = ms_error->code;
+      new_error->isreported = ms_error->isreported;
+      strlcpy(new_error->routine, ms_error->routine, sizeof(new_error->routine));
+      strlcpy(new_error->message, ms_error->message, sizeof(new_error->message));
+
+      ms_error->next = new_error;
+      ms_error->code = MS_NOERR;
+      ms_error->isreported = MS_FALSE;
+      ms_error->routine[0] = '\0';
+      ms_error->message[0] = '\0';
+    }
   }
 
   return ms_error;
@@ -226,13 +218,12 @@ void msResetErrorList()
   ms_error = msGetErrorObj();
 
   this_error = ms_error->next;
-  while( this_error != NULL)
-  {
-      errorObj *next_error;
+  while( this_error != NULL) {
+    errorObj *next_error;
 
-      next_error = this_error->next;
-      msFree(this_error);
-      this_error = next_error;
+    next_error = this_error->next;
+    msFree(this_error);
+    this_error = next_error;
   }
 
   ms_error->next = NULL;
@@ -240,45 +231,43 @@ void msResetErrorList()
   ms_error->routine[0] = '\0';
   ms_error->message[0] = '\0';
 
-/* -------------------------------------------------------------------- */
-/*      Cleanup our entry in the thread list.  This is mainly           */
-/*      imprortant when msCleanup() calls msResetErrorList().           */
-/* -------------------------------------------------------------------- */
+  /* -------------------------------------------------------------------- */
+  /*      Cleanup our entry in the thread list.  This is mainly           */
+  /*      imprortant when msCleanup() calls msResetErrorList().           */
+  /* -------------------------------------------------------------------- */
 #ifdef USE_THREAD
   {
-      int  thread_id = msGetThreadId();
-      te_info_t *link;
-
-      msAcquireLock( TLOCK_ERROROBJ );
-      
-      /* find link for this thread */
-    
-      for( link = error_list; 
-           link != NULL && link->thread_id != thread_id
-               && link->next != NULL && link->next->thread_id != thread_id;
-           link = link->next ) {}
-      
-      if( link->thread_id == thread_id )
-      { 
-          /* presumably link is at head of list.  */
-          if( error_list == link )
-              error_list = link->next;
-
-          free( link );
-      }
-      else if( link->next != NULL && link->next->thread_id == thread_id )
-      {
-          te_info_t *next_link = link->next;
-          link->next = link->next->next;
-          free( next_link );
-      }
-      msReleaseLock( TLOCK_ERROROBJ );
+    int  thread_id = msGetThreadId();
+    te_info_t *link;
+
+    msAcquireLock( TLOCK_ERROROBJ );
+
+    /* find link for this thread */
+
+    for( link = error_list;
+         link != NULL && link->thread_id != thread_id
+         && link->next != NULL && link->next->thread_id != thread_id;
+         link = link->next ) {}
+
+    if( link->thread_id == thread_id ) {
+      /* presumably link is at head of list.  */
+      if( error_list == link )
+        error_list = link->next;
+
+      free( link );
+    } else if( link->next != NULL && link->next->thread_id == thread_id ) {
+      te_info_t *next_link = link->next;
+      link->next = link->next->next;
+      free( next_link );
+    }
+    msReleaseLock( TLOCK_ERROROBJ );
   }
 #endif
 }
 
-char *msGetErrorCodeString(int code) {
-  
+char *msGetErrorCodeString(int code)
+{
+
   if(code<0 || code>MS_NUMERRORCODES-1)
     return("Invalid error code.");
 
@@ -292,15 +281,15 @@ char *msGetErrorCodeString(int code) {
 /* -------------------------------------------------------------------- */
 char *msAddErrorDisplayString(char *source, errorObj *error)
 {
-	if((source = msStringConcatenate(source, error->routine)) == NULL) return(NULL);
-	if((source = msStringConcatenate(source, ": ")) == NULL) return(NULL);
-	if((source = msStringConcatenate(source, ms_errorCodes[error->code])) == NULL) return(NULL);
-	if((source = msStringConcatenate(source, " ")) == NULL) return(NULL);
-	if((source = msStringConcatenate(source, error->message)) == NULL) return(NULL);
-	return source;
+  if((source = msStringConcatenate(source, error->routine)) == NULL) return(NULL);
+  if((source = msStringConcatenate(source, ": ")) == NULL) return(NULL);
+  if((source = msStringConcatenate(source, ms_errorCodes[error->code])) == NULL) return(NULL);
+  if((source = msStringConcatenate(source, " ")) == NULL) return(NULL);
+  if((source = msStringConcatenate(source, error->message)) == NULL) return(NULL);
+  return source;
 }
 
-char *msGetErrorString(char *delimiter) 
+char *msGetErrorString(char *delimiter)
 {
   char *errstr=NULL;
 
@@ -310,11 +299,11 @@ char *msGetErrorString(char *delimiter)
 
   while(error && error->code != MS_NOERR) {
     if((errstr = msAddErrorDisplayString(errstr, error)) == NULL) return(NULL);
-	 
-	if(error->next && error->next->code != MS_NOERR) { /* (peek ahead) more errors, use delimiter */
-		if((errstr = msStringConcatenate(errstr, delimiter)) == NULL) return(NULL);
-	}
-    error = error->next;   
+
+    if(error->next && error->next->code != MS_NOERR) { /* (peek ahead) more errors, use delimiter */
+      if((errstr = msStringConcatenate(errstr, delimiter)) == NULL) return(NULL);
+    }
+    error = error->next;
   }
 
   return(errstr);
@@ -335,8 +324,7 @@ void msSetError(int code, const char *message_fmt, const char *routine, ...)
 
   if(!message_fmt)
     strcpy(ms_error->message, "");
-  else
-  {
+  else {
     va_start(args, routine);
     vsnprintf( ms_error->message, MESSAGELENGTH, message_fmt, args );
     va_end(args);
@@ -351,11 +339,10 @@ void msWriteError(FILE *stream)
 {
   errorObj *ms_error = msGetErrorObj();
 
-  while (ms_error && ms_error->code != MS_NOERR)
-  {
-      msIO_fprintf(stream, "%s: %s %s <br>\n", ms_error->routine, ms_errorCodes[ms_error->code], ms_error->message);
-      ms_error->isreported = MS_TRUE;
-      ms_error = ms_error->next;
+  while (ms_error && ms_error->code != MS_NOERR) {
+    msIO_fprintf(stream, "%s: %s %s <br>\n", ms_error->routine, ms_errorCodes[ms_error->code], ms_error->message);
+    ms_error->isreported = MS_TRUE;
+    ms_error = ms_error->next;
   }
 }
 
@@ -364,20 +351,20 @@ void msWriteErrorXML(FILE *stream)
   char *message;
   errorObj *ms_error = msGetErrorObj();
 
-  while (ms_error && ms_error->code != MS_NOERR)
-  {
-      message = msEncodeHTMLEntities(ms_error->message);
+  while (ms_error && ms_error->code != MS_NOERR) {
+    message = msEncodeHTMLEntities(ms_error->message);
 
-      msIO_fprintf(stream, "%s: %s %s\n", ms_error->routine, 
-                   ms_errorCodes[ms_error->code], message);
-      ms_error->isreported = MS_TRUE;
-      ms_error = ms_error->next;
+    msIO_fprintf(stream, "%s: %s %s\n", ms_error->routine,
+                 ms_errorCodes[ms_error->code], message);
+    ms_error->isreported = MS_TRUE;
+    ms_error = ms_error->next;
 
-      msFree(message);
+    msFree(message);
   }
 }
 
-void msWriteErrorImage(mapObj *map, char *filename, int blank) {
+void msWriteErrorImage(mapObj *map, char *filename, int blank)
+{
   imageObj *img;
   rendererVTableObj *renderer;
   int font_index = 0;
@@ -397,112 +384,124 @@ void msWriteErrorImage(mapObj *map, char *filename, int blank) {
   int nWidthTxt = 0;
   outputFormatObj *format = NULL;
   char *errormsg = msGetErrorString("; ");
+  errorObj *error = msGetErrorObj();
   fontMetrics *font = NULL;
   char *imagepath = NULL, *imageurl = NULL;
   labelStyleObj ls;
   colorObj labelcolor, labeloutlinecolor, imagecolor, *imagecolorptr=NULL;
   ls.color = &labelcolor;
   ls.outlinecolor = &labeloutlinecolor;
-  
+  if(!errormsg) {
+    errormsg = msStrdup("No error found sorry. This is likely a bug");
+  }
+
   if (map) {
-      if( map->width > 0 && map->height > 0 )
-      {
-          width = map->width;
-          height = map->height;
-      }
-      format = map->outputformat;
-      imagepath = map->web.imagepath;
-      imageurl = map->web.imageurl;
+    if( map->width > 0 && map->height > 0 ) {
+      width = map->width;
+      height = map->height;
+    }
+    format = map->outputformat;
+    imagepath = map->web.imagepath;
+    imageurl = map->web.imageurl;
   }
 
   /* Default to GIF if no suitable GD output format set */
-  if (format == NULL || !MS_RENDERER_PLUGIN(format) || !format->vtable->supports_bitmap_fonts) 
-    format = msCreateDefaultOutputFormat( NULL, "GD/PC256", "gif" );
+  if (format == NULL || !MS_RENDERER_PLUGIN(format) || !format->vtable->supports_bitmap_fonts)
+    format = msCreateDefaultOutputFormat( NULL, "AGG/PNG8", "png" );
 
   if(!format->transparent) {
-     if(map && MS_VALID_COLOR(map->imagecolor)) {
-        imagecolorptr = &map->imagecolor;
-     } else {
-         MS_INIT_COLOR(imagecolor,255,255,255,255);
-         imagecolorptr = &imagecolor;
-     }
+    if(map && MS_VALID_COLOR(map->imagecolor)) {
+      imagecolorptr = &map->imagecolor;
+    } else {
+      MS_INIT_COLOR(imagecolor,255,255,255,255);
+      imagecolorptr = &imagecolor;
+    }
   }
 
   img = msImageCreate(width,height,format,imagepath,imageurl,MS_DEFAULT_RESOLUTION,MS_DEFAULT_RESOLUTION,imagecolorptr);
   renderer = MS_IMAGE_RENDERER(img);
 
-  for(i=0;i<5;i++) {
-	  /* use the first font we find */
-	  if((font = renderer->bitmapFontMetrics[font_index]) != NULL) {
-	     ls.size = i;
-         MS_INIT_COLOR(*ls.color,0,0,0,255);
-         MS_INIT_COLOR(*ls.outlinecolor,255,255,255,255);
-         break;
-	  }
+  for(i=0; i<5; i++) {
+    /* use the first font we find */
+    if((font = renderer->bitmapFontMetrics[font_index]) != NULL) {
+      ls.size = i;
+      MS_INIT_COLOR(*ls.color,0,0,0,255);
+      MS_INIT_COLOR(*ls.outlinecolor,255,255,255,255);
+      ls.outlinewidth = 1;
+      break;
+    }
   }
   /* if no font found we can't do much. this shouldn't happen */
   if(font) {
-	  
-	  nTextLength = strlen(errormsg); 
-	  nWidthTxt  =  nTextLength * font->charWidth;
-	  nUsableWidth = width - (nMargin*2);
-	
-	  /* Check to see if it all fits on one line. If not, split the text on several lines. */
-	  if(!blank) {
-		if (nWidthTxt > nUsableWidth) {
-		  nMaxCharsPerLine =  nUsableWidth/font->charWidth;
-		  nLines = (int) ceil ((double)nTextLength / (double)nMaxCharsPerLine);
-		  if (nLines > 0) {
-			papszLines = (char **)malloc(nLines*sizeof(char *));
-			for (i=0; i<nLines; i++) {
-			  papszLines[i] = (char *)malloc((nMaxCharsPerLine+1)*sizeof(char));
-			  papszLines[i][0] = '\0';
-			}
-		  }
-		  for (i=0; i<nLines; i++) {
-			nStart = i*nMaxCharsPerLine;
-			nEnd = nStart + nMaxCharsPerLine;
-			if (nStart < nTextLength) {
-			  if (nEnd > nTextLength)
-				nEnd = nTextLength;
-			  nLength = nEnd-nStart;
-	
-			  strncpy(papszLines[i], errormsg+nStart, nLength);
-			  papszLines[i][nLength] = '\0';
-			}
-		  }
-		} else {
-		  nLines = 1;
-		  papszLines = (char **)malloc(nLines*sizeof(char *));
-		  papszLines[0] = msStrdup(errormsg);
-		}   
-		for (i=0; i<nLines; i++) {
-		  nYPos = (font->charHeight) * ((i*2) +1); 
-		  nXPos = font->charWidth;;
-		  renderer->renderBitmapGlyphs(img, nXPos, nYPos, &ls, papszLines[i]); 
-		}
-		if (papszLines) {
-		  for (i=0; i<nLines; i++) {
-		free(papszLines[i]);
-		  }
-		  free(papszLines);
-		}
-	  }
+
+    nTextLength = strlen(errormsg);
+    nWidthTxt  =  nTextLength * font->charWidth;
+    nUsableWidth = width - (nMargin*2);
+
+    /* Check to see if it all fits on one line. If not, split the text on several lines. */
+    if(!blank) {
+      if (nWidthTxt > nUsableWidth) {
+        nMaxCharsPerLine =  nUsableWidth/font->charWidth;
+        nLines = (int) ceil ((double)nTextLength / (double)nMaxCharsPerLine);
+        if (nLines > 0) {
+          papszLines = (char **)malloc(nLines*sizeof(char *));
+          for (i=0; i<nLines; i++) {
+            papszLines[i] = (char *)malloc((nMaxCharsPerLine+1)*sizeof(char));
+            papszLines[i][0] = '\0';
+          }
+        }
+        for (i=0; i<nLines; i++) {
+          nStart = i*nMaxCharsPerLine;
+          nEnd = nStart + nMaxCharsPerLine;
+          if (nStart < nTextLength) {
+            if (nEnd > nTextLength)
+              nEnd = nTextLength;
+            nLength = nEnd-nStart;
+
+            strncpy(papszLines[i], errormsg+nStart, nLength);
+            papszLines[i][nLength] = '\0';
+          }
+        }
+      } else {
+        nLines = 1;
+        papszLines = (char **)malloc(nLines*sizeof(char *));
+        papszLines[0] = msStrdup(errormsg);
+      }
+      for (i=0; i<nLines; i++) {
+        nYPos = (font->charHeight) * ((i*2) +1);
+        nXPos = font->charWidth;;
+        renderer->renderBitmapGlyphs(img, nXPos, nYPos, &ls, papszLines[i]);
+      }
+      if (papszLines) {
+        for (i=0; i<nLines; i++) {
+          free(papszLines[i]);
+        }
+        free(papszLines);
+      }
+    }
   }
 
   /* actually write the image */
   if(!filename) {
-      msIO_printf("Content-type: %s%c%c", MS_IMAGE_MIME_TYPE(format), 10,10);
+    msIO_setHeader("Content-Type","%s", MS_IMAGE_MIME_TYPE(format));
+    msIO_sendHeaders();
   }
   msSaveImage(NULL,img,filename);
   msFreeImage(img);
 
+  /* the errors are reported */
+  while(error && error->code != MS_NOERR) {
+    error->isreported = MS_TRUE;
+    error = error->next;
+  }
+
   if (format->refcount == 0)
     msFreeOutputFormat(format);
-  msFree(errormsg);  
+  msFree(errormsg);
 }
 
-char *msGetVersion() {
+char *msGetVersion()
+{
   static char version[1024];
 
   sprintf(version, "MapServer version %s", MS_VERSION);
@@ -510,10 +509,10 @@ char *msGetVersion() {
 #ifdef USE_GD_GIF
   strcat(version, " OUTPUT=GIF");
 #endif
-#ifdef USE_GD_PNG
+#if (defined USE_GD_PNG || defined USE_PNG)
   strcat(version, " OUTPUT=PNG");
 #endif
-#ifdef USE_GD_JPEG
+#if (defined USE_GD_JPEG || defined USE_JPEG)
   strcat(version, " OUTPUT=JPEG");
 #endif
 #ifdef USE_PDF
@@ -525,19 +524,26 @@ char *msGetVersion() {
 #ifdef USE_PROJ
   strcat(version, " SUPPORTS=PROJ");
 #endif
+#ifdef USE_GD
+  strcat(version, " SUPPORTS=GD");
+#endif
   strcat(version, " SUPPORTS=AGG");
+  strcat(version, " SUPPORTS=FREETYPE");
 #ifdef USE_CAIRO
   strcat(version, " SUPPORTS=CAIRO");
 #endif
+#ifdef USE_SVG_CAIRO
+  strcat(version, " SUPPORTS=SVG_SYMBOLS");
+#endif
 #ifdef USE_OGL
   strcat(version, " SUPPORTS=OPENGL");
 #endif
-#ifdef USE_GD_FT
-  strcat(version, " SUPPORTS=FREETYPE");
-#endif
 #ifdef USE_ICONV
   strcat(version, " SUPPORTS=ICONV");
 #endif
+#ifdef USE_EXEMPI
+  strcat(version, " SUPPORTS=XMP");
+#endif
 #ifdef USE_FRIBIDI
   strcat(version, " SUPPORTS=FRIBIDI");
 #endif
@@ -587,7 +593,7 @@ char *msGetVersion() {
   strcat(version, " INPUT=POSTGIS");
 #endif
 #ifdef USE_ORACLESPATIAL
-  strcat(version, " INPUT=ORACLESPATIAL"); 
+  strcat(version, " INPUT=ORACLESPATIAL");
 #endif
 #ifdef USE_OGR
   strcat(version, " INPUT=OGR");
@@ -599,7 +605,7 @@ char *msGetVersion() {
   return(version);
 }
 
-int msGetVersionInt() 
+int msGetVersionInt()
 {
-    return MS_VERSION_NUM;
+  return MS_VERSION_NUM;
 }
diff --git a/maperror.h b/maperror.h
index f71c529..fe6bf4d 100644
--- a/maperror.h
+++ b/maperror.h
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -34,12 +34,12 @@
 extern "C" {
 #endif
 
-/*====================================================================
- *   maperror.c
- *====================================================================*/
+  /*====================================================================
+   *   maperror.c
+   *====================================================================*/
 
 #define MS_NOERR 0 /* general error codes */
-#define MS_IOERR 1 
+#define MS_IOERR 1
 #define MS_MEMERR 2
 #define MS_TYPEERR 3
 #define MS_SYMERR 4
@@ -94,60 +94,59 @@ extern "C" {
 #define  MS_DLL_EXPORT
 #endif
 
-typedef struct error_obj {
-  int code;
-  char routine[ROUTINELENGTH];
-  char message[MESSAGELENGTH];
-  int isreported;
+  typedef struct errorObj {
+    int code;
+    char routine[ROUTINELENGTH];
+    char message[MESSAGELENGTH];
+    int isreported;
 #ifndef SWIG
-  struct error_obj *next;
+    struct errorObj *next;
 #endif
-} errorObj;
+  } errorObj;
 
-/*
-** Function prototypes
-*/
-MS_DLL_EXPORT errorObj *msGetErrorObj(void);
-MS_DLL_EXPORT void msResetErrorList(void);
-MS_DLL_EXPORT char *msGetVersion(void);
-MS_DLL_EXPORT int  msGetVersionInt(void);
-MS_DLL_EXPORT char *msGetErrorString(char *delimiter);
+  /*
+  ** Function prototypes
+  */
+  MS_DLL_EXPORT errorObj *msGetErrorObj(void);
+  MS_DLL_EXPORT void msResetErrorList(void);
+  MS_DLL_EXPORT char *msGetVersion(void);
+  MS_DLL_EXPORT int  msGetVersionInt(void);
+  MS_DLL_EXPORT char *msGetErrorString(char *delimiter);
 
 #ifndef SWIG
-MS_DLL_EXPORT void msSetError(int code, const char *message, const char *routine, ...);
-MS_DLL_EXPORT void msWriteError(FILE *stream);
-MS_DLL_EXPORT void msWriteErrorXML(FILE *stream);
-MS_DLL_EXPORT char *msGetErrorCodeString(int code);
-MS_DLL_EXPORT char *msAddErrorDisplayString(char *source, errorObj *error);
+  MS_DLL_EXPORT void msSetError(int code, const char *message, const char *routine, ...);
+  MS_DLL_EXPORT void msWriteError(FILE *stream);
+  MS_DLL_EXPORT void msWriteErrorXML(FILE *stream);
+  MS_DLL_EXPORT char *msGetErrorCodeString(int code);
+  MS_DLL_EXPORT char *msAddErrorDisplayString(char *source, errorObj *error);
 
-struct map_obj;
-MS_DLL_EXPORT void msWriteErrorImage(struct map_obj *map, char *filename, int blank);
+  struct mapObj;
+  MS_DLL_EXPORT void msWriteErrorImage(struct mapObj *map, char *filename, int blank);
 
 #endif /* SWIG */
 
-/*====================================================================
- *   mapdebug.c (See also MS-RFC-28)
- *====================================================================*/
+  /*====================================================================
+   *   mapdebug.c (See also MS-RFC-28)
+   *====================================================================*/
 
-typedef enum { MS_DEBUGLEVEL_ERRORSONLY = 0,  /* DEBUG OFF, log fatal errors */
-               MS_DEBUGLEVEL_DEBUG      = 1,  /* DEBUG ON */
-               MS_DEBUGLEVEL_TUNING     = 2,  /* Reports timing info */
-               MS_DEBUGLEVEL_V          = 3,  /* Verbose */
-               MS_DEBUGLEVEL_VV         = 4,  /* Very verbose */
-               MS_DEBUGLEVEL_VVV        = 5   /* Very very verbose */
-} debugLevel;
+  typedef enum { MS_DEBUGLEVEL_ERRORSONLY = 0,  /* DEBUG OFF, log fatal errors */
+                 MS_DEBUGLEVEL_DEBUG      = 1,  /* DEBUG ON */
+                 MS_DEBUGLEVEL_TUNING     = 2,  /* Reports timing info */
+                 MS_DEBUGLEVEL_V          = 3,  /* Verbose */
+                 MS_DEBUGLEVEL_VV         = 4,  /* Very verbose */
+                 MS_DEBUGLEVEL_VVV        = 5   /* Very very verbose */
+               } debugLevel;
 
 #ifndef SWIG
 
-typedef enum { MS_DEBUGMODE_OFF,
-               MS_DEBUGMODE_FILE,
-               MS_DEBUGMODE_STDERR,
-               MS_DEBUGMODE_STDOUT,
-               MS_DEBUGMODE_WINDOWSDEBUG
-} debugMode;
+  typedef enum { MS_DEBUGMODE_OFF,
+                 MS_DEBUGMODE_FILE,
+                 MS_DEBUGMODE_STDERR,
+                 MS_DEBUGMODE_STDOUT,
+                 MS_DEBUGMODE_WINDOWSDEBUG
+               } debugMode;
 
-typedef struct debug_info_obj 
-{
+  typedef struct debug_info_obj {
     debugLevel  global_debug_level;
     debugMode   debug_mode;
     char        *errorfile;
@@ -155,17 +154,17 @@ typedef struct debug_info_obj
     /* The following 2 members are used only with USE_THREAD (but we won't #ifndef them) */
     int         thread_id;
     struct debug_info_obj *next;
-} debugInfoObj;
+  } debugInfoObj;
 
 
-MS_DLL_EXPORT void msDebug( const char * pszFormat, ... );
-MS_DLL_EXPORT int msSetErrorFile(const char *pszErrorFile, const char *pszRelToPath);
-MS_DLL_EXPORT void msCloseErrorFile( void );
-MS_DLL_EXPORT const char *msGetErrorFile( void );
-MS_DLL_EXPORT void msSetGlobalDebugLevel(int level);
-MS_DLL_EXPORT debugLevel msGetGlobalDebugLevel( void );
-MS_DLL_EXPORT int msDebugInitFromEnv( void );
-MS_DLL_EXPORT void msDebugCleanup( void );
+  MS_DLL_EXPORT void msDebug( const char * pszFormat, ... );
+  MS_DLL_EXPORT int msSetErrorFile(const char *pszErrorFile, const char *pszRelToPath);
+  MS_DLL_EXPORT void msCloseErrorFile( void );
+  MS_DLL_EXPORT const char *msGetErrorFile( void );
+  MS_DLL_EXPORT void msSetGlobalDebugLevel(int level);
+  MS_DLL_EXPORT debugLevel msGetGlobalDebugLevel( void );
+  MS_DLL_EXPORT int msDebugInitFromEnv( void );
+  MS_DLL_EXPORT void msDebugCleanup( void );
 
 #endif /* SWIG */
 
diff --git a/mapfile.c b/mapfile.c
index e31c39a..7b8759b 100644
--- a/mapfile.c
+++ b/mapfile.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -37,14 +37,13 @@
 #include "mapfile.h"
 #include "mapthread.h"
 #include "maptime.h"
-#include "mapaxisorder.h"
 
 #ifdef USE_GDAL
 #  include "cpl_conv.h"
 #  include "gdal.h"
 #endif
 
-MS_CVSID("$Id$")
+
 
 extern int msyylex(void);
 extern void msyyrestart(FILE *);
@@ -67,27 +66,10 @@ extern void writeSymbol(symbolObj *s, FILE *stream); /* in mapsymbol.c */
 static int loadGrid( layerObj *pLayer );
 static int loadStyle(styleObj *style);
 static void writeStyle(FILE* stream, int indent, styleObj *style);
-static int msResolveSymbolNames(mapObj *map);
-
-
-/************************************************************************/
-/*                           int msIsAxisInverted                       */
-/*      check to see if we shoudl invert the axis.                      */
-/*                                                                      */
-/************************************************************************/
-static int msIsAxisInverted(int epsg_code)
-{
-    int i;
-    /*check the static table*/
-    for (i=0; i<AXIS_ORIENTATION_TABLE_SIZE; i++)
-    {
-        if (axisOrientationEpsgCodes[i].code == epsg_code)
-          return MS_TRUE;
-    }
+static int resolveSymbolNames(mapObj *map);
+static int loadExpression(expressionObj *exp);
+static void writeExpression(FILE *stream, int indent, const char *name, expressionObj *exp);
 
-    return MS_FALSE;
-    
-}
 
 /*
 ** Symbol to string static arrays needed for writing map files.
@@ -109,7 +91,8 @@ char *msPositionsText[MS_POSITIONS_LENGTH] = {"UL", "LR", "UR", "LL", "CR", "CL"
 ** Validates a string (value) against a series of patterns. We support up to four to allow cascading from classObj to
 ** layerObj to webObj plus a legacy pattern like TEMPLATEPATTERN or qstring_validation_pattern.
 */
-int msValidateParameter(char *value, char *pattern1, char *pattern2, char *pattern3, char *pattern4) {
+int msValidateParameter(char *value, char *pattern1, char *pattern2, char *pattern3, char *pattern4)
+{
   if(msEvalRegex(pattern1, value) == MS_TRUE) return MS_SUCCESS;
   if(msEvalRegex(pattern2, value) == MS_TRUE) return MS_SUCCESS;
   if(msEvalRegex(pattern3, value) == MS_TRUE) return MS_SUCCESS;
@@ -119,16 +102,17 @@ int msValidateParameter(char *value, char *pattern1, char *pattern2, char *patte
   return(MS_FAILURE);
 }
 
-int msEvalRegex(char *e, char *s) {
+int msEvalRegex(char *e, char *s)
+{
   ms_regex_t re;
 
   if(!e || !s) return(MS_FALSE);
 
   if(ms_regcomp(&re, e, MS_REG_EXTENDED|MS_REG_NOSUB) != 0) {
-    msSetError(MS_REGEXERR, "Failed to compile expression (%s).", "msEvalRegex()", e);   
+    msSetError(MS_REGEXERR, "Failed to compile expression (%s).", "msEvalRegex()", e);
     return(MS_FALSE);
   }
-  
+
   if(ms_regexec(&re, s, 0, NULL, 0) != 0) { /* no match */
     ms_regfree(&re);
     msSetError(MS_REGEXERR, "String failed expression test.", "msEvalRegex()");
@@ -139,9 +123,12 @@ int msEvalRegex(char *e, char *s) {
   return(MS_TRUE);
 }
 
-void msFree(void *p) {
+#ifdef USE_MSFREE
+void msFree(void *p)
+{
   if(p) free(p);
 }
+#endif
 
 /*
 ** Free memory allocated for a character array
@@ -150,20 +137,18 @@ void msFreeCharArray(char **array, int num_items)
 {
   int i;
 
-  if((num_items < 0) || !array) return;
-
-  for(i=0;i<num_items;i++)
+  for(i=0; i<num_items; i++)
     msFree(array[i]);
-  msFree(array);
 
-  return;
+  msFree(array);
 }
 
 /*
 ** Checks symbol from lexer against variable length list of
 ** legal symbols.
 */
-int getSymbol(int n, ...) {
+int getSymbol(int n, ...)
+{
   int symbol;
   va_list argp;
   int i=0;
@@ -173,7 +158,7 @@ int getSymbol(int n, ...) {
   va_start(argp, n);
   while(i<n) { /* check each symbol in the list */
     if(symbol == va_arg(argp, int)) {
-      va_end(argp);      
+      va_end(argp);
       return(symbol);
     }
     i++;
@@ -181,23 +166,49 @@ int getSymbol(int n, ...) {
 
   va_end(argp);
 
-  msSetError(MS_SYMERR, "Parsing error near (%s):(line %d)", "getSymbol()", msyystring_buffer, msyylineno);  
+  msSetError(MS_SYMERR, "Parsing error near (%s):(line %d)", "getSymbol()", msyystring_buffer, msyylineno);
+  return(-1);
+}
+
+/*
+** Same as getSymbol, except no error message is set on failure
+*/
+int getSymbol2(int n, ...)
+{
+  int symbol;
+  va_list argp;
+  int i=0;
+
+  symbol = msyylex();
+
+  va_start(argp, n);
+  while(i<n) { /* check each symbol in the list */
+    if(symbol == va_arg(argp, int)) {
+      va_end(argp);
+      return(symbol);
+    }
+    i++;
+  }
+
+  va_end(argp);
   return(-1);
 }
 
 /*
 ** Get a string or symbol as a string.   Operates like getString(), but also
-** supports symbols. 
+** supports symbols.
 */
-static char *getToken(void) {
-  msyylex();  
+static char *getToken(void)
+{
+  msyylex();
   return msStrdup(msyystring_buffer);
 }
 
 /*
 ** Load a string from the map file. A "string" is defined in lexer.l.
 */
-int getString(char **s) {
+int getString(char **s)
+{
   /* if (*s)
     msSetError(MS_SYMERR, "Duplicate item (%s):(line %d)", "getString()", msyystring_buffer, msyylineno);
     return(MS_FAILURE);
@@ -205,10 +216,6 @@ int getString(char **s) {
   if(msyylex() == MS_STRING) {
     if(*s) free(*s); /* avoid leak */
     *s = msStrdup(msyystring_buffer);
-    if (*s == NULL) {
-      msSetError(MS_MEMERR, NULL, "getString()");
-      return(MS_FAILURE);
-    }
     return(MS_SUCCESS);
   }
 
@@ -219,36 +226,39 @@ int getString(char **s) {
 /*
 ** Load a floating point number from the map file. (see lexer.l)
 */
-int getDouble(double *d) {
+int getDouble(double *d)
+{
   if(msyylex() == MS_NUMBER) {
     *d = msyynumber;
     return(0); /* success */
   }
 
-  msSetError(MS_SYMERR, "Parsing error near (%s):(line %d)", "getDouble()", msyystring_buffer, msyylineno); 
+  msSetError(MS_SYMERR, "Parsing error near (%s):(line %d)", "getDouble()", msyystring_buffer, msyylineno);
   return(-1);
 }
 
 /*
 ** Load a integer from the map file. (see lexer.l)
 */
-int getInteger(int *i) {
+int getInteger(int *i)
+{
   if(msyylex() == MS_NUMBER) {
     *i = (int)msyynumber;
     return(0); /* success */
   }
 
-  msSetError(MS_SYMERR, "Parsing error near (%s):(line %d)", "getInteger()", msyystring_buffer, msyylineno); 
+  msSetError(MS_SYMERR, "Parsing error near (%s):(line %d)", "getInteger()", msyystring_buffer, msyylineno);
   return(-1);
 }
 
-int getCharacter(char *c) {
+int getCharacter(char *c)
+{
   if(msyylex() == MS_STRING) {
     *c = msyystring_buffer[0];
     return(0);
   }
 
-  msSetError(MS_SYMERR, "Parsing error near (%s):(line %d)", "getCharacter()", msyystring_buffer, msyylineno); 
+  msSetError(MS_SYMERR, "Parsing error near (%s):(line %d)", "getCharacter()", msyystring_buffer, msyylineno);
   return(-1);
 }
 
@@ -256,33 +266,33 @@ int getCharacter(char *c) {
 ** Try to load as an integer, then try as a named symbol.
 ** Part of work on bug 490.
 */
-int getIntegerOrSymbol(int *i, int n, ...) 
+int getIntegerOrSymbol(int *i, int n, ...)
 {
-    int symbol;
-    va_list argp;
-    int j=0;
-    
-    symbol = msyylex();
+  int symbol;
+  va_list argp;
+  int j=0;
 
-    if (symbol == MS_NUMBER) {
-        *i = (int)msyynumber;
-        return MS_SUCCESS; /* success */
-    }
+  symbol = msyylex();
 
-    va_start(argp, n);
-    while (j<n) { /* check each symbol in the list */
-        if(symbol == va_arg(argp, int)) {
-            va_end(argp);
-            *i = symbol;
-            return MS_SUCCESS;
-        }
-        j++;
+  if (symbol == MS_NUMBER) {
+    *i = (int)msyynumber;
+    return MS_SUCCESS; /* success */
+  }
+
+  va_start(argp, n);
+  while (j<n) { /* check each symbol in the list */
+    if(symbol == va_arg(argp, int)) {
+      va_end(argp);
+      *i = symbol;
+      return MS_SUCCESS;
     }
-    va_end(argp);
+    j++;
+  }
+  va_end(argp);
 
-    msSetError(MS_SYMERR, "Parsing error near (%s):(line %d)",
-               "getIntegerOrSymbol()", msyystring_buffer, msyylineno); 
-    return(-1);
+  msSetError(MS_SYMERR, "Parsing error near (%s):(line %d)",
+             "getIntegerOrSymbol()", msyystring_buffer, msyylineno);
+  return(-1);
 }
 
 
@@ -293,27 +303,27 @@ int getIntegerOrSymbol(int *i, int n, ...)
 */
 int msBuildPluginLibraryPath(char **dest, const char *lib_str, mapObj *map)
 {
-    char szLibPath[MS_MAXPATHLEN] = { '\0' };
-    char szLibPathExt[MS_MAXPATHLEN] = { '\0' };
-    const char *plugin_dir = msLookupHashTable( &(map->configoptions), "MS_PLUGIN_DIR");
+  char szLibPath[MS_MAXPATHLEN] = { '\0' };
+  char szLibPathExt[MS_MAXPATHLEN] = { '\0' };
+  const char *plugin_dir = msLookupHashTable( &(map->configoptions), "MS_PLUGIN_DIR");
 
-    /* do nothing on windows, filename without .dll will be loaded by default*/
+  /* do nothing on windows, filename without .dll will be loaded by default*/
 #if !defined(_WIN32)
-    if (lib_str) {
-        size_t len = strlen(lib_str);
-        if (3 < len && strcmp(lib_str + len-3, ".so")) {
-            strlcpy(szLibPathExt, lib_str, MS_MAXPATHLEN);
-            strlcat(szLibPathExt, ".so", MS_MAXPATHLEN);
-            lib_str = szLibPathExt;
-        }
+  if (lib_str) {
+    size_t len = strlen(lib_str);
+    if (3 < len && strcmp(lib_str + len-3, ".so")) {
+      strlcpy(szLibPathExt, lib_str, MS_MAXPATHLEN);
+      strlcat(szLibPathExt, ".so", MS_MAXPATHLEN);
+      lib_str = szLibPathExt;
     }
+  }
 #endif /* !defined(_WIN32) */
-    if (NULL == msBuildPath(szLibPath, plugin_dir, lib_str)) {
-        return MS_FAILURE;
-    }
-    *dest = msStrdup(szLibPath);
+  if (NULL == msBuildPath(szLibPath, plugin_dir, lib_str)) {
+    return MS_FAILURE;
+  }
+  *dest = msStrdup(szLibPath);
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 /*
@@ -349,7 +359,7 @@ int msGetLayerIndex(mapObj *map, char *name)
 
   if(!name) return(-1);
 
-  for(i=0;i<map->numlayers; i++) {
+  for(i=0; i<map->numlayers; i++) {
     if(!GET_LAYER(map, i)->name) /* skip it */
       continue;
     if(strcmp(name, GET_LAYER(map, i)->name) == 0)
@@ -364,7 +374,7 @@ int msGetClassIndex(layerObj *layer, char *name)
 
   if(!name) return(-1);
 
-  for(i=0;i<layer->numclasses; i++) {
+  for(i=0; i<layer->numclasses; i++) {
     if(!layer->class[i]->name) /* skip it */
       continue;
     if(strcmp(name, layer->class[i]->name) == 0)
@@ -373,7 +383,8 @@ int msGetClassIndex(layerObj *layer, char *name)
   return(-1);
 }
 
-int loadColor(colorObj *color, attributeBindingObj *binding) {
+int loadColor(colorObj *color, attributeBindingObj *binding)
+{
   int symbol;
   char hex[2];
 
@@ -406,9 +417,9 @@ int loadColor(colorObj *color, attributeBindingObj *binding) {
         color->alpha = msHexToInt(hex);
       }
     } else {
-       /* TODO: consider named colors here */
-       msSetError(MS_SYMERR, "Invalid hex color (%s):(line %d)", "loadColor()", msyystring_buffer, msyylineno); 
-       return MS_FAILURE;
+      /* TODO: consider named colors here */
+      msSetError(MS_SYMERR, "Invalid hex color (%s):(line %d)", "loadColor()", msyystring_buffer, msyylineno);
+      return MS_FAILURE;
     }
   } else {
     binding->item = msStrdup(msyystring_buffer);
@@ -419,14 +430,15 @@ int loadColor(colorObj *color, attributeBindingObj *binding) {
 }
 
 #if ALPHACOLOR_ENABLED
-int loadColorWithAlpha(colorObj *color) {
+int loadColorWithAlpha(colorObj *color)
+{
   char hex[2];
 
   if(getInteger(&(color->red)) == -1) {
     if(msyystring_buffer[0] == '#' && strlen(msyystring_buffer) == 7) { /* got a hex color */
       hex[0] = msyystring_buffer[1];
       hex[1] = msyystring_buffer[2];
-      color->red = msHexToInt(hex);      
+      color->red = msHexToInt(hex);
       hex[0] = msyystring_buffer[3];
       hex[1] = msyystring_buffer[4];
       color->green = msHexToInt(hex);
@@ -436,11 +448,10 @@ int loadColorWithAlpha(colorObj *color) {
       color->alpha = 0;
 
       return(MS_SUCCESS);
-    }
-    else if(msyystring_buffer[0] == '#' && strlen(msyystring_buffer) == 9) { /* got a hex color with alpha */
+    } else if(msyystring_buffer[0] == '#' && strlen(msyystring_buffer) == 9) { /* got a hex color with alpha */
       hex[0] = msyystring_buffer[1];
       hex[1] = msyystring_buffer[2];
-      color->red = msHexToInt(hex);      
+      color->red = msHexToInt(hex);
       hex[0] = msyystring_buffer[3];
       hex[1] = msyystring_buffer[4];
       color->green = msHexToInt(hex);
@@ -465,27 +476,32 @@ int loadColorWithAlpha(colorObj *color) {
 /*
 ** Helper functions for writing mapfiles.
 */
-static void writeLineFeed(FILE *stream) {
+static void writeLineFeed(FILE *stream)
+{
   fprintf(stream, "\n");
 }
 
-static void writeIndent(FILE *stream, int indent) {  
+static void writeIndent(FILE *stream, int indent)
+{
   const char *str="  "; /* change this string to define the indent */
   int i;
   for(i=0; i<indent; i++) fprintf(stream, "%s", str);
 }
 
-static void writeBlockBegin(FILE *stream, int indent, const char *name) {
+static void writeBlockBegin(FILE *stream, int indent, const char *name)
+{
   writeIndent(stream, indent);
   fprintf(stream, "%s\n", name);
 }
 
-static void writeBlockEnd(FILE *stream, int indent, const char *name) {
+static void writeBlockEnd(FILE *stream, int indent, const char *name)
+{
   writeIndent(stream, indent);
   fprintf(stream, "END # %s\n", name);
 }
 
-static void writeKeyword(FILE *stream, int indent, const char *name, int value, int size, ...) {
+static void writeKeyword(FILE *stream, int indent, const char *name, int value, int size, ...)
+{
   va_list argp;
   int i, j=0;
   const char *s;
@@ -505,7 +521,8 @@ static void writeKeyword(FILE *stream, int indent, const char *name, int value,
   va_end(argp);
 }
 
-static void writeDimension(FILE *stream, int indent, const char *name, int x, int y, char *bind_x, char *bind_y) {
+static void writeDimension(FILE *stream, int indent, const char *name, int x, int y, char *bind_x, char *bind_y)
+{
   writeIndent(stream, ++indent);
   if(bind_x) fprintf(stream, "%s [%s] ", name, bind_x);
   else fprintf(stream, "%s %d ", name, x);
@@ -513,25 +530,29 @@ static void writeDimension(FILE *stream, int indent, const char *name, int x, in
   else fprintf(stream, "%d\n", y);
 }
 
-static void writeExtent(FILE *stream, int indent, const char *name, rectObj extent) {
+static void writeExtent(FILE *stream, int indent, const char *name, rectObj extent)
+{
   if(!MS_VALID_EXTENT(extent)) return;
   writeIndent(stream, ++indent);
   fprintf(stream, "%s %.15g %.15g %.15g %.15g\n", name, extent.minx, extent.miny, extent.maxx, extent.maxy);
 }
 
-static void writeNumber(FILE *stream, int indent, const char *name, double defaultNumber, double number) {
+static void writeNumber(FILE *stream, int indent, const char *name, double defaultNumber, double number)
+{
   if(number == defaultNumber) return; /* don't output default */
   writeIndent(stream, ++indent);
   fprintf(stream, "%s %g\n", name, number);
 }
 
-static void writeCharacter(FILE *stream, int indent, const char *name, const char defaultCharacter, char character) {
+static void writeCharacter(FILE *stream, int indent, const char *name, const char defaultCharacter, char character)
+{
   if(defaultCharacter == character) return;
   writeIndent(stream, ++indent);
   fprintf(stream, "%s '%c'\n", name, character);
 }
 
-static void writeString(FILE *stream, int indent, const char *name, const char *defaultString, char *string) {
+static void writeString(FILE *stream, int indent, const char *name, const char *defaultString, char *string)
+{
   char *string_tmp;
 
   if(!string) return;
@@ -539,26 +560,28 @@ static void writeString(FILE *stream, int indent, const char *name, const char *
   writeIndent(stream, ++indent);
   if(name) fprintf(stream, "%s ", name);
   if ( (strchr(string, '\'') == NULL) && (strchr(string, '\"') == NULL))
-      fprintf(stream, "\"%s\"\n", string);
+    fprintf(stream, "\"%s\"\n", string);
   else if ( (strchr(string, '\"') != NULL) && (strchr(string, '\'') == NULL))
-      fprintf(stream, "'%s'\n", string);
+    fprintf(stream, "'%s'\n", string);
   else if ( (strchr(string, '\'') != NULL) && (strchr(string, '\"') == NULL))
     fprintf(stream, "\"%s\"\n", string);
   else {
-      string_tmp = msStringEscape(string);
-      fprintf(stream, "\"%s\"\n", string_tmp);
-      free(string_tmp);
-  }   
+    string_tmp = msStringEscape(string);
+    fprintf(stream, "\"%s\"\n", string_tmp);
+    if(string!=string_tmp) free(string_tmp);
+  }
 }
 
-static void writeNumberOrString(FILE *stream, int indent, const char *name, double defaultNumber, double number, char *string) {
+static void writeNumberOrString(FILE *stream, int indent, const char *name, double defaultNumber, double number, char *string)
+{
   if(string)
     writeString(stream, indent, name, NULL, string);
   else
     writeNumber(stream, indent, name, defaultNumber, number);
 }
 
-static void writeNumberOrKeyword(FILE *stream, int indent, const char *name, double defaultNumber, double number, int value, int size, ...) {
+static void writeNumberOrKeyword(FILE *stream, int indent, const char *name, double defaultNumber, double number, int value, int size, ...)
+{
   va_list argp;
   int i, j=0;
   const char *s;
@@ -580,46 +603,49 @@ static void writeNumberOrKeyword(FILE *stream, int indent, const char *name, dou
   writeNumber(stream, indent, name, defaultNumber, number);
 }
 
-static void writeNameValuePair(FILE *stream, int indent, const char *name, const char *value) {
+static void writeNameValuePair(FILE *stream, int indent, const char *name, const char *value)
+{
   char *string_tmp;
   if(!name || !value) return;
-  writeIndent(stream, ++indent);  
+  writeIndent(stream, ++indent);
 
   if ( (strchr(name, '\'') == NULL) && (strchr(name, '\"') == NULL))
-      fprintf(stream, "\"%s\"\t", name);
+    fprintf(stream, "\"%s\"\t", name);
   else if ( (strchr(name, '\"') != NULL) && (strchr(name, '\'') == NULL))
-      fprintf(stream, "'%s'\t", name);
+    fprintf(stream, "'%s'\t", name);
   else if ( (strchr(name, '\'') != NULL) && (strchr(name, '\"') == NULL))
     fprintf(stream, "\"%s\"\t", name);
   else {
-      string_tmp = msStringEscape(name);
-      fprintf(stream, "\"%s\"\t", string_tmp);
-      free(string_tmp);
-  }   
+    string_tmp = msStringEscape(name);
+    fprintf(stream, "\"%s\"\t", string_tmp);
+    if(name!=string_tmp) free(string_tmp);
+  }
 
   if ( (strchr(value, '\'') == NULL) && (strchr(value, '\"') == NULL))
-      fprintf(stream, "\"%s\"\n", value);
+    fprintf(stream, "\"%s\"\n", value);
   else if ( (strchr(value, '\"') != NULL) && (strchr(value, '\'') == NULL))
-      fprintf(stream, "'%s'\n", value);
+    fprintf(stream, "'%s'\n", value);
   else if ( (strchr(value, '\'') != NULL) && (strchr(value, '\"') == NULL))
     fprintf(stream, "\"%s\"\n", value);
   else {
-      string_tmp = msStringEscape(value);
-      fprintf(stream, "\"%s\"\n", string_tmp);
-      free(string_tmp);
-  }   
+    string_tmp = msStringEscape(value);
+    fprintf(stream, "\"%s\"\n", string_tmp);
+    if(value!=string_tmp) free(string_tmp);
+  }
 }
 
-static void writeAttributeBinding(FILE *stream, int indent, const char *name, attributeBindingObj *binding) {
+static void writeAttributeBinding(FILE *stream, int indent, const char *name, attributeBindingObj *binding)
+{
   if(!binding || !binding->item) return;
   writeIndent(stream, ++indent);
   fprintf(stream, "%s [%s]\n", name, binding->item);
 }
 
-static void writeColor(FILE *stream, int indent, const char *name, colorObj *defaultColor, colorObj *color) {
-    if (!defaultColor && !MS_VALID_COLOR(*color)) return;
-    else if(defaultColor && MS_COMPARE_COLOR(*defaultColor, *color)) return; /* if defaultColor has the same value than the color, return.*/
-  
+static void writeColor(FILE *stream, int indent, const char *name, colorObj *defaultColor, colorObj *color)
+{
+  if (!defaultColor && !MS_VALID_COLOR(*color)) return;
+  else if(defaultColor && MS_COMPARE_COLOR(*defaultColor, *color)) return; /* if defaultColor has the same value than the color, return.*/
+
   writeIndent(stream, ++indent);
 #if ALPHACOLOR_ENABLED
   fprintf(stream, "%s %d %d %d\n", name, color->red, color->green, color->blue, color->alpha);
@@ -629,7 +655,8 @@ static void writeColor(FILE *stream, int indent, const char *name, colorObj *def
 }
 
 /* todo: deal with alpha's... */
-static void writeColorRange(FILE *stream, int indent, const char *name, colorObj *mincolor, colorObj *maxcolor) {
+static void writeColorRange(FILE *stream, int indent, const char *name, colorObj *mincolor, colorObj *maxcolor)
+{
   if(!MS_VALID_COLOR(*mincolor) || !MS_VALID_COLOR(*maxcolor)) return;
   writeIndent(stream, ++indent);
   fprintf(stream, "%s %d %d %d  %d %d %d\n", name, mincolor->red, mincolor->green, mincolor->blue, maxcolor->red, maxcolor->green, maxcolor->blue);
@@ -646,7 +673,7 @@ void initJoin(joinObj *join)
 
   join->items = NULL; /* array to hold item names for the joined table */
   join->values = NULL; /* arrays of strings to holds one record worth of data */
- 
+
   join->table = NULL;
 
   join->joininfo = NULL;
@@ -664,7 +691,7 @@ void initJoin(joinObj *join)
   join->connectiontype = MS_DB_XBASE;
 }
 
-void freeJoin(joinObj *join) 
+void freeJoin(joinObj *join)
 {
   msFree(join->name);
   msFree(join->table);
@@ -689,54 +716,54 @@ int loadJoin(joinObj *join)
 
   for(;;) {
     switch(msyylex()) {
-    case(CONNECTION):
-      if(getString(&join->connection) == MS_FAILURE) return(-1);
-      break;
-    case(CONNECTIONTYPE):
-      if((join->connectiontype = getSymbol(5, MS_DB_XBASE, MS_DB_MYSQL, MS_DB_ORACLE, MS_DB_POSTGRES, MS_DB_CSV)) == -1) return(-1);
-      break;
-    case(EOF):
-      msSetError(MS_EOFERR, NULL, "loadJoin()");
-      return(-1);
-    case(END):      
-      if((join->from == NULL) || (join->to == NULL) || (join->table == NULL)) {
-	msSetError(MS_EOFERR, "Join must define table, name, from and to properties.", "loadJoin()");
-	return(-1);
-      }
-      if((join->type == MS_MULTIPLE) && ((join->template == NULL) || (join->name == NULL))) {
-	msSetError(MS_EOFERR, "One-to-many joins must define template and name properties.", "loadJoin()");
-	return(-1);
-      }      
-      return(0);
-    case(FOOTER):
-      if(getString(&join->footer) == MS_FAILURE) return(-1);
-      break;
-    case(FROM):
-      if(getString(&join->from) == MS_FAILURE) return(-1);
-      break;      
-    case(HEADER):
-      if(getString(&join->header) == MS_FAILURE) return(-1);
-      break;
-    case(JOIN):
-      break; /* for string loads */
-    case(NAME):
-      if(getString(&join->name) == MS_FAILURE) return(-1);
-      break;
-    case(TABLE):
-      if(getString(&join->table) == MS_FAILURE) return(-1);
-      break;
-    case(TEMPLATE):
-      if(getString(&join->template) == MS_FAILURE) return(-1);
-      break;
-    case(TO):
-      if(getString(&join->to) == MS_FAILURE) return(-1);
-      break;
-    case(TYPE):
-      if((join->type = getSymbol(2, MS_JOIN_ONE_TO_ONE, MS_JOIN_ONE_TO_MANY)) == -1) return(-1);
-      break;
-    default:
-      msSetError(MS_IDENTERR, "Parsing error near (%s):(line %d)", "loadJoin()", msyystring_buffer, msyylineno);
-      return(-1);
+      case(CONNECTION):
+        if(getString(&join->connection) == MS_FAILURE) return(-1);
+        break;
+      case(CONNECTIONTYPE):
+        if((join->connectiontype = getSymbol(5, MS_DB_XBASE, MS_DB_MYSQL, MS_DB_ORACLE, MS_DB_POSTGRES, MS_DB_CSV)) == -1) return(-1);
+        break;
+      case(EOF):
+        msSetError(MS_EOFERR, NULL, "loadJoin()");
+        return(-1);
+      case(END):
+        if((join->from == NULL) || (join->to == NULL) || (join->table == NULL)) {
+          msSetError(MS_EOFERR, "Join must define table, name, from and to properties.", "loadJoin()");
+          return(-1);
+        }
+        if((join->type == MS_MULTIPLE) && ((join->template == NULL) || (join->name == NULL))) {
+          msSetError(MS_EOFERR, "One-to-many joins must define template and name properties.", "loadJoin()");
+          return(-1);
+        }
+        return(0);
+      case(FOOTER):
+        if(getString(&join->footer) == MS_FAILURE) return(-1);
+        break;
+      case(FROM):
+        if(getString(&join->from) == MS_FAILURE) return(-1);
+        break;
+      case(HEADER):
+        if(getString(&join->header) == MS_FAILURE) return(-1);
+        break;
+      case(JOIN):
+        break; /* for string loads */
+      case(NAME):
+        if(getString(&join->name) == MS_FAILURE) return(-1);
+        break;
+      case(TABLE):
+        if(getString(&join->table) == MS_FAILURE) return(-1);
+        break;
+      case(TEMPLATE):
+        if(getString(&join->template) == MS_FAILURE) return(-1);
+        break;
+      case(TO):
+        if(getString(&join->to) == MS_FAILURE) return(-1);
+        break;
+      case(TYPE):
+        if((join->type = getSymbol(2, MS_JOIN_ONE_TO_ONE, MS_JOIN_ONE_TO_MANY)) == -1) return(-1);
+        break;
+      default:
+        msSetError(MS_IDENTERR, "Parsing error near (%s):(line %d)", "loadJoin()", msyystring_buffer, msyylineno);
+        return(-1);
     }
   } /* next token */
 }
@@ -777,29 +804,28 @@ featureListNodeObjPtr insertFeatureList(featureListNodeObjPtr *list, shapeObj *s
   /* if we are at the head of the list, we need to set the list to node, before pointing tailifhead somewhere  */
   if(*list == NULL) {
     *list=node;
-  } else {      
+  } else {
     if((*list)->tailifhead!=NULL) /* this should never be NULL, but just in case */
       (*list)->tailifhead->next=node; /* put the node at the end of the list */
   }
 
   /* repoint the head of the list to the end  - our new element
-     this causes a loop if we are at the head, be careful not to 
+     this causes a loop if we are at the head, be careful not to
      walk in a loop */
   (*list)->tailifhead = node;
- 
+
   return(node); /* a pointer to last object in the list */
 }
 
 void freeFeatureList(featureListNodeObjPtr list)
 {
-    featureListNodeObjPtr listNext = NULL;
-    while (list!=NULL)
-    {
-        listNext = list->next;
-        msFreeShape(&(list->shape));
-        msFree(list);
-        list = listNext;
-    }
+  featureListNodeObjPtr listNext = NULL;
+  while (list!=NULL) {
+    listNext = list->next;
+    msFreeShape(&(list->shape));
+    msFree(list);
+    list = listNext;
+  }
 }
 
 /* lineObj = multipointObj */
@@ -814,36 +840,36 @@ static int loadFeaturePoints(lineObj *points)
 
   for(;;) {
     switch(msyylex()) {
-    case(EOF):
-      msSetError(MS_EOFERR, NULL, "loadFeaturePoints()");      
-      return(MS_FAILURE);
-    case(END):
-      return(MS_SUCCESS);
-    case(MS_NUMBER):
-      if(points->numpoints == buffer_size) { /* just add it to the end */
-	points->point = (pointObj *) realloc(points->point, sizeof(pointObj)*(buffer_size+MS_FEATUREINCREMENT));
-        MS_CHECK_ALLOC(points->point, sizeof(pointObj)*(buffer_size+MS_FEATUREINCREMENT), MS_FAILURE);
-	buffer_size+=MS_FEATUREINCREMENT;
-      }
+      case(EOF):
+        msSetError(MS_EOFERR, NULL, "loadFeaturePoints()");
+        return(MS_FAILURE);
+      case(END):
+        return(MS_SUCCESS);
+      case(MS_NUMBER):
+        if(points->numpoints == buffer_size) { /* just add it to the end */
+          points->point = (pointObj *) realloc(points->point, sizeof(pointObj)*(buffer_size+MS_FEATUREINCREMENT));
+          MS_CHECK_ALLOC(points->point, sizeof(pointObj)*(buffer_size+MS_FEATUREINCREMENT), MS_FAILURE);
+          buffer_size+=MS_FEATUREINCREMENT;
+        }
 
-      points->point[points->numpoints].x = atof(msyystring_buffer);
-      if(getDouble(&(points->point[points->numpoints].y)) == -1) return(MS_FAILURE);
+        points->point[points->numpoints].x = atof(msyystring_buffer);
+        if(getDouble(&(points->point[points->numpoints].y)) == -1) return(MS_FAILURE);
 
-      points->numpoints++;
-      break;
-    default:
-      msSetError(MS_IDENTERR, "Parsing error near (%s):(line %d)", "loadFeaturePoints()",  msyystring_buffer, msyylineno );
-      return(MS_FAILURE);
+        points->numpoints++;
+        break;
+      default:
+        msSetError(MS_IDENTERR, "Parsing error near (%s):(line %d)", "loadFeaturePoints()",  msyystring_buffer, msyylineno );
+        return(MS_FAILURE);
     }
   }
 }
 
-static int loadFeature(layerObj	*player, int type)
+static int loadFeature(layerObj *player, int type)
 {
   int status=MS_SUCCESS;
   featureListNodeObjPtr *list = &(player->features);
   featureListNodeObjPtr node;
-  multipointObj points={0,NULL};
+  multipointObj points= {0,NULL};
   shapeObj *shape=NULL;
 
   shape = (shapeObj *) malloc(sizeof(shapeObj));
@@ -854,70 +880,69 @@ static int loadFeature(layerObj	*player, int type)
 
   for(;;) {
     switch(msyylex()) {
-    case(EOF):
-      msSetError(MS_EOFERR, NULL, "loadFeature()");      
-      return(MS_FAILURE);
-    case(END):
-      if(player->features != NULL && player->features->tailifhead != NULL) 
-            shape->index = player->features->tailifhead->shape.index + 1;
-        else 
-            shape->index = 0;
-      if((node = insertFeatureList(list, shape)) == NULL) 
-	  status = MS_FAILURE;
-
-      msFreeShape(shape); /* clean up */
-      msFree(shape);
-
-      return(status);
-    case(FEATURE):
-      break; /* for string loads */
-    case(POINTS):
-      if(loadFeaturePoints(&points) == MS_FAILURE) return(MS_FAILURE); /* no clean up necessary, just return */
-      status = msAddLine(shape, &points);
-
-      msFree(points.point); /* clean up */
-      points.numpoints = 0;
-
-      if(status == MS_FAILURE) return(MS_FAILURE);
-      break;
-    case(ITEMS):
-    {
-      char *string=NULL;
-      if(getString(&string) == MS_FAILURE) return(MS_FAILURE);
-      if (string)
-      {
-        if(shape->values) msFreeCharArray(shape->values, shape->numvalues);
-        shape->values = msStringSplit(string, ';', &shape->numvalues);
-        msFree(string); /* clean up */
+      case(EOF):
+        msSetError(MS_EOFERR, NULL, "loadFeature()");
+        return(MS_FAILURE);
+      case(END):
+        if(player->features != NULL && player->features->tailifhead != NULL)
+          shape->index = player->features->tailifhead->shape.index + 1;
+        else
+          shape->index = 0;
+        if((node = insertFeatureList(list, shape)) == NULL)
+          status = MS_FAILURE;
+
+        msFreeShape(shape); /* clean up */
+        msFree(shape);
+
+        return(status);
+      case(FEATURE):
+        break; /* for string loads */
+      case(POINTS):
+        if(loadFeaturePoints(&points) == MS_FAILURE) return(MS_FAILURE); /* no clean up necessary, just return */
+        status = msAddLine(shape, &points);
+
+        msFree(points.point); /* clean up */
+        points.numpoints = 0;
+
+        if(status == MS_FAILURE) return(MS_FAILURE);
+        break;
+      case(ITEMS): {
+        char *string=NULL;
+        if(getString(&string) == MS_FAILURE) return(MS_FAILURE);
+        if (string) {
+          if(shape->values) msFreeCharArray(shape->values, shape->numvalues);
+          shape->values = msStringSplit(string, ';', &shape->numvalues);
+          msFree(string); /* clean up */
+        }
+        break;
       }
-      break;
-    }
-    case(TEXT):
-      if(getString(&shape->text) == MS_FAILURE) return(MS_FAILURE);
-      break;
-    case(WKT):
-      {
-	char *string=NULL;
+      case(TEXT):
+        if(getString(&shape->text) == MS_FAILURE) return(MS_FAILURE);
+        break;
+      case(WKT): {
+        char *string=NULL;
+
+        /* todo, what do we do with multiple WKT property occurances? */
 
-	/* todo, what do we do with multiple WKT property occurances? */
-	
-	if(getString(&string) == MS_FAILURE) return(MS_FAILURE);
-	if((shape = msShapeFromWKT(string)) == NULL)
-	  status = MS_FAILURE;
+        if(getString(&string) == MS_FAILURE) return(MS_FAILURE);
+        msFreeShape(shape);
+        msFree(shape);
+        if((shape = msShapeFromWKT(string)) == NULL)
+          status = MS_FAILURE;
 
-	msFree(string); /* clean up */
+        msFree(string); /* clean up */
 
-	if(status == MS_FAILURE) return(MS_FAILURE);
-	break;
+        if(status == MS_FAILURE) return(MS_FAILURE);
+        break;
       }
-    default:
-      msSetError(MS_IDENTERR, "Parsing error near (%s):(line %d)", "loadfeature()", msyystring_buffer, msyylineno);
-      return(MS_FAILURE);
+      default:
+        msSetError(MS_IDENTERR, "Parsing error near (%s):(line %d)", "loadfeature()", msyystring_buffer, msyylineno);
+        return(MS_FAILURE);
     }
-  } /* next token */  
+  } /* next token */
 }
 
-static void writeFeature(FILE *stream, int indent, shapeObj *feature) 
+static void writeFeature(FILE *stream, int indent, shapeObj *feature)
 {
   int i,j;
 
@@ -960,52 +985,52 @@ static int loadGrid( layerObj *pLayer )
 {
   for(;;) {
     switch(msyylex()) {
-    case(EOF):
-      msSetError(MS_EOFERR, NULL, "loadGrid()");     
-      return(-1);      
-    case(END):
-      return(0);
-    case(GRID):
-      break; /* for string loads */
-    case( LABELFORMAT ):
-      if(getString(&((graticuleObj *)pLayer->layerinfo)->labelformat) == MS_FAILURE) {
-	if(strcasecmp(msyystring_buffer, "DD") == 0) /* DD triggers a symbol to be returned instead of a string so check for this special case */
-	  ((graticuleObj *)pLayer->layerinfo)->labelformat = msStrdup("DD");
-        else
-	  return(-1);
-      }
-      break;
-    case( MINARCS ):
-      if(getDouble(&((graticuleObj *)pLayer->layerinfo)->minarcs) == -1) 
-	return(-1);      
-      break;      
-    case( MAXARCS ):
-      if(getDouble(&((graticuleObj *)pLayer->layerinfo)->maxarcs) == -1) 
-	return(-1);      
-      break;
-    case( MININTERVAL ):
-      if(getDouble(&((graticuleObj *)pLayer->layerinfo)->minincrement) == -1) 
-	return(-1);      
-      break;      
-    case( MAXINTERVAL ):
-      if(getDouble(&((graticuleObj *)pLayer->layerinfo)->maxincrement) == -1) 
-	return(-1);      
-      break;
-    case( MINSUBDIVIDE ):
-      if(getDouble(&((graticuleObj *)pLayer->layerinfo)->minsubdivides) == -1) 
-	return(-1);      
-      break;      
-    case( MAXSUBDIVIDE ):
-      if(getDouble(&((graticuleObj *)pLayer->layerinfo)->maxsubdivides) == -1) 
-	return(-1);
-      break;				
-    default:
-      msSetError(MS_IDENTERR, "Parsing error near (%s):(line %d)", "loadGrid()", msyystring_buffer, msyylineno);          
-      return(-1);      
+      case(EOF):
+        msSetError(MS_EOFERR, NULL, "loadGrid()");
+        return(-1);
+      case(END):
+        return(0);
+      case(GRID):
+        break; /* for string loads */
+      case( LABELFORMAT ):
+        if(getString(&((graticuleObj *)pLayer->layerinfo)->labelformat) == MS_FAILURE) {
+          if(strcasecmp(msyystring_buffer, "DD") == 0) /* DD triggers a symbol to be returned instead of a string so check for this special case */
+            ((graticuleObj *)pLayer->layerinfo)->labelformat = msStrdup("DD");
+          else
+            return(-1);
+        }
+        break;
+      case( MINARCS ):
+        if(getDouble(&((graticuleObj *)pLayer->layerinfo)->minarcs) == -1)
+          return(-1);
+        break;
+      case( MAXARCS ):
+        if(getDouble(&((graticuleObj *)pLayer->layerinfo)->maxarcs) == -1)
+          return(-1);
+        break;
+      case( MININTERVAL ):
+        if(getDouble(&((graticuleObj *)pLayer->layerinfo)->minincrement) == -1)
+          return(-1);
+        break;
+      case( MAXINTERVAL ):
+        if(getDouble(&((graticuleObj *)pLayer->layerinfo)->maxincrement) == -1)
+          return(-1);
+        break;
+      case( MINSUBDIVIDE ):
+        if(getDouble(&((graticuleObj *)pLayer->layerinfo)->minsubdivides) == -1)
+          return(-1);
+        break;
+      case( MAXSUBDIVIDE ):
+        if(getDouble(&((graticuleObj *)pLayer->layerinfo)->maxsubdivides) == -1)
+          return(-1);
+        break;
+      default:
+        msSetError(MS_IDENTERR, "Parsing error near (%s):(line %d)", "loadGrid()", msyystring_buffer, msyylineno);
+        return(-1);
     }
   }
 }
-  
+
 static void writeGrid(FILE *stream, int indent, graticuleObj *pGraticule)
 {
   if(!pGraticule) return;
@@ -1030,23 +1055,33 @@ int msInitProjection(projectionObj *p)
   p->gt.need_geotransform = MS_FALSE;
   p->numargs = 0;
   p->args = NULL;
-#ifdef USE_PROJ  
+  p->wellknownprojection = wkp_none;
+#ifdef USE_PROJ
   p->proj = NULL;
   p->args = (char **)malloc(MS_MAXPROJARGS*sizeof(char *));
   MS_CHECK_ALLOC(p->args, MS_MAXPROJARGS*sizeof(char *), -1);
+#if PJ_VERSION >= 480
+  p->proj_ctx = NULL;
+#endif
 #endif
   return(0);
 }
 
-void msFreeProjection(projectionObj *p) {
+void msFreeProjection(projectionObj *p)
+{
 #ifdef USE_PROJ
-  if(p->proj)
-  {
-      pj_free(p->proj);
-      p->proj = NULL;
+  if(p->proj) {
+    pj_free(p->proj);
+    p->proj = NULL;
   }
+#if PJ_VERSION >= 480
+  if(p->proj_ctx) {
+    pj_ctx_free(p->proj_ctx);
+    p->proj_ctx = NULL;
+  }
+#endif
 
-  msFreeCharArray(p->args, p->numargs);  
+  msFreeCharArray(p->args, p->numargs);
   p->args = NULL;
   p->numargs = 0;
 #endif
@@ -1056,203 +1091,219 @@ void msFreeProjection(projectionObj *p) {
 ** Handle OGC WMS/WFS AUTO projection in the format:
 **    "AUTO:proj_id,units_id,lon0,lat0"
 */
-#ifdef USE_PROJ    
+#ifdef USE_PROJ
 static int _msProcessAutoProjection(projectionObj *p)
 {
-    char **args;
-    int numargs, nProjId, nUnitsId, nZone;
-    double dLat0, dLon0;
-    const char *pszUnits = "m";
-    char szProjBuf[512]="";
-
-    /* WMS/WFS AUTO projection: "AUTO:proj_id,units_id,lon0,lat0" */
-    args = msStringSplit(p->args[0], ',', &numargs);
-    if (numargs != 4 || 
-        (strncasecmp(args[0], "AUTO:", 5) != 0 &&
-         strncasecmp(args[0], "AUTO2:", 6) != 0))
-    {
-        msSetError(MS_PROJERR, 
-                   "WMS/WFS AUTO/AUTO2 PROJECTION must be in the format "
-                   "'AUTO:proj_id,units_id,lon0,lat0' or 'AUTO2:crs_id,factor,lon0,lat0'(got '%s').\n",
-                   "_msProcessAutoProjection()", p->args[0]);
-        return -1;
-    }
+  char **args;
+  int numargs, nProjId, nUnitsId, nZone;
+  double dLat0, dLon0;
+  const char *pszUnits = "m";
+  char szProjBuf[512]="";
+
+  /* WMS/WFS AUTO projection: "AUTO:proj_id,units_id,lon0,lat0" */
+  args = msStringSplit(p->args[0], ',', &numargs);
+  if (numargs != 4 ||
+      (strncasecmp(args[0], "AUTO:", 5) != 0 &&
+       strncasecmp(args[0], "AUTO2:", 6) != 0)) {
+    msSetError(MS_PROJERR,
+               "WMS/WFS AUTO/AUTO2 PROJECTION must be in the format "
+               "'AUTO:proj_id,units_id,lon0,lat0' or 'AUTO2:crs_id,factor,lon0,lat0'(got '%s').\n",
+               "_msProcessAutoProjection()", p->args[0]);
+    return -1;
+  }
 
-    if (strncasecmp(args[0], "AUTO:", 5)==0)
-      nProjId = atoi(args[0]+5);
-    else
-      nProjId = atoi(args[0]+6);
+  if (strncasecmp(args[0], "AUTO:", 5)==0)
+    nProjId = atoi(args[0]+5);
+  else
+    nProjId = atoi(args[0]+6);
 
-    nUnitsId = atoi(args[1]);
-    dLon0 = atof(args[2]);
-    dLat0 = atof(args[3]);
+  nUnitsId = atoi(args[1]);
+  dLon0 = atof(args[2]);
+  dLat0 = atof(args[3]);
 
 
-    /*There is no unit parameter for AUTO2. The 2nd parameter is
-     factor. Set the units to always be meter*/
-    if (strncasecmp(args[0], "AUTO2:", 6) == 0)
-      nUnitsId = 9001;
+  /*There is no unit parameter for AUTO2. The 2nd parameter is
+   factor. Set the units to always be meter*/
+  if (strncasecmp(args[0], "AUTO2:", 6) == 0)
+    nUnitsId = 9001;
 
-    msFreeCharArray(args, numargs);
+  msFreeCharArray(args, numargs);
 
-    /* Handle EPSG Units.  Only meters for now. */
-    switch(nUnitsId)
-    {
-      case 9001:  /* Meters */
-        pszUnits = "m";
-        break;
-      default:
-        msSetError(MS_PROJERR, 
-                   "WMS/WFS AUTO PROJECTION: EPSG Units %d not supported.\n",
-                   "_msProcessAutoProjection()", nUnitsId);
-        return -1;
-    }
+  /* Handle EPSG Units.  Only meters for now. */
+  switch(nUnitsId) {
+    case 9001:  /* Meters */
+      pszUnits = "m";
+      break;
+    default:
+      msSetError(MS_PROJERR,
+                 "WMS/WFS AUTO PROJECTION: EPSG Units %d not supported.\n",
+                 "_msProcessAutoProjection()", nUnitsId);
+      return -1;
+  }
 
-    /* Build PROJ4 definition.
-     * This is based on the definitions found in annex E of the WMS 1.1.1 
-     * spec and online at http://www.digitalearth.org/wmt/auto.html
-     * The conversion from the original WKT definitions to PROJ4 format was
-     * done using the MapScript setWKTProjection() function (based on OGR).
-     */
-    switch(nProjId)
-    {
-      case 42001: /** WGS 84 / Auto UTM **/
-        nZone = (int) floor( (dLon0 + 180.0) / 6.0 ) + 1;
-        sprintf( szProjBuf, 
-                 "+proj=tmerc+lat_0=0+lon_0=%.16g+k=0.999600+x_0=500000"
-                 "+y_0=%.16g+ellps=WGS84+datum=WGS84+units=%s", 
-                 -183.0 + nZone * 6.0, 
-                 (dLat0 >= 0.0) ? 0.0 : 10000000.0,
-                 pszUnits);
-        break;
-      case 42002: /** WGS 84 / Auto Tr. Mercator **/
-        sprintf( szProjBuf, 
-                 "+proj=tmerc+lat_0=0+lon_0=%.16g+k=0.999600+x_0=500000"
-                 "+y_0=%.16g+ellps=WGS84+datum=WGS84+units=%s",
-                 dLon0, 
-                 (dLat0 >= 0.0) ? 0.0 : 10000000.0,
-                 pszUnits);
-        break;
-      case 42003: /** WGS 84 / Auto Orthographic **/
-        sprintf( szProjBuf, 
-                 "+proj=ortho+lon_0=%.16g+lat_0=%.16g+x_0=0+y_0=0"
-                 "+ellps=WGS84+datum=WGS84+units=%s",
-                 dLon0, dLat0, pszUnits );
-        break;
-      case 42004: /** WGS 84 / Auto Equirectangular **/
-        /* Note that we have to pass lon_0 as lon_ts for this one to */
-        /* work.  Either a PROJ4 bug or a PROJ4 documentation issue. */
-        sprintf( szProjBuf, 
-                 "+proj=eqc+lon_ts=%.16g+lat_ts=%.16g+x_0=0+y_0=0"
-                 "+ellps=WGS84+datum=WGS84+units=%s",
-                 dLon0, dLat0, pszUnits);
-        break;
-      case 42005: /** WGS 84 / Auto Mollweide **/
-        sprintf( szProjBuf, 
-                 "+proj=moll+lon_0=%.16g+x_0=0+y_0=0+ellps=WGS84"
-                 "+datum=WGS84+units=%s",
-                 dLon0, pszUnits);
-        break;
-      default:
-        msSetError(MS_PROJERR, 
-                   "WMS/WFS AUTO PROJECTION %d not supported.\n",
-                   "_msProcessAutoProjection()", nProjId);
-        return -1;
-    }
+  /* Build PROJ4 definition.
+   * This is based on the definitions found in annex E of the WMS 1.1.1
+   * spec and online at http://www.digitalearth.org/wmt/auto.html
+   * The conversion from the original WKT definitions to PROJ4 format was
+   * done using the MapScript setWKTProjection() function (based on OGR).
+   */
+  switch(nProjId) {
+    case 42001: /** WGS 84 / Auto UTM **/
+      nZone = (int) floor( (dLon0 + 180.0) / 6.0 ) + 1;
+      sprintf( szProjBuf,
+               "+proj=tmerc+lat_0=0+lon_0=%.16g+k=0.999600+x_0=500000"
+               "+y_0=%.16g+ellps=WGS84+datum=WGS84+units=%s",
+               -183.0 + nZone * 6.0,
+               (dLat0 >= 0.0) ? 0.0 : 10000000.0,
+               pszUnits);
+      break;
+    case 42002: /** WGS 84 / Auto Tr. Mercator **/
+      sprintf( szProjBuf,
+               "+proj=tmerc+lat_0=0+lon_0=%.16g+k=0.999600+x_0=500000"
+               "+y_0=%.16g+ellps=WGS84+datum=WGS84+units=%s",
+               dLon0,
+               (dLat0 >= 0.0) ? 0.0 : 10000000.0,
+               pszUnits);
+      break;
+    case 42003: /** WGS 84 / Auto Orthographic **/
+      sprintf( szProjBuf,
+               "+proj=ortho+lon_0=%.16g+lat_0=%.16g+x_0=0+y_0=0"
+               "+ellps=WGS84+datum=WGS84+units=%s",
+               dLon0, dLat0, pszUnits );
+      break;
+    case 42004: /** WGS 84 / Auto Equirectangular **/
+      /* Note that we have to pass lon_0 as lon_ts for this one to */
+      /* work.  Either a PROJ4 bug or a PROJ4 documentation issue. */
+      sprintf( szProjBuf,
+               "+proj=eqc+lon_ts=%.16g+lat_ts=%.16g+x_0=0+y_0=0"
+               "+ellps=WGS84+datum=WGS84+units=%s",
+               dLon0, dLat0, pszUnits);
+      break;
+    case 42005: /** WGS 84 / Auto Mollweide **/
+      sprintf( szProjBuf,
+               "+proj=moll+lon_0=%.16g+x_0=0+y_0=0+ellps=WGS84"
+               "+datum=WGS84+units=%s",
+               dLon0, pszUnits);
+      break;
+    default:
+      msSetError(MS_PROJERR,
+                 "WMS/WFS AUTO PROJECTION %d not supported.\n",
+                 "_msProcessAutoProjection()", nProjId);
+      return -1;
+  }
 
-    /* msDebug("%s = %s\n", p->args[0], szProjBuf); */
+  /* msDebug("%s = %s\n", p->args[0], szProjBuf); */
 
-    /* OK, pass the definition to pj_init() */
-    args = msStringSplit(szProjBuf, '+', &numargs);
+  /* OK, pass the definition to pj_init() */
+  args = msStringSplit(szProjBuf, '+', &numargs);
 
-    msAcquireLock( TLOCK_PROJ );
-    if( !(p->proj = pj_init(numargs, args)) ) {
-        int *pj_errno_ref = pj_get_errno_ref();
-        msReleaseLock( TLOCK_PROJ );
-        msSetError(MS_PROJERR, pj_strerrno(*pj_errno_ref), 
-                   "msProcessProjection()");	  
-        return(-1);
-    }
-    
+  msAcquireLock( TLOCK_PROJ );
+  if( !(p->proj = pj_init(numargs, args)) ) {
+    int *pj_errno_ref = pj_get_errno_ref();
     msReleaseLock( TLOCK_PROJ );
+    msSetError(MS_PROJERR, "proj error \"%s\" for \"%s\"",
+               "msProcessProjection()", pj_strerrno(*pj_errno_ref), szProjBuf) ;
+    return(-1);
+  }
 
-    msFreeCharArray(args, numargs);
+  msReleaseLock( TLOCK_PROJ );
 
-    return(0);
+  msFreeCharArray(args, numargs);
+
+  return(0);
 }
 #endif /* USE_PROJ */
 
 int msProcessProjection(projectionObj *p)
 {
-#ifdef USE_PROJ    
-    assert( p->proj == NULL );
-    
-    if( strcasecmp(p->args[0],"GEOGRAPHIC") == 0 ) {
-        msSetError(MS_PROJERR, 
-                   "PROJECTION 'GEOGRAPHIC' no longer supported.\n"
-                   "Provide explicit definition.\n"
-                   "ie. proj=latlong\n"
-                   "    ellps=clrk66\n",
-                   "msProcessProjection()");	  
-        return(-1);
-    }
-
-    if (strcasecmp(p->args[0], "AUTO") == 0) {
-	p->proj = NULL;
-        return 0;
-    }
+#ifdef USE_PROJ
+  assert( p->proj == NULL );
+
+  if( strcasecmp(p->args[0],"GEOGRAPHIC") == 0 ) {
+    msSetError(MS_PROJERR,
+               "PROJECTION 'GEOGRAPHIC' no longer supported.\n"
+               "Provide explicit definition.\n"
+               "ie. proj=latlong\n"
+               "    ellps=clrk66\n",
+               "msProcessProjection()");
+    return(-1);
+  }
 
-    if (strncasecmp(p->args[0], "AUTO:", 5) == 0 ||
-        strncasecmp(p->args[0], "AUTO2:", 6) == 0)
-    {
-        /* WMS/WFS AUTO projection: "AUTO:proj_id,units_id,lon0,lat0" */
-        /*WMS 1.3.0: AUTO2:auto_crs_id,factor,lon0,lat0*/
-        return _msProcessAutoProjection(p);
-    }
-    msAcquireLock( TLOCK_PROJ );
-    if( !(p->proj = pj_init(p->numargs, p->args)) ) {
-        int *pj_errno_ref = pj_get_errno_ref();
-        msReleaseLock( TLOCK_PROJ );
-        msSetError(MS_PROJERR, pj_strerrno(*pj_errno_ref), 
-                   "msProcessProjection()");	  
-        return(-1);
-    }
-    
-    msReleaseLock( TLOCK_PROJ );
+  if (strcasecmp(p->args[0], "AUTO") == 0) {
+    p->proj = NULL;
+    return 0;
+  }
 
-    return(0);
+  if (strncasecmp(p->args[0], "AUTO:", 5) == 0 ||
+      strncasecmp(p->args[0], "AUTO2:", 6) == 0) {
+    /* WMS/WFS AUTO projection: "AUTO:proj_id,units_id,lon0,lat0" */
+    /*WMS 1.3.0: AUTO2:auto_crs_id,factor,lon0,lat0*/
+    return _msProcessAutoProjection(p);
+  }
+  msAcquireLock( TLOCK_PROJ );
+#if PJ_VERSION < 480
+  if( !(p->proj = pj_init(p->numargs, p->args)) ) {
 #else
-  msSetError(MS_PROJERR, "Projection support is not available.", 
-             "msProcessProjection()");
-  return(-1);
+  p->proj_ctx = pj_ctx_alloc();
+  if( !(p->proj=pj_init_ctx(p->proj_ctx, p->numargs, p->args)) ) {
 #endif
-}
 
-static int loadProjection(projectionObj *p)
-{
-#ifdef USE_PROJ
-  int i=0;
+    int *pj_errno_ref = pj_get_errno_ref();
+    msReleaseLock( TLOCK_PROJ );
+    if(p->numargs>1) {
+      msSetError(MS_PROJERR, "proj error \"%s\" for \"%s:%s\"",
+                 "msProcessProjection()", pj_strerrno(*pj_errno_ref), p->args[0],p->args[1]) ;
+    } else {
+      msSetError(MS_PROJERR, "proj error \"%s\" for \"%s\"",
+                 "msProcessProjection()", pj_strerrno(*pj_errno_ref), p->args[0]) ;
+    }
+    return(-1);
+  }
+
+  msReleaseLock( TLOCK_PROJ );
+
+#ifdef USE_PROJ_FASTPATHS
+  if(strcasestr(p->args[0],"epsg:4326")) {
+    p->wellknownprojection = wkp_lonlat;
+  } else if(strcasestr(p->args[0],"epsg:3857")) {
+    p->wellknownprojection = wkp_gmerc;
+  } else {
+    p->wellknownprojection = wkp_none;
+  }
+#endif
+
+
+  return(0);
+#else
+  msSetError(MS_PROJERR, "Projection support is not available.",
+             "msProcessProjection()");
+  return(-1);
+#endif
+}
+
+static int loadProjection(projectionObj *p)
+{
+#ifdef USE_PROJ
+  int i=0;
 #endif
 
   p->gt.need_geotransform = MS_FALSE;
 
 #ifdef USE_PROJ
 
-  if ( p->proj != NULL )
-  {
-      msSetError(MS_MISCERR, "Projection is already initialized. Multiple projection definitions are not allowed in this object. (line %d)", 
-                   "loadProjection()", msyylineno);	  
-        return(-1);
+  if ( p->proj != NULL ) {
+    msSetError(MS_MISCERR, "Projection is already initialized. Multiple projection definitions are not allowed in this object. (line %d)",
+               "loadProjection()", msyylineno);
+    return(-1);
   }
 
   for(;;) {
     switch(msyylex()) {
-    case(EOF):
-      msSetError(MS_EOFERR, NULL, "loadProjection()");      
-      return(-1);
-    case(END):
-      if( i == 1 && strstr(p->args[0],"+") != NULL )
-      {
+      case(EOF):
+        msSetError(MS_EOFERR, NULL, "loadProjection()");
+        return(-1);
+      case(END):
+        if( i == 1 && strstr(p->args[0],"+") != NULL ) {
           char *one_line_def = p->args[0];
           int result;
 
@@ -1260,26 +1311,24 @@ static int loadProjection(projectionObj *p)
           result = msLoadProjectionString( p, one_line_def );
           free( one_line_def );
           return result;
-      }
-      else
-      {
-      p->numargs = i;
-      if(p->numargs != 0)
-          return msProcessProjection(p);
-      else
-          return 0;
-      }
-      break;
-    case(MS_STRING):
-    case(MS_AUTO):
-      p->args[i] = msStrdup(msyystring_buffer);
-      p->automatic = MS_TRUE;
-      i++;
-      break;
-    default:
-      msSetError(MS_IDENTERR, "Parsing error near (%s):(line %d)", "loadProjection()",
-                 msyystring_buffer, msyylineno);
-      return(-1);
+        } else {
+          p->numargs = i;
+          if(p->numargs != 0)
+            return msProcessProjection(p);
+          else
+            return 0;
+        }
+        break;
+      case(MS_STRING):
+      case(MS_AUTO):
+        p->args[i] = msStrdup(msyystring_buffer);
+        p->automatic = MS_TRUE;
+        i++;
+        break;
+      default:
+        msSetError(MS_IDENTERR, "Parsing error near (%s):(line %d)", "loadProjection()",
+                   msyystring_buffer, msyylineno);
+        return(-1);
     }
   } /* next token */
 #else
@@ -1299,36 +1348,44 @@ static int loadProjection(projectionObj *p)
 int msLoadProjectionStringEPSG(projectionObj *p, const char *value)
 {
 #ifdef USE_PROJ
-   if(p) msFreeProjection(p);
-
-    p->gt.need_geotransform = MS_FALSE;
-    
-    if (strncasecmp(value, "EPSG:", 5) == 0)
-    {
-        size_t buffer_size = 10 + strlen(value+5) + 1;
-        char *init_string = (char*)msSmallMalloc(buffer_size);
-
-        /* translate into PROJ.4 format. */
-        snprintf(init_string, buffer_size, "init=epsg:%s", value+5 );
-
-        p->args = (char**)msSmallMalloc(sizeof(char*) * 2);
-        p->args[0] = init_string;
-        p->numargs = 1;
-        
-
-        if( msIsAxisInverted(atoi(value+5)))
-        {
-            p->args[1] = msStrdup("+epsgaxis=ne");
-            p->numargs = 2;
-        }
+  if(p) msFreeProjection(p);
+
+  p->gt.need_geotransform = MS_FALSE;
+#ifdef USE_PROJ_FASTPATHS
+  if(strcasestr(value,"epsg:4326")) {
+    p->wellknownprojection = wkp_lonlat;
+  } else if(strcasestr(value,"epsg:3857")) {
+    p->wellknownprojection = wkp_gmerc;
+  } else {
+    p->wellknownprojection = wkp_none;
+  }
+#endif
+
+
+  if (strncasecmp(value, "EPSG:", 5) == 0) {
+    size_t buffer_size = 10 + strlen(value+5) + 1;
+    char *init_string = (char*)msSmallMalloc(buffer_size);
 
-        return msProcessProjection( p );
+    /* translate into PROJ.4 format. */
+    snprintf(init_string, buffer_size, "init=epsg:%s", value+5 );
+
+    p->args = (char**)msSmallMalloc(sizeof(char*) * 2);
+    p->args[0] = init_string;
+    p->numargs = 1;
+
+
+    if( msIsAxisInverted(atoi(value+5))) {
+      p->args[1] = msStrdup("+epsgaxis=ne");
+      p->numargs = 2;
     }
 
-    return msLoadProjectionString(p, value);
+    return msProcessProjection( p );
+  }
+
+  return msLoadProjectionString(p, value);
 
 #else
-  msSetError(MS_PROJERR, "Projection support is not available.", 
+  msSetError(MS_PROJERR, "Projection support is not available.",
              "msLoadProjectionStringEPSG()");
   return(-1);
 #endif
@@ -1345,245 +1402,226 @@ int msLoadProjectionString(projectionObj *p, const char *value)
 
   /*
    * Handle new style definitions, the same as they would be given to
-   * the proj program.  
-   * eg. 
+   * the proj program.
+   * eg.
    *    "+proj=utm +zone=11 +ellps=WGS84"
    */
-  if( value[0] == '+' )
-  {
-      char 	*trimmed;
-      int	i, i_out=0;
-
-      trimmed = msStrdup(value+1);
-      for( i = 1; value[i] != '\0'; i++ )
-      {
-          if( !isspace( value[i] ) )
-              trimmed[i_out++] = value[i];
-      }
-      trimmed[i_out] = '\0';
-      
-      p->args = msStringSplit(trimmed,'+', &p->numargs);
-      free( trimmed );
-  }
-  else if (strncasecmp(value, "AUTO:", 5) == 0 ||
-           strncasecmp(value, "AUTO2:", 6) == 0)
-  {
-     /* WMS/WFS AUTO projection: "AUTO:proj_id,units_id,lon0,lat0" */
-     /* WMS 1.3.0 projection: "AUTO2:auto_crs_id,factor,lon0,lat0"*/
-     /* Keep the projection defn into a single token for writeProjection() */
-     /* to work fine. */
-      p->args = (char**)msSmallMalloc(sizeof(char*));
-      p->args[0] = msStrdup(value);
-      p->numargs = 1;
-  }
-  else if (strncasecmp(value, "EPSG:", 5) == 0)
-  {
-      size_t buffer_size = 10 + strlen(value+5) + 1;
-      char *init_string = (char*)msSmallMalloc(buffer_size);
-
-      /* translate into PROJ.4 format. */
-      snprintf( init_string, buffer_size, "init=epsg:%s", value+5);
-
-      p->args = (char**)msSmallMalloc(sizeof(char*) * 2);
-      p->args[0] = init_string;
-      p->numargs = 1;
-  }
-  else if (strncasecmp(value, "urn:ogc:def:crs:EPSG:",21) == 0)
-  { /* this is very preliminary urn support ... expand later */ 
-      size_t buffer_size = 0;
-      char *init_string =  NULL;
-      const char *code;
-
-      code = value + 21;
-
-      while( *code != ':' && *code != '\0' )
-          code++;
-      if( *code == ':' )
-          code++;
-
-      buffer_size = 10 + strlen(code) + 1;
-      init_string = (char*)msSmallMalloc(buffer_size);
-
-      /* translate into PROJ.4 format. */
-      snprintf( init_string, buffer_size, "init=epsg:%s", code );
-
-      p->args = (char**)msSmallMalloc(sizeof(char*) * 2);
-      p->args[0] = init_string;
-      p->numargs = 1;
-
-      if( msIsAxisInverted(atoi(code)))
-      {
-          p->args[1] = msStrdup("+epsgaxis=ne");
-          p->numargs = 2;
-      }
-  }
-  else if (strncasecmp(value, "urn:x-ogc:def:crs:EPSG:",23) == 0)
-  { /*this case is to account for OGC CITE tests where x-ogc was used
-      before the ogc name became an official NID. Note also we also account
-      for the fact that a space for the version of the espg is not used with CITE tests. 
-      (Syntax used could be urn:ogc:def:objectType:authority:code)*/ 
-    
-      size_t buffer_size = 0;
-      char *init_string =  NULL;
-      const char *code;
-
-      if (value[23] == ':')
-        code = value + 23;
-      else
-        code = value + 22;
+  if( value[0] == '+' ) {
+    char  *trimmed;
+    int i, i_out=0;
+
+    trimmed = msStrdup(value+1);
+    for( i = 1; value[i] != '\0'; i++ ) {
+      if( !isspace( value[i] ) )
+        trimmed[i_out++] = value[i];
+    }
+    trimmed[i_out] = '\0';
 
-      while( *code != ':' && *code != '\0' )
-          code++;
-      if( *code == ':' )
-          code++;
+    p->args = msStringSplit(trimmed,'+', &p->numargs);
+    free( trimmed );
+  } else if (strncasecmp(value, "AUTO:", 5) == 0 ||
+             strncasecmp(value, "AUTO2:", 6) == 0) {
+    /* WMS/WFS AUTO projection: "AUTO:proj_id,units_id,lon0,lat0" */
+    /* WMS 1.3.0 projection: "AUTO2:auto_crs_id,factor,lon0,lat0"*/
+    /* Keep the projection defn into a single token for writeProjection() */
+    /* to work fine. */
+    p->args = (char**)msSmallMalloc(sizeof(char*));
+    p->args[0] = msStrdup(value);
+    p->numargs = 1;
+  } else if (strncasecmp(value, "EPSG:", 5) == 0) {
+    size_t buffer_size = 10 + strlen(value+5) + 1;
+    char *init_string = (char*)msSmallMalloc(buffer_size);
+
+    /* translate into PROJ.4 format. */
+    snprintf( init_string, buffer_size, "init=epsg:%s", value+5);
+
+    p->args = (char**)msSmallMalloc(sizeof(char*) * 2);
+    p->args[0] = init_string;
+    p->numargs = 1;
+  } else if (strncasecmp(value, "urn:ogc:def:crs:EPSG:",21) == 0) {
+    /* this is very preliminary urn support ... expand later */
+    size_t buffer_size = 0;
+    char *init_string =  NULL;
+    const char *code;
+
+    code = value + 21;
+
+    while( *code != ':' && *code != '\0' )
+      code++;
+    if( *code == ':' )
+      code++;
+
+    buffer_size = 10 + strlen(code) + 1;
+    init_string = (char*)msSmallMalloc(buffer_size);
+
+    /* translate into PROJ.4 format. */
+    snprintf( init_string, buffer_size, "init=epsg:%s", code );
+
+    p->args = (char**)msSmallMalloc(sizeof(char*) * 2);
+    p->args[0] = init_string;
+    p->numargs = 1;
+
+    if( msIsAxisInverted(atoi(code))) {
+      p->args[1] = msStrdup("+epsgaxis=ne");
+      p->numargs = 2;
+    }
+  } else if (strncasecmp(value, "urn:x-ogc:def:crs:EPSG:",23) == 0) {
+    /*this case is to account for OGC CITE tests where x-ogc was used
+      before the ogc name became an official NID. Note also we also account
+      for the fact that a space for the version of the espg is not used with CITE tests.
+      (Syntax used could be urn:ogc:def:objectType:authority:code)*/
 
-      buffer_size = 10 + strlen(code) + 1;
-      init_string = (char*)msSmallMalloc(buffer_size);
+    size_t buffer_size = 0;
+    char *init_string =  NULL;
+    const char *code;
 
-      /* translate into PROJ.4 format. */
-      snprintf( init_string, buffer_size, "init=epsg:%s", code );
+    if (value[23] == ':')
+      code = value + 23;
+    else
+      code = value + 22;
 
-      p->args = (char**)msSmallMalloc(sizeof(char*) * 2);
-      p->args[0] = init_string;
-      p->numargs = 1;
+    while( *code != ':' && *code != '\0' )
+      code++;
+    if( *code == ':' )
+      code++;
 
-      if( msIsAxisInverted(atoi(code)))
-      {
-          p->args[1] = msStrdup("+epsgaxis=ne");
-          p->numargs = 2;
-      }
-    
-  }
-  else if (strncasecmp(value, "urn:ogc:def:crs:OGC:",20) == 0 )
-  { /* this is very preliminary urn support ... expand later */ 
-      char init_string[100];
-      const char *id;
+    buffer_size = 10 + strlen(code) + 1;
+    init_string = (char*)msSmallMalloc(buffer_size);
 
-      id = value + 20;
-      while( *id != ':' && *id == '\0' )
-          id++;
+    /* translate into PROJ.4 format. */
+    snprintf( init_string, buffer_size, "init=epsg:%s", code );
 
-      if( *id == ':' )
-          id++;
+    p->args = (char**)msSmallMalloc(sizeof(char*) * 2);
+    p->args[0] = init_string;
+    p->numargs = 1;
 
-      init_string[0] = '\0';
+    if( msIsAxisInverted(atoi(code))) {
+      p->args[1] = msStrdup("+epsgaxis=ne");
+      p->numargs = 2;
+    }
 
-      if( strcasecmp(id,"CRS84") == 0 )
-          strncpy( init_string, "init=epsg:4326", sizeof(init_string) );
-      else if( strcasecmp(id,"CRS83") == 0 )
-          strncpy( init_string, "init=epsg:4269", sizeof(init_string) );
-      else if( strcasecmp(id,"CRS27") == 0 )
-          strncpy( init_string, "init=epsg:4267", sizeof(init_string) );
-      else
-      {
-          msSetError( MS_PROJERR, 
-                      "Unrecognised OGC CRS def '%s'.",
-                      "msLoadProjectionString()", 
-                      value );
-          return -1;
-      }
+  } else if (strncasecmp(value, "urn:ogc:def:crs:OGC:",20) == 0 ) {
+    /* this is very preliminary urn support ... expand later */
+    char init_string[100];
+    const char *id;
+
+    id = value + 20;
+    while( *id != ':' && *id == '\0' )
+      id++;
+
+    if( *id == ':' )
+      id++;
+
+    init_string[0] = '\0';
+
+    if( strcasecmp(id,"CRS84") == 0 )
+      strncpy( init_string, "init=epsg:4326", sizeof(init_string) );
+    else if( strcasecmp(id,"CRS83") == 0 )
+      strncpy( init_string, "init=epsg:4269", sizeof(init_string) );
+    else if( strcasecmp(id,"CRS27") == 0 )
+      strncpy( init_string, "init=epsg:4267", sizeof(init_string) );
+    else {
+      msSetError( MS_PROJERR,
+                  "Unrecognised OGC CRS def '%s'.",
+                  "msLoadProjectionString()",
+                  value );
+      return -1;
+    }
 
-      p->args = (char**)msSmallMalloc(sizeof(char*) * 2);
-      p->args[0] = msStrdup(init_string);
-      p->numargs = 1;
+    p->args = (char**)msSmallMalloc(sizeof(char*) * 2);
+    p->args[0] = msStrdup(init_string);
+    p->numargs = 1;
   }
   /* URI projection support */
-  else if (EQUALN("http://www.opengis.net/def/crs/EPSG/", value, 36))
-  { /* this is very preliminary urn support ... expand later */
-      char init_string[100];
-      const char *code;
-
-      code = value + 36;
-      while( *code != '/' && *code != '\0' )
-          code++;
-      if( *code == '/' )
-          code++;
-
-      /* translate into PROJ.4 format. */
-      snprintf( init_string, sizeof(init_string), "init=epsg:%s", code );
-
-      p->args = (char**)msSmallMalloc(sizeof(char*) * 2);
-      p->args[0] = msStrdup(init_string);
-      p->numargs = 1;
-
-      if( msIsAxisInverted(atoi(code)))
-      {
-          p->args[1] = msStrdup("+epsgaxis=ne");
-          p->numargs = 2;
-      }
-  }
-  else if (EQUALN("http://www.opengis.net/def/crs/OGC/", value, 35) )
-  {
-      char init_string[100];
-      const char *id;
-
-      id = value + 35;
-      while( *id != '/' && *id == '\0' )
-          id++;
-      if( *id == '/' )
-          id++;
-
-      init_string[0] = '\0';
-
-      if( strcasecmp(id,"CRS84") == 0 )
-          strncpy( init_string, "init=epsg:4326", sizeof(init_string) );
-      else if( strcasecmp(id,"CRS83") == 0 )
-          strncpy( init_string, "init=epsg:4269", sizeof(init_string) );
-      else if( strcasecmp(id,"CRS27") == 0 )
-          strncpy( init_string, "init=epsg:4267", sizeof(init_string) );
-      else
-      {
-          msSetError( MS_PROJERR,
-                      "Unrecognised OGC CRS def '%s'.",
-                      "msLoadProjectionString()",
-                      value );
-          return -1;
-      }
+  else if (EQUALN("http://www.opengis.net/def/crs/EPSG/", value, 36)) {
+    /* this is very preliminary urn support ... expand later */
+    char init_string[100];
+    const char *code;
+
+    code = value + 36;
+    while( *code != '/' && *code != '\0' )
+      code++;
+    if( *code == '/' )
+      code++;
+
+    /* translate into PROJ.4 format. */
+    snprintf( init_string, sizeof(init_string), "init=epsg:%s", code );
+
+    p->args = (char**)msSmallMalloc(sizeof(char*) * 2);
+    p->args[0] = msStrdup(init_string);
+    p->numargs = 1;
+
+    if( msIsAxisInverted(atoi(code))) {
+      p->args[1] = msStrdup("+epsgaxis=ne");
+      p->numargs = 2;
+    }
+  } else if (EQUALN("http://www.opengis.net/def/crs/OGC/", value, 35) ) {
+    char init_string[100];
+    const char *id;
+
+    id = value + 35;
+    while( *id != '/' && *id == '\0' )
+      id++;
+    if( *id == '/' )
+      id++;
+
+    init_string[0] = '\0';
+
+    if( strcasecmp(id,"CRS84") == 0 )
+      strncpy( init_string, "init=epsg:4326", sizeof(init_string) );
+    else if( strcasecmp(id,"CRS83") == 0 )
+      strncpy( init_string, "init=epsg:4269", sizeof(init_string) );
+    else if( strcasecmp(id,"CRS27") == 0 )
+      strncpy( init_string, "init=epsg:4267", sizeof(init_string) );
+    else {
+      msSetError( MS_PROJERR,
+                  "Unrecognised OGC CRS def '%s'.",
+                  "msLoadProjectionString()",
+                  value );
+      return -1;
+    }
 
-      p->args = (char**)msSmallMalloc(sizeof(char*) * 2);
-      p->args[0] = msStrdup(init_string);
-      p->numargs = 1;
-  }
-  else if (strncasecmp(value, "CRS:",4) == 0 )
-  {
-      char init_string[100];
-      init_string[0] = '\0';
-      if (atoi(value+4) == 84)
-        strncpy( init_string, "init=epsg:4326", sizeof(init_string) );
-      else if (atoi(value+4) == 83)
-        strncpy( init_string, "init=epsg:4269", sizeof(init_string) );
-      else if (atoi(value+4) == 27)
-        strncpy( init_string, "init=epsg:4267", sizeof(init_string) );
-      else
-      {
-          msSetError( MS_PROJERR, 
-                      "Unrecognised OGC CRS def '%s'.",
-                      "msLoadProjectionString()", 
-                      value );
-          return -1;
-      }
-      p->args = (char**)msSmallMalloc(sizeof(char*) * 2);
-      p->args[0] = msStrdup(init_string);
-      p->numargs = 1;
+    p->args = (char**)msSmallMalloc(sizeof(char*) * 2);
+    p->args[0] = msStrdup(init_string);
+    p->numargs = 1;
+  } else if (strncasecmp(value, "CRS:",4) == 0 ) {
+    char init_string[100];
+    init_string[0] = '\0';
+    if (atoi(value+4) == 84)
+      strncpy( init_string, "init=epsg:4326", sizeof(init_string) );
+    else if (atoi(value+4) == 83)
+      strncpy( init_string, "init=epsg:4269", sizeof(init_string) );
+    else if (atoi(value+4) == 27)
+      strncpy( init_string, "init=epsg:4267", sizeof(init_string) );
+    else {
+      msSetError( MS_PROJERR,
+                  "Unrecognised OGC CRS def '%s'.",
+                  "msLoadProjectionString()",
+                  value );
+      return -1;
+    }
+    p->args = (char**)msSmallMalloc(sizeof(char*) * 2);
+    p->args[0] = msStrdup(init_string);
+    p->numargs = 1;
   }
   /*
    * Handle old style comma delimited.  eg. "proj=utm,zone=11,ellps=WGS84".
    */
-  else
-  {
-      p->args = msStringSplit(value,',', &p->numargs);
+  else {
+    p->args = msStringSplit(value,',', &p->numargs);
   }
 
   return msProcessProjection( p );
 #else
-  msSetError(MS_PROJERR, "Projection support is not available.", 
+  msSetError(MS_PROJERR, "Projection support is not available.",
              "msLoadProjectionString()");
   return(-1);
 #endif
 }
 
-static void writeProjection(FILE *stream, int indent, projectionObj *p) {
-#ifdef USE_PROJ  
+static void writeProjection(FILE *stream, int indent, projectionObj *p)
+{
+#ifdef USE_PROJ
   int i;
 
   if(!p || p->numargs <= 0) return;
@@ -1595,6 +1633,18 @@ static void writeProjection(FILE *stream, int indent, projectionObj *p) {
 #endif
 }
 
+void initLeader(labelLeaderObj *leader)
+{
+  leader->gridstep = 5;
+  leader->maxdistance = 0;
+
+  /* Set maxstyles = 0, styles[] will be allocated as needed on first call
+   * to msGrowLabelLeaderStyles()
+   */
+  leader->numstyles = leader->maxstyles = 0;
+  leader->styles = NULL;
+}
+
 /*
 ** Initialize, load and free a labelObj structure
 */
@@ -1602,9 +1652,11 @@ void initLabel(labelObj *label)
 {
   int i;
 
+  MS_REFCNT_INIT(label);
+
   label->antialias = -1; /* off  */
   label->align = MS_ALIGN_LEFT;
-  MS_INIT_COLOR(label->color, 0,0,0,255);  
+  MS_INIT_COLOR(label->color, 0,0,0,255);
   MS_INIT_COLOR(label->outlinecolor, -1,-1,-1,255); /* don't use it */
   label->outlinewidth=1;
 
@@ -1637,14 +1689,14 @@ void initLabel(labelObj *label)
 
   label->encoding = NULL;
 
-  label->force = MS_FALSE;
+  label->force = MS_OFF;
   label->priority = MS_DEFAULT_LABEL_PRIORITY;
 
-  /* Set maxstyles = 0, styles[] will be allocated as needed on first call 
+  /* Set maxstyles = 0, styles[] will be allocated as needed on first call
    * to msGrowLabelStyles()
    */
-  label->numstyles = label->maxstyles = 0;   
-  label->styles = NULL;  
+  label->numstyles = label->maxstyles = 0;
+  label->styles = NULL;
 
   label->numbindings = 0;
   for(i=0; i<MS_LABEL_BINDING_LENGTH; i++) {
@@ -1652,17 +1704,40 @@ void initLabel(labelObj *label)
     label->bindings[i].index = -1;
   }
 
+  label->status = MS_ON;
+  initExpression(&(label->expression));
+  initExpression(&(label->text));
+
+  label->annotext = NULL;
+  label->annopoly = NULL;
+
+  initLeader(&(label->leader));
+
   return;
 }
 
-static void freeLabel(labelObj *label)
+static int freeLabelLeader(labelLeaderObj *leader)
+{
+  int i;
+  for(i=0; i<leader->numstyles; i++) {
+    msFree(leader->styles[i]);
+  }
+  msFree(leader->styles);
+
+  return MS_SUCCESS;
+}
+int freeLabel(labelObj *label)
 {
   int i;
 
+  if( MS_REFCNT_DECR_IS_NOT_ZERO(label) ) {
+    return MS_FAILURE;
+  }
+
   msFree(label->font);
   msFree(label->encoding);
 
-  for(i=0;i<label->numstyles;i++) { /* each style */
+  for(i=0; i<label->numstyles; i++) { /* each style */
     if(label->styles[i]!=NULL) {
       if(freeStyle(label->styles[i]) == MS_SUCCESS) {
         msFree(label->styles[i]);
@@ -1673,6 +1748,54 @@ static void freeLabel(labelObj *label)
 
   for(i=0; i<MS_LABEL_BINDING_LENGTH; i++)
     msFree(label->bindings[i].item);
+
+  freeExpression(&(label->expression));
+  freeExpression(&(label->text));
+
+  /* free book keeping vars associated with the label cache */
+  msFree(label->annotext);
+  if(label->annopoly) {
+    msFreeShape(label->annopoly);
+    msFree(label->annopoly);
+  }
+
+  freeLabelLeader(&(label->leader));
+
+  return MS_SUCCESS;
+}
+
+static int loadLeader(labelLeaderObj *leader)
+{
+  for(;;) {
+    switch(msyylex()) {
+      case(END):
+        return(0);
+        break;
+      case(EOF):
+        msSetError(MS_EOFERR, NULL, "loadLeader()");
+        return(-1);
+      case GRIDSTEP:
+        if(getInteger(&(leader->gridstep)) == -1) return(-1);
+        break;
+      case MAXDISTANCE:
+        if(getInteger(&(leader->maxdistance)) == -1) return(-1);
+        break;
+      case STYLE:
+        if(msGrowLeaderStyles(leader) == NULL)
+          return(-1);
+        initStyle(leader->styles[leader->numstyles]);
+        if(loadStyle(leader->styles[leader->numstyles]) != MS_SUCCESS) return(-1);
+        leader->numstyles++;
+        break;
+      default:
+        if(strlen(msyystring_buffer) > 0) {
+          msSetError(MS_IDENTERR, "Parsing error near (%s):(line %d)", "loadLeader()", msyystring_buffer, msyylineno);
+          return(-1);
+        } else {
+          return(0); /* end of a string, not an error */
+        }
+    }
+  }
 }
 
 static int loadLabel(labelObj *label)
@@ -1681,221 +1804,249 @@ static int loadLabel(labelObj *label)
 
   for(;;) {
     switch(msyylex()) {
-    case(ANGLE):
-      if((symbol = getSymbol(5, MS_NUMBER,MS_AUTO,MS_AUTO2,MS_FOLLOW,MS_BINDING)) == -1) 
-	return(-1);
-
-      if(symbol == MS_NUMBER)
-	label->angle = msyynumber;
-      else if(symbol == MS_BINDING) {
-        if (label->bindings[MS_LABEL_BINDING_ANGLE].item != NULL)
-          msFree(label->bindings[MS_LABEL_BINDING_ANGLE].item);
-        label->bindings[MS_LABEL_BINDING_ANGLE].item = msStrdup(msyystring_buffer);
-        label->numbindings++;
-      } else if ( symbol == MS_FOLLOW ) {
-#ifndef GD_HAS_FTEX_XSHOW
-	msSetError(MS_IDENTERR, "Keyword FOLLOW is not valid without TrueType font support and GD version 2.0.29 or higher.", "loadlabel()");
-	return(-1);
-#else 
-        label->anglemode = MS_FOLLOW;         
-#endif
-      } else if ( symbol == MS_AUTO2 ) {
-	label->anglemode = MS_AUTO2;
-      } else
-	label->anglemode = MS_AUTO;
-      break;
-    case(ALIGN):
-      if((label->align = getSymbol(3, MS_ALIGN_LEFT,MS_ALIGN_CENTER,MS_ALIGN_RIGHT)) == -1) return(-1);
-      break;
-    case(ANTIALIAS):
-      if((label->antialias = getSymbol(2, MS_TRUE,MS_FALSE)) == -1) 
-	return(-1);
-      break;
-    case(BUFFER):
-      if(getInteger(&(label->buffer)) == -1) return(-1);
-      break;
-    case(COLOR): 
-      if(loadColor(&(label->color), &(label->bindings[MS_LABEL_BINDING_COLOR])) != MS_SUCCESS) return(-1);      
-      if(label->bindings[MS_LABEL_BINDING_COLOR].item) label->numbindings++;
-      break;
-    case(ENCODING):
-      if((getString(&label->encoding)) == MS_FAILURE) return(-1);
-      break;
-    case(END):
-      return(0);
-      break;
-    case(EOF):
-      msSetError(MS_EOFERR, NULL, "loadLabel()");      
-      return(-1);
-    case(FONT):
-#if defined (USE_GD_TTF) || defined (USE_GD_FT)
-      if((symbol = getSymbol(2, MS_STRING, MS_BINDING)) == -1)
+      case(ANGLE):
+        if((symbol = getSymbol(5, MS_NUMBER,MS_AUTO,MS_AUTO2,MS_FOLLOW,MS_BINDING)) == -1)
+          return(-1);
+
+        if(symbol == MS_NUMBER)
+          label->angle = msyynumber;
+        else if(symbol == MS_BINDING) {
+          if (label->bindings[MS_LABEL_BINDING_ANGLE].item != NULL)
+            msFree(label->bindings[MS_LABEL_BINDING_ANGLE].item);
+          label->bindings[MS_LABEL_BINDING_ANGLE].item = msStrdup(msyystring_buffer);
+          label->numbindings++;
+        } else if ( symbol == MS_FOLLOW ) {
+          label->anglemode = MS_FOLLOW;
+        } else if ( symbol == MS_AUTO2 ) {
+          label->anglemode = MS_AUTO2;
+        } else
+          label->anglemode = MS_AUTO;
+        break;
+      case(ALIGN):
+        if((label->align = getSymbol(3, MS_ALIGN_LEFT,MS_ALIGN_CENTER,MS_ALIGN_RIGHT)) == -1) return(-1);
+        break;
+      case(ANTIALIAS):
+        if((label->antialias = getSymbol(2, MS_TRUE,MS_FALSE)) == -1)
+          return(-1);
+        break;
+      case(BUFFER):
+        if(getInteger(&(label->buffer)) == -1) return(-1);
+        break;
+      case(COLOR):
+        if(loadColor(&(label->color), &(label->bindings[MS_LABEL_BINDING_COLOR])) != MS_SUCCESS) return(-1);
+        if(label->bindings[MS_LABEL_BINDING_COLOR].item) label->numbindings++;
+        break;
+      case(ENCODING):
+        if((getString(&label->encoding)) == MS_FAILURE) return(-1);
+        break;
+      case(END):
+        /* sanity check */
+        if(label->anglemode == MS_FOLLOW && label->type == MS_BITMAP) {
+          msSetError(MS_MISCERR,"Follow labels not supported with bitmap fonts.", "loadLabel()");
+          return -1;
+        }
+        return(0);
+        break;
+      case(EOF):
+        msSetError(MS_EOFERR, NULL, "loadLabel()");
         return(-1);
+      case(EXPRESSION):
+        if(loadExpression(&(label->expression)) == -1) return(-1); /* loadExpression() cleans up previously allocated expression */
+        if(msyysource == MS_URL_TOKENS) {
+          msSetError(MS_MISCERR, "URL-based EXPRESSION configuration not supported." , "loadLabel()");
+          freeExpression(&(label->expression));
+          return(-1);
+        }
+        break;
+      case(FONT):
+        if((symbol = getSymbol(2, MS_STRING, MS_BINDING)) == -1)
+          return(-1);
 
-      if(symbol == MS_STRING) {
-        if (label->font != NULL)
-          msFree(label->font);
-        label->font = msStrdup(msyystring_buffer);
-      } else {
-        if (label->bindings[MS_LABEL_BINDING_FONT].item != NULL)
-          msFree(label->bindings[MS_LABEL_BINDING_FONT].item);
-        label->bindings[MS_LABEL_BINDING_FONT].item = msStrdup(msyystring_buffer);
-        label->numbindings++;
-      }
-#else
-      msSetError(MS_IDENTERR, "Keyword FONT is not valid without TrueType font support.", "loadlabel()");    
-      return(-1);
-#endif
-      break;
-    case(FORCE):
-      if((label->force = getSymbol(2, MS_TRUE,MS_FALSE)) == -1) return(-1);
-      break;
-    case(LABEL):
-      break; /* for string loads */
-    case(MAXSIZE):      
-      if(getDouble(&(label->maxsize)) == -1) return(-1);
-      break;
-    case(MAXSCALEDENOM):
-      if(getDouble(&(label->maxscaledenom)) == -1) return(-1);
-      break;
-    case(MAXLENGTH):
-      if(getInteger(&(label->maxlength)) == -1) return(-1);
-      break;
-    case(MINLENGTH):
-      if(getInteger(&(label->minlength)) == -1) return(-1);
-      break; 
-    case(MINDISTANCE):      
-      if(getInteger(&(label->mindistance)) == -1) return(-1);
-      break;
-    case(REPEATDISTANCE):      
-      if(getInteger(&(label->repeatdistance)) == -1) return(-1);
-      break;
-    case(MAXOVERLAPANGLE):      
-      if(getDouble(&(label->maxoverlapangle)) == -1) return(-1);
-      break;
-    case(MINFEATURESIZE):
-      if((symbol = getSymbol(2, MS_NUMBER,MS_AUTO)) == -1)  return(-1);
-      if(symbol == MS_NUMBER)
-	label->minfeaturesize = (int)msyynumber;
-      else
-	label->autominfeaturesize = MS_TRUE;
-      break;
-    case(MINSCALEDENOM):
-      if(getDouble(&(label->minscaledenom)) == -1) return(-1);
-      break;
-    case(MINSIZE):
-      if(getDouble(&(label->minsize)) == -1) return(-1);
-      break;
-    case(OFFSET):
-      if(getInteger(&(label->offsetx)) == -1) return(-1);
-      if(getInteger(&(label->offsety)) == -1) return(-1);
-      break;
-    case(OUTLINECOLOR):
-      if(loadColor(&(label->outlinecolor), &(label->bindings[MS_LABEL_BINDING_OUTLINECOLOR])) != MS_SUCCESS) return(-1);      
-      if(label->bindings[MS_LABEL_BINDING_OUTLINECOLOR].item) label->numbindings++;
-      break;
-    case(OUTLINEWIDTH):
-      if(getInteger(&(label->outlinewidth)) == -1) return(-1);
-      break;
-    case(PARTIALS):
-      if((label->partials = getSymbol(2, MS_TRUE,MS_FALSE)) == -1) return(-1);
-      break;
-    case(POSITION):
-      if((label->position = getSymbol(11, MS_UL,MS_UC,MS_UR,MS_CL,MS_CC,MS_CR,MS_LL,MS_LC,MS_LR,MS_AUTO,MS_BINDING)) == -1)
+        if(symbol == MS_STRING) {
+          if (label->font != NULL)
+            msFree(label->font);
+          label->font = msStrdup(msyystring_buffer);
+        } else {
+          if (label->bindings[MS_LABEL_BINDING_FONT].item != NULL)
+            msFree(label->bindings[MS_LABEL_BINDING_FONT].item);
+          label->bindings[MS_LABEL_BINDING_FONT].item = msStrdup(msyystring_buffer);
+          label->numbindings++;
+        }
+        break;
+      case(FORCE):
+        switch(msyylex()) {
+          case MS_ON:
+            label->force = MS_ON;
+            break;
+          case MS_OFF:
+            label->force = MS_OFF;
+            break;
+          case GROUP:
+            label->force = MS_LABEL_FORCE_GROUP;
+            break;
+          default:
+            msSetError(MS_MISCERR, "Invalid FORCE, must be ON,OFF,or GROUP" , "loadLabel()");
+            return(-1);
+        }
+        break;
+      case(LABEL):
+        break; /* for string loads */
+      case(LEADER):
+        msSetError(MS_MISCERR, "LABEL LEADER not implemented. LEADER goes at the CLASS level." , "loadLabel()");
         return(-1);
-      if(label->position == MS_BINDING) {
-        if(label->bindings[MS_LABEL_BINDING_POSITION].item != NULL)
-	  msFree(label->bindings[MS_LABEL_BINDING_POSITION].item);
-	  label->bindings[MS_LABEL_BINDING_POSITION].item = strdup(msyystring_buffer);
-	  label->numbindings++;
-	}
-      break;
-    case(PRIORITY):
-      if((symbol = getSymbol(2, MS_NUMBER,MS_BINDING)) == -1) return(-1);
-      if(symbol == MS_NUMBER) {
-        label->priority = (int) msyynumber;
-        if(label->priority < 1 || label->priority > MS_MAX_LABEL_PRIORITY) {
-          msSetError(MS_MISCERR, "Invalid PRIORITY, must be an integer between 1 and %d." , "loadLabel()", MS_MAX_LABEL_PRIORITY);
+        if(loadLeader(&(label->leader)) == -1) return(-1);
+        break;
+      case(MAXSIZE):
+        if(getDouble(&(label->maxsize)) == -1) return(-1);
+        break;
+      case(MAXSCALEDENOM):
+        if(getDouble(&(label->maxscaledenom)) == -1) return(-1);
+        break;
+      case(MAXLENGTH):
+        if(getInteger(&(label->maxlength)) == -1) return(-1);
+        break;
+      case(MINLENGTH):
+        if(getInteger(&(label->minlength)) == -1) return(-1);
+        break;
+      case(MINDISTANCE):
+        if(getInteger(&(label->mindistance)) == -1) return(-1);
+        break;
+      case(REPEATDISTANCE):
+        if(getInteger(&(label->repeatdistance)) == -1) return(-1);
+        break;
+      case(MAXOVERLAPANGLE):
+        if(getDouble(&(label->maxoverlapangle)) == -1) return(-1);
+        break;
+      case(MINFEATURESIZE):
+        if((symbol = getSymbol(2, MS_NUMBER,MS_AUTO)) == -1)  return(-1);
+        if(symbol == MS_NUMBER)
+          label->minfeaturesize = (int)msyynumber;
+        else
+          label->autominfeaturesize = MS_TRUE;
+        break;
+      case(MINSCALEDENOM):
+        if(getDouble(&(label->minscaledenom)) == -1) return(-1);
+        break;
+      case(MINSIZE):
+        if(getDouble(&(label->minsize)) == -1) return(-1);
+        break;
+      case(OFFSET):
+        if(getInteger(&(label->offsetx)) == -1) return(-1);
+        if(getInteger(&(label->offsety)) == -1) return(-1);
+        break;
+      case(OUTLINECOLOR):
+        if(loadColor(&(label->outlinecolor), &(label->bindings[MS_LABEL_BINDING_OUTLINECOLOR])) != MS_SUCCESS) return(-1);
+        if(label->bindings[MS_LABEL_BINDING_OUTLINECOLOR].item) label->numbindings++;
+        break;
+      case(OUTLINEWIDTH):
+        if(getInteger(&(label->outlinewidth)) == -1) return(-1);
+        break;
+      case(PARTIALS):
+        if((label->partials = getSymbol(2, MS_TRUE,MS_FALSE)) == -1) return(-1);
+        break;
+      case(POSITION):
+        if((label->position = getSymbol(11, MS_UL,MS_UC,MS_UR,MS_CL,MS_CC,MS_CR,MS_LL,MS_LC,MS_LR,MS_AUTO,MS_BINDING)) == -1)
           return(-1);
+        if(label->position == MS_BINDING) {
+          if(label->bindings[MS_LABEL_BINDING_POSITION].item != NULL)
+            msFree(label->bindings[MS_LABEL_BINDING_POSITION].item);
+          label->bindings[MS_LABEL_BINDING_POSITION].item = strdup(msyystring_buffer);
+          label->numbindings++;
+        }
+        break;
+      case(PRIORITY):
+        if((symbol = getSymbol(2, MS_NUMBER,MS_BINDING)) == -1) return(-1);
+        if(symbol == MS_NUMBER) {
+          label->priority = (int) msyynumber;
+          if(label->priority < 1 || label->priority > MS_MAX_LABEL_PRIORITY) {
+            msSetError(MS_MISCERR, "Invalid PRIORITY, must be an integer between 1 and %d." , "loadLabel()", MS_MAX_LABEL_PRIORITY);
+            return(-1);
+          }
+        } else {
+          if (label->bindings[MS_LABEL_BINDING_PRIORITY].item != NULL)
+            msFree(label->bindings[MS_LABEL_BINDING_PRIORITY].item);
+          label->bindings[MS_LABEL_BINDING_PRIORITY].item = msStrdup(msyystring_buffer);
+          label->numbindings++;
+        }
+        break;
+      case(SHADOWCOLOR):
+        if(loadColor(&(label->shadowcolor), NULL) != MS_SUCCESS) return(-1);
+        break;
+      case(SHADOWSIZE):
+        /* if(getInteger(&(label->shadowsizex)) == -1) return(-1); */
+        if((symbol = getSymbol(2, MS_NUMBER,MS_BINDING)) == -1) return(-1);
+        if(symbol == MS_NUMBER) {
+          label->shadowsizex = (int) msyynumber;
+        } else {
+          if (label->bindings[MS_LABEL_BINDING_SHADOWSIZEX].item != NULL)
+            msFree(label->bindings[MS_LABEL_BINDING_SHADOWSIZEX].item);
+          label->bindings[MS_LABEL_BINDING_SHADOWSIZEX].item = msStrdup(msyystring_buffer);
+          label->numbindings++;
         }
-      } else {
-        if (label->bindings[MS_LABEL_BINDING_PRIORITY].item != NULL)
-          msFree(label->bindings[MS_LABEL_BINDING_PRIORITY].item);
-        label->bindings[MS_LABEL_BINDING_PRIORITY].item = msStrdup(msyystring_buffer);
-        label->numbindings++;
-      }
-      break;
-    case(SHADOWCOLOR):
-      if(loadColor(&(label->shadowcolor), NULL) != MS_SUCCESS) return(-1);      
-      break;
-    case(SHADOWSIZE):
-      /* if(getInteger(&(label->shadowsizex)) == -1) return(-1); */
-      if((symbol = getSymbol(2, MS_NUMBER,MS_BINDING)) == -1) return(-1);
-      if(symbol == MS_NUMBER) {
-        label->shadowsizex = (int) msyynumber;
-      } else {
-        if (label->bindings[MS_LABEL_BINDING_SHADOWSIZEX].item != NULL)
-          msFree(label->bindings[MS_LABEL_BINDING_SHADOWSIZEX].item);
-        label->bindings[MS_LABEL_BINDING_SHADOWSIZEX].item = msStrdup(msyystring_buffer);
-        label->numbindings++;
-      }
 
-      /* if(getInteger(&(label->shadowsizey)) == -1) return(-1); */
-      if((symbol = getSymbol(2, MS_NUMBER,MS_BINDING)) == -1) return(-1);
-      if(symbol == MS_NUMBER) {
-	label->shadowsizey = (int) msyynumber;
-      } else {
-	if (label->bindings[MS_LABEL_BINDING_SHADOWSIZEY].item != NULL)
-          msFree(label->bindings[MS_LABEL_BINDING_SHADOWSIZEY].item);
-        label->bindings[MS_LABEL_BINDING_SHADOWSIZEY].item = msStrdup(msyystring_buffer);
-        label->numbindings++;
-      }
-      break;
-    case(SIZE):
-#if defined (USE_GD_TTF) || defined (USE_GD_FT)
-      if(label->bindings[MS_LABEL_BINDING_SIZE].item) {
-        msFree(label->bindings[MS_LABEL_BINDING_SIZE].item);
-        label->bindings[MS_LABEL_BINDING_SIZE].item = NULL;
-	label->numbindings--;
-      }
+        /* if(getInteger(&(label->shadowsizey)) == -1) return(-1); */
+        if((symbol = getSymbol(2, MS_NUMBER,MS_BINDING)) == -1) return(-1);
+        if(symbol == MS_NUMBER) {
+          label->shadowsizey = (int) msyynumber;
+        } else {
+          if (label->bindings[MS_LABEL_BINDING_SHADOWSIZEY].item != NULL)
+            msFree(label->bindings[MS_LABEL_BINDING_SHADOWSIZEY].item);
+          label->bindings[MS_LABEL_BINDING_SHADOWSIZEY].item = msStrdup(msyystring_buffer);
+          label->numbindings++;
+        }
+        break;
+      case(SIZE):
+        if(label->bindings[MS_LABEL_BINDING_SIZE].item) {
+          msFree(label->bindings[MS_LABEL_BINDING_SIZE].item);
+          label->bindings[MS_LABEL_BINDING_SIZE].item = NULL;
+          label->numbindings--;
+        }
 
-      if((symbol = getSymbol(7, MS_NUMBER,MS_BINDING,MS_TINY,MS_SMALL,MS_MEDIUM,MS_LARGE,MS_GIANT)) == -1) 
-	return(-1);
+        if((symbol = getSymbol(7, MS_NUMBER,MS_BINDING,MS_TINY,MS_SMALL,MS_MEDIUM,MS_LARGE,MS_GIANT)) == -1)
+          return(-1);
 
-      if(symbol == MS_NUMBER) {
-        label->size = (double) msyynumber;
-      } else if(symbol == MS_BINDING) {
-        label->bindings[MS_LABEL_BINDING_SIZE].item = msStrdup(msyystring_buffer);
-        label->numbindings++;
-      } else
-        label->size = symbol;
-#else
-      if((label->size = getSymbol(5, MS_TINY,MS_SMALL,MS_MEDIUM,MS_LARGE,MS_GIANT)) == -1) 
-        return(-1);
-#endif
-      break; 
-    case(STYLE):
-      if(msGrowLabelStyles(label) == NULL)
-        return(-1);
-      initStyle(label->styles[label->numstyles]);
-      if(loadStyle(label->styles[label->numstyles]) != MS_SUCCESS) return(-1);
-      if(label->styles[label->numstyles]->_geomtransform.type == MS_GEOMTRANSFORM_NONE) 
-        label->styles[label->numstyles]->_geomtransform.type = MS_GEOMTRANSFORM_LABELPOINT; /* set a default, a marker? */
-      label->numstyles++;
-      break;
-    case(TYPE):
-      if((label->type = getSymbol(2, MS_TRUETYPE,MS_BITMAP)) == -1) return(-1);
-      break;    
-    case(WRAP):      
-      if(getCharacter(&(label->wrap)) == -1) return(-1);
-      break;
-    default:
-      if(strlen(msyystring_buffer) > 0) {
-        msSetError(MS_IDENTERR, "Parsing error near (%s):(line %d)", "loadLabel()", msyystring_buffer, msyylineno);
-        return(-1);
-      } else {
-        return(0); /* end of a string, not an error */
-      }
+        if(symbol == MS_NUMBER) {
+          label->size = (double) msyynumber;
+        } else if(symbol == MS_BINDING) {
+          label->bindings[MS_LABEL_BINDING_SIZE].item = msStrdup(msyystring_buffer);
+          label->numbindings++;
+        } else
+          label->size = symbol;
+        break;
+      case(STYLE):
+        if(msGrowLabelStyles(label) == NULL)
+          return(-1);
+        initStyle(label->styles[label->numstyles]);
+        if(loadStyle(label->styles[label->numstyles]) != MS_SUCCESS) return(-1);
+        if(label->styles[label->numstyles]->_geomtransform.type == MS_GEOMTRANSFORM_NONE)
+          label->styles[label->numstyles]->_geomtransform.type = MS_GEOMTRANSFORM_LABELPOINT; /* set a default, a marker? */
+        label->numstyles++;
+        break;
+      case(TEXT):
+        if(loadExpression(&(label->text)) == -1) return(-1); /* loadExpression() cleans up previously allocated expression */
+        if(msyysource == MS_URL_TOKENS) {
+          msSetError(MS_MISCERR, "URL-based TEXT configuration not supported for labels." , "loadLabel()");
+          freeExpression(&(label->text));
+          return(-1);
+        }
+        if((label->text.type != MS_STRING) && (label->text.type != MS_EXPRESSION)) {
+          msSetError(MS_MISCERR, "Text expressions support constant or tagged replacement strings." , "loadLabel()");
+          return(-1);
+        }
+        break;
+      case(TYPE):
+        if((label->type = getSymbol(2, MS_TRUETYPE,MS_BITMAP)) == -1) return(-1);
+        break;
+      case(WRAP):
+        if(getCharacter(&(label->wrap)) == -1) return(-1);
+        break;
+      default:
+        if(strlen(msyystring_buffer) > 0) {
+          msSetError(MS_IDENTERR, "Parsing error near (%s):(line %d)", "loadLabel()", msyystring_buffer, msyylineno);
+          return(-1);
+        } else {
+          return(0); /* end of a string, not an error */
+        }
     }
   } /* next token */
 }
@@ -1922,6 +2073,22 @@ int msUpdateLabelFromString(labelObj *label, char *string)
   return MS_SUCCESS;
 }
 
+static void writeLeader(FILE *stream, int indent, labelLeaderObj *leader)
+{
+  int i;
+  if(leader->maxdistance == 0 && leader->numstyles == 0) {
+    return;
+  }
+  indent++;
+  writeBlockBegin(stream, indent, "LEADER");
+  writeNumber(stream, indent, "MAXDISTANCE", 0, leader->maxdistance);
+  writeNumber(stream, indent, "GRIDSTEP", 5, leader->gridstep);
+  for(i=0; i<leader->numstyles; i++)
+    writeStyle(stream, indent, leader->styles[i]);
+
+  writeBlockEnd(stream, indent, "LEADER");
+}
+
 static void writeLabel(FILE *stream, int indent, labelObj *label)
 {
   int i;
@@ -1944,6 +2111,8 @@ static void writeLabel(FILE *stream, int indent, labelObj *label)
 
     writeKeyword(stream, indent, "ANTIALIAS", label->antialias, 1, MS_TRUE, "TRUE");
 
+    writeExpression(stream, indent, "EXPRESSION", &(label->expression));
+
     if(label->numbindings > 0 && label->bindings[MS_LABEL_BINDING_FONT].item)
       writeAttributeBinding(stream, indent, "FONT", &(label->bindings[MS_LABEL_BINDING_FONT]));
     else writeString(stream, indent, "FONT", NULL, label->font);
@@ -1967,7 +2136,8 @@ static void writeLabel(FILE *stream, int indent, labelObj *label)
   }
 
   writeString(stream, indent, "ENCODING", NULL, label->encoding);
-  writeKeyword(stream, indent, "FORCE", label->force, 1, MS_TRUE, "TRUE");
+  writeLeader(stream,indent,&(label->leader));
+  writeKeyword(stream, indent, "FORCE", label->force, 2, MS_TRUE, "TRUE", MS_LABEL_FORCE_GROUP, "GROUP");
   writeNumber(stream, indent, "MAXLENGTH", 0, label->maxlength);
   writeNumber(stream, indent, "MAXSCALEDENOM", -1, label->maxscaledenom);
   writeNumber(stream, indent, "MINDISTANCE", -1, label->mindistance);
@@ -1975,7 +2145,7 @@ static void writeLabel(FILE *stream, int indent, labelObj *label)
   writeNumber(stream, indent, "MINLENGTH", 0, label->minlength);
   writeNumber(stream, indent, "MINSCALEDENOM", -1, label->minscaledenom);
   writeDimension(stream, indent, "OFFSET",  label->offsetx, label->offsety, NULL, NULL);
-    
+
   if(label->numbindings > 0 && label->bindings[MS_LABEL_BINDING_OUTLINECOLOR].item)
     writeAttributeBinding(stream, indent, "OUTLINECOLOR", &(label->bindings[MS_LABEL_BINDING_OUTLINECOLOR]));
   else  writeColor(stream, indent, "OUTLINECOLOR", NULL, &(label->outlinecolor));
@@ -1984,7 +2154,7 @@ static void writeLabel(FILE *stream, int indent, labelObj *label)
   writeKeyword(stream, indent, "PARTIALS", label->partials, 1, MS_FALSE, "FALSE");
 
   if(label->numbindings > 0 && label->bindings[MS_LABEL_BINDING_POSITION].item)
-     writeAttributeBinding(stream, indent, "POSITION", &(label->bindings[MS_LABEL_BINDING_POSITION]));
+    writeAttributeBinding(stream, indent, "POSITION", &(label->bindings[MS_LABEL_BINDING_POSITION]));
   else writeKeyword(stream, indent, "POSITION", label->position, 10, MS_UL, "UL", MS_UC, "UC", MS_UR, "UR", MS_CL, "CL", MS_CC, "CC", MS_CR, "CR", MS_LL, "LL", MS_LC, "LC", MS_LR, "LR", MS_AUTO, "AUTO");
 
   if(label->numbindings > 0 && label->bindings[MS_LABEL_BINDING_PRIORITY].item)
@@ -1998,6 +2168,9 @@ static void writeLabel(FILE *stream, int indent, labelObj *label)
   writeNumber(stream, indent, "MAXOVERLAPANGLE", 22.5, label->maxoverlapangle);
   for(i=0; i<label->numstyles; i++)
     writeStyle(stream, indent, label->styles[i]);
+
+  writeExpression(stream, indent, "TEXT", &(label->text));
+
   writeKeyword(stream, indent, "TYPE", label->type, 2, MS_BITMAP, "BITMAP", MS_TRUETYPE, "TRUETYPE");
   writeCharacter(stream, indent, "WRAP", '\0', label->wrap);
   writeBlockEnd(stream, indent, "LABEL");
@@ -2025,22 +2198,22 @@ void freeExpressionTokens(expressionObj *exp)
       nextNode = node->next;
 
       switch(node->token) {
-      case MS_TOKEN_BINDING_DOUBLE:
-      case MS_TOKEN_BINDING_INTEGER:
-      case MS_TOKEN_BINDING_STRING:
-      case MS_TOKEN_BINDING_TIME:
-        msFree(node->tokenval.bindval.item);
-        break;
-      case MS_TOKEN_LITERAL_TIME:
-        /* anything to do? */
-        break;
-      case MS_TOKEN_LITERAL_STRING:
-        msFree(node->tokenval.strval);
-        break;
-      case MS_TOKEN_LITERAL_SHAPE:
-        msFreeShape(node->tokenval.shpval);
-        free(node->tokenval.shpval);
-        break;
+        case MS_TOKEN_BINDING_DOUBLE:
+        case MS_TOKEN_BINDING_INTEGER:
+        case MS_TOKEN_BINDING_STRING:
+        case MS_TOKEN_BINDING_TIME:
+          msFree(node->tokenval.bindval.item);
+          break;
+        case MS_TOKEN_LITERAL_TIME:
+          /* anything to do? */
+          break;
+        case MS_TOKEN_LITERAL_STRING:
+          msFree(node->tokenval.strval);
+          break;
+        case MS_TOKEN_LITERAL_SHAPE:
+          msFreeShape(node->tokenval.shpval);
+          free(node->tokenval.shpval);
+          break;
       }
 
       msFree(node);
@@ -2076,7 +2249,7 @@ int loadExpression(expressionObj *exp)
     exp->flags = exp->flags | MS_EXP_INSENSITIVE;
     exp->type = MS_REGEX;
   }
-  
+
   return(0);
 }
 
@@ -2091,7 +2264,7 @@ int loadExpression(expressionObj *exp)
 
    See bug 339 for more details -- SG.
    ------------------------------------------------------------------------ */
-   
+
 int msLoadExpressionString(expressionObj *exp, char *value)
 {
   int retval = MS_FAILURE;
@@ -2105,13 +2278,14 @@ int msLoadExpressionString(expressionObj *exp, char *value)
 
 int loadExpressionString(expressionObj *exp, char *value)
 {
-  msyystate = MS_TOKENIZE_STRING; msyystring = value;
+  msyystate = MS_TOKENIZE_STRING;
+  msyystring = value;
   msyylex(); /* sets things up but processes no tokens */
 
   freeExpression(exp); /* we're totally replacing the old expression so free (which re-inits) to start over */
 
   msyystring_icase = MS_TRUE;
-  if((exp->type = getSymbol(4, MS_EXPRESSION,MS_REGEX,MS_IREGEX,MS_ISTRING)) != -1) {
+  if((exp->type = getSymbol2(4, MS_EXPRESSION,MS_REGEX,MS_IREGEX,MS_ISTRING)) != -1) {
     exp->string = msStrdup(msyystring_buffer);
 
     if(exp->type == MS_ISTRING) {
@@ -2122,7 +2296,7 @@ int loadExpressionString(expressionObj *exp, char *value)
       exp->flags = exp->flags | MS_EXP_INSENSITIVE;
     }
   } else {
-    msResetErrorList(); /* failure above is not really an error since we'll consider anything not matching (like an unquoted number) as a STRING) */
+    /* failure above is not an error since we'll consider anything not matching (like an unquoted number) as a STRING) */
     exp->type = MS_STRING;
     if((strlen(value) - strlen(msyystring_buffer)) == 2)
       exp->string = msStrdup(msyystring_buffer); /* value was quoted */
@@ -2130,7 +2304,7 @@ int loadExpressionString(expressionObj *exp, char *value)
       exp->string = msStrdup(value); /* use the whole value */
   }
 
-  return(0); 
+  return(0);
 }
 
 /* msGetExpressionString()
@@ -2140,7 +2314,7 @@ int loadExpressionString(expressionObj *exp, char *value)
  *
  * Returns a newly allocated buffer that should be freed by the caller or NULL.
  */
-char *msGetExpressionString(expressionObj *exp) 
+char *msGetExpressionString(expressionObj *exp)
 {
   if(exp->string) {
     char *exprstring;
@@ -2155,19 +2329,19 @@ char *msGetExpressionString(expressionObj *exp)
     exprstring = (char*)msSmallMalloc(buffer_size);
 
     switch(exp->type) {
-    case(MS_REGEX):
-      snprintf(exprstring, buffer_size, "/%s/%s", exp->string, case_insensitive);
-      return exprstring;
-    case(MS_STRING):
-      snprintf(exprstring, buffer_size, "\"%s\"%s", exp->string, case_insensitive);
-      return exprstring;
-    case(MS_EXPRESSION):
-      snprintf(exprstring, buffer_size, "(%s)", exp->string);
-      return exprstring;
-    default:
-      /* We should never get to here really! */
-      free(exprstring);
-      return NULL;
+      case(MS_REGEX):
+        snprintf(exprstring, buffer_size, "/%s/%s", exp->string, case_insensitive);
+        return exprstring;
+      case(MS_STRING):
+        snprintf(exprstring, buffer_size, "\"%s\"%s", exp->string, case_insensitive);
+        return exprstring;
+      case(MS_EXPRESSION):
+        snprintf(exprstring, buffer_size, "(%s)", exp->string);
+        return exprstring;
+      default:
+        /* We should never get to here really! */
+        free(exprstring);
+        return NULL;
     }
   }
   return NULL;
@@ -2180,25 +2354,25 @@ static void writeExpression(FILE *stream, int indent, const char *name, expressi
 
   writeIndent(stream, ++indent);
   switch(exp->type) {
-  case(MS_REGEX):
-    fprintf(stream, "%s /%s/", name, exp->string);
-    break;
-  case(MS_STRING):
+    case(MS_REGEX):
+      fprintf(stream, "%s /%s/", name, exp->string);
+      break;
+    case(MS_STRING):
       if ( (strchr(exp->string, '\'') == NULL) && (strchr(exp->string, '\"') == NULL))
-          fprintf(stream, "%s \"%s\"", name, exp->string);
+        fprintf(stream, "%s \"%s\"", name, exp->string);
       else if ( (strchr(exp->string, '\"') != NULL) && (strchr(exp->string, '\'') == NULL))
-          fprintf(stream, "%s \'%s\'", name, exp->string);
+        fprintf(stream, "%s \'%s\'", name, exp->string);
       else if ( (strchr(exp->string, '\'') != NULL) && (strchr(exp->string, '\"') == NULL))
-          fprintf(stream, "%s \"%s\"", name, exp->string);
+        fprintf(stream, "%s \"%s\"", name, exp->string);
       else {
-          string_tmp = msStringEscape(exp->string);
-          fprintf(stream, "%s \"%s\"", name, string_tmp);
-          free(string_tmp);
-      }   
-    break;
-  case(MS_EXPRESSION):
-    fprintf(stream, "%s (%s)", name, exp->string);
-    break;
+        string_tmp = msStringEscape(exp->string);
+        fprintf(stream, "%s \"%s\"", name, string_tmp);
+        if(exp->string!=string_tmp) free(string_tmp);
+      }
+      break;
+    case(MS_EXPRESSION):
+      fprintf(stream, "%s (%s)", name, exp->string);
+      break;
   }
   if((exp->type == MS_STRING || exp->type == MS_REGEX) && (exp->flags & MS_EXP_INSENSITIVE))
     fprintf(stream, "i");
@@ -2208,34 +2382,36 @@ static void writeExpression(FILE *stream, int indent, const char *name, expressi
 int loadHashTable(hashTableObj *ptable)
 {
   char *key=NULL, *data=NULL;
-  
+
   if (!ptable) ptable = msCreateHashTable();
 
   for(;;) {
     switch(msyylex()) {
-    case(EOF):
-      msSetError(MS_EOFERR, NULL, "loadHashTable()");
-      return(MS_FAILURE);
-    case(END):
-      return(MS_SUCCESS);
-    case(MS_STRING):
-      key = msStrdup(msyystring_buffer); /* the key is *always* a string */
-      if(getString(&data) == MS_FAILURE) return(MS_FAILURE);      
-      msInsertHashTable(ptable, key, data);      
+      case(EOF):
+        msSetError(MS_EOFERR, NULL, "loadHashTable()");
+        return(MS_FAILURE);
+      case(END):
+        return(MS_SUCCESS);
+      case(MS_STRING):
+        key = msStrdup(msyystring_buffer); /* the key is *always* a string */
+        if(getString(&data) == MS_FAILURE) return(MS_FAILURE);
+        msInsertHashTable(ptable, key, data);
 
-      free(key);
-      free(data); data=NULL;
-      break;
-    default:
+        free(key);
+        free(data);
+        data=NULL;
+        break;
+      default:
         msSetError(MS_IDENTERR, "Parsing error near (%s):(line %d)", "loadHashTable()", msyystring_buffer, msyylineno );
-      return(MS_FAILURE);
+        return(MS_FAILURE);
     }
   }
 
   return(MS_SUCCESS);
 }
 
-static void writeHashTable(FILE *stream, int indent, const char *title, hashTableObj *table) {
+static void writeHashTable(FILE *stream, int indent, const char *title, hashTableObj *table)
+{
   struct hashObj *tp;
   int i;
 
@@ -2244,7 +2420,7 @@ static void writeHashTable(FILE *stream, int indent, const char *title, hashTabl
 
   indent++;
   writeBlockBegin(stream, indent, title);
-  for (i=0;i<MS_HASHSIZE; i++) {
+  for (i=0; i<MS_HASHSIZE; i++) {
     if (table->items[i] != NULL) {
       for (tp=table->items[i]; tp!=NULL; tp=tp->next)
         writeNameValuePair(stream, indent, tp->key, tp->data);
@@ -2253,71 +2429,75 @@ static void writeHashTable(FILE *stream, int indent, const char *title, hashTabl
   writeBlockEnd(stream, indent, title);
 }
 
-static void writeHashTableInline(FILE *stream, int indent, char *name, hashTableObj* table) {
-    struct hashObj *tp = NULL;
-    int i;
+static void writeHashTableInline(FILE *stream, int indent, char *name, hashTableObj* table)
+{
+  struct hashObj *tp = NULL;
+  int i;
 
-    if(!table) return;
-    if(msHashIsEmpty(table)) return;
+  if(!table) return;
+  if(msHashIsEmpty(table)) return;
 
-    ++indent;
-    for (i=0;i<MS_HASHSIZE;++i) {
-        if (table->items[i] != NULL) {
-            for (tp=table->items[i]; tp!=NULL; tp=tp->next) {
-                writeIndent(stream, indent);
-                fprintf(stream, "%s \"%s\" \"%s\"\n", name, tp->key, tp->data);
-            }
-        }
+  ++indent;
+  for (i=0; i<MS_HASHSIZE; ++i) {
+    if (table->items[i] != NULL) {
+      for (tp=table->items[i]; tp!=NULL; tp=tp->next) {
+        writeIndent(stream, indent);
+        fprintf(stream, "%s \"%s\" \"%s\"\n", name, tp->key, tp->data);
+      }
     }
+  }
 }
 
 /*
 ** Initialize, load and free a cluster object
 */
-void initCluster(clusterObj *cluster) {
-    cluster->maxdistance = 10;
-    cluster->buffer = 0;
-    cluster->region = NULL;
-    initExpression(&(cluster->group));
-    initExpression(&(cluster->filter));
+void initCluster(clusterObj *cluster)
+{
+  cluster->maxdistance = 10;
+  cluster->buffer = 0;
+  cluster->region = NULL;
+  initExpression(&(cluster->group));
+  initExpression(&(cluster->filter));
 }
 
-void freeCluster(clusterObj *cluster) {
-    msFree(cluster->region);
-    freeExpression(&(cluster->group));
-    freeExpression(&(cluster->filter));
+void freeCluster(clusterObj *cluster)
+{
+  msFree(cluster->region);
+  freeExpression(&(cluster->group));
+  freeExpression(&(cluster->filter));
 }
 
-int loadCluster(clusterObj *cluster) {
-  for(;;) {
-    switch(msyylex()) {
-    case(CLUSTER):
-      break; /* for string loads */
-    case(MAXDISTANCE):
-      if(getDouble(&(cluster->maxdistance)) == -1) return(-1);
-      break;
-    case(BUFFER):
-      if(getDouble(&(cluster->buffer)) == -1) return(-1);
-      break;
-    case(REGION):
-      if(getString(&cluster->region) == MS_FAILURE) return(-1);
-      break;
-    case(END):
-      return(0);
-      break;
-    case(GROUP):
-      if(loadExpression(&(cluster->group)) == -1) return(-1);
-      break;
-    case(FILTER):
-      if(loadExpression(&(cluster->filter)) == -1) return(-1);
-      break;
-    default:
-      if(strlen(msyystring_buffer) > 0) {
-        msSetError(MS_IDENTERR, "Parsing error near (%s):(line %d)", "loadCluster()", msyystring_buffer, msyylineno);
-        return(-1);
-      } else {
-        return(0); /* end of a string, not an error */
-      }
+int loadCluster(clusterObj *cluster)
+{
+  for(;;) {
+    switch(msyylex()) {
+      case(CLUSTER):
+        break; /* for string loads */
+      case(MAXDISTANCE):
+        if(getDouble(&(cluster->maxdistance)) == -1) return(-1);
+        break;
+      case(BUFFER):
+        if(getDouble(&(cluster->buffer)) == -1) return(-1);
+        break;
+      case(REGION):
+        if(getString(&cluster->region) == MS_FAILURE) return(-1);
+        break;
+      case(END):
+        return(0);
+        break;
+      case(GROUP):
+        if(loadExpression(&(cluster->group)) == -1) return(-1);
+        break;
+      case(FILTER):
+        if(loadExpression(&(cluster->filter)) == -1) return(-1);
+        break;
+      default:
+        if(strlen(msyystring_buffer) > 0) {
+          msSetError(MS_IDENTERR, "Parsing error near (%s):(line %d)", "loadCluster()", msyystring_buffer, msyylineno);
+          return(-1);
+        } else {
+          return(0); /* end of a string, not an error */
+        }
 
     }
   }
@@ -2346,7 +2526,8 @@ int msUpdateClusterFromString(clusterObj *cluster, char *string)
   return MS_SUCCESS;
 }
 
-static void writeCluster(FILE *stream, int indent, clusterObj *cluster) {
+static void writeCluster(FILE *stream, int indent, clusterObj *cluster)
+{
 
   if (cluster->maxdistance == 10 &&
       cluster->buffer == 0.0 &&
@@ -2368,7 +2549,8 @@ static void writeCluster(FILE *stream, int indent, clusterObj *cluster) {
 /*
 ** Initialize, load and free a single style
 */
-int initStyle(styleObj *style) {
+int initStyle(styleObj *style)
+{
   int i;
   MS_REFCNT_INIT(style);
   MS_INIT_COLOR(style->color, -1,-1,-1,255); /* must explictly set colors */
@@ -2392,6 +2574,7 @@ int initStyle(styleObj *style) {
   style->maxwidth = MS_MAXSYMBOLWIDTH;
   style->minscaledenom=style->maxscaledenom = -1.0;
   style->offsetx = style->offsety = 0; /* no offset */
+  style->polaroffsetpixel = style->polaroffsetangle = 0; /* no polar offset */
   style->antialias = MS_FALSE;
   style->angle = 0;
   style->autoangle= MS_FALSE;
@@ -2402,6 +2585,7 @@ int initStyle(styleObj *style) {
 
   style->patternlength = 0; /* solid line */
   style->gap = 0;
+  style->initialgap = -1;
   style->position = MS_CC;
   style->linecap = MS_CJC_DEFAULT_CAPS;
   style->linejoin = MS_CJC_DEFAULT_JOINS;
@@ -2416,63 +2600,63 @@ int initStyle(styleObj *style) {
   return MS_SUCCESS;
 }
 
-int loadStyle(styleObj *style) {
+int loadStyle(styleObj *style)
+{
   int symbol;
 
   for(;;) {
     switch(msyylex()) {
-  /* New Color Range fields*/
-    case (COLORRANGE):
-      /*These are both in one line now*/
-      if(loadColor(&(style->mincolor), NULL) != MS_SUCCESS) return(MS_FAILURE);
-      if(loadColor(&(style->maxcolor), NULL) != MS_SUCCESS) return(MS_FAILURE);
-      break;
-    case(DATARANGE):
-      /*These are both in one line now*/
-      if(getDouble(&(style->minvalue)) == -1) return(-1);
-      if(getDouble(&(style->maxvalue)) == -1) return(-1);
-      break;
-    case(RANGEITEM):
-      if(getString(&style->rangeitem) == MS_FAILURE) return(-1);
-      break;
-  /* End Range fields*/
-    case(ANGLE):
-      if((symbol = getSymbol(3, MS_NUMBER,MS_BINDING,MS_AUTO)) == -1) return(MS_FAILURE);
-
-      if(symbol == MS_NUMBER)
-        style->angle = (double) msyynumber;
-      else if(symbol==MS_BINDING){
-        if (style->bindings[MS_STYLE_BINDING_ANGLE].item != NULL)
-          msFree(style->bindings[MS_STYLE_BINDING_ANGLE].item);
-        style->bindings[MS_STYLE_BINDING_ANGLE].item = msStrdup(msyystring_buffer);
-        style->numbindings++;
-      } else {
-        style->autoangle=MS_TRUE;
-      }
-      break;
-    case(ANTIALIAS):
-      if((style->antialias = getSymbol(2, MS_TRUE,MS_FALSE)) == -1)
-	return(MS_FAILURE);
-      break;
-    case(BACKGROUNDCOLOR):
-      if(loadColor(&(style->backgroundcolor), NULL) != MS_SUCCESS) return(MS_FAILURE);
-      break;
-    case(COLOR):
-      if(loadColor(&(style->color), &(style->bindings[MS_STYLE_BINDING_COLOR])) != MS_SUCCESS) return(MS_FAILURE);
-      if(style->bindings[MS_STYLE_BINDING_COLOR].item) style->numbindings++;
-      break;
-    case(EOF):
-      msSetError(MS_EOFERR, NULL, "loadStyle()");
-      return(MS_FAILURE); /* missing END (probably) */
-    case(END): 
-      {
+        /* New Color Range fields*/
+      case (COLORRANGE):
+        /*These are both in one line now*/
+        if(loadColor(&(style->mincolor), NULL) != MS_SUCCESS) return(MS_FAILURE);
+        if(loadColor(&(style->maxcolor), NULL) != MS_SUCCESS) return(MS_FAILURE);
+        break;
+      case(DATARANGE):
+        /*These are both in one line now*/
+        if(getDouble(&(style->minvalue)) == -1) return(-1);
+        if(getDouble(&(style->maxvalue)) == -1) return(-1);
+        break;
+      case(RANGEITEM):
+        if(getString(&style->rangeitem) == MS_FAILURE) return(-1);
+        break;
+        /* End Range fields*/
+      case(ANGLE):
+        if((symbol = getSymbol(3, MS_NUMBER,MS_BINDING,MS_AUTO)) == -1) return(MS_FAILURE);
+
+        if(symbol == MS_NUMBER)
+          style->angle = (double) msyynumber;
+        else if(symbol==MS_BINDING) {
+          if (style->bindings[MS_STYLE_BINDING_ANGLE].item != NULL)
+            msFree(style->bindings[MS_STYLE_BINDING_ANGLE].item);
+          style->bindings[MS_STYLE_BINDING_ANGLE].item = msStrdup(msyystring_buffer);
+          style->numbindings++;
+        } else {
+          style->autoangle=MS_TRUE;
+        }
+        break;
+      case(ANTIALIAS):
+        if((style->antialias = getSymbol(2, MS_TRUE,MS_FALSE)) == -1)
+          return(MS_FAILURE);
+        break;
+      case(BACKGROUNDCOLOR):
+        if(loadColor(&(style->backgroundcolor), NULL) != MS_SUCCESS) return(MS_FAILURE);
+        break;
+      case(COLOR):
+        if(loadColor(&(style->color), &(style->bindings[MS_STYLE_BINDING_COLOR])) != MS_SUCCESS) return(MS_FAILURE);
+        if(style->bindings[MS_STYLE_BINDING_COLOR].item) style->numbindings++;
+        break;
+      case(EOF):
+        msSetError(MS_EOFERR, NULL, "loadStyle()");
+        return(MS_FAILURE); /* missing END (probably) */
+      case(END): {
         int alpha;
 
         /* apply opacity as the alpha channel color(s) */
         if(style->opacity < 100) {
           alpha = MS_NINT(style->opacity*2.55);
 
-          style->color.alpha = alpha; 
+          style->color.alpha = alpha;
           style->outlinecolor.alpha = alpha;
           style->backgroundcolor.alpha = alpha;
 
@@ -2483,172 +2667,212 @@ int loadStyle(styleObj *style) {
         return(MS_SUCCESS);
       }
       break;
-    case(GAP):
-      if((getDouble(&style->gap)) == -1) return(MS_FAILURE);
-      break;
-    case(MAXSCALEDENOM):
-      if(getDouble(&(style->maxscaledenom)) == -1) return(MS_FAILURE);
-      break;
-    case(MINSCALEDENOM):
-      if(getDouble(&(style->minscaledenom)) == -1) return(MS_FAILURE);
-      break;
-    case(GEOMTRANSFORM):
-      {
+      case(GAP):
+        if((getDouble(&style->gap)) == -1) return(MS_FAILURE);
+        break;
+      case(INITIALGAP):
+        if((getDouble(&style->initialgap)) == -1) return(MS_FAILURE);
+        if(style->initialgap < 0) {
+          msSetError(MS_MISCERR, "INITIALGAP requires a positive values", "loadStyle()");
+          return(MS_FAILURE);
+        }
+        break;
+      case(MAXSCALEDENOM):
+        if(getDouble(&(style->maxscaledenom)) == -1) return(MS_FAILURE);
+        break;
+      case(MINSCALEDENOM):
+        if(getDouble(&(style->minscaledenom)) == -1) return(MS_FAILURE);
+        break;
+      case(GEOMTRANSFORM): {
         int s;
-	if((s = getSymbol(2, MS_STRING, MS_EXPRESSION)) == -1) return(MS_FAILURE);
+        if((s = getSymbol(2, MS_STRING, MS_EXPRESSION)) == -1) return(MS_FAILURE);
         if(s == MS_STRING)
           msStyleSetGeomTransform(style, msyystring_buffer);
         else {
           /* handle expression case here for the moment */
           msFree(style->_geomtransform.string);
-	  style->_geomtransform.string = msStrdup(msyystring_buffer);
+          style->_geomtransform.string = msStrdup(msyystring_buffer);
           style->_geomtransform.type = MS_GEOMTRANSFORM_EXPRESSION;
         }
       }
       break;
-    case(LINECAP):
-      if((style->linecap = getSymbol(4,MS_CJC_BUTT, MS_CJC_ROUND, MS_CJC_SQUARE, MS_CJC_TRIANGLE)) == -1) return(MS_FAILURE);
-      break;
-    case(LINEJOIN):
-      if((style->linejoin = getSymbol(4,MS_CJC_NONE, MS_CJC_ROUND, MS_CJC_MITER, MS_CJC_BEVEL)) == -1) return(MS_FAILURE);
-      break;
-    case(LINEJOINMAXSIZE):
-      if((getDouble(&style->linejoinmaxsize)) == -1) return(MS_FAILURE);
-      break;
-    case(MAXSIZE):
-      if(getDouble(&(style->maxsize)) == -1) return(MS_FAILURE);      
-      break;
-    case(MINSIZE):
-      if(getDouble(&(style->minsize)) == -1) return(MS_FAILURE);
-      break;
-    case(MAXWIDTH):
-      if(getDouble(&(style->maxwidth)) == -1) return(MS_FAILURE);
-      break;
-    case(MINWIDTH):
-      if(getDouble(&(style->minwidth)) == -1) return(MS_FAILURE);
-      break;
-    case(OFFSET):
-      if(getDouble(&(style->offsetx)) == -1) return(MS_FAILURE);
-      if(getDouble(&(style->offsety)) == -1) return(MS_FAILURE);
-      break;
-    case(OPACITY):
-      if((symbol = getSymbol(2, MS_NUMBER,MS_BINDING)) == -1) return(MS_FAILURE);
-      if(symbol == MS_NUMBER)
-        style->opacity = MS_MAX(MS_MIN((int) msyynumber, 100), 0); /* force opacity to between 0 and 100 */
-      else {
-        if (style->bindings[MS_STYLE_BINDING_OPACITY].item != NULL)
-          msFree(style->bindings[MS_STYLE_BINDING_OPACITY].item);
-        style->bindings[MS_STYLE_BINDING_OPACITY].item = msStrdup(msyystring_buffer);
-        style->numbindings++;
-      }
-      break;
-    case(OUTLINECOLOR):
-      if(loadColor(&(style->outlinecolor), &(style->bindings[MS_STYLE_BINDING_OUTLINECOLOR])) != MS_SUCCESS) return(MS_FAILURE);
-      if(style->bindings[MS_STYLE_BINDING_OUTLINECOLOR].item) style->numbindings++;
-      break;
-    case(PATTERN): {
-      int done = MS_FALSE;
-      for(;;) { /* read till the next END */
-        switch(msyylex()) {  
-        case(END):
-          if(style->patternlength < 2) {
-            msSetError(MS_SYMERR, "Not enough pattern elements. A minimum of 2 are required", "loadStyle()");
-            return(-1);
-          }   
-          done = MS_TRUE;
-          break;
-        case(MS_NUMBER): /* read the pattern values */
-          if(style->patternlength == MS_MAXPATTERNLENGTH) {
-            msSetError(MS_SYMERR, "Pattern too long.", "loadStyle()");
-            return(-1);
+      case(LINECAP):
+        if((style->linecap = getSymbol(4,MS_CJC_BUTT, MS_CJC_ROUND, MS_CJC_SQUARE, MS_CJC_TRIANGLE)) == -1) return(MS_FAILURE);
+        break;
+      case(LINEJOIN):
+        if((style->linejoin = getSymbol(4,MS_CJC_NONE, MS_CJC_ROUND, MS_CJC_MITER, MS_CJC_BEVEL)) == -1) return(MS_FAILURE);
+        break;
+      case(LINEJOINMAXSIZE):
+        if((getDouble(&style->linejoinmaxsize)) == -1) return(MS_FAILURE);
+        break;
+      case(MAXSIZE):
+        if(getDouble(&(style->maxsize)) == -1) return(MS_FAILURE);
+        break;
+      case(MINSIZE):
+        if(getDouble(&(style->minsize)) == -1) return(MS_FAILURE);
+        break;
+      case(MAXWIDTH):
+        if(getDouble(&(style->maxwidth)) == -1) return(MS_FAILURE);
+        break;
+      case(MINWIDTH):
+        if(getDouble(&(style->minwidth)) == -1) return(MS_FAILURE);
+        break;
+      case(OFFSET):
+        if((symbol = getSymbol(2, MS_NUMBER,MS_BINDING)) == -1) return(MS_FAILURE);
+        if(symbol == MS_NUMBER)
+          style->offsetx = (double) msyynumber;
+        else {
+          if (style->bindings[MS_STYLE_BINDING_OFFSET_X].item != NULL)
+            msFree(style->bindings[MS_STYLE_BINDING_OFFSET_X].item);
+          style->bindings[MS_STYLE_BINDING_OFFSET_X].item = msStrdup(msyystring_buffer);
+          style->numbindings++;
+        }
+
+        if((symbol = getSymbol(2, MS_NUMBER,MS_BINDING)) == -1) return(MS_FAILURE);
+        if(symbol == MS_NUMBER)
+          style->offsety = (double) msyynumber;
+        else {
+          if (style->bindings[MS_STYLE_BINDING_OFFSET_Y].item != NULL)
+            msFree(style->bindings[MS_STYLE_BINDING_OFFSET_Y].item);
+          style->bindings[MS_STYLE_BINDING_OFFSET_Y].item = msStrdup(msyystring_buffer);
+          style->numbindings++;
+        }
+        break;
+      case(OPACITY):
+        if((symbol = getSymbol(2, MS_NUMBER,MS_BINDING)) == -1) return(MS_FAILURE);
+        if(symbol == MS_NUMBER)
+          style->opacity = MS_MAX(MS_MIN((int) msyynumber, 100), 0); /* force opacity to between 0 and 100 */
+        else {
+          if (style->bindings[MS_STYLE_BINDING_OPACITY].item != NULL)
+            msFree(style->bindings[MS_STYLE_BINDING_OPACITY].item);
+          style->bindings[MS_STYLE_BINDING_OPACITY].item = msStrdup(msyystring_buffer);
+          style->numbindings++;
+        }
+        break;
+      case(OUTLINECOLOR):
+        if(loadColor(&(style->outlinecolor), &(style->bindings[MS_STYLE_BINDING_OUTLINECOLOR])) != MS_SUCCESS) return(MS_FAILURE);
+        if(style->bindings[MS_STYLE_BINDING_OUTLINECOLOR].item) style->numbindings++;
+        break;
+      case(PATTERN): {
+        int done = MS_FALSE;
+        for(;;) { /* read till the next END */
+          switch(msyylex()) {
+            case(END):
+              if(style->patternlength < 2) {
+                msSetError(MS_SYMERR, "Not enough pattern elements. A minimum of 2 are required", "loadStyle()");
+                return(MS_FAILURE);
+              }
+              done = MS_TRUE;
+              break;
+            case(MS_NUMBER): /* read the pattern values */
+              if(style->patternlength == MS_MAXPATTERNLENGTH) {
+                msSetError(MS_SYMERR, "Pattern too long.", "loadStyle()");
+                return(-1);
+              }
+              style->pattern[style->patternlength] = atof(msyystring_buffer);
+              style->patternlength++;
+              break;
+            default:
+              msSetError(MS_TYPEERR, "Parsing error near (%s):(line %d)", "loadStyle()", msyystring_buffer, msyylineno);
+              return(-1);
           }
-          style->pattern[style->patternlength] = atof(msyystring_buffer);
-          style->patternlength++;
-          break;
-        default:
-          msSetError(MS_TYPEERR, "Parsing error near (%s):(line %d)", "loadStyle()", msyystring_buffer, msyylineno);
+          if(done == MS_TRUE)
+            break;
+        }
+        break;
+      }
+      case(POSITION):
+        /* if((s->position = getSymbol(3, MS_UC,MS_CC,MS_LC)) == -1)  */
+        /* return(-1); */
+        if((style->position = getSymbol(9, MS_UL,MS_UC,MS_UR,MS_CL,MS_CC,MS_CR,MS_LL,MS_LC,MS_LR)) == -1)
           return(-1);
+        break;
+      case(OUTLINEWIDTH):
+        if((symbol = getSymbol(2, MS_NUMBER,MS_BINDING)) == -1) return(MS_FAILURE);
+        if(symbol == MS_NUMBER) {
+          style->outlinewidth = (double) msyynumber;
+          if(style->outlinewidth < 0) {
+            msSetError(MS_MISCERR, "Invalid OUTLINEWIDTH, must be greater than 0" , "loadStyle()");
+            return(MS_FAILURE);
+          }
+        } else {
+          if (style->bindings[MS_STYLE_BINDING_OUTLINEWIDTH].item != NULL)
+            msFree(style->bindings[MS_STYLE_BINDING_OUTLINEWIDTH].item);
+          style->bindings[MS_STYLE_BINDING_OUTLINEWIDTH].item = msStrdup(msyystring_buffer);
+          style->numbindings++;
         }
-        if(done == MS_TRUE)
-          break;
-      }      
-      break;
-    }
-    case(POSITION):
-      /* if((s->position = getSymbol(3, MS_UC,MS_CC,MS_LC)) == -1)  */
-      /* return(-1); */
-      if((style->position = getSymbol(9, MS_UL,MS_UC,MS_UR,MS_CL,MS_CC,MS_CR,MS_LL,MS_LC,MS_LR)) == -1) 
-        return(-1);
-      break;
-    case(OUTLINEWIDTH):
-      if((symbol = getSymbol(2, MS_NUMBER,MS_BINDING)) == -1) return(MS_FAILURE);
-      if(symbol == MS_NUMBER) {
-        style->outlinewidth = (double) msyynumber;
-        if(style->outlinewidth < 0) {
-          msSetError(MS_MISCERR, "Invalid OUTLINEWIDTH, must be greater than 0" , "loadStyle()");
-          return(MS_FAILURE);
+        break;
+      case(SIZE):
+        if((symbol = getSymbol(2, MS_NUMBER,MS_BINDING)) == -1) return(MS_FAILURE);
+        if(symbol == MS_NUMBER)
+          style->size = (double) msyynumber;
+        else {
+          if (style->bindings[MS_STYLE_BINDING_SIZE].item != NULL)
+            msFree(style->bindings[MS_STYLE_BINDING_SIZE].item);
+          style->bindings[MS_STYLE_BINDING_SIZE].item = msStrdup(msyystring_buffer);
+          style->numbindings++;
         }
-      }
-      else {
-        if (style->bindings[MS_STYLE_BINDING_OUTLINEWIDTH].item != NULL)
-          msFree(style->bindings[MS_STYLE_BINDING_OUTLINEWIDTH].item);
-        style->bindings[MS_STYLE_BINDING_OUTLINEWIDTH].item = msStrdup(msyystring_buffer);
-        style->numbindings++;
-      }
-      break;
-    case(SIZE):
-      if((symbol = getSymbol(2, MS_NUMBER,MS_BINDING)) == -1) return(MS_FAILURE);
-      if(symbol == MS_NUMBER)
-        style->size = (double) msyynumber;
-      else {
-        if (style->bindings[MS_STYLE_BINDING_SIZE].item != NULL)
-          msFree(style->bindings[MS_STYLE_BINDING_SIZE].item);
- 	style->bindings[MS_STYLE_BINDING_SIZE].item = msStrdup(msyystring_buffer);
-        style->numbindings++;
-      }
-      break;
-    case(STYLE):
-      break; /* for string loads */
-    case(SYMBOL):
-      if((symbol = getSymbol(3, MS_NUMBER,MS_STRING,MS_BINDING)) == -1) return(MS_FAILURE);
-      if(symbol == MS_NUMBER) {
-        if (style->symbolname != NULL) {
-          msFree(style->symbolname);
-          style->symbolname = NULL;
+        break;
+      case(STYLE):
+        break; /* for string loads */
+      case(SYMBOL):
+        if((symbol = getSymbol(3, MS_NUMBER,MS_STRING,MS_BINDING)) == -1) return(MS_FAILURE);
+        if(symbol == MS_NUMBER) {
+          if (style->symbolname != NULL) {
+            msFree(style->symbolname);
+            style->symbolname = NULL;
+          }
+          style->symbol = (int) msyynumber;
+        } else if(symbol == MS_STRING) {
+          if (style->symbolname != NULL)
+            msFree(style->symbolname);
+          style->symbolname = msStrdup(msyystring_buffer);
+        } else {
+          if (style->bindings[MS_STYLE_BINDING_SYMBOL].item != NULL)
+            msFree(style->bindings[MS_STYLE_BINDING_SYMBOL].item);
+          style->bindings[MS_STYLE_BINDING_SYMBOL].item = msStrdup(msyystring_buffer);
+          style->numbindings++;
+        }
+        break;
+      case(WIDTH):
+        if((symbol = getSymbol(2, MS_NUMBER,MS_BINDING)) == -1) return(MS_FAILURE);
+        if(symbol == MS_NUMBER)
+          style->width = (double) msyynumber;
+        else {
+          if (style->bindings[MS_STYLE_BINDING_WIDTH].item != NULL)
+            msFree(style->bindings[MS_STYLE_BINDING_WIDTH].item);
+          style->bindings[MS_STYLE_BINDING_WIDTH].item = msStrdup(msyystring_buffer);
+          style->numbindings++;
+        }
+        break;
+      case(POLAROFFSET):
+        if((symbol = getSymbol(2, MS_NUMBER,MS_BINDING)) == -1) return(MS_FAILURE);
+        if(symbol == MS_NUMBER)
+          style->polaroffsetpixel = (double) msyynumber;
+        else {
+          if (style->bindings[MS_STYLE_BINDING_POLAROFFSET_PIXEL].item != NULL)
+            msFree(style->bindings[MS_STYLE_BINDING_POLAROFFSET_PIXEL].item);
+          style->bindings[MS_STYLE_BINDING_POLAROFFSET_PIXEL].item = msStrdup(msyystring_buffer);
+          style->numbindings++;
+        }
+
+        if((symbol = getSymbol(2, MS_NUMBER,MS_BINDING)) == -1) return(MS_FAILURE);
+        if(symbol == MS_NUMBER)
+          style->polaroffsetangle = (double) msyynumber;
+        else {
+          if (style->bindings[MS_STYLE_BINDING_POLAROFFSET_ANGLE].item != NULL)
+            msFree(style->bindings[MS_STYLE_BINDING_POLAROFFSET_ANGLE].item);
+          style->bindings[MS_STYLE_BINDING_POLAROFFSET_ANGLE].item = msStrdup(msyystring_buffer);
+          style->numbindings++;
+        }
+        break;
+      default:
+        if(strlen(msyystring_buffer) > 0) {
+          msSetError(MS_IDENTERR, "Parsing error near (%s):(line %d)", "loadStyle()", msyystring_buffer, msyylineno);
+          return(MS_FAILURE);
+        } else {
+          return(MS_SUCCESS); /* end of a string, not an error */
         }
-	style->symbol = (int) msyynumber;
-      }
-      else if(symbol == MS_STRING)
-      {
-        if (style->symbolname != NULL)
-          msFree(style->symbolname);
-        style->symbolname = msStrdup(msyystring_buffer);
-      }
-      else {
-        if (style->bindings[MS_STYLE_BINDING_SYMBOL].item != NULL)
-          msFree(style->bindings[MS_STYLE_BINDING_SYMBOL].item);
-        style->bindings[MS_STYLE_BINDING_SYMBOL].item = msStrdup(msyystring_buffer);
-        style->numbindings++;
-      }
-      break;
-    case(WIDTH):
-      if((symbol = getSymbol(2, MS_NUMBER,MS_BINDING)) == -1) return(MS_FAILURE);
-      if(symbol == MS_NUMBER)
-        style->width = (double) msyynumber;
-      else {
-        if (style->bindings[MS_STYLE_BINDING_WIDTH].item != NULL)
-          msFree(style->bindings[MS_STYLE_BINDING_WIDTH].item);
-        style->bindings[MS_STYLE_BINDING_WIDTH].item = msStrdup(msyystring_buffer);
-        style->numbindings++;
-      }
-      break;
-    default:
-      if(strlen(msyystring_buffer) > 0) {
-        msSetError(MS_IDENTERR, "Parsing error near (%s):(line %d)", "loadStyle()", msyystring_buffer, msyylineno);
-        return(MS_FAILURE);
-      } else {
-        return(MS_SUCCESS); /* end of a string, not an error */
-      }
     }
   }
 }
@@ -2678,10 +2902,13 @@ int msUpdateStyleFromString(styleObj *style, char *string, int url_string)
   return MS_SUCCESS;
 }
 
-int freeStyle(styleObj *style) {
+int freeStyle(styleObj *style)
+{
   int i;
 
-  if( MS_REFCNT_DECR_IS_NOT_ZERO(style) ) { return MS_FAILURE; }
+  if( MS_REFCNT_DECR_IS_NOT_ZERO(style) ) {
+    return MS_FAILURE;
+  }
 
   msFree(style->symbolname);
   freeExpression(&style->_geomtransform);
@@ -2693,14 +2920,15 @@ int freeStyle(styleObj *style) {
   return MS_SUCCESS;
 }
 
-void writeStyle(FILE *stream, int indent, styleObj *style) {
+void writeStyle(FILE *stream, int indent, styleObj *style)
+{
 
   indent++;
   writeBlockBegin(stream, indent, "STYLE");
 
   if(style->numbindings > 0 && style->bindings[MS_STYLE_BINDING_ANGLE].item)
     writeAttributeBinding(stream, indent, "ANGLE", &(style->bindings[MS_STYLE_BINDING_ANGLE]));
-  else writeNumberOrKeyword(stream, indent, "ANGLE", 360, style->angle, style->autoangle, 1, MS_TRUE, "AUTO");
+  else writeNumberOrKeyword(stream, indent, "ANGLE", 0, style->angle, style->autoangle, 1, MS_TRUE, "AUTO");
 
   writeKeyword(stream, indent, "ANTIALIAS", style->antialias, 1, MS_TRUE, "TRUE");
   writeColor(stream, indent, "BACKGROUNDCOLOR", NULL, &(style->backgroundcolor));
@@ -2708,34 +2936,40 @@ void writeStyle(FILE *stream, int indent, styleObj *style) {
   if(style->numbindings > 0 && style->bindings[MS_STYLE_BINDING_COLOR].item)
     writeAttributeBinding(stream, indent, "COLOR", &(style->bindings[MS_STYLE_BINDING_COLOR]));
   else writeColor(stream, indent, "COLOR", NULL, &(style->color));
-  
+
   writeNumber(stream, indent, "GAP", 0, style->gap);
+  writeNumber(stream, indent, "INITIALGAP", -1, style->initialgap);
 
-  if(style->_geomtransform.type != MS_GEOMTRANSFORM_NONE) {
-    writeKeyword(stream, indent, "GEOMTRANSFORM", style->_geomtransform.type, 6,
+  if(style->_geomtransform.type == MS_GEOMTRANSFORM_EXPRESSION) {
+    writeIndent(stream, indent + 1);
+    fprintf(stream, "GEOMTRANSFORM (%s)\n", style->_geomtransform.string);
+  }
+  else if(style->_geomtransform.type != MS_GEOMTRANSFORM_NONE) {
+    writeKeyword(stream, indent, "GEOMTRANSFORM", style->_geomtransform.type, 7,
                  MS_GEOMTRANSFORM_BBOX, "\"bbox\"",
                  MS_GEOMTRANSFORM_END, "\"end\"",
                  MS_GEOMTRANSFORM_LABELPOINT, "\"labelpnt\"",
                  MS_GEOMTRANSFORM_LABELPOLY, "\"labelpoly\"",
                  MS_GEOMTRANSFORM_START, "\"start\"",
-                 MS_GEOMTRANSFORM_VERTICES, "\"vertices\""
-    );
+                 MS_GEOMTRANSFORM_VERTICES, "\"vertices\"",
+                 MS_GEOMTRANSFORM_CENTROID, "\"centroid\""
+                );
   }
 
   if(style->linecap != MS_CJC_DEFAULT_CAPS) {
-     writeKeyword(stream,indent,"LINECAP",(int)style->linecap,5,
-           MS_CJC_NONE,"NONE",
-           MS_CJC_ROUND, "ROUND",
-           MS_CJC_SQUARE, "SQUARE",
-           MS_CJC_BUTT, "BUTT",
-           MS_CJC_TRIANGLE, "TRIANGLE");
+    writeKeyword(stream,indent,"LINECAP",(int)style->linecap,5,
+                 MS_CJC_NONE,"NONE",
+                 MS_CJC_ROUND, "ROUND",
+                 MS_CJC_SQUARE, "SQUARE",
+                 MS_CJC_BUTT, "BUTT",
+                 MS_CJC_TRIANGLE, "TRIANGLE");
   }
   if(style->linejoin != MS_CJC_DEFAULT_JOINS) {
-     writeKeyword(stream,indent,"LINEJOIN",(int)style->linejoin,5,
-           MS_CJC_NONE,"NONE",
-           MS_CJC_ROUND, "ROUND",
-           MS_CJC_BEVEL, "BEVEL",
-           MS_CJC_MITER, "MITER");
+    writeKeyword(stream,indent,"LINEJOIN",(int)style->linejoin,5,
+                 MS_CJC_NONE,"NONE",
+                 MS_CJC_ROUND, "ROUND",
+                 MS_CJC_BEVEL, "BEVEL",
+                 MS_CJC_MITER, "MITER");
   }
   writeNumber(stream, indent, "LINEJOINMAXSIZE", MS_CJC_DEFAULT_JOIN_MAXSIZE , style->linejoinmaxsize);
 
@@ -2746,7 +2980,11 @@ void writeStyle(FILE *stream, int indent, styleObj *style) {
   writeNumber(stream, indent, "MINSCALEDENOM", -1, style->minscaledenom);
   writeNumber(stream, indent, "MINSIZE", MS_MINSYMBOLSIZE, style->minsize);
   writeNumber(stream, indent, "MINWIDTH", MS_MINSYMBOLWIDTH, style->minwidth);
-  writeDimension(stream, indent, "OFFSET", style->offsetx, style->offsety, NULL, NULL);
+  if((style->numbindings > 0 && (style->bindings[MS_STYLE_BINDING_OFFSET_X].item||style->bindings[MS_STYLE_BINDING_OFFSET_Y].item))||style->offsetx!=0||style->offsety!=0)
+    writeDimension(stream, indent, "OFFSET", style->offsetx, style->offsety, style->bindings[MS_STYLE_BINDING_OFFSET_X].item, style->bindings[MS_STYLE_BINDING_OFFSET_Y].item);
+  if((style->numbindings > 0 && (style->bindings[MS_STYLE_BINDING_POLAROFFSET_PIXEL].item||style->bindings[MS_STYLE_BINDING_POLAROFFSET_ANGLE].item))||style->polaroffsetangle!=0||style->polaroffsetpixel!=0)
+    writeDimension(stream, indent, "POLAROFFSET", style->polaroffsetpixel, style->polaroffsetangle,
+                 style->bindings[MS_STYLE_BINDING_POLAROFFSET_PIXEL].item, style->bindings[MS_STYLE_BINDING_POLAROFFSET_ANGLE].item);
 
   if(style->numbindings > 0 && style->bindings[MS_STYLE_BINDING_OPACITY].item)
     writeAttributeBinding(stream, indent, "OPACITY", &(style->bindings[MS_STYLE_BINDING_OPACITY]));
@@ -2754,7 +2992,7 @@ void writeStyle(FILE *stream, int indent, styleObj *style) {
 
   if(style->numbindings > 0 && style->bindings[MS_STYLE_BINDING_OUTLINECOLOR].item)
     writeAttributeBinding(stream, indent, "OUTLINECOLOR", &(style->bindings[MS_STYLE_BINDING_OUTLINECOLOR]));
-  else  writeColor(stream, indent, "OUTLINECOLOR", NULL, &(style->outlinecolor)); 
+  else  writeColor(stream, indent, "OUTLINECOLOR", NULL, &(style->outlinecolor));
 
   if(style->numbindings > 0 && style->bindings[MS_STYLE_BINDING_OUTLINEWIDTH].item)
     writeAttributeBinding(stream, indent, "OUTLINEWIDTH", &(style->bindings[MS_STYLE_BINDING_OUTLINEWIDTH]));
@@ -2762,21 +3000,22 @@ void writeStyle(FILE *stream, int indent, styleObj *style) {
 
   /* PATTERN */
   if(style->patternlength != 0) {
-     int i;
-     indent++;
-     writeBlockBegin(stream,indent,"PATTERN");
-     for(i=0;i<style->patternlength;i++)
-       fprintf(stream, " %.2f", style->pattern[i]);
-     fprintf(stream,"\n");
-     writeBlockEnd(stream,indent,"PATTERN");
-     indent--;
+    int i;
+    indent++;
+    writeBlockBegin(stream,indent,"PATTERN");
+    writeIndent(stream, indent);
+    for(i=0; i<style->patternlength; i++)
+      fprintf(stream, " %.2f", style->pattern[i]);
+    fprintf(stream,"\n");
+    writeBlockEnd(stream,indent,"PATTERN");
+    indent--;
   }
 
   if(style->position != MS_CC) {
     writeKeyword(stream, indent, "POSITION", style->position, 9,
-          MS_UL, "UL", MS_UC, "UC", MS_UR, "UR", MS_CL, "CL",
-          MS_CC, "CC", MS_CR, "CR", MS_LL, "LL", MS_LC, "LC",
-          MS_LR, "LR");
+                 MS_UL, "UL", MS_UC, "UC", MS_UR, "UR", MS_CL, "CL",
+                 MS_CC, "CC", MS_CR, "CR", MS_LL, "LL", MS_LC, "LC",
+                 MS_LR, "LR");
   }
 
   if(style->numbindings > 0 && style->bindings[MS_STYLE_BINDING_SIZE].item)
@@ -2805,8 +3044,6 @@ void writeStyle(FILE *stream, int indent, styleObj *style) {
 */
 int initClass(classObj *class)
 {
-  /* printf("Init class at %p\n", class); */
-
   class->status = MS_ON;
   class->debug = MS_OFF;
   MS_REFCNT_INIT(class);
@@ -2815,30 +3052,32 @@ int initClass(classObj *class)
   class->name = NULL;
   class->title = NULL;
   initExpression(&(class->text));
-  
-  initLabel(&(class->label));
-  class->label.size = -1; /* no default */
 
   class->template = NULL;
 
   class->type = -1;
-  
+
   initHashTable(&(class->metadata));
   initHashTable(&(class->validation));
-  
+
   class->maxscaledenom = class->minscaledenom = -1.0;
   class->minfeaturesize = -1; /* no limit */
 
-  /* Set maxstyles = 0, styles[] will be allocated as needed on first call 
+  /* Set maxstyles = 0, styles[] will be allocated as needed on first call
    * to msGrowClassStyles()
    */
-  class->numstyles = class->maxstyles = 0;   
-  class->styles = NULL;  
+  class->numstyles = class->maxstyles = 0;
+  class->styles = NULL;
+
+  class->numlabels = class->maxlabels = 0;
+  class->labels = NULL;
 
   class->keyimage = NULL;
 
   class->group = NULL;
 
+  initLeader(&(class->leader));
+
   return(0);
 }
 
@@ -2846,21 +3085,21 @@ int freeClass(classObj *class)
 {
   int i;
 
-  if( MS_REFCNT_DECR_IS_NOT_ZERO(class) ) { return MS_FAILURE; }
-  /* printf("Freeing class at %p (%s)\n", class, class->name); */
+  if( MS_REFCNT_DECR_IS_NOT_ZERO(class) ) {
+    return MS_FAILURE;
+  }
 
-  freeLabel(&(class->label));
   freeExpression(&(class->expression));
   freeExpression(&(class->text));
   msFree(class->name);
   msFree(class->title);
   msFree(class->template);
   msFree(class->group);
-  
+
   if (&(class->metadata)) msFreeHashItems(&(class->metadata));
   if (&(class->validation)) msFreeHashItems(&(class->validation));
-  
-  for(i=0;i<class->numstyles;i++) { /* each style */
+
+  for(i=0; i<class->numstyles; i++) { /* each style */
     if(class->styles[i]!=NULL) {
       if(freeStyle(class->styles[i]) == MS_SUCCESS) {
         msFree(class->styles[i]);
@@ -2868,15 +3107,26 @@ int freeClass(classObj *class)
     }
   }
   msFree(class->styles);
+
+  for(i=0; i<class->numlabels; i++) { /* each label */
+    if(class->labels[i]!=NULL) {
+      if(freeLabel(class->labels[i]) == MS_SUCCESS) {
+        msFree(class->labels[i]);
+      }
+    }
+  }
+  msFree(class->labels);
+
   msFree(class->keyimage);
+  freeLabelLeader(&(class->leader));
 
   return MS_SUCCESS;
 }
 
 /*
-** Ensure there is at least one free entry in the sttyles array of this 
-** classObj. Grow the allocated styles array if necessary and allocate 
-** a new style for styles[numstyles] if there is not already one, 
+** Ensure there is at least one free entry in the sttyles array of this
+** classObj. Grow the allocated styles array if necessary and allocate
+** a new style for styles[numstyles] if there is not already one,
 ** setting its contents to all zero bytes (i.e. does not call initStyle()
 ** on it).
 **
@@ -2887,63 +3137,92 @@ int freeClass(classObj *class)
 */
 styleObj *msGrowClassStyles( classObj *class )
 {
-    /* Do we need to increase the size of styles[] by  MS_STYLE_ALLOCSIZE?
-     */
-    if (class->numstyles == class->maxstyles) {
-        styleObj **newStylePtr;
-        int i, newsize;
+  /* Do we need to increase the size of styles[] by  MS_STYLE_ALLOCSIZE?
+   */
+  if (class->numstyles == class->maxstyles) {
+    styleObj **newStylePtr;
+    int i, newsize;
 
-        newsize = class->maxstyles + MS_STYLE_ALLOCSIZE;
+    newsize = class->maxstyles + MS_STYLE_ALLOCSIZE;
 
-        /* Alloc/realloc styles */
-        newStylePtr = (styleObj**)realloc(class->styles,
-                                          newsize*sizeof(styleObj*));
-        MS_CHECK_ALLOC(newStylePtr, newsize*sizeof(styleObj*), NULL);
+    /* Alloc/realloc styles */
+    newStylePtr = (styleObj**)realloc(class->styles, newsize*sizeof(styleObj*));
+    MS_CHECK_ALLOC(newStylePtr, newsize*sizeof(styleObj*), NULL);
 
-        class->styles = newStylePtr;
-        class->maxstyles = newsize;
-        for(i=class->numstyles; i<class->maxstyles; i++) {
-            class->styles[i] = NULL;
-        }
+    class->styles = newStylePtr;
+    class->maxstyles = newsize;
+    for(i=class->numstyles; i<class->maxstyles; i++) {
+      class->styles[i] = NULL;
     }
+  }
 
-    if (class->styles[class->numstyles]==NULL) {
-        class->styles[class->numstyles]=(styleObj*)calloc(1,sizeof(styleObj));
-        MS_CHECK_ALLOC(class->styles[class->numstyles], sizeof(styleObj), NULL);
-    }
+  if (class->styles[class->numstyles]==NULL) {
+    class->styles[class->numstyles]=(styleObj*)calloc(1,sizeof(styleObj));
+    MS_CHECK_ALLOC(class->styles[class->numstyles], sizeof(styleObj), NULL);
+  }
 
-    return class->styles[class->numstyles];
+  return class->styles[class->numstyles];
 }
 
 /* exactly the same as for a classObj */
 styleObj *msGrowLabelStyles( labelObj *label )
 {
-    /* Do we need to increase the size of styles[] by  MS_STYLE_ALLOCSIZE?
-     */
-    if (label->numstyles == label->maxstyles) {
-        styleObj **newStylePtr;
-        int i, newsize;
+  /* Do we need to increase the size of styles[] by  MS_STYLE_ALLOCSIZE?
+   */
+  if (label->numstyles == label->maxstyles) {
+    styleObj **newStylePtr;
+    int i, newsize;
 
-        newsize = label->maxstyles + MS_STYLE_ALLOCSIZE;
+    newsize = label->maxstyles + MS_STYLE_ALLOCSIZE;
 
-        /* Alloc/realloc styles */
-        newStylePtr = (styleObj**)realloc(label->styles,
-                                          newsize*sizeof(styleObj*));
-        MS_CHECK_ALLOC(newStylePtr, newsize*sizeof(styleObj*), NULL);
+    /* Alloc/realloc styles */
+    newStylePtr = (styleObj**)realloc(label->styles, newsize*sizeof(styleObj*));
+    MS_CHECK_ALLOC(newStylePtr, newsize*sizeof(styleObj*), NULL);
 
-        label->styles = newStylePtr;
-        label->maxstyles = newsize;
-        for(i=label->numstyles; i<label->maxstyles; i++) {
-            label->styles[i] = NULL;
-        }
+    label->styles = newStylePtr;
+    label->maxstyles = newsize;
+    for(i=label->numstyles; i<label->maxstyles; i++) {
+      label->styles[i] = NULL;
     }
+  }
+
+  if (label->styles[label->numstyles]==NULL) {
+    label->styles[label->numstyles]=(styleObj*)calloc(1,sizeof(styleObj));
+    MS_CHECK_ALLOC(label->styles[label->numstyles], sizeof(styleObj), NULL);
+  }
+
+  return label->styles[label->numstyles];
+}
+
+/* exactly the same as for a labelLeaderObj, needs refactoring */
+styleObj *msGrowLeaderStyles( labelLeaderObj *leader )
+{
+  /* Do we need to increase the size of styles[] by  MS_STYLE_ALLOCSIZE?
+   */
+  if (leader->numstyles == leader->maxstyles) {
+    styleObj **newStylePtr;
+    int i, newsize;
 
-    if (label->styles[label->numstyles]==NULL) {
-        label->styles[label->numstyles]=(styleObj*)calloc(1,sizeof(styleObj));
-        MS_CHECK_ALLOC(label->styles[label->numstyles], sizeof(styleObj), NULL);
+    newsize = leader->maxstyles + MS_STYLE_ALLOCSIZE;
+
+    /* Alloc/realloc styles */
+    newStylePtr = (styleObj**)realloc(leader->styles,
+                                      newsize*sizeof(styleObj*));
+    MS_CHECK_ALLOC(newStylePtr, newsize*sizeof(styleObj*), NULL);
+
+    leader->styles = newStylePtr;
+    leader->maxstyles = newsize;
+    for(i=leader->numstyles; i<leader->maxstyles; i++) {
+      leader->styles[i] = NULL;
     }
+  }
+
+  if (leader->styles[leader->numstyles]==NULL) {
+    leader->styles[leader->numstyles]=(styleObj*)calloc(1,sizeof(styleObj));
+    MS_CHECK_ALLOC(leader->styles[leader->numstyles], sizeof(styleObj), NULL);
+  }
 
-    return label->styles[label->numstyles];
+  return leader->styles[leader->numstyles];
 }
 
 /* msMaybeAllocateClassStyle()
@@ -2952,29 +3231,30 @@ styleObj *msGrowLabelStyles( labelObj *label )
 **
 ** Returns MS_SUCCESS/MS_FAILURE.
 */
-int msMaybeAllocateClassStyle(classObj* c, int idx) {
-    if (c==NULL) return MS_FAILURE;
+int msMaybeAllocateClassStyle(classObj* c, int idx)
+{
+  if (c==NULL) return MS_FAILURE;
 
-    if ( idx < 0 ) {
-        msSetError(MS_MISCERR, "Invalid style index: %d", "msMaybeAllocateClassStyle()", idx);
-        return MS_FAILURE;
-    }
+  if ( idx < 0 ) {
+    msSetError(MS_MISCERR, "Invalid style index: %d", "msMaybeAllocateClassStyle()", idx);
+    return MS_FAILURE;
+  }
 
-    /* Alloc empty styles as needed up to idx.
-     * Nothing to do if requested style already exists
-     */
-    while(c->numstyles <= idx) {
-        if (msGrowClassStyles(c) == NULL)
-            return MS_FAILURE;
+  /* Alloc empty styles as needed up to idx.
+   * Nothing to do if requested style already exists
+   */
+  while(c->numstyles <= idx) {
+    if (msGrowClassStyles(c) == NULL)
+      return MS_FAILURE;
 
-        if ( initStyle(c->styles[c->numstyles]) == MS_FAILURE ) {
-            msSetError(MS_MISCERR, "Failed to init new styleObj", 
-                       "msMaybeAllocateClassStyle()");
-            return(MS_FAILURE);
-        }
-        c->numstyles++;
+    if ( initStyle(c->styles[c->numstyles]) == MS_FAILURE ) {
+      msSetError(MS_MISCERR, "Failed to init new styleObj",
+                 "msMaybeAllocateClassStyle()");
+      return(MS_FAILURE);
     }
-    return MS_SUCCESS;
+    c->numstyles++;
+  }
+  return MS_SUCCESS;
 }
 
 
@@ -2988,7 +3268,16 @@ void resetClassStyle(classObj *class)
 {
   int i;
 
-  freeLabel(&(class->label));
+  /* reset labels */
+  for(i=0; i<class->numlabels; i++) {
+    if(class->styles[i] != NULL) {
+      if(freeLabel(class->labels[i]) == MS_SUCCESS ) {
+        msFree(class->labels[i]);
+      }
+      class->labels[i] = NULL;
+    }
+  }
+  class->numlabels = 0;
 
   freeExpression(&(class->text));
   initExpression(&(class->text));
@@ -3004,13 +3293,40 @@ void resetClassStyle(classObj *class)
   }
   class->numstyles = 0;
 
-  initLabel(&(class->label));
-  class->label.size = -1; /* no default */
-
   class->type = -1;
   class->layer = NULL;
 }
 
+labelObj *msGrowClassLabels( classObj *class )
+{
+
+  /* Do we need to increase the size of labels[] by MS_LABEL_ALLOCSIZE?
+   */
+  if (class->numlabels == class->maxlabels) {
+    labelObj **newLabelPtr;
+    int i, newsize;
+
+    newsize = class->maxlabels + MS_LABEL_ALLOCSIZE;
+
+    /* Alloc/realloc labels */
+    newLabelPtr = (labelObj**)realloc(class->labels, newsize*sizeof(labelObj*));
+    MS_CHECK_ALLOC(newLabelPtr, newsize*sizeof(labelObj*), NULL);
+
+    class->labels = newLabelPtr;
+    class->maxlabels = newsize;
+    for(i=class->numlabels; i<class->maxlabels; i++) {
+      class->labels[i] = NULL;
+    }
+  }
+
+  if (class->labels[class->numlabels]==NULL) {
+    class->labels[class->numlabels]=(labelObj*)calloc(1,sizeof(labelObj));
+    MS_CHECK_ALLOC(class->labels[class->numlabels], sizeof(labelObj), NULL);
+  }
+
+  return class->labels[class->numlabels];
+}
+
 int loadClass(classObj *class, layerObj *layer)
 {
   int state;
@@ -3021,219 +3337,257 @@ int loadClass(classObj *class, layerObj *layer)
 
   for(;;) {
     switch(msyylex()) {
-    case(CLASS):
-      break; /* for string loads */
-    case(DEBUG):
-      if((class->debug = getSymbol(3, MS_ON,MS_OFF, MS_NUMBER)) == -1) return(-1);
-      if(class->debug == MS_NUMBER) class->debug = (int) msyynumber;
-      break;
-    case(EOF):
-      msSetError(MS_EOFERR, NULL, "loadClass()");
-      return(-1);
-    case(END):
-      return(0);
-      break;
-    case(EXPRESSION):
-      if(loadExpression(&(class->expression)) == -1) return(-1); /* loadExpression() cleans up previously allocated expression */
-      if(msyysource == MS_URL_TOKENS) {
-        if(msValidateParameter(class->expression.string, msLookupHashTable(&(class->validation), "expression"), msLookupHashTable(&(layer->validation), "expression"), msLookupHashTable(&(map->web.validation), "expression"), NULL) != MS_SUCCESS) {
-          msSetError(MS_MISCERR, "URL-based EXPRESSION configuration failed pattern validation." , "loadClass()");
-          freeExpression(&(class->expression));
-          return(-1);
+      case(CLASS):
+        break; /* for string loads */
+      case(DEBUG):
+        if((class->debug = getSymbol(3, MS_ON,MS_OFF, MS_NUMBER)) == -1) return(-1);
+        if(class->debug == MS_NUMBER) class->debug = (int) msyynumber;
+        break;
+      case(EOF):
+        msSetError(MS_EOFERR, NULL, "loadClass()");
+        return(-1);
+      case(END):
+        return(0);
+        break;
+      case(EXPRESSION):
+        if(loadExpression(&(class->expression)) == -1) return(-1); /* loadExpression() cleans up previously allocated expression */
+        if(msyysource == MS_URL_TOKENS) {
+          if(msValidateParameter(class->expression.string, msLookupHashTable(&(class->validation), "expression"), msLookupHashTable(&(layer->validation), "expression"), msLookupHashTable(&(map->web.validation), "expression"), NULL) != MS_SUCCESS) {
+            msSetError(MS_MISCERR, "URL-based EXPRESSION configuration failed pattern validation." , "loadClass()");
+            freeExpression(&(class->expression));
+            return(-1);
+          }
         }
-      }
-      break;
-    case(GROUP):
-      if(getString(&class->group) == MS_FAILURE) return(-1); /* getString() cleans up previously allocated string */
-      if(msyysource == MS_URL_TOKENS) {
-        if(msValidateParameter(class->group, msLookupHashTable(&(class->validation), "group"), msLookupHashTable(&(layer->validation), "group"), msLookupHashTable(&(map->web.validation), "group"), NULL) != MS_SUCCESS) {
-          msSetError(MS_MISCERR, "URL-based GROUP configuration failed pattern validation." , "loadClass()");
-          msFree(class->group); class->group=NULL;
-          return(-1);
+        break;
+      case(GROUP):
+        if(getString(&class->group) == MS_FAILURE) return(-1); /* getString() cleans up previously allocated string */
+        if(msyysource == MS_URL_TOKENS) {
+          if(msValidateParameter(class->group, msLookupHashTable(&(class->validation), "group"), msLookupHashTable(&(layer->validation), "group"), msLookupHashTable(&(map->web.validation), "group"), NULL) != MS_SUCCESS) {
+            msSetError(MS_MISCERR, "URL-based GROUP configuration failed pattern validation." , "loadClass()");
+            msFree(class->group);
+            class->group=NULL;
+            return(-1);
+          }
         }
-      }
-      break;      
-    case(KEYIMAGE):
-      if(getString(&class->keyimage) == MS_FAILURE) return(-1); /* getString() cleans up previously allocated string */
-      if(msyysource == MS_URL_TOKENS) {
-        if(msValidateParameter(class->keyimage, msLookupHashTable(&(class->validation), "keyimage"), msLookupHashTable(&(layer->validation), "keyimage"), msLookupHashTable(&(map->web.validation), "keyimage"), NULL) != MS_SUCCESS) {
-          msSetError(MS_MISCERR, "URL-based KEYIMAGE configuration failed pattern validation." , "loadClass()");
-          msFree(class->keyimage); class->keyimage=NULL;
-          return(-1);
+        break;
+      case(KEYIMAGE):
+        if(getString(&class->keyimage) == MS_FAILURE) return(-1); /* getString() cleans up previously allocated string */
+        if(msyysource == MS_URL_TOKENS) {
+          if(msValidateParameter(class->keyimage, msLookupHashTable(&(class->validation), "keyimage"), msLookupHashTable(&(layer->validation), "keyimage"), msLookupHashTable(&(map->web.validation), "keyimage"), NULL) != MS_SUCCESS) {
+            msSetError(MS_MISCERR, "URL-based KEYIMAGE configuration failed pattern validation." , "loadClass()");
+            msFree(class->keyimage);
+            class->keyimage=NULL;
+            return(-1);
+          }
         }
-      }
-      break;
-    case(LABEL):
-      class->label.size = MS_MEDIUM; /* only set a default if the LABEL section is present */
-      if(loadLabel(&(class->label)) == -1) return(-1);
-      break;
-    case(MAXSCALE):
-    case(MAXSCALEDENOM):
-      if(getDouble(&(class->maxscaledenom)) == -1) return(-1);
-      break;
-    case(METADATA):
-      if(loadHashTable(&(class->metadata)) != MS_SUCCESS) return(-1);
-      break;
-    case(MINSCALE):
-    case(MINSCALEDENOM):
-      if(getDouble(&(class->minscaledenom)) == -1) return(-1);
-      break;
-    case(MINFEATURESIZE):
-      if(getInteger(&(class->minfeaturesize)) == -1) return(-1);
-      break;
-    case(NAME):
-      if(getString(&class->name) == MS_FAILURE) return(-1);
-      break;         
-    case(STATUS):
-      if((class->status = getSymbol(2, MS_ON,MS_OFF)) == -1) return(-1);
-      break;    
-    case(STYLE):
-      if(msGrowClassStyles(class) == NULL)
-        return(-1);
-      initStyle(class->styles[class->numstyles]);
-      if(loadStyle(class->styles[class->numstyles]) != MS_SUCCESS) return(-1);
-      class->numstyles++;
-      break;
-    case(TEMPLATE):
-      if(getString(&class->template) == MS_FAILURE) return(-1); /* getString() cleans up previously allocated string */
-      if(msyysource == MS_URL_TOKENS) {
-        if(msValidateParameter(class->template, msLookupHashTable(&(class->validation), "template"), msLookupHashTable(&(layer->validation), "template"), msLookupHashTable(&(map->web.validation), "template"), map->templatepattern) != MS_SUCCESS) {
-          msSetError(MS_MISCERR, "URL-based TEMPLATE configuration failed pattern validation." , "loadClass()");
-          msFree(class->template); class->template=NULL;
+        break;
+      case(LABEL):
+        if(msGrowClassLabels(class) == NULL) return(-1);
+        initLabel(class->labels[class->numlabels]);
+        class->labels[class->numlabels]->size = MS_MEDIUM; /* only set a default if the LABEL section is present */
+        if(loadLabel(class->labels[class->numlabels]) == -1) return(-1);
+        class->numlabels++;
+        break;
+      case(LEADER):
+        if(loadLeader(&(class->leader)) == -1) return(-1);
+        break;
+      case(MAXSCALE):
+      case(MAXSCALEDENOM):
+        if(getDouble(&(class->maxscaledenom)) == -1) return(-1);
+        break;
+      case(METADATA):
+        if(loadHashTable(&(class->metadata)) != MS_SUCCESS) return(-1);
+        break;
+      case(MINSCALE):
+      case(MINSCALEDENOM):
+        if(getDouble(&(class->minscaledenom)) == -1) return(-1);
+        break;
+      case(MINFEATURESIZE):
+        if(getInteger(&(class->minfeaturesize)) == -1) return(-1);
+        break;
+      case(NAME):
+        if(getString(&class->name) == MS_FAILURE) return(-1);
+        break;
+      case(STATUS):
+        if((class->status = getSymbol(2, MS_ON,MS_OFF)) == -1) return(-1);
+        break;
+      case(STYLE):
+        if(msGrowClassStyles(class) == NULL)
           return(-1);
-	}
-      }
-      break;
-    case(TEXT):
-      if(loadExpression(&(class->text)) == -1) return(-1); /* loadExpression() cleans up previously allocated expression */
-      if(msyysource == MS_URL_TOKENS) {
-        if(msValidateParameter(class->text.string, msLookupHashTable(&(class->validation), "text"), msLookupHashTable(&(layer->validation), "text"), msLookupHashTable(&(map->web.validation), "text"), NULL) != MS_SUCCESS) {
-          msSetError(MS_MISCERR, "URL-based TEXT configuration failed pattern validation." , "loadClass()");
-          freeExpression(&(class->text));
+        initStyle(class->styles[class->numstyles]);
+        if(loadStyle(class->styles[class->numstyles]) != MS_SUCCESS) return(-1);
+        class->numstyles++;
+        break;
+      case(TEMPLATE):
+        if(getString(&class->template) == MS_FAILURE) return(-1); /* getString() cleans up previously allocated string */
+        if(msyysource == MS_URL_TOKENS) {
+          if(msValidateParameter(class->template, msLookupHashTable(&(class->validation), "template"), msLookupHashTable(&(layer->validation), "template"), msLookupHashTable(&(map->web.validation), "template"), map->templatepattern) != MS_SUCCESS) {
+            msSetError(MS_MISCERR, "URL-based TEMPLATE configuration failed pattern validation." , "loadClass()");
+            msFree(class->template);
+            class->template=NULL;
+            return(-1);
+          }
+        }
+        break;
+      case(TEXT):
+        if(loadExpression(&(class->text)) == -1) return(-1); /* loadExpression() cleans up previously allocated expression */
+        if(msyysource == MS_URL_TOKENS) {
+          if(msValidateParameter(class->text.string, msLookupHashTable(&(class->validation), "text"), msLookupHashTable(&(layer->validation), "text"), msLookupHashTable(&(map->web.validation), "text"), NULL) != MS_SUCCESS) {
+            msSetError(MS_MISCERR, "URL-based TEXT configuration failed pattern validation." , "loadClass()");
+            freeExpression(&(class->text));
+            return(-1);
+          }
+        }
+        if((class->text.type != MS_STRING) && (class->text.type != MS_EXPRESSION)) {
+          msSetError(MS_MISCERR, "Text expressions support constant or tagged replacement strings." , "loadClass()");
           return(-1);
         }
-      }
-      if((class->text.type != MS_STRING) && (class->text.type != MS_EXPRESSION)) {
-	msSetError(MS_MISCERR, "Text expressions support constant or tagged replacement strings." , "loadClass()");
-	return(-1);
-      }
-      break;
-    case(TITLE):
-      if(getString(&class->title) == MS_FAILURE) return(-1); /* getString() cleans up previously allocated string */
-      if(msyysource == MS_URL_TOKENS) {
-        if(msValidateParameter(class->title, msLookupHashTable(&(class->validation), "title"), msLookupHashTable(&(layer->validation), "title"), msLookupHashTable(&(map->web.validation), "title"), NULL) != MS_SUCCESS) {
-          msSetError(MS_MISCERR, "URL-based TITLE configuration failed pattern validation." , "loadClass()");
-          msFree(class->title); class->title=NULL;
+        break;
+      case(TITLE):
+        if(getString(&class->title) == MS_FAILURE) return(-1); /* getString() cleans up previously allocated string */
+        if(msyysource == MS_URL_TOKENS) {
+          if(msValidateParameter(class->title, msLookupHashTable(&(class->validation), "title"), msLookupHashTable(&(layer->validation), "title"), msLookupHashTable(&(map->web.validation), "title"), NULL) != MS_SUCCESS) {
+            msSetError(MS_MISCERR, "URL-based TITLE configuration failed pattern validation." , "loadClass()");
+            msFree(class->title);
+            class->title=NULL;
+            return(-1);
+          }
+        }
+        break;
+      case(TYPE):
+        if((class->type = getSymbol(6, MS_LAYER_POINT,MS_LAYER_LINE,MS_LAYER_RASTER,MS_LAYER_POLYGON,MS_LAYER_ANNOTATION,MS_LAYER_CIRCLE)) == -1) return(-1);
+        break;
+
+        /*
+        ** for backwards compatability, these are shortcuts for style 0
+        */
+      case(BACKGROUNDCOLOR):
+        if (msMaybeAllocateClassStyle(class, 0)) return MS_FAILURE;
+        if(loadColor(&(class->styles[0]->backgroundcolor), NULL) != MS_SUCCESS) return(-1);
+        break;
+      case(COLOR):
+        if (msMaybeAllocateClassStyle(class, 0)) return MS_FAILURE;
+        if(loadColor(&(class->styles[0]->color), NULL) != MS_SUCCESS) return(-1);
+        class->numstyles = 1; /* must *always* set a color or outlinecolor */
+        break;
+      case(MAXSIZE):
+        if (msMaybeAllocateClassStyle(class, 0)) return MS_FAILURE;
+        if(getDouble(&(class->styles[0]->maxsize)) == -1) return(-1);
+        break;
+      case(MINSIZE):
+        if (msMaybeAllocateClassStyle(class, 0)) return MS_FAILURE;
+        if(getDouble(&(class->styles[0]->minsize)) == -1) return(-1);
+        break;
+      case(OUTLINECOLOR):
+        if (msMaybeAllocateClassStyle(class, 0)) return MS_FAILURE;
+        if(loadColor(&(class->styles[0]->outlinecolor), NULL) != MS_SUCCESS) return(-1);
+        class->numstyles = 1; /* must *always* set a color, symbol or outlinecolor */
+        break;
+      case(SIZE):
+        if (msMaybeAllocateClassStyle(class, 0)) return MS_FAILURE;
+        if(getDouble(&(class->styles[0]->size)) == -1) return(-1);
+        break;
+      case(SYMBOL):
+        if (msMaybeAllocateClassStyle(class, 0)) return MS_FAILURE;
+        if((state = getSymbol(2, MS_NUMBER,MS_STRING)) == -1) return(-1);
+        if(state == MS_NUMBER)
+          class->styles[0]->symbol = (int) msyynumber;
+        else {
+          if (class->styles[0]->symbolname != NULL)
+            msFree(class->styles[0]->symbolname);
+          class->styles[0]->symbolname = msStrdup(msyystring_buffer);
+          class->numstyles = 1;
+        }
+        break;
+
+        /*
+        ** for backwards compatability, these are shortcuts for style 1
+        */
+      case(OVERLAYBACKGROUNDCOLOR):
+        if (msMaybeAllocateClassStyle(class, 1)) return MS_FAILURE;
+        if(loadColor(&(class->styles[1]->backgroundcolor), NULL) != MS_SUCCESS) return(-1);
+        break;
+      case(OVERLAYCOLOR):
+        if (msMaybeAllocateClassStyle(class, 1)) return MS_FAILURE;
+        if(loadColor(&(class->styles[1]->color), NULL) != MS_SUCCESS) return(-1);
+        class->numstyles = 2; /* must *always* set a color, symbol or outlinecolor */
+        break;
+      case(OVERLAYMAXSIZE):
+        if (msMaybeAllocateClassStyle(class, 1)) return MS_FAILURE;
+        if(getDouble(&(class->styles[1]->maxsize)) == -1) return(-1);
+        break;
+      case(OVERLAYMINSIZE):
+        if (msMaybeAllocateClassStyle(class, 1)) return MS_FAILURE;
+        if(getDouble(&(class->styles[1]->minsize)) == -1) return(-1);
+        break;
+      case(OVERLAYOUTLINECOLOR):
+        if (msMaybeAllocateClassStyle(class, 1)) return MS_FAILURE;
+        if(loadColor(&(class->styles[1]->outlinecolor), NULL) != MS_SUCCESS) return(-1);
+        class->numstyles = 2; /* must *always* set a color, symbol or outlinecolor */
+        break;
+      case(OVERLAYSIZE):
+        if (msMaybeAllocateClassStyle(class, 1)) return MS_FAILURE;
+        if(getDouble(&(class->styles[1]->size)) == -1) return(-1);
+        break;
+      case(OVERLAYSYMBOL):
+        if (msMaybeAllocateClassStyle(class, 1)) return MS_FAILURE;
+        if((state = getSymbol(2, MS_NUMBER,MS_STRING)) == -1) return(-1);
+        if(state == MS_NUMBER)
+          class->styles[1]->symbol = (int) msyynumber;
+        else  {
+          if (class->styles[1]->symbolname != NULL)
+            msFree(class->styles[1]->symbolname);
+          class->styles[1]->symbolname = msStrdup(msyystring_buffer);
+        }
+        class->numstyles = 2;
+        break;
+
+      case(VALIDATION):
+        if(loadHashTable(&(class->validation)) != MS_SUCCESS) return(-1);
+        break;
+      default:
+        if(strlen(msyystring_buffer) > 0) {
+          msSetError(MS_IDENTERR, "Parsing error near (%s):(line %d)", "loadClass()", msyystring_buffer, msyylineno);
           return(-1);
+        } else {
+          return(0); /* end of a string, not an error */
         }
-      }
-      break;
-    case(TYPE):
-      if((class->type = getSymbol(6, MS_LAYER_POINT,MS_LAYER_LINE,MS_LAYER_RASTER,MS_LAYER_POLYGON,MS_LAYER_ANNOTATION,MS_LAYER_CIRCLE)) == -1) return(-1);
-      break;
+    }
+  }
+}
 
-    /*
-    ** for backwards compatability, these are shortcuts for style 0
-    */
-    case(BACKGROUNDCOLOR):
-      if (msMaybeAllocateClassStyle(class, 0)) return MS_FAILURE;
-      if(loadColor(&(class->styles[0]->backgroundcolor), NULL) != MS_SUCCESS) return(-1);
-      break;
-    case(COLOR):
-      if (msMaybeAllocateClassStyle(class, 0)) return MS_FAILURE;
-      if(loadColor(&(class->styles[0]->color), NULL) != MS_SUCCESS) return(-1);
-      class->numstyles = 1; /* must *always* set a color or outlinecolor */
-      break;
-    case(MAXSIZE):
-      if (msMaybeAllocateClassStyle(class, 0)) return MS_FAILURE;
-      if(getDouble(&(class->styles[0]->maxsize)) == -1) return(-1);
-      break;
-    case(MINSIZE):      
-      if (msMaybeAllocateClassStyle(class, 0)) return MS_FAILURE;
-      if(getDouble(&(class->styles[0]->minsize)) == -1) return(-1);
-      break;
-    case(OUTLINECOLOR):            
-      if (msMaybeAllocateClassStyle(class, 0)) return MS_FAILURE;
-      if(loadColor(&(class->styles[0]->outlinecolor), NULL) != MS_SUCCESS) return(-1);
-      class->numstyles = 1; /* must *always* set a color, symbol or outlinecolor */
-      break;
-    case(SIZE):
-      if (msMaybeAllocateClassStyle(class, 0)) return MS_FAILURE;
-      if(getDouble(&(class->styles[0]->size)) == -1) return(-1);
-      break;
-    case(SYMBOL):
-      if (msMaybeAllocateClassStyle(class, 0)) return MS_FAILURE;
-      if((state = getSymbol(2, MS_NUMBER,MS_STRING)) == -1) return(-1);
-      if(state == MS_NUMBER)
-	class->styles[0]->symbol = (int) msyynumber;
-      else
-      {
-        if (class->styles[0]->symbolname != NULL)
-          msFree(class->styles[0]->symbolname);
-	class->styles[0]->symbolname = msStrdup(msyystring_buffer);
-        class->numstyles = 1;
-      }
-      break;
+static int classResolveSymbolNames(classObj *class)
+{
+  int i,j;
 
-    /*
-    ** for backwards compatability, these are shortcuts for style 1
-    */
-    case(OVERLAYBACKGROUNDCOLOR):
-      if (msMaybeAllocateClassStyle(class, 1)) return MS_FAILURE;
-      if(loadColor(&(class->styles[1]->backgroundcolor), NULL) != MS_SUCCESS) return(-1);
-      break;
-    case(OVERLAYCOLOR):
-      if (msMaybeAllocateClassStyle(class, 1)) return MS_FAILURE;
-      if(loadColor(&(class->styles[1]->color), NULL) != MS_SUCCESS) return(-1);
-      class->numstyles = 2; /* must *always* set a color, symbol or outlinecolor */
-      break;
-    case(OVERLAYMAXSIZE):
-      if (msMaybeAllocateClassStyle(class, 1)) return MS_FAILURE;
-      if(getDouble(&(class->styles[1]->maxsize)) == -1) return(-1);
-      break;
-    case(OVERLAYMINSIZE):      
-      if (msMaybeAllocateClassStyle(class, 1)) return MS_FAILURE;
-      if(getDouble(&(class->styles[1]->minsize)) == -1) return(-1);
-      break;
-    case(OVERLAYOUTLINECOLOR):      
-      if (msMaybeAllocateClassStyle(class, 1)) return MS_FAILURE;
-      if(loadColor(&(class->styles[1]->outlinecolor), NULL) != MS_SUCCESS) return(-1);
-      class->numstyles = 2; /* must *always* set a color, symbol or outlinecolor */
-      break;
-    case(OVERLAYSIZE):
-      if (msMaybeAllocateClassStyle(class, 1)) return MS_FAILURE;
-      if(getDouble(&(class->styles[1]->size)) == -1) return(-1);
-      break;
-    case(OVERLAYSYMBOL):
-      if (msMaybeAllocateClassStyle(class, 1)) return MS_FAILURE;
-      if((state = getSymbol(2, MS_NUMBER,MS_STRING)) == -1) return(-1);
-      if(state == MS_NUMBER)
-	class->styles[1]->symbol = (int) msyynumber;
-      else  {
-        if (class->styles[1]->symbolname != NULL)
-          msFree(class->styles[1]->symbolname);
-	class->styles[1]->symbolname = msStrdup(msyystring_buffer);
+  /* step through styles and labels to resolve symbol names */
+  /* class styles */
+  for(i=0; i<class->numstyles; i++) {
+    if(class->styles[i]->symbolname) {
+      if((class->styles[i]->symbol =  msGetSymbolIndex(&(class->layer->map->symbolset), class->styles[i]->symbolname, MS_TRUE)) == -1) {
+        msSetError(MS_MISCERR, "Undefined symbol \"%s\" in class, style %d of layer %s.", "classResolveSymbolNames()", class->styles[i]->symbolname, i, class->layer->name);
+        return MS_FAILURE;
       }
-      class->numstyles = 2;
-      break;
+    }
+  }
 
-    case(VALIDATION):
-      if(loadHashTable(&(class->validation)) != MS_SUCCESS) return(-1);
-      break;
-    default:
-      if(strlen(msyystring_buffer) > 0) {
-        msSetError(MS_IDENTERR, "Parsing error near (%s):(line %d)", "loadClass()", msyystring_buffer, msyylineno);
-        return(-1);
-      } else {
-        return(0); /* end of a string, not an error */
+  /* label styles */
+  for(i=0; i<class->numlabels; i++) {
+    for(j=0; j<class->labels[i]->numstyles; j++) {
+      if(class->labels[i]->styles[j]->symbolname) {
+        if((class->labels[i]->styles[j]->symbol =  msGetSymbolIndex(&(class->layer->map->symbolset), class->labels[i]->styles[j]->symbolname, MS_TRUE)) == -1) {
+          msSetError(MS_MISCERR, "Undefined symbol \"%s\" in class, label style %d of layer %s.", "classResolveSymbolNames()", class->labels[i]->styles[j]->symbolname, j, class->layer->name);
+          return MS_FAILURE;
+        }
       }
     }
   }
+
+  return MS_SUCCESS;
 }
 
 int msUpdateClassFromString(classObj *class, char *string, int url_string)
 {
-  int k;
   if(!class || !string) return MS_FAILURE;
 
   msAcquireLock( TLOCK_PARSER );
@@ -3255,27 +3609,7 @@ int msUpdateClassFromString(classObj *class, char *string, int url_string)
 
   msyylex_destroy();
 
-  /* step through styles and labels to resolve symbol names */
-  /* class styles */
-  for(k=0; k<class->numstyles; k++) {
-      if(class->styles[k]->symbolname) {
-          if((class->styles[k]->symbol =  msGetSymbolIndex(&(class->layer->map->symbolset), class->styles[k]->symbolname, MS_TRUE)) == -1) {
-              msSetError(MS_MISCERR, "Undefined symbol \"%s\" in class, style %d of layer %s.", "msUpdateClassFromString()", class->styles[k]->symbolname, k, class->layer->name);
-              return MS_FAILURE;
-          }
-      }
-  }
-
-  /* label styles */
-  for(k=0; k<class->label.numstyles; k++) {
-      if(class->label.styles[k]->symbolname) {
-          if((class->label.styles[k]->symbol =  msGetSymbolIndex(&(class->layer->map->symbolset), class->label.styles[k]->symbolname, MS_TRUE)) == -1) {
-              msSetError(MS_MISCERR, "Undefined symbol \"%s\" in class, label style %d of layer %s.", 
-                         "msUpdateClassFromString()", class->label.styles[k]->symbolname, k, class->layer->name);
-              return MS_FAILURE;
-          }
-      }
-  }
+  if(classResolveSymbolNames(class) != MS_SUCCESS) return MS_FAILURE;
 
   return MS_SUCCESS;
 }
@@ -3290,10 +3624,11 @@ static void writeClass(FILE *stream, int indent, classObj *class)
   writeBlockBegin(stream, indent, "CLASS");
   writeString(stream, indent, "NAME", NULL, class->name);
   writeString(stream, indent, "GROUP", NULL, class->group);
-  writeNumber(stream, indent, "DEBUG", 0, class->debug); 
+  writeNumber(stream, indent, "DEBUG", 0, class->debug);
   writeExpression(stream, indent, "EXPRESSION", &(class->expression));
   writeString(stream, indent, "KEYIMAGE", NULL, class->keyimage);
-  writeLabel(stream, indent, &(class->label));
+  for(i=0; i<class->numlabels; i++) writeLabel(stream, indent, class->labels[i]);
+  writeLeader(stream,indent,&(class->leader));
   writeNumber(stream, indent, "MAXSCALEDENOM", -1, class->maxscaledenom);
   writeHashTable(stream, indent, "METADATA", &(class->metadata));
   writeNumber(stream, indent, "MINSCALEDENOM", -1, class->minscaledenom);
@@ -3318,13 +3653,13 @@ int initLayer(layerObj *layer, mapObj *map)
   layer->debug = (int)msGetGlobalDebugLevel();
   MS_REFCNT_INIT(layer);
 
-  /* Set maxclasses = 0, class[] will be allocated as needed on first call 
+  /* Set maxclasses = 0, class[] will be allocated as needed on first call
    * to msGrowLayerClasses()
    */
   layer->numclasses = 0;
   layer->maxclasses = 0;
   layer->class = NULL;
-  
+
   layer->name = NULL;
   layer->group = NULL;
   layer->status = MS_OFF;
@@ -3351,7 +3686,7 @@ int initLayer(layerObj *layer, mapObj *map)
 
   layer->maxfeatures = -1; /* no quota */
   layer->startindex = -1; /*used for pagination*/
-  
+
   layer->template = layer->header = layer->footer = NULL;
 
   layer->transform = MS_TRUE;
@@ -3410,14 +3745,14 @@ int initLayer(layerObj *layer, mapObj *map)
   initHashTable(&(layer->metadata));
   initHashTable(&(layer->bindvals));
   initHashTable(&(layer->validation));
-  
+
   layer->dump = MS_FALSE;
 
   layer->styleitem = NULL;
   layer->styleitemindex = -1;
 
   layer->opacity = 100; /* fully opaque */
-  
+
   layer->numprocessing = 0;
   layer->processing = NULL;
   layer->numjoins = 0;
@@ -3429,19 +3764,25 @@ int initLayer(layerObj *layer, mapObj *map)
   layer->extent.maxx = -1.0;
   layer->extent.maxy = -1.0;
 
+  layer->mask = NULL;
+  layer->maskimage = NULL;
+
   return(0);
 }
 
-int freeLayer(layerObj *layer) {
+int freeLayer(layerObj *layer)
+{
   int i;
   if (!layer) return MS_FAILURE;
-  if( MS_REFCNT_DECR_IS_NOT_ZERO(layer) ) { return MS_FAILURE; }
+  if( MS_REFCNT_DECR_IS_NOT_ZERO(layer) ) {
+    return MS_FAILURE;
+  }
 
   if (layer->debug >= MS_DEBUGLEVEL_VVV)
-     msDebug("freeLayer(): freeing layer at %p.\n",layer);
+    msDebug("freeLayer(): freeing layer at %p.\n",layer);
 
   if(msLayerIsOpen(layer))
-     msLayerClose(layer);
+    msLayerClose(layer);
 
   msFree(layer->name);
   msFree(layer->group);
@@ -3464,12 +3805,12 @@ int freeLayer(layerObj *layer) {
 
   freeCluster(&layer->cluster);
 
-  for(i=0;i<layer->maxclasses;i++) {
+  for(i=0; i<layer->maxclasses; i++) {
     if (layer->class[i] != NULL) {
-    	layer->class[i]->layer=NULL;
-    	if ( freeClass(layer->class[i]) == MS_SUCCESS ) {
-		msFree(layer->class[i]);
-	}
+      layer->class[i]->layer=NULL;
+      if ( freeClass(layer->class[i]) == MS_SUCCESS ) {
+        msFree(layer->class[i]);
+      }
     }
   }
   msFree(layer->class);
@@ -3477,7 +3818,7 @@ int freeLayer(layerObj *layer) {
   if(layer->features)
     freeFeatureList(layer->features);
 
-  if(layer->resultcache) {    
+  if(layer->resultcache) {
     if(layer->resultcache->results) free(layer->resultcache->results);
     msFree(layer->resultcache);
   }
@@ -3495,22 +3836,27 @@ int freeLayer(layerObj *layer) {
   if(&(layer->bindvals))  msFreeHashItems(&layer->bindvals);
 
   if(layer->numprocessing > 0)
-      msFreeCharArray(layer->processing, layer->numprocessing);
+    msFreeCharArray(layer->processing, layer->numprocessing);
 
-  for(i=0;i<layer->numjoins;i++) /* each join */
+  for(i=0; i<layer->numjoins; i++) /* each join */
     freeJoin(&(layer->joins[i]));
   msFree(layer->joins);
   layer->numjoins = 0;
 
   layer->classgroup = NULL;
 
+  msFree(layer->mask);
+  if(layer->maskimage) {
+    msFreeImage(layer->maskimage);
+  }
+
   return MS_SUCCESS;
 }
 
 /*
-** Ensure there is at least one free entry in the class array of this 
-** layerObj. Grow the allocated class array if necessary and allocate 
-** a new class for class[numclasses] if there is not already one, 
+** Ensure there is at least one free entry in the class array of this
+** layerObj. Grow the allocated class array if necessary and allocate
+** a new class for class[numclasses] if there is not already one,
 ** setting its contents to all zero bytes (i.e. does not call initClass()
 ** on it).
 **
@@ -3521,32 +3867,32 @@ int freeLayer(layerObj *layer) {
 */
 classObj *msGrowLayerClasses( layerObj *layer )
 {
-    /* Do we need to increase the size of class[] by  MS_CLASS_ALLOCSIZE?
-     */
-    if (layer->numclasses == layer->maxclasses) {
-        classObj **newClassPtr;
-        int i, newsize;
+  /* Do we need to increase the size of class[] by  MS_CLASS_ALLOCSIZE?
+   */
+  if (layer->numclasses == layer->maxclasses) {
+    classObj **newClassPtr;
+    int i, newsize;
 
-        newsize = layer->maxclasses + MS_CLASS_ALLOCSIZE;
+    newsize = layer->maxclasses + MS_CLASS_ALLOCSIZE;
 
-        /* Alloc/realloc classes */
-        newClassPtr = (classObj**)realloc(layer->class,
-                                          newsize*sizeof(classObj*));
-        MS_CHECK_ALLOC(newClassPtr, newsize*sizeof(classObj*), NULL);
+    /* Alloc/realloc classes */
+    newClassPtr = (classObj**)realloc(layer->class,
+                                      newsize*sizeof(classObj*));
+    MS_CHECK_ALLOC(newClassPtr, newsize*sizeof(classObj*), NULL);
 
-        layer->class = newClassPtr;
-        layer->maxclasses = newsize;
-        for(i=layer->numclasses; i<layer->maxclasses; i++) {
-            layer->class[i] = NULL;
-        }
+    layer->class = newClassPtr;
+    layer->maxclasses = newsize;
+    for(i=layer->numclasses; i<layer->maxclasses; i++) {
+      layer->class[i] = NULL;
     }
+  }
 
-    if (layer->class[layer->numclasses]==NULL) {
-        layer->class[layer->numclasses]=(classObj*)calloc(1,sizeof(classObj));
-        MS_CHECK_ALLOC(layer->class[layer->numclasses], sizeof(classObj), NULL);
-    }
+  if (layer->class[layer->numclasses]==NULL) {
+    layer->class[layer->numclasses]=(classObj*)calloc(1,sizeof(classObj));
+    MS_CHECK_ALLOC(layer->class[layer->numclasses], sizeof(classObj), NULL);
+  }
 
-    return layer->class[layer->numclasses];
+  return layer->class[layer->numclasses];
 }
 
 int loadLayer(layerObj *layer, mapObj *map)
@@ -3557,376 +3903,401 @@ int loadLayer(layerObj *layer, mapObj *map)
 
   for(;;) {
     switch(msyylex()) {
-    case(BINDVALS):
-      if(loadHashTable(&(layer->bindvals)) != MS_SUCCESS) return(-1);
-      break;
-    case(CLASS):
-      if (msGrowLayerClasses(layer) == NULL)
-	return(-1);
-      initClass(layer->class[layer->numclasses]);
-      if(loadClass(layer->class[layer->numclasses], layer) == -1) return(-1);
-      if(layer->class[layer->numclasses]->type == -1) layer->class[layer->numclasses]->type = layer->type;
-      layer->numclasses++;
-      break;
-    case(CLUSTER):
-      initCluster(&layer->cluster);
-      if(loadCluster(&layer->cluster) == -1) return(-1);
-      break;
-    case(CLASSGROUP):
-      if(getString(&layer->classgroup) == MS_FAILURE) return(-1); /* getString() cleans up previously allocated string */
-      if(msyysource == MS_URL_TOKENS) {
-        if(msValidateParameter(layer->classgroup, msLookupHashTable(&(layer->validation), "classgroup"), msLookupHashTable(&(map->web.validation), "classgroup"), NULL, NULL) != MS_SUCCESS) {
-          msSetError(MS_MISCERR, "URL-based CLASSGROUP configuration failed pattern validation." , "loadLayer()");
-          msFree(layer->classgroup); layer->classgroup=NULL;
+      case(BINDVALS):
+        if(loadHashTable(&(layer->bindvals)) != MS_SUCCESS) return(-1);
+        break;
+      case(CLASS):
+        if (msGrowLayerClasses(layer) == NULL)
           return(-1);
+        initClass(layer->class[layer->numclasses]);
+        if(loadClass(layer->class[layer->numclasses], layer) == -1) return(-1);
+        if(layer->class[layer->numclasses]->type == -1) layer->class[layer->numclasses]->type = layer->type;
+        layer->numclasses++;
+        break;
+      case(CLUSTER):
+        initCluster(&layer->cluster);
+        if(loadCluster(&layer->cluster) == -1) return(-1);
+        break;
+      case(CLASSGROUP):
+        if(getString(&layer->classgroup) == MS_FAILURE) return(-1); /* getString() cleans up previously allocated string */
+        if(msyysource == MS_URL_TOKENS) {
+          if(msValidateParameter(layer->classgroup, msLookupHashTable(&(layer->validation), "classgroup"), msLookupHashTable(&(map->web.validation), "classgroup"), NULL, NULL) != MS_SUCCESS) {
+            msSetError(MS_MISCERR, "URL-based CLASSGROUP configuration failed pattern validation." , "loadLayer()");
+            msFree(layer->classgroup);
+            layer->classgroup=NULL;
+            return(-1);
+          }
         }
-      }
-      break;
-    case(CLASSITEM):
-      if(getString(&layer->classitem) == MS_FAILURE) return(-1); /* getString() cleans up previously allocated string */
-      if(msyysource == MS_URL_TOKENS) {
-        if(msValidateParameter(layer->classitem, msLookupHashTable(&(layer->validation), "classitem"), msLookupHashTable(&(map->web.validation), "classitem"), NULL, NULL) != MS_SUCCESS) {
-          msSetError(MS_MISCERR, "URL-based CLASSITEM configuration failed pattern validation." , "loadLayer()");
-          msFree(layer->classitem); layer->classitem=NULL;
-          return(-1);
+        break;
+      case(CLASSITEM):
+        if(getString(&layer->classitem) == MS_FAILURE) return(-1); /* getString() cleans up previously allocated string */
+        if(msyysource == MS_URL_TOKENS) {
+          if(msValidateParameter(layer->classitem, msLookupHashTable(&(layer->validation), "classitem"), msLookupHashTable(&(map->web.validation), "classitem"), NULL, NULL) != MS_SUCCESS) {
+            msSetError(MS_MISCERR, "URL-based CLASSITEM configuration failed pattern validation." , "loadLayer()");
+            msFree(layer->classitem);
+            layer->classitem=NULL;
+            return(-1);
+          }
         }
-      }
-      break;
-    case(CONNECTION):
-      if(getString(&layer->connection) == MS_FAILURE) return(-1); /* getString() cleans up previously allocated string */
-      if(msyysource == MS_URL_TOKENS) {
-        if(msValidateParameter(layer->connection, msLookupHashTable(&(layer->validation), "connection"), msLookupHashTable(&(map->web.validation), "connection"), NULL, NULL) != MS_SUCCESS) {
-          msSetError(MS_MISCERR, "URL-based CONNECTION configuration failed pattern validation." , "loadLayer()");
-          msFree(layer->connection); layer->connection=NULL;
-          return(-1);
+        break;
+      case(CONNECTION):
+        if(getString(&layer->connection) == MS_FAILURE) return(-1); /* getString() cleans up previously allocated string */
+        if(msyysource == MS_URL_TOKENS) {
+          if(msValidateParameter(layer->connection, msLookupHashTable(&(layer->validation), "connection"), msLookupHashTable(&(map->web.validation), "connection"), NULL, NULL) != MS_SUCCESS) {
+            msSetError(MS_MISCERR, "URL-based CONNECTION configuration failed pattern validation." , "loadLayer()");
+            msFree(layer->connection);
+            layer->connection=NULL;
+            return(-1);
+          }
         }
-      }
-      break;
-    case(CONNECTIONTYPE):
-      if((layer->connectiontype = getSymbol(9, MS_SDE, MS_OGR, MS_POSTGIS, MS_WMS, MS_ORACLESPATIAL, MS_WFS, MS_GRATICULE, MS_PLUGIN, MS_UNION)) == -1) return(-1);
-      break;
-    case(DATA):
-      if(getString(&layer->data) == MS_FAILURE) return(-1); /* getString() cleans up previously allocated string */
-      if(msyysource == MS_URL_TOKENS) {
-        if(msValidateParameter(layer->data, msLookupHashTable(&(layer->validation), "data"), msLookupHashTable(&(map->web.validation), "data"), map->datapattern, NULL) != MS_SUCCESS) {
-          msSetError(MS_MISCERR, "URL-based DATA configuration failed pattern validation." , "loadLayer()");
-          msFree(layer->data); layer->data=NULL;
+        break;
+      case(CONNECTIONTYPE):
+        if((layer->connectiontype = getSymbol(10, MS_SDE, MS_OGR, MS_POSTGIS, MS_WMS, MS_ORACLESPATIAL, MS_WFS, MS_GRATICULE, MS_PLUGIN, MS_UNION, MS_UVRASTER)) == -1) return(-1);
+        break;
+      case(DATA):
+        if(getString(&layer->data) == MS_FAILURE) return(-1); /* getString() cleans up previously allocated string */
+        if(msyysource == MS_URL_TOKENS) {
+          if(msValidateParameter(layer->data, msLookupHashTable(&(layer->validation), "data"), msLookupHashTable(&(map->web.validation), "data"), map->datapattern, NULL) != MS_SUCCESS) {
+            msSetError(MS_MISCERR, "URL-based DATA configuration failed pattern validation." , "loadLayer()");
+            msFree(layer->data);
+            layer->data=NULL;
+            return(-1);
+          }
+        }
+        break;
+      case(DEBUG):
+        if((layer->debug = getSymbol(3, MS_ON,MS_OFF, MS_NUMBER)) == -1) return(-1);
+        if(layer->debug == MS_NUMBER) layer->debug = (int) msyynumber;
+        break;
+      case(DUMP):
+        if((layer->dump = getSymbol(2, MS_TRUE,MS_FALSE)) == -1) return(-1);
+        break;
+      case(EOF):
+        msSetError(MS_EOFERR, NULL, "loadLayer()");
+        return(-1);
+        break;
+      case(END):
+        if(layer->type == -1) {
+          msSetError(MS_MISCERR, "Layer type not set.", "loadLayer()");
           return(-1);
         }
-      }
-      break;
-    case(DEBUG):
-      if((layer->debug = getSymbol(3, MS_ON,MS_OFF, MS_NUMBER)) == -1) return(-1);
-      if(layer->debug == MS_NUMBER) layer->debug = (int) msyynumber;
-      break;
-    case(DUMP):
-      if((layer->dump = getSymbol(2, MS_TRUE,MS_FALSE)) == -1) return(-1);
-      break;
-    case(EOF):
-      msSetError(MS_EOFERR, NULL, "loadLayer()");      
-      return(-1);
-      break;
-    case(END):
-      if(layer->type == -1) {
-	msSetError(MS_MISCERR, "Layer type not set.", "loadLayer()");      
-	return(-1);
-      }
 
-      return(0);
-      break;
-    case(EXTENT):
-    {
+        return(0);
+        break;
+      case(EXTENT): {
         if(getDouble(&(layer->extent.minx)) == -1) return(-1);
         if(getDouble(&(layer->extent.miny)) == -1) return(-1);
         if(getDouble(&(layer->extent.maxx)) == -1) return(-1);
         if(getDouble(&(layer->extent.maxy)) == -1) return(-1);
         if (!MS_VALID_EXTENT(layer->extent)) {
-          msSetError(MS_MISCERR, "Given layer extent is invalid. Check that it is in the form: minx, miny, maxx, maxy", "loadLayer()"); 
+          msSetError(MS_MISCERR, "Given layer extent is invalid. Check that it is in the form: minx, miny, maxx, maxy", "loadLayer()");
           return(-1);
         }
         break;
-    }
-    case(FEATURE):
-      if(layer->type == -1) {
-	msSetError(MS_MISCERR, "Layer type must be set before defining inline features.", "loadLayer()");      
-	return(-1);
       }
+      case(FEATURE):
+        if(layer->type == -1) {
+          msSetError(MS_MISCERR, "Layer type must be set before defining inline features.", "loadLayer()");
+          return(-1);
+        }
 
-      if(layer->type == MS_LAYER_POLYGON)
-	type = MS_SHAPE_POLYGON;
-      else if(layer->type == MS_LAYER_LINE)
-	type = MS_SHAPE_LINE;
-      else
-	type = MS_SHAPE_POINT;	
-	  
-      layer->connectiontype = MS_INLINE;
+        if(layer->type == MS_LAYER_POLYGON)
+          type = MS_SHAPE_POLYGON;
+        else if(layer->type == MS_LAYER_LINE)
+          type = MS_SHAPE_LINE;
+        else
+          type = MS_SHAPE_POINT;
 
-      if(loadFeature(layer, type) == MS_FAILURE) return(-1);      
-      break;
-    case(FILTER):
-      if(loadExpression(&(layer->filter)) == -1) return(-1); /* loadExpression() cleans up previously allocated expression */
-      if(msyysource == MS_URL_TOKENS) {
-        if(msValidateParameter(layer->filter.string, msLookupHashTable(&(layer->validation), "filter"), msLookupHashTable(&(map->web.validation), "filter"), NULL, NULL) != MS_SUCCESS) {
-          msSetError(MS_MISCERR, "URL-based FILTER configuration failed pattern validation." , "loadLayer()");
-          freeExpression(&(layer->filter));
-          return(-1);
-	}
-      }
-      break;
-    case(FILTERITEM):
-      if(getString(&layer->filteritem) == MS_FAILURE) return(-1); /* getString() cleans up previously allocated string */
-      if(msyysource == MS_URL_TOKENS) {
-        if(msValidateParameter(layer->filteritem, msLookupHashTable(&(layer->validation), "filteritem"), msLookupHashTable(&(map->web.validation), "filteritem"), NULL, NULL) != MS_SUCCESS) {
-          msSetError(MS_MISCERR, "URL-based FILTERITEM configuration failed pattern validation." , "loadLayer()");
-          msFree(layer->filteritem); layer->filteritem=NULL;
-          return(-1);
+        layer->connectiontype = MS_INLINE;
+
+        if(loadFeature(layer, type) == MS_FAILURE) return(-1);
+        break;
+      case(FILTER):
+        if(loadExpression(&(layer->filter)) == -1) return(-1); /* loadExpression() cleans up previously allocated expression */
+        if(msyysource == MS_URL_TOKENS) {
+          if(msValidateParameter(layer->filter.string, msLookupHashTable(&(layer->validation), "filter"), msLookupHashTable(&(map->web.validation), "filter"), NULL, NULL) != MS_SUCCESS) {
+            msSetError(MS_MISCERR, "URL-based FILTER configuration failed pattern validation." , "loadLayer()");
+            freeExpression(&(layer->filter));
+            return(-1);
+          }
         }
-      }
-      break;
-    case(FOOTER):
-      if(getString(&layer->footer) == MS_FAILURE) return(-1); /* getString() cleans up previously allocated string */
-      if(msyysource == MS_URL_TOKENS) {
-        if(msValidateParameter(layer->footer, msLookupHashTable(&(layer->validation), "footer"), msLookupHashTable(&(map->web.validation), "footer"), map->templatepattern, NULL) != MS_SUCCESS) {
-          msSetError(MS_MISCERR, "URL-based FOOTER configuration failed pattern validation." , "loadLayer()");
-          msFree(layer->footer); layer->footer=NULL;
-          return(-1);
+        break;
+      case(FILTERITEM):
+        if(getString(&layer->filteritem) == MS_FAILURE) return(-1); /* getString() cleans up previously allocated string */
+        if(msyysource == MS_URL_TOKENS) {
+          if(msValidateParameter(layer->filteritem, msLookupHashTable(&(layer->validation), "filteritem"), msLookupHashTable(&(map->web.validation), "filteritem"), NULL, NULL) != MS_SUCCESS) {
+            msSetError(MS_MISCERR, "URL-based FILTERITEM configuration failed pattern validation." , "loadLayer()");
+            msFree(layer->filteritem);
+            layer->filteritem=NULL;
+            return(-1);
+          }
         }
-      }
-      break;
-    case(GRID):
-      layer->connectiontype = MS_GRATICULE;
-      layer->layerinfo = (void *) malloc(sizeof(graticuleObj));
-      MS_CHECK_ALLOC(layer->layerinfo, sizeof(graticuleObj), -1);
+        break;
+      case(FOOTER):
+        if(getString(&layer->footer) == MS_FAILURE) return(-1); /* getString() cleans up previously allocated string */
+        if(msyysource == MS_URL_TOKENS) {
+          if(msValidateParameter(layer->footer, msLookupHashTable(&(layer->validation), "footer"), msLookupHashTable(&(map->web.validation), "footer"), map->templatepattern, NULL) != MS_SUCCESS) {
+            msSetError(MS_MISCERR, "URL-based FOOTER configuration failed pattern validation." , "loadLayer()");
+            msFree(layer->footer);
+            layer->footer=NULL;
+            return(-1);
+          }
+        }
+        break;
+      case(GRID):
+        layer->connectiontype = MS_GRATICULE;
+        layer->layerinfo = (void *) malloc(sizeof(graticuleObj));
+        MS_CHECK_ALLOC(layer->layerinfo, sizeof(graticuleObj), -1);
 
-      initGrid((graticuleObj *) layer->layerinfo);
-      loadGrid(layer);
-      break;
-    case(GROUP):
-      if(getString(&layer->group) == MS_FAILURE) return(-1); /* getString() cleans up previously allocated string */
-      if(msyysource == MS_URL_TOKENS) {
-        if(msValidateParameter(layer->group, msLookupHashTable(&(layer->validation), "group"), msLookupHashTable(&(map->web.validation), "group"), NULL, NULL) != MS_SUCCESS) {
-          msSetError(MS_MISCERR, "URL-based GROUP configuration failed pattern validation." , "loadLayer()");
-          msFree(layer->group); layer->group=NULL;
-          return(-1);
+        initGrid((graticuleObj *) layer->layerinfo);
+        loadGrid(layer);
+        break;
+      case(GROUP):
+        if(getString(&layer->group) == MS_FAILURE) return(-1); /* getString() cleans up previously allocated string */
+        if(msyysource == MS_URL_TOKENS) {
+          if(msValidateParameter(layer->group, msLookupHashTable(&(layer->validation), "group"), msLookupHashTable(&(map->web.validation), "group"), NULL, NULL) != MS_SUCCESS) {
+            msSetError(MS_MISCERR, "URL-based GROUP configuration failed pattern validation." , "loadLayer()");
+            msFree(layer->group);
+            layer->group=NULL;
+            return(-1);
+          }
         }
-      }
-      break;
-    case(HEADER):
-      if(getString(&layer->header) == MS_FAILURE) return(-1); /* getString() cleans up previously allocated string */
-      if(msyysource == MS_URL_TOKENS) {
-        if(msValidateParameter(layer->header, msLookupHashTable(&(layer->validation), "header"), msLookupHashTable(&(map->web.validation), "header"), map->templatepattern, NULL) != MS_SUCCESS) {
-          msSetError(MS_MISCERR, "URL-based HEADER configuration failed pattern validation." , "loadLayer()");
-          msFree(layer->header); layer->header=NULL;
+        break;
+      case(HEADER):
+        if(getString(&layer->header) == MS_FAILURE) return(-1); /* getString() cleans up previously allocated string */
+        if(msyysource == MS_URL_TOKENS) {
+          if(msValidateParameter(layer->header, msLookupHashTable(&(layer->validation), "header"), msLookupHashTable(&(map->web.validation), "header"), map->templatepattern, NULL) != MS_SUCCESS) {
+            msSetError(MS_MISCERR, "URL-based HEADER configuration failed pattern validation." , "loadLayer()");
+            msFree(layer->header);
+            layer->header=NULL;
+            return(-1);
+          }
+        }
+        break;
+      case(JOIN):
+        if(layer->numjoins == MS_MAXJOINS) { /* no room */
+          msSetError(MS_IDENTERR, "Maximum number of joins reached.", "loadLayer()");
           return(-1);
         }
-      }
-      break;
-    case(JOIN):
-      if(layer->numjoins == MS_MAXJOINS) { /* no room */
-	msSetError(MS_IDENTERR, "Maximum number of joins reached.", "loadLayer()");
-	return(-1);
-      }
 
-      if(loadJoin(&(layer->joins[layer->numjoins])) == -1) return(-1);
-      layer->numjoins++;
-      break;
-    case(LABELCACHE):
-      if((layer->labelcache = getSymbol(2, MS_ON, MS_OFF)) == -1) return(-1);
-      break;
-    case(LABELITEM):
-      if(getString(&layer->labelitem) == MS_FAILURE) return(-1); /* getString() cleans up previously allocated string */
-      if(msyysource == MS_URL_TOKENS) {
-        if(msValidateParameter(layer->labelitem, msLookupHashTable(&(layer->validation), "labelitem"), msLookupHashTable(&(map->web.validation), "labelitem"), NULL, NULL) != MS_SUCCESS) {
-          msSetError(MS_MISCERR, "URL-based LABELITEM configuration failed pattern validation." , "loadLayer()");
-          msFree(layer->labelitem); layer->labelitem=NULL;
-          return(-1);
+        if(loadJoin(&(layer->joins[layer->numjoins])) == -1) return(-1);
+        layer->numjoins++;
+        break;
+      case(LABELCACHE):
+        if((layer->labelcache = getSymbol(2, MS_ON, MS_OFF)) == -1) return(-1);
+        break;
+      case(LABELITEM):
+        if(getString(&layer->labelitem) == MS_FAILURE) return(-1); /* getString() cleans up previously allocated string */
+        if(msyysource == MS_URL_TOKENS) {
+          if(msValidateParameter(layer->labelitem, msLookupHashTable(&(layer->validation), "labelitem"), msLookupHashTable(&(map->web.validation), "labelitem"), NULL, NULL) != MS_SUCCESS) {
+            msSetError(MS_MISCERR, "URL-based LABELITEM configuration failed pattern validation." , "loadLayer()");
+            msFree(layer->labelitem);
+            layer->labelitem=NULL;
+            return(-1);
+          }
         }
-      }
-      break;
-    case(LABELMAXSCALE):
-    case(LABELMAXSCALEDENOM):
-      if(getDouble(&(layer->labelmaxscaledenom)) == -1) return(-1);
-      break;
-    case(LABELMINSCALE):
-    case(LABELMINSCALEDENOM):
-      if(getDouble(&(layer->labelminscaledenom)) == -1) return(-1);
-      break;    
-    case(LABELREQUIRES):
-      if(getString(&layer->labelrequires) == MS_FAILURE) return(-1); /* getString() cleans up previously allocated string */
-      if(msyysource == MS_URL_TOKENS) {
-        if(msValidateParameter(layer->labelrequires, msLookupHashTable(&(layer->validation), "labelrequires"), msLookupHashTable(&(map->web.validation), "labelrequires"), NULL, NULL) != MS_SUCCESS) {
-          msSetError(MS_MISCERR, "URL-based LABELREQUIRES configuration failed pattern validation." , "loadLayer()");
-          msFree(layer->labelrequires); layer->labelrequires=NULL;
-          return(-1);
+        break;
+      case(LABELMAXSCALE):
+      case(LABELMAXSCALEDENOM):
+        if(getDouble(&(layer->labelmaxscaledenom)) == -1) return(-1);
+        break;
+      case(LABELMINSCALE):
+      case(LABELMINSCALEDENOM):
+        if(getDouble(&(layer->labelminscaledenom)) == -1) return(-1);
+        break;
+      case(LABELREQUIRES):
+        if(getString(&layer->labelrequires) == MS_FAILURE) return(-1); /* getString() cleans up previously allocated string */
+        if(msyysource == MS_URL_TOKENS) {
+          if(msValidateParameter(layer->labelrequires, msLookupHashTable(&(layer->validation), "labelrequires"), msLookupHashTable(&(map->web.validation), "labelrequires"), NULL, NULL) != MS_SUCCESS) {
+            msSetError(MS_MISCERR, "URL-based LABELREQUIRES configuration failed pattern validation." , "loadLayer()");
+            msFree(layer->labelrequires);
+            layer->labelrequires=NULL;
+            return(-1);
+          }
         }
-      }
-      break;
-    case(LAYER):
-      break; /* for string loads */
-    case(MAXFEATURES):
-      if(getInteger(&(layer->maxfeatures)) == -1) return(-1);
-      break;
-    case(MAXSCALE):
-    case(MAXSCALEDENOM):
-      if(getDouble(&(layer->maxscaledenom)) == -1) return(-1);
-      break;
-    case(MAXGEOWIDTH):
-      if(getDouble(&(layer->maxgeowidth)) == -1) return(-1);
-      break;
-    case(METADATA):
-      if(loadHashTable(&(layer->metadata)) != MS_SUCCESS) return(-1);
-      break;
-    case(MINSCALE):
-    case(MINSCALEDENOM):
-      if(getDouble(&(layer->minscaledenom)) == -1) return(-1);
-      break;
-    case(MINGEOWIDTH):
-      if(getDouble(&(layer->mingeowidth)) == -1) return(-1);
-      break;
-    case(MINFEATURESIZE):
-      if(getInteger(&(layer->minfeaturesize)) == -1) return(-1);
-      break;
-    case(NAME):
-      if(getString(&layer->name) == MS_FAILURE) return(-1);
-      break;
-    case(OFFSITE):
-      if(loadColor(&(layer->offsite), NULL) != MS_SUCCESS) return(-1);
-      break;
-    case(OPACITY):
-    case(TRANSPARENCY): /* keyword supported for mapfile backwards compatability */
-      if (getIntegerOrSymbol(&(layer->opacity), 1, MS_GD_ALPHA) == -1)
-        return(-1);
-      break;
-    case(MS_PLUGIN): 
-    {
+        break;
+      case(LAYER):
+        break; /* for string loads */
+      case(MASK):
+        if(getString(&layer->mask) == MS_FAILURE) return(-1); /* getString() cleans up previously allocated string */
+        if(msyysource == MS_URL_TOKENS) {
+          if(msValidateParameter(layer->mask, msLookupHashTable(&(layer->validation), "mask"), msLookupHashTable(&(map->web.validation), "mask"), NULL, NULL) != MS_SUCCESS) {
+            msSetError(MS_MISCERR, "URL-based MASK configuration failed pattern validation." , "loadLayer()");
+            msFree(layer->mask);
+            layer->mask=NULL;
+            return(-1);
+          }
+        }
+        break;
+      case(MAXFEATURES):
+        if(getInteger(&(layer->maxfeatures)) == -1) return(-1);
+        break;
+      case(MAXSCALE):
+      case(MAXSCALEDENOM):
+        if(getDouble(&(layer->maxscaledenom)) == -1) return(-1);
+        break;
+      case(MAXGEOWIDTH):
+        if(getDouble(&(layer->maxgeowidth)) == -1) return(-1);
+        break;
+      case(METADATA):
+        if(loadHashTable(&(layer->metadata)) != MS_SUCCESS) return(-1);
+        break;
+      case(MINSCALE):
+      case(MINSCALEDENOM):
+        if(getDouble(&(layer->minscaledenom)) == -1) return(-1);
+        break;
+      case(MINGEOWIDTH):
+        if(getDouble(&(layer->mingeowidth)) == -1) return(-1);
+        break;
+      case(MINFEATURESIZE):
+        if(getInteger(&(layer->minfeaturesize)) == -1) return(-1);
+        break;
+      case(NAME):
+        if(getString(&layer->name) == MS_FAILURE) return(-1);
+        break;
+      case(OFFSITE):
+        if(loadColor(&(layer->offsite), NULL) != MS_SUCCESS) return(-1);
+        break;
+      case(OPACITY):
+      case(TRANSPARENCY): /* keyword supported for mapfile backwards compatability */
+        if (getIntegerOrSymbol(&(layer->opacity), 1, MS_GD_ALPHA) == -1)
+          return(-1);
+        break;
+      case(MS_PLUGIN): {
         int rv;
         if(getString(&layer->plugin_library_original) == MS_FAILURE) return(-1);
-        rv = msBuildPluginLibraryPath(&layer->plugin_library, 
-                                      layer->plugin_library_original, 
+        rv = msBuildPluginLibraryPath(&layer->plugin_library,
+                                      layer->plugin_library_original,
                                       map);
         if (rv == MS_FAILURE) return(-1);
-    }
-    break;
-    case(PROCESSING):
-    {
-      /* NOTE: processing array maintained as size+1 with NULL terminator.
-               This ensure that CSL (GDAL string list) functions can be
-               used on the list for easy processing. */
-      char *value=NULL;
-      if(getString(&value) == MS_FAILURE) return(-1);
-      if(msyysource == MS_URL_TOKENS) {
-        if(msValidateParameter(value, msLookupHashTable(&(layer->validation), "processing"), msLookupHashTable(&(map->web.validation), "processing"), NULL, NULL) != MS_SUCCESS) {
-          msSetError(MS_MISCERR, "URL-based PROCESSING configuration failed pattern validation." , "loadLayer()");
-          free(value); value=NULL;
-          return(-1);
-        }
       }
-      msLayerAddProcessing( layer, value );
-      free(value); value=NULL;
-    }
-    break;
-    case(POSTLABELCACHE):
-      if((layer->postlabelcache = getSymbol(2, MS_TRUE, MS_FALSE)) == -1) return(-1);
-      if(layer->postlabelcache)
-	layer->labelcache = MS_OFF;
-      break;
-    case(PROJECTION):
-      if(loadProjection(&(layer->projection)) == -1) return(-1);
-      layer->project = MS_TRUE;
       break;
-    case(REQUIRES):
-      if(getString(&layer->requires) == MS_FAILURE) return(-1); /* getString() cleans up previously allocated string */
-      if(msyysource == MS_URL_TOKENS) {
-        if(msValidateParameter(layer->requires, msLookupHashTable(&(layer->validation), "requires"), msLookupHashTable(&(map->web.validation), "requires"), NULL, NULL) != MS_SUCCESS) {
-          msSetError(MS_MISCERR, "URL-based REQUIRES configuration failed pattern validation." , "loadLayer()");
-          msFree(layer->requires); layer->requires=NULL;
-          return(-1);
+      case(PROCESSING): {
+        /* NOTE: processing array maintained as size+1 with NULL terminator.
+                 This ensure that CSL (GDAL string list) functions can be
+                 used on the list for easy processing. */
+        char *value=NULL;
+        if(getString(&value) == MS_FAILURE) return(-1);
+        if(msyysource == MS_URL_TOKENS) {
+          if(msValidateParameter(value, msLookupHashTable(&(layer->validation), "processing"), msLookupHashTable(&(map->web.validation), "processing"), NULL, NULL) != MS_SUCCESS) {
+            msSetError(MS_MISCERR, "URL-based PROCESSING configuration failed pattern validation." , "loadLayer()");
+            free(value);
+            value=NULL;
+            return(-1);
+          }
         }
+        msLayerAddProcessing( layer, value );
+        free(value);
+        value=NULL;
       }
       break;
-    case(SIZEUNITS):
-      if((layer->sizeunits = getSymbol(8, MS_INCHES,MS_FEET,MS_MILES,MS_METERS,MS_KILOMETERS,MS_NAUTICALMILES,MS_DD,MS_PIXELS)) == -1) return(-1);
-      break;
-    case(STATUS):
-      if((layer->status = getSymbol(3, MS_ON,MS_OFF,MS_DEFAULT)) == -1) return(-1);
-      break;
-    case(STYLEITEM):
-      if(getString(&layer->styleitem) == MS_FAILURE) return(-1); /* getString() cleans up previously allocated string */
-      if(msyysource == MS_URL_TOKENS) {
-        if(msValidateParameter(layer->styleitem, msLookupHashTable(&(layer->validation), "styleitem"), msLookupHashTable(&(map->web.validation), "styleitem"), NULL, NULL) != MS_SUCCESS) {
-          msSetError(MS_MISCERR, "URL-based STYLEITEM configuration failed pattern validation." , "loadLayer()");
-          msFree(layer->styleitem); layer->styleitem=NULL;
-          return(-1);
+      case(POSTLABELCACHE):
+        if((layer->postlabelcache = getSymbol(2, MS_TRUE, MS_FALSE)) == -1) return(-1);
+        if(layer->postlabelcache)
+          layer->labelcache = MS_OFF;
+        break;
+      case(PROJECTION):
+        if(loadProjection(&(layer->projection)) == -1) return(-1);
+        layer->project = MS_TRUE;
+        break;
+      case(REQUIRES):
+        if(getString(&layer->requires) == MS_FAILURE) return(-1); /* getString() cleans up previously allocated string */
+        if(msyysource == MS_URL_TOKENS) {
+          if(msValidateParameter(layer->requires, msLookupHashTable(&(layer->validation), "requires"), msLookupHashTable(&(map->web.validation), "requires"), NULL, NULL) != MS_SUCCESS) {
+            msSetError(MS_MISCERR, "URL-based REQUIRES configuration failed pattern validation." , "loadLayer()");
+            msFree(layer->requires);
+            layer->requires=NULL;
+            return(-1);
+          }
         }
-      }
-      break;
-    case(SYMBOLSCALE):
-    case(SYMBOLSCALEDENOM):
-      if(getDouble(&(layer->symbolscaledenom)) == -1) return(-1);
-      break;
-    case(TEMPLATE):
-      if(getString(&layer->template) == MS_FAILURE) return(-1); /* getString() cleans up previously allocated string */
-      if(msyysource == MS_URL_TOKENS) {
-        if(msValidateParameter(layer->template, msLookupHashTable(&(layer->validation), "template"), msLookupHashTable(&(map->web.validation), "template"), map->templatepattern, NULL) != MS_SUCCESS) {
-          msSetError(MS_MISCERR, "URL-based TEMPLATE configuration failed pattern validation." , "loadLayer()");
-          msFree(layer->template); layer->template=NULL;
-          return(-1);
+        break;
+      case(SIZEUNITS):
+        if((layer->sizeunits = getSymbol(8, MS_INCHES,MS_FEET,MS_MILES,MS_METERS,MS_KILOMETERS,MS_NAUTICALMILES,MS_DD,MS_PIXELS)) == -1) return(-1);
+        break;
+      case(STATUS):
+        if((layer->status = getSymbol(3, MS_ON,MS_OFF,MS_DEFAULT)) == -1) return(-1);
+        break;
+      case(STYLEITEM):
+        if(getString(&layer->styleitem) == MS_FAILURE) return(-1); /* getString() cleans up previously allocated string */
+        if(msyysource == MS_URL_TOKENS) {
+          if(msValidateParameter(layer->styleitem, msLookupHashTable(&(layer->validation), "styleitem"), msLookupHashTable(&(map->web.validation), "styleitem"), NULL, NULL) != MS_SUCCESS) {
+            msSetError(MS_MISCERR, "URL-based STYLEITEM configuration failed pattern validation." , "loadLayer()");
+            msFree(layer->styleitem);
+            layer->styleitem=NULL;
+            return(-1);
+          }
+        }
+        break;
+      case(SYMBOLSCALE):
+      case(SYMBOLSCALEDENOM):
+        if(getDouble(&(layer->symbolscaledenom)) == -1) return(-1);
+        break;
+      case(TEMPLATE):
+        if(getString(&layer->template) == MS_FAILURE) return(-1); /* getString() cleans up previously allocated string */
+        if(msyysource == MS_URL_TOKENS) {
+          if(msValidateParameter(layer->template, msLookupHashTable(&(layer->validation), "template"), msLookupHashTable(&(map->web.validation), "template"), map->templatepattern, NULL) != MS_SUCCESS) {
+            msSetError(MS_MISCERR, "URL-based TEMPLATE configuration failed pattern validation." , "loadLayer()");
+            msFree(layer->template);
+            layer->template=NULL;
+            return(-1);
+          }
+        }
+        break;
+      case(TILEINDEX):
+        if(getString(&layer->tileindex) == MS_FAILURE) return(-1); /* getString() cleans up previously allocated string */
+        if(msyysource == MS_URL_TOKENS) {
+          if(msValidateParameter(layer->tileindex, msLookupHashTable(&(layer->validation), "tileindex"), msLookupHashTable(&(map->web.validation), "tileindex"), NULL, NULL) != MS_SUCCESS) {
+            msSetError(MS_MISCERR, "URL-based TILEINDEX configuration failed pattern validation." , "loadLayer()");
+            msFree(layer->tileindex);
+            layer->tileindex=NULL;
+            return(-1);
+          }
         }
-      }
-      break;
-    case(TILEINDEX):
-      if(getString(&layer->tileindex) == MS_FAILURE) return(-1); /* getString() cleans up previously allocated string */
-      if(msyysource == MS_URL_TOKENS) {
-        if(msValidateParameter(layer->tileindex, msLookupHashTable(&(layer->validation), "tileindex"), msLookupHashTable(&(map->web.validation), "tileindex"), NULL, NULL) != MS_SUCCESS) {
-          msSetError(MS_MISCERR, "URL-based TILEINDEX configuration failed pattern validation." , "loadLayer()");
-          msFree(layer->tileindex); layer->tileindex=NULL;
-          return(-1);
+        break;
+      case(TILEITEM):
+        if(getString(&layer->tileitem) == MS_FAILURE) return(-1); /* getString() cleans up previously allocated string */
+        if(msyysource == MS_URL_TOKENS) {
+          if(msValidateParameter(layer->tileitem, msLookupHashTable(&(layer->validation), "tileitem"), msLookupHashTable(&(map->web.validation), "tileitem"), NULL, NULL) != MS_SUCCESS) {
+            msSetError(MS_MISCERR, "URL-based TILEITEM configuration failed pattern validation." , "loadLayer()");
+            msFree(layer->tileitem);
+            layer->tileitem=NULL;
+            return(-1);
+          }
         }
-      }
-      break;
-    case(TILEITEM):
-      if(getString(&layer->tileitem) == MS_FAILURE) return(-1); /* getString() cleans up previously allocated string */
-      if(msyysource == MS_URL_TOKENS) {
-        if(msValidateParameter(layer->tileitem, msLookupHashTable(&(layer->validation), "tileitem"), msLookupHashTable(&(map->web.validation), "tileitem"), NULL, NULL) != MS_SUCCESS) {
-          msSetError(MS_MISCERR, "URL-based TILEITEM configuration failed pattern validation." , "loadLayer()");
-          msFree(layer->tileitem); layer->tileitem=NULL;
+        break;
+      case(TOLERANCE):
+        if(getDouble(&(layer->tolerance)) == -1) return(-1);
+        break;
+      case(TOLERANCEUNITS):
+        if((layer->toleranceunits = getSymbol(8, MS_INCHES,MS_FEET,MS_MILES,MS_METERS,MS_KILOMETERS,MS_NAUTICALMILES,MS_DD,MS_PIXELS)) == -1) return(-1);
+        break;
+      case(TRANSFORM):
+        if((layer->transform = getSymbol(11, MS_TRUE,MS_FALSE, MS_UL,MS_UC,MS_UR,MS_CL,MS_CC,MS_CR,MS_LL,MS_LC,MS_LR)) == -1) return(-1);
+        break;
+      case(TYPE):
+        if((layer->type = getSymbol(9, MS_LAYER_POINT,MS_LAYER_LINE,MS_LAYER_RASTER,MS_LAYER_POLYGON,MS_LAYER_ANNOTATION,MS_LAYER_QUERY,MS_LAYER_CIRCLE,MS_LAYER_CHART,TILEINDEX)) == -1) return(-1);
+        if(layer->type == TILEINDEX) layer->type = MS_LAYER_TILEINDEX; /* TILEINDEX is also a parameter */
+        break;
+      case(UNITS):
+        if((layer->units = getSymbol(9, MS_INCHES,MS_FEET,MS_MILES,MS_METERS,MS_KILOMETERS,MS_NAUTICALMILES,MS_DD,MS_PIXELS,MS_PERCENTAGES)) == -1) return(-1);
+        break;
+      case(VALIDATION):
+        if(loadHashTable(&(layer->validation)) != MS_SUCCESS) return(-1);
+        break;
+      default:
+        if(strlen(msyystring_buffer) > 0) {
+          msSetError(MS_IDENTERR, "Parsing error near (%s):(line %d)", "loadLayer()", msyystring_buffer, msyylineno);
           return(-1);
+        } else {
+          return(0); /* end of a string, not an error */
         }
-      }
-      break;
-    case(TOLERANCE):
-      if(getDouble(&(layer->tolerance)) == -1) return(-1);
-      break;
-    case(TOLERANCEUNITS):
-      if((layer->toleranceunits = getSymbol(8, MS_INCHES,MS_FEET,MS_MILES,MS_METERS,MS_KILOMETERS,MS_NAUTICALMILES,MS_DD,MS_PIXELS)) == -1) return(-1);
-      break;
-    case(TRANSFORM):
-      if((layer->transform = getSymbol(11, MS_TRUE,MS_FALSE, MS_UL,MS_UC,MS_UR,MS_CL,MS_CC,MS_CR,MS_LL,MS_LC,MS_LR)) == -1) return(-1);
-      break;
-    case(TYPE):
-      if((layer->type = getSymbol(9, MS_LAYER_POINT,MS_LAYER_LINE,MS_LAYER_RASTER,MS_LAYER_POLYGON,MS_LAYER_ANNOTATION,MS_LAYER_QUERY,MS_LAYER_CIRCLE,MS_LAYER_CHART,TILEINDEX)) == -1) return(-1);
-      if(layer->type == TILEINDEX) layer->type = MS_LAYER_TILEINDEX; /* TILEINDEX is also a parameter */
-      break;    
-    case(UNITS):
-      if((layer->units = getSymbol(9, MS_INCHES,MS_FEET,MS_MILES,MS_METERS,MS_KILOMETERS,MS_NAUTICALMILES,MS_DD,MS_PIXELS,MS_PERCENTAGES)) == -1) return(-1);
-      break;
-    case(VALIDATION):
-      if(loadHashTable(&(layer->validation)) != MS_SUCCESS) return(-1);
-      break;
-    default:
-      if(strlen(msyystring_buffer) > 0) {
-        msSetError(MS_IDENTERR, "Parsing error near (%s):(line %d)", "loadLayer()", msyystring_buffer, msyylineno);      
-        return(-1);
-      } else {
-        return(0); /* end of a string, not an error */
-      }
     }
   } /* next token */
 }
 
 int msUpdateLayerFromString(layerObj *layer, char *string, int url_string)
 {
-  int j, k;
+  int i;
 
   if(!layer || !string) return MS_FAILURE;
 
@@ -3950,28 +4321,8 @@ int msUpdateLayerFromString(layerObj *layer, char *string, int url_string)
   msyylex_destroy();
 
   /* step through classes to resolve symbol names */
-  for(j=0; j<layer->numclasses; j++) {
-
-      /* class styles */
-      for(k=0; k<layer->class[j]->numstyles; k++) {
-          if(layer->class[j]->styles[k]->symbolname) {
-              if((layer->class[j]->styles[k]->symbol =  msGetSymbolIndex(&(layer->map->symbolset), layer->class[j]->styles[k]->symbolname, MS_TRUE)) == -1) {
-                  msSetError(MS_MISCERR, "Undefined symbol \"%s\" in class %d, style %d of layer %s.", "msUpdateLayerFromString()", layer->class[j]->styles[k]->symbolname, j, k, layer->name);
-                  return MS_FAILURE;
-              }
-          }
-      }
-
-      /* label styles */
-      for(k=0; k<layer->class[j]->label.numstyles; k++) {
-          if(layer->class[j]->label.styles[k]->symbolname) {
-              if((layer->class[j]->label.styles[k]->symbol =  msGetSymbolIndex(&(layer->map->symbolset), layer->class[j]->label.styles[k]->symbolname, MS_TRUE)) == -1) {
-                  msSetError(MS_MISCERR, "Undefined symbol \"%s\" in class %d, label style %d of layer %s.", 
-                             "msUpdateLayerFromString()", layer->class[j]->label.styles[k]->symbolname, j, k, layer->name);
-                  return MS_FAILURE;
-              }
-          }
-      }          
+  for(i=0; i<layer->numclasses; i++) {
+    if(classResolveSymbolNames(layer->class[i]) != MS_SUCCESS) return MS_FAILURE;
   }
 
   return MS_SUCCESS;
@@ -3987,15 +4338,15 @@ static void writeLayer(FILE *stream, int indent, layerObj *layer)
 
   indent++;
   writeBlockBegin(stream, indent, "LAYER");
-  // bindvals
+  /* bindvals */
   /* class - see below */
   writeString(stream, indent, "CLASSGROUP", NULL, layer->classgroup);
   writeString(stream, indent, "CLASSITEM", NULL, layer->classitem);
   writeCluster(stream, indent, &(layer->cluster));
   writeString(stream, indent, "CONNECTION", NULL, layer->connection);
-  writeKeyword(stream, indent, "CONNECTIONTYPE", layer->connectiontype, 9, MS_SDE, "SDE", MS_OGR, "OGR", MS_POSTGIS, "POSTGIS", MS_WMS, "WMS", MS_ORACLESPATIAL, "ORACLESPATIAL", MS_WFS, "WFS", MS_GRATICULE, "GRATICULE", MS_PLUGIN, "PLUGIN", MS_UNION, "UNION");
+  writeKeyword(stream, indent, "CONNECTIONTYPE", layer->connectiontype, 10, MS_SDE, "SDE", MS_OGR, "OGR", MS_POSTGIS, "POSTGIS", MS_WMS, "WMS", MS_ORACLESPATIAL, "ORACLESPATIAL", MS_WFS, "WFS", MS_GRATICULE, "GRATICULE", MS_PLUGIN, "PLUGIN", MS_UNION, "UNION", MS_UVRASTER, "UVRASTER");
   writeString(stream, indent, "DATA", NULL, layer->data);
-  writeNumber(stream, indent, "DEBUG", 0, layer->debug); /* is this right? see loadLayer() */ 
+  writeNumber(stream, indent, "DEBUG", 0, layer->debug); /* is this right? see loadLayer() */
   writeExtent(stream, indent, "EXTENT", layer->extent);
   writeExpression(stream, indent, "FILTER", &(layer->filter));
   writeString(stream, indent, "FILTERITEM", NULL, layer->filteritem);
@@ -4011,6 +4362,7 @@ static void writeLayer(FILE *stream, int indent, layerObj *layer)
   writeNumber(stream, indent, "MAXFEATURES", -1, layer->maxfeatures);
   writeNumber(stream, indent, "MAXGEOWIDTH", -1, layer->maxgeowidth);
   writeNumber(stream, indent, "MAXSCALEDENOM", -1, layer->maxscaledenom);
+  writeString(stream, indent, "MASK", NULL, layer->mask);
   writeHashTable(stream, indent, "METADATA", &(layer->metadata));
   writeNumber(stream, indent, "MINGEOWIDTH", -1, layer->mingeowidth);
   writeNumber(stream, indent, "MINSCALEDENOM", -1, layer->minscaledenom);
@@ -4033,7 +4385,7 @@ static void writeLayer(FILE *stream, int indent, layerObj *layer)
   writeNumber(stream, indent, "TOLERANCE", -1, layer->tolerance);
   writeKeyword(stream, indent, "TOLERANCEUNITS", layer->toleranceunits, 7, MS_INCHES, "INCHES", MS_FEET ,"FEET", MS_MILES, "MILES", MS_METERS, "METERS", MS_KILOMETERS, "KILOMETERS", MS_NAUTICALMILES, "NAUTICALMILES", MS_DD, "DD");
   writeKeyword(stream, indent, "TRANSFORM", layer->transform, 10, MS_FALSE, "FALSE", MS_UL, "UL", MS_UC, "UC", MS_UR, "UR", MS_CL, "CL", MS_CC, "CC", MS_CR, "CR", MS_LL, "LL", MS_LC, "LC", MS_LR, "LR");
-  writeNumberOrKeyword(stream, indent, "OPACITY", 100, layer->opacity, (int)layer->opacity, 1, MS_GD_ALPHA, "ALPHA"); 
+  writeNumberOrKeyword(stream, indent, "OPACITY", 100, layer->opacity, (int)layer->opacity, 1, MS_GD_ALPHA, "ALPHA");
   writeKeyword(stream, indent, "TYPE", layer->type, 9, MS_LAYER_POINT, "POINT", MS_LAYER_LINE, "LINE", MS_LAYER_POLYGON, "POLYGON", MS_LAYER_RASTER, "RASTER", MS_LAYER_ANNOTATION, "ANNOTATION", MS_LAYER_QUERY, "QUERY", MS_LAYER_CIRCLE, "CIRCLE", MS_LAYER_TILEINDEX, "TILEINDEX", MS_LAYER_CHART, "CHART");
   writeKeyword(stream, indent, "UNITS", layer->units, 9, MS_INCHES, "INCHES", MS_FEET ,"FEET", MS_MILES, "MILES", MS_METERS, "METERS", MS_KILOMETERS, "KILOMETERS", MS_NAUTICALMILES, "NAUTICALMILES", MS_DD, "DD", MS_PIXELS, "PIXELS", MS_PERCENTAGES, "PERCENTATGES");
   writeHashTable(stream, indent, "VALIDATION", &(layer->validation));
@@ -4065,7 +4417,7 @@ void initReferenceMap(referenceMapObj *ref)
   ref->extent.minx = ref->extent.miny = ref->extent.maxx = ref->extent.maxy = -1.0;
   ref->image = NULL;
   MS_INIT_COLOR(ref->color, 255, 0, 0, 255);
-  MS_INIT_COLOR(ref->outlinecolor, 0, 0, 0, 255);  
+  MS_INIT_COLOR(ref->outlinecolor, 0, 0, 0, 255);
   ref->status = MS_OFF;
   ref->marker = 0;
   ref->markername = NULL;
@@ -4089,77 +4441,76 @@ int loadReferenceMap(referenceMapObj *ref, mapObj *map)
 
   for(;;) {
     switch(msyylex()) {
-    case(EOF):
-      msSetError(MS_EOFERR, NULL, "loadReferenceMap()");
-      return(-1);
-    case(END):
-      if(!ref->image) {
-	msSetError(MS_MISCERR, "No image defined for the reference map.", "loadReferenceMap()");
-	return(-1);
-      }
-      if(ref->width == 0 || ref->height == 0) {
-	msSetError(MS_MISCERR, "No image size defined for the reference map.", "loadReferenceMap()");
-	return(-1);
-      }
-      return(0);
-      break;
-    case(COLOR):
-      if(loadColor(&(ref->color), NULL) != MS_SUCCESS) return(-1);
-      break;
-    case(EXTENT):
-      if(getDouble(&(ref->extent.minx)) == -1) return(-1);
-      if(getDouble(&(ref->extent.miny)) == -1) return(-1);
-      if(getDouble(&(ref->extent.maxx)) == -1) return(-1);
-      if(getDouble(&(ref->extent.maxy)) == -1) return(-1);
-      if (!MS_VALID_EXTENT(ref->extent)) {
-      	msSetError(MS_MISCERR, "Given reference extent is invalid. Check that it " \
-        "is in the form: minx, miny, maxx, maxy", "loadReferenceMap()"); 
+      case(EOF):
+        msSetError(MS_EOFERR, NULL, "loadReferenceMap()");
         return(-1);
-      	}
-      break;  
-    case(IMAGE):
-      if(getString(&ref->image) == MS_FAILURE) return(-1);
-      break;
-    case(OUTLINECOLOR):
-      if(loadColor(&(ref->outlinecolor), NULL) != MS_SUCCESS) return(-1);
-      break;
-    case(SIZE):
-      if(getInteger(&(ref->width)) == -1) return(-1);
-      if(getInteger(&(ref->height)) == -1) return(-1);
-      break;          
-    case(STATUS):
-      if((ref->status = getSymbol(2, MS_ON,MS_OFF)) == -1) return(-1);
-      break;
-    case(MARKER):
-      if((state = getSymbol(2, MS_NUMBER,MS_STRING)) == -1) return(-1);
+      case(END):
+        if(!ref->image) {
+          msSetError(MS_MISCERR, "No image defined for the reference map.", "loadReferenceMap()");
+          return(-1);
+        }
+        if(ref->width == 0 || ref->height == 0) {
+          msSetError(MS_MISCERR, "No image size defined for the reference map.", "loadReferenceMap()");
+          return(-1);
+        }
+        return(0);
+        break;
+      case(COLOR):
+        if(loadColor(&(ref->color), NULL) != MS_SUCCESS) return(-1);
+        break;
+      case(EXTENT):
+        if(getDouble(&(ref->extent.minx)) == -1) return(-1);
+        if(getDouble(&(ref->extent.miny)) == -1) return(-1);
+        if(getDouble(&(ref->extent.maxx)) == -1) return(-1);
+        if(getDouble(&(ref->extent.maxy)) == -1) return(-1);
+        if (!MS_VALID_EXTENT(ref->extent)) {
+          msSetError(MS_MISCERR, "Given reference extent is invalid. Check that it " \
+                     "is in the form: minx, miny, maxx, maxy", "loadReferenceMap()");
+          return(-1);
+        }
+        break;
+      case(IMAGE):
+        if(getString(&ref->image) == MS_FAILURE) return(-1);
+        break;
+      case(OUTLINECOLOR):
+        if(loadColor(&(ref->outlinecolor), NULL) != MS_SUCCESS) return(-1);
+        break;
+      case(SIZE):
+        if(getInteger(&(ref->width)) == -1) return(-1);
+        if(getInteger(&(ref->height)) == -1) return(-1);
+        break;
+      case(STATUS):
+        if((ref->status = getSymbol(2, MS_ON,MS_OFF)) == -1) return(-1);
+        break;
+      case(MARKER):
+        if((state = getSymbol(2, MS_NUMBER,MS_STRING)) == -1) return(-1);
 
-      if(state == MS_NUMBER)
-	ref->marker = (int) msyynumber;
-      else
-      {
-        if (ref->markername != NULL)
-          msFree(ref->markername);
-	ref->markername = msStrdup(msyystring_buffer);
-      }
-      break;
-    case(MARKERSIZE):
-      if(getInteger(&(ref->markersize)) == -1) return(-1);
-      break;
-    case(MINBOXSIZE):
-      if(getInteger(&(ref->minboxsize)) == -1) return(-1);
-      break;
-    case(MAXBOXSIZE):
-      if(getInteger(&(ref->maxboxsize)) == -1) return(-1);
-      break;
-    case(REFERENCE):
-      break; /* for string loads */
-    default:
-      if(strlen(msyystring_buffer) > 0) {
-        msSetError(MS_IDENTERR, "Parsing error near (%s):(line %d)", "loadReferenceMap()", msyystring_buffer, msyylineno);
-        return(-1);
-      } else {
-        return(0); /* end of a string, not an error */
-      }
+        if(state == MS_NUMBER)
+          ref->marker = (int) msyynumber;
+        else {
+          if (ref->markername != NULL)
+            msFree(ref->markername);
+          ref->markername = msStrdup(msyystring_buffer);
+        }
+        break;
+      case(MARKERSIZE):
+        if(getInteger(&(ref->markersize)) == -1) return(-1);
+        break;
+      case(MINBOXSIZE):
+        if(getInteger(&(ref->minboxsize)) == -1) return(-1);
+        break;
+      case(MAXBOXSIZE):
+        if(getInteger(&(ref->maxboxsize)) == -1) return(-1);
+        break;
+      case(REFERENCE):
+        break; /* for string loads */
+      default:
+        if(strlen(msyystring_buffer) > 0) {
+          msSetError(MS_IDENTERR, "Parsing error near (%s):(line %d)", "loadReferenceMap()", msyystring_buffer, msyylineno);
+          return(-1);
+        } else {
+          return(0); /* end of a string, not an error */
+        }
     }
   } /* next token */
 }
@@ -4229,90 +4580,86 @@ static int loadOutputFormat(mapObj *map)
 
   for(;;) {
     switch(msyylex()) {
-    case(EOF):
-      msSetError(MS_EOFERR, NULL, "loadOutputFormat()");      
-      return(-1);
+      case(EOF):
+        msSetError(MS_EOFERR, NULL, "loadOutputFormat()");
+        return(-1);
 
-    case(END):
-    {
+      case(END): {
         outputFormatObj *format;
 
-        if( driver == NULL )
-        {
-            msSetError(MS_MISCERR, 
-                       "OUTPUTFORMAT clause lacks DRIVER keyword near (%s):(%d)",
-                       "loadOutputFormat()",
-                       msyystring_buffer, msyylineno );
-            return -1;
+        if( driver == NULL ) {
+          msSetError(MS_MISCERR,
+                     "OUTPUTFORMAT clause lacks DRIVER keyword near (%s):(%d)",
+                     "loadOutputFormat()",
+                     msyystring_buffer, msyylineno );
+          return -1;
         }
-        
+
         format = msCreateDefaultOutputFormat( map, driver, name );
         msFree( name );
         name = NULL;
-        if( format == NULL )
-        {
-            msSetError(MS_MISCERR, 
-                       "OUTPUTFORMAT clause references driver %s, but this driver isn't configured.", 
-                       "loadOutputFormat()", driver );
-            return -1;
+        if( format == NULL ) {
+          msSetError(MS_MISCERR,
+                     "OUTPUTFORMAT clause references driver %s, but this driver isn't configured.",
+                     "loadOutputFormat()", driver );
+          return -1;
         }
         msFree( driver );
 
         if( transparent != MS_NOOVERRIDE )
-            format->transparent = transparent;
-        if( extension != NULL )
-        {
-            msFree( format->extension );
-            format->extension = extension;
+          format->transparent = transparent;
+        if( extension != NULL ) {
+          msFree( format->extension );
+          format->extension = extension;
         }
-        if( mimetype != NULL )
-        {
-            msFree( format->mimetype );
-            format->mimetype = mimetype;
+        if( mimetype != NULL ) {
+          msFree( format->mimetype );
+          format->mimetype = mimetype;
         }
-        if( imagemode != MS_NOOVERRIDE )
-        {
+        if( imagemode != MS_NOOVERRIDE ) {
+#ifndef USE_GD
+          /* don't override a GD format if GD isn't configured in */
+          if(imagemode != MS_IMAGEMODE_PC256)
+#endif
             format->imagemode = imagemode;
 
-            if( transparent == MS_NOOVERRIDE )
-            {
-                if( imagemode == MS_IMAGEMODE_RGB  )
-                    format->transparent = MS_FALSE;
-                else if( imagemode == MS_IMAGEMODE_RGBA  )
-                    format->transparent = MS_TRUE;
-            }
-            if( format->imagemode == MS_IMAGEMODE_INT16 
-                || format->imagemode == MS_IMAGEMODE_FLOAT32 
-                || format->imagemode == MS_IMAGEMODE_BYTE )
-                format->renderer = MS_RENDER_WITH_RAWDATA;
-            if( format->imagemode == MS_IMAGEMODE_PC256 )
-                format->renderer = MS_RENDER_WITH_GD;
+          if( transparent == MS_NOOVERRIDE ) {
+            if( imagemode == MS_IMAGEMODE_RGB  )
+              format->transparent = MS_FALSE;
+            else if( imagemode == MS_IMAGEMODE_RGBA  )
+              format->transparent = MS_TRUE;
+          }
+          if( format->imagemode == MS_IMAGEMODE_INT16
+              || format->imagemode == MS_IMAGEMODE_FLOAT32
+              || format->imagemode == MS_IMAGEMODE_BYTE )
+            format->renderer = MS_RENDER_WITH_RAWDATA;
+#ifdef USE_GD
+          if( format->imagemode == MS_IMAGEMODE_PC256 )
+            format->renderer = MS_RENDER_WITH_GD;
+#endif
         }
 
         format->numformatoptions = numformatoptions;
-        if( numformatoptions > 0 )
-        {
-            format->formatoptions = (char **) 
-                msSmallMalloc(sizeof(char *)*numformatoptions );
-            memcpy( format->formatoptions, formatoptions, 
-                    sizeof(char *)*numformatoptions );
+        if( numformatoptions > 0 ) {
+          format->formatoptions = (char **)
+          msSmallMalloc(sizeof(char *)*numformatoptions );
+          memcpy( format->formatoptions, formatoptions,
+                  sizeof(char *)*numformatoptions );
         }
 
         format->inmapfile = MS_TRUE;
 
-        if( !msOutputFormatValidate( format, MS_TRUE ) )
-            return -1;
+        msOutputFormatValidate( format, MS_FALSE );
         return(0);
-    }
-    case(NAME):
-      msFree( name );
-      if((name = getToken()) == NULL) return(-1);
-      break;
-    case(MIMETYPE):
-      if(getString(&mimetype) == MS_FAILURE) return(-1);
-      break;
-    case(DRIVER):
-      {
+      }
+      case(NAME):
+        msFree( name );
+        if((name = getToken()) == NULL) return(-1);
+        break;
+      case(MIMETYPE):
+        if(getString(&mimetype) == MS_FAILURE) return(-1);
+        break;
+      case(DRIVER): {
         int s;
         if((s = getSymbol(2, MS_STRING, TEMPLATE)) == -1) return -1; /* allow the template to be quoted or not in the mapfile */
         if(s == MS_STRING)
@@ -4321,53 +4668,53 @@ static int loadOutputFormat(mapObj *map)
           driver = msStrdup("TEMPLATE");
       }
       break;
-    case(EXTENSION):
-      if(getString(&extension) == MS_FAILURE) return(-1);
-      if( extension[0] == '.' )
-      {
+      case(EXTENSION):
+        if(getString(&extension) == MS_FAILURE) return(-1);
+        if( extension[0] == '.' ) {
           char *temp = msStrdup(extension+1);
           free( extension );
           extension = temp;
-      }
-      break;
-    case(FORMATOPTION):
-      if(getString(&value) == MS_FAILURE) return(-1);
-      if( numformatoptions < MAX_FORMATOPTIONS )
+        }
+        break;
+      case(FORMATOPTION):
+        if(getString(&value) == MS_FAILURE) return(-1);
+        if( numformatoptions < MAX_FORMATOPTIONS )
           formatoptions[numformatoptions++] = msStrdup(value);
-      free(value); value=NULL;
-      break;
-    case(IMAGEMODE):
-      value = getToken();
-      if( strcasecmp(value,"PC256") == 0 )
+        free(value);
+        value=NULL;
+        break;
+      case(IMAGEMODE):
+        value = getToken();
+        if( strcasecmp(value,"PC256") == 0 )
           imagemode = MS_IMAGEMODE_PC256;
-      else if( strcasecmp(value,"RGB") == 0 )
+        else if( strcasecmp(value,"RGB") == 0 )
           imagemode = MS_IMAGEMODE_RGB;
-      else if( strcasecmp(value,"RGBA") == 0)
+        else if( strcasecmp(value,"RGBA") == 0)
           imagemode = MS_IMAGEMODE_RGBA;
-      else if( strcasecmp(value,"INT16") == 0)
+        else if( strcasecmp(value,"INT16") == 0)
           imagemode = MS_IMAGEMODE_INT16;
-      else if( strcasecmp(value,"FLOAT32") == 0)
+        else if( strcasecmp(value,"FLOAT32") == 0)
           imagemode = MS_IMAGEMODE_FLOAT32;
-      else if( strcasecmp(value,"BYTE") == 0)
+        else if( strcasecmp(value,"BYTE") == 0)
           imagemode = MS_IMAGEMODE_BYTE;
-      else if( strcasecmp(value,"FEATURE") == 0)
+        else if( strcasecmp(value,"FEATURE") == 0)
           imagemode = MS_IMAGEMODE_FEATURE;
-      else
-      {
-          msSetError(MS_IDENTERR, 
-                     "Parsing error near (%s):(line %d), expected PC256, RGB, RGBA, FEATURE, BYTE, INT16, or FLOAT32 for IMAGEMODE.", "loadOutputFormat()", 
-                     msyystring_buffer, msyylineno);      
+        else {
+          msSetError(MS_IDENTERR,
+                     "Parsing error near (%s):(line %d), expected PC256, RGB, RGBA, FEATURE, BYTE, INT16, or FLOAT32 for IMAGEMODE.", "loadOutputFormat()",
+                     msyystring_buffer, msyylineno);
           return -1;
-      }
-      free(value); value=NULL;
-      break;
-    case(TRANSPARENT):
-      if((transparent = getSymbol(2, MS_ON,MS_OFF)) == -1) return(-1);
-      break;
-    default:
-      msSetError(MS_IDENTERR, "Parsing error near (%s):(line %d)", "loadOutputFormat()", 
-                 msyystring_buffer, msyylineno);      
-      return(-1);
+        }
+        free(value);
+        value=NULL;
+        break;
+      case(TRANSPARENT):
+        if((transparent = getSymbol(2, MS_ON,MS_OFF)) == -1) return(-1);
+        break;
+      default:
+        msSetError(MS_IDENTERR, "Parsing error near (%s):(line %d)", "loadOutputFormat()",
+                   msyystring_buffer, msyylineno);
+        return(-1);
     }
   } /* next token */
 }
@@ -4388,7 +4735,7 @@ static void writeOutputformatobject(FILE *stream, int indent, outputFormatObj *o
   writeString(stream, indent, "EXTENSION", NULL, outputformat->extension);
   writeKeyword(stream, indent, "IMAGEMODE", outputformat->imagemode, 7, MS_IMAGEMODE_PC256, "PC256", MS_IMAGEMODE_RGB, "RGB", MS_IMAGEMODE_RGBA, "RGBA", MS_IMAGEMODE_INT16, "INT16", MS_IMAGEMODE_FLOAT32, "FLOAT32", MS_IMAGEMODE_BYTE, "BYTE", MS_IMAGEMODE_FEATURE, "FEATURE");
   writeKeyword(stream, indent, "TRANSPARENT", outputformat->transparent, 2, MS_TRUE, "TRUE", MS_FALSE, "FALSE");
-  for (i=0; i<outputformat->numformatoptions; i++) 
+  for (i=0; i<outputformat->numformatoptions; i++)
     writeString(stream, indent, "FORMATOPTION", NULL, outputformat->formatoptions[i]);
   writeBlockEnd(stream, indent, "OUTPUTFORMAT");
   writeLineFeed(stream);
@@ -4405,17 +4752,17 @@ static void writeOutputformat(FILE *stream, int indent, mapObj *map)
 
   writeOutputformatobject(stream, indent, map->outputformat);
   for(i=0; i<map->numoutputformats; i++) {
-    if(map->outputformatlist[i]->inmapfile == MS_TRUE && strcmp(map->outputformatlist[i]->driver, map->outputformat->driver) != 0)
+    if(map->outputformatlist[i]->inmapfile == MS_TRUE && strcmp(map->outputformatlist[i]->name, map->outputformat->name) != 0)
       writeOutputformatobject(stream, indent, map->outputformatlist[i]);
   }
 }
-                              
+
 /*
 ** Initialize, load and free a legendObj structure
 */
 void initLegend(legendObj *legend)
 {
-  legend->height = legend->width = 0; 
+  legend->height = legend->width = 0;
   MS_INIT_COLOR(legend->imagecolor, 255,255,255,255); /* white */
   MS_INIT_COLOR(legend->outlinecolor, -1,-1,-1,255);
   initLabel(&legend->label);
@@ -4423,7 +4770,7 @@ void initLegend(legendObj *legend)
   legend->keysizex = 20;
   legend->keysizey = 10;
   legend->keyspacingx = 5;
-  legend->keyspacingy = 5;  
+  legend->keyspacingy = 5;
   legend->status = MS_OFF;
   legend->transparent = MS_NOOVERRIDE;
   legend->interlace = MS_NOOVERRIDE;
@@ -4436,7 +4783,7 @@ void initLegend(legendObj *legend)
 void freeLegend(legendObj *legend)
 {
   if (legend->template)
-     free(legend->template);
+    free(legend->template);
   freeLabel(&(legend->label));
 }
 
@@ -4446,58 +4793,58 @@ int loadLegend(legendObj *legend, mapObj *map)
 
   for(;;) {
     switch(msyylex()) {
-    case(EOF):
-      msSetError(MS_EOFERR, NULL, "loadLegend()");      
-      return(-1);
-    case(END):
-      legend->label.position = MS_XY; /* overrides go here */
-      return(0);
-      break;
-    case(IMAGECOLOR):
-      if(loadColor(&(legend->imagecolor), NULL) != MS_SUCCESS) return(-1);
-      break;
-    case(INTERLACE):
-      if((legend->interlace = getSymbol(2, MS_ON,MS_OFF)) == -1) return(-1);
-      break;
-    case(KEYSIZE):
-      if(getInteger(&(legend->keysizex)) == -1) return(-1);
-      if(getInteger(&(legend->keysizey)) == -1) return(-1);
-      break;      
-    case(KEYSPACING):
-      if(getInteger(&(legend->keyspacingx)) == -1) return(-1);
-      if(getInteger(&(legend->keyspacingy)) == -1) return(-1);
-      break;  
-    case(LABEL):
-      if(loadLabel(&(legend->label)) == -1) return(-1);
-      legend->label.angle = 0; /* force */
-      break;
-    case(LEGEND):
-      break; /* for string loads */
-    case(OUTLINECOLOR):     
-      if(loadColor(&(legend->outlinecolor), NULL) != MS_SUCCESS) return(-1);
-      break;
-    case(POSITION):
-      if((legend->position = getSymbol(6, MS_UL,MS_UR,MS_LL,MS_LR,MS_UC,MS_LC)) == -1) return(-1);
-      break;
-    case(POSTLABELCACHE):
-      if((legend->postlabelcache = getSymbol(2, MS_TRUE,MS_FALSE)) == -1) return(-1);      
-      break;
-    case(STATUS):
-      if((legend->status = getSymbol(3, MS_ON,MS_OFF,MS_EMBED)) == -1) return(-1);      
-      break;
-    case(TRANSPARENT):
-      if((legend->transparent = getSymbol(2, MS_ON,MS_OFF)) == -1) return(-1);
-      break;
-    case(TEMPLATE):
-      if(getString(&legend->template) == MS_FAILURE) return(-1);
-      break;
-    default:
-      if(strlen(msyystring_buffer) > 0) {
-        msSetError(MS_IDENTERR, "Parsing error near (%s):(line %d)", "loadLegend()", msyystring_buffer, msyylineno);
+      case(EOF):
+        msSetError(MS_EOFERR, NULL, "loadLegend()");
         return(-1);
-      } else {
-        return(0); /* end of a string, not an error */
-      }
+      case(END):
+        legend->label.position = MS_XY; /* overrides go here */
+        return(0);
+        break;
+      case(IMAGECOLOR):
+        if(loadColor(&(legend->imagecolor), NULL) != MS_SUCCESS) return(-1);
+        break;
+      case(INTERLACE):
+        if((legend->interlace = getSymbol(2, MS_ON,MS_OFF)) == -1) return(-1);
+        break;
+      case(KEYSIZE):
+        if(getInteger(&(legend->keysizex)) == -1) return(-1);
+        if(getInteger(&(legend->keysizey)) == -1) return(-1);
+        break;
+      case(KEYSPACING):
+        if(getInteger(&(legend->keyspacingx)) == -1) return(-1);
+        if(getInteger(&(legend->keyspacingy)) == -1) return(-1);
+        break;
+      case(LABEL):
+        if(loadLabel(&(legend->label)) == -1) return(-1);
+        legend->label.angle = 0; /* force */
+        break;
+      case(LEGEND):
+        break; /* for string loads */
+      case(OUTLINECOLOR):
+        if(loadColor(&(legend->outlinecolor), NULL) != MS_SUCCESS) return(-1);
+        break;
+      case(POSITION):
+        if((legend->position = getSymbol(6, MS_UL,MS_UR,MS_LL,MS_LR,MS_UC,MS_LC)) == -1) return(-1);
+        break;
+      case(POSTLABELCACHE):
+        if((legend->postlabelcache = getSymbol(2, MS_TRUE,MS_FALSE)) == -1) return(-1);
+        break;
+      case(STATUS):
+        if((legend->status = getSymbol(3, MS_ON,MS_OFF,MS_EMBED)) == -1) return(-1);
+        break;
+      case(TRANSPARENT):
+        if((legend->transparent = getSymbol(2, MS_ON,MS_OFF)) == -1) return(-1);
+        break;
+      case(TEMPLATE):
+        if(getString(&legend->template) == MS_FAILURE) return(-1);
+        break;
+      default:
+        if(strlen(msyystring_buffer) > 0) {
+          msSetError(MS_IDENTERR, "Parsing error near (%s):(line %d)", "loadLegend()", msyystring_buffer, msyylineno);
+          return(-1);
+        } else {
+          return(0); /* end of a string, not an error */
+        }
     }
   } /* next token */
 }
@@ -4554,8 +4901,8 @@ static void writeLegend(FILE *stream, int indent, legendObj *legend)
 */
 void initScalebar(scalebarObj *scalebar)
 {
-  MS_INIT_COLOR(scalebar->imagecolor, 255,255,255,255);
-  scalebar->width = 200; 
+  MS_INIT_COLOR(scalebar->imagecolor, -1,-1,-1,255);
+  scalebar->width = 200;
   scalebar->height = 3;
   scalebar->style = 0; /* only 2 styles at this point */
   scalebar->intervals = 4;
@@ -4573,7 +4920,8 @@ void initScalebar(scalebarObj *scalebar)
   scalebar->align = MS_ALIGN_CENTER;
 }
 
-void freeScalebar(scalebarObj *scalebar) {
+void freeScalebar(scalebarObj *scalebar)
+{
   freeLabel(&(scalebar->label));
 }
 
@@ -4581,69 +4929,69 @@ int loadScalebar(scalebarObj *scalebar)
 {
   for(;;) {
     switch(msyylex()) {
-    case(ALIGN):
-      if((scalebar->align = getSymbol(3, MS_ALIGN_LEFT,MS_ALIGN_CENTER,MS_ALIGN_RIGHT)) == -1) return(-1);
-      break;
-    case(BACKGROUNDCOLOR):            
-      if(loadColor(&(scalebar->backgroundcolor), NULL) != MS_SUCCESS) return(-1);
-      break;
-    case(COLOR):
-      if(loadColor(&(scalebar->color), NULL) != MS_SUCCESS) return(-1);   
-      break;
-    case(EOF):
-      msSetError(MS_EOFERR, NULL, "loadScalebar()");      
-      return(-1);
-    case(END):
-      return(0);
-      break;
-    case(IMAGECOLOR):      
-      if(loadColor(&(scalebar->imagecolor), NULL) != MS_SUCCESS) return(-1);
-      break;
-    case(INTERLACE):
-      if((scalebar->interlace = getSymbol(2, MS_ON,MS_OFF)) == -1) return(-1);
-      break;
-    case(INTERVALS):      
-      if(getInteger(&(scalebar->intervals)) == -1) return(-1);
-      break;
-    case(LABEL):
-      if(loadLabel(&(scalebar->label)) == -1) return(-1);
-      scalebar->label.angle = 0;
-      break;
-    case(OUTLINECOLOR):      
-      if(loadColor(&(scalebar->outlinecolor), NULL) != MS_SUCCESS) return(-1);
-      break;
-    case(POSITION):
-      if((scalebar->position = getSymbol(6, MS_UL,MS_UR,MS_LL,MS_LR,MS_UC,MS_LC)) == -1) 
-	return(-1);
-      break;
-    case(POSTLABELCACHE):
-      if((scalebar->postlabelcache = getSymbol(2, MS_TRUE,MS_FALSE)) == -1) return(-1);
-      break;
-    case(SCALEBAR):
-      break; /* for string loads */
-    case(SIZE):
-      if(getInteger(&(scalebar->width)) == -1) return(-1);
-      if(getInteger(&(scalebar->height)) == -1) return(-1);
-      break;
-    case(STATUS):
-      if((scalebar->status = getSymbol(3, MS_ON,MS_OFF,MS_EMBED)) == -1) return(-1);
-      break;
-    case(STYLE):      
-      if(getInteger(&(scalebar->style)) == -1) return(-1);
-      break;  
-    case(TRANSPARENT):
-      if((scalebar->transparent = getSymbol(2, MS_ON,MS_OFF)) == -1) return(-1);
-      break;
-    case(UNITS):
-      if((scalebar->units = getSymbol(6, MS_INCHES,MS_FEET,MS_MILES,MS_METERS,MS_KILOMETERS,MS_NAUTICALMILES)) == -1) return(-1);
-      break;
-    default:
-      if(strlen(msyystring_buffer) > 0) {
-        msSetError(MS_IDENTERR, "Parsing error near (%s):(line %d)", "loadScalebar()", msyystring_buffer, msyylineno);
+      case(ALIGN):
+        if((scalebar->align = getSymbol(3, MS_ALIGN_LEFT,MS_ALIGN_CENTER,MS_ALIGN_RIGHT)) == -1) return(-1);
+        break;
+      case(BACKGROUNDCOLOR):
+        if(loadColor(&(scalebar->backgroundcolor), NULL) != MS_SUCCESS) return(-1);
+        break;
+      case(COLOR):
+        if(loadColor(&(scalebar->color), NULL) != MS_SUCCESS) return(-1);
+        break;
+      case(EOF):
+        msSetError(MS_EOFERR, NULL, "loadScalebar()");
         return(-1);
-      } else {
-        return(0); /* end of a string, not an error */
-      }
+      case(END):
+        return(0);
+        break;
+      case(IMAGECOLOR):
+        if(loadColor(&(scalebar->imagecolor), NULL) != MS_SUCCESS) return(-1);
+        break;
+      case(INTERLACE):
+        if((scalebar->interlace = getSymbol(2, MS_ON,MS_OFF)) == -1) return(-1);
+        break;
+      case(INTERVALS):
+        if(getInteger(&(scalebar->intervals)) == -1) return(-1);
+        break;
+      case(LABEL):
+        if(loadLabel(&(scalebar->label)) == -1) return(-1);
+        scalebar->label.angle = 0;
+        break;
+      case(OUTLINECOLOR):
+        if(loadColor(&(scalebar->outlinecolor), NULL) != MS_SUCCESS) return(-1);
+        break;
+      case(POSITION):
+        if((scalebar->position = getSymbol(6, MS_UL,MS_UR,MS_LL,MS_LR,MS_UC,MS_LC)) == -1)
+          return(-1);
+        break;
+      case(POSTLABELCACHE):
+        if((scalebar->postlabelcache = getSymbol(2, MS_TRUE,MS_FALSE)) == -1) return(-1);
+        break;
+      case(SCALEBAR):
+        break; /* for string loads */
+      case(SIZE):
+        if(getInteger(&(scalebar->width)) == -1) return(-1);
+        if(getInteger(&(scalebar->height)) == -1) return(-1);
+        break;
+      case(STATUS):
+        if((scalebar->status = getSymbol(3, MS_ON,MS_OFF,MS_EMBED)) == -1) return(-1);
+        break;
+      case(STYLE):
+        if(getInteger(&(scalebar->style)) == -1) return(-1);
+        break;
+      case(TRANSPARENT):
+        if((scalebar->transparent = getSymbol(2, MS_ON,MS_OFF)) == -1) return(-1);
+        break;
+      case(UNITS):
+        if((scalebar->units = getSymbol(6, MS_INCHES,MS_FEET,MS_MILES,MS_METERS,MS_KILOMETERS,MS_NAUTICALMILES)) == -1) return(-1);
+        break;
+      default:
+        if(strlen(msyystring_buffer) > 0) {
+          msSetError(MS_IDENTERR, "Parsing error near (%s):(line %d)", "loadScalebar()", msyystring_buffer, msyylineno);
+          return(-1);
+        } else {
+          return(0); /* end of a string, not an error */
+        }
     }
   } /* next token */
 }
@@ -4714,35 +5062,35 @@ int loadQueryMap(queryMapObj *querymap)
 {
   for(;;) {
     switch(msyylex()) {
-    case(QUERYMAP):
-      break; /* for string loads */
-    case(COLOR):      
-      loadColor(&(querymap->color), NULL);
-      break;
-    case(EOF):
-      msSetError(MS_EOFERR, NULL, "loadQueryMap()");
-      return(-1);
-    case(END):
-      return(0);
-      break;
-    case(SIZE):
-      if(getInteger(&(querymap->width)) == -1) return(-1);
-      if(getInteger(&(querymap->height)) == -1) return(-1);
-      break;
-    case(STATUS):
-      if((querymap->status = getSymbol(2, MS_ON,MS_OFF)) == -1) return(-1);
-      break;
-    case(STYLE):
-    case(TYPE):
-      if((querymap->style = getSymbol(3, MS_NORMAL,MS_HILITE,MS_SELECTED)) == -1) return(-1);
-      break;
-    default:
-      if(strlen(msyystring_buffer) > 0) {
-        msSetError(MS_IDENTERR, "Parsing error near (%s):(line %d)", "loadQueryMap()", msyystring_buffer, msyylineno);
+      case(QUERYMAP):
+        break; /* for string loads */
+      case(COLOR):
+        loadColor(&(querymap->color), NULL);
+        break;
+      case(EOF):
+        msSetError(MS_EOFERR, NULL, "loadQueryMap()");
         return(-1);
-      } else {
-        return(0); /* end of a string, not an error */
-      }
+      case(END):
+        return(0);
+        break;
+      case(SIZE):
+        if(getInteger(&(querymap->width)) == -1) return(-1);
+        if(getInteger(&(querymap->height)) == -1) return(-1);
+        break;
+      case(STATUS):
+        if((querymap->status = getSymbol(2, MS_ON,MS_OFF)) == -1) return(-1);
+        break;
+      case(STYLE):
+      case(TYPE):
+        if((querymap->style = getSymbol(3, MS_NORMAL,MS_HILITE,MS_SELECTED)) == -1) return(-1);
+        break;
+      default:
+        if(strlen(msyystring_buffer) > 0) {
+          msSetError(MS_IDENTERR, "Parsing error near (%s):(line %d)", "loadQueryMap()", msyystring_buffer, msyylineno);
+          return(-1);
+        } else {
+          return(0); /* end of a string, not an error */
+        }
     }
   }
 }
@@ -4802,9 +5150,9 @@ void initWeb(webObj *web)
   web->imagepath = msStrdup("");
   web->temppath = NULL;
   web->imageurl = msStrdup("");
-  
+
   initHashTable(&(web->metadata));
-  initHashTable(&(web->validation));  
+  initHashTable(&(web->validation));
 
   web->map = NULL;
   web->queryformat = msStrdup("text/html");
@@ -4865,111 +5213,117 @@ int loadWeb(webObj *web, mapObj *map)
 
   for(;;) {
     switch(msyylex()) {
-    case(BROWSEFORMAT): /* change to use validation in 6.0 */
-      free(web->browseformat); web->browseformat = NULL; /* there is a default */
-      if(getString(&web->browseformat) == MS_FAILURE) return(-1);
-      break;
-    case(EMPTY):
-      if(getString(&web->empty) == MS_FAILURE) return(-1);
-      break;
-    case(WEB):
-      break; /* for string loads */
-    case(EOF):
-      msSetError(MS_EOFERR, NULL, "loadWeb()");
-      return(-1);
-    case(END):
-      return(0);
-      break;
-    case(ERROR):
-      if(getString(&web->error) == MS_FAILURE) return(-1);
-      break;
-    case(EXTENT):
-      if(getDouble(&(web->extent.minx)) == -1) return(-1);
-      if(getDouble(&(web->extent.miny)) == -1) return(-1);
-      if(getDouble(&(web->extent.maxx)) == -1) return(-1);
-      if(getDouble(&(web->extent.maxy)) == -1) return(-1);
-      if (!MS_VALID_EXTENT(web->extent)) {
-        msSetError(MS_MISCERR, "Given web extent is invalid. Check that it is in the form: minx, miny, maxx, maxy", "loadWeb()"); 
+      case(BROWSEFORMAT): /* change to use validation in 6.0 */
+        free(web->browseformat);
+        web->browseformat = NULL; /* there is a default */
+        if(getString(&web->browseformat) == MS_FAILURE) return(-1);
+        break;
+      case(EMPTY):
+        if(getString(&web->empty) == MS_FAILURE) return(-1);
+        break;
+      case(WEB):
+        break; /* for string loads */
+      case(EOF):
+        msSetError(MS_EOFERR, NULL, "loadWeb()");
         return(-1);
-      }
-      break;
-    case(FOOTER):
-      if(getString(&web->footer) == MS_FAILURE) return(-1); /* getString() cleans up previously allocated string */
-      if(msyysource == MS_URL_TOKENS) {
-        if(msValidateParameter(web->footer, msLookupHashTable(&(web->validation), "footer"), map->templatepattern, NULL, NULL) != MS_SUCCESS) {
-          msSetError(MS_MISCERR, "URL-based FOOTER configuration failed pattern validation." , "loadWeb()");
-          msFree(web->footer); web->footer=NULL;
+      case(END):
+        return(0);
+        break;
+      case(ERROR):
+        if(getString(&web->error) == MS_FAILURE) return(-1);
+        break;
+      case(EXTENT):
+        if(getDouble(&(web->extent.minx)) == -1) return(-1);
+        if(getDouble(&(web->extent.miny)) == -1) return(-1);
+        if(getDouble(&(web->extent.maxx)) == -1) return(-1);
+        if(getDouble(&(web->extent.maxy)) == -1) return(-1);
+        if (!MS_VALID_EXTENT(web->extent)) {
+          msSetError(MS_MISCERR, "Given web extent is invalid. Check that it is in the form: minx, miny, maxx, maxy", "loadWeb()");
           return(-1);
         }
-      }
-      break;
-    case(HEADER):
-      if(getString(&web->header) == MS_FAILURE) return(-1); /* getString() cleans up previously allocated string */
-      if(msyysource == MS_URL_TOKENS) {
-        if(msValidateParameter(web->header, msLookupHashTable(&(web->validation), "header"), map->templatepattern, NULL, NULL) != MS_SUCCESS) {
-          msSetError(MS_MISCERR, "URL-based HEADER configuration failed pattern validation." , "loadWeb()");
-          msFree(web->header); web->header=NULL;
-          return(-1);
+        break;
+      case(FOOTER):
+        if(getString(&web->footer) == MS_FAILURE) return(-1); /* getString() cleans up previously allocated string */
+        if(msyysource == MS_URL_TOKENS) {
+          if(msValidateParameter(web->footer, msLookupHashTable(&(web->validation), "footer"), map->templatepattern, NULL, NULL) != MS_SUCCESS) {
+            msSetError(MS_MISCERR, "URL-based FOOTER configuration failed pattern validation." , "loadWeb()");
+            msFree(web->footer);
+            web->footer=NULL;
+            return(-1);
+          }
         }
-      }
-      break;
-    case(IMAGEPATH):      
-      if(getString(&web->imagepath) == MS_FAILURE) return(-1);
-      break;
-    case(TEMPPATH):      
-      if(getString(&web->temppath) == MS_FAILURE) return(-1);
-      break;
-    case(IMAGEURL):
-      if(getString(&web->imageurl) == MS_FAILURE) return(-1);
-      break;
-    case(LEGENDFORMAT): /* change to use validation in 6.0 */
-      free(web->legendformat); web->legendformat = NULL; /* there is a default */
-      if(getString(&web->legendformat) == MS_FAILURE) return(-1);
-      break;
-    case(LOG):
-      if(getString(&web->log) == MS_FAILURE) return(-1);
-      break;
-    case(MAXSCALE):
-    case(MAXSCALEDENOM):
-      if(getDouble(&web->maxscaledenom) == -1) return(-1);
-      break;
-    case(MAXTEMPLATE):
-      if(getString(&web->maxtemplate) == MS_FAILURE) return(-1);
-      break;
-    case(METADATA):
-      if(loadHashTable(&(web->metadata)) != MS_SUCCESS) return(-1);
-      break;
-    case(MINSCALE):
-    case(MINSCALEDENOM):
-      if(getDouble(&web->minscaledenom) == -1) return(-1);
-      break;
-    case(MINTEMPLATE):
-      if(getString(&web->mintemplate) == MS_FAILURE) return(-1);
-      break; 
-    case(QUERYFORMAT): /* change to use validation in 6.0 */
-      free(web->queryformat); web->queryformat = NULL; /* there is a default */
-      if(getString(&web->queryformat) == MS_FAILURE) return(-1);
-      break;   
-    case(TEMPLATE):
-      if(getString(&web->template) == MS_FAILURE) return(-1); /* getString() cleans up previously allocated string */
-      if(msyysource == MS_URL_TOKENS) {
-        if(msValidateParameter(web->template, msLookupHashTable(&(web->validation), "template"), map->templatepattern, NULL, NULL) != MS_SUCCESS) {
-          msSetError(MS_MISCERR, "URL-based TEMPLATE configuration failed pattern validation." , "loadWeb()");
-          msFree(web->template); web->template=NULL;
-          return(-1);
+        break;
+      case(HEADER):
+        if(getString(&web->header) == MS_FAILURE) return(-1); /* getString() cleans up previously allocated string */
+        if(msyysource == MS_URL_TOKENS) {
+          if(msValidateParameter(web->header, msLookupHashTable(&(web->validation), "header"), map->templatepattern, NULL, NULL) != MS_SUCCESS) {
+            msSetError(MS_MISCERR, "URL-based HEADER configuration failed pattern validation." , "loadWeb()");
+            msFree(web->header);
+            web->header=NULL;
+            return(-1);
+          }
+        }
+        break;
+      case(IMAGEPATH):
+        if(getString(&web->imagepath) == MS_FAILURE) return(-1);
+        break;
+      case(TEMPPATH):
+        if(getString(&web->temppath) == MS_FAILURE) return(-1);
+        break;
+      case(IMAGEURL):
+        if(getString(&web->imageurl) == MS_FAILURE) return(-1);
+        break;
+      case(LEGENDFORMAT): /* change to use validation in 6.0 */
+        free(web->legendformat);
+        web->legendformat = NULL; /* there is a default */
+        if(getString(&web->legendformat) == MS_FAILURE) return(-1);
+        break;
+      case(LOG):
+        if(getString(&web->log) == MS_FAILURE) return(-1);
+        break;
+      case(MAXSCALE):
+      case(MAXSCALEDENOM):
+        if(getDouble(&web->maxscaledenom) == -1) return(-1);
+        break;
+      case(MAXTEMPLATE):
+        if(getString(&web->maxtemplate) == MS_FAILURE) return(-1);
+        break;
+      case(METADATA):
+        if(loadHashTable(&(web->metadata)) != MS_SUCCESS) return(-1);
+        break;
+      case(MINSCALE):
+      case(MINSCALEDENOM):
+        if(getDouble(&web->minscaledenom) == -1) return(-1);
+        break;
+      case(MINTEMPLATE):
+        if(getString(&web->mintemplate) == MS_FAILURE) return(-1);
+        break;
+      case(QUERYFORMAT): /* change to use validation in 6.0 */
+        free(web->queryformat);
+        web->queryformat = NULL; /* there is a default */
+        if(getString(&web->queryformat) == MS_FAILURE) return(-1);
+        break;
+      case(TEMPLATE):
+        if(getString(&web->template) == MS_FAILURE) return(-1); /* getString() cleans up previously allocated string */
+        if(msyysource == MS_URL_TOKENS) {
+          if(msValidateParameter(web->template, msLookupHashTable(&(web->validation), "template"), map->templatepattern, NULL, NULL) != MS_SUCCESS) {
+            msSetError(MS_MISCERR, "URL-based TEMPLATE configuration failed pattern validation." , "loadWeb()");
+            msFree(web->template);
+            web->template=NULL;
+            return(-1);
+          }
+        }
+        break;
+      case(VALIDATION):
+        if(loadHashTable(&(web->validation)) != MS_SUCCESS) return(-1);
+        break;
+      default:
+        if(strlen(msyystring_buffer) > 0) {
+          msSetError(MS_IDENTERR, "Parsing error near (%s):(line %d)", "loadWeb()", msyystring_buffer, msyylineno);
+          return(-1);
+        } else {
+          return(0); /* end of a string, not an error */
         }
-      }
-      break;
-    case(VALIDATION):
-      if(loadHashTable(&(web->validation)) != MS_SUCCESS) return(-1);
-      break;
-    default:
-      if(strlen(msyystring_buffer) > 0) {
-        msSetError(MS_IDENTERR, "Parsing error near (%s):(line %d)", "loadWeb()", msyystring_buffer, msyylineno);
-        return(-1);
-      } else {
-        return(0); /* end of a string, not an error */
-      }
     }
   }
 }
@@ -5002,7 +5356,7 @@ int msUpdateWebFromString(webObj *web, char *string, int url_string)
 /*
 ** Initialize, load and free a mapObj structure
 **
-** This really belongs in mapobject.c, but currently it also depends on 
+** This really belongs in mapobject.c, but currently it also depends on
 ** lots of other init methods in this file.
 */
 int initMap(mapObj *map)
@@ -5047,7 +5401,7 @@ int initMap(mapObj *map)
 
   /* map->configoptions = msCreateHashTable();; */
   initHashTable(&(map->configoptions));
-          
+
   map->imagetype = NULL;
 
   map->palette.numcolors = 0;
@@ -5057,21 +5411,21 @@ int initMap(mapObj *map)
   map->imagequality = MS_NOOVERRIDE;
 
   for(i=0; i<MS_MAX_LABEL_PRIORITY; i++) {
-      map->labelcache.slots[i].labels = NULL; /* cache is initialize at draw time */
-      map->labelcache.slots[i].cachesize = 0;
-      map->labelcache.slots[i].numlabels = 0;
-      map->labelcache.slots[i].markers = NULL;
-      map->labelcache.slots[i].markercachesize = 0;
-      map->labelcache.slots[i].nummarkers = 0;
+    map->labelcache.slots[i].labels = NULL; /* cache is initialize at draw time */
+    map->labelcache.slots[i].cachesize = 0;
+    map->labelcache.slots[i].numlabels = 0;
+    map->labelcache.slots[i].markers = NULL;
+    map->labelcache.slots[i].markercachesize = 0;
+    map->labelcache.slots[i].nummarkers = 0;
   }
   map->labelcache.numlabels = 0;
 
   map->fontset.filename = NULL;
-  map->fontset.numfonts = 0;  
-  
+  map->fontset.numfonts = 0;
+
   /* map->fontset.fonts = NULL; */
   initHashTable(&(map->fontset.fonts));
-  
+
   msInitSymbolSet(&map->symbolset);
   map->symbolset.fontset =  &(map->fontset);
 
@@ -5105,9 +5459,9 @@ int initMap(mapObj *map)
 }
 
 /*
-** Ensure there is at least one free entry in the layers and layerorder 
-** arrays of this mapObj. Grow the allocated layers/layerorder arrays if 
-** necessary and allocate a new layer for layers[numlayers] if there is 
+** Ensure there is at least one free entry in the layers and layerorder
+** arrays of this mapObj. Grow the allocated layers/layerorder arrays if
+** necessary and allocate a new layer for layers[numlayers] if there is
 ** not already one, setting its contents to all zero bytes (i.e. does not
 ** call initLayer() on it).
 **
@@ -5118,72 +5472,85 @@ int initMap(mapObj *map)
 */
 layerObj *msGrowMapLayers( mapObj *map )
 {
-    /* Do we need to increase the size of layers/layerorder by 
-     * MS_LAYER_ALLOCSIZE?
-     */
-    if (map->numlayers == map->maxlayers) {
-        layerObj **newLayersPtr;
-        int *newLayerorderPtr;
-        int i, newsize;
-
-        newsize = map->maxlayers + MS_LAYER_ALLOCSIZE;
-
-        /* Alloc/realloc layers */
-        newLayersPtr = (layerObj**)realloc(map->layers,
-                                           newsize*sizeof(layerObj*));
-        MS_CHECK_ALLOC(newLayersPtr, newsize*sizeof(layerObj*), NULL);
-
-        map->layers = newLayersPtr;
-
-        /* Alloc/realloc layerorder */
-        newLayerorderPtr = (int *)realloc(map->layerorder,
-                                          newsize*sizeof(int));
-        MS_CHECK_ALLOC(newLayerorderPtr, newsize*sizeof(int), NULL);
-        
-        map->layerorder = newLayerorderPtr;
-
-        map->maxlayers = newsize;
-        for(i=map->numlayers; i<map->maxlayers; i++) {
-            map->layers[i] = NULL;
-            map->layerorder[i] = 0;
-        }
-    }
+  /* Do we need to increase the size of layers/layerorder by
+   * MS_LAYER_ALLOCSIZE?
+   */
+  if (map->numlayers == map->maxlayers) {
+    layerObj **newLayersPtr;
+    int *newLayerorderPtr;
+    int i, newsize;
+
+    newsize = map->maxlayers + MS_LAYER_ALLOCSIZE;
+
+    /* Alloc/realloc layers */
+    newLayersPtr = (layerObj**)realloc(map->layers,
+                                       newsize*sizeof(layerObj*));
+    MS_CHECK_ALLOC(newLayersPtr, newsize*sizeof(layerObj*), NULL);
+
+    map->layers = newLayersPtr;
 
-    if (map->layers[map->numlayers]==NULL) {
-        map->layers[map->numlayers]=(layerObj*)calloc(1,sizeof(layerObj));
-        MS_CHECK_ALLOC(map->layers[map->numlayers], sizeof(layerObj), NULL);
+    /* Alloc/realloc layerorder */
+    newLayerorderPtr = (int *)realloc(map->layerorder,
+                                      newsize*sizeof(int));
+    MS_CHECK_ALLOC(newLayerorderPtr, newsize*sizeof(int), NULL);
+
+    map->layerorder = newLayerorderPtr;
+
+    map->maxlayers = newsize;
+    for(i=map->numlayers; i<map->maxlayers; i++) {
+      map->layers[i] = NULL;
+      map->layerorder[i] = 0;
     }
+  }
+
+  if (map->layers[map->numlayers]==NULL) {
+    map->layers[map->numlayers]=(layerObj*)calloc(1,sizeof(layerObj));
+    MS_CHECK_ALLOC(map->layers[map->numlayers], sizeof(layerObj), NULL);
+  }
 
-    return map->layers[map->numlayers];
+  return map->layers[map->numlayers];
 }
 
 
-int msFreeLabelCacheSlot(labelCacheSlotObj *cacheslot) {
+int msFreeLabelCacheSlot(labelCacheSlotObj *cacheslot)
+{
   int i, j;
 
   /* free the labels */
-  if (cacheslot->labels)
+  if (cacheslot->labels) {
     for(i=0; i<cacheslot->numlabels; i++) {
-      msFree(cacheslot->labels[i].text);
       if (cacheslot->labels[i].labelpath)
         msFreeLabelPathObj(cacheslot->labels[i].labelpath);
-      freeLabel(&(cacheslot->labels[i].label));
-      msFreeShape(cacheslot->labels[i].poly); /* empties the shape */
-      msFree(cacheslot->labels[i].poly); /* free's the pointer */
-      for(j=0;j<cacheslot->labels[i].numstyles; j++) freeStyle(&(cacheslot->labels[i].styles[j]));
+
+      for(j=0; j<cacheslot->labels[i].numlabels; j++) freeLabel(&(cacheslot->labels[i].labels[j]));
+      msFree(cacheslot->labels[i].labels);
+
+      if(cacheslot->labels[i].poly) {
+        msFreeShape(cacheslot->labels[i].poly); /* empties the shape */
+        msFree(cacheslot->labels[i].poly); /* free's the pointer */
+      }
+
+      for(j=0; j<cacheslot->labels[i].numstyles; j++) freeStyle(&(cacheslot->labels[i].styles[j]));
       msFree(cacheslot->labels[i].styles);
+      if(cacheslot->labels[i].leaderline) {
+        msFree(cacheslot->labels[i].leaderline->point);
+        msFree(cacheslot->labels[i].leaderline);
+        msFree(cacheslot->labels[i].leaderbbox);
+      }
     }
+  }
   msFree(cacheslot->labels);
   cacheslot->labels = NULL;
   cacheslot->cachesize = 0;
   cacheslot->numlabels = 0;
-  
+
   /* free the markers */
-  if (cacheslot->markers)
+  if (cacheslot->markers) {
     for(i=0; i<cacheslot->nummarkers; i++) {
       msFreeShape(cacheslot->markers[i].poly);
       msFree(cacheslot->markers[i].poly);
     }
+  }
   msFree(cacheslot->markers);
   cacheslot->markers = NULL;
   cacheslot->markercachesize = 0;
@@ -5192,12 +5559,13 @@ int msFreeLabelCacheSlot(labelCacheSlotObj *cacheslot) {
   return(MS_SUCCESS);
 }
 
-int msFreeLabelCache(labelCacheObj *cache) {
+int msFreeLabelCache(labelCacheObj *cache)
+{
   int p;
 
   for(p=0; p<MS_MAX_LABEL_PRIORITY; p++) {
-      if (msFreeLabelCacheSlot(&(cache->slots[p])) != MS_SUCCESS)
-          return MS_FAILURE;
+    if (msFreeLabelCacheSlot(&(cache->slots[p])) != MS_SUCCESS)
+      return MS_FAILURE;
   }
 
   cache->numlabels = 0;
@@ -5205,10 +5573,11 @@ int msFreeLabelCache(labelCacheObj *cache) {
   return MS_SUCCESS;
 }
 
-int msInitLabelCacheSlot(labelCacheSlotObj *cacheslot) {
+int msInitLabelCacheSlot(labelCacheSlotObj *cacheslot)
+{
 
-  if(cacheslot->labels || cacheslot->markers) 
-      msFreeLabelCacheSlot(cacheslot);
+  if(cacheslot->labels || cacheslot->markers)
+    msFreeLabelCacheSlot(cacheslot);
 
   cacheslot->labels = (labelCacheMemberObj *)malloc(sizeof(labelCacheMemberObj)*MS_LABELCACHEINITSIZE);
   MS_CHECK_ALLOC(cacheslot->labels, sizeof(labelCacheMemberObj)*MS_LABELCACHEINITSIZE, MS_FAILURE);
@@ -5225,14 +5594,16 @@ int msInitLabelCacheSlot(labelCacheSlotObj *cacheslot) {
   return(MS_SUCCESS);
 }
 
-int msInitLabelCache(labelCacheObj *cache) {
+int msInitLabelCache(labelCacheObj *cache)
+{
   int p;
 
   for(p=0; p<MS_MAX_LABEL_PRIORITY; p++) {
-      if (msInitLabelCacheSlot(&(cache->slots[p])) != MS_SUCCESS)
-          return MS_FAILURE;
+    if (msInitLabelCacheSlot(&(cache->slots[p])) != MS_SUCCESS)
+      return MS_FAILURE;
   }
   cache->numlabels = 0;
+  cache->gutter = 0;
 
   return MS_SUCCESS;
 }
@@ -5257,7 +5628,7 @@ int msSaveMap(mapObj *map, char *filename)
 
   stream = fopen(msBuildPath(szPath, map->mappath, filename), "w");
   if(!stream) {
-    msSetError(MS_IOERR, "(%s)", "msSaveMap()", filename);    
+    msSetError(MS_IOERR, "(%s)", "msSaveMap()", filename);
     return(-1);
   }
 
@@ -5275,14 +5646,14 @@ int msSaveMap(mapObj *map, char *filename)
   writeNumber(stream, indent, "MAXSIZE", MS_MAXIMAGESIZE_DEFAULT, map->maxsize);
   writeString(stream, indent, "NAME", NULL, map->name);
   writeNumber(stream, indent, "RESOLUTION", 72.0, map->resolution);
-  writeString(stream, indent, "SHAPEPATH", NULL, map->shapepath);   
+  writeString(stream, indent, "SHAPEPATH", NULL, map->shapepath);
   writeDimension(stream, indent, "SIZE", map->width, map->height, NULL, NULL);
   writeKeyword(stream, indent, "STATUS", map->status, 2, MS_ON, "ON", MS_OFF, "OFF");
   writeString(stream, indent, "SYMBOLSET", NULL, map->symbolset.filename);
   writeString(stream, indent, "TEMPLATEPATTERN", NULL, map->templatepattern); /* depricated */
   writeKeyword(stream, indent, "TRANSPARENT", map->transparent, 2, MS_TRUE, "TRUE", MS_FALSE, "FALSE");
-  writeKeyword(stream, indent, "UNITS", map->units, 7, MS_INCHES, "INCHES", MS_FEET ,"FEET", MS_MILES, "MILES", MS_METERS, "METERS", MS_KILOMETERS, "KILOMETERS", MS_NAUTICALMILES, "NAUTICALMILES", MS_DD, "DD"); 
-  writeLineFeed(stream); 
+  writeKeyword(stream, indent, "UNITS", map->units, 7, MS_INCHES, "INCHES", MS_FEET ,"FEET", MS_MILES, "MILES", MS_METERS, "METERS", MS_KILOMETERS, "KILOMETERS", MS_NAUTICALMILES, "NAUTICALMILES", MS_DD, "DD");
+  writeLineFeed(stream);
 
   writeOutputformat(stream, indent, map);
 
@@ -5292,7 +5663,7 @@ int msSaveMap(mapObj *map, char *filename)
   }
 
   writeProjection(stream, indent, &(map->projection));
-  
+
   writeLegend(stream, indent, &(map->legend));
   writeQueryMap(stream, indent, &(map->querymap));
   writeReferenceMap(stream, indent, &(map->reference));
@@ -5310,202 +5681,198 @@ int msSaveMap(mapObj *map, char *filename)
 
 static int loadMapInternal(mapObj *map)
 {
-  int foundMapToken=MS_FALSE; 
-  int token; 
+  int foundMapToken=MS_FALSE;
+  int token;
 
   for(;;) {
 
-    token = msyylex(); 
+    token = msyylex();
 
-    if(!foundMapToken && token != MAP) { 
-      msSetError(MS_IDENTERR, "First token must be MAP, this doesn't look like a mapfile.", "msLoadMap()"); 
-      return(MS_FAILURE); 
+    if(!foundMapToken && token != MAP) {
+      msSetError(MS_IDENTERR, "First token must be MAP, this doesn't look like a mapfile.", "msLoadMap()");
+      return(MS_FAILURE);
     }
 
     switch(token) {
 
-    case(CONFIG):
-    {
+      case(CONFIG): {
         char *key=NULL, *value=NULL;
 
         if( getString(&key) == MS_FAILURE )
-            return MS_FAILURE;
+          return MS_FAILURE;
 
         if( getString(&value) == MS_FAILURE ) {
-            free(key);
-            return MS_FAILURE;
+          free(key);
+          return MS_FAILURE;
         }
 
         if (msSetConfigOption( map, key, value ) == MS_FAILURE) {
-            free(key);
-            free(value);
-            return MS_FAILURE;
+          free(key);
+          free(value);
+          return MS_FAILURE;
         }
 
         free( key );
         free( value );
-    }
-    break;
-
-    case(DATAPATTERN):
-      if(getString(&map->datapattern) == MS_FAILURE) return MS_FAILURE;
-      break;
-    case(DEBUG):
-      if((map->debug = getSymbol(3, MS_ON,MS_OFF, MS_NUMBER)) == -1) return MS_FAILURE;
-      if(map->debug == MS_NUMBER) map->debug = (int) msyynumber;
+      }
       break;
-    case(END):
-      if(msyyin) {
+
+      case(DATAPATTERN):
+        if(getString(&map->datapattern) == MS_FAILURE) return MS_FAILURE;
+        break;
+      case(DEBUG):
+        if((map->debug = getSymbol(3, MS_ON,MS_OFF, MS_NUMBER)) == -1) return MS_FAILURE;
+        if(map->debug == MS_NUMBER) map->debug = (int) msyynumber;
+        break;
+      case(END):
+        if(msyyin) {
           fclose(msyyin);
           msyyin = NULL;
-      }
+        }
 
-      /*** Make config options current ***/
-      msApplyMapConfigOptions( map );
+        /*** Make config options current ***/
+        msApplyMapConfigOptions( map );
 
-      /*** Compute rotated extent info if applicable ***/
-      msMapComputeGeotransform( map );
-                                            
-      /*** OUTPUTFORMAT related setup ***/
-      if( msPostMapParseOutputFormatSetup( map ) == MS_FAILURE )
+        /*** Compute rotated extent info if applicable ***/
+        msMapComputeGeotransform( map );
+
+        /*** OUTPUTFORMAT related setup ***/
+        if( msPostMapParseOutputFormatSetup( map ) == MS_FAILURE )
           return MS_FAILURE;
 
-      if(loadSymbolSet(&(map->symbolset), map) == -1) return MS_FAILURE;
+        if(loadSymbolSet(&(map->symbolset), map) == -1) return MS_FAILURE;
 
-      if (msResolveSymbolNames(map) == MS_FAILURE) return MS_FAILURE;
-      
+        if (resolveSymbolNames(map) == MS_FAILURE) return MS_FAILURE;
 
-#if defined (USE_GD_TTF) || defined (USE_GD_FT)
-      if(msLoadFontSet(&(map->fontset), map) == -1) return MS_FAILURE;
-#endif
 
-      return MS_SUCCESS;
+        if(msLoadFontSet(&(map->fontset), map) == -1) return MS_FAILURE;
+
+        return MS_SUCCESS;
+        break;
+      case(EOF):
+        msSetError(MS_EOFERR, NULL, "msLoadMap()");
+        return MS_FAILURE;
+      case(EXTENT): {
+        if(getDouble(&(map->extent.minx)) == -1) return MS_FAILURE;
+        if(getDouble(&(map->extent.miny)) == -1) return MS_FAILURE;
+        if(getDouble(&(map->extent.maxx)) == -1) return MS_FAILURE;
+        if(getDouble(&(map->extent.maxy)) == -1) return MS_FAILURE;
+        if (!MS_VALID_EXTENT(map->extent)) {
+          msSetError(MS_MISCERR, "Given map extent is invalid. Check that it " \
+                     "is in the form: minx, miny, maxx, maxy", "loadMapInternal()");
+          return MS_FAILURE;
+        }
+      }
       break;
-    case(EOF):
-      msSetError(MS_EOFERR, NULL, "msLoadMap()");
-      return MS_FAILURE;
-    case(EXTENT):
-    {
-       if(getDouble(&(map->extent.minx)) == -1) return MS_FAILURE;
-       if(getDouble(&(map->extent.miny)) == -1) return MS_FAILURE;
-       if(getDouble(&(map->extent.maxx)) == -1) return MS_FAILURE;
-       if(getDouble(&(map->extent.maxy)) == -1) return MS_FAILURE;
-       if (!MS_VALID_EXTENT(map->extent)) {
-    	 msSetError(MS_MISCERR, "Given map extent is invalid. Check that it " \
-        "is in the form: minx, miny, maxx, maxy", "loadMapInternal()"); 
-      	 return MS_FAILURE;
-       }
-    }
-    break;
-    case(ANGLE):
-    {
+      case(ANGLE): {
         double rotation_angle;
         if(getDouble(&(rotation_angle)) == -1) return MS_FAILURE;
         msMapSetRotation( map, rotation_angle );
-    }
-    break;
-    case(TEMPLATEPATTERN):
-      if(getString(&map->templatepattern) == MS_FAILURE) return MS_FAILURE;
-      break;
-    case(FONTSET):
-      if(getString(&map->fontset.filename) == MS_FAILURE) return MS_FAILURE;
-      break;
-    case(IMAGECOLOR):
-      if(loadColor(&(map->imagecolor), NULL) != MS_SUCCESS) return MS_FAILURE;
-      break; 
-    case(IMAGEQUALITY):
-      if(getInteger(&(map->imagequality)) == -1) return MS_FAILURE;
-      break;
-    case(IMAGETYPE):
-      map->imagetype = getToken();
-      break;
-    case(INTERLACE):
-      if((map->interlace = getSymbol(2, MS_ON,MS_OFF)) == -1) return MS_FAILURE;
-      break;
-    case(LATLON):
-      msFreeProjection(&map->latlon);
-      if(loadProjection(&map->latlon) == -1) return MS_FAILURE;
+      }
       break;
-    case(LAYER):
-      if(msGrowMapLayers(map) == NULL)
+      case(TEMPLATEPATTERN):
+        if(getString(&map->templatepattern) == MS_FAILURE) return MS_FAILURE;
+        break;
+      case(FONTSET):
+        if(getString(&map->fontset.filename) == MS_FAILURE) return MS_FAILURE;
+        break;
+      case(IMAGECOLOR):
+        if(loadColor(&(map->imagecolor), NULL) != MS_SUCCESS) return MS_FAILURE;
+        break;
+      case(IMAGEQUALITY):
+        if(getInteger(&(map->imagequality)) == -1) return MS_FAILURE;
+        break;
+      case(IMAGETYPE):
+        map->imagetype = getToken();
+        break;
+      case(INTERLACE):
+        if((map->interlace = getSymbol(2, MS_ON,MS_OFF)) == -1) return MS_FAILURE;
+        break;
+      case(LATLON):
+        msFreeProjection(&map->latlon);
+        if(loadProjection(&map->latlon) == -1) return MS_FAILURE;
+        break;
+      case(LAYER):
+        if(msGrowMapLayers(map) == NULL)
           return MS_FAILURE;
-      if(initLayer((GET_LAYER(map, map->numlayers)), map) == -1) return MS_FAILURE;
-      if(loadLayer((GET_LAYER(map, map->numlayers)), map) == -1) return MS_FAILURE;
-      GET_LAYER(map, map->numlayers)->index = map->numlayers; /* save the index */
-      /* Update the layer order list with the layer's index. */
-      map->layerorder[map->numlayers] = map->numlayers;
-      map->numlayers++;
-      break;
-    case(OUTPUTFORMAT):
-      if(loadOutputFormat(map) == -1) return MS_FAILURE;
-      break;
-    case(LEGEND):
-      if(loadLegend(&(map->legend), map) == -1) return MS_FAILURE;
-      break;
-    case(MAP):
-      foundMapToken = MS_TRUE;
-      break;   
-    case(MAXSIZE):
-      if(getInteger(&(map->maxsize)) == -1) return MS_FAILURE;
-      break;
-    case(NAME):
-      free(map->name); map->name = NULL; /* erase default */
-      if(getString(&map->name) == MS_FAILURE) return MS_FAILURE;
-      break;
-    case(PROJECTION):
-      if(loadProjection(&map->projection) == -1) return MS_FAILURE;
-      break;
-    case(QUERYMAP):
-      if(loadQueryMap(&(map->querymap)) == -1) return MS_FAILURE;
-      break;
-    case(REFERENCE):
-      if(loadReferenceMap(&(map->reference), map) == -1) return MS_FAILURE;
-      break;
-    case(RESOLUTION):
-      if(getDouble(&(map->resolution)) == -1) return MS_FAILURE;
-      break;
-    case(DEFRESOLUTION):
-      if(getDouble(&(map->defresolution)) == -1) return MS_FAILURE;
-      break;
-    case(SCALE):
-    case(SCALEDENOM):
-      if(getDouble(&(map->scaledenom)) == -1) return MS_FAILURE;
-      break;
-    case(SCALEBAR):
-      if(loadScalebar(&(map->scalebar)) == -1) return MS_FAILURE;
-      break;   
-    case(SHAPEPATH):
-      if(getString(&map->shapepath) == MS_FAILURE) return MS_FAILURE;
-      break;
-    case(SIZE):
-      if(getInteger(&(map->width)) == -1) return MS_FAILURE;
-      if(getInteger(&(map->height)) == -1) return MS_FAILURE;
-      break;
-    case(STATUS):
-      if((map->status = getSymbol(2, MS_ON,MS_OFF)) == -1) return MS_FAILURE;
-      break;
-    case(SYMBOL):
-      if(msGrowSymbolSet(&(map->symbolset)) == NULL)
+        if(initLayer((GET_LAYER(map, map->numlayers)), map) == -1) return MS_FAILURE;
+        if(loadLayer((GET_LAYER(map, map->numlayers)), map) == -1) return MS_FAILURE;
+        GET_LAYER(map, map->numlayers)->index = map->numlayers; /* save the index */
+        /* Update the layer order list with the layer's index. */
+        map->layerorder[map->numlayers] = map->numlayers;
+        map->numlayers++;
+        break;
+      case(OUTPUTFORMAT):
+        if(loadOutputFormat(map) == -1) return MS_FAILURE;
+        break;
+      case(LEGEND):
+        if(loadLegend(&(map->legend), map) == -1) return MS_FAILURE;
+        break;
+      case(MAP):
+        foundMapToken = MS_TRUE;
+        break;
+      case(MAXSIZE):
+        if(getInteger(&(map->maxsize)) == -1) return MS_FAILURE;
+        break;
+      case(NAME):
+        free(map->name);
+        map->name = NULL; /* erase default */
+        if(getString(&map->name) == MS_FAILURE) return MS_FAILURE;
+        break;
+      case(PROJECTION):
+        if(loadProjection(&map->projection) == -1) return MS_FAILURE;
+        break;
+      case(QUERYMAP):
+        if(loadQueryMap(&(map->querymap)) == -1) return MS_FAILURE;
+        break;
+      case(REFERENCE):
+        if(loadReferenceMap(&(map->reference), map) == -1) return MS_FAILURE;
+        break;
+      case(RESOLUTION):
+        if(getDouble(&(map->resolution)) == -1) return MS_FAILURE;
+        break;
+      case(DEFRESOLUTION):
+        if(getDouble(&(map->defresolution)) == -1) return MS_FAILURE;
+        break;
+      case(SCALE):
+      case(SCALEDENOM):
+        if(getDouble(&(map->scaledenom)) == -1) return MS_FAILURE;
+        break;
+      case(SCALEBAR):
+        if(loadScalebar(&(map->scalebar)) == -1) return MS_FAILURE;
+        break;
+      case(SHAPEPATH):
+        if(getString(&map->shapepath) == MS_FAILURE) return MS_FAILURE;
+        break;
+      case(SIZE):
+        if(getInteger(&(map->width)) == -1) return MS_FAILURE;
+        if(getInteger(&(map->height)) == -1) return MS_FAILURE;
+        break;
+      case(STATUS):
+        if((map->status = getSymbol(2, MS_ON,MS_OFF)) == -1) return MS_FAILURE;
+        break;
+      case(SYMBOL):
+        if(msGrowSymbolSet(&(map->symbolset)) == NULL)
           return MS_FAILURE;
-      if((loadSymbol(map->symbolset.symbol[map->symbolset.numsymbols], map->mappath) == -1)) return MS_FAILURE;
-      map->symbolset.symbol[map->symbolset.numsymbols]->inmapfile = MS_TRUE;
-      map->symbolset.numsymbols++;
-      break;
-    case(SYMBOLSET):
-      if(getString(&map->symbolset.filename) == MS_FAILURE) return MS_FAILURE;
-      break;
-    case(TRANSPARENT):
-      if((map->transparent = getSymbol(2, MS_ON,MS_OFF)) == -1) return MS_FAILURE;
-      break;
-    case(UNITS):
-      if((map->units = getSymbol(7, MS_INCHES,MS_FEET,MS_MILES,MS_METERS,MS_KILOMETERS,MS_NAUTICALMILES,MS_DD)) == -1) return MS_FAILURE;
-      break;
-    case(WEB):
-      if(loadWeb(&(map->web), map) == -1) return MS_FAILURE;
-      break;
-    default:
-      msSetError(MS_IDENTERR, "Parsing error near (%s):(line %d)", "msLoadMap()", msyystring_buffer, msyylineno);
-      return MS_FAILURE;
+        if((loadSymbol(map->symbolset.symbol[map->symbolset.numsymbols], map->mappath) == -1)) return MS_FAILURE;
+        map->symbolset.symbol[map->symbolset.numsymbols]->inmapfile = MS_TRUE;
+        map->symbolset.numsymbols++;
+        break;
+      case(SYMBOLSET):
+        if(getString(&map->symbolset.filename) == MS_FAILURE) return MS_FAILURE;
+        break;
+      case(TRANSPARENT):
+        if((map->transparent = getSymbol(2, MS_ON,MS_OFF)) == -1) return MS_FAILURE;
+        break;
+      case(UNITS):
+        if((map->units = getSymbol(7, MS_INCHES,MS_FEET,MS_MILES,MS_METERS,MS_KILOMETERS,MS_NAUTICALMILES,MS_DD)) == -1) return MS_FAILURE;
+        break;
+      case(WEB):
+        if(loadWeb(&(map->web), map) == -1) return MS_FAILURE;
+        break;
+      default:
+        msSetError(MS_IDENTERR, "Parsing error near (%s):(line %d)", "msLoadMap()", msyystring_buffer, msyylineno);
+        return MS_FAILURE;
     }
   } /* next token */
 }
@@ -5523,10 +5890,9 @@ mapObj *msLoadMapFromString(char *buffer, char *new_mappath)
 
   debuglevel = (int)msGetGlobalDebugLevel();
 
-  if (debuglevel >= MS_DEBUGLEVEL_TUNING)
-  {
-      /* In debug mode, track time spent loading/parsing mapfile. */
-      msGettimeofday(&starttime, NULL);
+  if (debuglevel >= MS_DEBUGLEVEL_TUNING) {
+    /* In debug mode, track time spent loading/parsing mapfile. */
+    msGettimeofday(&starttime, NULL);
   }
 
   if(!buffer) {
@@ -5555,9 +5921,9 @@ mapObj *msLoadMapFromString(char *buffer, char *new_mappath)
 
   /* If new_mappath is provided then use it, otherwise use the CWD */
   if(NULL == getcwd(szCWDPath, MS_MAXPATHLEN)) {
-     msSetError(MS_MISCERR, "getcwd() returned a too long path", "msLoadMapFromString()");
-     msFreeMap(map);
-     msReleaseLock( TLOCK_PARSER );
+    msSetError(MS_MISCERR, "getcwd() returned a too long path", "msLoadMapFromString()");
+    msFreeMap(map);
+    msReleaseLock( TLOCK_PARSER );
   }
   if (new_mappath) {
     mappath = msStrdup(new_mappath);
@@ -5575,19 +5941,18 @@ mapObj *msLoadMapFromString(char *buffer, char *new_mappath)
   }
   msReleaseLock( TLOCK_PARSER );
 
-  if (debuglevel >= MS_DEBUGLEVEL_TUNING)
-  {
-      /* In debug mode, report time spent loading/parsing mapfile. */
-      msGettimeofday(&endtime, NULL);
-      msDebug("msLoadMap(): %.3fs\n", 
-              (endtime.tv_sec+endtime.tv_usec/1.0e6)-
-              (starttime.tv_sec+starttime.tv_usec/1.0e6) );
+  if (debuglevel >= MS_DEBUGLEVEL_TUNING) {
+    /* In debug mode, report time spent loading/parsing mapfile. */
+    msGettimeofday(&endtime, NULL);
+    msDebug("msLoadMap(): %.3fs\n",
+            (endtime.tv_sec+endtime.tv_usec/1.0e6)-
+            (starttime.tv_sec+starttime.tv_usec/1.0e6) );
   }
 
   if (mappath != NULL) free(mappath);
   msyylex_destroy();
 
-  if (msResolveSymbolNames(map) == MS_FAILURE) return NULL;
+  if (resolveSymbolNames(map) == MS_FAILURE) return NULL;
 
   return map;
 }
@@ -5604,17 +5969,16 @@ mapObj *msLoadMap(char *filename, char *new_mappath)
 
   debuglevel = (int)msGetGlobalDebugLevel();
 
-  if (debuglevel >= MS_DEBUGLEVEL_TUNING)
-  {
-      /* In debug mode, track time spent loading/parsing mapfile. */
-      msGettimeofday(&starttime, NULL);
+  if (debuglevel >= MS_DEBUGLEVEL_TUNING) {
+    /* In debug mode, track time spent loading/parsing mapfile. */
+    msGettimeofday(&starttime, NULL);
   }
 
   if(!filename) {
     msSetError(MS_MISCERR, "Filename is undefined.", "msLoadMap()");
     return(NULL);
   }
-  
+
   if(getenv("MS_MAPFILE_PATTERN")) { /* user override */
     if(msEvalRegex(getenv("MS_MAPFILE_PATTERN"), filename) != MS_TRUE) {
       msSetError(MS_REGEXERR, "MS_MAPFILE_PATTERN validation failed." , "msLoadMap()");
@@ -5626,7 +5990,7 @@ mapObj *msLoadMap(char *filename, char *new_mappath)
       return(NULL);
     }
   }
- 
+
   /*
   ** Allocate mapObj structure
   */
@@ -5637,36 +6001,32 @@ mapObj *msLoadMap(char *filename, char *new_mappath)
     msFree(map);
     return(NULL);
   }
-  
+
   msAcquireLock( TLOCK_PARSER );  /* Steve: might need to move this lock a bit higher; Umberto: done */
 
 #ifdef USE_XMLMAPFILE
   /* If the mapfile is an xml mapfile, transform it */
-  if ((getenv("MS_XMLMAPFILE_XSLT")) && 
+  if ((getenv("MS_XMLMAPFILE_XSLT")) &&
       (msEvalRegex(MS_DEFAULT_XMLMAPFILE_PATTERN, filename) == MS_TRUE)) {
 
-      msyyin = tmpfile();
-      if (msyyin == NULL)
-      {
-          msSetError(MS_IOERR, "tmpfile() failed to create temporary file", "msLoadMap()");
-          msReleaseLock( TLOCK_PARSER );
-      }
-      
-      if (msTransformXmlMapfile(getenv("MS_XMLMAPFILE_XSLT"), filename, msyyin) != MS_SUCCESS)
-      {
-          fclose(msyyin);
-          return NULL;
-      }
-      fseek ( msyyin , 0 , SEEK_SET );
-  }
-  else
-  {
+    msyyin = tmpfile();
+    if (msyyin == NULL) {
+      msSetError(MS_IOERR, "tmpfile() failed to create temporary file", "msLoadMap()");
+      msReleaseLock( TLOCK_PARSER );
+    }
+
+    if (msTransformXmlMapfile(getenv("MS_XMLMAPFILE_XSLT"), filename, msyyin) != MS_SUCCESS) {
+      fclose(msyyin);
+      return NULL;
+    }
+    fseek ( msyyin , 0 , SEEK_SET );
+  } else {
 #endif
-      if((msyyin = fopen(filename,"r")) == NULL) {
-          msSetError(MS_IOERR, "(%s)", "msLoadMap()", filename);
-          msReleaseLock( TLOCK_PARSER );
-          return NULL;
-      }
+    if((msyyin = fopen(filename,"r")) == NULL) {
+      msSetError(MS_IOERR, "(%s)", "msLoadMap()", filename);
+      msReleaseLock( TLOCK_PARSER );
+      return NULL;
+    }
 #ifdef USE_XMLMAPFILE
   }
 #endif
@@ -5680,11 +6040,11 @@ mapObj *msLoadMap(char *filename, char *new_mappath)
   /* If new_mappath is provided then use it, otherwise use the location */
   /* of the mapfile as the default path */
   if(NULL == getcwd(szCWDPath, MS_MAXPATHLEN)) {
-     msSetError(MS_MISCERR, "getcwd() returned a too long path", "msLoadMap()");
-     msFreeMap(map);
-     msReleaseLock( TLOCK_PARSER );
+    msSetError(MS_MISCERR, "getcwd() returned a too long path", "msLoadMap()");
+    msFreeMap(map);
+    msReleaseLock( TLOCK_PARSER );
   }
-  
+
   if (new_mappath)
     map->mappath = msStrdup(msBuildPath(szPath, szCWDPath, msStrdup(new_mappath)));
   else {
@@ -5699,20 +6059,19 @@ mapObj *msLoadMap(char *filename, char *new_mappath)
     msFreeMap(map);
     msReleaseLock( TLOCK_PARSER );
     if( msyyin ) {
-        fclose(msyyin);
-        msyyin = NULL;
+      fclose(msyyin);
+      msyyin = NULL;
     }
     return NULL;
   }
   msReleaseLock( TLOCK_PARSER );
 
-  if (debuglevel >= MS_DEBUGLEVEL_TUNING)
-  {
-      /* In debug mode, report time spent loading/parsing mapfile. */
-      msGettimeofday(&endtime, NULL);
-      msDebug("msLoadMap(): %.3fs\n", 
-              (endtime.tv_sec+endtime.tv_usec/1.0e6)-
-              (starttime.tv_sec+starttime.tv_usec/1.0e6) );
+  if (debuglevel >= MS_DEBUGLEVEL_TUNING) {
+    /* In debug mode, report time spent loading/parsing mapfile. */
+    msGettimeofday(&endtime, NULL);
+    msDebug("msLoadMap(): %.3fs\n",
+            (endtime.tv_sec+endtime.tv_usec/1.0e6)-
+            (starttime.tv_sec+starttime.tv_usec/1.0e6) );
   }
 
   return map;
@@ -5738,176 +6097,190 @@ int msUpdateMapFromURL(mapObj *map, char *variable, char *string)
   ms_error->code = MS_NOERR; /* init error code */
 
   switch(msyylex()) {
-  case(MAP):
-    switch(msyylex()) {
-    case(CONFIG): {
-        char *key=NULL, *value=NULL;
-        if((getString(&key) != MS_FAILURE) && (getString(&value) != MS_FAILURE)) {
-          msSetConfigOption( map, key, value );
-          free( key ); key=NULL;
-          free( value ); value=NULL;
+    case(MAP):
+      switch(msyylex()) {
+        case(CONFIG): {
+          char *key=NULL, *value=NULL;
+          if((getString(&key) != MS_FAILURE) && (getString(&value) != MS_FAILURE)) {
+            msSetConfigOption( map, key, value );
+            free( key );
+            key=NULL;
+            free( value );
+            value=NULL;
+          }
         }
-      } break;
-    case(EXTENT):
-      msyystate = MS_TOKENIZE_URL_STRING; msyystring = string;
-      msyylex();
-
-      if(getDouble(&(map->extent.minx)) == -1) break;
-      if(getDouble(&(map->extent.miny)) == -1) break;
-      if(getDouble(&(map->extent.maxx)) == -1) break;
-      if(getDouble(&(map->extent.maxy)) == -1) break;
-      if (!MS_VALID_EXTENT(map->extent)) {
-        msSetError(MS_MISCERR, "Given map extent is invalid. Check that it is in the form: minx, miny, maxx, maxy", "msLoadMapParameterFromUrl()"); 
         break;
-      }
-      msMapComputeGeotransform( map );
-      break;
-    case(ANGLE): {
-        double rotation_angle;
-        msyystate = MS_TOKENIZE_URL_STRING; msyystring = string;
-        msyylex();
-      
-        if(getDouble(&(rotation_angle)) == -1) break;
-        msMapSetRotation( map, rotation_angle );
-      } break;
-    case(IMAGECOLOR):
-      msyystate = MS_TOKENIZE_URL_STRING; msyystring = string;
-      msyylex();
-      
-      if(loadColor(&(map->imagecolor), NULL) != MS_SUCCESS) break;
-      break;
-    case(IMAGETYPE):
-      msyystate = MS_TOKENIZE_URL_STRING; msyystring = string;
-      msyylex();
+        case(EXTENT):
+          msyystate = MS_TOKENIZE_URL_STRING;
+          msyystring = string;
+          msyylex();
+
+          if(getDouble(&(map->extent.minx)) == -1) break;
+          if(getDouble(&(map->extent.miny)) == -1) break;
+          if(getDouble(&(map->extent.maxx)) == -1) break;
+          if(getDouble(&(map->extent.maxy)) == -1) break;
+          if (!MS_VALID_EXTENT(map->extent)) {
+            msSetError(MS_MISCERR, "Given map extent is invalid. Check that it is in the form: minx, miny, maxx, maxy", "msLoadMapParameterFromUrl()");
+            break;
+          }
+          msMapComputeGeotransform( map );
+          break;
+        case(ANGLE): {
+          double rotation_angle;
+          msyystate = MS_TOKENIZE_URL_STRING;
+          msyystring = string;
+          msyylex();
+
+          if(getDouble(&(rotation_angle)) == -1) break;
+          msMapSetRotation( map, rotation_angle );
+        }
+        break;
+        case(IMAGECOLOR):
+          msyystate = MS_TOKENIZE_URL_STRING;
+          msyystring = string;
+          msyylex();
 
-      /* TODO: should validate or does msPostMapParseOutputFormatSetup() do enough? */
+          if(loadColor(&(map->imagecolor), NULL) != MS_SUCCESS) break;
+          break;
+        case(IMAGETYPE):
+          msyystate = MS_TOKENIZE_URL_STRING;
+          msyystring = string;
+          msyylex();
 
-      map->imagetype = getToken();
-      msPostMapParseOutputFormatSetup( map );
-      break;
-    case(LAYER):
-      if((s = getSymbol(2, MS_NUMBER, MS_STRING)) == -1) {
-        return MS_FAILURE;
-      }
-      if(s == MS_STRING)
-        i = msGetLayerIndex(map, msyystring_buffer);
-      else
-        i = (int) msyynumber;
+          /* TODO: should validate or does msPostMapParseOutputFormatSetup() do enough? */
 
-      if(i>=map->numlayers || i<0) {
-        msSetError(MS_MISCERR, "Layer to be modified not valid.", "msUpdateMapFromURL()");
-        return MS_FAILURE;
-      }
+          map->imagetype = getToken();
+          msPostMapParseOutputFormatSetup( map );
+          break;
+        case(LAYER):
+          if((s = getSymbol(2, MS_NUMBER, MS_STRING)) == -1) {
+            return MS_FAILURE;
+          }
+          if(s == MS_STRING)
+            i = msGetLayerIndex(map, msyystring_buffer);
+          else
+            i = (int) msyynumber;
 
-      /* make sure this layer can be modified */
-      if(msLookupHashTable(&(GET_LAYER(map, i)->validation), "immutable"))
-        return(MS_SUCCESS); /* fail silently */
+          if(i>=map->numlayers || i<0) {
+            msSetError(MS_MISCERR, "Layer to be modified not valid.", "msUpdateMapFromURL()");
+            return MS_FAILURE;
+          }
 
-      if(msyylex() == CLASS) {
-        if((s = getSymbol(2, MS_NUMBER, MS_STRING)) == -1) return MS_FAILURE;
-        if(s == MS_STRING)
-          j = msGetClassIndex(GET_LAYER(map, i), msyystring_buffer);
-        else
-          j = (int) msyynumber;
+          /* make sure this layer can be modified */
+          if(msLookupHashTable(&(GET_LAYER(map, i)->validation), "immutable"))
+            return(MS_SUCCESS); /* fail silently */
 
-        if(j>=GET_LAYER(map, i)->numclasses || j<0) {
-          msSetError(MS_MISCERR, "Class to be modified not valid.", "msUpdateMapFromURL()");
-          return MS_FAILURE;
-        }
+          if(msyylex() == CLASS) {
+            if((s = getSymbol(2, MS_NUMBER, MS_STRING)) == -1) return MS_FAILURE;
+            if(s == MS_STRING)
+              j = msGetClassIndex(GET_LAYER(map, i), msyystring_buffer);
+            else
+              j = (int) msyynumber;
 
-	/* make sure this class can be modified */
-	if(msLookupHashTable(&(GET_LAYER(map, i)->class[j]->validation), "immutable"))
-	  return(MS_SUCCESS); /* fail silently */
+            if(j>=GET_LAYER(map, i)->numclasses || j<0) {
+              msSetError(MS_MISCERR, "Class to be modified not valid.", "msUpdateMapFromURL()");
+              return MS_FAILURE;
+            }
 
-        if(msyylex() == STYLE) {
-          if(getInteger(&k) == -1) return MS_FAILURE;
+            /* make sure this class can be modified */
+            if(msLookupHashTable(&(GET_LAYER(map, i)->class[j]->validation), "immutable"))
+              return(MS_SUCCESS); /* fail silently */
 
-          if(k>=GET_LAYER(map, i)->class[j]->numstyles || k<0) {
-            msSetError(MS_MISCERR, "Style to be modified not valid.", "msUpdateMapFromURL()");
-            return MS_FAILURE;
-          }
+            if(msyylex() == STYLE) {
+              if(getInteger(&k) == -1) return MS_FAILURE;
 
-          if(msUpdateStyleFromString((GET_LAYER(map, i))->class[j]->styles[k], string, MS_TRUE) != MS_SUCCESS) return MS_FAILURE;
-        } else {
-          if(msUpdateClassFromString((GET_LAYER(map, i))->class[j], string, MS_TRUE) != MS_SUCCESS) return MS_FAILURE;
-	}
-      } else {
-        if(msUpdateLayerFromString((GET_LAYER(map, i)), string, MS_TRUE) != MS_SUCCESS) return MS_FAILURE;
-      }
+              if(k>=GET_LAYER(map, i)->class[j]->numstyles || k<0) {
+                msSetError(MS_MISCERR, "Style to be modified not valid.", "msUpdateMapFromURL()");
+                return MS_FAILURE;
+              }
 
-      /* make sure any symbol names for this layer have been resolved (bug #2700) */
-      for(j=0; j<GET_LAYER(map, i)->numclasses; j++) {
-        for(k=0; k<GET_LAYER(map, i)->class[j]->numstyles; k++) {
-          if(GET_LAYER(map, i)->class[j]->styles[k]->symbolname && GET_LAYER(map, i)->class[j]->styles[k]->symbol == 0) {
-            if((GET_LAYER(map, i)->class[j]->styles[k]->symbol =  msGetSymbolIndex(&(map->symbolset), GET_LAYER(map, i)->class[j]->styles[k]->symbolname, MS_TRUE)) == -1) {
-              msSetError(MS_MISCERR, "Undefined symbol \"%s\" in class %d, style %d of layer %s.", "msUpdateMapFromURL()", GET_LAYER(map, i)->class[j]->styles[k]->symbolname, j, k, GET_LAYER(map, i)->name);
-              return MS_FAILURE;
+              if(msUpdateStyleFromString((GET_LAYER(map, i))->class[j]->styles[k], string, MS_TRUE) != MS_SUCCESS) return MS_FAILURE;
+            } else {
+              if(msUpdateClassFromString((GET_LAYER(map, i))->class[j], string, MS_TRUE) != MS_SUCCESS) return MS_FAILURE;
             }
+          } else {
+            if(msUpdateLayerFromString((GET_LAYER(map, i)), string, MS_TRUE) != MS_SUCCESS) return MS_FAILURE;
           }
-          if(!MS_IS_VALID_ARRAY_INDEX(GET_LAYER(map, i)->class[j]->styles[k]->symbol, map->symbolset.numsymbols)) {
-            msSetError(MS_MISCERR, "Invalid symbol index in class %d, style %d of layer %s.", "msUpdateMapFromURL()", j, k, GET_LAYER(map, i)->name);
-            return MS_FAILURE;
+
+          /* make sure any symbol names for this layer have been resolved (bug #2700) */
+          for(j=0; j<GET_LAYER(map, i)->numclasses; j++) {
+            for(k=0; k<GET_LAYER(map, i)->class[j]->numstyles; k++) {
+              if(GET_LAYER(map, i)->class[j]->styles[k]->symbolname && GET_LAYER(map, i)->class[j]->styles[k]->symbol == 0) {
+                if((GET_LAYER(map, i)->class[j]->styles[k]->symbol =  msGetSymbolIndex(&(map->symbolset), GET_LAYER(map, i)->class[j]->styles[k]->symbolname, MS_TRUE)) == -1) {
+                  msSetError(MS_MISCERR, "Undefined symbol \"%s\" in class %d, style %d of layer %s.", "msUpdateMapFromURL()", GET_LAYER(map, i)->class[j]->styles[k]->symbolname, j, k, GET_LAYER(map, i)->name);
+                  return MS_FAILURE;
+                }
+              }
+              if(!MS_IS_VALID_ARRAY_INDEX(GET_LAYER(map, i)->class[j]->styles[k]->symbol, map->symbolset.numsymbols)) {
+                msSetError(MS_MISCERR, "Invalid symbol index in class %d, style %d of layer %s.", "msUpdateMapFromURL()", j, k, GET_LAYER(map, i)->name);
+                return MS_FAILURE;
+              }
+            }
           }
-        }
-      }
 
-      break;
-    case(LEGEND):
-      return msUpdateLegendFromString(&(map->legend), string, MS_TRUE);
-    case(PROJECTION):
-      msLoadProjectionString(&(map->projection), string);
-      break;
-    case(QUERYMAP):
-      return msUpdateQueryMapFromString(&(map->querymap), string, MS_TRUE);
-    case(REFERENCE):
-      return msUpdateReferenceMapFromString(&(map->reference), string, MS_TRUE);
-    case(RESOLUTION):
-      msyystate = MS_TOKENIZE_URL_STRING; msyystring = string;
-      msyylex();
-
-      if(getDouble(&(map->resolution)) == -1) break;      
-      break;
-    case(DEFRESOLUTION):
-      msyystate = MS_TOKENIZE_URL_STRING; msyystring = string;
-      msyylex();
+          break;
+        case(LEGEND):
+          return msUpdateLegendFromString(&(map->legend), string, MS_TRUE);
+        case(PROJECTION):
+          msLoadProjectionString(&(map->projection), string);
+          break;
+        case(QUERYMAP):
+          return msUpdateQueryMapFromString(&(map->querymap), string, MS_TRUE);
+        case(REFERENCE):
+          return msUpdateReferenceMapFromString(&(map->reference), string, MS_TRUE);
+        case(RESOLUTION):
+          msyystate = MS_TOKENIZE_URL_STRING;
+          msyystring = string;
+          msyylex();
+
+          if(getDouble(&(map->resolution)) == -1) break;
+          break;
+        case(DEFRESOLUTION):
+          msyystate = MS_TOKENIZE_URL_STRING;
+          msyystring = string;
+          msyylex();
 
-      if(getDouble(&(map->defresolution)) == -1) break;      
-      break;    case(SCALEBAR):
-      return msUpdateScalebarFromString(&(map->scalebar), string, MS_TRUE);      
-    case(SIZE):
-      msyystate = MS_TOKENIZE_URL_STRING; msyystring = string;
-      msyylex();
+          if(getDouble(&(map->defresolution)) == -1) break;
+          break;
+        case(SCALEBAR):
+          return msUpdateScalebarFromString(&(map->scalebar), string, MS_TRUE);
+        case(SIZE):
+          msyystate = MS_TOKENIZE_URL_STRING;
+          msyystring = string;
+          msyylex();
+
+          if(getInteger(&(map->width)) == -1) break;
+          if(getInteger(&(map->height)) == -1) break;
+
+          if(map->width > map->maxsize || map->height > map->maxsize || map->width < 0 || map->height < 0) {
+            msSetError(MS_WEBERR, "Image size out of range.", "msUpdateMapFromURL()");
+            break;
+          }
+          msMapComputeGeotransform( map );
+          break;
+        case(TRANSPARENT):
+          msyystate = MS_TOKENIZE_URL_STRING;
+          msyystring = string;
+          msyylex();
 
-      if(getInteger(&(map->width)) == -1) break;
-      if(getInteger(&(map->height)) == -1) break;
+          if((map->transparent = getSymbol(2, MS_ON,MS_OFF)) == -1) break;
+          msPostMapParseOutputFormatSetup( map );
+          break;
+        case(UNITS):
+          msyystate = MS_TOKENIZE_URL_STRING;
+          msyystring = string;
+          msyylex();
 
-      if(map->width > map->maxsize || map->height > map->maxsize || map->width < 0 || map->height < 0) {
-        msSetError(MS_WEBERR, "Image size out of range.", "msUpdateMapFromURL()");
-        break;
+          if((map->units = getSymbol(7, MS_INCHES,MS_FEET,MS_MILES,MS_METERS,MS_KILOMETERS,MS_NAUTICALMILES,MS_DD)) == -1) break;
+          break;
+        case(WEB):
+          return msUpdateWebFromString(&(map->web), string, MS_TRUE);
+        default:
+          break; /* malformed string */
       }
-      msMapComputeGeotransform( map );
-      break;
-    case(TRANSPARENT):
-      msyystate = MS_TOKENIZE_URL_STRING; msyystring = string;
-      msyylex();
-
-      if((map->transparent = getSymbol(2, MS_ON,MS_OFF)) == -1) break;
-      msPostMapParseOutputFormatSetup( map );
       break;
-    case(UNITS):
-      msyystate = MS_TOKENIZE_URL_STRING; msyystring = string;
-      msyylex();
-
-      if((map->units = getSymbol(7, MS_INCHES,MS_FEET,MS_MILES,MS_METERS,MS_KILOMETERS,MS_NAUTICALMILES,MS_DD)) == -1) break;
-      break;
-    case(WEB):
-      return msUpdateWebFromString(&(map->web), string, MS_TRUE);
     default:
-      break; /* malformed string */
-    }
-    break;
-  default:
-    break;
+      break;
   }
 
   /* msyystate = 3; */ /* restore lexer state */
@@ -5918,7 +6291,8 @@ int msUpdateMapFromURL(mapObj *map, char *variable, char *string)
   return(MS_SUCCESS);
 }
 
-static int layerNeedsSubstitutions(layerObj *layer, char *from) {
+static int layerNeedsSubstitutions(layerObj *layer, char *from)
+{
   int i;
 
   if(layer->data && (strcasestr(layer->data, from) != NULL)) return MS_TRUE;
@@ -5929,6 +6303,7 @@ static int layerNeedsSubstitutions(layerObj *layer, char *from) {
   for(i=0; i<layer->numclasses; i++) {
     if(layer->class[i]->expression.string && (strcasestr(layer->class[i]->expression.string, from) != NULL)) return MS_TRUE;
     if(layer->class[i]->text.string && (strcasestr(layer->class[i]->text.string, from) != NULL)) return MS_TRUE;
+    if(layer->class[i]->title && (strcasestr(layer->class[i]->title, from) != NULL)) return MS_TRUE;
   }
 
   if(!msHashIsEmpty(&layer->bindvals)) return MS_TRUE;
@@ -5936,7 +6311,8 @@ static int layerNeedsSubstitutions(layerObj *layer, char *from) {
   return MS_FALSE;
 }
 
-static void layerSubstituteString(layerObj *layer, char *from, char *to) {
+static void layerSubstituteString(layerObj *layer, char *from, char *to)
+{
   int i;
   char *bindvals_key, *bindvals_val;
 
@@ -5946,10 +6322,9 @@ static void layerSubstituteString(layerObj *layer, char *from, char *to) {
   if(layer->filter.string) layer->filter.string = msCaseReplaceSubstring(layer->filter.string, from, to);
 
   for(i=0; i<layer->numclasses; i++) {
-    if(layer->class[i]->expression.string)
-      layer->class[i]->expression.string = msCaseReplaceSubstring(layer->class[i]->expression.string, from, to);
-    if(layer->class[i]->text.string)
-      layer->class[i]->text.string = msCaseReplaceSubstring(layer->class[i]->text.string, from, to);
+    if(layer->class[i]->expression.string) layer->class[i]->expression.string = msCaseReplaceSubstring(layer->class[i]->expression.string, from, to);
+    if(layer->class[i]->text.string) layer->class[i]->text.string = msCaseReplaceSubstring(layer->class[i]->text.string, from, to);
+    if(layer->class[i]->title) layer->class[i]->title = msCaseReplaceSubstring(layer->class[i]->title, from, to);
   }
 
   /* The bindvalues are most useful when able to substitute values from the URL */
@@ -5961,30 +6336,75 @@ static void layerSubstituteString(layerObj *layer, char *from, char *to) {
   }
 }
 
-/* 
+static void applyOutputFormatDefaultSubstitutions(outputFormatObj *format, const char *option, hashTableObj *table)
+{
+  const char *filename;
+
+  filename = msGetOutputFormatOption(format, option, NULL);
+  if(filename && strlen(filename)>0) {
+    char *tmpfilename = msStrdup(filename);
+    const char *default_key = msFirstKeyFromHashTable(table);
+    while(default_key) {
+      if(!strncmp(default_key,"default_",8)) {
+        char *new_filename = NULL;
+        size_t buffer_size = (strlen(default_key)-5);
+        char *tag = (char *)msSmallMalloc(buffer_size);
+        snprintf(tag, buffer_size, "%%%s%%", &(default_key[8]));
+
+        new_filename = msStrdup(tmpfilename);
+        new_filename = msCaseReplaceSubstring(new_filename, tag, msLookupHashTable(table, default_key));
+        free(tag);
+
+        msSetOutputFormatOption(format, option, new_filename);
+        free(new_filename);
+      }
+      default_key = msNextKeyFromHashTable(table, default_key);
+    }
+    msFree(tmpfilename);
+  }
+  return;
+}
+
+static void applyLayerDefaultSubstitutions(layerObj *layer, hashTableObj *table)
+{
+  const char *default_key = msFirstKeyFromHashTable(table);
+  while(default_key) {
+    if(!strncmp(default_key,"default_",8)) {
+      size_t buffer_size = (strlen(default_key)-5);
+      char *tag = (char *)msSmallMalloc(buffer_size);
+      snprintf(tag, buffer_size, "%%%s%%", &(default_key[8]));
+
+      layerSubstituteString(layer, tag, msLookupHashTable(table, default_key));
+      free(tag);
+    }
+    default_key = msNextKeyFromHashTable(table, default_key);
+  }
+  return;
+}
+
+/*
 ** Loop through layer metadata for keys that have a default_%key% pattern to replace
-** remaining %key% entries by their default value. 
+** remaining %key% entries by their default value.
 */
-void msApplyDefaultSubstitutions(mapObj *map) {
+void msApplyDefaultSubstitutions(mapObj *map)
+{
   int i;
-  for(i=0;i<map->numlayers;i++) {
+
+  /* output formats (#3751) */
+  for(i=0; i<map->numoutputformats; i++) {
+    applyOutputFormatDefaultSubstitutions(map->outputformatlist[i], "filename", &(map->web.validation));
+    applyOutputFormatDefaultSubstitutions(map->outputformatlist[i], "filename", &(map->web.metadata));
+  }
+
+  for(i=0; i<map->numlayers; i++) {
     layerObj *layer = GET_LAYER(map, i);
-    const char *defaultkey = msFirstKeyFromHashTable(&(layer->metadata));
-    while(defaultkey) {
-      if(!strncmp(defaultkey,"default_",8)){
-          size_t buffer_size = (strlen(defaultkey)-5);
-        char *tmpstr = (char *)msSmallMalloc(buffer_size);
-        snprintf(tmpstr, buffer_size, "%%%s%%", &(defaultkey[8]));
-
-        layerSubstituteString(layer,tmpstr,msLookupHashTable(&(layer->metadata),defaultkey));
-        free(tmpstr);
-      }
-      defaultkey = msNextKeyFromHashTable(&(layer->metadata),defaultkey);
-    }
+    applyLayerDefaultSubstitutions(layer, &(layer->validation));
+    applyLayerDefaultSubstitutions(layer, &(layer->metadata));
   }
 }
 
-void msApplySubstitutions(mapObj *map, char **names, char **values, int npairs) {
+void msApplySubstitutions(mapObj *map, char **names, char **values, int npairs)
+{
   int i,j;
 
   char *tag=NULL;
@@ -6000,17 +6420,29 @@ void msApplySubstitutions(mapObj *map, char **names, char **values, int npairs)
     validation_pattern_key = (char *) msSmallMalloc(sizeof(char)*strlen(names[i]) + 20);
     sprintf(validation_pattern_key,"%s_validation_pattern", names[i]);
 
+    /* output formats (#3751) */
+    for(j=0; j<map->numoutputformats; j++) {
+      const char *filename = msGetOutputFormatOption(map->outputformatlist[j], "FILENAME", NULL);
+      if(filename && (strcasestr(filename, tag) != NULL)) {
+        if(msValidateParameter(values[i], msLookupHashTable(&(map->web.validation), names[i]), msLookupHashTable(&(map->web.metadata), validation_pattern_key), NULL, NULL) == MS_SUCCESS) {
+          char *new_filename = msStrdup(filename);
+          new_filename = msCaseReplaceSubstring(new_filename, tag, values[i]);
+          msSetOutputFormatOption(map->outputformatlist[j], "FILENAME", new_filename);
+          free(new_filename);
+        }
+      }
+    }
+
     for(j=0; j<map->numlayers; j++) {
       layerObj *layer = GET_LAYER(map, j);
 
       if(!layerNeedsSubstitutions(layer, tag)) continue;
 
-      if( layer->debug >= MS_DEBUGLEVEL_V ) 
-          msDebug( "  runtime substitution - Layer %s, tag %s...\n", 
-                   layer->name, tag);
+      if(layer->debug >= MS_DEBUGLEVEL_V)
+        msDebug( "  runtime substitution - Layer %s, tag %s...\n", layer->name, tag);
 
       if(msValidateParameter(values[i], msLookupHashTable(&(layer->validation), names[i]),  msLookupHashTable(&(map->web.validation), names[i]),
-                                        msLookupHashTable(&(layer->metadata), validation_pattern_key), msLookupHashTable(&(map->web.validation), validation_pattern_key)) == MS_SUCCESS) {
+                             msLookupHashTable(&(layer->metadata), validation_pattern_key), msLookupHashTable(&(map->web.metadata), validation_pattern_key)) == MS_SUCCESS) {
         layerSubstituteString(layer, tag, values[i]);
       }
     }
@@ -6038,7 +6470,7 @@ static char **tokenizeMapInternal(char *filename, int *ret_numtokens)
     msSetError(MS_MISCERR, "Filename is undefined.", "msTokenizeMap()");
     return NULL;
   }
-  
+
   /*
   ** Check map filename to make sure it's legal
   */
@@ -6067,7 +6499,7 @@ static char **tokenizeMapInternal(char *filename, int *ret_numtokens)
   msyylineno = 1;
 
   numtokens = 0;
-  numtokens_allocated = 256; 
+  numtokens_allocated = 256;
   tokens = (char **) malloc(numtokens_allocated*sizeof(char*));
   if(tokens == NULL) {
     msSetError(MS_MEMERR, NULL, "msTokenizeMap()");
@@ -6077,7 +6509,7 @@ static char **tokenizeMapInternal(char *filename, int *ret_numtokens)
 
   for(;;) {
 
-    if(numtokens_allocated <= numtokens) {        
+    if(numtokens_allocated <= numtokens) {
       numtokens_allocated *= 2; /* double size of the array every time we reach the limit */
       tokens = (char **)realloc(tokens, numtokens_allocated*sizeof(char*));
       if(tokens == NULL) {
@@ -6086,10 +6518,10 @@ static char **tokenizeMapInternal(char *filename, int *ret_numtokens)
         return NULL;
       }
     }
- 
-    switch(msyylex()) {   
-      case(EOF): /* This is the normal way out... cleanup and exit */        
-        fclose(msyyin);      
+
+    switch(msyylex()) {
+      case(EOF): /* This is the normal way out... cleanup and exit */
+        fclose(msyyin);
         *ret_numtokens = numtokens;
         return(tokens);
         break;
@@ -6139,65 +6571,43 @@ char **msTokenizeMap(char *filename, int *numtokens)
   return tokens;
 }
 
-void msCloseConnections(mapObj *map) {
+void msCloseConnections(mapObj *map)
+{
   int i;
   layerObj *lp;
 
-  for (i=0;i<map->numlayers;i++) {
+  for (i=0; i<map->numlayers; i++) {
     lp = (GET_LAYER(map, i));
 
     /* If the vtable is null, then the layer is never accessed or used -> skip it
      */
     if (lp->vtable) {
-        lp->vtable->LayerCloseConnection(lp);
+      lp->vtable->LayerCloseConnection(lp);
     }
   }
 }
 
 void initResultCache(resultCacheObj *resultcache)
 {
-    if (resultcache)
-    {
-        resultcache->results = NULL;
-        resultcache->numresults = 0;
-        resultcache->cachesize = 0;
-        resultcache->bounds.minx = resultcache->bounds.miny = resultcache->bounds.maxx = resultcache->bounds.maxy = -1;
-        resultcache->usegetshape = MS_FALSE;
-    }
+  if (resultcache) {
+    resultcache->results = NULL;
+    resultcache->numresults = 0;
+    resultcache->cachesize = 0;
+    resultcache->bounds.minx = resultcache->bounds.miny = resultcache->bounds.maxx = resultcache->bounds.maxy = -1;
+    resultcache->usegetshape = MS_FALSE;
+  }
 }
 
-static int msResolveSymbolNames(mapObj* map)
+static int resolveSymbolNames(mapObj* map)
 {
-    int i, j, k;
-    /* step through layers and classes to resolve symbol names */
-    for(i=0; i<map->numlayers; i++) {
-        for(j=0; j<GET_LAYER(map, i)->numclasses; j++) {
-            /* class styles */
-            for(k=0; k<GET_LAYER(map, i)->class[j]->numstyles; k++) {
-                if(GET_LAYER(map, i)->class[j]->styles[k]->symbolname) {
-                    if((GET_LAYER(map, i)->class[j]->styles[k]->symbol =  msGetSymbolIndex(&(map->symbolset), GET_LAYER(map, i)->class[j]->styles[k]->symbolname, MS_TRUE)) == -1) {
-                        msSetError(MS_MISCERR, "Undefined symbol \"%s\" in class %d, style %d of layer %s.", "msLoadMap()", GET_LAYER(map, i)->class[j]->styles[k]->symbolname, j, k, GET_LAYER(map, i)->name);
-                        return MS_FAILURE;
-                    }
-                }
-                if(!MS_IS_VALID_ARRAY_INDEX(GET_LAYER(map, i)->class[j]->styles[k]->symbol, map->symbolset.numsymbols)) {
-                    msSetError(MS_MISCERR, "Invalid symbol index in class %d, style %d of layer %s.", "msLoadMap()", j, k, GET_LAYER(map, i)->name);
-                    return MS_FAILURE;
-                }
-            }
+  int i, j;
 
-            /* label styles */
-            for(k=0; k<GET_LAYER(map, i)->class[j]->label.numstyles; k++) {
-                if(GET_LAYER(map, i)->class[j]->label.styles[k]->symbolname) {
-                    if((GET_LAYER(map, i)->class[j]->label.styles[k]->symbol =  msGetSymbolIndex(&(map->symbolset), GET_LAYER(map, i)->class[j]->label.styles[k]->symbolname, MS_TRUE)) == -1) {
-                        msSetError(MS_MISCERR, "Undefined symbol \"%s\" in class %d, label style %d of layer %s.", 
-                                   "msLoadMap()", GET_LAYER(map, i)->class[j]->label.styles[k]->symbolname, j, k, GET_LAYER(map, i)->name);
-                        return MS_FAILURE;
-                    }
-                }
-            }          
-        }
+  /* step through layers and classes to resolve symbol names */
+  for(i=0; i<map->numlayers; i++) {
+    for(j=0; j<GET_LAYER(map, i)->numclasses; j++) {
+      if(classResolveSymbolNames(GET_LAYER(map, i)->class[j]) != MS_SUCCESS) return MS_FAILURE;
     }
+  }
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
diff --git a/mapfile.h b/mapfile.h
index f53e015..219081b 100644
--- a/mapfile.h
+++ b/mapfile.h
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -207,14 +207,14 @@ enum MS_TOKEN_SOURCES {MS_FILE_TOKENS=0, MS_STRING_TOKENS, MS_URL_TOKENS};
 #define FILEPATTERN 1151
 #define TEMPLATEPATTERN 1152
 
-#define PROCESSING	1153
+#define PROCESSING  1153
 
 /* The DEBUG macro is also used to request debugging output.  Redefine
    for keyword purposes.  */
 
 #ifdef DEBUG
 #undef DEBUG
-#endif 
+#endif
 
 #define DEBUG 1154
 
@@ -234,7 +234,7 @@ enum MS_TOKEN_SOURCES {MS_FILE_TOKENS=0, MS_STRING_TOKENS, MS_URL_TOKENS};
 
 #define OUTLINEWIDTH 1166
 
- /* Color Range support (was Gradient Support)*/
+/* Color Range support (was Gradient Support)*/
 #define COLORRANGE 1170
 #define DATARANGE 1172
 #define RANGEITEM 1173
@@ -297,7 +297,19 @@ enum MS_TOKEN_SOURCES {MS_FILE_TOKENS=0, MS_STRING_TOKENS, MS_URL_TOKENS};
 #define MAXDISTANCE 1227
 #define REGION 1228
 
+#define INITIALGAP 1229
+#define ANCHORPOINT 1230
+
+#define MASK 1250
+
+#define POLAROFFSET 1251
+
+/* rfc78 leader-lines labels */
+#define LEADER 1260
+#define GRIDSTEP 1261
+
 /* rfc59 bindvals objects */
 #define BINDVALS 2000
 
+
 #endif /* MAPFILE_H */
diff --git a/mapgd.c b/mapgd.c
index ba83956..9e7e22d 100644
--- a/mapgd.c
+++ b/mapgd.c
@@ -27,6 +27,8 @@
  * DEALINGS IN THE SOFTWARE.
  *****************************************************************************/
 #include "mapserver.h"
+#ifdef USE_GD
+
 #include "mapthread.h"
 #include <time.h>
 #include <gdfonts.h>
@@ -40,11 +42,53 @@
 #include <io.h>
 #endif
 
+int msGDSetup()
+{
+  if (gdFontCacheSetup() != 0) {
+    return MS_FAILURE;
+  }
+  return MS_SUCCESS;
+}
+
+void msGDCleanup(int signal)
+{
+  if(!signal) {
+    /* there's a potential deadlock if we're killed by a signal and the font
+     cache is already locked. We don't tear down the fontcache in this case
+     to avoid it (issue 4093)*/
+    gdFontCacheShutdown();
+  }
+}
+
 #define MS_IMAGE_GET_GDIMAGEPTR(image) ((gdImagePtr) image->img.plugin)
 
 fontMetrics bitmapFontMetricsGD[5];
 
-int msImageSetPenGD(gdImagePtr img, colorObj *color) 
+gdFontPtr msGetBitmapFont(int size)
+{
+  switch(size) { /* set the font to use */
+    case MS_TINY:
+      return gdFontGetTiny();
+      break;
+    case MS_SMALL:
+      return gdFontGetSmall();
+      break;
+    case MS_MEDIUM:
+      return gdFontGetMediumBold();
+      break;
+    case MS_LARGE:
+      return gdFontGetLarge();
+      break;
+    case MS_GIANT:
+      return gdFontGetGiant();
+      break;
+    default:
+      msSetError(MS_GDERR,"Invalid bitmap font. Must be one of tiny, small, medium, large or giant." , "msGetBitmapFont()");
+      return(NULL);
+  }
+}
+
+int msImageSetPenGD(gdImagePtr img, colorObj *color)
 {
   if(MS_VALID_COLOR(*color))
     color->pen = gdImageColorResolve(img, color->red, color->green, color->blue);
@@ -54,32 +98,36 @@ int msImageSetPenGD(gdImagePtr img, colorObj *color)
   return(MS_SUCCESS);
 }
 
-int startNewLayerGD(imageObj *img, mapObj *map, layerObj *layer) {
-	return MS_SUCCESS;
+int startNewLayerGD(imageObj *img, mapObj *map, layerObj *layer)
+{
+  return MS_SUCCESS;
 }
 
-int closeNewLayerGD(imageObj *img, mapObj *map, layerObj *layer) {
-	return MS_SUCCESS;
+int closeNewLayerGD(imageObj *img, mapObj *map, layerObj *layer)
+{
+  return MS_SUCCESS;
 }
 
 /*
 ** GD driver-specific image handling functions.
 */
-imageObj *createImageGD(int width, int height, outputFormatObj *format, colorObj* bg) 
+imageObj *createImageGD(int width, int height, outputFormatObj *format, colorObj* bg)
 {
   imageObj *img = NULL;
   gdImagePtr ip;
 
   img = (imageObj *) calloc(1, sizeof (imageObj));
-  MS_CHECK_ALLOC(img, sizeof (imageObj), NULL); 
+  MS_CHECK_ALLOC(img, sizeof (imageObj), NULL);
 
   /* we're only doing PC256 for the moment */
   ip = gdImageCreate(width, height);
-  if(!format->transparent && bg && MS_VALID_COLOR(*bg))
-	  gdImageColorAllocate(ip, bg->red, bg->green, bg->blue); /* set the background color */
-  else {
-	  gdImageColorAllocate(ip,117,17,91); /*random bg color (same one as picked in msResampleGDALToMap) */
-	  gdImageColorTransparent(ip, 0);
+  if(bg && MS_VALID_COLOR(*bg)) {
+    gdImageColorAllocate(ip, bg->red, bg->green, bg->blue); /* set the background color */
+  } else {
+    gdImageColorAllocate(ip,117,17,91); /*random bg color (same one as picked in msResampleGDALToMap) */
+  }
+  if(format->transparent || !bg || !MS_VALID_COLOR(*bg)) {
+    gdImageColorTransparent(ip, 0);
   }
 
   img->img.plugin = (void *) ip;
@@ -88,18 +136,18 @@ imageObj *createImageGD(int width, int height, outputFormatObj *format, colorObj
 
 
 
-int saveImageGD(imageObj *img, FILE *fp, outputFormatObj *format) 
+int saveImageGD(imageObj *img, mapObj *map, FILE *fp, outputFormatObj *format)
 {
   gdImagePtr ip;
 
   if(!img || !fp) return MS_FAILURE;
   if(!(ip = MS_IMAGE_GET_GDIMAGEPTR(img))) return MS_FAILURE;
-  
+
   return saveGdImage(ip,fp,format);
-  
+
 }
 
-int freeImageGD(imageObj *img) 
+int freeImageGD(imageObj *img)
 {
   gdImagePtr ip;
 
@@ -107,7 +155,7 @@ int freeImageGD(imageObj *img)
     ip = MS_IMAGE_GET_GDIMAGEPTR(img);
     if(ip) gdImageDestroy(ip);
   }
-  
+
   return MS_SUCCESS;
 }
 
@@ -146,34 +194,34 @@ static void imageFilledPolygon(gdImagePtr im, shapeObj *p, int c)
     int l;             /* line number */
     int s;             /* scanline */
   } pEdge;
-     
+
   pointObj *point1, *point2;
-     
+
   int k, l, i, j, xl, xr, ymin, ymax, y, n,nvert, nact, m;
   int wrong_order;
-     
+
   pEdge *edge, *temp;
   pEdge  **active;
   int *yhist, *edgeindex;
-     
+
   if(p->numlines == 0) return;
   n=0;
-     
+
   for(i=0; i<p->numlines; i++) {
-   n += p->line[i].numpoints;
+    n += p->line[i].numpoints;
   }
-     
+
   if(n == 0)   return;
 
   edge = (pEdge *) msSmallCalloc(n,sizeof(pEdge));           /* All edges in the polygon */
   edgeindex =  (int *) msSmallCalloc(n,sizeof(int));         /* Index to edges sorted by scanline */
   active = (pEdge **) msSmallCalloc(n,sizeof(pEdge*));       /* Pointers to active edges for current scanline */
-    
+
   nvert=0;
-     
+
   ymin= (int) ceil(p->line[0].point[0].y-0.5);
   ymax= (int) floor(p->line[0].point[0].y-0.5);
-     
+
   /* populate the edge table */
   for(l=0; l<p->numlines; l++) {
     for(i=0; i < p->line[l].numpoints; i++) {
@@ -185,63 +233,63 @@ static void imageFilledPolygon(gdImagePtr im, shapeObj *p, int c)
         point2 = &(p->line[l].point[i]);
         point1 = &(p->line[l].point[j]);
       }
-               
+
       edge[nvert].dx  = point2->y == point1->y ? 0 :  (point2->x - point1->x) / (point2->y - point1->y);
       edge[nvert].s = MS_NINT( p->line[l].point[i].y );  /* ceil( p->line[l].point[i].y  - 0.5 ); */
       edge[nvert].x = point1->x;
       edge[nvert].i = nvert;
       edge[nvert].l = l;
-               
+
       ymin = MS_MIN(ymin,edge[nvert].s);
       ymax = MS_MAX(ymax,edge[nvert].s);
 
       nvert++;
     }
   }
-   
+
   /* Use histogram sort to create a bucket-sorted edgeindex by scanline */
   yhist = (int*) msSmallCalloc(ymax - ymin + 2, sizeof(int));
 
-  for(i=0;i<nvert;i++) {
+  for(i=0; i<nvert; i++) {
     yhist[ edge[i].s - ymin + 1 ]++;
   }
   for(i=0; i<=(ymax - ymin); i++)  {/* Calculate starting point in edgeindex for each scanline */
-    yhist[i+1] += yhist[i]; 
+    yhist[i+1] += yhist[i];
   }
-  for(i=0;i<nvert;i++){ /* Bucket sort edges into edgeindex */
+  for(i=0; i<nvert; i++) { /* Bucket sort edges into edgeindex */
     y = edge[i].s;
     edgeindex[yhist[y-ymin]] = i;
     yhist[y-ymin]++;
   }
   free(yhist);
-   
+
   k=0;
   nact=0;
 
   for (y=ymin; y<=ymax; y++) { /* step through scanlines */
     /* scanline y is at y+.5 in continuous coordinates */
-          
+
     /* check vertices between previous scanline and current one, if any */
     for (; k<nvert && edge[edgeindex[k]].s <= y; k++) {
       i = edge[edgeindex[k]].i;
-               
+
       /* vertex previous to i */
       if(i==0 || edge[i].l != edge[i-1].l)
         j = i +  p->line[edge[i].l].numpoints - 1;
       else
         j = i - 1;
-               
+
       if (edge[j].s  <=  y  ) { /* old edge, remove from active list */
         for (m=0; m<nact && active[m]->i!=j; m++);
-          if (m<nact) {
-            nact--;
-            active[m]=active[nact];
-          }
+        if (m<nact) {
+          nact--;
+          active[m]=active[nact];
+        }
       } else if (edge[j].s > y) { /* new edge,  insert into active list */
         active[nact]= & edge[j];
         nact++;
       }
-               
+
       /* vertex next  after i */
       if(i==nvert-1 || edge[i].l != edge[i+1].l)
         j = i - p->line[edge[i].l].numpoints  + 1;
@@ -250,16 +298,16 @@ static void imageFilledPolygon(gdImagePtr im, shapeObj *p, int c)
 
       if (edge[j].s  <=  y - 1 ) {     /* old edge, remove from active list */
         for (m=0; m<nact && active[m]->i!=i; m++);
-          if (m<nact) {
-            nact--;
-            active[m]=active[nact];
-          }
+        if (m<nact) {
+          nact--;
+          active[m]=active[nact];
+        }
       } else if (edge[j].s > y ) { /* new edge, insert into active list */
         active[nact]= & edge[i];
         nact++;
       }
     }
-          
+
     /* Sort active edges by x */
     do {
       wrong_order = 0;
@@ -272,19 +320,19 @@ static void imageFilledPolygon(gdImagePtr im, shapeObj *p, int c)
     } while(wrong_order);
 
     /* draw horizontal spans for scanline y */
-    for (j=0; j<nact; j+=2) {	
+    for (j=0; j<nact; j+=2) {
       /* j -> j+1 is inside,  j+1 -> j+2 is outside */
-      xl = (int) MS_NINT(active[j]->x );  
+      xl = (int) MS_NINT(active[j]->x );
       xr = (int) (active[j+1]->x - 0.5) ;
 
-      if(active[j]->x != active[j+1]->x) 
+      if(active[j]->x != active[j+1]->x)
         imageScanline(im, xl, xr, y, c);
-               
-      active[j]->x += active[j]->dx;	/* increment edge coords */
+
+      active[j]->x += active[j]->dx;  /* increment edge coords */
       active[j+1]->x += active[j+1]->dx;
     }
   }
-     
+
   free(active);
   free(edgeindex);
   free(edge);
@@ -295,22 +343,22 @@ static void imagePolyline(gdImagePtr im, shapeObj *p, int c)
   int i, j;
 
   for (i=0; i < p->numlines; i++) {
-     lineObj *line = &(p->line[i]);
+    lineObj *line = &(p->line[i]);
     for(j=1; j<line->numpoints; j++) {
-       pointObj *point1 = &line->point[j-1];
-       pointObj *point2 = &line->point[j];
-              
-       gdImageLine(im, (int) point1->x, (int) point1->y, (int) point2->x, (int) point2->y, c);
+      pointObj *point1 = &line->point[j-1];
+      pointObj *point2 = &line->point[j];
+
+      gdImageLine(im, (int) point1->x, (int) point1->y, (int) point2->x, (int) point2->y, c);
     }
   }
 }
 
-int renderLineGD(imageObj *img, shapeObj *p, strokeStyleObj *stroke) 
+int renderLineGD(imageObj *img, shapeObj *p, strokeStyleObj *stroke)
 {
   gdImagePtr ip;
   int c;
   gdImagePtr brush=NULL;
-  
+
   if(!img || !p || !stroke) return MS_FAILURE;
   if(!(ip = MS_IMAGE_GET_GDIMAGEPTR(img))) return MS_FAILURE;
 
@@ -327,7 +375,7 @@ int renderLineGD(imageObj *img, shapeObj *p, strokeStyleObj *stroke)
     style = (int *) malloc (k * sizeof(int));
     MS_CHECK_ALLOC(style, k * sizeof(int), MS_FAILURE);
 
-    sc = c; /* start with the color */    
+    sc = c; /* start with the color */
 
     k=0;
     for(i=0; i<stroke->patternlength; i++) {
@@ -344,34 +392,34 @@ int renderLineGD(imageObj *img, shapeObj *p, strokeStyleObj *stroke)
   }
 
   if(stroke->width > 1) {
-     int brush_fc;
-     brush = gdImageCreate(ceil(stroke->width), ceil(stroke->width));
-     gdImageColorAllocate(brush, gdImageRed(ip,0), gdImageGreen(ip, 0), gdImageBlue(ip, 0));
-     gdImageColorTransparent(brush,0);
-     brush_fc = gdImageColorAllocate(brush, gdImageRed(ip,stroke->color->pen),
-           gdImageGreen(ip,stroke->color->pen), gdImageBlue(ip,stroke->color->pen));
-     gdImageFilledEllipse(brush,MS_NINT(brush->sx/2),MS_NINT(brush->sy/2),
-           MS_NINT(stroke->width),MS_NINT(stroke->width), brush_fc);
-     gdImageSetBrush(ip, brush);
-     if(stroke->patternlength > 0) {
-       c = gdStyledBrushed;
-     } else {
-       c = gdBrushed;
-     }
-  }
-    
+    int brush_fc;
+    brush = gdImageCreate(ceil(stroke->width), ceil(stroke->width));
+    gdImageColorAllocate(brush, gdImageRed(ip,0), gdImageGreen(ip, 0), gdImageBlue(ip, 0));
+    gdImageColorTransparent(brush,0);
+    brush_fc = gdImageColorAllocate(brush, gdImageRed(ip,stroke->color->pen),
+                                    gdImageGreen(ip,stroke->color->pen), gdImageBlue(ip,stroke->color->pen));
+    gdImageFilledEllipse(brush,MS_NINT(brush->sx/2),MS_NINT(brush->sy/2),
+                         MS_NINT(stroke->width),MS_NINT(stroke->width), brush_fc);
+    gdImageSetBrush(ip, brush);
+    if(stroke->patternlength > 0) {
+      c = gdStyledBrushed;
+    } else {
+      c = gdBrushed;
+    }
+  }
+
   /* finally draw something */
   imagePolyline(ip, p, c);
 
   /* clean up */
   if(stroke->width>1) {
-     gdImageDestroy(brush);
+    gdImageDestroy(brush);
   }
   return MS_SUCCESS;
 }
 
-int renderPolygonGD(imageObj *img, shapeObj *p, colorObj *color) 
-{  
+int renderPolygonGD(imageObj *img, shapeObj *p, colorObj *color)
+{
   gdImagePtr ip;
 
   if(!img || !p || !color) return MS_FAILURE;
@@ -381,94 +429,111 @@ int renderPolygonGD(imageObj *img, shapeObj *p, colorObj *color)
   return MS_SUCCESS;
 }
 
-int renderGlyphsLineGD(imageObj *img, labelPathObj *labelpath, labelStyleObj *style, char *text) {
+int renderGlyphsLineGD(imageObj *img, labelPathObj *labelpath, labelStyleObj *style, char *text)
+{
   return MS_SUCCESS;
 }
 
-int renderGlyphsGD(imageObj *img, double x, double y, labelStyleObj *style, char *text) {
-   gdImagePtr ip;
-   char *error=NULL;
-   int bbox[8];
-   x = MS_NINT(x);
-   y = MS_NINT(y);
-   if(!(ip = MS_IMAGE_GET_GDIMAGEPTR(img))) return MS_FAILURE;
-   if(!text || !strlen(text)) return(MS_SUCCESS); /* not errors, just don't want to do anything */
-
-   SETPEN(ip, style->color);
-   SETPEN(ip, style->outlinecolor);
-   
-   if(style->outlinewidth > 0) { /* handle the outline color */
-      error = gdImageStringFT(ip, bbox, style->outlinecolor->pen, style->font, style->size, style->rotation, x, y-1, text);
-      if(error) {
-         msSetError(MS_TTFERR, error, "msDrawTextGD()");
-         return(MS_FAILURE);
-      }
+int renderGlyphsGD(imageObj *img, double x, double y, labelStyleObj *style, char *text)
+{
+  gdImagePtr ip;
+  char *error=NULL;
+  int bbox[8];
+  int c = 0,oc = 0;
+  x = MS_NINT(x);
+  y = MS_NINT(y);
+  if(!(ip = MS_IMAGE_GET_GDIMAGEPTR(img))) return MS_FAILURE;
+  if(!text || !strlen(text)) return(MS_SUCCESS); /* not errors, just don't want to do anything */
+
+  SETPEN(ip, style->color);
+  SETPEN(ip, style->outlinecolor);
+
+  if(style->antialias) {
+    if(style->color)
+      c = style->color->pen;
+    if(style->outlinewidth > 0)
+      oc = style->outlinecolor->pen;
+  } else {
+    if(style->color)
+      c = -style->color->pen;
+    if(style->outlinewidth > 0)
+      oc = -style->outlinecolor->pen;
+  }
 
-      gdImageStringFT(ip, bbox, style->outlinecolor->pen, style->font, style->size, style->rotation, x, y+1, text);
-      gdImageStringFT(ip, bbox, style->outlinecolor->pen, style->font, style->size, style->rotation, x+1, y, text);
-      gdImageStringFT(ip, bbox, style->outlinecolor->pen, style->font, style->size, style->rotation, x-1, y, text);
-      gdImageStringFT(ip, bbox, style->outlinecolor->pen, style->font, style->size, style->rotation, x-1, y-1, text);      
-      gdImageStringFT(ip, bbox, style->outlinecolor->pen, style->font, style->size, style->rotation, x-1, y+1, text);
-      gdImageStringFT(ip, bbox, style->outlinecolor->pen, style->font, style->size, style->rotation, x+1, y-1, text);
-      gdImageStringFT(ip, bbox, style->outlinecolor->pen, style->font, style->size, style->rotation, x+1, y+1, text);
-   }
-   
-   if(style->color)
-      gdImageStringFT(ip, bbox, style->color->pen, style->font, style->size, style->rotation, x, y, text);
-   return MS_SUCCESS;
-}
-
-int renderEllipseSymbolGD(imageObj *img, double x, double y, symbolObj *symbol, symbolStyleObj *style) {
-   /* check for trivial cases - 1x1 and 2x2, GD does not do these well */
-   gdImagePtr ip;
-   int w,h,fc,oc;
-   if(!(ip = MS_IMAGE_GET_GDIMAGEPTR(img))) return MS_FAILURE;
-   SETPEN(ip, style->color);
-   SETPEN(ip, style->outlinecolor);
-   fc = style->color ? style->color->pen : -1;
-   oc = style->outlinecolor ? style->outlinecolor->pen : -1;
-   
-   if(oc==-1 && fc ==-1) {
-      return MS_SUCCESS;
-   }
-   
-   w = symbol->sizex * style->scale;
-   h = symbol->sizey * style->scale;
-   
-   if(w==1 && h==1) {
-      if(fc >= 0)
-         gdImageSetPixel(ip, x, y, fc);
-      else 
-         gdImageSetPixel(ip, x, y, oc);
-      return MS_SUCCESS;
-   }
-
-   if(w==2 && h==2) {
-      if(oc >= 0) {
-         gdImageSetPixel(ip, x, y, oc);
-         gdImageSetPixel(ip, x, y+1, oc);
-         gdImageSetPixel(ip, x+1, y, oc);
-         gdImageSetPixel(ip, x+1, y+1, oc);
-      } else {
-         gdImageSetPixel(ip, x, y, fc);
-         gdImageSetPixel(ip, x, y+1, fc);
-         gdImageSetPixel(ip, x+1, y, fc);
-         gdImageSetPixel(ip, x+1, y+1, fc);
-      }
-      return MS_SUCCESS;
-   }
+  if(style->outlinewidth > 0) { /* handle the outline color */
+    error = gdImageStringFT(ip, bbox, oc, style->fonts[0], style->size, style->rotation, x, y-1, text);
+    if(error) {
+      msSetError(MS_TTFERR, error, "msDrawTextGD()");
+      return(MS_FAILURE);
+    }
 
-   if(symbol->filled) {
-      if(fc >= 0) gdImageFilledEllipse(ip, x, y, w, h, fc);        
-      if(oc >= 0) gdImageArc(ip, x, y, w, h, 0, 360, oc);
-   } else {
-      if(fc < 0) fc = oc; /* try the outline color */
-      gdImageArc(ip, x, y, w, h, 0, 360, fc);
-   }
-   return MS_SUCCESS;
+    gdImageStringFT(ip, bbox, oc, style->fonts[0], style->size, style->rotation, x, y+1, text);
+    gdImageStringFT(ip, bbox, oc, style->fonts[0], style->size, style->rotation, x+1, y, text);
+    gdImageStringFT(ip, bbox, oc, style->fonts[0], style->size, style->rotation, x-1, y, text);
+    gdImageStringFT(ip, bbox, oc, style->fonts[0], style->size, style->rotation, x-1, y-1, text);
+    gdImageStringFT(ip, bbox, oc, style->fonts[0], style->size, style->rotation, x-1, y+1, text);
+    gdImageStringFT(ip, bbox, oc, style->fonts[0], style->size, style->rotation, x+1, y-1, text);
+    gdImageStringFT(ip, bbox, oc, style->fonts[0], style->size, style->rotation, x+1, y+1, text);
+  }
+
+  if(style->color)
+    gdImageStringFT(ip, bbox, c, style->fonts[0], style->size, style->rotation, x, y, text);
+  return MS_SUCCESS;
 }
 
-static void get_bbox(pointObj *poiList, int numpoints, double *minx, double *miny, double *maxx, double *maxy) {
+int renderEllipseSymbolGD(imageObj *img, double x, double y, symbolObj *symbol, symbolStyleObj *style)
+{
+  /* check for trivial cases - 1x1 and 2x2, GD does not do these well */
+  gdImagePtr ip;
+  int w,h,fc,oc;
+  if(!(ip = MS_IMAGE_GET_GDIMAGEPTR(img))) return MS_FAILURE;
+  SETPEN(ip, style->color);
+  SETPEN(ip, style->outlinecolor);
+  fc = style->color ? style->color->pen : -1;
+  oc = style->outlinecolor ? style->outlinecolor->pen : -1;
+
+  if(oc==-1 && fc ==-1) {
+    return MS_SUCCESS;
+  }
+
+  w = symbol->sizex * style->scale;
+  h = symbol->sizey * style->scale;
+
+  if(w==1 && h==1) {
+    if(fc >= 0)
+      gdImageSetPixel(ip, x, y, fc);
+    else
+      gdImageSetPixel(ip, x, y, oc);
+    return MS_SUCCESS;
+  }
+
+  if(w==2 && h==2) {
+    if(oc >= 0) {
+      gdImageSetPixel(ip, x, y, oc);
+      gdImageSetPixel(ip, x, y+1, oc);
+      gdImageSetPixel(ip, x+1, y, oc);
+      gdImageSetPixel(ip, x+1, y+1, oc);
+    } else {
+      gdImageSetPixel(ip, x, y, fc);
+      gdImageSetPixel(ip, x, y+1, fc);
+      gdImageSetPixel(ip, x+1, y, fc);
+      gdImageSetPixel(ip, x+1, y+1, fc);
+    }
+    return MS_SUCCESS;
+  }
+
+  if(symbol->filled) {
+    if(fc >= 0) gdImageFilledEllipse(ip, x, y, w, h, fc);
+    if(oc >= 0) gdImageArc(ip, x, y, w, h, 0, 360, oc);
+  } else {
+    if(fc < 0) fc = oc; /* try the outline color */
+    gdImageArc(ip, x, y, w, h, 0, 360, fc);
+  }
+  return MS_SUCCESS;
+}
+
+static void get_bbox(pointObj *poiList, int numpoints, double *minx, double *miny, double *maxx, double *maxy)
+{
   int j;
 
   *minx = *maxx = poiList[0].x;
@@ -484,274 +549,292 @@ static void get_bbox(pointObj *poiList, int numpoints, double *minx, double *min
   return;
 }
 
-symbolObj* rotateVectorSymbolPoints(symbolObj *symbol, double angle_rad) {
-   double dp_x, dp_y, xcor, ycor;
-   double sin_a, cos_a;
-   double minx,miny,maxx,maxy;
-   symbolObj *newSymbol;
-   double TOL=0.00000000001;
-   int i;
-   
-   angle_rad = -angle_rad;
-   
-   newSymbol = (symbolObj *) msSmallMalloc(sizeof(symbolObj));
-   msCopySymbol(newSymbol, symbol, NULL);
-   
-   sin_a = sin(angle_rad);
-   cos_a = cos(angle_rad);
-
-   dp_x = symbol->sizex * .5; /* get the shift vector at 0,0 */
-   dp_y = symbol->sizey * .5;
-
-   /* center at 0,0 and rotate; then move back */
-   for( i=0;i < symbol->numpoints;i++) {
-      /* don't rotate PENUP commands (TODO: should use a constant here) */
-      if ((symbol->points[i].x == -99.0) && (symbol->points[i].x == -99.0) ) {
-         newSymbol->points[i].x = -99.0;
-         newSymbol->points[i].y = -99.0;
-         continue;
-      }
+symbolObj* rotateVectorSymbolPoints(symbolObj *symbol, double angle_rad)
+{
+  double dp_x, dp_y, xcor, ycor;
+  double sin_a, cos_a;
+  double minx,miny,maxx,maxy;
+  symbolObj *newSymbol;
+  double TOL=0.00000000001;
+  int i;
 
-      newSymbol->points[i].x = dp_x + ((symbol->points[i].x-dp_x)*cos_a - (symbol->points[i].y-dp_y)*sin_a);
-      newSymbol->points[i].y = dp_y + ((symbol->points[i].x-dp_x)*sin_a + (symbol->points[i].y-dp_y)*cos_a);
-   }
-
-   /* get the new bbox of the symbol, because we need it to get the new dimensions of the new symbol */
-   get_bbox(newSymbol->points, newSymbol->numpoints, &minx, &miny, &maxx, &maxy);
-   if ( (fabs(minx)>TOL) || (fabs(miny)>TOL) ) {
-      xcor = minx*-1.0; /* symbols always start at 0,0 so get the shift vector */
-      ycor = miny*-1.0;
-      for( i=0;i < newSymbol->numpoints;i++) {
-         if ((newSymbol->points[i].x == -99.0) && (newSymbol->points[i].x == -99.0))
-            continue;
-         newSymbol->points[i].x = newSymbol->points[i].x + xcor;
-         newSymbol->points[i].y = newSymbol->points[i].y + ycor;
-      }
+  angle_rad = -angle_rad;
 
-      /* update the bbox to get the final dimension values for the symbol */
-      get_bbox(newSymbol->points, newSymbol->numpoints, &minx, &miny, &maxx, &maxy);
-   }
-   newSymbol->sizex = maxx;
-   newSymbol->sizey = maxy;
-   return newSymbol;
-}
-
-int renderVectorSymbolGD(imageObj *img, double x, double y, symbolObj *symbol, symbolStyleObj *style) {
-   int bRotated = MS_FALSE;
-   int j,k;
-   gdImagePtr ip;
-   gdPoint mPoints[MS_MAXVECTORPOINTS];
-   gdPoint oldpnt,newpnt;
-   int fc,oc;
-   if(!(ip = MS_IMAGE_GET_GDIMAGEPTR(img))) return MS_FAILURE;
-   
-   
-   SETPEN(ip, style->color);
-   SETPEN(ip, style->outlinecolor);
-   fc = style->color ? style->color->pen : -1;
-   oc = style->outlinecolor ? style->outlinecolor->pen : -1;
-   
-   if(oc==-1 && fc ==-1) {
-      return MS_SUCCESS;
-   }
-   
-   if (style->rotation != 0.0) {      
-      bRotated = MS_TRUE;
-      symbol = rotateVectorSymbolPoints(symbol, style->rotation);
-      if(!symbol) {
-         return MS_FAILURE;
-      }
-   }
-
-   /* We avoid MS_NINT in this context because the potentially variable
-          handling of 0.5 rounding is often a problem for symbols which are
-          often an odd size (ie. 7pixels) and so if "p" is integral the 
-          value is always on a 0.5 boundary - bug 1716 */
-   x -= style->scale*.5*symbol->sizex;
-   y -= style->scale*.5*symbol->sizey;
-
-   if(symbol->filled) { /* if filled */
-
-      k = 0; /* point counter */
-      for(j=0;j < symbol->numpoints;j++) {
-         if((symbol->points[j].x == -99) && (symbol->points[j].x == -99)) { /* new polygon (PENUP) */
-            if(k>2) {
-               if(fc >= 0)
-                  gdImageFilledPolygon(ip, mPoints, k, fc);
-               if(oc >= 0)
-                  gdImagePolygon(ip, mPoints, k, oc);
-            }
-            k = 0; /* reset point counter */
-         } else {
-            mPoints[k].x = MS_NINT(style->scale*symbol->points[j].x + x);
-            mPoints[k].y = MS_NINT(style->scale*symbol->points[j].y + y); 
-            k++;
-         }
+  newSymbol = (symbolObj *) msSmallMalloc(sizeof(symbolObj));
+  msCopySymbol(newSymbol, symbol, NULL);
+
+  sin_a = sin(angle_rad);
+  cos_a = cos(angle_rad);
+
+  dp_x = symbol->sizex * .5; /* get the shift vector at 0,0 */
+  dp_y = symbol->sizey * .5;
+
+  /* center at 0,0 and rotate; then move back */
+  for( i=0; i < symbol->numpoints; i++) {
+    /* don't rotate PENUP commands (TODO: should use a constant here) */
+    if ((symbol->points[i].x == -99.0) && (symbol->points[i].x == -99.0) ) {
+      newSymbol->points[i].x = -99.0;
+      newSymbol->points[i].y = -99.0;
+      continue;
+    }
+
+    newSymbol->points[i].x = dp_x + ((symbol->points[i].x-dp_x)*cos_a - (symbol->points[i].y-dp_y)*sin_a);
+    newSymbol->points[i].y = dp_y + ((symbol->points[i].x-dp_x)*sin_a + (symbol->points[i].y-dp_y)*cos_a);
+  }
+
+  /* get the new bbox of the symbol, because we need it to get the new dimensions of the new symbol */
+  get_bbox(newSymbol->points, newSymbol->numpoints, &minx, &miny, &maxx, &maxy);
+  if ( (fabs(minx)>TOL) || (fabs(miny)>TOL) ) {
+    xcor = minx*-1.0; /* symbols always start at 0,0 so get the shift vector */
+    ycor = miny*-1.0;
+    for( i=0; i < newSymbol->numpoints; i++) {
+      if ((newSymbol->points[i].x == -99.0) && (newSymbol->points[i].x == -99.0))
+        continue;
+      newSymbol->points[i].x = newSymbol->points[i].x + xcor;
+      newSymbol->points[i].y = newSymbol->points[i].y + ycor;
+    }
+
+    /* update the bbox to get the final dimension values for the symbol */
+    get_bbox(newSymbol->points, newSymbol->numpoints, &minx, &miny, &maxx, &maxy);
+  }
+  newSymbol->sizex = maxx;
+  newSymbol->sizey = maxy;
+  return newSymbol;
+}
+
+int renderVectorSymbolGD(imageObj *img, double x, double y, symbolObj *symbol, symbolStyleObj *style)
+{
+  int bRotated = MS_FALSE;
+  int j,k;
+  gdImagePtr ip;
+  gdPoint mPoints[MS_MAXVECTORPOINTS];
+  gdPoint oldpnt,newpnt;
+  int fc,oc;
+  if(!(ip = MS_IMAGE_GET_GDIMAGEPTR(img))) return MS_FAILURE;
+
+
+  SETPEN(ip, style->color);
+  SETPEN(ip, style->outlinecolor);
+  fc = style->color ? style->color->pen : -1;
+  oc = style->outlinecolor ? style->outlinecolor->pen : -1;
+
+  if(oc==-1 && fc ==-1) {
+    return MS_SUCCESS;
+  }
+
+  if (style->rotation != 0.0) {
+    bRotated = MS_TRUE;
+    symbol = rotateVectorSymbolPoints(symbol, style->rotation);
+    if(!symbol) {
+      return MS_FAILURE;
+    }
+  }
+
+  /* We avoid MS_NINT in this context because the potentially variable
+         handling of 0.5 rounding is often a problem for symbols which are
+         often an odd size (ie. 7pixels) and so if "p" is integral the
+         value is always on a 0.5 boundary - bug 1716 */
+  x -= style->scale*.5*symbol->sizex;
+  y -= style->scale*.5*symbol->sizey;
+
+  if(symbol->filled) { /* if filled */
+
+    k = 0; /* point counter */
+    for(j=0; j < symbol->numpoints; j++) {
+      if((symbol->points[j].x == -99) && (symbol->points[j].x == -99)) { /* new polygon (PENUP) */
+        if(k>2) {
+          if(fc >= 0)
+            gdImageFilledPolygon(ip, mPoints, k, fc);
+          if(oc >= 0)
+            gdImagePolygon(ip, mPoints, k, oc);
+        }
+        k = 0; /* reset point counter */
+      } else {
+        mPoints[k].x = MS_NINT(style->scale*symbol->points[j].x + x);
+        mPoints[k].y = MS_NINT(style->scale*symbol->points[j].y + y);
+        k++;
       }
+    }
 
-      if(fc >= 0)
-         gdImageFilledPolygon(ip, mPoints, k, fc);
-      if(oc >= 0)
-         gdImagePolygon(ip, mPoints, k, oc);
-
-   } else  { /* NOT filled */     
-
-      if(oc >= 0) fc = oc; /* try the outline color (reference maps sometimes do this when combining a box and a custom vector marker */
-      
-      oldpnt.x = MS_NINT(style->scale*symbol->points[0].x + x); /* convert first point in marker */
-      oldpnt.y = MS_NINT(style->scale*symbol->points[0].y + y);
-
-      gdImageSetThickness(ip, style->outlinewidth);
-
-      for(j=1;j < symbol->numpoints;j++) { /* step through the marker */
-         if((symbol->points[j].x != -99) || (symbol->points[j].x != -99)) {
-            if((symbol->points[j-1].x == -99) && (symbol->points[j-1].y == -99)) { /* Last point was PENUP, now a new beginning */
-               oldpnt.x = MS_NINT(style->scale*symbol->points[j].x + x);
-               oldpnt.y = MS_NINT(style->scale*symbol->points[j].y + y);
-            } else {
-               newpnt.x = MS_NINT(style->scale*symbol->points[j].x + x);
-               newpnt.y = MS_NINT(style->scale*symbol->points[j].y + y);
-               gdImageLine(ip, oldpnt.x, oldpnt.y, newpnt.x, newpnt.y, fc);
-               oldpnt = newpnt;
-            }
-         }
-      } /* end for loop */   
-
-      gdImageSetThickness(ip, 1); /* restore thinkness */
-   } /* end if-then-else */
-
-   if(bRotated) {
-      msFreeSymbol(symbol); /* clean up */
-      msFree(symbol);
-   }
-   return MS_SUCCESS;
-}
-
-int renderTruetypeSymbolGD(imageObj *img, double x, double y, symbolObj *symbol, symbolStyleObj *s) {
-   int bbox[8];
-   char *error;
-   gdImagePtr ip;
-   if(!(ip = MS_IMAGE_GET_GDIMAGEPTR(img))) return MS_FAILURE;
-   SETPEN(ip, s->color);
-   SETPEN(ip, s->outlinecolor);
-   gdImageStringFT(NULL, bbox, s->color->pen, symbol->full_font_path, s->scale, s->rotation, 0,0, symbol->character);
-   
-   x -=  (bbox[2] - bbox[0])/2 + bbox[0];
-   y +=  (bbox[1] - bbox[5])/2 - bbox[1];
-
-   if( s->outlinecolor ) {
-      error = gdImageStringFT(ip, bbox, s->outlinecolor->pen, symbol->full_font_path, s->scale, s->rotation, x, y-1, symbol->character);
-      if(error) {
-         msSetError(MS_TTFERR, error, "msDrawMarkerSymbolGD()");
-         return MS_FAILURE;
+    if(fc >= 0)
+      gdImageFilledPolygon(ip, mPoints, k, fc);
+    if(oc >= 0)
+      gdImagePolygon(ip, mPoints, k, oc);
+
+  } else  { /* NOT filled */
+
+    if(oc >= 0) fc = oc; /* try the outline color (reference maps sometimes do this when combining a box and a custom vector marker */
+
+    oldpnt.x = MS_NINT(style->scale*symbol->points[0].x + x); /* convert first point in marker */
+    oldpnt.y = MS_NINT(style->scale*symbol->points[0].y + y);
+
+    gdImageSetThickness(ip, style->outlinewidth);
+
+    for(j=1; j < symbol->numpoints; j++) { /* step through the marker */
+      if((symbol->points[j].x != -99) || (symbol->points[j].x != -99)) {
+        if((symbol->points[j-1].x == -99) && (symbol->points[j-1].y == -99)) { /* Last point was PENUP, now a new beginning */
+          oldpnt.x = MS_NINT(style->scale*symbol->points[j].x + x);
+          oldpnt.y = MS_NINT(style->scale*symbol->points[j].y + y);
+        } else {
+          newpnt.x = MS_NINT(style->scale*symbol->points[j].x + x);
+          newpnt.y = MS_NINT(style->scale*symbol->points[j].y + y);
+          gdImageLine(ip, oldpnt.x, oldpnt.y, newpnt.x, newpnt.y, fc);
+          oldpnt = newpnt;
+        }
       }
+    } /* end for loop */
+
+    gdImageSetThickness(ip, 1); /* restore thinkness */
+  } /* end if-then-else */
 
-      gdImageStringFT(ip, bbox, s->outlinecolor->pen, symbol->full_font_path, s->scale, s->rotation, x, y+1, symbol->character);
-      gdImageStringFT(ip, bbox, s->outlinecolor->pen, symbol->full_font_path, s->scale, s->rotation, x+1, y, symbol->character);
-      gdImageStringFT(ip, bbox, s->outlinecolor->pen, symbol->full_font_path, s->scale, s->rotation, x-1, y, symbol->character);
-      gdImageStringFT(ip, bbox, s->outlinecolor->pen, symbol->full_font_path, s->scale, s->rotation, x+1, y+1, symbol->character);
-      gdImageStringFT(ip, bbox, s->outlinecolor->pen, symbol->full_font_path, s->scale, s->rotation, x+1, y-1, symbol->character);
-      gdImageStringFT(ip, bbox, s->outlinecolor->pen, symbol->full_font_path, s->scale, s->rotation, x-1, y+1, symbol->character);
-      gdImageStringFT(ip, bbox, s->outlinecolor->pen, symbol->full_font_path, s->scale, s->rotation, x-1, y-1, symbol->character);
-   }
-   if(s->color)
-	   gdImageStringFT(ip, bbox, s->color->pen, symbol->full_font_path, s->scale, s->rotation, x, y, symbol->character);
+  if(bRotated) {
+    msFreeSymbol(symbol); /* clean up */
+    msFree(symbol);
+  }
   return MS_SUCCESS;
 }
 
-gdImagePtr rotatePixmapGD(gdImagePtr img, double angle_rad) {
-   gdImagePtr rimg = NULL;
-   double cos_a, sin_a;
-   double x1 = 0.0, y1 = 0.0; /* destination rectangle */
-   double x2 = 0.0, y2 = 0.0;
-   double x3 = 0.0, y3 = 0.0;
-   double x4 = 0.0, y4 = 0.0;
-
-   long minx, miny, maxx, maxy;
-
-   int width=0, height=0;
-   /* int color; */
-
-   sin_a = sin(angle_rad);
-   cos_a = cos(angle_rad);
-
-   /* compute distination rectangle (x1,y1 is known) */
-   x1 = 0 ; y1 = 0 ;
-   x2 = img->sy * sin_a;
-   y2 = -img->sy * cos_a;
-   x3 = (img->sx * cos_a) + (img->sy * sin_a);
-   y3 = (img->sx * sin_a) - (img->sy * cos_a);
-   x4 = (img->sx * cos_a);
-   y4 = (img->sx * sin_a);
-
-   minx = (long) MS_MIN(x1,MS_MIN(x2,MS_MIN(x3,x4)));
-   miny = (long) MS_MIN(y1,MS_MIN(y2,MS_MIN(y3,y4)));
-   maxx = (long) MS_MAX(x1,MS_MAX(x2,MS_MAX(x3,x4)));
-   maxy = (long) MS_MAX(y1,MS_MAX(y2,MS_MAX(y3,y4)));
-
-   width = (int)ceil(maxx-minx);
-   height = (int)ceil(maxy-miny);
-
-   /* create the new image based on the computed width/height */
-   
-   if (gdImageTrueColor(img)) {
-      rimg = gdImageCreateTrueColor(width, height);
-      gdImageAlphaBlending(rimg, 0);
-      gdImageFilledRectangle(rimg, 0, 0, width, height, gdImageColorAllocateAlpha(rimg, 0, 0, 0, gdAlphaTransparent)); 
-   } else {
-      int tc = gdImageGetTransparent(img);
-      rimg = gdImageCreate(width, height);  
-      if(tc != -1)
-         gdImageColorTransparent(rimg, gdImageColorAllocate(rimg, gdImageRed(img, tc), gdImageGreen(img, tc), gdImageBlue(img, tc)));
-   }
-   if(!rimg) {
-      msSetError(MS_GDERR,"failed to create rotated pixmap","rotatePixmapGD()");
-      return NULL;
-   }
-
-   gdImageCopyRotated (rimg, img, width*0.5, height*0.5, 0, 0, gdImageSX(img), gdImageSY(img), angle_rad*MS_RAD_TO_DEG);
-   return rimg;
-}
-
-int renderPixmapSymbolGD(imageObj *img, double x, double y, symbolObj *symbol, symbolStyleObj *style) {
-   gdImagePtr ip,pp;
-   if(!(ip = MS_IMAGE_GET_GDIMAGEPTR(img))) return MS_FAILURE;
-   assert(symbol->pixmap_buffer && symbol->pixmap_buffer->type == MS_BUFFER_GD);
-   pp = symbol->pixmap_buffer->data.gd_img;
-   //gdImageAlphaBlending(ip,1);
-   //gdImageAlphaBlending(pp,1);
-      
-   if(symbol->transparent)
-      gdImageColorTransparent(pp,symbol->transparentcolor);
-   if(style->scale == 1.0 && style->rotation == 0.0) { /* don't scale */
-      x -= .5*symbol->pixmap_buffer->width;
-      y -= .5*symbol->pixmap_buffer->height;
-      gdImageCopy(ip, pp, x, y, 0, 0, symbol->pixmap_buffer->width,symbol->pixmap_buffer->height);
-    } else {
-       int bRotated = MS_FALSE;
-       if(style->rotation) {
-          bRotated = MS_TRUE;
-          pp = rotatePixmapGD(pp,style->rotation);
-       }
-      x -=  .5*gdImageSX(pp)*style->scale;
-      y -=  .5*gdImageSY(pp)*style->scale;
-      gdImageCopyResampled(ip, pp, x, y, 0, 0,
-            (int)(gdImageSX(pp) * style->scale),
-            (int)(gdImageSY(pp) * style->scale),
-            gdImageSX(pp),gdImageSY(pp));
-      if(bRotated) {
-         gdImageDestroy(pp);
-      }
+int renderTruetypeSymbolGD(imageObj *img, double x, double y, symbolObj *symbol, symbolStyleObj *s)
+{
+  int bbox[8];
+  char *error;
+  int c,oc = 0;
+  gdImagePtr ip;
+  if(!(ip = MS_IMAGE_GET_GDIMAGEPTR(img))) return MS_FAILURE;
+  SETPEN(ip, s->color);
+  SETPEN(ip, s->outlinecolor);
+
+  if(s->style->antialias) {
+    c = s->color->pen;
+    if(s->outlinecolor)
+      oc = s->outlinecolor->pen;
+  } else {
+    c = -s->color->pen;
+    if(s->outlinecolor)
+      oc = -s->outlinecolor->pen;
+  }
+  gdImageStringFT(NULL, bbox, c, symbol->full_font_path, s->scale, s->rotation, 0,0, symbol->character);
+
+  x -=  (bbox[2] - bbox[0])/2 + bbox[0];
+  y +=  (bbox[1] - bbox[5])/2 - bbox[1];
+
+  if( s->outlinecolor ) {
+    error = gdImageStringFT(ip, bbox, oc, symbol->full_font_path, s->scale, s->rotation, x, y-1, symbol->character);
+    if(error) {
+      msSetError(MS_TTFERR, error, "msDrawMarkerSymbolGD()");
+      return MS_FAILURE;
     }
-   //gdImageAlphaBlending(ip,0);
-   return MS_SUCCESS;
+
+    gdImageStringFT(ip, bbox, oc, symbol->full_font_path, s->scale, s->rotation, x, y+1, symbol->character);
+    gdImageStringFT(ip, bbox, oc, symbol->full_font_path, s->scale, s->rotation, x+1, y, symbol->character);
+    gdImageStringFT(ip, bbox, oc, symbol->full_font_path, s->scale, s->rotation, x-1, y, symbol->character);
+    gdImageStringFT(ip, bbox, oc, symbol->full_font_path, s->scale, s->rotation, x+1, y+1, symbol->character);
+    gdImageStringFT(ip, bbox, oc, symbol->full_font_path, s->scale, s->rotation, x+1, y-1, symbol->character);
+    gdImageStringFT(ip, bbox, oc, symbol->full_font_path, s->scale, s->rotation, x-1, y+1, symbol->character);
+    gdImageStringFT(ip, bbox, oc, symbol->full_font_path, s->scale, s->rotation, x-1, y-1, symbol->character);
+  }
+  if(s->color)
+    gdImageStringFT(ip, bbox, c, symbol->full_font_path, s->scale, s->rotation, x, y, symbol->character);
+  return MS_SUCCESS;
+}
+
+gdImagePtr rotatePixmapGD(gdImagePtr img, double angle_rad)
+{
+  gdImagePtr rimg = NULL;
+  double cos_a, sin_a;
+  double x1 = 0.0, y1 = 0.0; /* destination rectangle */
+  double x2 = 0.0, y2 = 0.0;
+  double x3 = 0.0, y3 = 0.0;
+  double x4 = 0.0, y4 = 0.0;
+
+  long minx, miny, maxx, maxy;
+
+  int width=0, height=0;
+  /* int color; */
+
+  sin_a = sin(angle_rad);
+  cos_a = cos(angle_rad);
+
+  /* compute distination rectangle (x1,y1 is known) */
+  x1 = 0 ;
+  y1 = 0 ;
+  x2 = img->sy * sin_a;
+  y2 = -img->sy * cos_a;
+  x3 = (img->sx * cos_a) + (img->sy * sin_a);
+  y3 = (img->sx * sin_a) - (img->sy * cos_a);
+  x4 = (img->sx * cos_a);
+  y4 = (img->sx * sin_a);
+
+  minx = (long) MS_MIN(x1,MS_MIN(x2,MS_MIN(x3,x4)));
+  miny = (long) MS_MIN(y1,MS_MIN(y2,MS_MIN(y3,y4)));
+  maxx = (long) MS_MAX(x1,MS_MAX(x2,MS_MAX(x3,x4)));
+  maxy = (long) MS_MAX(y1,MS_MAX(y2,MS_MAX(y3,y4)));
+
+  width = (int)ceil(maxx-minx);
+  height = (int)ceil(maxy-miny);
+
+  /* create the new image based on the computed width/height */
+
+  if (gdImageTrueColor(img)) {
+    rimg = gdImageCreateTrueColor(width, height);
+    gdImageAlphaBlending(rimg, 0);
+    gdImageFilledRectangle(rimg, 0, 0, width, height, gdImageColorAllocateAlpha(rimg, 0, 0, 0, gdAlphaTransparent));
+  } else {
+    int tc = gdImageGetTransparent(img);
+    rimg = gdImageCreate(width, height);
+    if(tc != -1)
+      gdImageColorTransparent(rimg, gdImageColorAllocate(rimg, gdImageRed(img, tc), gdImageGreen(img, tc), gdImageBlue(img, tc)));
+  }
+  if(!rimg) {
+    msSetError(MS_GDERR,"failed to create rotated pixmap","rotatePixmapGD()");
+    return NULL;
+  }
+
+  gdImageCopyRotated (rimg, img, width*0.5, height*0.5, 0, 0, gdImageSX(img), gdImageSY(img), angle_rad*MS_RAD_TO_DEG);
+  return rimg;
 }
 
-int renderTileGD(imageObj *img, imageObj *tile, double x, double y) {
+int renderPixmapSymbolGD(imageObj *img, double x, double y, symbolObj *symbol, symbolStyleObj *style)
+{
+  gdImagePtr ip,pp;
+  if(!(ip = MS_IMAGE_GET_GDIMAGEPTR(img))) return MS_FAILURE;
+  assert(symbol->pixmap_buffer && symbol->pixmap_buffer->type == MS_BUFFER_GD);
+  pp = symbol->pixmap_buffer->data.gd_img;
+  /* gdImageAlphaBlending(ip,1); */
+  /* gdImageAlphaBlending(pp,1); */
+
+  if(symbol->transparent)
+    gdImageColorTransparent(pp,symbol->transparentcolor);
+  if(style->scale == 1.0 && style->rotation == 0.0) { /* don't scale */
+    x -= .5*symbol->pixmap_buffer->width;
+    y -= .5*symbol->pixmap_buffer->height;
+    gdImageCopy(ip, pp, x, y, 0, 0, symbol->pixmap_buffer->width,symbol->pixmap_buffer->height);
+  } else {
+    int bRotated = MS_FALSE;
+    if(style->rotation) {
+      bRotated = MS_TRUE;
+      pp = rotatePixmapGD(pp,style->rotation);
+    }
+    x -=  .5*gdImageSX(pp)*style->scale;
+    y -=  .5*gdImageSY(pp)*style->scale;
+    gdImageCopyResampled(ip, pp, x, y, 0, 0,
+                         (int)(gdImageSX(pp) * style->scale),
+                         (int)(gdImageSY(pp) * style->scale),
+                         gdImageSX(pp),gdImageSY(pp));
+    if(bRotated) {
+      gdImageDestroy(pp);
+    }
+  }
+  /* gdImageAlphaBlending(ip,0); */
   return MS_SUCCESS;
 }
 
-int renderPolygonTiledGD(imageObj *img, shapeObj *p,  imageObj *tile) 
+int renderTileGD(imageObj *img, imageObj *tile, double x, double y)
+{
+  return MS_SUCCESS;
+}
+
+int renderPolygonTiledGD(imageObj *img, shapeObj *p,  imageObj *tile)
 {
   gdImagePtr ip, tp;
 
@@ -765,180 +848,181 @@ int renderPolygonTiledGD(imageObj *img, shapeObj *p,  imageObj *tile)
 }
 
 
-int initializeRasterBufferGD(rasterBufferObj *rb, int width, int height, int mode) {
-	rb->type = MS_BUFFER_GD;
-	rb->data.gd_img = gdImageCreate(width, height);
-	if(!rb->data.gd_img)
-		return MS_FAILURE;
-	rb->width = width;
-	rb->height= height;
-	return MS_SUCCESS;
+int initializeRasterBufferGD(rasterBufferObj *rb, int width, int height, int mode)
+{
+  rb->type = MS_BUFFER_GD;
+  rb->data.gd_img = gdImageCreate(width, height);
+  if(!rb->data.gd_img)
+    return MS_FAILURE;
+  rb->width = width;
+  rb->height= height;
+  return MS_SUCCESS;
 }
 
 /*
 ** GD driver-specific raster buffer functions.
 */
-int getRasterBufferHandleGD(imageObj *img, rasterBufferObj *rb) {
-	gdImagePtr gdImg = MS_IMAGE_GET_GDIMAGEPTR(img);
-	rb->type = MS_BUFFER_GD;
-	rb->data.gd_img = gdImg;
-	rb->width = gdImg->sx;
-	rb->height = gdImg->sy;
-	return MS_SUCCESS;
-
-}
-
-int getRasterBufferCopyGD(imageObj *img, rasterBufferObj *rb) {
-	gdImagePtr gdImg = MS_IMAGE_GET_GDIMAGEPTR(img);
-	int row;
-	rb->type = MS_BUFFER_GD;
-	rb->width = gdImg->sx;
-	rb->height = gdImg->sy;
-	rb->data.gd_img = gdImageCreate(gdImg->sx,gdImg->sy);
-	rb->data.gd_img->transparent = gdImg->transparent;
-	gdImagePaletteCopy(rb->data.gd_img,gdImg);
-	for(row=0;row<gdImg->sy;row++)
-	   memcpy(rb->data.gd_img->pixels[row],gdImg->pixels[row],gdImg->sx);
-	return MS_SUCCESS;
-}
-
-int mergeRasterBufferGD(imageObj *dest, rasterBufferObj *overlay, double opacity, int srcX, int srcY, int dstX, int dstY, int width, int height) {
-	assert(dest && overlay);
-	assert(overlay->type == MS_BUFFER_GD);
-	gdImageCopyMerge(MS_IMAGE_GET_GDIMAGEPTR(dest),overlay->data.gd_img,dstX,dstY,srcX,srcY,width,height,opacity*100);
-	return MS_SUCCESS;
-}
-
-int getTruetypeTextBBoxGD(rendererVTableObj *renderer, char *font, double size, char *string, rectObj *rect, double **advances) {
-#ifdef USE_GD_FT
-   int bbox[8];
-   char *error;
-   if(advances) {
-#if defined (GD_HAS_FTEX_XSHOW)
-      char *s;
-      int k;
-      gdFTStringExtra strex;
-      strex.flags = gdFTEX_XSHOW;
-      error = gdImageStringFTEx(NULL, bbox, 0, font, size, 0, 0, 0, string, &strex);
-      if(error) {
-         msSetError(MS_TTFERR, error, "gdImageStringFTEx()");
-         return(MS_FAILURE);
-      }
+int getRasterBufferHandleGD(imageObj *img, rasterBufferObj *rb)
+{
+  gdImagePtr gdImg = MS_IMAGE_GET_GDIMAGEPTR(img);
+  rb->type = MS_BUFFER_GD;
+  rb->data.gd_img = gdImg;
+  rb->width = gdImg->sx;
+  rb->height = gdImg->sy;
+  return MS_SUCCESS;
 
-      *advances = (double*)malloc( strlen(string) * sizeof(double) );
-      MS_CHECK_ALLOC(*advances, strlen(string) * sizeof(double), MS_FAILURE);
-      s = strex.xshow;
-      k = 0;
-      while ( *s && k < strlen(string) ) {
-         (*advances)[k++] = atof(s);      
-         while ( *s && *s != ' ')
-            s++;
-         if ( *s == ' ' )
-            s++;
-      }
+}
 
-      gdFree(strex.xshow); /* done with character advances */
+int getRasterBufferCopyGD(imageObj *img, rasterBufferObj *rb)
+{
+  gdImagePtr gdImg = MS_IMAGE_GET_GDIMAGEPTR(img);
+  int row;
+  rb->type = MS_BUFFER_GD;
+  rb->width = gdImg->sx;
+  rb->height = gdImg->sy;
+  rb->data.gd_img = gdImageCreate(gdImg->sx,gdImg->sy);
+  rb->data.gd_img->transparent = gdImg->transparent;
+  gdImagePaletteCopy(rb->data.gd_img,gdImg);
+  for(row=0; row<gdImg->sy; row++)
+    memcpy(rb->data.gd_img->pixels[row],gdImg->pixels[row],gdImg->sx);
+  return MS_SUCCESS;
+}
 
-      rect->minx = bbox[0];
-      rect->miny = bbox[5];
-      rect->maxx = bbox[2];
-      rect->maxy = bbox[1];
-      return MS_SUCCESS;
-#else
-      msSetError(MS_TTFERR, "gdImageStringFTEx support is not available or is not current enough (requires 2.0.29 or higher).", "msGetTruetypeTextBBox()");
+int mergeRasterBufferGD(imageObj *dest, rasterBufferObj *overlay, double opacity, int srcX, int srcY, int dstX, int dstY, int width, int height)
+{
+  assert(dest && overlay);
+  assert(overlay->type == MS_BUFFER_GD);
+  gdImageCopyMerge(MS_IMAGE_GET_GDIMAGEPTR(dest),overlay->data.gd_img,dstX,dstY,srcX,srcY,width,height,opacity*100);
+  return MS_SUCCESS;
+}
+
+int getTruetypeTextBBoxGD(rendererVTableObj *renderer, char **fonts, int numfonts, double size, char *string, rectObj *rect, double **advances, int bAdjustBaseline)
+{
+  int bbox[8];
+  char *error;
+  if(advances) {
+    char *s;
+    int k;
+    gdFTStringExtra strex;
+    strex.flags = gdFTEX_XSHOW;
+    error = gdImageStringFTEx(NULL, bbox, 0, fonts[0], size, 0, 0, 0, string, &strex);
+    if(error) {
+      msSetError(MS_TTFERR, error, "gdImageStringFTEx()");
       return(MS_FAILURE);
-#endif
-   } else {
-      error = gdImageStringFT(NULL, bbox, 0, font, size, 0, 0, 0, string);
-      if(error) {
-         msSetError(MS_TTFERR, error, "msGetTruetypeTextBBox()");
-         return(MS_FAILURE);
-      }
+    }
 
-      rect->minx = bbox[0];
-      rect->miny = bbox[5];
-      rect->maxx = bbox[2];
-      rect->maxy = bbox[1];
-      return MS_SUCCESS;
-   }
-#else
-    msSetError(MS_TTFERR,"Truetype support not available", "getTruetypeTextBBoxGD()");
-    return(MS_FAILURE);
-#endif
+    *advances = (double*)malloc( strlen(string) * sizeof(double) );
+    MS_CHECK_ALLOC(*advances, strlen(string) * sizeof(double), MS_FAILURE);
+    s = strex.xshow;
+    k = 0;
+    /* TODO this smells buggy and can cause errors at a higher level. strlen NOK here*/
+    while ( *s && k < strlen(string) ) {
+      (*advances)[k++] = atof(s);
+      while ( *s && *s != ' ')
+        s++;
+      if ( *s == ' ' )
+        s++;
+    }
+
+    gdFree(strex.xshow); /* done with character advances */
+
+    rect->minx = bbox[0];
+    rect->miny = bbox[5];
+    rect->maxx = bbox[2];
+    rect->maxy = bbox[1];
+    return MS_SUCCESS;
+  } else {
+    error = gdImageStringFT(NULL, bbox, 0, fonts[0], size, 0, 0, 0, string);
+    if(error) {
+      msSetError(MS_TTFERR, error, "msGetTruetypeTextBBox()");
+      return(MS_FAILURE);
+    }
+
+    rect->minx = bbox[0];
+    rect->miny = bbox[5];
+    rect->maxx = bbox[2];
+    rect->maxy = bbox[1];
+    return MS_SUCCESS;
+  }
 }
 
-int renderBitmapGlyphsGD(imageObj *img, double x, double y, labelStyleObj *style, char *text) {
-   int size = MS_NINT(style->size);
-   gdFontPtr fontPtr;
-   gdImagePtr ip;
-   int numlines=0,t;
-   char **lines;
-   if(!(ip = MS_IMAGE_GET_GDIMAGEPTR(img))) return MS_FAILURE;
-   if(size<0 || size>4 || (fontPtr = msGetBitmapFont(size))==NULL) {
-      msSetError(MS_RENDERERERR,"invalid bitmap font size", "renderBitmapGlyphsGD()");
-      return MS_FAILURE;
-   }
-   
-   SETPEN(ip, style->color);
-   SETPEN(ip, style->outlinecolor);
-   
-   if(msCountChars(text,'\n')) {
-      if((lines = msStringSplit((const char*)text, '\n', &(numlines))) == NULL)
-         return(-1);
-   } else {
-      lines = &text;
-      numlines = 1;
-   }
-
-   y -= fontPtr->h;
-   for(t=0; t<numlines; t++) {
-      if(style->outlinewidth > 0) {
-         gdImageString(ip, fontPtr, x, y-1,   (unsigned char *) lines[t], style->outlinecolor->pen);
-         gdImageString(ip, fontPtr, x, y+1,   (unsigned char *) lines[t], style->outlinecolor->pen);
-         gdImageString(ip, fontPtr, x+1, y,   (unsigned char *) lines[t], style->outlinecolor->pen);
-         gdImageString(ip, fontPtr, x-1, y,   (unsigned char *) lines[t], style->outlinecolor->pen);
-         gdImageString(ip, fontPtr, x+1, y-1, (unsigned char *) lines[t], style->outlinecolor->pen);
-         gdImageString(ip, fontPtr, x+1, y+1, (unsigned char *) lines[t], style->outlinecolor->pen);
-         gdImageString(ip, fontPtr, x-1, y-1, (unsigned char *) lines[t], style->outlinecolor->pen);
-         gdImageString(ip, fontPtr, x-1, y+1, (unsigned char *) lines[t], style->outlinecolor->pen);
-      }
-      if(style->color->pen != -1) {
-         gdImageString(ip, fontPtr, x, y, (unsigned char *) lines[t], style->color->pen);
-      }
+int renderBitmapGlyphsGD(imageObj *img, double x, double y, labelStyleObj *style, char *text)
+{
+  int size = MS_NINT(style->size);
+  gdFontPtr fontPtr;
+  gdImagePtr ip;
+  int numlines=0,t;
+  char **lines;
+  if(!(ip = MS_IMAGE_GET_GDIMAGEPTR(img))) return MS_FAILURE;
+  if(size<0 || size>4 || (fontPtr = msGetBitmapFont(size))==NULL) {
+    msSetError(MS_RENDERERERR,"invalid bitmap font size", "renderBitmapGlyphsGD()");
+    return MS_FAILURE;
+  }
 
-      y += fontPtr->h; /* shift down */
-   }
+  SETPEN(ip, style->color);
+  SETPEN(ip, style->outlinecolor);
 
+  if(msCountChars(text,'\n')) {
+    if((lines = msStringSplit((const char*)text, '\n', &(numlines))) == NULL)
+      return(-1);
+  } else {
+    lines = &text;
+    numlines = 1;
+  }
+
+  y -= fontPtr->h;
+  for(t=0; t<numlines; t++) {
+    if(style->outlinewidth > 0) {
+      gdImageString(ip, fontPtr, x, y-1,   (unsigned char *) lines[t], style->outlinecolor->pen);
+      gdImageString(ip, fontPtr, x, y+1,   (unsigned char *) lines[t], style->outlinecolor->pen);
+      gdImageString(ip, fontPtr, x+1, y,   (unsigned char *) lines[t], style->outlinecolor->pen);
+      gdImageString(ip, fontPtr, x-1, y,   (unsigned char *) lines[t], style->outlinecolor->pen);
+      gdImageString(ip, fontPtr, x+1, y-1, (unsigned char *) lines[t], style->outlinecolor->pen);
+      gdImageString(ip, fontPtr, x+1, y+1, (unsigned char *) lines[t], style->outlinecolor->pen);
+      gdImageString(ip, fontPtr, x-1, y-1, (unsigned char *) lines[t], style->outlinecolor->pen);
+      gdImageString(ip, fontPtr, x-1, y+1, (unsigned char *) lines[t], style->outlinecolor->pen);
+    }
+    if(style->color->pen != -1) {
+      gdImageString(ip, fontPtr, x, y, (unsigned char *) lines[t], style->color->pen);
+    }
+
+    y += fontPtr->h; /* shift down */
+  }
 
-   if(*lines != text)
-      msFreeCharArray(lines, numlines);
-   return MS_SUCCESS;
+
+  if(*lines != text)
+    msFreeCharArray(lines, numlines);
+  return MS_SUCCESS;
 }
 
 /*
 ** Misc. cleanup functions for GD driver.
 */
 
-int freeSymbolGD(symbolObj *s) {
+int freeSymbolGD(symbolObj *s)
+{
   return MS_SUCCESS;
 }
+#endif
 
-int msPopulateRendererVTableGD( rendererVTableObj *renderer ) {
+int msPopulateRendererVTableGD( rendererVTableObj *renderer )
+{
+#ifdef USE_GD
   int i;
   renderer->use_imagecache=0;
   renderer->supports_pixel_buffer=1;
   renderer->supports_transparent_layers = 0;
   renderer->supports_bitmap_fonts = 1;
   renderer->default_transform_mode = MS_TRANSFORM_ROUND;
-  
-  for(i=0;i<5;i++) {
-     gdFontPtr f = msGetBitmapFont(i);
-     bitmapFontMetricsGD[i].charWidth = f->w;
-     bitmapFontMetricsGD[i].charHeight = f->h;
-     renderer->bitmapFontMetrics[i] = &bitmapFontMetricsGD[i];
-  }
-    
-  
+
+  for(i=0; i<5; i++) {
+    gdFontPtr f = msGetBitmapFont(i);
+    bitmapFontMetricsGD[i].charWidth = f->w;
+    bitmapFontMetricsGD[i].charHeight = f->h;
+    renderer->bitmapFontMetrics[i] = &bitmapFontMetricsGD[i];
+  }
+
+
   renderer->startLayer = startNewLayerGD;
   renderer->endLayer = closeNewLayerGD;
   renderer->renderLineTiled = NULL;
@@ -963,4 +1047,9 @@ int msPopulateRendererVTableGD( rendererVTableObj *renderer ) {
   renderer->renderPolygonTiled = &renderPolygonTiledGD;
   renderer->freeSymbol = &freeSymbolGD;
   return MS_SUCCESS;
+#else
+  msSetError(MS_MISCERR,"GD renderer requested but it is not configured in this build","msPopulateRendererVtableGD()");
+  return MS_FAILURE;
+#endif
 }
+
diff --git a/mapgdal.c b/mapgdal.c
index 2d0f3a7..ac05bcb 100644
--- a/mapgdal.c
+++ b/mapgdal.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -31,7 +31,7 @@
 #include "mapserver.h"
 #include "mapthread.h"
 
-MS_CVSID("$Id$")
+
 
 #if defined(USE_GDAL) || defined(USE_OGR)
 #include "cpl_conv.h"
@@ -52,16 +52,15 @@ static int    bGDALInitialized = 0;
 void msGDALInitialize( void )
 
 {
-    if( !bGDALInitialized )
-    {
-        msAcquireLock( TLOCK_GDAL );
+  if( !bGDALInitialized ) {
+    msAcquireLock( TLOCK_GDAL );
 
-        GDALAllRegister();
-        CPLPushErrorHandler( CPLQuietErrorHandler );
-        msReleaseLock( TLOCK_GDAL );
+    GDALAllRegister();
+    CPLPushErrorHandler( CPLQuietErrorHandler );
+    msReleaseLock( TLOCK_GDAL );
 
-        bGDALInitialized = 1;
-    }
+    bGDALInitialized = 1;
+  }
 }
 
 /************************************************************************/
@@ -71,53 +70,49 @@ void msGDALInitialize( void )
 void msGDALCleanup( void )
 
 {
-    if( bGDALInitialized )
-    {
-        int iRepeat = 5;
-        msAcquireLock( TLOCK_GDAL );
+  if( bGDALInitialized ) {
+    int iRepeat = 5;
+    msAcquireLock( TLOCK_GDAL );
 
 #if GDAL_RELEASE_DATE > 20101207
-        {
-            /* 
-            ** Cleanup any unreferenced but open datasets as will tend
-            ** to exist due to deferred close requests.  We are careful
-            ** to only close one file at a time before refecting the
-            ** list as closing some datasets may cause others to be 
-            ** closed (subdatasets in a VRT for instance).
-            */
-            GDALDatasetH *pahDSList = NULL;
-            int nDSCount = 0;
-            int bDidSomething;
-
-            do {
-                int i;
-                GDALGetOpenDatasets( &pahDSList, &nDSCount );
-                bDidSomething = FALSE;
-                for( i = 0; i < nDSCount && !bDidSomething; i++ )
-                {
-                    if( GDALReferenceDataset( pahDSList[i] ) == 1 )
-                    {
-                        GDALClose( pahDSList[i] );
-                        bDidSomething = TRUE;
-                    }
-                    else
-                        GDALDereferenceDataset( pahDSList[i] );
-                }
-            } while( bDidSomething );
+    {
+      /*
+      ** Cleanup any unreferenced but open datasets as will tend
+      ** to exist due to deferred close requests.  We are careful
+      ** to only close one file at a time before refecting the
+      ** list as closing some datasets may cause others to be
+      ** closed (subdatasets in a VRT for instance).
+      */
+      GDALDatasetH *pahDSList = NULL;
+      int nDSCount = 0;
+      int bDidSomething;
+
+      do {
+        int i;
+        GDALGetOpenDatasets( &pahDSList, &nDSCount );
+        bDidSomething = FALSE;
+        for( i = 0; i < nDSCount && !bDidSomething; i++ ) {
+          if( GDALReferenceDataset( pahDSList[i] ) == 1 ) {
+            GDALClose( pahDSList[i] );
+            bDidSomething = TRUE;
+          } else
+            GDALDereferenceDataset( pahDSList[i] );
         }
+      } while( bDidSomething );
+    }
 #endif
 
-        while( iRepeat-- )
-            CPLPopErrorHandler();
+    while( iRepeat-- )
+      CPLPopErrorHandler();
 
 #if GDAL_RELEASE_DATE > 20021001
-        GDALDestroyDriverManager();
+    GDALDestroyDriverManager();
 #endif
 
-        msReleaseLock( TLOCK_GDAL );
+    msReleaseLock( TLOCK_GDAL );
 
-        bGDALInitialized = 0;
-    }
+    bGDALInitialized = 0;
+  }
 }
 
 /************************************************************************/
@@ -130,19 +125,18 @@ void msGDALCleanup( void )
 void CleanVSIDir( const char *pszDir )
 
 {
-    char **papszFiles = CPLReadDir( pszDir );
-    int i, nFileCount = CSLCount( papszFiles );
+  char **papszFiles = CPLReadDir( pszDir );
+  int i, nFileCount = CSLCount( papszFiles );
 
-    for( i = 0; i < nFileCount; i++ )
-    {
-        if( strcasecmp(papszFiles[i],".") == 0 
-            || strcasecmp(papszFiles[i],"..") == 0 )
-            continue;
+  for( i = 0; i < nFileCount; i++ ) {
+    if( strcasecmp(papszFiles[i],".") == 0
+        || strcasecmp(papszFiles[i],"..") == 0 )
+      continue;
 
-        VSIUnlink( papszFiles[i] );
-    }
+    VSIUnlink( papszFiles[i] );
+  }
 
-    CSLDestroy( papszFiles );
+  CSLDestroy( papszFiles );
 }
 
 /************************************************************************/
@@ -152,438 +146,406 @@ void CleanVSIDir( const char *pszDir )
 int msSaveImageGDAL( mapObj *map, imageObj *image, char *filename )
 
 {
-    int  bFileIsTemporary = MS_FALSE;
-    GDALDatasetH hMemDS, hOutputDS;
-    GDALDriverH  hMemDriver, hOutputDriver;
-    int          nBands = 1;
-    int          iLine;
-    GByte       *pabyAlphaLine = NULL;
-    char        **papszOptions = NULL;
-    outputFormatObj *format = image->format;
-    rasterBufferObj rb;
-    GDALDataType eDataType = GDT_Byte;
-
-    msGDALInitialize();
-    memset(&rb,0,sizeof(rasterBufferObj));
-
-/* -------------------------------------------------------------------- */
-/*      Identify the proposed output driver.                            */
-/* -------------------------------------------------------------------- */
-    msAcquireLock( TLOCK_GDAL );
-    hOutputDriver = GDALGetDriverByName( format->driver+5 );
-    if( hOutputDriver == NULL )
-    {
-        msReleaseLock( TLOCK_GDAL );
-        msSetError( MS_MISCERR, "Failed to find %s driver.",
-                    "msSaveImageGDAL()", format->driver+5 );
-        return MS_FAILURE;
-    }
-
-/* -------------------------------------------------------------------- */
-/*      We will need to write the output to a temporary file and        */
-/*      then stream to stdout if no filename is passed.  If the         */
-/*      driver supports virtualio then we hold the temporary file in    */
-/*      memory, otherwise we try to put it in a reasonable temporary    */
-/*      file location.                                                  */
-/* -------------------------------------------------------------------- */
-    if( filename == NULL )
-    {
-        const char *pszExtension = format->extension;
-        if( pszExtension == NULL )
-            pszExtension = "img.tmp";
-
-#ifdef GDAL_DCAP_VIRTUALIO
-        if( GDALGetMetadataItem( hOutputDriver, GDAL_DCAP_VIRTUALIO, NULL ) 
-            != NULL )
-        {
-            CleanVSIDir( "/vsimem/msout" );
-            filename = msTmpFile(map, NULL, "/vsimem/msout/", pszExtension );
-        }
+  int  bFileIsTemporary = MS_FALSE;
+  GDALDatasetH hMemDS, hOutputDS;
+  GDALDriverH  hMemDriver, hOutputDriver;
+  int          nBands = 1;
+  int          iLine;
+  GByte       *pabyAlphaLine = NULL;
+  char        **papszOptions = NULL;
+  outputFormatObj *format = image->format;
+  rasterBufferObj rb;
+  GDALDataType eDataType = GDT_Byte;
+  int bUseXmp = MS_FALSE;
+
+  msGDALInitialize();
+  memset(&rb,0,sizeof(rasterBufferObj));
+
+#ifdef USE_EXEMPI
+  bUseXmp = msXmpPresent(map);
 #endif
-        if( filename == NULL && map != NULL)
-            filename = msTmpFile(map, map->mappath,NULL,pszExtension);
-        else if( filename == NULL )
-        {
-            filename = msTmpFile(map, NULL, NULL, pszExtension );
-        }
-            
-        bFileIsTemporary = MS_TRUE;
-    }
-    
-/* -------------------------------------------------------------------- */
-/*      Establish the characteristics of our memory, and final          */
-/*      dataset.                                                        */
-/* -------------------------------------------------------------------- */
 
-    if( format->imagemode == MS_IMAGEMODE_RGB )
-    {
-        nBands = 3;
-        assert( MS_RENDERER_PLUGIN(format) && format->vtable->supports_pixel_buffer );
-        format->vtable->getRasterBufferHandle(image,&rb);
-    }
-    else if( format->imagemode == MS_IMAGEMODE_RGBA )
-    {
-        pabyAlphaLine = (GByte *) calloc(image->width,1);
-        if (pabyAlphaLine == NULL)
-        {
-            msReleaseLock( TLOCK_GDAL );
-            msSetError( MS_MEMERR, "Out of memory allocating %u bytes.\n", "msSaveImageGDAL()", image->width);
-            return MS_FAILURE;
-        }
-        nBands = 4;
-        assert( MS_RENDERER_PLUGIN(format) && format->vtable->supports_pixel_buffer );
-        format->vtable->getRasterBufferHandle(image,&rb);
-    }
-    else if( format->imagemode == MS_IMAGEMODE_INT16 )
-    {
-        nBands = format->bands;
-        eDataType = GDT_Int16;
-    }
-    else if( format->imagemode == MS_IMAGEMODE_FLOAT32 )
-    {
-        nBands = format->bands;
-        eDataType = GDT_Float32;
-    }
-    else if( format->imagemode == MS_IMAGEMODE_BYTE )
-    {
-        nBands = format->bands;
-        eDataType = GDT_Byte;
+
+  /* -------------------------------------------------------------------- */
+  /*      Identify the proposed output driver.                            */
+  /* -------------------------------------------------------------------- */
+  msAcquireLock( TLOCK_GDAL );
+  hOutputDriver = GDALGetDriverByName( format->driver+5 );
+  if( hOutputDriver == NULL ) {
+    msReleaseLock( TLOCK_GDAL );
+    msSetError( MS_MISCERR, "Failed to find %s driver.",
+                "msSaveImageGDAL()", format->driver+5 );
+    return MS_FAILURE;
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      We will need to write the output to a temporary file and        */
+  /*      then stream to stdout if no filename is passed.  If the         */
+  /*      driver supports virtualio then we hold the temporary file in    */
+  /*      memory, otherwise we try to put it in a reasonable temporary    */
+  /*      file location.                                                  */
+  /* -------------------------------------------------------------------- */
+  if( filename == NULL ) {
+    const char *pszExtension = format->extension;
+    if( pszExtension == NULL )
+      pszExtension = "img.tmp";
+
+    if( bUseXmp == MS_FALSE && GDALGetMetadataItem( hOutputDriver, GDAL_DCAP_VIRTUALIO, NULL )
+        != NULL ) {
+      CleanVSIDir( "/vsimem/msout" );
+      filename = msTmpFile(map, NULL, "/vsimem/msout/", pszExtension );
     }
-    else
-    {
-        assert( format->imagemode == MS_IMAGEMODE_PC256
-                && format->renderer == MS_RENDER_WITH_GD );
+
+    if( filename == NULL && map != NULL)
+      filename = msTmpFile(map, map->mappath,NULL,pszExtension);
+    else if( filename == NULL ) {
+      filename = msTmpFile(map, NULL, NULL, pszExtension );
     }
 
-/* -------------------------------------------------------------------- */
-/*      Create a memory dataset which we can use as a source for a      */
-/*      CreateCopy().                                                   */
-/* -------------------------------------------------------------------- */
-    hMemDriver = GDALGetDriverByName( "MEM" );
-    if( hMemDriver == NULL )
-    {
-        msReleaseLock( TLOCK_GDAL );
-        msSetError( MS_MISCERR, "Failed to find MEM driver.",
-                    "msSaveImageGDAL()" );
-        return MS_FAILURE;
+    bFileIsTemporary = MS_TRUE;
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Establish the characteristics of our memory, and final          */
+  /*      dataset.                                                        */
+  /* -------------------------------------------------------------------- */
+
+  if( format->imagemode == MS_IMAGEMODE_RGB ) {
+    nBands = 3;
+    assert( MS_RENDERER_PLUGIN(format) && format->vtable->supports_pixel_buffer );
+    format->vtable->getRasterBufferHandle(image,&rb);
+  } else if( format->imagemode == MS_IMAGEMODE_RGBA ) {
+    pabyAlphaLine = (GByte *) calloc(image->width,1);
+    if (pabyAlphaLine == NULL) {
+      msReleaseLock( TLOCK_GDAL );
+      msSetError( MS_MEMERR, "Out of memory allocating %u bytes.\n", "msSaveImageGDAL()", image->width);
+      return MS_FAILURE;
     }
-   
-    hMemDS = GDALCreate( hMemDriver, "msSaveImageGDAL_temp", 
-                         image->width, image->height, nBands, 
-                         eDataType, NULL );
-    if( hMemDS == NULL )
+    nBands = 4;
+    assert( MS_RENDERER_PLUGIN(format) && format->vtable->supports_pixel_buffer );
+    format->vtable->getRasterBufferHandle(image,&rb);
+  } else if( format->imagemode == MS_IMAGEMODE_INT16 ) {
+    nBands = format->bands;
+    eDataType = GDT_Int16;
+  } else if( format->imagemode == MS_IMAGEMODE_FLOAT32 ) {
+    nBands = format->bands;
+    eDataType = GDT_Float32;
+  } else if( format->imagemode == MS_IMAGEMODE_BYTE ) {
+    nBands = format->bands;
+    eDataType = GDT_Byte;
+  } else {
+#ifdef USE_GD
+    assert( format->imagemode == MS_IMAGEMODE_PC256
+            && format->renderer == MS_RENDER_WITH_GD );
+#else
     {
-        msReleaseLock( TLOCK_GDAL );
-        msSetError( MS_MISCERR, "Failed to create MEM dataset.",
-                    "msSaveImageGDAL()" );
-        return MS_FAILURE;
-    }
-    
-/* -------------------------------------------------------------------- */
-/*      Copy the gd image into the memory dataset.                      */
-/* -------------------------------------------------------------------- */
-    for( iLine = 0; iLine < image->height; iLine++ )
-    {
-        int iBand;
-
-        for( iBand = 0; iBand < nBands; iBand++ )
-        {
-            GDALRasterBandH hBand = GDALGetRasterBand( hMemDS, iBand+1 );
-
-            if( format->imagemode == MS_IMAGEMODE_INT16 )
-            {
-                GDALRasterIO( hBand, GF_Write, 0, iLine, image->width, 1, 
-                              image->img.raw_16bit + iLine * image->width
-                              + iBand * image->width * image->height,
-                              image->width, 1, GDT_Int16, 2, 0 );
-                
-            }
-            else if( format->imagemode == MS_IMAGEMODE_FLOAT32 )
-            {
-                GDALRasterIO( hBand, GF_Write, 0, iLine, image->width, 1, 
-                              image->img.raw_float + iLine * image->width
-                              + iBand * image->width * image->height,
-                              image->width, 1, GDT_Float32, 4, 0 );
-            }
-            else if( format->imagemode == MS_IMAGEMODE_BYTE )
-            {
-                GDALRasterIO( hBand, GF_Write, 0, iLine, image->width, 1, 
-                              image->img.raw_byte + iLine * image->width
-                              + iBand * image->width * image->height,
-                              image->width, 1, GDT_Byte, 1, 0 );
-            }
-            else if(format->renderer == MS_RENDER_WITH_GD) {
-               gdImagePtr img = (gdImagePtr)image->img.plugin;
-               GDALRasterIO( hBand, GF_Write, 0, iLine, image->width, 1, 
-                              img->pixels[iLine], 
-                              image->width, 1, GDT_Byte, 0, 0 );
-            }
-            else {
-               GByte *pabyData;
-               unsigned char *pixptr = NULL;
-               assert( rb.type == MS_BUFFER_BYTE_RGBA );
-               switch(iBand) {
-               case 0:
-                  pixptr = rb.data.rgba.r;
-                  break;
-               case 1:
-                  pixptr = rb.data.rgba.g;
-                  break;
-               case 2:
-                  pixptr = rb.data.rgba.b;
-                  break;
-               case 3:
-                  pixptr = rb.data.rgba.a;
-                  break;
-               }
-               assert(pixptr);
-               if( pixptr == NULL )
-               {
-                   msReleaseLock( TLOCK_GDAL );
-                   msSetError( MS_MISCERR, "Missing RGB or A buffer.\n",
-                               "msSaveImageGDAL()" );
-                   return MS_FAILURE;
-               }
-
-               pabyData = (GByte *)(pixptr + iLine*rb.data.rgba.row_step);
-
-               if( rb.data.rgba.a == NULL || iBand == 3 )
-               {
-                   GDALRasterIO( hBand, GF_Write, 0, iLine, image->width, 1, 
-                                 pabyData, image->width, 1, GDT_Byte, 
-                                 rb.data.rgba.pixel_step, 0 );
-               }
-               else /* We need to un-pre-multiple RGB by alpha. */
-               {
-                   GByte *pabyUPM = (GByte*) malloc(image->width);
-                   GByte *pabyAlpha= (GByte *)(rb.data.rgba.a + iLine*rb.data.rgba.row_step);
-                   int i;
-
-                   for( i = 0; i < image->width; i++ )
-                   {
-                       int alpha = pabyAlpha[i*rb.data.rgba.pixel_step];
-
-                       if( alpha == 0 )
-                           pabyUPM[i] = 0;
-                       else
-                       {
-                           int result = (pabyData[i*rb.data.rgba.pixel_step] * 255) / alpha;
-                           
-                           if( result > 255 )
-                               result = 255;
-
-                           pabyUPM[i] = result;
-                       }
-                   }
-
-                   GDALRasterIO( hBand, GF_Write, 0, iLine, image->width, 1, 
-                                 pabyUPM, image->width, 1, GDT_Byte, 1, 0 );
-                   free( pabyUPM );
-               }
-            }
-        }
+      msReleaseLock( TLOCK_GDAL );
+      msSetError( MS_MEMERR, "GD not compiled in. This is a bug.", "msSaveImageGDAL()");
+      return MS_FAILURE;
     }
+#endif
 
-    if( pabyAlphaLine != NULL )
-        free( pabyAlphaLine );
+  }
 
-/* -------------------------------------------------------------------- */
-/*      Attach the palette if appropriate.                              */
-/* -------------------------------------------------------------------- */
-    if( format->renderer == MS_RENDER_WITH_GD )
-    {
-        GDALColorEntry sEntry;
-        int  iColor;
-        GDALColorTableH hCT;
+  /* -------------------------------------------------------------------- */
+  /*      Create a memory dataset which we can use as a source for a      */
+  /*      CreateCopy().                                                   */
+  /* -------------------------------------------------------------------- */
+  hMemDriver = GDALGetDriverByName( "MEM" );
+  if( hMemDriver == NULL ) {
+    msReleaseLock( TLOCK_GDAL );
+    msSetError( MS_MISCERR, "Failed to find MEM driver.",
+                "msSaveImageGDAL()" );
+    return MS_FAILURE;
+  }
+
+  hMemDS = GDALCreate( hMemDriver, "msSaveImageGDAL_temp",
+                       image->width, image->height, nBands,
+                       eDataType, NULL );
+  if( hMemDS == NULL ) {
+    msReleaseLock( TLOCK_GDAL );
+    msSetError( MS_MISCERR, "Failed to create MEM dataset.",
+                "msSaveImageGDAL()" );
+    return MS_FAILURE;
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Copy the gd image into the memory dataset.                      */
+  /* -------------------------------------------------------------------- */
+  for( iLine = 0; iLine < image->height; iLine++ ) {
+    int iBand;
+
+    for( iBand = 0; iBand < nBands; iBand++ ) {
+      GDALRasterBandH hBand = GDALGetRasterBand( hMemDS, iBand+1 );
+
+      if( format->imagemode == MS_IMAGEMODE_INT16 ) {
+        GDALRasterIO( hBand, GF_Write, 0, iLine, image->width, 1,
+                      image->img.raw_16bit + iLine * image->width
+                      + iBand * image->width * image->height,
+                      image->width, 1, GDT_Int16, 2, 0 );
+
+      } else if( format->imagemode == MS_IMAGEMODE_FLOAT32 ) {
+        GDALRasterIO( hBand, GF_Write, 0, iLine, image->width, 1,
+                      image->img.raw_float + iLine * image->width
+                      + iBand * image->width * image->height,
+                      image->width, 1, GDT_Float32, 4, 0 );
+      } else if( format->imagemode == MS_IMAGEMODE_BYTE ) {
+        GDALRasterIO( hBand, GF_Write, 0, iLine, image->width, 1,
+                      image->img.raw_byte + iLine * image->width
+                      + iBand * image->width * image->height,
+                      image->width, 1, GDT_Byte, 1, 0 );
+      }
+#ifdef USE_GD
+      else if(format->renderer == MS_RENDER_WITH_GD) {
         gdImagePtr img = (gdImagePtr)image->img.plugin;
-        hCT = GDALCreateColorTable( GPI_RGB );
-
-        for( iColor = 0; iColor < img->colorsTotal; iColor++ )
-        {
-            sEntry.c1 = img->red[iColor];
-            sEntry.c2 = img->green[iColor];
-            sEntry.c3 = img->blue[iColor];
-
-            if( iColor == gdImageGetTransparent( img ) )
-                sEntry.c4 = 0;
-            else if( iColor == 0 
-                     && gdImageGetTransparent( img ) == -1 
-                     && format->transparent )
-                sEntry.c4 = 0;
-            else
-                sEntry.c4 = 255;
-
-            GDALSetColorEntry( hCT, iColor, &sEntry );
+        GDALRasterIO( hBand, GF_Write, 0, iLine, image->width, 1,
+                      img->pixels[iLine],
+                      image->width, 1, GDT_Byte, 0, 0 );
+      }
+#endif
+      else {
+        GByte *pabyData;
+        unsigned char *pixptr = NULL;
+        assert( rb.type == MS_BUFFER_BYTE_RGBA );
+        switch(iBand) {
+          case 0:
+            pixptr = rb.data.rgba.r;
+            break;
+          case 1:
+            pixptr = rb.data.rgba.g;
+            break;
+          case 2:
+            pixptr = rb.data.rgba.b;
+            break;
+          case 3:
+            pixptr = rb.data.rgba.a;
+            break;
+        }
+        assert(pixptr);
+        if( pixptr == NULL ) {
+          msReleaseLock( TLOCK_GDAL );
+          msSetError( MS_MISCERR, "Missing RGB or A buffer.\n",
+                      "msSaveImageGDAL()" );
+          return MS_FAILURE;
         }
-        
-        GDALSetRasterColorTable( GDALGetRasterBand( hMemDS, 1 ), hCT );
 
-        GDALDestroyColorTable( hCT );
-    }
+        pabyData = (GByte *)(pixptr + iLine*rb.data.rgba.row_step);
 
-#if GDAL_VERSION_NUM > 1170
-    else if( format->imagemode == MS_IMAGEMODE_RGB )
-    {
-        GDALSetRasterColorInterpretation( 
-            GDALGetRasterBand( hMemDS, 1 ), GCI_RedBand );
-        GDALSetRasterColorInterpretation( 
-            GDALGetRasterBand( hMemDS, 2 ), GCI_GreenBand );
-        GDALSetRasterColorInterpretation( 
-            GDALGetRasterBand( hMemDS, 3 ), GCI_BlueBand );
-    }
-    else if( format->imagemode == MS_IMAGEMODE_RGBA )
-    {
-        GDALSetRasterColorInterpretation( 
-            GDALGetRasterBand( hMemDS, 1 ), GCI_RedBand );
-        GDALSetRasterColorInterpretation( 
-            GDALGetRasterBand( hMemDS, 2 ), GCI_GreenBand );
-        GDALSetRasterColorInterpretation( 
-            GDALGetRasterBand( hMemDS, 3 ), GCI_BlueBand );
-        GDALSetRasterColorInterpretation( 
-            GDALGetRasterBand( hMemDS, 4 ), GCI_AlphaBand );
-    }
-#endif
+        if( rb.data.rgba.a == NULL || iBand == 3 ) {
+          GDALRasterIO( hBand, GF_Write, 0, iLine, image->width, 1,
+                        pabyData, image->width, 1, GDT_Byte,
+                        rb.data.rgba.pixel_step, 0 );
+        } else { /* We need to un-pre-multiple RGB by alpha. */
+          GByte *pabyUPM = (GByte*) malloc(image->width);
+          GByte *pabyAlpha= (GByte *)(rb.data.rgba.a + iLine*rb.data.rgba.row_step);
+          int i;
 
-/* -------------------------------------------------------------------- */
-/*      Assign the projection and coordinate system to the memory       */
-/*      dataset.                                                        */
-/* -------------------------------------------------------------------- */
+          for( i = 0; i < image->width; i++ ) {
+            int alpha = pabyAlpha[i*rb.data.rgba.pixel_step];
 
-    if( map != NULL )
-    {
-        char *pszWKT;
+            if( alpha == 0 )
+              pabyUPM[i] = 0;
+            else {
+              int result = (pabyData[i*rb.data.rgba.pixel_step] * 255) / alpha;
 
-        GDALSetGeoTransform( hMemDS, map->gt.geotransform );
+              if( result > 255 )
+                result = 255;
 
-        pszWKT = msProjectionObj2OGCWKT( &(map->projection) );
-        if( pszWKT != NULL )
-        {
-            GDALSetProjection( hMemDS, pszWKT );
-            msFree( pszWKT );
-        }
-    }
+              pabyUPM[i] = result;
+            }
+          }
 
-/* -------------------------------------------------------------------- */
-/*      Possibly assign a nodata value.                                 */
-/* -------------------------------------------------------------------- */
-    if( msGetOutputFormatOption(format,"NULLVALUE",NULL) != NULL )
-    {
-        int iBand;
-        const char *nullvalue = msGetOutputFormatOption(format,
-                                                        "NULLVALUE",NULL);
-
-        for( iBand = 0; iBand < nBands; iBand++ )
-        {
-            GDALRasterBandH hBand = GDALGetRasterBand( hMemDS, iBand+1 );
-            GDALSetRasterNoDataValue( hBand, atof(nullvalue) );
+          GDALRasterIO( hBand, GF_Write, 0, iLine, image->width, 1,
+                        pabyUPM, image->width, 1, GDT_Byte, 1, 0 );
+          free( pabyUPM );
         }
+      }
+    }
+  }
+
+  if( pabyAlphaLine != NULL )
+    free( pabyAlphaLine );
+
+  /* -------------------------------------------------------------------- */
+  /*      Attach the palette if appropriate.                              */
+  /* -------------------------------------------------------------------- */
+#ifdef USE_GD
+  if( format->renderer == MS_RENDER_WITH_GD ) {
+    GDALColorEntry sEntry;
+    int  iColor;
+    GDALColorTableH hCT;
+    gdImagePtr img = (gdImagePtr)image->img.plugin;
+    hCT = GDALCreateColorTable( GPI_RGB );
+
+    for( iColor = 0; iColor < img->colorsTotal; iColor++ ) {
+      sEntry.c1 = img->red[iColor];
+      sEntry.c2 = img->green[iColor];
+      sEntry.c3 = img->blue[iColor];
+
+      if( iColor == gdImageGetTransparent( img ) )
+        sEntry.c4 = 0;
+      else if( iColor == 0
+               && gdImageGetTransparent( img ) == -1
+               && format->transparent )
+        sEntry.c4 = 0;
+      else
+        sEntry.c4 = 255;
+
+      GDALSetColorEntry( hCT, iColor, &sEntry );
     }
 
-/* -------------------------------------------------------------------- */
-/*  Try to save resolution in the output file.                          */
-/* -------------------------------------------------------------------- */
-    if( image->resolution > 0 )
-    {
-      char res[30];
+    GDALSetRasterColorTable( GDALGetRasterBand( hMemDS, 1 ), hCT );
 
-      sprintf( res, "%lf", image->resolution );
-      GDALSetMetadataItem( hMemDS, "TIFFTAG_XRESOLUTION", res, NULL );
-      GDALSetMetadataItem( hMemDS, "TIFFTAG_YRESOLUTION", res, NULL );
-      GDALSetMetadataItem( hMemDS, "TIFFTAG_RESOLUTIONUNIT", "2", NULL );
-    }
-    
-/* -------------------------------------------------------------------- */
-/*      Create a disk image in the selected output format from the      */
-/*      memory image.                                                   */
-/* -------------------------------------------------------------------- */
-    papszOptions = (char**)calloc(sizeof(char *),(format->numformatoptions+1));
-    if (papszOptions == NULL)
-    {
-        msReleaseLock( TLOCK_GDAL );
-        msSetError( MS_MEMERR, "Out of memory allocating %u bytes.\n", "msSaveImageGDAL()", 
-                    sizeof(char *)*(format->numformatoptions+1));
-        return MS_FAILURE;
+    GDALDestroyColorTable( hCT );
+  } else
+#endif
+    if( format->imagemode == MS_IMAGEMODE_RGB ) {
+      GDALSetRasterColorInterpretation(
+        GDALGetRasterBand( hMemDS, 1 ), GCI_RedBand );
+      GDALSetRasterColorInterpretation(
+        GDALGetRasterBand( hMemDS, 2 ), GCI_GreenBand );
+      GDALSetRasterColorInterpretation(
+        GDALGetRasterBand( hMemDS, 3 ), GCI_BlueBand );
+    } else if( format->imagemode == MS_IMAGEMODE_RGBA ) {
+      GDALSetRasterColorInterpretation(
+        GDALGetRasterBand( hMemDS, 1 ), GCI_RedBand );
+      GDALSetRasterColorInterpretation(
+        GDALGetRasterBand( hMemDS, 2 ), GCI_GreenBand );
+      GDALSetRasterColorInterpretation(
+        GDALGetRasterBand( hMemDS, 3 ), GCI_BlueBand );
+      GDALSetRasterColorInterpretation(
+        GDALGetRasterBand( hMemDS, 4 ), GCI_AlphaBand );
     }
 
-    memcpy( papszOptions, format->formatoptions, 
-            sizeof(char *) * format->numformatoptions );
-   
-    hOutputDS = GDALCreateCopy( hOutputDriver, filename, hMemDS, FALSE, 
-                                papszOptions, NULL, NULL );
+  /* -------------------------------------------------------------------- */
+  /*      Assign the projection and coordinate system to the memory       */
+  /*      dataset.                                                        */
+  /* -------------------------------------------------------------------- */
 
-    free( papszOptions );
+  if( map != NULL ) {
+    char *pszWKT;
 
-    if( hOutputDS == NULL )
-    {
-        GDALClose( hMemDS );
-        msReleaseLock( TLOCK_GDAL );
-        msSetError( MS_MISCERR, "Failed to create output %s file.\n%s",
-                    "msSaveImageGDAL()", format->driver+5, 
-                    CPLGetLastErrorMsg() );
-        return MS_FAILURE;
+    GDALSetGeoTransform( hMemDS, map->gt.geotransform );
+
+    pszWKT = msProjectionObj2OGCWKT( &(map->projection) );
+    if( pszWKT != NULL ) {
+      GDALSetProjection( hMemDS, pszWKT );
+      msFree( pszWKT );
+    }
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Possibly assign a nodata value.                                 */
+  /* -------------------------------------------------------------------- */
+  if( msGetOutputFormatOption(format,"NULLVALUE",NULL) != NULL ) {
+    int iBand;
+    const char *nullvalue = msGetOutputFormatOption(format,
+                            "NULLVALUE",NULL);
+
+    for( iBand = 0; iBand < nBands; iBand++ ) {
+      GDALRasterBandH hBand = GDALGetRasterBand( hMemDS, iBand+1 );
+      GDALSetRasterNoDataValue( hBand, atof(nullvalue) );
     }
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*  Try to save resolution in the output file.                          */
+  /* -------------------------------------------------------------------- */
+  if( image->resolution > 0 ) {
+    char res[30];
+
+    sprintf( res, "%lf", image->resolution );
+    GDALSetMetadataItem( hMemDS, "TIFFTAG_XRESOLUTION", res, NULL );
+    GDALSetMetadataItem( hMemDS, "TIFFTAG_YRESOLUTION", res, NULL );
+    GDALSetMetadataItem( hMemDS, "TIFFTAG_RESOLUTIONUNIT", "2", NULL );
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Create a disk image in the selected output format from the      */
+  /*      memory image.                                                   */
+  /* -------------------------------------------------------------------- */
+  papszOptions = (char**)calloc(sizeof(char *),(format->numformatoptions+1));
+  if (papszOptions == NULL) {
+    msReleaseLock( TLOCK_GDAL );
+    msSetError( MS_MEMERR, "Out of memory allocating %u bytes.\n", "msSaveImageGDAL()",
+                sizeof(char *)*(format->numformatoptions+1));
+    return MS_FAILURE;
+  }
 
-    /* closing the memory DS also frees all associated resources. */
-    GDALClose( hMemDS );
+  memcpy( papszOptions, format->formatoptions,
+          sizeof(char *) * format->numformatoptions );
 
-    GDALClose( hOutputDS );
+  hOutputDS = GDALCreateCopy( hOutputDriver, filename, hMemDS, FALSE,
+                              papszOptions, NULL, NULL );
 
-    msReleaseLock( TLOCK_GDAL );
+  free( papszOptions );
 
-/* -------------------------------------------------------------------- */
-/*      Is this supposed to be a temporary file?  If so, stream to      */
-/*      stdout and delete the file.                                     */
-/* -------------------------------------------------------------------- */
-    if( bFileIsTemporary )
-    {
-        FILE *fp; 
-        unsigned char block[4000];
-        int bytes_read;
-
-        if( msIO_needBinaryStdout() == MS_FAILURE )
-            return MS_FAILURE;
-
-        /* We aren't sure how far back GDAL exports the VSI*L API, so 
-           we only use it if we suspect we need it.  But we do need it if
-           holding temporary file in memory. */
-#ifdef GDAL_DCAP_VIRTUALIO
-        fp = VSIFOpenL( filename, "rb" );
-        if( fp == NULL )
-        {
-            msSetError( MS_MISCERR, 
-                        "Failed to open %s for streaming to stdout.",
-                        "msSaveImageGDAL()", filename );
-            return MS_FAILURE;
-        }
+  if( hOutputDS == NULL ) {
+    GDALClose( hMemDS );
+    msReleaseLock( TLOCK_GDAL );
+    msSetError( MS_MISCERR, "Failed to create output %s file.\n%s",
+                "msSaveImageGDAL()", format->driver+5,
+                CPLGetLastErrorMsg() );
+    return MS_FAILURE;
+  }
+
+  /* closing the memory DS also frees all associated resources. */
+  GDALClose( hMemDS );
+
+  GDALClose( hOutputDS );
+  msReleaseLock( TLOCK_GDAL );
+
+
+  /* -------------------------------------------------------------------- */
+  /*      Are we writing license info into the image?                     */
+  /*      If so, add it to the temp file on disk now.                     */
+  /* -------------------------------------------------------------------- */
+#ifdef USE_EXEMPI
+  if ( bUseXmp == MS_TRUE ) {
+    if( msXmpWrite(map, filename) == MS_FAILURE ) {
+      /* Something bad happened. */
+      msSetError( MS_MISCERR, "XMP write to %s failed.\n%s",
+                  "msSaveImageGDAL()", filename);
+      return MS_FAILURE;
+    }
+  }
+#endif
 
-        while( (bytes_read = VSIFReadL(block, 1, sizeof(block), fp)) > 0 )
-            msIO_fwrite( block, 1, bytes_read, stdout );
+  /* -------------------------------------------------------------------- */
+  /*      Is this supposed to be a temporary file?  If so, stream to      */
+  /*      stdout and delete the file.                                     */
+  /* -------------------------------------------------------------------- */
+  if( bFileIsTemporary ) {
+    FILE *fp;
+    unsigned char block[4000];
+    int bytes_read;
+
+    if( msIO_needBinaryStdout() == MS_FAILURE )
+      return MS_FAILURE;
+
+    /* We aren't sure how far back GDAL exports the VSI*L API, so
+       we only use it if we suspect we need it.  But we do need it if
+       holding temporary file in memory. */
+    fp = VSIFOpenL( filename, "rb" );
+    if( fp == NULL ) {
+      msSetError( MS_MISCERR,
+                  "Failed to open %s for streaming to stdout.",
+                  "msSaveImageGDAL()", filename );
+      return MS_FAILURE;
+    }
 
-        VSIFCloseL( fp );
+    while( (bytes_read = VSIFReadL(block, 1, sizeof(block), fp)) > 0 )
+      msIO_fwrite( block, 1, bytes_read, stdout );
 
-        VSIUnlink( filename );
-        CleanVSIDir( "/vsimem/msout" );
-#else
-        fp = fopen( filename, "rb" );
-        if( fp == NULL )
-        {
-            msSetError( MS_MISCERR, 
-                        "Failed to open %s for streaming to stdout.",
-                        "msSaveImageGDAL()", filename );
-            return MS_FAILURE;
-        }
+    VSIFCloseL( fp );
 
-        while( (bytes_read = fread(block, 1, sizeof(block), fp)) > 0 )
-            msIO_fwrite( block, 1, bytes_read, stdout );
+    VSIUnlink( filename );
+    CleanVSIDir( "/vsimem/msout" );
 
-        fclose( fp );
+    free( filename );
+  }
 
-        unlink( filename );
-#endif
-        free( filename );
-    }
-    
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 /************************************************************************/
@@ -593,56 +555,43 @@ int msSaveImageGDAL( mapObj *map, imageObj *image, char *filename )
 int msInitDefaultGDALOutputFormat( outputFormatObj *format )
 
 {
-    GDALDriverH hDriver; 
-
-    msGDALInitialize();
-
-/* -------------------------------------------------------------------- */
-/*      check that this driver exists.  Note visiting drivers should    */
-/*      be pretty threadsafe so don't bother acquiring the GDAL         */
-/*      lock.                                                           */
-/* -------------------------------------------------------------------- */
-    hDriver = GDALGetDriverByName( format->driver+5 );
-    if( hDriver == NULL )
-    {
-        msSetError( MS_MISCERR, "No GDAL driver named `%s' available.", 
-                    "msInitGDALOutputFormat()", format->driver+5 );
-        return MS_FAILURE;
-    }
-
-#ifdef GDAL_DCAP_CREATE
-    if( GDALGetMetadataItem( hDriver, GDAL_DCAP_CREATE, NULL ) == NULL 
-        && GDALGetMetadataItem( hDriver, GDAL_DCAP_CREATECOPY, NULL ) == NULL )
-    {
-        msSetError( MS_MISCERR, "GDAL `%s' driver does not support output.", 
-                    "msInitGDALOutputFormat()", format->driver+5 );
-        return MS_FAILURE;
-    }
-#endif
-
-/* -------------------------------------------------------------------- */
-/*      Initialize the object.                                          */
-/* -------------------------------------------------------------------- */
-    format->imagemode = MS_IMAGEMODE_RGB;
-    format->renderer = MS_RENDER_WITH_AGG;
-
-#ifdef GDAL_DMD_MIMETYPE 
-    if( GDALGetMetadataItem( hDriver, GDAL_DMD_MIMETYPE, NULL ) != NULL )
-        format->mimetype = 
-            msStrdup(GDALGetMetadataItem(hDriver,GDAL_DMD_MIMETYPE,NULL));
-    if( GDALGetMetadataItem( hDriver, GDAL_DMD_EXTENSION, NULL ) != NULL )
-        format->extension = 
-            msStrdup(GDALGetMetadataItem(hDriver,GDAL_DMD_EXTENSION,NULL));
-
-#else
-    if( strcasecmp(format->driver,"GDAL/GTiff") )
-    {
-        format->mimetype = msStrdup("image/tiff");
-        format->extension = msStrdup("tif");
-    }
-#endif
-    
-    return MS_SUCCESS;
+  GDALDriverH hDriver;
+
+  msGDALInitialize();
+
+  /* -------------------------------------------------------------------- */
+  /*      check that this driver exists.  Note visiting drivers should    */
+  /*      be pretty threadsafe so don't bother acquiring the GDAL         */
+  /*      lock.                                                           */
+  /* -------------------------------------------------------------------- */
+  hDriver = GDALGetDriverByName( format->driver+5 );
+  if( hDriver == NULL ) {
+    msSetError( MS_MISCERR, "No GDAL driver named `%s' available.",
+                "msInitGDALOutputFormat()", format->driver+5 );
+    return MS_FAILURE;
+  }
+
+  if( GDALGetMetadataItem( hDriver, GDAL_DCAP_CREATE, NULL ) == NULL
+      && GDALGetMetadataItem( hDriver, GDAL_DCAP_CREATECOPY, NULL ) == NULL ) {
+    msSetError( MS_MISCERR, "GDAL `%s' driver does not support output.",
+                "msInitGDALOutputFormat()", format->driver+5 );
+    return MS_FAILURE;
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Initialize the object.                                          */
+  /* -------------------------------------------------------------------- */
+  format->imagemode = MS_IMAGEMODE_RGB;
+  format->renderer = MS_RENDER_WITH_AGG;
+
+  if( GDALGetMetadataItem( hDriver, GDAL_DMD_MIMETYPE, NULL ) != NULL )
+    format->mimetype =
+      msStrdup(GDALGetMetadataItem(hDriver,GDAL_DMD_MIMETYPE,NULL));
+  if( GDALGetMetadataItem( hDriver, GDAL_DMD_EXTENSION, NULL ) != NULL )
+    format->extension =
+      msStrdup(GDALGetMetadataItem(hDriver,GDAL_DMD_EXTENSION,NULL));
+
+  return MS_SUCCESS;
 }
 
 #else
@@ -670,61 +619,58 @@ char *msProjectionObj2OGCWKT( projectionObj *projection )
 {
 
 #if !defined(USE_GDAL) && !defined(USE_OGR)
-    msSetError(MS_OGRERR, 
-               "Not implemented since neither OGR nor GDAL is enabled.",
-               "msProjectionObj2OGCWKT()");
-    return NULL;
+  msSetError(MS_OGRERR,
+             "Not implemented since neither OGR nor GDAL is enabled.",
+             "msProjectionObj2OGCWKT()");
+  return NULL;
 
 #else /* defined USE_GDAL or USE_OGR */
 
-    OGRSpatialReferenceH hSRS;
-    char *pszWKT=NULL, *pszProj4;
-    int  nLength = 0, i;
-    OGRErr eErr;
-
-    if( projection->proj == NULL )
-        return NULL;
-
-/* -------------------------------------------------------------------- */
-/*      Form arguments into a full Proj.4 definition string.            */
-/* -------------------------------------------------------------------- */
-    for( i = 0; i < projection->numargs; i++ )
-        nLength += strlen(projection->args[i]) + 2;
-
-    pszProj4 = (char *) CPLMalloc(nLength+2);
-    pszProj4[0] = '\0';
-
-    for( i = 0; i < projection->numargs; i++ )
-    {
-        strcat( pszProj4, "+" );
-        strcat( pszProj4, projection->args[i] );
-        strcat( pszProj4, " " );
-    }
-
-/* -------------------------------------------------------------------- */
-/*      Ingest the string into OGRSpatialReference.                     */
-/* -------------------------------------------------------------------- */
-    hSRS = OSRNewSpatialReference( NULL );
-    eErr =  OSRImportFromProj4( hSRS, pszProj4 );
-    CPLFree( pszProj4 );
-
-/* -------------------------------------------------------------------- */
-/*      Export as a WKT string.                                         */
-/* -------------------------------------------------------------------- */
-    if( eErr == OGRERR_NONE )
-        eErr = OSRExportToWkt( hSRS, &pszWKT );
+  OGRSpatialReferenceH hSRS;
+  char *pszWKT=NULL, *pszProj4;
+  int  nLength = 0, i;
+  OGRErr eErr;
 
-    OSRDestroySpatialReference( hSRS );
-
-    if( pszWKT )
-    {
-        char *pszWKT2 = msStrdup(pszWKT);
-        CPLFree( pszWKT );
+  if( projection->proj == NULL )
+    return NULL;
 
-        return pszWKT2;
-    }
-    else
-        return NULL;
+  /* -------------------------------------------------------------------- */
+  /*      Form arguments into a full Proj.4 definition string.            */
+  /* -------------------------------------------------------------------- */
+  for( i = 0; i < projection->numargs; i++ )
+    nLength += strlen(projection->args[i]) + 2;
+
+  pszProj4 = (char *) CPLMalloc(nLength+2);
+  pszProj4[0] = '\0';
+
+  for( i = 0; i < projection->numargs; i++ ) {
+    strcat( pszProj4, "+" );
+    strcat( pszProj4, projection->args[i] );
+    strcat( pszProj4, " " );
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Ingest the string into OGRSpatialReference.                     */
+  /* -------------------------------------------------------------------- */
+  hSRS = OSRNewSpatialReference( NULL );
+  eErr =  OSRImportFromProj4( hSRS, pszProj4 );
+  CPLFree( pszProj4 );
+
+  /* -------------------------------------------------------------------- */
+  /*      Export as a WKT string.                                         */
+  /* -------------------------------------------------------------------- */
+  if( eErr == OGRERR_NONE )
+    eErr = OSRExportToWkt( hSRS, &pszWKT );
+
+  OSRDestroySpatialReference( hSRS );
+
+  if( pszWKT ) {
+    char *pszWKT2 = msStrdup(pszWKT);
+    CPLFree( pszWKT );
+
+    return pszWKT2;
+  } else
+    return NULL;
 #endif /* defined USE_GDAL or USE_OGR */
 }
 
diff --git a/mapgeomtransform.c b/mapgeomtransform.c
index e4f95e1..e3d1906 100644
--- a/mapgeomtransform.c
+++ b/mapgeomtransform.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -32,31 +32,25 @@
 
 extern int yyparse(parseObj *p);
 
-void msStyleSetGeomTransform(styleObj *s, char *transform) {
-  msFree(s->_geomtransform.string);                                                                                                                                                          
+void msStyleSetGeomTransform(styleObj *s, char *transform)
+{
+  msFree(s->_geomtransform.string);
   s->_geomtransform.string = msStrdup(transform);
   if(!strncasecmp("start",transform,5)) {
     s->_geomtransform.type = MS_GEOMTRANSFORM_START;
-  }
-  else if(!strncasecmp("end",transform,3)) {
+  } else if(!strncasecmp("end",transform,3)) {
     s->_geomtransform.type = MS_GEOMTRANSFORM_END;
-  }
-  else if(!strncasecmp("vertices",transform,8)) {
+  } else if(!strncasecmp("vertices",transform,8)) {
     s->_geomtransform.type = MS_GEOMTRANSFORM_VERTICES;
-  }
-  else if(!strncasecmp("bbox",transform,4)) {
+  } else if(!strncasecmp("bbox",transform,4)) {
     s->_geomtransform.type = MS_GEOMTRANSFORM_BBOX;
-  }
-  else if(!strncasecmp("labelpnt",transform,8)) {
+  } else if(!strncasecmp("labelpnt",transform,8)) {
     s->_geomtransform.type = MS_GEOMTRANSFORM_LABELPOINT;
-  }
-  else if(!strncasecmp("labelpoly",transform,9)) {
+  } else if(!strncasecmp("labelpoly",transform,9)) {
     s->_geomtransform.type = MS_GEOMTRANSFORM_LABELPOLY;
-  }
-  else if(!strncasecmp("centroid",transform,8)) {
+  } else if(!strncasecmp("centroid",transform,8)) {
     s->_geomtransform.type = MS_GEOMTRANSFORM_CENTROID;
-  }
-  else {
+  } else {
     s->_geomtransform.type = MS_GEOMTRANSFORM_NONE;
     msSetError(MS_MISCERR,"unknown transform expression","msStyleSetGeomTransform()");
     msFree(s->_geomtransform.string);
@@ -69,18 +63,21 @@ void msStyleSetGeomTransform(styleObj *s, char *transform) {
  * return a copy of the geometry transform expression
  * returned char* must be freed by the caller
  */
-char *msStyleGetGeomTransform(styleObj *s) {
+char *msStyleGetGeomTransform(styleObj *s)
+{
   return msStrdup(s->_geomtransform.string);
 }
 
 
-double calcOrientation(pointObj *p1, pointObj *p2) {
+double calcOrientation(pointObj *p1, pointObj *p2)
+{
   double theta;
   theta = atan2(p2->x - p1->x,p2->y - p1->y);
   return MS_RAD_TO_DEG*(theta-MS_PI2);
 }
 
-double calcMidAngle(pointObj *p1, pointObj *p2, pointObj *p3) {
+double calcMidAngle(pointObj *p1, pointObj *p2, pointObj *p3)
+{
   double theta1,theta2;
   theta1 = atan2(p1->x-p2->x,p1->y-p2->y);
   if(theta1<0) theta1 += MS_2PI;
@@ -94,16 +91,17 @@ double calcMidAngle(pointObj *p1, pointObj *p2, pointObj *p3) {
  *  - transform the original shapeobj
  *  - use the styleObj to render the transformed shapeobj
  */
-int msDrawTransformedShape(mapObj *map, symbolSetObj *symbolset, imageObj *image, shapeObj *shape, styleObj *style, double scalefactor){
+int msDrawTransformedShape(mapObj *map, symbolSetObj *symbolset, imageObj *image, shapeObj *shape, styleObj *style, double scalefactor)
+{
   int type = style->_geomtransform.type;
   int i,j;
   switch(type) {
     case MS_GEOMTRANSFORM_END: /*render point on last vertex only*/
-      for(j=0;j<shape->numlines;j++) {
+      for(j=0; j<shape->numlines; j++) {
         lineObj *line = &(shape->line[j]);
         pointObj *p = &(line->point[line->numpoints-1]);
         if(p->x<0||p->x>image->width||p->y<0||p->y>image->height)
-            continue;
+          continue;
         if(style->autoangle==MS_TRUE && line->numpoints>1) {
           style->angle = calcOrientation(&(line->point[line->numpoints-2]),p);
         }
@@ -111,12 +109,12 @@ int msDrawTransformedShape(mapObj *map, symbolSetObj *symbolset, imageObj *image
       }
       break;
     case MS_GEOMTRANSFORM_START: /*render point on first vertex only*/
-      for(j=0;j<shape->numlines;j++) {
+      for(j=0; j<shape->numlines; j++) {
         lineObj *line = &(shape->line[j]);
         pointObj *p = &(line->point[0]);
         /*skip if outside image*/
         if(p->x<0||p->x>image->width||p->y<0||p->y>image->height)
-            continue;
+          continue;
         if(style->autoangle==MS_TRUE && line->numpoints>1) {
           style->angle = calcOrientation(p,&(line->point[1]));
         }
@@ -124,9 +122,9 @@ int msDrawTransformedShape(mapObj *map, symbolSetObj *symbolset, imageObj *image
       }
       break;
     case MS_GEOMTRANSFORM_VERTICES:
-      for(j=0;j<shape->numlines;j++) {
+      for(j=0; j<shape->numlines; j++) {
         lineObj *line = &(shape->line[j]);
-        for(i=1;i<line->numpoints-1;i++) {
+        for(i=1; i<line->numpoints-1; i++) {
           pointObj *p = &(line->point[i]);
           /*skip points outside image*/
           if(p->x<0||p->x>image->width||p->y<0||p->y>image->height)
@@ -138,65 +136,63 @@ int msDrawTransformedShape(mapObj *map, symbolSetObj *symbolset, imageObj *image
         }
       }
       break;
-    case MS_GEOMTRANSFORM_BBOX: 
-      {
-        shapeObj bbox;
-        lineObj bbox_line;
-        pointObj bbox_points[5];
-        int padding = MS_MAX(style->width,style->size)+3; //so clipped shape does not extent into image
-        
-        /*create a shapeObj representing the bounding box (clipped by the image size)*/
-        bbox.numlines = 1;
-        bbox.line = &bbox_line;
-        bbox.line->numpoints = 5;
-        bbox.line->point = bbox_points;
- 
-        msComputeBounds(shape);
-        bbox_points[0].x=bbox_points[4].x=bbox_points[1].x = 
-            (shape->bounds.minx < -padding) ? -padding : shape->bounds.minx;
-        bbox_points[2].x=bbox_points[3].x = 
-            (shape->bounds.maxx > image->width+padding) ? image->width+padding : shape->bounds.maxx;
-        bbox_points[0].y=bbox_points[4].y=bbox_points[3].y = 
-            (shape->bounds.miny < -padding) ? -padding : shape->bounds.miny;
-        bbox_points[1].y=bbox_points[2].y =
-            (shape->bounds.maxy > image->height+padding) ? image->height+padding : shape->bounds.maxy;
-  	    msDrawShadeSymbol(symbolset, image, &bbox, style, scalefactor);
-      }
-      break;
-    case MS_GEOMTRANSFORM_CENTROID:
-      {
-        double unused; /*used by centroid function*/
-        pointObj centroid;
-        if(MS_SUCCESS == msGetPolygonCentroid(shape,&centroid,&unused,&unused)){
-          msDrawMarkerSymbol(symbolset,image,&centroid,style,scalefactor);
-        }
+    case MS_GEOMTRANSFORM_BBOX: {
+      shapeObj bbox;
+      lineObj bbox_line;
+      pointObj bbox_points[5];
+      int padding = MS_MAX(style->width,style->size)+3; /* so clipped shape does not extent into image */
+
+      /*create a shapeObj representing the bounding box (clipped by the image size)*/
+      bbox.numlines = 1;
+      bbox.line = &bbox_line;
+      bbox.line->numpoints = 5;
+      bbox.line->point = bbox_points;
+
+      msComputeBounds(shape);
+      bbox_points[0].x=bbox_points[4].x=bbox_points[1].x =
+                                          (shape->bounds.minx < -padding) ? -padding : shape->bounds.minx;
+      bbox_points[2].x=bbox_points[3].x =
+                         (shape->bounds.maxx > image->width+padding) ? image->width+padding : shape->bounds.maxx;
+      bbox_points[0].y=bbox_points[4].y=bbox_points[3].y =
+                                          (shape->bounds.miny < -padding) ? -padding : shape->bounds.miny;
+      bbox_points[1].y=bbox_points[2].y =
+                         (shape->bounds.maxy > image->height+padding) ? image->height+padding : shape->bounds.maxy;
+      msDrawShadeSymbol(symbolset, image, &bbox, style, scalefactor);
+    }
+    break;
+    case MS_GEOMTRANSFORM_CENTROID: {
+      double unused; /*used by centroid function*/
+      pointObj centroid;
+      if(MS_SUCCESS == msGetPolygonCentroid(shape,&centroid,&unused,&unused)) {
+        msDrawMarkerSymbol(symbolset,image,&centroid,style,scalefactor);
       }
-      break;
-    case MS_GEOMTRANSFORM_EXPRESSION:
-      {
-        int status;
-	shapeObj *tmpshp;
-        parseObj p;
+    }
+    break;
+    case MS_GEOMTRANSFORM_EXPRESSION: {
+      int status;
+      shapeObj *tmpshp;
+      parseObj p;
 
-	p.shape = shape; /* set a few parser globals (hence the lock) */
-	p.expr = &(style->_geomtransform);
-	p.expr->curtoken = p.expr->tokens; /* reset */
-	p.type = MS_PARSE_TYPE_SHAPE;
+      p.shape = shape; /* set a few parser globals (hence the lock) */
+      p.expr = &(style->_geomtransform);
+      p.expr->curtoken = p.expr->tokens; /* reset */
+      p.type = MS_PARSE_TYPE_SHAPE;
 
-	status = yyparse(&p);
-	if (status != 0) {
-	  msSetError(MS_PARSEERR, "Failed to process shape expression: %s", "msDrawTransformedShape", style->_geomtransform.string);
-	  return MS_FAILURE;
-	}
+      status = yyparse(&p);
+      if (status != 0) {
+        msSetError(MS_PARSEERR, "Failed to process shape expression: %s", "msDrawTransformedShape", style->_geomtransform.string);
+        return MS_FAILURE;
+      }
 
-	tmpshp = p.result.shpval;
+      tmpshp = p.result.shpval;
 
-        /* TODO: check resulting shape type and draw accordingly */
-        msDrawShadeSymbol(symbolset, image, tmpshp, style, scalefactor);
+      /* TODO: check resulting shape type and draw accordingly */
+      msDrawShadeSymbol(symbolset, image, tmpshp, style, scalefactor);
 
-        msFreeShape(tmpshp);
-      }
-      break;
+      msFreeShape(tmpshp);
+      msFree(tmpshp);
+    }
+    break;
     case MS_GEOMTRANSFORM_LABELPOINT:
     case MS_GEOMTRANSFORM_LABELPOLY:
       break;
diff --git a/mapgeomutil.cpp b/mapgeomutil.cpp
index e4c910b..7ecc39e 100644
--- a/mapgeomutil.cpp
+++ b/mapgeomutil.cpp
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -34,98 +34,99 @@
 
 
 
-shapeObj *msRasterizeArc(double x0, double y0, double radius, double startAngle, double endAngle, int isSlice) {
-    static int allocated_size=100;
-    shapeObj *shape = (shapeObj*)calloc(1,sizeof(shapeObj));
-    MS_CHECK_ALLOC(shape, sizeof(shapeObj), NULL);
-    mapserver::arc arc ( x0, y0,radius,radius, startAngle*MS_DEG_TO_RAD, endAngle*MS_DEG_TO_RAD,true );
-    arc.approximation_scale ( 1 );
-    arc.rewind(1);
-    msInitShape(shape);
-    
-    lineObj *line = (lineObj*)calloc(1,sizeof(lineObj));
-    if (!line) {
-        msSetError(MS_MEMERR, "%s: %d: Out of memory allocating %u bytes.\n", "msRasterizeArc()" ,
-                   __FILE__, __LINE__, sizeof(lineObj));       
-        free(shape);
-        return NULL; 
-    }
-    shape->line = line;
-    shape->numlines = 1;
-    line->point = (pointObj*)calloc(allocated_size,sizeof(pointObj));
-    if (!line->point) {
+shapeObj *msRasterizeArc(double x0, double y0, double radius, double startAngle, double endAngle, int isSlice)
+{
+  static int allocated_size=100;
+  shapeObj *shape = (shapeObj*)calloc(1,sizeof(shapeObj));
+  MS_CHECK_ALLOC(shape, sizeof(shapeObj), NULL);
+  mapserver::arc arc ( x0, y0,radius,radius, startAngle*MS_DEG_TO_RAD, endAngle*MS_DEG_TO_RAD,true );
+  arc.approximation_scale ( 1 );
+  arc.rewind(1);
+  msInitShape(shape);
+
+  lineObj *line = (lineObj*)calloc(1,sizeof(lineObj));
+  if (!line) {
+    msSetError(MS_MEMERR, "%s: %d: Out of memory allocating %u bytes.\n", "msRasterizeArc()" ,
+               __FILE__, __LINE__, sizeof(lineObj));
+    free(shape);
+    return NULL;
+  }
+  shape->line = line;
+  shape->numlines = 1;
+  line->point = (pointObj*)calloc(allocated_size,sizeof(pointObj));
+  if (!line->point) {
+    msSetError(MS_MEMERR, "%s: %d: Out of memory allocating %u bytes.\n", "msRasterizeArc()" ,
+               __FILE__, __LINE__, allocated_size*sizeof(pointObj));
+    free(line);
+    free(shape);
+    return NULL;
+  }
+
+  line->numpoints = 0;
+
+  double x,y;
+
+  //first segment from center to first point of arc
+  if(isSlice) {
+    line->point[0].x = x0;
+    line->point[0].y = y0;
+    line->numpoints = 1;
+  }
+  while(arc.vertex(&x,&y) != mapserver::path_cmd_stop) {
+    if(line->numpoints == allocated_size) {
+      allocated_size *= 2;
+      line->point = (pointObj*)realloc(line->point, allocated_size * sizeof(pointObj));
+      if (!line->point) {
         msSetError(MS_MEMERR, "%s: %d: Out of memory allocating %u bytes.\n", "msRasterizeArc()" ,
-                       __FILE__, __LINE__, allocated_size*sizeof(pointObj));       
+                   __FILE__, __LINE__, allocated_size * sizeof(pointObj));
         free(line);
         free(shape);
-        return NULL; 
+        return NULL;
+      }
     }
+    line->point[line->numpoints].x = x;
+    line->point[line->numpoints].y = y;
+    line->numpoints++;
+  }
 
-    line->numpoints = 0;
-    
-    double x,y;
-    
-    //first segment from center to first point of arc
-    if(isSlice) {
-        line->point[0].x = x0;
-        line->point[0].y = y0;
-        line->numpoints = 1;
-    }
-    while(arc.vertex(&x,&y) != mapserver::path_cmd_stop) {
-        if(line->numpoints == allocated_size) {
-            allocated_size *= 2;
-            line->point = (pointObj*)realloc(line->point, allocated_size * sizeof(pointObj));
-            if (!line->point) {
-                msSetError(MS_MEMERR, "%s: %d: Out of memory allocating %u bytes.\n", "msRasterizeArc()" ,
-                           __FILE__, __LINE__, allocated_size * sizeof(pointObj));       
-                free(line);
-                free(shape);
-                return NULL; 
-            }
+  //make sure the shape is closed if we're doing a full circle
+  if(!isSlice && !(endAngle-startAngle)%360) {
+    if(line->point[line->numpoints-1].x != line->point[0].x ||
+        line->point[line->numpoints-1].y != line->point[0].y) {
+      if(line->numpoints == allocated_size) {
+        allocated_size *= 2;
+        line->point = (pointObj*)realloc(line->point, allocated_size * sizeof(pointObj));
+        if (!line->point) {
+          msSetError(MS_MEMERR, "%s: %d: Out of memory allocating %u bytes.\n", "msRasterizeArc()" ,
+                     __FILE__, __LINE__, allocated_size * sizeof(pointObj));
+          free(line);
+          free(shape);
+          return NULL;
         }
-        line->point[line->numpoints].x = x;
-        line->point[line->numpoints].y = y;
-        line->numpoints++;
+      }
+      line->point[line->numpoints].x = line->point[0].x;
+      line->point[line->numpoints].y = line->point[0].y;
+      line->numpoints++;
     }
-    
-    //make sure the shape is closed if we're doing a full circle
-    if(!isSlice && !(endAngle-startAngle)%360) {
-        if(line->point[line->numpoints-1].x != line->point[0].x ||
-           line->point[line->numpoints-1].y != line->point[0].y) {
-            if(line->numpoints == allocated_size) {
-                allocated_size *= 2;
-                line->point = (pointObj*)realloc(line->point, allocated_size * sizeof(pointObj));
-                if (!line->point) {
-                    msSetError(MS_MEMERR, "%s: %d: Out of memory allocating %u bytes.\n", "msRasterizeArc()" ,  
-                               __FILE__, __LINE__, allocated_size * sizeof(pointObj));       
-                    free(line);
-                    free(shape);
-                    return NULL; 
-                }
-            }
-            line->point[line->numpoints].x = line->point[0].x;
-            line->point[line->numpoints].y = line->point[0].y;
-            line->numpoints++;
-        }
-        
-    }
-    if(isSlice) {
-        if(line->numpoints == allocated_size) {
-            allocated_size *= 2;
-            line->point = (pointObj*)realloc(line->point, allocated_size * sizeof(pointObj));
-            if (!line->point) {
-                msSetError(MS_MEMERR, "%s: %d: Out of memory allocating %u bytes.\n", "msRasterizeArc()" ,
-                           __FILE__, __LINE__, allocated_size * sizeof(pointObj));       
-                free(line);
-                free(shape);
-                return NULL; 
-            }
-        }
-        line->point[line->numpoints].x = x0;
-        line->point[line->numpoints].y = y0;
-        line->numpoints++;
+
+  }
+  if(isSlice) {
+    if(line->numpoints == allocated_size) {
+      allocated_size *= 2;
+      line->point = (pointObj*)realloc(line->point, allocated_size * sizeof(pointObj));
+      if (!line->point) {
+        msSetError(MS_MEMERR, "%s: %d: Out of memory allocating %u bytes.\n", "msRasterizeArc()" ,
+                   __FILE__, __LINE__, allocated_size * sizeof(pointObj));
+        free(line);
+        free(shape);
+        return NULL;
+      }
     }
-    return shape;
+    line->point[line->numpoints].x = x0;
+    line->point[line->numpoints].y = y0;
+    line->numpoints++;
+  }
+  return shape;
 }
 
 
diff --git a/mapgeos.c b/mapgeos.c
index 0f0c0af..a64aceb 100644
--- a/mapgeos.c
+++ b/mapgeos.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -47,7 +47,7 @@ static void msGEOSError(const char *format, ...)
   return;
 }
 
-static void msGEOSNotice(const char *fmt, ...) 
+static void msGEOSNotice(const char *fmt, ...)
 {
   return; /* do nothing with notices at this point */
 }
@@ -55,12 +55,12 @@ static void msGEOSNotice(const char *fmt, ...)
 /*
 ** Setup/Cleanup wrappers
 */
-void msGEOSSetup() 
+void msGEOSSetup()
 {
   initGEOS(msGEOSNotice, msGEOSError);
 }
 
-void msGEOSCleanup() 
+void msGEOSCleanup()
 {
   finishGEOS();
 }
@@ -72,18 +72,18 @@ static GEOSGeom msGEOSShape2Geometry_point(pointObj *point)
 {
   GEOSCoordSeq coords;
   GEOSGeom g;
-  
+
   if(!point) return NULL;
-  
+
   coords = GEOSCoordSeq_create(1, 2); /* todo handle z's */
   if(!coords) return NULL;
-  
+
   GEOSCoordSeq_setX(coords, 0, point->x);
   GEOSCoordSeq_setY(coords, 0, point->y);
   /* GEOSCoordSeq_setY(coords, 0, point->z); */
 
   g = GEOSGeom_createPoint(coords); /* g owns the coordinate in coords */
-  
+
   return g;
 }
 
@@ -97,12 +97,12 @@ static GEOSGeom msGEOSShape2Geometry_multipoint(lineObj *multipoint)
 
   points = malloc(multipoint->numpoints*sizeof(GEOSGeom));
   if(!points) return NULL;
-  
+
   for(i=0; i<multipoint->numpoints; i++)
     points[i] = msGEOSShape2Geometry_point(&(multipoint->point[i]));
 
   g = GEOSGeom_createCollection(GEOS_MULTIPOINT, points, multipoint->numpoints);
-  
+
   free(points);
 
   return g;
@@ -112,10 +112,10 @@ static GEOSGeom msGEOSShape2Geometry_line(lineObj *line)
 {
   int i;
   GEOSGeom g;
-  GEOSCoordSeq coords;  
+  GEOSCoordSeq coords;
 
   if(!line) return NULL;
-  
+
   coords = GEOSCoordSeq_create(line->numpoints, 2); /* todo handle z's */
   if(!coords) return NULL;
 
@@ -126,7 +126,7 @@ static GEOSGeom msGEOSShape2Geometry_line(lineObj *line)
   }
 
   g = GEOSGeom_createLineString(coords); /* g owns the coordinates in coords */
-  
+
   return g;
 }
 
@@ -145,7 +145,7 @@ static GEOSGeom msGEOSShape2Geometry_multiline(shapeObj *multiline)
     lines[i] = msGEOSShape2Geometry_line(&(multiline->line[i]));
 
   g = GEOSGeom_createCollection(GEOS_MULTILINESTRING, lines, multiline->numlines);
-  
+
   free(lines);
 
   return g;
@@ -154,28 +154,28 @@ static GEOSGeom msGEOSShape2Geometry_multiline(shapeObj *multiline)
 static GEOSGeom msGEOSShape2Geometry_simplepolygon(shapeObj *shape, int r, int *outerList)
 {
   int i, j, k;
-  GEOSCoordSeq coords; 
+  GEOSCoordSeq coords;
   GEOSGeom g;
   GEOSGeom outerRing;
   GEOSGeom *innerRings=NULL;
   int numInnerRings=0, *innerList;
 
   if(!shape || !outerList) return NULL;
-    
+
   /* build the outer shell */
   coords = GEOSCoordSeq_create(shape->line[r].numpoints, 2); /* todo handle z's */
   if(!coords) return NULL;
-    
+
   for(i=0; i<shape->line[r].numpoints; i++) {
     GEOSCoordSeq_setX(coords, i, shape->line[r].point[i].x);
     GEOSCoordSeq_setY(coords, i, shape->line[r].point[i].y);
     /* GEOSCoordSeq_setZ(coords, i, shape->line[r].point[i].z); */
   }
-  
-  outerRing = GEOSGeom_createLinearRing(coords); /* outerRing owns the coordinates in coords */ 
-    
+
+  outerRing = GEOSGeom_createLinearRing(coords); /* outerRing owns the coordinates in coords */
+
   /* build the holes */
-  innerList = msGetInnerList(shape, r, outerList);    
+  innerList = msGetInnerList(shape, r, outerList);
   for(j=0; j<shape->numlines; j++)
     if(innerList[j] == MS_TRUE) numInnerRings++;
 
@@ -184,28 +184,29 @@ static GEOSGeom msGEOSShape2Geometry_simplepolygon(shapeObj *shape, int r, int *
 
     innerRings = malloc(numInnerRings*sizeof(GEOSGeom));
     if(!innerRings) return NULL; /* todo, this will leak memory (outerRing) */
-  
+
     for(j=0; j<shape->numlines; j++) {
-	  if(innerList[j] == MS_FALSE) continue;
-	
-	  coords = GEOSCoordSeq_create(shape->line[j].numpoints, 2); /* todo handle z's */
+      if(innerList[j] == MS_FALSE) continue;
+
+      coords = GEOSCoordSeq_create(shape->line[j].numpoints, 2); /* todo handle z's */
       if(!coords) return NULL; /* todo, this will leak memory (shell + allocated holes) */
-	
-	  for(i=0; i<shape->line[j].numpoints; i++) {
+
+      for(i=0; i<shape->line[j].numpoints; i++) {
         GEOSCoordSeq_setX(coords, i, shape->line[j].point[i].x);
         GEOSCoordSeq_setY(coords, i, shape->line[j].point[i].y);
         /* GEOSCoordSeq_setZ(coords, i, shape->line[j].point[i].z); */
-	  }
+      }
 
-	  innerRings[k] = GEOSGeom_createLinearRing(coords); /* innerRings[k] owns the coordinates in coords */
-	  k++;
+      innerRings[k] = GEOSGeom_createLinearRing(coords); /* innerRings[k] owns the coordinates in coords */
+      k++;
     }
   }
 
   g = GEOSGeom_createPolygon(outerRing, innerRings, numInnerRings);
 
   free(innerList); /* clean up */
-   
+  free(innerRings); /* clean up */
+
   return g;
 }
 
@@ -219,12 +220,12 @@ static GEOSGeom msGEOSShape2Geometry_polygon(shapeObj *shape)
   outerList = msGetOuterList(shape);
   for(i=0; i<shape->numlines; i++) {
     if(outerList[i] == MS_TRUE) {
-	  numOuterRings++;
-	  lastOuterRing = i; /* save for the simple case */
+      numOuterRings++;
+      lastOuterRing = i; /* save for the simple case */
     }
   }
 
-  if(numOuterRings == 1) { 
+  if(numOuterRings == 1) {
     g = msGEOSShape2Geometry_simplepolygon(shape, lastOuterRing, outerList);
   } else { /* a true multipolygon */
     polygons = malloc(numOuterRings*sizeof(GEOSGeom));
@@ -232,12 +233,13 @@ static GEOSGeom msGEOSShape2Geometry_polygon(shapeObj *shape)
 
     j = 0; /* part counter */
     for(i=0; i<shape->numlines; i++) {
-	  if(outerList[i] == MS_FALSE) continue;
-	  polygons[j] = msGEOSShape2Geometry_simplepolygon(shape, i, outerList); /* TODO: account for NULL return values */
-	  j++;
+      if(outerList[i] == MS_FALSE) continue;
+      polygons[j] = msGEOSShape2Geometry_simplepolygon(shape, i, outerList); /* TODO: account for NULL return values */
+      j++;
     }
 
     g = GEOSGeom_createCollection(GEOS_MULTIPOLYGON, polygons, numOuterRings);
+    free(polygons);
   }
 
   free(outerList);
@@ -250,32 +252,32 @@ GEOSGeom msGEOSShape2Geometry(shapeObj *shape)
     return NULL; /* a NULL shape generates a NULL geometry */
 
   switch(shape->type) {
-  case MS_SHAPE_POINT:
-    if(shape->numlines == 0 || shape->line[0].numpoints == 0) /* not enough info for a point */
-      return NULL;
-
-    if(shape->line[0].numpoints == 1) /* simple point */
-      return msGEOSShape2Geometry_point(&(shape->line[0].point[0]));
-    else /* multi-point */
-      return msGEOSShape2Geometry_multipoint(&(shape->line[0]));
-    break;
-  case MS_SHAPE_LINE:
-    if(shape->numlines == 0 || shape->line[0].numpoints < 2) /* not enough info for a line */
-      return NULL;
-
-    if(shape->numlines == 1) /* simple line */
-      return msGEOSShape2Geometry_line(&(shape->line[0]));
-    else /* multi-line */
-      return msGEOSShape2Geometry_multiline(shape);
-    break;
-  case MS_SHAPE_POLYGON:
-    if(shape->numlines == 0 || shape->line[0].numpoints < 4) /* not enough info for a polygon (first=last) */
-      return NULL;
-
-    return msGEOSShape2Geometry_polygon(shape); /* simple and multipolygon cases are addressed */
-    break;
-  default:
-    break;
+    case MS_SHAPE_POINT:
+      if(shape->numlines == 0 || shape->line[0].numpoints == 0) /* not enough info for a point */
+        return NULL;
+
+      if(shape->line[0].numpoints == 1) /* simple point */
+        return msGEOSShape2Geometry_point(&(shape->line[0].point[0]));
+      else /* multi-point */
+        return msGEOSShape2Geometry_multipoint(&(shape->line[0]));
+      break;
+    case MS_SHAPE_LINE:
+      if(shape->numlines == 0 || shape->line[0].numpoints < 2) /* not enough info for a line */
+        return NULL;
+
+      if(shape->numlines == 1) /* simple line */
+        return msGEOSShape2Geometry_line(&(shape->line[0]));
+      else /* multi-line */
+        return msGEOSShape2Geometry_multiline(shape);
+      break;
+    case MS_SHAPE_POLYGON:
+      if(shape->numlines == 0 || shape->line[0].numpoints < 4) /* not enough info for a polygon (first=last) */
+        return NULL;
+
+      return msGEOSShape2Geometry_polygon(shape); /* simple and multipolygon cases are addressed */
+      break;
+    default:
+      break;
   }
 
   return NULL; /* should not get here */
@@ -285,12 +287,12 @@ static shapeObj *msGEOSGeometry2Shape_point(GEOSGeom g)
 {
   GEOSCoordSeq coords;
   shapeObj *shape=NULL;
-  
+
   if(!g) return NULL;
-    
+
   shape = (shapeObj *) malloc(sizeof(shapeObj));
   msInitShape(shape);
-    
+
   shape->type = MS_SHAPE_POINT;
   shape->line = (lineObj *) malloc(sizeof(lineObj));
   shape->numlines = 1;
@@ -306,7 +308,7 @@ static shapeObj *msGEOSGeometry2Shape_point(GEOSGeom g)
 
   shape->bounds.minx = shape->bounds.maxx = shape->line[0].point[0].x;
   shape->bounds.miny = shape->bounds.maxy = shape->line[0].point[0].y;
- 
+
   return shape;
 }
 
@@ -316,7 +318,7 @@ static shapeObj *msGEOSGeometry2Shape_multipoint(GEOSGeom g)
   int numPoints;
   GEOSCoordSeq coords;
   GEOSGeom point;
-  
+
   shapeObj *shape=NULL;
 
   if(!g) return NULL;
@@ -340,8 +342,8 @@ static shapeObj *msGEOSGeometry2Shape_multipoint(GEOSGeom g)
     GEOSCoordSeq_getY(coords, 0, &(shape->line[0].point[i].y));
     /* GEOSCoordSeq_getZ(coords, 0, &(shape->line[0].point[i].z)); */
   }
- 
-  msComputeBounds(shape); 
+
+  msComputeBounds(shape);
 
   return shape;
 }
@@ -361,7 +363,7 @@ static shapeObj *msGEOSGeometry2Shape_line(GEOSGeom g)
   shape = (shapeObj *) malloc(sizeof(shapeObj));
   msInitShape(shape);
 
-  shape->type = MS_SHAPE_LINE; 
+  shape->type = MS_SHAPE_LINE;
   shape->line = (lineObj *) malloc(sizeof(lineObj));
   shape->numlines = 1;
   shape->line[0].point = (pointObj *) malloc(sizeof(pointObj)*numPoints);
@@ -374,7 +376,7 @@ static shapeObj *msGEOSGeometry2Shape_line(GEOSGeom g)
     /* GEOSCoordSeq_getZ(coords, i, &(shape->line[0].point[i].z)); */
   }
 
-  msComputeBounds(shape); 
+  msComputeBounds(shape);
 
   return shape;
 }
@@ -409,13 +411,13 @@ static shapeObj *msGEOSGeometry2Shape_multiline(GEOSGeom g)
     for(i=0; i<numPoints; i++) {
       GEOSCoordSeq_getX(coords, i, &(line.point[i].x));
       GEOSCoordSeq_getY(coords, i, &(line.point[i].y));
-      /* GEOSCoordSeq_getZ(coords, i, &(line.point[i].z)); */  	
+      /* GEOSCoordSeq_getZ(coords, i, &(line.point[i].z)); */
     }
 
     msAddLineDirectly(shape, &line);
   }
 
-  msComputeBounds(shape); 
+  msComputeBounds(shape);
 
   return shape;
 }
@@ -441,14 +443,14 @@ static shapeObj *msGEOSGeometry2Shape_polygon(GEOSGeom g)
   ring = (GEOSGeom) GEOSGetExteriorRing(g);
   numPoints = GEOSGetNumCoordinates(ring);
   coords = (GEOSCoordSeq) GEOSGeom_getCoordSeq(ring);
-  
+
   line.point = (pointObj *) malloc(sizeof(pointObj)*numPoints);
   line.numpoints = numPoints;
 
   for(i=0; i<numPoints; i++) {
     GEOSCoordSeq_getX(coords, i, &(line.point[i].x));
     GEOSCoordSeq_getY(coords, i, &(line.point[i].y));
-    /* GEOSCoordSeq_getZ(coords, i, &(line.point[i].z)); */    
+    /* GEOSCoordSeq_getZ(coords, i, &(line.point[i].z)); */
   }
   msAddLineDirectly(shape, &line);
 
@@ -472,7 +474,7 @@ static shapeObj *msGEOSGeometry2Shape_polygon(GEOSGeom g)
     msAddLineDirectly(shape, &line);
   }
 
-  msComputeBounds(shape); 
+  msComputeBounds(shape);
 
   return shape;
 }
@@ -507,70 +509,70 @@ static shapeObj *msGEOSGeometry2Shape_multipolygon(GEOSGeom g)
     line.numpoints = numPoints;
 
     for(i=0; i<numPoints; i++) {
-	  GEOSCoordSeq_getX(coords, i, &(line.point[i].x));
+      GEOSCoordSeq_getX(coords, i, &(line.point[i].x));
       GEOSCoordSeq_getY(coords, i, &(line.point[i].y));
       /* GEOSCoordSeq_getZ(coords, i, &(line.point[i].z)); */
     }
     msAddLineDirectly(shape, &line);
-    
+
     /* interior rings */
     numRings = GEOSGetNumInteriorRings(polygon);
 
     for(j=0; j<numRings; j++) {
       ring = (GEOSGeom) GEOSGetInteriorRingN(polygon, j);
-      if(GEOSisRing(ring) != 1) continue; /* skip it */      
+      if(GEOSisRing(ring) != 1) continue; /* skip it */
 
       numPoints = GEOSGetNumCoordinates(ring);
-      coords = (GEOSCoordSeq) GEOSGeom_getCoordSeq(ring);	  
+      coords = (GEOSCoordSeq) GEOSGeom_getCoordSeq(ring);
 
       line.point = (pointObj *) malloc(sizeof(pointObj)*numPoints);
       line.numpoints = numPoints;
 
       for(i=0; i<numPoints; i++) {
-	GEOSCoordSeq_getX(coords, i, &(line.point[i].x));
+        GEOSCoordSeq_getX(coords, i, &(line.point[i].x));
         GEOSCoordSeq_getY(coords, i, &(line.point[i].y));
         /* GEOSCoordSeq_getZ(coords, i, &(line.point[i].z)); */
       }
-      msAddLineDirectly(shape, &line);	  
+      msAddLineDirectly(shape, &line);
     }
   } /* next polygon */
 
-  msComputeBounds(shape); 
+  msComputeBounds(shape);
 
-  return shape; 
+  return shape;
 }
 
 shapeObj *msGEOSGeometry2Shape(GEOSGeom g)
 {
   int type;
 
-  if(!g) 
+  if(!g)
     return NULL; /* a NULL geometry generates a NULL shape */
 
   type = GEOSGeomTypeId(g);
   switch(type) {
-  case GEOS_POINT:
-    return msGEOSGeometry2Shape_point(g);
-    break;
-  case GEOS_MULTIPOINT:
-    return msGEOSGeometry2Shape_multipoint(g);
-    break;
-  case GEOS_LINESTRING:
-    return msGEOSGeometry2Shape_line(g);
-    break;
-  case GEOS_MULTILINESTRING:
-    return msGEOSGeometry2Shape_multiline(g);
-    break;
-  case GEOS_POLYGON:
-    return msGEOSGeometry2Shape_polygon(g);
-    break;
-  case GEOS_MULTIPOLYGON:
-    return msGEOSGeometry2Shape_multipolygon(g);
-    break;
-  default:
-    if (!GEOSisEmpty(g))
+    case GEOS_POINT:
+      return msGEOSGeometry2Shape_point(g);
+      break;
+    case GEOS_MULTIPOINT:
+      return msGEOSGeometry2Shape_multipoint(g);
+      break;
+    case GEOS_LINESTRING:
+      return msGEOSGeometry2Shape_line(g);
+      break;
+    case GEOS_MULTILINESTRING:
+      return msGEOSGeometry2Shape_multiline(g);
+      break;
+    case GEOS_POLYGON:
+      return msGEOSGeometry2Shape_polygon(g);
+      break;
+    case GEOS_MULTIPOLYGON:
+      return msGEOSGeometry2Shape_multipolygon(g);
+      break;
+    default:
+      if (!GEOSisEmpty(g))
         msSetError(MS_GEOSERR, "Unsupported GEOS geometry type (%d).", "msGEOSGeometry2Shape()", type);
-    return NULL;
+      return NULL;
   }
 }
 #endif
@@ -584,7 +586,7 @@ void msGEOSFreeGeometry(shapeObj *shape)
 #ifdef USE_GEOS
   GEOSGeom g=NULL;
 
-  if(!shape || !shape->geometry) 
+  if(!shape || !shape->geometry)
     return;
 
   g = (GEOSGeom) shape->geometry;
@@ -603,7 +605,7 @@ shapeObj *msGEOSShapeFromWKT(const char *wkt)
 #ifdef USE_GEOS
   GEOSGeom g;
 
-  if(!wkt) 
+  if(!wkt)
     return NULL;
 
   g = GEOSGeomFromWKT(wkt);
@@ -626,9 +628,9 @@ char *msGEOSShapeToWKT(shapeObj *shape)
 #ifdef USE_GEOS
   GEOSGeom g;
 
-  if(!shape) 
+  if(!shape)
     return NULL;
-    
+
   /* if we have a geometry, we should update it*/
   msGEOSFreeGeometry(shape);
 
@@ -661,9 +663,9 @@ void msGEOSFreeWKT(char* pszGEOSWKT)
 shapeObj *msGEOSBuffer(shapeObj *shape, double width)
 {
 #ifdef USE_GEOS
-  GEOSGeom g1, g2; 
+  GEOSGeom g1, g2;
 
-  if(!shape) 
+  if(!shape)
     return NULL;
 
   if(!shape->geometry) /* if no geometry for the shape then build one */
@@ -671,7 +673,7 @@ shapeObj *msGEOSBuffer(shapeObj *shape, double width)
 
   g1 = (GEOSGeom) shape->geometry;
   if(!g1) return NULL;
-  
+
   g2 = GEOSBuffer(g1, width, 30);
   return msGEOSGeometry2Shape(g2);
 #else
@@ -683,9 +685,9 @@ shapeObj *msGEOSBuffer(shapeObj *shape, double width)
 shapeObj *msGEOSSimplify(shapeObj *shape, double tolerance)
 {
 #ifdef USE_GEOS
-  GEOSGeom g1, g2; 
+  GEOSGeom g1, g2;
 
-  if(!shape) 
+  if(!shape)
     return NULL;
 
   if(!shape->geometry) /* if no geometry for the shape then build one */
@@ -693,7 +695,7 @@ shapeObj *msGEOSSimplify(shapeObj *shape, double tolerance)
 
   g1 = (GEOSGeom) shape->geometry;
   if(!g1) return NULL;
-  
+
   g2 = GEOSSimplify(g1, tolerance);
   return msGEOSGeometry2Shape(g2);
 #else
@@ -705,9 +707,9 @@ shapeObj *msGEOSSimplify(shapeObj *shape, double tolerance)
 shapeObj *msGEOSTopologyPreservingSimplify(shapeObj *shape, double tolerance)
 {
 #ifdef USE_GEOS
-  GEOSGeom g1, g2; 
+  GEOSGeom g1, g2;
 
-  if(!shape) 
+  if(!shape)
     return NULL;
 
   if(!shape->geometry) /* if no geometry for the shape then build one */
@@ -715,7 +717,7 @@ shapeObj *msGEOSTopologyPreservingSimplify(shapeObj *shape, double tolerance)
 
   g1 = (GEOSGeom) shape->geometry;
   if(!g1) return NULL;
-  
+
   g2 = GEOSTopologyPreserveSimplify(g1, tolerance);
   return msGEOSGeometry2Shape(g2);
 #else
@@ -901,7 +903,7 @@ shapeObj *msGEOSSymDifference(shapeObj *shape1, shapeObj *shape2)
 #endif
 }
 
-/* 
+/*
 ** Binary predicates exposed to MapServer/MapScript
 */
 
@@ -927,7 +929,7 @@ int msGEOSContains(shapeObj *shape1, shapeObj *shape2)
   g2 = shape2->geometry;
   if(!g2) return -1;
 
-  result = GEOSContains(g1, g2);  
+  result = GEOSContains(g1, g2);
   return ((result==2) ? -1 : result);
 #else
   msSetError(MS_GEOSERR, "GEOS support is not available.", "msGEOSContains()");
@@ -957,7 +959,7 @@ int msGEOSOverlaps(shapeObj *shape1, shapeObj *shape2)
   g2 = shape2->geometry;
   if(!g2) return -1;
 
-  result = GEOSOverlaps(g1, g2);  
+  result = GEOSOverlaps(g1, g2);
   return ((result==2) ? -1 : result);
 #else
   msSetError(MS_GEOSERR, "GEOS support is not available.", "msGEOSOverlaps()");
@@ -987,7 +989,7 @@ int msGEOSWithin(shapeObj *shape1, shapeObj *shape2)
   g2 = shape2->geometry;
   if(!g2) return -1;
 
-  result = GEOSWithin(g1, g2);  
+  result = GEOSWithin(g1, g2);
   return ((result==2) ? -1 : result);
 #else
   msSetError(MS_GEOSERR, "GEOS support is not available.", "msGEOSWithin()");
@@ -1017,7 +1019,7 @@ int msGEOSCrosses(shapeObj *shape1, shapeObj *shape2)
   g2 = shape2->geometry;
   if(!g2) return -1;
 
-  result = GEOSCrosses(g1, g2);  
+  result = GEOSCrosses(g1, g2);
   return ((result==2) ? -1 : result);
 #else
   msSetError(MS_GEOSERR, "GEOS support is not available.", "msGEOSCrosses()");
@@ -1047,29 +1049,29 @@ int msGEOSIntersects(shapeObj *shape1, shapeObj *shape2)
   g2 = (GEOSGeom) shape2->geometry;
   if(!g2) return -1;
 
-  result = GEOSIntersects(g1, g2);  
+  result = GEOSIntersects(g1, g2);
   return ((result==2) ? -1 : result);
 #else
   if(!shape1 || !shape2)
     return -1;
 
   switch(shape1->type) { /* todo: deal with point shapes */
-  case(MS_SHAPE_LINE):
-    switch(shape2->type) {
-    case(MS_SHAPE_LINE):
-      return msIntersectPolylines(shape1, shape2);
-    case(MS_SHAPE_POLYGON):
-      return msIntersectPolylinePolygon(shape1, shape2);
-    }
-    break;
-  case(MS_SHAPE_POLYGON):
-    switch(shape2->type) {
     case(MS_SHAPE_LINE):
-      return msIntersectPolylinePolygon(shape2, shape1);
+      switch(shape2->type) {
+        case(MS_SHAPE_LINE):
+          return msIntersectPolylines(shape1, shape2);
+        case(MS_SHAPE_POLYGON):
+          return msIntersectPolylinePolygon(shape1, shape2);
+      }
+      break;
     case(MS_SHAPE_POLYGON):
-      return msIntersectPolygons(shape1, shape2);
-    }
-    break;
+      switch(shape2->type) {
+        case(MS_SHAPE_LINE):
+          return msIntersectPolylinePolygon(shape2, shape1);
+        case(MS_SHAPE_POLYGON):
+          return msIntersectPolygons(shape1, shape2);
+      }
+      break;
   }
 
   return -1;
@@ -1098,7 +1100,7 @@ int msGEOSTouches(shapeObj *shape1, shapeObj *shape2)
   g2 = (GEOSGeom) shape2->geometry;
   if(!g2) return -1;
 
-  result = GEOSTouches(g1, g2);  
+  result = GEOSTouches(g1, g2);
   return ((result==2) ? -1 : result);
 #else
   msSetError(MS_GEOSERR, "GEOS support is not available.", "msGEOSTouches()");
@@ -1128,7 +1130,7 @@ int msGEOSEquals(shapeObj *shape1, shapeObj *shape2)
   g2 = (GEOSGeom) shape2->geometry;
   if(!g2) return -1;
 
-  result = GEOSEquals(g1, g2);  
+  result = GEOSEquals(g1, g2);
   return ((result==2) ? -1 : result);
 #else
   msSetError(MS_GEOSERR, "GEOS support is not available.", "msGEOSEquals()");
@@ -1158,7 +1160,7 @@ int msGEOSDisjoint(shapeObj *shape1, shapeObj *shape2)
   g2 = (GEOSGeom) shape2->geometry;
   if(!g2) return -1;
 
-  result = GEOSDisjoint(g1, g2);  
+  result = GEOSDisjoint(g1, g2);
   return ((result==2) ? -1 : result);
 #else
   msSetError(MS_GEOSERR, "GEOS support is not available.", "msGEOSDisjoint()");
@@ -1240,7 +1242,7 @@ double msGEOSDistance(shapeObj *shape1, shapeObj *shape2)
   g2 = (GEOSGeom) shape2->geometry;
   if(!g2) return -1;
 
-  result = GEOSDistance(g1, g2, &distance);  
+  result = GEOSDistance(g1, g2, &distance);
   return ((result==0) ? -1 : distance);
 #else
   return msDistanceShapeToShape(shape1, shape2); /* fall back on brute force method (for MapScript) */
diff --git a/mapgml.c b/mapgml.c
index 3cd64ed..049088c 100644
--- a/mapgml.c
+++ b/mapgml.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -31,7 +31,7 @@
 #include "maperror.h"
 #include "mapgml.h"
 
-MS_CVSID("$Id$")
+
 
 /* Use only mapgml.c if WMS or WFS is available (with minor exceptions at end)*/
 
@@ -45,7 +45,7 @@ static int msGMLGeometryLookup(gmlGeometryListObj *geometryList, char *type);
 
 /* GML 2.1.2 */
 static int gmlWriteBounds_GML2(FILE *stream, rectObj *rect, const char *srsname, char *tab)
-{ 
+{
   char *srsname_encoded;
 
   if(!stream) return(MS_FAILURE);
@@ -60,8 +60,8 @@ static int gmlWriteBounds_GML2(FILE *stream, rectObj *rect, const char *srsname,
   } else
     msIO_fprintf(stream, "%s\t<gml:Box>\n", tab);
 
-  msIO_fprintf(stream, "%s\t\t<gml:coordinates>", tab);  
-  msIO_fprintf(stream, "%.6f,%.6f %.6f,%.6f", rect->minx, rect->miny, rect->maxx, rect->maxy );   
+  msIO_fprintf(stream, "%s\t\t<gml:coordinates>", tab);
+  msIO_fprintf(stream, "%.6f,%.6f %.6f,%.6f", rect->minx, rect->miny, rect->maxx, rect->maxy );
   msIO_fprintf(stream, "</gml:coordinates>\n");
   msIO_fprintf(stream, "%s\t</gml:Box>\n", tab);
   msIO_fprintf(stream, "%s</gml:boundedBy>\n", tab);
@@ -71,7 +71,7 @@ static int gmlWriteBounds_GML2(FILE *stream, rectObj *rect, const char *srsname,
 
 /* GML 3.1 (MapServer limits GML encoding to the level 0 profile) */
 static int gmlWriteBounds_GML3(FILE *stream, rectObj *rect, const char *srsname, char *tab)
-{ 
+{
   char *srsname_encoded;
 
   if(!stream) return(MS_FAILURE);
@@ -88,7 +88,7 @@ static int gmlWriteBounds_GML3(FILE *stream, rectObj *rect, const char *srsname,
 
   msIO_fprintf(stream, "%s\t\t<gml:lowerCorner>%.6f %.6f</gml:lowerCorner>\n", tab, rect->minx, rect->miny);
   msIO_fprintf(stream, "%s\t\t<gml:upperCorner>%.6f %.6f</gml:upperCorner>\n", tab, rect->maxx, rect->maxy);
-  
+
   msIO_fprintf(stream, "%s\t</gml:Envelope>\n", tab);
   msIO_fprintf(stream, "%s</gml:boundedBy>\n", tab);
 
@@ -105,7 +105,7 @@ static void gmlStartGeometryContainer(FILE *stream, char *name, char *namespace,
     msIO_fprintf(stream, "%s<%s:%s>\n", tab, namespace, tag_name);
   else
     msIO_fprintf(stream, "%s<%s>\n", tab, tag_name);
-}  
+}
 
 static void gmlEndGeometryContainer(FILE *stream, char *name, char *namespace, const char *tab)
 {
@@ -117,10 +117,10 @@ static void gmlEndGeometryContainer(FILE *stream, char *name, char *namespace, c
     msIO_fprintf(stream, "%s</%s:%s>\n", tab, namespace, tag_name);
   else
     msIO_fprintf(stream, "%s</%s>\n", tab, tag_name);
-} 
+}
 
 /* GML 2.1.2 */
-static int gmlWriteGeometry_GML2(FILE *stream, gmlGeometryListObj *geometryList, shapeObj *shape, const char *srsname, char *namespace, char *tab)  
+static int gmlWriteGeometry_GML2(FILE *stream, gmlGeometryListObj *geometryList, shapeObj *shape, const char *srsname, char *namespace, char *tab)
 {
   int i, j, k;
   int *innerlist, *outerlist, numouters;
@@ -141,236 +141,236 @@ static int gmlWriteGeometry_GML2(FILE *stream, gmlGeometryListObj *geometryList,
 
   /* feature geometry */
   switch(shape->type) {
-  case(MS_SHAPE_POINT):
-    geometry_simple_index = msGMLGeometryLookup(geometryList, "point");
-    geometry_aggregate_index = msGMLGeometryLookup(geometryList, "multipoint");
-    if(geometry_simple_index >= 0) geometry_simple_name = geometryList->geometries[geometry_simple_index].name;
-    if(geometry_aggregate_index >= 0) geometry_aggregate_name = geometryList->geometries[geometry_aggregate_index].name;
-
-    if((geometry_simple_index != -1 && shape->line[0].numpoints == 1 && shape->numlines == 1) ||
-       (geometry_simple_index != -1 && geometry_aggregate_index == -1) ||
-       (geometryList->numgeometries == 0 && shape->line[0].numpoints == 1 && shape->numlines == 1)) { /* write a Point(s) */
-
-      for(i=0; i<shape->numlines; i++) {
-        for(j=0; j<shape->line[i].numpoints; j++) {
-          gmlStartGeometryContainer(stream, geometry_simple_name, namespace, tab);
-
-          /* Point */
-          if(srsname_encoded)
-            msIO_fprintf(stream, "%s<gml:Point srsName=\"%s\">\n", tab, srsname_encoded);
-          else
-            msIO_fprintf(stream, "%s<gml:Point>\n", tab);
-          msIO_fprintf(stream, "%s  <gml:coordinates>%f,%f</gml:coordinates>\n", tab, shape->line[i].point[j].x, shape->line[i].point[j].y);
-          msIO_fprintf(stream, "%s</gml:Point>\n", tab);
-
-          gmlEndGeometryContainer(stream, geometry_simple_name, namespace, tab);
-        }
-      }
-    } else if((geometry_aggregate_index != -1) || (geometryList->numgeometries == 0)) { /* write a MultiPoint */
-      gmlStartGeometryContainer(stream, geometry_aggregate_name, namespace, tab);
-
-      /* MultiPoint */
-      if(srsname_encoded)
-        msIO_fprintf(stream, "%s<gml:MultiPoint srsName=\"%s\">\n", tab, srsname_encoded);
-      else
-        msIO_fprintf(stream, "%s<gml:MultiPoint>\n", tab);
-
-      for(i=0; i<shape->numlines; i++) {
-        for(j=0; j<shape->line[i].numpoints; j++) {
-          msIO_fprintf(stream, "%s  <gml:pointMember>\n", tab);
-          msIO_fprintf(stream, "%s    <gml:Point>\n", tab);
-          msIO_fprintf(stream, "%s      <gml:coordinates>%f,%f</gml:coordinates>\n", tab, shape->line[i].point[j].x, shape->line[i].point[j].y);
-          msIO_fprintf(stream, "%s    </gml:Point>\n", tab);
-          msIO_fprintf(stream, "%s  </gml:pointMember>\n", tab);
+    case(MS_SHAPE_POINT):
+      geometry_simple_index = msGMLGeometryLookup(geometryList, "point");
+      geometry_aggregate_index = msGMLGeometryLookup(geometryList, "multipoint");
+      if(geometry_simple_index >= 0) geometry_simple_name = geometryList->geometries[geometry_simple_index].name;
+      if(geometry_aggregate_index >= 0) geometry_aggregate_name = geometryList->geometries[geometry_aggregate_index].name;
+
+      if((geometry_simple_index != -1 && shape->line[0].numpoints == 1 && shape->numlines == 1) ||
+          (geometry_simple_index != -1 && geometry_aggregate_index == -1) ||
+          (geometryList->numgeometries == 0 && shape->line[0].numpoints == 1 && shape->numlines == 1)) { /* write a Point(s) */
+
+        for(i=0; i<shape->numlines; i++) {
+          for(j=0; j<shape->line[i].numpoints; j++) {
+            gmlStartGeometryContainer(stream, geometry_simple_name, namespace, tab);
+
+            /* Point */
+            if(srsname_encoded)
+              msIO_fprintf(stream, "%s<gml:Point srsName=\"%s\">\n", tab, srsname_encoded);
+            else
+              msIO_fprintf(stream, "%s<gml:Point>\n", tab);
+            msIO_fprintf(stream, "%s  <gml:coordinates>%f,%f</gml:coordinates>\n", tab, shape->line[i].point[j].x, shape->line[i].point[j].y);
+            msIO_fprintf(stream, "%s</gml:Point>\n", tab);
+
+            gmlEndGeometryContainer(stream, geometry_simple_name, namespace, tab);
+          }
         }
-      }
+      } else if((geometry_aggregate_index != -1) || (geometryList->numgeometries == 0)) { /* write a MultiPoint */
+        gmlStartGeometryContainer(stream, geometry_aggregate_name, namespace, tab);
 
-      msIO_fprintf(stream, "%s</gml:MultiPoint>\n", tab);
-
-      gmlEndGeometryContainer(stream, geometry_aggregate_name, namespace, tab);
-    } else {
-      msIO_fprintf(stream, "<!-- Warning: Cannot write geometry- no point/multipoint geometry defined. -->\n");
-    }
-  
-    break;
-  case(MS_SHAPE_LINE):
-    geometry_simple_index = msGMLGeometryLookup(geometryList, "line");
-    geometry_aggregate_index = msGMLGeometryLookup(geometryList, "multiline");
-    if(geometry_simple_index >= 0) geometry_simple_name = geometryList->geometries[geometry_simple_index].name;
-    if(geometry_aggregate_index >= 0) geometry_aggregate_name = geometryList->geometries[geometry_aggregate_index].name;
-  
-    if((geometry_simple_index != -1 && shape->numlines == 1) ||
-       (geometry_simple_index != -1 && geometry_aggregate_index == -1) ||
-       (geometryList->numgeometries == 0 && shape->numlines == 1)) { /* write a LineStrings(s) */
-      for(i=0; i<shape->numlines; i++) {
-        gmlStartGeometryContainer(stream, geometry_simple_name, namespace, tab);
-
-        /* LineString */
+        /* MultiPoint */
         if(srsname_encoded)
-          msIO_fprintf(stream, "%s<gml:LineString srsName=\"%s\">\n", tab, srsname_encoded);
+          msIO_fprintf(stream, "%s<gml:MultiPoint srsName=\"%s\">\n", tab, srsname_encoded);
         else
-          msIO_fprintf(stream, "%s<gml:LineString>\n", tab);
-
-        msIO_fprintf(stream, "%s  <gml:coordinates>", tab);
-        for(j=0; j<shape->line[i].numpoints; j++)
-          msIO_fprintf(stream, "%f,%f ", shape->line[i].point[j].x, shape->line[i].point[j].y);
-        msIO_fprintf(stream, "</gml:coordinates>\n");
+          msIO_fprintf(stream, "%s<gml:MultiPoint>\n", tab);
+
+        for(i=0; i<shape->numlines; i++) {
+          for(j=0; j<shape->line[i].numpoints; j++) {
+            msIO_fprintf(stream, "%s  <gml:pointMember>\n", tab);
+            msIO_fprintf(stream, "%s    <gml:Point>\n", tab);
+            msIO_fprintf(stream, "%s      <gml:coordinates>%f,%f</gml:coordinates>\n", tab, shape->line[i].point[j].x, shape->line[i].point[j].y);
+            msIO_fprintf(stream, "%s    </gml:Point>\n", tab);
+            msIO_fprintf(stream, "%s  </gml:pointMember>\n", tab);
+          }
+        }
 
-        msIO_fprintf(stream, "%s</gml:LineString>\n", tab);
+        msIO_fprintf(stream, "%s</gml:MultiPoint>\n", tab);
 
-        gmlEndGeometryContainer(stream, geometry_simple_name, namespace, tab);
-      }
-    } else if(geometry_aggregate_index != -1 || (geometryList->numgeometries == 0)) { /* write a MultiCurve */
-      gmlStartGeometryContainer(stream, geometry_aggregate_name, namespace, tab);
-
-      /* MultiLineString */
-      if(srsname_encoded)
-        msIO_fprintf(stream, "%s<gml:MultiLineString srsName=\"%s\">\n", tab, srsname_encoded);
-      else
-        msIO_fprintf(stream, "%s<gml:MultiLineString>\n", tab);
-
-      for(j=0; j<shape->numlines; j++) {
-        msIO_fprintf(stream, "%s  <gml:lineStringMember>\n", tab); /* no srsname at this point */
-        msIO_fprintf(stream, "%s    <gml:LineString>\n", tab); /* no srsname at this point */
-
-        msIO_fprintf(stream, "%s      <gml:coordinates>", tab);
-        for(i=0; i<shape->line[j].numpoints; i++)
-          msIO_fprintf(stream, "%f,%f ", shape->line[j].point[i].x, shape->line[j].point[i].y);
-        msIO_fprintf(stream, "</gml:coordinates>\n");
-        msIO_fprintf(stream, "%s    </gml:LineString>\n", tab);
-        msIO_fprintf(stream, "%s  </gml:lineStringMember>\n", tab);
+        gmlEndGeometryContainer(stream, geometry_aggregate_name, namespace, tab);
+      } else {
+        msIO_fprintf(stream, "<!-- Warning: Cannot write geometry- no point/multipoint geometry defined. -->\n");
       }
-      
-      msIO_fprintf(stream, "%s</gml:MultiLineString>\n", tab);
 
-      gmlEndGeometryContainer(stream, geometry_aggregate_name, namespace, tab);
-    } else {
-      msIO_fprintf(stream, "<!-- Warning: Cannot write geometry- no line/multiline geometry defined. -->\n");
-    }
-    
-    break;
-  case(MS_SHAPE_POLYGON): /* this gets nasty, since our shapes are so flexible */
-    geometry_simple_index = msGMLGeometryLookup(geometryList, "polygon");
-    geometry_aggregate_index = msGMLGeometryLookup(geometryList, "multipolygon");
-    if(geometry_simple_index >= 0) geometry_simple_name = geometryList->geometries[geometry_simple_index].name;
-    if(geometry_aggregate_index >= 0) geometry_aggregate_name = geometryList->geometries[geometry_aggregate_index].name;
-
-    /* get a list of outter rings for this polygon */
-    outerlist = msGetOuterList(shape);
+      break;
+    case(MS_SHAPE_LINE):
+      geometry_simple_index = msGMLGeometryLookup(geometryList, "line");
+      geometry_aggregate_index = msGMLGeometryLookup(geometryList, "multiline");
+      if(geometry_simple_index >= 0) geometry_simple_name = geometryList->geometries[geometry_simple_index].name;
+      if(geometry_aggregate_index >= 0) geometry_aggregate_name = geometryList->geometries[geometry_aggregate_index].name;
+
+      if((geometry_simple_index != -1 && shape->numlines == 1) ||
+          (geometry_simple_index != -1 && geometry_aggregate_index == -1) ||
+          (geometryList->numgeometries == 0 && shape->numlines == 1)) { /* write a LineStrings(s) */
+        for(i=0; i<shape->numlines; i++) {
+          gmlStartGeometryContainer(stream, geometry_simple_name, namespace, tab);
 
-    numouters = 0;
-    for(i=0; i<shape->numlines; i++)
-      if(outerlist[i] == MS_TRUE) numouters++;
+          /* LineString */
+          if(srsname_encoded)
+            msIO_fprintf(stream, "%s<gml:LineString srsName=\"%s\">\n", tab, srsname_encoded);
+          else
+            msIO_fprintf(stream, "%s<gml:LineString>\n", tab);
 
-    if((geometry_simple_index != -1 && numouters == 1) ||
-       (geometry_simple_index != -1 && geometry_aggregate_index == -1) ||
-       (geometryList->numgeometries == 0 && shape->numlines == 1)) { /* write a Polygon(s) */
-      for(i=0; i<shape->numlines; i++) {
-        if(outerlist[i] == MS_FALSE) break; /* skip non-outer rings, each outer ring is a new polygon */
+          msIO_fprintf(stream, "%s  <gml:coordinates>", tab);
+          for(j=0; j<shape->line[i].numpoints; j++)
+            msIO_fprintf(stream, "%f,%f ", shape->line[i].point[j].x, shape->line[i].point[j].y);
+          msIO_fprintf(stream, "</gml:coordinates>\n");
 
-        /* get a list of inner rings for this polygon */
-        innerlist = msGetInnerList(shape, i, outerlist);
+          msIO_fprintf(stream, "%s</gml:LineString>\n", tab);
 
-        gmlStartGeometryContainer(stream, geometry_simple_name, namespace, tab);
+          gmlEndGeometryContainer(stream, geometry_simple_name, namespace, tab);
+        }
+      } else if(geometry_aggregate_index != -1 || (geometryList->numgeometries == 0)) { /* write a MultiCurve */
+        gmlStartGeometryContainer(stream, geometry_aggregate_name, namespace, tab);
 
-        /* Polygon */
+        /* MultiLineString */
         if(srsname_encoded)
-          msIO_fprintf(stream, "%s<gml:Polygon srsName=\"%s\">\n", tab, srsname_encoded);
+          msIO_fprintf(stream, "%s<gml:MultiLineString srsName=\"%s\">\n", tab, srsname_encoded);
         else
-          msIO_fprintf(stream, "%s<gml:Polygon>\n", tab);
+          msIO_fprintf(stream, "%s<gml:MultiLineString>\n", tab);
 
-        msIO_fprintf(stream, "%s  <gml:outerBoundaryIs>\n", tab);
-        msIO_fprintf(stream, "%s    <gml:LinearRing>\n", tab);
+        for(j=0; j<shape->numlines; j++) {
+          msIO_fprintf(stream, "%s  <gml:lineStringMember>\n", tab); /* no srsname at this point */
+          msIO_fprintf(stream, "%s    <gml:LineString>\n", tab); /* no srsname at this point */
 
-        msIO_fprintf(stream, "%s      <gml:coordinates>", tab);
-        for(j=0; j<shape->line[i].numpoints; j++)
-          msIO_fprintf(stream, "%f,%f ", shape->line[i].point[j].x, shape->line[i].point[j].y);
-        msIO_fprintf(stream, "</gml:coordinates>\n");
+          msIO_fprintf(stream, "%s      <gml:coordinates>", tab);
+          for(i=0; i<shape->line[j].numpoints; i++)
+            msIO_fprintf(stream, "%f,%f ", shape->line[j].point[i].x, shape->line[j].point[i].y);
+          msIO_fprintf(stream, "</gml:coordinates>\n");
+          msIO_fprintf(stream, "%s    </gml:LineString>\n", tab);
+          msIO_fprintf(stream, "%s  </gml:lineStringMember>\n", tab);
+        }
 
-        msIO_fprintf(stream, "%s    </gml:LinearRing>\n", tab);
-        msIO_fprintf(stream, "%s  </gml:outerBoundaryIs>\n", tab);
+        msIO_fprintf(stream, "%s</gml:MultiLineString>\n", tab);
 
-        for(k=0; k<shape->numlines; k++) { /* now step through all the inner rings */
-        if(innerlist[k] == MS_TRUE) {
-          msIO_fprintf(stream, "%s  <gml:innerBoundaryIs>\n", tab);
-          msIO_fprintf(stream, "%s    <gml:LinearRing>\n", tab);
+        gmlEndGeometryContainer(stream, geometry_aggregate_name, namespace, tab);
+      } else {
+        msIO_fprintf(stream, "<!-- Warning: Cannot write geometry- no line/multiline geometry defined. -->\n");
+      }
 
-            msIO_fprintf(stream, "%s      <gml:coordinates>", tab);
-            for(j=0; j<shape->line[k].numpoints; j++)
-              msIO_fprintf(stream, "%f,%f ", shape->line[k].point[j].x, shape->line[k].point[j].y);
-            msIO_fprintf(stream, "</gml:coordinates>\n");
-    
-            msIO_fprintf(stream, "%s    </gml:LinearRing>\n", tab);
-            msIO_fprintf(stream, "%s  </gml:innerBoundaryIs>\n", tab);
-          }
-        }
+      break;
+    case(MS_SHAPE_POLYGON): /* this gets nasty, since our shapes are so flexible */
+      geometry_simple_index = msGMLGeometryLookup(geometryList, "polygon");
+      geometry_aggregate_index = msGMLGeometryLookup(geometryList, "multipolygon");
+      if(geometry_simple_index >= 0) geometry_simple_name = geometryList->geometries[geometry_simple_index].name;
+      if(geometry_aggregate_index >= 0) geometry_aggregate_name = geometryList->geometries[geometry_aggregate_index].name;
 
-        msIO_fprintf(stream, "%s</gml:Polygon>\n", tab);
-        free(innerlist);
+      /* get a list of outter rings for this polygon */
+      outerlist = msGetOuterList(shape);
 
-        gmlEndGeometryContainer(stream, geometry_simple_name, namespace, tab);
-      }
-      free(outerlist);
-    } else if(geometry_aggregate_index != -1 || (geometryList->numgeometries == 0)) { /* write a MultiPolygon */  
-      gmlStartGeometryContainer(stream, geometry_aggregate_name, namespace, tab);
-
-      /* MultiPolygon */
-      if(srsname_encoded)
-        msIO_fprintf(stream, "%s<gml:MultiPolygon srsName=\"%s\">\n", tab, srsname_encoded);
-      else
-        msIO_fprintf(stream, "%s<gml:MultiPolygon>\n", tab);
-      
-      for(i=0; i<shape->numlines; i++) { /* step through the outer rings */
-        if(outerlist[i] == MS_TRUE) {
+      numouters = 0;
+      for(i=0; i<shape->numlines; i++)
+        if(outerlist[i] == MS_TRUE) numouters++;
+
+      if((geometry_simple_index != -1 && numouters == 1) ||
+          (geometry_simple_index != -1 && geometry_aggregate_index == -1) ||
+          (geometryList->numgeometries == 0 && shape->numlines == 1)) { /* write a Polygon(s) */
+        for(i=0; i<shape->numlines; i++) {
+          if(outerlist[i] == MS_FALSE) break; /* skip non-outer rings, each outer ring is a new polygon */
+
+          /* get a list of inner rings for this polygon */
           innerlist = msGetInnerList(shape, i, outerlist);
 
-          msIO_fprintf(stream, "%s<gml:polygonMember>\n", tab);
-          msIO_fprintf(stream, "%s  <gml:Polygon>\n", tab);
+          gmlStartGeometryContainer(stream, geometry_simple_name, namespace, tab);
 
-          msIO_fprintf(stream, "%s    <gml:outerBoundaryIs>\n", tab);
-          msIO_fprintf(stream, "%s      <gml:LinearRing>\n", tab);
+          /* Polygon */
+          if(srsname_encoded)
+            msIO_fprintf(stream, "%s<gml:Polygon srsName=\"%s\">\n", tab, srsname_encoded);
+          else
+            msIO_fprintf(stream, "%s<gml:Polygon>\n", tab);
 
-          msIO_fprintf(stream, "%s        <gml:coordinates>", tab);
+          msIO_fprintf(stream, "%s  <gml:outerBoundaryIs>\n", tab);
+          msIO_fprintf(stream, "%s    <gml:LinearRing>\n", tab);
+
+          msIO_fprintf(stream, "%s      <gml:coordinates>", tab);
           for(j=0; j<shape->line[i].numpoints; j++)
             msIO_fprintf(stream, "%f,%f ", shape->line[i].point[j].x, shape->line[i].point[j].y);
           msIO_fprintf(stream, "</gml:coordinates>\n");
 
-          msIO_fprintf(stream, "%s      </gml:LinearRing>\n", tab);
-          msIO_fprintf(stream, "%s    </gml:outerBoundaryIs>\n", tab);
+          msIO_fprintf(stream, "%s    </gml:LinearRing>\n", tab);
+          msIO_fprintf(stream, "%s  </gml:outerBoundaryIs>\n", tab);
 
           for(k=0; k<shape->numlines; k++) { /* now step through all the inner rings */
             if(innerlist[k] == MS_TRUE) {
-              msIO_fprintf(stream, "%s    <gml:innerBoundaryIs>\n", tab);
-              msIO_fprintf(stream, "%s      <gml:LinearRing>\n", tab);
+              msIO_fprintf(stream, "%s  <gml:innerBoundaryIs>\n", tab);
+              msIO_fprintf(stream, "%s    <gml:LinearRing>\n", tab);
 
-              msIO_fprintf(stream, "%s        <gml:coordinates>", tab);
+              msIO_fprintf(stream, "%s      <gml:coordinates>", tab);
               for(j=0; j<shape->line[k].numpoints; j++)
                 msIO_fprintf(stream, "%f,%f ", shape->line[k].point[j].x, shape->line[k].point[j].y);
               msIO_fprintf(stream, "</gml:coordinates>\n");
 
-              msIO_fprintf(stream, "%s      </gml:LinearRing>\n", tab);
-              msIO_fprintf(stream, "%s    </gml:innerBoundaryIs>\n", tab);
+              msIO_fprintf(stream, "%s    </gml:LinearRing>\n", tab);
+              msIO_fprintf(stream, "%s  </gml:innerBoundaryIs>\n", tab);
             }
           }
 
-          msIO_fprintf(stream, "%s  </gml:Polygon>\n", tab);
-          msIO_fprintf(stream, "%s</gml:polygonMember>\n", tab);
-
+          msIO_fprintf(stream, "%s</gml:Polygon>\n", tab);
           free(innerlist);
+
+          gmlEndGeometryContainer(stream, geometry_simple_name, namespace, tab);
         }
-      }
-      msIO_fprintf(stream, "%s</gml:MultiPolygon>\n", tab);
+        free(outerlist);
+      } else if(geometry_aggregate_index != -1 || (geometryList->numgeometries == 0)) { /* write a MultiPolygon */
+        gmlStartGeometryContainer(stream, geometry_aggregate_name, namespace, tab);
+
+        /* MultiPolygon */
+        if(srsname_encoded)
+          msIO_fprintf(stream, "%s<gml:MultiPolygon srsName=\"%s\">\n", tab, srsname_encoded);
+        else
+          msIO_fprintf(stream, "%s<gml:MultiPolygon>\n", tab);
 
-      free(outerlist);
+        for(i=0; i<shape->numlines; i++) { /* step through the outer rings */
+          if(outerlist[i] == MS_TRUE) {
+            innerlist = msGetInnerList(shape, i, outerlist);
 
-      gmlEndGeometryContainer(stream, geometry_aggregate_name, namespace, tab);
-    } else {
-      msIO_fprintf(stream, "<!-- Warning: Cannot write geometry- no polygon/multipolygon geometry defined. -->\n");
-    }
-  
-    break;
-  default:
-    break;
+            msIO_fprintf(stream, "%s<gml:polygonMember>\n", tab);
+            msIO_fprintf(stream, "%s  <gml:Polygon>\n", tab);
+
+            msIO_fprintf(stream, "%s    <gml:outerBoundaryIs>\n", tab);
+            msIO_fprintf(stream, "%s      <gml:LinearRing>\n", tab);
+
+            msIO_fprintf(stream, "%s        <gml:coordinates>", tab);
+            for(j=0; j<shape->line[i].numpoints; j++)
+              msIO_fprintf(stream, "%f,%f ", shape->line[i].point[j].x, shape->line[i].point[j].y);
+            msIO_fprintf(stream, "</gml:coordinates>\n");
+
+            msIO_fprintf(stream, "%s      </gml:LinearRing>\n", tab);
+            msIO_fprintf(stream, "%s    </gml:outerBoundaryIs>\n", tab);
+
+            for(k=0; k<shape->numlines; k++) { /* now step through all the inner rings */
+              if(innerlist[k] == MS_TRUE) {
+                msIO_fprintf(stream, "%s    <gml:innerBoundaryIs>\n", tab);
+                msIO_fprintf(stream, "%s      <gml:LinearRing>\n", tab);
+
+                msIO_fprintf(stream, "%s        <gml:coordinates>", tab);
+                for(j=0; j<shape->line[k].numpoints; j++)
+                  msIO_fprintf(stream, "%f,%f ", shape->line[k].point[j].x, shape->line[k].point[j].y);
+                msIO_fprintf(stream, "</gml:coordinates>\n");
+
+                msIO_fprintf(stream, "%s      </gml:LinearRing>\n", tab);
+                msIO_fprintf(stream, "%s    </gml:innerBoundaryIs>\n", tab);
+              }
+            }
+
+            msIO_fprintf(stream, "%s  </gml:Polygon>\n", tab);
+            msIO_fprintf(stream, "%s</gml:polygonMember>\n", tab);
+
+            free(innerlist);
+          }
+        }
+        msIO_fprintf(stream, "%s</gml:MultiPolygon>\n", tab);
+
+        free(outerlist);
+
+        gmlEndGeometryContainer(stream, geometry_aggregate_name, namespace, tab);
+      } else {
+        msIO_fprintf(stream, "<!-- Warning: Cannot write geometry- no polygon/multipolygon geometry defined. -->\n");
+      }
+
+      break;
+    default:
+      break;
   }
 
   /* clean-up */
@@ -380,7 +380,7 @@ static int gmlWriteGeometry_GML2(FILE *stream, gmlGeometryListObj *geometryList,
 }
 
 /* GML 3.1 (MapServer limits GML encoding to the level 0 profile) */
-static int gmlWriteGeometry_GML3(FILE *stream, gmlGeometryListObj *geometryList, shapeObj *shape, const char *srsname, char *namespace, char *tab) 
+static int gmlWriteGeometry_GML3(FILE *stream, gmlGeometryListObj *geometryList, shapeObj *shape, const char *srsname, char *namespace, char *tab)
 {
   int i, j, k;
   int *innerlist, *outerlist, numouters;
@@ -401,238 +401,238 @@ static int gmlWriteGeometry_GML3(FILE *stream, gmlGeometryListObj *geometryList,
 
   /* feature geometry */
   switch(shape->type) {
-  case(MS_SHAPE_POINT):
-    geometry_simple_index = msGMLGeometryLookup(geometryList, "point");
-    geometry_aggregate_index = msGMLGeometryLookup(geometryList, "multipoint");
-    if(geometry_simple_index >= 0) geometry_simple_name = geometryList->geometries[geometry_simple_index].name;
-    if(geometry_aggregate_index >= 0) geometry_aggregate_name = geometryList->geometries[geometry_aggregate_index].name;
-
-    if((geometry_simple_index != -1 && shape->line[0].numpoints == 1 && shape->numlines == 1) ||
-       (geometry_simple_index != -1 && geometry_aggregate_index == -1) ||
-       (geometryList->numgeometries == 0 && shape->line[0].numpoints == 1 && shape->numlines == 1)) { /* write a Point(s) */
-
-      for(i=0; i<shape->numlines; i++) {
-        for(j=0; j<shape->line[i].numpoints; j++) {
-          gmlStartGeometryContainer(stream, geometry_simple_name, namespace, tab);
-
-          /* Point */
-          if(srsname_encoded)
-            msIO_fprintf(stream, "%s  <gml:Point srsName=\"%s\">\n", tab, srsname_encoded);
-          else
-            msIO_fprintf(stream, "%s  <gml:Point>\n", tab);
-          msIO_fprintf(stream, "%s    <gml:pos>%f %f</gml:pos>\n", tab, shape->line[i].point[j].x, shape->line[i].point[j].y);
-          msIO_fprintf(stream, "%s  </gml:Point>\n", tab);
-
-          gmlEndGeometryContainer(stream, geometry_simple_name, namespace, tab);
-        }
-      }
-    } else if((geometry_aggregate_index != -1) || (geometryList->numgeometries == 0)) { /* write a MultiPoint */      
-      gmlStartGeometryContainer(stream, geometry_aggregate_name, namespace, tab);
-      
-      /* MultiPoint */
-      if(srsname_encoded)
-        msIO_fprintf(stream, "%s  <gml:MultiPoint srsName=\"%s\">\n", tab, srsname_encoded);
-      else
-        msIO_fprintf(stream, "%s  <gml:MultiPoint>\n", tab);
-
-      msIO_fprintf(stream, "%s    <gml:pointMembers>\n", tab);
-      for(i=0; i<shape->numlines; i++) {
-        for(j=0; j<shape->line[i].numpoints; j++) {
-          msIO_fprintf(stream, "%s      <gml:Point>\n", tab);
-          msIO_fprintf(stream, "%s        <gml:pos>%f %f</gml:pos>\n", tab, shape->line[i].point[j].x, shape->line[i].point[j].y);
-          msIO_fprintf(stream, "%s      </gml:Point>\n", tab);
+    case(MS_SHAPE_POINT):
+      geometry_simple_index = msGMLGeometryLookup(geometryList, "point");
+      geometry_aggregate_index = msGMLGeometryLookup(geometryList, "multipoint");
+      if(geometry_simple_index >= 0) geometry_simple_name = geometryList->geometries[geometry_simple_index].name;
+      if(geometry_aggregate_index >= 0) geometry_aggregate_name = geometryList->geometries[geometry_aggregate_index].name;
+
+      if((geometry_simple_index != -1 && shape->line[0].numpoints == 1 && shape->numlines == 1) ||
+          (geometry_simple_index != -1 && geometry_aggregate_index == -1) ||
+          (geometryList->numgeometries == 0 && shape->line[0].numpoints == 1 && shape->numlines == 1)) { /* write a Point(s) */
+
+        for(i=0; i<shape->numlines; i++) {
+          for(j=0; j<shape->line[i].numpoints; j++) {
+            gmlStartGeometryContainer(stream, geometry_simple_name, namespace, tab);
+
+            /* Point */
+            if(srsname_encoded)
+              msIO_fprintf(stream, "%s  <gml:Point srsName=\"%s\">\n", tab, srsname_encoded);
+            else
+              msIO_fprintf(stream, "%s  <gml:Point>\n", tab);
+            msIO_fprintf(stream, "%s    <gml:pos>%f %f</gml:pos>\n", tab, shape->line[i].point[j].x, shape->line[i].point[j].y);
+            msIO_fprintf(stream, "%s  </gml:Point>\n", tab);
+
+            gmlEndGeometryContainer(stream, geometry_simple_name, namespace, tab);
+          }
         }
-      }
-      msIO_fprintf(stream, "%s    </gml:pointMembers>\n", tab);
-      
-      msIO_fprintf(stream, "%s  </gml:MultiPoint>\n", tab);
+      } else if((geometry_aggregate_index != -1) || (geometryList->numgeometries == 0)) { /* write a MultiPoint */
+        gmlStartGeometryContainer(stream, geometry_aggregate_name, namespace, tab);
 
-      gmlEndGeometryContainer(stream, geometry_aggregate_name, namespace, tab);
-    } else {
-      msIO_fprintf(stream, "<!-- Warning: Cannot write geometry- no point/multipoint geometry defined. -->\n");
-    }
- 
-    break;
-  case(MS_SHAPE_LINE):    
-    geometry_simple_index = msGMLGeometryLookup(geometryList, "line");
-    geometry_aggregate_index = msGMLGeometryLookup(geometryList, "multiline");
-    if(geometry_simple_index >= 0) geometry_simple_name = geometryList->geometries[geometry_simple_index].name;
-    if(geometry_aggregate_index >= 0) geometry_aggregate_name = geometryList->geometries[geometry_aggregate_index].name;
-
-    if((geometry_simple_index != -1 && shape->numlines == 1) ||
-       (geometry_simple_index != -1 && geometry_aggregate_index == -1) ||
-       (geometryList->numgeometries == 0 && shape->numlines == 1)) { /* write a LineStrings(s) */
-      for(i=0; i<shape->numlines; i++) {
-        gmlStartGeometryContainer(stream, geometry_simple_name, namespace, tab);
-
-        /* LineString (should be Curve?) */
+        /* MultiPoint */
         if(srsname_encoded)
-          msIO_fprintf(stream, "%s  <gml:LineString srsName=\"%s\">\n", tab, srsname_encoded);
+          msIO_fprintf(stream, "%s  <gml:MultiPoint srsName=\"%s\">\n", tab, srsname_encoded);
         else
-          msIO_fprintf(stream, "%s  <gml:LineString>\n", tab);
-
-        msIO_fprintf(stream, "%s    <gml:posList srsDimension=\"2\">", tab);
-        for(j=0; j<shape->line[i].numpoints; j++)
-          msIO_fprintf(stream, "%f %f ", shape->line[i].point[j].x, shape->line[i].point[j].y);
-        msIO_fprintf(stream, "</gml:posList>\n");
+          msIO_fprintf(stream, "%s  <gml:MultiPoint>\n", tab);
+
+        msIO_fprintf(stream, "%s    <gml:pointMembers>\n", tab);
+        for(i=0; i<shape->numlines; i++) {
+          for(j=0; j<shape->line[i].numpoints; j++) {
+            msIO_fprintf(stream, "%s      <gml:Point>\n", tab);
+            msIO_fprintf(stream, "%s        <gml:pos>%f %f</gml:pos>\n", tab, shape->line[i].point[j].x, shape->line[i].point[j].y);
+            msIO_fprintf(stream, "%s      </gml:Point>\n", tab);
+          }
+        }
+        msIO_fprintf(stream, "%s    </gml:pointMembers>\n", tab);
 
-        msIO_fprintf(stream, "%s  </gml:LineString>\n", tab);
+        msIO_fprintf(stream, "%s  </gml:MultiPoint>\n", tab);
 
-        gmlEndGeometryContainer(stream, geometry_simple_name, namespace, tab);
-      }
-    } else if(geometry_aggregate_index != -1 || (geometryList->numgeometries == 0)) { /* write a MultiCurve */      
-      gmlStartGeometryContainer(stream, geometry_aggregate_name, namespace, tab);
-
-      /* MultiCurve */
-      if(srsname_encoded)
-        msIO_fprintf(stream, "%s  <gml:MultiCurve srsName=\"%s\">\n", tab, srsname_encoded);
-      else 
-        msIO_fprintf(stream, "%s  <gml:MultiCurve>\n", tab);
-
-      msIO_fprintf(stream, "%s    <gml:curveMembers>\n", tab);
-      for(i=0; i<shape->numlines; i++) {
-        msIO_fprintf(stream, "%s      <gml:LineString>\n", tab); /* no srsname at this point */
-
-        msIO_fprintf(stream, "%s        <gml:posList srsDimension=\"2\">", tab);
-        for(j=0; j<shape->line[i].numpoints; j++)
-          msIO_fprintf(stream, "%f %f ", shape->line[i].point[j].x, shape->line[i].point[j].y);
-        msIO_fprintf(stream, "</gml:posList>\n");
-        msIO_fprintf(stream, "%s      </gml:LineString>\n", tab);
+        gmlEndGeometryContainer(stream, geometry_aggregate_name, namespace, tab);
+      } else {
+        msIO_fprintf(stream, "<!-- Warning: Cannot write geometry- no point/multipoint geometry defined. -->\n");
       }
-      msIO_fprintf(stream, "%s    </gml:curveMembers>\n", tab);
-  
-      msIO_fprintf(stream, "%s  </gml:MultiCurve>\n", tab);
-
-      gmlEndGeometryContainer(stream, geometry_aggregate_name, namespace, tab);      
-    } else {
-      msIO_fprintf(stream, "<!-- Warning: Cannot write geometry- no line/multiline geometry defined. -->\n");
-    }
 
-    break;
-  case(MS_SHAPE_POLYGON): /* this gets nasty, since our shapes are so flexible */
-    geometry_simple_index = msGMLGeometryLookup(geometryList, "polygon");
-    geometry_aggregate_index = msGMLGeometryLookup(geometryList, "multipolygon");
-    if(geometry_simple_index >= 0) geometry_simple_name = geometryList->geometries[geometry_simple_index].name;
-    if(geometry_aggregate_index >= 0) geometry_aggregate_name = geometryList->geometries[geometry_aggregate_index].name;
-
-    /* get a list of outter rings for this polygon */
-    outerlist = msGetOuterList(shape);
+      break;
+    case(MS_SHAPE_LINE):
+      geometry_simple_index = msGMLGeometryLookup(geometryList, "line");
+      geometry_aggregate_index = msGMLGeometryLookup(geometryList, "multiline");
+      if(geometry_simple_index >= 0) geometry_simple_name = geometryList->geometries[geometry_simple_index].name;
+      if(geometry_aggregate_index >= 0) geometry_aggregate_name = geometryList->geometries[geometry_aggregate_index].name;
+
+      if((geometry_simple_index != -1 && shape->numlines == 1) ||
+          (geometry_simple_index != -1 && geometry_aggregate_index == -1) ||
+          (geometryList->numgeometries == 0 && shape->numlines == 1)) { /* write a LineStrings(s) */
+        for(i=0; i<shape->numlines; i++) {
+          gmlStartGeometryContainer(stream, geometry_simple_name, namespace, tab);
 
-    numouters = 0;
-    for(i=0; i<shape->numlines; i++)
-      if(outerlist[i] == MS_TRUE) numouters++;
+          /* LineString (should be Curve?) */
+          if(srsname_encoded)
+            msIO_fprintf(stream, "%s  <gml:LineString srsName=\"%s\">\n", tab, srsname_encoded);
+          else
+            msIO_fprintf(stream, "%s  <gml:LineString>\n", tab);
 
-    if((geometry_simple_index != -1 && numouters == 1) ||
-       (geometry_simple_index != -1 && geometry_aggregate_index == -1) ||
-       (geometryList->numgeometries == 0 && shape->numlines == 1)) { /* write a Polygon(s) */
-      for(i=0; i<shape->numlines; i++) {
-        if(outerlist[i] == MS_FALSE) break; /* skip non-outer rings, each outer ring is a new polygon */
+          msIO_fprintf(stream, "%s    <gml:posList srsDimension=\"2\">", tab);
+          for(j=0; j<shape->line[i].numpoints; j++)
+            msIO_fprintf(stream, "%f %f ", shape->line[i].point[j].x, shape->line[i].point[j].y);
+          msIO_fprintf(stream, "</gml:posList>\n");
 
-        /* get a list of inner rings for this polygon */
-        innerlist = msGetInnerList(shape, i, outerlist);
+          msIO_fprintf(stream, "%s  </gml:LineString>\n", tab);
 
-        gmlStartGeometryContainer(stream, geometry_simple_name, namespace, tab);
+          gmlEndGeometryContainer(stream, geometry_simple_name, namespace, tab);
+        }
+      } else if(geometry_aggregate_index != -1 || (geometryList->numgeometries == 0)) { /* write a MultiCurve */
+        gmlStartGeometryContainer(stream, geometry_aggregate_name, namespace, tab);
 
-        /* Polygon (should be Surface?) */
+        /* MultiCurve */
         if(srsname_encoded)
-          msIO_fprintf(stream, "%s  <gml:Polygon srsName=\"%s\">\n", tab, srsname_encoded);
+          msIO_fprintf(stream, "%s  <gml:MultiCurve srsName=\"%s\">\n", tab, srsname_encoded);
         else
-          msIO_fprintf(stream, "%s  <gml:Polygon>\n", tab);
+          msIO_fprintf(stream, "%s  <gml:MultiCurve>\n", tab);
 
-        msIO_fprintf(stream, "%s    <gml:exterior>\n", tab);
-        msIO_fprintf(stream, "%s      <gml:LinearRing>\n", tab);
+        msIO_fprintf(stream, "%s    <gml:curveMembers>\n", tab);
+        for(i=0; i<shape->numlines; i++) {
+          msIO_fprintf(stream, "%s      <gml:LineString>\n", tab); /* no srsname at this point */
 
-        msIO_fprintf(stream, "%s        <gml:posList srsDimension=\"2\">", tab);
-        for(j=0; j<shape->line[i].numpoints; j++)
-          msIO_fprintf(stream, "%f %f ", shape->line[i].point[j].x, shape->line[i].point[j].y);
-        msIO_fprintf(stream, "</gml:posList>\n");
-
-        msIO_fprintf(stream, "%s      </gml:LinearRing>\n", tab);
-        msIO_fprintf(stream, "%s    </gml:exterior>\n", tab);
-
-        for(k=0; k<shape->numlines; k++) { /* now step through all the inner rings */
-          if(innerlist[k] == MS_TRUE) {
-            msIO_fprintf(stream, "%s    <gml:interior>\n", tab);
-            msIO_fprintf(stream, "%s      <gml:LinearRing>\n", tab);
-
-            msIO_fprintf(stream, "%s        <gml:posList srsDimension=\"2\">", tab);
-            for(j=0; j<shape->line[k].numpoints; j++)
-              msIO_fprintf(stream, "%f %f ", shape->line[k].point[j].x, shape->line[k].point[j].y);
-            msIO_fprintf(stream, "</gml:posList>\n");
-
-            msIO_fprintf(stream, "%s      </gml:LinearRing>\n", tab);
-            msIO_fprintf(stream, "%s    </gml:interior>\n", tab);
-          }
+          msIO_fprintf(stream, "%s        <gml:posList srsDimension=\"2\">", tab);
+          for(j=0; j<shape->line[i].numpoints; j++)
+            msIO_fprintf(stream, "%f %f ", shape->line[i].point[j].x, shape->line[i].point[j].y);
+          msIO_fprintf(stream, "</gml:posList>\n");
+          msIO_fprintf(stream, "%s      </gml:LineString>\n", tab);
         }
+        msIO_fprintf(stream, "%s    </gml:curveMembers>\n", tab);
 
-        msIO_fprintf(stream, "%s  </gml:Polygon>\n", tab);
-        free(innerlist);
+        msIO_fprintf(stream, "%s  </gml:MultiCurve>\n", tab);
 
-        gmlEndGeometryContainer(stream, geometry_simple_name, namespace, tab);
+        gmlEndGeometryContainer(stream, geometry_aggregate_name, namespace, tab);
+      } else {
+        msIO_fprintf(stream, "<!-- Warning: Cannot write geometry- no line/multiline geometry defined. -->\n");
       }
-      free(outerlist);
-    } else if(geometry_aggregate_index != -1 || (geometryList->numgeometries == 0)) { /* write a MultiSurface */
-      gmlStartGeometryContainer(stream, geometry_aggregate_name, namespace, tab);
 
-      /* MultiSurface */
-      if(srsname_encoded)
-        msIO_fprintf(stream, "%s  <gml:MultiSurface srsName=\"%s\">\n", tab, srsname_encoded);
-      else
-        msIO_fprintf(stream, "%s  <gml:MultiSurface>\n", tab);
+      break;
+    case(MS_SHAPE_POLYGON): /* this gets nasty, since our shapes are so flexible */
+      geometry_simple_index = msGMLGeometryLookup(geometryList, "polygon");
+      geometry_aggregate_index = msGMLGeometryLookup(geometryList, "multipolygon");
+      if(geometry_simple_index >= 0) geometry_simple_name = geometryList->geometries[geometry_simple_index].name;
+      if(geometry_aggregate_index >= 0) geometry_aggregate_name = geometryList->geometries[geometry_aggregate_index].name;
+
+      /* get a list of outter rings for this polygon */
+      outerlist = msGetOuterList(shape);
+
+      numouters = 0;
+      for(i=0; i<shape->numlines; i++)
+        if(outerlist[i] == MS_TRUE) numouters++;
 
-      msIO_fprintf(stream, "%s    <gml:surfaceMembers>\n", tab);
-      for(i=0; i<shape->numlines; i++) { /* step through the outer rings */
-        if(outerlist[i] == MS_TRUE) {
+      if((geometry_simple_index != -1 && numouters == 1) ||
+          (geometry_simple_index != -1 && geometry_aggregate_index == -1) ||
+          (geometryList->numgeometries == 0 && shape->numlines == 1)) { /* write a Polygon(s) */
+        for(i=0; i<shape->numlines; i++) {
+          if(outerlist[i] == MS_FALSE) break; /* skip non-outer rings, each outer ring is a new polygon */
 
           /* get a list of inner rings for this polygon */
-          innerlist = msGetInnerList(shape, i, outerlist);            
+          innerlist = msGetInnerList(shape, i, outerlist);
 
-          msIO_fprintf(stream, "%s      <gml:Polygon>\n", tab);
+          gmlStartGeometryContainer(stream, geometry_simple_name, namespace, tab);
 
-          msIO_fprintf(stream, "%s        <gml:exterior>\n", tab);
-          msIO_fprintf(stream, "%s          <gml:LinearRing>\n", tab);
+          /* Polygon (should be Surface?) */
+          if(srsname_encoded)
+            msIO_fprintf(stream, "%s  <gml:Polygon srsName=\"%s\">\n", tab, srsname_encoded);
+          else
+            msIO_fprintf(stream, "%s  <gml:Polygon>\n", tab);
 
-          msIO_fprintf(stream, "%s            <gml:posList srsDimension=\"2\">", tab);
+          msIO_fprintf(stream, "%s    <gml:exterior>\n", tab);
+          msIO_fprintf(stream, "%s      <gml:LinearRing>\n", tab);
+
+          msIO_fprintf(stream, "%s        <gml:posList srsDimension=\"2\">", tab);
           for(j=0; j<shape->line[i].numpoints; j++)
             msIO_fprintf(stream, "%f %f ", shape->line[i].point[j].x, shape->line[i].point[j].y);
           msIO_fprintf(stream, "</gml:posList>\n");
 
-          msIO_fprintf(stream, "%s          </gml:LinearRing>\n", tab);
-          msIO_fprintf(stream, "%s        </gml:exterior>\n", tab);
+          msIO_fprintf(stream, "%s      </gml:LinearRing>\n", tab);
+          msIO_fprintf(stream, "%s    </gml:exterior>\n", tab);
 
           for(k=0; k<shape->numlines; k++) { /* now step through all the inner rings */
             if(innerlist[k] == MS_TRUE) {
-              msIO_fprintf(stream, "%s        <gml:interior>\n", tab);
-              msIO_fprintf(stream, "%s          <gml:LinearRing>\n", tab);
+              msIO_fprintf(stream, "%s    <gml:interior>\n", tab);
+              msIO_fprintf(stream, "%s      <gml:LinearRing>\n", tab);
 
-              msIO_fprintf(stream, "%s            <gml:posList srsDimension=\"2\">", tab);
+              msIO_fprintf(stream, "%s        <gml:posList srsDimension=\"2\">", tab);
               for(j=0; j<shape->line[k].numpoints; j++)
                 msIO_fprintf(stream, "%f %f ", shape->line[k].point[j].x, shape->line[k].point[j].y);
               msIO_fprintf(stream, "</gml:posList>\n");
 
-              msIO_fprintf(stream, "%s          </gml:LinearRing>\n", tab);
-              msIO_fprintf(stream, "%s        </gml:interior>\n", tab);
+              msIO_fprintf(stream, "%s      </gml:LinearRing>\n", tab);
+              msIO_fprintf(stream, "%s    </gml:interior>\n", tab);
             }
           }
 
-          msIO_fprintf(stream, "%s      </gml:Polygon>\n", tab);           
-
+          msIO_fprintf(stream, "%s  </gml:Polygon>\n", tab);
           free(innerlist);
+
+          gmlEndGeometryContainer(stream, geometry_simple_name, namespace, tab);
         }
-      }
-      msIO_fprintf(stream, "%s    </gml:surfaceMembers>\n", tab);
-      msIO_fprintf(stream, "%s  </gml:MultiSurface>\n", tab);
+        free(outerlist);
+      } else if(geometry_aggregate_index != -1 || (geometryList->numgeometries == 0)) { /* write a MultiSurface */
+        gmlStartGeometryContainer(stream, geometry_aggregate_name, namespace, tab);
 
-      free(outerlist);
+        /* MultiSurface */
+        if(srsname_encoded)
+          msIO_fprintf(stream, "%s  <gml:MultiSurface srsName=\"%s\">\n", tab, srsname_encoded);
+        else
+          msIO_fprintf(stream, "%s  <gml:MultiSurface>\n", tab);
 
-      gmlEndGeometryContainer(stream, geometry_aggregate_name, namespace, tab);      
-    } else {
-      msIO_fprintf(stream, "<!-- Warning: Cannot write geometry- no polygon/multipolygon geometry defined. -->\n");
-    }
+        msIO_fprintf(stream, "%s    <gml:surfaceMembers>\n", tab);
+        for(i=0; i<shape->numlines; i++) { /* step through the outer rings */
+          if(outerlist[i] == MS_TRUE) {
+
+            /* get a list of inner rings for this polygon */
+            innerlist = msGetInnerList(shape, i, outerlist);
 
-    break;
-  default:
-    break;
+            msIO_fprintf(stream, "%s      <gml:Polygon>\n", tab);
+
+            msIO_fprintf(stream, "%s        <gml:exterior>\n", tab);
+            msIO_fprintf(stream, "%s          <gml:LinearRing>\n", tab);
+
+            msIO_fprintf(stream, "%s            <gml:posList srsDimension=\"2\">", tab);
+            for(j=0; j<shape->line[i].numpoints; j++)
+              msIO_fprintf(stream, "%f %f ", shape->line[i].point[j].x, shape->line[i].point[j].y);
+            msIO_fprintf(stream, "</gml:posList>\n");
+
+            msIO_fprintf(stream, "%s          </gml:LinearRing>\n", tab);
+            msIO_fprintf(stream, "%s        </gml:exterior>\n", tab);
+
+            for(k=0; k<shape->numlines; k++) { /* now step through all the inner rings */
+              if(innerlist[k] == MS_TRUE) {
+                msIO_fprintf(stream, "%s        <gml:interior>\n", tab);
+                msIO_fprintf(stream, "%s          <gml:LinearRing>\n", tab);
+
+                msIO_fprintf(stream, "%s            <gml:posList srsDimension=\"2\">", tab);
+                for(j=0; j<shape->line[k].numpoints; j++)
+                  msIO_fprintf(stream, "%f %f ", shape->line[k].point[j].x, shape->line[k].point[j].y);
+                msIO_fprintf(stream, "</gml:posList>\n");
+
+                msIO_fprintf(stream, "%s          </gml:LinearRing>\n", tab);
+                msIO_fprintf(stream, "%s        </gml:interior>\n", tab);
+              }
+            }
+
+            msIO_fprintf(stream, "%s      </gml:Polygon>\n", tab);
+
+            free(innerlist);
+          }
+        }
+        msIO_fprintf(stream, "%s    </gml:surfaceMembers>\n", tab);
+        msIO_fprintf(stream, "%s  </gml:MultiSurface>\n", tab);
+
+        free(outerlist);
+
+        gmlEndGeometryContainer(stream, geometry_aggregate_name, namespace, tab);
+      } else {
+        msIO_fprintf(stream, "<!-- Warning: Cannot write geometry- no polygon/multipolygon geometry defined. -->\n");
+      }
+
+      break;
+    default:
+      break;
   }
 
   /* clean-up */
@@ -647,40 +647,40 @@ static int gmlWriteGeometry_GML3(FILE *stream, gmlGeometryListObj *geometryList,
 static int gmlWriteBounds(FILE *stream, int format, rectObj *rect, const char *srsname, char *tab)
 {
   switch(format) {
-  case(OWS_GML2):
-    return gmlWriteBounds_GML2(stream, rect, srsname, tab);
-    break;
-  case(OWS_GML3):
-    return gmlWriteBounds_GML3(stream, rect, srsname, tab);
-    break;
-  default:
-    msSetError(MS_IOERR, "Unsupported GML format.", "gmlWriteBounds()");
-  } 
-
- return(MS_FAILURE);
+    case(OWS_GML2):
+      return gmlWriteBounds_GML2(stream, rect, srsname, tab);
+      break;
+    case(OWS_GML3):
+      return gmlWriteBounds_GML3(stream, rect, srsname, tab);
+      break;
+    default:
+      msSetError(MS_IOERR, "Unsupported GML format.", "gmlWriteBounds()");
+  }
+
+  return(MS_FAILURE);
 }
 
 static int gmlWriteGeometry(FILE *stream, gmlGeometryListObj *geometryList, int format, shapeObj *shape, const char *srsname, char *namespace, char *tab)
 {
   switch(format) {
-  case(OWS_GML2):
-    return gmlWriteGeometry_GML2(stream, geometryList, shape, srsname, namespace, tab);
-    break;
-  case(OWS_GML3):
-    return gmlWriteGeometry_GML3(stream, geometryList, shape, srsname, namespace, tab);
-    break;
-  default:
-    msSetError(MS_IOERR, "Unsupported GML format.", "gmlWriteGeometry()");
-  } 
-
- return(MS_FAILURE);
+    case(OWS_GML2):
+      return gmlWriteGeometry_GML2(stream, geometryList, shape, srsname, namespace, tab);
+      break;
+    case(OWS_GML3):
+      return gmlWriteGeometry_GML3(stream, geometryList, shape, srsname, namespace, tab);
+      break;
+    default:
+      msSetError(MS_IOERR, "Unsupported GML format.", "gmlWriteGeometry()");
+  }
+
+  return(MS_FAILURE);
 }
 
 /*
 ** GML specific metadata handling functions.
-*/ 
+*/
 
-int msItemInGroups(char *name, gmlGroupListObj *groupList) 
+int msItemInGroups(char *name, gmlGroupListObj *groupList)
 {
   int i, j;
   gmlGroupObj *group;
@@ -703,7 +703,7 @@ static int msGMLGeometryLookup(gmlGeometryListObj *geometryList, char *type)
 
   if(!geometryList || !type) return -1; /* nothing to look for */
 
-  for(i=0; i<geometryList->numgeometries; i++)    
+  for(i=0; i<geometryList->numgeometries; i++)
     if(geometryList->geometries[i].type && (strcasecmp(geometryList->geometries[i].type, type) == 0))
       return i;
 
@@ -735,12 +735,11 @@ gmlGeometryListObj *msGMLGetGeometries(layerObj *layer, const char *metadata_nam
     /* allocation an array of gmlGeometryObj's */
     geometryList->numgeometries = numnames;
     geometryList->geometries = (gmlGeometryObj *) malloc(sizeof(gmlGeometryObj)*geometryList->numgeometries);
-    if (geometryList->geometries ==  NULL)
-    {
-        msSetError(MS_MEMERR, "Out of memory allocating %u bytes.\n", "msGMLGetGeometries()", 
-                   sizeof(gmlGeometryObj)*geometryList->numgeometries);
-        free(geometryList);
-        return NULL;
+    if (geometryList->geometries ==  NULL) {
+      msSetError(MS_MEMERR, "Out of memory allocating %u bytes.\n", "msGMLGetGeometries()",
+                 sizeof(gmlGeometryObj)*geometryList->numgeometries);
+      free(geometryList);
+      return NULL;
     }
 
     for(i=0; i<geometryList->numgeometries; i++) {
@@ -749,7 +748,7 @@ gmlGeometryListObj *msGMLGetGeometries(layerObj *layer, const char *metadata_nam
       geometry->name = msStrdup(names[i]); /* initialize a few things */
       geometry->type = NULL;
       geometry->occurmin = 0;
-      geometry->occurmax = 1;      
+      geometry->occurmax = 1;
 
       snprintf(tag, 64, "%s_type", names[i]);
       if((value =  msOWSLookupMetadata(&(layer->metadata), metadata_namespaces, tag)) != NULL)
@@ -766,7 +765,7 @@ gmlGeometryListObj *msGMLGetGeometries(layerObj *layer, const char *metadata_nam
           if(strcasecmp(occur[1], "UNBOUNDED") == 0)
             geometry->occurmax = OWS_GML_OCCUR_UNBOUNDED;
           else
-           geometry->occurmax = atof(occur[1]);
+            geometry->occurmax = atof(occur[1]);
         }
       }
     }
@@ -795,7 +794,7 @@ void msGMLFreeGeometries(gmlGeometryListObj *geometryList)
 static void msGMLWriteItem(FILE *stream, gmlItemObj *item, char *value, const char *namespace, const char *tab)
 {
   char *encoded_value, *tag_name;
-  int add_namespace = MS_TRUE;  
+  int add_namespace = MS_TRUE;
 
   if(!stream || !item) return;
   if(!item->visible) return;
@@ -805,20 +804,20 @@ static void msGMLWriteItem(FILE *stream, gmlItemObj *item, char *value, const ch
   if(item->encode == MS_TRUE)
     encoded_value = msEncodeHTMLEntities(value);
   else
-    encoded_value = msStrdup(value);  
-  
-  if(!item->template) { /* build the tag from pieces */  
+    encoded_value = msStrdup(value);
+
+  if(!item->template) { /* build the tag from pieces */
     if(item->alias) {
       tag_name = item->alias;
       if(strchr(item->alias, ':') != NULL) add_namespace = MS_FALSE;
     } else {
       tag_name = item->name;
       if(strchr(item->name, ':') != NULL) add_namespace = MS_FALSE;
-    }    
-  
+    }
+
     if(add_namespace == MS_TRUE && msIsXMLTagValid(tag_name) == MS_FALSE)
       msIO_fprintf(stream, "<!-- WARNING: The value '%s' is not valid in a XML tag context. -->\n", tag_name);
-  
+
     if(add_namespace == MS_TRUE)
       msIO_fprintf(stream, "%s<%s:%s>%s</%s:%s>\n", tab, namespace, tag_name, encoded_value, namespace, tag_name);
     else
@@ -851,10 +850,10 @@ gmlNamespaceListObj *msGMLGetNamespaces(webObj *web, const char *metadata_namesp
   gmlNamespaceObj *namespace=NULL;
 
   /* allocate the collection */
-  namespaceList = (gmlNamespaceListObj *) malloc(sizeof(gmlNamespaceListObj)); 
+  namespaceList = (gmlNamespaceListObj *) malloc(sizeof(gmlNamespaceListObj));
   MS_CHECK_ALLOC(namespaceList, sizeof(gmlNamespaceListObj), NULL) ;
   namespaceList->namespaces = NULL;
-  namespaceList->numnamespaces = 0; 
+  namespaceList->numnamespaces = 0;
 
   /* list of namespaces (TODO: make this automatic by parsing metadata) */
   if((value = msOWSLookupMetadata(&(web->metadata), metadata_namespaces, "external_namespace_prefixes")) != NULL) {
@@ -863,28 +862,27 @@ gmlNamespaceListObj *msGMLGetNamespaces(webObj *web, const char *metadata_namesp
     /* allocation an array of gmlNamespaceObj's */
     namespaceList->numnamespaces = numprefixes;
     namespaceList->namespaces = (gmlNamespaceObj *) malloc(sizeof(gmlNamespaceObj)*namespaceList->numnamespaces);
-    if (namespaceList->namespaces == NULL)
-    {
-        msSetError(MS_MEMERR, "Out of memory allocating %u bytes.\n", "msGMLGetNamespaces()",
-                   sizeof(gmlNamespaceObj)*namespaceList->numnamespaces);
-        free(namespaceList);
-        return NULL;      
+    if (namespaceList->namespaces == NULL) {
+      msSetError(MS_MEMERR, "Out of memory allocating %u bytes.\n", "msGMLGetNamespaces()",
+                 sizeof(gmlNamespaceObj)*namespaceList->numnamespaces);
+      free(namespaceList);
+      return NULL;
     }
 
     for(i=0; i<namespaceList->numnamespaces; i++) {
       namespace = &(namespaceList->namespaces[i]);
 
-      namespace->prefix = msStrdup(prefixes[i]); /* initialize a few things */      
+      namespace->prefix = msStrdup(prefixes[i]); /* initialize a few things */
       namespace->uri = NULL;
       namespace->schemalocation = NULL;
 
       snprintf(tag, 64, "%s_uri", namespace->prefix);
-      if((value = msOWSLookupMetadata(&(web->metadata), metadata_namespaces, tag)) != NULL) 
-      namespace->uri = msStrdup(value);
+      if((value = msOWSLookupMetadata(&(web->metadata), metadata_namespaces, tag)) != NULL)
+        namespace->uri = msStrdup(value);
 
       snprintf(tag, 64, "%s_schema_location", namespace->prefix);
-      if((value = msOWSLookupMetadata(&(web->metadata), metadata_namespaces, tag)) != NULL) 
-      namespace->schemalocation = msStrdup(value);
+      if((value = msOWSLookupMetadata(&(web->metadata), metadata_namespaces, tag)) != NULL)
+        namespace->schemalocation = msStrdup(value);
     }
 
     msFreeCharArray(prefixes, numprefixes);
@@ -921,7 +919,7 @@ gmlConstantListObj *msGMLGetConstants(layerObj *layer, const char *metadata_name
   gmlConstantObj *constant=NULL;
 
   /* allocate the collection */
-  constantList = (gmlConstantListObj *) malloc(sizeof(gmlConstantListObj)); 
+  constantList = (gmlConstantListObj *) malloc(sizeof(gmlConstantListObj));
   MS_CHECK_ALLOC(constantList, sizeof(gmlConstantListObj), NULL);
   constantList->constants = NULL;
   constantList->numconstants = 0;
@@ -933,34 +931,33 @@ gmlConstantListObj *msGMLGetConstants(layerObj *layer, const char *metadata_name
     /* allocation an array of gmlConstantObj's */
     constantList->numconstants = numnames;
     constantList->constants = (gmlConstantObj *) malloc(sizeof(gmlConstantObj)*constantList->numconstants);
-    if (constantList->constants == NULL)
-    {
-        msSetError(MS_MEMERR, "Out of memory allocating %u bytes.\n", "msGMLGetConstants()",
-                   sizeof(gmlConstantObj)*constantList->numconstants);
-        free(constantList);
-        return NULL;      
+    if (constantList->constants == NULL) {
+      msSetError(MS_MEMERR, "Out of memory allocating %u bytes.\n", "msGMLGetConstants()",
+                 sizeof(gmlConstantObj)*constantList->numconstants);
+      free(constantList);
+      return NULL;
     }
 
 
     for(i=0; i<constantList->numconstants; i++) {
       constant = &(constantList->constants[i]);
 
-      constant->name = msStrdup(names[i]); /* initialize a few things */      
+      constant->name = msStrdup(names[i]); /* initialize a few things */
       constant->value = NULL;
       constant->type = NULL;
 
       snprintf(tag, 64, "%s_value", constant->name);
-      if((value = msOWSLookupMetadata(&(layer->metadata), metadata_namespaces, tag)) != NULL) 
-      constant->value = msStrdup(value);
+      if((value = msOWSLookupMetadata(&(layer->metadata), metadata_namespaces, tag)) != NULL)
+        constant->value = msStrdup(value);
 
       snprintf(tag, 64, "%s_type", constant->name);
-      if((value = msOWSLookupMetadata(&(layer->metadata), metadata_namespaces, tag)) != NULL) 
-      constant->type = msStrdup(value);
+      if((value = msOWSLookupMetadata(&(layer->metadata), metadata_namespaces, tag)) != NULL)
+        constant->type = msStrdup(value);
     }
 
     msFreeCharArray(names, numnames);
-  } 
-  
+  }
+
   return constantList;
 }
 
@@ -981,17 +978,17 @@ void msGMLFreeConstants(gmlConstantListObj *constantList)
 
 static void msGMLWriteConstant(FILE *stream, gmlConstantObj *constant, const char *namespace, const char *tab)
 {
-  int add_namespace = MS_TRUE;  
+  int add_namespace = MS_TRUE;
 
   if(!stream || !constant) return;
   if(!constant->value) return;
 
   if(!namespace) add_namespace = MS_FALSE;
   if(strchr(constant->name, ':') != NULL) add_namespace = MS_FALSE;
-  
+
   if(add_namespace == MS_TRUE && msIsXMLTagValid(constant->name) == MS_FALSE)
     msIO_fprintf(stream, "<!-- WARNING: The value '%s' is not valid in a XML tag context. -->\n", constant->name);
-  
+
   if(add_namespace == MS_TRUE)
     msIO_fprintf(stream, "%s<%s:%s>%s</%s:%s>\n", tab, namespace, constant->name, constant->value, namespace, constant->name);
   else
@@ -1013,7 +1010,7 @@ gmlGroupListObj *msGMLGetGroups(layerObj *layer, const char *metadata_namespaces
   gmlGroupObj *group=NULL;
 
   /* allocate the collection */
-  groupList = (gmlGroupListObj *) malloc(sizeof(gmlGroupListObj)); 
+  groupList = (gmlGroupListObj *) malloc(sizeof(gmlGroupListObj));
   MS_CHECK_ALLOC(groupList, sizeof(gmlGroupListObj), NULL) ;
   groupList->groups = NULL;
   groupList->numgroups = 0;
@@ -1025,12 +1022,11 @@ gmlGroupListObj *msGMLGetGroups(layerObj *layer, const char *metadata_namespaces
     /* allocation an array of gmlGroupObj's */
     groupList->numgroups = numnames;
     groupList->groups = (gmlGroupObj *) malloc(sizeof(gmlGroupObj)*groupList->numgroups);
-    if (groupList->groups == NULL)
-    {
-        msSetError(MS_MEMERR, "Out of memory allocating %u bytes.\n", "msGMLGetGroups()",
-                   sizeof(gmlGroupObj)*groupList->numgroups);
-        free(groupList);
-        return NULL;      
+    if (groupList->groups == NULL) {
+      msSetError(MS_MEMERR, "Out of memory allocating %u bytes.\n", "msGMLGetGroups()",
+                 sizeof(gmlGroupObj)*groupList->numgroups);
+      free(groupList);
+      return NULL;
     }
 
     for(i=0; i<groupList->numgroups; i++) {
@@ -1046,13 +1042,13 @@ gmlGroupListObj *msGMLGetGroups(layerObj *layer, const char *metadata_namespaces
         group->items = msStringSplit(value, ',', &group->numitems);
 
       snprintf(tag, 64, "%s_type", group->name);
-      if((value = msOWSLookupMetadata(&(layer->metadata), metadata_namespaces, tag)) != NULL) 
-      group->type = msStrdup(value);
+      if((value = msOWSLookupMetadata(&(layer->metadata), metadata_namespaces, tag)) != NULL)
+        group->type = msStrdup(value);
     }
 
     msFreeCharArray(names, numnames);
-  } 
-  
+  }
+
   return groupList;
 }
 
@@ -1086,7 +1082,7 @@ static void msGMLWriteGroup(FILE *stream, gmlGroupObj *group, shapeObj *shape, g
   itemtab = (char *) msSmallMalloc(sizeof(char)*strlen(tab)+3);
 
   sprintf(itemtab, "%s  ", tab);
-     
+
   if(!namespace || strchr(group->name, ':') != NULL) add_namespace = MS_FALSE;
 
   /* start the group */
@@ -1094,12 +1090,12 @@ static void msGMLWriteGroup(FILE *stream, gmlGroupObj *group, shapeObj *shape, g
     msIO_fprintf(stream, "%s<%s:%s>\n", tab, namespace, group->name);
   else
     msIO_fprintf(stream, "%s<%s>\n", tab, group->name);
-  
-  /* now the items/constants in the group */  
-  for(i=0; i<group->numitems; i++) {    
+
+  /* now the items/constants in the group */
+  for(i=0; i<group->numitems; i++) {
     for(j=0; j<constantList->numconstants; j++) {
       constant = &(constantList->constants[j]);
-      if(strcasecmp(constant->name, group->items[i]) == 0) { 
+      if(strcasecmp(constant->name, group->items[i]) == 0) {
         msGMLWriteConstant(stream, constant, namespace, itemtab);
         break;
       }
@@ -1107,14 +1103,14 @@ static void msGMLWriteGroup(FILE *stream, gmlGroupObj *group, shapeObj *shape, g
     if(j != constantList->numconstants) continue; /* found this one */
     for(j=0; j<itemList->numitems; j++) {
       item = &(itemList->items[j]);
-      if(strcasecmp(item->name, group->items[i]) == 0) { 
+      if(strcasecmp(item->name, group->items[i]) == 0) {
         /* the number of items matches the number of values exactly */
         msGMLWriteItem(stream, item, shape->values[j], namespace, itemtab);
         break;
       }
     }
   }
-  
+
   /* end the group */
   if(add_namespace == MS_TRUE)
     msIO_fprintf(stream, "%s</%s:%s>\n", tab, namespace, group->name);
@@ -1183,11 +1179,11 @@ int msGMLWriteQuery(mapObj *map, char *filename, const char *namespaces)
 #ifdef USE_PROJ
       /* Determine output SRS, if map has none, then try using layer's native SRS */
       if ((pszOutputSRS = pszMapSRS) == NULL) {
-          pszOutputSRS = msOWSGetEPSGProj(&(lp->projection), NULL, namespaces, MS_TRUE);
-          if (pszOutputSRS == NULL) {
-              msSetError(MS_WMSERR, "No valid EPSG code in map or layer projection for GML output", "msGMLWriteQuery()");
-              continue;  /* No EPSG code, cannot output this layer */
-           }
+        pszOutputSRS = msOWSGetEPSGProj(&(lp->projection), NULL, namespaces, MS_TRUE);
+        if (pszOutputSRS == NULL) {
+          msSetError(MS_WMSERR, "No valid EPSG code in map or layer projection for GML output", "msGMLWriteQuery()");
+          continue;  /* No EPSG code, cannot output this layer */
+        }
       }
 #endif
 
@@ -1204,14 +1200,13 @@ int msGMLWriteQuery(mapObj *map, char *filename, const char *namespaces)
       }
 
       /* populate item and group metadata structures */
-      itemList = msGMLGetItems(lp, namespaces); 
+      itemList = msGMLGetItems(lp, namespaces);
       constantList = msGMLGetConstants(lp, namespaces);
       groupList = msGMLGetGroups(lp, namespaces);
       geometryList = msGMLGetGeometries(lp, namespaces);
-      if (itemList == NULL || constantList == NULL || groupList == NULL || geometryList == NULL)
-      {
-          msSetError(MS_MISCERR, "Unable to populate item and group metadata structures", "msGMLWriteQuery()");
-          return MS_FAILURE;
+      if (itemList == NULL || constantList == NULL || groupList == NULL || geometryList == NULL) {
+        msSetError(MS_MISCERR, "Unable to populate item and group metadata structures", "msGMLWriteQuery()");
+        return MS_FAILURE;
       }
 
       for(j=0; j<lp->resultcache->numresults; j++) {
@@ -1220,8 +1215,13 @@ int msGMLWriteQuery(mapObj *map, char *filename, const char *namespaces)
 
 #ifdef USE_PROJ
         /* project the shape into the map projection (if necessary), note that this projects the bounds as well */
-        if(pszOutputSRS == pszMapSRS && msProjectionsDiffer(&(lp->projection), &(map->projection)))
-          msProjectShape(&lp->projection, &map->projection, &shape);
+        if(pszOutputSRS == pszMapSRS && msProjectionsDiffer(&(lp->projection), &(map->projection))) {
+          status = msProjectShape(&lp->projection, &map->projection, &shape);
+          if(status != MS_SUCCESS) {
+            msIO_fprintf(stream, "<!-- Warning: Failed to reproject shape: %s -->\n",msGetErrorString(","));
+            continue;
+          }
+        }
 #endif
 
         /* start this feature */
@@ -1233,12 +1233,12 @@ int msGMLWriteQuery(mapObj *map, char *filename, const char *namespaces)
 
         /* Write the feature geometry and bounding box unless 'none' was requested. */
         /* Default to bbox only if nothing specified and output full geometry only if explicitly requested */
-        if(!(geometryList && geometryList->numgeometries == 1 && strcasecmp(geometryList->geometries[0].name, "none") == 0)) { 
+        if(!(geometryList && geometryList->numgeometries == 1 && strcasecmp(geometryList->geometries[0].name, "none") == 0)) {
 
 #ifdef USE_PROJ
           gmlWriteBounds(stream, OWS_GML2, &(shape.bounds), pszOutputSRS, "\t\t\t");
           if (geometryList && geometryList->numgeometries > 0 )
-              gmlWriteGeometry(stream, geometryList, OWS_GML2, &(shape), pszOutputSRS, NULL, "\t\t\t");
+            gmlWriteGeometry(stream, geometryList, OWS_GML2, &(shape), pszOutputSRS, NULL, "\t\t\t");
 #else
           gmlWriteBounds(stream, OWS_GML2, &(shape.bounds), NULL, "\t\t\t"); /* no projection information */
           if (geometryList && geometryList->numgeometries > 0 )
@@ -1249,15 +1249,15 @@ int msGMLWriteQuery(mapObj *map, char *filename, const char *namespaces)
 
         /* write any item/values */
         for(k=0; k<itemList->numitems; k++) {
-          item = &(itemList->items[k]);  
-          if(msItemInGroups(item->name, groupList) == MS_FALSE) 
+          item = &(itemList->items[k]);
+          if(msItemInGroups(item->name, groupList) == MS_FALSE)
             msGMLWriteItem(stream, item, shape.values[k], NULL, "\t\t\t");
         }
 
         /* write any constants */
         for(k=0; k<constantList->numconstants; k++) {
-          constant = &(constantList->constants[k]);  
-          if(msItemInGroups(constant->name, groupList) == MS_FALSE) 
+          constant = &(constantList->constants[k]);
+          if(msItemInGroups(constant->name, groupList) == MS_FALSE)
             msGMLWriteConstant(stream, constant, NULL, "\t\t\t");
         }
 
@@ -1300,8 +1300,8 @@ int msGMLWriteQuery(mapObj *map, char *filename, const char *namespaces)
   return(MS_SUCCESS);
 
 #else /* Stub for mapscript */
-    msSetError(MS_MISCERR, "WMS server support not enabled", "msGMLWriteQuery()");
-    return MS_FAILURE;
+  msSetError(MS_MISCERR, "WMS server support not enabled", "msGMLWriteQuery()");
+  return MS_FAILURE;
 #endif
 }
 
@@ -1314,38 +1314,34 @@ int msGMLWriteQuery(mapObj *map, char *filename, const char *namespaces)
 /************************************************************************/
 void msAxisSwapShape(shapeObj *shape)
 {
-    double tmp;
-    int i,j;
-
-    if (shape)
-    {
-        for(i=0; i<shape->numlines; i++) 
-        {
-            for( j=0; j<shape->line[i].numpoints; j++ ) 
-            {
-                tmp = shape->line[i].point[j].x;
-                shape->line[i].point[j].x = shape->line[i].point[j].y;
-                shape->line[i].point[j].y = tmp;
-            }
-        }
-
-        /*swap bounds*/
-        tmp = shape->bounds.minx;
-        shape->bounds.minx = shape->bounds.miny;
-        shape->bounds.miny = tmp;
+  double tmp;
+  int i,j;
 
-        tmp = shape->bounds.maxx;
-        shape->bounds.maxx = shape->bounds.maxy;
-        shape->bounds.maxy = tmp;
+  if (shape) {
+    for(i=0; i<shape->numlines; i++) {
+      for( j=0; j<shape->line[i].numpoints; j++ ) {
+        tmp = shape->line[i].point[j].x;
+        shape->line[i].point[j].x = shape->line[i].point[j].y;
+        shape->line[i].point[j].y = tmp;
+      }
     }
+
+    /*swap bounds*/
+    tmp = shape->bounds.minx;
+    shape->bounds.minx = shape->bounds.miny;
+    shape->bounds.miny = tmp;
+
+    tmp = shape->bounds.maxx;
+    shape->bounds.maxx = shape->bounds.maxy;
+    shape->bounds.maxy = tmp;
+  }
 }
 /*
 ** msGMLWriteWFSQuery()
 **
 ** Similar to msGMLWriteQuery() but tuned for use with WFS 1.0.0
 */
-int msGMLWriteWFSQuery(mapObj *map, FILE *stream, int startindex, int maxfeatures, 
-                       char *default_namespace_prefix, int outputformat)
+int msGMLWriteWFSQuery(mapObj *map, FILE *stream, char *default_namespace_prefix, int outputformat)
 {
 #ifdef USE_WFS_SVR
   int status;
@@ -1354,7 +1350,6 @@ int msGMLWriteWFSQuery(mapObj *map, FILE *stream, int startindex, int maxfeature
   shapeObj shape;
   rectObj  resultBounds = {-1.0,-1.0,-1.0,-1.0};
   int features = 0;
-  int currentfeature =0;
 
   gmlGroupListObj *groupList=NULL;
   gmlItemListObj *itemList=NULL;
@@ -1372,38 +1367,34 @@ int msGMLWriteWFSQuery(mapObj *map, FILE *stream, int startindex, int maxfeature
   msInitShape(&shape);
 
   /*add a check to see if the map projection is set to be north-east*/
-  for( i = 0; i < map->projection.numargs; i++ )
-  {
-      if( strstr(map->projection.args[i],"epsgaxis=") != NULL )
-      {
-          axis = strstr(map->projection.args[i],"=") + 1;
-          break;
-      }
+  for( i = 0; i < map->projection.numargs; i++ ) {
+    if( strstr(map->projection.args[i],"epsgaxis=") != NULL ) {
+      axis = strstr(map->projection.args[i],"=") + 1;
+      break;
+    }
   }
 
   if (axis && strcasecmp(axis,"ne") == 0 )
     bSwapAxis = 1;
 
-  
+
   /* Need to start with BBOX of the whole resultset */
-  if (msGetQueryResultBounds(map, &resultBounds) > 0)
-  {
-      if (bSwapAxis)
-      {
-          tmp = resultBounds.minx;
-          resultBounds.minx =  resultBounds.miny;
-          resultBounds.miny = tmp;
-
-          tmp = resultBounds.maxx;
-          resultBounds.maxx =  resultBounds.maxy;
-          resultBounds.maxy = tmp;
+  if (msGetQueryResultBounds(map, &resultBounds) > 0) {
+    if (bSwapAxis) {
+      tmp = resultBounds.minx;
+      resultBounds.minx =  resultBounds.miny;
+      resultBounds.miny = tmp;
 
-      }
-      srsMap = msOWSGetEPSGProj(&(map->projection), NULL, "FGO", MS_TRUE);
-      if (!srsMap)
-        msOWSGetEPSGProj(&(map->projection), &(map->web.metadata), "FGO", MS_TRUE);
+      tmp = resultBounds.maxx;
+      resultBounds.maxx =  resultBounds.maxy;
+      resultBounds.maxy = tmp;
 
-      gmlWriteBounds(stream, outputformat, &resultBounds, srsMap, "      ");
+    }
+    srsMap = msOWSGetEPSGProj(&(map->projection), NULL, "FGO", MS_TRUE);
+    if (!srsMap)
+      msOWSGetEPSGProj(&(map->projection), &(map->web.metadata), "FGO", MS_TRUE);
+
+    gmlWriteBounds(stream, outputformat, &resultBounds, srsMap, "      ");
   }
   /* step through the layers looking for query results */
   for(i=0; i<map->numlayers; i++) {
@@ -1411,15 +1402,15 @@ int msGMLWriteWFSQuery(mapObj *map, FILE *stream, int startindex, int maxfeature
     lp = GET_LAYER(map, map->layerorder[i]);
 
     if(lp->resultcache && lp->resultcache->numresults > 0)  { /* found results */
-      char *layerName;      
+      char *layerName;
       const char *value;
       int featureIdIndex=-1; /* no feature id */
 
-      
+
       /* setup namespace, a layer can override the default */
       namespace_prefix = (char*) msOWSLookupMetadata(&(lp->metadata), "OFG", "namespace_prefix");
       if(!namespace_prefix) namespace_prefix = default_namespace_prefix;
-      
+
       value = msOWSLookupMetadata(&(lp->metadata), "OFG", "featureid");
       if(value) { /* find the featureid amongst the items for this layer */
         for(j=0; j<lp->numitems; j++) {
@@ -1439,10 +1430,9 @@ int msGMLWriteWFSQuery(mapObj *map, FILE *stream, int startindex, int maxfeature
       constantList = msGMLGetConstants(lp, "G");
       groupList = msGMLGetGroups(lp, "G");
       geometryList = msGMLGetGeometries(lp, "GFO");
-      if (itemList == NULL || constantList == NULL || groupList == NULL || geometryList == NULL)
-      {
-          msSetError(MS_MISCERR, "Unable to populate item and group metadata structures", "msGMLWriteWFSQuery()");
-          return MS_FAILURE;
+      if (itemList == NULL || constantList == NULL || groupList == NULL || geometryList == NULL) {
+        msSetError(MS_MISCERR, "Unable to populate item and group metadata structures", "msGMLWriteWFSQuery()");
+        return MS_FAILURE;
       }
 
 
@@ -1455,24 +1445,18 @@ int msGMLWriteWFSQuery(mapObj *map, FILE *stream, int startindex, int maxfeature
 
       for(j=0; j<lp->resultcache->numresults; j++) {
 
-        if (startindex > 0 && currentfeature < startindex)
-        {
-            currentfeature++;
-            continue;
-        }
-
         status = msLayerGetShape(lp, &shape, &(lp->resultcache->results[j]));
-        if(status != MS_SUCCESS) 
-            return(status);
+        if(status != MS_SUCCESS)
+          return(status);
 
 #ifdef USE_PROJ
         /* project the shape into the map projection (if necessary), note that this projects the bounds as well */
         if(msProjectionsDiffer(&(lp->projection), &(map->projection)))
           msProjectShape(&lp->projection, &map->projection, &shape);
 #endif
-        
-        /* 
-        ** start this feature 
+
+        /*
+        ** start this feature
         */
         msIO_fprintf(stream, "    <gml:featureMember>\n");
         if(msIsXMLTagValid(layerName) == MS_FALSE)
@@ -1484,7 +1468,7 @@ int msGMLWriteWFSQuery(mapObj *map, FILE *stream, int startindex, int maxfeature
             msIO_fprintf(stream, "      <%s gml:id=\"%s.%s\">\n", layerName, lp->name, shape.values[featureIdIndex]);
         } else
           msIO_fprintf(stream, "      <%s>\n", layerName);
-              
+
         if (bSwapAxis)
           msAxisSwapShape(&shape);
 
@@ -1496,7 +1480,7 @@ int msGMLWriteWFSQuery(mapObj *map, FILE *stream, int startindex, int maxfeature
             msOWSGetEPSGProj(&(map->projection), &(map->web.metadata), "FGO", MS_TRUE);
           if(srsMap) { /* use the map projection first*/
             gmlWriteBounds(stream, outputformat, &(shape.bounds), srsMap, "        ");
-            gmlWriteGeometry(stream, geometryList, outputformat, &(shape), srsMap, namespace_prefix, "        "); 
+            gmlWriteGeometry(stream, geometryList, outputformat, &(shape), srsMap, namespace_prefix, "        ");
           } else { /* then use the layer projection and/or metadata */
             gmlWriteBounds(stream, outputformat, &(shape.bounds), msOWSGetEPSGProj(&(lp->projection), &(lp->metadata), "FGO", MS_TRUE), "        ");
             gmlWriteGeometry(stream, geometryList, outputformat, &(shape), msOWSGetEPSGProj(&(lp->projection), &(lp->metadata), "FGO", MS_TRUE), namespace_prefix, "        ");
@@ -1509,15 +1493,15 @@ int msGMLWriteWFSQuery(mapObj *map, FILE *stream, int startindex, int maxfeature
 
         /* write any item/values */
         for(k=0; k<itemList->numitems; k++) {
-          item = &(itemList->items[k]);  
-          if(msItemInGroups(item->name, groupList) == MS_FALSE) 
+          item = &(itemList->items[k]);
+          if(msItemInGroups(item->name, groupList) == MS_FALSE)
             msGMLWriteItem(stream, item, shape.values[k], namespace_prefix, "        ");
         }
 
         /* write any constants */
         for(k=0; k<constantList->numconstants; k++) {
-          constant = &(constantList->constants[k]);  
-          if(msItemInGroups(constant->name, groupList) == MS_FALSE) 
+          constant = &(constantList->constants[k]);
+          if(msItemInGroups(constant->name, groupList) == MS_FALSE)
             msGMLWriteConstant(stream, constant, namespace_prefix, "        ");
         }
 
@@ -1532,11 +1516,9 @@ int msGMLWriteWFSQuery(mapObj *map, FILE *stream, int startindex, int maxfeature
         msFreeShape(&shape); /* init too */
 
         features++;
-        if (maxfeatures > 0 && features == maxfeatures)
-          break; 
-      }      
+      }
 
-      /* done with this layer, do a little clean-up */      
+      /* done with this layer, do a little clean-up */
       msFree(layerName);
 
       msGMLFreeGroups(groupList);
@@ -1547,9 +1529,6 @@ int msGMLWriteWFSQuery(mapObj *map, FILE *stream, int startindex, int maxfeature
       /* msLayerClose(lp); */
     }
 
-    if (maxfeatures > 0 && features == maxfeatures)
-      break;
-
   } /* next layer */
 
   return(MS_SUCCESS);
@@ -1580,8 +1559,9 @@ int msGMLWriteWFSQuery(mapObj *map, FILE *stream, int startindex, int maxfeature
  *
  */
 
-xmlNodePtr msGML3BoundedBy(xmlNsPtr psNs, double minx, double miny, double maxx, double maxy, const char *psEpsg) {
-  xmlNodePtr psNode = NULL, psSubNode = NULL, psSubSubNode = NULL;
+xmlNodePtr msGML3BoundedBy(xmlNsPtr psNs, double minx, double miny, double maxx, double maxy, const char *psEpsg)
+{
+  xmlNodePtr psNode = NULL, psSubNode = NULL;
   char *pszTmp = NULL;
   char *pszTmp2 = NULL;
   char *pszEpsg = NULL;
@@ -1609,15 +1589,15 @@ xmlNodePtr msGML3BoundedBy(xmlNsPtr psNs, double minx, double miny, double maxx,
   pszTmp = msStringConcatenate(pszTmp, " ");
   pszTmp2 = msDoubleToString(miny, MS_TRUE);
   pszTmp = msStringConcatenate(pszTmp, pszTmp2);
-  psSubSubNode = xmlNewChild(psSubNode, NULL, BAD_CAST "lowerCorner", BAD_CAST pszTmp);
+  xmlNewChild(psSubNode, NULL, BAD_CAST "lowerCorner", BAD_CAST pszTmp);
   free(pszTmp);
   free(pszTmp2);
 
   pszTmp = msDoubleToString(maxx, MS_TRUE);
   pszTmp = msStringConcatenate(pszTmp, " ");
-  pszTmp2 = msDoubleToString(maxy,MS_TRUE); 
+  pszTmp2 = msDoubleToString(maxy,MS_TRUE);
   pszTmp = msStringConcatenate(pszTmp, pszTmp2);
-  psSubSubNode = xmlNewChild(psSubNode, NULL, BAD_CAST "upperCorner", BAD_CAST pszTmp);
+  xmlNewChild(psSubNode, NULL, BAD_CAST "upperCorner", BAD_CAST pszTmp);
   free(pszTmp);
   free(pszTmp2);
   return psNode;
@@ -1639,8 +1619,9 @@ xmlNodePtr msGML3BoundedBy(xmlNsPtr psNs, double minx, double miny, double maxx,
  *
  */
 
-xmlNodePtr msGML3Point(xmlNsPtr psNs, const char *psSrsName, const char *id, double x, double y) {
-  xmlNodePtr psNode = NULL, psSubNode = NULL;
+xmlNodePtr msGML3Point(xmlNsPtr psNs, const char *psSrsName, const char *id, double x, double y)
+{
+  xmlNodePtr psNode = NULL;
   char *pszTmp = NULL;
   int dimension = 2;
   char *pszSrsName = NULL;
@@ -1672,7 +1653,7 @@ xmlNodePtr msGML3Point(xmlNsPtr psNs, const char *psSrsName, const char *id, dou
   pszTmp = msStringConcatenate(pszTmp, " ");
   pszTmp2 = msDoubleToString(y, MS_TRUE);
   pszTmp = msStringConcatenate(pszTmp, pszTmp2);
-  psSubNode = xmlNewChild(psNode, NULL, BAD_CAST "pos", BAD_CAST pszTmp);
+  xmlNewChild(psNode, NULL, BAD_CAST "pos", BAD_CAST pszTmp);
 
   free(pszTmp);
   free(pszTmp2);
@@ -1687,20 +1668,21 @@ xmlNodePtr msGML3Point(xmlNsPtr psNs, const char *psSrsName, const char *id, dou
  * @param xmlNsPtr psNs the gml namespace object
  * @param pszStart start time
  * @param pszEnd end time
- * 
+ *
  * @return psNode xmlNodePtr of XML construct
  *
  */
 
-xmlNodePtr msGML3TimePeriod(xmlNsPtr psNs, char *pszStart, char *pszEnd) {
-  xmlNodePtr psNode=NULL,psSubNode=NULL;
+xmlNodePtr msGML3TimePeriod(xmlNsPtr psNs, char *pszStart, char *pszEnd)
+{
+  xmlNodePtr psNode=NULL;
 
   psNode = xmlNewNode(psNs, BAD_CAST "TimePeriod");
-  psSubNode = xmlNewChild(psNode, NULL, BAD_CAST "beginPosition", BAD_CAST pszStart);
+  xmlNewChild(psNode, NULL, BAD_CAST "beginPosition", BAD_CAST pszStart);
   if (pszEnd)
-    psSubNode = xmlNewChild(psNode, NULL, BAD_CAST "endPosition", BAD_CAST pszEnd);
+    xmlNewChild(psNode, NULL, BAD_CAST "endPosition", BAD_CAST pszEnd);
   else {
-    psSubNode = xmlNewChild(psNode, NULL, BAD_CAST "endPosition", NULL);
+    xmlNewChild(psNode, NULL, BAD_CAST "endPosition", NULL);
     xmlNewProp(psNode, BAD_CAST "indeterminatePosition", BAD_CAST "now");
   }
   return psNode;
@@ -1718,11 +1700,12 @@ xmlNodePtr msGML3TimePeriod(xmlNsPtr psNs, char *pszStart, char *pszEnd) {
  *
  */
 
-xmlNodePtr msGML3TimeInstant(xmlNsPtr psNs, char *pszTime) {
-  xmlNodePtr psNode=NULL,psSubNode=NULL;
+xmlNodePtr msGML3TimeInstant(xmlNsPtr psNs, char *pszTime)
+{
+  xmlNodePtr psNode=NULL;
 
   psNode = xmlNewNode(psNs, BAD_CAST "TimeInstant");
-  psSubNode = xmlNewChild(psNode, NULL, BAD_CAST "timePosition", BAD_CAST pszTime);
+  xmlNewChild(psNode, NULL, BAD_CAST "timePosition", BAD_CAST pszTime);
   return psNode;
 }
 
@@ -1734,11 +1717,11 @@ xmlNodePtr msGML3TimeInstant(xmlNsPtr psNs, char *pszTime) {
 /*      WMS and WFS are not available.                                  */
 /************************************************************************/
 
-gmlItemListObj *msGMLGetItems(layerObj *layer, const char *metadata_namespaces) 
+gmlItemListObj *msGMLGetItems(layerObj *layer, const char *metadata_namespaces)
 {
   int i,j;
 
-  char **xmlitems=NULL; 
+  char **xmlitems=NULL;
   int numxmlitems=0;
 
   char **incitems=NULL;
@@ -1750,19 +1733,19 @@ gmlItemListObj *msGMLGetItems(layerObj *layer, const char *metadata_namespaces)
   const char *value=NULL;
   char tag[64];
 
-  gmlItemListObj *itemList=NULL; 
+  gmlItemListObj *itemList=NULL;
   gmlItemObj *item=NULL;
 
   /* get a list of items that should be included in output */
-  if((value = msOWSLookupMetadata(&(layer->metadata), metadata_namespaces, "include_items")) != NULL)  
+  if((value = msOWSLookupMetadata(&(layer->metadata), metadata_namespaces, "include_items")) != NULL)
     incitems = msStringSplit(value, ',', &numincitems);
 
   /* get a list of items that should be excluded in output */
-  if((value = msOWSLookupMetadata(&(layer->metadata), metadata_namespaces, "exclude_items")) != NULL)  
+  if((value = msOWSLookupMetadata(&(layer->metadata), metadata_namespaces, "exclude_items")) != NULL)
     excitems = msStringSplit(value, ',', &numexcitems);
 
   /* get a list of items that need don't get encoded */
-  if((value = msOWSLookupMetadata(&(layer->metadata), metadata_namespaces, "xml_items")) != NULL)  
+  if((value = msOWSLookupMetadata(&(layer->metadata), metadata_namespaces, "xml_items")) != NULL)
     xmlitems = msStringSplit(value, ',', &numxmlitems);
 
   /* allocate memory and iinitialize the item collection */
@@ -1770,7 +1753,7 @@ gmlItemListObj *msGMLGetItems(layerObj *layer, const char *metadata_namespaces)
   if(itemList == NULL) {
     msSetError(MS_MEMERR, "Error allocating a collection GML item structures.", "msGMLGetItems()");
     return NULL;
-  } 
+  }
 
   itemList->items = NULL;
   itemList->numitems = 0;
@@ -1780,7 +1763,7 @@ gmlItemListObj *msGMLGetItems(layerObj *layer, const char *metadata_namespaces)
   if(!itemList->items) {
     msSetError(MS_MEMERR, "Error allocating a collection GML item structures.", "msGMLGetItems()");
     return NULL;
-  } 
+  }
 
   for(i=0; i<layer->numitems; i++) {
     item = &(itemList->items[i]);
@@ -1817,24 +1800,24 @@ gmlItemListObj *msGMLGetItems(layerObj *layer, const char *metadata_namespaces)
     }
 
     snprintf(tag, sizeof(tag), "%s_alias", layer->items[i]);
-    if((value = msOWSLookupMetadata(&(layer->metadata), metadata_namespaces, tag)) != NULL) 
+    if((value = msOWSLookupMetadata(&(layer->metadata), metadata_namespaces, tag)) != NULL)
       item->alias = msStrdup(value);
 
     snprintf(tag, sizeof(tag), "%s_type", layer->items[i]);
-    if((value = msOWSLookupMetadata(&(layer->metadata), metadata_namespaces, tag)) != NULL) 
+    if((value = msOWSLookupMetadata(&(layer->metadata), metadata_namespaces, tag)) != NULL)
       item->type = msStrdup(value);
 
     snprintf(tag, sizeof(tag), "%s_template", layer->items[i]);
-    if((value = msOWSLookupMetadata(&(layer->metadata), metadata_namespaces, tag)) != NULL) 
+    if((value = msOWSLookupMetadata(&(layer->metadata), metadata_namespaces, tag)) != NULL)
       item->template = msStrdup(value);
 
     snprintf(tag, sizeof(tag), "%s_width", layer->items[i]);
-    if((value = msOWSLookupMetadata(&(layer->metadata), metadata_namespaces, tag)) != NULL) 
-        item->width = atoi(value);
-    
+    if((value = msOWSLookupMetadata(&(layer->metadata), metadata_namespaces, tag)) != NULL)
+      item->width = atoi(value);
+
     snprintf(tag, sizeof(tag), "%s_precision", layer->items[i]);
-    if((value = msOWSLookupMetadata(&(layer->metadata), metadata_namespaces, tag)) != NULL) 
-        item->precision = atoi(value);
+    if((value = msOWSLookupMetadata(&(layer->metadata), metadata_namespaces, tag)) != NULL)
+      item->precision = atoi(value);
   }
 
   msFreeCharArray(incitems, numincitems);
@@ -1858,7 +1841,7 @@ void msGMLFreeItems(gmlItemListObj *itemList)
   }
 
   if( itemList->items != NULL )
-      free(itemList->items);
+    free(itemList->items);
 
   free(itemList);
 }
diff --git a/mapgml.h b/mapgml.h
index b5b7bcc..03dbac2 100644
--- a/mapgml.h
+++ b/mapgml.h
@@ -2,7 +2,7 @@
  * $Id$
  *
  * Project:  MapServer
- * Purpose:  Headers for mapgml.c.  shapeObj to GML output via MapServer 
+ * Purpose:  Headers for mapgml.c.  shapeObj to GML output via MapServer
  *           queries.
  * Author:   Steve Lime and the MapServer team.
  *
@@ -16,7 +16,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
diff --git a/mapgraticule.c b/mapgraticule.c
index 1284a0b..60e114b 100644
--- a/mapgraticule.c
+++ b/mapgraticule.c
@@ -14,37 +14,35 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
+ *
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  ****************************************************************************/
 
 #include "mapserver.h"
 #include <assert.h>
 #include "mapproject.h"
 
-MS_CVSID("$Id$")
+
 
 /**********************************************************************************************************************
  *
  */
-typedef enum
-{
-   posBottom = 1,
-   posTop,
-   posLeft,
-   posRight
+typedef enum {
+  posBottom = 1,
+  posTop,
+  posLeft,
+  posRight
 } msGraticulePosition;
 
-typedef enum
-{
+typedef enum {
   lpDefault = 0,
   lpDDMMSS = 1,
   lpDDMM,
@@ -67,13 +65,13 @@ int msGraticuleLayerInitItemInfo(layerObj *layer);
 /**********************************************************************************************************************
  *
  */
-int msGraticuleLayerOpen(layerObj *layer) 
+int msGraticuleLayerOpen(layerObj *layer)
 {
   graticuleObj *pInfo = (graticuleObj *) layer->layerinfo;
-  
+
   if( pInfo == NULL )
     return MS_FAILURE;
-  
+
   pInfo->dincrementlatitude = 15.0;
   pInfo->dincrementlongitude = 15.0;
   pInfo->dwhichlatitude = -90.0;
@@ -81,31 +79,34 @@ int msGraticuleLayerOpen(layerObj *layer)
   pInfo->bvertical = 1;
 
   if( layer->numclasses == 0 )
-      msDebug( "GRID layer has no classes, nothing will be rendered.\n" );
+    msDebug( "GRID layer has no classes, nothing will be rendered.\n" );
 
-  if( layer->numclasses == 0 || layer->class[0]->label.size == -1 )
-    pInfo->blabelaxes = 0;
-  else
+  if( layer->numclasses > 0 && layer->class[0]->numlabels > 0 )
     pInfo->blabelaxes = 1;
-  
+  else
+    pInfo->blabelaxes = 0;
+
   if( pInfo->labelformat == NULL ) {
     pInfo->labelformat = (char *) msSmallMalloc( strlen( MAPGRATICULE_FORMAT_STRING_DEFAULT ) + 1 );
     pInfo->ilabeltype = (int) lpDefault;
     strcpy( pInfo->labelformat, MAPGRATICULE_FORMAT_STRING_DEFAULT );
   } else if( strcmp( pInfo->labelformat, "DDMMSS" ) == 0 ) {
+    msFree(pInfo->labelformat);
     pInfo->labelformat = (char *) msSmallMalloc( strlen( MAPGRATICULE_FORMAT_STRING_DDMMSS ) + 1 );
     pInfo->ilabeltype = (int) lpDDMMSS;
     strcpy( pInfo->labelformat, MAPGRATICULE_FORMAT_STRING_DDMMSS );
   } else if( strcmp( pInfo->labelformat, "DDMM" )   == 0 ) {
+    msFree(pInfo->labelformat);
     pInfo->labelformat = (char *) msSmallMalloc( strlen( MAPGRATICULE_FORMAT_STRING_DDMM ) + 1 );
     pInfo->ilabeltype = (int) lpDDMM;
     strcpy( pInfo->labelformat, MAPGRATICULE_FORMAT_STRING_DDMM );
   } else if( strcmp( pInfo->labelformat, "DD" )   == 0 ) {
+    msFree(pInfo->labelformat);
     pInfo->labelformat = (char *) msSmallMalloc( strlen( MAPGRATICULE_FORMAT_STRING_DD ) + 1 );
     pInfo->ilabeltype = (int) lpDD;
     strcpy( pInfo->labelformat, MAPGRATICULE_FORMAT_STRING_DD );
   }
-  
+
   return MS_SUCCESS;
 }
 
@@ -127,12 +128,12 @@ int msGraticuleLayerIsOpen(layerObj *layer)
 int msGraticuleLayerClose(layerObj *layer)
 {
   graticuleObj *pInfo = (graticuleObj *) layer->layerinfo;
-  
+
   if( pInfo->labelformat ) {
     free( pInfo->labelformat );
     pInfo->labelformat = NULL;
   }
-   
+
   if( pInfo->pboundingpoints ) {
     free( pInfo->pboundingpoints );
     pInfo->pboundingpoints = NULL;
@@ -178,7 +179,7 @@ int msGraticuleLayerWhichShapes(layerObj *layer, rectObj rect, int isQuery)
     pInfo->dincrementlongitude = 0;
     pInfo->dincrementlatitude = 0;
   }
-   
+
   if( pInfo->maxarcs > 0 )
     iAxisTickCount = (int) pInfo->maxarcs;
   else if( pInfo->minarcs > 0 )
@@ -208,7 +209,7 @@ int msGraticuleLayerWhichShapes(layerObj *layer, rectObj rect, int isQuery)
   rectMapCoordinates = layer->map->extent;
   pInfo->pboundinglines   = (lineObj *)  msSmallMalloc( sizeof( lineObj )  * 4 );
   pInfo->pboundingpoints = (pointObj *) msSmallMalloc( sizeof( pointObj ) * 8 );
-  
+
   {
 
     /*
@@ -231,7 +232,7 @@ int msGraticuleLayerWhichShapes(layerObj *layer, rectObj rect, int isQuery)
     /*
      * bottom
      */
-    pInfo->pboundinglines[1].numpoints = 2; 
+    pInfo->pboundinglines[1].numpoints = 2;
     pInfo->pboundinglines[1].point = &pInfo->pboundingpoints[2];
     pInfo->pboundinglines[1].point[0].x = rectMapCoordinates.minx;
     pInfo->pboundinglines[1].point[0].y   = rectMapCoordinates.miny;
@@ -296,7 +297,7 @@ int msGraticuleLayerNextShape(layerObj *layer, shapeObj *shape)
   shape->numlines = 1;
   shape->type = MS_SHAPE_LINE;
   shape->line = (lineObj *) msSmallMalloc(sizeof( lineObj ));
-  shape->line->numpoints = (int) pInfo->maxsubdivides; 
+  shape->line->numpoints = (int) pInfo->maxsubdivides;
 
   /*
    * Subdivide and draw current arc, rendering the arc labels first
@@ -306,86 +307,86 @@ int msGraticuleLayerNextShape(layerObj *layer, shapeObj *shape)
     double dArcDelta = (pInfo->dendlatitude - pInfo->dstartlatitude) / (double) shape->line->numpoints;
     double dArcPosition  = pInfo->dstartlatitude + dArcDelta;
     double dStartY, dDeltaX;
-      
+
     switch( pInfo->ilabelstate ) {
-    case 0:
-      if(!pInfo->blabelaxes)  { /* Bottom */
-        pInfo->ilabelstate++;
-        shape->numlines = 0;
-        return MS_SUCCESS;
-      }
+      case 0:
+        if(!pInfo->blabelaxes)  { /* Bottom */
+          pInfo->ilabelstate++;
+          shape->numlines = 0;
+          return MS_SUCCESS;
+        }
 
-      dDeltaX = (pInfo->dwhichlongitude - pInfo->pboundinglines[1].point[0].x) / (pInfo->pboundinglines[1].point[1].x - pInfo->pboundinglines[1].point[0].x);
-      if (dDeltaX < 0)
-        dDeltaX=dDeltaX*-1;
+        dDeltaX = (pInfo->dwhichlongitude - pInfo->pboundinglines[1].point[0].x) / (pInfo->pboundinglines[1].point[1].x - pInfo->pboundinglines[1].point[0].x);
+        if (dDeltaX < 0)
+          dDeltaX=dDeltaX*-1;
 
-      dStartY = (pInfo->pboundinglines[1].point[1].y - pInfo->pboundinglines[1].point[0].y) * dDeltaX + pInfo->pboundinglines[1].point[0].y;
-      shape->line->numpoints = (int) 2;
-      shape->line->point = (pointObj *) msSmallMalloc( sizeof( pointObj ) * 2 );
-            
-      shape->line->point[0].x = pInfo->dwhichlongitude;
-      shape->line->point[0].y = dStartY;
-      shape->line->point[1].x = pInfo->dwhichlongitude;
-      shape->line->point[1].y = dStartY + dArcDelta;
+        dStartY = (pInfo->pboundinglines[1].point[1].y - pInfo->pboundinglines[1].point[0].y) * dDeltaX + pInfo->pboundinglines[1].point[0].y;
+        shape->line->numpoints = (int) 2;
+        shape->line->point = (pointObj *) msSmallMalloc( sizeof( pointObj ) * 2 );
 
-      _FormatLabel( layer, shape, shape->line->point[0].x );
-      if(_AdjustLabelPosition( layer, shape, posBottom ) != MS_SUCCESS)
-        return MS_FAILURE;
+        shape->line->point[0].x = pInfo->dwhichlongitude;
+        shape->line->point[0].y = dStartY;
+        shape->line->point[1].x = pInfo->dwhichlongitude;
+        shape->line->point[1].y = dStartY + dArcDelta;
 
-      pInfo->ilabelstate++;
-      return MS_SUCCESS;
+        _FormatLabel( layer, shape, shape->line->point[0].x );
+        if(_AdjustLabelPosition( layer, shape, posBottom ) != MS_SUCCESS)
+          return MS_FAILURE;
 
-    case 1:
-      if(!pInfo->blabelaxes) { /* Top */
         pInfo->ilabelstate++;
-        shape->numlines  = 0;
         return MS_SUCCESS;
-      }
 
-      dDeltaX = (pInfo->dwhichlongitude - pInfo->pboundinglines[0].point[0].x) / (pInfo->pboundinglines[0].point[1].x - pInfo->pboundinglines[0].point[0].x );
-      if (dDeltaX < 0)
-        dDeltaX=dDeltaX*-1;
+      case 1:
+        if(!pInfo->blabelaxes) { /* Top */
+          pInfo->ilabelstate++;
+          shape->numlines  = 0;
+          return MS_SUCCESS;
+        }
 
-      dStartY = (pInfo->pboundinglines[0].point[1].y - pInfo->pboundinglines[0].point[0].y) * dDeltaX + pInfo->pboundinglines[0].point[1].y;
-      shape->line->numpoints = (int) 2;
-      shape->line->point = (pointObj *) msSmallMalloc( sizeof( pointObj ) * 2 );
+        dDeltaX = (pInfo->dwhichlongitude - pInfo->pboundinglines[0].point[0].x) / (pInfo->pboundinglines[0].point[1].x - pInfo->pboundinglines[0].point[0].x );
+        if (dDeltaX < 0)
+          dDeltaX=dDeltaX*-1;
 
-      shape->line->point[0].x = pInfo->dwhichlongitude;
-      shape->line->point[0].y = dStartY - dArcDelta;
-      shape->line->point[1].x = pInfo->dwhichlongitude;
-      shape->line->point[1].y = dStartY;
+        dStartY = (pInfo->pboundinglines[0].point[1].y - pInfo->pboundinglines[0].point[0].y) * dDeltaX + pInfo->pboundinglines[0].point[1].y;
+        shape->line->numpoints = (int) 2;
+        shape->line->point = (pointObj *) msSmallMalloc( sizeof( pointObj ) * 2 );
 
-      _FormatLabel( layer, shape, shape->line->point[0].x );
-      if(_AdjustLabelPosition( layer, shape, posTop ) != MS_SUCCESS)
-        return MS_FAILURE;
+        shape->line->point[0].x = pInfo->dwhichlongitude;
+        shape->line->point[0].y = dStartY - dArcDelta;
+        shape->line->point[1].x = pInfo->dwhichlongitude;
+        shape->line->point[1].y = dStartY;
 
-      pInfo->ilabelstate++;
-      return MS_SUCCESS;
+        _FormatLabel( layer, shape, shape->line->point[0].x );
+        if(_AdjustLabelPosition( layer, shape, posTop ) != MS_SUCCESS)
+          return MS_FAILURE;
 
-    case 2:
-      shape->line->numpoints = (int) shape->line->numpoints + 1;
-      shape->line->point = (pointObj *) msSmallMalloc( sizeof( pointObj ) * shape->line->numpoints );
+        pInfo->ilabelstate++;
+        return MS_SUCCESS;
 
-      shape->line->point[0].x = pInfo->dwhichlongitude;
-      shape->line->point[0].y = pInfo->dstartlatitude;
+      case 2:
+        shape->line->numpoints = (int) shape->line->numpoints + 1;
+        shape->line->point = (pointObj *) msSmallMalloc( sizeof( pointObj ) * shape->line->numpoints );
 
-      for( iPointIndex = 1; iPointIndex < shape->line->numpoints; iPointIndex++ ) {
-        shape->line->point[iPointIndex].x   = pInfo->dwhichlongitude;
-        shape->line->point[iPointIndex].y   = dArcPosition;
-         
-        dArcPosition += dArcDelta;
-      }
-            
-      pInfo->ilabelstate = 0;
+        shape->line->point[0].x = pInfo->dwhichlongitude;
+        shape->line->point[0].y = pInfo->dstartlatitude;
 
-      pInfo->dwhichlongitude      += pInfo->dincrementlongitude;
-      break;
+        for( iPointIndex = 1; iPointIndex < shape->line->numpoints; iPointIndex++ ) {
+          shape->line->point[iPointIndex].x   = pInfo->dwhichlongitude;
+          shape->line->point[iPointIndex].y   = dArcPosition;
 
-    default:
-      pInfo->ilabelstate    = 0;
-      break;
+          dArcPosition += dArcDelta;
+        }
+
+        pInfo->ilabelstate = 0;
+
+        pInfo->dwhichlongitude      += pInfo->dincrementlongitude;
+        break;
+
+      default:
+        pInfo->ilabelstate    = 0;
+        break;
     }
-      
+
   } else { /*horizontal*/
     int iPointIndex;
     double dArcDelta = (pInfo->dendlongitude - pInfo->dstartlongitude) / (double) shape->line->numpoints;
@@ -393,91 +394,91 @@ int msGraticuleLayerNextShape(layerObj *layer, shapeObj *shape)
     double dStartX, dDeltaY;
 
     switch( pInfo->ilabelstate ) {
-    case 0:
-      if(!pInfo->blabelaxes) { /* Left side */
-         pInfo->ilabelstate++;
-         shape->numlines    = 0;
-         return MS_SUCCESS;
-      }
+      case 0:
+        if(!pInfo->blabelaxes) { /* Left side */
+          pInfo->ilabelstate++;
+          shape->numlines    = 0;
+          return MS_SUCCESS;
+        }
 
-      dDeltaY = (pInfo->dwhichlatitude - pInfo->pboundinglines[2].point[0].y) / (pInfo->pboundinglines[2].point[1].y - pInfo->pboundinglines[2].point[0].y );
-      if (dDeltaY < 0)
-        dDeltaY= dDeltaY*-1;
+        dDeltaY = (pInfo->dwhichlatitude - pInfo->pboundinglines[2].point[0].y) / (pInfo->pboundinglines[2].point[1].y - pInfo->pboundinglines[2].point[0].y );
+        if (dDeltaY < 0)
+          dDeltaY= dDeltaY*-1;
 
-      dStartX = (pInfo->pboundinglines[2].point[1].x - pInfo->pboundinglines[2].point[0].x) * dDeltaY + pInfo->pboundinglines[2].point[0].x;
-      shape->line->numpoints = (int) 2;
-      shape->line->point    = (pointObj *) msSmallMalloc( sizeof( pointObj ) * 2 );
-            
-      shape->line->point[0].x = dStartX;
-      shape->line->point[0].y = pInfo->dwhichlatitude;
-      shape->line->point[1].x = dStartX + dArcDelta;
-      shape->line->point[1].y = pInfo->dwhichlatitude;
+        dStartX = (pInfo->pboundinglines[2].point[1].x - pInfo->pboundinglines[2].point[0].x) * dDeltaY + pInfo->pboundinglines[2].point[0].x;
+        shape->line->numpoints = (int) 2;
+        shape->line->point    = (pointObj *) msSmallMalloc( sizeof( pointObj ) * 2 );
 
-      _FormatLabel( layer, shape, shape->line->point[0].y );
-      if(_AdjustLabelPosition( layer, shape, posLeft ) != MS_SUCCESS)
-        return MS_FAILURE;
+        shape->line->point[0].x = dStartX;
+        shape->line->point[0].y = pInfo->dwhichlatitude;
+        shape->line->point[1].x = dStartX + dArcDelta;
+        shape->line->point[1].y = pInfo->dwhichlatitude;
 
-      pInfo->ilabelstate++;
-      return MS_SUCCESS;
+        _FormatLabel( layer, shape, shape->line->point[0].y );
+        if(_AdjustLabelPosition( layer, shape, posLeft ) != MS_SUCCESS)
+          return MS_FAILURE;
 
-    case 1:
-      if(!pInfo->blabelaxes) { /* Right side */
         pInfo->ilabelstate++;
-        shape->numlines    = 0;
         return MS_SUCCESS;
-      }
 
-      dDeltaY = (pInfo->dwhichlatitude - pInfo->pboundinglines[3].point[0].y) / (pInfo->pboundinglines[3].point[1].y - pInfo->pboundinglines[3].point[0].y );
-      if (dDeltaY < 0)
-        dDeltaY= dDeltaY*-1;
+      case 1:
+        if(!pInfo->blabelaxes) { /* Right side */
+          pInfo->ilabelstate++;
+          shape->numlines    = 0;
+          return MS_SUCCESS;
+        }
 
-      dStartX = (pInfo->pboundinglines[3].point[1].x - pInfo->pboundinglines[3].point[0].x) * dDeltaY + pInfo->pboundinglines[3].point[0].x;
-      shape->line->numpoints = (int) 2;
-      shape->line->point = (pointObj *) msSmallMalloc( sizeof( pointObj ) * 2 );
+        dDeltaY = (pInfo->dwhichlatitude - pInfo->pboundinglines[3].point[0].y) / (pInfo->pboundinglines[3].point[1].y - pInfo->pboundinglines[3].point[0].y );
+        if (dDeltaY < 0)
+          dDeltaY= dDeltaY*-1;
 
-      shape->line->point[0].x = dStartX - dArcDelta;
-      shape->line->point[0].y = pInfo->dwhichlatitude;
-      shape->line->point[1].x = dStartX;
-      shape->line->point[1].y = pInfo->dwhichlatitude;
+        dStartX = (pInfo->pboundinglines[3].point[1].x - pInfo->pboundinglines[3].point[0].x) * dDeltaY + pInfo->pboundinglines[3].point[0].x;
+        shape->line->numpoints = (int) 2;
+        shape->line->point = (pointObj *) msSmallMalloc( sizeof( pointObj ) * 2 );
 
-      _FormatLabel( layer, shape, shape->line->point[0].y );
-      if(_AdjustLabelPosition( layer, shape, posRight ) != MS_SUCCESS)
-        return MS_FAILURE;
+        shape->line->point[0].x = dStartX - dArcDelta;
+        shape->line->point[0].y = pInfo->dwhichlatitude;
+        shape->line->point[1].x = dStartX;
+        shape->line->point[1].y = pInfo->dwhichlatitude;
 
-      pInfo->ilabelstate++;
-      return MS_SUCCESS;
+        _FormatLabel( layer, shape, shape->line->point[0].y );
+        if(_AdjustLabelPosition( layer, shape, posRight ) != MS_SUCCESS)
+          return MS_FAILURE;
 
-    case 2:
-      shape->line->numpoints = (int) shape->line->numpoints + 1;
-      shape->line->point = (pointObj *) msSmallMalloc( sizeof( pointObj ) * shape->line->numpoints );
+        pInfo->ilabelstate++;
+        return MS_SUCCESS;
 
-      shape->line->point[0].x = pInfo->dstartlongitude;
-      shape->line->point[0].y = pInfo->dwhichlatitude;
+      case 2:
+        shape->line->numpoints = (int) shape->line->numpoints + 1;
+        shape->line->point = (pointObj *) msSmallMalloc( sizeof( pointObj ) * shape->line->numpoints );
 
-      for(iPointIndex = 1; iPointIndex < shape->line->numpoints; iPointIndex++) {
-        shape->line->point[iPointIndex].x   = dArcPosition;
-        shape->line->point[iPointIndex].y   = pInfo->dwhichlatitude;
-         
-        dArcPosition += dArcDelta;
-      }
-            
-      pInfo->ilabelstate    = 0;
-      pInfo->dwhichlatitude += pInfo->dincrementlatitude;
-      break;
+        shape->line->point[0].x = pInfo->dstartlongitude;
+        shape->line->point[0].y = pInfo->dwhichlatitude;
 
-    default:
-      pInfo->ilabelstate    = 0;
-      break;
+        for(iPointIndex = 1; iPointIndex < shape->line->numpoints; iPointIndex++) {
+          shape->line->point[iPointIndex].x   = dArcPosition;
+          shape->line->point[iPointIndex].y   = pInfo->dwhichlatitude;
+
+          dArcPosition += dArcDelta;
+        }
+
+        pInfo->ilabelstate    = 0;
+        pInfo->dwhichlatitude += pInfo->dincrementlatitude;
+        break;
+
+      default:
+        pInfo->ilabelstate    = 0;
+        break;
     }
   }
 
- /*
-   * Increment and move to next arc
-   */
- 
+  /*
+    * Increment and move to next arc
+    */
+
   if( pInfo->bvertical && pInfo->dwhichlongitude > pInfo->dendlongitude )   {
-      pInfo->dwhichlatitude   = pInfo->dstartlatitude;
-      pInfo->bvertical   = 0;
+    pInfo->dwhichlatitude   = pInfo->dstartlatitude;
+    pInfo->bvertical   = 0;
   }
 
   if (pInfo->dwhichlatitude >  pInfo->dendlatitude) {
@@ -537,7 +538,7 @@ int msGraticuleLayerGetExtent(layerObj *layer, rectObj *extent)
   graticuleObj *pInfo = (graticuleObj  *) layer->layerinfo;
 
   if(pInfo) {
-    *extent = pInfo->extent;  
+    *extent = pInfo->extent;
     return MS_SUCCESS;
   }
 
@@ -560,32 +561,31 @@ int msGraticuleLayerGetAutoStyle(mapObj *map, layerObj *layer, classObj *c, shap
 /************************************************************************/
 void msGraticuleLayerFreeIntersectionPoints( graticuleIntersectionObj *psValue)
 {
-    int i=0;
-    if (psValue)
-    {
-        for (i=0; i<psValue->nTop; i++)
-          msFree(psValue->papszTopLabels[i]);
-        msFree(psValue->papszTopLabels);
-        msFree(psValue->pasTop);
-
-        for (i=0; i<psValue->nBottom; i++)
-          msFree(psValue->papszBottomLabels[i]);
-        msFree(psValue->papszBottomLabels);
-        msFree(psValue->pasBottom);
-
-
-        for (i=0; i<psValue->nLeft; i++)
-          msFree(psValue->papszLeftLabels[i]);
-        msFree(psValue->papszLeftLabels);
-        msFree(psValue->pasLeft);
-        
-        for (i=0; i<psValue->nRight; i++)
-          msFree(psValue->papszRightLabels[i]);
-        msFree(psValue->papszRightLabels);
-        msFree(psValue->pasRight);
-
-        msFree(psValue);
-    }
+  int i=0;
+  if (psValue) {
+    for (i=0; i<psValue->nTop; i++)
+      msFree(psValue->papszTopLabels[i]);
+    msFree(psValue->papszTopLabels);
+    msFree(psValue->pasTop);
+
+    for (i=0; i<psValue->nBottom; i++)
+      msFree(psValue->papszBottomLabels[i]);
+    msFree(psValue->papszBottomLabels);
+    msFree(psValue->pasBottom);
+
+
+    for (i=0; i<psValue->nLeft; i++)
+      msFree(psValue->papszLeftLabels[i]);
+    msFree(psValue->papszLeftLabels);
+    msFree(psValue->pasLeft);
+
+    for (i=0; i<psValue->nRight; i++)
+      msFree(psValue->papszRightLabels[i]);
+    msFree(psValue->papszRightLabels);
+    msFree(psValue->pasRight);
+
+    msFree(psValue);
+  }
 }
 
 
@@ -596,21 +596,20 @@ void msGraticuleLayerFreeIntersectionPoints( graticuleIntersectionObj *psValue)
 /************************************************************************/
 static void msGraticuleLayerInitIntersectionPoints( graticuleIntersectionObj *psValue)
 {
-    if (psValue)
-    {
-        psValue->nTop = 0;
-        psValue->pasTop = NULL;
-        psValue->papszTopLabels = NULL;
-        psValue->nBottom = 0;
-        psValue->pasBottom = NULL;
-        psValue->papszBottomLabels = NULL;
-        psValue->nLeft = 0;
-        psValue->pasLeft = NULL;
-        psValue->papszLeftLabels = NULL;
-        psValue->nRight = 0;
-        psValue->pasRight = NULL;
-        psValue->papszRightLabels = NULL;
-    }
+  if (psValue) {
+    psValue->nTop = 0;
+    psValue->pasTop = NULL;
+    psValue->papszTopLabels = NULL;
+    psValue->nBottom = 0;
+    psValue->pasBottom = NULL;
+    psValue->papszBottomLabels = NULL;
+    psValue->nLeft = 0;
+    psValue->pasLeft = NULL;
+    psValue->papszLeftLabels = NULL;
+    psValue->nRight = 0;
+    psValue->pasRight = NULL;
+    psValue->papszRightLabels = NULL;
+  }
 }
 
 
@@ -620,394 +619,356 @@ static void msGraticuleLayerInitIntersectionPoints( graticuleIntersectionObj *ps
 /*      Utility function thar returns all intersection positions and    */
 /*      labels (4 sides of the map) for a grid layer.                   */
 /************************************************************************/
-graticuleIntersectionObj *msGraticuleLayerGetIntersectionPoints(mapObj *map, 
-                                                                layerObj *layer)
+graticuleIntersectionObj *msGraticuleLayerGetIntersectionPoints(mapObj *map,
+    layerObj *layer)
 {
-    
-    shapeObj    shapegrid, tmpshape;
-    rectObj     searchrect;
-    int         status;
-    pointObj oFirstPoint;
-    pointObj oLastPoint;
-    lineObj oLineObj;
-    rectObj cliprect;
-    graticuleObj   *pInfo  = NULL;
-    double dfTmp;
-    graticuleIntersectionObj *psValues = NULL;
-    int i=0;
-
-    if (layer->connectiontype != MS_GRATICULE)
-      return NULL;
-
-    pInfo  = (graticuleObj *) layer->layerinfo;
-
-    /*set cellsize if bnot already set*/
-    if (map->cellsize == 0)
-      map->cellsize = msAdjustExtent(&(map->extent),map->width,map->height);
-
-    psValues = (graticuleIntersectionObj *)msSmallMalloc(sizeof(graticuleIntersectionObj));
- 
-    msGraticuleLayerInitIntersectionPoints(psValues);
-
-    if(layer->transform == MS_TRUE)
+
+  shapeObj    shapegrid, tmpshape;
+  rectObj     searchrect;
+  int         status;
+  pointObj oFirstPoint;
+  pointObj oLastPoint;
+  lineObj oLineObj;
+  rectObj cliprect;
+  graticuleObj   *pInfo  = NULL;
+  double dfTmp;
+  graticuleIntersectionObj *psValues = NULL;
+  int i=0;
+
+  if (layer->connectiontype != MS_GRATICULE)
+    return NULL;
+
+  pInfo  = (graticuleObj *) layer->layerinfo;
+
+  /*set cellsize if bnot already set*/
+  if (map->cellsize == 0)
+    map->cellsize = msAdjustExtent(&(map->extent),map->width,map->height);
+
+  psValues = (graticuleIntersectionObj *)msSmallMalloc(sizeof(graticuleIntersectionObj));
+
+  msGraticuleLayerInitIntersectionPoints(psValues);
+
+  if(layer->transform == MS_TRUE)
     searchrect = map->extent;
-    else {
-      searchrect.minx = searchrect.miny = 0;
-      searchrect.maxx = map->width-1;
-      searchrect.maxy = map->height-1;
-    }
-  
+  else {
+    searchrect.minx = searchrect.miny = 0;
+    searchrect.maxx = map->width-1;
+    searchrect.maxy = map->height-1;
+  }
+
 #ifdef USE_PROJ
-    if((map->projection.numargs > 0) && (layer->projection.numargs > 0))
-      msProjectRect(&map->projection, &layer->projection, &searchrect); /* project the searchrect to source coords */
+  if((map->projection.numargs > 0) && (layer->projection.numargs > 0))
+    msProjectRect(&map->projection, &layer->projection, &searchrect); /* project the searchrect to source coords */
 #endif
- 
-    msLayerOpen(layer);
-   
-    status = msLayerWhichShapes(layer, searchrect, MS_FALSE);
-    if(status == MS_DONE) { /* no overlap */
-      msLayerClose(layer);
-      return NULL;
-    } else if(status != MS_SUCCESS) {
-      msLayerClose(layer);
-      return NULL;
+
+  msLayerOpen(layer);
+
+  status = msLayerWhichShapes(layer, searchrect, MS_FALSE);
+  if(status == MS_DONE) { /* no overlap */
+    msLayerClose(layer);
+    return NULL;
+  } else if(status != MS_SUCCESS) {
+    msLayerClose(layer);
+    return NULL;
+  }
+
+  /* step through the target shapes */
+  msInitShape(&shapegrid);
+  cliprect.minx = map->extent.minx- map->cellsize;
+  cliprect.miny = map->extent.miny- map->cellsize;
+  cliprect.maxx = map->extent.maxx + map->cellsize;
+  cliprect.maxy = map->extent.maxy + map->cellsize;
+
+  /* clip using the layer projection */
+  /* msProjectRect(&map->projection , &layer->projection,  &cliprect); */
+
+  while((status = msLayerNextShape(layer, &shapegrid)) == MS_SUCCESS) {
+    /*don't really need a class here*/
+    /*
+      shapegrid.classindex = msShapeGetClass(layer, &shapegrid, map->scaledenom, NULL, 0);
+      if((shapegrid.classindex == -1) || (layer->class[shapegrid.classindex]->status == MS_OFF)) {
+    msFreeShape(&shapegrid);
+    continue;
     }
-  
-    /* step through the target shapes */
-    msInitShape(&shapegrid);
-    cliprect.minx = map->extent.minx- map->cellsize;
-    cliprect.miny = map->extent.miny- map->cellsize;
-    cliprect.maxx = map->extent.maxx + map->cellsize;
-    cliprect.maxy = map->extent.maxy + map->cellsize;
-
-    //clip using the layer projection
-    //msProjectRect(&map->projection , &layer->projection,  &cliprect);
-
-    while((status = msLayerNextShape(layer, &shapegrid)) == MS_SUCCESS) 
-    {
-        /*don't really need a class here*/
-        /*
-          shapegrid.classindex = msShapeGetClass(layer, &shapegrid, map->scaledenom, NULL, 0);
-          if((shapegrid.classindex == -1) || (layer->class[shapegrid.classindex]->status == MS_OFF)) {
-        msFreeShape(&shapegrid);
-        continue;
+    */
+
+    msInitShape(&tmpshape);
+    msCopyShape(&shapegrid, &tmpshape);
+    /* status = msDrawShape(map, layer, &tmpshape, image, -1); */
+
+    if(layer->project && msProjectionsDiffer(&(layer->projection), &(map->projection)))
+      msProjectShape(&layer->projection, &map->projection, &shapegrid);
+
+    msClipPolylineRect(&shapegrid, cliprect);
+
+
+    msTransformShapeToPixelRound(&shapegrid, map->extent, map->cellsize);
+
+
+
+    if(shapegrid.numlines <= 0 || shapegrid.line[0].numpoints < 2) { /* once clipped the shape didn't need to be drawn */
+      msFreeShape(&shapegrid);
+      msFreeShape(&tmpshape);
+      continue;
+    }
+
+
+
+    if(shapegrid.numlines >= 1 && shapegrid.line[0].numpoints >=2) { /* && shapegrid.text) */
+      int iTmpLine = 0;
+      int nNumPoints = 0;
+      /*grid code seems to retunr lines that can double cross the extenst??*/
+      /*creating a more than one clipped shape. Take the shape that has the most
+        points, which should be the most likley to be correct*/
+
+      if (shapegrid.numlines > 1) {
+        for (i=0; i<shapegrid.numlines; i++) {
+          if (shapegrid.line[i].numpoints > nNumPoints) {
+            nNumPoints = shapegrid.line[i].numpoints;
+            iTmpLine = i;
+          }
         }
-        */
-       
-      msInitShape(&tmpshape);
-      msCopyShape(&shapegrid, &tmpshape);      
-      //status = msDrawShape(map, layer, &tmpshape, image, -1);
-      
-      if(layer->project && msProjectionsDiffer(&(layer->projection), &(map->projection)))
-        msProjectShape(&layer->projection, &map->projection, &shapegrid);
-
-      msClipPolylineRect(&shapegrid, cliprect);
-     
-
-      msTransformShapeToPixelRound(&shapegrid, map->extent, map->cellsize);
-
-     
- 
-      if(shapegrid.numlines <= 0 || shapegrid.line[0].numpoints < 2) { /* once clipped the shape didn't need to be drawn */
-        msFreeShape(&shapegrid);
-        msFreeShape(&tmpshape);
-        continue;
       }
+      /* get the first and last point*/
+      oFirstPoint.x = shapegrid.line[iTmpLine].point[0].x;
+      oFirstPoint.y = shapegrid.line[iTmpLine].point[0].y;
+      oLineObj = shapegrid.line[iTmpLine];
+      oLastPoint.x = oLineObj.point[oLineObj.numpoints-1].x;
+      oLastPoint.y = oLineObj.point[oLineObj.numpoints-1].y;
+
+      if ( pInfo->bvertical) { /*vertical*/
+        /*SHAPES ARE DRAWN FROM BOTTOM TO TOP.*/
+        /*Normally lines are drawn FROM BOTTOM TO TOP but not always for some reason, so
+          make sure that firstpoint < lastpoint in y, We are in pixel coordinates so y increases as we
+        we go down*/
+        if (oFirstPoint.y < oLastPoint.y) {
+          dfTmp = oFirstPoint.x;
+          oFirstPoint.x = oLastPoint.x;
+          oLastPoint.x = dfTmp;
+          dfTmp = oFirstPoint.y;
+          oFirstPoint.y = oLastPoint.y;
+          oLastPoint.y = dfTmp;
+
+        }
+
+        /*first point should cross the BOTTOM base where y== map->height*/
+
+        if (abs ((int)oFirstPoint.y - map->height)  <=1) {
+          char *pszLabel=NULL;
+          oFirstPoint.y = map->height;
+
+          /*validate point is in map width/height*/
+          if (oFirstPoint.x < 0 || oFirstPoint.x > map->width)
+            continue;
 
-      
-
-      if(shapegrid.numlines >= 1 && shapegrid.line[0].numpoints >=2)// && shapegrid.text)
-      {         
-          int iTmpLine = 0;
-          int nNumPoints = 0;
-          /*grid code seems to retunr lines that can double cross the extenst??*/
-          /*creating a more than one clipped shape. Take the shape that has the most
-            points, which should be the most likley to be correct*/
-          
-          if (shapegrid.numlines > 1)
-          {
-              for (i=0; i<shapegrid.numlines; i++)
-              {
-                  if (shapegrid.line[i].numpoints > nNumPoints)
-                  {
-                      nNumPoints = shapegrid.line[i].numpoints;
-                      iTmpLine = i;
-                  }
-              }
+          /*validate point is in map width/height*/
+          if (oLastPoint.x < 0 || oLastPoint.x > map->width)
+            continue;
+
+          if (shapegrid.text)
+            pszLabel =  msStrdup(shapegrid.text);
+          else {
+            _FormatLabel(layer, &tmpshape, tmpshape.line[0].point[tmpshape.line[0].numpoints-1].x );
+            if (tmpshape.text)
+              pszLabel = msStrdup(tmpshape.text);
+            else
+              pszLabel = msStrdup("unknown");
           }
-          /* get the first and last point*/
-          oFirstPoint.x = shapegrid.line[iTmpLine].point[0].x;
-          oFirstPoint.y = shapegrid.line[iTmpLine].point[0].y;
-          oLineObj = shapegrid.line[iTmpLine];
-          oLastPoint.x = oLineObj.point[oLineObj.numpoints-1].x;
-          oLastPoint.y = oLineObj.point[oLineObj.numpoints-1].y;          
-
-          if ( pInfo->bvertical) /*vertical*/
-            {
-              /*SHAPES ARE DRAWN FROM BOTTOM TO TOP.*/
-              /*Normally lines are drawn FROM BOTTOM TO TOP but not always for some reason, so
-                make sure that firstpoint < lastpoint in y, We are in pixel coordinates so y increases as we 
-              we go down*/
-              if (oFirstPoint.y < oLastPoint.y)
-                {
-                  dfTmp = oFirstPoint.x;
-                  oFirstPoint.x = oLastPoint.x;
-                  oLastPoint.x = dfTmp;
-                  dfTmp = oFirstPoint.y;
-                  oFirstPoint.y = oLastPoint.y;
-                  oLastPoint.y = dfTmp;
-                      
-                }
-
-              /*first point should cross the BOTTOM base where y== map->height*/
-                 
-              if (abs ((int)oFirstPoint.y - map->height)  <=1)
-              { 
-                  char *pszLabel=NULL;
-                  oFirstPoint.y = map->height;
-                      
-                  /*validate point is in map width/height*/
-                  if (oFirstPoint.x < 0 || oFirstPoint.x > map->width)
-                    continue;
-
-                  /*validate point is in map width/height*/
-                  if (oLastPoint.x < 0 || oLastPoint.x > map->width)
-                    continue;
-
-                  if (shapegrid.text)
-                    pszLabel =  msStrdup(shapegrid.text);
-                  else
-                  {
-                      _FormatLabel(layer, &tmpshape, tmpshape.line[0].point[tmpshape.line[0].numpoints-1].x );
-                      if (tmpshape.text)
-                        pszLabel = msStrdup(tmpshape.text);
-                      else
-                        pszLabel = msStrdup("unknown");
-                  }
-                  /*validate that the  value is not already in the array*/
-                  if ( psValues->nBottom > 0)
-                    {
-                      //if (psValues->pasBottom[psValues->nBottom-1].x == oFirstPoint.x)
-                      //continue;
-
-                      for (i=0; i<psValues->nBottom; i++)
-                        {
-                          if (psValues->pasBottom[i].x == oFirstPoint.x)
-                            break;
-                        }
-                      if (i  < psValues->nBottom)
-                        continue;
-                    }
-                  if (psValues->pasBottom == NULL)
-                    {
-                      psValues->pasBottom = (pointObj *)msSmallMalloc(sizeof(pointObj));
-                      psValues->papszBottomLabels = (char **)msSmallMalloc(sizeof(char *));
-                      psValues->nBottom = 1;
-                    }
-                  else
-                    {
-                      psValues->nBottom++;
-                      psValues->pasBottom = (pointObj *)msSmallRealloc(psValues->pasBottom, sizeof(pointObj)*psValues->nBottom);
-                      psValues->papszBottomLabels = (char **)msSmallRealloc(psValues->papszBottomLabels, sizeof(char *)*psValues->nBottom);
-                    }
-                      
-                  psValues->pasBottom[psValues->nBottom-1].x = oFirstPoint.x;
-                  psValues->pasBottom[psValues->nBottom-1].y = oFirstPoint.y;
-                  psValues->papszBottomLabels[psValues->nBottom-1] = msStrdup(pszLabel);
-
-                  msFree(pszLabel); 
-
-                }
-              /*first point should cross the TOP base where y==0*/
-              if (abs((int)oLastPoint.y) <=1)
-              {
-                  char *pszLabel=NULL;
-                  oLastPoint.y = 0;
-
-                  /*validate point is in map width/height*/
-                  if (oLastPoint.x < 0 || oLastPoint.x > map->width)
-                    continue;
-
-                  if (shapegrid.text)
-                    pszLabel =  msStrdup(shapegrid.text);
-                  else
-                  {
-                      _FormatLabel(layer, &tmpshape, tmpshape.line[0].point[tmpshape.line[0].numpoints-1].x );
-                       if (tmpshape.text)
-                         pszLabel = msStrdup(tmpshape.text);
-                       else
-                         pszLabel = msStrdup("unknown");
-                  }
-                  /*validate if same value is not already there*/
-                  if ( psValues->nTop > 0)
-                    {
-                      //if (psValues->pasTop[psValues->nTop-1].x == oLastPoint.x)
-                      //continue;
-
-                      for (i=0; i<psValues->nTop; i++)
-                        {
-                          if (psValues->pasTop[i].x == oLastPoint.x || 
-                              strcasecmp(pszLabel, psValues->papszTopLabels[i]) == 0)
-                            break;
-                        }
-                      if (i < psValues->nTop)
-                        continue;
-                    }
-                  
-                    
-                  if (psValues->pasTop == NULL)
-                    {
-                      psValues->pasTop = (pointObj *)msSmallMalloc(sizeof(pointObj));
-                      psValues->papszTopLabels = (char **)msSmallMalloc(sizeof(char *));
-                      psValues->nTop = 1;
-                    }
-                  else
-                    {
-                      psValues->nTop++;
-                      psValues->pasTop = (pointObj *)msSmallRealloc(psValues->pasTop, sizeof(pointObj)*psValues->nTop);
-                      psValues->papszTopLabels = (char **)msSmallRealloc(psValues->papszTopLabels, sizeof(char *)*psValues->nTop);
-                    }
-                      
-                  psValues->pasTop[psValues->nTop-1].x = oLastPoint.x;
-                  psValues->pasTop[psValues->nTop-1].y = oLastPoint.y;
-                  psValues->papszTopLabels[psValues->nTop-1] = msStrdup(pszLabel);
-
-                  msFree(pszLabel); 
-                }
+          /*validate that the  value is not already in the array*/
+          if ( psValues->nBottom > 0) {
+            /* if (psValues->pasBottom[psValues->nBottom-1].x == oFirstPoint.x)
+                 continue; */
+
+            for (i=0; i<psValues->nBottom; i++) {
+              if (psValues->pasBottom[i].x == oFirstPoint.x)
+                break;
             }
-          else /*horzontal*/
-            {
-              /*Normally lines are drawn from left to right but not always for some reason, so
-                make sure that firstpoint < lastpoint in x*/
-              if (oFirstPoint.x > oLastPoint.x)
-              {
-                  
-                  dfTmp = oFirstPoint.x;
-                  oFirstPoint.x = oLastPoint.x;
-                  oLastPoint.x = dfTmp;
-                  dfTmp = oFirstPoint.y;
-                  oFirstPoint.y = oLastPoint.y;
-                  oLastPoint.y = dfTmp;
-                      
-                }
-              /*first point should cross the LEFT base where x=0 axis*/
-              if (abs((int)oFirstPoint.x) <=1)
-              {
-                  char *pszLabel=NULL;
-                  oFirstPoint.x = 0;
-
-                  /*validate point is in map width/height*/
-                  if (oFirstPoint.y < 0 || oFirstPoint.y > map->height)
-                    continue;
-
-                  if (shapegrid.text)
-                    pszLabel =  msStrdup(shapegrid.text);
-                  else
-                  {
-                      _FormatLabel(layer, &tmpshape, tmpshape.line[0].point[tmpshape.line[0].numpoints-1].y );
-                       if (tmpshape.text)
-                         pszLabel = msStrdup(tmpshape.text);
-                       else
-                         pszLabel = msStrdup("unknown");
-                  }
-
-                  /*validate that the previous value is not the same*/
-                  if ( psValues->nLeft > 0)
-                    {
-                      //if (psValues->pasLeft[psValues->nLeft-1].y == oFirstPoint.y)
-                      // continue;
-
-                      for (i=0; i<psValues->nLeft; i++)
-                        {
-                          if (psValues->pasLeft[i].y == oFirstPoint.y)
-                            break;
-                        }
-                      if (i < psValues->nLeft)
-                        continue;
-                    }
-                  if (psValues->pasLeft == NULL)
-                    {
-                      psValues->pasLeft = (pointObj *)msSmallMalloc(sizeof(pointObj));
-                      psValues->papszLeftLabels = (char **)msSmallMalloc(sizeof(char *));
-                      psValues->nLeft = 1;
-                    }
-                  else
-                    {
-                      psValues->nLeft++;
-                      psValues->pasLeft = (pointObj *)msSmallRealloc(psValues->pasLeft, sizeof(pointObj)*psValues->nLeft);
-                      psValues->papszLeftLabels = (char **)msSmallRealloc(psValues->papszLeftLabels, sizeof(char *)*psValues->nLeft);
-                    }
-                      
-                  psValues->pasLeft[psValues->nLeft-1].x = oFirstPoint.x;
-                  psValues->pasLeft[psValues->nLeft-1].y = oFirstPoint.y;
-                  psValues->papszLeftLabels[psValues->nLeft-1] = msStrdup(pszLabel);
-                  msFree(pszLabel); 
-                }
-              /*first point should cross the RIGHT base where x=map=>width axis*/
-              if (abs((int)oLastPoint.x - map->width) <=1)
-              {
-                  char *pszLabel=NULL;
-                  oLastPoint.x =  map->width;
-
-                  /*validate point is in map width/height*/
-                  if (oLastPoint.y < 0 || oLastPoint.y > map->height)
-                    continue;
-
-                  if (shapegrid.text)
-                    pszLabel =  msStrdup(shapegrid.text);
-                  else
-                  {
-                      _FormatLabel(layer, &tmpshape, tmpshape.line[0].point[tmpshape.line[0].numpoints-1].y );
-                       if (tmpshape.text)
-                         pszLabel = msStrdup(tmpshape.text);
-                       else
-                         pszLabel = msStrdup("unknown");
-                  }
-
-                  /*validate that the previous value is not the same*/
-                  if ( psValues->nRight > 0)
-                    {
-                      //if (psValues->pasRight[psValues->nRight-1].y == oLastPoint.y)
-                      // continue;
-                      for (i=0; i<psValues->nRight; i++)
-                        {     
-                          if (psValues->pasRight[i].y == oLastPoint.y)
-                            break;
-                        }
-                      if (i < psValues->nRight)
-                        continue;
-                    }
-                  if (psValues->pasRight == NULL)
-                    {
-                      psValues->pasRight = (pointObj *)msSmallMalloc(sizeof(pointObj));
-                      psValues->papszRightLabels = (char **)msSmallMalloc(sizeof(char *));
-                      psValues->nRight = 1;
-                    }
-                  else
-                    {
-                      psValues->nRight++;
-                      psValues->pasRight = (pointObj *)msSmallRealloc(psValues->pasRight, sizeof(pointObj)*psValues->nRight);
-                      psValues->papszRightLabels = (char **)msSmallRealloc(psValues->papszRightLabels, sizeof(char *)*psValues->nRight);
-                    }
-                      
-                  psValues->pasRight[psValues->nRight-1].x = oLastPoint.x;
-                  psValues->pasRight[psValues->nRight-1].y = oLastPoint.y;
-                  psValues->papszRightLabels[psValues->nRight-1] = msStrdup(pszLabel);
-
-                  msFree(pszLabel); 
-                }
+            if (i  < psValues->nBottom)
+              continue;
+          }
+          if (psValues->pasBottom == NULL) {
+            psValues->pasBottom = (pointObj *)msSmallMalloc(sizeof(pointObj));
+            psValues->papszBottomLabels = (char **)msSmallMalloc(sizeof(char *));
+            psValues->nBottom = 1;
+          } else {
+            psValues->nBottom++;
+            psValues->pasBottom = (pointObj *)msSmallRealloc(psValues->pasBottom, sizeof(pointObj)*psValues->nBottom);
+            psValues->papszBottomLabels = (char **)msSmallRealloc(psValues->papszBottomLabels, sizeof(char *)*psValues->nBottom);
+          }
+
+          psValues->pasBottom[psValues->nBottom-1].x = oFirstPoint.x;
+          psValues->pasBottom[psValues->nBottom-1].y = oFirstPoint.y;
+          psValues->papszBottomLabels[psValues->nBottom-1] = msStrdup(pszLabel);
+
+          msFree(pszLabel);
+
+        }
+        /*first point should cross the TOP base where y==0*/
+        if (abs((int)oLastPoint.y) <=1) {
+          char *pszLabel=NULL;
+          oLastPoint.y = 0;
+
+          /*validate point is in map width/height*/
+          if (oLastPoint.x < 0 || oLastPoint.x > map->width)
+            continue;
+
+          if (shapegrid.text)
+            pszLabel =  msStrdup(shapegrid.text);
+          else {
+            _FormatLabel(layer, &tmpshape, tmpshape.line[0].point[tmpshape.line[0].numpoints-1].x );
+            if (tmpshape.text)
+              pszLabel = msStrdup(tmpshape.text);
+            else
+              pszLabel = msStrdup("unknown");
+          }
+          /*validate if same value is not already there*/
+          if ( psValues->nTop > 0) {
+            /* if (psValues->pasTop[psValues->nTop-1].x == oLastPoint.x)
+                 continue; */
+
+            for (i=0; i<psValues->nTop; i++) {
+              if (psValues->pasTop[i].x == oLastPoint.x ||
+                  strcasecmp(pszLabel, psValues->papszTopLabels[i]) == 0)
+                break;
             }
-          msFreeShape(&shapegrid);
-          msFreeShape(&tmpshape);
+            if (i < psValues->nTop)
+              continue;
+          }
+
+
+          if (psValues->pasTop == NULL) {
+            psValues->pasTop = (pointObj *)msSmallMalloc(sizeof(pointObj));
+            psValues->papszTopLabels = (char **)msSmallMalloc(sizeof(char *));
+            psValues->nTop = 1;
+          } else {
+            psValues->nTop++;
+            psValues->pasTop = (pointObj *)msSmallRealloc(psValues->pasTop, sizeof(pointObj)*psValues->nTop);
+            psValues->papszTopLabels = (char **)msSmallRealloc(psValues->papszTopLabels, sizeof(char *)*psValues->nTop);
+          }
+
+          psValues->pasTop[psValues->nTop-1].x = oLastPoint.x;
+          psValues->pasTop[psValues->nTop-1].y = oLastPoint.y;
+          psValues->papszTopLabels[psValues->nTop-1] = msStrdup(pszLabel);
+
+          msFree(pszLabel);
         }
-      msInitShape(&shapegrid);
-     
+      } else { /*horzontal*/
+        /*Normally lines are drawn from left to right but not always for some reason, so
+          make sure that firstpoint < lastpoint in x*/
+        if (oFirstPoint.x > oLastPoint.x) {
+
+          dfTmp = oFirstPoint.x;
+          oFirstPoint.x = oLastPoint.x;
+          oLastPoint.x = dfTmp;
+          dfTmp = oFirstPoint.y;
+          oFirstPoint.y = oLastPoint.y;
+          oLastPoint.y = dfTmp;
 
-  
+        }
+        /*first point should cross the LEFT base where x=0 axis*/
+        if (abs((int)oFirstPoint.x) <=1) {
+          char *pszLabel=NULL;
+          oFirstPoint.x = 0;
+
+          /*validate point is in map width/height*/
+          if (oFirstPoint.y < 0 || oFirstPoint.y > map->height)
+            continue;
+
+          if (shapegrid.text)
+            pszLabel =  msStrdup(shapegrid.text);
+          else {
+            _FormatLabel(layer, &tmpshape, tmpshape.line[0].point[tmpshape.line[0].numpoints-1].y );
+            if (tmpshape.text)
+              pszLabel = msStrdup(tmpshape.text);
+            else
+              pszLabel = msStrdup("unknown");
+          }
+
+          /*validate that the previous value is not the same*/
+          if ( psValues->nLeft > 0) {
+            /* if (psValues->pasLeft[psValues->nLeft-1].y == oFirstPoint.y)
+                 continue; */
+
+            for (i=0; i<psValues->nLeft; i++) {
+              if (psValues->pasLeft[i].y == oFirstPoint.y)
+                break;
+            }
+            if (i < psValues->nLeft)
+              continue;
+          }
+          if (psValues->pasLeft == NULL) {
+            psValues->pasLeft = (pointObj *)msSmallMalloc(sizeof(pointObj));
+            psValues->papszLeftLabels = (char **)msSmallMalloc(sizeof(char *));
+            psValues->nLeft = 1;
+          } else {
+            psValues->nLeft++;
+            psValues->pasLeft = (pointObj *)msSmallRealloc(psValues->pasLeft, sizeof(pointObj)*psValues->nLeft);
+            psValues->papszLeftLabels = (char **)msSmallRealloc(psValues->papszLeftLabels, sizeof(char *)*psValues->nLeft);
+          }
+
+          psValues->pasLeft[psValues->nLeft-1].x = oFirstPoint.x;
+          psValues->pasLeft[psValues->nLeft-1].y = oFirstPoint.y;
+          psValues->papszLeftLabels[psValues->nLeft-1] = msStrdup(pszLabel);
+          msFree(pszLabel);
+        }
+        /*first point should cross the RIGHT base where x=map=>width axis*/
+        if (abs((int)oLastPoint.x - map->width) <=1) {
+          char *pszLabel=NULL;
+          oLastPoint.x =  map->width;
+
+          /*validate point is in map width/height*/
+          if (oLastPoint.y < 0 || oLastPoint.y > map->height)
+            continue;
+
+          if (shapegrid.text)
+            pszLabel =  msStrdup(shapegrid.text);
+          else {
+            _FormatLabel(layer, &tmpshape, tmpshape.line[0].point[tmpshape.line[0].numpoints-1].y );
+            if (tmpshape.text)
+              pszLabel = msStrdup(tmpshape.text);
+            else
+              pszLabel = msStrdup("unknown");
+          }
+
+          /*validate that the previous value is not the same*/
+          if ( psValues->nRight > 0) {
+            /* if (psValues->pasRight[psValues->nRight-1].y == oLastPoint.y)
+                 continue; */
+            for (i=0; i<psValues->nRight; i++) {
+              if (psValues->pasRight[i].y == oLastPoint.y)
+                break;
+            }
+            if (i < psValues->nRight)
+              continue;
+          }
+          if (psValues->pasRight == NULL) {
+            psValues->pasRight = (pointObj *)msSmallMalloc(sizeof(pointObj));
+            psValues->papszRightLabels = (char **)msSmallMalloc(sizeof(char *));
+            psValues->nRight = 1;
+          } else {
+            psValues->nRight++;
+            psValues->pasRight = (pointObj *)msSmallRealloc(psValues->pasRight, sizeof(pointObj)*psValues->nRight);
+            psValues->papszRightLabels = (char **)msSmallRealloc(psValues->papszRightLabels, sizeof(char *)*psValues->nRight);
+          }
+
+          psValues->pasRight[psValues->nRight-1].x = oLastPoint.x;
+          psValues->pasRight[psValues->nRight-1].y = oLastPoint.y;
+          psValues->papszRightLabels[psValues->nRight-1] = msStrdup(pszLabel);
+
+          msFree(pszLabel);
+        }
+      }
+      msFreeShape(&shapegrid);
+      msFreeShape(&tmpshape);
     }
-    msLayerClose(layer);
-    return psValues;
-    
+    msInitShape(&shapegrid);
+
+
+
+  }
+  msLayerClose(layer);
+  return psValues;
+
 }
 
 
@@ -1048,29 +1009,29 @@ static void _FormatLabel( layerObj *pLayer, shapeObj *pShape, double dDataToForm
   graticuleObj *pInfo = (graticuleObj  *) pLayer->layerinfo;
   char cBuffer[32];
   int iDegrees, iMinutes;
-   
+
   switch( pInfo->ilabeltype ) {
-  case lpDDMMSS:
-    iDegrees = (int) dDataToFormat;
-    dDataToFormat = fabs( dDataToFormat - (double) iDegrees );    
-    iMinutes = (int) (dDataToFormat * 60.0);
-    dDataToFormat = dDataToFormat - (((double) iMinutes) / 60.0);    
-    sprintf( cBuffer, pInfo->labelformat, iDegrees, iMinutes, (int) (dDataToFormat * 3600.0) );
-    break;
-  case lpDDMM:
-    iDegrees = (int) dDataToFormat;
-    dDataToFormat = fabs( dDataToFormat - (double) iDegrees );    
-    sprintf( cBuffer, pInfo->labelformat, iDegrees, (int) (dDataToFormat * 60.0) );
-    break;
-  case lpDD:
-    iDegrees = (int) dDataToFormat;
-    sprintf( cBuffer, pInfo->labelformat, iDegrees);
-    break;  
-  case lpDefault:
-  default:
-    sprintf( cBuffer, pInfo->labelformat, dDataToFormat );
+    case lpDDMMSS:
+      iDegrees = (int) dDataToFormat;
+      dDataToFormat = fabs( dDataToFormat - (double) iDegrees );
+      iMinutes = (int) (dDataToFormat * 60.0);
+      dDataToFormat = dDataToFormat - (((double) iMinutes) / 60.0);
+      sprintf( cBuffer, pInfo->labelformat, iDegrees, iMinutes, (int) (dDataToFormat * 3600.0) );
+      break;
+    case lpDDMM:
+      iDegrees = (int) dDataToFormat;
+      dDataToFormat = fabs( dDataToFormat - (double) iDegrees );
+      sprintf( cBuffer, pInfo->labelformat, iDegrees, (int) (dDataToFormat * 60.0) );
+      break;
+    case lpDD:
+      iDegrees = (int) dDataToFormat;
+      sprintf( cBuffer, pInfo->labelformat, iDegrees);
+      break;
+    case lpDefault:
+    default:
+      sprintf( cBuffer, pInfo->labelformat, dDataToFormat );
   }
-   
+
   pShape->text = msStrdup( cBuffer );
 }
 
@@ -1083,16 +1044,16 @@ static int _AdjustLabelPosition( layerObj *pLayer, shapeObj *pShape, msGraticule
   graticuleObj *pInfo = (graticuleObj  *) pLayer->layerinfo;
   rectObj rectLabel;
   pointObj ptPoint;
-  double size = pLayer->class[0]->label.size; //TODO TBT: adjust minsize/maxsize/resolution
+  double size = -1;
 
   if( pInfo == NULL || pShape == NULL ) {
     msSetError(MS_MISCERR, "Assertion failed: Null shape or layerinfo!, ", "_AdjustLabelPosition()");
     return MS_FAILURE;
   }
- 
+
   if(msCheckParentPointer(pLayer->map,"map")==MS_FAILURE)
     return MS_FAILURE;
-   
+
   ptPoint = pShape->line->point[0];
 
 #ifdef USE_PROJ
@@ -1101,50 +1062,51 @@ static int _AdjustLabelPosition( layerObj *pLayer, shapeObj *pShape, msGraticule
 #endif
 
   if(pLayer->transform) {
-     msTransformShapeToPixelRound(pShape, pLayer->map->extent, pLayer->map->cellsize);
+    msTransformShapeToPixelRound(pShape, pLayer->map->extent, pLayer->map->cellsize);
   }
 
-  if(msGetLabelSize(pLayer->map, &pLayer->class[0]->label,pShape->text, size,&rectLabel,NULL) != MS_SUCCESS)
-	  return MS_FAILURE;  /* msSetError already called */
+  size = pLayer->class[0]->labels[0]->size; /* TODO TBT: adjust minsize/maxsize/resolution. TODO RFC 77: ok to use first label? */
+  if(msGetLabelSize(pLayer->map, pLayer->class[0]->labels[0], pShape->text, size, &rectLabel, NULL) != MS_SUCCESS)
+    return MS_FAILURE;  /* msSetError already called */
 
   switch( ePosition ) {
-  case posBottom:
-    pShape->line->point[1].y = pLayer->map->height;
-    pShape->line->point[0].y = pLayer->map->height - (fabs(rectLabel.maxy - rectLabel.miny) * 2 + 5);
-    break;
-  case posTop:
-    pShape->line->point[1].y = 0;
-    pShape->line->point[0].y = fabs(rectLabel.maxy - rectLabel.miny) * 2 + 5;
-    break;
-  case posLeft:
-    pShape->line->point[1].x = 0;
-    pShape->line->point[0].x = fabs(rectLabel.maxx - rectLabel.minx) * 2 + 5;
-    break;
-  case posRight:
-    pShape->line->point[1].x = pLayer->map->width;
-    pShape->line->point[0].x = pLayer->map->width - (fabs(rectLabel.maxx - rectLabel.minx) * 2 + 5);
-    break;
+    case posBottom:
+      pShape->line->point[1].y = pLayer->map->height;
+      pShape->line->point[0].y = pLayer->map->height - (fabs(rectLabel.maxy - rectLabel.miny) * 2 + 5);
+      break;
+    case posTop:
+      pShape->line->point[1].y = 0;
+      pShape->line->point[0].y = fabs(rectLabel.maxy - rectLabel.miny) * 2 + 5;
+      break;
+    case posLeft:
+      pShape->line->point[1].x = 0;
+      pShape->line->point[0].x = fabs(rectLabel.maxx - rectLabel.minx) * 2 + 5;
+      break;
+    case posRight:
+      pShape->line->point[1].x = pLayer->map->width;
+      pShape->line->point[0].x = pLayer->map->width - (fabs(rectLabel.maxx - rectLabel.minx) * 2 + 5);
+      break;
   }
 
-  if(pLayer->transform) 
+  if(pLayer->transform)
     msTransformPixelToShape( pShape, pLayer->map->extent, pLayer->map->cellsize );
-   
+
 #ifdef USE_PROJ
   if(pLayer->project && msProjectionsDiffer( &pLayer->map->projection, &pLayer->projection ))
     msProjectShape( &pLayer->map->projection, &pLayer->projection, pShape );
 #endif
 
   switch( ePosition ) {
-  case posBottom:
-  case posTop:
-    pShape->line->point[1].x = ptPoint.x;
-    pShape->line->point[0].x = ptPoint.x;
-    break;
-  case posLeft:
-  case posRight:
-    pShape->line->point[1].y = ptPoint.y;
-    pShape->line->point[0].y = ptPoint.y;
-    break;
+    case posBottom:
+    case posTop:
+      pShape->line->point[1].x = ptPoint.x;
+      pShape->line->point[0].x = ptPoint.x;
+      break;
+    case posLeft:
+    case posRight:
+      pShape->line->point[1].y = ptPoint.y;
+      pShape->line->point[0].y = ptPoint.y;
+      break;
   }
 
   return MS_SUCCESS;
@@ -1179,7 +1141,7 @@ void DefineAxis( int iTickCountTarget, double *Min, double *Max, double *Inc )
 
   /* handle special case of repeated values */
 
-  else if( Range == 0)  {   
+  else if( Range == 0)  {
     *Min = ceil(*Max) - 1 ;
     *Max = *Min + 1 ;
     *Inc = 1 ;
@@ -1190,52 +1152,52 @@ void DefineAxis( int iTickCountTarget, double *Min, double *Max, double *Inc )
 
   Test_inc = pow( 10.0, ceil( log10( Range/10 ) ) ) ;
   if(*Inc > 0 && ( Test_inc < *Inc || Test_inc > *Inc ))
-     Test_inc = *Inc;
+    Test_inc = *Inc;
 
-   /* establish maximum scale value... */
-   Test_max = ( (long)(*Max / Test_inc)) * Test_inc ;
+  /* establish maximum scale value... */
+  Test_max = ( (long)(*Max / Test_inc)) * Test_inc ;
 
-   if( Test_max < *Max )
-      Test_max += Test_inc ;
+  if( Test_max < *Max )
+    Test_max += Test_inc ;
 
-   /* establish minimum scale value... */
-   Test_min = Test_max ;
-   do {
-     ++i ;
-     Test_min -= Test_inc ;
-   } while( Test_min > *Min ) ;
+  /* establish minimum scale value... */
+  Test_min = Test_max ;
+  do {
+    ++i ;
+    Test_min -= Test_inc ;
+  } while( Test_min > *Min ) ;
 
-   /* subtracting small values can screw up the scale limits, */
-   /* eg: if DefineAxis is called with (min,max)=(0.01, 0.1), */
-   /* then the calculated scale is 1.0408E17 TO 0.05 BY 0.01. */
-   /* the following if statment corrects for this... */
+  /* subtracting small values can screw up the scale limits, */
+  /* eg: if DefineAxis is called with (min,max)=(0.01, 0.1), */
+  /* then the calculated scale is 1.0408E17 TO 0.05 BY 0.01. */
+  /* the following if statment corrects for this... */
 
-   /* if(fabs(Test_min) < 1E-10) */
-   /* Test_min = 0 ; */
+  /* if(fabs(Test_min) < 1E-10) */
+  /* Test_min = 0 ; */
 
-   /* adjust for too few tick marks */
+  /* adjust for too few tick marks */
 
-   if(iTickCountTarget <= 0)
-     iTickCountTarget   = MAPGRATICULE_ARC_MINIMUM;
+  if(iTickCountTarget <= 0)
+    iTickCountTarget   = MAPGRATICULE_ARC_MINIMUM;
 
-   while(i < iTickCountTarget) {
-     Test_inc /= 2 ;
-     i *= 2 ;
-   }
+  while(i < iTickCountTarget) {
+    Test_inc /= 2 ;
+    i *= 2 ;
+  }
 
-   if(i < 6 && 0) {
-     Test_inc /= 2 ;
-     if((Test_min + Test_inc) <= *Min)
-       Test_min += Test_inc ;
-     if((Test_max - Test_inc) >= *Max)
-       Test_max -= Test_inc ;
-   }
+  if(i < 6 && 0) {
+    Test_inc /= 2 ;
+    if((Test_min + Test_inc) <= *Min)
+      Test_min += Test_inc ;
+    if((Test_max - Test_inc) >= *Max)
+      Test_max -= Test_inc ;
+  }
 
-   /* pass back axis definition to caller */
+  /* pass back axis definition to caller */
 
-   *Min = Test_min;
-   *Max = Test_max;
-   *Inc = Test_inc;
+  *Min = Test_min;
+  *Max = Test_max;
+  *Inc = Test_inc;
 }
 
 /**********************************************************************************************************************
diff --git a/maphash.c b/maphash.c
index 26ccf8f..d6dd3e0 100644
--- a/maphash.c
+++ b/maphash.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -32,226 +32,223 @@
 #include "mapserver.h"
 #include "maphash.h"
 
-MS_CVSID("$Id$")
+
 
 static unsigned hash(const char *key)
 {
   unsigned hashval;
-  
+
   for(hashval=0; *key!='\0'; key++)
     hashval = tolower(*key) + 31 * hashval;
 
   return(hashval % MS_HASHSIZE);
 }
 
-hashTableObj *msCreateHashTable() 
+hashTableObj *msCreateHashTable()
 {
-    int i;
-    hashTableObj *table;
-    
-    table = (hashTableObj *) msSmallMalloc(sizeof(hashTableObj));
-    table->items = (struct hashObj **) msSmallMalloc(sizeof(struct hashObj *)*MS_HASHSIZE);
-    
-    for (i=0; i<MS_HASHSIZE; i++)
-        table->items[i] = NULL;
-    table->numitems = 0;
-    
-    return table;
+  int i;
+  hashTableObj *table;
+
+  table = (hashTableObj *) msSmallMalloc(sizeof(hashTableObj));
+  table->items = (struct hashObj **) msSmallMalloc(sizeof(struct hashObj *)*MS_HASHSIZE);
+
+  for (i=0; i<MS_HASHSIZE; i++)
+    table->items[i] = NULL;
+  table->numitems = 0;
+
+  return table;
 }
 
-int initHashTable( hashTableObj *table ) 
+int initHashTable( hashTableObj *table )
 {
-    int i;
+  int i;
 
-    table->items = (struct hashObj **) malloc(sizeof(struct hashObj *)*MS_HASHSIZE);
-    MS_CHECK_ALLOC(table->items, sizeof(struct hashObj *)*MS_HASHSIZE, MS_FAILURE);
+  table->items = (struct hashObj **) malloc(sizeof(struct hashObj *)*MS_HASHSIZE);
+  MS_CHECK_ALLOC(table->items, sizeof(struct hashObj *)*MS_HASHSIZE, MS_FAILURE);
 
-    for (i=0; i<MS_HASHSIZE; i++)
-        table->items[i] = NULL;
-    table->numitems = 0;
-    return MS_SUCCESS;
+  for (i=0; i<MS_HASHSIZE; i++)
+    table->items[i] = NULL;
+  table->numitems = 0;
+  return MS_SUCCESS;
 }
 
 void msFreeHashTable( hashTableObj *table )
 {
-    if( table != NULL )
-    {
-        msFreeHashItems(table);
-        free(table);
-        table = NULL;
-    }
+  if( table != NULL ) {
+    msFreeHashItems(table);
+    free(table);
+    table = NULL;
+  }
 }
 
 int msHashIsEmpty( hashTableObj *table )
 {
-    if (table->numitems == 0 )
-        return MS_TRUE;
-    else
-        return MS_FALSE;
+  if (table->numitems == 0 )
+    return MS_TRUE;
+  else
+    return MS_FALSE;
 }
 
 
 void msFreeHashItems( hashTableObj *table )
 {
-    int i;
-    struct hashObj *tp=NULL;
-    struct hashObj *prev_tp=NULL;
-    
-    if (table) {
-        if(table->items) {
-            for (i=0; i<MS_HASHSIZE; i++) {
-                if (table->items[i] != NULL) {
-                    for (tp=table->items[i]; tp!=NULL; prev_tp=tp,tp=tp->next,free(prev_tp)) {
-                      msFree(tp->key);
-                      msFree(tp->data);
-                    }
-                }
-                if (tp) free(tp);
-            }
-            free(table->items);
-            table->items = NULL;
-        } else {
-          msSetError(MS_HASHERR, "No items allocated.", "msFreeHashItems()");
+  int i;
+  struct hashObj *tp=NULL;
+  struct hashObj *prev_tp=NULL;
+
+  if (table) {
+    if(table->items) {
+      for (i=0; i<MS_HASHSIZE; i++) {
+        if (table->items[i] != NULL) {
+          for (tp=table->items[i]; tp!=NULL; prev_tp=tp,tp=tp->next,free(prev_tp)) {
+            msFree(tp->key);
+            msFree(tp->data);
+          }
         }
+        if (tp) free(tp);
+      }
+      free(table->items);
+      table->items = NULL;
     } else {
-        msSetError(MS_HASHERR, "Can't free NULL table", "msFreeHashItems()");
+      msSetError(MS_HASHERR, "No items allocated.", "msFreeHashItems()");
     }
+  } else {
+    msSetError(MS_HASHERR, "Can't free NULL table", "msFreeHashItems()");
+  }
 }
 
-struct hashObj *msInsertHashTable(hashTableObj *table, 
-                                  const char *key, const char *value)
-{
-    struct hashObj *tp;
-    unsigned hashval;
-
-    if (!table || !key || !value) {
-        msSetError(MS_HASHERR, "Invalid hash table or key",
-                               "msInsertHashTable");
-        return NULL;
-    }
-
-    for (tp=table->items[hash(key)]; tp!=NULL; tp=tp->next)
-        if(strcasecmp(key, tp->key) == 0)
-            break;
-
-    if (tp == NULL) { /* not found */
-        tp = (struct hashObj *) malloc(sizeof(*tp));
-        MS_CHECK_ALLOC(tp, sizeof(*tp), NULL);
-        tp->key = msStrdup(key);
-        hashval = hash(key);
-        tp->next = table->items[hashval];
-        table->items[hashval] = tp;
-        table->numitems++;
-    } else {
-        free(tp->data);
-    }
+struct hashObj *msInsertHashTable(hashTableObj *table,
+                                  const char *key, const char *value) {
+  struct hashObj *tp;
+  unsigned hashval;
 
-    if ((tp->data = msStrdup(value)) == NULL)
-        return NULL;
+  if (!table || !key || !value) {
+    msSetError(MS_HASHERR, "Invalid hash table or key",
+               "msInsertHashTable");
+    return NULL;
+  }
+
+  for (tp=table->items[hash(key)]; tp!=NULL; tp=tp->next)
+    if(strcasecmp(key, tp->key) == 0)
+      break;
+
+  if (tp == NULL) { /* not found */
+    tp = (struct hashObj *) malloc(sizeof(*tp));
+    MS_CHECK_ALLOC(tp, sizeof(*tp), NULL);
+    tp->key = msStrdup(key);
+    hashval = hash(key);
+    tp->next = table->items[hashval];
+    table->items[hashval] = tp;
+    table->numitems++;
+  } else {
+    free(tp->data);
+  }
+
+  if ((tp->data = msStrdup(value)) == NULL)
+    return NULL;
 
-    return tp;
+  return tp;
 }
 
 char *msLookupHashTable(hashTableObj *table, const char *key)
 {
-    struct hashObj *tp;
+  struct hashObj *tp;
 
-    if (!table || !key) {
-        return(NULL);
-    }
+  if (!table || !key) {
+    return(NULL);
+  }
 
-    for (tp=table->items[hash(key)]; tp!=NULL; tp=tp->next)
-        if (strcasecmp(key, tp->key) == 0)
-            return(tp->data);
+  for (tp=table->items[hash(key)]; tp!=NULL; tp=tp->next)
+    if (strcasecmp(key, tp->key) == 0)
+      return(tp->data);
 
-    return NULL;
+  return NULL;
 }
 
 int msRemoveHashTable(hashTableObj *table, const char *key)
-{ 
-    struct hashObj *tp;
-    struct hashObj *prev_tp=NULL;
-    int status = MS_FAILURE;
-
-    if (!table || !key) {
-        msSetError(MS_HASHERR, "No hash table", "msRemoveHashTable");
-        return MS_FAILURE;
-    }
-  
-    tp=table->items[hash(key)];
-    if (!tp) {
-        msSetError(MS_HASHERR, "No such hash entry", "msRemoveHashTable");
-        return MS_FAILURE;
-    }
-
-    prev_tp = NULL;
-    while (tp != NULL) {
-        if (strcasecmp(key, tp->key) == 0) {
-            status = MS_SUCCESS;
-            if (prev_tp) {     
-                prev_tp->next = tp->next;
-                free(tp);
-                break;
-            }
-            else {
-                table->items[hash(key)] = tp->next;
-                free(tp);
-                break;
-            }
-        }
-        prev_tp = tp;
-        tp = tp->next;
+{
+  struct hashObj *tp;
+  struct hashObj *prev_tp=NULL;
+  int status = MS_FAILURE;
+
+  if (!table || !key) {
+    msSetError(MS_HASHERR, "No hash table", "msRemoveHashTable");
+    return MS_FAILURE;
+  }
+
+  tp=table->items[hash(key)];
+  if (!tp) {
+    msSetError(MS_HASHERR, "No such hash entry", "msRemoveHashTable");
+    return MS_FAILURE;
+  }
+
+  prev_tp = NULL;
+  while (tp != NULL) {
+    if (strcasecmp(key, tp->key) == 0) {
+      status = MS_SUCCESS;
+      if (prev_tp) {
+        prev_tp->next = tp->next;
+        free(tp);
+        break;
+      } else {
+        table->items[hash(key)] = tp->next;
+        free(tp);
+        break;
+      }
     }
+    prev_tp = tp;
+    tp = tp->next;
+  }
 
-    if (status == MS_SUCCESS)
-        table->numitems--;
+  if (status == MS_SUCCESS)
+    table->numitems--;
 
-    return status;
+  return status;
 }
-      
+
 const char *msFirstKeyFromHashTable( hashTableObj *table )
 {
-    int hash_index;
-    
-    if (!table) {
-        msSetError(MS_HASHERR, "No hash table", "msFirstKeyFromHashTable");
-        return NULL;
-    }
-    
-    for (hash_index = 0; hash_index < MS_HASHSIZE; hash_index++ ) {
-        if (table->items[hash_index] != NULL )
-            return table->items[hash_index]->key;
-    }
+  int hash_index;
 
+  if (!table) {
+    msSetError(MS_HASHERR, "No hash table", "msFirstKeyFromHashTable");
     return NULL;
+  }
+
+  for (hash_index = 0; hash_index < MS_HASHSIZE; hash_index++ ) {
+    if (table->items[hash_index] != NULL )
+      return table->items[hash_index]->key;
+  }
+
+  return NULL;
 }
 
 const char *msNextKeyFromHashTable( hashTableObj *table, const char *lastKey )
 {
-    int hash_index;
-    struct hashObj *link;
-
-    if (!table) {
-        msSetError(MS_HASHERR, "No hash table", "msNextKeyFromHashTable");
-        return NULL;
-    }
-    
-    if ( lastKey == NULL )
-        return msFirstKeyFromHashTable( table );
-
-    hash_index = hash(lastKey);
-    for ( link = table->items[hash_index]; 
-         link != NULL && strcasecmp(lastKey,link->key) != 0;
-         link = link->next ) {}
-    
-    if ( link != NULL && link->next != NULL )
-        return link->next->key;
-
-    while ( ++hash_index < MS_HASHSIZE ) {
-        if ( table->items[hash_index] != NULL )
-            return table->items[hash_index]->key;
-    }
+  int hash_index;
+  struct hashObj *link;
 
+  if (!table) {
+    msSetError(MS_HASHERR, "No hash table", "msNextKeyFromHashTable");
     return NULL;
+  }
+
+  if ( lastKey == NULL )
+    return msFirstKeyFromHashTable( table );
+
+  hash_index = hash(lastKey);
+  for ( link = table->items[hash_index];
+        link != NULL && strcasecmp(lastKey,link->key) != 0;
+        link = link->next ) {}
+
+  if ( link != NULL && link->next != NULL )
+    return link->next->key;
+
+  while ( ++hash_index < MS_HASHSIZE ) {
+    if ( table->items[hash_index] != NULL )
+      return table->items[hash_index]->key;
+  }
+
+  return NULL;
 }
 
diff --git a/maphash.h b/maphash.h
index 5efc4d2..bd85aed 100644
--- a/maphash.h
+++ b/maphash.h
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -42,117 +42,117 @@ extern "C" {
 
 #define MS_HASHSIZE 41
 
-/* =========================================================================
- * Structs
- * ========================================================================= */
+  /* =========================================================================
+   * Structs
+   * ========================================================================= */
 
 #ifndef SWIG
-struct hashObj {
+  struct hashObj {
     struct hashObj *next;  /* pointer to next item */
     char           *key;   /* string key that is hashed */
-    char           *data;  /* string stored in this item */ 
-};
+    char           *data;  /* string stored in this item */
+  };
 #endif /*SWIG*/
 
-typedef struct {
+  typedef struct {
 #ifndef SWIG
     struct hashObj **items;  /* the hash table */
 #endif
 #ifdef SWIG
-%immutable;
+    %immutable;
 #endif /*SWIG*/
     int              numitems;  /* number of items */
 #ifdef SWIG
-	%mutable;
+    %mutable;
 #endif /*SWIG*/
-} hashTableObj;
+  } hashTableObj;
 
-/* =========================================================================
- * Functions
- * ========================================================================= */
+  /* =========================================================================
+   * Functions
+   * ========================================================================= */
 
 #ifndef SWIG
-/* msCreateHashTable - create a hash table
- * ARGS:
- *     None
- * RETURNS:
- *     New hash table
- */
-MS_DLL_EXPORT hashTableObj *msCreateHashTable( void );
-
-/* For use in mapfile.c with hashTableObj structure members */
-MS_DLL_EXPORT int initHashTable( hashTableObj *table );
-
-/* msFreeHashTable - free allocated memory
- * ARGS:
- *     table - target hash table
- * RETURNS:
- *     None
- */
-MS_DLL_EXPORT void msFreeHashTable( hashTableObj *table );
-
-/* Free only the items for hashTableObj structure members (metadata, &c) */
-MS_DLL_EXPORT void msFreeHashItems( hashTableObj *table );
-
-/* msInsertHashTable - insert new item
- * ARGS:
- *     table - the target hash table
- *     key   - key string for new item
- *     value - data string for new item
- * RETURNS:
- *     pointer to the new item or NULL
- * EXCEPTIONS:
- *     raise MS_HASHERR on failure
- */
-MS_DLL_EXPORT struct hashObj *msInsertHashTable( hashTableObj *table,
-                                                 const char *key,
-                                                 const char *value );
-
-/* msLookupHashTable - get the value of an item by its key
- * ARGS:
- *     table - the target hash table
- *     key   - key string of item
- * RETURNS:
- *     string value of item
- */
-MS_DLL_EXPORT char *msLookupHashTable( hashTableObj *table, const char *key);
-
-/* msRemoveHashTable - remove item from table at key
- * ARGS:
- *     table - target hash table
- *     key   - key string
- * RETURNS:
- *     MS_SUCCESS or MS_FAILURE
- */
-MS_DLL_EXPORT int msRemoveHashTable( hashTableObj *table, const char *key);
-
-/* msFirstKeyFromHashTable - get key of first item
- * ARGS:
- *     table - target hash table
- * RETURNS:
- *     first key as a string
- */
-MS_DLL_EXPORT const char *msFirstKeyFromHashTable( hashTableObj *table );
-
-/* msNextKeyFromHashTable - get next key
- * ARGS:
- *     table - target hash table
- *     prevkey - the previous key
- * RETURNS:
- *     the key of the item of following prevkey as a string
- */
-MS_DLL_EXPORT const char *msNextKeyFromHashTable( hashTableObj *table,
-                                                  const char *prevkey );
-
-/* msHashIsEmpty - get next key
- * ARGS:
- *     table - target hash table
- * RETURNS:
- *     MS_TRUE if the table is empty and MS_FALSE if the table has items
- */
-
-MS_DLL_EXPORT int msHashIsEmpty( hashTableObj* table );
- 
+  /* msCreateHashTable - create a hash table
+   * ARGS:
+   *     None
+   * RETURNS:
+   *     New hash table
+   */
+  MS_DLL_EXPORT hashTableObj *msCreateHashTable( void );
+
+  /* For use in mapfile.c with hashTableObj structure members */
+  MS_DLL_EXPORT int initHashTable( hashTableObj *table );
+
+  /* msFreeHashTable - free allocated memory
+   * ARGS:
+   *     table - target hash table
+   * RETURNS:
+   *     None
+   */
+  MS_DLL_EXPORT void msFreeHashTable( hashTableObj *table );
+
+  /* Free only the items for hashTableObj structure members (metadata, &c) */
+  MS_DLL_EXPORT void msFreeHashItems( hashTableObj *table );
+
+  /* msInsertHashTable - insert new item
+   * ARGS:
+   *     table - the target hash table
+   *     key   - key string for new item
+   *     value - data string for new item
+   * RETURNS:
+   *     pointer to the new item or NULL
+   * EXCEPTIONS:
+   *     raise MS_HASHERR on failure
+   */
+  MS_DLL_EXPORT struct hashObj *msInsertHashTable( hashTableObj *table,
+      const char *key,
+      const char *value );
+
+  /* msLookupHashTable - get the value of an item by its key
+   * ARGS:
+   *     table - the target hash table
+   *     key   - key string of item
+   * RETURNS:
+   *     string value of item
+   */
+  MS_DLL_EXPORT char *msLookupHashTable( hashTableObj *table, const char *key);
+
+  /* msRemoveHashTable - remove item from table at key
+   * ARGS:
+   *     table - target hash table
+   *     key   - key string
+   * RETURNS:
+   *     MS_SUCCESS or MS_FAILURE
+   */
+  MS_DLL_EXPORT int msRemoveHashTable( hashTableObj *table, const char *key);
+
+  /* msFirstKeyFromHashTable - get key of first item
+   * ARGS:
+   *     table - target hash table
+   * RETURNS:
+   *     first key as a string
+   */
+  MS_DLL_EXPORT const char *msFirstKeyFromHashTable( hashTableObj *table );
+
+  /* msNextKeyFromHashTable - get next key
+   * ARGS:
+   *     table - target hash table
+   *     prevkey - the previous key
+   * RETURNS:
+   *     the key of the item of following prevkey as a string
+   */
+  MS_DLL_EXPORT const char *msNextKeyFromHashTable( hashTableObj *table,
+      const char *prevkey );
+
+  /* msHashIsEmpty - get next key
+   * ARGS:
+   *     table - target hash table
+   * RETURNS:
+   *     MS_TRUE if the table is empty and MS_FALSE if the table has items
+   */
+
+  MS_DLL_EXPORT int msHashIsEmpty( hashTableObj* table );
+
 #endif /*SWIG*/
 
 #ifdef __cplusplus
diff --git a/maphttp.c b/maphttp.c
index 9a383fc..c8bd608 100644
--- a/maphttp.c
+++ b/maphttp.c
@@ -14,16 +14,16 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
+ *
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  ****************************************************************************/
 
 /* For now this code is enabled only when WMS/WFS client is enabled.
@@ -37,7 +37,7 @@
 #include "maperror.h"
 #include "mapthread.h"
 
-MS_CVSID("$Id$")
+
 
 #include <time.h>
 #ifndef _WIN32
@@ -48,7 +48,7 @@ MS_CVSID("$Id$")
 
 /*
  * Note: This code uses libcurl to access remote files via the HTTP protocol.
- * Requires libcurl v 7.10 or more recent.  
+ * Requires libcurl v 7.10 or more recent.
  * See http://curl.haxx.se/libcurl/c/ for the lib source code and docs.
  */
 #include <curl/curl.h>
@@ -57,7 +57,7 @@ MS_CVSID("$Id$")
  *                          msHTTPInit()
  *
  * This function is called to init libcurl before the first HTTP request
- * in this process is executed.  
+ * in this process is executed.
  * On further calls (when gbCurlInitialized = MS_TRUE) it simply doest nothing.
  *
  * Returns MS_SUCCESS/MS_FAILURE.
@@ -69,25 +69,24 @@ static int gbCurlInitialized = MS_FALSE;
 
 int msHTTPInit()
 {
-    /* curl_global_init() should only be called once (no matter how
-     * many threads or libcurl sessions that'll be used) by every
-     * application that uses libcurl.
-     */
-     
-    msAcquireLock(TLOCK_OWS);
-    if (!gbCurlInitialized && 
-        curl_global_init(CURL_GLOBAL_ALL) != 0)
-    {
-        msReleaseLock(TLOCK_OWS);
-        msSetError(MS_HTTPERR, "Libcurl initialization failed.", 
-                   "msHTTPInit()");
-        return MS_FAILURE;
-    }
+  /* curl_global_init() should only be called once (no matter how
+   * many threads or libcurl sessions that'll be used) by every
+   * application that uses libcurl.
+   */
+
+  msAcquireLock(TLOCK_OWS);
+  if (!gbCurlInitialized &&
+      curl_global_init(CURL_GLOBAL_ALL) != 0) {
+    msReleaseLock(TLOCK_OWS);
+    msSetError(MS_HTTPERR, "Libcurl initialization failed.",
+               "msHTTPInit()");
+    return MS_FAILURE;
+  }
 
-    gbCurlInitialized = MS_TRUE;
+  gbCurlInitialized = MS_TRUE;
 
-    msReleaseLock(TLOCK_OWS);
-    return MS_SUCCESS;
+  msReleaseLock(TLOCK_OWS);
+  return MS_SUCCESS;
 }
 
 
@@ -97,12 +96,12 @@ int msHTTPInit()
  **********************************************************************/
 void msHTTPCleanup()
 {
-    msAcquireLock(TLOCK_OWS);
-    if (gbCurlInitialized)
-        curl_global_cleanup();
-        
-    gbCurlInitialized = MS_FALSE;
-    msReleaseLock(TLOCK_OWS);
+  msAcquireLock(TLOCK_OWS);
+  if (gbCurlInitialized)
+    curl_global_cleanup();
+
+  gbCurlInitialized = MS_FALSE;
+  msReleaseLock(TLOCK_OWS);
 }
 
 
@@ -113,42 +112,41 @@ void msHTTPCleanup()
  * for use with msHTTPExecuteRequest(), etc.
  *
  * Note that users of this module should always allocate and init one
- * more instance of httpRequestObj in their array than what they plan to 
- * use because the terminate_handler() needs the last entry in the array 
+ * more instance of httpRequestObj in their array than what they plan to
+ * use because the terminate_handler() needs the last entry in the array
  * to have reqObj->request == NULL
  *
  **********************************************************************/
-void msHTTPInitRequestObj(httpRequestObj *pasReqInfo, int numRequests) 
+void msHTTPInitRequestObj(httpRequestObj *pasReqInfo, int numRequests)
 {
-    int i;
-
-    for(i=0; i<numRequests; i++)
-    {
-        pasReqInfo[i].pszGetUrl = NULL;
-        pasReqInfo[i].pszPostRequest = NULL;
-        pasReqInfo[i].pszPostContentType = NULL;
-        pasReqInfo[i].pszOutputFile = NULL;
-        pasReqInfo[i].nLayerId = 0;
-        pasReqInfo[i].nTimeout = 0;
-        pasReqInfo[i].nStatus = 0;
-        pasReqInfo[i].pszContentType = NULL;
-        pasReqInfo[i].pszErrBuf = NULL;
-        pasReqInfo[i].pszUserAgent = NULL;
-        pasReqInfo[i].pszHTTPCookieData = NULL;
-        pasReqInfo[i].pszProxyAddress = NULL;
-        pasReqInfo[i].pszProxyUsername = NULL;
-        pasReqInfo[i].pszProxyPassword = NULL;
-        pasReqInfo[i].pszHttpUsername = NULL;
-        pasReqInfo[i].pszHttpPassword = NULL;
-
-        pasReqInfo[i].debug = MS_FALSE;
-
-        pasReqInfo[i].curl_handle = NULL;
-        pasReqInfo[i].fp = NULL;
-        pasReqInfo[i].result_data = NULL;
-        pasReqInfo[i].result_size = 0;
-        pasReqInfo[i].result_buf_size = 0;
-    }
+  int i;
+
+  for(i=0; i<numRequests; i++) {
+    pasReqInfo[i].pszGetUrl = NULL;
+    pasReqInfo[i].pszPostRequest = NULL;
+    pasReqInfo[i].pszPostContentType = NULL;
+    pasReqInfo[i].pszOutputFile = NULL;
+    pasReqInfo[i].nLayerId = 0;
+    pasReqInfo[i].nTimeout = 0;
+    pasReqInfo[i].nStatus = 0;
+    pasReqInfo[i].pszContentType = NULL;
+    pasReqInfo[i].pszErrBuf = NULL;
+    pasReqInfo[i].pszUserAgent = NULL;
+    pasReqInfo[i].pszHTTPCookieData = NULL;
+    pasReqInfo[i].pszProxyAddress = NULL;
+    pasReqInfo[i].pszProxyUsername = NULL;
+    pasReqInfo[i].pszProxyPassword = NULL;
+    pasReqInfo[i].pszHttpUsername = NULL;
+    pasReqInfo[i].pszHttpPassword = NULL;
+
+    pasReqInfo[i].debug = MS_FALSE;
+
+    pasReqInfo[i].curl_handle = NULL;
+    pasReqInfo[i].fp = NULL;
+    pasReqInfo[i].result_data = NULL;
+    pasReqInfo[i].result_size = 0;
+    pasReqInfo[i].result_buf_size = 0;
+  }
 }
 
 
@@ -156,50 +154,49 @@ void msHTTPInitRequestObj(httpRequestObj *pasReqInfo, int numRequests)
  *                          msHTTPFreeRequestObj()
  *
  **********************************************************************/
-void msHTTPFreeRequestObj(httpRequestObj *pasReqInfo, int numRequests) 
+void msHTTPFreeRequestObj(httpRequestObj *pasReqInfo, int numRequests)
 {
-    int i;
-    for(i=0; i<numRequests; i++)
-    {
-        if (pasReqInfo[i].pszGetUrl)
-            free(pasReqInfo[i].pszGetUrl);
-        pasReqInfo[i].pszGetUrl = NULL;
-
-        if (pasReqInfo[i].pszPostRequest)
-          free(pasReqInfo[i].pszPostRequest);
-        pasReqInfo[i].pszPostRequest = NULL;
-
-        if (pasReqInfo[i].pszPostContentType)
-          free(pasReqInfo[i].pszPostContentType);
-        pasReqInfo[i].pszPostContentType = NULL;
-
-        if (pasReqInfo[i].pszOutputFile)
-            free(pasReqInfo[i].pszOutputFile);
-        pasReqInfo[i].pszOutputFile = NULL;
-
-        if (pasReqInfo[i].pszContentType)
-            free(pasReqInfo[i].pszContentType);
-        pasReqInfo[i].pszContentType = NULL;
-
-        if (pasReqInfo[i].pszErrBuf)
-            free(pasReqInfo[i].pszErrBuf);
-        pasReqInfo[i].pszErrBuf = NULL;
-
-        if (pasReqInfo[i].pszUserAgent)
-            free(pasReqInfo[i].pszUserAgent);
-        pasReqInfo[i].pszUserAgent = NULL;
-
-        if (pasReqInfo[i].pszHTTPCookieData)
-            free(pasReqInfo[i].pszHTTPCookieData);
-        pasReqInfo[i].pszHTTPCookieData = NULL;
-
-        pasReqInfo[i].curl_handle = NULL;
-
-        free( pasReqInfo[i].result_data );
-        pasReqInfo[i].result_data = NULL;
-        pasReqInfo[i].result_size = 0;
-        pasReqInfo[i].result_buf_size = 0;
-    }
+  int i;
+  for(i=0; i<numRequests; i++) {
+    if (pasReqInfo[i].pszGetUrl)
+      free(pasReqInfo[i].pszGetUrl);
+    pasReqInfo[i].pszGetUrl = NULL;
+
+    if (pasReqInfo[i].pszPostRequest)
+      free(pasReqInfo[i].pszPostRequest);
+    pasReqInfo[i].pszPostRequest = NULL;
+
+    if (pasReqInfo[i].pszPostContentType)
+      free(pasReqInfo[i].pszPostContentType);
+    pasReqInfo[i].pszPostContentType = NULL;
+
+    if (pasReqInfo[i].pszOutputFile)
+      free(pasReqInfo[i].pszOutputFile);
+    pasReqInfo[i].pszOutputFile = NULL;
+
+    if (pasReqInfo[i].pszContentType)
+      free(pasReqInfo[i].pszContentType);
+    pasReqInfo[i].pszContentType = NULL;
+
+    if (pasReqInfo[i].pszErrBuf)
+      free(pasReqInfo[i].pszErrBuf);
+    pasReqInfo[i].pszErrBuf = NULL;
+
+    if (pasReqInfo[i].pszUserAgent)
+      free(pasReqInfo[i].pszUserAgent);
+    pasReqInfo[i].pszUserAgent = NULL;
+
+    if (pasReqInfo[i].pszHTTPCookieData)
+      free(pasReqInfo[i].pszHTTPCookieData);
+    pasReqInfo[i].pszHTTPCookieData = NULL;
+
+    pasReqInfo[i].curl_handle = NULL;
+
+    free( pasReqInfo[i].result_data );
+    pasReqInfo[i].result_data = NULL;
+    pasReqInfo[i].result_size = 0;
+    pasReqInfo[i].result_buf_size = 0;
+  }
 }
 
 
@@ -208,62 +205,55 @@ void msHTTPFreeRequestObj(httpRequestObj *pasReqInfo, int numRequests)
  *
  * CURL_OPTWRITEFUNCTION, called to write blocks of data to the file we
  * are downloading.  Should return the number of bytes that were taken
- * care of.  If that  amount  differs  from  the  amount passed to it 
- * it'll signal an error to the library and it will abort the transfer 
+ * care of.  If that  amount  differs  from  the  amount passed to it
+ * it'll signal an error to the library and it will abort the transfer
  * and produce a CURLE_WRITE_ERROR.
  *
  **********************************************************************/
-static size_t msHTTPWriteFct(void *buffer, size_t size, size_t nmemb, 
+static size_t msHTTPWriteFct(void *buffer, size_t size, size_t nmemb,
                              void *reqInfo)
 {
-    httpRequestObj *psReq;
-
-    psReq = (httpRequestObj *)reqInfo;
-
-    if (psReq->debug)
-    {
-        msDebug("msHTTPWriteFct(id=%d, %d bytes)\n",
-                psReq->nLayerId, size*nmemb);
+  httpRequestObj *psReq;
+
+  psReq = (httpRequestObj *)reqInfo;
+
+  if (psReq->debug) {
+    msDebug("msHTTPWriteFct(id=%d, %d bytes)\n",
+            psReq->nLayerId, size*nmemb);
+  }
+
+  /* Case where we are writing to a disk file. */
+  if( psReq->fp != NULL ) {
+    return fwrite(buffer, size, nmemb, psReq->fp);
+  }
+
+  /* Case where we build up the result in memory */
+  else {
+    if( psReq->result_data == NULL ) {
+      psReq->result_buf_size = size*nmemb + 10000;
+      psReq->result_data = (char *) msSmallMalloc( psReq->result_buf_size );
+    } else if( psReq->result_size + nmemb * size > psReq->result_buf_size ) {
+      psReq->result_buf_size = psReq->result_size + nmemb*size + 10000;
+      psReq->result_data = (char *) msSmallRealloc( psReq->result_data,
+                           psReq->result_buf_size );
     }
 
-    /* Case where we are writing to a disk file. */
-    if( psReq->fp != NULL )
-    {
-        return fwrite(buffer, size, nmemb, psReq->fp);
+    if( psReq->result_data == NULL ) {
+      msSetError(MS_HTTPERR,
+                 "Unable to grow HTTP result buffer to size %d.",
+                 "msHTTPWriteFct()",
+                 psReq->result_buf_size );
+      psReq->result_buf_size = 0;
+      psReq->result_size = 0;
+      return -1;
     }
-    
-    /* Case where we build up the result in memory */
-    else
-    {
-        if( psReq->result_data == NULL )
-        {
-            psReq->result_buf_size = size*nmemb + 10000;
-            psReq->result_data = (char *) msSmallMalloc( psReq->result_buf_size );
-        }
-        else if( psReq->result_size + nmemb * size > psReq->result_buf_size )
-        {
-            psReq->result_buf_size = psReq->result_size + nmemb*size + 10000;
-            psReq->result_data = (char *) msSmallRealloc( psReq->result_data,
-                                                          psReq->result_buf_size );
-        }
 
-        if( psReq->result_data == NULL )
-        {
-            msSetError(MS_HTTPERR, 
-                       "Unable to grow HTTP result buffer to size %d.",
-                       "msHTTPWriteFct()",
-                       psReq->result_buf_size );
-            psReq->result_buf_size = 0;
-            psReq->result_size = 0;
-            return -1;
-        }
-        
-        memcpy( psReq->result_data + psReq->result_size,
-                buffer, size*nmemb );
-        psReq->result_size += size*nmemb;
+    memcpy( psReq->result_data + psReq->result_size,
+            buffer, size*nmemb );
+    psReq->result_size += size*nmemb;
 
-        return size*nmemb;
-    }
+    return size*nmemb;
+  }
 }
 
 /**********************************************************************
@@ -274,21 +264,20 @@ static size_t msHTTPWriteFct(void *buffer, size_t size, size_t nmemb,
  **********************************************************************/
 long msGetCURLAuthType(enum MS_HTTP_AUTH_TYPE authType)
 {
-    switch (authType)
-    {
-        case MS_BASIC:
-            return CURLAUTH_BASIC;
-        case MS_DIGEST:
-            return CURLAUTH_DIGEST;
-        case MS_NTLM:
-            return CURLAUTH_NTLM;
-        case MS_ANY:
-            return CURLAUTH_ANY;
-        case MS_ANYSAFE:
-            return CURLAUTH_ANYSAFE;
-        default:
-            return CURLAUTH_BASIC;    
-    }
+  switch (authType) {
+    case MS_BASIC:
+      return CURLAUTH_BASIC;
+    case MS_DIGEST:
+      return CURLAUTH_DIGEST;
+    case MS_NTLM:
+      return CURLAUTH_NTLM;
+    case MS_ANY:
+      return CURLAUTH_ANY;
+    case MS_ANYSAFE:
+      return CURLAUTH_ANYSAFE;
+    default:
+      return CURLAUTH_BASIC;
+  }
 }
 
 /**********************************************************************
@@ -296,7 +285,7 @@ long msGetCURLAuthType(enum MS_HTTP_AUTH_TYPE authType)
  *
  * Fetch a map slide via HTTP request and save to specified temp file.
  *
- * If bCheckLocalCache==MS_TRUE then if the pszOutputfile already exists 
+ * If bCheckLocalCache==MS_TRUE then if the pszOutputfile already exists
  * then is is not downloaded again, and status 242 is returned.
  *
  * Return value:
@@ -307,523 +296,481 @@ long msGetCURLAuthType(enum MS_HTTP_AUTH_TYPE authType)
 int msHTTPExecuteRequests(httpRequestObj *pasReqInfo, int numRequests,
                           int bCheckLocalCache)
 {
-    int     i, nStatus = MS_SUCCESS, nTimeout, still_running=0, num_msgs=0;
-    CURLM   *multi_handle;
-    CURLMsg *curl_msg;
-    char     debug = MS_FALSE;
-    const char *pszCurlCABundle = NULL;
-
-    if (numRequests == 0)
-        return MS_SUCCESS;  /* Nothing to do */
-
-    if (!gbCurlInitialized)
-        msHTTPInit();
-  
-    /* Establish the timeout (seconds) for how long we are going to wait 
-     * for a response. 
-     * We use the longest timeout value in the array of requests 
-     */
-    nTimeout = pasReqInfo[0].nTimeout;
-    for (i=0; i<numRequests; i++)
-    {
-        if (pasReqInfo[i].nTimeout > nTimeout)
-            nTimeout = pasReqInfo[i].nTimeout;
+  int     i, nStatus = MS_SUCCESS, nTimeout, still_running=0, num_msgs=0;
+  CURLM   *multi_handle;
+  CURLMsg *curl_msg;
+  char     debug = MS_FALSE;
+  const char *pszCurlCABundle = NULL;
+
+  if (numRequests == 0)
+    return MS_SUCCESS;  /* Nothing to do */
+
+  if (!gbCurlInitialized)
+    msHTTPInit();
+
+  /* Establish the timeout (seconds) for how long we are going to wait
+   * for a response.
+   * We use the longest timeout value in the array of requests
+   */
+  nTimeout = pasReqInfo[0].nTimeout;
+  for (i=0; i<numRequests; i++) {
+    if (pasReqInfo[i].nTimeout > nTimeout)
+      nTimeout = pasReqInfo[i].nTimeout;
+
+    if (pasReqInfo[i].debug)
+      debug = MS_TRUE;  /* For the download loop */
+  }
+
+  if (nTimeout <= 0)
+    nTimeout = 30;
+
+  /* Check if we've got a CURL_CA_BUNDLE env. var.
+   * If set then the value is the full path to the ca-bundle.crt file
+   * e.g. CURL_CA_BUNDLE=/usr/local/share/curl/curl-ca-bundle.crt
+   */
+  pszCurlCABundle = getenv("CURL_CA_BUNDLE");
+
+  if (debug) {
+    msDebug("HTTP: Starting to prepare HTTP requests.\n");
+    if (pszCurlCABundle)
+      msDebug("Using CURL_CA_BUNDLE=%s\n", pszCurlCABundle);
+  }
+
+  /* Alloc a curl-multi handle, and add a curl-easy handle to it for each
+   * file to download.
+   */
+  multi_handle = curl_multi_init();
+  if (multi_handle == NULL) {
+    msSetError(MS_HTTPERR, "curl_multi_init() failed.",
+               "msHTTPExecuteRequests()");
+    return(MS_FAILURE);
+  }
+
+  for (i=0; i<numRequests; i++) {
+    CURL *http_handle;
+    FILE *fp;
+
+    if (pasReqInfo[i].pszGetUrl == NULL ) {
+      msSetError(MS_HTTPERR, "URL or output file parameter missing.",
+                 "msHTTPExecuteRequests()");
+      return(MS_FAILURE);
+    }
+
+    if (pasReqInfo[i].debug) {
+      msDebug("HTTP request: id=%d, %s\n",
+              pasReqInfo[i].nLayerId, pasReqInfo[i].pszGetUrl);
+    }
 
+    /* Reset some members */
+    pasReqInfo[i].nStatus = 0;
+    if (pasReqInfo[i].pszContentType)
+      free(pasReqInfo[i].pszContentType);
+    pasReqInfo[i].pszContentType = NULL;
+
+    /* Check local cache if requested */
+    if (bCheckLocalCache && pasReqInfo[i].pszOutputFile != NULL ) {
+      fp = fopen(pasReqInfo[i].pszOutputFile, "r");
+      if (fp) {
+        /* File already there, don't download again. */
         if (pasReqInfo[i].debug)
-            debug = MS_TRUE;  /* For the download loop */
+          msDebug("HTTP request: id=%d, found in cache, skipping.\n",
+                  pasReqInfo[i].nLayerId);
+        fclose(fp);
+        pasReqInfo[i].nStatus = 242;
+        pasReqInfo[i].pszContentType = msStrdup("unknown/cached");
+        continue;
+      }
     }
 
-    if (nTimeout <= 0)
-        nTimeout = 30;
+    /* Alloc curl handle */
+    http_handle = curl_easy_init();
+    if (http_handle == NULL) {
+      msSetError(MS_HTTPERR, "curl_easy_init() failed.",
+                 "msHTTPExecuteRequests()");
+      return(MS_FAILURE);
+    }
 
-    /* Check if we've got a CURL_CA_BUNDLE env. var.
-     * If set then the value is the full path to the ca-bundle.crt file
-     * e.g. CURL_CA_BUNDLE=/usr/local/share/curl/curl-ca-bundle.crt
-     */
-    pszCurlCABundle = getenv("CURL_CA_BUNDLE");
+    pasReqInfo[i].curl_handle = http_handle;
 
-    if (debug)
-    {
-        msDebug("HTTP: Starting to prepare HTTP requests.\n");
-        if (pszCurlCABundle)
-            msDebug("Using CURL_CA_BUNDLE=%s\n", pszCurlCABundle);
+    /* set URL, note that curl keeps only a ref to our string buffer */
+    curl_easy_setopt(http_handle, CURLOPT_URL, pasReqInfo[i].pszGetUrl );
+
+    /* Set User-Agent (auto-generate if not set by caller */
+    if (pasReqInfo[i].pszUserAgent == NULL) {
+      curl_version_info_data *psCurlVInfo;
+
+      psCurlVInfo = curl_version_info(CURLVERSION_NOW);
+
+      pasReqInfo[i].pszUserAgent = (char*)msSmallMalloc(100*sizeof(char));
+
+      if (pasReqInfo[i].pszUserAgent) {
+        sprintf(pasReqInfo[i].pszUserAgent,
+                "MapServer/%s libcurl/%d.%d.%d",
+                MS_VERSION,
+                psCurlVInfo->version_num/0x10000 & 0xff,
+                psCurlVInfo->version_num/0x100 & 0xff,
+                psCurlVInfo->version_num & 0xff );
+      }
+    }
+    if (pasReqInfo[i].pszUserAgent) {
+      curl_easy_setopt(http_handle,
+                       CURLOPT_USERAGENT, pasReqInfo[i].pszUserAgent );
     }
 
-    /* Alloc a curl-multi handle, and add a curl-easy handle to it for each
-     * file to download.
-     */
-    multi_handle = curl_multi_init();
-    if (multi_handle == NULL)
-    {
-        msSetError(MS_HTTPERR, "curl_multi_init() failed.", 
+    /* Enable following redirections.  Requires libcurl 7.10.1 at least */
+    curl_easy_setopt(http_handle, CURLOPT_FOLLOWLOCATION, 1 );
+    curl_easy_setopt(http_handle, CURLOPT_MAXREDIRS, 10 );
+
+    /* Set timeout.*/
+    curl_easy_setopt(http_handle, CURLOPT_TIMEOUT, nTimeout );
+
+    /* Pass CURL_CA_BUNDLE if set */
+    if (pszCurlCABundle)
+      curl_easy_setopt(http_handle, CURLOPT_CAINFO, pszCurlCABundle );
+
+    /* Set proxying settings */
+    if (pasReqInfo[i].pszProxyAddress != NULL
+        && strlen(pasReqInfo[i].pszProxyAddress) > 0) {
+      long    nProxyType     = CURLPROXY_HTTP;
+
+      curl_easy_setopt(http_handle, CURLOPT_PROXY,
+                       pasReqInfo[i].pszProxyAddress);
+
+      if (pasReqInfo[i].nProxyPort > 0
+          && pasReqInfo[i].nProxyPort < 65535) {
+        curl_easy_setopt(http_handle, CURLOPT_PROXYPORT,
+                         pasReqInfo[i].nProxyPort);
+      }
+
+      switch (pasReqInfo[i].eProxyType) {
+        case MS_HTTP:
+          nProxyType = CURLPROXY_HTTP;
+          break;
+        case MS_SOCKS5:
+          nProxyType = CURLPROXY_SOCKS5;
+          break;
+      }
+      curl_easy_setopt(http_handle, CURLOPT_PROXYTYPE, nProxyType);
+
+      /* If there is proxy authentication information, set it */
+      if (pasReqInfo[i].pszProxyUsername != NULL
+          && pasReqInfo[i].pszProxyPassword != NULL
+          && strlen(pasReqInfo[i].pszProxyUsername) > 0
+          && strlen(pasReqInfo[i].pszProxyPassword) > 0) {
+        char    szUsernamePasswd[128];
+#ifdef USE_CURLOPT_PROXYAUTH
+        long    nProxyAuthType = CURLAUTH_BASIC;
+        /* CURLOPT_PROXYAUTH available only in Curl 7.10.7 and up */
+        nProxyAuthType = msGetCURLAuthType(pasReqInfo[i].eProxyAuthType);
+        curl_easy_setopt(http_handle, CURLOPT_PROXYAUTH, nProxyAuthType);
+#else
+        /* We log an error but don't abort processing */
+        msSetError(MS_HTTPERR, "CURLOPT_PROXYAUTH not supported. Requires Curl 7.10.7 and up. *_proxy_auth_type setting ignored.",
                    "msHTTPExecuteRequests()");
-        return(MS_FAILURE);
+#endif /* CURLOPT_PROXYAUTH */
+
+        snprintf(szUsernamePasswd, 127, "%s:%s",
+                 pasReqInfo[i].pszProxyUsername,
+                 pasReqInfo[i].pszProxyPassword);
+        curl_easy_setopt(http_handle, CURLOPT_PROXYUSERPWD,
+                         szUsernamePasswd);
+      }
     }
 
-    for (i=0; i<numRequests; i++)
-    {
-        CURL *http_handle;
-        FILE *fp;
+    /* Set HTTP Authentication settings */
+    if (pasReqInfo[i].pszHttpUsername != NULL
+        && pasReqInfo[i].pszHttpPassword != NULL
+        && strlen(pasReqInfo[i].pszHttpUsername) > 0
+        && strlen(pasReqInfo[i].pszHttpPassword) > 0) {
+      char    szUsernamePasswd[128];
+      long    nHttpAuthType = CURLAUTH_BASIC;
+
+      snprintf(szUsernamePasswd, 127, "%s:%s",
+               pasReqInfo[i].pszHttpUsername,
+               pasReqInfo[i].pszHttpPassword);
+      curl_easy_setopt(http_handle, CURLOPT_USERPWD,
+                       szUsernamePasswd);
+
+      nHttpAuthType = msGetCURLAuthType(pasReqInfo[i].eHttpAuthType);
+      curl_easy_setopt(http_handle, CURLOPT_HTTPAUTH, nHttpAuthType);
+    }
 
-        if (pasReqInfo[i].pszGetUrl == NULL )
-        {
-            msSetError(MS_HTTPERR, "URL or output file parameter missing.", 
-                       "msHTTPExecuteRequests()");
-            return(MS_FAILURE);
-        }
+    /* NOSIGNAL should be set to true for timeout to work in multithread
+     * environments on Unix, requires libcurl 7.10 or more recent.
+     * (this force avoiding the use of sgnal handlers)
+     */
+#ifdef CURLOPT_NOSIGNAL
+    curl_easy_setopt(http_handle, CURLOPT_NOSIGNAL, 1 );
+#endif
 
-        if (pasReqInfo[i].debug)
-        {
-            msDebug("HTTP request: id=%d, %s\n", 
-                    pasReqInfo[i].nLayerId, pasReqInfo[i].pszGetUrl);
-        }
+    /* If we are writing file to disk, open the file now. */
+    if( pasReqInfo[i].pszOutputFile != NULL ) {
+      if ( (fp = fopen(pasReqInfo[i].pszOutputFile, "wb")) == NULL) {
+        msSetError(MS_HTTPERR, "Can't open output file %s.",
+                   "msHTTPExecuteRequests()", pasReqInfo[i].pszOutputFile);
+        return(MS_FAILURE);
+      }
 
-        /* Reset some members */
-        pasReqInfo[i].nStatus = 0;
-        if (pasReqInfo[i].pszContentType)
-            free(pasReqInfo[i].pszContentType);
-        pasReqInfo[i].pszContentType = NULL;
-
-        /* Check local cache if requested */
-        if (bCheckLocalCache && pasReqInfo[i].pszOutputFile != NULL )
-        {
-            fp = fopen(pasReqInfo[i].pszOutputFile, "r");
-            if (fp)
-            {
-                /* File already there, don't download again. */
-                if (pasReqInfo[i].debug)
-                    msDebug("HTTP request: id=%d, found in cache, skipping.\n",
-                            pasReqInfo[i].nLayerId);
-                fclose(fp);
-                pasReqInfo[i].nStatus = 242;
-                pasReqInfo[i].pszContentType = msStrdup("unknown/cached");
-                continue;
-            }
-        }
+      pasReqInfo[i].fp = fp;
+    }
 
-        /* Alloc curl handle */
-        http_handle = curl_easy_init();
-        if (http_handle == NULL)
-        {
-            msSetError(MS_HTTPERR, "curl_easy_init() failed.", 
-                       "msHTTPExecuteRequests()");
-            return(MS_FAILURE);
-        }
+    curl_easy_setopt(http_handle, CURLOPT_WRITEDATA, &(pasReqInfo[i]));
+    curl_easy_setopt(http_handle, CURLOPT_WRITEFUNCTION, msHTTPWriteFct);
 
-        pasReqInfo[i].curl_handle = http_handle;
+    /* Provide a buffer where libcurl can write human readable error msgs
+     */
+    if (pasReqInfo[i].pszErrBuf == NULL)
+      pasReqInfo[i].pszErrBuf = (char *)msSmallMalloc((CURL_ERROR_SIZE+1)*
+                                sizeof(char));
+    pasReqInfo[i].pszErrBuf[0] = '\0';
+
+    curl_easy_setopt(http_handle, CURLOPT_ERRORBUFFER,
+                     pasReqInfo[i].pszErrBuf);
+
+    if(pasReqInfo[i].pszPostRequest != NULL ) {
+      char szBuf[100];
+
+      struct curl_slist *headers=NULL;
+      snprintf(szBuf, 100,
+               "Content-Type: %s", pasReqInfo[i].pszPostContentType);
+      headers = curl_slist_append(headers, szBuf);
+
+      curl_easy_setopt(http_handle, CURLOPT_POST, 1 );
+      curl_easy_setopt(http_handle, CURLOPT_POSTFIELDS,
+                       pasReqInfo[i].pszPostRequest);
+      curl_easy_setopt(http_handle, CURLOPT_HTTPHEADER, headers);
+      /* curl_slist_free_all(headers); */ /* free the header list */
+    }
 
-        /* set URL, note that curl keeps only a ref to our string buffer */
-        curl_easy_setopt(http_handle, CURLOPT_URL, pasReqInfo[i].pszGetUrl );
+    /* Added by RFC-42 HTTP Cookie Forwarding */
+    if(pasReqInfo[i].pszHTTPCookieData != NULL) {
+      /* Check if there's no end of line in the Cookie string */
+      /* This could break the HTTP Header */
+      int nPos;
+
+      for(nPos=0; nPos<strlen(pasReqInfo[i].pszHTTPCookieData); nPos++) {
+        if(pasReqInfo[i].pszHTTPCookieData[nPos] == '\n') {
+          msSetError(MS_HTTPERR, "Can't use cookie containing a newline character.",
+                     "msHTTPExecuteRequests()");
+          return(MS_FAILURE);
+        }
+      }
 
-        /* Set User-Agent (auto-generate if not set by caller */
-        if (pasReqInfo[i].pszUserAgent == NULL)
-        {
-            curl_version_info_data *psCurlVInfo;
+      /* Set the Curl option to send Cookie */
+      curl_easy_setopt(http_handle, CURLOPT_COOKIE,
+                       pasReqInfo[i].pszHTTPCookieData);
+    }
 
-            psCurlVInfo = curl_version_info(CURLVERSION_NOW);
+    /* Add to multi handle */
+    curl_multi_add_handle(multi_handle, http_handle);
 
-            pasReqInfo[i].pszUserAgent = (char*)msSmallMalloc(100*sizeof(char));
+  }
 
-            if (pasReqInfo[i].pszUserAgent)
-            {
-                sprintf(pasReqInfo[i].pszUserAgent, 
-                        "MapServer/%s libcurl/%d.%d.%d",
-                        MS_VERSION, 
-                        psCurlVInfo->version_num/0x10000 & 0xff,
-                        psCurlVInfo->version_num/0x100 & 0xff,
-                        psCurlVInfo->version_num & 0xff );
-            }
-        }
-        if (pasReqInfo[i].pszUserAgent)
-        {
-            curl_easy_setopt(http_handle, 
-                             CURLOPT_USERAGENT, pasReqInfo[i].pszUserAgent );
-        }
+  if (debug) {
+    msDebug("HTTP: Before download loop\n");
+  }
 
-        /* Enable following redirections.  Requires libcurl 7.10.1 at least */
-        curl_easy_setopt(http_handle, CURLOPT_FOLLOWLOCATION, 1 );
-        curl_easy_setopt(http_handle, CURLOPT_MAXREDIRS, 10 );
-
-        /* Set timeout.*/
-        curl_easy_setopt(http_handle, CURLOPT_TIMEOUT, nTimeout );
-
-        /* Pass CURL_CA_BUNDLE if set */
-        if (pszCurlCABundle)
-            curl_easy_setopt(http_handle, CURLOPT_CAINFO, pszCurlCABundle );
-
-        /* Set proxying settings */
-        if (pasReqInfo[i].pszProxyAddress != NULL
-            && strlen(pasReqInfo[i].pszProxyAddress) > 0)
-        {
-            long    nProxyType     = CURLPROXY_HTTP;
-            
-            curl_easy_setopt(http_handle, CURLOPT_PROXY,
-                             pasReqInfo[i].pszProxyAddress);
-            
-            if (pasReqInfo[i].nProxyPort > 0
-                && pasReqInfo[i].nProxyPort < 65535)
-            {
-                curl_easy_setopt(http_handle, CURLOPT_PROXYPORT,
-                                 pasReqInfo[i].nProxyPort);
-            }
-            
-            switch (pasReqInfo[i].eProxyType)
-            {
-                case MS_HTTP:
-                    nProxyType = CURLPROXY_HTTP;
-                    break;
-                case MS_SOCKS5:
-                    nProxyType = CURLPROXY_SOCKS5;
-                    break;
-            }
-            curl_easy_setopt(http_handle, CURLOPT_PROXYTYPE, nProxyType);
-            
-            /* If there is proxy authentication information, set it */
-            if (pasReqInfo[i].pszProxyUsername != NULL
-                && pasReqInfo[i].pszProxyPassword != NULL
-                && strlen(pasReqInfo[i].pszProxyUsername) > 0
-                && strlen(pasReqInfo[i].pszProxyPassword) > 0)
-            {
-                char    szUsernamePasswd[128];    
-#ifdef USE_CURLOPT_PROXYAUTH
-                long    nProxyAuthType = CURLAUTH_BASIC;
-                /* CURLOPT_PROXYAUTH available only in Curl 7.10.7 and up */
-                nProxyAuthType = msGetCURLAuthType(pasReqInfo[i].eProxyAuthType);
-                curl_easy_setopt(http_handle, CURLOPT_PROXYAUTH, nProxyAuthType);
-#else
-                /* We log an error but don't abort processing */
-                msSetError(MS_HTTPERR, "CURLOPT_PROXYAUTH not supported. Requires Curl 7.10.7 and up. *_proxy_auth_type setting ignored.", 
-                           "msHTTPExecuteRequests()");
-#endif /* CURLOPT_PROXYAUTH */ 
-                
-                snprintf(szUsernamePasswd, 127, "%s:%s",
-                         pasReqInfo[i].pszProxyUsername,
-                         pasReqInfo[i].pszProxyPassword);
-                curl_easy_setopt(http_handle, CURLOPT_PROXYUSERPWD,
-                                 szUsernamePasswd);
-            }
-        }
-        
-        /* Set HTTP Authentication settings */
-        if (pasReqInfo[i].pszHttpUsername != NULL
-            && pasReqInfo[i].pszHttpPassword != NULL
-            && strlen(pasReqInfo[i].pszHttpUsername) > 0
-            && strlen(pasReqInfo[i].pszHttpPassword) > 0)
-        {
-            char    szUsernamePasswd[128];
-            long    nHttpAuthType = CURLAUTH_BASIC;
-            
-            snprintf(szUsernamePasswd, 127, "%s:%s",
-                     pasReqInfo[i].pszHttpUsername,
-                     pasReqInfo[i].pszHttpPassword);
-            curl_easy_setopt(http_handle, CURLOPT_USERPWD,
-                             szUsernamePasswd);
-                                 
-            nHttpAuthType = msGetCURLAuthType(pasReqInfo[i].eHttpAuthType);
-            curl_easy_setopt(http_handle, CURLOPT_HTTPAUTH, nHttpAuthType);
-        }
+  /* DOWNLOAD LOOP ... inspired from multi-double.c example */
 
-        /* NOSIGNAL should be set to true for timeout to work in multithread
-         * environments on Unix, requires libcurl 7.10 or more recent.
-         * (this force avoiding the use of sgnal handlers)
-         */
-#ifdef CURLOPT_NOSIGNAL
-        curl_easy_setopt(http_handle, CURLOPT_NOSIGNAL, 1 );
-#endif
+  /* we start some action by calling perform right away */
+  while(CURLM_CALL_MULTI_PERFORM ==
+        curl_multi_perform(multi_handle, &still_running));
 
-        /* If we are writing file to disk, open the file now. */
-        if( pasReqInfo[i].pszOutputFile != NULL )
-        {
-            if ( (fp = fopen(pasReqInfo[i].pszOutputFile, "wb")) == NULL)
-            {
-                msSetError(MS_HTTPERR, "Can't open output file %s.", 
-                           "msHTTPExecuteRequests()", pasReqInfo[i].pszOutputFile);
-                return(MS_FAILURE);
-            }
-
-            pasReqInfo[i].fp = fp;
-        }
+  while(still_running) {
+    struct timeval timeout;
+    int rc; /* select() return code */
 
-        curl_easy_setopt(http_handle, CURLOPT_WRITEDATA, &(pasReqInfo[i]));
-        curl_easy_setopt(http_handle, CURLOPT_WRITEFUNCTION, msHTTPWriteFct);
+    fd_set fdread;
+    fd_set fdwrite;
+    fd_set fdexcep;
+    int maxfd;
 
-        /* Provide a buffer where libcurl can write human readable error msgs
-         */
-        if (pasReqInfo[i].pszErrBuf == NULL)
-            pasReqInfo[i].pszErrBuf = (char *)msSmallMalloc((CURL_ERROR_SIZE+1)*
-                                                     sizeof(char));
-        pasReqInfo[i].pszErrBuf[0] = '\0';
-
-        curl_easy_setopt(http_handle, CURLOPT_ERRORBUFFER, 
-                         pasReqInfo[i].pszErrBuf);
-
-        if(pasReqInfo[i].pszPostRequest != NULL )
-        {
-            char szBuf[100];
-
-            struct curl_slist *headers=NULL;
-            snprintf(szBuf, 100, 
-                     "Content-Type: %s", pasReqInfo[i].pszPostContentType);
-            headers = curl_slist_append(headers, szBuf);
-
-            curl_easy_setopt(http_handle, CURLOPT_POST, 1 );
-            curl_easy_setopt(http_handle, CURLOPT_POSTFIELDS, 
-                             pasReqInfo[i].pszPostRequest);
-            curl_easy_setopt(http_handle, CURLOPT_HTTPHEADER, headers);
-            /* curl_slist_free_all(headers); */ /* free the header list */
-        }
+    FD_ZERO(&fdread);
+    FD_ZERO(&fdwrite);
+    FD_ZERO(&fdexcep);
 
-        /* Added by RFC-42 HTTP Cookie Forwarding */
-        if(pasReqInfo[i].pszHTTPCookieData != NULL)
-        {
-            /* Check if there's no end of line in the Cookie string */
-            /* This could break the HTTP Header */
-            int nPos;
-
-            for(nPos=0; nPos<strlen(pasReqInfo[i].pszHTTPCookieData); nPos++)
-            {
-                if(pasReqInfo[i].pszHTTPCookieData[nPos] == '\n')
-                {
-                    msSetError(MS_HTTPERR, "Can't use cookie containing a newline character.", 
-                       "msHTTPExecuteRequests()");
-                    return(MS_FAILURE);
-                }
-            }
-
-            /* Set the Curl option to send Cookie */
-            curl_easy_setopt(http_handle, CURLOPT_COOKIE, 
-                             pasReqInfo[i].pszHTTPCookieData);
-        }
+    /* set a suitable timeout to play around with */
+    timeout.tv_sec = 0;
+    timeout.tv_usec = 100000;
 
-        /* Add to multi handle */
-        curl_multi_add_handle(multi_handle, http_handle);
+    /* get file descriptors from the transfers */
+    curl_multi_fdset(multi_handle, &fdread, &fdwrite, &fdexcep, &maxfd);
 
-    }
+    rc = select(maxfd+1, &fdread, &fdwrite, &fdexcep, &timeout);
 
-    if (debug)
-    {
-        msDebug("HTTP: Before download loop\n");
-    }
+    switch(rc) {
+      case -1:
+        /* select error */
 
-    /* DOWNLOAD LOOP ... inspired from multi-double.c example */
-
-    /* we start some action by calling perform right away */
-    while(CURLM_CALL_MULTI_PERFORM ==
-          curl_multi_perform(multi_handle, &still_running));
-
-    while(still_running) 
-    {
-        struct timeval timeout;
-        int rc; /* select() return code */
-
-        fd_set fdread;
-        fd_set fdwrite;
-        fd_set fdexcep;
-        int maxfd;
-
-        FD_ZERO(&fdread);
-        FD_ZERO(&fdwrite);
-        FD_ZERO(&fdexcep);
-
-        /* set a suitable timeout to play around with */
-        timeout.tv_sec = 0;
-        timeout.tv_usec = 100000;
-
-        /* get file descriptors from the transfers */
-        curl_multi_fdset(multi_handle, &fdread, &fdwrite, &fdexcep, &maxfd);
-
-        rc = select(maxfd+1, &fdread, &fdwrite, &fdexcep, &timeout);
-
-        switch(rc) 
-        {
-          case -1:
-            /* select error */
-
-/* ==================================================================== */
-/*      On Windows the select function (just above) returns -1 when     */
-/*      it is called the second time and all the calls after            */
-/*      that. This causes an infinite loop.                             */
-/*      I do not really know why.                                       */
-/*      To sovle the problem the break frop case -1 has been removed.   */
-/* ==================================================================== */
-#ifndef _WIN32            
-            break;
+        /* ==================================================================== */
+        /*      On Windows the select function (just above) returns -1 when     */
+        /*      it is called the second time and all the calls after            */
+        /*      that. This causes an infinite loop.                             */
+        /*      I do not really know why.                                       */
+        /*      To sovle the problem the break frop case -1 has been removed.   */
+        /* ==================================================================== */
+#ifndef _WIN32
+        break;
 #endif
-          case 0:
-          default:
-            /* timeout or readable/writable sockets */
-            curl_multi_perform(multi_handle, &still_running);
-            break;
-        }
+      case 0:
+      default:
+        /* timeout or readable/writable sockets */
+        curl_multi_perform(multi_handle, &still_running);
+        break;
     }
+  }
+
+  if (debug)
+    msDebug("HTTP: After download loop\n");
+
+  /* Scan message stack from CURL and report fatal errors*/
+
+  while((curl_msg = curl_multi_info_read( multi_handle, &num_msgs)) != NULL) {
+    httpRequestObj *psReq = NULL;
 
-    if (debug)
-        msDebug("HTTP: After download loop\n");
-
-    /* Scan message stack from CURL and report fatal errors*/
-
-    while((curl_msg = curl_multi_info_read( multi_handle, &num_msgs)) != NULL)
-    {
-        httpRequestObj *psReq = NULL;
-
-        if (curl_msg->msg == CURLMSG_DONE &&
-            curl_msg->data.result != CURLE_OK)
-        {
-            /* Something went wrong with this transfer... report error */
-
-            for (i=0; i<numRequests; i++)
-            {
-                if (pasReqInfo[i].curl_handle == curl_msg->easy_handle)
-                {
-                    psReq = &(pasReqInfo[i]);
-                    break;
-                }
-            }
-
-            if (psReq != NULL)
-            {
-                /* Record error code in nStatus as a negative value */
-                psReq->nStatus = -curl_msg->data.result;
-            }
+    if (curl_msg->msg == CURLMSG_DONE &&
+        curl_msg->data.result != CURLE_OK) {
+      /* Something went wrong with this transfer... report error */
+
+      for (i=0; i<numRequests; i++) {
+        if (pasReqInfo[i].curl_handle == curl_msg->easy_handle) {
+          psReq = &(pasReqInfo[i]);
+          break;
         }
+      }
+
+      if (psReq != NULL) {
+        /* Record error code in nStatus as a negative value */
+        psReq->nStatus = -curl_msg->data.result;
+      }
     }
+  }
+
+  if (debug) {
+    /* Print a msDebug header for timings reported in the loop below */
+    msDebug("msHTTPExecuteRequests() timing summary per layer (connect_time + time_to_first_packet + download_time = total_time in seconds)\n");
+  }
+
+  /* Check status of all requests, close files, report errors and cleanup
+   * handles
+   */
+  for (i=0; i<numRequests; i++) {
+    httpRequestObj *psReq;
+    CURL *http_handle;
+    long lVal=0;
+
+    psReq = &(pasReqInfo[i]);
 
-    if (debug)
-    {
-        /* Print a msDebug header for timings reported in the loop below */
-        msDebug("msHTTPExecuteRequests() timing summary per layer (connect_time + time_to_first_packet + download_time = total_time in seconds)\n");
+    if (psReq->nStatus == 242)
+      continue;  /* Nothing to do here, this file was in cache already */
+
+    if (psReq->fp)
+      fclose(psReq->fp);
+    psReq->fp = NULL;
+
+    http_handle = (CURL*)(psReq->curl_handle);
+
+    if (psReq->nStatus == 0 &&
+        curl_easy_getinfo(http_handle,
+                          CURLINFO_HTTP_CODE, &lVal) == CURLE_OK) {
+      char *pszContentType = NULL;
+
+      psReq->nStatus = lVal;
+
+      /* Fetch content type of response */
+      if (curl_easy_getinfo(http_handle,
+                            CURLINFO_CONTENT_TYPE,
+                            &pszContentType) == CURLE_OK &&
+          pszContentType != NULL) {
+        psReq->pszContentType = msStrdup(pszContentType);
+      }
     }
 
-    /* Check status of all requests, close files, report errors and cleanup
-     * handles 
-     */
-    for (i=0; i<numRequests; i++)
-    {
-        httpRequestObj *psReq;
-        CURL *http_handle;
-        long lVal=0;
-
-        psReq = &(pasReqInfo[i]);
-
-        if (psReq->nStatus == 242)
-            continue;  /* Nothing to do here, this file was in cache already */
-
-        if (psReq->fp)
-            fclose(psReq->fp);
-        psReq->fp = NULL;
-
-        http_handle = (CURL*)(psReq->curl_handle);
-
-        if (psReq->nStatus == 0 &&
-            curl_easy_getinfo(http_handle,
-                              CURLINFO_HTTP_CODE, &lVal) == CURLE_OK)
-        {
-            char *pszContentType = NULL;
-
-            psReq->nStatus = lVal;
-
-            /* Fetch content type of response */
-            if (curl_easy_getinfo(http_handle, 
-                                  CURLINFO_CONTENT_TYPE, 
-                                  &pszContentType) == CURLE_OK &&
-                pszContentType != NULL)
-            {
-                psReq->pszContentType = msStrdup(pszContentType);
-            }
-        }
+    if (!MS_HTTP_SUCCESS(psReq->nStatus)) {
+      /* Set status to MS_DONE to indicate that transfers were  */
+      /* completed but may not be succesfull */
+      nStatus = MS_DONE;
 
-        if (!MS_HTTP_SUCCESS(psReq->nStatus))
-        {
-            /* Set status to MS_DONE to indicate that transfers were  */
-            /* completed but may not be succesfull */
-            nStatus = MS_DONE;
-
-            if (psReq->nStatus == -(CURLE_OPERATION_TIMEOUTED))
-            {
-                /* Timeout isn't a fatal error */
-                if (psReq->debug)
-                    msDebug("HTTP: TIMEOUT of %d seconds exceeded for %s\n",
-                            nTimeout, psReq->pszGetUrl );
-
-                msSetError(MS_HTTPERR, 
-                           "HTTP: TIMEOUT of %d seconds exceeded for %s\n",
-                           "msHTTPExecuteRequests()", 
-                           nTimeout, psReq->pszGetUrl);
-
-                /* Rewrite error message, the curl timeout message isn't
-                 * of much use to our users.
-                 */
-                sprintf(psReq->pszErrBuf, 
-                        "TIMEOUT of %d seconds exceeded.", nTimeout);
-            }
-            else if (psReq->nStatus > 0)
-            {
-                /* Got an HTTP Error, e.g. 404, etc. */
-
-                if (psReq->debug)
-                    msDebug("HTTP: HTTP GET request failed with status %d (%s)"
-                            " for %s\n",
-                            psReq->nStatus, psReq->pszErrBuf, 
-                            psReq->pszGetUrl);
-
-                msSetError(MS_HTTPERR, 
-                           "HTTP GET request failed with status %d (%s) "
-                           "for %s",
-                           "msHTTPExecuteRequests()", psReq->nStatus, 
-                           psReq->pszErrBuf, psReq->pszGetUrl);
-            }
-            else
-            {
-                /* Got a curl error */
-
-                if (psReq->debug)
-                    msDebug("HTTP: request failed with curl error "
-                            "code %d (%s) for %s",
-                            -psReq->nStatus, psReq->pszErrBuf, 
-                            psReq->pszGetUrl);
-
-                msSetError(MS_HTTPERR, 
-                           "HTTP: request failed with curl error "
-                           "code %d (%s) for %s",
-                           "msHTTPExecuteRequests()", 
-                           -psReq->nStatus, psReq->pszErrBuf, 
-                           psReq->pszGetUrl);
-            }
-        }
+      if (psReq->nStatus == -(CURLE_OPERATION_TIMEOUTED)) {
+        /* Timeout isn't a fatal error */
+        if (psReq->debug)
+          msDebug("HTTP: TIMEOUT of %d seconds exceeded for %s\n",
+                  nTimeout, psReq->pszGetUrl );
+
+        msSetError(MS_HTTPERR,
+                   "HTTP: TIMEOUT of %d seconds exceeded for %s\n",
+                   "msHTTPExecuteRequests()",
+                   nTimeout, psReq->pszGetUrl);
+
+        /* Rewrite error message, the curl timeout message isn't
+         * of much use to our users.
+         */
+        sprintf(psReq->pszErrBuf,
+                "TIMEOUT of %d seconds exceeded.", nTimeout);
+      } else if (psReq->nStatus > 0) {
+        /* Got an HTTP Error, e.g. 404, etc. */
 
-        /* Report download times foreach handle, in debug mode */
         if (psReq->debug)
-        {
-            double dConnectTime=0.0, dTotalTime=0.0, dStartTfrTime=0.0;
-
-            curl_easy_getinfo(http_handle, 
-                              CURLINFO_CONNECT_TIME, &dConnectTime);
-            curl_easy_getinfo(http_handle, 
-                              CURLINFO_STARTTRANSFER_TIME, &dStartTfrTime);
-            curl_easy_getinfo(http_handle, 
-                              CURLINFO_TOTAL_TIME, &dTotalTime);
-            /* STARTTRANSFER_TIME includes CONNECT_TIME, but TOTAL_TIME
-             * doesn't, so we need to add it.
-             */
-            dTotalTime += dConnectTime;
-
-            msDebug("Layer %d: %.3f + %.3f + %.3f = %.3fs\n", psReq->nLayerId,
-                    dConnectTime, dStartTfrTime-dConnectTime, 
-                    dTotalTime-dStartTfrTime, dTotalTime);
-        }
+          msDebug("HTTP: HTTP GET request failed with status %d (%s)"
+                  " for %s\n",
+                  psReq->nStatus, psReq->pszErrBuf,
+                  psReq->pszGetUrl);
+
+        msSetError(MS_HTTPERR,
+                   "HTTP GET request failed with status %d (%s) "
+                   "for %s",
+                   "msHTTPExecuteRequests()", psReq->nStatus,
+                   psReq->pszErrBuf, psReq->pszGetUrl);
+      } else {
+        /* Got a curl error */
 
-        /* Cleanup this handle */
-        curl_easy_setopt(http_handle, CURLOPT_URL, "" );
-        curl_multi_remove_handle(multi_handle, http_handle);
-        curl_easy_cleanup(http_handle);
-        psReq->curl_handle = NULL;
+        if (psReq->debug)
+          msDebug("HTTP: request failed with curl error "
+                  "code %d (%s) for %s",
+                  -psReq->nStatus, psReq->pszErrBuf,
+                  psReq->pszGetUrl);
+
+        msSetError(MS_HTTPERR,
+                   "HTTP: request failed with curl error "
+                   "code %d (%s) for %s",
+                   "msHTTPExecuteRequests()",
+                   -psReq->nStatus, psReq->pszErrBuf,
+                   psReq->pszGetUrl);
+      }
+    }
 
+    /* Report download times foreach handle, in debug mode */
+    if (psReq->debug) {
+      double dConnectTime=0.0, dTotalTime=0.0, dStartTfrTime=0.0;
+
+      curl_easy_getinfo(http_handle,
+                        CURLINFO_CONNECT_TIME, &dConnectTime);
+      curl_easy_getinfo(http_handle,
+                        CURLINFO_STARTTRANSFER_TIME, &dStartTfrTime);
+      curl_easy_getinfo(http_handle,
+                        CURLINFO_TOTAL_TIME, &dTotalTime);
+      /* STARTTRANSFER_TIME includes CONNECT_TIME, but TOTAL_TIME
+       * doesn't, so we need to add it.
+       */
+      dTotalTime += dConnectTime;
+
+      msDebug("Layer %d: %.3f + %.3f + %.3f = %.3fs\n", psReq->nLayerId,
+              dConnectTime, dStartTfrTime-dConnectTime,
+              dTotalTime-dStartTfrTime, dTotalTime);
     }
 
-    /* Cleanup multi handle, each handle had to be cleaned up individually */
-    curl_multi_cleanup(multi_handle);
+    /* Cleanup this handle */
+    curl_easy_setopt(http_handle, CURLOPT_URL, "" );
+    curl_multi_remove_handle(multi_handle, http_handle);
+    curl_easy_cleanup(http_handle);
+    psReq->curl_handle = NULL;
 
-    return nStatus;
+  }
+
+  /* Cleanup multi handle, each handle had to be cleaned up individually */
+  curl_multi_cleanup(multi_handle);
+
+  return nStatus;
 }
 
 /**********************************************************************
@@ -831,42 +778,41 @@ int msHTTPExecuteRequests(httpRequestObj *pasReqInfo, int numRequests,
  *
  * Wrapper to call msHTTPExecuteRequests() for a single file.
  **********************************************************************/
-int msHTTPGetFile(const char *pszGetUrl, const char *pszOutputFile, 
+int msHTTPGetFile(const char *pszGetUrl, const char *pszOutputFile,
                   int *pnHTTPStatus, int nTimeout, int bCheckLocalCache,
                   int bDebug)
 {
-    httpRequestObj *pasReqInfo;
-
-    /* Alloc httpRequestInfo structs through which status of each request 
-     * will be returned.
-     * We need to alloc 2 instance of requestobj so that the last
-     * object in the array can be set to NULL. 
-    */
-    pasReqInfo = (httpRequestObj*)calloc(2, sizeof(httpRequestObj));
-    MS_CHECK_ALLOC(pasReqInfo, 2*sizeof(httpRequestObj), MS_FAILURE);
-    
-    msHTTPInitRequestObj(pasReqInfo, 2);
-
-    pasReqInfo[0].pszGetUrl = msStrdup(pszGetUrl);
-    pasReqInfo[0].pszOutputFile = msStrdup(pszOutputFile);
-    pasReqInfo[0].debug = (char)bDebug;
-
-    if (msHTTPExecuteRequests(pasReqInfo, 1, bCheckLocalCache) != MS_SUCCESS)
-    {
-        *pnHTTPStatus = pasReqInfo[0].nStatus;
-        if (pasReqInfo[0].debug)
-            msDebug("HTTP request failed for %s.\n", pszGetUrl);
-        msHTTPFreeRequestObj(pasReqInfo, 2);
-        free(pasReqInfo);
-        return MS_FAILURE;
-    }
+  httpRequestObj *pasReqInfo;
 
-    *pnHTTPStatus = pasReqInfo[0].nStatus;
+  /* Alloc httpRequestInfo structs through which status of each request
+   * will be returned.
+   * We need to alloc 2 instance of requestobj so that the last
+   * object in the array can be set to NULL.
+  */
+  pasReqInfo = (httpRequestObj*)calloc(2, sizeof(httpRequestObj));
+  MS_CHECK_ALLOC(pasReqInfo, 2*sizeof(httpRequestObj), MS_FAILURE);
+
+  msHTTPInitRequestObj(pasReqInfo, 2);
+
+  pasReqInfo[0].pszGetUrl = msStrdup(pszGetUrl);
+  pasReqInfo[0].pszOutputFile = msStrdup(pszOutputFile);
+  pasReqInfo[0].debug = (char)bDebug;
 
+  if (msHTTPExecuteRequests(pasReqInfo, 1, bCheckLocalCache) != MS_SUCCESS) {
+    *pnHTTPStatus = pasReqInfo[0].nStatus;
+    if (pasReqInfo[0].debug)
+      msDebug("HTTP request failed for %s.\n", pszGetUrl);
     msHTTPFreeRequestObj(pasReqInfo, 2);
     free(pasReqInfo);
+    return MS_FAILURE;
+  }
+
+  *pnHTTPStatus = pasReqInfo[0].nStatus;
+
+  msHTTPFreeRequestObj(pasReqInfo, 2);
+  free(pasReqInfo);
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 
diff --git a/maphttp.h b/maphttp.h
index 337c034..10c5d32 100644
--- a/maphttp.h
+++ b/maphttp.h
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -41,23 +41,21 @@ extern "C" {
 
 #define MS_HTTP_SUCCESS(status)  (status == 200 || status == 242)
 
-enum MS_HTTP_PROXY_TYPE
-{
+  enum MS_HTTP_PROXY_TYPE
+  {
     MS_HTTP,
     MS_SOCKS5
-};
+  };
 
-enum MS_HTTP_AUTH_TYPE
-{
+  enum MS_HTTP_AUTH_TYPE {
     MS_BASIC,
     MS_DIGEST,
     MS_NTLM,
     MS_ANY,
     MS_ANYSAFE
-};
+  };
 
-typedef struct http_request_info
-{
+  typedef struct http_request_info {
     int     nLayerId;
     char    *pszGetUrl;
     char    *pszOutputFile;
@@ -72,14 +70,14 @@ typedef struct http_request_info
     char    *pszPostContentType;/* post request MIME type */
     char    *pszUserAgent;      /* User-Agent, auto-generated if not set */
     char    *pszHTTPCookieData; /* HTTP Cookie data */
-    
+
     char    *pszProxyAddress;   /* The address (IP or hostname) of proxy svr */
     long     nProxyPort;        /* The proxy's port                          */
     enum MS_HTTP_PROXY_TYPE eProxyType; /* The type of proxy                 */
     enum MS_HTTP_AUTH_TYPE  eProxyAuthType; /* Auth method against proxy     */
     char    *pszProxyUsername;  /* Proxy authentication username             */
     char    *pszProxyPassword;  /* Proxy authentication password             */
-    
+
     enum MS_HTTP_AUTH_TYPE eHttpAuthType; /* HTTP Authentication type        */
     char    *pszHttpUsername;   /* HTTP Authentication username              */
     char    *pszHttpPassword;   /* HTTP Authentication password              */
@@ -90,25 +88,25 @@ typedef struct http_request_info
     /* Private members */
     void      * curl_handle;   /* CURLM * handle */
     FILE      * fp;            /* FILE * used during download */
-    
+
     char      * result_data;   /* output if pszOutputFile is NULL */
     int       result_size;
     int       result_buf_size;
 
-} httpRequestObj;
+  } httpRequestObj;
 
 #ifdef USE_CURL
 
-int msHTTPInit(void);
-void msHTTPCleanup(void);
+  int msHTTPInit(void);
+  void msHTTPCleanup(void);
 
-void msHTTPInitRequestObj(httpRequestObj *pasReqInfo, int numRequests);
-void msHTTPFreeRequestObj(httpRequestObj *pasReqInfo, int numRequests);
-int  msHTTPExecuteRequests(httpRequestObj *pasReqInfo, int numRequests,
-                           int bCheckLocalCache);
-int  msHTTPGetFile(const char *pszGetUrl, const char *pszOutputFile, 
-                   int *pnHTTPStatus, int nTimeout, int bCheckLocalCache,
-                   int bDebug);
+  void msHTTPInitRequestObj(httpRequestObj *pasReqInfo, int numRequests);
+  void msHTTPFreeRequestObj(httpRequestObj *pasReqInfo, int numRequests);
+  int  msHTTPExecuteRequests(httpRequestObj *pasReqInfo, int numRequests,
+                             int bCheckLocalCache);
+  int  msHTTPGetFile(const char *pszGetUrl, const char *pszOutputFile,
+                     int *pnHTTPStatus, int nTimeout, int bCheckLocalCache,
+                     int bDebug);
 
 #endif /*USE_CURL*/
 
diff --git a/mapimageio.c b/mapimageio.c
index 718d251..8fcba05 100644
--- a/mapimageio.c
+++ b/mapimageio.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -38,502 +38,512 @@
 #include "gif_lib.h"
 #endif
 
-MS_CVSID("$Id$")
+
 
 typedef struct _streamInfo {
-    FILE *fp;
-    bufferObj *buffer;
+  FILE *fp;
+  bufferObj *buffer;
 } streamInfo;
 
-void png_write_data_to_stream(png_structp png_ptr, png_bytep data, png_size_t length) {
-    FILE *fp = ((streamInfo*)png_get_io_ptr(png_ptr))->fp;
-    msIO_fwrite(data,length,1,fp);
+void png_write_data_to_stream(png_structp png_ptr, png_bytep data, png_size_t length)
+{
+  FILE *fp = ((streamInfo*)png_get_io_ptr(png_ptr))->fp;
+  msIO_fwrite(data,length,1,fp);
 }
 
-void png_write_data_to_buffer(png_structp png_ptr, png_bytep data, png_size_t length) {
-    bufferObj *buffer = ((streamInfo*)png_get_io_ptr(png_ptr))->buffer;
-    msBufferAppend(buffer,data,length);
+void png_write_data_to_buffer(png_structp png_ptr, png_bytep data, png_size_t length)
+{
+  bufferObj *buffer = ((streamInfo*)png_get_io_ptr(png_ptr))->buffer;
+  msBufferAppend(buffer,data,length);
 }
 
-void png_flush_data(png_structp png_ptr) {
- // do nothing
+void png_flush_data(png_structp png_ptr)
+{
+  /* do nothing */
 }
 
 typedef struct {
-    struct jpeg_destination_mgr pub;
-    unsigned char *data;
+  struct jpeg_destination_mgr pub;
+  unsigned char *data;
 } ms_destination_mgr;
 
 typedef struct {
-    ms_destination_mgr mgr;
-    FILE *stream;
+  ms_destination_mgr mgr;
+  FILE *stream;
 } ms_stream_destination_mgr;
 
 typedef struct {
-    ms_destination_mgr mgr;
-    bufferObj *buffer;
+  ms_destination_mgr mgr;
+  bufferObj *buffer;
 } ms_buffer_destination_mgr;
 
 #define OUTPUT_BUF_SIZE 4096
 
 void
-jpeg_init_destination (j_compress_ptr cinfo) {
-    ms_destination_mgr *dest = (ms_destination_mgr*) cinfo->dest;
+jpeg_init_destination (j_compress_ptr cinfo)
+{
+  ms_destination_mgr *dest = (ms_destination_mgr*) cinfo->dest;
 
-    /* Allocate the output buffer --- it will be released when done with image */
-    dest->data = (unsigned char *)
-        (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-                OUTPUT_BUF_SIZE * sizeof (unsigned char));
+  /* Allocate the output buffer --- it will be released when done with image */
+  dest->data = (unsigned char *)
+               (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+                   OUTPUT_BUF_SIZE * sizeof (unsigned char));
 
-    dest->pub.next_output_byte = dest->data;
-    dest->pub.free_in_buffer = OUTPUT_BUF_SIZE;
+  dest->pub.next_output_byte = dest->data;
+  dest->pub.free_in_buffer = OUTPUT_BUF_SIZE;
 }
 
-void jpeg_stream_term_destination (j_compress_ptr cinfo) {
-    ms_stream_destination_mgr *dest = (ms_stream_destination_mgr*) cinfo->dest;
-    msIO_fwrite(dest->mgr.data, OUTPUT_BUF_SIZE-dest->mgr.pub.free_in_buffer, 1, dest->stream);
-    dest->mgr.pub.next_output_byte = dest->mgr.data;
-    dest->mgr.pub.free_in_buffer = OUTPUT_BUF_SIZE;
+void jpeg_stream_term_destination (j_compress_ptr cinfo)
+{
+  ms_stream_destination_mgr *dest = (ms_stream_destination_mgr*) cinfo->dest;
+  msIO_fwrite(dest->mgr.data, OUTPUT_BUF_SIZE-dest->mgr.pub.free_in_buffer, 1, dest->stream);
+  dest->mgr.pub.next_output_byte = dest->mgr.data;
+  dest->mgr.pub.free_in_buffer = OUTPUT_BUF_SIZE;
 }
 
-void jpeg_buffer_term_destination (j_compress_ptr cinfo) {
-    ms_buffer_destination_mgr *dest = (ms_buffer_destination_mgr*) cinfo->dest;
-    msBufferAppend(dest->buffer, dest->mgr.data, OUTPUT_BUF_SIZE-dest->mgr.pub.free_in_buffer);
-    dest->mgr.pub.next_output_byte = dest->mgr.data;
-    dest->mgr.pub.free_in_buffer = OUTPUT_BUF_SIZE;
+void jpeg_buffer_term_destination (j_compress_ptr cinfo)
+{
+  ms_buffer_destination_mgr *dest = (ms_buffer_destination_mgr*) cinfo->dest;
+  msBufferAppend(dest->buffer, dest->mgr.data, OUTPUT_BUF_SIZE-dest->mgr.pub.free_in_buffer);
+  dest->mgr.pub.next_output_byte = dest->mgr.data;
+  dest->mgr.pub.free_in_buffer = OUTPUT_BUF_SIZE;
 }
 
-int jpeg_stream_empty_output_buffer (j_compress_ptr cinfo) {
-    ms_stream_destination_mgr *dest = (ms_stream_destination_mgr*) cinfo->dest;
-    msIO_fwrite(dest->mgr.data, OUTPUT_BUF_SIZE, 1, dest->stream);
-    dest->mgr.pub.next_output_byte = dest->mgr.data;
-    dest->mgr.pub.free_in_buffer = OUTPUT_BUF_SIZE;
-    return TRUE;
+int jpeg_stream_empty_output_buffer (j_compress_ptr cinfo)
+{
+  ms_stream_destination_mgr *dest = (ms_stream_destination_mgr*) cinfo->dest;
+  msIO_fwrite(dest->mgr.data, OUTPUT_BUF_SIZE, 1, dest->stream);
+  dest->mgr.pub.next_output_byte = dest->mgr.data;
+  dest->mgr.pub.free_in_buffer = OUTPUT_BUF_SIZE;
+  return TRUE;
 }
 
-int jpeg_buffer_empty_output_buffer (j_compress_ptr cinfo) {
-    ms_buffer_destination_mgr *dest = (ms_buffer_destination_mgr*) cinfo->dest;
-    msBufferAppend(dest->buffer, dest->mgr.data, OUTPUT_BUF_SIZE);
-    dest->mgr.pub.next_output_byte = dest->mgr.data;
-    dest->mgr.pub.free_in_buffer = OUTPUT_BUF_SIZE;
-    return TRUE;
+int jpeg_buffer_empty_output_buffer (j_compress_ptr cinfo)
+{
+  ms_buffer_destination_mgr *dest = (ms_buffer_destination_mgr*) cinfo->dest;
+  msBufferAppend(dest->buffer, dest->mgr.data, OUTPUT_BUF_SIZE);
+  dest->mgr.pub.next_output_byte = dest->mgr.data;
+  dest->mgr.pub.free_in_buffer = OUTPUT_BUF_SIZE;
+  return TRUE;
 }
 
 
 int saveAsJPEG(mapObj *map /*not used*/, rasterBufferObj *rb, streamInfo *info,
-      outputFormatObj *format)  {
-    struct jpeg_compress_struct cinfo;
-    struct jpeg_error_mgr jerr;
-    int quality = atoi(msGetOutputFormatOption( format, "QUALITY", "75"));
-    ms_destination_mgr *dest;
-    JSAMPLE *rowdata; 
-    unsigned int row;
-    cinfo.err = jpeg_std_error(&jerr);
-    jpeg_create_compress(&cinfo);
-
-    if (cinfo.dest == NULL)
-    {
-        if(info->fp) {
-            cinfo.dest = (struct jpeg_destination_mgr *)
-                (*cinfo.mem->alloc_small) ((j_common_ptr) &cinfo, JPOOL_PERMANENT,
-                                           sizeof (ms_stream_destination_mgr));
-            ((ms_stream_destination_mgr*)cinfo.dest)->mgr.pub.empty_output_buffer = jpeg_stream_empty_output_buffer;
-            ((ms_stream_destination_mgr*)cinfo.dest)->mgr.pub.term_destination = jpeg_stream_term_destination;
-            ((ms_stream_destination_mgr*)cinfo.dest)->stream = info->fp;
-        } else {
+               outputFormatObj *format)
+{
+  struct jpeg_compress_struct cinfo;
+  struct jpeg_error_mgr jerr;
+  int quality = atoi(msGetOutputFormatOption( format, "QUALITY", "75"));
+  ms_destination_mgr *dest;
+  JSAMPLE *rowdata;
+  unsigned int row;
+  cinfo.err = jpeg_std_error(&jerr);
+  jpeg_create_compress(&cinfo);
+
+  if (cinfo.dest == NULL) {
+    if(info->fp) {
+      cinfo.dest = (struct jpeg_destination_mgr *)
+                   (*cinfo.mem->alloc_small) ((j_common_ptr) &cinfo, JPOOL_PERMANENT,
+                                              sizeof (ms_stream_destination_mgr));
+      ((ms_stream_destination_mgr*)cinfo.dest)->mgr.pub.empty_output_buffer = jpeg_stream_empty_output_buffer;
+      ((ms_stream_destination_mgr*)cinfo.dest)->mgr.pub.term_destination = jpeg_stream_term_destination;
+      ((ms_stream_destination_mgr*)cinfo.dest)->stream = info->fp;
+    } else {
 
-            cinfo.dest = (struct jpeg_destination_mgr *)
-                (*cinfo.mem->alloc_small) ((j_common_ptr) &cinfo, JPOOL_PERMANENT,
-                                           sizeof (ms_buffer_destination_mgr));
-            ((ms_buffer_destination_mgr*)cinfo.dest)->mgr.pub.empty_output_buffer = jpeg_buffer_empty_output_buffer;
-            ((ms_buffer_destination_mgr*)cinfo.dest)->mgr.pub.term_destination = jpeg_buffer_term_destination;
-            ((ms_buffer_destination_mgr*)cinfo.dest)->buffer = info->buffer;
-        }
+      cinfo.dest = (struct jpeg_destination_mgr *)
+                   (*cinfo.mem->alloc_small) ((j_common_ptr) &cinfo, JPOOL_PERMANENT,
+                                              sizeof (ms_buffer_destination_mgr));
+      ((ms_buffer_destination_mgr*)cinfo.dest)->mgr.pub.empty_output_buffer = jpeg_buffer_empty_output_buffer;
+      ((ms_buffer_destination_mgr*)cinfo.dest)->mgr.pub.term_destination = jpeg_buffer_term_destination;
+      ((ms_buffer_destination_mgr*)cinfo.dest)->buffer = info->buffer;
     }
-    dest = (ms_destination_mgr*) cinfo.dest;
-    dest->pub.init_destination = jpeg_init_destination;
-
-    cinfo.image_width = rb->width;
-    cinfo.image_height = rb->height;
-    cinfo.input_components = 3;
-    cinfo.in_color_space = JCS_RGB;
-    jpeg_set_defaults(&cinfo);
-    jpeg_set_quality(&cinfo, quality, TRUE);
-    jpeg_start_compress(&cinfo, TRUE);
-
-    rowdata = (JSAMPLE*)malloc(rb->width*cinfo.input_components*sizeof(JSAMPLE));
-    for(row=0;row<rb->height;row++) {
-        JSAMPLE *pixptr = rowdata;
-        int col;
-        unsigned char *r,*g,*b;
-        r=rb->data.rgba.r+row*rb->data.rgba.row_step;
-        g=rb->data.rgba.g+row*rb->data.rgba.row_step;
-        b=rb->data.rgba.b+row*rb->data.rgba.row_step;
-        for(col=0;col<rb->width;col++) {
-            *(pixptr++) = *r;
-            *(pixptr++) = *g;
-            *(pixptr++) = *b;
-            r+=rb->data.rgba.pixel_step;
-            g+=rb->data.rgba.pixel_step;
-            b+=rb->data.rgba.pixel_step;
-        }
-        (void) jpeg_write_scanlines(&cinfo, &rowdata, 1);
+  }
+  dest = (ms_destination_mgr*) cinfo.dest;
+  dest->pub.init_destination = jpeg_init_destination;
+
+  cinfo.image_width = rb->width;
+  cinfo.image_height = rb->height;
+  cinfo.input_components = 3;
+  cinfo.in_color_space = JCS_RGB;
+  jpeg_set_defaults(&cinfo);
+  jpeg_set_quality(&cinfo, quality, TRUE);
+  jpeg_start_compress(&cinfo, TRUE);
+
+  rowdata = (JSAMPLE*)malloc(rb->width*cinfo.input_components*sizeof(JSAMPLE));
+  for(row=0; row<rb->height; row++) {
+    JSAMPLE *pixptr = rowdata;
+    int col;
+    unsigned char *r,*g,*b;
+    r=rb->data.rgba.r+row*rb->data.rgba.row_step;
+    g=rb->data.rgba.g+row*rb->data.rgba.row_step;
+    b=rb->data.rgba.b+row*rb->data.rgba.row_step;
+    for(col=0; col<rb->width; col++) {
+      *(pixptr++) = *r;
+      *(pixptr++) = *g;
+      *(pixptr++) = *b;
+      r+=rb->data.rgba.pixel_step;
+      g+=rb->data.rgba.pixel_step;
+      b+=rb->data.rgba.pixel_step;
     }
+    (void) jpeg_write_scanlines(&cinfo, &rowdata, 1);
+  }
 
-    /* Step 6: Finish compression */
+  /* Step 6: Finish compression */
 
-    jpeg_finish_compress(&cinfo);
-    jpeg_destroy_compress(&cinfo);
-    free(rowdata);
-    return MS_SUCCESS;
+  jpeg_finish_compress(&cinfo);
+  jpeg_destroy_compress(&cinfo);
+  free(rowdata);
+  return MS_SUCCESS;
 }
 
 /*
  * sort a given list of rgba entries so that all the opaque pixels are at the end
  */
-int remapPaletteForPNG(rasterBufferObj *rb, rgbPixel *rgb, unsigned char *a, int *num_a) {
-   int bot_idx, top_idx, x;
-   int remap[256];
-   unsigned int maxval = rb->data.palette.scaling_maxval; 
-  
-   assert(rb->type == MS_BUFFER_BYTE_PALETTE);
-   
-   /*
-   ** remap the palette colors so that all entries with
-   ** the maximal alpha value (i.e., fully opaque) are at the end and can
-   ** therefore be omitted from the tRNS chunk.  Note that the ordering of
-   ** opaque entries is reversed from how they were previously arranged
-   ** --not that this should matter to anyone.
-   */
-   
-   for (top_idx = rb->data.palette.num_entries-1, bot_idx = x = 0;  x < rb->data.palette.num_entries;  ++x) {
-     if (rb->data.palette.palette[x].a == maxval)
-         remap[x] = top_idx--;
-     else
-         remap[x] = bot_idx++;
-   }
-   /* sanity check:  top and bottom indices should have just crossed paths */
-   if (bot_idx != top_idx + 1) {
-     msSetError(MS_MISCERR,"quantization sanity check failed","createPNGPalette()");
-     return MS_FAILURE;
-   }
-   
-   *num_a = bot_idx;
-   
-   for(x=0;x<rb->width*rb->height;x++)
-      rb->data.palette.pixels[x] = remap[rb->data.palette.pixels[x]];
-   
-
-   for (x = 0; x < rb->data.palette.num_entries; ++x) {
-      if(maxval == 255) {
-         a[remap[x]] = rb->data.palette.palette[x].a;
-         rgb[remap[x]].r = rb->data.palette.palette[x].r;
-         rgb[remap[x]].g = rb->data.palette.palette[x].g;
-         rgb[remap[x]].b = rb->data.palette.palette[x].b;
-      } else {
-         /* rescale palette */
-         rgb[remap[x]].r = (rb->data.palette.palette[x].r * 255 + (maxval >> 1)) / maxval;
-         rgb[remap[x]].g = (rb->data.palette.palette[x].g * 255 + (maxval >> 1)) / maxval;
-         rgb[remap[x]].b = (rb->data.palette.palette[x].b * 255 + (maxval >> 1)) / maxval;
-         a[remap[x]] = (rb->data.palette.palette[x].a * 255 + (maxval >> 1)) / maxval;
-      }
-      if(a[remap[x]] != 255) {
-         /* un-premultiply pixels */
-         double da = 255.0/a[remap[x]];
-         rgb[remap[x]].r *=  da;
-         rgb[remap[x]].g *=  da;
-         rgb[remap[x]].b *=  da;
-      }
-   }
-   
-   return MS_SUCCESS;
+int remapPaletteForPNG(rasterBufferObj *rb, rgbPixel *rgb, unsigned char *a, int *num_a)
+{
+  int bot_idx, top_idx, x;
+  int remap[256];
+  unsigned int maxval = rb->data.palette.scaling_maxval;
+
+  assert(rb->type == MS_BUFFER_BYTE_PALETTE);
+
+  /*
+  ** remap the palette colors so that all entries with
+  ** the maximal alpha value (i.e., fully opaque) are at the end and can
+  ** therefore be omitted from the tRNS chunk.  Note that the ordering of
+  ** opaque entries is reversed from how they were previously arranged
+  ** --not that this should matter to anyone.
+  */
+
+  for (top_idx = rb->data.palette.num_entries-1, bot_idx = x = 0;  x < rb->data.palette.num_entries;  ++x) {
+    if (rb->data.palette.palette[x].a == maxval)
+      remap[x] = top_idx--;
+    else
+      remap[x] = bot_idx++;
+  }
+  /* sanity check:  top and bottom indices should have just crossed paths */
+  if (bot_idx != top_idx + 1) {
+    msSetError(MS_MISCERR,"quantization sanity check failed","createPNGPalette()");
+    return MS_FAILURE;
+  }
+
+  *num_a = bot_idx;
+
+  for(x=0; x<rb->width*rb->height; x++)
+    rb->data.palette.pixels[x] = remap[rb->data.palette.pixels[x]];
+
+
+  for (x = 0; x < rb->data.palette.num_entries; ++x) {
+    if(maxval == 255) {
+      a[remap[x]] = rb->data.palette.palette[x].a;
+      rgb[remap[x]].r = rb->data.palette.palette[x].r;
+      rgb[remap[x]].g = rb->data.palette.palette[x].g;
+      rgb[remap[x]].b = rb->data.palette.palette[x].b;
+    } else {
+      /* rescale palette */
+      rgb[remap[x]].r = (rb->data.palette.palette[x].r * 255 + (maxval >> 1)) / maxval;
+      rgb[remap[x]].g = (rb->data.palette.palette[x].g * 255 + (maxval >> 1)) / maxval;
+      rgb[remap[x]].b = (rb->data.palette.palette[x].b * 255 + (maxval >> 1)) / maxval;
+      a[remap[x]] = (rb->data.palette.palette[x].a * 255 + (maxval >> 1)) / maxval;
+    }
+    if(a[remap[x]] != 255) {
+      /* un-premultiply pixels */
+      double da = 255.0/a[remap[x]];
+      rgb[remap[x]].r *=  da;
+      rgb[remap[x]].g *=  da;
+      rgb[remap[x]].b *=  da;
+    }
+  }
+
+  return MS_SUCCESS;
 }
 
-int savePalettePNG(rasterBufferObj *rb, streamInfo *info, int compression) {
-   png_infop info_ptr;
-   rgbPixel rgb[256];
-   unsigned char a[256];
-   int num_a;
-   int row,sample_depth;
-   png_structp png_ptr = png_create_write_struct(
-         PNG_LIBPNG_VER_STRING, NULL,NULL,NULL);
-    
-   assert(rb->type == MS_BUFFER_BYTE_PALETTE);
-
-   if (!png_ptr)
-      return (MS_FAILURE);
+int savePalettePNG(rasterBufferObj *rb, streamInfo *info, int compression)
+{
+  png_infop info_ptr;
+  rgbPixel rgb[256];
+  unsigned char a[256];
+  int num_a;
+  int row,sample_depth;
+  png_structp png_ptr = png_create_write_struct(
+                          PNG_LIBPNG_VER_STRING, NULL,NULL,NULL);
+
+  assert(rb->type == MS_BUFFER_BYTE_PALETTE);
+
+  if (!png_ptr)
+    return (MS_FAILURE);
+
+  png_set_compression_level(png_ptr, compression);
+  png_set_filter (png_ptr,0, PNG_FILTER_NONE);
+
+  info_ptr = png_create_info_struct(png_ptr);
+  if (!info_ptr) {
+    png_destroy_write_struct(&png_ptr,
+                             (png_infopp)NULL);
+    return (MS_FAILURE);
+  }
 
-   info_ptr = png_create_info_struct(png_ptr);
-   if (!info_ptr)
-   {
-      png_destroy_write_struct(&png_ptr,
-            (png_infopp)NULL);
-      return (MS_FAILURE);
-   }
+  if (setjmp(png_jmpbuf(png_ptr))) {
+    png_destroy_write_struct(&png_ptr, &info_ptr);
+    return (MS_FAILURE);
+  }
+  if(info->fp)
+    png_set_write_fn(png_ptr,info, png_write_data_to_stream, png_flush_data);
+  else
+    png_set_write_fn(png_ptr,info, png_write_data_to_buffer, png_flush_data);
 
-   if (setjmp(png_jmpbuf(png_ptr)))
-   {
-      png_destroy_write_struct(&png_ptr, &info_ptr);
-      return (MS_FAILURE);
-   }
-   if(info->fp) 
-      png_set_write_fn(png_ptr,info, png_write_data_to_stream, png_flush_data);
-   else
-      png_set_write_fn(png_ptr,info, png_write_data_to_buffer, png_flush_data);
-   
-   png_set_compression_level(png_ptr, compression);
-   
-   if (rb->data.palette.num_entries <= 2)
+
+  if (rb->data.palette.num_entries <= 2)
     sample_depth = 1;
-   else if (rb->data.palette.num_entries <= 4)
+  else if (rb->data.palette.num_entries <= 4)
     sample_depth = 2;
-   else if (rb->data.palette.num_entries <= 16)
+  else if (rb->data.palette.num_entries <= 16)
     sample_depth = 4;
-   else
+  else
     sample_depth = 8;
-   
-   png_set_IHDR(png_ptr, info_ptr, rb->width, rb->height,
+
+  png_set_IHDR(png_ptr, info_ptr, rb->width, rb->height,
                sample_depth, PNG_COLOR_TYPE_PALETTE,
                0, PNG_COMPRESSION_TYPE_DEFAULT,
                PNG_FILTER_TYPE_DEFAULT);
-   
-   remapPaletteForPNG(rb,rgb,a,&num_a);
-
-   png_set_PLTE(png_ptr, info_ptr, (png_colorp)(rgb),rb->data.palette.num_entries);
-   if(num_a)
-      png_set_tRNS(png_ptr, info_ptr, a,num_a, NULL);
-
-   png_write_info(png_ptr, info_ptr);
-   png_set_packing(png_ptr);
-
-   for(row=0;row<rb->height;row++) {
-      unsigned char *rowptr = &(rb->data.palette.pixels[row*rb->width]);
-      png_write_row(png_ptr, rowptr);
-   }
-   png_write_end(png_ptr, info_ptr);
-   png_destroy_write_struct(&png_ptr, &info_ptr);
-   return MS_SUCCESS;
+
+  remapPaletteForPNG(rb,rgb,a,&num_a);
+
+  png_set_PLTE(png_ptr, info_ptr, (png_colorp)(rgb),rb->data.palette.num_entries);
+  if(num_a)
+    png_set_tRNS(png_ptr, info_ptr, a,num_a, NULL);
+
+  png_write_info(png_ptr, info_ptr);
+  png_set_packing(png_ptr);
+
+  for(row=0; row<rb->height; row++) {
+    unsigned char *rowptr = &(rb->data.palette.pixels[row*rb->width]);
+    png_write_row(png_ptr, rowptr);
+  }
+  png_write_end(png_ptr, info_ptr);
+  png_destroy_write_struct(&png_ptr, &info_ptr);
+  return MS_SUCCESS;
 }
 
-int readPalette(const char *palette, rgbaPixel *entries, unsigned int *nEntries, int useAlpha) {
-   FILE *stream = NULL;
-   char buffer[MS_BUFFER_LENGTH];
-   int r,g,b,a;
-   *nEntries = 0;
-   
-   stream = fopen(palette, "r");
-   if(!stream) {
+int readPalette(const char *palette, rgbaPixel *entries, unsigned int *nEntries, int useAlpha)
+{
+  FILE *stream = NULL;
+  char buffer[MS_BUFFER_LENGTH];
+  int r,g,b,a;
+  *nEntries = 0;
+
+  stream = fopen(palette, "r");
+  if(!stream) {
     msSetError(MS_IOERR, "Error opening palette file %s.", "readPalette()", palette);
     return MS_FAILURE;
-   }
-   
-   while(fgets(buffer, MS_BUFFER_LENGTH, stream) && *nEntries<256) 
-   { /* while there are colors to load */
-      if(buffer[0] == '#' || buffer[0] == '\n' || buffer[0] == '\r')
-        continue; /* skip comments and blank lines */
-      if(!useAlpha) {
-         if(3 != sscanf(buffer,"%d,%d,%d\n",&r,&g,&b)) {
-            msSetError(MS_MISCERR,"failed to parse color %d r,g,b triplet in line \"%s\" from file %s","readPalette()",*nEntries+1,buffer,palette);
-            return MS_FAILURE;
-         }
-      }
-      else {
-         if(4 != sscanf(buffer,"%d,%d,%d,%d\n",&r,&g,&b,&a)) {
-            msSetError(MS_MISCERR,"failed to parse color %d r,g,b,a quadruplet in line \"%s\" from file %s","readPalette()",*nEntries+1,buffer,palette);
-            return MS_FAILURE;
-         }
+  }
+
+  while(fgets(buffer, MS_BUFFER_LENGTH, stream) && *nEntries<256) {
+    /* while there are colors to load */
+    if(buffer[0] == '#' || buffer[0] == '\n' || buffer[0] == '\r')
+      continue; /* skip comments and blank lines */
+    if(!useAlpha) {
+      if(3 != sscanf(buffer,"%d,%d,%d\n",&r,&g,&b)) {
+        msSetError(MS_MISCERR,"failed to parse color %d r,g,b triplet in line \"%s\" from file %s","readPalette()",*nEntries+1,buffer,palette);
+        return MS_FAILURE;
       }
-      if(useAlpha && a != 255) {
-         double da = a/255.0;
-         entries[*nEntries].r = r * da;
-         entries[*nEntries].g = g * da;
-         entries[*nEntries].b = b * da;
-         entries[*nEntries].a = a;
-      } else {
-         entries[*nEntries].r = r;
-         entries[*nEntries].g = g;
-         entries[*nEntries].b = b;
-         entries[*nEntries].a = 255;
+    } else {
+      if(4 != sscanf(buffer,"%d,%d,%d,%d\n",&r,&g,&b,&a)) {
+        msSetError(MS_MISCERR,"failed to parse color %d r,g,b,a quadruplet in line \"%s\" from file %s","readPalette()",*nEntries+1,buffer,palette);
+        return MS_FAILURE;
       }
-      (*nEntries)++;
-   }
-   fclose(stream);
-   return MS_SUCCESS;
+    }
+    if(useAlpha && a != 255) {
+      double da = a/255.0;
+      entries[*nEntries].r = r * da;
+      entries[*nEntries].g = g * da;
+      entries[*nEntries].b = b * da;
+      entries[*nEntries].a = a;
+    } else {
+      entries[*nEntries].r = r;
+      entries[*nEntries].g = g;
+      entries[*nEntries].b = b;
+      entries[*nEntries].a = 255;
+    }
+    (*nEntries)++;
+  }
+  fclose(stream);
+  return MS_SUCCESS;
 }
 
-int saveAsPNG(mapObj *map,rasterBufferObj *rb, streamInfo *info, outputFormatObj *format) {
-    int force_pc256 = MS_FALSE;
-    int force_palette = MS_FALSE;
-   
-    int ret = MS_FAILURE;
-
-    const char *force_string,*zlib_compression;
-    int compression = -1;
-
-    zlib_compression = msGetOutputFormatOption( format, "COMPRESSION", NULL);
-    if(zlib_compression && *zlib_compression) {
-      char *endptr;
-      compression = strtol(zlib_compression,&endptr,10);
-      if(*endptr || compression<-1 || compression>9) {
-         msSetError(MS_MISCERR,"failed to parse FORMATOPTION \"COMPRESSION=%s\", expecting integer from 0 to 9.","saveAsPNG()",zlib_compression);
-         return MS_FAILURE;
+int saveAsPNG(mapObj *map,rasterBufferObj *rb, streamInfo *info, outputFormatObj *format)
+{
+  int force_pc256 = MS_FALSE;
+  int force_palette = MS_FALSE;
+
+  int ret = MS_FAILURE;
+
+  const char *force_string,*zlib_compression;
+  int compression = -1;
+
+  zlib_compression = msGetOutputFormatOption( format, "COMPRESSION", NULL);
+  if(zlib_compression && *zlib_compression) {
+    char *endptr;
+    compression = strtol(zlib_compression,&endptr,10);
+    if(*endptr || compression<-1 || compression>9) {
+      msSetError(MS_MISCERR,"failed to parse FORMATOPTION \"COMPRESSION=%s\", expecting integer from 0 to 9.","saveAsPNG()",zlib_compression);
+      return MS_FAILURE;
+    }
+  }
+
+
+  force_string = msGetOutputFormatOption( format, "QUANTIZE_FORCE", NULL );
+  if( force_string && (strcasecmp(force_string,"on") == 0  || strcasecmp(force_string,"yes") == 0 || strcasecmp(force_string,"true") == 0) )
+    force_pc256 = MS_TRUE;
+
+  force_string = msGetOutputFormatOption( format, "PALETTE_FORCE", NULL );
+  if( force_string && (strcasecmp(force_string,"on") == 0  || strcasecmp(force_string,"yes") == 0 || strcasecmp(force_string,"true") == 0) )
+    force_palette = MS_TRUE;
+
+  if(force_pc256 || force_palette) {
+    rasterBufferObj qrb;
+    rgbaPixel palette[256], paletteGiven[256];
+    unsigned int numPaletteGivenEntries;
+    memset(&qrb,0,sizeof(rasterBufferObj));
+    qrb.type = MS_BUFFER_BYTE_PALETTE;
+    qrb.width = rb->width;
+    qrb.height = rb->height;
+    qrb.data.palette.pixels = (unsigned char*)malloc(qrb.width*qrb.height*sizeof(unsigned char));
+    qrb.data.palette.scaling_maxval = 255;
+    if(force_pc256) {
+      qrb.data.palette.palette = palette;
+      qrb.data.palette.num_entries = atoi(msGetOutputFormatOption( format, "QUANTIZE_COLORS", "256"));
+      ret = msQuantizeRasterBuffer(rb,&(qrb.data.palette.num_entries),qrb.data.palette.palette,
+                                   NULL, 0,
+                                   &qrb.data.palette.scaling_maxval);
+    } else {
+      int colorsWanted = atoi(msGetOutputFormatOption( format, "QUANTIZE_COLORS", "0"));
+      const char *palettePath = msGetOutputFormatOption( format, "PALETTE", "palette.txt");
+      char szPath[MS_MAXPATHLEN];
+      if(map) {
+        msBuildPath(szPath, map->mappath, palettePath);
+        palettePath = szPath;
+      }
+      if(readPalette(palettePath,paletteGiven,&numPaletteGivenEntries,format->transparent) != MS_SUCCESS) {
+        return MS_FAILURE;
+      }
+
+      if(numPaletteGivenEntries == 256 || colorsWanted == 0) {
+        qrb.data.palette.palette = paletteGiven;
+        qrb.data.palette.num_entries = numPaletteGivenEntries;
+        ret = MS_SUCCESS;
+
+        /* we have a full palette and don't want an additional quantization step */
+      } else {
+        /* quantize the image, and mix our colours in the resulting palette */
+        qrb.data.palette.palette = palette;
+        qrb.data.palette.num_entries = MS_MAX(colorsWanted,numPaletteGivenEntries);
+        ret = msQuantizeRasterBuffer(rb,&(qrb.data.palette.num_entries),qrb.data.palette.palette,
+                                     paletteGiven,numPaletteGivenEntries,
+                                     &qrb.data.palette.scaling_maxval);
       }
     }
+    if(ret != MS_FAILURE) {
+      ret = msClassifyRasterBuffer(rb,&qrb);
+      ret = savePalettePNG(&qrb,info,compression);
+    }
+    msFree(qrb.data.palette.pixels);
+    return ret;
+  } else if(rb->type == MS_BUFFER_BYTE_RGBA) {
+    png_infop info_ptr;
+    int color_type;
+    int row;
+    unsigned int *rowdata;
+    png_structp png_ptr = png_create_write_struct(
+                            PNG_LIBPNG_VER_STRING, NULL,NULL,NULL);
 
-   
-    force_string = msGetOutputFormatOption( format, "QUANTIZE_FORCE", NULL );
-    if( force_string && (strcasecmp(force_string,"on") == 0  || strcasecmp(force_string,"yes") == 0 || strcasecmp(force_string,"true") == 0) )
-        force_pc256 = MS_TRUE;
-
-    force_string = msGetOutputFormatOption( format, "PALETTE_FORCE", NULL );
-    if( force_string && (strcasecmp(force_string,"on") == 0  || strcasecmp(force_string,"yes") == 0 || strcasecmp(force_string,"true") == 0) )
-        force_palette = MS_TRUE;
-       
-    if(force_pc256 || force_palette) {
-        rasterBufferObj qrb;
-        rgbaPixel palette[256], paletteGiven[256];
-        unsigned int numPaletteGivenEntries;
-        memset(&qrb,0,sizeof(rasterBufferObj));
-        qrb.type = MS_BUFFER_BYTE_PALETTE;
-        qrb.width = rb->width;
-        qrb.height = rb->height;
-        qrb.data.palette.pixels = (unsigned char*)malloc(qrb.width*qrb.height*sizeof(unsigned char));
-        qrb.data.palette.scaling_maxval = 255;
-        if(force_pc256) {
-            qrb.data.palette.palette = palette;
-            qrb.data.palette.num_entries = atoi(msGetOutputFormatOption( format, "QUANTIZE_COLORS", "256"));
-            ret = msQuantizeRasterBuffer(rb,&(qrb.data.palette.num_entries),qrb.data.palette.palette,
-                  NULL, 0,
-                  &qrb.data.palette.scaling_maxval);
-        } else {
-            int colorsWanted = atoi(msGetOutputFormatOption( format, "QUANTIZE_COLORS", "0"));
-            const char *palettePath = msGetOutputFormatOption( format, "PALETTE", "palette.txt");
-            char szPath[MS_MAXPATHLEN];
-            if(map) {
-               msBuildPath(szPath, map->mappath, palettePath);
-               palettePath = szPath;
-            }
-            if(readPalette(palettePath,paletteGiven,&numPaletteGivenEntries,format->transparent) != MS_SUCCESS) {
-                return MS_FAILURE;
-            }
-         
-            if(numPaletteGivenEntries == 256 || colorsWanted == 0) {
-                qrb.data.palette.palette = paletteGiven;
-                qrb.data.palette.num_entries = numPaletteGivenEntries;
-                ret = MS_SUCCESS;
-            
-                //we have a full palette and don't want an additional quantization step
-            } else {
-                //quantize the image, and mix our colours in the resulting palette
-                qrb.data.palette.palette = palette;
-                qrb.data.palette.num_entries = MS_MAX(colorsWanted,numPaletteGivenEntries);
-                ret = msQuantizeRasterBuffer(rb,&(qrb.data.palette.num_entries),qrb.data.palette.palette,
-                                             paletteGiven,numPaletteGivenEntries,
-                                             &qrb.data.palette.scaling_maxval);            
-            }
-        }
-        if(ret != MS_FAILURE) {
-            ret = msClassifyRasterBuffer(rb,&qrb);
-            ret = savePalettePNG(&qrb,info,compression);  
-        }
-        msFree(qrb.data.palette.pixels);
-        return ret;
+    if (!png_ptr)
+      return (MS_FAILURE);
+
+    png_set_compression_level(png_ptr, compression);
+    png_set_filter (png_ptr,0, PNG_FILTER_NONE);
+
+    info_ptr = png_create_info_struct(png_ptr);
+    if (!info_ptr) {
+      png_destroy_write_struct(&png_ptr,
+                               (png_infopp)NULL);
+      return (MS_FAILURE);
     }
-    else if(rb->type == MS_BUFFER_BYTE_RGBA) {
-        png_infop info_ptr; 
-        int color_type;
-        int row;
-        unsigned int *rowdata;
-        png_structp png_ptr = png_create_write_struct(
-            PNG_LIBPNG_VER_STRING, NULL,NULL,NULL);
-				
-        if (!png_ptr)
-            return (MS_FAILURE);
-	
-        info_ptr = png_create_info_struct(png_ptr);
-        if (!info_ptr)
-        {
-            png_destroy_write_struct(&png_ptr,
-                                     (png_infopp)NULL);
-            return (MS_FAILURE);
-        }
-	
-        if (setjmp(png_jmpbuf(png_ptr)))
-        {
-            png_destroy_write_struct(&png_ptr, &info_ptr);
-            return (MS_FAILURE);
+
+    if (setjmp(png_jmpbuf(png_ptr))) {
+      png_destroy_write_struct(&png_ptr, &info_ptr);
+      return (MS_FAILURE);
+    }
+    if(info->fp)
+      png_set_write_fn(png_ptr,info, png_write_data_to_stream, png_flush_data);
+    else
+      png_set_write_fn(png_ptr,info, png_write_data_to_buffer, png_flush_data);
+
+    if(rb->data.rgba.a)
+      color_type = PNG_COLOR_TYPE_RGB_ALPHA;
+    else
+      color_type = PNG_COLOR_TYPE_RGB;
+
+    png_set_IHDR(png_ptr, info_ptr, rb->width, rb->height,
+                 8, color_type, PNG_INTERLACE_NONE,
+                 PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
+
+    png_write_info(png_ptr, info_ptr);
+
+    if(!rb->data.rgba.a && rb->data.rgba.pixel_step==4)
+      png_set_filler(png_ptr, 0, PNG_FILLER_AFTER);
+
+    rowdata = (unsigned int*)malloc(rb->width*sizeof(unsigned int));
+    for(row=0; row<rb->height; row++) {
+      unsigned int *pixptr = rowdata;
+      int col;
+      unsigned char *a,*r,*g,*b;
+      r=rb->data.rgba.r+row*rb->data.rgba.row_step;
+      g=rb->data.rgba.g+row*rb->data.rgba.row_step;
+      b=rb->data.rgba.b+row*rb->data.rgba.row_step;
+      if(rb->data.rgba.a) {
+        a=rb->data.rgba.a+row*rb->data.rgba.row_step;
+        for(col=0; col<rb->width; col++) {
+          if(*a) {
+            double da = *a/255.0;
+            unsigned char *pix = (unsigned char*)pixptr;
+            pix[0] = *r/da;
+            pix[1] = *g/da;
+            pix[2] = *b/da;
+            pix[3] = *a;
+          } else {
+            *pixptr=0;
+          }
+          pixptr++;
+          a+=rb->data.rgba.pixel_step;
+          r+=rb->data.rgba.pixel_step;
+          g+=rb->data.rgba.pixel_step;
+          b+=rb->data.rgba.pixel_step;
         }
-        if(info->fp) 
-            png_set_write_fn(png_ptr,info, png_write_data_to_stream, png_flush_data);
-        else
-            png_set_write_fn(png_ptr,info, png_write_data_to_buffer, png_flush_data);
-	
-        if(rb->data.rgba.a)
-            color_type = PNG_COLOR_TYPE_RGB_ALPHA;
-        else
-            color_type = PNG_COLOR_TYPE_RGB;
-	
-        png_set_compression_level(png_ptr, compression);
-        png_set_IHDR(png_ptr, info_ptr, rb->width, rb->height,
-                     8, color_type, PNG_INTERLACE_NONE,
-                     PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
-	
-        png_write_info(png_ptr, info_ptr);
-	
-        if(!rb->data.rgba.a && rb->data.rgba.pixel_step==4)
-            png_set_filler(png_ptr, 0, PNG_FILLER_AFTER);
-	
-        rowdata = (unsigned int*)malloc(rb->width*sizeof(unsigned int));
-        for(row=0;row<rb->height;row++) {
-            unsigned int *pixptr = rowdata;
-            int col;
-            unsigned char *a,*r,*g,*b;
-            r=rb->data.rgba.r+row*rb->data.rgba.row_step;
-            g=rb->data.rgba.g+row*rb->data.rgba.row_step;
-            b=rb->data.rgba.b+row*rb->data.rgba.row_step;
-            if(rb->data.rgba.a) {
-                a=rb->data.rgba.a+row*rb->data.rgba.row_step;
-                for(col=0;col<rb->width;col++) {
-                    if(*a) {
-                        double da = *a/255.0;
-                        unsigned char *pix = (unsigned char*)pixptr;
-                        pix[0] = *r/da;
-                        pix[1] = *g/da;
-                        pix[2] = *b/da;
-                        pix[3] = *a;
-                    } else {
-                        *pixptr=0;
-                    }
-                    pixptr++;
-                    a+=rb->data.rgba.pixel_step;
-                    r+=rb->data.rgba.pixel_step;
-                    g+=rb->data.rgba.pixel_step;
-                    b+=rb->data.rgba.pixel_step;
-                }
-            } else {
-                for(col=0;col<rb->width;col++) {
-                    unsigned char *pix = (unsigned char*)pixptr;
-                    pix[0] = *r;
-                    pix[1] = *g;
-                    pix[2] = *b;
-                    pixptr++;
-                    r+=rb->data.rgba.pixel_step;
-                    g+=rb->data.rgba.pixel_step;
-                    b+=rb->data.rgba.pixel_step;
-                }
-            }
-	
-            png_write_row(png_ptr,(png_bytep)rowdata);
-	
+      } else {
+        for(col=0; col<rb->width; col++) {
+          unsigned char *pix = (unsigned char*)pixptr;
+          pix[0] = *r;
+          pix[1] = *g;
+          pix[2] = *b;
+          pixptr++;
+          r+=rb->data.rgba.pixel_step;
+          g+=rb->data.rgba.pixel_step;
+          b+=rb->data.rgba.pixel_step;
         }
-        png_write_end(png_ptr, info_ptr);
-        free(rowdata);
-        png_destroy_write_struct(&png_ptr, &info_ptr);
-        return MS_SUCCESS;
-    } else {
-        msSetError(MS_MISCERR,"Unknown buffer type","saveAsPNG()");
-        return MS_FAILURE;
+      }
+
+      png_write_row(png_ptr,(png_bytep)rowdata);
+
     }
+    png_write_end(png_ptr, info_ptr);
+    free(rowdata);
+    png_destroy_write_struct(&png_ptr, &info_ptr);
+    return MS_SUCCESS;
+  } else {
+    msSetError(MS_MISCERR,"Unknown buffer type","saveAsPNG()");
+    return MS_FAILURE;
+  }
 }
 
 /* For platforms with incomplete ANSI defines. Fortunately,
@@ -543,6 +553,9 @@ int saveAsPNG(mapObj *map,rasterBufferObj *rb, streamInfo *info, outputFormatObj
 #define SEEK_SET 0
 #endif /* SEEK_SET */
 
+
+
+#ifdef USE_GD
 /* #include <math.h> */
 /* #include <string.h> */
 /* #include <stdlib.h> */
@@ -550,8 +563,7 @@ int saveAsPNG(mapObj *map,rasterBufferObj *rb, streamInfo *info, outputFormatObj
 
 /* this is used for creating images in main memory */
 
-typedef struct fileIOCtx
-{
+typedef struct fileIOCtx {
   gdIOCtx ctx;
   FILE *f;
 }
@@ -640,392 +652,426 @@ gdIOCtx *msNewGDFileCtx (FILE * f)
   return (gdIOCtx *) ctx;
 }
 
-static const unsigned char PNGsig[8] = {137, 80, 78, 71, 13, 10, 26, 10}; /* 89 50 4E 47 0D 0A 1A 0A hex */ 
+static const unsigned char PNGsig[8] = {137, 80, 78, 71, 13, 10, 26, 10}; /* 89 50 4E 47 0D 0A 1A 0A hex */
 
-int msLoadGDRasterBufferFromFile(char *path, rasterBufferObj *rb) {
-    FILE *stream;
-    char bytes[8];
-    gdImagePtr img = NULL; 
-    stream = fopen(path,"rb");
-    if(!stream) {
-        msSetError(MS_MISCERR, "unable to open file %s for reading", "loadGDImg()", path);
-        return MS_FAILURE;
-    }
-    if(1 != fread(bytes,8,1,stream)) /* read some bytes to try and identify the file */
-    {
-        msSetError(MS_MISCERR, "Unable to read header from image file %s", "msLoadGDRasterBufferFromFile()",path);
-        return MS_FAILURE;
-    }
-    rewind(stream); /* reset the image for the readers */
-    if(memcmp(bytes,"GIF8",4)==0) {
+int msLoadGDRasterBufferFromFile(char *path, rasterBufferObj *rb)
+{
+  FILE *stream;
+  char bytes[8];
+  gdImagePtr img = NULL;
+  stream = fopen(path,"rb");
+  if(!stream) {
+    msSetError(MS_MISCERR, "unable to open file %s for reading", "loadGDImg()", path);
+    return MS_FAILURE;
+  }
+  if(1 != fread(bytes,8,1,stream)) { /* read some bytes to try and identify the file */
+    msSetError(MS_MISCERR, "Unable to read header from image file %s", "msLoadGDRasterBufferFromFile()",path);
+    return MS_FAILURE;
+  }
+  rewind(stream); /* reset the image for the readers */
+  if(memcmp(bytes,"GIF8",4)==0) {
 #ifdef USE_GD_GIF
-        gdIOCtx *ctx;
-        ctx = msNewGDFileCtx(stream);
-        img = gdImageCreateFromGifCtx(ctx);
-        ctx->gd_free(ctx);
+    gdIOCtx *ctx;
+    ctx = msNewGDFileCtx(stream);
+    img = gdImageCreateFromGifCtx(ctx);
+    ctx->gd_free(ctx);
 #else
-        msSetError(MS_MISCERR, "Unable to load GIF symbol.", "msLoadGDRasterBufferFromFile()");
-        return MS_FAILURE;
+    msSetError(MS_MISCERR, "Unable to load GIF symbol.", "msLoadGDRasterBufferFromFile()");
+    return MS_FAILURE;
 #endif
-    } else if (memcmp(bytes,PNGsig,8)==0) {
+  } else if (memcmp(bytes,PNGsig,8)==0) {
 #ifdef USE_GD_PNG
-        gdIOCtx *ctx;
-        ctx = msNewGDFileCtx(stream);
-        img = gdImageCreateFromPngCtx(ctx);
-        ctx->gd_free(ctx);
+    gdIOCtx *ctx;
+    ctx = msNewGDFileCtx(stream);
+    img = gdImageCreateFromPngCtx(ctx);
+    ctx->gd_free(ctx);
 #else
-        msSetError(MS_MISCERR, "Unable to load PNG symbol.", "msLoadGDRasterBufferFromFile()");
-        return MS_FAILURE;
+    msSetError(MS_MISCERR, "Unable to load PNG symbol.", "msLoadGDRasterBufferFromFile()");
+    return MS_FAILURE;
 #endif
-    }
-    
-    fclose(stream);
+  }
 
-    if(!img) {
-        msSetError(MS_GDERR, NULL, "loadGDImg()");
-        rb->type = MS_BUFFER_NONE;
-        return MS_FAILURE;
-    }
-    if(gdImageTrueColor(img)) {
-       int x,y;
-       gdImagePtr pimg = gdImageCreate(gdImageSX(img),gdImageSY(img));
-       gdImageColorAllocateAlpha(pimg,0,0,0,127);
-       for(y = 0 ; y < gdImageSY(img); y++) {
-          for(x = 0; x < gdImageSX(img); x++) {
-             int pix = gdImageGetTrueColorPixel(img,x,y);
-             if(gdTrueColorGetAlpha(pix) == 127) {
-                gdImageSetPixel(pimg,x,y,0);
-                pimg->transparent = 0;
-             } else {
-                gdImageSetPixel(pimg,x,y,gdImageColorResolveAlpha(pimg,gdTrueColorGetRed(pix),gdTrueColorGetGreen(pix),
-                      gdTrueColorGetBlue(pix),gdTrueColorGetAlpha(pix)));
-             }
-             
-          }
-       }
-       gdImageDestroy(img);
-       img = pimg;
+  fclose(stream);
+
+  if(!img) {
+    msSetError(MS_GDERR, NULL, "loadGDImg()");
+    rb->type = MS_BUFFER_NONE;
+    return MS_FAILURE;
+  }
+  if(gdImageTrueColor(img)) {
+    int x,y;
+    gdImagePtr pimg = gdImageCreate(gdImageSX(img),gdImageSY(img));
+    gdImageColorAllocateAlpha(pimg,0,0,0,127);
+    for(y = 0 ; y < gdImageSY(img); y++) {
+      for(x = 0; x < gdImageSX(img); x++) {
+        int pix = gdImageGetTrueColorPixel(img,x,y);
+        if(gdTrueColorGetAlpha(pix) == 127) {
+          gdImageSetPixel(pimg,x,y,0);
+          pimg->transparent = 0;
+        } else {
+          gdImageSetPixel(pimg,x,y,gdImageColorResolveAlpha(pimg,gdTrueColorGetRed(pix),gdTrueColorGetGreen(pix),
+                          gdTrueColorGetBlue(pix),gdTrueColorGetAlpha(pix)));
+        }
+
+      }
     }
-    rb->type = MS_BUFFER_GD;
-    rb->width = gdImageSX(img);
-    rb->height = gdImageSY(img);
-    rb->data.gd_img = img;
-    return MS_SUCCESS;
+    gdImageDestroy(img);
+    img = pimg;
+  }
+  rb->type = MS_BUFFER_GD;
+  rb->width = gdImageSX(img);
+  rb->height = gdImageSY(img);
+  rb->data.gd_img = img;
+  return MS_SUCCESS;
 }
+#endif
 
-int readPNG(char *path, rasterBufferObj *rb) {
-    png_uint_32 width,height,row_bytes;
-    int bit_depth,color_type,i;
-    unsigned char **row_pointers;
-    png_structp png_ptr = NULL;
-    png_infop info_ptr = NULL;
-    
-    FILE *stream = fopen(path,"rb");
-    if(!stream)
-    	return MS_FAILURE;
-
-    /* could pass pointers to user-defined error handlers instead of NULLs: */
-    png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
-    if (!png_ptr)
-        return MS_FAILURE;   /* out of memory */
+int readPNG(char *path, rasterBufferObj *rb)
+{
+  png_uint_32 width,height;
+  unsigned char *a,*r,*g,*b;
+  int bit_depth,color_type,i;
+  unsigned char **row_pointers;
+  png_structp png_ptr = NULL;
+  png_infop info_ptr = NULL;
+
+  FILE *stream = fopen(path,"rb");
+  if(!stream)
+    return MS_FAILURE;
 
-    info_ptr = png_create_info_struct(png_ptr);
-    if (!info_ptr) {
-        png_destroy_read_struct(&png_ptr, NULL, NULL);
-        return MS_FAILURE;   /* out of memory */
-    }
+  /* could pass pointers to user-defined error handlers instead of NULLs: */
+  png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
+  if (!png_ptr)
+    return MS_FAILURE;   /* out of memory */
 
-    if(setjmp(png_jmpbuf(png_ptr))) {
-        png_destroy_read_struct(&png_ptr,&info_ptr,NULL);
-        return MS_FAILURE;
-    }
+  info_ptr = png_create_info_struct(png_ptr);
+  if (!info_ptr) {
+    png_destroy_read_struct(&png_ptr, NULL, NULL);
+    return MS_FAILURE;   /* out of memory */
+  }
+
+  if(setjmp(png_jmpbuf(png_ptr))) {
+    png_destroy_read_struct(&png_ptr,&info_ptr,NULL);
+    return MS_FAILURE;
+  }
 
-    png_init_io(png_ptr,stream);
-    png_read_info(png_ptr,info_ptr);
-    png_get_IHDR(png_ptr, info_ptr, &width, &height,
-            &bit_depth, &color_type,
-            NULL,NULL,NULL);
-    
-    rb->width = width;
-    rb->height = height;
-    rb->type = MS_BUFFER_BYTE_RGBA;
-    rb->data.rgba.pixels = (unsigned char*)malloc(width*height*4*sizeof(unsigned char)); 
-    row_pointers = (unsigned char**)malloc(height*sizeof(unsigned char*));
-    rb->data.rgba.pixel_step=4;
-    rb->data.rgba.row_step = width*4;
-    rb->data.rgba.b = &rb->data.rgba.pixels[0];
-    rb->data.rgba.g = &rb->data.rgba.pixels[1];
-    rb->data.rgba.r = &rb->data.rgba.pixels[2];
-    rb->data.rgba.a = &rb->data.rgba.pixels[3];
-    
-    for(i=0;i<height;i++) {
-        row_pointers[i] = &(rb->data.rgba.pixels[i*rb->data.rgba.row_step]);
+  png_init_io(png_ptr,stream);
+  png_read_info(png_ptr,info_ptr);
+  png_get_IHDR(png_ptr, info_ptr, &width, &height,
+               &bit_depth, &color_type,
+               NULL,NULL,NULL);
+
+  rb->width = width;
+  rb->height = height;
+  rb->type = MS_BUFFER_BYTE_RGBA;
+  rb->data.rgba.pixels = (unsigned char*)malloc(width*height*4*sizeof(unsigned char));
+  row_pointers = (unsigned char**)malloc(height*sizeof(unsigned char*));
+  rb->data.rgba.pixel_step=4;
+  rb->data.rgba.row_step = width*4;
+  b = rb->data.rgba.b = &rb->data.rgba.pixels[0];
+  g = rb->data.rgba.g = &rb->data.rgba.pixels[1];
+  r = rb->data.rgba.r = &rb->data.rgba.pixels[2];
+  a = rb->data.rgba.a = &rb->data.rgba.pixels[3];
+
+  for(i=0; i<height; i++) {
+    row_pointers[i] = &(rb->data.rgba.pixels[i*rb->data.rgba.row_step]);
+  }
+
+  if (color_type == PNG_COLOR_TYPE_PALETTE)
+    /* expand palette images to RGB */
+    png_set_expand(png_ptr);
+  if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
+    /* expand low bit-depth grayscale to 8bits */
+    png_set_expand(png_ptr);
+  if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS))
+    /* expand transparency chunks to full alpha */
+    png_set_expand(png_ptr);
+  if (bit_depth == 16)
+    /* scale 16bits down to 8 */
+    png_set_strip_16(png_ptr);
+  if (color_type == PNG_COLOR_TYPE_GRAY ||
+      color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
+    /* convert grayscale to rgba */
+    png_set_gray_to_rgb(png_ptr);
+
+  png_set_bgr(png_ptr);
+  if (color_type == PNG_COLOR_TYPE_RGB || color_type == PNG_COLOR_TYPE_GRAY ||
+      color_type == PNG_COLOR_TYPE_PALETTE)
+    png_set_add_alpha(png_ptr, 0xff, PNG_FILLER_AFTER);
+
+  png_read_update_info(png_ptr, info_ptr);
+  assert(png_get_rowbytes(png_ptr, info_ptr) == rb->data.rgba.row_step);
+
+  png_read_image(png_ptr, row_pointers);
+  free(row_pointers);
+  row_pointers=NULL;
+  png_read_end(png_ptr,NULL);
+  png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
+
+  /*premultiply data*/
+  for(i=0; i<width*height; i++) {
+    if(*a < 255) {
+      if(*a == 0) {
+        *r=*g=*b=0;
+      } else {
+        *r = (*r * *a + 255) >> 8;
+        *g = (*g * *a + 255) >> 8;
+        *b = (*b * *a + 255) >> 8;
+      }
     }
-    
-    if (color_type == PNG_COLOR_TYPE_PALETTE)
-        /* expand palette images to RGB */
-        png_set_expand(png_ptr);
-    if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
-        /* expand low bit-depth grayscale to 8bits */
-        png_set_expand(png_ptr);
-    if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS))
-        /* expand transparency chunks to full alpha */
-        png_set_expand(png_ptr);
-    if (bit_depth == 16)
-        /* scale 16bits down to 8 */
-        png_set_strip_16(png_ptr);
-    if (color_type == PNG_COLOR_TYPE_GRAY ||
-        color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
-        /* convert grayscale to rgba */
-        png_set_gray_to_rgb(png_ptr);
-    
-    png_set_bgr(png_ptr);
-    if (color_type == PNG_COLOR_TYPE_RGB || color_type == PNG_COLOR_TYPE_GRAY ||
-        color_type == PNG_COLOR_TYPE_PALETTE)
-        png_set_add_alpha(png_ptr, 0xff, PNG_FILLER_AFTER);
-
-    png_read_update_info(png_ptr, info_ptr);
-    row_bytes = png_get_rowbytes(png_ptr, info_ptr);
-    assert(row_bytes == rb->data.rgba.row_step);
-    
-    png_read_image(png_ptr, row_pointers);
-    free(row_pointers);
-    row_pointers=NULL;
-    png_read_end(png_ptr,NULL);
-    png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
-    
-    fclose(stream);
-    return MS_SUCCESS; 
+    a+=4;
+    b+=4;
+    g+=4;
+    r+=4;
+  }
+
+  fclose(stream);
+  return MS_SUCCESS;
 
 }
 
-int saveGdImage(gdImagePtr ip, FILE *fp, outputFormatObj *format) {
-    gdIOCtx *ctx = NULL;
+#ifdef USE_GD
+int saveGdImage(gdImagePtr ip, FILE *fp, outputFormatObj *format)
+{
+  gdIOCtx *ctx = NULL;
 
-    if (fp && (fp == stdout))
-        ctx = msIO_getGDIOCtx( fp );
+  if (fp && (fp == stdout))
+    ctx = msIO_getGDIOCtx( fp );
 
-    if(strcasecmp("ON", msGetOutputFormatOption(format, "INTERLACE", "ON")) == 0)
-        gdImageInterlace(ip, 1);
+  if(strcasecmp("ON", msGetOutputFormatOption(format, "INTERLACE", "ON")) == 0)
+    gdImageInterlace(ip, 1);
 
-    if(format->transparent)
-        gdImageColorTransparent(ip, 0);
+  if(format->transparent)
+    gdImageColorTransparent(ip, 0);
 
-    if(strcasestr(format->driver, "/gif")) {
+  if(strcasestr(format->driver, "/gif")) {
 #ifdef USE_GD_GIF
-        if (ctx)
-            gdImageGifCtx(ip, ctx);
-        else
-            gdImageGif(ip, fp);
+    if (ctx)
+      gdImageGifCtx(ip, ctx);
+    else
+      gdImageGif(ip, fp);
 #else
-        msSetError(MS_MISCERR, "GIF output is not available.", "saveImageGD()");
-        return(MS_FAILURE);
+    msSetError(MS_MISCERR, "GIF output is not available.", "saveImageGD()");
+    return(MS_FAILURE);
 #endif
-    } else if(strcasestr(format->driver, "/png")) {
+  } else if(strcasestr(format->driver, "/png")) {
 #ifdef USE_GD_PNG
-        if (ctx)
-            gdImagePngCtx(ip, ctx);
-        else
-            gdImagePng(ip, fp);
+    if (ctx)
+      gdImagePngCtx(ip, ctx);
+    else
+      gdImagePng(ip, fp);
 #else
-        msSetError(MS_MISCERR, "PNG output is not available.", "saveImageGD()");
-        return(MS_FAILURE);
+    msSetError(MS_MISCERR, "PNG output is not available.", "saveImageGD()");
+    return(MS_FAILURE);
 #endif
-    } else if(strcasestr(format->driver, "/jpeg")) {
+  } else if(strcasestr(format->driver, "/jpeg")) {
 #ifdef USE_GD_JPEG
-        if (ctx)
-            gdImageJpegCtx(ip, ctx, atoi(msGetOutputFormatOption( format, "QUALITY", "75")));
-        else
-            gdImageJpeg(ip, fp, atoi(msGetOutputFormatOption( format, "QUALITY", "75")));
+    if (ctx)
+      gdImageJpegCtx(ip, ctx, atoi(msGetOutputFormatOption( format, "QUALITY", "75")));
+    else
+      gdImageJpeg(ip, fp, atoi(msGetOutputFormatOption( format, "QUALITY", "75")));
 #else
-        msSetError(MS_MISCERR, "JPEG output is not available.", "saveImageGD()");
-        return(MS_FAILURE);
+    msSetError(MS_MISCERR, "JPEG output is not available.", "saveImageGD()");
+    return(MS_FAILURE);
 #endif
-    } else {
-        msSetError(MS_MISCERR, "Unknown or unsupported format.", "saveImageGD()");
-        return(MS_FAILURE);
-    }
-    msFree(ctx);
+  } else {
+    msSetError(MS_MISCERR, "Unknown or unsupported format.", "saveImageGD()");
+    return(MS_FAILURE);
+  }
+  msFree(ctx);
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
-int saveGdImageBuffer(gdImagePtr ip, bufferObj *buffer, outputFormatObj *format) {
-    gdIOCtx *ctx;
-    int tmp_size;
+int saveGdImageBuffer(gdImagePtr ip, bufferObj *buffer, outputFormatObj *format)
+{
+  gdIOCtx *ctx;
+  int tmp_size;
 
-    ctx = gdNewDynamicCtx (2048, NULL);
+  ctx = gdNewDynamicCtx (2048, NULL);
 
-    if( format->imagemode == MS_IMAGEMODE_RGBA )
-        gdImageSaveAlpha( ip, 1 );
-    else if( format->imagemode == MS_IMAGEMODE_RGB )
-        gdImageSaveAlpha( ip, 0 );
-    
-    if(strcasecmp("ON", msGetOutputFormatOption(format, "INTERLACE", "ON")) == 0)
-        gdImageInterlace(ip, 1);
+  if( format->imagemode == MS_IMAGEMODE_RGBA )
+    gdImageSaveAlpha( ip, 1 );
+  else if( format->imagemode == MS_IMAGEMODE_RGB )
+    gdImageSaveAlpha( ip, 0 );
 
-    if(format->transparent)
-        gdImageColorTransparent(ip, 0);
+  if(strcasecmp("ON", msGetOutputFormatOption(format, "INTERLACE", "ON")) == 0)
+    gdImageInterlace(ip, 1);
 
-    if(strcasestr(format->driver, "/gif")) {
+  if(format->transparent)
+    gdImageColorTransparent(ip, 0);
+
+  if(strcasestr(format->driver, "/gif")) {
 #ifdef USE_GD_GIF
-        gdImageGifCtx( ip, ctx );
+    gdImageGifCtx( ip, ctx );
 #else
-        msSetError(MS_MISCERR, "GIF output is not available.", "saveImageGD()");
-        ctx->gd_free(ctx);
-        return(MS_FAILURE);
+    msSetError(MS_MISCERR, "GIF output is not available.", "saveImageGD()");
+    ctx->gd_free(ctx);
+    return(MS_FAILURE);
 #endif
-    } else if(strcasestr(format->driver, "/png")) {
+  } else if(strcasestr(format->driver, "/png")) {
 #ifdef USE_GD_PNG
-        gdImagePngCtx(ip, ctx);
+    gdImagePngCtx(ip, ctx);
 #else
-        msSetError(MS_MISCERR, "PNG output is not available.", "saveImageGD()");
-        ctx->gd_free(ctx);
-        return(MS_FAILURE);
+    msSetError(MS_MISCERR, "PNG output is not available.", "saveImageGD()");
+    ctx->gd_free(ctx);
+    return(MS_FAILURE);
 #endif
-    } else if(strcasestr(format->driver, "/jpeg")) {
+  } else if(strcasestr(format->driver, "/jpeg")) {
 #ifdef USE_GD_JPEG
-        gdImageJpegCtx(ip, ctx, atoi(msGetOutputFormatOption( format, "QUALITY", "75")));
+    gdImageJpegCtx(ip, ctx, atoi(msGetOutputFormatOption( format, "QUALITY", "75")));
 #else
-        msSetError(MS_MISCERR, "JPEG output is not available.", "saveImageGD()");
-        ctx->gd_free(ctx);
-        return(MS_FAILURE);
+    msSetError(MS_MISCERR, "JPEG output is not available.", "saveImageGD()");
+    ctx->gd_free(ctx);
+    return(MS_FAILURE);
 #endif
-    } else {
-        msSetError(MS_MISCERR, "Unknown or unsupported format.", "saveImageGD()");
-        ctx->gd_free(ctx);
-        return(MS_FAILURE);
-    }
+  } else {
+    msSetError(MS_MISCERR, "Unknown or unsupported format.", "saveImageGD()");
+    ctx->gd_free(ctx);
+    return(MS_FAILURE);
+  }
 
-    /* gdDPExtractData expects a int*, but bufferObj::size is a size_t */
-    /* so use a temp variable to hold it */
-    buffer->data = gdDPExtractData (ctx, &tmp_size);
-    buffer->size = tmp_size;
+  /* gdDPExtractData expects a int*, but bufferObj::size is a size_t */
+  /* so use a temp variable to hold it */
+  buffer->data = gdDPExtractData (ctx, &tmp_size);
+  buffer->size = tmp_size;
 
-    ctx->gd_free(ctx);
-    return MS_SUCCESS;
+  ctx->gd_free(ctx);
+  return MS_SUCCESS;
 }
+#endif
 
 int msSaveRasterBuffer(mapObj *map, rasterBufferObj *rb, FILE *stream,
-        outputFormatObj *format) {
-	if(rb->type == MS_BUFFER_GD) {
-		return saveGdImage(rb->data.gd_img, stream, format);
-	}
-    if(strcasestr(format->driver,"/png")) {
-        streamInfo info;
-        info.fp = stream;
-        info.buffer = NULL;
-        
-        return saveAsPNG(map, rb,&info,format);
-    } else if(strcasestr(format->driver,"/jpeg")) {
-        streamInfo info;
-        info.fp = stream;
-        info.buffer=NULL;
-        return saveAsJPEG(map, rb,&info,format);
-    } else {
-        msSetError(MS_MISCERR,"unsupported image format\n", "msSaveRasterBuffer()");
-        return MS_FAILURE;
-    }
+                       outputFormatObj *format)
+{
+#ifdef USE_GD
+  if(rb->type == MS_BUFFER_GD) {
+    return saveGdImage(rb->data.gd_img, stream, format);
+  }
+#else
+  assert(rb->type != MS_BUFFER_GD);
+#endif
+  if(strcasestr(format->driver,"/png")) {
+    streamInfo info;
+    info.fp = stream;
+    info.buffer = NULL;
+
+    return saveAsPNG(map, rb,&info,format);
+  } else if(strcasestr(format->driver,"/jpeg")) {
+    streamInfo info;
+    info.fp = stream;
+    info.buffer=NULL;
+    return saveAsJPEG(map, rb,&info,format);
+  } else {
+    msSetError(MS_MISCERR,"unsupported image format\n", "msSaveRasterBuffer()");
+    return MS_FAILURE;
+  }
 }
 
 int msSaveRasterBufferToBuffer(rasterBufferObj *data, bufferObj *buffer,
-        outputFormatObj *format) {
-    if(data->type == MS_BUFFER_GD) {
-		return saveGdImageBuffer(data->data.gd_img, buffer, format);
-	}
-    if(strcasestr(format->driver,"/png")) {
-        streamInfo info;
-        info.fp = NULL;
-        info.buffer = buffer;
-        return saveAsPNG(NULL, data,&info,format);
-    } else if(strcasestr(format->driver,"/jpeg")) {
-        streamInfo info;
-        info.fp = NULL;
-        info.buffer=buffer;
-        return saveAsJPEG(NULL, data,&info,format);
-    } else {
-        msSetError(MS_MISCERR,"unsupported image format\n", "msSaveRasterBuffer()");
-        return MS_FAILURE;
-    }
+                               outputFormatObj *format)
+{
+#ifdef USE_GD
+  if(data->type == MS_BUFFER_GD) {
+    return saveGdImageBuffer(data->data.gd_img, buffer, format);
+  }
+#else
+  assert(data->type != MS_BUFFER_GD);
+#endif
+  if(strcasestr(format->driver,"/png")) {
+    streamInfo info;
+    info.fp = NULL;
+    info.buffer = buffer;
+    return saveAsPNG(NULL, data,&info,format);
+  } else if(strcasestr(format->driver,"/jpeg")) {
+    streamInfo info;
+    info.fp = NULL;
+    info.buffer=buffer;
+    return saveAsJPEG(NULL, data,&info,format);
+  } else {
+    msSetError(MS_MISCERR,"unsupported image format\n", "msSaveRasterBuffer()");
+    return MS_FAILURE;
+  }
 }
 #ifdef USE_GIF
-static char const *gif_error_msg() {
+static char const *gif_error_msg()
+{
   static char msg[80];
 
   int code = GifLastError();
   switch (code) {
-  case E_GIF_ERR_OPEN_FAILED: /* should not see this */
-    return "Failed to open given file";
+    case E_GIF_ERR_OPEN_FAILED: /* should not see this */
+      return "Failed to open given file";
 
-  case E_GIF_ERR_WRITE_FAILED:
-    return "Write failed";
+    case E_GIF_ERR_WRITE_FAILED:
+      return "Write failed";
 
-  case E_GIF_ERR_HAS_SCRN_DSCR: /* should not see this */
-    return "Screen descriptor already passed to giflib";
+    case E_GIF_ERR_HAS_SCRN_DSCR: /* should not see this */
+      return "Screen descriptor already passed to giflib";
 
-  case E_GIF_ERR_HAS_IMAG_DSCR: /* should not see this */
-    return "Image descriptor already passed to giflib";
+    case E_GIF_ERR_HAS_IMAG_DSCR: /* should not see this */
+      return "Image descriptor already passed to giflib";
 
-  case E_GIF_ERR_NO_COLOR_MAP: /* should not see this */
-    return "Neither global nor local color map set";
+    case E_GIF_ERR_NO_COLOR_MAP: /* should not see this */
+      return "Neither global nor local color map set";
 
-  case E_GIF_ERR_DATA_TOO_BIG: /* should not see this */
-    return "Too much pixel data passed to giflib";
+    case E_GIF_ERR_DATA_TOO_BIG: /* should not see this */
+      return "Too much pixel data passed to giflib";
 
-  case E_GIF_ERR_NOT_ENOUGH_MEM:
-    return "Out of memory";
+    case E_GIF_ERR_NOT_ENOUGH_MEM:
+      return "Out of memory";
 
-  case E_GIF_ERR_DISK_IS_FULL:
-    return "Disk is full";
+    case E_GIF_ERR_DISK_IS_FULL:
+      return "Disk is full";
 
-  case E_GIF_ERR_CLOSE_FAILED: /* should not see this */
-    return "File close failed";
+    case E_GIF_ERR_CLOSE_FAILED: /* should not see this */
+      return "File close failed";
 
-  case E_GIF_ERR_NOT_WRITEABLE: /* should not see this */
-    return "File not writable";
+    case E_GIF_ERR_NOT_WRITEABLE: /* should not see this */
+      return "File not writable";
 
-  case D_GIF_ERR_OPEN_FAILED:
-    return "Failed to open file";
+    case D_GIF_ERR_OPEN_FAILED:
+      return "Failed to open file";
 
-  case D_GIF_ERR_READ_FAILED:
-    return "Failed to read from file";
+    case D_GIF_ERR_READ_FAILED:
+      return "Failed to read from file";
 
-  case D_GIF_ERR_NOT_GIF_FILE:
-    return "File is not a GIF file";
+    case D_GIF_ERR_NOT_GIF_FILE:
+      return "File is not a GIF file";
 
-  case D_GIF_ERR_NO_SCRN_DSCR:
-    return "No screen descriptor detected - invalid file";
+    case D_GIF_ERR_NO_SCRN_DSCR:
+      return "No screen descriptor detected - invalid file";
 
-  case D_GIF_ERR_NO_IMAG_DSCR:
-    return "No image descriptor detected - invalid file";
+    case D_GIF_ERR_NO_IMAG_DSCR:
+      return "No image descriptor detected - invalid file";
 
-  case D_GIF_ERR_NO_COLOR_MAP:
-    return "No global or local color map found";
+    case D_GIF_ERR_NO_COLOR_MAP:
+      return "No global or local color map found";
 
-  case D_GIF_ERR_WRONG_RECORD:
-    return "Wrong record type detected - invalid file?";
+    case D_GIF_ERR_WRONG_RECORD:
+      return "Wrong record type detected - invalid file?";
 
-  case D_GIF_ERR_DATA_TOO_BIG:
-    return "Data in file too big for image";
+    case D_GIF_ERR_DATA_TOO_BIG:
+      return "Data in file too big for image";
 
-  case D_GIF_ERR_NOT_ENOUGH_MEM:
-    return "Out of memory";
+    case D_GIF_ERR_NOT_ENOUGH_MEM:
+      return "Out of memory";
 
-  case D_GIF_ERR_CLOSE_FAILED:
-    return "Close failed";
+    case D_GIF_ERR_CLOSE_FAILED:
+      return "Close failed";
 
-  case D_GIF_ERR_NOT_READABLE:
-    return "File not opened for read";
+    case D_GIF_ERR_NOT_READABLE:
+      return "File not opened for read";
 
-  case D_GIF_ERR_IMAGE_DEFECT:
-    return "Defective image";
+    case D_GIF_ERR_IMAGE_DEFECT:
+      return "Defective image";
 
-  case D_GIF_ERR_EOF_TOO_SOON:
-    return "Unexpected EOF - invalid file";
+    case D_GIF_ERR_EOF_TOO_SOON:
+      return "Unexpected EOF - invalid file";
 
-  default:
-    sprintf(msg, "Unknown giflib error code %d", code);
-    return msg;
+    default:
+      sprintf(msg, "Unknown giflib error code %d", code);
+      return msg;
   }
 }
 
@@ -1034,218 +1080,215 @@ static char const *gif_error_msg() {
 /* missing: set the first pointer to a,r,g,b */
 int readGIF(char *path, rasterBufferObj *rb)
 {
-   int i, j, codeSize, extCode, firstImageRead = MS_FALSE;
-   unsigned char *r,*g,*b,*a;
-   int transIdx = -1;
-   GifFileType *image;
-   GifPixelType *line;
-   GifRecordType recordType;
-   GifByteType *codeBlock, *extension;
-   ColorMapObject *cmap;
-   int interlacedOffsets[] = {0,4,2,1};
-   int interlacedJumps[] = {8,8,4,2};
-
-
-   rb->type = MS_BUFFER_BYTE_RGBA;
-   image =  DGifOpenFileName(path);
-   if (image == NULL) {
-	  msSetError(MS_MISCERR,"failed to load gif image: %s","readGIF()", gif_error_msg());
+  int i, j, codeSize, extCode, firstImageRead = MS_FALSE;
+  unsigned char *r,*g,*b,*a;
+  int transIdx = -1;
+  GifFileType *image;
+  GifPixelType *line;
+  GifRecordType recordType;
+  GifByteType *codeBlock, *extension;
+  ColorMapObject *cmap;
+  int interlacedOffsets[] = {0,4,2,1};
+  int interlacedJumps[] = {8,8,4,2};
+
+
+  rb->type = MS_BUFFER_BYTE_RGBA;
+  image =  DGifOpenFileName(path);
+  if (image == NULL) {
+    msSetError(MS_MISCERR,"failed to load gif image: %s","readGIF()", gif_error_msg());
+    return MS_FAILURE;
+  }
+  rb->width = image->SWidth;
+  rb->height = image->SHeight;
+  rb->data.rgba.row_step = rb->width * 4;
+  rb->data.rgba.pixel_step = 4;
+  rb->data.rgba.pixels = (unsigned char*)malloc(rb->width*rb->height*4*sizeof(unsigned char*));
+  b = rb->data.rgba.b = &rb->data.rgba.pixels[0];
+  g = rb->data.rgba.g = &rb->data.rgba.pixels[1];
+  r = rb->data.rgba.r = &rb->data.rgba.pixels[2];
+  a = rb->data.rgba.a = &rb->data.rgba.pixels[3];
+
+  cmap = (image->Image.ColorMap)?image->Image.ColorMap:image->SColorMap;
+  for(i=0; i<rb->width*rb->height; i++) {
+    *a = 255;
+    *r = cmap->Colors[image->SBackGroundColor].Red;
+    *g = cmap->Colors[image->SBackGroundColor].Green;
+    *b = cmap->Colors[image->SBackGroundColor].Blue;
+    a+=rb->data.rgba.pixel_step;
+    r+=rb->data.rgba.pixel_step;
+    g+=rb->data.rgba.pixel_step;
+    b+=rb->data.rgba.pixel_step;
+  }
+
+  do {
+    if (DGifGetRecordType(image, &recordType) == GIF_ERROR) {
+      msSetError(MS_MISCERR,"corrupted gif image?: %s","readGIF()", gif_error_msg());
       return MS_FAILURE;
-   }
-   rb->width = image->SWidth;
-   rb->height = image->SHeight;
-   rb->data.rgba.row_step = rb->width * 4;
-   rb->data.rgba.pixel_step = 4;
-   rb->data.rgba.pixels = (unsigned char*)malloc(rb->width*rb->height*4*sizeof(unsigned char*));
-   b = rb->data.rgba.b = &rb->data.rgba.pixels[0];
-   g = rb->data.rgba.g = &rb->data.rgba.pixels[1];
-   r = rb->data.rgba.r = &rb->data.rgba.pixels[2];
-   a = rb->data.rgba.a = &rb->data.rgba.pixels[3];
-   
-   cmap = (image->Image.ColorMap)?image->Image.ColorMap:image->SColorMap;
-   for(i=0; i<rb->width*rb->height; i++) {
-      *a = 255;
-      *r = cmap->Colors[image->SBackGroundColor].Red;
-      *g = cmap->Colors[image->SBackGroundColor].Green;
-      *b = cmap->Colors[image->SBackGroundColor].Blue;
-      a+=rb->data.rgba.pixel_step;
-      r+=rb->data.rgba.pixel_step;
-      g+=rb->data.rgba.pixel_step;
-      b+=rb->data.rgba.pixel_step;
-   }
-   
-   do 
-   {  
-      if (DGifGetRecordType(image, &recordType) == GIF_ERROR) {
-         msSetError(MS_MISCERR,"corrupted gif image?: %s","readGIF()", gif_error_msg());
-         return MS_FAILURE;
-      }
+    }
 
-      switch (recordType)
-      {
+    switch (recordType) {
       case SCREEN_DESC_RECORD_TYPE:
-         DGifGetScreenDesc(image);
-         break;
+        DGifGetScreenDesc(image);
+        break;
       case IMAGE_DESC_RECORD_TYPE:
-         if (DGifGetImageDesc(image) == GIF_ERROR) {
-            msSetError(MS_MISCERR,"corrupted gif image?: %s","readGIF()", gif_error_msg());
+        if (DGifGetImageDesc(image) == GIF_ERROR) {
+          msSetError(MS_MISCERR,"corrupted gif image?: %s","readGIF()", gif_error_msg());
+          return MS_FAILURE;
+        }
+        if (!firstImageRead) {
+
+          int row = image->Image.Top;
+          int col = image->Image.Left;
+          int width = image->Image.Width;
+          int height = image->Image.Height;
+
+          /* sanity check: */
+          if(col+width>rb->width || row+height>rb->height) {
+            msSetError(MS_MISCERR,"corrupted gif image, img size exceeds screen size","readGIF()");
             return MS_FAILURE;
-         }
-         if (!firstImageRead)
-         {
-            
-            int row = image->Image.Top;
-            int col = image->Image.Left;
-            int width = image->Image.Width;
-            int height = image->Image.Height;
-            
-            //sanity check:
-            if(col+width>rb->width || row+height>rb->height) {
-               msSetError(MS_MISCERR,"corrupted gif image, img size exceeds screen size","readGIF()");
-               return MS_FAILURE;
-            }
-                                            
-            line = (GifPixelType *) malloc(width * sizeof(GifPixelType));
-            if(image->Image.Interlace) {
-               int count;
-               for(count=0; count<4; count++) {
-                  for(i=row+interlacedOffsets[count];i<row+height;i+=interlacedJumps[count]) {
-                     int offset = i * rb->data.rgba.row_step + col * rb->data.rgba.pixel_step;
-                     a = rb->data.rgba.a + offset;
-                     r = rb->data.rgba.r + offset;
-                     g = rb->data.rgba.g + offset;
-                     b = rb->data.rgba.b + offset;
-                     if (DGifGetLine(image, line, width) == GIF_ERROR) {
-                        msSetError(MS_MISCERR,"corrupted gif image?: %s","readGIF()",gif_error_msg());
-                        return MS_FAILURE;
-                     }
-                     
-                     for(j=0; j<width; j++) {
-                        GifPixelType pix = line[j];
-                        if(transIdx == -1 || pix != transIdx) {
-                           *a = 255;
-                           *r = cmap->Colors[pix].Red;
-                           *g = cmap->Colors[pix].Green;
-                           *b = cmap->Colors[pix].Blue;
-                        } else {
-                           *a = *r = *g = *b = 0;
-                        }
-                        a+=rb->data.rgba.pixel_step;
-                        r+=rb->data.rgba.pixel_step;
-                        g+=rb->data.rgba.pixel_step;
-                        b+=rb->data.rgba.pixel_step;
-                     }
-                  }
-               }
-            } else {
-               for (i = 0; i < height; i++) {
-                  int offset = i * rb->data.rgba.row_step + col * rb->data.rgba.pixel_step;
-                  a = rb->data.rgba.a + offset;
-                  r = rb->data.rgba.r + offset;
-                  g = rb->data.rgba.g + offset;
-                  b = rb->data.rgba.b + offset;
-                  if (DGifGetLine(image, line, width) == GIF_ERROR) {
-                     msSetError(MS_MISCERR,"corrupted gif image?: %s","readGIF()",gif_error_msg());
-                     return MS_FAILURE;
-                  }
-                  for(j=0; j<width; j++) {
-                     GifPixelType pix = line[j];
-                     if(transIdx == -1 || pix != transIdx) {
-                        *a = 255;
-                        *r = cmap->Colors[pix].Red;
-                        *g = cmap->Colors[pix].Green;
-                        *b = cmap->Colors[pix].Blue;
-                     } else {
-                        *a = *r = *g = *b = 0;
-                     }
-                     a+=rb->data.rgba.pixel_step;
-                     r+=rb->data.rgba.pixel_step;
-                     g+=rb->data.rgba.pixel_step;
-                     b+=rb->data.rgba.pixel_step;
+          }
+
+          line = (GifPixelType *) malloc(width * sizeof(GifPixelType));
+          if(image->Image.Interlace) {
+            int count;
+            for(count=0; count<4; count++) {
+              for(i=row+interlacedOffsets[count]; i<row+height; i+=interlacedJumps[count]) {
+                int offset = i * rb->data.rgba.row_step + col * rb->data.rgba.pixel_step;
+                a = rb->data.rgba.a + offset;
+                r = rb->data.rgba.r + offset;
+                g = rb->data.rgba.g + offset;
+                b = rb->data.rgba.b + offset;
+                if (DGifGetLine(image, line, width) == GIF_ERROR) {
+                  msSetError(MS_MISCERR,"corrupted gif image?: %s","readGIF()",gif_error_msg());
+                  return MS_FAILURE;
+                }
+
+                for(j=0; j<width; j++) {
+                  GifPixelType pix = line[j];
+                  if(transIdx == -1 || pix != transIdx) {
+                    *a = 255;
+                    *r = cmap->Colors[pix].Red;
+                    *g = cmap->Colors[pix].Green;
+                    *b = cmap->Colors[pix].Blue;
+                  } else {
+                    *a = *r = *g = *b = 0;
                   }
-               }
+                  a+=rb->data.rgba.pixel_step;
+                  r+=rb->data.rgba.pixel_step;
+                  g+=rb->data.rgba.pixel_step;
+                  b+=rb->data.rgba.pixel_step;
+                }
+              }
             }
-            free((char *) line);
-            firstImageRead = MS_TRUE;
-         } 
-         else
-         {  /* Skip all next images */
-            if (DGifGetCode(image, &codeSize, &codeBlock) == GIF_ERROR) {
-               msSetError(MS_MISCERR,"corrupted gif image?: %s","readGIF()", gif_error_msg());
-               return MS_FAILURE;
+          } else {
+            for (i = 0; i < height; i++) {
+              int offset = i * rb->data.rgba.row_step + col * rb->data.rgba.pixel_step;
+              a = rb->data.rgba.a + offset;
+              r = rb->data.rgba.r + offset;
+              g = rb->data.rgba.g + offset;
+              b = rb->data.rgba.b + offset;
+              if (DGifGetLine(image, line, width) == GIF_ERROR) {
+                msSetError(MS_MISCERR,"corrupted gif image?: %s","readGIF()",gif_error_msg());
+                return MS_FAILURE;
+              }
+              for(j=0; j<width; j++) {
+                GifPixelType pix = line[j];
+                if(transIdx == -1 || pix != transIdx) {
+                  *a = 255;
+                  *r = cmap->Colors[pix].Red;
+                  *g = cmap->Colors[pix].Green;
+                  *b = cmap->Colors[pix].Blue;
+                } else {
+                  *a = *r = *g = *b = 0;
+                }
+                a+=rb->data.rgba.pixel_step;
+                r+=rb->data.rgba.pixel_step;
+                g+=rb->data.rgba.pixel_step;
+                b+=rb->data.rgba.pixel_step;
+              }
             }
-            while (codeBlock != NULL) {
-               if (DGifGetCodeNext(image, &codeBlock) == GIF_ERROR) {
-                  msSetError(MS_MISCERR,"corrupted gif image?: %s","readGIF()", gif_error_msg());
-                  return MS_FAILURE;
-               }
+          }
+          free((char *) line);
+          firstImageRead = MS_TRUE;
+        } else {
+          /* Skip all next images */
+          if (DGifGetCode(image, &codeSize, &codeBlock) == GIF_ERROR) {
+            msSetError(MS_MISCERR,"corrupted gif image?: %s","readGIF()", gif_error_msg());
+            return MS_FAILURE;
+          }
+          while (codeBlock != NULL) {
+            if (DGifGetCodeNext(image, &codeBlock) == GIF_ERROR) {
+              msSetError(MS_MISCERR,"corrupted gif image?: %s","readGIF()", gif_error_msg());
+              return MS_FAILURE;
             }
-         }
-         break;
+          }
+        }
+        break;
       case EXTENSION_RECORD_TYPE:
-         /* skip all extension blocks */
-         if (DGifGetExtension(image, &extCode, &extension) == GIF_ERROR) {
+        /* skip all extension blocks */
+        if (DGifGetExtension(image, &extCode, &extension) == GIF_ERROR) {
+          msSetError(MS_MISCERR,"corrupted gif image?: %s","readGIF()", gif_error_msg());
+          return MS_FAILURE;
+        }
+        if(extCode == 249 && (extension[1] & 1))
+          transIdx = extension[4];
+        for (;;) {
+          if (DGifGetExtensionNext(image, &extension) == GIF_ERROR) {
             msSetError(MS_MISCERR,"corrupted gif image?: %s","readGIF()", gif_error_msg());
             return MS_FAILURE;
-         }
-         if(extCode == 249 && (extension[1] & 1))
+          }
+          if (extension == NULL)
+            break;
+          if(extension[1] & 1)
             transIdx = extension[4];
-         for (;;) {
-            if (DGifGetExtensionNext(image, &extension) == GIF_ERROR) {
-               msSetError(MS_MISCERR,"corrupted gif image?: %s","readGIF()", gif_error_msg());
-               return MS_FAILURE;
-            }
-            if (extension == NULL)
-               break;
-            if(extension[1] & 1)
-               transIdx = extension[4];
-         }
-         break;
+        }
+        break;
       case UNDEFINED_RECORD_TYPE:
-         break;
+        break;
       case TERMINATE_RECORD_TYPE:
-         break;
+        break;
       default:
-         break;
-      }
+        break;
+    }
 
-   } while (recordType != TERMINATE_RECORD_TYPE);
+  } while (recordType != TERMINATE_RECORD_TYPE);
 
-   if (DGifCloseFile(image) == GIF_ERROR) {
-      msSetError(MS_MISCERR,"failed to close gif after loading: %s","readGIF()", gif_error_msg());
-      return MS_FAILURE;
-   }
+  if (DGifCloseFile(image) == GIF_ERROR) {
+    msSetError(MS_MISCERR,"failed to close gif after loading: %s","readGIF()", gif_error_msg());
+    return MS_FAILURE;
+  }
 
-   return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 #endif
 
-int msLoadMSRasterBufferFromFile(char *path, rasterBufferObj *rb) {
-    FILE *stream;
-    unsigned char signature[8];
-    int ret = MS_FAILURE;
-    stream = fopen(path,"rb");
-    if(!stream) {
-        msSetError(MS_MISCERR, "unable to open file %s for reading", "msLoadMSRasterBufferFromFile()", path);
-        return MS_FAILURE;
-    }
-    if(1 != fread(signature,8,1,stream)) {
-       msSetError(MS_MISCERR, "Unable to read header from image file %s", "msLoadMSRasterBufferFromFile()",path);
-       return MS_FAILURE;
-    }
-    fclose(stream);
-    if(png_sig_cmp(signature,0,8) == 0) {
-        ret = readPNG(path,rb);
-    }
+int msLoadMSRasterBufferFromFile(char *path, rasterBufferObj *rb)
+{
+  FILE *stream;
+  unsigned char signature[8];
+  int ret = MS_FAILURE;
+  stream = fopen(path,"rb");
+  if(!stream) {
+    msSetError(MS_MISCERR, "unable to open file %s for reading", "msLoadMSRasterBufferFromFile()", path);
+    return MS_FAILURE;
+  }
+  if(1 != fread(signature,8,1,stream)) {
+    msSetError(MS_MISCERR, "Unable to read header from image file %s", "msLoadMSRasterBufferFromFile()",path);
+    return MS_FAILURE;
+  }
+  fclose(stream);
+  if(png_sig_cmp(signature,0,8) == 0) {
+    ret = readPNG(path,rb);
+  } else if (!strncmp((char*)signature,"GIF",3)) {
 #ifdef USE_GIF
-    else if (!strncmp((char*)signature,"GIF",3)) {
-
-        ret = readGIF(path,rb);
-    }
+    ret = readGIF(path,rb);
+#else
+    msSetError(MS_MISCERR,"pixmap %s seems to be GIF formatted, but this server is compiled without GIF support","readImage()",path);
+    return MS_FAILURE;
 #endif
-    else {
-        msSetError(MS_MISCERR,"unsupported pixmap format","readImage()");
-        return MS_FAILURE;
-    }
-    return ret;
+  } else {
+    msSetError(MS_MISCERR,"unsupported pixmap format","readImage()");
+    return MS_FAILURE;
+  }
+  return ret;
 }
diff --git a/mapimagemap.c b/mapimagemap.c
index 71be7c1..9c48c7f 100644
--- a/mapimagemap.c
+++ b/mapimagemap.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -29,7 +29,7 @@
 
 #include "mapserver.h"
 #include "dxfcolor.h"
- 
+
 #include <stdarg.h>
 #include <time.h>
 
@@ -38,10 +38,10 @@
 #include <io.h>
 #endif
 
-MS_CVSID("$Id$")
+
 
 #define MYDEBUG 0
-#define DEBUG_IF if (MYDEBUG > 2) 
+#define DEBUG_IF if (MYDEBUG > 2)
 
 /*
  * Client-side imagemap support was originally written by
@@ -73,7 +73,7 @@ MS_CVSID("$Id$")
  *   SUPPRESS   if "yes", then we will suppress area declarations with
  *              no title.
  *              default: "NO"
- * 
+ *
  * For example, http://vevo.verifiedvoting.org/verifier contains this
  * .map file fragment:
  *         OUTPUTFORMAT
@@ -97,11 +97,11 @@ MS_CVSID("$Id$")
  * 'image' data structure) for these.  The 'iprintf' function appends
  * to a pString. */
 typedef struct pString {
-	/* these two fields are somewhere else */
-	char **string;
-	int *alloc_size;
-	/* this field is stored locally. */
-	int string_len;
+  /* these two fields are somewhere else */
+  char **string;
+  int *alloc_size;
+  /* this field is stored locally. */
+  int string_len;
 } pString;
 /* These are the pStrings we declare statically.  One is the 'output'
  * imagemap/dxf file; parts of this live in another data structure and
@@ -109,7 +109,7 @@ typedef struct pString {
  * information for the dxf output. */
 static char *layerlist=NULL;
 static int layersize=0;
-static pString imgStr, layerStr={ &layerlist, &layersize, 0 };
+static pString imgStr, layerStr= { &layerlist, &layersize, 0 };
 
 /* Format strings for the various bits of a client-side imagemap. */
 static const char *polyHrefFmt, *polyMOverFmt, *polyMOutFmt;
@@ -121,7 +121,8 @@ static int suppressEmpty=0;
 /* Prevent buffer-overrun and format-string attacks by "sanitizing" any
  * provided format string to fit the number of expected string arguments
  * (MAX) exactly. */
-static const char *makeFmtSafe(const char *fmt, int MAX) {
+static const char *makeFmtSafe(const char *fmt, int MAX)
+{
   /* format string should have exactly 'MAX' %s */
 
   char *result = msSmallMalloc(strlen(fmt)+1+3*MAX), *cp;
@@ -131,12 +132,12 @@ static const char *makeFmtSafe(const char *fmt, int MAX) {
   for (cp=result; *cp; cp++) {
     if (saw_percent) {
       if (*cp=='%') {
-	/* safe */
+        /* safe */
       } else if (*cp=='s' && numstr<MAX) {
-	numstr++; /* still safe */
+        numstr++; /* still safe */
       } else {
-	/* disable this unsafe format string! */
-	*(cp-1)=' ';
+        /* disable this unsafe format string! */
+        *(cp-1)=' ';
       }
       saw_percent=0;
     } else if (*cp=='%')
@@ -154,43 +155,44 @@ static const char *makeFmtSafe(const char *fmt, int MAX) {
 /* Append the given printf-style formatted string to the pString 'ps'.
  * This is much cleaner (and faster) than the technique this file
  * used to use! */
-static void im_iprintf(pString *ps, const char *fmt, ...) {
-	int n, remaining;
-	va_list ap;
-	do {
-		remaining = *(ps->alloc_size) - ps->string_len;
-		va_start(ap, fmt);
+static void im_iprintf(pString *ps, const char *fmt, ...)
+{
+  int n, remaining;
+  va_list ap;
+  do {
+    remaining = *(ps->alloc_size) - ps->string_len;
+    va_start(ap, fmt);
 #if defined(HAVE_VSNPRINTF)
-		n = vsnprintf((*(ps->string)) + ps->string_len, 
-			      remaining, fmt, ap);
+    n = vsnprintf((*(ps->string)) + ps->string_len,
+                  remaining, fmt, ap);
 #else
-                /* If vsnprintf() is not available then require a minimum
-                 * of 512 bytes of free space to prevent a buffer overflow
-                 * This is not fully bulletproof but should help, see bug 1613
-                 */
-                if (remaining < 512)
-                    n = -1;  
-                else
-                    n = vsprintf((*(ps->string)) + ps->string_len, fmt, ap);
+    /* If vsnprintf() is not available then require a minimum
+     * of 512 bytes of free space to prevent a buffer overflow
+     * This is not fully bulletproof but should help, see bug 1613
+     */
+    if (remaining < 512)
+      n = -1;
+    else
+      n = vsprintf((*(ps->string)) + ps->string_len, fmt, ap);
 #endif
-		va_end(ap);
-		/* if that worked, we're done! */
-		if (-1<n && n<remaining) {
-			ps->string_len += n;
-			return;
-		} else { /* double allocated string size */
-			*(ps->alloc_size) *= 2;/* these keeps realloc linear.*/
-			if (*(ps->alloc_size) < 1024)
-				/* careful: initial size can be 0 */
-				*(ps->alloc_size)=1024;
-			if (n>-1 && *(ps->alloc_size) <= (n + ps->string_len))
-				/* ensure at least as much as what is needed */
-				*(ps->alloc_size) = n+ps->string_len+1;
-			*(ps->string) = (char *) msSmallRealloc
-				(*(ps->string), *(ps->alloc_size));
-			/* if realloc doesn't work, we're screwed! */
-		}
-	} while (1); /* go back and try again. */
+    va_end(ap);
+    /* if that worked, we're done! */
+    if (-1<n && n<remaining) {
+      ps->string_len += n;
+      return;
+    } else { /* double allocated string size */
+      *(ps->alloc_size) *= 2;/* these keeps realloc linear.*/
+      if (*(ps->alloc_size) < 1024)
+        /* careful: initial size can be 0 */
+        *(ps->alloc_size)=1024;
+      if (n>-1 && *(ps->alloc_size) <= (n + ps->string_len))
+        /* ensure at least as much as what is needed */
+        *(ps->alloc_size) = n+ps->string_len+1;
+      *(ps->string) = (char *) msSmallRealloc
+                      (*(ps->string), *(ps->alloc_size));
+      /* if realloc doesn't work, we're screwed! */
+    }
+  } while (1); /* go back and try again. */
 }
 
 
@@ -198,93 +200,52 @@ static void im_iprintf(pString *ps, const char *fmt, ...) {
 static int lastcolor=-1;
 static int matchdxfcolor(colorObj col)
 {
-	int best=7;
-	int delta=128*255;
-	int tcolor = 0;
-	if (lastcolor != -1)
-		return lastcolor;
-	while (tcolor < 256 && (ctable[tcolor].r != col.red || ctable[tcolor].g != col.green || ctable[tcolor].b != col.blue)){
-		tcolor++;
-		if (abs(
-					(ctable[tcolor].r - col.red) * (ctable[tcolor].r - col.red)+ 
-					(ctable[tcolor].b - col.blue) * (ctable[tcolor].b - col.blue) + 
-					(ctable[tcolor].g - col.green) * (ctable[tcolor].g - col.green) < delta)
-		   ){
-			best = tcolor;
-			delta = abs(
-					(ctable[tcolor].r - col.red) * (ctable[tcolor].r - col.red)+ 
-					(ctable[tcolor].b - col.blue) * (ctable[tcolor].b - col.blue) + 
-					(ctable[tcolor].g - col.green) * (ctable[tcolor].g - col.green)
-				);
-		}
-	}
-	if (tcolor >= 256) tcolor = best;
-/* DEBUG_IF	printf("%d/%d/%d (%d/%d - %d), %d : %d/%d/%d<BR>\n", ctable[tcolor].r, ctable[tcolor].g, ctable[tcolor].b, tcolor, best, delta, lastcolor, col.red, col.green, col.blue); */
-	lastcolor = tcolor;
-	return tcolor;
-}
-
-#ifdef notdef /* not currently used */
-static gdImagePtr searchImageCache(struct imageCacheObj *ic, styleObj *style, int size) {
-/* struct imageCacheObj *icp; */
-DEBUG_IF printf("searchImageCache\n<BR>");
-/*
-  icp = ic;
-  while(icp) {
-    if(icp->symbol == symbol && icp->color == color && icp->size == size) return(icp->img);
-    icp = icp->next;
+  int best=7;
+  int delta=128*255;
+  int tcolor = 0;
+  if (lastcolor != -1)
+    return lastcolor;
+  while (tcolor < 256 && (ctable[tcolor].r != col.red || ctable[tcolor].g != col.green || ctable[tcolor].b != col.blue)) {
+    if (abs(
+          (ctable[tcolor].r - col.red) * (ctable[tcolor].r - col.red)+
+          (ctable[tcolor].b - col.blue) * (ctable[tcolor].b - col.blue) +
+          (ctable[tcolor].g - col.green) * (ctable[tcolor].g - col.green) < delta)
+       ) {
+      best = tcolor;
+      delta = abs(
+                (ctable[tcolor].r - col.red) * (ctable[tcolor].r - col.red)+
+                (ctable[tcolor].b - col.blue) * (ctable[tcolor].b - col.blue) +
+                (ctable[tcolor].g - col.green) * (ctable[tcolor].g - col.green)
+              );
+    }
+    tcolor++;
   }
-*/
-  return(NULL);
+  if (tcolor >= 256) tcolor = best;
+  /* DEBUG_IF printf("%d/%d/%d (%d/%d - %d), %d : %d/%d/%d<BR>\n", ctable[tcolor].r, ctable[tcolor].g, ctable[tcolor].b, tcolor, best, delta, lastcolor, col.red, col.green, col.blue); */
+  lastcolor = tcolor;
+  return tcolor;
 }
-#endif /* def notdef */
 
 static char* lname;
 static int dxf;
 
-void msImageStartLayerIM(mapObj *map, layerObj *layer, imageObj *image){
-DEBUG_IF printf("ImageStartLayerIM\n<BR>");
-	free(lname);
-	if (layer->name)
-		lname = msStrdup(layer->name);
-	else
-		lname = msStrdup("NONE");
-	if (dxf == 2){
-		im_iprintf(&layerStr, "LAYER\n%s\n", lname);
-	} else if (dxf) {
-		im_iprintf(&layerStr,
-			"  0\nLAYER\n  2\n%s\n"
-			" 70\n  64\n 6\nCONTINUOUS\n", lname);
-	}
-	lastcolor = -1;
-}
-	
-#ifdef notdef /* not currently used */
-static struct imageCacheObj *addImageCache(struct imageCacheObj *ic, int *icsize, styleObj *style, int size, gdImagePtr img) {
-  struct imageCacheObj *icp;
-DEBUG_IF printf("addImageCache\n<BR>");
-
-  if(*icsize > MS_IMAGECACHESIZE) { /* remove last element, size stays the same */
-    icp = ic;
-    while(icp->next && icp->next->next) icp = icp->next;
-    freeImageCache(icp->next);
-    icp->next = NULL;
-  } else 
-    *icsize += 1;
-
-  icp = (struct imageCacheObj *)malloc(sizeof(struct imageCacheObj));
-  MS_CHECK_ALLOC(icp, sizeof(struct imageCacheObj), NULL);
-  
-  icp->img = img;
-  icp->color = style->color;
-  icp->symbol = style->symbol;
-  icp->size = size;
-  icp->next = ic; /* insert at the beginning */
- 
-  return(icp);
+void msImageStartLayerIM(mapObj *map, layerObj *layer, imageObj *image)
+{
+  DEBUG_IF printf("ImageStartLayerIM\n<BR>");
+  free(lname);
+  if (layer->name)
+    lname = msStrdup(layer->name);
+  else
+    lname = msStrdup("NONE");
+  if (dxf == 2) {
+    im_iprintf(&layerStr, "LAYER\n%s\n", lname);
+  } else if (dxf) {
+    im_iprintf(&layerStr,
+               "  0\nLAYER\n  2\n%s\n"
+               " 70\n  64\n 6\nCONTINUOUS\n", lname);
+  }
+  lastcolor = -1;
 }
-#endif /* def notdef */
-
 
 /*
  * Utility function to create a IM image. Returns
@@ -293,866 +254,212 @@ DEBUG_IF printf("addImageCache\n<BR>");
 imageObj *msImageCreateIM(int width, int height, outputFormatObj *format,
                           char *imagepath, char *imageurl, double resolution, double defresolution)
 {
-    imageObj  *image=NULL;
-    if (setvbuf(stdout, NULL, _IONBF , 0)){
-               printf("Whoops...");
-    };
-DEBUG_IF printf("msImageCreateIM<BR>\n");
-    if (width > 0 && height > 0)
-    {
-        image = (imageObj *)calloc(1,sizeof(imageObj));
-        MS_CHECK_ALLOC(image, sizeof(imageObj), NULL);
-/*
-
-        if( format->imagemode == MS_IMAGEMODE_RGB 
-            || format->imagemode == MS_IMAGEMODE_RGBA )
-        {
-#if IM2_VERS > 1
-            image->img.gd = gdImageCreateTrueColor(width, height);
-#else
-            msSetError(MS_IMGERR, 
-                       "Attempt to use RGB or RGBA IMAGEMODE with IM 1.x, please upgrade to GD 2.x.", "msImageCreateGD()" );
-#endif
-        }
-        else
-            image->img.gd = gdImageCreate(width, height);
- */   
-        if (image)
-        {
-	    imgStr.string = &(image->img.imagemap);
-	    imgStr.alloc_size = &(image->size);
-
-            image->format = format;
-            format->refcount++;
-
-            image->width = width;
-            image->height = height;
-            image->imagepath = NULL;
-            image->imageurl = NULL;
-            image->resolution = resolution;
-            image->resolutionfactor = resolution/defresolution;
-
-	    if( strcasecmp("ON",msGetOutputFormatOption( format, "DXF", "OFF" )) == 0){
-		    dxf = 1;
-		    im_iprintf(&layerStr, "  2\nLAYER\n 70\n  10\n");
-	    } else
-		    dxf = 0;
-
-	    if( strcasecmp("ON",msGetOutputFormatOption( format, "SCRIPT", "OFF" )) == 0){
-		    dxf = 2;
-		    im_iprintf(&layerStr, "");
-	    }
-
-	    /* get href formation string options */
-	    polyHrefFmt = makeFmtSafe(msGetOutputFormatOption
-	      ( format, "POLYHREF", "javascript:Clicked('%s');"), 1);
-            polyMOverFmt = makeFmtSafe(msGetOutputFormatOption
-	      ( format, "POLYMOUSEOVER", ""), 1);
-	    polyMOutFmt = makeFmtSafe(msGetOutputFormatOption
-	      ( format, "POLYMOUSEOUT", ""), 1);
-	    symbolHrefFmt = makeFmtSafe(msGetOutputFormatOption
-	      ( format, "SYMBOLHREF", "javascript:SymbolClicked();"), 1);
-	    symbolMOverFmt = makeFmtSafe(msGetOutputFormatOption
-	      ( format, "SYMBOLMOUSEOVER", ""), 1);
-	    symbolMOutFmt = makeFmtSafe(msGetOutputFormatOption
-	      ( format, "SYMBOLMOUSEOUT", ""), 1);
-	    /* get name of client-side image map */
-	    mapName = msGetOutputFormatOption
-	      ( format, "MAPNAME", "map1" );
-	    /* should we suppress area declarations with no title? */
-	    if( strcasecmp("YES",msGetOutputFormatOption( format, "SUPPRESS", "NO" )) == 0){
-	      suppressEmpty=1;
-	    }
-
-	    lname = msStrdup("NONE");
-	    *(imgStr.string) = msStrdup("");
-	    if (*(imgStr.string)){
-		    *(imgStr.alloc_size) =
-			    imgStr.string_len = strlen(*(imgStr.string));
-	    } else {
-		    *(imgStr.alloc_size) =
-			    imgStr.string_len = 0;
-	    }
-            if (imagepath)
-            {
-                image->imagepath = msStrdup(imagepath);
-            }
-            if (imageurl)
-            {
-                image->imageurl = msStrdup(imageurl);
-            }
-            
-            return image;
-        }
-        else
-            free( image );   
-    }
-    else
-    {
-        msSetError(MS_IMGERR, 
-                   "Cannot create IM image of size %d x %d.", 
-                   "msImageCreateIM()", width, height );
-    }
-    return image;
-}
-
-/*
- * Utility function to initialize the color of an image.  The background
- * color is passed, but the outputFormatObj is consulted to see if the
- * transparency should be set (for RGBA images).   Note this function only
- * affects TrueColor images.
- */
-
-void msImageInitIM( imageObj *image )
-
-{
-DEBUG_IF printf("msImageInitIM<BR>\n");
-/*    if( image->format->imagemode == MS_IMAGEMODE_PC256 ) {
-        gdImageColorAllocate(image->img.gd, background->red, background->green, background->blue);
-        return;
-    }
-
-#if IM2_VERS > 1
-    {
-        int		pen, pixels, line;
-        int             *tpixels;
-
-        if( image->format->imagemode == MS_IMAGEMODE_RGBA )
-            pen = imTrueColorAlpha( background->red, 
-                                    background->green, 
-                                    background->blue,
-                                    image->format->transparent ? 127 : 0 );
-        else
-            pen = imTrueColor( background->red, 
-                               background->green, 
-                               background->blue );
-
-        for( line = 0; line < image->img.gd->sy; line++ )
-        {
-            pixels = image->img.gd->sx;
-            tpixels = image->img.gd->tpixels[line];
-
-            while( pixels-- > 0 )
-                *(tpixels++) = pen;
-        }
-    }
-#endif
-*/
-}
-
-/*
- * Utility function to load an image in a IM supported format, and
- * return it as a valid imageObj.
- */
-imageObj *msImageLoadIM( const char *filename )
-{
-/*  FILE *stream;
-  gdImagePtr img=NULL;
-  const char *driver = NULL;
-  char bytes[8];
-*/  imageObj      *image = NULL;
-
-  DEBUG_IF printf("msImageLoadIM<BR>\n");
-/*
-  image = (imageObj *)calloc(1,sizeof(imageObj));
-  
-  stream = fopen(filename,"rb"); // allocate input and output images (same size)
-  if(!stream) {
-    msSetError(MS_IOERR, "(%s)", "msImageLoadIM()", filename );
-    return(NULL);
-  }
-
-  fread(bytes,8,1,stream); // read some bytes to try and identify the file
-  rewind(stream); // reset the image for the readers
-  if (memcmp(bytes,"GIF8",4)==0) {
-#ifdef USE_GD_GIF
-    img = gdImageCreateFromGif(stream);
-    driver = "IM/GIF";
-    image->img.gd = img;
-    image->imagepath = NULL;
-    image->imageurl = NULL;
-    image->width = img->sx;
-    image->height = img->sy;
-#else
-    msSetError(MS_MISCERR, "Unable to load GIF reference image.", "msImageLoadIM()");
-    fclose(stream);
-    return(NULL);
-#endif
-  } else if (memcmp(bytes,PNGsig,8)==0) {
-#ifdef USE_GD_PNG
-    img = gdImageCreateFromPng(stream);
-    driver = "IM/PNG";
-    image->img.gd = img;
-    image->imagepath = NULL;
-    image->imageurl = NULL;
-    image->width = img->sx;
-    image->height = img->sy;
-#else
-    msSetError(MS_MISCERR, "Unable to load PNG reference image.", "msImageLoadIM()");
-    fclose(stream);
-    return(NULL);
-#endif
-  } else if (memcmp(bytes,JPEGsig,3)==0) {
-#ifdef USE_GD_JPEG
-    img = gdImageCreateFromJpeg(stream);
-    driver = "IM/JPEG";
-    image->img.gd = img;
-    image->imagepath = NULL;
-    image->imageurl = NULL;
-    image->width = img->sx;
-    image->height = img->sy;
-#else
-    msSetError(MS_MISCERR, "Unable to load JPEG reference image.", "msImageLoadIM()");
-    fclose(stream);
-    return(NULL);
-#endif
-  }
-
-  if(!img) {
-    msSetError(MS_IMERR, "Unable to initialize image '%s'", "msLoadImage()", 
-               filename);
-    fclose(stream);
-    return(NULL);
-  }
-
-  // Create an outputFormatObj for the format. //
-  image->format = msCreateDefaultOutputFormat( NULL, driver );
-
-  if( image->format == NULL )
-  {
-    msSetError(MS_IMERR, "Unable to create default OUTPUTFORMAT definition for driver '%s'.", "msImageLoadGD()", driver );
-    return(NULL);
-  }
-*/
-  return image;
-}
-
-#ifdef notdef /* not currently used */
-
-/* TODO: might be a way to optimize this (halve the number of additions) */
-static void imageOffsetPolyline(gdImagePtr img, shapeObj *p, int color, int offsetx, int offsety)
-{
-/*  int i, j;
-  double dx, dy;
-  int ox=0, oy=0;
-*/
-  DEBUG_IF printf("imageOffsetPolyline\n<BR>");
-/*
-  if(offsety == -99) { // old-style offset (version 3.3 and earlier)
-    for (i = 0; i < p->numlines; i++) {
-      for(j=1; j<p->line[i].numpoints; j++) {        
-	dx = abs(p->line[i].point[j-1].x - p->line[i].point[j].x);
-	dy = abs(p->line[i].point[j-1].y - p->line[i].point[j].y);
-	if(dx<=dy)
-	  ox=offsetx;
-	else
-	  oy=offsetx;
-        
-        gdImageLine(img, (int)p->line[i].point[j-1].x+ox, (int)p->line[i].point[j-1].y+oy, (int)p->line[i].point[j].x+ox, (int)p->line[i].point[j].y+oy, color);
-        ox=0;
-        oy=0;
+  imageObj  *image=NULL;
+  if (setvbuf(stdout, NULL, _IONBF , 0)) {
+    printf("Whoops...");
+  };
+  DEBUG_IF printf("msImageCreateIM<BR>\n");
+  if (width > 0 && height > 0) {
+    image = (imageObj *)calloc(1,sizeof(imageObj));
+    MS_CHECK_ALLOC(image, sizeof(imageObj), NULL);
+    if (image) {
+      imgStr.string = &(image->img.imagemap);
+      imgStr.alloc_size = &(image->size);
+
+      image->format = format;
+      format->refcount++;
+
+      image->width = width;
+      image->height = height;
+      image->imagepath = NULL;
+      image->imageurl = NULL;
+      image->resolution = resolution;
+      image->resolutionfactor = resolution/defresolution;
+
+      if( strcasecmp("ON",msGetOutputFormatOption( format, "DXF", "OFF" )) == 0) {
+        dxf = 1;
+        im_iprintf(&layerStr, "  2\nLAYER\n 70\n  10\n");
+      } else
+        dxf = 0;
+
+      if( strcasecmp("ON",msGetOutputFormatOption( format, "SCRIPT", "OFF" )) == 0) {
+        dxf = 2;
+        im_iprintf(&layerStr, "");
       }
-    }
-  } else { // normal offset (eg. drop shadow)
-    for (i = 0; i < p->numlines; i++)
-      for(j=1; j<p->line[i].numpoints; j++)
-        gdImageLine(img, (int)p->line[i].point[j-1].x+offsetx, (int)p->line[i].point[j-1].y+offsety, (int)p->line[i].point[j].x+offsetx, (int)p->line[i].point[j].y+offsety, color);
-  }
-  */
-}
-
-static void imagePolyline(gdImagePtr img, shapeObj *p, int color, int offsetx, int offsety)
-{
-/* int i, j; */
-  
-DEBUG_IF printf("imagePolyline\n<BR>");
-/*
- if(offsetx != 0 || offsetx != 0) 
-    imageOffsetPolyline(img, p, color, offsetx, offsety);
-  else {
-    for (i = 0; i < p->numlines; i++)
-      for(j=1; j<p->line[i].numpoints; j++)
-        gdImageLine(img, (int)p->line[i].point[j-1].x, (int)p->line[i].point[j-1].y, (int)p->line[i].point[j].x, (int)p->line[i].point[j].y, color);
-  }
-  */
-}
-#endif /* def notdef */
-
-/* ------------------------------------------------------------------------- */
-/* Stroke an ellipse with a line symbol of the specified size and color      */
-/* ------------------------------------------------------------------------- */
-void msCircleDrawLineSymbolIM(symbolSetObj *symbolset, imageObj* img, pointObj *p, double r, styleObj *style, double scalefactor)
-{
-/*  int i, j;
-  symbolObj *symbol;
-  int styleDashed[100];
-  int x, y, ox, oy;
-  int bc, fc;
-  int brush_bc, brush_fc;
-  double size, d;
-  gdImagePtr brush=NULL;
-  gdPoint points[MS_MAXVECTORPOINTS];
-*/
-  DEBUG_IF printf("msCircleDrawLineSymbolIM\n<BR>");
-/*  
-  if(!p) return;
 
-  if(style->backgroundcolor.pen == MS_PEN_UNSET) msImageSetPenIM(img, &(style->backgroundcolor));
-  if(style->color.pen == MS_PEN_UNSET) msImageSetPenIM(img, &(style->color));
-  if(style->outlinecolor.pen == MS_PEN_UNSET) msImageSetPenIM(img, &(style->outlinecolor));
-  
-  symbol = symbolset->symbol[style->symbol];
-  bc = style->backgroundcolor.pen;
-  fc = style->color.pen;
-  if(fc==-1) fc = style->outlinecolor.pen;
-  ox = style->offsetx; // TODO: add scaling?
-  oy = style->offsety;
-  size = MS_NINT(style->size*scalefactor);
-  size = MS_MAX(size, style->minsize);
-  size = MS_MIN(size, style->maxsize);
-
-  if(style->symbol > symbolset->numsymbols || style->symbol < 0) return; // no such symbol, 0 is OK
-  if(fc < 0) return; // nothing to do
-  if(size < 1) return; // size too small
-
-  if(symbol == 0) { // just draw a single width line
-    gdImageArc(img, (int)p->x + ox, (int)p->y + oy, (int)r, (int)r, 0, 360, fc);
-    return;
-  }
-
-  switch(symbol->type) {
-  case(MS_SYMBOL_SIMPLE):
-    if(bc == -1) bc = imTransparent;
-    break;
-  case(MS_SYMBOL_TRUETYPE):
-    // msImageTruetypePolyline(img, p, symbol, fc, size, symbolset->fontset);
-    return;
-    break;
-  case(MS_SYMBOL_ELLIPSE):   
-    bc = imTransparent;
-
-    d = size/symbol->sizey;
-    x = MS_NINT(symbol->sizex*d);    
-    y = MS_NINT(symbol->sizey*d);
-   
-    if((x < 2) && (y < 2)) break;
-    
-    // create the brush image
-    if((brush = searchImageCache(symbolset->imagecache, style, size)) == NULL) { // not in cache, create
-      brush = gdImageCreate(x, y);
-      brush_bc = gdImageColorAllocate(brush, gdImageRed(img,0), gdImageGreen(img, 0), gdImageBlue(img, 0));    
-      gdImageColorTransparent(brush,0);
-      brush_fc = gdImageColorAllocate(brush, style->color.red, style->color.green, style->color.blue);
-      
-      x = MS_NINT(brush->sx/2); // center the ellipse
-      y = MS_NINT(brush->sy/2);
-      
-      // draw in the brush image
-      gdImageArc(brush, x, y, MS_NINT(d*symbol->points[0].x), MS_NINT(d*symbol->points[0].y), 0, 360, brush_fc);
-      if(symbol->filled)
-	gdImageFillToBorder(brush, x, y, brush_fc, brush_fc);
-      
-      symbolset->imagecache = addImageCache(symbolset->imagecache, &symbolset->imagecachesize, style, size, brush);
-    }
+      /* get href formation string options */
+      polyHrefFmt = makeFmtSafe(msGetOutputFormatOption
+                                ( format, "POLYHREF", "javascript:Clicked('%s');"), 1);
+      polyMOverFmt = makeFmtSafe(msGetOutputFormatOption
+                                 ( format, "POLYMOUSEOVER", ""), 1);
+      polyMOutFmt = makeFmtSafe(msGetOutputFormatOption
+                                ( format, "POLYMOUSEOUT", ""), 1);
+      symbolHrefFmt = makeFmtSafe(msGetOutputFormatOption
+                                  ( format, "SYMBOLHREF", "javascript:SymbolClicked();"), 1);
+      symbolMOverFmt = makeFmtSafe(msGetOutputFormatOption
+                                   ( format, "SYMBOLMOUSEOVER", ""), 1);
+      symbolMOutFmt = makeFmtSafe(msGetOutputFormatOption
+                                  ( format, "SYMBOLMOUSEOUT", ""), 1);
+      /* get name of client-side image map */
+      mapName = msGetOutputFormatOption
+                ( format, "MAPNAME", "map1" );
+      /* should we suppress area declarations with no title? */
+      if( strcasecmp("YES",msGetOutputFormatOption( format, "SUPPRESS", "NO" )) == 0) {
+        suppressEmpty=1;
+      }
 
-    gdImageSetBrush(img, brush);
-    fc=1; bc=0;
-    break;
-  case(MS_SYMBOL_PIXMAP):
-    gdImageSetBrush(img, symbol->img);
-    fc=1; bc=0;
-    break;
-  case(MS_SYMBOL_VECTOR):
-    if(bc == -1) bc = imTransparent;
-
-    d = size/symbol->sizey;
-    x = MS_NINT(symbol->sizex*d);    
-    y = MS_NINT(symbol->sizey*d);
-
-    if((x < 2) && (y < 2)) break;
-
-    // create the brush image
-    if((brush = searchImageCache(symbolset->imagecache, style, size)) == NULL) { // not in cache, create
-      brush = gdImageCreate(x, y);
-      if(style->backgroundcolor.pen >= 0)
-	brush_bc = gdImageColorAllocate(brush, style->backgroundcolor.red, style->backgroundcolor.green, style->backgroundcolor.blue);
-      else {
-	brush_bc = gdImageColorAllocate(brush, gdImageRed(img,0), gdImageGreen(img, 0), gdImageBlue(img, 0));
-	gdImageColorTransparent(brush,0);
+      lname = msStrdup("NONE");
+      *(imgStr.string) = msStrdup("");
+      if (*(imgStr.string)) {
+        *(imgStr.alloc_size) =
+          imgStr.string_len = strlen(*(imgStr.string));
+      } else {
+        *(imgStr.alloc_size) =
+          imgStr.string_len = 0;
       }
-      brush_fc = gdImageColorAllocate(brush, style->color.red, style->color.green, style->color.blue);
-      
-      // draw in the brush image
-      for(i=0;i < symbol->numpoints;i++) {
-	points[i].x = MS_NINT(d*symbol->points[i].x);
-	points[i].y = MS_NINT(d*symbol->points[i].y);
+      if (imagepath) {
+        image->imagepath = msStrdup(imagepath);
       }
-      gdImageFilledPolygon(brush, points, symbol->numpoints, brush_fc);
-
-      symbolset->imagecache = addImageCache(symbolset->imagecache, &symbolset->imagecachesize, style, size, brush);
-    }
-
-    gdImageSetBrush(img, brush);
-    fc = 1; bc = 0;
-    break;
-  }  
-
-  if(symbol->patternlength > 0) {
-    int k=0, sc;
-   
-    sc = fc; // start with foreground color
-    for(i=0; i<symbol->patternlength; i++) {      
-      for(j=0; j<symbol->pattern[i]; j++) {
-	styleDashed[k] = sc;
-	k++;
-      } 
-      if(sc==fc) sc = bc; else sc = fc;
-    }
-    gdImageSetStyle(img, styleDashed, k);
-
-    // gdImageArc(brush, x, y, MS_NINT(d*symbol->points[0].x), MS_NINT(d*symbol->points[0].y), 0, 360, brush_fc);
-
-    if(!brush && !symbol->img)
-      gdImageArc(img, (int)p->x + ox, (int)p->y + oy, (int)(2*r), (int)(2*r), 0, 360, gdStyled);      
-    else 
-      gdImageArc(img, (int)p->x + ox, (int)p->y + oy, (int)(2*r), (int)(2*r), 0, 360, gdStyledBrushed);
-  } else {
-    if(!brush && !symbol->img)
-      gdImageArc(img, (int)p->x + ox, (int)p->y + oy, (int)(2*r), (int)(2*r), 0, 360, fc);
-    else
-      gdImageArc(img, (int)p->x + ox, (int)p->y + oy, (int)(2*r), (int)(2*r), 0, 360, gdBrushed);
-  }
-*/
-  return;
-}
-
-/* ------------------------------------------------------------------------- */
-/* Fill a circle with a shade symbol of the specified size and color         */
-/* ------------------------------------------------------------------------- */
-void msCircleDrawShadeSymbolIM(symbolSetObj *symbolset, imageObj* img, 
-                               pointObj *p, double r, styleObj *style, double scalefactor)
-{
-/*  symbolObj *symbol;
-  int i;
-  gdPoint oldpnt,newpnt;
-  gdPoint sPoints[MS_MAXVECTORPOINTS];
-  gdImagePtr tile=NULL;
-  int x, y, ox, oy;
-
-  int fc, bc, oc;
-  int tile_bc=-1, tile_fc=-1; // colors (background and foreground) //
-  double size, d;  
-
-  int bbox[8];
-  rectObj rect;
-  char *font=NULL;
-*/
-DEBUG_IF printf("msCircleDrawShadeSymbolIM<BR>\n");
-/*
-  if(!p) return;
-
-  if(style->backgroundcolor.pen == MS_PEN_UNSET) msImageSetPenIM(img, &(style->backgroundcolor));
-  if(style->color.pen == MS_PEN_UNSET) msImageSetPenIM(img, &(style->color));
-  if(style->outlinecolor.pen == MS_PEN_UNSET) msImageSetPenIM(img, &(style->outlinecolor));
-
-  symbol = symbolset->symbol[style->symbol];
-  bc = style->backgroundcolor.pen;
-  fc = style->color.pen;
-  oc = style->outlinecolor.pen;
-  ox = style->offsetx; // TODO: add scaling?
-  oy = style->offsety;
-  size = MS_NINT(style->size*scalefactor);
-  size = MS_MAX(size, style->minsize);
-  size = MS_MIN(size, style->maxsize);
-
-  if(fc==-1 && oc!=-1) { // use msDrawLineSymbolIM() instead (POLYLINE)
-    msCircleDrawLineSymbolIM(symbolset, img, p, r, style, scalefactor);
-    return;
-  }
-
-  if(style->symbol > symbolset->numsymbols || style->symbol < 0) return; // no such symbol, 0 is OK
-  if(fc ) return; // invalid color, -1 is valid
-  if(size < 1) return; // size too small
-      
-  if(style->symbol == 0) { // simply draw a single pixel of the specified color
-    msImageFilledCircle(img, p, r, fc);
-    if(oc>-1) gdImageArc(img, (int)p->x, (int)p->y, (int)(2*r), (int)(2*r), 0, 360, oc);
-    return;
-  }
-
-  switch(symbol->type) {
-  case(MS_SYMBOL_TRUETYPE):    
-    
-#if defined (USE_GD_FT) || defined (USE_GD_TTF)
-    font = msLookupHashTable(&(symbolset->fontset->fonts), symbol->font);
-    if(!font) return;
-
-    if(msGetCharacterSize(symbol->character, size, font, &rect) != MS_SUCCESS) return;
-    x = rect.maxx - rect.minx;
-    y = rect.maxy - rect.miny;
-
-    tile = gdImageCreate(x, y);
-    if(bc >= 0)
-      tile_bc = gdImageColorAllocate(tile, style->backgroundcolor.red, style->backgroundcolor.green, style->backgroundcolor.blue);
-    else {
-      tile_bc = gdImageColorAllocate(tile, gdImageRed(img, 0), gdImageGreen(img, 0), gdImageBlue(img, 0));
-      gdImageColorTransparent(tile,0);
-    }    
-    tile_fc = gdImageColorAllocate(tile, style->color.red, style->color.green, style->color.blue);
-    
-    x = -rect.minx;
-    y = -rect.miny;
-
-#ifdef USE_GD_TTF
-    gdImageStringTTF(tile, bbox, ((symbol->antialias)?(tile_fc):-(tile_fc)), font, size, 0, x, y, symbol->character);
-#else
-    gdImageStringFT(tile, bbox, ((symbol->antialias)?(tile_fc):-(tile_fc)), font, size, 0, x, y, symbol->character);
-#endif    
-
-    gdImageSetTile(img, tile);
-#endif
-
-    break;
-  case(MS_SYMBOL_PIXMAP):
-    
-    gdImageSetTile(img, symbol->img);
-
-    break;
-  case(MS_SYMBOL_ELLIPSE):    
-   
-    d = size/symbol->sizey; // size ~ height in pixels
-    x = MS_NINT(symbol->sizex*d)+1;
-    y = MS_NINT(symbol->sizey*d)+1;
-
-    if((x <= 1) && (y <= 1)) { // No sense using a tile, just fill solid
-      msImageFilledCircle(img, p, r, fc);
-      if(oc>-1) gdImageArc(img, (int)p->x, (int)p->y, (int)(2*r), (int)(2*r), 0, 360, oc);
-      return;
-    }
-
-    tile = gdImageCreate(x, y);
-    if(bc >= 0)
-      tile_bc = gdImageColorAllocate(tile, style->backgroundcolor.red, style->backgroundcolor.green, style->backgroundcolor.blue);
-    else {
-      tile_bc = gdImageColorAllocate(tile, gdImageRed(img, 0), gdImageGreen(img, 0), gdImageBlue(img, 0));
-      gdImageColorTransparent(tile,0);
-    }    
-    tile_fc = gdImageColorAllocate(tile, style->color.red, style->color.green, style->color.blue);
-    
-    x = MS_NINT(tile->sx/2);
-    y = MS_NINT(tile->sy/2);
-
-    //
-   //draw in the tile image
-    //
-    gdImageArc(tile, x, y, MS_NINT(d*symbol->points[0].x), MS_NINT(d*symbol->points[0].y), 0, 360, tile_fc);
-    if(symbol->filled)
-      gdImageFillToBorder(tile, x, y, tile_fc, tile_fc);
-
-    //
-   //Fill the polygon in the main image
-    //
-    gdImageSetTile(img, tile);
- 
-    break;
-  case(MS_SYMBOL_VECTOR):
-
-    if(fc < 0)
-      return;
-
-    d = size/symbol->sizey; // size ~ height in pixels
-    x = MS_NINT(symbol->sizex*d)+1;    
-    y = MS_NINT(symbol->sizey*d)+1;
-
-    if((x <= 1) && (y <= 1)) { // No sense using a tile, just fill solid
-      msImageFilledCircle(img, p, r, fc);
-      if(oc>-1) gdImageArc(img, (int)p->x, (int)p->y, (int)(2*r), (int)(2*r), 0, 360, oc);
-      return;
-    }
-
-    //
-   //create tile image
-    //
-    tile = gdImageCreate(x, y);
-    if(bc >= 0)
-      tile_bc = gdImageColorAllocate(tile, style->backgroundcolor.red, style->backgroundcolor.green, style->backgroundcolor.blue);
-    else {
-      tile_bc = gdImageColorAllocate(tile, gdImageRed(img, 0), gdImageGreen(img, 0), gdImageBlue(img, 0));
-      gdImageColorTransparent(tile,0);
-    }
-    tile_fc = gdImageColorAllocate(tile, style->color.red, style->color.green, style->color.blue);
-   
-    //
-   //draw in the tile image
-    //
-    if(symbol->filled) {
-
-      for(i=0;i < symbol->numpoints;i++) {
-	sPoints[i].x = MS_NINT(d*symbol->points[i].x);
-	sPoints[i].y = MS_NINT(d*symbol->points[i].y);
+      if (imageurl) {
+        image->imageurl = msStrdup(imageurl);
       }
-      gdImageFilledPolygon(tile, sPoints, symbol->numpoints, tile_fc);      
-
-    } else  { // shade is a vector drawing //
-      
-      oldpnt.x = MS_NINT(d*symbol->points[0].x); // convert first point in shade smbol //
-      oldpnt.y = MS_NINT(d*symbol->points[0].y);
-
-      // step through the shade symbol //
-      for(i=1;i < symbol->numpoints;i++) {
-	if((symbol->points[i].x < 0) && (symbol->points[i].y < 0)) {
-	  oldpnt.x = MS_NINT(d*symbol->points[i].x);
-	  oldpnt.y = MS_NINT(d*symbol->points[i].y);
-	} else {
-	  if((symbol->points[i-1].x < 0) && (symbol->points[i-1].y < 0)) { // Last point was PENUP, now a new beginning //
-	    oldpnt.x = MS_NINT(d*symbol->points[i].x);
-	    oldpnt.y = MS_NINT(d*symbol->points[i].y);
-	  } else {
-	    newpnt.x = MS_NINT(d*symbol->points[i].x);
-	    newpnt.y = MS_NINT(d*symbol->points[i].y);
-	    gdImageLine(tile, oldpnt.x, oldpnt.y, newpnt.x, newpnt.y, tile_fc);
-	    oldpnt = newpnt;
-	  }
-	}
-      } // end for loop //
-    }
 
-    //
-   //Fill the polygon in the main image
-    //
-    gdImageSetTile(img, tile);
- 
-    break;
-  default:
-    break;
+      return image;
+    } else
+      free( image );
+  } else {
+    msSetError(MS_IMGERR,
+               "Cannot create IM image of size %d x %d.",
+               "msImageCreateIM()", width, height );
   }
-
-  //
- //Fill the polygon in the main image
-  //
-  msImageFilledCircle(img, p, r, imTiled);
-  if(oc>-1) gdImageArc(img, (int)p->x, (int)p->y, (int)(2*r), (int)(2*r), 0, 360, oc);
-  if(tile) gdImageDestroy(tile);
-*/
-  return;
+  return image;
 }
 
-
 /* ------------------------------------------------------------------------- */
 /* Draw a single marker symbol of the specified size and color               */
 /* ------------------------------------------------------------------------- */
 void msDrawMarkerSymbolIM(symbolSetObj *symbolset, imageObj* img, pointObj *p, styleObj *style, double scalefactor)
 {
   symbolObj *symbol;
-/*  int offset_x, offset_y, x, y;
-  int j;
-  gdPoint oldpnt,newpnt;
-  gdPoint mPoints[MS_MAXVECTORPOINTS];
-
-  gdImagePtr tmp;
-  int tmp_fc=-1, tmp_bc, tmp_oc=-1;
-*/  int fc, bc, oc;
-/*  double d;
-
-  
-  int bbox[8];
-  rectObj rect;
-  char *font=NULL;
-*/
   int ox, oy;
   double size;
-	
-DEBUG_IF printf("msDrawMarkerSymbolIM\n<BR>");
 
-/* skip this, we don't do text */
+  DEBUG_IF printf("msDrawMarkerSymbolIM\n<BR>");
+
+  /* skip this, we don't do text */
 
 
 
   if(!p) return;
 
-/* if(style->backgroundcolor.pen == MS_PEN_UNSET) msImageSetPenIM(img, &(style->backgroundcolor)); */
-/* if(style->color.pen == MS_PEN_UNSET) msImageSetPenIM(img, &(style->color)); */
-/* if(style->outlinecolor.pen == MS_PEN_UNSET) msImageSetPenIM(img, &(style->outlinecolor)); */
 
   symbol = symbolset->symbol[style->symbol];
-  bc = style->backgroundcolor.pen;
-  fc = style->color.pen;
-  oc = style->outlinecolor.pen;
   ox = style->offsetx*scalefactor;
   oy = style->offsety*scalefactor;
   if(style->size == -1) {
-      size = msSymbolGetDefaultSize( symbol );
-      size = MS_NINT(size*scalefactor);
-  }
-  else
-      size = MS_NINT(style->size*scalefactor);
+    size = msSymbolGetDefaultSize( symbol );
+    size = MS_NINT(size*scalefactor);
+  } else
+    size = MS_NINT(style->size*scalefactor);
   size = MS_MAX(size, style->minsize*img->resolutionfactor);
   size = MS_MIN(size, style->maxsize*img->resolutionfactor);
 
   if(style->symbol > symbolset->numsymbols || style->symbol < 0) return; /* no such symbol, 0 is OK */
-/* if(fc<0 && oc<0) return; // nothing to do */
   if(size < 1) return; /* size too small */
 
-/* DEBUG_IF printf(".%d.%d.%d.", symbol->type, style->symbol, fc); */
+  /* DEBUG_IF printf(".%d.%d.%d.", symbol->type, style->symbol, fc); */
   if(style->symbol == 0) { /* simply draw a single pixel of the specified color */
-/* gdImageSetPixel(img, p->x + ox, p->y + oy, fc); */
-		
+
     if (dxf) {
       if (dxf==2)
-	im_iprintf (&imgStr, "POINT\n%.0f %.0f\n%d\n",
-		 p->x + ox, p->y + oy, matchdxfcolor(style->color));
+        im_iprintf (&imgStr, "POINT\n%.0f %.0f\n%d\n",
+                    p->x + ox, p->y + oy, matchdxfcolor(style->color));
       else
-	im_iprintf (&imgStr, 
-		 "  0\nPOINT\n 10\n%f\n 20\n%f\n 30\n0.0\n"
-		 " 62\n%6d\n  8\n%s\n",
-		 p->x + ox, p->y + oy, matchdxfcolor(style->color), lname);
+        im_iprintf (&imgStr,
+                    "  0\nPOINT\n 10\n%f\n 20\n%f\n 30\n0.0\n"
+                    " 62\n%6d\n  8\n%s\n",
+                    p->x + ox, p->y + oy, matchdxfcolor(style->color), lname);
     } else {
       im_iprintf (&imgStr, "<area ");
       if (strcmp(symbolHrefFmt,"%.s")!=0) {
-	      im_iprintf (&imgStr, "href=\"");
-	      im_iprintf (&imgStr, symbolHrefFmt, lname);
-	      im_iprintf (&imgStr, "\" ");
+        im_iprintf (&imgStr, "href=\"");
+        im_iprintf (&imgStr, symbolHrefFmt, lname);
+        im_iprintf (&imgStr, "\" ");
       }
       if (strcmp(symbolMOverFmt,"%.s")!=0) {
-	      im_iprintf (&imgStr, "onMouseOver=\"");
-	      im_iprintf (&imgStr, symbolMOverFmt, lname);
-	      im_iprintf (&imgStr, "\" ");
+        im_iprintf (&imgStr, "onMouseOver=\"");
+        im_iprintf (&imgStr, symbolMOverFmt, lname);
+        im_iprintf (&imgStr, "\" ");
       }
       if (strcmp(symbolMOutFmt,"%.s")!=0) {
-	      im_iprintf (&imgStr, "onMouseOut=\"");
-	      im_iprintf (&imgStr, symbolMOutFmt, lname);
-	      im_iprintf (&imgStr, "\" ");
+        im_iprintf (&imgStr, "onMouseOut=\"");
+        im_iprintf (&imgStr, symbolMOutFmt, lname);
+        im_iprintf (&imgStr, "\" ");
       }
       im_iprintf (&imgStr, "shape=\"circle\" coords=\"%.0f,%.0f, 3\" />\n",
-	       p->x + ox, p->y + oy);
+                  p->x + ox, p->y + oy);
     }
-		      
-	/* point2 = &( p->line[j].point[i] ); */
-	/* if(point1->y == point2->y) {} */
-    return;
-  }  
-DEBUG_IF printf("A");
-  switch(symbol->type) {  
-  case(MS_SYMBOL_TRUETYPE):
-DEBUG_IF printf("T");
-/*
- * #if defined (USE_GD_FT) || defined (USE_GD_TTF)
-    font = msLookupHashTable(&(symbolset->fontset->fonts), symbol->font);
-    if(!font) return;
 
-    if(msGetCharacterSize(symbol->character, size, font, &rect) != MS_SUCCESS) return;
-
-    x = p->x + ox - (rect.maxx - rect.minx)/2 - rect.minx;
-    y = p->y + oy - rect.maxy + (rect.maxy - rect.miny)/2;  
+    /* point2 = &( p->line[j].point[i] ); */
+    /* if(point1->y == point2->y) {} */
+    return;
+  }
+  DEBUG_IF printf("A");
+  switch(symbol->type) {
+    case(MS_SYMBOL_TRUETYPE):
+      DEBUG_IF printf("T");
+      break;
+    case(MS_SYMBOL_PIXMAP):
+      DEBUG_IF printf("P");
+      break;
+    case(MS_SYMBOL_VECTOR):
+      DEBUG_IF printf("V");
+      {
+        double d, offset_x, offset_y;
+
+        d = size/symbol->sizey;
+        offset_x = MS_NINT(p->x - d*.5*symbol->sizex + ox);
+        offset_y = MS_NINT(p->y - d*.5*symbol->sizey + oy);
+
+        /* For now I only render filled vector symbols in imagemap, and no */
+        /* dxf support available yet.  */
+        if(symbol->filled && !dxf /* && fc >= 0 */ ) {
+          /* char *title=(p->numvalues) ? p->values[0] : ""; */
+          char *title = "";
+          int  j;
+
+          im_iprintf (&imgStr, "<area ");
+          if (strcmp(symbolHrefFmt,"%.s")!=0) {
+            im_iprintf (&imgStr, "href=\"");
+            im_iprintf (&imgStr, symbolHrefFmt, lname);
+            im_iprintf (&imgStr, "\" ");
+          }
+          if (strcmp(symbolMOverFmt,"%.s")!=0) {
+            im_iprintf (&imgStr, "onMouseOver=\"");
+            im_iprintf (&imgStr, symbolMOverFmt, lname);
+            im_iprintf (&imgStr, "\" ");
+          }
+          if (strcmp(symbolMOutFmt,"%.s")!=0) {
+            im_iprintf (&imgStr, "onMouseOut=\"");
+            im_iprintf (&imgStr, symbolMOutFmt, lname);
+            im_iprintf (&imgStr, "\" ");
+          }
 
-#ifdef USE_GD_TTF
-    gdImageStringTTF(img, bbox, ((symbol->antialias)?(fc):-(fc)), font, size, 0, x, y, symbol->character);
-#else
-    gdImageStringFT(img, bbox, ((symbol->antialias)?(fc):-(fc)), font, size, 0, x, y, symbol->character);
-#endif
+          im_iprintf (&imgStr, "title=\"%s\" shape=\"poly\" coords=\"", title);
 
-#endif
-*/
-    break;
-  case(MS_SYMBOL_PIXMAP):
-DEBUG_IF printf("P");
-/*    if(size == 1) { // don't scale
-      offset_x = MS_NINT(p->x - .5*symbol->img->sx + ox);
-      offset_y = MS_NINT(p->y - .5*symbol->img->sy + oy);
-      gdImageCopy(img, symbol->img, offset_x, offset_y, 0, 0, symbol->img->sx, symbol->img->sy);
-    } else {
-      d = size/symbol->img->sy;
-      offset_x = MS_NINT(p->x - .5*symbol->img->sx*d + ox);
-      offset_y = MS_NINT(p->y - .5*symbol->img->sy*d + oy);
-      gdImageCopyResized(img, symbol->img, offset_x, offset_y, 0, 0, symbol->img->sx*d, symbol->img->sy*d, symbol->img->sx, symbol->img->sy);
-    }
-    break;
-  case(MS_SYMBOL_ELLIPSE):
-    d = size/symbol->sizey;
-    x = MS_NINT(symbol->sizex*d)+1;
-    y = MS_NINT(symbol->sizey*d)+1;
-
-    // create temporary image and allocate a few colors //
-    tmp = gdImageCreate(x, y);
-    tmp_bc = gdImageColorAllocate(tmp, gdImageRed(img, 0), gdImageGreen(img, 0), gdImageBlue(img, 0));
-    gdImageColorTransparent(tmp, 0);
-    if(fc >= 0)
-      tmp_fc = gdImageColorAllocate(tmp, gdImageRed(img, fc), gdImageGreen(img, fc), gdImageBlue(img, fc));
-    if(oc >= 0)
-      tmp_oc = gdImageColorAllocate(tmp, gdImageRed(img, oc), gdImageGreen(img, oc), gdImageBlue(img, oc));
-
-    x = MS_NINT(tmp->sx/2);
-    y = MS_NINT(tmp->sy/2);
-
-    // draw in the temporary image //
-    if(tmp_oc >= 0) {
-      gdImageArc(tmp, x, y, MS_NINT(d*symbol->points[0].x), MS_NINT(d*symbol->points[0].y), 0, 360, tmp_oc);
-      if(symbol->filled && tmp_fc >= 0)
-	gdImageFillToBorder(tmp, x, y, tmp_oc, tmp_fc);
-    } else {
-      if(tmp_fc >= 0) {
-	gdImageArc(tmp, x, y, MS_NINT(d*symbol->points[0].x), MS_NINT(d*symbol->points[0].y), 0, 360, tmp_fc);
-	if(symbol->filled)
-	  gdImageFillToBorder(tmp, x, y, tmp_fc, tmp_fc);
+          for(j=0; j < symbol->numpoints; j++) {
+            im_iprintf (&imgStr, "%s %d,%d", j == 0 ? "": ",",
+                        MS_NINT(d*symbol->points[j].x + offset_x),
+                        MS_NINT(d*symbol->points[j].y + offset_y) );
+          }
+          im_iprintf (&imgStr, "\" />\n");
+        } /* end of imagemap, filled case. */
       }
-    }
+      break;
 
-    // paste the tmp image in the main image //
-    offset_x = MS_NINT(p->x - .5*tmp->sx + ox);
-    offset_y = MS_NINT(p->y - .5*tmp->sx + oy);
-    gdImageCopy(img, tmp, offset_x, offset_y, 0, 0, tmp->sx, tmp->sy);
-
-    gdImageDestroy(tmp);
-*/
-    break;
-  case(MS_SYMBOL_VECTOR):
-DEBUG_IF printf("V");
- {
-     double d, offset_x, offset_y;
-     
-     d = size/symbol->sizey;
-     offset_x = MS_NINT(p->x - d*.5*symbol->sizex + ox);
-     offset_y = MS_NINT(p->y - d*.5*symbol->sizey + oy);
-
-     /* For now I only render filled vector symbols in imagemap, and no */
-     /* dxf support available yet.  */
-     if(symbol->filled && !dxf /* && fc >= 0 */ ) {
-/* char *title=(p->numvalues) ? p->values[0] : ""; */
-         char *title = "";
-         int  j;
-
-         im_iprintf (&imgStr, "<area ");
-         if (strcmp(symbolHrefFmt,"%.s")!=0) {
-             im_iprintf (&imgStr, "href=\"");
-             im_iprintf (&imgStr, symbolHrefFmt, lname);
-             im_iprintf (&imgStr, "\" ");
-         }
-         if (strcmp(symbolMOverFmt,"%.s")!=0) {
-             im_iprintf (&imgStr, "onMouseOver=\"");
-             im_iprintf (&imgStr, symbolMOverFmt, lname);
-             im_iprintf (&imgStr, "\" ");
-         }
-         if (strcmp(symbolMOutFmt,"%.s")!=0) {
-             im_iprintf (&imgStr, "onMouseOut=\"");
-             im_iprintf (&imgStr, symbolMOutFmt, lname);
-             im_iprintf (&imgStr, "\" ");
-         }
-         
-         im_iprintf (&imgStr, "title=\"%s\" shape=\"poly\" coords=\"", title);
-         
-         for(j=0;j < symbol->numpoints;j++) {
-             im_iprintf (&imgStr, "%s %d,%d", j == 0 ? "": ",", 
-                         MS_NINT(d*symbol->points[j].x + offset_x),
-                         MS_NINT(d*symbol->points[j].y + offset_y) );
-         }
-         im_iprintf (&imgStr, "\" />\n");
-     } /* end of imagemap, filled case. */
- }
- break;
-
-  default:
-DEBUG_IF printf("DEF");
-    break;
+    default:
+      DEBUG_IF printf("DEF");
+      break;
   } /* end switch statement */
 
   return;
@@ -1164,197 +471,78 @@ DEBUG_IF printf("DEF");
 void msDrawLineSymbolIM(symbolSetObj *symbolset, imageObj* img, shapeObj *p, styleObj *style, double scalefactor)
 {
   symbolObj *symbol;
-/* int styleDashed[100]; */
-/* int x, y; */
-/* int brush_bc, brush_fc; */
-/* double size, d; */
-/* gdImagePtr brush=NULL; */
-/* gdPoint points[MS_MAXVECTORPOINTS]; */
-  int fc, bc;
   int i,j,l;
-char first = 1;
-double size;
-DEBUG_IF printf("msDrawLineSymbolIM<BR>\n");
+  char first = 1;
+  double size;
+  DEBUG_IF printf("msDrawLineSymbolIM<BR>\n");
 
 
   if(!p) return;
   if(p->numlines <= 0) return;
 
-/* if(style->backgroundcolor.pen == MS_PEN_UNSET) msImageSetPenIM(img, &(style->backgroundcolor)); */
-/* if(style->outlinecolor.pen == MS_PEN_UNSET) msImageSetPenIM(img, &(style->outlinecolor)); */
-/* if(style->color.pen == MS_PEN_UNSET) msImageSetPenIM(img, &(style->color)); */
-
   symbol = symbolset->symbol[style->symbol];
-  bc = style->backgroundcolor.pen;
-  fc = style->color.pen;
-  if(fc==-1) fc = style->outlinecolor.pen;
   if(style->size == -1) {
-      size = msSymbolGetDefaultSize( symbol );
-      size = MS_NINT(size*scalefactor);
-  }
-  else
-      size = MS_NINT(style->size*scalefactor);
+    size = msSymbolGetDefaultSize( symbol );
+    size = MS_NINT(size*scalefactor);
+  } else
+    size = MS_NINT(style->size*scalefactor);
   size = MS_MAX(size, style->minsize*img->resolutionfactor);
   size = MS_MIN(size, style->maxsize*img->resolutionfactor);
 
   if(style->symbol > symbolset->numsymbols || style->symbol < 0) return; /* no such symbol, 0 is OK */
   if (suppressEmpty && p->numvalues==0) return;/* suppress area with empty title */
-/* if(fc < 0) return; // nothing to do */
-/* if(size < 1) return; // size too small */
   if(style->symbol == 0) { /* just draw a single width line */
-/* imagePolyline(img, p, fc, style->offsetx, style->offsety); */
-		  for(l=0,j=0; j<p->numlines; j++) {
-		    if (dxf == 2){
-		      im_iprintf (&imgStr, "LINE\n%d\n", matchdxfcolor(style->color));
-		    } else if (dxf){
-		      im_iprintf (&imgStr, "  0\nPOLYLINE\n 70\n     0\n 62\n%6d\n  8\n%s\n", matchdxfcolor(style->color), lname);
-		    } else {
-                      char *title;
-
-                      first = 1;
-		      title=(p->numvalues) ? p->values[0] : "";
-		      im_iprintf (&imgStr, "<area ");
-		      if (strcmp(polyHrefFmt,"%.s")!=0) {
-			im_iprintf (&imgStr, "href=\"");
-			im_iprintf (&imgStr, polyHrefFmt, title);
-			im_iprintf (&imgStr, "\" ");
-		      }
-		      if (strcmp(polyMOverFmt,"%.s")!=0) {
-			im_iprintf (&imgStr, "onMouseOver=\"");
-			im_iprintf (&imgStr, polyMOverFmt, title);
-			im_iprintf (&imgStr, "\" ");
-		      }
-		      if (strcmp(polyMOutFmt,"%.s")!=0) {
-			im_iprintf (&imgStr, "onMouseOut=\"");
-			im_iprintf (&imgStr, polyMOutFmt, title);
-			im_iprintf (&imgStr, "\" ");
-		      }
-		      im_iprintf (&imgStr, "title=\"%s\" shape=\"poly\" coords=\"", title);
-		    }
-		/* point1 = &( p->line[j].point[p->line[j].numpoints-1] ); */
-		      for(i=0; i < p->line[j].numpoints; i++,l++) {
-				if (dxf == 2){
-					im_iprintf (&imgStr, "%.0f %.0f\n", p->line[j].point[i].x, p->line[j].point[i].y);
-				} else if (dxf){
-					im_iprintf (&imgStr, "  0\nVERTEX\n 10\n%f\n 20\n%f\n 30\n%f\n", p->line[j].point[i].x, p->line[j].point[i].y, 0.0);
-				} else {
-					im_iprintf (&imgStr, "%s %.0f,%.0f", first ? "": ",", p->line[j].point[i].x, p->line[j].point[i].y);
-				}
-				first = 0;
-			      
-		/* point2 = &( p->line[j].point[i] ); */
-		/* if(point1->y == point2->y) {} */
-		      }
-		      im_iprintf (&imgStr, dxf ? (dxf == 2 ? "": "  0\nSEQEND\n") : "\" />\n");
-		  }
-
-/* DEBUG_IF printf ("%d, ",strlen(img->img.imagemap) ); */
-    return;
-  }
-
-  DEBUG_IF printf("-%d-",symbol->type);
-  
-/*  switch(symbol->type) {
-  case(MS_SYMBOL_SIMPLE):
-    if(bc == -1) bc = imTransparent;
-    break;
-  case(MS_SYMBOL_TRUETYPE):
-    msImageTruetypePolyline(symbolset, img, p, style, scalefactor);
-    return;
-    break;
-  case(MS_SYMBOL_ELLIPSE):
-    bc = imTransparent;
-
-    d = (size)/symbol->sizey;
-    x = MS_NINT(symbol->sizex*d);    
-    y = MS_NINT(symbol->sizey*d);
-    
-    if((x < 2) && (y < 2)) break;
-    
-    // create the brush image
-    if((brush = searchImageCache(symbolset->imagecache, style, size)) == NULL) { // not in cache, create
-      brush = gdImageCreate(x, y);
-      brush_bc = gdImageColorAllocate(brush,gdImageRed(img,0), gdImageGreen(img, 0), gdImageBlue(img, 0));    
-      gdImageColorTransparent(brush,0);
-      brush_fc = gdImageColorAllocate(brush, style->color.red, style->color.green, style->color.blue);
-      
-      x = MS_NINT(brush->sx/2); // center the ellipse
-      y = MS_NINT(brush->sy/2);
-      
-      // draw in the brush image
-      gdImageArc(brush, x, y, MS_NINT(d*symbol->points[0].x), MS_NINT(d*symbol->points[0].y), 0, 360, brush_fc);
-      if(symbol->filled)
-	gdImageFillToBorder(brush, x, y, brush_fc, brush_fc);
-      
-      symbolset->imagecache = addImageCache(symbolset->imagecache, &symbolset->imagecachesize, style, size, brush);
-    }
-
-    gdImageSetBrush(img, brush);
-    fc = 1; bc = 0;
-    break;
-  case(MS_SYMBOL_PIXMAP):
-    gdImageSetBrush(img, symbol->img);
-    fc = 1; bc = 0;
-    break;
-  case(MS_SYMBOL_VECTOR):
-    if(bc == -1) bc = imTransparent;
-
-    d = size/symbol->sizey;
-    x = MS_NINT(symbol->sizex*d);    
-    y = MS_NINT(symbol->sizey*d);
-
-    if((x < 2) && (y < 2)) break;
-
-    // create the brush image
-    if((brush = searchImageCache(symbolset->imagecache, style, fc, size)) == NULL) { // not in cache, create
-      brush = gdImageCreate(x, y);
-      if(bc >= 0)
-	brush_bc = gdImageColorAllocate(brush, style->backgroundcolor.red, style->backgroundcolor.green, style->backgroundcolor.blue);
-      else {
-	brush_bc = gdImageColorAllocate(brush, gdImageRed(img,0), gdImageGreen(img, 0), gdImageBlue(img, 0));
-	gdImageColorTransparent(brush,0);
-      }
-      brush_fc = gdImageColorAllocate(brush,style->color.red, style->color.green, style->color.blue);
-      
-      // draw in the brush image 
-      for(i=0;i < symbol->numpoints;i++) {
-	points[i].x = MS_NINT(d*symbol->points[i].x);
-	points[i].y = MS_NINT(d*symbol->points[i].y);
+    for(l=0,j=0; j<p->numlines; j++) {
+      if (dxf == 2) {
+        im_iprintf (&imgStr, "LINE\n%d\n", matchdxfcolor(style->color));
+      } else if (dxf) {
+        im_iprintf (&imgStr, "  0\nPOLYLINE\n 70\n     0\n 62\n%6d\n  8\n%s\n", matchdxfcolor(style->color), lname);
+      } else {
+        char *title;
+
+        first = 1;
+        title=(p->numvalues) ? p->values[0] : "";
+        im_iprintf (&imgStr, "<area ");
+        if (strcmp(polyHrefFmt,"%.s")!=0) {
+          im_iprintf (&imgStr, "href=\"");
+          im_iprintf (&imgStr, polyHrefFmt, title);
+          im_iprintf (&imgStr, "\" ");
+        }
+        if (strcmp(polyMOverFmt,"%.s")!=0) {
+          im_iprintf (&imgStr, "onMouseOver=\"");
+          im_iprintf (&imgStr, polyMOverFmt, title);
+          im_iprintf (&imgStr, "\" ");
+        }
+        if (strcmp(polyMOutFmt,"%.s")!=0) {
+          im_iprintf (&imgStr, "onMouseOut=\"");
+          im_iprintf (&imgStr, polyMOutFmt, title);
+          im_iprintf (&imgStr, "\" ");
+        }
+        im_iprintf (&imgStr, "title=\"%s\" shape=\"poly\" coords=\"", title);
       }
-      gdImageFilledPolygon(brush, points, symbol->numpoints, brush_fc);
-
-      symbolset->imagecache = addImageCache(symbolset->imagecache, &symbolset->imagecachesize, style, size, brush);
-    }
+      /* point1 = &( p->line[j].point[p->line[j].numpoints-1] ); */
+      for(i=0; i < p->line[j].numpoints; i++,l++) {
+        if (dxf == 2) {
+          im_iprintf (&imgStr, "%.0f %.0f\n", p->line[j].point[i].x, p->line[j].point[i].y);
+        } else if (dxf) {
+          im_iprintf (&imgStr, "  0\nVERTEX\n 10\n%f\n 20\n%f\n 30\n%f\n", p->line[j].point[i].x, p->line[j].point[i].y, 0.0);
+        } else {
+          im_iprintf (&imgStr, "%s %.0f,%.0f", first ? "": ",", p->line[j].point[i].x, p->line[j].point[i].y);
+        }
+        first = 0;
 
-    gdImageSetBrush(img, brush);
-    fc = 1; bc = 0;
-    break;
-  }  
-
-  if(symbol->patternlength > 0) {
-    int k=0, sc;
-   
-    sc = fc; // start with foreground color
-    for(i=0; i<symbol->patternlength; i++) {      
-      for(j=0; j<symbol->pattern[i]; j++) {
-	styleDashed[k] = sc;
-	k++;
-      } 
-      if(sc==fc) sc = bc; else sc = fc;
+        /* point2 = &( p->line[j].point[i] ); */
+        /* if(point1->y == point2->y) {} */
+      }
+      im_iprintf (&imgStr, dxf ? (dxf == 2 ? "": "  0\nSEQEND\n") : "\" />\n");
     }
-    gdImageSetStyle(img, styleDashed, k);
 
-    if(!brush && !symbol->img)
-      imagePolyline(img, p, imStyled, style->offsetx, style->offsety);
-    else 
-      imagePolyline(img, p, imStyledBrushed, style->offsetx, style->offsety);
-  } else {
-    if(!brush && !symbol->img)
-      imagePolyline(img, p, fc, style->offsetx, style->offsety);
-    else
-      imagePolyline(img, p, imBrushed, style->offsetx, style->offsety);
+    /* DEBUG_IF printf ("%d, ",strlen(img->img.imagemap) ); */
+    return;
   }
-*/
+
+  DEBUG_IF printf("-%d-",symbol->type);
+
   return;
 }
 
@@ -1365,610 +553,94 @@ DEBUG_IF printf("msDrawLineSymbolIM<BR>\n");
 void msDrawShadeSymbolIM(symbolSetObj *symbolset, imageObj* img, shapeObj *p, styleObj *style, double scalefactor)
 {
   symbolObj *symbol;
-/*  gdPoint oldpnt, newpnt;
-  gdPoint sPoints[MS_MAXVECTORPOINTS];
-  gdImagePtr tile;
-  int x, y;
-  int tile_bc=-1, tile_fc=-1; // colors (background and foreground) //
-  int fc, bc, oc;
-  double d;
-  int bbox[8];
-  rectObj rect;
-  char *font=NULL;
-  */
   int i,j,l;
-char first = 1;
-double size;
+  char first = 1;
+  double size;
 
-DEBUG_IF printf("msDrawShadeSymbolIM\n<BR>");
+  DEBUG_IF printf("msDrawShadeSymbolIM\n<BR>");
   if(!p) return;
   if(p->numlines <= 0) return;
-/* if(style->backgroundcolor.pen == MS_PEN_UNSET) msImageSetPenIM(img, &(style->backgroundcolor)); */
-/* if(style->color.pen == MS_PEN_UNSET) msImageSetPenIM(img, &(style->color)); */
-/* if(style->outlinecolor.pen == MS_PEN_UNSET) msImageSetPenIM(img, &(style->outlinecolor)); */
 
   symbol = symbolset->symbol[style->symbol];
-/* bc = style->backgroundcolor.pen; */
-/* fc = style->color.pen; */
-/* oc = style->outlinecolor.pen; */
   if(style->size == -1) {
-      size = msSymbolGetDefaultSize( symbol );
-      size = MS_NINT(size*scalefactor);
-  }
-  else
-      size = MS_NINT(style->size*scalefactor);
+    size = msSymbolGetDefaultSize( symbol );
+    size = MS_NINT(size*scalefactor);
+  } else
+    size = MS_NINT(style->size*scalefactor);
   size = MS_MAX(size, style->minsize*img->resolutionfactor);
   size = MS_MIN(size, style->maxsize*img->resolutionfactor);
 
-/* DEBUG_IF printf ("a"); */
-/* if(fc==-1 && oc!=-1) { // use msDrawLineSymbolIM() instead (POLYLINE) */
-/* msDrawLineSymbolIM(symbolset, img, p, style, scalefactor); */
-/* return; */
-/* } */
-/* DEBUG_IF printf ("b"); */
-
-/* if(style->symbol > symbolset->numsymbols || style->symbol < 0) return; // no such symbol, 0 is OK */
   if (suppressEmpty && p->numvalues==0) return;/* suppress area with empty title */
-/* DEBUG_IF printf ("1"); */
-/* if(fc < 0) return; // nothing to do */
-/* DEBUG_IF printf ("2"); */
-/* if(size < 1) return; // size too small */
-/* DEBUG_IF printf ("3"); */
-      
-/* DEBUG_IF printf("BEF%s", img->img.imagemap); */
-	  if(style->symbol == 0) { /* simply draw a single pixel of the specified color //     */
-		  for(l=0,j=0; j<p->numlines; j++) {
-		    if (dxf == 2){
-		      im_iprintf (&imgStr, "POLY\n%d\n", matchdxfcolor(style->color));
-		    } else if (dxf){
-		      im_iprintf (&imgStr, "  0\nPOLYLINE\n 73\n     1\n 62\n%6d\n  8\n%s\n", matchdxfcolor(style->color), lname);
-		    } else {
-		      char *title=(p->numvalues) ? p->values[0] : "";
-                      first = 1;
-		      im_iprintf (&imgStr, "<area ");
-		      if (strcmp(polyHrefFmt,"%.s")!=0) {
-			im_iprintf (&imgStr, "href=\"");
-			im_iprintf (&imgStr, polyHrefFmt, title);
-			im_iprintf (&imgStr, "\" ");
-		      }
-		      if (strcmp(polyMOverFmt,"%.s")!=0) {
-			im_iprintf (&imgStr, "onMouseOver=\"");
-			im_iprintf (&imgStr, polyMOverFmt, title);
-			im_iprintf (&imgStr, "\" ");
-		      }
-		      if (strcmp(polyMOutFmt,"%.s")!=0) {
-			im_iprintf (&imgStr, "onMouseOut=\"");
-			im_iprintf (&imgStr, polyMOutFmt, title);
-			im_iprintf (&imgStr, "\" ");
-		      }
-		      im_iprintf (&imgStr, "title=\"%s\" shape=\"poly\" coords=\"", title);
-		    }
-
-		/* point1 = &( p->line[j].point[p->line[j].numpoints-1] ); */
-		      for(i=0; i < p->line[j].numpoints; i++,l++) {
-				if (dxf == 2){
-					im_iprintf (&imgStr, "%.0f %.0f\n", p->line[j].point[i].x, p->line[j].point[i].y);
-				} else if (dxf){
-					im_iprintf (&imgStr, "  0\nVERTEX\n 10\n%f\n 20\n%f\n 30\n%f\n", p->line[j].point[i].x, p->line[j].point[i].y, 0.0);
-				} else {
-					im_iprintf (&imgStr, "%s %.0f,%.0f", first ? "": ",", p->line[j].point[i].x, p->line[j].point[i].y);
-				}
-				first = 0;
-			      
-		/* point2 = &( p->line[j].point[i] ); */
-		/* if(point1->y == point2->y) {} */
-		      }
-		      im_iprintf (&imgStr, dxf ? (dxf == 2 ? "": "  0\nSEQEND\n") : "\" />\n");
-		  }
-  
-/* DEBUG_IF printf("AFT%s", img->img.imagemap); */
-/* STOOPID. GD draws polygons pixel by pixel ?! */
-	
-/* msImageFilledPolygon(img, p, fc); */
-/* if(oc>-1) imagePolyline(img, p, oc, style->offsetx, style->offsety); */
-  	     return;
-	  }
-/* DEBUG_IF printf ("d"); */
-  DEBUG_IF printf("-%d-",symbol->type);
-/*  
-  switch(symbol->type) {
-  case(MS_SYMBOL_TRUETYPE):    
-    
-#if defined (USE_GD_FT) || defined (USE_GD_TTF)
-    font = msLookupHashTable(&(symbolset->fontset->fonts), symbol->font);
-    if(!font) return;
-
-    if(msGetCharacterSize(symbol->character, size, font, &rect) != MS_SUCCESS) return;
-    x = rect.maxx - rect.minx;
-    y = rect.maxy - rect.miny;
-
-    tile = gdImageCreate(x, y);
-    if(bc >= 0)
-      tile_bc = gdImageColorAllocate(tile, style->backgroundcolor.red, style->backgroundcolor.green, style->backgroundcolor.blue);
-    else {
-      tile_bc = gdImageColorAllocate(tile, gdImageRed(img, 0), gdImageGreen(img, 0), gdImageBlue(img, 0));
-      gdImageColorTransparent(tile,0);
-    }    
-    tile_fc = gdImageColorAllocate(tile, style->color.red, style->color.green, style->color.blue);
-    
-    x = -rect.minx;
-    y = -rect.miny;
-
-#ifdef USE_GD_TTF
-    gdImageStringTTF(tile, bbox, ((symbol->antialias)?(tile_fc):-(tile_fc)), font, size, 0, x, y, symbol->character);
-#else
-    gdImageStringFT(tile, bbox, ((symbol->antialias)?(tile_fc):-(tile_fc)), font, size, 0, x, y, symbol->character);
-#endif    
-
-    gdImageSetTile(img, tile);
-    msImageFilledPolygon(img,p,gdTiled);
-    if(oc>-1) imagePolyline(img, p, oc, style->offsetx, style->offsety);
-    gdImageDestroy(tile);
-#endif
-
-    break;
-  case(MS_SYMBOL_PIXMAP):
-    
-    gdImageSetTile(img, symbol->img);
-    msImageFilledPolygon(img, p, imTiled);
-    if(oc>-1) imagePolyline(img, p, oc, style->offsetx, style->offsety);
-
-    break;
-  case(MS_SYMBOL_ELLIPSE):    
-    d = size/symbol->sizey; // size ~ height in pixels
-    x = MS_NINT(symbol->sizex*d)+1;
-    y = MS_NINT(symbol->sizey*d)+1;
-
-    if((x <= 1) && (y <= 1)) { // No sense using a tile, just fill solid //
-      msImageFilledPolygon(img, p, fc);
-      if(oc>-1) imagePolyline(img, p, oc, style->offsetx, style->offsety);
-      return;
-    }
+  if(style->symbol == 0) { /* simply draw a single pixel of the specified color //     */
+    for(l=0,j=0; j<p->numlines; j++) {
+      if (dxf == 2) {
+        im_iprintf (&imgStr, "POLY\n%d\n", matchdxfcolor(style->color));
+      } else if (dxf) {
+        im_iprintf (&imgStr, "  0\nPOLYLINE\n 73\n     1\n 62\n%6d\n  8\n%s\n", matchdxfcolor(style->color), lname);
+      } else {
+        char *title=(p->numvalues) ? p->values[0] : "";
+        first = 1;
+        im_iprintf (&imgStr, "<area ");
+        if (strcmp(polyHrefFmt,"%.s")!=0) {
+          im_iprintf (&imgStr, "href=\"");
+          im_iprintf (&imgStr, polyHrefFmt, title);
+          im_iprintf (&imgStr, "\" ");
+        }
+        if (strcmp(polyMOverFmt,"%.s")!=0) {
+          im_iprintf (&imgStr, "onMouseOver=\"");
+          im_iprintf (&imgStr, polyMOverFmt, title);
+          im_iprintf (&imgStr, "\" ");
+        }
+        if (strcmp(polyMOutFmt,"%.s")!=0) {
+          im_iprintf (&imgStr, "onMouseOut=\"");
+          im_iprintf (&imgStr, polyMOutFmt, title);
+          im_iprintf (&imgStr, "\" ");
+        }
+        im_iprintf (&imgStr, "title=\"%s\" shape=\"poly\" coords=\"", title);
+      }
 
-    tile = gdImageCreate(x, y);
-    if(bc >= 0)
-      tile_bc = gdImageColorAllocate(tile, style->backgroundcolor.red, style->backgroundcolor.green, style->backgroundcolor.blue);
-    else {
-      tile_bc = gdImageColorAllocate(tile, gdImageRed(img, 0), gdImageGreen(img, 0), gdImageBlue(img, 0));
-      gdImageColorTransparent(tile,0);
-    }    
-    tile_fc = gdImageColorAllocate(tile, style->color.red, style->color.green, style->color.blue);
-    
-    x = MS_NINT(tile->sx/2);
-    y = MS_NINT(tile->sy/2);
-
-    //
-   //draw in the tile image
-    //
-    gdImageArc(tile, x, y, MS_NINT(d*symbol->points[0].x), MS_NINT(d*symbol->points[0].y), 0, 360, tile_fc);
-    if(symbol->filled)
-      gdImageFillToBorder(tile, x, y, tile_fc, tile_fc);
-
-    //
-   //Fill the polygon in the main image
-    //
-    gdImageSetTile(img, tile);
-    msImageFilledPolygon(img,p,gdTiled);
-    if(oc>-1) imagePolyline(img, p, oc, style->offsetx, style->offsety);
-    gdImageDestroy(tile);
-
-    break;
-  case(MS_SYMBOL_VECTOR):
-    d = size/symbol->sizey; // size ~ height in pixels
-    x = MS_NINT(symbol->sizex*d)+1;    
-    y = MS_NINT(symbol->sizey*d)+1;
-
-    if((x <= 1) && (y <= 1)) { // No sense using a tile, just fill solid //
-      msImageFilledPolygon(img, p, fc);
-      if(oc>-1) imagePolyline(img, p, oc, style->offsetx, style->offsety);
-      return;
-    }
+      /* point1 = &( p->line[j].point[p->line[j].numpoints-1] ); */
+      for(i=0; i < p->line[j].numpoints; i++,l++) {
+        if (dxf == 2) {
+          im_iprintf (&imgStr, "%.0f %.0f\n", p->line[j].point[i].x, p->line[j].point[i].y);
+        } else if (dxf) {
+          im_iprintf (&imgStr, "  0\nVERTEX\n 10\n%f\n 20\n%f\n 30\n%f\n", p->line[j].point[i].x, p->line[j].point[i].y, 0.0);
+        } else {
+          im_iprintf (&imgStr, "%s %.0f,%.0f", first ? "": ",", p->line[j].point[i].x, p->line[j].point[i].y);
+        }
+        first = 0;
 
-    //
-   //create tile image
-    //
-    tile = gdImageCreate(x, y);
-    if(bc >= 0)
-      tile_bc = gdImageColorAllocate(tile, gdImageRed(img, bc), gdImageGreen(img, bc), gdImageBlue(img, bc));
-    else {
-      tile_bc = gdImageColorAllocate(tile, gdImageRed(img, 0), gdImageGreen(img, 0), gdImageBlue(img, 0));
-      gdImageColorTransparent(tile,0);
-    }
-    tile_fc = gdImageColorAllocate(tile, gdImageRed(img, fc), gdImageGreen(img, fc), gdImageBlue(img, fc));
-   
-    //
-   //draw in the tile image
-    //
-    if(symbol->filled) {
-
-      for(i=0;i < symbol->numpoints;i++) {
-	sPoints[i].x = MS_NINT(d*symbol->points[i].x);
-	sPoints[i].y = MS_NINT(d*symbol->points[i].y);
+        /* point2 = &( p->line[j].point[i] ); */
+        /* if(point1->y == point2->y) {} */
       }
-      gdImageFilledPolygon(tile, sPoints, symbol->numpoints, tile_fc);      
-
-    } else  { // shade is a vector drawing //
-      
-      oldpnt.x = MS_NINT(d*symbol->points[0].x); // convert first point in shade smbol //
-      oldpnt.y = MS_NINT(d*symbol->points[0].y);
-
-      // step through the shade sy //
-      for(i=1;i < symbol->numpoints;i++) {
-	if((symbol->points[i].x < 0) && (symbol->points[i].y < 0)) {
-	  oldpnt.x = MS_NINT(d*symbol->points[i].x);
-	  oldpnt.y = MS_NINT(d*symbol->points[i].y);
-	} else {
-	  if((symbol->points[i-1].x < 0) && (symbol->points[i-1].y < 0)) { // Last point was PENUP, now a new beginning //
-	    oldpnt.x = MS_NINT(d*symbol->points[i].x);
-	    oldpnt.y = MS_NINT(d*symbol->points[i].y);
-	  } else {
-	    newpnt.x = MS_NINT(d*symbol->points[i].x);
-	    newpnt.y = MS_NINT(d*symbol->points[i].y);
-	    gdImageLine(tile, oldpnt.x, oldpnt.y, newpnt.x, newpnt.y, tile_fc);
-	    oldpnt = newpnt;
-	  }
-	}
-      } // end for loop //
+      im_iprintf (&imgStr, dxf ? (dxf == 2 ? "": "  0\nSEQEND\n") : "\" />\n");
     }
 
-    //
-   //Fill the polygon in the main image
-    //
-    gdImageSetTile(img, tile);
-    msImageFilledPolygon(img, p, imTiled);
-    if(oc>-1)
-      imagePolyline(img, p, oc, style->offsetx, style->offsety);
-
-    break;
-  default:
-    break;
+    return;
   }
-*/
+  /* DEBUG_IF printf ("d"); */
+  DEBUG_IF printf("-%d-",symbol->type);
   return;
 }
 
-#ifdef notdef /* not currently used */
-static void billboardIM(imageObj* img, shapeObj *shape, labelObj *label)
-{
-/* int i; */
-/* shapeObj temp; */
-DEBUG_IF printf("billboardIM<BR>\n");
-/*
-  msInitShape(&temp);
-  msAddLine(&temp, &shape->line[0]);
-
-  if(label->backgroundcolor.pen == MS_PEN_UNSET) msImageSetPenIM(img, &(label->backgroundcolor));
-  if(label->backgroundshadowcolor.pen == MS_PEN_UNSET) msImageSetPenIM(img, &(label->backgroundshadowcolor));
-
-  if(label->backgroundshadowcolor.pen >= 0) {
-    for(i=0; i<temp.line[0].numpoints; i++) {
-      temp.line[0].point[i].x += label->backgroundshadowsizex;
-      temp.line[0].point[i].y += label->backgroundshadowsizey;
-    }
-    msImageFilledPolygon(img, &temp, label->backgroundshadowcolor.pen);
-    for(i=0; i<temp.line[0].numpoints; i++) {
-      temp.line[0].point[i].x -= label->backgroundshadowsizex;
-      temp.line[0].point[i].y -= label->backgroundshadowsizey;
-    }
-  }
-
-  msImageFilledPolygon(img, &temp, label->backgroundcolor.pen);
-
-  msFreeShape(&temp);
-*/
-  
-}
-#endif /* def notdef */
-
 /*
  * Simply draws a label based on the label point and the supplied label object.
  */
 int msDrawTextIM(imageObj* img, pointObj labelPnt, char *string, labelObj *label, fontSetObj *fontset, double scalefactor)
 {
-  int x, y;
-		
-
   DEBUG_IF printf("msDrawText<BR>\n");
   if(!string) return(0); /* not errors, just don't want to do anything */
   if(strlen(string) == 0) return(0);
   if(!dxf) return (0);
-  x = MS_NINT(labelPnt.x);
-  y = MS_NINT(labelPnt.y);
-
-	if (dxf == 2) {
-		im_iprintf (&imgStr, "TEXT\n%d\n%s\n%.0f\n%.0f\n%.0f\n" , matchdxfcolor(label->color), string, labelPnt.x, labelPnt.y, -label->angle);
-	} else if (dxf) {
-		im_iprintf (&imgStr, "  0\nTEXT\n  1\n%s\n 10\n%f\n 20\n%f\n 30\n0.0\n 40\n%f\n 50\n%f\n 62\n%6d\n  8\n%s\n 73\n   2\n 72\n   1\n" , string, labelPnt.x, labelPnt.y, label->size * scalefactor *100, -label->angle, matchdxfcolor(label->color), lname);
-	}
-/*
-  if(label->color.pen == MS_PEN_UNSET) msImageSetPenIM(img, &(label->color));
-  if(label->outlinecolor.pen == MS_PEN_UNSET) msImageSetPenIM(img, &(label->outlinecolor));
-  if(label->shadowcolor.pen == MS_PEN_UNSET) msImageSetPenIM(img, &(label->shadowcolor));
-
-  if(label->type == MS_TRUETYPE) {
-    char *error=NULL, *font=NULL;
-    int bbox[8];
-    double angle_radians = MS_DEG_TO_RAD*label->angle;
-    double size;
-
-    size = label->size*scalefactor;
-
-#if defined (USE_GD_FT) || defined (USE_GD_TTF)
-    if(!fontset) {
-      msSetError(MS_TTFERR, "No fontset defined.", "msDrawTextIM()");
-      return(-1);
-    }
-
-    if(!label->font) {
-      msSetError(MS_TTFERR, "No Trueype font defined.", "msDrawTextIM()");
-      return(-1);
-    }
-
-    font = msLookupHashTable(&(fontset->fonts), label->font);
-    if(!font) {
-       msSetError(MS_TTFERR, "Requested font (%s) not found.", "msDrawTextIM()",
-                  label->font);
-      return(-1);
-    }
-
-    if(label->outlinecolor.pen >= 0) { // handle the outline color //
-#ifdef USE_GD_TTF
-      error = gdImageStringTTF(img, bbox, ((label->antialias)?(label->outlinecolor.pen):-(label->outlinecolor.pen)), font, size, angle_radians, x-1, y-1, string);
-#else
-      error = gdImageStringFT(img, bbox, ((label->antialias)?(label->outlinecolor.pen):-(label->outlinecolor.pen)), font, size, angle_radians, x-1, y-1, string);
-#endif
-      if(error) {
-	msSetError(MS_TTFERR, error, "msDrawTextIM()");
-	return(-1);
-      }
-
-#ifdef USE_GD_TTF
-      gdImageStringTTF(img, bbox, ((label->antialias)?(label->outlinecolor.pen):-(label->outlinecolor.pen)), font, size, angle_radians, x-1, y+1, string);
-      gdImageStringTTF(img, bbox, ((label->antialias)?(label->outlinecolor.pen):-(label->outlinecolor.pen)), font, size, angle_radians, x+1, y+1, string);
-      gdImageStringTTF(img, bbox, ((label->antialias)?(label->outlinecolor.pen):-(label->outlinecolor.pen)), font, size, angle_radians, x+1, y-1, string);
-#else
-      gdImageStringFT(img, bbox, ((label->antialias)?(label->outlinecolor.pen):-(label->outlinecolor.pen)), font, size, angle_radians, x-1, y+1, string);
-      gdImageStringFT(img, bbox, ((label->antialias)?(label->outlinecolor.pen):-(label->outlinecolor.pen)), font, size, angle_radians, x+1, y+1, string);
-      gdImageStringFT(img, bbox, ((label->antialias)?(label->outlinecolor.pen):-(label->outlinecolor.pen)), font, size, angle_radians, x+1, y-1, string);
-#endif
-
-    }
-
-    if(label->shadowcolor.pen >= 0) { // handle the shadow color //
-#ifdef USE_GD_TTF
-      error = gdImageStringTTF(img, bbox, ((label->antialias)?(label->shadowcolor.pen):-(label->shadowcolor.pen)), font, size, angle_radians, x+label->shadowsizex, y+label->shadowsizey, string);
-#else
-      error = gdImageStringFT(img, bbox, ((label->antialias)?(label->shadowcolor.pen):-(label->shadowcolor.pen)), font, size, angle_radians, x+label->shadowsizex, y+label->shadowsizey, string);
-#endif
-      if(error) {
-	msSetError(MS_TTFERR, error, "msDrawTextIM()");
-	return(-1);
-      }
-    }
-
-#ifdef USE_GD_TTF
-    gdImageStringTTF(img, bbox, ((label->antialias)?(label->color.pen):-(label->color.pen)), font, size, angle_radians, x, y, string);
-#else
-    gdImageStringFT(img, bbox, ((label->antialias)?(label->color.pen):-(label->color.pen)), font, size, angle_radians, x, y, string);
-#endif
-
-#else
-    msSetError(MS_TTFERR, "TrueType font support is not available.", "msDrawTextIM()");
-    return(-1);
-#endif
-
-  } else { // MS_BITMAP //
-    char **token=NULL;
-    int t, num_tokens;
-    imFontPtr fontPtr;
-
-    if((fontPtr = msGetBitmapFont(label->size)) == NULL)
-      return(-1);
-
-    if(label->wrap != '\0') {
-      if((token = msStringSplit(string, label->wrap, &(num_tokens))) == NULL)
-	return(-1);
-
-      y -= fontPtr->h*num_tokens;
-      for(t=0; t<num_tokens; t++) {
-	if(label->outlinecolor.pen >= 0) {
-	  gdImageString(img, fontPtr, x-1, y-1, token[t], label->outlinecolor.pen);
-	  gdImageString(img, fontPtr, x-1, y+1, token[t], label->outlinecolor.pen);
-	  gdImageString(img, fontPtr, x+1, y+1, token[t], label->outlinecolor.pen);
-	  gdImageString(img, fontPtr, x+1, y-1, token[t], label->outlinecolor.pen);
-	}
-
-	if(label->shadowcolor.pen >= 0)
-	  gdImageString(img, fontPtr, x+label->shadowsizex, y+label->shadowsizey, token[t], label->shadowcolor.pen);
-
-	gdImageString(img, fontPtr, x, y, token[t], label->color.pen);
 
-	y += fontPtr->h; // shift down //
-      }
-
-      msFreeCharArray(token, num_tokens);
-    } else {
-      y -= fontPtr->h;
-
-      if(label->outlinecolor.pen >= 0) {
-	gdImageString(img, fontPtr, x-1, y-1, string, label->outlinecolor.pen);
-	gdImageString(img, fontPtr, x-1, y+1, string, label->outlinecolor.pen);
-	gdImageString(img, fontPtr, x+1, y+1, string, label->outlinecolor.pen);
-	gdImageString(img, fontPtr, x+1, y-1, string, label->outlinecolor.pen);
-      }
-
-      if(label->shadowcolor.pen >= 0)
-	gdImageString(img, fontPtr, x+label->shadowsizex, y+label->shadowsizey, string, label->shadowcolor.pen);
-
-      gdImageString(img, fontPtr, x, y, string, label->color.pen);
-    }
+  if (dxf == 2) {
+    im_iprintf (&imgStr, "TEXT\n%d\n%s\n%.0f\n%.0f\n%.0f\n" , matchdxfcolor(label->color), string, labelPnt.x, labelPnt.y, -label->angle);
+  } else if (dxf) {
+    im_iprintf (&imgStr, "  0\nTEXT\n  1\n%s\n 10\n%f\n 20\n%f\n 30\n0.0\n 40\n%f\n 50\n%f\n 62\n%6d\n  8\n%s\n 73\n   2\n 72\n   1\n" , string, labelPnt.x, labelPnt.y, label->size * scalefactor *100, -label->angle, matchdxfcolor(label->color), lname);
   }
-*/
   return(0);
 }
 
-int msDrawLabelCacheIM(imageObj* img, mapObj *map)
-{
-  pointObj p;
-  int i, j, l, priority;
-  rectObj r;
-  
-  labelCacheMemberObj *cachePtr=NULL;
-  layerObj *layerPtr=NULL;
-  labelObj *labelPtr=NULL;
-
-  int marker_width, marker_height;
-  int marker_offset_x, marker_offset_y, label_offset_x, label_offset_y;
-  rectObj marker_rect;
-  int label_mindistance, label_buffer;
-
-  label_mindistance=-1;
-  label_buffer=0;
-
-  DEBUG_IF printf("msDrawLabelCacheIM\n<BR>");
-  for(priority=MS_MAX_LABEL_PRIORITY-1; priority>=0; priority--) {
-   labelCacheSlotObj *cacheslot;
-   cacheslot = &(map->labelcache.slots[priority]);
-
-   for(l=cacheslot->numlabels-1; l>=0; l--) {
-	double size = cachePtr->label.size*layerPtr->scalefactor;
-    cachePtr = &(cacheslot->labels[l]); /* point to right spot in the label cache */
-
-    layerPtr = (GET_LAYER(map, cachePtr->layerindex)); /* set a couple of other pointers, avoids nasty references */
-    labelPtr = &(cachePtr->label);
-
-    if(!cachePtr->text || strlen(cachePtr->text) == 0)
-      continue; /* not an error, just don't want to do anything */
-
-    if(labelPtr->type == MS_TRUETYPE) {
-    	size = MS_MAX(size, labelPtr->minsize*img->resolutionfactor);
-    	size = MS_MIN(size, labelPtr->maxsize*img->resolutionfactor);  
-    }
-
-    if(msGetLabelSize(map,labelPtr,cachePtr->text, size,&r, NULL) != MS_SUCCESS) {
-      return MS_FAILURE;
-    }
-
-    label_offset_x = labelPtr->offsetx*layerPtr->scalefactor;
-    label_offset_y = labelPtr->offsety*layerPtr->scalefactor;
-    label_buffer = MS_NINT(labelPtr->buffer*img->resolutionfactor);
-    label_mindistance = MS_NINT(labelPtr->mindistance*img->resolutionfactor);
-
-    if(labelPtr->autominfeaturesize && (cachePtr->featuresize != -1) && ((r.maxx-r.minx) > cachePtr->featuresize))
-      continue; /* label too large relative to the feature */
-
-    marker_offset_x = marker_offset_y = 0; /* assume no marker */
-    if((layerPtr->type == MS_LAYER_ANNOTATION && cachePtr->numstyles > 0) || layerPtr->type == MS_LAYER_POINT) { /* there *is* a marker       */
-
-      /* TO DO: at the moment only checks the bottom style, perhaps should check all of them */
-      if (msGetMarkerSize(&map->symbolset, &(cachePtr->styles[0]), &marker_width, &marker_height, layerPtr->scalefactor) != MS_SUCCESS)
-	return(MS_FAILURE);
-
-      marker_width = (int) (marker_width * layerPtr->scalefactor);
-      marker_height = (int) (marker_height * layerPtr->scalefactor);
-
-      marker_offset_x = MS_NINT(marker_width/2.0);
-      marker_offset_y = MS_NINT(marker_height/2.0);      
-
-      marker_rect.minx = MS_NINT(cachePtr->point.x - .5 * marker_width);
-      marker_rect.miny = MS_NINT(cachePtr->point.y - .5 * marker_height);
-      marker_rect.maxx = marker_rect.minx + (marker_width-1);
-      marker_rect.maxy = marker_rect.miny + (marker_height-1);
-
-      for(i=0; i<cachePtr->numstyles; i++) {
-        if(cachePtr->styles[i].size == -1)
-          cachePtr->styles[i].size = (int) msSymbolGetDefaultSize( 
-              map->symbolset.symbol[cachePtr->styles[i].symbol] );
-	cachePtr->styles[i].size = (int)
-            ( cachePtr->styles[i].size * layerPtr->scalefactor);
-      }
-    }
-
-    if(labelPtr->position == MS_AUTO) {
-
-      if(layerPtr->type == MS_LAYER_LINE) {
-	int position = MS_UC;
-
-	for(j=0; j<2; j++) { /* Two angles or two positions, depending on angle. Steep angles will use the angle approach, otherwise we'll rotate between UC and LC. */
-
-	  msFreeShape(cachePtr->poly);
-	  cachePtr->status = MS_TRUE; /* assume label *can* be drawn */
-
-	  p = get_metrics(&(cachePtr->point), position, r, (marker_offset_x + label_offset_x), (marker_offset_y + label_offset_y), labelPtr->angle, label_buffer, cachePtr->poly);
-
-	  if(layerPtr->type == MS_LAYER_ANNOTATION && cachePtr->numstyles > 0)
-	    msRectToPolygon(marker_rect, cachePtr->poly); /* save marker bounding polygon */
-
-          /* Compare against rendered labels and markers (sets cachePtr->status) */
-          msTestLabelCacheCollisions(&(map->labelcache), labelPtr, 
-                                     -1, -1, label_buffer, cachePtr, priority, l, label_mindistance, (r.maxx-r.minx));
-
-	  if(cachePtr->status) /* found a suitable place for this label */
-	    break;
-
-	} /* next angle */
-
-      } else {
-	for(j=0; j<=7; j++) { /* loop through the outer label positions */
-
-	  msFreeShape(cachePtr->poly);
-	  cachePtr->status = MS_TRUE; /* assume label *can* be drawn */
-
-	  p = get_metrics(&(cachePtr->point), j, r, (marker_offset_x + label_offset_x), (marker_offset_y + label_offset_y), labelPtr->angle, label_buffer, cachePtr->poly);
-
-	  if(layerPtr->type == MS_LAYER_ANNOTATION && cachePtr->numstyles > 0)
-	    msRectToPolygon(marker_rect, cachePtr->poly); /* save marker bounding polygon */
-
-          /* Compare against rendered labels and markers (sets cachePtr->status) */
-          msTestLabelCacheCollisions(&(map->labelcache), labelPtr, 
-                                     -1, -1, label_buffer, cachePtr, priority, l,label_mindistance, (r.maxx-r.minx));
-
-	  if(cachePtr->status) /* found a suitable place for this label */
-	    break;
-	} /* next position */
-      }
-
-      if(labelPtr->force) cachePtr->status = MS_TRUE; /* draw in spite of collisions based on last position, need a *best* position */
-
-    } else {
-
-      cachePtr->status = MS_TRUE; /* assume label *can* be drawn */
-
-      if(labelPtr->position == MS_CC) /* don't need the marker_offset */
-        p = get_metrics(&(cachePtr->point), labelPtr->position, r, label_offset_x, label_offset_y, labelPtr->angle, label_buffer, cachePtr->poly);
-      else
-        p = get_metrics(&(cachePtr->point), labelPtr->position, r, (marker_offset_x + label_offset_x), (marker_offset_y + label_offset_y), labelPtr->angle, label_buffer, cachePtr->poly);
-
-      if(layerPtr->type == MS_LAYER_ANNOTATION && cachePtr->numstyles > 0)
-	msRectToPolygon(marker_rect, cachePtr->poly); /* save marker bounding polygon, part of overlap tests */
-
-      if(!labelPtr->force) { /* no need to check anything else */
-
-        /* Compare against rendered labels and markers (sets cachePtr->status) */
-        msTestLabelCacheCollisions(&(map->labelcache), labelPtr, 
-                                   -1, -1, label_buffer, cachePtr, priority, l,label_mindistance, (r.maxx-r.minx));
-      }
-    } /* end position if-then-else */
-
-    /* imagePolyline(img, cachePtr->poly, 1, 0, 0); */
-
-    if(!cachePtr->status)
-      continue; /* next label */
-
-/* if(layerPtr->type == MS_LAYER_ANNOTATION && cachePtr->numstyles > 0) { // need to draw a marker */
-/* for(i=0; i<cachePtr->numstyles; i++) */
-/* msDrawMarkerSymbolIM(&map->symbolset, img, &(cachePtr->point), &(cachePtr->styles[i]), layerPtr->scalefactor); */
-/* } */
-
-/* if(MS_VALID_COLOR(labelPtr->backgroundcolor)) billboardIM(img, cachePtr->poly, labelPtr); */
-    msDrawTextIM(img, p, cachePtr->text, labelPtr, &(map->fontset), layerPtr->scalefactor); /* actually draw the label, we scaled it in msAddLabel */
-
-   } /* next label in cache */
-  } /* next priority */
-
-  return(MS_SUCCESS);
-}
-
 /*
  * Save an image to a file named filename, if filename is NULL it goes to stdout
  */
@@ -1976,13 +648,13 @@ int msDrawLabelCacheIM(imageObj* img, mapObj *map)
 int msSaveImageIM(imageObj* img, char *filename, outputFormatObj *format )
 
 {
-    FILE *stream;
-    char workbuffer[5000];
-    int nSize=0, size=0, iIndice=0; 
+  FILE *stream;
+  char workbuffer[5000];
+  int nSize=0, size=0, iIndice=0;
 
-DEBUG_IF printf("msSaveImageIM\n<BR>");
+  DEBUG_IF printf("msSaveImageIM\n<BR>");
 
-if(filename != NULL && strlen(filename) > 0) {
+  if(filename != NULL && strlen(filename) > 0) {
     stream = fopen(filename, "wb");
     if(!stream) {
       msSetError(MS_IOERR, "(%s)", "msSaveImage()", filename);
@@ -2002,66 +674,46 @@ if(filename != NULL && strlen(filename) > 0) {
     stream = stdout;
   }
 
-/*  if( strcasecmp("ON",msGetOutputFormatOption( format, "INTERLACE", "ON" ))
-      == 0 )
-      gdImageInterlace(img, 1);
-
-  if(format->transparent)
-    gdImageColorTransparent(img, 0);
-*/
-  if( strcasecmp(format->driver,"imagemap") == 0 )
-  {
-DEBUG_IF printf("ALLOCD %d<BR>\n", img->size);
-/* DEBUG_IF printf("F %s<BR>\n", img->img.imagemap); */
-DEBUG_IF printf("FLEN %d<BR>\n", (int)strlen(img->img.imagemap));
-	  if (dxf == 2){
-	    msIO_fprintf(stream, "%s", layerlist); 
-	  } else if (dxf){
-	    msIO_fprintf(stream, "  0\nSECTION\n  2\nHEADER\n  9\n$ACADVER\n  1\nAC1009\n0\nENDSEC\n  0\nSECTION\n  2\nTABLES\n  0\nTABLE\n%s0\nENDTAB\n0\nENDSEC\n  0\nSECTION\n  2\nBLOCKS\n0\nENDSEC\n  0\nSECTION\n  2\nENTITIES\n", layerlist); 
-	  } else {
-	    msIO_fprintf(stream, "<map name=\"%s\" width=\"%d\" height=\"%d\">\n", mapName, img->width, img->height);
-    	  }
-          nSize = sizeof(workbuffer);
-
-          size = strlen(img->img.imagemap);
-          if (size > nSize)
-          {
-              iIndice = 0;
-              while ((iIndice + nSize) <= size)
-              {
-                  snprintf(workbuffer, sizeof(workbuffer), "%s", img->img.imagemap+iIndice );
-                  workbuffer[nSize-1] = '\0';
-                  msIO_fwrite(workbuffer, strlen(workbuffer), 1, stream);
-                  iIndice +=nSize-1;
-              }
-              if (iIndice < size)
-              {
-                  sprintf(workbuffer, "%s", img->img.imagemap+iIndice );
-                  msIO_fprintf(stream, workbuffer);
-              }
-          }
-          else
-              msIO_fwrite(img->img.imagemap, size, 1, stream);
-	  if( strcasecmp("OFF",msGetOutputFormatOption( format, "SKIPENDTAG", "OFF" )) == 0){
-		  if (dxf == 2)
-			  msIO_fprintf(stream, "END");
-		  else if (dxf)
-			  msIO_fprintf(stream, "0\nENDSEC\n0\nEOF\n");
-		  else 
-			  msIO_fprintf(stream, "</map>");
-/*#ifdef USE_GD_GIF
-    gdImageGif(img, stream);
-#else
-    msSetError(MS_MISCERR, "GIF output is not available.", "msSaveImage()");
+  if( strcasecmp(format->driver,"imagemap") == 0 ) {
+    DEBUG_IF printf("ALLOCD %d<BR>\n", img->size);
+    /* DEBUG_IF printf("F %s<BR>\n", img->img.imagemap); */
+    DEBUG_IF printf("FLEN %d<BR>\n", (int)strlen(img->img.imagemap));
+    if (dxf == 2) {
+      msIO_fprintf(stream, "%s", layerlist);
+    } else if (dxf) {
+      msIO_fprintf(stream, "  0\nSECTION\n  2\nHEADER\n  9\n$ACADVER\n  1\nAC1009\n0\nENDSEC\n  0\nSECTION\n  2\nTABLES\n  0\nTABLE\n%s0\nENDTAB\n0\nENDSEC\n  0\nSECTION\n  2\nBLOCKS\n0\nENDSEC\n  0\nSECTION\n  2\nENTITIES\n", layerlist);
+    } else {
+      msIO_fprintf(stream, "<map name=\"%s\" width=\"%d\" height=\"%d\">\n", mapName, img->width, img->height);
+    }
+    nSize = sizeof(workbuffer);
+
+    size = strlen(img->img.imagemap);
+    if (size > nSize) {
+      iIndice = 0;
+      while ((iIndice + nSize) <= size) {
+        snprintf(workbuffer, sizeof(workbuffer), "%s", img->img.imagemap+iIndice );
+        workbuffer[nSize-1] = '\0';
+        msIO_fwrite(workbuffer, strlen(workbuffer), 1, stream);
+        iIndice +=nSize-1;
+      }
+      if (iIndice < size) {
+        sprintf(workbuffer, "%s", img->img.imagemap+iIndice );
+        msIO_fprintf(stream, workbuffer);
+      }
+    } else
+      msIO_fwrite(img->img.imagemap, size, 1, stream);
+    if( strcasecmp("OFF",msGetOutputFormatOption( format, "SKIPENDTAG", "OFF" )) == 0) {
+      if (dxf == 2)
+        msIO_fprintf(stream, "END");
+      else if (dxf)
+        msIO_fprintf(stream, "0\nENDSEC\n0\nEOF\n");
+      else
+        msIO_fprintf(stream, "</map>");
+    }
+  } else {
+    msSetError(MS_MISCERR, "Unknown output image type driver: %s.",
+               "msSaveImage()", format->driver );
     return(MS_FAILURE);
-#endif*/
-	  }
-  }
-  else
-  {
-      msSetError(MS_MISCERR, "Unknown output image type driver: %s.", 
-                 "msSaveImage()", format->driver );
-      return(MS_FAILURE);
   }
 
   if(filename != NULL && strlen(filename) > 0) fclose(stream);
diff --git a/mapio.c b/mapio.c
index 1e79585..ac8cc5b 100644
--- a/mapio.c
+++ b/mapio.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -37,18 +37,23 @@
 #include <io.h>
 #endif
 
-MS_CVSID("$Id$")
+#ifdef MOD_WMS_ENABLED
+#  include "httpd.h"
+#  include "apr_strings.h"
+#endif
+
+
+
 
 static int is_msIO_initialized = MS_FALSE;
 
-typedef struct msIOContextGroup_t
-{
-    msIOContext stdin_context;
-    msIOContext stdout_context;
-    msIOContext stderr_context;
+typedef struct msIOContextGroup_t {
+  msIOContext stdin_context;
+  msIOContext stdout_context;
+  msIOContext stderr_context;
 
-    int    thread_id;
-    struct msIOContextGroup_t *next;
+  int    thread_id;
+  struct msIOContextGroup_t *next;
 } msIOContextGroup;
 
 static msIOContextGroup default_contexts;
@@ -70,17 +75,16 @@ static void msIO_Initialize( void );
 void msIO_Cleanup()
 
 {
-    if( is_msIO_initialized )
-
-    {
-        is_msIO_initialized = MS_FALSE;
-        while( io_context_list != NULL )
-        {
-            msIOContextGroup *last = io_context_list;
-            io_context_list = io_context_list->next;
-            free( last );
-        }
+  if( is_msIO_initialized )
+
+  {
+    is_msIO_initialized = MS_FALSE;
+    while( io_context_list != NULL ) {
+      msIOContextGroup *last = io_context_list;
+      io_context_list = io_context_list->next;
+      free( last );
     }
+  }
 }
 
 /************************************************************************/
@@ -90,58 +94,55 @@ void msIO_Cleanup()
 static msIOContextGroup *msIO_GetContextGroup()
 
 {
-    int nThreadId = msGetThreadId();
-    msIOContextGroup *prev = NULL, *group = io_context_list;
-
-    if( group != NULL && group->thread_id == nThreadId )
-        return group;
-
-/* -------------------------------------------------------------------- */
-/*      Search for group for this thread                                */
-/* -------------------------------------------------------------------- */
-    msAcquireLock( TLOCK_IOCONTEXT );
-    msIO_Initialize();
-
-    group = io_context_list;
-    while( group != NULL && group->thread_id != nThreadId )
-    {
-        prev = group;
-        group = group->next;
-    }
+  int nThreadId = msGetThreadId();
+  msIOContextGroup *prev = NULL, *group = io_context_list;
 
-/* -------------------------------------------------------------------- */
-/*      If we found it, make sure it is pushed to the front of the      */
-/*      link for faster finding next time, and return it.               */
-/* -------------------------------------------------------------------- */
-    if( group != NULL )
-    {
-        if( prev != NULL )
-        {
-            prev->next = group->next;
-            group->next = io_context_list;
-            io_context_list = group;
-        }
-
-        msReleaseLock( TLOCK_IOCONTEXT );
-        return group;
-    }
+  if( group != NULL && group->thread_id == nThreadId )
+    return group;
 
-/* -------------------------------------------------------------------- */
-/*      Create a new context group for this thread.                     */
-/* -------------------------------------------------------------------- */
-    group = (msIOContextGroup *) calloc(sizeof(msIOContextGroup),1);
-    
-    group->stdin_context = default_contexts.stdin_context;
-    group->stdout_context = default_contexts.stdout_context;
-    group->stderr_context = default_contexts.stderr_context;
-    group->thread_id = nThreadId;
+  /* -------------------------------------------------------------------- */
+  /*      Search for group for this thread                                */
+  /* -------------------------------------------------------------------- */
+  msAcquireLock( TLOCK_IOCONTEXT );
+  msIO_Initialize();
+
+  group = io_context_list;
+  while( group != NULL && group->thread_id != nThreadId ) {
+    prev = group;
+    group = group->next;
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      If we found it, make sure it is pushed to the front of the      */
+  /*      link for faster finding next time, and return it.               */
+  /* -------------------------------------------------------------------- */
+  if( group != NULL ) {
+    if( prev != NULL ) {
+      prev->next = group->next;
+      group->next = io_context_list;
+      io_context_list = group;
+    }
 
-    group->next = io_context_list;
-    io_context_list = group;
-    
     msReleaseLock( TLOCK_IOCONTEXT );
-
     return group;
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Create a new context group for this thread.                     */
+  /* -------------------------------------------------------------------- */
+  group = (msIOContextGroup *) calloc(sizeof(msIOContextGroup),1);
+
+  group->stdin_context = default_contexts.stdin_context;
+  group->stdout_context = default_contexts.stdout_context;
+  group->stderr_context = default_contexts.stderr_context;
+  group->thread_id = nThreadId;
+
+  group->next = io_context_list;
+  io_context_list = group;
+
+  msReleaseLock( TLOCK_IOCONTEXT );
+
+  return group;
 }
 
 /************************************************************************/
@@ -151,28 +152,68 @@ static msIOContextGroup *msIO_GetContextGroup()
 msIOContext *msIO_getHandler( FILE * fp )
 
 {
-    int nThreadId = msGetThreadId();
-    msIOContextGroup *group = io_context_list;
+  int nThreadId = msGetThreadId();
+  msIOContextGroup *group = io_context_list;
 
-    msIO_Initialize();
+  msIO_Initialize();
 
-    if( group == NULL || group->thread_id != nThreadId )
-    {
-        group = msIO_GetContextGroup();
-        if( group == NULL )
-            return NULL;
+  if( group == NULL || group->thread_id != nThreadId ) {
+    group = msIO_GetContextGroup();
+    if( group == NULL )
+      return NULL;
+  }
+
+  if( fp == stdin || fp == NULL || strcmp((const char *)fp,"stdin") == 0 )
+    return &(group->stdin_context);
+  else if( fp == stdout || strcmp((const char *)fp,"stdout") == 0 )
+    return &(group->stdout_context);
+  else if( fp == stderr || strcmp((const char *)fp,"stderr") == 0 )
+    return &(group->stderr_context);
+  else
+    return NULL;
+}
+
+void msIO_setHeader (const char *header, const char* value, ...)
+{
+  va_list args;
+  va_start( args, value );
+#ifdef MOD_WMS_ENABLED
+  msIOContext *ioctx = msIO_getHandler (stdout);
+  if(ioctx && !strcmp(ioctx->label,"apache")) {
+
+    request_rec *r = (request_rec*) (ioctx->cbData);
+    char *fullvalue = apr_pvsprintf(r->pool, value,args);
+    if (strcasecmp (header, "Content-Type") == 0) {
+      r->content_type = fullvalue;
+    } else if (strcasecmp (header, "Status") == 0) {
+      r->status = atoi (fullvalue);
+    } else {
+      apr_table_setn (r->headers_out,
+                      apr_pstrdup (r->pool, header),
+                      fullvalue
+                     );
     }
+  } else {
+#endif // MOD_WMS_ENABLED
+    msIO_fprintf(stdout,"%s: ",header);
+    msIO_vfprintf(stdout,value,args);
+    msIO_fprintf(stdout,"\r\n");
+#ifdef MOD_WMS_ENABLED
+  }
+#endif
+}
 
-    if( fp == stdin || fp == NULL || strcmp((const char *)fp,"stdin") == 0 )
-        return &(group->stdin_context);
-    else if( fp == stdout || strcmp((const char *)fp,"stdout") == 0 )
-        return &(group->stdout_context);
-    else if( fp == stderr || strcmp((const char *)fp,"stderr") == 0 )
-        return &(group->stderr_context);
-    else
-        return NULL;
+void msIO_sendHeaders ()
+{
+#ifdef MOD_WMS_ENABLED
+  msIOContext *ioctx = msIO_getHandler (stdout);
+  if(ioctx && !strcmp(ioctx->label,"apache")) return;
+#endif // !MOD_WMS_ENABLED
+  msIO_printf ("\r\n");
+  fflush (stdout);
 }
 
+
 /************************************************************************/
 /*                        msIO_installHandlers()                        */
 /************************************************************************/
@@ -182,28 +223,28 @@ int msIO_installHandlers( msIOContext *stdin_context,
                           msIOContext *stderr_context )
 
 {
-    msIOContextGroup *group;
+  msIOContextGroup *group;
 
-    msIO_Initialize();
+  msIO_Initialize();
 
-    group = msIO_GetContextGroup();
-    
-    if( stdin_context == NULL )
-        group->stdin_context = default_contexts.stdin_context;
-    else if( stdin_context != &group->stdin_context )
-        group->stdin_context = *stdin_context;
-    
-    if( stdout_context == NULL )
-        group->stdout_context = default_contexts.stdout_context;
-    else if( stdout_context != &group->stdout_context )
-        group->stdout_context = *stdout_context;
-    
-    if( stderr_context == NULL )
-        group->stderr_context = default_contexts.stderr_context;
-    else if( stderr_context != &group->stderr_context )
-        group->stderr_context = *stderr_context;
-    
-    return MS_TRUE;
+  group = msIO_GetContextGroup();
+
+  if( stdin_context == NULL )
+    group->stdin_context = default_contexts.stdin_context;
+  else if( stdin_context != &group->stdin_context )
+    group->stdin_context = *stdin_context;
+
+  if( stdout_context == NULL )
+    group->stdout_context = default_contexts.stdout_context;
+  else if( stdout_context != &group->stdout_context )
+    group->stdout_context = *stdout_context;
+
+  if( stderr_context == NULL )
+    group->stderr_context = default_contexts.stderr_context;
+  else if( stderr_context != &group->stderr_context )
+    group->stderr_context = *stderr_context;
+
+  return MS_TRUE;
 }
 
 /************************************************************************/
@@ -213,10 +254,10 @@ int msIO_installHandlers( msIOContext *stdin_context,
 int msIO_contextRead( msIOContext *context, void *data, int byteCount )
 
 {
-    if( context->write_channel == MS_TRUE )
-        return 0;
-    else
-        return context->readWriteFunc( context->cbData, data, byteCount );
+  if( context->write_channel == MS_TRUE )
+    return 0;
+  else
+    return context->readWriteFunc( context->cbData, data, byteCount );
 }
 
 /************************************************************************/
@@ -226,11 +267,11 @@ int msIO_contextRead( msIOContext *context, void *data, int byteCount )
 int msIO_contextWrite( msIOContext *context, const void *data, int byteCount )
 
 {
-    if( context->write_channel == MS_FALSE )
-        return 0;
-    else
-        return context->readWriteFunc( context->cbData, (void *) data, 
-                                       byteCount );
+  if( context->write_channel == MS_FALSE )
+    return 0;
+  else
+    return context->readWriteFunc( context->cbData, (void *) data,
+                                   byteCount );
 }
 
 /* ==================================================================== */
@@ -246,62 +287,58 @@ int msIO_contextWrite( msIOContext *context, const void *data, int byteCount )
 static int _ms_vsprintf(char **workBufPtr, const char *format, va_list ap )
 
 {
-    int     ret_val;
-    int   workBufSize = 16000;
+  int     ret_val;
+  int   workBufSize = 16000;
 
-    *workBufPtr = (char*)malloc(workBufSize * sizeof(char));
-    if (*workBufPtr == NULL)
-    {
-        msSetError( MS_MEMERR, NULL, "_ms_vsprintf()");
-        return -1;
-    }
+  *workBufPtr = (char*)malloc(workBufSize * sizeof(char));
+  if (*workBufPtr == NULL) {
+    msSetError( MS_MEMERR, NULL, "_ms_vsprintf()");
+    return -1;
+  }
 
 #if defined(HAVE_VSNPRINTF)
-    /* This should grow a big enough buffer to hold any formatted result. */
-    {
-        va_list wrk_args;
+  /* This should grow a big enough buffer to hold any formatted result. */
+  {
+    va_list wrk_args;
 
 #ifdef va_copy
-        va_copy( wrk_args, ap );
+    va_copy( wrk_args, ap );
 #else
-        wrk_args = ap;
+    wrk_args = ap;
 #endif
 
-        while( (ret_val = vsnprintf( *workBufPtr, workBufSize, 
-                                     format, wrk_args)) >= workBufSize-1 
-               || ret_val == -1 )
-        {
-            workBufSize *= 4;
-            *workBufPtr = (char *) realloc(*workBufPtr, workBufSize );
-            if (*workBufPtr == NULL)
-            {
-                msSetError( MS_MEMERR, NULL, "_ms_vsprintf()");
-                va_end( wrk_args );
-                return -1;
-            }
+    while( (ret_val = vsnprintf( *workBufPtr, workBufSize,
+                                 format, wrk_args)) >= workBufSize-1
+           || ret_val == -1 ) {
+      workBufSize *= 4;
+      *workBufPtr = (char *) realloc(*workBufPtr, workBufSize );
+      if (*workBufPtr == NULL) {
+        msSetError( MS_MEMERR, NULL, "_ms_vsprintf()");
+        va_end( wrk_args );
+        return -1;
+      }
 #ifdef va_copy
-            va_end( wrk_args );
-            va_copy( wrk_args, ap );
+      va_end( wrk_args );
+      va_copy( wrk_args, ap );
 #else
-            wrk_args = ap;
+      wrk_args = ap;
 #endif
-        }
-        va_end( wrk_args );
     }
+    va_end( wrk_args );
+  }
 #else
-    /* We do not have vsnprintf()... there is a risk of buffer overrun */
-    ret_val = vsprintf( *workBufPtr, format, ap );
-
-    if( ret_val < 0 || ret_val >= workBufSize )
-    {
-        msSetError(MS_MISCERR, "Possible buffer overrun.", "_ms_vsprintf()");
-        msFree(*workBufPtr);
-        *workBufPtr = NULL;
-        return -1;
-    }
+  /* We do not have vsnprintf()... there is a risk of buffer overrun */
+  ret_val = vsprintf( *workBufPtr, format, ap );
+
+  if( ret_val < 0 || ret_val >= workBufSize ) {
+    msSetError(MS_MISCERR, "Possible buffer overrun.", "_ms_vsprintf()");
+    msFree(*workBufPtr);
+    *workBufPtr = NULL;
+    return -1;
+  }
 #endif
 
-    return ret_val;
+  return ret_val;
 }
 
 
@@ -312,55 +349,12 @@ static int _ms_vsprintf(char **workBufPtr, const char *format, va_list ap )
 int msIO_printf( const char *format, ... )
 
 {
-    va_list args, args_copy;
-    int     return_val;
-    msIOContext *context;
-    char workBuf[8000], *largerBuf = NULL;
-
-    va_start( args, format );
-
-#if !defined(HAVE_VSNPRINTF)
-    return_val = vsprintf( workBuf, format, args);
-
-    if( return_val < 0 || return_val >= sizeof(workBuf) )
-    {
-        va_end( args );
-        msSetError(MS_MISCERR, "Possible buffer overrun.", "msIO_printf()");
-        return -1;
-    }
-
-#else
-
-#ifdef va_copy
-    va_copy( args_copy, args );
-#else
-    args_copy = args;
-#endif /* va_copy */
-
-    return_val = vsnprintf( workBuf, sizeof(workBuf), format, args );
-    if (return_val == -1 || return_val >= sizeof(workBuf)-1)
-    {
-        return_val = _ms_vsprintf(&largerBuf, format, args_copy );
-    }
-    va_end(args_copy);
-
-#endif /* HAVE_VSNPRINTF */
-
-    va_end( args );
-
-    if (return_val < 0)
-        return -1;
-
-    context = msIO_getHandler( stdout );
-    if( context == NULL )
-        return -1;
-
-    return_val = msIO_contextWrite( context, 
-                                    largerBuf?largerBuf:workBuf, 
-                                    return_val );
-    msFree(largerBuf);
-
-    return return_val;
+  va_list args;
+  int ret;
+  va_start( args, format );
+  ret = msIO_vfprintf(stdout,format,args);
+  va_end(args);
+  return ret;
 }
 
 /************************************************************************/
@@ -370,56 +364,12 @@ int msIO_printf( const char *format, ... )
 int msIO_fprintf( FILE *fp, const char *format, ... )
 
 {
-    va_list args, args_copy;
-    int     return_val;
-    msIOContext *context;
-    char workBuf[8000], *largerBuf = NULL;
-
-    va_start( args, format );
-
-#if !defined(HAVE_VSNPRINTF)
-    return_val = vsprintf( workBuf, format, args);
-
-    if( return_val < 0 || return_val >= sizeof(workBuf) )
-    {
-        va_end( args );
-        msSetError(MS_MISCERR, "Possible buffer overrun.", "msIO_fprintf()");
-        return -1;
-    }
-
-#else
-
-#ifdef va_copy
-    va_copy( args_copy, args );
-#else
-    args_copy = args;
-#endif /* va_copy */
-
-    return_val = vsnprintf( workBuf, sizeof(workBuf), format, args );
-    if (return_val == -1 || return_val >= sizeof(workBuf)-1)
-    {
-        return_val = _ms_vsprintf(&largerBuf, format, args_copy );
-    }
-    va_end(args_copy);
-
-#endif /* HAVE_VSNPRINTF */
-
-    va_end( args );
-
-    if (return_val < 0)
-        return -1;
-
-    context = msIO_getHandler( fp );
-    if( context == NULL )
-        return_val = fwrite( largerBuf?largerBuf:workBuf, 1, return_val, fp );
-    else
-        return_val =  msIO_contextWrite( context, 
-                                         largerBuf?largerBuf:workBuf, 
-                                         return_val );
-
-    msFree(largerBuf);
-
-    return return_val;
+  va_list args;
+  int ret;
+  va_start( args, format );
+  ret = msIO_vfprintf(fp,format,args);
+  va_end(args);
+  return ret;
 }
 
 /************************************************************************/
@@ -429,51 +379,49 @@ int msIO_fprintf( FILE *fp, const char *format, ... )
 int msIO_vfprintf( FILE *fp, const char *format, va_list ap )
 
 {
-    va_list args_copy;
-    int     return_val;
-    msIOContext *context;
-    char workBuf[8000], *largerBuf = NULL;
+  va_list args_copy;
+  int     return_val;
+  msIOContext *context;
+  char workBuf[8000], *largerBuf = NULL;
 
 #if !defined(HAVE_VSNPRINTF)
-    return_val = vsprintf( workBuf, format, ap);
+  return_val = vsprintf( workBuf, format, ap);
 
-    if( return_val < 0 || return_val >= sizeof(workBuf) )
-    {
-        msSetError(MS_MISCERR, "Possible buffer overrun.", "msIO_vfprintf()");
-        return -1;
-    }
+  if( return_val < 0 || return_val >= sizeof(workBuf) ) {
+    msSetError(MS_MISCERR, "Possible buffer overrun.", "msIO_vfprintf()");
+    return -1;
+  }
 
 #else
 
 #ifdef va_copy
-    va_copy( args_copy, ap );
+  va_copy( args_copy, ap );
 #else
-    args_copy = ap;
+  args_copy = ap;
 #endif /* va_copy */
 
-    return_val = vsnprintf( workBuf, sizeof(workBuf), format, ap );
-    if (return_val == -1 || return_val >= sizeof(workBuf)-1)
-    {
-        return_val = _ms_vsprintf(&largerBuf, format, args_copy );
-    }
-    va_end(args_copy);
+  return_val = vsnprintf( workBuf, sizeof(workBuf), format, ap );
+  if (return_val == -1 || return_val >= sizeof(workBuf)-1) {
+    return_val = _ms_vsprintf(&largerBuf, format, args_copy );
+  }
+  va_end(args_copy);
 
 #endif /* HAVE_VSNPRINTF */
 
-    if (return_val < 0)
-        return -1;
+  if (return_val < 0)
+    return -1;
 
-    context = msIO_getHandler( fp );
-    if( context == NULL )
-        return_val = fwrite( largerBuf?largerBuf:workBuf, 1, return_val, fp );
-    else
-        return_val =  msIO_contextWrite( context, 
-                                         largerBuf?largerBuf:workBuf, 
-                                         return_val );
+  context = msIO_getHandler( fp );
+  if( context == NULL )
+    return_val = fwrite( largerBuf?largerBuf:workBuf, 1, return_val, fp );
+  else
+    return_val =  msIO_contextWrite( context,
+                                     largerBuf?largerBuf:workBuf,
+                                     return_val );
 
-    msFree(largerBuf);
+  msFree(largerBuf);
 
-    return return_val;
+  return return_val;
 }
 
 /************************************************************************/
@@ -483,13 +431,16 @@ int msIO_vfprintf( FILE *fp, const char *format, va_list ap )
 int msIO_fwrite( const void *data, size_t size, size_t nmemb, FILE *fp )
 
 {
-    msIOContext *context;
+  msIOContext *context;
 
-    context = msIO_getHandler( fp );
-    if( context == NULL )
-        return fwrite( data, size, nmemb, fp );
-    else
-        return msIO_contextWrite( context, data, size * nmemb ) / size;
+  if( size == 0 || nmemb == 0 )
+    return 0;
+
+  context = msIO_getHandler( fp );
+  if( context == NULL )
+    return fwrite( data, size, nmemb, fp );
+  else
+    return msIO_contextWrite( context, data, size * nmemb ) / size;
 }
 
 /************************************************************************/
@@ -499,13 +450,16 @@ int msIO_fwrite( const void *data, size_t size, size_t nmemb, FILE *fp )
 int msIO_fread( void *data, size_t size, size_t nmemb, FILE *fp )
 
 {
-    msIOContext *context;
+  msIOContext *context;
 
-    context = msIO_getHandler( fp );
-    if( context == NULL )
-        return fread( data, size, nmemb, fp );
-    else
-        return msIO_contextRead( context, data, size * nmemb ) / size;
+  if( size == 0 || nmemb == 0 )
+    return 0;
+
+  context = msIO_getHandler( fp );
+  if( context == NULL )
+    return fread( data, size, nmemb, fp );
+  else
+    return msIO_contextRead( context, data, size * nmemb ) / size;
 }
 
 /* ==================================================================== */
@@ -524,7 +478,7 @@ int msIO_fread( void *data, size_t size, size_t nmemb, FILE *fp )
 static int msIO_stdioRead( void *cbData, void *data, int byteCount )
 
 {
-    return fread( data, 1, byteCount, (FILE *) cbData );
+  return fread( data, 1, byteCount, (FILE *) cbData );
 }
 
 /************************************************************************/
@@ -536,7 +490,7 @@ static int msIO_stdioRead( void *cbData, void *data, int byteCount )
 static int msIO_stdioWrite( void *cbData, void *data, int byteCount )
 
 {
-    return fwrite( data, 1, byteCount, (FILE *) cbData );
+  return fwrite( data, 1, byteCount, (FILE *) cbData );
 }
 
 /************************************************************************/
@@ -546,28 +500,28 @@ static int msIO_stdioWrite( void *cbData, void *data, int byteCount )
 static void msIO_Initialize( void )
 
 {
-    if( is_msIO_initialized == MS_TRUE )
-        return;
+  if( is_msIO_initialized == MS_TRUE )
+    return;
 
-    default_contexts.stdin_context.label = "stdio";
-    default_contexts.stdin_context.write_channel = MS_FALSE;
-    default_contexts.stdin_context.readWriteFunc = msIO_stdioRead;
-    default_contexts.stdin_context.cbData = (void *) stdin;
+  default_contexts.stdin_context.label = "stdio";
+  default_contexts.stdin_context.write_channel = MS_FALSE;
+  default_contexts.stdin_context.readWriteFunc = msIO_stdioRead;
+  default_contexts.stdin_context.cbData = (void *) stdin;
 
-    default_contexts.stdout_context.label = "stdio";
-    default_contexts.stdout_context.write_channel = MS_TRUE;
-    default_contexts.stdout_context.readWriteFunc = msIO_stdioWrite;
-    default_contexts.stdout_context.cbData = (void *) stdout;
+  default_contexts.stdout_context.label = "stdio";
+  default_contexts.stdout_context.write_channel = MS_TRUE;
+  default_contexts.stdout_context.readWriteFunc = msIO_stdioWrite;
+  default_contexts.stdout_context.cbData = (void *) stdout;
 
-    default_contexts.stderr_context.label = "stdio";
-    default_contexts.stderr_context.write_channel = MS_TRUE;
-    default_contexts.stderr_context.readWriteFunc = msIO_stdioWrite;
-    default_contexts.stderr_context.cbData = (void *) stderr;
+  default_contexts.stderr_context.label = "stdio";
+  default_contexts.stderr_context.write_channel = MS_TRUE;
+  default_contexts.stderr_context.readWriteFunc = msIO_stdioWrite;
+  default_contexts.stderr_context.cbData = (void *) stderr;
 
-    default_contexts.next = NULL;
-    default_contexts.thread_id = 0;
+  default_contexts.next = NULL;
+  default_contexts.thread_id = 0;
 
-    is_msIO_initialized = MS_TRUE;
+  is_msIO_initialized = MS_TRUE;
 }
 
 /* ==================================================================== */
@@ -578,10 +532,14 @@ static void msIO_Initialize( void )
 /* ==================================================================== */
 
 typedef struct {
-    gdIOCtx        gd_io_ctx;
-    msIOContext    *ms_io_ctx;
+#ifdef USE_GD
+  gdIOCtx        gd_io_ctx;
+#endif
+  msIOContext    *ms_io_ctx;
 } msIO_gdIOCtx;
 
+
+#ifdef USE_GD
 /************************************************************************/
 /*                            msIO_gd_putC()                            */
 /*                                                                      */
@@ -592,10 +550,10 @@ typedef struct {
 static void msIO_gd_putC( gdIOCtx *cbData, int out_char )
 
 {
-    msIO_gdIOCtx *merged_context = (msIO_gdIOCtx *) cbData;
-    char out_char_as_char = (char) out_char;
+  msIO_gdIOCtx *merged_context = (msIO_gdIOCtx *) cbData;
+  char out_char_as_char = (char) out_char;
 
-    msIO_contextWrite( merged_context->ms_io_ctx, &out_char_as_char, 1 );
+  msIO_contextWrite( merged_context->ms_io_ctx, &out_char_as_char, 1 );
 }
 
 /************************************************************************/
@@ -608,10 +566,11 @@ static void msIO_gd_putC( gdIOCtx *cbData, int out_char )
 static int msIO_gd_putBuf( gdIOCtx *cbData, const void *data, int byteCount )
 
 {
-    msIO_gdIOCtx *merged_context = (msIO_gdIOCtx *) cbData;
+  msIO_gdIOCtx *merged_context = (msIO_gdIOCtx *) cbData;
 
-    return msIO_contextWrite( merged_context->ms_io_ctx, data, byteCount );
+  return msIO_contextWrite( merged_context->ms_io_ctx, data, byteCount );
 }
+#endif
 
 /************************************************************************/
 /*                          msIO_getGDIOCtx()                           */
@@ -620,22 +579,24 @@ static int msIO_gd_putBuf( gdIOCtx *cbData, const void *data, int byteCount )
 /*      longer needed.                                                  */
 /************************************************************************/
 
+#ifdef USE_GD
 gdIOCtx *msIO_getGDIOCtx( FILE *fp )
 
 {
-    msIO_gdIOCtx *merged_context;
-    msIOContext *context = msIO_getHandler( fp );
+  msIO_gdIOCtx *merged_context;
+  msIOContext *context = msIO_getHandler( fp );
 
-    if( context == NULL )
-        return NULL;
+  if( context == NULL )
+    return NULL;
 
-    merged_context = (msIO_gdIOCtx *) calloc(1,sizeof(msIO_gdIOCtx));
-    merged_context->gd_io_ctx.putC = msIO_gd_putC;
-    merged_context->gd_io_ctx.putBuf = msIO_gd_putBuf;
-    merged_context->ms_io_ctx = context;
+  merged_context = (msIO_gdIOCtx *) calloc(1,sizeof(msIO_gdIOCtx));
+  merged_context->gd_io_ctx.putC = msIO_gd_putC;
+  merged_context->gd_io_ctx.putBuf = msIO_gd_putBuf;
+  merged_context->ms_io_ctx = context;
 
-    return (gdIOCtx *) merged_context;
+  return (gdIOCtx *) merged_context;
 }
+#endif
 
 /* ==================================================================== */
 /* ==================================================================== */
@@ -643,65 +604,7 @@ gdIOCtx *msIO_getGDIOCtx( FILE *fp )
 /* ==================================================================== */
 /* ==================================================================== */
 
-#ifdef USE_FASTCGI
-
-#define NO_FCGI_DEFINES
-#include "fcgi_stdio.h"
-
-/************************************************************************/
-/*                           msIO_fcgiRead()                            */
-/*                                                                      */
-/*      This is the default implementation via stdio.                   */
-/************************************************************************/
-
-static int msIO_fcgiRead( void *cbData, void *data, int byteCount )
-
-{
-    return FCGI_fread( data, 1, byteCount, (FCGI_FILE *) cbData );
-}
-
-/************************************************************************/
-/*                           msIO_fcgiWrite()                           */
-/*                                                                      */
-/*      This is the default implementation via stdio.                   */
-/************************************************************************/
-
-static int msIO_fcgiWrite( void *cbData, void *data, int byteCount )
-
-{
-    return FCGI_fwrite( data, 1, byteCount, (FCGI_FILE *) cbData );
-}
-
-/************************************************************************/
-/*                    msIO_installFastCGIRedirect()                     */
-/************************************************************************/
-
-int msIO_installFastCGIRedirect()
-
-{
-    msIOContext stdin_ctx, stdout_ctx, stderr_ctx;
-
-    stdin_ctx.label = "fcgi";
-    stdin_ctx.write_channel = MS_FALSE;
-    stdin_ctx.readWriteFunc = msIO_fcgiRead;
-    stdin_ctx.cbData = (void *) FCGI_stdin;
-
-    stdout_ctx.label = "fcgi";
-    stdout_ctx.write_channel = MS_TRUE;
-    stdout_ctx.readWriteFunc = msIO_fcgiWrite;
-    stdout_ctx.cbData = (void *) FCGI_stdout;
-
-    stderr_ctx.label = "fcgi";
-    stderr_ctx.write_channel = MS_TRUE;
-    stderr_ctx.readWriteFunc = msIO_fcgiWrite;
-    stderr_ctx.cbData = (void *) FCGI_stderr;
 
-    msIO_installHandlers( &stdin_ctx, &stdout_ctx, &stderr_ctx );
-
-    return MS_TRUE;
-}
-
-#endif
 
 /************************************************************************/
 /*                       msIO_needBinaryStdout()                        */
@@ -719,16 +622,15 @@ int msIO_needBinaryStdout()
 
 {
 #if defined(_WIN32) && !defined(USE_FASTCGI)
-    if(_setmode( _fileno(stdout), _O_BINARY) == -1) 
-    {
-      msSetError(MS_IOERR, 
-                 "Unable to change stdout to binary mode.", 
-                 "msIO_needBinaryStdout()" );
-      return(MS_FAILURE);
-    }
+  if(_setmode( _fileno(stdout), _O_BINARY) == -1) {
+    msSetError(MS_IOERR,
+               "Unable to change stdout to binary mode.",
+               "msIO_needBinaryStdout()" );
+    return(MS_FAILURE);
+  }
 #endif
-    
-    return MS_SUCCESS;
+
+  return MS_SUCCESS;
 }
 
 /************************************************************************/
@@ -747,16 +649,15 @@ int msIO_needBinaryStdin()
 
 {
 #if defined(_WIN32) && !defined(USE_FASTCGI)
-    if(_setmode( _fileno(stdin), _O_BINARY) == -1) 
-    {
-      msSetError(MS_IOERR, 
-                 "Unable to change stdin to binary mode.", 
-                 "msIO_needBinaryStdin()" );
-      return(MS_FAILURE);
-    }
+  if(_setmode( _fileno(stdin), _O_BINARY) == -1) {
+    msSetError(MS_IOERR,
+               "Unable to change stdin to binary mode.",
+               "msIO_needBinaryStdin()" );
+    return(MS_FAILURE);
+  }
 #endif
-    
-    return MS_SUCCESS;
+
+  return MS_SUCCESS;
 }
 
 /* ==================================================================== */
@@ -770,39 +671,36 @@ int msIO_needBinaryStdin()
 void msIO_resetHandlers()
 
 {
-    msIOContextGroup *group = msIO_GetContextGroup();
+  msIOContextGroup *group = msIO_GetContextGroup();
 
-    if( group == NULL )
-        return;
-
-    if( strcmp(group->stdin_context.label,"buffer") == 0 )
-    {
-        msIOBuffer *buf = (msIOBuffer *) group->stdin_context.cbData;
-        
-        if( buf->data != NULL )
-            free( buf->data );
-        free( buf );
-    }
+  if( group == NULL )
+    return;
 
-    if( strcmp(group->stdout_context.label,"buffer") == 0 )
-    {
-        msIOBuffer *buf = (msIOBuffer *) group->stdout_context.cbData;
-        
-        if( buf->data != NULL )
-            free( buf->data );
-        free( buf );
-    }
+  if( strcmp(group->stdin_context.label,"buffer") == 0 ) {
+    msIOBuffer *buf = (msIOBuffer *) group->stdin_context.cbData;
 
-    if( strcmp(group->stderr_context.label,"buffer") == 0 )
-    {
-        msIOBuffer *buf = (msIOBuffer *) group->stderr_context.cbData;
-        
-        if( buf->data != NULL )
-            free( buf->data );
-        free( buf );
-    }
+    if( buf->data != NULL )
+      free( buf->data );
+    free( buf );
+  }
+
+  if( strcmp(group->stdout_context.label,"buffer") == 0 ) {
+    msIOBuffer *buf = (msIOBuffer *) group->stdout_context.cbData;
+
+    if( buf->data != NULL )
+      free( buf->data );
+    free( buf );
+  }
+
+  if( strcmp(group->stderr_context.label,"buffer") == 0 ) {
+    msIOBuffer *buf = (msIOBuffer *) group->stderr_context.cbData;
 
-    msIO_installHandlers( NULL, NULL, NULL );
+    if( buf->data != NULL )
+      free( buf->data );
+    free( buf );
+  }
+
+  msIO_installHandlers( NULL, NULL, NULL );
 }
 
 /************************************************************************/
@@ -812,17 +710,17 @@ void msIO_resetHandlers()
 void msIO_installStdoutToBuffer()
 
 {
-    msIOContextGroup *group = msIO_GetContextGroup();
-    msIOContext  context;
-    
-    context.label = "buffer";
-    context.write_channel = MS_TRUE;
-    context.readWriteFunc = msIO_bufferWrite;
-    context.cbData = calloc(sizeof(msIOBuffer),1);
-
-    msIO_installHandlers( &group->stdin_context, 
-                          &context, 
-                          &group->stderr_context );
+  msIOContextGroup *group = msIO_GetContextGroup();
+  msIOContext  context;
+
+  context.label = "buffer";
+  context.write_channel = MS_TRUE;
+  context.readWriteFunc = msIO_bufferWrite;
+  context.cbData = calloc(sizeof(msIOBuffer),1);
+
+  msIO_installHandlers( &group->stdin_context,
+                        &context,
+                        &group->stderr_context );
 }
 
 /************************************************************************/
@@ -832,105 +730,100 @@ void msIO_installStdoutToBuffer()
 void msIO_installStdinFromBuffer()
 
 {
-    msIOContextGroup *group = msIO_GetContextGroup();
-    msIOContext  context;
+  msIOContextGroup *group = msIO_GetContextGroup();
+  msIOContext  context;
 
-    context.label = "buffer";
-    context.write_channel = MS_FALSE;
-    context.readWriteFunc = msIO_bufferRead;
-    context.cbData = calloc(sizeof(msIOBuffer),1);
+  context.label = "buffer";
+  context.write_channel = MS_FALSE;
+  context.readWriteFunc = msIO_bufferRead;
+  context.cbData = calloc(sizeof(msIOBuffer),1);
 
-    msIO_installHandlers( &context, 
-                          &group->stdout_context, 
-                          &group->stderr_context );
+  msIO_installHandlers( &context,
+                        &group->stdout_context,
+                        &group->stderr_context );
 }
 
 /************************************************************************/
 /*                 msIO_stripStdoutBufferContentType()                  */
 /*                                                                      */
-/*      Strip off content-type header from buffer, and return to        */
+/*      Strip off Content-Type header from buffer, and return to        */
 /*      caller.  Returned string is the callers responsibility to       */
 /*      call msFree() on to deallocate.  This function will return      */
-/*      NULL if there is no content-type header.                        */
+/*      NULL if there is no Content-Type header.                        */
 /************************************************************************/
 
 char *msIO_stripStdoutBufferContentType()
 
 {
-/* -------------------------------------------------------------------- */
-/*      Find stdout buffer.                                             */
-/* -------------------------------------------------------------------- */
-    msIOContext *ctx = msIO_getHandler( (FILE *) "stdout" );
-    msIOBuffer  *buf;
-    char *content_type = NULL;
-    int end_of_ct, start_of_data;
-
-    if( ctx == NULL || ctx->write_channel == MS_FALSE 
-        || strcmp(ctx->label,"buffer") != 0 )
-    {
-	msSetError( MS_MISCERR, "Can't identify msIO buffer.",
-                    "msIO_stripStdoutBufferContentType" );
-	return NULL;
-    }
-
-    buf = (msIOBuffer *) ctx->cbData;
-
-/* -------------------------------------------------------------------- */
-/*      Return NULL if we don't have a content-type header.             */
-/* -------------------------------------------------------------------- */
-    if( buf->data_offset < 14 
-        || strncasecmp((const char*) buf->data,"Content-type: ",14) != 0 )
-        return NULL;
-
-/* -------------------------------------------------------------------- */
-/*      Find newline marker at end of content type argument.            */
-/* -------------------------------------------------------------------- */
-    end_of_ct = 13;
-    while( end_of_ct+1 < buf->data_offset 
-           && buf->data[end_of_ct+1] != 10 )
-        end_of_ct++;
-
-    if( end_of_ct+1 == buf->data_offset )
-    {
-	msSetError( MS_MISCERR, "Corrupt Content-type header.",
-                    "msIO_stripStdoutBufferContentType" );
-	return NULL;
-    }
-
-/* -------------------------------------------------------------------- */
-/*      Continue on to the start of data ... skipping two newline       */
-/*      markers.                                                        */
-/* -------------------------------------------------------------------- */
-    start_of_data = end_of_ct+2;
-    while( start_of_data  < buf->data_offset 
-           && buf->data[start_of_data] != 10 )
-        start_of_data++;
-
-    if( start_of_data == buf->data_offset )
-    {
-	msSetError( MS_MISCERR, "Corrupt Content-type header.",
-                    "msIO_stripStdoutBufferContentType" );
-	return NULL;
-    }
-
-    start_of_data++;
-
-/* -------------------------------------------------------------------- */
-/*      Copy out content type.                                          */
-/* -------------------------------------------------------------------- */
-    content_type = (char *) malloc(end_of_ct-14+2);
-    strlcpy( content_type, (const char *) buf->data + 14, end_of_ct - 14 + 2);
-    content_type[end_of_ct-14+1] = '\0';
-
-/* -------------------------------------------------------------------- */
-/*      Move data to front of buffer, and reset length.                 */
-/* -------------------------------------------------------------------- */
-    memmove( buf->data, buf->data+start_of_data, 
-             buf->data_offset - start_of_data );
-    buf->data[buf->data_offset - start_of_data] = '\0';
-    buf->data_offset -= start_of_data;
-
-    return content_type;
+  /* -------------------------------------------------------------------- */
+  /*      Find stdout buffer.                                             */
+  /* -------------------------------------------------------------------- */
+  msIOContext *ctx = msIO_getHandler( (FILE *) "stdout" );
+  msIOBuffer  *buf;
+  char *content_type = NULL;
+  int end_of_ct, start_of_data;
+
+  if( ctx == NULL || ctx->write_channel == MS_FALSE
+      || strcmp(ctx->label,"buffer") != 0 ) {
+    msSetError( MS_MISCERR, "Can't identify msIO buffer.",
+                "msIO_stripStdoutBufferContentType" );
+    return NULL;
+  }
+
+  buf = (msIOBuffer *) ctx->cbData;
+
+  /* -------------------------------------------------------------------- */
+  /*      Return NULL if we don't have a Content-Type header.             */
+  /* -------------------------------------------------------------------- */
+  if( buf->data_offset < 14
+      || strncasecmp((const char*) buf->data,"Content-Type: ",14) != 0 )
+    return NULL;
+
+  /* -------------------------------------------------------------------- */
+  /*      Find newline marker at end of content type argument.            */
+  /* -------------------------------------------------------------------- */
+  end_of_ct = 13;
+  while( end_of_ct+1 < buf->data_offset
+         && buf->data[end_of_ct+1] != '\r' )
+    end_of_ct++;
+
+  if( end_of_ct+1 == buf->data_offset ) {
+    msSetError( MS_MISCERR, "Corrupt Content-Type header.",
+                "msIO_stripStdoutBufferContentType" );
+    return NULL;
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Continue on to the start of data ...                            */
+  /*      Go to next line and skip if empty.                              */
+  /* -------------------------------------------------------------------- */
+  start_of_data = end_of_ct+3;
+  if( start_of_data  < buf->data_offset
+      && buf->data[start_of_data] == '\r' )
+    start_of_data +=2;
+  
+  if( start_of_data == buf->data_offset ) {
+    msSetError( MS_MISCERR, "Corrupt Content-Type header.",
+                "msIO_stripStdoutBufferContentType" );
+    return NULL;
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Copy out content type.                                          */
+  /* -------------------------------------------------------------------- */
+  content_type = (char *) malloc(end_of_ct-14+2);
+  strlcpy( content_type, (const char *) buf->data + 14, end_of_ct - 14 + 2);
+  content_type[end_of_ct-14+1] = '\0';
+
+  /* -------------------------------------------------------------------- */
+  /*      Move data to front of buffer, and reset length.                 */
+  /* -------------------------------------------------------------------- */
+  memmove( buf->data, buf->data+start_of_data,
+           buf->data_offset - start_of_data );
+  buf->data[buf->data_offset - start_of_data] = '\0';
+  buf->data_offset -= start_of_data;
+
+  return content_type;
 }
 
 /************************************************************************/
@@ -941,80 +834,77 @@ char *msIO_stripStdoutBufferContentType()
 
 void msIO_stripStdoutBufferContentHeaders()
 {
-/* -------------------------------------------------------------------- */
-/*      Find stdout buffer.                                             */
-/* -------------------------------------------------------------------- */
-    msIOContext *ctx = msIO_getHandler( (FILE *) "stdout" );
-    msIOBuffer  *buf;
-    int start_of_data;
-
-    if( ctx == NULL || ctx->write_channel == MS_FALSE
-        || strcmp(ctx->label,"buffer") != 0 )
-    {
+  /* -------------------------------------------------------------------- */
+  /*      Find stdout buffer.                                             */
+  /* -------------------------------------------------------------------- */
+  msIOContext *ctx = msIO_getHandler( (FILE *) "stdout" );
+  msIOBuffer  *buf;
+  int start_of_data;
+
+  if( ctx == NULL || ctx->write_channel == MS_FALSE
+      || strcmp(ctx->label,"buffer") != 0 ) {
     msSetError( MS_MISCERR, "Can't identify msIO buffer.",
-                    "msIO_stripStdoutBufferContentHeaders" );
+                "msIO_stripStdoutBufferContentHeaders" );
     return;
-    }
+  }
 
-    buf = (msIOBuffer *) ctx->cbData;
-
-/* -------------------------------------------------------------------- */
-/*      Exit if we don't have any content-* header.                     */
-/* -------------------------------------------------------------------- */
-    if( buf->data_offset < 8 
-        || strncasecmp((const char*) buf->data,"Content-",8) != 0 )
-        return;
-
-/* -------------------------------------------------------------------- */
-/*      Loop over all content-* headers.                                */
-/* -------------------------------------------------------------------- */
-    start_of_data = 0;
-    while( buf->data_offset > start_of_data
-        && strncasecmp((const char*) buf->data+start_of_data,"Content-",8) == 0 )
-    {
-/* -------------------------------------------------------------------- */
-/*      Find newline marker at end of content-* header argument.        */
-/* -------------------------------------------------------------------- */
-        start_of_data +=7;
-        while( start_of_data+1 < buf->data_offset 
-               && buf->data[start_of_data+1] != 10 )
-            start_of_data++;
-
-        if( start_of_data+1 == buf->data_offset )
-        {
-        msSetError( MS_MISCERR, "Corrupt Content-* header.",
-                        "msIO_stripStdoutBufferContentHeaders" );
-        return;
-        }
-        start_of_data +=2;
-    }
+  buf = (msIOBuffer *) ctx->cbData;
 
-/* -------------------------------------------------------------------- */
-/*      Continue on to the start of data ... skipping two newline       */
-/*      markers.                                                        */
-/* -------------------------------------------------------------------- */
-    while( start_of_data  < buf->data_offset 
-           && buf->data[start_of_data] != 10 )
-        start_of_data++;
+  /* -------------------------------------------------------------------- */
+  /*      Exit if we don't have any content-* header.                     */
+  /* -------------------------------------------------------------------- */
+  if( buf->data_offset < 8
+      || strncasecmp((const char*) buf->data,"Content-",8) != 0 )
+    return;
 
-    if( start_of_data == buf->data_offset )
-    {
+  /* -------------------------------------------------------------------- */
+  /*      Loop over all content-* headers.                                */
+  /* -------------------------------------------------------------------- */
+  start_of_data = 0;
+  while( buf->data_offset > start_of_data
+         && strncasecmp((const char*) buf->data+start_of_data,"Content-",8) == 0 ) {
+    /* -------------------------------------------------------------------- */
+    /*      Find newline marker at end of content-* header argument.        */
+    /* -------------------------------------------------------------------- */
+    start_of_data +=7;
+    while( start_of_data+1 < buf->data_offset
+           && buf->data[start_of_data+1] != '\r' )
+      start_of_data++;
+
+    if( start_of_data+1 == buf->data_offset ) {
+      msSetError( MS_MISCERR, "Corrupt Content-* header.",
+                  "msIO_stripStdoutBufferContentHeaders" );
+      return;
+    }
+    /* -------------------------------------------------------------------- */
+    /*      Go to next line.                                                */
+    /* -------------------------------------------------------------------- */
+    start_of_data +=3;
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Continue on to the start of data ...                            */
+  /*      Skip next line if empty.                                        */
+  /* -------------------------------------------------------------------- */
+  if( start_of_data  < buf->data_offset
+      && buf->data[start_of_data] == '\r' )
+    start_of_data +=2;
+
+  if( start_of_data == buf->data_offset ) {
     msSetError( MS_MISCERR, "Corrupt Content-* header.",
-                    "msIO_stripStdoutBufferContentHeaders" );
+                "msIO_stripStdoutBufferContentHeaders" );
     return;
-    }
-
-    start_of_data++;
+  }
 
-/* -------------------------------------------------------------------- */
-/*      Move data to front of buffer, and reset length.                 */
-/* -------------------------------------------------------------------- */
-    memmove( buf->data, buf->data+start_of_data,
-             buf->data_offset - start_of_data );
-    buf->data[buf->data_offset - start_of_data] = '\0';
-    buf->data_offset -= start_of_data;
+  /* -------------------------------------------------------------------- */
+  /*      Move data to front of buffer, and reset length.                 */
+  /* -------------------------------------------------------------------- */
+  memmove( buf->data, buf->data+start_of_data,
+           buf->data_offset - start_of_data );
+  buf->data[buf->data_offset - start_of_data] = '\0';
+  buf->data_offset -= start_of_data;
 
-    return;
+  return;
 }
 
 /************************************************************************/
@@ -1024,37 +914,35 @@ void msIO_stripStdoutBufferContentHeaders()
 int msIO_bufferWrite( void *cbData, void *data, int byteCount )
 
 {
-    msIOBuffer *buf = (msIOBuffer *) cbData;
-
-    /*
-    ** Grow buffer if needed.
-    */
-    if( buf->data_offset + byteCount > buf->data_len )
-    {
-        buf->data_len = buf->data_len * 2 + byteCount + 100;
-        if( buf->data == NULL )
-            buf->data = (unsigned char *) malloc(buf->data_len);
-        else
-            buf->data = (unsigned char *) realloc(buf->data, buf->data_len);
-
-        if( buf->data == NULL )
-        {
-            msSetError( MS_MEMERR, 
-                        "Failed to allocate %d bytes for capture buffer.",
-                        "msIO_bufferWrite()", buf->data_len );
-            buf->data_len = 0;
-            return 0;
-        }
+  msIOBuffer *buf = (msIOBuffer *) cbData;
+
+  /*
+  ** Grow buffer if needed.
+  */
+  if( buf->data_offset + byteCount > buf->data_len ) {
+    buf->data_len = buf->data_len * 2 + byteCount + 100;
+    if( buf->data == NULL )
+      buf->data = (unsigned char *) malloc(buf->data_len);
+    else
+      buf->data = (unsigned char *) realloc(buf->data, buf->data_len);
+
+    if( buf->data == NULL ) {
+      msSetError( MS_MEMERR,
+                  "Failed to allocate %d bytes for capture buffer.",
+                  "msIO_bufferWrite()", buf->data_len );
+      buf->data_len = 0;
+      return 0;
     }
+  }
 
-    /*
-    ** Copy result into buffer.
-    */
+  /*
+  ** Copy result into buffer.
+  */
 
-    memcpy( buf->data + buf->data_offset, data, byteCount );
-    buf->data_offset += byteCount;
+  memcpy( buf->data + buf->data_offset, data, byteCount );
+  buf->data_offset += byteCount;
 
-    return byteCount;
+  return byteCount;
 }
 
 /************************************************************************/
@@ -1064,9 +952,9 @@ int msIO_bufferWrite( void *cbData, void *data, int byteCount )
 int msIO_bufferRead( void *cbData, void *data, int byteCount )
 
 {
-/*    msIOBuffer *buf = (msIOBuffer *) cbData; */
+  /*    msIOBuffer *buf = (msIOBuffer *) cbData; */
 
-    /* not implemented yet. */
+  /* not implemented yet. */
 
-    return 0;
+  return 0;
 }
diff --git a/mapio.h b/mapio.h
index 84b5080..0a559ee 100644
--- a/mapio.h
+++ b/mapio.h
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -30,97 +30,81 @@
 #ifndef MAPIO_H
 #define MAPIO_H
 
-#define USE_MAPIO
-
-#if defined(USE_FASTCGI) && !defined(USE_MAPIO)
-#define USE_MAPIO
-#endif
-
-
 /*
-** We deliberately emulate stdio functions in the msIO cover functions. 
+** We deliberately emulate stdio functions in the msIO cover functions.
 ** This makes it easy for folks to understand the semantics, and means we
-** can just #define things to use stdio in the simplest case. 
+** can just #define things to use stdio in the simplest case.
 */
 
-#ifdef USE_MAPIO
-
 #include <stdarg.h>
 
 #ifdef __cplusplus
 extern "C" {
 #endif
 
-/* stdio analogs */
-int MS_DLL_EXPORT msIO_printf( const char *format, ... );
-int MS_DLL_EXPORT msIO_fprintf( FILE *stream, const char *format, ... );
-int MS_DLL_EXPORT msIO_fwrite( const void *ptr, size_t size, size_t nmemb, FILE *stream );
-int MS_DLL_EXPORT msIO_fread( void *ptr, size_t size, size_t nmemb, FILE *stream );
-int MS_DLL_EXPORT msIO_vfprintf( FILE *fp, const char *format, va_list ap );
-
-#else
-
-#define msIO_printf   printf
-#define msIO_fprintf  fprintf
-#define msIO_fwrite   fwrite
-#define msIO_fread    fread
-#define msIO_vfprintf vfprintf
+  /* stdio analogs */
+  int MS_DLL_EXPORT msIO_printf( const char *format, ... );
+  int MS_DLL_EXPORT msIO_fprintf( FILE *stream, const char *format, ... );
+  int MS_DLL_EXPORT msIO_fwrite( const void *ptr, size_t size, size_t nmemb, FILE *stream );
+  int MS_DLL_EXPORT msIO_fread( void *ptr, size_t size, size_t nmemb, FILE *stream );
+  int MS_DLL_EXPORT msIO_vfprintf( FILE *fp, const char *format, va_list ap );
 
+#ifdef USE_GD
+  gdIOCtx MS_DLL_EXPORT *msIO_getGDIOCtx( FILE *fp );
 #endif
 
-int MS_DLL_EXPORT msIO_installFastCGIRedirect( void );
-gdIOCtx MS_DLL_EXPORT *msIO_getGDIOCtx( FILE *fp );
-
-/*
-** Definitions for the callback function and the details of the IO
-** channel contexts.
-*/
+  /*
+  ** Definitions for the callback function and the details of the IO
+  ** channel contexts.
+  */
 
-typedef int (*msIO_llReadWriteFunc)( void *cbData, void *data, int byteCount );
+  typedef int (*msIO_llReadWriteFunc)( void *cbData, void *data, int byteCount );
 
-typedef struct msIOContext_t {
+  typedef struct msIOContext_t {
     const char           *label;
     int                   write_channel; /* 1 for stdout/stderr, 0 for stdin */
     msIO_llReadWriteFunc  readWriteFunc;
     void                  *cbData;
-} msIOContext;
-
-int MS_DLL_EXPORT msIO_installHandlers( msIOContext *stdin_context,
-                                        msIOContext *stdout_context,
-                                        msIOContext *stderr_context );
-msIOContext MS_DLL_EXPORT *msIO_getHandler( FILE * );
-
-/*
-** These can be used instead of the stdio style functions if you have
-** msIOContext's for the channel in question.
-*/
-int msIO_contextRead( msIOContext *context, void *data, int byteCount );
-int msIO_contextWrite( msIOContext *context, const void *data, int byteCount );
-
-/*
-** For redirecting IO to a memory buffer. 
-*/
-
-typedef struct {
+  } msIOContext;
+
+  int MS_DLL_EXPORT msIO_installHandlers( msIOContext *stdin_context,
+                                          msIOContext *stdout_context,
+                                          msIOContext *stderr_context );
+  msIOContext MS_DLL_EXPORT *msIO_getHandler( FILE * );
+  void msIO_setHeader (const char *header, const char* value, ...);
+  void msIO_sendHeaders(void);
+
+  /*
+  ** These can be used instead of the stdio style functions if you have
+  ** msIOContext's for the channel in question.
+  */
+  int msIO_contextRead( msIOContext *context, void *data, int byteCount );
+  int msIO_contextWrite( msIOContext *context, const void *data, int byteCount );
+
+  /*
+  ** For redirecting IO to a memory buffer.
+  */
+
+  typedef struct {
     unsigned char *data;
     int            data_len;    /* really buffer length */
     int            data_offset; /* really buffer used */
-} msIOBuffer;
+  } msIOBuffer;
 
-int MS_DLL_EXPORT msIO_bufferRead( void *, void *, int );
-int MS_DLL_EXPORT msIO_bufferWrite( void *, void *, int );
+  int MS_DLL_EXPORT msIO_bufferRead( void *, void *, int );
+  int MS_DLL_EXPORT msIO_bufferWrite( void *, void *, int );
 
-void MS_DLL_EXPORT msIO_resetHandlers(void);
-void MS_DLL_EXPORT msIO_installStdoutToBuffer(void);
-void MS_DLL_EXPORT msIO_installStdinFromBuffer(void);
-void MS_DLL_EXPORT msIO_Cleanup(void);
-char MS_DLL_EXPORT *msIO_stripStdoutBufferContentType(void);
-void MS_DLL_EXPORT msIO_stripStdoutBufferContentHeaders(void);
+  void MS_DLL_EXPORT msIO_resetHandlers(void);
+  void MS_DLL_EXPORT msIO_installStdoutToBuffer(void);
+  void MS_DLL_EXPORT msIO_installStdinFromBuffer(void);
+  void MS_DLL_EXPORT msIO_Cleanup(void);
+  char MS_DLL_EXPORT *msIO_stripStdoutBufferContentType(void);
+  void MS_DLL_EXPORT msIO_stripStdoutBufferContentHeaders(void);
 
-/* this is just for setting normal stdout's to binary mode on windows */
+  /* this is just for setting normal stdout's to binary mode on windows */
 
-int msIO_needBinaryStdout( void );
-int msIO_needBinaryStdin( void );
+  int msIO_needBinaryStdout( void );
+  int msIO_needBinaryStdin( void );
 
 #ifdef __cplusplus
 }
diff --git a/mapjoin.c b/mapjoin.c
index 828530c..8632d32 100644
--- a/mapjoin.c
+++ b/mapjoin.c
@@ -2,7 +2,7 @@
  * $Id$
  *
  * Project:  MapServer
- * Purpose:  Implements MapServer joins. 
+ * Purpose:  Implements MapServer joins.
  * Author:   Steve Lime and the MapServer team.
  *
  ******************************************************************************
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -29,7 +29,7 @@
 
 #include "mapserver.h"
 
-MS_CVSID("$Id$")
+
 
 #define ROW_ALLOCATION_SIZE 10
 
@@ -62,92 +62,92 @@ int msPOSTGRESQLJoinNext(joinObj *join);
 int msPOSTGRESQLJoinClose(joinObj *join);
 
 /* wrapper function for DB specific join functions */
-int msJoinConnect(layerObj *layer, joinObj *join) 
+int msJoinConnect(layerObj *layer, joinObj *join)
 {
   switch(join->connectiontype) {
-  case(MS_DB_XBASE):
-    return msDBFJoinConnect(layer, join);
-    break;
-  case(MS_DB_CSV):
-    return msCSVJoinConnect(layer, join);
-    break;
-  case(MS_DB_MYSQL):
-    return msMySQLJoinConnect(layer, join);
-    break;
-  case(MS_DB_POSTGRES):
-    return msPOSTGRESQLJoinConnect(layer, join);
-    break;
-  default:
-    break;
+    case(MS_DB_XBASE):
+      return msDBFJoinConnect(layer, join);
+      break;
+    case(MS_DB_CSV):
+      return msCSVJoinConnect(layer, join);
+      break;
+    case(MS_DB_MYSQL):
+      return msMySQLJoinConnect(layer, join);
+      break;
+    case(MS_DB_POSTGRES):
+      return msPOSTGRESQLJoinConnect(layer, join);
+      break;
+    default:
+      break;
   }
 
   msSetError(MS_JOINERR, "Unsupported join connection type.", "msJoinConnect()");
   return MS_FAILURE;
 }
 
-int msJoinPrepare(joinObj *join, shapeObj *shape) 
+int msJoinPrepare(joinObj *join, shapeObj *shape)
 {
   switch(join->connectiontype) {
-  case(MS_DB_XBASE):
-    return msDBFJoinPrepare(join, shape);
-    break;
-  case(MS_DB_CSV):
-    return msCSVJoinPrepare(join, shape);
-    break;
-  case(MS_DB_MYSQL):
-    return msMySQLJoinPrepare(join, shape);
-    break;
-  case(MS_DB_POSTGRES):
-    return msPOSTGRESQLJoinPrepare(join, shape);
-    break;
-  default:
-    break;
+    case(MS_DB_XBASE):
+      return msDBFJoinPrepare(join, shape);
+      break;
+    case(MS_DB_CSV):
+      return msCSVJoinPrepare(join, shape);
+      break;
+    case(MS_DB_MYSQL):
+      return msMySQLJoinPrepare(join, shape);
+      break;
+    case(MS_DB_POSTGRES):
+      return msPOSTGRESQLJoinPrepare(join, shape);
+      break;
+    default:
+      break;
   }
 
   msSetError(MS_JOINERR, "Unsupported join connection type.", "msJoinPrepare()");
   return MS_FAILURE;
 }
 
-int msJoinNext(joinObj *join) 
+int msJoinNext(joinObj *join)
 {
   switch(join->connectiontype) {
-  case(MS_DB_XBASE):
-    return msDBFJoinNext(join);
-    break;
-  case(MS_DB_CSV):
-    return msCSVJoinNext(join);
-    break;
-  case(MS_DB_MYSQL):
-    return msMySQLJoinNext(join);
-    break;
-  case(MS_DB_POSTGRES):
-    return msPOSTGRESQLJoinNext(join);
-    break;
-  default:
-    break;
+    case(MS_DB_XBASE):
+      return msDBFJoinNext(join);
+      break;
+    case(MS_DB_CSV):
+      return msCSVJoinNext(join);
+      break;
+    case(MS_DB_MYSQL):
+      return msMySQLJoinNext(join);
+      break;
+    case(MS_DB_POSTGRES):
+      return msPOSTGRESQLJoinNext(join);
+      break;
+    default:
+      break;
   }
 
   msSetError(MS_JOINERR, "Unsupported join connection type.", "msJoinNext()");
   return MS_FAILURE;
 }
 
-int msJoinClose(joinObj *join) 
+int msJoinClose(joinObj *join)
 {
   switch(join->connectiontype) {
-  case(MS_DB_XBASE):
-    return msDBFJoinClose(join);
-    break;
-  case(MS_DB_CSV):
-    return msCSVJoinClose(join);
-    break;
-  case(MS_DB_MYSQL):
-    return msMySQLJoinClose(join);
-    break;
-  case(MS_DB_POSTGRES):
-    return msPOSTGRESQLJoinClose(join);
-    break;
-  default:
-    break;
+    case(MS_DB_XBASE):
+      return msDBFJoinClose(join);
+      break;
+    case(MS_DB_CSV):
+      return msCSVJoinClose(join);
+      break;
+    case(MS_DB_MYSQL):
+      return msMySQLJoinClose(join);
+      break;
+    case(MS_DB_POSTGRES):
+      return msPOSTGRESQLJoinClose(join);
+      break;
+    default:
+      break;
   }
 
   msSetError(MS_JOINERR, "Unsupported join connection type.", "msJoinClose()");
@@ -164,18 +164,18 @@ typedef struct {
   int nextrecord;
 } msDBFJoinInfo;
 
-int msDBFJoinConnect(layerObj *layer, joinObj *join) 
+int msDBFJoinConnect(layerObj *layer, joinObj *join)
 {
   int i;
   char szPath[MS_MAXPATHLEN];
   msDBFJoinInfo *joininfo;
 
   if(join->joininfo) return(MS_SUCCESS); /* already open */
-  
+
   if ( msCheckParentPointer(layer->map,"map")==MS_FAILURE )
-	return MS_FAILURE;
-  
-    
+    return MS_FAILURE;
+
+
   /* allocate a msDBFJoinInfo struct */
   joininfo = (msDBFJoinInfo *) malloc(sizeof(msDBFJoinInfo));
   if(!joininfo) {
@@ -191,15 +191,15 @@ int msDBFJoinConnect(layerObj *layer, joinObj *join)
 
   /* open the XBase file */
   if((joininfo->hDBF = msDBFOpen( msBuildPath3(szPath, layer->map->mappath, layer->map->shapepath, join->table), "rb" )) == NULL) {
-    if((joininfo->hDBF = msDBFOpen( msBuildPath(szPath, layer->map->mappath, join->table), "rb" )) == NULL) {     
-      msSetError(MS_IOERR, "(%s)", "msDBFJoinConnect()", join->table);   
+    if((joininfo->hDBF = msDBFOpen( msBuildPath(szPath, layer->map->mappath, join->table), "rb" )) == NULL) {
+      msSetError(MS_IOERR, "(%s)", "msDBFJoinConnect()", join->table);
       return(MS_FAILURE);
     }
   }
 
   /* get "to" item index */
-  if((joininfo->toindex = msDBFGetItemIndex(joininfo->hDBF, join->to)) == -1) { 
-    msSetError(MS_DBFERR, "Item %s not found in table %s.", "msDBFJoinConnect()", join->to, join->table); 
+  if((joininfo->toindex = msDBFGetItemIndex(joininfo->hDBF, join->to)) == -1) {
+    msSetError(MS_DBFERR, "Item %s not found in table %s.", "msDBFJoinConnect()", join->to, join->table);
     return(MS_FAILURE);
   }
 
@@ -212,34 +212,34 @@ int msDBFJoinConnect(layerObj *layer, joinObj *join)
   }
 
   if(i == layer->numitems) {
-    msSetError(MS_JOINERR, "Item %s not found in layer %s.", "msDBFJoinConnect()", join->from, layer->name); 
+    msSetError(MS_JOINERR, "Item %s not found in layer %s.", "msDBFJoinConnect()", join->from, layer->name);
     return(MS_FAILURE);
   }
 
   /* finally store away the item names in the XBase table */
   join->numitems =  msDBFGetFieldCount(joininfo->hDBF);
   join->items = msDBFGetItems(joininfo->hDBF);
-  if(!join->items) return(MS_FAILURE);  
+  if(!join->items) return(MS_FAILURE);
 
   return(MS_SUCCESS);
 }
 
-int msDBFJoinPrepare(joinObj *join, shapeObj *shape) 
+int msDBFJoinPrepare(joinObj *join, shapeObj *shape)
 {
-  msDBFJoinInfo *joininfo = join->joininfo;  
+  msDBFJoinInfo *joininfo = join->joininfo;
 
   if(!joininfo) {
-    msSetError(MS_JOINERR, "Join connection has not be created.", "msDBFJoinPrepare()"); 
+    msSetError(MS_JOINERR, "Join connection has not be created.", "msDBFJoinPrepare()");
     return(MS_FAILURE);
   }
 
   if(!shape) {
-    msSetError(MS_JOINERR, "Shape to be joined is empty.", "msDBFJoinPrepare()"); 
+    msSetError(MS_JOINERR, "Shape to be joined is empty.", "msDBFJoinPrepare()");
     return(MS_FAILURE);
   }
 
   if(!shape->values) {
-    msSetError(MS_JOINERR, "Shape to be joined has no attributes.", "msDBFJoinPrepare()"); 
+    msSetError(MS_JOINERR, "Shape to be joined has no attributes.", "msDBFJoinPrepare()");
     return(MS_FAILURE);
   }
 
@@ -251,13 +251,13 @@ int msDBFJoinPrepare(joinObj *join, shapeObj *shape)
   return(MS_SUCCESS);
 }
 
-int msDBFJoinNext(joinObj *join) 
+int msDBFJoinNext(joinObj *join)
 {
   int i, n;
   msDBFJoinInfo *joininfo = join->joininfo;
 
   if(!joininfo) {
-    msSetError(MS_JOINERR, "Join connection has not be created.", "msDBFJoinNext()"); 
+    msSetError(MS_JOINERR, "Join connection has not be created.", "msDBFJoinNext()");
     return(MS_FAILURE);
   }
 
@@ -267,17 +267,17 @@ int msDBFJoinNext(joinObj *join)
   }
 
   /* clear any old data */
-  if(join->values) { 
+  if(join->values) {
     msFreeCharArray(join->values, join->numitems);
     join->values = NULL;
   }
 
   n = msDBFGetRecordCount(joininfo->hDBF);
-    
+
   for(i=joininfo->nextrecord; i<n; i++) { /* find a match */
     if(strcmp(joininfo->target, msDBFReadStringAttribute(joininfo->hDBF, i, joininfo->toindex)) == 0) break;
-  }  
-    
+  }
+
   if(i == n) { /* unable to do the join */
     if((join->values = (char **)malloc(sizeof(char *)*join->numitems)) == NULL) {
       msSetError(MS_MEMERR, NULL, "msDBFJoinNext()");
@@ -289,8 +289,8 @@ int msDBFJoinNext(joinObj *join)
     joininfo->nextrecord = n;
     return(MS_DONE);
   }
-    
-  if((join->values = msDBFGetValues(joininfo->hDBF,i)) == NULL) 
+
+  if((join->values = msDBFGetValues(joininfo->hDBF,i)) == NULL)
     return(MS_FAILURE);
 
   joininfo->nextrecord = i+1; /* so we know where to start looking next time through */
@@ -298,7 +298,7 @@ int msDBFJoinNext(joinObj *join)
   return(MS_SUCCESS);
 }
 
-int msDBFJoinClose(joinObj *join) 
+int msDBFJoinClose(joinObj *join)
 {
   msDBFJoinInfo *joininfo = join->joininfo;
 
@@ -323,7 +323,7 @@ typedef struct {
   int nextrow;
 } msCSVJoinInfo;
 
-int msCSVJoinConnect(layerObj *layer, joinObj *join) 
+int msCSVJoinConnect(layerObj *layer, joinObj *join)
 {
   int i;
   FILE *stream;
@@ -333,9 +333,9 @@ int msCSVJoinConnect(layerObj *layer, joinObj *join)
 
   if(join->joininfo) return(MS_SUCCESS); /* already open */
   if ( msCheckParentPointer(layer->map,"map")==MS_FAILURE )
-	return MS_FAILURE;
-  
-    
+    return MS_FAILURE;
+
+
   /* allocate a msCSVJoinInfo struct */
   if((joininfo = (msCSVJoinInfo *) malloc(sizeof(msCSVJoinInfo))) == NULL) {
     msSetError(MS_MEMERR, "Error allocating CSV table info structure.", "msCSVJoinConnect()");
@@ -350,12 +350,12 @@ int msCSVJoinConnect(layerObj *layer, joinObj *join)
 
   /* open the CSV file */
   if((stream = fopen( msBuildPath3(szPath, layer->map->mappath, layer->map->shapepath, join->table), "r" )) == NULL) {
-    if((stream = fopen( msBuildPath(szPath, layer->map->mappath, join->table), "r" )) == NULL) {     
-      msSetError(MS_IOERR, "(%s)", "msCSVJoinConnect()", join->table);   
+    if((stream = fopen( msBuildPath(szPath, layer->map->mappath, join->table), "r" )) == NULL) {
+      msSetError(MS_IOERR, "(%s)", "msCSVJoinConnect()", join->table);
       return(MS_FAILURE);
     }
   }
-  
+
   /* once through to get the number of rows */
   joininfo->numrows = 0;
   while(fgets(buffer, MS_BUFFER_LENGTH, stream) != NULL) joininfo->numrows++;
@@ -368,8 +368,8 @@ int msCSVJoinConnect(layerObj *layer, joinObj *join)
 
   /* load the rows */
   i = 0;
-  while(fgets(buffer, MS_BUFFER_LENGTH, stream) != NULL) {  
-    msStringTrimEOL(buffer);  
+  while(fgets(buffer, MS_BUFFER_LENGTH, stream) != NULL) {
+    msStringTrimEOL(buffer);
     joininfo->rows[i] = msStringSplitComplex(buffer, ",", &(join->numitems), MS_ALLOWEMPTYTOKENS);
     i++;
   }
@@ -384,14 +384,14 @@ int msCSVJoinConnect(layerObj *layer, joinObj *join)
   }
 
   if(i == layer->numitems) {
-    msSetError(MS_JOINERR, "Item %s not found in layer %s.", "msCSVJoinConnect()", join->from, layer->name); 
+    msSetError(MS_JOINERR, "Item %s not found in layer %s.", "msCSVJoinConnect()", join->from, layer->name);
     return(MS_FAILURE);
   }
 
   /* get "to" index (for now the user tells us which column, 1..n) */
   joininfo->toindex = atoi(join->to) - 1;
   if(joininfo->toindex < 0 || joininfo->toindex > join->numitems) {
-    msSetError(MS_JOINERR, "Invalid column index %s.", "msCSVJoinConnect()", join->to); 
+    msSetError(MS_JOINERR, "Invalid column index %s.", "msCSVJoinConnect()", join->to);
     return(MS_FAILURE);
   }
 
@@ -408,22 +408,22 @@ int msCSVJoinConnect(layerObj *layer, joinObj *join)
   return(MS_SUCCESS);
 }
 
-int msCSVJoinPrepare(joinObj *join, shapeObj *shape) 
+int msCSVJoinPrepare(joinObj *join, shapeObj *shape)
 {
   msCSVJoinInfo *joininfo = join->joininfo;
 
   if(!joininfo) {
-    msSetError(MS_JOINERR, "Join connection has not be created.", "msCSVJoinPrepare()"); 
+    msSetError(MS_JOINERR, "Join connection has not be created.", "msCSVJoinPrepare()");
     return(MS_FAILURE);
   }
 
   if(!shape) {
-    msSetError(MS_JOINERR, "Shape to be joined is empty.", "msCSVJoinPrepare()"); 
+    msSetError(MS_JOINERR, "Shape to be joined is empty.", "msCSVJoinPrepare()");
     return(MS_FAILURE);
   }
 
   if(!shape->values) {
-    msSetError(MS_JOINERR, "Shape to be joined has no attributes.", "msCSVJoinPrepare()"); 
+    msSetError(MS_JOINERR, "Shape to be joined has no attributes.", "msCSVJoinPrepare()");
     return(MS_FAILURE);
   }
 
@@ -435,38 +435,38 @@ int msCSVJoinPrepare(joinObj *join, shapeObj *shape)
   return(MS_SUCCESS);
 }
 
-int msCSVJoinNext(joinObj *join) 
+int msCSVJoinNext(joinObj *join)
 {
   int i,j;
   msCSVJoinInfo *joininfo = join->joininfo;
 
   if(!joininfo) {
-    msSetError(MS_JOINERR, "Join connection has not be created.", "msCSVJoinNext()"); 
+    msSetError(MS_JOINERR, "Join connection has not be created.", "msCSVJoinNext()");
     return(MS_FAILURE);
   }
 
   /* clear any old data */
-  if(join->values) { 
+  if(join->values) {
     msFreeCharArray(join->values, join->numitems);
     join->values = NULL;
   }
 
   for(i=joininfo->nextrow; i<joininfo->numrows; i++) { /* find a match     */
     if(strcmp(joininfo->target, joininfo->rows[i][joininfo->toindex]) == 0) break;
-  }  
+  }
 
   if((join->values = (char ** )malloc(sizeof(char *)*join->numitems)) == NULL) {
     msSetError(MS_MEMERR, NULL, "msCSVJoinNext()");
     return(MS_FAILURE);
   }
-  
+
   if(i == joininfo->numrows) { /* unable to do the join     */
     for(j=0; j<join->numitems; j++)
       join->values[j] = msStrdup("\0"); /* intialize to zero length strings */
 
     joininfo->nextrow = joininfo->numrows;
     return(MS_DONE);
-  } 
+  }
 
   for(j=0; j<join->numitems; j++)
     join->values[j] = msStrdup(joininfo->rows[i][j]);
@@ -476,8 +476,8 @@ int msCSVJoinNext(joinObj *join)
   return(MS_SUCCESS);
 }
 
-int msCSVJoinClose(joinObj *join) 
-{ 
+int msCSVJoinClose(joinObj *join)
+{
   int i;
   msCSVJoinInfo *joininfo = join->joininfo;
 
@@ -510,18 +510,18 @@ char* delim;
 
 MYSQL_RES *msMySQLQuery(char *q, MYSQL *conn)
 {
-		MYSQL_RES *qresult=NULL;
-    if (mysql_query(conn,q) < 0){
-      mysql_close(conn);
-      msSetError(MS_QUERYERR, "Bad mysql query (%s)", "msMySQLQuery()", q);
-      return qresult;
-    }
-    if (!(qresult=mysql_store_result(conn)))    {
-      mysql_close(conn);
-      msSetError(MS_QUERYERR, "mysql query failed (%s)", "msMySQLQuery()", q);
-      return qresult;
-    }
+  MYSQL_RES *qresult=NULL;
+  if (mysql_query(conn,q) < 0) {
+    mysql_close(conn);
+    msSetError(MS_QUERYERR, "Bad mysql query (%s)", "msMySQLQuery()", q);
+    return qresult;
+  }
+  if (!(qresult=mysql_store_result(conn)))    {
+    mysql_close(conn);
+    msSetError(MS_QUERYERR, "mysql query failed (%s)", "msMySQLQuery()", q);
     return qresult;
+  }
+  return qresult;
 }
 
 /*  */
@@ -529,20 +529,20 @@ MYSQL_RES *msMySQLQuery(char *q, MYSQL *conn)
 /*  */
 typedef struct {
   MYSQL mysql, *conn;
-	MYSQL_RES *qresult;
-	MYSQL_ROW row;
-	int rows;
+  MYSQL_RES *qresult;
+  MYSQL_ROW row;
+  int rows;
   int fromindex;
-	char *tocolumn;
+  char *tocolumn;
   char *target;
   int nextrecord;
 } msMySQLJoinInfo;
 #endif
 
 
-int msMySQLJoinConnect(layerObj *layer, joinObj *join) 
+int msMySQLJoinConnect(layerObj *layer, joinObj *join)
 {
-   
+
 #ifndef USE_MYSQL
   msSetError(MS_QUERYERR, "MySQL support not available (compile with --with-mysql)", "msMySQLJoinConnect()");
   return(MS_FAILURE);
@@ -552,9 +552,11 @@ int msMySQLJoinConnect(layerObj *layer, joinObj *join)
   char *conn_decrypted;
   msMySQLJoinInfo *joininfo;
 
-  MYDEBUG if (setvbuf(stdout, NULL, _IONBF , 0)){printf("Whoops...");};
+  MYDEBUG if (setvbuf(stdout, NULL, _IONBF , 0)) {
+    printf("Whoops...");
+  };
   if(join->joininfo) return(MS_SUCCESS); /* already open */
-    
+
   /* allocate a msMySQLJoinInfo struct */
   joininfo = (msMySQLJoinInfo *) malloc(sizeof(msMySQLJoinInfo));
   if(!joininfo) {
@@ -572,98 +574,91 @@ int msMySQLJoinConnect(layerObj *layer, joinObj *join)
   /* open the mysql connection */
 
   if( join->connection == NULL ) {
-      msSetError(MS_QUERYERR, "Error parsing MYSQL JOIN: nothing specified in CONNECTION statement.",
-      "msMySQLJoinConnect()");
+    msSetError(MS_QUERYERR, "Error parsing MYSQL JOIN: nothing specified in CONNECTION statement.",
+               "msMySQLJoinConnect()");
 
-        return(MS_FAILURE);
-    }
-  
-    conn_decrypted = msDecryptStringTokens(layer->map, join->connection);
-    if (conn_decrypted == NULL) {
-      msSetError(MS_QUERYERR, "Error parsing MYSQL JOIN: unable to decrypt CONNECTION statement.",
-                 "msMySQLJoinConnect()");
-      return(MS_FAILURE);
-    }
-  
-    delim = msStrdup(":");
-    DB_HOST = msStrdup(strtok(conn_decrypted, delim));
-    DB_USER = msStrdup(strtok(NULL, delim));
-    DB_PASSWD = msStrdup(strtok(NULL, delim));
-    DB_DATABASE = msStrdup(strtok(NULL, delim));
-    free(conn_decrypted);
-
-    if (DB_HOST == NULL || DB_USER == NULL || DB_PASSWD == NULL || DB_DATABASE == NULL)
-    {
-      msSetError(MS_QUERYERR, "DB param error: at least one of HOST, USER, PASSWD or DATABASE is null!", "msMySQLJoinConnect()");
-      return MS_FAILURE;
-    }
-    if (strcmp(DB_PASSWD, "none") == 0) strcpy(DB_PASSWD, "");
+    return(MS_FAILURE);
+  }
+
+  conn_decrypted = msDecryptStringTokens(layer->map, join->connection);
+  if (conn_decrypted == NULL) {
+    msSetError(MS_QUERYERR, "Error parsing MYSQL JOIN: unable to decrypt CONNECTION statement.",
+               "msMySQLJoinConnect()");
+    return(MS_FAILURE);
+  }
+
+  delim = msStrdup(":");
+  DB_HOST = msStrdup(strtok(conn_decrypted, delim));
+  DB_USER = msStrdup(strtok(NULL, delim));
+  DB_PASSWD = msStrdup(strtok(NULL, delim));
+  DB_DATABASE = msStrdup(strtok(NULL, delim));
+  free(conn_decrypted);
+
+  if (DB_HOST == NULL || DB_USER == NULL || DB_PASSWD == NULL || DB_DATABASE == NULL) {
+    msSetError(MS_QUERYERR, "DB param error: at least one of HOST, USER, PASSWD or DATABASE is null!", "msMySQLJoinConnect()");
+    return MS_FAILURE;
+  }
+  if (strcmp(DB_PASSWD, "none") == 0) strcpy(DB_PASSWD, "");
 
 #if MYSQL_VERSION_ID >= 40000
-    mysql_init(&(joininfo->mysql));
-    if (!(joininfo->conn = mysql_real_connect(&(joininfo->mysql),DB_HOST,DB_USER,DB_PASSWD,NULL, 0, NULL, 0)))
+  mysql_init(&(joininfo->mysql));
+  if (!(joininfo->conn = mysql_real_connect(&(joininfo->mysql),DB_HOST,DB_USER,DB_PASSWD,NULL, 0, NULL, 0)))
 #else
-    if (!(joininfo->conn = mysql_connect(&(joininfo->mysql),DB_HOST,DB_USER,DB_PASSWD)))
+  if (!(joininfo->conn = mysql_connect(&(joininfo->mysql),DB_HOST,DB_USER,DB_PASSWD)))
 #endif
-    {
-        char tmp[4000];
-        snprintf( tmp, sizeof(tmp), "Failed to connect to SQL server: Error: %s\nHost: %s\nUsername:%s\nPassword:%s\n", mysql_error(joininfo->conn), DB_HOST, DB_USER, DB_PASSWD);
-        msSetError(MS_QUERYERR, tmp,
-           "msMYSQLLayerOpen()");
-        free(joininfo);
-        return MS_FAILURE;
+  {
+    char tmp[4000];
+    snprintf( tmp, sizeof(tmp), "Failed to connect to SQL server: Error: %s\nHost: %s\nUsername:%s\nPassword:%s\n", mysql_error(joininfo->conn), DB_HOST, DB_USER, DB_PASSWD);
+    msSetError(MS_QUERYERR, tmp,
+               "msMYSQLLayerOpen()");
+    free(joininfo);
+    return MS_FAILURE;
+  }
+
+  MYDEBUG printf("msMYSQLLayerOpen2 called<br>\n");
+  if (mysql_select_db(joininfo->conn,DB_DATABASE) < 0) {
+    mysql_close(joininfo->conn);
+  }
+  MYDEBUG printf("msMYSQLLayerOpen3 called<br>\n");
+  if (joininfo->qresult != NULL) { /* query leftover */
+    MYDEBUG printf("msMYSQLLayerOpen4 called<br>\n");
+    mysql_free_result(joininfo->qresult);
+  }
+  MYDEBUG printf("msMYSQLLayerOpen5 called<br>\n");
+  snprintf(qbuf, sizeof(qbuf), "SELECT count(%s) FROM %s", join->to, join->table);
+  MYDEBUG printf("%s<br>\n", qbuf);
+  if ((joininfo->qresult = msMySQLQuery(qbuf, joininfo->conn))) { /* There were some rows found, write 'em out for debug */
+    int numrows = mysql_affected_rows(joininfo->conn);
+    MYDEBUG printf("%d rows<br>\n", numrows);
+    for(i=0; i<numrows; i++) {
+      MYSQL_ROW row = mysql_fetch_row(joininfo->qresult);
+      MYDEBUG printf("(%s)<BR>\n",row[0]);
+      joininfo->rows = atoi(row[0]);
     }
+  } else {
+    msSetError(MS_DBFERR, "Item %s not found in table %s.", "msMySQLJoinConnect()", join->to, join->table);
+    return(MS_FAILURE);
+  }
+  snprintf(qbuf, sizeof(qbuf), "EXPLAIN %s", join->table);
+  if ((joininfo->qresult = msMySQLQuery(qbuf, joininfo->conn))) { /* There were some rows found, write 'em out for debug */
+    join->numitems = mysql_affected_rows(joininfo->conn);
+    if((join->items = (char **)malloc(sizeof(char *)*join->numitems)) == NULL) {
+      msSetError(MS_MEMERR, NULL, "msMySQLJoinConnect()");
+      return(MS_FAILURE);
+    }
+    MYDEBUG printf("%d rows<br>\n", join->numitems);
+    for(i=0; i<join->numitems; i++) {
+      MYSQL_ROW row = mysql_fetch_row(joininfo->qresult);
+      MYDEBUG printf("(%s)<BR>\n",row[0]);
+      join->items[i] = msStrdup(row[0]);
+    }
+  } else {
+    msSetError(MS_DBFERR, "Item %s not found in table %s.", "msMySQLJoinConnect()", join->to, join->table);
+    return(MS_FAILURE);
+  }
+  joininfo->tocolumn = msStrdup(join->to);
+
 
-    MYDEBUG printf("msMYSQLLayerOpen2 called<br>\n");
-    if (mysql_select_db(joininfo->conn,DB_DATABASE) < 0)
-    {
-      mysql_close(joininfo->conn);
-		}
-    MYDEBUG printf("msMYSQLLayerOpen3 called<br>\n");
-		if (joininfo->qresult != NULL) /* query leftover */
-		{
-    	MYDEBUG printf("msMYSQLLayerOpen4 called<br>\n");
-			mysql_free_result(joininfo->qresult);
-		}
-    MYDEBUG printf("msMYSQLLayerOpen5 called<br>\n");
-               snprintf(qbuf, sizeof(qbuf), "SELECT count(%s) FROM %s", join->to, join->table);
-		MYDEBUG printf("%s<br>\n", qbuf);
-   	if ((joininfo->qresult = msMySQLQuery(qbuf, joininfo->conn))) /* There were some rows found, write 'em out for debug */
-		{
-	  		int numrows = mysql_affected_rows(joininfo->conn);
-				MYDEBUG printf("%d rows<br>\n", numrows);
-        for(i=0;i<numrows;i++)
-        {
-            MYSQL_ROW row = mysql_fetch_row(joininfo->qresult);
-            MYDEBUG printf("(%s)<BR>\n",row[0]);
-						joininfo->rows = atoi(row[0]);
-        }
-		} else { 
-    	msSetError(MS_DBFERR, "Item %s not found in table %s.", "msMySQLJoinConnect()", join->to, join->table); 
-	    return(MS_FAILURE);
-		}
-		snprintf(qbuf, sizeof(qbuf), "EXPLAIN %s", join->table);
-   	if ((joininfo->qresult = msMySQLQuery(qbuf, joininfo->conn))) /* There were some rows found, write 'em out for debug */
-		{
-	  		join->numitems = mysql_affected_rows(joininfo->conn);
-			  if((join->items = (char **)malloc(sizeof(char *)*join->numitems)) == NULL) {
-				    msSetError(MS_MEMERR, NULL, "msMySQLJoinConnect()");
-		  		  return(MS_FAILURE);
-			  }
-				MYDEBUG printf("%d rows<br>\n", join->numitems);
-        for(i=0;i<join->numitems;i++)
-        {
-            MYSQL_ROW row = mysql_fetch_row(joininfo->qresult);
-            MYDEBUG printf("(%s)<BR>\n",row[0]);
-						join->items[i] = msStrdup(row[0]);
-        }
-		} else {
-    	msSetError(MS_DBFERR, "Item %s not found in table %s.", "msMySQLJoinConnect()", join->to, join->table); 
-	    return(MS_FAILURE);
-		}
-		joininfo->tocolumn = msStrdup(join->to);
-
-	
 
   /* get "from" item index   */
   for(i=0; i<layer->numitems; i++) {
@@ -674,37 +669,37 @@ int msMySQLJoinConnect(layerObj *layer, joinObj *join)
   }
 
   if(i == layer->numitems) {
-    msSetError(MS_JOINERR, "Item %s not found in layer %s.", "msMySQLJoinConnect()", join->from, layer->name); 
+    msSetError(MS_JOINERR, "Item %s not found in layer %s.", "msMySQLJoinConnect()", join->from, layer->name);
     return(MS_FAILURE);
   }
 
   /* finally store away the item names in the XBase table */
-  if(!join->items) return(MS_FAILURE);  
+  if(!join->items) return(MS_FAILURE);
 
   return(MS_SUCCESS);
 #endif
 }
 
-int msMySQLJoinPrepare(joinObj *join, shapeObj *shape) 
+int msMySQLJoinPrepare(joinObj *join, shapeObj *shape)
 {
 #ifndef USE_MYSQL
   msSetError(MS_QUERYERR, "MySQL support not available (compile with --with-mysql)", "msMySQLJoinPrepare()");
   return(MS_FAILURE);
 #else
-  msMySQLJoinInfo *joininfo = join->joininfo;  
+  msMySQLJoinInfo *joininfo = join->joininfo;
 
   if(!joininfo) {
-    msSetError(MS_JOINERR, "Join connection has not be created.", "msMySQLJoinPrepare()"); 
+    msSetError(MS_JOINERR, "Join connection has not be created.", "msMySQLJoinPrepare()");
     return(MS_FAILURE);
   }
 
   if(!shape) {
-    msSetError(MS_JOINERR, "Shape to be joined is empty.", "msMySQLJoinPrepare()"); 
+    msSetError(MS_JOINERR, "Shape to be joined is empty.", "msMySQLJoinPrepare()");
     return(MS_FAILURE);
   }
 
   if(!shape->values) {
-    msSetError(MS_JOINERR, "Shape to be joined has no attributes.", "msMySQLJoinPrepare()"); 
+    msSetError(MS_JOINERR, "Shape to be joined has no attributes.", "msMySQLJoinPrepare()");
     return(MS_FAILURE);
   }
 
@@ -717,18 +712,18 @@ int msMySQLJoinPrepare(joinObj *join, shapeObj *shape)
 #endif
 }
 
-int msMySQLJoinNext(joinObj *join) 
+int msMySQLJoinNext(joinObj *join)
 {
 #ifndef USE_MYSQL
   msSetError(MS_QUERYERR, "MySQL support not available (compile with --with-mysql)", "msMySQLJoinNext()");
   return(MS_FAILURE);
 #else
   int i, n;
-	char qbuf[4000];
+  char qbuf[4000];
   msMySQLJoinInfo *joininfo = join->joininfo;
 
   if(!joininfo) {
-    msSetError(MS_JOINERR, "Join connection has not be created.", "msMySQLJoinNext()"); 
+    msSetError(MS_JOINERR, "Join connection has not be created.", "msMySQLJoinNext()");
     return(MS_FAILURE);
   }
 
@@ -738,54 +733,52 @@ int msMySQLJoinNext(joinObj *join)
   }
 
   /* clear any old data */
-  if(join->values) { 
+  if(join->values) {
     msFreeCharArray(join->values, join->numitems);
     join->values = NULL;
   }
 
   n = joininfo->rows;
-    
-/* for(i=joininfo->nextrecord; i<n; i++) { // find a match */
-/* if(strcmp(joininfo->target, msMySQLReadStringAttribute(joininfo->conn, i, joininfo->toindex)) == 0) break; */
-/* }   */
-   	snprintf(qbuf, sizeof(qbuf), "SELECT * FROM %s WHERE %s = %s", join->table, joininfo->tocolumn, joininfo->target); 
-		MYDEBUG printf("%s<BR>\n", qbuf);
-   	if ((joininfo->qresult = msMySQLQuery(qbuf, joininfo->conn))) /* There were some rows found, write 'em out for debug */
-		{
-	  		int numrows = mysql_affected_rows(joininfo->conn);
-	  		int numfields = mysql_field_count(joininfo->conn);
-				MYDEBUG printf("%d rows<br>\n", numrows);
-        if (numrows > 0)
-        {
-            MYSQL_ROW row = mysql_fetch_row(joininfo->qresult);
-						for(i=0; i<numfields; i++){
-            	MYDEBUG printf("%s,",row[i]);
-						}
-           	MYDEBUG printf("<BR>\n");
-						free(join->values);
-						if((join->values = (char **)malloc(sizeof(char *)*join->numitems)) == NULL) {
-							msSetError(MS_MEMERR, NULL, "msMySQLJoinNext()");
-							return(MS_FAILURE);
-						}
-						for(i=0; i<join->numitems; i++){
-/* join->values[i] = msStrdup("\0"); */ /* intialize to zero length strings */
-							join->values[i] = msStrdup(row[i]); /* intialize to zero length strings */
-				/* rows = atoi(row[0]); */
-						}
-				}	else {
-						if((join->values = (char **)malloc(sizeof(char *)*join->numitems)) == NULL) {
-							msSetError(MS_MEMERR, NULL, "msMySQLJoinNext()");
-							return(MS_FAILURE);
-						}
-						for(i=0; i<join->numitems; i++)
-							join->values[i] = msStrdup("\0"); /* intialize to zero length strings  */
-
-						return(MS_DONE);
-				} 
-		} else {
-  		msSetError(MS_QUERYERR, "Query error (%s)", "msMySQLJoinNext()", qbuf);
-			return(MS_FAILURE);
-		}
+
+  /* for(i=joininfo->nextrecord; i<n; i++) { // find a match */
+  /* if(strcmp(joininfo->target, msMySQLReadStringAttribute(joininfo->conn, i, joininfo->toindex)) == 0) break; */
+  /* }   */
+  snprintf(qbuf, sizeof(qbuf), "SELECT * FROM %s WHERE %s = %s", join->table, joininfo->tocolumn, joininfo->target);
+  MYDEBUG printf("%s<BR>\n", qbuf);
+  if ((joininfo->qresult = msMySQLQuery(qbuf, joininfo->conn))) { /* There were some rows found, write 'em out for debug */
+    int numrows = mysql_affected_rows(joininfo->conn);
+    int numfields = mysql_field_count(joininfo->conn);
+    MYDEBUG printf("%d rows<br>\n", numrows);
+    if (numrows > 0) {
+      MYSQL_ROW row = mysql_fetch_row(joininfo->qresult);
+      for(i=0; i<numfields; i++) {
+        MYDEBUG printf("%s,",row[i]);
+      }
+      MYDEBUG printf("<BR>\n");
+      free(join->values);
+      if((join->values = (char **)malloc(sizeof(char *)*join->numitems)) == NULL) {
+        msSetError(MS_MEMERR, NULL, "msMySQLJoinNext()");
+        return(MS_FAILURE);
+      }
+      for(i=0; i<join->numitems; i++) {
+        /* join->values[i] = msStrdup("\0"); */ /* intialize to zero length strings */
+        join->values[i] = msStrdup(row[i]); /* intialize to zero length strings */
+        /* rows = atoi(row[0]); */
+      }
+    } else {
+      if((join->values = (char **)malloc(sizeof(char *)*join->numitems)) == NULL) {
+        msSetError(MS_MEMERR, NULL, "msMySQLJoinNext()");
+        return(MS_FAILURE);
+      }
+      for(i=0; i<join->numitems; i++)
+        join->values[i] = msStrdup("\0"); /* intialize to zero length strings  */
+
+      return(MS_DONE);
+    }
+  } else {
+    msSetError(MS_QUERYERR, "Query error (%s)", "msMySQLJoinNext()", qbuf);
+    return(MS_FAILURE);
+  }
 
 #ifdef __NOTDEF__
   if(i == n) { /* unable to do the join */
@@ -799,8 +792,8 @@ int msMySQLJoinNext(joinObj *join)
     joininfo->nextrecord = n;
     return(MS_DONE);
   }
-    
-  if((join->values = msMySQLGetValues(joininfo->conn,i)) == NULL) 
+
+  if((join->values = msMySQLGetValues(joininfo->conn,i)) == NULL)
     return(MS_FAILURE);
 
   joininfo->nextrecord = i+1; /* so we know where to start looking next time through */
@@ -810,7 +803,7 @@ int msMySQLJoinNext(joinObj *join)
 #endif
 }
 
-int msMySQLJoinClose(joinObj *join) 
+int msMySQLJoinClose(joinObj *join)
 {
 #ifndef USE_MYSQL
   msSetError(MS_QUERYERR, "MySQL support not available (compile with --with-mysql)", "msMySQLJoinClose()");
diff --git a/mapkml.cpp b/mapkml.cpp
index 8cb34e7..7ec0557 100644
--- a/mapkml.cpp
+++ b/mapkml.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id$ 
+ * $Id$
  *
  * Project:  MapServer
  * Purpose:  Headers for mapkml.cpp Google Earth KML output
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -36,13 +36,13 @@
 extern "C" {
 #endif
 
-KmlRenderer* getKmlRenderer(imageObj* img)
-{
+  KmlRenderer* getKmlRenderer(imageObj* img)
+  {
     return (KmlRenderer*) img->img.plugin;
-}
+  }
 
-imageObj* msCreateImageKml(int width, int height, outputFormatObj *format, colorObj* bg)
-{
+  imageObj* msCreateImageKml(int width, int height, outputFormatObj *format, colorObj* bg)
+  {
     imageObj *image = NULL;
 
     image = (imageObj*)malloc(sizeof(imageObj));
@@ -53,155 +53,155 @@ imageObj* msCreateImageKml(int width, int height, outputFormatObj *format, color
     image->img.plugin = (void *) ren;
 
     return image;
-}
+  }
 
-int msSaveImageKml(imageObj *img, FILE *fp, outputFormatObj *format)
-{
+  int msSaveImageKml(imageObj *img, mapObj* map, FILE *fp, outputFormatObj *format)
+  {
     KmlRenderer* renderer = getKmlRenderer(img);
     return renderer->saveImage(img, fp, format);
-}
+  }
 
-int msRenderLineKml(imageObj *img, shapeObj *p, strokeStyleObj *style)
-{
+  int msRenderLineKml(imageObj *img, shapeObj *p, strokeStyleObj *style)
+  {
     KmlRenderer* renderer = getKmlRenderer(img);
     renderer->renderLine(img, p, style);
     return MS_SUCCESS;
-}
+  }
 
-int msRenderPolygonKml(imageObj *img, shapeObj *p, colorObj *color)
-{
+  int msRenderPolygonKml(imageObj *img, shapeObj *p, colorObj *color)
+  {
     KmlRenderer* renderer = getKmlRenderer(img);
     renderer->renderPolygon(img, p, color);
     return MS_SUCCESS;
-}
+  }
 
-int msRenderPolygonTiledKml(imageObj *img, shapeObj *p,  imageObj *tile)
-{
+  int msRenderPolygonTiledKml(imageObj *img, shapeObj *p,  imageObj *tile)
+  {
     /*KmlRenderer* renderer = getKmlRenderer(img);*/
     return MS_SUCCESS;
-}
+  }
 
-int msRenderLineTiledKml(imageObj *img, shapeObj *p, imageObj *tile)
-{
+  int msRenderLineTiledKml(imageObj *img, shapeObj *p, imageObj *tile)
+  {
     return MS_SUCCESS;
-}
+  }
 
-int msRenderGlyphsKml(imageObj *img, double x, double y,
-                      labelStyleObj *style, char *text)
-{
+  int msRenderGlyphsKml(imageObj *img, double x, double y,
+                        labelStyleObj *style, char *text)
+  {
     KmlRenderer* renderer = getKmlRenderer(img);
     renderer->renderGlyphs(img, x, y, style, text);
     return MS_SUCCESS;
-}
+  }
 
-int msRenderVectorSymbolKml(imageObj *img, double x, double y,
-                            symbolObj *symbol, symbolStyleObj *style)
-{
+  int msRenderVectorSymbolKml(imageObj *img, double x, double y,
+                              symbolObj *symbol, symbolStyleObj *style)
+  {
     KmlRenderer* renderer = getKmlRenderer(img);
     renderer->renderVectorSymbol(img, x, y, symbol, style);
     return MS_SUCCESS;
-}
+  }
 
-int msRenderPixmapSymbolKml(imageObj *img, double x, double y,
-                            symbolObj *symbol, symbolStyleObj *style)
-{
+  int msRenderPixmapSymbolKml(imageObj *img, double x, double y,
+                              symbolObj *symbol, symbolStyleObj *style)
+  {
     KmlRenderer* renderer = getKmlRenderer(img);
     renderer->renderPixmapSymbol(img, x, y, symbol, style);
     return MS_SUCCESS;
-}
+  }
 
-int msRenderEllipseSymbolKml(imageObj *image, double x, double y, 
-                             symbolObj *symbol, symbolStyleObj *style)
-{
+  int msRenderEllipseSymbolKml(imageObj *image, double x, double y,
+                               symbolObj *symbol, symbolStyleObj *style)
+  {
     KmlRenderer* renderer = getKmlRenderer(image);
     renderer->renderEllipseSymbol(image, x, y, symbol, style);
     return MS_SUCCESS;
-}
+  }
 
-int msRenderTruetypeSymbolKml(imageObj *image, double x, double y,
-                              symbolObj *symbol, symbolStyleObj *style)
-{
+  int msRenderTruetypeSymbolKml(imageObj *image, double x, double y,
+                                symbolObj *symbol, symbolStyleObj *style)
+  {
     KmlRenderer* renderer = getKmlRenderer(image);
     renderer->renderTruetypeSymbol(image, x, y, symbol, style);
     return MS_SUCCESS;
-}
+  }
 
 
-int msRenderTileKml(imageObj *img, imageObj *tile, double x, double y)
-{
+  int msRenderTileKml(imageObj *img, imageObj *tile, double x, double y)
+  {
     return MS_SUCCESS;
-}
+  }
 
-int msGetRasterBufferKml(imageObj *img,rasterBufferObj *rb)
-{
+  int msGetRasterBufferKml(imageObj *img,rasterBufferObj *rb)
+  {
     return MS_FAILURE; //not supported for kml
-}
-
-
-int msGetTruetypeTextBBoxKml(rendererVTableObj *r,char *font, double size, char *string,
-		rectObj *rect, double **advances)
-{
-   rect->minx=0.0;
-   rect->maxx=0.0;
-   rect->miny=0.0;
-   rect->maxy=0.0;
-   if (advances) {
-         int numglyphs = msGetNumGlyphs(string);
-         *advances = (double*) msSmallMalloc(numglyphs * sizeof (double));
-         for(int i=0;i<numglyphs;i++) {
-            (*advances)[i] = size;
-         }
-   }
-   return MS_SUCCESS;
-}
+  }
+
+
+  int msGetTruetypeTextBBoxKml(rendererVTableObj *r,char** fonts, int numfonts, double size, char *string,
+                               rectObj *rect, double **advances, int bAdjustBaseline)
+  {
+    rect->minx=0.0;
+    rect->maxx=0.0;
+    rect->miny=0.0;
+    rect->maxy=0.0;
+    if (advances) {
+      int numglyphs = msGetNumGlyphs(string);
+      *advances = (double*) msSmallMalloc(numglyphs * sizeof (double));
+      for(int i=0; i<numglyphs; i++) {
+        (*advances)[i] = size;
+      }
+    }
+    return MS_SUCCESS;
+  }
 
-int msStartNewLayerKml(imageObj *img, mapObj *map, layerObj *layer)
-{
+  int msStartNewLayerKml(imageObj *img, mapObj *map, layerObj *layer)
+  {
     KmlRenderer* renderer = getKmlRenderer(img);
     return renderer->startNewLayer(img, layer);
-}
+  }
 
-int msCloseNewLayerKml(imageObj *img, mapObj *map, layerObj *layer)
-{
+  int msCloseNewLayerKml(imageObj *img, mapObj *map, layerObj *layer)
+  {
     KmlRenderer* renderer = getKmlRenderer(img);
     return renderer->closeNewLayer(img, layer);
-}
+  }
 
-int msFreeImageKml(imageObj *image)
-{
+  int msFreeImageKml(imageObj *image)
+  {
     KmlRenderer* renderer = getKmlRenderer(image);
-    if (renderer)
-    {
-        delete renderer;
+    if (renderer) {
+      delete renderer;
     }
     image->img.plugin=NULL;
     return MS_SUCCESS;
-}
+  }
 
-int msFreeSymbolKml(symbolObj *symbol)
-{
+  int msFreeSymbolKml(symbolObj *symbol)
+  {
     return MS_SUCCESS;
-}
+  }
 
-int msStartShapeKml(imageObj *img, shapeObj *shape)
-{
+  int msStartShapeKml(imageObj *img, shapeObj *shape)
+  {
     KmlRenderer* renderer = getKmlRenderer(img);
     renderer->startShape(img, shape);
     return MS_SUCCESS;
-}
+  }
 
-int msEndShapeKml(imageObj *img, shapeObj *shape)
-{
+  int msEndShapeKml(imageObj *img, shapeObj *shape)
+  {
     KmlRenderer* renderer = getKmlRenderer(img);
     renderer->endShape(img, shape);
     return MS_SUCCESS;
-}
+  }
 
-int msMergeRasterBufferKml(imageObj *dest, rasterBufferObj *overlay, double opacity, int srcX, 
-                           int srcY, int dstX, int dstY, int width, int height) {
+  int msMergeRasterBufferKml(imageObj *dest, rasterBufferObj *overlay, double opacity, int srcX,
+                             int srcY, int dstX, int dstY, int width, int height)
+  {
     KmlRenderer* renderer = getKmlRenderer(dest);
     return renderer->mergeRasterBuffer(dest,overlay);
-}
+  }
 
 #ifdef __cplusplus
 }
@@ -216,43 +216,43 @@ int msPopulateRendererVTableKML( rendererVTableObj *renderer )
 {
 #ifdef USE_KML
 
-    renderer->supports_transparent_layers = 1;
-    renderer->supports_pixel_buffer = 0;
-    renderer->supports_bitmap_fonts = 0;
-    renderer->supports_clipping = 0;
-    renderer->use_imagecache = 0;
-    renderer->default_transform_mode = MS_TRANSFORM_NONE;
-
-    renderer->startLayer = msStartNewLayerKml;
-    renderer->endLayer = msCloseNewLayerKml;
-    renderer->renderLine=&msRenderLineKml;
-    renderer->createImage=&msCreateImageKml;
-    renderer->saveImage=&msSaveImageKml;
-    renderer->renderPolygon=&msRenderPolygonKml;
-    renderer->renderGlyphs=&msRenderGlyphsKml;
-    renderer->renderEllipseSymbol = &msRenderEllipseSymbolKml;
-    renderer->renderVectorSymbol = &msRenderVectorSymbolKml;
-    renderer->renderPixmapSymbol = &msRenderPixmapSymbolKml;
-    renderer->renderTruetypeSymbol = &msRenderTruetypeSymbolKml;
-    renderer->mergeRasterBuffer = &msMergeRasterBufferKml;
-    renderer->loadImageFromFile = msLoadMSRasterBufferFromFile;
-    renderer->initializeRasterBuffer = aggInitializeRasterBuffer;
-    renderer->getTruetypeTextBBox = &msGetTruetypeTextBBoxKml;
-    renderer->renderTile = &msRenderTileKml;
-    renderer->renderPolygonTiled = &msRenderPolygonTiledKml;
-    renderer->renderLineTiled = NULL;
-    renderer->freeSymbol = &msFreeSymbolKml;
-    renderer->freeImage=&msFreeImageKml;
-    renderer->mergeRasterBuffer = msMergeRasterBufferKml;
-
-    renderer->startShape=&msStartShapeKml;
-    renderer->endShape=&msEndShapeKml;
-
-    return MS_SUCCESS;
+  renderer->supports_transparent_layers = 1;
+  renderer->supports_pixel_buffer = 0;
+  renderer->supports_bitmap_fonts = 0;
+  renderer->supports_clipping = 0;
+  renderer->use_imagecache = 0;
+  renderer->default_transform_mode = MS_TRANSFORM_NONE;
+
+  renderer->startLayer = msStartNewLayerKml;
+  renderer->endLayer = msCloseNewLayerKml;
+  renderer->renderLine=&msRenderLineKml;
+  renderer->createImage=&msCreateImageKml;
+  renderer->saveImage=&msSaveImageKml;
+  renderer->renderPolygon=&msRenderPolygonKml;
+  renderer->renderGlyphs=&msRenderGlyphsKml;
+  renderer->renderEllipseSymbol = &msRenderEllipseSymbolKml;
+  renderer->renderVectorSymbol = &msRenderVectorSymbolKml;
+  renderer->renderPixmapSymbol = &msRenderPixmapSymbolKml;
+  renderer->renderTruetypeSymbol = &msRenderTruetypeSymbolKml;
+  renderer->mergeRasterBuffer = &msMergeRasterBufferKml;
+  renderer->loadImageFromFile = msLoadMSRasterBufferFromFile;
+  renderer->initializeRasterBuffer = aggInitializeRasterBuffer;
+  renderer->getTruetypeTextBBox = &msGetTruetypeTextBBoxKml;
+  renderer->renderTile = &msRenderTileKml;
+  renderer->renderPolygonTiled = &msRenderPolygonTiledKml;
+  renderer->renderLineTiled = NULL;
+  renderer->freeSymbol = &msFreeSymbolKml;
+  renderer->freeImage=&msFreeImageKml;
+  renderer->mergeRasterBuffer = msMergeRasterBufferKml;
+
+  renderer->startShape=&msStartShapeKml;
+  renderer->endShape=&msEndShapeKml;
+
+  return MS_SUCCESS;
 #else
-    msSetError(MS_MISCERR, "KML Driver requested but is not built in", 
-               "msPopulateRendererVTableKML()");
-    return MS_FAILURE;
+  msSetError(MS_MISCERR, "KML Driver requested but is not built in",
+             "msPopulateRendererVTableKML()");
+  return MS_FAILURE;
 #endif
 }
 
diff --git a/mapkmlrenderer.cpp b/mapkmlrenderer.cpp
index d013ca3..24551ac 100644
--- a/mapkmlrenderer.cpp
+++ b/mapkmlrenderer.cpp
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -41,173 +41,168 @@
 
 #define  KML_MAXFEATURES_TODRAW 1000
 
-KmlRenderer::KmlRenderer(int width, int height, outputFormatObj *format, colorObj* color/*=NULL*/) 
+KmlRenderer::KmlRenderer(int width, int height, outputFormatObj *format, colorObj* color/*=NULL*/)
   : Width(width), Height(height), MapCellsize(1.0), XmlDoc(NULL), LayerNode(NULL), GroundOverlayNode(NULL),
     PlacemarkNode(NULL), GeomNode(NULL),
     Items(NULL), NumItems(0), FirstLayer(MS_TRUE), map(NULL), currentLayer(NULL),
     mElevationFromAttribute( false ), mElevationAttributeIndex( -1 ), mCurrentElevationValue(0.0)
 
 {
-    /*private variables*/        
-    pszLayerDescMetadata = NULL;  
-    papszLayerIncludeItems = NULL;
-    nIncludeItems=0;
-    papszLayerExcludeItems = NULL;
-    nExcludeItems=0;
-    pszLayerNameAttributeMetadata = NULL;  /*metadata to use for a name for each feature*/
-    
-    LineStyle = NULL;
-    numLineStyle = 0;
+  /*private variables*/
+  pszLayerDescMetadata = NULL;
+  papszLayerIncludeItems = NULL;
+  nIncludeItems=0;
+  papszLayerExcludeItems = NULL;
+  nExcludeItems=0;
+  pszLayerNameAttributeMetadata = NULL;  /*metadata to use for a name for each feature*/
+
+  LineStyle = NULL;
+  numLineStyle = 0;
+
+  xmlNodePtr styleNode;
+  xmlNodePtr listStyleNode;
+  /*  Create document.*/
+  XmlDoc = xmlNewDoc(BAD_CAST "1.0");
 
-    xmlNodePtr styleNode;
-    xmlNodePtr listStyleNode;
-    /*	Create document.*/
-    XmlDoc = xmlNewDoc(BAD_CAST "1.0");
+  xmlNodePtr rootNode = xmlNewNode(NULL, BAD_CAST "kml");
 
-    xmlNodePtr rootNode = xmlNewNode(NULL, BAD_CAST "kml");
+  /*  Name spaces*/
+  xmlSetNs(rootNode, xmlNewNs(rootNode, BAD_CAST "http://www.opengis.net/kml/2.2", NULL));
 
-    /*	Name spaces*/
-    xmlSetNs(rootNode, xmlNewNs(rootNode, BAD_CAST "http://www.opengis.net/kml/2.2", NULL));
+  xmlDocSetRootElement(XmlDoc, rootNode);
 
-    xmlDocSetRootElement(XmlDoc, rootNode);
+  DocNode = xmlNewChild(rootNode, NULL, BAD_CAST "Document", NULL);
 
-    DocNode = xmlNewChild(rootNode, NULL, BAD_CAST "Document", NULL);
+  styleNode = xmlNewChild(DocNode, NULL, BAD_CAST "Style", NULL);
+  xmlNewProp(styleNode, BAD_CAST "id", BAD_CAST "LayerFolder_check");
+  listStyleNode = xmlNewChild(styleNode, NULL, BAD_CAST "ListStyle", NULL);
+  xmlNewChild(listStyleNode, NULL, BAD_CAST "listItemType", BAD_CAST "check");
 
-    styleNode = xmlNewChild(DocNode, NULL, BAD_CAST "Style", NULL);
-    xmlNewProp(styleNode, BAD_CAST "id", BAD_CAST "LayerFolder_check");
-    listStyleNode = xmlNewChild(styleNode, NULL, BAD_CAST "ListStyle", NULL);
-    xmlNewChild(listStyleNode, NULL, BAD_CAST "listItemType", BAD_CAST "check");
+  styleNode = xmlNewChild(DocNode, NULL, BAD_CAST "Style", NULL);
+  xmlNewProp(styleNode, BAD_CAST "id", BAD_CAST "LayerFolder_checkHideChildren");
+  listStyleNode = xmlNewChild(styleNode, NULL, BAD_CAST "ListStyle", NULL);
+  xmlNewChild(listStyleNode, NULL, BAD_CAST "listItemType", BAD_CAST "checkHideChildren");
 
-    styleNode = xmlNewChild(DocNode, NULL, BAD_CAST "Style", NULL);
-    xmlNewProp(styleNode, BAD_CAST "id", BAD_CAST "LayerFolder_checkHideChildren");
-    listStyleNode = xmlNewChild(styleNode, NULL, BAD_CAST "ListStyle", NULL);
-    xmlNewChild(listStyleNode, NULL, BAD_CAST "listItemType", BAD_CAST "checkHideChildren");
+  styleNode = xmlNewChild(DocNode, NULL, BAD_CAST "Style", NULL);
+  xmlNewProp(styleNode, BAD_CAST "id", BAD_CAST "LayerFolder_checkOffOnly");
+  listStyleNode = xmlNewChild(styleNode, NULL, BAD_CAST "ListStyle", NULL);
+  xmlNewChild(listStyleNode, NULL, BAD_CAST "listItemType", BAD_CAST "checkOffOnly");
 
-    styleNode = xmlNewChild(DocNode, NULL, BAD_CAST "Style", NULL);
-    xmlNewProp(styleNode, BAD_CAST "id", BAD_CAST "LayerFolder_checkOffOnly");
-    listStyleNode = xmlNewChild(styleNode, NULL, BAD_CAST "ListStyle", NULL);
-    xmlNewChild(listStyleNode, NULL, BAD_CAST "listItemType", BAD_CAST "checkOffOnly");
+  styleNode = xmlNewChild(DocNode, NULL, BAD_CAST "Style", NULL);
+  xmlNewProp(styleNode, BAD_CAST "id", BAD_CAST "LayerFolder_radioFolder");
+  listStyleNode = xmlNewChild(styleNode, NULL, BAD_CAST "ListStyle", NULL);
+  xmlNewChild(listStyleNode, NULL, BAD_CAST "listItemType", BAD_CAST "radioFolder");
 
-    styleNode = xmlNewChild(DocNode, NULL, BAD_CAST "Style", NULL);
-    xmlNewProp(styleNode, BAD_CAST "id", BAD_CAST "LayerFolder_radioFolder");
-    listStyleNode = xmlNewChild(styleNode, NULL, BAD_CAST "ListStyle", NULL);
-    xmlNewChild(listStyleNode, NULL, BAD_CAST "listItemType", BAD_CAST "radioFolder");
 
+  StyleHashTable = msCreateHashTable();
 
-    StyleHashTable = msCreateHashTable();
-	
 }
 
 KmlRenderer::~KmlRenderer()
 {
-    if (XmlDoc)
-      xmlFreeDoc(XmlDoc);
+  if (XmlDoc)
+    xmlFreeDoc(XmlDoc);
 
-    if (StyleHashTable)
-      msFreeHashTable(StyleHashTable);
+  if (StyleHashTable)
+    msFreeHashTable(StyleHashTable);
 
-    if(LineStyle)
-      msFree(LineStyle);
+  if(LineStyle)
+    msFree(LineStyle);
 
-    xmlCleanupParser();
+  xmlCleanupParser();
 }
 
 imageObj* KmlRenderer::createImage(int, int, outputFormatObj*, colorObj*)
 {
-    return NULL;
+  return NULL;
 }
 
 int KmlRenderer::saveImage(imageObj *, FILE *fp, outputFormatObj *format)
-{    
-/* -------------------------------------------------------------------- */
-/*      Write out the document.                                         */
-/* -------------------------------------------------------------------- */
-
-    int bufSize = 0;
-    xmlChar *buf = NULL;
-    msIOContext *context = NULL;
-    int chunkSize = 4096;
+{
+  /* -------------------------------------------------------------------- */
+  /*      Write out the document.                                         */
+  /* -------------------------------------------------------------------- */
+
+  int bufSize = 0;
+  xmlChar *buf = NULL;
+  msIOContext *context = NULL;
+  int chunkSize = 4096;
 #if defined(CPL_ZIP_API_OFFERED)
-    int bZip = MS_FALSE;
+  int bZip = MS_FALSE;
 #endif
- 
-    if( msIO_needBinaryStdout() == MS_FAILURE )
-      return MS_FAILURE;
 
-    xmlDocDumpFormatMemoryEnc(XmlDoc, &buf, &bufSize, "UTF-8", 1);
+  if( msIO_needBinaryStdout() == MS_FAILURE )
+    return MS_FAILURE;
+
+  xmlDocDumpFormatMemoryEnc(XmlDoc, &buf, &bufSize, "UTF-8", 1);
 
 #if defined(USE_OGR)
-    if (format && format->driver && strcasecmp(format->driver, "kmz") == 0)
-    {
+  if (format && format->driver && strcasecmp(format->driver, "kmz") == 0) {
 #if defined(CPL_ZIP_API_OFFERED)
-        bZip = MS_TRUE;
+    bZip = MS_TRUE;
 #else
-        msSetError( MS_MISCERR, "kmz format support unavailable, perhaps you need to upgrade to GDAL/OGR 1.8?",
-                    "KmlRenderer::saveImage()");
-        xmlFree(buf);
-        return MS_FAILURE;
+    msSetError( MS_MISCERR, "kmz format support unavailable, perhaps you need to upgrade to GDAL/OGR 1.8?",
+                "KmlRenderer::saveImage()");
+    xmlFree(buf);
+    return MS_FAILURE;
 #endif
+  }
+
+#if defined(CPL_ZIP_API_OFFERED)
+  if (bZip) {
+    VSILFILE *fpZip;
+    int bytes_read;
+    char buffer[1024];
+    char *zip_filename =NULL;
+    void *hZip=NULL;
+
+    zip_filename = msTmpFile(NULL, NULL, "/vsimem/kmlzip/", "kmz" );
+    hZip = CPLCreateZip( zip_filename, NULL );
+    CPLCreateFileInZip( hZip, "mapserver.kml", NULL );
+    for (int i=0; i<bufSize; i+=chunkSize) {
+      int size = chunkSize;
+      if (i + size > bufSize)
+        size = bufSize - i;
+      CPLWriteFileInZip( hZip,  buf+i, size);
     }
+    CPLCloseFileInZip( hZip );
+    CPLCloseZip( hZip );
 
-#if defined(CPL_ZIP_API_OFFERED) 
-    if (bZip)
-    {
-        VSILFILE *fpZip;
-        int bytes_read;
-        char buffer[1024];
-        char *zip_filename =NULL;
-        void *hZip=NULL;
-
-        zip_filename = msTmpFile(NULL, NULL, "/vsimem/kmlzip/", "kmz" );
-        hZip = CPLCreateZip( zip_filename, NULL );
-        CPLCreateFileInZip( hZip, "mapserver.kml", NULL );
-        for (int i=0; i<bufSize; i+=chunkSize)
-        {
-            int size = chunkSize;
-            if (i + size > bufSize)
-              size = bufSize - i;
-            CPLWriteFileInZip( hZip,  buf+i, size);
-        }
-        CPLCloseFileInZip( hZip );
-        CPLCloseZip( hZip );
-
-        context = msIO_getHandler(fp);
-        fpZip = VSIFOpenL( zip_filename, "r" );
-        
-        while( (bytes_read = VSIFReadL( buffer, 1, sizeof(buffer), fpZip )) > 0 )
-        {
-            if (context)
-              msIO_contextWrite(context, buffer, bytes_read);
-            else
-              msIO_fwrite( buffer, 1, bytes_read, fp );
-        }
-        VSIFCloseL( fpZip );
-        msFree( zip_filename);
-        xmlFree(buf);
-        return(MS_SUCCESS);
+    context = msIO_getHandler(fp);
+    fpZip = VSIFOpenL( zip_filename, "r" );
+
+    while( (bytes_read = VSIFReadL( buffer, 1, sizeof(buffer), fpZip )) > 0 ) {
+      if (context)
+        msIO_contextWrite(context, buffer, bytes_read);
+      else
+        msIO_fwrite( buffer, 1, bytes_read, fp );
     }
+    VSIFCloseL( fpZip );
+    msFree( zip_filename);
+    xmlFree(buf);
+    return(MS_SUCCESS);
+  }
 #endif
 
 #endif
-    
-    context = msIO_getHandler(fp);
 
-    
-    for (int i=0; i<bufSize; i+=chunkSize)
-    {
-        int size = chunkSize;
-        if (i + size > bufSize)
-          size = bufSize - i;
-
-        if (context)
-          msIO_contextWrite(context, buf+i, size);
-        else
-          msIO_fwrite(buf+i, 1, size, fp);
-    }
+  context = msIO_getHandler(fp);
 
-    xmlFree(buf);
 
-    return(MS_SUCCESS);
+  for (int i=0; i<bufSize; i+=chunkSize) {
+    int size = chunkSize;
+    if (i + size > bufSize)
+      size = bufSize - i;
+
+    if (context)
+      msIO_contextWrite(context, buf+i, size);
+    else
+      msIO_fwrite(buf+i, 1, size, fp);
+  }
+
+  xmlFree(buf);
+
+  return(MS_SUCCESS);
 }
 
 
@@ -218,63 +213,60 @@ int KmlRenderer::saveImage(imageObj *, FILE *fp, outputFormatObj *format)
 /************************************************************************/
 void KmlRenderer::processLayer(layerObj *layer, outputFormatObj *format)
 {
-    int i;
-    const char *asRaster = NULL;
-    int nMaxFeatures = -1;
-    const char *pszTmp;
-    char szTmp[10]; 
-
-    if (!layer)
-      return;
-
-    /*turn of labelcache*/
-    layer->labelcache = MS_OFF;
-    
-    /*if there are labels we want the coordinates to 
-      be the center of the element.*/
-    for(i=0; i<layer->numclasses; i++)
-      layer->_class[i]->label.position = MS_XY;
-   
-    /*we do not want to draw multiple styles.
-      the new rendering architecture does not allow
-      to know if we are dealing with a multi-style.
-      So here we remove all styles beside the first one*/
-    
-    for(i=0; i<layer->numclasses; i++)
-    {
-        while (layer->_class[i]->numstyles > 1)
-          msDeleteStyle(layer->_class[i], layer->_class[i]->numstyles-1);
-    }
-
-    /*if layer has a metadata KML_OUTPUTASRASTER set to true, add a processing directive
-      to use an agg driver*/
-    asRaster = msLookupHashTable(&layer->metadata, "kml_outputasraster");
-    if (!asRaster)
-      asRaster = msLookupHashTable(&(layer->map->web.metadata), "kml_outputasraster");
-    if (asRaster && (strcasecmp(asRaster, "true") == 0 ||
-                     strcasecmp(asRaster, "yes") == 0))
-      msLayerAddProcessing(layer, "RENDERER=png24");
-      
-    
-    /*set a maxfeaturestodraw, if not already set*/
-    
-    pszTmp = msLookupHashTable(&layer->metadata, "maxfeaturestodraw");
+  int i;
+  const char *asRaster = NULL;
+  int nMaxFeatures = -1;
+  const char *pszTmp;
+  char szTmp[10];
+
+  if (!layer)
+    return;
+
+  /*turn of labelcache*/
+  layer->labelcache = MS_OFF;
+
+  /*if there are labels we want the coordinates to
+    be the center of the element.*/
+  for(i=0; i<layer->numclasses; i++)
+    if(layer->_class[i]->numlabels > 0) layer->_class[i]->labels[0]->position = MS_XY;
+
+  /*we do not want to draw multiple styles.
+    the new rendering architecture does not allow
+    to know if we are dealing with a multi-style.
+    So here we remove all styles beside the first one*/
+
+  for(i=0; i<layer->numclasses; i++) {
+    while (layer->_class[i]->numstyles > 1)
+      msDeleteStyle(layer->_class[i], layer->_class[i]->numstyles-1);
+  }
+
+  /*if layer has a metadata KML_OUTPUTASRASTER set to true, add a processing directive
+    to use an agg driver*/
+  asRaster = msLookupHashTable(&layer->metadata, "kml_outputasraster");
+  if (!asRaster)
+    asRaster = msLookupHashTable(&(layer->map->web.metadata), "kml_outputasraster");
+  if (asRaster && (strcasecmp(asRaster, "true") == 0 ||
+                   strcasecmp(asRaster, "yes") == 0))
+    msLayerAddProcessing(layer, "RENDERER=png24");
+
+
+  /*set a maxfeaturestodraw, if not already set*/
+
+  pszTmp = msLookupHashTable(&layer->metadata, "maxfeaturestodraw");
+  if (pszTmp)
+    nMaxFeatures = atoi(pszTmp);
+  else {
+    pszTmp = msLookupHashTable(&layer->map->web.metadata, "maxfeaturestodraw");
     if (pszTmp)
       nMaxFeatures = atoi(pszTmp);
-    else
-    {
-        pszTmp = msLookupHashTable(&layer->map->web.metadata, "maxfeaturestodraw");
-        if (pszTmp)
-          nMaxFeatures = atoi(pszTmp);
-    }
-    if (nMaxFeatures < 0 && format)
-      nMaxFeatures = atoi(msGetOutputFormatOption( format, "maxfeaturestodraw", "-1"));
-    
-    if (nMaxFeatures < 0 && format)
-    {
-        snprintf(szTmp, sizeof(szTmp), "%d", KML_MAXFEATURES_TODRAW);
-        msSetOutputFormatOption( format, "maxfeaturestodraw", szTmp);
-    }
+  }
+  if (nMaxFeatures < 0 && format)
+    nMaxFeatures = atoi(msGetOutputFormatOption( format, "maxfeaturestodraw", "-1"));
+
+  if (nMaxFeatures < 0 && format) {
+    snprintf(szTmp, sizeof(szTmp), "%d", KML_MAXFEATURES_TODRAW);
+    msSetOutputFormatOption( format, "maxfeaturestodraw", szTmp);
+  }
 
 }
 
@@ -285,505 +277,470 @@ void KmlRenderer::processLayer(layerObj *layer, outputFormatObj *format)
 /************************************************************************/
 char* KmlRenderer::getLayerName(layerObj *layer)
 {
-    char stmp[20];
-    const char *name=NULL;;
+  char stmp[20];
+  const char *name=NULL;;
 
-    if (!layer)
-      return NULL;
+  if (!layer)
+    return NULL;
 
 
-    name = msLookupHashTable(&layer->metadata, "ows_name");
-    if (name && strlen(name) > 0)
-      return msStrdup(name);
+  name = msLookupHashTable(&layer->metadata, "ows_name");
+  if (name && strlen(name) > 0)
+    return msStrdup(name);
 
-    if (layer->name && strlen(layer->name) > 0)
-      return msStrdup(layer->name);
+  if (layer->name && strlen(layer->name) > 0)
+    return msStrdup(layer->name);
 
-    sprintf(stmp, "Layer%d",layer->index);
-    return msStrdup(stmp); 
+  sprintf(stmp, "Layer%d",layer->index);
+  return msStrdup(stmp);
 
 }
 
 const char* KmlRenderer::getAliasName(layerObj *lp, char *pszItemName, const char *namespaces)
 {
-    const char *pszAlias = NULL;
-    if (lp && pszItemName && strlen(pszItemName) > 0)
-    {
-        char szTmp[256];
-        snprintf(szTmp, sizeof(szTmp), "%s_alias", pszItemName);
-        pszAlias = msOWSLookupMetadata(&(lp->metadata), namespaces, szTmp);
-    }
-    return pszAlias;
+  const char *pszAlias = NULL;
+  if (lp && pszItemName && strlen(pszItemName) > 0) {
+    char szTmp[256];
+    snprintf(szTmp, sizeof(szTmp), "%s_alias", pszItemName);
+    pszAlias = msOWSLookupMetadata(&(lp->metadata), namespaces, szTmp);
+  }
+  return pszAlias;
 }
 
 int KmlRenderer::startNewLayer(imageObj *img, layerObj *layer)
 {
-    char *layerName=NULL;
-    const char *value=NULL;
-
-    LayerNode = xmlNewNode(NULL, BAD_CAST "Folder");
-	
-    layerName = getLayerName(layer);
-    xmlNewChild(LayerNode, NULL, BAD_CAST "name", BAD_CAST layerName);
-    msFree(layerName);
-
-    const char *layerVisibility = layer->status != MS_OFF ? "1" : "0";
-    xmlNewChild(LayerNode, NULL, BAD_CAST "visibility", BAD_CAST layerVisibility);
-
-    const char *layerDsiplayFolder = msLookupHashTable(&(layer->metadata), "kml_folder_display");
-    if (layerDsiplayFolder == NULL)
-      layerDsiplayFolder = msLookupHashTable(&(layer->map->web.metadata), "kml_folder_display");
-    if (!layerDsiplayFolder || strlen(layerDsiplayFolder)<=0)
-    {
-        xmlNewChild(LayerNode, NULL, BAD_CAST "styleUrl", BAD_CAST "#LayerFolder_check"); 
-    }
-
+  char *layerName=NULL;
+  const char *value=NULL;
+
+  LayerNode = xmlNewNode(NULL, BAD_CAST "Folder");
+
+  layerName = getLayerName(layer);
+  xmlNewChild(LayerNode, NULL, BAD_CAST "name", BAD_CAST layerName);
+  msFree(layerName);
+
+  const char *layerVisibility = layer->status != MS_OFF ? "1" : "0";
+  xmlNewChild(LayerNode, NULL, BAD_CAST "visibility", BAD_CAST layerVisibility);
+
+  const char *layerDsiplayFolder = msLookupHashTable(&(layer->metadata), "kml_folder_display");
+  if (layerDsiplayFolder == NULL)
+    layerDsiplayFolder = msLookupHashTable(&(layer->map->web.metadata), "kml_folder_display");
+  if (!layerDsiplayFolder || strlen(layerDsiplayFolder)<=0) {
+    xmlNewChild(LayerNode, NULL, BAD_CAST "styleUrl", BAD_CAST "#LayerFolder_check");
+  }
+
+  else {
+    if (strcasecmp(layerDsiplayFolder, "checkHideChildren") == 0)
+      xmlNewChild(LayerNode, NULL, BAD_CAST "styleUrl", BAD_CAST "#LayerFolder_checkHideChildren");
+    else if (strcasecmp(layerDsiplayFolder, "checkOffOnly") == 0)
+      xmlNewChild(LayerNode, NULL, BAD_CAST "styleUrl", BAD_CAST "#LayerFolder_checkOffOnly");
+    else if (strcasecmp(layerDsiplayFolder, "radioFolder") == 0)
+      xmlNewChild(LayerNode, NULL, BAD_CAST "styleUrl", BAD_CAST "#LayerFolder_radioFolder");
     else
-    {
-        if (strcasecmp(layerDsiplayFolder, "checkHideChildren") == 0)
-          xmlNewChild(LayerNode, NULL, BAD_CAST "styleUrl", BAD_CAST "#LayerFolder_checkHideChildren");
-        else if (strcasecmp(layerDsiplayFolder, "checkOffOnly") == 0)
-          xmlNewChild(LayerNode, NULL, BAD_CAST "styleUrl", BAD_CAST "#LayerFolder_checkOffOnly");
-        else if (strcasecmp(layerDsiplayFolder, "radioFolder") == 0)
-          xmlNewChild(LayerNode, NULL, BAD_CAST "styleUrl", BAD_CAST "#LayerFolder_radioFolder");
-        else 
-          xmlNewChild(LayerNode, NULL, BAD_CAST "styleUrl", BAD_CAST "#LayerFolder_check");
-    }
+      xmlNewChild(LayerNode, NULL, BAD_CAST "styleUrl", BAD_CAST "#LayerFolder_check");
+  }
 
-  
-    /*Init few things on the first layer*/
-    if (FirstLayer)
-    {
-        FirstLayer = MS_FALSE;
-        map = layer->map;
 
-        if (layer->map->mappath)
-          snprintf(MapPath, sizeof(MapPath), "%s", layer->map->mappath);
+  /*Init few things on the first layer*/
+  if (FirstLayer) {
+    FirstLayer = MS_FALSE;
+    map = layer->map;
 
-        /*First rendered layer - check mapfile projection*/
-        checkProjection(layer->map);
+    if (layer->map->mappath)
+      snprintf(MapPath, sizeof(MapPath), "%s", layer->map->mappath);
 
-        /*check for image path and image url*/
-        if (layer->map->debug && (layer->map->web.imageurl == NULL ||   layer->map->web.imagepath == NULL))
-          msDebug("KmlRenderer::startNewLayer: imagepath and imageurl sould be set in the web object\n");
+    /*First rendered layer - check mapfile projection*/
+    checkProjection(layer->map);
 
+    /*check for image path and image url*/
+    if (layer->map->debug && (layer->map->web.imageurl == NULL ||   layer->map->web.imagepath == NULL))
+      msDebug("KmlRenderer::startNewLayer: imagepath and imageurl sould be set in the web object\n");
 
-        /*map rect for ground overlay*/
-        MapExtent = layer->map->extent;
-        MapCellsize = layer->map->cellsize;
-        BgColor = layer->map->imagecolor;
 
-        xmlNewChild(DocNode, NULL, BAD_CAST "name", BAD_CAST layer->map->name);
-        aggFormat = msSelectOutputFormat( layer->map, "png24");
-        aggFormat->transparent = MS_TRUE;
-         
-    }
+    /*map rect for ground overlay*/
+    MapExtent = layer->map->extent;
+    MapCellsize = layer->map->cellsize;
+    BgColor = layer->map->imagecolor;
 
-    currentLayer = layer;
+    xmlNewChild(DocNode, NULL, BAD_CAST "name", BAD_CAST layer->map->name);
+    aggFormat = msSelectOutputFormat( layer->map, "png24");
+    aggFormat->transparent = MS_TRUE;
 
-    if (!msLayerIsOpen(layer))
-    {
-        if (msLayerOpen(layer) != MS_SUCCESS)
-        {
-            msSetError(MS_MISCERR, "msLayerOpen failed", "KmlRenderer::startNewLayer" );
-        }
-    }
+  }
 
-    /*pre process the layer to set things that make sense for kml output*/
-    if (img)
-      processLayer(layer, img->format);
-    else
-      processLayer(layer, NULL);
-
-    if (msLookupHashTable(&layer->metadata, "kml_description"))
-      pszLayerDescMetadata = msLookupHashTable(&layer->metadata, "kml_description");
-    else if (msLookupHashTable(&layer->metadata, "ows_description"))
-      pszLayerDescMetadata = msLookupHashTable(&layer->metadata, "ows_description");
-
-    value=msLookupHashTable(&layer->metadata, "kml_include_items");
-    if (!value)
-      value=msLookupHashTable(&layer->metadata, "ows_include_items");
-    if (value)
-      papszLayerIncludeItems = msStringSplit(value, ',', &nIncludeItems);
-
-    value=msLookupHashTable(&layer->metadata, "kml_exclude_items");
-    if (!value)
-      value=msLookupHashTable(&layer->metadata, "ows_exclude_items");
-    if (value)
-      papszLayerExcludeItems = msStringSplit(value, ',', &nExcludeItems);
-
-     
-    if (msLookupHashTable(&layer->metadata, "kml_name_item"))
-      pszLayerNameAttributeMetadata = msLookupHashTable(&layer->metadata, "kml_name_item");
-
-    /*get all attributes*/
-    msLayerWhichItems(layer, MS_TRUE, NULL);
-
-
-    NumItems = layer->numitems;
-    if (NumItems)
-    {
-        Items = (char **)msSmallCalloc(NumItems, sizeof(char *));
-        for (int i=0; i<NumItems; i++)
-          Items[i] = msStrdup(layer->items[i]);
-    }
+  currentLayer = layer;
 
-    
-    char* elevationAttribute = msLookupHashTable(&layer->metadata, "kml_elevation_attribute");
-    if( elevationAttribute )
-    {
-        mElevationFromAttribute = true;
-        for( int i = 0; i < layer->numitems; ++i )
-        {
-            if( strcasecmp( layer->items[i], elevationAttribute ) == 0 )
-            {
-                mElevationAttributeIndex = i;
-            }
-        }
-    }  
+  if (!msLayerIsOpen(layer)) {
+    if (msLayerOpen(layer) != MS_SUCCESS) {
+      msSetError(MS_MISCERR, "msLayerOpen failed", "KmlRenderer::startNewLayer" );
+    }
+  }
+
+  /*pre process the layer to set things that make sense for kml output*/
+  if (img)
+    processLayer(layer, img->format);
+  else
+    processLayer(layer, NULL);
+
+  if (msLookupHashTable(&layer->metadata, "kml_description"))
+    pszLayerDescMetadata = msLookupHashTable(&layer->metadata, "kml_description");
+  else if (msLookupHashTable(&layer->metadata, "ows_description"))
+    pszLayerDescMetadata = msLookupHashTable(&layer->metadata, "ows_description");
+
+  value=msLookupHashTable(&layer->metadata, "kml_include_items");
+  if (!value)
+    value=msLookupHashTable(&layer->metadata, "ows_include_items");
+  if (value)
+    papszLayerIncludeItems = msStringSplit(value, ',', &nIncludeItems);
+
+  value=msLookupHashTable(&layer->metadata, "kml_exclude_items");
+  if (!value)
+    value=msLookupHashTable(&layer->metadata, "ows_exclude_items");
+  if (value)
+    papszLayerExcludeItems = msStringSplit(value, ',', &nExcludeItems);
+
+
+  if (msLookupHashTable(&layer->metadata, "kml_name_item"))
+    pszLayerNameAttributeMetadata = msLookupHashTable(&layer->metadata, "kml_name_item");
+
+  /*get all attributes*/
+  msLayerWhichItems(layer, MS_TRUE, NULL);
+
+
+  NumItems = layer->numitems;
+  if (NumItems) {
+    Items = (char **)msSmallCalloc(NumItems, sizeof(char *));
+    for (int i=0; i<NumItems; i++)
+      Items[i] = msStrdup(layer->items[i]);
+  }
+
+
+  char* elevationAttribute = msLookupHashTable(&layer->metadata, "kml_elevation_attribute");
+  if( elevationAttribute ) {
+    mElevationFromAttribute = true;
+    for( int i = 0; i < layer->numitems; ++i ) {
+      if( strcasecmp( layer->items[i], elevationAttribute ) == 0 ) {
+        mElevationAttributeIndex = i;
+      }
+    }
+  }
 
-    setupRenderingParams(&layer->metadata);
-    return MS_SUCCESS;
+  setupRenderingParams(&layer->metadata);
+  return MS_SUCCESS;
 }
 
 int KmlRenderer::closeNewLayer(imageObj *img, layerObj *layer)
 {
-    flushPlacemark();
-        
-    xmlAddChild(DocNode, LayerNode);
-
-    if(Items)
-    {
-        msFreeCharArray(Items, NumItems);
-        Items = NULL;
-        NumItems = 0;
-    }
+  flushPlacemark();
 
-    if (pszLayerDescMetadata)
-      pszLayerDescMetadata = NULL;
-    if (pszLayerNameAttributeMetadata)
-      pszLayerNameAttributeMetadata = NULL;
+  xmlAddChild(DocNode, LayerNode);
 
-    if (papszLayerIncludeItems && nIncludeItems>0)
-      msFreeCharArray(papszLayerIncludeItems, nIncludeItems);
-    papszLayerIncludeItems=NULL;
+  if(Items) {
+    msFreeCharArray(Items, NumItems);
+    Items = NULL;
+    NumItems = 0;
+  }
 
-    if (papszLayerExcludeItems && nExcludeItems>0)
-      msFreeCharArray(papszLayerExcludeItems, nExcludeItems);
-    papszLayerExcludeItems=NULL;
+  if (pszLayerDescMetadata)
+    pszLayerDescMetadata = NULL;
+  if (pszLayerNameAttributeMetadata)
+    pszLayerNameAttributeMetadata = NULL;
 
-    return MS_SUCCESS;
-}
+  if (papszLayerIncludeItems && nIncludeItems>0)
+    msFreeCharArray(papszLayerIncludeItems, nIncludeItems);
+  papszLayerIncludeItems=NULL;
 
-int KmlRenderer::mergeRasterBuffer(imageObj *image, rasterBufferObj *rb) {
-    assert(rb && rb->type == MS_BUFFER_BYTE_RGBA);
-    char *tmpFileName = NULL;
-    char *tmpUrl = NULL;
-    FILE *tmpFile = NULL;
-    
-    tmpFileName = msTmpFile(NULL, MapPath, image->imagepath, "png");
-    tmpFile = fopen(tmpFileName,"wb");
-    if (tmpFile)
-    {
-     
-        if (!aggFormat->vtable)
-          msInitializeRendererVTable(aggFormat);
-
-        msSaveRasterBuffer(map,rb,tmpFile,aggFormat);
-        tmpUrl = msStrdup( image->imageurl);
-        tmpUrl = msStringConcatenate(tmpUrl, (char *)(msGetBasename(tmpFileName)));
-        tmpUrl = msStringConcatenate(tmpUrl, ".png");
-        
-        createGroundOverlayNode(LayerNode, tmpUrl, currentLayer);
-        msFree(tmpFileName);
-        msFree(tmpUrl);
-        fclose(tmpFile);
-        return MS_SUCCESS;
-    } else {
-        msSetError(MS_IOERR,"Failed to create file for kml overlay","KmlRenderer::mergeRasterBuffer()");
-        return MS_FAILURE;
-    }
+  if (papszLayerExcludeItems && nExcludeItems>0)
+    msFreeCharArray(papszLayerExcludeItems, nExcludeItems);
+  papszLayerExcludeItems=NULL;
+
+  return MS_SUCCESS;
 }
 
-void KmlRenderer::setupRenderingParams(hashTableObj *layerMetadata)
+int KmlRenderer::mergeRasterBuffer(imageObj *image, rasterBufferObj *rb)
 {
-    AltitudeMode = 0;
-    Extrude = 0;
-    Tessellate = 0;
-
-    char *altitudeModeVal = msLookupHashTable(layerMetadata, "kml_altitudeMode");
-    if (altitudeModeVal)
-    {
-        if(strcasecmp(altitudeModeVal, "absolute") == 0)
-          AltitudeMode = absolute;
-        else if(strcasecmp(altitudeModeVal, "relativeToGround") == 0)
-          AltitudeMode = relativeToGround;
-        else if(strcasecmp(altitudeModeVal, "clampToGround") == 0)
-          AltitudeMode = clampToGround;
-    }
+  assert(rb && rb->type == MS_BUFFER_BYTE_RGBA);
+  char *tmpFileName = NULL;
+  char *tmpUrl = NULL;
+  FILE *tmpFile = NULL;
 
-    char *extrudeVal = msLookupHashTable(layerMetadata, "kml_extrude");
-    if (altitudeModeVal)
-    {
-        Extrude = atoi(extrudeVal);
-    }
+  tmpFileName = msTmpFile(NULL, MapPath, image->imagepath, "png");
+  tmpFile = fopen(tmpFileName,"wb");
+  if (tmpFile) {
 
-    char *tessellateVal = msLookupHashTable(layerMetadata, "kml_tessellate");
-    if (tessellateVal)
-    {
-        Tessellate = atoi(tessellateVal);
-    }
+    if (!aggFormat->vtable)
+      msInitializeRendererVTable(aggFormat);
+
+    msSaveRasterBuffer(map,rb,tmpFile,aggFormat);
+    tmpUrl = msStrdup( image->imageurl);
+    tmpUrl = msStringConcatenate(tmpUrl, (char *)(msGetBasename(tmpFileName)));
+    tmpUrl = msStringConcatenate(tmpUrl, ".png");
+
+    createGroundOverlayNode(LayerNode, tmpUrl, currentLayer);
+    msFree(tmpFileName);
+    msFree(tmpUrl);
+    fclose(tmpFile);
+    return MS_SUCCESS;
+  } else {
+    msSetError(MS_IOERR,"Failed to create file for kml overlay","KmlRenderer::mergeRasterBuffer()");
+    return MS_FAILURE;
+  }
+}
+
+void KmlRenderer::setupRenderingParams(hashTableObj *layerMetadata)
+{
+  AltitudeMode = 0;
+  Extrude = 0;
+  Tessellate = 0;
+
+  char *altitudeModeVal = msLookupHashTable(layerMetadata, "kml_altitudeMode");
+  if (altitudeModeVal) {
+    if(strcasecmp(altitudeModeVal, "absolute") == 0)
+      AltitudeMode = absolute;
+    else if(strcasecmp(altitudeModeVal, "relativeToGround") == 0)
+      AltitudeMode = relativeToGround;
+    else if(strcasecmp(altitudeModeVal, "clampToGround") == 0)
+      AltitudeMode = clampToGround;
+  }
+
+  char *extrudeVal = msLookupHashTable(layerMetadata, "kml_extrude");
+  if (altitudeModeVal) {
+    Extrude = atoi(extrudeVal);
+  }
+
+  char *tessellateVal = msLookupHashTable(layerMetadata, "kml_tessellate");
+  if (tessellateVal) {
+    Tessellate = atoi(tessellateVal);
+  }
 
 }
 
 int KmlRenderer::checkProjection(mapObj *map)
 {
-    projectionObj *projection= &map->projection;
+  projectionObj *projection= &map->projection;
 #ifdef USE_PROJ
-    if (projection && projection->numargs > 0 && pj_is_latlong(projection->proj))
-    {
-        return MS_SUCCESS;
-    }
-    else
-    {
-        char epsg_string[100];
-        rectObj sRect;
-        projectionObj out;
-
-        /* for layer the do not have any projection set, set them with the current map
-           projection*/
-        if (projection && projection->numargs > 0)
-        {
-            layerObj *lp = NULL;
-            int i =0;
-            char *pszMapProjectString = msGetProjectionString(projection);
-            if (pszMapProjectString)
-            {
-                for(i=0; i<map->numlayers; i++)
-                {
-                    lp = GET_LAYER(map, i);
-                    if (lp->projection.numargs == 0 && lp->transform == MS_TRUE)
-                    {
-                        msFreeProjection(&lp->projection);
-                        msLoadProjectionString(&lp->projection, pszMapProjectString);
-                    }
-                }
-                msFree(pszMapProjectString);
-            }
+  if (projection && projection->numargs > 0 && pj_is_latlong(projection->proj)) {
+    return MS_SUCCESS;
+  } else {
+    char epsg_string[100];
+    rectObj sRect;
+    projectionObj out;
+
+    /* for layer the do not have any projection set, set them with the current map
+       projection*/
+    if (projection && projection->numargs > 0) {
+      layerObj *lp = NULL;
+      int i =0;
+      char *pszMapProjectString = msGetProjectionString(projection);
+      if (pszMapProjectString) {
+        for(i=0; i<map->numlayers; i++) {
+          lp = GET_LAYER(map, i);
+          if (lp->projection.numargs == 0 && lp->transform == MS_TRUE) {
+            msFreeProjection(&lp->projection);
+            msLoadProjectionString(&lp->projection, pszMapProjectString);
+          }
         }
-        strcpy(epsg_string, "epsg:4326" );
-        msInitProjection(&out);
-        msLoadProjectionString(&out, epsg_string);
+        msFree(pszMapProjectString);
+      }
+    }
+    strcpy(epsg_string, "epsg:4326" );
+    msInitProjection(&out);
+    msLoadProjectionString(&out, epsg_string);
 
-        sRect = map->extent;
-        msProjectRect(projection, &out, &sRect);
-        msFreeProjection(projection);
-        msLoadProjectionString(projection, epsg_string);
+    sRect = map->extent;
+    msProjectRect(projection, &out, &sRect);
+    msFreeProjection(projection);
+    msLoadProjectionString(projection, epsg_string);
 
-        /*change also units and extents*/
-        map->extent = sRect;
-        map->units = MS_DD;
+    /*change also units and extents*/
+    map->extent = sRect;
+    map->units = MS_DD;
 
 
-        if (map->debug)
-          msDebug("KmlRenderer::checkProjection: Mapfile projection set to epsg:4326\n");
+    if (map->debug)
+      msDebug("KmlRenderer::checkProjection: Mapfile projection set to epsg:4326\n");
 
-        return MS_SUCCESS;
-    }
+    return MS_SUCCESS;
+  }
 
 #else
-    msSetError(MS_MISCERR, "Projection support not enabled", "KmlRenderer::checkProjection" );
-    return MS_FAILURE;
+  msSetError(MS_MISCERR, "Projection support not enabled", "KmlRenderer::checkProjection" );
+  return MS_FAILURE;
 #endif
 }
 
 xmlNodePtr KmlRenderer::createPlacemarkNode(xmlNodePtr parentNode, char *styleUrl)
 {
-    xmlNodePtr placemarkNode = xmlNewChild(parentNode, NULL, BAD_CAST "Placemark", NULL);
-    /*always add a name. It will be replaced by a text value if available*/
-    char tmpid[100];
-    char *stmp=NULL, *layerName=NULL;
-    if (CurrentShapeName && strlen(CurrentShapeName)>0)
-    {
-        xmlNewChild(placemarkNode, NULL, BAD_CAST "name", BAD_CAST CurrentShapeName);
-    }
-    else
-    {
-        sprintf(tmpid, ".%d", CurrentShapeIndex);
-        layerName = getLayerName(currentLayer);
-        stmp = msStringConcatenate(stmp, layerName);
-        stmp = msStringConcatenate(stmp, tmpid);
-        xmlNewChild(placemarkNode, NULL, BAD_CAST "name", BAD_CAST stmp);
-    }
-    msFree(layerName);
-    msFree(stmp);
-    if (styleUrl)
-      xmlNewChild(placemarkNode, NULL, BAD_CAST "styleUrl", BAD_CAST styleUrl);
-
-    return placemarkNode;
+  xmlNodePtr placemarkNode = xmlNewChild(parentNode, NULL, BAD_CAST "Placemark", NULL);
+  /*always add a name. It will be replaced by a text value if available*/
+  char tmpid[100];
+  char *stmp=NULL, *layerName=NULL;
+  if (CurrentShapeName && strlen(CurrentShapeName)>0) {
+    xmlNewChild(placemarkNode, NULL, BAD_CAST "name", BAD_CAST CurrentShapeName);
+  } else {
+    sprintf(tmpid, ".%d", CurrentShapeIndex);
+    layerName = getLayerName(currentLayer);
+    stmp = msStringConcatenate(stmp, layerName);
+    stmp = msStringConcatenate(stmp, tmpid);
+    xmlNewChild(placemarkNode, NULL, BAD_CAST "name", BAD_CAST stmp);
+  }
+  msFree(layerName);
+  msFree(stmp);
+  if (styleUrl)
+    xmlNewChild(placemarkNode, NULL, BAD_CAST "styleUrl", BAD_CAST styleUrl);
+
+  return placemarkNode;
 }
 
 void KmlRenderer::renderLine(imageObj*, shapeObj *p, strokeStyleObj *style)
 {
-    if (p->numlines == 0)
-      return;
-
-    if (PlacemarkNode == NULL)
-      PlacemarkNode = createPlacemarkNode(LayerNode, NULL);
-
-    if (!PlacemarkNode)
-      return;
-
-    addLineStyleToList(style);    
-    SymbologyFlag[Line] = 1;
-
-    /*p->index > CurrentDrawnShapeIndexneed to be reviewd. Added since the hight
-      level code caches shapes when rendering lines*/
-    if (CurrentDrawnShapeIndex == -1 || p->index > CurrentDrawnShapeIndex)
-    {
-        xmlNodePtr geomNode = getGeomParentNode("LineString");
-        addAddRenderingSpecifications(geomNode);
-        addCoordsNode(geomNode, p->line[0].point, p->line[0].numpoints);
-          
-        /* more than one line => MultiGeometry*/
-        if (p->numlines > 1)
-        {
-            geomNode = getGeomParentNode("LineString"); // returns MultiGeom Node
-            for (int i=1; i<p->numlines; i++)
-            {
-                xmlNodePtr lineStringNode = xmlNewChild(geomNode, NULL, BAD_CAST "LineString", NULL);
-                addAddRenderingSpecifications(lineStringNode);
-                addCoordsNode(lineStringNode, p->line[i].point, p->line[i].numpoints);
-            }
-        }
-      
-        CurrentDrawnShapeIndex = p->index;
+  if (p->numlines == 0)
+    return;
+
+  if (PlacemarkNode == NULL)
+    PlacemarkNode = createPlacemarkNode(LayerNode, NULL);
+
+  if (!PlacemarkNode)
+    return;
+
+  addLineStyleToList(style);
+  SymbologyFlag[Line] = 1;
+
+  /*p->index > CurrentDrawnShapeIndexneed to be reviewd. Added since the hight
+    level code caches shapes when rendering lines*/
+  if (CurrentDrawnShapeIndex == -1 || p->index > CurrentDrawnShapeIndex) {
+    xmlNodePtr geomNode = getGeomParentNode("LineString");
+    addAddRenderingSpecifications(geomNode);
+    addCoordsNode(geomNode, p->line[0].point, p->line[0].numpoints);
+
+    /* more than one line => MultiGeometry*/
+    if (p->numlines > 1) {
+      geomNode = getGeomParentNode("LineString"); // returns MultiGeom Node
+      for (int i=1; i<p->numlines; i++) {
+        xmlNodePtr lineStringNode = xmlNewChild(geomNode, NULL, BAD_CAST "LineString", NULL);
+        addAddRenderingSpecifications(lineStringNode);
+        addCoordsNode(lineStringNode, p->line[i].point, p->line[i].numpoints);
+      }
     }
-      
+
+    CurrentDrawnShapeIndex = p->index;
+  }
+
 }
 
 void KmlRenderer::renderPolygon(imageObj*, shapeObj *p, colorObj *color)
 {
-    if (PlacemarkNode == NULL)
-      PlacemarkNode = createPlacemarkNode(LayerNode, NULL);
+  if (PlacemarkNode == NULL)
+    PlacemarkNode = createPlacemarkNode(LayerNode, NULL);
 
-    if (!PlacemarkNode)
-      return;
+  if (!PlacemarkNode)
+    return;
 
-    memcpy(&PolygonColor, color, sizeof(colorObj));
-    SymbologyFlag[Polygon] = 1;
+  memcpy(&PolygonColor, color, sizeof(colorObj));
+  SymbologyFlag[Polygon] = 1;
 
-    
-    if (p->index != CurrentDrawnShapeIndex)
-    {
-    
-        xmlNodePtr geomParentNode = getGeomParentNode("Polygon");
 
-        for (int i=0; i<p->numlines; i++)
-        {
-            xmlNodePtr bdryNode = NULL;
+  if (p->index != CurrentDrawnShapeIndex) {
 
-            if (i==0) /* __TODO__ check ring order*/
-              bdryNode = xmlNewChild(geomParentNode, NULL, BAD_CAST "outerBoundaryIs", NULL);
-            else
-              bdryNode = xmlNewChild(geomParentNode, NULL, BAD_CAST "innerBoundaryIs", NULL);
+    xmlNodePtr geomParentNode = getGeomParentNode("Polygon");
 
-            xmlNodePtr ringNode = xmlNewChild(bdryNode, NULL, BAD_CAST "LinearRing", NULL);
-            addAddRenderingSpecifications(ringNode);
-            addCoordsNode(ringNode, p->line[i].point, p->line[i].numpoints);
-        }
+    for (int i=0; i<p->numlines; i++) {
+      xmlNodePtr bdryNode = NULL;
+
+      if (i==0) /* __TODO__ check ring order*/
+        bdryNode = xmlNewChild(geomParentNode, NULL, BAD_CAST "outerBoundaryIs", NULL);
+      else
+        bdryNode = xmlNewChild(geomParentNode, NULL, BAD_CAST "innerBoundaryIs", NULL);
 
-        CurrentDrawnShapeIndex = p->index;
-      
+      xmlNodePtr ringNode = xmlNewChild(bdryNode, NULL, BAD_CAST "LinearRing", NULL);
+      addAddRenderingSpecifications(ringNode);
+      addCoordsNode(ringNode, p->line[i].point, p->line[i].numpoints);
     }
-      
+
+    CurrentDrawnShapeIndex = p->index;
+
+  }
+
 }
 
 void KmlRenderer::addCoordsNode(xmlNodePtr parentNode, pointObj *pts, int numPts)
 {
-    char lineBuf[128];
+  char lineBuf[128];
 
-    xmlNodePtr coordsNode = xmlNewChild(parentNode, NULL, BAD_CAST "coordinates", NULL);
-    xmlNodeAddContent(coordsNode, BAD_CAST "\n");
+  xmlNodePtr coordsNode = xmlNewChild(parentNode, NULL, BAD_CAST "coordinates", NULL);
+  xmlNodeAddContent(coordsNode, BAD_CAST "\n");
 
-    for (int i=0; i<numPts; i++)
-    {
-        if( mElevationFromAttribute )
-        {
-            sprintf(lineBuf, "\t%.8f,%.8f,%.8f\n", pts[i].x, pts[i].y, mCurrentElevationValue);
-        }
-        else if (AltitudeMode == relativeToGround || AltitudeMode == absolute)
-        {
+  for (int i=0; i<numPts; i++) {
+    if( mElevationFromAttribute ) {
+      sprintf(lineBuf, "\t%.8f,%.8f,%.8f\n", pts[i].x, pts[i].y, mCurrentElevationValue);
+    } else if (AltitudeMode == relativeToGround || AltitudeMode == absolute) {
 #ifdef USE_POINT_Z_M
-            sprintf(lineBuf, "\t%.8f,%.8f,%.8f\n", pts[i].x, pts[i].y, pts[i].z);
+      sprintf(lineBuf, "\t%.8f,%.8f,%.8f\n", pts[i].x, pts[i].y, pts[i].z);
 #else
-            msSetError(MS_MISCERR, "Z coordinates support not available  (mapserver not compiled with USE_POINT_Z_M option)", "KmlRenderer::addCoordsNode()");
+      msSetError(MS_MISCERR, "Z coordinates support not available  (mapserver not compiled with USE_POINT_Z_M option)", "KmlRenderer::addCoordsNode()");
 #endif
-        }
-        else
-          sprintf(lineBuf, "\t%.8f,%.8f\n", pts[i].x, pts[i].y);
+    } else
+      sprintf(lineBuf, "\t%.8f,%.8f\n", pts[i].x, pts[i].y);
 
-        xmlNodeAddContent(coordsNode, BAD_CAST lineBuf);
-    }
-    xmlNodeAddContent(coordsNode, BAD_CAST "\t");
+    xmlNodeAddContent(coordsNode, BAD_CAST lineBuf);
+  }
+  xmlNodeAddContent(coordsNode, BAD_CAST "\t");
 }
 
 void KmlRenderer::renderGlyphs(imageObj*, double x, double y, labelStyleObj *style, char *text)
 {
-    xmlNodePtr node; 
+  xmlNodePtr node;
 
-    if (PlacemarkNode == NULL)
-      PlacemarkNode = createPlacemarkNode(LayerNode, NULL);
+  if (PlacemarkNode == NULL)
+    PlacemarkNode = createPlacemarkNode(LayerNode, NULL);
 
-    if (!PlacemarkNode)
-      return;
+  if (!PlacemarkNode)
+    return;
 
-    memcpy(&LabelStyle, style, sizeof(labelStyleObj));
-    SymbologyFlag[Label] = 1;
+  memcpy(&LabelStyle, style, sizeof(labelStyleObj));
+  SymbologyFlag[Label] = 1;
 
-    /*there is alaws a default name (layer.shapeid). Replace it*/
-    for (node = PlacemarkNode->children; node; node = node->next) 
-    {
-        if (node->type != XML_ELEMENT_NODE)
-          continue;
+  /*there is alaws a default name (layer.shapeid). Replace it*/
+  for (node = PlacemarkNode->children; node; node = node->next) {
+    if (node->type != XML_ELEMENT_NODE)
+      continue;
 
-        if (strcmp((char *)node->name, "name") == 0)
-        {
-            xmlNodeSetContent(node,  BAD_CAST text);
-            break;
-        }
+    if (strcmp((char *)node->name, "name") == 0) {
+      xmlNodeSetContent(node,  BAD_CAST text);
+      break;
     }
-            
-    /*xmlNewChild(PlacemarkNode, NULL, BAD_CAST "name", BAD_CAST text);*/
+  }
 
-    xmlNodePtr geomNode = getGeomParentNode("Point");
-    addAddRenderingSpecifications(geomNode);
+  /*xmlNewChild(PlacemarkNode, NULL, BAD_CAST "name", BAD_CAST text);*/
+
+  xmlNodePtr geomNode = getGeomParentNode("Point");
+  addAddRenderingSpecifications(geomNode);
 
-    pointObj pt;
-    pt.x = x; pt.y = y;
-    addCoordsNode(geomNode, &pt, 1);
+  pointObj pt;
+  pt.x = x;
+  pt.y = y;
+  addCoordsNode(geomNode, &pt, 1);
 }
 
 void KmlRenderer::addAddRenderingSpecifications(xmlNodePtr node)
 {
-    /*
-      <extrude>0</extrude>                   <!-- boolean -->
-      <tessellate>0</tessellate>             <!-- boolean -->
-      <altitudeMode>clampToGround</altitudeMode> 
-    */
-
-    if (Extrude)
-      xmlNewChild(node, NULL, BAD_CAST "extrude", BAD_CAST "1");
-
-    if (Tessellate)
-      xmlNewChild(node, NULL, BAD_CAST "tessellate", BAD_CAST "1");
-
-    if (AltitudeMode == absolute)
-      xmlNewChild(node, NULL, BAD_CAST "altitudeMode", BAD_CAST "absolute");
-    else if (AltitudeMode == relativeToGround)
-      xmlNewChild(node, NULL, BAD_CAST "altitudeMode", BAD_CAST "relativeToGround");
-    else if (AltitudeMode == clampToGround)
-      xmlNewChild(node, NULL, BAD_CAST "altitudeMode", BAD_CAST "clampToGround");
+  /*
+    <extrude>0</extrude>                   <!-- boolean -->
+    <tessellate>0</tessellate>             <!-- boolean -->
+    <altitudeMode>clampToGround</altitudeMode>
+  */
+
+  if (Extrude)
+    xmlNewChild(node, NULL, BAD_CAST "extrude", BAD_CAST "1");
+
+  if (Tessellate)
+    xmlNewChild(node, NULL, BAD_CAST "tessellate", BAD_CAST "1");
+
+  if (AltitudeMode == absolute)
+    xmlNewChild(node, NULL, BAD_CAST "altitudeMode", BAD_CAST "absolute");
+  else if (AltitudeMode == relativeToGround)
+    xmlNewChild(node, NULL, BAD_CAST "altitudeMode", BAD_CAST "relativeToGround");
+  else if (AltitudeMode == clampToGround)
+    xmlNewChild(node, NULL, BAD_CAST "altitudeMode", BAD_CAST "clampToGround");
 }
 
 
@@ -791,596 +748,553 @@ imageObj *agg2CreateImage(int width, int height, outputFormatObj *format, colorO
 
 int KmlRenderer::createIconImage(char *fileName, symbolObj *symbol, symbolStyleObj *symstyle)
 {
-    pointObj p;
-    
-    imageObj *tmpImg = NULL;
-    
-    tmpImg = agg2CreateImage((int)(symbol->sizex*symstyle->scale), 
-                             (int)(symbol->sizey*symstyle->scale), 
-                             aggFormat, NULL);
-    tmpImg->format = aggFormat;
-    if (!aggFormat->vtable)
-      msInitializeRendererVTable(aggFormat);
+  pointObj p;
+
+  imageObj *tmpImg = NULL;
 
-    p.x = symbol->sizex * symstyle->scale / 2;
-    p.y = symbol->sizey *symstyle->scale / 2;
+  tmpImg = agg2CreateImage((int)(symbol->sizex*symstyle->scale),
+                           (int)(symbol->sizey*symstyle->scale),
+                           aggFormat, NULL);
+  tmpImg->format = aggFormat;
+  if (!aggFormat->vtable)
+    msInitializeRendererVTable(aggFormat);
+
+  p.x = symbol->sizex * symstyle->scale / 2;
+  p.y = symbol->sizey *symstyle->scale / 2;
 #ifdef USE_POINT_Z_M
-    p.z = 0.0;
+  p.z = 0.0;
 #endif
 
-    msDrawMarkerSymbol(&map->symbolset,tmpImg, &p, symstyle->style, 1);
+  msDrawMarkerSymbol(&map->symbolset,tmpImg, &p, symstyle->style, 1);
 
-    return msSaveImage(map, tmpImg, fileName);
+  return msSaveImage(map, tmpImg, fileName);
 }
 
 void KmlRenderer::renderSymbol(imageObj *img, double x, double y, symbolObj *symbol, symbolStyleObj *style)
 {
-    if (PlacemarkNode == NULL)
-      PlacemarkNode = createPlacemarkNode(LayerNode, NULL);
+  if (PlacemarkNode == NULL)
+    PlacemarkNode = createPlacemarkNode(LayerNode, NULL);
 
-    if (!PlacemarkNode)
-      return;
+  if (!PlacemarkNode)
+    return;
 
-    snprintf(SymbolUrl, sizeof(SymbolUrl), "%s", lookupSymbolUrl(img, symbol, style));
-    SymbologyFlag[Symbol] = 1;
+  snprintf(SymbolUrl, sizeof(SymbolUrl), "%s", lookupSymbolUrl(img, symbol, style));
+  SymbologyFlag[Symbol] = 1;
 
-    xmlNodePtr geomNode = getGeomParentNode("Point");
-    addAddRenderingSpecifications(geomNode);
+  xmlNodePtr geomNode = getGeomParentNode("Point");
+  addAddRenderingSpecifications(geomNode);
 
-    pointObj pt;
-    pt.x = x; pt.y = y;
-    addCoordsNode(geomNode, &pt, 1);
+  pointObj pt;
+  pt.x = x;
+  pt.y = y;
+  addCoordsNode(geomNode, &pt, 1);
 }
 
-void KmlRenderer::renderPixmapSymbol(imageObj *img, double x, double y, symbolObj *symbol, 
+void KmlRenderer::renderPixmapSymbol(imageObj *img, double x, double y, symbolObj *symbol,
                                      symbolStyleObj *style)
 {
-    renderSymbol(img, x, y, symbol, style);
+  renderSymbol(img, x, y, symbol, style);
 }
 
-void KmlRenderer::renderVectorSymbol(imageObj *img, double x, double y, symbolObj *symbol, 
+void KmlRenderer::renderVectorSymbol(imageObj *img, double x, double y, symbolObj *symbol,
                                      symbolStyleObj *style)
 {
-    renderSymbol(img, x, y, symbol, style);
+  renderSymbol(img, x, y, symbol, style);
 }
 
-void KmlRenderer::renderEllipseSymbol(imageObj *img, double x, double y, symbolObj *symbol, 
+void KmlRenderer::renderEllipseSymbol(imageObj *img, double x, double y, symbolObj *symbol,
                                       symbolStyleObj *style)
 {
-    renderSymbol(img, x, y, symbol, style);
+  renderSymbol(img, x, y, symbol, style);
 }
 
-void KmlRenderer::renderTruetypeSymbol(imageObj *img, double x, double y, symbolObj *symbol, 
+void KmlRenderer::renderTruetypeSymbol(imageObj *img, double x, double y, symbolObj *symbol,
                                        symbolStyleObj *style)
 {
-    renderSymbol(img, x, y, symbol, style);
+  renderSymbol(img, x, y, symbol, style);
 }
 
 xmlNodePtr KmlRenderer::createGroundOverlayNode(xmlNodePtr parentNode, char *imageHref, layerObj *layer)
 {
-    /*
-      <?xml version="1.0" encoding="UTF-8"?>
-      <kml xmlns="http://www.opengis.net/kml/2.2">
-      <GroundOverlay>
-      <name>GroundOverlay.kml</name>
-      <color>7fffffff</color>
-      <drawOrder>1</drawOrder>
-      <Icon>
-      <href>http://www.google.com/intl/en/images/logo.gif</href>
-      <refreshMode>onInterval</refreshMode>
-      <refreshInterval>86400</refreshInterval>
-      <viewBoundScale>0.75</viewBoundScale>
-      </Icon>
-      <LatLonBox>
-      <north>37.83234</north>
-      <south>37.832122</south>
-      <east>-122.373033</east>
-      <west>-122.373724</west>
-      <rotation>45</rotation>
-      </LatLonBox>
-      </GroundOverlay>
-      </kml>
-    */
-    char	layerHexColor[32];
-    xmlNodePtr groundOverlayNode = xmlNewChild(parentNode, NULL, BAD_CAST "GroundOverlay", NULL);
-    char *layerName = getLayerName(layer);
-    xmlNewChild(groundOverlayNode, NULL, BAD_CAST "name", BAD_CAST layerName);
-    if (layer->opacity > 0 && layer->opacity < 100)
-    {
-        sprintf(layerHexColor, "%02xffffff", (unsigned int)MS_NINT(layer->opacity*2.55));
-        xmlNewChild(groundOverlayNode, NULL, BAD_CAST "color", BAD_CAST layerHexColor);
-    }
-    else
-      xmlNewChild(groundOverlayNode, NULL, BAD_CAST "color", BAD_CAST "ffffffff");
-    char stmp[20];
-    sprintf(stmp, "%d",layer->index);
-    xmlNewChild(groundOverlayNode, NULL, BAD_CAST "drawOrder", BAD_CAST stmp);
-
-    if (imageHref)
-    {
-        xmlNodePtr iconNode = xmlNewChild(groundOverlayNode, NULL, BAD_CAST "Icon", NULL);
-        xmlNewChild(iconNode, NULL, BAD_CAST "href", BAD_CAST imageHref);
-    }
-
-    char crdStr[64];
-    rectObj mapextent;
-    if (map->gt.need_geotransform == MS_TRUE)
-      mapextent = currentLayer->map->saved_extent;
-    else
-      mapextent = currentLayer->map->extent;
-
-    xmlNodePtr latLonBoxNode = xmlNewChild(groundOverlayNode, NULL, BAD_CAST "LatLonBox", NULL);
-    sprintf(crdStr, "%.8f", mapextent.maxy);
-    xmlNewChild(latLonBoxNode, NULL, BAD_CAST "north", BAD_CAST crdStr);
-
-    sprintf(crdStr, "%.8f", mapextent.miny);
-    xmlNewChild(latLonBoxNode, NULL, BAD_CAST "south", BAD_CAST crdStr);
-
-    sprintf(crdStr, "%.8f", mapextent.minx);
-    xmlNewChild(latLonBoxNode, NULL, BAD_CAST "west", BAD_CAST crdStr);
-
-    sprintf(crdStr, "%.8f", mapextent.maxx);
-    xmlNewChild(latLonBoxNode, NULL, BAD_CAST "east", BAD_CAST crdStr);
-
-    xmlNewChild(latLonBoxNode, NULL, BAD_CAST "rotation", BAD_CAST "0.0");
-
-    return groundOverlayNode;
+  /*
+    <?xml version="1.0" encoding="UTF-8"?>
+    <kml xmlns="http://www.opengis.net/kml/2.2">
+    <GroundOverlay>
+    <name>GroundOverlay.kml</name>
+    <color>7fffffff</color>
+    <drawOrder>1</drawOrder>
+    <Icon>
+    <href>http://www.google.com/intl/en/images/logo.gif</href>
+    <refreshMode>onInterval</refreshMode>
+    <refreshInterval>86400</refreshInterval>
+    <viewBoundScale>0.75</viewBoundScale>
+    </Icon>
+    <LatLonBox>
+    <north>37.83234</north>
+    <south>37.832122</south>
+    <east>-122.373033</east>
+    <west>-122.373724</west>
+    <rotation>45</rotation>
+    </LatLonBox>
+    </GroundOverlay>
+    </kml>
+  */
+  char  layerHexColor[32];
+  xmlNodePtr groundOverlayNode = xmlNewChild(parentNode, NULL, BAD_CAST "GroundOverlay", NULL);
+  char *layerName = getLayerName(layer);
+  xmlNewChild(groundOverlayNode, NULL, BAD_CAST "name", BAD_CAST layerName);
+  if (layer->opacity > 0 && layer->opacity < 100) {
+    sprintf(layerHexColor, "%02xffffff", (unsigned int)MS_NINT(layer->opacity*2.55));
+    xmlNewChild(groundOverlayNode, NULL, BAD_CAST "color", BAD_CAST layerHexColor);
+  } else
+    xmlNewChild(groundOverlayNode, NULL, BAD_CAST "color", BAD_CAST "ffffffff");
+  char stmp[20];
+  sprintf(stmp, "%d",layer->index);
+  xmlNewChild(groundOverlayNode, NULL, BAD_CAST "drawOrder", BAD_CAST stmp);
+
+  if (imageHref) {
+    xmlNodePtr iconNode = xmlNewChild(groundOverlayNode, NULL, BAD_CAST "Icon", NULL);
+    xmlNewChild(iconNode, NULL, BAD_CAST "href", BAD_CAST imageHref);
+  }
+
+  char crdStr[64];
+  rectObj mapextent;
+  if (map->gt.need_geotransform == MS_TRUE)
+    mapextent = currentLayer->map->saved_extent;
+  else
+    mapextent = currentLayer->map->extent;
+
+  xmlNodePtr latLonBoxNode = xmlNewChild(groundOverlayNode, NULL, BAD_CAST "LatLonBox", NULL);
+  sprintf(crdStr, "%.8f", mapextent.maxy);
+  xmlNewChild(latLonBoxNode, NULL, BAD_CAST "north", BAD_CAST crdStr);
+
+  sprintf(crdStr, "%.8f", mapextent.miny);
+  xmlNewChild(latLonBoxNode, NULL, BAD_CAST "south", BAD_CAST crdStr);
+
+  sprintf(crdStr, "%.8f", mapextent.minx);
+  xmlNewChild(latLonBoxNode, NULL, BAD_CAST "west", BAD_CAST crdStr);
+
+  sprintf(crdStr, "%.8f", mapextent.maxx);
+  xmlNewChild(latLonBoxNode, NULL, BAD_CAST "east", BAD_CAST crdStr);
+
+  xmlNewChild(latLonBoxNode, NULL, BAD_CAST "rotation", BAD_CAST "0.0");
+
+  return groundOverlayNode;
 }
 
 void KmlRenderer::startShape(imageObj *, shapeObj *shape)
 {
-    if (PlacemarkNode)
-      flushPlacemark();
-
-    CurrentShapeIndex=-1;
-    CurrentDrawnShapeIndex = -1;
-    CurrentShapeName=NULL;
+  if (PlacemarkNode)
+    flushPlacemark();
 
-    /*should be done at endshape but the plugin architecture does not call endshape yet*/
-    if(LineStyle)
-    {
-        msFree(LineStyle);
+  CurrentShapeIndex=-1;
+  CurrentDrawnShapeIndex = -1;
+  CurrentShapeName=NULL;
 
-        LineStyle = NULL;
-        numLineStyle = 0;
-    }
+  /*should be done at endshape but the plugin architecture does not call endshape yet*/
+  if(LineStyle) {
+    msFree(LineStyle);
 
-    if (shape)
-    {
-        CurrentShapeIndex = shape->index;
-        if (pszLayerNameAttributeMetadata)
-        {
-            for (int i=0; i<currentLayer->numitems; i++)
-            {
-                if (strcasecmp(currentLayer->items[i], pszLayerNameAttributeMetadata) == 0 && shape->values[i])
-                {
-                    CurrentShapeName = msStrdup(shape->values[i]);
-                    break;
-                }
-            }
+    LineStyle = NULL;
+    numLineStyle = 0;
+  }
+
+  if (shape) {
+    CurrentShapeIndex = shape->index;
+    if (pszLayerNameAttributeMetadata) {
+      for (int i=0; i<currentLayer->numitems; i++) {
+        if (strcasecmp(currentLayer->items[i], pszLayerNameAttributeMetadata) == 0 && shape->values[i]) {
+          CurrentShapeName = msStrdup(shape->values[i]);
+          break;
         }
+      }
     }
-    PlacemarkNode = NULL;
-    GeomNode = NULL;
+  }
+  PlacemarkNode = NULL;
+  GeomNode = NULL;
 
-    DescriptionNode = createDescriptionNode(shape);
+  DescriptionNode = createDescriptionNode(shape);
 
-    if( mElevationFromAttribute && shape->numvalues > mElevationAttributeIndex && 
-        mElevationAttributeIndex >= 0 && shape->values[mElevationAttributeIndex])
-    {
-        mCurrentElevationValue = atof( shape->values[mElevationAttributeIndex] );
-    }
+  if( mElevationFromAttribute && shape->numvalues > mElevationAttributeIndex &&
+      mElevationAttributeIndex >= 0 && shape->values[mElevationAttributeIndex]) {
+    mCurrentElevationValue = atof( shape->values[mElevationAttributeIndex] );
+  }
 
 
-    memset(SymbologyFlag, 0, NumSymbologyFlag);
+  memset(SymbologyFlag, 0, NumSymbologyFlag);
 }
 
 void KmlRenderer::endShape(imageObj*, shapeObj*)
 {
-    CurrentShapeIndex = -1;
-    if (CurrentShapeName)
-      msFree(CurrentShapeName);
-    CurrentShapeName = NULL;
+  CurrentShapeIndex = -1;
+  if (CurrentShapeName)
+    msFree(CurrentShapeName);
+  CurrentShapeName = NULL;
 }
 
 xmlNodePtr KmlRenderer::getGeomParentNode(const char *geomName)
 {
-    /*we do not need a multi-geometry for point layers*/
-    if (currentLayer->type != MS_LAYER_POINT && currentLayer->type != MS_LAYER_ANNOTATION && GeomNode)
-    {
-        /*placemark geometry already defined, we need multigeometry node*/
-        xmlNodePtr multiGeomNode = xmlNewNode(NULL, BAD_CAST "MultiGeometry");
-        xmlAddChild(multiGeomNode, GeomNode);
-        GeomNode = multiGeomNode;
-
-        xmlNodePtr geomNode = xmlNewChild(multiGeomNode, NULL, BAD_CAST geomName, NULL);
-        return geomNode;
-    }
-    else
-    {
-        GeomNode = xmlNewNode(NULL, BAD_CAST geomName);
-        return GeomNode;
-    }
+  /*we do not need a multi-geometry for point layers*/
+  if (currentLayer->type != MS_LAYER_POINT && currentLayer->type != MS_LAYER_ANNOTATION && GeomNode) {
+    /*placemark geometry already defined, we need multigeometry node*/
+    xmlNodePtr multiGeomNode = xmlNewNode(NULL, BAD_CAST "MultiGeometry");
+    xmlAddChild(multiGeomNode, GeomNode);
+    GeomNode = multiGeomNode;
+
+    xmlNodePtr geomNode = xmlNewChild(multiGeomNode, NULL, BAD_CAST geomName, NULL);
+    return geomNode;
+  } else {
+    GeomNode = xmlNewNode(NULL, BAD_CAST geomName);
+    return GeomNode;
+  }
 }
 
 char* KmlRenderer::lookupSymbolUrl(imageObj *img, symbolObj *symbol, symbolStyleObj *symstyle)
 {
-    char	symbolHexColor[32];
-    /*	
-        <Style id="randomColorIcon">
-        <IconStyle>
-        <color>ff00ff00</color>
-        <colorMode>random</colorMode>
-        <scale>1.1</scale>
-        <Icon>
-        <href>http://maps.google.com/mapfiles/kml/pal3/icon21.png</href>
-        </Icon>
-        </IconStyle>
-        </Style>
-    */
-
-    sprintf(symbolHexColor,"%02x%02x%02x%02x", symstyle->style->color.alpha, symstyle->style->color.blue,
-            symstyle->style->color.green, symstyle->style->color.red);
-    snprintf(SymbolName, sizeof(SymbolName), "symbol_%s_%.1f_%s", symbol->name, symstyle->scale, symbolHexColor);
-
-    char *symbolUrl = msLookupHashTable(StyleHashTable, SymbolName);
-    if (!symbolUrl)
-    {
-        char iconFileName[MS_MAXPATHLEN];
-        char iconUrl[MS_MAXPATHLEN];
-
-        if (img->imagepath)
-        {
-            char *tmpFileName = msTmpFile(NULL, MapPath, img->imagepath, "png");
-            snprintf(iconFileName, sizeof(iconFileName), "%s", tmpFileName);
-            msFree(tmpFileName);
-        }
-        else
-        {
-            sprintf(iconFileName, "symbol_%s_%.1f.%s", symbol->name, symstyle->scale, "png");
-        }
+  char  symbolHexColor[32];
+  /*
+      <Style id="randomColorIcon">
+      <IconStyle>
+      <color>ff00ff00</color>
+      <colorMode>random</colorMode>
+      <scale>1.1</scale>
+      <Icon>
+      <href>http://maps.google.com/mapfiles/kml/pal3/icon21.png</href>
+      </Icon>
+      </IconStyle>
+      </Style>
+  */
+
+  sprintf(symbolHexColor,"%02x%02x%02x%02x", symstyle->style->color.alpha, symstyle->style->color.blue,
+          symstyle->style->color.green, symstyle->style->color.red);
+  snprintf(SymbolName, sizeof(SymbolName), "symbol_%s_%.1f_%s", symbol->name, symstyle->scale, symbolHexColor);
+
+  char *symbolUrl = msLookupHashTable(StyleHashTable, SymbolName);
+  if (!symbolUrl) {
+    char iconFileName[MS_MAXPATHLEN];
+    char iconUrl[MS_MAXPATHLEN];
+
+    if (img->imagepath) {
+      char *tmpFileName = msTmpFile(NULL, MapPath, img->imagepath, "png");
+      snprintf(iconFileName, sizeof(iconFileName), "%s", tmpFileName);
+      msFree(tmpFileName);
+    } else {
+      sprintf(iconFileName, "symbol_%s_%.1f.%s", symbol->name, symstyle->scale, "png");
+    }
 
-        if (createIconImage(iconFileName, symbol, symstyle) != MS_SUCCESS)
-        {
-            char errMsg[512];
-            sprintf(errMsg, "Error creating icon file '%s'", iconFileName);
-            msSetError(MS_IOERR, errMsg, "KmlRenderer::lookupSymbolStyle()" );
-            return NULL;
-        }
+    if (createIconImage(iconFileName, symbol, symstyle) != MS_SUCCESS) {
+      char errMsg[512];
+      sprintf(errMsg, "Error creating icon file '%s'", iconFileName);
+      msSetError(MS_IOERR, errMsg, "KmlRenderer::lookupSymbolStyle()" );
+      return NULL;
+    }
 
-        if (img->imageurl)
-          sprintf(iconUrl, "%s%s.%s", img->imageurl, msGetBasename(iconFileName), "png");
-        else
-          snprintf(iconUrl, sizeof(iconUrl), "%s", iconFileName);
+    if (img->imageurl)
+      sprintf(iconUrl, "%s%s.%s", img->imageurl, msGetBasename(iconFileName), "png");
+    else
+      snprintf(iconUrl, sizeof(iconUrl), "%s", iconFileName);
 
-        hashObj *hash = msInsertHashTable(StyleHashTable, SymbolName, iconUrl);
-        symbolUrl = hash->data;
-    }
+    hashObj *hash = msInsertHashTable(StyleHashTable, SymbolName, iconUrl);
+    symbolUrl = hash->data;
+  }
 
-    return symbolUrl;
+  return symbolUrl;
 }
 
 char* KmlRenderer::lookupPlacemarkStyle()
 {
-    char	lineHexColor[32];
-    char	polygonHexColor[32];
-    char	labelHexColor[32];
-    char        *styleName=NULL;
-
-    styleName = msStringConcatenate(styleName, "style");
-
-    if (SymbologyFlag[Line])
-    {
-        /*
-          <LineStyle id="ID">
-          <!-- inherited from ColorStyle -->
-          <color>ffffffff</color>            <!-- kml:color -->
-          <colorMode>normal</colorMode>      <!-- colorModeEnum: normal or random -->
-
-          <!-- specific to LineStyle -->
-          <width>1</width>                   <!-- float -->
-          </LineStyle>
-        */
-    
-        for (int i=0; i<numLineStyle; i++)
-        {
-            if (currentLayer && currentLayer->opacity > 0 && currentLayer->opacity < 100 &&
-                LineStyle[i].color->alpha == 255)
-              LineStyle[i].color->alpha = MS_NINT(currentLayer->opacity*2.55);
-              
-            sprintf(lineHexColor,"%02x%02x%02x%02x", LineStyle[i].color->alpha, LineStyle[0].color->blue,
-                    LineStyle[i].color->green, LineStyle[i].color->red);
-
-            char lineStyleName[32];
-            sprintf(lineStyleName, "_line_%s_w%.1f", lineHexColor, LineStyle[i].width);
-            styleName = msStringConcatenate(styleName, lineStyleName);
-        }
-    }
+  char  lineHexColor[32];
+  char  polygonHexColor[32];
+  char  labelHexColor[32];
+  char        *styleName=NULL;
 
-    if (SymbologyFlag[Polygon])
-    {
-        /*
-          <PolyStyle id="ID">
-          <!-- inherited from ColorStyle -->
-          <color>ffffffff</color>            <!-- kml:color -->
-          <colorMode>normal</colorMode>      <!-- kml:colorModeEnum: normal or random -->
-
-          <!-- specific to PolyStyle -->
-          <fill>1</fill>                     <!-- boolean -->
-          <outline>1</outline>               <!-- boolean -->
-          </PolyStyle>
-        */
-
-        if (currentLayer && currentLayer->opacity > 0 && currentLayer->opacity < 100 &&
-            PolygonColor.alpha == 255)
-          PolygonColor.alpha = MS_NINT(currentLayer->opacity*2.55);
-        sprintf(polygonHexColor,"%02x%02x%02x%02x", PolygonColor.alpha, PolygonColor.blue, PolygonColor.green, PolygonColor.red);
-
-        char polygonStyleName[64];
-        sprintf(polygonStyleName, "_polygon_%s", polygonHexColor);
-        styleName = msStringConcatenate(styleName, polygonStyleName);
-    }
+  styleName = msStringConcatenate(styleName, "style");
+
+  if (SymbologyFlag[Line]) {
+    /*
+      <LineStyle id="ID">
+      <!-- inherited from ColorStyle -->
+      <color>ffffffff</color>            <!-- kml:color -->
+      <colorMode>normal</colorMode>      <!-- colorModeEnum: normal or random -->
+
+      <!-- specific to LineStyle -->
+      <width>1</width>                   <!-- float -->
+      </LineStyle>
+    */
 
-    if (SymbologyFlag[Label])
-    {
-        /*
-          <LabelStyle id="ID">
-          <!-- inherited from ColorStyle -->
-          <color>ffffffff</color>            <!-- kml:color -->
-          <colorMode>normal</colorMode>      <!-- kml:colorModeEnum: normal or random -->
-
-          <!-- specific to LabelStyle -->
-          <scale>1</scale>                   <!-- float -->
-          </LabelStyle>
-        */
-
-        if (currentLayer && currentLayer->opacity > 0 && currentLayer->opacity < 100 &&
-            LabelStyle.color->alpha == 255)
-          LabelStyle.color->alpha = MS_NINT(currentLayer->opacity*2.55);
-        sprintf(labelHexColor,"%02x%02x%02x%02x", LabelStyle.color->alpha, LabelStyle.color->blue, LabelStyle.color->green, LabelStyle.color->red);
-
-        // __TODO__ add label scale
-
-        char labelStyleName[64];
-        sprintf(labelStyleName, "_label_%s", labelHexColor);
-        styleName = msStringConcatenate(styleName, labelStyleName);
+    for (int i=0; i<numLineStyle; i++) {
+      if (currentLayer && currentLayer->opacity > 0 && currentLayer->opacity < 100 &&
+          LineStyle[i].color->alpha == 255)
+        LineStyle[i].color->alpha = MS_NINT(currentLayer->opacity*2.55);
+
+      sprintf(lineHexColor,"%02x%02x%02x%02x", LineStyle[i].color->alpha, LineStyle[0].color->blue,
+              LineStyle[i].color->green, LineStyle[i].color->red);
+
+      char lineStyleName[32];
+      sprintf(lineStyleName, "_line_%s_w%.1f", lineHexColor, LineStyle[i].width);
+      styleName = msStringConcatenate(styleName, lineStyleName);
     }
+  }
 
-    if (SymbologyFlag[Symbol])
-    {
-        /*	
-		<Style id="randomColorIcon">
-                <IconStyle>
-                <color>ff00ff00</color>
-                <colorMode>random</colorMode>
-                <scale>1.1</scale>
-                <Icon>
-                <href>http://maps.google.com/mapfiles/kml/pal3/icon21.png</href>
-                </Icon>
-                </IconStyle>
-		</Style>
-        */
-
-        /* __TODO__ add label scale */
-
-        styleName = msStringConcatenate(styleName, "_");
-        styleName = msStringConcatenate(styleName, SymbolName);
+  if (SymbologyFlag[Polygon]) {
+    /*
+      <PolyStyle id="ID">
+      <!-- inherited from ColorStyle -->
+      <color>ffffffff</color>            <!-- kml:color -->
+      <colorMode>normal</colorMode>      <!-- kml:colorModeEnum: normal or random -->
+
+      <!-- specific to PolyStyle -->
+      <fill>1</fill>                     <!-- boolean -->
+      <outline>1</outline>               <!-- boolean -->
+      </PolyStyle>
+    */
+
+    if (currentLayer && currentLayer->opacity > 0 && currentLayer->opacity < 100 &&
+        PolygonColor.alpha == 255)
+      PolygonColor.alpha = MS_NINT(currentLayer->opacity*2.55);
+    sprintf(polygonHexColor,"%02x%02x%02x%02x", PolygonColor.alpha, PolygonColor.blue, PolygonColor.green, PolygonColor.red);
+
+    char polygonStyleName[64];
+    sprintf(polygonStyleName, "_polygon_%s", polygonHexColor);
+    styleName = msStringConcatenate(styleName, polygonStyleName);
+  }
+
+  if (SymbologyFlag[Label]) {
+    /*
+      <LabelStyle id="ID">
+      <!-- inherited from ColorStyle -->
+      <color>ffffffff</color>            <!-- kml:color -->
+      <colorMode>normal</colorMode>      <!-- kml:colorModeEnum: normal or random -->
+
+      <!-- specific to LabelStyle -->
+      <scale>1</scale>                   <!-- float -->
+      </LabelStyle>
+    */
+
+    if (currentLayer && currentLayer->opacity > 0 && currentLayer->opacity < 100 &&
+        LabelStyle.color->alpha == 255)
+      LabelStyle.color->alpha = MS_NINT(currentLayer->opacity*2.55);
+    sprintf(labelHexColor,"%02x%02x%02x%02x", LabelStyle.color->alpha, LabelStyle.color->blue, LabelStyle.color->green, LabelStyle.color->red);
+
+    // __TODO__ add label scale
+
+    char labelStyleName[64];
+    sprintf(labelStyleName, "_label_%s", labelHexColor);
+    styleName = msStringConcatenate(styleName, labelStyleName);
+  }
+
+  if (SymbologyFlag[Symbol]) {
+    /*
+    <Style id="randomColorIcon">
+            <IconStyle>
+            <color>ff00ff00</color>
+            <colorMode>random</colorMode>
+            <scale>1.1</scale>
+            <Icon>
+            <href>http://maps.google.com/mapfiles/kml/pal3/icon21.png</href>
+            </Icon>
+            </IconStyle>
+    </Style>
+    */
+
+    /* __TODO__ add label scale */
+
+    styleName = msStringConcatenate(styleName, "_");
+    styleName = msStringConcatenate(styleName, SymbolName);
+  }
+
+  char *styleUrl = msLookupHashTable(StyleHashTable, styleName);
+  if (!styleUrl) {
+    char *styleValue=NULL;
+    styleValue = msStringConcatenate(styleValue, "#");
+    styleValue = msStringConcatenate(styleValue, styleName);
+    hashObj *hash = msInsertHashTable(StyleHashTable, styleName, styleValue);
+    styleUrl = hash->data;
+    msFree(styleValue);
+
+    /* Insert new Style node into Document node*/
+    xmlNodePtr styleNode = xmlNewChild(DocNode, NULL, BAD_CAST "Style", NULL);
+    xmlNewProp(styleNode, BAD_CAST "id", BAD_CAST styleName);
+
+    if (SymbologyFlag[Polygon]) {
+      xmlNodePtr polyStyleNode = xmlNewChild(styleNode, NULL, BAD_CAST "PolyStyle", NULL);
+      xmlNewChild(polyStyleNode, NULL, BAD_CAST "color", BAD_CAST polygonHexColor);
     }
 
-    char *styleUrl = msLookupHashTable(StyleHashTable, styleName);
-    if (!styleUrl)
-    {
-        char *styleValue=NULL;
-        styleValue = msStringConcatenate(styleValue, "#");
-        styleValue = msStringConcatenate(styleValue, styleName);
-        hashObj *hash = msInsertHashTable(StyleHashTable, styleName, styleValue);
-        styleUrl = hash->data;
-        msFree(styleValue);
-
-        /* Insert new Style node into Document node*/
-        xmlNodePtr styleNode = xmlNewChild(DocNode, NULL, BAD_CAST "Style", NULL);
-        xmlNewProp(styleNode, BAD_CAST "id", BAD_CAST styleName);
-
-        if (SymbologyFlag[Polygon])
-        {
-            xmlNodePtr polyStyleNode = xmlNewChild(styleNode, NULL, BAD_CAST "PolyStyle", NULL);
-            xmlNewChild(polyStyleNode, NULL, BAD_CAST "color", BAD_CAST polygonHexColor);
-        }
+    if (SymbologyFlag[Line]) {
+      for (int i=0; i<numLineStyle; i++) {
+        xmlNodePtr lineStyleNode = xmlNewChild(styleNode, NULL, BAD_CAST "LineStyle", NULL);
+        sprintf(lineHexColor,"%02x%02x%02x%02x", LineStyle[i].color->alpha, LineStyle[i].color->blue,
+                LineStyle[i].color->green, LineStyle[i].color->red);
+        xmlNewChild(lineStyleNode, NULL, BAD_CAST "color", BAD_CAST lineHexColor);
+
+        char width[16];
+        sprintf(width, "%.1f", LineStyle[i].width);
+        xmlNewChild(lineStyleNode, NULL, BAD_CAST "width", BAD_CAST width);
+      }
+    }
 
-        if (SymbologyFlag[Line])
-        {
-            for (int i=0; i<numLineStyle; i++)
-            {
-                xmlNodePtr lineStyleNode = xmlNewChild(styleNode, NULL, BAD_CAST "LineStyle", NULL);
-                sprintf(lineHexColor,"%02x%02x%02x%02x", LineStyle[i].color->alpha, LineStyle[i].color->blue,
-                        LineStyle[i].color->green, LineStyle[i].color->red);
-                xmlNewChild(lineStyleNode, NULL, BAD_CAST "color", BAD_CAST lineHexColor);
-
-                char width[16];
-                sprintf(width, "%.1f", LineStyle[i].width);
-                xmlNewChild(lineStyleNode, NULL, BAD_CAST "width", BAD_CAST width);
-            }
-        }
+    if (SymbologyFlag[Symbol]) {
+      xmlNodePtr iconStyleNode = xmlNewChild(styleNode, NULL, BAD_CAST "IconStyle", NULL);
 
-        if (SymbologyFlag[Symbol])
-        {
-            xmlNodePtr iconStyleNode = xmlNewChild(styleNode, NULL, BAD_CAST "IconStyle", NULL);
+      xmlNodePtr iconNode = xmlNewChild(iconStyleNode, NULL, BAD_CAST "Icon", NULL);
+      xmlNewChild(iconNode, NULL, BAD_CAST "href", BAD_CAST SymbolUrl);
 
-            xmlNodePtr iconNode = xmlNewChild(iconStyleNode, NULL, BAD_CAST "Icon", NULL);
-            xmlNewChild(iconNode, NULL, BAD_CAST "href", BAD_CAST SymbolUrl);
+      /*char scale[16];
+        sprintf(scale, "%.1f", style->scale);
+        xmlNewChild(iconStyleNode, NULL, BAD_CAST "scale", BAD_CAST scale);*/
+    } else {
+      const char *value=msLookupHashTable(&currentLayer->metadata, "kml_default_symbol_href");
+      if (value && strlen(value) > 0) {
+        xmlNodePtr iconStyleNode = xmlNewChild(styleNode, NULL, BAD_CAST "IconStyle", NULL);
 
-            /*char scale[16];
-              sprintf(scale, "%.1f", style->scale);
-              xmlNewChild(iconStyleNode, NULL, BAD_CAST "scale", BAD_CAST scale);*/
-        }
-        else
-        {
-            const char *value=msLookupHashTable(&currentLayer->metadata, "kml_default_symbol_href");
-            if (value && strlen(value) > 0)
-            {
-                xmlNodePtr iconStyleNode = xmlNewChild(styleNode, NULL, BAD_CAST "IconStyle", NULL);
-
-                xmlNodePtr iconNode = xmlNewChild(iconStyleNode, NULL, BAD_CAST "Icon", NULL);
-                xmlNewChild(iconNode, NULL, BAD_CAST "href", BAD_CAST value);
-            }
-        }
+        xmlNodePtr iconNode = xmlNewChild(iconStyleNode, NULL, BAD_CAST "Icon", NULL);
+        xmlNewChild(iconNode, NULL, BAD_CAST "href", BAD_CAST value);
+      }
+    }
 
-        if (SymbologyFlag[Label])
-        {
-            xmlNodePtr labelStyleNode = xmlNewChild(styleNode, NULL, BAD_CAST "LabelStyle", NULL);
-            xmlNewChild(labelStyleNode, NULL, BAD_CAST "color", BAD_CAST labelHexColor);
+    if (SymbologyFlag[Label]) {
+      xmlNodePtr labelStyleNode = xmlNewChild(styleNode, NULL, BAD_CAST "LabelStyle", NULL);
+      xmlNewChild(labelStyleNode, NULL, BAD_CAST "color", BAD_CAST labelHexColor);
 
-            /*char scale[16];
-              sprintf(scale, "%.1f", style->scale);
-              xmlNewChild(iconStyleNode, NULL, BAD_CAST "scale", BAD_CAST scale);*/
-        }
+      /*char scale[16];
+        sprintf(scale, "%.1f", style->scale);
+        xmlNewChild(iconStyleNode, NULL, BAD_CAST "scale", BAD_CAST scale);*/
     }
+  }
 
-    if (styleName)
-      msFree(styleName);
+  if (styleName)
+    msFree(styleName);
 
-    return styleUrl;
+  return styleUrl;
 }
 
 void KmlRenderer::flushPlacemark()
 {
-    if (PlacemarkNode)
-    {
-        char *styleUrl = lookupPlacemarkStyle();
-        xmlNewChild(PlacemarkNode, NULL, BAD_CAST "styleUrl", BAD_CAST styleUrl);
-        
-        if (DescriptionNode)
-          xmlAddChild(PlacemarkNode, DescriptionNode);
-        
-        if (GeomNode)
-          xmlAddChild(PlacemarkNode, GeomNode);
-    }       
+  if (PlacemarkNode) {
+    char *styleUrl = lookupPlacemarkStyle();
+    xmlNewChild(PlacemarkNode, NULL, BAD_CAST "styleUrl", BAD_CAST styleUrl);
+
+    if (DescriptionNode)
+      xmlAddChild(PlacemarkNode, DescriptionNode);
+
+    if (GeomNode)
+      xmlAddChild(PlacemarkNode, GeomNode);
+  }
 }
 
 
 xmlNodePtr KmlRenderer::createDescriptionNode(shapeObj *shape)
 {
-    /*
-      <description>
-      <![CDATA[
-      special characters here
-      ]]> 
-      <description>
-    */
-
-
-    /*description nodes for vector layers:
-      - if kml_description is set, use it
-      - if not, dump the attributes */
-
-    if (pszLayerDescMetadata)
-    {
-        char *pszTmp=NULL;
-        char *pszTmpDesc = NULL;
-        size_t bufferSize = 0;
-        pszTmpDesc = msStrdup(pszLayerDescMetadata);
-        
-        for (int i=0; i<currentLayer->numitems; i++)
-        {
-            bufferSize = strlen(currentLayer->items[i]) + 3;
-            pszTmp = (char *)msSmallMalloc(bufferSize);
-            snprintf(pszTmp, bufferSize, "%%%s%%",currentLayer->items[i]);
-            if (strcasestr(pszTmpDesc, pszTmp))
-              pszTmpDesc = msCaseReplaceSubstring(pszTmpDesc,  pszTmp, shape->values[i]);
-            msFree(pszTmp);
-        }   
-        xmlNodePtr descriptionNode = xmlNewNode(NULL, BAD_CAST "description");
-        xmlNodeAddContent(descriptionNode, BAD_CAST pszTmpDesc);       
-        msFree(pszTmpDesc);
-        return descriptionNode;
+  /*
+    <description>
+    <![CDATA[
+    special characters here
+    ]]>
+    <description>
+  */
+
+
+  /*description nodes for vector layers:
+    - if kml_description is set, use it
+    - if not, dump the attributes */
+
+  if (pszLayerDescMetadata) {
+    char *pszTmp=NULL;
+    char *pszTmpDesc = NULL;
+    size_t bufferSize = 0;
+    pszTmpDesc = msStrdup(pszLayerDescMetadata);
+
+    for (int i=0; i<currentLayer->numitems; i++) {
+      bufferSize = strlen(currentLayer->items[i]) + 3;
+      pszTmp = (char *)msSmallMalloc(bufferSize);
+      snprintf(pszTmp, bufferSize, "%%%s%%",currentLayer->items[i]);
+      if (strcasestr(pszTmpDesc, pszTmp))
+        pszTmpDesc = msCaseReplaceSubstring(pszTmpDesc,  pszTmp, shape->values[i]);
+      msFree(pszTmp);
     }
-    else if ((papszLayerIncludeItems && nIncludeItems > 0) || 
-             (papszLayerExcludeItems && nExcludeItems > 0))
-    {
-        /* -------------------------------------------------------------------- */
-        /*      preffered way is to use the ExtendedData tag (#3728)            */
-        /*      http://code.google.com/apis/kml/documentation/extendeddata.html */
-        /* -------------------------------------------------------------------- */
-        
-        xmlNodePtr extendedDataNode = xmlNewNode(NULL, BAD_CAST "ExtendedData");
-        xmlNodePtr dataNode = NULL; 
-        const char*pszAlias=NULL;
-        int bIncludeAll = MS_FALSE;
-
-        if(papszLayerIncludeItems && nIncludeItems == 1 &&
-           strcasecmp(papszLayerIncludeItems[0], "all") == 0)
-          bIncludeAll = MS_TRUE;
-           
-        for (int i=0; i<currentLayer->numitems; i++)
-        {
-            int j=0,k=0;
-            
-            /*TODO optimize to calculate this only once per layer*/
-            for (j=0; j<nIncludeItems;j++)
-            {
-                if (strcasecmp(currentLayer->items[i], papszLayerIncludeItems[j]) == 0)
-                  break;
-            }
-            if (j<nIncludeItems || bIncludeAll)
-            {
-                if (papszLayerExcludeItems && nExcludeItems > 0)
-                {
-                    for (k=0; k<nExcludeItems;k++)
-                    {
-                        if (strcasecmp(currentLayer->items[i], papszLayerExcludeItems[k]) == 0)
-                          break;
-                    }
-                }
-                if (nExcludeItems == 0 || k == nExcludeItems)
-                {
-                    dataNode = xmlNewNode(NULL, BAD_CAST "Data");
-                    xmlNewProp(dataNode, BAD_CAST "name", BAD_CAST  currentLayer->items[i]);
-                    pszAlias = getAliasName(currentLayer, currentLayer->items[i], "GO");
-                    if (pszAlias)
-                      xmlNewChild(dataNode, NULL, BAD_CAST "displayName", BAD_CAST  pszAlias);
-                    else
-                      xmlNewChild(dataNode, NULL, BAD_CAST "displayName", BAD_CAST  currentLayer->items[i]);
-                    if (shape->values[i] && strlen(shape->values[i]))
-                      xmlNewChild(dataNode, NULL, BAD_CAST "value", BAD_CAST  shape->values[i]);
-                    else
-                      xmlNewChild(dataNode, NULL, BAD_CAST "value", NULL);
-                    xmlAddChild(extendedDataNode, dataNode);
-                }
-            }
+    xmlNodePtr descriptionNode = xmlNewNode(NULL, BAD_CAST "description");
+    xmlNodeAddContent(descriptionNode, BAD_CAST pszTmpDesc);
+    msFree(pszTmpDesc);
+    return descriptionNode;
+  } else if ((papszLayerIncludeItems && nIncludeItems > 0) ||
+             (papszLayerExcludeItems && nExcludeItems > 0)) {
+    /* -------------------------------------------------------------------- */
+    /*      preffered way is to use the ExtendedData tag (#3728)            */
+    /*      http://code.google.com/apis/kml/documentation/extendeddata.html */
+    /* -------------------------------------------------------------------- */
+
+    xmlNodePtr extendedDataNode = xmlNewNode(NULL, BAD_CAST "ExtendedData");
+    xmlNodePtr dataNode = NULL;
+    const char*pszAlias=NULL;
+    int bIncludeAll = MS_FALSE;
+
+    if(papszLayerIncludeItems && nIncludeItems == 1 &&
+        strcasecmp(papszLayerIncludeItems[0], "all") == 0)
+      bIncludeAll = MS_TRUE;
+
+    for (int i=0; i<currentLayer->numitems; i++) {
+      int j=0,k=0;
+
+      /*TODO optimize to calculate this only once per layer*/
+      for (j=0; j<nIncludeItems; j++) {
+        if (strcasecmp(currentLayer->items[i], papszLayerIncludeItems[j]) == 0)
+          break;
+      }
+      if (j<nIncludeItems || bIncludeAll) {
+        if (papszLayerExcludeItems && nExcludeItems > 0) {
+          for (k=0; k<nExcludeItems; k++) {
+            if (strcasecmp(currentLayer->items[i], papszLayerExcludeItems[k]) == 0)
+              break;
+          }
+        }
+        if (nExcludeItems == 0 || k == nExcludeItems) {
+          dataNode = xmlNewNode(NULL, BAD_CAST "Data");
+          xmlNewProp(dataNode, BAD_CAST "name", BAD_CAST  currentLayer->items[i]);
+          pszAlias = getAliasName(currentLayer, currentLayer->items[i], "GO");
+          if (pszAlias)
+            xmlNewChild(dataNode, NULL, BAD_CAST "displayName", BAD_CAST  pszAlias);
+          else
+            xmlNewChild(dataNode, NULL, BAD_CAST "displayName", BAD_CAST  currentLayer->items[i]);
+          if (shape->values[i] && strlen(shape->values[i]))
+            xmlNewChild(dataNode, NULL, BAD_CAST "value", BAD_CAST  shape->values[i]);
+          else
+            xmlNewChild(dataNode, NULL, BAD_CAST "value", NULL);
+          xmlAddChild(extendedDataNode, dataNode);
         }
+      }
+    }
 
-        return extendedDataNode;
+    return extendedDataNode;
 
-        
-    }
 
-    return NULL;
+  }
+
+  return NULL;
 }
 
 void KmlRenderer::addLineStyleToList(strokeStyleObj *style)
 {
-    /*actually this is not necessary. kml only uses the last LineStyle
-      so we should not bother keeping them all*/
-    int i =0;
-    for (i=0; i<numLineStyle; i++)
-    {
-        if (style->width == LineStyle[i].width &&
-            LineStyle[i].color->alpha == style->color->alpha &&
-            LineStyle[i].color->red == style->color->red &&
-            LineStyle[i].color->green == style->color->green &&
-            LineStyle[i].color->blue == style->color->blue)
-          break;
-    }
-    if (i == numLineStyle)
-    {
-        numLineStyle++;
-        if (LineStyle == NULL)
-          LineStyle = (strokeStyleObj *)msSmallMalloc(sizeof(strokeStyleObj));
-        else
-          LineStyle = (strokeStyleObj *)msSmallRealloc(LineStyle, sizeof(strokeStyleObj)*numLineStyle);
-
-        memcpy(&LineStyle[numLineStyle-1], style, sizeof(strokeStyleObj));
-    }
+  /*actually this is not necessary. kml only uses the last LineStyle
+    so we should not bother keeping them all*/
+  int i =0;
+  for (i=0; i<numLineStyle; i++) {
+    if (style->width == LineStyle[i].width &&
+        LineStyle[i].color->alpha == style->color->alpha &&
+        LineStyle[i].color->red == style->color->red &&
+        LineStyle[i].color->green == style->color->green &&
+        LineStyle[i].color->blue == style->color->blue)
+      break;
+  }
+  if (i == numLineStyle) {
+    numLineStyle++;
+    if (LineStyle == NULL)
+      LineStyle = (strokeStyleObj *)msSmallMalloc(sizeof(strokeStyleObj));
+    else
+      LineStyle = (strokeStyleObj *)msSmallRealloc(LineStyle, sizeof(strokeStyleObj)*numLineStyle);
+
+    memcpy(&LineStyle[numLineStyle-1], style, sizeof(strokeStyleObj));
+  }
 
 }
 
diff --git a/mapkmlrenderer.h b/mapkmlrenderer.h
index 3f95f7e..47a6a87 100644
--- a/mapkmlrenderer.h
+++ b/mapkmlrenderer.h
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id$ 
+ * $Id$
  *
  * Project:  MapServer
  * Purpose:  Headers for mapkmlrenderer.cpp Google Earth KML output
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -39,136 +39,136 @@
 
 class KmlRenderer
 {
-  private:
-    const char *pszLayerDescMetadata; /*if the kml_description is set*/
-    char **papszLayerIncludeItems;
-    int nIncludeItems;
-    char **papszLayerExcludeItems;
-    int nExcludeItems;
-    char *pszLayerNameAttributeMetadata;
+private:
+  const char *pszLayerDescMetadata; /*if the kml_description is set*/
+  char **papszLayerIncludeItems;
+  int nIncludeItems;
+  char **papszLayerExcludeItems;
+  int nExcludeItems;
+  char *pszLayerNameAttributeMetadata;
 
-  protected:
+protected:
 
-    // map properties
-    int				Width, Height;
-    rectObj			MapExtent;
-    double			MapCellsize;
-    colorObj		BgColor;
-    char			MapPath[MS_MAXPATHLEN];
+  // map properties
+  int       Width, Height;
+  rectObj     MapExtent;
+  double      MapCellsize;
+  colorObj    BgColor;
+  char      MapPath[MS_MAXPATHLEN];
 
-    // xml nodes pointers
-    xmlDocPtr	XmlDoc;
-    xmlNodePtr	DocNode;
-    xmlNodePtr	LayerNode;
-    xmlNodePtr	GroundOverlayNode;
+  // xml nodes pointers
+  xmlDocPtr XmlDoc;
+  xmlNodePtr  DocNode;
+  xmlNodePtr  LayerNode;
+  xmlNodePtr  GroundOverlayNode;
 
-    xmlNodePtr	PlacemarkNode;
-    xmlNodePtr	GeomNode;
-    xmlNodePtr	DescriptionNode;
+  xmlNodePtr  PlacemarkNode;
+  xmlNodePtr  GeomNode;
+  xmlNodePtr  DescriptionNode;
 
-    int	        CurrentShapeIndex;
-    int	        CurrentDrawnShapeIndex;
-    char            *CurrentShapeName;
-    char		**Items;
-    int			NumItems;
-    int			DumpAttributes;
+  int         CurrentShapeIndex;
+  int         CurrentDrawnShapeIndex;
+  char            *CurrentShapeName;
+  char    **Items;
+  int     NumItems;
+  int     DumpAttributes;
 
-    // placemark symbology
-    hashTableObj	*StyleHashTable;
+  // placemark symbology
+  hashTableObj  *StyleHashTable;
 
-    labelStyleObj	        LabelStyle;
-    strokeStyleObj	        *LineStyle;
-    int                     numLineStyle;
-    colorObj		PolygonColor;
+  labelStyleObj         LabelStyle;
+  strokeStyleObj          *LineStyle;
+  int                     numLineStyle;
+  colorObj    PolygonColor;
 
-    char			SymbolName[128];
-    char			SymbolUrl[128];
+  char      SymbolName[128];
+  char      SymbolUrl[128];
 
-    enum			{ NumSymbologyFlag = 4};
-    char			SymbologyFlag[NumSymbologyFlag];
+  enum      { NumSymbologyFlag = 4};
+  char      SymbologyFlag[NumSymbologyFlag];
 
-    enum			symbFlagsEnum { Label, Line, Polygon, Symbol };
+  enum      symbFlagsEnum { Label, Line, Polygon, Symbol };
 
-    int				FirstLayer;
-        
-    mapObj                  *map;
-    layerObj                *currentLayer;
+  int       FirstLayer;
 
-    int				AltitudeMode;
-    int				Tessellate;
-    int				Extrude;
+  mapObj                  *map;
+  layerObj                *currentLayer;
 
-    enum altitudeModeEnum { undefined, clampToGround, relativeToGround, absolute };
-    /**True if elevation is taken from a feature attribute*/
-    bool mElevationFromAttribute;
-    /**Attribute index of elevation (or -1 if elevation is not attribute driven*/
-    int mElevationAttributeIndex;
-    double mCurrentElevationValue;
- 	
+  int       AltitudeMode;
+  int       Tessellate;
+  int       Extrude;
 
-    outputFormatObj *aggFormat;
+  enum altitudeModeEnum { undefined, clampToGround, relativeToGround, absolute };
+  /**True if elevation is taken from a feature attribute*/
+  bool mElevationFromAttribute;
+  /**Attribute index of elevation (or -1 if elevation is not attribute driven*/
+  int mElevationAttributeIndex;
+  double mCurrentElevationValue;
 
-  protected:
 
-    imageObj* createInternalImage();
-    xmlNodePtr createPlacemarkNode(xmlNodePtr parentNode, char *styleUrl);
-    xmlNodePtr createGroundOverlayNode(xmlNodePtr parentNode, char *imageHref, layerObj *layer);
-    xmlNodePtr createDescriptionNode(shapeObj *shape);
+  outputFormatObj *aggFormat;
 
-    char* lookupSymbolUrl(imageObj *img, symbolObj *symbol, symbolStyleObj *style);
+protected:
 
-    void addCoordsNode(xmlNodePtr parentNode, pointObj *pts, int numPts);
+  imageObj* createInternalImage();
+  xmlNodePtr createPlacemarkNode(xmlNodePtr parentNode, char *styleUrl);
+  xmlNodePtr createGroundOverlayNode(xmlNodePtr parentNode, char *imageHref, layerObj *layer);
+  xmlNodePtr createDescriptionNode(shapeObj *shape);
 
-    void setupRenderingParams(hashTableObj *layerMetadata);
-    void addAddRenderingSpecifications(xmlNodePtr node);
+  char* lookupSymbolUrl(imageObj *img, symbolObj *symbol, symbolStyleObj *style);
 
-    int checkProjection(mapObj *map);
+  void addCoordsNode(xmlNodePtr parentNode, pointObj *pts, int numPts);
 
-    int createIconImage(char *fileName, symbolObj *symbol, symbolStyleObj *style);
+  void setupRenderingParams(hashTableObj *layerMetadata);
+  void addAddRenderingSpecifications(xmlNodePtr node);
 
-    void renderSymbol(imageObj *img, double x, double y, symbolObj *symbol, symbolStyleObj *style);
+  int checkProjection(mapObj *map);
 
-    //////////////////////////////////////////////////////////////////////////////
+  int createIconImage(char *fileName, symbolObj *symbol, symbolStyleObj *style);
 
-    void renderLineVector(imageObj *img, shapeObj *p, strokeStyleObj *style);
-    void renderPolygonVector(imageObj *img, shapeObj *p, colorObj *color);
-    void renderGlyphsVector(imageObj *img, double x, double y, labelStyleObj *style, char *text);
+  void renderSymbol(imageObj *img, double x, double y, symbolObj *symbol, symbolStyleObj *style);
 
-    char* lookupPlacemarkStyle();
-    void flushPlacemark();
-    xmlNodePtr getGeomParentNode(const char *geomName);
-    char* getLayerName(layerObj *layer);
-    void processLayer(layerObj *layer, outputFormatObj *format);
-    void addLineStyleToList(strokeStyleObj *style);
-    const char *getAliasName(layerObj *lp, char *pszItemName, const char *namespaces);
+  //////////////////////////////////////////////////////////////////////////////
 
-  public:
+  void renderLineVector(imageObj *img, shapeObj *p, strokeStyleObj *style);
+  void renderPolygonVector(imageObj *img, shapeObj *p, colorObj *color);
+  void renderGlyphsVector(imageObj *img, double x, double y, labelStyleObj *style, char *text);
 
-    KmlRenderer(int width, int height, outputFormatObj *format, colorObj* color = NULL);
-    virtual ~KmlRenderer();
+  char* lookupPlacemarkStyle();
+  void flushPlacemark();
+  xmlNodePtr getGeomParentNode(const char *geomName);
+  char* getLayerName(layerObj *layer);
+  void processLayer(layerObj *layer, outputFormatObj *format);
+  void addLineStyleToList(strokeStyleObj *style);
+  const char *getAliasName(layerObj *lp, char *pszItemName, const char *namespaces);
 
-    imageObj* createImage(int width, int height, outputFormatObj *format, colorObj* bg);
-    int saveImage(imageObj *img, FILE *fp, outputFormatObj *format);
-    
-    int startNewLayer(imageObj *img, layerObj *layer);
-    int closeNewLayer(imageObj *img, layerObj *layer);
+public:
 
-    void startShape(imageObj *img, shapeObj *shape);
-    void endShape(imageObj *img, shapeObj *shape);
+  KmlRenderer(int width, int height, outputFormatObj *format, colorObj* color = NULL);
+  virtual ~KmlRenderer();
 
-    void renderLine(imageObj *img, shapeObj *p, strokeStyleObj *style);
-    void renderPolygon(imageObj *img, shapeObj *p, colorObj *color);
+  imageObj* createImage(int width, int height, outputFormatObj *format, colorObj* bg);
+  int saveImage(imageObj *img, FILE *fp, outputFormatObj *format);
 
-    void renderGlyphs(imageObj *img, double x, double y, labelStyleObj *style, char *text);
+  int startNewLayer(imageObj *img, layerObj *layer);
+  int closeNewLayer(imageObj *img, layerObj *layer);
 
-    // Symbols
-    void renderPixmapSymbol(imageObj *img, double x, double y, symbolObj *symbol, symbolStyleObj *style);
-    void renderVectorSymbol(imageObj *img, double x, double y, symbolObj *symbol, symbolStyleObj *style);
-    void renderEllipseSymbol(imageObj *img, double x, double y, symbolObj *symbol, symbolStyleObj *style);
-    void renderTruetypeSymbol(imageObj *img, double x, double y, symbolObj *symbol, symbolStyleObj *style);
+  void startShape(imageObj *img, shapeObj *shape);
+  void endShape(imageObj *img, shapeObj *shape);
 
-    int getTruetypeTextBBox(imageObj *img,char *font, double size, char *string, rectObj *rect, double **advances);
-    int mergeRasterBuffer(imageObj *image, rasterBufferObj *rb);
+  void renderLine(imageObj *img, shapeObj *p, strokeStyleObj *style);
+  void renderPolygon(imageObj *img, shapeObj *p, colorObj *color);
+
+  void renderGlyphs(imageObj *img, double x, double y, labelStyleObj *style, char *text);
+
+  // Symbols
+  void renderPixmapSymbol(imageObj *img, double x, double y, symbolObj *symbol, symbolStyleObj *style);
+  void renderVectorSymbol(imageObj *img, double x, double y, symbolObj *symbol, symbolStyleObj *style);
+  void renderEllipseSymbol(imageObj *img, double x, double y, symbolObj *symbol, symbolStyleObj *style);
+  void renderTruetypeSymbol(imageObj *img, double x, double y, symbolObj *symbol, symbolStyleObj *style);
+
+  int getTruetypeTextBBox(imageObj *img,char **fonts, int numfonts, double size, char *string, rectObj *rect, double **advances);
+  int mergeRasterBuffer(imageObj *image, rasterBufferObj *rb);
 };
 
 #endif /* USE_KML */
diff --git a/maplabel.c b/maplabel.c
index a911e0c..cf97176 100644
--- a/maplabel.c
+++ b/maplabel.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -30,15 +30,10 @@
 /*
 ** maplabel.c: Routines to enable text drawing, BITMAP or TRUETYPE.
 */
-#include <gdfonts.h>
-#include <gdfontl.h>
-#include <gdfontt.h>
-#include <gdfontmb.h>
-#include <gdfontg.h>
 
 #include "mapserver.h"
 
-MS_CVSID("$Id$")
+
 
 
 /**
@@ -56,253 +51,450 @@ MS_CVSID("$Id$")
  * for a summary of how wrap/maxlength interact on the result
  * of the text transformation
  */
-char *msWrapText(labelObj *label, char *text) {
-    char wrap;
-    int maxlength;
-    if(!text) /*not an error if no text*/
-        return text;
-    wrap = label->wrap;
-    maxlength = label->maxlength;
-    if(maxlength == 0) {
-        if(wrap!='\0') {
-            /* if maxlength = 0 *and* a wrap character was specified,
-             * replace all wrap characters by \n
-             * this is the traditional meaning of the wrap character
-             */
-            msReplaceChar(text, wrap, '\n');
-        }
-        /* if neither maxlength, nor wrap were specified,
-         * don't transform this text */
-        return text;
-    } else if(maxlength>0) {
-        if(wrap!='\0') {
-            /* split input text at the wrap character, only if
-             * the current line length is over maxlength */
-
-            /* TODO: check if the wrap character is a valid byte
-             * inside a multibyte utf8 glyph. if so, the msCountChars
-             * will return an erroneous value */
-            int numwrapchars = msCountChars(text,wrap);
-
-            if(numwrapchars > 0) {
-                if(label->encoding) {
-                    /* we have to use utf decoding functions here, so as not to
-                     * split a text line on a multibyte character */
-                    
-                    int num_cur_glyph_on_line = 0; /*count for the number of glyphs
+char *msWrapText(labelObj *label, char *text)
+{
+  char wrap;
+  int maxlength;
+  if(!text) /*not an error if no text*/
+    return text;
+  wrap = label->wrap;
+  maxlength = label->maxlength;
+  if(maxlength == 0) {
+    if(wrap!='\0') {
+      /* if maxlength = 0 *and* a wrap character was specified,
+       * replace all wrap characters by \n
+       * this is the traditional meaning of the wrap character
+       */
+      msReplaceChar(text, wrap, '\n');
+    }
+    /* if neither maxlength, nor wrap were specified,
+     * don't transform this text */
+    return text;
+  } else if(maxlength>0) {
+    if(wrap!='\0') {
+      /* split input text at the wrap character, only if
+       * the current line length is over maxlength */
+
+      /* TODO: check if the wrap character is a valid byte
+       * inside a multibyte utf8 glyph. if so, the msCountChars
+       * will return an erroneous value */
+      int numwrapchars = msCountChars(text,wrap);
+
+      if(numwrapchars > 0) {
+        if(label->encoding) {
+          /* we have to use utf decoding functions here, so as not to
+           * split a text line on a multibyte character */
+
+          int num_cur_glyph_on_line = 0; /*count for the number of glyphs
                                                      on the current line*/
-                    char *textptr = text;
-                    char glyph[11]; /*storage for unicode fetching function*/
-                    int glyphlen = 0; /*size of current glyph in bytes*/
-                    while((glyphlen = msGetNextGlyph((const char**)&textptr,glyph))>0) {
-                        num_cur_glyph_on_line++;
-                        if(*glyph == wrap && num_cur_glyph_on_line>=(maxlength)) {
-                            /*FIXME (if wrap becomes something other than char):*/
-                            *(textptr-1)='\n'; /*replace wrap char with a \n*/
-                            num_cur_glyph_on_line=0; /*reset count*/
-                        }
-                    }
-                } else {
-                    int cur_char_on_line = 0;
-                    char *textptr = text;
-                    while(*textptr != 0) {
-                        cur_char_on_line++;
-                        if(*textptr == wrap && cur_char_on_line>=maxlength) {
-                            *textptr='\n'; /*replace wrap char with a \n*/
-                            cur_char_on_line=0; /*reset count*/
-                        }
-                        textptr++;
-                    }
-                }
-                return text;
-            } else {
-                /*there are no characters available for wrapping*/
-                return text;
+          char *textptr = text;
+          char glyph[11]; /*storage for unicode fetching function*/
+          int glyphlen = 0; /*size of current glyph in bytes*/
+          while((glyphlen = msGetNextGlyph((const char**)&textptr,glyph))>0) {
+            num_cur_glyph_on_line++;
+            if(*glyph == wrap && num_cur_glyph_on_line>=(maxlength)) {
+              /*FIXME (if wrap becomes something other than char):*/
+              *(textptr-1)='\n'; /*replace wrap char with a \n*/
+              num_cur_glyph_on_line=0; /*reset count*/
             }
+          }
         } else {
-            /* if no wrap character was specified, but a maxlength was,
-             * don't draw this label if it is longer than the specified maxlength*/
-            if(msGetNumGlyphs(text)>maxlength) {
-                free(text);
-                return NULL;
-            } else {
-                return text;
+          int cur_char_on_line = 0;
+          char *textptr = text;
+          while(*textptr != 0) {
+            cur_char_on_line++;
+            if(*textptr == wrap && cur_char_on_line>=maxlength) {
+              *textptr='\n'; /*replace wrap char with a \n*/
+              cur_char_on_line=0; /*reset count*/
             }
+            textptr++;
+          }
         }
-    } else { /* negative maxlength: we split lines unconditionally, i.e. without
+        return text;
+      } else {
+        /*there are no characters available for wrapping*/
+        return text;
+      }
+    } else {
+      /* if no wrap character was specified, but a maxlength was,
+       * don't draw this label if it is longer than the specified maxlength*/
+      if(msGetNumGlyphs(text)>maxlength) {
+        free(text);
+        return NULL;
+      } else {
+        return text;
+      }
+    }
+  } else {
+    /* negative maxlength: we split lines unconditionally, i.e. without
     loooking for a wrap character*/
-        int numglyphs,numlines;
-        maxlength = -maxlength; /* use a positive value*/
-        numglyphs = msGetNumGlyphs(text);
-        numlines = numglyphs / maxlength; /*count total number of lines needed
+    int numglyphs,numlines;
+    maxlength = -maxlength; /* use a positive value*/
+    numglyphs = msGetNumGlyphs(text);
+    numlines = (numglyphs-1) / maxlength + 1; /*count total number of lines needed
                                             after splitting*/
-        if(numlines>1) {
-            char *newtext = msSmallMalloc(strlen(text)+numlines+1);
-            char *newtextptr = newtext;
-            char *textptr = text;
-            int glyphlen = 0, num_cur_glyph = 0;
-            while((glyphlen = msGetNextGlyph((const char**)&textptr,newtextptr))>0) {
-                num_cur_glyph++;
-                newtextptr += glyphlen;
-                if(num_cur_glyph%maxlength == 0 && num_cur_glyph != numglyphs) {
-                    /*we're at a split location, insert a newline*/
-                    *newtextptr = '\n';
-                    newtextptr++;
-                }
-            }
-            free(text);
-            return newtext;
-        } else {
-            /*no splitting needed, return the original*/
-            return text;
+    if(numlines>1) {
+      char *newtext = msSmallMalloc(strlen(text)+numlines+1);
+      char *newtextptr = newtext;
+      char *textptr = text;
+      int glyphlen = 0, num_cur_glyph = 0;
+      while((glyphlen = msGetNextGlyph((const char**)&textptr,newtextptr))>0) {
+        num_cur_glyph++;
+        newtextptr += glyphlen;
+        if(num_cur_glyph%maxlength == 0 && num_cur_glyph != numglyphs) {
+          /*we're at a split location, insert a newline*/
+          *newtextptr = '\n';
+          newtextptr++;
         }
+      }
+      free(text);
+      return newtext;
+    } else {
+      /*no splitting needed, return the original*/
+      return text;
     }
+  }
 }
 
-char *msAlignText(mapObj *map, imageObj *image, labelObj *label, char *text) {
-    double spacewidth=0.0; /*size of a single space, in fractional pixels*/
-    int numlines;
-    char **textlines,*newtext,*newtextptr;
-    int *textlinelengths,*numspacesforpadding;
-    int numspacestoadd,maxlinelength,i;
-    rectObj label_rect;
-    if(!msCountChars(text,'\n'))
-        return text; /*only one line*/
-    
-    /*split text into individual lines
-     * TODO: check if splitting on \n is utf8 safe*/
-    textlines = msStringSplit(text,'\n',&numlines);
-    
-    /*
-     * label->space_size_10 contains a cache for the horizontal size of a single
-     * 'space' character, at size 10 for the current label
-     * FIXME: in case of attribute binding for the FONT of the label, this cache will
-     * be wrong for labels where the attributed font is different than the first
-     * computed font. This shouldn't happen too often, and hopefully the size of a 
-     * space character shouldn't vary too much between different fonts*/
-    if(label->space_size_10 == 0.0) {
-        /*if the cache hasn't been initialized yet, or with pixmap fonts*/
-        
-        /* compute the size of 16 adjacent spaces. we can't do this for just one space,
-         * as the labelSize computing functions return integer bounding boxes. we assume
-         * that the integer rounding for such a number of spaces will be negligeable
-         * compared to the actual size of thoses spaces */ 
-        if(msGetLabelSize(map,label,".              .",10.0,&label_rect,NULL) != MS_SUCCESS) {
-            /*error computing label size, we can't continue*/
-
-            /*free the previously allocated split text*/
-            while(numlines--)
-                free(textlines[numlines]);
-            free(textlines);
-            return text;
-        }
+char *msAlignText(mapObj *map, labelObj *label, char *text)
+{
+  double spacewidth=0.0; /*size of a single space, in fractional pixels*/
+  int numlines;
+  char **textlines,*newtext,*newtextptr;
+  int *textlinelengths,*numspacesforpadding;
+  int numspacestoadd,maxlinelength,i;
+  rectObj label_rect;
+  if(!msCountChars(text,'\n'))
+    return text; /*only one line*/
+
+  /*split text into individual lines
+   * TODO: check if splitting on \n is utf8 safe*/
+  textlines = msStringSplit(text,'\n',&numlines);
+
+  /*
+   * label->space_size_10 contains a cache for the horizontal size of a single
+   * 'space' character, at size 10 for the current label
+   * FIXME: in case of attribute binding for the FONT of the label, this cache will
+   * be wrong for labels where the attributed font is different than the first
+   * computed font. This shouldn't happen too often, and hopefully the size of a
+   * space character shouldn't vary too much between different fonts*/
+  if(label->space_size_10 == 0.0) {
+    /*if the cache hasn't been initialized yet, or with pixmap fonts*/
+
+    /* compute the size of 16 adjacent spaces. we can't do this for just one space,
+     * as the labelSize computing functions return integer bounding boxes. we assume
+     * that the integer rounding for such a number of spaces will be negligeable
+     * compared to the actual size of thoses spaces */
+    if(msGetLabelSize(map,label,".              .",10.0,&label_rect,NULL) != MS_SUCCESS) {
+      /*error computing label size, we can't continue*/
+
+      /*free the previously allocated split text*/
+      while(numlines--)
+        free(textlines[numlines]);
+      free(textlines);
+      return text;
+    }
 
-        /* this is the size of a single space character. for truetype fonts,
-         * it's the size of a 10pt space. For pixmap fonts, it's the size
-         * for the current label */
-        spacewidth = (label_rect.maxx-label_rect.minx)/16.0;
-        if(label->type == MS_TRUETYPE) {
-            label->space_size_10=spacewidth; /*cache the computed size*/
+    /* this is the size of a single space character. for truetype fonts,
+     * it's the size of a 10pt space. For pixmap fonts, it's the size
+     * for the current label */
+    spacewidth = (label_rect.maxx-label_rect.minx)/16.0;
+    if(label->type == MS_TRUETYPE) {
+      label->space_size_10=spacewidth; /*cache the computed size*/
 
-            /*size of a space for current label size*/
-            spacewidth = spacewidth * (double)label->size/10.0;
-        }
-    } else {
-        spacewidth = label->space_size_10 * (double)label->size/10.0;
+      /*size of a space for current label size*/
+      spacewidth = spacewidth * (double)label->size/10.0;
     }
-   
-    
-    /*length in pixels of each line*/
-    textlinelengths = (int*)msSmallMalloc(numlines*sizeof(int));
-    
-    /*number of spaces that need to be added to each line*/
-    numspacesforpadding = (int*)msSmallMalloc(numlines*sizeof(int));
-    
-    /*total number of spaces that need to be added*/
-    numspacestoadd=0;
-
-    /*length in pixels of the longest line*/
-    maxlinelength=0;
-    for(i=0;i<numlines;i++) {
-        msGetLabelSize(map,label,textlines[i],label->size, &label_rect,NULL);
-        textlinelengths[i] = label_rect.maxx-label_rect.minx;
-        if(maxlinelength<textlinelengths[i])
-            maxlinelength=textlinelengths[i];
+  } else {
+    spacewidth = label->space_size_10 * (double)label->size/10.0;
+  }
+  spacewidth = MS_MAX(1,spacewidth);
+
+
+  /*length in pixels of each line*/
+  textlinelengths = (int*)msSmallMalloc(numlines*sizeof(int));
+
+  /*number of spaces that need to be added to each line*/
+  numspacesforpadding = (int*)msSmallMalloc(numlines*sizeof(int));
+
+  /*total number of spaces that need to be added*/
+  numspacestoadd=0;
+
+  /*length in pixels of the longest line*/
+  maxlinelength=0;
+  for(i=0; i<numlines; i++) {
+    if(MS_SUCCESS != msGetLabelSize(map,label,textlines[i],label->size, &label_rect,NULL)) {
+      msFreeCharArray(textlines,numlines);
+      msFree(textlinelengths);
+      msFree(numspacesforpadding);
+      return text;
     }
-    for(i=0;i<numlines;i++) {
-        /* number of spaces to add so the current line is
-         * as long as the longest line */
-        double nfracspaces = (maxlinelength - textlinelengths[i])/spacewidth;
+    textlinelengths[i] = label_rect.maxx-label_rect.minx;
+    if(maxlinelength<textlinelengths[i])
+      maxlinelength=textlinelengths[i];
+  }
+  for(i=0; i<numlines; i++) {
+    /* number of spaces to add so the current line is
+     * as long as the longest line */
+    double nfracspaces = (maxlinelength - textlinelengths[i])/spacewidth;
 
-        if(label->align == MS_ALIGN_CENTER) {
-            numspacesforpadding[i]=MS_NINT(nfracspaces/2.0);
-        } else {
-           if(label->align == MS_ALIGN_RIGHT) {
-               numspacesforpadding[i]=MS_NINT(nfracspaces);
-           }
-        }
-        numspacestoadd+=numspacesforpadding[i];
+    if(label->align == MS_ALIGN_CENTER) {
+      numspacesforpadding[i]=MS_NINT(nfracspaces/2.0);
+    } else {
+      if(label->align == MS_ALIGN_RIGHT) {
+        numspacesforpadding[i]=MS_NINT(nfracspaces);
+      }
     }
+    numspacestoadd+=numspacesforpadding[i];
+  }
 
-    /*allocate new text with room for the additional spaces needed*/
-    newtext = (char*)msSmallMalloc(strlen(text)+1+numspacestoadd);
-    newtextptr=newtext;
-    for(i=0;i<numlines;i++) {
-        int j;
-        /*padd beginning of line with needed spaces*/
-        for(j=0;j<numspacesforpadding[i];j++) {
-            *(newtextptr++)=' ';
-        }
-        /*copy original line*/
-        strcpy(newtextptr,textlines[i]);
-        /*place pointer at the char right after the current line*/
-        newtextptr+=strlen(textlines[i])+1;
-        if(i!=numlines-1) {
-            /*put the \n back in (was taken away by msStringSplit)*/
-            *(newtextptr-1)='\n';
-        }
+  /*allocate new text with room for the additional spaces needed*/
+  newtext = (char*)msSmallMalloc(strlen(text)+1+numspacestoadd);
+  newtextptr=newtext;
+  for(i=0; i<numlines; i++) {
+    int j;
+    /*padd beginning of line with needed spaces*/
+    for(j=0; j<numspacesforpadding[i]; j++) {
+      *(newtextptr++)=' ';
     }
-    /*free the original text*/
-    free(text);
-    for(i=0;i<numlines;i++) {
-        free(textlines[i]);
+    /*copy original line*/
+    strcpy(newtextptr,textlines[i]);
+    /*place pointer at the char right after the current line*/
+    newtextptr+=strlen(textlines[i])+1;
+    if(i!=numlines-1) {
+      /*put the \n back in (was taken away by msStringSplit)*/
+      *(newtextptr-1)='\n';
     }
-    free(textlines);
-    free(textlinelengths);
-    free(numspacesforpadding);
+  }
+  /*free the original text*/
+  free(text);
+  for(i=0; i<numlines; i++) {
+    free(textlines[i]);
+  }
+  free(textlines);
+  free(textlinelengths);
+  free(numspacesforpadding);
 
-    /*return the aligned text. note that the terminating \0 was added by the last
-     * call to strcpy */
-    return newtext;
+  /*return the aligned text. note that the terminating \0 was added by the last
+   * call to strcpy */
+  return newtext;
 }
 
 
 /*
  * this function applies the label encoding and wrap parameters
  * to the supplied text
- * Note: it is the caller's responsibility to free the returned 
+ * Note: it is the caller's responsibility to free the returned
  * char array
  */
-char *msTransformLabelText(mapObj *map, imageObj* image,labelObj *label, char *text)
+char *msTransformLabelText(mapObj *map, labelObj *label, char *text)
 {
-    char *newtext = text;
-    if(label->encoding)
-        newtext = msGetEncodedString(text, label->encoding);
-    else
-        newtext=msStrdup(text);
-    
-    if(newtext && (label->wrap!='\0' || label->maxlength!=0)) {
-        newtext = msWrapText(label, newtext);
+  char *newtext = text;
+  if(label->encoding)
+    newtext = msGetEncodedString(text, label->encoding);
+  else
+    newtext=msStrdup(text);
+
+  if(newtext && (label->wrap!='\0' || label->maxlength!=0)) {
+    newtext = msWrapText(label, newtext);
+  }
+
+  if(newtext && label->align!=MS_ALIGN_LEFT ) {
+    newtext = msAlignText(map, label, newtext);
+  }
+
+  return newtext;
+}
+
+int msAddLabelGroup(mapObj *map, int layerindex, int classindex, shapeObj *shape, pointObj *point, double featuresize)
+{
+  int i, priority, numactivelabels=0;
+  labelCacheSlotObj *cacheslot;
+
+  labelCacheMemberObj *cachePtr=NULL;
+  layerObj *layerPtr=NULL;
+  classObj *classPtr=NULL;
+
+  layerPtr = (GET_LAYER(map, layerindex)); /* set up a few pointers for clarity */
+  classPtr = GET_LAYER(map, layerindex)->class[classindex];
+
+  if(classPtr->numlabels == 0) return MS_SUCCESS; /* not an error just nothing to do */
+  for(i=0; i<classPtr->numlabels; i++) {
+    if(classPtr->labels[i]->status == MS_ON) {
+      numactivelabels++;
+    }
+  }
+  if(numactivelabels == 0) return MS_SUCCESS;
+
+  /* if the number of labels is 1 then call msAddLabel() accordingly */
+  if(numactivelabels == 1) {
+    for(i=0; i<classPtr->numlabels; i++) {
+      if(classPtr->labels[i]->status == MS_ON)
+        return msAddLabel(map, classPtr->labels[i], layerindex, classindex, shape, point, NULL, featuresize);
     }
+  }
+
+  if (layerPtr->type == MS_LAYER_ANNOTATION && (cachePtr->numlabels > 1 || classPtr->leader.maxdistance)) {
+    msSetError(MS_MISCERR, "Multiple Labels and/or LEADERs are not supported with annotation layers", "msAddLabelGroup()");
+    return MS_FAILURE;
+  }
 
-    if(newtext && label->align!=MS_ALIGN_LEFT ) {
-        newtext = msAlignText(map, image,label, newtext);
+  /* check that the label intersects the layer mask */
+  if(layerPtr->mask) {
+    int maskLayerIdx = msGetLayerIndex(map,layerPtr->mask);
+    layerObj *maskLayer = GET_LAYER(map,maskLayerIdx);
+    unsigned char *alphapixptr;
+    if(maskLayer->maskimage && MS_IMAGE_RENDERER(maskLayer->maskimage)->supports_pixel_buffer) {
+      rasterBufferObj rb;
+      int x,y;
+      memset(&rb,0,sizeof(rasterBufferObj));
+      MS_IMAGE_RENDERER(maskLayer->maskimage)->getRasterBufferHandle(maskLayer->maskimage,&rb);
+      x = MS_NINT(point->x);
+      y = MS_NINT(point->y);
+#ifdef USE_GD
+      if(rb.type == MS_BUFFER_BYTE_RGBA) {
+        alphapixptr = rb.data.rgba.a+rb.data.rgba.row_step*y + rb.data.rgba.pixel_step*x;
+        if(!*alphapixptr) {
+          /* label point does not intersect mask */
+          return MS_SUCCESS;
+        }
+      } else {
+        if(!gdImageGetPixel(rb.data.gd_img,x,y))
+          return MS_SUCCESS;
+      }
+#else
+      assert(rb.type == MS_BUFFER_BYTE_RGBA);
+      alphapixptr = rb.data.rgba.a+rb.data.rgba.row_step*y + rb.data.rgba.pixel_step*x;
+      if(!*alphapixptr) {
+        /* label point does not intersect mask */
+        return MS_SUCCESS;
+      }
+#endif
+    } else {
+      msSetError(MS_MISCERR, "Layer (%s) references references a mask layer, but the selected renderer does not support them", "msAddLabelGroup()", layerPtr->name);
+      return (MS_FAILURE);
     }
+  }
+
+
+
+  /* Validate label priority value and get ref on label cache for it */
+  priority = classPtr->labels[0]->priority; /* take priority from the first label */
+  if (priority < 1)
+    priority = 1;
+  else if (priority > MS_MAX_LABEL_PRIORITY)
+    priority = MS_MAX_LABEL_PRIORITY;
 
-    return newtext;
+  cacheslot = &(map->labelcache.slots[priority-1]);
+
+  if(cacheslot->numlabels == cacheslot->cachesize) { /* just add it to the end */
+    cacheslot->labels = (labelCacheMemberObj *) realloc(cacheslot->labels, sizeof(labelCacheMemberObj)*(cacheslot->cachesize+MS_LABELCACHEINCREMENT));
+    MS_CHECK_ALLOC(cacheslot->labels, sizeof(labelCacheMemberObj)*(cacheslot->cachesize+MS_LABELCACHEINCREMENT), MS_FAILURE);
+    cacheslot->cachesize += MS_LABELCACHEINCREMENT;
+  }
+
+  cachePtr = &(cacheslot->labels[cacheslot->numlabels]);
+
+  cachePtr->layerindex = layerindex; /* so we can get back to this *raw* data if necessary */
+  cachePtr->classindex = classindex;
+  if(shape) {
+    cachePtr->shapetype = shape->type;
+  } else {
+    cachePtr->shapetype = MS_SHAPE_POINT;
+  }
+
+  cachePtr->point = *point; /* the actual label point */
+  cachePtr->labelpath = NULL;
+
+  cachePtr->leaderline = NULL;
+  cachePtr->leaderbbox = NULL;
+
+  // cachePtr->text = msStrdup(string); /* the actual text */
+
+  /* TODO: perhaps we can get rid of this next section and just store a marker size? Why do we cache the styles for a point layer? */
+
+  /* copy the styles (only if there is an accompanying marker)
+   * We cannot simply keep refs because the rendering code  might alters some members of the style objects
+   */
+  cachePtr->styles = NULL;
+  cachePtr->numstyles = 0;
+  if(layerPtr->type == MS_LAYER_ANNOTATION && classPtr->numstyles > 0) {
+    cachePtr->numstyles = classPtr->numstyles;
+    cachePtr->styles = (styleObj *) msSmallMalloc(sizeof(styleObj)*classPtr->numstyles);
+    if (classPtr->numstyles > 0) {
+      for(i=0; i<classPtr->numstyles; i++) {
+        initStyle(&(cachePtr->styles[i]));
+        msCopyStyle(&(cachePtr->styles[i]), classPtr->styles[i]);
+      }
+    }
+  }
+
+  /*
+  ** copy the labels (we are guaranteed to have more than one):
+  **   we cannot simply keep refs because the rendering code alters some members of the style objects
+  */
+
+  cachePtr->numlabels = 0;
+  cachePtr->labels = (labelObj *) msSmallMalloc(sizeof(labelObj)*numactivelabels);
+  for(i=0; i<classPtr->numlabels; i++) {
+    if(classPtr->labels[i]->status == MS_OFF) continue;
+    initLabel(&(cachePtr->labels[cachePtr->numlabels]));
+    msCopyLabel(&(cachePtr->labels[cachePtr->numlabels]), classPtr->labels[i]);
+    cachePtr->numlabels++;
+  }
+  assert(cachePtr->numlabels == numactivelabels);
+
+  cachePtr->markerid = -1;
+
+  cachePtr->featuresize = featuresize;
+
+  //cachePtr->poly = (shapeObj *) msSmallMalloc(sizeof(shapeObj));
+  //msInitShape(cachePtr->poly);
+  cachePtr->poly = NULL;
+
+  cachePtr->status = MS_FALSE;
+
+  if(layerPtr->type == MS_LAYER_POINT && classPtr->numstyles > 0) {
+    /* cache the marker placement, it's already on the map */
+    /* TO DO: at the moment only checks the bottom style, perhaps should check all of them */
+    /* #2347: after RFC-24 classPtr->styles could be NULL so we check it */
+    rectObj rect;
+    double w, h;
+    if(msGetMarkerSize(&map->symbolset, classPtr->styles[0], &w, &h, layerPtr->scalefactor) != MS_SUCCESS)
+      return(MS_FAILURE);
+
+    if(cacheslot->nummarkers == cacheslot->markercachesize) { /* just add it to the end */
+      cacheslot->markers = (markerCacheMemberObj *) realloc(cacheslot->markers, sizeof(markerCacheMemberObj)*(cacheslot->cachesize+MS_LABELCACHEINCREMENT));
+      MS_CHECK_ALLOC(cacheslot->markers, sizeof(markerCacheMemberObj)*(cacheslot->cachesize+MS_LABELCACHEINCREMENT), MS_FAILURE);
+      cacheslot->markercachesize+=MS_LABELCACHEINCREMENT;
+    }
+
+    i = cacheslot->nummarkers;
+
+    cacheslot->markers[i].poly = (shapeObj *) msSmallMalloc(sizeof(shapeObj));
+    msInitShape(cacheslot->markers[i].poly);
+
+    rect.minx = (point->x - .5 * w);
+    rect.miny = (point->y - .5 * h);
+    rect.maxx = rect.minx + (w-1);
+    rect.maxy = rect.miny + (h-1);
+    msRectToPolygon(rect, cacheslot->markers[i].poly);
+    cacheslot->markers[i].id = cacheslot->numlabels;
+
+    cachePtr->markerid = i;
+
+    cacheslot->nummarkers++;
+  }
+
+  cacheslot->numlabels++;
+
+  /* Maintain main labelCacheObj.numlabels only for backwards compatibility */
+  map->labelcache.numlabels++;
+
+  return(MS_SUCCESS);
 }
 
-int msAddLabel(mapObj *map, int layerindex, int classindex, shapeObj *shape, pointObj *point, labelPathObj *labelpath, char *string, double featuresize, labelObj *label )
+int msAddLabel(mapObj *map, labelObj *label, int layerindex, int classindex, shapeObj *shape, pointObj *point, labelPathObj *labelpath, double featuresize)
 {
   int i;
   labelCacheSlotObj *cacheslot;
@@ -311,20 +503,103 @@ int msAddLabel(mapObj *map, int layerindex, int classindex, shapeObj *shape, poi
   layerObj *layerPtr=NULL;
   classObj *classPtr=NULL;
 
-  if(!string) return(MS_SUCCESS); /* not an error */ 
+  if(!label) return(MS_FAILURE); // RFC 77 TODO: set a proper message
+  if(label->status == MS_OFF) return(MS_SUCCESS); /* not an error */
+  if(!label->annotext) {
+    /* check if we have a labelpnt style */
+    for(i=0; i<label->numstyles; i++) {
+      if(label->styles[i]->_geomtransform.type == MS_GEOMTRANSFORM_LABELPOINT)
+        break;
+    }
+    if(i==label->numstyles) {
+      /* label has no text or marker symbols */
+      return MS_SUCCESS;
+    }
+  }
 
   layerPtr = (GET_LAYER(map, layerindex)); /* set up a few pointers for clarity */
   classPtr = GET_LAYER(map, layerindex)->class[classindex];
 
-  if( label == NULL )
-    label = &(classPtr->label);
-
-  if(map->scaledenom > 0) {
-    if((label->maxscaledenom != -1) && (map->scaledenom >= label->maxscaledenom))
-      return(MS_SUCCESS);
-    if((label->minscaledenom != -1) && (map->scaledenom < label->minscaledenom))
-      return(MS_SUCCESS);
+  if(classPtr->leader.maxdistance) {
+    if (layerPtr->type == MS_LAYER_ANNOTATION) {
+      msSetError(MS_MISCERR, "LEADERs are not supported on annotation layers", "msAddLabel()");
+      return MS_FAILURE;
+    }
+    if(labelpath) {
+      msSetError(MS_MISCERR, "LEADERs are not supported on ANGLE FOLLOW labels", "msAddLabel()");
+      return MS_FAILURE;
+    }
   }
+  /* check that the label intersects the layer mask */
+
+  if (layerPtr->mask) {
+    int maskLayerIdx = msGetLayerIndex(map, layerPtr->mask);
+    layerObj *maskLayer = GET_LAYER(map, maskLayerIdx);
+    unsigned char *alphapixptr;
+    if (maskLayer->maskimage && MS_IMAGE_RENDERER(maskLayer->maskimage)->supports_pixel_buffer) {
+      rasterBufferObj rb;
+      memset(&rb, 0, sizeof (rasterBufferObj));
+      MS_IMAGE_RENDERER(maskLayer->maskimage)->getRasterBufferHandle(maskLayer->maskimage, &rb);
+      if (point) {
+        int x = MS_NINT(point->x);
+        int y = MS_NINT(point->y);
+#ifdef USE_GD
+        if(rb.type == MS_BUFFER_BYTE_RGBA) {
+          alphapixptr = rb.data.rgba.a+rb.data.rgba.row_step*y + rb.data.rgba.pixel_step*x;
+          if(!*alphapixptr) {
+            /* label point does not intersect mask */
+            return MS_SUCCESS;
+          }
+        } else {
+          if(!gdImageGetPixel(rb.data.gd_img,x,y)) {
+            return MS_SUCCESS;
+          }
+        }
+#else
+        assert(rb.type == MS_BUFFER_BYTE_RGBA);
+        alphapixptr = rb.data.rgba.a+rb.data.rgba.row_step*y + rb.data.rgba.pixel_step*x;
+        if(!*alphapixptr) {
+          /* label point does not intersect mask */
+          return MS_SUCCESS;
+        }
+#endif
+      } else if (labelpath) {
+        int i = 0;
+        for (i = 0; i < labelpath->path.numpoints; i++) {
+          int x = MS_NINT(labelpath->path.point[i].x);
+          int y = MS_NINT(labelpath->path.point[i].y);
+#ifdef USE_GD
+          if (rb.type == MS_BUFFER_BYTE_RGBA) {
+            alphapixptr = rb.data.rgba.a + rb.data.rgba.row_step * y + rb.data.rgba.pixel_step*x;
+            if (!*alphapixptr) {
+              /* label point does not intersect mask */
+              msFreeLabelPathObj(labelpath);
+              return MS_SUCCESS;
+            }
+          } else {
+            if (!gdImageGetPixel(rb.data.gd_img, x, y)) {
+              msFreeLabelPathObj(labelpath);
+              return MS_SUCCESS;
+            }
+          }
+#else
+          assert(rb.type == MS_BUFFER_BYTE_RGBA);
+          alphapixptr = rb.data.rgba.a + rb.data.rgba.row_step * y + rb.data.rgba.pixel_step*x;
+          if (!*alphapixptr) {
+            /* label point does not intersect mask */
+            msFreeLabelPathObj(labelpath);
+            return MS_SUCCESS;
+          }
+#endif
+        }
+      }
+    } else {
+      msSetError(MS_MISCERR, "Layer (%s) references references a mask layer, but the selected renderer does not support them", "msAddLabel()", layerPtr->name);
+      return (MS_FAILURE);
+    }
+  }
+
+
 
   /* Validate label priority value and get ref on label cache for it */
   if (label->priority < 1)
@@ -344,33 +619,25 @@ int msAddLabel(mapObj *map, int layerindex, int classindex, shapeObj *shape, poi
 
   cachePtr->layerindex = layerindex; /* so we can get back to this *raw* data if necessary */
   cachePtr->classindex = classindex;
-
   if(shape) {
-    cachePtr->tileindex = shape->tileindex;
-    cachePtr->shapeindex = shape->index;
     cachePtr->shapetype = shape->type;
   } else {
-    cachePtr->tileindex = cachePtr->shapeindex = -1;    
     cachePtr->shapetype = MS_SHAPE_POINT;
   }
+  cachePtr->leaderline = NULL;
+  cachePtr->leaderbbox = NULL;
 
   /* Store the label point or the label path (Bug #1620) */
   if ( point ) {
     cachePtr->point = *point; /* the actual label point */
-    cachePtr->point.x = MS_NINT(cachePtr->point.x);
-    cachePtr->point.y = MS_NINT(cachePtr->point.y);
     cachePtr->labelpath = NULL;
-  } else if ( labelpath ) {
-    int i;
+  } else {
+    assert(labelpath);
     cachePtr->labelpath = labelpath;
     /* Use the middle point of the labelpath for mindistance calculations */
-    i = labelpath->path.numpoints / 2;
-    cachePtr->point.x = MS_NINT(labelpath->path.point[i].x);
-    cachePtr->point.y = MS_NINT(labelpath->path.point[i].y);
+    cachePtr->point = labelpath->path.point[labelpath->path.numpoints / 2];
   }
 
-  cachePtr->text = msStrdup(string); /* the actual text */
-
   /* TODO: perhaps we can get rid of this next section and just store a marker size? Why do we cache the styles for a point layer? */
 
   /* copy the styles (only if there is an accompanying marker)
@@ -383,32 +650,35 @@ int msAddLabel(mapObj *map, int layerindex, int classindex, shapeObj *shape, poi
     cachePtr->styles = (styleObj *) msSmallMalloc(sizeof(styleObj)*classPtr->numstyles);
     if (classPtr->numstyles > 0) {
       for(i=0; i<classPtr->numstyles; i++) {
-	initStyle(&(cachePtr->styles[i]));
-	msCopyStyle(&(cachePtr->styles[i]), classPtr->styles[i]);
+        initStyle(&(cachePtr->styles[i]));
+        msCopyStyle(&(cachePtr->styles[i]), classPtr->styles[i]);
       }
     }
   }
 
   /* copy the label */
-  initLabel(&(cachePtr->label));
-  msCopyLabel(&(cachePtr->label), label);
+  cachePtr->numlabels = 1;
+  cachePtr->labels = (labelObj *) msSmallMalloc(sizeof(labelObj));
+  initLabel(cachePtr->labels);
+  msCopyLabel(cachePtr->labels, label);
 
   cachePtr->markerid = -1;
 
   cachePtr->featuresize = featuresize;
 
-  cachePtr->poly = (shapeObj *) msSmallMalloc(sizeof(shapeObj));
-  msInitShape(cachePtr->poly);
+  //cachePtr->poly = (shapeObj *) msSmallMalloc(sizeof(shapeObj));
+  //msInitShape(cachePtr->poly);
+  cachePtr->poly = NULL;
 
   cachePtr->status = MS_FALSE;
 
-  if(layerPtr->type == MS_LAYER_POINT) { /* cache the marker placement, it's already on the map */
+  if(layerPtr->type == MS_LAYER_POINT && classPtr->numstyles > 0) { /* cache the marker placement, it's already on the map */
     rectObj rect;
-    int w, h;
+    double w, h;
 
     if(cacheslot->nummarkers == cacheslot->markercachesize) { /* just add it to the end */
       cacheslot->markers = (markerCacheMemberObj *) realloc(cacheslot->markers, sizeof(markerCacheMemberObj)*(cacheslot->cachesize+MS_LABELCACHEINCREMENT));
-      MS_CHECK_ALLOC(cacheslot->markers, sizeof(markerCacheMemberObj)*(cacheslot->cachesize+MS_LABELCACHEINCREMENT), MS_FAILURE); 
+      MS_CHECK_ALLOC(cacheslot->markers, sizeof(markerCacheMemberObj)*(cacheslot->cachesize+MS_LABELCACHEINCREMENT), MS_FAILURE);
       cacheslot->markercachesize+=MS_LABELCACHEINCREMENT;
     }
 
@@ -420,22 +690,19 @@ int msAddLabel(mapObj *map, int layerindex, int classindex, shapeObj *shape, poi
     /* TO DO: at the moment only checks the bottom style, perhaps should check all of them */
     /* #2347: after RFC-24 classPtr->styles could be NULL so we check it */
     if(classPtr->styles != NULL) {
-      if(msGetMarkerSize(&map->symbolset, classPtr->styles[0], &w, &h, layerPtr->scalefactor) != MS_SUCCESS) 
+      if(msGetMarkerSize(&map->symbolset, classPtr->styles[0], &w, &h, layerPtr->scalefactor) != MS_SUCCESS)
         return(MS_FAILURE);
-    } else {
-      msSetError(MS_MISCERR, "msAddLabel error: missing style definition for layer '%s'", "msAddLabel()", layerPtr->name);
-      return(MS_FAILURE);
-    }
-    rect.minx = MS_NINT(point->x - .5 * w);
-    rect.miny = MS_NINT(point->y - .5 * h);
-    rect.maxx = rect.minx + (w-1);
-    rect.maxy = rect.miny + (h-1);
-    msRectToPolygon(rect, cacheslot->markers[i].poly);    
-    cacheslot->markers[i].id = cacheslot->numlabels;
- 
-    cachePtr->markerid = i;
+      rect.minx = point->x - .5 * w;
+      rect.miny = point->y - .5 * h;
+      rect.maxx = rect.minx + (w-1);
+      rect.maxy = rect.miny + (h-1);
+      msRectToPolygon(rect, cacheslot->markers[i].poly);
+      cacheslot->markers[i].id = cacheslot->numlabels;
 
-    cacheslot->nummarkers++;
+      cachePtr->markerid = i;
+
+      cacheslot->nummarkers++;
+    }
   }
 
   cacheslot->numlabels++;
@@ -446,16 +713,23 @@ int msAddLabel(mapObj *map, int layerindex, int classindex, shapeObj *shape, poi
   return(MS_SUCCESS);
 }
 
-
 /*
-** Is a label completely in the image, reserving a gutter (in pixels) inside 
-** image for no labels (effectively making image larger. The gutter can be 
+** Is a label completely in the image, reserving a gutter (in pixels) inside
+** image for no labels (effectively making image larger. The gutter can be
 ** negative in cases where a label has a buffer around it.
 */
 static int labelInImage(int width, int height, shapeObj *lpoly, int gutter)
 {
   int i,j;
 
+  /* do a bbox test first */
+  if(lpoly->bounds.minx >= gutter &&
+      lpoly->bounds.miny >= gutter &&
+      lpoly->bounds.maxx < width-gutter &&
+      lpoly->bounds.maxy < height-gutter) {
+    return MS_TRUE;
+  }
+
   for(i=0; i<lpoly->numlines; i++) {
     for(j=1; j<lpoly->line[i].numpoints; j++) {
       if(lpoly->line[i].point[j].x < gutter) return(MS_FALSE);
@@ -475,71 +749,136 @@ static int labelInImage(int width, int height, shapeObj *lpoly, int gutter)
 ** or collides with a marker.
 **
 ** This function is used by the various msDrawLabelCacheXX() implementations.
-*/
-void msTestLabelCacheCollisions(labelCacheObj *labelcache, labelObj *labelPtr, 
+
+int msTestLabelCacheCollisions(labelCacheObj *labelcache, labelObj *labelPtr,
                                 int mapwidth, int mapheight, int buffer,
-                                labelCacheMemberObj *cachePtr, int current_priority, 
-                                int current_label, int mindistance, double label_size)
+                                labelCacheMemberObj *cachePtr, int current_priority,
+                                int current_label, int mindistance, double label_size);
+*/
+
+int msTestLabelCacheCollisions(mapObj *map, labelCacheMemberObj *cachePtr, shapeObj *poly,
+                               int mindistance, int current_priority, int current_label)
 {
-    int i, p;
+  labelCacheObj *labelcache = &(map->labelcache);
+  int i, p, ll, pp;
+  double label_width = 0;
+  labelCacheMemberObj *curCachePtr=NULL;
 
-    /* Check against image bounds first 
-    ** Pass mapwidth=-1 to skip this test
-     */
-    if(!labelPtr->partials && mapwidth > 0 && mapheight > 0) {
-        if(labelInImage(mapwidth, mapheight, cachePtr->poly, buffer) == MS_FALSE) {
-	    cachePtr->status = MS_FALSE;
-            return;
-        }
+  /*
+   * Check against image bounds first
+   */
+  if(!cachePtr->labels[0].partials) {
+    if(labelInImage(map->width, map->height, poly, labelcache->gutter) == MS_FALSE) {
+      return MS_FALSE;
     }
+  }
 
-    /* Compare against all rendered markers from this priority level and higher.
-    ** Labels can overlap their own marker and markers from lower priority levels
-    */
-    for (p=current_priority; p < MS_MAX_LABEL_PRIORITY; p++) {
-        labelCacheSlotObj *markerslot;
-        markerslot = &(labelcache->slots[p]);
-
-        for ( i = 0; i < markerslot->nummarkers; i++ ) {
-            if ( !(p == current_priority && current_label == markerslot->markers[i].id) ) {  /* labels can overlap their own marker */
-                if ( intersectLabelPolygons(markerslot->markers[i].poly, cachePtr->poly ) == MS_TRUE ) {
-                    cachePtr->status = MS_FALSE;  /* polys intersect */
-                    return;
-                }
-            }
+  /* compute start index of first label to test: only test against rendered labels */
+  if(current_label>=0) {
+    i = current_label+1;
+  } else {
+    i = 0;
+    current_label = -current_label;
+  }
+
+  /* Compare against all rendered markers from this priority level and higher.
+  ** Labels can overlap their own marker and markers from lower priority levels
+  */
+  for (p=current_priority; p < MS_MAX_LABEL_PRIORITY; p++) {
+    labelCacheSlotObj *markerslot;
+    markerslot = &(labelcache->slots[p]);
+
+    for ( ll = 0; ll < markerslot->nummarkers; ll++ ) {
+      if ( !(p == current_priority && current_label == markerslot->markers[ll].id ) ) {  /* labels can overlap their own marker */
+        if ( intersectLabelPolygons(markerslot->markers[ll].poly, poly ) == MS_TRUE ) {
+          return MS_FALSE;
         }
+      }
     }
+  }
 
-    /* compare against rendered labels */
-    i = current_label+1;
+  if(mindistance > 0)
+    label_width = poly->bounds.maxx - poly->bounds.minx;
+
+  for(p=current_priority; p<MS_MAX_LABEL_PRIORITY; p++) {
+    labelCacheSlotObj *cacheslot;
+    cacheslot = &(labelcache->slots[p]);
+
+    for(  ; i < cacheslot->numlabels; i++) {
+      curCachePtr = &(cacheslot->labels[i]);
+
+      if(curCachePtr->status == MS_TRUE) { /* compare bounding polygons and check for duplicates */
+
+        /* skip testing against ourself */
+        assert(p!=current_priority || i != current_label);
+
+        /*
+        ** Note 1: We add the label_size to the mindistance value when comparing because we do want the mindistance
+        ** value between the labels and not only from point to point.
+        **
+        ** Note 2: We only check the first label (could be multiples (RFC 77)) since that is *by far* the most common
+        ** use case. Could change in the future but it's not worth the overhead at this point.
+        */
+        if(mindistance >0  &&
+            (cachePtr->layerindex == curCachePtr->layerindex) &&
+            (cachePtr->classindex == curCachePtr->classindex) &&
+            (cachePtr->labels[0].annotext && curCachePtr->labels[0].annotext &&
+             strcmp(cachePtr->labels[0].annotext, curCachePtr->labels[0].annotext) == 0) &&
+            (msDistancePointToPoint(&(cachePtr->point), &(curCachePtr->point)) <= (mindistance + label_width))) { /* label is a duplicate */
+          return MS_FALSE;
+        }
 
-    for(p=current_priority; p<MS_MAX_LABEL_PRIORITY; p++) {
-        labelCacheSlotObj *cacheslot;
-        cacheslot = &(labelcache->slots[p]);
-
-        for(  ; i < cacheslot->numlabels; i++) { 
-            if(cacheslot->labels[i].status == MS_TRUE) { /* compare bounding polygons and check for duplicates */
-                /* We add the label_size to the mindistance value when comparing because we do want the mindistance 
-                   value between the labels and not only from point to point. */
-                if(label_size > 0 && (mindistance != -1) && 
-                   (cachePtr->layerindex == cacheslot->labels[i].layerindex) && (cachePtr->classindex == cacheslot->labels[i].classindex) && 
-                   (strcmp(cachePtr->text,cacheslot->labels[i].text) == 0) &&
-                   (msDistancePointToPoint(&(cachePtr->point), &(cacheslot->labels[i].point)) <= (mindistance + label_size))) { /* label is a duplicate */
-                    cachePtr->status = MS_FALSE;
-                    return;
+        if(intersectLabelPolygons(curCachePtr->poly, poly) == MS_TRUE) { /* polys intersect */
+          return MS_FALSE;
+        }
+        if(curCachePtr->leaderline) {
+          /* our poly against rendered leader lines */
+          /* first do a bbox check */
+          if(msRectOverlap(curCachePtr->leaderbbox, &(poly->bounds))) {
+            /* look for intersecting line segments */
+            for(ll=0; ll<poly->numlines; ll++)
+              for(pp=1; pp<poly->line[ll].numpoints; pp++)
+                if(msIntersectSegments(
+                      &(poly->line[ll].point[pp-1]),
+                      &(poly->line[ll].point[pp]),
+                      &(curCachePtr->leaderline->point[0]),
+                      &(curCachePtr->leaderline->point[1])) ==  MS_TRUE) {
+                  return(MS_FALSE);
                 }
+          }
 
-                if(intersectLabelPolygons(cacheslot->labels[i].poly, cachePtr->poly) == MS_TRUE) { /* polys intersect */
-                    cachePtr->status = MS_FALSE;
-                    return;
+        }
+        if(cachePtr->leaderline) {
+          /* does our leader intersect current label */
+          /* first do a bbox check */
+          if(msRectOverlap(cachePtr->leaderbbox, &(curCachePtr->poly->bounds))) {
+            /* look for intersecting line segments */
+            for(ll=0; ll<curCachePtr->poly->numlines; ll++)
+              for(pp=1; pp<curCachePtr->poly->line[ll].numpoints; pp++)
+                if(msIntersectSegments(
+                      &(curCachePtr->poly->line[ll].point[pp-1]),
+                      &(curCachePtr->poly->line[ll].point[pp]),
+                      &(cachePtr->leaderline->point[0]),
+                      &(cachePtr->leaderline->point[1])) ==  MS_TRUE) {
+                  return(MS_FALSE);
                 }
+
+          }
+          if(curCachePtr->leaderline) {
+            /* TODO: check intersection of leader lines, not only bbox test ? */
+            if(msRectOverlap(curCachePtr->leaderbbox, cachePtr->leaderbbox)) {
+              return MS_FALSE;
             }
-        } /* i */
 
-        i = 0; /* Start over with 1st label of next slot */
-    } /* p */
-}
+          }
+        }
+      }
+    } /* i */
 
+    i = 0; /* Start over with 1st label of next slot */
+  } /* p */
+  return MS_TRUE;
+}
 
 /* msGetLabelCacheMember()
 **
@@ -550,51 +889,48 @@ void msTestLabelCacheCollisions(labelCacheObj *labelcache, labelObj *labelPtr,
 */
 labelCacheMemberObj *msGetLabelCacheMember(labelCacheObj *labelcache, int i)
 {
-    if(i >= 0 && i < labelcache->numlabels)
-    {
-        int p;
-        for(p=0; p<MS_MAX_LABEL_PRIORITY; p++)
-        {
-            if (i < labelcache->slots[p].numlabels )
-                return &(labelcache->slots[p].labels[i]); /* Found it */
-            else
-                i -= labelcache->slots[p].numlabels; /* Check next slots */
-        }
+  if(i >= 0 && i < labelcache->numlabels) {
+    int p;
+    for(p=0; p<MS_MAX_LABEL_PRIORITY; p++) {
+      if (i < labelcache->slots[p].numlabels )
+        return &(labelcache->slots[p].labels[i]); /* Found it */
+      else
+        i -= labelcache->slots[p].numlabels; /* Check next slots */
     }
+  }
 
-    /* Out of range / not found */
-    return NULL;
+  /* Out of range / not found */
+  return NULL;
 }
 
 
 int msInitFontSet(fontSetObj *fontset)
 {
-    fontset->filename = NULL;
-    
-    /* fontset->fonts = NULL; */
-    initHashTable(&(fontset->fonts));
-    
-    fontset->numfonts = 0;
-    fontset->map = NULL;
-    return( 0 );
+  fontset->filename = NULL;
+
+  /* fontset->fonts = NULL; */
+  initHashTable(&(fontset->fonts));
+
+  fontset->numfonts = 0;
+  fontset->map = NULL;
+  return( 0 );
 }
 
 int msFreeFontSet(fontSetObj *fontset)
 {
-    if (fontset->filename)
-        free(fontset->filename);
-    fontset->filename = NULL;
-    if (&(fontset->fonts))
-        msFreeHashItems(&(fontset->fonts));
-    /* fontset->fonts = NULL; */
-    fontset->numfonts = 0;    
-
-    return( 0 );
+  if (fontset->filename)
+    free(fontset->filename);
+  fontset->filename = NULL;
+  if (&(fontset->fonts))
+    msFreeHashItems(&(fontset->fonts));
+  /* fontset->fonts = NULL; */
+  fontset->numfonts = 0;
+
+  return( 0 );
 }
 
 int msLoadFontSet(fontSetObj *fontset, mapObj *map)
 {
-#ifdef USE_GD_FT
   FILE *stream;
   char buffer[MS_BUFFER_LENGTH];
   char alias[64], file1[MS_PATH_LENGTH], file2[MS_PATH_LENGTH];
@@ -636,7 +972,7 @@ int msLoadFontSet(fontSetObj *fontset, mapObj *map)
 
     if (!(*file1) || !(*alias) || (strlen(file1) <= 0))
       continue;
-    
+
     bFullPath = 0;
 #if defined(_WIN32) && !defined(__CYGWIN__)
     if (file1[0] == '\\' || (strlen(file1) > 1 && (file1[1] == ':')))
@@ -654,12 +990,12 @@ int msLoadFontSet(fontSetObj *fontset, mapObj *map)
 
       /*
       ** msBuildPath is use here, but if we have to save the fontset file
-      ** the msBuildPath must be done everywhere the fonts are used and 
+      ** the msBuildPath must be done everywhere the fonts are used and
       ** removed here.
       */
-      msInsertHashTable(&(fontset->fonts), alias, 
+      msInsertHashTable(&(fontset->fonts), alias,
                         msBuildPath(szPath, fontset->map->mappath, file2));
-      
+
     }
 
     i++;
@@ -670,121 +1006,135 @@ int msLoadFontSet(fontSetObj *fontset, mapObj *map)
   free(path);
 
   return(0);
-#else
-  msSetError(MS_TTFERR, "TrueType font support is not available.", "msLoadFontSet()");
-  return(-1);
-#endif
 }
 
-int msGetTruetypeTextBBox(rendererVTableObj *renderer, char *font, double size, char *string, rectObj *rect, double **advances) {
-	if(renderer) {
-		return renderer->getTruetypeTextBBox(renderer,font,size,string,rect,advances);
-	} 
-#ifdef USE_GD_FT
-	else {
-        int bbox[8];
-        char *error;
-        if(advances) {
-#if defined (GD_HAS_FTEX_XSHOW)
-            char *s;
-            int k;
-            gdFTStringExtra strex;
-            strex.flags = gdFTEX_XSHOW;
-            error = gdImageStringFTEx(NULL, bbox, 0, font, size, 0, 0, 0, string, &strex);
-            if(error) {
-                msSetError(MS_TTFERR, error, "gdImageStringFTEx()");
-                return(MS_FAILURE);
-            }
-
-            *advances = (double*)malloc( strlen(string) * sizeof(double) );
-            MS_CHECK_ALLOC(*advances, strlen(string) * sizeof(double), MS_FAILURE);
-            s = strex.xshow;
-            k = 0;
-            while ( *s && k < strlen(string) ) {
-                (*advances)[k++] = atof(s);      
-                while ( *s && *s != ' ')
-                    s++;
-                if ( *s == ' ' )
-                    s++;
-            }
-
-            gdFree(strex.xshow); /* done with character advances */
-
-            rect->minx = bbox[0];
-            rect->miny = bbox[5];
-            rect->maxx = bbox[2];
-            rect->maxy = bbox[1];
-            return MS_SUCCESS;
-#else
-            msSetError(MS_TTFERR, "gdImageStringFTEx support is not available or is not current enough (requires 2.0.29 or higher).", "msGetTruetypeTextBBox()");
-            return MS_FAILURE;
-#endif
-        } else {
-            error = gdImageStringFT(NULL, bbox, 0, font, size, 0, 0, 0, string);
-            if(error) {
-                msSetError(MS_TTFERR, "gdImageStringFT: %s (%s)", "msGetTruetypeTextBBox()", error, font);
-                return(MS_FAILURE);
-            }
+int msGetTruetypeTextBBox(rendererVTableObj *renderer, char* fontstring, fontSetObj *fontset,
+                          double size, char *string, rectObj *rect, double **advances, int bAdjustbaseline)
+{
+  outputFormatObj *format = NULL;
+  int ret = MS_FAILURE;
+  char *lookedUpFonts[MS_MAX_LABEL_FONTS];
+  int numfonts;
+  if(!renderer) {
+    outputFormatObj *format = msCreateDefaultOutputFormat(NULL,"AGG/PNG","tmp");
+    if(!format) {
+      goto tt_cleanup;
+    }
+    msInitializeRendererVTable(format);
+    renderer = format->vtable;
+  }
+  if(MS_FAILURE == msFontsetLookupFonts(fontstring, &numfonts, fontset, lookedUpFonts))
+    goto tt_cleanup;
+  ret = renderer->getTruetypeTextBBox(renderer,lookedUpFonts,numfonts,size,string,rect,advances,bAdjustbaseline);
+tt_cleanup:
+  if(format) {
+    msFreeOutputFormat(format);
+  }
+  return ret;
+}
 
-            rect->minx = bbox[0];
-            rect->miny = bbox[5];
-            rect->maxx = bbox[2];
-            rect->maxy = bbox[1];
-            return MS_SUCCESS;
-        }
+int msGetRasterTextBBox(rendererVTableObj *renderer, int size, char *string, rectObj *rect)
+{
+  if(renderer && renderer->supports_bitmap_fonts) {
+    int num_lines=1, cur_line_length=0, max_line_length=0;
+    char *stringPtr = string;
+    fontMetrics *fontPtr;
+    if((fontPtr=renderer->bitmapFontMetrics[size]) == NULL) {
+      msSetError(MS_MISCERR, "selected renderer does not support bitmap font size %d", "msGetRasterTextBBox()",size);
+      return MS_FAILURE;
     }
-#else
-    /*shouldn't happen*/
+    while(*stringPtr) {
+      if(*stringPtr=='\n') {
+        max_line_length = MS_MAX(cur_line_length,max_line_length);
+        num_lines++;
+        cur_line_length=0;
+      } else {
+        if(*stringPtr!='\r')
+          cur_line_length++;
+      }
+      stringPtr++;
+    }
+    max_line_length = MS_MAX(cur_line_length,max_line_length);
+    rect->minx = 0;
+    rect->miny = -fontPtr->charHeight;
+    rect->maxx = fontPtr->charWidth * max_line_length;
+    rect->maxy = fontPtr->charHeight * (num_lines-1);
+    return MS_SUCCESS;
+  } else if(!renderer) {
+    int ret = MS_FAILURE;
+    outputFormatObj *format = msCreateDefaultOutputFormat(NULL,"AGG/PNG","tmp");
+    if(!format) {
+      msSetError(MS_MISCERR, "failed to create default format", "msGetRasterTextBBox()");
+      return MS_FAILURE;
+    }
+    msInitializeRendererVTable(format);
+    renderer = format->vtable;
+    ret = msGetRasterTextBBox(renderer,size,string,rect);
+    msFreeOutputFormat(format);
+    return ret;
+  } else {
+    msSetError(MS_MISCERR, "selected renderer does not support raster fonts", "msGetRasterTextBBox()");
     return MS_FAILURE;
-#endif
+  }
 }
 
-int msGetRasterTextBBox(rendererVTableObj *renderer, int size, char *string, rectObj *rect) {
-    if(renderer && renderer->supports_bitmap_fonts) {
-    	int num_lines=1, cur_line_length=0, max_line_length=0;
-    	char *stringPtr = string;
-    	fontMetrics *fontPtr;
-    	if((fontPtr=renderer->bitmapFontMetrics[size]) == NULL) {
-    		msSetError(MS_MISCERR, "selected renderer does not support bitmap font size %d", "msGetRasterTextBBox()",size);
-    		return MS_FAILURE;
-    	}
-    	while(*stringPtr) {
-    		if(*stringPtr=='\n') {
-    			max_line_length = MS_MAX(cur_line_length,max_line_length);
-    			num_lines++;
-    			cur_line_length=0;
-    		} else {
-    			if(*stringPtr!='\r')
-    				cur_line_length++;
-    		}
-    		stringPtr++;
-    	}
-    	max_line_length = MS_MAX(cur_line_length,max_line_length);
-    	rect->minx = 0;
-		rect->miny = -(fontPtr->charHeight * num_lines);
-		rect->maxx = fontPtr->charWidth * max_line_length;
-		rect->maxy = 0;
-    	return MS_SUCCESS;
+
+char *msFontsetLookupFont(fontSetObj *fontset, char *fontKey)
+{
+  char *font;
+  if(!fontKey) {
+    msSetError(MS_TTFERR, "Requested font (NULL) not found.", "msFontsetLookupFont()");
+    return NULL;
+  }
+  font = msLookupHashTable(&(fontset->fonts), fontKey);
+  if(!font) {
+    msSetError(MS_TTFERR, "Requested font (%s) not found.", "msFontsetLookupFont()", fontKey);
+    return NULL;
+  }
+  return font;
+}
+
+int msFontsetLookupFonts(char* fontstring, int *numfonts, fontSetObj *fontset, char **lookedUpFonts)
+{
+  char *start,*ptr;
+  *numfonts = 0;
+  start = ptr = fontstring;
+  while(*numfonts<MS_MAX_LABEL_FONTS) {
+    if(*ptr==',') {
+      if(start==ptr) { /*first char is a comma, or two successive commas*/
+        start = ++ptr;
+        continue;
+      }
+      *ptr = 0;
+      lookedUpFonts[*numfonts] = msLookupHashTable(&(fontset->fonts), start);
+      *ptr = ',';
+      if (!lookedUpFonts[*numfonts]) {
+        msSetError(MS_TTFERR, "Requested font (%s) not found.","msFontsetLookupFonts()", fontstring);
+        return MS_FAILURE;
+      }
+      start = ++ptr;
+      (*numfonts)++;
+    } else if(*ptr==0) {
+      if(start==ptr) { /* last char of string was a comma */
+        return MS_SUCCESS;
+      }
+      lookedUpFonts[*numfonts] = msLookupHashTable(&(fontset->fonts), start);
+      if (!lookedUpFonts[*numfonts]) {
+        msSetError(MS_TTFERR, "Requested font (%s) not found.","msFontsetLookupFonts()", fontstring);
+        return (MS_FAILURE);
+      }
+      (*numfonts)++;
+      return MS_SUCCESS;
     } else {
-		msSetError(MS_MISCERR, "selected renderer does not support raster fonts", "msGetRasterTextBBox()");
-		return MS_FAILURE;
-	}
+      ptr++;
+    }
+  }
+  msSetError(MS_TTFERR, "Requested font (%s) not has too many members (max is %d)",
+             "msFontsetLookupFonts()", fontstring, MS_MAX_LABEL_FONTS);
+  return MS_FAILURE;
 }
 
 
-char *msFontsetLookupFont(fontSetObj *fontset, char *fontKey) {
-  char *font;
-	if(!fontKey) {
-		msSetError(MS_TTFERR, "Requested font (NULL) not found.", "msFontsetLookupFont()");
-		return NULL;
-	}
-	font = msLookupHashTable(&(fontset->fonts), fontKey);
-	if(!font) {
-	  msSetError(MS_TTFERR, "Requested font (%s) not found.", "msGetLabelSize()", fontKey);
-	  return NULL;
-	}
-	return font;
-}
 /*
 ** Note: All these routines assume a reference point at the LL corner of the text. GD's
 ** bitmapped fonts use UL and this is compensated for. Note the rect is relative to the
@@ -799,76 +1149,29 @@ int msGetLabelSize(mapObj *map, labelObj *label, char *string, double size, rect
   if (map)
     renderer =MS_MAP_RENDERER(map);
 
-  if (!renderer)
-    return MS_FAILURE;
   if(label->type == MS_TRUETYPE) {
-    char *font=msFontsetLookupFont(&(map->fontset), label->font);
-    if(!font) {
-    	//error message already set in fontset lookup
-    	return MS_FAILURE;
+    if(!label->font) {
+      msSetError(MS_MISCERR, "label has no true type font", "msGetLabelSize()");
+      return MS_FAILURE;
+    }
+    return msGetTruetypeTextBBox(renderer,label->font,&(map->fontset),size,string,rect,advances,1);
+  } else if(label->type == MS_BITMAP) {
+    if(renderer->supports_bitmap_fonts)
+      return msGetRasterTextBBox(renderer,MS_NINT(label->size),string,rect);
+    else {
+      msSetError(MS_MISCERR, "renderer does not support bitmap fonts", "msGetLabelSize()");
+      return MS_FAILURE;
     }
-    return msGetTruetypeTextBBox(renderer,font,size,string,rect,advances);
-  } else if(label->type == MS_BITMAP){
-	  if(renderer->supports_bitmap_fonts)
-		  return msGetRasterTextBBox(renderer,MS_NINT(label->size),string,rect);
-	  else {
-		  msSetError(MS_MISCERR, "renderer does not support bitmap fonts", "msGetLabelSize()");
-		  return MS_FAILURE;
-	  }
   } else {
-	  msSetError(MS_MISCERR, "unknown label type", "msGetLabelSize()");
-	  return MS_FAILURE;
-  }
-}
-
-gdFontPtr msGetBitmapFont(int size)
-{
-  switch(size) { /* set the font to use */
-  case MS_TINY:
-#ifdef GD_HAS_GETBITMAPFONT
-    return gdFontGetTiny();
-#else
-    return(gdFontTiny);
-#endif
-    break;
-  case MS_SMALL:
-#ifdef GD_HAS_GETBITMAPFONT
-    return gdFontGetSmall();
-#else
-    return(gdFontSmall);
-#endif
-    break;
-  case MS_MEDIUM:
-#ifdef GD_HAS_GETBITMAPFONT
-    return gdFontGetMediumBold();
-#else
-    return(gdFontMediumBold);
-#endif
-    break;
-  case MS_LARGE:
-#ifdef GD_HAS_GETBITMAPFONT
-    return gdFontGetLarge();
-#else
-    return(gdFontLarge);
-#endif
-    break;
-  case MS_GIANT:
-#ifdef GD_HAS_GETBITMAPFONT
-    return gdFontGetGiant();
-#else
-    return(gdFontGiant);
-#endif
-    break;
-  default:
-    msSetError(MS_GDERR,"Invalid bitmap font. Must be one of tiny, small, medium, large or giant." , "msGetBitmapFont()");
-    return(NULL);
+    msSetError(MS_MISCERR, "unknown label type", "msGetLabelSize()");
+    return MS_FAILURE;
   }
 }
 
 #define MARKER_SLOP 2
 
 /*pointObj get_metrics_line(pointObj *p, int position, rectObj rect, int ox, int oy, double angle, int buffer, lineObj *poly)
- * called by get_metrics and drawLabelCache 
+ * called by get_metrics and drawLabelCache
  * the poly lineObj MUST have at least 5 points allocated in poly->point
  * it should also probably have poly->numpoints set to 5 */
 pointObj get_metrics_line(pointObj *p, int position, rectObj rect, int ox, int oy, double angle, int buffer, lineObj *poly)
@@ -882,42 +1185,42 @@ pointObj get_metrics_line(pointObj *p, int position, rectObj rect, int ox, int o
   h = rect.maxy - rect.miny;
 
   switch(position) {
-  case MS_UL:
-    x1 = -w - ox;
-    y1 = -oy;
-    break;
-  case MS_UC:
-    x1 = -(w/2.0);
-    y1 = -oy - MARKER_SLOP;
-    break;
-  case MS_UR:
-    x1 = ox;
-    y1 = -oy;
-    break;
-  case MS_CL:
-    x1 = -w - ox - MARKER_SLOP;
-    y1 = (h/2.0);
-    break;
-  case MS_CC:
-    x1 = -(w/2.0) + ox;
-    y1 = (h/2.0) + oy;
-    break;
-  case MS_CR:
-    x1 = ox + MARKER_SLOP;
-    y1 = (h/2.0);
-    break;
-  case MS_LL:
-    x1 = -w - ox;
-    y1 = h + oy;
-    break;
-  case MS_LC:
-    x1 = -(w/2.0);
-    y1 = h + oy + MARKER_SLOP;
-    break;
-  case MS_LR:
-    x1 = ox;
-    y1 = h + oy;
-    break;
+    case MS_UL:
+      x1 = -w - ox;
+      y1 = -oy;
+      break;
+    case MS_UC:
+      x1 = -(w/2.0);
+      y1 = -oy - MARKER_SLOP;
+      break;
+    case MS_UR:
+      x1 = ox;
+      y1 = -oy;
+      break;
+    case MS_CL:
+      x1 = -w - ox - MARKER_SLOP;
+      y1 = (h/2.0);
+      break;
+    case MS_CC:
+      x1 = -(w/2.0) + ox;
+      y1 = (h/2.0) + oy;
+      break;
+    case MS_CR:
+      x1 = ox + MARKER_SLOP;
+      y1 = (h/2.0);
+      break;
+    case MS_LL:
+      x1 = -w - ox;
+      y1 = h + oy;
+      break;
+    case MS_LC:
+      x1 = -(w/2.0);
+      y1 = h + oy + MARKER_SLOP;
+      break;
+    case MS_LR:
+      x1 = ox;
+      y1 = h + oy;
+      break;
   }
 
   sin_a = sin(MS_DEG_TO_RAD*angle);
@@ -929,30 +1232,30 @@ pointObj get_metrics_line(pointObj *p, int position, rectObj rect, int ox, int o
   q.y = p->y - (x * sin_a + (y) * cos_a);
 
   if(poly) {
-      /*
-       * here we should/could have a test asserting that the poly lineObj 
-       * has at least 5 points available.
-       */
+    /*
+     * here we should/could have a test asserting that the poly lineObj
+     * has at least 5 points available.
+     */
 
     x2 = x1 - buffer; /* ll */
     y2 = y1 + buffer;
-    poly->point[0].x = p->x + MS_NINT(x2 * cos_a - (-y2) * sin_a);
-    poly->point[0].y = p->y - MS_NINT(x2 * sin_a + (-y2) * cos_a);
+    poly->point[0].x = p->x + (x2 * cos_a - (-y2) * sin_a);
+    poly->point[0].y = p->y - (x2 * sin_a + (-y2) * cos_a);
 
     x2 = x1 - buffer; /* ul */
     y2 = y1 - h - buffer;
-    poly->point[1].x = p->x + MS_NINT(x2 * cos_a - (-y2) * sin_a);
-    poly->point[1].y = p->y - MS_NINT(x2 * sin_a + (-y2) * cos_a);
+    poly->point[1].x = p->x + (x2 * cos_a - (-y2) * sin_a);
+    poly->point[1].y = p->y - (x2 * sin_a + (-y2) * cos_a);
 
     x2 = x1 + w + buffer; /* ur */
     y2 = y1 - h - buffer;
-    poly->point[2].x = p->x + MS_NINT(x2 * cos_a - (-y2) * sin_a);
-    poly->point[2].y = p->y - MS_NINT(x2 * sin_a + (-y2) * cos_a);
+    poly->point[2].x = p->x + (x2 * cos_a - (-y2) * sin_a);
+    poly->point[2].y = p->y - (x2 * sin_a + (-y2) * cos_a);
 
     x2 = x1 + w + buffer; /* lr */
     y2 = y1 + buffer;
-    poly->point[3].x = p->x + MS_NINT(x2 * cos_a - (-y2) * sin_a);
-    poly->point[3].y = p->y - MS_NINT(x2 * sin_a + (-y2) * cos_a);
+    poly->point[3].x = p->x + (x2 * cos_a - (-y2) * sin_a);
+    poly->point[3].y = p->y - (x2 * sin_a + (-y2) * cos_a);
 
     poly->point[4].x = poly->point[0].x;
     poly->point[4].y = poly->point[0].y;
@@ -963,18 +1266,19 @@ pointObj get_metrics_line(pointObj *p, int position, rectObj rect, int ox, int o
 
 
 /* static pointObj get_metrics(pointObj *p, int position, rectObj rect, int ox, int oy, double angle, int buffer, shapeObj *poly) */
-pointObj get_metrics(pointObj *p, int position, rectObj rect, int ox, int oy, double angle, int buffer, shapeObj *poly) {
-    lineObj newline;
-    pointObj newpoints[5];
-    pointObj rp;
-    newline.numpoints=5;
-    newline.point=newpoints;
-    rp = get_metrics_line(p, position, rect, ox,oy, angle, buffer, &newline);
-    if(poly) {
-        msAddLine(poly,&newline);
-        msComputeBounds(poly);
-    }
-    return rp;
+pointObj get_metrics(pointObj *p, int position, rectObj rect, int ox, int oy, double angle, int buffer, shapeObj *poly)
+{
+  lineObj newline;
+  pointObj newpoints[5];
+  pointObj rp;
+  newline.numpoints=5;
+  newline.point=newpoints;
+  rp = get_metrics_line(p, position, rect, ox,oy, angle, buffer, &newline);
+  if(poly) {
+    msAddLine(poly,&newline);
+    msComputeBounds(poly);
+  }
+  return rp;
 }
 
 /*
@@ -983,28 +1287,31 @@ pointObj get_metrics(pointObj *p, int position, rectObj rect, int ox, int oy, do
 */
 
 /* static int intersectLabelPolygons(shapeObj *p1, shapeObj *p2) { */
-int intersectLabelPolygons(shapeObj *p1, shapeObj *p2) {
+int intersectLabelPolygons(shapeObj *p1, shapeObj *p2)
+{
   int c1,v1,c2,v2;
   pointObj *point;
 
   /* STEP 0: check bounding boxes */
-  if(!msRectOverlap(&p1->bounds, &p2->bounds)) /* from alans at wunderground.com */
+  if(!msRectOverlap(&p1->bounds, &p2->bounds)) { /* from alans at wunderground.com */
     return(MS_FALSE);
+  }
 
   /* STEP 1: look for intersecting line segments */
   for(c1=0; c1<p1->numlines; c1++)
     for(v1=1; v1<p1->line[c1].numpoints; v1++)
       for(c2=0; c2<p2->numlines; c2++)
-	for(v2=1; v2<p2->line[c2].numpoints; v2++)
-	  if(msIntersectSegments(&(p1->line[c1].point[v1-1]), &(p1->line[c1].point[v1]), &(p2->line[c2].point[v2-1]), &(p2->line[c2].point[v2])) ==  MS_TRUE)
-	    return(MS_TRUE);
+        for(v2=1; v2<p2->line[c2].numpoints; v2++)
+          if(msIntersectSegments(&(p1->line[c1].point[v1-1]), &(p1->line[c1].point[v1]), &(p2->line[c2].point[v2-1]), &(p2->line[c2].point[v2])) ==  MS_TRUE) {
+            return(MS_TRUE);
+          }
 
   /* STEP 2: polygon one completely contains two (only need to check one point from each part) */
   for(c2=0; c2<p2->numlines; c2++) {
     point = &(p2->line[c2].point[0]);
     for(c1=0; c1<p1->numlines; c1++) {
       if(msPointInPolygon(point, &p1->line[c1]) == MS_TRUE) /* ok, the point is in a polygon */
-	return(MS_TRUE);
+        return(MS_TRUE);
     }
   }
 
@@ -1013,7 +1320,7 @@ int intersectLabelPolygons(shapeObj *p1, shapeObj *p2) {
     point = &(p1->line[c1].point[0]);
     for(c2=0; c2<p2->numlines; c2++) {
       if(msPointInPolygon(point, &p2->line[c2]) == MS_TRUE) /* ok, the point is in a polygon */
-	return(MS_TRUE);
+        return(MS_TRUE);
     }
   }
 
@@ -1021,138 +1328,131 @@ int intersectLabelPolygons(shapeObj *p1, shapeObj *p2) {
 }
 
 /* For MapScript, exactly the same the msInsertStyle */
-int msInsertLabelStyle(labelObj *label, styleObj *style, int nStyleIndex) {
-    int i;
+int msInsertLabelStyle(labelObj *label, styleObj *style, int nStyleIndex)
+{
+  int i;
 
-    if (!style)
-    {
-        msSetError(MS_CHILDERR, "Can't insert a NULL Style", "msInsertLabelStyle()");
-        return -1;
-    }
+  if (!style) {
+    msSetError(MS_CHILDERR, "Can't insert a NULL Style", "msInsertLabelStyle()");
+    return -1;
+  }
 
-    /* Ensure there is room for a new style */
-    if (msGrowLabelStyles(label) == NULL) {
-        return -1;
-    }
-    /* Catch attempt to insert past end of styles array */
-    else if (nStyleIndex >= label->numstyles) {
-        msSetError(MS_CHILDERR, "Cannot insert style beyond index %d", "insertLabelStyle()", label->numstyles-1);
-        return -1;
-    }
-    else if (nStyleIndex < 0) { /* Insert at the end by default */
-        label->styles[label->numstyles]=style;
-	MS_REFCNT_INCR(style);
-        label->numstyles++;
-        return label->numstyles-1;
-    }
-    else if (nStyleIndex >= 0 && nStyleIndex < label->numstyles) {
-        /* Move styles existing at the specified nStyleIndex or greater */
-        /* to a higher nStyleIndex */
-        for (i=label->numstyles-1; i>=nStyleIndex; i--) {
-            label->styles[i+1] = label->styles[i];
-        }
-        label->styles[nStyleIndex]=style;
-	MS_REFCNT_INCR(style);
-        label->numstyles++;
-        return nStyleIndex;
-    }
-    else {
-        msSetError(MS_CHILDERR, "Invalid nStyleIndex", "insertLabelStyle()");
-        return -1;
+  /* Ensure there is room for a new style */
+  if (msGrowLabelStyles(label) == NULL) {
+    return -1;
+  }
+  /* Catch attempt to insert past end of styles array */
+  else if (nStyleIndex >= label->numstyles) {
+    msSetError(MS_CHILDERR, "Cannot insert style beyond index %d", "insertLabelStyle()", label->numstyles-1);
+    return -1;
+  } else if (nStyleIndex < 0) { /* Insert at the end by default */
+    label->styles[label->numstyles]=style;
+    MS_REFCNT_INCR(style);
+    label->numstyles++;
+    return label->numstyles-1;
+  } else if (nStyleIndex >= 0 && nStyleIndex < label->numstyles) {
+    /* Move styles existing at the specified nStyleIndex or greater */
+    /* to a higher nStyleIndex */
+    for (i=label->numstyles-1; i>=nStyleIndex; i--) {
+      label->styles[i+1] = label->styles[i];
     }
+    label->styles[nStyleIndex]=style;
+    MS_REFCNT_INCR(style);
+    label->numstyles++;
+    return nStyleIndex;
+  } else {
+    msSetError(MS_CHILDERR, "Invalid nStyleIndex", "insertLabelStyle()");
+    return -1;
+  }
 }
 
 /**
  * Move the style up inside the array of styles.
- */  
+ */
 int msMoveLabelStyleUp(labelObj *label, int nStyleIndex)
 {
-    styleObj *psTmpStyle = NULL;
-    if (label && nStyleIndex < label->numstyles && nStyleIndex >0)
-    {
-        psTmpStyle = (styleObj *)malloc(sizeof(styleObj));
-        initStyle(psTmpStyle);
-        
-        msCopyStyle(psTmpStyle, label->styles[nStyleIndex]);
-
-        msCopyStyle(label->styles[nStyleIndex], 
-                    label->styles[nStyleIndex-1]);
-        
-        msCopyStyle(label->styles[nStyleIndex-1], psTmpStyle);
-
-        return(MS_SUCCESS);
-    }
-    msSetError(MS_CHILDERR, "Invalid index: %d", "msMoveLabelStyleUp()",
-               nStyleIndex);
-    return (MS_FAILURE);
+  styleObj *psTmpStyle = NULL;
+  if (label && nStyleIndex < label->numstyles && nStyleIndex >0) {
+    psTmpStyle = (styleObj *)malloc(sizeof(styleObj));
+    initStyle(psTmpStyle);
+
+    msCopyStyle(psTmpStyle, label->styles[nStyleIndex]);
+
+    msCopyStyle(label->styles[nStyleIndex],
+                label->styles[nStyleIndex-1]);
+
+    msCopyStyle(label->styles[nStyleIndex-1], psTmpStyle);
+
+    return(MS_SUCCESS);
+  }
+  msSetError(MS_CHILDERR, "Invalid index: %d", "msMoveLabelStyleUp()",
+             nStyleIndex);
+  return (MS_FAILURE);
 }
 
 
 /**
  * Move the style down inside the array of styles.
- */  
+ */
 int msMoveLabelStyleDown(labelObj *label, int nStyleIndex)
 {
-    styleObj *psTmpStyle = NULL;
+  styleObj *psTmpStyle = NULL;
 
-    if (label && nStyleIndex < label->numstyles-1 && nStyleIndex >=0)
-    {
-        psTmpStyle = (styleObj *)malloc(sizeof(styleObj));
-        initStyle(psTmpStyle);
-        
-        msCopyStyle(psTmpStyle, label->styles[nStyleIndex]);
+  if (label && nStyleIndex < label->numstyles-1 && nStyleIndex >=0) {
+    psTmpStyle = (styleObj *)malloc(sizeof(styleObj));
+    initStyle(psTmpStyle);
 
-        msCopyStyle(label->styles[nStyleIndex], 
-                    label->styles[nStyleIndex+1]);
-        
-        msCopyStyle(label->styles[nStyleIndex+1], psTmpStyle);
+    msCopyStyle(psTmpStyle, label->styles[nStyleIndex]);
 
-        return(MS_SUCCESS);
-    }
-    msSetError(MS_CHILDERR, "Invalid index: %d", "msMoveLabelStyleDown()",
-               nStyleIndex);
-    return (MS_FAILURE);
+    msCopyStyle(label->styles[nStyleIndex],
+                label->styles[nStyleIndex+1]);
+
+    msCopyStyle(label->styles[nStyleIndex+1], psTmpStyle);
+
+    return(MS_SUCCESS);
+  }
+  msSetError(MS_CHILDERR, "Invalid index: %d", "msMoveLabelStyleDown()",
+             nStyleIndex);
+  return (MS_FAILURE);
 }
 
 /**
  * Delete the style identified by the index and shift
  * styles that follows the deleted style.
- */  
+ */
 int msDeleteLabelStyle(labelObj *label, int nStyleIndex)
 {
-    int i = 0;
-    if (label && nStyleIndex < label->numstyles && nStyleIndex >=0)
-    {
-        if (freeStyle(label->styles[nStyleIndex]) == MS_SUCCESS)
-            msFree(label->styles[nStyleIndex]);
-        for (i=nStyleIndex; i< label->numstyles-1; i++)
-        {
-            label->styles[i] = label->styles[i+1];
-        }
-        label->styles[label->numstyles-1] = NULL;
-        label->numstyles--;
-        return(MS_SUCCESS);
+  int i = 0;
+  if (label && nStyleIndex < label->numstyles && nStyleIndex >=0) {
+    if (freeStyle(label->styles[nStyleIndex]) == MS_SUCCESS)
+      msFree(label->styles[nStyleIndex]);
+    for (i=nStyleIndex; i< label->numstyles-1; i++) {
+      label->styles[i] = label->styles[i+1];
     }
-    msSetError(MS_CHILDERR, "Invalid index: %d", "msDeleteLabelStyle()",
-               nStyleIndex);
-    return (MS_FAILURE);
+    label->styles[label->numstyles-1] = NULL;
+    label->numstyles--;
+    return(MS_SUCCESS);
+  }
+  msSetError(MS_CHILDERR, "Invalid index: %d", "msDeleteLabelStyle()",
+             nStyleIndex);
+  return (MS_FAILURE);
 }
 
-styleObj *msRemoveLabelStyle(labelObj *label, int nStyleIndex) {
-    int i;
-    styleObj *style;
-    if (nStyleIndex < 0 || nStyleIndex >= label->numstyles) {
-        msSetError(MS_CHILDERR, "Cannot remove style, invalid nStyleIndex %d", "removeLabelStyle()", nStyleIndex);
-        return NULL;
-    }
-    else {
-        style=label->styles[nStyleIndex];
-        for (i=nStyleIndex; i<label->numstyles-1; i++) {
-             label->styles[i]=label->styles[i+1];
-        }
-	label->styles[label->numstyles-1]=NULL;
-        label->numstyles--;
-	MS_REFCNT_DECR(style);
-        return style;
+styleObj *msRemoveLabelStyle(labelObj *label, int nStyleIndex)
+{
+  int i;
+  styleObj *style;
+  if (nStyleIndex < 0 || nStyleIndex >= label->numstyles) {
+    msSetError(MS_CHILDERR, "Cannot remove style, invalid nStyleIndex %d", "removeLabelStyle()", nStyleIndex);
+    return NULL;
+  } else {
+    style=label->styles[nStyleIndex];
+    for (i=nStyleIndex; i<label->numstyles-1; i++) {
+      label->styles[i]=label->styles[i+1];
     }
+    label->styles[label->numstyles-1]=NULL;
+    label->numstyles--;
+    MS_REFCNT_DECR(style);
+    return style;
+  }
 }
diff --git a/maplayer.c b/maplayer.c
index a486e2d..5691c2e 100644
--- a/maplayer.c
+++ b/maplayer.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -36,7 +36,7 @@
 #include "mapparser.h"
 
 #include <assert.h>
-MS_CVSID("$Id$")
+
 
 static int populateVirtualTable(layerVTableObj *vtable);
 
@@ -48,22 +48,22 @@ static int populateVirtualTable(layerVTableObj *vtable);
 ** helper functions below initialize and free that structure member which is used locally by layer
 ** specific functions.
 */
-int msLayerInitItemInfo(layerObj *layer) 
+int msLayerInitItemInfo(layerObj *layer)
 {
-    if ( ! layer->vtable) {
-        int rv =  msInitializeVirtualTable(layer);
-        if (rv != MS_SUCCESS)
-            return rv;
-    }
-    return layer->vtable->LayerInitItemInfo(layer);
+  if ( ! layer->vtable) {
+    int rv =  msInitializeVirtualTable(layer);
+    if (rv != MS_SUCCESS)
+      return rv;
+  }
+  return layer->vtable->LayerInitItemInfo(layer);
 }
 
-void msLayerFreeItemInfo(layerObj *layer) 
+void msLayerFreeItemInfo(layerObj *layer)
 {
   if ( ! layer->vtable) {
-      int rv =  msInitializeVirtualTable(layer);
-      if (rv != MS_SUCCESS)
-          return;
+    int rv =  msInitializeVirtualTable(layer);
+    if (rv != MS_SUCCESS)
+      return;
   }
   layer->vtable->LayerFreeItemInfo(layer);
 }
@@ -76,8 +76,8 @@ int msLayerOpen(layerObj *layer)
   /* RFC-69 clustering support */
   if (layer->cluster.region)
     return msClusterLayerOpen(layer);
-    
-  if(layer->features && layer->connectiontype != MS_GRATICULE ) 
+
+  if(layer->features && layer->connectiontype != MS_GRATICULE )
     layer->connectiontype = MS_INLINE;
 
   if(layer->tileindex && layer->connectiontype == MS_SHAPEFILE)
@@ -87,9 +87,9 @@ int msLayerOpen(layerObj *layer)
     layer->connectiontype = MS_RASTER;
 
   if ( ! layer->vtable) {
-      int rv =  msInitializeVirtualTable(layer);
-      if (rv != MS_SUCCESS)
-          return rv;
+    int rv =  msInitializeVirtualTable(layer);
+    if (rv != MS_SUCCESS)
+      return rv;
   }
   return layer->vtable->LayerOpen(layer);
 }
@@ -100,9 +100,9 @@ int msLayerOpen(layerObj *layer)
 int msLayerIsOpen(layerObj *layer)
 {
   if ( ! layer->vtable) {
-      int rv =  msInitializeVirtualTable(layer);
-      if (rv != MS_SUCCESS)
-          return rv;
+    int rv =  msInitializeVirtualTable(layer);
+    if (rv != MS_SUCCESS)
+      return rv;
   }
   return layer->vtable->LayerIsOpen(layer);
 }
@@ -133,9 +133,9 @@ int msLayerSupportsCommonFilters(layerObj *layer)
 int msLayerWhichShapes(layerObj *layer, rectObj rect, int isQuery)
 {
   if ( ! layer->vtable) {
-      int rv =  msInitializeVirtualTable(layer);
-      if (rv != MS_SUCCESS)
-          return rv;
+    int rv =  msInitializeVirtualTable(layer);
+    if (rv != MS_SUCCESS)
+      return rv;
   }
   return layer->vtable->LayerWhichShapes(layer, rect, isQuery);
 }
@@ -146,15 +146,15 @@ int msLayerWhichShapes(layerObj *layer, rectObj rect, int isQuery)
 **
 ** Shapefiles: NULL shapes (shapes with attributes but NO vertices are skipped)
 */
-int msLayerNextShape(layerObj *layer, shapeObj *shape) 
+int msLayerNextShape(layerObj *layer, shapeObj *shape)
 {
   if ( ! layer->vtable) {
-      int rv =  msInitializeVirtualTable(layer);
-      if (rv != MS_SUCCESS)
-          return rv;
+    int rv =  msInitializeVirtualTable(layer);
+    if (rv != MS_SUCCESS)
+      return rv;
   }
 
-  /* At the end of switch case (default -> break; -> return MS_FAILURE), 
+  /* At the end of switch case (default -> break; -> return MS_FAILURE),
    * was following TODO ITEM:
    */
   /* TO DO! This is where dynamic joins will happen. Joined attributes will be */
@@ -202,9 +202,9 @@ int msLayerGetShape(layerObj *layer, shapeObj *shape, resultObj *record)
 /*
 ** Closes resources used by a particular layer.
 */
-void msLayerClose(layerObj *layer) 
+void msLayerClose(layerObj *layer)
 {
-  int i,j;
+  int i,j,k;
 
   /* no need for items once the layer is closed */
   msLayerFreeItemInfo(layer);
@@ -218,11 +218,15 @@ void msLayerClose(layerObj *layer)
   freeExpressionTokens(&(layer->filter));
   freeExpressionTokens(&(layer->cluster.group));
   freeExpressionTokens(&(layer->cluster.filter));
-  for(i=0; i<layer->numclasses; i++) {    
+  for(i=0; i<layer->numclasses; i++) {
     freeExpressionTokens(&(layer->class[i]->expression));
     freeExpressionTokens(&(layer->class[i]->text));
     for(j=0; j<layer->class[i]->numstyles; j++)
       freeExpressionTokens(&(layer->class[i]->styles[j]->_geomtransform));
+    for(k=0; k<layer->class[i]->numlabels; k++) {
+      freeExpressionTokens(&(layer->class[i]->labels[k]->expression));
+      freeExpressionTokens(&(layer->class[i]->labels[k]->text));
+    }
   }
 
   if (layer->vtable) {
@@ -235,7 +239,7 @@ void msLayerClose(layerObj *layer)
 ** at this point. This function is used when processing query results to expose attributes to query
 ** templates. At that point all attributes are fair game.
 */
-int msLayerGetItems(layerObj *layer) 
+int msLayerGetItems(layerObj *layer)
 {
   const char *itemNames;
   /* clean up any previously allocated instances */
@@ -247,30 +251,28 @@ int msLayerGetItems(layerObj *layer)
   }
 
   if ( ! layer->vtable) {
-      int rv =  msInitializeVirtualTable(layer);
-      if (rv != MS_SUCCESS)
-          return rv;
+    int rv =  msInitializeVirtualTable(layer);
+    if (rv != MS_SUCCESS)
+      return rv;
   }
 
-  /* At the end of switch case (default -> break; -> return MS_FAILURE), 
+  /* At the end of switch case (default -> break; -> return MS_FAILURE),
    * was following TODO ITEM:
    */
   /* TO DO! Need to add any joined itemd on to the core layer items, one long list!  */
   itemNames = msLayerGetProcessingKey( layer, "ITEMS" );
-  if (itemNames)
-  {
+  if (itemNames) {
     layer->items = msStringSplit(itemNames, ',', &layer->numitems);
     /* populate the iteminfo array */
     return (msLayerInitItemInfo(layer));
-  }
-  else
+  } else
     return layer->vtable->LayerGetItems(layer);
 }
 
 /*
 ** Returns extent of spatial coverage for a layer.
 **
-** If layer->extent is set then this value is used, otherwise the 
+** If layer->extent is set then this value is used, otherwise the
 ** driver-specific implementation is called (this can be expensive).
 **
 ** If layer is not already opened then it is opened and closed (so this
@@ -278,35 +280,33 @@ int msLayerGetItems(layerObj *layer)
 **
 ** Returns MS_SUCCESS/MS_FAILURE.
 */
-int msLayerGetExtent(layerObj *layer, rectObj *extent) 
+int msLayerGetExtent(layerObj *layer, rectObj *extent)
 {
   int need_to_close = MS_FALSE, status = MS_SUCCESS;
 
-  if (MS_VALID_EXTENT(layer->extent))
-  {
-      *extent = layer->extent;
-      return MS_SUCCESS;
+  if (MS_VALID_EXTENT(layer->extent)) {
+    *extent = layer->extent;
+    return MS_SUCCESS;
   }
 
-  if (!msLayerIsOpen(layer))
-  {
-      if (msLayerOpen(layer) != MS_SUCCESS)
-          return MS_FAILURE;
-      need_to_close = MS_TRUE;
+  if (!msLayerIsOpen(layer)) {
+    if (msLayerOpen(layer) != MS_SUCCESS)
+      return MS_FAILURE;
+    need_to_close = MS_TRUE;
   }
 
   if ( ! layer->vtable) {
-      int rv =  msInitializeVirtualTable(layer);
-      if (rv != MS_SUCCESS) {
-        if (need_to_close)
-            msLayerClose(layer);
-            return rv;
-      }
+    int rv =  msInitializeVirtualTable(layer);
+    if (rv != MS_SUCCESS) {
+      if (need_to_close)
+        msLayerClose(layer);
+      return rv;
+    }
   }
   status = layer->vtable->LayerGetExtent(layer, extent);
 
   if (need_to_close)
-      msLayerClose(layer);
+    msLayerClose(layer);
 
   return(status);
 }
@@ -318,7 +318,7 @@ int msLayerGetItemIndex(layerObj *layer, char *item)
   for(i=0; i<layer->numitems; i++) {
     if(strcasecmp(layer->items[i], item) == 0) return(i);
   }
-    
+
   return -1; /* item not found */
 }
 
@@ -355,7 +355,7 @@ int msTokenizeExpression(expressionObj *expression, char **list, int *listsize)
   int token;
 
   /* TODO: make sure the constants can't somehow reference invalid expression types */
-  // if(expression->type != MS_EXPRESSION && expression->type != MS_GEOMTRANSFORM_EXPRESSION) return MS_SUCCESS;
+  /* if(expression->type != MS_EXPRESSION && expression->type != MS_GEOMTRANSFORM_EXPRESSION) return MS_SUCCESS; */
 
   msAcquireLock(TLOCK_PARSER);
   msyystate = MS_TOKENIZE_EXPRESSION;
@@ -372,62 +372,62 @@ int msTokenizeExpression(expressionObj *expression, char **list, int *listsize)
     node->next = NULL;
 
     switch(token) {
-    case MS_TOKEN_LITERAL_NUMBER:
-      node->token = token;
-      node->tokenval.dblval = msyynumber;
-      break;
-    case MS_TOKEN_LITERAL_STRING:
-      node->token = token;
-      node->tokenval.strval = msStrdup(msyystring_buffer);
-      break;
-    case MS_TOKEN_LITERAL_TIME:
-      node->token = token;
-      msTimeInit(&(node->tokenval.tmval));
-      if(msParseTime(msyystring_buffer, &(node->tokenval.tmval)) != MS_TRUE) {
-        msSetError(MS_PARSEERR, "Parsing time value failed.", "msTokenizeExpression()");
-        goto parse_error;
-      }
-      break;
-    case MS_TOKEN_BINDING_DOUBLE: /* we've encountered an attribute (binding) reference */
-    case MS_TOKEN_BINDING_INTEGER:
-    case MS_TOKEN_BINDING_STRING:
-    case MS_TOKEN_BINDING_TIME: 
-      node->token = token; /* binding type */
-      node->tokenval.bindval.item = msStrdup(msyystring_buffer);
-      if(list) node->tokenval.bindval.index = string2list(list, listsize, msyystring_buffer);
-      break;
-    case MS_TOKEN_BINDING_SHAPE:
-      node->token = token;
-      break;
-    case MS_TOKEN_FUNCTION_FROMTEXT: /* we want to process a shape from WKT once and not for every feature being evaluated */
-      if((token = msyylex()) != 40) { /* ( */
-        msSetError(MS_PARSEERR, "Parsing fromText function failed.", "msTokenizeExpression()");
-        goto parse_error;
-      }
+      case MS_TOKEN_LITERAL_NUMBER:
+        node->token = token;
+        node->tokenval.dblval = msyynumber;
+        break;
+      case MS_TOKEN_LITERAL_STRING:
+        node->token = token;
+        node->tokenval.strval = msStrdup(msyystring_buffer);
+        break;
+      case MS_TOKEN_LITERAL_TIME:
+        node->token = token;
+        msTimeInit(&(node->tokenval.tmval));
+        if(msParseTime(msyystring_buffer, &(node->tokenval.tmval)) != MS_TRUE) {
+          msSetError(MS_PARSEERR, "Parsing time value failed.", "msTokenizeExpression()");
+          goto parse_error;
+        }
+        break;
+      case MS_TOKEN_BINDING_DOUBLE: /* we've encountered an attribute (binding) reference */
+      case MS_TOKEN_BINDING_INTEGER:
+      case MS_TOKEN_BINDING_STRING:
+      case MS_TOKEN_BINDING_TIME:
+        node->token = token; /* binding type */
+        node->tokenval.bindval.item = msStrdup(msyystring_buffer);
+        if(list) node->tokenval.bindval.index = string2list(list, listsize, msyystring_buffer);
+        break;
+      case MS_TOKEN_BINDING_SHAPE:
+        node->token = token;
+        break;
+      case MS_TOKEN_FUNCTION_FROMTEXT: /* we want to process a shape from WKT once and not for every feature being evaluated */
+        if((token = msyylex()) != 40) { /* ( */
+          msSetError(MS_PARSEERR, "Parsing fromText function failed.", "msTokenizeExpression()");
+          goto parse_error;
+        }
 
-      if((token = msyylex()) != MS_TOKEN_LITERAL_STRING) {
-	msSetError(MS_PARSEERR, "Parsing fromText function failed.", "msTokenizeExpression()");
-        goto parse_error;
-      }
+        if((token = msyylex()) != MS_TOKEN_LITERAL_STRING) {
+          msSetError(MS_PARSEERR, "Parsing fromText function failed.", "msTokenizeExpression()");
+          goto parse_error;
+        }
 
-      node->token = MS_TOKEN_LITERAL_SHAPE;
-      node->tokenval.shpval = msShapeFromWKT(msyystring_buffer);
+        node->token = MS_TOKEN_LITERAL_SHAPE;
+        node->tokenval.shpval = msShapeFromWKT(msyystring_buffer);
 
-      if(!node->tokenval.shpval) {
-        msSetError(MS_PARSEERR, "Parsing fromText function failed, WKT processing failed.", "msTokenizeExpression()");
-        goto parse_error;
-      }
+        if(!node->tokenval.shpval) {
+          msSetError(MS_PARSEERR, "Parsing fromText function failed, WKT processing failed.", "msTokenizeExpression()");
+          goto parse_error;
+        }
 
-      /* todo: perhaps process optional args (e.g. projection) */
+        /* todo: perhaps process optional args (e.g. projection) */
 
-      if((token = msyylex()) != 41) { /* ) */
-        msSetError(MS_PARSEERR, "Parsing fromText function failed.", "msTokenizeExpression()");
-        goto parse_error;
-      }
-      break;
-    default:
-      node->token = token; /* for everything else */
-      break;
+        if((token = msyylex()) != 41) { /* ) */
+          msSetError(MS_PARSEERR, "Parsing fromText function failed.", "msTokenizeExpression()");
+          goto parse_error;
+        }
+        break;
+      default:
+        node->token = token; /* for everything else */
+        break;
     }
 
     /* add node to token list */
@@ -435,11 +435,11 @@ int msTokenizeExpression(expressionObj *expression, char **list, int *listsize)
       expression->tokens = node;
     } else {
       if(expression->tokens->tailifhead != NULL) /* this should never be NULL, but just in case */
-	expression->tokens->tailifhead->next = node; /* put the node at the end of the list */
+        expression->tokens->tailifhead->next = node; /* put the node at the end of the list */
     }
 
-    /* repoint the head of the list to the end  - our new element                                                                                                   
-       this causes a loop if we are at the head, be careful not to                                                                                                  
+    /* repoint the head of the list to the end  - our new element
+       this causes a loop if we are at the head, be careful not to
        walk in a loop */
     expression->tokens->tailifhead = node;
   }
@@ -449,9 +449,9 @@ int msTokenizeExpression(expressionObj *expression, char **list, int *listsize)
   msReleaseLock(TLOCK_PARSER);
   return MS_SUCCESS;
 
-  parse_error:
-    msReleaseLock(TLOCK_PARSER);
-    return MS_FAILURE;
+parse_error:
+  msReleaseLock(TLOCK_PARSER);
+  return MS_FAILURE;
 }
 
 /*
@@ -461,7 +461,7 @@ int msTokenizeExpression(expressionObj *expression, char **list, int *listsize)
 */
 int msLayerWhichItems(layerObj *layer, int get_all, char *metadata)
 {
-  int i, j, k, rv;
+  int i, j, k, l, rv;
   int nt=0;
 
   if (!layer->vtable) {
@@ -482,6 +482,11 @@ int msLayerWhichItems(layerObj *layer, int get_all, char *metadata)
   */
 
   /* layer level counts */
+  layer->classitemindex = -1;
+  layer->filteritemindex = -1;
+  layer->styleitemindex = -1;
+  layer->labelitemindex = -1;
+
   if(layer->classitem) nt++;
   if(layer->filteritem) nt++;
   if(layer->styleitem && strcasecmp(layer->styleitem, "AUTO") != 0) nt++;
@@ -510,12 +515,19 @@ int msLayerWhichItems(layerObj *layer, int get_all, char *metadata)
     if(layer->class[i]->expression.type == MS_EXPRESSION)
       nt += msCountChars(layer->class[i]->expression.string, '[');
 
-    nt += layer->class[i]->label.numbindings;
-    for(j=0; j<layer->class[i]->label.numstyles; j++) {
-      if(layer->class[i]->label.styles[j]->rangeitem) nt++;
-      nt += layer->class[i]->label.styles[j]->numbindings;
-      if(layer->class[i]->label.styles[j]->_geomtransform.type == MS_GEOMTRANSFORM_EXPRESSION)
-        nt += msCountChars(layer->class[i]->label.styles[j]->_geomtransform.string, '[');
+    for(l=0; l<layer->class[i]->numlabels; l++) {
+      nt += layer->class[i]->labels[l]->numbindings;
+      for(j=0; j<layer->class[i]->labels[l]->numstyles; j++) {
+        if(layer->class[i]->labels[l]->styles[j]->rangeitem) nt++;
+        nt += layer->class[i]->labels[l]->styles[j]->numbindings;
+        if(layer->class[i]->labels[l]->styles[j]->_geomtransform.type == MS_GEOMTRANSFORM_EXPRESSION)
+          nt += msCountChars(layer->class[i]->labels[l]->styles[j]->_geomtransform.string, '[');
+      }
+
+      if(layer->class[i]->labels[l]->expression.type == MS_EXPRESSION)
+        nt += msCountChars(layer->class[i]->labels[l]->expression.string, '[');
+      if(layer->class[i]->labels[l]->text.type == MS_EXPRESSION || (layer->class[i]->labels[l]->text.string && strchr(layer->class[i]->labels[l]->text.string,'[') != NULL && strchr(layer->class[i]->labels[l]->text.string,']') != NULL))
+        nt += msCountChars(layer->class[i]->labels[l]->text.string, '[');
     }
 
     if(layer->class[i]->text.type == MS_EXPRESSION || (layer->class[i]->text.string && strchr(layer->class[i]->text.string,'[') != NULL && strchr(layer->class[i]->text.string,']') != NULL))
@@ -528,7 +540,7 @@ int msLayerWhichItems(layerObj *layer, int get_all, char *metadata)
 
   /* always retrieve all items in some cases */
   if(layer->connectiontype == MS_INLINE || get_all == MS_TRUE ||
-     (layer->map->outputformat && layer->map->outputformat->renderer == MS_RENDER_WITH_KML)) {
+      (layer->map->outputformat && layer->map->outputformat->renderer == MS_RENDER_WITH_KML)) {
     msLayerGetItems(layer);
     if(nt > 0) /* need to realloc the array to accept the possible new items*/
       layer->items = (char **)msSmallRealloc(layer->items, sizeof(char *)*(layer->numitems + nt));
@@ -559,22 +571,33 @@ int msLayerWhichItems(layerObj *layer, int get_all, char *metadata)
         if(layer->class[i]->styles[j]->rangeitem) layer->class[i]->styles[j]->rangeitemindex = string2list(layer->items, &(layer->numitems), layer->class[i]->styles[j]->rangeitem);
         for(k=0; k<MS_STYLE_BINDING_LENGTH; k++)
           if(layer->class[i]->styles[j]->bindings[k].item) layer->class[i]->styles[j]->bindings[k].index = string2list(layer->items, &(layer->numitems), layer->class[i]->styles[j]->bindings[k].item);
-        if(layer->class[i]->styles[j]->_geomtransform.type == MS_GEOMTRANSFORM_EXPRESSION) 
+        if(layer->class[i]->styles[j]->_geomtransform.type == MS_GEOMTRANSFORM_EXPRESSION)
           msTokenizeExpression(&(layer->class[i]->styles[j]->_geomtransform), layer->items, &(layer->numitems));
       }
-      for(j=0; j<layer->class[i]->label.numstyles; j++) {
-        if(layer->class[i]->label.styles[j]->rangeitem) layer->class[i]->label.styles[j]->rangeitemindex = string2list(layer->items, &(layer->numitems), layer->class[i]->label.styles[j]->rangeitem);
-        for(k=0; k<MS_STYLE_BINDING_LENGTH; k++)
-          if(layer->class[i]->label.styles[j]->bindings[k].item) layer->class[i]->label.styles[j]->bindings[k].index = string2list(layer->items, &(layer->numitems), layer->class[i]->label.styles[j]->bindings[k].item);
-        if(layer->class[i]->label.styles[j]->_geomtransform.type == MS_GEOMTRANSFORM_EXPRESSION) 
-          msTokenizeExpression(&(layer->class[i]->label.styles[j]->_geomtransform), layer->items, &(layer->numitems));
+
+      /* class labels and label styles (items, bindings, geomtransform) */
+      for(l=0; l<layer->class[i]->numlabels; l++) {
+        for(j=0; j<layer->class[i]->labels[l]->numstyles; j++) {
+          if(layer->class[i]->labels[l]->styles[j]->rangeitem) layer->class[i]->labels[l]->styles[j]->rangeitemindex = string2list(layer->items, &(layer->numitems), layer->class[i]->labels[l]->styles[j]->rangeitem);
+          for(k=0; k<MS_STYLE_BINDING_LENGTH; k++)
+            if(layer->class[i]->labels[l]->styles[j]->bindings[k].item) layer->class[i]->labels[l]->styles[j]->bindings[k].index = string2list(layer->items, &(layer->numitems), layer->class[i]->labels[l]->styles[j]->bindings[k].item);
+          if(layer->class[i]->labels[l]->styles[j]->_geomtransform.type == MS_GEOMTRANSFORM_EXPRESSION)
+            msTokenizeExpression(&(layer->class[i]->labels[l]->styles[j]->_geomtransform), layer->items, &(layer->numitems));
+        }
+        for(k=0; k<MS_LABEL_BINDING_LENGTH; k++)
+          if(layer->class[i]->labels[l]->bindings[k].item) layer->class[i]->labels[l]->bindings[k].index = string2list(layer->items, &(layer->numitems), layer->class[i]->labels[l]->bindings[k].item);
+
+        /* label expression */
+        if(layer->class[i]->labels[l]->expression.type == MS_EXPRESSION)  msTokenizeExpression(&(layer->class[i]->labels[l]->expression), layer->items, &(layer->numitems));
+
+        /* label text */
+        if(layer->class[i]->labels[l]->text.type == MS_EXPRESSION || (layer->class[i]->labels[l]->text.string && strchr(layer->class[i]->labels[l]->text.string,'[') != NULL && strchr(layer->class[i]->labels[l]->text.string,']') != NULL))
+          msTokenizeExpression(&(layer->class[i]->labels[l]->text), layer->items, &(layer->numitems));
       }
 
-      /* class text and label bindings */
+      /* class text */
       if(layer->class[i]->text.type == MS_EXPRESSION || (layer->class[i]->text.string && strchr(layer->class[i]->text.string,'[') != NULL && strchr(layer->class[i]->text.string,']') != NULL))
         msTokenizeExpression(&(layer->class[i]->text), layer->items, &(layer->numitems));
-      for(k=0; k<MS_LABEL_BINDING_LENGTH; k++)
-        if(layer->class[i]->label.bindings[k].item) layer->class[i]->label.bindings[k].index = string2list(layer->items, &(layer->numitems), layer->class[i]->label.bindings[k].item);
     }
 
     /* layer filter */
@@ -651,17 +674,17 @@ int msLayerSetItems(layerObj *layer, char **items, int numitems)
 /*
 ** Fills a classObj with style info from the specified shape.  This is used
 ** with STYLEITEM AUTO when rendering shapes.
-** For optimal results, this should be called immediately after 
+** For optimal results, this should be called immediately after
 ** GetNextShape() or GetShape() so that the shape doesn't have to be read
 ** twice.
-** 
+**
 */
 int msLayerGetAutoStyle(mapObj *map, layerObj *layer, classObj *c, shapeObj* shape)
 {
   if ( ! layer->vtable) {
-      int rv =  msInitializeVirtualTable(layer);
-      if (rv != MS_SUCCESS)
-          return rv;
+    int rv =  msInitializeVirtualTable(layer);
+    if (rv != MS_SUCCESS)
+      return rv;
   }
   return layer->vtable->LayerGetAutoStyle(map, layer, c, shape);
 }
@@ -669,115 +692,122 @@ int msLayerGetAutoStyle(mapObj *map, layerObj *layer, classObj *c, shapeObj* sha
 /*
 ** Fills a classObj with style info from the specified attribute.  This is used
 ** with STYLEITEM "attribute" when rendering shapes.
-** 
+**
 */
 int msLayerGetFeatureStyle(mapObj *map, layerObj *layer, classObj *c, shapeObj* shape)
 {
-    char* stylestring;
-    if (layer->styleitem && layer->styleitemindex >=0)
-    {
-        stylestring = shape->values[layer->styleitemindex];
-        /* try to find out the current style format */
-        if (strncasecmp(stylestring,"style",5) == 0)
-        {
-            resetClassStyle(c);
-            if (msMaybeAllocateClassStyle(c, 0))
-                return(MS_FAILURE);
-
-            msUpdateStyleFromString(c->styles[0], stylestring, MS_FALSE);
-        }
-        else if (strncasecmp(stylestring,"class",5) == 0)
-        {
-            msUpdateClassFromString(c, stylestring, MS_FALSE);
-        }
-        else if (strncasecmp(stylestring,"pen",3) == 0 || strncasecmp(stylestring,"brush",5) == 0 ||
-            strncasecmp(stylestring,"symbol",6) == 0 || strncasecmp(stylestring,"label",5) == 0)
-        {
-            msOGRUpdateStyleFromString(map, layer, c, stylestring);
-        }
-
-        return MS_SUCCESS;
+  char* stylestring;
+  if (layer->styleitem && layer->styleitemindex >=0) {
+    stylestring = shape->values[layer->styleitemindex];
+    /* try to find out the current style format */
+    if (strncasecmp(stylestring,"style",5) == 0) {
+      resetClassStyle(c);
+      if (msMaybeAllocateClassStyle(c, 0))
+        return(MS_FAILURE);
+
+      msUpdateStyleFromString(c->styles[0], stylestring, MS_FALSE);
+    } else if (strncasecmp(stylestring,"class",5) == 0) {
+      msUpdateClassFromString(c, stylestring, MS_FALSE);
+    } else if (strncasecmp(stylestring,"pen",3) == 0 || strncasecmp(stylestring,"brush",5) == 0 ||
+               strncasecmp(stylestring,"symbol",6) == 0 || strncasecmp(stylestring,"label",5) == 0) {
+      msOGRUpdateStyleFromString(map, layer, c, stylestring);
+    } else {
+      resetClassStyle(c);
     }
-    return MS_FAILURE;
+
+    return MS_SUCCESS;
+  }
+  return MS_FAILURE;
 }
 
 
 /*
 Returns the number of inline feature of a layer
 */
-int msLayerGetNumFeatures(layerObj *layer) 
+int msLayerGetNumFeatures(layerObj *layer)
 {
-    if ( ! layer->vtable) {
-        int rv =  msInitializeVirtualTable(layer);
-        if (rv != MS_SUCCESS)
-            return rv;
-    }
-    return layer->vtable->LayerGetNumFeatures(layer);
+  if ( ! layer->vtable) {
+    int rv =  msInitializeVirtualTable(layer);
+    if (rv != MS_SUCCESS)
+      return rv;
+  }
+  return layer->vtable->LayerGetNumFeatures(layer);
 }
 
-void 
+void
 msLayerSetProcessingKey( layerObj *layer, const char *key, const char *value)
 
 {
-    int len = strlen(key);
-    int i;
-    char *directive;
+  int len = strlen(key);
+  int i;
+  char *directive = NULL;
 
+  if( value != NULL ) {
     directive = (char *) msSmallMalloc(strlen(key)+strlen(value)+2);
     sprintf( directive, "%s=%s", key, value );
+  }
 
-    for( i = 0; i < layer->numprocessing; i++ )
-    {
-        /* If the key is found, replace it */
-        if( strncasecmp( key, layer->processing[i], len ) == 0 
-            && layer->processing[i][len] == '=' )
-        {
-            free( layer->processing[i] );
-            layer->processing[i] = directive;
-            return;
-        }
+  for( i = 0; i < layer->numprocessing; i++ ) {
+    if( strncasecmp( key, layer->processing[i], len ) == 0
+        && layer->processing[i][len] == '=' ) {
+      free( layer->processing[i] );
+
+      /*
+      ** Either replace the existing entry with a new one or
+      ** clear the entry.
+      */
+      if( directive != NULL )
+        layer->processing[i] = directive;
+      else {
+        layer->processing[i] = layer->processing[layer->numprocessing-1];
+        layer->processing[layer->numprocessing-1] = NULL;
+        layer->numprocessing--;
+      }
+      return;
     }
+  }
 
-    /* otherwise add the directive at the end. */
+  /* otherwise add the directive at the end. */
 
+  if( directive != NULL ) {
     msLayerAddProcessing( layer, directive );
     free( directive );
+  }
 }
 
 void msLayerAddProcessing( layerObj *layer, const char *directive )
 
 {
-    layer->numprocessing++;
-    if( layer->numprocessing == 1 )
-        layer->processing = (char **) msSmallMalloc(2*sizeof(char *));
-    else
-        layer->processing = (char **) msSmallRealloc(layer->processing, sizeof(char*) * (layer->numprocessing+1) );
-    layer->processing[layer->numprocessing-1] = msStrdup(directive);
-    layer->processing[layer->numprocessing] = NULL;
+  layer->numprocessing++;
+  if( layer->numprocessing == 1 )
+    layer->processing = (char **) msSmallMalloc(2*sizeof(char *));
+  else
+    layer->processing = (char **) msSmallRealloc(layer->processing, sizeof(char*) * (layer->numprocessing+1) );
+  layer->processing[layer->numprocessing-1] = msStrdup(directive);
+  layer->processing[layer->numprocessing] = NULL;
 }
 
-char *msLayerGetProcessing( layerObj *layer, int proc_index) {
-    if (proc_index < 0 || proc_index >= layer->numprocessing) {
-        msSetError(MS_CHILDERR, "Invalid processing index.", "msLayerGetProcessing()");
-        return NULL;
-    }
-    else {
-        return layer->processing[proc_index];
-    }
+char *msLayerGetProcessing( layerObj *layer, int proc_index)
+{
+  if (proc_index < 0 || proc_index >= layer->numprocessing) {
+    msSetError(MS_CHILDERR, "Invalid processing index.", "msLayerGetProcessing()");
+    return NULL;
+  } else {
+    return layer->processing[proc_index];
+  }
 }
 
-char *msLayerGetProcessingKey( layerObj *layer, const char *key ) 
+char *msLayerGetProcessingKey( layerObj *layer, const char *key )
 {
-    int i, len = strlen(key);
+  int i, len = strlen(key);
 
-    for( i = 0; i < layer->numprocessing; i++ )
-    {
-        if( strncasecmp(layer->processing[i],key,len) == 0 
-            && layer->processing[i][len] == '=' )
-            return layer->processing[i] + len + 1;
-    }
-    
-    return NULL;
+  for( i = 0; i < layer->numprocessing; i++ ) {
+    if( strncasecmp(layer->processing[i],key,len) == 0
+        && layer->processing[i][len] == '=' )
+      return layer->processing[i] + len + 1;
+  }
+
+  return NULL;
 }
 
 
@@ -790,310 +820,291 @@ char *msLayerGetProcessingKey( layerObj *layer, const char *key )
 /************************************************************************/
 int msLayerGetMaxFeaturesToDraw(layerObj *layer, outputFormatObj *format)
 {
-    int nMaxFeatures = -1;
-    const char *pszTmp = NULL;
-    if (layer && format)
-    {
-        pszTmp = msLookupHashTable(&layer->metadata, "maxfeaturestodraw");
-        if (pszTmp)
-          nMaxFeatures = atoi(pszTmp);
-        else
-        {
-            pszTmp = msLookupHashTable(&layer->map->web.metadata, "maxfeaturestodraw");
-            if (pszTmp)
-              nMaxFeatures = atoi(pszTmp);
-        }
-        if (nMaxFeatures < 0)
-          nMaxFeatures = atoi(msGetOutputFormatOption( format, "maxfeaturestodraw", "-1"));
-     }
-    
-    return nMaxFeatures;
-
-}
-int msLayerClearProcessing( layerObj *layer ) {
-    if (layer->numprocessing > 0) {
-        msFreeCharArray( layer->processing, layer->numprocessing );
-        layer->processing = NULL;
-        layer->numprocessing = 0;
+  int nMaxFeatures = -1;
+  const char *pszTmp = NULL;
+  if (layer && format) {
+    pszTmp = msLookupHashTable(&layer->metadata, "maxfeaturestodraw");
+    if (pszTmp)
+      nMaxFeatures = atoi(pszTmp);
+    else {
+      pszTmp = msLookupHashTable(&layer->map->web.metadata, "maxfeaturestodraw");
+      if (pszTmp)
+        nMaxFeatures = atoi(pszTmp);
     }
-    return layer->numprocessing;
+    if (nMaxFeatures < 0)
+      nMaxFeatures = atoi(msGetOutputFormatOption( format, "maxfeaturestodraw", "-1"));
+  }
+
+  return nMaxFeatures;
+
+}
+int msLayerClearProcessing( layerObj *layer )
+{
+  if (layer->numprocessing > 0) {
+    msFreeCharArray( layer->processing, layer->numprocessing );
+    layer->processing = NULL;
+    layer->numprocessing = 0;
+  }
+  return layer->numprocessing;
 }
 
 
-int 
-makeTimeFilter(layerObj *lp, 
-               const char *timestring, 
+int
+makeTimeFilter(layerObj *lp,
+               const char *timestring,
                const char *timefield,
                const int addtimebacktics)
 {
-  
-    char **atimes, **tokens = NULL;
-    int numtimes,i, ntmp = 0;
-    char *pszBuffer = NULL;
-    int bOnlyExistingFilter = 0;
 
-    if (!lp || !timestring || !timefield)
-      return MS_FALSE;
+  char **atimes, **tokens = NULL;
+  int numtimes,i, ntmp = 0;
+  char *pszBuffer = NULL;
+  int bOnlyExistingFilter = 0;
+
+  if (!lp || !timestring || !timefield)
+    return MS_FALSE;
+
+  /* parse the time string. We support dicrete times (eg 2004-09-21),  */
+  /* multiple times (2004-09-21, 2004-09-22, ...) */
+  /* and range(s) (2004-09-21/2004-09-25, 2004-09-27/2004-09-29) */
+
+  if (strstr(timestring, ",") == NULL &&
+      strstr(timestring, "/") == NULL) { /* discrete time */
+    /*
+    if(lp->filteritem) free(lp->filteritem);
+    lp->filteritem = msStrdup(timefield);
+    if (&lp->filter)
+      freeExpression(&lp->filter);
+    */
+
+    if (&lp->filter) {
+      /* if the filter is set and it's a sting type, concatenate it with
+         the time. If not just free it */
+      if (lp->filter.type == MS_EXPRESSION) {
+        pszBuffer = msStringConcatenate(pszBuffer, "((");
+        pszBuffer = msStringConcatenate(pszBuffer, lp->filter.string);
+        pszBuffer = msStringConcatenate(pszBuffer, ") and ");
+      } else {
+        freeExpression(&lp->filter);
+      }
+    }
+
+    pszBuffer = msStringConcatenate(pszBuffer, "(");
+    if (addtimebacktics)
+      pszBuffer = msStringConcatenate(pszBuffer,  "`");
+
+    if (addtimebacktics)
+      pszBuffer = msStringConcatenate(pszBuffer, "[");
+    pszBuffer = msStringConcatenate(pszBuffer, (char *)timefield);
+    if (addtimebacktics)
+      pszBuffer = msStringConcatenate(pszBuffer, "]");
+    if (addtimebacktics)
+      pszBuffer = msStringConcatenate(pszBuffer,  "`");
+
+
+    pszBuffer = msStringConcatenate(pszBuffer, " = ");
+    if (addtimebacktics)
+      pszBuffer = msStringConcatenate(pszBuffer,  "`");
+    else
+      pszBuffer = msStringConcatenate(pszBuffer,  "'");
+
+    pszBuffer = msStringConcatenate(pszBuffer, (char *)timestring);
+    if (addtimebacktics)
+      pszBuffer = msStringConcatenate(pszBuffer,  "`");
+    else
+      pszBuffer = msStringConcatenate(pszBuffer,  "'");
+
+    pszBuffer = msStringConcatenate(pszBuffer, ")");
+
+    /* if there was a filter, It was concatenate with an And ans should be closed*/
+    if(&lp->filter && lp->filter.type == MS_EXPRESSION) {
+      pszBuffer = msStringConcatenate(pszBuffer, ")");
+    }
+
+    loadExpressionString(&lp->filter, pszBuffer);
+
+    if (pszBuffer)
+      msFree(pszBuffer);
 
-    /* parse the time string. We support dicrete times (eg 2004-09-21),  */
-    /* multiple times (2004-09-21, 2004-09-22, ...) */
-    /* and range(s) (2004-09-21/2004-09-25, 2004-09-27/2004-09-29) */
-
-    if (strstr(timestring, ",") == NULL && 
-        strstr(timestring, "/") == NULL) /* discrete time */
-    {   
-        /*
-        if(lp->filteritem) free(lp->filteritem);
-        lp->filteritem = msStrdup(timefield);
-        if (&lp->filter)
-          freeExpression(&lp->filter);
-        */
-
-        if (&lp->filter)
-        {
-            /* if the filter is set and it's a sting type, concatenate it with
-               the time. If not just free it */
-            if (lp->filter.type == MS_EXPRESSION)
-            {
-                pszBuffer = msStringConcatenate(pszBuffer, "((");
-                pszBuffer = msStringConcatenate(pszBuffer, lp->filter.string);
-                pszBuffer = msStringConcatenate(pszBuffer, ") and ");
-            }
-            else
-            {
-                freeExpression(&lp->filter);
-            }
+    return MS_TRUE;
+  }
+
+  atimes = msStringSplit(timestring, ',', &numtimes);
+  if (atimes == NULL || numtimes < 1)
+    return MS_FALSE;
+
+  if (numtimes >= 1) {
+    if (&lp->filter && lp->filter.type == MS_EXPRESSION) {
+      pszBuffer = msStringConcatenate(pszBuffer, "((");
+      pszBuffer = msStringConcatenate(pszBuffer, lp->filter.string);
+      pszBuffer = msStringConcatenate(pszBuffer, ") and ");
+      /*this flag is used to indicate that the buffer contains only the
+        existing filter. It is set to 0 when time filter parts are
+        added to the buffer */
+      bOnlyExistingFilter = 1;
+    } else
+      freeExpression(&lp->filter);
+
+    /* check to see if we have ranges by parsing the first entry */
+    tokens = msStringSplit(atimes[0],  '/', &ntmp);
+    if (ntmp == 2) { /* ranges */
+      msFreeCharArray(tokens, ntmp);
+      for (i=0; i<numtimes; i++) {
+        tokens = msStringSplit(atimes[i],  '/', &ntmp);
+        if (ntmp == 2) {
+          if (pszBuffer && strlen(pszBuffer) > 0 && bOnlyExistingFilter == 0)
+            pszBuffer = msStringConcatenate(pszBuffer, " OR ");
+          else
+            pszBuffer = msStringConcatenate(pszBuffer, "(");
+
+          bOnlyExistingFilter = 0;
+
+          pszBuffer = msStringConcatenate(pszBuffer, "(");
+          if (addtimebacktics)
+            pszBuffer = msStringConcatenate(pszBuffer,  "`");
+
+          if (addtimebacktics)
+            pszBuffer = msStringConcatenate(pszBuffer, "[");
+          pszBuffer = msStringConcatenate(pszBuffer, (char *)timefield);
+          if (addtimebacktics)
+            pszBuffer = msStringConcatenate(pszBuffer, "]");
+
+          if (addtimebacktics)
+            pszBuffer = msStringConcatenate(pszBuffer,  "`");
+
+          pszBuffer = msStringConcatenate(pszBuffer, " >= ");
+          if (addtimebacktics)
+            pszBuffer = msStringConcatenate(pszBuffer,  "`");
+          else
+            pszBuffer = msStringConcatenate(pszBuffer,  "'");
+
+          pszBuffer = msStringConcatenate(pszBuffer, tokens[0]);
+          if (addtimebacktics)
+            pszBuffer = msStringConcatenate(pszBuffer,  "`");
+          else
+            pszBuffer = msStringConcatenate(pszBuffer,  "'");
+          pszBuffer = msStringConcatenate(pszBuffer, " AND ");
+
+          if (addtimebacktics)
+            pszBuffer = msStringConcatenate(pszBuffer,  "`");
+
+          if (addtimebacktics)
+            pszBuffer = msStringConcatenate(pszBuffer, "[");
+          pszBuffer = msStringConcatenate(pszBuffer, (char *)timefield);
+          if (addtimebacktics)
+            pszBuffer = msStringConcatenate(pszBuffer, "]");
+          if (addtimebacktics)
+            pszBuffer = msStringConcatenate(pszBuffer,  "`");
+
+          pszBuffer = msStringConcatenate(pszBuffer, " <= ");
+
+          if (addtimebacktics)
+            pszBuffer = msStringConcatenate(pszBuffer,  "`");
+          else
+            pszBuffer = msStringConcatenate(pszBuffer,  "'");
+          pszBuffer = msStringConcatenate(pszBuffer, tokens[1]);
+          if (addtimebacktics)
+            pszBuffer = msStringConcatenate(pszBuffer,  "`");
+          else
+            pszBuffer = msStringConcatenate(pszBuffer,  "'");
+          pszBuffer = msStringConcatenate(pszBuffer, ")");
         }
-        
+
+        msFreeCharArray(tokens, ntmp);
+      }
+      if (pszBuffer && strlen(pszBuffer) > 0 && bOnlyExistingFilter == 0)
+        pszBuffer = msStringConcatenate(pszBuffer, ")");
+    } else if (ntmp == 1) { /* multiple times */
+      msFreeCharArray(tokens, ntmp);
+      pszBuffer = msStringConcatenate(pszBuffer, "(");
+      for (i=0; i<numtimes; i++) {
+        if (i > 0)
+          pszBuffer = msStringConcatenate(pszBuffer, " OR ");
+
         pszBuffer = msStringConcatenate(pszBuffer, "(");
         if (addtimebacktics)
-          pszBuffer = msStringConcatenate(pszBuffer,  "`");
+          pszBuffer = msStringConcatenate(pszBuffer, "`");
 
         if (addtimebacktics)
-           pszBuffer = msStringConcatenate(pszBuffer, "[");
+          pszBuffer = msStringConcatenate(pszBuffer, "[");
         pszBuffer = msStringConcatenate(pszBuffer, (char *)timefield);
         if (addtimebacktics)
           pszBuffer = msStringConcatenate(pszBuffer, "]");
+
         if (addtimebacktics)
-          pszBuffer = msStringConcatenate(pszBuffer,  "`");
+          pszBuffer = msStringConcatenate(pszBuffer, "`");
 
-         
         pszBuffer = msStringConcatenate(pszBuffer, " = ");
+
         if (addtimebacktics)
-          pszBuffer = msStringConcatenate(pszBuffer,  "`");
+          pszBuffer = msStringConcatenate(pszBuffer, "`");
         else
           pszBuffer = msStringConcatenate(pszBuffer,  "'");
-
-        pszBuffer = msStringConcatenate(pszBuffer, (char *)timestring);
+        pszBuffer = msStringConcatenate(pszBuffer, atimes[i]);
         if (addtimebacktics)
           pszBuffer = msStringConcatenate(pszBuffer,  "`");
         else
           pszBuffer = msStringConcatenate(pszBuffer,  "'");
-
         pszBuffer = msStringConcatenate(pszBuffer, ")");
-        
-        /* if there was a filter, It was concatenate with an And ans should be closed*/
-        if(&lp->filter && lp->filter.type == MS_EXPRESSION)
-        {
-            pszBuffer = msStringConcatenate(pszBuffer, ")");
-        }
-
-        loadExpressionString(&lp->filter, pszBuffer);
-
-        if (pszBuffer)
-          msFree(pszBuffer);
-
-        return MS_TRUE;
-    }
-    
-    atimes = msStringSplit(timestring, ',', &numtimes);
-    if (atimes == NULL || numtimes < 1)
+      }
+      pszBuffer = msStringConcatenate(pszBuffer, ")");
+    } else {
+      msFreeCharArray(atimes, numtimes);
       return MS_FALSE;
+    }
 
-    if (numtimes >= 1)
-    {
-        if (&lp->filter && lp->filter.type == MS_EXPRESSION)
-        {
-            pszBuffer = msStringConcatenate(pszBuffer, "((");
-            pszBuffer = msStringConcatenate(pszBuffer, lp->filter.string);
-            pszBuffer = msStringConcatenate(pszBuffer, ") and ");
-            /*this flag is used to indicate that the buffer contains only the 
-              existing filter. It is set to 0 when time filter parts are
-              added to the buffer */
-            bOnlyExistingFilter = 1;
-        }
-        else
-          freeExpression(&lp->filter);
-
-        /* check to see if we have ranges by parsing the first entry */
-        tokens = msStringSplit(atimes[0],  '/', &ntmp);
-        if (ntmp == 2) /* ranges */
-        {
-            msFreeCharArray(tokens, ntmp);
-            for (i=0; i<numtimes; i++)
-            {
-                 tokens = msStringSplit(atimes[i],  '/', &ntmp);
-                 if (ntmp == 2)
-                 {
-                     if (pszBuffer && strlen(pszBuffer) > 0 && bOnlyExistingFilter == 0)
-                       pszBuffer = msStringConcatenate(pszBuffer, " OR ");
-                     else
-                       pszBuffer = msStringConcatenate(pszBuffer, "(");
-
-                     bOnlyExistingFilter = 0;
-
-                     pszBuffer = msStringConcatenate(pszBuffer, "(");
-                     if (addtimebacktics)
-                       pszBuffer = msStringConcatenate(pszBuffer,  "`");
-
-                     if (addtimebacktics)
-                       pszBuffer = msStringConcatenate(pszBuffer, "[");
-                     pszBuffer = msStringConcatenate(pszBuffer, (char *)timefield);
-                     if (addtimebacktics)
-                       pszBuffer = msStringConcatenate(pszBuffer, "]");
-                     
-                     if (addtimebacktics)
-                       pszBuffer = msStringConcatenate(pszBuffer,  "`");
-
-                     pszBuffer = msStringConcatenate(pszBuffer, " >= ");
-                     if (addtimebacktics)
-                       pszBuffer = msStringConcatenate(pszBuffer,  "`");
-                     else
-                       pszBuffer = msStringConcatenate(pszBuffer,  "'");
-
-                     pszBuffer = msStringConcatenate(pszBuffer, tokens[0]);
-                     if (addtimebacktics)
-                       pszBuffer = msStringConcatenate(pszBuffer,  "`");
-                     else
-                       pszBuffer = msStringConcatenate(pszBuffer,  "'");
-                     pszBuffer = msStringConcatenate(pszBuffer, " AND ");
-
-                     if (addtimebacktics)
-                       pszBuffer = msStringConcatenate(pszBuffer,  "`");
-
-                     if (addtimebacktics)
-                       pszBuffer = msStringConcatenate(pszBuffer, "[");
-                     pszBuffer = msStringConcatenate(pszBuffer, (char *)timefield);
-                     if (addtimebacktics)
-                       pszBuffer = msStringConcatenate(pszBuffer, "]");
-                     if (addtimebacktics)
-                       pszBuffer = msStringConcatenate(pszBuffer,  "`");
-
-                     pszBuffer = msStringConcatenate(pszBuffer, " <= ");
-                     
-                     if (addtimebacktics)
-                       pszBuffer = msStringConcatenate(pszBuffer,  "`");
-                     else
-                       pszBuffer = msStringConcatenate(pszBuffer,  "'");
-                     pszBuffer = msStringConcatenate(pszBuffer, tokens[1]);
-                     if (addtimebacktics)
-                       pszBuffer = msStringConcatenate(pszBuffer,  "`");
-                     else
-                       pszBuffer = msStringConcatenate(pszBuffer,  "'");
-                     pszBuffer = msStringConcatenate(pszBuffer, ")");
-                 }
-                 
-                  msFreeCharArray(tokens, ntmp);
-            }
-            if (pszBuffer && strlen(pszBuffer) > 0 && bOnlyExistingFilter == 0)
-              pszBuffer = msStringConcatenate(pszBuffer, ")");
-        }
-        else if (ntmp == 1) /* multiple times */
-        {
-            msFreeCharArray(tokens, ntmp);
-            pszBuffer = msStringConcatenate(pszBuffer, "(");
-            for (i=0; i<numtimes; i++)
-            {
-                if (i > 0)
-                  pszBuffer = msStringConcatenate(pszBuffer, " OR ");
-
-                pszBuffer = msStringConcatenate(pszBuffer, "(");
-                if (addtimebacktics)
-                  pszBuffer = msStringConcatenate(pszBuffer, "`");
-                  
-                if (addtimebacktics)
-                  pszBuffer = msStringConcatenate(pszBuffer, "[");
-                pszBuffer = msStringConcatenate(pszBuffer, (char *)timefield);
-                if (addtimebacktics)
-                  pszBuffer = msStringConcatenate(pszBuffer, "]");
-
-                if (addtimebacktics)
-                  pszBuffer = msStringConcatenate(pszBuffer, "`");
-
-                pszBuffer = msStringConcatenate(pszBuffer, " = ");
-                  
-                if (addtimebacktics)
-                  pszBuffer = msStringConcatenate(pszBuffer, "`");
-                else
-                  pszBuffer = msStringConcatenate(pszBuffer,  "'");
-                pszBuffer = msStringConcatenate(pszBuffer, atimes[i]);
-                if (addtimebacktics)
-                  pszBuffer = msStringConcatenate(pszBuffer,  "`");
-                else
-                  pszBuffer = msStringConcatenate(pszBuffer,  "'");
-                pszBuffer = msStringConcatenate(pszBuffer, ")");
-            } 
-            pszBuffer = msStringConcatenate(pszBuffer, ")");
-        }
-        else
-        {
-            msFreeCharArray(atimes, numtimes);
-            return MS_FALSE;
-        }
+    msFreeCharArray(atimes, numtimes);
 
-        msFreeCharArray(atimes, numtimes);
+    /* load the string to the filter */
+    if (pszBuffer && strlen(pszBuffer) > 0) {
+      if(&lp->filter && lp->filter.type == MS_EXPRESSION)
+        pszBuffer = msStringConcatenate(pszBuffer, ")");
+      /*
+      if(lp->filteritem)
+        free(lp->filteritem);
+      lp->filteritem = msStrdup(timefield);
+      */
 
-        /* load the string to the filter */
-        if (pszBuffer && strlen(pszBuffer) > 0)
-        {
-            if(&lp->filter && lp->filter.type == MS_EXPRESSION)
-              pszBuffer = msStringConcatenate(pszBuffer, ")");
-            /*
-            if(lp->filteritem) 
-              free(lp->filteritem);
-            lp->filteritem = msStrdup(timefield);
-            */     
+      loadExpressionString(&lp->filter, pszBuffer);
 
-            loadExpressionString(&lp->filter, pszBuffer);
+      if (pszBuffer)
+        msFree(pszBuffer);
+    }
 
-            if (pszBuffer)
-              msFree(pszBuffer);
-        }
+    return MS_TRUE;
 
-        return MS_TRUE;
-                 
-    }
-    
-     return MS_FALSE;
+  }
+
+  return MS_FALSE;
 }
 
 /**
   set the filter parameter for a time filter
 **/
 
-int msLayerSetTimeFilter(layerObj *lp, const char *timestring, 
-                         const char *timefield) 
+int msLayerSetTimeFilter(layerObj *lp, const char *timestring,
+                         const char *timefield)
 {
   if ( ! lp->vtable) {
-      int rv =  msInitializeVirtualTable(lp);
-      if (rv != MS_SUCCESS)
-          return rv;
+    int rv =  msInitializeVirtualTable(lp);
+    if (rv != MS_SUCCESS)
+      return rv;
   }
   return lp->vtable->LayerSetTimeFilter(lp, timestring, timefield);
-}   
+}
 
-int 
-msLayerMakeBackticsTimeFilter(layerObj *lp, const char *timestring, 
-                              const char *timefield) 
+int
+msLayerMakeBackticsTimeFilter(layerObj *lp, const char *timestring,
+                              const char *timefield)
 {
-    return makeTimeFilter(lp, timestring, timefield, MS_TRUE);
+  return makeTimeFilter(lp, timestring, timefield, MS_TRUE);
 }
 
-int 
-msLayerMakePlainTimeFilter(layerObj *lp, const char *timestring, 
-                              const char *timefield) 
+int
+msLayerMakePlainTimeFilter(layerObj *lp, const char *timestring,
+                           const char *timefield)
 {
-    return makeTimeFilter(lp, timestring, timefield, MS_FALSE);
+  return makeTimeFilter(lp, timestring, timefield, MS_FALSE);
 }
 
 
@@ -1145,37 +1156,63 @@ int LayerDefaultGetItems(layerObj *layer)
   return MS_SUCCESS; /* returning no items is legit */
 }
 
-int 
-msLayerApplyCondSQLFilterToLayer(FilterEncodingNode *psNode, mapObj *map, 
+int
+msLayerApplyCondSQLFilterToLayer(FilterEncodingNode *psNode, mapObj *map,
                                  int iLayerIndex)
 {
 #if USE_OGR
   return FLTLayerApplyCondSQLFilterToLayer(psNode, map, iLayerIndex);
 
 #else
-    return MS_FAILURE;
+  return MS_FAILURE;
 #endif
 }
 
 int msLayerSupportsPaging(layerObj *layer)
 {
-    if (layer && layer->connectiontype == MS_ORACLESPATIAL)
-      return MS_TRUE;
+  if (layer &&
+      ((layer->connectiontype == MS_ORACLESPATIAL) ||
+       (layer->connectiontype == MS_POSTGIS)) )
+    return MS_TRUE;
 
-    return MS_FALSE;
+  return MS_FALSE;
 }
 
-int 
-msLayerApplyPlainFilterToLayer(FilterEncodingNode *psNode, mapObj *map, 
+int
+msLayerApplyPlainFilterToLayer(FilterEncodingNode *psNode, mapObj *map,
                                int iLayerIndex)
 {
 #if USE_OGR
-  return FLTLayerApplyPlainFilterToLayer(psNode, map, iLayerIndex); 
+  return FLTLayerApplyPlainFilterToLayer(psNode, map, iLayerIndex);
 #else
-    return MS_FAILURE;
+  return MS_FAILURE;
 #endif
 }
 
+int msLayerGetPaging(layerObj *layer)
+{
+  if ( ! layer->vtable) {
+    int rv =  msInitializeVirtualTable(layer);
+    if (rv != MS_SUCCESS) {
+      msSetError(MS_MISCERR, "Unable to initialize virtual table", "msLayerGetPaging()");
+      return MS_FAILURE;
+    }
+  }
+  return layer->vtable->LayerGetPaging(layer);
+}
+
+void msLayerEnablePaging(layerObj *layer, int value)
+{
+  if ( ! layer->vtable) {
+    int rv =  msInitializeVirtualTable(layer);
+    if (rv != MS_SUCCESS) {
+      msSetError(MS_MISCERR, "Unable to initialize virtual table", "msLayerEnablePaging()");
+      return;
+    }
+  }
+  return layer->vtable->LayerEnablePaging(layer, value);
+}
+
 int LayerDefaultGetExtent(layerObj *layer, rectObj *extent)
 {
   return MS_FAILURE;
@@ -1184,7 +1221,7 @@ int LayerDefaultGetExtent(layerObj *layer, rectObj *extent)
 int LayerDefaultGetAutoStyle(mapObj *map, layerObj *layer, classObj *c, shapeObj *shape)
 {
   msSetError(MS_MISCERR, "'STYLEITEM AUTO' not supported for this data source.", "msLayerGetAutoStyle()");
-  return MS_FAILURE; 
+  return MS_FAILURE;
 }
 
 int LayerDefaultCloseConnection(layerObj *layer)
@@ -1220,6 +1257,16 @@ int LayerDefaultSupportsCommonFilters(layerObj *layer)
   return MS_FALSE;
 }
 
+int msLayerDefaultGetPaging(layerObj *layer)
+{
+  return MS_FALSE;
+}
+
+void msLayerDefaultEnablePaging(layerObj *layer, int value)
+{
+  return;
+}
+
 /************************************************************************/
 /*                          LayerDefaultEscapeSQLParam                  */
 /*                                                                      */
@@ -1229,33 +1276,27 @@ int LayerDefaultSupportsCommonFilters(layerObj *layer)
 /************************************************************************/
 char *LayerDefaultEscapeSQLParam(layerObj *layer, const char* pszString)
 {
-     char *pszEscapedStr=NULL;
-     if (pszString)
-     {
-         int nSrcLen;
-         char c;
-         int i=0, j=0;
-         nSrcLen = (int)strlen(pszString);
-         pszEscapedStr = (char*) msSmallMalloc( 2 * nSrcLen + 1);
-         for(i = 0, j = 0; i < nSrcLen; i++)
-         {
-             c = pszString[i];
-             if (c == '\'')
-             {
-                 pszEscapedStr[j++] = '\'';
-                 pszEscapedStr[j++] = '\'';
-             }
-             else if (c == '\\')
-             {
-                 pszEscapedStr[j++] = '\\';
-                 pszEscapedStr[j++] = '\\';
-             }
-             else
-               pszEscapedStr[j++] = c;
-         }
-         pszEscapedStr[j] = 0;
-     }  
-     return pszEscapedStr;
+  char *pszEscapedStr=NULL;
+  if (pszString) {
+    int nSrcLen;
+    char c;
+    int i=0, j=0;
+    nSrcLen = (int)strlen(pszString);
+    pszEscapedStr = (char*) msSmallMalloc( 2 * nSrcLen + 1);
+    for(i = 0, j = 0; i < nSrcLen; i++) {
+      c = pszString[i];
+      if (c == '\'') {
+        pszEscapedStr[j++] = '\'';
+        pszEscapedStr[j++] = '\'';
+      } else if (c == '\\') {
+        pszEscapedStr[j++] = '\\';
+        pszEscapedStr[j++] = '\\';
+      } else
+        pszEscapedStr[j++] = c;
+    }
+    pszEscapedStr[j] = 0;
+  }
+  return pszEscapedStr;
 }
 
 /************************************************************************/
@@ -1265,37 +1306,31 @@ char *LayerDefaultEscapeSQLParam(layerObj *layer, const char* pszString)
 /************************************************************************/
 char *LayerDefaultEscapePropertyName(layerObj *layer, const char* pszString)
 {
-     char* pszEscapedStr=NULL;
-     int i, j = 0;   
-
-     if (layer && pszString && strlen(pszString) > 0)
-     {
-         int nLength = strlen(pszString);
-
-         pszEscapedStr = (char*) msSmallMalloc( 1 + 2 * nLength + 1 + 1);
-         pszEscapedStr[j++] = '"';
-
-         for (i=0; i<nLength; i++)
-         {
-             char c = pszString[i];
-             if (c == '"')
-             {
-                 pszEscapedStr[j++] = '"';
-                 pszEscapedStr[j++] ='"';
-             }
-             else if (c == '\\')
-             {
-                 pszEscapedStr[j++] = '\\';
-                 pszEscapedStr[j++] = '\\';
-             }
-             else
-               pszEscapedStr[j++] = c;
-         }
-         pszEscapedStr[j++] = '"';
-         pszEscapedStr[j++] = 0;
-        
-     }
-     return pszEscapedStr;
+  char* pszEscapedStr=NULL;
+  int i, j = 0;
+
+  if (layer && pszString && strlen(pszString) > 0) {
+    int nLength = strlen(pszString);
+
+    pszEscapedStr = (char*) msSmallMalloc( 1 + 2 * nLength + 1 + 1);
+    pszEscapedStr[j++] = '"';
+
+    for (i=0; i<nLength; i++) {
+      char c = pszString[i];
+      if (c == '"') {
+        pszEscapedStr[j++] = '"';
+        pszEscapedStr[j++] ='"';
+      } else if (c == '\\') {
+        pszEscapedStr[j++] = '\\';
+        pszEscapedStr[j++] = '\\';
+      } else
+        pszEscapedStr[j++] = c;
+    }
+    pszEscapedStr[j++] = '"';
+    pszEscapedStr[j++] = 0;
+
+  }
+  return pszEscapedStr;
 }
 
 
@@ -1311,22 +1346,22 @@ int msConnectLayer(layerObj *layer,
                    const int connectiontype,
                    const char *library_str)
 {
-    layer->connectiontype = connectiontype;
-    /* For internal types, library_str is ignored */
-    if (connectiontype == MS_PLUGIN) {
-        int rv;
-        msFree(layer->plugin_library);
-        msFree(layer->plugin_library_original);
-
-        layer->plugin_library_original = msStrdup(library_str);
-        rv = msBuildPluginLibraryPath(&layer->plugin_library, 
-                                      layer->plugin_library_original, 
-                                      layer->map);
-        if (rv != MS_SUCCESS) {
-            return rv;
-        }
+  layer->connectiontype = connectiontype;
+  /* For internal types, library_str is ignored */
+  if (connectiontype == MS_PLUGIN) {
+    int rv;
+    msFree(layer->plugin_library);
+    msFree(layer->plugin_library_original);
+
+    layer->plugin_library_original = msStrdup(library_str);
+    rv = msBuildPluginLibraryPath(&layer->plugin_library,
+                                  layer->plugin_library_original,
+                                  layer->map);
+    if (rv != MS_SUCCESS) {
+      return rv;
     }
-    return msInitializeVirtualTable(layer) ;   
+  }
+  return msInitializeVirtualTable(layer) ;
 }
 
 static int populateVirtualTable(layerVTableObj *vtable)
@@ -1341,7 +1376,7 @@ static int populateVirtualTable(layerVTableObj *vtable)
   vtable->LayerWhichShapes = LayerDefaultWhichShapes;
 
   vtable->LayerNextShape = LayerDefaultNextShape;
-  // vtable->LayerResultsGetShape = LayerDefaultResultsGetShape;
+  /* vtable->LayerResultsGetShape = LayerDefaultResultsGetShape; */
   vtable->LayerGetShape = LayerDefaultGetShape;
   vtable->LayerClose = LayerDefaultClose;
   vtable->LayerGetItems = LayerDefaultGetItems;
@@ -1354,15 +1389,18 @@ static int populateVirtualTable(layerVTableObj *vtable)
   vtable->LayerApplyFilterToLayer = msLayerApplyPlainFilterToLayer;
 
   vtable->LayerCreateItems = LayerDefaultCreateItems;
-    
+
   vtable->LayerGetNumFeatures = LayerDefaultGetNumFeatures;
-  
+
   vtable->LayerGetAutoProjection = LayerDefaultAutoProjection;
 
   vtable->LayerEscapeSQLParam = LayerDefaultEscapeSQLParam;
 
   vtable->LayerEscapePropertyName = LayerDefaultEscapePropertyName;
 
+  vtable->LayerEnablePaging = msLayerDefaultEnablePaging;
+  vtable->LayerGetPaging = msLayerDefaultGetPaging;
+
   return MS_SUCCESS;
 }
 
@@ -1388,8 +1426,8 @@ int msInitializeVirtualTable(layerObj *layer)
     destroyVirtualTable(&layer->vtable);
   }
   createVirtualTable(&layer->vtable);
-   
-  if(layer->features && layer->connectiontype != MS_GRATICULE ) 
+
+  if(layer->features && layer->connectiontype != MS_GRATICULE )
     layer->connectiontype = MS_INLINE;
 
   if(layer->tileindex && layer->connectiontype == MS_SHAPEFILE)
@@ -1439,99 +1477,104 @@ int msInitializeVirtualTable(layerObj *layer)
     case(MS_UNION):
       return(msUnionLayerInitializeVirtualTable(layer));
       break;
+    case(MS_UVRASTER):
+      return(msUVRASTERLayerInitializeVirtualTable(layer));
+      break;
     default:
       msSetError(MS_MISCERR, "Unknown connectiontype, it was %d", "msInitializeVirtualTable()", layer->connectiontype);
       return MS_FAILURE;
       break;
-    }
+  }
 
-    /* not reached */
-    return MS_FAILURE;
+  /* not reached */
+  return MS_FAILURE;
 }
 
-/* 
- * INLINE: Virtual table functions 
+/*
+ * INLINE: Virtual table functions
  */
 
 int msINLINELayerIsOpen(layerObj *layer)
 {
-    if (layer->currentfeature)
-        return(MS_TRUE);
-    else
-        return(MS_FALSE);
+  if (layer->currentfeature)
+    return(MS_TRUE);
+  else
+    return(MS_FALSE);
 }
 
 
 int msINLINELayerOpen(layerObj *layer)
 {
-    layer->currentfeature = layer->features; /* point to the begining of the feature list */
-    return(MS_SUCCESS);
+  layer->currentfeature = layer->features; /* point to the begining of the feature list */
+  return(MS_SUCCESS);
 }
 
 /* Author: Cristoph Spoerri and Sean Gillies */
-int msINLINELayerGetShape(layerObj *layer, shapeObj *shape, resultObj *record) 
+int msINLINELayerGetShape(layerObj *layer, shapeObj *shape, resultObj *record)
 {
-    int i=0;
-    featureListNodeObjPtr current;
+  int i=0;
+  featureListNodeObjPtr current;
 
-    int shapeindex = record->shapeindex; /* only index necessary */
+  int shapeindex = record->shapeindex; /* only index necessary */
 
-    current = layer->features;
-    while (current!=NULL && i!=shapeindex) {
-        i++;
-        current = current->next;
-    }
-    if (current == NULL) {
-        msSetError(MS_SHPERR, "No inline feature with this index.", "msINLINELayerGetShape()");
-        return MS_FAILURE;
-    } 
-    
-    if (msCopyShape(&(current->shape), shape) != MS_SUCCESS) {
-        msSetError(MS_SHPERR, "Cannot retrieve inline shape. There some problem with the shape", "msINLINELayerGetShape()");
-        return MS_FAILURE;
-    }
-    /* check for the expected size of the values array */
-    if (layer->numitems > shape->numvalues) {
-        shape->values = (char **)msSmallRealloc(shape->values, sizeof(char *)*(layer->numitems));
-        for (i = shape->numvalues; i < layer->numitems; i++)
-            shape->values[i] = msStrdup("");
-    }
-    return MS_SUCCESS;
+  current = layer->features;
+  while (current!=NULL && i!=shapeindex) {
+    i++;
+    current = current->next;
+  }
+  if (current == NULL) {
+    msSetError(MS_SHPERR, "No inline feature with this index.", "msINLINELayerGetShape()");
+    return MS_FAILURE;
+  }
+
+  if (msCopyShape(&(current->shape), shape) != MS_SUCCESS) {
+    msSetError(MS_SHPERR, "Cannot retrieve inline shape. There some problem with the shape", "msINLINELayerGetShape()");
+    return MS_FAILURE;
+  }
+  /* check for the expected size of the values array */
+  if (layer->numitems > shape->numvalues) {
+    shape->values = (char **)msSmallRealloc(shape->values, sizeof(char *)*(layer->numitems));
+    for (i = shape->numvalues; i < layer->numitems; i++)
+      shape->values[i] = msStrdup("");
+  }
+  msComputeBounds(shape);
+  return MS_SUCCESS;
 }
 
-int msINLINELayerNextShape(layerObj *layer, shapeObj *shape) 
+int msINLINELayerNextShape(layerObj *layer, shapeObj *shape)
 {
-    if( ! (layer->currentfeature)) {
-        /* out of features */
-        return(MS_DONE); 
-    }
+  if( ! (layer->currentfeature)) {
+    /* out of features */
+    return(MS_DONE);
+  }
 
-    msCopyShape(&(layer->currentfeature->shape), shape);
+  msCopyShape(&(layer->currentfeature->shape), shape);
 
-    layer->currentfeature = layer->currentfeature->next;
+  layer->currentfeature = layer->currentfeature->next;
 
-    /* check for the expected size of the values array */
-    if (layer->numitems > shape->numvalues) {
-        int i;
-        shape->values = (char **)msSmallRealloc(shape->values, sizeof(char *)*(layer->numitems));
-        for (i = shape->numvalues; i < layer->numitems; i++)
-            shape->values[i] = msStrdup("");
-    }
+  /* check for the expected size of the values array */
+  if (layer->numitems > shape->numvalues) {
+    int i;
+    shape->values = (char **)msSmallRealloc(shape->values, sizeof(char *)*(layer->numitems));
+    for (i = shape->numvalues; i < layer->numitems; i++)
+      shape->values[i] = msStrdup("");
+  }
+  msComputeBounds(shape);
 
-    return(MS_SUCCESS);
+  return(MS_SUCCESS);
 }
 
 int msINLINELayerGetNumFeatures(layerObj *layer)
 {
-    int i = 0;
-    featureListNodeObjPtr current;
+  int i = 0;
+  featureListNodeObjPtr current;
 
-    current = layer->features;
-    while (current != NULL) {
-        i++;
-        current = current->next;
-    }
-    return i;
+  current = layer->features;
+  while (current != NULL) {
+    i++;
+    current = current->next;
+  }
+  return i;
 }
 
 
@@ -1539,61 +1582,65 @@ int msINLINELayerGetNumFeatures(layerObj *layer)
 /*
 Returns an escaped string
 */
-char  *msLayerEscapeSQLParam(layerObj *layer, const char*pszString) 
+char  *msLayerEscapeSQLParam(layerObj *layer, const char*pszString)
 {
-    if ( ! layer->vtable) {
-        int rv =  msInitializeVirtualTable(layer);
-        if (rv != MS_SUCCESS)
-            return "";
-    }
-    return layer->vtable->LayerEscapeSQLParam(layer, pszString);
+  if ( ! layer->vtable) {
+    int rv =  msInitializeVirtualTable(layer);
+    if (rv != MS_SUCCESS)
+      return "";
+  }
+  return layer->vtable->LayerEscapeSQLParam(layer, pszString);
 }
 
-char  *msLayerEscapePropertyName(layerObj *layer, const char*pszString) 
+char  *msLayerEscapePropertyName(layerObj *layer, const char*pszString)
 {
-    if ( ! layer->vtable) {
-        int rv =  msInitializeVirtualTable(layer);
-        if (rv != MS_SUCCESS)
-            return "";
-    }
-    return layer->vtable->LayerEscapePropertyName(layer, pszString);
+  if ( ! layer->vtable) {
+    int rv =  msInitializeVirtualTable(layer);
+    if (rv != MS_SUCCESS)
+      return "";
+  }
+  return layer->vtable->LayerEscapePropertyName(layer, pszString);
 }
 
 
 int
 msINLINELayerInitializeVirtualTable(layerObj *layer)
 {
-    assert(layer != NULL);
-    assert(layer->vtable != NULL);
+  assert(layer != NULL);
+  assert(layer->vtable != NULL);
+
+  /* layer->vtable->LayerInitItemInfo, use default */
+  /* layer->vtable->LayerFreeItemInfo, use default */
+  layer->vtable->LayerOpen = msINLINELayerOpen;
+  layer->vtable->LayerIsOpen = msINLINELayerIsOpen;
+  /* layer->vtable->LayerWhichShapes, use default */
+  layer->vtable->LayerNextShape = msINLINELayerNextShape;
+  layer->vtable->LayerGetShape = msINLINELayerGetShape;
+  /* layer->vtable->LayerClose, use default */
+  /* layer->vtable->LayerGetItems, use default */
+
+  /*
+   * Original code contained following
+   * TODO: need to compute extents
+   */
+  /* layer->vtable->LayerGetExtent, use default */
 
-    /* layer->vtable->LayerInitItemInfo, use default */
-    /* layer->vtable->LayerFreeItemInfo, use default */
-    layer->vtable->LayerOpen = msINLINELayerOpen;
-    layer->vtable->LayerIsOpen = msINLINELayerIsOpen;
-    /* layer->vtable->LayerWhichShapes, use default */
-    layer->vtable->LayerNextShape = msINLINELayerNextShape;
-    layer->vtable->LayerGetShape = msINLINELayerGetShape;
-    /* layer->vtable->LayerClose, use default */
-    /* layer->vtable->LayerGetItems, use default */
+  /* layer->vtable->LayerGetAutoStyle, use default */
+  /* layer->vtable->LayerCloseConnection, use default */
+  layer->vtable->LayerSetTimeFilter = msLayerMakeBackticsTimeFilter;
 
-    /* 
-     * Original code contained following 
-     * TODO: need to compute extents
-     */
-    /* layer->vtable->LayerGetExtent, use default */
+  /* layer->vtable->LayerApplyFilterToLayer, use default */
 
-    /* layer->vtable->LayerGetAutoStyle, use default */
-    /* layer->vtable->LayerCloseConnection, use default */
-    layer->vtable->LayerSetTimeFilter = msLayerMakeBackticsTimeFilter;
+  /* layer->vtable->LayerCreateItems, use default */
+  layer->vtable->LayerGetNumFeatures = msINLINELayerGetNumFeatures;
 
-    /* layer->vtable->LayerApplyFilterToLayer, use default */
+  /*layer->vtable->LayerEscapeSQLParam, use default*/
+  /*layer->vtable->LayerEscapePropertyName, use default*/
 
-    /* layer->vtable->LayerCreateItems, use default */
-    layer->vtable->LayerGetNumFeatures = msINLINELayerGetNumFeatures;
+  /* layer->vtable->LayerEnablePaging, use default */
+  /* layer->vtable->LayerGetPaging, use default */
 
-    /*layer->vtable->LayerEscapeSQLParam, use default*/
-    /*layer->vtable->LayerEscapePropertyName, use default*/
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 
diff --git a/maplegend.c b/maplegend.c
index 85e7b9f..c0efdaa 100644
--- a/maplegend.c
+++ b/maplegend.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -29,21 +29,21 @@
 
 #include "mapserver.h"
 
-MS_CVSID("$Id$")
+
 
 #define PSF .8
 #define VMARGIN 5 /* margin at top and bottom of legend graphic */
 #define HMARGIN 5 /* margin at left and right of legend graphic */
 
-/* 
+/*
  * generic function for drawing a legend icon. (added for bug #2348)
  * renderer specific drawing functions shouldn't be called directly, but through
  * this function
  */
-int msDrawLegendIcon(mapObj *map, layerObj *lp, classObj *theclass, 
-        int width, int height, imageObj *image, int dstX, int dstY)
+int msDrawLegendIcon(mapObj *map, layerObj *lp, classObj *theclass,
+                     int width, int height, imageObj *image, int dstX, int dstY)
 {
-  int i, type;
+  int i, type, hasmarkersymbol;
   double offset;
   shapeObj box, zigzag;
   pointObj marker;
@@ -56,38 +56,36 @@ int msDrawLegendIcon(mapObj *map, layerObj *lp, classObj *theclass,
   const char *alternativeFormatString = NULL;
 
   if(!MS_RENDERER_PLUGIN(image->format)) {
-      msSetError(MS_MISCERR,"unsupported image format","msDrawLegendIcon()");
-      return MS_FAILURE;
+    msSetError(MS_MISCERR,"unsupported image format","msDrawLegendIcon()");
+    return MS_FAILURE;
   }
- 
+
   alternativeFormatString = msLayerGetProcessingKey(lp, "RENDERER");
-  if (MS_RENDERER_PLUGIN(image_draw->format) && alternativeFormatString!=NULL && 
-      (altFormat=  msSelectOutputFormat(map, alternativeFormatString)))
-  {
-      msInitializeRendererVTable(altFormat);
-
-      image_draw = msImageCreate(image->width, image->height,
-                                 altFormat, image->imagepath, image->imageurl, map->resolution, map->defresolution, &map->imagecolor);
-      renderer = MS_IMAGE_RENDERER(image_draw);
-  }
-  else {
-      renderer = MS_IMAGE_RENDERER(image_draw);
-      if (lp->opacity > 0 && lp->opacity < 100) {
-         if (!renderer->supports_transparent_layers) {
-              image_draw = msImageCreate(image->width, image->height,
-                  image->format, image->imagepath, image->imageurl, map->resolution, map->defresolution, NULL);
-              if (!image_draw) {
-                  msSetError(MS_MISCERR, "Unable to initialize temporary transparent image.",
-                             "msDrawLegendIcon()");
-                  return (MS_FAILURE);
-              }
-              /* set opacity to full, as the renderer should be rendering a fully opaque image */
-              lp->opacity=100;
-          } 
+  if (MS_RENDERER_PLUGIN(image_draw->format) && alternativeFormatString!=NULL &&
+      (altFormat=  msSelectOutputFormat(map, alternativeFormatString))) {
+    msInitializeRendererVTable(altFormat);
+
+    image_draw = msImageCreate(image->width, image->height,
+                               altFormat, image->imagepath, image->imageurl, map->resolution, map->defresolution, &map->imagecolor);
+    renderer = MS_IMAGE_RENDERER(image_draw);
+  } else {
+    renderer = MS_IMAGE_RENDERER(image_draw);
+    if (lp->opacity > 0 && lp->opacity < 100) {
+      if (!renderer->supports_transparent_layers) {
+        image_draw = msImageCreate(image->width, image->height,
+                                   image->format, image->imagepath, image->imageurl, map->resolution, map->defresolution, NULL);
+        if (!image_draw) {
+          msSetError(MS_MISCERR, "Unable to initialize temporary transparent image.",
+                     "msDrawLegendIcon()");
+          return (MS_FAILURE);
+        }
+        /* set opacity to full, as the renderer should be rendering a fully opaque image */
+        lp->opacity=100;
       }
+    }
   }
-  
-  
+
+
   if(renderer->supports_clipping && MS_VALID_COLOR(map->legend.outlinecolor)) {
     /* keep GD specific code here for now as it supports clipping */
     rectObj clip;
@@ -97,7 +95,7 @@ int msDrawLegendIcon(mapObj *map, layerObj *lp, classObj *theclass,
     clip.miny = dstY;
     renderer->setClip(image_draw,clip);
   }
-  
+
   /* initialize the box used for polygons and for outlines */
   box.line = (lineObj *)msSmallMalloc(sizeof(lineObj));
   box.numlines = 1;
@@ -115,118 +113,133 @@ int msDrawLegendIcon(mapObj *map, layerObj *lp, classObj *theclass,
   box.line[0].point[4].x = box.line[0].point[0].x;
   box.line[0].point[4].y = box.line[0].point[0].y;
   box.line[0].numpoints = 5;
-    
+
   /* if the class has a keyimage, treat it as a point layer
    * (the keyimage will be treated there) */
   if(theclass->keyimage != NULL) {
     type = MS_LAYER_POINT;
-  } else {        
+  } else {
     /* some polygon layers may be better drawn using zigzag if there is no fill */
     type = lp->type;
     if(type == MS_LAYER_POLYGON) {
       type = MS_LAYER_LINE;
       for(i=0; i<theclass->numstyles; i++) {
-       if(MS_VALID_COLOR(theclass->styles[i]->color)) { /* there is a fill */
-      type = MS_LAYER_POLYGON;
-      break;
+        if(MS_VALID_COLOR(theclass->styles[i]->color)) { /* there is a fill */
+          type = MS_LAYER_POLYGON;
+          break;
         }
       }
     }
   }
 
-  /* 
-  ** now draw the appropriate color/symbol/size combination 
-  */     
+  /*
+  ** now draw the appropriate color/symbol/size combination
+  */
   switch(type) {
-  case MS_LAYER_ANNOTATION:
-    marker.x = dstX + MS_NINT(width / 2.0);
-    marker.y = dstY + MS_NINT(height / 2.0);
-    if (theclass->numstyles > 0) {
-      for(i=0; i<theclass->numstyles; i++)
-        msDrawMarkerSymbol(&map->symbolset, image_draw, &marker, theclass->styles[i], lp->scalefactor);          
-    } else if (theclass->label.size!=-1) {
-      labelObj label = theclass->label;
-      double lsize = label.size;
-      double langle = label.angle;
-      int lpos = label.position;
-      label.angle = 0;
-      label.position = MS_CC;
-      if (label.type == MS_TRUETYPE) label.size = height;
-      msDrawLabel(map, image_draw, marker, (char*)"Az", &label,1.0);
-      label.size = lsize;
-      label.position = lpos;
-      label.angle = langle;
-    }
-    break;
-  case MS_LAYER_POINT:
-    marker.x = dstX + MS_NINT(width / 2.0);
-    marker.y = dstY + MS_NINT(height / 2.0);
-    if(theclass->keyimage != NULL) {
-      int symbolNum;
-      styleObj imgStyle;
-      symbolObj *symbol=NULL;
-      symbolNum = msAddImageSymbol(&(map->symbolset), msBuildPath(szPath, map->mappath, theclass->keyimage));
-      if(symbolNum == -1) { 
+    case MS_LAYER_ANNOTATION:
+      marker.x = dstX + MS_NINT(width / 2.0);
+      marker.y = dstY + MS_NINT(height / 2.0);
+      hasmarkersymbol = 0;
+      for(i=0; i<theclass->numstyles; i++) {
+          if (theclass->styles[i]->symbol < map->symbolset.numsymbols && theclass->styles[i]->symbol > 0) {
+             hasmarkersymbol = 1;
+             break;
+          }
+      }
+      if (hasmarkersymbol) {
+        for(i=0; i<theclass->numstyles; i++)
+          msDrawMarkerSymbol(&map->symbolset, image_draw, &marker, theclass->styles[i], lp->scalefactor);
+      } else if (theclass->labels && theclass->numlabels > 0) {
+        labelObj *label = theclass->labels[0]; /* use the first label definition */
+        double lsize = label->size;
+        double langle = label->angle;
+        int lpos = label->position;
+        int loffsetx = label->offsetx;
+        int loffsety = label->offsety;
+
+        label->offsetx = 0;
+        label->offsety = 0;
+        label->angle = 0;
+        label->position = MS_CC;
+        if (label->type == MS_TRUETYPE) label->size = height;
+        msDrawLabel(map, image_draw, marker, (char*)"Az", label,1.0);
+
+        label->size = lsize;
+        label->position = lpos;
+        label->angle = langle;
+        label->offsetx = loffsetx;
+        label->offsety = loffsety;
+      }
+      break;
+    case MS_LAYER_POINT:
+      marker.x = dstX + MS_NINT(width / 2.0);
+      marker.y = dstY + MS_NINT(height / 2.0);
+      if(theclass->keyimage != NULL) {
+        int symbolNum;
+        styleObj imgStyle;
+        symbolObj *symbol=NULL;
+        symbolNum = msAddImageSymbol(&(map->symbolset), msBuildPath(szPath, map->mappath, theclass->keyimage));
+        if(symbolNum == -1) {
           msSetError(MS_GDERR, "Failed to open legend key image", "msCreateLegendIcon()");
           return(MS_FAILURE);
+        }
+
+        symbol = map->symbolset.symbol[symbolNum];
+
+        initStyle(&imgStyle);
+        /*set size so that symbol will be scaled properly #3296*/
+        if (width/symbol->sizex < height/symbol->sizey)
+          imgStyle.size = symbol->sizey*(width/symbol->sizex);
+        else
+          imgStyle.size = symbol->sizey*(height/symbol->sizey);
+
+        if (imgStyle.size > imgStyle.maxsize)
+          imgStyle.maxsize = imgStyle.size;
+
+        imgStyle.symbol = symbolNum;
+        msDrawMarkerSymbol(&map->symbolset,image_draw,&marker,&imgStyle,lp->scalefactor);
+        /* TO DO: we may want to handle this differently depending on the relative size of the keyimage */
+      } else {
+        for(i=0; i<theclass->numstyles; i++)
+          msDrawMarkerSymbol(&map->symbolset, image_draw, &marker, theclass->styles[i], lp->scalefactor);
       }
-      
-      symbol = map->symbolset.symbol[symbolNum];
-      
-      initStyle(&imgStyle);
-      /*set size so that symbol will be scaled properly #3296*/
-      if (width/symbol->sizex < height/symbol->sizey)
-        imgStyle.size = symbol->sizey*(width/symbol->sizex);
-      else
-        imgStyle.size = symbol->sizey*(height/symbol->sizey);
+      break;
+    case MS_LAYER_LINE:
+      offset = 1;
+      /* To set the offset, we only check the size/width parameter of the first style */
+      if (theclass->numstyles > 0) {
+        offset = (theclass->styles[0]->size != -1) ? theclass->styles[0]->size/2 : theclass->styles[0]->width/2;
+      }
+      zigzag.line = (lineObj *)msSmallMalloc(sizeof(lineObj));
+      zigzag.numlines = 1;
+      zigzag.line[0].point = (pointObj *)msSmallMalloc(sizeof(pointObj)*4);
+      zigzag.line[0].numpoints = 4;
+
+      zigzag.line[0].point[0].x = dstX + offset;
+      zigzag.line[0].point[0].y = dstY + height - offset;
+      zigzag.line[0].point[1].x = dstX + MS_NINT(width / 3.0) - 1;
+      zigzag.line[0].point[1].y = dstY + offset;
+      zigzag.line[0].point[2].x = dstX + MS_NINT(2.0 * width / 3.0) - 1;
+      zigzag.line[0].point[2].y = dstY + height - offset;
+      zigzag.line[0].point[3].x = dstX + width - offset;
+      zigzag.line[0].point[3].y = dstY + offset;
 
-      if (imgStyle.size > imgStyle.maxsize)
-        imgStyle.maxsize = imgStyle.size;
+      for(i=0; i<theclass->numstyles; i++)
+        msDrawLineSymbol(&map->symbolset, image_draw, &zigzag, theclass->styles[i], lp->scalefactor);
 
-      imgStyle.symbol = symbolNum;
-      msDrawMarkerSymbol(&map->symbolset,image_draw,&marker,&imgStyle,lp->scalefactor);
-      /* TO DO: we may want to handle this differently depending on the relative size of the keyimage */
-    } else {
+      free(zigzag.line[0].point);
+      free(zigzag.line);
+      break;
+    case MS_LAYER_CIRCLE:
+    case MS_LAYER_RASTER:
+    case MS_LAYER_CHART:
+    case MS_LAYER_POLYGON:
       for(i=0; i<theclass->numstyles; i++)
-        msDrawMarkerSymbol(&map->symbolset, image_draw, &marker, theclass->styles[i], lp->scalefactor);
-    }
-    break;
-  case MS_LAYER_LINE:
-    offset = 1;
-    /* To set the offset, we only check the size/width parameter of the first style */
-    if (theclass->numstyles > 0) {
-      offset = (theclass->styles[0]->size != -1) ? theclass->styles[0]->size/2 : theclass->styles[0]->width/2;
-    }
-    zigzag.line = (lineObj *)msSmallMalloc(sizeof(lineObj));
-    zigzag.numlines = 1;
-    zigzag.line[0].point = (pointObj *)msSmallMalloc(sizeof(pointObj)*4);
-    zigzag.line[0].numpoints = 4;
-
-    zigzag.line[0].point[0].x = dstX + offset;
-    zigzag.line[0].point[0].y = dstY + height - offset;
-    zigzag.line[0].point[1].x = dstX + MS_NINT(width / 3.0) - 1; 
-    zigzag.line[0].point[1].y = dstY + offset;
-    zigzag.line[0].point[2].x = dstX + MS_NINT(2.0 * width / 3.0) - 1; 
-    zigzag.line[0].point[2].y = dstY + height - offset; 
-    zigzag.line[0].point[3].x = dstX + width - offset; 
-    zigzag.line[0].point[3].y = dstY + offset;
-
-    for(i=0; i<theclass->numstyles; i++)
-      msDrawLineSymbol(&map->symbolset, image_draw, &zigzag, theclass->styles[i], lp->scalefactor); 
-
-    free(zigzag.line[0].point);
-    free(zigzag.line);    
-    break;
-  case MS_LAYER_CIRCLE:
-  case MS_LAYER_RASTER:
-  case MS_LAYER_CHART:
-  case MS_LAYER_POLYGON:
-    for(i=0; i<theclass->numstyles; i++)     
-      msDrawShadeSymbol(&map->symbolset, image_draw, &box, theclass->styles[i], lp->scalefactor);
-    break;
-  default:
-    return MS_FAILURE;
-    break;
+        msDrawShadeSymbol(&map->symbolset, image_draw, &box, theclass->styles[i], lp->scalefactor);
+      break;
+    default:
+      return MS_FAILURE;
+      break;
   } /* end symbol drawing */
 
   /* handle an outline if necessary */
@@ -236,55 +249,53 @@ int msDrawLegendIcon(mapObj *map, layerObj *lp, classObj *theclass,
     msDrawLineSymbol(&map->symbolset, image_draw, &box, &outline_style, 1.0);
     /* reset clipping rectangle */
     if(renderer->supports_clipping)
-    	renderer->resetClip(image_draw);
+      renderer->resetClip(image_draw);
   }
 
-  if (altFormat)
-  {
-      rendererVTableObj *renderer = MS_IMAGE_RENDERER(image);
-      rendererVTableObj *altrenderer = MS_IMAGE_RENDERER(image_draw);
-      rasterBufferObj rb;
-      memset(&rb,0,sizeof(rasterBufferObj));
-
-      altrenderer->getRasterBufferHandle(image_draw,&rb);
-      renderer->mergeRasterBuffer(image,&rb,lp->opacity*0.01,0,0,0,0,rb.width,rb.height);  
-      /* 
-       * hack to work around bug #3834: if we have use an alternate renderer, the symbolset may contain
-       * symbols that reference it. We want to remove those references before the altFormat is destroyed
-       * to avoid a segfault and/or a leak, and so the the main renderer doesn't pick the cache up thinking
-       * it's for him.
-       */
-      for(i=0; i<map->symbolset.numsymbols; i++) {
-         if (map->symbolset.symbol[i]!=NULL) {
-            symbolObj *s = map->symbolset.symbol[i];
-            if(s->renderer == altrenderer) {
-	            altrenderer->freeSymbol(s);
-               s->renderer = NULL;
-            }
-         }
+  if (altFormat) {
+    rendererVTableObj *renderer = MS_IMAGE_RENDERER(image);
+    rendererVTableObj *altrenderer = MS_IMAGE_RENDERER(image_draw);
+    rasterBufferObj rb;
+    memset(&rb,0,sizeof(rasterBufferObj));
+
+    altrenderer->getRasterBufferHandle(image_draw,&rb);
+    renderer->mergeRasterBuffer(image,&rb,lp->opacity*0.01,0,0,0,0,rb.width,rb.height);
+    /*
+     * hack to work around bug #3834: if we have use an alternate renderer, the symbolset may contain
+     * symbols that reference it. We want to remove those references before the altFormat is destroyed
+     * to avoid a segfault and/or a leak, and so the the main renderer doesn't pick the cache up thinking
+     * it's for him.
+     */
+    for(i=0; i<map->symbolset.numsymbols; i++) {
+      if (map->symbolset.symbol[i]!=NULL) {
+        symbolObj *s = map->symbolset.symbol[i];
+        if(s->renderer == altrenderer) {
+          altrenderer->freeSymbol(s);
+          s->renderer = NULL;
+        }
       }
-      msFreeImage(image_draw);
-      
-  }
-  else if(image != image_draw) {
-	  rendererVTableObj *renderer = MS_IMAGE_RENDERER(image_draw);
-	  rasterBufferObj rb;
-	  memset(&rb,0,sizeof(rasterBufferObj));
+    }
+    msFreeImage(image_draw);
+
+  } else if(image != image_draw) {
+    rendererVTableObj *renderer = MS_IMAGE_RENDERER(image_draw);
+    rasterBufferObj rb;
+    memset(&rb,0,sizeof(rasterBufferObj));
 
-	  lp->opacity = originalopacity;
+    lp->opacity = originalopacity;
 
-	  renderer->getRasterBufferHandle(image_draw,&rb);
-	  renderer->mergeRasterBuffer(image,&rb,lp->opacity*0.01,0,0,0,0,rb.width,rb.height);  
-	  msFreeImage(image_draw);
+    renderer->getRasterBufferHandle(image_draw,&rb);
+    renderer->mergeRasterBuffer(image,&rb,lp->opacity*0.01,0,0,0,0,rb.width,rb.height);
+    msFreeImage(image_draw);
 
-	  /* deref and possibly free temporary transparent output format.  */
-	  msApplyOutputFormat( &transFormat, NULL, MS_NOOVERRIDE, MS_NOOVERRIDE, MS_NOOVERRIDE );
+    /* deref and possibly free temporary transparent output format.  */
+    msApplyOutputFormat( &transFormat, NULL, MS_NOOVERRIDE, MS_NOOVERRIDE, MS_NOOVERRIDE );
 
   }
 
   free(box.line[0].point);
   free(box.line);
-  
+
   return MS_SUCCESS;
 }
 
@@ -294,9 +305,9 @@ imageObj *msCreateLegendIcon(mapObj* map, layerObj* lp, classObj* class, int wid
   imageObj *image;
   outputFormatObj *format = NULL;
   int i = 0;
-  
+
   rendererVTableObj *renderer = MS_MAP_RENDERER(map);
-  
+
   if( !renderer ) {
     msSetError(MS_MISCERR, "invalid map outputformat", "msCreateLegendIcon()");
     return(NULL);
@@ -304,10 +315,10 @@ imageObj *msCreateLegendIcon(mapObj* map, layerObj* lp, classObj* class, int wid
 
   /* ensure we have an image format representing the options for the legend */
   msApplyOutputFormat(&format, map->outputformat, map->legend.transparent, map->legend.interlace, MS_NOOVERRIDE);
-  
+
   image = msImageCreate(width,height,format,map->web.imagepath, map->web.imageurl,
-		  map->resolution, map->defresolution, &(map->legend.imagecolor));
-  
+                        map->resolution, map->defresolution, &(map->legend.imagecolor));
+
   /* drop this reference to output format */
   msApplyOutputFormat( &format, NULL, MS_NOOVERRIDE, MS_NOOVERRIDE, MS_NOOVERRIDE );
 
@@ -321,7 +332,9 @@ imageObj *msCreateLegendIcon(mapObj* map, layerObj* lp, classObj* class, int wid
   /* (If class is NULL draw the legend for all classes. Modifications done */
   /* Fev 2004 by AY) */
   if (lp) {
+#ifdef USE_GD
     msClearLayerPenValues(lp); /* just in case the mapfile has already been processed */
+#endif
     if (class) {
       msDrawLegendIcon(map, lp, class, width, height, image, 0, 0);
     } else {
@@ -338,25 +351,25 @@ imageObj *msCreateLegendIcon(mapObj* map, layerObj* lp, classObj* class, int wid
  * argument is given, the legend size will be calculated for only that
  * layer. Otherwise, the legend size is calculated for all layers that
  * are not MS_OFF or of MS_LAYER_QUERY type.
- *     
+ *
  * Returns one of:
  *   MS_SUCCESS
  *   MS_FAILURE
  */
-int msLegendCalcSize(mapObj *map, int scale_independent, int *size_x, int *size_y, 
+int msLegendCalcSize(mapObj *map, int scale_independent, int *size_x, int *size_y,
                      int *layer_index, int num_layers)
 {
   int i, j;
   int status, maxwidth=0, nLegendItems=0;
   char *text, *transformedText; /* legend text before/after applying wrapping, encoding if necessary */
-  layerObj *lp;  
+  layerObj *lp;
   rectObj rect;
   int current_layers=0;
 
   /* reset sizes */
   *size_x = 0;
   *size_y = 0;
-    
+
   /* enable scale-dependent calculations */
   if(!scale_independent) {
     map->cellsize = msAdjustExtent(&(map->extent), map->width, map->height);
@@ -372,7 +385,7 @@ int msLegendCalcSize(mapObj *map, int scale_independent, int *size_x, int *size_
     current_layers  = num_layers;
   else
     current_layers = map->numlayers;
-       
+
   for(i=0; i< current_layers; i++) {
 
     if (layer_index != NULL && num_layers > 0)
@@ -382,48 +395,48 @@ int msLegendCalcSize(mapObj *map, int scale_independent, int *size_x, int *size_
 
     if((lp->status == MS_OFF && (layer_index == NULL || num_layers <= 0)) || (lp->type == MS_LAYER_QUERY)) /* skip it */
       continue;
-            
+
     if(!scale_independent && map->scaledenom > 0) {
       if((lp->maxscaledenom > 0) && (map->scaledenom > lp->maxscaledenom)) continue;
       if((lp->minscaledenom > 0) && (map->scaledenom <= lp->minscaledenom)) continue;
     }
-        
+
     for(j=lp->numclasses-1; j>=0; j--) {
       text = lp->class[j]->title?lp->class[j]->title:lp->class[j]->name; /* point to the right legend text, title takes precedence */
       if(!text) continue; /* skip it */
-            
+
       /* skip the class if the classgroup is defined */
       if(lp->classgroup && (lp->class[j]->group == NULL || strcasecmp(lp->class[j]->group, lp->classgroup) != 0))
         continue;
 
-       /* verify class scale */
-       if(!scale_independent && map->scaledenom > 0) {
-         if((lp->class[j]->maxscaledenom > 0) && (map->scaledenom > lp->class[j]->maxscaledenom)) continue;                    
-         if((lp->class[j]->minscaledenom > 0) && (map->scaledenom <= lp->class[j]->minscaledenom)) continue;
-       }
-            
-       /*
-        * apply encoding and line wrapping to the legend label if requested
-        * this is done conditionally as the text transformation function
-        * does some memory allocations that can be avoided in most cases.
-        * the transformed text must be freed once finished, this must be done
-        * conditionnally by testing if the transformed text pointer is the
-        * same as the class name pointer
-        */
-       if(map->legend.label.encoding || map->legend.label.wrap)
-         transformedText = msTransformLabelText(map,NULL,&map->legend.label, text);
-       else
-         transformedText = msStrdup(text);
-
-       if(transformedText == NULL || msGetLabelSize(map, &map->legend.label, transformedText, map->legend.label.size, &rect, NULL) != MS_SUCCESS) { /* something bad happened */
-         if(transformedText) msFree(transformedText);
-         return MS_FAILURE;
-       }
-
-       msFree(transformedText);
-       maxwidth = MS_MAX(maxwidth, MS_NINT(rect.maxx - rect.minx));
-       *size_y += MS_MAX(MS_NINT(rect.maxy - rect.miny), map->legend.keysizey);
-       nLegendItems++;
+      /* verify class scale */
+      if(!scale_independent && map->scaledenom > 0) {
+        if((lp->class[j]->maxscaledenom > 0) && (map->scaledenom > lp->class[j]->maxscaledenom)) continue;
+        if((lp->class[j]->minscaledenom > 0) && (map->scaledenom <= lp->class[j]->minscaledenom)) continue;
+      }
+
+      /*
+       * apply encoding and line wrapping to the legend label if requested
+       * this is done conditionally as the text transformation function
+       * does some memory allocations that can be avoided in most cases.
+       * the transformed text must be freed once finished, this must be done
+       * conditionnally by testing if the transformed text pointer is the
+       * same as the class name pointer
+       */
+      if(map->legend.label.encoding || map->legend.label.wrap)
+        transformedText = msTransformLabelText(map,&map->legend.label, text);
+      else
+        transformedText = msStrdup(text);
+
+      if(transformedText == NULL || msGetLabelSize(map, &map->legend.label, transformedText, map->legend.label.size, &rect, NULL) != MS_SUCCESS) { /* something bad happened */
+        if(transformedText) msFree(transformedText);
+        return MS_FAILURE;
+      }
+
+      msFree(transformedText);
+      maxwidth = MS_MAX(maxwidth, MS_NINT(rect.maxx - rect.minx));
+      *size_y += MS_MAX(MS_NINT(rect.maxy - rect.miny), map->legend.keysizey);
+      nLegendItems++;
     }
   }
 
@@ -432,7 +445,7 @@ int msLegendCalcSize(mapObj *map, int scale_independent, int *size_x, int *size_
   *size_y += (2*VMARGIN) + ((nLegendItems-1) * map->legend.keyspacingy);
   /*   - determine the legend width */
   *size_x = (2*HMARGIN) + maxwidth + map->legend.keyspacingx + map->legend.keysizex;
-    
+
   if(*size_y <=0 ||  *size_x <=0)
     return MS_FAILURE;
 
@@ -454,7 +467,7 @@ imageObj *msDrawLegend(mapObj *map, int scale_independent)
   int i,j; /* loop counters */
   pointObj pnt;
   int size_x, size_y=0;
-  layerObj *lp;  
+  layerObj *lp;
   rectObj rect;
   imageObj *image = NULL;
   outputFormatObj *format = NULL;
@@ -469,10 +482,10 @@ imageObj *msDrawLegend(mapObj *map, int scale_independent)
   };
   typedef struct legend_struct legendlabel;
   legendlabel *head=NULL,*cur=NULL;
-  
+
   if(!MS_RENDERER_PLUGIN(map->outputformat)) {
-      msSetError(MS_MISCERR,"unsupported output format","msDrawLegend()");
-      return NULL;
+    msSetError(MS_MISCERR,"unsupported output format","msDrawLegend()");
+    return NULL;
   }
   if(msValidateContexts(map) != MS_SUCCESS) return NULL; /* make sure there are no recursive REQUIRES or LABELREQUIRES expressions */
   if(msLegendCalcSize(map, scale_independent, &size_x, &size_y, NULL, 0) != MS_SUCCESS) return NULL;
@@ -486,7 +499,7 @@ imageObj *msDrawLegend(mapObj *map, int scale_independent)
 
     if((lp->status == MS_OFF) || (lp->type == MS_LAYER_QUERY)) /* skip it */
       continue;
-        
+
     if(!scale_independent && map->scaledenom > 0) {
       if((lp->maxscaledenom > 0) && (map->scaledenom > lp->maxscaledenom)) continue;
       if((lp->minscaledenom > 0) && (map->scaledenom <= lp->minscaledenom)) continue;
@@ -497,7 +510,7 @@ imageObj *msDrawLegend(mapObj *map, int scale_independent)
       if((lp->mingeowidth > 0) && ((map->extent.maxx - map->extent.minx) < lp->mingeowidth)) continue;
     }
 
-    for(j=lp->numclasses-1;j>=0;j--) {
+    for(j=lp->numclasses-1; j>=0; j--) {
       text = lp->class[j]->title?lp->class[j]->title:lp->class[j]->name; /* point to the right legend text, title takes precedence */
       if(!text) continue; /* skip it */
 
@@ -511,7 +524,7 @@ imageObj *msDrawLegend(mapObj *map, int scale_independent)
       }
 
       cur = (legendlabel*) msSmallMalloc(sizeof(legendlabel));
-            
+
       /*
        * apply encoding and line wrapping to the legend label if requested
        * this is done conditionnally as the text transformation function
@@ -521,7 +534,7 @@ imageObj *msDrawLegend(mapObj *map, int scale_independent)
        * same as the class name pointer
        */
       if(map->legend.label.encoding || map->legend.label.wrap)
-        cur->transformedText = msTransformLabelText(map,NULL,&map->legend.label,text);
+        cur->transformedText = msTransformLabelText(map,&map->legend.label,text);
       else
         cur->transformedText = msStrdup(text); /* so we can always do msFree() when cleaning up */
 
@@ -530,17 +543,17 @@ imageObj *msDrawLegend(mapObj *map, int scale_independent)
       cur->pred = head;
       head = cur;
 
-      if(cur->transformedText==NULL || 
-    		  msGetLabelSize(map, &map->legend.label, cur->transformedText, map->legend.label.size, &rect, NULL) != MS_SUCCESS) { /* something bad happened, free allocated mem */
-        while(cur) {          
+      if(cur->transformedText==NULL ||
+          msGetLabelSize(map, &map->legend.label, cur->transformedText, map->legend.label.size, &rect, NULL) != MS_SUCCESS) { /* something bad happened, free allocated mem */
+        while(cur) {
           free(cur->transformedText);
           head = cur;
           cur = cur->pred;
           free(head);
         }
-        return(NULL); 
+        return(NULL);
       }
-            
+
       cur->height = MS_MAX(MS_NINT(rect.maxy - rect.miny), map->legend.keysizey);
     }
   }
@@ -554,12 +567,14 @@ imageObj *msDrawLegend(mapObj *map, int scale_independent)
     msSetError(MS_MISCERR, "Unable to initialize image.", "msDrawLegend()");
     return NULL;
   }
-  //image = renderer->createImage(size_x,size_y,format,&(map->legend.imagecolor));
+  /* image = renderer->createImage(size_x,size_y,format,&(map->legend.imagecolor)); */
 
   /* drop this reference to output format */
   msApplyOutputFormat(&format, NULL, MS_NOOVERRIDE, MS_NOOVERRIDE, MS_NOOVERRIDE);
 
+#ifdef USE_GD
   msClearPenValues(map); /* just in case the mapfile has already been processed */
+#endif
   pnt.y = VMARGIN;
   pnt.x = HMARGIN + map->legend.keysizex + map->legend.keyspacingx;
 
@@ -568,25 +583,25 @@ imageObj *msDrawLegend(mapObj *map, int scale_independent)
 
     /* set the scale factor so that scale dependant symbols are drawn in the legend with their default size */
     if(cur->layer->sizeunits != MS_PIXELS) {
-       map->cellsize = msAdjustExtent(&(map->extent), map->width, map->height);
+      map->cellsize = msAdjustExtent(&(map->extent), map->width, map->height);
       cur->layer->scalefactor = (msInchesPerUnit(cur->layer->sizeunits,0)/msInchesPerUnit(map->units,0)) / map->cellsize;
     }
     if(msDrawLegendIcon(map, cur->layer, cur->theclass,  map->legend.keysizex,  map->legend.keysizey, image, HMARGIN, (int) pnt.y) != MS_SUCCESS)
       return NULL;
-        
+
     /*
-     * adjust the baseline for multiline truetype labels. the label point is the bottom left 
+     * adjust the baseline for multiline truetype labels. the label point is the bottom left
      * corner of the *first* line, which we do not know exactly as we only have the
      * bounding box of the whole label. current approach is to suppose that all lines
-     * mostly have the same height, and offset the starting point by the mean hight of 
+     * mostly have the same height, and offset the starting point by the mean hight of
      * one line. This isn't perfect but still much better than the previous approach
-     */        
+     */
     if(map->legend.label.type==MS_TRUETYPE && (number_of_newlines=msCountChars(cur->transformedText,'\n')) > 0) {
       offset=cur->height/(number_of_newlines+1);
       pnt.y += offset;
     } else
       pnt.y += cur->height;
- 
+
     /* TODO: note tbonfort: if this todo concerned treating the individual heights of the legend labels, then this is now done */
 
     msDrawLabel(map, image, pnt, cur->transformedText, &(map->legend.label), 1.0);
@@ -595,14 +610,14 @@ imageObj *msDrawLegend(mapObj *map, int scale_independent)
       pnt.y += cur->height-offset;
     }
     pnt.y += map->legend.keyspacingy; /* bump y for next label */
-        
+
     /* clean up */
     free(cur->transformedText);
     head = cur;
     cur = cur->pred;
     free(head);
   } /* next legend */
-    
+
   return(image);
 }
 
@@ -623,7 +638,7 @@ int msEmbedLegend(mapObj *map, imageObj *img)
   renderer = MS_MAP_RENDERER(map);
 
   s = msGetSymbolIndex(&(map->symbolset), "legend", MS_FALSE);
-  if(s != -1) 
+  if(s != -1)
     msRemoveSymbol(&(map->symbolset), s); /* solves some caching issues in AGG with long-running processes */
 
   if(msGrowSymbolSet(&map->symbolset) == NULL)
@@ -642,7 +657,7 @@ int msEmbedLegend(mapObj *map, imageObj *img)
   MS_CHECK_ALLOC(legendSymbol->pixmap_buffer, sizeof(rasterBufferObj), MS_FAILURE);
 
   if(MS_SUCCESS != renderer->getRasterBufferCopy(image,legendSymbol->pixmap_buffer))
-	  return MS_FAILURE;
+    return MS_FAILURE;
   legendSymbol->renderer = renderer;
 
   msFreeImage( image );
@@ -650,73 +665,86 @@ int msEmbedLegend(mapObj *map, imageObj *img)
   if(!legendSymbol->pixmap_buffer) return(-1); /* something went wrong creating scalebar */
 
   legendSymbol->type = MS_SYMBOL_PIXMAP; /* intialize a few things */
-  legendSymbol->name = msStrdup("legend");  
+  legendSymbol->name = msStrdup("legend");
   legendSymbol->sizex = legendSymbol->pixmap_buffer->width;
   legendSymbol->sizey = legendSymbol->pixmap_buffer->height;
 
   /* I'm not too sure this test is sufficient ... NFW. */
-  //if(map->legend.transparent == MS_ON)
-  //  gdImageColorTransparent(legendSymbol->img_deprecated, 0);
+  /* if(map->legend.transparent == MS_ON) */
+  /*  gdImageColorTransparent(legendSymbol->img_deprecated, 0); */
 
   switch(map->legend.position) {
-  case(MS_LL):
-    point.x = MS_NINT(legendSymbol->sizex/2.0);
-    point.y = map->height - MS_NINT(legendSymbol->sizey/2.0);
-    break;
-  case(MS_LR):
-    point.x = map->width - MS_NINT(legendSymbol->sizex/2.0);
-    point.y = map->height - MS_NINT(legendSymbol->sizey/2.0);
-    break;
-  case(MS_LC):
-    point.x = MS_NINT(map->width/2.0);
-    point.y = map->height - MS_NINT(legendSymbol->sizey/2.0);
-    break;
-  case(MS_UR):
-    point.x = map->width - MS_NINT(legendSymbol->sizex/2.0);
-    point.y = MS_NINT(legendSymbol->sizey/2.0);
-    break;
-  case(MS_UL):
-    point.x = MS_NINT(legendSymbol->sizex/2.0);
-    point.y = MS_NINT(legendSymbol->sizey/2.0);
-    break;
-  case(MS_UC):
-    point.x = MS_NINT(map->width/2.0);
-    point.y = MS_NINT(legendSymbol->sizey/2.0);
-    break;
+    case(MS_LL):
+      point.x = MS_NINT(legendSymbol->sizex/2.0);
+      point.y = map->height - MS_NINT(legendSymbol->sizey/2.0);
+      break;
+    case(MS_LR):
+      point.x = map->width - MS_NINT(legendSymbol->sizex/2.0);
+      point.y = map->height - MS_NINT(legendSymbol->sizey/2.0);
+      break;
+    case(MS_LC):
+      point.x = MS_NINT(map->width/2.0);
+      point.y = map->height - MS_NINT(legendSymbol->sizey/2.0);
+      break;
+    case(MS_UR):
+      point.x = map->width - MS_NINT(legendSymbol->sizex/2.0);
+      point.y = MS_NINT(legendSymbol->sizey/2.0);
+      break;
+    case(MS_UL):
+      point.x = MS_NINT(legendSymbol->sizex/2.0);
+      point.y = MS_NINT(legendSymbol->sizey/2.0);
+      break;
+    case(MS_UC):
+      point.x = MS_NINT(map->width/2.0);
+      point.y = MS_NINT(legendSymbol->sizey/2.0);
+      break;
   }
 
   l = msGetLayerIndex(map, "__embed__legend");
   if(l == -1) {
     if(msGrowMapLayers(map) == NULL)
-        return(-1);
+      return(-1);
     l = map->numlayers;
     map->numlayers++;
     if(initLayer((GET_LAYER(map, l)), map) == -1) return(-1);
     GET_LAYER(map, l)->name = msStrdup("__embed__legend");
-    GET_LAYER(map, l)->type = MS_LAYER_ANNOTATION;
+    GET_LAYER(map, l)->type = MS_LAYER_POINT;
 
     if(msGrowLayerClasses( GET_LAYER(map, l) ) == NULL)
-        return(-1);
+      return(-1);
     if(initClass(GET_LAYER(map, l)->class[0]) == -1) return(-1);
     GET_LAYER(map, l)->numclasses = 1; /* so we make sure to free it */
-        
+
     /* update the layer order list with the layer's index. */
     map->layerorder[l] = l;
   }
 
   GET_LAYER(map, l)->status = MS_ON;
 
-  if(msMaybeAllocateClassStyle(GET_LAYER(map, l)->class[0], 0)==MS_FAILURE) return MS_FAILURE;
-  GET_LAYER(map, l)->class[0]->styles[0]->symbol = s;
-  GET_LAYER(map, l)->class[0]->styles[0]->color.pen = -1;
-  GET_LAYER(map, l)->class[0]->label.force = MS_TRUE;
-  GET_LAYER(map, l)->class[0]->label.size = MS_MEDIUM; /* must set a size to have a valid label definition */
-  GET_LAYER(map, l)->class[0]->label.priority = MS_MAX_LABEL_PRIORITY;
-
-  if(map->legend.postlabelcache) /* add it directly to the image */
+  if(map->legend.postlabelcache) { /* add it directly to the image */
+    if(msMaybeAllocateClassStyle(GET_LAYER(map, l)->class[0], 0)==MS_FAILURE) return MS_FAILURE;
+    GET_LAYER(map, l)->class[0]->styles[0]->symbol = s;
     msDrawMarkerSymbol(&map->symbolset, img, &point, GET_LAYER(map, l)->class[0]->styles[0], 1.0);
-  else
-    msAddLabel(map, l, 0, NULL, &point, NULL, "", 1.0, NULL);
+  } else {
+    if(!GET_LAYER(map, l)->class[0]->labels) {
+      if(msGrowClassLabels(GET_LAYER(map, l)->class[0]) == NULL) return MS_FAILURE;
+      initLabel(GET_LAYER(map, l)->class[0]->labels[0]);
+      GET_LAYER(map, l)->class[0]->numlabels = 1;
+      GET_LAYER(map, l)->class[0]->labels[0]->force = MS_TRUE;
+      GET_LAYER(map, l)->class[0]->labels[0]->size = MS_MEDIUM; /* must set a size to have a valid label definition */
+      GET_LAYER(map, l)->class[0]->labels[0]->priority = MS_MAX_LABEL_PRIORITY;
+      GET_LAYER(map, l)->class[0]->labels[0]->annotext = NULL;
+    }
+    if(GET_LAYER(map, l)->class[0]->labels[0]->numstyles == 0) {
+      if(msGrowLabelStyles(GET_LAYER(map,l)->class[0]->labels[0]) == NULL)
+        return(MS_FAILURE);
+      GET_LAYER(map,l)->class[0]->labels[0]->numstyles = 1;
+      initStyle(GET_LAYER(map,l)->class[0]->labels[0]->styles[0]);
+      GET_LAYER(map,l)->class[0]->labels[0]->styles[0]->_geomtransform.type = MS_GEOMTRANSFORM_LABELPOINT;
+    }
+    GET_LAYER(map,l)->class[0]->labels[0]->styles[0]->symbol = s;
+    msAddLabel(map, GET_LAYER(map, l)->class[0]->labels[0], l, 0, NULL, &point, NULL, -1);
+  }
 
   /* Mark layer as deleted so that it doesn't interfere with html legends or with saving maps */
   GET_LAYER(map, l)->status = MS_DELETE;
diff --git a/maplexer.c b/maplexer.c
index c5aa6fa..a9da53f 100644
--- a/maplexer.c
+++ b/maplexer.c
@@ -6,29 +6,10 @@
 
 /* A lexical scanner generated by flex */
 
-#define yy_create_buffer msyy_create_buffer
-#define yy_delete_buffer msyy_delete_buffer
-#define yy_flex_debug msyy_flex_debug
-#define yy_init_buffer msyy_init_buffer
-#define yy_flush_buffer msyy_flush_buffer
-#define yy_load_buffer_state msyy_load_buffer_state
-#define yy_switch_to_buffer msyy_switch_to_buffer
-#define yyin msyyin
-#define yyleng msyyleng
-#define yylex msyylex
-#define yylineno msyylineno
-#define yyout msyyout
-#define yyrestart msyyrestart
-#define yytext msyytext
-#define yywrap msyywrap
-#define yyalloc msyyalloc
-#define yyrealloc msyyrealloc
-#define yyfree msyyfree
-
 #define FLEX_SCANNER
 #define YY_FLEX_MAJOR_VERSION 2
 #define YY_FLEX_MINOR_VERSION 5
-#define YY_FLEX_SUBMINOR_VERSION 35
+#define YY_FLEX_SUBMINOR_VERSION 33
 #if YY_FLEX_SUBMINOR_VERSION > 0
 #define FLEX_BETA
 #endif
@@ -50,7 +31,7 @@
 
 /* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */
 
-#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
+#if __STDC_VERSION__ >= 199901L
 
 /* C99 says to define __STDC_LIMIT_MACROS before including stdint.h,
  * if you want the limit (max/min) macros for int types. 
@@ -73,6 +54,7 @@ typedef int flex_int32_t;
 typedef unsigned char flex_uint8_t; 
 typedef unsigned short int flex_uint16_t;
 typedef unsigned int flex_uint32_t;
+#endif /* ! C99 */
 
 /* Limits of integral types. */
 #ifndef INT8_MIN
@@ -103,8 +85,6 @@ typedef unsigned int flex_uint32_t;
 #define UINT32_MAX             (4294967295U)
 #endif
 
-#endif /* ! C99 */
-
 #endif /* ! FLEXINT_H */
 
 #ifdef __cplusplus
@@ -114,12 +94,11 @@ typedef unsigned int flex_uint32_t;
 
 #else	/* ! __cplusplus */
 
-/* C99 requires __STDC__ to be defined as 1. */
-#if defined (__STDC__)
+#if __STDC__
 
 #define YY_USE_CONST
 
-#endif	/* defined (__STDC__) */
+#endif	/* __STDC__ */
 #endif	/* ! __cplusplus */
 
 #ifdef YY_USE_CONST
@@ -161,15 +140,7 @@ typedef unsigned int flex_uint32_t;
 
 /* Size of default input buffer. */
 #ifndef YY_BUF_SIZE
-#ifdef __ia64__
-/* On IA-64, the buffer size is 16k, not 8k.
- * Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case.
- * Ditto for the __ia64__ case accordingly.
- */
-#define YY_BUF_SIZE 32768
-#else
 #define YY_BUF_SIZE 16384
-#endif /* __ia64__ */
 #endif
 
 /* The state buf must be large enough to hold one state per character in the main buffer.
@@ -207,9 +178,14 @@ extern FILE *msyyin, *msyyout;
 
 #define unput(c) yyunput( c, (yytext_ptr)  )
 
+/* The following is because we cannot portably get our hands on size_t
+ * (without autoconf's help, which isn't available because we want
+ * flex-generated scanners to compile on their own).
+ */
+
 #ifndef YY_TYPEDEF_YY_SIZE_T
 #define YY_TYPEDEF_YY_SIZE_T
-typedef size_t yy_size_t;
+typedef unsigned int yy_size_t;
 #endif
 
 #ifndef YY_STRUCT_YY_BUFFER_STATE
@@ -388,8 +364,8 @@ static void yy_fatal_error (yyconst char msg[]  );
 	*yy_cp = '\0'; \
 	(yy_c_buf_p) = yy_cp;
 
-#define YY_NUM_RULES 314
-#define YY_END_OF_BUFFER 315
+#define YY_NUM_RULES 322
+#define YY_END_OF_BUFFER 323
 /* This struct is not used in this scanner,
    but its presence is necessary. */
 struct yy_trans_info
@@ -397,207 +373,212 @@ struct yy_trans_info
 	flex_int32_t yy_verify;
 	flex_int32_t yy_nxt;
 	};
-static yyconst flex_int16_t yy_accept[1807] =
+static yyconst flex_int16_t yy_accept[1854] =
     {   0,
         0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
-        0,    0,  315,  312,    1,  310,  303,    2,  312,  312,
-      297,  309,  297,  309,  309,  309,  309,  309,  309,  309,
-      309,  309,  309,  309,  309,  309,  309,  309,  309,  309,
-      309,  309,  309,  309,  309,  309,  309,  312,  311,  311,
-        3,  312,  312,  312,  312,  312,  312,  312,  312,  312,
-      312,  312,  312,  312,  312,  312,    1,  309,  309,  309,
-      309,  309,  309,  309,  309,  309,  309,  309,  309,  309,
-      309,  309,  309,  309,  309,  309,  309,  313,    1,    1,
-        6,  308,  313,  308,  313,  298,  298,   10,    7,    9,
-
-      313,  313,  313,  313,  313,  313,  313,  313,  313,  313,
-      313,  313,  313,  313,  313,  313,  311,   13,  311,  314,
-        1,  314,  314,  306,  304,  304,  305,    1,    2,    0,
-      302,  297,  297,  309,  297,  309,    0,  309,  301,  297,
-        0,  309,  309,  309,  309,  309,  309,  309,  309,  219,
-      309,  309,  309,  223,  309,  224,  309,  309,  229,  309,
-      309,  309,  309,  309,  309,  309,  309,  309,  309,  309,
-      309,  309,  309,  309,  309,  309,  309,  309,  309,  309,
-      309,  309,  309,  309,  309,  309,  241,  309,  309,  244,
-      309,  245,  309,  309,  309,  309,  309,  309,  309,  309,
-
-      309,  256,  309,  309,  309,  309,  309,  309,  309,  309,
-      309,  309,  309,  309,  309,  309,  309,  309,  309,  309,
-      309,  309,  309,  309,  309,  309,  309,  309,  309,  309,
-      200,  309,  309,  282,  283,  309,  284,  309,  309,  309,
-      309,  309,  309,  309,  309,    0,  292,    0,    0,    0,
+        0,    0,  323,  320,    1,  318,  311,    2,  320,  320,
+      305,  317,  305,  320,  317,  317,  317,  317,  317,  317,
+      317,  317,  317,  317,  317,  317,  317,  317,  317,  317,
+      317,  317,  317,  317,  317,  317,  317,  317,  319,  319,
+        3,  320,  320,  320,  320,  320,  320,  320,  320,  320,
+      320,  320,  320,  320,  320,  320,    1,  317,  317,  317,
+      317,  317,  317,  317,  317,  317,  317,  317,  317,  317,
+      317,  317,  317,  317,  317,  317,  317,  321,    1,    1,
+        6,  316,  321,  316,  321,  306,  306,   10,    7,    9,
+
+      321,  321,  321,  321,  321,  321,  321,  321,  321,  321,
+      321,  321,  321,  321,  321,  321,  319,   13,  319,  322,
+        1,  322,  322,  314,  312,  312,  313,    1,    2,    0,
+      310,  305,  305,  317,  305,  317,    0,  317,  309,  305,
+        0,    0,  300,  317,  317,  317,  317,  317,  317,  317,
+      317,  225,  317,  317,  317,  229,  317,  230,  317,  317,
+      235,  317,  317,  317,  317,  317,  317,  317,  317,  317,
+      317,  317,  317,  317,  317,  317,  317,  317,  317,  317,
+      317,  317,  317,  317,  317,  317,  317,  317,  247,  317,
+      317,  250,  317,  251,  317,  317,  317,  317,  317,  317,
+
+      317,  317,  317,  262,  317,  317,  317,  317,  317,  317,
+      317,  317,  317,  317,  317,  317,  317,  317,  317,  317,
+      317,  317,  317,  317,  317,  317,  317,  317,  317,  317,
+      317,  317,  206,  317,  317,  289,  290,  317,  291,  317,
+      317,  317,  317,  317,  317,  317,  317,  317,    0,    0,
+      299,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+        0,    0,    0,    0,    0,    0,    0,    0,  317,  317,
+      317,  229,  317,  317,  317,  317,  317,  317,  317,  317,
+      317,  317,  317,  317,  317,  317,  317,  317,  317,  317,
+      262,  317,  317,  317,  317,  317,  317,  317,  317,  317,
+
+      317,  317,  317,  317,  317,  317,  317,    8,    0,    5,
+        0,  306,  306,  306,    0,  306,    0,   12,   14,    7,
+       11,    0,  302,    0,    0,    0,  307,    0,    0,    0,
+        0,    0,    0,    0,    0,    0,    9,   16,   12,   10,
+        0,    4,    0,    0,    0,    0,   15,    0,  315,    0,
+      314,  312,  313,  305,    0,    0,  317,  305,  309,  308,
+      305,    0,    0,  305,  317,  317,  317,  317,  317,  317,
+      317,  317,  317,  317,  317,  317,  317,  317,  317,  317,
+      317,  317,  317,  317,  317,  317,  231,  317,  317,  317,
+      317,  317,  317,  317,  317,  317,   62,  317,  317,  317,
+
+      317,  317,  317,  317,  317,  317,  317,  317,  317,   77,
+      317,  317,  317,  317,  317,  317,  317,  317,  317,  317,
+      317,  317,  317,  317,  317,  317,  317,  317,  317,  317,
+      317,  317,  317,  317,  317,  118,  119,  317,  317,  317,
+      317,  317,  317,  317,  317,  317,  317,  317,  317,  317,
+      317,  317,  260,  261,  317,  317,  317,  317,  317,  317,
+      317,  317,  317,  317,  317,  317,  317,  317,  317,  317,
+      317,  317,  317,  317,  317,  317,  317,  317,  317,  317,
+      317,  277,  317,  317,  317,  317,  317,  317,  317,  317,
+      317,  283,  317,  317,  317,  317,  317,  317,  317,  317,
+
+      317,  317,  317,  317,  317,  317,  317,  317,  215,  295,
+      317,  217,  296,  317,    0,  298,    0,    0,    0,    0,
+        0,    0,    0,  119,    0,    0,    0,    0,    0,    0,
+        0,    0,    0,  215,  317,  317,  317,  317,  317,  317,
+      317,  317,  317,  317,  317,  317,  317,  317,  260,  317,
+      317,  317,  317,  317,  317,  317,  317,  317,  317,  317,
+        0,    0,    0,    0,    0,  306,  306,    0,    0,  306,
         0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
-        0,    0,    0,    0,    0,    0,  291,  309,  309,  223,
-      309,  309,  309,  309,  309,  309,  309,  309,  309,  309,
-      309,  309,  309,  309,  309,  309,  309,  309,  309,  256,
-      309,  309,  309,  309,  309,  309,  309,  309,  309,  309,
-
-      309,  309,  309,  309,  309,    8,    0,    5,    0,  298,
-      298,  298,    0,  298,    0,   12,   14,    7,   11,    0,
-        0,    0,    0,    0,    0,    0,    0,    0,    9,   16,
-       12,   10,    0,    4,    0,    0,    0,    0,    0,    0,
-      294,    0,    0,  299,   15,    0,  307,    0,  306,  304,
-      304,  305,  297,    0,    0,  309,  297,  301,  300,  297,
-        0,    0,  297,  309,  309,  309,  309,  309,  309,  309,
-      309,  309,  309,  309,  309,  309,  309,  309,  309,  309,
-      309,  309,  309,  309,  225,  309,  309,  309,  309,  309,
-      309,  309,  309,  309,   60,  309,  309,  309,  309,  309,
-
-      309,  309,  309,  309,  309,  309,  309,   75,  309,  309,
-      309,  309,  309,  309,  309,  309,  309,  309,  309,  309,
-      309,  309,  309,  309,  309,  309,  309,  309,  309,  309,
-      309,  113,  114,  309,  309,  309,  309,  309,  309,  309,
-      309,  309,  309,  309,  309,  309,  309,  254,  255,  309,
-      309,  309,  309,  309,  309,  309,  309,  309,  309,  309,
-      309,  309,  309,  309,  309,  309,  309,  309,  309,  309,
-      309,  309,  309,  309,  309,  309,  271,  309,  309,  309,
-      309,  309,  309,  309,  309,  309,  277,  309,  309,  309,
-      309,  309,  309,  309,  309,  309,  309,  309,  309,  309,
-
-      309,  309,  209,  287,  309,  211,  288,  309,    0,    0,
-        0,    0,    0,    0,    0,  114,    0,    0,    0,    0,
-        0,    0,    0,    0,    0,  209,    0,  290,  309,  309,
-      309,  309,  309,  309,  309,  309,  309,  309,  309,  309,
-      309,  309,  309,  309,  254,  309,  309,  309,  309,  309,
-      309,  309,  309,  309,  309,  309,    0,    0,    0,    0,
-        0,  298,  298,    0,    0,  298,    0,    0,    0,    0,
-        0,    0,    0,    0,    0,    0,    0,    6,    0,    0,
-        0,    0,    0,    0,    0,    0,  297,  300,    0,  297,
-      309,  309,  309,  309,  309,  214,  309,  309,  309,  309,
-
-      309,  309,  309,  218,  309,  309,  309,  309,  309,  309,
-      309,  309,   53,  309,  309,  309,  309,   57,  309,  309,
-      309,  309,  309,  309,  309,  309,  309,  233,  309,  309,
-      309,   70,  309,  309,  309,   74,  309,  309,  309,   77,
-      309,  309,  309,  309,  309,  309,  309,  309,  309,  309,
-       93,  309,  309,  309,  309,  309,  309,  309,  242,  309,
-      243,  309,  309,  309,  309,  309,  309,  309,  309,  309,
-      309,  309,  309,  309,  309,  309,  309,  309,  309,  309,
-      309,  309,  309,  309,  309,  309,  309,  309,  309,  309,
-      309,  147,  309,  252,  309,  309,  309,  309,  309,  309,
-
-      309,  309,  309,  309,  309,  309,  309,  309,  309,  309,
-      309,  309,  309,  309,  309,  309,  309,  309,  309,  309,
-      309,  309,  309,  309,  309,  309,  309,  309,  309,  309,
-      309,  309,  184,  309,  309,  309,  309,  309,  309,  309,
-      196,  309,  278,  309,  309,  309,  309,  280,  206,  309,
-      309,  309,  309,  309,  212,    0,    0,    0,    0,    0,
-        0,    0,    0,    0,    0,    0,    0,  184,    0,    0,
-        0,  309,  309,   53,  309,   70,  309,  309,  309,  309,
-      309,  309,  309,  309,  184,  309,  309,  280,  295,    0,
-      298,   17,    0,    0,    0,    0,    0,    0,    0,    0,
-
-        0,    0,    0,    0,    0,    0,    0,    0,  296,   36,
-      289,   37,  309,  309,  215,  309,  309,  216,  309,  309,
-      309,  309,  309,  309,  221,  309,   45,  309,   49,  309,
-      309,  309,  309,   55,  309,  309,  309,  309,  231,   58,
-      309,   61,  309,  309,  232,  309,  309,  309,  309,  309,
-      309,   72,  309,  309,  235,  309,   79,  236,  309,  309,
-       81,  309,  309,   90,  309,  164,  309,  309,  309,  309,
-       97,  240,  309,  107,  309,  309,  309,  309,  309,  309,
-      309,  309,  309,  309,  309,  309,  309,  309,  309,  309,
-      309,  309,  309,  309,  249,  309,  309,  309,  309,  309,
-
-      309,  309,  309,  309,  309,  309,  309,  309,  250,  309,
-      227,  309,  309,  309,  309,  309,  309,  309,  309,  309,
-      309,  309,  309,  309,  309,  309,  309,  263,  309,  309,
-      309,  309,  309,  309,  309,  267,  309,  309,  309,  309,
-      309,  309,  309,  309,  269,  270,  178,  309,  309,  309,
-      309,  309,  309,  275,  309,  309,  187,  309,  193,  309,
-      309,  309,  199,  309,  309,  309,  309,  285,  207,  309,
-      309,  210,   37,   45,    0,    0,    0,  107,    0,    0,
-        0,    0,    0,    0,  187,    0,  207,  309,   49,  309,
-      309,  309,   97,  309,  309,  309,  309,    0,    0,    0,
-
-        0,    0,    0,    0,    0,    0,    0,    0,   21,    0,
-        0,    0,    0,  309,  309,  309,  309,  309,  217,  309,
-       43,  220,  309,  222,  309,  309,  309,  309,   50,  309,
-      309,  309,  309,  309,   56,  309,  309,  309,  309,   63,
-      309,   66,   67,  234,  309,   69,  309,  309,  309,   80,
-      237,  309,  309,  309,  309,  309,  309,  238,  309,  309,
-      309,  309,  309,  309,  309,  309,  309,  309,  309,  309,
-      106,  108,  309,  309,  115,  309,  309,  309,  309,  309,
-      309,  309,  309,  309,  309,  309,  309,  309,  246,  309,
-      247,  309,  309,  309,  309,  309,  309,  309,  309,  309,
-
-      309,  309,  309,  309,  309,  309,  253,  148,  309,  309,
-      309,  309,  309,  309,  309,  309,  309,  309,  262,  261,
-      266,  163,  309,  309,  309,  309,  309,  309,  309,  309,
-      309,  309,  309,  268,  309,  173,  309,  309,  309,  309,
-      309,  309,  309,  309,  309,  273,  274,  309,  276,  186,
-      309,  189,  309,  309,  309,  309,  309,  309,  309,  309,
-      309,  309,  286,    0,   63,    0,    0,  108,    0,    0,
-        0,    0,    0,    0,  309,  189,  309,   30,   22,    0,
-        0,    0,    0,    0,    0,    0,   18,    0,    0,    0,
-       28,    0,  309,  309,  309,  309,  309,  309,  309,  309,
-
-      309,   48,  309,  309,  309,  309,  228,  309,  230,  309,
-      309,  309,   65,  309,   71,  309,  309,  309,  309,  309,
-      309,  309,  309,  309,   89,  309,  309,  309,   95,  309,
-      309,  309,  309,  309,  309,  309,  309,  309,  110,  309,
-      309,  117,  309,  309,  309,  309,  309,  309,  309,  309,
-      126,  309,  309,  309,  309,  309,  132,  309,  309,  309,
-      309,  309,  309,  309,  143,  309,  309,  309,  309,  309,
-      149,  309,  150,  309,  309,  309,  309,  309,  162,  309,
-      264,  309,  265,  309,  309,  309,  309,  309,  309,  309,
-      309,  309,  309,  309,  309,  309,  309,  309,  309,  309,
-
-      309,  309,  309,  309,  309,  309,  309,  309,  309,  309,
-      309,  309,  309,  309,  309,    0,    0,    0,    0,    0,
-        0,    0,    0,    0,  309,  309,   20,    0,   27,    0,
-       31,    0,    0,    0,    0,   25,  293,  309,  309,  309,
-      309,   41,  309,  309,  309,  309,  309,  309,  309,  309,
-      309,   59,  309,  309,  309,  309,  309,  309,  309,  309,
-      309,  309,  309,   88,  309,  309,   94,  309,  309,  309,
-      309,  309,  309,  309,  309,  309,  111,  309,  309,  309,
-      309,  309,  309,  309,  309,  122,  309,  309,  129,  130,
-      131,  309,  309,  309,  309,  309,  309,  139,  309,  309,
-
-      146,  251,  309,  309,  309,  309,  309,  309,  309,  309,
-      309,  309,  309,  309,  161,  309,  165,  309,  309,  167,
-      309,  309,  309,  171,  309,  309,  309,  309,  175,  309,
-      180,  309,  272,  309,  309,  309,  309,  309,  309,  309,
-      194,   87,  309,  198,  309,  309,  309,  279,  281,  309,
-        0,    0,    0,    0,  171,    0,    0,  180,    0,  194,
-       29,   24,   32,    0,   26,   19,  309,   38,  309,   40,
-      309,   44,  309,   46,  309,  309,  309,   34,  309,  309,
-       64,  309,  309,  309,   78,  309,   85,   86,  309,   83,
-       91,   92,  309,  309,  309,  309,  100,  309,  309,  309,
-
-      309,  309,  309,  309,  309,  309,  309,  309,  125,  309,
-      309,  309,  309,  309,  309,  309,  309,  309,  142,  309,
-      309,  309,  309,  309,  309,  309,  309,  309,  309,  309,
-      309,  309,  309,  309,  309,  309,  309,  309,  309,  309,
-      309,  309,   35,  172,  309,  309,  309,  309,  309,  309,
-      183,  185,  188,  309,  192,  309,  197,  201,  205,  309,
-      309,    0,    0,   83,    0,  172,    0,    0,    0,  213,
-      309,  309,   47,   33,   51,  309,  309,   62,   68,  309,
-      309,   82,  309,   96,  239,   98,  309,  309,  309,  309,
-      309,  309,  116,  118,  309,  309,  309,  309,  309,  309,
-
-      309,  309,  133,  309,  309,  309,  309,  309,  309,  309,
-      309,  309,  257,  309,  309,  309,  309,  309,  309,  309,
-      309,  309,  309,  309,  309,  226,  309,  168,  169,  309,
-      174,  309,  176,  179,  309,  182,  309,  309,  309,  309,
-      208,    0,   82,  169,  176,    0,   23,  309,  309,  309,
-       54,  309,  309,  309,  309,   99,  309,  309,  309,  309,
-      309,  119,  120,  124,  121,  309,  309,  309,  128,  134,
-      309,  141,  138,  309,  309,  145,  309,  258,  309,  309,
-      309,  309,  309,  309,  309,  309,  309,  159,  309,  260,
-      309,  170,  309,  181,  190,  309,  309,  309,  204,    0,
-
-      204,  309,   42,  309,  309,   73,  309,   84,  309,  309,
-      309,  109,  309,  309,  309,  127,  309,  309,  144,  309,
-      309,  151,  152,  153,  309,  155,  309,  309,  309,  309,
-      309,  309,  309,  309,  309,  203,    0,  309,  309,  177,
-       76,  101,  103,  105,  309,  309,  123,  309,  140,  248,
-      259,  309,  309,  309,  309,  160,  309,  309,  309,  309,
-      309,  177,  309,   52,  309,  309,  309,  309,  137,  309,
-      156,  157,  309,  166,  135,  309,  309,  202,   39,  309,
-      309,  112,  136,  309,  309,  309,  195,  309,  309,  309,
-      309,  191,  309,  309,  309,  309,  102,  104,  309,  309,
-
-      309,  158,  309,  309,  154,    0
+        0,    0,    0,    0,    0,    6,    0,    0,    0,    0,
+        0,  305,  308,    0,  305,  317,  317,  317,  317,  317,
+
+      317,  220,  317,  317,  317,  317,  317,  317,  317,  224,
+      317,  317,  317,  317,  317,  317,  317,  317,   55,  317,
+      317,  317,  317,   59,  317,  317,  317,  317,  317,  317,
+      317,  317,  317,  239,  317,  317,  317,   72,  317,  317,
+      317,   76,  317,  317,  317,   79,  317,  317,  317,  317,
+      317,  317,  317,  317,  317,  317,  317,   97,  317,  317,
+      317,  317,  317,  317,  317,  317,  248,  317,  249,  317,
+      122,  317,  317,  317,  317,  317,  317,  317,  317,  317,
+      317,  317,  317,  317,  317,  317,  317,  317,  317,  317,
+      317,  317,  317,  317,  317,  317,  317,  317,  317,  317,
+
+      153,  317,  258,  317,  317,  317,  317,  317,  317,  317,
+      317,  317,  317,  317,  317,  317,  317,  317,  317,  317,
+      317,  317,  317,  317,  317,  317,  317,  317,  317,  317,
+      317,  317,  317,  317,  317,  317,  317,  317,  317,  317,
+      317,  317,  190,  317,  317,  317,  317,  317,  317,  317,
+      202,  317,  285,  317,  317,  317,  317,  287,  212,  317,
+      317,  317,  317,  317,  317,  218,    0,    0,    0,    0,
+        0,    0,    0,    0,    0,    0,    0,    0,  190,    0,
+        0,    0,  317,  317,   55,  317,   72,  317,  317,  317,
+      317,  317,  317,  317,  190,  317,  317,  287,  303,    0,
+
+      306,    0,  304,   17,    0,    0,    0,    0,    0,    0,
+        0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+       37,  297,  317,   39,  317,  317,  221,  317,  317,  222,
+      317,  317,  317,  317,  317,  317,  227,  317,   47,  317,
+       51,  317,  317,  317,  317,   57,  317,  317,  317,  317,
+      237,   60,  317,   63,  317,  317,  238,  317,  317,  317,
+      317,  317,  317,   74,  317,  317,  241,  317,  317,   82,
+      242,  317,  317,   84,  317,  317,   93,  317,  317,  170,
+      317,  317,  317,  317,  101,  246,  317,  111,  317,  317,
+      317,  317,  317,  317,  317,  317,  317,  317,  317,  317,
+
+      317,  317,  317,  317,  317,  317,  317,  317,  317,  255,
+      317,  317,  317,  317,  317,  317,  317,  317,  317,  317,
+      317,  317,  317,  256,  317,  233,  317,  317,  317,  317,
+      317,  317,  317,  317,  317,  317,  317,  317,  317,  317,
+      317,  317,  269,  317,  317,  317,  317,  317,  317,  317,
+      317,  273,  317,  317,  317,  317,  317,  317,  317,  317,
+      275,  276,  184,  317,  317,  317,  317,  317,  317,  281,
+      317,  317,  193,  317,  199,  317,  317,  317,  205,  317,
+      317,  317,  317,  292,  213,  317,  317,  317,  216,   39,
+       47,    0,    0,    0,  111,    0,    0,    0,    0,    0,
+
+        0,  193,    0,  213,  317,   51,  317,  317,  317,  101,
+      317,  317,  317,  317,    0,    0,    0,    0,    0,    0,
+        0,    0,    0,    0,    0,    0,    0,   21,    0,    0,
+        0,  317,  317,  317,  317,  317,  317,  223,  317,   45,
+      226,  317,  228,  317,  317,  317,  317,   52,  317,  317,
+      317,  317,  317,   58,  317,  317,  317,  317,   65,  317,
+       68,   69,  240,  317,   71,  317,  317,  317,  317,   83,
+      243,  317,  317,  317,  317,  317,  317,  244,  317,  317,
+      317,  317,  317,  317,  317,  317,  317,  317,  317,  317,
+      317,  110,  112,  113,  317,  317,  120,  317,  317,  317,
+
+      317,  317,  317,  317,  317,  317,  317,  317,  317,  317,
+      252,  317,  253,  317,  317,  317,  317,  317,  317,  317,
+      317,  317,  317,  317,  317,  317,  317,  317,  259,  154,
+      317,  317,  317,  317,  317,  317,  317,  317,  317,  317,
+      268,  267,  272,  169,  317,  317,  317,  317,  317,  317,
+      317,  317,  317,  317,  317,  317,  274,  317,  179,  317,
+      317,  317,  317,  317,  317,  317,  317,  317,  279,  280,
+      317,  282,  192,  317,  195,  317,  317,  317,  317,  317,
+      317,  317,  317,  317,  317,  317,  294,    0,   65,    0,
+        0,  113,    0,    0,    0,    0,    0,    0,  317,  195,
+
+      317,    0,   31,   22,    0,    0,    0,    0,    0,    0,
+        0,    0,   18,    0,    0,    0,   29,  317,  317,  317,
+      317,  317,  317,  317,  317,  317,  317,   50,  317,  317,
+      317,  317,  234,  317,  236,  317,  317,  317,   67,  317,
+       73,  317,  317,  317,  317,  317,  317,  317,  317,  317,
+      317,   92,  317,  317,  317,  317,   99,  317,  317,  317,
+      317,  317,  317,  317,  317,  317,  115,  317,  317,  123,
+      317,  317,  317,  317,  317,  317,  317,  317,  132,  317,
+      317,  317,  317,  317,  138,  317,  317,  317,  317,  317,
+      317,  317,  149,  317,  317,  317,  317,  317,  155,  317,
+
+      156,  317,  317,  317,  317,  317,  168,  317,  317,  270,
+      317,  271,  317,  317,  317,  317,  317,  317,  317,  317,
+      317,  317,  317,  317,  317,  317,  317,  317,  317,  317,
+      317,  317,  317,  317,  317,  317,  317,  317,  317,  317,
+      317,  317,  317,  317,  317,    0,    0,    0,    0,    0,
+        0,    0,    0,    0,  317,  317,  301,   20,    0,   28,
+        0,    0,   32,    0,    0,    0,    0,   26,  317,  317,
+      317,  317,  317,   43,  317,  317,  317,  317,  317,  317,
+      317,  317,  317,   61,  317,  317,  317,  317,  317,  317,
+       80,  317,  317,  317,  317,  317,   91,  317,  317,  317,
+
+       98,  317,  317,  317,  317,  317,  317,  317,  317,  317,
+      116,  317,  317,  317,  317,  317,  317,  317,  317,  128,
+      317,  317,  135,  136,  137,  317,  317,  317,  317,  317,
+      317,  145,  317,  317,  152,  257,  317,  317,  317,  317,
+      317,  317,  317,  317,  317,  317,  317,  317,  167,  317,
+      317,  171,  317,  317,  173,  317,  317,  317,  177,  317,
+      317,  317,  317,  181,  317,  186,  317,  278,  317,  317,
+      317,  317,  317,  317,  317,  200,   90,  317,  204,  317,
+      317,  317,  286,  288,  293,  317,    0,    0,    0,    0,
+      177,    0,    0,  186,    0,  200,   30,    0,   25,   33,
+
+        0,   27,   19,  317,  317,   40,  317,   42,  317,   46,
+      317,   48,  317,  317,  317,   35,  317,  317,   66,  317,
+      317,  317,   81,  317,   88,   89,  317,   86,  317,   95,
+       96,  317,  317,  317,  317,  104,  317,  317,  317,  317,
+      317,  317,  317,  317,  317,  317,  317,  131,  317,  317,
+      317,  317,  317,  317,  317,  317,  317,  148,  317,  317,
+      317,  317,  317,  317,  317,  317,  317,  317,  317,  317,
+      317,  317,  317,  317,  317,  317,  317,  317,  317,  317,
+      317,  317,   36,  178,  317,  317,  317,  317,  317,  317,
+      189,  191,  194,  317,  198,  317,  203,  207,  211,  317,
+
+      317,    0,    0,   86,    0,  178,    0,    0,    0,    0,
+      317,  219,  317,  317,   49,   34,   53,  317,  317,   64,
+       70,  317,  317,   85,  317,   94,  100,  245,  102,  317,
+      317,  317,  317,  317,  317,  121,  124,  317,  317,  317,
+      317,  317,  317,  317,  317,  139,  317,  317,  317,  317,
+      317,  317,  317,  317,  317,  263,  317,  317,  317,  317,
+      317,  317,  317,  317,  317,  317,  317,  317,  317,  232,
+      317,  174,  175,  317,  180,  317,  182,  185,  317,  188,
+      317,  317,  317,  317,  214,    0,   85,  175,  182,    0,
+       23,   24,   38,  317,  317,  317,   56,  317,  317,  317,
+
+      317,  103,  317,  317,  317,  317,  317,  125,  126,  130,
+      127,  317,  317,  317,  134,  140,  317,  147,  144,  317,
+      317,  151,  317,  264,  317,  317,  317,  317,  317,  317,
+      317,  317,  317,  165,  317,  266,  284,  317,  176,  317,
+      187,  196,  317,  317,  317,  210,    0,  210,  317,   44,
+      317,  317,   75,  317,   87,  317,  317,  317,  114,  317,
+      317,  317,  133,  317,  317,  150,  317,  317,  157,  158,
+      159,  317,  161,  317,  317,  317,  317,  317,  317,  317,
+      317,  317,  209,    0,  317,  317,  183,   78,  105,  107,
+      109,  317,  317,  129,  317,  146,  254,  265,  317,  317,
+
+      317,  317,  166,  317,  317,  317,  317,  317,  183,  317,
+       54,  317,  317,  317,  317,  143,  317,  162,  163,  317,
+      172,  141,  317,  317,  208,   41,  317,  317,  117,  142,
+      317,  317,  317,  201,  317,  317,  317,  317,  197,  317,
+      317,  317,  317,  106,  108,  317,  317,  317,  164,  317,
+      317,  160,    0
     } ;
 
 static yyconst flex_int32_t yy_ec[256] =
@@ -608,14 +589,14 @@ static yyconst flex_int32_t yy_ec[256] =
         1,    5,    6,    7,    8,    1,    1,    9,   10,   11,
        12,   13,   14,    1,   15,   16,   17,   18,   18,   19,
        18,   18,   18,   18,   18,   18,   18,    1,    1,   20,
-       21,   22,    1,    1,   23,   24,   25,   26,   27,   28,
-       29,   30,   31,   32,   33,   34,   35,   36,   37,   38,
-       39,   40,   41,   42,   43,   44,   45,   46,   47,   48,
-       49,   50,   51,    1,   52,   53,   54,   55,   56,   57,
-
-       58,   59,   60,   61,   62,   63,   64,   65,   66,   67,
-       68,   69,   70,   71,   72,   73,   74,   75,   76,   77,
-       78,   79,    1,   80,    1,   81,    1,    1,    1,    1,
+       21,   22,    1,    1,   28,   29,   30,   31,   32,   33,
+       34,   35,   36,   37,   38,   39,   40,   41,   42,   43,
+       44,   45,   46,   47,   48,   49,   50,   51,   52,   53,
+       23,   24,   25,    1,   26,   27,   28,   29,   30,   31,
+
+       32,   33,   34,   35,   36,   37,   38,   39,   40,   41,
+       42,   43,   44,   45,   46,   47,   48,   49,   50,   51,
+       52,   53,    1,   54,    1,   55,    1,    1,    1,    1,
         1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
         1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
         1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
@@ -632,1361 +613,966 @@ static yyconst flex_int32_t yy_ec[256] =
         1,    1,    1,    1,    1
     } ;
 
-static yyconst flex_int32_t yy_meta[83] =
+static yyconst flex_int32_t yy_meta[57] =
     {   0,
         1,    1,    2,    1,    3,    1,    4,    1,    1,    5,
         1,    1,    1,    1,    6,    7,    7,    7,    7,    1,
-        6,    1,    7,    7,    7,    7,    7,    7,    7,    7,
+        6,    1,    1,    8,    9,    6,    1,    7,    7,    7,
         7,    7,    7,    7,    7,    7,    7,    7,    7,    7,
-        7,    7,    7,    7,    7,    7,    7,    7,    1,    8,
-        9,    6,    1,    7,    7,    7,    7,    7,    7,    7,
         7,    7,    7,    7,    7,    7,    7,    7,    7,    7,
-        7,    7,    7,    7,    7,    7,    7,    7,    7,    1,
-        1,    1
+        7,    7,    7,    1,    1,    1
     } ;
 
-static yyconst flex_int16_t yy_base[1825] =
+static yyconst flex_int16_t yy_base[1872] =
     {   0,
-        0,    0,   82,    0,  164,    0,  246,    0,  327,  331,
-      332,  333,  772, 4122,  342, 4122, 4122,    0,  746,  332,
-      334,  392,  349,  343,  392,  450,  425,  390,  470,  486,
-      471,  495,  312,  327,  546,  496,  390,  590,  598,  313,
-      600,  645,  651,  480,  395,  532,    0,  705, 4122, 4122,
-     4122,  321,  325,  333,  370,  393,  406,  408,  398,  396,
-      413,  551,  463,  468,  526,  537,  367,  612,  541,  656,
-      552,  664,  705,  526,  554,  659,  558,  712,  717,  582,
-      709,  720,  707,  755,  750,  764,  731, 4122,  484,  637,
-      729,  697,  724,  668,  787,  792,  807,  687,  342,  676,
-
-      773,  772,  787,  791,  583,  633,  805,  649,  810,  811,
-      799,  724,  777,  810,  808,  313,  587,  638, 4122, 4122,
-      852,  640,  635,    0,  811,  820,  371,  882,    0,  628,
-      603,  858,  872,    0,  874,  888,  575,  932,  833,  890,
-      896,  858,  924,  824,  922,  837,  858,  861,  927,    0,
-      883,  903,  888,  933,  927,    0,  918,  922,    0,  943,
-      934,  933,  936,  950,  947,  935,  973,  943,  993,  945,
-      987,  972,  979,  981,  999, 1002,  984, 1005,  995, 1007,
-     1037, 1007, 1004,  989, 1003, 1045,    0, 1015, 1005,    0,
-     1016,    0, 1040, 1047, 1048, 1016, 1030, 1053, 1055, 1049,
-
-     1057, 1071, 1076, 1078, 1061, 1078, 1091, 1066, 1061, 1069,
-     1108, 1104, 1097, 1104, 1118, 1115, 1105, 1127, 1124, 1119,
-     1131, 1156, 1135, 1120, 1146, 1136, 1132, 1144, 1151, 1167,
-     1140, 1183, 1164,    0,    0, 1176,    0, 1174, 1185, 1187,
-     1171, 1187, 1173, 1175, 1195,  536, 4122, 1190, 1197, 1193,
-     1183, 1204, 1182, 1201, 1193, 1199, 1221, 1225, 1231, 1207,
-     1212, 1240, 1233, 1241,  501, 1250, 4122, 1240, 1247, 1250,
-     1240, 1233, 1249, 1254, 1254, 1245, 1247, 1255, 1245, 1265,
-     1268, 1251, 1275, 1272, 1269, 1274, 1291, 1274, 1293,    0,
-     1284, 1301, 1286, 1302, 1297, 1296, 1313, 1289, 1315, 1304,
-
-     1305, 1308, 1310, 1302, 1318, 4122,  498, 4122,  495, 1335,
-     1367, 1360, 1377, 1370, 1384, 4122, 4122, 4122, 4122, 1351,
-     1357, 1343, 1372, 1369, 1364, 1365, 1376, 1372, 4122, 1368,
-     1375, 4122, 1370, 4122, 1386, 1371, 1376, 1374,  491, 1400,
-     4122,  447,  322, 4122, 4122,  488, 4122,  482,    0, 4122,
-     4122, 4122, 1435, 1408,  625,  736,  842, 1393,    0, 1438,
-     1445,  886,  903, 1410, 1416, 1415, 1415, 1427, 1429, 1434,
-     1442, 1442, 1445, 1437, 1428, 1446, 1433, 1434, 1438, 1454,
-     1440, 1441, 1447, 1458,    0, 1462, 1444, 1468, 1444, 1452,
-     1461, 1468, 1459, 1474,    0, 1477, 1480, 1497, 1486, 1486,
-
-     1487, 1496, 1497, 1491, 1492, 1511, 1500,    0, 1502, 1504,
-     1499, 1517, 1501, 1522, 1522, 1518, 1521, 1522, 1526, 1527,
-     1522, 1527, 1545, 1533, 1546, 1553, 1555, 1563, 1549, 1565,
-     1566,    0,    0, 1562, 1604, 1567, 1582, 1573, 1576, 1658,
-     1579, 1566, 1572, 1585, 1574, 1592, 1590, 1603,    0,  470,
-     1623, 1627, 1633, 1614, 1615, 1618, 1637, 1638, 1641, 1638,
-     1631, 1664, 1653, 1682, 1654, 1668, 1666, 1683, 1680, 1693,
-     1692, 1679, 1687, 1697, 1693, 1698,    0, 1706, 1710, 1697,
-     1711, 1716, 1710, 1723, 1707, 1717,    0, 1728, 1720, 1718,
-     1715, 1732, 1714, 1728, 1738, 1732, 1746, 1743, 1745, 1736,
-
-     1745, 1739,    0,    0, 1742,    0,    0, 1748, 1755, 1750,
-     1754, 1768, 1768, 1771, 1775, 4122, 1773, 1766, 1781, 1773,
-     1777, 1786, 1780, 1780, 1776, 4122,  386, 4122, 1778, 1784,
-     1787, 1801, 1804, 1803, 1789, 1790, 1805, 1805, 1811, 1812,
-     1813, 1805, 1821, 1810,    0, 1822, 1817, 1832, 1824, 1833,
-     1841, 1841, 1846, 1834, 1846, 1833,  383,  323,  369,  360,
-      905, 1013, 1862, 1878, 1142, 1342, 1853, 1841, 1855, 1850,
-     1844, 1853, 1868, 1860, 1870, 1881, 1881, 4122, 1871, 1876,
-     1871, 1890, 1888, 1896,  425,  548, 1415, 4122, 1578, 1596,
-     1885, 1899, 1896, 1882, 1903,  365, 1898, 1887, 1895, 1886,
-
-     1909, 1893, 1908,    0, 1910, 1922, 1904, 1899, 1906, 1911,
-     1925, 1935, 1932, 1938, 1930, 1947, 1948,    0, 1939, 1952,
-     1933, 1955, 1943, 1957, 1949, 1959, 1945,    0, 1962, 1963,
-     1954, 1951, 1967, 1969, 1974,    0, 1957, 1958, 1971,    0,
-     1969, 1980, 1986, 1976, 1997, 1999, 1986, 1986, 1994, 1994,
-        0, 2001, 2008, 2002, 2006, 2015, 2006, 2005,    0, 2011,
-     2026, 2021, 2010, 2015, 2022, 2027, 2029, 2023, 2034, 2018,
-     2055, 2037, 2038, 2029, 2049, 2048, 2050, 2052, 2056, 2060,
-     2068, 2074, 2075, 2068, 2078, 2083, 2080, 2078, 2070, 2081,
-     2079,    0, 2084,    0, 2093, 2093, 2076, 2090, 2089, 2100,
-
-     2091, 2103, 2111, 2121, 2123, 2119, 2133, 2127, 2117, 2131,
-     2119, 2135, 2123, 2139, 2140, 2123, 2144, 2145, 2134, 2138,
-     2134, 2154, 2147, 2146, 2140, 2157, 2158, 2161, 2151, 2166,
-     2162, 2165, 2161, 2176, 2172, 2172, 2191, 2183, 2194, 2188,
-        0, 2192,    0, 2198, 2188, 2188, 2195, 2190,    0, 2197,
-     2193, 2210, 2200, 2208,    0, 2212, 2199, 2215, 2208, 2218,
-     2207, 2212, 2223, 2208, 2218, 2227, 2239, 4122, 2245, 2233,
-     2236, 2239, 2242,    0, 2247,    0, 2257, 2245, 2256, 2254,
-     2265, 2266, 2259, 2252,    0, 2258, 2262,    0, 4122, 2280,
-     2282, 4122, 2266, 2277, 2275, 2284, 2268, 2273, 2282, 2275,
-
-     2280, 2281, 2294, 2303, 2290, 2301, 2301, 2296, 4122,    0,
-        0,    0, 2313, 2305,    0, 2302, 2313,    0, 2322, 2308,
-     2322, 2310, 2312, 2328,    0, 2328, 2327, 2330, 2324, 2337,
-     2343, 2346, 2348,    0, 2338, 2333, 2338, 2338,    0,    0,
-     2351,    0, 2344, 2349,    0, 2352, 2367, 2354, 2351, 2371,
-     2361,    0, 2362, 2366,    0, 2382,    0,    0, 2368, 2384,
-     2405, 2373, 2389,    0, 2384,    0, 2396, 2372, 2403, 2404,
-     2441,    0, 2397,    0, 2408, 2413, 2415, 2413, 2429, 2409,
-     2415, 2435, 2423, 2421, 2432, 2443, 2450, 2429, 2456, 2447,
-     2462, 2455, 2469, 2452,    0, 2448, 2471, 2452, 2461, 2482,
-
-     2469, 2467, 2474, 2491, 2467, 2492, 2482, 2492,    0, 2482,
-        0, 2497, 2491, 2486, 2488, 2494, 2490, 2507, 2499, 2496,
-     2516, 2519, 2503, 2508, 2509, 2514, 2518, 2514, 2520, 2527,
-     2536, 2537, 2533, 2527, 2546, 2544, 2546, 2538, 2553, 2546,
-     2553, 2545, 2550, 2549,    0,    0, 2570, 2551, 2552, 2562,
-     2574, 2577, 2569,    0, 2579, 2571, 2583, 2582,    0, 2594,
-     2596, 2584,    0, 2599, 2601, 2601, 2586,    0,    0, 2611,
-     2598,    0, 4122, 4122, 2599, 2599, 2617, 4122, 2618, 2621,
-     2614, 2625, 2611, 2631, 4122, 2618, 4122, 2637,    0, 2616,
-     2637, 2619, 2636, 2651, 2637, 2645, 2658, 2656, 2644, 2660,
-
-     2660, 2665, 2664, 2665, 2673, 2660, 2672, 2680, 4122, 2673,
-     2679, 2672, 2687, 2669, 2685, 2680, 2676, 2686,    0, 2693,
-        0,    0, 2682,    0, 2685, 2686, 2689, 2707,    0, 2694,
-     2698, 2705, 2701, 2707,    0, 2719, 2714, 2712, 2723,    0,
-     2730,    0, 2727,    0, 2720,    0, 2726, 2741, 2722,    0,
-        0, 2729, 2731, 2746, 2727, 2726, 2736,    0, 2751, 2756,
-     2757, 2753, 2756, 2761, 2745, 2767, 2754, 2750, 2775, 2775,
-        0, 2775, 2767, 2777, 2771, 2774, 2775, 2777, 2778, 2779,
-     2798, 2797, 2787, 2794, 2803, 2805, 2794, 2793,    0, 2796,
-        0, 2802, 2800, 2801, 2802, 2803, 2803, 2822, 2823, 2819,
-
-     2827, 2834, 2826, 2823, 2833, 2845,    0,    0, 2843,  349,
-     2827, 2836, 2851, 2853, 2835, 2852, 2851, 2846,    0,    0,
-        0,    0, 2853, 2853, 2851, 2866, 2870, 2855, 2859, 2860,
-     2866, 2881, 2864,    0, 2871,    0, 2866, 2885, 2887, 2873,
-     2893, 2895, 2899, 2902, 2906,    0,    0, 2899,    0,    0,
-     2890, 2895, 2897, 2898, 2918, 2921, 2913, 2913, 2928, 2918,
-     2916, 2913,    0, 2919, 4122, 2922, 2915, 4122, 2922, 2942,
-     2930, 2926, 2946, 2949, 2926,    0, 2934, 4122, 4122, 2930,
-     2942, 2943, 2952, 2953, 2945, 2965, 4122, 2956, 2962, 2960,
-     4122,  294, 2971, 2982, 2963, 2983, 2970, 2975, 2986, 2977,
-
-     2989,    0, 2981, 2987, 2979, 2995,    0, 2992,    0, 2998,
-     2997, 2993,    0, 2989,    0, 2996, 2999, 3004, 3005, 3014,
-     3004, 3027, 3013, 3019,    0, 3029, 3022, 3033,    0, 3032,
-     3037, 3042, 3028, 3045, 3027, 3038, 3036, 3039,    0, 3042,
-     3048,    0, 3049, 3060, 3043, 3057, 3049, 3048, 3058, 3066,
-        0, 3065, 3063, 3070, 3078, 3075,    0, 3077, 3089, 3070,
-     3084, 3076, 3076, 3095,    0, 3094, 3092, 3099, 3103, 3100,
-        0, 3100,    0, 3098, 3113, 3103, 3138, 3100,    0, 3122,
-        0, 3114,    0, 3110, 3125, 3107, 3124, 3128, 3124, 3132,
-     3147, 3152, 3151, 3149, 3143, 3156, 3148, 3155, 3166, 3159,
-
-     3166, 3156, 3157, 3173, 3187, 3175, 3173, 3180, 3178, 3191,
-     3177, 3180, 3194, 3197, 3194, 3192, 3198, 3197, 3205, 3199,
-     3214, 3209, 3201, 3202, 3237, 3219, 4122, 3208, 4122, 3208,
-     4122, 3211, 3229, 3217, 3230, 4122, 4122, 3223, 3223, 3229,
-     3234,    0, 3235, 3236, 3236, 3247, 3254, 3249, 3260, 3261,
-     3251,    0, 3260, 3262, 3272, 3259, 3261, 3276, 3267, 3281,
-     3281, 3278, 3288,    0, 3289, 3279,    0, 3285, 3282, 3293,
-     3289, 3291, 3286, 3290, 3293, 3297, 3303, 3292, 3293, 3308,
-     3305, 3322, 3305, 3320, 3333, 3333, 3316, 3338,    0,    0,
-        0, 3315, 3328, 3325, 3340, 3326, 3343, 3348, 3333, 3355,
-
-        0,    0, 3347, 3360, 3348, 3362, 3349, 3357, 3349, 3370,
-     3361, 3376, 3357, 3371,    0, 3374,    0, 3367, 3376,    0,
-     3375, 3375, 3386,    0, 3387, 3396, 3383, 3385,    0, 3390,
-        0, 3391,    0, 3398, 3387, 3406, 3398, 3405, 3421, 3403,
-     3408,    0, 3401,    0, 3421, 3415, 3424,    0,    0, 3418,
-     3417, 3424, 3435, 3427, 4122, 3438, 3431, 4122, 3442,    0,
-     4122, 4122, 4122, 3430, 4122, 4122, 3437,    0, 3448,    0,
-     3445,    0, 3445,    0, 3457, 3449, 3447,    0, 3446, 3453,
-        0, 3455, 3463, 3469,    0, 3458,    0,    0, 3470,    0,
-        0,    0, 3473, 3465, 3480, 3485,    0, 3484, 3485, 3481,
-
-     3478, 3494, 3495, 3496, 3499, 3499, 3485, 3507,    0, 3493,
-     3507, 3504, 3494, 3515, 3520, 3519, 3505, 3526,    0, 3523,
-     3520, 3510, 3525, 3523, 3533, 3521, 3530, 3542, 3534, 3545,
-     3537, 3526, 3538, 3533, 3531, 3549, 3558, 3552, 3563, 3560,
-     3556, 3570,    0,    0, 3559, 3555, 3562, 3569, 3570, 3581,
-        0,    0,    0, 3575,    0, 3588,    0, 3569,    0, 3577,
-     3578, 3576, 3581, 4122, 3586, 4122, 3589, 3590, 3589,    0,
-     3606, 3609,    0,    0, 3591, 3598, 3605,    0,    0, 3600,
-     3604,    0, 3604,    0,    0,    0, 3605, 3625, 3627, 3611,
-     3631, 3609,    0,    0, 3631, 3618, 3630, 3632, 3646, 3634,
-
-     3645, 3646,    0, 3647, 3634, 3646, 3646, 3647, 3658, 3660,
-     3654, 3645,    0, 3662, 3657, 3653, 3673, 3665, 3662, 3662,
-     3667, 3675, 3683, 3688, 3672,    0, 3693,    0,    0, 3675,
-        0, 3697,    0,    0, 3681,    0, 3695, 3686, 3695, 3707,
-        0, 3702, 4122, 4122, 4122, 3693, 4122, 3699, 3695, 3691,
-        0, 3705, 3709, 3706, 3703,    0, 3720, 3721, 3729, 3715,
-     3717,    0,    0,    0,    0, 3724, 3724, 3738,    0,    0,
-     3739,    0,    0, 3734, 3745,    0, 3747,    0, 3752, 3738,
-     3749, 3740, 3754, 3744, 3759, 3762, 3763,    0, 3758,    0,
-     3772,    0, 3762,    0, 3773, 3758, 3773, 3760,    0, 3771,
-
-     4122, 3777,    0, 3774, 3780,    0, 3782,    0, 3791, 3792,
-     3779,    0, 3791, 3794, 3792,    0, 3784, 3798,    0, 3793,
-     3802,    0,    0,    0, 3797,    0, 3792, 3793, 3808, 3811,
-     3816, 3827, 3828, 3829, 3815,    0, 3823, 3823, 3834,    0,
-        0, 3836, 3840,    0, 3821, 3836,    0, 3846,    0,    0,
-        0, 3837, 3851, 3852, 3853,    0, 3854, 3855, 3848, 3845,
-     3848, 4122, 3854,    0, 3868, 3869, 3871, 3872,    0, 3859,
-        0,    0, 3878,    0,    0, 3869, 3871,    0,    0, 3872,
-     3878,    0,    0, 3881, 3881, 3884,    0, 3884, 3885, 3897,
-     3890,    0, 3893, 3896, 3907, 3898,    0,    0, 3899, 3900,
-
-     3907,    0, 3905, 3903,    0, 4122, 3974, 3983, 3992, 4001,
-     4005, 4012, 4021, 4024, 4033, 4042, 4051, 4060, 4069, 4078,
-     4085, 4094, 4103, 4112
+        0,    0,   54,  108,  164,    0,  220,    0,   57,   61,
+       65,   71, 2324, 2325,  101, 2325, 2325,    0, 2311,   97,
+       55,  276,  101, 2297,   82,  305,  310,   97,  318,   90,
+      315,   60,  321, 2279,   47,  342,  343,   99,  349,  357,
+     2272,  372,  385,  391,  400,  118,  373,    0, 2325, 2325,
+     2325,  348, 2278, 2279, 2285, 2265, 2275,  129, 2286, 2268,
+     2264, 2279,  113, 2265, 2268, 2276,  334,  362, 2279,  408,
+      420,  414,  428,  320, 2274,  294,  127,  430,  344, 2277,
+      426,  435,  390,  443,  449,  443,   71, 2325,  494,  498,
+     2283, 2280, 2293, 2278,  488,  490,  494, 2279,  455, 2278,
+
+      361,  401,  390,   28,  441,  451, 2254, 2252,  410, 2255,
+      414,  312,  444, 2253, 2252, 2257, 2238, 2278, 2325, 2325,
+      512, 2283, 2279,    0, 2252, 2251,  508,  519,    0, 2274,
+     2273,  501,  509,    0,  511,  520, 2267,    0, 2247,  518,
+      530, 2257, 2325,  504,  512, 2234,  347, 2231,  464, 2237,
+      518,    0, 2237, 2249, 2231,  524,  515,    0, 2226, 2227,
+        0,  528, 2237, 2232, 2232,  526,  532, 2225,  517, 2230,
+      538, 2229,  532, 2225, 2223, 2223, 2236,  539, 2216, 2234,
+     2222, 2232,  548, 2227, 2222, 2205, 2217,  547,    0,  552,
+     2214,    0, 2220,    0,  545,  551,  561, 2214, 2206,  549,
+
+      542, 2218, 2205, 2217, 2220, 2219, 2199, 2213,  558, 2199,
+     2192, 2194,  568,  570, 2209,  451,  576, 2206, 2191, 2210,
+     2205, 2197, 2207,  576, 2206, 2185,  583, 2198, 2191, 2201,
+      573,  584, 2190,  590, 2185,    0,    0, 2191,    0, 2181,
+     2186, 2194, 2194, 2176, 2190, 2173, 2173, 2190, 2192,  609,
+     2325, 2182, 2187, 2181, 2166, 2184, 2159, 2176, 2166, 2166,
+     2175,  597, 2178, 2152, 2152, 2175, 2166, 2172, 2164,  598,
+     2169, 2170,  601, 2150, 2163, 2166, 2163,  590, 2154,  605,
+     2150, 2163,  618, 2138, 2160, 2155, 2140, 2147, 2137, 2151,
+        0, 2136, 2150, 2134, 2129,  522, 2137, 2134, 2149, 2123,
+
+     2147, 2134,  601,  610, 2134, 2124, 2135, 2325, 2145, 2325,
+     2144,  632,  637,  640,  648,  642,  661, 2325, 2325, 2325,
+     2325, 2143, 2325,  643, 2140,  646, 2325, 2135, 2133, 2112,
+     2130,  641, 2120,  637, 2125, 2118, 2325, 2112, 2117, 2325,
+     2110, 2325, 2124, 2107,  638, 2107, 2325, 2146, 2325, 2142,
+        0, 2325, 2325,  669,  675,  673,  677,  679, 2115,    0,
+      681,  688,  686,  690, 2116, 2114, 2113, 2108, 2104, 2109,
+     2102, 2105, 2111, 2109, 2109, 2099, 2088, 2104, 2089, 2088,
+     2089, 2103, 2086, 2085, 2088,  644,    0, 2101, 2080,  682,
+     2078, 2083, 2089, 2092, 2076, 2080,    0, 2079, 2075, 2087,
+
+     2072, 2070, 2069,  672, 2076, 2067, 2066,  682, 2072,    0,
+     2071, 2069, 2062, 2077, 2059, 2076, 2074, 2068, 2069,  679,
+     2070, 2054, 2068, 2059, 2057,  679, 2055, 2064, 2061, 2055,
+     2061, 2061, 2044, 2058, 2057,    0,    0, 2050, 2049,  700,
+     2050,  688, 2053, 2052,  723, 2051, 2035, 2037, 2048, 2032,
+     2046, 2037, 2030,    0, 2060, 2044, 2043,  678, 2027, 2024,
+     2023, 2039,  692, 2034, 2026,  709,  694, 2024,  708, 2020,
+     2030, 2016, 2030, 2025, 2032, 2027, 2010, 2015, 2021, 2014,
+     2015,    0, 2021,  692, 2009, 2017, 2018, 2010, 2020, 2000,
+     2007,    0, 2016, 2005, 2000, 1995, 2009, 1988, 2000, 2006,
+
+     1996, 2008, 2003, 2002,  701, 2005, 1996, 1984,    0,    0,
+     1983,    0,    0, 1986, 2003, 2325, 1988, 1980, 1980, 1992,
+     1989, 1990, 1989, 2325, 1983, 1974, 1986, 1975, 1977, 1983,
+     1975, 1972, 1965, 2325, 1965, 1968, 1968, 1980, 1979, 1974,
+     1958, 1957, 1969, 1967, 1969,  717, 1968, 1967, 1952, 1958,
+     1951, 1963, 1953, 1957, 1961, 1959, 1961, 1946, 1956, 1940,
+     1961,  719, 1960,  611,  746,  748,  753,  760,  758,  762,
+      730,  757,  761, 1956, 1941, 1949, 1941, 1933, 1933, 1945,
+     1940, 1929, 1935, 1942, 1939, 2325, 1927, 1930, 1923, 1939,
+     1933,  771, 2325,  773,  775, 1926, 1938, 1923, 1932, 1916,
+
+     1934, 1942, 1926, 1913, 1919, 1908, 1928, 1909, 1922,    0,
+     1921,  721, 1913, 1905, 1903, 1904, 1912, 1915,  752, 1912,
+     1897, 1912, 1911,    0, 1899, 1910, 1888, 1908, 1893, 1905,
+     1895, 1903, 1886,    0, 1901, 1900, 1889, 1884, 1897, 1896,
+     1899,    0, 1879, 1878, 1888, 1877, 1879, 1886, 1888, 1872,
+     1886, 1885, 1868, 1864, 1878, 1868, 1866,    0, 1871,  760,
+     1870, 1870, 1876, 1865, 1861, 1873,    0, 1863,  768, 1871,
+        0, 1857, 1859, 1864, 1867, 1866, 1856, 1864, 1846,  770,
+     1862, 1857, 1844, 1860, 1845, 1843, 1841, 1842, 1844, 1849,
+     1852, 1851, 1841, 1849,  771, 1848, 1843, 1833, 1841, 1837,
+
+        0, 1839,    0, 1846,  751, 1826, 1836, 1832, 1834, 1821,
+     1829, 1831, 1834, 1833, 1825, 1835, 1826, 1814, 1815, 1825,
+     1811,  765, 1812, 1824, 1823, 1802, 1821, 1820, 1806, 1808,
+     1802, 1820, 1811, 1807, 1798, 1813, 1811, 1812, 1799, 1808,
+     1800, 1799, 1789, 1784, 1768, 1760, 1773, 1762, 1760,  769,
+        0, 1753,    0, 1756, 1702, 1681, 1677,   22,    0,   50,
+       68,   91,  333,  370,  409,    0,  499,  547,  708,  719,
+      770,  764,  769,  779,  761,  769,  776,  784, 2325,  785,
+      774,  775,  776,  778,    0,  783,    0,  793,  781,  791,
+      789,  797,  791,  784,    0,  790,  794,    0, 2325,  816,
+
+      818,  813, 2325, 2325,  798,  808,  805,  814,  797,  812,
+      803,  811,  800,  803,  802,  811,  820,  807,  818,  818,
+        0,    0,  810,    0,  829,  819,    0,  814,  824,    0,
+      833,  819,  831,  819,  820,  836,    0,  835,  834,  837,
+      826,  838,  843,  846,  847,    0,  837,  831,  833,  833,
+        0,    0,  844,    0,  835,  836,    0,  839,  854,  841,
+      837,  856,  844,    0,  843,  846,    0,  862,  846,    0,
+        0,  849,  863,  866,  851,  867,    0,  871,  862,    0,
+      872,  849,  875,  872,  882,    0,  864,    0,  862,  877,
+      888,  875,  874,  890,  870,  877,  896,  883,  879,  887,
+
+      897,  902,  878,  903,  893,  903,  895,  908,  891,    0,
+      886,  909,  889,  895,  914,  901,  897,  904,  918,  894,
+      919,  909,  919,    0,  908,    0,  922,  914,  907,  908,
+      914,  910,  926,  918,  913,  933,  934,  918,  923,  919,
+      923,  926,  922,  927,  928,  935,  936,  945,  938,  929,
+      946,  944,  942,  934,  948,  941,  947,  938,  941,  939,
+        0,    0,  959,  942,  941,  949,  961,  962,  954,    0,
+      964,  951,  962,  960,    0,  972,  973,  961,    0,  975,
+      971,  971,  954,    0,    0,  960,  981,  965,    0, 2325,
+     2325,  965,  965,  983, 2325,  984,  986,  977,  986,  971,
+
+      991, 2325,  978, 2325,  988,    0,  976,  995,  977,  991,
+     1000,  983,  992, 1004, 1008, 1003,  990, 1004, 1002, 1007,
+      996, 1006, 1007, 1012,  999, 1011, 1019, 2325, 1012, 1017,
+     1009, 1008, 1005, 1017, 1012, 1008, 1017,    0, 1024,    0,
+        0, 1011,    0, 1014, 1013, 1016, 1034,    0, 1016, 1017,
+     1024, 1019, 1025,    0, 1036, 1028, 1024, 1035,    0, 1040,
+        0, 1037,    0, 1027,    0, 1033, 1048, 1029, 1046,    0,
+        0, 1037, 1038, 1053, 1034, 1031, 1039,    0, 1053, 1047,
+     1059, 1060, 1055, 1058, 1061, 1045, 1065, 1052, 1048, 1068,
+     1065,    0,    0, 1065, 1056, 1064, 1055, 1056, 1057, 1058,
+
+     1059, 1057, 1076, 1075, 1065, 1072, 1080, 1082, 1071, 1068,
+        0, 1069,    0, 1074, 1072, 1073, 1073, 1074, 1072, 1091,
+     1090, 1086, 1094, 1096, 1085, 1082, 1091, 1103,    0,    0,
+     1100, 1118, 1082, 1089, 1104, 1104, 1086, 1100, 1099, 1094,
+        0,    0,    0,    0, 1109, 1102, 1102, 1099, 1114, 1118,
+     1101, 1103, 1103, 1109, 1124, 1106,    0, 1113,    0, 1106,
+     1125, 1125, 1111, 1131, 1128, 1129, 1132, 1135,    0,    0,
+     1128,    0,    0, 1118, 1120, 1120, 1121, 1138, 1138, 1130,
+     1130, 1145, 1135, 1132, 1144, 1130,    0, 1137, 2325, 1138,
+     1129, 2325, 1135, 1155, 1143, 1138, 1158, 1159, 1136,    0,
+
+     1142, 1165, 2325, 2325, 1139, 1151, 1147, 1162, 1154, 1155,
+     1146, 1166, 2325, 1156, 1159, 1155, 2325, 1160, 1167, 1176,
+     1157, 1174, 1161, 1166, 1177, 1168, 1179,    0, 1171, 1177,
+     1167, 1181,    0, 1177,    0, 1183, 1182, 1177,    0, 1173,
+        0, 1178, 1181, 1184, 1181, 1186, 1195, 1180, 1200, 1186,
+     1191,    0, 1197, 1202, 1194, 1202,    0, 1199, 1204, 1207,
+     1193, 1207, 1189, 1200, 1198, 1201,    0, 1203, 1209,    0,
+     1210, 1219, 1200, 1213, 1205, 1204, 1213, 1221,    0, 1218,
+     1216, 1221, 1229, 1226,    0, 1223, 1232, 1213, 1226, 1218,
+     1217, 1233,    0, 1230, 1228, 1233, 1237, 1231,    0, 1231,
+
+        0, 1229, 1244, 1233, 1247, 1232,    0, 1251, 1247,    0,
+     1240,    0, 1236, 1251, 1232, 1249, 1250, 1243, 1247, 1259,
+     1262, 1263, 1260, 1251, 1262, 1254, 1259, 1270, 1260, 1267,
+     1257, 1258, 1274, 1277, 1276, 1275, 1279, 1272, 1283, 1269,
+     1270, 1284, 1285, 1273, 1283, 1281, 1282, 1279, 1287, 1281,
+     1295, 1290, 1282, 1283, 1300, 1299, 2325, 2325, 1286, 2325,
+     1292, 1287, 2325, 1288, 1306, 1291, 1304, 2325, 1303, 1298,
+     1295, 1302, 1304,    0, 1300, 1302, 1300, 1309, 1316, 1309,
+     1320, 1321, 1306,    0, 1313, 1315, 1325, 1311, 1313, 1328,
+        0, 1319, 1330, 1328, 1325, 1333,    0, 1338, 1335, 1322,
+
+        0, 1328, 1325, 1336, 1332, 1333, 1328, 1329, 1328, 1332,
+     1338, 1326, 1327, 1340, 1337, 1352, 1335, 1350, 1358, 1356,
+     1339, 1361,    0,    0,    0, 1337, 1350, 1347, 1362, 1345,
+     1360, 1365, 1348, 1370,    0,    0, 1359, 1372, 1360, 1374,
+     1361, 1368, 1360, 1378, 1365, 1380, 1361, 1374,    0, 1377,
+     1366,    0, 1369, 1375,    0, 1374, 1375, 1378,    0, 1379,
+     1388, 1374, 1376,    0, 1381,    0, 1382,    0, 1386, 1374,
+     1393, 1383, 1390, 1403, 1385, 1390,    0, 1383,    0, 1403,
+     1396, 1405,    0,    0,    0, 1396, 1391, 1398, 1409, 1400,
+     2325, 1411, 1402, 2325, 1413,    0, 2325, 1416, 2325, 2325,
+
+     1400, 2325, 2325, 1407, 1408,    0, 1419,    0, 1411,    0,
+     1409,    0, 1421, 1413, 1410,    0, 1409, 1416,    0, 1418,
+     1423, 1427,    0, 1416,    0,    0, 1426,    0, 1420,    0,
+        0, 1430, 1419, 1434, 1439,    0, 1438, 1439, 1434, 1431,
+     1444, 1441, 1442, 1445, 1444, 1430, 1450,    0, 1436, 1448,
+     1445, 1435, 1451, 1454, 1453, 1439, 1459,    0, 1456, 1453,
+     1443, 1455, 1451, 1461, 1447, 1456, 1465, 1457, 1468, 1460,
+     1449, 1460, 1455, 1450, 1464, 1473, 1474, 1468, 1478, 1475,
+     1469, 1483,    0,    0, 1470, 1466, 1473, 1475, 1474, 1485,
+        0,    0,    0, 1479,    0, 1491,    0, 1472,    0, 1480,
+
+     1481, 1476, 1479, 2325, 1484, 2325, 1485, 1486, 1496, 1483,
+     1483,    0, 1501, 1504,    0,    0, 1486, 1493, 1499,    0,
+        0, 1494, 1495,    0, 1491,    0,    0,    0,    0, 1492,
+     1512, 1513, 1497, 1515, 1493,    0,    0, 1513, 1500, 1512,
+     1509, 1521, 1509, 1520, 1520,    0, 1521, 1508, 1520, 1517,
+     1516, 1527, 1527, 1521, 1509,    0, 1526, 1521, 1517, 1537,
+     1528, 1525, 1522, 1523, 1531, 1539, 1543, 1527, 1527,    0,
+     1547,    0,    0, 1529,    0, 1549,    0,    0, 1533,    0,
+     1547, 1533, 1540, 1552,    0, 1547, 2325, 2325, 2325, 1537,
+     2325, 2325,    0, 1543, 1539, 1535,    0, 1546, 1548, 1545,
+
+     1539,    0, 1553, 1554, 1562, 1548, 1550,    0,    0,    0,
+        0, 1556, 1556, 1568,    0,    0, 1565,    0,    0, 1560,
+     1571,    0, 1572,    0, 1577, 1561, 1572, 1561, 1575, 1565,
+     1575, 1576, 1577,    0, 1572,    0,    0, 1585,    0, 1575,
+        0, 1586, 1571, 1583, 1568,    0, 1579, 2325, 1583,    0,
+     1580, 1583,    0, 1585,    0, 1594, 1595, 1582,    0, 1593,
+     1596, 1591,    0, 1579, 1593,    0, 1588, 1596,    0,    0,
+        0, 1591,    0, 1584, 1585, 1598, 1601, 1606, 1612, 1611,
+     1612, 1598,    0, 1605, 1605, 1616,    0,    0, 1618, 1619,
+        0, 1598, 1613,    0, 1621,    0,    0,    0, 1612, 1623,
+
+     1624, 1625,    0, 1626, 1627, 1619, 1616, 1616, 2325, 1618,
+        0, 1632, 1633, 1634, 1635,    0, 1620,    0,    0, 1639,
+        0,    0, 1628, 1630,    0,    0, 1631, 1632,    0,    0,
+     1633, 1633, 1636,    0, 1635, 1636, 1648, 1641,    0, 1641,
+     1642, 1653, 1642,    0,    0, 1643, 1641, 1648,    0, 1646,
+     1644,    0, 2325, 1689, 1698, 1707, 1716, 1725, 1729, 1736,
+     1739, 1748, 1757, 1766, 1775, 1784, 1793, 1800, 1809, 1818,
+     1827
     } ;
 
-static yyconst flex_int16_t yy_def[1825] =
+static yyconst flex_int16_t yy_def[1872] =
     {   0,
-     1806,    1, 1806,    3, 1806,    5, 1806,    7, 1807, 1807,
-     1808, 1808, 1806, 1806, 1806, 1806, 1806, 1809, 1810, 1806,
-     1811, 1812, 1806, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1813, 1806, 1806,
-     1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806,
-     1806, 1806, 1806, 1806, 1806, 1814, 1806, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811,   35, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1806, 1806, 1806,
-     1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806,
-
-     1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806,
-     1806, 1806, 1806, 1806, 1815, 1816, 1806, 1806, 1806, 1806,
-     1806, 1817, 1818, 1819, 1806, 1806, 1806, 1806, 1809, 1810,
-     1810, 1806, 1806, 1811, 1811, 1811, 1820, 1812, 1811, 1806,
-     1806, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1813, 1806, 1806, 1806, 1806,
-     1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806,
-     1806, 1806, 1806, 1806, 1821, 1806, 1806, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-
-     1811, 1811, 1811, 1811, 1811, 1806, 1822, 1806, 1823, 1806,
-     1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806,
-     1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806,
-     1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1815, 1815,
-     1806, 1816, 1824, 1806, 1806, 1817, 1806, 1818, 1819, 1806,
-     1806, 1806, 1806, 1806, 1806, 1811, 1811, 1806, 1811, 1806,
-     1806, 1806, 1806, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1806, 1806,
-     1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806,
-     1806, 1806, 1806, 1806, 1806, 1806, 1821, 1806, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1822, 1822, 1823, 1823,
-     1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806,
-     1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806,
-     1806, 1806, 1806, 1815, 1824, 1824, 1806, 1806, 1806, 1806,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1806, 1806, 1806, 1806, 1806,
-     1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806,
-     1806, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1806, 1806,
-     1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806,
-
-     1806, 1806, 1806, 1806, 1806, 1806, 1806, 1815, 1806, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806,
-     1806, 1806, 1806, 1806, 1806, 1806, 1806, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1806, 1806, 1806,
-
-     1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806,
-     1806, 1806, 1815, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1806, 1806, 1806, 1806, 1806, 1806, 1806,
-     1806, 1806, 1806, 1806, 1811, 1811, 1811, 1806, 1806, 1806,
-     1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806,
-     1806, 1815, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1806, 1806, 1806, 1806, 1806,
-     1806, 1806, 1806, 1806, 1811, 1811, 1806, 1806, 1806, 1806,
-     1806, 1806, 1806, 1806, 1806, 1806, 1806, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1811,
-     1806, 1806, 1806, 1806, 1806, 1806, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1806, 1806, 1806, 1806, 1806, 1806, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1806,
-
-     1806, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1806, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1806, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-     1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811, 1811,
-
-     1811, 1811, 1811, 1811, 1811,    0, 1806, 1806, 1806, 1806,
-     1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806,
-     1806, 1806, 1806, 1806
+     1853,    1, 1854, 1854, 1853,    5, 1853,    7, 1855, 1855,
+     1856, 1856, 1853, 1853, 1853, 1853, 1853, 1857, 1858, 1853,
+     1859, 1853, 1853, 1860, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1853, 1853,
+     1853, 1861, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853,
+     1853, 1853, 1853, 1853, 1853, 1853, 1853, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859,   36, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1853, 1853, 1853,
+     1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853,
+
+     1862, 1863, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853,
+     1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853,
+     1853, 1864, 1865, 1866, 1853, 1853, 1853, 1853, 1857, 1858,
+     1858, 1853, 1853, 1859, 1859, 1859, 1867,   22, 1859, 1853,
+     1853, 1860, 1853, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1868, 1853,
+     1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853,
+     1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1853, 1869, 1853,
+     1870, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853,
+     1853, 1862, 1853, 1862, 1863, 1871, 1853, 1853, 1853, 1853,
+     1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853,
+     1853, 1853, 1853, 1853, 1853, 1853, 1853, 1864, 1853, 1865,
+     1866, 1853, 1853, 1853, 1853, 1853, 1859, 1859, 1853, 1859,
+     1853, 1853, 1853, 1853, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1868, 1853, 1853, 1853, 1853, 1853,
+     1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853,
+     1853, 1853, 1853, 1853, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1869, 1869, 1870, 1870, 1853, 1853, 1853, 1853, 1853, 1853,
+     1862, 1871, 1871, 1853, 1853, 1853, 1853, 1853, 1853, 1853,
+     1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853,
+     1853, 1853, 1853, 1853, 1853, 1859, 1859, 1859, 1859, 1859,
+
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1853, 1853, 1853, 1853,
+     1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853,
+     1853, 1853, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1853, 1853,
+
+     1853, 1862, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853,
+     1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1853,
+     1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853,
+
+     1853, 1853, 1853, 1853, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1862, 1853, 1853, 1853, 1853, 1853,
+     1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853,
+     1853, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1853, 1853, 1853,
+     1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1859, 1859,
+
+     1859, 1862, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853,
+     1853, 1853, 1853, 1853, 1853, 1853, 1853, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1853, 1853, 1853, 1853, 1853,
+     1853, 1853, 1853, 1853, 1859, 1859, 1853, 1853, 1853, 1853,
+     1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1853, 1853, 1853, 1853,
+     1853, 1853, 1853, 1853, 1853, 1859, 1853, 1853, 1853, 1853,
+
+     1853, 1853, 1853, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+
+     1859, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1853, 1853, 1853, 1853, 1853,
+     1853, 1853, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1853, 1853, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1853, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1853, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859, 1859,
+     1859, 1859,    0, 1853, 1853, 1853, 1853, 1853, 1853, 1853,
+     1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853,
+     1853
     } ;
 
-static yyconst flex_int16_t yy_nxt[4205] =
+static yyconst flex_int16_t yy_nxt[2382] =
     {   0,
        14,   15,   16,   15,   15,   14,   17,   18,   14,   17,
        19,   14,   14,   14,   20,   21,   22,   23,   23,   14,
-       14,   14,   24,   25,   26,   27,   28,   29,   30,   31,
-       32,   33,   34,   35,   36,   37,   38,   39,   40,   41,
-       42,   43,   44,   45,   46,   47,   47,   47,   48,   14,
-       14,   14,   14,   24,   25,   26,   27,   28,   29,   30,
-       31,   32,   33,   34,   35,   36,   37,   38,   39,   40,
-       41,   42,   43,   44,   45,   46,   47,   47,   47,   14,
-       14,   14,   14,   14,   49,   50,   14,   14,   14,   14,
-       14,   14,   14,   14,   14,   14,   14,   51,   14,   14,
-
-       14,   14,   14,   14,   52,   14,   53,   54,   55,   14,
-       14,   14,   56,   14,   14,   57,   58,   14,   14,   59,
-       60,   61,   62,   63,   64,   14,   65,   14,   14,   14,
-       66,   14,   14,   51,   14,   52,   14,   53,   54,   55,
-       14,   14,   14,   56,   14,   14,   57,   58,   14,   14,
-       59,   60,   61,   62,   63,   64,   14,   65,   14,   14,
-       14,   50,   14,   50,   14,   15,   49,   67,   15,   14,
+       14,   14,   24,   14,   14,   14,   14,   25,   26,   27,
+       28,   29,   30,   31,   32,   33,   34,   35,   36,   37,
+       38,   39,   40,   41,   42,   43,   44,   45,   46,   47,
+       48,   48,   48,   14,   14,   14,   49,   50,  121,  330,
+      121,  121,  121,  122,  121,  121,  123,  122,  983,   51,
+      123,  125,  135,  135,  126,  331,   52,  125,  186,   51,
+      126,   53,  187,   54,   55,   56,  136,  179,  127,   57,
+      984,  180,   58,   59,  127,  181,   60,   61,   62,   63,
+
+       64,   65,  128,   66,  128,  128,  245,   50,  246,   50,
+       49,   50,  132,  985,  133,  133,  140,  170,  133,  133,
+      144,  171,  145,   51,  160,  172,  200,  161,  162,  146,
+       52,  173,  141,   51,  174,   53,  986,   54,   55,   56,
+      201,  163,  263,   57,  164,  241,   58,   59,  264,  242,
+       60,   61,   62,   63,   64,   65,  257,   66,  284,  265,
+      258,   50,  187,   50,   14,   15,   49,   67,   15,   14,
        17,   14,   14,   17,   19,   14,   14,   14,   20,   21,
-       22,   23,   23,   14,   14,   14,   68,   69,   70,   71,
-       72,   73,   74,   75,   76,   47,   77,   78,   79,   80,
-
-       81,   82,   47,   83,   84,   85,   86,   47,   87,   47,
-       47,   47,   14,   14,   14,   14,   14,   68,   69,   70,
-       71,   72,   73,   74,   75,   76,   47,   77,   78,   79,
-       80,   81,   82,   47,   83,   84,   85,   86,   47,   87,
-       47,   47,   47,   50,   14,   50,   88,   89,   49,   90,
-       89,   91,   92,   88,   93,   94,   88,   88,   88,   88,
-       95,   96,   88,   97,   97,   98,   99,  100,  101,  102,
-      103,  104,  105,  106,  107,   88,  108,   88,   88,  109,
-       88,  110,  111,   88,   88,  112,   88,  113,   88,   88,
-      114,   88,   88,   88,  115,   88,   88,   88,  116,  101,
-
-      102,  103,  104,  105,  106,  107,   88,  108,   88,   88,
-      109,   88,  110,  111,   88,   88,  112,   88,  113,   88,
-       88,  114,   88,   88,   88,  117,  118,  119,  121,  789,
-      121,  121,  121,  122,  121,  121,  123,  122,  125,  125,
-      123,  126,  126,  128, 1337,  128,  128,  132,  183,  133,
-      133,  135,  135,  184,  317,  213,  248,  185,  249,  250,
-      136,  343,  318, 1272,  140,  344,  133,  133,  128,  789,
-      128,  128,  586,  558,  344,  141,  142,  352,  143,  183,
-      352,  127,  127,  815,  184,  144,  213,  248,  185,  249,
-      250,  136,  137,  137,  137,  137,  137,  137,  137,  137,
-
-      137,  137,  137,  137,  137,  137,  141,  142,  139,  143,
-      560,  137,  198,  137,  145,  251,  144,  238,  146,  560,
-      352,  239,  147,  163,  164,  165,  199,  252,  253,  166,
-      255,  148,  254,  558,  149,  167,  528,  256,  257,  258,
-      137,  137,  137,  198,  137,  145,  251,  158,  238,  146,
-      159,  160,  239,  147,  163,  164,  165,  199,  252,  253,
-      166,  255,  148,  254,  161,  149,  167,  162,  256,  257,
-      258,  137,  137,  137,  150,  586,  151,  344,  158,  152,
-      153,  159,  160,  154,  697,  128,  155,  128,  128,  156,
-      157,  347,  168,  177,  347,  161,  169,  178,  162,  344,
-
-      170,  179,  262,  263,  234,  150,  171,  151,  173,  172,
-      152,  153,  174,  235,  154,  236,  175,  155,  193,  237,
-      156,  157,  194,  168,  177,  176,  195,  169,  178,  180,
-      181,  170,  179,  262,  263,  234,  182,  171,  196,  173,
-      172,  341,  197,  174,  235,  560,  236,  175,  558,  193,
-      237,  528,  264,  194,  266,  266,  176,  195,  240,  241,
-      180,  181,  242,  269,  243,  279,  244,  182,  186,  196,
-      187,  245,  188,  197,  272,  259,  189,  159,  273,  190,
-      178,  260,  191,  264,  282,  192,  247,  267,  185,  240,
-      241,  358,  261,  242,  269,  243,  279,  244,  586,  186,
-
-      809,  187,  245,  188,  288,  272,  259,  189,  159,  273,
-      190,  178,  260,  191,  131,  282,  192,  200,  201,  185,
-      207,  318,  214,  261,  208,  202,  215,  203,  209,  204,
-      216,  210,  205,  206,  211,  288,  217,  212,  128,  131,
-      128,  128,  587,  587,  347,  268,  347,  143,  200,  201,
-      345,  207,  318,  214,  144,  208,  202,  215,  203,  209,
-      204,  216,  210,  205,  206,  211,  334,  217,  212,  218,
-      219,  220,  328,  228,  221,  222,  268,  229,  143,  223,
-      150,  230,  151,  224,  330,  144,  225,  231,  226,  270,
-      232,  227,  271,  280,  281,  156,  319,  233,  274,  275,
-
-      218,  219,  220,  328,  228,  221,  222,  316,  229,  276,
-      223,  150,  230,  151,  224,  330,  309,  225,  231,  226,
-      270,  232,  227,  271,  280,  281,  156,  168,  233,  274,
-      275,  169,  308,  296,  283,  277,  289,  216,  284,  285,
-      276,  278,  134,  286,  290,  307,  203,  287,  134,  306,
-      293,  291,  292,  357,  357,  247,  294,  131,  168,  295,
-      336,  242,  169,  243,  296,  283,  277,  289,  216,  284,
-      285, 1806,  278,  134,  286,  290,  301,  203,  287,  134,
-      302,  293,  291,  292,  297,  298,  303,  294,  234,  304,
-      295,  336,  242, 1806,  243, 1806,  299,  235,  322,  305,
-
-     1806,  300,  310,  237,  311,  311, 1806,  301,  320,  312,
-      312,  302,  321,  337,  323,  297,  298,  303,  313,  234,
-      304,  326,  314,  324,  311,  311,  325,  299,  235,  322,
-      305,  319,  300,  315,  237,  327,  331,  306,  334,  320,
-      338,  350,  335,  321,  337,  323,  329,  333,  340,  313,
-      351,  332,  326,  128,  324,  128,  128,  325,  341,  357,
-      357, 1806,  319,  359,  315,  369,  327,  331,  306,  334,
-     1806,  338,  350,  335, 1806,  353,  353,  329,  333,  340,
-      372,  351,  332,  128,  354,  128,  128,  140,  364,  133,
-      133,  135,  135,  373,  359,  365,  369,  375,  141,  374,
-
-      136,  355,  356,  363,  363,  357,  357,  360,  360,  362,
-      362,  372, 1806,  363,  363,  354,  361, 1806,  378,  364,
-      363,  363,  562,  562,  373,  379,  365,  380,  375,  141,
-      374,  136,  137,  137,  137,  137,  137,  137,  137,  137,
-      137,  137,  137,  137,  137,  137,  370,  361,  139,  378,
-     1806,  137,  366,  137,  376,  381,  379,  371,  380,  367,
-      383,  385,  384,  386,  389,  368,  387,  390,  377,  391,
-      388,  394,  395,  392,  396,  382,  399,  370,  402, 1806,
-      137,  137,  137,  366,  137,  376,  381,  393,  371, 1806,
-      367,  383,  385,  384,  386,  389,  368,  387,  390,  377,
-
-      391,  388,  394,  395,  392,  396,  382,  399,  407,  402,
-      397,  137,  137,  137,  398,  400,  408,  409,  393,  401,
-      403,  410,  404,  405,  411,  414,  406,  415,  416,  417,
-      562,  562,  412,  421,  422,  423,  424, 1806,  413,  407,
-      431,  397,  429,  430,  432,  398,  400,  408,  409,  442,
-      401,  403,  410,  404,  405,  411,  414,  406,  415,  416,
-      417,  418,  419,  412,  421,  422,  423,  424,  425,  413,
-      443,  431,  436,  429,  430,  432,  448,  433,  420,  434,
-      442,  438,  439,  440,  426,  435,  427,  444,  437,  441,
-      446,  428,  418,  419,  447,  445,  449,  450,  451,  425,
-
-      452,  443,  453,  436,  454,  457,  458,  448,  433,  420,
-      434,  459,  438,  439,  440,  426,  435,  427,  444,  437,
-      441,  446,  428,  465, 1806,  447,  445,  449,  450,  451,
-      455,  452,  456,  453,  463,  454,  457,  458,  460,  466,
-      464,  461,  459,  474,  467,  468,  469,  475,  462,  476,
-      477,  470,  478,  479,  465,  471,  472,  483,  473,  566,
-      566,  455,  484,  456,  487,  463,  488,  489,  485,  460,
-      466,  464,  461,  495,  474,  467,  468,  469,  475,  462,
-      476,  477,  470,  478,  479,  490,  471,  472,  483,  473,
-      480,  481,  486,  484, 1806,  487,  491,  488,  489,  485,
-
-      492,  499,  493,  482,  495,  496,  500,  501,  494,  502,
-      503,  504,  505,  497,  506,  507,  490,  508,  509,  510,
-      511,  480,  481,  486,  512,  498,  513,  491,  514,  515,
-      516,  492,  499,  493,  482,  517,  496,  500,  501,  494,
-      502,  503,  504,  505,  497,  506,  507,  518,  508,  509,
-      510,  511,  519,  521,  522,  512,  498,  513,  523,  514,
-      515,  516,  524,  525,  526,  520,  517,  266,  266, 1806,
-      364,  370,  529,  530,  532,  531,  533,  392,  518,  395,
-      535,  413,  397,  519,  521,  522,  534,  537,  403,  523,
-      536,  405,  538,  524,  525,  526,  520,  540,  541,  429,
-
-      267,  364,  370,  529,  530,  532,  531,  533,  392,  539,
-      395,  535,  413,  397,  542,  543,  445,  534,  537,  403,
-      545,  536,  405,  538,  438,  546,  544,  547,  540,  541,
-      429,  548,  549,  464,  472,  551,  552,  485,  553,  554,
-      539,  492,  550,  495,  555,  542,  543,  445,  556,  494,
-      491,  545,  312,  312, 1806,  438,  546,  544,  547,  566,
-      566,  313,  548,  549,  464,  472,  551,  552,  485,  553,
-      554, 1806,  492,  550,  495,  555,  308,  312,  312,  556,
-      494,  491,  314,  567,  311,  311,  313,  563,  563,  568,
-      561,  561,  313,  315,  562,  562,  564,  565,  565,  569,
-
-      572,  566,  566,  570,  571,  573,  574,  308,  575,  576,
-      577,  578,  579,  580,  567,  583,  581,  313,  582, 1806,
-      568,  355,  355,  588,  315,  587,  587,  564, 1806,  584,
-      569,  572,  587,  587,  570,  571,  573,  574,  591,  575,
-      576,  577,  578,  579,  580,  592,  583,  581,  593,  582,
-      341,  594,  353,  353,  588,  360,  360,  595,  589,  589,
-      584,  354,  590,  590,  361,  596,  597,  598,  599,  591,
-      600,  601,  602,  603,  604,  605,  592,  606,  607,  593,
-      608,  609,  594,  610,  613,  611,  614,  617,  595,  618,
-      615,  619,  354,  612,  620,  361,  596,  597,  598,  599,
-
-      621,  600,  601,  602,  603,  604,  605,  616,  606,  607,
-      622,  608,  609,  623,  610,  613,  611,  614,  617,  624,
-      618,  615,  619,  625,  612,  620,  626,  627,  628,  629,
-      631,  621,  632,  633,  636,  634,  637,  630,  616,  638,
-      639,  622,  640,  641,  623,  635,  642,  643,  644,  645,
-      624,  646,  648,  649,  625,  647,  650,  626,  627,  628,
-      629,  631,  651,  632,  633,  636,  634,  637,  630,  654,
-      638,  639,  655,  640,  641,  652,  635,  642,  643,  644,
-      645,  656,  646,  648,  649,  653,  647,  650,  657,  658,
-      659,  660,  661,  651,  662,  590,  590,  674, 1806,  677,
-
-      654, 1806,  678,  655,  675,  689,  652,  690,  676, 1806,
-      691,  692,  656,  590,  590,  693,  653, 1806,  694,  657,
-      658,  659,  660,  661,  695,  662,  663,  664,  674,  665,
-      677,  666,  667,  678,  668,  675,  689,  669,  690,  676,
-      670,  691,  692,  696,  671,  672,  693,  698,  673,  694,
-     1806,  699, 1806,  702, 1806,  695,  703,  663,  664,  704,
-      665,  705,  666,  667,  706,  668,  700, 1806,  669,  708,
-      701,  670,  707,  709,  696,  671,  672,  710,  698,  673,
-      679,  680,  699,  681,  702,  682,  683,  703,  684,  713,
-      704,  685,  705,  716,  711,  706,  717,  700,  686,  687,
-
-      708,  701,  688,  707,  709,  712,  714,  718,  710,  719,
-      720,  679,  680,  715,  681,  721,  682,  683,  722,  684,
-      713,  723,  685,  724,  716,  711,  725,  717,  726,  686,
-      687,  727,  728,  688,  731,  729,  712,  714,  718,  732,
-      719,  720,  733,  734,  715,  735,  721,  730,  736,  722,
-      737,  738,  723,  739,  724,  740,  741,  725,  742,  726,
-      743,  744,  727,  728,  745,  731,  729,  746,  747,  748,
-      732,  749,  750,  733,  734,  752,  735,  751,  730,  736,
-      753,  737,  738,  754,  739,  755,  740,  741,  756,  742,
-      757,  743,  744,  758,  759,  745,  760,  761,  746,  747,
-
-      748,  762,  749,  750,  763,  764,  752,  765,  751,  766,
-      767,  753,  768,  769,  754,  770,  755,  771,  772,  756,
-      773,  757,  612,  774,  758,  759,  615,  760,  761,  775,
-      630,  776,  762,  777,  646,  763,  764,  778,  765,  780,
-      766,  767,  652,  768,  769,  781,  770,  676,  771,  772,
-      782,  773,  779,  612,  774,  700,  783,  615,  706,  784,
-      775,  630,  776,  711,  777,  646,  729,  785,  778,  786,
-      780,  787,  788,  652,  751,  792,  781,  793,  676,  563,
-      563,  782,  794,  779,  795,  796,  700,  783,  564,  706,
-      784,  790,  790,  797,  711,  791,  791,  729,  785,  798,
-
-      786,  799,  787,  788,  800,  751,  792,  801,  793,  802,
-      803,  804,  805,  794,  806,  795,  796,  807,  808,  564,
-      810,  811,  812,  813,  797,  814,  816,  817,  818,  819,
-      798,  820,  799,  821,  822,  800,  823,  826,  801,  827,
-      802,  803,  804,  805,  824,  806,  341,  828,  807,  808,
-      829,  810,  811,  812,  813,  830,  814,  816,  817,  818,
-      819,  831,  820,  825,  821,  822,  834,  823,  826,  832,
-      827,  833,  835,  836,  837,  824,  838,  839,  828,  840,
-      841,  829,  842,  843,  844,  845,  830,  846,  847,  848,
-      849,  850,  831,  851,  825,  852,  853,  834,  854,  855,
-
-      832,  856,  833,  835,  836,  837,  857,  838,  839,  858,
-      840,  841,  859,  842,  843,  844,  845,  860,  846,  847,
-      848,  849,  850,  861,  851,  862,  852,  853,  863,  854,
-      855,  864,  856,  865,  866,  867,  870,  857,  868,  871,
-      858,  872,  873,  859,  874,  869,  875,  878,  860,  879,
-      876,  880,  881,  882,  861,  883,  862,  877,  884,  863,
-      885,  886,  864,  890,  865,  866,  867,  870,  891,  868,
-      871,  892,  872,  873,  893,  874,  869,  875,  878,  887,
-      879,  876,  880,  881,  882,  888,  883,  894,  877,  884,
-      895,  885,  886,  896,  890,  897,  898,  889,  899,  891,
-
-      900,  901,  892,  902,  903,  893,  907,  904,  908,  909,
-      887,  910,  911,  905,  912,  913,  888,  916,  894,  914,
-      917,  895,  918,  915,  896,  906,  897,  898,  889,  899,
-      919,  900,  901,  920,  902,  903,  921,  907,  904,  908,
-      909,  922,  910,  911,  905,  912,  913,  923,  916,  924,
-      914,  917,  925,  918,  915,  926,  906,  927,  928,  929,
-      930,  919,  933,  931,  920,  934,  935,  921,  932,  936,
-      937,  938,  922,  939,  940,  941,  942,  943,  923,  944,
-      924,  945,  946,  925,  947,  948,  926,  949,  927,  928,
-      929,  930,  950,  933,  931,  951,  934,  935,  952,  932,
-
-      936,  937,  938,  953,  939,  940,  941,  942,  943,  954,
-      944,  955,  945,  946,  956,  947,  948,  957,  949,  958,
-      959,  960,  962,  950,  963,  961,  951,  964,  965,  952,
-      966,  967,  968,  969,  953,  970,  971,  972,  973,  974,
-      954,  975,  955,  976,  977,  956,  978,  979,  957,  980,
-      958,  959,  960,  962,  981,  963,  961,  982,  964,  965,
-      983,  966,  967,  968,  969,  984,  970,  971,  972,  973,
-      974,  985,  975,  986,  976,  977,  987,  978,  979,  988,
-      980,  989,  990,  991,  992,  981,  868,  993,  982,  887,
-      904,  983,  994,  995,  996,  997,  984,  791,  791,  791,
-
-      791,  998,  985,  999,  986, 1000, 1001,  987, 1002, 1003,
-      988, 1004,  989,  990,  991,  992, 1005,  868,  993, 1006,
-      887,  904, 1007,  994,  995,  996,  997, 1008, 1009, 1010,
-     1011, 1012,  998, 1013,  999, 1014, 1000, 1001, 1015, 1002,
-     1003, 1016, 1004, 1017, 1018, 1019,  341, 1005, 1020, 1021,
-     1006, 1022, 1023, 1007, 1024, 1025, 1027, 1026, 1008, 1009,
-     1010, 1011, 1012, 1028, 1013, 1029, 1014, 1030, 1031, 1015,
-     1032, 1033, 1016, 1034, 1017, 1018, 1019, 1035, 1036, 1020,
-     1021, 1037, 1022, 1023, 1038, 1024, 1025, 1027, 1026, 1039,
-     1040, 1041, 1042, 1043, 1028, 1044, 1029, 1045, 1030, 1031,
-
-     1046, 1032, 1033, 1047, 1034, 1048, 1049, 1050, 1035, 1036,
-     1051, 1806, 1037, 1058, 1059, 1038, 1806, 1060, 1062, 1063,
-     1039, 1040, 1041, 1042, 1043, 1064, 1044, 1061, 1045, 1052,
-     1065, 1046, 1071, 1072, 1047, 1073, 1048, 1049, 1050, 1053,
-     1806, 1051, 1054, 1055, 1058, 1059, 1056, 1057, 1060, 1062,
-     1063, 1074, 1075, 1076, 1077, 1078, 1064, 1079, 1061, 1080,
-     1052, 1065, 1081, 1071, 1072, 1066, 1073, 1082, 1067, 1083,
-     1053, 1068, 1084, 1054, 1055, 1069, 1085, 1056, 1057, 1086,
-     1070, 1087, 1074, 1075, 1076, 1077, 1078, 1088, 1079, 1089,
-     1080, 1090, 1091, 1081, 1092, 1093, 1066, 1094, 1082, 1067,
-
-     1083, 1095, 1068, 1084, 1096, 1097, 1069, 1085, 1098, 1099,
-     1086, 1070, 1087, 1100, 1101, 1102, 1103, 1104, 1088, 1105,
-     1089, 1106, 1090, 1091, 1107, 1092, 1093, 1108, 1094, 1109,
-     1110, 1111, 1095, 1112, 1113, 1096, 1097, 1114, 1115, 1098,
-     1099, 1116, 1117, 1118, 1100, 1101, 1102, 1103, 1104, 1119,
-     1105, 1120, 1106, 1121, 1122, 1107, 1123, 1124, 1108, 1127,
-     1109, 1110, 1111, 1128, 1112, 1113, 1125, 1129, 1114, 1115,
-     1130, 1131, 1116, 1117, 1118, 1126, 1133, 1134, 1132, 1135,
-     1119, 1136, 1120, 1137, 1121, 1122, 1138, 1123, 1124, 1139,
-     1127, 1140, 1143, 1141, 1128, 1142, 1144, 1125, 1129, 1145,
-
-     1146, 1130, 1131, 1147, 1148, 1149, 1126, 1133, 1134, 1132,
-     1135, 1150, 1136, 1151, 1137, 1152, 1153, 1138, 1154, 1155,
-     1139, 1157, 1140, 1143, 1141, 1156, 1142, 1144, 1158, 1160,
-     1145, 1146, 1161, 1162, 1147, 1148, 1149, 1163, 1159, 1164,
-     1165, 1166, 1150, 1168, 1151, 1169, 1152, 1153, 1170, 1154,
-     1155, 1171, 1157, 1172, 1173, 1174, 1156, 1040, 1167, 1158,
-     1160, 1052, 1061, 1161, 1162, 1025, 1068, 1026, 1163, 1159,
-     1164, 1165, 1166, 1175, 1168, 1070, 1169, 1122, 1176, 1170,
-     1177, 1178, 1171, 1179, 1172, 1173, 1174, 1180, 1040, 1167,
-     1181, 1182, 1052, 1061, 1183, 1184, 1025, 1068, 1026, 1185,
-
-     1186, 1187, 1188, 1189, 1175, 1190, 1070, 1191, 1122, 1176,
-     1193, 1177, 1178, 1192, 1179, 1194, 1195, 1196, 1180, 1197,
-     1198, 1181, 1182, 1199, 1200, 1183, 1184, 1201, 1202, 1203,
-     1185, 1186, 1187, 1188, 1189, 1204, 1190,  341, 1191, 1205,
-     1206, 1193, 1207, 1208, 1192, 1209, 1194, 1195, 1196, 1210,
-     1197, 1198, 1211, 1212, 1199, 1200, 1213, 1214, 1201, 1202,
-     1203, 1215, 1216, 1217, 1218, 1219, 1204, 1220, 1221, 1222,
-     1205, 1206, 1223, 1207, 1208, 1224, 1209, 1225, 1226, 1227,
-     1210, 1228, 1229, 1211, 1212, 1230, 1231, 1213, 1214, 1232,
-     1233, 1234, 1215, 1216, 1217, 1218, 1219, 1235, 1220, 1221,
-
-     1222, 1237, 1238, 1223, 1239, 1236, 1224, 1240, 1225, 1226,
-     1227, 1241, 1228, 1229, 1242, 1243, 1230, 1231, 1244, 1245,
-     1232, 1233, 1234, 1246, 1247, 1248, 1249, 1250, 1235, 1251,
-     1252, 1253, 1237, 1238, 1254, 1239, 1236, 1255, 1240, 1256,
-     1257, 1258, 1241, 1259, 1260, 1242, 1243, 1261, 1262, 1244,
-     1245, 1263, 1264, 1265, 1246, 1247, 1248, 1249, 1250, 1266,
-     1251, 1252, 1253, 1267, 1268, 1254, 1269, 1270, 1255, 1271,
-     1256, 1257, 1258, 1273, 1259, 1260, 1274, 1275, 1261, 1262,
-     1276, 1277, 1263, 1264, 1265, 1278, 1279, 1280, 1281, 1282,
-     1266, 1283, 1284, 1285, 1267, 1268, 1286, 1269, 1270, 1287,
-
-     1271, 1288, 1289, 1290, 1273, 1291, 1292, 1274, 1275, 1293,
-     1294, 1276, 1277, 1295, 1296, 1297, 1278, 1279, 1280, 1281,
-     1282, 1298, 1283, 1284, 1285, 1299, 1300, 1286, 1302, 1303,
-     1287, 1304, 1288, 1289, 1290, 1305, 1291, 1292, 1306, 1307,
-     1293, 1294, 1301, 1308, 1295, 1296, 1297, 1309, 1310, 1311,
-     1312, 1313, 1298, 1314, 1315, 1316, 1299, 1300, 1317, 1302,
-     1303, 1318, 1304, 1319, 1320, 1321, 1305, 1322, 1323, 1306,
-     1307, 1324, 1325, 1301, 1308, 1326, 1327, 1328, 1309, 1310,
-     1311, 1312, 1313, 1329, 1314, 1315, 1316, 1330, 1331, 1317,
-     1332, 1333, 1318, 1334, 1319, 1320, 1321, 1335, 1322, 1323,
-
-     1336, 1338, 1324, 1325, 1339, 1340, 1326, 1327, 1328, 1341,
-     1342, 1343, 1344, 1345, 1329, 1346, 1347, 1348, 1330, 1331,
-     1349, 1332, 1333, 1350, 1334, 1351, 1352, 1353, 1335, 1354,
-     1355, 1336, 1338, 1356, 1357, 1339, 1340, 1358, 1359, 1360,
-     1341, 1342, 1343, 1344, 1345, 1361, 1346, 1347, 1348, 1362,
-     1363, 1349, 1364, 1365, 1350, 1366, 1351, 1352, 1353, 1367,
-     1354, 1355, 1368, 1369, 1356, 1357, 1370, 1371, 1358, 1359,
-     1360, 1372, 1373, 1374, 1375, 1376, 1361, 1377, 1378, 1379,
-     1362, 1363, 1380, 1364, 1365, 1381, 1366, 1382, 1383, 1384,
-     1367, 1385, 1386, 1368, 1369, 1387, 1388, 1370, 1371, 1389,
-
-     1390, 1391, 1372, 1373, 1374, 1375, 1376, 1392, 1377, 1378,
-     1379, 1393, 1394, 1380, 1395, 1396, 1381, 1397, 1382, 1383,
-     1384, 1398, 1385, 1386, 1399, 1400, 1387, 1388, 1401, 1402,
-     1389, 1390, 1391, 1403, 1404, 1406, 1405, 1407, 1392, 1409,
-     1415, 1806, 1393, 1394, 1416, 1395, 1396, 1806, 1397, 1417,
-     1418, 1419, 1398, 1420, 1421, 1399, 1400, 1408, 1422, 1401,
-     1402, 1410, 1411, 1423, 1403, 1404, 1406, 1405, 1407, 1424,
-     1409, 1415, 1412, 1425, 1413, 1416, 1426, 1427, 1414, 1428,
-     1417, 1418, 1419, 1429, 1420, 1421, 1430, 1431, 1408, 1422,
-     1432, 1433, 1410, 1411, 1423, 1434, 1435, 1436, 1437, 1438,
-
-     1424, 1441, 1442, 1412, 1425, 1413, 1443, 1426, 1427, 1414,
-     1428, 1439, 1444, 1440, 1429, 1445, 1446, 1430, 1431, 1447,
-     1448, 1432, 1433, 1449, 1450, 1451, 1434, 1435, 1436, 1437,
-     1438, 1452, 1441, 1442, 1453, 1454, 1455, 1443, 1456, 1457,
-     1458, 1459, 1439, 1444, 1440, 1460, 1445, 1446, 1461, 1462,
-     1447, 1448, 1463, 1464, 1449, 1450, 1451, 1465, 1466, 1467,
-     1410, 1411, 1452, 1468, 1469, 1453, 1454, 1455, 1470, 1456,
-     1457, 1458, 1459, 1413, 1471, 1472, 1460, 1414, 1473, 1461,
-     1462, 1474, 1475, 1463, 1464, 1476, 1477, 1478, 1465, 1466,
-     1467, 1410, 1411, 1479, 1468, 1469, 1480, 1481, 1482, 1470,
-
-     1483, 1484, 1485, 1486, 1413, 1471, 1472, 1487, 1414, 1473,
-     1488, 1489, 1474, 1475, 1490, 1491, 1476, 1477, 1478, 1492,
-     1493, 1494, 1495, 1496, 1479, 1497, 1498, 1480, 1481, 1482,
-     1499, 1483, 1484, 1485, 1486, 1500, 1501, 1502, 1487, 1503,
-     1504, 1488, 1489, 1505, 1506, 1490, 1491, 1507, 1508, 1509,
-     1492, 1493, 1494, 1495, 1496, 1510, 1497, 1498, 1511, 1512,
-     1513, 1499, 1514, 1515, 1516, 1517, 1500, 1501, 1502, 1518,
-     1503, 1504, 1519, 1520, 1505, 1506, 1521, 1522, 1507, 1508,
-     1509, 1523, 1524, 1525, 1526, 1527, 1510, 1528, 1529, 1511,
-     1512, 1513, 1530, 1514, 1515, 1516, 1517, 1531, 1532, 1534,
-
-     1518, 1535, 1537, 1519, 1520, 1538, 1533, 1521, 1522, 1539,
-     1540, 1541, 1523, 1524, 1525, 1526, 1527, 1536, 1528, 1529,
-     1542, 1543, 1544, 1530, 1545, 1546, 1547, 1548, 1531, 1532,
-     1534, 1549, 1535, 1537, 1550, 1551, 1538, 1533, 1552, 1553,
-     1539, 1540, 1541, 1554, 1555, 1556, 1557, 1558, 1536, 1559,
-     1560, 1542, 1543, 1544, 1561, 1545, 1546, 1547, 1548, 1562,
-     1563, 1564, 1549, 1565, 1566, 1550, 1551, 1567, 1568, 1552,
-     1553, 1569, 1570, 1571, 1554, 1555, 1556, 1557, 1558, 1572,
-     1559, 1560, 1573, 1574, 1575, 1561, 1576, 1577, 1578, 1579,
-     1562, 1563, 1564, 1580, 1565, 1566, 1581, 1582, 1567, 1568,
-
-     1583, 1584, 1569, 1570, 1571, 1585, 1586, 1587, 1588, 1589,
-     1572, 1590, 1591, 1573, 1574, 1575, 1592, 1576, 1577, 1578,
-     1579, 1593, 1594, 1595, 1580, 1596, 1597, 1581, 1582, 1598,
-     1599, 1583, 1584, 1600, 1601, 1602, 1585, 1586, 1587, 1588,
-     1589, 1603, 1590, 1591, 1604, 1605, 1606, 1592, 1607, 1608,
-     1609, 1610, 1593, 1594, 1595, 1611, 1596, 1597, 1612, 1613,
-     1598, 1599, 1614, 1615, 1600, 1601, 1602, 1616, 1617, 1618,
-     1619, 1620, 1603, 1621, 1622, 1604, 1605, 1606, 1623, 1607,
-     1608, 1609, 1610, 1624, 1625, 1626, 1611, 1627, 1628, 1612,
-     1613, 1629, 1630, 1614, 1615, 1631, 1632, 1633, 1616, 1617,
-
-     1618, 1619, 1620, 1634, 1621, 1622, 1635, 1636, 1637, 1623,
-     1638, 1639, 1640, 1641, 1624, 1625, 1626, 1642, 1627, 1628,
-     1643, 1644, 1629, 1630, 1645, 1646, 1631, 1632, 1633, 1647,
-     1648, 1649, 1650, 1651, 1634, 1652, 1653, 1635, 1636, 1637,
-     1654, 1638, 1639, 1640, 1641, 1655, 1656, 1657, 1642, 1658,
-     1659, 1643, 1644, 1660, 1661, 1645, 1646, 1662, 1663, 1664,
-     1647, 1648, 1649, 1650, 1651, 1665, 1652, 1653, 1666, 1667,
-     1668, 1654, 1669, 1670, 1671, 1672, 1655, 1656, 1657, 1673,
-     1658, 1659, 1674, 1675, 1660, 1661, 1676, 1677, 1662, 1663,
-     1664, 1678, 1679, 1680, 1681, 1682, 1665, 1683, 1684, 1666,
-
-     1667, 1668, 1685, 1669, 1670, 1671, 1672, 1686, 1687, 1688,
-     1673, 1689, 1690, 1674, 1675, 1691, 1692, 1676, 1677, 1693,
-     1694, 1695, 1678, 1679, 1680, 1681, 1682, 1696, 1683, 1684,
-     1697, 1698, 1700, 1685, 1701, 1702, 1703, 1704, 1686, 1687,
-     1688, 1705, 1689, 1690, 1706, 1707, 1691, 1692, 1699, 1708,
-     1693, 1694, 1695, 1709, 1710, 1711, 1712, 1713, 1696, 1714,
-     1715, 1697, 1698, 1700, 1716, 1701, 1702, 1703, 1704, 1717,
-     1718, 1719, 1705, 1720, 1721, 1706, 1707, 1722, 1723, 1699,
-     1708, 1724, 1725, 1726, 1709, 1710, 1711, 1712, 1713, 1727,
-     1714, 1715, 1728, 1729, 1730, 1716, 1731, 1732, 1733, 1734,
-
-     1717, 1718, 1719, 1735, 1720, 1721, 1736, 1737, 1722, 1723,
-     1738, 1739, 1724, 1725, 1726, 1740, 1741, 1742, 1743, 1744,
-     1727, 1745, 1746, 1728, 1729, 1730, 1747, 1731, 1732, 1733,
-     1734, 1748, 1749, 1750, 1735, 1751, 1752, 1736, 1737, 1753,
-     1754, 1738, 1739, 1755, 1756, 1757, 1740, 1741, 1742, 1743,
-     1744, 1758, 1745, 1746, 1759, 1760, 1761, 1747, 1762, 1763,
-     1764, 1765, 1748, 1749, 1750, 1766, 1751, 1752, 1767, 1768,
-     1753, 1754, 1769, 1770, 1755, 1756, 1757, 1771, 1772, 1773,
-     1774, 1775, 1758, 1776, 1777, 1759, 1760, 1761, 1778, 1762,
-     1763, 1764, 1765, 1779, 1780, 1781, 1766, 1782, 1783, 1767,
-
-     1768, 1784, 1785, 1769, 1770, 1786, 1787, 1788, 1771, 1772,
-     1773, 1774, 1775, 1789, 1776, 1777, 1790, 1791, 1792, 1778,
-     1793, 1794, 1795, 1796, 1779, 1780, 1781, 1797, 1782, 1783,
-     1798, 1799, 1784, 1785, 1800, 1801, 1786, 1787, 1788, 1802,
-     1803, 1804, 1805, 1806, 1789, 1806, 1806, 1790, 1791, 1792,
-     1806, 1793, 1794, 1795, 1796, 1806, 1806, 1806, 1797, 1806,
-     1806, 1798, 1799, 1806, 1806, 1800, 1801, 1806, 1806, 1806,
-     1802, 1803, 1804, 1805,  120,  120,  120,  120,  120,  120,
-      120,  120,  120,  124,  124,  124,  124,  124,  124,  124,
-      124,  124,  129, 1806,  129,  129,  129,  129,  129,  129,
-
-      129,  130, 1806,  130,  130,  130,  130,  130,  130,  130,
-      134,  134,  138,  138,  138,  138,  138,  138,  138,  138,
-      138,  246,  246,  246,  246,  246,  246,  246,  246,  246,
-      265, 1806,  265,  339,  339,  339,  339,  339,  339,  339,
-      339,  339,  342,  342,  342,  342,  342,  342,  342,  342,
-      342,  346,  346,  346,  346,  346,  346,  346,  346,  346,
-      348,  348,  348,  348,  348,  348,  348,  348,  348,  349,
-      349,  349, 1806, 1806,  349,  349, 1806,  349,  137,  137,
-      137,  137,  137,  137,  137,  137,  137,  527, 1806, 1806,
-      527,  527, 1806,  527,  557,  557,  557, 1806,  557,  557,
-
-      557,  557,  557,  559,  559,  559,  559, 1806,  559,  559,
-      559,  559,  585,  585,  585,  585,  585,  585,  585,  585,
-      585,   13, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806,
-     1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806,
-     1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806,
-     1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806,
-     1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806,
-     1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806,
-     1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806,
-     1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806,
-
-     1806, 1806, 1806, 1806
+       22,   23,   23,   14,   14,   14,   14,   14,   14,   14,
+       14,   68,   69,   70,   71,   72,   73,   74,   75,   76,
+
+       48,   77,   78,   79,   80,   81,   82,   48,   83,   84,
+       85,   86,   48,   87,   48,   48,   48,   50,   14,   50,
+       88,   89,   49,   90,   89,   91,   92,   88,   93,   94,
+       88,   88,   88,   88,   95,   96,   88,   97,   97,   98,
+       99,  100,  101,   88,   88,   88,  102,  103,  104,  105,
+      106,  107,  108,  109,   88,  110,   88,   88,  111,   88,
+      112,  113,   88,   88,  114,   88,  115,   88,   88,  116,
+       88,   88,   88,  117,  118,  119,  137,  137,  137,  137,
+      137,  137,  137,  137,  137,  137,  137,  137,  137,  137,
+      138,  138,  139,  138,  138,  137,  138,  137,  137,  137,
+
+      137,  138,  137,  138,  138,  138,  138,  138,  138,  138,
+      138,  138,  138,  138,  138,  138,  138,  138,  138,  138,
+      138,  138,  138,  138,  138,  138,  138,  138,  138,  137,
+      137,  137,  147,  282,  283,  128,  148,  128,  128,  152,
+      149,  153,  175,  308,  154,  155,  176,  175,  156,  150,
+      177,  157,  151,  341,  158,  159,  165,  166,  167,  178,
+      182,  183,  168,  987,  281,  250,  250,  184,  169,  188,
+      195,  189,  251,  190,  196,  287,  372,  191,  197,  288,
+      192,  202,  203,  193,  209,  323,  194,  373,  210,  204,
+      198,  205,  211,  206,  199,  212,  207,  208,  213,  216,
+
+      269,  214,  270,  217,  243,  244,  324,  218,  245,  146,
+      246,  988,  247,  219,  220,  221,  222,  248,  230,  223,
+      224,  298,  231,  326,  225,  218,  232,  327,  226,  236,
+      328,  227,  233,  228,  329,  234,  229,  152,  237,  153,
+      238,  321,  235,  989,  239,  339,  272,  274,  240,  273,
+      161,  275,  158,  276,  277,  170,  337,  285,  290,  171,
+      340,  286,  294,  279,  278,  134,  291,  319,  205,  280,
+      295,  134,  236,  292,  293,  320,  296,  299,  300,  297,
+      303,  237,  332,  307,  304,  333,  334,  239,  342,  301,
+      305,  471,  343,  306,  302,  128,  472,  128,  128,  128,
+
+      335,  128,  128,  312,  375,  313,  313,  314,  314,  316,
+      376,  313,  313,  128,  353,  128,  128,  353,  354,  354,
+      128,  315,  128,  128,  140,  317,  133,  133,  135,  135,
+      990,  353,  355,  356,  357,  361,  361,  358,  358,  365,
+      141,  367,  136,  363,  363,  368,  366,  364,  364,  362,
+      378,  383,  369,  385,  394,  386,  389,  553,  370,  399,
+      390,  396,  397,  400,  379,  402,  413,  554,  395,  403,
+      405,  384,  406,  407,  414,  428,  408,  420,  421,  432,
+      415,  441,  451,  422,  433,  434,  452,  437,  449,  438,
+      439,  429,  991,  430,  423,  440,  450,  442,  431,  443,
+
+      444,  445,  460,  465,  461,  468,  466,  446,  473,  474,
+      490,  469,  495,  467,  475,  485,  486,  501,  476,  477,
+      799,  478,  497,  496,  498,  502,  250,  250,  487,  527,
+      499,  368,  399,  251,  491,  564,  540,  503,  369,  536,
+      558,  537,  528,  405,  370,  542,  407,  544,  497,  314,
+      314,  496,  316,  422,  313,  313,  499,  314,  314,  567,
+      567,  565,  565,  315,  545,  566,  566,  323,  317,  580,
+      573,  315,  327,  568,  569,  569,  617,  571,  570,  570,
+      577,  578,  581,  589,  618,  590,  354,  354,  356,  356,
+      592,  592,  592,  592,  358,  358,  358,  358,  361,  361,
+
+      355,  594,  594,  364,  364,  595,  595,  364,  364,  621,
+      635,  640,  362,  652,  659,  684,  709,  653,  636,  685,
+      710,  641,  739,  715,  660,  799,  622,  672,  673,  721,
+      674,  716,  675,  676,  740,  677,  719,  724,  678,  992,
+      722,  679,  760,  562,  725,  680,  681,  761,  836,  682,
+      688,  689,  659,  690,  323,  691,  692,  802,  693,  993,
+      720,  694,  790,  566,  566,  566,  566,  837,  695,  696,
+      567,  567,  697,  800,  800,  570,  570,  801,  801,  570,
+      570,  573,  929,  327,  568,  573,  930,  803,  592,  592,
+      595,  595,  595,  595,  844,  882,  845,  891,  947,  902,
+
+      919,  994,  883,  948,  892,  903,  920,  976,  995,  996,
+      997,  977,  998,  999, 1000, 1001, 1002,  904,  921, 1003,
+     1004, 1005, 1006, 1007, 1008, 1009,  882, 1010,  929, 1011,
+     1012, 1013, 1014,  801,  801,  801,  801,  323, 1016, 1017,
+     1018, 1019, 1020, 1021, 1022, 1023, 1024, 1025, 1026, 1027,
+     1028, 1029, 1030, 1031, 1032, 1015, 1033, 1034, 1035, 1036,
+     1037, 1038, 1039, 1040, 1041, 1042, 1043, 1044, 1046, 1045,
+     1047, 1048, 1049, 1050, 1051, 1052, 1053, 1054, 1055, 1056,
+     1057, 1058, 1059, 1060, 1061, 1062, 1063, 1064, 1065, 1066,
+     1067, 1068, 1069, 1070, 1071, 1072, 1078, 1079, 1080, 1083,
+
+     1081, 1084, 1085, 1086, 1092, 1073, 1093, 1094, 1074, 1075,
+     1082, 1087, 1076, 1077, 1088, 1095, 1096, 1089, 1097, 1098,
+     1099, 1090, 1100, 1101, 1102, 1103, 1091, 1104, 1105, 1106,
+     1107, 1108, 1109, 1110, 1111, 1112, 1113, 1114, 1115, 1116,
+     1117, 1118, 1119, 1120, 1121, 1122, 1123, 1124, 1125, 1126,
+     1127, 1128, 1129, 1130, 1131, 1132, 1133, 1134, 1135, 1136,
+     1137, 1138, 1139, 1140, 1141, 1142, 1143, 1144, 1145, 1146,
+     1147, 1148, 1150, 1151, 1152, 1153, 1154, 1156, 1157, 1158,
+     1149, 1159, 1160, 1155, 1161, 1162, 1163, 1164, 1166, 1165,
+     1167, 1168, 1169, 1170, 1171, 1172, 1173, 1174, 1175, 1176,
+
+     1177, 1178, 1180, 1181, 1183, 1184, 1185, 1179, 1186, 1187,
+     1188, 1189, 1190, 1182, 1192, 1193, 1194, 1195, 1196, 1197,
+     1198, 1044, 1059, 1045, 1072, 1082, 1089, 1199, 1144, 1191,
+     1200, 1201,  323, 1203, 1204, 1091, 1205, 1206, 1207, 1202,
+     1208, 1209, 1210, 1211, 1212, 1213, 1214, 1215, 1216, 1217,
+     1218, 1219, 1220, 1221, 1222, 1223, 1224, 1225, 1226, 1227,
+     1228, 1229, 1230, 1231, 1232, 1233, 1234, 1235, 1236, 1237,
+     1238, 1239, 1240, 1241, 1242, 1243, 1244, 1245, 1246, 1247,
+     1248, 1249, 1250, 1251, 1252, 1253, 1254, 1255, 1256, 1257,
+     1258, 1259, 1260, 1261, 1262, 1263, 1265, 1266, 1267, 1268,
+
+     1269, 1270, 1271, 1264, 1272, 1273, 1274, 1275, 1276, 1277,
+     1278, 1279, 1280, 1281, 1282, 1283, 1284, 1285, 1286, 1287,
+     1288, 1289, 1290, 1291, 1292, 1293, 1294, 1295, 1296, 1297,
+     1298, 1299, 1300, 1301, 1302, 1303, 1304, 1305, 1306, 1307,
+     1308, 1309, 1310, 1311, 1312, 1313, 1314, 1315, 1316, 1317,
+     1318, 1319, 1320, 1321, 1322, 1323, 1324, 1325, 1326, 1327,
+     1328, 1329, 1331, 1332, 1333, 1334, 1335, 1336, 1337, 1338,
+     1339, 1340, 1341, 1342, 1343, 1344, 1345, 1330, 1346, 1347,
+     1348, 1349, 1350, 1351, 1352, 1353, 1354, 1355, 1356, 1357,
+     1358, 1359, 1360, 1361, 1362, 1363, 1364, 1365, 1366, 1367,
+
+     1368, 1369, 1370, 1371, 1372, 1373, 1374, 1375, 1376, 1377,
+     1378, 1379, 1380, 1381, 1382, 1383, 1384, 1385, 1386, 1387,
+     1388, 1389, 1390, 1391, 1392, 1393, 1394, 1395, 1396, 1397,
+     1398, 1399, 1400, 1401, 1402, 1403, 1404, 1405, 1406, 1407,
+     1408, 1409, 1410, 1411, 1412, 1413, 1414, 1415, 1416, 1417,
+     1418, 1419, 1420, 1421, 1422, 1423, 1424, 1425, 1426, 1427,
+     1428, 1429, 1430, 1431, 1432, 1433, 1434, 1435, 1436, 1437,
+     1438, 1440, 1439, 1441, 1443, 1444, 1445, 1449, 1450, 1451,
+     1452, 1453, 1454, 1455, 1456, 1457, 1446, 1458, 1447, 1459,
+     1460, 1461, 1448, 1442, 1462, 1463, 1464, 1465, 1466, 1467,
+
+     1468, 1469, 1470, 1471, 1472, 1473, 1474, 1476, 1475, 1477,
+     1478, 1479, 1480, 1481, 1482, 1483, 1484, 1485, 1486, 1487,
+     1488, 1489, 1490, 1491, 1492, 1493, 1494, 1495, 1444, 1445,
+     1496, 1497, 1498, 1499, 1500, 1501, 1502, 1503, 1504, 1505,
+     1506, 1447, 1507, 1508, 1509, 1448, 1510, 1511, 1512, 1513,
+     1514, 1515, 1516, 1517, 1518, 1519, 1520, 1521, 1522, 1523,
+     1524, 1525, 1526, 1527, 1528, 1529, 1530, 1531, 1532, 1533,
+     1534, 1535, 1536, 1537, 1538, 1539, 1540, 1541, 1542, 1543,
+     1544, 1545, 1546, 1547, 1548, 1549, 1550, 1551, 1552, 1553,
+     1554, 1555, 1556, 1557, 1558, 1559, 1560, 1561, 1562, 1563,
+
+     1564, 1565, 1566, 1567, 1568, 1569, 1570, 1571, 1573, 1574,
+     1576, 1577, 1578, 1579, 1580, 1572, 1581, 1582, 1583, 1584,
+     1585, 1586, 1587, 1588, 1589, 1575, 1590, 1591, 1592, 1593,
+     1594, 1595, 1596, 1597, 1598, 1599, 1600, 1601, 1602, 1603,
+     1604, 1605, 1606, 1607, 1608, 1609, 1610, 1611, 1612, 1613,
+     1614, 1615, 1616, 1617, 1618, 1619, 1620, 1621, 1622, 1623,
+     1624, 1625, 1626, 1627, 1628, 1629, 1630, 1631, 1632, 1633,
+     1634, 1635, 1636, 1637, 1638, 1639, 1640, 1641, 1642, 1643,
+     1644, 1645, 1646, 1647, 1648, 1649, 1650, 1651, 1652, 1653,
+     1654, 1655, 1656, 1657, 1658, 1659, 1660, 1661, 1662, 1663,
+
+     1664, 1665, 1666, 1667, 1668, 1669, 1670, 1671, 1672, 1673,
+     1674, 1675, 1676, 1677, 1678, 1679, 1680, 1681, 1682, 1683,
+     1684, 1685, 1686, 1687, 1688, 1689, 1690, 1691, 1692, 1693,
+     1694, 1695, 1696, 1697, 1698, 1699, 1700, 1701, 1702, 1703,
+     1704, 1705, 1706, 1707, 1708, 1709, 1710, 1711, 1712, 1713,
+     1714, 1715, 1716, 1717, 1718, 1719, 1720, 1721, 1722, 1723,
+     1724, 1725, 1726, 1727, 1728, 1729, 1730, 1731, 1732, 1733,
+     1734, 1735, 1736, 1737, 1738, 1739, 1740, 1741, 1742, 1743,
+     1744, 1745, 1747, 1748, 1749, 1750, 1751, 1752, 1753, 1754,
+     1755, 1756, 1757, 1758, 1759, 1760, 1761, 1762, 1746, 1763,
+
+     1764, 1765, 1766, 1767, 1768, 1769, 1770, 1771, 1772, 1773,
+     1774, 1775, 1776, 1777, 1778, 1779, 1780, 1781, 1782, 1783,
+     1784, 1785, 1786, 1787, 1788, 1789, 1790, 1791, 1792, 1793,
+     1794, 1795, 1796, 1797, 1798, 1799, 1800, 1801, 1802, 1803,
+     1804, 1805, 1806, 1807, 1808, 1809, 1810, 1811, 1812, 1813,
+     1814, 1815, 1816, 1817, 1818, 1819, 1820, 1821, 1822, 1823,
+     1824, 1825, 1826, 1827, 1828, 1829, 1830, 1831, 1832, 1833,
+     1834, 1835, 1836, 1837, 1838, 1839, 1840, 1841, 1842, 1843,
+     1844, 1845, 1846, 1847, 1848, 1849, 1850, 1851, 1852,   14,
+       14,   14,   14,   14,   14,   14,   14,   14,  120,  120,
+
+      120,  120,  120,  120,  120,  120,  120,  124,  124,  124,
+      124,  124,  124,  124,  124,  124,  129,  982,  129,  129,
+      129,  129,  129,  129,  129,  130,  981,  130,  130,  130,
+      130,  130,  130,  130,  134,  134,  142,  142,  142,  142,
+      142,  142,  142,  142,  142,  249,  980,  249,  322,  322,
+      322,  322,  322,  322,  322,  322,  322,  325,  325,  325,
+      325,  325,  325,  325,  325,  325,  348,  348,  348,  348,
+      348,  348,  348,  348,  348,  350,  350,  350,  350,  350,
+      350,  350,  350,  350,  351,  351,  351,  979,  978,  351,
+      351,  975,  351,  137,  137,  137,  137,  137,  137,  137,
+
+      137,  137,  515,  974,  973,  515,  515,  972,  515,  561,
+      561,  561,  971,  561,  561,  561,  561,  561,  563,  563,
+      563,  563,  970,  563,  563,  563,  563,  572,  572,  572,
+      572,  572,  572,  572,  572,  572,  969,  968,  967,  966,
+      965,  964,  963,  962,  961,  960,  959,  958,  957,  956,
+      955,  954,  953,  952,  951,  950,  949,  946,  945,  944,
+      943,  942,  941,  940,  939,  938,  937,  936,  935,  934,
+      933,  932,  931,  928,  927,  926,  925,  924,  923,  922,
+      918,  917,  916,  915,  914,  913,  912,  911,  910,  909,
+      908,  907,  906,  905,  901,  900,  899,  898,  897,  896,
+
+      895,  894,  893,  890,  889,  888,  887,  886,  885,  884,
+      881,  880,  879,  878,  877,  876,  875,  874,  873,  872,
+      871,  870,  869,  868,  867,  866,  865,  864,  863,  862,
+      861,  860,  859,  858,  857,  856,  855,  854,  853,  852,
+      851,  850,  849,  848,  847,  846,  843,  842,  841,  840,
+      839,  838,  835,  834,  833,  832,  831,  830,  829,  828,
+      827,  826,  825,  824,  823,  822,  821,  820,  819,  818,
+      817,  816,  815,  814,  813,  812,  811,  810,  809,  808,
+      807,  806,  805,  804,  564,  562,  761,  798,  797,  796,
+      795,  739,  721,  794,  715,  793,  709,  792,  685,  791,
+
+      789,  652,  788,  787,  636,  786,  621,  785,  618,  784,
+      783,  782,  781,  780,  779,  778,  777,  776,  775,  774,
+      773,  772,  771,  770,  769,  768,  767,  516,  766,  765,
+      764,  763,  762,  759,  758,  757,  756,  755,  754,  753,
+      752,  751,  750,  749,  748,  747,  746,  745,  744,  743,
+      742,  741,  738,  737,  736,  735,  734,  733,  732,  731,
+      730,  729,  728,  727,  726,  723,  718,  717,  714,  713,
+      712,  711,  708,  707,  706,  705,  704,  703,  702,  701,
+      700,  699,  698,  687,  686,  683,  671,  670,  669,  668,
+      667,  666,  665,  664,  663,  662,  661,  658,  657,  656,
+
+      655,  654,  651,  650,  649,  648,  647,  646,  645,  644,
+      643,  642,  639,  638,  637,  634,  633,  632,  631,  630,
+      629,  628,  627,  626,  625,  624,  623,  620,  619,  616,
+      615,  614,  613,  612,  611,  610,  609,  608,  607,  606,
+      605,  604,  603,  602,  601,  600,  599,  598,  597,  596,
+      593,  349,  349,  591,  588,  587,  586,  585,  584,  583,
+      582,  579,  576,  575,  574,  310,  327,  323,  564,  562,
+      560,  559,  500,  557,  490,  556,  555,  477,  469,  552,
+      461,  551,  550,  549,  450,  443,  548,  433,  547,  546,
+      543,  415,  541,  397,  394,  539,  538,  535,  372,  365,
+
+      534,  533,  532,  531,  530,  529,  526,  525,  524,  523,
+      522,  521,  520,  519,  518,  517,  516,  514,  513,  512,
+      511,  510,  509,  508,  507,  506,  505,  504,  500,  494,
+      493,  492,  489,  488,  484,  483,  482,  481,  480,  479,
+      470,  464,  463,  462,  459,  458,  457,  456,  455,  454,
+      453,  448,  447,  436,  435,  427,  426,  425,  424,  419,
+      418,  417,  416,  412,  411,  410,  409,  404,  401,  398,
+      393,  392,  391,  388,  387,  382,  381,  380,  377,  374,
+      371,  143,  360,  359,  131,  131,  352,  352,  349,  349,
+      347,  342,  346,  345,  344,  338,  336,  320,  321,  318,
+
+      311,  310,  309,  308,  289,  180,  271,  268,  267,  266,
+      262,  261,  260,  259,  256,  255,  254,  253,  252,  215,
+      185,  143,  131, 1853,   13, 1853, 1853, 1853, 1853, 1853,
+     1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853,
+     1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853,
+     1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853,
+     1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853,
+     1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853,
+     1853
     } ;
 
-static yyconst flex_int16_t yy_chk[4205] =
+static yyconst flex_int16_t yy_chk[2382] =
     {   0,
         1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
         1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
         1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
         1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
         1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
-        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
-        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
-        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
-        1,    1,    3,    3,    3,    3,    3,    3,    3,    3,
-        3,    3,    3,    3,    3,    3,    3,    3,    3,    3,
-
-        3,    3,    3,    3,    3,    3,    3,    3,    3,    3,
-        3,    3,    3,    3,    3,    3,    3,    3,    3,    3,
-        3,    3,    3,    3,    3,    3,    3,    3,    3,    3,
-        3,    3,    3,    3,    3,    3,    3,    3,    3,    3,
-        3,    3,    3,    3,    3,    3,    3,    3,    3,    3,
-        3,    3,    3,    3,    3,    3,    3,    3,    3,    3,
-        3,    3,    3,    3,    5,    5,    5,    5,    5,    5,
+        1,    1,    1,    1,    1,    1,    3,    3,    9,  104,
+        9,    9,   10,    9,   10,   10,    9,   10,  758,    3,
+       10,   11,   21,   21,   11,  104,    3,   12,   35,    3,
+       12,    3,   35,    3,    3,    3,   21,   32,   11,    3,
+      760,   32,    3,    3,   12,   32,    3,    3,    3,    3,
+
+        3,    3,   15,    3,   15,   15,   87,    3,   87,    3,
+        4,    4,   20,  761,   20,   20,   23,   30,   23,   23,
+       25,   30,   25,    4,   28,   30,   38,   28,   28,   25,
+        4,   30,   23,    4,   30,    4,  762,    4,    4,    4,
+       38,   28,   63,    4,   28,   46,    4,    4,   63,   46,
+        4,    4,    4,    4,    4,    4,   58,    4,   77,   63,
+       58,    4,   77,    4,    5,    5,    5,    5,    5,    5,
         5,    5,    5,    5,    5,    5,    5,    5,    5,    5,
         5,    5,    5,    5,    5,    5,    5,    5,    5,    5,
         5,    5,    5,    5,    5,    5,    5,    5,    5,    5,
 
         5,    5,    5,    5,    5,    5,    5,    5,    5,    5,
         5,    5,    5,    5,    5,    5,    5,    5,    5,    5,
-        5,    5,    5,    5,    5,    5,    5,    5,    5,    5,
-        5,    5,    5,    5,    5,    5,    5,    5,    5,    5,
-        5,    5,    5,    5,    5,    5,    7,    7,    7,    7,
-        7,    7,    7,    7,    7,    7,    7,    7,    7,    7,
         7,    7,    7,    7,    7,    7,    7,    7,    7,    7,
         7,    7,    7,    7,    7,    7,    7,    7,    7,    7,
         7,    7,    7,    7,    7,    7,    7,    7,    7,    7,
         7,    7,    7,    7,    7,    7,    7,    7,    7,    7,
-
-        7,    7,    7,    7,    7,    7,    7,    7,    7,    7,
         7,    7,    7,    7,    7,    7,    7,    7,    7,    7,
-        7,    7,    7,    7,    7,    7,    7,    7,    9,  558,
-        9,    9,   10,    9,   10,   10,    9,   10,   11,   12,
-       10,   11,   12,   15, 1192,   15,   15,   20,   33,   20,
-       20,   21,   21,   34,   99,   40,   52,   34,   53,   54,
-       21,  116,   99, 1110,   23,  116,   23,   23,   67,  560,
-       67,   67,  343,  558,  343,   23,   24,  127,   24,   33,
-      127,   11,   12,  596,   34,   24,   40,   52,   34,   53,
-       54,   21,   22,   22,   22,   22,   22,   22,   22,   22,
-
-       22,   22,   22,   22,   22,   22,   23,   24,   22,   24,
-      560,   22,   37,   22,   25,   55,   24,   45,   25,  559,
-      127,   45,   25,   28,   28,   28,   37,   56,   57,   28,
-       58,   25,   57,  557,   25,   28,  527,   59,   60,   61,
-       22,   22,   22,   37,   22,   25,   55,   27,   45,   25,
-       27,   27,   45,   25,   28,   28,   28,   37,   56,   57,
-       28,   58,   25,   57,   27,   25,   28,   27,   59,   60,
-       61,   22,   22,   22,   26,  585,   26,  585,   27,   26,
-       26,   27,   27,   26,  450,   89,   26,   89,   89,   26,
-       26,  348,   29,   31,  346,   27,   29,   31,   27,  342,
-
-       29,   31,   63,   64,   44,   26,   29,   26,   30,   29,
-       26,   26,   30,   44,   26,   44,   30,   26,   36,   44,
-       26,   26,   36,   29,   31,   30,   36,   29,   31,   32,
-       32,   29,   31,   63,   64,   44,   32,   29,   36,   30,
-       29,  339,   36,   30,   44,  309,   44,   30,  307,   36,
-       44,  265,   65,   36,   66,   66,   30,   36,   46,   46,
-       32,   32,   46,   69,   46,   74,   46,   32,   35,   36,
-       35,   46,   35,   36,   71,   62,   35,   71,   71,   35,
-       75,   62,   35,   65,   77,   35,  246,   66,   77,   46,
-       46,  137,   62,   46,   69,   46,   74,   46,  586,   35,
-
-      586,   35,   46,   35,   80,   71,   62,   35,   71,   71,
-       35,   75,   62,   35,  131,   77,   35,   38,   38,   77,
-       39,  105,   41,   62,   39,   38,   41,   38,   39,   38,
-       41,   39,   38,   38,   39,   80,   41,   39,   90,  130,
-       90,   90,  355,  355,  123,   68,  122,   68,   38,   38,
-      118,   39,  105,   41,   68,   39,   38,   41,   38,   39,
-       38,   41,   39,   38,   38,   39,  117,   41,   39,   42,
-       42,   42,  106,   43,   42,   42,   68,   43,   68,   42,
-       70,   43,   70,   42,  108,   68,   42,   43,   42,   70,
-       43,   42,   70,   76,   76,   70,  100,   43,   72,   72,
-
-       42,   42,   42,  106,   43,   42,   42,   98,   43,   72,
-       42,   70,   43,   70,   42,  108,   94,   42,   43,   42,
-       70,   43,   42,   70,   76,   76,   70,   73,   43,   72,
-       72,   73,   93,   83,   78,   73,   81,   83,   78,   79,
-       72,   73,   78,   79,   81,   92,   81,   79,   78,   91,
-       82,   81,   81,  356,  356,   48,   82,   19,   73,   82,
-      112,   87,   73,   87,   83,   78,   73,   81,   83,   78,
-       79,   13,   73,   78,   79,   81,   85,   81,   79,   78,
-       85,   82,   81,   81,   84,   84,   85,   82,   86,   85,
-       82,  112,   87,    0,   87,    0,   84,   86,  102,   86,
-
-        0,   84,   95,   86,   95,   95,    0,   85,  101,   96,
-       96,   85,  101,  113,  102,   84,   84,   85,   96,   86,
-       85,  104,   97,  103,   97,   97,  103,   84,   86,  102,
-       86,  107,   84,   97,   86,  104,  109,  110,  111,  101,
-      114,  125,  111,  101,  113,  102,  107,  110,  115,   96,
-      126,  109,  104,  121,  103,  121,  121,  103,  115,  357,
-      357,    0,  107,  139,   97,  144,  104,  109,  110,  111,
-        0,  114,  125,  111,    0,  132,  132,  107,  110,  115,
-      146,  126,  109,  128,  132,  128,  128,  133,  142,  133,
-      133,  135,  135,  147,  139,  142,  144,  148,  133,  147,
-
-      135,  136,  136,  362,  362,  136,  136,  140,  140,  141,
-      141,  146,    0,  141,  141,  132,  140,    0,  151,  142,
-      363,  363,  561,  561,  147,  152,  142,  153,  148,  133,
-      147,  135,  138,  138,  138,  138,  138,  138,  138,  138,
-      138,  138,  138,  138,  138,  138,  145,  140,  138,  151,
-        0,  138,  143,  138,  149,  154,  152,  145,  153,  143,
-      155,  157,  155,  158,  161,  143,  160,  162,  149,  163,
-      160,  165,  165,  164,  166,  154,  168,  145,  170,    0,
-      138,  138,  138,  143,  138,  149,  154,  164,  145,    0,
-      143,  155,  157,  155,  158,  161,  143,  160,  162,  149,
-
-      163,  160,  165,  165,  164,  166,  154,  168,  172,  170,
-      167,  138,  138,  138,  167,  169,  173,  174,  164,  169,
-      171,  175,  171,  171,  176,  177,  171,  178,  179,  180,
-      562,  562,  176,  182,  183,  184,  185,    0,  176,  172,
-      189,  167,  188,  188,  191,  167,  169,  173,  174,  196,
-      169,  171,  175,  171,  171,  176,  177,  171,  178,  179,
-      180,  181,  181,  176,  182,  183,  184,  185,  186,  176,
-      197,  189,  194,  188,  188,  191,  200,  193,  181,  193,
-      196,  195,  195,  195,  186,  193,  186,  198,  194,  195,
-      199,  186,  181,  181,  199,  198,  201,  202,  203,  186,
-
-      204,  197,  205,  194,  206,  208,  209,  200,  193,  181,
-      193,  210,  195,  195,  195,  186,  193,  186,  198,  194,
-      195,  199,  186,  213,    0,  199,  198,  201,  202,  203,
-      207,  204,  207,  205,  212,  206,  208,  209,  211,  214,
-      212,  211,  210,  216,  214,  215,  215,  217,  211,  218,
-      219,  215,  220,  221,  213,  215,  215,  223,  215,  565,
-      565,  207,  224,  207,  226,  212,  227,  228,  225,  211,
-      214,  212,  211,  231,  216,  214,  215,  215,  217,  211,
-      218,  219,  215,  220,  221,  229,  215,  215,  223,  215,
-      222,  222,  225,  224,    0,  226,  229,  227,  228,  225,
-
-      230,  233,  230,  222,  231,  232,  236,  238,  230,  239,
-      240,  241,  242,  232,  243,  244,  229,  245,  248,  249,
-      250,  222,  222,  225,  251,  232,  252,  229,  253,  254,
-      255,  230,  233,  230,  222,  256,  232,  236,  238,  230,
-      239,  240,  241,  242,  232,  243,  244,  257,  245,  248,
-      249,  250,  258,  259,  260,  251,  232,  252,  261,  253,
-      254,  255,  262,  263,  264,  258,  256,  266,  266,    0,
-      268,  269,  270,  271,  272,  271,  273,  274,  257,  275,
-      277,  279,  276,  258,  259,  260,  276,  280,  278,  261,
-      278,  278,  281,  262,  263,  264,  258,  282,  283,  284,
-
-      266,  268,  269,  270,  271,  272,  271,  273,  274,  281,
-      275,  277,  279,  276,  285,  286,  288,  276,  280,  278,
-      289,  278,  278,  281,  287,  291,  287,  292,  282,  283,
-      284,  293,  294,  295,  296,  297,  298,  299,  300,  301,
-      281,  302,  294,  303,  304,  285,  286,  288,  305,  302,
-      301,  289,  310,  310,    0,  287,  291,  287,  292,  566,
-      566,  310,  293,  294,  295,  296,  297,  298,  299,  300,
-      301,    0,  302,  294,  303,  304,  320,  312,  312,  305,
-      302,  301,  311,  321,  311,  311,  312,  314,  314,  322,
-      313,  313,  310,  311,  313,  313,  314,  315,  315,  323,
-
-      325,  315,  315,  324,  324,  326,  327,  320,  328,  330,
-      331,  333,  335,  336,  321,  338,  337,  312,  337,    0,
-      322,  354,  354,  358,  311,  354,  354,  314,    0,  340,
-      323,  325,  587,  587,  324,  324,  326,  327,  364,  328,
-      330,  331,  333,  335,  336,  365,  338,  337,  366,  337,
-      340,  367,  353,  353,  358,  360,  360,  368,  361,  361,
-      340,  353,  361,  361,  360,  369,  370,  371,  372,  364,
-      373,  374,  375,  376,  377,  378,  365,  379,  380,  366,
-      381,  382,  367,  383,  386,  384,  387,  389,  368,  390,
-      388,  391,  353,  384,  392,  360,  369,  370,  371,  372,
-
-      393,  373,  374,  375,  376,  377,  378,  388,  379,  380,
-      394,  381,  382,  396,  383,  386,  384,  387,  389,  397,
-      390,  388,  391,  398,  384,  392,  399,  400,  401,  402,
-      403,  393,  404,  405,  407,  406,  409,  402,  388,  410,
-      411,  394,  412,  413,  396,  406,  414,  415,  416,  417,
-      397,  418,  419,  420,  398,  418,  421,  399,  400,  401,
-      402,  403,  422,  404,  405,  407,  406,  409,  402,  424,
-      410,  411,  425,  412,  413,  423,  406,  414,  415,  416,
-      417,  426,  418,  419,  420,  423,  418,  421,  427,  428,
-      429,  430,  431,  422,  434,  589,  589,  436,    0,  438,
-
-      424,    0,  439,  425,  437,  441,  423,  442,  437,    0,
-      443,  444,  426,  590,  590,  445,  423,    0,  446,  427,
-      428,  429,  430,  431,  447,  434,  435,  435,  436,  435,
-      438,  435,  435,  439,  435,  437,  441,  435,  442,  437,
-      435,  443,  444,  448,  435,  435,  445,  451,  435,  446,
-        0,  452,    0,  454,    0,  447,  455,  435,  435,  456,
-      435,  457,  435,  435,  458,  435,  453,    0,  435,  459,
-      453,  435,  458,  460,  448,  435,  435,  461,  451,  435,
-      440,  440,  452,  440,  454,  440,  440,  455,  440,  463,
-      456,  440,  457,  465,  462,  458,  466,  453,  440,  440,
-
-      459,  453,  440,  458,  460,  462,  464,  467,  461,  468,
-      469,  440,  440,  464,  440,  470,  440,  440,  471,  440,
-      463,  472,  440,  473,  465,  462,  474,  466,  475,  440,
-      440,  476,  478,  440,  480,  479,  462,  464,  467,  481,
-      468,  469,  482,  483,  464,  484,  470,  479,  485,  471,
-      486,  488,  472,  489,  473,  490,  491,  474,  492,  475,
-      493,  494,  476,  478,  495,  480,  479,  496,  497,  498,
-      481,  499,  500,  482,  483,  501,  484,  500,  479,  485,
-      502,  486,  488,  505,  489,  508,  490,  491,  509,  492,
-      510,  493,  494,  511,  512,  495,  513,  514,  496,  497,
-
-      498,  515,  499,  500,  517,  518,  501,  519,  500,  520,
-      521,  502,  522,  523,  505,  524,  508,  525,  529,  509,
-      530,  510,  531,  532,  511,  512,  533,  513,  514,  534,
-      535,  536,  515,  537,  538,  517,  518,  539,  519,  541,
-      520,  521,  540,  522,  523,  542,  524,  543,  525,  529,
-      544,  530,  540,  531,  532,  546,  547,  533,  548,  549,
-      534,  535,  536,  550,  537,  538,  551,  552,  539,  553,
-      541,  554,  555,  540,  556,  567,  542,  568,  543,  563,
-      563,  544,  569,  540,  570,  571,  546,  547,  563,  548,
-      549,  564,  564,  572,  550,  564,  564,  551,  552,  573,
-
-      553,  574,  554,  555,  575,  556,  567,  576,  568,  577,
-      579,  580,  581,  569,  582,  570,  571,  583,  584,  563,
-      591,  592,  593,  594,  572,  595,  597,  598,  599,  600,
-      573,  601,  574,  602,  603,  575,  605,  607,  576,  608,
-      577,  579,  580,  581,  606,  582,  584,  609,  583,  584,
-      610,  591,  592,  593,  594,  611,  595,  597,  598,  599,
-      600,  612,  601,  606,  602,  603,  614,  605,  607,  613,
-      608,  613,  615,  616,  617,  606,  619,  620,  609,  621,
-      622,  610,  623,  624,  625,  626,  611,  627,  629,  630,
-      631,  632,  612,  633,  606,  634,  635,  614,  637,  638,
-
-      613,  639,  613,  615,  616,  617,  641,  619,  620,  642,
-      621,  622,  643,  623,  624,  625,  626,  644,  627,  629,
-      630,  631,  632,  645,  633,  646,  634,  635,  647,  637,
-      638,  648,  639,  649,  650,  652,  654,  641,  653,  655,
-      642,  656,  657,  643,  658,  653,  660,  662,  644,  663,
-      661,  664,  665,  666,  645,  667,  646,  661,  668,  647,
-      669,  670,  648,  672,  649,  650,  652,  654,  673,  653,
-      655,  674,  656,  657,  675,  658,  653,  660,  662,  671,
-      663,  661,  664,  665,  666,  671,  667,  676,  661,  668,
-      677,  669,  670,  678,  672,  679,  680,  671,  681,  673,
-
-      682,  683,  674,  684,  685,  675,  687,  686,  688,  689,
-      671,  690,  691,  686,  693,  695,  671,  697,  676,  696,
-      698,  677,  699,  696,  678,  686,  679,  680,  671,  681,
-      700,  682,  683,  701,  684,  685,  702,  687,  686,  688,
-      689,  703,  690,  691,  686,  693,  695,  704,  697,  705,
-      696,  698,  706,  699,  696,  707,  686,  708,  709,  710,
-      711,  700,  713,  712,  701,  714,  715,  702,  712,  716,
-      717,  718,  703,  719,  720,  721,  722,  723,  704,  724,
-      705,  725,  726,  706,  727,  728,  707,  729,  708,  709,
-      710,  711,  730,  713,  712,  731,  714,  715,  732,  712,
-
-      716,  717,  718,  733,  719,  720,  721,  722,  723,  734,
-      724,  735,  725,  726,  736,  727,  728,  737,  729,  738,
-      739,  740,  742,  730,  744,  740,  731,  745,  746,  732,
-      747,  748,  750,  751,  733,  752,  753,  754,  756,  757,
-      734,  758,  735,  759,  760,  736,  761,  762,  737,  763,
-      738,  739,  740,  742,  764,  744,  740,  765,  745,  746,
-      766,  747,  748,  750,  751,  767,  752,  753,  754,  756,
-      757,  769,  758,  770,  759,  760,  771,  761,  762,  772,
-      763,  773,  775,  777,  778,  764,  779,  780,  765,  781,
-      782,  766,  783,  784,  786,  787,  767,  790,  790,  791,
-
-      791,  793,  769,  794,  770,  795,  796,  771,  797,  798,
-      772,  799,  773,  775,  777,  778,  800,  779,  780,  801,
-      781,  782,  802,  783,  784,  786,  787,  803,  804,  805,
-      806,  807,  793,  808,  794,  813,  795,  796,  814,  797,
-      798,  816,  799,  817,  819,  820,  808,  800,  821,  822,
-      801,  823,  824,  802,  826,  827,  828,  827,  803,  804,
-      805,  806,  807,  829,  808,  830,  813,  831,  832,  814,
-      833,  835,  816,  836,  817,  819,  820,  837,  838,  821,
-      822,  841,  823,  824,  843,  826,  827,  828,  827,  844,
-      844,  846,  847,  848,  829,  849,  830,  850,  831,  832,
-
-      851,  833,  835,  853,  836,  854,  856,  859,  837,  838,
-      860,    0,  841,  862,  863,  843,    0,  865,  867,  868,
-      844,  844,  846,  847,  848,  869,  849,  865,  850,  861,
-      870,  851,  873,  875,  853,  876,  854,  856,  859,  861,
-        0,  860,  861,  861,  862,  863,  861,  861,  865,  867,
-      868,  877,  878,  879,  880,  881,  869,  882,  865,  883,
-      861,  870,  884,  873,  875,  871,  876,  885,  871,  886,
-      861,  871,  887,  861,  861,  871,  888,  861,  861,  889,
-      871,  890,  877,  878,  879,  880,  881,  891,  882,  892,
-      883,  893,  894,  884,  896,  897,  871,  898,  885,  871,
-
-      886,  899,  871,  887,  900,  901,  871,  888,  902,  903,
-      889,  871,  890,  904,  905,  906,  907,  908,  891,  910,
-      892,  912,  893,  894,  913,  896,  897,  914,  898,  915,
-      916,  917,  899,  918,  919,  900,  901,  920,  921,  902,
-      903,  922,  923,  924,  904,  905,  906,  907,  908,  925,
-      910,  926,  912,  927,  928,  913,  929,  930,  914,  932,
-      915,  916,  917,  933,  918,  919,  931,  934,  920,  921,
-      935,  936,  922,  923,  924,  931,  937,  938,  936,  939,
-      925,  940,  926,  941,  927,  928,  942,  929,  930,  943,
-      932,  944,  948,  947,  933,  947,  949,  931,  934,  950,
-
-      951,  935,  936,  952,  953,  955,  931,  937,  938,  936,
-      939,  956,  940,  957,  941,  958,  960,  942,  961,  962,
-      943,  964,  944,  948,  947,  962,  947,  949,  965,  966,
-      950,  951,  967,  970,  952,  953,  955,  971,  965,  975,
-      976,  977,  956,  979,  957,  980,  958,  960,  981,  961,
-      962,  982,  964,  983,  984,  986,  962,  990,  977,  965,
-      966,  991,  992,  967,  970,  988,  993,  988,  971,  965,
-      975,  976,  977,  994,  979,  993,  980,  995,  996,  981,
-      997,  998,  982,  999,  983,  984,  986, 1000,  990,  977,
-     1001, 1002,  991,  992, 1003, 1004,  988,  993,  988, 1005,
-
-     1006, 1007, 1008, 1010,  994, 1011,  993, 1012,  995,  996,
-     1014,  997,  998, 1013,  999, 1015, 1016, 1017, 1000, 1018,
-     1020, 1001, 1002, 1023, 1025, 1003, 1004, 1026, 1027, 1028,
-     1005, 1006, 1007, 1008, 1010, 1030, 1011, 1013, 1012, 1031,
-     1032, 1014, 1033, 1034, 1013, 1036, 1015, 1016, 1017, 1037,
-     1018, 1020, 1038, 1039, 1023, 1025, 1041, 1043, 1026, 1027,
-     1028, 1045, 1047, 1048, 1049, 1052, 1030, 1053, 1054, 1055,
-     1031, 1032, 1056, 1033, 1034, 1057, 1036, 1059, 1060, 1061,
-     1037, 1062, 1063, 1038, 1039, 1064, 1065, 1041, 1043, 1066,
-     1067, 1068, 1045, 1047, 1048, 1049, 1052, 1069, 1053, 1054,
-
-     1055, 1070, 1072, 1056, 1073, 1069, 1057, 1074, 1059, 1060,
-     1061, 1075, 1062, 1063, 1076, 1077, 1064, 1065, 1078, 1079,
-     1066, 1067, 1068, 1080, 1081, 1082, 1083, 1084, 1069, 1085,
-     1086, 1087, 1070, 1072, 1088, 1073, 1069, 1090, 1074, 1092,
-     1093, 1094, 1075, 1095, 1096, 1076, 1077, 1097, 1098, 1078,
-     1079, 1099, 1100, 1101, 1080, 1081, 1082, 1083, 1084, 1102,
-     1085, 1086, 1087, 1103, 1104, 1088, 1105, 1106, 1090, 1109,
-     1092, 1093, 1094, 1111, 1095, 1096, 1112, 1113, 1097, 1098,
-     1114, 1115, 1099, 1100, 1101, 1116, 1117, 1118, 1123, 1124,
-     1102, 1125, 1126, 1127, 1103, 1104, 1128, 1105, 1106, 1129,
-
-     1109, 1130, 1131, 1132, 1111, 1133, 1135, 1112, 1113, 1137,
-     1138, 1114, 1115, 1139, 1140, 1141, 1116, 1117, 1118, 1123,
-     1124, 1142, 1125, 1126, 1127, 1143, 1144, 1128, 1145, 1148,
-     1129, 1151, 1130, 1131, 1132, 1152, 1133, 1135, 1153, 1154,
-     1137, 1138, 1144, 1155, 1139, 1140, 1141, 1156, 1157, 1158,
-     1159, 1160, 1142, 1161, 1162, 1164, 1143, 1144, 1166, 1145,
-     1148, 1167, 1151, 1169, 1170, 1171, 1152, 1172, 1173, 1153,
-     1154, 1174, 1175, 1144, 1155, 1177, 1180, 1181, 1156, 1157,
-     1158, 1159, 1160, 1182, 1161, 1162, 1164, 1183, 1184, 1166,
-     1185, 1186, 1167, 1188, 1169, 1170, 1171, 1189, 1172, 1173,
-
-     1190, 1193, 1174, 1175, 1194, 1195, 1177, 1180, 1181, 1196,
-     1197, 1198, 1199, 1200, 1182, 1201, 1203, 1204, 1183, 1184,
-     1205, 1185, 1186, 1206, 1188, 1208, 1210, 1211, 1189, 1212,
-     1214, 1190, 1193, 1216, 1217, 1194, 1195, 1218, 1219, 1220,
-     1196, 1197, 1198, 1199, 1200, 1221, 1201, 1203, 1204, 1222,
-     1223, 1205, 1224, 1226, 1206, 1227, 1208, 1210, 1211, 1228,
-     1212, 1214, 1230, 1231, 1216, 1217, 1232, 1233, 1218, 1219,
-     1220, 1234, 1235, 1236, 1237, 1238, 1221, 1240, 1241, 1243,
-     1222, 1223, 1244, 1224, 1226, 1245, 1227, 1246, 1247, 1248,
-     1228, 1249, 1250, 1230, 1231, 1252, 1253, 1232, 1233, 1254,
-
-     1255, 1256, 1234, 1235, 1236, 1237, 1238, 1258, 1240, 1241,
-     1243, 1259, 1260, 1244, 1261, 1262, 1245, 1263, 1246, 1247,
-     1248, 1264, 1249, 1250, 1266, 1267, 1252, 1253, 1268, 1269,
-     1254, 1255, 1256, 1270, 1272, 1274, 1272, 1275, 1258, 1276,
-     1278,    0, 1259, 1260, 1280, 1261, 1262,    0, 1263, 1282,
-     1284, 1285, 1264, 1286, 1287, 1266, 1267, 1275, 1288, 1268,
-     1269, 1277, 1277, 1289, 1270, 1272, 1274, 1272, 1275, 1290,
-     1276, 1278, 1277, 1291, 1277, 1280, 1292, 1293, 1277, 1294,
-     1282, 1284, 1285, 1295, 1286, 1287, 1296, 1297, 1275, 1288,
-     1298, 1299, 1277, 1277, 1289, 1300, 1301, 1302, 1303, 1304,
-
-     1290, 1306, 1307, 1277, 1291, 1277, 1308, 1292, 1293, 1277,
-     1294, 1305, 1309, 1305, 1295, 1310, 1311, 1296, 1297, 1312,
-     1313, 1298, 1299, 1314, 1315, 1316, 1300, 1301, 1302, 1303,
-     1304, 1317, 1306, 1307, 1318, 1319, 1320, 1308, 1321, 1322,
-     1323, 1324, 1305, 1309, 1305, 1326, 1310, 1311, 1328, 1330,
-     1312, 1313, 1332, 1333, 1314, 1315, 1316, 1334, 1335, 1338,
-     1325, 1325, 1317, 1339, 1340, 1318, 1319, 1320, 1341, 1321,
-     1322, 1323, 1324, 1325, 1343, 1344, 1326, 1325, 1345, 1328,
-     1330, 1346, 1347, 1332, 1333, 1348, 1349, 1350, 1334, 1335,
-     1338, 1325, 1325, 1351, 1339, 1340, 1353, 1354, 1355, 1341,
-
-     1356, 1357, 1358, 1359, 1325, 1343, 1344, 1360, 1325, 1345,
-     1361, 1362, 1346, 1347, 1363, 1365, 1348, 1349, 1350, 1366,
-     1368, 1369, 1370, 1371, 1351, 1372, 1373, 1353, 1354, 1355,
-     1374, 1356, 1357, 1358, 1359, 1375, 1376, 1377, 1360, 1378,
-     1379, 1361, 1362, 1380, 1381, 1363, 1365, 1382, 1383, 1384,
-     1366, 1368, 1369, 1370, 1371, 1385, 1372, 1373, 1386, 1387,
-     1388, 1374, 1392, 1393, 1394, 1395, 1375, 1376, 1377, 1396,
-     1378, 1379, 1397, 1398, 1380, 1381, 1399, 1400, 1382, 1383,
-     1384, 1403, 1404, 1405, 1406, 1407, 1385, 1408, 1409, 1386,
-     1387, 1388, 1410, 1392, 1393, 1394, 1395, 1411, 1412, 1413,
-
-     1396, 1414, 1416, 1397, 1398, 1418, 1412, 1399, 1400, 1419,
-     1421, 1422, 1403, 1404, 1405, 1406, 1407, 1414, 1408, 1409,
-     1423, 1425, 1426, 1410, 1427, 1428, 1430, 1432, 1411, 1412,
-     1413, 1434, 1414, 1416, 1435, 1436, 1418, 1412, 1437, 1438,
-     1419, 1421, 1422, 1439, 1440, 1441, 1443, 1445, 1414, 1446,
-     1447, 1423, 1425, 1426, 1450, 1427, 1428, 1430, 1432, 1451,
-     1452, 1453, 1434, 1454, 1456, 1435, 1436, 1457, 1459, 1437,
-     1438, 1464, 1467, 1469, 1439, 1440, 1441, 1443, 1445, 1471,
-     1446, 1447, 1473, 1475, 1476, 1450, 1477, 1479, 1480, 1482,
-     1451, 1452, 1453, 1483, 1454, 1456, 1484, 1486, 1457, 1459,
-
-     1489, 1493, 1464, 1467, 1469, 1494, 1495, 1496, 1498, 1499,
-     1471, 1500, 1501, 1473, 1475, 1476, 1502, 1477, 1479, 1480,
-     1482, 1503, 1504, 1505, 1483, 1506, 1507, 1484, 1486, 1508,
-     1510, 1489, 1493, 1511, 1512, 1513, 1494, 1495, 1496, 1498,
-     1499, 1514, 1500, 1501, 1515, 1516, 1517, 1502, 1518, 1520,
-     1521, 1522, 1503, 1504, 1505, 1523, 1506, 1507, 1524, 1525,
-     1508, 1510, 1526, 1527, 1511, 1512, 1513, 1528, 1529, 1530,
-     1531, 1532, 1514, 1533, 1534, 1515, 1516, 1517, 1535, 1518,
-     1520, 1521, 1522, 1536, 1537, 1538, 1523, 1539, 1540, 1524,
-     1525, 1541, 1542, 1526, 1527, 1545, 1546, 1547, 1528, 1529,
-
-     1530, 1531, 1532, 1548, 1533, 1534, 1549, 1550, 1554, 1535,
-     1556, 1558, 1560, 1561, 1536, 1537, 1538, 1562, 1539, 1540,
-     1563, 1565, 1541, 1542, 1567, 1568, 1545, 1546, 1547, 1569,
-     1571, 1572, 1575, 1576, 1548, 1577, 1580, 1549, 1550, 1554,
-     1581, 1556, 1558, 1560, 1561, 1583, 1587, 1588, 1562, 1589,
-     1590, 1563, 1565, 1591, 1592, 1567, 1568, 1595, 1596, 1597,
-     1569, 1571, 1572, 1575, 1576, 1598, 1577, 1580, 1599, 1600,
-     1601, 1581, 1602, 1604, 1605, 1606, 1583, 1587, 1588, 1607,
-     1589, 1590, 1608, 1609, 1591, 1592, 1610, 1611, 1595, 1596,
-     1597, 1612, 1614, 1615, 1616, 1617, 1598, 1618, 1619, 1599,
-
-     1600, 1601, 1620, 1602, 1604, 1605, 1606, 1621, 1622, 1623,
-     1607, 1624, 1625, 1608, 1609, 1627, 1630, 1610, 1611, 1632,
-     1635, 1637, 1612, 1614, 1615, 1616, 1617, 1638, 1618, 1619,
-     1639, 1640, 1642, 1620, 1646, 1648, 1649, 1650, 1621, 1622,
-     1623, 1652, 1624, 1625, 1653, 1654, 1627, 1630, 1640, 1655,
-     1632, 1635, 1637, 1657, 1658, 1659, 1660, 1661, 1638, 1666,
-     1667, 1639, 1640, 1642, 1668, 1646, 1648, 1649, 1650, 1671,
-     1674, 1675, 1652, 1677, 1679, 1653, 1654, 1680, 1681, 1640,
-     1655, 1682, 1683, 1684, 1657, 1658, 1659, 1660, 1661, 1685,
-     1666, 1667, 1686, 1687, 1689, 1668, 1691, 1693, 1695, 1696,
-
-     1671, 1674, 1675, 1697, 1677, 1679, 1698, 1700, 1680, 1681,
-     1702, 1704, 1682, 1683, 1684, 1705, 1707, 1709, 1710, 1711,
-     1685, 1713, 1714, 1686, 1687, 1689, 1715, 1691, 1693, 1695,
-     1696, 1717, 1718, 1720, 1697, 1721, 1725, 1698, 1700, 1727,
-     1728, 1702, 1704, 1729, 1730, 1731, 1705, 1707, 1709, 1710,
-     1711, 1732, 1713, 1714, 1733, 1734, 1735, 1715, 1737, 1738,
-     1739, 1742, 1717, 1718, 1720, 1743, 1721, 1725, 1745, 1746,
-     1727, 1728, 1748, 1752, 1729, 1730, 1731, 1753, 1754, 1755,
-     1757, 1758, 1732, 1759, 1760, 1733, 1734, 1735, 1761, 1737,
-     1738, 1739, 1742, 1763, 1765, 1766, 1743, 1767, 1768, 1745,
-
-     1746, 1770, 1773, 1748, 1752, 1776, 1777, 1780, 1753, 1754,
-     1755, 1757, 1758, 1781, 1759, 1760, 1784, 1785, 1786, 1761,
-     1788, 1789, 1790, 1791, 1763, 1765, 1766, 1793, 1767, 1768,
-     1794, 1795, 1770, 1773, 1796, 1799, 1776, 1777, 1780, 1800,
-     1801, 1803, 1804,    0, 1781,    0,    0, 1784, 1785, 1786,
-        0, 1788, 1789, 1790, 1791,    0,    0,    0, 1793,    0,
-        0, 1794, 1795,    0,    0, 1796, 1799,    0,    0,    0,
-     1800, 1801, 1803, 1804, 1807, 1807, 1807, 1807, 1807, 1807,
-     1807, 1807, 1807, 1808, 1808, 1808, 1808, 1808, 1808, 1808,
-     1808, 1808, 1809,    0, 1809, 1809, 1809, 1809, 1809, 1809,
-
-     1809, 1810,    0, 1810, 1810, 1810, 1810, 1810, 1810, 1810,
-     1811, 1811, 1812, 1812, 1812, 1812, 1812, 1812, 1812, 1812,
-     1812, 1813, 1813, 1813, 1813, 1813, 1813, 1813, 1813, 1813,
-     1814,    0, 1814, 1815, 1815, 1815, 1815, 1815, 1815, 1815,
-     1815, 1815, 1816, 1816, 1816, 1816, 1816, 1816, 1816, 1816,
-     1816, 1817, 1817, 1817, 1817, 1817, 1817, 1817, 1817, 1817,
-     1818, 1818, 1818, 1818, 1818, 1818, 1818, 1818, 1818, 1819,
-     1819, 1819,    0,    0, 1819, 1819,    0, 1819, 1820, 1820,
-     1820, 1820, 1820, 1820, 1820, 1820, 1820, 1821,    0,    0,
-     1821, 1821,    0, 1821, 1822, 1822, 1822,    0, 1822, 1822,
-
-     1822, 1822, 1822, 1823, 1823, 1823, 1823,    0, 1823, 1823,
-     1823, 1823, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
-     1824, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806,
-     1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806,
-     1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806,
-     1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806,
-     1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806,
-     1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806,
-     1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806,
-     1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806, 1806,
-
-     1806, 1806, 1806, 1806
+        7,    7,    7,    7,    7,    7,   22,   22,   22,   22,
+       22,   22,   22,   22,   22,   22,   22,   22,   22,   22,
+       22,   22,   22,   22,   22,   22,   22,   22,   22,   22,
+
+       22,   22,   22,   22,   22,   22,   22,   22,   22,   22,
+       22,   22,   22,   22,   22,   22,   22,   22,   22,   22,
+       22,   22,   22,   22,   22,   22,   22,   22,   22,   22,
+       22,   22,   26,   76,   76,   67,   26,   67,   67,   27,
+       26,   27,   31,  112,   27,   27,   31,   74,   27,   26,
+       31,   27,   26,  112,   27,   27,   29,   29,   29,   31,
+       33,   33,   29,  763,   74,   52,   52,   33,   29,   36,
+       37,   36,   52,   36,   37,   79,  147,   36,   37,   79,
+       36,   39,   39,   36,   40,  101,   36,  147,   40,   39,
+       37,   39,   40,   39,   37,   40,   39,   39,   40,   42,
+
+       68,   40,   68,   42,   47,   47,  101,   42,   47,   68,
+       47,  764,   47,   42,   43,   43,   43,   47,   44,   43,
+       43,   83,   44,  102,   43,   83,   44,  102,   43,   45,
+      103,   43,   44,   43,  103,   44,   43,   70,   45,   70,
+       45,  109,   44,  765,   45,  111,   70,   71,   45,   70,
+       71,   71,   70,   72,   72,   73,  109,   78,   81,   73,
+      111,   78,   82,   73,   72,   78,   81,   99,   81,   73,
+       82,   78,   86,   81,   81,   99,   82,   84,   84,   82,
+       85,   86,  105,   86,   85,  105,  106,   86,  113,   84,
+       85,  216,  113,   85,   84,   89,  216,   89,   89,   90,
+
+      106,   90,   90,   95,  149,   95,   95,   96,   96,   97,
+      149,   97,   97,  121,  127,  121,  121,  127,  132,  132,
+      128,   96,  128,  128,  133,   97,  133,  133,  135,  135,
+      767,  127,  132,  136,  136,  140,  140,  136,  136,  144,
+      133,  145,  135,  141,  141,  145,  144,  141,  141,  140,
+      151,  156,  145,  157,  166,  157,  162,  296,  145,  169,
+      162,  167,  167,  169,  151,  171,  178,  296,  166,  171,
+      173,  156,  173,  173,  178,  188,  173,  183,  183,  190,
+      178,  196,  201,  183,  190,  190,  201,  195,  200,  195,
+      195,  188,  768,  188,  183,  195,  200,  196,  188,  197,
+
+      197,  197,  209,  213,  209,  214,  213,  197,  217,  217,
+      227,  214,  231,  213,  217,  224,  224,  234,  217,  217,
+      564,  217,  232,  231,  232,  234,  250,  250,  224,  262,
+      232,  270,  278,  250,  227,  564,  278,  234,  270,  273,
+      303,  273,  262,  280,  270,  280,  280,  283,  304,  312,
+      312,  303,  313,  283,  313,  313,  304,  314,  314,  316,
+      316,  315,  315,  312,  283,  315,  315,  324,  313,  334,
+      326,  314,  326,  316,  317,  317,  386,  324,  317,  317,
+      332,  332,  334,  345,  386,  345,  354,  354,  355,  355,
+      356,  356,  355,  355,  357,  357,  358,  358,  361,  361,
+
+      354,  362,  362,  363,  363,  362,  362,  364,  364,  390,
+      404,  408,  361,  420,  426,  442,  458,  420,  404,  442,
+      458,  408,  484,  463,  426,  562,  390,  440,  440,  467,
+      440,  463,  440,  440,  484,  440,  466,  469,  440,  769,
+      467,  440,  505,  562,  469,  440,  440,  505,  612,  440,
+      445,  445,  546,  445,  571,  445,  445,  571,  445,  770,
+      466,  445,  546,  565,  565,  566,  566,  612,  445,  445,
+      567,  567,  445,  568,  568,  569,  569,  568,  568,  570,
+      570,  572,  705,  572,  567,  573,  705,  573,  592,  592,
+      594,  594,  595,  595,  619,  660,  619,  669,  722,  680,
+
+      695,  771,  660,  722,  669,  680,  695,  750,  772,  773,
+      774,  750,  775,  776,  777,  778,  780,  680,  695,  781,
+      782,  783,  784,  786,  788,  789,  790,  791,  792,  793,
+      794,  796,  797,  800,  800,  801,  801,  802,  805,  806,
+      807,  808,  809,  810,  811,  812,  813,  814,  815,  816,
+      817,  818,  819,  820,  823,  802,  825,  826,  828,  829,
+      831,  832,  833,  834,  835,  836,  838,  839,  840,  839,
+      841,  842,  843,  844,  845,  847,  848,  849,  850,  853,
+      855,  856,  856,  858,  859,  860,  861,  862,  863,  865,
+      866,  868,  869,  872,  873,  874,  875,  876,  878,  881,
+
+      879,  882,  883,  884,  887,  874,  889,  890,  874,  874,
+      879,  885,  874,  874,  885,  891,  892,  885,  893,  894,
+      895,  885,  896,  897,  898,  899,  885,  900,  901,  902,
+      903,  904,  905,  906,  907,  908,  909,  911,  912,  913,
+      914,  915,  916,  917,  918,  919,  920,  921,  922,  923,
+      925,  927,  928,  929,  930,  931,  932,  933,  934,  935,
+      936,  937,  938,  939,  940,  941,  942,  943,  944,  945,
+      946,  947,  948,  949,  950,  951,  952,  953,  954,  955,
+      947,  956,  957,  952,  958,  959,  960,  963,  964,  963,
+      965,  966,  967,  968,  969,  971,  972,  973,  974,  976,
+
+      977,  978,  980,  981,  982,  983,  986,  978,  987,  988,
+      992,  993,  994,  981,  996,  997,  998,  999, 1000, 1001,
+     1003, 1005, 1007, 1005, 1008, 1009, 1010, 1011, 1012,  994,
+     1013, 1014, 1015, 1016, 1017, 1010, 1018, 1019, 1020, 1015,
+     1021, 1022, 1023, 1024, 1025, 1026, 1027, 1029, 1030, 1031,
+     1032, 1033, 1034, 1035, 1036, 1037, 1039, 1042, 1044, 1045,
+     1046, 1047, 1049, 1050, 1051, 1052, 1053, 1055, 1056, 1057,
+     1058, 1060, 1062, 1064, 1066, 1067, 1068, 1069, 1072, 1073,
+     1074, 1075, 1076, 1077, 1079, 1080, 1081, 1082, 1083, 1084,
+     1085, 1086, 1087, 1088, 1089, 1090, 1091, 1094, 1095, 1096,
+
+     1097, 1098, 1099, 1090, 1100, 1101, 1102, 1103, 1104, 1105,
+     1106, 1107, 1108, 1109, 1110, 1112, 1114, 1115, 1116, 1117,
+     1118, 1119, 1120, 1121, 1122, 1123, 1124, 1125, 1126, 1127,
+     1128, 1131, 1132, 1133, 1134, 1135, 1136, 1137, 1138, 1139,
+     1140, 1145, 1146, 1147, 1148, 1149, 1150, 1151, 1152, 1153,
+     1154, 1155, 1156, 1158, 1160, 1161, 1162, 1163, 1164, 1165,
+     1166, 1167, 1168, 1171, 1174, 1175, 1176, 1177, 1178, 1179,
+     1180, 1181, 1182, 1183, 1184, 1185, 1186, 1167, 1188, 1190,
+     1191, 1193, 1194, 1195, 1196, 1197, 1198, 1199, 1201, 1202,
+     1205, 1206, 1207, 1208, 1209, 1210, 1211, 1212, 1214, 1215,
+
+     1216, 1218, 1219, 1220, 1221, 1222, 1223, 1224, 1225, 1226,
+     1227, 1229, 1230, 1231, 1232, 1234, 1236, 1237, 1238, 1240,
+     1242, 1243, 1244, 1245, 1246, 1247, 1248, 1249, 1250, 1251,
+     1253, 1254, 1255, 1256, 1258, 1259, 1260, 1261, 1262, 1263,
+     1264, 1265, 1266, 1268, 1269, 1271, 1272, 1273, 1274, 1275,
+     1276, 1277, 1278, 1280, 1281, 1282, 1283, 1284, 1286, 1287,
+     1288, 1289, 1290, 1291, 1292, 1294, 1295, 1296, 1297, 1298,
+     1300, 1302, 1300, 1303, 1304, 1305, 1305, 1306, 1308, 1309,
+     1311, 1313, 1314, 1315, 1316, 1317, 1305, 1318, 1305, 1319,
+     1320, 1321, 1305, 1303, 1322, 1323, 1324, 1325, 1326, 1327,
+
+     1328, 1329, 1330, 1331, 1332, 1333, 1334, 1335, 1334, 1336,
+     1337, 1338, 1339, 1340, 1341, 1342, 1343, 1344, 1345, 1346,
+     1347, 1348, 1349, 1350, 1351, 1352, 1353, 1354, 1355, 1355,
+     1356, 1359, 1361, 1362, 1364, 1365, 1366, 1367, 1369, 1370,
+     1371, 1355, 1372, 1373, 1375, 1355, 1376, 1377, 1378, 1379,
+     1380, 1381, 1382, 1383, 1385, 1386, 1387, 1388, 1389, 1390,
+     1392, 1393, 1394, 1395, 1396, 1398, 1399, 1400, 1402, 1403,
+     1404, 1405, 1406, 1407, 1408, 1409, 1410, 1411, 1412, 1413,
+     1414, 1415, 1416, 1417, 1418, 1419, 1420, 1421, 1422, 1426,
+     1427, 1428, 1429, 1430, 1431, 1432, 1433, 1434, 1437, 1438,
+
+     1439, 1440, 1441, 1442, 1443, 1444, 1445, 1446, 1447, 1448,
+     1450, 1451, 1453, 1454, 1456, 1446, 1457, 1458, 1460, 1461,
+     1462, 1463, 1465, 1467, 1469, 1448, 1470, 1471, 1472, 1473,
+     1474, 1475, 1476, 1478, 1480, 1481, 1482, 1486, 1487, 1488,
+     1489, 1490, 1492, 1493, 1495, 1498, 1501, 1504, 1505, 1507,
+     1509, 1511, 1513, 1514, 1515, 1517, 1518, 1520, 1521, 1522,
+     1524, 1527, 1529, 1532, 1533, 1534, 1535, 1537, 1538, 1539,
+     1540, 1541, 1542, 1543, 1544, 1545, 1546, 1547, 1549, 1550,
+     1551, 1552, 1553, 1554, 1555, 1556, 1557, 1559, 1560, 1561,
+     1562, 1563, 1564, 1565, 1566, 1567, 1568, 1569, 1570, 1571,
+
+     1572, 1573, 1574, 1575, 1576, 1577, 1578, 1579, 1580, 1581,
+     1582, 1585, 1586, 1587, 1588, 1589, 1590, 1594, 1596, 1598,
+     1600, 1601, 1602, 1603, 1605, 1607, 1608, 1609, 1610, 1611,
+     1613, 1614, 1617, 1618, 1619, 1622, 1623, 1625, 1630, 1631,
+     1632, 1633, 1634, 1635, 1638, 1639, 1640, 1641, 1642, 1643,
+     1644, 1645, 1647, 1648, 1649, 1650, 1651, 1652, 1653, 1654,
+     1655, 1657, 1658, 1659, 1660, 1661, 1662, 1663, 1664, 1665,
+     1666, 1667, 1668, 1669, 1671, 1674, 1676, 1679, 1681, 1682,
+     1683, 1684, 1686, 1690, 1694, 1695, 1696, 1698, 1699, 1700,
+     1701, 1703, 1704, 1705, 1706, 1707, 1712, 1713, 1684, 1714,
+
+     1717, 1720, 1721, 1723, 1725, 1726, 1727, 1728, 1729, 1730,
+     1731, 1732, 1733, 1735, 1738, 1740, 1742, 1743, 1744, 1745,
+     1747, 1749, 1751, 1752, 1754, 1756, 1757, 1758, 1760, 1761,
+     1762, 1764, 1765, 1767, 1768, 1772, 1774, 1775, 1776, 1777,
+     1778, 1779, 1780, 1781, 1782, 1784, 1785, 1786, 1789, 1790,
+     1792, 1793, 1795, 1799, 1800, 1801, 1802, 1804, 1805, 1806,
+     1807, 1808, 1810, 1812, 1813, 1814, 1815, 1817, 1820, 1823,
+     1824, 1827, 1828, 1831, 1832, 1833, 1835, 1836, 1837, 1838,
+     1840, 1841, 1842, 1843, 1846, 1847, 1848, 1850, 1851, 1854,
+     1854, 1854, 1854, 1854, 1854, 1854, 1854, 1854, 1855, 1855,
+
+     1855, 1855, 1855, 1855, 1855, 1855, 1855, 1856, 1856, 1856,
+     1856, 1856, 1856, 1856, 1856, 1856, 1857,  757, 1857, 1857,
+     1857, 1857, 1857, 1857, 1857, 1858,  756, 1858, 1858, 1858,
+     1858, 1858, 1858, 1858, 1859, 1859, 1860, 1860, 1860, 1860,
+     1860, 1860, 1860, 1860, 1860, 1861,  755, 1861, 1862, 1862,
+     1862, 1862, 1862, 1862, 1862, 1862, 1862, 1863, 1863, 1863,
+     1863, 1863, 1863, 1863, 1863, 1863, 1864, 1864, 1864, 1864,
+     1864, 1864, 1864, 1864, 1864, 1865, 1865, 1865, 1865, 1865,
+     1865, 1865, 1865, 1865, 1866, 1866, 1866,  754,  752, 1866,
+     1866,  749, 1866, 1867, 1867, 1867, 1867, 1867, 1867, 1867,
+
+     1867, 1867, 1868,  748,  747, 1868, 1868,  746, 1868, 1869,
+     1869, 1869,  745, 1869, 1869, 1869, 1869, 1869, 1870, 1870,
+     1870, 1870,  744, 1870, 1870, 1870, 1870, 1871, 1871, 1871,
+     1871, 1871, 1871, 1871, 1871, 1871,  743,  742,  741,  740,
+      739,  738,  737,  736,  735,  734,  733,  732,  731,  730,
+      729,  728,  727,  726,  725,  724,  723,  721,  720,  719,
+      718,  717,  716,  715,  714,  713,  712,  711,  710,  709,
+      708,  707,  706,  704,  702,  700,  699,  698,  697,  696,
+      694,  693,  692,  691,  690,  689,  688,  687,  686,  685,
+      684,  683,  682,  681,  679,  678,  677,  676,  675,  674,
+
+      673,  672,  670,  668,  666,  665,  664,  663,  662,  661,
+      659,  657,  656,  655,  654,  653,  652,  651,  650,  649,
+      648,  647,  646,  645,  644,  643,  641,  640,  639,  638,
+      637,  636,  635,  633,  632,  631,  630,  629,  628,  627,
+      626,  625,  623,  622,  621,  620,  618,  617,  616,  615,
+      614,  613,  611,  609,  608,  607,  606,  605,  604,  603,
+      602,  601,  600,  599,  598,  597,  596,  591,  590,  589,
+      588,  587,  585,  584,  583,  582,  581,  580,  579,  578,
+      577,  576,  575,  574,  563,  561,  560,  559,  558,  557,
+      556,  555,  554,  553,  552,  551,  550,  549,  548,  547,
+
+      545,  544,  543,  542,  541,  540,  539,  538,  537,  536,
+      535,  533,  532,  531,  530,  529,  528,  527,  526,  525,
+      523,  522,  521,  520,  519,  518,  517,  515,  514,  511,
+      508,  507,  506,  504,  503,  502,  501,  500,  499,  498,
+      497,  496,  495,  494,  493,  491,  490,  489,  488,  487,
+      486,  485,  483,  481,  480,  479,  478,  477,  476,  475,
+      474,  473,  472,  471,  470,  468,  465,  464,  462,  461,
+      460,  459,  457,  456,  455,  453,  452,  451,  450,  449,
+      448,  447,  446,  444,  443,  441,  439,  438,  435,  434,
+      433,  432,  431,  430,  429,  428,  427,  425,  424,  423,
+
+      422,  421,  419,  418,  417,  416,  415,  414,  413,  412,
+      411,  409,  407,  406,  405,  403,  402,  401,  400,  399,
+      398,  396,  395,  394,  393,  392,  391,  389,  388,  385,
+      384,  383,  382,  381,  380,  379,  378,  377,  376,  375,
+      374,  373,  372,  371,  370,  369,  368,  367,  366,  365,
+      359,  350,  348,  346,  344,  343,  341,  339,  338,  336,
+      335,  333,  331,  330,  329,  328,  325,  322,  311,  309,
+      307,  306,  305,  302,  301,  300,  299,  298,  297,  295,
+      294,  293,  292,  290,  289,  288,  287,  286,  285,  284,
+      282,  281,  279,  277,  276,  275,  274,  272,  271,  269,
+
+      268,  267,  266,  265,  264,  263,  261,  260,  259,  258,
+      257,  256,  255,  254,  253,  252,  249,  248,  247,  246,
+      245,  244,  243,  242,  241,  240,  238,  235,  233,  230,
+      229,  228,  226,  225,  223,  222,  221,  220,  219,  218,
+      215,  212,  211,  210,  208,  207,  206,  205,  204,  203,
+      202,  199,  198,  193,  191,  187,  186,  185,  184,  182,
+      181,  180,  179,  177,  176,  175,  174,  172,  170,  168,
+      165,  164,  163,  160,  159,  155,  154,  153,  150,  148,
+      146,  142,  139,  137,  131,  130,  126,  125,  123,  122,
+      118,  117,  116,  115,  114,  110,  108,  107,  100,   98,
+
+       94,   93,   92,   91,   80,   75,   69,   66,   65,   64,
+       62,   61,   60,   59,   57,   56,   55,   54,   53,   41,
+       34,   24,   19,   13, 1853, 1853, 1853, 1853, 1853, 1853,
+     1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853,
+     1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853,
+     1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853,
+     1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853,
+     1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853, 1853,
+     1853
     } ;
 
 static yy_state_type yy_last_accepting_state;
@@ -2085,7 +1671,7 @@ char path[MS_MAXPATHLEN];
 
 
 
-#line 2089 "maplexer.c"
+#line 1675 "maplexer.c"
 
 #define INITIAL 0
 #define URL_VARIABLE 1
@@ -2100,35 +1686,6 @@ char path[MS_MAXPATHLEN];
 
 static int yy_init_globals (void );
 
-/* Accessor methods to globals.
-   These are made visible to non-reentrant scanners for convenience. */
-
-int msyylex_destroy (void );
-
-int msyyget_debug (void );
-
-void msyyset_debug (int debug_flag  );
-
-YY_EXTRA_TYPE msyyget_extra (void );
-
-void msyyset_extra (YY_EXTRA_TYPE user_defined  );
-
-FILE *msyyget_in (void );
-
-void msyyset_in  (FILE * in_str  );
-
-FILE *msyyget_out (void );
-
-void msyyset_out  (FILE * out_str  );
-
-int msyyget_leng (void );
-
-char *msyyget_text (void );
-
-int msyyget_lineno (void );
-
-void msyyset_lineno (int line_number  );
-
 /* Macros after this point can all be overridden by user definitions in
  * section 1.
  */
@@ -2163,12 +1720,7 @@ static int input (void );
 
 /* Amount of stuff to slurp up with each read. */
 #ifndef YY_READ_BUF_SIZE
-#ifdef __ia64__
-/* On IA-64, the buffer size is 16k, not 8k */
-#define YY_READ_BUF_SIZE 16384
-#else
 #define YY_READ_BUF_SIZE 8192
-#endif /* __ia64__ */
 #endif
 
 /* Copy whatever the last rule matched to the standard output. */
@@ -2176,7 +1728,7 @@ static int input (void );
 /* This used to be an fputs(), but since the string might contain NUL's,
  * we now use fwrite().
  */
-#define ECHO do { if (fwrite( msyytext, msyyleng, 1, msyyout )) {} } while (0)
+#define ECHO (void) fwrite( msyytext, msyyleng, 1, msyyout )
 #endif
 
 /* Gets input and stuffs it into "buf".  number of characters read, or YY_NULL,
@@ -2343,7 +1895,7 @@ YY_DECL
          break;
        }
 
-#line 2347 "maplexer.c"
+#line 1899 "maplexer.c"
 
 	if ( !(yy_init) )
 		{
@@ -2396,13 +1948,13 @@ yy_match:
 			while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
 				{
 				yy_current_state = (int) yy_def[yy_current_state];
-				if ( yy_current_state >= 1807 )
+				if ( yy_current_state >= 1854 )
 					yy_c = yy_meta[(unsigned int) yy_c];
 				}
 			yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
 			++yy_cp;
 			}
-		while ( yy_base[yy_current_state] != 4122 );
+		while ( yy_base[yy_current_state] != 2325 );
 
 yy_find_action:
 		yy_act = yy_accept[yy_current_state];
@@ -2538,1342 +2090,1382 @@ YY_RULE_SETUP
 	YY_BREAK
 case 23:
 YY_RULE_SETUP
-#line 188 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_TOKEN_COMPARISON_INTERSECTS); }
+#line 187 "maplexer.l"
+{ MS_LEXER_RETURN_TOKEN(MS_TOKEN_FUNCTION_DIFFERENCE); }
 	YY_BREAK
 case 24:
 YY_RULE_SETUP
 #line 189 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_TOKEN_COMPARISON_DISJOINT); }
+{ MS_LEXER_RETURN_TOKEN(MS_TOKEN_COMPARISON_INTERSECTS); }
 	YY_BREAK
 case 25:
 YY_RULE_SETUP
 #line 190 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_TOKEN_COMPARISON_TOUCHES); }
+{ MS_LEXER_RETURN_TOKEN(MS_TOKEN_COMPARISON_DISJOINT); }
 	YY_BREAK
 case 26:
 YY_RULE_SETUP
 #line 191 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_TOKEN_COMPARISON_OVERLAPS); }
+{ MS_LEXER_RETURN_TOKEN(MS_TOKEN_COMPARISON_TOUCHES); }
 	YY_BREAK
 case 27:
 YY_RULE_SETUP
 #line 192 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_TOKEN_COMPARISON_CROSSES); }
+{ MS_LEXER_RETURN_TOKEN(MS_TOKEN_COMPARISON_OVERLAPS); }
 	YY_BREAK
 case 28:
 YY_RULE_SETUP
 #line 193 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_TOKEN_COMPARISON_WITHIN); }
+{ MS_LEXER_RETURN_TOKEN(MS_TOKEN_COMPARISON_CROSSES); }
 	YY_BREAK
 case 29:
 YY_RULE_SETUP
 #line 194 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_TOKEN_COMPARISON_CONTAINS); }
+{ MS_LEXER_RETURN_TOKEN(MS_TOKEN_COMPARISON_WITHIN); }
 	YY_BREAK
 case 30:
 YY_RULE_SETUP
 #line 195 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_TOKEN_COMPARISON_BEYOND); }
+{ MS_LEXER_RETURN_TOKEN(MS_TOKEN_COMPARISON_CONTAINS); }
 	YY_BREAK
 case 31:
 YY_RULE_SETUP
 #line 196 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_TOKEN_COMPARISON_DWITHIN); }
+{ MS_LEXER_RETURN_TOKEN(MS_TOKEN_COMPARISON_BEYOND); }
 	YY_BREAK
 case 32:
 YY_RULE_SETUP
-#line 198 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_TOKEN_FUNCTION_FROMTEXT); }
+#line 197 "maplexer.l"
+{ MS_LEXER_RETURN_TOKEN(MS_TOKEN_COMPARISON_DWITHIN); }
 	YY_BREAK
 case 33:
 YY_RULE_SETUP
-#line 200 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(COLORRANGE); }
+#line 199 "maplexer.l"
+{ MS_LEXER_RETURN_TOKEN(MS_TOKEN_FUNCTION_FROMTEXT); }
 	YY_BREAK
 case 34:
 YY_RULE_SETUP
 #line 201 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(DATARANGE); }
+{ MS_LEXER_RETURN_TOKEN(COLORRANGE); }
 	YY_BREAK
 case 35:
 YY_RULE_SETUP
 #line 202 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(RANGEITEM); }
+{ MS_LEXER_RETURN_TOKEN(DATARANGE); }
 	YY_BREAK
 case 36:
 YY_RULE_SETUP
-#line 204 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(ALIGN); }
+#line 203 "maplexer.l"
+{ MS_LEXER_RETURN_TOKEN(RANGEITEM); }
 	YY_BREAK
 case 37:
 YY_RULE_SETUP
 #line 205 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(ANGLE); }
+{ MS_LEXER_RETURN_TOKEN(ALIGN); }
 	YY_BREAK
 case 38:
 YY_RULE_SETUP
 #line 206 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(ANTIALIAS); }
+{ MS_LEXER_RETURN_TOKEN(ANCHORPOINT); }
 	YY_BREAK
 case 39:
 YY_RULE_SETUP
 #line 207 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(BACKGROUNDCOLOR); }
+{ MS_LEXER_RETURN_TOKEN(ANGLE); }
 	YY_BREAK
 case 40:
 YY_RULE_SETUP
 #line 208 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(BANDSITEM); }
+{ MS_LEXER_RETURN_TOKEN(ANTIALIAS); }
 	YY_BREAK
 case 41:
 YY_RULE_SETUP
 #line 209 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(BINDVALS); }
+{ MS_LEXER_RETURN_TOKEN(BACKGROUNDCOLOR); }
 	YY_BREAK
 case 42:
 YY_RULE_SETUP
 #line 210 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(BROWSEFORMAT); }
+{ MS_LEXER_RETURN_TOKEN(BANDSITEM); }
 	YY_BREAK
 case 43:
 YY_RULE_SETUP
 #line 211 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(BUFFER); }
+{ MS_LEXER_RETURN_TOKEN(BINDVALS); }
 	YY_BREAK
 case 44:
 YY_RULE_SETUP
 #line 212 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(CHARACTER); }
+{ MS_LEXER_RETURN_TOKEN(BROWSEFORMAT); }
 	YY_BREAK
 case 45:
 YY_RULE_SETUP
 #line 213 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(CLASS); }
+{ MS_LEXER_RETURN_TOKEN(BUFFER); }
 	YY_BREAK
 case 46:
 YY_RULE_SETUP
 #line 214 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(CLASSITEM); }
+{ MS_LEXER_RETURN_TOKEN(CHARACTER); }
 	YY_BREAK
 case 47:
 YY_RULE_SETUP
 #line 215 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(CLASSGROUP); }
+{ MS_LEXER_RETURN_TOKEN(CLASS); }
 	YY_BREAK
 case 48:
 YY_RULE_SETUP
 #line 216 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(CLUSTER); }
+{ MS_LEXER_RETURN_TOKEN(CLASSITEM); }
 	YY_BREAK
 case 49:
 YY_RULE_SETUP
 #line 217 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(COLOR); }
+{ MS_LEXER_RETURN_TOKEN(CLASSGROUP); }
 	YY_BREAK
 case 50:
 YY_RULE_SETUP
 #line 218 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(CONFIG); }
+{ MS_LEXER_RETURN_TOKEN(CLUSTER); }
 	YY_BREAK
 case 51:
 YY_RULE_SETUP
 #line 219 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(CONNECTION); }
+{ MS_LEXER_RETURN_TOKEN(COLOR); }
 	YY_BREAK
 case 52:
 YY_RULE_SETUP
 #line 220 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(CONNECTIONTYPE); }
+{ MS_LEXER_RETURN_TOKEN(CONFIG); }
 	YY_BREAK
 case 53:
 YY_RULE_SETUP
 #line 221 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(DATA); }
+{ MS_LEXER_RETURN_TOKEN(CONNECTION); }
 	YY_BREAK
 case 54:
 YY_RULE_SETUP
 #line 222 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(DATAPATTERN); }
+{ MS_LEXER_RETURN_TOKEN(CONNECTIONTYPE); }
 	YY_BREAK
 case 55:
 YY_RULE_SETUP
 #line 223 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(DEBUG); }
+{ MS_LEXER_RETURN_TOKEN(DATA); }
 	YY_BREAK
 case 56:
 YY_RULE_SETUP
 #line 224 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(DRIVER); }
+{ MS_LEXER_RETURN_TOKEN(DATAPATTERN); }
 	YY_BREAK
 case 57:
 YY_RULE_SETUP
 #line 225 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(DUMP); }
+{ MS_LEXER_RETURN_TOKEN(DEBUG); }
 	YY_BREAK
 case 58:
 YY_RULE_SETUP
 #line 226 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(EMPTY); }
+{ MS_LEXER_RETURN_TOKEN(DRIVER); }
 	YY_BREAK
 case 59:
 YY_RULE_SETUP
 #line 227 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(ENCODING); }
+{ MS_LEXER_RETURN_TOKEN(DUMP); }
 	YY_BREAK
 case 60:
 YY_RULE_SETUP
 #line 228 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(END); }
+{ MS_LEXER_RETURN_TOKEN(EMPTY); }
 	YY_BREAK
 case 61:
 YY_RULE_SETUP
 #line 229 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(ERROR); }
+{ MS_LEXER_RETURN_TOKEN(ENCODING); }
 	YY_BREAK
 case 62:
 YY_RULE_SETUP
 #line 230 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(EXPRESSION); }
+{ MS_LEXER_RETURN_TOKEN(END); }
 	YY_BREAK
 case 63:
 YY_RULE_SETUP
 #line 231 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(EXTENT); }
+{ MS_LEXER_RETURN_TOKEN(ERROR); }
 	YY_BREAK
 case 64:
 YY_RULE_SETUP
 #line 232 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(EXTENSION); }
+{ MS_LEXER_RETURN_TOKEN(EXPRESSION); }
 	YY_BREAK
 case 65:
 YY_RULE_SETUP
 #line 233 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(FEATURE); }
+{ MS_LEXER_RETURN_TOKEN(EXTENT); }
 	YY_BREAK
 case 66:
 YY_RULE_SETUP
 #line 234 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(FILLED); }
+{ MS_LEXER_RETURN_TOKEN(EXTENSION); }
 	YY_BREAK
 case 67:
 YY_RULE_SETUP
 #line 235 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(FILTER); }
+{ MS_LEXER_RETURN_TOKEN(FEATURE); }
 	YY_BREAK
 case 68:
 YY_RULE_SETUP
 #line 236 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(FILTERITEM); }
+{ MS_LEXER_RETURN_TOKEN(FILLED); }
 	YY_BREAK
 case 69:
 YY_RULE_SETUP
 #line 237 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(FOOTER); }
+{ MS_LEXER_RETURN_TOKEN(FILTER); }
 	YY_BREAK
 case 70:
 YY_RULE_SETUP
 #line 238 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(FONT); }
+{ MS_LEXER_RETURN_TOKEN(FILTERITEM); }
 	YY_BREAK
 case 71:
 YY_RULE_SETUP
 #line 239 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(FONTSET); }
+{ MS_LEXER_RETURN_TOKEN(FOOTER); }
 	YY_BREAK
 case 72:
 YY_RULE_SETUP
 #line 240 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(FORCE); }
+{ MS_LEXER_RETURN_TOKEN(FONT); }
 	YY_BREAK
 case 73:
 YY_RULE_SETUP
 #line 241 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(FORMATOPTION); }
+{ MS_LEXER_RETURN_TOKEN(FONTSET); }
 	YY_BREAK
 case 74:
 YY_RULE_SETUP
 #line 242 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(FROM); }
+{ MS_LEXER_RETURN_TOKEN(FORCE); }
 	YY_BREAK
 case 75:
 YY_RULE_SETUP
 #line 243 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(GAP); }
+{ MS_LEXER_RETURN_TOKEN(FORMATOPTION); }
 	YY_BREAK
 case 76:
 YY_RULE_SETUP
 #line 244 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(GEOMTRANSFORM); }
+{ MS_LEXER_RETURN_TOKEN(FROM); }
 	YY_BREAK
 case 77:
 YY_RULE_SETUP
 #line 245 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(GRID); }
+{ MS_LEXER_RETURN_TOKEN(GAP); }
 	YY_BREAK
 case 78:
 YY_RULE_SETUP
 #line 246 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(GRATICULE); }
+{ MS_LEXER_RETURN_TOKEN(GEOMTRANSFORM); }
 	YY_BREAK
 case 79:
 YY_RULE_SETUP
 #line 247 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(GROUP); }
+{ MS_LEXER_RETURN_TOKEN(GRID); }
 	YY_BREAK
 case 80:
 YY_RULE_SETUP
 #line 248 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(HEADER); }
+{ MS_LEXER_RETURN_TOKEN(GRIDSTEP); }
 	YY_BREAK
 case 81:
 YY_RULE_SETUP
 #line 249 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(IMAGE); }
+{ MS_LEXER_RETURN_TOKEN(GRATICULE); }
 	YY_BREAK
 case 82:
 YY_RULE_SETUP
 #line 250 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(IMAGECOLOR); }
+{ MS_LEXER_RETURN_TOKEN(GROUP); }
 	YY_BREAK
 case 83:
 YY_RULE_SETUP
 #line 251 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(IMAGETYPE); }
+{ MS_LEXER_RETURN_TOKEN(HEADER); }
 	YY_BREAK
 case 84:
 YY_RULE_SETUP
 #line 252 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(IMAGEQUALITY); }
+{ MS_LEXER_RETURN_TOKEN(IMAGE); }
 	YY_BREAK
 case 85:
 YY_RULE_SETUP
 #line 253 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(IMAGEMODE); }
+{ MS_LEXER_RETURN_TOKEN(IMAGECOLOR); }
 	YY_BREAK
 case 86:
 YY_RULE_SETUP
 #line 254 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(IMAGEPATH); }
+{ MS_LEXER_RETURN_TOKEN(IMAGETYPE); }
 	YY_BREAK
 case 87:
 YY_RULE_SETUP
 #line 255 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(TEMPPATH); }
+{ MS_LEXER_RETURN_TOKEN(IMAGEQUALITY); }
 	YY_BREAK
 case 88:
 YY_RULE_SETUP
 #line 256 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(IMAGEURL); }
+{ MS_LEXER_RETURN_TOKEN(IMAGEMODE); }
 	YY_BREAK
 case 89:
 YY_RULE_SETUP
 #line 257 "maplexer.l"
-{ BEGIN(INCLUDE); }
+{ MS_LEXER_RETURN_TOKEN(IMAGEPATH); }
 	YY_BREAK
 case 90:
 YY_RULE_SETUP
 #line 258 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(INDEX); }
+{ MS_LEXER_RETURN_TOKEN(TEMPPATH); }
 	YY_BREAK
 case 91:
 YY_RULE_SETUP
 #line 259 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(INTERLACE); }
+{ MS_LEXER_RETURN_TOKEN(IMAGEURL); }
 	YY_BREAK
 case 92:
 YY_RULE_SETUP
 #line 260 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(INTERVALS); } 
+{ BEGIN(INCLUDE); }
 	YY_BREAK
 case 93:
 YY_RULE_SETUP
 #line 261 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(JOIN); }
+{ MS_LEXER_RETURN_TOKEN(INDEX); }
 	YY_BREAK
 case 94:
 YY_RULE_SETUP
 #line 262 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(KEYIMAGE); }
+{ MS_LEXER_RETURN_TOKEN(INITIALGAP); }
 	YY_BREAK
 case 95:
 YY_RULE_SETUP
 #line 263 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(KEYSIZE); }
+{ MS_LEXER_RETURN_TOKEN(INTERLACE); }
 	YY_BREAK
 case 96:
 YY_RULE_SETUP
 #line 264 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(KEYSPACING); }
+{ MS_LEXER_RETURN_TOKEN(INTERVALS); } 
 	YY_BREAK
 case 97:
 YY_RULE_SETUP
 #line 265 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(LABEL); }
+{ MS_LEXER_RETURN_TOKEN(JOIN); }
 	YY_BREAK
 case 98:
 YY_RULE_SETUP
 #line 266 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(LABELCACHE); }
+{ MS_LEXER_RETURN_TOKEN(KEYIMAGE); }
 	YY_BREAK
 case 99:
 YY_RULE_SETUP
 #line 267 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(LABELFORMAT); }
+{ MS_LEXER_RETURN_TOKEN(KEYSIZE); }
 	YY_BREAK
 case 100:
 YY_RULE_SETUP
 #line 268 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(LABELITEM); }
+{ MS_LEXER_RETURN_TOKEN(KEYSPACING); }
 	YY_BREAK
 case 101:
 YY_RULE_SETUP
 #line 269 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(LABELMAXSCALE); }
+{ MS_LEXER_RETURN_TOKEN(LABEL); }
 	YY_BREAK
 case 102:
 YY_RULE_SETUP
 #line 270 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(LABELMAXSCALEDENOM); }
+{ MS_LEXER_RETURN_TOKEN(LABELCACHE); }
 	YY_BREAK
 case 103:
 YY_RULE_SETUP
 #line 271 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(LABELMINSCALE); }
+{ MS_LEXER_RETURN_TOKEN(LABELFORMAT); }
 	YY_BREAK
 case 104:
 YY_RULE_SETUP
 #line 272 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(LABELMINSCALEDENOM); }
+{ MS_LEXER_RETURN_TOKEN(LABELITEM); }
 	YY_BREAK
 case 105:
 YY_RULE_SETUP
 #line 273 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(LABELREQUIRES); }
+{ MS_LEXER_RETURN_TOKEN(LABELMAXSCALE); }
 	YY_BREAK
 case 106:
 YY_RULE_SETUP
 #line 274 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(LATLON); }
+{ MS_LEXER_RETURN_TOKEN(LABELMAXSCALEDENOM); }
 	YY_BREAK
 case 107:
 YY_RULE_SETUP
 #line 275 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(LAYER); }
+{ MS_LEXER_RETURN_TOKEN(LABELMINSCALE); }
 	YY_BREAK
 case 108:
 YY_RULE_SETUP
 #line 276 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(LEGEND); }
+{ MS_LEXER_RETURN_TOKEN(LABELMINSCALEDENOM); }
 	YY_BREAK
 case 109:
 YY_RULE_SETUP
 #line 277 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(LEGENDFORMAT); }
+{ MS_LEXER_RETURN_TOKEN(LABELREQUIRES); }
 	YY_BREAK
 case 110:
 YY_RULE_SETUP
 #line 278 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(LINECAP); }
+{ MS_LEXER_RETURN_TOKEN(LATLON); }
 	YY_BREAK
 case 111:
 YY_RULE_SETUP
 #line 279 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(LINEJOIN); }
+{ MS_LEXER_RETURN_TOKEN(LAYER); }
 	YY_BREAK
 case 112:
 YY_RULE_SETUP
 #line 280 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(LINEJOINMAXSIZE); }
+{ MS_LEXER_RETURN_TOKEN(LEADER); }
 	YY_BREAK
 case 113:
 YY_RULE_SETUP
 #line 281 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(LOG); }
+{ MS_LEXER_RETURN_TOKEN(LEGEND); }
 	YY_BREAK
 case 114:
 YY_RULE_SETUP
 #line 282 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MAP); }
+{ MS_LEXER_RETURN_TOKEN(LEGENDFORMAT); }
 	YY_BREAK
 case 115:
 YY_RULE_SETUP
 #line 283 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MARKER); }
+{ MS_LEXER_RETURN_TOKEN(LINECAP); }
 	YY_BREAK
 case 116:
 YY_RULE_SETUP
 #line 284 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MARKERSIZE); }
+{ MS_LEXER_RETURN_TOKEN(LINEJOIN); }
 	YY_BREAK
 case 117:
 YY_RULE_SETUP
 #line 285 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MAXARCS); }
+{ MS_LEXER_RETURN_TOKEN(LINEJOINMAXSIZE); }
 	YY_BREAK
 case 118:
 YY_RULE_SETUP
 #line 286 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MAXBOXSIZE); }
+{ MS_LEXER_RETURN_TOKEN(LOG); }
 	YY_BREAK
 case 119:
 YY_RULE_SETUP
 #line 287 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MAXDISTANCE); }
+{ MS_LEXER_RETURN_TOKEN(MAP); }
 	YY_BREAK
 case 120:
 YY_RULE_SETUP
 #line 288 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MAXFEATURES); }
+{ MS_LEXER_RETURN_TOKEN(MARKER); }
 	YY_BREAK
 case 121:
 YY_RULE_SETUP
 #line 289 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MAXINTERVAL); }
+{ MS_LEXER_RETURN_TOKEN(MARKERSIZE); }
 	YY_BREAK
 case 122:
 YY_RULE_SETUP
 #line 290 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MAXSCALE); }
+{ MS_LEXER_RETURN_TOKEN(MASK); }
 	YY_BREAK
 case 123:
 YY_RULE_SETUP
 #line 291 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MAXSCALEDENOM); }
+{ MS_LEXER_RETURN_TOKEN(MAXARCS); }
 	YY_BREAK
 case 124:
 YY_RULE_SETUP
 #line 292 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MAXGEOWIDTH); }
+{ MS_LEXER_RETURN_TOKEN(MAXBOXSIZE); }
 	YY_BREAK
 case 125:
 YY_RULE_SETUP
 #line 293 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MAXLENGTH); }
+{ MS_LEXER_RETURN_TOKEN(MAXDISTANCE); }
 	YY_BREAK
 case 126:
 YY_RULE_SETUP
 #line 294 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MAXSIZE); }
+{ MS_LEXER_RETURN_TOKEN(MAXFEATURES); }
 	YY_BREAK
 case 127:
 YY_RULE_SETUP
 #line 295 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MAXSUBDIVIDE); }
+{ MS_LEXER_RETURN_TOKEN(MAXINTERVAL); }
 	YY_BREAK
 case 128:
 YY_RULE_SETUP
 #line 296 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MAXTEMPLATE); }
+{ MS_LEXER_RETURN_TOKEN(MAXSCALE); }
 	YY_BREAK
 case 129:
 YY_RULE_SETUP
 #line 297 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MAXWIDTH); }
+{ MS_LEXER_RETURN_TOKEN(MAXSCALEDENOM); }
 	YY_BREAK
 case 130:
 YY_RULE_SETUP
 #line 298 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(METADATA); }
+{ MS_LEXER_RETURN_TOKEN(MAXGEOWIDTH); }
 	YY_BREAK
 case 131:
 YY_RULE_SETUP
 #line 299 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MIMETYPE); }
+{ MS_LEXER_RETURN_TOKEN(MAXLENGTH); }
 	YY_BREAK
 case 132:
 YY_RULE_SETUP
 #line 300 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MINARCS); }
+{ MS_LEXER_RETURN_TOKEN(MAXSIZE); }
 	YY_BREAK
 case 133:
 YY_RULE_SETUP
 #line 301 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MINBOXSIZE); }
+{ MS_LEXER_RETURN_TOKEN(MAXSUBDIVIDE); }
 	YY_BREAK
 case 134:
 YY_RULE_SETUP
 #line 302 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MINDISTANCE); }
+{ MS_LEXER_RETURN_TOKEN(MAXTEMPLATE); }
 	YY_BREAK
 case 135:
 YY_RULE_SETUP
 #line 303 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(REPEATDISTANCE); }
+{ MS_LEXER_RETURN_TOKEN(MAXWIDTH); }
 	YY_BREAK
 case 136:
 YY_RULE_SETUP
 #line 304 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MAXOVERLAPANGLE); } 
+{ MS_LEXER_RETURN_TOKEN(METADATA); }
 	YY_BREAK
 case 137:
 YY_RULE_SETUP
 #line 305 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MINFEATURESIZE); }
+{ MS_LEXER_RETURN_TOKEN(MIMETYPE); }
 	YY_BREAK
 case 138:
 YY_RULE_SETUP
 #line 306 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MININTERVAL); }
+{ MS_LEXER_RETURN_TOKEN(MINARCS); }
 	YY_BREAK
 case 139:
 YY_RULE_SETUP
 #line 307 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MINSCALE); }
+{ MS_LEXER_RETURN_TOKEN(MINBOXSIZE); }
 	YY_BREAK
 case 140:
 YY_RULE_SETUP
 #line 308 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MINSCALEDENOM); }
+{ MS_LEXER_RETURN_TOKEN(MINDISTANCE); }
 	YY_BREAK
 case 141:
 YY_RULE_SETUP
 #line 309 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MINGEOWIDTH); }
+{ MS_LEXER_RETURN_TOKEN(REPEATDISTANCE); }
 	YY_BREAK
 case 142:
 YY_RULE_SETUP
 #line 310 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MINLENGTH); }
+{ MS_LEXER_RETURN_TOKEN(MAXOVERLAPANGLE); } 
 	YY_BREAK
 case 143:
 YY_RULE_SETUP
 #line 311 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MINSIZE); }
+{ MS_LEXER_RETURN_TOKEN(MINFEATURESIZE); }
 	YY_BREAK
 case 144:
 YY_RULE_SETUP
 #line 312 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MINSUBDIVIDE); }
+{ MS_LEXER_RETURN_TOKEN(MININTERVAL); }
 	YY_BREAK
 case 145:
 YY_RULE_SETUP
 #line 313 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MINTEMPLATE); }
+{ MS_LEXER_RETURN_TOKEN(MINSCALE); }
 	YY_BREAK
 case 146:
 YY_RULE_SETUP
 #line 314 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MINWIDTH); }
+{ MS_LEXER_RETURN_TOKEN(MINSCALEDENOM); }
 	YY_BREAK
 case 147:
 YY_RULE_SETUP
 #line 315 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(NAME); }
+{ MS_LEXER_RETURN_TOKEN(MINGEOWIDTH); }
 	YY_BREAK
 case 148:
 YY_RULE_SETUP
 #line 316 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(OFFSET); }
+{ MS_LEXER_RETURN_TOKEN(MINLENGTH); }
 	YY_BREAK
 case 149:
 YY_RULE_SETUP
 #line 317 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(OFFSITE); }
+{ MS_LEXER_RETURN_TOKEN(MINSIZE); }
 	YY_BREAK
 case 150:
 YY_RULE_SETUP
 #line 318 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(OPACITY); }
+{ MS_LEXER_RETURN_TOKEN(MINSUBDIVIDE); }
 	YY_BREAK
 case 151:
 YY_RULE_SETUP
 #line 319 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(OUTLINECOLOR); }
+{ MS_LEXER_RETURN_TOKEN(MINTEMPLATE); }
 	YY_BREAK
 case 152:
 YY_RULE_SETUP
 #line 320 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(OUTLINEWIDTH); }
+{ MS_LEXER_RETURN_TOKEN(MINWIDTH); }
 	YY_BREAK
 case 153:
 YY_RULE_SETUP
 #line 321 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(OUTPUTFORMAT); }
+{ MS_LEXER_RETURN_TOKEN(NAME); }
 	YY_BREAK
 case 154:
 YY_RULE_SETUP
 #line 322 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(OVERLAYBACKGROUNDCOLOR); }
+{ MS_LEXER_RETURN_TOKEN(OFFSET); }
 	YY_BREAK
 case 155:
 YY_RULE_SETUP
 #line 323 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(OVERLAYCOLOR); }
+{ MS_LEXER_RETURN_TOKEN(OFFSITE); }
 	YY_BREAK
 case 156:
 YY_RULE_SETUP
 #line 324 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(OVERLAYMAXSIZE); }
+{ MS_LEXER_RETURN_TOKEN(OPACITY); }
 	YY_BREAK
 case 157:
 YY_RULE_SETUP
 #line 325 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(OVERLAYMINSIZE); }
+{ MS_LEXER_RETURN_TOKEN(OUTLINECOLOR); }
 	YY_BREAK
 case 158:
 YY_RULE_SETUP
 #line 326 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(OVERLAYOUTLINECOLOR); }
+{ MS_LEXER_RETURN_TOKEN(OUTLINEWIDTH); }
 	YY_BREAK
 case 159:
 YY_RULE_SETUP
 #line 327 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(OVERLAYSIZE); }
+{ MS_LEXER_RETURN_TOKEN(OUTPUTFORMAT); }
 	YY_BREAK
 case 160:
 YY_RULE_SETUP
 #line 328 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(OVERLAYSYMBOL); }
+{ MS_LEXER_RETURN_TOKEN(OVERLAYBACKGROUNDCOLOR); }
 	YY_BREAK
 case 161:
 YY_RULE_SETUP
 #line 329 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(PARTIALS); }
+{ MS_LEXER_RETURN_TOKEN(OVERLAYCOLOR); }
 	YY_BREAK
 case 162:
 YY_RULE_SETUP
 #line 330 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(PATTERN); }
+{ MS_LEXER_RETURN_TOKEN(OVERLAYMAXSIZE); }
 	YY_BREAK
 case 163:
 YY_RULE_SETUP
 #line 331 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(POINTS); }
+{ MS_LEXER_RETURN_TOKEN(OVERLAYMINSIZE); }
 	YY_BREAK
 case 164:
 YY_RULE_SETUP
 #line 332 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(ITEMS); }
+{ MS_LEXER_RETURN_TOKEN(OVERLAYOUTLINECOLOR); }
 	YY_BREAK
 case 165:
 YY_RULE_SETUP
 #line 333 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(POSITION); }
+{ MS_LEXER_RETURN_TOKEN(OVERLAYSIZE); }
 	YY_BREAK
 case 166:
 YY_RULE_SETUP
 #line 334 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(POSTLABELCACHE); }
+{ MS_LEXER_RETURN_TOKEN(OVERLAYSYMBOL); }
 	YY_BREAK
 case 167:
 YY_RULE_SETUP
 #line 335 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(PRIORITY); }
+{ MS_LEXER_RETURN_TOKEN(PARTIALS); }
 	YY_BREAK
 case 168:
 YY_RULE_SETUP
 #line 336 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(PROCESSING); }
+{ MS_LEXER_RETURN_TOKEN(PATTERN); }
 	YY_BREAK
 case 169:
 YY_RULE_SETUP
 #line 337 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(PROJECTION); }
+{ MS_LEXER_RETURN_TOKEN(POINTS); }
 	YY_BREAK
 case 170:
 YY_RULE_SETUP
 #line 338 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(QUERYFORMAT); }
+{ MS_LEXER_RETURN_TOKEN(ITEMS); }
 	YY_BREAK
 case 171:
 YY_RULE_SETUP
 #line 339 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(QUERYMAP); }
+{ MS_LEXER_RETURN_TOKEN(POSITION); }
 	YY_BREAK
 case 172:
 YY_RULE_SETUP
 #line 340 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(REFERENCE); }
+{ MS_LEXER_RETURN_TOKEN(POSTLABELCACHE); }
 	YY_BREAK
 case 173:
 YY_RULE_SETUP
 #line 341 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(REGION); }
+{ MS_LEXER_RETURN_TOKEN(PRIORITY); }
 	YY_BREAK
 case 174:
 YY_RULE_SETUP
 #line 342 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(RELATIVETO); }
+{ MS_LEXER_RETURN_TOKEN(PROCESSING); }
 	YY_BREAK
 case 175:
 YY_RULE_SETUP
 #line 343 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(REQUIRES); }
+{ MS_LEXER_RETURN_TOKEN(PROJECTION); }
 	YY_BREAK
 case 176:
 YY_RULE_SETUP
 #line 344 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(RESOLUTION); }
+{ MS_LEXER_RETURN_TOKEN(QUERYFORMAT); }
 	YY_BREAK
 case 177:
 YY_RULE_SETUP
 #line 345 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(DEFRESOLUTION); }
+{ MS_LEXER_RETURN_TOKEN(QUERYMAP); }
 	YY_BREAK
 case 178:
 YY_RULE_SETUP
 #line 346 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(SCALE); }
+{ MS_LEXER_RETURN_TOKEN(REFERENCE); }
 	YY_BREAK
 case 179:
 YY_RULE_SETUP
 #line 347 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(SCALEDENOM); }
+{ MS_LEXER_RETURN_TOKEN(REGION); }
 	YY_BREAK
 case 180:
 YY_RULE_SETUP
 #line 348 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(SCALEBAR); }
+{ MS_LEXER_RETURN_TOKEN(RELATIVETO); }
 	YY_BREAK
 case 181:
 YY_RULE_SETUP
 #line 349 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(SHADOWCOLOR); }
+{ MS_LEXER_RETURN_TOKEN(REQUIRES); }
 	YY_BREAK
 case 182:
 YY_RULE_SETUP
 #line 350 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(SHADOWSIZE); }
+{ MS_LEXER_RETURN_TOKEN(RESOLUTION); }
 	YY_BREAK
 case 183:
 YY_RULE_SETUP
 #line 351 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(SHAPEPATH); }
+{ MS_LEXER_RETURN_TOKEN(DEFRESOLUTION); }
 	YY_BREAK
 case 184:
 YY_RULE_SETUP
 #line 352 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(SIZE); }
+{ MS_LEXER_RETURN_TOKEN(SCALE); }
 	YY_BREAK
 case 185:
 YY_RULE_SETUP
 #line 353 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(SIZEUNITS); }
+{ MS_LEXER_RETURN_TOKEN(SCALEDENOM); }
 	YY_BREAK
 case 186:
 YY_RULE_SETUP
 #line 354 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(STATUS); }
+{ MS_LEXER_RETURN_TOKEN(SCALEBAR); }
 	YY_BREAK
 case 187:
 YY_RULE_SETUP
 #line 355 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(STYLE); }
+{ MS_LEXER_RETURN_TOKEN(SHADOWCOLOR); }
 	YY_BREAK
 case 188:
 YY_RULE_SETUP
 #line 356 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(STYLEITEM); }
+{ MS_LEXER_RETURN_TOKEN(SHADOWSIZE); }
 	YY_BREAK
 case 189:
 YY_RULE_SETUP
 #line 357 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(SYMBOL); }
+{ MS_LEXER_RETURN_TOKEN(SHAPEPATH); }
 	YY_BREAK
 case 190:
 YY_RULE_SETUP
 #line 358 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(SYMBOLSCALE); }
+{ MS_LEXER_RETURN_TOKEN(SIZE); }
 	YY_BREAK
 case 191:
 YY_RULE_SETUP
 #line 359 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(SYMBOLSCALEDENOM); }
+{ MS_LEXER_RETURN_TOKEN(SIZEUNITS); }
 	YY_BREAK
 case 192:
 YY_RULE_SETUP
 #line 360 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(SYMBOLSET); }
+{ MS_LEXER_RETURN_TOKEN(STATUS); }
 	YY_BREAK
 case 193:
 YY_RULE_SETUP
 #line 361 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(TABLE); }
+{ MS_LEXER_RETURN_TOKEN(STYLE); }
 	YY_BREAK
 case 194:
 YY_RULE_SETUP
 #line 362 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(TEMPLATE); }
+{ MS_LEXER_RETURN_TOKEN(STYLEITEM); }
 	YY_BREAK
 case 195:
 YY_RULE_SETUP
 #line 363 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(TEMPLATEPATTERN); }
+{ MS_LEXER_RETURN_TOKEN(SYMBOL); }
 	YY_BREAK
 case 196:
 YY_RULE_SETUP
 #line 364 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(TEXT); }
+{ MS_LEXER_RETURN_TOKEN(SYMBOLSCALE); }
 	YY_BREAK
 case 197:
 YY_RULE_SETUP
 #line 365 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(TILEINDEX); }
+{ MS_LEXER_RETURN_TOKEN(SYMBOLSCALEDENOM); }
 	YY_BREAK
 case 198:
 YY_RULE_SETUP
 #line 366 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(TILEITEM); }
+{ MS_LEXER_RETURN_TOKEN(SYMBOLSET); }
 	YY_BREAK
 case 199:
 YY_RULE_SETUP
 #line 367 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(TITLE); }
+{ MS_LEXER_RETURN_TOKEN(TABLE); }
 	YY_BREAK
 case 200:
 YY_RULE_SETUP
 #line 368 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(TO); }
+{ MS_LEXER_RETURN_TOKEN(TEMPLATE); }
 	YY_BREAK
 case 201:
 YY_RULE_SETUP
 #line 369 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(TOLERANCE); }
+{ MS_LEXER_RETURN_TOKEN(TEMPLATEPATTERN); }
 	YY_BREAK
 case 202:
 YY_RULE_SETUP
 #line 370 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(TOLERANCEUNITS); }
+{ MS_LEXER_RETURN_TOKEN(TEXT); }
 	YY_BREAK
 case 203:
 YY_RULE_SETUP
 #line 371 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(TRANSPARENCY); }
+{ MS_LEXER_RETURN_TOKEN(TILEINDEX); }
 	YY_BREAK
 case 204:
 YY_RULE_SETUP
 #line 372 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(TRANSPARENT); }
+{ MS_LEXER_RETURN_TOKEN(TILEITEM); }
 	YY_BREAK
 case 205:
 YY_RULE_SETUP
 #line 373 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(TRANSFORM); }
+{ MS_LEXER_RETURN_TOKEN(TITLE); }
 	YY_BREAK
 case 206:
 YY_RULE_SETUP
 #line 374 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(TYPE); }
+{ MS_LEXER_RETURN_TOKEN(TO); }
 	YY_BREAK
 case 207:
 YY_RULE_SETUP
 #line 375 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(UNITS); }
+{ MS_LEXER_RETURN_TOKEN(TOLERANCE); }
 	YY_BREAK
 case 208:
 YY_RULE_SETUP
 #line 376 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(VALIDATION); }
+{ MS_LEXER_RETURN_TOKEN(TOLERANCEUNITS); }
 	YY_BREAK
 case 209:
 YY_RULE_SETUP
 #line 377 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(WEB); }
+{ MS_LEXER_RETURN_TOKEN(TRANSPARENCY); }
 	YY_BREAK
 case 210:
 YY_RULE_SETUP
 #line 378 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(WIDTH); }
+{ MS_LEXER_RETURN_TOKEN(TRANSPARENT); }
 	YY_BREAK
 case 211:
 YY_RULE_SETUP
 #line 379 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(WKT); }
+{ MS_LEXER_RETURN_TOKEN(TRANSFORM); }
 	YY_BREAK
 case 212:
 YY_RULE_SETUP
 #line 380 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(WRAP); }
+{ MS_LEXER_RETURN_TOKEN(TYPE); }
 	YY_BREAK
 case 213:
 YY_RULE_SETUP
-#line 382 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_LAYER_ANNOTATION); }
+#line 381 "maplexer.l"
+{ MS_LEXER_RETURN_TOKEN(UNITS); }
 	YY_BREAK
 case 214:
 YY_RULE_SETUP
-#line 383 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_AUTO); }
+#line 382 "maplexer.l"
+{ MS_LEXER_RETURN_TOKEN(VALIDATION); }
 	YY_BREAK
 case 215:
 YY_RULE_SETUP
-#line 384 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_AUTO2); }
+#line 383 "maplexer.l"
+{ MS_LEXER_RETURN_TOKEN(WEB); }
 	YY_BREAK
 case 216:
 YY_RULE_SETUP
-#line 385 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_CJC_BEVEL); }
+#line 384 "maplexer.l"
+{ MS_LEXER_RETURN_TOKEN(WIDTH); }
 	YY_BREAK
 case 217:
 YY_RULE_SETUP
-#line 386 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_BITMAP); }
+#line 385 "maplexer.l"
+{ MS_LEXER_RETURN_TOKEN(WKT); }
 	YY_BREAK
 case 218:
 YY_RULE_SETUP
-#line 387 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_CJC_BUTT); }
+#line 386 "maplexer.l"
+{ MS_LEXER_RETURN_TOKEN(WRAP); }
 	YY_BREAK
 case 219:
 YY_RULE_SETUP
 #line 388 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_CC); }
+{ MS_LEXER_RETURN_TOKEN(MS_LAYER_ANNOTATION); }
 	YY_BREAK
 case 220:
 YY_RULE_SETUP
 #line 389 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_ALIGN_CENTER); }
+{ MS_LEXER_RETURN_TOKEN(MS_AUTO); }
 	YY_BREAK
 case 221:
 YY_RULE_SETUP
 #line 390 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_LAYER_CHART); }
+{ MS_LEXER_RETURN_TOKEN(MS_AUTO2); }
 	YY_BREAK
 case 222:
 YY_RULE_SETUP
 #line 391 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_LAYER_CIRCLE); }
+{ MS_LEXER_RETURN_TOKEN(MS_CJC_BEVEL); }
 	YY_BREAK
 case 223:
 YY_RULE_SETUP
 #line 392 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_CL); }
+{ MS_LEXER_RETURN_TOKEN(MS_BITMAP); }
 	YY_BREAK
 case 224:
 YY_RULE_SETUP
 #line 393 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_CR); }
+{ MS_LEXER_RETURN_TOKEN(MS_CJC_BUTT); }
 	YY_BREAK
 case 225:
 YY_RULE_SETUP
 #line 394 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_DB_CSV); }
+{ MS_LEXER_RETURN_TOKEN(MS_CC); }
 	YY_BREAK
 case 226:
 YY_RULE_SETUP
 #line 395 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_DB_POSTGRES); }
+{ MS_LEXER_RETURN_TOKEN(MS_ALIGN_CENTER); }
 	YY_BREAK
 case 227:
 YY_RULE_SETUP
 #line 396 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_DB_MYSQL); }
+{ MS_LEXER_RETURN_TOKEN(MS_LAYER_CHART); }
 	YY_BREAK
 case 228:
 YY_RULE_SETUP
 #line 397 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_DEFAULT); }
+{ MS_LEXER_RETURN_TOKEN(MS_LAYER_CIRCLE); }
 	YY_BREAK
 case 229:
 YY_RULE_SETUP
 #line 398 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_DD); }
+{ MS_LEXER_RETURN_TOKEN(MS_CL); }
 	YY_BREAK
 case 230:
 YY_RULE_SETUP
 #line 399 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_SYMBOL_ELLIPSE); }
+{ MS_LEXER_RETURN_TOKEN(MS_CR); }
 	YY_BREAK
 case 231:
 YY_RULE_SETUP
 #line 400 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_EMBED); }
+{ MS_LEXER_RETURN_TOKEN(MS_DB_CSV); }
 	YY_BREAK
 case 232:
 YY_RULE_SETUP
 #line 401 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_FALSE); }
+{ MS_LEXER_RETURN_TOKEN(MS_DB_POSTGRES); }
 	YY_BREAK
 case 233:
 YY_RULE_SETUP
 #line 402 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_FEET); }
+{ MS_LEXER_RETURN_TOKEN(MS_DB_MYSQL); }
 	YY_BREAK
 case 234:
 YY_RULE_SETUP
 #line 403 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_FOLLOW); }
+{ MS_LEXER_RETURN_TOKEN(MS_DEFAULT); }
 	YY_BREAK
 case 235:
 YY_RULE_SETUP
 #line 404 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_GIANT); }
+{ MS_LEXER_RETURN_TOKEN(MS_DD); }
 	YY_BREAK
 case 236:
 YY_RULE_SETUP
 #line 405 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_SYMBOL_HATCH); }
+{ MS_LEXER_RETURN_TOKEN(MS_SYMBOL_ELLIPSE); }
 	YY_BREAK
 case 237:
 YY_RULE_SETUP
 #line 406 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_HILITE); }
+{ MS_LEXER_RETURN_TOKEN(MS_EMBED); }
 	YY_BREAK
 case 238:
 YY_RULE_SETUP
 #line 407 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_INCHES); }
+{ MS_LEXER_RETURN_TOKEN(MS_FALSE); }
 	YY_BREAK
 case 239:
 YY_RULE_SETUP
 #line 408 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_KILOMETERS); }
+{ MS_LEXER_RETURN_TOKEN(MS_FEET); }
 	YY_BREAK
 case 240:
 YY_RULE_SETUP
 #line 409 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_LARGE); }
+{ MS_LEXER_RETURN_TOKEN(MS_FOLLOW); }
 	YY_BREAK
 case 241:
 YY_RULE_SETUP
 #line 410 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_LC); }
+{ MS_LEXER_RETURN_TOKEN(MS_GIANT); }
 	YY_BREAK
 case 242:
 YY_RULE_SETUP
 #line 411 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_ALIGN_LEFT); }
+{ MS_LEXER_RETURN_TOKEN(MS_SYMBOL_HATCH); }
 	YY_BREAK
 case 243:
 YY_RULE_SETUP
 #line 412 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_LAYER_LINE); }
+{ MS_LEXER_RETURN_TOKEN(MS_HILITE); }
 	YY_BREAK
 case 244:
 YY_RULE_SETUP
 #line 413 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_LL); }
+{ MS_LEXER_RETURN_TOKEN(MS_INCHES); }
 	YY_BREAK
 case 245:
 YY_RULE_SETUP
 #line 414 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_LR); }
+{ MS_LEXER_RETURN_TOKEN(MS_KILOMETERS); }
 	YY_BREAK
 case 246:
 YY_RULE_SETUP
 #line 415 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_MEDIUM); }
+{ MS_LEXER_RETURN_TOKEN(MS_LARGE); }
 	YY_BREAK
 case 247:
 YY_RULE_SETUP
 #line 416 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_METERS); }
+{ MS_LEXER_RETURN_TOKEN(MS_LC); }
 	YY_BREAK
 case 248:
 YY_RULE_SETUP
 #line 417 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_NAUTICALMILES); }
+{ MS_LEXER_RETURN_TOKEN(MS_ALIGN_LEFT); }
 	YY_BREAK
 case 249:
 YY_RULE_SETUP
 #line 418 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_MILES); }
+{ MS_LEXER_RETURN_TOKEN(MS_LAYER_LINE); }
 	YY_BREAK
 case 250:
 YY_RULE_SETUP
 #line 419 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_CJC_MITER); }
+{ MS_LEXER_RETURN_TOKEN(MS_LL); }
 	YY_BREAK
 case 251:
 YY_RULE_SETUP
 #line 420 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_MULTIPLE); }
+{ MS_LEXER_RETURN_TOKEN(MS_LR); }
 	YY_BREAK
 case 252:
 YY_RULE_SETUP
 #line 421 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_CJC_NONE); }
+{ MS_LEXER_RETURN_TOKEN(MS_MEDIUM); }
 	YY_BREAK
 case 253:
 YY_RULE_SETUP
 #line 422 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_NORMAL); }
+{ MS_LEXER_RETURN_TOKEN(MS_METERS); }
 	YY_BREAK
 case 254:
 YY_RULE_SETUP
 #line 423 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_OFF); }
+{ MS_LEXER_RETURN_TOKEN(MS_NAUTICALMILES); }
 	YY_BREAK
 case 255:
 YY_RULE_SETUP
 #line 424 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_OGR); }
+{ MS_LEXER_RETURN_TOKEN(MS_MILES); }
 	YY_BREAK
 case 256:
 YY_RULE_SETUP
 #line 425 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_ON); }
+{ MS_LEXER_RETURN_TOKEN(MS_CJC_MITER); }
 	YY_BREAK
 case 257:
 YY_RULE_SETUP
 #line 426 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_JOIN_ONE_TO_ONE); }
+{ MS_LEXER_RETURN_TOKEN(MS_MULTIPLE); }
 	YY_BREAK
 case 258:
 YY_RULE_SETUP
 #line 427 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_JOIN_ONE_TO_MANY); }
+{ MS_LEXER_RETURN_TOKEN(MS_CJC_NONE); }
 	YY_BREAK
 case 259:
 YY_RULE_SETUP
 #line 428 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_ORACLESPATIAL); }
+{ MS_LEXER_RETURN_TOKEN(MS_NORMAL); }
 	YY_BREAK
 case 260:
 YY_RULE_SETUP
 #line 429 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_PERCENTAGES); }
+{ MS_LEXER_RETURN_TOKEN(MS_OFF); }
 	YY_BREAK
 case 261:
 YY_RULE_SETUP
 #line 430 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_SYMBOL_PIXMAP); }
+{ MS_LEXER_RETURN_TOKEN(MS_OGR); }
 	YY_BREAK
 case 262:
 YY_RULE_SETUP
 #line 431 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_PIXELS); }
+{ MS_LEXER_RETURN_TOKEN(MS_ON); }
 	YY_BREAK
 case 263:
 YY_RULE_SETUP
 #line 432 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_LAYER_POINT); }
+{ MS_LEXER_RETURN_TOKEN(MS_JOIN_ONE_TO_ONE); }
 	YY_BREAK
 case 264:
 YY_RULE_SETUP
 #line 433 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_LAYER_POLYGON); }
+{ MS_LEXER_RETURN_TOKEN(MS_JOIN_ONE_TO_MANY); }
 	YY_BREAK
 case 265:
 YY_RULE_SETUP
 #line 434 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_POSTGIS); }
+{ MS_LEXER_RETURN_TOKEN(MS_ORACLESPATIAL); }
 	YY_BREAK
 case 266:
 YY_RULE_SETUP
 #line 435 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_PLUGIN); }
+{ MS_LEXER_RETURN_TOKEN(MS_PERCENTAGES); }
 	YY_BREAK
 case 267:
 YY_RULE_SETUP
 #line 436 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_LAYER_QUERY); }
+{ MS_LEXER_RETURN_TOKEN(MS_SYMBOL_PIXMAP); }
 	YY_BREAK
 case 268:
 YY_RULE_SETUP
 #line 437 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_LAYER_RASTER); }
+{ MS_LEXER_RETURN_TOKEN(MS_PIXELS); }
 	YY_BREAK
 case 269:
 YY_RULE_SETUP
 #line 438 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_ALIGN_RIGHT); }
+{ MS_LEXER_RETURN_TOKEN(MS_LAYER_POINT); }
 	YY_BREAK
 case 270:
 YY_RULE_SETUP
 #line 439 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_CJC_ROUND); }
+{ MS_LEXER_RETURN_TOKEN(MS_LAYER_POLYGON); }
 	YY_BREAK
 case 271:
 YY_RULE_SETUP
 #line 440 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_SDE); }
+{ MS_LEXER_RETURN_TOKEN(MS_POSTGIS); }
 	YY_BREAK
 case 272:
 YY_RULE_SETUP
 #line 441 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_SELECTED); }
+{ MS_LEXER_RETURN_TOKEN(MS_PLUGIN); }
 	YY_BREAK
 case 273:
 YY_RULE_SETUP
 #line 442 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_SYMBOL_SIMPLE); }
+{ MS_LEXER_RETURN_TOKEN(MS_LAYER_QUERY); }
 	YY_BREAK
 case 274:
 YY_RULE_SETUP
 #line 443 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_SINGLE); }
+{ MS_LEXER_RETURN_TOKEN(MS_LAYER_RASTER); }
 	YY_BREAK
 case 275:
 YY_RULE_SETUP
 #line 444 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_SMALL); }
+{ MS_LEXER_RETURN_TOKEN(MS_ALIGN_RIGHT); }
 	YY_BREAK
 case 276:
 YY_RULE_SETUP
 #line 445 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_CJC_SQUARE); }
+{ MS_LEXER_RETURN_TOKEN(MS_CJC_ROUND); }
 	YY_BREAK
 case 277:
 YY_RULE_SETUP
 #line 446 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_SYMBOL_SVG); }
+{ MS_LEXER_RETURN_TOKEN(MS_SDE); }
 	YY_BREAK
 case 278:
 YY_RULE_SETUP
 #line 447 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_TINY); }
+{ MS_LEXER_RETURN_TOKEN(MS_SELECTED); }
 	YY_BREAK
 case 279:
 YY_RULE_SETUP
 #line 448 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_CJC_TRIANGLE); }
+{ MS_LEXER_RETURN_TOKEN(MS_SYMBOL_SIMPLE); }
 	YY_BREAK
 case 280:
 YY_RULE_SETUP
 #line 449 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_TRUE); }
+{ MS_LEXER_RETURN_TOKEN(MS_SINGLE); }
 	YY_BREAK
 case 281:
 YY_RULE_SETUP
 #line 450 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_TRUETYPE); }
+{ MS_LEXER_RETURN_TOKEN(MS_SMALL); }
 	YY_BREAK
 case 282:
 YY_RULE_SETUP
 #line 451 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_UC); }
+{ MS_LEXER_RETURN_TOKEN(MS_CJC_SQUARE); }
 	YY_BREAK
 case 283:
 YY_RULE_SETUP
 #line 452 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_UL); }
+{ MS_LEXER_RETURN_TOKEN(MS_SYMBOL_SVG); }
 	YY_BREAK
 case 284:
 YY_RULE_SETUP
 #line 453 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_UR); }
+{ MS_LEXER_RETURN_TOKEN(POLAROFFSET); }
 	YY_BREAK
 case 285:
 YY_RULE_SETUP
 #line 454 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_UNION); }
+{ MS_LEXER_RETURN_TOKEN(MS_TINY); }
 	YY_BREAK
 case 286:
 YY_RULE_SETUP
 #line 455 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_SYMBOL_VECTOR); }
+{ MS_LEXER_RETURN_TOKEN(MS_CJC_TRIANGLE); }
 	YY_BREAK
 case 287:
 YY_RULE_SETUP
 #line 456 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_WFS); }
+{ MS_LEXER_RETURN_TOKEN(MS_TRUE); }
 	YY_BREAK
 case 288:
 YY_RULE_SETUP
 #line 457 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_WMS); }
+{ MS_LEXER_RETURN_TOKEN(MS_TRUETYPE); }
 	YY_BREAK
 case 289:
 YY_RULE_SETUP
 #line 458 "maplexer.l"
-{ MS_LEXER_RETURN_TOKEN(MS_GD_ALPHA); }
+{ MS_LEXER_RETURN_TOKEN(MS_UC); }
 	YY_BREAK
 case 290:
 YY_RULE_SETUP
+#line 459 "maplexer.l"
+{ MS_LEXER_RETURN_TOKEN(MS_UL); }
+	YY_BREAK
+case 291:
+YY_RULE_SETUP
 #line 460 "maplexer.l"
+{ MS_LEXER_RETURN_TOKEN(MS_UR); }
+	YY_BREAK
+case 292:
+YY_RULE_SETUP
+#line 461 "maplexer.l"
+{ MS_LEXER_RETURN_TOKEN(MS_UNION); }
+	YY_BREAK
+case 293:
+YY_RULE_SETUP
+#line 462 "maplexer.l"
+{ MS_LEXER_RETURN_TOKEN(MS_UVRASTER); }
+	YY_BREAK
+case 294:
+YY_RULE_SETUP
+#line 463 "maplexer.l"
+{ MS_LEXER_RETURN_TOKEN(MS_SYMBOL_VECTOR); }
+	YY_BREAK
+case 295:
+YY_RULE_SETUP
+#line 464 "maplexer.l"
+{ MS_LEXER_RETURN_TOKEN(MS_WFS); }
+	YY_BREAK
+case 296:
+YY_RULE_SETUP
+#line 465 "maplexer.l"
+{ MS_LEXER_RETURN_TOKEN(MS_WMS); }
+	YY_BREAK
+case 297:
+YY_RULE_SETUP
+#line 466 "maplexer.l"
+{ MS_LEXER_RETURN_TOKEN(MS_GD_ALPHA); }
+	YY_BREAK
+case 298:
+YY_RULE_SETUP
+#line 468 "maplexer.l"
 {
                                                  msyytext++;
                                                  msyytext[strlen(msyytext)-1] = '\0';
@@ -3883,9 +3475,9 @@ YY_RULE_SETUP
                                                  return(MS_STRING);
                                                }
 	YY_BREAK
-case 291:
+case 299:
 YY_RULE_SETUP
-#line 468 "maplexer.l"
+#line 476 "maplexer.l"
 {
                                                  msyytext++;
                                                  msyytext[strlen(msyytext)-1] = '\0';
@@ -3896,10 +3488,10 @@ YY_RULE_SETUP
                                                  return(MS_NUMBER);
                                                }
 	YY_BREAK
-case 292:
-/* rule 292 can match eol */
+case 300:
+/* rule 300 can match eol */
 YY_RULE_SETUP
-#line 478 "maplexer.l"
+#line 486 "maplexer.l"
 {
                                                  msyytext++;
                                                  msyytext[strlen(msyytext)-1] = '\0';
@@ -3909,18 +3501,18 @@ YY_RULE_SETUP
                                                  return(MS_BINDING);
                                                }
 	YY_BREAK
-case 293:
+case 301:
 YY_RULE_SETUP
-#line 487 "maplexer.l"
+#line 495 "maplexer.l"
 { 
   /* attribute binding - shape (fixed value) */
   return(MS_TOKEN_BINDING_SHAPE);
 }
 	YY_BREAK
-case 294:
-/* rule 294 can match eol */
+case 302:
+/* rule 302 can match eol */
 YY_RULE_SETUP
-#line 491 "maplexer.l"
+#line 499 "maplexer.l"
 {
   /* attribute binding - numeric (no quotes) */
   msyytext++;
@@ -3931,10 +3523,10 @@ YY_RULE_SETUP
   return(MS_TOKEN_BINDING_DOUBLE);
 }
 	YY_BREAK
-case 295:
-/* rule 295 can match eol */
+case 303:
+/* rule 303 can match eol */
 YY_RULE_SETUP
-#line 500 "maplexer.l"
+#line 508 "maplexer.l"
 {
   /* attribute binding - string (single or double quotes) */
   msyytext+=2;
@@ -3945,10 +3537,10 @@ YY_RULE_SETUP
   return(MS_TOKEN_BINDING_STRING);
 }
 	YY_BREAK
-case 296:
-/* rule 296 can match eol */
+case 304:
+/* rule 304 can match eol */
 YY_RULE_SETUP
-#line 509 "maplexer.l"
+#line 517 "maplexer.l"
 {
   /* attribute binding - time */
   msyytext+=2;
@@ -3959,9 +3551,9 @@ YY_RULE_SETUP
   return(MS_TOKEN_BINDING_TIME);
 }
 	YY_BREAK
-case 297:
+case 305:
 YY_RULE_SETUP
-#line 519 "maplexer.l"
+#line 527 "maplexer.l"
 {
   MS_LEXER_STRING_REALLOC(msyystring_buffer, strlen(msyytext), 
                           msyystring_buffer_size, msyystring_buffer_ptr);
@@ -3970,9 +3562,9 @@ YY_RULE_SETUP
   return(MS_NUMBER); 
 }
 	YY_BREAK
-case 298:
+case 306:
 YY_RULE_SETUP
-#line 527 "maplexer.l"
+#line 535 "maplexer.l"
 {
   MS_LEXER_STRING_REALLOC(msyystring_buffer, strlen(msyytext), 
                           msyystring_buffer_size, msyystring_buffer_ptr);
@@ -3981,10 +3573,10 @@ YY_RULE_SETUP
   return(MS_TOKEN_LITERAL_NUMBER);
 }
 	YY_BREAK
-case 299:
-/* rule 299 can match eol */
+case 307:
+/* rule 307 can match eol */
 YY_RULE_SETUP
-#line 535 "maplexer.l"
+#line 543 "maplexer.l"
 {
   msyytext++;
   msyytext[strlen(msyytext)-1] = '\0';
@@ -3994,10 +3586,10 @@ YY_RULE_SETUP
   return(MS_TOKEN_LITERAL_TIME);
 }
 	YY_BREAK
-case 300:
-/* rule 300 can match eol */
+case 308:
+/* rule 308 can match eol */
 YY_RULE_SETUP
-#line 544 "maplexer.l"
+#line 552 "maplexer.l"
 {
                                                  msyytext++;
                                                  msyytext[strlen(msyytext)-2] = '\0';
@@ -4007,10 +3599,10 @@ YY_RULE_SETUP
                                                  return(MS_IREGEX);
                                                }
 	YY_BREAK
-case 301:
-/* rule 301 can match eol */
+case 309:
+/* rule 309 can match eol */
 YY_RULE_SETUP
-#line 553 "maplexer.l"
+#line 561 "maplexer.l"
 {
                                                  msyytext++;
                                                  msyytext[strlen(msyytext)-1] = '\0';
@@ -4020,9 +3612,9 @@ YY_RULE_SETUP
                                                  return(MS_REGEX);
                                                }
 	YY_BREAK
-case 302:
+case 310:
 YY_RULE_SETUP
-#line 562 "maplexer.l"
+#line 570 "maplexer.l"
 {
                                                  msyytext++;
                                                  msyytext[strlen(msyytext)-1] = '\0';
@@ -4032,9 +3624,9 @@ YY_RULE_SETUP
                                                  return(MS_EXPRESSION);
                                                }
 	YY_BREAK
-case 303:
+case 311:
 YY_RULE_SETUP
-#line 571 "maplexer.l"
+#line 579 "maplexer.l"
 {
                                                  msyystring_return_state = MS_STRING;
                                                  msyystring_begin = msyytext[0]; 
@@ -4043,9 +3635,9 @@ YY_RULE_SETUP
                                                  BEGIN(MSSTRING);
                                               }
 	YY_BREAK
-case 304:
+case 312:
 YY_RULE_SETUP
-#line 579 "maplexer.l"
+#line 587 "maplexer.l"
 {
                                                 MS_LEXER_STRING_REALLOC(msyystring_buffer, msyystring_size, 
                                                                                            msyystring_buffer_size, msyystring_buffer_ptr);
@@ -4076,9 +3668,9 @@ YY_RULE_SETUP
                                                 }
                                               }
 	YY_BREAK
-case 305:
+case 313:
 YY_RULE_SETUP
-#line 609 "maplexer.l"
+#line 617 "maplexer.l"
 { 
                                                 MS_LEXER_STRING_REALLOC(msyystring_buffer, msyystring_size, 
                                                                                            msyystring_buffer_size, msyystring_buffer_ptr);
@@ -4090,10 +3682,10 @@ YY_RULE_SETUP
                                                     *msyystring_buffer_ptr++ = msyytext[0];
                                              }
 	YY_BREAK
-case 306:
-/* rule 306 can match eol */
+case 314:
+/* rule 314 can match eol */
 YY_RULE_SETUP
-#line 620 "maplexer.l"
+#line 628 "maplexer.l"
 {
                                                  char *yptr = msyytext;
                                                  while ( *yptr ) { 
@@ -4104,10 +3696,10 @@ YY_RULE_SETUP
                                                  }
                                              }
 	YY_BREAK
-case 307:
-/* rule 307 can match eol */
+case 315:
+/* rule 315 can match eol */
 YY_RULE_SETUP
-#line 630 "maplexer.l"
+#line 638 "maplexer.l"
 {
                                                  msyytext++;
                                                  msyytext[strlen(msyytext)-1] = '\0';
@@ -4133,9 +3725,9 @@ YY_RULE_SETUP
                                                  BEGIN(INITIAL);
                                                }
 	YY_BREAK
-case 308:
+case 316:
 YY_RULE_SETUP
-#line 655 "maplexer.l"
+#line 663 "maplexer.l"
 {
                                                  msyystring_return_state = MS_TOKEN_LITERAL_STRING;
                                                  msyystring_begin = msyytext[0]; 
@@ -4144,9 +3736,9 @@ YY_RULE_SETUP
                                                  BEGIN(MSSTRING);
                                               }
 	YY_BREAK
-case 309:
+case 317:
 YY_RULE_SETUP
-#line 663 "maplexer.l"
+#line 671 "maplexer.l"
 { 
                                                     MS_LEXER_STRING_REALLOC(msyystring_buffer, strlen(msyytext), 
                                                                             msyystring_buffer_size, msyystring_buffer_ptr);
@@ -4154,14 +3746,14 @@ YY_RULE_SETUP
                                                     return(MS_STRING); 
                                                 }
 	YY_BREAK
-case 310:
-/* rule 310 can match eol */
+case 318:
+/* rule 318 can match eol */
 YY_RULE_SETUP
-#line 670 "maplexer.l"
+#line 678 "maplexer.l"
 { msyylineno++; }
 	YY_BREAK
 case YY_STATE_EOF(INITIAL):
-#line 672 "maplexer.l"
+#line 680 "maplexer.l"
 {
                                                   if( --include_stack_ptr < 0 )
                                                     return(EOF); /* end of main file */
@@ -4173,17 +3765,17 @@ case YY_STATE_EOF(INITIAL):
                                                   }
                                                 }
 	YY_BREAK
-case 311:
-/* rule 311 can match eol */
+case 319:
+/* rule 319 can match eol */
 YY_RULE_SETUP
-#line 683 "maplexer.l"
+#line 691 "maplexer.l"
 {
   return(0); 
 }
 	YY_BREAK
-case 312:
+case 320:
 YY_RULE_SETUP
-#line 687 "maplexer.l"
+#line 695 "maplexer.l"
 { 
                                                   MS_LEXER_STRING_REALLOC(msyystring_buffer, strlen(msyytext), 
                                                                           msyystring_buffer_size, msyystring_buffer_ptr);
@@ -4191,17 +3783,17 @@ YY_RULE_SETUP
                                                   return(0); 
                                                 }
 	YY_BREAK
-case 313:
+case 321:
 YY_RULE_SETUP
-#line 693 "maplexer.l"
+#line 701 "maplexer.l"
 { return(msyytext[0]); }
 	YY_BREAK
-case 314:
+case 322:
 YY_RULE_SETUP
-#line 694 "maplexer.l"
+#line 702 "maplexer.l"
 ECHO;
 	YY_BREAK
-#line 4205 "maplexer.c"
+#line 3797 "maplexer.c"
 case YY_STATE_EOF(URL_VARIABLE):
 case YY_STATE_EOF(URL_STRING):
 case YY_STATE_EOF(EXPRESSION_STRING):
@@ -4436,7 +4028,7 @@ static int yy_get_next_buffer (void)
 
 		/* Read in more data. */
 		YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]),
-			(yy_n_chars), (size_t) num_to_read );
+			(yy_n_chars), num_to_read );
 
 		YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
 		}
@@ -4460,14 +4052,6 @@ static int yy_get_next_buffer (void)
 	else
 		ret_val = EOB_ACT_CONTINUE_SCAN;
 
-	if ((yy_size_t) ((yy_n_chars) + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) {
-		/* Extend the array by 50%, plus the number we really need. */
-		yy_size_t new_size = (yy_n_chars) + number_to_move + ((yy_n_chars) >> 1);
-		YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) msyyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size  );
-		if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
-			YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" );
-	}
-
 	(yy_n_chars) += number_to_move;
 	YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] = YY_END_OF_BUFFER_CHAR;
 	YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] = YY_END_OF_BUFFER_CHAR;
@@ -4488,7 +4072,7 @@ static int yy_get_next_buffer (void)
 
 	for ( yy_cp = (yytext_ptr) + YY_MORE_ADJ; yy_cp < (yy_c_buf_p); ++yy_cp )
 		{
-		register YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 82);
+		register YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 56);
 		if ( yy_accept[yy_current_state] )
 			{
 			(yy_last_accepting_state) = yy_current_state;
@@ -4497,7 +4081,7 @@ static int yy_get_next_buffer (void)
 		while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
 			{
 			yy_current_state = (int) yy_def[yy_current_state];
-			if ( yy_current_state >= 1807 )
+			if ( yy_current_state >= 1854 )
 				yy_c = yy_meta[(unsigned int) yy_c];
 			}
 		yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
@@ -4516,7 +4100,7 @@ static int yy_get_next_buffer (void)
 	register int yy_is_jam;
     	register char *yy_cp = (yy_c_buf_p);
 
-	register YY_CHAR yy_c = 82;
+	register YY_CHAR yy_c = 56;
 	if ( yy_accept[yy_current_state] )
 		{
 		(yy_last_accepting_state) = yy_current_state;
@@ -4525,11 +4109,11 @@ static int yy_get_next_buffer (void)
 	while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
 		{
 		yy_current_state = (int) yy_def[yy_current_state];
-		if ( yy_current_state >= 1807 )
+		if ( yy_current_state >= 1854 )
 			yy_c = yy_meta[(unsigned int) yy_c];
 		}
 	yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
-	yy_is_jam = (yy_current_state == 1806);
+	yy_is_jam = (yy_current_state == 1853);
 
 	return yy_is_jam ? 0 : yy_current_state;
 }
@@ -4619,7 +4203,7 @@ static int yy_get_next_buffer (void)
 				case EOB_ACT_END_OF_FILE:
 					{
 					if ( msyywrap( ) )
-						return EOF;
+						return 0;
 
 					if ( ! (yy_did_buffer_switch_on_eof) )
 						YY_NEW_FILE;
@@ -4883,9 +4467,7 @@ static void msyyensure_buffer_stack (void)
 		(yy_buffer_stack) = (struct yy_buffer_state**)msyyalloc
 								(num_to_alloc * sizeof(struct yy_buffer_state*)
 								);
-		if ( ! (yy_buffer_stack) )
-			YY_FATAL_ERROR( "out of dynamic memory in msyyensure_buffer_stack()" );
-								  
+		
 		memset((yy_buffer_stack), 0, num_to_alloc * sizeof(struct yy_buffer_state*));
 				
 		(yy_buffer_stack_max) = num_to_alloc;
@@ -4903,8 +4485,6 @@ static void msyyensure_buffer_stack (void)
 								((yy_buffer_stack),
 								num_to_alloc * sizeof(struct yy_buffer_state*)
 								);
-		if ( ! (yy_buffer_stack) )
-			YY_FATAL_ERROR( "out of dynamic memory in msyyensure_buffer_stack()" );
 
 		/* zero only the new slots.*/
 		memset((yy_buffer_stack) + (yy_buffer_stack_max), 0, grow_size * sizeof(struct yy_buffer_state*));
@@ -4949,7 +4529,7 @@ YY_BUFFER_STATE msyy_scan_buffer  (char * base, yy_size_t  size )
 
 /** Setup the input buffer state to scan a string. The next call to msyylex() will
  * scan from a @e copy of @a str.
- * @param yystr a NUL-terminated string to scan
+ * @param str a NUL-terminated string to scan
  * 
  * @return the newly allocated buffer state object.
  * @note If you want to scan bytes that may contain NUL values, then use
@@ -4963,8 +4543,8 @@ YY_BUFFER_STATE msyy_scan_string (yyconst char * yystr )
 
 /** Setup the input buffer state to scan the given bytes. The next call to msyylex() will
  * scan from a @e copy of @a bytes.
- * @param yybytes the byte buffer to scan
- * @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes.
+ * @param bytes the byte buffer to scan
+ * @param len the number of bytes in the buffer pointed to by @a bytes.
  * 
  * @return the newly allocated buffer state object.
  */
@@ -5203,7 +4783,7 @@ void msyyfree (void * ptr )
 
 #define YYTABLES_NAME "yytables"
 
-#line 694 "maplexer.l"
+#line 702 "maplexer.l"
 
 
 
diff --git a/maplexer.l b/maplexer.l
index 6029f07..890c65e 100644
--- a/maplexer.l
+++ b/maplexer.l
@@ -184,6 +184,7 @@ char path[MS_MAXPATHLEN];
 <EXPRESSION_STRING>round                       { MS_LEXER_RETURN_TOKEN(MS_TOKEN_FUNCTION_ROUND); }
 
 <EXPRESSION_STRING>buffer                      { MS_LEXER_RETURN_TOKEN(MS_TOKEN_FUNCTION_BUFFER); }
+<EXPRESSION_STRING>difference                  { MS_LEXER_RETURN_TOKEN(MS_TOKEN_FUNCTION_DIFFERENCE); }
 
 <EXPRESSION_STRING>intersects                  { MS_LEXER_RETURN_TOKEN(MS_TOKEN_COMPARISON_INTERSECTS); }
 <EXPRESSION_STRING>disjoint                    { MS_LEXER_RETURN_TOKEN(MS_TOKEN_COMPARISON_DISJOINT); }
@@ -201,7 +202,8 @@ char path[MS_MAXPATHLEN];
 <INITIAL>datarange                             { MS_LEXER_RETURN_TOKEN(DATARANGE); }
 <INITIAL>rangeitem                             { MS_LEXER_RETURN_TOKEN(RANGEITEM); }
 
-<INITIAL,URL_STRING>align                       { MS_LEXER_RETURN_TOKEN(ALIGN); }
+<INITIAL,URL_STRING>align                      { MS_LEXER_RETURN_TOKEN(ALIGN); }
+<INITIAL>anchorpoint                           { MS_LEXER_RETURN_TOKEN(ANCHORPOINT); }
 <INITIAL,URL_VARIABLE,URL_STRING>angle         { MS_LEXER_RETURN_TOKEN(ANGLE); }
 <INITIAL,URL_STRING>antialias                  { MS_LEXER_RETURN_TOKEN(ANTIALIAS); }
 <INITIAL,URL_STRING>backgroundcolor            { MS_LEXER_RETURN_TOKEN(BACKGROUNDCOLOR); }
@@ -240,9 +242,10 @@ char path[MS_MAXPATHLEN];
 <INITIAL>force                                 { MS_LEXER_RETURN_TOKEN(FORCE); }
 <INITIAL>formatoption                          { MS_LEXER_RETURN_TOKEN(FORMATOPTION); }
 <INITIAL>from                                  { MS_LEXER_RETURN_TOKEN(FROM); }
-<INITIAL>gap                                   { MS_LEXER_RETURN_TOKEN(GAP); }
+<INITIAL,URL_STRING>gap                        { MS_LEXER_RETURN_TOKEN(GAP); }
 <INITIAL>geomtransform                         { MS_LEXER_RETURN_TOKEN(GEOMTRANSFORM); }
 <INITIAL>grid                                  { MS_LEXER_RETURN_TOKEN(GRID); }
+<INITIAL>gridstep                              { MS_LEXER_RETURN_TOKEN(GRIDSTEP); }
 <INITIAL>graticule                             { MS_LEXER_RETURN_TOKEN(GRATICULE); }
 <INITIAL,URL_STRING>group                      { MS_LEXER_RETURN_TOKEN(GROUP); }
 <INITIAL,URL_STRING>header                     { MS_LEXER_RETURN_TOKEN(HEADER); }
@@ -256,6 +259,7 @@ char path[MS_MAXPATHLEN];
 <INITIAL>imageurl                              { MS_LEXER_RETURN_TOKEN(IMAGEURL); }
 <INITIAL>include                               { BEGIN(INCLUDE); }
 <INITIAL>index                                 { MS_LEXER_RETURN_TOKEN(INDEX); }
+<INITIAL,URL_STRING>initialgap                 { MS_LEXER_RETURN_TOKEN(INITIALGAP); }
 <INITIAL>interlace                             { MS_LEXER_RETURN_TOKEN(INTERLACE); }
 <INITIAL,URL_STRING>intervals                  { MS_LEXER_RETURN_TOKEN(INTERVALS); } 
 <INITIAL>join                                  { MS_LEXER_RETURN_TOKEN(JOIN); }
@@ -273,6 +277,7 @@ char path[MS_MAXPATHLEN];
 <INITIAL,URL_STRING>labelrequires              { MS_LEXER_RETURN_TOKEN(LABELREQUIRES); }
 <INITIAL>latlon                                { MS_LEXER_RETURN_TOKEN(LATLON); }
 <INITIAL,URL_VARIABLE>layer                    { MS_LEXER_RETURN_TOKEN(LAYER); }
+<INITIAL>leader                                { MS_LEXER_RETURN_TOKEN(LEADER); }
 <INITIAL,URL_VARIABLE>legend                   { MS_LEXER_RETURN_TOKEN(LEGEND); }
 <INITIAL>legendformat                          { MS_LEXER_RETURN_TOKEN(LEGENDFORMAT); }
 <INITIAL>linecap                               { MS_LEXER_RETURN_TOKEN(LINECAP); }
@@ -282,13 +287,14 @@ char path[MS_MAXPATHLEN];
 <INITIAL,URL_VARIABLE>map                      { MS_LEXER_RETURN_TOKEN(MAP); }
 <INITIAL>marker                                { MS_LEXER_RETURN_TOKEN(MARKER); }
 <INITIAL>markersize                            { MS_LEXER_RETURN_TOKEN(MARKERSIZE); }
+<INITIAL>mask                                  { MS_LEXER_RETURN_TOKEN(MASK); }
 <INITIAL>maxarcs                               { MS_LEXER_RETURN_TOKEN(MAXARCS); }
 <INITIAL>maxboxsize                            { MS_LEXER_RETURN_TOKEN(MAXBOXSIZE); }
 <INITIAL>maxdistance                           { MS_LEXER_RETURN_TOKEN(MAXDISTANCE); }
 <INITIAL>maxfeatures                           { MS_LEXER_RETURN_TOKEN(MAXFEATURES); }
 <INITIAL>maxinterval                           { MS_LEXER_RETURN_TOKEN(MAXINTERVAL); }
-<INITIAL,URL_STRING>maxscale                   { MS_LEXER_RETURN_TOKEN(MAXSCALE); }
-<INITIAL,URL_STRING>maxscaledenom              { MS_LEXER_RETURN_TOKEN(MAXSCALEDENOM); }
+<INITIAL>maxscale                              { MS_LEXER_RETURN_TOKEN(MAXSCALE); }
+<INITIAL>maxscaledenom                         { MS_LEXER_RETURN_TOKEN(MAXSCALEDENOM); }
 <INITIAL>maxgeowidth                           { MS_LEXER_RETURN_TOKEN(MAXGEOWIDTH); }
 <INITIAL>maxlength                             { MS_LEXER_RETURN_TOKEN(MAXLENGTH); }
 <INITIAL>maxsize                               { MS_LEXER_RETURN_TOKEN(MAXSIZE); }
@@ -304,8 +310,8 @@ char path[MS_MAXPATHLEN];
 <INITIAL>maxoverlapangle                       { MS_LEXER_RETURN_TOKEN(MAXOVERLAPANGLE); } 
 <INITIAL>minfeaturesize                        { MS_LEXER_RETURN_TOKEN(MINFEATURESIZE); }
 <INITIAL>mininterval                           { MS_LEXER_RETURN_TOKEN(MININTERVAL); }
-<INITIAL,URL_STRING>minscale                   { MS_LEXER_RETURN_TOKEN(MINSCALE); }
-<INITIAL,URL_STRING>minscaledenom              { MS_LEXER_RETURN_TOKEN(MINSCALEDENOM); }
+<INITIAL>minscale                              { MS_LEXER_RETURN_TOKEN(MINSCALE); }
+<INITIAL>minscaledenom                         { MS_LEXER_RETURN_TOKEN(MINSCALEDENOM); }
 <INITIAL>mingeowidth                           { MS_LEXER_RETURN_TOKEN(MINGEOWIDTH); }
 <INITIAL>minlength                             { MS_LEXER_RETURN_TOKEN(MINLENGTH); }
 <INITIAL>minsize                               { MS_LEXER_RETURN_TOKEN(MINSIZE); }
@@ -313,7 +319,7 @@ char path[MS_MAXPATHLEN];
 <INITIAL>mintemplate                           { MS_LEXER_RETURN_TOKEN(MINTEMPLATE); }
 <INITIAL>minwidth                              { MS_LEXER_RETURN_TOKEN(MINWIDTH); }
 <INITIAL>name                                  { MS_LEXER_RETURN_TOKEN(NAME); }
-<INITIAL>offset                                { MS_LEXER_RETURN_TOKEN(OFFSET); }
+<INITIAL,URL_STRING>offset                     { MS_LEXER_RETURN_TOKEN(OFFSET); }
 <INITIAL>offsite                               { MS_LEXER_RETURN_TOKEN(OFFSITE); }
 <INITIAL,URL_STRING>opacity                    { MS_LEXER_RETURN_TOKEN(OPACITY); }
 <INITIAL,URL_STRING>outlinecolor               { MS_LEXER_RETURN_TOKEN(OUTLINECOLOR); }
@@ -327,7 +333,7 @@ char path[MS_MAXPATHLEN];
 <INITIAL,URL_STRING>overlaysize                { MS_LEXER_RETURN_TOKEN(OVERLAYSIZE); }
 <INITIAL,URL_STRING>overlaysymbol              { MS_LEXER_RETURN_TOKEN(OVERLAYSYMBOL); }
 <INITIAL>partials                              { MS_LEXER_RETURN_TOKEN(PARTIALS); }
-<INITIAL>pattern                               { MS_LEXER_RETURN_TOKEN(PATTERN); }
+<INITIAL,URL_STRING>pattern                    { MS_LEXER_RETURN_TOKEN(PATTERN); }
 <INITIAL,URL_STRING>points                     { MS_LEXER_RETURN_TOKEN(POINTS); }
 <INITIAL>items                                 { MS_LEXER_RETURN_TOKEN(ITEMS); }
 <INITIAL,URL_STRING>position                   { MS_LEXER_RETURN_TOKEN(POSITION); }
@@ -444,6 +450,7 @@ char path[MS_MAXPATHLEN];
 <INITIAL>small                                 { MS_LEXER_RETURN_TOKEN(MS_SMALL); }
 <INITIAL>square                                { MS_LEXER_RETURN_TOKEN(MS_CJC_SQUARE); }
 <INITIAL>svg                                   { MS_LEXER_RETURN_TOKEN(MS_SYMBOL_SVG); }
+<INITIAL>polaroffset                           { MS_LEXER_RETURN_TOKEN(POLAROFFSET); }
 <INITIAL>tiny                                  { MS_LEXER_RETURN_TOKEN(MS_TINY); }
 <INITIAL>triangle                              { MS_LEXER_RETURN_TOKEN(MS_CJC_TRIANGLE); }
 <INITIAL,URL_STRING>true                       { MS_LEXER_RETURN_TOKEN(MS_TRUE); }
@@ -452,6 +459,7 @@ char path[MS_MAXPATHLEN];
 <INITIAL,URL_STRING>ul                         { MS_LEXER_RETURN_TOKEN(MS_UL); }
 <INITIAL,URL_STRING>ur                         { MS_LEXER_RETURN_TOKEN(MS_UR); }
 <INITIAL>union                                 { MS_LEXER_RETURN_TOKEN(MS_UNION); }
+<INITIAL>uvraster                              { MS_LEXER_RETURN_TOKEN(MS_UVRASTER); }
 <INITIAL>vector                                { MS_LEXER_RETURN_TOKEN(MS_SYMBOL_VECTOR); }
 <INITIAL>wfs                                   { MS_LEXER_RETURN_TOKEN(MS_WFS); }
 <INITIAL>wms                                   { MS_LEXER_RETURN_TOKEN(MS_WMS); }
diff --git a/maplibxml2.c b/maplibxml2.c
index 52dfba9..c869431 100644
--- a/maplibxml2.c
+++ b/maplibxml2.c
@@ -36,7 +36,7 @@
 #include<libxml/xpath.h>
 #include<libxml/xpathInternals.h>
 
-MS_CVSID("$Id$")
+
 
 /**
  * msLibXml2GenerateList()
@@ -51,7 +51,8 @@ MS_CVSID("$Id$")
  *
  */
 
-void msLibXml2GenerateList(xmlNodePtr psParent, xmlNsPtr psNs, const char *elname, const char *values, char delim) {
+void msLibXml2GenerateList(xmlNodePtr psParent, xmlNsPtr psNs, const char *elname, const char *values, char delim)
+{
   char **tokens = NULL;
   int n = 0;
   int i = 0;
@@ -77,13 +78,14 @@ void msLibXml2GenerateList(xmlNodePtr psParent, xmlNsPtr psNs, const char *elnam
  *
  */
 
-xmlXPathObjectPtr msLibXml2GetXPath(xmlDocPtr doc, xmlXPathContextPtr context, xmlChar *xpath) {
+xmlXPathObjectPtr msLibXml2GetXPath(xmlDocPtr doc, xmlXPathContextPtr context, xmlChar *xpath)
+{
   xmlXPathObjectPtr result;
   result = xmlXPathEval(xpath, context);
   if (result == NULL) {
     return NULL;
   }
-  if(xmlXPathNodeSetIsEmpty(result->nodesetval)){
+  if(xmlXPathNodeSetIsEmpty(result->nodesetval)) {
     xmlXPathFreeObject(result);
     return NULL;
   }
@@ -102,7 +104,8 @@ xmlXPathObjectPtr msLibXml2GetXPath(xmlDocPtr doc, xmlXPathContextPtr context, x
  *
  */
 
-const char *msLibXml2GetXPathTree(xmlDocPtr doc, xmlXPathObjectPtr xpath) {
+const char *msLibXml2GetXPathTree(xmlDocPtr doc, xmlXPathObjectPtr xpath)
+{
   xmlBufferPtr xbuf;
   const char *result = NULL;
 
diff --git a/mapmssql2008.c b/mapmssql2008.c
index 2080995..a7cda77 100644
--- a/mapmssql2008.c
+++ b/mapmssql2008.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -27,7 +27,7 @@
  * DEALINGS IN THE SOFTWARE.
  ******************************************************************************
  *
- * Revision 1.0  2007/7/1 
+ * Revision 1.0  2007/7/1
  * Created.
  *
  */
@@ -49,29 +49,112 @@
 #include <string.h>
 #include <ctype.h> /* tolower() */
 
-MS_CVSID("$Id$")
+
+
+/* Native geometry parser macros */
+
+/* parser error codes */
+#define NOERROR 0
+#define NOT_ENOUGH_DATA 1
+#define CORRUPT_DATA 2
+#define UNSUPPORTED_GEOMETRY_TYPE 3
+
+/* geometry format to transfer geometry column */
+#define MSSQLGEOMETRY_NATIVE 0
+#define MSSQLGEOMETRY_WKB 1
+#define MSSQLGEOMETRY_WKT 2
+
+/* geometry column types */
+#define MSSQLCOLTYPE_GEOMETRY  0
+#define MSSQLCOLTYPE_GEOGRAPHY 1
+#define MSSQLCOLTYPE_BINARY 2
+#define MSSQLCOLTYPE_TEXT 3
+
+#define SP_NONE 0
+#define SP_HASZVALUES 1
+#define SP_HASMVALUES 2
+#define SP_ISVALID 4
+#define SP_ISSINGLEPOINT 8
+#define SP_ISSINGLELINESEGMENT 0x10
+#define SP_ISWHOLEGLOBE 0x20
+
+#define ST_UNKNOWN 0
+#define ST_POINT 1
+#define ST_LINESTRING 2
+#define ST_POLYGON 3
+#define ST_MULTIPOINT 4
+#define ST_MULTILINESTRING 5
+#define ST_MULTIPOLYGON 6
+#define ST_GEOMETRYCOLLECTION 7
+
+#define ReadInt32(nPos) (*((unsigned int*)(gpi->pszData + (nPos))))
+
+#define ReadByte(nPos) (gpi->pszData[nPos])
+
+#define ReadDouble(nPos) (*((double*)(gpi->pszData + (nPos))))
+
+#define ParentOffset(iShape) (ReadInt32(gpi->nShapePos + (iShape) * 9 ))
+#define FigureOffset(iShape) (ReadInt32(gpi->nShapePos + (iShape) * 9 + 4))
+#define ShapeType(iShape) (ReadByte(gpi->nShapePos + (iShape) * 9 + 8))
+
+#define NextFigureOffset(iShape) (iShape + 1 < gpi->nNumShapes? FigureOffset((iShape) +1) : gpi->nNumFigures)
+
+#define FigureAttribute(iFigure) (ReadByte(gpi->nFigurePos + (iFigure) * 5))
+#define PointOffset(iFigure) (ReadInt32(gpi->nFigurePos + (iFigure) * 5 + 1))
+#define NextPointOffset(iFigure) (iFigure + 1 < gpi->nNumFigures? PointOffset((iFigure) +1) : gpi->nNumPoints)
+
+#define ReadX(iPoint) (ReadDouble(gpi->nPointPos + 16 * (iPoint)))
+#define ReadY(iPoint) (ReadDouble(gpi->nPointPos + 16 * (iPoint) + 8))
+#define ReadZ(iPoint) (ReadDouble(gpi->nPointPos + 16 * gpi->nNumPoints + 8 * (iPoint)))
+#define ReadM(iPoint) (ReadDouble(gpi->nPointPos + 24 * gpi->nNumPoints + 8 * (iPoint)))
+
+/* Native geometry parser struct */
+typedef struct msGeometryParserInfo_t {
+  unsigned char* pszData;
+  int nLen;
+  /* serialization propeties */
+  char chProps;
+  /* point array */
+  int nPointSize;
+  int nPointPos;
+  int nNumPoints;
+  /* figure array */
+  int nFigurePos;
+  int nNumFigures;
+  /* shape array */
+  int nShapePos;
+  int nNumShapes;
+  int nSRSId;
+  /* geometry or geography */
+  int nColType;
+  /* bounds */
+  double minx;
+  double miny;
+  double maxx;
+  double maxy;
+} msGeometryParserInfo;
 
 /* Structure for connection to an ODBC database (Microsoft preferred way to connect to SQL Server 2005 from c/c++) */
-typedef struct msODBCconn_t
-{
-    SQLHENV     henv;               /* ODBC HENV */
-    SQLHDBC     hdbc;               /* ODBC HDBC */
-    SQLHSTMT    hstmt;              /* ODBC HSTMNT */
-    char        errorMessage[1024]; /* Last error message if any */
+typedef struct msODBCconn_t {
+  SQLHENV     henv;               /* ODBC HENV */
+  SQLHDBC     hdbc;               /* ODBC HDBC */
+  SQLHSTMT    hstmt;              /* ODBC HSTMNT */
+  char        errorMessage[1024]; /* Last error message if any */
 } msODBCconn;
 
-typedef struct ms_MSSQL2008_layer_info_t
-{
-    char        *sql;           /* sql query to send to DB */
-    long        row_num;        /* what row is the NEXT to be read (for random access) */
-	char		*geom_column;	/* name of the actual geometry column parsed from the LAYER's DATA field */
-    char		*geom_column_type;	/* the type of the geometry column */
-	char		*geom_table;	/* the table name or sub-select decalred in the LAYER's DATA field */
-    char        *urid_name;     /* name of user-specified unique identifier or OID */
-    char        *user_srid;     /* zero length = calculate, non-zero means using this value! */
-	char		*index_name;	/* hopefully this isn't necessary - but if the optimizer ain't cuttin' it... */
-
-    msODBCconn * conn;          /* Connection to db */
+typedef struct ms_MSSQL2008_layer_info_t {
+  char        *sql;           /* sql query to send to DB */
+  long        row_num;        /* what row is the NEXT to be read (for random access) */
+  char    *geom_column; /* name of the actual geometry column parsed from the LAYER's DATA field */
+  char    *geom_column_type;  /* the type of the geometry column */
+  char    *geom_table;  /* the table name or sub-select decalred in the LAYER's DATA field */
+  char        *urid_name;     /* name of user-specified unique identifier or OID */
+  char        *user_srid;     /* zero length = calculate, non-zero means using this value! */
+  char    *index_name;  /* hopefully this isn't necessary - but if the optimizer ain't cuttin' it... */
+
+  msODBCconn * conn;          /* Connection to db */
+  msGeometryParserInfo gpi;   /* struct for the geometry parser */
+  int geometry_format;        /* Geometry format to be retrieved from the database */
 } msMSSQL2008LayerInfo;
 
 #define SQL_COLUMN_NAME_MAX_LENGTH 128
@@ -85,106 +168,287 @@ typedef struct ms_MSSQL2008_layer_info_t
     "For more help, please see http://www.mapdotnet.com \n\n<br><br>" \
     "mapmssql2008.c - version of 2007/7/1.\n"
 
-/* Little dummy buffer used to clean up memory allocation */
-char dummyBuffer[1];
+/* Native geometry parser code */
+void ReadPoint(msGeometryParserInfo* gpi, pointObj* p, int iPoint, int iOrder)
+{
+  if (gpi->nColType == MSSQLCOLTYPE_GEOGRAPHY) {
+    p->x = ReadY(iPoint);
+    p->y = ReadX(iPoint);
+  } else {
+    p->x = ReadX(iPoint);
+    p->y = ReadY(iPoint);
+  }
+  /* calculate bounds */
+  if (iOrder == 0) {
+    gpi->minx = gpi->maxx = p->x;
+    gpi->miny = gpi->maxy = p->y;
+  } else {
+    if (gpi->minx > p->x) gpi->minx = p->x;
+    else if (gpi->maxx < p->x) gpi->maxx = p->x;
+    if (gpi->miny > p->y) gpi->miny = p->y;
+    else if (gpi->maxy < p->y) gpi->maxy = p->y;
+  }
+
+#ifdef USE_POINT_Z_M
+  if ( gpi->chProps & SP_HASZVALUES )
+    p->z = ReadZ(iPoint);
+  if ( gpi->chProps & SP_HASMVALUES )
+    p->z = ReadM(iPoint);
+#endif
+}
+
+int ParseSqlGeometry(msMSSQL2008LayerInfo* layerinfo, shapeObj *shape)
+{
+  msGeometryParserInfo* gpi = &layerinfo->gpi;
+
+  if (gpi->nLen < 10) {
+    msDebug("ParseSqlGeometry NOT_ENOUGH_DATA\n");
+    return NOT_ENOUGH_DATA;
+  }
+
+  /* store the SRS id for further use */
+  gpi->nSRSId = ReadInt32(0);
+
+  if ( ReadByte(4) != 1 ) {
+    msDebug("ParseSqlGeometry CORRUPT_DATA\n");
+    return CORRUPT_DATA;
+  }
+
+  gpi->chProps = ReadByte(5);
+
+  if ( gpi->chProps & SP_HASMVALUES )
+    gpi->nPointSize = 32;
+  else if ( gpi->chProps & SP_HASZVALUES )
+    gpi->nPointSize = 24;
+  else
+    gpi->nPointSize = 16;
+
+  if ( gpi->chProps & SP_ISSINGLEPOINT ) {
+    // single point geometry
+    gpi->nNumPoints = 1;
+    if (gpi->nLen < 6 + gpi->nPointSize) {
+      msDebug("ParseSqlGeometry NOT_ENOUGH_DATA\n");
+      return NOT_ENOUGH_DATA;
+    }
+
+    shape->type = MS_SHAPE_POINT;
+    shape->line = (lineObj *) msSmallMalloc(sizeof(lineObj));
+    shape->numlines = 1;
+    shape->line[0].point = (pointObj *) msSmallMalloc(sizeof(pointObj));
+    shape->line[0].numpoints = 1;
+    gpi->nPointPos = 6;
+
+    ReadPoint(gpi, &shape->line[0].point[0], 0, 0);
+  } else if ( gpi->chProps & SP_ISSINGLELINESEGMENT ) {
+    // single line segment with 2 points
+    gpi->nNumPoints = 2;
+    if (gpi->nLen < 6 + 2 * gpi->nPointSize) {
+      msDebug("ParseSqlGeometry NOT_ENOUGH_DATA\n");
+      return NOT_ENOUGH_DATA;
+    }
+
+    shape->type = MS_SHAPE_LINE;
+    shape->line = (lineObj *) msSmallMalloc(sizeof(lineObj));
+    shape->numlines = 1;
+    shape->line[0].point = (pointObj *) msSmallMalloc(sizeof(pointObj) * 2);
+    shape->line[0].numpoints = 2;
+    gpi->nPointPos = 6;
+
+    ReadPoint(gpi, &shape->line[0].point[0], 0, 0);
+    ReadPoint(gpi, &shape->line[0].point[1], 1, 1);
+  } else {
+    int iShape, iFigure;
+    // complex geometries
+    gpi->nNumPoints = ReadInt32(6);
+
+    if ( gpi->nNumPoints <= 0 ) {
+      return NOERROR;
+    }
+
+    // position of the point array
+    gpi->nPointPos = 10;
+
+    // position of the figures
+    gpi->nFigurePos = gpi->nPointPos + gpi->nPointSize * gpi->nNumPoints + 4;
+
+    if (gpi->nLen < gpi->nFigurePos) {
+      msDebug("ParseSqlGeometry NOT_ENOUGH_DATA\n");
+      return NOT_ENOUGH_DATA;
+    }
+
+    gpi->nNumFigures = ReadInt32(gpi->nFigurePos - 4);
+
+    if ( gpi->nNumFigures <= 0 ) {
+      return NOERROR;
+    }
+
+    // position of the shapes
+    gpi->nShapePos = gpi->nFigurePos + 5 * gpi->nNumFigures + 4;
+
+    if (gpi->nLen < gpi->nShapePos) {
+      msDebug("ParseSqlGeometry NOT_ENOUGH_DATA\n");
+      return NOT_ENOUGH_DATA;
+    }
+
+    gpi->nNumShapes = ReadInt32(gpi->nShapePos - 4);
+
+    if (gpi->nLen < gpi->nShapePos + 9 * gpi->nNumShapes) {
+      msDebug("ParseSqlGeometry NOT_ENOUGH_DATA\n");
+      return NOT_ENOUGH_DATA;
+    }
+
+    if ( gpi->nNumShapes <= 0 ) {
+      return NOERROR;
+    }
+
+    // pick up the root shape
+    if ( ParentOffset(0) != 0xFFFFFFFF) {
+      msDebug("ParseSqlGeometry CORRUPT_DATA\n");
+      return CORRUPT_DATA;
+    }
+
+    // determine the shape type
+    for (iShape = 0; iShape < gpi->nNumShapes; iShape++) {
+      unsigned char shapeType = ShapeType(iShape);
+      if (shapeType == ST_POINT || shapeType == ST_MULTIPOINT) {
+        shape->type = MS_SHAPE_POINT;
+        break;
+      } else if (shapeType == ST_LINESTRING || shapeType == ST_MULTILINESTRING) {
+        shape->type = MS_SHAPE_LINE;
+        break;
+      } else if (shapeType == ST_POLYGON || shapeType == ST_MULTIPOLYGON) {
+        shape->type = MS_SHAPE_POLYGON;
+        break;
+      }
+    }
+
+    shape->line = (lineObj *) msSmallMalloc(sizeof(lineObj) * gpi->nNumFigures);
+    shape->numlines = gpi->nNumFigures;
+    // read figures
+    for (iFigure = 0; iFigure < gpi->nNumFigures; iFigure++) {
+      int iPoint, iNextPoint, i;
+      iPoint = PointOffset(iFigure);
+      iNextPoint = NextPointOffset(iFigure);
+
+      shape->line[iFigure].point = (pointObj *) msSmallMalloc(sizeof(pointObj)*(iNextPoint - iPoint));
+
+      i = 0;
+      while (iPoint < iNextPoint) {
+        ReadPoint(gpi, &shape->line[iFigure].point[i], iPoint, i);
+        ++iPoint;
+        ++i;
+      }
+
+      shape->line[iFigure].numpoints = i;
+    }
+  }
+
+  /* set bounds */
+  shape->bounds.minx = gpi->minx;
+  shape->bounds.miny = gpi->miny;
+  shape->bounds.maxx = gpi->maxx;
+  shape->bounds.maxy = gpi->maxy;
+
+  return NOERROR;
+}
+
+/* MS SQL driver code*/
 
 msMSSQL2008LayerInfo *getMSSQL2008LayerInfo(const layerObj *layer)
 {
-    return layer->layerinfo;
+  return layer->layerinfo;
 }
 
 void setMSSQL2008LayerInfo(layerObj *layer, msMSSQL2008LayerInfo *MSSQL2008layerinfo)
 {
-     layer->layerinfo = (void*) MSSQL2008layerinfo;
+  layer->layerinfo = (void*) MSSQL2008layerinfo;
 }
 
 void handleSQLError(layerObj *layer)
 {
-   SQLCHAR       SqlState[6], Msg[SQL_MAX_MESSAGE_LENGTH];
-   SQLINTEGER    NativeError;
-   SQLSMALLINT   i, MsgLen;
-   SQLRETURN  rc;
-   msMSSQL2008LayerInfo *layerinfo = getMSSQL2008LayerInfo(layer);
-
-   if (layerinfo == NULL)
-       return;
-   
-    // Get the status records.
-   i = 1;
-   while ((rc = SQLGetDiagRec(SQL_HANDLE_STMT, layerinfo->conn->hstmt, i, SqlState, &NativeError,
-            Msg, sizeof(Msg), &MsgLen)) != SQL_NO_DATA) 
-   {
-      if(layer->debug) 
-      {
-            msDebug("SQLError: %s\n", Msg);
-      }
-      i++;
-   }
+  SQLCHAR       SqlState[6], Msg[SQL_MAX_MESSAGE_LENGTH];
+  SQLINTEGER    NativeError;
+  SQLSMALLINT   i, MsgLen;
+  SQLRETURN  rc;
+  msMSSQL2008LayerInfo *layerinfo = getMSSQL2008LayerInfo(layer);
+
+  if (layerinfo == NULL)
+    return;
+
+  // Get the status records.
+  i = 1;
+  while ((rc = SQLGetDiagRec(SQL_HANDLE_STMT, layerinfo->conn->hstmt, i, SqlState, &NativeError,
+                             Msg, sizeof(Msg), &MsgLen)) != SQL_NO_DATA) {
+    if(layer->debug) {
+      msDebug("SQLError: %s\n", Msg);
+    }
+    i++;
+  }
 }
 
 /* remove white space */
 /* dont send in empty strings or strings with just " " in them! */
 static char* removeWhite(char *str)
 {
-    int     initial;
-    char    *orig, *loc;
-
-    initial = strspn(str, " ");
-    if(initial) {
-        memmove(str, str + initial, strlen(str) - initial + 1);
-    }
-    /* now final */
-    if(strlen(str) == 0) {
-        return str;
-    }
-    if(str[strlen(str) - 1] == ' ') {
-        /* have to remove from end */
-        orig = str;
-        loc = &str[strlen(str) - 1];
-        while((*loc = ' ') && (loc >orig)) {
-            *loc = 0;
-            loc--;
-        }
-    }
+  int     initial;
+  char    *orig, *loc;
+
+  initial = strspn(str, " ");
+  if(initial) {
+    memmove(str, str + initial, strlen(str) - initial + 1);
+  }
+  /* now final */
+  if(strlen(str) == 0) {
     return str;
+  }
+  if(str[strlen(str) - 1] == ' ') {
+    /* have to remove from end */
+    orig = str;
+    loc = &str[strlen(str) - 1];
+    while((*loc = ' ') && (loc >orig)) {
+      *loc = 0;
+      loc--;
+    }
+  }
+  return str;
 }
 
 /* TODO Take a look at glibc's strcasestr */
 static char *strstrIgnoreCase(const char *haystack, const char *needle)
 {
-    char    *hay_lower;
-    char    *needle_lower;
-    int     len_hay,len_need;
-    int     t;
-    char    *loc;
-    int     match = -1;
+  char    *hay_lower;
+  char    *needle_lower;
+  int     len_hay,len_need;
+  int     t;
+  char    *loc;
+  int     match = -1;
 
-    len_hay = strlen(haystack);
-    len_need = strlen(needle);
+  len_hay = strlen(haystack);
+  len_need = strlen(needle);
 
-    hay_lower = (char*) msSmallMalloc(len_hay + 1);
-    needle_lower =(char*) msSmallMalloc(len_need + 1);
+  hay_lower = (char*) msSmallMalloc(len_hay + 1);
+  needle_lower =(char*) msSmallMalloc(len_need + 1);
 
 
-    for(t = 0; t < len_hay; t++) {
-        hay_lower[t] = (char)tolower(haystack[t]);
-    }
-    hay_lower[t] = 0;
+  for(t = 0; t < len_hay; t++) {
+    hay_lower[t] = (char)tolower(haystack[t]);
+  }
+  hay_lower[t] = 0;
 
-    for(t = 0; t < len_need; t++) {
-        needle_lower[t] = (char)tolower(needle[t]);
-    }
-    needle_lower[t] = 0;
+  for(t = 0; t < len_need; t++) {
+    needle_lower[t] = (char)tolower(needle[t]);
+  }
+  needle_lower[t] = 0;
 
-    loc = strstr(hay_lower, needle_lower);
-    if(loc) {
-        match = loc - hay_lower;
-    }
+  loc = strstr(hay_lower, needle_lower);
+  if(loc) {
+    match = loc - hay_lower;
+  }
 
-    msFree(hay_lower);
-    msFree(needle_lower);
+  msFree(hay_lower);
+  msFree(needle_lower);
 
-    return (char *) (match < 0 ? NULL : haystack + match);
+  return (char *) (match < 0 ? NULL : haystack + match);
 }
 
 static int msMSSQL2008LayerParseData(layerObj *layer, char **geom_column_name, char **geom_column_type, char **table_name, char **urid_name, char **user_srid, char **index_name, int debug);
@@ -192,119 +456,111 @@ static int msMSSQL2008LayerParseData(layerObj *layer, char **geom_column_name, c
 /* Close connection and handles */
 static void msMSSQL2008CloseConnection(void *conn_handle)
 {
-    msODBCconn * conn = (msODBCconn *) conn_handle;
-
-    if (!conn)
-    {
-        return;
-    }
-
-	if (conn->hstmt)
-	{
-		SQLFreeHandle(SQL_HANDLE_STMT, conn->hstmt);    
-	}
-	if (conn->hdbc)
-	{
-		SQLDisconnect(conn->hdbc);
-		SQLFreeHandle(SQL_HANDLE_DBC, conn->hdbc);
-	}
-	if (conn->henv)	
-	{
-		SQLFreeHandle(SQL_HANDLE_ENV, conn->henv);   
-	}
-
-	msFree(conn);
+  msODBCconn * conn = (msODBCconn *) conn_handle;
+
+  if (!conn) {
+    return;
+  }
+
+  if (conn->hstmt) {
+    SQLFreeHandle(SQL_HANDLE_STMT, conn->hstmt);
+  }
+  if (conn->hdbc) {
+    SQLDisconnect(conn->hdbc);
+    SQLFreeHandle(SQL_HANDLE_DBC, conn->hdbc);
+  }
+  if (conn->henv) {
+    SQLFreeHandle(SQL_HANDLE_ENV, conn->henv);
+  }
+
+  msFree(conn);
 }
 
 /* Set the error string for the connection */
 static void setConnError(msODBCconn *conn)
 {
-    SQLSMALLINT len;
+  SQLSMALLINT len;
 
-    SQLGetDiagField(SQL_HANDLE_DBC, conn->hdbc, 1, SQL_DIAG_MESSAGE_TEXT, (SQLPOINTER) conn->errorMessage, sizeof(conn->errorMessage), &len);
+  SQLGetDiagField(SQL_HANDLE_DBC, conn->hdbc, 1, SQL_DIAG_MESSAGE_TEXT, (SQLPOINTER) conn->errorMessage, sizeof(conn->errorMessage), &len);
 
-    conn->errorMessage[len] = 0;
+  conn->errorMessage[len] = 0;
 }
 
 /* Connect to db */
 static msODBCconn * mssql2008Connect(const char * connString)
 {
-    SQLCHAR fullConnString[1024];
-    SQLRETURN rc;
-    msODBCconn * conn = msSmallMalloc(sizeof(msODBCconn));
+  SQLCHAR fullConnString[1024];
+  SQLRETURN rc;
+  msODBCconn * conn = msSmallMalloc(sizeof(msODBCconn));
 
-    memset(conn, 0, sizeof(*conn));
+  memset(conn, 0, sizeof(*conn));
 
-    SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &conn->henv);
-    
-    SQLSetEnvAttr(conn->henv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER) SQL_OV_ODBC3, 0);
+  SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &conn->henv);
 
-    SQLAllocHandle(SQL_HANDLE_DBC, conn->henv, &conn->hdbc);
+  SQLSetEnvAttr(conn->henv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER) SQL_OV_ODBC3, 0);
 
-    snprintf((char*)fullConnString, sizeof(fullConnString), "DRIVER=SQL Server;%s", connString);
+  SQLAllocHandle(SQL_HANDLE_DBC, conn->henv, &conn->hdbc);
 
-    {
-        SQLCHAR outConnString[1024];
-        SQLSMALLINT outConnStringLen;
+  snprintf((char*)fullConnString, sizeof(fullConnString), "DRIVER=SQL Server;%s", connString);
 
-        rc = SQLDriverConnect(conn->hdbc, NULL, fullConnString, SQL_NTS, outConnString, 1024, &outConnStringLen, SQL_DRIVER_NOPROMPT);
-    }
+  {
+    SQLCHAR outConnString[1024];
+    SQLSMALLINT outConnStringLen;
 
-    if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO)
-    {
-        setConnError(conn);
+    rc = SQLDriverConnect(conn->hdbc, NULL, fullConnString, SQL_NTS, outConnString, 1024, &outConnStringLen, SQL_DRIVER_NOPROMPT);
+  }
 
-        return conn;
-    }
- 
-    SQLAllocHandle(SQL_HANDLE_STMT, conn->hdbc, &conn->hstmt);
+  if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) {
+    setConnError(conn);
 
     return conn;
+  }
+
+  SQLAllocHandle(SQL_HANDLE_STMT, conn->hdbc, &conn->hstmt);
+
+  return conn;
 }
 
 /* Set the error string for the statement execution */
 static void setStmntError(msODBCconn *conn)
 {
-    SQLSMALLINT len;
+  SQLSMALLINT len;
 
-    SQLGetDiagField(SQL_HANDLE_STMT, conn->hstmt, 1, SQL_DIAG_MESSAGE_TEXT, (SQLPOINTER) conn->errorMessage, sizeof(conn->errorMessage), &len);
+  SQLGetDiagField(SQL_HANDLE_STMT, conn->hstmt, 1, SQL_DIAG_MESSAGE_TEXT, (SQLPOINTER) conn->errorMessage, sizeof(conn->errorMessage), &len);
 
-    conn->errorMessage[len] = 0;
+  conn->errorMessage[len] = 0;
 }
 
 /* Execute SQL against connection. Set error string  if failed */
 static int executeSQL(msODBCconn *conn, const char * sql)
 {
-    SQLRETURN rc;
+  SQLRETURN rc;
 
-    SQLCloseCursor(conn->hstmt);
+  SQLCloseCursor(conn->hstmt);
 
-    rc = SQLExecDirect(conn->hstmt, (SQLCHAR *) sql, SQL_NTS);
+  rc = SQLExecDirect(conn->hstmt, (SQLCHAR *) sql, SQL_NTS);
 
-    if (rc == SQL_SUCCESS || rc == SQL_SUCCESS_WITH_INFO)
-    {
-        return 1;
-    }
-    else
-    {
-        setStmntError(conn);
-        return 0;
-    }
+  if (rc == SQL_SUCCESS || rc == SQL_SUCCESS_WITH_INFO) {
+    return 1;
+  } else {
+    setStmntError(conn);
+    return 0;
+  }
 }
 
 /* Get columns name from query results */
 static int columnName(msODBCconn *conn, int index, char *buffer, int bufferLength)
 {
-    SQLRETURN rc;
+  SQLRETURN rc;
 
-    SQLCHAR columnName[SQL_COLUMN_NAME_MAX_LENGTH + 1];
-    SQLSMALLINT columnNameLen;
-    SQLSMALLINT dataType;
-    SQLUINTEGER columnSize;
-    SQLSMALLINT decimalDigits;
-    SQLSMALLINT nullable;
+  SQLCHAR columnName[SQL_COLUMN_NAME_MAX_LENGTH + 1];
+  SQLSMALLINT columnNameLen;
+  SQLSMALLINT dataType;
+  SQLUINTEGER columnSize;
+  SQLSMALLINT decimalDigits;
+  SQLSMALLINT nullable;
 
-    rc = SQLDescribeCol(
+  rc = SQLDescribeCol(
          conn->hstmt,
          (SQLUSMALLINT)index,
          columnName,
@@ -315,478 +571,481 @@ static int columnName(msODBCconn *conn, int index, char *buffer, int bufferLengt
          &decimalDigits,
          &nullable);
 
-    if (rc == SQL_SUCCESS || rc == SQL_SUCCESS_WITH_INFO)
-    {
-        if (bufferLength < SQL_COLUMN_NAME_MAX_LENGTH + 1)
-            strlcpy(buffer, (const char *)columnName, bufferLength);
-        else
-            strlcpy(buffer, (const char *)columnName, SQL_COLUMN_NAME_MAX_LENGTH + 1);
-        return 1;
-    }
+  if (rc == SQL_SUCCESS || rc == SQL_SUCCESS_WITH_INFO) {
+    if (bufferLength < SQL_COLUMN_NAME_MAX_LENGTH + 1)
+      strlcpy(buffer, (const char *)columnName, bufferLength);
     else
-    {
-        setStmntError(conn);
-        return 0;
-    }
+      strlcpy(buffer, (const char *)columnName, SQL_COLUMN_NAME_MAX_LENGTH + 1);
+    return 1;
+  } else {
+    setStmntError(conn);
+    return 0;
+  }
 }
 
 /* open up a connection to the MS SQL 2008 database using the connection string in layer->connection */
 /* ie. "driver=<driver>;server=<server>;database=<database>;integrated security=?;user id=<username>;password=<password>" */
 int msMSSQL2008LayerOpen(layerObj *layer)
 {
-    msMSSQL2008LayerInfo  *layerinfo;
-    char                *index, *maskeddata;
-    int                 i, count;
-	char *conn_decrypted = NULL;
+  msMSSQL2008LayerInfo  *layerinfo;
+  char                *index, *maskeddata;
+  int                 i, count;
+  char *conn_decrypted = NULL;
 
+  if(layer->debug) {
+    msDebug("msMSSQL2008LayerOpen called datastatement: %s\n", layer->data);
+  }
+
+  if(getMSSQL2008LayerInfo(layer)) {
     if(layer->debug) {
-        msDebug("msMSSQL2008LayerOpen called datastatement: %s\n", layer->data);
+      msDebug("msMSSQL2008LayerOpen :: layer is already open!!\n");
     }
+    return MS_SUCCESS;  /* already open */
+  }
 
-    if(getMSSQL2008LayerInfo(layer)) {
-        if(layer->debug) {
-            msDebug("msMSSQL2008LayerOpen :: layer is already open!!\n");
-        }
-        return MS_SUCCESS;  /* already open */
-    }
+  if(!layer->data) {
+    msSetError(MS_QUERYERR, DATA_ERROR_MESSAGE, "msMSSQL2008LayerOpen()", "", "Error parsing MSSQL2008 data variable: nothing specified in DATA statement.<br><br>\n\nMore Help:<br><br>\n\n");
 
-    if(!layer->data) {
-        msSetError(MS_QUERYERR, DATA_ERROR_MESSAGE, "msMSSQL2008LayerOpen()", "", "Error parsing MSSQL2008 data variable: nothing specified in DATA statement.<br><br>\n\nMore Help:<br><br>\n\n");
+    return MS_FAILURE;
+  }
 
-        return MS_FAILURE;
-    }
+  if(!layer->connection) {
+    msSetError( MS_QUERYERR, "MSSQL connection parameter not specified.", "msMSSQL2008LayerOpen()");
+    return MS_FAILURE;
+  }
 
-    if(!layer->connection) {
-		msSetError( MS_QUERYERR, "MSSQL connection parameter not specified.", "msMSSQL2008LayerOpen()");
-        return MS_FAILURE;
+  /* have to setup a connection to the database */
+
+  layerinfo = (msMSSQL2008LayerInfo*) msSmallMalloc(sizeof(msMSSQL2008LayerInfo));
+
+  layerinfo->sql = NULL; /* calc later */
+  layerinfo->row_num = 0;
+  layerinfo->geom_column = NULL;
+  layerinfo->geom_column_type = NULL;
+  layerinfo->geom_table = NULL;
+  layerinfo->urid_name = NULL;
+  layerinfo->user_srid = NULL;
+  layerinfo->index_name = NULL;
+  layerinfo->conn = NULL;
+
+  layerinfo->conn = (msODBCconn *) msConnPoolRequest(layer);
+
+  if(!layerinfo->conn) {
+    if(layer->debug) {
+      msDebug("MSMSSQL2008LayerOpen -- shared connection not available.\n");
     }
 
-    /* have to setup a connection to the database */
+    /* Decrypt any encrypted token in connection and attempt to connect */
+    conn_decrypted = msDecryptStringTokens(layer->map, layer->connection);
+    if (conn_decrypted == NULL) {
+      return(MS_FAILURE);  /* An error should already have been produced */
+    }
 
-    layerinfo = (msMSSQL2008LayerInfo*) msSmallMalloc(sizeof(msMSSQL2008LayerInfo));
+    layerinfo->conn = mssql2008Connect(conn_decrypted);
 
-    layerinfo->sql = NULL; /* calc later */
-    layerinfo->row_num = 0;
-	layerinfo->geom_column = NULL;
-    layerinfo->geom_column_type = NULL;
-	layerinfo->geom_table = NULL;
-    layerinfo->urid_name = NULL;
-    layerinfo->user_srid = NULL;
-	layerinfo->index_name = NULL;
-    layerinfo->conn = NULL;
+    msFree(conn_decrypted);
+    conn_decrypted = NULL;
 
-    layerinfo->conn = (msODBCconn *) msConnPoolRequest(layer);
+    if(!layerinfo->conn || layerinfo->conn->errorMessage[0]) {
+      char *errMess = "Out of memory";
 
-    if(!layerinfo->conn) {
-        if(layer->debug) {
-            msDebug("MSMSSQL2008LayerOpen -- shared connection not available.\n");
-        }
-                
-        /* Decrypt any encrypted token in connection and attempt to connect */
-        conn_decrypted = msDecryptStringTokens(layer->map, layer->connection);
-        if (conn_decrypted == NULL)
-		{
-			return(MS_FAILURE);  /* An error should already have been produced */
+      msDebug("FAILURE!!!");
+      maskeddata = (char *)msSmallMalloc(strlen(layer->connection) + 1);
+      strcpy(maskeddata, layer->connection);
+      index = strstr(maskeddata, "password=");
+      if(index != NULL) {
+        index = (char *)(index + 9);
+        count = (int)(strstr(index, " ") - index);
+        for(i = 0; i < count; i++) {
+          strlcpy(index, "*", (int)1);
+          index++;
         }
+      }
 
-		layerinfo->conn = mssql2008Connect(conn_decrypted);
-
-		msFree(conn_decrypted);
-		conn_decrypted = NULL;
-
-        if(!layerinfo->conn || layerinfo->conn->errorMessage[0]) 
-        {
-            char *errMess = "Out of memory";
-
-            msDebug("FAILURE!!!");
-            maskeddata = (char *)msSmallMalloc(strlen(layer->connection) + 1);
-            strcpy(maskeddata, layer->connection);
-            index = strstr(maskeddata, "password=");
-            if(index != NULL) {
-              index = (char *)(index + 9);
-              count = (int)(strstr(index, " ") - index);
-              for(i = 0; i < count; i++) {
-                  strlcpy(index, "*", (int)1);
-                  index++;
-              }
-            }
-            
-            if (layerinfo->conn)
-            {
-                errMess = layerinfo->conn->errorMessage;
-            }
+      if (layerinfo->conn) {
+        errMess = layerinfo->conn->errorMessage;
+      }
 
-            msSetError(MS_QUERYERR, 
-                "Couldnt make connection to MS SQL Server 2008 with connect string '%s'.\n<br>\n"
-                "Error reported was '%s'.\n<br>\n\n"
-                "This error occured when trying to make a connection to the specified SQL server.  \n"
-                "<br>\nMost commonly this is caused by <br>\n"
-                "(1) incorrect connection string <br>\n"
-                "(2) you didnt specify a 'user id=...' in your connection string <br>\n"
-                "(3) SQL server isnt running <br>\n"
-                "(4) TCPIP not enabled for SQL Client or server <br>\n\n", 
-                "msMSSQL2008LayerOpen()", maskeddata, errMess);
-
-            msFree(maskeddata);
-            msMSSQL2008CloseConnection(layerinfo->conn);
-            msFree(layerinfo);
-            return MS_FAILURE;
-        }
+      msSetError(MS_QUERYERR,
+                 "Couldnt make connection to MS SQL Server 2008 with connect string '%s'.\n<br>\n"
+                 "Error reported was '%s'.\n<br>\n\n"
+                 "This error occured when trying to make a connection to the specified SQL server.  \n"
+                 "<br>\nMost commonly this is caused by <br>\n"
+                 "(1) incorrect connection string <br>\n"
+                 "(2) you didnt specify a 'user id=...' in your connection string <br>\n"
+                 "(3) SQL server isnt running <br>\n"
+                 "(4) TCPIP not enabled for SQL Client or server <br>\n\n",
+                 "msMSSQL2008LayerOpen()", maskeddata, errMess);
 
-        msConnPoolRegister(layer, layerinfo->conn, msMSSQL2008CloseConnection);
+      msFree(maskeddata);
+      msMSSQL2008CloseConnection(layerinfo->conn);
+      msFree(layerinfo);
+      return MS_FAILURE;
     }
 
-    setMSSQL2008LayerInfo(layer, layerinfo);
+    msConnPoolRegister(layer, layerinfo->conn, msMSSQL2008CloseConnection);
+  }
 
-    if (msMSSQL2008LayerParseData(layer, &layerinfo->geom_column, &layerinfo->geom_column_type, &layerinfo->geom_table, &layerinfo->urid_name, &layerinfo->user_srid, &layerinfo->index_name, layer->debug) != MS_SUCCESS)
-	{
-		msSetError( MS_QUERYERR, "Could not parse the layer data", "msMSSQL2008LayerOpen()");
-        return MS_FAILURE;
-    }
+  setMSSQL2008LayerInfo(layer, layerinfo);
 
-    return MS_SUCCESS;
+  if (msMSSQL2008LayerParseData(layer, &layerinfo->geom_column, &layerinfo->geom_column_type, &layerinfo->geom_table, &layerinfo->urid_name, &layerinfo->user_srid, &layerinfo->index_name, layer->debug) != MS_SUCCESS) {
+    msSetError( MS_QUERYERR, "Could not parse the layer data", "msMSSQL2008LayerOpen()");
+    return MS_FAILURE;
+  }
+
+  /* identify the geometry transfer type */
+  if (msLayerGetProcessingKey( layer, "MSSQL_READ_WKB" ) != NULL)
+    layerinfo->geometry_format = MSSQLGEOMETRY_WKB;
+  else {
+    layerinfo->geometry_format = MSSQLGEOMETRY_NATIVE;
+    if (strcasecmp(layerinfo->geom_column_type, "geography") == 0)
+      layerinfo->gpi.nColType = MSSQLCOLTYPE_GEOGRAPHY;
+    else
+      layerinfo->gpi.nColType = MSSQLCOLTYPE_GEOMETRY;
+  }
+
+  return MS_SUCCESS;
 }
 
 /* Return MS_TRUE if layer is open, MS_FALSE otherwise. */
 int msMSSQL2008LayerIsOpen(layerObj *layer)
 {
-    return getMSSQL2008LayerInfo(layer) ? MS_TRUE : MS_FALSE;
+  return getMSSQL2008LayerInfo(layer) ? MS_TRUE : MS_FALSE;
 }
 
 
 /* Free the itemindexes array in a layer. */
 void msMSSQL2008LayerFreeItemInfo(layerObj *layer)
 {
-    if(layer->debug) {
-        msDebug("msMSSQL2008LayerFreeItemInfo called\n");
-    }
+  if(layer->debug) {
+    msDebug("msMSSQL2008LayerFreeItemInfo called\n");
+  }
 
-    if(layer->iteminfo) {
-        msFree(layer->iteminfo);
-    }
+  if(layer->iteminfo) {
+    msFree(layer->iteminfo);
+  }
 
-    layer->iteminfo = NULL;
+  layer->iteminfo = NULL;
 }
 
 
 /* allocate the iteminfo index array - same order as the item list */
 int msMSSQL2008LayerInitItemInfo(layerObj *layer)
 {
-    int     i;
-    int     *itemindexes ;
+  int     i;
+  int     *itemindexes ;
 
-    if (layer->debug) {
-        msDebug("msMSSQL2008LayerInitItemInfo called\n");
-    }
+  if (layer->debug) {
+    msDebug("msMSSQL2008LayerInitItemInfo called\n");
+  }
 
-    if(layer->numitems == 0) {
-        return MS_SUCCESS;
-    }
+  if(layer->numitems == 0) {
+    return MS_SUCCESS;
+  }
 
-    msFree(layer->iteminfo);
+  msFree(layer->iteminfo);
 
-    layer->iteminfo = (int *) msSmallMalloc(sizeof(int) * layer->numitems);
+  layer->iteminfo = (int *) msSmallMalloc(sizeof(int) * layer->numitems);
 
-    itemindexes = (int*)layer->iteminfo;
+  itemindexes = (int*)layer->iteminfo;
 
-    for(i = 0; i < layer->numitems; i++) {
-        itemindexes[i] = i; /* last one is always the geometry one - the rest are non-geom */
-    }
+  for(i = 0; i < layer->numitems; i++) {
+    itemindexes[i] = i; /* last one is always the geometry one - the rest are non-geom */
+  }
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 /* Prepare and execute the SQL statement for this layer */
 static int prepare_database(layerObj *layer, rectObj rect, char **query_string)
 {
-    msMSSQL2008LayerInfo *layerinfo;
-    char        *columns_wanted = 0;
-    char        *data_source = 0;
-    char        *f_table_name = 0;
-	char		*geom_table = 0;
-	/*
-		"Geometry::STGeomFromText('POLYGON(())',)" + terminator = 40 chars
-		Plus 10 formatted doubles (15 digits of precision, a decimal point, a space/comma delimiter each = 17 chars each)
-		Plus SRID + comma - if SRID is a long...we'll be safe with 10 chars 
-	*/
-	char        box3d[40 + 10 * 22 + 11];
-    char        query_string_temp[10000];       /* Should be big enough */
-    int         t;
-
-    char        *pos_from, *pos_ftab, *pos_space, *pos_paren;
-
-    layerinfo =  getMSSQL2008LayerInfo(layer);
-
-    /* Extract the proper f_table_name from the geom_table string.
-     * We are expecting the geom_table to be either a single word
-     * or a sub-select clause that possibly includes a join --
-     *
-     * (select column[,column[,...]] from ftab[ natural join table2]) as foo
-     *
-     * We are expecting whitespace or a ')' after the ftab name.
-     *
-     */
-
-	geom_table = msStrdup(layerinfo->geom_table);
-    pos_from = strstrIgnoreCase(geom_table, " from ");
-
-    if(!pos_from) {
-        f_table_name = (char *) msSmallMalloc(strlen(geom_table) + 1);
-        strcpy(f_table_name, geom_table);
-    } else { /* geom_table is a sub-select clause */
-        pos_ftab = pos_from + 6; /* This should be the start of the ftab name */
-        pos_space = strstr(pos_ftab, " "); /* First space */
-
-        /* TODO strrchr is POSIX and C99, rindex is neither */
+  msMSSQL2008LayerInfo *layerinfo;
+  char        *columns_wanted = 0;
+  char        *data_source = 0;
+  char        *f_table_name = 0;
+  char    *geom_table = 0;
+  /*
+    "Geometry::STGeomFromText('POLYGON(())',)" + terminator = 40 chars
+    Plus 10 formatted doubles (15 digits of precision, a decimal point, a space/comma delimiter each = 17 chars each)
+    Plus SRID + comma - if SRID is a long...we'll be safe with 10 chars
+  */
+  char        box3d[40 + 10 * 22 + 11];
+  char        query_string_temp[10000];       /* Should be big enough */
+  int         t;
+
+  char        *pos_from, *pos_ftab, *pos_space, *pos_paren;
+  rectObj     extent;
+
+  layerinfo =  getMSSQL2008LayerInfo(layer);
+
+  /* Extract the proper f_table_name from the geom_table string.
+   * We are expecting the geom_table to be either a single word
+   * or a sub-select clause that possibly includes a join --
+   *
+   * (select column[,column[,...]] from ftab[ natural join table2]) as foo
+   *
+   * We are expecting whitespace or a ')' after the ftab name.
+   *
+   */
+
+  geom_table = msStrdup(layerinfo->geom_table);
+  pos_from = strstrIgnoreCase(geom_table, " from ");
+
+  if(!pos_from) {
+    f_table_name = (char *) msSmallMalloc(strlen(geom_table) + 1);
+    strcpy(f_table_name, geom_table);
+  } else { /* geom_table is a sub-select clause */
+    pos_ftab = pos_from + 6; /* This should be the start of the ftab name */
+    pos_space = strstr(pos_ftab, " "); /* First space */
+
+    /* TODO strrchr is POSIX and C99, rindex is neither */
 #if defined(_WIN32) && !defined(__CYGWIN__)
-        pos_paren = strrchr(pos_ftab, ')');
+    pos_paren = strrchr(pos_ftab, ')');
 #else
-        pos_paren = rindex(pos_ftab, ')');
+    pos_paren = rindex(pos_ftab, ')');
 #endif
 
-        if(!pos_space || !pos_paren) {
-            msSetError(MS_QUERYERR, DATA_ERROR_MESSAGE, "prepare_database()", geom_table, "Error parsing MSSQL2008 data variable: Something is wrong with your subselect statement.<br><br>\n\nMore Help:<br><br>\n\n");
-
-            return MS_FAILURE;
-        }
+    if(!pos_space || !pos_paren) {
+      msSetError(MS_QUERYERR, DATA_ERROR_MESSAGE, "prepare_database()", geom_table, "Error parsing MSSQL2008 data variable: Something is wrong with your subselect statement.<br><br>\n\nMore Help:<br><br>\n\n");
 
-        if (pos_paren < pos_space) { /* closing parenthesis preceeds any space */
-            f_table_name = (char *) msSmallMalloc(pos_paren - pos_ftab + 1);
-            strlcpy(f_table_name, pos_ftab, pos_paren - pos_ftab + 1);
-        } else {
-            f_table_name = (char *) msSmallMalloc(pos_space - pos_ftab + 1);
-            strlcpy(f_table_name, pos_ftab, pos_space - pos_ftab + 1);
-        }
+      return MS_FAILURE;
     }
 
-    if(layer->numitems == 0) 
-    {
-        char buffer[1000];
+    if (pos_paren < pos_space) { /* closing parenthesis preceeds any space */
+      f_table_name = (char *) msSmallMalloc(pos_paren - pos_ftab + 1);
+      strlcpy(f_table_name, pos_ftab, pos_paren - pos_ftab + 1);
+    } else {
+      f_table_name = (char *) msSmallMalloc(pos_space - pos_ftab + 1);
+      strlcpy(f_table_name, pos_ftab, pos_space - pos_ftab + 1);
+    }
+  }
 
-        snprintf(buffer, sizeof(buffer), "%s.STAsBinary(),convert(varchar(36), %s)", layerinfo->geom_column, layerinfo->urid_name);
+  if(layer->numitems == 0) {
+    char buffer[1000];
 
-        columns_wanted = msStrdup(buffer);
-    } 
-    else 
-    {
-        char buffer[10000] = "";
-
-        for(t = 0; t < layer->numitems; t++) {
-            snprintf(buffer + strlen(buffer), sizeof(buffer) - strlen(buffer), "convert(varchar(max), %s),", layer->items[t]);
-        }
+    if (layerinfo->geometry_format == MSSQLGEOMETRY_NATIVE)
+      snprintf(buffer, sizeof(buffer), "[%s],convert(varchar(36), [%s])", layerinfo->geom_column, layerinfo->urid_name);
+    else
+      snprintf(buffer, sizeof(buffer), "[%s].STAsBinary(),convert(varchar(36), [%s])", layerinfo->geom_column, layerinfo->urid_name);
 
-        snprintf(buffer + strlen(buffer), sizeof(buffer) - strlen(buffer), "%s.STAsBinary(),convert(varchar(36), %s)", layerinfo->geom_column, layerinfo->urid_name);
+    columns_wanted = msStrdup(buffer);
+  } else {
+    char buffer[10000] = "";
 
-        columns_wanted = msStrdup(buffer);
+    for(t = 0; t < layer->numitems; t++) {
+      snprintf(buffer + strlen(buffer), sizeof(buffer) - strlen(buffer), "convert(varchar(max), [%s]),", layer->items[t]);
     }
 
-	if (rect.minx == rect.maxx || rect.miny == rect.maxy)
-    {
-        /* create point shape for rectangles with zero area */
-        sprintf(box3d, "%s::STGeomFromText('POINT(%.15g %.15g)',%s)", /* %s.STSrid)", */
-		    layerinfo->geom_column_type, rect.minx, rect.miny, layerinfo->user_srid);
-    }
+    if (layerinfo->geometry_format == MSSQLGEOMETRY_NATIVE)
+      snprintf(buffer + strlen(buffer), sizeof(buffer) - strlen(buffer), "[%s],convert(varchar(36), [%s])", layerinfo->geom_column, layerinfo->urid_name);
     else
-    {
-	    sprintf(box3d, "%s::STGeomFromText('POLYGON((%.15g %.15g,%.15g %.15g,%.15g %.15g,%.15g %.15g,%.15g %.15g))',%s)", /* %s.STSrid)", */
-		    layerinfo->geom_column_type,
-            rect.minx, rect.miny, 
-		    rect.maxx, rect.miny, 
-		    rect.maxx, rect.maxy, 
-		    rect.minx, rect.maxy,
-		    rect.minx, rect.miny,
+      snprintf(buffer + strlen(buffer), sizeof(buffer) - strlen(buffer), "[%s].STAsBinary(),convert(varchar(36), [%s])", layerinfo->geom_column, layerinfo->urid_name);
+
+    columns_wanted = msStrdup(buffer);
+  }
+
+  if (rect.minx == rect.maxx || rect.miny == rect.maxy) {
+    /* create point shape for rectangles with zero area */
+    sprintf(box3d, "%s::STGeomFromText('POINT(%.15g %.15g)',%s)", /* %s.STSrid)", */
+            layerinfo->geom_column_type, rect.minx, rect.miny, layerinfo->user_srid);
+  } else {
+    sprintf(box3d, "%s::STGeomFromText('POLYGON((%.15g %.15g,%.15g %.15g,%.15g %.15g,%.15g %.15g,%.15g %.15g))',%s)", /* %s.STSrid)", */
+            layerinfo->geom_column_type,
+            rect.minx, rect.miny,
+            rect.maxx, rect.miny,
+            rect.maxx, rect.maxy,
+            rect.minx, rect.maxy,
+            rect.minx, rect.miny,
             layerinfo->user_srid
-            );
-    }
-
-    /* substitute token '!BOX!' in geom_table with the box3d - do an unlimited # of subs */
-    /* to not undo the work here, we need to make sure that data_source is malloc'd here */
-
-    if(!strstr(geom_table, "!BOX!")) 
-    {
-        data_source = (char *) msSmallMalloc(strlen(geom_table) + 1);
-        strcpy(data_source, geom_table);
-    } 
-    else 
-    {
-        char* result = NULL;
-
-        while (strstr(geom_table,"!BOX!"))
-        {
-            /* need to do a substition */
-            char    *start, *end;
-            char    *oldresult = result;
-            start = strstr(geom_table,"!BOX!");
-            end = start+5;
-
-            result = (char *)msSmallMalloc((start - geom_table) + strlen(box3d) + strlen(end) +1);
-
-            strlcpy(result, geom_table, start - geom_table + 1);
-            strcpy(result + (start - geom_table), box3d);
-            strcat(result, end);
-
-            geom_table= result;
-            msFree(oldresult);
-        }
-
-       /* if we're here, this will be a malloc'd string, so no need to copy it */
-        data_source = (char *)geom_table;
-    }
-
-	/* use the index hint if provided */
-	if ( layerinfo->index_name )
-	{
-		/* given the template - figure out how much to malloc and malloc it */
-		char *with_template = "%s WITH (INDEX(%s))";
-		int need_len = strlen(data_source) + strlen(with_template) + strlen(layerinfo->index_name);
-		char *tmp = (char*) msSmallMalloc( need_len + 1 );
-		sprintf( tmp, with_template, data_source, layerinfo->index_name );
-		msFree(data_source);
-		data_source = tmp;
-	}
-
-    if(!layer->filter.string) 
-    {
-        snprintf(query_string_temp, sizeof(query_string_temp),  "SELECT %s from %s WHERE %s.STIntersects(%s) = 1 ", 
-            columns_wanted, data_source, layerinfo->geom_column, box3d );
-    } 
-    else 
-    {
-        snprintf(query_string_temp, sizeof(query_string_temp), "SELECT %s from %s WHERE (%s) and %s.STIntersects(%s) = 1 ",
-            columns_wanted, data_source, layer->filter.string, layerinfo->geom_column, box3d );
-    }
-
+           );
+  }
+
+  /* substitute token '!BOX!' in geom_table with the box3d - do an unlimited # of subs */
+  /* to not undo the work here, we need to make sure that data_source is malloc'd here */
+
+  if(!strstr(geom_table, "!BOX!")) {
+    data_source = (char *) msSmallMalloc(strlen(geom_table) + 1);
+    strcpy(data_source, geom_table);
+  } else {
+    char* result = NULL;
+
+    while (strstr(geom_table,"!BOX!")) {
+      /* need to do a substition */
+      char    *start, *end;
+      char    *oldresult = result;
+      start = strstr(geom_table,"!BOX!");
+      end = start+5;
+
+      result = (char *)msSmallMalloc((start - geom_table) + strlen(box3d) + strlen(end) +1);
+
+      strlcpy(result, geom_table, start - geom_table + 1);
+      strcpy(result + (start - geom_table), box3d);
+      strcat(result, end);
+
+      geom_table= result;
+      msFree(oldresult);
+    }
+
+    /* if we're here, this will be a malloc'd string, so no need to copy it */
+    data_source = (char *)geom_table;
+  }
+
+  /* use the index hint if provided */
+  if ( layerinfo->index_name ) {
+    /* given the template - figure out how much to malloc and malloc it */
+    char *with_template = "%s WITH (INDEX(%s))";
+    int need_len = strlen(data_source) + strlen(with_template) + strlen(layerinfo->index_name);
+    char *tmp = (char*) msSmallMalloc( need_len + 1 );
+    sprintf( tmp, with_template, data_source, layerinfo->index_name );
     msFree(data_source);
-    msFree(f_table_name);
-    msFree(columns_wanted);
+    data_source = tmp;
+  }
+
+  /* test whether we should omit spatial filtering */
+  msMSSQL2008LayerGetExtent(layer, &extent);
+  if (rect.minx <= extent.minx && rect.miny <= extent.miny && 
+      rect.maxx >= extent.maxx && rect.maxy >= extent.maxy) {
+      /* no spatial filter used */
+      if(!layer->filter.string) {
+        snprintf(query_string_temp, sizeof(query_string_temp),  "SELECT %s from %s", columns_wanted, data_source );
+      } else {
+        snprintf(query_string_temp, sizeof(query_string_temp), "SELECT %s from %s WHERE (%s)", columns_wanted, data_source, layer->filter.string );
+      }
+  }
+  else {
+      if(!layer->filter.string) {
+        snprintf(query_string_temp, sizeof(query_string_temp),  "SELECT %s from %s WHERE %s.STIntersects(%s) = 1 ", columns_wanted, data_source, layerinfo->geom_column, box3d );
+      } else {
+        snprintf(query_string_temp, sizeof(query_string_temp), "SELECT %s from %s WHERE (%s) and %s.STIntersects(%s) = 1 ", columns_wanted, data_source, layer->filter.string, layerinfo->geom_column, box3d );
+      }
+  }
 
-    if(layer->debug) {
-        msDebug("query_string_temp:%s\n", query_string_temp);
-    }
+  msFree(data_source);
+  msFree(f_table_name);
+  msFree(columns_wanted);
 
-    if (executeSQL(layerinfo->conn, query_string_temp))
-    {
-        *query_string = msStrdup(query_string_temp);
+  if(layer->debug) {
+    msDebug("query_string_temp:%s\n", query_string_temp);
+  }
 
-        return MS_SUCCESS;
-    }
-    else
-    {
-        msSetError(MS_QUERYERR, "Error executing MSSQL2008 SQL statement: %s\n-%s\n", "msMSSQL2008LayerGetShape()", query_string_temp, layerinfo->conn->errorMessage);
+  if (executeSQL(layerinfo->conn, query_string_temp)) {
+    *query_string = msStrdup(query_string_temp);
 
-        return MS_FAILURE;
-    }
+    return MS_SUCCESS;
+  } else {
+    msSetError(MS_QUERYERR, "Error executing MSSQL2008 SQL statement: %s\n-%s\n", "msMSSQL2008LayerGetShape()", query_string_temp, layerinfo->conn->errorMessage);
+
+    return MS_FAILURE;
+  }
 }
 
 /* Execute SQL query for this layer */
 int msMSSQL2008LayerWhichShapes(layerObj *layer, rectObj rect, int isQuery)
 {
-    msMSSQL2008LayerInfo  *layerinfo = 0;
-    char    *query_str = 0;
-    int     set_up_result;
+  msMSSQL2008LayerInfo  *layerinfo = 0;
+  char    *query_str = 0;
+  int     set_up_result;
 
-    if(layer->debug) {
-        msDebug("msMSSQL2008LayerWhichShapes called\n");
-    }
+  if(layer->debug) {
+    msDebug("msMSSQL2008LayerWhichShapes called\n");
+  }
 
-    layerinfo = getMSSQL2008LayerInfo(layer);
+  layerinfo = getMSSQL2008LayerInfo(layer);
 
-    if(!layerinfo) {
-        /* layer not opened yet */
-        msSetError(MS_QUERYERR, "msMSSQL2008LayerWhichShapes called on unopened layer (layerinfo = NULL)", "msMSSQL2008LayerWhichShapes()");
+  if(!layerinfo) {
+    /* layer not opened yet */
+    msSetError(MS_QUERYERR, "msMSSQL2008LayerWhichShapes called on unopened layer (layerinfo = NULL)", "msMSSQL2008LayerWhichShapes()");
 
-        return MS_FAILURE;
-    }
+    return MS_FAILURE;
+  }
 
-    if(!layer->data) {
-        msSetError(MS_QUERYERR, "Missing DATA clause in MSSQL2008 Layer definition.  DATA statement must contain 'geometry_column from table_name' or 'geometry_column from (sub-query) as foo'.", "msMSSQL2008LayerWhichShapes()");
+  if(!layer->data) {
+    msSetError(MS_QUERYERR, "Missing DATA clause in MSSQL2008 Layer definition.  DATA statement must contain 'geometry_column from table_name' or 'geometry_column from (sub-query) as foo'.", "msMSSQL2008LayerWhichShapes()");
 
-        return MS_FAILURE;
-    }
+    return MS_FAILURE;
+  }
 
-	set_up_result = prepare_database(layer, rect, &query_str);
+  set_up_result = prepare_database(layer, rect, &query_str);
 
-    if(set_up_result != MS_SUCCESS) {
-        msFree(query_str);
+  if(set_up_result != MS_SUCCESS) {
+    msFree(query_str);
 
-        return set_up_result; /* relay error */
-    }
+    return set_up_result; /* relay error */
+  }
 
-    msFree(layerinfo->sql);
-    layerinfo->sql = query_str;
-    layerinfo->row_num = 0;
+  msFree(layerinfo->sql);
+  layerinfo->sql = query_str;
+  layerinfo->row_num = 0;
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 /* Close the MSSQL2008 record set and connection */
 int msMSSQL2008LayerClose(layerObj *layer)
 {
-    msMSSQL2008LayerInfo  *layerinfo;
-
-    layerinfo = getMSSQL2008LayerInfo(layer);
+  msMSSQL2008LayerInfo  *layerinfo;
 
-    if(layer->debug) 
-    {
-        char *data = "";
+  layerinfo = getMSSQL2008LayerInfo(layer);
 
-        if (layer->data)
-        {
-            data = layer->data;
-        }
+  if(layer->debug) {
+    char *data = "";
 
-        msDebug("msMSSQL2008LayerClose datastatement: %s\n", data);
+    if (layer->data) {
+      data = layer->data;
     }
 
-    if(layer->debug && !layerinfo) {
-        msDebug("msMSSQL2008LayerClose -- layerinfo is  NULL\n");
-    }
+    msDebug("msMSSQL2008LayerClose datastatement: %s\n", data);
+  }
 
-    if(layerinfo) {
-        msConnPoolRelease(layer, layerinfo->conn);
+  if(layer->debug && !layerinfo) {
+    msDebug("msMSSQL2008LayerClose -- layerinfo is  NULL\n");
+  }
 
-        layerinfo->conn = NULL;
+  if(layerinfo) {
+    msConnPoolRelease(layer, layerinfo->conn);
 
-		if(layerinfo->user_srid) {
-			msFree(layerinfo->user_srid);
-			layerinfo->user_srid = NULL;
-		}
+    layerinfo->conn = NULL;
 
-        if(layerinfo->urid_name) {
-            msFree(layerinfo->urid_name);
-            layerinfo->urid_name = NULL;
-        }
+    if(layerinfo->user_srid) {
+      msFree(layerinfo->user_srid);
+      layerinfo->user_srid = NULL;
+    }
 
-		if(layerinfo->index_name) {
-			msFree(layerinfo->index_name);
-			layerinfo->index_name = NULL;
-		}
+    if(layerinfo->urid_name) {
+      msFree(layerinfo->urid_name);
+      layerinfo->urid_name = NULL;
+    }
 
-        if(layerinfo->sql) {
-            msFree(layerinfo->sql);
-            layerinfo->sql = NULL;
-        }
+    if(layerinfo->index_name) {
+      msFree(layerinfo->index_name);
+      layerinfo->index_name = NULL;
+    }
 
-        if(layerinfo->geom_column) {
-            msFree(layerinfo->geom_column);
-            layerinfo->geom_column = NULL;
-        }
+    if(layerinfo->sql) {
+      msFree(layerinfo->sql);
+      layerinfo->sql = NULL;
+    }
 
-        if(layerinfo->geom_column_type) {
-            msFree(layerinfo->geom_column_type);
-            layerinfo->geom_column_type = NULL;
-        }
+    if(layerinfo->geom_column) {
+      msFree(layerinfo->geom_column);
+      layerinfo->geom_column = NULL;
+    }
 
-        if(layerinfo->geom_table) {
-            msFree(layerinfo->geom_table);
-            layerinfo->geom_table = NULL;
-        }
+    if(layerinfo->geom_column_type) {
+      msFree(layerinfo->geom_column_type);
+      layerinfo->geom_column_type = NULL;
+    }
 
-        setMSSQL2008LayerInfo(layer, NULL);
-        msFree(layerinfo);
+    if(layerinfo->geom_table) {
+      msFree(layerinfo->geom_table);
+      layerinfo->geom_table = NULL;
     }
 
-    return MS_SUCCESS;
+    setMSSQL2008LayerInfo(layer, NULL);
+    msFree(layerinfo);
+  }
+
+  return MS_SUCCESS;
 }
 
 /* ******************************************************* */
@@ -807,75 +1066,74 @@ int msMSSQL2008LayerClose(layerObj *layer)
 
 static int  force_to_points(char *wkb, shapeObj *shape)
 {
-    /* we're going to make a 'line' for each entity (point, line or ring) in the geom collection */
-
-    int     offset = 0;
-    int     pt_offset;
-    int     ngeoms;
-    int     t, u, v;
-    int     type, nrings, npoints;
-    lineObj line = {0, NULL};
-
-    shape->type = MS_SHAPE_NULL;  /* nothing in it */
-
-    memcpy(&ngeoms, &wkb[5], 4);
-    offset = 9;  /* were the first geometry is */
-    for(t=0; t < ngeoms; t++) {
-        memcpy(&type, &wkb[offset + 1], 4);  /* type of this geometry */
-
-        if(type == 1) {
-            /* Point */
-            shape->type = MS_SHAPE_POINT;
-            line.numpoints = 1;
-            line.point = (pointObj *) msSmallMalloc(sizeof(pointObj));
-
-            memcpy(&line.point[0].x, &wkb[offset + 5], 8);
-            memcpy(&line.point[0].y, &wkb[offset + 5 + 8], 8);
-            offset += 5 + 16;
-            msAddLine(shape, &line);
-            msFree(line.point);
-        } else if(type == 2) {
-            /* Linestring */
-            shape->type = MS_SHAPE_POINT;
-
-            memcpy(&line.numpoints, &wkb[offset+5], 4); /* num points */
-            line.point = (pointObj *) msSmallMalloc(sizeof(pointObj) * line.numpoints);
-            for(u = 0; u < line.numpoints; u++) {
-                memcpy( &line.point[u].x, &wkb[offset+9 + (16 * u)], 8);
-                memcpy( &line.point[u].y, &wkb[offset+9 + (16 * u)+8], 8);
-            }
-            offset += 9 + 16 * line.numpoints;  /* length of object */
-            msAddLine(shape, &line);
-            msFree(line.point);
-        } else if(type == 3) {
-            /* Polygon */
-            shape->type = MS_SHAPE_POINT;
-
-            memcpy(&nrings, &wkb[offset+5],4); /* num rings */
-            /* add a line for each polygon ring */
-            pt_offset = 0;
-            offset += 9; /* now points at 1st linear ring */
-            for(u = 0; u < nrings; u++) {
-                /* for each ring, make a line */
-                memcpy(&npoints, &wkb[offset], 4); /* num points */
-                line.numpoints = npoints;
-                line.point = (pointObj *) msSmallMalloc(sizeof(pointObj)* npoints); 
-                /* point struct */
-                for(v = 0; v < npoints; v++)
-                {
-                    memcpy(&line.point[v].x, &wkb[offset + 4 + (16 * v)], 8);
-                    memcpy(&line.point[v].y, &wkb[offset + 4 + (16 * v) + 8], 8);
-                }
-                /* make offset point to next linear ring */
-                msAddLine(shape, &line);
-                msFree(line.point);
-                offset += 4 + 16 *npoints;
-            }
-        } 
-    
+  /* we're going to make a 'line' for each entity (point, line or ring) in the geom collection */
+
+  int     offset = 0;
+  int     pt_offset;
+  int     ngeoms;
+  int     t, u, v;
+  int     type, nrings, npoints;
+  lineObj line = {0, NULL};
+
+  shape->type = MS_SHAPE_NULL;  /* nothing in it */
+
+  memcpy(&ngeoms, &wkb[5], 4);
+  offset = 9;  /* were the first geometry is */
+  for(t=0; t < ngeoms; t++) {
+    memcpy(&type, &wkb[offset + 1], 4);  /* type of this geometry */
+
+    if(type == 1) {
+      /* Point */
+      shape->type = MS_SHAPE_POINT;
+      line.numpoints = 1;
+      line.point = (pointObj *) msSmallMalloc(sizeof(pointObj));
+
+      memcpy(&line.point[0].x, &wkb[offset + 5], 8);
+      memcpy(&line.point[0].y, &wkb[offset + 5 + 8], 8);
+      offset += 5 + 16;
+      msAddLine(shape, &line);
+      msFree(line.point);
+    } else if(type == 2) {
+      /* Linestring */
+      shape->type = MS_SHAPE_POINT;
+
+      memcpy(&line.numpoints, &wkb[offset+5], 4); /* num points */
+      line.point = (pointObj *) msSmallMalloc(sizeof(pointObj) * line.numpoints);
+      for(u = 0; u < line.numpoints; u++) {
+        memcpy( &line.point[u].x, &wkb[offset+9 + (16 * u)], 8);
+        memcpy( &line.point[u].y, &wkb[offset+9 + (16 * u)+8], 8);
+      }
+      offset += 9 + 16 * line.numpoints;  /* length of object */
+      msAddLine(shape, &line);
+      msFree(line.point);
+    } else if(type == 3) {
+      /* Polygon */
+      shape->type = MS_SHAPE_POINT;
+
+      memcpy(&nrings, &wkb[offset+5],4); /* num rings */
+      /* add a line for each polygon ring */
+      pt_offset = 0;
+      offset += 9; /* now points at 1st linear ring */
+      for(u = 0; u < nrings; u++) {
+        /* for each ring, make a line */
+        memcpy(&npoints, &wkb[offset], 4); /* num points */
+        line.numpoints = npoints;
+        line.point = (pointObj *) msSmallMalloc(sizeof(pointObj)* npoints);
+        /* point struct */
+        for(v = 0; v < npoints; v++) {
+          memcpy(&line.point[v].x, &wkb[offset + 4 + (16 * v)], 8);
+          memcpy(&line.point[v].y, &wkb[offset + 4 + (16 * v) + 8], 8);
+        }
+        /* make offset point to next linear ring */
+        msAddLine(shape, &line);
+        msFree(line.point);
+        offset += 4 + 16 *npoints;
+      }
     }
 
-    return MS_SUCCESS;
+  }
+
+  return MS_SUCCESS;
 }
 
 /* convert the wkb into lines */
@@ -885,62 +1143,62 @@ static int  force_to_points(char *wkb, shapeObj *shape)
 
 static int  force_to_lines(char *wkb, shapeObj *shape)
 {
-    int     offset = 0;
-    int     pt_offset;
-    int     ngeoms;
-    int     t, u, v;
-    int     type, nrings, npoints;
-    lineObj line = {0, NULL};
-
-    shape->type = MS_SHAPE_NULL;  /* nothing in it */
-
-    memcpy(&ngeoms, &wkb[5], 4);
-    offset = 9;  /* were the first geometry is */
-    for(t=0; t < ngeoms; t++) {
-        memcpy(&type, &wkb[offset + 1], 4);  /* type of this geometry */
-
-        /* cannot do anything with a point */
-
-        if(type == 2) {
-            /* Linestring */
-            shape->type = MS_SHAPE_LINE;
-
-            memcpy(&line.numpoints, &wkb[offset + 5], 4);
-            line.point = (pointObj*) msSmallMalloc(sizeof(pointObj) * line.numpoints );
-            for(u=0; u < line.numpoints; u++) {
-                memcpy(&line.point[u].x, &wkb[offset + 9 + (16 * u)], 8);
-                memcpy(&line.point[u].y, &wkb[offset + 9 + (16 * u)+8], 8);
-            }
-            offset += 9 + 16 * line.numpoints;  /* length of object */
-            msAddLine(shape, &line);
-            msFree(line.point);
-        } else if(type == 3) {
-            /* polygon */
-            shape->type = MS_SHAPE_LINE;
-
-            memcpy(&nrings, &wkb[offset + 5], 4); /* num rings */
-            /* add a line for each polygon ring */
-            pt_offset = 0;
-            offset += 9; /* now points at 1st linear ring */
-            for(u = 0; u < nrings; u++) {
-                /* for each ring, make a line */
-                memcpy(&npoints, &wkb[offset], 4);
-                line.numpoints = npoints;
-                line.point = (pointObj*) msSmallMalloc(sizeof(pointObj) * npoints); 
-                /* point struct */
-                for(v = 0; v < npoints; v++) {
-                    memcpy(&line.point[v].x, &wkb[offset + 4 + (16 * v)], 8);
-                    memcpy(&line.point[v].y, &wkb[offset + 4 + (16 * v) + 8], 8);
-                }
-                /* make offset point to next linear ring */
-                msAddLine(shape, &line);
-                msFree(line.point);
-                offset += 4 + 16 * npoints;
-            }
+  int     offset = 0;
+  int     pt_offset;
+  int     ngeoms;
+  int     t, u, v;
+  int     type, nrings, npoints;
+  lineObj line = {0, NULL};
+
+  shape->type = MS_SHAPE_NULL;  /* nothing in it */
+
+  memcpy(&ngeoms, &wkb[5], 4);
+  offset = 9;  /* were the first geometry is */
+  for(t=0; t < ngeoms; t++) {
+    memcpy(&type, &wkb[offset + 1], 4);  /* type of this geometry */
+
+    /* cannot do anything with a point */
+
+    if(type == 2) {
+      /* Linestring */
+      shape->type = MS_SHAPE_LINE;
+
+      memcpy(&line.numpoints, &wkb[offset + 5], 4);
+      line.point = (pointObj*) msSmallMalloc(sizeof(pointObj) * line.numpoints );
+      for(u=0; u < line.numpoints; u++) {
+        memcpy(&line.point[u].x, &wkb[offset + 9 + (16 * u)], 8);
+        memcpy(&line.point[u].y, &wkb[offset + 9 + (16 * u)+8], 8);
+      }
+      offset += 9 + 16 * line.numpoints;  /* length of object */
+      msAddLine(shape, &line);
+      msFree(line.point);
+    } else if(type == 3) {
+      /* polygon */
+      shape->type = MS_SHAPE_LINE;
+
+      memcpy(&nrings, &wkb[offset + 5], 4); /* num rings */
+      /* add a line for each polygon ring */
+      pt_offset = 0;
+      offset += 9; /* now points at 1st linear ring */
+      for(u = 0; u < nrings; u++) {
+        /* for each ring, make a line */
+        memcpy(&npoints, &wkb[offset], 4);
+        line.numpoints = npoints;
+        line.point = (pointObj*) msSmallMalloc(sizeof(pointObj) * npoints);
+        /* point struct */
+        for(v = 0; v < npoints; v++) {
+          memcpy(&line.point[v].x, &wkb[offset + 4 + (16 * v)], 8);
+          memcpy(&line.point[v].y, &wkb[offset + 4 + (16 * v) + 8], 8);
         }
+        /* make offset point to next linear ring */
+        msAddLine(shape, &line);
+        msFree(line.point);
+        offset += 4 + 16 * npoints;
+      }
     }
+  }
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 /* point   -> reject */
@@ -948,46 +1206,46 @@ static int  force_to_lines(char *wkb, shapeObj *shape)
 /* polygon -> lines of linear rings */
 static int  force_to_polygons(char  *wkb, shapeObj *shape)
 {
-    int     offset = 0;
-    int     pt_offset;
-    int     ngeoms;
-    int     t, u, v;
-    int     type, nrings, npoints;
-    lineObj line = {0, NULL};
-
-    shape->type = MS_SHAPE_NULL;  /* nothing in it */
-
-    memcpy(&ngeoms, &wkb[5], 4);
-    offset = 9;  /* were the first geometry is */
-    for(t = 0; t < ngeoms; t++) {
-        memcpy(&type, &wkb[offset + 1], 4);  /* type of this geometry */
-
-        if(type == 3) {
-            /* polygon */
-            shape->type = MS_SHAPE_POLYGON;
-
-            memcpy(&nrings, &wkb[offset + 5], 4); /* num rings */
-            /* add a line for each polygon ring */
-            pt_offset = 0;
-            offset += 9; /* now points at 1st linear ring */
-            for(u=0; u < nrings; u++) {
-                /* for each ring, make a line */
-                memcpy(&npoints, &wkb[offset], 4); /* num points */
-                line.numpoints = npoints;
-                line.point = (pointObj*) msSmallMalloc(sizeof(pointObj) * npoints);
-                for(v=0; v < npoints; v++) {
-                    memcpy(&line.point[v].x, &wkb[offset + 4 + (16 * v)], 8);
-                    memcpy(&line.point[v].y, &wkb[offset + 4 + (16 * v) + 8], 8);
-                }
-                /* make offset point to next linear ring */
-                msAddLine(shape, &line);
-                msFree(line.point);
-                offset += 4 + 16 * npoints;
-            }
+  int     offset = 0;
+  int     pt_offset;
+  int     ngeoms;
+  int     t, u, v;
+  int     type, nrings, npoints;
+  lineObj line = {0, NULL};
+
+  shape->type = MS_SHAPE_NULL;  /* nothing in it */
+
+  memcpy(&ngeoms, &wkb[5], 4);
+  offset = 9;  /* were the first geometry is */
+  for(t = 0; t < ngeoms; t++) {
+    memcpy(&type, &wkb[offset + 1], 4);  /* type of this geometry */
+
+    if(type == 3) {
+      /* polygon */
+      shape->type = MS_SHAPE_POLYGON;
+
+      memcpy(&nrings, &wkb[offset + 5], 4); /* num rings */
+      /* add a line for each polygon ring */
+      pt_offset = 0;
+      offset += 9; /* now points at 1st linear ring */
+      for(u=0; u < nrings; u++) {
+        /* for each ring, make a line */
+        memcpy(&npoints, &wkb[offset], 4); /* num points */
+        line.numpoints = npoints;
+        line.point = (pointObj*) msSmallMalloc(sizeof(pointObj) * npoints);
+        for(v=0; v < npoints; v++) {
+          memcpy(&line.point[v].x, &wkb[offset + 4 + (16 * v)], 8);
+          memcpy(&line.point[v].y, &wkb[offset + 4 + (16 * v) + 8], 8);
         }
+        /* make offset point to next linear ring */
+        msAddLine(shape, &line);
+        msFree(line.point);
+        offset += 4 + 16 * npoints;
+      }
     }
+  }
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 /* if there is any polygon in wkb, return force_polygon */
@@ -996,38 +1254,38 @@ static int  force_to_polygons(char  *wkb, shapeObj *shape)
 
 static int  dont_force(char *wkb, shapeObj *shape)
 {
-    int     offset =0;
-    int     ngeoms;
-    int     type, t;
-    int     best_type;
-
-    best_type = MS_SHAPE_NULL;  /* nothing in it */
-
-    memcpy(&ngeoms, &wkb[5], 4);
-    offset = 9;  /* were the first geometry is */
-    for(t = 0; t < ngeoms; t++) {
-        memcpy(&type, &wkb[offset + 1], 4);  /* type of this geometry */
-
-        if(type == 3) {
-            best_type = MS_SHAPE_POLYGON;
-        } else if(type ==2 && best_type != MS_SHAPE_POLYGON) {
-            best_type = MS_SHAPE_LINE;
-        } else if(type == 1 && best_type == MS_SHAPE_NULL) {
-            best_type = MS_SHAPE_POINT;
-        }
-    }
-
-    if(best_type == MS_SHAPE_POINT) {
-        return force_to_points(wkb, shape);
-    }
-    if(best_type == MS_SHAPE_LINE) {
-        return force_to_lines(wkb, shape);
-    }
-    if(best_type == MS_SHAPE_POLYGON) {
-        return force_to_polygons(wkb, shape);
-    }
-
-    return MS_FAILURE; /* unknown type */
+  int     offset =0;
+  int     ngeoms;
+  int     type, t;
+  int     best_type;
+
+  best_type = MS_SHAPE_NULL;  /* nothing in it */
+
+  memcpy(&ngeoms, &wkb[5], 4);
+  offset = 9;  /* were the first geometry is */
+  for(t = 0; t < ngeoms; t++) {
+    memcpy(&type, &wkb[offset + 1], 4);  /* type of this geometry */
+
+    if(type == 3) {
+      best_type = MS_SHAPE_POLYGON;
+    } else if(type ==2 && best_type != MS_SHAPE_POLYGON) {
+      best_type = MS_SHAPE_LINE;
+    } else if(type == 1 && best_type == MS_SHAPE_NULL) {
+      best_type = MS_SHAPE_POINT;
+    }
+  }
+
+  if(best_type == MS_SHAPE_POINT) {
+    return force_to_points(wkb, shape);
+  }
+  if(best_type == MS_SHAPE_LINE) {
+    return force_to_lines(wkb, shape);
+  }
+  if(best_type == MS_SHAPE_POLYGON) {
+    return force_to_polygons(wkb, shape);
+  }
+
+  return MS_FAILURE; /* unknown type */
 }
 
 /* ******************************************************* */
@@ -1040,98 +1298,86 @@ static int  dont_force(char *wkb, shapeObj *shape)
 /* polys->   treat ring like line and pull out the consituent points */
 static int  force_to_shapeType(char *wkb, shapeObj *shape, int msShapeType)
 {
-    int     offset = 0;
-    int     ngeoms = 1;
-    int     u, v;
-    int     type, nrings, npoints;
-    lineObj line = {0, NULL};
+  int     offset = 0;
+  int     ngeoms = 1;
+  int     u, v;
+  int     type, nrings, npoints;
+  lineObj line = {0, NULL};
 
-    shape->type = MS_SHAPE_NULL;  /* nothing in it */
+  shape->type = MS_SHAPE_NULL;  /* nothing in it */
 
-    do
-    {
-        ngeoms--;
+  do {
+    ngeoms--;
 
-        memcpy(&type, &wkb[offset + 1], 4);  /* type of this geometry */
+    memcpy(&type, &wkb[offset + 1], 4);  /* type of this geometry */
 
-        if (type == 1)
-        {
-            /* Point */
-            shape->type = msShapeType;
-            line.numpoints = 1;
-            line.point = (pointObj *) msSmallMalloc(sizeof(pointObj));
+    if (type == 1) {
+      /* Point */
+      shape->type = msShapeType;
+      line.numpoints = 1;
+      line.point = (pointObj *) msSmallMalloc(sizeof(pointObj));
 
-            memcpy(&line.point[0].x, &wkb[offset + 5], 8);
-            memcpy(&line.point[0].y, &wkb[offset + 5 + 8], 8);
-            offset += 5 + 16;
+      memcpy(&line.point[0].x, &wkb[offset + 5], 8);
+      memcpy(&line.point[0].y, &wkb[offset + 5 + 8], 8);
+      offset += 5 + 16;
 
-            if (msShapeType == MS_SHAPE_POINT)
-            {
-                msAddLine(shape, &line);
-            }
+      if (msShapeType == MS_SHAPE_POINT) {
+        msAddLine(shape, &line);
+      }
 
-            msFree(line.point);
-        } 
-        else if(type == 2) 
-        {
-            /* Linestring */
-            shape->type = msShapeType;
-
-            memcpy(&line.numpoints, &wkb[offset+5], 4); /* num points */
-            line.point = (pointObj *) msSmallMalloc(sizeof(pointObj) * line.numpoints);
-            for(u = 0; u < line.numpoints; u++) {
-                memcpy( &line.point[u].x, &wkb[offset+9 + (16 * u)], 8);
-                memcpy( &line.point[u].y, &wkb[offset+9 + (16 * u)+8], 8);
-            }
-            offset += 9 + 16 * line.numpoints;  /* length of object */
+      msFree(line.point);
+    } else if(type == 2) {
+      /* Linestring */
+      shape->type = msShapeType;
 
-            if ((msShapeType == MS_SHAPE_POINT) || (msShapeType == MS_SHAPE_LINE))
-            {
-                msAddLine(shape, &line);
-            }
+      memcpy(&line.numpoints, &wkb[offset+5], 4); /* num points */
+      line.point = (pointObj *) msSmallMalloc(sizeof(pointObj) * line.numpoints);
+      for(u = 0; u < line.numpoints; u++) {
+        memcpy( &line.point[u].x, &wkb[offset+9 + (16 * u)], 8);
+        memcpy( &line.point[u].y, &wkb[offset+9 + (16 * u)+8], 8);
+      }
+      offset += 9 + 16 * line.numpoints;  /* length of object */
 
-            msFree(line.point);
-        } 
-        else if(type == 3) 
-        {
-            /* Polygon */
-            shape->type = msShapeType;
-
-            memcpy(&nrings, &wkb[offset+5],4); /* num rings */
-            /* add a line for each polygon ring */
-            offset += 9; /* now points at 1st linear ring */
-            for(u = 0; u < nrings; u++) {
-                /* for each ring, make a line */
-                memcpy(&npoints, &wkb[offset], 4); /* num points */
-                line.numpoints = npoints;
-                line.point = (pointObj *) msSmallMalloc(sizeof(pointObj)* npoints); 
-                /* point struct */
-                for(v = 0; v < npoints; v++)
-                {
-                    memcpy(&line.point[v].x, &wkb[offset + 4 + (16 * v)], 8);
-                    memcpy(&line.point[v].y, &wkb[offset + 4 + (16 * v) + 8], 8);
-                }
-                /* make offset point to next linear ring */
-                msAddLine(shape, &line);
-                msFree(line.point);
-                offset += 4 + 16 *npoints;
-            }
-        } 
-        else if(type >= 4 && type <= 7) 
-        {
-            int cnt = 0;
+      if ((msShapeType == MS_SHAPE_POINT) || (msShapeType == MS_SHAPE_LINE)) {
+        msAddLine(shape, &line);
+      }
 
-            offset += 5;
+      msFree(line.point);
+    } else if(type == 3) {
+      /* Polygon */
+      shape->type = msShapeType;
+
+      memcpy(&nrings, &wkb[offset+5],4); /* num rings */
+      /* add a line for each polygon ring */
+      offset += 9; /* now points at 1st linear ring */
+      for(u = 0; u < nrings; u++) {
+        /* for each ring, make a line */
+        memcpy(&npoints, &wkb[offset], 4); /* num points */
+        line.numpoints = npoints;
+        line.point = (pointObj *) msSmallMalloc(sizeof(pointObj)* npoints);
+        /* point struct */
+        for(v = 0; v < npoints; v++) {
+          memcpy(&line.point[v].x, &wkb[offset + 4 + (16 * v)], 8);
+          memcpy(&line.point[v].y, &wkb[offset + 4 + (16 * v) + 8], 8);
+        }
+        /* make offset point to next linear ring */
+        msAddLine(shape, &line);
+        msFree(line.point);
+        offset += 4 + 16 *npoints;
+      }
+    } else if(type >= 4 && type <= 7) {
+      int cnt = 0;
 
-            memcpy(&cnt, &wkb[offset], 4);
-            offset += 4;  /* were the first geometry is */
+      offset += 5;
 
-            ngeoms += cnt;
-        }
+      memcpy(&cnt, &wkb[offset], 4);
+      offset += 4;  /* were the first geometry is */
+
+      ngeoms += cnt;
     }
-    while (ngeoms > 0);
+  } while (ngeoms > 0);
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 ///* if there is any polygon in wkb, return force_polygon */
@@ -1166,16 +1412,16 @@ static int  force_to_shapeType(char *wkb, shapeObj *shape, int msShapeType)
 //        {
 //            /* Point */
 //            offset += 5 + 16;
-//        } 
-//        else if(type == 2) 
+//        }
+//        else if(type == 2)
 //        {
 //            int numPoints;
 //
 //            memcpy(&numPoints, &wkb[offset+5], 4); /* num points */
 //            /* Linestring */
 //            offset += 9 + 16 * numPoints;  /* length of object */
-//        } 
-//        else if(type == 3) 
+//        }
+//        else if(type == 3)
 //        {
 //            /* Polygon */
 //            memcpy(&nrings, &wkb[offset+5],4); /* num rings */
@@ -1185,8 +1431,8 @@ static int  force_to_shapeType(char *wkb, shapeObj *shape, int msShapeType)
 //                memcpy(&npoints, &wkb[offset], 4); /* num points */
 //                offset += 4 + 16 *npoints;
 //            }
-//        } 
-//        else if(type >= 4 && type <= 7) 
+//        }
+//        else if(type >= 4 && type <= 7)
 //        {
 //            int cnt = 0;
 //
@@ -1206,237 +1452,252 @@ static int  force_to_shapeType(char *wkb, shapeObj *shape, int msShapeType)
 /* find the bounds of the shape */
 static void find_bounds(shapeObj *shape)
 {
-    int     t, u;
-    int     first_one = 1;
-
-    for(t = 0; t < shape->numlines; t++) {
-        for(u = 0; u < shape->line[t].numpoints; u++) {
-            if(first_one) {
-                shape->bounds.minx = shape->line[t].point[u].x;
-                shape->bounds.maxx = shape->line[t].point[u].x;
-
-                shape->bounds.miny = shape->line[t].point[u].y;
-                shape->bounds.maxy = shape->line[t].point[u].y;
-                first_one = 0;
-            } else {
-                if(shape->line[t].point[u].x < shape->bounds.minx) {
-                    shape->bounds.minx = shape->line[t].point[u].x;
-                }
-                if(shape->line[t].point[u].x > shape->bounds.maxx) {
-                    shape->bounds.maxx = shape->line[t].point[u].x;
-                }
-
-                if(shape->line[t].point[u].y < shape->bounds.miny) {
-                    shape->bounds.miny = shape->line[t].point[u].y;
-                }
-                if(shape->line[t].point[u].y > shape->bounds.maxy) {
-                    shape->bounds.maxy = shape->line[t].point[u].y;
-                }
-            }
+  int     t, u;
+  int     first_one = 1;
+
+  for(t = 0; t < shape->numlines; t++) {
+    for(u = 0; u < shape->line[t].numpoints; u++) {
+      if(first_one) {
+        shape->bounds.minx = shape->line[t].point[u].x;
+        shape->bounds.maxx = shape->line[t].point[u].x;
+
+        shape->bounds.miny = shape->line[t].point[u].y;
+        shape->bounds.maxy = shape->line[t].point[u].y;
+        first_one = 0;
+      } else {
+        if(shape->line[t].point[u].x < shape->bounds.minx) {
+          shape->bounds.minx = shape->line[t].point[u].x;
         }
+        if(shape->line[t].point[u].x > shape->bounds.maxx) {
+          shape->bounds.maxx = shape->line[t].point[u].x;
+        }
+
+        if(shape->line[t].point[u].y < shape->bounds.miny) {
+          shape->bounds.miny = shape->line[t].point[u].y;
+        }
+        if(shape->line[t].point[u].y > shape->bounds.maxy) {
+          shape->bounds.maxy = shape->line[t].point[u].y;
+        }
+      }
     }
+  }
 }
 
 /* Used by NextShape() to access a shape in the query set */
 int msMSSQL2008LayerGetShapeRandom(layerObj *layer, shapeObj *shape, long *record)
 {
-    msMSSQL2008LayerInfo  *layerinfo;
-    int                 result;
-	SQLINTEGER needLen = 0;
-    SQLINTEGER retLen = 0;
-	char dummyBuffer[1];
-	char *wkbBuffer;
-	char *valueBuffer;
-	char oidBuffer[ 16 ];		/* assuming the OID will always be a long this should be enough */
-    long record_oid;
-	int t;
-
-    /* for coercing single types into geometry collections */
-    char *wkbTemp;
-    int geomType;
-
-    layerinfo = getMSSQL2008LayerInfo(layer);
-
-    if(!layerinfo)
-	{
-        msSetError(MS_QUERYERR, "GetShape called with layerinfo = NULL", "msMSSQL2008LayerGetShape()");
-        return MS_FAILURE;
-    }
+  msMSSQL2008LayerInfo  *layerinfo;
+  int                 result;
+  SQLINTEGER needLen = 0;
+  SQLINTEGER retLen = 0;
+  char dummyBuffer[1];
+  char *wkbBuffer;
+  char *valueBuffer;
+  char oidBuffer[ 16 ];   /* assuming the OID will always be a long this should be enough */
+  long record_oid;
+  int t;
+
+  /* for coercing single types into geometry collections */
+  char *wkbTemp;
+  int geomType;
+
+  layerinfo = getMSSQL2008LayerInfo(layer);
+
+  if(!layerinfo) {
+    msSetError(MS_QUERYERR, "GetShape called with layerinfo = NULL", "msMSSQL2008LayerGetShape()");
+    return MS_FAILURE;
+  }
 
-    if(!layerinfo->conn)
-	{
-        msSetError(MS_QUERYERR, "NextShape called on MSSQL2008 layer with no connection to DB.", "msMSSQL2008LayerGetShape()");
-        return MS_FAILURE;
+  if(!layerinfo->conn) {
+    msSetError(MS_QUERYERR, "NextShape called on MSSQL2008 layer with no connection to DB.", "msMSSQL2008LayerGetShape()");
+    return MS_FAILURE;
+  }
+
+  shape->type = MS_SHAPE_NULL;
+
+  while(shape->type == MS_SHAPE_NULL) {
+    /* SQLRETURN rc = SQLFetchScroll(layerinfo->conn->hstmt, SQL_FETCH_ABSOLUTE, (SQLINTEGER) (*record) + 1); */
+
+    /* We only do forward fetches. the parameter 'record' is ignored, but is incremented */
+    SQLRETURN rc = SQLFetch(layerinfo->conn->hstmt);
+
+    /* Any error assume out of recordset bounds */
+    if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) {
+      handleSQLError(layer);
+      return MS_DONE;
     }
 
-    shape->type = MS_SHAPE_NULL;
+    /* retreive an item */
 
-    while(shape->type == MS_SHAPE_NULL) 
     {
-        /* SQLRETURN rc = SQLFetchScroll(layerinfo->conn->hstmt, SQL_FETCH_ABSOLUTE, (SQLINTEGER) (*record) + 1); */
-
-        /* We only do forward fetches. the parameter 'record' is ignored, but is incremented */
-        SQLRETURN rc = SQLFetch(layerinfo->conn->hstmt);
+      /* have to retrieve shape attributes */
+      shape->values = (char **) msSmallMalloc(sizeof(char *) * layer->numitems);
+      shape->numvalues = layer->numitems;
+
+      for(t=0; t < layer->numitems; t++) {
+        /* figure out how big the buffer needs to be */
+        rc = SQLGetData(layerinfo->conn->hstmt, (SQLUSMALLINT)(t + 1), SQL_C_BINARY, dummyBuffer, 0, &needLen);
+        if (rc == SQL_ERROR)
+          handleSQLError(layer);
+
+        if (needLen > 0) {
+          /* allocate the buffer - this will be a null-terminated string so alloc for the null too */
+          valueBuffer = (char*) msSmallMalloc( needLen + 1 );
+          if ( valueBuffer == NULL ) {
+            msSetError( MS_QUERYERR, "Could not allocate value buffer.", "msMSSQL2008LayerGetShapeRandom()" );
+            return MS_FAILURE;
+          }
 
-        /* Any error assume out of recordset bounds */
-        if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO)
-        {
+          /* Now grab the data */
+          rc = SQLGetData(layerinfo->conn->hstmt, (SQLUSMALLINT)(t + 1), SQL_C_BINARY, valueBuffer, needLen, &retLen);
+          if (rc == SQL_ERROR || rc == SQL_SUCCESS_WITH_INFO)
             handleSQLError(layer);
-            return MS_DONE;
-        }
 
-        /* retreive an item */
-
-        {
-            /* have to retrieve shape attributes */
-            shape->values = (char **) msSmallMalloc(sizeof(char *) * layer->numitems);
-            shape->numvalues = layer->numitems;
-
-            for(t=0; t < layer->numitems; t++)
-			{
-				/* figure out how big the buffer needs to be */
-                rc = SQLGetData(layerinfo->conn->hstmt, (SQLUSMALLINT)(t + 1), SQL_C_BINARY, dummyBuffer, 0, &needLen);
-                if (rc == SQL_ERROR)
-                    handleSQLError(layer);
-
-                if (needLen > 0)
-                {
-				    /* allocate the buffer - this will be a null-terminated string so alloc for the null too */
-				    valueBuffer = (char*) msSmallMalloc( needLen + 1 );
-				    if ( valueBuffer == NULL )
-				    {
-					    msSetError( MS_QUERYERR, "Could not allocate value buffer.", "msMSSQL2008LayerGetShapeRandom()" );
-					    return MS_FAILURE;
-				    }
-
-				    /* Now grab the data */
-                    rc = SQLGetData(layerinfo->conn->hstmt, (SQLUSMALLINT)(t + 1), SQL_C_BINARY, valueBuffer, needLen, &retLen);
-                    if (rc == SQL_ERROR || rc == SQL_SUCCESS_WITH_INFO)
-                        handleSQLError(layer);
-
-				    /* Terminate the buffer */
-                    valueBuffer[retLen] = 0; /* null terminate it */
-
-				    /* Pop the value into the shape's value array */
-                    shape->values[t] = valueBuffer;
-                }
-                else
-                    /* Copy empty sting for NULL values */
-                    shape->values[t] = msStrdup("");
-            }
+          /* Terminate the buffer */
+          valueBuffer[retLen] = 0; /* null terminate it */
 
-            /* Get shape geometry */
-            {
-				/* Set up to request the size of the buffer needed */
-                rc = SQLGetData(layerinfo->conn->hstmt, (SQLUSMALLINT)(layer->numitems + 1), SQL_C_BINARY, dummyBuffer, 0, &needLen);
-                if (rc == SQL_ERROR)
-                    handleSQLError(layer);
-
-                /* allow space for coercion to geometry collection if needed*/
-                wkbTemp = (char*)msSmallMalloc(needLen+9);  
-
-                /* write data above space allocated for geometry collection coercion */
-                wkbBuffer = wkbTemp + 9; 
-
-				if ( wkbBuffer == NULL )
-				{
-					msSetError( MS_QUERYERR, "Could not allocate value buffer.", "msMSSQL2008LayerGetShapeRandom()" );
-					return MS_FAILURE;
-				}
-
-				/* Grab the WKB */
-                rc = SQLGetData(layerinfo->conn->hstmt, (SQLUSMALLINT)(layer->numitems + 1), SQL_C_BINARY, wkbBuffer, needLen, &retLen);
-                if (rc == SQL_ERROR || rc == SQL_SUCCESS_WITH_INFO)
-                    handleSQLError(layer);
-
-                memcpy(&geomType, wkbBuffer + 1, 4);
-
-                /* is this a single type? */
-                if (geomType < 4)
-                {
-                    /* copy byte order marker (although we don't check it) */
-                    wkbTemp[0] = wkbBuffer[0];
-                    wkbBuffer = wkbTemp;
-
-                    /* indicate type is geometry collection (although geomType + 3 would also work) */
-                    wkbBuffer[1] = (char)7;
-                    wkbBuffer[2] = (char)0;
-                    wkbBuffer[3] = (char)0;
-                    wkbBuffer[4] = (char)0;
-
-                    /* indicate 1 shape */
-                    wkbBuffer[5] = (char)1;
-                    wkbBuffer[6] = (char)0;
-                    wkbBuffer[7] = (char)0;
-                    wkbBuffer[8] = (char)0;
-                }
-
-                switch(layer->type) 
-                {
-                    case MS_LAYER_POINT:
-						result = force_to_points(wkbBuffer, shape);
-                        break;
-
-                    case MS_LAYER_LINE:
-						result = force_to_lines(wkbBuffer, shape);
-                        break;
-
-                    case MS_LAYER_POLYGON:
-						result = force_to_polygons(wkbBuffer, shape);
-                        break;
-
-                    case MS_LAYER_ANNOTATION:
-                    case MS_LAYER_QUERY:
-                    case MS_LAYER_CHART:
-                        result = dont_force(wkbBuffer, shape);
-                        break;
-
-                    case MS_LAYER_RASTER:
-                        msDebug( "Ignoring MS_LAYER_RASTER in mapMSSQL2008.c\n" );
-                        break;
-
-                    case MS_LAYER_CIRCLE:
-                        msDebug( "Ignoring MS_LAYER_CIRCLE in mapMSSQL2008.c\n" );
-                        break;
-
-                    default:
-                       msDebug( "Unsupported layer type in msMSSQL2008LayerNextShape()!" );
-                       break;
-                }
-
-                //free(wkbBuffer);
-                msFree(wkbTemp);
-            }
+          /* Pop the value into the shape's value array */
+          shape->values[t] = valueBuffer;
+        } else
+          /* Copy empty sting for NULL values */
+          shape->values[t] = msStrdup("");
+      }
 
-            /* Next get unique id for row - since the OID shouldn't be larger than a long we'll assume billions as a limit */
-            rc = SQLGetData(layerinfo->conn->hstmt, (SQLUSMALLINT)(layer->numitems + 2), SQL_C_BINARY, oidBuffer, sizeof(oidBuffer) - 1, &retLen);
-            if (rc == SQL_ERROR || rc == SQL_SUCCESS_WITH_INFO)
-                    handleSQLError(layer);
+      /* Get shape geometry */
+      {
+        /* Set up to request the size of the buffer needed */
+        rc = SQLGetData(layerinfo->conn->hstmt, (SQLUSMALLINT)(layer->numitems + 1), SQL_C_BINARY, dummyBuffer, 0, &needLen);
+        if (rc == SQL_ERROR)
+          handleSQLError(layer);
 
-			oidBuffer[retLen] = 0;
-            record_oid = strtol(oidBuffer, NULL, 10);
+        /* allow space for coercion to geometry collection if needed*/
+        wkbTemp = (char*)msSmallMalloc(needLen+9);
 
-            shape->index = record_oid;
-            shape->resultindex = (*record);
+        /* write data above space allocated for geometry collection coercion */
+        wkbBuffer = wkbTemp + 9;
 
-            find_bounds(shape);
-            (*record)++;        /* move to next shape */
+        if ( wkbBuffer == NULL ) {
+          msSetError( MS_QUERYERR, "Could not allocate value buffer.", "msMSSQL2008LayerGetShapeRandom()" );
+          return MS_FAILURE;
+        }
 
-            if(shape->type != MS_SHAPE_NULL) 
-            {
-                return MS_SUCCESS;
-            }
-            else
-            {
-                msDebug("msMSSQL2008LayerGetShapeRandom bad shape: %d\n", *record);
+        /* Grab the WKB */
+        rc = SQLGetData(layerinfo->conn->hstmt, (SQLUSMALLINT)(layer->numitems + 1), SQL_C_BINARY, wkbBuffer, needLen, &retLen);
+        if (rc == SQL_ERROR || rc == SQL_SUCCESS_WITH_INFO)
+          handleSQLError(layer);
+
+        if (layerinfo->geometry_format == MSSQLGEOMETRY_NATIVE) {
+          layerinfo->gpi.pszData = (unsigned char*)wkbBuffer;
+          layerinfo->gpi.nLen = retLen;
+
+          if (!ParseSqlGeometry(layerinfo, shape)) {
+            switch(layer->type) {
+              case MS_LAYER_POINT:
+                shape->type = MS_SHAPE_POINT;
+                break;
+
+              case MS_LAYER_LINE:
+                shape->type = MS_SHAPE_LINE;
+                break;
+
+              case MS_LAYER_POLYGON:
+                shape->type = MS_SHAPE_POLYGON;
+                break;
             }
-            /* if (layer->type == MS_LAYER_POINT) {return MS_DONE;} */
+          }
+        } else {
+          memcpy(&geomType, wkbBuffer + 1, 4);
+
+          /* is this a single type? */
+          if (geomType < 4) {
+            /* copy byte order marker (although we don't check it) */
+            wkbTemp[0] = wkbBuffer[0];
+            wkbBuffer = wkbTemp;
+
+            /* indicate type is geometry collection (although geomType + 3 would also work) */
+            wkbBuffer[1] = (char)7;
+            wkbBuffer[2] = (char)0;
+            wkbBuffer[3] = (char)0;
+            wkbBuffer[4] = (char)0;
+
+            /* indicate 1 shape */
+            wkbBuffer[5] = (char)1;
+            wkbBuffer[6] = (char)0;
+            wkbBuffer[7] = (char)0;
+            wkbBuffer[8] = (char)0;
+          }
+
+          switch(layer->type) {
+            case MS_LAYER_POINT:
+              result = force_to_points(wkbBuffer, shape);
+              break;
+
+            case MS_LAYER_LINE:
+              result = force_to_lines(wkbBuffer, shape);
+              break;
+
+            case MS_LAYER_POLYGON:
+              result = force_to_polygons(wkbBuffer, shape);
+              break;
+
+            case MS_LAYER_ANNOTATION:
+            case MS_LAYER_QUERY:
+            case MS_LAYER_CHART:
+              result = dont_force(wkbBuffer, shape);
+              break;
+
+            case MS_LAYER_RASTER:
+              msDebug( "Ignoring MS_LAYER_RASTER in mapMSSQL2008.c\n" );
+              break;
+
+            case MS_LAYER_CIRCLE:
+              msDebug( "Ignoring MS_LAYER_CIRCLE in mapMSSQL2008.c\n" );
+              break;
+
+            default:
+              msDebug( "Unsupported layer type in msMSSQL2008LayerNextShape()!" );
+              break;
+          }
+          find_bounds(shape);
         }
+
+        //free(wkbBuffer);
+        msFree(wkbTemp);
+      }
+
+      /* Next get unique id for row - since the OID shouldn't be larger than a long we'll assume billions as a limit */
+      rc = SQLGetData(layerinfo->conn->hstmt, (SQLUSMALLINT)(layer->numitems + 2), SQL_C_BINARY, oidBuffer, sizeof(oidBuffer) - 1, &retLen);
+      if (rc == SQL_ERROR || rc == SQL_SUCCESS_WITH_INFO)
+        handleSQLError(layer);
+
+      if (retLen < sizeof(oidBuffer))
+	  {
+		oidBuffer[retLen] = 0;
+		record_oid = strtol(oidBuffer, NULL, 10);
+		shape->index = record_oid;
+	  }
+	  else
+	  {
+		/* non integer fid column, use single pass */
+		shape->index = -1;
+	  }
+
+      shape->resultindex = (*record);
+
+      (*record)++;        /* move to next shape */
+
+      if(shape->type != MS_SHAPE_NULL) {
+        return MS_SUCCESS;
+      } else {
+        msDebug("msMSSQL2008LayerGetShapeRandom bad shape: %d\n", *record);
+      }
+      /* if (layer->type == MS_LAYER_POINT) {return MS_DONE;} */
     }
+  }
 
-    msFreeShape(shape);
+  msFreeShape(shape);
 
-    return MS_FAILURE;
+  return MS_FAILURE;
 }
 
 /* find the next shape with the appropriate shape type (convert it if necessary) */
@@ -1444,307 +1705,291 @@ int msMSSQL2008LayerGetShapeRandom(layerObj *layer, shapeObj *shape, long *recor
 /* MS_DONE => no more data */
 int msMSSQL2008LayerNextShape(layerObj *layer, shapeObj *shape)
 {
-    int     result;
+  int     result;
 
-    msMSSQL2008LayerInfo  *layerinfo;
+  msMSSQL2008LayerInfo  *layerinfo;
 
-    layerinfo = getMSSQL2008LayerInfo(layer);
+  layerinfo = getMSSQL2008LayerInfo(layer);
 
-    if(!layerinfo)
-	{
-        msSetError(MS_QUERYERR, "NextShape called with layerinfo = NULL", "msMSSQL2008LayerNextShape()");
-        return MS_FAILURE;
-    }
+  if(!layerinfo) {
+    msSetError(MS_QUERYERR, "NextShape called with layerinfo = NULL", "msMSSQL2008LayerNextShape()");
+    return MS_FAILURE;
+  }
 
-    result = msMSSQL2008LayerGetShapeRandom(layer, shape, &(layerinfo->row_num));
-    /* getshaperandom will increment the row_num */
-    /* layerinfo->row_num   ++; */
+  result = msMSSQL2008LayerGetShapeRandom(layer, shape, &(layerinfo->row_num));
+  /* getshaperandom will increment the row_num */
+  /* layerinfo->row_num   ++; */
 
-    return result;
+  return result;
 }
 
 /* Execute a query on the DB based on the query result. */
 int msMSSQL2008LayerGetShape(layerObj *layer, shapeObj *shape, resultObj *record)
 {
-    char    *query_str;
-    char    *columns_wanted = 0;
-    
-    msMSSQL2008LayerInfo  *layerinfo;
-    int                 t;
-    char buffer[32000] = "";
-    long shapeindex = record->shapeindex;
-    long resultindex = record->resultindex;
+  char    *query_str;
+  char    *columns_wanted = 0;
 
-    if(layer->debug) {
-        msDebug("msMSSQL2008LayerGetShape called for shapeindex = %i\n", shapeindex);
-    }
+  msMSSQL2008LayerInfo  *layerinfo;
+  int                 t;
+  char buffer[32000] = "";
+  long shapeindex = record->shapeindex;
+  long resultindex = record->resultindex;
 
-    layerinfo = getMSSQL2008LayerInfo(layer);
+  if(layer->debug) {
+    msDebug("msMSSQL2008LayerGetShape called for shapeindex = %i\n", shapeindex);
+  }
 
-    if(!layerinfo) {
-        /* Layer not open */
-        msSetError(MS_QUERYERR, "msMSSQL2008LayerGetShape called on unopened layer (layerinfo = NULL)", "msMSSQL2008LayerGetShape()");
+  layerinfo = getMSSQL2008LayerInfo(layer);
 
-        return MS_FAILURE;
-    }
+  if(!layerinfo) {
+    /* Layer not open */
+    msSetError(MS_QUERYERR, "msMSSQL2008LayerGetShape called on unopened layer (layerinfo = NULL)", "msMSSQL2008LayerGetShape()");
 
-    if (resultindex >= 0 && layerinfo->sql)
-    {
-        /* trying to provide the result from the current resultset (single-pass query) */
-        if( resultindex < layerinfo->row_num)
-        {
-            /* re-issue the query */
-            if (!executeSQL(layerinfo->conn, layerinfo->sql))
-            {
-                msSetError(MS_QUERYERR, "Error executing MSSQL2008 SQL statement: %s\n-%s\n", "msMSSQL2008LayerGetShape()", layerinfo->sql, layerinfo->conn->errorMessage);
-
-                return MS_FAILURE;
-            }
-            layerinfo->row_num = 0;
-        }
-        while( layerinfo->row_num < resultindex )
-        {
-            /* move forward until we reach the desired index */
-            if (msMSSQL2008LayerGetShapeRandom(layer, shape, &(layerinfo->row_num)) != MS_SUCCESS)
-                return MS_FAILURE;
-        }
+    return MS_FAILURE;
+  }
+
+  if (resultindex >= 0 && layerinfo->sql) {
+    /* trying to provide the result from the current resultset (single-pass query) */
+    if( resultindex < layerinfo->row_num) {
+      /* re-issue the query */
+      if (!executeSQL(layerinfo->conn, layerinfo->sql)) {
+        msSetError(MS_QUERYERR, "Error executing MSSQL2008 SQL statement: %s\n-%s\n", "msMSSQL2008LayerGetShape()", layerinfo->sql, layerinfo->conn->errorMessage);
 
-        return msMSSQL2008LayerGetShapeRandom(layer, shape, &(layerinfo->row_num));
+        return MS_FAILURE;
+      }
+      layerinfo->row_num = 0;
+    }
+    while( layerinfo->row_num < resultindex ) {
+      /* move forward until we reach the desired index */
+      if (msMSSQL2008LayerGetShapeRandom(layer, shape, &(layerinfo->row_num)) != MS_SUCCESS)
+        return MS_FAILURE;
     }
 
-    /* non single-pass case, fetch the record from the database */
+    return msMSSQL2008LayerGetShapeRandom(layer, shape, &(layerinfo->row_num));
+  }
 
-    if(layer->numitems == 0) 
-    {
-        snprintf(buffer, sizeof(buffer), "%s.STAsBinary(), convert(varchar(36), %s)", layerinfo->geom_column, layerinfo->urid_name);
-        columns_wanted = msStrdup(buffer);
-    } 
-    else 
-    {
-        for(t = 0; t < layer->numitems; t++) {
-            snprintf(buffer + strlen(buffer), sizeof(buffer) - strlen(buffer), "convert(varchar(max), %s),", layer->items[t]);
-        }
-
-        snprintf(buffer + strlen(buffer), sizeof(buffer) - strlen(buffer), "%s.STAsBinary(), convert(varchar(36), %s)", layerinfo->geom_column, layerinfo->urid_name);
+  /* non single-pass case, fetch the record from the database */
 
-        columns_wanted = msStrdup(buffer);
+  if(layer->numitems == 0) {
+    if (layerinfo->geometry_format == MSSQLGEOMETRY_NATIVE)
+      snprintf(buffer, sizeof(buffer), "%s, convert(varchar(36), %s)", layerinfo->geom_column, layerinfo->urid_name);
+    else
+      snprintf(buffer, sizeof(buffer), "%s.STAsBinary(), convert(varchar(36), %s)", layerinfo->geom_column, layerinfo->urid_name);
+    columns_wanted = msStrdup(buffer);
+  } else {
+    for(t = 0; t < layer->numitems; t++) {
+      snprintf(buffer + strlen(buffer), sizeof(buffer) - strlen(buffer), "convert(varchar(max), %s),", layer->items[t]);
     }
 
-	/* index_name is ignored here since the hint should be for the spatial index, not the PK index */
-    snprintf(buffer, sizeof(buffer), "select %s from %s where %s = %d", columns_wanted, layerinfo->geom_table, layerinfo->urid_name, shapeindex);
+    if (layerinfo->geometry_format == MSSQLGEOMETRY_NATIVE)
+      snprintf(buffer + strlen(buffer), sizeof(buffer) - strlen(buffer), "%s, convert(varchar(36), %s)", layerinfo->geom_column, layerinfo->urid_name);
+    else
+      snprintf(buffer + strlen(buffer), sizeof(buffer) - strlen(buffer), "%s.STAsBinary(), convert(varchar(36), %s)", layerinfo->geom_column, layerinfo->urid_name);
 
-    query_str = msStrdup(buffer);
+    columns_wanted = msStrdup(buffer);
+  }
 
-    if(layer->debug) {
-        msDebug("msMSSQL2008LayerGetShape: %s \n", query_str);
-    }
+  /* index_name is ignored here since the hint should be for the spatial index, not the PK index */
+  snprintf(buffer, sizeof(buffer), "select %s from %s where %s = %d", columns_wanted, layerinfo->geom_table, layerinfo->urid_name, shapeindex);
 
-    msFree(columns_wanted);
+  query_str = msStrdup(buffer);
 
-    if (!executeSQL(layerinfo->conn, query_str))
-	{
-        msSetError(MS_QUERYERR, "Error executing MSSQL2008 SQL statement: %s\n-%s\n", "msMSSQL2008LayerGetShape()", 
-            query_str, layerinfo->conn->errorMessage);
+  if(layer->debug) {
+    msDebug("msMSSQL2008LayerGetShape: %s \n", query_str);
+  }
 
-        msFree(query_str);
+  msFree(columns_wanted);
 
-        return MS_FAILURE;
-    }
+  if (!executeSQL(layerinfo->conn, query_str)) {
+    msSetError(MS_QUERYERR, "Error executing MSSQL2008 SQL statement: %s\n-%s\n", "msMSSQL2008LayerGetShape()",
+               query_str, layerinfo->conn->errorMessage);
 
-    /* we don't preserve the query string in this case (cannot be re-used) */
     msFree(query_str);
-    layerinfo->row_num = 0;
 
-	return msMSSQL2008LayerGetShapeRandom(layer, shape, &(layerinfo->row_num));
+    return MS_FAILURE;
+  }
+
+  /* we don't preserve the query string in this case (cannot be re-used) */
+  msFree(query_str);
+  layerinfo->row_num = 0;
+
+  return msMSSQL2008LayerGetShapeRandom(layer, shape, &(layerinfo->row_num));
 }
 
 /* Query the DB for info about the requested table */
 int msMSSQL2008LayerGetItems(layerObj *layer)
 {
-    msMSSQL2008LayerInfo  *layerinfo;
-    char                *geom_column_name = 0;
-    char                sql[1000];
-    int                 t;
-    char                found_geom = 0;
-    int                 item_num;
-    SQLSMALLINT cols = 0;
-
-    if(layer->debug) 
-    {
-        msDebug("in msMSSQL2008LayerGetItems  (find column names)\n");
-    }
+  msMSSQL2008LayerInfo  *layerinfo;
+  char                *sql = NULL;
+  int                 t, sqlSize;
+  char                found_geom = 0;
+  int                 item_num;
+  SQLSMALLINT cols = 0;
 
-    layerinfo = getMSSQL2008LayerInfo(layer);
+  if(layer->debug) {
+    msDebug("in msMSSQL2008LayerGetItems  (find column names)\n");
+  }
 
-    if(!layerinfo) 
-    {
-        /* layer not opened yet */
-        msSetError(MS_QUERYERR, "msMSSQL2008LayerGetItems called on unopened layer", "msMSSQL2008LayerGetItems()");
+  layerinfo = getMSSQL2008LayerInfo(layer);
 
-        return MS_FAILURE;
-    }
+  if(!layerinfo) {
+    /* layer not opened yet */
+    msSetError(MS_QUERYERR, "msMSSQL2008LayerGetItems called on unopened layer", "msMSSQL2008LayerGetItems()");
 
-    if(!layerinfo->conn) 
-    {
-        msSetError(MS_QUERYERR, "msMSSQL2008LayerGetItems called on MSSQL2008 layer with no connection to DB.", "msMSSQL2008LayerGetItems()");
+    return MS_FAILURE;
+  }
 
-        return MS_FAILURE;
-    }
+  if(!layerinfo->conn) {
+    msSetError(MS_QUERYERR, "msMSSQL2008LayerGetItems called on MSSQL2008 layer with no connection to DB.", "msMSSQL2008LayerGetItems()");
 
-    snprintf(sql, sizeof(sql), "SELECT top 0 * FROM %s", layerinfo->geom_table); 
+    return MS_FAILURE;
+  }
 
-    if (!executeSQL(layerinfo->conn, sql))
-    {
-        msFree(geom_column_name);
+  sqlSize = strlen(layerinfo->geom_table) + 30;
+  sql = msSmallMalloc(sizeof(char *) * sqlSize);
 
-        return MS_FAILURE;
-    }
+  snprintf(sql, sqlSize, "SELECT top 0 * FROM %s", layerinfo->geom_table);
+
+  if (!executeSQL(layerinfo->conn, sql)) {
+    msFree(sql);
+    return MS_FAILURE;
+  }
 
-    SQLNumResultCols (layerinfo->conn->hstmt, &cols);
+  msFree(sql);
 
-    layer->numitems = cols - 1; /* dont include the geometry column */
+  SQLNumResultCols (layerinfo->conn->hstmt, &cols);
 
-    layer->items = msSmallMalloc(sizeof(char *) * (layer->numitems + 1)); /* +1 in case there is a problem finding goeometry column */
-                                                                /* it will return an error if there is no geometry column found, */
-                                                                /* so this isnt a problem */
+  layer->numitems = cols - 1; /* dont include the geometry column */
 
-    found_geom = 0; /* havent found the geom field */
-    item_num = 0;
+  layer->items = msSmallMalloc(sizeof(char *) * (layer->numitems + 1)); /* +1 in case there is a problem finding goeometry column */
+  /* it will return an error if there is no geometry column found, */
+  /* so this isnt a problem */
 
-    for(t = 0; t < cols; t++) 
-    {
-        char colBuff[256];
+  found_geom = 0; /* havent found the geom field */
+  item_num = 0;
 
-        columnName(layerinfo->conn, t + 1, colBuff, sizeof(colBuff));
+  for(t = 0; t < cols; t++) {
+    char colBuff[256];
 
-        if(strcmp(colBuff, layerinfo->geom_column) != 0) {
-            /* this isnt the geometry column */
-            layer->items[item_num] = (char *) msSmallMalloc(strlen(colBuff) + 1);
-            strcpy(layer->items[item_num], colBuff);
-            item_num++;
-        } else {
-            found_geom = 1;
-        }
-    }
+    columnName(layerinfo->conn, t + 1, colBuff, sizeof(colBuff));
 
-    if(!found_geom)
-	{
-        msSetError(MS_QUERYERR, "msMSSQL2008LayerGetItems: tried to find the geometry column in the results from the database, but couldnt find it.  Is it miss-capitialized? '%s'", "msMSSQL2008LayerGetItems()", layerinfo->geom_column);
-        return MS_FAILURE;
+    if(strcmp(colBuff, layerinfo->geom_column) != 0) {
+      /* this isnt the geometry column */
+      layer->items[item_num] = (char *) msSmallMalloc(strlen(colBuff) + 1);
+      strcpy(layer->items[item_num], colBuff);
+      item_num++;
+    } else {
+      found_geom = 1;
     }
+  }
 
-    return msMSSQL2008LayerInitItemInfo(layer);
+  if(!found_geom) {
+    msSetError(MS_QUERYERR, "msMSSQL2008LayerGetItems: tried to find the geometry column in the results from the database, but couldnt find it.  Is it miss-capitialized? '%s'", "msMSSQL2008LayerGetItems()", layerinfo->geom_column);
+    return MS_FAILURE;
+  }
+
+  return msMSSQL2008LayerInitItemInfo(layer);
 }
 
 /* Get the layer extent as specified in the mapfile or a largest area */
 /* covering all features */
 int msMSSQL2008LayerGetExtent(layerObj *layer, rectObj *extent)
 {
-    if(layer->debug) {
-        msDebug("msMSSQL2008LayerGetExtent called\n");
-    }
-
-    if (layer->extent.minx == -1.0 && layer->extent.miny == -1.0 &&
-        layer->extent.maxx == -1.0 && layer->extent.maxy == -1.0)
-    {
-        extent->minx = extent->miny = -1.0 * FLT_MAX;
-        extent->maxx = extent->maxy = FLT_MAX;
-    }
-    else
-    {
-        extent->minx = layer->extent.minx;
-        extent->miny = layer->extent.miny;
-        extent->maxx = layer->extent.maxx;
-        extent->maxy = layer->extent.maxy;
-    }
-
-    return MS_SUCCESS;
+  if(layer->debug) {
+    msDebug("msMSSQL2008LayerGetExtent called\n");
+  }
+
+  if (layer->extent.minx == -1.0 && layer->extent.miny == -1.0 &&
+      layer->extent.maxx == -1.0 && layer->extent.maxy == -1.0) {
+    extent->minx = extent->miny = -1.0 * FLT_MAX;
+    extent->maxx = extent->maxy = FLT_MAX;
+  } else {
+    extent->minx = layer->extent.minx;
+    extent->miny = layer->extent.miny;
+    extent->maxx = layer->extent.maxx;
+    extent->maxy = layer->extent.maxy;
+  }
+
+  return MS_SUCCESS;
 }
 
 /* Get primary key column of table */
-int msMSSQL2008LayerRetrievePK(layerObj *layer, char **urid_name, char* table_name, int debug) 
+int msMSSQL2008LayerRetrievePK(layerObj *layer, char **urid_name, char* table_name, int debug)
 {
 
-    char        sql[1024];
-    msMSSQL2008LayerInfo *layerinfo = 0;
-    SQLRETURN rc;
-
-    snprintf(sql, sizeof(sql), 
-        "SELECT     convert(varchar(50), sys.columns.name) AS ColumnName, sys.indexes.name "
-        "FROM         sys.columns INNER JOIN "
-        "                     sys.indexes INNER JOIN "
-        "                     sys.tables ON sys.indexes.object_id = sys.tables.object_id INNER JOIN "
-        "                     sys.index_columns ON sys.indexes.object_id = sys.index_columns.object_id AND sys.indexes.index_id = sys.index_columns.index_id ON "
-        "                     sys.columns.object_id = sys.index_columns.object_id AND sys.columns.column_id = sys.index_columns.column_id "
-        "WHERE     (sys.indexes.is_primary_key = 1) AND (sys.tables.name = N'%s') ",
-        table_name);
-    
-    if (debug)
-    {
-       msDebug("msMSSQL2008LayerRetrievePK: query = %s\n", sql);
-    }
+  char        sql[1024];
+  msMSSQL2008LayerInfo *layerinfo = 0;
+  SQLRETURN rc;
 
-    layerinfo = (msMSSQL2008LayerInfo *) layer->layerinfo;
+  snprintf(sql, sizeof(sql),
+           "SELECT     convert(varchar(50), sys.columns.name) AS ColumnName, sys.indexes.name "
+           "FROM         sys.columns INNER JOIN "
+           "                     sys.indexes INNER JOIN "
+           "                     sys.tables ON sys.indexes.object_id = sys.tables.object_id INNER JOIN "
+           "                     sys.index_columns ON sys.indexes.object_id = sys.index_columns.object_id AND sys.indexes.index_id = sys.index_columns.index_id ON "
+           "                     sys.columns.object_id = sys.index_columns.object_id AND sys.columns.column_id = sys.index_columns.column_id "
+           "WHERE     (sys.indexes.is_primary_key = 1) AND (sys.tables.name = N'%s') ",
+           table_name);
 
-    if(layerinfo->conn == NULL) 
-    {
+  if (debug) {
+    msDebug("msMSSQL2008LayerRetrievePK: query = %s\n", sql);
+  }
 
-      msSetError(MS_QUERYERR, "Layer does not have a MSSQL2008 connection.", "msMSSQL2008LayerRetrievePK()");
+  layerinfo = (msMSSQL2008LayerInfo *) layer->layerinfo;
 
-      return(MS_FAILURE);
-    }
+  if(layerinfo->conn == NULL) {
 
-    /* error somewhere above here in this method */
+    msSetError(MS_QUERYERR, "Layer does not have a MSSQL2008 connection.", "msMSSQL2008LayerRetrievePK()");
 
-    if(!executeSQL(layerinfo->conn, sql)) 
-    {
-        char *tmp1;
-        char *tmp2 = NULL;
-
-        tmp1 = "Error executing MSSQL2008 statement (msMSSQL2008LayerRetrievePK():";
-        tmp2 = (char *)msSmallMalloc(sizeof(char)*(strlen(tmp1) + strlen(sql) + 1));
-        strcpy(tmp2, tmp1);
-        strcat(tmp2, sql);
-        msSetError(MS_QUERYERR, tmp2, "msMSSQL2008LayerRetrievePK()");
-        msFree(tmp2);
-        return(MS_FAILURE);
-    }
+    return(MS_FAILURE);
+  }
 
-    rc = SQLFetch(layerinfo->conn->hstmt);
+  /* error somewhere above here in this method */
 
-    if(rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) 
-    {
-        if(debug) 
-        {
-            msDebug("msMSSQL2008LayerRetrievePK: No results found.\n");
-        }
+  if(!executeSQL(layerinfo->conn, sql)) {
+    char *tmp1;
+    char *tmp2 = NULL;
 
-        return MS_FAILURE;
-    }
+    tmp1 = "Error executing MSSQL2008 statement (msMSSQL2008LayerRetrievePK():";
+    tmp2 = (char *)msSmallMalloc(sizeof(char)*(strlen(tmp1) + strlen(sql) + 1));
+    strcpy(tmp2, tmp1);
+    strcat(tmp2, sql);
+    msSetError(MS_QUERYERR, tmp2, "msMSSQL2008LayerRetrievePK()");
+    msFree(tmp2);
+    return(MS_FAILURE);
+  }
 
-    {
-        char buff[100];
-        SQLINTEGER retLen;
-        rc = SQLGetData(layerinfo->conn->hstmt, 1, SQL_C_BINARY, buff, sizeof(buff), &retLen);
+  rc = SQLFetch(layerinfo->conn->hstmt);
+
+  if(rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) {
+    if(debug) {
+      msDebug("msMSSQL2008LayerRetrievePK: No results found.\n");
+    }
 
-        rc = SQLFetch(layerinfo->conn->hstmt);
+    return MS_FAILURE;
+  }
 
-        if(rc == SQL_SUCCESS || rc == SQL_SUCCESS_WITH_INFO) 
-        {
-            if(debug) 
-            {
-                msDebug("msMSSQL2008LayerRetrievePK: Multiple primary key columns are not supported in MapServer\n");
-            }
+  {
+    char buff[100];
+    SQLINTEGER retLen;
+    rc = SQLGetData(layerinfo->conn->hstmt, 1, SQL_C_BINARY, buff, sizeof(buff), &retLen);
 
-            return MS_FAILURE;
-        }
+    rc = SQLFetch(layerinfo->conn->hstmt);
 
-        buff[retLen] = 0;
+    if(rc == SQL_SUCCESS || rc == SQL_SUCCESS_WITH_INFO) {
+      if(debug) {
+        msDebug("msMSSQL2008LayerRetrievePK: Multiple primary key columns are not supported in MapServer\n");
+      }
 
-        *urid_name = msStrdup(buff);
+      return MS_FAILURE;
     }
 
-    return MS_SUCCESS;
+    buff[retLen] = 0;
+
+    *urid_name = msStrdup(buff);
+  }
+
+  return MS_SUCCESS;
 }
 
 /* Function to parse the Mapserver DATA parameter for geometry
@@ -1753,125 +1998,131 @@ int msMSSQL2008LayerRetrievePK(layerObj *layer, char **urid_name, char* table_na
  */
 static int msMSSQL2008LayerParseData(layerObj *layer, char **geom_column_name, char **geom_column_type, char **table_name, char **urid_name, char **user_srid, char **index_name, int debug)
 {
-    char    *pos_opt, *pos_scn, *tmp, *pos_srid, *pos_urid, *pos_geomtype, *pos_geomtype2, *pos_indexHint, *data;
-    int     slength;
-
-    data = layer->data;
-
-    /* given a string of the from 'geom from ctivalues' or 'geom from () as foo'
-     * return geom_column_name as 'geom'
-     * and table name as 'ctivalues' or 'geom from () as foo'
-     */
-
-    /* First look for the optional ' using unique ID' string */
-    pos_urid = strstrIgnoreCase(data, " using unique ");
-
-    if(pos_urid) {
-        /* CHANGE - protect the trailing edge for thing like 'using unique ftab_id using srid=33' */
-        tmp = strstr(pos_urid + 14, " ");
-        if(!tmp) {
-            tmp = pos_urid + strlen(pos_urid);
-        }
-        *urid_name = (char *) msSmallMalloc((tmp - (pos_urid + 14)) + 1);
-        strlcpy(*urid_name, pos_urid + 14, (tmp - (pos_urid + 14)) + 1);
-    }
-
-    /* Find the srid */
-    pos_srid = strstrIgnoreCase(data, " using SRID=");
-    if(!pos_srid) {
-        *user_srid = (char *) msSmallMalloc(2);
-        (*user_srid)[0] = '0';
-        (*user_srid)[1] = 0;
+  char    *pos_opt, *pos_scn, *tmp, *pos_srid, *pos_urid, *pos_geomtype, *pos_geomtype2, *pos_indexHint, *data;
+  int     slength;
+
+  data = msStrdup(layer->data);
+  /* replace tabs with spaces */
+  msReplaceChar(data, '\t', ' ');
+
+  /* given a string of the from 'geom from ctivalues' or 'geom from () as foo'
+   * return geom_column_name as 'geom'
+   * and table name as 'ctivalues' or 'geom from () as foo'
+   */
+
+  /* First look for the optional ' using unique ID' string */
+  pos_urid = strstrIgnoreCase(data, " using unique ");
+
+  if(pos_urid) {
+    /* CHANGE - protect the trailing edge for thing like 'using unique ftab_id using srid=33' */
+    tmp = strstr(pos_urid + 14, " ");
+    if(!tmp) {
+      tmp = pos_urid + strlen(pos_urid);
+    }
+    *urid_name = (char *) msSmallMalloc((tmp - (pos_urid + 14)) + 1);
+    strlcpy(*urid_name, pos_urid + 14, (tmp - (pos_urid + 14)) + 1);
+  }
+
+  /* Find the srid */
+  pos_srid = strstrIgnoreCase(data, " using SRID=");
+  if(!pos_srid) {
+    *user_srid = (char *) msSmallMalloc(2);
+    (*user_srid)[0] = '0';
+    (*user_srid)[1] = 0;
+  } else {
+    slength = strspn(pos_srid + 12, "-0123456789");
+    if(!slength) {
+      msSetError(MS_QUERYERR, DATA_ERROR_MESSAGE, "msMSSQL2008LayerParseData()", "Error parsing MSSQL2008 data variable: You specified 'using SRID=#' but didnt have any numbers!<br><br>\n\nMore Help:<br><br>\n\n", data);
+
+      msFree(data);
+      return MS_FAILURE;
     } else {
-        slength = strspn(pos_srid + 12, "-0123456789");
-        if(!slength) {
-            msSetError(MS_QUERYERR, DATA_ERROR_MESSAGE, "msMSSQL2008LayerParseData()", "Error parsing MSSQL2008 data variable: You specified 'using SRID=#' but didnt have any numbers!<br><br>\n\nMore Help:<br><br>\n\n", data);
-
-            return MS_FAILURE;
-        } else {
-            *user_srid = (char *) msSmallMalloc(slength + 1);
-            strlcpy(*user_srid, pos_srid + 12, slength+1);
-        }
-    }
-
-	pos_indexHint = strstrIgnoreCase(data, " using index ");
-    if(pos_indexHint) {
-        /* CHANGE - protect the trailing edge for thing like 'using unique ftab_id using srid=33' */
-        tmp = strstr(pos_indexHint + 13, " ");
-        if(!tmp) {
-            tmp = pos_indexHint + strlen(pos_indexHint);
-        }
-        *index_name = (char *) msSmallMalloc((tmp - (pos_indexHint + 13)) + 1);
-        strlcpy(*index_name, pos_indexHint + 13, tmp - (pos_indexHint + 13)+1);
-    }
-
-    /* this is a little hack so the rest of the code works.  If the ' using SRID=' comes before */
-    /* the ' using unique ', then make sure pos_opt points to where the ' using SRID' starts! */
-    pos_opt = pos_urid;
-	if ( !pos_opt || ( pos_srid && pos_srid < pos_opt ) ) pos_opt = pos_srid;
-	if ( !pos_opt || ( pos_indexHint && pos_indexHint < pos_opt ) ) pos_opt = pos_indexHint;
-	if ( !pos_opt ) pos_opt = data + strlen(data);
+      *user_srid = (char *) msSmallMalloc(slength + 1);
+      strlcpy(*user_srid, pos_srid + 12, slength+1);
+    }
+  }
+
+  pos_indexHint = strstrIgnoreCase(data, " using index ");
+  if(pos_indexHint) {
+    /* CHANGE - protect the trailing edge for thing like 'using unique ftab_id using srid=33' */
+    tmp = strstr(pos_indexHint + 13, " ");
+    if(!tmp) {
+      tmp = pos_indexHint + strlen(pos_indexHint);
+    }
+    *index_name = (char *) msSmallMalloc((tmp - (pos_indexHint + 13)) + 1);
+    strlcpy(*index_name, pos_indexHint + 13, tmp - (pos_indexHint + 13)+1);
+  }
+
+  /* this is a little hack so the rest of the code works.  If the ' using SRID=' comes before */
+  /* the ' using unique ', then make sure pos_opt points to where the ' using SRID' starts! */
+  pos_opt = pos_urid;
+  if ( !pos_opt || ( pos_srid && pos_srid < pos_opt ) ) pos_opt = pos_srid;
+  if ( !pos_opt || ( pos_indexHint && pos_indexHint < pos_opt ) ) pos_opt = pos_indexHint;
+  if ( !pos_opt ) pos_opt = data + strlen(data);
+
+  /* Scan for the table or sub-select clause */
+  pos_scn = strstrIgnoreCase(data, " from ");
+  if(!pos_scn) {
+    msSetError(MS_QUERYERR, DATA_ERROR_MESSAGE, "msMSSQL2008LayerParseData()", "Error parsing MSSQL2008 data variable.  Must contain 'geometry_column from table_name' or 'geom from (subselect) as foo' (couldn't find ' from ').  More help: <br><br>\n\n", data);
+
+    msFree(data);
+    return MS_FAILURE;
+  }
 
-    /* Scan for the table or sub-select clause */
-    pos_scn = strstrIgnoreCase(data, " from ");
-    if(!pos_scn) {
-        msSetError(MS_QUERYERR, DATA_ERROR_MESSAGE, "msMSSQL2008LayerParseData()", "Error parsing MSSQL2008 data variable.  Must contain 'geometry_column from table_name' or 'geom from (subselect) as foo' (couldn't find ' from ').  More help: <br><br>\n\n", data);
+  /* Scanning the geometry column type */
+  pos_geomtype = data;
+  while (pos_geomtype < pos_scn && *pos_geomtype != '(' && *pos_geomtype != 0)
+    ++pos_geomtype;
 
-        return MS_FAILURE;
+  if(*pos_geomtype == '(') {
+    pos_geomtype2 = pos_geomtype;
+    while (pos_geomtype2 < pos_scn && *pos_geomtype2 != ')' && *pos_geomtype2 != 0)
+      ++pos_geomtype2;
+    if (*pos_geomtype2 != ')' || pos_geomtype2 == pos_geomtype) {
+      msSetError(MS_QUERYERR, DATA_ERROR_MESSAGE, "msMSSQL2008LayerParseData()", "Error parsing MSSQL2008 data variable.  Invalid syntax near geometry column type.", data);
+      msFree(data);
+      return MS_FAILURE;
     }
 
-    /* Scanning the geometry column type */
-    pos_geomtype = data;
-    while (pos_geomtype < pos_scn && *pos_geomtype != '(' && *pos_geomtype != 0)
-        ++pos_geomtype;
+    *geom_column_name = (char *) msSmallMalloc((pos_geomtype - data) + 1);
+    strlcpy(*geom_column_name, data, pos_geomtype - data + 1);
 
-    if(*pos_geomtype == '(')
-    {
-        pos_geomtype2 = pos_geomtype;
-        while (pos_geomtype2 < pos_scn && *pos_geomtype2 != ')' && *pos_geomtype2 != 0)
-            ++pos_geomtype2;
-        if (*pos_geomtype2 != ')' || pos_geomtype2 == pos_geomtype) {
-            msSetError(MS_QUERYERR, DATA_ERROR_MESSAGE, "msMSSQL2008LayerParseData()", "Error parsing MSSQL2008 data variable.  Invalid syntax near geometry column type.", data);
-            return MS_FAILURE;
-        }
-
-        *geom_column_name = (char *) msSmallMalloc((pos_geomtype - data) + 1);
-        strlcpy(*geom_column_name, data, pos_geomtype - data + 1);
-
-        *geom_column_type = (char *) msSmallMalloc(pos_geomtype2 - pos_geomtype);
-        strlcpy(*geom_column_type, pos_geomtype + 1, pos_geomtype2 - pos_geomtype);
-    }
-    else {
+    *geom_column_type = (char *) msSmallMalloc(pos_geomtype2 - pos_geomtype);
+    strlcpy(*geom_column_type, pos_geomtype + 1, pos_geomtype2 - pos_geomtype);
+  } else {
     /* Copy the geometry column name */
-        *geom_column_name = (char *) msSmallMalloc((pos_scn - data) + 1);
-        strlcpy(*geom_column_name, data, pos_scn - data + 1);
-        *geom_column_type = msStrdup("geometry");
-    }
+    *geom_column_name = (char *) msSmallMalloc((pos_scn - data) + 1);
+    strlcpy(*geom_column_name, data, pos_scn - data + 1);
+    *geom_column_type = msStrdup("geometry");
+  }
 
-    /* Copy out the table name or sub-select clause */
-    *table_name = (char *) msSmallMalloc((pos_opt - (pos_scn + 6)) + 1);
-    strlcpy(*table_name, pos_scn + 6, pos_opt - (pos_scn + 6) + 1);
+  /* Copy out the table name or sub-select clause */
+  *table_name = (char *) msSmallMalloc((pos_opt - (pos_scn + 6)) + 1);
+  strlcpy(*table_name, pos_scn + 6, pos_opt - (pos_scn + 6) + 1);
 
-    if(strlen(*table_name) < 1 || strlen(*geom_column_name) < 1) {
-        msSetError(MS_QUERYERR, DATA_ERROR_MESSAGE, "msMSSQL2008LayerParseData()", "Error parsing MSSQL2008 data variable.  Must contain 'geometry_column from table_name' or 'geom from (subselect) as foo' (couldnt find a geometry_column or table/subselect).  More help: <br><br>\n\n", data);
+  if(strlen(*table_name) < 1 || strlen(*geom_column_name) < 1) {
+    msSetError(MS_QUERYERR, DATA_ERROR_MESSAGE, "msMSSQL2008LayerParseData()", "Error parsing MSSQL2008 data variable.  Must contain 'geometry_column from table_name' or 'geom from (subselect) as foo' (couldnt find a geometry_column or table/subselect).  More help: <br><br>\n\n", data);
 
-        return MS_FAILURE;
-    }
+    msFree(data);
+    return MS_FAILURE;
+  }
 
-    if( !pos_urid ) {
-        if( msMSSQL2008LayerRetrievePK(layer, urid_name, *table_name, debug) != MS_SUCCESS ) {
-            msSetError(MS_QUERYERR, DATA_ERROR_MESSAGE, "msMSSQL2008LayerParseData()", "No primary key defined for table, or primary key contains more that one column\n\n", 
-                *table_name);
+  if( !pos_urid ) {
+    if( msMSSQL2008LayerRetrievePK(layer, urid_name, *table_name, debug) != MS_SUCCESS ) {
+      msSetError(MS_QUERYERR, DATA_ERROR_MESSAGE, "msMSSQL2008LayerParseData()", "No primary key defined for table, or primary key contains more that one column\n\n",
+                 *table_name);
 
-            return MS_FAILURE;
-        }
+      msFree(data);
+      return MS_FAILURE;
     }
+  }
 
-    if(debug) {
-        msDebug("msMSSQL2008LayerParseData: unique column = %s, srid='%s', geom_column_name = %s, table_name=%s\n", *urid_name, *user_srid, *geom_column_name, *table_name);
-    }
+  if(debug) {
+    msDebug("msMSSQL2008LayerParseData: unique column = %s, srid='%s', geom_column_name = %s, table_name=%s\n", *urid_name, *user_srid, *geom_column_name, *table_name);
+  }
 
-    return MS_SUCCESS;
+  msFree(data);
+  return MS_SUCCESS;
 }
 
 #else
@@ -1880,67 +2131,67 @@ static int msMSSQL2008LayerParseData(layerObj *layer, char **geom_column_name, c
 
 int msMSSQL2008LayerOpen(layerObj *layer)
 {
-    msSetError(MS_QUERYERR, "msMSSQL2008LayerOpen called but unimplemented!  (mapserver not compiled with MSSQL2008 support)", "msMSSQL2008LayerOpen()");
-    return MS_FAILURE;
+  msSetError(MS_QUERYERR, "msMSSQL2008LayerOpen called but unimplemented!  (mapserver not compiled with MSSQL2008 support)", "msMSSQL2008LayerOpen()");
+  return MS_FAILURE;
 }
 
 int msMSSQL2008LayerIsOpen(layerObj *layer)
 {
-    msSetError(MS_QUERYERR, "msMSSQL2008IsLayerOpen called but unimplemented!  (mapserver not compiled with MSSQL2008 support)", "msMSSQL2008LayerIsOpen()");
-    return MS_FALSE;
+  msSetError(MS_QUERYERR, "msMSSQL2008IsLayerOpen called but unimplemented!  (mapserver not compiled with MSSQL2008 support)", "msMSSQL2008LayerIsOpen()");
+  return MS_FALSE;
 }
 
 void msMSSQL2008LayerFreeItemInfo(layerObj *layer)
 {
-    msSetError(MS_QUERYERR, "msMSSQL2008LayerFreeItemInfo called but unimplemented!(mapserver not compiled with MSSQL2008 support)", "msMSSQL2008LayerFreeItemInfo()");
+  msSetError(MS_QUERYERR, "msMSSQL2008LayerFreeItemInfo called but unimplemented!(mapserver not compiled with MSSQL2008 support)", "msMSSQL2008LayerFreeItemInfo()");
 }
 
 int msMSSQL2008LayerInitItemInfo(layerObj *layer)
 {
-    msSetError(MS_QUERYERR, "msMSSQL2008LayerInitItemInfo called but unimplemented!(mapserver not compiled with MSSQL2008 support)", "msMSSQL2008LayerInitItemInfo()");
-    return MS_FAILURE;
+  msSetError(MS_QUERYERR, "msMSSQL2008LayerInitItemInfo called but unimplemented!(mapserver not compiled with MSSQL2008 support)", "msMSSQL2008LayerInitItemInfo()");
+  return MS_FAILURE;
 }
 
 int msMSSQL2008LayerWhichShapes(layerObj *layer, rectObj rect, int isQuery)
 {
-    msSetError(MS_QUERYERR, "msMSSQL2008LayerWhichShapes called but unimplemented!(mapserver not compiled with MSSQL2008 support)", "msMSSQL2008LayerWhichShapes()");
-    return MS_FAILURE;
+  msSetError(MS_QUERYERR, "msMSSQL2008LayerWhichShapes called but unimplemented!(mapserver not compiled with MSSQL2008 support)", "msMSSQL2008LayerWhichShapes()");
+  return MS_FAILURE;
 }
 
 int msMSSQL2008LayerClose(layerObj *layer)
 {
-    msSetError(MS_QUERYERR, "msMSSQL2008LayerClose called but unimplemented!(mapserver not compiled with MSSQL2008 support)", "msMSSQL2008LayerClose()");
-    return MS_FAILURE;
+  msSetError(MS_QUERYERR, "msMSSQL2008LayerClose called but unimplemented!(mapserver not compiled with MSSQL2008 support)", "msMSSQL2008LayerClose()");
+  return MS_FAILURE;
 }
 
 int msMSSQL2008LayerNextShape(layerObj *layer, shapeObj *shape)
 {
-    msSetError(MS_QUERYERR, "msMSSQL2008LayerNextShape called but unimplemented!(mapserver not compiled with MSSQL2008 support)", "msMSSQL2008LayerNextShape()");
-    return MS_FAILURE;
+  msSetError(MS_QUERYERR, "msMSSQL2008LayerNextShape called but unimplemented!(mapserver not compiled with MSSQL2008 support)", "msMSSQL2008LayerNextShape()");
+  return MS_FAILURE;
 }
 
 int msMSSQL2008LayerGetShape(layerObj *layer, shapeObj *shape, long record)
 {
-    msSetError(MS_QUERYERR, "msMSSQL2008LayerGetShape called but unimplemented!(mapserver not compiled with MSSQL2008 support)", "msMSSQL2008LayerGetShape()");
-    return MS_FAILURE;
+  msSetError(MS_QUERYERR, "msMSSQL2008LayerGetShape called but unimplemented!(mapserver not compiled with MSSQL2008 support)", "msMSSQL2008LayerGetShape()");
+  return MS_FAILURE;
 }
 
 int msMSSQL2008LayerGetExtent(layerObj *layer, rectObj *extent)
 {
-    msSetError(MS_QUERYERR, "msMSSQL2008LayerGetExtent called but unimplemented!(mapserver not compiled with MSSQL2008 support)", "msMSSQL2008LayerGetExtent()");
-    return MS_FAILURE;
+  msSetError(MS_QUERYERR, "msMSSQL2008LayerGetExtent called but unimplemented!(mapserver not compiled with MSSQL2008 support)", "msMSSQL2008LayerGetExtent()");
+  return MS_FAILURE;
 }
 
 int msMSSQL2008LayerGetShapeRandom(layerObj *layer, shapeObj *shape, long *record)
 {
-    msSetError(MS_QUERYERR, "msMSSQL2008LayerGetShapeRandom called but unimplemented!(mapserver not compiled with MSSQL2008 support)", "msMSSQL2008LayerGetShapeRandom()");
-    return MS_FAILURE;
+  msSetError(MS_QUERYERR, "msMSSQL2008LayerGetShapeRandom called but unimplemented!(mapserver not compiled with MSSQL2008 support)", "msMSSQL2008LayerGetShapeRandom()");
+  return MS_FAILURE;
 }
 
 int msMSSQL2008LayerGetItems(layerObj *layer)
 {
-    msSetError(MS_QUERYERR, "msMSSQL2008LayerGetItems called but unimplemented!(mapserver not compiled with MSSQL2008 support)", "msMSSQL2008LayerGetItems()");
-    return MS_FAILURE;
+  msSetError(MS_QUERYERR, "msMSSQL2008LayerGetItems called but unimplemented!(mapserver not compiled with MSSQL2008 support)", "msMSSQL2008LayerGetItems()");
+  return MS_FAILURE;
 }
 
 
@@ -1952,33 +2203,33 @@ int msMSSQL2008LayerGetItems(layerObj *layer)
 MS_DLL_EXPORT  int
 PluginInitializeVirtualTable(layerVTableObj* vtable, layerObj *layer)
 {
-    assert(layer != NULL);
-    assert(vtable != NULL);
+  assert(layer != NULL);
+  assert(vtable != NULL);
 
-    vtable->LayerInitItemInfo = msMSSQL2008LayerInitItemInfo;
-    vtable->LayerFreeItemInfo = msMSSQL2008LayerFreeItemInfo;
-    vtable->LayerOpen = msMSSQL2008LayerOpen;
-    vtable->LayerIsOpen = msMSSQL2008LayerIsOpen;
-    vtable->LayerWhichShapes = msMSSQL2008LayerWhichShapes;
-    vtable->LayerNextShape = msMSSQL2008LayerNextShape;
-    vtable->LayerGetShape = msMSSQL2008LayerGetShape;
+  vtable->LayerInitItemInfo = msMSSQL2008LayerInitItemInfo;
+  vtable->LayerFreeItemInfo = msMSSQL2008LayerFreeItemInfo;
+  vtable->LayerOpen = msMSSQL2008LayerOpen;
+  vtable->LayerIsOpen = msMSSQL2008LayerIsOpen;
+  vtable->LayerWhichShapes = msMSSQL2008LayerWhichShapes;
+  vtable->LayerNextShape = msMSSQL2008LayerNextShape;
+  vtable->LayerGetShape = msMSSQL2008LayerGetShape;
 
-    vtable->LayerClose = msMSSQL2008LayerClose;
+  vtable->LayerClose = msMSSQL2008LayerClose;
 
-    vtable->LayerGetItems = msMSSQL2008LayerGetItems;
-    vtable->LayerGetExtent = msMSSQL2008LayerGetExtent;
+  vtable->LayerGetItems = msMSSQL2008LayerGetItems;
+  vtable->LayerGetExtent = msMSSQL2008LayerGetExtent;
 
-    vtable->LayerApplyFilterToLayer = msLayerApplyCondSQLFilterToLayer;
+  vtable->LayerApplyFilterToLayer = msLayerApplyCondSQLFilterToLayer;
 
-    /* vtable->LayerGetAutoStyle, not supported for this layer */
-    vtable->LayerCloseConnection = msMSSQL2008LayerClose;
-    
-    vtable->LayerSetTimeFilter = msLayerMakePlainTimeFilter;
-    /* vtable->LayerCreateItems, use default */
-    /* vtable->LayerGetNumFeatures, use default */
-    /* layer->vtable->LayerGetAutoProjection, use defaut*/
+  /* vtable->LayerGetAutoStyle, not supported for this layer */
+  vtable->LayerCloseConnection = msMSSQL2008LayerClose;
 
-    return MS_SUCCESS;
+  vtable->LayerSetTimeFilter = msLayerMakePlainTimeFilter;
+  /* vtable->LayerCreateItems, use default */
+  /* vtable->LayerGetNumFeatures, use default */
+  /* layer->vtable->LayerGetAutoProjection, use defaut*/
+
+  return MS_SUCCESS;
 }
 
 #endif
@@ -1986,31 +2237,31 @@ PluginInitializeVirtualTable(layerVTableObj* vtable, layerObj *layer)
 int
 msMSSQL2008LayerInitializeVirtualTable(layerObj *layer)
 {
-    assert(layer != NULL);
-    assert(layer->vtable != NULL);
+  assert(layer != NULL);
+  assert(layer->vtable != NULL);
 
-    layer->vtable->LayerInitItemInfo = msMSSQL2008LayerInitItemInfo;
-    layer->vtable->LayerFreeItemInfo = msMSSQL2008LayerFreeItemInfo;
-    layer->vtable->LayerOpen = msMSSQL2008LayerOpen;
-    layer->vtable->LayerIsOpen = msMSSQL2008LayerIsOpen;
-    layer->vtable->LayerWhichShapes = msMSSQL2008LayerWhichShapes;
-    layer->vtable->LayerNextShape = msMSSQL2008LayerNextShape;
-    layer->vtable->LayerGetShape = msMSSQL2008LayerGetShape;
+  layer->vtable->LayerInitItemInfo = msMSSQL2008LayerInitItemInfo;
+  layer->vtable->LayerFreeItemInfo = msMSSQL2008LayerFreeItemInfo;
+  layer->vtable->LayerOpen = msMSSQL2008LayerOpen;
+  layer->vtable->LayerIsOpen = msMSSQL2008LayerIsOpen;
+  layer->vtable->LayerWhichShapes = msMSSQL2008LayerWhichShapes;
+  layer->vtable->LayerNextShape = msMSSQL2008LayerNextShape;
+  layer->vtable->LayerGetShape = msMSSQL2008LayerGetShape;
 
-    layer->vtable->LayerClose = msMSSQL2008LayerClose;
+  layer->vtable->LayerClose = msMSSQL2008LayerClose;
 
-    layer->vtable->LayerGetItems = msMSSQL2008LayerGetItems;
-    layer->vtable->LayerGetExtent = msMSSQL2008LayerGetExtent;
+  layer->vtable->LayerGetItems = msMSSQL2008LayerGetItems;
+  layer->vtable->LayerGetExtent = msMSSQL2008LayerGetExtent;
 
-    layer->vtable->LayerApplyFilterToLayer = msLayerApplyCondSQLFilterToLayer;
+  layer->vtable->LayerApplyFilterToLayer = msLayerApplyCondSQLFilterToLayer;
 
-    /* layer->vtable->LayerGetAutoStyle, not supported for this layer */
-    layer->vtable->LayerCloseConnection = msMSSQL2008LayerClose;
-    
-    layer->vtable->LayerSetTimeFilter = msLayerMakePlainTimeFilter;
-    /* layer->vtable->LayerCreateItems, use default */
-    /* layer->vtable->LayerGetNumFeatures, use default */
+  /* layer->vtable->LayerGetAutoStyle, not supported for this layer */
+  layer->vtable->LayerCloseConnection = msMSSQL2008LayerClose;
 
+  layer->vtable->LayerSetTimeFilter = msLayerMakePlainTimeFilter;
+  /* layer->vtable->LayerCreateItems, use default */
+  /* layer->vtable->LayerGetNumFeatures, use default */
 
-    return MS_SUCCESS;
+
+  return MS_SUCCESS;
 }
diff --git a/mapobject.c b/mapobject.c
index f7618f9..2d7ee4d 100644
--- a/mapobject.c
+++ b/mapobject.c
@@ -16,7 +16,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -35,7 +35,7 @@
 #  include "cpl_conv.h"
 #endif
 
-MS_CVSID("$Id$")
+
 
 void freeWeb(webObj *web);
 void freeScalebar(scalebarObj *scalebar);
@@ -50,40 +50,42 @@ void freeLegend(legendObj *legend);
 
 mapObj *msNewMapObj()
 {
-    mapObj *map;
+  mapObj *map;
 
-    /* create an empty map, no layers etc... */
-    map = (mapObj *)calloc(sizeof(mapObj),1);
+  /* create an empty map, no layers etc... */
+  map = (mapObj *)calloc(sizeof(mapObj),1);
 
-    if(!map)
-    {
-        msSetError(MS_MEMERR, NULL, "msCreateMap()");
-        return NULL;
-    }
+  if(!map) {
+    msSetError(MS_MEMERR, NULL, "msCreateMap()");
+    return NULL;
+  }
 
-    if( initMap( map ) == -1 )
-        return NULL;
+  if( initMap( map ) == -1 )
+    return NULL;
 
-    if( msPostMapParseOutputFormatSetup( map ) == MS_FAILURE )
-        return NULL;
+  if( msPostMapParseOutputFormatSetup( map ) == MS_FAILURE )
+    return NULL;
 
-    return map;
+  return map;
 }
 
 /************************************************************************/
 /*                             msFreeMap()                              */
 /************************************************************************/
 
-void msFreeMap(mapObj *map) {
+void msFreeMap(mapObj *map)
+{
   int i;
 
   if(!map) return;
 
   /* printf("msFreeMap(): maybe freeing map at %p count=%d.\n",map, map->refcount); */
-  if(MS_REFCNT_DECR_IS_NOT_ZERO(map)) { return; }
+  if(MS_REFCNT_DECR_IS_NOT_ZERO(map)) {
+    return;
+  }
   if(map->debug >= MS_DEBUGLEVEL_VV)
-     msDebug("msFreeMap(): freeing map at %p.\n",map);
-  
+    msDebug("msFreeMap(): freeing map at %p.\n",map);
+
   msCloseConnections(map);
 
   msFree(map->name);
@@ -106,7 +108,7 @@ void msFreeMap(mapObj *map) {
 
   freeScalebar(&(map->scalebar));
   freeReferenceMap(&(map->reference));
-  freeLegend(&(map->legend));  
+  freeLegend(&(map->legend));
 
   for(i=0; i<map->maxlayers; i++) {
     if(GET_LAYER(map, i) != NULL) {
@@ -145,7 +147,7 @@ void msFreeMap(mapObj *map) {
 const char *msGetConfigOption( mapObj *map, const char *key)
 
 {
-    return msLookupHashTable( &(map->configoptions), key );
+  return msLookupHashTable( &(map->configoptions), key );
 }
 
 /************************************************************************/
@@ -155,29 +157,27 @@ const char *msGetConfigOption( mapObj *map, const char *key)
 int msSetConfigOption( mapObj *map, const char *key, const char *value)
 
 {
-    /* We have special "early" handling of this so that it will be */
-    /* in effect when the projection blocks are parsed and pj_init is called. */
-    if( strcasecmp(key,"PROJ_LIB") == 0 )
-    {
-        /* value may be relative to map path */
-        msSetPROJ_LIB( value, map->mappath );
-    }
+  /* We have special "early" handling of this so that it will be */
+  /* in effect when the projection blocks are parsed and pj_init is called. */
+  if( strcasecmp(key,"PROJ_LIB") == 0 ) {
+    /* value may be relative to map path */
+    msSetPROJ_LIB( value, map->mappath );
+  }
 
-    /* Same for MS_ERRORFILE, we want it to kick in as early as possible
-     * to catch parsing errors.
-     * Value can be relative to mapfile, unless it's already absolute 
-     */
-    if( strcasecmp(key,"MS_ERRORFILE") == 0 )
-    {
-        if (msSetErrorFile( value, map->mappath ) != MS_SUCCESS)
-            return MS_FAILURE;
-    }
+  /* Same for MS_ERRORFILE, we want it to kick in as early as possible
+   * to catch parsing errors.
+   * Value can be relative to mapfile, unless it's already absolute
+   */
+  if( strcasecmp(key,"MS_ERRORFILE") == 0 ) {
+    if (msSetErrorFile( value, map->mappath ) != MS_SUCCESS)
+      return MS_FAILURE;
+  }
 
-    if( msLookupHashTable( &(map->configoptions), key ) != NULL )
-        msRemoveHashTable( &(map->configoptions), key );
-    msInsertHashTable( &(map->configoptions), key, value );
+  if( msLookupHashTable( &(map->configoptions), key ) != NULL )
+    msRemoveHashTable( &(map->configoptions), key );
+  msInsertHashTable( &(map->configoptions), key, value );
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 /************************************************************************/
@@ -187,17 +187,17 @@ int msSetConfigOption( mapObj *map, const char *key, const char *value)
 int msTestConfigOption( mapObj *map, const char *key, int default_result )
 
 {
-    const char *result = msGetConfigOption( map, key );
-
-    if( result == NULL )
-        return default_result;
-    
-    if( strcasecmp(result,"YES") == 0 
-        || strcasecmp(result,"ON") == 0 
-        || strcasecmp(result,"TRUE") == 0 )
-        return MS_TRUE;
-    else
-        return MS_FALSE;
+  const char *result = msGetConfigOption( map, key );
+
+  if( result == NULL )
+    return default_result;
+
+  if( strcasecmp(result,"YES") == 0
+      || strcasecmp(result,"ON") == 0
+      || strcasecmp(result,"TRUE") == 0 )
+    return MS_TRUE;
+  else
+    return MS_FALSE;
 }
 
 /************************************************************************/
@@ -207,29 +207,23 @@ int msTestConfigOption( mapObj *map, const char *key, int default_result )
 void msApplyMapConfigOptions( mapObj *map )
 
 {
-    const char *key;
-
-    for( key = msFirstKeyFromHashTable( &(map->configoptions) );
-         key != NULL;
-         key = msNextKeyFromHashTable( &(map->configoptions), key ) )
-    {
-        const char *value = msLookupHashTable( &(map->configoptions), key );
-        if( strcasecmp(key,"PROJ_LIB") == 0 )
-        {
-            msSetPROJ_LIB( value, map->mappath );
-        }
-        else if( strcasecmp(key,"MS_ERRORFILE") == 0 )
-        {
-            msSetErrorFile( value, map->mappath );
-        }
-        else 
-        {
+  const char *key;
+
+  for( key = msFirstKeyFromHashTable( &(map->configoptions) );
+       key != NULL;
+       key = msNextKeyFromHashTable( &(map->configoptions), key ) ) {
+    const char *value = msLookupHashTable( &(map->configoptions), key );
+    if( strcasecmp(key,"PROJ_LIB") == 0 ) {
+      msSetPROJ_LIB( value, map->mappath );
+    } else if( strcasecmp(key,"MS_ERRORFILE") == 0 ) {
+      msSetErrorFile( value, map->mappath );
+    } else {
 
 #if defined(USE_GDAL) && GDAL_RELEASE_DATE > 20030601
-            CPLSetConfigOption( key, value );
+      CPLSetConfigOption( key, value );
 #endif
-        }   
     }
+  }
 }
 
 /************************************************************************/
@@ -238,114 +232,114 @@ void msApplyMapConfigOptions( mapObj *map )
 
 int msMapIgnoreMissingData( mapObj *map )
 {
-    const char *result = msGetConfigOption( map, "ON_MISSING_DATA" );
-    const int default_result = 
+  const char *result = msGetConfigOption( map, "ON_MISSING_DATA" );
+  const int default_result =
 #ifndef IGNORE_MISSING_DATA
-        MS_MISSING_DATA_FAIL;
+    MS_MISSING_DATA_FAIL;
 #else
-        MS_MISSING_DATA_LOG;
+    MS_MISSING_DATA_LOG;
 #endif
-        
-    if( result == NULL )
-        return default_result;
-        
-    if( strcasecmp(result,"FAIL") == 0 ) 
-        return MS_MISSING_DATA_FAIL;
-    else if( strcasecmp(result,"LOG") == 0 )
-        return MS_MISSING_DATA_LOG;
-    else if( strcasecmp(result,"IGNORE") == 0 )
-        return MS_MISSING_DATA_IGNORE;
-
-    return default_result;    
+
+  if( result == NULL )
+    return default_result;
+
+  if( strcasecmp(result,"FAIL") == 0 )
+    return MS_MISSING_DATA_FAIL;
+  else if( strcasecmp(result,"LOG") == 0 )
+    return MS_MISSING_DATA_LOG;
+  else if( strcasecmp(result,"IGNORE") == 0 )
+    return MS_MISSING_DATA_IGNORE;
+
+  return default_result;
 }
 
 /************************************************************************/
 /*                           msMapSetExtent()                           */
 /************************************************************************/
 
-int msMapSetExtent( mapObj *map, 
-                    double minx, double miny, double maxx, double maxy) 
-{ 
+int msMapSetExtent( mapObj *map,
+                    double minx, double miny, double maxx, double maxy)
+{
 
-    map->extent.minx = minx;
-    map->extent.miny = miny;
-    map->extent.maxx = maxx;
-    map->extent.maxy = maxy;
-    
-    if (!MS_VALID_EXTENT(map->extent)) {
-        msSetError(MS_MISCERR, "Given map extent is invalid. Check that it " \
-        "is in the form: minx, miny, maxx, maxy", "setExtent()"); 
-        return MS_FAILURE;
-    }
-      
-    map->cellsize = msAdjustExtent(&(map->extent), map->width, 
-                                   map->height);
+  map->extent.minx = minx;
+  map->extent.miny = miny;
+  map->extent.maxx = maxx;
+  map->extent.maxy = maxy;
+
+  if (!MS_VALID_EXTENT(map->extent)) {
+    msSetError(MS_MISCERR, "Given map extent is invalid. Check that it " \
+               "is in the form: minx, miny, maxx, maxy", "setExtent()");
+    return MS_FAILURE;
+  }
 
-    /* if the map size is also set, recompute scale, ignore errors? */
-    if( map->width != -1 || map->height != -1 )
-        msCalculateScale(map->extent, map->units, map->width, map->height, 
-                         map->resolution, &(map->scaledenom));
+  map->cellsize = msAdjustExtent(&(map->extent), map->width,
+                                 map->height);
 
-    return msMapComputeGeotransform( map );
+  /* if the map size is also set, recompute scale, ignore errors? */
+  if( map->width != -1 || map->height != -1 )
+    msCalculateScale(map->extent, map->units, map->width, map->height,
+                     map->resolution, &(map->scaledenom));
+
+  return msMapComputeGeotransform( map );
 }
 
 /************************************************************************/
 /*                           msMapOffsetExtent()                        */
 /************************************************************************/
 
-int msMapOffsetExtent( mapObj *map, double x, double y) 
-{ 
-	return msMapSetExtent( map, 
-                        map->extent.minx + x, map->extent.miny + y, 
-		                map->extent.maxx + x, map->extent.maxy + y);
+int msMapOffsetExtent( mapObj *map, double x, double y)
+{
+  return msMapSetExtent( map,
+                         map->extent.minx + x, map->extent.miny + y,
+                         map->extent.maxx + x, map->extent.maxy + y);
 }
 
 /************************************************************************/
 /*                           msMapScaleExtent()                         */
 /************************************************************************/
 
-int msMapScaleExtent( mapObj *map, double zoomfactor, 
-					 double minscaledenom, double maxscaledenom) 
-{ 
-	double geo_width, geo_height, center_x, center_y, md;
+int msMapScaleExtent( mapObj *map, double zoomfactor,
+                      double minscaledenom, double maxscaledenom)
+{
+  double geo_width, geo_height, center_x, center_y, md;
 
-	if (zoomfactor <= 0.0) {
-		msSetError(MS_MISCERR, "The given zoomfactor is invalid", "msMapScaleExtent()"); 
-	}
+  if (zoomfactor <= 0.0) {
+    msSetError(MS_MISCERR, "The given zoomfactor is invalid", "msMapScaleExtent()");
+  }
 
-	geo_width = map->extent.maxx - map->extent.minx;
-    geo_height = map->extent.maxy - map->extent.miny;
+  geo_width = map->extent.maxx - map->extent.minx;
+  geo_height = map->extent.maxy - map->extent.miny;
 
-    center_x = map->extent.minx + geo_width * 0.5;
-    center_y = map->extent.miny + geo_height * 0.5;
+  center_x = map->extent.minx + geo_width * 0.5;
+  center_y = map->extent.miny + geo_height * 0.5;
 
-	geo_width *= zoomfactor;
+  geo_width *= zoomfactor;
 
-	if (minscaledenom > 0 || maxscaledenom > 0) {
-		/* ensure we are within the valid scale domain */
-		md = (map->width-1)/(map->resolution * msInchesPerUnit(map->units, center_y));
-		if (minscaledenom > 0 && geo_width < minscaledenom * md)
-			geo_width = minscaledenom * md;
-		if (maxscaledenom > 0 && geo_width > maxscaledenom * md)
-			geo_width = maxscaledenom * md;
-	}
+  if (minscaledenom > 0 || maxscaledenom > 0) {
+    /* ensure we are within the valid scale domain */
+    md = (map->width-1)/(map->resolution * msInchesPerUnit(map->units, center_y));
+    if (minscaledenom > 0 && geo_width < minscaledenom * md)
+      geo_width = minscaledenom * md;
+    if (maxscaledenom > 0 && geo_width > maxscaledenom * md)
+      geo_width = maxscaledenom * md;
+  }
 
-	geo_width *= 0.5;
-	geo_height = geo_width * map->height / map->width;
-	
-	return msMapSetExtent( map, 
-                        center_x - geo_width, center_y - geo_height, 
-		                center_x + geo_width, center_y + geo_height);
+  geo_width *= 0.5;
+  geo_height = geo_width * map->height / map->width;
+
+  return msMapSetExtent( map,
+                         center_x - geo_width, center_y - geo_height,
+                         center_x + geo_width, center_y + geo_height);
 }
 
 /************************************************************************/
 /*                           msMapSetCenter()                           */
 /************************************************************************/
 
-int msMapSetCenter( mapObj *map, pointObj *center) 
-{ 
-	return msMapOffsetExtent(map, center->x - (map->extent.minx + map->extent.maxx) * 0.5,
-		                          center->y - (map->extent.miny + map->extent.maxy) * 0.5);
+int msMapSetCenter( mapObj *map, pointObj *center)
+{
+  return msMapOffsetExtent(map, center->x - (map->extent.minx + map->extent.maxx) * 0.5,
+                           center->y - (map->extent.miny + map->extent.maxy) * 0.5);
 }
 
 /************************************************************************/
@@ -355,13 +349,13 @@ int msMapSetCenter( mapObj *map, pointObj *center)
 int msMapSetRotation( mapObj *map, double rotation_angle )
 
 {
-    map->gt.rotation_angle = rotation_angle;
-    if( map->gt.rotation_angle != 0.0 )
-        map->gt.need_geotransform = MS_TRUE;
-    else
-        map->gt.need_geotransform = MS_FALSE;
+  map->gt.rotation_angle = rotation_angle;
+  if( map->gt.rotation_angle != 0.0 )
+    map->gt.need_geotransform = MS_TRUE;
+  else
+    map->gt.need_geotransform = MS_FALSE;
 
-    return msMapComputeGeotransform( map );
+  return msMapComputeGeotransform( map );
 }
 
 /************************************************************************/
@@ -371,10 +365,10 @@ int msMapSetRotation( mapObj *map, double rotation_angle )
 int msMapSetSize( mapObj *map, int width, int height )
 
 {
-    map->width = width;
-    map->height = height;
+  map->width = width;
+  map->height = height;
 
-    return msMapComputeGeotransform( map ); /* like SetRotation -- sean */
+  return msMapComputeGeotransform( map ); /* like SetRotation -- sean */
 }
 
 /************************************************************************/
@@ -386,50 +380,50 @@ extern int InvGeoTransform( double *gt_in, double *gt_out );
 int msMapComputeGeotransform( mapObj * map )
 
 {
-    double rot_angle;
-    double geo_width, geo_height, center_x, center_y;
+  double rot_angle;
+  double geo_width, geo_height, center_x, center_y;
 
-    map->saved_extent = map->extent;
+  map->saved_extent = map->extent;
 
-    /* Do we have all required parameters? */
-    if( map->extent.minx == map->extent.maxx 
-        || map->width == 0 || map->height == 0 )
-        return MS_FAILURE;
+  /* Do we have all required parameters? */
+  if( map->extent.minx == map->extent.maxx
+      || map->width == 0 || map->height == 0 )
+    return MS_FAILURE;
 
-    rot_angle = map->gt.rotation_angle * MS_PI / 180.0;
-
-    geo_width = map->extent.maxx - map->extent.minx;
-    geo_height = map->extent.maxy - map->extent.miny;
-
-    center_x = map->extent.minx + geo_width*0.5;
-    center_y = map->extent.miny + geo_height*0.5;
-
-    /*
-    ** Per bug 1916 we have to adjust for the fact that map extents
-    ** are based on the center of the edge pixels, not the outer
-    ** edges as is expected in a geotransform.
-    */
-    map->gt.geotransform[1] = 
-        cos(rot_angle) * geo_width / (map->width-1);
-    map->gt.geotransform[2] = 
-        sin(rot_angle) * geo_height / (map->height-1);
-    map->gt.geotransform[0] = center_x 
-        - (map->width * 0.5) * map->gt.geotransform[1]
-        - (map->height * 0.5) * map->gt.geotransform[2];
-
-    map->gt.geotransform[4] = 
-        sin(rot_angle) * geo_width / (map->width-1);
-    map->gt.geotransform[5] = 
-        - cos(rot_angle) * geo_height / (map->height-1);
-    map->gt.geotransform[3] = center_y 
-        - (map->width * 0.5) * map->gt.geotransform[4]
-        - (map->height * 0.5) * map->gt.geotransform[5];
-
-    if( InvGeoTransform( map->gt.geotransform, 
-                         map->gt.invgeotransform ) )
-        return MS_SUCCESS;
-    else
-        return MS_FAILURE;
+  rot_angle = map->gt.rotation_angle * MS_PI / 180.0;
+
+  geo_width = map->extent.maxx - map->extent.minx;
+  geo_height = map->extent.maxy - map->extent.miny;
+
+  center_x = map->extent.minx + geo_width*0.5;
+  center_y = map->extent.miny + geo_height*0.5;
+
+  /*
+  ** Per bug 1916 we have to adjust for the fact that map extents
+  ** are based on the center of the edge pixels, not the outer
+  ** edges as is expected in a geotransform.
+  */
+  map->gt.geotransform[1] =
+    cos(rot_angle) * geo_width / (map->width-1);
+  map->gt.geotransform[2] =
+    sin(rot_angle) * geo_height / (map->height-1);
+  map->gt.geotransform[0] = center_x
+                            - (map->width * 0.5) * map->gt.geotransform[1]
+                            - (map->height * 0.5) * map->gt.geotransform[2];
+
+  map->gt.geotransform[4] =
+    sin(rot_angle) * geo_width / (map->width-1);
+  map->gt.geotransform[5] =
+    - cos(rot_angle) * geo_height / (map->height-1);
+  map->gt.geotransform[3] = center_y
+                            - (map->width * 0.5) * map->gt.geotransform[4]
+                            - (map->height * 0.5) * map->gt.geotransform[5];
+
+  if( InvGeoTransform( map->gt.geotransform,
+                       map->gt.invgeotransform ) )
+    return MS_SUCCESS;
+  else
+    return MS_FAILURE;
 }
 
 /************************************************************************/
@@ -439,7 +433,7 @@ int msMapComputeGeotransform( mapObj * map )
 void msMapPixelToGeoref( mapObj *map, double *x, double *y )
 
 {
-    msSetError(MS_MISCERR, NULL, "msMapPixelToGeoref() not yet implemented");
+  msSetError(MS_MISCERR, NULL, "msMapPixelToGeoref() not yet implemented");
 }
 
 /************************************************************************/
@@ -449,7 +443,7 @@ void msMapPixelToGeoref( mapObj *map, double *x, double *y )
 void msMapGeorefToPixel( mapObj *map, double *x, double *y )
 
 {
-    msSetError(MS_MISCERR, NULL, "msMapGeorefToPixel() not yet implemented");
+  msSetError(MS_MISCERR, NULL, "msMapGeorefToPixel() not yet implemented");
 }
 
 /************************************************************************/
@@ -459,49 +453,49 @@ void msMapGeorefToPixel( mapObj *map, double *x, double *y )
 int msMapSetFakedExtent( mapObj *map )
 
 {
-    int i;
-/* -------------------------------------------------------------------- */
-/*      Remember the original map extents so we can restore them        */
-/*      later.                                                          */
-/* -------------------------------------------------------------------- */
-    map->saved_extent = map->extent;
-
-/* -------------------------------------------------------------------- */
-/*      Set extents such that the bottom left corner is 0,0 and the     */
-/*      top right is width,height.  Note this is upside down from       */
-/*      the normal sense of pixel/line coordiantes, but we do this      */
-/*      so that the normal "extent" concept of coordinates              */
-/*      increasing to the right, and up is maintained (like in          */
-/*      georeferenced coordinate systems).                              */
-/* -------------------------------------------------------------------- */
-    map->extent.minx = 0;
-    map->extent.maxx = map->width;
-    map->extent.miny = 0;
-    map->extent.maxy = map->height;
-    map->cellsize = 1.0;
-
-/* -------------------------------------------------------------------- */
-/*      When we copy the geotransform into the projection object we     */
-/*      have to flip it to account for the preceeding upside-down       */
-/*      coordinate system.                                              */
-/* -------------------------------------------------------------------- */
-    map->projection.gt = map->gt;
-
-    map->projection.gt.geotransform[0] 
-        += map->height * map->gt.geotransform[2];
-    map->projection.gt.geotransform[3] 
-        += map->height * map->gt.geotransform[5];
-
-    map->projection.gt.geotransform[2] *= -1;
-    map->projection.gt.geotransform[5] *= -1;
-
-    for(i=0; i<map->numlayers; i++)
-        GET_LAYER(map, i)->project = MS_TRUE;
-
-    return InvGeoTransform( map->projection.gt.geotransform, 
-                            map->projection.gt.invgeotransform );
+  int i;
+  /* -------------------------------------------------------------------- */
+  /*      Remember the original map extents so we can restore them        */
+  /*      later.                                                          */
+  /* -------------------------------------------------------------------- */
+  map->saved_extent = map->extent;
+
+  /* -------------------------------------------------------------------- */
+  /*      Set extents such that the bottom left corner is 0,0 and the     */
+  /*      top right is width,height.  Note this is upside down from       */
+  /*      the normal sense of pixel/line coordiantes, but we do this      */
+  /*      so that the normal "extent" concept of coordinates              */
+  /*      increasing to the right, and up is maintained (like in          */
+  /*      georeferenced coordinate systems).                              */
+  /* -------------------------------------------------------------------- */
+  map->extent.minx = 0;
+  map->extent.maxx = map->width;
+  map->extent.miny = 0;
+  map->extent.maxy = map->height;
+  map->cellsize = 1.0;
+
+  /* -------------------------------------------------------------------- */
+  /*      When we copy the geotransform into the projection object we     */
+  /*      have to flip it to account for the preceeding upside-down       */
+  /*      coordinate system.                                              */
+  /* -------------------------------------------------------------------- */
+  map->projection.gt = map->gt;
+
+  map->projection.gt.geotransform[0]
+  += map->height * map->gt.geotransform[2];
+  map->projection.gt.geotransform[3]
+  += map->height * map->gt.geotransform[5];
+
+  map->projection.gt.geotransform[2] *= -1;
+  map->projection.gt.geotransform[5] *= -1;
+
+  for(i=0; i<map->numlayers; i++)
+    GET_LAYER(map, i)->project = MS_TRUE;
+
+  return InvGeoTransform( map->projection.gt.geotransform,
+                          map->projection.gt.invgeotransform );
 }
-    
+
 /************************************************************************/
 /*                      msMapRestoreRealExtent()                        */
 /************************************************************************/
@@ -509,11 +503,11 @@ int msMapSetFakedExtent( mapObj *map )
 int msMapRestoreRealExtent( mapObj *map )
 
 {
-    map->projection.gt.need_geotransform = MS_FALSE;
-    map->extent = map->saved_extent;
-    map->cellsize = msAdjustExtent(&(map->extent), map->width, map->height);
+  map->projection.gt.need_geotransform = MS_FALSE;
+  map->extent = map->saved_extent;
+  map->cellsize = msAdjustExtent(&(map->extent), map->width, map->height);
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 /************************************************************************/
@@ -521,207 +515,193 @@ int msMapRestoreRealExtent( mapObj *map )
 /************************************************************************/
 /* Returns the index at which the layer was inserted
  */
- 
-int msInsertLayer(mapObj *map, layerObj *layer, int nIndex) 
+
+int msInsertLayer(mapObj *map, layerObj *layer, int nIndex)
 {
-    if (!layer)
-    {
-        msSetError(MS_CHILDERR, "Can't insert a NULL Layer", "msInsertLayer()");
-        return -1;
-    }
+  if (!layer) {
+    msSetError(MS_CHILDERR, "Can't insert a NULL Layer", "msInsertLayer()");
+    return -1;
+  }
 
-    /* Ensure there is room for a new layer */
-    if (map->numlayers == map->maxlayers)
-              {
-                              if (msGrowMapLayers(map) == NULL)
-                                              return -1;
-              }
-
-              /* msGrowMapLayers allocates the new layer which we don't need to do since we have 1 that we are inserting 
-                              not sure if it is possible for this to be non null otherwise, but better to check since this function
-                              replaces the value */
-              if (map->layers[map->numlayers]!=NULL)
-                              free(map->layers[map->numlayers]);
-
-              /* Catch attempt to insert past end of layers array */
-              if (nIndex >= map->numlayers) {
-        msSetError(MS_CHILDERR, "Cannot insert layer beyond index %d",
-                   "msInsertLayer()", map->numlayers-1);
-        return -1;
-    }
-    else if (nIndex < 0) { /* Insert at the end by default */
-        map->layerorder[map->numlayers] = map->numlayers;
-        GET_LAYER(map, map->numlayers) = layer;
-        GET_LAYER(map, map->numlayers)->index = map->numlayers;
-	GET_LAYER(map, map->numlayers)->map = map;
-	MS_REFCNT_INCR(layer);
-        map->numlayers++;
-        return map->numlayers-1;
+  /* Ensure there is room for a new layer */
+  if (map->numlayers == map->maxlayers) {
+    if (msGrowMapLayers(map) == NULL)
+      return -1;
+  }
+
+  /* msGrowMapLayers allocates the new layer which we don't need to do since we have 1 that we are inserting
+                  not sure if it is possible for this to be non null otherwise, but better to check since this function
+                  replaces the value */
+  if (map->layers[map->numlayers]!=NULL)
+    free(map->layers[map->numlayers]);
+
+  /* Catch attempt to insert past end of layers array */
+  if (nIndex >= map->numlayers) {
+    msSetError(MS_CHILDERR, "Cannot insert layer beyond index %d",
+               "msInsertLayer()", map->numlayers-1);
+    return -1;
+  } else if (nIndex < 0) { /* Insert at the end by default */
+    map->layerorder[map->numlayers] = map->numlayers;
+    GET_LAYER(map, map->numlayers) = layer;
+    GET_LAYER(map, map->numlayers)->index = map->numlayers;
+    GET_LAYER(map, map->numlayers)->map = map;
+    MS_REFCNT_INCR(layer);
+    map->numlayers++;
+    return map->numlayers-1;
+  } else if (nIndex >= 0 && nIndex < map->numlayers) {
+    /* Move existing layers at the specified nIndex or greater */
+    /* to an index one higher */
+    int i;
+    for (i=map->numlayers; i>nIndex; i--) {
+      GET_LAYER(map, i)=GET_LAYER(map, i-1);
+      GET_LAYER(map, i)->index = i;
     }
-    else if (nIndex >= 0 && nIndex < map->numlayers) {
-        /* Move existing layers at the specified nIndex or greater */
-        /* to an index one higher */
-        int i;
-        for (i=map->numlayers; i>nIndex; i--) {
-	    GET_LAYER(map, i)=GET_LAYER(map, i-1);
-            GET_LAYER(map, i)->index = i;
-        }
 
-        /* assign new layer to specified index */
-	GET_LAYER(map, nIndex)=layer;
-        GET_LAYER(map, nIndex)->index = nIndex;
-	GET_LAYER(map, nIndex)->map = map;
+    /* assign new layer to specified index */
+    GET_LAYER(map, nIndex)=layer;
+    GET_LAYER(map, nIndex)->index = nIndex;
+    GET_LAYER(map, nIndex)->map = map;
 
-        /* adjust layers drawing order */
-        for (i=map->numlayers; i>nIndex; i--) {
-            map->layerorder[i] = map->layerorder[i-1];
-            if (map->layerorder[i] >= nIndex) map->layerorder[i]++;
-        }
-        for (i=0; i<nIndex; i++) {
-            if (map->layerorder[i] >= nIndex) map->layerorder[i]++;
-        }
-        map->layerorder[nIndex] = nIndex;
-        
-        /* increment number of layers and return */
-	MS_REFCNT_INCR(layer);
-        map->numlayers++;
-        return nIndex;
+    /* adjust layers drawing order */
+    for (i=map->numlayers; i>nIndex; i--) {
+      map->layerorder[i] = map->layerorder[i-1];
+      if (map->layerorder[i] >= nIndex) map->layerorder[i]++;
     }
-    else {
-        msSetError(MS_CHILDERR, "Invalid index", "msInsertLayer()");
-        return -1;
+    for (i=0; i<nIndex; i++) {
+      if (map->layerorder[i] >= nIndex) map->layerorder[i]++;
     }
+    map->layerorder[nIndex] = nIndex;
+
+    /* increment number of layers and return */
+    MS_REFCNT_INCR(layer);
+    map->numlayers++;
+    return nIndex;
+  } else {
+    msSetError(MS_CHILDERR, "Invalid index", "msInsertLayer()");
+    return -1;
+  }
 }
 
 /************************************************************************/
 /*                           msRemoveLayer()                            */
 /************************************************************************/
-layerObj *msRemoveLayer(mapObj *map, int nIndex) 
+layerObj *msRemoveLayer(mapObj *map, int nIndex)
 {
-    int i;
-    int order_index;
-    layerObj *layer;
-    
-    if (nIndex < 0 || nIndex >= map->numlayers) {
-        msSetError(MS_CHILDERR, "Cannot remove Layer, invalid index %d",
-                   "msRemoveLayer()", nIndex);
-        return NULL;
+  int i;
+  int order_index;
+  layerObj *layer;
+
+  if (nIndex < 0 || nIndex >= map->numlayers) {
+    msSetError(MS_CHILDERR, "Cannot remove Layer, invalid index %d",
+               "msRemoveLayer()", nIndex);
+    return NULL;
+  } else {
+    layer=GET_LAYER(map, nIndex);
+    /* msCopyLayer(layer, (GET_LAYER(map, nIndex))); */
+
+    /* Iteratively copy the higher index layers down one index */
+    for (i=nIndex; i<map->numlayers-1; i++) {
+      /* freeLayer((GET_LAYER(map, i))); */
+      /* initLayer((GET_LAYER(map, i)), map); */
+      /* msCopyLayer(GET_LAYER(map, i), GET_LAYER(map, i+1)); */
+      GET_LAYER(map, i)=GET_LAYER(map, i+1);
+      GET_LAYER(map, i)->index = i;
     }
-    else {
-    	layer=GET_LAYER(map, nIndex);
-        /* msCopyLayer(layer, (GET_LAYER(map, nIndex))); */
-        
-        /* Iteratively copy the higher index layers down one index */
-        for (i=nIndex; i<map->numlayers-1; i++) {
-            /* freeLayer((GET_LAYER(map, i))); */
-            /* initLayer((GET_LAYER(map, i)), map); */
-            /* msCopyLayer(GET_LAYER(map, i), GET_LAYER(map, i+1)); */
-	    GET_LAYER(map, i)=GET_LAYER(map, i+1);
-            GET_LAYER(map, i)->index = i;
-        }
-        /* Free the extra layer at the end */
-        /* freeLayer((GET_LAYER(map, map->numlayers-1))); */
-        GET_LAYER(map, map->numlayers-1)=NULL;
-        
-        /* Adjust drawing order */
-        order_index = 0;
-        for (i=0; i<map->numlayers; i++) {
-            if (map->layerorder[i] > nIndex) map->layerorder[i]--;
-            if (map->layerorder[i] == nIndex) {
-                order_index = i;
-                break;
-            }
-        }
-        for (i=order_index; i<map->numlayers-1; i++) {
-            map->layerorder[i] = map->layerorder[i+1];
-            if (map->layerorder[i] > nIndex) map->layerorder[i]--;
-        }
-        
-        /* decrement number of layers and return copy of removed layer */
-        map->numlayers--;
-	layer->map=NULL;
-	MS_REFCNT_DECR(layer);
-        return layer;
+    /* Free the extra layer at the end */
+    /* freeLayer((GET_LAYER(map, map->numlayers-1))); */
+    GET_LAYER(map, map->numlayers-1)=NULL;
+
+    /* Adjust drawing order */
+    order_index = 0;
+    for (i=0; i<map->numlayers; i++) {
+      if (map->layerorder[i] > nIndex) map->layerorder[i]--;
+      if (map->layerorder[i] == nIndex) {
+        order_index = i;
+        break;
+      }
     }
+    for (i=order_index; i<map->numlayers-1; i++) {
+      map->layerorder[i] = map->layerorder[i+1];
+      if (map->layerorder[i] > nIndex) map->layerorder[i]--;
+    }
+
+    /* decrement number of layers and return copy of removed layer */
+    map->numlayers--;
+    layer->map=NULL;
+    MS_REFCNT_DECR(layer);
+    return layer;
+  }
 }
 
 /*
 ** Move the layer's order for drawing purpose. Moving it up here
-** will have the effect of drawing the layer earlier. 
+** will have the effect of drawing the layer earlier.
 */
 int msMoveLayerUp(mapObj *map, int nLayerIndex)
 {
-    int iCurrentIndex = -1;
-    int i = 0;
-    if (map && nLayerIndex < map->numlayers && nLayerIndex >=0)
-    {
-        for (i=0; i<map->numlayers; i++)
-        {
-            if ( map->layerorder[i] == nLayerIndex)
-            {
-                iCurrentIndex = i;
-                break;
-            }
-        }
-        if (iCurrentIndex >=0) 
-        {
-            /* we do not need to promote if it is the first one. */
-            if (iCurrentIndex == 0)
-                return MS_FAILURE;
+  int iCurrentIndex = -1;
+  int i = 0;
+  if (map && nLayerIndex < map->numlayers && nLayerIndex >=0) {
+    for (i=0; i<map->numlayers; i++) {
+      if ( map->layerorder[i] == nLayerIndex) {
+        iCurrentIndex = i;
+        break;
+      }
+    }
+    if (iCurrentIndex >=0) {
+      /* we do not need to promote if it is the first one. */
+      if (iCurrentIndex == 0)
+        return MS_FAILURE;
 
-            map->layerorder[iCurrentIndex] =  
-                map->layerorder[iCurrentIndex-1];
-            map->layerorder[iCurrentIndex-1] = nLayerIndex;
+      map->layerorder[iCurrentIndex] =
+        map->layerorder[iCurrentIndex-1];
+      map->layerorder[iCurrentIndex-1] = nLayerIndex;
 
-            return MS_SUCCESS;
-        }
+      return MS_SUCCESS;
     }
-    msSetError(MS_CHILDERR, "Invalid index: %d", "msMoveLayerUp()",
-               nLayerIndex);
-    return MS_FAILURE;
+  }
+  msSetError(MS_CHILDERR, "Invalid index: %d", "msMoveLayerUp()",
+             nLayerIndex);
+  return MS_FAILURE;
 }
 
 /*
 ** Move the layer's order for drawing purpose. Moving it down here
-** will have the effect of drawing the layer later. 
+** will have the effect of drawing the layer later.
 */
 int msMoveLayerDown(mapObj *map, int nLayerIndex)
 {
-    int iCurrentIndex = -1;
-    int i = 0;
-    if (map && nLayerIndex < map->numlayers && nLayerIndex >=0)
-    {
-        for (i=0; i<map->numlayers; i++)
-        {
-            if ( map->layerorder[i] == nLayerIndex)
-            {
-                iCurrentIndex = i;
-                break;
-            }
-        }
-        if (iCurrentIndex >=0) 
-        {
-            /* we do not need to demote if it is the last one. */
-            if (iCurrentIndex == map->numlayers-1)
-                return MS_FAILURE;
+  int iCurrentIndex = -1;
+  int i = 0;
+  if (map && nLayerIndex < map->numlayers && nLayerIndex >=0) {
+    for (i=0; i<map->numlayers; i++) {
+      if ( map->layerorder[i] == nLayerIndex) {
+        iCurrentIndex = i;
+        break;
+      }
+    }
+    if (iCurrentIndex >=0) {
+      /* we do not need to demote if it is the last one. */
+      if (iCurrentIndex == map->numlayers-1)
+        return MS_FAILURE;
 
-            map->layerorder[iCurrentIndex] =  
-                map->layerorder[iCurrentIndex+1];
-            map->layerorder[iCurrentIndex+1] = nLayerIndex;
+      map->layerorder[iCurrentIndex] =
+        map->layerorder[iCurrentIndex+1];
+      map->layerorder[iCurrentIndex+1] = nLayerIndex;
 
-            return MS_SUCCESS;
-        }
+      return MS_SUCCESS;
     }
-    msSetError(MS_CHILDERR, "Invalid index: %d", "msMoveLayerDown()",
-               nLayerIndex);
-    return MS_FAILURE;
+  }
+  msSetError(MS_CHILDERR, "Invalid index: %d", "msMoveLayerDown()",
+             nLayerIndex);
+  return MS_FAILURE;
 }
 
 
 /*
 ** Set the array used for the drawing order. The array passed must contain
 ** all the layer's index ordered by the drawing priority.
-** Ex : for 3 layers in the map file, if 
+** Ex : for 3 layers in the map file, if
 **                          panIndexes[0] = 2
 **                          panIndexes[1] = 0
 **                          panIndexes[2] = 1
@@ -734,43 +714,38 @@ int msMoveLayerDown(mapObj *map, int nLayerIndex)
 */
 int msSetLayersdrawingOrder(mapObj *self, int *panIndexes)
 {
-    int nElements = 0;
-    int i, j = 0;
-    int bFound = 0;
-
-    if (self && panIndexes)
-    {
-        nElements = self->numlayers;
-        for (i=0; i<nElements; i++)
-        {
-            bFound = 0;
-            for (j=0; j<nElements; j++)
-            {
-                if (panIndexes[j] == i)
-                {
-                    bFound = 1;
-                    break;
-                }
-            }
-            if (!bFound)
-                return 0;
+  int nElements = 0;
+  int i, j = 0;
+  int bFound = 0;
+
+  if (self && panIndexes) {
+    nElements = self->numlayers;
+    for (i=0; i<nElements; i++) {
+      bFound = 0;
+      for (j=0; j<nElements; j++) {
+        if (panIndexes[j] == i) {
+          bFound = 1;
+          break;
         }
-/* -------------------------------------------------------------------- */
-/*    At this point the array is valid so update the layers order array.*/
-/* -------------------------------------------------------------------- */
-        for (i=0; i<nElements; i++)
-        {
-            self->layerorder[i] = panIndexes[i];
-        }
-        return 1;
+      }
+      if (!bFound)
+        return 0;
+    }
+    /* -------------------------------------------------------------------- */
+    /*    At this point the array is valid so update the layers order array.*/
+    /* -------------------------------------------------------------------- */
+    for (i=0; i<nElements; i++) {
+      self->layerorder[i] = panIndexes[i];
     }
-    return 0;
+    return 1;
+  }
+  return 0;
 }
 
 
 /* =========================================================================
    msMapLoadOWSParameters
-   
+
    Function to support mapscript mapObj::loadOWSParameters
    ========================================================================= */
 
@@ -778,41 +753,40 @@ int msMapLoadOWSParameters(mapObj *map, cgiRequestObj *request,
                            const char *wmtver)
 {
 #ifdef USE_WMS_SVR
-    int version;
-    char *wms_exception_format = NULL;
-    const char *wms_request= NULL;
-    int result, i = 0;
-    owsRequestObj ows_request;
+  int version;
+  char *wms_exception_format = NULL;
+  const char *wms_request= NULL;
+  int result, i = 0;
+  owsRequestObj ows_request;
 
-    ows_request.numlayers = 0;
-    ows_request.enabled_layers = NULL;
+  ows_request.numlayers = 0;
+  ows_request.enabled_layers = NULL;
 
 
-    version = msOWSParseVersionString(wmtver);
-     for(i=0; i<request->NumParams; i++) 
-     {
-         if (strcasecmp(request->ParamNames[i], "EXCEPTIONS") == 0)
-           wms_exception_format = request->ParamValues[i];
-         else if (strcasecmp(request->ParamNames[i], "REQUEST") == 0)
-             wms_request = request->ParamValues[i];
+  version = msOWSParseVersionString(wmtver);
+  for(i=0; i<request->NumParams; i++) {
+    if (strcasecmp(request->ParamNames[i], "EXCEPTIONS") == 0)
+      wms_exception_format = request->ParamValues[i];
+    else if (strcasecmp(request->ParamNames[i], "REQUEST") == 0)
+      wms_request = request->ParamValues[i];
 
-     }
+  }
 
-     msOWSRequestLayersEnabled(map, "M", wms_request, &ows_request);
+  msOWSRequestLayersEnabled(map, "M", wms_request, &ows_request);
 
-     result = msWMSLoadGetMapParams(map, version, request->ParamNames,
-				    request->ParamValues, request->NumParams,  wms_exception_format, 
-				    wms_request, &ows_request);
+  result = msWMSLoadGetMapParams(map, version, request->ParamNames,
+                                 request->ParamValues, request->NumParams,  wms_exception_format,
+                                 wms_request, &ows_request);
 
-     if (ows_request.numlayers > 0)
-       msFree(ows_request.enabled_layers);
+  if (ows_request.numlayers > 0)
+    msFree(ows_request.enabled_layers);
 
-     return result;
+  return result;
 
 #else
-    msSetError(MS_WMSERR, "WMS server support is not available.",
-               "msMapLoadOWSParameters()");
-    return MS_FAILURE;
+  msSetError(MS_WMSERR, "WMS server support is not available.",
+             "msMapLoadOWSParameters()");
+  return MS_FAILURE;
 #endif
 }
 
diff --git a/mapogcfilter.c b/mapogcfilter.c
index 8bbc8e6..940fac0 100644
--- a/mapogcfilter.c
+++ b/mapogcfilter.c
@@ -14,16 +14,16 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
+ *
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  ****************************************************************************/
 
 
@@ -31,237 +31,445 @@
 
 #ifdef USE_OGR
 #include "cpl_minixml.h"
+#include "cpl_string.h"
 #endif
 
 #include "mapogcfilter.h"
 #include "mapserver.h"
 #include "mapowscommon.h"
 
-MS_CVSID("$Id$")
 
-#ifdef USE_OGR
+
 
 int FLTIsNumeric(char *pszValue)
 {
-    if (pszValue)
-    {
-          /*the regex seems to have a problem on windows when mapserver is built using
-            PHP regex*/
+  if (pszValue != NULL && *pszValue != '\0' && !isspace(*pszValue)) {
+    /*the regex seems to have a problem on windows when mapserver is built using
+      PHP regex*/
 #if defined(_WIN32) && !defined(__CYGWIN__)
-        int i = 0, nLength=0, bString=0;
+    int i = 0, nLength=0, bString=0;
 
-        nLength = strlen(pszValue);
-        for (i=0; i<nLength; i++)
-        {
-            if (i == 0)
-            {
-                if (!isdigit(pszValue[i]) &&  pszValue[i] != '-')
-                {
-                     bString = 1;
-                     break;
-                }
-            }
-            else if (!isdigit(pszValue[i]) &&  pszValue[i] != '.')
-            {
-                bString = 1;
-                break;
-            }
+    nLength = strlen(pszValue);
+    for (i=0; i<nLength; i++) {
+      if (i == 0) {
+        if (!isdigit(pszValue[i]) &&  pszValue[i] != '-') {
+          bString = 1;
+          break;
         }
-        if (!bString)
-          return MS_TRUE;
+      } else if (!isdigit(pszValue[i]) &&  pszValue[i] != '.') {
+        bString = 1;
+        break;
+      }
+    }
+    if (!bString)
+      return MS_TRUE;
 #else
-        if (msEvalRegex("^[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?$", pszValue) == MS_TRUE)
-          return MS_TRUE;
+    char * p;
+    strtod (pszValue, &p);
+    if (*p == '\0') return MS_TRUE;
 #endif
-    }
+  }
 
-    return MS_FALSE;
+  return MS_FALSE;
 }
 
-int FLTogrConvertGeometry(OGRGeometryH hGeometry, shapeObj *psShape,
-                          OGRwkbGeometryType nType) 
+/*
+** Apply an expression to the layer's filter element.
+**
+*/
+int FLTApplyExpressionToLayer(layerObj *lp, char *pszExpression)
 {
-    return msOGRGeometryToShape(hGeometry, psShape, nType);
+  char *pszFinalExpression=NULL, *pszBuffer = NULL;
+  /*char *escapedTextString=NULL;*/
+  int bConcatWhere=0, bHasAWhere=0;
+
+  if (lp && pszExpression) {
+    if (lp->connectiontype == MS_POSTGIS || lp->connectiontype ==  MS_ORACLESPATIAL ||
+        lp->connectiontype == MS_SDE || lp->connectiontype == MS_PLUGIN) {
+      pszFinalExpression = msStrdup("(");
+      pszFinalExpression = msStringConcatenate(pszFinalExpression, pszExpression);
+      pszFinalExpression = msStringConcatenate(pszFinalExpression, ")");
+    } else if (lp->connectiontype == MS_OGR) {
+      pszFinalExpression = msStrdup(pszExpression);
+      if (lp->filter.type != MS_EXPRESSION) {
+        bConcatWhere = 1;
+      } else {
+        if (lp->filter.string && EQUALN(lp->filter.string,"WHERE ",6)) {
+          bHasAWhere = 1;
+          bConcatWhere =1;
+        }
+      }
+
+    } else
+      pszFinalExpression = msStrdup(pszExpression);
+
+    if (bConcatWhere)
+      pszBuffer = msStringConcatenate(pszBuffer, "WHERE ");
+    /* if the filter is set and it's an expression type, concatenate it with
+                this filter. If not just free it */
+    if (lp->filter.string && lp->filter.type == MS_EXPRESSION) {
+      pszBuffer = msStringConcatenate(pszBuffer, "((");
+      if (bHasAWhere)
+        pszBuffer = msStringConcatenate(pszBuffer, lp->filter.string+6);
+      else
+        pszBuffer = msStringConcatenate(pszBuffer, lp->filter.string);
+      pszBuffer = msStringConcatenate(pszBuffer, ") and ");
+    } else if (lp->filter.string)
+      freeExpression(&lp->filter);
+
+    pszBuffer = msStringConcatenate(pszBuffer, pszFinalExpression);
+
+    if(lp->filter.string && lp->filter.type == MS_EXPRESSION)
+      pszBuffer = msStringConcatenate(pszBuffer, ")");
+
+    /*assuming that expression was properly escaped
+          escapedTextString = msStringEscape(pszBuffer);
+          msLoadExpressionString(&lp->filter,
+                                 (char*)CPLSPrintf("%s", escapedTextString));
+          msFree(escapedTextString);
+    */
+    msLoadExpressionString(&lp->filter, pszBuffer);
+
+
+    msFree(pszFinalExpression);
+
+    if (pszBuffer)
+      msFree(pszBuffer);
+
+    return MS_TRUE;
+  }
+
+  return MS_FALSE;
 }
 
-int FLTShapeFromGMLTree(CPLXMLNode *psTree, shapeObj *psShape , char **ppszSRS)
+char *FLTGetExpressionForValuesRanges(layerObj *lp, char *item, char *value,  int forcecharcter)
 {
-    char *pszSRS = NULL;
-    if (psTree && psShape)
-    {
-        CPLXMLNode *psNext = psTree->psNext;
-        OGRGeometryH hGeometry = NULL;
+  int bIscharacter, bSqlLayer;
+  char *pszExpression = NULL, *pszEscapedStr=NULL, *pszTmpExpression=NULL;
+  char **paszElements = NULL, **papszRangeElements=NULL;
+  int numelements,i,nrangeelements;
+  /* double minval, maxval; */
+  if (lp && item && value) {
+    if (lp->connectiontype == MS_POSTGIS || lp->connectiontype ==  MS_ORACLESPATIAL ||
+        lp->connectiontype == MS_SDE || lp->connectiontype == MS_PLUGIN)
+      bSqlLayer = MS_TRUE;
+    else
+      bSqlLayer = MS_FALSE;
+
+    if (strstr(value, "/") == NULL) {
+      /*value(s)*/
+      paszElements = msStringSplit (value, ',', &numelements);
+      if (paszElements && numelements > 0) {
+        if (forcecharcter)
+          bIscharacter = MS_TRUE;
+        bIscharacter= !FLTIsNumeric(paszElements[0]);
+
+        pszTmpExpression = msStringConcatenate(pszTmpExpression, "(");
+        for (i=0; i<numelements; i++) {
+          pszTmpExpression = msStringConcatenate(pszTmpExpression, "(");
+          if (bSqlLayer)
+            pszTmpExpression = msStringConcatenate(pszTmpExpression, item);
+          else {
+            if (bIscharacter)
+              pszTmpExpression = msStringConcatenate(pszTmpExpression, "\"");
+            pszTmpExpression = msStringConcatenate(pszTmpExpression, "[");
+            pszTmpExpression = msStringConcatenate(pszTmpExpression, item);
+            pszTmpExpression = msStringConcatenate(pszTmpExpression, "]");
+            if (bIscharacter)
+              pszTmpExpression = msStringConcatenate(pszTmpExpression, "\"");
+          }
+          if (bIscharacter) {
+            if (bSqlLayer)
+              pszTmpExpression = msStringConcatenate(pszTmpExpression, " = '");
+            else
+              pszTmpExpression = msStringConcatenate(pszTmpExpression, " = \"");
+          } else
+            pszTmpExpression = msStringConcatenate(pszTmpExpression, " = ");
 
-        psTree->psNext = NULL;
-        hGeometry = OGR_G_CreateFromGMLTree(psTree );
-        psTree->psNext = psNext;
+          pszEscapedStr = msLayerEscapeSQLParam(lp, paszElements[i]);
+          pszTmpExpression = msStringConcatenate(pszTmpExpression, pszEscapedStr);
 
-        if (hGeometry)
-        {
-            OGRwkbGeometryType nType;
-            nType = OGR_G_GetGeometryType(hGeometry);
-            if (nType == wkbPolygon25D || nType == wkbMultiPolygon25D)
-              nType = wkbPolygon;
-            else if (nType == wkbLineString25D || nType == wkbMultiLineString25D)
-              nType = wkbLineString;
-            else if (nType == wkbPoint25D  || nType ==  wkbMultiPoint25D)
-              nType = wkbPoint;
-            FLTogrConvertGeometry(hGeometry, psShape, nType);
-
-            OGR_G_DestroyGeometry(hGeometry);
+          if (bIscharacter) {
+            if (bSqlLayer)
+              pszTmpExpression = msStringConcatenate(pszTmpExpression, "'");
+            else
+              pszTmpExpression = msStringConcatenate(pszTmpExpression, "\"");
+          }
+          pszTmpExpression = msStringConcatenate(pszTmpExpression, ")");
+
+          msFree(pszEscapedStr);
+          pszEscapedStr=NULL;
+
+          if (pszExpression != NULL)
+            pszExpression = msStringConcatenate(pszExpression, " OR ");
+
+          pszExpression =  msStringConcatenate(pszExpression, pszTmpExpression);
+
+          msFree(pszTmpExpression);
+          pszTmpExpression = NULL;
         }
+        pszExpression = msStringConcatenate(pszExpression, ")");
+        msFreeCharArray(paszElements, numelements);
+      }
+    } else {
+      /*range(s)*/
+      paszElements = msStringSplit (value, ',', &numelements);
+      if (paszElements && numelements > 0) {
+        pszTmpExpression = msStringConcatenate(pszTmpExpression, "(");
+        for (i=0; i<numelements; i++) {
+          papszRangeElements = msStringSplit (paszElements[i], '/', &nrangeelements);
+          if (papszRangeElements && nrangeelements > 0) {
+            pszTmpExpression = msStringConcatenate(pszTmpExpression, "(");
+            if (nrangeelements == 2 || nrangeelements == 3) {
+              /*
+              minval = atof(papszRangeElements[0]);
+              maxval = atof(papszRangeElements[1]);
+              */
+              if (bSqlLayer)
+                pszTmpExpression = msStringConcatenate(pszTmpExpression, item);
+              else {
+                pszTmpExpression = msStringConcatenate(pszTmpExpression, "[");
+                pszTmpExpression = msStringConcatenate(pszTmpExpression, item);
+                pszTmpExpression = msStringConcatenate(pszTmpExpression, "]");
+              }
+
+              pszTmpExpression = msStringConcatenate(pszTmpExpression, " >= ");
+
+              pszEscapedStr = msLayerEscapeSQLParam(lp, papszRangeElements[0]);
+              pszTmpExpression = msStringConcatenate(pszTmpExpression, pszEscapedStr);
+              msFree(pszEscapedStr);
+              pszEscapedStr=NULL;
+
+              pszTmpExpression = msStringConcatenate(pszTmpExpression, " AND ");
+
+              if (bSqlLayer)
+                pszTmpExpression = msStringConcatenate(pszTmpExpression, item);
+              else {
+                pszTmpExpression = msStringConcatenate(pszTmpExpression, "[");
+                pszTmpExpression = msStringConcatenate(pszTmpExpression, item);
+                pszTmpExpression = msStringConcatenate(pszTmpExpression, "]");
+              }
+
+              pszTmpExpression = msStringConcatenate(pszTmpExpression, " <= ");
+
+              pszEscapedStr = msLayerEscapeSQLParam(lp, papszRangeElements[1]);
+              pszTmpExpression = msStringConcatenate(pszTmpExpression, pszEscapedStr);
+              msFree(pszEscapedStr);
+              pszEscapedStr=NULL;
+
+              pszTmpExpression = msStringConcatenate(pszTmpExpression, ")");
+            } else if (nrangeelements == 1) {
+              pszTmpExpression = msStringConcatenate(pszTmpExpression, "(");
+              if (bSqlLayer)
+                pszTmpExpression = msStringConcatenate(pszTmpExpression, item);
+              else {
+                pszTmpExpression = msStringConcatenate(pszTmpExpression, "[");
+                pszTmpExpression = msStringConcatenate(pszTmpExpression, item);
+                pszTmpExpression = msStringConcatenate(pszTmpExpression, "]");
+              }
+
+              pszTmpExpression = msStringConcatenate(pszTmpExpression, " = ");
+
+              pszEscapedStr = msLayerEscapeSQLParam(lp, papszRangeElements[0]);
+              pszTmpExpression = msStringConcatenate(pszTmpExpression, pszEscapedStr);
+              msFree(pszEscapedStr);
+              pszEscapedStr=NULL;
+
+              pszTmpExpression = msStringConcatenate(pszTmpExpression, ")");
+            }
 
-        pszSRS = (char *)CPLGetXMLValue(psTree, "srsName", NULL);
-        if (ppszSRS && pszSRS)
-          *ppszSRS = msStrdup(pszSRS);
+            if (pszExpression != NULL)
+              pszExpression = msStringConcatenate(pszExpression, " OR ");
 
-        return MS_TRUE;
+            pszExpression =  msStringConcatenate(pszExpression, pszTmpExpression);
+            msFree(pszTmpExpression);
+            pszTmpExpression = NULL;
+
+            msFreeCharArray(papszRangeElements, nrangeelements);
+          }
+        }
+        pszExpression = msStringConcatenate(pszExpression, ")");
+        msFreeCharArray(paszElements, numelements);
+      }
     }
+  }
+  return pszExpression;
+}
 
-    return MS_FALSE;
+#ifdef USE_OGR
+
+
+int FLTogrConvertGeometry(OGRGeometryH hGeometry, shapeObj *psShape,
+                          OGRwkbGeometryType nType)
+{
+  return msOGRGeometryToShape(hGeometry, psShape, nType);
 }
 
-int FLTGetGeosOperator(char *pszValue)
+int FLTShapeFromGMLTree(CPLXMLNode *psTree, shapeObj *psShape , char **ppszSRS)
 {
-    if (!pszValue)
-      return -1;
-
-    if (strcasecmp(pszValue, "Equals") == 0)
-      return MS_GEOS_EQUALS;
-    else if (strcasecmp(pszValue, "Intersect") == 0 ||
-             strcasecmp(pszValue, "Intersects") == 0)
-      return MS_GEOS_INTERSECTS;
-    else if (strcasecmp(pszValue, "Disjoint") == 0)
-      return MS_GEOS_DISJOINT;
-     else if (strcasecmp(pszValue, "Touches") == 0)
-      return MS_GEOS_TOUCHES;
-     else if (strcasecmp(pszValue, "Crosses") == 0)
-      return MS_GEOS_CROSSES;
-     else if (strcasecmp(pszValue, "Within") == 0)
-      return MS_GEOS_WITHIN;
-     else if (strcasecmp(pszValue, "Contains") == 0)
-      return MS_GEOS_CONTAINS;
-     else if (strcasecmp(pszValue, "Overlaps") == 0)
-      return MS_GEOS_OVERLAPS;
-     else if (strcasecmp(pszValue, "Beyond") == 0)
-      return MS_GEOS_BEYOND;
-    else if (strcasecmp(pszValue, "DWithin") == 0)
-      return MS_GEOS_DWITHIN;
+  char *pszSRS = NULL;
+  if (psTree && psShape) {
+    CPLXMLNode *psNext = psTree->psNext;
+    OGRGeometryH hGeometry = NULL;
+
+    psTree->psNext = NULL;
+    hGeometry = OGR_G_CreateFromGMLTree(psTree );
+    psTree->psNext = psNext;
+
+    if (hGeometry) {
+      OGRwkbGeometryType nType;
+      nType = OGR_G_GetGeometryType(hGeometry);
+      if (nType == wkbPolygon25D || nType == wkbMultiPolygon25D)
+        nType = wkbPolygon;
+      else if (nType == wkbLineString25D || nType == wkbMultiLineString25D)
+        nType = wkbLineString;
+      else if (nType == wkbPoint25D  || nType ==  wkbMultiPoint25D)
+        nType = wkbPoint;
+      FLTogrConvertGeometry(hGeometry, psShape, nType);
 
+      OGR_G_DestroyGeometry(hGeometry);
+    }
+
+    pszSRS = (char *)CPLGetXMLValue(psTree, "srsName", NULL);
+    if (ppszSRS && pszSRS)
+      *ppszSRS = msStrdup(pszSRS);
+
+    return MS_TRUE;
+  }
+
+  return MS_FALSE;
+}
+
+int FLTGetGeosOperator(char *pszValue)
+{
+  if (!pszValue)
     return -1;
+
+  if (strcasecmp(pszValue, "Equals") == 0)
+    return MS_GEOS_EQUALS;
+  else if (strcasecmp(pszValue, "Intersect") == 0 ||
+           strcasecmp(pszValue, "Intersects") == 0)
+    return MS_GEOS_INTERSECTS;
+  else if (strcasecmp(pszValue, "Disjoint") == 0)
+    return MS_GEOS_DISJOINT;
+  else if (strcasecmp(pszValue, "Touches") == 0)
+    return MS_GEOS_TOUCHES;
+  else if (strcasecmp(pszValue, "Crosses") == 0)
+    return MS_GEOS_CROSSES;
+  else if (strcasecmp(pszValue, "Within") == 0)
+    return MS_GEOS_WITHIN;
+  else if (strcasecmp(pszValue, "Contains") == 0)
+    return MS_GEOS_CONTAINS;
+  else if (strcasecmp(pszValue, "Overlaps") == 0)
+    return MS_GEOS_OVERLAPS;
+  else if (strcasecmp(pszValue, "Beyond") == 0)
+    return MS_GEOS_BEYOND;
+  else if (strcasecmp(pszValue, "DWithin") == 0)
+    return MS_GEOS_DWITHIN;
+
+  return -1;
 }
 
 int FLTIsGeosNode(char *pszValue)
 {
-    if (FLTGetGeosOperator(pszValue) == -1)
-      return MS_FALSE;
+  if (FLTGetGeosOperator(pszValue) == -1)
+    return MS_FALSE;
 
-    return MS_TRUE;
+  return MS_TRUE;
 }
 
 int FLTParseEpsgString(char *pszEpsg, projectionObj *psProj)
 {
-    int nStatus = MS_FALSE;
-    int nTokens = 0;
-    char **tokens = NULL;
-    int nEpsgTmp=0;
-    size_t bufferSize = 0;
+  int nStatus = MS_FALSE;
+  int nTokens = 0;
+  char **tokens = NULL;
+  int nEpsgTmp=0;
+  size_t bufferSize = 0;
 
 #ifdef USE_PROJ
-    if (pszEpsg && psProj)
-    {
-        nTokens = 0;
-        tokens = msStringSplit(pszEpsg,'#', &nTokens);
-        if (tokens && nTokens == 2)
-        {
-            char *szTmp;
-            bufferSize = 10+strlen(tokens[1])+1;
-            szTmp = (char *)malloc(bufferSize);
-            snprintf(szTmp, bufferSize, "init=epsg:%s", tokens[1]);
-            msInitProjection(psProj);
-            if (msLoadProjectionString(psProj, szTmp) == 0)
-              nStatus = MS_TRUE;
-            free(szTmp);
-        }
-        else if (tokens &&  nTokens == 1)
-        {
-            if (tokens)
-              msFreeCharArray(tokens, nTokens);
-            nTokens = 0;
-
-            tokens = msStringSplit(pszEpsg,':', &nTokens);
-            nEpsgTmp = -1;
-            if (tokens &&  nTokens == 1)
-            {
-                nEpsgTmp = atoi(tokens[0]);
-                
-            }
-            else if (tokens &&  nTokens == 2)
-            {
-                nEpsgTmp = atoi(tokens[1]);
-            }
-            if (nEpsgTmp > 0)
-            {
-                char szTmp[32];
-                snprintf(szTmp, sizeof(szTmp), "init=epsg:%d",nEpsgTmp);
-                msInitProjection(psProj);
-                if (msLoadProjectionString(psProj, szTmp) == 0)
-                  nStatus = MS_TRUE;
-            }
-        }
-        if (tokens)
-          msFreeCharArray(tokens, nTokens);
+  if (pszEpsg && psProj) {
+    nTokens = 0;
+    tokens = msStringSplit(pszEpsg,'#', &nTokens);
+    if (tokens && nTokens == 2) {
+      char *szTmp;
+      bufferSize = 10+strlen(tokens[1])+1;
+      szTmp = (char *)malloc(bufferSize);
+      snprintf(szTmp, bufferSize, "init=epsg:%s", tokens[1]);
+      msInitProjection(psProj);
+      if (msLoadProjectionString(psProj, szTmp) == 0)
+        nStatus = MS_TRUE;
+      free(szTmp);
+    } else if (tokens &&  nTokens == 1) {
+      if (tokens)
+        msFreeCharArray(tokens, nTokens);
+      nTokens = 0;
+
+      tokens = msStringSplit(pszEpsg,':', &nTokens);
+      nEpsgTmp = -1;
+      if (tokens &&  nTokens == 1) {
+        nEpsgTmp = atoi(tokens[0]);
+
+      } else if (tokens &&  nTokens == 2) {
+        nEpsgTmp = atoi(tokens[1]);
+      }
+      if (nEpsgTmp > 0) {
+        char szTmp[32];
+        snprintf(szTmp, sizeof(szTmp), "init=epsg:%d",nEpsgTmp);
+        msInitProjection(psProj);
+        if (msLoadProjectionString(psProj, szTmp) == 0)
+          nStatus = MS_TRUE;
+      }
     }
+    if (tokens)
+      msFreeCharArray(tokens, nTokens);
+  }
 #endif
-    return nStatus;
+  return nStatus;
 }
-    
 
- 
+
+
 int FLTGML2Shape_XMLNode(CPLXMLNode *psNode, shapeObj *psShp)
 {
-    lineObj line={0,NULL};
-    CPLXMLNode *psCoordinates = NULL;
-    char *pszTmpCoord = NULL;
-    char **szCoords = NULL;
-    int nCoords = 0;
-
-
-    if (!psNode || !psShp)
-      return MS_FALSE;
-
-    
-    if( strcasecmp(psNode->pszValue,"PointType") == 0
-        || strcasecmp(psNode->pszValue,"Point") == 0)
-    {
-        psCoordinates = CPLGetXMLNode(psNode, "coordinates");
-        
-        if (psCoordinates && psCoordinates->psChild && 
-            psCoordinates->psChild->pszValue)
-        {
-            pszTmpCoord = psCoordinates->psChild->pszValue;
-            szCoords = msStringSplit(pszTmpCoord, ',', &nCoords);
-            if (szCoords && nCoords >= 2)
-            {
-                line.numpoints = 1;
-                line.point = (pointObj *)malloc(sizeof(pointObj));
-                line.point[0].x = atof(szCoords[0]);
-                line.point[0].y =  atof(szCoords[1]);
+  lineObj line= {0,NULL};
+  CPLXMLNode *psCoordinates = NULL;
+  char *pszTmpCoord = NULL;
+  char **szCoords = NULL;
+  int nCoords = 0;
+
+
+  if (!psNode || !psShp)
+    return MS_FALSE;
+
+
+  if( strcasecmp(psNode->pszValue,"PointType") == 0
+      || strcasecmp(psNode->pszValue,"Point") == 0) {
+    psCoordinates = CPLGetXMLNode(psNode, "coordinates");
+
+    if (psCoordinates && psCoordinates->psChild &&
+        psCoordinates->psChild->pszValue) {
+      pszTmpCoord = psCoordinates->psChild->pszValue;
+      szCoords = msStringSplit(pszTmpCoord, ',', &nCoords);
+      if (szCoords && nCoords >= 2) {
+        line.numpoints = 1;
+        line.point = (pointObj *)malloc(sizeof(pointObj));
+        line.point[0].x = atof(szCoords[0]);
+        line.point[0].y =  atof(szCoords[1]);
 #ifdef USE_POINT_Z_M
-                line.point[0].m = 0;
+        line.point[0].m = 0;
 #endif
 
-                psShp->type = MS_SHAPE_POINT;
+        psShp->type = MS_SHAPE_POINT;
 
-                msAddLine(psShp, &line);
-                free(line.point);
+        msAddLine(psShp, &line);
+        free(line.point);
 
-                return MS_TRUE;
-            }
-        }
+        return MS_TRUE;
+      }
     }
-    
-    return MS_FALSE;
+  }
+
+  return MS_FALSE;
 }
 
 
@@ -274,247 +482,218 @@ int FLTGML2Shape_XMLNode(CPLXMLNode *psNode, shapeObj *psShp)
 /************************************************************************/
 int FLTIsSimpleFilterNoSpatial(FilterEncodingNode *psNode)
 {
-    if (FLTIsSimpleFilter(psNode) &&
-        FLTNumberOfFilterType(psNode, "BBOX") == 0)
-      return MS_TRUE;
+  if (FLTIsSimpleFilter(psNode) &&
+      FLTNumberOfFilterType(psNode, "BBOX") == 0)
+    return MS_TRUE;
 
-    return MS_FALSE;
+  return MS_FALSE;
 }
 
 
+
+
 /************************************************************************/
 /*                      FLTApplySimpleSQLFilter()                       */
 /************************************************************************/
 
-int FLTApplySimpleSQLFilter(FilterEncodingNode *psNode, mapObj *map, 
-                             int iLayerIndex)
+int FLTApplySimpleSQLFilter(FilterEncodingNode *psNode, mapObj *map,
+                            int iLayerIndex)
 {
-    layerObj *lp = NULL;
-    char *szExpression = NULL;
-    rectObj sQueryRect = map->extent;
-    char *szEPSG = NULL;
-    char **tokens = NULL;
-    int nTokens = 0, nEpsgTmp = 0;
-    projectionObj sProjTmp;
-    char *pszBuffer = NULL;
-    int bConcatWhere = 0;
-    int bHasAWhere =0;
-    char *pszTmp = NULL, *pszTmp2 = NULL;
-    size_t bufferSize = 0;
-    char *tmpfilename = NULL;
-
-    lp = (GET_LAYER(map, iLayerIndex));
-
-    /* if there is a bbox use it */
-    szEPSG = FLTGetBBOX(psNode, &sQueryRect);
-    if(szEPSG && map->projection.numargs > 0)
-    {
+  layerObj *lp = NULL;
+  char *szExpression = NULL;
+  rectObj sQueryRect = map->extent;
+  char *szEPSG = NULL;
+  char **tokens = NULL;
+  int nTokens = 0, nEpsgTmp = 0;
+  projectionObj sProjTmp;
+  char *pszBuffer = NULL;
+  int bConcatWhere = 0;
+  int bHasAWhere =0;
+  char *pszTmp = NULL, *pszTmp2 = NULL;
+  size_t bufferSize = 0;
+  char *tmpfilename = NULL;
+
+  lp = (GET_LAYER(map, iLayerIndex));
+
+  /* if there is a bbox use it */
+  szEPSG = FLTGetBBOX(psNode, &sQueryRect);
+  if(szEPSG && map->projection.numargs > 0) {
 #ifdef USE_PROJ
-        nTokens = 0;
-        tokens = msStringSplit(szEPSG,'#', &nTokens);
-        if (tokens && nTokens == 2)
-        {
-            char *szTmp;
-            bufferSize = 10+strlen(tokens[1])+1;
-            szTmp = (char *)malloc(bufferSize);
-            snprintf(szTmp, bufferSize, "init=epsg:%s",tokens[1]);
-            msInitProjection(&sProjTmp);
-            if (msLoadProjectionString(&sProjTmp, szTmp) == 0)
-              msProjectRect(&sProjTmp, &map->projection,  &sQueryRect);
-            free(szTmp);
-        }
-        else if (tokens &&  nTokens == 1)
-        {
-            if (tokens)
-              msFreeCharArray(tokens, nTokens);
-            nTokens = 0;
-
-            tokens = msStringSplit(szEPSG,':', &nTokens);
-            nEpsgTmp = -1;
-            if (tokens &&  nTokens == 1)
-            {
-                nEpsgTmp = atoi(tokens[0]);
-                
-            }
-            else if (tokens &&  nTokens == 2)
-            {
-                nEpsgTmp = atoi(tokens[1]);
-            }
-            if (nEpsgTmp > 0)
-            {
-                char szTmp[32];
-                snprintf(szTmp, sizeof(szTmp), "init=epsg:%d",nEpsgTmp);
-                msInitProjection(&sProjTmp);
-                if (msLoadProjectionString(&sProjTmp, szTmp) == 0)
-                  msProjectRect(&sProjTmp, &map->projection,  &sQueryRect);
-                msFreeProjection(&sProjTmp);
-            }
-        }
-        if (tokens)
-          msFreeCharArray(tokens, nTokens);
+    nTokens = 0;
+    tokens = msStringSplit(szEPSG,'#', &nTokens);
+    if (tokens && nTokens == 2) {
+      char *szTmp;
+      bufferSize = 10+strlen(tokens[1])+1;
+      szTmp = (char *)malloc(bufferSize);
+      snprintf(szTmp, bufferSize, "init=epsg:%s",tokens[1]);
+      msInitProjection(&sProjTmp);
+      if (msLoadProjectionString(&sProjTmp, szTmp) == 0)
+        msProjectRect(&sProjTmp, &map->projection,  &sQueryRect);
+      free(szTmp);
+    } else if (tokens &&  nTokens == 1) {
+      if (tokens)
+        msFreeCharArray(tokens, nTokens);
+      nTokens = 0;
+
+      tokens = msStringSplit(szEPSG,':', &nTokens);
+      nEpsgTmp = -1;
+      if (tokens &&  nTokens == 1) {
+        nEpsgTmp = atoi(tokens[0]);
+
+      } else if (tokens &&  nTokens == 2) {
+        nEpsgTmp = atoi(tokens[1]);
+      }
+      if (nEpsgTmp > 0) {
+        char szTmp[32];
+        snprintf(szTmp, sizeof(szTmp), "init=epsg:%d",nEpsgTmp);
+        msInitProjection(&sProjTmp);
+        if (msLoadProjectionString(&sProjTmp, szTmp) == 0)
+          msProjectRect(&sProjTmp, &map->projection,  &sQueryRect);
+        msFreeProjection(&sProjTmp);
+      }
+    }
+    if (tokens)
+      msFreeCharArray(tokens, nTokens);
 #endif
+  }
+
+  /* make sure that the layer can be queried*/
+  if (!lp->template)
+    lp->template = msStrdup("ttt.html");
+
+  /* if there is no class, create at least one, so that query by rect
+     would work*/
+  if (lp->numclasses == 0) {
+    if (msGrowLayerClasses(lp) == NULL)
+      return MS_FAILURE;
+    initClass(lp->class[0]);
+  }
+
+  bConcatWhere = 0;
+  bHasAWhere = 0;
+  if (lp->connectiontype == MS_POSTGIS || lp->connectiontype ==  MS_ORACLESPATIAL ||
+      lp->connectiontype == MS_SDE || lp->connectiontype == MS_PLUGIN) {
+    szExpression = FLTGetSQLExpression(psNode, lp);
+    if (szExpression) {
+      pszTmp = msStrdup("(");
+      pszTmp = msStringConcatenate(pszTmp, szExpression);
+      pszTmp = msStringConcatenate(pszTmp, ")");
+      msFree(szExpression);
+      szExpression = pszTmp;
+    }
+  }
+  /* concatenates the WHERE clause for OGR layers. This only applies if
+     the expression was empty or not of an expression string. If there
+     is an sql type expression, it is assumed to have the WHERE clause.
+     If it is an expression and does not have a WHERE it is assumed to be a mapserver
+     type expression*/
+  else if (lp->connectiontype == MS_OGR) {
+    if (lp->filter.type != MS_EXPRESSION) {
+      szExpression = FLTGetSQLExpression(psNode, lp);
+      bConcatWhere = 1;
+    } else {
+      if (lp->filter.string && EQUALN(lp->filter.string,"WHERE ",6)) {
+        szExpression = FLTGetSQLExpression(psNode, lp);
+        bHasAWhere = 1;
+        bConcatWhere =1;
+      } else {
+        szExpression = FLTGetCommonExpression(psNode, lp);
+      }
     }
+  } else {
+    szExpression = FLTGetCommonExpression(psNode, lp);
 
-    /* make sure that the layer can be queried*/
-    if (!lp->template)
-      lp->template = msStrdup("ttt.html");
-
-    /* if there is no class, create at least one, so that query by rect
-       would work*/
-    if (lp->numclasses == 0)
-    {
-        if (msGrowLayerClasses(lp) == NULL)
-          return MS_FAILURE;
-        initClass(lp->class[0]);
-    }
+  }
 
-    bConcatWhere = 0;
-    bHasAWhere = 0;
-    if (lp->connectiontype == MS_POSTGIS || lp->connectiontype ==  MS_ORACLESPATIAL ||
-        lp->connectiontype == MS_SDE || lp->connectiontype == MS_PLUGIN)
-    {
-        szExpression = FLTGetSQLExpression(psNode, lp);
-        if (szExpression)
-        {
-            pszTmp = msStrdup("(");
-            pszTmp = msStringConcatenate(pszTmp, szExpression);
-            pszTmp = msStringConcatenate(pszTmp, ")");
-            msFree(szExpression);
-            szExpression = pszTmp;
-        }
-    }
-    /* concatenates the WHERE clause for OGR layers. This only applies if
-       the expression was empty or not of an expression string. If there
-       is an sql type expression, it is assumed to have the WHERE clause. 
-       If it is an expression and does not have a WHERE it is assumed to be a mapserver
-       type expression*/
-    else if (lp->connectiontype == MS_OGR)
-    {
-	if (lp->filter.type != MS_EXPRESSION)
-	{
-	    szExpression = FLTGetSQLExpression(psNode, lp);
-	    bConcatWhere = 1;
-	}
-	else
-	{
-	    if (lp->filter.string && EQUALN(lp->filter.string,"WHERE ",6))
-	    {
-		szExpression = FLTGetSQLExpression(psNode, lp);
-		bHasAWhere = 1;
-		bConcatWhere =1;
-	    }
-	    else
-	    {
-              szExpression = FLTGetCommonExpression(psNode, lp);
-	    }
-	}
-    }
-    else
-    {
-      szExpression = FLTGetCommonExpression(psNode, lp);
-        
-    }
-   
-
-    if (szExpression)
-    {
-        if (bConcatWhere)
-          pszBuffer = msStringConcatenate(pszBuffer, "WHERE ");
-
-	/* if the filter is set and it's an expression type, concatenate it with
-               this filter. If not just free it */
-	if (lp->filter.string && lp->filter.type == MS_EXPRESSION)
-	{
-	    pszBuffer = msStringConcatenate(pszBuffer, "((");
-	    if (bHasAWhere)
-	      pszBuffer = msStringConcatenate(pszBuffer, lp->filter.string+6);
-	    else
-	       pszBuffer = msStringConcatenate(pszBuffer, lp->filter.string);
-	    pszBuffer = msStringConcatenate(pszBuffer, ") and ");
-	}
-	else if (lp->filter.string)
-	  freeExpression(&lp->filter);
-
-       
-	pszBuffer = msStringConcatenate(pszBuffer, szExpression);
-
-	if(lp->filter.string && lp->filter.type == MS_EXPRESSION)
-	  pszBuffer = msStringConcatenate(pszBuffer, ")");
-        
-        
-        msLoadExpressionString(&lp->filter, pszBuffer);
-        free(szExpression);
-    }
 
-    if (pszBuffer)
-      free(pszBuffer);
+  if (szExpression) {
 
-    map->query.type = MS_QUERY_BY_RECT;
-    map->query.mode = MS_QUERY_MULTIPLE;
-    map->query.layer = lp->index;
-    map->query.rect = sQueryRect;
+    if (bConcatWhere)
+      pszBuffer = msStringConcatenate(pszBuffer, "WHERE ");
 
-    if(map->debug == MS_DEBUGLEVEL_VVV)
-    {
-        tmpfilename = msTmpFile(map, map->mappath, NULL, "_filter.map");
-        if (tmpfilename == NULL)
-        {
-            tmpfilename = msTmpFile(map, NULL, NULL, "_filter.map" );
-        }
-        if (tmpfilename)
-        {
-            msSaveMap(map,tmpfilename);
-            msDebug("FLTApplySimpleSQLFilter(): Map file after Filter was applied %s", tmpfilename);
-            msFree(tmpfilename);
-        }
+    /* if the filter is set and it's an expression type, concatenate it with
+                 this filter. If not just free it */
+    if (lp->filter.string && lp->filter.type == MS_EXPRESSION) {
+      pszBuffer = msStringConcatenate(pszBuffer, "((");
+      if (bHasAWhere)
+        pszBuffer = msStringConcatenate(pszBuffer, lp->filter.string+6);
+      else
+        pszBuffer = msStringConcatenate(pszBuffer, lp->filter.string);
+      pszBuffer = msStringConcatenate(pszBuffer, ") and ");
+    } else if (lp->filter.string)
+      freeExpression(&lp->filter);
+
+
+    pszBuffer = msStringConcatenate(pszBuffer, szExpression);
+
+    if(lp->filter.string && lp->filter.type == MS_EXPRESSION)
+      pszBuffer = msStringConcatenate(pszBuffer, ")");
+
+    msLoadExpressionString(&lp->filter, pszBuffer);
+    free(szExpression);
+  }
+
+  if (pszBuffer)
+    free(pszBuffer);
+
+  map->query.type = MS_QUERY_BY_RECT;
+  map->query.mode = MS_QUERY_MULTIPLE;
+  map->query.layer = lp->index;
+  map->query.rect = sQueryRect;
+
+  if(map->debug == MS_DEBUGLEVEL_VVV) {
+    tmpfilename = msTmpFile(map, map->mappath, NULL, "_filter.map");
+    if (tmpfilename == NULL) {
+      tmpfilename = msTmpFile(map, NULL, NULL, "_filter.map" );
+    }
+    if (tmpfilename) {
+      msSaveMap(map,tmpfilename);
+      msDebug("FLTApplySimpleSQLFilter(): Map file after Filter was applied %s", tmpfilename);
+      msFree(tmpfilename);
+    }
+  }
+
+  /*for oracle connection, if we have a simple filter with no spatial constraints
+    we should set the connection function to NONE to have a better performance
+    (#2725)*/
+
+  if (lp->connectiontype ==  MS_ORACLESPATIAL && FLTIsSimpleFilterNoSpatial(psNode)) {
+    if (strcasestr(lp->data, "USING") == 0)
+      lp->data = msStringConcatenate(lp->data, " USING NONE");
+    else if (strcasestr(lp->data, "NONE") == 0) {
+      /*if one of the functions is used, just replace it with NONE*/
+      if (strcasestr(lp->data, "FILTER"))
+        lp->data = msCaseReplaceSubstring(lp->data, "FILTER", "NONE");
+      else if (strcasestr(lp->data, "GEOMRELATE"))
+        lp->data = msCaseReplaceSubstring(lp->data, "GEOMRELATE", "NONE");
+      else if (strcasestr(lp->data, "RELATE"))
+        lp->data = msCaseReplaceSubstring(lp->data, "RELATE", "NONE");
+      else if (strcasestr(lp->data, "VERSION")) {
+        /*should add NONE just before the VERSION. Cases are:
+          DATA "ORA_GEOMETRY FROM data USING VERSION 10g
+          DATA "ORA_GEOMETRY FROM data  USING UNIQUE FID VERSION 10g"
+         */
+        pszTmp = (char *)strcasestr(lp->data, "VERSION");
+        pszTmp2 = msStringConcatenate(pszTmp2, " NONE ");
+        pszTmp2 = msStringConcatenate(pszTmp2, pszTmp);
+
+        lp->data = msCaseReplaceSubstring(lp->data, pszTmp, pszTmp2);
+
+        msFree(pszTmp2);
+
+      } else if (strcasestr(lp->data, "SRID")) {
+        lp->data = msStringConcatenate(lp->data, " NONE");
+      }
     }
+  }
 
-    /*for oracle connection, if we have a simple filter with no spatial constraints 
-      we should set the connection function to NONE to have a better performance
-      (#2725)*/
-      
-    if (lp->connectiontype ==  MS_ORACLESPATIAL && FLTIsSimpleFilterNoSpatial(psNode))
-    {
-        if (strcasestr(lp->data, "USING") == 0)
-          lp->data = msStringConcatenate(lp->data, " USING NONE"); 
-        else if (strcasestr(lp->data, "NONE") == 0)
-        {
-            /*if one of the functions is used, just replace it with NONE*/
-            if (strcasestr(lp->data, "FILTER"))
-              lp->data = msCaseReplaceSubstring(lp->data, "FILTER", "NONE");
-            else if (strcasestr(lp->data, "GEOMRELATE"))
-              lp->data = msCaseReplaceSubstring(lp->data, "GEOMRELATE", "NONE");
-            else if (strcasestr(lp->data, "RELATE"))
-              lp->data = msCaseReplaceSubstring(lp->data, "RELATE", "NONE");
-            else if (strcasestr(lp->data, "VERSION"))
-            {
-                /*should add NONE just before the VERSION. Cases are:
-                  DATA "ORA_GEOMETRY FROM data USING VERSION 10g
-                  DATA "ORA_GEOMETRY FROM data  USING UNIQUE FID VERSION 10g"
-                 */
-                pszTmp = (char *)strcasestr(lp->data, "VERSION");
-                pszTmp2 = msStringConcatenate(pszTmp2, " NONE ");
-                pszTmp2 = msStringConcatenate(pszTmp2, pszTmp);
-                
-                lp->data = msCaseReplaceSubstring(lp->data, pszTmp, pszTmp2);
-
-                msFree(pszTmp2);
-                
-            }
-            else if (strcasestr(lp->data, "SRID"))
-            {
-                lp->data = msStringConcatenate(lp->data, " NONE"); 
-            }
-        }
-    }
-    
-    return msQueryByRect(map);
+  return msQueryByRect(map);
 
-    /* return MS_SUCCESS; */
+  /* return MS_SUCCESS; */
 }
 
 
-       
+
 
 
 /************************************************************************/
@@ -524,23 +703,22 @@ int FLTApplySimpleSQLFilter(FilterEncodingNode *psNode, mapObj *map,
 /************************************************************************/
 int FLTIsSimpleFilter(FilterEncodingNode *psNode)
 {
-    if (FLTValidForBBoxFilter(psNode))
-    {
-        if (FLTNumberOfFilterType(psNode, "DWithin") == 0 &&
-            FLTNumberOfFilterType(psNode, "Intersect") == 0 &&
-            FLTNumberOfFilterType(psNode, "Intersects") == 0 &&
-            FLTNumberOfFilterType(psNode, "Equals") == 0 &&
-            FLTNumberOfFilterType(psNode, "Disjoint") == 0 &&
-            FLTNumberOfFilterType(psNode, "Touches") == 0 &&
-            FLTNumberOfFilterType(psNode, "Crosses") == 0 &&
-            FLTNumberOfFilterType(psNode, "Within") == 0 &&
-            FLTNumberOfFilterType(psNode, "Contains") == 0 &&
-            FLTNumberOfFilterType(psNode, "Overlaps") == 0 &&
-            FLTNumberOfFilterType(psNode, "Beyond") == 0)
-          return TRUE;
-    }
-
-    return FALSE;
+  if (FLTValidForBBoxFilter(psNode)) {
+    if (FLTNumberOfFilterType(psNode, "DWithin") == 0 &&
+        FLTNumberOfFilterType(psNode, "Intersect") == 0 &&
+        FLTNumberOfFilterType(psNode, "Intersects") == 0 &&
+        FLTNumberOfFilterType(psNode, "Equals") == 0 &&
+        FLTNumberOfFilterType(psNode, "Disjoint") == 0 &&
+        FLTNumberOfFilterType(psNode, "Touches") == 0 &&
+        FLTNumberOfFilterType(psNode, "Crosses") == 0 &&
+        FLTNumberOfFilterType(psNode, "Within") == 0 &&
+        FLTNumberOfFilterType(psNode, "Contains") == 0 &&
+        FLTNumberOfFilterType(psNode, "Overlaps") == 0 &&
+        FLTNumberOfFilterType(psNode, "Beyond") == 0)
+      return TRUE;
+  }
+
+  return FALSE;
 }
 
 
@@ -551,17 +729,17 @@ int FLTIsSimpleFilter(FilterEncodingNode *psNode)
 /*      Use the filter encoding node to create mapserver expressions    */
 /*      and apply it to the layer.                                      */
 /************************************************************************/
-int FLTApplyFilterToLayer(FilterEncodingNode *psNode, mapObj *map, 
+int FLTApplyFilterToLayer(FilterEncodingNode *psNode, mapObj *map,
                           int iLayerIndex)
 {
-    layerObj *layer = GET_LAYER(map, iLayerIndex);
+  layerObj *layer = GET_LAYER(map, iLayerIndex);
 
-    if ( ! layer->vtable) {
-        int rv =  msInitializeVirtualTable(layer);
-        if (rv != MS_SUCCESS)
-            return rv;
-    }
-    return layer->vtable->LayerApplyFilterToLayer(psNode, map,  iLayerIndex);
+  if ( ! layer->vtable) {
+    int rv =  msInitializeVirtualTable(layer);
+    if (rv != MS_SUCCESS)
+      return rv;
+  }
+  return layer->vtable->LayerApplyFilterToLayer(psNode, map,  iLayerIndex);
 
 }
 
@@ -570,20 +748,19 @@ int FLTApplyFilterToLayer(FilterEncodingNode *psNode, mapObj *map,
 /*                                                                      */
 /* Helper function for layer virtual table architecture                 */
 /************************************************************************/
-int FLTLayerApplyCondSQLFilterToLayer(FilterEncodingNode *psNode, mapObj *map, 
+int FLTLayerApplyCondSQLFilterToLayer(FilterEncodingNode *psNode, mapObj *map,
                                       int iLayerIndex)
 {
-/* ==================================================================== */
-/*      Check here to see if it is a simple filter and if that is       */
-/*      the case, we are going to use the FILTER element on             */
-/*      the layer.                                                      */
-/* ==================================================================== */
-    if (FLTIsSimpleFilter(psNode))
-    {
-        return FLTApplySimpleSQLFilter(psNode, map, iLayerIndex);
-    }        
-    
-    return FLTLayerApplyPlainFilterToLayer(psNode, map, iLayerIndex);
+  /* ==================================================================== */
+  /*      Check here to see if it is a simple filter and if that is       */
+  /*      the case, we are going to use the FILTER element on             */
+  /*      the layer.                                                      */
+  /* ==================================================================== */
+  if (FLTIsSimpleFilter(psNode)) {
+    return FLTApplySimpleSQLFilter(psNode, map, iLayerIndex);
+  }
+
+  return FLTLayerApplyPlainFilterToLayer(psNode, map, iLayerIndex);
 }
 
 /************************************************************************/
@@ -591,20 +768,19 @@ int FLTLayerApplyCondSQLFilterToLayer(FilterEncodingNode *psNode, mapObj *map,
 /*                                                                      */
 /* Helper function for layer virtual table architecture                 */
 /************************************************************************/
-int FLTLayerApplyPlainFilterToLayer(FilterEncodingNode *psNode, mapObj *map, 
+int FLTLayerApplyPlainFilterToLayer(FilterEncodingNode *psNode, mapObj *map,
                                     int iLayerIndex)
 {
-    char *pszExpression  =NULL;
-    int status =MS_FALSE;
-
-    pszExpression = FLTGetCommonExpression(psNode,  GET_LAYER(map, iLayerIndex));
-    if (pszExpression)
-    {
-        status = FLTApplyFilterToLayerCommonExpression(map, iLayerIndex, pszExpression);
-        msFree(pszExpression);
-    }
+  char *pszExpression  =NULL;
+  int status =MS_FALSE;
 
-    return status;
+  pszExpression = FLTGetCommonExpression(psNode,  GET_LAYER(map, iLayerIndex));
+  if (pszExpression) {
+    status = FLTApplyFilterToLayerCommonExpression(map, iLayerIndex, pszExpression);
+    msFree(pszExpression);
+  }
+
+  return status;
 }
 
 
@@ -621,73 +797,66 @@ int FLTLayerApplyPlainFilterToLayer(FilterEncodingNode *psNode, mapObj *map,
 /************************************************************************/
 FilterEncodingNode *FLTParseFilterEncoding(char *szXMLString)
 {
-    CPLXMLNode *psRoot = NULL, *psChild=NULL, *psFilter=NULL;
-    CPLXMLNode  *psFilterStart = NULL;
-    FilterEncodingNode *psFilterNode = NULL;
-    
-    if (szXMLString == NULL || strlen(szXMLString) <= 0 ||
-        (strstr(szXMLString, "Filter") == NULL))
-      return NULL;
+  CPLXMLNode *psRoot = NULL, *psChild=NULL, *psFilter=NULL;
+  CPLXMLNode  *psFilterStart = NULL;
+  FilterEncodingNode *psFilterNode = NULL;
 
-    psRoot = CPLParseXMLString(szXMLString);
-    
-    if( psRoot == NULL)
-       return NULL;
-
-    /* strip namespaces. We srtip all name spaces (#1350)*/
-    CPLStripXMLNamespace(psRoot, NULL, 1);
-
-/* -------------------------------------------------------------------- */
-/*      get the root element (Filter).                                  */
-/* -------------------------------------------------------------------- */
-    psChild = psRoot;
-    psFilter = NULL;
-     
-    while( psChild != NULL )
-    {
-        if (psChild->eType == CXT_Element &&
-            EQUAL(psChild->pszValue,"Filter"))
-        {
-            psFilter = psChild;
-            break;
-        }
-        else
-          psChild = psChild->psNext;
-    }
+  if (szXMLString == NULL || strlen(szXMLString) <= 0 ||
+      (strstr(szXMLString, "Filter") == NULL))
+    return NULL;
 
-    if (!psFilter)
-      return NULL;
+  psRoot = CPLParseXMLString(szXMLString);
 
-    psChild = psFilter->psChild;
-    psFilterStart = NULL;
-    while (psChild)
-    { 
-        if (FLTIsSupportedFilterType(psChild))
-        {
-            psFilterStart = psChild;
-            psChild = NULL;
-        }
-        else
-          psChild = psChild->psNext;
-    }
-              
-    if (psFilterStart && FLTIsSupportedFilterType(psFilterStart))
-    {
-        psFilterNode = FLTCreateFilterEncodingNode();
-        
-        FLTInsertElementInNode(psFilterNode, psFilterStart);
-    }
+  if( psRoot == NULL)
+    return NULL;
 
-    CPLDestroyXMLNode( psRoot );
+  /* strip namespaces. We srtip all name spaces (#1350)*/
+  CPLStripXMLNamespace(psRoot, NULL, 1);
+
+  /* -------------------------------------------------------------------- */
+  /*      get the root element (Filter).                                  */
+  /* -------------------------------------------------------------------- */
+  psChild = psRoot;
+  psFilter = NULL;
+
+  while( psChild != NULL ) {
+    if (psChild->eType == CXT_Element &&
+        EQUAL(psChild->pszValue,"Filter")) {
+      psFilter = psChild;
+      break;
+    } else
+      psChild = psChild->psNext;
+  }
+
+  if (!psFilter)
+    return NULL;
 
-/* -------------------------------------------------------------------- */
-/*      validate the node tree to make sure that all the nodes are valid.*/
-/* -------------------------------------------------------------------- */
-    if (!FLTValidFilterNode(psFilterNode))
-      return NULL;
+  psChild = psFilter->psChild;
+  psFilterStart = NULL;
+  while (psChild) {
+    if (FLTIsSupportedFilterType(psChild)) {
+      psFilterStart = psChild;
+      psChild = NULL;
+    } else
+      psChild = psChild->psNext;
+  }
+
+  if (psFilterStart && FLTIsSupportedFilterType(psFilterStart)) {
+    psFilterNode = FLTCreateFilterEncodingNode();
 
+    FLTInsertElementInNode(psFilterNode, psFilterStart);
+  }
 
-    return psFilterNode;
+  CPLDestroyXMLNode( psRoot );
+
+  /* -------------------------------------------------------------------- */
+  /*      validate the node tree to make sure that all the nodes are valid.*/
+  /* -------------------------------------------------------------------- */
+  if (!FLTValidFilterNode(psFilterNode))
+    return NULL;
+
+
+  return psFilterNode;
 }
 
 
@@ -701,24 +870,23 @@ FilterEncodingNode *FLTParseFilterEncoding(char *szXMLString)
 /************************************************************************/
 int FLTValidFilterNode(FilterEncodingNode *psFilterNode)
 {
-    int  bReturn = 0;
+  int  bReturn = 0;
 
-    if (!psFilterNode)
-      return 0;
+  if (!psFilterNode)
+    return 0;
 
-    if (psFilterNode->eType == FILTER_NODE_TYPE_UNDEFINED)
-      return 0;
+  if (psFilterNode->eType == FILTER_NODE_TYPE_UNDEFINED)
+    return 0;
 
-    if (psFilterNode->psLeftNode)
-    {
-        bReturn = FLTValidFilterNode(psFilterNode->psLeftNode);
-        if (bReturn == 0)
-          return 0;
-        else if (psFilterNode->psRightNode)
-          return FLTValidFilterNode(psFilterNode->psRightNode);
-    }
+  if (psFilterNode->psLeftNode) {
+    bReturn = FLTValidFilterNode(psFilterNode->psLeftNode);
+    if (bReturn == 0)
+      return 0;
+    else if (psFilterNode->psRightNode)
+      return FLTValidFilterNode(psFilterNode->psRightNode);
+  }
 
-    return 1;
+  return 1;
 }
 /************************************************************************/
 /*                          FLTFreeFilterEncodingNode                   */
@@ -727,51 +895,44 @@ int FLTValidFilterNode(FilterEncodingNode *psFilterNode)
 /************************************************************************/
 void FLTFreeFilterEncodingNode(FilterEncodingNode *psFilterNode)
 {
-    if (psFilterNode)
-    {
-        if (psFilterNode->psLeftNode)
-        {
-            FLTFreeFilterEncodingNode(psFilterNode->psLeftNode);
-            psFilterNode->psLeftNode = NULL;
-        }
-        if (psFilterNode->psRightNode)
-        {
-            FLTFreeFilterEncodingNode(psFilterNode->psRightNode);
-            psFilterNode->psRightNode = NULL;
-        }
-
-        if (psFilterNode->pszSRS)
-          free( psFilterNode->pszSRS);
-
-        if( psFilterNode->pOther )
-        {
-            if (psFilterNode->pszValue != NULL &&
-                strcasecmp(psFilterNode->pszValue, "PropertyIsLike") == 0)
-            {
-                if( ((FEPropertyIsLike *)psFilterNode->pOther)->pszWildCard )
-                    free( ((FEPropertyIsLike *)psFilterNode->pOther)->pszWildCard );
-                if( ((FEPropertyIsLike *)psFilterNode->pOther)->pszSingleChar )
-                    free( ((FEPropertyIsLike *)psFilterNode->pOther)->pszSingleChar );
-                if( ((FEPropertyIsLike *)psFilterNode->pOther)->pszEscapeChar )
-                    free( ((FEPropertyIsLike *)psFilterNode->pOther)->pszEscapeChar );
-            }
-            else if (psFilterNode->eType == FILTER_NODE_TYPE_GEOMETRY_POINT ||
-                     psFilterNode->eType == FILTER_NODE_TYPE_GEOMETRY_LINE ||
-                     psFilterNode->eType == FILTER_NODE_TYPE_GEOMETRY_POLYGON)
-            {
-                msFreeShape((shapeObj *)(psFilterNode->pOther));
-            }
-            /* else */
-            /* TODO free pOther special fields */
-            free( psFilterNode->pOther );
-        }
+  if (psFilterNode) {
+    if (psFilterNode->psLeftNode) {
+      FLTFreeFilterEncodingNode(psFilterNode->psLeftNode);
+      psFilterNode->psLeftNode = NULL;
+    }
+    if (psFilterNode->psRightNode) {
+      FLTFreeFilterEncodingNode(psFilterNode->psRightNode);
+      psFilterNode->psRightNode = NULL;
+    }
+
+    if (psFilterNode->pszSRS)
+      free( psFilterNode->pszSRS);
+
+    if( psFilterNode->pOther ) {
+      if (psFilterNode->pszValue != NULL &&
+          strcasecmp(psFilterNode->pszValue, "PropertyIsLike") == 0) {
+        if( ((FEPropertyIsLike *)psFilterNode->pOther)->pszWildCard )
+          free( ((FEPropertyIsLike *)psFilterNode->pOther)->pszWildCard );
+        if( ((FEPropertyIsLike *)psFilterNode->pOther)->pszSingleChar )
+          free( ((FEPropertyIsLike *)psFilterNode->pOther)->pszSingleChar );
+        if( ((FEPropertyIsLike *)psFilterNode->pOther)->pszEscapeChar )
+          free( ((FEPropertyIsLike *)psFilterNode->pOther)->pszEscapeChar );
+      } else if (psFilterNode->eType == FILTER_NODE_TYPE_GEOMETRY_POINT ||
+                 psFilterNode->eType == FILTER_NODE_TYPE_GEOMETRY_LINE ||
+                 psFilterNode->eType == FILTER_NODE_TYPE_GEOMETRY_POLYGON) {
+        msFreeShape((shapeObj *)(psFilterNode->pOther));
+      }
+      /* else */
+      /* TODO free pOther special fields */
+      free( psFilterNode->pOther );
+    }
 
-        /* Cannot free pszValue before, 'cause we are testing it above */
-        if( psFilterNode->pszValue )
-            free( psFilterNode->pszValue );
+    /* Cannot free pszValue before, 'cause we are testing it above */
+    if( psFilterNode->pszValue )
+      free( psFilterNode->pszValue );
 
-        free(psFilterNode);
-    }
+    free(psFilterNode);
+  }
 }
 
 
@@ -782,31 +943,31 @@ void FLTFreeFilterEncodingNode(FilterEncodingNode *psFilterNode)
 /************************************************************************/
 FilterEncodingNode *FLTCreateFilterEncodingNode(void)
 {
-    FilterEncodingNode *psFilterNode = NULL;
-
-    psFilterNode = 
-      (FilterEncodingNode *)malloc(sizeof (FilterEncodingNode));
-    psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
-    psFilterNode->pszValue = NULL;
-    psFilterNode->pOther = NULL;
-    psFilterNode->pszSRS = NULL;
-    psFilterNode->psLeftNode = NULL;
-    psFilterNode->psRightNode = NULL;
-
-    return psFilterNode;
+  FilterEncodingNode *psFilterNode = NULL;
+
+  psFilterNode =
+  (FilterEncodingNode *)malloc(sizeof (FilterEncodingNode));
+  psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
+  psFilterNode->pszValue = NULL;
+  psFilterNode->pOther = NULL;
+  psFilterNode->pszSRS = NULL;
+  psFilterNode->psLeftNode = NULL;
+  psFilterNode->psRightNode = NULL;
+
+  return psFilterNode;
 }
 
 FilterEncodingNode *FLTCreateBinaryCompFilterEncodingNode(void)
 {
-    FilterEncodingNode *psFilterNode = NULL;
-    
-    psFilterNode = FLTCreateFilterEncodingNode();
-    /* used to store case sensitivity flag. Default is 0 meaning the 
-       comparing is case snetitive */
-    psFilterNode->pOther = (int *)malloc(sizeof(int));
-    (*(int *)(psFilterNode->pOther)) = 0;
+  FilterEncodingNode *psFilterNode = NULL;
 
-    return psFilterNode;
+  psFilterNode = FLTCreateFilterEncodingNode();
+  /* used to store case sensitivity flag. Default is 0 meaning the
+     comparing is case snetitive */
+  psFilterNode->pOther = (int *)malloc(sizeof(int));
+  (*(int *)(psFilterNode->pOther)) = 0;
+
+  return psFilterNode;
 }
 
 /************************************************************************/
@@ -818,708 +979,656 @@ FilterEncodingNode *FLTCreateBinaryCompFilterEncodingNode(void)
 void FLTInsertElementInNode(FilterEncodingNode *psFilterNode,
                             CPLXMLNode *psXMLNode)
 {
-    int nStrLength = 0;
-    char *pszTmp = NULL;
-    FilterEncodingNode *psCurFilNode= NULL;
-    CPLXMLNode *psCurXMLNode = NULL;
-    CPLXMLNode *psTmpNode = NULL;
-    CPLXMLNode *psFeatureIdNode = NULL;
-    char *pszFeatureId=NULL, *pszFeatureIdList=NULL;
-    char **tokens = NULL;
-    int nTokens = 0;
-
-    if (psFilterNode && psXMLNode && psXMLNode->pszValue)
-    {
-        psFilterNode->pszValue = msStrdup(psXMLNode->pszValue);
-        psFilterNode->psLeftNode = NULL;
-        psFilterNode->psRightNode = NULL;
-        
-/* -------------------------------------------------------------------- */
-/*      Logical filter. AND, OR and NOT are supported. Example of       */
-/*      filer using logical filters :                                   */
-/*      <Filter>                                                        */
-/*        <And>                                                         */
-/*          <PropertyIsGreaterThan>                                     */
-/*            <PropertyName>Person/Age</PropertyName>                   */
-/*            <Literal>50</Literal>                                     */
-/*          </PropertyIsGreaterThan>                                    */
-/*          <PropertyIsEqualTo>                                         */
-/*             <PropertyName>Person/Address/City</PropertyName>         */
-/*             <Literal>Toronto</Literal>                               */
-/*          </PropertyIsEqualTo>                                        */
-/*        </And>                                                        */
-/*      </Filter>                                                       */
-/* -------------------------------------------------------------------- */
-        if (FLTIsLogicalFilterType(psXMLNode->pszValue))
-        {
-            psFilterNode->eType = FILTER_NODE_TYPE_LOGICAL;
-            if (strcasecmp(psFilterNode->pszValue, "AND") == 0 ||
-                strcasecmp(psFilterNode->pszValue, "OR") == 0)
-            {
-                if (psXMLNode->psChild && psXMLNode->psChild->psNext)
-                {
-                    /*2 operators */
-                    if (psXMLNode->psChild->psNext->psNext == NULL)
-                    {
-                        psFilterNode->psLeftNode = FLTCreateFilterEncodingNode();
-                        FLTInsertElementInNode(psFilterNode->psLeftNode, 
-                                               psXMLNode->psChild);
-                        psFilterNode->psRightNode = FLTCreateFilterEncodingNode();
-                        FLTInsertElementInNode(psFilterNode->psRightNode, 
-                                               psXMLNode->psChild->psNext);
-                    }
-                    else
-                    {
-                        psCurXMLNode =  psXMLNode->psChild;
-                        psCurFilNode = psFilterNode;
-                        while(psCurXMLNode)
-                        {
-                            if (psCurXMLNode->psNext && psCurXMLNode->psNext->psNext)
-                            {
-                                psCurFilNode->psLeftNode = 
-                                  FLTCreateFilterEncodingNode();
-                                FLTInsertElementInNode(psCurFilNode->psLeftNode,
-                                                       psCurXMLNode);
-                                psCurFilNode->psRightNode = 
-                                  FLTCreateFilterEncodingNode();
-                                psCurFilNode->psRightNode->eType = 
-                                  FILTER_NODE_TYPE_LOGICAL;
-                                psCurFilNode->psRightNode->pszValue = 
-                                  msStrdup(psFilterNode->pszValue);
-                                
-                                psCurFilNode = psCurFilNode->psRightNode;
-                                psCurXMLNode = psCurXMLNode->psNext;
-                            }
-                            else if (psCurXMLNode->psNext)/*last 2 operators*/
-                            {
-                                psCurFilNode->psLeftNode = 
-                                  FLTCreateFilterEncodingNode();
-                                FLTInsertElementInNode(psCurFilNode->psLeftNode,
-                                                       psCurXMLNode);
-
-                                psCurFilNode->psRightNode = 
-                                  FLTCreateFilterEncodingNode();
-                                FLTInsertElementInNode(psCurFilNode->psRightNode,
-                                                       psCurXMLNode->psNext);
-                                psCurXMLNode = psCurXMLNode->psNext->psNext;
-                                
-                            }
-                        }
-                    }
-                }
-            }
-            else if (strcasecmp(psFilterNode->pszValue, "NOT") == 0)
-            {
-                if (psXMLNode->psChild)
-                {
-                    psFilterNode->psLeftNode = FLTCreateFilterEncodingNode();
-                    FLTInsertElementInNode(psFilterNode->psLeftNode, 
-                                        psXMLNode->psChild); 
-                }
-            } 
-            else
-              psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
-        }/* end if is logical */
-/* -------------------------------------------------------------------- */
-/*      Spatial Filter.                                                 */
-/*      BBOX :                                                          */
-/*      <Filter>                                                        */
-/*       <BBOX>                                                         */
-/*        <PropertyName>Geometry</PropertyName>                         */
-/*        <gml:Box srsName="http://www.opengis.net/gml/srs/epsg.xml#4326">*/
-/*          <gml:coordinates>13.0983,31.5899 35.5472,42.8143</gml:coordinates>*/
-/*        </gml:Box>                                                    */
-/*       </BBOX>                                                        */
-/*      </Filter>                                                       */
-/*                                                                      */
-/*       DWithin                                                        */
-/*                                                                      */
-/*      <xsd:element name="DWithin"                                     */
-/*      type="ogc:DistanceBufferType"                                   */
-/*      substitutionGroup="ogc:spatialOps"/>                            */
-/*                                                                      */
-/*      <xsd:complexType name="DistanceBufferType">                     */
-/*         <xsd:complexContent>                                         */
-/*            <xsd:extension base="ogc:SpatialOpsType">                 */
-/*               <xsd:sequence>                                         */
-/*                  <xsd:element ref="ogc:PropertyName"/>               */
-/*                  <xsd:element ref="gml:_Geometry"/>                  */
-/*                  <xsd:element name="Distance" type="ogc:DistanceType"/>*/
-/*               </xsd:sequence>                                        */
-/*            </xsd:extension>                                          */
-/*         </xsd:complexContent>                                        */
-/*      </xsd:complexType>                                              */
-/*                                                                      */
-/*                                                                      */
-/*       <Filter>                                                       */
-/*       <DWithin>                                                      */
-/*        <PropertyName>Geometry</PropertyName>                         */
-/*        <gml:Point>                                                   */
-/*          <gml:coordinates>13.0983,31.5899</gml:coordinates>          */
-/*        </gml:Point>                                                  */
-/*        <Distance units="url#m">10</Distance>                         */
-/*       </DWithin>                                                     */
-/*      </Filter>                                                       */
-/*                                                                      */
-/*       Intersect                                                      */
-/*                                                                      */
-/*       type="ogc:BinarySpatialOpType" substitutionGroup="ogc:spatialOps"/>*/
-/*      <xsd:element name="Intersects"                                  */
-/*      type="ogc:BinarySpatialOpType"                                  */
-/*      substitutionGroup="ogc:spatialOps"/>                            */
-/*                                                                      */
-/*      <xsd:complexType name="BinarySpatialOpType">                    */
-/*      <xsd:complexContent>                                            */
-/*      <xsd:extension base="ogc:SpatialOpsType">                       */
-/*      <xsd:sequence>                                                  */
-/*      <xsd:element ref="ogc:PropertyName"/>                           */
-/*      <xsd:choice>                                                    */
-/*      <xsd:element ref="gml:_Geometry"/>                              */
-/*      <xsd:element ref="gml:Box"/>                                    */
-/*      </xsd:sequence>                                                 */
-/*      </xsd:extension>                                                */
-/*      </xsd:complexContent>                                           */
-/*      </xsd:complexType>                                              */
-/* -------------------------------------------------------------------- */
-        else if (FLTIsSpatialFilterType(psXMLNode->pszValue))
-        {
-	    psFilterNode->eType = FILTER_NODE_TYPE_SPATIAL;
+  int nStrLength = 0;
+  char *pszTmp = NULL;
+  FilterEncodingNode *psCurFilNode= NULL;
+  CPLXMLNode *psCurXMLNode = NULL;
+  CPLXMLNode *psTmpNode = NULL;
+  CPLXMLNode *psFeatureIdNode = NULL;
+  char *pszFeatureId=NULL, *pszFeatureIdList=NULL;
+  char **tokens = NULL;
+  int nTokens = 0;
+
+  if (psFilterNode && psXMLNode && psXMLNode->pszValue) {
+    psFilterNode->pszValue = msStrdup(psXMLNode->pszValue);
+    psFilterNode->psLeftNode = NULL;
+    psFilterNode->psRightNode = NULL;
 
-            if (strcasecmp(psXMLNode->pszValue, "BBOX") == 0)
-            {
-                char *pszSRS = NULL;
-                CPLXMLNode *psPropertyName = NULL;
-                CPLXMLNode *psBox = NULL, *psEnvelope=NULL;
-                rectObj sBox;
-                
-                int bCoordinatesValid = 0;
-
-                psPropertyName = CPLGetXMLNode(psXMLNode, "PropertyName");
-                psBox = CPLGetXMLNode(psXMLNode, "Box");
-                if (!psBox)
-                  psBox = CPLGetXMLNode(psXMLNode, "BoxType");
-
-                /*FE 1.0 used box FE1.1 uses envelop*/
-                if (psBox)
-                  bCoordinatesValid = FLTParseGMLBox(psBox, &sBox, &pszSRS);
-                else if ((psEnvelope = CPLGetXMLNode(psXMLNode, "Envelope")))
-                  bCoordinatesValid = FLTParseGMLEnvelope(psEnvelope, &sBox, &pszSRS);
-
-                if (psPropertyName == NULL || !bCoordinatesValid)
-                  psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
-
-                if (psPropertyName && bCoordinatesValid)
-                {
-                    psFilterNode->psLeftNode = FLTCreateFilterEncodingNode();
-                    /* not really using the property name anywhere ??  */
-                    /* Is is always Geometry ?  */
-                    if (psPropertyName->psChild && 
-                        psPropertyName->psChild->pszValue)
-                    {
-                        psFilterNode->psLeftNode->eType = 
-                          FILTER_NODE_TYPE_PROPERTYNAME;
-                        psFilterNode->psLeftNode->pszValue = 
-                          msStrdup(psPropertyName->psChild->pszValue);
-                    }
-                
-                    /* srs and coordinates */
-                    psFilterNode->psRightNode = FLTCreateFilterEncodingNode();
-                    psFilterNode->psRightNode->eType = FILTER_NODE_TYPE_BBOX;
-                    /* srs might be empty */
-                    if (pszSRS)
-                      psFilterNode->psRightNode->pszValue = pszSRS;
-
-                    psFilterNode->psRightNode->pOther =     
-                      (rectObj *)msSmallMalloc(sizeof(rectObj));
-                    ((rectObj *)psFilterNode->psRightNode->pOther)->minx = sBox.minx; 
-                    ((rectObj *)psFilterNode->psRightNode->pOther)->miny = sBox.miny; 
-                    ((rectObj *)psFilterNode->psRightNode->pOther)->maxx = sBox.maxx; 
-                    ((rectObj *)psFilterNode->psRightNode->pOther)->maxy =  sBox.maxy; 
-                }
-            }
-            else if (strcasecmp(psXMLNode->pszValue, "DWithin") == 0 ||
-                     strcasecmp(psXMLNode->pszValue, "Beyond") == 0)
- 
-            {
-                shapeObj *psShape = NULL;
-                int bPoint = 0, bLine = 0, bPolygon = 0;
-                char *pszUnits = NULL;
-                char *pszSRS = NULL;
-                
-                
-                CPLXMLNode *psGMLElement = NULL, *psDistance=NULL;
-
-
-                psGMLElement = CPLGetXMLNode(psXMLNode, "Point");
-                if (!psGMLElement)
-                  psGMLElement =  CPLGetXMLNode(psXMLNode, "PointType");
-                if (psGMLElement)
-                  bPoint =1;
-                else
-                {
-                    psGMLElement= CPLGetXMLNode(psXMLNode, "Polygon");
-                    if (psGMLElement)
-                      bPolygon = 1;
-                    else if ((psGMLElement= CPLGetXMLNode(psXMLNode, "MultiPolygon")))
-                      bPolygon = 1;
-                    else if ((psGMLElement= CPLGetXMLNode(psXMLNode, "MultiSurface")))
-                      bPolygon = 1; 
-                    else if ((psGMLElement= CPLGetXMLNode(psXMLNode, "Box")))
-                      bPolygon = 1;
-                    else
-                    {
-                        psGMLElement= CPLGetXMLNode(psXMLNode, "LineString");
-                        if (psGMLElement)
-                          bLine = 1;
-                    }		
-                }
-
-                psDistance = CPLGetXMLNode(psXMLNode, "Distance");
-                if (psGMLElement && psDistance && psDistance->psChild &&  
-                    psDistance->psChild->psNext && psDistance->psChild->psNext->pszValue)
-                {
-                    pszUnits = (char *)CPLGetXMLValue(psDistance, "units", NULL);
-                    psShape = (shapeObj *)msSmallMalloc(sizeof(shapeObj));
-                    msInitShape(psShape);
-                    if (FLTShapeFromGMLTree(psGMLElement, psShape, &pszSRS))
-                      /* if (FLTGML2Shape_XMLNode(psPoint, psShape)) */
-                    {
-                        /*set the srs if available*/
-                        if (pszSRS)
-                          psFilterNode->pszSRS = pszSRS;
-
-                        psFilterNode->psLeftNode = FLTCreateFilterEncodingNode();
-                        /* not really using the property name anywhere ?? Is is always */
-                        /* Geometry ?  */
-                    
-                        psFilterNode->psLeftNode->eType = FILTER_NODE_TYPE_PROPERTYNAME;
-                        psFilterNode->psLeftNode->pszValue = msStrdup("Geometry");
-
-                        psFilterNode->psRightNode = FLTCreateFilterEncodingNode();
-                        if (bPoint)
-                          psFilterNode->psRightNode->eType = FILTER_NODE_TYPE_GEOMETRY_POINT;
-                        else if (bLine)
-                          psFilterNode->psRightNode->eType = FILTER_NODE_TYPE_GEOMETRY_LINE;
-                        else if (bPolygon)
-                          psFilterNode->psRightNode->eType = FILTER_NODE_TYPE_GEOMETRY_POLYGON;
-                        psFilterNode->psRightNode->pOther = (shapeObj *)psShape;
-                        /*the value will be distance;units*/
-                        psFilterNode->psRightNode->pszValue = 
-                          msStrdup(psDistance->psChild->psNext->pszValue);
-                        if (pszUnits)
-                        {
-                            psFilterNode->psRightNode->pszValue= msStringConcatenate(psFilterNode->psRightNode->pszValue, ";");
-                            psFilterNode->psRightNode->pszValue= msStringConcatenate(psFilterNode->psRightNode->pszValue, pszUnits);
-                        }
-                    }
-                }
-                else
-                  psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
-            }
-            else if (strcasecmp(psXMLNode->pszValue, "Intersect") == 0 ||
-                     strcasecmp(psXMLNode->pszValue, "Intersects") == 0 ||
-                     strcasecmp(psXMLNode->pszValue, "Equals") == 0 ||
-                     strcasecmp(psXMLNode->pszValue, "Disjoint") == 0 ||
-                     strcasecmp(psXMLNode->pszValue, "Touches") == 0 ||
-                     strcasecmp(psXMLNode->pszValue, "Crosses") == 0 ||
-                     strcasecmp(psXMLNode->pszValue, "Within") == 0 ||
-                     strcasecmp(psXMLNode->pszValue, "Contains") == 0 ||
-                     strcasecmp(psXMLNode->pszValue, "Overlaps") == 0)
-            {
-                shapeObj *psShape = NULL;
-                int  bLine = 0, bPolygon = 0, bPoint=0;
-                char *pszSRS = NULL;
-
-                
-                CPLXMLNode *psGMLElement = NULL;
-
-
-                psGMLElement = CPLGetXMLNode(psXMLNode, "Polygon");
-                if (psGMLElement)
-                  bPolygon = 1;
-                else if ((psGMLElement= CPLGetXMLNode(psXMLNode, "MultiPolygon")))
-                  bPolygon = 1;
-                else if ((psGMLElement= CPLGetXMLNode(psXMLNode, "MultiSurface")))
-                  bPolygon = 1;
-                else if ((psGMLElement= CPLGetXMLNode(psXMLNode, "Box")))
-                  bPolygon = 1;
-                else if ((psGMLElement= CPLGetXMLNode(psXMLNode, "LineString")))
-                {
-                    if (psGMLElement)
-                      bLine = 1;
-                }
-
-		else
-                {
-                     psGMLElement = CPLGetXMLNode(psXMLNode, "Point");
-                     if (!psGMLElement)
-                       psGMLElement =  CPLGetXMLNode(psXMLNode, "PointType");
-                     if (psGMLElement)
-                       bPoint =1;
-                }
-
-                if (psGMLElement)
-                {
-                    psShape = (shapeObj *)msSmallMalloc(sizeof(shapeObj));
-                    msInitShape(psShape);
-                    if (FLTShapeFromGMLTree(psGMLElement, psShape, &pszSRS))
-                      /* if (FLTGML2Shape_XMLNode(psPoint, psShape)) */
-                    {
-                        /*set the srs if available*/
-                        if (pszSRS)
-                          psFilterNode->pszSRS = pszSRS;
-
-                        psFilterNode->psLeftNode = FLTCreateFilterEncodingNode();
-                        /* not really using the property name anywhere ?? Is is always */
-                        /* Geometry ?  */
-                    
-                        psFilterNode->psLeftNode->eType = FILTER_NODE_TYPE_PROPERTYNAME;
-                        psFilterNode->psLeftNode->pszValue = msStrdup("Geometry");
-
-                        psFilterNode->psRightNode = FLTCreateFilterEncodingNode();
-                        if (bPoint)
-                          psFilterNode->psRightNode->eType = FILTER_NODE_TYPE_GEOMETRY_POINT;
-                        if (bLine)
-                          psFilterNode->psRightNode->eType = FILTER_NODE_TYPE_GEOMETRY_LINE;
-                        else if (bPolygon)
-                          psFilterNode->psRightNode->eType = FILTER_NODE_TYPE_GEOMETRY_POLYGON;
-                        psFilterNode->psRightNode->pOther = (shapeObj *)psShape;
-
-                    }
-                }
-                else
-                  psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
+    /* -------------------------------------------------------------------- */
+    /*      Logical filter. AND, OR and NOT are supported. Example of       */
+    /*      filer using logical filters :                                   */
+    /*      <Filter>                                                        */
+    /*        <And>                                                         */
+    /*          <PropertyIsGreaterThan>                                     */
+    /*            <PropertyName>Person/Age</PropertyName>                   */
+    /*            <Literal>50</Literal>                                     */
+    /*          </PropertyIsGreaterThan>                                    */
+    /*          <PropertyIsEqualTo>                                         */
+    /*             <PropertyName>Person/Address/City</PropertyName>         */
+    /*             <Literal>Toronto</Literal>                               */
+    /*          </PropertyIsEqualTo>                                        */
+    /*        </And>                                                        */
+    /*      </Filter>                                                       */
+    /* -------------------------------------------------------------------- */
+    if (FLTIsLogicalFilterType(psXMLNode->pszValue)) {
+      psFilterNode->eType = FILTER_NODE_TYPE_LOGICAL;
+      if (strcasecmp(psFilterNode->pszValue, "AND") == 0 ||
+          strcasecmp(psFilterNode->pszValue, "OR") == 0) {
+        if (psXMLNode->psChild && psXMLNode->psChild->psNext) {
+          /*2 operators */
+          if (psXMLNode->psChild->psNext->psNext == NULL) {
+            psFilterNode->psLeftNode = FLTCreateFilterEncodingNode();
+            FLTInsertElementInNode(psFilterNode->psLeftNode,
+                                   psXMLNode->psChild);
+            psFilterNode->psRightNode = FLTCreateFilterEncodingNode();
+            FLTInsertElementInNode(psFilterNode->psRightNode,
+                                   psXMLNode->psChild->psNext);
+          } else {
+            psCurXMLNode =  psXMLNode->psChild;
+            psCurFilNode = psFilterNode;
+            while(psCurXMLNode) {
+              if (psCurXMLNode->psNext && psCurXMLNode->psNext->psNext) {
+                psCurFilNode->psLeftNode =
+                FLTCreateFilterEncodingNode();
+                FLTInsertElementInNode(psCurFilNode->psLeftNode,
+                                       psCurXMLNode);
+                psCurFilNode->psRightNode =
+                FLTCreateFilterEncodingNode();
+                psCurFilNode->psRightNode->eType =
+                FILTER_NODE_TYPE_LOGICAL;
+                psCurFilNode->psRightNode->pszValue =
+                msStrdup(psFilterNode->pszValue);
+
+                psCurFilNode = psCurFilNode->psRightNode;
+                psCurXMLNode = psCurXMLNode->psNext;
+              } else if (psCurXMLNode->psNext) { /*last 2 operators*/
+                psCurFilNode->psLeftNode =
+                FLTCreateFilterEncodingNode();
+                FLTInsertElementInNode(psCurFilNode->psLeftNode,
+                                       psCurXMLNode);
+
+                psCurFilNode->psRightNode =
+                FLTCreateFilterEncodingNode();
+                FLTInsertElementInNode(psCurFilNode->psRightNode,
+                                       psCurXMLNode->psNext);
+                psCurXMLNode = psCurXMLNode->psNext->psNext;
+
+              }
             }
-            
-                
-        }/* end of is spatial */
+          }
+        }
+      } else if (strcasecmp(psFilterNode->pszValue, "NOT") == 0) {
+        if (psXMLNode->psChild) {
+          psFilterNode->psLeftNode = FLTCreateFilterEncodingNode();
+          FLTInsertElementInNode(psFilterNode->psLeftNode,
+                                 psXMLNode->psChild);
+        }
+      } else
+        psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
+    }/* end if is logical */
+    /* -------------------------------------------------------------------- */
+    /*      Spatial Filter.                                                 */
+    /*      BBOX :                                                          */
+    /*      <Filter>                                                        */
+    /*       <BBOX>                                                         */
+    /*        <PropertyName>Geometry</PropertyName>                         */
+    /*        <gml:Box srsName="http://www.opengis.net/gml/srs/epsg.xml#4326">*/
+    /*          <gml:coordinates>13.0983,31.5899 35.5472,42.8143</gml:coordinates>*/
+    /*        </gml:Box>                                                    */
+    /*       </BBOX>                                                        */
+    /*      </Filter>                                                       */
+    /*                                                                      */
+    /*       DWithin                                                        */
+    /*                                                                      */
+    /*      <xsd:element name="DWithin"                                     */
+    /*      type="ogc:DistanceBufferType"                                   */
+    /*      substitutionGroup="ogc:spatialOps"/>                            */
+    /*                                                                      */
+    /*      <xsd:complexType name="DistanceBufferType">                     */
+    /*         <xsd:complexContent>                                         */
+    /*            <xsd:extension base="ogc:SpatialOpsType">                 */
+    /*               <xsd:sequence>                                         */
+    /*                  <xsd:element ref="ogc:PropertyName"/>               */
+    /*                  <xsd:element ref="gml:_Geometry"/>                  */
+    /*                  <xsd:element name="Distance" type="ogc:DistanceType"/>*/
+    /*               </xsd:sequence>                                        */
+    /*            </xsd:extension>                                          */
+    /*         </xsd:complexContent>                                        */
+    /*      </xsd:complexType>                                              */
+    /*                                                                      */
+    /*                                                                      */
+    /*       <Filter>                                                       */
+    /*       <DWithin>                                                      */
+    /*        <PropertyName>Geometry</PropertyName>                         */
+    /*        <gml:Point>                                                   */
+    /*          <gml:coordinates>13.0983,31.5899</gml:coordinates>          */
+    /*        </gml:Point>                                                  */
+    /*        <Distance units="url#m">10</Distance>                         */
+    /*       </DWithin>                                                     */
+    /*      </Filter>                                                       */
+    /*                                                                      */
+    /*       Intersect                                                      */
+    /*                                                                      */
+    /*       type="ogc:BinarySpatialOpType" substitutionGroup="ogc:spatialOps"/>*/
+    /*      <xsd:element name="Intersects"                                  */
+    /*      type="ogc:BinarySpatialOpType"                                  */
+    /*      substitutionGroup="ogc:spatialOps"/>                            */
+    /*                                                                      */
+    /*      <xsd:complexType name="BinarySpatialOpType">                    */
+    /*      <xsd:complexContent>                                            */
+    /*      <xsd:extension base="ogc:SpatialOpsType">                       */
+    /*      <xsd:sequence>                                                  */
+    /*      <xsd:element ref="ogc:PropertyName"/>                           */
+    /*      <xsd:choice>                                                    */
+    /*      <xsd:element ref="gml:_Geometry"/>                              */
+    /*      <xsd:element ref="gml:Box"/>                                    */
+    /*      </xsd:sequence>                                                 */
+    /*      </xsd:extension>                                                */
+    /*      </xsd:complexContent>                                           */
+    /*      </xsd:complexType>                                              */
+    /* -------------------------------------------------------------------- */
+    else if (FLTIsSpatialFilterType(psXMLNode->pszValue)) {
+      psFilterNode->eType = FILTER_NODE_TYPE_SPATIAL;
+
+      if (strcasecmp(psXMLNode->pszValue, "BBOX") == 0) {
+        char *pszSRS = NULL;
+        CPLXMLNode *psPropertyName = NULL;
+        CPLXMLNode *psBox = NULL, *psEnvelope=NULL;
+        rectObj sBox;
+
+        int bCoordinatesValid = 0;
+
+        psPropertyName = CPLGetXMLNode(psXMLNode, "PropertyName");
+        psBox = CPLGetXMLNode(psXMLNode, "Box");
+        if (!psBox)
+          psBox = CPLGetXMLNode(psXMLNode, "BoxType");
+
+        /*FE 1.0 used box FE1.1 uses envelop*/
+        if (psBox)
+          bCoordinatesValid = FLTParseGMLBox(psBox, &sBox, &pszSRS);
+        else if ((psEnvelope = CPLGetXMLNode(psXMLNode, "Envelope")))
+          bCoordinatesValid = FLTParseGMLEnvelope(psEnvelope, &sBox, &pszSRS);
+
+        if (psPropertyName == NULL || !bCoordinatesValid)
+          psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
+
+        if (psPropertyName && bCoordinatesValid) {
+          psFilterNode->psLeftNode = FLTCreateFilterEncodingNode();
+          /* not really using the property name anywhere ??  */
+          /* Is is always Geometry ?  */
+          if (psPropertyName->psChild &&
+              psPropertyName->psChild->pszValue) {
+            psFilterNode->psLeftNode->eType =
+            FILTER_NODE_TYPE_PROPERTYNAME;
+            psFilterNode->psLeftNode->pszValue =
+            msStrdup(psPropertyName->psChild->pszValue);
+          }
+
+          /* srs and coordinates */
+          psFilterNode->psRightNode = FLTCreateFilterEncodingNode();
+          psFilterNode->psRightNode->eType = FILTER_NODE_TYPE_BBOX;
+          /* srs might be empty */
+          if (pszSRS)
+            psFilterNode->psRightNode->pszValue = pszSRS;
+
+          psFilterNode->psRightNode->pOther =
+          (rectObj *)msSmallMalloc(sizeof(rectObj));
+          ((rectObj *)psFilterNode->psRightNode->pOther)->minx = sBox.minx;
+          ((rectObj *)psFilterNode->psRightNode->pOther)->miny = sBox.miny;
+          ((rectObj *)psFilterNode->psRightNode->pOther)->maxx = sBox.maxx;
+          ((rectObj *)psFilterNode->psRightNode->pOther)->maxy =  sBox.maxy;
+        }
+      } else if (strcasecmp(psXMLNode->pszValue, "DWithin") == 0 ||
+                 strcasecmp(psXMLNode->pszValue, "Beyond") == 0)
 
+      {
+        shapeObj *psShape = NULL;
+        int bPoint = 0, bLine = 0, bPolygon = 0;
+        char *pszUnits = NULL;
+        char *pszSRS = NULL;
+
+
+        CPLXMLNode *psGMLElement = NULL, *psDistance=NULL;
+
+
+        psGMLElement = CPLGetXMLNode(psXMLNode, "Point");
+        if (!psGMLElement)
+          psGMLElement =  CPLGetXMLNode(psXMLNode, "PointType");
+        if (psGMLElement)
+          bPoint =1;
+        else {
+          psGMLElement= CPLGetXMLNode(psXMLNode, "Polygon");
+          if (psGMLElement)
+            bPolygon = 1;
+          else if ((psGMLElement= CPLGetXMLNode(psXMLNode, "MultiPolygon")))
+            bPolygon = 1;
+          else if ((psGMLElement= CPLGetXMLNode(psXMLNode, "MultiSurface")))
+            bPolygon = 1;
+          else if ((psGMLElement= CPLGetXMLNode(psXMLNode, "Box")))
+            bPolygon = 1;
+          else {
+            psGMLElement= CPLGetXMLNode(psXMLNode, "LineString");
+            if (psGMLElement)
+              bLine = 1;
+          }
+        }
 
-/* -------------------------------------------------------------------- */
-/*      Comparison Filter                                               */
-/* -------------------------------------------------------------------- */
-        else if (FLTIsComparisonFilterType(psXMLNode->pszValue))
-        {
-            psFilterNode->eType = FILTER_NODE_TYPE_COMPARISON;
-/* -------------------------------------------------------------------- */
-/*      binary comaparison types. Example :                             */
-/*                                                                      */
-/*      <Filter>                                                        */
-/*        <PropertyIsEqualTo>                                           */
-/*          <PropertyName>SomeProperty</PropertyName>                   */
-/*          <Literal>100</Literal>                                      */
-/*        </PropertyIsEqualTo>                                          */
-/*      </Filter>                                                       */
-/* -------------------------------------------------------------------- */
-            if (FLTIsBinaryComparisonFilterType(psXMLNode->pszValue))
-            {
-                psTmpNode = CPLSearchXMLNode(psXMLNode,  "PropertyName");
-                if (psTmpNode &&  psTmpNode->psChild && 
-                    psTmpNode->psChild->pszValue && 
-                    strlen(psTmpNode->psChild->pszValue) > 0)
-                {
-                    psFilterNode->psLeftNode = FLTCreateFilterEncodingNode();
-                    psFilterNode->psLeftNode->eType = FILTER_NODE_TYPE_PROPERTYNAME;
-                    psFilterNode->psLeftNode->pszValue = 
-                      msStrdup(psTmpNode->psChild->pszValue);
-                    
-                    psTmpNode = CPLSearchXMLNode(psXMLNode,  "Literal");
-                    if (psTmpNode)
-                    {
-                        psFilterNode->psRightNode = FLTCreateBinaryCompFilterEncodingNode();
-                        psFilterNode->psRightNode->eType = FILTER_NODE_TYPE_LITERAL;
-                    
-                        if (psTmpNode && 
-                            psTmpNode->psChild && 
-                            psTmpNode->psChild->pszValue &&
-                            strlen(psTmpNode->psChild->pszValue) > 0)
-                        {
-                        
-                            psFilterNode->psRightNode->pszValue = 
-                              msStrdup(psTmpNode->psChild->pszValue);
-
-                            /*check if the matchCase attribute is set*/
-                            if (psXMLNode->psChild && 
-                                psXMLNode->psChild->eType == CXT_Attribute  &&
-                                psXMLNode->psChild->pszValue && 
-                                strcasecmp(psXMLNode->psChild->pszValue, "matchCase") == 0 &&
-                                psXMLNode->psChild->psChild &&  
-                                psXMLNode->psChild->psChild->pszValue &&
-                                strcasecmp( psXMLNode->psChild->psChild->pszValue, "false") == 0)
-                            {
-                                (*(int *)psFilterNode->psRightNode->pOther) = 1;
-                            }
-                        
-                        }
-                        /* special case where the user puts an empty value */
-                        /* for the Literal so it can end up as an empty  */
-                        /* string query in the expression */
-                        else
-                          psFilterNode->psRightNode->pszValue = NULL;
-                    }
-                }
-                if (psFilterNode->psLeftNode == NULL || psFilterNode->psRightNode == NULL)
-                  psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
-            }
- 
-/* -------------------------------------------------------------------- */
-/*      PropertyIsBetween filter : extract property name and boudary    */
-/*      values. The boundary  values are stored in the right            */
-/*      node. The values are separated by a semi-column (;)             */
-/*      Eg of Filter :                                                  */
-/*      <PropertyIsBetween>                                             */
-/*         <PropertyName>DEPTH</PropertyName>                           */
-/*         <LowerBoundary><Literal>400</Literal></LowerBoundary>        */
-/*         <UpperBoundary><Literal>800</Literal></UpperBoundary>        */
-/*      </PropertyIsBetween>                                            */
-/*                                                                      */
-/*      Or                                                              */
-/*      <PropertyIsBetween>                                             */
-/*         <PropertyName>DEPTH</PropertyName>                           */
-/*         <LowerBoundary>400</LowerBoundary>                           */
-/*         <UpperBoundary>800</UpperBoundary>                           */
-/*      </PropertyIsBetween>                                            */
-/* -------------------------------------------------------------------- */
-            else if (strcasecmp(psXMLNode->pszValue, "PropertyIsBetween") == 0)
-            {
-                CPLXMLNode *psUpperNode = NULL, *psLowerNode = NULL;
-                if (psXMLNode->psChild &&
-                    strcasecmp(psXMLNode->psChild->pszValue, 
-                               "PropertyName") == 0 &&
-                    psXMLNode->psChild->psNext &&  
-                      strcasecmp(psXMLNode->psChild->psNext->pszValue, 
-                               "LowerBoundary") == 0 &&
-                    psXMLNode->psChild->psNext->psNext &&
-                    strcasecmp(psXMLNode->psChild->psNext->psNext->pszValue, 
-                                "UpperBoundary") == 0)
-                {
-                    psFilterNode->psLeftNode = FLTCreateFilterEncodingNode();
-                    
-                    if (psXMLNode->psChild->psChild && 
-                        psXMLNode->psChild->psChild->pszValue)
-                    {
-                        psFilterNode->psLeftNode->eType = FILTER_NODE_TYPE_PROPERTYNAME;
-                        psFilterNode->psLeftNode->pszValue = 
-                          msStrdup(psXMLNode->psChild->psChild->pszValue);
-                    }
-
-                    psFilterNode->psRightNode = FLTCreateFilterEncodingNode();
-                    if (psXMLNode->psChild->psNext->psChild &&
-                        psXMLNode->psChild->psNext->psNext->psChild &&
-                        psXMLNode->psChild->psNext->psChild->pszValue &&
-                        psXMLNode->psChild->psNext->psNext->psChild->pszValue)
-                    {
-                        /* check if the <Literals> is there */
-                        psFilterNode->psRightNode->eType = FILTER_NODE_TYPE_BOUNDARY;
-                        if (psXMLNode->psChild->psNext->psChild->psChild)
-                          psLowerNode = psXMLNode->psChild->psNext->psChild->psChild;
-                        else
-                          psLowerNode = psXMLNode->psChild->psNext->psChild;
-
-                        if (psXMLNode->psChild->psNext->psNext->psChild->psChild)
-                          psUpperNode = psXMLNode->psChild->psNext->psNext->psChild->psChild;
-                        else
-                          psUpperNode = psXMLNode->psChild->psNext->psNext->psChild;
-
-                        nStrLength = 
-                          strlen(psLowerNode->pszValue);
-                        nStrLength +=
-                          strlen(psUpperNode->pszValue);
-
-                        nStrLength += 2; /* adding a ; between bounary values */
-                         psFilterNode->psRightNode->pszValue = 
-                           (char *)malloc(sizeof(char)*(nStrLength));
-                         strcpy( psFilterNode->psRightNode->pszValue,
-                                psLowerNode->pszValue);
-                         strlcat(psFilterNode->psRightNode->pszValue, ";", nStrLength);
-                         strlcat(psFilterNode->psRightNode->pszValue,
-                                 psUpperNode->pszValue, nStrLength); 
-                    }
-                         
-                  
-                }
-                else
-                  psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
-
-            }/* end of PropertyIsBetween  */
-/* -------------------------------------------------------------------- */
-/*      PropertyIsLike                                                  */
-/*                                                                      */
-/*      <Filter>                                                        */
-/*      <PropertyIsLike wildCard="*" singleChar="#" escape="!">         */
-/*      <PropertyName>LAST_NAME</PropertyName>                          */
-/*      <Literal>JOHN*</Literal>                                        */
-/*      </PropertyIsLike>                                               */
-/*      </Filter>                                                       */
-/* -------------------------------------------------------------------- */
-            else if (strcasecmp(psXMLNode->pszValue, "PropertyIsLike") == 0)
-            {
-                if (CPLSearchXMLNode(psXMLNode,  "Literal") &&
-                    CPLSearchXMLNode(psXMLNode,  "PropertyName") &&
-                    CPLGetXMLValue(psXMLNode, "wildCard", "") &&
-                    CPLGetXMLValue(psXMLNode, "singleChar", "") &&
-                    (CPLGetXMLValue(psXMLNode, "escape", "") || 
-                     CPLGetXMLValue(psXMLNode, "escapeChar", "")))
-                  /*
-                    psXMLNode->psChild &&  
-                    strcasecmp(psXMLNode->psChild->pszValue, "wildCard") == 0 &&
-                    psXMLNode->psChild->psNext &&
-                    strcasecmp(psXMLNode->psChild->psNext->pszValue, "singleChar") == 0 &&
-                    psXMLNode->psChild->psNext->psNext &&
-                    strcasecmp(psXMLNode->psChild->psNext->psNext->pszValue, "escape") == 0 &&
-                    psXMLNode->psChild->psNext->psNext->psNext &&
-                    strcasecmp(psXMLNode->psChild->psNext->psNext->psNext->pszValue, "PropertyName") == 0 &&
-                    psXMLNode->psChild->psNext->psNext->psNext->psNext &&
-                    strcasecmp(psXMLNode->psChild->psNext->psNext->psNext->psNext->pszValue, "Literal") == 0)
-                  */
-                {
-/* -------------------------------------------------------------------- */
-/*      Get the wildCard, the singleChar and the escapeChar used.       */
-/* -------------------------------------------------------------------- */
-                    psFilterNode->pOther = (FEPropertyIsLike *)malloc(sizeof(FEPropertyIsLike));
-                    /*default is case sensitive*/
-                    ((FEPropertyIsLike *)psFilterNode->pOther)->bCaseInsensitive = 0;
-
-                    pszTmp = (char *)CPLGetXMLValue(psXMLNode, "wildCard", "");
-                    if (pszTmp)
-                      ((FEPropertyIsLike *)psFilterNode->pOther)->pszWildCard = 
-                        msStrdup(pszTmp);
-                    pszTmp = (char *)CPLGetXMLValue(psXMLNode, "singleChar", "");
-                    if (pszTmp)
-                      ((FEPropertyIsLike *)psFilterNode->pOther)->pszSingleChar = 
-                        msStrdup(pszTmp);
-                    pszTmp = (char *)CPLGetXMLValue(psXMLNode, "escape", "");
-                    if (pszTmp && strlen(pszTmp)>0)
-                      ((FEPropertyIsLike *)psFilterNode->pOther)->pszEscapeChar = 
-                        msStrdup(pszTmp);
-                    else
-                    {
-                        pszTmp = (char *)CPLGetXMLValue(psXMLNode, "escapeChar", "");
-                        if (pszTmp)
-                          ((FEPropertyIsLike *)psFilterNode->pOther)->pszEscapeChar = 
-                            msStrdup(pszTmp);
-                    }
-                    pszTmp = (char *)CPLGetXMLValue(psXMLNode, "matchCase", "");
-                    if (pszTmp && strlen(pszTmp) > 0 && 
-                        strcasecmp(pszTmp, "false") == 0)
-                    {
-                      ((FEPropertyIsLike *)psFilterNode->pOther)->bCaseInsensitive =1;
-                    }
-/* -------------------------------------------------------------------- */
-/*      Create left and right node for the attribute and the value.     */
-/* -------------------------------------------------------------------- */
-                    psFilterNode->psLeftNode = FLTCreateFilterEncodingNode();
-
-                    psTmpNode = CPLSearchXMLNode(psXMLNode,  "PropertyName");
-                    if (psTmpNode &&  psTmpNode->psChild &&
-                        psTmpNode->psChild->pszValue && 
-                        strlen(psTmpNode->psChild->pszValue) > 0)
-                    
-                    {
-                        /*
-                    if (psXMLNode->psChild->psNext->psNext->psNext->psChild &&
-                        psXMLNode->psChild->psNext->psNext->psNext->psChild->pszValue)
-                    {
-                        psFilterNode->psLeftNode->pszValue = 
-                          msStrdup(psXMLNode->psChild->psNext->psNext->psNext->psChild->pszValue);
-                        */
-                        psFilterNode->psLeftNode->pszValue = 
-                          msStrdup(psTmpNode->psChild->pszValue);
-                        psFilterNode->psLeftNode->eType = FILTER_NODE_TYPE_PROPERTYNAME;
-                        
-                    }
-
-                    psFilterNode->psRightNode = FLTCreateFilterEncodingNode();
-
-                    
-                    psTmpNode = CPLSearchXMLNode(psXMLNode,  "Literal");
-                    if (psTmpNode &&  psTmpNode->psChild &&
-                        psTmpNode->psChild->pszValue && 
-                        strlen(psTmpNode->psChild->pszValue) > 0)
-                    {
-                        /*
-                    if (psXMLNode->psChild->psNext->psNext->psNext->psNext->psChild &&
-                        psXMLNode->psChild->psNext->psNext->psNext->psNext->psChild->pszValue)
-                    {
-                        
-                        psFilterNode->psRightNode->pszValue = 
-                          msStrdup(psXMLNode->psChild->psNext->psNext->psNext->psNext->psChild->pszValue);        
-                        */
-                        psFilterNode->psRightNode->pszValue = 
-                          msStrdup(psTmpNode->psChild->pszValue);
-
-                        psFilterNode->psRightNode->eType = FILTER_NODE_TYPE_LITERAL;
-                    }
-                }
-                else
-                  psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
-                  
+        psDistance = CPLGetXMLNode(psXMLNode, "Distance");
+        if (psGMLElement && psDistance && psDistance->psChild &&
+            psDistance->psChild->psNext && psDistance->psChild->psNext->pszValue) {
+          pszUnits = (char *)CPLGetXMLValue(psDistance, "units", NULL);
+          psShape = (shapeObj *)msSmallMalloc(sizeof(shapeObj));
+          msInitShape(psShape);
+          if (FLTShapeFromGMLTree(psGMLElement, psShape, &pszSRS))
+            /* if (FLTGML2Shape_XMLNode(psPoint, psShape)) */
+          {
+            /*set the srs if available*/
+            if (pszSRS)
+              psFilterNode->pszSRS = pszSRS;
+
+            psFilterNode->psLeftNode = FLTCreateFilterEncodingNode();
+            /* not really using the property name anywhere ?? Is is always */
+            /* Geometry ?  */
+
+            psFilterNode->psLeftNode->eType = FILTER_NODE_TYPE_PROPERTYNAME;
+            psFilterNode->psLeftNode->pszValue = msStrdup("Geometry");
+
+            psFilterNode->psRightNode = FLTCreateFilterEncodingNode();
+            if (bPoint)
+              psFilterNode->psRightNode->eType = FILTER_NODE_TYPE_GEOMETRY_POINT;
+            else if (bLine)
+              psFilterNode->psRightNode->eType = FILTER_NODE_TYPE_GEOMETRY_LINE;
+            else if (bPolygon)
+              psFilterNode->psRightNode->eType = FILTER_NODE_TYPE_GEOMETRY_POLYGON;
+            psFilterNode->psRightNode->pOther = (shapeObj *)psShape;
+            /*the value will be distance;units*/
+            psFilterNode->psRightNode->pszValue =
+            msStrdup(psDistance->psChild->psNext->pszValue);
+            if (pszUnits) {
+              psFilterNode->psRightNode->pszValue= msStringConcatenate(psFilterNode->psRightNode->pszValue, ";");
+              psFilterNode->psRightNode->pszValue= msStringConcatenate(psFilterNode->psRightNode->pszValue, pszUnits);
             }
+          }
+        } else
+          psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
+      } else if (strcasecmp(psXMLNode->pszValue, "Intersect") == 0 ||
+                 strcasecmp(psXMLNode->pszValue, "Intersects") == 0 ||
+                 strcasecmp(psXMLNode->pszValue, "Equals") == 0 ||
+                 strcasecmp(psXMLNode->pszValue, "Disjoint") == 0 ||
+                 strcasecmp(psXMLNode->pszValue, "Touches") == 0 ||
+                 strcasecmp(psXMLNode->pszValue, "Crosses") == 0 ||
+                 strcasecmp(psXMLNode->pszValue, "Within") == 0 ||
+                 strcasecmp(psXMLNode->pszValue, "Contains") == 0 ||
+                 strcasecmp(psXMLNode->pszValue, "Overlaps") == 0) {
+        shapeObj *psShape = NULL;
+        int  bLine = 0, bPolygon = 0, bPoint=0;
+        char *pszSRS = NULL;
+
+
+        CPLXMLNode *psGMLElement = NULL;
+
+
+        psGMLElement = CPLGetXMLNode(psXMLNode, "Polygon");
+        if (psGMLElement)
+          bPolygon = 1;
+        else if ((psGMLElement= CPLGetXMLNode(psXMLNode, "MultiPolygon")))
+          bPolygon = 1;
+        else if ((psGMLElement= CPLGetXMLNode(psXMLNode, "MultiSurface")))
+          bPolygon = 1;
+        else if ((psGMLElement= CPLGetXMLNode(psXMLNode, "Box")))
+          bPolygon = 1;
+        else if ((psGMLElement= CPLGetXMLNode(psXMLNode, "LineString"))) {
+          if (psGMLElement)
+            bLine = 1;
         }
-/* -------------------------------------------------------------------- */
-/*      FeatureId Filter                                                */
-/*                                                                      */
-/*      <ogc:Filter>                                                    */
-/*      <ogc:FeatureId fid="INWATERA_1M.1013"/>                         */
-/*      <ogc:FeatureId fid="INWATERA_1M.10"/>                           */
-/*      <ogc:FeatureId fid="INWATERA_1M.13"/>                           */
-/*      <ogc:FeatureId fid="INWATERA_1M.140"/>                          */
-/*      <ogc:FeatureId fid="INWATERA_1M.5001"/>                         */
-/*      <ogc:FeatureId fid="INWATERA_1M.2001"/>                         */
-/*      </ogc:Filter>                                                   */
-/*                                                                      */
-/*                                                                      */
-/*      Note that for FES1.1.0 the featureid has been depricated in     */
-/*      favor of GmlObjectId                                            */
-/*      <GmlObjectId gml:id="TREESA_1M.1234"/>                          */
-/* -------------------------------------------------------------------- */
-        else if (FLTIsFeatureIdFilterType(psXMLNode->pszValue))
-        {
-            psFilterNode->eType = FILTER_NODE_TYPE_FEATUREID;
-            pszFeatureId = (char *)CPLGetXMLValue(psXMLNode, "fid", NULL);
-            /*for FE 1.1.0 GmlObjectId */
-            if (pszFeatureId == NULL)
-              pszFeatureId = (char *)CPLGetXMLValue(psXMLNode, "id", NULL);
-            pszFeatureIdList = NULL;
-            
-            psFeatureIdNode = psXMLNode;
-            while (psFeatureIdNode)
-            {
-                pszFeatureId = (char *)CPLGetXMLValue(psFeatureIdNode, "fid", NULL);
-                if (!pszFeatureId)
-                   pszFeatureId = (char *)CPLGetXMLValue(psFeatureIdNode, "id", NULL);
-
-                if (pszFeatureId)
-                {
-                    if (pszFeatureIdList)
-                      pszFeatureIdList = msStringConcatenate(pszFeatureIdList, ",");
-
-                    /*typname could be part of the value : INWATERA_1M.1234*/
-                    tokens = msStringSplit(pszFeatureId,'.', &nTokens);
-                    if (tokens && nTokens == 2)
-                      pszFeatureIdList = msStringConcatenate(pszFeatureIdList, tokens[1]);
-                    else
-                      pszFeatureIdList = msStringConcatenate(pszFeatureIdList, pszFeatureId);
-
-                    if (tokens)
-                      msFreeCharArray(tokens, nTokens);
-                }
-                psFeatureIdNode = psFeatureIdNode->psNext;
-            }
 
-            if (pszFeatureIdList)
-            {
-                psFilterNode->pszValue =  msStrdup(pszFeatureIdList);
-                msFree(pszFeatureIdList);
+        else {
+          psGMLElement = CPLGetXMLNode(psXMLNode, "Point");
+          if (!psGMLElement)
+            psGMLElement =  CPLGetXMLNode(psXMLNode, "PointType");
+          if (psGMLElement)
+            bPoint =1;
+        }
+
+        if (psGMLElement) {
+          psShape = (shapeObj *)msSmallMalloc(sizeof(shapeObj));
+          msInitShape(psShape);
+          if (FLTShapeFromGMLTree(psGMLElement, psShape, &pszSRS))
+            /* if (FLTGML2Shape_XMLNode(psPoint, psShape)) */
+          {
+            /*set the srs if available*/
+            if (pszSRS)
+              psFilterNode->pszSRS = pszSRS;
+
+            psFilterNode->psLeftNode = FLTCreateFilterEncodingNode();
+            /* not really using the property name anywhere ?? Is is always */
+            /* Geometry ?  */
+
+            psFilterNode->psLeftNode->eType = FILTER_NODE_TYPE_PROPERTYNAME;
+            psFilterNode->psLeftNode->pszValue = msStrdup("Geometry");
+
+            psFilterNode->psRightNode = FLTCreateFilterEncodingNode();
+            if (bPoint)
+              psFilterNode->psRightNode->eType = FILTER_NODE_TYPE_GEOMETRY_POINT;
+            if (bLine)
+              psFilterNode->psRightNode->eType = FILTER_NODE_TYPE_GEOMETRY_LINE;
+            else if (bPolygon)
+              psFilterNode->psRightNode->eType = FILTER_NODE_TYPE_GEOMETRY_POLYGON;
+            psFilterNode->psRightNode->pOther = (shapeObj *)psShape;
+
+          }
+        } else
+          psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
+      }
+
+
+    }/* end of is spatial */
+
+
+    /* -------------------------------------------------------------------- */
+    /*      Comparison Filter                                               */
+    /* -------------------------------------------------------------------- */
+    else if (FLTIsComparisonFilterType(psXMLNode->pszValue)) {
+      psFilterNode->eType = FILTER_NODE_TYPE_COMPARISON;
+      /* -------------------------------------------------------------------- */
+      /*      binary comaparison types. Example :                             */
+      /*                                                                      */
+      /*      <Filter>                                                        */
+      /*        <PropertyIsEqualTo>                                           */
+      /*          <PropertyName>SomeProperty</PropertyName>                   */
+      /*          <Literal>100</Literal>                                      */
+      /*        </PropertyIsEqualTo>                                          */
+      /*      </Filter>                                                       */
+      /* -------------------------------------------------------------------- */
+      if (FLTIsBinaryComparisonFilterType(psXMLNode->pszValue)) {
+        psTmpNode = CPLSearchXMLNode(psXMLNode,  "PropertyName");
+        if (psTmpNode &&  psTmpNode->psChild &&
+            psTmpNode->psChild->pszValue &&
+            strlen(psTmpNode->psChild->pszValue) > 0) {
+          psFilterNode->psLeftNode = FLTCreateFilterEncodingNode();
+          psFilterNode->psLeftNode->eType = FILTER_NODE_TYPE_PROPERTYNAME;
+          psFilterNode->psLeftNode->pszValue =
+            msStrdup(psTmpNode->psChild->pszValue);
+
+          psTmpNode = CPLSearchXMLNode(psXMLNode,  "Literal");
+          if (psTmpNode) {
+            psFilterNode->psRightNode = FLTCreateBinaryCompFilterEncodingNode();
+            psFilterNode->psRightNode->eType = FILTER_NODE_TYPE_LITERAL;
+
+            if (psTmpNode &&
+                psTmpNode->psChild &&
+                psTmpNode->psChild->pszValue &&
+                strlen(psTmpNode->psChild->pszValue) > 0) {
+
+              psFilterNode->psRightNode->pszValue =
+                msStrdup(psTmpNode->psChild->pszValue);
+
+              /*check if the matchCase attribute is set*/
+              if (psXMLNode->psChild &&
+                  psXMLNode->psChild->eType == CXT_Attribute  &&
+                  psXMLNode->psChild->pszValue &&
+                  strcasecmp(psXMLNode->psChild->pszValue, "matchCase") == 0 &&
+                  psXMLNode->psChild->psChild &&
+                  psXMLNode->psChild->psChild->pszValue &&
+                  strcasecmp( psXMLNode->psChild->psChild->pszValue, "false") == 0) {
+                (*(int *)psFilterNode->psRightNode->pOther) = 1;
+              }
+
             }
+            /* special case where the user puts an empty value */
+            /* for the Literal so it can end up as an empty  */
+            /* string query in the expression */
+            else
+              psFilterNode->psRightNode->pszValue = NULL;
+          }
+        }
+        if (psFilterNode->psLeftNode == NULL || psFilterNode->psRightNode == NULL)
+          psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
+      }
+
+      /* -------------------------------------------------------------------- */
+      /*      PropertyIsBetween filter : extract property name and boudary    */
+      /*      values. The boundary  values are stored in the right            */
+      /*      node. The values are separated by a semi-column (;)             */
+      /*      Eg of Filter :                                                  */
+      /*      <PropertyIsBetween>                                             */
+      /*         <PropertyName>DEPTH</PropertyName>                           */
+      /*         <LowerBoundary><Literal>400</Literal></LowerBoundary>        */
+      /*         <UpperBoundary><Literal>800</Literal></UpperBoundary>        */
+      /*      </PropertyIsBetween>                                            */
+      /*                                                                      */
+      /*      Or                                                              */
+      /*      <PropertyIsBetween>                                             */
+      /*         <PropertyName>DEPTH</PropertyName>                           */
+      /*         <LowerBoundary>400</LowerBoundary>                           */
+      /*         <UpperBoundary>800</UpperBoundary>                           */
+      /*      </PropertyIsBetween>                                            */
+      /* -------------------------------------------------------------------- */
+      else if (strcasecmp(psXMLNode->pszValue, "PropertyIsBetween") == 0) {
+        CPLXMLNode *psUpperNode = NULL, *psLowerNode = NULL;
+        if (psXMLNode->psChild &&
+            strcasecmp(psXMLNode->psChild->pszValue,
+                       "PropertyName") == 0 &&
+            psXMLNode->psChild->psNext &&
+            strcasecmp(psXMLNode->psChild->psNext->pszValue,
+                       "LowerBoundary") == 0 &&
+            psXMLNode->psChild->psNext->psNext &&
+            strcasecmp(psXMLNode->psChild->psNext->psNext->pszValue,
+                       "UpperBoundary") == 0) {
+          psFilterNode->psLeftNode = FLTCreateFilterEncodingNode();
+
+          if (psXMLNode->psChild->psChild &&
+              psXMLNode->psChild->psChild->pszValue) {
+            psFilterNode->psLeftNode->eType = FILTER_NODE_TYPE_PROPERTYNAME;
+            psFilterNode->psLeftNode->pszValue =
+              msStrdup(psXMLNode->psChild->psChild->pszValue);
+          }
+
+          psFilterNode->psRightNode = FLTCreateFilterEncodingNode();
+          if (psXMLNode->psChild->psNext->psChild &&
+              psXMLNode->psChild->psNext->psNext->psChild &&
+              psXMLNode->psChild->psNext->psChild->pszValue &&
+              psXMLNode->psChild->psNext->psNext->psChild->pszValue) {
+            /* check if the <Literals> is there */
+            psFilterNode->psRightNode->eType = FILTER_NODE_TYPE_BOUNDARY;
+            if (psXMLNode->psChild->psNext->psChild->psChild)
+              psLowerNode = psXMLNode->psChild->psNext->psChild->psChild;
+            else
+              psLowerNode = psXMLNode->psChild->psNext->psChild;
+
+            if (psXMLNode->psChild->psNext->psNext->psChild->psChild)
+              psUpperNode = psXMLNode->psChild->psNext->psNext->psChild->psChild;
             else
-               psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
+              psUpperNode = psXMLNode->psChild->psNext->psNext->psChild;
+
+            nStrLength =
+              strlen(psLowerNode->pszValue);
+            nStrLength +=
+              strlen(psUpperNode->pszValue);
+
+            nStrLength += 2; /* adding a ; between bounary values */
+            psFilterNode->psRightNode->pszValue =
+              (char *)malloc(sizeof(char)*(nStrLength));
+            strcpy( psFilterNode->psRightNode->pszValue,
+                    psLowerNode->pszValue);
+            strlcat(psFilterNode->psRightNode->pszValue, ";", nStrLength);
+            strlcat(psFilterNode->psRightNode->pszValue,
+                    psUpperNode->pszValue, nStrLength);
+          }
+
+
+        } else
+          psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
+
+      }/* end of PropertyIsBetween  */
+      /* -------------------------------------------------------------------- */
+      /*      PropertyIsLike                                                  */
+      /*                                                                      */
+      /*      <Filter>                                                        */
+      /*      <PropertyIsLike wildCard="*" singleChar="#" escape="!">         */
+      /*      <PropertyName>LAST_NAME</PropertyName>                          */
+      /*      <Literal>JOHN*</Literal>                                        */
+      /*      </PropertyIsLike>                                               */
+      /*      </Filter>                                                       */
+      /* -------------------------------------------------------------------- */
+      else if (strcasecmp(psXMLNode->pszValue, "PropertyIsLike") == 0) {
+        if (CPLSearchXMLNode(psXMLNode,  "Literal") &&
+            CPLSearchXMLNode(psXMLNode,  "PropertyName") &&
+            CPLGetXMLValue(psXMLNode, "wildCard", "") &&
+            CPLGetXMLValue(psXMLNode, "singleChar", "") &&
+            (CPLGetXMLValue(psXMLNode, "escape", "") ||
+             CPLGetXMLValue(psXMLNode, "escapeChar", "")))
+          /*
+            psXMLNode->psChild &&
+            strcasecmp(psXMLNode->psChild->pszValue, "wildCard") == 0 &&
+            psXMLNode->psChild->psNext &&
+            strcasecmp(psXMLNode->psChild->psNext->pszValue, "singleChar") == 0 &&
+            psXMLNode->psChild->psNext->psNext &&
+            strcasecmp(psXMLNode->psChild->psNext->psNext->pszValue, "escape") == 0 &&
+            psXMLNode->psChild->psNext->psNext->psNext &&
+            strcasecmp(psXMLNode->psChild->psNext->psNext->psNext->pszValue, "PropertyName") == 0 &&
+            psXMLNode->psChild->psNext->psNext->psNext->psNext &&
+            strcasecmp(psXMLNode->psChild->psNext->psNext->psNext->psNext->pszValue, "Literal") == 0)
+          */
+        {
+          /* -------------------------------------------------------------------- */
+          /*      Get the wildCard, the singleChar and the escapeChar used.       */
+          /* -------------------------------------------------------------------- */
+          psFilterNode->pOther = (FEPropertyIsLike *)malloc(sizeof(FEPropertyIsLike));
+          /*default is case sensitive*/
+          ((FEPropertyIsLike *)psFilterNode->pOther)->bCaseInsensitive = 0;
+
+          pszTmp = (char *)CPLGetXMLValue(psXMLNode, "wildCard", "");
+          if (pszTmp)
+            ((FEPropertyIsLike *)psFilterNode->pOther)->pszWildCard =
+              msStrdup(pszTmp);
+          pszTmp = (char *)CPLGetXMLValue(psXMLNode, "singleChar", "");
+          if (pszTmp)
+            ((FEPropertyIsLike *)psFilterNode->pOther)->pszSingleChar =
+              msStrdup(pszTmp);
+          pszTmp = (char *)CPLGetXMLValue(psXMLNode, "escape", "");
+          if (pszTmp && strlen(pszTmp)>0)
+            ((FEPropertyIsLike *)psFilterNode->pOther)->pszEscapeChar =
+              msStrdup(pszTmp);
+          else {
+            pszTmp = (char *)CPLGetXMLValue(psXMLNode, "escapeChar", "");
+            if (pszTmp)
+              ((FEPropertyIsLike *)psFilterNode->pOther)->pszEscapeChar =
+                msStrdup(pszTmp);
+          }
+          pszTmp = (char *)CPLGetXMLValue(psXMLNode, "matchCase", "");
+          if (pszTmp && strlen(pszTmp) > 0 &&
+              strcasecmp(pszTmp, "false") == 0) {
+            ((FEPropertyIsLike *)psFilterNode->pOther)->bCaseInsensitive =1;
+          }
+          /* -------------------------------------------------------------------- */
+          /*      Create left and right node for the attribute and the value.     */
+          /* -------------------------------------------------------------------- */
+          psFilterNode->psLeftNode = FLTCreateFilterEncodingNode();
+
+          psTmpNode = CPLSearchXMLNode(psXMLNode,  "PropertyName");
+          if (psTmpNode &&  psTmpNode->psChild &&
+              psTmpNode->psChild->pszValue &&
+              strlen(psTmpNode->psChild->pszValue) > 0)
+
+          {
+            /*
+            if (psXMLNode->psChild->psNext->psNext->psNext->psChild &&
+            psXMLNode->psChild->psNext->psNext->psNext->psChild->pszValue)
+            {
+            psFilterNode->psLeftNode->pszValue =
+              msStrdup(psXMLNode->psChild->psNext->psNext->psNext->psChild->pszValue);
+            */
+            psFilterNode->psLeftNode->pszValue =
+              msStrdup(psTmpNode->psChild->pszValue);
+            psFilterNode->psLeftNode->eType = FILTER_NODE_TYPE_PROPERTYNAME;
+
+          }
+
+          psFilterNode->psRightNode = FLTCreateFilterEncodingNode();
+
+
+          psTmpNode = CPLSearchXMLNode(psXMLNode,  "Literal");
+          if (psTmpNode &&  psTmpNode->psChild &&
+              psTmpNode->psChild->pszValue &&
+              strlen(psTmpNode->psChild->pszValue) > 0) {
+            /*
+            if (psXMLNode->psChild->psNext->psNext->psNext->psNext->psChild &&
+            psXMLNode->psChild->psNext->psNext->psNext->psNext->psChild->pszValue)
+            {
+
+            psFilterNode->psRightNode->pszValue =
+              msStrdup(psXMLNode->psChild->psNext->psNext->psNext->psNext->psChild->pszValue);
+            */
+            psFilterNode->psRightNode->pszValue =
+              msStrdup(psTmpNode->psChild->pszValue);
+
+            psFilterNode->psRightNode->eType = FILTER_NODE_TYPE_LITERAL;
+          }
+        } else
+          psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
+
+      }
+    }
+    /* -------------------------------------------------------------------- */
+    /*      FeatureId Filter                                                */
+    /*                                                                      */
+    /*      <ogc:Filter>                                                    */
+    /*      <ogc:FeatureId fid="INWATERA_1M.1013"/>                         */
+    /*      <ogc:FeatureId fid="INWATERA_1M.10"/>                           */
+    /*      <ogc:FeatureId fid="INWATERA_1M.13"/>                           */
+    /*      <ogc:FeatureId fid="INWATERA_1M.140"/>                          */
+    /*      <ogc:FeatureId fid="INWATERA_1M.5001"/>                         */
+    /*      <ogc:FeatureId fid="INWATERA_1M.2001"/>                         */
+    /*      </ogc:Filter>                                                   */
+    /*                                                                      */
+    /*                                                                      */
+    /*      Note that for FES1.1.0 the featureid has been depricated in     */
+    /*      favor of GmlObjectId                                            */
+    /*      <GmlObjectId gml:id="TREESA_1M.1234"/>                          */
+    /* -------------------------------------------------------------------- */
+    else if (FLTIsFeatureIdFilterType(psXMLNode->pszValue)) {
+      psFilterNode->eType = FILTER_NODE_TYPE_FEATUREID;
+      pszFeatureId = (char *)CPLGetXMLValue(psXMLNode, "fid", NULL);
+      /*for FE 1.1.0 GmlObjectId */
+      if (pszFeatureId == NULL)
+        pszFeatureId = (char *)CPLGetXMLValue(psXMLNode, "id", NULL);
+      pszFeatureIdList = NULL;
+
+      psFeatureIdNode = psXMLNode;
+      while (psFeatureIdNode) {
+        pszFeatureId = (char *)CPLGetXMLValue(psFeatureIdNode, "fid", NULL);
+        if (!pszFeatureId)
+          pszFeatureId = (char *)CPLGetXMLValue(psFeatureIdNode, "id", NULL);
+
+        if (pszFeatureId) {
+          if (pszFeatureIdList)
+            pszFeatureIdList = msStringConcatenate(pszFeatureIdList, ",");
+
+          /*typname could be part of the value : INWATERA_1M.1234*/
+          tokens = msStringSplit(pszFeatureId,'.', &nTokens);
+          if (tokens && nTokens == 2)
+            pszFeatureIdList = msStringConcatenate(pszFeatureIdList, tokens[1]);
+          else
+            pszFeatureIdList = msStringConcatenate(pszFeatureIdList, pszFeatureId);
+
+          if (tokens)
+            msFreeCharArray(tokens, nTokens);
         }
-            
+        psFeatureIdNode = psFeatureIdNode->psNext;
+      }
+
+      if (pszFeatureIdList) {
+        psFilterNode->pszValue =  msStrdup(pszFeatureIdList);
+        msFree(pszFeatureIdList);
+      } else
+        psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
     }
+
+  }
 }
 
- 
+
 /************************************************************************/
 /*            int FLTIsLogicalFilterType((char *pszValue)                  */
 /*                                                                      */
@@ -1528,15 +1637,14 @@ void FLTInsertElementInNode(FilterEncodingNode *psFilterNode,
 /************************************************************************/
 int FLTIsLogicalFilterType(char *pszValue)
 {
-    if (pszValue)
-    {
-        if (strcasecmp(pszValue, "AND") == 0 ||
-            strcasecmp(pszValue, "OR") == 0 ||
-             strcasecmp(pszValue, "NOT") == 0)
-           return MS_TRUE;
-    }
+  if (pszValue) {
+    if (strcasecmp(pszValue, "AND") == 0 ||
+        strcasecmp(pszValue, "OR") == 0 ||
+        strcasecmp(pszValue, "NOT") == 0)
+      return MS_TRUE;
+  }
 
-    return MS_FALSE;
+  return MS_FALSE;
 }
 
 /************************************************************************/
@@ -1546,18 +1654,17 @@ int FLTIsLogicalFilterType(char *pszValue)
 /************************************************************************/
 int FLTIsBinaryComparisonFilterType(char *pszValue)
 {
-    if (pszValue)
-    {
-         if (strcasecmp(pszValue, "PropertyIsEqualTo") == 0 ||  
-             strcasecmp(pszValue, "PropertyIsNotEqualTo") == 0 ||  
-             strcasecmp(pszValue, "PropertyIsLessThan") == 0 ||  
-             strcasecmp(pszValue, "PropertyIsGreaterThan") == 0 ||  
-             strcasecmp(pszValue, "PropertyIsLessThanOrEqualTo") == 0 ||  
-             strcasecmp(pszValue, "PropertyIsGreaterThanOrEqualTo") == 0)
-           return MS_TRUE;
-    }
+  if (pszValue) {
+    if (strcasecmp(pszValue, "PropertyIsEqualTo") == 0 ||
+        strcasecmp(pszValue, "PropertyIsNotEqualTo") == 0 ||
+        strcasecmp(pszValue, "PropertyIsLessThan") == 0 ||
+        strcasecmp(pszValue, "PropertyIsGreaterThan") == 0 ||
+        strcasecmp(pszValue, "PropertyIsLessThanOrEqualTo") == 0 ||
+        strcasecmp(pszValue, "PropertyIsGreaterThanOrEqualTo") == 0)
+      return MS_TRUE;
+  }
 
-    return MS_FALSE;
+  return MS_FALSE;
 }
 
 /************************************************************************/
@@ -1568,15 +1675,14 @@ int FLTIsBinaryComparisonFilterType(char *pszValue)
 /************************************************************************/
 int FLTIsComparisonFilterType(char *pszValue)
 {
-    if (pszValue)
-    {
-         if (FLTIsBinaryComparisonFilterType(pszValue) ||  
-             strcasecmp(pszValue, "PropertyIsLike") == 0 ||  
-             strcasecmp(pszValue, "PropertyIsBetween") == 0)
-           return MS_TRUE;
-    }
+  if (pszValue) {
+    if (FLTIsBinaryComparisonFilterType(pszValue) ||
+        strcasecmp(pszValue, "PropertyIsLike") == 0 ||
+        strcasecmp(pszValue, "PropertyIsBetween") == 0)
+      return MS_TRUE;
+  }
 
-    return MS_FALSE;
+  return MS_FALSE;
 }
 
 /************************************************************************/
@@ -1587,12 +1693,12 @@ int FLTIsComparisonFilterType(char *pszValue)
 /************************************************************************/
 int FLTIsFeatureIdFilterType(char *pszValue)
 {
-    if (pszValue && (strcasecmp(pszValue, "FeatureId") == 0 ||
-                     strcasecmp(pszValue, "GmlObjectId") == 0))
-                     
-      return MS_TRUE;
+  if (pszValue && (strcasecmp(pszValue, "FeatureId") == 0 ||
+                   strcasecmp(pszValue, "GmlObjectId") == 0))
+
+    return MS_TRUE;
 
-     return MS_FALSE;
+  return MS_FALSE;
 }
 
 /************************************************************************/
@@ -1603,24 +1709,23 @@ int FLTIsFeatureIdFilterType(char *pszValue)
 /************************************************************************/
 int FLTIsSpatialFilterType(char *pszValue)
 {
-    if (pszValue)
-    {
-        if ( strcasecmp(pszValue, "BBOX") == 0 ||
-             strcasecmp(pszValue, "DWithin") == 0 ||
-             strcasecmp(pszValue, "Intersect") == 0 ||
-             strcasecmp(pszValue, "Intersects") == 0 ||
-             strcasecmp(pszValue, "Equals") == 0 ||
-             strcasecmp(pszValue, "Disjoint") == 0 ||
-             strcasecmp(pszValue, "Touches") == 0 ||
-             strcasecmp(pszValue, "Crosses") == 0 ||
-             strcasecmp(pszValue, "Within") == 0 ||
-             strcasecmp(pszValue, "Contains") == 0 ||
-             strcasecmp(pszValue, "Overlaps") == 0 ||
-             strcasecmp(pszValue, "Beyond") == 0)
-          return MS_TRUE;
-    }
+  if (pszValue) {
+    if ( strcasecmp(pszValue, "BBOX") == 0 ||
+         strcasecmp(pszValue, "DWithin") == 0 ||
+         strcasecmp(pszValue, "Intersect") == 0 ||
+         strcasecmp(pszValue, "Intersects") == 0 ||
+         strcasecmp(pszValue, "Equals") == 0 ||
+         strcasecmp(pszValue, "Disjoint") == 0 ||
+         strcasecmp(pszValue, "Touches") == 0 ||
+         strcasecmp(pszValue, "Crosses") == 0 ||
+         strcasecmp(pszValue, "Within") == 0 ||
+         strcasecmp(pszValue, "Contains") == 0 ||
+         strcasecmp(pszValue, "Overlaps") == 0 ||
+         strcasecmp(pszValue, "Beyond") == 0)
+      return MS_TRUE;
+  }
 
-    return MS_FALSE;
+  return MS_FALSE;
 }
 
 /************************************************************************/
@@ -1631,18 +1736,17 @@ int FLTIsSpatialFilterType(char *pszValue)
 /************************************************************************/
 int FLTIsSupportedFilterType(CPLXMLNode *psXMLNode)
 {
-    if (psXMLNode)
-    {
-        if (FLTIsLogicalFilterType(psXMLNode->pszValue) ||
-            FLTIsSpatialFilterType(psXMLNode->pszValue) ||
-            FLTIsComparisonFilterType(psXMLNode->pszValue) ||
-            FLTIsFeatureIdFilterType(psXMLNode->pszValue))
-          return MS_TRUE;
-    }
+  if (psXMLNode) {
+    if (FLTIsLogicalFilterType(psXMLNode->pszValue) ||
+        FLTIsSpatialFilterType(psXMLNode->pszValue) ||
+        FLTIsComparisonFilterType(psXMLNode->pszValue) ||
+        FLTIsFeatureIdFilterType(psXMLNode->pszValue))
+      return MS_TRUE;
+  }
 
-    return MS_FALSE;
+  return MS_FALSE;
 }
- 
+
 /************************************************************************/
 /*                          FLTNumberOfFilterType                       */
 /*                                                                      */
@@ -1651,27 +1755,27 @@ int FLTIsSupportedFilterType(CPLXMLNode *psXMLNode)
 /************************************************************************/
 int FLTNumberOfFilterType(FilterEncodingNode *psFilterNode, const char *szType)
 {
-    int nCount = 0;
-    int nLeftNode=0 , nRightNode = 0;
+  int nCount = 0;
+  int nLeftNode=0 , nRightNode = 0;
 
-    if (!psFilterNode || !szType || !psFilterNode->pszValue)
-      return 0;
+  if (!psFilterNode || !szType || !psFilterNode->pszValue)
+    return 0;
 
-    if (strcasecmp(psFilterNode->pszValue, (char*)szType) == 0)
-      nCount++;
+  if (strcasecmp(psFilterNode->pszValue, (char*)szType) == 0)
+    nCount++;
 
-    if (psFilterNode->psLeftNode)
-      nLeftNode = FLTNumberOfFilterType(psFilterNode->psLeftNode, szType);
+  if (psFilterNode->psLeftNode)
+    nLeftNode = FLTNumberOfFilterType(psFilterNode->psLeftNode, szType);
 
-    nCount += nLeftNode;
+  nCount += nLeftNode;
 
-    if (psFilterNode->psRightNode)
-      nRightNode = FLTNumberOfFilterType(psFilterNode->psRightNode, szType);
-    nCount += nRightNode;
-   
-    return nCount;
+  if (psFilterNode->psRightNode)
+    nRightNode = FLTNumberOfFilterType(psFilterNode->psRightNode, szType);
+  nCount += nRightNode;
+
+  return nCount;
 }
-    
+
 
 
 
@@ -1710,169 +1814,162 @@ int FLTNumberOfFilterType(FilterEncodingNode *psFilterNode, const char *szType)
 /************************************************************************/
 int FLTValidForBBoxFilter(FilterEncodingNode *psFilterNode)
 {
-    int nCount = 0;
-   
-    if (!psFilterNode || !psFilterNode->pszValue)
-      return 1;
+  int nCount = 0;
 
-    nCount = FLTNumberOfFilterType(psFilterNode, "BBOX");
+  if (!psFilterNode || !psFilterNode->pszValue)
+    return 1;
 
-    if (nCount > 1)
-      return 0;
-    else if (nCount == 0)
-      return 1;
+  nCount = FLTNumberOfFilterType(psFilterNode, "BBOX");
 
-    /* nCount ==1  */
-    if (strcasecmp(psFilterNode->pszValue, "BBOX") == 0)
-      return 1;
+  if (nCount > 1)
+    return 0;
+  else if (nCount == 0)
+    return 1;
 
-    if (strcasecmp(psFilterNode->pszValue, "AND") == 0)
-    {
-      if (strcasecmp(psFilterNode->psLeftNode->pszValue, "BBOX") ==0 ||
-          strcasecmp(psFilterNode->psRightNode->pszValue, "BBOX") ==0)
-        return 1;
-    }
+  /* nCount ==1  */
+  if (strcasecmp(psFilterNode->pszValue, "BBOX") == 0)
+    return 1;
 
-    return 0;
-}    
+  if (strcasecmp(psFilterNode->pszValue, "AND") == 0) {
+    if (strcasecmp(psFilterNode->psLeftNode->pszValue, "BBOX") ==0 ||
+        strcasecmp(psFilterNode->psRightNode->pszValue, "BBOX") ==0)
+      return 1;
+  }
+
+  return 0;
+}
 
 int FLTIsLineFilter(FilterEncodingNode *psFilterNode)
 {
-    if (!psFilterNode || !psFilterNode->pszValue)
-      return 0;
+  if (!psFilterNode || !psFilterNode->pszValue)
+    return 0;
 
-    if (psFilterNode->eType == FILTER_NODE_TYPE_SPATIAL && 
-        psFilterNode->psRightNode &&  
-        psFilterNode->psRightNode->eType == FILTER_NODE_TYPE_GEOMETRY_LINE)
-      return 1;
+  if (psFilterNode->eType == FILTER_NODE_TYPE_SPATIAL &&
+      psFilterNode->psRightNode &&
+      psFilterNode->psRightNode->eType == FILTER_NODE_TYPE_GEOMETRY_LINE)
+    return 1;
 
-    return 0;
+  return 0;
 }
-  
+
 int FLTIsPolygonFilter(FilterEncodingNode *psFilterNode)
 {
-    if (!psFilterNode || !psFilterNode->pszValue)
-      return 0;
+  if (!psFilterNode || !psFilterNode->pszValue)
+    return 0;
 
-    if (psFilterNode->eType == FILTER_NODE_TYPE_SPATIAL && 
-        psFilterNode->psRightNode &&  
-        psFilterNode->psRightNode->eType == FILTER_NODE_TYPE_GEOMETRY_POLYGON)
-      return 1;
+  if (psFilterNode->eType == FILTER_NODE_TYPE_SPATIAL &&
+      psFilterNode->psRightNode &&
+      psFilterNode->psRightNode->eType == FILTER_NODE_TYPE_GEOMETRY_POLYGON)
+    return 1;
 
-    return 0;
+  return 0;
 }
-    
+
 int FLTIsPointFilter(FilterEncodingNode *psFilterNode)
 {
-    if (!psFilterNode || !psFilterNode->pszValue)
-      return 0;
+  if (!psFilterNode || !psFilterNode->pszValue)
+    return 0;
 
-    if (psFilterNode->eType == FILTER_NODE_TYPE_SPATIAL && 
-        psFilterNode->psRightNode &&  
-        psFilterNode->psRightNode->eType == FILTER_NODE_TYPE_GEOMETRY_POINT)
-      return 1;
+  if (psFilterNode->eType == FILTER_NODE_TYPE_SPATIAL &&
+      psFilterNode->psRightNode &&
+      psFilterNode->psRightNode->eType == FILTER_NODE_TYPE_GEOMETRY_POINT)
+    return 1;
 
-    return 0;
+  return 0;
 }
 
 int FLTIsBBoxFilter(FilterEncodingNode *psFilterNode)
 {
-    if (!psFilterNode || !psFilterNode->pszValue)
-      return 0;
-    
-    if (strcasecmp(psFilterNode->pszValue, "BBOX") == 0)
-      return 1;
-
-    /*    if (strcasecmp(psFilterNode->pszValue, "AND") == 0)
-    {
-      if (strcasecmp(psFilterNode->psLeftNode->pszValue, "BBOX") ==0 ||
-          strcasecmp(psFilterNode->psRightNode->pszValue, "BBOX") ==0)
-        return 1;
-    }
-    */
+  if (!psFilterNode || !psFilterNode->pszValue)
     return 0;
-}       
+
+  if (strcasecmp(psFilterNode->pszValue, "BBOX") == 0)
+    return 1;
+
+  /*    if (strcasecmp(psFilterNode->pszValue, "AND") == 0)
+  {
+    if (strcasecmp(psFilterNode->psLeftNode->pszValue, "BBOX") ==0 ||
+        strcasecmp(psFilterNode->psRightNode->pszValue, "BBOX") ==0)
+      return 1;
+  }
+  */
+  return 0;
+}
 
 shapeObj *FLTGetShape(FilterEncodingNode *psFilterNode, double *pdfDistance,
                       int *pnUnit)
 {
-    char **tokens = NULL;
-    int nTokens = 0;
-    FilterEncodingNode *psNode = psFilterNode;
-    char *szUnitStr = NULL;
-    char *szUnit = NULL;
-
-    if (psNode)
-    {
-        if (psNode->eType == FILTER_NODE_TYPE_SPATIAL && psNode->psRightNode)
-          psNode = psNode->psRightNode;
-
-        if (psNode->eType == FILTER_NODE_TYPE_GEOMETRY_POINT ||
-            psNode->eType == FILTER_NODE_TYPE_GEOMETRY_LINE ||
-            psNode->eType == FILTER_NODE_TYPE_GEOMETRY_POLYGON)
-        {
-            
-            if (psNode->pszValue && pdfDistance)
-            {
-                /*
-                sytnax expected is "distance;unit" or just "distance"
-                if unit is there syntax is "URI#unit" (eg http://..../#m)
-                or just "unit"
-                */
-                tokens = msStringSplit(psNode->pszValue,';', &nTokens);
-                if (tokens && nTokens >= 1)
-                {
-                    *pdfDistance = atof(tokens[0]);
-                
-                    if (nTokens == 2 && pnUnit)
-                    {
-                        szUnitStr = msStrdup(tokens[1]);
-                        msFreeCharArray(tokens, nTokens);
-                        nTokens = 0;
-                        tokens = msStringSplit(szUnitStr,'#', &nTokens);
-                        msFree(szUnitStr);
-                        if (tokens && nTokens >= 1)
-                        {
-                            if (nTokens ==1)
-                              szUnit = tokens[0];
-                            else
-                              szUnit = tokens[1];
-
-                            if (strcasecmp(szUnit,"m") == 0 ||
-                                strcasecmp(szUnit,"meters") == 0 )
-                              *pnUnit = MS_METERS;
-                            else if (strcasecmp(szUnit,"km") == 0 || 
-                                     strcasecmp(szUnit,"kilometers") == 0)
-                              *pnUnit = MS_KILOMETERS;
-                            else if (strcasecmp(szUnit,"NM") == 0 || 
-                                     strcasecmp(szUnit,"nauticalmiles") == 0)
-                              *pnUnit = MS_NAUTICALMILES;
-                            else if (strcasecmp(szUnit,"mi") == 0 || 
-                                     strcasecmp(szUnit,"miles") == 0)
-                              *pnUnit = MS_MILES;
-                            else if (strcasecmp(szUnit,"in") == 0 ||
-                                    strcasecmp(szUnit,"inches") == 0)
-                              *pnUnit = MS_INCHES;
-                           else if (strcasecmp(szUnit,"ft") == 0 ||
-                                    strcasecmp(szUnit,"feet") == 0)
-                             *pnUnit = MS_FEET;
-                           else if (strcasecmp(szUnit,"deg") == 0 ||
-                                    strcasecmp(szUnit,"dd") == 0)
-                              *pnUnit = MS_DD;
-                             else if (strcasecmp(szUnit,"px") == 0)
-                              *pnUnit = MS_PIXELS;
-                            
-                             msFreeCharArray(tokens, nTokens);
-                        }
-                    }
-                }       
-                           
-            }
+  char **tokens = NULL;
+  int nTokens = 0;
+  FilterEncodingNode *psNode = psFilterNode;
+  char *szUnitStr = NULL;
+  char *szUnit = NULL;
+
+  if (psNode) {
+    if (psNode->eType == FILTER_NODE_TYPE_SPATIAL && psNode->psRightNode)
+      psNode = psNode->psRightNode;
+
+    if (psNode->eType == FILTER_NODE_TYPE_GEOMETRY_POINT ||
+        psNode->eType == FILTER_NODE_TYPE_GEOMETRY_LINE ||
+        psNode->eType == FILTER_NODE_TYPE_GEOMETRY_POLYGON) {
+
+      if (psNode->pszValue && pdfDistance) {
+        /*
+        sytnax expected is "distance;unit" or just "distance"
+        if unit is there syntax is "URI#unit" (eg http://..../#m)
+        or just "unit"
+        */
+        tokens = msStringSplit(psNode->pszValue,';', &nTokens);
+        if (tokens && nTokens >= 1) {
+          *pdfDistance = atof(tokens[0]);
+
+          if (nTokens == 2 && pnUnit) {
+            szUnitStr = msStrdup(tokens[1]);
+            msFreeCharArray(tokens, nTokens);
+            nTokens = 0;
+            tokens = msStringSplit(szUnitStr,'#', &nTokens);
+            msFree(szUnitStr);
+            if (tokens && nTokens >= 1) {
+              if (nTokens ==1)
+                szUnit = tokens[0];
+              else
+                szUnit = tokens[1];
+
+              if (strcasecmp(szUnit,"m") == 0 ||
+                  strcasecmp(szUnit,"meters") == 0 )
+                *pnUnit = MS_METERS;
+              else if (strcasecmp(szUnit,"km") == 0 ||
+                       strcasecmp(szUnit,"kilometers") == 0)
+                *pnUnit = MS_KILOMETERS;
+              else if (strcasecmp(szUnit,"NM") == 0 ||
+                       strcasecmp(szUnit,"nauticalmiles") == 0)
+                *pnUnit = MS_NAUTICALMILES;
+              else if (strcasecmp(szUnit,"mi") == 0 ||
+                       strcasecmp(szUnit,"miles") == 0)
+                *pnUnit = MS_MILES;
+              else if (strcasecmp(szUnit,"in") == 0 ||
+                       strcasecmp(szUnit,"inches") == 0)
+                *pnUnit = MS_INCHES;
+              else if (strcasecmp(szUnit,"ft") == 0 ||
+                       strcasecmp(szUnit,"feet") == 0)
+                *pnUnit = MS_FEET;
+              else if (strcasecmp(szUnit,"deg") == 0 ||
+                       strcasecmp(szUnit,"dd") == 0)
+                *pnUnit = MS_DD;
+              else if (strcasecmp(szUnit,"px") == 0)
+                *pnUnit = MS_PIXELS;
 
-            return (shapeObj *)psNode->pOther;
+              msFreeCharArray(tokens, nTokens);
+            }
+          }
         }
+
+      }
+
+      return (shapeObj *)psNode->pOther;
     }
-    return NULL;   
+  }
+  return NULL;
 }
 
 /************************************************************************/
@@ -1884,34 +1981,30 @@ shapeObj *FLTGetShape(FilterEncodingNode *psFilterNode, double *pdfDistance,
 /************************************************************************/
 char *FLTGetBBOX(FilterEncodingNode *psFilterNode, rectObj *psRect)
 {
-    char *pszReturn = NULL;
-    
-    if (!psFilterNode || !psRect)
-      return NULL;
+  char *pszReturn = NULL;
+
+  if (!psFilterNode || !psRect)
+    return NULL;
+
+  if (psFilterNode->pszValue && strcasecmp(psFilterNode->pszValue, "BBOX") == 0) {
+    if (psFilterNode->psRightNode && psFilterNode->psRightNode->pOther) {
+      psRect->minx = ((rectObj *)psFilterNode->psRightNode->pOther)->minx;
+      psRect->miny = ((rectObj *)psFilterNode->psRightNode->pOther)->miny;
+      psRect->maxx = ((rectObj *)psFilterNode->psRightNode->pOther)->maxx;
+      psRect->maxy = ((rectObj *)psFilterNode->psRightNode->pOther)->maxy;
+
+      return psFilterNode->psRightNode->pszValue;
 
-    if (psFilterNode->pszValue && strcasecmp(psFilterNode->pszValue, "BBOX") == 0)
-    {
-        if (psFilterNode->psRightNode && psFilterNode->psRightNode->pOther)
-        {
-            psRect->minx = ((rectObj *)psFilterNode->psRightNode->pOther)->minx;
-            psRect->miny = ((rectObj *)psFilterNode->psRightNode->pOther)->miny;
-            psRect->maxx = ((rectObj *)psFilterNode->psRightNode->pOther)->maxx;
-            psRect->maxy = ((rectObj *)psFilterNode->psRightNode->pOther)->maxy;
-            
-            return psFilterNode->psRightNode->pszValue;
-            
-        }
     }
+  } else {
+    pszReturn = FLTGetBBOX(psFilterNode->psLeftNode, psRect);
+    if (pszReturn)
+      return pszReturn;
     else
-    {
-        pszReturn = FLTGetBBOX(psFilterNode->psLeftNode, psRect);
-        if (pszReturn)
-          return pszReturn;
-        else
-          return  FLTGetBBOX(psFilterNode->psRightNode, psRect);
-    }
+      return  FLTGetBBOX(psFilterNode->psRightNode, psRect);
+  }
 
-    return pszReturn;
+  return pszReturn;
 }
 
 /************************************************************************/
@@ -1921,98 +2014,77 @@ char *FLTGetBBOX(FilterEncodingNode *psFilterNode, rectObj *psRect)
 /************************************************************************/
 char *FLTGetMapserverExpression(FilterEncodingNode *psFilterNode, layerObj *lp)
 {
-    char *pszExpression = NULL;
-    const char *pszAttribute = NULL;
-    char szTmp[256];
-    char **tokens = NULL;
-    int nTokens = 0, i=0,bString=0;
-    char *pszTmp;
-    
-    if (!psFilterNode)
-      return NULL;
+  char *pszExpression = NULL;
+  const char *pszAttribute = NULL;
+  char szTmp[256];
+  char **tokens = NULL;
+  int nTokens = 0, i=0,bString=0;
+  char *pszTmp;
+
+  if (!psFilterNode)
+    return NULL;
 
-    if (psFilterNode->eType == FILTER_NODE_TYPE_COMPARISON)
-    {
-        if ( psFilterNode->psLeftNode && psFilterNode->psRightNode)
-        {
-            if (FLTIsBinaryComparisonFilterType(psFilterNode->pszValue))
-            {
-              pszExpression = FLTGetBinaryComparisonExpresssion(psFilterNode, lp);
-            }
-            else if (strcasecmp(psFilterNode->pszValue, 
-                                "PropertyIsBetween") == 0)
-            {
-              pszExpression = FLTGetIsBetweenComparisonExpresssion(psFilterNode, lp);
-            }
-            else if (strcasecmp(psFilterNode->pszValue, 
-                                "PropertyIsLike") == 0)
-            {
-                 pszExpression = FLTGetIsLikeComparisonExpression(psFilterNode);
-            }
-        }
-    }
-    else if (psFilterNode->eType == FILTER_NODE_TYPE_LOGICAL)
-    {
-        if (strcasecmp(psFilterNode->pszValue, "AND") == 0 ||
-            strcasecmp(psFilterNode->pszValue, "OR") == 0)
-        {
-          pszExpression = FLTGetLogicalComparisonExpresssion(psFilterNode, lp);
-        }
-        else if (strcasecmp(psFilterNode->pszValue, "NOT") == 0)
-        {       
-          pszExpression = FLTGetLogicalComparisonExpresssion(psFilterNode, lp);
-        }
+  if (psFilterNode->eType == FILTER_NODE_TYPE_COMPARISON) {
+    if ( psFilterNode->psLeftNode && psFilterNode->psRightNode) {
+      if (FLTIsBinaryComparisonFilterType(psFilterNode->pszValue)) {
+        pszExpression = FLTGetBinaryComparisonExpresssion(psFilterNode, lp);
+      } else if (strcasecmp(psFilterNode->pszValue,
+                            "PropertyIsBetween") == 0) {
+        pszExpression = FLTGetIsBetweenComparisonExpresssion(psFilterNode, lp);
+      } else if (strcasecmp(psFilterNode->pszValue,
+                            "PropertyIsLike") == 0) {
+        pszExpression = FLTGetIsLikeComparisonExpression(psFilterNode);
+      }
     }
-    else if (psFilterNode->eType == FILTER_NODE_TYPE_SPATIAL)
-    {
-        /* TODO */
+  } else if (psFilterNode->eType == FILTER_NODE_TYPE_LOGICAL) {
+    if (strcasecmp(psFilterNode->pszValue, "AND") == 0 ||
+        strcasecmp(psFilterNode->pszValue, "OR") == 0) {
+      pszExpression = FLTGetLogicalComparisonExpresssion(psFilterNode, lp);
+    } else if (strcasecmp(psFilterNode->pszValue, "NOT") == 0) {
+      pszExpression = FLTGetLogicalComparisonExpresssion(psFilterNode, lp);
     }
-    else if (psFilterNode->eType == FILTER_NODE_TYPE_FEATUREID)
-    {
+  } else if (psFilterNode->eType == FILTER_NODE_TYPE_SPATIAL) {
+    /* TODO */
+  } else if (psFilterNode->eType == FILTER_NODE_TYPE_FEATUREID) {
 #if defined(USE_WMS_SVR) || defined (USE_WFS_SVR) || defined (USE_WCS_SVR) || defined(USE_SOS_SVR)
-       if (psFilterNode->pszValue)
-       {
-            pszAttribute = msOWSLookupMetadata(&(lp->metadata), "OFG", "featureid");
-            if (pszAttribute)
-            {
-                tokens = msStringSplit(psFilterNode->pszValue,',', &nTokens);
-                if (tokens && nTokens > 0)
-                {
-                    for (i=0; i<nTokens; i++)
-                    {   
-                        if (i == 0)
-                        {
-                            pszTmp = tokens[0];
-                            if(FLTIsNumeric(pszTmp) == MS_FALSE) 
-                              bString = 1;
-                        }
-                        if (bString)
-                            snprintf(szTmp, sizeof(szTmp), "('[%s]' = '%s')" , pszAttribute, tokens[i]);
-                        else
-                            snprintf(szTmp, sizeof(szTmp), "([%s] = %s)" , pszAttribute, tokens[i]);
-
-                        if (pszExpression != NULL)
-                          pszExpression = msStringConcatenate(pszExpression, " OR ");
-                        else
-                          pszExpression = msStringConcatenate(pszExpression, "(");
-                        pszExpression = msStringConcatenate(pszExpression, szTmp);
-                    }
-
-                    msFreeCharArray(tokens, nTokens);
-                }
-            }   
-            /*opening and closing brackets are needed for mapserver expressions*/
-            if (pszExpression)
-               pszExpression = msStringConcatenate(pszExpression, ")");
+    if (psFilterNode->pszValue) {
+      pszAttribute = msOWSLookupMetadata(&(lp->metadata), "OFG", "featureid");
+      if (pszAttribute) {
+        tokens = msStringSplit(psFilterNode->pszValue,',', &nTokens);
+        if (tokens && nTokens > 0) {
+          for (i=0; i<nTokens; i++) {
+            if (i == 0) {
+              pszTmp = tokens[0];
+              if(FLTIsNumeric(pszTmp) == MS_FALSE)
+                bString = 1;
+            }
+            if (bString)
+              snprintf(szTmp, sizeof(szTmp), "('[%s]' = '%s')" , pszAttribute, tokens[i]);
+            else
+              snprintf(szTmp, sizeof(szTmp), "([%s] = %s)" , pszAttribute, tokens[i]);
+
+            if (pszExpression != NULL)
+              pszExpression = msStringConcatenate(pszExpression, " OR ");
+            else
+              pszExpression = msStringConcatenate(pszExpression, "(");
+            pszExpression = msStringConcatenate(pszExpression, szTmp);
+          }
+
+          msFreeCharArray(tokens, nTokens);
         }
+      }
+      /*opening and closing brackets are needed for mapserver expressions*/
+      if (pszExpression)
+        pszExpression = msStringConcatenate(pszExpression, ")");
+    }
 #else
-       msSetError(MS_MISCERR, "OWS support is not available.", 
-                   "FLTGetMapserverExpression()");
+    msSetError(MS_MISCERR, "OWS support is not available.",
+               "FLTGetMapserverExpression()");
     return(MS_FAILURE);
 #endif
 
-    }
-    return pszExpression;
+  }
+  return pszExpression;
 }
 
 
@@ -2023,119 +2095,98 @@ char *FLTGetMapserverExpression(FilterEncodingNode *psFilterNode, layerObj *lp)
 /************************************************************************/
 char *FLTGetSQLExpression(FilterEncodingNode *psFilterNode, layerObj *lp)
 {
-    char *pszExpression = NULL;
-    int connectiontype;
-    const char *pszAttribute = NULL;
-    char szTmp[256];
-    char **tokens = NULL;
-    int nTokens = 0, i=0, bString=0;
-
-    if (psFilterNode == NULL || lp == NULL)
-      return NULL;
+  char *pszExpression = NULL;
+  const char *pszAttribute = NULL;
+  char szTmp[256];
+  char **tokens = NULL;
+  int nTokens = 0, i=0, bString=0;
 
-    connectiontype = lp->connectiontype;
-    if (psFilterNode->eType == FILTER_NODE_TYPE_COMPARISON)
-    {
-        if ( psFilterNode->psLeftNode && psFilterNode->psRightNode)
-        {
-            if (FLTIsBinaryComparisonFilterType(psFilterNode->pszValue))
-            {
-                pszExpression = 
-                  FLTGetBinaryComparisonSQLExpresssion(psFilterNode, lp);
-            }            
-            else if (strcasecmp(psFilterNode->pszValue, 
-                                "PropertyIsBetween") == 0)
-            {
-                 pszExpression = 
-                   FLTGetIsBetweenComparisonSQLExpresssion(psFilterNode, lp);
-            }
-            else if (strcasecmp(psFilterNode->pszValue, 
-                                "PropertyIsLike") == 0)
-            {
-                 pszExpression = 
-                   FLTGetIsLikeComparisonSQLExpression(psFilterNode, lp);
+  if (psFilterNode == NULL || lp == NULL)
+    return NULL;
 
-            }
-        }
+  if (psFilterNode->eType == FILTER_NODE_TYPE_COMPARISON) {
+    if ( psFilterNode->psLeftNode && psFilterNode->psRightNode) {
+      if (FLTIsBinaryComparisonFilterType(psFilterNode->pszValue)) {
+        pszExpression =
+          FLTGetBinaryComparisonSQLExpresssion(psFilterNode, lp);
+      } else if (strcasecmp(psFilterNode->pszValue,
+                            "PropertyIsBetween") == 0) {
+        pszExpression =
+          FLTGetIsBetweenComparisonSQLExpresssion(psFilterNode, lp);
+      } else if (strcasecmp(psFilterNode->pszValue,
+                            "PropertyIsLike") == 0) {
+        pszExpression =
+          FLTGetIsLikeComparisonSQLExpression(psFilterNode, lp);
+
+      }
     }
-    else if (psFilterNode->eType == FILTER_NODE_TYPE_LOGICAL)
-    {
-        if (strcasecmp(psFilterNode->pszValue, "AND") == 0 ||
-            strcasecmp(psFilterNode->pszValue, "OR") == 0)
-        {
-            pszExpression =
-              FLTGetLogicalComparisonSQLExpresssion(psFilterNode, lp);
+  } else if (psFilterNode->eType == FILTER_NODE_TYPE_LOGICAL) {
+    if (strcasecmp(psFilterNode->pszValue, "AND") == 0 ||
+        strcasecmp(psFilterNode->pszValue, "OR") == 0) {
+      pszExpression =
+        FLTGetLogicalComparisonSQLExpresssion(psFilterNode, lp);
 
-        }
-        else if (strcasecmp(psFilterNode->pszValue, "NOT") == 0)
-        {       
-            pszExpression = 
-              FLTGetLogicalComparisonSQLExpresssion(psFilterNode, lp);
+    } else if (strcasecmp(psFilterNode->pszValue, "NOT") == 0) {
+      pszExpression =
+        FLTGetLogicalComparisonSQLExpresssion(psFilterNode, lp);
 
-        }
-    }
-    
-    else if (psFilterNode->eType == FILTER_NODE_TYPE_SPATIAL)
-    {
-        /* TODO */
     }
-    else if (psFilterNode->eType == FILTER_NODE_TYPE_FEATUREID)
-    {
+  }
+
+  else if (psFilterNode->eType == FILTER_NODE_TYPE_SPATIAL) {
+    /* TODO */
+  } else if (psFilterNode->eType == FILTER_NODE_TYPE_FEATUREID) {
 #if defined(USE_WMS_SVR) || defined (USE_WFS_SVR) || defined (USE_WCS_SVR) || defined(USE_SOS_SVR)
-        if (psFilterNode->pszValue)
-        {
-            pszAttribute = msOWSLookupMetadata(&(lp->metadata), "OFG", "featureid");
-            if (pszAttribute)
-            {
-                tokens = msStringSplit(psFilterNode->pszValue,',', &nTokens);
-                bString = 0;
-                if (tokens && nTokens > 0)
-                {
-                    for (i=0; i<nTokens; i++)
-                    {
-                        char *pszEscapedStr = NULL;
-                        if (strlen(tokens[i]) <= 0)
-                          continue;
-
-                        if (FLTIsNumeric((tokens[i])) == MS_FALSE)    
-                          bString = 1;
-
-                        pszEscapedStr = msLayerEscapeSQLParam(lp, tokens[i]);
-                        if (bString)
-                            snprintf(szTmp, sizeof(szTmp), "(%s = '%s')" , pszAttribute, pszEscapedStr);
-                        else
-                            snprintf(szTmp, sizeof(szTmp), "(%s = %s)" , pszAttribute, pszEscapedStr);
-
-                        msFree(pszEscapedStr);
-                        pszEscapedStr=NULL;
-
-                        if (pszExpression != NULL)
-                          pszExpression = msStringConcatenate(pszExpression, " OR ");
-                        else
-                          /*opening and closing brackets*/
-                          pszExpression = msStringConcatenate(pszExpression, "(");
-
-                        pszExpression = msStringConcatenate(pszExpression, szTmp);
-                    }
-
-                    msFreeCharArray(tokens, nTokens);
-                }
-            }
-            /*opening and closing brackets*/
-            if (pszExpression)
-               pszExpression = msStringConcatenate(pszExpression, ")");
+    if (psFilterNode->pszValue) {
+      pszAttribute = msOWSLookupMetadata(&(lp->metadata), "OFG", "featureid");
+      if (pszAttribute) {
+        tokens = msStringSplit(psFilterNode->pszValue,',', &nTokens);
+        bString = 0;
+        if (tokens && nTokens > 0) {
+          for (i=0; i<nTokens; i++) {
+            char *pszEscapedStr = NULL;
+            if (strlen(tokens[i]) <= 0)
+              continue;
+
+            if (FLTIsNumeric((tokens[i])) == MS_FALSE)
+              bString = 1;
+
+            pszEscapedStr = msLayerEscapeSQLParam(lp, tokens[i]);
+            if (bString)
+              snprintf(szTmp, sizeof(szTmp), "(%s = '%s')" , pszAttribute, pszEscapedStr);
+            else
+              snprintf(szTmp, sizeof(szTmp), "(%s = %s)" , pszAttribute, pszEscapedStr);
+
+            msFree(pszEscapedStr);
+            pszEscapedStr=NULL;
+
+            if (pszExpression != NULL)
+              pszExpression = msStringConcatenate(pszExpression, " OR ");
+            else
+              /*opening and closing brackets*/
+              pszExpression = msStringConcatenate(pszExpression, "(");
+
+            pszExpression = msStringConcatenate(pszExpression, szTmp);
+          }
+
+          msFreeCharArray(tokens, nTokens);
         }
+      }
+      /*opening and closing brackets*/
+      if (pszExpression)
+        pszExpression = msStringConcatenate(pszExpression, ")");
+    }
 #else
-        msSetError(MS_MISCERR, "OWS support is not available.", 
-                   "FLTGetSQLExpression()");
+    msSetError(MS_MISCERR, "OWS support is not available.",
+               "FLTGetSQLExpression()");
     return(MS_FAILURE);
 #endif
 
-    }
-    
-    return pszExpression;
+  }
+
+  return pszExpression;
 }
-  
+
 /************************************************************************/
 /*                            FLTGetNodeExpression                      */
 /*                                                                      */
@@ -2143,23 +2194,22 @@ char *FLTGetSQLExpression(FilterEncodingNode *psFilterNode, layerObj *lp)
 /************************************************************************/
 char *FLTGetNodeExpression(FilterEncodingNode *psFilterNode, layerObj *lp)
 {
-    char *pszExpression = NULL;
-    if (!psFilterNode)
-      return NULL;
-
-    if (FLTIsLogicalFilterType(psFilterNode->pszValue))
-      pszExpression = FLTGetLogicalComparisonExpresssion(psFilterNode, lp);
-    else if (FLTIsComparisonFilterType(psFilterNode->pszValue))
-    {
-        if (FLTIsBinaryComparisonFilterType(psFilterNode->pszValue))
-          pszExpression = FLTGetBinaryComparisonExpresssion(psFilterNode, lp);
-        else if (strcasecmp(psFilterNode->pszValue, "PropertyIsBetween") == 0)
-          pszExpression = FLTGetIsBetweenComparisonExpresssion(psFilterNode, lp);
-        else if (strcasecmp(psFilterNode->pszValue, "PropertyIsLike") == 0)
-          pszExpression = FLTGetIsLikeComparisonExpression(psFilterNode);
-    }
+  char *pszExpression = NULL;
+  if (!psFilterNode)
+    return NULL;
 
-    return pszExpression;
+  if (FLTIsLogicalFilterType(psFilterNode->pszValue))
+    pszExpression = FLTGetLogicalComparisonExpresssion(psFilterNode, lp);
+  else if (FLTIsComparisonFilterType(psFilterNode->pszValue)) {
+    if (FLTIsBinaryComparisonFilterType(psFilterNode->pszValue))
+      pszExpression = FLTGetBinaryComparisonExpresssion(psFilterNode, lp);
+    else if (strcasecmp(psFilterNode->pszValue, "PropertyIsBetween") == 0)
+      pszExpression = FLTGetIsBetweenComparisonExpresssion(psFilterNode, lp);
+    else if (strcasecmp(psFilterNode->pszValue, "PropertyIsLike") == 0)
+      pszExpression = FLTGetIsLikeComparisonExpression(psFilterNode);
+  }
+
+  return pszExpression;
 }
 
 
@@ -2169,94 +2219,87 @@ char *FLTGetNodeExpression(FilterEncodingNode *psFilterNode, layerObj *lp)
 /*      Return the expression for logical comparison expression.        */
 /************************************************************************/
 char *FLTGetLogicalComparisonSQLExpresssion(FilterEncodingNode *psFilterNode,
-                                            layerObj *lp)
+    layerObj *lp)
 {
-    char *pszBuffer = NULL;
-    char *pszTmp = NULL;
-    int nTmp = 0;
-    int connectiontype;
+  char *pszBuffer = NULL;
+  char *pszTmp = NULL;
+  int nTmp = 0;
+
+  if (lp == NULL)
+    return NULL;
+
+  /* ==================================================================== */
+  /*      special case for BBOX node.                                     */
+  /* ==================================================================== */
+  if (psFilterNode->psLeftNode && psFilterNode->psRightNode &&
+      ((strcasecmp(psFilterNode->psLeftNode->pszValue, "BBOX") == 0) ||
+       (strcasecmp(psFilterNode->psRightNode->pszValue, "BBOX") == 0))) {
+    if (strcasecmp(psFilterNode->psLeftNode->pszValue, "BBOX") != 0)
+      pszTmp = FLTGetSQLExpression(psFilterNode->psLeftNode, lp);
+    else
+      pszTmp = FLTGetSQLExpression(psFilterNode->psRightNode, lp);
 
-    if (lp == NULL)
+    if (!pszTmp)
       return NULL;
 
-    connectiontype = lp->connectiontype;
-
-/* ==================================================================== */
-/*      special case for BBOX node.                                     */
-/* ==================================================================== */
-    if (psFilterNode->psLeftNode && psFilterNode->psRightNode &&
-        ((strcasecmp(psFilterNode->psLeftNode->pszValue, "BBOX") == 0) ||
-         (strcasecmp(psFilterNode->psRightNode->pszValue, "BBOX") == 0)))
-    {
-         if (strcasecmp(psFilterNode->psLeftNode->pszValue, "BBOX") != 0)
-           pszTmp = FLTGetSQLExpression(psFilterNode->psLeftNode, lp);
-         else
-           pszTmp = FLTGetSQLExpression(psFilterNode->psRightNode, lp);
-           
-         if (!pszTmp)
-          return NULL;
-
-         pszBuffer = (char *)malloc(sizeof(char) * (strlen(pszTmp) + 1));
-         sprintf(pszBuffer, "%s", pszTmp);
-    }
+    pszBuffer = (char *)malloc(sizeof(char) * (strlen(pszTmp) + 1));
+    sprintf(pszBuffer, "%s", pszTmp);
+  }
 
-/* -------------------------------------------------------------------- */
-/*      OR and AND                                                      */
-/* -------------------------------------------------------------------- */
-    else if (psFilterNode->psLeftNode && psFilterNode->psRightNode)
-    {
-        pszTmp = FLTGetSQLExpression(psFilterNode->psLeftNode, lp);
-        if (!pszTmp)
-          return NULL;
-
-        pszBuffer = (char *)malloc(sizeof(char) * 
-                                    (strlen(pszTmp) + 
-                                     strlen(psFilterNode->pszValue) + 5));
-        pszBuffer[0] = '\0';
-        strcat(pszBuffer, " (");
-        strcat(pszBuffer, pszTmp);
-        strcat(pszBuffer, " ");
-        strcat(pszBuffer, psFilterNode->pszValue);
-        strcat(pszBuffer, " ");
-
-        free( pszTmp );
-
-        nTmp = strlen(pszBuffer);
-        pszTmp = FLTGetSQLExpression(psFilterNode->psRightNode, lp);
-        if (!pszTmp)
-          return NULL;
-
-        pszBuffer = (char *)realloc(pszBuffer, 
-                                    sizeof(char) * (strlen(pszTmp) + nTmp +3));
-        strcat(pszBuffer, pszTmp);
-        strcat(pszBuffer, ") ");
-    }
-/* -------------------------------------------------------------------- */
-/*      NOT                                                             */
-/* -------------------------------------------------------------------- */
-    else if (psFilterNode->psLeftNode && 
-             strcasecmp(psFilterNode->pszValue, "NOT") == 0)
-    {
-        pszTmp = FLTGetSQLExpression(psFilterNode->psLeftNode, lp);
-        if (!pszTmp)
-          return NULL;
-        
-        pszBuffer = (char *)malloc(sizeof(char) * (strlen(pszTmp) +  9));
-        pszBuffer[0] = '\0';
-
-        strcat(pszBuffer, " (NOT ");
-        strcat(pszBuffer, pszTmp);
-        strcat(pszBuffer, ") ");
-    }
-    else
+  /* -------------------------------------------------------------------- */
+  /*      OR and AND                                                      */
+  /* -------------------------------------------------------------------- */
+  else if (psFilterNode->psLeftNode && psFilterNode->psRightNode) {
+    pszTmp = FLTGetSQLExpression(psFilterNode->psLeftNode, lp);
+    if (!pszTmp)
       return NULL;
 
-/* -------------------------------------------------------------------- */
-/*      Cleanup.                                                        */
-/* -------------------------------------------------------------------- */
-    if( pszTmp != NULL )
-        free( pszTmp );
-    return pszBuffer;
+    pszBuffer = (char *)malloc(sizeof(char) *
+                               (strlen(pszTmp) +
+                                strlen(psFilterNode->pszValue) + 5));
+    pszBuffer[0] = '\0';
+    strcat(pszBuffer, " (");
+    strcat(pszBuffer, pszTmp);
+    strcat(pszBuffer, " ");
+    strcat(pszBuffer, psFilterNode->pszValue);
+    strcat(pszBuffer, " ");
+
+    free( pszTmp );
+
+    nTmp = strlen(pszBuffer);
+    pszTmp = FLTGetSQLExpression(psFilterNode->psRightNode, lp);
+    if (!pszTmp)
+      return NULL;
+
+    pszBuffer = (char *)realloc(pszBuffer,
+                                sizeof(char) * (strlen(pszTmp) + nTmp +3));
+    strcat(pszBuffer, pszTmp);
+    strcat(pszBuffer, ") ");
+  }
+  /* -------------------------------------------------------------------- */
+  /*      NOT                                                             */
+  /* -------------------------------------------------------------------- */
+  else if (psFilterNode->psLeftNode &&
+           strcasecmp(psFilterNode->pszValue, "NOT") == 0) {
+    pszTmp = FLTGetSQLExpression(psFilterNode->psLeftNode, lp);
+    if (!pszTmp)
+      return NULL;
+
+    pszBuffer = (char *)malloc(sizeof(char) * (strlen(pszTmp) +  9));
+    pszBuffer[0] = '\0';
+
+    strcat(pszBuffer, " (NOT ");
+    strcat(pszBuffer, pszTmp);
+    strcat(pszBuffer, ") ");
+  } else
+    return NULL;
+
+  /* -------------------------------------------------------------------- */
+  /*      Cleanup.                                                        */
+  /* -------------------------------------------------------------------- */
+  if( pszTmp != NULL )
+    free( pszTmp );
+  return pszBuffer;
 
 }
 
@@ -2267,113 +2310,110 @@ char *FLTGetLogicalComparisonSQLExpresssion(FilterEncodingNode *psFilterNode,
 /************************************************************************/
 char *FLTGetLogicalComparisonExpresssion(FilterEncodingNode *psFilterNode, layerObj *lp)
 {
-    char *pszTmp = NULL;
-    char *pszBuffer = NULL;
-    int nTmp = 0;
+  char *pszTmp = NULL;
+  char *pszBuffer = NULL;
+  int nTmp = 0;
 
-    if (!psFilterNode || !FLTIsLogicalFilterType(psFilterNode->pszValue))
-      return NULL;
+  if (!psFilterNode || !FLTIsLogicalFilterType(psFilterNode->pszValue))
+    return NULL;
 
-    
-/* ==================================================================== */
-/*      special case for BBOX node.                                     */
-/* ==================================================================== */
-    if (psFilterNode->psLeftNode && psFilterNode->psRightNode &&
-        (strcasecmp(psFilterNode->psLeftNode->pszValue, "BBOX") == 0 ||
-         strcasecmp(psFilterNode->psRightNode->pszValue, "BBOX") == 0 ||
-         FLTIsGeosNode(psFilterNode->psLeftNode->pszValue) ||
-         FLTIsGeosNode(psFilterNode->psRightNode->pszValue)))
-         
-         
-    {
-        
-        /*strcat(szBuffer, " (");*/
-        if (strcasecmp(psFilterNode->psLeftNode->pszValue, "BBOX") != 0 &&
-            strcasecmp(psFilterNode->psLeftNode->pszValue, "DWithin") != 0 &&
-            FLTIsGeosNode(psFilterNode->psLeftNode->pszValue) == MS_FALSE)
-          pszTmp = FLTGetNodeExpression(psFilterNode->psLeftNode, lp);
-        else
-          pszTmp = FLTGetNodeExpression(psFilterNode->psRightNode, lp);
 
-        if (!pszTmp)
-          return NULL;
-        
-        pszBuffer = (char *)malloc(sizeof(char) * (strlen(pszTmp) + 3));
-        pszBuffer[0] = '\0';
-        /*
-        if (strcasecmp(psFilterNode->psLeftNode->pszValue, "PropertyIsLike") == 0 ||
-            strcasecmp(psFilterNode->psRightNode->pszValue, "PropertyIsLike") == 0)
-          sprintf(pszBuffer, "%s", pszTmp);
-        else
-        */
-        sprintf(pszBuffer, "(%s)", pszTmp);
+  /* ==================================================================== */
+  /*      special case for BBOX node.                                     */
+  /* ==================================================================== */
+  if (psFilterNode->psLeftNode && psFilterNode->psRightNode &&
+      (strcasecmp(psFilterNode->psLeftNode->pszValue, "BBOX") == 0 ||
+       strcasecmp(psFilterNode->psRightNode->pszValue, "BBOX") == 0 ||
+       FLTIsGeosNode(psFilterNode->psLeftNode->pszValue) ||
+       FLTIsGeosNode(psFilterNode->psRightNode->pszValue)))
 
-        free(pszTmp);
-        
-        return pszBuffer;
-    }
 
-    
-/* -------------------------------------------------------------------- */
-/*      OR and AND                                                      */
-/* -------------------------------------------------------------------- */
-    if (psFilterNode->psLeftNode && psFilterNode->psRightNode)
-    {
-        pszTmp = FLTGetNodeExpression(psFilterNode->psLeftNode, lp);
-        if (!pszTmp)
-          return NULL;
-
-        pszBuffer = (char *)malloc(sizeof(char) * 
-                                   (strlen(pszTmp) + strlen(psFilterNode->pszValue) + 5));
-        pszBuffer[0] = '\0';
-        strcat(pszBuffer, " (");
-        
-        strcat(pszBuffer, pszTmp);
-        strcat(pszBuffer, " ");
-        strcat(pszBuffer, psFilterNode->pszValue);
-        strcat(pszBuffer, " ");
-        free(pszTmp);
-
-        pszTmp = FLTGetNodeExpression(psFilterNode->psRightNode, lp);
-        if (!pszTmp)
-          return NULL;
-
-        nTmp = strlen(pszBuffer);
-        pszBuffer = (char *)realloc(pszBuffer, 
-                                    sizeof(char) * (strlen(pszTmp) + nTmp +3));
-
-        strcat(pszBuffer, pszTmp);
-        strcat(pszBuffer, ") ");
-        free(pszTmp);
-    }
-/* -------------------------------------------------------------------- */
-/*      NOT                                                             */
-/* -------------------------------------------------------------------- */
-    else if (psFilterNode->psLeftNode && 
-             strcasecmp(psFilterNode->pszValue, "NOT") == 0)
-    {
-        pszTmp = FLTGetNodeExpression(psFilterNode->psLeftNode, lp);
-        if (!pszTmp)
-          return NULL;
-
-        pszBuffer = (char *)malloc(sizeof(char) *
-                                   (strlen(pszTmp) +  9));
-        pszBuffer[0] = '\0';
-        strcat(pszBuffer, " (NOT ");
-        strcat(pszBuffer, pszTmp);
-        strcat(pszBuffer, ") ");
-
-        free(pszTmp);
-    }
+  {
+
+    /*strcat(szBuffer, " (");*/
+    if (strcasecmp(psFilterNode->psLeftNode->pszValue, "BBOX") != 0 &&
+        strcasecmp(psFilterNode->psLeftNode->pszValue, "DWithin") != 0 &&
+        FLTIsGeosNode(psFilterNode->psLeftNode->pszValue) == MS_FALSE)
+      pszTmp = FLTGetNodeExpression(psFilterNode->psLeftNode, lp);
     else
+      pszTmp = FLTGetNodeExpression(psFilterNode->psRightNode, lp);
+
+    if (!pszTmp)
       return NULL;
-    
+
+    pszBuffer = (char *)malloc(sizeof(char) * (strlen(pszTmp) + 3));
+    pszBuffer[0] = '\0';
+    /*
+    if (strcasecmp(psFilterNode->psLeftNode->pszValue, "PropertyIsLike") == 0 ||
+        strcasecmp(psFilterNode->psRightNode->pszValue, "PropertyIsLike") == 0)
+      sprintf(pszBuffer, "%s", pszTmp);
+    else
+    */
+    sprintf(pszBuffer, "(%s)", pszTmp);
+
+    free(pszTmp);
+
     return pszBuffer;
-    
+  }
+
+
+  /* -------------------------------------------------------------------- */
+  /*      OR and AND                                                      */
+  /* -------------------------------------------------------------------- */
+  if (psFilterNode->psLeftNode && psFilterNode->psRightNode) {
+    pszTmp = FLTGetNodeExpression(psFilterNode->psLeftNode, lp);
+    if (!pszTmp)
+      return NULL;
+
+    pszBuffer = (char *)malloc(sizeof(char) *
+                               (strlen(pszTmp) + strlen(psFilterNode->pszValue) + 5));
+    pszBuffer[0] = '\0';
+    strcat(pszBuffer, " (");
+
+    strcat(pszBuffer, pszTmp);
+    strcat(pszBuffer, " ");
+    strcat(pszBuffer, psFilterNode->pszValue);
+    strcat(pszBuffer, " ");
+    free(pszTmp);
+
+    pszTmp = FLTGetNodeExpression(psFilterNode->psRightNode, lp);
+    if (!pszTmp)
+      return NULL;
+
+    nTmp = strlen(pszBuffer);
+    pszBuffer = (char *)realloc(pszBuffer,
+                                sizeof(char) * (strlen(pszTmp) + nTmp +3));
+
+    strcat(pszBuffer, pszTmp);
+    strcat(pszBuffer, ") ");
+    free(pszTmp);
+  }
+  /* -------------------------------------------------------------------- */
+  /*      NOT                                                             */
+  /* -------------------------------------------------------------------- */
+  else if (psFilterNode->psLeftNode &&
+           strcasecmp(psFilterNode->pszValue, "NOT") == 0) {
+    pszTmp = FLTGetNodeExpression(psFilterNode->psLeftNode, lp);
+    if (!pszTmp)
+      return NULL;
+
+    pszBuffer = (char *)malloc(sizeof(char) *
+                               (strlen(pszTmp) +  9));
+    pszBuffer[0] = '\0';
+    strcat(pszBuffer, " (NOT ");
+    strcat(pszBuffer, pszTmp);
+    strcat(pszBuffer, ") ");
+
+    free(pszTmp);
+  } else
+    return NULL;
+
+  return pszBuffer;
+
 }
 
-    
-    
+
+
 /************************************************************************/
 /*                      FLTGetBinaryComparisonExpresssion               */
 /*                                                                      */
@@ -2381,93 +2421,88 @@ char *FLTGetLogicalComparisonExpresssion(FilterEncodingNode *psFilterNode, layer
 /************************************************************************/
 char *FLTGetBinaryComparisonExpresssion(FilterEncodingNode *psFilterNode, layerObj *lp)
 {
-    const size_t bufferSize = 1024;
-    char szBuffer[1024];
-    int bString=0;
-    char szTmp[256];
+  const size_t bufferSize = 1024;
+  char szBuffer[1024];
+  int bString=0;
+  char szTmp[256];
 
-    szBuffer[0] = '\0';
-    if (!psFilterNode || !FLTIsBinaryComparisonFilterType(psFilterNode->pszValue))
-      return NULL;
+  szBuffer[0] = '\0';
+  if (!psFilterNode || !FLTIsBinaryComparisonFilterType(psFilterNode->pszValue))
+    return NULL;
 
-/* -------------------------------------------------------------------- */
-/*      check if the value is a numeric value or alphanumeric. If it    */
-/*      is alphanumeric, add quotes around attribute and values.        */
-/* -------------------------------------------------------------------- */
-    bString = 0;
-    if (psFilterNode->psRightNode->pszValue)
-    {
-        const char* pszOFGType;
-        snprintf(szTmp, sizeof(szTmp), "%s_type",  psFilterNode->psLeftNode->pszValue);
-        pszOFGType = msOWSLookupMetadata(&(lp->metadata), "OFG", szTmp);
-        if (pszOFGType!= NULL && strcasecmp(pszOFGType, "Character") == 0)
-          bString = 1;
-        else if (FLTIsNumeric(psFilterNode->psRightNode->pszValue) == MS_FALSE)
-          bString = 1;
-    }
-    
-    /* specical case to be able to have empty strings in the expression. */
-    if (psFilterNode->psRightNode->pszValue == NULL)
+  /* -------------------------------------------------------------------- */
+  /*      check if the value is a numeric value or alphanumeric. If it    */
+  /*      is alphanumeric, add quotes around attribute and values.        */
+  /* -------------------------------------------------------------------- */
+  bString = 0;
+  if (psFilterNode->psRightNode->pszValue) {
+    const char* pszOFGType;
+    snprintf(szTmp, sizeof(szTmp), "%s_type",  psFilterNode->psLeftNode->pszValue);
+    pszOFGType = msOWSLookupMetadata(&(lp->metadata), "OFG", szTmp);
+    if (pszOFGType!= NULL && strcasecmp(pszOFGType, "Character") == 0)
       bString = 1;
-      
+    else if (FLTIsNumeric(psFilterNode->psRightNode->pszValue) == MS_FALSE)
+      bString = 1;
+  }
 
-    if (bString)
-      strlcat(szBuffer, " (\"[", bufferSize);
-    else
-      strlcat(szBuffer, " ([", bufferSize);
-    /* attribute */
+  /* specical case to be able to have empty strings in the expression. */
+  if (psFilterNode->psRightNode->pszValue == NULL)
+    bString = 1;
 
-    strlcat(szBuffer, psFilterNode->psLeftNode->pszValue, bufferSize);
-    if (bString)
-      strlcat(szBuffer, "]\" ", bufferSize);
-    else
-      strlcat(szBuffer, "] ", bufferSize); 
-    
-
-    /* logical operator */
-    if (strcasecmp(psFilterNode->pszValue, 
-                   "PropertyIsEqualTo") == 0)
-    {
-        /*case insensitive set ? */
-        if (psFilterNode->psRightNode->pOther && 
-            (*(int *)psFilterNode->psRightNode->pOther) == 1)
-        {
-            strlcat(szBuffer, "IEQ", bufferSize);
-        }
-        else
-          strlcat(szBuffer, "=", bufferSize);
-    }
-    else if (strcasecmp(psFilterNode->pszValue, 
-                        "PropertyIsNotEqualTo") == 0)
-      strlcat(szBuffer, "!=", bufferSize); 
-    else if (strcasecmp(psFilterNode->pszValue, 
-                        "PropertyIsLessThan") == 0)
-      strlcat(szBuffer, "<", bufferSize);
-    else if (strcasecmp(psFilterNode->pszValue, 
-                        "PropertyIsGreaterThan") == 0)
-      strlcat(szBuffer, ">", bufferSize);
-    else if (strcasecmp(psFilterNode->pszValue, 
-                        "PropertyIsLessThanOrEqualTo") == 0)
-      strlcat(szBuffer, "<=", bufferSize);
-    else if (strcasecmp(psFilterNode->pszValue, 
-                        "PropertyIsGreaterThanOrEqualTo") == 0)
-      strlcat(szBuffer, ">=", bufferSize);
-    
-    strlcat(szBuffer, " ", bufferSize);
-    
-    /* value */
-    if (bString)
-      strlcat(szBuffer, "\"", bufferSize);
-    
-    if (psFilterNode->psRightNode->pszValue)
-      strlcat(szBuffer, psFilterNode->psRightNode->pszValue, bufferSize);
 
-    if (bString)
-      strlcat(szBuffer, "\"", bufferSize);
-    
-    strlcat(szBuffer, ") ", bufferSize);
+  if (bString)
+    strlcat(szBuffer, " (\"[", bufferSize);
+  else
+    strlcat(szBuffer, " ([", bufferSize);
+  /* attribute */
+
+  strlcat(szBuffer, psFilterNode->psLeftNode->pszValue, bufferSize);
+  if (bString)
+    strlcat(szBuffer, "]\" ", bufferSize);
+  else
+    strlcat(szBuffer, "] ", bufferSize);
 
-    return msStrdup(szBuffer);
+
+  /* logical operator */
+  if (strcasecmp(psFilterNode->pszValue,
+                 "PropertyIsEqualTo") == 0) {
+    /*case insensitive set ? */
+    if (psFilterNode->psRightNode->pOther &&
+        (*(int *)psFilterNode->psRightNode->pOther) == 1) {
+      strlcat(szBuffer, "IEQ", bufferSize);
+    } else
+      strlcat(szBuffer, "=", bufferSize);
+  } else if (strcasecmp(psFilterNode->pszValue,
+                        "PropertyIsNotEqualTo") == 0)
+    strlcat(szBuffer, "!=", bufferSize);
+  else if (strcasecmp(psFilterNode->pszValue,
+                      "PropertyIsLessThan") == 0)
+    strlcat(szBuffer, "<", bufferSize);
+  else if (strcasecmp(psFilterNode->pszValue,
+                      "PropertyIsGreaterThan") == 0)
+    strlcat(szBuffer, ">", bufferSize);
+  else if (strcasecmp(psFilterNode->pszValue,
+                      "PropertyIsLessThanOrEqualTo") == 0)
+    strlcat(szBuffer, "<=", bufferSize);
+  else if (strcasecmp(psFilterNode->pszValue,
+                      "PropertyIsGreaterThanOrEqualTo") == 0)
+    strlcat(szBuffer, ">=", bufferSize);
+
+  strlcat(szBuffer, " ", bufferSize);
+
+  /* value */
+  if (bString)
+    strlcat(szBuffer, "\"", bufferSize);
+
+  if (psFilterNode->psRightNode->pszValue)
+    strlcat(szBuffer, psFilterNode->psRightNode->pszValue, bufferSize);
+
+  if (bString)
+    strlcat(szBuffer, "\"", bufferSize);
+
+  strlcat(szBuffer, ") ", bufferSize);
+
+  return msStrdup(szBuffer);
 }
 
 
@@ -2479,129 +2514,120 @@ char *FLTGetBinaryComparisonExpresssion(FilterEncodingNode *psFilterNode, layerO
 /*      Return the expression for a binary comparison filter node.      */
 /************************************************************************/
 char *FLTGetBinaryComparisonSQLExpresssion(FilterEncodingNode *psFilterNode,
-                                           layerObj *lp)
+    layerObj *lp)
 {
-    const size_t bufferSize = 1024;
-    char szBuffer[1024];
-    int bString=0;
-    char szTmp[256];
-    char* pszEscapedStr = NULL;
-
-    szBuffer[0] = '\0';
-    if (!psFilterNode || !
-        FLTIsBinaryComparisonFilterType(psFilterNode->pszValue))
-      return NULL;
+  const size_t bufferSize = 1024;
+  char szBuffer[1024];
+  int bString=0;
+  char szTmp[256];
+  char* pszEscapedStr = NULL;
+
+  szBuffer[0] = '\0';
+  if (!psFilterNode || !
+      FLTIsBinaryComparisonFilterType(psFilterNode->pszValue))
+    return NULL;
 
-/* -------------------------------------------------------------------- */
-/*      check if the value is a numeric value or alphanumeric. If it    */
-/*      is alphanumeric, add quotes around attribute and values.        */
-/* -------------------------------------------------------------------- */
-    bString = 0;
-    if (psFilterNode->psRightNode->pszValue)
-    {
-        const char* pszOFGType;
-        snprintf(szTmp, sizeof(szTmp), "%s_type",  psFilterNode->psLeftNode->pszValue);
-        pszOFGType = msOWSLookupMetadata(&(lp->metadata), "OFG", szTmp);
-        if (pszOFGType!= NULL && strcasecmp(pszOFGType, "Character") == 0)
-          bString = 1;
+  /* -------------------------------------------------------------------- */
+  /*      check if the value is a numeric value or alphanumeric. If it    */
+  /*      is alphanumeric, add quotes around attribute and values.        */
+  /* -------------------------------------------------------------------- */
+  bString = 0;
+  if (psFilterNode->psRightNode->pszValue) {
+    const char* pszOFGType;
+    snprintf(szTmp, sizeof(szTmp), "%s_type",  psFilterNode->psLeftNode->pszValue);
+    pszOFGType = msOWSLookupMetadata(&(lp->metadata), "OFG", szTmp);
+    if (pszOFGType!= NULL && strcasecmp(pszOFGType, "Character") == 0)
+      bString = 1;
 
-        else if (FLTIsNumeric(psFilterNode->psRightNode->pszValue) == MS_FALSE)    
-          bString = 1;
-    }
-    
-    /* specical case to be able to have empty strings in the expression. */
-    if (psFilterNode->psRightNode->pszValue == NULL)
+    else if (FLTIsNumeric(psFilterNode->psRightNode->pszValue) == MS_FALSE)
       bString = 1;
-      
+  }
 
-    /*opening bracket*/
-    strlcat(szBuffer, " (", bufferSize);
+  /* specical case to be able to have empty strings in the expression. */
+  if (psFilterNode->psRightNode->pszValue == NULL)
+    bString = 1;
 
-    pszEscapedStr = msLayerEscapePropertyName(lp, psFilterNode->psLeftNode->pszValue);
 
+  /*opening bracket*/
+  strlcat(szBuffer, " (", bufferSize);
 
-    /* attribute */
-    /*case insensitive set ? */
-    if (bString &&
-        strcasecmp(psFilterNode->pszValue, 
-                   "PropertyIsEqualTo") == 0 &&
-        psFilterNode->psRightNode->pOther && 
-        (*(int *)psFilterNode->psRightNode->pOther) == 1)
-    {
-        snprintf(szTmp, sizeof(szTmp), "lower(%s) ",  pszEscapedStr);
-        strlcat(szBuffer, szTmp, bufferSize);
-    }
-    else
-      strlcat(szBuffer, pszEscapedStr, bufferSize);
+  pszEscapedStr = msLayerEscapePropertyName(lp, psFilterNode->psLeftNode->pszValue);
 
-    msFree(pszEscapedStr);
-    pszEscapedStr = NULL;
 
+  /* attribute */
+  /*case insensitive set ? */
+  if (bString &&
+      strcasecmp(psFilterNode->pszValue,
+                 "PropertyIsEqualTo") == 0 &&
+      psFilterNode->psRightNode->pOther &&
+      (*(int *)psFilterNode->psRightNode->pOther) == 1) {
+    snprintf(szTmp, sizeof(szTmp), "lower(%s) ",  pszEscapedStr);
+    strlcat(szBuffer, szTmp, bufferSize);
+  } else
+    strlcat(szBuffer, pszEscapedStr, bufferSize);
 
-    /* logical operator */
-    if (strcasecmp(psFilterNode->pszValue, 
-                   "PropertyIsEqualTo") == 0)
-      strlcat(szBuffer, "=", bufferSize);
-    else if (strcasecmp(psFilterNode->pszValue, 
-                        "PropertyIsNotEqualTo") == 0)
-      strlcat(szBuffer, "<>", bufferSize); 
-    else if (strcasecmp(psFilterNode->pszValue, 
-                        "PropertyIsLessThan") == 0)
-      strlcat(szBuffer, "<", bufferSize);
-    else if (strcasecmp(psFilterNode->pszValue, 
-                        "PropertyIsGreaterThan") == 0)
-      strlcat(szBuffer, ">", bufferSize);
-    else if (strcasecmp(psFilterNode->pszValue, 
-                        "PropertyIsLessThanOrEqualTo") == 0)
-      strlcat(szBuffer, "<=", bufferSize);
-    else if (strcasecmp(psFilterNode->pszValue, 
-                        "PropertyIsGreaterThanOrEqualTo") == 0)
-      strlcat(szBuffer, ">=", bufferSize);
-    
-    strlcat(szBuffer, " ", bufferSize);
-    
-    /* value */
-
-    if (bString && 
-        psFilterNode->psRightNode->pszValue &&
-        strcasecmp(psFilterNode->pszValue, 
-                   "PropertyIsEqualTo") == 0 &&
-        psFilterNode->psRightNode->pOther && 
-        (*(int *)psFilterNode->psRightNode->pOther) == 1)
-    {
+  msFree(pszEscapedStr);
+  pszEscapedStr = NULL;
+
+
+  /* logical operator */
+  if (strcasecmp(psFilterNode->pszValue,
+                 "PropertyIsEqualTo") == 0)
+    strlcat(szBuffer, "=", bufferSize);
+  else if (strcasecmp(psFilterNode->pszValue,
+                      "PropertyIsNotEqualTo") == 0)
+    strlcat(szBuffer, "<>", bufferSize);
+  else if (strcasecmp(psFilterNode->pszValue,
+                      "PropertyIsLessThan") == 0)
+    strlcat(szBuffer, "<", bufferSize);
+  else if (strcasecmp(psFilterNode->pszValue,
+                      "PropertyIsGreaterThan") == 0)
+    strlcat(szBuffer, ">", bufferSize);
+  else if (strcasecmp(psFilterNode->pszValue,
+                      "PropertyIsLessThanOrEqualTo") == 0)
+    strlcat(szBuffer, "<=", bufferSize);
+  else if (strcasecmp(psFilterNode->pszValue,
+                      "PropertyIsGreaterThanOrEqualTo") == 0)
+    strlcat(szBuffer, ">=", bufferSize);
+
+  strlcat(szBuffer, " ", bufferSize);
+
+  /* value */
+
+  if (bString &&
+      psFilterNode->psRightNode->pszValue &&
+      strcasecmp(psFilterNode->pszValue,
+                 "PropertyIsEqualTo") == 0 &&
+      psFilterNode->psRightNode->pOther &&
+      (*(int *)psFilterNode->psRightNode->pOther) == 1) {
+    char* pszEscapedStr;
+    pszEscapedStr = msLayerEscapeSQLParam(lp, psFilterNode->psRightNode->pszValue);
+    snprintf(szTmp, sizeof(szTmp), "lower('%s') ", pszEscapedStr);
+    msFree(pszEscapedStr);
+    strlcat(szBuffer, szTmp, bufferSize);
+  } else {
+    if (bString)
+      strlcat(szBuffer, "'", bufferSize);
+
+    if (psFilterNode->psRightNode->pszValue) {
+      if (bString) {
         char* pszEscapedStr;
         pszEscapedStr = msLayerEscapeSQLParam(lp, psFilterNode->psRightNode->pszValue);
-        snprintf(szTmp, sizeof(szTmp), "lower('%s') ", pszEscapedStr);
+        strlcat(szBuffer, pszEscapedStr, bufferSize);
         msFree(pszEscapedStr);
-        strlcat(szBuffer, szTmp, bufferSize);
+        pszEscapedStr=NULL;
+      } else
+        strlcat(szBuffer, psFilterNode->psRightNode->pszValue, bufferSize);
     }
-    else
-    {
-        if (bString)
-          strlcat(szBuffer, "'", bufferSize);
-    
-        if (psFilterNode->psRightNode->pszValue)
-        {
-            if (bString)
-            {
-               char* pszEscapedStr;
-                pszEscapedStr = msLayerEscapeSQLParam(lp, psFilterNode->psRightNode->pszValue);
-                strlcat(szBuffer, pszEscapedStr, bufferSize);
-                msFree(pszEscapedStr);
-                pszEscapedStr=NULL;
-            }
-            else
-                strlcat(szBuffer, psFilterNode->psRightNode->pszValue, bufferSize);
-        }
 
-        if (bString)
-          strlcat(szBuffer, "'", bufferSize);
+    if (bString)
+      strlcat(szBuffer, "'", bufferSize);
 
-    }
-    /*closing bracket*/
-    strlcat(szBuffer, ") ", bufferSize);
+  }
+  /*closing bracket*/
+  strlcat(szBuffer, ") ", bufferSize);
 
-    return msStrdup(szBuffer);
+  return msStrdup(szBuffer);
 }
 
 
@@ -2611,212 +2637,205 @@ char *FLTGetBinaryComparisonSQLExpresssion(FilterEncodingNode *psFilterNode,
 /*      Build an SQL expresssion for IsBteween Filter.                  */
 /************************************************************************/
 char *FLTGetIsBetweenComparisonSQLExpresssion(FilterEncodingNode *psFilterNode,
-                                              layerObj *lp)
+    layerObj *lp)
 {
-    const size_t bufferSize = 1024;
-    char szBuffer[1024];
-    char **aszBounds = NULL;
-    int nBounds = 0;
-    int bString=0;
-    char szTmp[256];
-    char* pszEscapedStr;
-
-    szBuffer[0] = '\0';
-    if (!psFilterNode ||
-        !(strcasecmp(psFilterNode->pszValue, "PropertyIsBetween") == 0))
-      return NULL;
+  const size_t bufferSize = 1024;
+  char szBuffer[1024];
+  char **aszBounds = NULL;
+  int nBounds = 0;
+  int bString=0;
+  char szTmp[256];
+  char* pszEscapedStr;
+
+  szBuffer[0] = '\0';
+  if (!psFilterNode ||
+      !(strcasecmp(psFilterNode->pszValue, "PropertyIsBetween") == 0))
+    return NULL;
 
-    if (!psFilterNode->psLeftNode || !psFilterNode->psRightNode )
-      return NULL;
+  if (!psFilterNode->psLeftNode || !psFilterNode->psRightNode )
+    return NULL;
 
-/* -------------------------------------------------------------------- */
-/*      Get the bounds value which are stored like boundmin;boundmax    */
-/* -------------------------------------------------------------------- */
-    aszBounds = msStringSplit(psFilterNode->psRightNode->pszValue, ';', &nBounds);
-    if (nBounds != 2)
-      return NULL;
-/* -------------------------------------------------------------------- */
-/*      check if the value is a numeric value or alphanumeric. If it    */
-/*      is alphanumeric, add quotes around attribute and values.        */
-/* -------------------------------------------------------------------- */
-    bString = 0;
-    if (aszBounds[0])
-    {
-        const char* pszOFGType;
-        snprintf(szTmp, sizeof(szTmp), "%s_type",  psFilterNode->psLeftNode->pszValue);
-        pszOFGType = msOWSLookupMetadata(&(lp->metadata), "OFG", szTmp);
-        if (pszOFGType!= NULL && strcasecmp(pszOFGType, "Character") == 0)
-          bString = 1;
-        else if (FLTIsNumeric(aszBounds[0]) == MS_FALSE)    
-          bString = 1;
-    }
-    if (!bString)
-    {
-        if (aszBounds[1])
-        {
-            if (FLTIsNumeric(aszBounds[1]) == MS_FALSE)    
-              bString = 1;
-        }
+  /* -------------------------------------------------------------------- */
+  /*      Get the bounds value which are stored like boundmin;boundmax    */
+  /* -------------------------------------------------------------------- */
+  aszBounds = msStringSplit(psFilterNode->psRightNode->pszValue, ';', &nBounds);
+  if (nBounds != 2)
+    return NULL;
+  /* -------------------------------------------------------------------- */
+  /*      check if the value is a numeric value or alphanumeric. If it    */
+  /*      is alphanumeric, add quotes around attribute and values.        */
+  /* -------------------------------------------------------------------- */
+  bString = 0;
+  if (aszBounds[0]) {
+    const char* pszOFGType;
+    snprintf(szTmp, sizeof(szTmp), "%s_type",  psFilterNode->psLeftNode->pszValue);
+    pszOFGType = msOWSLookupMetadata(&(lp->metadata), "OFG", szTmp);
+    if (pszOFGType!= NULL && strcasecmp(pszOFGType, "Character") == 0)
+      bString = 1;
+    else if (FLTIsNumeric(aszBounds[0]) == MS_FALSE)
+      bString = 1;
+  }
+  if (!bString) {
+    if (aszBounds[1]) {
+      if (FLTIsNumeric(aszBounds[1]) == MS_FALSE)
+        bString = 1;
     }
-        
+  }
 
-/* -------------------------------------------------------------------- */
-/*      build expresssion.                                              */
-/* -------------------------------------------------------------------- */
-    /*opening paranthesis */
-    strlcat(szBuffer, " (", bufferSize);
 
-    /* attribute */
-    pszEscapedStr = msLayerEscapePropertyName(lp, psFilterNode->psLeftNode->pszValue);
+  /* -------------------------------------------------------------------- */
+  /*      build expresssion.                                              */
+  /* -------------------------------------------------------------------- */
+  /*opening paranthesis */
+  strlcat(szBuffer, " (", bufferSize);
 
-    strlcat(szBuffer, pszEscapedStr, bufferSize);
-    msFree(pszEscapedStr);
-    pszEscapedStr = NULL;
+  /* attribute */
+  pszEscapedStr = msLayerEscapePropertyName(lp, psFilterNode->psLeftNode->pszValue);
 
-    /*between*/
-    strlcat(szBuffer, " BETWEEN ", bufferSize);
+  strlcat(szBuffer, pszEscapedStr, bufferSize);
+  msFree(pszEscapedStr);
+  pszEscapedStr = NULL;
 
-    /*bound 1*/
-    if (bString)
-      strlcat(szBuffer,"'", bufferSize);
-    pszEscapedStr = msLayerEscapeSQLParam( lp, aszBounds[0]);
-    strlcat(szBuffer, pszEscapedStr, bufferSize);
-    msFree(pszEscapedStr);
-    pszEscapedStr=NULL;
+  /*between*/
+  strlcat(szBuffer, " BETWEEN ", bufferSize);
 
-    if (bString)
-      strlcat(szBuffer,"'", bufferSize);
+  /*bound 1*/
+  if (bString)
+    strlcat(szBuffer,"'", bufferSize);
+  pszEscapedStr = msLayerEscapeSQLParam( lp, aszBounds[0]);
+  strlcat(szBuffer, pszEscapedStr, bufferSize);
+  msFree(pszEscapedStr);
+  pszEscapedStr=NULL;
 
-    strlcat(szBuffer, " AND ", bufferSize);
+  if (bString)
+    strlcat(szBuffer,"'", bufferSize);
 
-    /*bound 2*/
-    if (bString)
-      strlcat(szBuffer, "'", bufferSize);
-    pszEscapedStr = msLayerEscapeSQLParam( lp, aszBounds[1]);
-    strlcat(szBuffer, pszEscapedStr, bufferSize);
-    msFree(pszEscapedStr);
-    pszEscapedStr=NULL;
+  strlcat(szBuffer, " AND ", bufferSize);
 
-    if (bString)
-      strlcat(szBuffer,"'", bufferSize);
+  /*bound 2*/
+  if (bString)
+    strlcat(szBuffer, "'", bufferSize);
+  pszEscapedStr = msLayerEscapeSQLParam( lp, aszBounds[1]);
+  strlcat(szBuffer, pszEscapedStr, bufferSize);
+  msFree(pszEscapedStr);
+  pszEscapedStr=NULL;
+
+  if (bString)
+    strlcat(szBuffer,"'", bufferSize);
+
+  /*closing paranthesis*/
+  strlcat(szBuffer, ")", bufferSize);
 
-    /*closing paranthesis*/
-    strlcat(szBuffer, ")", bufferSize);
-     
-    
-    return msStrdup(szBuffer);
+
+  return msStrdup(szBuffer);
 }
-  
+
 /************************************************************************/
 /*                    FLTGetIsBetweenComparisonExpresssion              */
 /*                                                                      */
 /*      Build expresssion for IsBteween Filter.                         */
 /************************************************************************/
 char *FLTGetIsBetweenComparisonExpresssion(FilterEncodingNode *psFilterNode,
-                                           layerObj *lp)
+    layerObj *lp)
 {
-    const size_t bufferSize = 1024;
-    char szBuffer[1024];
-    char **aszBounds = NULL;
-    int nBounds = 0;
-    int bString=0;
-    char szTmp[256];
+  const size_t bufferSize = 1024;
+  char szBuffer[1024];
+  char **aszBounds = NULL;
+  int nBounds = 0;
+  int bString=0;
+  char szTmp[256];
 
 
-    szBuffer[0] = '\0';
-    if (!psFilterNode ||
-        !(strcasecmp(psFilterNode->pszValue, "PropertyIsBetween") == 0))
-      return NULL;
+  szBuffer[0] = '\0';
+  if (!psFilterNode ||
+      !(strcasecmp(psFilterNode->pszValue, "PropertyIsBetween") == 0))
+    return NULL;
 
-    if (!psFilterNode->psLeftNode || !psFilterNode->psRightNode )
-      return NULL;
+  if (!psFilterNode->psLeftNode || !psFilterNode->psRightNode )
+    return NULL;
 
-/* -------------------------------------------------------------------- */
-/*      Get the bounds value which are stored like boundmin;boundmax    */
-/* -------------------------------------------------------------------- */
-    aszBounds = msStringSplit(psFilterNode->psRightNode->pszValue, ';', &nBounds);
-    if (nBounds != 2)
-    {
-      msFreeCharArray(aszBounds, nBounds);
-      return NULL;
-    }
-/* -------------------------------------------------------------------- */
-/*      check if the value is a numeric value or alphanumeric. If it    */
-/*      is alphanumeric, add quotes around attribute and values.        */
-/* -------------------------------------------------------------------- */
-    bString = 0;
-    if (aszBounds[0])
-    {
-        const char* pszOFGType;
-        snprintf(szTmp, sizeof(szTmp), "%s_type",  psFilterNode->psLeftNode->pszValue);
-        pszOFGType = msOWSLookupMetadata(&(lp->metadata), "OFG", szTmp);
-        if (pszOFGType!= NULL && strcasecmp(pszOFGType, "Character") == 0)
-          bString = 1;
-        else if (FLTIsNumeric(aszBounds[0]) == MS_FALSE)    
-          bString = 1;
-    }
-    if (!bString)
-    {
-        if (aszBounds[1])
-        {
-            if (FLTIsNumeric(aszBounds[1]) == MS_FALSE)    
-              bString = 1;  
-        }
+  /* -------------------------------------------------------------------- */
+  /*      Get the bounds value which are stored like boundmin;boundmax    */
+  /* -------------------------------------------------------------------- */
+  aszBounds = msStringSplit(psFilterNode->psRightNode->pszValue, ';', &nBounds);
+  if (nBounds != 2) {
+    msFreeCharArray(aszBounds, nBounds);
+    return NULL;
+  }
+  /* -------------------------------------------------------------------- */
+  /*      check if the value is a numeric value or alphanumeric. If it    */
+  /*      is alphanumeric, add quotes around attribute and values.        */
+  /* -------------------------------------------------------------------- */
+  bString = 0;
+  if (aszBounds[0]) {
+    const char* pszOFGType;
+    snprintf(szTmp, sizeof(szTmp), "%s_type",  psFilterNode->psLeftNode->pszValue);
+    pszOFGType = msOWSLookupMetadata(&(lp->metadata), "OFG", szTmp);
+    if (pszOFGType!= NULL && strcasecmp(pszOFGType, "Character") == 0)
+      bString = 1;
+    else if (FLTIsNumeric(aszBounds[0]) == MS_FALSE)
+      bString = 1;
+  }
+  if (!bString) {
+    if (aszBounds[1]) {
+      if (FLTIsNumeric(aszBounds[1]) == MS_FALSE)
+        bString = 1;
     }
-        
+  }
 
-/* -------------------------------------------------------------------- */
-/*      build expresssion.                                              */
-/* -------------------------------------------------------------------- */
-    if (bString)
-      strlcat(szBuffer, " (\"[", bufferSize);
-    else
-      strlcat(szBuffer, " ([", bufferSize);
 
-    /* attribute */
-    strlcat(szBuffer, psFilterNode->psLeftNode->pszValue, bufferSize);
+  /* -------------------------------------------------------------------- */
+  /*      build expresssion.                                              */
+  /* -------------------------------------------------------------------- */
+  if (bString)
+    strlcat(szBuffer, " (\"[", bufferSize);
+  else
+    strlcat(szBuffer, " ([", bufferSize);
 
-    if (bString)
-      strlcat(szBuffer, "]\" ", bufferSize);
-    else
-      strlcat(szBuffer, "] ", bufferSize);
-        
-    
-    strlcat(szBuffer, " >= ", bufferSize);
-    if (bString)
-      strlcat(szBuffer,"\"", bufferSize);
-    strlcat(szBuffer, aszBounds[0], bufferSize);
-    if (bString)
-      strlcat(szBuffer,"\"", bufferSize);
+  /* attribute */
+  strlcat(szBuffer, psFilterNode->psLeftNode->pszValue, bufferSize);
 
-    strlcat(szBuffer, " AND ", bufferSize);
+  if (bString)
+    strlcat(szBuffer, "]\" ", bufferSize);
+  else
+    strlcat(szBuffer, "] ", bufferSize);
 
-    if (bString)
-      strlcat(szBuffer, " \"[", bufferSize);
-    else
-      strlcat(szBuffer, " [", bufferSize); 
 
-    /* attribute */
-    strlcat(szBuffer, psFilterNode->psLeftNode->pszValue, bufferSize);
-    
-    if (bString)
-      strlcat(szBuffer, "]\" ", bufferSize);
-    else
-      strlcat(szBuffer, "] ", bufferSize);
-    
-    strlcat(szBuffer, " <= ", bufferSize);
-    if (bString)
-      strlcat(szBuffer,"\"", bufferSize);
-    strlcat(szBuffer, aszBounds[1], bufferSize);
-    if (bString)
-      strlcat(szBuffer,"\"", bufferSize);
-    strlcat(szBuffer, ")", bufferSize);
+  strlcat(szBuffer, " >= ", bufferSize);
+  if (bString)
+    strlcat(szBuffer,"\"", bufferSize);
+  strlcat(szBuffer, aszBounds[0], bufferSize);
+  if (bString)
+    strlcat(szBuffer,"\"", bufferSize);
 
-    msFreeCharArray(aszBounds, nBounds);
+  strlcat(szBuffer, " AND ", bufferSize);
+
+  if (bString)
+    strlcat(szBuffer, " \"[", bufferSize);
+  else
+    strlcat(szBuffer, " [", bufferSize);
+
+  /* attribute */
+  strlcat(szBuffer, psFilterNode->psLeftNode->pszValue, bufferSize);
+
+  if (bString)
+    strlcat(szBuffer, "]\" ", bufferSize);
+  else
+    strlcat(szBuffer, "] ", bufferSize);
+
+  strlcat(szBuffer, " <= ", bufferSize);
+  if (bString)
+    strlcat(szBuffer,"\"", bufferSize);
+  strlcat(szBuffer, aszBounds[1], bufferSize);
+  if (bString)
+    strlcat(szBuffer,"\"", bufferSize);
+  strlcat(szBuffer, ")", bufferSize);
+
+  msFreeCharArray(aszBounds, nBounds);
 
-    return msStrdup(szBuffer);
+  return msStrdup(szBuffer);
 }
-    
+
 /************************************************************************/
 /*                      FLTGetIsLikeComparisonExpression               */
 /*                                                                      */
@@ -2824,106 +2843,97 @@ char *FLTGetIsBetweenComparisonExpresssion(FilterEncodingNode *psFilterNode,
 /************************************************************************/
 char *FLTGetIsLikeComparisonExpression(FilterEncodingNode *psFilterNode)
 {
-    const size_t bufferSize = 1024;
-    char szBuffer[1024];
-    char szTmp[256];
-    char *pszValue = NULL;
-    
-    char *pszWild = NULL;
-    char *pszSingle = NULL;
-    char *pszEscape = NULL;
-    int  bCaseInsensitive = 0;
-
-    int nLength=0, i=0, iTmp=0;
-
-
-    if (!psFilterNode || !psFilterNode->pOther || !psFilterNode->psLeftNode ||
-        !psFilterNode->psRightNode || !psFilterNode->psRightNode->pszValue)
-      return NULL;
+  const size_t bufferSize = 1024;
+  char szBuffer[1024];
+  char szTmp[256];
+  char *pszValue = NULL;
 
-    pszWild = ((FEPropertyIsLike *)psFilterNode->pOther)->pszWildCard;
-    pszSingle = ((FEPropertyIsLike *)psFilterNode->pOther)->pszSingleChar;
-    pszEscape = ((FEPropertyIsLike *)psFilterNode->pOther)->pszEscapeChar;
-    bCaseInsensitive = ((FEPropertyIsLike *)psFilterNode->pOther)->bCaseInsensitive;
+  char *pszWild = NULL;
+  char *pszSingle = NULL;
+  char *pszEscape = NULL;
+  int  bCaseInsensitive = 0;
 
-    if (!pszWild || strlen(pszWild) == 0 ||
-        !pszSingle || strlen(pszSingle) == 0 || 
-        !pszEscape || strlen(pszEscape) == 0)
-      return NULL;
+  int nLength=0, i=0, iTmp=0;
 
- 
-/* -------------------------------------------------------------------- */
-/*      Use operand with regular expressions.                           */
-/* -------------------------------------------------------------------- */
-    szBuffer[0] = '\0';
-    sprintf(szTmp, "%s", " (\"[");
-    szTmp[4] = '\0';
 
-    strlcat(szBuffer, szTmp, bufferSize);
+  if (!psFilterNode || !psFilterNode->pOther || !psFilterNode->psLeftNode ||
+      !psFilterNode->psRightNode || !psFilterNode->psRightNode->pszValue)
+    return NULL;
 
-    /* attribute */
-    strlcat(szBuffer, psFilterNode->psLeftNode->pszValue, bufferSize);
-    szBuffer[strlen(szBuffer)] = '\0';
+  pszWild = ((FEPropertyIsLike *)psFilterNode->pOther)->pszWildCard;
+  pszSingle = ((FEPropertyIsLike *)psFilterNode->pOther)->pszSingleChar;
+  pszEscape = ((FEPropertyIsLike *)psFilterNode->pOther)->pszEscapeChar;
+  bCaseInsensitive = ((FEPropertyIsLike *)psFilterNode->pOther)->bCaseInsensitive;
 
-    /*#3521 */
-    if(bCaseInsensitive == 1)
-      sprintf(szTmp, "%s", "]\" ~* /");
-    else
-      sprintf(szTmp, "%s", "]\" =~ /");
-    szTmp[7] = '\0';
-    strlcat(szBuffer, szTmp, bufferSize);
-    szBuffer[strlen(szBuffer)] = '\0';
+  if (!pszWild || strlen(pszWild) == 0 ||
+      !pszSingle || strlen(pszSingle) == 0 ||
+      !pszEscape || strlen(pszEscape) == 0)
+    return NULL;
 
 
-    pszValue = psFilterNode->psRightNode->pszValue;
-    nLength = strlen(pszValue);
-    
-    iTmp =0;
-    if (nLength > 0 && pszValue[0] != pszWild[0] && 
-        pszValue[0] != pszSingle[0] &&
-        pszValue[0] != pszEscape[0])
-    {
-      szTmp[iTmp]= '^';
+  /* -------------------------------------------------------------------- */
+  /*      Use operand with regular expressions.                           */
+  /* -------------------------------------------------------------------- */
+  szBuffer[0] = '\0';
+  sprintf(szTmp, "%s", " (\"[");
+  szTmp[4] = '\0';
+
+  strlcat(szBuffer, szTmp, bufferSize);
+
+  /* attribute */
+  strlcat(szBuffer, psFilterNode->psLeftNode->pszValue, bufferSize);
+  szBuffer[strlen(szBuffer)] = '\0';
+
+  /*#3521 */
+  if(bCaseInsensitive == 1)
+    sprintf(szTmp, "%s", "]\" ~* /");
+  else
+    sprintf(szTmp, "%s", "]\" =~ /");
+  szTmp[7] = '\0';
+  strlcat(szBuffer, szTmp, bufferSize);
+  szBuffer[strlen(szBuffer)] = '\0';
+
+
+  pszValue = psFilterNode->psRightNode->pszValue;
+  nLength = strlen(pszValue);
+
+  iTmp =0;
+  if (nLength > 0 && pszValue[0] != pszWild[0] &&
+      pszValue[0] != pszSingle[0] &&
+      pszValue[0] != pszEscape[0]) {
+    szTmp[iTmp]= '^';
+    iTmp++;
+  }
+  for (i=0; i<nLength; i++) {
+    if (pszValue[i] != pszWild[0] &&
+        pszValue[i] != pszSingle[0] &&
+        pszValue[i] != pszEscape[0]) {
+      szTmp[iTmp] = pszValue[i];
       iTmp++;
-    }
-    for (i=0; i<nLength; i++)
-    {
-        if (pszValue[i] != pszWild[0] && 
-            pszValue[i] != pszSingle[0] &&
-            pszValue[i] != pszEscape[0])
-        {
-            szTmp[iTmp] = pszValue[i];
-            iTmp++;
-            szTmp[iTmp] = '\0';
-        }
-        else if  (pszValue[i] == pszSingle[0])
-        {
-             szTmp[iTmp] = '.';
-             iTmp++;
-             szTmp[iTmp] = '\0';
-        }
-        else if  (pszValue[i] == pszEscape[0])
-        {
-            szTmp[iTmp] = '\\';
-            iTmp++;
-            szTmp[iTmp] = '\0';
-
-        }
-        else if (pszValue[i] == pszWild[0])
-        {
-            /* strcat(szBuffer, "[0-9,a-z,A-Z,\\s]*"); */
-            /* iBuffer+=17; */
-            szTmp[iTmp++] = '.';
-            szTmp[iTmp++] = '*';
-            szTmp[iTmp] = '\0';
-        }
-    }   
-    szTmp[iTmp] = '/';
-    szTmp[++iTmp] = '\0';
-    
-    strlcat(szBuffer, szTmp, bufferSize);
-    strlcat(szBuffer, ")", bufferSize);     
-    return msStrdup(szBuffer);
+      szTmp[iTmp] = '\0';
+    } else if  (pszValue[i] == pszSingle[0]) {
+      szTmp[iTmp] = '.';
+      iTmp++;
+      szTmp[iTmp] = '\0';
+    } else if  (pszValue[i] == pszEscape[0]) {
+      szTmp[iTmp] = '\\';
+      iTmp++;
+      szTmp[iTmp] = '\0';
+
+    } else if (pszValue[i] == pszWild[0]) {
+      /* strcat(szBuffer, "[0-9,a-z,A-Z,\\s]*"); */
+      /* iBuffer+=17; */
+      szTmp[iTmp++] = '.';
+      szTmp[iTmp++] = '*';
+      szTmp[iTmp] = '\0';
+    }
+  }
+  szTmp[iTmp] = '/';
+  szTmp[++iTmp] = '\0';
+
+  strlcat(szBuffer, szTmp, bufferSize);
+  strlcat(szBuffer, ")", bufferSize);
+  return msStrdup(szBuffer);
 }
 
 /************************************************************************/
@@ -2932,140 +2942,122 @@ char *FLTGetIsLikeComparisonExpression(FilterEncodingNode *psFilterNode)
 /*      Build an sql expression for IsLike filter.                      */
 /************************************************************************/
 char *FLTGetIsLikeComparisonSQLExpression(FilterEncodingNode *psFilterNode,
-                                          layerObj *lp)
+    layerObj *lp)
 {
-    const size_t bufferSize = 1024;
-    char szBuffer[1024];
-    char *pszValue = NULL;
-    
-    char *pszWild = NULL;
-    char *pszSingle = NULL;
-    char *pszEscape = NULL;
-    char szTmp[4];
-
-    int nLength=0, i=0, j=0;
-    int  bCaseInsensitive = 0;
-
-    char *pszEscapedStr = NULL;
-
-    if (!psFilterNode || !psFilterNode->pOther || !psFilterNode->psLeftNode ||
-        !psFilterNode->psRightNode || !psFilterNode->psRightNode->pszValue)
-      return NULL;
+  const size_t bufferSize = 1024;
+  char szBuffer[1024];
+  char *pszValue = NULL;
 
-    pszWild = ((FEPropertyIsLike *)psFilterNode->pOther)->pszWildCard;
-    pszSingle = ((FEPropertyIsLike *)psFilterNode->pOther)->pszSingleChar;
-    pszEscape = ((FEPropertyIsLike *)psFilterNode->pOther)->pszEscapeChar;
-    bCaseInsensitive = ((FEPropertyIsLike *)psFilterNode->pOther)->bCaseInsensitive;
+  char *pszWild = NULL;
+  char *pszSingle = NULL;
+  char *pszEscape = NULL;
+  char szTmp[4];
 
-    if (!pszWild || strlen(pszWild) == 0 ||
-        !pszSingle || strlen(pszSingle) == 0 || 
-        !pszEscape || strlen(pszEscape) == 0)
-      return NULL;
+  int nLength=0, i=0, j=0;
+  int  bCaseInsensitive = 0;
 
-    if (pszEscape[0] == '\'')
-    {
-        /* This might be valid, but the risk of SQL injection is too high */
-        /* and the below code is not ready for that */
-        /* Someone who does this has clearly suspect intentions ! */
-        msSetError(MS_MISCERR, "Single quote character is not allowed as an escaping character.",
-                   "FLTGetIsLikeComparisonSQLExpression()");
-        return NULL;
-    }
+  char *pszEscapedStr = NULL;
 
+  if (!psFilterNode || !psFilterNode->pOther || !psFilterNode->psLeftNode ||
+      !psFilterNode->psRightNode || !psFilterNode->psRightNode->pszValue)
+    return NULL;
 
-    szBuffer[0] = '\0';
-    /*opening bracket*/
-    strlcat(szBuffer, " (", bufferSize);
+  pszWild = ((FEPropertyIsLike *)psFilterNode->pOther)->pszWildCard;
+  pszSingle = ((FEPropertyIsLike *)psFilterNode->pOther)->pszSingleChar;
+  pszEscape = ((FEPropertyIsLike *)psFilterNode->pOther)->pszEscapeChar;
+  bCaseInsensitive = ((FEPropertyIsLike *)psFilterNode->pOther)->bCaseInsensitive;
 
-    /* attribute name */
-    pszEscapedStr = msLayerEscapePropertyName(lp, psFilterNode->psLeftNode->pszValue);
+  if (!pszWild || strlen(pszWild) == 0 ||
+      !pszSingle || strlen(pszSingle) == 0 ||
+      !pszEscape || strlen(pszEscape) == 0)
+    return NULL;
 
-    strlcat(szBuffer, pszEscapedStr, bufferSize);
-    msFree(pszEscapedStr);
-    pszEscapedStr = NULL;
+  if (pszEscape[0] == '\'') {
+    /* This might be valid, but the risk of SQL injection is too high */
+    /* and the below code is not ready for that */
+    /* Someone who does this has clearly suspect intentions ! */
+    msSetError(MS_MISCERR, "Single quote character is not allowed as an escaping character.",
+               "FLTGetIsLikeComparisonSQLExpression()");
+    return NULL;
+  }
 
-    if (bCaseInsensitive == 1 && lp->connectiontype == MS_POSTGIS)
-      strlcat(szBuffer, " ilike '", bufferSize);
-    else
-      strlcat(szBuffer, " like '", bufferSize);
-        
-   
-    pszValue = psFilterNode->psRightNode->pszValue;
-    nLength = strlen(pszValue);
 
-    pszEscapedStr = (char*) msSmallMalloc( 3 * nLength + 1);
+  szBuffer[0] = '\0';
+  /*opening bracket*/
+  strlcat(szBuffer, " (", bufferSize);
 
-    for (i=0, j=0; i<nLength; i++)
-    {
-        char c = pszValue[i];
-        if (c != pszWild[0] &&
-            c != pszSingle[0] &&
-            c != pszEscape[0])
-        {
-            if (c == '\'')
-            {
-                pszEscapedStr[j++] = '\'';
-                pszEscapedStr[j++] = '\'';
-            }
-            else if (c == '\\')
-            {
-                pszEscapedStr[j++] = '\\';
-                pszEscapedStr[j++] = '\\';
-            }
-            else
-                pszEscapedStr[j++] = c;
-        }
-        else if  (c == pszSingle[0])
-        {
-            pszEscapedStr[j++] = '_';
-        }
-        else if  (c == pszEscape[0])
-        {
-            pszEscapedStr[j++] = pszEscape[0];
-            if (i+1<nLength)
-            {
-                char nextC = pszValue[i+1];
-                i++;
-                if (nextC == '\'')
-                {
-                    pszEscapedStr[j++] = '\'';
-                    pszEscapedStr[j++] = '\'';
-                }
-                else
-                    pszEscapedStr[j++] = nextC;
-            }
-        }
-        else if (c == pszWild[0])
-        {
-            pszEscapedStr[j++] = '%';
-        }
-    }
-    pszEscapedStr[j++] = 0;
-    strlcat(szBuffer, pszEscapedStr, bufferSize);
-    msFree(pszEscapedStr);
+  /* attribute name */
+  pszEscapedStr = msLayerEscapePropertyName(lp, psFilterNode->psLeftNode->pszValue);
 
-    strlcat(szBuffer, "'", bufferSize);
-    if (lp->connectiontype != MS_OGR)
-    {
-      strlcat(szBuffer, " escape '", bufferSize);
-      szTmp[0] = pszEscape[0];
-      if (pszEscape[0] == '\\')
-      {
-          szTmp[1] = '\\';
-          szTmp[2] = '\'';
-          szTmp[3] = '\0';
-      }
-      else
-      {
-          szTmp[1] = '\'';
-          szTmp[2] = '\0';
-      }
+  strlcat(szBuffer, pszEscapedStr, bufferSize);
+  msFree(pszEscapedStr);
+  pszEscapedStr = NULL;
 
-      strlcat(szBuffer,  szTmp, bufferSize);
-    }
-    strlcat(szBuffer,  ") ", bufferSize);
-    
-    return msStrdup(szBuffer);
+  if (lp->connectiontype == MS_POSTGIS) {
+    if (bCaseInsensitive == 1)
+      strlcat(szBuffer, "::text ilike '", bufferSize);
+    else
+      strlcat(szBuffer, "::text like '", bufferSize);
+  } else
+    strlcat(szBuffer, " like '", bufferSize);
+
+  pszValue = psFilterNode->psRightNode->pszValue;
+  nLength = strlen(pszValue);
+
+  pszEscapedStr = (char*) msSmallMalloc( 3 * nLength + 1);
+
+  for (i=0, j=0; i<nLength; i++) {
+    char c = pszValue[i];
+    if (c != pszWild[0] &&
+        c != pszSingle[0] &&
+        c != pszEscape[0]) {
+      if (c == '\'') {
+        pszEscapedStr[j++] = '\'';
+        pszEscapedStr[j++] = '\'';
+      } else if (c == '\\') {
+        pszEscapedStr[j++] = '\\';
+        pszEscapedStr[j++] = '\\';
+      } else
+        pszEscapedStr[j++] = c;
+    } else if  (c == pszSingle[0]) {
+      pszEscapedStr[j++] = '_';
+    } else if  (c == pszEscape[0]) {
+      pszEscapedStr[j++] = pszEscape[0];
+      if (i+1<nLength) {
+        char nextC = pszValue[i+1];
+        i++;
+        if (nextC == '\'') {
+          pszEscapedStr[j++] = '\'';
+          pszEscapedStr[j++] = '\'';
+        } else
+          pszEscapedStr[j++] = nextC;
+      }
+    } else if (c == pszWild[0]) {
+      pszEscapedStr[j++] = '%';
+    }
+  }
+  pszEscapedStr[j++] = 0;
+  strlcat(szBuffer, pszEscapedStr, bufferSize);
+  msFree(pszEscapedStr);
+
+  strlcat(szBuffer, "'", bufferSize);
+  if (lp->connectiontype != MS_OGR) {
+    strlcat(szBuffer, " escape '", bufferSize);
+    szTmp[0] = pszEscape[0];
+    if (pszEscape[0] == '\\') {
+      szTmp[1] = '\\';
+      szTmp[2] = '\'';
+      szTmp[3] = '\0';
+    } else {
+      szTmp[1] = '\'';
+      szTmp[2] = '\0';
+    }
+
+    strlcat(szBuffer,  szTmp, bufferSize);
+  }
+  strlcat(szBuffer,  ") ", bufferSize);
+
+  return msStrdup(szBuffer);
 }
 
 /************************************************************************/
@@ -3076,31 +3068,29 @@ char *FLTGetIsLikeComparisonSQLExpression(FilterEncodingNode *psFilterNode,
 /************************************************************************/
 int FLTHasSpatialFilter(FilterEncodingNode *psNode)
 {
-    int bResult = MS_FALSE;
+  int bResult = MS_FALSE;
 
-    if (!psNode)
-      return MS_FALSE;
+  if (!psNode)
+    return MS_FALSE;
 
-    if (psNode->eType == FILTER_NODE_TYPE_LOGICAL)
-    {
-        if (psNode->psLeftNode)
-          bResult = FLTHasSpatialFilter(psNode->psLeftNode);
+  if (psNode->eType == FILTER_NODE_TYPE_LOGICAL) {
+    if (psNode->psLeftNode)
+      bResult = FLTHasSpatialFilter(psNode->psLeftNode);
 
-        if (bResult)
-          return MS_TRUE;
+    if (bResult)
+      return MS_TRUE;
 
-        if (psNode->psRightNode)
-           bResult = FLTHasSpatialFilter(psNode->psRightNode);
+    if (psNode->psRightNode)
+      bResult = FLTHasSpatialFilter(psNode->psRightNode);
 
-        if (bResult)
-          return MS_TRUE;
-    }
-    else if (FLTIsBBoxFilter(psNode) || FLTIsPointFilter(psNode) ||
-             FLTIsLineFilter(psNode) || FLTIsPolygonFilter(psNode))
+    if (bResult)
       return MS_TRUE;
+  } else if (FLTIsBBoxFilter(psNode) || FLTIsPointFilter(psNode) ||
+             FLTIsLineFilter(psNode) || FLTIsPolygonFilter(psNode))
+    return MS_TRUE;
 
 
-    return MS_FALSE;
+  return MS_FALSE;
 }
 
 
@@ -3111,26 +3101,25 @@ int FLTHasSpatialFilter(FilterEncodingNode *psNode)
 /************************************************************************/
 FilterEncodingNode *FLTCreateFeatureIdFilterEncoding(char *pszString)
 {
-    FilterEncodingNode *psFilterNode = NULL;
-    char **tokens = NULL;
-    int nTokens = 0;
-
-    if (pszString)
-    {
-        psFilterNode = FLTCreateFilterEncodingNode();
-        psFilterNode->eType = FILTER_NODE_TYPE_FEATUREID;
-        /*split if tyname is included in the string*/
-        tokens = msStringSplit(pszString,'.', &nTokens);
-        if (tokens && nTokens == 2)
-          psFilterNode->pszValue = msStrdup(tokens[1]);
-        else
-          psFilterNode->pszValue =  msStrdup(pszString);
+  FilterEncodingNode *psFilterNode = NULL;
+  char **tokens = NULL;
+  int nTokens = 0;
 
-        if (tokens)
-          msFreeCharArray(tokens, nTokens); 
-        return psFilterNode;
-    }
-    return NULL;
+  if (pszString) {
+    psFilterNode = FLTCreateFilterEncodingNode();
+    psFilterNode->eType = FILTER_NODE_TYPE_FEATUREID;
+    /*split if tyname is included in the string*/
+    tokens = msStringSplit(pszString,'.', &nTokens);
+    if (tokens && nTokens == 2)
+      psFilterNode->pszValue = msStrdup(tokens[1]);
+    else
+      psFilterNode->pszValue =  msStrdup(pszString);
+
+    if (tokens)
+      msFreeCharArray(tokens, nTokens);
+    return psFilterNode;
+  }
+  return NULL;
 }
 
 
@@ -3141,111 +3130,99 @@ FilterEncodingNode *FLTCreateFeatureIdFilterEncoding(char *pszString)
 /************************************************************************/
 int FLTParseGMLBox(CPLXMLNode *psBox, rectObj *psBbox, char **ppszSRS)
 {
-    int bCoordinatesValid = 0;
-    CPLXMLNode *psCoordinates = NULL, *psCoordChild=NULL;
-    CPLXMLNode *psCoord1 = NULL, *psCoord2 = NULL;
-    CPLXMLNode *psX = NULL, *psY = NULL;
-    char **papszCoords=NULL, **papszMin=NULL, **papszMax = NULL;
-    int nCoords = 0, nCoordsMin = 0, nCoordsMax = 0;
-    char *pszTmpCoord = NULL;
-    const char *pszSRS = NULL;
-    const char *pszTS = NULL;
-    const char *pszCS = NULL;
-    double minx = 0.0, miny = 0.0, maxx = 0.0, maxy = 0.0;
-
-    if (psBox)
-    {
-        pszSRS = CPLGetXMLValue(psBox, "srsName", NULL);
-        if (ppszSRS && pszSRS)
-          *ppszSRS = msStrdup(pszSRS);
-
-        psCoordinates = CPLGetXMLNode(psBox, "coordinates");
-        if (!psCoordinates)
-          return 0;
-        pszTS = CPLGetXMLValue(psCoordinates, "ts", NULL);
-        pszCS = CPLGetXMLValue(psCoordinates, "cs", NULL);
-
-        psCoordChild =  psCoordinates->psChild;
-        while (psCoordinates && psCoordChild && psCoordChild->eType != CXT_Text)
-        {
-            psCoordChild = psCoordChild->psNext;
-        }
-        if (psCoordChild && psCoordChild->pszValue)
-        {
-            pszTmpCoord = psCoordChild->pszValue;
-            if (pszTS)
-              papszCoords = msStringSplit(pszTmpCoord, pszTS[0], &nCoords);
-            else
-              papszCoords = msStringSplit(pszTmpCoord, ' ', &nCoords);
-            if (papszCoords && nCoords == 2)
-            {
-                if (pszCS)
-                  papszMin = msStringSplit(papszCoords[0], pszCS[0], &nCoordsMin);
-                else
-                  papszMin = msStringSplit(papszCoords[0], ',', &nCoordsMin);
-                if (papszMin && nCoordsMin == 2)
-                {
-                    if (pszCS)
-                      papszMax = msStringSplit(papszCoords[1], pszCS[0], &nCoordsMax);
-                    else
-                      papszMax = msStringSplit(papszCoords[1], ',', &nCoordsMax);
-                }
-                if (papszMax && nCoordsMax == 2)
-                {
-                    bCoordinatesValid =1;
-                    minx =  atof(papszMin[0]);
-                    miny =  atof(papszMin[1]);
-                    maxx =  atof(papszMax[0]);
-                    maxy =  atof(papszMax[1]);
-                }
-
-                msFreeCharArray(papszMin, nCoordsMin);
-                msFreeCharArray(papszMax, nCoordsMax);
-            }
+  int bCoordinatesValid = 0;
+  CPLXMLNode *psCoordinates = NULL, *psCoordChild=NULL;
+  CPLXMLNode *psCoord1 = NULL, *psCoord2 = NULL;
+  CPLXMLNode *psX = NULL, *psY = NULL;
+  char **papszCoords=NULL, **papszMin=NULL, **papszMax = NULL;
+  int nCoords = 0, nCoordsMin = 0, nCoordsMax = 0;
+  char *pszTmpCoord = NULL;
+  const char *pszSRS = NULL;
+  const char *pszTS = NULL;
+  const char *pszCS = NULL;
+  double minx = 0.0, miny = 0.0, maxx = 0.0, maxy = 0.0;
+
+  if (psBox) {
+    pszSRS = CPLGetXMLValue(psBox, "srsName", NULL);
+    if (ppszSRS && pszSRS)
+      *ppszSRS = msStrdup(pszSRS);
+
+    psCoordinates = CPLGetXMLNode(psBox, "coordinates");
+    if (!psCoordinates)
+      return 0;
+    pszTS = CPLGetXMLValue(psCoordinates, "ts", NULL);
+    pszCS = CPLGetXMLValue(psCoordinates, "cs", NULL);
 
-            msFreeCharArray(papszCoords, nCoords);
-        }
+    psCoordChild =  psCoordinates->psChild;
+    while (psCoordinates && psCoordChild && psCoordChild->eType != CXT_Text) {
+      psCoordChild = psCoordChild->psNext;
+    }
+    if (psCoordChild && psCoordChild->pszValue) {
+      pszTmpCoord = psCoordChild->pszValue;
+      if (pszTS)
+        papszCoords = msStringSplit(pszTmpCoord, pszTS[0], &nCoords);
+      else
+        papszCoords = msStringSplit(pszTmpCoord, ' ', &nCoords);
+      if (papszCoords && nCoords == 2) {
+        if (pszCS)
+          papszMin = msStringSplit(papszCoords[0], pszCS[0], &nCoordsMin);
         else
-        {
-            psCoord1 = CPLGetXMLNode(psBox, "coord");
-            if (psCoord1 && psCoord1->psNext && 
-                psCoord1->psNext->pszValue && 
-                strcmp(psCoord1->psNext->pszValue, "coord") ==0)
-            {
-                psCoord2 = psCoord1->psNext;
-                psX =  CPLGetXMLNode(psCoord1, "X");
-                psY =  CPLGetXMLNode(psCoord1, "Y");
-                if (psX && psY && psX->psChild && psY->psChild &&
-                    psX->psChild->pszValue && psY->psChild->pszValue)
-                {
-                    minx = atof(psX->psChild->pszValue);
-                    miny = atof(psY->psChild->pszValue);
-
-                    psX =  CPLGetXMLNode(psCoord2, "X");
-                    psY =  CPLGetXMLNode(psCoord2, "Y");
-                    if (psX && psY && psX->psChild && psY->psChild &&
-                        psX->psChild->pszValue && psY->psChild->pszValue)
-                    {
-                        maxx = atof(psX->psChild->pszValue);
-                        maxy = atof(psY->psChild->pszValue);
-                        bCoordinatesValid = 1;
-                    }
-                }
-            }
-                    
+          papszMin = msStringSplit(papszCoords[0], ',', &nCoordsMin);
+        if (papszMin && nCoordsMin == 2) {
+          if (pszCS)
+            papszMax = msStringSplit(papszCoords[1], pszCS[0], &nCoordsMax);
+          else
+            papszMax = msStringSplit(papszCoords[1], ',', &nCoordsMax);
         }
-    }
+        if (papszMax && nCoordsMax == 2) {
+          bCoordinatesValid =1;
+          minx =  atof(papszMin[0]);
+          miny =  atof(papszMin[1]);
+          maxx =  atof(papszMax[0]);
+          maxy =  atof(papszMax[1]);
+        }
+
+        msFreeCharArray(papszMin, nCoordsMin);
+        msFreeCharArray(papszMax, nCoordsMax);
+      }
 
-    if (bCoordinatesValid)
-    {
-        psBbox->minx =  minx;
-        psBbox->miny =  miny;
+      msFreeCharArray(papszCoords, nCoords);
+    } else {
+      psCoord1 = CPLGetXMLNode(psBox, "coord");
+      if (psCoord1 && psCoord1->psNext &&
+          psCoord1->psNext->pszValue &&
+          strcmp(psCoord1->psNext->pszValue, "coord") ==0) {
+        psCoord2 = psCoord1->psNext;
+        psX =  CPLGetXMLNode(psCoord1, "X");
+        psY =  CPLGetXMLNode(psCoord1, "Y");
+        if (psX && psY && psX->psChild && psY->psChild &&
+            psX->psChild->pszValue && psY->psChild->pszValue) {
+          minx = atof(psX->psChild->pszValue);
+          miny = atof(psY->psChild->pszValue);
+
+          psX =  CPLGetXMLNode(psCoord2, "X");
+          psY =  CPLGetXMLNode(psCoord2, "Y");
+          if (psX && psY && psX->psChild && psY->psChild &&
+              psX->psChild->pszValue && psY->psChild->pszValue) {
+            maxx = atof(psX->psChild->pszValue);
+            maxy = atof(psY->psChild->pszValue);
+            bCoordinatesValid = 1;
+          }
+        }
+      }
 
-        psBbox->maxx =  maxx;
-        psBbox->maxy =  maxy;
     }
+  }
+
+  if (bCoordinatesValid) {
+    psBbox->minx =  minx;
+    psBbox->miny =  miny;
+
+    psBbox->maxx =  maxx;
+    psBbox->maxy =  maxy;
+  }
 
-    return bCoordinatesValid;
+  return bCoordinatesValid;
 }
 /************************************************************************/
 /*                           FLTParseGMLEnvelope                        */
@@ -3254,144 +3231,130 @@ int FLTParseGMLBox(CPLXMLNode *psBox, rectObj *psBbox, char **ppszSRS)
 /************************************************************************/
 int FLTParseGMLEnvelope(CPLXMLNode *psRoot, rectObj *psBbox, char **ppszSRS)
 {
-    CPLXMLNode *psChild=NULL; 
-    CPLXMLNode *psUpperCorner=NULL, *psLowerCorner=NULL;
-    char *pszLowerCorner=NULL, *pszUpperCorner=NULL;
-    int bValid = 0;
-    char **tokens;
-    int n;
-
-    if (psRoot && psBbox && psRoot->eType == CXT_Element && 
-        EQUAL(psRoot->pszValue,"Envelope")) 
-    {
-        /*Get the srs if available*/
-        if (ppszSRS)
-        {
-            psChild = psRoot->psChild;
-            while (psChild != NULL) 
-            {
-               if (psChild->eType == CXT_Attribute && psChild->pszValue &&
-                   EQUAL(psChild->pszValue, "srsName") && psChild->psChild &&
-                   psChild->psChild->pszValue)
-               {
-                   *ppszSRS = msStrdup(psChild->psChild->pszValue);
-                   break;
-               } 
-               psChild = psChild->psNext;
-            }
+  CPLXMLNode *psChild=NULL;
+  CPLXMLNode *psUpperCorner=NULL, *psLowerCorner=NULL;
+  char *pszLowerCorner=NULL, *pszUpperCorner=NULL;
+  int bValid = 0;
+  char **tokens;
+  int n;
+
+  if (psRoot && psBbox && psRoot->eType == CXT_Element &&
+      EQUAL(psRoot->pszValue,"Envelope")) {
+    /*Get the srs if available*/
+    if (ppszSRS) {
+      psChild = psRoot->psChild;
+      while (psChild != NULL) {
+        if (psChild->eType == CXT_Attribute && psChild->pszValue &&
+            EQUAL(psChild->pszValue, "srsName") && psChild->psChild &&
+            psChild->psChild->pszValue) {
+          *ppszSRS = msStrdup(psChild->psChild->pszValue);
+          break;
         }
-        psLowerCorner = CPLSearchXMLNode(psRoot, "lowerCorner");
-        psUpperCorner = CPLSearchXMLNode(psRoot, "upperCorner");
+        psChild = psChild->psNext;
+      }
+    }
+    psLowerCorner = CPLSearchXMLNode(psRoot, "lowerCorner");
+    psUpperCorner = CPLSearchXMLNode(psRoot, "upperCorner");
 
-        if (psLowerCorner && psUpperCorner && EQUAL(psLowerCorner->pszValue,"lowerCorner") && 
-            EQUAL(psUpperCorner->pszValue,"upperCorner")) 
-        {
-                /*get the values*/
-            psChild = psLowerCorner->psChild;
-            while (psChild != NULL) {
-                if (psChild->eType != CXT_Text)
-                  psChild = psChild->psNext;
-                else
-                  break;
-            }
-            if (psChild && psChild->eType == CXT_Text)
-              pszLowerCorner = psChild->pszValue;
-
-            psChild = psUpperCorner->psChild;
-            while (psChild != NULL) {
-                if (psChild->eType != CXT_Text)
-                  psChild = psChild->psNext;
-                else
-                  break;
-            }
-            if (psChild && psChild->eType == CXT_Text)
-              pszUpperCorner = psChild->pszValue;
-
-            if (pszLowerCorner && pszUpperCorner) {
-                tokens = msStringSplit(pszLowerCorner, ' ', &n);
-                if (tokens && n >= 2) {
-                    psBbox->minx = atof(tokens[0]);
-                    psBbox->miny = atof(tokens[1]);
-
-                    msFreeCharArray(tokens, n);
-
-                    tokens = msStringSplit(pszUpperCorner, ' ', &n);
-                    if (tokens && n >= 2) {
-                        psBbox->maxx = atof(tokens[0]);
-                        psBbox->maxy = atof(tokens[1]);
-                        msFreeCharArray(tokens, n);
-
-                        bValid = 1;
-                    }
-                }
-            }
+    if (psLowerCorner && psUpperCorner && EQUAL(psLowerCorner->pszValue,"lowerCorner") &&
+        EQUAL(psUpperCorner->pszValue,"upperCorner")) {
+      /*get the values*/
+      psChild = psLowerCorner->psChild;
+      while (psChild != NULL) {
+        if (psChild->eType != CXT_Text)
+          psChild = psChild->psNext;
+        else
+          break;
+      }
+      if (psChild && psChild->eType == CXT_Text)
+        pszLowerCorner = psChild->pszValue;
+
+      psChild = psUpperCorner->psChild;
+      while (psChild != NULL) {
+        if (psChild->eType != CXT_Text)
+          psChild = psChild->psNext;
+        else
+          break;
+      }
+      if (psChild && psChild->eType == CXT_Text)
+        pszUpperCorner = psChild->pszValue;
+
+      if (pszLowerCorner && pszUpperCorner) {
+        tokens = msStringSplit(pszLowerCorner, ' ', &n);
+        if (tokens && n >= 2) {
+          psBbox->minx = atof(tokens[0]);
+          psBbox->miny = atof(tokens[1]);
+
+          msFreeCharArray(tokens, n);
+
+          tokens = msStringSplit(pszUpperCorner, ' ', &n);
+          if (tokens && n >= 2) {
+            psBbox->maxx = atof(tokens[0]);
+            psBbox->maxy = atof(tokens[1]);
+            msFreeCharArray(tokens, n);
+
+            bValid = 1;
+          }
         }
+      }
     }
-    if (bValid && ppszSRS && *ppszSRS)
-    {
-        projectionObj sProjTmp;
-        msInitProjection(&sProjTmp);
-        if (msLoadProjectionStringEPSG(&sProjTmp, *ppszSRS) == 0)
-        {
-            msAxisNormalizePoints( &sProjTmp, 1, &psBbox->minx, &psBbox->miny);
-            msAxisNormalizePoints( &sProjTmp, 1, &psBbox->maxx, &psBbox->maxy);
-        }
+  }
+  if (bValid && ppszSRS && *ppszSRS) {
+    projectionObj sProjTmp;
+    msInitProjection(&sProjTmp);
+    if (msLoadProjectionStringEPSG(&sProjTmp, *ppszSRS) == 0) {
+      msAxisNormalizePoints( &sProjTmp, 1, &psBbox->minx, &psBbox->miny);
+      msAxisNormalizePoints( &sProjTmp, 1, &psBbox->maxx, &psBbox->maxy);
     }
-    return bValid;
+  }
+  return bValid;
 }
 
 
 static void FLTReplacePropertyName(FilterEncodingNode *psFilterNode,
                                    const char *pszOldName, char *pszNewName)
 {
-    if (psFilterNode && pszOldName && pszNewName)
-    {
-        if (psFilterNode->eType == FILTER_NODE_TYPE_PROPERTYNAME)
-        {
-            if (psFilterNode->pszValue && 
-                strcasecmp(psFilterNode->pszValue, pszOldName) == 0)
-            {
-                msFree(psFilterNode->pszValue);
-                psFilterNode->pszValue = msStrdup(pszNewName);
-            }
-        }
-        if (psFilterNode->psLeftNode)
-          FLTReplacePropertyName(psFilterNode->psLeftNode, pszOldName,
-                                   pszNewName);
-        if (psFilterNode->psRightNode)
-          FLTReplacePropertyName(psFilterNode->psRightNode, pszOldName,
-                                 pszNewName);
+  if (psFilterNode && pszOldName && pszNewName) {
+    if (psFilterNode->eType == FILTER_NODE_TYPE_PROPERTYNAME) {
+      if (psFilterNode->pszValue &&
+          strcasecmp(psFilterNode->pszValue, pszOldName) == 0) {
+        msFree(psFilterNode->pszValue);
+        psFilterNode->pszValue = msStrdup(pszNewName);
+      }
     }
+    if (psFilterNode->psLeftNode)
+      FLTReplacePropertyName(psFilterNode->psLeftNode, pszOldName,
+                             pszNewName);
+    if (psFilterNode->psRightNode)
+      FLTReplacePropertyName(psFilterNode->psRightNode, pszOldName,
+                             pszNewName);
+  }
 }
 
 
 static void FLTStripNameSpacesFromPropertyName(FilterEncodingNode *psFilterNode)
 {
-    char **tokens=NULL;
-    int n=0;
-
-    if (psFilterNode)
-    {
-         if (psFilterNode->eType == FILTER_NODE_TYPE_PROPERTYNAME)
-         {
-             if (psFilterNode->pszValue &&  
-                 strstr(psFilterNode->pszValue, ":"))
-             {
-                 tokens = msStringSplit(psFilterNode->pszValue, ':', &n);
-                 if (tokens && n==2)
-                 {
-                     msFree(psFilterNode->pszValue);
-                     psFilterNode->pszValue = msStrdup(tokens[1]);
-                 }
-                 if (tokens && n>0)
-                   msFreeCharArray(tokens, n);
-             }
-         }
-         if (psFilterNode->psLeftNode)
-           FLTStripNameSpacesFromPropertyName(psFilterNode->psLeftNode);
-         if (psFilterNode->psRightNode)
-           FLTStripNameSpacesFromPropertyName(psFilterNode->psRightNode);
+  char **tokens=NULL;
+  int n=0;
+
+  if (psFilterNode) {
+    if (psFilterNode->eType == FILTER_NODE_TYPE_PROPERTYNAME) {
+      if (psFilterNode->pszValue &&
+          strstr(psFilterNode->pszValue, ":")) {
+        tokens = msStringSplit(psFilterNode->pszValue, ':', &n);
+        if (tokens && n==2) {
+          msFree(psFilterNode->pszValue);
+          psFilterNode->pszValue = msStrdup(tokens[1]);
+        }
+        if (tokens && n>0)
+          msFreeCharArray(tokens, n);
+      }
     }
+    if (psFilterNode->psLeftNode)
+      FLTStripNameSpacesFromPropertyName(psFilterNode->psLeftNode);
+    if (psFilterNode->psRightNode)
+      FLTStripNameSpacesFromPropertyName(psFilterNode->psRightNode);
+  }
 
 }
 
@@ -3401,43 +3364,42 @@ static void FLTStripNameSpacesFromPropertyName(FilterEncodingNode *psFilterNode)
 /*      Utility function to replace aliased' attributes with their      */
 /*      real name.                                                      */
 /************************************************************************/
-void FLTPreParseFilterForAlias(FilterEncodingNode *psFilterNode, 
+void FLTPreParseFilterForAlias(FilterEncodingNode *psFilterNode,
                                mapObj *map, int i, const char *namespaces)
 {
-    layerObj *lp=NULL;
-    char szTmp[256];
-    const char *pszFullName = NULL;
+  layerObj *lp=NULL;
+  char szTmp[256];
+  const char *pszFullName = NULL;
+  int layerWasOpened =  MS_FALSE;
 
 #if defined(USE_WMS_SVR) || defined (USE_WFS_SVR) || defined (USE_WCS_SVR) || defined(USE_SOS_SVR)
 
-    if (psFilterNode && map && i>=0 && i<map->numlayers)
-    {
-        /*strip name speces befor hand*/
-        FLTStripNameSpacesFromPropertyName(psFilterNode);
-
-        lp = GET_LAYER(map, i);
-        if (msLayerOpen(lp) == MS_SUCCESS && msLayerGetItems(lp) == MS_SUCCESS)
-        {
-            for(i=0; i<lp->numitems; i++) 
-            {
-                if (!lp->items[i] || strlen(lp->items[i]) <= 0)
-                    continue;
-                snprintf(szTmp, sizeof(szTmp), "%s_alias", lp->items[i]);
-                pszFullName = msOWSLookupMetadata(&(lp->metadata), namespaces, szTmp);
-                if (pszFullName)
-                {
-                    FLTReplacePropertyName(psFilterNode, pszFullName, 
-                                           lp->items[i]);
-                }
-            }
-            msLayerClose(lp);
+  if (psFilterNode && map && i>=0 && i<map->numlayers) {
+    /*strip name speces befor hand*/
+    FLTStripNameSpacesFromPropertyName(psFilterNode);
+
+    lp = GET_LAYER(map, i);
+    layerWasOpened = msLayerIsOpen(lp);
+    if (msLayerOpen(lp) == MS_SUCCESS && msLayerGetItems(lp) == MS_SUCCESS) {
+      for(i=0; i<lp->numitems; i++) {
+        if (!lp->items[i] || strlen(lp->items[i]) <= 0)
+          continue;
+        snprintf(szTmp, sizeof(szTmp), "%s_alias", lp->items[i]);
+        pszFullName = msOWSLookupMetadata(&(lp->metadata), namespaces, szTmp);
+        if (pszFullName) {
+          FLTReplacePropertyName(psFilterNode, pszFullName,
+                                 lp->items[i]);
         }
-    } 
+      }
+      if (!layerWasOpened) /* do not close the layer if it has been opened somewhere else (paging?) */
+        msLayerClose(lp);
+    }
+  }
 #else
-    msSetError(MS_MISCERR, "OWS support is not available.", 
-               "FLTPreParseFilterForAlias()");
-    
-#endif   
+  msSetError(MS_MISCERR, "OWS support is not available.",
+             "FLTPreParseFilterForAlias()");
+
+#endif
 }
 
 
@@ -3445,71 +3407,70 @@ void FLTPreParseFilterForAlias(FilterEncodingNode *psFilterNode,
 
 xmlNodePtr FLTGetCapabilities(xmlNsPtr psNsParent, xmlNsPtr psNsOgc, int bTemporal)
 {
-    xmlNodePtr psRootNode = NULL, psNode = NULL, psSubNode = NULL, psSubSubNode = NULL;
-    
-    psRootNode = xmlNewNode(psNsParent, BAD_CAST "Filter_Capabilities");
-    
-    psNode = xmlNewChild(psRootNode, psNsOgc, BAD_CAST "Spatial_Capabilities", NULL);
-
-    psSubNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "GeometryOperands", NULL);
-    psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "GeometryOperand", BAD_CAST "gml:Point");
-    psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "GeometryOperand", BAD_CAST "gml:LineString");
-    psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "GeometryOperand", BAD_CAST "gml:Polygon");
-    psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "GeometryOperand", BAD_CAST "gml:Envelope");
-
-    psSubNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "SpatialOperators", NULL);
+  xmlNodePtr psRootNode = NULL, psNode = NULL, psSubNode = NULL, psSubSubNode = NULL;
+
+  psRootNode = xmlNewNode(psNsParent, BAD_CAST "Filter_Capabilities");
+
+  psNode = xmlNewChild(psRootNode, psNsOgc, BAD_CAST "Spatial_Capabilities", NULL);
+
+  psSubNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "GeometryOperands", NULL);
+  psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "GeometryOperand", BAD_CAST "gml:Point");
+  psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "GeometryOperand", BAD_CAST "gml:LineString");
+  psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "GeometryOperand", BAD_CAST "gml:Polygon");
+  psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "GeometryOperand", BAD_CAST "gml:Envelope");
+
+  psSubNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "SpatialOperators", NULL);
 #ifdef USE_GEOS
-    psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "SpatialOperator", NULL);
-    xmlNewProp(psSubSubNode, BAD_CAST "name", BAD_CAST "Equals");
-    psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "SpatialOperator", NULL);
-    xmlNewProp(psSubSubNode, BAD_CAST "name", BAD_CAST "Disjoint");
-    psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "SpatialOperator", NULL);
-    xmlNewProp(psSubSubNode, BAD_CAST "name", BAD_CAST "Touches");
-    psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "SpatialOperator", NULL);
-    xmlNewProp(psSubSubNode, BAD_CAST "name", BAD_CAST "Within");
-    psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "SpatialOperator", NULL);
-    xmlNewProp(psSubSubNode, BAD_CAST "name", BAD_CAST "Overlaps");
-    psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "SpatialOperator", NULL);
-    xmlNewProp(psSubSubNode, BAD_CAST "name", BAD_CAST "Crosses");
-    psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "SpatialOperator", NULL);
-    xmlNewProp(psSubSubNode, BAD_CAST "name", BAD_CAST "Intersects");
-    psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "SpatialOperator", NULL);
-    xmlNewProp(psSubSubNode, BAD_CAST "name", BAD_CAST "Contains");
-    psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "SpatialOperator", NULL);
-    xmlNewProp(psSubSubNode, BAD_CAST "name", BAD_CAST "DWithin");
-    psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "SpatialOperator", NULL);
-    xmlNewProp(psSubSubNode, BAD_CAST "name", BAD_CAST "Beyond");
+  psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "SpatialOperator", NULL);
+  xmlNewProp(psSubSubNode, BAD_CAST "name", BAD_CAST "Equals");
+  psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "SpatialOperator", NULL);
+  xmlNewProp(psSubSubNode, BAD_CAST "name", BAD_CAST "Disjoint");
+  psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "SpatialOperator", NULL);
+  xmlNewProp(psSubSubNode, BAD_CAST "name", BAD_CAST "Touches");
+  psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "SpatialOperator", NULL);
+  xmlNewProp(psSubSubNode, BAD_CAST "name", BAD_CAST "Within");
+  psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "SpatialOperator", NULL);
+  xmlNewProp(psSubSubNode, BAD_CAST "name", BAD_CAST "Overlaps");
+  psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "SpatialOperator", NULL);
+  xmlNewProp(psSubSubNode, BAD_CAST "name", BAD_CAST "Crosses");
+  psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "SpatialOperator", NULL);
+  xmlNewProp(psSubSubNode, BAD_CAST "name", BAD_CAST "Intersects");
+  psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "SpatialOperator", NULL);
+  xmlNewProp(psSubSubNode, BAD_CAST "name", BAD_CAST "Contains");
+  psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "SpatialOperator", NULL);
+  xmlNewProp(psSubSubNode, BAD_CAST "name", BAD_CAST "DWithin");
+  psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "SpatialOperator", NULL);
+  xmlNewProp(psSubSubNode, BAD_CAST "name", BAD_CAST "Beyond");
 #endif
-    psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "SpatialOperator", NULL);
-    xmlNewProp(psSubSubNode, BAD_CAST "name", BAD_CAST "BBOX");
-
-    if (bTemporal)
-    {
-        psNode = xmlNewChild(psRootNode, psNsOgc, BAD_CAST "Temporal_Capabilities", NULL);
-        psSubNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "TemporalOperands", NULL);
-        psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "TemporalOperand", BAD_CAST "gml:TimePeriod");
-        psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "TemporalOperand", BAD_CAST "gml:TimeInstant");
-
-        psSubNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "TemporalOperators", NULL);
-        psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "TemporalOperator", NULL);
-        xmlNewProp(psSubSubNode, BAD_CAST "name", BAD_CAST "TM_Equals");
-    }
-    psNode = xmlNewChild(psRootNode, psNsOgc, BAD_CAST "Scalar_Capabilities", NULL);
-    xmlNewChild(psNode, psNsOgc, BAD_CAST "LogicalOperators", NULL);
-    psNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "ComparisonOperators", NULL);
-    psSubNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "ComparisonOperator", BAD_CAST "LessThan");
-    psSubNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "ComparisonOperator", BAD_CAST "GreaterThan");
-    psSubNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "ComparisonOperator", BAD_CAST "LessThanEqualTo");
-    psSubNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "ComparisonOperator", BAD_CAST "GreaterThanEqualTo");
-    psSubNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "ComparisonOperator", BAD_CAST "EqualTo");
-    psSubNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "ComparisonOperator", BAD_CAST "NotEqualTo");
-    psSubNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "ComparisonOperator", BAD_CAST "Like");
-    psSubNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "ComparisonOperator", BAD_CAST "Between");
-    
-    psNode = xmlNewChild(psRootNode, psNsOgc, BAD_CAST "Id_Capabilities", NULL);
-    xmlNewChild(psNode, psNsOgc, BAD_CAST "EID", NULL);
-    xmlNewChild(psNode, psNsOgc, BAD_CAST "FID", NULL);
-    return psRootNode;
+  psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "SpatialOperator", NULL);
+  xmlNewProp(psSubSubNode, BAD_CAST "name", BAD_CAST "BBOX");
+
+  if (bTemporal) {
+    psNode = xmlNewChild(psRootNode, psNsOgc, BAD_CAST "Temporal_Capabilities", NULL);
+    psSubNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "TemporalOperands", NULL);
+    psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "TemporalOperand", BAD_CAST "gml:TimePeriod");
+    psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "TemporalOperand", BAD_CAST "gml:TimeInstant");
+
+    psSubNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "TemporalOperators", NULL);
+    psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "TemporalOperator", NULL);
+    xmlNewProp(psSubSubNode, BAD_CAST "name", BAD_CAST "TM_Equals");
+  }
+  psNode = xmlNewChild(psRootNode, psNsOgc, BAD_CAST "Scalar_Capabilities", NULL);
+  xmlNewChild(psNode, psNsOgc, BAD_CAST "LogicalOperators", NULL);
+  psNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "ComparisonOperators", NULL);
+  psSubNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "ComparisonOperator", BAD_CAST "LessThan");
+  psSubNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "ComparisonOperator", BAD_CAST "GreaterThan");
+  psSubNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "ComparisonOperator", BAD_CAST "LessThanEqualTo");
+  psSubNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "ComparisonOperator", BAD_CAST "GreaterThanEqualTo");
+  psSubNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "ComparisonOperator", BAD_CAST "EqualTo");
+  psSubNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "ComparisonOperator", BAD_CAST "NotEqualTo");
+  psSubNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "ComparisonOperator", BAD_CAST "Like");
+  psSubNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "ComparisonOperator", BAD_CAST "Between");
+
+  psNode = xmlNewChild(psRootNode, psNsOgc, BAD_CAST "Id_Capabilities", NULL);
+  xmlNewChild(psNode, psNsOgc, BAD_CAST "EID", NULL);
+  xmlNewChild(psNode, psNsOgc, BAD_CAST "FID", NULL);
+  return psRootNode;
 }
 #endif
 #endif
diff --git a/mapogcfilter.h b/mapogcfilter.h
index 7a216a2..b06c9ec 100644
--- a/mapogcfilter.h
+++ b/mapogcfilter.h
@@ -14,22 +14,28 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
+ *
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  ****************************************************************************/
 
 #ifndef MAPOGCFILTER_H
 #define MAPOGCFILTER_H
 
 #include "mapserver.h"
+
+/*dont need ogr for these functikons*/
+MS_DLL_EXPORT int FLTIsNumeric(char *pszValue);
+MS_DLL_EXPORT int FLTApplyExpressionToLayer(layerObj *lp, char *pszExpression);
+MS_DLL_EXPORT  char *FLTGetExpressionForValuesRanges(layerObj *lp, char *item, char *value,  int forcecharcter);
+
 #ifdef USE_OGR
 
 /* There is a dependency to OGR for the MiniXML parser */
@@ -42,45 +48,44 @@
 #endif
 
 
-typedef struct
-{
-      char *pszWildCard;
-      char *pszSingleChar;
-      char *pszEscapeChar;
-      int  bCaseInsensitive;
-}FEPropertyIsLike;
+typedef struct {
+  char *pszWildCard;
+  char *pszSingleChar;
+  char *pszEscapeChar;
+  int  bCaseInsensitive;
+} FEPropertyIsLike;
 
 /* -------------------------------------------------------------------- */
 /*      prototypes.                                                     */
 /* -------------------------------------------------------------------- */
 MS_DLL_EXPORT FilterEncodingNode *FLTParseFilterEncoding(char *szXMLString);
 MS_DLL_EXPORT FilterEncodingNode *FLTCreateFilterEncodingNode(void);
-MS_DLL_EXPORT int FLTApplyFilterToLayer(FilterEncodingNode *psNode, mapObj *map, 
+MS_DLL_EXPORT int FLTApplyFilterToLayer(FilterEncodingNode *psNode, mapObj *map,
                                         int iLayerIndex);
 
-MS_DLL_EXPORT int FLTLayerApplyCondSQLFilterToLayer(FilterEncodingNode *psNode, mapObj *map, 
-                                                    int iLayerIndex);
-MS_DLL_EXPORT int FLTLayerApplyPlainFilterToLayer(FilterEncodingNode *psNode, mapObj *map, 
-                                                  int iLayerIndex);
+MS_DLL_EXPORT int FLTLayerApplyCondSQLFilterToLayer(FilterEncodingNode *psNode, mapObj *map,
+    int iLayerIndex);
+MS_DLL_EXPORT int FLTLayerApplyPlainFilterToLayer(FilterEncodingNode *psNode, mapObj *map,
+    int iLayerIndex);
 
 MS_DLL_EXPORT void FLTFreeFilterEncodingNode(FilterEncodingNode *psFilterNode);
 
 MS_DLL_EXPORT int FLTValidFilterNode(FilterEncodingNode *psFilterNode);
 MS_DLL_EXPORT int FLTValidForBBoxFilter(FilterEncodingNode *psFilterNode);
-MS_DLL_EXPORT int FLTNumberOfFilterType(FilterEncodingNode *psFilterNode, 
-                          const char *szType);
+MS_DLL_EXPORT int FLTNumberOfFilterType(FilterEncodingNode *psFilterNode,
+                                        const char *szType);
 MS_DLL_EXPORT int FLTIsBBoxFilter(FilterEncodingNode *psFilterNode);
 MS_DLL_EXPORT int FLTIsPointFilter(FilterEncodingNode *psFilterNode);
 MS_DLL_EXPORT int FLTIsLineFilter(FilterEncodingNode *psFilterNode);
 MS_DLL_EXPORT int FLTIsPolygonFilter(FilterEncodingNode *psFilterNode);
 
 MS_DLL_EXPORT int FLTValidForPropertyIsLikeFilter(FilterEncodingNode *psFilterNode);
-MS_DLL_EXPORT char *FLTGetMapserverIsPropertyExpression(FilterEncodingNode *psFilterNode, 
-                                                        layerObj *lp);
+MS_DLL_EXPORT char *FLTGetMapserverIsPropertyExpression(FilterEncodingNode *psFilterNode,
+    layerObj *lp);
 MS_DLL_EXPORT int FLTIsOnlyPropertyIsLike(FilterEncodingNode *psFilterNode);
 
 MS_DLL_EXPORT void FLTInsertElementInNode(FilterEncodingNode *psFilterNode,
-                            CPLXMLNode *psXMLNode);
+    CPLXMLNode *psXMLNode);
 MS_DLL_EXPORT int FLTIsLogicalFilterType(char *pszValue);
 MS_DLL_EXPORT int FLTIsBinaryComparisonFilterType(char *pszValue);
 MS_DLL_EXPORT int FLTIsComparisonFilterType(char *pszValue);
@@ -93,7 +98,7 @@ MS_DLL_EXPORT char *FLTGetNodeExpression(FilterEncodingNode *psFilterNode, layer
 MS_DLL_EXPORT char *FLTGetBBOX(FilterEncodingNode *psFilterNode, rectObj *psRect);
 
 MS_DLL_EXPORT shapeObj *FLTGetShape(FilterEncodingNode *psFilterNode, double *pdfDistance,
-                      int *pnUnit);
+                                    int *pnUnit);
 
 MS_DLL_EXPORT char *FLTGetLogicalComparisonExpresssion(FilterEncodingNode *psFilterNode, layerObj *lp);
 MS_DLL_EXPORT char *FLTGetBinaryComparisonExpresssion(FilterEncodingNode *psFilterNode, layerObj *lp);
@@ -103,8 +108,8 @@ MS_DLL_EXPORT int FLTHasSpatialFilter(FilterEncodingNode *psFilterNode);
 
 
 /*SQL expressions related functions.*/
-MS_DLL_EXPORT int FLTApplySimpleSQLFilter(FilterEncodingNode *psNode, mapObj *map, 
-                          int iLayerIndex);
+MS_DLL_EXPORT int FLTApplySimpleSQLFilter(FilterEncodingNode *psNode, mapObj *map,
+    int iLayerIndex);
 
 MS_DLL_EXPORT char *FLTGetSQLExpression(FilterEncodingNode *psFilterNode,layerObj *lp);
 MS_DLL_EXPORT char *FLTGetBinaryComparisonSQLExpresssion(FilterEncodingNode *psFilterNode, layerObj *lp);
@@ -112,7 +117,7 @@ MS_DLL_EXPORT char *FLTGetIsBetweenComparisonSQLExpresssion(FilterEncodingNode *
 MS_DLL_EXPORT char *FLTGetIsLikeComparisonSQLExpression(FilterEncodingNode *psFilterNode, layerObj *lp);
 
 MS_DLL_EXPORT char *FLTGetLogicalComparisonSQLExpresssion(FilterEncodingNode *psFilterNode,
-                                            layerObj *lp);
+    layerObj *lp);
 MS_DLL_EXPORT int FLTIsSimpleFilter(FilterEncodingNode *psFilterNode);
 
 MS_DLL_EXPORT FilterEncodingNode *FLTCreateFeatureIdFilterEncoding(char *pszString);
@@ -120,7 +125,6 @@ MS_DLL_EXPORT FilterEncodingNode *FLTCreateFeatureIdFilterEncoding(char *pszStri
 MS_DLL_EXPORT int FLTParseGMLEnvelope(CPLXMLNode *psRoot, rectObj *psBbox, char **ppszSRS);
 MS_DLL_EXPORT  int FLTParseGMLBox(CPLXMLNode *psBox, rectObj *psBbox, char **ppszSRS);
 
-MS_DLL_EXPORT int FLTIsNumeric(char *pszValue);
 /*common-expressions*/
 MS_DLL_EXPORT   char *FLTGetBinaryComparisonCommonExpression(FilterEncodingNode *psFilterNode, layerObj *lp);
 MS_DLL_EXPORT  char *FLTGetCommonExpression(FilterEncodingNode *psFilterNode, layerObj *lp);
@@ -132,7 +136,7 @@ MS_DLL_EXPORT xmlNodePtr FLTGetCapabilities(xmlNsPtr psNsParent, xmlNsPtr psNsOg
 #endif
 
 
-void FLTPreParseFilterForAlias(FilterEncodingNode *psFilterNode, 
+void FLTPreParseFilterForAlias(FilterEncodingNode *psFilterNode,
                                mapObj *map, int i, const char *namespaces);
 
 #endif
diff --git a/mapogcfiltercommon.c b/mapogcfiltercommon.c
index afdf7a2..cdd6abc 100644
--- a/mapogcfiltercommon.c
+++ b/mapogcfiltercommon.c
@@ -14,16 +14,16 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
+ *
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  ****************************************************************************/
 
 #ifdef USE_OGR
@@ -34,699 +34,667 @@
 #include "mapserver.h"
 #include "mapowscommon.h"
 
-MS_CVSID("$Id$")
+
 
 #ifdef USE_OGR
 
 static int FTLParseEpsgString(char *pszEpsg, projectionObj *psProj)
 {
-    int nStatus = MS_FALSE;
-    int nTokens = 0;
-    char **tokens = NULL;
-    int nEpsgTmp=0;
+  int nStatus = MS_FALSE;
+  int nTokens = 0;
+  char **tokens = NULL;
+  int nEpsgTmp=0;
 
 #ifdef USE_PROJ
-    if (pszEpsg && psProj)
-    {
-        nTokens = 0;
-        tokens = msStringSplit(pszEpsg,'#', &nTokens);
-        if (tokens && nTokens == 2)
-        {
-            char szTmp[32];
-            sprintf(szTmp, "init=epsg:%s",tokens[1]);
-            msInitProjection(psProj);
-            if (msLoadProjectionString(psProj, szTmp) == 0)
-              nStatus = MS_TRUE;
-        }
-        else if (tokens &&  nTokens == 1)
-        {
-            if (tokens)
-              msFreeCharArray(tokens, nTokens);
-            nTokens = 0;
-
-            tokens = msStringSplit(pszEpsg,':', &nTokens);
-            nEpsgTmp = -1;
-            if (tokens &&  nTokens == 1)
-            {
-                nEpsgTmp = atoi(tokens[0]);
-                
-            }
-            else if (tokens &&  nTokens == 2)
-            {
-                nEpsgTmp = atoi(tokens[1]);
-            }
-            if (nEpsgTmp > 0)
-            {
-                char szTmp[32];
-                sprintf(szTmp, "init=epsg:%d",nEpsgTmp);
-                msInitProjection(psProj);
-                if (msLoadProjectionString(psProj, szTmp) == 0)
-                  nStatus = MS_TRUE;
-            }
-        }
-        if (tokens)
-          msFreeCharArray(tokens, nTokens);
+  if (pszEpsg && psProj) {
+    nTokens = 0;
+    tokens = msStringSplit(pszEpsg,'#', &nTokens);
+    if (tokens && nTokens == 2) {
+      char szTmp[32];
+      sprintf(szTmp, "init=epsg:%s",tokens[1]);
+      msInitProjection(psProj);
+      if (msLoadProjectionString(psProj, szTmp) == 0)
+        nStatus = MS_TRUE;
+    } else if (tokens &&  nTokens == 1) {
+      if (tokens)
+        msFreeCharArray(tokens, nTokens);
+      nTokens = 0;
+
+      tokens = msStringSplit(pszEpsg,':', &nTokens);
+      nEpsgTmp = -1;
+      if (tokens &&  nTokens == 1) {
+        nEpsgTmp = atoi(tokens[0]);
+
+      } else if (tokens &&  nTokens == 2) {
+        nEpsgTmp = atoi(tokens[1]);
+      }
+      if (nEpsgTmp > 0) {
+        char szTmp[32];
+        sprintf(szTmp, "init=epsg:%d",nEpsgTmp);
+        msInitProjection(psProj);
+        if (msLoadProjectionString(psProj, szTmp) == 0)
+          nStatus = MS_TRUE;
+      }
     }
+    if (tokens)
+      msFreeCharArray(tokens, nTokens);
+  }
 #endif
-    return nStatus;
+  return nStatus;
 }
 
 char *FLTGetIsLikeComparisonCommonExpression(FilterEncodingNode *psFilterNode)
 {
-    const size_t bufferSize = 1024;
-    char szBuffer[1024];
-    char szTmp[256];
-    char *pszValue = NULL;
-    
-    char *pszWild = NULL;
-    char *pszSingle = NULL;
-    char *pszEscape = NULL;
-    int  bCaseInsensitive = 0;
-
-    int nLength=0, i=0, iTmp=0;
-
-
-    if (!psFilterNode || !psFilterNode->pOther || !psFilterNode->psLeftNode ||
-        !psFilterNode->psRightNode || !psFilterNode->psRightNode->pszValue)
-      return NULL;
-
-    pszWild = ((FEPropertyIsLike *)psFilterNode->pOther)->pszWildCard;
-    pszSingle = ((FEPropertyIsLike *)psFilterNode->pOther)->pszSingleChar;
-    pszEscape = ((FEPropertyIsLike *)psFilterNode->pOther)->pszEscapeChar;
-    bCaseInsensitive = ((FEPropertyIsLike *)psFilterNode->pOther)->bCaseInsensitive;
-
-    if (!pszWild || strlen(pszWild) == 0 ||
-        !pszSingle || strlen(pszSingle) == 0 || 
-        !pszEscape || strlen(pszEscape) == 0)
-      return NULL;
-
- 
-/* -------------------------------------------------------------------- */
-/*      Use operand with regular expressions.                           */
-/* -------------------------------------------------------------------- */
-    szBuffer[0] = '\0';
-    sprintf(szTmp, "%s", " (\"[");
-    szTmp[4] = '\0';
-
-    strlcat(szBuffer, szTmp, bufferSize);
-
-    /* attribute */
-    strlcat(szBuffer, psFilterNode->psLeftNode->pszValue, bufferSize);
-    szBuffer[strlen(szBuffer)] = '\0';
-
-    /*#3521 */
-    if(bCaseInsensitive == 1)
-      sprintf(szTmp, "%s", "]\" ~* \"");
-    else
-      sprintf(szTmp, "%s", "]\" ~ \"");
-    szTmp[7] = '\0';
-    strlcat(szBuffer, szTmp, bufferSize);
-    szBuffer[strlen(szBuffer)] = '\0';
-
-
-    pszValue = psFilterNode->psRightNode->pszValue;
-    nLength = strlen(pszValue);
-    
-    iTmp =0;
-    if (nLength > 0 && pszValue[0] != pszWild[0] && 
-        pszValue[0] != pszSingle[0] &&
-        pszValue[0] != pszEscape[0])
-    {
-      szTmp[iTmp]= '^';
+  const size_t bufferSize = 1024;
+  char szBuffer[1024];
+  char szTmp[256];
+  char *pszValue = NULL;
+
+  char *pszWild = NULL;
+  char *pszSingle = NULL;
+  char *pszEscape = NULL;
+  int  bCaseInsensitive = 0;
+
+  int nLength=0, i=0, iTmp=0;
+
+
+  if (!psFilterNode || !psFilterNode->pOther || !psFilterNode->psLeftNode ||
+      !psFilterNode->psRightNode || !psFilterNode->psRightNode->pszValue)
+    return NULL;
+
+  pszWild = ((FEPropertyIsLike *)psFilterNode->pOther)->pszWildCard;
+  pszSingle = ((FEPropertyIsLike *)psFilterNode->pOther)->pszSingleChar;
+  pszEscape = ((FEPropertyIsLike *)psFilterNode->pOther)->pszEscapeChar;
+  bCaseInsensitive = ((FEPropertyIsLike *)psFilterNode->pOther)->bCaseInsensitive;
+
+  if (!pszWild || strlen(pszWild) == 0 ||
+      !pszSingle || strlen(pszSingle) == 0 ||
+      !pszEscape || strlen(pszEscape) == 0)
+    return NULL;
+
+
+  /* -------------------------------------------------------------------- */
+  /*      Use operand with regular expressions.                           */
+  /* -------------------------------------------------------------------- */
+  szBuffer[0] = '\0';
+  sprintf(szTmp, "%s", " (\"[");
+  szTmp[4] = '\0';
+
+  strlcat(szBuffer, szTmp, bufferSize);
+
+  /* attribute */
+  strlcat(szBuffer, psFilterNode->psLeftNode->pszValue, bufferSize);
+  szBuffer[strlen(szBuffer)] = '\0';
+
+  /*#3521 */
+  if(bCaseInsensitive == 1)
+    sprintf(szTmp, "%s", "]\" ~* \"");
+  else
+    sprintf(szTmp, "%s", "]\" ~ \"");
+  szTmp[7] = '\0';
+  strlcat(szBuffer, szTmp, bufferSize);
+  szBuffer[strlen(szBuffer)] = '\0';
+
+
+  pszValue = psFilterNode->psRightNode->pszValue;
+  nLength = strlen(pszValue);
+
+  iTmp =0;
+  if (nLength > 0 && pszValue[0] != pszWild[0] &&
+      pszValue[0] != pszSingle[0] &&
+      pszValue[0] != pszEscape[0]) {
+    szTmp[iTmp]= '^';
+    iTmp++;
+  }
+  for (i=0; i<nLength; i++) {
+    if (pszValue[i] != pszWild[0] &&
+        pszValue[i] != pszSingle[0] &&
+        pszValue[i] != pszEscape[0]) {
+      szTmp[iTmp] = pszValue[i];
+      iTmp++;
+      szTmp[iTmp] = '\0';
+    } else if  (pszValue[i] == pszSingle[0]) {
+      szTmp[iTmp] = '.';
       iTmp++;
+      szTmp[iTmp] = '\0';
+    } else if  (pszValue[i] == pszEscape[0]) {
+      szTmp[iTmp] = '\\';
+      iTmp++;
+      szTmp[iTmp] = '\0';
+
+    } else if (pszValue[i] == pszWild[0]) {
+      /* strcat(szBuffer, "[0-9,a-z,A-Z,\\s]*"); */
+      /* iBuffer+=17; */
+      szTmp[iTmp++] = '.';
+      szTmp[iTmp++] = '*';
+      szTmp[iTmp] = '\0';
     }
-    for (i=0; i<nLength; i++)
-    {
-        if (pszValue[i] != pszWild[0] && 
-            pszValue[i] != pszSingle[0] &&
-            pszValue[i] != pszEscape[0])
-        {
-            szTmp[iTmp] = pszValue[i];
-            iTmp++;
-            szTmp[iTmp] = '\0';
-        }
-        else if  (pszValue[i] == pszSingle[0])
-        {
-             szTmp[iTmp] = '.';
-             iTmp++;
-             szTmp[iTmp] = '\0';
-        }
-        else if  (pszValue[i] == pszEscape[0])
-        {
-            szTmp[iTmp] = '\\';
-            iTmp++;
-            szTmp[iTmp] = '\0';
+  }
+  szTmp[iTmp] = '"';
+  szTmp[++iTmp] = '\0';
 
-        }
-        else if (pszValue[i] == pszWild[0])
-        {
-            /* strcat(szBuffer, "[0-9,a-z,A-Z,\\s]*"); */
-            /* iBuffer+=17; */
-            szTmp[iTmp++] = '.';
-            szTmp[iTmp++] = '*';
-            szTmp[iTmp] = '\0';
-        }
-    }   
-    szTmp[iTmp] = '"';
-    szTmp[++iTmp] = '\0';
-    
-    strlcat(szBuffer, szTmp, bufferSize);
-    strlcat(szBuffer, ")", bufferSize);     
-    return msStrdup(szBuffer);
+  strlcat(szBuffer, szTmp, bufferSize);
+  strlcat(szBuffer, ")", bufferSize);
+  return msStrdup(szBuffer);
 }
 
 
 char *FLTGetIsBetweenComparisonCommonExpresssion(FilterEncodingNode *psFilterNode,
-                                                 layerObj *lp)
+    layerObj *lp)
 {
-    const size_t bufferSize = 1024;
-    char szBuffer[1024];
-    char **aszBounds = NULL;
-    int nBounds = 0;
-    int bString=0;
-    char *pszExpression=NULL;
-
-    if (!psFilterNode ||
-        !(strcasecmp(psFilterNode->pszValue, "PropertyIsBetween") == 0))
-      return NULL;
-
-    if (psFilterNode->psLeftNode == NULL || psFilterNode->psRightNode == NULL )
-      return NULL;
-
-/* -------------------------------------------------------------------- */
-/*      Get the bounds value which are stored like boundmin;boundmax    */
-/* -------------------------------------------------------------------- */
-    aszBounds = msStringSplit(psFilterNode->psRightNode->pszValue, ';', &nBounds);
-    if (nBounds != 2)
-    {
-        if (aszBounds)
-          msFreeCharArray(aszBounds, nBounds);
-        return NULL;
-    }
-/* -------------------------------------------------------------------- */
-/*      check if the value is a numeric value or alphanumeric. If it    */
-/*      is alphanumeric, add quotes around attribute and values.        */
-/* -------------------------------------------------------------------- */
-    bString = 0;
-    if (aszBounds[0])
-    {
-        snprintf(szBuffer,  bufferSize, "%s_type",  psFilterNode->psLeftNode->pszValue);
-        if (msOWSLookupMetadata(&(lp->metadata), "OFG", szBuffer) != NULL &&
-            (strcasecmp(msOWSLookupMetadata(&(lp->metadata), "G", szBuffer), "Character") == 0))
-          bString = 1;
-        else if (FLTIsNumeric(aszBounds[0]) == MS_FALSE)    
-          bString = 1;
-    }
-    if (!bString)
-    {
-        if (aszBounds[1])
-        {
-            if (FLTIsNumeric(aszBounds[1]) == MS_FALSE)    
-              bString = 1;  
-        }
+  const size_t bufferSize = 1024;
+  char szBuffer[1024];
+  char **aszBounds = NULL;
+  int nBounds = 0;
+  int bString=0;
+  char *pszExpression=NULL, *pszTmpEscaped;
+
+  if (!psFilterNode ||
+      !(strcasecmp(psFilterNode->pszValue, "PropertyIsBetween") == 0))
+    return NULL;
+
+  if (psFilterNode->psLeftNode == NULL || psFilterNode->psRightNode == NULL )
+    return NULL;
+
+  /* -------------------------------------------------------------------- */
+  /*      Get the bounds value which are stored like boundmin;boundmax    */
+  /* -------------------------------------------------------------------- */
+  aszBounds = msStringSplit(psFilterNode->psRightNode->pszValue, ';', &nBounds);
+  if (nBounds != 2) {
+    if (aszBounds)
+      msFreeCharArray(aszBounds, nBounds);
+    return NULL;
+  }
+  /* -------------------------------------------------------------------- */
+  /*      check if the value is a numeric value or alphanumeric. If it    */
+  /*      is alphanumeric, add quotes around attribute and values.        */
+  /* -------------------------------------------------------------------- */
+  bString = 0;
+  if (aszBounds[0]) {
+    snprintf(szBuffer,  bufferSize, "%s_type",  psFilterNode->psLeftNode->pszValue);
+    if (msOWSLookupMetadata(&(lp->metadata), "OFG", szBuffer) != NULL &&
+        (strcasecmp(msOWSLookupMetadata(&(lp->metadata), "OFG", szBuffer), "Character") == 0))
+      bString = 1;
+    else if (FLTIsNumeric(aszBounds[0]) == MS_FALSE)
+      bString = 1;
+  }
+  if (!bString) {
+    if (aszBounds[1]) {
+      if (FLTIsNumeric(aszBounds[1]) == MS_FALSE)
+        bString = 1;
     }
-        
-
-/* -------------------------------------------------------------------- */
-/*      build expresssion.                                              */
-/* -------------------------------------------------------------------- */
-    /* attribute */
-    if (bString)
-      sprintf(szBuffer, "%s", " (\"[");
-    else
-      sprintf(szBuffer, "%s", " ([");
+  }
+
+
+  /* -------------------------------------------------------------------- */
+  /*      build expresssion.                                              */
+  /* -------------------------------------------------------------------- */
+  /* attribute */
+  if (bString)
+    sprintf(szBuffer, "%s", " (\"[");
+  else
+    sprintf(szBuffer, "%s", " ([");
+  pszExpression = msStringConcatenate(pszExpression, szBuffer);
+  
+  pszExpression = msStringConcatenate(pszExpression, psFilterNode->psLeftNode->pszValue);
+
+  if (bString)
+    sprintf(szBuffer, "%s", "]\" ");
+  else
+    sprintf(szBuffer, "%s", "] ");
+  pszExpression = msStringConcatenate(pszExpression, szBuffer);
+
+  sprintf(szBuffer, "%s", " >= ");
+  pszExpression = msStringConcatenate(pszExpression, szBuffer);
+
+  if (bString) {
+    sprintf(szBuffer,"%s", "\"");
     pszExpression = msStringConcatenate(pszExpression, szBuffer);
-    pszExpression = msStringConcatenate(pszExpression, psFilterNode->psLeftNode->pszValue);
-
-    if (bString)
-      sprintf(szBuffer, "%s", "]\" ");
-    else
-      sprintf(szBuffer, "%s", "] ");
-    pszExpression = msStringConcatenate(pszExpression, szBuffer);    
-    
-    sprintf(szBuffer, "%s", " >= ");
-    pszExpression = msStringConcatenate(pszExpression, szBuffer); 
-
-    if (bString)
-    {
-        sprintf(szBuffer,"%s", "\"");
-        pszExpression = msStringConcatenate(pszExpression, szBuffer); 
-    }
-
-    snprintf(szBuffer, bufferSize, "%s", aszBounds[0]);
-    pszExpression = msStringConcatenate(pszExpression, szBuffer); 
-    if (bString)
-    {
-        sprintf(szBuffer, "%s", "\"");
-        pszExpression = msStringConcatenate(pszExpression, szBuffer); 
-    }
-
-    sprintf(szBuffer, "%s", " AND ");
-    pszExpression = msStringConcatenate(pszExpression, szBuffer); 
-
-    if (bString)
-      sprintf(szBuffer, "%s", " \"[");
-    else
-      sprintf(szBuffer, "%s", " ["); 
-    pszExpression = msStringConcatenate(pszExpression, szBuffer); 
-     
-    /* attribute */
-    pszExpression = msStringConcatenate(pszExpression, psFilterNode->psLeftNode->pszValue);
-    
-    if (bString)
-      sprintf(szBuffer, "%s", "]\" ");
-    else
-      sprintf(szBuffer, "%s", "] ");
-    pszExpression = msStringConcatenate(pszExpression, szBuffer); 
-
-    sprintf(szBuffer, "%s", " <= ");
-    pszExpression = msStringConcatenate(pszExpression, szBuffer); 
-    if (bString)
-    {
-        sprintf(szBuffer,"%s", "\"");
-        pszExpression = msStringConcatenate(pszExpression, szBuffer); 
-    }
-    snprintf(szBuffer, bufferSize, "%s", aszBounds[1]);
-    pszExpression = msStringConcatenate(pszExpression, szBuffer); 
+  }
+
+  pszTmpEscaped = msStringEscape(aszBounds[0]);
+  snprintf(szBuffer, bufferSize, "%s", pszTmpEscaped);
+  if(pszTmpEscaped != aszBounds[0] ) msFree(pszTmpEscaped);
+  pszExpression = msStringConcatenate(pszExpression, szBuffer);
+  if (bString) {
+    sprintf(szBuffer, "%s", "\"");
+    pszExpression = msStringConcatenate(pszExpression, szBuffer);
+  }
+
+  sprintf(szBuffer, "%s", " AND ");
+  pszExpression = msStringConcatenate(pszExpression, szBuffer);
+
+  if (bString)
+    sprintf(szBuffer, "%s", " \"[");
+  else
+    sprintf(szBuffer, "%s", " [");
+  pszExpression = msStringConcatenate(pszExpression, szBuffer);
+
+  /* attribute */
+  pszExpression = msStringConcatenate(pszExpression, psFilterNode->psLeftNode->pszValue);
+
+  if (bString)
+    sprintf(szBuffer, "%s", "]\" ");
+  else
+    sprintf(szBuffer, "%s", "] ");
+  pszExpression = msStringConcatenate(pszExpression, szBuffer);
+
+  sprintf(szBuffer, "%s", " <= ");
+  pszExpression = msStringConcatenate(pszExpression, szBuffer);
+  if (bString) {
+    sprintf(szBuffer,"%s", "\"");
+    pszExpression = msStringConcatenate(pszExpression, szBuffer);
+  }
+  pszTmpEscaped = msStringEscape(aszBounds[1]);
+  snprintf(szBuffer, bufferSize, "%s", pszTmpEscaped);
+  if(pszTmpEscaped != aszBounds[1] ) msFree(pszTmpEscaped);
+  pszExpression = msStringConcatenate(pszExpression, szBuffer);
+
+  if (bString) {
+    sprintf(szBuffer,"\"");
+    pszExpression = msStringConcatenate(pszExpression, szBuffer);
+  }
+  sprintf(szBuffer, "%s", ")");
+  pszExpression = msStringConcatenate(pszExpression, szBuffer);
 
-    if (bString)
-    {
-        sprintf(szBuffer,"\"");
-        pszExpression = msStringConcatenate(pszExpression, szBuffer); 
-    }
-    sprintf(szBuffer, "%s", ")");     
-    pszExpression = msStringConcatenate(pszExpression, szBuffer); 
-    
-    if (aszBounds)
-      msFreeCharArray(aszBounds, nBounds);
+  if (aszBounds)
+    msFreeCharArray(aszBounds, nBounds);
 
-    return pszExpression;
+  return pszExpression;
 }
 
 char *FLTGetBinaryComparisonCommonExpression(FilterEncodingNode *psFilterNode, layerObj *lp)
 {
-     char szTmp[1024];
-     char *pszExpression = NULL;
-     int bString;
+  char szTmp[1024];
+  char *pszExpression = NULL, *pszTmpEscaped;
+  int bString;
+
+  if (psFilterNode == NULL)
+    return NULL;
+
+  /* -------------------------------------------------------------------- */
+  /*      check if the value is a numeric value or alphanumeric. If it    */
+  /*      is alphanumeric, add quotes around attribute and values.        */
+  /* -------------------------------------------------------------------- */
+  bString = 0;
+  if (psFilterNode->psRightNode->pszValue) {
+    snprintf(szTmp, sizeof(szTmp), "%s_type",  psFilterNode->psLeftNode->pszValue);
+    if (msOWSLookupMetadata(&(lp->metadata), "OFG", szTmp) != NULL &&
+        (strcasecmp(msOWSLookupMetadata(&(lp->metadata), "OFG", szTmp), "Character") == 0))
+      bString = 1;
+    else if (FLTIsNumeric(psFilterNode->psRightNode->pszValue) == MS_FALSE)
+      bString = 1;
+  }
 
-     if (psFilterNode == NULL)
-      return NULL;
+  /* specical case to be able to have empty strings in the expression. */
+  /*propertyislike is always treated as string*/
+  if (psFilterNode->psRightNode->pszValue == NULL ||
+      strcasecmp(psFilterNode->pszValue, "PropertyIsLike") == 0)
+    bString = 1;
 
-/* -------------------------------------------------------------------- */
-/*      check if the value is a numeric value or alphanumeric. If it    */
-/*      is alphanumeric, add quotes around attribute and values.        */
-/* -------------------------------------------------------------------- */
-    bString = 0;
-    if (psFilterNode->psRightNode->pszValue)
-    {
-        snprintf(szTmp, sizeof(szTmp), "%s_type",  psFilterNode->psLeftNode->pszValue);
-        if (msOWSLookupMetadata(&(lp->metadata), "OFG", szTmp) != NULL &&
-            (strcasecmp(msOWSLookupMetadata(&(lp->metadata), "G", szTmp), "Character") == 0))
-          bString = 1;
-        else if (FLTIsNumeric(psFilterNode->psRightNode->pszValue) == MS_FALSE)    
-          bString = 1;
-    }
 
-    /* specical case to be able to have empty strings in the expression. */
-    /*propertyislike is always treated as string*/
-    if (psFilterNode->psRightNode->pszValue == NULL || 
-        strcasecmp(psFilterNode->pszValue, "PropertyIsLike") == 0)
-      bString = 1;
-    
-    
-      
-    /* attribute */
-    if (bString)
-      sprintf(szTmp, "%s", " (\"[");
-    else
-      sprintf(szTmp,  "%s"," ([");
-    pszExpression = msStringConcatenate(pszExpression, szTmp);
-    pszExpression = msStringConcatenate(pszExpression, psFilterNode->psLeftNode->pszValue);
-    if (bString)
-      sprintf(szTmp,  "%s","]\" ");
-    else
-      sprintf(szTmp,  "%s", "] "); 
-    pszExpression = msStringConcatenate(pszExpression, szTmp);
 
-    if (strcasecmp(psFilterNode->pszValue, 
-                   "PropertyIsEqualTo") == 0)
-    {
-        /*case insensitive set ? */
-        if (psFilterNode->psRightNode->pOther && 
-            (*(int *)psFilterNode->psRightNode->pOther) == 1)
-        {
-          sprintf(szTmp,  "%s", "=*"); 
-        }
-        else
-          sprintf(szTmp,  "%s", "=");
-    
-    }
-    else if (strcasecmp(psFilterNode->pszValue, 
+  /* attribute */
+  if (bString)
+    sprintf(szTmp, "%s", " (\"[");
+  else
+    sprintf(szTmp,  "%s"," ([");
+  pszExpression = msStringConcatenate(pszExpression, szTmp);
+  pszExpression = msStringConcatenate(pszExpression, psFilterNode->psLeftNode->pszValue);
+  
+  if (bString)
+    sprintf(szTmp,  "%s","]\" ");
+  else
+    sprintf(szTmp,  "%s", "] ");
+  pszExpression = msStringConcatenate(pszExpression, szTmp);
+
+  if (strcasecmp(psFilterNode->pszValue,
+                 "PropertyIsEqualTo") == 0) {
+    /*case insensitive set ? */
+    if (psFilterNode->psRightNode->pOther &&
+        (*(int *)psFilterNode->psRightNode->pOther) == 1) {
+      sprintf(szTmp,  "%s", "=*");
+    } else
+      sprintf(szTmp,  "%s", "=");
+
+  } else if (strcasecmp(psFilterNode->pszValue,
                         "PropertyIsNotEqualTo") == 0)
-      sprintf(szTmp,  "%s", " != "); 
-    else if (strcasecmp(psFilterNode->pszValue, 
-                        "PropertyIsLessThan") == 0)
-      sprintf(szTmp,  "%s", " < ");
-    else if (strcasecmp(psFilterNode->pszValue, 
-                        "PropertyIsGreaterThan") == 0)
-      sprintf(szTmp,  "%s", " > ");
-    else if (strcasecmp(psFilterNode->pszValue, 
-                        "PropertyIsLessThanOrEqualTo") == 0)
-      sprintf(szTmp,  "%s", " <= ");
-    else if (strcasecmp(psFilterNode->pszValue, 
-                        "PropertyIsGreaterThanOrEqualTo") == 0)
-      sprintf(szTmp,  "%s", " >= ");
-    else if (strcasecmp(psFilterNode->pszValue, 
-                        "PropertyIsLike") == 0)
-      sprintf(szTmp,  "%s", " ~ ");
-    
+    sprintf(szTmp,  "%s", " != ");
+  else if (strcasecmp(psFilterNode->pszValue,
+                      "PropertyIsLessThan") == 0)
+    sprintf(szTmp,  "%s", " < ");
+  else if (strcasecmp(psFilterNode->pszValue,
+                      "PropertyIsGreaterThan") == 0)
+    sprintf(szTmp,  "%s", " > ");
+  else if (strcasecmp(psFilterNode->pszValue,
+                      "PropertyIsLessThanOrEqualTo") == 0)
+    sprintf(szTmp,  "%s", " <= ");
+  else if (strcasecmp(psFilterNode->pszValue,
+                      "PropertyIsGreaterThanOrEqualTo") == 0)
+    sprintf(szTmp,  "%s", " >= ");
+  else if (strcasecmp(psFilterNode->pszValue,
+                      "PropertyIsLike") == 0)
+    sprintf(szTmp,  "%s", " ~ ");
+
+  pszExpression = msStringConcatenate(pszExpression, szTmp);
+
+  /* value */
+  if (bString) {
+    sprintf(szTmp,  "%s", "\"");
     pszExpression = msStringConcatenate(pszExpression, szTmp);
+  }
 
-    /* value */
-    if (bString)
-    {
-        sprintf(szTmp,  "%s", "\"");
-        pszExpression = msStringConcatenate(pszExpression, szTmp);
-    }
-
-    if (psFilterNode->psRightNode->pszValue)
-      pszExpression = msStringConcatenate(pszExpression, psFilterNode->psRightNode->pszValue);
+  if (psFilterNode->psRightNode->pszValue) {
+    pszTmpEscaped = msStringEscape(psFilterNode->psRightNode->pszValue);
+    pszExpression = msStringConcatenate(pszExpression, pszTmpEscaped);
+    if(pszTmpEscaped != psFilterNode->psRightNode->pszValue ) msFree(pszTmpEscaped);
+  }
 
-    if (bString)
-    {
-        sprintf(szTmp,  "%s", "\"");
-        pszExpression = msStringConcatenate(pszExpression, szTmp);
-    }
+  if (bString) {
+    sprintf(szTmp,  "%s", "\"");
+    pszExpression = msStringConcatenate(pszExpression, szTmp);
+  }
 
-     sprintf(szTmp,  "%s", ")");
-     pszExpression = msStringConcatenate(pszExpression, szTmp);
+  sprintf(szTmp,  "%s", ")");
+  pszExpression = msStringConcatenate(pszExpression, szTmp);
 
-    return pszExpression;
+  return pszExpression;
 }
 
 
 
 char *FLTGetLogicalComparisonCommonExpression(FilterEncodingNode *psFilterNode, layerObj *lp)
 {
-    char *pszExpression = NULL;
-    char *pszTmp = NULL;
-    char szBuffer[256];
+  char *pszExpression = NULL;
+  char *pszTmp = NULL;
+  char szBuffer[256];
+
+  if (!psFilterNode || !FLTIsLogicalFilterType(psFilterNode->pszValue))
+    return NULL;
+
+  /* -------------------------------------------------------------------- */
+  /*      OR and AND                                                      */
+  /* -------------------------------------------------------------------- */
+  if (psFilterNode->psLeftNode && psFilterNode->psRightNode) {
+    pszTmp = FLTGetCommonExpression(psFilterNode->psLeftNode, lp);
+    if (!pszTmp)
+      return NULL;
+
+    sprintf(szBuffer, "%s", " (");
+    pszExpression = msStringConcatenate(pszExpression, szBuffer);
 
-    if (!psFilterNode || !FLTIsLogicalFilterType(psFilterNode->pszValue))
+    pszExpression = msStringConcatenate(pszExpression, pszTmp);
+    msFree(pszTmp);
+
+    sprintf(szBuffer, "%s", " ");
+    pszExpression = msStringConcatenate(pszExpression, szBuffer);
+
+    pszExpression = msStringConcatenate(pszExpression, psFilterNode->pszValue);
+    sprintf(szBuffer, "%s", " ");
+
+
+    pszTmp = FLTGetCommonExpression(psFilterNode->psRightNode, lp);
+    if (!pszTmp)
       return NULL;
 
-/* -------------------------------------------------------------------- */
-/*      OR and AND                                                      */
-/* -------------------------------------------------------------------- */
-    if (psFilterNode->psLeftNode && psFilterNode->psRightNode)
-    {
-        pszTmp = FLTGetCommonExpression(psFilterNode->psLeftNode, lp);
-        if (!pszTmp)
-          return NULL;
-
-        sprintf(szBuffer, "%s", " (");
-        pszExpression = msStringConcatenate(pszExpression, szBuffer);
-        
-        pszExpression = msStringConcatenate(pszExpression, pszTmp);
-        msFree(pszTmp);
-        
-        sprintf(szBuffer, "%s", " ");
-        pszExpression = msStringConcatenate(pszExpression, szBuffer);
+    pszExpression = msStringConcatenate(pszExpression, pszTmp);
+    msFree(pszTmp);
 
-        pszExpression = msStringConcatenate(pszExpression, psFilterNode->pszValue);
-        sprintf(szBuffer, "%s", " ");
+    sprintf(szBuffer, "%s", ") ");
+    pszExpression = msStringConcatenate(pszExpression, szBuffer);
+  }
+  /* -------------------------------------------------------------------- */
+  /*      NOT                                                             */
+  /* -------------------------------------------------------------------- */
+  else if (psFilterNode->psLeftNode &&
+           strcasecmp(psFilterNode->pszValue, "NOT") == 0) {
+    pszTmp = FLTGetCommonExpression(psFilterNode->psLeftNode, lp);
+    if (!pszTmp)
+      return NULL;
 
+    sprintf(szBuffer, "%s", " (NOT ");
+    pszExpression = msStringConcatenate(pszExpression, szBuffer);
 
-        pszTmp = FLTGetCommonExpression(psFilterNode->psRightNode, lp);
-        if (!pszTmp)
-          return NULL;
+    pszExpression = msStringConcatenate(pszExpression, pszTmp);
+    msFree(pszTmp);
 
-        pszExpression = msStringConcatenate(pszExpression, pszTmp);
-        msFree(pszTmp);
+    sprintf(szBuffer, "%s", ") ");
+    pszExpression = msStringConcatenate(pszExpression, szBuffer);
 
-        sprintf(szBuffer, "%s", ") ");
-        pszExpression = msStringConcatenate(pszExpression, szBuffer);
-    }
-/* -------------------------------------------------------------------- */
-/*      NOT                                                             */
-/* -------------------------------------------------------------------- */
-    else if (psFilterNode->psLeftNode && 
-             strcasecmp(psFilterNode->pszValue, "NOT") == 0)
-    {
-        pszTmp = FLTGetCommonExpression(psFilterNode->psLeftNode, lp);
-        if (!pszTmp)
-          return NULL;
-
-        sprintf(szBuffer, "%s", " (NOT ");
-        pszExpression = msStringConcatenate(pszExpression, szBuffer);
-
-        pszExpression = msStringConcatenate(pszExpression, pszTmp);
-        msFree(pszTmp);
+  }
 
-        sprintf(szBuffer, "%s", ") ");
-        pszExpression = msStringConcatenate(pszExpression, szBuffer);
-        
-    }
 
-    
-    return pszExpression;
+  return pszExpression;
 }
 
 
 char *FLTGetSpatialComparisonCommonExpression(FilterEncodingNode *psNode, layerObj *lp)
 {
-    char *pszExpression = NULL;
-    shapeObj *psQueryShape = NULL;
-    double dfDistance = -1;
-    int nUnit = -1;
-    char *pszWktText = NULL;
-    char szBuffer[256];
-    char *pszTmp=NULL;
-    projectionObj sProjTmp;
-    char *pszEPSG= NULL;
-    rectObj sQueryRect;
-    shapeObj *psTmpShape=NULL, *psBufferShape=NULL;
-    int bBBoxQuery = 0;
-    
-    if (psNode == NULL || lp == NULL)
-      return NULL;
-
-    if (psNode->eType != FILTER_NODE_TYPE_SPATIAL)
-      return NULL;
-
-    /* get the shape*/
-    /*BBOX case: replace it with NOT DISJOINT.*/
-    if(FLTIsBBoxFilter(psNode))
-    {
-        pszEPSG = FLTGetBBOX(psNode, &sQueryRect);
-        /*this should be removed and bbox should parse and strore the srs properly, 
-          using now legacy code*/
-        if (pszEPSG)
-          psNode->pszSRS = msStrdup(pszEPSG);
-        
-        psTmpShape = (shapeObj *)msSmallMalloc(sizeof(shapeObj));
-        msInitShape(psTmpShape);
-        msRectToPolygon(sQueryRect, psTmpShape);
-        bBBoxQuery = 1;
-
+  char *pszExpression = NULL;
+  shapeObj *psQueryShape = NULL;
+  double dfDistance = -1;
+  int nUnit = -1;
+  char *pszWktText = NULL;
+  char szBuffer[256];
+  char *pszTmp=NULL;
+  projectionObj sProjTmp;
+  char *pszEPSG= NULL;
+  rectObj sQueryRect;
+  shapeObj *psTmpShape=NULL, *psBufferShape=NULL;
+  int bBBoxQuery = 0;
+
+  if (psNode == NULL || lp == NULL)
+    return NULL;
+
+  if (psNode->eType != FILTER_NODE_TYPE_SPATIAL)
+    return NULL;
+
+  /* get the shape*/
+  /*BBOX case: replace it with NOT DISJOINT.*/
+  if(FLTIsBBoxFilter(psNode)) {
+    pszEPSG = FLTGetBBOX(psNode, &sQueryRect);
+    /*this should be removed and bbox should parse and strore the srs properly,
+      using now legacy code*/
+    if (pszEPSG)
+      psNode->pszSRS = msStrdup(pszEPSG);
+
+    psTmpShape = (shapeObj *)msSmallMalloc(sizeof(shapeObj));
+    msInitShape(psTmpShape);
+    msRectToPolygon(sQueryRect, psTmpShape);
+    bBBoxQuery = 1;
+
+  } else {
+    /*other geos type operations*/
+
+    /*project shape to layer projection. If the proj is not part of the filter query,
+      assume that the cooredinates are in the map projection*/
+
+    psQueryShape = FLTGetShape(psNode, &dfDistance, &nUnit);
+
+    if ((strcasecmp(psNode->pszValue, "DWithin") == 0 ||
+         strcasecmp(psNode->pszValue, "Beyond") == 0 ) &&
+        dfDistance > 0) {
+      if (nUnit >=0 && nUnit != lp->map->units)
+        dfDistance *= msInchesPerUnit(nUnit,0)/msInchesPerUnit(lp->map->units,0);
+
+      psBufferShape = msGEOSBuffer(psQueryShape, dfDistance);
     }
+    if (psBufferShape)
+      psTmpShape = psBufferShape;
     else
-    {
-        /*other geos type operations*/
-
-        /*project shape to layer projection. If the proj is not part of the filter query,
-          assume that the cooredinates are in the map projection*/
-      
-        psQueryShape = FLTGetShape(psNode, &dfDistance, &nUnit);
-    
-        if ((strcasecmp(psNode->pszValue, "DWithin") == 0 ||
-             strcasecmp(psNode->pszValue, "Beyond") == 0 ) &&
-            dfDistance > 0)
-        {
-            if (nUnit >=0 && nUnit != lp->map->units)
-              dfDistance *= msInchesPerUnit(nUnit,0)/msInchesPerUnit(lp->map->units,0);
-
-            psBufferShape = msGEOSBuffer(psQueryShape, dfDistance);
-        }
-        if (psBufferShape)
-          psTmpShape = psBufferShape;
-        else
-          psTmpShape = psQueryShape;
+      psTmpShape = psQueryShape;
+  }
+
+  if (psTmpShape) {
+    if( lp->projection.numargs > 0) {
+      if (psNode->pszSRS && FTLParseEpsgString(psNode->pszSRS, &sProjTmp)) {
+        msProjectShape(&sProjTmp, &lp->projection, psTmpShape);
+        msFreeProjection(&sProjTmp);
+      } else if (lp->map->projection.numargs > 0)
+        msProjectShape(&lp->map->projection, &lp->projection, psTmpShape);
     }
+    /* ==================================================================== */
+    /*      use within for bbox. Not Disjoint does not work.                */
+    /* ==================================================================== */
+    if (bBBoxQuery)
+      sprintf(szBuffer, "%s", " ([shape] ");
+    /* sprintf(szBuffer, "%s", " (NOT ([shape] "); */
+    else
+      sprintf(szBuffer, "%s", " ([shape] ");
 
-    if (psTmpShape)
-    {
-        if( lp->projection.numargs > 0)
-        {
-            if (psNode->pszSRS && FTLParseEpsgString(psNode->pszSRS, &sProjTmp))
-            {
-              msProjectShape(&sProjTmp, &lp->projection, psTmpShape);
-              msFreeProjection(&sProjTmp);
-            }
-            else if (lp->map->projection.numargs > 0)
-              msProjectShape(&lp->map->projection, &lp->projection, psTmpShape);
-        }
-        if (bBBoxQuery)
-          sprintf(szBuffer, "%s", " (NOT ([shape] ");
-        else
-          sprintf(szBuffer, "%s", " ([shape] ");
-
-        pszExpression = msStringConcatenate(pszExpression, szBuffer);
+    pszExpression = msStringConcatenate(pszExpression, szBuffer);
 
 
-        if (strcasecmp(psNode->pszValue, "intersect") == 0)
-          pszTmp = msStrdup(psNode->pszValue);
-        else
-          pszTmp = msStrdup(psNode->pszValue);
+    if (bBBoxQuery) {
+      sprintf(szBuffer, " %s ", "intersects");
+    } else {
+      if (strncasecmp(psNode->pszValue, "intersect", 9) == 0)
+        sprintf(szBuffer, " %s ", "intersects");
+      else if (strncasecmp(psNode->pszValue, "equals", 6) == 0)
+        sprintf(szBuffer, " %s ", "eq");
+      else {
+        pszTmp = msStrdup(psNode->pszValue);
         msStringToLower(pszTmp);
-        if (bBBoxQuery)
-          sprintf(szBuffer, " %s ", "disjoint");
-        else
-           sprintf(szBuffer, " %s ", pszTmp);
-
-        pszExpression = msStringConcatenate(pszExpression, szBuffer);
+        sprintf(szBuffer, " %s ", pszTmp);
         msFree(pszTmp);
-
-        pszWktText = msGEOSShapeToWKT(psTmpShape);
-        sprintf(szBuffer, "%s", " fromText('");
-        pszExpression = msStringConcatenate(pszExpression, szBuffer);
-        pszExpression = msStringConcatenate(pszExpression, pszWktText);
-        sprintf(szBuffer, "%s", "')");
-        pszExpression = msStringConcatenate(pszExpression, szBuffer);
-        msGEOSFreeWKT(pszWktText);
+      }
     }
-    if (psBufferShape)
-      msFreeShape(psBufferShape);
 
-    
-    sprintf(szBuffer, "%s", ")");
     pszExpression = msStringConcatenate(pszExpression, szBuffer);
 
-     if (bBBoxQuery)
-     {
-          sprintf(szBuffer, "%s", ")");
-          pszExpression = msStringConcatenate(pszExpression, szBuffer);
-     }
-    return pszExpression;
+    pszWktText = msGEOSShapeToWKT(psTmpShape);
+    sprintf(szBuffer, "%s", " fromText('");
+    pszExpression = msStringConcatenate(pszExpression, szBuffer);
+    pszExpression = msStringConcatenate(pszExpression, pszWktText);
+    sprintf(szBuffer, "%s", "')");
+    pszExpression = msStringConcatenate(pszExpression, szBuffer);
+    msGEOSFreeWKT(pszWktText);
+  }
+  if (psBufferShape) {
+    msFreeShape(psBufferShape);
+    msFree(psBufferShape);
+  }
+  if(bBBoxQuery) {
+     msFreeShape(psTmpShape);
+     msFree(psTmpShape);
+  }
+
+
+  sprintf(szBuffer, "%s", ")");
+  pszExpression = msStringConcatenate(pszExpression, szBuffer);
+
+  if (0) { /* bBBoxQuery */
+    sprintf(szBuffer, "%s", ")");
+    pszExpression = msStringConcatenate(pszExpression, szBuffer);
+  }
+  return pszExpression;
 }
 
 char *FLTGetFeatureIdCommonExpression(FilterEncodingNode *psFilterNode, layerObj *lp)
 {
-    
-    char *pszExpression = NULL;
-    int nTokens = 0, i=0, bString=0;
-    char **tokens = NULL;
-    const char *pszAttribute=NULL;
+
+  char *pszExpression = NULL;
+  int nTokens = 0, i=0, bString=0;
+  char **tokens = NULL;
+  const char *pszAttribute=NULL;
 
 #if defined(USE_WMS_SVR) || defined (USE_WFS_SVR) || defined (USE_WCS_SVR) || defined(USE_SOS_SVR)
-    if (psFilterNode->pszValue)
-    {
-        pszAttribute = msOWSLookupMetadata(&(lp->metadata), "OFG", "featureid");
-        if (pszAttribute)
-        {
-            tokens = msStringSplit(psFilterNode->pszValue,',', &nTokens);
-            if (tokens && nTokens > 0)
-            {
-                for (i=0; i<nTokens; i++)
-                {   
-                    char *pszTmp = NULL;
-                    int bufferSize = 0;	
-
-                    if (i == 0)
-                    {
-                        if(FLTIsNumeric(tokens[0]) == MS_FALSE) 
-                          bString = 1;
-                    }
-                    
-                   
-                    if (bString)
-                    {   
-                        bufferSize = 11+strlen(tokens[i])+strlen(pszAttribute)+1;
-                        pszTmp = (char *)msSmallMalloc(bufferSize);
-                        snprintf(pszTmp, bufferSize, "(\"[%s]\" ==\"%s\")" , pszAttribute, tokens[i]);
-                    }
-                    else
-                    {   
-                        bufferSize = 8+strlen(tokens[i])+strlen(pszAttribute)+1;
-                        pszTmp = (char *)msSmallMalloc(bufferSize);
-                        snprintf(pszTmp, bufferSize, "([%s] == %s)" , pszAttribute, tokens[i]);
-                    }
-
-                    if (pszExpression != NULL)
-                      pszExpression = msStringConcatenate(pszExpression, " OR ");
-                    else
-                      pszExpression = msStringConcatenate(pszExpression, "(");
-                    pszExpression = msStringConcatenate(pszExpression, pszTmp);
-                    msFree(pszTmp);
-                }
-
-                msFreeCharArray(tokens, nTokens);
-            }
-        }   
-        /*opening and closing brackets are needed for mapserver expressions*/
-        if (pszExpression)
-          pszExpression = msStringConcatenate(pszExpression, ")");
+  if (psFilterNode->pszValue) {
+    pszAttribute = msOWSLookupMetadata(&(lp->metadata), "OFG", "featureid");
+    if (pszAttribute) {
+      tokens = msStringSplit(psFilterNode->pszValue,',', &nTokens);
+      if (tokens && nTokens > 0) {
+        for (i=0; i<nTokens; i++) {
+          char *pszTmp = NULL;
+          int bufferSize = 0;
+
+          if (i == 0) {
+            if(FLTIsNumeric(tokens[0]) == MS_FALSE)
+              bString = 1;
+          }
+
+
+          if (bString) {
+            bufferSize = 11+strlen(tokens[i])+strlen(pszAttribute)+1;
+            pszTmp = (char *)msSmallMalloc(bufferSize);
+            snprintf(pszTmp, bufferSize, "(\"[%s]\" ==\"%s\")" , pszAttribute, tokens[i]);
+          } else {
+            bufferSize = 8+strlen(tokens[i])+strlen(pszAttribute)+1;
+            pszTmp = (char *)msSmallMalloc(bufferSize);
+            snprintf(pszTmp, bufferSize, "([%s] == %s)" , pszAttribute, tokens[i]);
+          }
+
+          if (pszExpression != NULL)
+            pszExpression = msStringConcatenate(pszExpression, " OR ");
+          else
+            pszExpression = msStringConcatenate(pszExpression, "(");
+          pszExpression = msStringConcatenate(pszExpression, pszTmp);
+          msFree(pszTmp);
+        }
+
+        msFreeCharArray(tokens, nTokens);
+      }
     }
+    /*opening and closing brackets are needed for mapserver expressions*/
+    if (pszExpression)
+      pszExpression = msStringConcatenate(pszExpression, ")");
+  }
 #endif
 
-    return pszExpression;
+  return pszExpression;
 }
 
 char *FLTGetCommonExpression(FilterEncodingNode *psFilterNode, layerObj *lp)
 {
-    char *pszExpression = NULL;
+  char *pszExpression = NULL;
 
-    if (!psFilterNode)
-      return NULL;
+  if (!psFilterNode)
+    return NULL;
 
-    if (psFilterNode->eType == FILTER_NODE_TYPE_COMPARISON)
-    {
-        if ( psFilterNode->psLeftNode && psFilterNode->psRightNode)
-        {
-            if (FLTIsBinaryComparisonFilterType(psFilterNode->pszValue))               
-              pszExpression = FLTGetBinaryComparisonCommonExpression(psFilterNode, lp);
-            
-            else if (strcasecmp(psFilterNode->pszValue, "PropertyIsLike") == 0)
-              pszExpression = FLTGetIsLikeComparisonCommonExpression(psFilterNode);
-
-            else if (strcasecmp(psFilterNode->pszValue, "PropertyIsBetween") == 0)
-              pszExpression = FLTGetIsBetweenComparisonCommonExpresssion(psFilterNode, lp);
-        }
+  if (psFilterNode->eType == FILTER_NODE_TYPE_COMPARISON) {
+    if ( psFilterNode->psLeftNode && psFilterNode->psRightNode) {
+      if (FLTIsBinaryComparisonFilterType(psFilterNode->pszValue))
+        pszExpression = FLTGetBinaryComparisonCommonExpression(psFilterNode, lp);
+
+      else if (strcasecmp(psFilterNode->pszValue, "PropertyIsLike") == 0)
+        pszExpression = FLTGetIsLikeComparisonCommonExpression(psFilterNode);
+
+      else if (strcasecmp(psFilterNode->pszValue, "PropertyIsBetween") == 0)
+        pszExpression = FLTGetIsBetweenComparisonCommonExpresssion(psFilterNode, lp);
     }
-    else if (psFilterNode->eType == FILTER_NODE_TYPE_LOGICAL)
-      pszExpression = FLTGetLogicalComparisonCommonExpression(psFilterNode, lp);
+  } else if (psFilterNode->eType == FILTER_NODE_TYPE_LOGICAL)
+    pszExpression = FLTGetLogicalComparisonCommonExpression(psFilterNode, lp);
 
-    else if (psFilterNode->eType == FILTER_NODE_TYPE_SPATIAL)
-      pszExpression = FLTGetSpatialComparisonCommonExpression(psFilterNode, lp);
+  else if (psFilterNode->eType == FILTER_NODE_TYPE_SPATIAL)
+    pszExpression = FLTGetSpatialComparisonCommonExpression(psFilterNode, lp);
 
-    else if (psFilterNode->eType ==  FILTER_NODE_TYPE_FEATUREID)
-      pszExpression = FLTGetFeatureIdCommonExpression(psFilterNode, lp);
+  else if (psFilterNode->eType ==  FILTER_NODE_TYPE_FEATUREID)
+    pszExpression = FLTGetFeatureIdCommonExpression(psFilterNode, lp);
 
-    return pszExpression;
+  return pszExpression;
 }
 
 
 int FLTApplyFilterToLayerCommonExpression(mapObj *map, int iLayerIndex, char *pszExpression)
 {
-    int retval;
+  int retval;
+
+  msInitQuery(&(map->query));
+
+  map->query.type = MS_QUERY_BY_FILTER;
 
-    msFreeQuery(&(map->query));
-    msInitQuery(&(map->query));
-    
-    map->query.type = MS_QUERY_BY_FILTER;
+  map->query.filter = (expressionObj *) msSmallMalloc(sizeof(expressionObj));
+  initExpression( map->query.filter);
+  map->query.filter->string = msStrdup(pszExpression);
+  map->query.filter->type = 2000;
+  map->query.layer = iLayerIndex;
 
-    map->query.filter = (expressionObj *) msSmallMalloc(sizeof(expressionObj));
-    initExpression( map->query.filter);
-    map->query.filter->string = msStrdup(pszExpression);
-    map->query.filter->type = 2000;
-    map->query.layer = iLayerIndex;
+  /*TODO: if there is a bbox in the node, get it and set the map extent*/
+  map->query.rect = map->extent;
 
-    /*TODO: if there is a bbox in the node, get it and set the map extent*/
-    map->query.rect = map->extent;
+  retval = msQueryByFilter(map);
 
-    retval = msQueryByFilter(map);
-    
-    return retval;
+  return retval;
 }
 
 #endif
diff --git a/mapogcsld.c b/mapogcsld.c
index 5c41398..654175c 100644
--- a/mapogcsld.c
+++ b/mapogcsld.c
@@ -14,16 +14,16 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
+ *
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  ****************************************************************************/
 
 #include "mapogcsld.h"
@@ -34,7 +34,7 @@
 #include "cpl_string.h"
 #endif
 
-MS_CVSID("$Id$")
+
 
 #define SLD_LINE_SYMBOL_NAME "sld_line_symbol"
 #define SLD_LINE_SYMBOL_DASH_NAME "sld_line_symbol_dash"
@@ -59,63 +59,57 @@ MS_CVSID("$Id$")
 /*      used to do the match.                                           */
 /************************************************************************/
 int msSLDApplySLDURL(mapObj *map, char *szURL, int iLayer,
-                     char *pszStyleLayerName)
+                     char *pszStyleLayerName,  char **ppszLayerNames)
 {
 #ifdef USE_OGR
 
-/* needed for libcurl function msHTTPGetFile in maphttp.c */
+  /* needed for libcurl function msHTTPGetFile in maphttp.c */
 #if defined(USE_CURL)
 
-    char *pszSLDTmpFile = NULL;
-    int status = 0;
-    char *pszSLDbuf=NULL;
-    FILE *fp = NULL;               
-    int nStatus = MS_FAILURE;
-    
-    if (map && szURL)
-    {
-        pszSLDTmpFile = msTmpFile(map, map->mappath, NULL, "sld.xml");
-        if (pszSLDTmpFile == NULL)
-        {
-            pszSLDTmpFile = msTmpFile(map, NULL, NULL, "sld.xml" );
-        }
-        if (msHTTPGetFile(szURL, pszSLDTmpFile, &status,-1, 0, 0) ==  MS_SUCCESS)
-        {
-            if ((fp = fopen(pszSLDTmpFile, "rb")) != NULL)
-            {
-                int   nBufsize=0;
-                fseek(fp, 0, SEEK_END);
-                nBufsize = ftell(fp);
-                rewind(fp);
-                pszSLDbuf = (char*)malloc((nBufsize+1)*sizeof(char));
-                fread(pszSLDbuf, 1, nBufsize, fp);
-                fclose(fp);
-                pszSLDbuf[nBufsize] = '\0';
-                unlink(pszSLDTmpFile);
-            }
-        }
-        else
-        {
-            msSetError(MS_WMSERR, "Could not open SLD %s and save it in temporary file %s. Please make sure that the sld url is valid and that the temporary path is set. The temporary path can be defined for example by setting TMPPATH in the map file. Please check the MapServer documentation on temporary path settings.", "msSLDApplySLDURL", szURL, pszSLDTmpFile);
-        }
-        if (pszSLDbuf)
-          nStatus = msSLDApplySLD(map, pszSLDbuf, iLayer, pszStyleLayerName);
+  char *pszSLDTmpFile = NULL;
+  int status = 0;
+  char *pszSLDbuf=NULL;
+  FILE *fp = NULL;
+  int nStatus = MS_FAILURE;
+
+  if (map && szURL) {
+    pszSLDTmpFile = msTmpFile(map, map->mappath, NULL, "sld.xml");
+    if (pszSLDTmpFile == NULL) {
+      pszSLDTmpFile = msTmpFile(map, NULL, NULL, "sld.xml" );
+    }
+    if (msHTTPGetFile(szURL, pszSLDTmpFile, &status,-1, 0, 0) ==  MS_SUCCESS) {
+      if ((fp = fopen(pszSLDTmpFile, "rb")) != NULL) {
+        int   nBufsize=0;
+        fseek(fp, 0, SEEK_END);
+        nBufsize = ftell(fp);
+        rewind(fp);
+        pszSLDbuf = (char*)malloc((nBufsize+1)*sizeof(char));
+        fread(pszSLDbuf, 1, nBufsize, fp);
+        fclose(fp);
+        pszSLDbuf[nBufsize] = '\0';
+        unlink(pszSLDTmpFile);
+      }
+    } else {
+      msSetError(MS_WMSERR, "Could not open SLD %s and save it in temporary file %s. Please make sure that the sld url is valid and that the temporary path is set. The temporary path can be defined for example by setting TMPPATH in the map file. Please check the MapServer documentation on temporary path settings.", "msSLDApplySLDURL", szURL, pszSLDTmpFile);
     }
+    if (pszSLDbuf)
+      nStatus = msSLDApplySLD(map, pszSLDbuf, iLayer, pszStyleLayerName, ppszLayerNames);
+  }
 
-    return nStatus;
+  return nStatus;
 
 #else
-    msSetError(MS_MISCERR, "WMS/WFS client support is not enabled .", "msSLDApplySLDURL()");
-    return(MS_FAILURE);
+  msSetError(MS_MISCERR, "WMS/WFS client support is not enabled .", "msSLDApplySLDURL()");
+  return(MS_FAILURE);
 #endif
 
 #else
-/* ------------------------------------------------------------------
- * OGR Support not included...
- * ------------------------------------------------------------------ */
+  /* ------------------------------------------------------------------
+   * OGR Support not included...
+   * ------------------------------------------------------------------ */
 
-    msSetError(MS_MISCERR, "OGR support is not available.", "msSLDApplySLDURL()");
-    return(MS_FAILURE);
+  msSetError(MS_MISCERR, "OGR support is not available.", "msSLDApplySLDURL()");
+  return(MS_FAILURE);
 
 #endif /* USE_OGR */
 
@@ -130,370 +124,383 @@ int msSLDApplySLDURL(mapObj *map, char *szURL, int iLayer,
 /*      the SLD layers onto the map layers.                             */
 /************************************************************************/
 int msSLDApplySLD(mapObj *map, char *psSLDXML, int iLayer,
-                  char *pszStyleLayerName)
+                  char *pszStyleLayerName, char **ppszLayerNames)
 {
 #if defined(USE_WMS_SVR) || defined (USE_WFS_SVR) || defined (USE_WCS_SVR) || defined(USE_SOS_SVR)
 
 #ifdef USE_OGR
 
-    int nLayers = 0;
-    layerObj *pasLayers = NULL;
-    int i, j, k, z, iClass;
-    int bUseSpecificLayer = 0;
-    int bSuccess =0;
-    const char *pszTmp = NULL;
-    int bFreeTemplate = 0;
-    int nLayerStatus = 0;
-    int nStatus = MS_SUCCESS;
-    /*const char *pszSLDNotSupported = NULL;*/
-    char *tmpfilename = NULL;
-    const char *pszFullName = NULL; 
-    char szTmp[512]; 
-    char *pszTmp1=NULL;
-    char *pszTmp2 = NULL; 
-    char *pszBuffer = NULL;
-    layerObj *lp = NULL;
-    char *pszSqlExpression=NULL;
-    FilterEncodingNode *psExpressionNode =NULL;
-    int bFailedExpression=0;
- 
-    pasLayers = msSLDParseSLD(map, psSLDXML, &nLayers);
-
-    if (pasLayers && nLayers > 0)
-    {
-        for (i=0; i<map->numlayers; i++)
-        {
-            if (iLayer >=0 && iLayer< map->numlayers)
-            {
-                i = iLayer;
-                bUseSpecificLayer = 1;
-            }
-
-            /* compare layer name to wms_name as well */
-            pszTmp = msOWSLookupMetadata(&(GET_LAYER(map, i)->metadata), "MO", "name");
-
-            for (j=0; j<nLayers; j++)
-            {
-                    
-/* -------------------------------------------------------------------- */
-/*      copy :  - class                                                 */
-/*              - layer's labelitem                                     */
-/* -------------------------------------------------------------------- */
-                if ((pasLayers[j].name && pszStyleLayerName == NULL && 
-                     ((strcasecmp(GET_LAYER(map, i)->name, pasLayers[j].name) == 0 ||
-                      (pszTmp && strcasecmp(pszTmp, pasLayers[j].name) == 0))||
-                     (GET_LAYER(map, i)->group && 
-                       strcasecmp(GET_LAYER(map, i)->group, pasLayers[j].name) == 0))) ||
-                    (bUseSpecificLayer && pszStyleLayerName && pasLayers[j].name &&
-                     strcasecmp(pasLayers[j].name, pszStyleLayerName) == 0))
-                {
-                    bSuccess =1;
+  int nLayers = 0;
+  layerObj *pasLayers = NULL;
+  int i, j, k, z, iClass;
+  int bUseSpecificLayer = 0;
+  const char *pszTmp = NULL;
+  int bFreeTemplate = 0;
+  int nLayerStatus = 0;
+  int nStatus = MS_SUCCESS;
+  /*const char *pszSLDNotSupported = NULL;*/
+  char *tmpfilename = NULL;
+  const char *pszFullName = NULL;
+  char szTmp[512];
+  char *pszTmp1=NULL;
+  char *pszTmp2 = NULL;
+  char *pszBuffer = NULL;
+  layerObj *lp = NULL;
+  char *pszSqlExpression=NULL;
+  FilterEncodingNode *psExpressionNode =NULL;
+  int bFailedExpression=0;
+
+  pasLayers = msSLDParseSLD(map, psSLDXML, &nLayers);
+  /* -------------------------------------------------------------------- */
+  /*      If the same layer is given more that once, we need to           */
+  /*      duplicate it.                                                   */
+  /* -------------------------------------------------------------------- */
+  if (pasLayers && nLayers>0) {
+    int l,m;
+    for (m=0; m<nLayers; m++) {
+      layerObj *psTmpLayer=NULL;
+      int nIndex;
+      char tmpId[128];
+      for (l=0; l<nLayers; l++) {
+        if(pasLayers[m].name == NULL || pasLayers[l].name == NULL)
+          continue;
+
+        nIndex = msGetLayerIndex(map, pasLayers[m].name);
+
+        if (m !=l && strcasecmp(pasLayers[m].name, pasLayers[l].name)== 0 &&
+            nIndex != -1) {
+          psTmpLayer = (layerObj *) malloc(sizeof(layerObj));
+          initLayer(psTmpLayer, map);
+          msCopyLayer(psTmpLayer, GET_LAYER(map,nIndex));
+          /* open the source layer */
+          if ( !psTmpLayer->vtable)
+            msInitializeVirtualTable(psTmpLayer);
+
+          /*make the name unique*/
+          snprintf(tmpId, sizeof(tmpId), "%lx_%x_%d",(long)time(NULL),(int)getpid(),
+                   map->numlayers);
+          if (psTmpLayer->name)
+            msFree(psTmpLayer->name);
+          psTmpLayer->name = strdup(tmpId);
+          msFree(pasLayers[l].name);
+          pasLayers[l].name = strdup(tmpId);
+          msInsertLayer(map, psTmpLayer, -1);
+          MS_REFCNT_DECR(psTmpLayer);
+        }
+      }
+    }
+  }
+
+  if (pasLayers && nLayers > 0) {
+    for (i=0; i<map->numlayers; i++) {
+      if (iLayer >=0 && iLayer< map->numlayers) {
+        i = iLayer;
+        bUseSpecificLayer = 1;
+      }
+
+      /* compare layer name to wms_name as well */
+      pszTmp = msOWSLookupMetadata(&(GET_LAYER(map, i)->metadata), "MO", "name");
+
+      for (j=0; j<nLayers; j++) {
+        /* -------------------------------------------------------------------- */
+        /*      copy :  - class                                                 */
+        /*              - layer's labelitem                                     */
+        /* -------------------------------------------------------------------- */
+        if ((pasLayers[j].name && pszStyleLayerName == NULL &&
+             ((strcasecmp(GET_LAYER(map, i)->name, pasLayers[j].name) == 0 ||
+               (pszTmp && strcasecmp(pszTmp, pasLayers[j].name) == 0))||
+              (GET_LAYER(map, i)->group &&
+               strcasecmp(GET_LAYER(map, i)->group, pasLayers[j].name) == 0))) ||
+            (bUseSpecificLayer && pszStyleLayerName && pasLayers[j].name &&
+             strcasecmp(pasLayers[j].name, pszStyleLayerName) == 0)) {
 #ifdef notdef
-                    /*this is a test code if we decide to flag some layers as not supporting SLD*/
-                    pszSLDNotSupported = msOWSLookupMetadata(&(GET_LAYER(map, i)->metadata), "M", "SLD_NOT_SUPPORTED");
-                    if (pszSLDNotSupported)
-                    {
-                        msSetError(MS_WMSERR, "Layer %s does not support SLD", "msSLDApplySLD", pasLayers[j].name);
-                        return MS_FAILURE;
-                    }
+          /*this is a test code if we decide to flag some layers as not supporting SLD*/
+          pszSLDNotSupported = msOWSLookupMetadata(&(GET_LAYER(map, i)->metadata), "M", "SLD_NOT_SUPPORTED");
+          if (pszSLDNotSupported) {
+            msSetError(MS_WMSERR, "Layer %s does not support SLD", "msSLDApplySLD", pasLayers[j].name);
+            return MS_FAILURE;
+          }
 #endif
 
-                    if ( pasLayers[j].numclasses > 0)
-                    {
-                        GET_LAYER(map, i)->type = pasLayers[j].type;
-
-                        for(k=0;k<GET_LAYER(map, i)->numclasses;k++) 
-                        {
-                            if (GET_LAYER(map, i)->class[k] != NULL) 
-                            {
-                                GET_LAYER(map, i)->class[k]->layer=NULL;
-                                if (freeClass(GET_LAYER(map, i)->class[k]) == MS_SUCCESS )
-                                {
-                                    msFree(GET_LAYER(map, i)->class[k]);
-                                    GET_LAYER(map, i)->class[k] = NULL;
-                                }
-                            }
-                        }
+          if ( pasLayers[j].numclasses > 0) {
+            GET_LAYER(map, i)->type = pasLayers[j].type;
 
-                        GET_LAYER(map, i)->numclasses = 0;
-
-                        /*unset the classgroup on the layer if it was set. This allows the layer to render
-                          with all the classes defined in the SLD*/
-                        if (GET_LAYER(map, i)->classgroup)
-                          msFree(GET_LAYER(map, i)->classgroup);
-                        GET_LAYER(map, i)->classgroup = NULL;
-
-                        iClass = 0;
-                        for (k=0; k < pasLayers[j].numclasses; k++)
-                        {
-                            if (msGrowLayerClasses(GET_LAYER(map, i)) == NULL)
-                              return MS_FAILURE;
-
-                            initClass(GET_LAYER(map, i)->class[iClass]);
-                            msCopyClass(GET_LAYER(map, i)->class[iClass],
-                                        pasLayers[j].class[k], NULL);
-                            GET_LAYER(map, i)->class[iClass]->layer = GET_LAYER(map, i);
-                            GET_LAYER(map, i)->class[iClass]->type = GET_LAYER(map, i)->type;
-                            GET_LAYER(map, i)->numclasses++;
-                            
-                            /*aliases may have been used as part of the sld text symbolizer for
-                              label element. Try to process it if that is the case #3114*/
-                            if (msLayerOpen(GET_LAYER(map, i)) == MS_SUCCESS && 
-                                msLayerGetItems(GET_LAYER(map, i)) == MS_SUCCESS) 
-                            { 
-                                if (GET_LAYER(map, i)->class[iClass]->text.string)
-                                {
-                                    for(z=0; z<GET_LAYER(map, i)->numitems; z++) 
-                                    { 
-                                        if (!GET_LAYER(map, i)->items[z] || strlen(GET_LAYER(map, i)->items[z]) <= 0) 
-                                          continue; 
-                                        snprintf(szTmp, sizeof(szTmp), "%s_alias", GET_LAYER(map, i)->items[z]); 
-                                        pszFullName = msOWSLookupMetadata(&(GET_LAYER(map, i)->metadata), "G", szTmp); 
-                                        pszTmp1 = msStrdup( GET_LAYER(map, i)->class[iClass]->text.string);
-                                        if (pszFullName != NULL && (strstr(pszTmp1, pszFullName) != NULL)) 
-                                        { 
-                                            char *tmpstr1= NULL; 
-                                            tmpstr1 = msReplaceSubstring(pszTmp1, pszFullName, GET_LAYER(map, i)->items[z]); 
-                                            pszTmp2 = (char *)malloc(sizeof(char)*(strlen(tmpstr1)+3)); 
-                                            sprintf(pszTmp2,"(%s)",tmpstr1); 
-                                            msLoadExpressionString(&(GET_LAYER(map, i)->class[iClass]->text), pszTmp2); 
-                                            msFree(pszTmp2); 
-                                        } 
-                                        msFree(pszTmp1);
-                                    }
-                                }
-                            } 
-
-                            iClass++;
-                        }
-                    }
-                    else
-                    {   
-                        /*this is probably an SLD that uses Named styles*/
-                        if (pasLayers[j].classgroup)
-                        {
-                            for (k=0; k<GET_LAYER(map, i)->numclasses; k++)
-                            {
-                                if (GET_LAYER(map, i)->class[k]->group &&
-                                    strcasecmp(GET_LAYER(map, i)->class[k]->group, 
-                                               pasLayers[j].classgroup) == 0)
-                                  break;
-                            }
-                            if (k < GET_LAYER(map, i)->numclasses)
-                            {
-                                if ( GET_LAYER(map, i)->classgroup)
-                                  msFree( GET_LAYER(map, i)->classgroup);
-                                GET_LAYER(map, i)->classgroup = msStrdup(pasLayers[j].classgroup);
-                            }   
-                            else
-                            {
-                                /* TODO  we throw an exception ?*/
-                            }
-                        }
-                    }
-                    if (pasLayers[j].labelitem)
-                    {
-                        if (GET_LAYER(map, i)->labelitem)
-                          free(GET_LAYER(map, i)->labelitem);
+            for(k=0; k<GET_LAYER(map, i)->numclasses; k++) {
+              if (GET_LAYER(map, i)->class[k] != NULL) {
+                GET_LAYER(map, i)->class[k]->layer=NULL;
+                if (freeClass(GET_LAYER(map, i)->class[k]) == MS_SUCCESS ) {
+                  msFree(GET_LAYER(map, i)->class[k]);
+                  GET_LAYER(map, i)->class[k] = NULL;
+                }
+              }
+            }
 
-                        GET_LAYER(map, i)->labelitem = msStrdup(pasLayers[j].labelitem);
-                    }
+            GET_LAYER(map, i)->numclasses = 0;
+
+            /*unset the classgroup on the layer if it was set. This allows the layer to render
+              with all the classes defined in the SLD*/
+            msFree(GET_LAYER(map, i)->classgroup);
+            GET_LAYER(map, i)->classgroup = NULL;
 
-                    if (pasLayers[j].classitem)
-                    {
-                        if (GET_LAYER(map, i)->classitem)
-                          free(GET_LAYER(map, i)->classitem);
+            iClass = 0;
+            for (k=0; k < pasLayers[j].numclasses; k++) {
+              if (msGrowLayerClasses(GET_LAYER(map, i)) == NULL)
+                return MS_FAILURE;
 
-                        GET_LAYER(map, i)->classitem = msStrdup(pasLayers[j].classitem);
+              initClass(GET_LAYER(map, i)->class[iClass]);
+              msCopyClass(GET_LAYER(map, i)->class[iClass],
+                          pasLayers[j].class[k], NULL);
+              GET_LAYER(map, i)->class[iClass]->layer = GET_LAYER(map, i);
+              GET_LAYER(map, i)->class[iClass]->type = GET_LAYER(map, i)->type;
+              GET_LAYER(map, i)->numclasses++;
+
+              /*aliases may have been used as part of the sld text symbolizer for
+                label element. Try to process it if that is the case #3114*/
+              if (msLayerOpen(GET_LAYER(map, i)) == MS_SUCCESS &&
+                  msLayerGetItems(GET_LAYER(map, i)) == MS_SUCCESS) {
+                if (GET_LAYER(map, i)->class[iClass]->text.string) {
+                  for(z=0; z<GET_LAYER(map, i)->numitems; z++) {
+                    if (!GET_LAYER(map, i)->items[z] || strlen(GET_LAYER(map, i)->items[z]) <= 0)
+                      continue;
+                    snprintf(szTmp, sizeof(szTmp), "%s_alias", GET_LAYER(map, i)->items[z]);
+                    pszFullName = msOWSLookupMetadata(&(GET_LAYER(map, i)->metadata), "G", szTmp);
+                    pszTmp1 = msStrdup( GET_LAYER(map, i)->class[iClass]->text.string);
+                    if (pszFullName != NULL && (strstr(pszTmp1, pszFullName) != NULL)) {
+                      char *tmpstr1= NULL;
+                      tmpstr1 = msReplaceSubstring(pszTmp1, pszFullName, GET_LAYER(map, i)->items[z]);
+                      pszTmp2 = (char *)malloc(sizeof(char)*(strlen(tmpstr1)+3));
+                      sprintf(pszTmp2,"(%s)",tmpstr1);
+                      msLoadExpressionString(&(GET_LAYER(map, i)->class[iClass]->text), pszTmp2);
+                      msFree(pszTmp2);
                     }
-                    
-                    /* opacity for sld raster */
-                    if (GET_LAYER(map, i)->type == MS_LAYER_RASTER && 
-                        pasLayers[j].opacity != -1)
-                      GET_LAYER(map, i)->opacity = pasLayers[j].opacity;
-
-                    /* mark as auto-generate SLD */
-                    if (GET_LAYER(map, i)->connectiontype == MS_WMS)
-                      msInsertHashTable(&(GET_LAYER(map, i)->metadata), 
-                                        "wms_sld_body", "auto" );
-/* ==================================================================== */
-/*      if the SLD contained a spatial feature, the layerinfo           */
-/*      parameter contains the node. Extract it and do a query on       */
-/*      the layer. Insert also a metadata that will be used when        */
-/*      rendering the final image.                                      */
-/* ==================================================================== */
-                    if (pasLayers[j].layerinfo && 
-                        (GET_LAYER(map, i)->type ==  MS_LAYER_POINT || 
-                         GET_LAYER(map, i)->type == MS_LAYER_LINE ||
-                         GET_LAYER(map, i)->type == MS_LAYER_POLYGON ||
-                         GET_LAYER(map, i)->type == MS_LAYER_ANNOTATION ||
-                         GET_LAYER(map, i)->type == MS_LAYER_TILEINDEX))
-                    {  
-                        FilterEncodingNode *psNode = NULL;
-
-                        msInsertHashTable(&(GET_LAYER(map, i)->metadata), 
-                                          "tmp_wms_sld_query", "true" );
-                        psNode = (FilterEncodingNode *)pasLayers[j].layerinfo;
+                    msFree(pszTmp1);
+                  }
+                }
+              }
 
-/* -------------------------------------------------------------------- */
-/*      set the template on the classes so that the query works         */
-/*      using classes. If there are no classes, set it at the layer level.*/
-/* -------------------------------------------------------------------- */
-                        if (GET_LAYER(map, i)->numclasses > 0)
-                        {
-                            for (k=0; k<GET_LAYER(map, i)->numclasses; k++)
-                            {
-                                if (!GET_LAYER(map, i)->class[k]->template)
-                                  GET_LAYER(map, i)->class[k]->template = msStrdup("ttt.html");
-                            }
-                        }
-                        else if (!GET_LAYER(map, i)->template)
-                        {
-                            bFreeTemplate = 1;
-                            GET_LAYER(map, i)->template = msStrdup("ttt.html");
-                        }
+              iClass++;
+            }
+          } else {
+            /*this is probably an SLD that uses Named styles*/
+            if (pasLayers[j].classgroup) {
+              for (k=0; k<GET_LAYER(map, i)->numclasses; k++) {
+                if (GET_LAYER(map, i)->class[k]->group &&
+                    strcasecmp(GET_LAYER(map, i)->class[k]->group,
+                               pasLayers[j].classgroup) == 0)
+                  break;
+              }
+              if (k < GET_LAYER(map, i)->numclasses) {
+                msFree( GET_LAYER(map, i)->classgroup);
+                GET_LAYER(map, i)->classgroup = msStrdup(pasLayers[j].classgroup);
+              } else {
+                /* TODO  we throw an exception ?*/
+              }
+            }
+          }
+          if (pasLayers[j].labelitem) {
+            if (GET_LAYER(map, i)->labelitem)
+              free(GET_LAYER(map, i)->labelitem);
+
+            GET_LAYER(map, i)->labelitem = msStrdup(pasLayers[j].labelitem);
+          }
+
+          if (pasLayers[j].classitem) {
+            if (GET_LAYER(map, i)->classitem)
+              free(GET_LAYER(map, i)->classitem);
+
+            GET_LAYER(map, i)->classitem = msStrdup(pasLayers[j].classitem);
+          }
+
+          /* opacity for sld raster */
+          if (GET_LAYER(map, i)->type == MS_LAYER_RASTER &&
+              pasLayers[j].opacity != -1)
+            GET_LAYER(map, i)->opacity = pasLayers[j].opacity;
+
+          /* mark as auto-generate SLD */
+          if (GET_LAYER(map, i)->connectiontype == MS_WMS)
+            msInsertHashTable(&(GET_LAYER(map, i)->metadata),
+                              "wms_sld_body", "auto" );
+          /* ==================================================================== */
+          /*      if the SLD contained a spatial feature, the layerinfo           */
+          /*      parameter contains the node. Extract it and do a query on       */
+          /*      the layer. Insert also a metadata that will be used when        */
+          /*      rendering the final image.                                      */
+          /* ==================================================================== */
+          if (pasLayers[j].layerinfo &&
+              (GET_LAYER(map, i)->type ==  MS_LAYER_POINT ||
+               GET_LAYER(map, i)->type == MS_LAYER_LINE ||
+               GET_LAYER(map, i)->type == MS_LAYER_POLYGON ||
+               GET_LAYER(map, i)->type == MS_LAYER_ANNOTATION ||
+               GET_LAYER(map, i)->type == MS_LAYER_TILEINDEX)) {
+            FilterEncodingNode *psNode = NULL;
+
+            msInsertHashTable(&(GET_LAYER(map, i)->metadata),
+                              "tmp_wms_sld_query", "true" );
+            psNode = (FilterEncodingNode *)pasLayers[j].layerinfo;
+
+            /* -------------------------------------------------------------------- */
+            /*      set the template on the classes so that the query works         */
+            /*      using classes. If there are no classes, set it at the layer level.*/
+            /* -------------------------------------------------------------------- */
+            if (GET_LAYER(map, i)->numclasses > 0) {
+              for (k=0; k<GET_LAYER(map, i)->numclasses; k++) {
+                if (!GET_LAYER(map, i)->class[k]->template)
+                  GET_LAYER(map, i)->class[k]->template = msStrdup("ttt.html");
+              }
+            } else if (!GET_LAYER(map, i)->template) {
+              bFreeTemplate = 1;
+              GET_LAYER(map, i)->template = msStrdup("ttt.html");
+            }
 
-                        nLayerStatus =  GET_LAYER(map, i)->status;
-                        GET_LAYER(map, i)->status = MS_ON;
+            nLayerStatus =  GET_LAYER(map, i)->status;
+            GET_LAYER(map, i)->status = MS_ON;
+
+            nStatus =
+            FLTApplyFilterToLayer(psNode, map,
+                                  GET_LAYER(map, i)->index);
+            /* -------------------------------------------------------------------- */
+            /*      nothing found is a valid, do not exit.                          */
+            /* -------------------------------------------------------------------- */
+            if (nStatus !=  MS_SUCCESS) {
+              errorObj   *ms_error;
+              ms_error = msGetErrorObj();
+              if(ms_error->code == MS_NOTFOUND)
+                nStatus =  MS_SUCCESS;
+            }
 
-                        nStatus = 
-                            FLTApplyFilterToLayer(psNode, map,  
-                                                  GET_LAYER(map, i)->index);
 
+            GET_LAYER(map, i)->status = nLayerStatus;
+            FLTFreeFilterEncodingNode(psNode);
 
-                        GET_LAYER(map, i)->status = nLayerStatus;
-                        FLTFreeFilterEncodingNode(psNode);
+            if ( bFreeTemplate) {
+              free(GET_LAYER(map, i)->template);
+              GET_LAYER(map, i)->template = NULL;
+            }
 
-                        if ( bFreeTemplate)
-                        {
-                            free(GET_LAYER(map, i)->template);
-                            GET_LAYER(map, i)->template = NULL;
+            pasLayers[j].layerinfo=NULL;
+
+            if( nStatus != MS_SUCCESS )
+              return nStatus;
+          } else {
+            /*in some cases it would make sense to concatenate all the class
+              expressions and use it to set the filter on the layer. This
+              could increase performace. Will do it for db types layers #2840*/
+            lp = GET_LAYER(map, i);
+            if (lp->filter.string == NULL ||
+                (lp->filter.string && lp->filter.type == MS_EXPRESSION)) {
+              if (lp->connectiontype == MS_POSTGIS || lp->connectiontype ==  MS_ORACLESPATIAL ||
+                  lp->connectiontype == MS_SDE || lp->connectiontype == MS_PLUGIN) {
+                if (lp->numclasses > 0) {
+                  /*check first that all classes have an expression type. That is
+                    the only way we can concatenate them and set the filter
+                    expression*/
+                  for (k=0; k<lp->numclasses; k++) {
+                    if (lp->class[k]->expression.type != MS_EXPRESSION)
+                      break;
+                  }
+                  if (k == lp->numclasses) {
+                    bFailedExpression = 0;
+                    for (k=0; k<lp->numclasses; k++) {
+                      if (pszBuffer == NULL)
+                        snprintf(szTmp, sizeof(szTmp), "%s", "((");
+                      else
+                        snprintf(szTmp, sizeof(szTmp), "%s", " OR ");
+
+                      pszBuffer =msStringConcatenate(pszBuffer, szTmp);
+                      psExpressionNode = BuildExpressionTree(lp->class[k]->expression.string,NULL);
+                      if (psExpressionNode) {
+                        pszSqlExpression = FLTGetSQLExpression(psExpressionNode,lp);
+                        if (pszSqlExpression) {
+                          pszBuffer =
+                            msStringConcatenate(pszBuffer, pszSqlExpression);
+                          msFree(pszSqlExpression);
+                        } else {
+                          bFailedExpression =1;
+                          break;
                         }
-
-                        pasLayers[j].layerinfo=NULL;
-
-                        if( nStatus != MS_SUCCESS )
-                            return nStatus;
+                        FLTFreeFilterEncodingNode(psExpressionNode);
+                      } else {
+                        bFailedExpression =1;
+                        break;
+                      }
                     }
-                    else
-                    {
-                        /*in some cases it would make sense to concatenate all the class
-                          expressions and use it to set the filter on the layer. This   
-                          could increase performace. Will do it for db types layers #2840*/
-                        lp = GET_LAYER(map, i);
-                        if (lp->filter.string == NULL || 
-                            (lp->filter.string && lp->filter.type == MS_EXPRESSION))
-                        {
-                            if (lp->connectiontype == MS_POSTGIS || lp->connectiontype ==  MS_ORACLESPATIAL ||
-                                lp->connectiontype == MS_SDE || lp->connectiontype == MS_PLUGIN)
-                            {
-                                if (lp->numclasses > 0)
-                                {
-                                    /*check first that all classes have an expression type. That is
-                                      the only way we can concatenate them and set the filter 
-                                      expression*/
-                                    for (k=0;k<lp->numclasses;k++)
-                                    {
-                                        if (lp->class[k]->expression.type != MS_EXPRESSION)
-                                          break;
-                                    }
-                                    if (k == lp->numclasses)
-                                    {
-                                        bFailedExpression = 0;
-                                        for (k=0;k<lp->numclasses;k++)
-                                        {
-                                            if (pszBuffer == NULL)
-                                               snprintf(szTmp, sizeof(szTmp), "%s", "((");
-                                            else
-                                               snprintf(szTmp, sizeof(szTmp), "%s", " OR ");
-
-                                            pszBuffer =msStringConcatenate(pszBuffer, szTmp);
-                                            psExpressionNode = BuildExpressionTree(lp->class[k]->expression.string,NULL);
-                                            if (psExpressionNode)
-                                            {
-                                                pszSqlExpression = FLTGetSQLExpression(psExpressionNode,lp);
-                                                if (pszSqlExpression)
-                                                {
-                                                    pszBuffer =
-                                                      msStringConcatenate(pszBuffer, pszSqlExpression);
-                                                    msFree(pszSqlExpression);
-                                                }
-                                                else
-						{
-                                                    bFailedExpression =1;
-                                                    break;
-                                                }
-                                                FLTFreeFilterEncodingNode(psExpressionNode);
-                                            }
-                                            else
-					    {   
-                                                bFailedExpression =1;
-                                                break;
-                                            }
-                                        }
-                                        if (!bFailedExpression)
-                                        {
-                                            snprintf(szTmp, sizeof(szTmp), "%s", "))");
-                                            pszBuffer =msStringConcatenate(pszBuffer, szTmp);
-                                            msLoadExpressionString(&lp->filter, pszBuffer);
-                                        }
-                                        msFree(pszBuffer);
-                                    }
-                                }    
-                            }       
-                        }
-                        
+                    if (!bFailedExpression) {
+                      snprintf(szTmp, sizeof(szTmp), "%s", "))");
+                      pszBuffer =msStringConcatenate(pszBuffer, szTmp);
+                      msLoadExpressionString(&lp->filter, pszBuffer);
                     }
-                    break;
+                    msFree(pszBuffer);
+                    pszBuffer = NULL;
+                  }
                 }
+              }
             }
-            if (bUseSpecificLayer)
-              break;
+
+          }
+          break;
         }
-	
-	for (i=0; i<nLayers; i++)
-	  freeLayer(&pasLayers[i]);
-	msFree(pasLayers);
+      }
+      if (bUseSpecificLayer)
+        break;
     }
-    if(map->debug == MS_DEBUGLEVEL_VVV)
-    {
-        tmpfilename = msTmpFile(map, map->mappath, NULL, "_sld.map");
-        if (tmpfilename == NULL)
-        {
-            tmpfilename = msTmpFile(map, NULL, NULL, "_sld.map" );
-        }
-        if (tmpfilename)
-        {
-            msSaveMap(map,tmpfilename);
-            msDebug("msApplySLD(): Map file after SLD was applied %s", tmpfilename);
-            msFree(tmpfilename);
+
+    /* -------------------------------------------------------------------- */
+    /*      if needed return a comma separated list of the layers found     */
+    /*      in the sld.                                                     */
+    /* -------------------------------------------------------------------- */
+    if (ppszLayerNames) {
+      char *pszTmp = NULL;
+      for (i=0; i<nLayers; i++) {
+        if (pasLayers[i].name) {
+          if (pszTmp !=NULL)
+            pszTmp = msStringConcatenate(pszTmp, ",");
+          pszTmp = msStringConcatenate(pszTmp, pasLayers[i].name);
+
         }
+      }
+      *ppszLayerNames = pszTmp;
+
     }
-    return MS_SUCCESS;
+    for (i=0; i<nLayers; i++)
+      freeLayer(&pasLayers[i]);
+    msFree(pasLayers);
+  }
+  if(map->debug == MS_DEBUGLEVEL_VVV) {
+    tmpfilename = msTmpFile(map, map->mappath, NULL, "_sld.map");
+    if (tmpfilename == NULL) {
+      tmpfilename = msTmpFile(map, NULL, NULL, "_sld.map" );
+    }
+    if (tmpfilename) {
+      msSaveMap(map,tmpfilename);
+      msDebug("msApplySLD(): Map file after SLD was applied %s", tmpfilename);
+      msFree(tmpfilename);
+    }
+  }
+  return MS_SUCCESS;
 
 
 #else
-/* ------------------------------------------------------------------
- * OGR Support not included...
- * ------------------------------------------------------------------ */
+  /* ------------------------------------------------------------------
+   * OGR Support not included...
+   * ------------------------------------------------------------------ */
 
-    msSetError(MS_MISCERR, "OGR support is not available.", "msSLDApplySLD()");
-    return(MS_FAILURE);
+  msSetError(MS_MISCERR, "OGR support is not available.", "msSLDApplySLD()");
+  return(MS_FAILURE);
 
 #endif /* USE_OGR */
 
 #else
-    msSetError(MS_MISCERR, "OWS support is not available.", 
-               "msSLDApplySLD()");
-    return(MS_FAILURE);
+  msSetError(MS_MISCERR, "OWS support is not available.",
+             "msSLDApplySLD()");
+  return(MS_FAILURE);
 #endif
 }
 
 
 
 #ifdef USE_OGR
-                       
-    
+
+
 /************************************************************************/
 /*                              msSLDParseSLD                           */
 /*                                                                      */
@@ -505,117 +512,122 @@ int msSLDApplySLD(mapObj *map, char *psSLDXML, int iLayer,
 /************************************************************************/
 layerObj  *msSLDParseSLD(mapObj *map, char *psSLDXML, int *pnLayers)
 {
-    CPLXMLNode *psRoot = NULL;
-    CPLXMLNode *psSLD, *psNamedLayer, *psChild, *psName;
-    layerObj *pasLayers = NULL;
-    int iLayer = 0;
-    int nLayers = 0;
+  CPLXMLNode *psRoot = NULL;
+  CPLXMLNode *psSLD, *psNamedLayer, *psChild, *psName;
+  layerObj *pasLayers = NULL;
+  int iLayer = 0;
+  int nLayers = 0;
 
 
-    if (map == NULL || psSLDXML == NULL || strlen(psSLDXML) <= 0 ||
-        (strstr(psSLDXML, "StyledLayerDescriptor") == NULL))
-    {
-        msSetError(MS_WMSERR, "Invalid SLD document", "");
-        return NULL;
-    }
+  if (map == NULL || psSLDXML == NULL || strlen(psSLDXML) <= 0 ||
+      (strstr(psSLDXML, "StyledLayerDescriptor") == NULL)) {
+    msSetError(MS_WMSERR, "Invalid SLD document", "");
+    return NULL;
+  }
 
-    psRoot = CPLParseXMLString(psSLDXML);
-    if( psRoot == NULL)
-    {
-        msSetError(MS_WMSERR, "Invalid SLD document : %s", "", psSLDXML);
-        return NULL;
+  psRoot = CPLParseXMLString(psSLDXML);
+  if( psRoot == NULL) {
+    msSetError(MS_WMSERR, "Invalid SLD document : %s", "", psSLDXML);
+    return NULL;
+  }
+
+  /* strip namespaces ogc and sld and gml */
+  CPLStripXMLNamespace(psRoot, "ogc", 1);
+  CPLStripXMLNamespace(psRoot, "sld", 1);
+  CPLStripXMLNamespace(psRoot, "gml", 1);
+  CPLStripXMLNamespace(psRoot, "se", 1);
+
+
+  /* -------------------------------------------------------------------- */
+  /*      get the root element (Filter).                                  */
+  /* -------------------------------------------------------------------- */
+  psChild = psRoot;
+  psSLD = NULL;
+
+  while( psChild != NULL ) {
+    if (psChild->eType == CXT_Element &&
+        EQUAL(psChild->pszValue,"StyledLayerDescriptor")) {
+      psSLD = psChild;
+      break;
+    } else
+      psChild = psChild->psNext;
+  }
+
+  if (!psSLD) {
+    msSetError(MS_WMSERR, "Invalid SLD document : %s", "", psSLDXML);
+    return NULL;
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Parse the named layers.                                         */
+  /* -------------------------------------------------------------------- */
+  psNamedLayer = CPLGetXMLNode(psSLD, "NamedLayer");
+  while (psNamedLayer) {
+    if (!psNamedLayer->pszValue ||
+        strcasecmp(psNamedLayer->pszValue, "NamedLayer") != 0) {
+      psNamedLayer = psNamedLayer->psNext;
+      continue;
     }
 
-    /* strip namespaces ogc and sld and gml */
-    CPLStripXMLNamespace(psRoot, "ogc", 1); 
-    CPLStripXMLNamespace(psRoot, "sld", 1); 
-    CPLStripXMLNamespace(psRoot, "gml", 1); 
-    CPLStripXMLNamespace(psRoot, "se", 1); 
-    
-
-/* -------------------------------------------------------------------- */
-/*      get the root element (Filter).                                  */
-/* -------------------------------------------------------------------- */
-    psChild = psRoot;
-    psSLD = NULL;
-     
-    while( psChild != NULL )
-    {
-        if (psChild->eType == CXT_Element &&
-            EQUAL(psChild->pszValue,"StyledLayerDescriptor"))
-        {
-            psSLD = psChild;
-            break;
-        }
-        else
-          psChild = psChild->psNext;
-    }
+    psNamedLayer = psNamedLayer->psNext;
+    nLayers++;
+  }
 
-    if (!psSLD)
-    {
-        msSetError(MS_WMSERR, "Invalid SLD document : %s", "", psSLDXML);
-        return NULL;
-    }
+  if (nLayers > 0)
+    pasLayers = (layerObj *)malloc(sizeof(layerObj)*nLayers);
+  else
+    return NULL;
 
-/* -------------------------------------------------------------------- */
-/*      Parse the named layers.                                         */
-/* -------------------------------------------------------------------- */
-    psNamedLayer = CPLGetXMLNode(psSLD, "NamedLayer");
+  psNamedLayer = CPLGetXMLNode(psSLD, "NamedLayer");
+  if (psNamedLayer) {
+    iLayer = 0;
     while (psNamedLayer)
+
     {
-        if (!psNamedLayer->pszValue || 
-            strcasecmp(psNamedLayer->pszValue, "NamedLayer") != 0)
-        {
-            psNamedLayer = psNamedLayer->psNext;
-            continue;
-        }
-    
+      if (!psNamedLayer->pszValue ||
+          strcasecmp(psNamedLayer->pszValue, "NamedLayer") != 0) {
         psNamedLayer = psNamedLayer->psNext;
-        nLayers++;
-    }
+        continue;
+      }
 
-    if (nLayers > 0)
-      pasLayers = (layerObj *)malloc(sizeof(layerObj)*nLayers);
-    else
-      return NULL;
+      psName = CPLGetXMLNode(psNamedLayer, "Name");
+      initLayer(&pasLayers[iLayer], map);
 
-    psNamedLayer = CPLGetXMLNode(psSLD, "NamedLayer");
-    if (psNamedLayer)
-    {
-        iLayer = 0;
-        while (psNamedLayer) 
+      if (psName && psName->psChild &&  psName->psChild->pszValue)
+        pasLayers[iLayer].name = msStrdup(psName->psChild->pszValue);
 
-        {
-            if (!psNamedLayer->pszValue || 
-                strcasecmp(psNamedLayer->pszValue, "NamedLayer") != 0)
-            {
-                psNamedLayer = psNamedLayer->psNext;
-                continue;
-            }
+      msSLDParseNamedLayer(psNamedLayer, &pasLayers[iLayer]);
 
-            psName = CPLGetXMLNode(psNamedLayer, "Name");
-            initLayer(&pasLayers[iLayer], map);
-            
-            if (psName && psName->psChild &&  psName->psChild->pszValue)
-              pasLayers[iLayer].name = msStrdup(psName->psChild->pszValue);
-            
-            msSLDParseNamedLayer(psNamedLayer, &pasLayers[iLayer]);
-            
-            psNamedLayer = psNamedLayer->psNext;
-            iLayer++;
-        }
+      psNamedLayer = psNamedLayer->psNext;
+      iLayer++;
     }
+  }
 
-    if (pnLayers)
-      *pnLayers = nLayers;
+  if (pnLayers)
+    *pnLayers = nLayers;
 
-    if (psRoot)
-      CPLDestroyXMLNode(psRoot);
+  if (psRoot)
+    CPLDestroyXMLNode(psRoot);
 
-    return pasLayers;
+  return pasLayers;
 }
 
 
+int _msSLDParseSizeParameter(CPLXMLNode *psSize)
+{
+  int nSize = 0;
+  CPLXMLNode *psLiteral = NULL;
+
+  if (psSize) {
+    psLiteral = CPLGetXMLNode(psSize, "Literal");
+    if (psLiteral && psLiteral->psChild && psLiteral->psChild->pszValue)
+      nSize = atof(psLiteral->psChild->pszValue);
+    else if (psSize->psChild && psSize->psChild->pszValue)
+      nSize = atof(psSize->psChild->pszValue);
+  }
+
+  return nSize;
+}
 
 /************************************************************************/
 /*                           _SLDApplyRuleValues                        */
@@ -623,84 +635,77 @@ layerObj  *msSLDParseSLD(mapObj *map, char *psSLDXML, int *pnLayers)
 /*      Utility function to set the scale, title/name for the          */
 /*      classes created by a Rule.                                      */
 /************************************************************************/
-void  _SLDApplyRuleValues(CPLXMLNode *psRule, layerObj *psLayer, 
+void  _SLDApplyRuleValues(CPLXMLNode *psRule, layerObj *psLayer,
                           int nNewClasses)
 {
-    int         i=0;
-    CPLXMLNode *psMinScale=NULL, *psMaxScale=NULL;
-    CPLXMLNode *psName=NULL, *psTitle=NULL;
-    double dfMinScale=0, dfMaxScale=0;
-    char *pszName=NULL, *pszTitle=NULL;
-
-    if (psRule && psLayer && nNewClasses > 0)
-    {
-/* -------------------------------------------------------------------- */
-/*      parse minscale and maxscale.                                    */
-/* -------------------------------------------------------------------- */
-        psMinScale = CPLGetXMLNode(psRule, 
-                                   "MinScaleDenominator");
-        if (psMinScale && psMinScale->psChild && 
-            psMinScale->psChild->pszValue)
-          dfMinScale = atof(psMinScale->psChild->pszValue);
-
-        psMaxScale = CPLGetXMLNode(psRule, 
-                                   "MaxScaleDenominator");
-        if (psMaxScale && psMaxScale->psChild && 
-            psMaxScale->psChild->pszValue)
-          dfMaxScale = atof(psMaxScale->psChild->pszValue);
-
-/* -------------------------------------------------------------------- */
-/*      parse name and title.                                           */
-/* -------------------------------------------------------------------- */
-        psName = CPLGetXMLNode(psRule, "Name");  
-        if (psName && psName->psChild && 
-            psName->psChild->pszValue)
-          pszName = psName->psChild->pszValue;
+  int         i=0;
+  CPLXMLNode *psMinScale=NULL, *psMaxScale=NULL;
+  CPLXMLNode *psName=NULL, *psTitle=NULL;
+  double dfMinScale=0, dfMaxScale=0;
+  char *pszName=NULL, *pszTitle=NULL;
+
+  if (psRule && psLayer && nNewClasses > 0) {
+    /* -------------------------------------------------------------------- */
+    /*      parse minscale and maxscale.                                    */
+    /* -------------------------------------------------------------------- */
+    psMinScale = CPLGetXMLNode(psRule,
+                               "MinScaleDenominator");
+    if (psMinScale && psMinScale->psChild &&
+        psMinScale->psChild->pszValue)
+      dfMinScale = atof(psMinScale->psChild->pszValue);
+
+    psMaxScale = CPLGetXMLNode(psRule,
+                               "MaxScaleDenominator");
+    if (psMaxScale && psMaxScale->psChild &&
+        psMaxScale->psChild->pszValue)
+      dfMaxScale = atof(psMaxScale->psChild->pszValue);
+
+    /* -------------------------------------------------------------------- */
+    /*      parse name and title.                                           */
+    /* -------------------------------------------------------------------- */
+    psName = CPLGetXMLNode(psRule, "Name");
+    if (psName && psName->psChild &&
+        psName->psChild->pszValue)
+      pszName = psName->psChild->pszValue;
+
+    psTitle = CPLGetXMLNode(psRule, "Title");
+    if (psTitle && psTitle->psChild &&
+        psTitle->psChild->pszValue)
+      pszTitle = psTitle->psChild->pszValue;
+
+    /* -------------------------------------------------------------------- */
+    /*      set the scale to all the classes created by the rule.           */
+    /* -------------------------------------------------------------------- */
+    if (dfMinScale > 0 || dfMaxScale > 0) {
+      for (i=0; i<nNewClasses; i++) {
+        if (dfMinScale > 0)
+          psLayer->class[psLayer->numclasses-1-i]->minscaledenom = dfMinScale;
+        if (dfMaxScale)
+          psLayer->class[psLayer->numclasses-1-i]->maxscaledenom = dfMaxScale;
+      }
+    }
+    /* -------------------------------------------------------------------- */
+    /*      set name and title to the classes created by the rule.          */
+    /* -------------------------------------------------------------------- */
+    for (i=0; i<nNewClasses; i++) {
+      if (!psLayer->class[psLayer->numclasses-1-i]->name) {
+        if (pszName)
+          psLayer->class[psLayer->numclasses-1-i]->name = msStrdup(pszName);
+        else if (pszTitle)
+          psLayer->class[psLayer->numclasses-1-i]->name = msStrdup(pszTitle);
+        else
+          psLayer->class[psLayer->numclasses-1-i]->name = msStrdup("Unknown");
+      }
+    }
+    if (pszTitle) {
+      for (i=0; i<nNewClasses; i++) {
+        psLayer->class[psLayer->numclasses-1-i]->title =
+              msStrdup(pszTitle);
+      }
+    }
 
-        psTitle = CPLGetXMLNode(psRule, "Title");  
-        if (psTitle && psTitle->psChild && 
-            psTitle->psChild->pszValue)
-          pszTitle = psTitle->psChild->pszValue;
+  }
 
-/* -------------------------------------------------------------------- */
-/*      set the scale to all the classes created by the rule.           */
-/* -------------------------------------------------------------------- */
-        if (dfMinScale > 0 || dfMaxScale > 0)
-        {
-            for (i=0; i<nNewClasses; i++)
-            {
-                if (dfMinScale > 0)
-                  psLayer->class[psLayer->numclasses-1-i]->minscaledenom = dfMinScale;
-                if (dfMaxScale)
-                  psLayer->class[psLayer->numclasses-1-i]->maxscaledenom = dfMaxScale;
-            }                           
-        }
-/* -------------------------------------------------------------------- */
-/*      set name and title to the classes created by the rule.          */
-/* -------------------------------------------------------------------- */
-        for (i=0; i<nNewClasses; i++)
-        {
-            if (!psLayer->class[psLayer->numclasses-1-i]->name)
-            {
-                if (pszName)
-                  psLayer->class[psLayer->numclasses-1-i]->name = msStrdup(pszName);
-                else if (pszTitle)
-                  psLayer->class[psLayer->numclasses-1-i]->name = msStrdup(pszTitle);
-                else
-                  psLayer->class[psLayer->numclasses-1-i]->name = msStrdup("Unknown");
-            }
-        }
-        if (pszTitle)
-        {
-            for (i=0; i<nNewClasses; i++)
-            {
-                psLayer->class[psLayer->numclasses-1-i]->title = 
-                  msStrdup(pszTitle);
-            }                           
-        }
-          
-    }
-        
 }
 
 
@@ -711,212 +716,187 @@ void  _SLDApplyRuleValues(CPLXMLNode *psRule, layerObj *psLayer,
 /************************************************************************/
 int msSLDParseNamedLayer(CPLXMLNode *psRoot, layerObj *psLayer)
 {
-    CPLXMLNode *psFeatureTypeStyle, *psRule, *psUserStyle; 
-    CPLXMLNode *psSLDName = NULL, *psNamedStyle=NULL;
-    CPLXMLNode *psElseFilter = NULL, *psFilter=NULL;
-    CPLXMLNode *psTmpNode = NULL;
-    FilterEncodingNode *psNode = NULL;
-    char *szExpression = NULL;
-    int i=0, nNewClasses=0, nClassBeforeFilter=0, nClassAfterFilter=0;
-    int nClassAfterRule=0, nClassBeforeRule=0;
-    char *pszTmpFilter = NULL;
-    layerObj *psCurrentLayer = NULL;
-    const char *pszWmsName=NULL;
-    int j=0;
-    const char *key=NULL;
-
-    if (!psRoot || !psLayer)
-        return MS_FAILURE;
+  CPLXMLNode *psFeatureTypeStyle, *psRule, *psUserStyle;
+  CPLXMLNode *psSLDName = NULL, *psNamedStyle=NULL;
+  CPLXMLNode *psElseFilter = NULL, *psFilter=NULL;
+  CPLXMLNode *psTmpNode = NULL;
+  FilterEncodingNode *psNode = NULL;
+  int nNewClasses=0, nClassBeforeFilter=0, nClassAfterFilter=0;
+  int nClassAfterRule=0, nClassBeforeRule=0;
+  char *pszTmpFilter = NULL;
+  layerObj *psCurrentLayer = NULL;
+  const char *pszWmsName=NULL;
+  int j=0;
+  const char *key=NULL;
+
+  if (!psRoot || !psLayer)
+    return MS_FAILURE;
 
-        psUserStyle = CPLGetXMLNode(psRoot, "UserStyle");
-        if (psUserStyle)
-        {
-            psFeatureTypeStyle = CPLGetXMLNode(psUserStyle, "FeatureTypeStyle");
-            if (psFeatureTypeStyle)
-            {
-                while (psFeatureTypeStyle && psFeatureTypeStyle->pszValue && 
-                       strcasecmp(psFeatureTypeStyle->pszValue, 
-                                  "FeatureTypeStyle") == 0)
-                {
-                    if (!psFeatureTypeStyle->pszValue ||
-                        strcasecmp(psFeatureTypeStyle->pszValue, 
-                                   "FeatureTypeStyle") != 0)
-                    {
-                        psFeatureTypeStyle = psFeatureTypeStyle->psNext;
-                        continue;
-                    }
+  psUserStyle = CPLGetXMLNode(psRoot, "UserStyle");
+  if (psUserStyle) {
+    psFeatureTypeStyle = CPLGetXMLNode(psUserStyle, "FeatureTypeStyle");
+    if (psFeatureTypeStyle) {
+      while (psFeatureTypeStyle && psFeatureTypeStyle->pszValue &&
+             strcasecmp(psFeatureTypeStyle->pszValue,
+                        "FeatureTypeStyle") == 0) {
+        if (!psFeatureTypeStyle->pszValue ||
+            strcasecmp(psFeatureTypeStyle->pszValue,
+                       "FeatureTypeStyle") != 0) {
+          psFeatureTypeStyle = psFeatureTypeStyle->psNext;
+          continue;
+        }
 
-/* -------------------------------------------------------------------- */
-/*      Parse rules with no Else filter.                                */
-/* -------------------------------------------------------------------- */
-                    psRule = CPLGetXMLNode(psFeatureTypeStyle, "Rule");
-                    while (psRule)
-                    {
-                        if (!psRule->pszValue || 
-                            strcasecmp(psRule->pszValue, "Rule") != 0)
-                        {
-                            psRule = psRule->psNext;
-                            continue;
-                        }
-                        /* used for scale setting */
-                        nClassBeforeRule = psLayer->numclasses;
+        /* -------------------------------------------------------------------- */
+        /*      Parse rules with no Else filter.                                */
+        /* -------------------------------------------------------------------- */
+        psRule = CPLGetXMLNode(psFeatureTypeStyle, "Rule");
+        while (psRule) {
+          if (!psRule->pszValue ||
+              strcasecmp(psRule->pszValue, "Rule") != 0) {
+            psRule = psRule->psNext;
+            continue;
+          }
+          /* used for scale setting */
+          nClassBeforeRule = psLayer->numclasses;
+
+          psElseFilter = CPLGetXMLNode(psRule, "ElseFilter");
+          nClassBeforeFilter = psLayer->numclasses;
+          if (psElseFilter == NULL)
+            msSLDParseRule(psRule, psLayer);
+          nClassAfterFilter = psLayer->numclasses;
+
+          /* -------------------------------------------------------------------- */
+          /*      Parse the filter and apply it to the latest class created by    */
+          /*      the rule.                                                       */
+          /*      NOTE : Spatial Filter is not supported.                         */
+          /* -------------------------------------------------------------------- */
+          psFilter = CPLGetXMLNode(psRule, "Filter");
+          if (psFilter && psFilter->psChild &&
+              psFilter->psChild->pszValue) {
+            CPLXMLNode *psTmpNextNode = NULL;
+            /* clone the tree and set the next node to null */
+            /* so we only have the Filter node */
+            psTmpNode = CPLCloneXMLTree(psFilter);
+            psTmpNextNode = psTmpNode->psNext;
+            psTmpNode->psNext = NULL;
+            pszTmpFilter = CPLSerializeXMLTree(psTmpNode);
+            psTmpNode->psNext = psTmpNextNode;
+            CPLDestroyXMLNode(psTmpNode);
+
+            if (pszTmpFilter) {
+              /* nTmp = strlen(psFilter->psChild->pszValue)+17; */
+              /* pszTmpFilter = malloc(sizeof(char)*nTmp); */
+              /* sprintf(pszTmpFilter,"<Filter>%s</Filter>", */
+              /* psFilter->psChild->pszValue); */
+              /* pszTmpFilter[nTmp-1]='\0'; */
+              psNode = FLTParseFilterEncoding(pszTmpFilter);
+
+              CPLFree(pszTmpFilter);
+            }
 
-                        psElseFilter = CPLGetXMLNode(psRule, "ElseFilter");
-                        nClassBeforeFilter = psLayer->numclasses;
-                        if (psElseFilter == NULL)
-                          msSLDParseRule(psRule, psLayer);
-                        nClassAfterFilter = psLayer->numclasses;
+            if (psNode) {
+              char *pszExpression = NULL;
+              int i;
 
-/* -------------------------------------------------------------------- */
-/*      Parse the filter and apply it to the latest class created by    */
-/*      the rule.                                                       */
-/*      NOTE : Spatial Filter is not supported.                         */
-/* -------------------------------------------------------------------- */
-                        psFilter = CPLGetXMLNode(psRule, "Filter");
-                        if (psFilter && psFilter->psChild && 
-                            psFilter->psChild->pszValue)
-                        {
-                            
-                            /* clone the tree and set the next node to null */
-                            /* so we only have the Filter node */
-                            psTmpNode = CPLCloneXMLTree(psFilter);
-                            psTmpNode->psNext = NULL;
-                            pszTmpFilter = CPLSerializeXMLTree(psTmpNode);
-                            CPLDestroyXMLNode(psTmpNode);
-
-                            if (pszTmpFilter)
-                            {
-                            /* nTmp = strlen(psFilter->psChild->pszValue)+17; */
-                            /* pszTmpFilter = malloc(sizeof(char)*nTmp); */
-                            /* sprintf(pszTmpFilter,"<Filter>%s</Filter>", */
-                            /* psFilter->psChild->pszValue); */
-                            /* pszTmpFilter[nTmp-1]='\0'; */
-                                psNode = FLTParseFilterEncoding(pszTmpFilter);
-                            
-                                CPLFree(pszTmpFilter);
-                            }
-
-                            if (psNode)
-                            {
-                                /*preparse the filter for possible gml aliases set on the layer's metada:
-                                  "gml_NA3DESC_alias" "alias_name" and filter could be  
-                                <ogc:PropertyName>alias_name</ogc:PropertyName> #3079*/
-                                for (j=0; j<psLayer->map->numlayers; j++)
-                                {
-                                    psCurrentLayer = GET_LAYER(psLayer->map, j);
-
-                                    pszWmsName = msOWSLookupMetadata(&(psCurrentLayer->metadata), "MO", "name");
-
-                                    if ((psCurrentLayer->name && psLayer->name && 
-                                         strcasecmp(psCurrentLayer->name, psLayer->name) == 0) ||
-                                        (psCurrentLayer->group && psLayer->name &&
-                                         strcasecmp(psCurrentLayer->group, psLayer->name) == 0) ||
-                                        (psLayer->name && pszWmsName &&
-                                         strcasecmp(pszWmsName, psLayer->name) == 0))
-                                      break;
-                                }
-                                if (j < psLayer->map->numlayers)
-                                {
-                                    /*make sure that the tmp layer has all the metadata that
-                                      the orinal layer has, allowing to do parsing for
-                                      such things as gml_attribute_type #3052*/
-                                    while (1) 
-                                    {
-                                        key = msNextKeyFromHashTable(&psCurrentLayer->metadata, key);
-                                        if (!key) 
-                                          break;
-                                        else 
-                                          msInsertHashTable(&psLayer->metadata, key, 
-                                                            msLookupHashTable(&psCurrentLayer->metadata, key));
-                                    }
-                                    FLTPreParseFilterForAlias(psNode, psLayer->map, j, "G");
-                                }
-
-                                szExpression = FLTGetCommonExpression(psNode, psLayer);
-
-/* ==================================================================== */
-/*      If the filter has a spatial filter or is a simple, we keep      */
-/*      the node. This node will be parsed when applying the SLD and    */
-/*      be used to do queries on the layer.  Simple filers              */
-/*      (Comparision operators (PropertyIsEqualTo,                      */
-/*      PropertyNotEqualTo, ... combined or not with logical            */
-/*      operators such as AND/OR/NOT) will be used to set the FILTER    */
-/*      element of the layer.                                           */
-/* ==================================================================== */
-                                if (FLTHasSpatialFilter(psNode)) 
-                                  psLayer->layerinfo = (void *)psNode;
-                                else
-                                  FLTFreeFilterEncodingNode(psNode);
-                                psNode = NULL;
-
-                                if (szExpression)
-                                {
-                                    nNewClasses = 
-                                      nClassAfterFilter - nClassBeforeFilter;
-                                    for (i=0; i<nNewClasses; i++)
-                                    {
-                                        msLoadExpressionString(&psLayer->
-                                                             class[psLayer->numclasses-1-i]->
-                                                             expression, szExpression);
-                                    }
-                                    msFree(szExpression);
-                                    szExpression = NULL;
-                                }
-                            }
-                        }
-                        nClassAfterRule = psLayer->numclasses;
-                        nNewClasses = nClassAfterRule - nClassBeforeRule;
+              /*preparse the filter for possible gml aliases set on the layer's metada:
+                "gml_NA3DESC_alias" "alias_name" and filter could be
+              <ogc:PropertyName>alias_name</ogc:PropertyName> #3079*/
+              for (j=0; j<psLayer->map->numlayers; j++) {
+                psCurrentLayer = GET_LAYER(psLayer->map, j);
 
-                        /* apply scale and title to newly created classes */
-                        _SLDApplyRuleValues(psRule, psLayer, nNewClasses);
+                pszWmsName = msOWSLookupMetadata(&(psCurrentLayer->metadata), "MO", "name");
 
-                        /* TODO : parse legendgraphic */
-                        psRule = psRule->psNext;
+                if ((psCurrentLayer->name && psLayer->name &&
+                     strcasecmp(psCurrentLayer->name, psLayer->name) == 0) ||
+                    (psCurrentLayer->group && psLayer->name &&
+                     strcasecmp(psCurrentLayer->group, psLayer->name) == 0) ||
+                    (psLayer->name && pszWmsName &&
+                     strcasecmp(pszWmsName, psLayer->name) == 0))
+                  break;
+              }
+              if (j < psLayer->map->numlayers) {
+                /*make sure that the tmp layer has all the metadata that
+                  the orinal layer has, allowing to do parsing for
+                  such things as gml_attribute_type #3052*/
+                while (1) {
+                  key = msNextKeyFromHashTable(&psCurrentLayer->metadata, key);
+                  if (!key)
+                    break;
+                  else
+                    msInsertHashTable(&psLayer->metadata, key,
+                                      msLookupHashTable(&psCurrentLayer->metadata, key));
+                }
+                FLTPreParseFilterForAlias(psNode, psLayer->map, j, "G");
+              }
+
+              pszExpression = FLTGetCommonExpression(psNode, psLayer);
+              FLTFreeFilterEncodingNode(psNode);
+              psNode = NULL;
+
+              if (pszExpression) {
+                nNewClasses =
+                  nClassAfterFilter - nClassBeforeFilter;
+                for (i=0; i<nNewClasses; i++) {
+                  msLoadExpressionString(&psLayer->
+                                         class[psLayer->numclasses-1-i]->
+                                         expression, pszExpression);
+                }
+                msFree(pszExpression);
+                pszExpression = NULL;
+              }
 
-                    }
-/* -------------------------------------------------------------------- */
-/*      First parse rules with the else filter. These rules will        */
-/*      create the classes that are placed at the end of class          */
-/*      list. (See how classes are applied to layers in function        */
-/*      msSLDApplySLD).                                                 */
-/* -------------------------------------------------------------------- */
-                    psRule = CPLGetXMLNode(psFeatureTypeStyle, "Rule");
-                    while (psRule)
-                    {
-                        if (!psRule->pszValue || 
-                            strcasecmp(psRule->pszValue, "Rule") != 0)
-                        {
-                            psRule = psRule->psNext;
-                            continue;
-                        }
-                        psElseFilter = CPLGetXMLNode(psRule, "ElseFilter");
-                        if (psElseFilter)
-                        {
-                            msSLDParseRule(psRule, psLayer);
-                            _SLDApplyRuleValues(psRule, psLayer, 1);
-                        }
-                        psRule = psRule->psNext;
+            }
+          }
+          nClassAfterRule = psLayer->numclasses;
+          nNewClasses = nClassAfterRule - nClassBeforeRule;
 
-                        
-                    }
+          /* apply scale and title to newly created classes */
+          _SLDApplyRuleValues(psRule, psLayer, nNewClasses);
+
+          /* TODO : parse legendgraphic */
+          psRule = psRule->psNext;
 
-                    psFeatureTypeStyle = psFeatureTypeStyle->psNext;
-                }
-            }
         }
-        /* check for Named styles*/
-        else
-        {
-            psNamedStyle = CPLGetXMLNode(psRoot, "NamedStyle");
-            if (psNamedStyle)
-            {
-                psSLDName = CPLGetXMLNode(psNamedStyle, "Name");
-                if (psSLDName && psSLDName->psChild &&  psSLDName->psChild->pszValue)
-                  psLayer->classgroup = msStrdup(psSLDName->psChild->pszValue);
-            }
+        /* -------------------------------------------------------------------- */
+        /*      First parse rules with the else filter. These rules will        */
+        /*      create the classes that are placed at the end of class          */
+        /*      list. (See how classes are applied to layers in function        */
+        /*      msSLDApplySLD).                                                 */
+        /* -------------------------------------------------------------------- */
+        psRule = CPLGetXMLNode(psFeatureTypeStyle, "Rule");
+        while (psRule) {
+          if (!psRule->pszValue ||
+              strcasecmp(psRule->pszValue, "Rule") != 0) {
+            psRule = psRule->psNext;
+            continue;
+          }
+          psElseFilter = CPLGetXMLNode(psRule, "ElseFilter");
+          if (psElseFilter) {
+            msSLDParseRule(psRule, psLayer);
+            _SLDApplyRuleValues(psRule, psLayer, 1);
+          }
+          psRule = psRule->psNext;
+
+
         }
 
-        return MS_SUCCESS;
+        psFeatureTypeStyle = psFeatureTypeStyle->psNext;
+      }
+    }
+  }
+  /* check for Named styles*/
+  else {
+    psNamedStyle = CPLGetXMLNode(psRoot, "NamedStyle");
+    if (psNamedStyle) {
+      psSLDName = CPLGetXMLNode(psNamedStyle, "Name");
+      if (psSLDName && psSLDName->psChild &&  psSLDName->psChild->pszValue) {
+        msFree(psLayer->classgroup);
+        psLayer->classgroup = msStrdup(psSLDName->psChild->pszValue);
+      }
+    }
+  }
+
+  return MS_SUCCESS;
 }
 
 
@@ -927,145 +907,135 @@ int msSLDParseNamedLayer(CPLXMLNode *psRoot, layerObj *psLayer)
 /************************************************************************/
 int msSLDParseRule(CPLXMLNode *psRoot, layerObj *psLayer)
 {
-    CPLXMLNode *psLineSymbolizer = NULL;
-    CPLXMLNode *psPolygonSymbolizer = NULL;
-    CPLXMLNode *psPointSymbolizer = NULL;
-    CPLXMLNode *psTextSymbolizer = NULL;
-    CPLXMLNode *psRasterSymbolizer = NULL;
-
-    int bSymbolizer = 0;
-    int bNewClass=0, nSymbolizer=0;
-
-    if (!psRoot || !psLayer)
-        return MS_FAILURE;
-
-        /* TODO : parse name of the rule */
-/* -------------------------------------------------------------------- */
-/*      The SLD specs assumes here that a certain FeatureType can only have*/
-/*      rules for only one type of symbolizer.                          */
-/* -------------------------------------------------------------------- */
-/* ==================================================================== */
-/*      For each rule a new class is created. If there are more than    */
-/*      one symbolizer of the same type, a style is added in the        */
-/*      same class.                                                     */
-/* ==================================================================== */
-        nSymbolizer =0;
- 
-        /* line symbolizer */
-        psLineSymbolizer = CPLGetXMLNode(psRoot, "LineSymbolizer");
-        while (psLineSymbolizer)
-        {
-            if (!psLineSymbolizer->pszValue || 
-                strcasecmp(psLineSymbolizer->pszValue, 
-                           "LineSymbolizer") != 0)
-            {
-                psLineSymbolizer = psLineSymbolizer->psNext;
-                continue;
-            }
+  CPLXMLNode *psLineSymbolizer = NULL;
+  CPLXMLNode *psPolygonSymbolizer = NULL;
+  CPLXMLNode *psPointSymbolizer = NULL;
+  CPLXMLNode *psTextSymbolizer = NULL;
+  CPLXMLNode *psRasterSymbolizer = NULL;
 
-            bSymbolizer = 1;
-            if (nSymbolizer == 0)
-              bNewClass = 1;
-            else
-              bNewClass = 0;
+  int bSymbolizer = 0;
+  int bNewClass=0, nSymbolizer=0;
 
-            msSLDParseLineSymbolizer(psLineSymbolizer, psLayer, bNewClass);
-            psLineSymbolizer = psLineSymbolizer->psNext;
-            psLayer->type = MS_LAYER_LINE;
-            nSymbolizer++;
-        }
+  if (!psRoot || !psLayer)
+    return MS_FAILURE;
 
-        /* Polygon symbolizer */
-        psPolygonSymbolizer = CPLGetXMLNode(psRoot, "PolygonSymbolizer");
-        while (psPolygonSymbolizer)        
-        {
-            if (!psPolygonSymbolizer->pszValue || 
-                strcasecmp(psPolygonSymbolizer->pszValue, 
-                           "PolygonSymbolizer") != 0)
-            {
-                psPolygonSymbolizer = psPolygonSymbolizer->psNext;
-                continue;
-            }
-            bSymbolizer = 1;
-            if (nSymbolizer == 0)
-              bNewClass = 1;
-            else
-              bNewClass = 0;
-            msSLDParsePolygonSymbolizer(psPolygonSymbolizer, psLayer,
-                                        bNewClass);
-            psPolygonSymbolizer = psPolygonSymbolizer->psNext;
-            psLayer->type = MS_LAYER_POLYGON;
-            nSymbolizer++;
-        }
-        /* Point Symbolizer */
-        psPointSymbolizer = CPLGetXMLNode(psRoot, "PointSymbolizer");
-        while (psPointSymbolizer)
-        {
-            if (!psPointSymbolizer->pszValue || 
-                strcasecmp(psPointSymbolizer->pszValue, 
-                           "PointSymbolizer") != 0)
-            {
-                psPointSymbolizer = psPointSymbolizer->psNext;
-                continue;
-            }
-            bSymbolizer = 1;
-            if (nSymbolizer == 0)
-              bNewClass = 1;
-            else
-              bNewClass = 0;
-            msSLDParsePointSymbolizer(psPointSymbolizer, psLayer, bNewClass);
-            psPointSymbolizer = psPointSymbolizer->psNext;
-            psLayer->type = MS_LAYER_POINT;
-            nSymbolizer++;
-        }
-        /* Text symbolizer */
-/* ==================================================================== */
-/*      For text symbolizer, here is how it is translated into          */
-/*      mapserver classes :                                             */
-/*        - If there are other symbolizers(line, polygon, symbol),      */
-/*      the label object created will be created in the same class      */
-/*      (the last class) as the  symbolizer. This allows o have for     */
-/*      example of point layer with labels.                             */
-/*        - If there are no other symbolizers, a new clas will be       */
-/*      created ocontain the label object.                              */
-/* ==================================================================== */
-        psTextSymbolizer = CPLGetXMLNode(psRoot, "TextSymbolizer");
-        while (psTextSymbolizer && psTextSymbolizer->pszValue && 
-               strcasecmp(psTextSymbolizer->pszValue, 
-                          "TextSymbolizer") == 0)
-        {
-            if (!psTextSymbolizer->pszValue || 
-                strcasecmp(psTextSymbolizer->pszValue, 
-                           "TextSymbolizer") != 0)
-            {
-                psTextSymbolizer = psTextSymbolizer->psNext;
-                continue;
-            }
-            if (nSymbolizer == 0)
-                psLayer->type = MS_LAYER_ANNOTATION;
-            msSLDParseTextSymbolizer(psTextSymbolizer, psLayer, bSymbolizer);
-            psTextSymbolizer = psTextSymbolizer->psNext;
-        }
+  /* TODO : parse name of the rule */
+  /* -------------------------------------------------------------------- */
+  /*      The SLD specs assumes here that a certain FeatureType can only have*/
+  /*      rules for only one type of symbolizer.                          */
+  /* -------------------------------------------------------------------- */
+  /* ==================================================================== */
+  /*      For each rule a new class is created. If there are more than    */
+  /*      one symbolizer of the same type, a style is added in the        */
+  /*      same class.                                                     */
+  /* ==================================================================== */
+  nSymbolizer =0;
+
+  /* line symbolizer */
+  psLineSymbolizer = CPLGetXMLNode(psRoot, "LineSymbolizer");
+  while (psLineSymbolizer) {
+    if (!psLineSymbolizer->pszValue ||
+        strcasecmp(psLineSymbolizer->pszValue,
+                   "LineSymbolizer") != 0) {
+      psLineSymbolizer = psLineSymbolizer->psNext;
+      continue;
+    }
 
-        /* Raster symbolizer */
-        psRasterSymbolizer = CPLGetXMLNode(psRoot, "RasterSymbolizer");
-        while (psRasterSymbolizer && psRasterSymbolizer->pszValue && 
-               strcasecmp(psRasterSymbolizer->pszValue, 
-                          "RasterSymbolizer") == 0)
-        {
-            if (!psRasterSymbolizer->pszValue || 
-                strcasecmp(psRasterSymbolizer->pszValue, 
-                           "RasterSymbolizer") != 0)
-            {
-                psRasterSymbolizer = psRasterSymbolizer->psNext;
-                continue;
-            }
-            msSLDParseRasterSymbolizer(psRasterSymbolizer, psLayer);
-            psRasterSymbolizer = psRasterSymbolizer->psNext;
-            psLayer->type = MS_LAYER_RASTER;
-        } 
+    bSymbolizer = 1;
+    if (nSymbolizer == 0)
+      bNewClass = 1;
+    else
+      bNewClass = 0;
+
+    msSLDParseLineSymbolizer(psLineSymbolizer, psLayer, bNewClass);
+    psLineSymbolizer = psLineSymbolizer->psNext;
+    psLayer->type = MS_LAYER_LINE;
+    nSymbolizer++;
+  }
+
+  /* Polygon symbolizer */
+  psPolygonSymbolizer = CPLGetXMLNode(psRoot, "PolygonSymbolizer");
+  while (psPolygonSymbolizer) {
+    if (!psPolygonSymbolizer->pszValue ||
+        strcasecmp(psPolygonSymbolizer->pszValue,
+                   "PolygonSymbolizer") != 0) {
+      psPolygonSymbolizer = psPolygonSymbolizer->psNext;
+      continue;
+    }
+    bSymbolizer = 1;
+    if (nSymbolizer == 0)
+      bNewClass = 1;
+    else
+      bNewClass = 0;
+    msSLDParsePolygonSymbolizer(psPolygonSymbolizer, psLayer,
+                                bNewClass);
+    psPolygonSymbolizer = psPolygonSymbolizer->psNext;
+    psLayer->type = MS_LAYER_POLYGON;
+    nSymbolizer++;
+  }
+  /* Point Symbolizer */
+  psPointSymbolizer = CPLGetXMLNode(psRoot, "PointSymbolizer");
+  while (psPointSymbolizer) {
+    if (!psPointSymbolizer->pszValue ||
+        strcasecmp(psPointSymbolizer->pszValue,
+                   "PointSymbolizer") != 0) {
+      psPointSymbolizer = psPointSymbolizer->psNext;
+      continue;
+    }
+    bSymbolizer = 1;
+    if (nSymbolizer == 0)
+      bNewClass = 1;
+    else
+      bNewClass = 0;
+    msSLDParsePointSymbolizer(psPointSymbolizer, psLayer, bNewClass);
+    psPointSymbolizer = psPointSymbolizer->psNext;
+    psLayer->type = MS_LAYER_POINT;
+    nSymbolizer++;
+  }
+  /* Text symbolizer */
+  /* ==================================================================== */
+  /*      For text symbolizer, here is how it is translated into          */
+  /*      mapserver classes :                                             */
+  /*        - If there are other symbolizers(line, polygon, symbol),      */
+  /*      the label object created will be created in the same class      */
+  /*      (the last class) as the  symbolizer. This allows o have for     */
+  /*      example of point layer with labels.                             */
+  /*        - If there are no other symbolizers, a new clas will be       */
+  /*      created ocontain the label object.                              */
+  /* ==================================================================== */
+  psTextSymbolizer = CPLGetXMLNode(psRoot, "TextSymbolizer");
+  while (psTextSymbolizer && psTextSymbolizer->pszValue &&
+         strcasecmp(psTextSymbolizer->pszValue,
+                    "TextSymbolizer") == 0) {
+    if (!psTextSymbolizer->pszValue ||
+        strcasecmp(psTextSymbolizer->pszValue,
+                   "TextSymbolizer") != 0) {
+      psTextSymbolizer = psTextSymbolizer->psNext;
+      continue;
+    }
+    if (nSymbolizer == 0)
+      psLayer->type = MS_LAYER_ANNOTATION;
+    msSLDParseTextSymbolizer(psTextSymbolizer, psLayer, bSymbolizer);
+    psTextSymbolizer = psTextSymbolizer->psNext;
+  }
+
+  /* Raster symbolizer */
+  psRasterSymbolizer = CPLGetXMLNode(psRoot, "RasterSymbolizer");
+  while (psRasterSymbolizer && psRasterSymbolizer->pszValue &&
+         strcasecmp(psRasterSymbolizer->pszValue,
+                    "RasterSymbolizer") == 0) {
+    if (!psRasterSymbolizer->pszValue ||
+        strcasecmp(psRasterSymbolizer->pszValue,
+                   "RasterSymbolizer") != 0) {
+      psRasterSymbolizer = psRasterSymbolizer->psNext;
+      continue;
+    }
+    msSLDParseRasterSymbolizer(psRasterSymbolizer, psLayer);
+    psRasterSymbolizer = psRasterSymbolizer->psNext;
+    psLayer->type = MS_LAYER_RASTER;
+  }
 
-        return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 
@@ -1115,45 +1085,41 @@ int msSLDParseRule(CPLXMLNode *psRoot, layerObj *psLayer)
 /*       ...                                                            */
 /************************************************************************/
 int msSLDParseLineSymbolizer(CPLXMLNode *psRoot, layerObj *psLayer,
-                              int bNewClass)
+                             int bNewClass)
 {
-    int nClassId = 0;
-    CPLXMLNode *psStroke=NULL, *psOffset=NULL;
-    int iStyle = 0;
-
-    if (!psRoot || !psLayer)
-        return MS_FAILURE;
+  int nClassId = 0;
+  CPLXMLNode *psStroke=NULL, *psOffset=NULL;
+  int iStyle = 0;
 
-        psStroke =  CPLGetXMLNode(psRoot, "Stroke");
-        if (psStroke)
-        {
-            if (bNewClass || psLayer->numclasses <= 0)
-            {
-        	if (msGrowLayerClasses(psLayer) == NULL)
-                    return MS_FAILURE;
-                initClass(psLayer->class[psLayer->numclasses]);
-                nClassId = psLayer->numclasses;
-                psLayer->numclasses++;
-            }
-            else
-              nClassId = psLayer->numclasses-1;
+  if (!psRoot || !psLayer)
+    return MS_FAILURE;
 
-            iStyle = psLayer->class[nClassId]->numstyles;
-	    msMaybeAllocateClassStyle(psLayer->class[nClassId], iStyle);
-            
-            msSLDParseStroke(psStroke, psLayer->class[nClassId]->styles[iStyle],
-                             psLayer->map, 0); 
-
-            /*parse PerpendicularOffset SLD 1.1.10*/
-            psOffset = CPLGetXMLNode(psRoot, "PerpendicularOffset");
-            if (psOffset && psOffset->psChild && psOffset->psChild->pszValue)
-            {
-              psLayer->class[nClassId]->styles[iStyle]->offsetx = atoi(psOffset->psChild->pszValue);
-              psLayer->class[nClassId]->styles[iStyle]->offsety = psLayer->class[nClassId]->styles[iStyle]->offsetx;
-            }
-        }
+  psStroke =  CPLGetXMLNode(psRoot, "Stroke");
+  if (psStroke) {
+    if (bNewClass || psLayer->numclasses <= 0) {
+      if (msGrowLayerClasses(psLayer) == NULL)
+        return MS_FAILURE;
+      initClass(psLayer->class[psLayer->numclasses]);
+      nClassId = psLayer->numclasses;
+      psLayer->numclasses++;
+    } else
+      nClassId = psLayer->numclasses-1;
+
+    iStyle = psLayer->class[nClassId]->numstyles;
+    msMaybeAllocateClassStyle(psLayer->class[nClassId], iStyle);
+
+    msSLDParseStroke(psStroke, psLayer->class[nClassId]->styles[iStyle],
+                     psLayer->map, 0);
+
+    /*parse PerpendicularOffset SLD 1.1.10*/
+    psOffset = CPLGetXMLNode(psRoot, "PerpendicularOffset");
+    if (psOffset && psOffset->psChild && psOffset->psChild->pszValue) {
+      psLayer->class[nClassId]->styles[iStyle]->offsetx = atoi(psOffset->psChild->pszValue);
+      psLayer->class[nClassId]->styles[iStyle]->offsety = psLayer->class[nClassId]->styles[iStyle]->offsetx;
+    }
+  }
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 
@@ -1167,132 +1133,116 @@ int msSLDParseLineSymbolizer(CPLXMLNode *psRoot, layerObj *psLayer,
 /*      :                                                               */
 /*        0 : for color                                                 */
 /*        1 : outlinecolor                                              */
-/*        2 : backgroundcolor                                           */
 /************************************************************************/
 int msSLDParseStroke(CPLXMLNode *psStroke, styleObj *psStyle,
                      mapObj *map, int iColorParam)
 {
-    CPLXMLNode *psCssParam = NULL, *psGraphicFill=NULL;
-    char *psStrkName = NULL;
-    char *psColor = NULL;
-    int nLength = 0;
-    char *pszDashValue = NULL;
-
-    if (!psStroke || !psStyle)
-        return MS_FAILURE;
+  CPLXMLNode *psCssParam = NULL, *psGraphicFill=NULL;
+  char *psStrkName = NULL;
+  char *psColor = NULL;
+  int nLength = 0;
+  char *pszDashValue = NULL;
 
-        /* parse css parameters */
-        psCssParam =  CPLGetXMLNode(psStroke, "CssParameter");
-        /*sld 1.1 used SvgParameter*/ 
-        if (psCssParam == NULL)
-          psCssParam =  CPLGetXMLNode(psStroke, "SvgParameter");
+  if (!psStroke || !psStyle)
+    return MS_FAILURE;
 
-        while (psCssParam && psCssParam->pszValue && 
-               (strcasecmp(psCssParam->pszValue, "CssParameter") == 0 ||
-                strcasecmp(psCssParam->pszValue, "SvgParameter") == 0))
-        {
-            psStrkName = (char*)CPLGetXMLValue(psCssParam, "name", NULL);
-
-            if (psStrkName)
-            {
-                if (strcasecmp(psStrkName, "stroke") == 0)
-                {
-                    if(psCssParam->psChild && psCssParam->psChild->psNext && 
-                       psCssParam->psChild->psNext->pszValue)
-                      psColor = psCssParam->psChild->psNext->pszValue;
-
-                    if (psColor)
-                    {
-                        nLength = strlen(psColor);
-                        /* expecting hexadecimal ex : #aaaaff */
-                        if (nLength == 7 && psColor[0] == '#')
-                        {
-                            if (iColorParam == 0)
-                            {
-                                psStyle->color.red = msHexToInt(psColor+1);
-                                psStyle->color.green = msHexToInt(psColor+3);
-                                psStyle->color.blue= msHexToInt(psColor+5);
-                            }
-                            else if (iColorParam == 1)
-                            {
-                                psStyle->outlinecolor.red = msHexToInt(psColor+1);
-                                psStyle->outlinecolor.green = msHexToInt(psColor+3);
-                                psStyle->outlinecolor.blue= msHexToInt(psColor+5);
-                            }
-                            else if (iColorParam == 2)
-                            {
-                                psStyle->backgroundcolor.red = msHexToInt(psColor+1);
-                                psStyle->backgroundcolor.green = msHexToInt(psColor+3);
-                                psStyle->backgroundcolor.blue= msHexToInt(psColor+5);
-                            }
-                        }
-                    }
-                }
-                else if (strcasecmp(psStrkName, "stroke-width") == 0)
-                {
-                    if(psCssParam->psChild &&  psCssParam->psChild->psNext && 
-                       psCssParam->psChild->psNext->pszValue)
-                    {
-                        psStyle->width = 
-                          atof(psCssParam->psChild->psNext->pszValue);
-                    }
-                }
-                else if (strcasecmp(psStrkName, "stroke-dasharray") == 0)
-                {
-                    if(psCssParam->psChild && psCssParam->psChild->psNext &&
-                       psCssParam->psChild->psNext->pszValue)
-                    {
-                       int nDash = 0, i;
-                       char **aszValues = NULL;
-                       int nMaxDash;
-                       pszDashValue = 
-                          msStrdup(psCssParam->psChild->psNext->pszValue);
-                       aszValues = msStringSplit(pszDashValue, ' ', &nDash);
-                       if (nDash > 0)
-                       {
-                           nMaxDash = nDash;
-                           if (nDash > MS_MAXPATTERNLENGTH)
-                             nMaxDash =  MS_MAXPATTERNLENGTH;
-
-                           psStyle->patternlength = nMaxDash;
-                           for (i=0; i<nMaxDash; i++)
-                              psStyle->pattern[i] = atof(aszValues[i]);
-
-                           msFreeCharArray(aszValues, nDash);
-                           psStyle->linecap = MS_CJC_BUTT;
-                       }
-                        
-                    }
-                }
-                else if (strcasecmp(psStrkName, "stroke-opacity") == 0)
-                {
-                    if(psCssParam->psChild &&  psCssParam->psChild->psNext && 
-                       psCssParam->psChild->psNext->pszValue)
-                    {
-                        psStyle->color.alpha = 
-                           (int)(atof(psCssParam->psChild->psNext->pszValue)*255);
-                    }
-                }
+  /* parse css parameters */
+  psCssParam =  CPLGetXMLNode(psStroke, "CssParameter");
+  /*sld 1.1 used SvgParameter*/
+  if (psCssParam == NULL)
+    psCssParam =  CPLGetXMLNode(psStroke, "SvgParameter");
+
+  while (psCssParam && psCssParam->pszValue &&
+         (strcasecmp(psCssParam->pszValue, "CssParameter") == 0 ||
+          strcasecmp(psCssParam->pszValue, "SvgParameter") == 0)) {
+    psStrkName = (char*)CPLGetXMLValue(psCssParam, "name", NULL);
+
+    if (psStrkName) {
+      if (strcasecmp(psStrkName, "stroke") == 0) {
+        if(psCssParam->psChild && psCssParam->psChild->psNext &&
+            psCssParam->psChild->psNext->pszValue)
+          psColor = psCssParam->psChild->psNext->pszValue;
+
+        if (psColor) {
+          nLength = strlen(psColor);
+          /* expecting hexadecimal ex : #aaaaff */
+          if (nLength == 7 && psColor[0] == '#') {
+            if (iColorParam == 0) {
+              psStyle->color.red = msHexToInt(psColor+1);
+              psStyle->color.green = msHexToInt(psColor+3);
+              psStyle->color.blue= msHexToInt(psColor+5);
+            } else if (iColorParam == 1) {
+              psStyle->outlinecolor.red = msHexToInt(psColor+1);
+              psStyle->outlinecolor.green = msHexToInt(psColor+3);
+              psStyle->outlinecolor.blue= msHexToInt(psColor+5);
+            } else if (iColorParam == 2) {
+              psStyle->backgroundcolor.red = msHexToInt(psColor+1);
+              psStyle->backgroundcolor.green = msHexToInt(psColor+3);
+              psStyle->backgroundcolor.blue= msHexToInt(psColor+5);
             }
-            psCssParam = psCssParam->psNext;
+          }
+        }
+      } else if (strcasecmp(psStrkName, "stroke-width") == 0) {
+        if(psCssParam->psChild &&  psCssParam->psChild->psNext &&
+            psCssParam->psChild->psNext->pszValue) {
+          psStyle->width =
+            atof(psCssParam->psChild->psNext->pszValue);
         }
+      } else if (strcasecmp(psStrkName, "stroke-dasharray") == 0) {
+        if(psCssParam->psChild && psCssParam->psChild->psNext &&
+            psCssParam->psChild->psNext->pszValue) {
+          int nDash = 0, i;
+          char **aszValues = NULL;
+          int nMaxDash;
+          pszDashValue =
+            msStrdup(psCssParam->psChild->psNext->pszValue);
+          aszValues = msStringSplit(pszDashValue, ' ', &nDash);
+          if (nDash > 0) {
+            nMaxDash = nDash;
+            if (nDash > MS_MAXPATTERNLENGTH)
+              nMaxDash =  MS_MAXPATTERNLENGTH;
+
+            psStyle->patternlength = nMaxDash;
+            for (i=0; i<nMaxDash; i++)
+              psStyle->pattern[i] = atof(aszValues[i]);
+
+            msFreeCharArray(aszValues, nDash);
+            psStyle->linecap = MS_CJC_BUTT;
+          }
 
-        /* parse graphic fill or stroke */
-        /* graphic fill and graphic stroke pare parsed the same way :  */
-        /* TODO : It seems inconsistent to me since the only diffrence */
-        /* between them seems to be fill (fill) or not fill (stroke). And */
-        /* then again the fill parameter can be used inside both elements. */
-        psGraphicFill =  CPLGetXMLNode(psStroke, "GraphicFill");
-        if (psGraphicFill)
-          msSLDParseGraphicFillOrStroke(psGraphicFill, pszDashValue, psStyle, map, 0);
-        psGraphicFill =  CPLGetXMLNode(psStroke, "GraphicStroke");
-        if (psGraphicFill)
-          msSLDParseGraphicFillOrStroke(psGraphicFill, pszDashValue, psStyle, map, 0);
-
-        if (pszDashValue)
-          free(pszDashValue);
-
-        return MS_SUCCESS;
+        }
+      } else if (strcasecmp(psStrkName, "stroke-opacity") == 0) {
+        if(psCssParam->psChild &&  psCssParam->psChild->psNext &&
+            psCssParam->psChild->psNext->pszValue) {
+          if (iColorParam == 0) {
+            psStyle->color.alpha =
+              (int)(atof(psCssParam->psChild->psNext->pszValue)*255);
+          } else {
+            psStyle->outlinecolor.alpha =
+              (int)(atof(psCssParam->psChild->psNext->pszValue)*255);
+          }
+        }
+      }
+    }
+    psCssParam = psCssParam->psNext;
+  }
+
+  /* parse graphic fill or stroke */
+  /* graphic fill and graphic stroke pare parsed the same way :  */
+  /* TODO : It seems inconsistent to me since the only diffrence */
+  /* between them seems to be fill (fill) or not fill (stroke). And */
+  /* then again the fill parameter can be used inside both elements. */
+  psGraphicFill =  CPLGetXMLNode(psStroke, "GraphicFill");
+  if (psGraphicFill)
+    msSLDParseGraphicFillOrStroke(psGraphicFill, pszDashValue, psStyle, map, 0);
+  psGraphicFill =  CPLGetXMLNode(psStroke, "GraphicStroke");
+  if (psGraphicFill)
+    msSLDParseGraphicFillOrStroke(psGraphicFill, pszDashValue, psStyle, map, 0);
+
+  if (pszDashValue)
+    free(pszDashValue);
+
+  return MS_SUCCESS;
 }
 
 
@@ -1373,109 +1323,96 @@ int msSLDParseStroke(CPLXMLNode *psStroke, styleObj *psStyle,
 /*      marks may be made solid or hollow depending on Fill and Stroke elements.*/
 /*                                                                      */
 /************************************************************************/
-int msSLDParsePolygonSymbolizer(CPLXMLNode *psRoot, layerObj *psLayer, 
-                                 int bNewClass)
+int msSLDParsePolygonSymbolizer(CPLXMLNode *psRoot, layerObj *psLayer,
+                                int bNewClass)
 {
-    CPLXMLNode *psFill, *psStroke;
-    int nClassId=0, iStyle=0;
-    CPLXMLNode *psDisplacement=NULL, *psDisplacementX=NULL, *psDisplacementY=NULL;
-    int nOffsetX=-1, nOffsetY=-1;
+  CPLXMLNode *psFill, *psStroke;
+  int nClassId=0, iStyle=0;
+  CPLXMLNode *psDisplacement=NULL, *psDisplacementX=NULL, *psDisplacementY=NULL;
+  int nOffsetX=-1, nOffsetY=-1;
+
+  if (!psRoot || !psLayer)
+    return MS_FAILURE;
+
+  /*parse displacement for SLD 1.1.0*/
+  psDisplacement = CPLGetXMLNode(psRoot, "Displacement");
+  if (psDisplacement) {
+    psDisplacementX = CPLGetXMLNode(psDisplacement, "DisplacementX");
+    psDisplacementY = CPLGetXMLNode(psDisplacement, "DisplacementY");
+    /* psCssParam->psChild->psNext->pszValue) */
+    if (psDisplacementX &&
+        psDisplacementX->psChild &&
+        psDisplacementX->psChild->pszValue &&
+        psDisplacementY &&
+        psDisplacementY->psChild &&
+        psDisplacementY->psChild->pszValue) {
+      nOffsetX = atoi(psDisplacementX->psChild->pszValue);
+      nOffsetY = atoi(psDisplacementY->psChild->pszValue);
+    }
+  }
 
-    if (!psRoot || !psLayer)
+  psFill =  CPLGetXMLNode(psRoot, "Fill");
+  if (psFill) {
+    if (bNewClass || psLayer->numclasses <= 0) {
+      if (msGrowLayerClasses(psLayer) == NULL)
         return MS_FAILURE;
+      initClass(psLayer->class[psLayer->numclasses]);
+      nClassId = psLayer->numclasses;
+      psLayer->numclasses++;
+    } else
+      nClassId = psLayer->numclasses-1;
 
-        /*parse displacement for SLD 1.1.0*/
-        psDisplacement = CPLGetXMLNode(psRoot, "Displacement");
-        if (psDisplacement)
-        {
-            psDisplacementX = CPLGetXMLNode(psDisplacement, "DisplacementX");
-            psDisplacementY = CPLGetXMLNode(psDisplacement, "DisplacementY");
-            /* psCssParam->psChild->psNext->pszValue) */
-            if (psDisplacementX &&
-                psDisplacementX->psChild && 
-                psDisplacementX->psChild->pszValue &&
-                psDisplacementY && 
-                psDisplacementY->psChild && 
-                psDisplacementY->psChild->pszValue)
-            {
-                nOffsetX = atoi(psDisplacementX->psChild->pszValue);
-                nOffsetY = atoi(psDisplacementY->psChild->pszValue);
-            }
-        }
-            
-        psFill =  CPLGetXMLNode(psRoot, "Fill");
-        if (psFill)
-        {
-            if (bNewClass || psLayer->numclasses <= 0)
-            {
-        	if (msGrowLayerClasses(psLayer) == NULL)
-                    return MS_FAILURE;
-                initClass(psLayer->class[psLayer->numclasses]);
-                nClassId = psLayer->numclasses;
-                psLayer->numclasses++;
-            }
-            else
-               nClassId = psLayer->numclasses-1;
-
-            iStyle = psLayer->class[nClassId]->numstyles;
-  	    msMaybeAllocateClassStyle(psLayer->class[nClassId], iStyle);
-            
-            msSLDParsePolygonFill(psFill, psLayer->class[nClassId]->styles[iStyle],
-                                  psLayer->map);
-            
-            if (nOffsetX > 0 && nOffsetY > 0)
-            {
-                psLayer->class[nClassId]->styles[iStyle]->offsetx = nOffsetX;   
-                psLayer->class[nClassId]->styles[iStyle]->offsety = nOffsetY;  
-            }
-        }
-        /* stroke wich corresponds to the outilne in mapserver */
-        /* is drawn after the fill */
-        psStroke =  CPLGetXMLNode(psRoot, "Stroke");
-        if (psStroke)
-        {
-/* -------------------------------------------------------------------- */
-/*      there was a fill so add a style to the last class created       */
-/*      by the fill                                                     */
-/* -------------------------------------------------------------------- */
-            if (psFill && psLayer->numclasses > 0) 
-            {
-                nClassId =psLayer->numclasses-1;
-                iStyle = psLayer->class[nClassId]->numstyles;
-	 	msMaybeAllocateClassStyle(psLayer->class[nClassId], iStyle);
-            }
-            else
-            {
-                if (bNewClass || psLayer->numclasses <= 0)
-                {
-        	    if (msGrowLayerClasses(psLayer) == NULL)
-                        return MS_FAILURE;
-                    initClass(psLayer->class[psLayer->numclasses]);
-                    nClassId = psLayer->numclasses;
-                    psLayer->numclasses++;
-                }
-                else
-                  nClassId = psLayer->numclasses-1;
+    iStyle = psLayer->class[nClassId]->numstyles;
+    msMaybeAllocateClassStyle(psLayer->class[nClassId], iStyle);
 
-                iStyle = psLayer->class[nClassId]->numstyles;
-		msMaybeAllocateClassStyle(psLayer->class[nClassId], iStyle);
-                
-            }
-            msSLDParseStroke(psStroke, psLayer->class[nClassId]->styles[iStyle],
-                             psLayer->map, 1);
+    msSLDParsePolygonFill(psFill, psLayer->class[nClassId]->styles[iStyle],
+                          psLayer->map);
 
-            if (nOffsetX > 0 && nOffsetY > 0)
-            {
-                psLayer->class[nClassId]->styles[iStyle]->offsetx = nOffsetX;   
-                psLayer->class[nClassId]->styles[iStyle]->offsety = nOffsetY;  
-            }
-        }
+    if (nOffsetX > 0 && nOffsetY > 0) {
+      psLayer->class[nClassId]->styles[iStyle]->offsetx = nOffsetX;
+      psLayer->class[nClassId]->styles[iStyle]->offsety = nOffsetY;
+    }
+  }
+  /* stroke wich corresponds to the outilne in mapserver */
+  /* is drawn after the fill */
+  psStroke =  CPLGetXMLNode(psRoot, "Stroke");
+  if (psStroke) {
+    /* -------------------------------------------------------------------- */
+    /*      there was a fill so add a style to the last class created       */
+    /*      by the fill                                                     */
+    /* -------------------------------------------------------------------- */
+    if (psFill && psLayer->numclasses > 0) {
+      nClassId =psLayer->numclasses-1;
+      iStyle = psLayer->class[nClassId]->numstyles;
+      msMaybeAllocateClassStyle(psLayer->class[nClassId], iStyle);
+    } else {
+      if (bNewClass || psLayer->numclasses <= 0) {
+        if (msGrowLayerClasses(psLayer) == NULL)
+          return MS_FAILURE;
+        initClass(psLayer->class[psLayer->numclasses]);
+        nClassId = psLayer->numclasses;
+        psLayer->numclasses++;
+      } else
+        nClassId = psLayer->numclasses-1;
+
+      iStyle = psLayer->class[nClassId]->numstyles;
+      msMaybeAllocateClassStyle(psLayer->class[nClassId], iStyle);
 
-        return MS_SUCCESS;
-}
-  
+    }
+    msSLDParseStroke(psStroke, psLayer->class[nClassId]->styles[iStyle],
+                     psLayer->map, 1);
 
-/************************************************************************/
+    if (nOffsetX > 0 && nOffsetY > 0) {
+      psLayer->class[nClassId]->styles[iStyle]->offsetx = nOffsetX;
+      psLayer->class[nClassId]->styles[iStyle]->offsety = nOffsetY;
+    }
+  }
+
+  return MS_SUCCESS;
+}
+
+
+/************************************************************************/
 /*    void msSLDParsePolygonFill(CPLXMLNode *psFill, styleObj *psStyle, */
 /*                                 mapObj *map)                         */
 /*                                                                      */
@@ -1484,73 +1421,65 @@ int msSLDParsePolygonSymbolizer(CPLXMLNode *psRoot, layerObj *psLayer,
 int msSLDParsePolygonFill(CPLXMLNode *psFill, styleObj *psStyle,
                           mapObj *map)
 {
-    CPLXMLNode *psCssParam, *psGraphicFill;
-    char *psColor=NULL, *psFillName=NULL;
-    int nLength = 0;
-
-    if (!psFill || !psStyle || !map)
-        return MS_FAILURE;
+  CPLXMLNode *psCssParam, *psGraphicFill;
+  char *psColor=NULL, *psFillName=NULL;
+  int nLength = 0;
 
-        /* sets the default fill color defined in the spec #808080 */
-        psStyle->color.red = 128;
-        psStyle->color.green = 128;
-        psStyle->color.blue = 128;
-
-        psCssParam =  CPLGetXMLNode(psFill, "CssParameter");
-        /*sld 1.1 used SvgParameter*/ 
-        if (psCssParam == NULL)
-          psCssParam =  CPLGetXMLNode(psFill, "SvgParameter");
+  if (!psFill || !psStyle || !map)
+    return MS_FAILURE;
 
-        while (psCssParam && psCssParam->pszValue && 
-               (strcasecmp(psCssParam->pszValue, "CssParameter") == 0 ||
-                strcasecmp(psCssParam->pszValue, "SvgParameter") == 0))
-        {
-            psFillName = (char*)CPLGetXMLValue(psCssParam, "name", NULL);
-            if (psFillName)
-            {
-                if (strcasecmp(psFillName, "fill") == 0)
-                {
-                    if(psCssParam->psChild && psCssParam->psChild->psNext && 
-                       psCssParam->psChild->psNext->pszValue)
-                      psColor = psCssParam->psChild->psNext->pszValue;
-
-                    if (psColor)
-                    {
-                        nLength = strlen(psColor);
-                        /* expecting hexadecimal ex : #aaaaff */
-                        if (nLength == 7 && psColor[0] == '#')
-                        {
-                            psStyle->color.red = msHexToInt(psColor+1);
-                            psStyle->color.green = msHexToInt(psColor+3);
-                            psStyle->color.blue= msHexToInt(psColor+5);
-                        }
-                    }
-                }
-                else if (strcasecmp(psFillName, "fill-opacity") == 0)
-                {
-                    if(psCssParam->psChild &&  psCssParam->psChild->psNext && 
-                       psCssParam->psChild->psNext->pszValue)
-                    {
-                        psStyle->color.alpha = (int)(atof(psCssParam->psChild->psNext->pszValue)*255);
-                    }
-                }
-            }
-            psCssParam = psCssParam->psNext;
+  /* sets the default fill color defined in the spec #808080 */
+  psStyle->color.red = 128;
+  psStyle->color.green = 128;
+  psStyle->color.blue = 128;
+
+  psCssParam =  CPLGetXMLNode(psFill, "CssParameter");
+  /*sld 1.1 used SvgParameter*/
+  if (psCssParam == NULL)
+    psCssParam =  CPLGetXMLNode(psFill, "SvgParameter");
+
+  while (psCssParam && psCssParam->pszValue &&
+         (strcasecmp(psCssParam->pszValue, "CssParameter") == 0 ||
+          strcasecmp(psCssParam->pszValue, "SvgParameter") == 0)) {
+    psFillName = (char*)CPLGetXMLValue(psCssParam, "name", NULL);
+    if (psFillName) {
+      if (strcasecmp(psFillName, "fill") == 0) {
+        if(psCssParam->psChild && psCssParam->psChild->psNext &&
+            psCssParam->psChild->psNext->pszValue)
+          psColor = psCssParam->psChild->psNext->pszValue;
+
+        if (psColor) {
+          nLength = strlen(psColor);
+          /* expecting hexadecimal ex : #aaaaff */
+          if (nLength == 7 && psColor[0] == '#') {
+            psStyle->color.red = msHexToInt(psColor+1);
+            psStyle->color.green = msHexToInt(psColor+3);
+            psStyle->color.blue= msHexToInt(psColor+5);
+          }
+        }
+      } else if (strcasecmp(psFillName, "fill-opacity") == 0) {
+        if(psCssParam->psChild &&  psCssParam->psChild->psNext &&
+            psCssParam->psChild->psNext->pszValue) {
+          psStyle->color.alpha = (int)(atof(psCssParam->psChild->psNext->pszValue)*255);
         }
-        
-        /* graphic fill and graphic stroke pare parsed the same way :  */
-        /* TODO : It seems inconsistent to me since the only diffrence */
-        /* between them seems to be fill (fill) or not fill (stroke). And */
-        /* then again the fill parameter can be used inside both elements. */
-        psGraphicFill =  CPLGetXMLNode(psFill, "GraphicFill");
-        if (psGraphicFill)
-          msSLDParseGraphicFillOrStroke(psGraphicFill, NULL, psStyle, map, 0);
-        psGraphicFill =  CPLGetXMLNode(psFill, "GraphicStroke");
-        if (psGraphicFill)
-          msSLDParseGraphicFillOrStroke(psGraphicFill, NULL, psStyle, map, 0);
-
-        
-        return MS_SUCCESS;
+      }
+    }
+    psCssParam = psCssParam->psNext;
+  }
+
+  /* graphic fill and graphic stroke pare parsed the same way :  */
+  /* TODO : It seems inconsistent to me since the only diffrence */
+  /* between them seems to be fill (fill) or not fill (stroke). And */
+  /* then again the fill parameter can be used inside both elements. */
+  psGraphicFill =  CPLGetXMLNode(psFill, "GraphicFill");
+  if (psGraphicFill)
+    msSLDParseGraphicFillOrStroke(psGraphicFill, NULL, psStyle, map, 0);
+  psGraphicFill =  CPLGetXMLNode(psFill, "GraphicStroke");
+  if (psGraphicFill)
+    msSLDParseGraphicFillOrStroke(psGraphicFill, NULL, psStyle, map, 0);
+
+
+  return MS_SUCCESS;
 }
 
 
@@ -1560,238 +1489,240 @@ int msSLDParsePolygonFill(CPLXMLNode *psFill, styleObj *psStyle,
 /*      Parse the GraphicFill Or GraphicStroke node : look for a        */
 /*      Marker symbol and set the style for that symbol.                */
 /************************************************************************/
-int msSLDParseGraphicFillOrStroke(CPLXMLNode *psRoot, 
-                                   char *pszDashValue,
-                                   styleObj *psStyle, mapObj *map,
-                                   int bPointLayer)
+int msSLDParseGraphicFillOrStroke(CPLXMLNode *psRoot,
+                                  char *pszDashValue,
+                                  styleObj *psStyle, mapObj *map,
+                                  int bPointLayer)
 {
-    CPLXMLNode  *psCssParam, *psGraphic, *psExternalGraphic, *psMark, *psSize;
-    CPLXMLNode *psWellKnownName, *psStroke, *psFill;
-    CPLXMLNode *psDisplacement=NULL, *psDisplacementX=NULL, *psDisplacementY=NULL;
-    CPLXMLNode *psOpacity=NULL, *psRotation=NULL;
-    char *psColor=NULL, *psColorName = NULL;
-    int nLength = 0;
-    char *pszSymbolName = NULL;
-    int bFilled = 0, bStroked=0;
-    CPLXMLNode *psPropertyName=NULL;
-    char szTmp[256];
-
-    bPointLayer=0;
-
-    if (!psRoot || !psStyle || !map)
-        return MS_FAILURE;
-/* ==================================================================== */
-/*      This a definition taken from the specification (11.3.2) :       */
-/*      Graphics can either be referenced from an external URL in a common format (such as*/
-/*      GIF or SVG) or may be derived from a Mark. Multiple external URLs and marks may be*/
-/*      referenced with the semantic that they all provide the equivalent graphic in different*/
-/*      formats.                                                        */
-/*                                                                      */
-/*      For this reason, we only need to support one Mark and one       */
-/*      ExtrnalGraphic ????                                             */
-/* ==================================================================== */
-        psGraphic =  CPLGetXMLNode(psRoot, "Graphic");
-        if (psGraphic)
-        {
-            /* extract symbol size */
-            psSize = CPLGetXMLNode(psGraphic, "Size");
-            if (psSize && psSize->psChild && psSize->psChild->pszValue)
-              psStyle->size = atof(psSize->psChild->pszValue);
-            else 
-            {
-                /*do not set a default for external symbols #2305*/
-                psExternalGraphic =  CPLGetXMLNode(psGraphic, "ExternalGraphic");
-                if (!psExternalGraphic)
-                  psStyle->size = 6; /* default value */
-            }
+  CPLXMLNode  *psCssParam, *psGraphic, *psExternalGraphic, *psMark, *psSize;
+  CPLXMLNode *psWellKnownName, *psStroke, *psFill;
+  CPLXMLNode *psDisplacement=NULL, *psDisplacementX=NULL, *psDisplacementY=NULL;
+  CPLXMLNode *psOpacity=NULL, *psRotation=NULL;
+  char *psName=NULL, *psValue = NULL;
+  int nLength = 0;
+  char *pszSymbolName = NULL;
+  int bFilled = 0;
+  CPLXMLNode *psPropertyName=NULL;
+  char szTmp[256];
+
+  bPointLayer=0;
+
+  if (!psRoot || !psStyle || !map)
+    return MS_FAILURE;
+  /* ==================================================================== */
+  /*      This a definition taken from the specification (11.3.2) :       */
+  /*      Graphics can either be referenced from an external URL in a common format (such as*/
+  /*      GIF or SVG) or may be derived from a Mark. Multiple external URLs and marks may be*/
+  /*      referenced with the semantic that they all provide the equivalent graphic in different*/
+  /*      formats.                                                        */
+  /*                                                                      */
+  /*      For this reason, we only need to support one Mark and one       */
+  /*      ExtrnalGraphic ????                                             */
+  /* ==================================================================== */
+  psGraphic =  CPLGetXMLNode(psRoot, "Graphic");
+  if (psGraphic) {
+    /* extract symbol size */
+    psSize = CPLGetXMLNode(psGraphic, "Size");
+    if (psSize)
+      psStyle->size = _msSLDParseSizeParameter(psSize);
+    else {
+      /*do not set a default for external symbols #2305*/
+      psExternalGraphic =  CPLGetXMLNode(psGraphic, "ExternalGraphic");
+      if (!psExternalGraphic)
+        psStyle->size = 6; /* default value */
+    }
 
-            /*SLD 1.1.0 extract opacity, rotation, displacement*/
-            psOpacity = CPLGetXMLNode(psGraphic, "Opacity");
-            if (psOpacity && psOpacity->psChild && psOpacity->psChild->pszValue)
-              psStyle->opacity = (int)(atof(psOpacity->psChild->pszValue) * 100);
-
-            psRotation = CPLGetXMLNode(psGraphic, "Rotation");
-            if (psRotation)
-            {
-                psPropertyName = CPLGetXMLNode(psRotation, "PropertyName");
-                if (psPropertyName)
-                {   
-                    snprintf(szTmp, sizeof(szTmp), "%s", CPLGetXMLValue(psPropertyName, NULL, NULL));
-                    psStyle->bindings[MS_STYLE_BINDING_ANGLE].item = msStrdup(szTmp);
-                    psStyle->numbindings++;
-                }
-                else
-                {
-                    if (psRotation->psChild && psRotation->psChild->pszValue)
-                      psStyle->angle = atof(psRotation->psChild->pszValue);
-                }
-            }
-            psDisplacement = CPLGetXMLNode(psGraphic, "Displacement");
-            if (psDisplacement)
-            {
-                psDisplacementX = CPLGetXMLNode(psDisplacement, "DisplacementX");
-                psDisplacementY = CPLGetXMLNode(psDisplacement, "DisplacementY");
-                /* psCssParam->psChild->psNext->pszValue) */
-                if (psDisplacementX &&
-                    psDisplacementX->psChild && 
-                    psDisplacementX->psChild->pszValue &&
-                    psDisplacementY && 
-                    psDisplacementY->psChild && 
-                    psDisplacementY->psChild->pszValue)
-                {
-                    psStyle->offsetx = atoi(psDisplacementX->psChild->pszValue);
-                    psStyle->offsety = atoi(psDisplacementY->psChild->pszValue);
+    /*SLD 1.1.0 extract opacity, rotation, displacement*/
+    psOpacity = CPLGetXMLNode(psGraphic, "Opacity");
+    if (psOpacity && psOpacity->psChild && psOpacity->psChild->pszValue)
+      psStyle->opacity = (int)(atof(psOpacity->psChild->pszValue) * 100);
+
+    psRotation = CPLGetXMLNode(psGraphic, "Rotation");
+    if (psRotation) {
+      psPropertyName = CPLGetXMLNode(psRotation, "PropertyName");
+      if (psPropertyName) {
+        snprintf(szTmp, sizeof(szTmp), "%s", CPLGetXMLValue(psPropertyName, NULL, NULL));
+        psStyle->bindings[MS_STYLE_BINDING_ANGLE].item = msStrdup(szTmp);
+        psStyle->numbindings++;
+      } else {
+        if (psRotation->psChild && psRotation->psChild->pszValue)
+          psStyle->angle = atof(psRotation->psChild->pszValue);
+      }
+    }
+    psDisplacement = CPLGetXMLNode(psGraphic, "Displacement");
+    if (psDisplacement) {
+      psDisplacementX = CPLGetXMLNode(psDisplacement, "DisplacementX");
+      psDisplacementY = CPLGetXMLNode(psDisplacement, "DisplacementY");
+      /* psCssParam->psChild->psNext->pszValue) */
+      if (psDisplacementX &&
+          psDisplacementX->psChild &&
+          psDisplacementX->psChild->pszValue &&
+          psDisplacementY &&
+          psDisplacementY->psChild &&
+          psDisplacementY->psChild->pszValue) {
+        psStyle->offsetx = atoi(psDisplacementX->psChild->pszValue);
+        psStyle->offsety = atoi(psDisplacementY->psChild->pszValue);
+      }
+    }
+    /* extract symbol */
+    psMark =  CPLGetXMLNode(psGraphic, "Mark");
+    if (psMark) {
+      pszSymbolName = NULL;
+      psWellKnownName =  CPLGetXMLNode(psMark, "WellKnownName");
+      if (psWellKnownName && psWellKnownName->psChild &&
+          psWellKnownName->psChild->pszValue)
+        pszSymbolName =
+          msStrdup(psWellKnownName->psChild->pszValue);
+
+      /* default symbol is square */
+
+      if (!pszSymbolName || !*pszSymbolName || 
+          (strcasecmp(pszSymbolName, "square") != 0 &&
+           strcasecmp(pszSymbolName, "circle") != 0 &&
+           strcasecmp(pszSymbolName, "triangle") != 0 &&
+           strcasecmp(pszSymbolName, "star") != 0 &&
+           strcasecmp(pszSymbolName, "cross") != 0 &&
+           strcasecmp(pszSymbolName, "x") != 0)) {
+        if (!pszSymbolName || !*pszSymbolName || msGetSymbolIndex(&map->symbolset, pszSymbolName,  MS_FALSE) < 0) {
+          msFree(pszSymbolName);
+          pszSymbolName = msStrdup("square");
+        }
+      }
+
+
+      /* check if the symbol should be filled or not */
+      psFill = CPLGetXMLNode(psMark, "Fill");
+      psStroke = CPLGetXMLNode(psMark, "Stroke");
+
+      if (psFill || psStroke) {
+        if (psFill)
+          bFilled = 1;
+        else
+          bFilled = 0;
+
+        if (psFill) {
+          psCssParam =  CPLGetXMLNode(psFill, "CssParameter");
+          /*sld 1.1 used SvgParameter*/
+          if (psCssParam == NULL)
+            psCssParam =  CPLGetXMLNode(psFill, "SvgParameter");
+
+          while (psCssParam && psCssParam->pszValue &&
+                 (strcasecmp(psCssParam->pszValue, "CssParameter") == 0 ||
+                  strcasecmp(psCssParam->pszValue, "SvgParameter") == 0)) {
+            psName =
+              (char*)CPLGetXMLValue(psCssParam, "name", NULL);
+            if (psName &&
+                strcasecmp(psName, "fill") == 0) {
+              if(psCssParam->psChild &&
+                  psCssParam->psChild->psNext &&
+                  psCssParam->psChild->psNext->pszValue)
+                psValue = psCssParam->psChild->psNext->pszValue;
+
+              if (psValue) {
+                nLength = strlen(psValue);
+                if (nLength == 7 && psValue[0] == '#') {
+                  msSLDSetColorObject(psValue,
+                                      &psStyle->color);
                 }
+              }
+            } else if (psName &&
+                       strcasecmp(psName, "fill-opacity") == 0) {
+              if(psCssParam->psChild &&
+                  psCssParam->psChild->psNext &&
+                  psCssParam->psChild->psNext->pszValue)
+                psValue = psCssParam->psChild->psNext->pszValue;
+
+              if (psValue) {
+                psStyle->color.alpha = (int)(atof(psValue)*255);
+              }
             }
-            /* extract symbol */
-            psMark =  CPLGetXMLNode(psGraphic, "Mark");
-            if (psMark)
-            {
-                pszSymbolName = NULL;
-                psWellKnownName =  CPLGetXMLNode(psMark, "WellKnownName");
-                if (psWellKnownName && psWellKnownName->psChild &&
-                    psWellKnownName->psChild->pszValue)
-                  pszSymbolName = 
-                    msStrdup(psWellKnownName->psChild->pszValue);
-                    
-                /* default symbol is square */
-                
-                if (!pszSymbolName || 
-                    (strcasecmp(pszSymbolName, "square") != 0 &&
-                     strcasecmp(pszSymbolName, "circle") != 0 &&
-                     strcasecmp(pszSymbolName, "triangle") != 0 &&
-                     strcasecmp(pszSymbolName, "star") != 0 &&
-                     strcasecmp(pszSymbolName, "cross") != 0 &&
-                     strcasecmp(pszSymbolName, "x") != 0))
-                {
-                    if (msGetSymbolIndex(&map->symbolset, pszSymbolName,  MS_FALSE) < 0)
-                      pszSymbolName = msStrdup("square");
-                }
-                
-                
-                /* check if the symbol should be filled or not */
-                psFill = CPLGetXMLNode(psMark, "Fill");
-                psStroke = CPLGetXMLNode(psMark, "Stroke");
-                    
-                if (psFill || psStroke)
-                {
-                    if (psFill)
-                      bFilled = 1;
-                    else
-                      bFilled = 0;
-
-                    if (psStroke)
-                      bStroked = 1;
-                    else
-                      bStroked = 0;
-
-                    if (psFill)
-                    {
-                        psCssParam =  CPLGetXMLNode(psFill, "CssParameter");
-                        /*sld 1.1 used SvgParameter*/ 
-                         if (psCssParam == NULL)
-                           psCssParam =  CPLGetXMLNode(psFill, "SvgParameter");
-
-                        while (psCssParam && psCssParam->pszValue && 
-                               (strcasecmp(psCssParam->pszValue, "CssParameter") == 0 ||
-                                strcasecmp(psCssParam->pszValue, "SvgParameter") == 0))
-                        {
-                            psColorName = 
-                              (char*)CPLGetXMLValue(psCssParam, "name", NULL);
-                            if (psColorName && 
-                                strcasecmp(psColorName, "fill") == 0)
-                            {
-                                if(psCssParam->psChild && 
-                                   psCssParam->psChild->psNext && 
-                                   psCssParam->psChild->psNext->pszValue)
-                                  psColor = psCssParam->psChild->psNext->pszValue;
-
-                                if (psColor)
-                                {
-                                    nLength = strlen(psColor);
-                                    if (nLength == 7 && psColor[0] == '#')
-                                    {
-                                        msSLDSetColorObject(psColor,
-                                                            &psStyle->color);
-                                    }
-                                }
-                                break;
-                            }
-                        
-                            psCssParam = psCssParam->psNext;
-                        }
-                    }
-                    if (psStroke)
-                    {
-                        psCssParam =  CPLGetXMLNode(psStroke, "CssParameter");
-                        /*sld 1.1 used SvgParameter*/ 
-                        if (psCssParam == NULL)
-                          psCssParam =  CPLGetXMLNode(psStroke, "SvgParameter");
-
-                        while (psCssParam && psCssParam->pszValue && 
-                               (strcasecmp(psCssParam->pszValue, "CssParameter") == 0 ||
-                                strcasecmp(psCssParam->pszValue, "SvgParameter") == 0))
-                        {
-                            psColorName = 
-                              (char*)CPLGetXMLValue(psCssParam, "name", NULL);
-                            if (psColorName && 
-                                strcasecmp(psColorName, "stroke") == 0) 
-                            {
-                                if(psCssParam->psChild && 
-                                   psCssParam->psChild->psNext && 
-                                   psCssParam->psChild->psNext->pszValue)
-                                  psColor = psCssParam->psChild->psNext->pszValue;
-
-                                if (psColor)
-                                {
-                                    nLength = strlen(psColor);
-                                    if (nLength == 7 && psColor[0] == '#')
-                                    {
-                                      msSLDSetColorObject(psColor,
-                                                          &psStyle->outlinecolor);
-                                    }
-                                }
-                                break;
-                            }
-                        
-                            psCssParam = psCssParam->psNext;
-                        }
-                    }
-                    
+
+            psCssParam = psCssParam->psNext;
+          }
+        }
+        if (psStroke) {
+          psCssParam =  CPLGetXMLNode(psStroke, "CssParameter");
+          /*sld 1.1 used SvgParameter*/
+          if (psCssParam == NULL)
+            psCssParam =  CPLGetXMLNode(psStroke, "SvgParameter");
+
+          while (psCssParam && psCssParam->pszValue &&
+                 (strcasecmp(psCssParam->pszValue, "CssParameter") == 0 ||
+                  strcasecmp(psCssParam->pszValue, "SvgParameter") == 0)) {
+            psName =
+              (char*)CPLGetXMLValue(psCssParam, "name", NULL);
+            if (psName &&
+                strcasecmp(psName, "stroke") == 0) {
+              if(psCssParam->psChild &&
+                  psCssParam->psChild->psNext &&
+                  psCssParam->psChild->psNext->pszValue)
+                psValue = psCssParam->psChild->psNext->pszValue;
+
+              if (psValue) {
+                nLength = strlen(psValue);
+                if (nLength == 7 && psValue[0] == '#') {
+                  msSLDSetColorObject(psValue,
+                                      &psStyle->outlinecolor);
                 }
-                /* set the default color if color is not not already set */
-                if ((psStyle->color.red < 0 || 
-                     psStyle->color.green == -1 ||
-                     psStyle->color.blue == -1) &&
-                    (psStyle->outlinecolor.red == -1 ||
-                     psStyle->outlinecolor.green == -1 ||
-                     psStyle->outlinecolor.blue == -1))
-                  {   
-                      psStyle->color.red = 128;
-                      psStyle->color.green = 128;
-                      psStyle->color.blue = 128;
-                  }
-                    
-                
-                /* Get the corresponding symbol id  */
-                psStyle->symbol = msSLDGetMarkSymbol(map, pszSymbolName, bFilled);
-                if (psStyle->symbol > 0 &&
-                    psStyle->symbol < map->symbolset.numsymbols)
-                  psStyle->symbolname = 
-                    msStrdup(map->symbolset.symbol[psStyle->symbol]->name);
-                    
-            }
-            else
-            {
-                psExternalGraphic =  CPLGetXMLNode(psGraphic, "ExternalGraphic");
-                if (psExternalGraphic)
-                  msSLDParseExternalGraphic(psExternalGraphic, psStyle, map);
+              }
+            } else if (psName &&
+                       strcasecmp(psName, "stroke-opacity") == 0) {
+              if(psCssParam->psChild &&
+                  psCssParam->psChild->psNext &&
+                  psCssParam->psChild->psNext->pszValue)
+                psValue = psCssParam->psChild->psNext->pszValue;
+
+              if (psValue) {
+                psStyle->outlinecolor.alpha = (int)(atof(psValue)*255);
+              }
+            } else if (psName &&
+                       strcasecmp(psName, "stroke-width") == 0) {
+              if(psCssParam->psChild &&
+                  psCssParam->psChild->psNext &&
+                  psCssParam->psChild->psNext->pszValue)
+                psValue = psCssParam->psChild->psNext->pszValue;
+
+              if (psValue) {
+                psStyle->width = atof(psValue);
+              }
             }
+
+            psCssParam = psCssParam->psNext;
+          }
         }
 
-        return MS_SUCCESS;
+      }
+      /* set the default color if color is not not already set */
+      if ((psStyle->color.red < 0 ||
+           psStyle->color.green == -1 ||
+           psStyle->color.blue == -1) &&
+          (psStyle->outlinecolor.red == -1 ||
+           psStyle->outlinecolor.green == -1 ||
+           psStyle->outlinecolor.blue == -1)) {
+        psStyle->color.red = 128;
+        psStyle->color.green = 128;
+        psStyle->color.blue = 128;
+      }
+
+
+      /* Get the corresponding symbol id  */
+      psStyle->symbol = msSLDGetMarkSymbol(map, pszSymbolName, bFilled);
+      if (psStyle->symbol > 0 &&
+          psStyle->symbol < map->symbolset.numsymbols)
+        psStyle->symbolname =
+          msStrdup(map->symbolset.symbol[psStyle->symbol]->name);
+
+    } else {
+      psExternalGraphic =  CPLGetXMLNode(psGraphic, "ExternalGraphic");
+      if (psExternalGraphic)
+        msSLDParseExternalGraphic(psExternalGraphic, psStyle, map);
+    }
+    msFree(pszSymbolName);
+  }
+
+  return MS_SUCCESS;
 }
-  
+
 
 /************************************************************************/
 /*                            msSLDGetMarkSymbol                        */
@@ -1802,272 +1733,248 @@ int msSLDParseGraphicFillOrStroke(CPLXMLNode *psRoot,
 /************************************************************************/
 int msSLDGetMarkSymbol(mapObj *map, char *pszSymbolName, int bFilled)
 {
-    int nSymbolId = 0;
-    symbolObj *psSymbol = NULL;
+  int nSymbolId = 0;
+  symbolObj *psSymbol = NULL;
 
-    if (!map || !pszSymbolName)
-      return 0;
+  if (!map || !pszSymbolName)
+    return 0;
 
-    if (strcasecmp(pszSymbolName, "square") == 0)
-    {
-        if (bFilled)
-          nSymbolId = msGetSymbolIndex(&map->symbolset, 
-                                       SLD_MARK_SYMBOL_SQUARE_FILLED, 
-                                       MS_FALSE);
-        else
-          nSymbolId = msGetSymbolIndex(&map->symbolset, 
-                                       SLD_MARK_SYMBOL_SQUARE, 
-                                       MS_FALSE);
-    }   
-    else if (strcasecmp(pszSymbolName, "circle") == 0)
-    {
-        
-        if (bFilled)
-          nSymbolId = msGetSymbolIndex(&map->symbolset, 
-                                       SLD_MARK_SYMBOL_CIRCLE_FILLED, 
-                                       MS_FALSE);
-        else
-          nSymbolId = msGetSymbolIndex(&map->symbolset, 
-                                       SLD_MARK_SYMBOL_CIRCLE, 
-                                       MS_FALSE);
-    }
-    else if (strcasecmp(pszSymbolName, "triangle") == 0)
-    {
-        
-        if (bFilled)
-          nSymbolId = msGetSymbolIndex(&map->symbolset, 
-                                       SLD_MARK_SYMBOL_TRIANGLE_FILLED, 
-                                       MS_FALSE);
-        else
-          nSymbolId = msGetSymbolIndex(&map->symbolset, 
-                                       SLD_MARK_SYMBOL_TRIANGLE, 
-                                       MS_FALSE);
-    }
-    else if (strcasecmp(pszSymbolName, "star") == 0)
-    {
-        
-        if (bFilled)
-          nSymbolId = msGetSymbolIndex(&map->symbolset, 
-                                       SLD_MARK_SYMBOL_STAR_FILLED, 
-                                       MS_FALSE);
-        else
-          nSymbolId = msGetSymbolIndex(&map->symbolset, 
-                                       SLD_MARK_SYMBOL_STAR, 
-                                       MS_FALSE);
-    }
-    else if (strcasecmp(pszSymbolName, "cross") == 0)
-    {
-        
-        if (bFilled)
-          nSymbolId = msGetSymbolIndex(&map->symbolset, 
-                                       SLD_MARK_SYMBOL_CROSS_FILLED, 
-                                       MS_FALSE);
-        else
-          nSymbolId = msGetSymbolIndex(&map->symbolset, 
-                                       SLD_MARK_SYMBOL_CROSS, 
-                                       MS_FALSE);
-    }
-    else if (strcasecmp(pszSymbolName, "x") == 0)
-    {
-        
-        if (bFilled)
-          nSymbolId = msGetSymbolIndex(&map->symbolset, 
-                                       SLD_MARK_SYMBOL_X_FILLED, 
-                                       MS_FALSE);
-        else
-          nSymbolId = msGetSymbolIndex(&map->symbolset, 
-                                       SLD_MARK_SYMBOL_X, 
-                                       MS_FALSE);
-    }
+  if (strcasecmp(pszSymbolName, "square") == 0) {
+    if (bFilled)
+      nSymbolId = msGetSymbolIndex(&map->symbolset,
+                                   SLD_MARK_SYMBOL_SQUARE_FILLED,
+                                   MS_FALSE);
     else
-    {
-        nSymbolId = msGetSymbolIndex(&map->symbolset, 
-                                     pszSymbolName, 
-                                     MS_FALSE);
+      nSymbolId = msGetSymbolIndex(&map->symbolset,
+                                   SLD_MARK_SYMBOL_SQUARE,
+                                   MS_FALSE);
+  } else if (strcasecmp(pszSymbolName, "circle") == 0) {
+
+    if (bFilled)
+      nSymbolId = msGetSymbolIndex(&map->symbolset,
+                                   SLD_MARK_SYMBOL_CIRCLE_FILLED,
+                                   MS_FALSE);
+    else
+      nSymbolId = msGetSymbolIndex(&map->symbolset,
+                                   SLD_MARK_SYMBOL_CIRCLE,
+                                   MS_FALSE);
+  } else if (strcasecmp(pszSymbolName, "triangle") == 0) {
+
+    if (bFilled)
+      nSymbolId = msGetSymbolIndex(&map->symbolset,
+                                   SLD_MARK_SYMBOL_TRIANGLE_FILLED,
+                                   MS_FALSE);
+    else
+      nSymbolId = msGetSymbolIndex(&map->symbolset,
+                                   SLD_MARK_SYMBOL_TRIANGLE,
+                                   MS_FALSE);
+  } else if (strcasecmp(pszSymbolName, "star") == 0) {
+
+    if (bFilled)
+      nSymbolId = msGetSymbolIndex(&map->symbolset,
+                                   SLD_MARK_SYMBOL_STAR_FILLED,
+                                   MS_FALSE);
+    else
+      nSymbolId = msGetSymbolIndex(&map->symbolset,
+                                   SLD_MARK_SYMBOL_STAR,
+                                   MS_FALSE);
+  } else if (strcasecmp(pszSymbolName, "cross") == 0) {
+
+    if (bFilled)
+      nSymbolId = msGetSymbolIndex(&map->symbolset,
+                                   SLD_MARK_SYMBOL_CROSS_FILLED,
+                                   MS_FALSE);
+    else
+      nSymbolId = msGetSymbolIndex(&map->symbolset,
+                                   SLD_MARK_SYMBOL_CROSS,
+                                   MS_FALSE);
+  } else if (strcasecmp(pszSymbolName, "x") == 0) {
+
+    if (bFilled)
+      nSymbolId = msGetSymbolIndex(&map->symbolset,
+                                   SLD_MARK_SYMBOL_X_FILLED,
+                                   MS_FALSE);
+    else
+      nSymbolId = msGetSymbolIndex(&map->symbolset,
+                                   SLD_MARK_SYMBOL_X,
+                                   MS_FALSE);
+  } else {
+    nSymbolId = msGetSymbolIndex(&map->symbolset,
+                                 pszSymbolName,
+                                 MS_FALSE);
+  }
+
+  if (nSymbolId <= 0) {
+    if( (psSymbol = msGrowSymbolSet(&(map->symbolset))) == NULL)
+      return 0; /* returns 0 for no symbol */
+
+    nSymbolId = map->symbolset.numsymbols;
+    map->symbolset.numsymbols++;
+    initSymbol(psSymbol);
+    psSymbol->inmapfile = MS_TRUE;
+    psSymbol->sizex = 1;
+    psSymbol->sizey = 1;
+
+    if (strcasecmp(pszSymbolName, "square") == 0) {
+      if (bFilled)
+        psSymbol->name = msStrdup(SLD_MARK_SYMBOL_SQUARE_FILLED);
+      else
+        psSymbol->name = msStrdup(SLD_MARK_SYMBOL_SQUARE);
+
+      psSymbol->type = MS_SYMBOL_VECTOR;
+      if (bFilled)
+        psSymbol->filled = MS_TRUE;
+      psSymbol->points[psSymbol->numpoints].x = 0;
+      psSymbol->points[psSymbol->numpoints].y = 1;
+      psSymbol->numpoints++;
+      psSymbol->points[psSymbol->numpoints].x = 0;
+      psSymbol->points[psSymbol->numpoints].y = 0;
+      psSymbol->numpoints++;
+      psSymbol->points[psSymbol->numpoints].x = 1;
+      psSymbol->points[psSymbol->numpoints].y = 0;
+      psSymbol->numpoints++;
+      psSymbol->points[psSymbol->numpoints].x = 1;
+      psSymbol->points[psSymbol->numpoints].y = 1;
+      psSymbol->numpoints++;
+      psSymbol->points[psSymbol->numpoints].x = 0;
+      psSymbol->points[psSymbol->numpoints].y = 1;
+      psSymbol->numpoints++;
+    } else if (strcasecmp(pszSymbolName, "circle") == 0) {
+      if (bFilled)
+        psSymbol->name = msStrdup(SLD_MARK_SYMBOL_CIRCLE_FILLED);
+      else
+        psSymbol->name = msStrdup(SLD_MARK_SYMBOL_CIRCLE);
+
+      psSymbol->type = MS_SYMBOL_ELLIPSE;
+      if (bFilled)
+        psSymbol->filled = MS_TRUE;
+
+      psSymbol->points[psSymbol->numpoints].x = 1;
+      psSymbol->points[psSymbol->numpoints].y = 1;
+      psSymbol->sizex = 1;
+      psSymbol->sizey = 1;
+      psSymbol->numpoints++;
+    } else if (strcasecmp(pszSymbolName, "triangle") == 0) {
+      if (bFilled)
+        psSymbol->name = msStrdup(SLD_MARK_SYMBOL_TRIANGLE_FILLED);
+      else
+        psSymbol->name = msStrdup(SLD_MARK_SYMBOL_TRIANGLE);
+
+      psSymbol->type = MS_SYMBOL_VECTOR;
+      if (bFilled)
+        psSymbol->filled = MS_TRUE;
+
+      psSymbol->points[psSymbol->numpoints].x = 0;
+      psSymbol->points[psSymbol->numpoints].y = 1;
+      psSymbol->numpoints++;
+      psSymbol->points[psSymbol->numpoints].x = 0.5;
+      psSymbol->points[psSymbol->numpoints].y = 0;
+      psSymbol->numpoints++;
+      psSymbol->points[psSymbol->numpoints].x = 1;
+      psSymbol->points[psSymbol->numpoints].y = 1;
+      psSymbol->numpoints++;
+      psSymbol->points[psSymbol->numpoints].x = 0;
+      psSymbol->points[psSymbol->numpoints].y = 1;
+      psSymbol->numpoints++;
+
+    } else if (strcasecmp(pszSymbolName, "star") == 0) {
+      if (bFilled)
+        psSymbol->name = msStrdup(SLD_MARK_SYMBOL_STAR_FILLED);
+      else
+        psSymbol->name = msStrdup(SLD_MARK_SYMBOL_STAR);
+
+      psSymbol->type = MS_SYMBOL_VECTOR;
+      if (bFilled)
+        psSymbol->filled = MS_TRUE;
+
+      psSymbol->points[psSymbol->numpoints].x = 0;
+      psSymbol->points[psSymbol->numpoints].y = 0.375;
+      psSymbol->numpoints++;
+      psSymbol->points[psSymbol->numpoints].x = 0.35;
+      psSymbol->points[psSymbol->numpoints].y = 0.375;
+      psSymbol->numpoints++;
+      psSymbol->points[psSymbol->numpoints].x = 0.5;
+      psSymbol->points[psSymbol->numpoints].y = 0;
+      psSymbol->numpoints++;
+      psSymbol->points[psSymbol->numpoints].x = 0.65;
+      psSymbol->points[psSymbol->numpoints].y = 0.375;
+      psSymbol->numpoints++;
+      psSymbol->points[psSymbol->numpoints].x = 1;
+      psSymbol->points[psSymbol->numpoints].y = 0.375;
+      psSymbol->numpoints++;
+      psSymbol->points[psSymbol->numpoints].x = 0.75;
+      psSymbol->points[psSymbol->numpoints].y = 0.625;
+      psSymbol->numpoints++;
+      psSymbol->points[psSymbol->numpoints].x = 0.875;
+      psSymbol->points[psSymbol->numpoints].y = 1;
+      psSymbol->numpoints++;
+      psSymbol->points[psSymbol->numpoints].x = 0.5;
+      psSymbol->points[psSymbol->numpoints].y = 0.75;
+      psSymbol->numpoints++;
+      psSymbol->points[psSymbol->numpoints].x = 0.125;
+      psSymbol->points[psSymbol->numpoints].y = 1;
+      psSymbol->numpoints++;
+      psSymbol->points[psSymbol->numpoints].x = 0.25;
+      psSymbol->points[psSymbol->numpoints].y = 0.625;
+      psSymbol->numpoints++;
     }
-
-    if (nSymbolId <= 0)
-    {
-        if( (psSymbol = msGrowSymbolSet(&(map->symbolset))) == NULL)
-            return 0; /* returns 0 for no symbol */
-
-        nSymbolId = map->symbolset.numsymbols;
-        map->symbolset.numsymbols++;
-        initSymbol(psSymbol);
-        psSymbol->inmapfile = MS_TRUE;
-        psSymbol->sizex = 1;
-        psSymbol->sizey = 1; 
-        
-        if (strcasecmp(pszSymbolName, "square") == 0)
-        {
-            if (bFilled)
-              psSymbol->name = msStrdup(SLD_MARK_SYMBOL_SQUARE_FILLED);
-            else
-              psSymbol->name = msStrdup(SLD_MARK_SYMBOL_SQUARE);
-
-            psSymbol->type = MS_SYMBOL_VECTOR;
-            if (bFilled)
-              psSymbol->filled = MS_TRUE;
-            psSymbol->points[psSymbol->numpoints].x = 0;
-            psSymbol->points[psSymbol->numpoints].y = 1;
-            psSymbol->numpoints++;
-            psSymbol->points[psSymbol->numpoints].x = 0;
-            psSymbol->points[psSymbol->numpoints].y = 0;
-            psSymbol->numpoints++;
-            psSymbol->points[psSymbol->numpoints].x = 1;
-            psSymbol->points[psSymbol->numpoints].y = 0;
-            psSymbol->numpoints++;
-            psSymbol->points[psSymbol->numpoints].x = 1;
-            psSymbol->points[psSymbol->numpoints].y = 1;
-            psSymbol->numpoints++;
-            psSymbol->points[psSymbol->numpoints].x = 0;
-            psSymbol->points[psSymbol->numpoints].y = 1;
-            psSymbol->numpoints++;
-        }
-        else if (strcasecmp(pszSymbolName, "circle") == 0)
-        {
-            if (bFilled)
-              psSymbol->name = msStrdup(SLD_MARK_SYMBOL_CIRCLE_FILLED);
-            else
-              psSymbol->name = msStrdup(SLD_MARK_SYMBOL_CIRCLE);
-            
-            psSymbol->type = MS_SYMBOL_ELLIPSE;
-            if (bFilled)
-              psSymbol->filled = MS_TRUE;
-
-            psSymbol->points[psSymbol->numpoints].x = 1;
-            psSymbol->points[psSymbol->numpoints].y = 1;
-            psSymbol->sizex = 1;
-            psSymbol->sizey = 1; 
-            psSymbol->numpoints++;
-        }
-        else if (strcasecmp(pszSymbolName, "triangle") == 0)
-        {
-            if (bFilled)
-              psSymbol->name = msStrdup(SLD_MARK_SYMBOL_TRIANGLE_FILLED);
-            else
-              psSymbol->name = msStrdup(SLD_MARK_SYMBOL_TRIANGLE);
-            
-            psSymbol->type = MS_SYMBOL_VECTOR;
-            if (bFilled)
-              psSymbol->filled = MS_TRUE;
-
-            psSymbol->points[psSymbol->numpoints].x = 0;
-            psSymbol->points[psSymbol->numpoints].y = 1;
-            psSymbol->numpoints++;
-            psSymbol->points[psSymbol->numpoints].x = 0.5;
-            psSymbol->points[psSymbol->numpoints].y = 0;
-            psSymbol->numpoints++;
-            psSymbol->points[psSymbol->numpoints].x = 1;
-            psSymbol->points[psSymbol->numpoints].y = 1;
-            psSymbol->numpoints++;
-            psSymbol->points[psSymbol->numpoints].x = 0;
-            psSymbol->points[psSymbol->numpoints].y = 1;
-            psSymbol->numpoints++;
-        
-        }
-        else if (strcasecmp(pszSymbolName, "star") == 0)
-        {
-            if (bFilled)
-              psSymbol->name = msStrdup(SLD_MARK_SYMBOL_STAR_FILLED);
-            else
-              psSymbol->name = msStrdup(SLD_MARK_SYMBOL_STAR);
-
-            psSymbol->type = MS_SYMBOL_VECTOR;
-            if (bFilled)
-              psSymbol->filled = MS_TRUE;
-
-            psSymbol->points[psSymbol->numpoints].x = 0;
-            psSymbol->points[psSymbol->numpoints].y = 0.375;
-            psSymbol->numpoints++;
-            psSymbol->points[psSymbol->numpoints].x = 0.35;
-            psSymbol->points[psSymbol->numpoints].y = 0.375;
-            psSymbol->numpoints++;
-            psSymbol->points[psSymbol->numpoints].x = 0.5;
-            psSymbol->points[psSymbol->numpoints].y = 0;
-            psSymbol->numpoints++;
-            psSymbol->points[psSymbol->numpoints].x = 0.65;
-            psSymbol->points[psSymbol->numpoints].y = 0.375;
-            psSymbol->numpoints++;
-            psSymbol->points[psSymbol->numpoints].x = 1;
-            psSymbol->points[psSymbol->numpoints].y = 0.375;
-            psSymbol->numpoints++;
-            psSymbol->points[psSymbol->numpoints].x = 0.75;
-            psSymbol->points[psSymbol->numpoints].y = 0.625;
-            psSymbol->numpoints++;
-            psSymbol->points[psSymbol->numpoints].x = 0.875;
-            psSymbol->points[psSymbol->numpoints].y = 1;
-            psSymbol->numpoints++;
-            psSymbol->points[psSymbol->numpoints].x = 0.5;
-            psSymbol->points[psSymbol->numpoints].y = 0.75;
-            psSymbol->numpoints++;
-            psSymbol->points[psSymbol->numpoints].x = 0.125;
-            psSymbol->points[psSymbol->numpoints].y = 1;
-            psSymbol->numpoints++;
-            psSymbol->points[psSymbol->numpoints].x = 0.25;
-            psSymbol->points[psSymbol->numpoints].y = 0.625;
-            psSymbol->numpoints++;
-        }
-        /* cross is like plus (+) since there is also X symbol ?? */
-        else if (strcasecmp(pszSymbolName, "cross") == 0)
-        {
-            /* NEVER FILL CROSS */
-            /* if (bFilled) */
-            /* psSymbol->name = msStrdup(SLD_MARK_SYMBOL_CROSS_FILLED); */
-            /* else */
-              psSymbol->name = msStrdup(SLD_MARK_SYMBOL_CROSS);
-            
-            psSymbol->type = MS_SYMBOL_VECTOR;
-            /* if (bFilled) */
-            /* psSymbol->filled = MS_TRUE; */
-
-            psSymbol->points[psSymbol->numpoints].x = 0.5;
-            psSymbol->points[psSymbol->numpoints].y = 0;
-            psSymbol->numpoints++;
-            psSymbol->points[psSymbol->numpoints].x = 0.5;
-            psSymbol->points[psSymbol->numpoints].y = 1;
-            psSymbol->numpoints++;
-            psSymbol->points[psSymbol->numpoints].x = -99;
-            psSymbol->points[psSymbol->numpoints].y = -99;
-            psSymbol->numpoints++;
-            psSymbol->points[psSymbol->numpoints].x = 0;
-            psSymbol->points[psSymbol->numpoints].y = 0.5;
-            psSymbol->numpoints++;
-            psSymbol->points[psSymbol->numpoints].x = 1;
-            psSymbol->points[psSymbol->numpoints].y = 0.5;
-            psSymbol->numpoints++;
-        }
-        else if (strcasecmp(pszSymbolName, "x") == 0)
-        {
-            /* NEVER FILL X */
-            /* if (bFilled) */
-            /* psSymbol->name = msStrdup(SLD_MARK_SYMBOL_X_FILLED); */
-            /* else */
-              psSymbol->name = msStrdup(SLD_MARK_SYMBOL_X);
-            
-            psSymbol->type = MS_SYMBOL_VECTOR;
-            /* if (bFilled) */
-            /* psSymbol->filled = MS_TRUE; */
-            psSymbol->points[psSymbol->numpoints].x = 0;
-            psSymbol->points[psSymbol->numpoints].y = 0;
-            psSymbol->numpoints++;
-            psSymbol->points[psSymbol->numpoints].x = 1;
-            psSymbol->points[psSymbol->numpoints].y = 1;
-            psSymbol->numpoints++;
-            psSymbol->points[psSymbol->numpoints].x = -99;
-            psSymbol->points[psSymbol->numpoints].y = -99;
-            psSymbol->numpoints++;
-            psSymbol->points[psSymbol->numpoints].x = 0;
-            psSymbol->points[psSymbol->numpoints].y = 1;
-            psSymbol->numpoints++;
-            psSymbol->points[psSymbol->numpoints].x = 1;
-            psSymbol->points[psSymbol->numpoints].y = 0;
-            psSymbol->numpoints++;
-        }
-
+    /* cross is like plus (+) since there is also X symbol ?? */
+    else if (strcasecmp(pszSymbolName, "cross") == 0) {
+      /* NEVER FILL CROSS */
+      /* if (bFilled) */
+      /* psSymbol->name = msStrdup(SLD_MARK_SYMBOL_CROSS_FILLED); */
+      /* else */
+      psSymbol->name = msStrdup(SLD_MARK_SYMBOL_CROSS);
+
+      psSymbol->type = MS_SYMBOL_VECTOR;
+      /* if (bFilled) */
+      /* psSymbol->filled = MS_TRUE; */
+
+      psSymbol->points[psSymbol->numpoints].x = 0.5;
+      psSymbol->points[psSymbol->numpoints].y = 0;
+      psSymbol->numpoints++;
+      psSymbol->points[psSymbol->numpoints].x = 0.5;
+      psSymbol->points[psSymbol->numpoints].y = 1;
+      psSymbol->numpoints++;
+      psSymbol->points[psSymbol->numpoints].x = -99;
+      psSymbol->points[psSymbol->numpoints].y = -99;
+      psSymbol->numpoints++;
+      psSymbol->points[psSymbol->numpoints].x = 0;
+      psSymbol->points[psSymbol->numpoints].y = 0.5;
+      psSymbol->numpoints++;
+      psSymbol->points[psSymbol->numpoints].x = 1;
+      psSymbol->points[psSymbol->numpoints].y = 0.5;
+      psSymbol->numpoints++;
+    } else if (strcasecmp(pszSymbolName, "x") == 0) {
+      /* NEVER FILL X */
+      /* if (bFilled) */
+      /* psSymbol->name = msStrdup(SLD_MARK_SYMBOL_X_FILLED); */
+      /* else */
+      psSymbol->name = msStrdup(SLD_MARK_SYMBOL_X);
+
+      psSymbol->type = MS_SYMBOL_VECTOR;
+      /* if (bFilled) */
+      /* psSymbol->filled = MS_TRUE; */
+      psSymbol->points[psSymbol->numpoints].x = 0;
+      psSymbol->points[psSymbol->numpoints].y = 0;
+      psSymbol->numpoints++;
+      psSymbol->points[psSymbol->numpoints].x = 1;
+      psSymbol->points[psSymbol->numpoints].y = 1;
+      psSymbol->numpoints++;
+      psSymbol->points[psSymbol->numpoints].x = -99;
+      psSymbol->points[psSymbol->numpoints].y = -99;
+      psSymbol->numpoints++;
+      psSymbol->points[psSymbol->numpoints].x = 0;
+      psSymbol->points[psSymbol->numpoints].y = 1;
+      psSymbol->numpoints++;
+      psSymbol->points[psSymbol->numpoints].x = 1;
+      psSymbol->points[psSymbol->numpoints].y = 0;
+      psSymbol->numpoints++;
     }
 
-    return nSymbolId;
+  }
+
+  return nSymbolId;
 }
 
 static const unsigned char PNGsig[8] = {137, 80, 78, 71, 13, 10, 26, 10}; /* 89 50 4E 47 0D 0A 1A 0A hex */
@@ -2081,26 +1988,25 @@ static const unsigned char PNGsig[8] = {137, 80, 78, 71, 13, 10, 26, 10}; /* 89
 int msSLDGetGraphicSymbol(mapObj *map, char *pszFileName,  char* extGraphicName,
                           int nGap)
 {
-    int nSymbolId = 0;
-    symbolObj *psSymbol = NULL;
-
-
-    if (map && pszFileName)
-    {
-		if( (psSymbol = msGrowSymbolSet(&(map->symbolset))) == NULL)
-			return 0; /* returns 0 for no symbol */
-		nSymbolId = map->symbolset.numsymbols;
-		map->symbolset.numsymbols++;
-		initSymbol(psSymbol);
-		psSymbol->inmapfile = MS_TRUE;
-		psSymbol->type = MS_SYMBOL_PIXMAP;
-		psSymbol->name = msStrdup(extGraphicName);
-		psSymbol->imagepath = msStrdup(pszFileName);
-                psSymbol->full_pixmap_path = msStrdup(pszFileName);
-    }
-    return nSymbolId;
+  int nSymbolId = 0;
+  symbolObj *psSymbol = NULL;
+
+
+  if (map && pszFileName) {
+    if( (psSymbol = msGrowSymbolSet(&(map->symbolset))) == NULL)
+      return 0; /* returns 0 for no symbol */
+    nSymbolId = map->symbolset.numsymbols;
+    map->symbolset.numsymbols++;
+    initSymbol(psSymbol);
+    psSymbol->inmapfile = MS_TRUE;
+    psSymbol->type = MS_SYMBOL_PIXMAP;
+    psSymbol->name = msStrdup(extGraphicName);
+    psSymbol->imagepath = msStrdup(pszFileName);
+    psSymbol->full_pixmap_path = msStrdup(pszFileName);
+  }
+  return nSymbolId;
 }
-                 
+
 
 /************************************************************************/
 /*      msSLDParsePointSymbolizer                                       */
@@ -2117,34 +2023,32 @@ int msSLDGetGraphicSymbol(mapObj *map, char *pszFileName,  char* extGraphicName,
 /*      </xs:element>                                                   */
 /************************************************************************/
 int msSLDParsePointSymbolizer(CPLXMLNode *psRoot, layerObj *psLayer,
-                               int bNewClass)
+                              int bNewClass)
 {
-    int nClassId = 0;
-    int iStyle = 0;
+  int nClassId = 0;
+  int iStyle = 0;
 
-    if (!psRoot || !psLayer)
-        return MS_FAILURE;
+  if (!psRoot || !psLayer)
+    return MS_FAILURE;
 
-        if (bNewClass || psLayer->numclasses <= 0)
-        {
-            if (msGrowLayerClasses(psLayer) == NULL)
-                return MS_FAILURE;
-            initClass(psLayer->class[psLayer->numclasses]);
-            nClassId = psLayer->numclasses;
-            psLayer->numclasses++;
-        }
-        else
-          nClassId = psLayer->numclasses-1;
+  if (bNewClass || psLayer->numclasses <= 0) {
+    if (msGrowLayerClasses(psLayer) == NULL)
+      return MS_FAILURE;
+    initClass(psLayer->class[psLayer->numclasses]);
+    nClassId = psLayer->numclasses;
+    psLayer->numclasses++;
+  } else
+    nClassId = psLayer->numclasses-1;
+
+  iStyle = psLayer->class[nClassId]->numstyles;
+  msMaybeAllocateClassStyle(psLayer->class[nClassId], iStyle);
 
-        iStyle = psLayer->class[nClassId]->numstyles;
-	msMaybeAllocateClassStyle(psLayer->class[nClassId], iStyle);
-        
 
-        msSLDParseGraphicFillOrStroke(psRoot, NULL,
-                                      psLayer->class[nClassId]->styles[iStyle],
-                                      psLayer->map, 1);
+  msSLDParseGraphicFillOrStroke(psRoot, NULL,
+                                psLayer->class[nClassId]->styles[iStyle],
+                                psLayer->map, 1);
 
-        return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 
@@ -2155,72 +2059,65 @@ int msSLDParsePointSymbolizer(CPLXMLNode *psRoot, layerObj *psLayer,
 /*      by the URL and create a PIXMAP inmap symbol. Only GIF and       */
 /*      PNG are supported.                                              */
 /************************************************************************/
-int msSLDParseExternalGraphic(CPLXMLNode *psExternalGraphic, 
-                               styleObj *psStyle,  mapObj *map)
+int msSLDParseExternalGraphic(CPLXMLNode *psExternalGraphic,
+                              styleObj *psStyle,  mapObj *map)
 {
-/* needed for libcurl function msHTTPGetFile in maphttp.c */
+  /* needed for libcurl function msHTTPGetFile in maphttp.c */
 #if defined(USE_CURL)
 
-    char *pszFormat = NULL;
-    CPLXMLNode *psURL=NULL, *psFormat=NULL, *psTmp=NULL;
-    char *pszURL=NULL, *pszTmpSymbolName=NULL;
-    int status;
-
-
-    if (!psExternalGraphic || !psStyle || !map)
-        return MS_FAILURE;
+  char *pszFormat = NULL;
+  CPLXMLNode *psURL=NULL, *psFormat=NULL, *psTmp=NULL;
+  char *pszURL=NULL;
 
-        psFormat = CPLGetXMLNode(psExternalGraphic, "Format");
-        if (psFormat && psFormat->psChild && psFormat->psChild->pszValue)
-          pszFormat = psFormat->psChild->pszValue;
+  if (!psExternalGraphic || !psStyle || !map)
+    return MS_FAILURE;
 
-        /* supports GIF and PNG */
-        if (pszFormat && 
-            (strcasecmp(pszFormat, "GIF") == 0 ||
-             strcasecmp(pszFormat, "image/gif") == 0 || 
-             strcasecmp(pszFormat, "PNG") == 0 ||
-             strcasecmp(pszFormat, "image/png") == 0))
-        {
-          
-            /* <OnlineResource xmlns:xlink="http://www.w3.org/1999/xlink" xlink:type="simple" xlink:href="http://www.vendor.com/geosym/2267.svg"/> */
-            psURL = CPLGetXMLNode(psExternalGraphic, "OnlineResource");
-            if (psURL && psURL->psChild)
-            {
-                psTmp =  psURL->psChild;
-                while (psTmp != NULL && 
-                       psTmp->pszValue && 
-                       strcasecmp(psTmp->pszValue, "xlink:href") != 0)
-                {
-                    psTmp = psTmp->psNext;
-                }
-                if (psTmp && psTmp->psChild)
-                {
-                    pszURL = (char*)psTmp->psChild->pszValue;
-                    
-                    /*external symbols using http will be automaticallly downloaded. The file should be 
-                      saved in a temporary directory (msAddImageSymbol) #2305*/
-                    psStyle->symbol = msGetSymbolIndex(&map->symbolset, 
-                                                       pszURL, 
-                                                       MS_TRUE);
-                    
-                    if (psStyle->symbol > 0 && psStyle->symbol < map->symbolset.numsymbols)
-                      psStyle->symbolname = msStrdup(map->symbolset.symbol[psStyle->symbol]->name);
-
-                    /* set the color parameter if not set. Does not make sense */
-                    /* for pixmap but mapserver needs it. */
-                    if (psStyle->color.red == -1 || psStyle->color.green || psStyle->color.blue)
-                    {
-                        psStyle->color.red = 0;
-                        psStyle->color.green = 0;
-                        psStyle->color.blue = 0;
-                    }
-                }
-            }
+  psFormat = CPLGetXMLNode(psExternalGraphic, "Format");
+  if (psFormat && psFormat->psChild && psFormat->psChild->pszValue)
+    pszFormat = psFormat->psChild->pszValue;
+
+  /* supports GIF and PNG */
+  if (pszFormat &&
+      (strcasecmp(pszFormat, "GIF") == 0 ||
+       strcasecmp(pszFormat, "image/gif") == 0 ||
+       strcasecmp(pszFormat, "PNG") == 0 ||
+       strcasecmp(pszFormat, "image/png") == 0)) {
+
+    /* <OnlineResource xmlns:xlink="http://www.w3.org/1999/xlink" xlink:type="simple" xlink:href="http://www.vendor.com/geosym/2267.svg"/> */
+    psURL = CPLGetXMLNode(psExternalGraphic, "OnlineResource");
+    if (psURL && psURL->psChild) {
+      psTmp =  psURL->psChild;
+      while (psTmp != NULL &&
+             psTmp->pszValue &&
+             strcasecmp(psTmp->pszValue, "xlink:href") != 0) {
+        psTmp = psTmp->psNext;
+      }
+      if (psTmp && psTmp->psChild) {
+        pszURL = (char*)psTmp->psChild->pszValue;
+
+        /*external symbols using http will be automaticallly downloaded. The file should be
+          saved in a temporary directory (msAddImageSymbol) #2305*/
+        psStyle->symbol = msGetSymbolIndex(&map->symbolset,
+                                           pszURL,
+                                           MS_TRUE);
+
+        if (psStyle->symbol > 0 && psStyle->symbol < map->symbolset.numsymbols)
+          psStyle->symbolname = msStrdup(map->symbolset.symbol[psStyle->symbol]->name);
+
+        /* set the color parameter if not set. Does not make sense */
+        /* for pixmap but mapserver needs it. */
+        if (psStyle->color.red == -1 || psStyle->color.green || psStyle->color.blue) {
+          psStyle->color.red = 0;
+          psStyle->color.green = 0;
+          psStyle->color.blue = 0;
         }
-        
-        return MS_SUCCESS;
+      }
+    }
+  }
+
+  return MS_SUCCESS;
 #else
-    return MS_FAILURE;
+  return MS_FAILURE;
 #endif
 }
 
@@ -2254,7 +2151,7 @@ int msSLDParseExternalGraphic(CPLXMLNode *psExternalGraphic,
 /*      </xs:complexType>                                               */
 /*      </xs:element>                                                   */
 /*                                                                      */
-/*      Four types of CssParameter are allowed, font-family, font-style,*/ 
+/*      Four types of CssParameter are allowed, font-family, font-style,*/
 /*      fontweight,and font-size.                                       */
 /*                                                                      */
 /*      <xs:element name="LabelPlacement">                              */
@@ -2318,35 +2215,32 @@ int msSLDParseExternalGraphic(CPLXMLNode *psExternalGraphic,
 /*      </xs:element>                                                   */
 /************************************************************************/
 int msSLDParseTextSymbolizer(CPLXMLNode *psRoot, layerObj *psLayer,
-                              int bOtherSymboliser)
+                             int bOtherSymboliser)
 {
-    int nStyleId=0, nClassId=0;
-
-    if (!psRoot || !psLayer)
-        return MS_FAILURE;
-
-        if (!bOtherSymboliser)
-        {	
-            if (msGrowLayerClasses(psLayer) == NULL)
-                return MS_FAILURE;
-            initClass(psLayer->class[psLayer->numclasses]);
-            nClassId = psLayer->numclasses;
-            psLayer->numclasses++;
-	    msMaybeAllocateClassStyle(psLayer->class[nClassId], 0);
-            nStyleId = 0;
-        }
-        else
-        {
-            nClassId = psLayer->numclasses - 1;
-            if (nClassId >= 0)/* should always be true */
-              nStyleId = psLayer->class[nClassId]->numstyles -1;
-        }
+  int nStyleId=0, nClassId=0;
 
-        if (nStyleId >= 0 && nClassId >= 0) /* should always be true */
-          msSLDParseTextParams(psRoot, psLayer,
-                               psLayer->class[nClassId]);
+  if (!psRoot || !psLayer)
+    return MS_FAILURE;
 
-        return MS_SUCCESS;
+  if (!bOtherSymboliser) {
+    if (msGrowLayerClasses(psLayer) == NULL)
+      return MS_FAILURE;
+    initClass(psLayer->class[psLayer->numclasses]);
+    nClassId = psLayer->numclasses;
+    psLayer->numclasses++;
+    msMaybeAllocateClassStyle(psLayer->class[nClassId], 0);
+    nStyleId = 0;
+  } else {
+    nClassId = psLayer->numclasses - 1;
+    if (nClassId >= 0)/* should always be true */
+      nStyleId = psLayer->class[nClassId]->numstyles -1;
+  }
+
+  if (nStyleId >= 0 && nClassId >= 0) /* should always be true */
+    msSLDParseTextParams(psRoot, psLayer,
+                         psLayer->class[nClassId]);
+
+  return MS_SUCCESS;
 }
 
 
@@ -2445,714 +2339,648 @@ int msSLDParseTextSymbolizer(CPLXMLNode *psRoot, layerObj *psLayer,
 /************************************************************************/
 int msSLDParseRasterSymbolizer(CPLXMLNode *psRoot, layerObj *psLayer)
 {
-    CPLXMLNode  *psColorMap = NULL, *psColorEntry = NULL, *psOpacity=NULL;
-    char *pszColor=NULL, *pszQuantity=NULL;
-    char *pszPreviousColor=NULL, *pszPreviousQuality=NULL;
-    colorObj sColor;
-    char szExpression[100];
-    int nClassId = 0;
-    double dfOpacity = 1.0;
-    char *pszLabel = NULL,  *pszPreviousLabel = NULL;
-    char *pch = NULL, *pchPrevious=NULL;
-    
-    CPLXMLNode  *psNode=NULL, *psCategorize=NULL;
-    char **papszValues = (char **)malloc(sizeof(char*)*100);
-    char **papszThresholds = (char **)malloc(sizeof(char*)*100);
-    char *pszTmp = NULL;
-    int nValues=0, nThresholds=0;
-    int i,nMaxValues= 100, nMaxThreshold=100;
-
-    if (!psRoot || !psLayer)
+  CPLXMLNode  *psColorMap = NULL, *psColorEntry = NULL, *psOpacity=NULL;
+  char *pszColor=NULL, *pszQuantity=NULL;
+  char *pszPreviousColor=NULL, *pszPreviousQuality=NULL;
+  colorObj sColor;
+  char szExpression[100];
+  int nClassId = 0;
+  double dfOpacity = 1.0;
+  char *pszLabel = NULL,  *pszPreviousLabel = NULL;
+  char *pch = NULL, *pchPrevious=NULL;
+
+  CPLXMLNode  *psNode=NULL, *psCategorize=NULL;
+  char *pszTmp = NULL;
+  int nValues=0, nThresholds=0;
+  int i,nMaxValues= 100, nMaxThreshold=100;
+
+  if (!psRoot || !psLayer)
+    return MS_FAILURE;
+
+  /* ==================================================================== */
+  /*      The default opacity value is 0 : we set it here to -1           */
+  /*      so that when testing the values in msSLDApplySLD (to be         */
+  /*      applied on the layer), we can assume that a value of 0 comes    */
+  /*      from the sld.                                                   */
+  /* ==================================================================== */
+  psLayer->opacity = -1;
+
+  psOpacity = CPLGetXMLNode(psRoot, "Opacity");
+  if (psOpacity) {
+    if (psOpacity->psChild && psOpacity->psChild->pszValue)
+      dfOpacity = atof(psOpacity->psChild->pszValue);
+
+    /* values in sld goes from 0.0 (for transparent) to 1.0 (for full opacity); */
+    if (dfOpacity >=0.0 && dfOpacity <=1.0)
+      psLayer->opacity = (int)(dfOpacity * 100);
+    else {
+      msSetError(MS_WMSERR, "Invalid opacity value. Values should be between 0.0 and 1.0", "msSLDParseRasterSymbolizer()");
       return MS_FAILURE;
+    }
+  }
+  psColorMap = CPLGetXMLNode(psRoot, "ColorMap");
+  if (psColorMap) {
+    psColorEntry = CPLGetXMLNode(psColorMap, "ColorMapEntry");
+
+    if (psColorEntry) { /*SLD 1.0*/
+      while (psColorEntry && psColorEntry->pszValue &&
+             strcasecmp(psColorEntry->pszValue, "ColorMapEntry") == 0) {
+        pszColor = (char *)CPLGetXMLValue(psColorEntry, "color", NULL);
+        pszQuantity = (char *)CPLGetXMLValue(psColorEntry, "quantity", NULL);
+        pszLabel = (char *)CPLGetXMLValue(psColorEntry, "label", NULL);
+
+        if (pszColor && pszQuantity) {
+          if (pszPreviousColor && pszPreviousQuality) {
+            if (strlen(pszPreviousColor) == 7 &&
+                pszPreviousColor[0] == '#' &&
+                strlen(pszColor) == 7 && pszColor[0] == '#') {
+              sColor.red = msHexToInt(pszPreviousColor+1);
+              sColor.green= msHexToInt(pszPreviousColor+3);
+              sColor.blue = msHexToInt(pszPreviousColor+5);
+
+              /* pszQuantity and pszPreviousQuality may be integer or float */
+              pchPrevious=strchr(pszPreviousQuality,'.');
+              pch=strchr(pszQuantity,'.');
+              if (pchPrevious==NULL && pch==NULL) {
+                snprintf(szExpression, sizeof(szExpression),
+                         "([pixel] >= %d AND [pixel] < %d)",
+                         atoi(pszPreviousQuality),
+                         atoi(pszQuantity));
+              } else if (pchPrevious != NULL && pch==NULL) {
+                snprintf(szExpression, sizeof(szExpression),
+                         "([pixel] >= %f AND [pixel] < %d)",
+                         atof(pszPreviousQuality),
+                         atoi(pszQuantity));
+              } else if (pchPrevious == NULL && pch != NULL) {
+                snprintf(szExpression, sizeof(szExpression),
+                         "([pixel] >= %d AND [pixel] < %f)",
+                         atoi(pszPreviousQuality),
+                         atof(pszQuantity));
+              } else {
+                snprintf(szExpression, sizeof(szExpression),
+                         "([pixel] >= %f AND [pixel] < %f)",
+                         atof(pszPreviousQuality),
+                         atof(pszQuantity));
+              }
+
+
+              if (msGrowLayerClasses(psLayer) == NULL)
+                return MS_FAILURE;
+              else {
+                initClass(psLayer->class[psLayer->numclasses]);
+                psLayer->numclasses++;
+                nClassId = psLayer->numclasses-1;
 
-/* ==================================================================== */
-/*      The default opacity value is 0 : we set it here to -1           */
-/*      so that when testing the values in msSLDApplySLD (to be         */
-/*      applied on the layer), we can assume that a value of 0 comes    */
-/*      from the sld.                                                   */
-/* ==================================================================== */
-    psLayer->opacity = -1;
+                /*set the class name using the label. If label not defined
+                  set it with the quantity*/
+                if (pszPreviousLabel)
+                  psLayer->class[nClassId]->name = msStrdup(pszPreviousLabel);
+                else
+                  psLayer->class[nClassId]->name = msStrdup(pszPreviousQuality);
 
-    psOpacity = CPLGetXMLNode(psRoot, "Opacity");
-    if (psOpacity)
-    {
-        if (psOpacity->psChild && psOpacity->psChild->pszValue)
-          dfOpacity = atof(psOpacity->psChild->pszValue);
-        
-        /* values in sld goes from 0.0 (for transparent) to 1.0 (for full opacity); */
-        if (dfOpacity >=0.0 && dfOpacity <=1.0)
-          psLayer->opacity = (int)(dfOpacity * 100);
-        else
-        {
-            msSetError(MS_WMSERR, "Invalid opacity value. Values should be between 0.0 and 1.0", "msSLDParseRasterSymbolizer()");
-            return MS_FAILURE;
-        }
-    }
-    psColorMap = CPLGetXMLNode(psRoot, "ColorMap");
-    if (psColorMap)
-    {
-        psColorEntry = CPLGetXMLNode(psColorMap, "ColorMapEntry");
-        
-        if (psColorEntry) /*SLD 1.0*/
-        {
-            while (psColorEntry && psColorEntry->pszValue &&
-                   strcasecmp(psColorEntry->pszValue, "ColorMapEntry") == 0)
-            {
-                pszColor = (char *)CPLGetXMLValue(psColorEntry, "color", NULL);
-                pszQuantity = (char *)CPLGetXMLValue(psColorEntry, "quantity", NULL);
-                pszLabel = (char *)CPLGetXMLValue(psColorEntry, "label", NULL);
-
-                if (pszColor && pszQuantity)
-                {
-                    if (pszPreviousColor && pszPreviousQuality)
-                    {
-                        if (strlen(pszPreviousColor) == 7 && 
-                            pszPreviousColor[0] == '#' &&
-                            strlen(pszColor) == 7 && pszColor[0] == '#')
-                        {
-                            sColor.red = msHexToInt(pszPreviousColor+1);
-                            sColor.green= msHexToInt(pszPreviousColor+3);
-                            sColor.blue = msHexToInt(pszPreviousColor+5);
-
-                            /* pszQuantity and pszPreviousQuality may be integer or float */
-                            pchPrevious=strchr(pszPreviousQuality,'.');
-                            pch=strchr(pszQuantity,'.');
-                            if (pchPrevious==NULL && pch==NULL) {
-                                snprintf(szExpression, sizeof(szExpression),
-                                         "([pixel] >= %d AND [pixel] < %d)",
-                                         atoi(pszPreviousQuality),
-                                         atoi(pszQuantity));
-                            } else if (pchPrevious != NULL && pch==NULL) {
-                                snprintf(szExpression, sizeof(szExpression),
-                                         "([pixel] >= %f AND [pixel] < %d)",
-                                         atof(pszPreviousQuality),
-                                         atoi(pszQuantity));
-                            } else if (pchPrevious == NULL && pch != NULL) {
-                                snprintf(szExpression, sizeof(szExpression),
-                                         "([pixel] >= %d AND [pixel] < %f)",
-                                         atoi(pszPreviousQuality),
-                                         atof(pszQuantity));
-                            } else {
-                                snprintf(szExpression, sizeof(szExpression),
-                                         "([pixel] >= %f AND [pixel] < %f)",
-                                         atof(pszPreviousQuality),
-                                         atof(pszQuantity));
-                            }
-
-
-                            if (msGrowLayerClasses(psLayer) == NULL)
-                              return MS_FAILURE;
-                            else
-                            {
-                                initClass(psLayer->class[psLayer->numclasses]);
-                                psLayer->numclasses++;
-                                nClassId = psLayer->numclasses-1;
-
-                                /*set the class name using the label. If label not defined
-                                  set it with the quantity*/
-                                if (pszPreviousLabel)
-                                  psLayer->class[nClassId]->name = msStrdup(pszPreviousLabel);
-                                else
-                                  psLayer->class[nClassId]->name = msStrdup(pszPreviousQuality);
-
-                                msMaybeAllocateClassStyle(psLayer->class[nClassId], 0);
-
-                                psLayer->class[nClassId]->styles[0]->color.red = 
-                                  sColor.red;
-                                psLayer->class[nClassId]->styles[0]->color.green = 
-                                  sColor.green;
-                                psLayer->class[nClassId]->styles[0]->color.blue = 
-                                  sColor.blue;
-
-                                if (psLayer->classitem && 
-                                    strcasecmp(psLayer->classitem, "[pixel]") != 0)
-                                  free(psLayer->classitem);
-                                psLayer->classitem = msStrdup("[pixel]");
-
-                                msLoadExpressionString(&psLayer->class[nClassId]->expression,
-                                                       szExpression);
-                            
-                            
-                            }
-                        }
-                        else
-                        {
-                            msSetError(MS_WMSERR, 
-                                       "Invalid ColorMap Entry.", 
-                                       "msSLDParseRasterSymbolizer()");
-                            return MS_FAILURE;
-                        }
+                msMaybeAllocateClassStyle(psLayer->class[nClassId], 0);
 
-                    }
-               
-                    pszPreviousColor = pszColor;
-                    pszPreviousQuality = pszQuantity;
-                    pszPreviousLabel = pszLabel;
+                psLayer->class[nClassId]->styles[0]->color.red =
+                      sColor.red;
+              psLayer->class[nClassId]->styles[0]->color.green =
+                      sColor.green;
+              psLayer->class[nClassId]->styles[0]->color.blue =
+                      sColor.blue;
 
-                }
-                psColorEntry = psColorEntry->psNext;
+                if (psLayer->classitem &&
+                    strcasecmp(psLayer->classitem, "[pixel]") != 0)
+                  free(psLayer->classitem);
+                psLayer->classitem = msStrdup("[pixel]");
+
+                msLoadExpressionString(&psLayer->class[nClassId]->expression,
+                                       szExpression);
+
+
+              }
+            } else {
+              msSetError(MS_WMSERR,
+                         "Invalid ColorMap Entry.",
+                         "msSLDParseRasterSymbolizer()");
+              return MS_FAILURE;
             }
-            /* do the last Color Map Entry */
-            if (pszColor && pszQuantity)
-            {
-                if (strlen(pszColor) == 7 && pszColor[0] == '#')
-                {
-                    sColor.red = msHexToInt(pszColor+1);
-                    sColor.green= msHexToInt(pszColor+3);
-                    sColor.blue = msHexToInt(pszColor+5);
-
-                    /* pszQuantity may be integer or float */
-                    pch=strchr(pszQuantity,'.');
-                    if (pch==NULL) {
-                        snprintf(szExpression, sizeof(szExpression), "([pixel] = %d)", atoi(pszQuantity));
-                    } else {
-                        snprintf(szExpression, sizeof(szExpression), "([pixel] = %f)", atof(pszQuantity));
-                    }
 
-                    if (msGrowLayerClasses(psLayer) == NULL)
-                      return MS_FAILURE;
-                    else
-                    {
-                        initClass(psLayer->class[psLayer->numclasses]);
-                        psLayer->numclasses++;
-                        nClassId = psLayer->numclasses-1;
-                        msMaybeAllocateClassStyle(psLayer->class[nClassId], 0);
-                        if (pszLabel)
-                          psLayer->class[nClassId]->name = msStrdup(pszLabel);
-                        else
-                          psLayer->class[nClassId]->name = msStrdup(pszQuantity);
-                        psLayer->class[nClassId]->numstyles = 1;
-                        psLayer->class[nClassId]->styles[0]->color.red = 
-                          sColor.red;
-                        psLayer->class[nClassId]->styles[0]->color.green = 
-                          sColor.green;
-                        psLayer->class[nClassId]->styles[0]->color.blue = 
-                          sColor.blue;
-
-                        if (psLayer->classitem && 
-                            strcasecmp(psLayer->classitem, "[pixel]") != 0)
-                          free(psLayer->classitem);
-                        psLayer->classitem = msStrdup("[pixel]");
-
-                        msLoadExpressionString(&psLayer->class[nClassId]->expression,
-                                               szExpression);
-                    }
-                }
+          }
+
+          pszPreviousColor = pszColor;
+          pszPreviousQuality = pszQuantity;
+          pszPreviousLabel = pszLabel;
+
+        }
+        psColorEntry = psColorEntry->psNext;
+      }
+      /* do the last Color Map Entry */
+      if (pszColor && pszQuantity) {
+        if (strlen(pszColor) == 7 && pszColor[0] == '#') {
+          sColor.red = msHexToInt(pszColor+1);
+          sColor.green= msHexToInt(pszColor+3);
+          sColor.blue = msHexToInt(pszColor+5);
+
+          /* pszQuantity may be integer or float */
+          pch=strchr(pszQuantity,'.');
+          if (pch==NULL) {
+            snprintf(szExpression, sizeof(szExpression), "([pixel] = %d)", atoi(pszQuantity));
+          } else {
+            snprintf(szExpression, sizeof(szExpression), "([pixel] = %f)", atof(pszQuantity));
+          }
+
+          if (msGrowLayerClasses(psLayer) == NULL)
+            return MS_FAILURE;
+          else {
+            initClass(psLayer->class[psLayer->numclasses]);
+            psLayer->numclasses++;
+            nClassId = psLayer->numclasses-1;
+            msMaybeAllocateClassStyle(psLayer->class[nClassId], 0);
+            if (pszLabel)
+              psLayer->class[nClassId]->name = msStrdup(pszLabel);
+            else
+              psLayer->class[nClassId]->name = msStrdup(pszQuantity);
+            psLayer->class[nClassId]->numstyles = 1;
+            psLayer->class[nClassId]->styles[0]->color.red =
+                  sColor.red;
+          psLayer->class[nClassId]->styles[0]->color.green =
+                  sColor.green;
+          psLayer->class[nClassId]->styles[0]->color.blue =
+                  sColor.blue;
+
+            if (psLayer->classitem &&
+                strcasecmp(psLayer->classitem, "[pixel]") != 0)
+              free(psLayer->classitem);
+            psLayer->classitem = msStrdup("[pixel]");
+
+            msLoadExpressionString(&psLayer->class[nClassId]->expression,
+                                   szExpression);
+          }
+        }
+      }
+    } else if ((psCategorize = CPLGetXMLNode(psColorMap, "Categorize"))) {
+      char** papszValues = (char **)malloc(sizeof(char*)*nMaxValues);
+      char** papszThresholds = (char **)malloc(sizeof(char*)*nMaxThreshold);
+      psNode =  CPLGetXMLNode(psCategorize, "Value");
+      while (psNode && psNode->pszValue &&
+             psNode->psChild && psNode->psChild->pszValue)
+
+      {
+        if (strcasecmp(psNode->pszValue, "Value") == 0) {
+          papszValues[nValues] =  psNode->psChild->pszValue;
+          nValues++;
+          if (nValues == nMaxValues) {
+            nMaxValues +=100;
+            papszValues = (char **)realloc(papszValues, sizeof(char*)*nMaxValues);
+          }
+        } else if (strcasecmp(psNode->pszValue, "Threshold") == 0) {
+          papszThresholds[nThresholds] =  psNode->psChild->pszValue;
+          nThresholds++;
+          if (nValues == nMaxThreshold) {
+            nMaxThreshold += 100;
+            papszThresholds = (char **)realloc(papszThresholds, sizeof(char*)*nMaxThreshold);
+          }
+        }
+        psNode = psNode->psNext;
+      }
+
+      if (nValues == nThresholds+1) {
+        /*free existing classes*/
+        for(i=0; i<psLayer->numclasses; i++) {
+          if (psLayer->class[i] != NULL) {
+            psLayer->class[i]->layer=NULL;
+            if ( freeClass(psLayer->class[i]) == MS_SUCCESS ) {
+              msFree(psLayer->class[i]);
+              psLayer->class[i]=NULL;
             }
+          }
         }
-        else if ((psCategorize = CPLGetXMLNode(psColorMap, "Categorize")))
-        {
-            papszValues = (char **)malloc(sizeof(char*)*nMaxValues);
-            papszThresholds = (char **)malloc(sizeof(char*)*nMaxThreshold);
-            psNode =  CPLGetXMLNode(psCategorize, "Value");
-            while (psNode && psNode->pszValue &&
-                   psNode->psChild && psNode->psChild->pszValue)
-                   
-            {
-                if (strcasecmp(psNode->pszValue, "Value") == 0)
-                {
-                    papszValues[nValues] =  psNode->psChild->pszValue;  
-                    nValues++;
-                    if (nValues == nMaxValues)
-                    {
-                        nMaxValues +=100;
-                        papszValues = (char **)realloc(papszValues, sizeof(char*)*nMaxValues);
-                    }
-                }
-                else if (strcasecmp(psNode->pszValue, "Threshold") == 0)
-                {
-                    papszThresholds[nThresholds] =  psNode->psChild->pszValue;
-                    nThresholds++;
-                    if (nValues == nMaxThreshold)
-                    {
-                        nMaxThreshold += 100;
-                        papszThresholds = (char **)realloc(papszThresholds, sizeof(char*)*nMaxThreshold);
-                    }
-                }
-                psNode = psNode->psNext;
+        psLayer->numclasses=0;
+        for (i=0; i<nValues; i++) {
+          pszTmp = (papszValues[i]);
+          if (pszTmp && strlen(pszTmp) == 7 && pszTmp[0] == '#') {
+            sColor.red = msHexToInt(pszTmp+1);
+            sColor.green= msHexToInt(pszTmp+3);
+            sColor.blue = msHexToInt(pszTmp+5);
+            if (i == 0) {
+              if (strchr(papszThresholds[i],'.'))
+                snprintf(szExpression, sizeof(szExpression), "([pixel] < %f)", atof(papszThresholds[i]));
+              else
+                snprintf(szExpression, sizeof(szExpression), "([pixel] < %d)", atoi(papszThresholds[i]));
+
+            } else if (i < nValues-1) {
+              if (strchr(papszThresholds[i],'.'))
+                snprintf(szExpression,  sizeof(szExpression),
+                         "([pixel] >= %f AND [pixel] < %f)",
+                         atof(papszThresholds[i-1]),
+                         atof(papszThresholds[i]));
+              else
+                snprintf(szExpression, sizeof(szExpression),
+                         "([pixel] >= %d AND [pixel] < %d)",
+                         atoi(papszThresholds[i-1]),
+                         atoi(papszThresholds[i]));
+            } else {
+              if (strchr(papszThresholds[i-1],'.'))
+                snprintf(szExpression, sizeof(szExpression), "([pixel] >= %f)", atof(papszThresholds[i-1]));
+              else
+                snprintf(szExpression, sizeof(szExpression), "([pixel] >= %d)", atoi(papszThresholds[i-1]));
             }
-
-            if (nValues == nThresholds+1)
-            {
-                /*free existing classes*/
-                for(i=0;i<psLayer->numclasses;i++) {
-                    if (psLayer->class[i] != NULL) 
-                    {
-                        psLayer->class[i]->layer=NULL;
-                        if ( freeClass(psLayer->class[i]) == MS_SUCCESS ) {
-                            msFree(psLayer->class[i]);
-                            psLayer->class[i]=NULL;
-                        }
-                    }
-                }
-                psLayer->numclasses=0;
-                for (i=0; i<nValues; i++)
-                {
-                    pszTmp = (papszValues[i]);
-                    if (pszTmp && strlen(pszTmp) == 7 && pszTmp[0] == '#')
-                    {
-                        sColor.red = msHexToInt(pszTmp+1);
-                        sColor.green= msHexToInt(pszTmp+3);
-                        sColor.blue = msHexToInt(pszTmp+5);
-                        if (i == 0)
-                        {
-                            if (strchr(papszThresholds[i],'.'))
-                                snprintf(szExpression, sizeof(szExpression), "([pixel] < %f)", atof(papszThresholds[i]));
-                            else
-                                snprintf(szExpression, sizeof(szExpression), "([pixel] < %d)", atoi(papszThresholds[i]));
-                        
-                        }
-                        else if (i < nValues-1)
-                        {
-                            if (strchr(papszThresholds[i],'.'))
-                              snprintf(szExpression,  sizeof(szExpression),
-                                       "([pixel] >= %f AND [pixel] < %f)",
-                                       atof(papszThresholds[i-1]), 
-                                       atof(papszThresholds[i]));
-                            else
-                              snprintf(szExpression, sizeof(szExpression),
-                                       "([pixel] >= %d AND [pixel] < %d)",
-                                       atoi(papszThresholds[i-1]), 
-                                       atoi(papszThresholds[i]));
-                        }
-                        else
-                        {
-                            if (strchr(papszThresholds[i-1],'.'))
-                                snprintf(szExpression, sizeof(szExpression), "([pixel] >= %f)", atof(papszThresholds[i-1]));
-                            else
-                                snprintf(szExpression, sizeof(szExpression), "([pixel] >= %d)", atoi(papszThresholds[i-1]));
-                        }
-                        if (msGrowLayerClasses(psLayer))
-                        {
-                            initClass(psLayer->class[psLayer->numclasses]);
-                            psLayer->numclasses++;
-                            nClassId = psLayer->numclasses-1;
-                            msMaybeAllocateClassStyle(psLayer->class[nClassId], 0);
-                            psLayer->class[nClassId]->numstyles = 1;
-                            psLayer->class[nClassId]->styles[0]->color.red = 
-                              sColor.red;
-                            psLayer->class[nClassId]->styles[0]->color.green = 
-                              sColor.green;
-                            psLayer->class[nClassId]->styles[0]->color.blue = 
-                              sColor.blue;
-                            if (psLayer->classitem && 
-                                strcasecmp(psLayer->classitem, "[pixel]") != 0)
-                              free(psLayer->classitem);
-                            psLayer->classitem = msStrdup("[pixel]");
-                            msLoadExpressionString(&psLayer->class[nClassId]->expression,
-                                                   szExpression);
-                        }
-                        
-                    }
-                }
+            if (msGrowLayerClasses(psLayer)) {
+              initClass(psLayer->class[psLayer->numclasses]);
+              psLayer->numclasses++;
+              nClassId = psLayer->numclasses-1;
+              msMaybeAllocateClassStyle(psLayer->class[nClassId], 0);
+              psLayer->class[nClassId]->numstyles = 1;
+              psLayer->class[nClassId]->styles[0]->color.red =
+                    sColor.red;
+            psLayer->class[nClassId]->styles[0]->color.green =
+                    sColor.green;
+            psLayer->class[nClassId]->styles[0]->color.blue =
+                    sColor.blue;
+              if (psLayer->classitem &&
+                  strcasecmp(psLayer->classitem, "[pixel]") != 0)
+                free(psLayer->classitem);
+              psLayer->classitem = msStrdup("[pixel]");
+              msLoadExpressionString(&psLayer->class[nClassId]->expression,
+                                     szExpression);
             }
-            free(papszValues);
-            free(papszThresholds);
 
-            
-        } 
-        else
-        {
-            msSetError(MS_WMSERR, "Invalid SLD document. msSLDParseRaster", "");
-            return MS_FAILURE;
+          }
         }
+      }
+      free(papszValues);
+      free(papszThresholds);
+
+
+    } else {
+      msSetError(MS_WMSERR, "Invalid SLD document. msSLDParseRaster", "");
+      return MS_FAILURE;
     }
+  }
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 /************************************************************************/
 /*                           msSLDParseTextParams                       */
 /*                                                                      */
 /*      Parse text paramaters like font, placement and color.           */
 /************************************************************************/
-int msSLDParseTextParams(CPLXMLNode *psRoot, layerObj *psLayer, 
+int msSLDParseTextParams(CPLXMLNode *psRoot, layerObj *psLayer,
                          classObj *psClass)
 {
-    char szFontName[100];
-    double  dfFontSize = 10;
-    int bFontSet = 0;
-
-    CPLXMLNode *psLabel=NULL, *psFont=NULL;
-    CPLXMLNode *psCssParam = NULL;
-    char *pszName=NULL, *pszFontFamily=NULL, *pszFontStyle=NULL;
-    char *pszFontWeight=NULL; 
-    CPLXMLNode *psLabelPlacement=NULL, *psPointPlacement=NULL, *psLinePlacement=NULL;
-    CPLXMLNode *psFill = NULL, *psPropertyName=NULL, *psHalo=NULL, *psHaloRadius=NULL, *psHaloFill=NULL;
-    int nLength = 0;
-    char *pszColor = NULL;
-    /* char *pszItem = NULL; */
-    CPLXMLNode *psTmpNode = NULL;
-    char *pszClassText = NULL;
-    char szTmp[100];
-
-    szFontName[0]='\0';
-
-    if (!psRoot || !psClass || !psLayer)
-        return MS_FAILURE;
-    
-        /*set the angle by default to auto. the angle can be
-          modified Label Placement #2806*/
-        psClass->label.anglemode = MS_AUTO;
-
-
-        /* label  */
-        /* support literal expression  and  propertyname 
-         - <TextSymbolizer><Label>MY_COLUMN</Label>
-         - <TextSymbolizer><Label><ogc:PropertyName>MY_COLUMN</ogc:PropertyName></Label>
-        Bug 1857 */
-        psLabel = CPLGetXMLNode(psRoot, "Label");
-        if (psLabel )
-        {
-            psTmpNode = psLabel->psChild;
-            psPropertyName = CPLGetXMLNode(psLabel, "PropertyName");
-            if (psPropertyName)
-            {
-                while (psTmpNode)
-                {
-                    /* open bracket to get valid expression */
-                    if (pszClassText == NULL)
-                      pszClassText = msStringConcatenate(pszClassText, "(");
-                    
-                    if (psTmpNode->eType == CXT_Text && psTmpNode->pszValue)
-                    {
-                        pszClassText = msStringConcatenate(pszClassText, psTmpNode->pszValue);
-                    }
-                    else if (psTmpNode->eType == CXT_Element && 
-                             strcasecmp(psTmpNode->pszValue,"PropertyName") ==0 &&
-                             CPLGetXMLValue(psTmpNode, NULL, NULL))
-                    {
-                        snprintf(szTmp, sizeof(szTmp), "\"[%s]\"", CPLGetXMLValue(psTmpNode, NULL, NULL));
-                        pszClassText = msStringConcatenate(pszClassText, szTmp);
-                    }
-                    psTmpNode = psTmpNode->psNext;
-                
-                }
-                /* close bracket to get valid expression */
-                if (pszClassText != NULL)
-                  pszClassText = msStringConcatenate(pszClassText, ")");
-            }
-            else
-            {
-                /* supports  - <TextSymbolizer><Label>MY_COLUMN</Label> */
-                if (psLabel->psChild && psLabel->psChild->pszValue)
-                {
-                    pszClassText = msStringConcatenate(pszClassText, "(\"[");
-                    pszClassText = msStringConcatenate(pszClassText, psLabel->psChild->pszValue);
-                    pszClassText = msStringConcatenate(pszClassText, "]\")");
-                }
-            }
-            
-            if (pszClassText) /* pszItem) */
-            {
-                
-                msLoadExpressionString(&psClass->text, pszClassText);
-                free(pszClassText);
-
-                /* font */
-                psFont = CPLGetXMLNode(psRoot, "Font");
-                if (psFont)
-                {
-                    psCssParam =  CPLGetXMLNode(psFont, "CssParameter");
-                    /*sld 1.1 used SvgParameter*/ 
-                    if (psCssParam == NULL)
-                      psCssParam =  CPLGetXMLNode(psFont, "SvgParameter");
-
-                    while (psCssParam && psCssParam->pszValue && 
-                           (strcasecmp(psCssParam->pszValue, "CssParameter") == 0 ||
-                            strcasecmp(psCssParam->pszValue, "SvgParameter") == 0))
-                    {
-                        pszName = (char*)CPLGetXMLValue(psCssParam, "name", NULL);
-                        if (pszName)
-                        {
-                            if (strcasecmp(pszName, "font-family") == 0)
-                            {
-                                if(psCssParam->psChild && psCssParam->psChild->psNext && 
-                                  psCssParam->psChild->psNext->pszValue)
-                                  pszFontFamily = psCssParam->psChild->psNext->pszValue;
-                            }
-                            /* normal, italic, oblique */
-                            else if (strcasecmp(pszName, "font-style") == 0)
-                            {
-                                if(psCssParam->psChild && psCssParam->psChild->psNext && 
-                                   psCssParam->psChild->psNext->pszValue)
-                                  pszFontStyle = psCssParam->psChild->psNext->pszValue;
-                            }
-                            /* normal or bold */
-                            else if (strcasecmp(pszName, "font-weight") == 0)
-                            {
-                                 if(psCssParam->psChild && psCssParam->psChild->psNext && 
-                                   psCssParam->psChild->psNext->pszValue)
-                                  pszFontWeight = psCssParam->psChild->psNext->pszValue;
-                            }
-                            /* default is 10 pix */
-                            else if (strcasecmp(pszName, "font-size") == 0)
-                            {
-
-                                 if(psCssParam->psChild && psCssParam->psChild->psNext && 
-                                    psCssParam->psChild->psNext->pszValue)
-                                   dfFontSize = atof(psCssParam->psChild->psNext->pszValue); 
-                                 if (dfFontSize <=0.0)
-                                   dfFontSize = 10.0;
-                            }
-                        }
-                        psCssParam = psCssParam->psNext;
-                    }
-                }
-/* -------------------------------------------------------------------- */
-/*      build the font name using the font font-family, font-style      */
-/*      and font-weight. The name building uses a - between these       */
-/*      parameters and the resulting name is compared to the list of    */
-/*      available fonts. If the name exists, it will be used else we    */
-/*      go to the bitmap fonts.                                         */
-/* -------------------------------------------------------------------- */
-                if (pszFontFamily)
-                {
-                    snprintf(szFontName, sizeof(szFontName), "%s", pszFontFamily);
-                    if (pszFontWeight && strcasecmp(pszFontWeight, "normal") != 0)
-                    {
-                        strlcat(szFontName, "-", sizeof(szFontName));
-                        strlcat(szFontName, pszFontWeight, sizeof(szFontName));
-                    }
-                    if (pszFontStyle && strcasecmp(pszFontStyle, "normal") != 0)
-                    {
-                        strlcat(szFontName, "-", sizeof(szFontName));
-                        strlcat(szFontName, pszFontStyle, sizeof(szFontName));
-                    }
-                        
-                    if ((msLookupHashTable(&(psLayer->map->fontset.fonts), szFontName) !=NULL))
-                    {
-                        bFontSet = 1;
-                        psClass->label.font = msStrdup(szFontName);
-                        psClass->label.type = MS_TRUETYPE;
-                        psClass->label.size = dfFontSize;
-                    }
-                }       
-                if (!bFontSet)
-                {
-                    psClass->label.type = MS_BITMAP;
-                    psClass->label.size = MS_MEDIUM;
-                }
-/* -------------------------------------------------------------------- */
-/*      parse the label placement.                                      */
-/* -------------------------------------------------------------------- */
-                psLabelPlacement = CPLGetXMLNode(psRoot, "LabelPlacement");
-                if (psLabelPlacement)
-                {
-                    psPointPlacement = CPLGetXMLNode(psLabelPlacement, 
-                                                     "PointPlacement");
-                    psLinePlacement = CPLGetXMLNode(psLabelPlacement, 
-                                                     "LinePlacement");
-                    if (psPointPlacement)
-                      ParseTextPointPlacement(psPointPlacement, psClass);
-                    if (psLinePlacement)
-                      ParseTextLinePlacement(psLinePlacement, psClass);
-                }
-
-/* -------------------------------------------------------------------- */
-/*      parse the halo parameter.                                       */
-/* -------------------------------------------------------------------- */
-                psHalo = CPLGetXMLNode(psRoot, "Halo");
-                if (psHalo)
-                {
-                    psHaloRadius =  CPLGetXMLNode(psHalo, "Radius");
-                    if (psHaloRadius && psHaloRadius->psChild && psHaloRadius->psChild->pszValue)
-                      psClass->label.outlinewidth = atoi(psHaloRadius->psChild->pszValue);
-
-                    psHaloFill =  CPLGetXMLNode(psHalo, "Fill");
-                    if (psHaloFill)
-                    {
-                        psCssParam =  CPLGetXMLNode(psHaloFill, "CssParameter");
-                        /*sld 1.1 used SvgParameter*/ 
-                        if (psCssParam == NULL)
-                          psCssParam =  CPLGetXMLNode(psHaloFill, "SvgParameter");
-
-                        while (psCssParam && psCssParam->pszValue && 
-                               (strcasecmp(psCssParam->pszValue, "CssParameter") == 0 ||
-                                strcasecmp(psCssParam->pszValue, "SvgParameter") == 0))
-                        {
-                            pszName = (char*)CPLGetXMLValue(psCssParam, "name", NULL);
-                            if (pszName)
-                            {
-                                if (strcasecmp(pszName, "fill") == 0)
-                                {
-                                    if(psCssParam->psChild && psCssParam->psChild->psNext && 
-                                       psCssParam->psChild->psNext->pszValue)
-                                      pszColor = psCssParam->psChild->psNext->pszValue;
-
-                                    if (pszColor)
-                                    {
-                                        nLength = strlen(pszColor);
-                                        /* expecting hexadecimal ex : #aaaaff */
-                                        if (nLength == 7 && pszColor[0] == '#')
-                                        {
-                                            psClass->label.outlinecolor.red = msHexToInt(pszColor+1);
-                                            psClass->label.outlinecolor.green = msHexToInt(pszColor+3);
-                                            psClass->label.outlinecolor.blue = msHexToInt(pszColor+5);
-                                        }
-                                    }
-                                }
-                            }
-                            psCssParam = psCssParam->psNext;
-                        }
+  char szFontName[100];
+  double  dfFontSize = 10;
+  int bFontSet = 0;
+
+  CPLXMLNode *psLabel=NULL, *psFont=NULL;
+  CPLXMLNode *psCssParam = NULL;
+  char *pszName=NULL, *pszFontFamily=NULL, *pszFontStyle=NULL;
+  char *pszFontWeight=NULL;
+  CPLXMLNode *psLabelPlacement=NULL, *psPointPlacement=NULL, *psLinePlacement=NULL;
+  CPLXMLNode *psFill = NULL, *psPropertyName=NULL, *psHalo=NULL, *psHaloRadius=NULL, *psHaloFill=NULL;
+  int nLength = 0;
+  char *pszColor = NULL;
+  /* char *pszItem = NULL; */
+  CPLXMLNode *psTmpNode = NULL;
+  char *pszClassText = NULL;
+  char szTmp[100];
+  labelObj *psLabelObj = NULL;
+  szFontName[0]='\0';
+
+  if (!psRoot || !psClass || !psLayer)
+    return MS_FAILURE;
 
-                    }
-                    
-                }
-/* -------------------------------------------------------------------- */
-/*      Parse the color                                                 */
-/* -------------------------------------------------------------------- */
-                psFill = CPLGetXMLNode(psRoot, "Fill");
-                if (psFill)
-                {
-                    psCssParam =  CPLGetXMLNode(psFill, "CssParameter");
-                     /*sld 1.1 used SvgParameter*/ 
-                    if (psCssParam == NULL)
-                      psCssParam =  CPLGetXMLNode(psFill, "SvgParameter");
-
-                    while (psCssParam && psCssParam->pszValue && 
-                           (strcasecmp(psCssParam->pszValue, "CssParameter") == 0 ||
-                            strcasecmp(psCssParam->pszValue, "SvgParameter") == 0))
-                    {   
-                        pszName = (char*)CPLGetXMLValue(psCssParam, "name", NULL);
-                        if (pszName)
-                        {
-                            if (strcasecmp(pszName, "fill") == 0)
-                            {
-                                if(psCssParam->psChild && psCssParam->psChild->psNext && 
-                                   psCssParam->psChild->psNext->pszValue)
-                                  pszColor = psCssParam->psChild->psNext->pszValue;
-
-                                if (pszColor)
-                                {
-                                    nLength = strlen(pszColor);
-                                    /* expecting hexadecimal ex : #aaaaff */
-                                    if (nLength == 7 && pszColor[0] == '#')
-                                    {
-                                        psClass->label.color.red = msHexToInt(pszColor+1);
-                                        psClass->label.color.green = msHexToInt(pszColor+3);
-                                        psClass->label.color.blue = msHexToInt(pszColor+5);
-                                    }
-                                }
-                            }
-                        }
-                        psCssParam = psCssParam->psNext;
-                    }
-                }
-            
-            }/* labelitem */
+  if(psClass->numlabels == 0) {
+    if(msGrowClassLabels(psClass) == NULL) return(MS_FAILURE);
+    initLabel(psClass->labels[0]);
+    psClass->numlabels++;
+  }
+  psLabelObj = psClass->labels[0];
+
+  /*set the angle by default to auto. the angle can be
+    modified Label Placement #2806*/
+  psLabelObj->anglemode = MS_AUTO;
+
+
+  /* label  */
+  /* support literal expression  and  propertyname
+   - <TextSymbolizer><Label>MY_COLUMN</Label>
+   - <TextSymbolizer><Label><ogc:PropertyName>MY_COLUMN</ogc:PropertyName></Label>
+  Bug 1857 */
+  psLabel = CPLGetXMLNode(psRoot, "Label");
+  if (psLabel ) {
+    psTmpNode = psLabel->psChild;
+    psPropertyName = CPLGetXMLNode(psLabel, "PropertyName");
+    if (psPropertyName) {
+      while (psTmpNode) {
+        /* open bracket to get valid expression */
+        if (pszClassText == NULL)
+          pszClassText = msStringConcatenate(pszClassText, "(");
+
+        if (psTmpNode->eType == CXT_Text && psTmpNode->pszValue) {
+          pszClassText = msStringConcatenate(pszClassText, psTmpNode->pszValue);
+        } else if (psTmpNode->eType == CXT_Element &&
+                   strcasecmp(psTmpNode->pszValue,"PropertyName") ==0 &&
+                   CPLGetXMLValue(psTmpNode, NULL, NULL)) {
+          snprintf(szTmp, sizeof(szTmp), "\"[%s]\"", CPLGetXMLValue(psTmpNode, NULL, NULL));
+          pszClassText = msStringConcatenate(pszClassText, szTmp);
         }
+        psTmpNode = psTmpNode->psNext;
+
+      }
+      /* close bracket to get valid expression */
+      if (pszClassText != NULL)
+        pszClassText = msStringConcatenate(pszClassText, ")");
+    } else {
+      /* supports  - <TextSymbolizer><Label>MY_COLUMN</Label> */
+      if (psLabel->psChild && psLabel->psChild->pszValue) {
+        pszClassText = msStringConcatenate(pszClassText, "(\"[");
+        pszClassText = msStringConcatenate(pszClassText, psLabel->psChild->pszValue);
+        pszClassText = msStringConcatenate(pszClassText, "]\")");
+      }
+    }
 
-        return MS_SUCCESS;
-}
-
-/************************************************************************/
-/*                         ParseTextPointPlacement                      */
-/*                                                                      */
-/*      point placement node for the text symbolizer.                  */
-/************************************************************************/
-int ParseTextPointPlacement(CPLXMLNode *psRoot, classObj *psClass)
-{
-    CPLXMLNode *psAnchor, *psAnchorX, *psAnchorY;
-    double dfAnchorX=0, dfAnchorY=0;
-    CPLXMLNode *psDisplacement, *psDisplacementX, *psDisplacementY;
-    CPLXMLNode *psRotation=NULL, *psPropertyName=NULL;
-    char szTmp[100];
+    if (pszClassText) { /* pszItem) */
 
-    if (!psRoot || !psClass)
-        return MS_FAILURE;
+      msLoadExpressionString(&psClass->text, pszClassText);
+      free(pszClassText);
 
-        /* init the label with the default position */
-        psClass->label.position = MS_CL;
+      /* font */
+      psFont = CPLGetXMLNode(psRoot, "Font");
+      if (psFont) {
+        psCssParam =  CPLGetXMLNode(psFont, "CssParameter");
+        /*sld 1.1 used SvgParameter*/
+        if (psCssParam == NULL)
+          psCssParam =  CPLGetXMLNode(psFont, "SvgParameter");
 
-/* -------------------------------------------------------------------- */
-/*      parse anchor point. see function msSLDParseTextSymbolizer       */
-/*      for documentation.                                              */
-/* -------------------------------------------------------------------- */
-        psAnchor = CPLGetXMLNode(psRoot, "AnchorPoint");
-        if (psAnchor)
-        {
-            psAnchorX = CPLGetXMLNode(psAnchor, "AnchorPointX");
-            psAnchorY = CPLGetXMLNode(psAnchor, "AnchorPointY");
-            /* psCssParam->psChild->psNext->pszValue) */
-            if (psAnchorX &&
-                psAnchorX->psChild && 
-                psAnchorX->psChild->pszValue &&
-                psAnchorY && 
-                psAnchorY->psChild && 
-                psAnchorY->psChild->pszValue)
-            {
-                dfAnchorX = atof(psAnchorX->psChild->pszValue);
-                dfAnchorY = atof(psAnchorY->psChild->pszValue);
-
-                if ((dfAnchorX == 0 || dfAnchorX == 0.5 || dfAnchorX == 1) &&
-                    (dfAnchorY == 0 || dfAnchorY == 0.5 || dfAnchorY == 1))
-                {
-                    if (dfAnchorX == 0 && dfAnchorY == 0)
-                      psClass->label.position = MS_LL;
-                    if (dfAnchorX == 0 && dfAnchorY == 0.5)
-                      psClass->label.position = MS_CL;
-                    if (dfAnchorX == 0 && dfAnchorY == 1)
-                      psClass->label.position = MS_UL;
-
-                    if (dfAnchorX == 0.5 && dfAnchorY == 0)
-                      psClass->label.position = MS_LC;
-                    if (dfAnchorX == 0.5 && dfAnchorY == 0.5)
-                      psClass->label.position = MS_CC;
-                    if (dfAnchorX == 0.5 && dfAnchorY == 1)
-                      psClass->label.position = MS_UC;
-
-                    if (dfAnchorX == 1 && dfAnchorY == 0)
-                      psClass->label.position = MS_LR;
-                    if (dfAnchorX == 1 && dfAnchorY == 0.5)
-                      psClass->label.position = MS_CR;
-                    if (dfAnchorX == 1 && dfAnchorY == 1)
-                      psClass->label.position = MS_UR;
-                }
+        while (psCssParam && psCssParam->pszValue &&
+               (strcasecmp(psCssParam->pszValue, "CssParameter") == 0 ||
+                strcasecmp(psCssParam->pszValue, "SvgParameter") == 0)) {
+          pszName = (char*)CPLGetXMLValue(psCssParam, "name", NULL);
+          if (pszName) {
+            if (strcasecmp(pszName, "font-family") == 0) {
+              if(psCssParam->psChild && psCssParam->psChild->psNext &&
+                  psCssParam->psChild->psNext->pszValue)
+                pszFontFamily = psCssParam->psChild->psNext->pszValue;
             }
+            /* normal, italic, oblique */
+            else if (strcasecmp(pszName, "font-style") == 0) {
+              if(psCssParam->psChild && psCssParam->psChild->psNext &&
+                  psCssParam->psChild->psNext->pszValue)
+                pszFontStyle = psCssParam->psChild->psNext->pszValue;
+            }
+            /* normal or bold */
+            else if (strcasecmp(pszName, "font-weight") == 0) {
+              if(psCssParam->psChild && psCssParam->psChild->psNext &&
+                  psCssParam->psChild->psNext->pszValue)
+                pszFontWeight = psCssParam->psChild->psNext->pszValue;
+            }
+            /* default is 10 pix */
+            else if (strcasecmp(pszName, "font-size") == 0) {
+
+              if(psCssParam->psChild && psCssParam->psChild->psNext &&
+                  psCssParam->psChild->psNext->pszValue)
+                dfFontSize = atof(psCssParam->psChild->psNext->pszValue);
+              if (dfFontSize <=0.0)
+                dfFontSize = 10.0;
+            }
+          }
+          psCssParam = psCssParam->psNext;
+        }
+      }
+      /* -------------------------------------------------------------------- */
+      /*      build the font name using the font font-family, font-style      */
+      /*      and font-weight. The name building uses a - between these       */
+      /*      parameters and the resulting name is compared to the list of    */
+      /*      available fonts. If the name exists, it will be used else we    */
+      /*      go to the bitmap fonts.                                         */
+      /* -------------------------------------------------------------------- */
+      if (pszFontFamily) {
+        snprintf(szFontName, sizeof(szFontName), "%s", pszFontFamily);
+        if (pszFontWeight && strcasecmp(pszFontWeight, "normal") != 0) {
+          strlcat(szFontName, "-", sizeof(szFontName));
+          strlcat(szFontName, pszFontWeight, sizeof(szFontName));
+        }
+        if (pszFontStyle && strcasecmp(pszFontStyle, "normal") != 0) {
+          strlcat(szFontName, "-", sizeof(szFontName));
+          strlcat(szFontName, pszFontStyle, sizeof(szFontName));
         }
 
-/* -------------------------------------------------------------------- */
-/*      Parse displacement                                              */
-/* -------------------------------------------------------------------- */
-        psDisplacement = CPLGetXMLNode(psRoot, "Displacement");
-        if (psDisplacement)
-        {
-            psDisplacementX = CPLGetXMLNode(psDisplacement, "DisplacementX");
-            psDisplacementY = CPLGetXMLNode(psDisplacement, "DisplacementY");
-            /* psCssParam->psChild->psNext->pszValue) */
-            if (psDisplacementX &&
-                psDisplacementX->psChild && 
-                psDisplacementX->psChild->pszValue &&
-                psDisplacementY && 
-                psDisplacementY->psChild && 
-                psDisplacementY->psChild->pszValue)
-            {
-                psClass->label.offsetx = atoi(psDisplacementX->psChild->pszValue);
-                psClass->label.offsety = atoi(psDisplacementY->psChild->pszValue);
+        if ((msLookupHashTable(&(psLayer->map->fontset.fonts), szFontName) !=NULL)) {
+          bFontSet = 1;
+          psLabelObj->font = msStrdup(szFontName);
+          psLabelObj->type = MS_TRUETYPE;
+          psLabelObj->size = dfFontSize;
+        }
+      }
+      if (!bFontSet) {
+        psLabelObj->type = MS_BITMAP;
+        psLabelObj->size = MS_MEDIUM;
+      }
+      /* -------------------------------------------------------------------- */
+      /*      parse the label placement.                                      */
+      /* -------------------------------------------------------------------- */
+      psLabelPlacement = CPLGetXMLNode(psRoot, "LabelPlacement");
+      if (psLabelPlacement) {
+        psPointPlacement = CPLGetXMLNode(psLabelPlacement,
+                                         "PointPlacement");
+        psLinePlacement = CPLGetXMLNode(psLabelPlacement,
+                                        "LinePlacement");
+        if (psPointPlacement)
+          ParseTextPointPlacement(psPointPlacement, psClass);
+        if (psLinePlacement)
+          ParseTextLinePlacement(psLinePlacement, psClass);
+      }
+
+      /* -------------------------------------------------------------------- */
+      /*      parse the halo parameter.                                       */
+      /* -------------------------------------------------------------------- */
+      psHalo = CPLGetXMLNode(psRoot, "Halo");
+      if (psHalo) {
+        psHaloRadius =  CPLGetXMLNode(psHalo, "Radius");
+        if (psHaloRadius && psHaloRadius->psChild && psHaloRadius->psChild->pszValue)
+          psLabelObj->outlinewidth = atoi(psHaloRadius->psChild->pszValue);
+
+        psHaloFill =  CPLGetXMLNode(psHalo, "Fill");
+        if (psHaloFill) {
+          psCssParam =  CPLGetXMLNode(psHaloFill, "CssParameter");
+          /*sld 1.1 used SvgParameter*/
+          if (psCssParam == NULL)
+            psCssParam =  CPLGetXMLNode(psHaloFill, "SvgParameter");
+
+          while (psCssParam && psCssParam->pszValue &&
+                 (strcasecmp(psCssParam->pszValue, "CssParameter") == 0 ||
+                  strcasecmp(psCssParam->pszValue, "SvgParameter") == 0)) {
+            pszName = (char*)CPLGetXMLValue(psCssParam, "name", NULL);
+            if (pszName) {
+              if (strcasecmp(pszName, "fill") == 0) {
+                if(psCssParam->psChild && psCssParam->psChild->psNext &&
+                    psCssParam->psChild->psNext->pszValue)
+                  pszColor = psCssParam->psChild->psNext->pszValue;
+
+                if (pszColor) {
+                  nLength = strlen(pszColor);
+                  /* expecting hexadecimal ex : #aaaaff */
+                  if (nLength == 7 && pszColor[0] == '#') {
+                    psLabelObj->outlinecolor.red = msHexToInt(pszColor+1);
+                    psLabelObj->outlinecolor.green = msHexToInt(pszColor+3);
+                    psLabelObj->outlinecolor.blue = msHexToInt(pszColor+5);
+                  }
+                }
+              }
             }
+            psCssParam = psCssParam->psNext;
+          }
+
         }
 
-/* -------------------------------------------------------------------- */
-/*      parse rotation.                                                 */
-/* -------------------------------------------------------------------- */
-        psRotation = CPLGetXMLNode(psRoot, "Rotation");
-        if (psRotation)
-        {
-            psPropertyName = CPLGetXMLNode(psRotation, "PropertyName");
-            if (psPropertyName)
-            {   
-                snprintf(szTmp, sizeof(szTmp), "%s", CPLGetXMLValue(psPropertyName, NULL, NULL));
-                psClass->label.bindings[MS_LABEL_BINDING_ANGLE].item = msStrdup(szTmp);
-                psClass->label.numbindings++;
-            }
-            else
-            {
-                if (psRotation->psChild && psRotation->psChild->pszValue)
-                  psClass->label.angle = atof(psRotation->psChild->pszValue);
+      }
+      /* -------------------------------------------------------------------- */
+      /*      Parse the color                                                 */
+      /* -------------------------------------------------------------------- */
+      psFill = CPLGetXMLNode(psRoot, "Fill");
+      if (psFill) {
+        psCssParam =  CPLGetXMLNode(psFill, "CssParameter");
+        /*sld 1.1 used SvgParameter*/
+        if (psCssParam == NULL)
+          psCssParam =  CPLGetXMLNode(psFill, "SvgParameter");
+
+        while (psCssParam && psCssParam->pszValue &&
+               (strcasecmp(psCssParam->pszValue, "CssParameter") == 0 ||
+                strcasecmp(psCssParam->pszValue, "SvgParameter") == 0)) {
+          pszName = (char*)CPLGetXMLValue(psCssParam, "name", NULL);
+          if (pszName) {
+            if (strcasecmp(pszName, "fill") == 0) {
+              if(psCssParam->psChild && psCssParam->psChild->psNext &&
+                  psCssParam->psChild->psNext->pszValue)
+                pszColor = psCssParam->psChild->psNext->pszValue;
+
+              if (pszColor) {
+                nLength = strlen(pszColor);
+                /* expecting hexadecimal ex : #aaaaff */
+                if (nLength == 7 && pszColor[0] == '#') {
+                  psLabelObj->color.red = msHexToInt(pszColor+1);
+                  psLabelObj->color.green = msHexToInt(pszColor+3);
+                  psLabelObj->color.blue = msHexToInt(pszColor+5);
+                }
+              }
             }
+          }
+          psCssParam = psCssParam->psNext;
         }
-        
-        return MS_SUCCESS;
+      }
+
+    }/* labelitem */
+  }
+
+  return MS_SUCCESS;
+}
+
+/************************************************************************/
+/*                         ParseTextPointPlacement                      */
+/*                                                                      */
+/*      point placement node for the text symbolizer.                  */
+/************************************************************************/
+int ParseTextPointPlacement(CPLXMLNode *psRoot, classObj *psClass)
+{
+  CPLXMLNode *psAnchor, *psAnchorX, *psAnchorY;
+  double dfAnchorX=0, dfAnchorY=0;
+  CPLXMLNode *psDisplacement, *psDisplacementX, *psDisplacementY;
+  CPLXMLNode *psRotation=NULL, *psPropertyName=NULL;
+  char szTmp[100];
+  labelObj *psLabelObj = NULL;
+
+  if (!psRoot || !psClass)
+    return MS_FAILURE;
+  if(psClass->numlabels == 0) {
+    if(msGrowClassLabels(psClass) == NULL) return(MS_FAILURE);
+    initLabel(psClass->labels[0]);
+    psClass->numlabels++;
+  }
+  psLabelObj = psClass->labels[0];
+
+  /* init the label with the default position */
+  psLabelObj->position = MS_CL;
+
+  /* -------------------------------------------------------------------- */
+  /*      parse anchor point. see function msSLDParseTextSymbolizer       */
+  /*      for documentation.                                              */
+  /* -------------------------------------------------------------------- */
+  psAnchor = CPLGetXMLNode(psRoot, "AnchorPoint");
+  if (psAnchor) {
+    psAnchorX = CPLGetXMLNode(psAnchor, "AnchorPointX");
+    psAnchorY = CPLGetXMLNode(psAnchor, "AnchorPointY");
+    /* psCssParam->psChild->psNext->pszValue) */
+    if (psAnchorX &&
+        psAnchorX->psChild &&
+        psAnchorX->psChild->pszValue &&
+        psAnchorY &&
+        psAnchorY->psChild &&
+        psAnchorY->psChild->pszValue) {
+      dfAnchorX = atof(psAnchorX->psChild->pszValue);
+      dfAnchorY = atof(psAnchorY->psChild->pszValue);
+
+      if ((dfAnchorX == 0 || dfAnchorX == 0.5 || dfAnchorX == 1) &&
+          (dfAnchorY == 0 || dfAnchorY == 0.5 || dfAnchorY == 1)) {
+        if (dfAnchorX == 0 && dfAnchorY == 0)
+          psLabelObj->position = MS_LL;
+        if (dfAnchorX == 0 && dfAnchorY == 0.5)
+          psLabelObj->position = MS_CL;
+        if (dfAnchorX == 0 && dfAnchorY == 1)
+          psLabelObj->position = MS_UL;
+
+        if (dfAnchorX == 0.5 && dfAnchorY == 0)
+          psLabelObj->position = MS_LC;
+        if (dfAnchorX == 0.5 && dfAnchorY == 0.5)
+          psLabelObj->position = MS_CC;
+        if (dfAnchorX == 0.5 && dfAnchorY == 1)
+          psLabelObj->position = MS_UC;
+
+        if (dfAnchorX == 1 && dfAnchorY == 0)
+          psLabelObj->position = MS_LR;
+        if (dfAnchorX == 1 && dfAnchorY == 0.5)
+          psLabelObj->position = MS_CR;
+        if (dfAnchorX == 1 && dfAnchorY == 1)
+          psLabelObj->position = MS_UR;
+      }
+    }
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Parse displacement                                              */
+  /* -------------------------------------------------------------------- */
+  psDisplacement = CPLGetXMLNode(psRoot, "Displacement");
+  if (psDisplacement) {
+    psDisplacementX = CPLGetXMLNode(psDisplacement, "DisplacementX");
+    psDisplacementY = CPLGetXMLNode(psDisplacement, "DisplacementY");
+    /* psCssParam->psChild->psNext->pszValue) */
+    if (psDisplacementX &&
+        psDisplacementX->psChild &&
+        psDisplacementX->psChild->pszValue &&
+        psDisplacementY &&
+        psDisplacementY->psChild &&
+        psDisplacementY->psChild->pszValue) {
+      psLabelObj->offsetx = atoi(psDisplacementX->psChild->pszValue);
+      psLabelObj->offsety = atoi(psDisplacementY->psChild->pszValue);
+    }
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      parse rotation.                                                 */
+  /* -------------------------------------------------------------------- */
+  psRotation = CPLGetXMLNode(psRoot, "Rotation");
+  if (psRotation) {
+    psPropertyName = CPLGetXMLNode(psRotation, "PropertyName");
+    if (psPropertyName) {
+      snprintf(szTmp, sizeof(szTmp), "%s", CPLGetXMLValue(psPropertyName, NULL, NULL));
+      psLabelObj->bindings[MS_LABEL_BINDING_ANGLE].item = msStrdup(szTmp);
+      psLabelObj->numbindings++;
+    } else {
+      if (psRotation->psChild && psRotation->psChild->pszValue)
+        psLabelObj->angle = atof(psRotation->psChild->pszValue);
+    }
+  }
+
+  return MS_SUCCESS;
 }
 
 /************************************************************************/
@@ -3163,40 +2991,45 @@ int ParseTextPointPlacement(CPLXMLNode *psRoot, classObj *psClass)
 int ParseTextLinePlacement(CPLXMLNode *psRoot, classObj *psClass)
 {
   CPLXMLNode *psOffset = NULL, *psAligned=NULL;
+  labelObj *psLabelObj = NULL;
 
   if (!psRoot || !psClass)
-      return MS_FAILURE;
-
-        /*if there is a line placement, we will assume that the 
-          best setting for mapserver would be for the text to follow
-          the line #2806*/
-        psClass->label.anglemode = MS_FOLLOW;         
+    return MS_FAILURE;
 
-        /*sld 1.1.0 has a parameter IsAligned. default value is true*/
-        psAligned = CPLGetXMLNode(psRoot, "IsAligned");
-        if (psAligned && psAligned->psChild && psAligned->psChild->pszValue && 
-            strcasecmp(psAligned->psChild->pszValue, "false") == 0)
-        {
-            psClass->label.anglemode = MS_NONE;
-        }
-        psOffset = CPLGetXMLNode(psRoot, "PerpendicularOffset");
-        if (psOffset && psOffset->psChild && psOffset->psChild->pszValue)
-        {
-            psClass->label.offsetx = atoi(psOffset->psChild->pszValue);
-            psClass->label.offsety = atoi(psOffset->psChild->pszValue);
-
-            /*if there is a PerpendicularOffset, we will assume that the 
-              best setting for mapserver would be to use angle=0 and the
-              the offset #2806*/
-            /* since sld 1.1.0 introduces the IsAligned parameter, only
-               set the angles if the parameter is not set*/
-            if (!psAligned)
-            {
-                psClass->label.anglemode = MS_NONE;
-            }
-        }
+  if(psClass->numlabels == 0) {
+    if(msGrowClassLabels(psClass) == NULL) return(MS_FAILURE);
+    initLabel(psClass->labels[0]);
+    psClass->numlabels++;
+  }
+  psLabelObj = psClass->labels[0];
+
+  /*if there is a line placement, we will assume that the
+    best setting for mapserver would be for the text to follow
+    the line #2806*/
+  psLabelObj->anglemode = MS_FOLLOW;
+
+  /*sld 1.1.0 has a parameter IsAligned. default value is true*/
+  psAligned = CPLGetXMLNode(psRoot, "IsAligned");
+  if (psAligned && psAligned->psChild && psAligned->psChild->pszValue &&
+      strcasecmp(psAligned->psChild->pszValue, "false") == 0) {
+    psLabelObj->anglemode = MS_NONE;
+  }
+  psOffset = CPLGetXMLNode(psRoot, "PerpendicularOffset");
+  if (psOffset && psOffset->psChild && psOffset->psChild->pszValue) {
+    psLabelObj->offsetx = atoi(psOffset->psChild->pszValue);
+    psLabelObj->offsety = atoi(psOffset->psChild->pszValue);
+
+    /*if there is a PerpendicularOffset, we will assume that the
+      best setting for mapserver would be to use angle=0 and the
+      the offset #2806*/
+    /* since sld 1.1.0 introduces the IsAligned parameter, only
+       set the angles if the parameter is not set*/
+    if (!psAligned) {
+      psLabelObj->anglemode = MS_NONE;
+    }
+  }
 
-        return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 
@@ -3210,17 +3043,16 @@ int ParseTextLinePlacement(CPLXMLNode *psRoot, classObj *psClass)
 /************************************************************************/
 int msSLDSetColorObject(char *psHexColor, colorObj *psColor)
 {
-    if (psHexColor && psColor && strlen(psHexColor)== 7 && 
-        psHexColor[0] == '#')
-    {
-        
-        psColor->red = msHexToInt(psHexColor+1);
-        psColor->green = msHexToInt(psHexColor+3);
-        psColor->blue= msHexToInt(psHexColor+5);
-    }
+  if (psHexColor && psColor && strlen(psHexColor)== 7 &&
+      psHexColor[0] == '#') {
+
+    psColor->red = msHexToInt(psHexColor+1);
+    psColor->green = msHexToInt(psHexColor+3);
+    psColor->blue= msHexToInt(psHexColor+5);
+  }
 
-    return MS_SUCCESS;
-}   
+  return MS_SUCCESS;
+}
 
 #endif
 
@@ -3245,71 +3077,64 @@ char *msSLDGenerateSLD(mapObj *map, int iLayer, const char *pszVersion)
 #ifdef USE_OGR
 
 
-    char szTmp[500];
-    int i = 0;
-    char *pszTmp = NULL;
-    char *pszSLD = NULL;
-    char *schemalocation = NULL;
-    int sld_version = OWS_VERSION_NOTSET;
+  char szTmp[500];
+  int i = 0;
+  char *pszTmp = NULL;
+  char *pszSLD = NULL;
+  char *schemalocation = NULL;
+  int sld_version = OWS_VERSION_NOTSET;
 
-    sld_version = msOWSParseVersionString(pszVersion);
+  sld_version = msOWSParseVersionString(pszVersion);
 
-    if (sld_version == OWS_VERSION_NOTSET || 
-        (sld_version!= OWS_1_0_0 && sld_version!= OWS_1_1_0))
-      sld_version = OWS_1_0_0;
-    
-    if (map)
-    {
-        schemalocation = msEncodeHTMLEntities(msOWSGetSchemasLocation(map));
-        if (sld_version ==  OWS_1_0_0)
-            snprintf(szTmp, sizeof(szTmp), "<StyledLayerDescriptor version=\"1.0.0\" xmlns=\"http://www.opengis.net/sld\" xmlns:gml=\"http://www.opengis.net/gml\" xmlns:ogc=\"http://www.opengis.net/ogc\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.opengis.net/sld %s/sld/1.0.0/StyledLayerDescriptor.xsd\">\n",schemalocation );
-        else
-            snprintf(szTmp, sizeof(szTmp), "<StyledLayerDescriptor version=\"1.1.0\" xsi:schemaLocation=\"http://www.opengis.net/sld %s/sld/1.1.0/StyledLayerDescriptor.xsd\" xmlns=\"http://www.opengis.net/sld\" xmlns:ogc=\"http://www.opengis.net/ogc\" xmlns:se=\"http://www.opengis.net/se\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n", schemalocation);
+  if (sld_version == OWS_VERSION_NOTSET ||
+      (sld_version!= OWS_1_0_0 && sld_version!= OWS_1_1_0))
+    sld_version = OWS_1_0_0;
 
-        free(schemalocation);
+  if (map) {
+    schemalocation = msEncodeHTMLEntities(msOWSGetSchemasLocation(map));
+    if (sld_version ==  OWS_1_0_0)
+      snprintf(szTmp, sizeof(szTmp), "<StyledLayerDescriptor version=\"1.0.0\" xmlns=\"http://www.opengis.net/sld\" xmlns:gml=\"http://www.opengis.net/gml\" xmlns:ogc=\"http://www.opengis.net/ogc\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.opengis.net/sld %s/sld/1.0.0/StyledLayerDescriptor.xsd\">\n",schemalocation );
+    else
+      snprintf(szTmp, sizeof(szTmp), "<StyledLayerDescriptor version=\"1.1.0\" xsi:schemaLocation=\"http://www.opengis.net/sld %s/sld/1.1.0/StyledLayerDescriptor.xsd\" xmlns=\"http://www.opengis.net/sld\" xmlns:ogc=\"http://www.opengis.net/ogc\" xmlns:se=\"http://www.opengis.net/se\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n", schemalocation);
 
-        pszSLD = msStringConcatenate(pszSLD, szTmp);
-        if (iLayer < 0 || iLayer > map->numlayers -1)
-        {
-            for (i=0; i<map->numlayers; i++)
-            {
-                pszTmp = msSLDGenerateSLDLayer(GET_LAYER(map, i), sld_version);
-                if (pszTmp)
-                {
-                    pszSLD= msStringConcatenate(pszSLD, pszTmp);
-                    free(pszTmp);
-                }
-            }
-        }
-        else
-        {
-            pszTmp = msSLDGenerateSLDLayer(GET_LAYER(map, iLayer), sld_version);
-             if (pszTmp)
-             {
-                 pszSLD = msStringConcatenate(pszSLD, pszTmp);
-                 free(pszTmp);
-             }
+    free(schemalocation);
+
+    pszSLD = msStringConcatenate(pszSLD, szTmp);
+    if (iLayer < 0 || iLayer > map->numlayers -1) {
+      for (i=0; i<map->numlayers; i++) {
+        pszTmp = msSLDGenerateSLDLayer(GET_LAYER(map, i), sld_version);
+        if (pszTmp) {
+          pszSLD= msStringConcatenate(pszSLD, pszTmp);
+          free(pszTmp);
         }
-        snprintf(szTmp, sizeof(szTmp), "%s", "</StyledLayerDescriptor>\n");
-        pszSLD = msStringConcatenate(pszSLD, szTmp);
+      }
+    } else {
+      pszTmp = msSLDGenerateSLDLayer(GET_LAYER(map, iLayer), sld_version);
+      if (pszTmp) {
+        pszSLD = msStringConcatenate(pszSLD, pszTmp);
+        free(pszTmp);
+      }
     }
+    snprintf(szTmp, sizeof(szTmp), "%s", "</StyledLayerDescriptor>\n");
+    pszSLD = msStringConcatenate(pszSLD, szTmp);
+  }
 
-    return pszSLD;
+  return pszSLD;
 
 #else
-/* ------------------------------------------------------------------
- * OGR Support not included...
- * ------------------------------------------------------------------ */
+  /* ------------------------------------------------------------------
+   * OGR Support not included...
+   * ------------------------------------------------------------------ */
 
-    msSetError(MS_MISCERR, "OGR support is not available.", "msSLDGenerateSLD()");
-    return NULL;
+  msSetError(MS_MISCERR, "OGR support is not available.", "msSLDGenerateSLD()");
+  return NULL;
 
 #endif /* USE_OGR */
 
 #else
-    msSetError(MS_MISCERR, "OWS support is not available.", 
-               "msSLDGenerateSLDLayer()");
-    return NULL; 
+  msSetError(MS_MISCERR, "OWS support is not available.",
+             "msSLDGenerateSLDLayer()");
+  return NULL;
 
 #endif
 }
@@ -3326,351 +3151,320 @@ char *msSLDGetGraphicSLD(styleObj *psStyle, layerObj *psLayer,
 {
 #if defined(USE_WMS_SVR) || defined (USE_WFS_SVR) || defined (USE_WCS_SVR) || defined(USE_SOS_SVR)
 
-    char *pszSLD = NULL;
-    int nSymbol = -1;
-    symbolObj *psSymbol = NULL;
-    char szTmp[512];
-    char *pszURL = NULL;
-    char szFormat[4];
-    int i = 0, nLength = 0;
-    int bFillColor = 0, bColorAvailable=0;
-    int bGenerateDefaultSymbol = 0;
-    char *pszSymbolName= NULL;
-    char sNameSpace[10];
-    char sCssParam[30];
-
-     sCssParam[0] = '\0';
-    if (nVersion > OWS_1_0_0)
-      strcpy(sCssParam, "se:SvgParameter");
-    else
-      strcpy(sCssParam, "CssParameter");
-
-    sNameSpace[0] = '\0';
-    if (nVersion > OWS_1_0_0)
-      strcpy(sNameSpace, "se:");
+  char *pszSLD = NULL;
+  int nSymbol = -1;
+  symbolObj *psSymbol = NULL;
+  char szTmp[512];
+  char *pszURL = NULL;
+  char szFormat[4];
+  int i = 0, nLength = 0;
+  int bFillColor = 0, bColorAvailable=0;
+  int bGenerateDefaultSymbol = 0;
+  char *pszSymbolName= NULL;
+  char sNameSpace[10];
+  char sCssParam[30];
+
+  sCssParam[0] = '\0';
+  if (nVersion > OWS_1_0_0)
+    strcpy(sCssParam, "se:SvgParameter");
+  else
+    strcpy(sCssParam, "CssParameter");
+
+  sNameSpace[0] = '\0';
+  if (nVersion > OWS_1_0_0)
+    strcpy(sNameSpace, "se:");
+
+  if (psStyle && psLayer && psLayer->map) {
+    nSymbol = -1;
+    if (psStyle->symbol > 0)
+      nSymbol = psStyle->symbol;
+    else if (psStyle->symbolname)
+      nSymbol = msGetSymbolIndex(&psLayer->map->symbolset,
+                                 psStyle->symbolname, MS_FALSE);
 
-    if (psStyle && psLayer && psLayer->map)
-    {
-        nSymbol = -1;
-        if (psStyle->symbol > 0)
-          nSymbol = psStyle->symbol;
-        else if (psStyle->symbolname)
-          nSymbol = msGetSymbolIndex(&psLayer->map->symbolset,
-                                     psStyle->symbolname, MS_FALSE);
+    bGenerateDefaultSymbol = 0;
 
-        bGenerateDefaultSymbol = 0;
+    if (bNeedMarkSybol &&
+        (nSymbol <=0 || nSymbol >=  psLayer->map->symbolset.numsymbols))
+      bGenerateDefaultSymbol = 1;
 
-        if (bNeedMarkSybol && 
-            (nSymbol <=0 || nSymbol >=  psLayer->map->symbolset.numsymbols))
-          bGenerateDefaultSymbol = 1;
+    if (nSymbol > 0 && nSymbol < psLayer->map->symbolset.numsymbols) {
+      psSymbol =  psLayer->map->symbolset.symbol[nSymbol];
+      if (psSymbol->type == MS_SYMBOL_VECTOR ||
+          psSymbol->type == MS_SYMBOL_ELLIPSE) {
+        /* Mark symbol */
+        if (psSymbol->name)
 
-        if (nSymbol > 0 && nSymbol < psLayer->map->symbolset.numsymbols)
         {
-            psSymbol =  psLayer->map->symbolset.symbol[nSymbol];
-            if (psSymbol->type == MS_SYMBOL_VECTOR || 
-                psSymbol->type == MS_SYMBOL_ELLIPSE)
-            {
-                /* Mark symbol */
-                if (psSymbol->name)
-                    
-                {
-                    if (strcasecmp(psSymbol->name, "square") == 0 ||
-                        strcasecmp(psSymbol->name, "circle") == 0 ||
-                        strcasecmp(psSymbol->name, "triangle") == 0 ||
-                        strcasecmp(psSymbol->name, "star") == 0 ||
-                        strcasecmp(psSymbol->name, "cross") == 0 ||
-                        strcasecmp(psSymbol->name, "x") == 0)
-                      pszSymbolName = msStrdup(psSymbol->name);
-                    else if (strncasecmp(psSymbol->name, 
-                                         "sld_mark_symbol_square", 22) == 0)
-                      pszSymbolName = msStrdup("square");
-                    else if (strncasecmp(psSymbol->name, 
-                                         "sld_mark_symbol_triangle", 24) == 0)
-                      pszSymbolName = msStrdup("triangle");
-                    else if (strncasecmp(psSymbol->name, 
-                                         "sld_mark_symbol_circle", 22) == 0)
-                      pszSymbolName = msStrdup("circle");
-                    else if (strncasecmp(psSymbol->name, 
-                                         "sld_mark_symbol_star", 20) == 0)
-                      pszSymbolName = msStrdup("star");
-                    else if (strncasecmp(psSymbol->name, 
-                                         "sld_mark_symbol_cross", 21) == 0)
-                      pszSymbolName = msStrdup("cross");
-                    else if (strncasecmp(psSymbol->name, 
-                                         "sld_mark_symbol_x", 17) == 0)
-                      pszSymbolName = msStrdup("X");
-                             
-
-                   
-                    if (pszSymbolName)
-                    {
-                        colorObj sTmpColor;
-
-                        snprintf(szTmp, sizeof(szTmp), "<%sGraphic>\n", sNameSpace);
-                        pszSLD = msStringConcatenate(pszSLD, szTmp);
-
-                        
-
-                        snprintf(szTmp, sizeof(szTmp), "<%sMark>\n", sNameSpace);
-                        pszSLD = msStringConcatenate(pszSLD, szTmp);
-
-                        snprintf(szTmp, sizeof(szTmp), "<%sWellKnownName>%s</%sWellKnownName>\n",
-                                 sNameSpace, pszSymbolName, sNameSpace);
-                        pszSLD = msStringConcatenate(pszSLD, szTmp);
-
-                        
-                        if (psStyle->color.red != -1 && 
-                            psStyle->color.green != -1 &&
-                            psStyle->color.blue != -1)
-                        {
-                            sTmpColor.red = psStyle->color.red;
-                            sTmpColor.green = psStyle->color.green;
-                            sTmpColor.blue = psStyle->color.blue;
-                            bFillColor =1;
-                        }
-                        else if (psStyle->outlinecolor.red != -1 && 
-                                 psStyle->outlinecolor.green != -1 &&
-                                 psStyle->outlinecolor.blue != -1) 
-                        {
-                            sTmpColor.red = psStyle->outlinecolor.red;
-                            sTmpColor.green = psStyle->outlinecolor.green;
-                            sTmpColor.blue = psStyle->outlinecolor.blue;
-                            bFillColor = 0;
-                        }
-                        else
-                        {
-                            sTmpColor.red = 128;
-                            sTmpColor.green = 128;
-                            sTmpColor.blue = 128;
-                             bFillColor =1;
-                        }
-                        
-                        
-                        if (psLayer->type == MS_LAYER_POINT)
-                        {
-                            if (psSymbol->filled || bFillColor)
-                            {
-                                snprintf(szTmp, sizeof(szTmp), "<%sFill>\n", sNameSpace);
-                                pszSLD = msStringConcatenate(pszSLD, szTmp);
-                                snprintf(szTmp, sizeof(szTmp), "<%s name=\"fill\">#%02x%02x%02x</%s>\n",
-                                         sCssParam,sTmpColor.red,
-                                         sTmpColor.green,
-                                         sTmpColor.blue,
-                                         sCssParam);
-                            }
-                            else
-                            {
-                                snprintf(szTmp, sizeof(szTmp), "<%sStroke>\n", sNameSpace);
-                                pszSLD = msStringConcatenate(pszSLD, szTmp);
-                                snprintf(szTmp, sizeof(szTmp), "<%s name=\"stroke\">#%02x%02x%02x</%s>\n",
-                                         sCssParam,
-                                         sTmpColor.red,
-                                         sTmpColor.green,
-                                         sTmpColor.blue,
-                                         sCssParam);
-                            }
-                        }       
-                        else    
-                        {
-                            if (bFillColor)
-                            {
-                                snprintf(szTmp, sizeof(szTmp), "<%sFill>\n", sNameSpace);
-                                pszSLD = msStringConcatenate(pszSLD, szTmp);
-                                snprintf(szTmp, sizeof(szTmp), "<%s name=\"fill\">#%02x%02x%02x</%s>\n",
-                                         sCssParam,
-                                         sTmpColor.red,
-                                         sTmpColor.green,
-                                         sTmpColor.blue,
-                                         sCssParam);
-                            }
-                            else
-                            {
-                                snprintf(szTmp, sizeof(szTmp), "<%sStroke>\n", sNameSpace);
-                                pszSLD = msStringConcatenate(pszSLD, szTmp);
-                                snprintf(szTmp, sizeof(szTmp), "<%s name=\"stroke\">#%02x%02x%02x</%s>\n",
-                                         sCssParam,
-                                         sTmpColor.red,
-                                         sTmpColor.green,
-                                         sTmpColor.blue,
-                                         sCssParam);
-                            }
-                        }
-                        pszSLD = msStringConcatenate(pszSLD, szTmp);
-
-                        if ((psLayer->type == MS_LAYER_POINT && psSymbol->filled) || 
-                            bFillColor)
-                           snprintf(szTmp, sizeof(szTmp), "</%sFill>\n", sNameSpace);
-                        else
-                          snprintf(szTmp, sizeof(szTmp), "</%sStroke>\n", sNameSpace);
-                        pszSLD = msStringConcatenate(pszSLD, szTmp);
-
-                        snprintf(szTmp, sizeof(szTmp), "</%sMark>\n", sNameSpace);
-                        pszSLD = msStringConcatenate(pszSLD, szTmp);
-                    
-                        if (psStyle->size > 0)
-                        {
-                          snprintf(szTmp, sizeof(szTmp), "<%sSize>%g</%sSize>\n", sNameSpace, 
-                                  psStyle->size, sNameSpace);
-                            pszSLD = msStringConcatenate(pszSLD, szTmp);
-                        }
-
-                        snprintf(szTmp, sizeof(szTmp), "</%sGraphic>\n", sNameSpace);
-                        pszSLD = msStringConcatenate(pszSLD, szTmp);
-
-                        if (pszSymbolName)
-                          free(pszSymbolName);
-                    }
-                }
-                else
-                  bGenerateDefaultSymbol =1;
-            }
-            else if (psSymbol->type == MS_SYMBOL_PIXMAP)
-            {
-                if (psSymbol->name)
-                {
-                    pszURL = msLookupHashTable(&(psLayer->metadata), "WMS_SLD_SYMBOL_URL");
-                    if (!pszURL)
-                      pszURL = msLookupHashTable(&(psLayer->map->web.metadata), "WMS_SLD_SYMBOL_URL");
-
-                    if (pszURL)
-                    {
-                        snprintf(szTmp, sizeof(szTmp), "<%sGraphic>\n", sNameSpace);
-                        pszSLD = msStringConcatenate(pszSLD, szTmp);
-
-                        
-
-                        snprintf(szTmp, sizeof(szTmp), "<%sExternalGraphic>\n", sNameSpace);
-                        pszSLD = msStringConcatenate(pszSLD, szTmp);
-                        
-                        snprintf(szTmp, sizeof(szTmp), "<%sOnlineResource xmlns:xlink=\"http://www.w3.org/1999/xlink\" xlink:type=\"simple\" xlink:href=\"%s%s\"/>\n", sNameSpace,
-                                 pszURL,psSymbol->imagepath);
-                        pszSLD = msStringConcatenate(pszSLD, szTmp);
-                        /* TODO : extract format from symbol */
-
-                        szFormat[0] = '\0';
-                        nLength = strlen(psSymbol->imagepath);
-                        if (nLength > 3)
-                        {
-                            for (i=0; i<=2; i++)
-                              szFormat[2-i] = psSymbol->imagepath[nLength-1-i];
-                            szFormat[3] = '\0';
-                        }
-                        if (strlen(szFormat) > 0 &&
-                            ((strcasecmp (szFormat, "GIF") == 0) ||
-                             (strcasecmp (szFormat, "PNG") == 0)))
-                        {
-                            if (strcasecmp (szFormat, "GIF") == 0)
-                              snprintf(szTmp, sizeof(szTmp), "<%sFormat>image/gif</%sFormat>\n", 
-                                       sNameSpace, sNameSpace);
-                            else
-                              snprintf(szTmp, sizeof(szTmp), "<%sFormat>image/png</%sFormat>\n",
-                                       sNameSpace, sNameSpace);
-                        }
-                        else
-                          snprintf(szTmp, sizeof(szTmp), "<%sFormat>%s</%sFormat>\n", "image/gif",
-                                   sNameSpace, sNameSpace);
-                            
-                        pszSLD = msStringConcatenate(pszSLD, szTmp);  
-
-                        snprintf(szTmp, sizeof(szTmp), "</%sExternalGraphic>\n",  sNameSpace);
-                        pszSLD = msStringConcatenate(pszSLD, szTmp);
-
-                        if (psStyle->size > 0)
-                          snprintf(szTmp, sizeof(szTmp), "<%sSize>%g</%sSize>\n", sNameSpace, psStyle->size,
-                                  sNameSpace);
-                        pszSLD = msStringConcatenate(pszSLD, szTmp);
-
-                        snprintf(szTmp, sizeof(szTmp), "</%sGraphic>\n", sNameSpace);
-                        pszSLD = msStringConcatenate(pszSLD, szTmp);
+          if (strcasecmp(psSymbol->name, "square") == 0 ||
+              strcasecmp(psSymbol->name, "circle") == 0 ||
+              strcasecmp(psSymbol->name, "triangle") == 0 ||
+              strcasecmp(psSymbol->name, "star") == 0 ||
+              strcasecmp(psSymbol->name, "cross") == 0 ||
+              strcasecmp(psSymbol->name, "x") == 0)
+            pszSymbolName = msStrdup(psSymbol->name);
+          else if (strncasecmp(psSymbol->name,
+                               "sld_mark_symbol_square", 22) == 0)
+            pszSymbolName = msStrdup("square");
+          else if (strncasecmp(psSymbol->name,
+                               "sld_mark_symbol_triangle", 24) == 0)
+            pszSymbolName = msStrdup("triangle");
+          else if (strncasecmp(psSymbol->name,
+                               "sld_mark_symbol_circle", 22) == 0)
+            pszSymbolName = msStrdup("circle");
+          else if (strncasecmp(psSymbol->name,
+                               "sld_mark_symbol_star", 20) == 0)
+            pszSymbolName = msStrdup("star");
+          else if (strncasecmp(psSymbol->name,
+                               "sld_mark_symbol_cross", 21) == 0)
+            pszSymbolName = msStrdup("cross");
+          else if (strncasecmp(psSymbol->name,
+                               "sld_mark_symbol_x", 17) == 0)
+            pszSymbolName = msStrdup("X");
+
+
+
+          if (pszSymbolName) {
+            colorObj sTmpColor;
 
-                    }
-                }
-                    
-            }
-        }
-        if (bGenerateDefaultSymbol) /* genrate a default square symbol */
-        {
             snprintf(szTmp, sizeof(szTmp), "<%sGraphic>\n", sNameSpace);
             pszSLD = msStringConcatenate(pszSLD, szTmp);
 
-            
+
 
             snprintf(szTmp, sizeof(szTmp), "<%sMark>\n", sNameSpace);
             pszSLD = msStringConcatenate(pszSLD, szTmp);
 
             snprintf(szTmp, sizeof(szTmp), "<%sWellKnownName>%s</%sWellKnownName>\n",
-                     sNameSpace, "square", sNameSpace);
+                     sNameSpace, pszSymbolName, sNameSpace);
             pszSLD = msStringConcatenate(pszSLD, szTmp);
 
-            bColorAvailable = 0;
-            if (psStyle->color.red != -1 && 
+
+            if (psStyle->color.red != -1 &&
                 psStyle->color.green != -1 &&
-                psStyle->color.blue != -1)
-            {
+                psStyle->color.blue != -1) {
+              sTmpColor.red = psStyle->color.red;
+              sTmpColor.green = psStyle->color.green;
+              sTmpColor.blue = psStyle->color.blue;
+              bFillColor =1;
+            } else if (psStyle->outlinecolor.red != -1 &&
+                       psStyle->outlinecolor.green != -1 &&
+                       psStyle->outlinecolor.blue != -1) {
+              sTmpColor.red = psStyle->outlinecolor.red;
+              sTmpColor.green = psStyle->outlinecolor.green;
+              sTmpColor.blue = psStyle->outlinecolor.blue;
+              bFillColor = 0;
+            } else {
+              sTmpColor.red = 128;
+              sTmpColor.green = 128;
+              sTmpColor.blue = 128;
+              bFillColor =1;
+            }
+
+
+            if (psLayer->type == MS_LAYER_POINT) {
+              if (psSymbol->filled || bFillColor) {
                 snprintf(szTmp, sizeof(szTmp), "<%sFill>\n", sNameSpace);
                 pszSLD = msStringConcatenate(pszSLD, szTmp);
                 snprintf(szTmp, sizeof(szTmp), "<%s name=\"fill\">#%02x%02x%02x</%s>\n",
-                         sCssParam,
-                         psStyle->color.red,
-                         psStyle->color.green,
-                         psStyle->color.blue,
+                         sCssParam,sTmpColor.red,
+                         sTmpColor.green,
+                         sTmpColor.blue,
                          sCssParam);
-                pszSLD = msStringConcatenate(pszSLD, szTmp);
-                snprintf(szTmp, sizeof(szTmp), "</%sFill>\n", sNameSpace);
-                pszSLD = msStringConcatenate(pszSLD, szTmp);
-                bColorAvailable = 1;
-            }
-            if (psStyle->outlinecolor.red != -1 && 
-                psStyle->outlinecolor.green != -1 &&
-                psStyle->outlinecolor.blue != -1)    
-            {
+              } else {
                 snprintf(szTmp, sizeof(szTmp), "<%sStroke>\n", sNameSpace);
                 pszSLD = msStringConcatenate(pszSLD, szTmp);
-                snprintf(szTmp, sizeof(szTmp), "<%s name=\"Stroke\">#%02x%02x%02x</%s>\n",
+                snprintf(szTmp, sizeof(szTmp), "<%s name=\"stroke\">#%02x%02x%02x</%s>\n",
                          sCssParam,
-                         psStyle->outlinecolor.red,
-                         psStyle->outlinecolor.green,
-                         psStyle->outlinecolor.blue,
+                         sTmpColor.red,
+                         sTmpColor.green,
+                         sTmpColor.blue,
                          sCssParam);
-                pszSLD = msStringConcatenate(pszSLD, szTmp);
-                snprintf(szTmp, sizeof(szTmp), "</%sStroke>\n", sNameSpace);
-                pszSLD = msStringConcatenate(pszSLD, szTmp);
-                bColorAvailable = 1;
-            }
-            if (!bColorAvailable)
-            {       
-                /* default color */
+              }
+            } else {
+              if (bFillColor) {
                 snprintf(szTmp, sizeof(szTmp), "<%sFill>\n", sNameSpace);
                 pszSLD = msStringConcatenate(pszSLD, szTmp);
-                snprintf(szTmp, sizeof(szTmp), 
-                         "<%s name=\"fill\">%s</%s>\n",
-                         sCssParam, "#808080", sCssParam);
-                pszSLD = msStringConcatenate(pszSLD, szTmp);
-                snprintf(szTmp, sizeof(szTmp), "</%sFill>\n", sNameSpace);
+                snprintf(szTmp, sizeof(szTmp), "<%s name=\"fill\">#%02x%02x%02x</%s>\n",
+                         sCssParam,
+                         sTmpColor.red,
+                         sTmpColor.green,
+                         sTmpColor.blue,
+                         sCssParam);
+              } else {
+                snprintf(szTmp, sizeof(szTmp), "<%sStroke>\n", sNameSpace);
                 pszSLD = msStringConcatenate(pszSLD, szTmp);
+                snprintf(szTmp, sizeof(szTmp), "<%s name=\"stroke\">#%02x%02x%02x</%s>\n",
+                         sCssParam,
+                         sTmpColor.red,
+                         sTmpColor.green,
+                         sTmpColor.blue,
+                         sCssParam);
+              }
             }
+            pszSLD = msStringConcatenate(pszSLD, szTmp);
+
+            if ((psLayer->type == MS_LAYER_POINT && psSymbol->filled) ||
+                bFillColor)
+              snprintf(szTmp, sizeof(szTmp), "</%sFill>\n", sNameSpace);
+            else
+              snprintf(szTmp, sizeof(szTmp), "</%sStroke>\n", sNameSpace);
+            pszSLD = msStringConcatenate(pszSLD, szTmp);
 
             snprintf(szTmp, sizeof(szTmp), "</%sMark>\n", sNameSpace);
             pszSLD = msStringConcatenate(pszSLD, szTmp);
 
-            if (psStyle->size > 0)
+            if (psStyle->size > 0) {
               snprintf(szTmp, sizeof(szTmp), "<%sSize>%g</%sSize>\n", sNameSpace,
-                      psStyle->size, sNameSpace);
-            else
-              snprintf(szTmp,  sizeof(szTmp), "<%sSize>%d</%sSize>\n", sNameSpace,1,sNameSpace);
+                       psStyle->size, sNameSpace);
+              pszSLD = msStringConcatenate(pszSLD, szTmp);
+            }
+
+            snprintf(szTmp, sizeof(szTmp), "</%sGraphic>\n", sNameSpace);
+            pszSLD = msStringConcatenate(pszSLD, szTmp);
+
+            if (pszSymbolName)
+              free(pszSymbolName);
+          }
+        } else
+          bGenerateDefaultSymbol =1;
+      } else if (psSymbol->type == MS_SYMBOL_PIXMAP) {
+        if (psSymbol->name) {
+          pszURL = msLookupHashTable(&(psLayer->metadata), "WMS_SLD_SYMBOL_URL");
+          if (!pszURL)
+            pszURL = msLookupHashTable(&(psLayer->map->web.metadata), "WMS_SLD_SYMBOL_URL");
+
+          if (pszURL) {
+            snprintf(szTmp, sizeof(szTmp), "<%sGraphic>\n", sNameSpace);
+            pszSLD = msStringConcatenate(pszSLD, szTmp);
+
+
+
+            snprintf(szTmp, sizeof(szTmp), "<%sExternalGraphic>\n", sNameSpace);
+            pszSLD = msStringConcatenate(pszSLD, szTmp);
+
+            snprintf(szTmp, sizeof(szTmp), "<%sOnlineResource xmlns:xlink=\"http://www.w3.org/1999/xlink\" xlink:type=\"simple\" xlink:href=\"%s%s\"/>\n", sNameSpace,
+                     pszURL,psSymbol->imagepath);
+            pszSLD = msStringConcatenate(pszSLD, szTmp);
+            /* TODO : extract format from symbol */
+
+            szFormat[0] = '\0';
+            nLength = strlen(psSymbol->imagepath);
+            if (nLength > 3) {
+              for (i=0; i<=2; i++)
+                szFormat[2-i] = psSymbol->imagepath[nLength-1-i];
+              szFormat[3] = '\0';
+            }
+            if (strlen(szFormat) > 0 &&
+                ((strcasecmp (szFormat, "GIF") == 0) ||
+                 (strcasecmp (szFormat, "PNG") == 0))) {
+              if (strcasecmp (szFormat, "GIF") == 0)
+                snprintf(szTmp, sizeof(szTmp), "<%sFormat>image/gif</%sFormat>\n",
+                         sNameSpace, sNameSpace);
+              else
+                snprintf(szTmp, sizeof(szTmp), "<%sFormat>image/png</%sFormat>\n",
+                         sNameSpace, sNameSpace);
+            } else
+              snprintf(szTmp, sizeof(szTmp), "<%sFormat>%s</%sFormat>\n", "image/gif",
+                       sNameSpace, sNameSpace);
+
+            pszSLD = msStringConcatenate(pszSLD, szTmp);
+
+            snprintf(szTmp, sizeof(szTmp), "</%sExternalGraphic>\n",  sNameSpace);
+            pszSLD = msStringConcatenate(pszSLD, szTmp);
+
+            if (psStyle->size > 0)
+              snprintf(szTmp, sizeof(szTmp), "<%sSize>%g</%sSize>\n", sNameSpace, psStyle->size,
+                       sNameSpace);
             pszSLD = msStringConcatenate(pszSLD, szTmp);
 
             snprintf(szTmp, sizeof(szTmp), "</%sGraphic>\n", sNameSpace);
             pszSLD = msStringConcatenate(pszSLD, szTmp);
-            
-        
+
+          }
         }
+
+      }
+    }
+    if (bGenerateDefaultSymbol) { /* genrate a default square symbol */
+      snprintf(szTmp, sizeof(szTmp), "<%sGraphic>\n", sNameSpace);
+      pszSLD = msStringConcatenate(pszSLD, szTmp);
+
+
+
+      snprintf(szTmp, sizeof(szTmp), "<%sMark>\n", sNameSpace);
+      pszSLD = msStringConcatenate(pszSLD, szTmp);
+
+      snprintf(szTmp, sizeof(szTmp), "<%sWellKnownName>%s</%sWellKnownName>\n",
+               sNameSpace, "square", sNameSpace);
+      pszSLD = msStringConcatenate(pszSLD, szTmp);
+
+      bColorAvailable = 0;
+      if (psStyle->color.red != -1 &&
+          psStyle->color.green != -1 &&
+          psStyle->color.blue != -1) {
+        snprintf(szTmp, sizeof(szTmp), "<%sFill>\n", sNameSpace);
+        pszSLD = msStringConcatenate(pszSLD, szTmp);
+        snprintf(szTmp, sizeof(szTmp), "<%s name=\"fill\">#%02x%02x%02x</%s>\n",
+                 sCssParam,
+                 psStyle->color.red,
+                 psStyle->color.green,
+                 psStyle->color.blue,
+                 sCssParam);
+        pszSLD = msStringConcatenate(pszSLD, szTmp);
+        snprintf(szTmp, sizeof(szTmp), "</%sFill>\n", sNameSpace);
+        pszSLD = msStringConcatenate(pszSLD, szTmp);
+        bColorAvailable = 1;
+      }
+      if (psStyle->outlinecolor.red != -1 &&
+          psStyle->outlinecolor.green != -1 &&
+          psStyle->outlinecolor.blue != -1) {
+        snprintf(szTmp, sizeof(szTmp), "<%sStroke>\n", sNameSpace);
+        pszSLD = msStringConcatenate(pszSLD, szTmp);
+        snprintf(szTmp, sizeof(szTmp), "<%s name=\"Stroke\">#%02x%02x%02x</%s>\n",
+                 sCssParam,
+                 psStyle->outlinecolor.red,
+                 psStyle->outlinecolor.green,
+                 psStyle->outlinecolor.blue,
+                 sCssParam);
+        pszSLD = msStringConcatenate(pszSLD, szTmp);
+        snprintf(szTmp, sizeof(szTmp), "</%sStroke>\n", sNameSpace);
+        pszSLD = msStringConcatenate(pszSLD, szTmp);
+        bColorAvailable = 1;
+      }
+      if (!bColorAvailable) {
+        /* default color */
+        snprintf(szTmp, sizeof(szTmp), "<%sFill>\n", sNameSpace);
+        pszSLD = msStringConcatenate(pszSLD, szTmp);
+        snprintf(szTmp, sizeof(szTmp),
+                 "<%s name=\"fill\">%s</%s>\n",
+                 sCssParam, "#808080", sCssParam);
+        pszSLD = msStringConcatenate(pszSLD, szTmp);
+        snprintf(szTmp, sizeof(szTmp), "</%sFill>\n", sNameSpace);
+        pszSLD = msStringConcatenate(pszSLD, szTmp);
+      }
+
+      snprintf(szTmp, sizeof(szTmp), "</%sMark>\n", sNameSpace);
+      pszSLD = msStringConcatenate(pszSLD, szTmp);
+
+      if (psStyle->size > 0)
+        snprintf(szTmp, sizeof(szTmp), "<%sSize>%g</%sSize>\n", sNameSpace,
+                 psStyle->size, sNameSpace);
+      else
+        snprintf(szTmp,  sizeof(szTmp), "<%sSize>%d</%sSize>\n", sNameSpace,1,sNameSpace);
+      pszSLD = msStringConcatenate(pszSLD, szTmp);
+
+      snprintf(szTmp, sizeof(szTmp), "</%sGraphic>\n", sNameSpace);
+      pszSLD = msStringConcatenate(pszSLD, szTmp);
+
+
     }
+  }
 
-    return pszSLD;
+  return pszSLD;
 
 #else
-    return NULL;
+  return NULL;
 
 #endif
 
@@ -3688,132 +3482,128 @@ char *msSLDGenerateLineSLD(styleObj *psStyle, layerObj *psLayer, int nVersion)
 {
 #if defined(USE_WMS_SVR) || defined (USE_WFS_SVR) || defined (USE_WCS_SVR) || defined(USE_SOS_SVR)
 
-    char *pszSLD = NULL;
-    char szTmp[100];
-    char szHexColor[7];
-    int nSymbol = -1;
-    int i = 0;
-    double dfSize = 1.0;
-    char *pszDashArray = NULL;
-    char *pszGraphicSLD = NULL;
-    char sCssParam[30];
-    char sNameSpace[10];
-
-    if ( msCheckParentPointer(psLayer->map,"map")==MS_FAILURE )
-      return NULL;
+  char *pszSLD = NULL;
+  char szTmp[100];
+  char szHexColor[7];
+  int nSymbol = -1;
+  int i = 0;
+  double dfSize = 1.0;
+  char *pszDashArray = NULL;
+  char *pszGraphicSLD = NULL;
+  char sCssParam[30];
+  char sNameSpace[10];
+
+  if ( msCheckParentPointer(psLayer->map,"map")==MS_FAILURE )
+    return NULL;
 
-    sCssParam[0] = '\0';
-    if (nVersion > OWS_1_0_0)
-      strcpy( sCssParam, "se:SvgParameter");
-    else
-      strcpy( sCssParam, "CssParameter");
+  sCssParam[0] = '\0';
+  if (nVersion > OWS_1_0_0)
+    strcpy( sCssParam, "se:SvgParameter");
+  else
+    strcpy( sCssParam, "CssParameter");
 
-    sNameSpace[0] = '\0';
-    if (nVersion > OWS_1_0_0)
-      strcpy(sNameSpace, "se:");
+  sNameSpace[0] = '\0';
+  if (nVersion > OWS_1_0_0)
+    strcpy(sNameSpace, "se:");
+
+  snprintf(szTmp, sizeof(szTmp), "<%sLineSymbolizer>\n",  sNameSpace);
+
+  pszSLD = msStringConcatenate(pszSLD, szTmp);
+
+  snprintf(szTmp, sizeof(szTmp), "<%sStroke>\n",  sNameSpace);
 
-    snprintf(szTmp, sizeof(szTmp), "<%sLineSymbolizer>\n",  sNameSpace);
+  pszSLD = msStringConcatenate(pszSLD, szTmp);
+
+  pszGraphicSLD = msSLDGetGraphicSLD(psStyle, psLayer, 0, nVersion);
+  if (pszGraphicSLD) {
+    snprintf(szTmp, sizeof(szTmp), "<%sGraphicStroke>\n",  sNameSpace);
 
     pszSLD = msStringConcatenate(pszSLD, szTmp);
 
-    snprintf(szTmp, sizeof(szTmp), "<%sStroke>\n",  sNameSpace);
+    pszSLD = msStringConcatenate(pszSLD, pszGraphicSLD);
+
+    snprintf(szTmp, sizeof(szTmp), "</%sGraphicStroke>\n",  sNameSpace);
 
     pszSLD = msStringConcatenate(pszSLD, szTmp);
 
-    pszGraphicSLD = msSLDGetGraphicSLD(psStyle, psLayer, 0, nVersion);
-    if (pszGraphicSLD)
-    {
-        snprintf(szTmp, sizeof(szTmp), "<%sGraphicStroke>\n",  sNameSpace);
+    free(pszGraphicSLD);
+    pszGraphicSLD = NULL;
+  }
+
+  if (psStyle->color.red != -1 &&
+      psStyle->color.green != -1 &&
+      psStyle->color.blue != -1)
+    sprintf(szHexColor,"%02x%02x%02x",psStyle->color.red,
+            psStyle->color.green,psStyle->color.blue);
+  else
+    sprintf(szHexColor,"%02x%02x%02x",psStyle->outlinecolor.red,
+            psStyle->outlinecolor.green,psStyle->outlinecolor.blue);
+
+  snprintf(szTmp,  sizeof(szTmp),
+           "<%s name=\"stroke\">#%s</%s>\n",
+           sCssParam, szHexColor, sCssParam);
+  pszSLD = msStringConcatenate(pszSLD, szTmp);
+
+  if(psStyle->color.alpha != 255 && psStyle->color.alpha!=-1) {
+    snprintf(szTmp, sizeof(szTmp),
+             "<%s name=\"stroke-opacity\">%.2f</%s>\n",
+             sCssParam, (float)psStyle->color.alpha/255.0, sCssParam);
+    pszSLD = msStringConcatenate(pszSLD, szTmp);
+  }
 
-        pszSLD = msStringConcatenate(pszSLD, szTmp);
-        
-        pszSLD = msStringConcatenate(pszSLD, pszGraphicSLD);
 
-        snprintf(szTmp, sizeof(szTmp), "</%sGraphicStroke>\n",  sNameSpace);
+  nSymbol = -1;
 
-        pszSLD = msStringConcatenate(pszSLD, szTmp);
-             
-        free(pszGraphicSLD);
-        pszGraphicSLD = NULL;
-    }
+  if (psStyle->symbol >= 0)
+    nSymbol = psStyle->symbol;
+  else if (psStyle->symbolname)
+    nSymbol = msGetSymbolIndex(&psLayer->map->symbolset,
+                               psStyle->symbolname, MS_FALSE);
 
-    if (psStyle->color.red != -1 && 
-        psStyle->color.green != -1 &&
-        psStyle->color.blue != -1)
-      sprintf(szHexColor,"%02x%02x%02x",psStyle->color.red,
-              psStyle->color.green,psStyle->color.blue);
+  if (nSymbol <0)
+    dfSize = 1.0;
+  else {
+    if (psStyle->size > 0)
+      dfSize = psStyle->size;
+    else if (psStyle->width > 0)
+      dfSize = psStyle->width;
     else
-      sprintf(szHexColor,"%02x%02x%02x",psStyle->outlinecolor.red,
-              psStyle->outlinecolor.green,psStyle->outlinecolor.blue);
-                            
-    snprintf(szTmp,  sizeof(szTmp),
-            "<%s name=\"stroke\">#%s</%s>\n", 
-            sCssParam, szHexColor, sCssParam);
-    pszSLD = msStringConcatenate(pszSLD, szTmp);
+      dfSize = 1;
+  }
 
-    if(psStyle->color.alpha != 255 && psStyle->color.alpha!=-1) {
-      snprintf(szTmp, sizeof(szTmp),
-               "<%s name=\"stroke-opacity\">%.2f</%s>\n", 
-               sCssParam, (float)psStyle->color.alpha/255.0, sCssParam);
-      pszSLD = msStringConcatenate(pszSLD, szTmp);
-    }
+  snprintf(szTmp, sizeof(szTmp),
+           "<%s name=\"stroke-width\">%.2f</%s>\n",
+           sCssParam, dfSize, sCssParam);
+  pszSLD = msStringConcatenate(pszSLD, szTmp);
 
-                            
-    nSymbol = -1;
+  /* -------------------------------------------------------------------- */
+  /*      dash array                                                      */
+  /* -------------------------------------------------------------------- */
 
-    if (psStyle->symbol >= 0)
-      nSymbol = psStyle->symbol;
-    else if (psStyle->symbolname)
-      nSymbol = msGetSymbolIndex(&psLayer->map->symbolset,
-                                 psStyle->symbolname, MS_FALSE);
-                            
-    if (nSymbol <0)
-      dfSize = 1.0;
-    else
-    {
-        if (psStyle->size > 0)
-          dfSize = psStyle->size;
-        else if (psStyle->width > 0)
-          dfSize = psStyle->width;
-        else
-          dfSize = 1;
-    }
 
+  if (psStyle->patternlength > 0) {
+    for (i=0; i<psStyle->patternlength; i++) {
+      snprintf(szTmp, sizeof(szTmp), "%.2f ", psStyle->pattern[i]);
+      pszDashArray = msStringConcatenate(pszDashArray, szTmp);
+    }
     snprintf(szTmp, sizeof(szTmp),
-             "<%s name=\"stroke-width\">%.2f</%s>\n",
-             sCssParam, dfSize, sCssParam);
+             "<%s name=\"stroke-dasharray\">%s</%s>\n",
+             sCssParam, pszDashArray, sCssParam);
     pszSLD = msStringConcatenate(pszSLD, szTmp);
-                            
-/* -------------------------------------------------------------------- */
-/*      dash array                                                      */
-/* -------------------------------------------------------------------- */
-                            
-                            
-    if (psStyle->patternlength > 0)
-    {
-        for (i=0; i<psStyle->patternlength; i++)
-        {
-            snprintf(szTmp, sizeof(szTmp), "%.2f ", psStyle->pattern[i]);
-            pszDashArray = msStringConcatenate(pszDashArray, szTmp);
-        }
-        snprintf(szTmp, sizeof(szTmp),
-                 "<%s name=\"stroke-dasharray\">%s</%s>\n", 
-                 sCssParam, pszDashArray, sCssParam);
-        pszSLD = msStringConcatenate(pszSLD, szTmp);
-    }  
+  }
 
-    snprintf(szTmp, sizeof(szTmp), "</%sStroke>\n",  sNameSpace);
+  snprintf(szTmp, sizeof(szTmp), "</%sStroke>\n",  sNameSpace);
 
-    pszSLD = msStringConcatenate(pszSLD, szTmp);
+  pszSLD = msStringConcatenate(pszSLD, szTmp);
 
-    snprintf(szTmp, sizeof(szTmp), "</%sLineSymbolizer>\n",  sNameSpace);
+  snprintf(szTmp, sizeof(szTmp), "</%sLineSymbolizer>\n",  sNameSpace);
 
-    pszSLD = msStringConcatenate(pszSLD, szTmp);
+  pszSLD = msStringConcatenate(pszSLD, szTmp);
 
-    return pszSLD;
+  return pszSLD;
 
 #else
-    return NULL;
+  return NULL;
 #endif
 }
 
@@ -3827,134 +3617,129 @@ char *msSLDGeneratePolygonSLD(styleObj *psStyle, layerObj *psLayer, int nVersion
 {
 #if defined(USE_WMS_SVR) || defined (USE_WFS_SVR) || defined (USE_WCS_SVR) || defined(USE_SOS_SVR)
 
-    char szTmp[100];
-    char *pszSLD = NULL;
-    char szHexColor[7];
-    char *pszGraphicSLD = NULL;
-    double dfSize;
-    char sCssParam[30];
-    char sNameSpace[10];
+  char szTmp[100];
+  char *pszSLD = NULL;
+  char szHexColor[7];
+  char *pszGraphicSLD = NULL;
+  double dfSize;
+  char sCssParam[30];
+  char sNameSpace[10];
 
-    sCssParam[0] = '\0';
-    if (nVersion > OWS_1_0_0)
-      strcpy(sCssParam, "se:SvgParameter");
-    else
-      strcpy(sCssParam, "CssParameter");
+  sCssParam[0] = '\0';
+  if (nVersion > OWS_1_0_0)
+    strcpy(sCssParam, "se:SvgParameter");
+  else
+    strcpy(sCssParam, "CssParameter");
 
-    sNameSpace[0] = '\0';
-    if (nVersion > OWS_1_0_0)
-      strcpy(sNameSpace, "se:");
+  sNameSpace[0] = '\0';
+  if (nVersion > OWS_1_0_0)
+    strcpy(sNameSpace, "se:");
+
+  snprintf(szTmp, sizeof(szTmp), "<%sPolygonSymbolizer>\n",  sNameSpace);
 
-    snprintf(szTmp, sizeof(szTmp), "<%sPolygonSymbolizer>\n",  sNameSpace);
+  pszSLD = msStringConcatenate(pszSLD, szTmp);
+  /* fill */
+  if (psStyle->color.red != -1 && psStyle->color.green != -1 &&
+      psStyle->color.blue != -1) {
+
+    snprintf(szTmp, sizeof(szTmp), "<%sFill>\n",  sNameSpace);
 
     pszSLD = msStringConcatenate(pszSLD, szTmp);
-    /* fill */
-    if (psStyle->color.red != -1 && psStyle->color.green != -1 &&
-        psStyle->color.blue != -1)
-    {
 
-        snprintf(szTmp, sizeof(szTmp), "<%sFill>\n",  sNameSpace);
+    pszGraphicSLD = msSLDGetGraphicSLD(psStyle, psLayer, 0, nVersion);
+    if (pszGraphicSLD) {
+      snprintf(szTmp, sizeof(szTmp), "<%sGraphicFill>\n",  sNameSpace);
 
-        pszSLD = msStringConcatenate(pszSLD, szTmp);
+      pszSLD = msStringConcatenate(pszSLD, szTmp);
 
-        pszGraphicSLD = msSLDGetGraphicSLD(psStyle, psLayer, 0, nVersion);
-        if (pszGraphicSLD)
-        {
-            snprintf(szTmp, sizeof(szTmp), "<%sGraphicFill>\n",  sNameSpace);
+      pszSLD = msStringConcatenate(pszSLD, pszGraphicSLD);
 
-            pszSLD = msStringConcatenate(pszSLD, szTmp);
+      snprintf(szTmp, sizeof(szTmp), "</%sGraphicFill>\n",  sNameSpace);
 
-            pszSLD = msStringConcatenate(pszSLD, pszGraphicSLD);
+      pszSLD = msStringConcatenate(pszSLD, szTmp);
 
-            snprintf(szTmp, sizeof(szTmp), "</%sGraphicFill>\n",  sNameSpace);
+      free(pszGraphicSLD);
+      pszGraphicSLD = NULL;
+    }
 
-             pszSLD = msStringConcatenate(pszSLD, szTmp);
-             
-             free(pszGraphicSLD);
-             pszGraphicSLD = NULL;
-        }
+    sprintf(szHexColor,"%02x%02x%02x",psStyle->color.red,
+            psStyle->color.green,psStyle->color.blue);
 
-        sprintf(szHexColor,"%02x%02x%02x",psStyle->color.red,
-                psStyle->color.green,psStyle->color.blue);
-                             
-        snprintf(szTmp, sizeof(szTmp),
-                "<%s name=\"fill\">#%s</%s>\n", 
-                sCssParam, szHexColor, sCssParam);
-        pszSLD = msStringConcatenate(pszSLD, szTmp);
+    snprintf(szTmp, sizeof(szTmp),
+             "<%s name=\"fill\">#%s</%s>\n",
+             sCssParam, szHexColor, sCssParam);
+    pszSLD = msStringConcatenate(pszSLD, szTmp);
 
-        if(psStyle->color.alpha != 255 && psStyle->color.alpha!=-1) {
-           snprintf(szTmp, sizeof(szTmp),
-                 "<%s name=\"fill-opacity\">%.2f</%s>\n", 
-                 sCssParam, (float)psStyle->color.alpha/255, sCssParam);
-           pszSLD = msStringConcatenate(pszSLD, szTmp);
-        }
+    if(psStyle->color.alpha != 255 && psStyle->color.alpha!=-1) {
+      snprintf(szTmp, sizeof(szTmp),
+               "<%s name=\"fill-opacity\">%.2f</%s>\n",
+               sCssParam, (float)psStyle->color.alpha/255, sCssParam);
+      pszSLD = msStringConcatenate(pszSLD, szTmp);
+    }
 
 
-        snprintf(szTmp, sizeof(szTmp), "</%sFill>\n",  sNameSpace);
+    snprintf(szTmp, sizeof(szTmp), "</%sFill>\n",  sNameSpace);
 
-        pszSLD = msStringConcatenate(pszSLD, szTmp);
-    }
-    /* stroke */
-    if (psStyle->outlinecolor.red != -1 && 
-        psStyle->outlinecolor.green != -1 &&
-        psStyle->outlinecolor.blue != -1)
-    {
-        snprintf(szTmp, sizeof(szTmp), "<%sStroke>\n",  sNameSpace);
-        pszSLD = msStringConcatenate(pszSLD, szTmp);
+    pszSLD = msStringConcatenate(pszSLD, szTmp);
+  }
+  /* stroke */
+  if (psStyle->outlinecolor.red != -1 &&
+      psStyle->outlinecolor.green != -1 &&
+      psStyle->outlinecolor.blue != -1) {
+    snprintf(szTmp, sizeof(szTmp), "<%sStroke>\n",  sNameSpace);
+    pszSLD = msStringConcatenate(pszSLD, szTmp);
 
-        
 
-        /* If there is a symbol to be used for sroke, the color in the */
-        /* style sholud be set to -1. Else It won't apply here. */
-        if (psStyle->color.red == -1 && psStyle->color.green == -1 &&
-            psStyle->color.blue == -1)
-        {
-          pszGraphicSLD = msSLDGetGraphicSLD(psStyle, psLayer, 0, nVersion);
-            if (pszGraphicSLD)
-            {
-                snprintf(szTmp, sizeof(szTmp), "<%sGraphicFill>\n",  sNameSpace);
-                pszSLD = msStringConcatenate(pszSLD, szTmp);
 
-                pszSLD = msStringConcatenate(pszSLD, pszGraphicSLD);
-                snprintf(szTmp, sizeof(szTmp), "</%sGraphicFill>\n",  sNameSpace);
-                pszSLD = msStringConcatenate(pszSLD, szTmp);
-             
-                free(pszGraphicSLD);
-                pszGraphicSLD = NULL;
-            }
-        }
-
-        sprintf(szHexColor,"%02x%02x%02x",psStyle->outlinecolor.red,
-                psStyle->outlinecolor.green,
-                psStyle->outlinecolor.blue);
-        
-        snprintf(szTmp, sizeof(szTmp),
-                "<%s name=\"stroke\">#%s</%s>\n", 
-                sCssParam, szHexColor, sCssParam);
+    /* If there is a symbol to be used for sroke, the color in the */
+    /* style sholud be set to -1. Else It won't apply here. */
+    if (psStyle->color.red == -1 && psStyle->color.green == -1 &&
+        psStyle->color.blue == -1) {
+      pszGraphicSLD = msSLDGetGraphicSLD(psStyle, psLayer, 0, nVersion);
+      if (pszGraphicSLD) {
+        snprintf(szTmp, sizeof(szTmp), "<%sGraphicFill>\n",  sNameSpace);
         pszSLD = msStringConcatenate(pszSLD, szTmp);
 
-        dfSize = 1.0;
-        if (psStyle->size > 0)
-          dfSize = psStyle->size;
-        else if (psStyle->width > 0)
-          dfSize = psStyle->width;
-            
-        snprintf(szTmp, sizeof(szTmp),
-            "<%s name=\"stroke-width\">%.2f</%s>\n",
-                sCssParam,dfSize,sCssParam);
+        pszSLD = msStringConcatenate(pszSLD, pszGraphicSLD);
+        snprintf(szTmp, sizeof(szTmp), "</%sGraphicFill>\n",  sNameSpace);
         pszSLD = msStringConcatenate(pszSLD, szTmp);
 
-        snprintf(szTmp, sizeof(szTmp), "</%sStroke>\n",  sNameSpace);
-        pszSLD = msStringConcatenate(pszSLD, szTmp);
+        free(pszGraphicSLD);
+        pszGraphicSLD = NULL;
+      }
     }
 
-    snprintf(szTmp, sizeof(szTmp), "</%sPolygonSymbolizer>\n", sNameSpace);
+    sprintf(szHexColor,"%02x%02x%02x",psStyle->outlinecolor.red,
+            psStyle->outlinecolor.green,
+            psStyle->outlinecolor.blue);
+
+    snprintf(szTmp, sizeof(szTmp),
+             "<%s name=\"stroke\">#%s</%s>\n",
+             sCssParam, szHexColor, sCssParam);
+    pszSLD = msStringConcatenate(pszSLD, szTmp);
+
+    dfSize = 1.0;
+    if (psStyle->size > 0)
+      dfSize = psStyle->size;
+    else if (psStyle->width > 0)
+      dfSize = psStyle->width;
+
+    snprintf(szTmp, sizeof(szTmp),
+             "<%s name=\"stroke-width\">%.2f</%s>\n",
+             sCssParam,dfSize,sCssParam);
+    pszSLD = msStringConcatenate(pszSLD, szTmp);
+
+    snprintf(szTmp, sizeof(szTmp), "</%sStroke>\n",  sNameSpace);
     pszSLD = msStringConcatenate(pszSLD, szTmp);
+  }
+
+  snprintf(szTmp, sizeof(szTmp), "</%sPolygonSymbolizer>\n", sNameSpace);
+  pszSLD = msStringConcatenate(pszSLD, szTmp);
 
-    return pszSLD;
+  return pszSLD;
 
 #else
-    return NULL;
+  return NULL;
 #endif
 }
 
@@ -3966,32 +3751,31 @@ char *msSLDGeneratePolygonSLD(styleObj *psStyle, layerObj *psLayer, int nVersion
 char *msSLDGeneratePointSLD(styleObj *psStyle, layerObj *psLayer, int nVersion)
 {
 #if defined(USE_WMS_SVR) || defined (USE_WFS_SVR) || defined (USE_WCS_SVR) || defined(USE_SOS_SVR)
-    char *pszSLD = NULL;
-    char *pszGraphicSLD = NULL;
-    char szTmp[100];
-    char sNameSpace[10];
+  char *pszSLD = NULL;
+  char *pszGraphicSLD = NULL;
+  char szTmp[100];
+  char sNameSpace[10];
 
-    sNameSpace[0] = '\0';
-    if (nVersion > OWS_1_0_0)
-      strcpy(sNameSpace, "se:");
+  sNameSpace[0] = '\0';
+  if (nVersion > OWS_1_0_0)
+    strcpy(sNameSpace, "se:");
 
-    snprintf(szTmp, sizeof(szTmp), "<%sPointSymbolizer>\n",  sNameSpace);
-    pszSLD = msStringConcatenate(pszSLD, szTmp);
+  snprintf(szTmp, sizeof(szTmp), "<%sPointSymbolizer>\n",  sNameSpace);
+  pszSLD = msStringConcatenate(pszSLD, szTmp);
 
-    pszGraphicSLD = msSLDGetGraphicSLD(psStyle, psLayer, 1, nVersion);
-    if (pszGraphicSLD)
-    {
-        pszSLD = msStringConcatenate(pszSLD, pszGraphicSLD);
-        free(pszGraphicSLD);
-    }
-    
-    snprintf(szTmp, sizeof(szTmp), "</%sPointSymbolizer>\n",  sNameSpace);
-    pszSLD = msStringConcatenate(pszSLD, szTmp);
+  pszGraphicSLD = msSLDGetGraphicSLD(psStyle, psLayer, 1, nVersion);
+  if (pszGraphicSLD) {
+    pszSLD = msStringConcatenate(pszSLD, pszGraphicSLD);
+    free(pszGraphicSLD);
+  }
+
+  snprintf(szTmp, sizeof(szTmp), "</%sPointSymbolizer>\n",  sNameSpace);
+  pszSLD = msStringConcatenate(pszSLD, szTmp);
 
-    return pszSLD;
+  return pszSLD;
 
 #else
-    return NULL;
+  return NULL;
 
 #endif
 }
@@ -4007,236 +3791,207 @@ char *msSLDGeneratePointSLD(styleObj *psStyle, layerObj *psLayer, int nVersion)
 char *msSLDGenerateTextSLD(classObj *psClass, layerObj *psLayer, int nVersion)
 {
 #if defined(USE_WMS_SVR) || defined (USE_WFS_SVR) || defined (USE_WCS_SVR) || defined(USE_SOS_SVR)
-    char *pszSLD = NULL;
-
-    char szTmp[100];
-    char **aszFontsParts = NULL;
-    int nFontParts = 0;
-    char szHexColor[7];
-    int nColorRed=-1, nColorGreen=-1, nColorBlue=-1;
-    double dfAnchorX = 0.5, dfAnchorY = 0.5;
-    int i = 0;
-    char sCssParam[30];
-    char sNameSpace[10];
-
-    sCssParam[0] = '\0';
-    if (nVersion > OWS_1_0_0)
-      strcpy(sCssParam, "se:SvgParameter");
-    else
-      strcpy(sCssParam, "CssParameter");
-
-    sNameSpace[0] = '\0';
-    if (nVersion > OWS_1_0_0)
-      strcpy(sNameSpace, "se:");
+  char *pszSLD = NULL;
+
+  char szTmp[100];
+  char **aszFontsParts = NULL;
+  int nFontParts = 0;
+  char szHexColor[7];
+  int nColorRed=-1, nColorGreen=-1, nColorBlue=-1;
+  double dfAnchorX = 0.5, dfAnchorY = 0.5;
+  int i = 0;
+  char sCssParam[30];
+  char sNameSpace[10];
+  labelObj *psLabelObj = NULL;
+
+  sCssParam[0] = '\0';
+  if (nVersion > OWS_1_0_0)
+    strcpy(sCssParam, "se:SvgParameter");
+  else
+    strcpy(sCssParam, "CssParameter");
+
+  sNameSpace[0] = '\0';
+  if (nVersion > OWS_1_0_0)
+    strcpy(sNameSpace, "se:");
+
+
+  if (psClass && psLayer && psLayer->labelitem &&
+      strlen(psLayer->labelitem) > 0 && psClass->numlabels > 0) {
+    psLabelObj = psClass->labels[0];
+    snprintf(szTmp, sizeof(szTmp), "<%sTextSymbolizer>\n",  sNameSpace);
+    pszSLD = msStringConcatenate(pszSLD, szTmp);
 
+    snprintf(szTmp, sizeof(szTmp), "<%sLabel>%s</%sLabel>\n",  sNameSpace,
+             psLayer->labelitem, sNameSpace);
+    pszSLD = msStringConcatenate(pszSLD, szTmp);
 
-    if (psClass && psLayer && psLayer->labelitem && 
-        strlen(psLayer->labelitem) > 0)
-    {
-        snprintf(szTmp, sizeof(szTmp), "<%sTextSymbolizer>\n",  sNameSpace);
+    /* -------------------------------------------------------------------- */
+    /*      only true type fonts are exported. Font name should be          */
+    /*      something like arial-bold-italic. There are 3 parts to the      */
+    /*      name font-family, font-style (italic, oblique, nomal),          */
+    /*      font-weight (bold, normal). These 3 elements are separated      */
+    /*      with -.                                                         */
+    /* -------------------------------------------------------------------- */
+    if (psLabelObj->type == MS_TRUETYPE && psLabelObj->font) {
+      aszFontsParts = msStringSplit(psLabelObj->font, '-', &nFontParts);
+      if (nFontParts > 0) {
+        snprintf(szTmp, sizeof(szTmp), "<%sFont>\n",  sNameSpace);
         pszSLD = msStringConcatenate(pszSLD, szTmp);
 
-        snprintf(szTmp, sizeof(szTmp), "<%sLabel>%s</%sLabel>\n",  sNameSpace,
-                psLayer->labelitem, sNameSpace);
+        /* assuming first one is font-family */
+        snprintf(szTmp, sizeof(szTmp),
+                 "<%s name=\"font-family\">%s</%s>\n",
+                 sCssParam, aszFontsParts[0], sCssParam);
         pszSLD = msStringConcatenate(pszSLD, szTmp);
-
-/* -------------------------------------------------------------------- */
-/*      only true type fonts are exported. Font name should be          */
-/*      something like arial-bold-italic. There are 3 parts to the      */
-/*      name font-family, font-style (italic, oblique, nomal),          */
-/*      font-weight (bold, normal). These 3 elements are separated      */
-/*      with -.                                                         */
-/* -------------------------------------------------------------------- */
-        if (psClass->label.type == MS_TRUETYPE && psClass->label.font)
-        {
-            aszFontsParts = msStringSplit(psClass->label.font, '-', &nFontParts);
-            if (nFontParts > 0)
-            {
-                snprintf(szTmp, sizeof(szTmp), "<%sFont>\n",  sNameSpace);
-                pszSLD = msStringConcatenate(pszSLD, szTmp);
-
-                /* assuming first one is font-family */
-                snprintf(szTmp, sizeof(szTmp), 
-                         "<%s name=\"font-family\">%s</%s>\n",
-                         sCssParam, aszFontsParts[0], sCssParam);
-                pszSLD = msStringConcatenate(pszSLD, szTmp);
-                for (i=1; i<nFontParts; i++)
-                {
-                    if (strcasecmp(aszFontsParts[i], "italic") == 0 ||
-                        strcasecmp(aszFontsParts[i], "oblique") == 0)
-                    {
-                        snprintf(szTmp, sizeof(szTmp),
-                                 "<%s name=\"font-style\">%s</%s>\n",
-                                 sCssParam, aszFontsParts[i], sCssParam);
-                        pszSLD = msStringConcatenate(pszSLD, szTmp);
-                    }
-                    else if (strcasecmp(aszFontsParts[i], "bold") == 0)
-                    {
-                        snprintf(szTmp, sizeof(szTmp),
-                                 "<%s name=\"font-weight\">%s</%s>\n",
-                                 sCssParam,
-                                 aszFontsParts[i], sCssParam);
-                        pszSLD = msStringConcatenate(pszSLD, szTmp);
-                    }
-                }
-                /* size */
-                if (psClass->label.size > 0)
-                {
-                    snprintf(szTmp, sizeof(szTmp),
-                            "<%s name=\"font-size\">%.2f</%s>\n",
-                            sCssParam, psClass->label.size, sCssParam);
-                    pszSLD = msStringConcatenate(pszSLD, szTmp);
-                }
-                snprintf(szTmp, sizeof(szTmp), "</%sFont>\n",  sNameSpace);
-                pszSLD = msStringConcatenate(pszSLD, szTmp);
-
-                msFreeCharArray(aszFontsParts, nFontParts);
-            }
+        for (i=1; i<nFontParts; i++) {
+          if (strcasecmp(aszFontsParts[i], "italic") == 0 ||
+              strcasecmp(aszFontsParts[i], "oblique") == 0) {
+            snprintf(szTmp, sizeof(szTmp),
+                     "<%s name=\"font-style\">%s</%s>\n",
+                     sCssParam, aszFontsParts[i], sCssParam);
+            pszSLD = msStringConcatenate(pszSLD, szTmp);
+          } else if (strcasecmp(aszFontsParts[i], "bold") == 0) {
+            snprintf(szTmp, sizeof(szTmp),
+                     "<%s name=\"font-weight\">%s</%s>\n",
+                     sCssParam,
+                     aszFontsParts[i], sCssParam);
+            pszSLD = msStringConcatenate(pszSLD, szTmp);
+          }
+        }
+        /* size */
+        if (psLabelObj->size > 0) {
+          snprintf(szTmp, sizeof(szTmp),
+                   "<%s name=\"font-size\">%.2f</%s>\n",
+                   sCssParam, psLabelObj->size, sCssParam);
+          pszSLD = msStringConcatenate(pszSLD, szTmp);
         }
-        
-        
-        /* label placement */
-        snprintf(szTmp, sizeof(szTmp), "<%sLabelPlacement>\n<%sPointPlacement>\n", 
-                 sNameSpace, sNameSpace  );
+        snprintf(szTmp, sizeof(szTmp), "</%sFont>\n",  sNameSpace);
         pszSLD = msStringConcatenate(pszSLD, szTmp);
 
-        snprintf(szTmp, sizeof(szTmp), "<%sAnchorPoint>\n", sNameSpace);
-        pszSLD = msStringConcatenate(pszSLD, szTmp);
+        msFreeCharArray(aszFontsParts, nFontParts);
+      }
+    }
 
-        if (psClass->label.position == MS_LL)
-        {
-            dfAnchorX =0; 
-            dfAnchorY = 0;
-        }
-        else if (psClass->label.position == MS_CL)
-        {
-            dfAnchorX =0; 
-            dfAnchorY = 0.5;
-        }
-        else if (psClass->label.position == MS_UL)
-        {
-            dfAnchorX =0; 
-            dfAnchorY = 1;
-        }
-        
-        else if (psClass->label.position == MS_LC)
-        {
-            dfAnchorX =0.5; 
-            dfAnchorY = 0;
-        }
-        else if (psClass->label.position == MS_CC)
-        {
-            dfAnchorX =0.5; 
-            dfAnchorY = 0.5;
-        }
-        else if (psClass->label.position == MS_UC)
-        {
-            dfAnchorX =0.5; 
-            dfAnchorY = 1;
-        }
-        
-        else if (psClass->label.position == MS_LR)
-        {
-            dfAnchorX =1; 
-            dfAnchorY = 0;
-        }
-        else if (psClass->label.position == MS_CR)
-        {
-            dfAnchorX =1; 
-            dfAnchorY = 0.5;
-        }
-        else if (psClass->label.position == MS_UR)
-        {
-            dfAnchorX =1; 
-            dfAnchorY = 1;
-        }
-        snprintf(szTmp, sizeof(szTmp), "<%sAnchorPointX>%.1f</%sAnchorPointX>\n", 
-                 sNameSpace, dfAnchorX, sNameSpace);
-        pszSLD = msStringConcatenate(pszSLD, szTmp);
-        snprintf(szTmp, sizeof(szTmp), "<%sAnchorPointY>%.1f</%sAnchorPointY>\n", sNameSpace,
-                 dfAnchorY, sNameSpace);
-        pszSLD = msStringConcatenate(pszSLD, szTmp);
 
-        snprintf(szTmp, sizeof(szTmp), "</%sAnchorPoint>\n",  sNameSpace);
-        pszSLD = msStringConcatenate(pszSLD, szTmp);
+    /* label placement */
+    snprintf(szTmp, sizeof(szTmp), "<%sLabelPlacement>\n<%sPointPlacement>\n",
+             sNameSpace, sNameSpace  );
+    pszSLD = msStringConcatenate(pszSLD, szTmp);
 
-        /* displacement */
-        if (psClass->label.offsetx > 0 || psClass->label.offsety > 0)
-        {
-            snprintf(szTmp, sizeof(szTmp), "<%sDisplacement>\n",  sNameSpace);
-            pszSLD = msStringConcatenate(pszSLD, szTmp);
+    snprintf(szTmp, sizeof(szTmp), "<%sAnchorPoint>\n", sNameSpace);
+    pszSLD = msStringConcatenate(pszSLD, szTmp);
 
-            if (psClass->label.offsetx > 0)
-            {
-                snprintf(szTmp, sizeof(szTmp), "<%sDisplacementX>%d</%sDisplacementX>\n", 
-                         sNameSpace, psClass->label.offsetx, sNameSpace);
-                pszSLD = msStringConcatenate(pszSLD, szTmp);
-            }
-            if (psClass->label.offsety > 0)
-            {
-                snprintf(szTmp, sizeof(szTmp), "<%sDisplacementY>%d</%sDisplacementY>\n", 
-                         sNameSpace, psClass->label.offsety, sNameSpace);
-                pszSLD = msStringConcatenate(pszSLD, szTmp);
-            }
+    if (psLabelObj->position == MS_LL) {
+      dfAnchorX =0;
+      dfAnchorY = 0;
+    } else if (psLabelObj->position == MS_CL) {
+      dfAnchorX =0;
+      dfAnchorY = 0.5;
+    } else if (psLabelObj->position == MS_UL) {
+      dfAnchorX =0;
+      dfAnchorY = 1;
+    }
 
-            snprintf(szTmp,  sizeof(szTmp), "</%sDisplacement>\n",  sNameSpace);
-            pszSLD = msStringConcatenate(pszSLD, szTmp);
-        }
-        /* rotation */
-        if (psClass->label.angle > 0)
-        {
-            snprintf(szTmp, sizeof(szTmp), "<%sRotation>%.2f</%sRotation>\n", 
-                     sNameSpace, psClass->label.angle, sNameSpace);
-            pszSLD = msStringConcatenate(pszSLD, szTmp);
-        }
+    else if (psLabelObj->position == MS_LC) {
+      dfAnchorX =0.5;
+      dfAnchorY = 0;
+    } else if (psLabelObj->position == MS_CC) {
+      dfAnchorX =0.5;
+      dfAnchorY = 0.5;
+    } else if (psLabelObj->position == MS_UC) {
+      dfAnchorX =0.5;
+      dfAnchorY = 1;
+    }
 
-         /* TODO : support Halo parameter => shadow */
+    else if (psLabelObj->position == MS_LR) {
+      dfAnchorX =1;
+      dfAnchorY = 0;
+    } else if (psLabelObj->position == MS_CR) {
+      dfAnchorX =1;
+      dfAnchorY = 0.5;
+    } else if (psLabelObj->position == MS_UR) {
+      dfAnchorX =1;
+      dfAnchorY = 1;
+    }
+    snprintf(szTmp, sizeof(szTmp), "<%sAnchorPointX>%.1f</%sAnchorPointX>\n",
+             sNameSpace, dfAnchorX, sNameSpace);
+    pszSLD = msStringConcatenate(pszSLD, szTmp);
+    snprintf(szTmp, sizeof(szTmp), "<%sAnchorPointY>%.1f</%sAnchorPointY>\n", sNameSpace,
+             dfAnchorY, sNameSpace);
+    pszSLD = msStringConcatenate(pszSLD, szTmp);
+
+    snprintf(szTmp, sizeof(szTmp), "</%sAnchorPoint>\n",  sNameSpace);
+    pszSLD = msStringConcatenate(pszSLD, szTmp);
 
-        snprintf(szTmp, sizeof(szTmp), "</%sPointPlacement>\n</%sLabelPlacement>\n", sNameSpace, sNameSpace);
+    /* displacement */
+    if (psLabelObj->offsetx > 0 || psLabelObj->offsety > 0) {
+      snprintf(szTmp, sizeof(szTmp), "<%sDisplacement>\n",  sNameSpace);
+      pszSLD = msStringConcatenate(pszSLD, szTmp);
+
+      if (psLabelObj->offsetx > 0) {
+        snprintf(szTmp, sizeof(szTmp), "<%sDisplacementX>%d</%sDisplacementX>\n",
+                 sNameSpace, psLabelObj->offsetx, sNameSpace);
+        pszSLD = msStringConcatenate(pszSLD, szTmp);
+      }
+      if (psLabelObj->offsety > 0) {
+        snprintf(szTmp, sizeof(szTmp), "<%sDisplacementY>%d</%sDisplacementY>\n",
+                 sNameSpace, psLabelObj->offsety, sNameSpace);
         pszSLD = msStringConcatenate(pszSLD, szTmp);
+      }
 
+      snprintf(szTmp,  sizeof(szTmp), "</%sDisplacement>\n",  sNameSpace);
+      pszSLD = msStringConcatenate(pszSLD, szTmp);
+    }
+    /* rotation */
+    if (psLabelObj->angle > 0) {
+      snprintf(szTmp, sizeof(szTmp), "<%sRotation>%.2f</%sRotation>\n",
+               sNameSpace, psLabelObj->angle, sNameSpace);
+      pszSLD = msStringConcatenate(pszSLD, szTmp);
+    }
 
-        /* color */
-        if (psClass->label.color.red != -1 &&
-            psClass->label.color.green != -1 &&
-            psClass->label.color.blue != -1)
-        {
-            nColorRed = psClass->label.color.red;
-            nColorGreen = psClass->label.color.green;
-            nColorBlue = psClass->label.color.blue;
-        }
-        else if (psClass->label.outlinecolor.red != -1 &&
-                 psClass->label.outlinecolor.green != -1 &&
-                 psClass->label.outlinecolor.blue != -1)
-        {
-            nColorRed = psClass->label.outlinecolor.red;
-            nColorGreen = psClass->label.outlinecolor.green;
-            nColorBlue = psClass->label.outlinecolor.blue;
-        }
-        if (nColorRed >= 0 && nColorGreen >= 0  && nColorBlue >=0)
-        {
-            snprintf(szTmp, sizeof(szTmp), "<%sFill>\n", sNameSpace );
-            pszSLD = msStringConcatenate(pszSLD, szTmp);
-            
-            sprintf(szHexColor,"%02x%02x%02x",nColorRed,
-                    nColorGreen, nColorBlue);
+    /* TODO : support Halo parameter => shadow */
 
-            snprintf(szTmp, sizeof(szTmp),
-                     "<%s name=\"fill\">#%s</%s>\n", 
-                     sCssParam, szHexColor, sCssParam);
-            pszSLD = msStringConcatenate(pszSLD, szTmp);
+    snprintf(szTmp, sizeof(szTmp), "</%sPointPlacement>\n</%sLabelPlacement>\n", sNameSpace, sNameSpace);
+    pszSLD = msStringConcatenate(pszSLD, szTmp);
 
-            snprintf(szTmp, sizeof(szTmp), "</%sFill>\n",  sNameSpace);
-            pszSLD = msStringConcatenate(pszSLD, szTmp);
-        }
-        
-        snprintf(szTmp, sizeof(szTmp), "</%sTextSymbolizer>\n",  sNameSpace);
-        pszSLD = msStringConcatenate(pszSLD, szTmp);
+
+    /* color */
+    if (psLabelObj->color.red != -1 &&
+        psLabelObj->color.green != -1 &&
+        psLabelObj->color.blue != -1) {
+      nColorRed = psLabelObj->color.red;
+      nColorGreen = psLabelObj->color.green;
+      nColorBlue = psLabelObj->color.blue;
+    } else if (psLabelObj->outlinecolor.red != -1 &&
+               psLabelObj->outlinecolor.green != -1 &&
+               psLabelObj->outlinecolor.blue != -1) {
+      nColorRed = psLabelObj->outlinecolor.red;
+      nColorGreen = psLabelObj->outlinecolor.green;
+      nColorBlue = psLabelObj->outlinecolor.blue;
     }
-    return pszSLD;
+    if (nColorRed >= 0 && nColorGreen >= 0  && nColorBlue >=0) {
+      snprintf(szTmp, sizeof(szTmp), "<%sFill>\n", sNameSpace );
+      pszSLD = msStringConcatenate(pszSLD, szTmp);
+
+      sprintf(szHexColor,"%02x%02x%02x",nColorRed,
+              nColorGreen, nColorBlue);
+
+      snprintf(szTmp, sizeof(szTmp),
+               "<%s name=\"fill\">#%s</%s>\n",
+               sCssParam, szHexColor, sCssParam);
+      pszSLD = msStringConcatenate(pszSLD, szTmp);
+
+      snprintf(szTmp, sizeof(szTmp), "</%sFill>\n",  sNameSpace);
+      pszSLD = msStringConcatenate(pszSLD, szTmp);
+    }
+
+    snprintf(szTmp, sizeof(szTmp), "</%sTextSymbolizer>\n",  sNameSpace);
+    pszSLD = msStringConcatenate(pszSLD, szTmp);
+  }
+  return pszSLD;
 
 #else
-    return NULL;
+  return NULL;
 #endif
 }
 
@@ -4251,276 +4006,248 @@ char *msSLDGenerateSLDLayer(layerObj *psLayer, int nVersion)
 #if defined(USE_WMS_SVR) || defined (USE_WFS_SVR) || defined (USE_WCS_SVR) || defined(USE_SOS_SVR)
 
 #ifdef USE_OGR
-    char szTmp[100];
-    char *pszTmpName = NULL;
-    int i, j;
-    styleObj *psStyle = NULL;
-    char *pszFilter = NULL;
-    char *pszFinalSLD = NULL;
-    char *pszSLD = NULL;
-    const char *pszTmp = NULL;
-    double dfMinScale =-1, dfMaxScale = -1;
-    const char *pszWfsFilter= NULL;
-    char *pszEncoded = NULL, *pszWfsFilterEncoded=NULL;
-
-    
-    if (psLayer && 
-        (psLayer->status == MS_ON || psLayer->status == MS_DEFAULT) &&
-        (psLayer->type == MS_LAYER_POINT ||
-                    psLayer->type == MS_LAYER_LINE ||
-                    psLayer->type == MS_LAYER_POLYGON ||
-                    psLayer->type == MS_LAYER_ANNOTATION))
-    {
-        snprintf(szTmp, sizeof(szTmp), "%s\n",  "<NamedLayer>");
-        pszFinalSLD = msStringConcatenate(pszFinalSLD, szTmp);
+  char szTmp[100];
+  char *pszTmpName = NULL;
+  int i, j;
+  styleObj *psStyle = NULL;
+  char *pszFilter = NULL;
+  char *pszFinalSLD = NULL;
+  char *pszSLD = NULL;
+  const char *pszTmp = NULL;
+  double dfMinScale =-1, dfMaxScale = -1;
+  const char *pszWfsFilter= NULL;
+  char *pszEncoded = NULL, *pszWfsFilterEncoded=NULL;
+
+
+  if (psLayer &&
+      (psLayer->status == MS_ON || psLayer->status == MS_DEFAULT) &&
+      (psLayer->type == MS_LAYER_POINT ||
+       psLayer->type == MS_LAYER_LINE ||
+       psLayer->type == MS_LAYER_POLYGON ||
+       psLayer->type == MS_LAYER_ANNOTATION)) {
+    snprintf(szTmp, sizeof(szTmp), "%s\n",  "<NamedLayer>");
+    pszFinalSLD = msStringConcatenate(pszFinalSLD, szTmp);
+
+    pszTmp = msOWSLookupMetadata(&(psLayer->metadata), "MO", "name");
+    if (pszTmp) {
+      pszEncoded = msEncodeHTMLEntities(pszTmp);
+      if (nVersion > OWS_1_0_0)
+        snprintf(szTmp, sizeof(szTmp), "<se:Name>%s</se:Name>\n", pszEncoded);
+      else
+        snprintf(szTmp, sizeof(szTmp), "<Name>%s</Name>\n", pszEncoded);
+      pszFinalSLD = msStringConcatenate(pszFinalSLD, szTmp);
+      msFree(pszEncoded);
+    } else if (psLayer->name) {
+      pszEncoded = msEncodeHTMLEntities(psLayer->name);
+      pszTmpName = (char *)malloc(sizeof(char)*(strlen(pszEncoded)+100));
+      if (nVersion > OWS_1_0_0)
+        sprintf(pszTmpName, "<se:Name>%s</se:Name>\n", pszEncoded);
+      else
+        sprintf(pszTmpName, "<Name>%s</Name>\n", pszEncoded);
+
+
+      msFree(pszEncoded);
+      pszFinalSLD = msStringConcatenate(pszFinalSLD, pszTmpName);
+      msFree(pszTmpName);
+      pszTmpName=NULL;
+
+    } else {
+      if (nVersion > OWS_1_0_0)
+        snprintf(szTmp, sizeof(szTmp), "<se:Name>%s</se:Name>\n", "NamedLayer");
+      else
+        snprintf(szTmp, sizeof(szTmp), "<Name>%s</Name>\n", "NamedLayer");
+      pszFinalSLD = msStringConcatenate(pszFinalSLD, szTmp);
+    }
 
-        pszTmp = msOWSLookupMetadata(&(psLayer->metadata), "MO", "name");
-        if (pszTmp)
-        {
-            pszEncoded = msEncodeHTMLEntities(pszTmp);
-            if (nVersion > OWS_1_0_0)
-              snprintf(szTmp, sizeof(szTmp), "<se:Name>%s</se:Name>\n", pszEncoded);
-            else
-              snprintf(szTmp, sizeof(szTmp), "<Name>%s</Name>\n", pszEncoded);
-	     pszFinalSLD = msStringConcatenate(pszFinalSLD, szTmp);
-            msFree(pszEncoded);
-        }
-        else if (psLayer->name)
-        {
-            pszEncoded = msEncodeHTMLEntities(psLayer->name);
-            pszTmpName = (char *)malloc(sizeof(char)*(strlen(pszEncoded)+100));
-            if (nVersion > OWS_1_0_0)
-              sprintf(pszTmpName, "<se:Name>%s</se:Name>\n", pszEncoded);
-            else
-              sprintf(pszTmpName, "<Name>%s</Name>\n", pszEncoded);
-            
-            
-            msFree(pszEncoded);
-            pszFinalSLD = msStringConcatenate(pszFinalSLD, pszTmpName);
-            msFree(pszTmpName);
-            pszTmpName=NULL;
 
-        }
-        else
-        {
-            if (nVersion > OWS_1_0_0)
-                snprintf(szTmp, sizeof(szTmp), "<se:Name>%s</se:Name>\n", "NamedLayer");
-            else
-                snprintf(szTmp, sizeof(szTmp), "<Name>%s</Name>\n", "NamedLayer"); 
-            pszFinalSLD = msStringConcatenate(pszFinalSLD, szTmp);
-        }
-        
+    snprintf(szTmp,  sizeof(szTmp), "%s\n",  "<UserStyle>");
+    pszFinalSLD = msStringConcatenate(pszFinalSLD, szTmp);
 
-        snprintf(szTmp,  sizeof(szTmp), "%s\n",  "<UserStyle>");
-        pszFinalSLD = msStringConcatenate(pszFinalSLD, szTmp);
+    if (nVersion > OWS_1_0_0)
+      snprintf(szTmp, sizeof(szTmp), "%s\n",  "<se:FeatureTypeStyle>");
+    else
+      snprintf(szTmp, sizeof(szTmp), "%s\n",  "<FeatureTypeStyle>");
 
+    pszFinalSLD = msStringConcatenate(pszFinalSLD, szTmp);
+
+    pszWfsFilter = msLookupHashTable(&(psLayer->metadata), "wfs_filter");
+    if (pszWfsFilter)
+      pszWfsFilterEncoded = msEncodeHTMLEntities(pszWfsFilter);
+    if (psLayer->numclasses > 0) {
+      for (i=0; i<psLayer->numclasses; i++) {
         if (nVersion > OWS_1_0_0)
-          snprintf(szTmp, sizeof(szTmp), "%s\n",  "<se:FeatureTypeStyle>");
+          snprintf(szTmp, sizeof(szTmp), "%s\n",  "<se:Rule>");
         else
-          snprintf(szTmp, sizeof(szTmp), "%s\n",  "<FeatureTypeStyle>");
+          snprintf(szTmp, sizeof(szTmp), "%s\n",  "<Rule>");
 
         pszFinalSLD = msStringConcatenate(pszFinalSLD, szTmp);
 
-        pszWfsFilter = msLookupHashTable(&(psLayer->metadata), "wfs_filter");
-        if (pszWfsFilter)
-          pszWfsFilterEncoded = msEncodeHTMLEntities(pszWfsFilter);
-        if (psLayer->numclasses > 0)
-        {
-	  for (i=0; i<psLayer->numclasses; i++)
-            {
-                if (nVersion > OWS_1_0_0)
-                  snprintf(szTmp, sizeof(szTmp), "%s\n",  "<se:Rule>");
-                else
-                  snprintf(szTmp, sizeof(szTmp), "%s\n",  "<Rule>");
+        /* if class has a name, use it as the RULE name */
+        if (psLayer->class[i]->name) {
+          pszEncoded = msEncodeHTMLEntities(psLayer->class[i]->name);
+          pszTmpName = (char *)malloc(sizeof(char)*(strlen(pszEncoded)+100));
 
-                pszFinalSLD = msStringConcatenate(pszFinalSLD, szTmp);
+          if (nVersion > OWS_1_0_0)
+            sprintf(pszTmpName, "<se:Name>%s</se:Name>\n",  pszEncoded);
+          else
+            sprintf(pszTmpName, "<Name>%s</Name>\n",  pszEncoded);
 
-                /* if class has a name, use it as the RULE name */
-                if (psLayer->class[i]->name)
-                {
-                    pszEncoded = msEncodeHTMLEntities(psLayer->class[i]->name);
-                    pszTmpName = (char *)malloc(sizeof(char)*(strlen(pszEncoded)+100));
+          msFree(pszEncoded);
 
-                    if (nVersion > OWS_1_0_0)
-                      sprintf(pszTmpName, "<se:Name>%s</se:Name>\n",  pszEncoded);
-                    else
-                      sprintf(pszTmpName, "<Name>%s</Name>\n",  pszEncoded);
+          pszFinalSLD = msStringConcatenate(pszFinalSLD, pszTmpName);
+          msFree(pszTmpName);
+          pszTmpName=NULL;
+        }
+        /* -------------------------------------------------------------------- */
+        /*      get the Filter if there is a class expression.                  */
+        /* -------------------------------------------------------------------- */
+        pszFilter = msSLDGetFilter(psLayer->class[i] ,
+                                   pszWfsFilter);/* pszWfsFilterEncoded); */
+
+        if (pszFilter) {
+          pszFinalSLD = msStringConcatenate(pszFinalSLD, pszFilter);
+          free(pszFilter);
+        }
+        /* -------------------------------------------------------------------- */
+        /*      generate the min/max scale.                                     */
+        /* -------------------------------------------------------------------- */
+        dfMinScale = -1.0;
+        if (psLayer->class[i]->minscaledenom > 0)
+          dfMinScale = psLayer->class[i]->minscaledenom;
+        else if (psLayer->minscaledenom > 0)
+          dfMinScale = psLayer->minscaledenom;
+        else if (psLayer->map && psLayer->map->web.minscaledenom > 0)
+          dfMinScale = psLayer->map->web.minscaledenom;
+        if (dfMinScale > 0) {
+          if (nVersion > OWS_1_0_0)
+            snprintf(szTmp, sizeof(szTmp), "<se:MinScaleDenominator>%f</se:MinScaleDenominator>\n",
+                     dfMinScale);
+          else
+            snprintf(szTmp, sizeof(szTmp), "<MinScaleDenominator>%f</MinScaleDenominator>\n",
+                     dfMinScale);
+
+          pszFinalSLD = msStringConcatenate(pszFinalSLD, szTmp);
+        }
 
-                    msFree(pszEncoded);
+        dfMaxScale = -1.0;
+        if (psLayer->class[i]->maxscaledenom > 0)
+          dfMaxScale = psLayer->class[i]->maxscaledenom;
+        else if (psLayer->maxscaledenom > 0)
+          dfMaxScale = psLayer->maxscaledenom;
+        else if (psLayer->map && psLayer->map->web.maxscaledenom > 0)
+          dfMaxScale = psLayer->map->web.maxscaledenom;
+        if (dfMaxScale > 0) {
+          if (nVersion > OWS_1_0_0)
+            snprintf(szTmp, sizeof(szTmp), "<se:MaxScaleDenominator>%f</se:MaxScaleDenominator>\n",
+                     dfMaxScale);
+          else
+            snprintf(szTmp, sizeof(szTmp), "<MaxScaleDenominator>%f</MaxScaleDenominator>\n",
+                     dfMaxScale);
+
+          pszFinalSLD = msStringConcatenate(pszFinalSLD, szTmp);
+        }
 
-                    pszFinalSLD = msStringConcatenate(pszFinalSLD, pszTmpName);
-                    msFree(pszTmpName);
-                    pszTmpName=NULL;
-               }
-/* -------------------------------------------------------------------- */
-/*      get the Filter if there is a class expression.                  */
-/* -------------------------------------------------------------------- */
-                pszFilter = msSLDGetFilter(psLayer->class[i] ,
-                                           pszWfsFilter);/* pszWfsFilterEncoded); */
-                    
-                if (pszFilter)
-                {
-                    pszFinalSLD = msStringConcatenate(pszFinalSLD, pszFilter);
-                    free(pszFilter);
-                }
-/* -------------------------------------------------------------------- */
-/*      generate the min/max scale.                                     */
-/* -------------------------------------------------------------------- */
-                dfMinScale = -1.0;
-                if (psLayer->class[i]->minscaledenom > 0)
-                  dfMinScale = psLayer->class[i]->minscaledenom;      
-                else if (psLayer->minscaledenom > 0)
-                  dfMinScale = psLayer->minscaledenom;
-                else if (psLayer->map && psLayer->map->web.minscaledenom > 0)
-                  dfMinScale = psLayer->map->web.minscaledenom;
-                if (dfMinScale > 0)
-                {
-                    if (nVersion > OWS_1_0_0)
-                      snprintf(szTmp, sizeof(szTmp), "<se:MinScaleDenominator>%f</se:MinScaleDenominator>\n",  
-                               dfMinScale);
-                    else
-                      snprintf(szTmp, sizeof(szTmp), "<MinScaleDenominator>%f</MinScaleDenominator>\n",  
-                               dfMinScale);
-
-                     pszFinalSLD = msStringConcatenate(pszFinalSLD, szTmp);
-                }
-               
-                dfMaxScale = -1.0;
-                if (psLayer->class[i]->maxscaledenom > 0)
-                  dfMaxScale = psLayer->class[i]->maxscaledenom;      
-                else if (psLayer->maxscaledenom > 0)
-                  dfMaxScale = psLayer->maxscaledenom;
-                else if (psLayer->map && psLayer->map->web.maxscaledenom > 0)
-                  dfMaxScale = psLayer->map->web.maxscaledenom;
-                if (dfMaxScale > 0)
-                {
-                    if (nVersion > OWS_1_0_0)
-                      snprintf(szTmp, sizeof(szTmp), "<se:MaxScaleDenominator>%f</se:MaxScaleDenominator>\n",  
-                               dfMaxScale);
-                    else
-                      snprintf(szTmp, sizeof(szTmp), "<MaxScaleDenominator>%f</MaxScaleDenominator>\n",  
-                               dfMaxScale);
-
-                     pszFinalSLD = msStringConcatenate(pszFinalSLD, szTmp);
-                }
-                 
 
-                  
-/* -------------------------------------------------------------------- */
-/*      Line symbolizer.                                                */
-/*                                                                      */
-/*      Right now only generates a stroke element containing css        */
-/*      parameters.                                                     */
-/*      Lines using symbols TODO (specially for dash lines)             */
-/* -------------------------------------------------------------------- */
-                if (psLayer->type == MS_LAYER_LINE)
-                {
-                    for (j=0; j<psLayer->class[i]->numstyles; j++)
-                    {
-                        psStyle = psLayer->class[i]->styles[j];
-                        pszSLD = msSLDGenerateLineSLD(psStyle, psLayer, nVersion);
-                        if (pszSLD)
-                        {
-                            pszFinalSLD = msStringConcatenate(pszFinalSLD, pszSLD);
-                            free(pszSLD);
-                        }
-                    }
-                   
-                }
-                else if (psLayer->type == MS_LAYER_POLYGON)
-                {
-                    for (j=0; j<psLayer->class[i]->numstyles; j++)
-                    {
-                        psStyle = psLayer->class[i]->styles[j];
-                        pszSLD = msSLDGeneratePolygonSLD(psStyle, psLayer, nVersion);
-                        if (pszSLD)
-                        {
-                            pszFinalSLD = msStringConcatenate(pszFinalSLD, pszSLD);
-                            free(pszSLD);
-                        }
-                    } 
-                    
-                }
-                else if (psLayer->type == MS_LAYER_POINT)
-                {
-                    for (j=0; j<psLayer->class[i]->numstyles; j++)
-                    {
-                        psStyle = psLayer->class[i]->styles[j];
-                        pszSLD = msSLDGeneratePointSLD(psStyle, psLayer, nVersion);
-                        if (pszSLD)
-                        {
-                            pszFinalSLD = msStringConcatenate(pszFinalSLD, pszSLD);
-                            free(pszSLD);
-                        }
-                    } 
-                    
-                }
-                else if (psLayer->type == MS_LAYER_ANNOTATION)
-                {
-                    for (j=0; j<psLayer->class[i]->numstyles; j++)
-                    {
-                        psStyle = psLayer->class[i]->styles[j];
-                        pszSLD = msSLDGeneratePointSLD(psStyle, psLayer, nVersion);
-                        if (pszSLD)
-                        {
-                            pszFinalSLD = msStringConcatenate(pszFinalSLD, pszSLD);
-                            free(pszSLD);
-                        }
-                    } 
-                    
-                }
-                /* label if it exists */
-                pszSLD = msSLDGenerateTextSLD(psLayer->class[i], psLayer, nVersion);
-                if (pszSLD)
-                {
-                    pszFinalSLD = msStringConcatenate(pszFinalSLD, pszSLD);
-                    free(pszSLD);
-                }
-                if (nVersion > OWS_1_0_0)
-                  snprintf(szTmp, sizeof(szTmp), "%s\n",  "</se:Rule>");
-                else
-                  snprintf(szTmp, sizeof(szTmp), "%s\n",  "</Rule>");
 
-                pszFinalSLD = msStringConcatenate(pszFinalSLD, szTmp);
-                
-            
+        /* -------------------------------------------------------------------- */
+        /*      Line symbolizer.                                                */
+        /*                                                                      */
+        /*      Right now only generates a stroke element containing css        */
+        /*      parameters.                                                     */
+        /*      Lines using symbols TODO (specially for dash lines)             */
+        /* -------------------------------------------------------------------- */
+        if (psLayer->type == MS_LAYER_LINE) {
+          for (j=0; j<psLayer->class[i]->numstyles; j++) {
+            psStyle = psLayer->class[i]->styles[j];
+            pszSLD = msSLDGenerateLineSLD(psStyle, psLayer, nVersion);
+            if (pszSLD) {
+              pszFinalSLD = msStringConcatenate(pszFinalSLD, pszSLD);
+              free(pszSLD);
             }
+          }
+
+        } else if (psLayer->type == MS_LAYER_POLYGON) {
+          for (j=0; j<psLayer->class[i]->numstyles; j++) {
+            psStyle = psLayer->class[i]->styles[j];
+            pszSLD = msSLDGeneratePolygonSLD(psStyle, psLayer, nVersion);
+            if (pszSLD) {
+              pszFinalSLD = msStringConcatenate(pszFinalSLD, pszSLD);
+              free(pszSLD);
+            }
+          }
+
+        } else if (psLayer->type == MS_LAYER_POINT) {
+          for (j=0; j<psLayer->class[i]->numstyles; j++) {
+            psStyle = psLayer->class[i]->styles[j];
+            pszSLD = msSLDGeneratePointSLD(psStyle, psLayer, nVersion);
+            if (pszSLD) {
+              pszFinalSLD = msStringConcatenate(pszFinalSLD, pszSLD);
+              free(pszSLD);
+            }
+          }
+
+        } else if (psLayer->type == MS_LAYER_ANNOTATION) {
+          for (j=0; j<psLayer->class[i]->numstyles; j++) {
+            psStyle = psLayer->class[i]->styles[j];
+            pszSLD = msSLDGeneratePointSLD(psStyle, psLayer, nVersion);
+            if (pszSLD) {
+              pszFinalSLD = msStringConcatenate(pszFinalSLD, pszSLD);
+              free(pszSLD);
+            }
+          }
+
         }
-        if (pszWfsFilterEncoded)
-          msFree(pszWfsFilterEncoded);
-         if (nVersion > OWS_1_0_0)
-           snprintf(szTmp, sizeof(szTmp), "%s\n",  "</se:FeatureTypeStyle>");
-         else
-           snprintf(szTmp, sizeof(szTmp), "%s\n",  "</FeatureTypeStyle>");
+        /* label if it exists */
+        pszSLD = msSLDGenerateTextSLD(psLayer->class[i], psLayer, nVersion);
+        if (pszSLD) {
+          pszFinalSLD = msStringConcatenate(pszFinalSLD, pszSLD);
+          free(pszSLD);
+        }
+        if (nVersion > OWS_1_0_0)
+          snprintf(szTmp, sizeof(szTmp), "%s\n",  "</se:Rule>");
+        else
+          snprintf(szTmp, sizeof(szTmp), "%s\n",  "</Rule>");
 
         pszFinalSLD = msStringConcatenate(pszFinalSLD, szTmp);
 
-        snprintf(szTmp, sizeof(szTmp), "%s\n",  "</UserStyle>");
-        pszFinalSLD = msStringConcatenate(pszFinalSLD, szTmp);
 
-        snprintf(szTmp, sizeof(szTmp), "%s\n",  "</NamedLayer>");
-        pszFinalSLD = msStringConcatenate(pszFinalSLD, szTmp);
-        
+      }
     }
-    return pszFinalSLD;
+    if (pszWfsFilterEncoded)
+      msFree(pszWfsFilterEncoded);
+    if (nVersion > OWS_1_0_0)
+      snprintf(szTmp, sizeof(szTmp), "%s\n",  "</se:FeatureTypeStyle>");
+    else
+      snprintf(szTmp, sizeof(szTmp), "%s\n",  "</FeatureTypeStyle>");
+
+    pszFinalSLD = msStringConcatenate(pszFinalSLD, szTmp);
+
+    snprintf(szTmp, sizeof(szTmp), "%s\n",  "</UserStyle>");
+    pszFinalSLD = msStringConcatenate(pszFinalSLD, szTmp);
+
+    snprintf(szTmp, sizeof(szTmp), "%s\n",  "</NamedLayer>");
+    pszFinalSLD = msStringConcatenate(pszFinalSLD, szTmp);
+
+  }
+  return pszFinalSLD;
 
 
 #else
-/* ------------------------------------------------------------------
- * OGR Support not included...
- * ------------------------------------------------------------------ */
+  /* ------------------------------------------------------------------
+   * OGR Support not included...
+   * ------------------------------------------------------------------ */
 
-    msSetError(MS_MISCERR, "OGR support is not available.", 
-               "msSLDGenerateSLDLayer()");
-    return NULL;
+  msSetError(MS_MISCERR, "OGR support is not available.",
+             "msSLDGenerateSLDLayer()");
+  return NULL;
 
 #endif /* USE_OGR */
 
 
 #else
-    msSetError(MS_MISCERR, "OWS support is not available.", 
-               "msSLDGenerateSLDLayer()");
-    return NULL; 
+  msSetError(MS_MISCERR, "OWS support is not available.",
+             "msSLDGenerateSLDLayer()");
+  return NULL;
 #endif
 }
 
@@ -4532,501 +4259,436 @@ char *msSLDGenerateSLDLayer(layerObj *psLayer, int nVersion)
 
 char *msSLDGetComparisonValue(char *pszExpression)
 {
-    char *pszValue = NULL;
-    if (!pszExpression)
-      return NULL;
+  char *pszValue = NULL;
+  if (!pszExpression)
+    return NULL;
 
-    if (strstr(pszExpression, "<=") || strstr(pszExpression, " le "))
-      pszValue = msStrdup("PropertyIsLessThanOrEqualTo");
-    else if (strstr(pszExpression, "=~"))
-      pszValue = msStrdup("PropertyIsLike");
-    else if (strstr(pszExpression, "~*"))
-      pszValue = msStrdup("PropertyIsLike");
-    else if (strstr(pszExpression, ">=") || strstr(pszExpression, " ge "))
-      pszValue = msStrdup("PropertyIsGreaterThanOrEqualTo");
-    else if (strstr(pszExpression, "!=") || strstr(pszExpression, " ne "))
-      pszValue = msStrdup("PropertyIsNotEqualTo");
-    else if (strstr(pszExpression, "=") || strstr(pszExpression, " eq "))
-      pszValue = msStrdup("PropertyIsEqualTo");
-    else if (strstr(pszExpression, "<") || strstr(pszExpression, " lt "))
-      pszValue = msStrdup("PropertyIsLessThan");
-    else if (strstr(pszExpression, ">") || strstr(pszExpression, " gt "))
-      pszValue = msStrdup("PropertyIsGreaterThan");
-   
-
-    return pszValue;
+  if (strstr(pszExpression, "<=") || strstr(pszExpression, " le "))
+    pszValue = msStrdup("PropertyIsLessThanOrEqualTo");
+  else if (strstr(pszExpression, "=~"))
+    pszValue = msStrdup("PropertyIsLike");
+  else if (strstr(pszExpression, "~*"))
+    pszValue = msStrdup("PropertyIsLike");
+  else if (strstr(pszExpression, ">=") || strstr(pszExpression, " ge "))
+    pszValue = msStrdup("PropertyIsGreaterThanOrEqualTo");
+  else if (strstr(pszExpression, "!=") || strstr(pszExpression, " ne "))
+    pszValue = msStrdup("PropertyIsNotEqualTo");
+  else if (strstr(pszExpression, "=") || strstr(pszExpression, " eq "))
+    pszValue = msStrdup("PropertyIsEqualTo");
+  else if (strstr(pszExpression, "<") || strstr(pszExpression, " lt "))
+    pszValue = msStrdup("PropertyIsLessThan");
+  else if (strstr(pszExpression, ">") || strstr(pszExpression, " gt "))
+    pszValue = msStrdup("PropertyIsGreaterThan");
+
+
+  return pszValue;
 }
 
 char *msSLDGetLogicalOperator(char *pszExpression)
 {
 
-    if (!pszExpression)
-      return NULL;
+  if (!pszExpression)
+    return NULL;
 
-    /* TODO for NOT */
+  /* TODO for NOT */
 
-    if(strstr(pszExpression, " AND ") || strstr(pszExpression, "AND("))
-      return msStrdup("And");
-    
-    if(strstr(pszExpression, " OR ") || strstr(pszExpression, "OR("))
-      return msStrdup("Or");
+  if(strstr(pszExpression, " AND ") || strstr(pszExpression, "AND("))
+    return msStrdup("And");
 
-     if(strstr(pszExpression, "NOT ") || strstr(pszExpression, "NOT("))
-      return msStrdup("Not");
+  if(strstr(pszExpression, " OR ") || strstr(pszExpression, "OR("))
+    return msStrdup("Or");
 
-    return NULL;
+  if(strstr(pszExpression, "NOT ") || strstr(pszExpression, "NOT("))
+    return msStrdup("Not");
+
+  return NULL;
 }
 
 char *msSLDGetRightExpressionOfOperator(char *pszExpression)
 {
-    char *pszAnd = NULL, *pszOr = NULL, *pszNot=NULL;
-
-    pszAnd = strstr(pszExpression, " AND "); 
-    if (!pszAnd)
-      pszAnd = strstr(pszExpression, " and ");
-  
-    if (pszAnd)
-      return msStrdup(pszAnd+4);
-    else
-    {
-        pszOr = strstr(pszExpression, " OR "); 
-        if (!pszOr)
-          pszOr = strstr(pszExpression, " or ");
-
-        if (pszOr)
-          return msStrdup(pszOr+3);
-        else
-        {
-            pszNot = strstr(pszExpression, "NOT ");
-            if (!pszNot)
-              pszNot = strstr(pszExpression, "not ");
-            if (!pszNot)
-              pszNot = strstr(pszExpression, "NOT(");
-            if (!pszNot)
-              pszNot = strstr(pszExpression, "not(");
-
-            if (pszNot)
-              return msStrdup(pszNot+4);
-        }
+  char *pszAnd = NULL, *pszOr = NULL, *pszNot=NULL;
+
+  pszAnd = strstr(pszExpression, " AND ");
+  if (!pszAnd)
+    pszAnd = strstr(pszExpression, " and ");
+
+  if (pszAnd)
+    return msStrdup(pszAnd+4);
+  else {
+    pszOr = strstr(pszExpression, " OR ");
+    if (!pszOr)
+      pszOr = strstr(pszExpression, " or ");
+
+    if (pszOr)
+      return msStrdup(pszOr+3);
+    else {
+      pszNot = strstr(pszExpression, "NOT ");
+      if (!pszNot)
+        pszNot = strstr(pszExpression, "not ");
+      if (!pszNot)
+        pszNot = strstr(pszExpression, "NOT(");
+      if (!pszNot)
+        pszNot = strstr(pszExpression, "not(");
+
+      if (pszNot)
+        return msStrdup(pszNot+4);
     }
-    return NULL;
-        
+  }
+  return NULL;
+
 }
 
 char *msSLDGetLeftExpressionOfOperator(char *pszExpression)
 {
-    char *pszReturn = NULL;
-    int nLength = 0, i =0, iReturn=0;
+  char *pszReturn = NULL;
+  int nLength = 0, i =0, iReturn=0;
 
-    if (!pszExpression || (nLength = strlen(pszExpression)) <=0)
-      return NULL;
+  if (!pszExpression || (nLength = strlen(pszExpression)) <=0)
+    return NULL;
 
-    pszReturn = (char *)malloc(sizeof(char)*(nLength+1));
-    pszReturn[0] = '\0';
-    if (strstr(pszExpression, " AND ") || strstr(pszExpression, " and "))
-    {
-        for (i=0; i<nLength-5; i++)
-        {
-            if (pszExpression[i] == ' ' && 
-                (pszExpression[i+1] == 'A' || pszExpression[i] == 'a') &&
-                (pszExpression[i+2] == 'N' || pszExpression[i] == 'n') &&
-                (pszExpression[i+3] == 'D' || pszExpression[i] == 'd') &&
-                (pszExpression[i+4] == ' '))
-              break;
-            else
-            {
-                pszReturn[iReturn++] = pszExpression[i];
-            }
-            pszReturn[iReturn] = '\0';
-        }
+  pszReturn = (char *)malloc(sizeof(char)*(nLength+1));
+  pszReturn[0] = '\0';
+  if (strstr(pszExpression, " AND ") || strstr(pszExpression, " and ")) {
+    for (i=0; i<nLength-5; i++) {
+      if (pszExpression[i] == ' ' &&
+          (pszExpression[i+1] == 'A' || pszExpression[i] == 'a') &&
+          (pszExpression[i+2] == 'N' || pszExpression[i] == 'n') &&
+          (pszExpression[i+3] == 'D' || pszExpression[i] == 'd') &&
+          (pszExpression[i+4] == ' '))
+        break;
+      else {
+        pszReturn[iReturn++] = pszExpression[i];
+      }
+      pszReturn[iReturn] = '\0';
     }
-    else if (strstr(pszExpression, "AND(") || strstr(pszExpression, "and("))
-    {
-        for (i=0; i<nLength-4; i++)
-        {
-            if ((pszExpression[i] == 'A' || pszExpression[i] == 'a') &&
-                (pszExpression[i+1] == 'N' || pszExpression[i] == 'n') &&
-                (pszExpression[i+2] == 'D' || pszExpression[i] == 'd') &&
-                (pszExpression[i+3] == '('))
-              break;
-            else
-            {
-                pszReturn[iReturn++] = pszExpression[i];
-            }
-            pszReturn[iReturn] = '\0';
-        }
+  } else if (strstr(pszExpression, "AND(") || strstr(pszExpression, "and(")) {
+    for (i=0; i<nLength-4; i++) {
+      if ((pszExpression[i] == 'A' || pszExpression[i] == 'a') &&
+          (pszExpression[i+1] == 'N' || pszExpression[i] == 'n') &&
+          (pszExpression[i+2] == 'D' || pszExpression[i] == 'd') &&
+          (pszExpression[i+3] == '('))
+        break;
+      else {
+        pszReturn[iReturn++] = pszExpression[i];
+      }
+      pszReturn[iReturn] = '\0';
     }
-    else if (strstr(pszExpression, " OR ") || strstr(pszExpression, " or "))
-    {
-        for (i=0; i<nLength-4; i++)
-        {
-            if (pszExpression[i] == ' ' && 
-                (pszExpression[i+1] == 'O' || pszExpression[i] == 'o') &&
-                (pszExpression[i+2] == 'R' || pszExpression[i] == 'r') &&
-                pszExpression[i+3] == ' ')
-              break;
-            else
-            {
-                pszReturn[iReturn++] = pszExpression[i];
-            }
-            pszReturn[iReturn] = '\0';
-        }
+  } else if (strstr(pszExpression, " OR ") || strstr(pszExpression, " or ")) {
+    for (i=0; i<nLength-4; i++) {
+      if (pszExpression[i] == ' ' &&
+          (pszExpression[i+1] == 'O' || pszExpression[i] == 'o') &&
+          (pszExpression[i+2] == 'R' || pszExpression[i] == 'r') &&
+          pszExpression[i+3] == ' ')
+        break;
+      else {
+        pszReturn[iReturn++] = pszExpression[i];
+      }
+      pszReturn[iReturn] = '\0';
     }
-    else if (strstr(pszExpression, "OR(") || strstr(pszExpression, " or("))
-    {
-        for (i=0; i<nLength-3; i++)
-        {
-            if ((pszExpression[i] == 'O' || pszExpression[i] == 'o') &&
-                (pszExpression[i+1] == 'R' || pszExpression[i] == 'r') &&
-                pszExpression[i+2] == '(')
-              break;
-            else
-            {
-                pszReturn[iReturn++] = pszExpression[i];
-            }
-            pszReturn[iReturn] = '\0';
-        }
+  } else if (strstr(pszExpression, "OR(") || strstr(pszExpression, " or(")) {
+    for (i=0; i<nLength-3; i++) {
+      if ((pszExpression[i] == 'O' || pszExpression[i] == 'o') &&
+          (pszExpression[i+1] == 'R' || pszExpression[i] == 'r') &&
+          pszExpression[i+2] == '(')
+        break;
+      else {
+        pszReturn[iReturn++] = pszExpression[i];
+      }
+      pszReturn[iReturn] = '\0';
     }
-    else
-      return NULL;
+  } else
+    return NULL;
 
-    return pszReturn;
+  return pszReturn;
 }
 
 
 int msSLDNumberOfLogicalOperators(char *pszExpression)
 {
-    char *pszAnd = NULL;
-    char *pszOr = NULL;
-    char *pszNot = NULL;
-    char *pszSecondAnd=NULL, *pszSecondOr=NULL;
-    if (!pszExpression)
-      return 0;
-
-/* -------------------------------------------------------------------- */
-/*      tests here are minimal to be able to parse simple expression    */
-/*      like A AND B, A OR B, NOT A.                                    */
-/* -------------------------------------------------------------------- */
-    pszAnd = strcasestr(pszExpression, " AND ");
-    pszOr = strcasestr(pszExpression, " OR ");
-    pszNot = strcasestr(pszExpression, "NOT ");
-
-    if (!pszAnd && !pszOr)
-    {
-        pszAnd = strcasestr(pszExpression, "AND(");
-        pszOr = strcasestr(pszExpression, "OR(");
-    }
-
-    if (!pszAnd && !pszOr && !pszNot)
-      return 0;
-
-    /* doen not matter how many exactly if there are 2 or more */
-    if ((pszAnd && pszOr) || (pszAnd && pszNot) || (pszOr && pszNot)) 
-      return 2;
-
-    if (pszAnd)
-    {
-        pszSecondAnd = strcasestr(pszAnd+3, " AND ");
-        pszSecondOr = strcasestr(pszAnd+3, " OR ");
-    }
-    else if (pszOr)
-    {
-        pszSecondAnd = strcasestr(pszOr+2, " AND ");
-        pszSecondOr = strcasestr(pszOr+2, " OR ");
-    }
-
-    if (!pszSecondAnd && !pszSecondOr)
-      return 1;
-    else
-      return 2;
+  char *pszAnd = NULL;
+  char *pszOr = NULL;
+  char *pszNot = NULL;
+  char *pszSecondAnd=NULL, *pszSecondOr=NULL;
+  if (!pszExpression)
+    return 0;
+
+  /* -------------------------------------------------------------------- */
+  /*      tests here are minimal to be able to parse simple expression    */
+  /*      like A AND B, A OR B, NOT A.                                    */
+  /* -------------------------------------------------------------------- */
+  pszAnd = strcasestr(pszExpression, " AND ");
+  pszOr = strcasestr(pszExpression, " OR ");
+  pszNot = strcasestr(pszExpression, "NOT ");
+
+  if (!pszAnd && !pszOr) {
+    pszAnd = strcasestr(pszExpression, "AND(");
+    pszOr = strcasestr(pszExpression, "OR(");
+  }
+
+  if (!pszAnd && !pszOr && !pszNot)
+    return 0;
+
+  /* doen not matter how many exactly if there are 2 or more */
+  if ((pszAnd && pszOr) || (pszAnd && pszNot) || (pszOr && pszNot))
+    return 2;
+
+  if (pszAnd) {
+    pszSecondAnd = strcasestr(pszAnd+3, " AND ");
+    pszSecondOr = strcasestr(pszAnd+3, " OR ");
+  } else if (pszOr) {
+    pszSecondAnd = strcasestr(pszOr+2, " AND ");
+    pszSecondOr = strcasestr(pszOr+2, " OR ");
+  }
+
+  if (!pszSecondAnd && !pszSecondOr)
+    return 1;
+  else
+    return 2;
 }
 
 
-char *msSLDGetAttributeNameOrValue(char *pszExpression, 
+char *msSLDGetAttributeNameOrValue(char *pszExpression,
                                    char *pszComparionValue,
                                    int bReturnName)
 {
-    char **aszValues = NULL;
-    char *pszAttributeName = NULL;
-    char *pszAttributeValue = NULL;
-    char cCompare = '=';
-    char szCompare[3] = {0};
-    char szCompare2[3] = {0};
-    int bOneCharCompare = -1, nTokens = 0, nLength =0;
-    int iValue=0, i=0, iValueIndex =0;
-    int bStartCopy=0, iAtt=0;
-    char *pszFinalAttributeName=NULL, *pszFinalAttributeValue=NULL;
-    int bSingleQuote = 0, bDoubleQuote = 0;
-
-    if (!pszExpression || !pszComparionValue || strlen(pszExpression) <=0)
-      return NULL;
-
-    szCompare[0] = '\0';
-    szCompare2[0] = '\0';
-    
-
-    if (strcasecmp(pszComparionValue, "PropertyIsEqualTo") == 0)
-    {
-        cCompare = '=';
-        szCompare[0] = 'e';
-        szCompare[1] = 'q';
-        szCompare[2] = '\0';
-
-        bOneCharCompare =1;
-    }
-    if (strcasecmp(pszComparionValue, "PropertyIsNotEqualTo") == 0)
-    {
-        szCompare[0] = 'n';
-        szCompare[1] = 'e';
-        szCompare[2] = '\0';
-
-        szCompare2[0] = '!';
-        szCompare2[1] = '=';
-        szCompare2[2] = '\0';
+  char **aszValues = NULL;
+  char *pszAttributeName = NULL;
+  char *pszAttributeValue = NULL;
+  char cCompare = '=';
+  char szCompare[3] = {0};
+  char szCompare2[3] = {0};
+  int bOneCharCompare = -1, nTokens = 0, nLength =0;
+  int iValue=0, i=0, iValueIndex =0;
+  int bStartCopy=0, iAtt=0;
+  char *pszFinalAttributeName=NULL, *pszFinalAttributeValue=NULL;
+  int bSingleQuote = 0, bDoubleQuote = 0;
+
+  if (!pszExpression || !pszComparionValue || strlen(pszExpression) <=0)
+    return NULL;
 
-        bOneCharCompare =0;
-    }
-    else if (strcasecmp(pszComparionValue, "PropertyIsLike") == 0)
-    {
-        szCompare[0] = '=';
-        szCompare[1] = '~';
-        szCompare[2] = '\0';
+  szCompare[0] = '\0';
+  szCompare2[0] = '\0';
+
+
+  if (strcasecmp(pszComparionValue, "PropertyIsEqualTo") == 0) {
+    cCompare = '=';
+    szCompare[0] = 'e';
+    szCompare[1] = 'q';
+    szCompare[2] = '\0';
+
+    bOneCharCompare =1;
+  }
+  if (strcasecmp(pszComparionValue, "PropertyIsNotEqualTo") == 0) {
+    szCompare[0] = 'n';
+    szCompare[1] = 'e';
+    szCompare[2] = '\0';
+
+    szCompare2[0] = '!';
+    szCompare2[1] = '=';
+    szCompare2[2] = '\0';
+
+    bOneCharCompare =0;
+  } else if (strcasecmp(pszComparionValue, "PropertyIsLike") == 0) {
+    szCompare[0] = '=';
+    szCompare[1] = '~';
+    szCompare[2] = '\0';
+
+    szCompare2[0] = '~';
+    szCompare2[1] = '*';
+    szCompare2[2] = '\0';
+
+    bOneCharCompare =0;
+  } else if (strcasecmp(pszComparionValue, "PropertyIsLessThan") == 0) {
+    cCompare = '<';
+    szCompare[0] = 'l';
+    szCompare[1] = 't';
+    szCompare[2] = '\0';
+    bOneCharCompare =1;
+  } else if (strcasecmp(pszComparionValue, "PropertyIsLessThanOrEqualTo") == 0) {
+    szCompare[0] = 'l';
+    szCompare[1] = 'e';
+    szCompare[2] = '\0';
+
+    szCompare2[0] = '<';
+    szCompare2[1] = '=';
+    szCompare2[2] = '\0';
+
+    bOneCharCompare =0;
+  } else if (strcasecmp(pszComparionValue, "PropertyIsGreaterThan") == 0) {
+    cCompare = '>';
+    szCompare[0] = 'g';
+    szCompare[1] = 't';
+    szCompare[2] = '\0';
+    bOneCharCompare =1;
+  } else if (strcasecmp(pszComparionValue, "PropertyIsGreaterThanOrEqualTo") == 0) {
+    szCompare[0] = 'g';
+    szCompare[1] = 'e';
+    szCompare[2] = '\0';
+
+    szCompare2[0] = '>';
+    szCompare2[1] = '=';
+    szCompare2[2] = '\0';
+
+    bOneCharCompare =0;
+  }
+
+  if (bOneCharCompare == 1) {
+    aszValues= msStringSplit (pszExpression, cCompare, &nTokens);
+    if (nTokens > 1) {
+      pszAttributeName = msStrdup(aszValues[0]);
+      pszAttributeValue =  msStrdup(aszValues[1]);
+      msFreeCharArray(aszValues, nTokens);
+    } else {
+      nLength = strlen(pszExpression);
+      pszAttributeName = (char *)malloc(sizeof(char)*(nLength+1));
+      iValue = 0;
+      for (i=0; i<nLength-2; i++) {
+        if (pszExpression[i] != szCompare[0] &&
+            pszExpression[i] != toupper(szCompare[0])) {
+          pszAttributeName[iValue++] = pszExpression[i];
+        } else {
+          if ((pszExpression[i+1] == szCompare[1] ||
+               pszExpression[i+1] == toupper(szCompare[1])) &&
+              (pszExpression[i+2] == ' ')) {
+            iValueIndex = i+3;
+            pszAttributeValue = msStrdup(pszExpression+iValueIndex);
+            break;
+          } else
+            pszAttributeName[iValue++] = pszExpression[i];
+        }
+        pszAttributeName[iValue] = '\0';
+      }
 
-        szCompare2[0] = '~';
-        szCompare2[1] = '*';
-        szCompare2[2] = '\0';
 
-        bOneCharCompare =0;
     }
-    else if (strcasecmp(pszComparionValue, "PropertyIsLessThan") == 0)
-    {
-        cCompare = '<';
-        szCompare[0] = 'l';
-        szCompare[1] = 't';
-        szCompare[2] = '\0';
-        bOneCharCompare =1;
+  } else if (bOneCharCompare == 0) {
+    nLength = strlen(pszExpression);
+    pszAttributeName = (char *)malloc(sizeof(char)*(nLength+1));
+    iValue = 0;
+    for (i=0; i<nLength-2; i++) {
+      if ((pszExpression[i] != szCompare[0] ||
+           pszExpression[i] != toupper(szCompare[0])) &&
+          (pszExpression[i] != szCompare2[0] ||
+           pszExpression[i] != toupper(szCompare2[0])))
+
+      {
+        pszAttributeName[iValue++] = pszExpression[i];
+      } else {
+        if (((pszExpression[i+1] == szCompare[1] ||
+              pszExpression[i+1] == toupper(szCompare[1])) ||
+             (pszExpression[i+1] == szCompare2[1] ||
+              pszExpression[i+1] == toupper(szCompare2[1]))) &&
+            (pszExpression[i+2] == ' ')) {
+          iValueIndex = i+3;
+          pszAttributeValue = msStrdup(pszExpression+iValueIndex);
+          break;
+        } else
+          pszAttributeName[iValue++] = pszExpression[i];
+      }
+      pszAttributeName[iValue] = '\0';
     }
-    else if (strcasecmp(pszComparionValue, "PropertyIsLessThanOrEqualTo") == 0)
-    {
-        szCompare[0] = 'l';
-        szCompare[1] = 'e';
-        szCompare[2] = '\0';
-
-        szCompare2[0] = '<';
-        szCompare2[1] = '=';
-        szCompare2[2] = '\0';
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Return the name of the attribute : It is supposed to be         */
+  /*      inside []                                                       */
+  /* -------------------------------------------------------------------- */
+  if (bReturnName) {
+    if (!pszAttributeName)
+      return NULL;
 
-        bOneCharCompare =0;
-    }
-    else if (strcasecmp(pszComparionValue, "PropertyIsGreaterThan") == 0)
-    {
-        cCompare = '>';
-        szCompare[0] = 'g';
-        szCompare[1] = 't';
-        szCompare[2] = '\0';
-        bOneCharCompare =1;
+    nLength = strlen(pszAttributeName);
+    pszFinalAttributeName = (char *)malloc(sizeof(char)*(nLength+1));
+    bStartCopy= 0;
+    iAtt = 0;
+    for (i=0; i<nLength; i++) {
+      if (pszAttributeName[i] == ' ' && bStartCopy == 0)
+        continue;
+
+      if (pszAttributeName[i] == '[') {
+        bStartCopy = 1;
+        continue;
+      }
+      if (pszAttributeName[i] == ']')
+        break;
+      if (bStartCopy) {
+        pszFinalAttributeName[iAtt++] = pszAttributeName[i];
+      }
+      pszFinalAttributeName[iAtt] = '\0';
     }
-    else if (strcasecmp(pszComparionValue, "PropertyIsGreaterThanOrEqualTo") == 0)
-    {
-        szCompare[0] = 'g';
-        szCompare[1] = 'e';
-        szCompare[2] = '\0';
 
-        szCompare2[0] = '>';
-        szCompare2[1] = '=';
-        szCompare2[2] = '\0';
+    return pszFinalAttributeName;
+  } else {
 
-        bOneCharCompare =0;
+    if (!pszAttributeValue)
+      return NULL;
+    nLength = strlen(pszAttributeValue);
+    pszFinalAttributeValue = (char *)malloc(sizeof(char)*(nLength+1));
+    bStartCopy= 0;
+    iAtt = 0;
+    for (i=0; i<nLength; i++) {
+      if (pszAttributeValue[i] == ' ' && bStartCopy == 0)
+        continue;
+
+      if (pszAttributeValue[i] == '\'' && bStartCopy == 0) {
+        bSingleQuote = 1;
+        bStartCopy = 1;
+        continue;
+      } else if (pszAttributeValue[i] == '"' && bStartCopy == 0) {
+        bDoubleQuote = 1;
+        bStartCopy = 1;
+        continue;
+      } else
+        bStartCopy =1;
+
+      if (bStartCopy) {
+        if (pszAttributeValue[i] == '\'' && bSingleQuote)
+          break;
+        else if (pszAttributeValue[i] == '"' && bDoubleQuote)
+          break;
+        else if (pszAttributeValue[i] == ')')
+          break;
+        pszFinalAttributeValue[iAtt++] = pszAttributeValue[i];
+      }
+      pszFinalAttributeValue[iAtt] = '\0';
     }
 
-    if (bOneCharCompare == 1)
-    {
-        aszValues= msStringSplit (pszExpression, cCompare, &nTokens);
-        if (nTokens > 1)
-        {
-            pszAttributeName = msStrdup(aszValues[0]);
-            pszAttributeValue =  msStrdup(aszValues[1]);
-            msFreeCharArray(aszValues, nTokens);
-        }
+    /*trim  for regular expressions*/
+    if (pszFinalAttributeValue && strlen(pszFinalAttributeValue) > 2 &&
+        strcasecmp(pszComparionValue, "PropertyIsLike") == 0) {
+      int len = strlen(pszFinalAttributeValue);
+      msStringTrimBlanks(pszFinalAttributeValue);
+      if (pszFinalAttributeValue[0] == '/' &&
+          (pszFinalAttributeValue[len-1] == '/' ||
+           (pszFinalAttributeValue[len-1] == 'i' &&
+            pszFinalAttributeValue[len-2] == '/'))) {
+        if (pszFinalAttributeValue[len-1] == '/')
+          pszFinalAttributeValue[len-1] = '\0';
         else
-        {
-            nLength = strlen(pszExpression);
-            pszAttributeName = (char *)malloc(sizeof(char)*(nLength+1));
-            iValue = 0;
-            for (i=0; i<nLength-2; i++)
-            {
-                if (pszExpression[i] != szCompare[0] && 
-                    pszExpression[i] != toupper(szCompare[0]))
-                {
-                    pszAttributeName[iValue++] = pszExpression[i];
-                }
-                else
-                {
-                    if ((pszExpression[i+1] == szCompare[1] || 
-                         pszExpression[i+1] == toupper(szCompare[1])) &&
-                        (pszExpression[i+2] == ' '))
-                    {
-                        iValueIndex = i+3;
-                        pszAttributeValue = msStrdup(pszExpression+iValueIndex);
-                        break;
-                    }
-                    else
-                      pszAttributeName[iValue++] = pszExpression[i];
-                }
-                pszAttributeName[iValue] = '\0';
-            }
-
-            
-        }
-    }
-    else if (bOneCharCompare == 0)
-    {
-        nLength = strlen(pszExpression);
-        pszAttributeName = (char *)malloc(sizeof(char)*(nLength+1));
-        iValue = 0;
-        for (i=0; i<nLength-2; i++)
-        {
-            if ((pszExpression[i] != szCompare[0] || 
-                 pszExpression[i] != toupper(szCompare[0])) &&
-                (pszExpression[i] != szCompare2[0] || 
-                 pszExpression[i] != toupper(szCompare2[0])))
-                
-            {
-                pszAttributeName[iValue++] = pszExpression[i];
-            }
-            else
-            {
-                if (((pszExpression[i+1] == szCompare[1] || 
-                     pszExpression[i+1] == toupper(szCompare[1])) ||
-                    (pszExpression[i+1] == szCompare2[1] || 
-                     pszExpression[i+1] == toupper(szCompare2[1]))) &&
-                    (pszExpression[i+2] == ' '))
-                {
-                    iValueIndex = i+3;
-                    pszAttributeValue = msStrdup(pszExpression+iValueIndex);
-                    break;
-                }
-                else
-                  pszAttributeName[iValue++] = pszExpression[i];
-            }
-            pszAttributeName[iValue] = '\0';
-        }
-    }
+          pszFinalAttributeValue[len-2] = '\0';
 
-/* -------------------------------------------------------------------- */
-/*      Return the name of the attribute : It is supposed to be         */
-/*      inside []                                                       */
-/* -------------------------------------------------------------------- */
-    if (bReturnName)
-    {
-        if (!pszAttributeName)
-          return NULL;
-
-        nLength = strlen(pszAttributeName);
-        pszFinalAttributeName = (char *)malloc(sizeof(char)*(nLength+1));
-        bStartCopy= 0;
-        iAtt = 0;
-        for (i=0; i<nLength; i++)
-        {
-            if (pszAttributeName[i] == ' ' && bStartCopy == 0)
-              continue;
+        memmove(pszFinalAttributeValue, pszFinalAttributeValue +
+                ((pszFinalAttributeValue[1] == '^') ? 2 : 1), len-1);
 
-            if (pszAttributeName[i] == '[')
-            {
-                bStartCopy = 1;
-                continue;
-            }
-            if (pszAttributeName[i] == ']')
-              break;
-            if (bStartCopy)
-            {
-                pszFinalAttributeName[iAtt++] = pszAttributeName[i];
-            }
-            pszFinalAttributeName[iAtt] = '\0';
-        }
-
-        return pszFinalAttributeName;
-    }
-    else
-    {
-        
-        if (!pszAttributeValue)
-          return NULL;
-        nLength = strlen(pszAttributeValue);
-        pszFinalAttributeValue = (char *)malloc(sizeof(char)*(nLength+1));
-        bStartCopy= 0;
-        iAtt = 0;
-        for (i=0; i<nLength; i++)
-        {
-            if (pszAttributeValue[i] == ' ' && bStartCopy == 0)
-              continue;
-
-            if (pszAttributeValue[i] == '\'' && bStartCopy == 0)
-            {
-                bSingleQuote = 1;
-                bStartCopy = 1;
-                continue;
-            }
-            else if (pszAttributeValue[i] == '"' && bStartCopy == 0)
-            {
-                bDoubleQuote = 1;
-                bStartCopy = 1;
-                continue;
-            }
-            else
-              bStartCopy =1;
-
-            if (bStartCopy)
-            {
-                if (pszAttributeValue[i] == '\'' && bSingleQuote)
-                  break;
-                else if (pszAttributeValue[i] == '"' && bDoubleQuote)
-                  break;
-                else if (pszAttributeValue[i] == ')')
-                  break;
-                pszFinalAttributeValue[iAtt++] = pszAttributeValue[i];
-            }
-            pszFinalAttributeValue[iAtt] = '\0';
-        }
-         
-        /*trim  for regular expressions*/
-        if (pszFinalAttributeValue && strlen(pszFinalAttributeValue) > 2 && 
-            strcasecmp(pszComparionValue, "PropertyIsLike") == 0)
-        {
-            int len = strlen(pszFinalAttributeValue);
-            msStringTrimBlanks(pszFinalAttributeValue);
-            if (pszFinalAttributeValue[0] == '/' &&  
-                (pszFinalAttributeValue[len-1] == '/' ||
-                 (pszFinalAttributeValue[len-1] == 'i' && 
-                  pszFinalAttributeValue[len-2] == '/')))
-            {
-                if (pszFinalAttributeValue[len-1] == '/')
-                  pszFinalAttributeValue[len-1] = '\0';
-                else
-                  pszFinalAttributeValue[len-2] = '\0';
-
-                memmove(pszFinalAttributeValue, pszFinalAttributeValue +
-                        ((pszFinalAttributeValue[1] == '^') ? 2 : 1), len-1);
-
-                /*replace wild card string .* with * */
-                pszFinalAttributeValue = msReplaceSubstring(pszFinalAttributeValue, ".*", "*");
-            }
-        }
-        return pszFinalAttributeValue;
+        /*replace wild card string .* with * */
+        pszFinalAttributeValue = msReplaceSubstring(pszFinalAttributeValue, ".*", "*");
+      }
     }
+    return pszFinalAttributeValue;
+  }
 }
 
 
-char *msSLDGetAttributeName(char *pszExpression, 
-                         char *pszComparionValue)
+char *msSLDGetAttributeName(char *pszExpression,
+                            char *pszComparionValue)
 {
-    return msSLDGetAttributeNameOrValue(pszExpression, pszComparionValue, 1);
+  return msSLDGetAttributeNameOrValue(pszExpression, pszComparionValue, 1);
 }
 
-char *msSLDGetAttributeValue(char *pszExpression, 
+char *msSLDGetAttributeValue(char *pszExpression,
                              char *pszComparionValue)
 {
-    return msSLDGetAttributeNameOrValue(pszExpression, pszComparionValue, 0);
+  return msSLDGetAttributeNameOrValue(pszExpression, pszComparionValue, 0);
 }
 
 
@@ -5042,399 +4704,224 @@ char *msSLDGetAttributeValue(char *pszExpression,
 /*        A OR B                                                        */
 /*        NOT A                                                         */
 /************************************************************************/
-FilterEncodingNode *BuildExpressionTree(char *pszExpression, 
+FilterEncodingNode *BuildExpressionTree(char *pszExpression,
                                         FilterEncodingNode *psNode)
 {
-    char *apszExpression[20]; 
-    int nLength = 0;
-    /* int bInsideExpression = 0; */
-    int i =0, nOperators=0;
-    char *pszFinalExpression = NULL;
-    int iFinal = 0, iIndiceExp=0, nOpeningBrackets=0;/* nIndice=0; */
-    /* char szTmp[6]; */
-    int iExpression = 0;
-    /* char *pszSimplifiedExpression = NULL; */
-    char *pszComparionValue=NULL, *pszAttibuteName=NULL;
-    char *pszAttibuteValue=NULL;
-    char *pszLeftExpression=NULL, *pszRightExpression=NULL, *pszOperator=NULL;
-
-    if (!pszExpression || (nLength = strlen(pszExpression)) <=0)
-      return NULL;
-
-    for (i=0; i<20; i++)
-      apszExpression[i] = (char *)malloc(sizeof(char)*(nLength+1));
-
-    pszFinalExpression = (char *)malloc(sizeof(char)*(nLength+1));
-    pszFinalExpression[0] = '\0';
-
-    iExpression = -1; /* first incremnt will put it to 0; */
-    iFinal = 0;
-    iIndiceExp = 0;
-    nOpeningBrackets = 0;
+  int nLength = 0;
+  int nOperators=0;
+  char *pszFinalExpression = NULL;
+  char *pszComparionValue=NULL, *pszAttibuteName=NULL;
+  char *pszAttibuteValue=NULL;
+  char *pszLeftExpression=NULL, *pszRightExpression=NULL, *pszOperator=NULL;
+
+  if (!pszExpression || (nLength = strlen(pszExpression)) <=0)
+    return NULL;
 
-/* -------------------------------------------------------------------- */
-/*      First we check how many logical operators are there :           */
-/*       - if none : It means It is a comparision operator (like =,      */
-/*      >, >= .... We get the comparison value as well as the           */
-/*      attribute and the attribut's value and assign it to the node    */
-/*      passed in argument.                                             */
-/*       - if there is one operator, we assign the operator to the      */
-/*      node and adds the expressions into the left and right nodes.    */
-/* -------------------------------------------------------------------- */
-    nOperators = msSLDNumberOfLogicalOperators(pszExpression);
-    if (nOperators == 0)
-    {
-        if (!psNode)
-          psNode = FLTCreateFilterEncodingNode();
+  pszFinalExpression = (char *)malloc(sizeof(char)*(nLength+1));
+  pszFinalExpression[0] = '\0';
+
+  /* -------------------------------------------------------------------- */
+  /*      First we check how many logical operators are there :           */
+  /*       - if none : It means It is a comparision operator (like =,      */
+  /*      >, >= .... We get the comparison value as well as the           */
+  /*      attribute and the attribut's value and assign it to the node    */
+  /*      passed in argument.                                             */
+  /*       - if there is one operator, we assign the operator to the      */
+  /*      node and adds the expressions into the left and right nodes.    */
+  /* -------------------------------------------------------------------- */
+  nOperators = msSLDNumberOfLogicalOperators(pszExpression);
+  if (nOperators == 0) {
+    if (!psNode)
+      psNode = FLTCreateFilterEncodingNode();
+
+    pszComparionValue = msSLDGetComparisonValue(pszExpression);
+    pszAttibuteName = msSLDGetAttributeName(pszExpression, pszComparionValue);
+    pszAttibuteValue = msSLDGetAttributeValue(pszExpression, pszComparionValue);
+    if (pszComparionValue && pszAttibuteName && pszAttibuteValue) {
+      psNode->eType = FILTER_NODE_TYPE_COMPARISON;
+      psNode->pszValue = msStrdup(pszComparionValue);
+
+      psNode->psLeftNode = FLTCreateFilterEncodingNode();
+      psNode->psLeftNode->eType = FILTER_NODE_TYPE_PROPERTYNAME;
+      psNode->psLeftNode->pszValue = msStrdup(pszAttibuteName);
+
+      psNode->psRightNode = FLTCreateFilterEncodingNode();
+      psNode->psRightNode->eType = FILTER_NODE_TYPE_LITERAL;
+      psNode->psRightNode->pszValue = msStrdup(pszAttibuteValue);
+
+      if (strcasecmp(pszComparionValue, "PropertyIsLike") == 0) {
+        psNode->pOther = (FEPropertyIsLike *)malloc(sizeof(FEPropertyIsLike));
+        ((FEPropertyIsLike *)psNode->pOther)->bCaseInsensitive = 0;
+        ((FEPropertyIsLike *)psNode->pOther)->pszWildCard = msStrdup("*");
+        ((FEPropertyIsLike *)psNode->pOther)->pszSingleChar = msStrdup("#");
+        ((FEPropertyIsLike *)psNode->pOther)->pszEscapeChar = msStrdup("!");
+      }
+      free(pszComparionValue);
+      free(pszAttibuteName);
+      free(pszAttibuteValue);
+    }
+    return psNode;
+
+  } else if (nOperators == 1) {
+    pszOperator = msSLDGetLogicalOperator(pszExpression);
+    if (pszOperator) {
+      if (!psNode)
+        psNode = FLTCreateFilterEncodingNode();
+
+      psNode->eType = FILTER_NODE_TYPE_LOGICAL;
+      psNode->pszValue = msStrdup(pszOperator);
+      free(pszOperator);
+
+      pszLeftExpression = msSLDGetLeftExpressionOfOperator(pszExpression);
+      pszRightExpression = msSLDGetRightExpressionOfOperator(pszExpression);
+
+      if (pszLeftExpression || pszRightExpression) {
+        if (pszLeftExpression) {
+          pszComparionValue = msSLDGetComparisonValue(pszLeftExpression);
+          pszAttibuteName = msSLDGetAttributeName(pszLeftExpression,
+                                                  pszComparionValue);
+          pszAttibuteValue = msSLDGetAttributeValue(pszLeftExpression,
+                             pszComparionValue);
+
+          if (pszComparionValue && pszAttibuteName && pszAttibuteValue) {
+            psNode->psLeftNode = FLTCreateFilterEncodingNode();
+            psNode->psLeftNode->eType = FILTER_NODE_TYPE_COMPARISON;
+            psNode->psLeftNode->pszValue = msStrdup(pszComparionValue);
 
-        pszComparionValue = msSLDGetComparisonValue(pszExpression);
-        pszAttibuteName = msSLDGetAttributeName(pszExpression, pszComparionValue);
-        pszAttibuteValue = msSLDGetAttributeValue(pszExpression, pszComparionValue);
-        if (pszComparionValue && pszAttibuteName && pszAttibuteValue)
-        {
-            psNode->eType = FILTER_NODE_TYPE_COMPARISON;
-            psNode->pszValue = msStrdup(pszComparionValue);
+            psNode->psLeftNode->psLeftNode = FLTCreateFilterEncodingNode();
+            psNode->psLeftNode->psLeftNode->eType =
+              FILTER_NODE_TYPE_PROPERTYNAME;
+            psNode->psLeftNode->psLeftNode->pszValue = msStrdup(pszAttibuteName);
 
-            psNode->psLeftNode = FLTCreateFilterEncodingNode();
-            psNode->psLeftNode->eType = FILTER_NODE_TYPE_PROPERTYNAME;
-            psNode->psLeftNode->pszValue = msStrdup(pszAttibuteName);
+            psNode->psLeftNode->psRightNode = FLTCreateFilterEncodingNode();
+            psNode->psLeftNode->psRightNode->eType =
+              FILTER_NODE_TYPE_LITERAL;
+            psNode->psLeftNode->psRightNode->pszValue =
+              msStrdup(pszAttibuteValue);
 
-            psNode->psRightNode = FLTCreateFilterEncodingNode();
-            psNode->psRightNode->eType = FILTER_NODE_TYPE_LITERAL;
-            psNode->psRightNode->pszValue = msStrdup(pszAttibuteValue);
-
-            if (strcasecmp(pszComparionValue, "PropertyIsLike") == 0)
-            {
-                psNode->pOther = (FEPropertyIsLike *)malloc(sizeof(FEPropertyIsLike));
-                ((FEPropertyIsLike *)psNode->pOther)->bCaseInsensitive = 0;
-                ((FEPropertyIsLike *)psNode->pOther)->pszWildCard = msStrdup("*");
-                 ((FEPropertyIsLike *)psNode->pOther)->pszSingleChar = msStrdup("#");
-                 ((FEPropertyIsLike *)psNode->pOther)->pszEscapeChar = msStrdup("!");
-            }
             free(pszComparionValue);
             free(pszAttibuteName);
             free(pszAttibuteValue);
+          }
         }
-        return psNode;
-        
-    }
-    else if (nOperators == 1)
-    {
-        pszOperator = msSLDGetLogicalOperator(pszExpression);
-        if (pszOperator)
-        {
-            if (!psNode)
-                  psNode = FLTCreateFilterEncodingNode();
-
-            psNode->eType = FILTER_NODE_TYPE_LOGICAL;
-            psNode->pszValue = msStrdup(pszOperator);
-            free(pszOperator);
-
-            pszLeftExpression = msSLDGetLeftExpressionOfOperator(pszExpression);
-            pszRightExpression = msSLDGetRightExpressionOfOperator(pszExpression);
-            
-            if (pszLeftExpression || pszRightExpression)
-            {
-                if (pszLeftExpression)
-                {
-                    pszComparionValue = msSLDGetComparisonValue(pszLeftExpression);
-                    pszAttibuteName = msSLDGetAttributeName(pszLeftExpression, 
-                                                            pszComparionValue);
-                    pszAttibuteValue = msSLDGetAttributeValue(pszLeftExpression, 
-                                                              pszComparionValue);
-
-                    if (pszComparionValue && pszAttibuteName && pszAttibuteValue)
-                    {
-                        psNode->psLeftNode = FLTCreateFilterEncodingNode();
-                        psNode->psLeftNode->eType = FILTER_NODE_TYPE_COMPARISON;
-                        psNode->psLeftNode->pszValue = msStrdup(pszComparionValue);
-
-                        psNode->psLeftNode->psLeftNode = FLTCreateFilterEncodingNode();
-                        psNode->psLeftNode->psLeftNode->eType = 
-                          FILTER_NODE_TYPE_PROPERTYNAME;
-                        psNode->psLeftNode->psLeftNode->pszValue = msStrdup(pszAttibuteName);
-
-                        psNode->psLeftNode->psRightNode = FLTCreateFilterEncodingNode();
-                        psNode->psLeftNode->psRightNode->eType = 
-                          FILTER_NODE_TYPE_LITERAL;
-                        psNode->psLeftNode->psRightNode->pszValue = 
-                          msStrdup(pszAttibuteValue);
-
-                        free(pszComparionValue);
-                        free(pszAttibuteName);
-                        free(pszAttibuteValue);
-                    }
-                }
-                if (pszRightExpression)
-                {
-                    pszComparionValue = msSLDGetComparisonValue(pszRightExpression);
-                    pszAttibuteName = msSLDGetAttributeName(pszRightExpression, 
-                                                            pszComparionValue);
-                    pszAttibuteValue = msSLDGetAttributeValue(pszRightExpression, 
-                                                              pszComparionValue);
-
-                    if (pszComparionValue && pszAttibuteName && pszAttibuteValue)
-                    {
-                        psNode->psRightNode = FLTCreateFilterEncodingNode();
-                        psNode->psRightNode->eType = FILTER_NODE_TYPE_COMPARISON;
-                        psNode->psRightNode->pszValue = msStrdup(pszComparionValue);
-
-                        psNode->psRightNode->psLeftNode = 
-                          FLTCreateFilterEncodingNode();
-                        psNode->psRightNode->psLeftNode->eType = 
-                          FILTER_NODE_TYPE_PROPERTYNAME;
-                        psNode->psRightNode->psLeftNode->pszValue = 
-                          msStrdup(pszAttibuteName);
-
-                        psNode->psRightNode->psRightNode = 
-                          FLTCreateFilterEncodingNode();
-                        psNode->psRightNode->psRightNode->eType = 
-                          FILTER_NODE_TYPE_LITERAL;
-                        psNode->psRightNode->psRightNode->pszValue = 
-                          msStrdup(pszAttibuteValue);
-
-                        free(pszComparionValue);
-                        free(pszAttibuteName);
-                        free(pszAttibuteValue);
-                    }
-                }
-            }
-        }
-
-        return psNode;
-    }
-    else
-      return NULL;
+        if (pszRightExpression) {
+          pszComparionValue = msSLDGetComparisonValue(pszRightExpression);
+          pszAttibuteName = msSLDGetAttributeName(pszRightExpression,
+                                                  pszComparionValue);
+          pszAttibuteValue = msSLDGetAttributeValue(pszRightExpression,
+                             pszComparionValue);
+
+          if (pszComparionValue && pszAttibuteName && pszAttibuteValue) {
+            psNode->psRightNode = FLTCreateFilterEncodingNode();
+            psNode->psRightNode->eType = FILTER_NODE_TYPE_COMPARISON;
+            psNode->psRightNode->pszValue = msStrdup(pszComparionValue);
+
+            psNode->psRightNode->psLeftNode =
+              FLTCreateFilterEncodingNode();
+            psNode->psRightNode->psLeftNode->eType =
+              FILTER_NODE_TYPE_PROPERTYNAME;
+            psNode->psRightNode->psLeftNode->pszValue =
+              msStrdup(pszAttibuteName);
+
+            psNode->psRightNode->psRightNode =
+              FLTCreateFilterEncodingNode();
+            psNode->psRightNode->psRightNode->eType =
+              FILTER_NODE_TYPE_LITERAL;
+            psNode->psRightNode->psRightNode->pszValue =
+              msStrdup(pszAttibuteValue);
 
-    /*
-    for (i=0; i<nLength; i++)
-    {
-        if (pszExpression[i] == '(')
-        {
-            if (bInsideExpression)
-            {
-                pszFinalExpression[iFinal++] = pszExpression[i];
-                nOpeningBrackets++;
-            }
-            else
-            {
-                bInsideExpression = 1;
-                iExpression++;
-                iIndiceExp = 0;
-            }
-        }
-        else if (pszExpression[i] == ')')
-        {
-            if (bInsideExpression)
-            {
-                if (nOpeningBrackets > 0)
-                {
-                    nOpeningBrackets--;
-                    apszExpression[iExpression][iIndiceExp++] = pszExpression[i];
-                }
-                else
-                {
-                    // end of an expression
-                    pszFinalExpression[iFinal++] = ' ';
-                    pszFinalExpression[iFinal] = '\0';
-                    sprintf(szTmp, "exp%d ", iExpression);
-                    strcat(pszFinalExpression,szTmp);
-                    if (iExpression < 10)
-                      iFinal+=5;
-                    else
-                      iFinal+=6;
-                    bInsideExpression = 0;
-                }
-            }
-        }
-        else
-        {
-            if (bInsideExpression)
-            {
-                apszExpression[iExpression][iIndiceExp++] = pszExpression[i];
-            }
-            else
-            {
-                pszFinalExpression[iFinal++] =  pszExpression[i];
-            }
+            free(pszComparionValue);
+            free(pszAttibuteName);
+            free(pszAttibuteValue);
+          }
         }
-
-        if (iExpression >=0 && iIndiceExp >0)
-          apszExpression[iExpression][iIndiceExp] = '\0';
-        if (iFinal > 0)
-          pszFinalExpression[iFinal] = '\0';
+      }
     }
 
-    if (msSLDHasMoreThatOneLogicalOperator(pszFinalExpression))
-    {
-        pszSimplifiedExpression = 
-          msSLDSimplifyExpression(pszFinalExpression);
-        free(pszFinalExpression);
-        
-        // increase the size so it can fit the brakets () that will be added
-        pszFinalExpression = (char *)malloc(sizeof(char)*(nLength+3));
-        if(iExpression > 0)
-        {
-            nLength = strlen(pszSimplifiedExpression);
-            iFinal = 0;
-            for (i=0; i<nLength; i++)
-            {
-                if (i < nLength-4)
-                {
-                    if (pszSimplifiedExpression[i] == 'e' &&
-                        pszSimplifiedExpression[i+1] == 'x' &&
-                        pszSimplifiedExpression[i+2] == 'p')
-                    {
-                        nIndice = atoi(pszSimplifiedExpression[i+3]);
-                        if (nIndice >=0 && nIndice < iExpression)
-                        {
-                            strcat(pszFinalExpression, 
-                                   apszExpression[nIndice]);
-                            iFinal+= strlen(apszExpression[nIndice]);
-                        }
-                    }
-                }
-                else
-                {
-                    pszFinalExpression[iFinal++] = pszSimplifiedExpression[i];
-                }
-            }    
-        }
-        else
-          pszFinalExpression = msStrdup(pszFinalExpression);
-
-        return BuildExpressionTree(pszFinalExpression, psNode);
-    }
-    pszLogicalOper = msSLDGetLogicalOperator(pszFinalExpression);
-    //TODO : NOT operator
-    if (pszLogicalOper)
-    {
-        if (strcasecmp(pszLogicalOper, "AND") == 0 ||
-            strcasecmp(pszLogicalOper, "OR") == 0)
-        {
-            if (!psNode)
-              psNode = FLTCreateFilterEncodingNode();
-        
-            psNode->eType = FILTER_NODE_TYPE_LOGICAL;
-            if (strcasecmp(pszLogicalOper, "AND") == 0)
-              psNode->pszValue = "AND";
-            else
-              psNode->pszValue = "OR";
-                
-            psNode->psLeftNode =  FLTCreateFilterEncodingNode();
-            psNode->psRightNode =  FLTCreateFilterEncodingNode();
-
-            psLeftExpresion = 
-              msSLDGetLogicalOperatorExpression(pszFinalExpression, 0);
-            psRightExpresion = 
-              msSLDGetLogicalOperatorExpression(pszFinalExpression, 0);
-            
-            BuildExpressionTree(psNode->psLeftNode, psLeftExpresion);
-
-            BuildExpressionTree(psNode->psRightNode,psRightExpresion);
-
-            if (psLeftExpresion)
-              free(psLeftExpresion);
-            if (psRightExpresion)
-              free(psRightExpresion);
-        }
-    }
-    else //means it is a simple expression with comaprison
-    {
+    return psNode;
+  } else
+    return NULL;
+}
 
-    */
-    
-}   
-    
 char *msSLDBuildFilterEncoding(FilterEncodingNode *psNode)
 {
-    char *pszTmp = NULL;
-    char szTmp[200];
-    char *pszExpression = NULL;
+  char *pszTmp = NULL;
+  char szTmp[200];
+  char *pszExpression = NULL;
 
-    if (!psNode)
-      return NULL;
+  if (!psNode)
+    return NULL;
 
-    if (psNode->eType == FILTER_NODE_TYPE_COMPARISON && 
-        psNode->pszValue && psNode->psLeftNode && psNode->psLeftNode->pszValue &&
-        psNode->psRightNode && psNode->psRightNode->pszValue)
-    {
-        snprintf(szTmp, sizeof(szTmp), "<ogc:%s><ogc:PropertyName>%s</ogc:PropertyName><ogc:Literal>%s</ogc:Literal></ogc:%s>",
-                 psNode->pszValue, psNode->psLeftNode->pszValue,
-                 psNode->psRightNode->pszValue, psNode->pszValue);
-        pszExpression = msStrdup(szTmp);
-    }
-    else if (psNode->eType == FILTER_NODE_TYPE_LOGICAL && 
-             psNode->pszValue && 
+  if (psNode->eType == FILTER_NODE_TYPE_COMPARISON &&
+      psNode->pszValue && psNode->psLeftNode && psNode->psLeftNode->pszValue &&
+      psNode->psRightNode && psNode->psRightNode->pszValue) {
+    snprintf(szTmp, sizeof(szTmp), "<ogc:%s><ogc:PropertyName>%s</ogc:PropertyName><ogc:Literal>%s</ogc:Literal></ogc:%s>",
+             psNode->pszValue, psNode->psLeftNode->pszValue,
+             psNode->psRightNode->pszValue, psNode->pszValue);
+    pszExpression = msStrdup(szTmp);
+  } else if (psNode->eType == FILTER_NODE_TYPE_LOGICAL &&
+             psNode->pszValue &&
              ((psNode->psLeftNode && psNode->psLeftNode->pszValue) ||
-              (psNode->psRightNode && psNode->psRightNode->pszValue)))
-    {
-        snprintf(szTmp, sizeof(szTmp), "<ogc:%s>", psNode->pszValue);
-        pszExpression = msStringConcatenate(pszExpression, szTmp);
-        if (psNode->psLeftNode)
-        {
-            pszTmp = msSLDBuildFilterEncoding(psNode->psLeftNode);
-            if (pszTmp)
-            {
-                pszExpression = msStringConcatenate(pszExpression, pszTmp); 
-                free(pszTmp);
-            }
-        }
-        if (psNode->psRightNode)
-        {
-            pszTmp = msSLDBuildFilterEncoding(psNode->psRightNode);
-            if (pszTmp)
-            {
-                pszExpression = msStringConcatenate(pszExpression, pszTmp); 
-                free(pszTmp);
-            }
-        }
-        snprintf(szTmp,  sizeof(szTmp), "</ogc:%s>", psNode->pszValue);
-        pszExpression = msStringConcatenate(pszExpression, szTmp);
+              (psNode->psRightNode && psNode->psRightNode->pszValue))) {
+    snprintf(szTmp, sizeof(szTmp), "<ogc:%s>", psNode->pszValue);
+    pszExpression = msStringConcatenate(pszExpression, szTmp);
+    if (psNode->psLeftNode) {
+      pszTmp = msSLDBuildFilterEncoding(psNode->psLeftNode);
+      if (pszTmp) {
+        pszExpression = msStringConcatenate(pszExpression, pszTmp);
+        free(pszTmp);
+      }
     }
-    return pszExpression;
+    if (psNode->psRightNode) {
+      pszTmp = msSLDBuildFilterEncoding(psNode->psRightNode);
+      if (pszTmp) {
+        pszExpression = msStringConcatenate(pszExpression, pszTmp);
+        free(pszTmp);
+      }
+    }
+    snprintf(szTmp,  sizeof(szTmp), "</ogc:%s>", psNode->pszValue);
+    pszExpression = msStringConcatenate(pszExpression, szTmp);
+  }
+  return pszExpression;
 }
 
-      
+
 
 char *msSLDParseLogicalExpression(char *pszExpression, const char *pszWfsFilter)
 {
-    FilterEncodingNode *psNode = NULL;
-    char *pszFLTExpression = NULL;
-    char *pszTmp = NULL;
+  FilterEncodingNode *psNode = NULL;
+  char *pszFLTExpression = NULL;
+  char *pszTmp = NULL;
 
-    if (!pszExpression || strlen(pszExpression) <=0)
-      return NULL;
+  if (!pszExpression || strlen(pszExpression) <=0)
+    return NULL;
 
 
-    /* psNode = BuildExpressionTree(pszExpression, NULL); */
-    psNode = BuildExpressionTree(pszExpression, NULL);
-    
-    if (psNode)
-    {
-        pszFLTExpression = msSLDBuildFilterEncoding(psNode);
-        if (pszFLTExpression)
-        {
-            pszTmp = msStringConcatenate(pszTmp, "<ogc:Filter>");
-            if (pszWfsFilter)
-            {
-                pszTmp = msStringConcatenate(pszTmp, "<ogc:And>");
-                pszTmp = msStringConcatenate(pszTmp, (char *)pszWfsFilter);
-            }
-            pszTmp = msStringConcatenate(pszTmp, pszFLTExpression);
+  /* psNode = BuildExpressionTree(pszExpression, NULL); */
+  psNode = BuildExpressionTree(pszExpression, NULL);
 
-            if (pszWfsFilter)
-              pszTmp = msStringConcatenate(pszTmp, "</ogc:And>");
+  if (psNode) {
+    pszFLTExpression = msSLDBuildFilterEncoding(psNode);
+    if (pszFLTExpression) {
+      pszTmp = msStringConcatenate(pszTmp, "<ogc:Filter>");
+      if (pszWfsFilter) {
+        pszTmp = msStringConcatenate(pszTmp, "<ogc:And>");
+        pszTmp = msStringConcatenate(pszTmp, (char *)pszWfsFilter);
+      }
+      pszTmp = msStringConcatenate(pszTmp, pszFLTExpression);
 
-            pszTmp = msStringConcatenate(pszTmp, "</ogc:Filter>\n");
+      if (pszWfsFilter)
+        pszTmp = msStringConcatenate(pszTmp, "</ogc:And>");
 
-            free(pszFLTExpression);
-            pszFLTExpression = pszTmp;
-        }
-            
+      pszTmp = msStringConcatenate(pszTmp, "</ogc:Filter>\n");
+
+      free(pszFLTExpression);
+      pszFLTExpression = pszTmp;
     }
-    
-    return pszFLTExpression;
+
+  }
+
+  return pszFLTExpression;
 }
 
 /************************************************************************/
@@ -5445,93 +4932,83 @@ char *msSLDParseLogicalExpression(char *pszExpression, const char *pszWfsFilter)
 /************************************************************************/
 char *msSLDParseExpression(char *pszExpression)
 {
-    int nElements = 0;
-    char **aszElements = NULL;
-    char szBuffer[500];
-    char szFinalAtt[40];
-    char szFinalValue[40];
-    char szAttribute[40];
-    char szValue[40];
-    int i=0, nLength=0, iAtt=0, iVal=0; 
-    int bStartCopy=0, bSinglequote=0, bDoublequote=0;
-    char *pszFilter = NULL;
- 
-    if (!pszExpression)
-      return NULL;
-
-    nLength = strlen(pszExpression);
-
-    aszElements = msStringSplit(pszExpression, ' ', &nElements);
-
-    szFinalAtt[0] = '\0';
-    szFinalValue[0] = '\0';
-    for (i=0; i<nElements; i++)
-    {
-        if (strcasecmp(aszElements[i], "=") == 0 ||
-            strcasecmp(aszElements[i], "eq") == 0)
-        {
-            if (i > 0 && i < nElements-1)
-            {
-              snprintf(szAttribute, sizeof(szAttribute), "%s", aszElements[i-1]);
-	      snprintf(szValue, sizeof(szValue), "%s", aszElements[i+1]);
-
-                /* parse attribute */
-                nLength = strlen(szAttribute);
-                if (nLength > 0)
-                {
-                    iAtt = 0;
-                    for (i=0; i<nLength; i++)
-                    {
-                        if (szAttribute[i] == '[')
-                        {
-                            bStartCopy = 1;
-                            continue;
-                        }
-                        if (szAttribute[i] == ']')
-                          break;
-                        if (bStartCopy)
-                        {
-                            szFinalAtt[iAtt] = szAttribute[i];
-                            iAtt++;
-                        }
-                        szFinalAtt[iAtt] = '\0';
-                    }
-                }
+  int nElements = 0;
+  char **aszElements = NULL;
+  char szBuffer[500];
+  char szFinalAtt[40];
+  char szFinalValue[40];
+  char szAttribute[40];
+  char szValue[40];
+  int i=0, nLength=0, iAtt=0, iVal=0;
+  int bStartCopy=0, bSinglequote=0, bDoublequote=0;
+  char *pszFilter = NULL;
+
+  if (!pszExpression)
+    return NULL;
 
-                /* parse value */
-                nLength = strlen(szValue);
-                if (nLength > 0)
-                {
-                    if (szValue[0] == '\'')
-                      bSinglequote = 1;
-                    else if (szValue[0] == '\"')
-                       bDoublequote = 1;
-                    else
-                       snprintf(szFinalValue, sizeof(szFinalValue), "%s", szValue);
-                    
-                    iVal = 0;
-                    if (bSinglequote || bDoublequote)
-                    {
-                         for (i=1; i<nLength-1; i++)
-                           szFinalValue[iVal++] = szValue[i];
-
-                         szFinalValue[iVal] = '\0';
-                    }
-                }
+  nLength = strlen(pszExpression);
+
+  aszElements = msStringSplit(pszExpression, ' ', &nElements);
+
+  szFinalAtt[0] = '\0';
+  szFinalValue[0] = '\0';
+  for (i=0; i<nElements; i++) {
+    if (strcasecmp(aszElements[i], "=") == 0 ||
+        strcasecmp(aszElements[i], "eq") == 0) {
+      if (i > 0 && i < nElements-1) {
+        snprintf(szAttribute, sizeof(szAttribute), "%s", aszElements[i-1]);
+        snprintf(szValue, sizeof(szValue), "%s", aszElements[i+1]);
+
+        /* parse attribute */
+        nLength = strlen(szAttribute);
+        if (nLength > 0) {
+          iAtt = 0;
+          for (i=0; i<nLength; i++) {
+            if (szAttribute[i] == '[') {
+              bStartCopy = 1;
+              continue;
             }
-            if (strlen(szFinalAtt) > 0 && strlen(szFinalValue) >0)
-            {
-                snprintf(szBuffer, sizeof(szBuffer), "<ogc:Filter><ogc:PropertyIsEqualTo><ogc:PropertyName>%s</ogc:PropertyName><ogc:Literal>%s</ogc:Literal></ogc:PropertyIsEqualTo></ogc:Filter>", 
-                        szFinalAtt, szFinalValue);
-                pszFilter = msStrdup(szBuffer);
+            if (szAttribute[i] == ']')
+              break;
+            if (bStartCopy) {
+              szFinalAtt[iAtt] = szAttribute[i];
+              iAtt++;
             }
+            szFinalAtt[iAtt] = '\0';
+          }
         }
+
+        /* parse value */
+        nLength = strlen(szValue);
+        if (nLength > 0) {
+          if (szValue[0] == '\'')
+            bSinglequote = 1;
+          else if (szValue[0] == '\"')
+            bDoublequote = 1;
+          else
+            snprintf(szFinalValue, sizeof(szFinalValue), "%s", szValue);
+
+          iVal = 0;
+          if (bSinglequote || bDoublequote) {
+            for (i=1; i<nLength-1; i++)
+              szFinalValue[iVal++] = szValue[i];
+
+            szFinalValue[iVal] = '\0';
+          }
+        }
+      }
+      if (strlen(szFinalAtt) > 0 && strlen(szFinalValue) >0) {
+        snprintf(szBuffer, sizeof(szBuffer), "<ogc:Filter><ogc:PropertyIsEqualTo><ogc:PropertyName>%s</ogc:PropertyName><ogc:Literal>%s</ogc:Literal></ogc:PropertyIsEqualTo></ogc:Filter>",
+                 szFinalAtt, szFinalValue);
+        pszFilter = msStrdup(szBuffer);
+      }
     }
+  }
+
+  return pszFilter;
+}
+
 
-    return pszFilter;
-}               
-               
-    
 /************************************************************************/
 /*                     msSLDConvertRegexExpToOgcIsLike                  */
 /*                                                                      */
@@ -5561,41 +5038,34 @@ char *msSLDParseExpression(char *pszExpression)
 /*                                                                      */
 /************************************************************************/
 char *msSLDConvertRegexExpToOgcIsLike(char *pszRegex)
-{   
-    char szBuffer[1024];
-    int iBuffer = 0, i=0;
-    int nLength = 0;
-
-    if (!pszRegex || strlen(pszRegex) == 0)
-      return NULL;
+{
+  char szBuffer[1024];
+  int iBuffer = 0, i=0;
+  int nLength = 0;
 
-    szBuffer[0] = '\0';
-    nLength = strlen(pszRegex);
+  if (!pszRegex || strlen(pszRegex) == 0)
+    return NULL;
 
-    while (i < nLength)
-    {
-        if (pszRegex[i] != '.')
-        {
-            szBuffer[iBuffer++] = pszRegex[i];
-            i++;
-        }
-        else 
-        {
-            if (i<nLength-1 && pszRegex[i+1] == '*')
-            {
-                szBuffer[iBuffer++] = '*';
-                i = i+2;
-            }
-            else
-            {
-                szBuffer[iBuffer++] =  pszRegex[i];
-                i++;
-            }
-        }
+  szBuffer[0] = '\0';
+  nLength = strlen(pszRegex);
+
+  while (i < nLength) {
+    if (pszRegex[i] != '.') {
+      szBuffer[iBuffer++] = pszRegex[i];
+      i++;
+    } else {
+      if (i<nLength-1 && pszRegex[i+1] == '*') {
+        szBuffer[iBuffer++] = '*';
+        i = i+2;
+      } else {
+        szBuffer[iBuffer++] =  pszRegex[i];
+        i++;
+      }
     }
-    szBuffer[iBuffer] = '\0';
+  }
+  szBuffer[iBuffer] = '\0';
 
-    return msStrdup(szBuffer);
+  return msStrdup(szBuffer);
 }
 
 
@@ -5609,56 +5079,46 @@ char *msSLDConvertRegexExpToOgcIsLike(char *pszRegex)
 /************************************************************************/
 char *msSLDGetFilter(classObj *psClass, const char *pszWfsFilter)
 {
-    char *pszFilter = NULL;
-    char szBuffer[500];
-    char *pszOgcFilter = NULL;
-
-    if (psClass && psClass->expression.string)
-    {   
-        /* string expression */
-        if (psClass->expression.type == MS_STRING)
-        {
-            if (psClass->layer && psClass->layer->classitem)
-            {
-                if (pszWfsFilter)
-                  snprintf(szBuffer, sizeof(szBuffer), "<ogc:Filter><ogc:And>%s<ogc:PropertyIsEqualTo><ogc:PropertyName>%s</ogc:PropertyName><ogc:Literal>%s</ogc:Literal></ogc:PropertyIsEqualTo></ogc:And></ogc:Filter>\n", 
-                        pszWfsFilter, psClass->layer->classitem, psClass->expression.string);
-                else
-                  snprintf(szBuffer, sizeof(szBuffer), "<ogc:Filter><ogc:PropertyIsEqualTo><ogc:PropertyName>%s</ogc:PropertyName><ogc:Literal>%s</ogc:Literal></ogc:PropertyIsEqualTo></ogc:Filter>\n", 
-                        psClass->layer->classitem, psClass->expression.string);
-                pszFilter = msStrdup(szBuffer);
-            }
-        }
-        else if (psClass->expression.type == MS_EXPRESSION)
-        {
-            pszFilter = msSLDParseLogicalExpression(psClass->expression.string, 
-                                                    pszWfsFilter);
-        }
-        else if (psClass->expression.type == MS_REGEX)
-        {
-            if (psClass->layer && psClass->layer->classitem && psClass->expression.string)
-            {
-                pszOgcFilter = msSLDConvertRegexExpToOgcIsLike(psClass->expression.string);
+  char *pszFilter = NULL;
+  char szBuffer[500];
+  char *pszOgcFilter = NULL;
+
+  if (psClass && psClass->expression.string) {
+    /* string expression */
+    if (psClass->expression.type == MS_STRING) {
+      if (psClass->layer && psClass->layer->classitem) {
+        if (pszWfsFilter)
+          snprintf(szBuffer, sizeof(szBuffer), "<ogc:Filter><ogc:And>%s<ogc:PropertyIsEqualTo><ogc:PropertyName>%s</ogc:PropertyName><ogc:Literal>%s</ogc:Literal></ogc:PropertyIsEqualTo></ogc:And></ogc:Filter>\n",
+                   pszWfsFilter, psClass->layer->classitem, psClass->expression.string);
+        else
+          snprintf(szBuffer, sizeof(szBuffer), "<ogc:Filter><ogc:PropertyIsEqualTo><ogc:PropertyName>%s</ogc:PropertyName><ogc:Literal>%s</ogc:Literal></ogc:PropertyIsEqualTo></ogc:Filter>\n",
+                   psClass->layer->classitem, psClass->expression.string);
+        pszFilter = msStrdup(szBuffer);
+      }
+    } else if (psClass->expression.type == MS_EXPRESSION) {
+      pszFilter = msSLDParseLogicalExpression(psClass->expression.string,
+                                              pszWfsFilter);
+    } else if (psClass->expression.type == MS_REGEX) {
+      if (psClass->layer && psClass->layer->classitem && psClass->expression.string) {
+        pszOgcFilter = msSLDConvertRegexExpToOgcIsLike(psClass->expression.string);
 
-                if (pszWfsFilter)
-                  snprintf(szBuffer, sizeof(szBuffer), "<ogc:Filter><ogc:And>%s<ogc:PropertyIsLike wildCard=\"*\" singleChar=\".\" escape=\"\\\"><ogc:PropertyName>%s</ogc:PropertyName><ogc:Literal>%s</ogc:Literal></ogc:PropertyIsLike></ogc:And></ogc:Filter>\n", 
-                        pszWfsFilter, psClass->layer->classitem, pszOgcFilter);
-                else
-                  snprintf(szBuffer, sizeof(szBuffer), "<ogc:Filter><ogc:PropertyIsLike wildCard=\"*\" singleChar=\".\" escape=\"\\\"><ogc:PropertyName>%s</ogc:PropertyName><ogc:Literal>%s</ogc:Literal></ogc:PropertyIsLike></ogc:Filter>\n", 
-                          psClass->layer->classitem, pszOgcFilter);
+        if (pszWfsFilter)
+          snprintf(szBuffer, sizeof(szBuffer), "<ogc:Filter><ogc:And>%s<ogc:PropertyIsLike wildCard=\"*\" singleChar=\".\" escape=\"\\\"><ogc:PropertyName>%s</ogc:PropertyName><ogc:Literal>%s</ogc:Literal></ogc:PropertyIsLike></ogc:And></ogc:Filter>\n",
+                   pszWfsFilter, psClass->layer->classitem, pszOgcFilter);
+        else
+          snprintf(szBuffer, sizeof(szBuffer), "<ogc:Filter><ogc:PropertyIsLike wildCard=\"*\" singleChar=\".\" escape=\"\\\"><ogc:PropertyName>%s</ogc:PropertyName><ogc:Literal>%s</ogc:Literal></ogc:PropertyIsLike></ogc:Filter>\n",
+                   psClass->layer->classitem, pszOgcFilter);
 
-                free(pszOgcFilter);
+        free(pszOgcFilter);
 
-                pszFilter = msStrdup(szBuffer);
-            }
-        }
-    }
-    else if (pszWfsFilter)
-    {
-        snprintf(szBuffer, sizeof(szBuffer), "<ogc:Filter>%s</ogc:Filter>\n", pszWfsFilter);
         pszFilter = msStrdup(szBuffer);
+      }
     }
-    return pszFilter;
-}            
+  } else if (pszWfsFilter) {
+    snprintf(szBuffer, sizeof(szBuffer), "<ogc:Filter>%s</ogc:Filter>\n", pszWfsFilter);
+    pszFilter = msStrdup(szBuffer);
+  }
+  return pszFilter;
+}
 
 #endif
diff --git a/mapogcsld.h b/mapogcsld.h
index 7c42255..a6a5f4b 100644
--- a/mapogcsld.h
+++ b/mapogcsld.h
@@ -14,25 +14,25 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
+ *
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  ****************************************************************************/
 
 #include "mapserver.h"
 
 MS_DLL_EXPORT char *msSLDGenerateSLD(mapObj *map, int iLayer, const char *pszVersion);
 MS_DLL_EXPORT int msSLDApplySLDURL(mapObj *map, char *szURL, int iLayer,
-                                   char *pszStyleLayerName);
-MS_DLL_EXPORT int msSLDApplySLD(mapObj *map, char *psSLDXML, int iLayer, 
-                                char *pszStyleLayerName);
+                                   char *pszStyleLayerName, char **ppszLayerNames);
+MS_DLL_EXPORT int msSLDApplySLD(mapObj *map, char *psSLDXML, int iLayer,
+                                char *pszStyleLayerName, char **ppszLayerNames);
 
 #ifdef USE_OGR
 
@@ -49,22 +49,22 @@ int msSLDParseRule(CPLXMLNode *psRoot, layerObj *psLayer);
 int msSLDParseStroke(CPLXMLNode *psStroke, styleObj *psStyle,
                      mapObj *map, int iColorParam);
 int msSLDParsePolygonFill(CPLXMLNode *psFill, styleObj *psStyle,
-                           mapObj *map);
+                          mapObj *map);
 
-int msSLDParseLineSymbolizer(CPLXMLNode *psRoot, layerObj *psLayer,  
+int msSLDParseLineSymbolizer(CPLXMLNode *psRoot, layerObj *psLayer,
                              int bNewClass);
 int msSLDParsePolygonSymbolizer(CPLXMLNode *psRoot, layerObj *psLayer,
                                 int bNewClass);
-int msSLDParsePointSymbolizer(CPLXMLNode *psRoot, layerObj *psLayer, 
+int msSLDParsePointSymbolizer(CPLXMLNode *psRoot, layerObj *psLayer,
                               int bNewClass);
 int msSLDParseTextSymbolizer(CPLXMLNode *psRoot, layerObj *psLayer,
-                              int bOtherSymboliser);
+                             int bOtherSymboliser);
 int msSLDParseRasterSymbolizer(CPLXMLNode *psRoot, layerObj *psLayer);
 
 int msSLDParseGraphicFillOrStroke(CPLXMLNode *psGraphicFill,
                                   char *pszDashValue,
                                   styleObj *psStyle, mapObj *map, int bPointLayer);
-int msSLDParseExternalGraphic(CPLXMLNode *psExternalGraphic, styleObj *psStyle, 
+int msSLDParseExternalGraphic(CPLXMLNode *psExternalGraphic, styleObj *psStyle,
                               mapObj *map);
 
 int msSLDGetLineSymbol(mapObj *map);
diff --git a/mapogcsos.c b/mapogcsos.c
index 7f2d5a6..274405f 100644
--- a/mapogcsos.c
+++ b/mapogcsos.c
@@ -14,16 +14,16 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
+ *
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  * DEALINGS IN THE SOFTWARE.
  **********************************************************************/
 
@@ -32,7 +32,7 @@
 #include "mapserver.h"
 
 
-MS_CVSID("$Id$")
+
 
 #if defined(USE_SOS_SVR) && defined(USE_LIBXML2)
 
@@ -73,17 +73,18 @@ void msSOSFreeParamsObj(sosParamsObj *sosparams);
 ** Report current MapServer error in XML exception format.
 ** Wrapper function around msOWSCommonExceptionReport. Merely
 ** passes SOS specific info.
-** 
+**
 */
 
-static int msSOSException(mapObj *map, char *locator, char *exceptionCode) {
+static int msSOSException(mapObj *map, char *locator, char *exceptionCode)
+{
   int size = 0;
   char *errorString     = NULL;
   char *errorMessage    = NULL;
   char *schemasLocation = NULL;
   const char *encoding;
 
-  xmlDocPtr  psDoc      = NULL;   
+  xmlDocPtr  psDoc      = NULL;
   xmlNodePtr psRootNode = NULL;
   xmlNsPtr   psNsOws    = NULL;
   xmlChar *buffer       = NULL;
@@ -101,15 +102,16 @@ static int msSOSException(mapObj *map, char *locator, char *exceptionCode) {
 
   xmlDocSetRootElement(psDoc, psRootNode);
 
-  psNsOws = xmlNewNs(psRootNode, BAD_CAST "http://www.opengis.net/ows/1.1", BAD_CAST "ows");
+  xmlNewNs(psRootNode, BAD_CAST "http://www.opengis.net/ows/1.1", BAD_CAST "ows");
 
   if (encoding)
-      msIO_printf("Content-type: text/xml; charset=%s%c%c", encoding,10,10);
+    msIO_setHeader("Content-Type","text/xml; charset=%s", encoding);
   else
-      msIO_printf("Content-type: text/xml%c%c",10,10);
+    msIO_setHeader("Content-Type","text/xml");
+  msIO_sendHeaders();
 
   xmlDocDumpFormatMemoryEnc(psDoc, &buffer, &size, (encoding ? encoding : "ISO-8859-1"), 1);
-    
+
   msIO_printf("%s", buffer);
 
   /*free buffer and the document */
@@ -118,22 +120,24 @@ static int msSOSException(mapObj *map, char *locator, char *exceptionCode) {
   free(schemasLocation);
   xmlFree(buffer);
   xmlFreeDoc(psDoc);
+  xmlFreeNs(psNsOws);
 
-  /* 
-  ** The typical pattern is to call msSOSException() right after 
+  /*
+  ** The typical pattern is to call msSOSException() right after
   ** msSetError().  In order to prevent mapserv.c from re-reporting this
   ** error at a higher level, we mark it as reported here. #3571
   */
   {
-      errorObj *err = msGetErrorObj();
-      if( err != NULL && err->code != MS_NOERR )
-          err->isreported = MS_TRUE;
+    errorObj *err = msGetErrorObj();
+    if( err != NULL && err->code != MS_NOERR )
+      err->isreported = MS_TRUE;
   }
 
   return MS_FAILURE;
 }
 
-static int _IsInList(char **papsProcedures, int nDistinctProcedures, char *pszProcedure) {
+static int _IsInList(char **papsProcedures, int nDistinctProcedures, char *pszProcedure)
+{
   int i = 0;
   if (papsProcedures && nDistinctProcedures > 0 && pszProcedure) {
     for (i=0; i<nDistinctProcedures; i++) {
@@ -150,39 +154,33 @@ static int _IsInList(char **papsProcedures, int nDistinctProcedures, char *pszPr
 /*      Look if the filter's property names have an equivalent          */
 /*      layre's attribute.                                              */
 /************************************************************************/
-static int msSOSValidateFilter(FilterEncodingNode *psFilterNode, 
-                                            layerObj *lp)
+static int msSOSValidateFilter(FilterEncodingNode *psFilterNode,
+                               layerObj *lp)
 {
-    int i=0, bFound =0;
-    /* assuming here that the layer is opened*/
-    if (psFilterNode && lp)
-    {
-        if (psFilterNode->eType == FILTER_NODE_TYPE_PROPERTYNAME)
-        {
-            for (i=0; i<lp->numitems; i++) 
-            {
-                if (strcasecmp(lp->items[i], psFilterNode->pszValue) == 0)
-                {
-                    bFound = 1;
-                    break;
-                }
-            }
-            if (!bFound)
-              return MS_FALSE;
-        }
-        if (psFilterNode->psLeftNode && psFilterNode->eType != FILTER_NODE_TYPE_SPATIAL)
-        {
-            if (msSOSValidateFilter(psFilterNode->psLeftNode, lp) == MS_FALSE)
-              return MS_FALSE;
-        }
-        if (psFilterNode->psRightNode && psFilterNode->eType != FILTER_NODE_TYPE_SPATIAL)
-        {
-            if (msSOSValidateFilter(psFilterNode->psRightNode, lp) == MS_FALSE)
-              return MS_FALSE;
+  int i=0, bFound =0;
+  /* assuming here that the layer is opened*/
+  if (psFilterNode && lp) {
+    if (psFilterNode->eType == FILTER_NODE_TYPE_PROPERTYNAME) {
+      for (i=0; i<lp->numitems; i++) {
+        if (strcasecmp(lp->items[i], psFilterNode->pszValue) == 0) {
+          bFound = 1;
+          break;
         }
+      }
+      if (!bFound)
+        return MS_FALSE;
+    }
+    if (psFilterNode->psLeftNode && psFilterNode->eType != FILTER_NODE_TYPE_SPATIAL) {
+      if (msSOSValidateFilter(psFilterNode->psLeftNode, lp) == MS_FALSE)
+        return MS_FALSE;
     }
+    if (psFilterNode->psRightNode && psFilterNode->eType != FILTER_NODE_TYPE_SPATIAL) {
+      if (msSOSValidateFilter(psFilterNode->psRightNode, lp) == MS_FALSE)
+        return MS_FALSE;
+    }
+  }
 
-    return MS_TRUE;
+  return MS_TRUE;
 }
 
 
@@ -193,26 +191,24 @@ static int msSOSValidateFilter(FilterEncodingNode *psFilterNode,
 /*      Utility function to add a metadata node.                        */
 /************************************************************************/
 void msSOSAddMetadataChildNode(xmlNodePtr psParent, const char *psNodeName,
-                              xmlNsPtr psNs, hashTableObj *metadata,
-                              const char *psNamespaces, 
-                              const char *psMetadataName, 
-                              const char *psDefaultValue)
+                               xmlNsPtr psNs, hashTableObj *metadata,
+                               const char *psNamespaces,
+                               const char *psMetadataName,
+                               const char *psDefaultValue)
 {
-    xmlNodePtr psNode = NULL;
-    char *psValue = NULL;
-
-    if (psParent && psNodeName)
-    {   
-        psValue = msOWSGetEncodeMetadata(metadata, psNamespaces, psMetadataName, 
-                                         psDefaultValue);
-        if (psValue)
-        {
-            psNode = xmlNewChild(psParent, NULL, BAD_CAST psNodeName, BAD_CAST psValue);
-            if (psNs)
-              xmlSetNs(psNode,  psNs);
-            free(psValue);
-        }
+  xmlNodePtr psNode = NULL;
+  char *psValue = NULL;
+
+  if (psParent && psNodeName) {
+    psValue = msOWSGetEncodeMetadata(metadata, psNamespaces, psMetadataName,
+                                     psDefaultValue);
+    if (psValue) {
+      psNode = xmlNewChild(psParent, NULL, BAD_CAST psNodeName, BAD_CAST psValue);
+      if (psNs)
+        xmlSetNs(psNode,  psNs);
+      free(psValue);
     }
+  }
 }
 
 
@@ -224,42 +220,36 @@ void msSOSAddMetadataChildNode(xmlNodePtr psParent, const char *psNodeName,
 layerObj *msSOSGetFirstLayerForOffering(mapObj *map, const char *pszOffering,
                                         const char *pszProperty)
 {
-    layerObj *lp = NULL;
-    const char *pszTmp = NULL;
-    int i = 0;
-
-    if (pszOffering && map)
-    {
-        for (i=0; i<map->numlayers; i++)
-        {
-            pszTmp = 
-              msOWSLookupMetadata(&(GET_LAYER(map, i)->metadata), "S", "offering_id");
-            if (pszTmp && (strcasecmp(pszTmp, pszOffering) == 0))
-            {
-                if (pszProperty)
-                {
-                    pszTmp = 
-                      msOWSLookupMetadata(&(GET_LAYER(map, i)->metadata), "S", 
-                                          "observedproperty_id");
-                    if (pszTmp && (strcasecmp(pszTmp, pszProperty) == 0))
-                    {
-                        lp = (GET_LAYER(map, i));
-                        break;
-                    }
-                }
-                else
-                {
-                    lp = (GET_LAYER(map, i));
-                    break;
-                }
-            }
+  layerObj *lp = NULL;
+  const char *pszTmp = NULL;
+  int i = 0;
+
+  if (pszOffering && map) {
+    for (i=0; i<map->numlayers; i++) {
+      pszTmp =
+        msOWSLookupMetadata(&(GET_LAYER(map, i)->metadata), "S", "offering_id");
+      if (pszTmp && (strcasecmp(pszTmp, pszOffering) == 0)) {
+        if (pszProperty) {
+          pszTmp =
+            msOWSLookupMetadata(&(GET_LAYER(map, i)->metadata), "S",
+                                "observedproperty_id");
+          if (pszTmp && (strcasecmp(pszTmp, pszProperty) == 0)) {
+            lp = (GET_LAYER(map, i));
+            break;
+          }
+        } else {
+          lp = (GET_LAYER(map, i));
+          break;
         }
+      }
     }
-    return lp;
+  }
+  return lp;
 }
 
-xmlNodePtr msSOSAddTimeNode(xmlNsPtr psNs, xmlNsPtr psNsGml, char *pszStart, char *pszEnd) {
-  xmlNodePtr psNode=NULL,psTimeNode=NULL;
+xmlNodePtr msSOSAddTimeNode(xmlNsPtr psNs, xmlNsPtr psNsGml, char *pszStart, char *pszEnd)
+{
+  xmlNodePtr psNode=NULL;
 
   char *timeel= NULL;
 
@@ -267,103 +257,101 @@ xmlNodePtr msSOSAddTimeNode(xmlNsPtr psNs, xmlNsPtr psNsGml, char *pszStart, cha
     timeel = "time";
   if (strcmp((char *)psNs->prefix,"om") == 0)
     timeel = "samplingTime";
-  else 
+  else
     timeel = "time";
 
   psNode = xmlNewNode(psNs, BAD_CAST timeel);
-  psTimeNode = xmlAddChild(psNode, msGML3TimePeriod(psNsGml, pszStart, pszEnd));
+  xmlAddChild(psNode, msGML3TimePeriod(psNsGml, pszStart, pszEnd));
   return psNode;
 }
 
 void msSOSAddPropertyNode(xmlNsPtr psNsSwe, xmlNsPtr psNsXLink, xmlNodePtr psParent, layerObj *lp, xmlNsPtr psNsGml, char *pszCompositePhenomenonId)
 {
-    const char *pszValue = NULL;
-    char *pszTmpVal = NULL, *pszFullName = NULL;
-    xmlNodePtr psCompNode, psNode;
-    int i, j=0;
-    char szTmp[256];
-    const char *pszComponentBase = "urn:ogc:def:property:";
-
-    if (psParent && lp)
-    {
-        psNode = xmlNewChild(psParent, NULL, BAD_CAST "observedProperty", NULL);
-        psCompNode = xmlNewChild(psNode, psNsSwe, BAD_CAST "CompositePhenomenon", NULL);
-        pszValue = msOWSLookupMetadata(&(lp->metadata), "S", 
-                                       "observedproperty_id");
-        pszTmpVal = msStrdup(pszValue);
+  const char *pszValue = NULL;
+  char *pszTmpVal = NULL, *pszFullName = NULL;
+  xmlNodePtr psCompNode, psNode;
+  int i, j=0;
+  char szTmp[256];
+  const char *pszComponentBase = "urn:ogc:def:property:";
+
+  if (psParent && lp) {
+    psNode = xmlNewChild(psParent, NULL, BAD_CAST "observedProperty", NULL);
+    psCompNode = xmlNewChild(psNode, psNsSwe, BAD_CAST "CompositePhenomenon", NULL);
+    pszValue = msOWSLookupMetadata(&(lp->metadata), "S",
+                                   "observedproperty_id");
+    pszTmpVal = msStrdup(pszValue);
+
+    if (pszCompositePhenomenonId != NULL) { /* unique value needs to be constructed */
+      pszTmpVal = msStringConcatenate(pszTmpVal, "_");
+      pszTmpVal = msStringConcatenate(pszTmpVal, pszCompositePhenomenonId);
+    }
 
-        if (pszCompositePhenomenonId != NULL) { /* unique value needs to be constructed */
-            pszTmpVal = msStringConcatenate(pszTmpVal, "_");
-            pszTmpVal = msStringConcatenate(pszTmpVal, pszCompositePhenomenonId);
-        }
+    if (pszTmpVal) { /*should always be true */
+      xmlNewNsProp(psCompNode, psNsGml, BAD_CAST "id", BAD_CAST pszTmpVal);
+      msFree(pszTmpVal);
+    }
 
-        if (pszTmpVal)/*should always be true */ {
-          xmlNewNsProp(psCompNode, psNsGml, BAD_CAST "id", BAD_CAST pszTmpVal);
-          msFree(pszTmpVal);
-        }
+    pszValue = msOWSLookupMetadata(&(lp->metadata), "S",
+                                   "observedproperty_name");
+    if (pszValue)
+      psNode = xmlNewChild(psCompNode, psNsGml,
+                           BAD_CAST "name", BAD_CAST pszValue);
 
-        pszValue = msOWSLookupMetadata(&(lp->metadata), "S", 
-                                         "observedproperty_name");
-        if (pszValue)
-          psNode = xmlNewChild(psCompNode, psNsGml, 
-                                 BAD_CAST "name", BAD_CAST pszValue);
+    /* add components */
 
-        /* add components */
- 
-        /*assuming that the layer is opened and msLayerGetItems called*/ 
-        for(i=0; i<lp->numitems; i++) 
-        {
-            pszValue = msOWSLookupMetadata(&(lp->metadata), "S", "observedproperty_authority");
+    /*assuming that the layer is opened and msLayerGetItems called*/
+    for(i=0; i<lp->numitems; i++) {
+      pszValue = msOWSLookupMetadata(&(lp->metadata), "S", "observedproperty_authority");
 
-            if (pszValue)
-              pszTmpVal = msStrdup(pszValue);
-            else
-              pszTmpVal = msStrdup("OGC-SWE");
+      if (pszValue)
+        pszTmpVal = msStrdup(pszValue);
+      else
+        pszTmpVal = msStrdup("OGC-SWE");
 
-            pszFullName = msStrdup(pszComponentBase);
+      pszFullName = msStrdup(pszComponentBase);
 
-            pszFullName = msStringConcatenate(pszFullName, pszTmpVal);
+      pszFullName = msStringConcatenate(pszFullName, pszTmpVal);
 
-            free(pszTmpVal);
+      free(pszTmpVal);
 
-            pszFullName = msStringConcatenate(pszFullName, ":");
+      pszFullName = msStringConcatenate(pszFullName, ":");
 
-            pszValue = msOWSLookupMetadata(&(lp->metadata), "S", "observedproperty_version");
+      pszValue = msOWSLookupMetadata(&(lp->metadata), "S", "observedproperty_version");
 
-            if (pszValue)
-              pszTmpVal = msStrdup(pszValue);
-            else 
-              pszTmpVal = msStrdup("1");
+      if (pszValue)
+        pszTmpVal = msStrdup(pszValue);
+      else
+        pszTmpVal = msStrdup("1");
 
-            pszFullName = msStringConcatenate(pszFullName, pszTmpVal);
+      pszFullName = msStringConcatenate(pszFullName, pszTmpVal);
 
-            free(pszTmpVal);
+      free(pszTmpVal);
 
-            pszFullName = msStringConcatenate(pszFullName, ":");
+      pszFullName = msStringConcatenate(pszFullName, ":");
 
-            snprintf(szTmp, sizeof(szTmp), "%s_alias", lp->items[i]);
-            pszValue = msOWSLookupMetadata(&(lp->metadata), "S", szTmp);
+      snprintf(szTmp, sizeof(szTmp), "%s_alias", lp->items[i]);
+      pszValue = msOWSLookupMetadata(&(lp->metadata), "S", szTmp);
 
-            if (pszValue)
-              pszTmpVal = msStrdup(pszValue);
-            else
-              pszTmpVal = msStrdup(lp->items[i]);
+      if (pszValue)
+        pszTmpVal = msStrdup(pszValue);
+      else
+        pszTmpVal = msStrdup(lp->items[i]);
 
-            pszFullName = msStringConcatenate(pszFullName, pszTmpVal);
+      pszFullName = msStringConcatenate(pszFullName, pszTmpVal);
 
-            psNode = xmlNewChild(psCompNode, psNsSwe, BAD_CAST "component", NULL);
+      psNode = xmlNewChild(psCompNode, psNsSwe, BAD_CAST "component", NULL);
 
-            xmlNewNsProp(psNode, psNsXLink, BAD_CAST "href", BAD_CAST pszFullName);
-            free(pszFullName);
-            free(pszTmpVal);
-            j++;
-        }
-        pszTmpVal = msIntToString(j); 
-        xmlNewNsProp(psCompNode, NULL, BAD_CAST "dimension", BAD_CAST pszTmpVal);
-        free(pszTmpVal);
-    }	
+      xmlNewNsProp(psNode, psNsXLink, BAD_CAST "href", BAD_CAST pszFullName);
+      free(pszFullName);
+      free(pszTmpVal);
+      j++;
+    }
+    pszTmpVal = msIntToString(j);
+    xmlNewNsProp(psCompNode, NULL, BAD_CAST "dimension", BAD_CAST pszTmpVal);
+    free(pszTmpVal);
+  }
 }
-        
+
 /************************************************************************/
 /*                           msSOSAddGeometryNode                       */
 /*                                                                      */
@@ -371,184 +359,164 @@ void msSOSAddPropertyNode(xmlNsPtr psNsSwe, xmlNsPtr psNsXLink, xmlNodePtr psPar
 /*      from gmlWriteGeometry_GML2. Should be merged at one point if    */
 /*      possible.                                                       */
 /************************************************************************/
-void  msSOSAddGeometryNode(xmlNsPtr psNsGml, xmlNsPtr psNsMs, xmlNodePtr psParent, mapObj *map, layerObj *lp, shapeObj *psShape, 
+void  msSOSAddGeometryNode(xmlNsPtr psNsGml, xmlNsPtr psNsMs, xmlNodePtr psParent, mapObj *map, layerObj *lp, shapeObj *psShape,
                            const char *pszEpsg)
 {
-    char *pszTmp = NULL;
-    int i,j = 0;
-    xmlNodePtr psPointNode, psNode, psLineNode, psPolygonNode;
-    int *panOuterList = NULL, *panInnerList = NULL;
-
-    if (psParent && psShape)
-    {
-      if (msProjectionsDiffer(&map->projection, &lp->projection) == MS_TRUE) 
-      {
-        msProjectShape(&lp->projection, &map->projection, psShape);
-        pszEpsg = msOWSGetEPSGProj(&(map->projection), &(lp->metadata), "SO", MS_TRUE);
-      }
-        switch(psShape->type) 
-        {
-            case(MS_SHAPE_POINT):
-              psNode = xmlNewChild(psParent, NULL, BAD_CAST "msGeometry", NULL);
-              xmlSetNs(psNode, psNsMs);
-              if (psShape->line[0].numpoints > 1)
-              {
-                  psPointNode = xmlNewChild(psNode, NULL, BAD_CAST "MultiPoint", NULL);
-                  xmlSetNs(psPointNode, psNsGml);
-                   
-                  if (pszEpsg)
-                    xmlNewProp(psPointNode, BAD_CAST "srsName", BAD_CAST pszEpsg);
-              }
-              else
-                psPointNode= psNode;
-
-              /*add all points */
-              for(i=0; i<psShape->line[0].numpoints; i++)
-              {
-                  psNode = xmlAddChild(psPointNode, msGML3Point(psNsGml, pszEpsg, NULL, psShape->line[0].point[i].x, psShape->line[0].point[i].y));
-              }
-              break;
-              
-            case(MS_SHAPE_LINE):
-              psNode = xmlNewChild(psParent, NULL, BAD_CAST "msGeometry", NULL);
-              xmlSetNs(psNode,xmlNewNs(psNode, NULL,  NULL));
-              if (psShape->numlines > 1)
-              {
-                  psLineNode = xmlNewChild(psNode, NULL, BAD_CAST "MultiLineString", NULL);
-                  xmlSetNs(psLineNode,xmlNewNs(psLineNode, 
-                                               BAD_CAST "http://www.opengis.net/gml",  
-                                               BAD_CAST "gml"));
-                   
-                  if (pszEpsg)
-                    xmlNewProp(psLineNode, BAD_CAST "srsName", BAD_CAST pszEpsg);
-              }
-              else
-                psLineNode= psNode;
-
-              for(i=0; i<psShape->numlines; i++)
-              {
-                  if (psShape->numlines > 1)
-                  {
-                      psNode = xmlNewChild(psLineNode, NULL, BAD_CAST "lineStringMember", NULL);
-                      xmlSetNs(psNode,xmlNewNs(psNode, 
-                                               BAD_CAST "http://www.opengis.net/gml",  
-                                               BAD_CAST "gml"));
-                      psNode = xmlNewChild(psNode, NULL, BAD_CAST "LineString", NULL);
-                      xmlSetNs(psNode,xmlNewNs(psNode, 
-                                               BAD_CAST "http://www.opengis.net/gml",  
-                                               BAD_CAST "gml"));
-                  }
-                  else
-                  {
-                      psNode = xmlNewChild(psLineNode, NULL, BAD_CAST "LineString", NULL);
-                      xmlSetNs(psNode,xmlNewNs(psNode, 
-                                               BAD_CAST "http://www.opengis.net/gml",  
-                                               BAD_CAST "gml"));
-                  }
-                  if (pszEpsg)
-                    xmlNewProp(psNode, BAD_CAST "srsName", BAD_CAST pszEpsg);
-
-                  pszTmp = NULL;
-                  for(j=0; j<psShape->line[i].numpoints; j++)
-                  {
-                      pszTmp = msStringConcatenate(pszTmp, 
-                                           msDoubleToString(psShape->line[i].point[j].x, MS_TRUE));
-                      pszTmp = msStringConcatenate(pszTmp, ",");
-                      pszTmp = msStringConcatenate(pszTmp, 
-                                           msDoubleToString(psShape->line[i].point[j].y, MS_TRUE));
-                      pszTmp = msStringConcatenate(pszTmp, " ");
-                  }
-                  psNode = xmlNewChild(psNode, NULL, BAD_CAST "coordinates", BAD_CAST pszTmp);
-                  xmlSetNs(psNode,xmlNewNs(psNode, BAD_CAST "http://www.opengis.net/gml", BAD_CAST "gml"));
-                  free(pszTmp);
-              }
-
-              break;
-
-            case(MS_SHAPE_POLYGON):
-              psNode = xmlNewChild(psParent, NULL, BAD_CAST "msGeometry", NULL);
-              xmlSetNs(psNode,xmlNewNs(psNode, NULL,  NULL));
-              if (psShape->numlines > 1)
-              {
-                  psPolygonNode = xmlNewChild(psNode, NULL, BAD_CAST "MultiPolygon", NULL);
-                  xmlSetNs(psPolygonNode,
-                           xmlNewNs(psPolygonNode, BAD_CAST "http://www.opengis.net/gml",
-                                    BAD_CAST "gml"));
-                   
-                  if (pszEpsg)
-                    xmlNewProp(psPolygonNode, BAD_CAST "srsName", BAD_CAST pszEpsg);
-              }
-              else
-                psPolygonNode= psNode;
+  char *pszTmp = NULL;
+  int i,j = 0;
+  xmlNodePtr psPointNode, psNode, psLineNode, psPolygonNode;
+  int *panOuterList = NULL, *panInnerList = NULL;
+
+  if (psParent && psShape) {
+    if (msProjectionsDiffer(&map->projection, &lp->projection) == MS_TRUE) {
+      msProjectShape(&lp->projection, &map->projection, psShape);
+      pszEpsg = msOWSGetEPSGProj(&(map->projection), &(lp->metadata), "SO", MS_TRUE);
+    }
+    switch(psShape->type) {
+      case(MS_SHAPE_POINT):
+        psNode = xmlNewChild(psParent, NULL, BAD_CAST "msGeometry", NULL);
+        xmlSetNs(psNode, psNsMs);
+        if (psShape->line[0].numpoints > 1) {
+          psPointNode = xmlNewChild(psNode, NULL, BAD_CAST "MultiPoint", NULL);
+          xmlSetNs(psPointNode, psNsGml);
+
+          if (pszEpsg)
+            xmlNewProp(psPointNode, BAD_CAST "srsName", BAD_CAST pszEpsg);
+        } else
+          psPointNode= psNode;
+
+        /*add all points */
+        for(i=0; i<psShape->line[0].numpoints; i++) {
+          psNode = xmlAddChild(psPointNode, msGML3Point(psNsGml, pszEpsg, NULL, psShape->line[0].point[i].x, psShape->line[0].point[i].y));
+        }
+        break;
+
+      case(MS_SHAPE_LINE):
+        psNode = xmlNewChild(psParent, NULL, BAD_CAST "msGeometry", NULL);
+        xmlSetNs(psNode,xmlNewNs(psNode, NULL,  NULL));
+        if (psShape->numlines > 1) {
+          psLineNode = xmlNewChild(psNode, NULL, BAD_CAST "MultiLineString", NULL);
+          xmlSetNs(psLineNode,xmlNewNs(psLineNode,
+                                       BAD_CAST "http://www.opengis.net/gml",
+                                       BAD_CAST "gml"));
+
+          if (pszEpsg)
+            xmlNewProp(psLineNode, BAD_CAST "srsName", BAD_CAST pszEpsg);
+        } else
+          psLineNode= psNode;
+
+        for(i=0; i<psShape->numlines; i++) {
+          if (psShape->numlines > 1) {
+            psNode = xmlNewChild(psLineNode, NULL, BAD_CAST "lineStringMember", NULL);
+            xmlSetNs(psNode,xmlNewNs(psNode,
+                                     BAD_CAST "http://www.opengis.net/gml",
+                                     BAD_CAST "gml"));
+            psNode = xmlNewChild(psNode, NULL, BAD_CAST "LineString", NULL);
+            xmlSetNs(psNode,xmlNewNs(psNode,
+                                     BAD_CAST "http://www.opengis.net/gml",
+                                     BAD_CAST "gml"));
+          } else {
+            psNode = xmlNewChild(psLineNode, NULL, BAD_CAST "LineString", NULL);
+            xmlSetNs(psNode,xmlNewNs(psNode,
+                                     BAD_CAST "http://www.opengis.net/gml",
+                                     BAD_CAST "gml"));
+          }
+          if (pszEpsg)
+            xmlNewProp(psNode, BAD_CAST "srsName", BAD_CAST pszEpsg);
+
+          pszTmp = NULL;
+          for(j=0; j<psShape->line[i].numpoints; j++) {
+            pszTmp = msStringConcatenate(pszTmp,
+                                         msDoubleToString(psShape->line[i].point[j].x, MS_TRUE));
+            pszTmp = msStringConcatenate(pszTmp, ",");
+            pszTmp = msStringConcatenate(pszTmp,
+                                         msDoubleToString(psShape->line[i].point[j].y, MS_TRUE));
+            pszTmp = msStringConcatenate(pszTmp, " ");
+          }
+          psNode = xmlNewChild(psNode, NULL, BAD_CAST "coordinates", BAD_CAST pszTmp);
+          xmlSetNs(psNode,xmlNewNs(psNode, BAD_CAST "http://www.opengis.net/gml", BAD_CAST "gml"));
+          free(pszTmp);
+        }
 
-              panOuterList = msGetOuterList(psShape);
-               
-              for(i=0; i<psShape->numlines; i++)
-              {        
-                  if(panOuterList[i] != MS_TRUE)
-                    continue;
+        break;
+
+      case(MS_SHAPE_POLYGON):
+        psNode = xmlNewChild(psParent, NULL, BAD_CAST "msGeometry", NULL);
+        xmlSetNs(psNode,xmlNewNs(psNode, NULL,  NULL));
+        if (psShape->numlines > 1) {
+          psPolygonNode = xmlNewChild(psNode, NULL, BAD_CAST "MultiPolygon", NULL);
+          xmlSetNs(psPolygonNode,
+                   xmlNewNs(psPolygonNode, BAD_CAST "http://www.opengis.net/gml",
+                            BAD_CAST "gml"));
+
+          if (pszEpsg)
+            xmlNewProp(psPolygonNode, BAD_CAST "srsName", BAD_CAST pszEpsg);
+        } else
+          psPolygonNode= psNode;
+
+        panOuterList = msGetOuterList(psShape);
+
+        for(i=0; i<psShape->numlines; i++) {
+          if(panOuterList[i] != MS_TRUE)
+            continue;
+
+          panInnerList = msGetInnerList(psShape, i, panOuterList);
+
+          if (psShape->numlines > 1) {
+            psNode = xmlNewChild(psPolygonNode, NULL, BAD_CAST "polygonMember", NULL);
+            xmlSetNs(psNode,xmlNewNs(psNode, BAD_CAST "http://www.opengis.net/gml",
+                                     BAD_CAST "gml"));
+            psNode = xmlNewChild(psNode, NULL, BAD_CAST "Polygon", NULL);
+            xmlSetNs(psNode,xmlNewNs(psNode, BAD_CAST "http://www.opengis.net/gml",
+                                     BAD_CAST "gml"));
+          } else {
+            psNode = xmlNewChild(psPolygonNode, NULL, BAD_CAST "Polygon", NULL);
+            xmlSetNs(psNode,xmlNewNs(psNode, BAD_CAST "http://www.opengis.net/gml",
+                                     BAD_CAST "gml"));
+          }
+          if (pszEpsg)
+            xmlNewProp(psNode, BAD_CAST "srsName", BAD_CAST pszEpsg);
+
+          psNode = xmlNewChild(psNode, NULL, BAD_CAST "outerBoundaryIs", NULL);
+          xmlSetNs(psNode,xmlNewNs(psNode, BAD_CAST "http://www.opengis.net/gml",
+                                   BAD_CAST "gml"));
+          psNode = xmlNewChild(psNode, NULL, BAD_CAST "LinearRing", NULL);
+          xmlSetNs(psNode,xmlNewNs(psNode, BAD_CAST "http://www.opengis.net/gml",
+                                   BAD_CAST "gml"));
+
+          pszTmp = NULL;
+          for(j=0; j<psShape->line[i].numpoints; j++) {
+
+            pszTmp =
+              msStringConcatenate(pszTmp,
+                                  msDoubleToString(psShape->line[i].point[j].x, MS_TRUE));
+            pszTmp = msStringConcatenate(pszTmp, ",");
+            pszTmp =
+              msStringConcatenate(pszTmp,
+                                  msDoubleToString(psShape->line[i].point[j].y, MS_TRUE));
+            pszTmp = msStringConcatenate(pszTmp, " ");
+          }
+          psNode = xmlNewChild(psNode, NULL, BAD_CAST "coordinates", BAD_CAST pszTmp);
+          xmlSetNs(psNode,xmlNewNs(psNode,
+                                   BAD_CAST "http://www.opengis.net/gml",
+                                   BAD_CAST "gml"));
+          free(pszTmp);
+
+          if (panInnerList)
+            free(panInnerList);
+        }
 
-                  panInnerList = msGetInnerList(psShape, i, panOuterList);
+        if (panOuterList)
+          free(panOuterList);
 
-                  if (psShape->numlines > 1)
-                  {
-                      psNode = xmlNewChild(psPolygonNode, NULL, BAD_CAST "polygonMember", NULL);
-                      xmlSetNs(psNode,xmlNewNs(psNode, BAD_CAST "http://www.opengis.net/gml",  
-                                               BAD_CAST "gml"));
-                      psNode = xmlNewChild(psNode, NULL, BAD_CAST "Polygon", NULL);
-                      xmlSetNs(psNode,xmlNewNs(psNode, BAD_CAST "http://www.opengis.net/gml",  
-                                               BAD_CAST "gml"));
-                  }
-                  else
-                  {
-                      psNode = xmlNewChild(psPolygonNode, NULL, BAD_CAST "Polygon", NULL);
-                      xmlSetNs(psNode,xmlNewNs(psNode, BAD_CAST "http://www.opengis.net/gml",  
-                                               BAD_CAST "gml"));
-                  }
-                  if (pszEpsg)
-                    xmlNewProp(psNode, BAD_CAST "srsName", BAD_CAST pszEpsg);
-
-                  psNode = xmlNewChild(psNode, NULL, BAD_CAST "outerBoundaryIs", NULL);
-                  xmlSetNs(psNode,xmlNewNs(psNode, BAD_CAST "http://www.opengis.net/gml",  
-                                           BAD_CAST "gml"));
-                  psNode = xmlNewChild(psNode, NULL, BAD_CAST "LinearRing", NULL);
-                  xmlSetNs(psNode,xmlNewNs(psNode, BAD_CAST "http://www.opengis.net/gml",  
-                                           BAD_CAST "gml"));
-                   
-                  pszTmp = NULL;
-                  for(j=0; j<psShape->line[i].numpoints; j++)
-                  {
-  
-                      pszTmp = 
-                        msStringConcatenate(pszTmp, 
-                                    msDoubleToString(psShape->line[i].point[j].x, MS_TRUE));
-                      pszTmp = msStringConcatenate(pszTmp, ",");
-                      pszTmp = 
-                        msStringConcatenate(pszTmp, 
-                                    msDoubleToString(psShape->line[i].point[j].y, MS_TRUE));
-                      pszTmp = msStringConcatenate(pszTmp, " ");
-                  }
-                  psNode = xmlNewChild(psNode, NULL, BAD_CAST "coordinates", BAD_CAST pszTmp);
-                  xmlSetNs(psNode,xmlNewNs(psNode, 
-                                           BAD_CAST "http://www.opengis.net/gml", 
-                                           BAD_CAST "gml"));
-                  free(pszTmp);
-
-                  if (panInnerList)
-                    free(panInnerList);
-              }
+        break;
 
-              if (panOuterList)
-                free(panOuterList);
+      default:
+        break;
+    }
 
-              break;
+  }
 
-            default:
-              break;
-        }
-                   
-    }   
-      
 }
 
 /************************************************************************/
@@ -559,104 +527,100 @@ void  msSOSAddGeometryNode(xmlNsPtr psNsGml, xmlNsPtr psNsMs, xmlNodePtr psParen
 /************************************************************************/
 void msSOSAddDataBlockDefinition(xmlNsPtr psNsSwe, xmlNodePtr psParent, layerObj *lp)
 {
-    xmlNodePtr psNode, psRecordNode, psCompNode, psSubNode, psEncNode;
-    const char *pszDefinition = NULL, *pszUom=NULL, *pszValue=NULL, *pszName=NULL;
-    char szTmp[100];
-    int i=0;
-    char *pszTokenValue = NULL;
-    char *pszBlockValue = NULL;
-    const char *pszBlockSep=NULL, *pszTokenSep=NULL;
-
-    if (psParent)
-    {
-        psNode = xmlNewChild(psParent, NULL, BAD_CAST "DataBlockDefinition", NULL);
-        xmlSetNs(psNode, psNsSwe);
-
-/* -------------------------------------------------------------------- */
-/*      Add components.                                                 */
-/* -------------------------------------------------------------------- */
-        psCompNode = xmlNewChild(psNode, NULL, BAD_CAST "components", NULL);
-        psEncNode = xmlNewChild(psNode, NULL, BAD_CAST "encoding", NULL);
-        psRecordNode = xmlNewChild(psCompNode, NULL, BAD_CAST "DataRecord", NULL);
-
-        /*always add a time field if timeitem is defined*/      
-        if (msOWSLookupMetadata(&(lp->metadata), "SO", "timeitem"))
-        {
-            psNode = xmlNewChild(psRecordNode, NULL, BAD_CAST "field", NULL);
-            xmlNewNsProp(psNode, NULL, BAD_CAST "name", BAD_CAST "time");
-            psNode = xmlNewChild(psNode, NULL, BAD_CAST "Time", NULL);
-            xmlNewNsProp(psNode, NULL, BAD_CAST "definition", BAD_CAST "urn:ogc:phenomenon:time:iso8601");
-        }
-        /*add all other fields*/
-        /*assuming that the layer is open */       
-        for(i=0; i<lp->numitems; i++) 
-        {
-            snprintf(szTmp, sizeof(szTmp), "%s_alias", lp->items[i]);
-            pszValue = msOWSLookupMetadata(&(lp->metadata), "S", szTmp);
-            if (pszValue)
-            {
-                psNode = xmlNewChild(psRecordNode, NULL, BAD_CAST "field", NULL);
-
-                /* check if there is an alias/full name used */
-                snprintf(szTmp, sizeof(szTmp), "%s_alias", lp->items[i]);
-                pszName = msOWSLookupMetadata(&(lp->metadata), "S", szTmp);
-                if (!pszName)
-                  pszName = lp->items[i];
-
-                xmlNewNsProp(psNode, NULL, BAD_CAST "name", BAD_CAST pszName);
-
-                psNode = xmlNewChild(psNode, NULL, BAD_CAST "Quantity", NULL);
-
-                /* get definition and uom */
-                snprintf(szTmp, sizeof(szTmp), "%s_definition", lp->items[i]);
-                pszDefinition =  msOWSLookupMetadata(&(lp->metadata), "S", szTmp);
-                    
-                if (pszDefinition == NULL)
-                  pszDefinition = "urn:ogc:object:definition";
-
-                xmlNewNsProp(psNode, NULL, BAD_CAST "definition", BAD_CAST pszDefinition);
-
-                snprintf(szTmp, sizeof(szTmp), "%s_uom", lp->items[i]);
-                pszUom =  msOWSLookupMetadata(&(lp->metadata), "S", szTmp);
-
-                if (pszUom == NULL)
-                  pszUom = "urn:ogc:object:uom";
-
-                psNode = xmlNewChild(psNode, NULL, BAD_CAST "uom", NULL);
-                xmlNewNsProp(psNode, NULL, BAD_CAST "code", BAD_CAST pszUom);
-                         
-            }
-        }
-            
-/* -------------------------------------------------------------------- */
-/*      Add encoding block.                                             */
-/* -------------------------------------------------------------------- */
-        pszBlockSep = msOWSLookupMetadata(&(lp->map->web.metadata), "S", 
-                                          "encoding_blockSeparator");
-        pszTokenSep = msOWSLookupMetadata(&(lp->map->web.metadata), "S", 
-                                          "encoding_tokenSeparator");
-
-        psSubNode = xmlNewChild(psEncNode, NULL, BAD_CAST "TextBlock", NULL);
-
-        if (pszTokenSep)
-          pszTokenValue = msStringConcatenate(pszTokenValue, (char *)pszTokenSep);
-        else
-          pszTokenValue = msStringConcatenate(pszTokenValue, ",");
+  xmlNodePtr psNode, psRecordNode, psCompNode, psSubNode, psEncNode;
+  const char *pszDefinition = NULL, *pszUom=NULL, *pszValue=NULL, *pszName=NULL;
+  char szTmp[100];
+  int i=0;
+  char *pszTokenValue = NULL;
+  char *pszBlockValue = NULL;
+  const char *pszBlockSep=NULL, *pszTokenSep=NULL;
+
+  if (psParent) {
+    psNode = xmlNewChild(psParent, NULL, BAD_CAST "DataBlockDefinition", NULL);
+    xmlSetNs(psNode, psNsSwe);
+
+    /* -------------------------------------------------------------------- */
+    /*      Add components.                                                 */
+    /* -------------------------------------------------------------------- */
+    psCompNode = xmlNewChild(psNode, NULL, BAD_CAST "components", NULL);
+    psEncNode = xmlNewChild(psNode, NULL, BAD_CAST "encoding", NULL);
+    psRecordNode = xmlNewChild(psCompNode, NULL, BAD_CAST "DataRecord", NULL);
+
+    /*always add a time field if timeitem is defined*/
+    if (msOWSLookupMetadata(&(lp->metadata), "SO", "timeitem")) {
+      psNode = xmlNewChild(psRecordNode, NULL, BAD_CAST "field", NULL);
+      xmlNewNsProp(psNode, NULL, BAD_CAST "name", BAD_CAST "time");
+      psNode = xmlNewChild(psNode, NULL, BAD_CAST "Time", NULL);
+      xmlNewNsProp(psNode, NULL, BAD_CAST "definition", BAD_CAST "urn:ogc:phenomenon:time:iso8601");
+    }
+    /*add all other fields*/
+    /*assuming that the layer is open */
+    for(i=0; i<lp->numitems; i++) {
+      snprintf(szTmp, sizeof(szTmp), "%s_alias", lp->items[i]);
+      pszValue = msOWSLookupMetadata(&(lp->metadata), "S", szTmp);
+      if (pszValue) {
+        psNode = xmlNewChild(psRecordNode, NULL, BAD_CAST "field", NULL);
 
-        xmlNewNsProp(psSubNode, NULL, BAD_CAST "tokenSeparator", BAD_CAST pszTokenValue);
+        /* check if there is an alias/full name used */
+        snprintf(szTmp, sizeof(szTmp), "%s_alias", lp->items[i]);
+        pszName = msOWSLookupMetadata(&(lp->metadata), "S", szTmp);
+        if (!pszName)
+          pszName = lp->items[i];
 
-        if (pszBlockSep)
-          pszBlockValue = msStringConcatenate(pszBlockValue, (char *)pszBlockSep);
-        else
-          pszBlockValue = msStringConcatenate(pszBlockValue, "\n");
+        xmlNewNsProp(psNode, NULL, BAD_CAST "name", BAD_CAST pszName);
+
+        psNode = xmlNewChild(psNode, NULL, BAD_CAST "Quantity", NULL);
 
-        xmlNewNsProp(psSubNode, NULL, BAD_CAST "blockSeparator", BAD_CAST pszBlockValue);
+        /* get definition and uom */
+        snprintf(szTmp, sizeof(szTmp), "%s_definition", lp->items[i]);
+        pszDefinition =  msOWSLookupMetadata(&(lp->metadata), "S", szTmp);
 
-        xmlNewNsProp(psSubNode, NULL, BAD_CAST "decimalSeparator", BAD_CAST ".");
+        if (pszDefinition == NULL)
+          pszDefinition = "urn:ogc:object:definition";
 
-        msFree(pszTokenValue);
-        msFree(pszBlockValue);
-    }   
+        xmlNewNsProp(psNode, NULL, BAD_CAST "definition", BAD_CAST pszDefinition);
+
+        snprintf(szTmp, sizeof(szTmp), "%s_uom", lp->items[i]);
+        pszUom =  msOWSLookupMetadata(&(lp->metadata), "S", szTmp);
+
+        if (pszUom == NULL)
+          pszUom = "urn:ogc:object:uom";
+
+        psNode = xmlNewChild(psNode, NULL, BAD_CAST "uom", NULL);
+        xmlNewNsProp(psNode, NULL, BAD_CAST "code", BAD_CAST pszUom);
+
+      }
+    }
+
+    /* -------------------------------------------------------------------- */
+    /*      Add encoding block.                                             */
+    /* -------------------------------------------------------------------- */
+    pszBlockSep = msOWSLookupMetadata(&(lp->map->web.metadata), "S",
+                                      "encoding_blockSeparator");
+    pszTokenSep = msOWSLookupMetadata(&(lp->map->web.metadata), "S",
+                                      "encoding_tokenSeparator");
+
+    psSubNode = xmlNewChild(psEncNode, NULL, BAD_CAST "TextBlock", NULL);
+
+    if (pszTokenSep)
+      pszTokenValue = msStringConcatenate(pszTokenValue, (char *)pszTokenSep);
+    else
+      pszTokenValue = msStringConcatenate(pszTokenValue, ",");
+
+    xmlNewNsProp(psSubNode, NULL, BAD_CAST "tokenSeparator", BAD_CAST pszTokenValue);
+
+    if (pszBlockSep)
+      pszBlockValue = msStringConcatenate(pszBlockValue, (char *)pszBlockSep);
+    else
+      pszBlockValue = msStringConcatenate(pszBlockValue, "\n");
+
+    xmlNewNsProp(psSubNode, NULL, BAD_CAST "blockSeparator", BAD_CAST pszBlockValue);
+
+    xmlNewNsProp(psSubNode, NULL, BAD_CAST "decimalSeparator", BAD_CAST ".");
+
+    msFree(pszTokenValue);
+    msFree(pszBlockValue);
+  }
 }
 
 /************************************************************************/
@@ -666,250 +630,230 @@ void msSOSAddDataBlockDefinition(xmlNsPtr psNsSwe, xmlNodePtr psParent, layerObj
 /*      Assuming that the layer is opened and msLayerGetItems is        */
 /*      called on it.                                                   */
 /************************************************************************/
-void msSOSAddMemberNode(xmlNsPtr psNsGml, xmlNsPtr psNsOm, xmlNsPtr psNsSwe, xmlNsPtr psNsXLink, xmlNsPtr psNsMs, xmlNodePtr psParent, mapObj *map, layerObj *lp, 
+void msSOSAddMemberNode(xmlNsPtr psNsGml, xmlNsPtr psNsOm, xmlNsPtr psNsSwe, xmlNsPtr psNsXLink, xmlNsPtr psNsMs, xmlNodePtr psParent, mapObj *map, layerObj *lp,
                         int iFeatureId, const char *script_url, const char *opLayerName)
 {
-    xmlNodePtr psObsNode, psNode, psSubNode, psLayerNode = NULL;
-    const char *pszEpsg = NULL, *pszValue = NULL;
-    int status,i,j;
-    shapeObj sShape;
-    char szTmp[256];
-    layerObj *lpfirst = NULL;
-    const char *pszTimeField = NULL;
-    char *pszTmp = NULL;
-    char *pszOid = NULL;
-    char *pszTime = NULL;
-    char *pszValueShape = NULL;
-    const char *pszFeatureId  = NULL;
-
-    if (psParent)
-    {
-        msInitShape(&sShape);
-    
-        status = msLayerGetShape(lp, &sShape, &(lp->resultcache->results[iFeatureId]));
-        if(status != MS_SUCCESS) {
-          xmlFreeNs(psNsOm);
-          return;
-        }
+  xmlNodePtr psObsNode, psNode, psLayerNode = NULL;
+  const char *pszEpsg = NULL, *pszValue = NULL;
+  int status,i,j;
+  shapeObj sShape;
+  char szTmp[256];
+  layerObj *lpfirst = NULL;
+  const char *pszTimeField = NULL;
+  char *pszTmp = NULL;
+  char *pszOid = NULL;
+  char *pszTime = NULL;
+  char *pszValueShape = NULL;
+  const char *pszFeatureId  = NULL;
 
-        psNode = xmlNewChild(psParent, NULL, BAD_CAST "member", NULL);
-        
-        psObsNode = xmlNewChild(psNode, NULL, BAD_CAST "Observation", BAD_CAST pszValue);
+  if (psParent) {
+    msInitShape(&sShape);
 
-        pszFeatureId = msOWSLookupMetadata(&(lp->metadata), "OSG", "featureid");
+    status = msLayerGetShape(lp, &sShape, &(lp->resultcache->results[iFeatureId]));
+    if(status != MS_SUCCESS) {
+      xmlFreeNs(psNsOm);
+      return;
+    }
 
-        if(pszFeatureId && msLayerGetItems(lp) == MS_SUCCESS)
-        { /* find the featureid amongst the items for this layer */
-            for(j=0; j<lp->numitems; j++) {
-                if(strcasecmp(lp->items[j], pszFeatureId) == 0) { /* found it  */
-                    break;
-                }
-            }
-            if (j<lp->numitems) {
-                pszOid = msStringConcatenate(pszOid, "o_");
-                pszOid = msStringConcatenate(pszOid, sShape.values[j]);
-                xmlNewNsProp(psObsNode, psNsGml, BAD_CAST "id", BAD_CAST pszOid);
-            }
+    psNode = xmlNewChild(psParent, NULL, BAD_CAST "member", NULL);
+
+    psObsNode = xmlNewChild(psNode, NULL, BAD_CAST "Observation", BAD_CAST pszValue);
+
+    pszFeatureId = msOWSLookupMetadata(&(lp->metadata), "OSG", "featureid");
+
+    if(pszFeatureId && msLayerGetItems(lp) == MS_SUCCESS) {
+      /* find the featureid amongst the items for this layer */
+      for(j=0; j<lp->numitems; j++) {
+        if(strcasecmp(lp->items[j], pszFeatureId) == 0) { /* found it  */
+          break;
         }
+      }
+      if (j<lp->numitems) {
+        pszOid = msStringConcatenate(pszOid, "o_");
+        pszOid = msStringConcatenate(pszOid, sShape.values[j]);
+        xmlNewNsProp(psObsNode, psNsGml, BAD_CAST "id", BAD_CAST pszOid);
+      }
+    }
 
-        /* order of elements is time, location, procedure, observedproperty
-         featureofinterest, result */
-
-        /* time*/
-        pszTimeField =  msOWSLookupMetadata(&(lp->metadata), "SO",
-                                            "timeitem");
-        if (pszTimeField && sShape.values)
-        {
-            for(i=0; i<lp->numitems; i++) 
-            {
-                if (strcasecmp(lp->items[i], pszTimeField) == 0)
-                {
-                    if (sShape.values[i] && strlen(sShape.values[i]) > 0)
-                    {
-                        pszTime = msStringConcatenate(pszTime, sShape.values[i]);
-                        psNode = xmlNewChild(psObsNode, psNsOm, BAD_CAST "samplingTime", NULL);
-                        psSubNode = xmlAddChild(psNode, msGML3TimeInstant(psNsGml, pszTime));
-                        msFree(pszTime);
-                    }
-                    break;
-                }
-            }
+    /* order of elements is time, location, procedure, observedproperty
+     featureofinterest, result */
+
+    /* time*/
+    pszTimeField =  msOWSLookupMetadata(&(lp->metadata), "SO",
+                                        "timeitem");
+    if (pszTimeField && sShape.values) {
+      for(i=0; i<lp->numitems; i++) {
+        if (strcasecmp(lp->items[i], pszTimeField) == 0) {
+          if (sShape.values[i] && strlen(sShape.values[i]) > 0) {
+            pszTime = msStringConcatenate(pszTime, sShape.values[i]);
+            psNode = xmlNewChild(psObsNode, psNsOm, BAD_CAST "samplingTime", NULL);
+            xmlAddChild(psNode, msGML3TimeInstant(psNsGml, pszTime));
+            msFree(pszTime);
+          }
+          break;
         }
-        /*TODO add location*/
-
-        /*procedure*/
-        /* if a procedure_item is defined, we should extract the value for the
-           attributes. If not dump what is found in the procedure metadata bug 2054*/
-        if ((pszValue =  msOWSLookupMetadata(&(lp->metadata), "S", "procedure_item")))
-        {
-            lpfirst = msSOSGetFirstLayerForOffering(map, 
-                                                    msOWSLookupMetadata(&(lp->metadata), "S", 
-                                                                        "offering_id"), 
-                                                    msOWSLookupMetadata(&(lp->metadata), "S", 
-                                                                        "observedproperty_id"));
-
-            if (lp != lpfirst)
-              status = msLayerOpen(lpfirst);
-            if (status == MS_SUCCESS && msLayerGetItems(lpfirst) == MS_SUCCESS)
-            {           
-                for(i=0; i<lpfirst->numitems; i++) 
-                {
-                    if (strcasecmp(lpfirst->items[i], pszValue) == 0)
-                    {
-                        break;
-                    }
-                }
-                if (i < lpfirst->numitems)
-                {
-                    snprintf(szTmp, sizeof(szTmp), "%s", "urn:ogc:def:procedure:");
-                    pszTmp = msStringConcatenate(pszTmp, szTmp);
-                    pszValueShape = msEncodeHTMLEntities(sShape.values[i]);
-                    pszTmp = msStringConcatenate(pszTmp, pszValueShape);
-            
-                        psNode =  xmlNewChild(psObsNode, NULL, BAD_CAST "procedure", NULL);
-                        xmlNewNsProp(psNode, psNsXLink, BAD_CAST "href", BAD_CAST pszTmp);
-                        msFree(pszTmp);
-                        pszTmp = NULL;
-                        msFree(pszValueShape);
-                }
-                /*else should we generate a warning !*/
-                if (lp != lpfirst)
-                  msLayerClose(lpfirst);
-            }
-                
+      }
+    }
+    /*TODO add location*/
+
+    /*procedure*/
+    /* if a procedure_item is defined, we should extract the value for the
+       attributes. If not dump what is found in the procedure metadata bug 2054*/
+    if ((pszValue =  msOWSLookupMetadata(&(lp->metadata), "S", "procedure_item"))) {
+      lpfirst = msSOSGetFirstLayerForOffering(map,
+                                              msOWSLookupMetadata(&(lp->metadata), "S",
+                                                  "offering_id"),
+                                              msOWSLookupMetadata(&(lp->metadata), "S",
+                                                  "observedproperty_id"));
+
+      if (lp != lpfirst)
+        status = msLayerOpen(lpfirst);
+      if (status == MS_SUCCESS && msLayerGetItems(lpfirst) == MS_SUCCESS) {
+        for(i=0; i<lpfirst->numitems; i++) {
+          if (strcasecmp(lpfirst->items[i], pszValue) == 0) {
+            break;
+          }
         }
-        else if ((pszValue = msOWSLookupMetadata(&(lp->metadata), "S", "procedure")))
-        {
-            if (! msOWSLookupMetadata(&(lp->metadata), "S", "procedure_item"))
-                xmlAddSibling(psNode, xmlNewComment(BAD_CAST "WARNING: Optional metadata \"sos_procedure_item\" missing for sos:procedure.  If you have more than 1 procedures, sos:procedure will output them incorrectly."));
-
-            snprintf(szTmp, sizeof(szTmp), "%s", "urn:ogc:def:procedure:");
-            pszTmp = msStringConcatenate(pszTmp, szTmp);
-            pszTmp = msStringConcatenate(pszTmp, (char *)pszValue);
-            
-            psNode =  xmlNewChild(psObsNode, NULL, BAD_CAST "procedure", NULL);
-            xmlNewNsProp(psNode, psNsXLink, BAD_CAST "href", BAD_CAST pszTmp);
-            msFree(pszTmp);
-            pszTmp = NULL;
+        if (i < lpfirst->numitems) {
+          snprintf(szTmp, sizeof(szTmp), "%s", "urn:ogc:def:procedure:");
+          pszTmp = msStringConcatenate(pszTmp, szTmp);
+          pszValueShape = msEncodeHTMLEntities(sShape.values[i]);
+          pszTmp = msStringConcatenate(pszTmp, pszValueShape);
+
+          psNode =  xmlNewChild(psObsNode, NULL, BAD_CAST "procedure", NULL);
+          xmlNewNsProp(psNode, psNsXLink, BAD_CAST "href", BAD_CAST pszTmp);
+          msFree(pszTmp);
+          pszTmp = NULL;
+          msFree(pszValueShape);
         }
+        /*else should we generate a warning !*/
+        if (lp != lpfirst)
+          msLayerClose(lpfirst);
+      }
+
+    } else if ((pszValue = msOWSLookupMetadata(&(lp->metadata), "S", "procedure"))) {
+      if (! msOWSLookupMetadata(&(lp->metadata), "S", "procedure_item"))
+        xmlAddSibling(psNode, xmlNewComment(BAD_CAST "WARNING: Optional metadata \"sos_procedure_item\" missing for sos:procedure.  If you have more than 1 procedures, sos:procedure will output them incorrectly."));
+
+      snprintf(szTmp, sizeof(szTmp), "%s", "urn:ogc:def:procedure:");
+      pszTmp = msStringConcatenate(pszTmp, szTmp);
+      pszTmp = msStringConcatenate(pszTmp, (char *)pszValue);
+
+      psNode =  xmlNewChild(psObsNode, NULL, BAD_CAST "procedure", NULL);
+      xmlNewNsProp(psNode, psNsXLink, BAD_CAST "href", BAD_CAST pszTmp);
+      msFree(pszTmp);
+      pszTmp = NULL;
+    }
+
+    /*observed property*/
+    pszValue = msOWSLookupMetadata(&(lp->metadata), "S",
+                                   "observedproperty_id");
+    if (pszValue)
+      msSOSAddPropertyNode(psNsSwe, psNsXLink, psObsNode, lp, psNsGml, pszOid);
+    msFree(pszOid);
+    pszOid = NULL;
 
-        /*observed property*/
-        pszValue = msOWSLookupMetadata(&(lp->metadata), "S", 
-                                       "observedproperty_id");
-        if (pszValue)
-            msSOSAddPropertyNode(psNsSwe, psNsXLink, psObsNode, lp, psNsGml, pszOid);
-        msFree(pszOid);
-        pszOid = NULL;
+    /*TODO add featureofinterest*/
 
-        /*TODO add featureofinterest*/
+    pszTmp = msStringConcatenate(pszTmp, (char *) script_url);
+    pszTmp = msStringConcatenate(pszTmp, "service=WFS&version=1.1.0&request=DescribeFeatureType&typename=");
+    pszTmp = msStringConcatenate(pszTmp, (char *) opLayerName);
 
-        pszTmp = msStringConcatenate(pszTmp, (char *) script_url);
-        pszTmp = msStringConcatenate(pszTmp, "service=WFS&version=1.1.0&request=DescribeFeatureType&typename=");
-        pszTmp = msStringConcatenate(pszTmp, (char *) opLayerName);
+    psNode =  xmlNewChild(psObsNode, psNsOm, BAD_CAST "featureOfInterest", NULL);
+    xmlNewNsProp(psNode, psNsXLink, BAD_CAST "href", BAD_CAST pszTmp);
 
-        psNode =  xmlNewChild(psObsNode, psNsOm, BAD_CAST "featureOfInterest", NULL);
-        xmlNewNsProp(psNode, psNsXLink, BAD_CAST "href", BAD_CAST pszTmp);
+    msFree(pszTmp);
+    pszTmp=NULL;
 
-        msFree(pszTmp);
-        pszTmp=NULL;
+    /* add result : gml:featureMember of all selected elements */
+    psNode = xmlNewChild(psObsNode, NULL, BAD_CAST "result", NULL);
+
+    /*TODO should we add soemwhere the units of the value :
+      <om:result uom="units.xml#cm">29.00</om:result> */
 
-        /* add result : gml:featureMember of all selected elements */
-        psNode = xmlNewChild(psObsNode, NULL, BAD_CAST "result", NULL);
 
-        /*TODO should we add soemwhere the units of the value :
-          <om:result uom="units.xml#cm">29.00</om:result> */
 
-        
-        
 #ifdef USE_PROJ
-        if(msProjectionsDiffer(&(lp->projection), &(map->projection)))
-          msProjectShape(&lp->projection, &lp->projection, &sShape);
+    if(msProjectionsDiffer(&(lp->projection), &(map->projection)))
+      msProjectShape(&lp->projection, &lp->projection, &sShape);
 #endif
-        psNode = xmlNewChild(psNode, psNsGml, BAD_CAST "featureMember", NULL);
-        //xmlSetNs(psNode,xmlNewNs(psNode, BAD_CAST "http://www.opengis.net/gml", BAD_CAST "gml"));
+    psNode = xmlNewChild(psNode, psNsGml, BAD_CAST "featureMember", NULL);
+    /* xmlSetNs(psNode,xmlNewNs(psNode, BAD_CAST "http://www.opengis.net/gml", BAD_CAST "gml")); */
+
+    /*TODO : add namespaces like wfs " ms and a url to mapserve ? */
+    psLayerNode = xmlNewChild(psNode, psNsMs, BAD_CAST lp->name, NULL);
 
-        /*TODO : add namespaces like wfs " ms and a url to mapserve ? */
-        psLayerNode = xmlNewChild(psNode, psNsMs, BAD_CAST lp->name, NULL);
+    /* fetch gml:id */
 
-        /* fetch gml:id */
+    pszFeatureId = msOWSLookupMetadata(&(lp->metadata), "OSG", "featureid");
 
-        pszFeatureId = msOWSLookupMetadata(&(lp->metadata), "OSG", "featureid");
+    if(pszFeatureId && msLayerOpen(lp) == MS_SUCCESS && msLayerGetItems(lp) == MS_SUCCESS)
 
-        if(pszFeatureId && msLayerOpen(lp) == MS_SUCCESS && msLayerGetItems(lp) == MS_SUCCESS)
+      xmlSetNs(psLayerNode,psNsMs);
 
-        xmlSetNs(psLayerNode,psNsMs);
-        
-        /*bbox*/
+    /*bbox*/
 #ifdef USE_PROJ
-        pszEpsg = msOWSGetEPSGProj(&(map->projection), &(lp->metadata), "SO", MS_TRUE);
-        if (!pszEpsg)
-          pszEpsg = msOWSGetEPSGProj(&(lp->projection), &(lp->metadata), "SO", MS_TRUE);
-
-        if (msProjectionsDiffer(&map->projection, &lp->projection) == MS_TRUE)
-              msProjectRect(&lp->projection, &map->projection, &sShape.bounds);
-#endif        
-        psNode = xmlAddChild(psLayerNode, msGML3BoundedBy(psNsGml, sShape.bounds.minx, sShape.bounds.miny, sShape.bounds.maxx, sShape.bounds.maxy, pszEpsg));
-
-        /*geometry*/
-        msSOSAddGeometryNode(psNsGml, psNsMs, psLayerNode, map, lp, &sShape, pszEpsg);
-
-        /*attributes */
-        /* TODO only output attributes where there is a sos_%s_alias (to be discussed)*/
-        /* the first layer is the one that has to have all the metadata defined */
-        lpfirst = msSOSGetFirstLayerForOffering(map, 
-                                                msOWSLookupMetadata(&(lp->metadata), "S", 
-                                                                    "offering_id"), 
-                                                msOWSLookupMetadata(&(lp->metadata), "S", 
-                                                                    "observedproperty_id"));
-
-        if (lpfirst && msLayerOpen(lpfirst) == MS_SUCCESS && 
-            msLayerGetItems(lpfirst) == MS_SUCCESS)
-        {
-            for(i=0; i<lpfirst->numitems; i++) 
-            {
-                snprintf(szTmp, sizeof(szTmp), "%s_alias", lpfirst->items[i]);
-                pszValue = msOWSLookupMetadata(&(lpfirst->metadata), "S", szTmp);
-                if (pszValue)
-                {
-                    for (j=0; j<lp->numitems; j++)
-                    {
-                        if (strcasecmp(lpfirst->items[i],  lpfirst->items[j]) == 0)
-                        {
-                            /*if there is an alias used, use it to output the
-                              parameter name : eg "sos_AMMON_DIS_alias" "Amonia"  */
-                            snprintf(szTmp, sizeof(szTmp), "%s_alias", lpfirst->items[i]);
-                            pszValue = msOWSLookupMetadata(&(lpfirst->metadata), "S", szTmp);
-                            pszValueShape = msEncodeHTMLEntities(sShape.values[j]);
-                            
-                            if (pszValue)
-                            {
-                              pszTmp = msEncodeHTMLEntities(pszValue);
-                              psNode = xmlNewChild(psLayerNode, psNsMs, BAD_CAST pszValue, 
-                                                   BAD_CAST pszValueShape);
-                              free(pszTmp);
-                            } 
-                            else
-                            {
-                                pszTmp = msEncodeHTMLEntities(lpfirst->items[i]);
-                                psNode = xmlNewChild(psLayerNode, psNsMs, 
-                                                     BAD_CAST lpfirst->items[i], 
-                                                     BAD_CAST pszValueShape);
-                              free(pszTmp);
-                            } 
-
-                            free(pszValueShape);
-                            xmlSetNs(psNode,psNsMs);
-                            break;
-                        }
-                    }
-                }
+    pszEpsg = msOWSGetEPSGProj(&(map->projection), &(lp->metadata), "SO", MS_TRUE);
+    if (!pszEpsg)
+      pszEpsg = msOWSGetEPSGProj(&(lp->projection), &(lp->metadata), "SO", MS_TRUE);
+
+    if (msProjectionsDiffer(&map->projection, &lp->projection) == MS_TRUE)
+      msProjectRect(&lp->projection, &map->projection, &sShape.bounds);
+#endif
+    psNode = xmlAddChild(psLayerNode, msGML3BoundedBy(psNsGml, sShape.bounds.minx, sShape.bounds.miny, sShape.bounds.maxx, sShape.bounds.maxy, pszEpsg));
+
+    /*geometry*/
+    msSOSAddGeometryNode(psNsGml, psNsMs, psLayerNode, map, lp, &sShape, pszEpsg);
+
+    /*attributes */
+    /* TODO only output attributes where there is a sos_%s_alias (to be discussed)*/
+    /* the first layer is the one that has to have all the metadata defined */
+    lpfirst = msSOSGetFirstLayerForOffering(map,
+                                            msOWSLookupMetadata(&(lp->metadata), "S",
+                                                "offering_id"),
+                                            msOWSLookupMetadata(&(lp->metadata), "S",
+                                                "observedproperty_id"));
+
+    if (lpfirst && msLayerOpen(lpfirst) == MS_SUCCESS &&
+        msLayerGetItems(lpfirst) == MS_SUCCESS) {
+      for(i=0; i<lpfirst->numitems; i++) {
+        snprintf(szTmp, sizeof(szTmp), "%s_alias", lpfirst->items[i]);
+        pszValue = msOWSLookupMetadata(&(lpfirst->metadata), "S", szTmp);
+        if (pszValue) {
+          for (j=0; j<lp->numitems; j++) {
+            if (strcasecmp(lpfirst->items[i],  lpfirst->items[j]) == 0) {
+              /*if there is an alias used, use it to output the
+                parameter name : eg "sos_AMMON_DIS_alias" "Amonia"  */
+              snprintf(szTmp, sizeof(szTmp), "%s_alias", lpfirst->items[i]);
+              pszValue = msOWSLookupMetadata(&(lpfirst->metadata), "S", szTmp);
+              pszValueShape = msEncodeHTMLEntities(sShape.values[j]);
+
+              if (pszValue) {
+                pszTmp = msEncodeHTMLEntities(pszValue);
+                psNode = xmlNewChild(psLayerNode, psNsMs, BAD_CAST pszValue,
+                                     BAD_CAST pszValueShape);
+                free(pszTmp);
+              } else {
+                pszTmp = msEncodeHTMLEntities(lpfirst->items[i]);
+                psNode = xmlNewChild(psLayerNode, psNsMs,
+                                     BAD_CAST lpfirst->items[i],
+                                     BAD_CAST pszValueShape);
+                free(pszTmp);
+              }
+
+              free(pszValueShape);
+              xmlSetNs(psNode,psNsMs);
+              break;
             }
-            if (lp->index != lpfirst->index)
-              msLayerClose(lpfirst);
+          }
         }
+      }
+      if (lp->index != lpfirst->index)
+        msLayerClose(lpfirst);
     }
+  }
 
-    msFreeShape(&sShape);
+  msFreeShape(&sShape);
 }
 
 /************************************************************************/
@@ -921,88 +865,77 @@ void msSOSAddMemberNode(xmlNsPtr psNsGml, xmlNsPtr psNsOm, xmlNsPtr psNsSwe, xml
 /************************************************************************/
 char* msSOSReturnMemberResult(layerObj *lp, int iFeatureId, char **ppszProcedure)
 {
-    char *pszFinalValue = NULL;
-    shapeObj sShape;
-    int i, j, status;
-    layerObj *lpfirst;
-    const char *pszTimeField = NULL, *pszValue=NULL, *pszProcedureField=NULL;
-    char *pszValueShape = NULL;
-    char szTmp[100];
-    const char *pszSep=NULL;
-
-    msInitShape(&sShape);
-    status = msLayerGetShape(lp, &sShape, &(lp->resultcache->results[iFeatureId]));
-    if(status != MS_SUCCESS) 
-      return NULL;
-
-    pszTimeField =  msOWSLookupMetadata(&(lp->metadata), "SO", "timeitem");
-    if (pszTimeField && sShape.values)
-    {
-        for(i=0; i<lp->numitems; i++) 
-        {
-            if (strcasecmp(lp->items[i], pszTimeField) == 0)
-            {
-                pszFinalValue = msStringConcatenate(pszFinalValue,  sShape.values[i]);
-                break;
-            }
-        }
+  char *pszFinalValue = NULL;
+  shapeObj sShape;
+  int i, j, status;
+  layerObj *lpfirst;
+  const char *pszTimeField = NULL, *pszValue=NULL, *pszProcedureField=NULL;
+  char *pszValueShape = NULL;
+  char szTmp[100];
+  const char *pszSep=NULL;
+
+  msInitShape(&sShape);
+  status = msLayerGetShape(lp, &sShape, &(lp->resultcache->results[iFeatureId]));
+  if(status != MS_SUCCESS)
+    return NULL;
+
+  pszTimeField =  msOWSLookupMetadata(&(lp->metadata), "SO", "timeitem");
+  if (pszTimeField && sShape.values) {
+    for(i=0; i<lp->numitems; i++) {
+      if (strcasecmp(lp->items[i], pszTimeField) == 0) {
+        pszFinalValue = msStringConcatenate(pszFinalValue,  sShape.values[i]);
+        break;
+      }
     }
-    if (ppszProcedure)
-    {
-        pszProcedureField = msOWSLookupMetadata(&(lp->metadata), "S", "procedure_item");
-        for(i=0; i<lp->numitems; i++) 
-        {
-            if (strcasecmp(lp->items[i], pszProcedureField) == 0)
-            {
-                (*ppszProcedure) = msStrdup( sShape.values[i]);
-                break;
-            }
-        }
+  }
+  if (ppszProcedure) {
+    pszProcedureField = msOWSLookupMetadata(&(lp->metadata), "S", "procedure_item");
+    for(i=0; i<lp->numitems; i++) {
+      if (strcasecmp(lp->items[i], pszProcedureField) == 0) {
+        (*ppszProcedure) = msStrdup( sShape.values[i]);
+        break;
+      }
     }
+  }
 
-    /* the first layer is the one that has to have all the metadata defined */
-    lpfirst = msSOSGetFirstLayerForOffering(lp->map, 
-                                            msOWSLookupMetadata(&(lp->metadata), "S", 
-                                                                "offering_id"), 
-                                            msOWSLookupMetadata(&(lp->metadata), "S", 
-                                                                "observedproperty_id"));
-
-
-    if (lp == lpfirst || (lpfirst && msLayerOpen(lpfirst) == MS_SUCCESS && 
-                          msLayerGetItems(lpfirst) == MS_SUCCESS))
-    {
-        pszSep = msOWSLookupMetadata(&(lp->map->web.metadata), "S", 
-                                     "encoding_tokenSeparator");
-        for(i=0; i<lpfirst->numitems; i++) 
-        {
-            snprintf(szTmp, sizeof(szTmp), "%s_alias", lpfirst->items[i]);
-            pszValue = msOWSLookupMetadata(&(lpfirst->metadata), "S", szTmp);
-            if (pszValue)
-            {
-                for (j=0; j<lp->numitems; j++)
-                {
-                    if (strcasecmp(lpfirst->items[i],  lpfirst->items[j]) == 0)
-                    {
-                        pszValueShape = msEncodeHTMLEntities(sShape.values[j]);
-
-                         
-                        if (pszFinalValue)
-                        {
-                            if (pszSep)
-                              pszFinalValue = msStringConcatenate(pszFinalValue, (char *)pszSep);
-                            else
-                              pszFinalValue = msStringConcatenate(pszFinalValue, ",");
-                        }
-                        pszFinalValue = msStringConcatenate(pszFinalValue,  pszValueShape);
-                        
-                        msFree(pszValueShape);
-                    }
-                }
+  /* the first layer is the one that has to have all the metadata defined */
+  lpfirst = msSOSGetFirstLayerForOffering(lp->map,
+                                          msOWSLookupMetadata(&(lp->metadata), "S",
+                                              "offering_id"),
+                                          msOWSLookupMetadata(&(lp->metadata), "S",
+                                              "observedproperty_id"));
+
+
+  if (lp == lpfirst || (lpfirst && msLayerOpen(lpfirst) == MS_SUCCESS &&
+                        msLayerGetItems(lpfirst) == MS_SUCCESS)) {
+    pszSep = msOWSLookupMetadata(&(lp->map->web.metadata), "S",
+                                 "encoding_tokenSeparator");
+    for(i=0; i<lpfirst->numitems; i++) {
+      snprintf(szTmp, sizeof(szTmp), "%s_alias", lpfirst->items[i]);
+      pszValue = msOWSLookupMetadata(&(lpfirst->metadata), "S", szTmp);
+      if (pszValue) {
+        for (j=0; j<lp->numitems; j++) {
+          if (strcasecmp(lpfirst->items[i],  lpfirst->items[j]) == 0) {
+            pszValueShape = msEncodeHTMLEntities(sShape.values[j]);
+
+
+            if (pszFinalValue) {
+              if (pszSep)
+                pszFinalValue = msStringConcatenate(pszFinalValue, (char *)pszSep);
+              else
+                pszFinalValue = msStringConcatenate(pszFinalValue, ",");
             }
+            pszFinalValue = msStringConcatenate(pszFinalValue,  pszValueShape);
+
+            msFree(pszValueShape);
+          }
         }
+      }
     }
-    return pszFinalValue;
-}       
+  }
+  msFreeShape(&sShape);
+  return pszFinalValue;
+}
 
 /************************************************************************/
 /*                      msSOSAddMemberNodeObservation                   */
@@ -1012,80 +945,75 @@ char* msSOSReturnMemberResult(layerObj *lp, int iFeatureId, char **ppszProcedure
 /************************************************************************/
 xmlNodePtr msSOSAddMemberNodeObservation(xmlNsPtr psNsGml, xmlNsPtr psNsSos, xmlNsPtr psNsOm, xmlNsPtr psNsSwe, xmlNsPtr psNsXLink, xmlNodePtr psParent, mapObj *map, layerObj *lp, const char *pszProcedure)
 {
-    char *pszTmp = NULL;
-    xmlNodePtr psNode=NULL, psObsNode=NULL, psMemberNode=NULL;
-    layerObj *lpfirst;
-    const char *value = NULL;
-
-    /*always featch the first layer that has the same offering id and observered propery.
-     This allows to only define all the attributes and components on the first layer if the user
-    wants to present several mapserver layers as the same offering.*/
-    lpfirst = msSOSGetFirstLayerForOffering(map, 
-                                            msOWSLookupMetadata(&(lp->metadata), "S", 
-                                                                "offering_id"), 
-                                            msOWSLookupMetadata(&(lp->metadata), "S", 
-                                                                "observedproperty_id"));
-    if (psParent)
-    {
-         psMemberNode = xmlNewChild(psParent, NULL, BAD_CAST "member", NULL);
-         psObsNode = xmlNewChild(psMemberNode, NULL, BAD_CAST "Observation", NULL);
+  char *pszTmp = NULL;
+  xmlNodePtr psNode=NULL, psObsNode=NULL, psMemberNode=NULL;
+  layerObj *lpfirst;
+  const char *value = NULL;
+
+  /*always featch the first layer that has the same offering id and observered propery.
+   This allows to only define all the attributes and components on the first layer if the user
+  wants to present several mapserver layers as the same offering.*/
+  lpfirst = msSOSGetFirstLayerForOffering(map,
+                                          msOWSLookupMetadata(&(lp->metadata), "S",
+                                              "offering_id"),
+                                          msOWSLookupMetadata(&(lp->metadata), "S",
+                                              "observedproperty_id"));
+  if (psParent) {
+    psMemberNode = xmlNewChild(psParent, NULL, BAD_CAST "member", NULL);
+    psObsNode = xmlNewChild(psMemberNode, NULL, BAD_CAST "Observation", NULL);
+
+    /*time*/
+    /* ??TODO : sampling time is a manadatory element but uses a non mandatory metadata sos_offering_timeextent */
+    value = msOWSLookupMetadata(&(lp->metadata), "S", "offering_timeextent");
+    if (value) {
+      char **tokens;
+      int n;
+      char *pszEndTime = NULL;
+      tokens = msStringSplit(value, '/', &n);
+      if (tokens==NULL || (n != 1 && n!=2)) {
+        msSetError(MS_SOSERR, "Wrong number of arguments for sos_offering_timeextent.",
+                   "msSOSGetObservation()");
+        msSOSException(map, "sos_offering_timeextent", "InvalidParameterValue");
+        return NULL;
+      }
 
-        /*time*/
-         /* ??TODO : sampling time is a manadatory element but uses a non mandatory metadata sos_offering_timeextent */
-         value = msOWSLookupMetadata(&(lp->metadata), "S", "offering_timeextent");
-         if (value)
-         {
-             char **tokens;
-             int n;
-             char *pszEndTime = NULL;
-             tokens = msStringSplit(value, '/', &n);
-             if (tokens==NULL || (n != 1 && n!=2)) {
-                 msSetError(MS_SOSERR, "Wrong number of arguments for sos_offering_timeextent.",
-                            "msSOSGetObservation()");
-                 msSOSException(map, "sos_offering_timeextent", "InvalidParameterValue");
-                 return NULL;
-             }
-
-             if (n == 2) /* end time is empty. It is going to be set as "now*/
-               pszEndTime = tokens[1];
-
-             psNode = xmlAddChild(psObsNode, msSOSAddTimeNode(psNsOm, psNsGml, tokens[0], pszEndTime));
-             msFreeCharArray(tokens, n);
-             
-         }
-
-         /* procedure */
-         if (pszProcedure) /*this should always be true since procedure is a manadtory element*/
-         {
-             if (! msOWSLookupMetadata(&(lp->metadata), "S", "procedure_item") && msOWSLookupMetadata(&(lp->metadata), "S", "procedure"))
-                xmlAddSibling(psNode, xmlNewComment(BAD_CAST "WARNING: Optional metadata \"sos_procedure_item\" missing for sos:procedure.  If you have more than 1 procedures, sos:procedure will output them incorrectly."));
-
-             pszTmp = msStringConcatenate(pszTmp, "urn:ogc:def:procedure:");
-             pszTmp = msStringConcatenate(pszTmp, (char *)pszProcedure);
-             psNode =  xmlNewChild(psObsNode, NULL, BAD_CAST "procedure", NULL);
-             /* xmlNewNsProp(psNode, xmlNewNs(NULL, BAD_CAST "http://www.w3.org/1999/xlink", BAD_CAST "xlink"), BAD_CAST "href", BAD_CAST pszTmp); */
-             xmlNewNsProp(psNode, psNsXLink, BAD_CAST "href", BAD_CAST pszTmp);
-             msFree(pszTmp);
-             pszTmp = NULL;
-         }
-
-         /*observed propery and components*/
-         if (lp != lpfirst &&  
-             msLayerOpen(lpfirst) == MS_SUCCESS && msLayerGetItems(lpfirst) == MS_SUCCESS)
-         {
-             msSOSAddPropertyNode(psNsSwe, psNsXLink, psObsNode, lpfirst, psNsGml, NULL);
-             msLayerClose(lpfirst);
-         }
-         else
-           msSOSAddPropertyNode(psNsSwe, psNsXLink, psObsNode, lpfirst, psNsGml, NULL);
-         
-         /* result definition*/
-         psNode = xmlNewChild(psObsNode, NULL, BAD_CAST "resultDefinition", NULL);
-         msSOSAddDataBlockDefinition(psNsSwe, psNode, lpfirst);
-         
-    }   
-
-    return psObsNode;
+      if (n == 2) /* end time is empty. It is going to be set as "now*/
+        pszEndTime = tokens[1];
+
+      psNode = xmlAddChild(psObsNode, msSOSAddTimeNode(psNsOm, psNsGml, tokens[0], pszEndTime));
+      msFreeCharArray(tokens, n);
+
+    }
+
+    /* procedure */
+    if (pszProcedure) { /*this should always be true since procedure is a manadtory element*/
+      if (! msOWSLookupMetadata(&(lp->metadata), "S", "procedure_item") && msOWSLookupMetadata(&(lp->metadata), "S", "procedure"))
+        xmlAddSibling(psNode, xmlNewComment(BAD_CAST "WARNING: Optional metadata \"sos_procedure_item\" missing for sos:procedure.  If you have more than 1 procedures, sos:procedure will output them incorrectly."));
+
+      pszTmp = msStringConcatenate(pszTmp, "urn:ogc:def:procedure:");
+      pszTmp = msStringConcatenate(pszTmp, (char *)pszProcedure);
+      psNode =  xmlNewChild(psObsNode, NULL, BAD_CAST "procedure", NULL);
+      /* xmlNewNsProp(psNode, xmlNewNs(NULL, BAD_CAST "http://www.w3.org/1999/xlink", BAD_CAST "xlink"), BAD_CAST "href", BAD_CAST pszTmp); */
+      xmlNewNsProp(psNode, psNsXLink, BAD_CAST "href", BAD_CAST pszTmp);
+      msFree(pszTmp);
+      pszTmp = NULL;
+    }
+
+    /*observed propery and components*/
+    if (lp != lpfirst &&
+        msLayerOpen(lpfirst) == MS_SUCCESS && msLayerGetItems(lpfirst) == MS_SUCCESS) {
+      msSOSAddPropertyNode(psNsSwe, psNsXLink, psObsNode, lpfirst, psNsGml, NULL);
+      msLayerClose(lpfirst);
+    } else
+      msSOSAddPropertyNode(psNsSwe, psNsXLink, psObsNode, lpfirst, psNsGml, NULL);
+
+    /* result definition*/
+    psNode = xmlNewChild(psObsNode, NULL, BAD_CAST "resultDefinition", NULL);
+    msSOSAddDataBlockDefinition(psNsSwe, psNode, lpfirst);
+
+  }
+
+  return psObsNode;
 }
 
 /************************************************************************/
@@ -1109,693 +1037,646 @@ xmlNodePtr msSOSAddMemberNodeObservation(xmlNsPtr psNsGml, xmlNsPtr psNsSos, xml
 /************************************************************************/
 char *msSOSParseTimeGML(char *pszGmlTime)
 {
-    char *pszReturn = NULL, *pszBegin = NULL, *pszEnd = NULL;
-    CPLXMLNode *psRoot=NULL, *psChild=NULL;
-    CPLXMLNode *psTime=NULL, *psBegin=NULL, *psEnd=NULL;
-    struct tm tm_struct;
-
-    if (pszGmlTime)
-    {
-        psRoot = CPLParseXMLString(pszGmlTime);
-        if(!psRoot)
-          return NULL;
-        CPLStripXMLNamespace(psRoot, "gml", 1);
-        
-        if (psRoot->eType == CXT_Element && 
-            (EQUAL(psRoot->pszValue,"TimePeriod") || 
-             EQUAL(psRoot->pszValue,"TimeInstant")))
-        {
-            if (EQUAL(psRoot->pszValue,"TimeInstant"))
-            {
-                psChild = psRoot->psChild;
-                if (psChild && EQUAL(psChild->pszValue,"timePosition"))
-                {
-                    psTime = psChild->psNext;
-                    if (psTime && psTime->pszValue && psTime->eType == CXT_Text)
-                    {
-                        if (msParseTime(psTime->pszValue, &tm_struct) == MS_TRUE)
-                          pszReturn = msStrdup(psTime->pszValue);
-                    }
-                }
-            }
-            else
-            {
-                psBegin = psRoot->psChild;
-                if (psBegin)
-                  psEnd = psBegin->psNext;
-
-                if (psBegin && EQUAL(psBegin->pszValue, "beginPosition") &&
-                    psEnd && EQUAL(psEnd->pszValue, "endPosition"))
-                {
-                    if (psBegin->psChild && psBegin->psChild->pszValue &&
-                        psBegin->psChild->eType == CXT_Text)
-                      pszBegin = msStrdup( psBegin->psChild->pszValue);
-
-                    if (psEnd->psChild && psEnd->psChild->pszValue &&
-                        psEnd->psChild->eType == CXT_Text)
-                      pszEnd = msStrdup(psEnd->psChild->pszValue);
-
-                    if (pszBegin && pszEnd)
-                    {
-                        if (msParseTime(pszBegin, &tm_struct) == MS_TRUE &&
-                            msParseTime(pszEnd, &tm_struct) == MS_TRUE)
-                        {
-                            pszReturn = msStrdup(pszBegin);
-                            pszReturn = msStringConcatenate(pszReturn, "/");
-                            pszReturn = msStringConcatenate(pszReturn, pszEnd);
-                        }
-                    }
-                    msFree(pszBegin);
-                    msFree(pszEnd);
-                }
+  char *pszReturn = NULL, *pszBegin = NULL, *pszEnd = NULL;
+  CPLXMLNode *psRoot=NULL, *psChild=NULL;
+  CPLXMLNode *psTime=NULL, *psBegin=NULL, *psEnd=NULL;
+  struct tm tm_struct;
+
+  if (pszGmlTime) {
+    psRoot = CPLParseXMLString(pszGmlTime);
+    if(!psRoot)
+      return NULL;
+    CPLStripXMLNamespace(psRoot, "gml", 1);
+
+    if (psRoot->eType == CXT_Element &&
+        (EQUAL(psRoot->pszValue,"TimePeriod") ||
+         EQUAL(psRoot->pszValue,"TimeInstant"))) {
+      if (EQUAL(psRoot->pszValue,"TimeInstant")) {
+        psChild = psRoot->psChild;
+        if (psChild && EQUAL(psChild->pszValue,"timePosition")) {
+          psTime = psChild->psNext;
+          if (psTime && psTime->pszValue && psTime->eType == CXT_Text) {
+            if (msParseTime(psTime->pszValue, &tm_struct) == MS_TRUE)
+              pszReturn = msStrdup(psTime->pszValue);
+          }
+        }
+      } else {
+        psBegin = psRoot->psChild;
+        if (psBegin)
+          psEnd = psBegin->psNext;
+
+        if (psBegin && EQUAL(psBegin->pszValue, "beginPosition") &&
+            psEnd && EQUAL(psEnd->pszValue, "endPosition")) {
+          if (psBegin->psChild && psBegin->psChild->pszValue &&
+              psBegin->psChild->eType == CXT_Text)
+            pszBegin = msStrdup( psBegin->psChild->pszValue);
+
+          if (psEnd->psChild && psEnd->psChild->pszValue &&
+              psEnd->psChild->eType == CXT_Text)
+            pszEnd = msStrdup(psEnd->psChild->pszValue);
+
+          if (pszBegin && pszEnd) {
+            if (msParseTime(pszBegin, &tm_struct) == MS_TRUE &&
+                msParseTime(pszEnd, &tm_struct) == MS_TRUE) {
+              pszReturn = msStrdup(pszBegin);
+              pszReturn = msStringConcatenate(pszReturn, "/");
+              pszReturn = msStringConcatenate(pszReturn, pszEnd);
             }
+          }
+          msFree(pszBegin);
+          msFree(pszEnd);
+        }
+      }
+    }
+  }
+  CPLDestroyXMLNode(psRoot);
+  return pszReturn;
+}
+
+
+/************************************************************************/
+/*                           msSOSGetCapabilities                       */
+/*                                                                      */
+/*      getCapabilities request handler.                                */
+/************************************************************************/
+int msSOSGetCapabilities(mapObj *map, sosParamsObj *sosparams, cgiRequestObj *req, owsRequestObj *ows_request)
+{
+  xmlDocPtr psDoc = NULL;       /* document pointer */
+  xmlNodePtr psRootNode, psMainNode, psNode;
+  xmlNodePtr psOfferingNode;
+
+  char *schemalocation = NULL;
+  char *xsi_schemaLocation = NULL;
+  char *script_url=NULL;
+  const char *updatesequence=NULL;
+  const char *encoding;
+
+  int i,j,k;
+  layerObj *lp = NULL, *lpTmp = NULL;
+  const char *value = NULL;
+  char *pszTmp = NULL;
+  char *pszProcedure = NULL;
+  char szTmp[256];
+
+  /* array of offering */
+  char **papsOfferings = NULL;
+  int nOfferings  =0, nCurrentOff = -1;
+  int nProperties = 0;
+  char **papszProperties = NULL;
+
+  int iItemPosition = -1;
+  shapeObj sShape;
+  int status;
+
+  /* for each layer it indicates the indice to be used in papsOfferings
+     (to associate it with the offering) */
+  int *panOfferingLayers = NULL;
+
+  char **papsProcedures = NULL;
+  int nDistinctProcedures =0;
+
+  xmlNsPtr psNsGml = NULL;
+  xmlNsPtr psNsSos = NULL;
+  xmlNsPtr psNsOws = NULL;
+  xmlNsPtr psNsOgc = NULL;
+  xmlNsPtr psNsXLink = NULL;
+  xmlNsPtr psNsSwe = NULL;
+
+  xmlChar *buffer = NULL;
+  int size = 0;
+  msIOContext *context = NULL;
+
+  int ows_version = OWS_1_1_0;
+
+  int sosSupportedVersions[] = {OWS_1_0_0};
+  int sosNumSupportedVersions = 1;
+
+  /* acceptversions: do OWS Common style of version negotiation */
+  if (sosparams->pszAcceptVersions) {
+    char **tokens;
+    int i, j, k=-1;
+
+    tokens = msStringSplit(sosparams->pszAcceptVersions, ',', &j);
+
+    for (i=0; i<j; i++) {
+      int iVersion = 0;
+
+      iVersion = msOWSParseVersionString(tokens[i]);
+
+      if (iVersion == -1) {
+        msSetError(MS_SOSERR, "Invalid version format.", "msSOSGetCapabilities()", tokens[i]);
+        msFreeCharArray(tokens, j);
+        return msSOSException(map, "acceptversions", "VersionNegotiationFailed");
+      }
+
+      /* negotiate version */
+      k = msOWSCommonNegotiateVersion(iVersion, sosSupportedVersions, sosNumSupportedVersions);
+
+      if (k != -1)
+        break;
+    }
+    msFreeCharArray(tokens, j);
+
+    if(k == -1) {
+      msSetError(MS_SOSERR, "ACCEPTVERSIONS list (%s) does not match supported versions (%s)", "msSOSGetCapabilities()", sosparams->pszAcceptVersions, pszSOSVersion);
+      return msSOSException(map, "acceptversions", "VersionNegotiationFailed");
+    }
+  }
+
+  /* updateSequence */
+  updatesequence = msOWSLookupMetadata(&(map->web.metadata), "SO", "updatesequence");
+  encoding = msOWSLookupMetadata(&(map->web.metadata), "SO", "encoding");
+
+  if (sosparams->pszUpdateSequence != NULL) {
+    i = msOWSNegotiateUpdateSequence(sosparams->pszUpdateSequence, updatesequence);
+    if (i == 0) { /* current */
+      msSetError(MS_SOSERR, "UPDATESEQUENCE parameter (%s) is equal to server (%s)", "msSOSGetCapabilities()", sosparams->pszUpdateSequence, updatesequence);
+      return msSOSException(map, "updatesequence", "CurrentUpdateSequence");
+    }
+    if (i > 0) { /* invalid */
+      msSetError(MS_SOSERR, "UPDATESEQUENCE parameter (%s) is higher than server (%s)", "msSOSGetCapabilities()", sosparams->pszUpdateSequence, updatesequence);
+      return msSOSException(map, "updatesequence", "InvalidUpdateSequence");
+    }
+  }
+
+  psDoc = xmlNewDoc(BAD_CAST "1.0");
+
+  psRootNode = xmlNewNode(NULL, BAD_CAST "Capabilities");
+
+  xmlDocSetRootElement(psDoc, psRootNode);
+
+  psNsGml = xmlNewNs(NULL, BAD_CAST "http://www.opengis.net/gml", BAD_CAST "gml");
+  psNsSos = xmlNewNs(NULL, BAD_CAST pszSOSNamespaceUri, BAD_CAST pszSOSNamespacePrefix);
+  psNsOgc = xmlNewNs(NULL, BAD_CAST MS_OWSCOMMON_OGC_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_OGC_NAMESPACE_PREFIX);
+  psNsSwe = xmlNewNs(NULL, BAD_CAST "http://www.opengis.net/swe/1.0.1", BAD_CAST "swe");
+
+  /* name spaces */
+  xmlSetNs(psRootNode,  xmlNewNs(psRootNode, BAD_CAST "http://www.opengis.net/gml", BAD_CAST "gml"));
+  xmlSetNs(psRootNode,  xmlNewNs(psRootNode, BAD_CAST "http://www.opengis.net/om/1.0", BAD_CAST "om"));
+
+  psNsOws = xmlNewNs(psRootNode, BAD_CAST "http://www.opengis.net/ows/1.1", BAD_CAST "ows");
+  xmlSetNs(psRootNode, psNsOws );
+
+  xmlSetNs(psRootNode,xmlNewNs(psRootNode, BAD_CAST "http://www.opengis.net/swe/1.0.1", BAD_CAST "swe"));
+
+  psNsXLink = xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_W3C_XLINK_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_W3C_XLINK_NAMESPACE_PREFIX);
+  xmlSetNs(psRootNode, psNsXLink );
+
+  xmlSetNs(psRootNode,xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_W3C_XSI_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_W3C_XSI_NAMESPACE_PREFIX));
+  xmlSetNs(psRootNode, xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_OGC_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_OGC_NAMESPACE_PREFIX));
+  xmlSetNs(psRootNode, xmlNewNs(psRootNode, BAD_CAST pszSOSNamespaceUri, BAD_CAST pszSOSNamespacePrefix));
+
+  /*version fixed for now*/
+  xmlNewProp(psRootNode, BAD_CAST "version", BAD_CAST pszSOSVersion);
+
+  value = msOWSLookupMetadata(&(map->web.metadata), "SO", "updatesequence");
+
+  if (value)
+    xmlNewProp(psRootNode, BAD_CAST "updateSequence", BAD_CAST value);
+
+  /*schema fixed*/
+  schemalocation = msEncodeHTMLEntities( msOWSGetSchemasLocation(map) );
+  xsi_schemaLocation = msStrdup(pszSOSNamespaceUri);
+  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, " ");
+  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, schemalocation);
+  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, "/sos/");
+  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, (char *)pszSOSVersion);
+  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, "/sosGetCapabilities.xsd");
+  xmlNewNsProp(psRootNode, NULL, BAD_CAST "xsi:schemaLocation", BAD_CAST xsi_schemaLocation);
+
+  xmlAddChild(psRootNode, xmlNewComment(BAD_CAST msGetVersion()));
+
+  /*service identification*/
+  xmlAddChild(psRootNode, msOWSCommonServiceIdentification(psNsOws, map, "SOS", pszSOSVersion, "SO"));
+
+  /*service provider*/
+  xmlAddChild(psRootNode, msOWSCommonServiceProvider(psNsOws, psNsXLink, map, "SO"));
+
+  /*operation metadata */
+
+  if ((script_url=msOWSGetOnlineResource(map, "SO", "onlineresource", req)) == NULL)
+    return msSOSException(map, "NoApplicableCode", "NoApplicableCode");
+
+  psMainNode = xmlAddChild(psRootNode, msOWSCommonOperationsMetadata(psNsOws));
+
+  psNode     = xmlAddChild(psMainNode, msOWSCommonOperationsMetadataOperation(psNsOws,psNsXLink,"GetCapabilities", OWS_METHOD_GETPOST, (char *) script_url));
+  xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,"Parameter", "service", "SOS"));
+  xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,"Parameter", "version", (char *)pszSOSVersion));
+
+  if (msOWSRequestIsEnabled(map, NULL, "S", "DescribeSensor", MS_TRUE)) {
+    psNode     = xmlAddChild(psMainNode, msOWSCommonOperationsMetadataOperation(psNsOws,psNsXLink,"DescribeSensor", OWS_METHOD_GETPOST, (char *) script_url));
+    xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,"Parameter", "service", "SOS"));
+    xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,"Parameter", "version", (char *)pszSOSVersion));
+    xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,"Parameter", "sensorid", "urn:ogc:object:procedure"));
+    xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,"Parameter", "outputFormat", (char *)pszSOSDescribeSensorMimeType));
+  }
+
+  if (msOWSRequestIsEnabled(map, NULL, "S", "DescribeObservationType", MS_TRUE)) {
+    psNode     = xmlAddChild(psMainNode, msOWSCommonOperationsMetadataOperation(psNsOws,psNsXLink,"DescribeObservationType", OWS_METHOD_GETPOST, (char *) script_url));
+    xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,"Parameter", "service", "SOS"));
+    xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,"Parameter", "version", (char *)pszSOSVersion));
+    xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,"Parameter", "observedproperty", "urn:ogc:object:observedproperty"));
+  }
+
+  if (msOWSRequestIsEnabled(map, NULL, "S", "GetObservation", MS_TRUE)) {
+    psNode     = xmlAddChild(psMainNode, msOWSCommonOperationsMetadataOperation(psNsOws,psNsXLink,"GetObservation", OWS_METHOD_GETPOST, (char *) script_url));
+    xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,"Parameter", "service", "SOS"));
+    xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,"Parameter", "version", (char *)pszSOSVersion));
+    xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,"Parameter", "offering", "urn:ogc:object:offering"));
+    xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,"Parameter", "observedproperty", "urn:ogc:object:observedproperty"));
+    xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,"Parameter", "eventtime", "sos:time"));
+    xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,"Parameter", "procedure", "urn:ogc:object:sensor"));
+    xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,"Parameter", "featureofinterest", "gml:location"));
+    xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,"Parameter", "result", "ogc:Filter"));
+    xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,"Parameter", "responseFormat", (char *)pszSOSGetObservationMimeType));
+    xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,"Parameter", "resultModel", "Observation,Measurement"));
+  }
+
+  value = msOWSLookupMetadata(&(map->web.metadata), "SO", "maxfeatures");
+
+  if (value) {
+    psNode  = xmlAddChild(psMainNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,"Constraint", "DefaultMaxFeatures", (char *)value));
+  }
+
+  /*<ogc:Filter_Capabilities> */
+  xmlAddChild(psRootNode, FLTGetCapabilities(psNsSos, psNsOgc, MS_TRUE));
+
+  /*Offerings */
+  psNode = xmlNewChild(psRootNode, NULL, BAD_CAST "Contents", NULL);
+  psMainNode = xmlNewChild(psNode, NULL, BAD_CAST "ObservationOfferingList", NULL);
+
+  /*go through the layers and check for metadata sos_offering_id.
+    One or more layers could have the same offering id. In that case they
+    are adverized as the same offering. The first layer that has*/
+
+  if (map->numlayers) {
+    papsOfferings = (char **)malloc(sizeof(char *)*map->numlayers);
+    panOfferingLayers = (int *)malloc(sizeof(int)*map->numlayers);
+    for (i=0; i<map->numlayers; i++)
+      panOfferingLayers[i] = -1;
+
+    for (i=0; i<map->numlayers; i++) {
+      lp = (GET_LAYER(map, i));
+
+      if (lp->status == MS_DELETE)
+        continue;
+
+      value = msOWSLookupMetadata(&(lp->metadata), "S", "offering_id");
+      if (value && (msIntegerInArray(lp->index, ows_request->enabled_layers, ows_request->numlayers))) {
+        nCurrentOff = -1;
+        for (j=0; j<nOfferings; j++) {
+          if (strcasecmp(value, papsOfferings[j]) == 0) {
+            nCurrentOff = j;
+            break;
+          }
+        }
+        if (nCurrentOff >= 0) /* existing offering */
+          panOfferingLayers[i] = nCurrentOff;
+        else { /*new offering */
+          papsOfferings[nOfferings] = msStrdup(value);
+          panOfferingLayers[i] = nOfferings;
+          nOfferings++;
         }
+      }
     }
-    CPLDestroyXMLNode(psRoot);
-    return pszReturn;
-}
 
+    if (nOfferings > 0) {
+      for (i=0; i<nOfferings; i++) {
+        psOfferingNode =
+          xmlNewChild(psMainNode, NULL,BAD_CAST "ObservationOffering", NULL);
+        xmlNewNsProp(psOfferingNode, psNsGml,
+                     BAD_CAST "id", BAD_CAST papsOfferings[i]);
+        for (j=0; j<map->numlayers; j++) {
+          if (panOfferingLayers[j] == i) /*first layer of the offering */
+            break;
+        }
 
-/************************************************************************/
-/*                           msSOSGetCapabilities                       */
-/*                                                                      */
-/*      getCapabilities request handler.                                */
-/************************************************************************/
-int msSOSGetCapabilities(mapObj *map, sosParamsObj *sosparams, cgiRequestObj *req, owsRequestObj *ows_request) {
-    xmlDocPtr psDoc = NULL;       /* document pointer */
-    xmlNodePtr psRootNode, psMainNode, psNode;
-    xmlNodePtr psOfferingNode;
-    xmlNodePtr psTmpNode;
-
-    char *schemalocation = NULL;
-    char *xsi_schemaLocation = NULL;
-    char *script_url=NULL;
-    const char *updatesequence=NULL;
-    const char *encoding;
-
-    int i,j,k;
-    layerObj *lp = NULL, *lpTmp = NULL;
-    const char *value = NULL;
-    char *pszTmp = NULL;
-    char *pszProcedure = NULL;
-    char szTmp[256]; 
-
-     /* array of offering */
-    char **papsOfferings = NULL; 
-    int nOfferings  =0, nCurrentOff = -1;
-    int nProperties = 0;
-    char **papszProperties = NULL;
-
-    int iItemPosition = -1;
-    shapeObj sShape;
-    int status;
-
-     /* for each layer it indicates the indice to be used in papsOfferings
-        (to associate it with the offering) */
-    int *panOfferingLayers = NULL;
-   
-    char **papsProcedures = NULL;
-    int nDistinctProcedures =0;
-
-    xmlNsPtr psNsGml = NULL;
-    xmlNsPtr psNsSos = NULL;
-    xmlNsPtr psNsOws = NULL;
-    xmlNsPtr psNsOgc = NULL;
-    xmlNsPtr psNsXLink = NULL;
-    xmlNsPtr psNsSwe = NULL;
-
-    xmlChar *buffer = NULL;
-    int size = 0;
-    msIOContext *context = NULL;
-
-    int ows_version = OWS_1_1_0;
-
-    int sosSupportedVersions[] = {OWS_1_0_0};
-    int sosNumSupportedVersions = 1;
-
-    /* acceptversions: do OWS Common style of version negotiation */
-    if (sosparams->pszAcceptVersions) {
-      char **tokens;
-      int i, j, k=-1;
+        /*description*/
+        value = msOWSLookupMetadata(&(lp->metadata), "S",
+                                    "offering_description");
+        if (value)
+          psNode = xmlNewChild(psOfferingNode, psNsGml, BAD_CAST "description", BAD_CAST value);
+        else
+          xmlAddSibling(psNode, xmlNewComment(BAD_CAST "WARNING: Optional metadata \"sos_offering_description\" missing for gml:description"));
 
-      tokens = msStringSplit(sosparams->pszAcceptVersions, ',', &j);
+        /*name*/
+        lp = (GET_LAYER(map, j)); /*first layer*/
+        value = msOWSLookupMetadata(&(lp->metadata), "S", "offering_name");
+        if (value)
+          psNode = xmlNewChild(psOfferingNode, psNsGml, BAD_CAST "name", BAD_CAST value);
+        else
+          xmlAddSibling(psNode, xmlNewComment(BAD_CAST "WARNING: Optional metadata \"sos_offering_name\" missing for gml:name"));
 
-      for (i=0; i<j;i++) {
-        int iVersion = 0;
+        /* srsName */
+        value = msOWSLookupMetadata(&(map->web.metadata), "SO", "srs");
 
-        iVersion = msOWSParseVersionString(tokens[i]);
+        if (value)
+          msLibXml2GenerateList(psOfferingNode, psNsGml, "srsName", value, ' ');
+        else
+          xmlAddSibling(psNode, xmlNewComment(BAD_CAST "WARNING: Required metadata \"sos_srs\" missing for gml:srsName"));
+
+        /*bounding box */
+        /*TODO : if sos_offering_extent does not exist compute extents
+                 Check also what happen if epsg not present */
+        value = msOWSLookupMetadata(&(lp->metadata), "S", "offering_extent");
+        if (value) {
+          char **tokens;
+          int n;
+          tokens = msStringSplit(value, ',', &n);
+          if (tokens==NULL || n != 4) {
+            msSetError(MS_SOSERR, "Wrong number of arguments for sos_offering_extent.",
+                       "msSOSGetCapabilities()");
+            return msSOSException(map, "sos_offering_extent", "InvalidParameterValue");
+          }
+          value = msOWSGetEPSGProj(&(lp->projection),
+                                   &(lp->metadata), "SO", MS_TRUE);
+          if (value)
+            psNode = xmlAddChild(psOfferingNode, msGML3BoundedBy(psNsGml, atof(tokens[0]), atof(tokens[1]), atof(tokens[2]), atof(tokens[3]), value));
+          msFreeCharArray(tokens, n);
 
-        if (iVersion == -1) {
-          msSetError(MS_SOSERR, "Invalid version format.", "msSOSGetCapabilities()", tokens[i]);
-          msFreeCharArray(tokens, j);
-          return msSOSException(map, "acceptversions", "VersionNegotiationFailed");
         }
 
-        /* negotiate version */
-        k = msOWSCommonNegotiateVersion(iVersion, sosSupportedVersions, sosNumSupportedVersions);
+        /* intended application */
 
-        if (k != -1)
-          break;
-      }
-      msFreeCharArray(tokens, j);
+        value = msOWSLookupMetadata(&(lp->metadata), "S", "offering_intendedapplication");
 
-      if(k == -1){
-          msSetError(MS_SOSERR, "ACCEPTVERSIONS list (%s) does not match supported versions (%s)", "msSOSGetCapabilities()", sosparams->pszAcceptVersions, pszSOSVersion);
-          return msSOSException(map, "acceptversions", "VersionNegotiationFailed");
-      }
-    }
+        if (value)
+          psNode = xmlNewChild(psOfferingNode, psNsSos, BAD_CAST "intendedApplication", BAD_CAST value);
+        else
+          xmlAddSibling(psNode, xmlNewComment(BAD_CAST "WARNING: Optional metadata \"sos_offering_intendedapplication\" missing for sos:intendedApplication"));
+
+        /*time*/
+        value = msOWSLookupMetadata(&(lp->metadata), "S",
+                                    "offering_timeextent");
+        if (value) {
+          char **tokens;
+          int n;
+          char *pszEndTime = NULL;
+          tokens = msStringSplit(value, '/', &n);
+          if (tokens==NULL || (n != 1 && n!=2)) {
+            msSetError(MS_SOSERR, "Wrong number of arguments for sos_offering_timeextent.",
+                       "msSOSGetCapabilities()");
+            return msSOSException(map, "sos_offering_timeextent", "InvalidParameterValue");
+          }
 
-    /* updateSequence */
-    updatesequence = msOWSLookupMetadata(&(map->web.metadata), "SO", "updatesequence");
-    encoding = msOWSLookupMetadata(&(map->web.metadata), "SO", "encoding");
+          if (n == 2) /* end time is empty. It is going to be set as "now*/
+            pszEndTime = tokens[1];
 
-    if (sosparams->pszUpdateSequence != NULL) {
-      i = msOWSNegotiateUpdateSequence(sosparams->pszUpdateSequence, updatesequence);
-      if (i == 0) { /* current */
-          msSetError(MS_SOSERR, "UPDATESEQUENCE parameter (%s) is equal to server (%s)", "msSOSGetCapabilities()", sosparams->pszUpdateSequence, updatesequence);
-          return msSOSException(map, "updatesequence", "CurrentUpdateSequence");
-      }
-      if (i > 0) { /* invalid */
-          msSetError(MS_SOSERR, "UPDATESEQUENCE parameter (%s) is higher than server (%s)", "msSOSGetCapabilities()", sosparams->pszUpdateSequence, updatesequence);
-          return msSOSException(map, "updatesequence", "InvalidUpdateSequence");
-      }
-    }
+          psNode = xmlAddChild(psOfferingNode, msSOSAddTimeNode(psNsSos, psNsGml, tokens[0], pszEndTime));
+          msFreeCharArray(tokens, n);
 
-    psDoc = xmlNewDoc(BAD_CAST "1.0");
+        }
+
+        /*procedure : output all procedure links for the offering */
+        for (j=0; j<map->numlayers; j++) {
+          if (panOfferingLayers[j] == i) {
+            value = msOWSLookupMetadata(&(GET_LAYER(map, j)->metadata), "S",
+                                        "procedure");
+            if (value && strlen(value) > 0) {
+              /*value could be a list of procedure*/
+              char **tokens;
+              int n = 0;
+              tokens = msStringSplit(value, ' ', &n);
+              for (k=0; k<n; k++) {
+                /*TODO review the urn output */
+                snprintf(szTmp, sizeof(szTmp), "%s", "urn:ogc:def:procedure:");
+                pszTmp = msStringConcatenate(pszTmp, szTmp);
+                pszTmp = msStringConcatenate(pszTmp, tokens[k]);
+
+                psNode =
+                  xmlNewChild(psOfferingNode, NULL, BAD_CAST "procedure", NULL);
+                /* xmlNewNsProp(psNode, xmlNewNs(NULL, BAD_CAST "http://www.w3.org/1999/xlink", BAD_CAST "xlink"), BAD_CAST "href", BAD_CAST pszTmp); */
+                xmlNewNsProp(psNode, psNsXLink, BAD_CAST "href", BAD_CAST pszTmp);
+                msFree(pszTmp);
+                pszTmp = NULL;
+              }
+              msFreeCharArray(tokens, n);
+            } else if ((value = msOWSLookupMetadata(&(GET_LAYER(map,j)->metadata), "S",
+                                                    "procedure_item"))) {
+              /* if a procedure_item is used, it means that the procedure
+                 (or sensor) need to be extracted from the data. Thus we need to
+                 query the layer and get the values from each feature */
+
+
+              lpTmp = GET_LAYER(map,j);
+              if (lpTmp->template == NULL)
+                lpTmp->template = msStrdup("ttt");
+
+              map->query.type = MS_QUERY_BY_RECT;
+              map->query.mode = MS_QUERY_MULTIPLE;
+              map->query.layer = j;
+              map->query.rect = map->extent;
+              msQueryByRect(map);
 
-    psRootNode = xmlNewNode(NULL, BAD_CAST "Capabilities");
+              /*check if the attribute specified in the procedure_item is available
+                on the layer*/
+              iItemPosition = -1;
+              if (msLayerGetItems(lpTmp) == MS_SUCCESS &&
+                  lpTmp->resultcache && lpTmp->resultcache->numresults > 0) {
+                for(k=0; k<lpTmp->numitems; k++) {
+                  if (strcasecmp(lpTmp->items[k], value) == 0) {
+                    iItemPosition = k;
+                    break;
+                  }
+                }
+                if (iItemPosition == -1) {
+                  msSetError(MS_SOSERR, "procedure_item %s could not be found on the layer %s",
+                             "msSOSGetCapabilities()", value, lpTmp->name);
+                  return msSOSException(map, "mapserv", "NoApplicableCode");
+                }
 
-    xmlDocSetRootElement(psDoc, psRootNode);
+                /*for each selected feature, grab the value of the prodedire_item*/
+                /* do not duplicate sensor ids if they are the same */
 
-    psNsGml = xmlNewNs(NULL, BAD_CAST "http://www.opengis.net/gml", BAD_CAST "gml");
-    psNsSos = xmlNewNs(NULL, BAD_CAST pszSOSNamespaceUri, BAD_CAST pszSOSNamespacePrefix);
-    psNsOgc = xmlNewNs(NULL, BAD_CAST MS_OWSCOMMON_OGC_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_OGC_NAMESPACE_PREFIX);
-    psNsSwe = xmlNewNs(NULL, BAD_CAST "http://www.opengis.net/swe/1.0.1", BAD_CAST "swe");
+                /*keep list of distinct procedures*/
+                papsProcedures =
+                  (char **)malloc(sizeof(char *) * lpTmp->resultcache->numresults);
+                nDistinctProcedures = 0;
+                for(k=0; k<lpTmp->resultcache->numresults; k++)
+                  papsProcedures[k] = NULL;
 
-    /* name spaces */
-    xmlSetNs(psRootNode,  xmlNewNs(psRootNode, BAD_CAST "http://www.opengis.net/gml", BAD_CAST "gml"));
-    xmlSetNs(psRootNode,  xmlNewNs(psRootNode, BAD_CAST "http://www.opengis.net/om/1.0", BAD_CAST "om"));
 
-    psNsOws = xmlNewNs(psRootNode, BAD_CAST "http://www.opengis.net/ows/1.1", BAD_CAST "ows");
-    xmlSetNs(psRootNode, psNsOws );
+                for(k=0; k<lpTmp->resultcache->numresults; k++) {
+                  msInitShape(&sShape);
+                  status = msLayerGetShape(lp, &sShape, &(lpTmp->resultcache->results[k]));
+                  if(status != MS_SUCCESS)
+                    continue;
 
-    xmlSetNs(psRootNode,xmlNewNs(psRootNode, BAD_CAST "http://www.opengis.net/swe/1.0.1", BAD_CAST "swe"));
-    
-    psNsXLink = xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_W3C_XLINK_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_W3C_XLINK_NAMESPACE_PREFIX);
-    xmlSetNs(psRootNode, psNsXLink );
+                  if (sShape.values[iItemPosition]) {
+                    pszProcedure = msStringConcatenate(pszProcedure, sShape.values[iItemPosition]);
+                    if (!_IsInList(papsProcedures, nDistinctProcedures, pszProcedure)) {
+                      papsProcedures[nDistinctProcedures] = msStrdup(pszProcedure);
+                      nDistinctProcedures++;
+                      snprintf(szTmp, sizeof(szTmp), "%s", "urn:ogc:def:procedure:");
+                      pszTmp = msStringConcatenate(pszTmp, szTmp);
+                      pszTmp = msStringConcatenate(pszTmp, pszProcedure);
+
+                      psNode =
+                        xmlNewChild(psOfferingNode, NULL, BAD_CAST "procedure", NULL);
+                      xmlNewNsProp(psNode,
+                                   xmlNewNs(NULL, BAD_CAST "http://www.w3.org/1999/xlink",
+                                            BAD_CAST "xlink"), BAD_CAST "href", BAD_CAST pszTmp);
+                      msFree(pszTmp);
+                      pszTmp = NULL;
 
-    xmlSetNs(psRootNode,xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_W3C_XSI_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_W3C_XSI_NAMESPACE_PREFIX));
-    xmlSetNs(psRootNode, xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_OGC_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_OGC_NAMESPACE_PREFIX));
-    xmlSetNs(psRootNode, xmlNewNs(psRootNode, BAD_CAST pszSOSNamespaceUri, BAD_CAST pszSOSNamespacePrefix));
+                    }
+                    msFree(pszProcedure);
+                    pszProcedure = NULL;
+                  }
+                }
+                for(k=0; k<lpTmp->resultcache->numresults; k++)
+                  if (papsProcedures[k] != NULL)
+                    msFree(papsProcedures[k]);
+                msFree(papsProcedures);
+
+              } else {
+                msSetError(MS_SOSERR, "Invalid procedure %s", "msSOSGetCapabilities()", value);
+                return msSOSException(map, "procedure", "InvalidParameterValue");
+              }
+            } else {
+              msSetError(MS_SOSERR, "Mandatory metadata procedure_item could not be found on the layer %s",
+                         "msSOSGetCapabilities()", GET_LAYER(map,j)->name);
+              return msSOSException(map, "mapserv", "NoApplicableCode");
+            }
 
-    /*version fixed for now*/
-    xmlNewProp(psRootNode, BAD_CAST "version", BAD_CAST pszSOSVersion);
+          }
+        }
+        /*observed property */
+        /* observed property are equivalent to layers. We can group
+           sevaral layers using the same sos_observedproperty_id. The
+           components are the attributes. Components are exposed
+           using the metadata sos_%s_aliasl */
+
+        nProperties = 0;
+        papszProperties =
+          (char **)malloc(sizeof(char *)*map->numlayers);
+
+        for (j=0; j<map->numlayers; j++) {
+          if (panOfferingLayers[j] == i) {
+            if ((value =
+                   msOWSLookupMetadata(&(GET_LAYER(map, j)->metadata), "S",
+                                       "observedproperty_id"))) {
+              for (k=0; k<nProperties; k++) {
+                if (strcasecmp(value, papszProperties[k]) == 0)
+                  break;
+              }
+              if (k == nProperties) { /*not found*/
+                papszProperties[nProperties] = msStrdup(value);
+                nProperties++;
+                lpTmp = GET_LAYER(map, j);
+                if (msLayerOpen(lpTmp) == MS_SUCCESS && msLayerGetItems(lpTmp) == MS_SUCCESS) {
+                  msSOSAddPropertyNode(psNsSwe, psNsXLink, psOfferingNode,
+                                       lpTmp, psNsGml, NULL);
+                  msLayerClose(lpTmp);
+                }
+              }
+            }
+          }
+        }
+        for (j=0; j<nProperties; j++)
+          free(papszProperties[j]);
+        free(papszProperties);
+
+        psNode = xmlNewChild(psOfferingNode, NULL, BAD_CAST "featureOfInterest", NULL);
+        xmlNewNsProp(psNode, psNsXLink, BAD_CAST "href", BAD_CAST "urn:ogc:def:feature:OGC-SWE:3:transient");
+
+        psNode = xmlNewChild(psOfferingNode, NULL, BAD_CAST "responseFormat",
+                             BAD_CAST pszSOSGetObservationMimeType);
+        psNode = xmlNewChild(psOfferingNode, NULL, BAD_CAST "resultModel",
+                             BAD_CAST "om:Observation");
+        psNode = xmlNewChild(psOfferingNode, NULL, BAD_CAST "resultModel",
+                             BAD_CAST "om:Measurement");
+        psNode = xmlNewChild(psOfferingNode, NULL, BAD_CAST "responseMode",
+                             BAD_CAST "inline");
+
+      }/*end of offerings*/
+    }
 
-    value = msOWSLookupMetadata(&(map->web.metadata), "SO", "updatesequence");
+    if (papsOfferings && nOfferings > 0) {
+      for (i=0; i<nOfferings; i++)
+        msFree(papsOfferings[i]);
+    }
+    msFree(papsOfferings);
+    if(panOfferingLayers)
+      msFree(panOfferingLayers);
 
-    if (value) 
-      xmlNewProp(psRootNode, BAD_CAST "updateSequence", BAD_CAST value);
+  }/* end of offerings */
 
-    /*schema fixed*/
-    schemalocation = msEncodeHTMLEntities( msOWSGetSchemasLocation(map) );
-    xsi_schemaLocation = msStrdup(pszSOSNamespaceUri);
-    xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, " ");
-    xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, schemalocation);
-    xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, "/sos/");
-    xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, (char *)pszSOSVersion);
-    xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, "/sosGetCapabilities.xsd");
-    xmlNewNsProp(psRootNode, NULL, BAD_CAST "xsi:schemaLocation", BAD_CAST xsi_schemaLocation);
+  if ( msIO_needBinaryStdout() == MS_FAILURE )
+    return MS_FAILURE;
 
-    psTmpNode = xmlAddChild(psRootNode, xmlNewComment(BAD_CAST msGetVersion()));
+  if (encoding)
+    msIO_setHeader("Content-Type","text/xml; charset=%s", encoding);
+  else
+    msIO_setHeader("Content-Type","text/xml");
+  msIO_sendHeaders();
+
+  /*TODO* : check the encoding validity. Internally libxml2 uses UTF-8
+  msOWSPrintEncodeMetadata(stdout, &(map->web.metadata),
+                           "SO", "encoding", OWS_NOERR,
+                           "<?xml version='1.0' encoding=\"%s\" standalone=\"no\" ?>\n",
+                           "ISO-8859-1");
+  */
+  /*xmlDocDumpFormatMemoryEnc(psDoc, &buffer, &size, (encoding ? encoding : "ISO-8859-1"), 1);*/
 
-    /*service identification*/
-    psTmpNode = xmlAddChild(psRootNode, msOWSCommonServiceIdentification(psNsOws, map, "SOS", pszSOSVersion, "SO"));
+  /* xmlDocDump crashs withe the prebuild windows binaries distibutes at the libxml site???.
+   It works with locally build binaries*/
 
-    /*service provider*/
-    psTmpNode = xmlAddChild(psRootNode, msOWSCommonServiceProvider(psNsOws, psNsXLink, map, "SO"));
+  context = msIO_getHandler(stdout);
 
-    /*operation metadata */
+  xmlDocDumpFormatMemoryEnc(psDoc, &buffer, &size, (encoding ? encoding : "ISO-8859-1"), 1);
+  msIO_contextWrite(context, buffer, size);
+  xmlFree(buffer);
 
-    if ((script_url=msOWSGetOnlineResource(map, "SO", "onlineresource", req)) == NULL)
-        return msSOSException(map, "NoApplicableCode", "NoApplicableCode");
+  /*free buffer and the document */
+  /*xmlFree(buffer);*/
+  xmlFreeDoc(psDoc);
+  xmlFreeNs(psNsGml);
+  xmlFreeNs(psNsSos);
+  xmlFreeNs(psNsOgc);
+  xmlFreeNs(psNsSwe);
 
-    psMainNode = xmlAddChild(psRootNode, msOWSCommonOperationsMetadata(psNsOws));
+  free(xsi_schemaLocation);
+  free(schemalocation);
+  msFree(script_url);
 
-    psNode     = xmlAddChild(psMainNode, msOWSCommonOperationsMetadataOperation(psNsOws,psNsXLink,"GetCapabilities", OWS_METHOD_GETPOST, (char *) script_url));
-    psTmpNode  = xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,"Parameter", "service", "SOS"));
-    psTmpNode  = xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,"Parameter", "version", (char *)pszSOSVersion));
+  /*
+   *Free the global variables that may
+   *have been allocated by the parser.
+   */
+  xmlCleanupParser();
 
-    if (msOWSRequestIsEnabled(map, NULL, "S", "DescribeSensor", MS_TRUE)) 
-    {
-        psNode     = xmlAddChild(psMainNode, msOWSCommonOperationsMetadataOperation(psNsOws,psNsXLink,"DescribeSensor", OWS_METHOD_GETPOST, (char *) script_url));
-        psTmpNode  = xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,"Parameter", "service", "SOS"));
-        psTmpNode  = xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,"Parameter", "version", (char *)pszSOSVersion));
-        psTmpNode  = xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,"Parameter", "sensorid", "urn:ogc:object:procedure"));
-        psTmpNode  = xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,"Parameter", "outputFormat", (char *)pszSOSDescribeSensorMimeType));
-    }
 
-    if (msOWSRequestIsEnabled(map, NULL, "S", "DescribeObservationType", MS_TRUE))
-    {
-        psNode     = xmlAddChild(psMainNode, msOWSCommonOperationsMetadataOperation(psNsOws,psNsXLink,"DescribeObservationType", OWS_METHOD_GETPOST, (char *) script_url));
-        psTmpNode  = xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,"Parameter", "service", "SOS"));
-        psTmpNode  = xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,"Parameter", "version", (char *)pszSOSVersion));
-        psTmpNode  = xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,"Parameter", "observedproperty", "urn:ogc:object:observedproperty"));
-    }
+  return(MS_SUCCESS);
 
-    if (msOWSRequestIsEnabled(map, NULL, "S", "GetObservation", MS_TRUE)) 
-    {
-        psNode     = xmlAddChild(psMainNode, msOWSCommonOperationsMetadataOperation(psNsOws,psNsXLink,"GetObservation", OWS_METHOD_GETPOST, (char *) script_url));
-        psTmpNode  = xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,"Parameter", "service", "SOS"));
-        psTmpNode  = xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,"Parameter", "version", (char *)pszSOSVersion));
-        psTmpNode  = xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,"Parameter", "offering", "urn:ogc:object:offering"));
-        psTmpNode  = xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,"Parameter", "observedproperty", "urn:ogc:object:observedproperty"));
-        psTmpNode  = xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,"Parameter", "eventtime", "sos:time"));
-        psTmpNode  = xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,"Parameter", "procedure", "urn:ogc:object:sensor"));
-        psTmpNode  = xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,"Parameter", "featureofinterest", "gml:location"));
-        psTmpNode  = xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,"Parameter", "result", "ogc:Filter"));
-        psTmpNode  = xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,"Parameter", "responseFormat", (char *)pszSOSGetObservationMimeType));
-        psTmpNode  = xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,"Parameter", "resultModel", "Observation,Measurement"));
-    }
 
-    value = msOWSLookupMetadata(&(map->web.metadata), "SO", "maxfeatures");
+  /*
+  nSize = sizeof(workbuffer);
+  nSize = nSize-1;*/ /* the last character for the '\0' */
 
-    if (value) {
-      psNode  = xmlAddChild(psMainNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,"Constraint", "DefaultMaxFeatures", (char *)value));
-    }
-
-    /*<ogc:Filter_Capabilities> */
-    psTmpNode = xmlAddChild(psRootNode, FLTGetCapabilities(psNsSos, psNsOgc, MS_TRUE));
-
-    /*Offerings */
-     psNode = xmlNewChild(psRootNode, NULL, BAD_CAST "Contents", NULL);
-     psMainNode = xmlNewChild(psNode, NULL, BAD_CAST "ObservationOfferingList", NULL);
-     
-     /*go through the layers and check for metadata sos_offering_id.
-       One or more layers could have the same offering id. In that case they
-       are adverized as the same offering. The first layer that has*/
-
-     if (map->numlayers)
-     {
-         papsOfferings = (char **)malloc(sizeof(char *)*map->numlayers);
-         panOfferingLayers = (int *)malloc(sizeof(int)*map->numlayers);
-         for (i=0; i<map->numlayers; i++)
-           panOfferingLayers[i] = -1;
-         
-         for (i=0; i<map->numlayers; i++)
-         {
-             lp = (GET_LAYER(map, i));
-
-             if (lp->status == MS_DELETE)
-                continue;
+  /*
+  if (size > nSize)
+  {
+       iIndice = 0;
+       while ((iIndice + nSize) <= size)
+       {
+           snprintf(workbuffer, (sizeof(workbuffer)-1), "%s", buffer+iIndice );
+           workbuffer[sizeof(workbuffer)-1] = '\0';
+           msIO_printf("%s", workbuffer);
 
-             value = msOWSLookupMetadata(&(lp->metadata), "S", "offering_id");
-             if (value && (msIntegerInArray(lp->index, ows_request->enabled_layers, ows_request->numlayers)))
-             {
-                 nCurrentOff = -1;
-                 for (j=0; j<nOfferings; j++)
-                 {
-                     if (strcasecmp(value, papsOfferings[j]) == 0)
-                     {
-                         nCurrentOff = j;
-                         break;
-                     }
-                 }
-                 if (nCurrentOff >= 0) /* existing offering */
-                   panOfferingLayers[i] = nCurrentOff;
-                 else /*new offering */
-                 {
-                     papsOfferings[nOfferings] = msStrdup(value);
-                     panOfferingLayers[i] = nOfferings;
-                     nOfferings++;
-                 }
-             }
-         }
-         
-         if (nOfferings > 0)
-         {
-             for (i=0; i<nOfferings; i++)
-             {
-                 psOfferingNode = 
-                   xmlNewChild(psMainNode, NULL,BAD_CAST "ObservationOffering", NULL);
-                 xmlNewNsProp(psOfferingNode, psNsGml,
-                              BAD_CAST "id", BAD_CAST papsOfferings[i]);
-                 for (j=0; j<map->numlayers; j++)
-                 {
-                     if (panOfferingLayers[j] == i) /*first layer of the offering */
-                       break;
-                 }
-
-                 /*description*/
-                 value = msOWSLookupMetadata(&(lp->metadata), "S",
-                                             "offering_description");
-                 if (value)
-                     psNode = xmlNewChild(psOfferingNode, psNsGml, BAD_CAST "description", BAD_CAST value);
-                 else
-                     xmlAddSibling(psNode, xmlNewComment(BAD_CAST "WARNING: Optional metadata \"sos_offering_description\" missing for gml:description"));
-
-                 /*name*/
-                 lp = (GET_LAYER(map, j)); /*first layer*/
-                 value = msOWSLookupMetadata(&(lp->metadata), "S", "offering_name");
-                 if (value)
-                     psNode = xmlNewChild(psOfferingNode, psNsGml, BAD_CAST "name", BAD_CAST value);
-                 else
-                     xmlAddSibling(psNode, xmlNewComment(BAD_CAST "WARNING: Optional metadata \"sos_offering_name\" missing for gml:name"));
-
-                 /* srsName */                 
-                 value = msOWSLookupMetadata(&(map->web.metadata), "SO", "srs");
-
-                 if (value)
-                     msLibXml2GenerateList(psOfferingNode, psNsGml, "srsName", value, ' ');
-                 else                  
-                     xmlAddSibling(psNode, xmlNewComment(BAD_CAST "WARNING: Required metadata \"sos_srs\" missing for gml:srsName"));
-
-                 /*bounding box */
-                 /*TODO : if sos_offering_extent does not exist compute extents 
-                          Check also what happen if epsg not present */
-                 value = msOWSLookupMetadata(&(lp->metadata), "S", "offering_extent");
-                 if (value)
-                 {
-                     char **tokens;
-                     int n;
-                     tokens = msStringSplit(value, ',', &n);
-                     if (tokens==NULL || n != 4) {
-                         msSetError(MS_SOSERR, "Wrong number of arguments for sos_offering_extent.",
-                                    "msSOSGetCapabilities()");
-                         return msSOSException(map, "sos_offering_extent", "InvalidParameterValue");
-                     }
-                     value = msOWSGetEPSGProj(&(lp->projection),
-                                              &(lp->metadata), "SO", MS_TRUE);
-                     if (value)
-                       psNode = xmlAddChild(psOfferingNode, msGML3BoundedBy(psNsGml, atof(tokens[0]), atof(tokens[1]), atof(tokens[2]), atof(tokens[3]), value));
-                     msFreeCharArray(tokens, n);
-                       
-                 }
-
-                 /* intended application */
-
-                 value = msOWSLookupMetadata(&(lp->metadata), "S", "offering_intendedapplication");
-
-                 if (value)
-                     psNode = xmlNewChild(psOfferingNode, psNsSos, BAD_CAST "intendedApplication", BAD_CAST value);
-                 else
-                     xmlAddSibling(psNode, xmlNewComment(BAD_CAST "WARNING: Optional metadata \"sos_offering_intendedapplication\" missing for sos:intendedApplication"));
-
-                 /*time*/
-                 value = msOWSLookupMetadata(&(lp->metadata), "S", 
-                                             "offering_timeextent");
-                 if (value)
-                 {
-                     char **tokens;
-                     int n;
-                     char *pszEndTime = NULL;
-                     tokens = msStringSplit(value, '/', &n);
-                     if (tokens==NULL || (n != 1 && n!=2)) {
-                         msSetError(MS_SOSERR, "Wrong number of arguments for sos_offering_timeextent.",
-                                    "msSOSGetCapabilities()");
-                         return msSOSException(map, "sos_offering_timeextent", "InvalidParameterValue");
-                     }
-
-                     if (n == 2) /* end time is empty. It is going to be set as "now*/
-                       pszEndTime = tokens[1];
-
-                     psNode = xmlAddChild(psOfferingNode, msSOSAddTimeNode(psNsSos, psNsGml, tokens[0], pszEndTime));
-                     msFreeCharArray(tokens, n);
-                     
-                 }
-                 
-                 /*procedure : output all procedure links for the offering */
-                 for (j=0; j<map->numlayers; j++)
-                 {
-                     if (panOfferingLayers[j] == i)
-                     {
-                         value = msOWSLookupMetadata(&(GET_LAYER(map, j)->metadata), "S", 
-                                                     "procedure");
-                         if (value && strlen(value) > 0)
-                         {   
-                             /*value could be a list of procedure*/
-                             char **tokens;
-                             int n = 0;
-                             tokens = msStringSplit(value, ' ', &n);
-                             for (k=0; k<n; k++)
-                             {
-                                 /*TODO review the urn output */
-                                 snprintf(szTmp, sizeof(szTmp), "%s", "urn:ogc:def:procedure:");
-                                 pszTmp = msStringConcatenate(pszTmp, szTmp);
-                                 pszTmp = msStringConcatenate(pszTmp, tokens[k]);
-
-                                 psNode = 
-                                   xmlNewChild(psOfferingNode, NULL, BAD_CAST "procedure", NULL);
-                                 /* xmlNewNsProp(psNode, xmlNewNs(NULL, BAD_CAST "http://www.w3.org/1999/xlink", BAD_CAST "xlink"), BAD_CAST "href", BAD_CAST pszTmp); */
-                                 xmlNewNsProp(psNode, psNsXLink, BAD_CAST "href", BAD_CAST pszTmp);
-                                 msFree(pszTmp);
-                                 pszTmp = NULL;
-                             }
-                             msFreeCharArray(tokens, n);
-                         }
-                         else if ((value = msOWSLookupMetadata(&(GET_LAYER(map,j)->metadata), "S", 
-                                                               "procedure_item")))
-                         {
-                             /* if a procedure_item is used, it means that the procedure 
-                                (or sensor) need to be extracted from the data. Thus we need to 
-                                query the layer and get the values from each feature */
-                          
-
-                             lpTmp = GET_LAYER(map,j);
-                             if (lpTmp->template == NULL)
-                               lpTmp->template = msStrdup("ttt");
-
-                             map->query.type = MS_QUERY_BY_RECT;
-                             map->query.mode = MS_QUERY_MULTIPLE;
-                             map->query.layer = j;
-                             map->query.rect = map->extent;
-                             msQueryByRect(map);
-
-                             /*check if the attribute specified in the procedure_item is available
-                               on the layer*/
-                             iItemPosition = -1;
-                             if (msLayerGetItems(lpTmp) == MS_SUCCESS &&
-                                 lpTmp->resultcache && lpTmp->resultcache->numresults > 0)
-                             {
-                                 for(k=0; k<lpTmp->numitems; k++) 
-                                 {
-                                     if (strcasecmp(lpTmp->items[k], value) == 0)
-                                     {
-                                         iItemPosition = k;
-                                         break;
-                                     }
-                                 }
-                                 if (iItemPosition == -1)
-                                 {
-                                     msSetError(MS_SOSERR, "procedure_item %s could not be found on the layer %s",
-                                    "msSOSGetCapabilities()", value, lpTmp->name);
-                                     return msSOSException(map, "mapserv", "NoApplicableCode");
-                                 }
-
-                                 /*for each selected feature, grab the value of the prodedire_item*/
-                                 /* do not duplicate sensor ids if they are the same */
-
-                                 /*keep list of distinct procedures*/
-                                 papsProcedures = 
-                                   (char **)malloc(sizeof(char *) * lpTmp->resultcache->numresults);
-                                 nDistinctProcedures = 0;
-                                 for(k=0; k<lpTmp->resultcache->numresults; k++)
-                                   papsProcedures[k] = NULL;
-                                 
-
-                                 for(k=0; k<lpTmp->resultcache->numresults; k++)
-                                 {      
-                                     msInitShape(&sShape);
-                                     status = msLayerGetShape(lp, &sShape, &(lpTmp->resultcache->results[k]));
-                                     if(status != MS_SUCCESS) 
-                                       continue;
-
-                                     if (sShape.values[iItemPosition])
-                                     {
-                                         pszProcedure = msStringConcatenate(pszProcedure, sShape.values[iItemPosition]);
-                                         if (!_IsInList(papsProcedures, nDistinctProcedures, pszProcedure))
-                                         {
-                                               papsProcedures[nDistinctProcedures] = msStrdup(pszProcedure);
-                                               nDistinctProcedures++;
-                                               snprintf(szTmp, sizeof(szTmp), "%s", "urn:ogc:def:procedure:");
-                                               pszTmp = msStringConcatenate(pszTmp, szTmp);
-                                               pszTmp = msStringConcatenate(pszTmp, pszProcedure);
-
-                                               psNode = 
-                                               xmlNewChild(psOfferingNode, NULL, BAD_CAST "procedure", NULL);
-                                               xmlNewNsProp(psNode,
-                                                            xmlNewNs(NULL, BAD_CAST "http://www.w3.org/1999/xlink", 
-                                                                     BAD_CAST "xlink"), BAD_CAST "href", BAD_CAST pszTmp);
-                                               msFree(pszTmp);
-                                               pszTmp = NULL;
-                                               
-                                           }
-                                         msFree(pszProcedure);
-                                         pszProcedure = NULL;
-                                     }
-                                 }
-                                 for(k=0; k<lpTmp->resultcache->numresults; k++)
-                                   if (papsProcedures[k] != NULL)
-                                     msFree(papsProcedures[k]);
-                                 msFree(papsProcedures);
-                                 
-                             }
-                             else
-                             {  
-                                 msSetError(MS_SOSERR, "Invalid procedure %s", "msSOSGetCapabilities()", value);
-                                 return msSOSException(map, "procedure", "InvalidParameterValue");
-                             }
-                         }
-                         else
-                         {
-                              msSetError(MS_SOSERR, "Mandatory metadata procedure_item could not be found on the layer %s",
-                                            "msSOSGetCapabilities()", GET_LAYER(map,j)->name);
-                                 return msSOSException(map, "mapserv", "NoApplicableCode");
-                         }
-                         
-                     }
-                 }
-                 /*observed property */
-                 /* observed property are equivalent to layers. We can group 
-                    sevaral layers using the same sos_observedproperty_id. The 
-                    components are the attributes. Components are exposed 
-                    using the metadata sos_%s_aliasl */
-                 
-                 nProperties = 0;
-                 papszProperties = 
-                   (char **)malloc(sizeof(char *)*map->numlayers);
-                 
-                 for (j=0; j<map->numlayers; j++)
-                 {
-                     if (panOfferingLayers[j] == i)
-                     {
-                         if ((value = 
-                             msOWSLookupMetadata(&(GET_LAYER(map, j)->metadata), "S", 
-                                                 "observedproperty_id")))
-                         {
-                             for (k=0; k<nProperties; k++)
-                             {
-                                 if (strcasecmp(value, papszProperties[k]) == 0)
-                                   break;
-                             }
-                             if (k == nProperties)/*not found*/
-                             {
-                                 papszProperties[nProperties] = msStrdup(value);
-                                 nProperties++;
-                                 lpTmp = GET_LAYER(map, j);
-                                 if (msLayerOpen(lpTmp) == MS_SUCCESS && msLayerGetItems(lpTmp) == MS_SUCCESS)
-                                 {
-                                     msSOSAddPropertyNode(psNsSwe, psNsXLink, psOfferingNode, 
-                                                          lpTmp, psNsGml, NULL);
-                                     msLayerClose(lpTmp);
-                                 }
-                             }
-                         }
-                     }
-                 }
-                 for (j=0; j<nProperties; j++)
-                   free(papszProperties[j]);
-                 free(papszProperties);
-
-                 psNode = xmlNewChild(psOfferingNode, NULL, BAD_CAST "featureOfInterest", NULL);
-                 xmlNewNsProp(psNode, psNsXLink, BAD_CAST "href", BAD_CAST "urn:ogc:def:feature:OGC-SWE:3:transient");
-                 
-                 psNode = xmlNewChild(psOfferingNode, NULL, BAD_CAST "responseFormat", 
-                                      BAD_CAST pszSOSGetObservationMimeType);
-                 psNode = xmlNewChild(psOfferingNode, NULL, BAD_CAST "resultModel", 
-                                      BAD_CAST "om:Observation");
-                 psNode = xmlNewChild(psOfferingNode, NULL, BAD_CAST "resultModel", 
-                                      BAD_CAST "om:Measurement");
-                 psNode = xmlNewChild(psOfferingNode, NULL, BAD_CAST "responseMode", 
-                                      BAD_CAST "inline");
-
-             }/*end of offerings*/
-         }
-     
-         if (papsOfferings && nOfferings > 0)
-         {
-             for (i=0; i<nOfferings; i++)
-               msFree(papsOfferings[i]);
-         }
-         msFree(papsOfferings);
-         if(panOfferingLayers)
-           msFree(panOfferingLayers);        
-
-     }/* end of offerings */
-
-     if ( msIO_needBinaryStdout() == MS_FAILURE )
-       return MS_FAILURE;
-     
-     if (encoding)
-         msIO_printf("Content-type: text/xml; charset=%s%c%c", encoding,10,10);
-     else
-         msIO_printf("Content-type: text/xml%c%c",10,10);
-    
-    /*TODO* : check the encoding validity. Internally libxml2 uses UTF-8
-    msOWSPrintEncodeMetadata(stdout, &(map->web.metadata),
-                             "SO", "encoding", OWS_NOERR,
-                             "<?xml version='1.0' encoding=\"%s\" standalone=\"no\" ?>\n",
-                             "ISO-8859-1");
-    */
-     /*xmlDocDumpFormatMemoryEnc(psDoc, &buffer, &size, (encoding ? encoding : "ISO-8859-1"), 1);*/
-     
-     /* xmlDocDump crashs withe the prebuild windows binaries distibutes at the libxml site???.
-      It works with locally build binaries*/
-     
-     context = msIO_getHandler(stdout);
-
-     xmlDocDumpFormatMemoryEnc(psDoc, &buffer, &size, (encoding ? encoding : "ISO-8859-1"), 1);
-     msIO_contextWrite(context, buffer, size);
-     xmlFree(buffer);
-
-     /*free buffer and the document */
-     /*xmlFree(buffer);*/
-     xmlFreeDoc(psDoc);
-     xmlFreeNs(psNsGml);
-     xmlFreeNs(psNsSos);
-     xmlFreeNs(psNsOgc);
-     xmlFreeNs(psNsSwe);
-
-     free(xsi_schemaLocation);
-     free(schemalocation);
-     msFree(script_url);
-
-    /*
-     *Free the global variables that may
-     *have been allocated by the parser.
-     */
-     xmlCleanupParser();
-
-
-    return(MS_SUCCESS);
-
-    
-     /*
-    nSize = sizeof(workbuffer);
-    nSize = nSize-1;*/ /* the last character for the '\0' */
-     
-    /*
-    if (size > nSize)
-    {
-         iIndice = 0;
-         while ((iIndice + nSize) <= size)
-         {
-             snprintf(workbuffer, (sizeof(workbuffer)-1), "%s", buffer+iIndice );
-             workbuffer[sizeof(workbuffer)-1] = '\0';
-             msIO_printf("%s", workbuffer);
-
-             iIndice +=nSize;
-         }
-         if (iIndice < size)
-         {
-              sprintf(workbuffer, "%s", buffer+iIndice );
-              msIO_printf("%s", workbuffer);
-         }
-     }
-    else
-    {
-        msIO_printf("%s", buffer);
-    }
-    */
+           iIndice +=nSize;
+       }
+       if (iIndice < size)
+       {
+            sprintf(workbuffer, "%s", buffer+iIndice );
+            msIO_printf("%s", workbuffer);
+       }
+   }
+  else
+  {
+      msIO_printf("%s", buffer);
+  }
+  */
 }
 
 /************************************************************************/
@@ -1803,7 +1684,8 @@ int msSOSGetCapabilities(mapObj *map, sosParamsObj *sosparams, cgiRequestObj *re
 /*                                                                      */
 /*      GetObservation request handler                                  */
 /************************************************************************/
-int msSOSGetObservation(mapObj *map, sosParamsObj *sosparams, cgiRequestObj *req, owsRequestObj *ows_request) {
+int msSOSGetObservation(mapObj *map, sosParamsObj *sosparams, cgiRequestObj *req, owsRequestObj *ows_request)
+{
   char *schemalocation = NULL;
   char *xsi_schemaLocation = NULL;
   const char *pszTmp = NULL, *pszTmp2 = NULL;
@@ -1811,7 +1693,7 @@ int msSOSGetObservation(mapObj *map, sosParamsObj *sosparams, cgiRequestObj *req
   const char *user_namespace_prefix = "ms";
   char *script_url=NULL;
   int i, j, k, bLayerFound = 0;
-  layerObj *lp = NULL, *lpfirst = NULL; 
+  layerObj *lp = NULL, *lpfirst = NULL;
   const char *pszTimeExtent=NULL, *pszTimeField=NULL, *pszValue=NULL;
   FilterEncodingNode *psFilterNode = NULL;
   rectObj sBbox;
@@ -1884,14 +1766,15 @@ int msSOSGetObservation(mapObj *map, sosParamsObj *sosparams, cgiRequestObj *req
 
   /*validate if offering exists*/
   for (i=0; i<map->numlayers; i++) {
-      pszTmp = msOWSLookupMetadata(&(GET_LAYER(map, i)->metadata), "S", "offering_id");
-    if (pszTmp && (strcasecmp(pszTmp, sosparams->pszOffering) == 0) && 
+    pszTmp = msOWSLookupMetadata(&(GET_LAYER(map, i)->metadata), "S", "offering_id");
+    if (pszTmp && (strcasecmp(pszTmp, sosparams->pszOffering) == 0) &&
         (msIntegerInArray(GET_LAYER(map, i)->index, ows_request->enabled_layers, ows_request->numlayers)))
       break;
   }
 
   if (i==map->numlayers) {
-    msSetError(MS_SOSERR, "Offering %s not found.", "msSOSGetObservation()", sosparams->pszOffering);
+    msSetError(MS_SOSERR, "Offering %s not found. A layer might be disabled for \
+this request. Check sos/ows_enable_request settings.", "msSOSGetObservation()", sosparams->pszOffering);
     return msSOSException(map, "offering", "InvalidParameterValue");
   }
 
@@ -1902,20 +1785,20 @@ int msSOSGetObservation(mapObj *map, sosParamsObj *sosparams, cgiRequestObj *req
 
   bLayerFound = 0;
   tokens = msStringSplit(sosparams->pszObservedProperty, ',', &n);
-    
+
   for (i=0; i<map->numlayers; i++) {
     pszTmp = msOWSLookupMetadata(&(GET_LAYER(map, i)->metadata), "S", "offering_id");
     pszTmp2 = msOWSLookupMetadata(&(GET_LAYER(map, i)->metadata), "S", "observedproperty_id");
 
     GET_LAYER(map, i)->status = MS_OFF;
-        
+
     if (pszTmp && pszTmp2) {
-      if (strcasecmp(pszTmp, sosparams->pszOffering) == 0) {   
+      if (strcasecmp(pszTmp, sosparams->pszOffering) == 0) {
         if (tokens && n > 0) {
           for (j=0; j<n; j++) {
             if(strcasecmp(pszTmp2, tokens[j]) == 0) {
               GET_LAYER(map, i)->status = MS_ON;
-              //opLayerName = msStrdup(GET_LAYER(map, i)->name);
+              /* opLayerName = msStrdup(GET_LAYER(map, i)->name); */
               opLayerName = GET_LAYER(map, i)->name;
               /* Force setting a template to enable query. */
               if (!GET_LAYER(map, i)->template)
@@ -1924,7 +1807,7 @@ int msSOSGetObservation(mapObj *map, sosParamsObj *sosparams, cgiRequestObj *req
               break;
             }
           }
-        }                 
+        }
       }
     }
   }
@@ -1935,7 +1818,7 @@ int msSOSGetObservation(mapObj *map, sosParamsObj *sosparams, cgiRequestObj *req
     msSetError(MS_SOSERR, "ObservedProperty %s not found.", "msSOSGetObservation()", sosparams->pszObservedProperty);
     return msSOSException(map, "observedproperty", "InvalidParameterValue");
   }
-     
+
   /* apply procedure : could be a comma separated list.
      set status to on those layers that have the sos_procedure metadata
      equals to this parameter. Note that the layer should already have it's status at ON
@@ -1944,16 +1827,16 @@ int msSOSGetObservation(mapObj *map, sosParamsObj *sosparams, cgiRequestObj *req
   if (sosparams->pszProcedure) {
     bLayerFound = 0;
     tokens = msStringSplit(sosparams->pszProcedure, ',', &n);
-        
+
     if (tokens && n > 0) {
       for (i=0; i<map->numlayers; i++) {
         if(GET_LAYER(map, i)->status == MS_ON) {
           pszValue =  msOWSLookupMetadata(&(GET_LAYER(map, i)->metadata), "S", "procedure");
-                    
+
           if (pszValue) {
             /* the procedure metadata can be a list "sensor1 sensor2..."*/
             tokens1 = msStringSplit(pszValue, ' ', &n1);
-                        
+
             for (j=0; j<n; j++) {
               for (k=0; k<n1; k++) {
                 if (strcasecmp(tokens1[k], tokens[j]) == 0) { /* found */
@@ -1976,7 +1859,7 @@ int msSOSGetObservation(mapObj *map, sosParamsObj *sosparams, cgiRequestObj *req
               return msSOSException(map, "procedure", "InvalidParameterValue");
             }
           }
-                    
+
           /* if there is a procedure_item defined on the layer, we will */
           /* use it to set the filter parameter of the layer */
 
@@ -1984,7 +1867,7 @@ int msSOSGetObservation(mapObj *map, sosParamsObj *sosparams, cgiRequestObj *req
 
             lp = GET_LAYER(map, i);
 
-/* HACK BEGIN */
+            /* HACK BEGIN */
 
             if (msOWSLookupMetadata(&(GET_LAYER(map,i)->metadata), "S", "procedure") == NULL) {
               /* if sos_procedure_item is used, and sos_procedure is not, it means that */
@@ -2012,19 +1895,19 @@ int msSOSGetObservation(mapObj *map, sosParamsObj *sosparams, cgiRequestObj *req
                 }
                 if (iItemPosition == -1) {
                   msSetError(MS_SOSERR, "sos_procedure_item %s could not be found on the layer %s",
-                  "msSOSGetCapabilities()", pszProcedureItem, lp->name);
+                             "msSOSGetCapabilities()", pszProcedureItem, lp->name);
                   return msSOSException(map, "mapserv", "NoApplicableCode");
                 }
 
                 /*for each selected feature, grab the value of the procedure_item*/
                 bLayerFound = 0;
 
-                for(k=0; k<lp->resultcache->numresults; k++) {      
+                for(k=0; k<lp->resultcache->numresults; k++) {
                   msInitShape(&sShape);
                   status = msLayerGetShape(lp, &sShape, &(lp->resultcache->results[k]));
-                  if(status != MS_SUCCESS) 
+                  if(status != MS_SUCCESS)
                     continue;
- 
+
                   if (sShape.values[iItemPosition]) {
                     tokens = msStringSplit(sosparams->pszProcedure, ',', &n);
                     for (j=0; j<n; j++) {
@@ -2034,58 +1917,54 @@ int msSOSGetObservation(mapObj *map, sosParamsObj *sosparams, cgiRequestObj *req
                       }
                     }
                   }
-                          
+
                   if (bLayerFound)
                     break;
                 }
 
-               if (bLayerFound == 0) {  
-                 msSetError(MS_SOSERR, "Invalid procedure value %s", "msSOSGetCapabilities()", sosparams->pszProcedure);
-                 return msSOSException(map, "procedure", "InvalidParameterValue");
-               }
-             }
+                if (bLayerFound == 0) {
+                  msSetError(MS_SOSERR, "Invalid procedure value %s", "msSOSGetCapabilities()", sosparams->pszProcedure);
+                  return msSOSException(map, "procedure", "InvalidParameterValue");
+                }
+              }
             }
-/* HACK END */
+            /* HACK END */
 
             pszBuffer = NULL;
             if (&lp->filter) {
               if (lp->filter.string && strlen(lp->filter.string) > 0)
                 freeExpression(&lp->filter);
-            } 
-                                
+            }
+
             /*The filter should reflect the underlying db*/
             /*for ogr add a where clause */
             bSpatialDB = 0;
             if (lp->connectiontype == MS_POSTGIS ||  lp->connectiontype == MS_ORACLESPATIAL || lp->connectiontype == MS_SDE ||     lp->connectiontype == MS_OGR)
               bSpatialDB = 1;
-                                    
-                                    
+
+
             if (bSpatialDB) {
               if (lp->connectiontype != MS_OGR)
                 pszBuffer = msStringConcatenate(pszBuffer, "(");
               else
                 pszBuffer = msStringConcatenate(pszBuffer, "WHERE ");
-            }
-            else
+            } else
               pszBuffer = msStringConcatenate(pszBuffer, "(");
 
             for (j=0; j<n; j++) {
               if (j > 0)
                 pszBuffer = msStringConcatenate(pszBuffer, " OR ");
-                            
+
               pszBuffer = msStringConcatenate(pszBuffer, "(");
-                            
-              if (!bSpatialDB)
-              {
-                  pszBuffer = msStringConcatenate(pszBuffer, "'[");
-                  pszBuffer = msStringConcatenate(pszBuffer, (char *)pszProcedureItem);
-              }
-              else
-              {
-                  pszEscapedStr = msLayerEscapePropertyName(lp, (char *)pszProcedureItem);
-                  pszBuffer = msStringConcatenate(pszBuffer, pszEscapedStr);
-                  msFree(pszEscapedStr);
-                  pszEscapedStr = NULL;
+
+              if (!bSpatialDB) {
+                pszBuffer = msStringConcatenate(pszBuffer, "'[");
+                pszBuffer = msStringConcatenate(pszBuffer, (char *)pszProcedureItem);
+              } else {
+                pszEscapedStr = msLayerEscapePropertyName(lp, (char *)pszProcedureItem);
+                pszBuffer = msStringConcatenate(pszBuffer, pszEscapedStr);
+                msFree(pszEscapedStr);
+                pszEscapedStr = NULL;
               }
 
               if (!bSpatialDB)
@@ -2097,7 +1976,7 @@ int msSOSGetObservation(mapObj *map, sosParamsObj *sosparams, cgiRequestObj *req
               msFree(pszEscapedStr);
               pszBuffer = msStringConcatenate(pszBuffer,  "')");
             }
-                                
+
             if (!bSpatialDB || lp->connectiontype != MS_OGR)
               pszBuffer = msStringConcatenate(pszBuffer, ")");
 
@@ -2105,12 +1984,12 @@ int msSOSGetObservation(mapObj *map, sosParamsObj *sosparams, cgiRequestObj *req
             if (pszBuffer)
               msFree(pszBuffer);
           }
-        }       
+        }
       }
       msFreeCharArray(tokens, n);
     }
   }
-              
+
   /* -------------------------------------------------------------------- */
   /*      supports 2 types of gml:Time : TimePeriod and TimeInstant :     */
   /*      - <gml:TimePeriod>                                              */
@@ -2186,8 +2065,7 @@ int msSOSGetObservation(mapObj *map, sosParamsObj *sosparams, cgiRequestObj *req
               /*we should turn the layer off since the eventTime is not in the time extent*/
               GET_LAYER(map, i)->status = MS_OFF;
             }
-          }
-          else
+          } else
             msLayerSetTimeFilter((GET_LAYER(map, i)), pszTimeString, pszTimeField);
         }
       }
@@ -2199,19 +2077,18 @@ int msSOSGetObservation(mapObj *map, sosParamsObj *sosparams, cgiRequestObj *req
   /*bbox*/
   /* this is a gml feature
   <gml:Envelope xmlns:gml="http://www.opengis.net/gml">
-  <gml:lowerCorner srsName="EPSG:4326">-66 43</gml:lowerCorner> 
-  <upperCorner srsName="EPSG:4326">-62 45</upperCorner> 
+  <gml:lowerCorner srsName="EPSG:4326">-66 43</gml:lowerCorner>
+  <upperCorner srsName="EPSG:4326">-62 45</upperCorner>
   </gml:Envelope>
   */
 
-  if (sosparams->pszFeatureOfInterest) 
-  {
+  if (sosparams->pszFeatureOfInterest) {
     int bValid = 0;
     CPLXMLNode *psRoot=NULL;
     char *pszSRS = NULL;
 
     psRoot = CPLParseXMLString(sosparams->pszFeatureOfInterest);
-    if(!psRoot) {       
+    if(!psRoot) {
       msSetError(MS_SOSERR, "Invalid gml:Envelope value given for featureOfInterest.", "msSOSGetObservation()");
       return msSOSException(map, "featureofinterest", "InvalidParameterValue");
     }
@@ -2221,8 +2098,8 @@ int msSOSGetObservation(mapObj *map, sosParamsObj *sosparams, cgiRequestObj *req
 
     /* TODO we should reproject the bbox to the map projection if there is an srs defined */
     if (!bValid) {
-        msSetError(MS_SOSERR, "Invalid gml:Envelope value given for featureOfInterest %s.", "msSOSGetObservation()", sosparams->pszEventTime);
-        return msSOSException(map, "featureofinterest", "InvalidParameterValue");
+      msSetError(MS_SOSERR, "Invalid gml:Envelope value given for featureOfInterest %s.", "msSOSGetObservation()", sosparams->pszEventTime);
+      return msSOSException(map, "featureofinterest", "InvalidParameterValue");
     }
     map->extent.minx = sBbox.minx;
     map->extent.miny = sBbox.miny;
@@ -2273,11 +2150,11 @@ int msSOSGetObservation(mapObj *map, sosParamsObj *sosparams, cgiRequestObj *req
               msSetError(MS_SOSERR, "Could not set output projection to \"%s\"", "msSOSGetObservation()", sosparams->pszSrsName);
               return msSOSException(map, "mapserv", "NoApplicableCode");
             }
-                 
+
             iUnits = GetMapserverUnitUsingProj(&(map->projection));
             if (iUnits != -1)
               map->units = iUnits;
-                
+
             msFreeProjection(&po);
             break;
           }
@@ -2288,8 +2165,7 @@ int msSOSGetObservation(mapObj *map, sosParamsObj *sosparams, cgiRequestObj *req
         msSetError(MS_SOSERR, "srsName value \"%s\" unsupported / invalid", "msSOSGetObservation()", sosparams->pszSrsName);
         return msSOSException(map, "srsName", "InvalidParameterValue");
       }
-    }
-    else {
+    } else {
       msSetError(MS_SOSERR, "MAP.WEB.METADATA.sos_srs not set", "msSOSGetObservation()");
       return msSOSException(map, "mapserv", "NoApplicableCode");
     }
@@ -2309,7 +2185,7 @@ int msSOSGetObservation(mapObj *map, sosParamsObj *sosparams, cgiRequestObj *req
       if (lp->status == MS_ON) {
         /* preparse parser so that alias for fields can be used */
         FLTPreParseFilterForAlias(psFilterNode, map, i, "S");
-        /* validate that the property names used are valid 
+        /* validate that the property names used are valid
           (there is a corresponding layer attribute) */
         if (msLayerOpen(lp) == MS_SUCCESS && msLayerGetItems(lp) == MS_SUCCESS) {
           if (msSOSValidateFilter(psFilterNode, lp)== MS_FALSE) {
@@ -2325,311 +2201,292 @@ int msSOSGetObservation(mapObj *map, sosParamsObj *sosparams, cgiRequestObj *req
     FLTFreeFilterEncodingNode(psFilterNode);
   }
 
-  
 
-      /* this is just a fall back if bbox is enetered. The bbox parameter is not supported
-         by the sos specs */
-      if (sosparams->pszBBox && !sosparams->pszFeatureOfInterest) {
-        char **tokens;
-        int n;
 
-        tokens = msStringSplit(sosparams->pszBBox, ',', &n);
-        if (tokens==NULL || n != 4) {
-          msSetError(MS_SOSERR, "Wrong number of arguments for bounding box.", "msSOSGetObservation()");
-          return msSOSException(map, "bbox", "InvalidParameterValue");
-        }
-        sBbox.minx = atof(tokens[0]);
-        sBbox.miny = atof(tokens[1]);
-        sBbox.maxx = atof(tokens[2]);
-        sBbox.maxy = atof(tokens[3]);
-        msFreeCharArray(tokens, n);
-      }
+  /* this is just a fall back if bbox is enetered. The bbox parameter is not supported
+     by the sos specs */
+  if (sosparams->pszBBox && !sosparams->pszFeatureOfInterest) {
+    char **tokens;
+    int n;
 
-      /* do the query if the filter encoding (pszResult) is not part of the request.
-         If pszResult is available, the query on the layers will be done when the filter
-         is parsed*/
-      if (!sosparams->pszResult) {
-        map->query.type = MS_QUERY_BY_RECT;
-        map->query.mode = MS_QUERY_MULTIPLE;
-        map->query.layer = -1;
-        map->query.rect = sBbox;
-        msQueryByRect(map);
-      }
+    tokens = msStringSplit(sosparams->pszBBox, ',', &n);
+    if (tokens==NULL || n != 4) {
+      msSetError(MS_SOSERR, "Wrong number of arguments for bounding box.", "msSOSGetObservation()");
+      return msSOSException(map, "bbox", "InvalidParameterValue");
+    }
+    sBbox.minx = atof(tokens[0]);
+    sBbox.miny = atof(tokens[1]);
+    sBbox.maxx = atof(tokens[2]);
+    sBbox.maxy = atof(tokens[3]);
+    msFreeCharArray(tokens, n);
+  }
 
-      /*get the first layers of the offering*/
-      for (i=0; i<map->numlayers; i++) {
-        pszTmp = msOWSLookupMetadata(&(GET_LAYER(map, i)->metadata), "S", "offering_id");
-        if (pszTmp && (strcasecmp(pszTmp, sosparams->pszOffering) == 0)) {
-          lp = (GET_LAYER(map, i));
-          break;
-        }
-      }
-    
-    /* build xml return tree*/
-
-    psNsSos = xmlNewNs(NULL, BAD_CAST "http://www.opengis.net/sos/1.0", BAD_CAST "sos");
-    psNsGml = xmlNewNs(NULL, BAD_CAST "http://www.opengis.net/gml", BAD_CAST "gml");
-    psNsOm = xmlNewNs(NULL, BAD_CAST pszOMNamespaceUri, BAD_CAST pszOMNamespacePrefix);
-    psNsSwe = xmlNewNs(NULL, BAD_CAST "http://www.opengis.net/swe/1.0.1", BAD_CAST "swe");
-    psNsXLink = xmlNewNs(NULL, BAD_CAST MS_OWSCOMMON_W3C_XLINK_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_W3C_XLINK_NAMESPACE_PREFIX);
-    psNsMs = xmlNewNs(NULL, BAD_CAST user_namespace_uri, BAD_CAST user_namespace_prefix);
-
-    psDoc = xmlNewDoc(BAD_CAST "1.0");
-    psRootNode = xmlNewNode(NULL, BAD_CAST "ObservationCollection");
-    xmlDocSetRootElement(psDoc, psRootNode);
-
-    xmlSetNs(psRootNode,  xmlNewNs(psRootNode, BAD_CAST "http://www.opengis.net/gml", BAD_CAST "gml"));
-    xmlSetNs(psRootNode,  xmlNewNs(psRootNode, BAD_CAST "http://www.opengis.net/ows/1.1", BAD_CAST "ows"));
-    xmlSetNs(psRootNode,  xmlNewNs(psRootNode, BAD_CAST "http://www.opengis.net/swe/1.0.1", BAD_CAST "swe"));
-    xmlSetNs(psRootNode,  xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_W3C_XLINK_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_W3C_XLINK_NAMESPACE_PREFIX));
-    xmlSetNs(psRootNode,  xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_W3C_XSI_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_W3C_XSI_NAMESPACE_PREFIX));
-    xmlSetNs(psRootNode,  xmlNewNs(psRootNode, BAD_CAST pszSOSNamespaceUri, BAD_CAST pszSOSNamespacePrefix));
-    xmlSetNs(psRootNode,  xmlNewNs(psRootNode, BAD_CAST user_namespace_uri, BAD_CAST user_namespace_prefix));
-    xmlSetNs(psRootNode,  xmlNewNs(psRootNode, BAD_CAST "http://www.opengis.net/om/1.0", BAD_CAST "om"));
- 
-    xmlNewNsProp(psRootNode, psNsGml, BAD_CAST "id", BAD_CAST sosparams->pszOffering);
-
-    schemalocation = msEncodeHTMLEntities(msOWSGetSchemasLocation(map));
-
-    if ((script_url=msOWSGetOnlineResource(map, "SO", "onlineresource", req)) == NULL)
-        return msSOSException(map, "NoApplicableCode", "NoApplicableCode");
-
-    xsi_schemaLocation = msStrdup("http://www.opengis.net/om/1.0 ");
-    xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, schemalocation);
-    xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, "/om/1.0.0/om.xsd ");
-    xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, (char *) user_namespace_uri);
-    xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, " ");
-    xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, (char *) script_url);
-    xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, "service=WFS&version=1.1.0&request=DescribeFeatureType&typename=");
-    xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, (char *) opLayerName);
-    xmlNewNsProp(psRootNode, NULL, BAD_CAST "xsi:schemaLocation", BAD_CAST xsi_schemaLocation);
-
-    /* description */
-    pszTmp = msOWSLookupMetadata(&(lp->metadata), "S", "offering_description");
-    if (pszTmp)
-    {
-        psNode = xmlNewChild(psRootNode, NULL, BAD_CAST "description", BAD_CAST pszTmp);
-        xmlSetNs(psNode, xmlNewNs(psNode, BAD_CAST "http://www.opengis.net/gml", BAD_CAST "gml"));
-    }
-
-    /* name */
-    pszTmp = msOWSLookupMetadata(&(lp->metadata), "S", "offering_name");
-    if (pszTmp)
-    {
-        psNode = xmlNewChild(psRootNode, NULL, BAD_CAST "name", BAD_CAST pszTmp);
-        xmlSetNs(psNode, xmlNewNs(psNode, BAD_CAST "http://www.opengis.net/gml", BAD_CAST "gml"));
-    }
-
-    /* extent */
-    pszTmp = msOWSLookupMetadata(&(lp->metadata), "S", "offering_extent");
-
-    if (pszTmp)
-    {
-       char **tokens;
-       int n;
-       rectObj envelope;
-
-       pszTmp2 = msOWSGetEPSGProj(&(map->projection), &(lp->metadata), "SO", MS_TRUE);
-
-       tokens = msStringSplit(pszTmp, ',', &n);
-       if (tokens==NULL || n != 4) {
-          msSetError(MS_SOSERR, "Wrong number of arguments for sos_offering_extent.",
-          "msSOSGetCapabilities()");
-          return msSOSException(map, "sos_offering_extent", "InvalidParameterValue");
-       }
+  /* do the query if the filter encoding (pszResult) is not part of the request.
+     If pszResult is available, the query on the layers will be done when the filter
+     is parsed*/
+  if (!sosparams->pszResult) {
+    map->query.type = MS_QUERY_BY_RECT;
+    map->query.mode = MS_QUERY_MULTIPLE;
+    map->query.layer = -1;
+    map->query.rect = sBbox;
+    msQueryByRect(map);
+  }
 
-       envelope.minx = atof(tokens[0]);
-       envelope.miny = atof(tokens[1]);
-       envelope.maxx = atof(tokens[2]);
-       envelope.maxy = atof(tokens[3]);
+  /*get the first layers of the offering*/
+  for (i=0; i<map->numlayers; i++) {
+    pszTmp = msOWSLookupMetadata(&(GET_LAYER(map, i)->metadata), "S", "offering_id");
+    if (pszTmp && (strcasecmp(pszTmp, sosparams->pszOffering) == 0)) {
+      lp = (GET_LAYER(map, i));
+      break;
+    }
+  }
 
-       if (map && msProjectionsDiffer(&map->projection, &lp->projection) == MS_TRUE) {
-         if (msProjectRect(&lp->projection, &map->projection, &envelope) == MS_FAILURE){ 
-           msSetError(MS_SOSERR, "Coordinates transformation failed.  Raised in msProjectRect() of file %s line %d", "msSOSGetCapabilities()", __FILE__, __LINE__);
-           return msSOSException(map, "sos_offering_extent", "InvalidParameterValue");
-         }
-       }
+  /* build xml return tree*/
 
-       psNode = xmlAddChild(psRootNode, msGML3BoundedBy(psNsGml, envelope.minx, envelope.miny, envelope.maxx, envelope.maxy, pszTmp2));
-       msFreeCharArray(tokens, n);
-    }
+  psNsSos = xmlNewNs(NULL, BAD_CAST "http://www.opengis.net/sos/1.0", BAD_CAST "sos");
+  psNsGml = xmlNewNs(NULL, BAD_CAST "http://www.opengis.net/gml", BAD_CAST "gml");
+  psNsOm = xmlNewNs(NULL, BAD_CAST pszOMNamespaceUri, BAD_CAST pszOMNamespacePrefix);
+  psNsSwe = xmlNewNs(NULL, BAD_CAST "http://www.opengis.net/swe/1.0.1", BAD_CAST "swe");
+  psNsXLink = xmlNewNs(NULL, BAD_CAST MS_OWSCOMMON_W3C_XLINK_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_W3C_XLINK_NAMESPACE_PREFIX);
+  psNsMs = xmlNewNs(NULL, BAD_CAST user_namespace_uri, BAD_CAST user_namespace_prefix);
 
-    /* time 
-    pszTmp = msOWSLookupMetadata(&(lp->metadata), "S","offering_timeextent");
-    if (pszTmp)
-    {
-        char **tokens;
-        int n;
-        char *pszEndTime = NULL;
-        tokens = msStringSplit(pszTmp, '/', &n);
-        if (tokens==NULL || (n != 1 && n!=2)) {
-            msSetError(MS_SOSERR, "Wrong number of arguments for sos_offering_timeextent.",
-                       "msSOSGetCapabilities()");
-            return msSOSException(map, "sos_offering_timeextent", "InvalidParameterValue");
-        }
-    */ 
-    /*    if (n == 2) */ /* end time is empty. It is going to be set as "now" */
-    /*      pszEndTime = tokens[1];
-    
-          psNode = xmlAddChild(psRootNode, msSOSAddTimeNode(xmlNewNs(NULL, BAD_CAST pszOMNamespaceUri, BAD_CAST pszOMNamespacePrefix), tokens[0], pszEndTime));
-        psNode = xmlAddChild(psRootNode, msSOSAddTimeNode(psNsOm, psNsGml, tokens[0], pszEndTime));
-        msFreeCharArray(tokens, n);
-                     
+  psDoc = xmlNewDoc(BAD_CAST "1.0");
+  psRootNode = xmlNewNode(NULL, BAD_CAST "ObservationCollection");
+  xmlDocSetRootElement(psDoc, psRootNode);
+
+  xmlSetNs(psRootNode,  xmlNewNs(psRootNode, BAD_CAST "http://www.opengis.net/gml", BAD_CAST "gml"));
+  xmlSetNs(psRootNode,  xmlNewNs(psRootNode, BAD_CAST "http://www.opengis.net/ows/1.1", BAD_CAST "ows"));
+  xmlSetNs(psRootNode,  xmlNewNs(psRootNode, BAD_CAST "http://www.opengis.net/swe/1.0.1", BAD_CAST "swe"));
+  xmlSetNs(psRootNode,  xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_W3C_XLINK_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_W3C_XLINK_NAMESPACE_PREFIX));
+  xmlSetNs(psRootNode,  xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_W3C_XSI_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_W3C_XSI_NAMESPACE_PREFIX));
+  xmlSetNs(psRootNode,  xmlNewNs(psRootNode, BAD_CAST pszSOSNamespaceUri, BAD_CAST pszSOSNamespacePrefix));
+  xmlSetNs(psRootNode,  xmlNewNs(psRootNode, BAD_CAST user_namespace_uri, BAD_CAST user_namespace_prefix));
+  xmlSetNs(psRootNode,  xmlNewNs(psRootNode, BAD_CAST "http://www.opengis.net/om/1.0", BAD_CAST "om"));
+
+  xmlNewNsProp(psRootNode, psNsGml, BAD_CAST "id", BAD_CAST sosparams->pszOffering);
+
+  schemalocation = msEncodeHTMLEntities(msOWSGetSchemasLocation(map));
+
+  if ((script_url=msOWSGetOnlineResource(map, "SO", "onlineresource", req)) == NULL)
+    return msSOSException(map, "NoApplicableCode", "NoApplicableCode");
+
+  xsi_schemaLocation = msStrdup("http://www.opengis.net/om/1.0 ");
+  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, schemalocation);
+  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, "/om/1.0.0/om.xsd ");
+  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, (char *) user_namespace_uri);
+  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, " ");
+  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, (char *) script_url);
+  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, "service=WFS&version=1.1.0&request=DescribeFeatureType&typename=");
+  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, (char *) opLayerName);
+  xmlNewNsProp(psRootNode, NULL, BAD_CAST "xsi:schemaLocation", BAD_CAST xsi_schemaLocation);
+
+  /* description */
+  pszTmp = msOWSLookupMetadata(&(lp->metadata), "S", "offering_description");
+  if (pszTmp) {
+    psNode = xmlNewChild(psRootNode, NULL, BAD_CAST "description", BAD_CAST pszTmp);
+    xmlSetNs(psNode, xmlNewNs(psNode, BAD_CAST "http://www.opengis.net/gml", BAD_CAST "gml"));
+  }
+
+  /* name */
+  pszTmp = msOWSLookupMetadata(&(lp->metadata), "S", "offering_name");
+  if (pszTmp) {
+    psNode = xmlNewChild(psRootNode, NULL, BAD_CAST "name", BAD_CAST pszTmp);
+    xmlSetNs(psNode, xmlNewNs(psNode, BAD_CAST "http://www.opengis.net/gml", BAD_CAST "gml"));
+  }
+
+  /* extent */
+  pszTmp = msOWSLookupMetadata(&(lp->metadata), "S", "offering_extent");
+
+  if (pszTmp) {
+    char **tokens;
+    int n;
+    rectObj envelope;
+
+    pszTmp2 = msOWSGetEPSGProj(&(map->projection), &(lp->metadata), "SO", MS_TRUE);
+
+    tokens = msStringSplit(pszTmp, ',', &n);
+    if (tokens==NULL || n != 4) {
+      msSetError(MS_SOSERR, "Wrong number of arguments for sos_offering_extent.",
+                 "msSOSGetCapabilities()");
+      return msSOSException(map, "sos_offering_extent", "InvalidParameterValue");
     }
-    */
 
-    if (sosparams->pszResultModel && strcasecmp(sosparams->pszResultModel, "om:Measurement") != 0 &&
-        strcasecmp(sosparams->pszResultModel, "om:Observation") != 0)
-    {
-        msSetError(MS_SOSERR, "resultModel should be om:Measurement or om:Observation", "msSOSGetObservation()");
-        free(xsi_schemaLocation);
-        free(schemalocation);
-        return msSOSException(map, "resultModel", "InvalidParameterValue");
+    envelope.minx = atof(tokens[0]);
+    envelope.miny = atof(tokens[1]);
+    envelope.maxx = atof(tokens[2]);
+    envelope.maxy = atof(tokens[3]);
+
+    if (map && msProjectionsDiffer(&map->projection, &lp->projection) == MS_TRUE) {
+      if (msProjectRect(&lp->projection, &map->projection, &envelope) == MS_FAILURE) {
+        msSetError(MS_SOSERR, "Coordinates transformation failed.  Raised in msProjectRect() of file %s line %d", "msSOSGetCapabilities()", __FILE__, __LINE__);
+        return msSOSException(map, "sos_offering_extent", "InvalidParameterValue");
+      }
     }
 
-    else {
-       /* output result members */
-       for (i=0; i<map->numlayers; i++)
-       {
-          if (GET_LAYER(map, i)->resultcache && GET_LAYER(map, i)->resultcache->numresults > 0)
-            {       
-                msLayerGetItems((GET_LAYER(map, i)));
-                pszTmp = msOWSLookupMetadata(&(map->web.metadata), "SO", "maxfeatures");
-                if (pszTmp != NULL)
-                  n1 = atoi(pszTmp);
+    psNode = xmlAddChild(psRootNode, msGML3BoundedBy(psNsGml, envelope.minx, envelope.miny, envelope.maxx, envelope.maxy, pszTmp2));
+    msFreeCharArray(tokens, n);
+  }
+
+  /* time
+  pszTmp = msOWSLookupMetadata(&(lp->metadata), "S","offering_timeextent");
+  if (pszTmp)
+  {
+      char **tokens;
+      int n;
+      char *pszEndTime = NULL;
+      tokens = msStringSplit(pszTmp, '/', &n);
+      if (tokens==NULL || (n != 1 && n!=2)) {
+          msSetError(MS_SOSERR, "Wrong number of arguments for sos_offering_timeextent.",
+                     "msSOSGetCapabilities()");
+          return msSOSException(map, "sos_offering_timeextent", "InvalidParameterValue");
+      }
+  */
+  /*    if (n == 2) */ /* end time is empty. It is going to be set as "now" */
+  /*      pszEndTime = tokens[1];
+
+        psNode = xmlAddChild(psRootNode, msSOSAddTimeNode(xmlNewNs(NULL, BAD_CAST pszOMNamespaceUri, BAD_CAST pszOMNamespacePrefix), tokens[0], pszEndTime));
+      psNode = xmlAddChild(psRootNode, msSOSAddTimeNode(psNsOm, psNsGml, tokens[0], pszEndTime));
+      msFreeCharArray(tokens, n);
+
+  }
+  */
+
+  if (sosparams->pszResultModel && strcasecmp(sosparams->pszResultModel, "om:Measurement") != 0 &&
+      strcasecmp(sosparams->pszResultModel, "om:Observation") != 0) {
+    msSetError(MS_SOSERR, "resultModel should be om:Measurement or om:Observation", "msSOSGetObservation()");
+    free(xsi_schemaLocation);
+    free(schemalocation);
+    return msSOSException(map, "resultModel", "InvalidParameterValue");
+  }
+
+  else {
+    /* output result members */
+    for (i=0; i<map->numlayers; i++) {
+      if (GET_LAYER(map, i)->resultcache && GET_LAYER(map, i)->resultcache->numresults > 0) {
+        msLayerGetItems((GET_LAYER(map, i)));
+        pszTmp = msOWSLookupMetadata(&(map->web.metadata), "SO", "maxfeatures");
+        if (pszTmp != NULL)
+          n1 = atoi(pszTmp);
+        else
+          n1 = 0;
+
+        if (sosparams->pszResultModel == NULL || strcasecmp(sosparams->pszResultModel, "om:Measurement") == 0) {
+          for(j=0; j<GET_LAYER(map, i)->resultcache->numresults; j++) {
+            msSOSAddMemberNode(psNsGml, psNsOm, psNsSwe, psNsXLink, psNsMs, psRootNode, map, (GET_LAYER(map, i)), j, script_url, opLayerName);
+            if (j == n1-1)
+              break;
+          }
+        } else { /*assuming here that pszResultModel = observation */
+          /*layer does not define a procedure_item: this means one procedure per
+            layer defined using sos_procedure)*/
+          if (msOWSLookupMetadata(&(GET_LAYER(map, i)->metadata), "S", "procedure_item") == NULL) {
+            pszProcedure = msOWSLookupMetadata(&(lp->metadata), "S", "procedure");
+            psObservationNode = msSOSAddMemberNodeObservation(psNsGml, psNsSos, psNsOm, psNsSwe, psNsXLink, psRootNode, map, (GET_LAYER(map, i)),
+                                pszProcedure);
+            /*add a result node*/
+            psResultNode = xmlNewChild(psObservationNode, NULL, BAD_CAST "result", NULL);
+            for(j=0; j<GET_LAYER(map, i)->resultcache->numresults; j++) {
+              /*add a block separator*/
+              if (j > 0) {
+                pszBlockSep = msOWSLookupMetadata(&(map->web.metadata), "S",
+                                                  "encoding_blockSeparator");
+                if (pszBlockSep)
+                  xmlNodeAddContent(psResultNode, BAD_CAST pszBlockSep);
                 else
-                  n1 = 0;
-
-                if (sosparams->pszResultModel == NULL || strcasecmp(sosparams->pszResultModel, "om:Measurement") == 0) 
-                  {
-                      for(j=0; j<GET_LAYER(map, i)->resultcache->numresults; j++) 
-                        {
-                            msSOSAddMemberNode(psNsGml, psNsOm, psNsSwe, psNsXLink, psNsMs, psRootNode, map, (GET_LAYER(map, i)), j, script_url, opLayerName);
-                            if (j == n1-1) 
-                              break;
-                        }
-                  }
-                else /*assuming here that pszResultModel = observation */
-                  {
-                      /*layer does not define a procedure_item: this means one procedure per 
-                        layer defined using sos_procedure)*/
-                      if (msOWSLookupMetadata(&(GET_LAYER(map, i)->metadata), "S", "procedure_item") == NULL)
-                        {
-                            pszProcedure = msOWSLookupMetadata(&(lp->metadata), "S", "procedure");
-                            psObservationNode = msSOSAddMemberNodeObservation(psNsGml, psNsSos, psNsOm, psNsSwe, psNsXLink, psRootNode, map, (GET_LAYER(map, i)),
-                                                                              pszProcedure);
-                            /*add a result node*/
-                            psResultNode = xmlNewChild(psObservationNode, NULL, BAD_CAST "result", NULL);
-                            for(j=0; j<GET_LAYER(map, i)->resultcache->numresults; j++) 
-                              {
-                                  /*add a block separator*/
-                                  if (j > 0)
-                                    {
-                                        pszBlockSep = msOWSLookupMetadata(&(map->web.metadata), "S", 
-                                                                          "encoding_blockSeparator");
-                                        if (pszBlockSep)
-                                          xmlNodeAddContent(psResultNode, BAD_CAST pszBlockSep);
-                                        else
-                                          xmlNodeAddContent(psResultNode, BAD_CAST "\n");
-                                    }
-                                  pszResult = msSOSReturnMemberResult((GET_LAYER(map, i)), j, NULL);
-                                  if (pszResult)
-                                    {   
-                                        xmlNodeAddContent(psResultNode, BAD_CAST pszResult);
-                                        msFree(pszResult);
-                                    }
-                              }
-                        }
-                      /*this is the case where procedure_item is used. Needs more management since
-                        the same data on a layer contains different procedures (procedures are
-                        one of the fields of the record)*/
-                      else
-                        {
-                        
-                            for(j=0; j<GET_LAYER(map, i)->resultcache->numresults; j++) 
-                              {
-                                  pszResult = msSOSReturnMemberResult((GET_LAYER(map, i)), j, &pszProcedureValue);
-                                  if (!pszProcedureValue || !pszResult)
-                                    continue;
-                                  for (k=0; k<nDiffrentProc; k++)
-                                    {
-                                        if (strcasecmp(paDiffrentProc[k].pszProcedure, pszProcedureValue) == 0)
-                                          {
-                                              pszBlockSep = msOWSLookupMetadata(&(map->web.metadata), "S", 
-                                                                                "encoding_blockSeparator");
-                                              if (pszBlockSep)
-                                                xmlNodeAddContent(paDiffrentProc[k].psResultNode, BAD_CAST pszBlockSep);
-                                              else
-                                                xmlNodeAddContent(paDiffrentProc[k].psResultNode, BAD_CAST "\n");
-                                              xmlNodeAddContent(paDiffrentProc[k].psResultNode, BAD_CAST pszResult);
-                                              break;
-                                          }
-                                    }
-                                  if (k == nDiffrentProc) /*a new procedure*/
-                                    {
-                                        nDiffrentProc++;
-                                        if (paDiffrentProc == NULL)
-                                          paDiffrentProc = (SOSProcedureNode *)malloc(sizeof(SOSProcedureNode));
-                                        else
-                                          paDiffrentProc = (SOSProcedureNode *)realloc(paDiffrentProc, 
-                                                                                       sizeof(SOSProcedureNode)
-                                                                                       *nDiffrentProc);
-
-                                        paDiffrentProc[nDiffrentProc-1].pszProcedure = msStrdup(pszProcedureValue);
-                                        psObservationNode = msSOSAddMemberNodeObservation(psNsGml, psNsSos, psNsOm, psNsSwe, psNsXLink, psRootNode, map, 
-                                                                                          (GET_LAYER(map, i)),
-                                                                                          pszProcedureValue);
-                                        msFree(pszProcedureValue);
-                                
-                                        paDiffrentProc[nDiffrentProc-1].psResultNode = 
-                                          xmlNewChild(psObservationNode, NULL, BAD_CAST "result", NULL);
-
-                                        xmlNodeAddContent(paDiffrentProc[nDiffrentProc-1].psResultNode, BAD_CAST pszResult);
-                                        msFree(pszResult);
-                                    }
-                              }
-                            if (paDiffrentProc)
-                              {
-                                  for (k=0; k<nDiffrentProc; k++)
-                                    msFree(paDiffrentProc[k].pszProcedure);
-                                  free(paDiffrentProc);
-                              }
-                        }
-                  }
+                  xmlNodeAddContent(psResultNode, BAD_CAST "\n");
+              }
+              pszResult = msSOSReturnMemberResult((GET_LAYER(map, i)), j, NULL);
+              if (pszResult) {
+                xmlNodeAddContent(psResultNode, BAD_CAST pszResult);
+                msFree(pszResult);
+              }
             }
-       }
+          }
+          /*this is the case where procedure_item is used. Needs more management since
+            the same data on a layer contains different procedures (procedures are
+            one of the fields of the record)*/
+          else {
+
+            for(j=0; j<GET_LAYER(map, i)->resultcache->numresults; j++) {
+              pszResult = msSOSReturnMemberResult((GET_LAYER(map, i)), j, &pszProcedureValue);
+              if (!pszProcedureValue || !pszResult)
+                continue;
+              for (k=0; k<nDiffrentProc; k++) {
+                if (strcasecmp(paDiffrentProc[k].pszProcedure, pszProcedureValue) == 0) {
+                  pszBlockSep = msOWSLookupMetadata(&(map->web.metadata), "S",
+                                                    "encoding_blockSeparator");
+                  if (pszBlockSep)
+                    xmlNodeAddContent(paDiffrentProc[k].psResultNode, BAD_CAST pszBlockSep);
+                  else
+                    xmlNodeAddContent(paDiffrentProc[k].psResultNode, BAD_CAST "\n");
+                  xmlNodeAddContent(paDiffrentProc[k].psResultNode, BAD_CAST pszResult);
+                  break;
+                }
+              }
+              if (k == nDiffrentProc) { /*a new procedure*/
+                nDiffrentProc++;
+                if (paDiffrentProc == NULL)
+                  paDiffrentProc = (SOSProcedureNode *)malloc(sizeof(SOSProcedureNode));
+                else
+                  paDiffrentProc = (SOSProcedureNode *)realloc(paDiffrentProc,
+                                   sizeof(SOSProcedureNode)
+                                   *nDiffrentProc);
+
+                paDiffrentProc[nDiffrentProc-1].pszProcedure = msStrdup(pszProcedureValue);
+                psObservationNode = msSOSAddMemberNodeObservation(psNsGml, psNsSos, psNsOm, psNsSwe, psNsXLink, psRootNode, map,
+                                    (GET_LAYER(map, i)),
+                                    pszProcedureValue);
+                msFree(pszProcedureValue);
+
+                paDiffrentProc[nDiffrentProc-1].psResultNode =
+                  xmlNewChild(psObservationNode, NULL, BAD_CAST "result", NULL);
+
+                xmlNodeAddContent(paDiffrentProc[nDiffrentProc-1].psResultNode, BAD_CAST pszResult);
+                msFree(pszResult);
+              }
+            }
+            if (paDiffrentProc) {
+              for (k=0; k<nDiffrentProc; k++)
+                msFree(paDiffrentProc[k].pszProcedure);
+              free(paDiffrentProc);
+            }
+          }
+        }
+      }
     }
-   
-    /* output results */    
-    if (encoding)
-        msIO_printf("Content-type: text/xml; charset=%s%c%c", encoding,10,10);
-    else
-        msIO_printf("Content-type: text/xml%c%c",10,10);
-
-     context = msIO_getHandler(stdout);
-     xmlDocDumpFormatMemoryEnc(psDoc, &buffer, &size, (encoding ? encoding : "ISO-8859-1"), 1);
-     msIO_contextWrite(context, buffer, size);
-     free(schemalocation);
-     free(xsi_schemaLocation);
-     xmlFreeNs(psNsSos);
-     xmlFreeNs(psNsGml);
-     xmlFreeNs(psNsOm);
-     xmlFreeNs(psNsSwe);
-     xmlFreeNs(psNsXLink);
-     xmlFreeNs(psNsMs);
-     xmlFree(buffer);
-     msFree(script_url);
-
-    /*free  document */
-     xmlFreeDoc(psDoc);
-     /*
-     *Free the global variables that may
-     *have been allocated by the parser.
-     */
-     xmlCleanupParser();
-     
-
-    return(MS_SUCCESS);
+  }
+
+  /* output results */
+  if (encoding)
+    msIO_setHeader("Content-Type","text/xml; charset=%s", encoding);
+  else
+    msIO_setHeader("Content-Type","text/xml");
+  msIO_sendHeaders();
+
+  context = msIO_getHandler(stdout);
+  xmlDocDumpFormatMemoryEnc(psDoc, &buffer, &size, (encoding ? encoding : "ISO-8859-1"), 1);
+  msIO_contextWrite(context, buffer, size);
+  free(schemalocation);
+  free(xsi_schemaLocation);
+  xmlFreeNs(psNsSos);
+  xmlFreeNs(psNsGml);
+  xmlFreeNs(psNsOm);
+  xmlFreeNs(psNsSwe);
+  xmlFreeNs(psNsXLink);
+  xmlFreeNs(psNsMs);
+  xmlFree(buffer);
+  msFree(script_url);
+
+  /*free  document */
+  xmlFreeDoc(psDoc);
+  /*
+  *Free the global variables that may
+  *have been allocated by the parser.
+  */
+  xmlCleanupParser();
+
+
+  return(MS_SUCCESS);
 }
 
 
@@ -2639,7 +2496,8 @@ int msSOSGetObservation(mapObj *map, sosParamsObj *sosparams, cgiRequestObj *req
 /*                                                                      */
 /*      Describe sensor request handler.                               */
 /************************************************************************/
-int msSOSDescribeSensor(mapObj *map, sosParamsObj *sosparams, owsRequestObj *ows_request) {
+int msSOSDescribeSensor(mapObj *map, sosParamsObj *sosparams, owsRequestObj *ows_request)
+{
   char *pszEncodedUrl = NULL;
   const char *pszId = NULL, *pszUrl = NULL;
   int i = 0, j=0, k=0;
@@ -2679,20 +2537,21 @@ int msSOSDescribeSensor(mapObj *map, sosParamsObj *sosparams, owsRequestObj *ows
           pszProcedureURI = msStringConcatenate(pszProcedureURI, tokens[k]);
           if ( (pszProcedureURI && strcasecmp(pszProcedureURI, sosparams->pszProcedure) == 0) &&
                (msIntegerInArray(lp->index, ows_request->enabled_layers, ows_request->numlayers)) ) {
-            bFound = 1; 
+            bFound = 1;
             pszProcedureId = msStrdup(tokens[k]);
             msFree(pszProcedureURI);
-            msFreeCharArray(tokens, n);
             break;
           }
+          msFree(pszProcedureURI);
         }
       }
+      msFreeCharArray(tokens, n);
       if (bFound) {
         pszUrl = msOWSLookupMetadata(&(lp->metadata), "S", "describesensor_url");
         if (pszUrl) {
           pszTmp = msStrdup(pszUrl);
 
-          /* %procedure% is the hardcoded variable name to use 
+          /* %procedure% is the hardcoded variable name to use
              within sos_describesensor_url */
           tmpstr = (char *)malloc(sizeof(char)*strlen("procedure") + 3);
           sprintf(tmpstr,"%%%s%%", "procedure");
@@ -2700,20 +2559,18 @@ int msSOSDescribeSensor(mapObj *map, sosParamsObj *sosparams, owsRequestObj *ows
             pszTmp = msCaseReplaceSubstring(pszTmp, tmpstr, pszProcedureId);
           msFree(tmpstr);
 
-          pszEncodedUrl = msEncodeHTMLEntities(pszTmp); 
+          pszEncodedUrl = msEncodeHTMLEntities(pszTmp);
           msIO_printf("Location: %s\n\n", pszEncodedUrl);
           msFree(pszTmp);
           msFree(pszEncodedUrl);
           msFree(pszProcedureId);
           return(MS_SUCCESS);
-        }
-        else {
+        } else {
           msSetError(MS_SOSERR, "Missing mandatory metadata sos_describesensor_url on layer %s", "msSOSDescribeSensor()", lp->name);
           return msSOSException(map, "sos_describesensor_url", "MissingParameterValue");
         }
       }
-    }
-    else if ((pszId = msOWSLookupMetadata(&(lp->metadata), "S", "procedure_item"))) {   
+    } else if ((pszId = msOWSLookupMetadata(&(lp->metadata), "S", "procedure_item"))) {
       iItemPosition = -1;
       if (msLayerOpen(lp) == MS_SUCCESS && msLayerGetItems(lp) == MS_SUCCESS) {
         for(j=0; j<lp->numitems; j++) {
@@ -2735,12 +2592,12 @@ int msSOSDescribeSensor(mapObj *map, sosParamsObj *sosparams, owsRequestObj *ows
         msQueryByRect(map);
 
         msLayerGetItems(lp);
-                
+
         if (lp->resultcache && lp->resultcache->numresults > 0) {
-          for(j=0; j<lp->resultcache->numresults; j++) {      
-            msInitShape(&sShape);     
+          for(j=0; j<lp->resultcache->numresults; j++) {
+            msInitShape(&sShape);
             status = msLayerGetShape(lp, &sShape, &(lp->resultcache->results[j]));
-            if(status != MS_SUCCESS) 
+            if(status != MS_SUCCESS)
               continue;
 
             if (sShape.values[iItemPosition]) {
@@ -2749,7 +2606,7 @@ int msSOSDescribeSensor(mapObj *map, sosParamsObj *sosparams, owsRequestObj *ows
               if (strcasecmp(pszProcedureURI, sosparams->pszProcedure) == 0) {
                 pszUrl = msOWSLookupMetadata(&(lp->metadata), "S", "describesensor_url");
                 pszProcedureId = msStrdup(sShape.values[iItemPosition]);
-                if (pszUrl) {   
+                if (pszUrl) {
                   pszTmp = msStrdup(pszUrl);
 
                   /* %procedure% is the hardcoded variable names to use
@@ -2760,12 +2617,11 @@ int msSOSDescribeSensor(mapObj *map, sosParamsObj *sosparams, owsRequestObj *ows
                     pszTmp = msCaseReplaceSubstring(pszTmp, tmpstr, pszProcedureId);
                   msFree(tmpstr);
 
-                  pszEncodedUrl = msEncodeHTMLEntities(pszTmp); 
+                  pszEncodedUrl = msEncodeHTMLEntities(pszTmp);
                   msIO_printf("Location: %s\n\n", pszEncodedUrl);
                   msFree(pszTmp);
                   return(MS_SUCCESS);
-                }
-                else {
+                } else {
                   msSetError(MS_SOSERR, "Missing mandatory metadata sos_describesensor_url on layer %s", "msSOSDescribeSensor()", lp->name);
                   return msSOSException(map, "mapserv", "NoApplicableCode");
                 }
@@ -2848,7 +2704,8 @@ int msSOSDescribeObservationType(mapObj *map, sosParamsObj *sosparams, cgiReques
 ** - If this is a valid request then it is processed and MS_SUCCESS is returned
 **   on success, or MS_FAILURE on failure.
 */
-int msSOSDispatch(mapObj *map, cgiRequestObj *req, owsRequestObj *ows_request) {
+int msSOSDispatch(mapObj *map, cgiRequestObj *req, owsRequestObj *ows_request)
+{
 #if defined(USE_SOS_SVR) && defined(USE_LIBXML2)
   int returnvalue = MS_DONE;
   sosParamsObj *paramsObj = (sosParamsObj *)calloc(1, sizeof(sosParamsObj));
@@ -2867,13 +2724,12 @@ int msSOSDispatch(mapObj *map, cgiRequestObj *req, owsRequestObj *ows_request) {
     }
 
     msOWSRequestLayersEnabled(map, "S", paramsObj->pszRequest, ows_request);
-    if (ows_request->numlayers == 0)
-    {
-        msSetError(MS_SOSERR, "SOS request not enabled. Check sos/ows_enable_request settings.", "msSOSDispatch()");
-        msSOSFreeParamsObj(paramsObj);
-        free(paramsObj);
-        paramsObj = NULL;
-        return msSOSException(map, "request", "InvalidParameterValue");
+    if (ows_request->numlayers == 0) {
+      msSetError(MS_SOSERR, "SOS request not enabled. Check sos/ows_enable_request settings.", "msSOSDispatch()");
+      msSOSFreeParamsObj(paramsObj);
+      free(paramsObj);
+      paramsObj = NULL;
+      return msSOSException(map, "request", "InvalidParameterValue");
     }
 
     if (strcasecmp(paramsObj->pszRequest, "GetCapabilities") == 0) {
@@ -2887,7 +2743,7 @@ int msSOSDispatch(mapObj *map, cgiRequestObj *req, owsRequestObj *ows_request) {
     else if (strcasecmp(paramsObj->pszRequest, "DescribeSensor") == 0 ||
              strcasecmp(paramsObj->pszRequest, "GetObservation") == 0 ||
              strcasecmp(paramsObj->pszRequest, "DescribeObservationType") == 0
-    ) { 
+            ) {
       /* check version */
       if (!paramsObj->pszVersion) {
         msSetError(MS_SOSERR, "Missing VERSION parameter", "msSOSDispatch()");
@@ -2912,22 +2768,20 @@ int msSOSDispatch(mapObj *map, cgiRequestObj *req, owsRequestObj *ows_request) {
         returnvalue = msSOSGetObservation(map, paramsObj, req, ows_request);
 
       else if (strcasecmp(paramsObj->pszRequest, "DescribeObservationType") == 0)
-          returnvalue = msSOSDescribeObservationType(map, paramsObj, req, ows_request);
+        returnvalue = msSOSDescribeObservationType(map, paramsObj, req, ows_request);
 
       msSOSFreeParamsObj(paramsObj);
       free(paramsObj);
       paramsObj = NULL;
       return returnvalue;
-    }
-    else {
+    } else {
       msSetError(MS_SOSERR, "Invalid REQUEST parameter: %s", "msSOSDispatch()", paramsObj->pszRequest);
       msSOSFreeParamsObj(paramsObj);
       free(paramsObj);
       paramsObj = NULL;
       return msSOSException(map, "request", "InvalidParameterValue");
     }
-  }
-  else
+  } else
     return MS_DONE;  /* Not an SOS request */
 #else
   msSetError(MS_SOSERR, "SOS support is not available.", "msSOSDispatch()");
@@ -2937,7 +2791,8 @@ int msSOSDispatch(mapObj *map, cgiRequestObj *req, owsRequestObj *ows_request) {
 
 #if defined(USE_SOS_SVR) && defined(USE_LIBXML2)
 
-int msSOSParseRequest(mapObj *map, cgiRequestObj *request, sosParamsObj *sosparams) {
+int msSOSParseRequest(mapObj *map, cgiRequestObj *request, sosParamsObj *sosparams)
+{
   int i;
   xmlDocPtr doc;
   xmlXPathContextPtr context;
@@ -3003,9 +2858,9 @@ int msSOSParseRequest(mapObj *map, cgiRequestObj *request, sosParamsObj *sospara
 
     /* register namespaces */
     if(xmlXPathRegisterNs(context, (xmlChar *)"sos", (xmlChar *)"http://www.opengis.net/sos/1.0") != 0 ||
-       xmlXPathRegisterNs(context, (xmlChar *)"ows", (xmlChar *)"http://www.opengis.net/ows/1.1") != 0 ||
-       xmlXPathRegisterNs(context, (xmlChar *)"ogc", (xmlChar *)"http://www.opengis.net/ogc") != 0 ||
-       xmlXPathRegisterNs(context, (xmlChar *)"gml", (xmlChar *)"http://www.opengis.net/gml") != 0) {
+        xmlXPathRegisterNs(context, (xmlChar *)"ows", (xmlChar *)"http://www.opengis.net/ows/1.1") != 0 ||
+        xmlXPathRegisterNs(context, (xmlChar *)"ogc", (xmlChar *)"http://www.opengis.net/ogc") != 0 ||
+        xmlXPathRegisterNs(context, (xmlChar *)"gml", (xmlChar *)"http://www.opengis.net/gml") != 0) {
       msSetError(MS_SOSERR, "Could not register namespaces (xmlXPathRegisterNs)", "msSOSParseRequest()");
       return msSOSException(map, "request", "NoApplicableCode");
     }
@@ -3076,8 +2931,8 @@ int msSOSParseRequest(mapObj *map, cgiRequestObj *request, sosParamsObj *sospara
 
     /* check for Procedure */
     psXPathTmp = msLibXml2GetXPath(doc, context, (xmlChar *)"/sos:DescribeSensor/sos:procedure");
-    
-    if (psXPathTmp) { 
+
+    if (psXPathTmp) {
       nodeset = psXPathTmp->nodesetval;
       sosparams->pszProcedure = (char *)xmlNodeListGetString(doc, nodeset->nodeTab[0]->xmlChildrenNode, 1);
     }
@@ -3162,7 +3017,7 @@ int msSOSParseRequest(mapObj *map, cgiRequestObj *request, sosParamsObj *sospara
       pszTmp = msStringConcatenate(pszTmp, "<ogc:Filter>");
       pszTmp = msStringConcatenate(pszTmp, sosparams->pszResult);
       pszTmp = msStringConcatenate(pszTmp, "</ogc:Filter>");
-      msFree(sosparams->pszResult); 
+      msFree(sosparams->pszResult);
       sosparams->pszResult = msStrdup(pszTmp);
       msFree(pszTmp);
     }
@@ -3193,7 +3048,8 @@ int msSOSParseRequest(mapObj *map, cgiRequestObj *request, sosParamsObj *sospara
   return MS_SUCCESS;
 }
 
-void msSOSFreeParamsObj(sosParamsObj *sosparams) {
+void msSOSFreeParamsObj(sosParamsObj *sosparams)
+{
   if (sosparams) {
     if (sosparams->pszService)
       free(sosparams->pszService);
diff --git a/mapogl.cpp b/mapogl.cpp
index 42aeac6..e22a2cf 100644
--- a/mapogl.cpp
+++ b/mapogl.cpp
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -35,43 +35,43 @@
 #include "mapoglrenderer.h"
 #include "mapoglcontext.h"
 
-MS_CVSID("$Id$")
+
 
 imageObj* createImageObjOgl(OglRenderer* renderer)
-{    
-    if (!renderer->isValid()) return NULL;
-    imageObj* pNewImage = (imageObj*)calloc(1, sizeof(imageObj));
-    if (!pNewImage)
-        return pNewImage;    
-    pNewImage->img.plugin = (void *) renderer;    
+{
+  if (!renderer->isValid()) return NULL;
+  imageObj* pNewImage = (imageObj*)calloc(1, sizeof(imageObj));
+  if (!pNewImage)
     return pNewImage;
+  pNewImage->img.plugin = (void *) renderer;
+  return pNewImage;
 }
 
 OglRenderer* getOglRenderer(imageObj* img)
 {
-    return (OglRenderer*) img->img.plugin;
+  return (OglRenderer*) img->img.plugin;
 }
 
-int msSaveImageOgl(imageObj *img, FILE *fp, outputFormatObj *format)
+int msSaveImageOgl(imageObj *img, mapObj *map, FILE *fp, outputFormatObj *format)
 {
-    rasterBufferObj data;
-    OglRenderer* renderer = getOglRenderer(img);
-    renderer->readRasterBuffer(&data);        
-    return msSaveRasterBuffer(NULL,&data,fp,img->format );
+  rasterBufferObj data;
+  OglRenderer* renderer = getOglRenderer(img);
+  renderer->readRasterBuffer(&data);
+  return msSaveRasterBuffer(NULL,&data,fp,img->format );
 }
 
 int msDrawLineOgl(imageObj *img, shapeObj *p, strokeStyleObj *style)
 {
-    OglRenderer* renderer = getOglRenderer(img);
-    renderer->renderPolyline(p, style->color, style->width, style->patternlength, style->pattern);
-    return MS_SUCCESS;
+  OglRenderer* renderer = getOglRenderer(img);
+  renderer->renderPolyline(p, style->color, style->width, style->patternlength, style->pattern);
+  return MS_SUCCESS;
 }
 
 int msDrawPolygonOgl(imageObj *img, shapeObj *p, colorObj *color)
 {
-    OglRenderer* renderer = getOglRenderer(img);
-    renderer->renderPolygon(p, color, NULL, 0);
-    return MS_SUCCESS;
+  OglRenderer* renderer = getOglRenderer(img);
+  renderer->renderPolygon(p, color, NULL, 0);
+  return MS_SUCCESS;
 }
 
 //void msFreeTileOgl(imageObj *tile)
@@ -81,192 +81,189 @@ int msDrawPolygonOgl(imageObj *img, shapeObj *p, colorObj *color)
 
 int msDrawLineTiledOgl(imageObj *img, shapeObj *p, imageObj *tile)
 {
-    OglRenderer* renderer = getOglRenderer(img);
-    renderer->renderPolylineTile(p, getOglRenderer(tile)->getTexture());
-    return MS_SUCCESS;
+  OglRenderer* renderer = getOglRenderer(img);
+  renderer->renderPolylineTile(p, getOglRenderer(tile)->getTexture());
+  return MS_SUCCESS;
 }
 
 int msDrawPolygonTiledOgl(imageObj *img, shapeObj *p, imageObj *tile)
 {
-    OglRenderer* renderer = getOglRenderer(img);
-    renderer->renderPolygon(p, NULL, NULL, 0.0, getOglRenderer(tile)->getTexture());
-    return MS_SUCCESS;
+  OglRenderer* renderer = getOglRenderer(img);
+  renderer->renderPolygon(p, NULL, NULL, 0.0, getOglRenderer(tile)->getTexture());
+  return MS_SUCCESS;
 }
 
 int msRenderPixmapOgl(imageObj *img, double x, double y,
-            symbolObj *symbol, symbolStyleObj *style)
+                      symbolObj *symbol, symbolStyleObj *style)
 {
-    OglRenderer* renderer = getOglRenderer(img);
-    renderer->renderPixmap(symbol, x, y, style->rotation, style->scale);    
-    return MS_SUCCESS;
+  OglRenderer* renderer = getOglRenderer(img);
+  renderer->renderPixmap(symbol, x, y, style->rotation, style->scale);
+  return MS_SUCCESS;
 }
 
 int msRenderVectorSymbolOgl
-    (imageObj *img, double x, double y,
-            symbolObj *symbol, symbolStyleObj *style)
+(imageObj *img, double x, double y,
+ symbolObj *symbol, symbolStyleObj *style)
 {
-    OglRenderer* renderer = getOglRenderer(img);
-    renderer->renderVectorSymbol(x, y, symbol, style->scale, style->rotation, style->color, style->outlinecolor, style->outlinewidth);        
-    return MS_SUCCESS;
+  OglRenderer* renderer = getOglRenderer(img);
+  renderer->renderVectorSymbol(x, y, symbol, style->scale, style->rotation, style->color, style->outlinecolor, style->outlinewidth);
+  return MS_SUCCESS;
 }
 
 int msRenderTruetypeSymbolOgl(imageObj *img, double x, double y,
-        symbolObj *symbol, symbolStyleObj * style)
+                              symbolObj *symbol, symbolStyleObj * style)
 {
-    OglRenderer* renderer = getOglRenderer(img);
-    double size = style->scale*72.0;    
-    renderer->renderGlyphs(0, 0, style->color, style->outlinecolor, size, symbol->font, symbol->character, style->rotation, NULL, 0, 0);    
-    return MS_SUCCESS;
+  OglRenderer* renderer = getOglRenderer(img);
+  double size = style->scale*72.0;
+  renderer->renderGlyphs(0, 0, style->color, style->outlinecolor, size, symbol->font, symbol->character, style->rotation, NULL, 0, 0);
+  return MS_SUCCESS;
 }
 
 int msRenderTileOgl(imageObj *img, imageObj *tile, double x, double y)
 {
-    OglRenderer* renderer = getOglRenderer(img);    
-    renderer->renderTile(getOglRenderer(tile)->getTexture(), x, y, 0.0);
-    return MS_SUCCESS;
+  OglRenderer* renderer = getOglRenderer(img);
+  renderer->renderTile(getOglRenderer(tile)->getTexture(), x, y, 0.0);
+  return MS_SUCCESS;
 }
 
-int msGetTruetypeTextBBoxOgl(rendererVTableObj *renderer, char *font, double size, char *string, rectObj *rect, double **advances)
-{    
-    if (OglRenderer::getStringBBox(font, size, string, rect, advances))
-    {
-        return MS_SUCCESS;
-    }
-    else
-    {
-        return MS_FAILURE;
-    }
+int msGetTruetypeTextBBoxOgl(rendererVTableObj *renderer, char **fonts, int numfonts, double size, char *string, rectObj *rect, double **advances, int bAdjustBaseline)
+{
+  if (OglRenderer::getStringBBox(fonts[0], size, string, rect, advances)) {
+    return MS_SUCCESS;
+  } else {
+    return MS_FAILURE;
+  }
 }
 
 int msRenderGlyphsOgl(imageObj *img, double x, double y,
-            labelStyleObj *style, char *text)        
+                      labelStyleObj *style, char *text)
 {
-    OglRenderer* renderer = getOglRenderer(img);
-    renderer->renderGlyphs(x, y, style->color, style->outlinecolor, style->size, style->font, text, style->rotation, NULL, 0.0, 0.0);
-    return MS_SUCCESS;
+  OglRenderer* renderer = getOglRenderer(img);
+  renderer->renderGlyphs(x, y, style->color, style->outlinecolor, style->size, style->fonts[0], text, style->rotation, NULL, 0.0, 0.0);
+  return MS_SUCCESS;
 }
 
 int msMergeRasterBufferOgl(imageObj *dest, rasterBufferObj *overlay, double opacity, int srcX, int srcY, int dstX, int dstY, int width, int height)
 {
-    OglRenderer* renderer = getOglRenderer(dest);
-    renderer->drawRasterBuffer(overlay, opacity, srcX, srcY, dstX, dstY, width, height);
-    return MS_SUCCESS;
+  OglRenderer* renderer = getOglRenderer(dest);
+  renderer->drawRasterBuffer(overlay, opacity, srcX, srcY, dstX, dstY, width, height);
+  return MS_SUCCESS;
 }
 
 imageObj* msImageCreateOgl(int width, int height, outputFormatObj *format, colorObj* bg)
 {
-    imageObj *pNewImage = NULL;
-
-    if (format->imagemode != MS_IMAGEMODE_RGB && format->imagemode
-            != MS_IMAGEMODE_RGBA)
-    {
-        msSetError(
-                MS_OGLERR, "OpenGL driver only supports RGB or RGBA pixel models.",
-                "msImageCreateOGL()");
-        return NULL;
-    }
-    return createImageObjOgl(new OglRenderer(width, height, bg));
+  imageObj *pNewImage = NULL;
+
+  if (format->imagemode != MS_IMAGEMODE_RGB && format->imagemode
+      != MS_IMAGEMODE_RGBA) {
+    msSetError(
+      MS_OGLERR, "OpenGL driver only supports RGB or RGBA pixel models.",
+      "msImageCreateOGL()");
+    return NULL;
+  }
+  return createImageObjOgl(new OglRenderer(width, height, bg));
 }
 
-int msRenderEllipseOgl(imageObj *image, double x, double y, 
-            symbolObj *symbol, symbolStyleObj *style)        
+int msRenderEllipseOgl(imageObj *image, double x, double y,
+                       symbolObj *symbol, symbolStyleObj *style)
 {
-    
-    OglRenderer* renderer = getOglRenderer(image);
-    renderer->renderEllipse(x, y, style->rotation, symbol->sizex, symbol->sizey, style->color, style->outlinecolor, style->outlinewidth);
-    return MS_SUCCESS;
+
+  OglRenderer* renderer = getOglRenderer(image);
+  renderer->renderEllipse(x, y, style->rotation, symbol->sizex, symbol->sizey, style->color, style->outlinecolor, style->outlinewidth);
+  return MS_SUCCESS;
 }
 
 int msFreeImageOgl(imageObj *img)
 {
-    OglRenderer* renderer = getOglRenderer(img);
-    if (renderer)
-    {
-        delete renderer;
-    }
-    img->img.plugin=NULL;
-    return MS_SUCCESS;
+  OglRenderer* renderer = getOglRenderer(img);
+  if (renderer) {
+    delete renderer;
+  }
+  img->img.plugin=NULL;
+  return MS_SUCCESS;
 }
 
 int msStartLayerOgl(imageObj *img, mapObj *map, layerObj *layer)
 {
-    getOglRenderer(img)->setTransparency((double)layer->opacity/100);
-    return MS_SUCCESS;
+  getOglRenderer(img)->setTransparency((double)layer->opacity/100);
+  return MS_SUCCESS;
 }
 
 int msEndLayerOgl(imageObj *img, mapObj *map, layerObj *layer)
 {
-    getOglRenderer(img)->setTransparency(1.0);
-    return MS_SUCCESS;
+  getOglRenderer(img)->setTransparency(1.0);
+  return MS_SUCCESS;
 }
 
 int msFreeSymbolOgl(symbolObj *s)
 {
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
-int msGetRasterBufferCopyOgl(imageObj *img, rasterBufferObj *rb) {
-    getOglRenderer(img)->readRasterBuffer(rb);
-    return MS_SUCCESS;
+int msGetRasterBufferCopyOgl(imageObj *img, rasterBufferObj *rb)
+{
+  getOglRenderer(img)->readRasterBuffer(rb);
+  return MS_SUCCESS;
 }
 
 int msGetRasterBufferHandleOgl(imageObj *img, rasterBufferObj * rb)
 {
-    getOglRenderer(img)->readRasterBuffer(rb);
-    return MS_SUCCESS;
+  getOglRenderer(img)->readRasterBuffer(rb);
+  return MS_SUCCESS;
 }
 
-int msInitializeRasterBufferOgl(rasterBufferObj *rb, int width, int height, int mode) 
+int msInitializeRasterBufferOgl(rasterBufferObj *rb, int width, int height, int mode)
 {
-    OglRenderer::initializeRasterBuffer(rb, width, height, mode==MS_IMAGEMODE_RGBA);
-    return MS_SUCCESS;
+  OglRenderer::initializeRasterBuffer(rb, width, height, mode==MS_IMAGEMODE_RGBA);
+  return MS_SUCCESS;
 }
 
 #endif /* USE_OGL */
 
-int msPopulateRendererVTableOGL(rendererVTableObj *renderer) {
+int msPopulateRendererVTableOGL(rendererVTableObj *renderer)
+{
 #ifdef USE_OGL
-        renderer->supports_transparent_layers = 1;
-        renderer->supports_pixel_buffer = 1;
-        renderer->supports_clipping = 0;
-        renderer->use_imagecache = 0;
-        renderer->supports_bitmap_fonts = 0;
-        renderer->default_transform_mode = MS_TRANSFORM_SIMPLIFY;
-        renderer->startLayer = msStartLayerOgl;
-        renderer->endLayer = msEndLayerOgl;        
-        
-        renderer->createImage=&msImageCreateOgl;
-        renderer->saveImage=&msSaveImageOgl;
-        
-        
-        renderer->renderLine=&msDrawLineOgl;
-        renderer->renderPolygon=&msDrawPolygonOgl;
-        renderer->renderGlyphs=&msRenderGlyphsOgl;
-        renderer->renderEllipseSymbol = &msRenderEllipseOgl;
-        renderer->renderVectorSymbol = &msRenderVectorSymbolOgl;
-        renderer->renderPixmapSymbol = &msRenderPixmapOgl;        
-        renderer->renderTruetypeSymbol = &msRenderTruetypeSymbolOgl;
-
-        renderer->renderTile = &msRenderTileOgl;
-        renderer->renderPolygonTiled = &msDrawPolygonTiledOgl;
-        renderer->renderLineTiled = &msDrawLineTiledOgl;
-        
-        renderer->getTruetypeTextBBox = &msGetTruetypeTextBBoxOgl;
-        
-        renderer->getRasterBufferHandle = msGetRasterBufferHandleOgl;
-        renderer->getRasterBufferCopy = msGetRasterBufferCopyOgl;
-        renderer->initializeRasterBuffer = msInitializeRasterBufferOgl;
-        renderer->mergeRasterBuffer = msMergeRasterBufferOgl;        
-        renderer->loadImageFromFile = msLoadMSRasterBufferFromFile;                            
-
-        renderer->freeSymbol = &msFreeSymbolOgl;
-        renderer->freeImage=&msFreeImageOgl;
-
-        return MS_SUCCESS;
-    #else
-        msSetError(MS_MISCERR,"OGL driver requested but it is not compiled in this release",
-                "msPopulateRendererVTableOGL()");
-        return MS_FAILURE;
+  renderer->supports_transparent_layers = 1;
+  renderer->supports_pixel_buffer = 1;
+  renderer->supports_clipping = 0;
+  renderer->use_imagecache = 0;
+  renderer->supports_bitmap_fonts = 0;
+  renderer->default_transform_mode = MS_TRANSFORM_SIMPLIFY;
+  renderer->startLayer = msStartLayerOgl;
+  renderer->endLayer = msEndLayerOgl;
+
+  renderer->createImage=&msImageCreateOgl;
+  renderer->saveImage=&msSaveImageOgl;
+
+
+  renderer->renderLine=&msDrawLineOgl;
+  renderer->renderPolygon=&msDrawPolygonOgl;
+  renderer->renderGlyphs=&msRenderGlyphsOgl;
+  renderer->renderEllipseSymbol = &msRenderEllipseOgl;
+  renderer->renderVectorSymbol = &msRenderVectorSymbolOgl;
+  renderer->renderPixmapSymbol = &msRenderPixmapOgl;
+  renderer->renderTruetypeSymbol = &msRenderTruetypeSymbolOgl;
+
+  renderer->renderTile = &msRenderTileOgl;
+  renderer->renderPolygonTiled = &msDrawPolygonTiledOgl;
+  renderer->renderLineTiled = &msDrawLineTiledOgl;
+
+  renderer->getTruetypeTextBBox = &msGetTruetypeTextBBoxOgl;
+
+  renderer->getRasterBufferHandle = msGetRasterBufferHandleOgl;
+  renderer->getRasterBufferCopy = msGetRasterBufferCopyOgl;
+  renderer->initializeRasterBuffer = msInitializeRasterBufferOgl;
+  renderer->mergeRasterBuffer = msMergeRasterBufferOgl;
+  renderer->loadImageFromFile = msLoadMSRasterBufferFromFile;
+
+  renderer->freeSymbol = &msFreeSymbolOgl;
+  renderer->freeImage=&msFreeImageOgl;
+
+  return MS_SUCCESS;
+#else
+  msSetError(MS_MISCERR,"OGL driver requested but it is not compiled in this release",
+             "msPopulateRendererVTableOGL()");
+  return MS_FAILURE;
 #endif
 
 }
diff --git a/mapoglcontext.cpp b/mapoglcontext.cpp
index ec555bd..306d19f 100644
--- a/mapoglcontext.cpp
+++ b/mapoglcontext.cpp
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -33,7 +33,7 @@
 #include "maperror.h"
 #include "mapoglcontext.h"
 
-MS_CVSID("$Id$")
+
 
 #define _T(x) __TEXT(x)
 
@@ -44,52 +44,48 @@ ms_uint32 OglContext::MIN_TEXTURE_SIZE = 0;
 OglContext* OglContext::current = NULL;
 
 OglContext::OglContext(ms_uint32 width, ms_uint32 height)
-    : valid(false)
+  : valid(false)
 {
-    if (!window && !initWindow()) return;
-    if (!sharingContext && !initSharingContext()) return;
+  if (!window && !initWindow()) return;
+  if (!sharingContext && !initSharingContext()) return;
 
-    if (!(this->width = getTextureSize(GL_TEXTURE_WIDTH, width))) return;
-    if (!(this->height = getTextureSize(GL_TEXTURE_HEIGHT, height))) return;
+  if (!(this->width = getTextureSize(GL_TEXTURE_WIDTH, width))) return;
+  if (!(this->height = getTextureSize(GL_TEXTURE_HEIGHT, height))) return;
 
-    if (!createPBuffer(this->width, this->height)) return;
-    if (!makeCurrent()) return;    
-    valid = true;
+  if (!createPBuffer(this->width, this->height)) return;
+  if (!makeCurrent()) return;
+  valid = true;
 }
 
 ms_uint32 OglContext::getTextureSize(GLuint dimension, ms_uint32 value)
 {
-    glTexImage2D(GL_PROXY_TEXTURE_2D, 0, GL_RGBA,  value, value, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
-    GLint check = 0;
-    glGetTexLevelParameteriv(GL_PROXY_TEXTURE_2D, 0, dimension, &check);
-
-    if (glGetError() != GL_NO_ERROR)
-    {
-        msSetError(MS_OGLERR, "glGetTexLevelParameteriv failed. glError: %d", "OglContext::getTextureSize()", glGetError());
-    }
-
-    if (check == 0)
-    {
-        return MS_MAX(MS_MIN(NextPowerOf2(value), OglContext::MAX_TEXTURE_SIZE), OglContext::MIN_TEXTURE_SIZE);
-    }
-    else
-    {
-        msSetError(MS_OGLERR, "Unable to create opengl texture of map size", "OglContext::getTextureSize()");
-        return value;
-    }
+  glTexImage2D(GL_PROXY_TEXTURE_2D, 0, GL_RGBA,  value, value, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
+  GLint check = 0;
+  glGetTexLevelParameteriv(GL_PROXY_TEXTURE_2D, 0, dimension, &check);
+
+  if (glGetError() != GL_NO_ERROR) {
+    msSetError(MS_OGLERR, "glGetTexLevelParameteriv failed. glError: %d", "OglContext::getTextureSize()", glGetError());
+  }
+
+  if (check == 0) {
+    return MS_MAX(MS_MIN(NextPowerOf2(value), OglContext::MAX_TEXTURE_SIZE), OglContext::MIN_TEXTURE_SIZE);
+  } else {
+    msSetError(MS_OGLERR, "Unable to create opengl texture of map size", "OglContext::getTextureSize()");
+    return value;
+  }
 }
 
 GLuint OglContext::NextPowerOf2(GLuint in)
 {
-    in -= 1;
+  in -= 1;
 
-    in |= in >> 16;
-    in |= in >> 8;
-    in |= in >> 4;
-    in |= in >> 2;
-    in |= in >> 1;
+  in |= in >> 16;
+  in |= in >> 8;
+  in |= in >> 4;
+  in |= in >> 2;
+  in |= in >> 1;
 
-    return in + 1;
+  return in + 1;
 }
 
 #if defined(_WIN32) && !defined(__CYGWIN__)
@@ -98,242 +94,220 @@ HDC OglContext::window = NULL;
 HGLRC OglContext::sharingContext = NULL;
 
 LRESULT CALLBACK WndProc(HWND hWnd,
-        UINT message,
-        WPARAM wParam,
-        LPARAM lParam)
+                         UINT message,
+                         WPARAM wParam,
+                         LPARAM lParam)
 {
-    return(1L);
+  return(1L);
 }
 
 OglContext::~OglContext()
 {
-    //TODO
+  //TODO
 }
 
 bool OglContext::makeCurrent()
 {
-    if (current != this)
-    {
-        current = this;
-        if (!wglMakeContextCurrentARB(hPBufferDC, hPBufferDC, hPBufferRC))
-        {
-            msSetError(MS_OGLERR, "Can't Activate The GL Rendering pbuffer.", "OglContext::makeCurrent()");
-            return FALSE;
-        }
-    }
-    return true;
+  if (current != this) {
+    current = this;
+    if (!wglMakeContextCurrentARB(hPBufferDC, hPBufferDC, hPBufferRC)) {
+      msSetError(MS_OGLERR, "Can't Activate The GL Rendering pbuffer.", "OglContext::makeCurrent()");
+      return FALSE;
+    }
+  }
+  return true;
 }
 
 bool OglContext::initWindow()
 {
-    int windowPixelFormat;
-    WNDCLASS wc;
-    DWORD dwExStyle;
-    DWORD dwStyle;
-    RECT WindowRect;
-    HMODULE hInstance = NULL;
-    HWND hWnd = NULL;
-    WindowRect.left=(long)0;
-    WindowRect.right=(long)0;
-    WindowRect.top=(long)0;
-    WindowRect.bottom=(long)0;
-    hInstance = GetModuleHandle(NULL);
-    wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
-    wc.cbClsExtra = 0;
-    wc.cbWndExtra = 0;
-    wc.lpfnWndProc = (WNDPROC) WndProc;
-    wc.hInstance = hInstance;
-    wc.hIcon = LoadIcon(NULL, IDI_WINLOGO);
-    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
-    wc.hbrBackground = NULL;
-    wc.lpszMenuName = NULL;
-    wc.lpszClassName = _T("OpenGL");
-
-    if (!RegisterClass(&wc))
-    {
-        msSetError(MS_OGLERR, "Failed To Register The Window Class.", "OglContext::initWindow()");
-        return FALSE;
-    }
-    dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
-    dwStyle=WS_OVERLAPPEDWINDOW;
-
-    AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle);
-
-    if (!(hWnd=CreateWindowEx( dwExStyle,
-                            _T("OpenGL"),
-                            _T("temp"),
-                            dwStyle |
-                            WS_CLIPSIBLINGS |
-                            WS_CLIPCHILDREN,
-                            0, 0,
-                            WindowRect.right-WindowRect.left,
-                            WindowRect.bottom-WindowRect.top,
-                            NULL,
-                            NULL,
-                            hInstance,
-                            NULL)))
-    {
-        msSetError(MS_OGLERR, "Window Creation Error.", "OglContext::initWindow()");
-        return FALSE;
-    }
+  int windowPixelFormat;
+  WNDCLASS wc;
+  DWORD dwExStyle;
+  DWORD dwStyle;
+  RECT WindowRect;
+  HMODULE hInstance = NULL;
+  HWND hWnd = NULL;
+  WindowRect.left=(long)0;
+  WindowRect.right=(long)0;
+  WindowRect.top=(long)0;
+  WindowRect.bottom=(long)0;
+  hInstance = GetModuleHandle(NULL);
+  wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
+  wc.cbClsExtra = 0;
+  wc.cbWndExtra = 0;
+  wc.lpfnWndProc = (WNDPROC) WndProc;
+  wc.hInstance = hInstance;
+  wc.hIcon = LoadIcon(NULL, IDI_WINLOGO);
+  wc.hCursor = LoadCursor(NULL, IDC_ARROW);
+  wc.hbrBackground = NULL;
+  wc.lpszMenuName = NULL;
+  wc.lpszClassName = _T("OpenGL");
+
+  if (!RegisterClass(&wc)) {
+    msSetError(MS_OGLERR, "Failed To Register The Window Class.", "OglContext::initWindow()");
+    return FALSE;
+  }
+  dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
+  dwStyle=WS_OVERLAPPEDWINDOW;
+
+  AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle);
+
+  if (!(hWnd=CreateWindowEx( dwExStyle,
+                             _T("OpenGL"),
+                             _T("temp"),
+                             dwStyle |
+                             WS_CLIPSIBLINGS |
+                             WS_CLIPCHILDREN,
+                             0, 0,
+                             WindowRect.right-WindowRect.left,
+                             WindowRect.bottom-WindowRect.top,
+                             NULL,
+                             NULL,
+                             hInstance,
+                             NULL))) {
+    msSetError(MS_OGLERR, "Window Creation Error.", "OglContext::initWindow()");
+    return FALSE;
+  }
+
+  static PIXELFORMATDESCRIPTOR pfd= {
+    sizeof(PIXELFORMATDESCRIPTOR),
+    1,
+    PFD_DRAW_TO_WINDOW |
+    PFD_SUPPORT_OPENGL |
+    PFD_DOUBLEBUFFER,
+    PFD_TYPE_RGBA,
+    24, // Select Our Color Depth
+    0, 0, 0, 0, 0, 0, // Color Bits Ignored
+    8, // Alpha Buffer
+    0, // Shift Bit Ignored
+    0, // No Accumulation Buffer
+    0, 0, 0, 0, // Accumulation Bits Ignored
+    16, // 16Bit Z-Buffer (Depth Buffer)
+    0, // No Stencil Buffer
+    0, // No Auxiliary Buffer
+    PFD_MAIN_PLANE, // Main Drawing Layer
+    0, // Reserved
+    0, 0, 0 // Layer Masks Ignored
+  };
+
+  if (!(window=GetDC(hWnd))) {
+    msSetError(MS_OGLERR, "Can't Create A GL Device Context.. Last Error: %d", "OglContext::initWindow()", GetLastError());
+    return FALSE;
+  }
+
+  if (!(windowPixelFormat=ChoosePixelFormat(window,&pfd))) {
+    msSetError(MS_OGLERR, "Can't Find A Suitable windowPixelFormat. Last Error: %d", "OglContext::initWindow()", GetLastError());
+    return FALSE;
+  }
+
+  if(!SetPixelFormat(window,windowPixelFormat,&pfd)) {
+    msSetError(MS_OGLERR, "Can't Set The windowPixelFormat. Last Error: %d", "OglContext::initWindow()", GetLastError());
+    return FALSE;
+  }
+  return TRUE;
+}
 
-    static PIXELFORMATDESCRIPTOR pfd=
-    {
-        sizeof(PIXELFORMATDESCRIPTOR),
-        1,
-        PFD_DRAW_TO_WINDOW |
-        PFD_SUPPORT_OPENGL |
-        PFD_DOUBLEBUFFER,
-        PFD_TYPE_RGBA,
-        24, // Select Our Color Depth
-        0, 0, 0, 0, 0, 0, // Color Bits Ignored
-        8, // Alpha Buffer
-        0, // Shift Bit Ignored
-        0, // No Accumulation Buffer
-        0, 0, 0, 0, // Accumulation Bits Ignored
-        16, // 16Bit Z-Buffer (Depth Buffer)
-        0, // No Stencil Buffer
-        0, // No Auxiliary Buffer
-        PFD_MAIN_PLANE, // Main Drawing Layer
-        0, // Reserved
-        0, 0, 0 // Layer Masks Ignored
-    };
+bool OglContext::initSharingContext()
+{
+  if (!(sharingContext=wglCreateContext(window))) {
+    msSetError(MS_OGLERR, "Can't Create A GL Rendering Context.", "OglContext::createContext()");
+    return FALSE;
+  }
 
-    if (!(window=GetDC(hWnd)))
-    {
-        msSetError(MS_OGLERR, "Can't Create A GL Device Context.. Last Error: %d", "OglContext::initWindow()", GetLastError());
-        return FALSE;
-    }
+  if(!wglMakeCurrent(window,sharingContext)) {
+    msSetError(MS_OGLERR, "Can't Activate The GL Rendering Context.", "OglContext::createContext()");
+    return FALSE;
+  }
 
-    if (!(windowPixelFormat=ChoosePixelFormat(window,&pfd)))
-    {
-        msSetError(MS_OGLERR, "Can't Find A Suitable windowPixelFormat. Last Error: %d", "OglContext::initWindow()", GetLastError());
-        return FALSE;
-    }
+  if (!(wglChoosePixelFormatARB = (PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress("wglChoosePixelFormatARB"))) {
+    msSetError(MS_OGLERR, "unable to retreive wglChoosePixelFormatARB method.", "OglContext::createContext()");
+    return FALSE;
+  }
 
-    if(!SetPixelFormat(window,windowPixelFormat,&pfd))
-    {
-        msSetError(MS_OGLERR, "Can't Set The windowPixelFormat. Last Error: %d", "OglContext::initWindow()", GetLastError());
-        return FALSE;
-    }
-    return TRUE;
-}
+  if (!(wglCreatePbufferARB = (PFNWGLCREATEPBUFFERARBPROC)wglGetProcAddress("wglCreatePbufferARB"))) {
+    msSetError(MS_OGLERR, "unable to retreive wglCreatePbufferARB method.", "OglContext::createContext()");
+    return FALSE;
+  }
 
-bool OglContext::initSharingContext()
-{
-    if (!(sharingContext=wglCreateContext(window)))
-    {
-        msSetError(MS_OGLERR, "Can't Create A GL Rendering Context.", "OglContext::createContext()");
-        return FALSE;
-    }
+  if (!(wglGetPbufferDCARB = (PFNWGLGETPBUFFERDCARBPROC)wglGetProcAddress("wglGetPbufferDCARB"))) {
+    msSetError(MS_OGLERR, "unable to retreive wglGetPbufferDCARB method.", "OglContext::createContext()");
+    return FALSE;
+  }
 
-    if(!wglMakeCurrent(window,sharingContext))
-    {
-        msSetError(MS_OGLERR, "Can't Activate The GL Rendering Context.", "OglContext::createContext()");
-        return FALSE;
-    }
+  if (!(wglReleasePbufferDCARB = (PFNWGLRELEASEPBUFFERDCARBPROC)wglGetProcAddress("wglReleasePbufferDCARB"))) {
+    msSetError(MS_OGLERR, "unable to retreive wglReleasePbufferDCARB method.", "OglContext::createContext()");
+    return FALSE;
+  }
 
-    if (!(wglChoosePixelFormatARB = (PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress("wglChoosePixelFormatARB")))
-    {
-        msSetError(MS_OGLERR, "unable to retreive wglChoosePixelFormatARB method.", "OglContext::createContext()");
-        return FALSE;
-    }
-    
-    if (!(wglCreatePbufferARB = (PFNWGLCREATEPBUFFERARBPROC)wglGetProcAddress("wglCreatePbufferARB")))
-    {
-        msSetError(MS_OGLERR, "unable to retreive wglCreatePbufferARB method.", "OglContext::createContext()");
-        return FALSE;
-    }
-    
-    if (!(wglGetPbufferDCARB = (PFNWGLGETPBUFFERDCARBPROC)wglGetProcAddress("wglGetPbufferDCARB")))
-    {
-        msSetError(MS_OGLERR, "unable to retreive wglGetPbufferDCARB method.", "OglContext::createContext()");
-        return FALSE;
-    }
-    
-    if (!(wglReleasePbufferDCARB = (PFNWGLRELEASEPBUFFERDCARBPROC)wglGetProcAddress("wglReleasePbufferDCARB")))
-    {
-        msSetError(MS_OGLERR, "unable to retreive wglReleasePbufferDCARB method.", "OglContext::createContext()");
-        return FALSE;
-    }
-    
-    if (!(wglMakeContextCurrentARB = (PFNWGLMAKECONTEXTCURRENTARBPROC)wglGetProcAddress("wglMakeContextCurrentARB")))
-    {
-        msSetError(MS_OGLERR, "unable to retreive wglMakeContextCurrentARB method.", "OglContext::createContext()");
-        return FALSE;
-    }
+  if (!(wglMakeContextCurrentARB = (PFNWGLMAKECONTEXTCURRENTARBPROC)wglGetProcAddress("wglMakeContextCurrentARB"))) {
+    msSetError(MS_OGLERR, "unable to retreive wglMakeContextCurrentARB method.", "OglContext::createContext()");
+    return FALSE;
+  }
 
-    glGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, (GLint*) &MAX_ANISOTROPY);
-    glGetIntegerv(GL_MAX_TEXTURE_SIZE, (GLint*)&MAX_TEXTURE_SIZE);
+  glGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, (GLint*) &MAX_ANISOTROPY);
+  glGetIntegerv(GL_MAX_TEXTURE_SIZE, (GLint*)&MAX_TEXTURE_SIZE);
 
-    MIN_TEXTURE_SIZE = 8;
+  MIN_TEXTURE_SIZE = 8;
 
 
-    return TRUE;
+  return TRUE;
 }
 
 bool OglContext::createPBuffer(ms_uint32 width, ms_uint32 height)
 {
-    HPBUFFERARB hPBuffer = NULL;
-    hPBufferDC = NULL;
-    hPBufferRC = NULL;
-
-    int pixelFormat;
-    int valid = false;
-    UINT numFormats = 0;
-    float fAttributes[] = {0,0};
-    int samples = MAX_MULTISAMPLE_SAMPLES;
-
-    while ((!valid || numFormats == 0) && samples >= 0)
-    {
-        int iAttributes[] =
-        {
-            WGL_SAMPLES_ARB,samples,
-            WGL_DRAW_TO_PBUFFER_ARB,GL_TRUE,
-            WGL_SUPPORT_OPENGL_ARB,GL_TRUE,
-            WGL_ACCELERATION_ARB,WGL_FULL_ACCELERATION_ARB,
-            WGL_COLOR_BITS_ARB,24,
-            WGL_ALPHA_BITS_ARB,8,
-            WGL_DEPTH_BITS_ARB,16,
-            WGL_STENCIL_BITS_ARB,0,
-            WGL_SAMPLE_BUFFERS_ARB,GL_TRUE,
-            WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB,            
-            0,0
-        };
-
-        valid = wglChoosePixelFormatARB(window,iAttributes,fAttributes,1,&pixelFormat,&numFormats);
-        if (!valid || numFormats == 0) samples -= 2;
-    }    
-
-    if(numFormats == 0)
-    {
-        msSetError(MS_OGLERR, "P-buffer Error: Unable to find an acceptable pixel format.", "OglContext::createPBuffer()");
-        return FALSE;
-    }
-
-    if (!(hPBuffer = wglCreatePbufferARB(window, pixelFormat, width, height, 0)))
-    {
-        msSetError(MS_OGLERR, "P-buffer Error: Unable to create P-buffer. glError: %d", "OglContext::createPBuffer()", glGetError());
-        return FALSE;
-    }
-    if (!(hPBufferDC = wglGetPbufferDCARB(hPBuffer)))
-    {
-        msSetError(MS_OGLERR, "P-buffer Error: Unable to get P-buffer DC. glError: %d", "OglContext::createPBuffer()", glGetError());
-        return FALSE;
-    }
-    if (!(hPBufferRC = wglCreateContext(hPBufferDC)))
-    {
-        msSetError(MS_OGLERR, "P-buffer Error: Unable to get P-buffer DC. glError: %d", "OglContext::createPBuffer()", glGetError());
-        return FALSE;
-    }
-
-    if (wglShareLists(sharingContext,hPBufferRC) == FALSE)
-    {
-        msSetError(MS_OGLERR, "P-buffer Error: Unable to share display lists. glError: %d", "OglContext::createPBuffer()", glGetError());
-        return FALSE;
-    }
+  HPBUFFERARB hPBuffer = NULL;
+  hPBufferDC = NULL;
+  hPBufferRC = NULL;
+
+  int pixelFormat;
+  int valid = false;
+  UINT numFormats = 0;
+  float fAttributes[] = {0,0};
+  int samples = MAX_MULTISAMPLE_SAMPLES;
+
+  while ((!valid || numFormats == 0) && samples >= 0) {
+    int iAttributes[] = {
+      WGL_SAMPLES_ARB,samples,
+      WGL_DRAW_TO_PBUFFER_ARB,GL_TRUE,
+      WGL_SUPPORT_OPENGL_ARB,GL_TRUE,
+      WGL_ACCELERATION_ARB,WGL_FULL_ACCELERATION_ARB,
+      WGL_COLOR_BITS_ARB,24,
+      WGL_ALPHA_BITS_ARB,8,
+      WGL_DEPTH_BITS_ARB,16,
+      WGL_STENCIL_BITS_ARB,0,
+      WGL_SAMPLE_BUFFERS_ARB,GL_TRUE,
+      WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB,
+      0,0
+    };
 
-    return TRUE;
+    valid = wglChoosePixelFormatARB(window,iAttributes,fAttributes,1,&pixelFormat,&numFormats);
+    if (!valid || numFormats == 0) samples -= 2;
+  }
+
+  if(numFormats == 0) {
+    msSetError(MS_OGLERR, "P-buffer Error: Unable to find an acceptable pixel format.", "OglContext::createPBuffer()");
+    return FALSE;
+  }
+
+  if (!(hPBuffer = wglCreatePbufferARB(window, pixelFormat, width, height, 0))) {
+    msSetError(MS_OGLERR, "P-buffer Error: Unable to create P-buffer. glError: %d", "OglContext::createPBuffer()", glGetError());
+    return FALSE;
+  }
+  if (!(hPBufferDC = wglGetPbufferDCARB(hPBuffer))) {
+    msSetError(MS_OGLERR, "P-buffer Error: Unable to get P-buffer DC. glError: %d", "OglContext::createPBuffer()", glGetError());
+    return FALSE;
+  }
+  if (!(hPBufferRC = wglCreateContext(hPBufferDC))) {
+    msSetError(MS_OGLERR, "P-buffer Error: Unable to get P-buffer DC. glError: %d", "OglContext::createPBuffer()", glGetError());
+    return FALSE;
+  }
+
+  if (wglShareLists(sharingContext,hPBufferRC) == FALSE) {
+    msSetError(MS_OGLERR, "P-buffer Error: Unable to share display lists. glError: %d", "OglContext::createPBuffer()", glGetError());
+    return FALSE;
+  }
+
+  return TRUE;
 }
 
 PFNWGLCHOOSEPIXELFORMATARBPROC OglContext::wglChoosePixelFormatARB = NULL;
@@ -350,161 +324,147 @@ GLXFBConfig* OglContext::configs = NULL;
 
 OglContext::~OglContext()
 {
-    //TODO
+  //TODO
 }
 
 
 bool OglContext::makeCurrent()
 {
-    if (current != this)
-    {
-        current = this;
-        if (!glXMakeCurrent(window, pbuffer, sharingContext))
-        {
-            msSetError(MS_OGLERR, "glXMakeCurrent failed. glError: %d", "OglContext::makeCurrent()", glGetError());
-            return false;
-        }
-    }
-    return true;
+  if (current != this) {
+    current = this;
+    if (!glXMakeCurrent(window, pbuffer, sharingContext)) {
+      msSetError(MS_OGLERR, "glXMakeCurrent failed. glError: %d", "OglContext::makeCurrent()", glGetError());
+      return false;
+    }
+  }
+  return true;
 }
 
 bool OglContext::initSharingContext()
 {
-    int fb_attributes[] =
-    {
-        GLX_SAMPLES_ARB, MAX_MULTISAMPLE_SAMPLES,
-        GLX_RENDER_TYPE, GLX_RGBA_BIT,
-        GLX_DRAWABLE_TYPE, GLX_PBUFFER_BIT,
-        GLX_RED_SIZE, 8,
-        GLX_GREEN_SIZE, 8,
-        GLX_BLUE_SIZE, 8,
-        GLX_ALPHA_SIZE, 8,
-        GLX_DEPTH_SIZE, 16,
-        GLX_DOUBLEBUFFER, 0,
-        GLX_SAMPLE_BUFFERS_ARB, 1,
-        0
-    };
-
-    int num_configs = 0;
-    while (num_configs == 0 && fb_attributes[1] >= 0)
-    {
-        configs = glXChooseFBConfig(window, DefaultScreen(window), fb_attributes, &num_configs);
-        fb_attributes[1] -= 2;
-    }
-
-    if (configs == NULL || num_configs == 0)
-    {
-        msSetError(MS_OGLERR, "glXChooseFBConfig could not find any configs. Likely your video card or drivers are not supported. glError: %d", "OglContext::init()", glGetError());
-        return false;
-    }
-
-    sharingContext = glXCreateNewContext(window, *configs, GLX_RGBA_TYPE, NULL, 1);
-    if (sharingContext == NULL)
-    {
-        msSetError(MS_OGLERR, "glXCreateNewContext failed. glError: %d", "OglContext::initSharingContext()", glGetError());
-        return false;
-    }
-
-    return true;
+  int fb_attributes[] = {
+    GLX_SAMPLES_ARB, MAX_MULTISAMPLE_SAMPLES,
+    GLX_RENDER_TYPE, GLX_RGBA_BIT,
+    GLX_DRAWABLE_TYPE, GLX_PBUFFER_BIT,
+    GLX_RED_SIZE, 8,
+    GLX_GREEN_SIZE, 8,
+    GLX_BLUE_SIZE, 8,
+    GLX_ALPHA_SIZE, 8,
+    GLX_DEPTH_SIZE, 16,
+    GLX_DOUBLEBUFFER, 0,
+    GLX_SAMPLE_BUFFERS_ARB, 1,
+    0
+  };
+
+  int num_configs = 0;
+  while (num_configs == 0 && fb_attributes[1] >= 0) {
+    configs = glXChooseFBConfig(window, DefaultScreen(window), fb_attributes, &num_configs);
+    fb_attributes[1] -= 2;
+  }
+
+  if (configs == NULL || num_configs == 0) {
+    msSetError(MS_OGLERR, "glXChooseFBConfig could not find any configs. Likely your video card or drivers are not supported. glError: %d", "OglContext::init()", glGetError());
+    return false;
+  }
+
+  sharingContext = glXCreateNewContext(window, *configs, GLX_RGBA_TYPE, NULL, 1);
+  if (sharingContext == NULL) {
+    msSetError(MS_OGLERR, "glXCreateNewContext failed. glError: %d", "OglContext::initSharingContext()", glGetError());
+    return false;
+  }
+
+  return true;
 }
 
 bool OglContext::createPBuffer(ms_uint32 width, ms_uint32 height)
 {
-    int maxHeight, maxWidth;
+  int maxHeight, maxWidth;
 
-    glXGetFBConfigAttrib(window, *configs, GLX_MAX_PBUFFER_WIDTH, &maxWidth);
-    glXGetFBConfigAttrib(window, *configs, GLX_MAX_PBUFFER_HEIGHT, &maxHeight);
+  glXGetFBConfigAttrib(window, *configs, GLX_MAX_PBUFFER_WIDTH, &maxWidth);
+  glXGetFBConfigAttrib(window, *configs, GLX_MAX_PBUFFER_HEIGHT, &maxHeight);
 
-    ms_uint32 uMaxHeight = maxHeight, uMaxWidth = maxWidth;
+  ms_uint32 uMaxHeight = maxHeight, uMaxWidth = maxWidth;
 
-    this->width = MS_MIN(width, uMaxWidth);
-    this->height = MS_MIN(height, uMaxHeight);
+  this->width = MS_MIN(width, uMaxWidth);
+  this->height = MS_MIN(height, uMaxHeight);
 
-    int iPbufferAttributes[] =
-    {
-            GLX_PBUFFER_WIDTH, this->width,
-            GLX_PBUFFER_HEIGHT, this->height,
-            GLX_LARGEST_PBUFFER, false,
-            0, 0
-    };
+  int iPbufferAttributes[] = {
+    GLX_PBUFFER_WIDTH, this->width,
+    GLX_PBUFFER_HEIGHT, this->height,
+    GLX_LARGEST_PBUFFER, false,
+    0, 0
+  };
 
-    pbuffer = glXCreatePbuffer(window, *configs, iPbufferAttributes);
-    if (pbuffer == 0)
-    {
-        msSetError(MS_OGLERR, "glXCreatePbuffer failed. glError: %d", "OglContext::init()", glGetError());
-        return false;
-    }
+  pbuffer = glXCreatePbuffer(window, *configs, iPbufferAttributes);
+  if (pbuffer == 0) {
+    msSetError(MS_OGLERR, "glXCreatePbuffer failed. glError: %d", "OglContext::init()", glGetError());
+    return false;
+  }
 
-    return true;
+  return true;
 }
 
 bool OglContext::initWindow()
 {
-    const char* const display_name = getenv("DISPLAY");
-    if (!display_name)
-    {
-        msSetError(MS_OGLERR, "DISPLAY environment variable not set", "OglContext::init()");
-        return false;
-    }
-
-    window = XOpenDisplay(display_name);
-    if (!window)
-    {
-        msSetError(MS_OGLERR, "XOpenDisplay() failed.", "OglContext::init()");
-        return false;
-    }
-
-    const int fb_attributes[] = {
-            GLX_RENDER_TYPE, GLX_RGBA_BIT,
-            GLX_DRAWABLE_TYPE, GLX_PBUFFER_BIT,
-            GLX_RED_SIZE, 8,
-            GLX_GREEN_SIZE, 8,
-            GLX_BLUE_SIZE, 8,
-            GLX_ALPHA_SIZE, 8,
-            GLX_DEPTH_SIZE, 16,
-            GLX_DOUBLEBUFFER, 0,
-            GLX_SAMPLE_BUFFERS_ARB, 1,
-            0
-        };
-
-    int num_configs = 0;
-    GLXFBConfig* tempConfigs = glXChooseFBConfig(window, DefaultScreen(window), fb_attributes, &num_configs);
-
-    if (tempConfigs == NULL || num_configs == 0)
-    {
-        msSetError(MS_OGLERR, "glXChooseFBConfig could not find any configs. Likely your video card or drivers are not supported.", "OglContext::initWindow()");
-        return false;
-    }
-
-    GLXContext tempContext = glXCreateNewContext(window, *tempConfigs, GLX_RGBA_TYPE, NULL, 1);
-    if (tempContext == NULL)
-    {
-        msSetError(MS_OGLERR, "glXCreateNewContext failed.", "OglContext::initWindow()");
-        return false;
-    }
-
-    int iPbufferAttributes[] =    {0, 0};
-
-    GLXPbuffer tempBuffer = glXCreatePbuffer(window, *tempConfigs, iPbufferAttributes);
-    if (tempBuffer == 0)
-    {
-        msSetError(MS_OGLERR, "glXCreatePbuffer failed.", "OglContext::initWindow()");
-        return false;
-    }
-
-    if (!glXMakeCurrent(window, tempBuffer, tempContext))
-    {
-        msSetError(MS_OGLERR, "glXMakeCurrent failed.", "OglContext::initWindow()");
-        return false;
-    }
-
-    glGetIntegerv(GL_MAX_SAMPLES_EXT, (GLint*)&MAX_MULTISAMPLE_SAMPLES);
-    glGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, (GLint*) &MAX_ANISOTROPY);
-    glGetIntegerv(GL_MAX_TEXTURE_SIZE, (GLint*)&MAX_TEXTURE_SIZE);
-
-    MIN_TEXTURE_SIZE = 8;
-
-    return true;
+  const char* const display_name = getenv("DISPLAY");
+  if (!display_name) {
+    msSetError(MS_OGLERR, "DISPLAY environment variable not set", "OglContext::init()");
+    return false;
+  }
+
+  window = XOpenDisplay(display_name);
+  if (!window) {
+    msSetError(MS_OGLERR, "XOpenDisplay() failed.", "OglContext::init()");
+    return false;
+  }
+
+  const int fb_attributes[] = {
+    GLX_RENDER_TYPE, GLX_RGBA_BIT,
+    GLX_DRAWABLE_TYPE, GLX_PBUFFER_BIT,
+    GLX_RED_SIZE, 8,
+    GLX_GREEN_SIZE, 8,
+    GLX_BLUE_SIZE, 8,
+    GLX_ALPHA_SIZE, 8,
+    GLX_DEPTH_SIZE, 16,
+    GLX_DOUBLEBUFFER, 0,
+    GLX_SAMPLE_BUFFERS_ARB, 1,
+    0
+  };
+
+  int num_configs = 0;
+  GLXFBConfig* tempConfigs = glXChooseFBConfig(window, DefaultScreen(window), fb_attributes, &num_configs);
+
+  if (tempConfigs == NULL || num_configs == 0) {
+    msSetError(MS_OGLERR, "glXChooseFBConfig could not find any configs. Likely your video card or drivers are not supported.", "OglContext::initWindow()");
+    return false;
+  }
+
+  GLXContext tempContext = glXCreateNewContext(window, *tempConfigs, GLX_RGBA_TYPE, NULL, 1);
+  if (tempContext == NULL) {
+    msSetError(MS_OGLERR, "glXCreateNewContext failed.", "OglContext::initWindow()");
+    return false;
+  }
+
+  int iPbufferAttributes[] =    {0, 0};
+
+  GLXPbuffer tempBuffer = glXCreatePbuffer(window, *tempConfigs, iPbufferAttributes);
+  if (tempBuffer == 0) {
+    msSetError(MS_OGLERR, "glXCreatePbuffer failed.", "OglContext::initWindow()");
+    return false;
+  }
+
+  if (!glXMakeCurrent(window, tempBuffer, tempContext)) {
+    msSetError(MS_OGLERR, "glXMakeCurrent failed.", "OglContext::initWindow()");
+    return false;
+  }
+
+  glGetIntegerv(GL_MAX_SAMPLES_EXT, (GLint*)&MAX_MULTISAMPLE_SAMPLES);
+  glGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, (GLint*) &MAX_ANISOTROPY);
+  glGetIntegerv(GL_MAX_TEXTURE_SIZE, (GLint*)&MAX_TEXTURE_SIZE);
+
+  MIN_TEXTURE_SIZE = 8;
+
+  return true;
 }
 
 #endif /* UNIX */
diff --git a/mapoglcontext.h b/mapoglcontext.h
index b2b9f7d..df2c5e2 100644
--- a/mapoglcontext.h
+++ b/mapoglcontext.h
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -64,52 +64,59 @@ typedef GLXPbuffer OGL_PBUFFER;
 
 class OglRenderer;
 
-class OglContext {
+class OglContext
+{
 private:
-    static OglContext* current;
-    static bool initWindow();
-    static bool initSharingContext();
-    static ms_uint32 getTextureSize(GLuint dimension, ms_uint32 value);
-    static GLuint NextPowerOf2(GLuint in);
+  static OglContext* current;
+  static bool initWindow();
+  static bool initSharingContext();
+  static ms_uint32 getTextureSize(GLuint dimension, ms_uint32 value);
+  static GLuint NextPowerOf2(GLuint in);
 
 #if defined(_WIN32) && !defined(__CYGWIN__)
-    static HDC window;
-    static HGLRC sharingContext;
-    HDC hPBufferDC;
-    HGLRC hPBufferRC;
+  static HDC window;
+  static HGLRC sharingContext;
+  HDC hPBufferDC;
+  HGLRC hPBufferRC;
 #else
-    static Display* window;
-    static GLXContext sharingContext;
-    static GLXFBConfig* configs;
-    GLXPbuffer pbuffer;
+  static Display* window;
+  static GLXContext sharingContext;
+  static GLXFBConfig* configs;
+  GLXPbuffer pbuffer;
 #endif
 
 public:
-    static ms_uint32 MAX_MULTISAMPLE_SAMPLES;
-    static ms_uint32 MAX_ANISOTROPY;
-    static ms_uint32 MAX_TEXTURE_SIZE;
-    static ms_uint32 MIN_TEXTURE_SIZE;
-
-    OglContext(ms_uint32 width, ms_uint32 height);
-    ~OglContext();
-    int getHeight() const { return height; }
-    int getWidth() const { return width; }
-    bool isValid() const { return valid; }
-    bool makeCurrent();
-    void bindPBufferToTexture();
+  static ms_uint32 MAX_MULTISAMPLE_SAMPLES;
+  static ms_uint32 MAX_ANISOTROPY;
+  static ms_uint32 MAX_TEXTURE_SIZE;
+  static ms_uint32 MIN_TEXTURE_SIZE;
+
+  OglContext(ms_uint32 width, ms_uint32 height);
+  ~OglContext();
+  int getHeight() const {
+    return height;
+  }
+  int getWidth() const {
+    return width;
+  }
+  bool isValid() const {
+    return valid;
+  }
+  bool makeCurrent();
+  void bindPBufferToTexture();
 private:
-    bool createPBuffer(ms_uint32 width, ms_uint32 height);
-    ms_uint32 width;
-    ms_uint32 height;
-    bool valid;
-    int windowPixelFormat;    
+  bool createPBuffer(ms_uint32 width, ms_uint32 height);
+  ms_uint32 width;
+  ms_uint32 height;
+  bool valid;
+  int windowPixelFormat;
 
 #if defined(_WIN32) && !defined(__CYGWIN__)
-    static PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB;
-    static PFNWGLCREATEPBUFFERARBPROC wglCreatePbufferARB;
-    static PFNWGLGETPBUFFERDCARBPROC wglGetPbufferDCARB;
-    static PFNWGLRELEASEPBUFFERDCARBPROC wglReleasePbufferDCARB;
-    static PFNWGLMAKECONTEXTCURRENTARBPROC wglMakeContextCurrentARB;
+  static PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB;
+  static PFNWGLCREATEPBUFFERARBPROC wglCreatePbufferARB;
+  static PFNWGLGETPBUFFERDCARBPROC wglGetPbufferDCARB;
+  static PFNWGLRELEASEPBUFFERDCARBPROC wglReleasePbufferDCARB;
+  static PFNWGLMAKECONTEXTCURRENTARBPROC wglMakeContextCurrentARB;
 #endif
 };
 
diff --git a/mapoglrenderer.cpp b/mapoglrenderer.cpp
index cca2f35..d0fa550 100644
--- a/mapoglrenderer.cpp
+++ b/mapoglrenderer.cpp
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -36,7 +36,7 @@
 #include "maperror.h"
 #include "mapoglrenderer.h"
 
-MS_CVSID("$Id$")
+
 
 using namespace std;
 
@@ -59,754 +59,700 @@ GLvoid CALLBACK combineDataCallback(GLdouble coords[3], GLdouble* vertex_data[4]
 GLvoid CALLBACK vertexCallback(GLdouble *vertex);
 
 OglRenderer::OglRenderer(ms_uint32 width, ms_uint32 height, colorObj* color)
-    : width(width), height(height), texture(NULL), transparency(1.0), valid(false)
-{    
-    context = new OglContext(width, height);
-    if (!context->isValid()) return;
-    if (!context->makeCurrent()) return;
-
-    int viewPort[4];
-    glGetIntegerv(GL_VIEWPORT ,viewPort);
-    viewportX = viewPort[0];
-    viewportY = viewPort[1];
-    viewportWidth = viewPort[2];
-    viewportHeight = viewPort[3];
-
-    glPushMatrix();
-
-    // set read/write context to pbuffer
-    glEnable(GL_MULTISAMPLE_ARB);
-    glHint(GL_MULTISAMPLE_FILTER_HINT_NV, GL_NICEST);
-
-    glEnable(GL_TEXTURE_2D);
-    glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE );
-    glEnable(GL_BLEND);
-    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
-
-    glDisable(GL_DEPTH_TEST);
-    glDepthFunc(GL_LEQUAL);
-
-    // draw & read the front buffer of pbuffer
-    glDrawBuffer(GL_FRONT);
-    glReadBuffer(GL_FRONT);
-
-    if (!(tess = gluNewTess()))
-    {
-        msSetError(MS_OGLERR, "P-buffer Error: Unable to create tessalotor",
-                "OglRenderer");
-        return;
-    }
-
-    gluTessCallback(tess, GLU_TESS_VERTEX, (void (CALLBACK*)(void)) vertexCallback);
-    gluTessCallback(tess, GLU_TESS_BEGIN, (void(CALLBACK*)(void)) beginCallback);
-    gluTessCallback(tess, GLU_TESS_END, (void(CALLBACK*)(void)) endCallback);
-    gluTessCallback(tess, GLU_TESS_ERROR, (void(CALLBACK*)(void)) errorCallback);
-    gluTessCallback(tess, GLU_TESS_COMBINE_DATA, (void(CALLBACK*)(void)) combineDataCallback);
-
-    if (color)
-    {
-        glClearColor((double) color->red / 255,
-                     (double) color->green / 255,
-                     (double) color->blue / 255,
-                     (double)color->alpha / 100);
-    }
-    else
-    {
-        glClearColor(0.0, 0.0, 0.0, 0.0);
-    }
-    glClear(GL_COLOR_BUFFER_BIT);
-
-    glViewport(0, 0, width, height);
-    glMatrixMode(GL_PROJECTION);
-    glLoadIdentity();
-    glOrtho(0.0, width, 0.0, height, -3.0, 3.0);
-
-    createShapes();
-    valid = true;
+  : width(width), height(height), texture(NULL), transparency(1.0), valid(false)
+{
+  context = new OglContext(width, height);
+  if (!context->isValid()) return;
+  if (!context->makeCurrent()) return;
+
+  int viewPort[4];
+  glGetIntegerv(GL_VIEWPORT ,viewPort);
+  viewportX = viewPort[0];
+  viewportY = viewPort[1];
+  viewportWidth = viewPort[2];
+  viewportHeight = viewPort[3];
+
+  glPushMatrix();
+
+  // set read/write context to pbuffer
+  glEnable(GL_MULTISAMPLE_ARB);
+  glHint(GL_MULTISAMPLE_FILTER_HINT_NV, GL_NICEST);
+
+  glEnable(GL_TEXTURE_2D);
+  glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE );
+  glEnable(GL_BLEND);
+  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
+
+  glDisable(GL_DEPTH_TEST);
+  glDepthFunc(GL_LEQUAL);
+
+  // draw & read the front buffer of pbuffer
+  glDrawBuffer(GL_FRONT);
+  glReadBuffer(GL_FRONT);
+
+  if (!(tess = gluNewTess())) {
+    msSetError(MS_OGLERR, "P-buffer Error: Unable to create tessalotor",
+               "OglRenderer");
+    return;
+  }
+
+  gluTessCallback(tess, GLU_TESS_VERTEX, (void (CALLBACK*)(void)) vertexCallback);
+  gluTessCallback(tess, GLU_TESS_BEGIN, (void(CALLBACK*)(void)) beginCallback);
+  gluTessCallback(tess, GLU_TESS_END, (void(CALLBACK*)(void)) endCallback);
+  gluTessCallback(tess, GLU_TESS_ERROR, (void(CALLBACK*)(void)) errorCallback);
+  gluTessCallback(tess, GLU_TESS_COMBINE_DATA, (void(CALLBACK*)(void)) combineDataCallback);
+
+  if (color) {
+    glClearColor((double) color->red / 255,
+                 (double) color->green / 255,
+                 (double) color->blue / 255,
+                 (double)color->alpha / 100);
+  } else {
+    glClearColor(0.0, 0.0, 0.0, 0.0);
+  }
+  glClear(GL_COLOR_BUFFER_BIT);
+
+  glViewport(0, 0, width, height);
+  glMatrixMode(GL_PROJECTION);
+  glLoadIdentity();
+  glOrtho(0.0, width, 0.0, height, -3.0, 3.0);
+
+  createShapes();
+  valid = true;
 }
 
 OglRenderer::~OglRenderer()
 {
-    makeCurrent();
-    glViewport(viewportX, viewportY, viewportWidth, viewportHeight);
-    glPopMatrix();
-    delete context;
+  makeCurrent();
+  glViewport(viewportX, viewportY, viewportWidth, viewportHeight);
+  glPopMatrix();
+  delete context;
 }
 
 OglCachePtr OglRenderer::getTexture()
 {
-    if (!texture)
-    {
-        makeCurrent();
-        texture = new OglCache();
-        texture->texture = createTexture(0,0);//TEXTURE_BORDER/2, TEXTURE_BORDER/2);
-        texture->width = this->width;
-        texture->height = this->height;
-    }
-    return texture;
+  if (!texture) {
+    makeCurrent();
+    texture = new OglCache();
+    texture->texture = createTexture(0,0);//TEXTURE_BORDER/2, TEXTURE_BORDER/2);
+    texture->width = this->width;
+    texture->height = this->height;
+  }
+  return texture;
 }
 
 GLuint OglRenderer::createTexture(ms_uint32 offsetX, ms_uint32 offsetY)
 {
-    GLuint texture = 0;
-    glGenTextures(1, &texture);
-    glBindTexture(GL_TEXTURE_2D, texture);
-    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
-    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
-    glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE);
-    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,GL_NEAREST);
-    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,GL_NEAREST);
-    if (OglContext::MAX_ANISOTROPY != 0)
-    {
-        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, OglContext::MAX_ANISOTROPY);
-    }
-    glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, offsetX, offsetY, context->getWidth(), context->getHeight(), 0);
-    glBindTexture(GL_TEXTURE_2D,0);
-    return texture;
+  GLuint texture = 0;
+  glGenTextures(1, &texture);
+  glBindTexture(GL_TEXTURE_2D, texture);
+  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
+  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
+  glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE);
+  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,GL_NEAREST);
+  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,GL_NEAREST);
+  if (OglContext::MAX_ANISOTROPY != 0) {
+    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, OglContext::MAX_ANISOTROPY);
+  }
+  glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, offsetX, offsetY, context->getWidth(), context->getHeight(), 0);
+  glBindTexture(GL_TEXTURE_2D,0);
+  return texture;
 }
 
 bool OglRenderer::getStringBBox(char *font, double size, char *string, rectObj *rect, double** advances)
-{    
-    FTFont* face = getFTFont(font, size);
-    if (!face) 
-    {
-        msSetError(MS_OGLERR, "Failed to load font (%s).", "OglRenderer::getStringBBox()", font);
-        return false;
-    }
-    
-    float llx =0.0f, lly=0.0f, llz=0.0f, urx=0.0f, ury=0.0f, urz=0.0f;
-    glPushAttrib( GL_ALL_ATTRIB_BITS );
-    FTBBox boundingBox = face->BBox(string);
-    glPopAttrib();
-
-    rect->minx = boundingBox.Lower().X();
-    rect->maxx = boundingBox.Upper().X();
-    rect->miny = -boundingBox.Upper().Y();
-    rect->maxy = -boundingBox.Lower().Y();
-        
-    if (advances)
-    {
-        int length = strlen(string);
-        *advances = new double[length];        
-        for (int i = 0; i < length; ++i)
-        {
-            (*advances)[i] = face->Advance(&string[i], 1);
-        }
+{
+  FTFont* face = getFTFont(font, size);
+  if (!face) {
+    msSetError(MS_OGLERR, "Failed to load font (%s).", "OglRenderer::getStringBBox()", font);
+    return false;
+  }
+
+  float llx =0.0f, lly=0.0f, llz=0.0f, urx=0.0f, ury=0.0f, urz=0.0f;
+  glPushAttrib( GL_ALL_ATTRIB_BITS );
+  FTBBox boundingBox = face->BBox(string);
+  glPopAttrib();
+
+  rect->minx = boundingBox.Lower().X();
+  rect->maxx = boundingBox.Upper().X();
+  rect->miny = -boundingBox.Upper().Y();
+  rect->maxy = -boundingBox.Lower().Y();
+
+  if (advances) {
+    int length = strlen(string);
+    *advances = new double[length];
+    for (int i = 0; i < length; ++i) {
+      (*advances)[i] = face->Advance(&string[i], 1);
     }
+  }
 
-    return true;
+  return true;
 }
 
-void OglRenderer::initializeRasterBuffer(rasterBufferObj * rb, int width, int height, bool useAlpha) 
-{   
-    unsigned char* buffer = new unsigned char[4 * width * height];
-    rb->data.rgba.pixels = buffer;
-    rb->data.rgba.r = &buffer[2];
-    rb->data.rgba.g = &buffer[1];
-    rb->data.rgba.b = &buffer[0];
-    if (useAlpha) rb->data.rgba.a = &buffer[3];   
-        
-    rb->type =MS_BUFFER_BYTE_RGBA;    
-    rb->data.rgba.row_step = 4*width;
-    rb->data.rgba.pixel_step = 4;
-    rb->width = width;
-    rb->height = height;
+void OglRenderer::initializeRasterBuffer(rasterBufferObj * rb, int width, int height, bool useAlpha)
+{
+  unsigned char* buffer = new unsigned char[4 * width * height];
+  rb->data.rgba.pixels = buffer;
+  rb->data.rgba.r = &buffer[2];
+  rb->data.rgba.g = &buffer[1];
+  rb->data.rgba.b = &buffer[0];
+  if (useAlpha) rb->data.rgba.a = &buffer[3];
+
+  rb->type =MS_BUFFER_BYTE_RGBA;
+  rb->data.rgba.row_step = 4*width;
+  rb->data.rgba.pixel_step = 4;
+  rb->width = width;
+  rb->height = height;
 }
 
-void OglRenderer::readRasterBuffer(rasterBufferObj * rb) 
-{   
-    makeCurrent();
-    unsigned char* buffer = new unsigned char[4 * width * height];
-    glReadPixels(0, 0, width, height, GL_BGRA, GL_UNSIGNED_BYTE, buffer);
-    
-    rb->type =MS_BUFFER_BYTE_RGBA;
-    rb->data.rgba.pixels = buffer;
-    rb->data.rgba.row_step = 4*width;
-    rb->data.rgba.pixel_step = 4;
-    rb->width = width;
-    rb->height = height;
-    rb->data.rgba.r = &buffer[2];
-    rb->data.rgba.g = &buffer[1];
-    rb->data.rgba.b = &buffer[0];
-    rb->data.rgba.a = NULL;
+void OglRenderer::readRasterBuffer(rasterBufferObj * rb)
+{
+  makeCurrent();
+  unsigned char* buffer = new unsigned char[4 * width * height];
+  glReadPixels(0, 0, width, height, GL_BGRA, GL_UNSIGNED_BYTE, buffer);
+
+  rb->type =MS_BUFFER_BYTE_RGBA;
+  rb->data.rgba.pixels = buffer;
+  rb->data.rgba.row_step = 4*width;
+  rb->data.rgba.pixel_step = 4;
+  rb->width = width;
+  rb->height = height;
+  rb->data.rgba.r = &buffer[2];
+  rb->data.rgba.g = &buffer[1];
+  rb->data.rgba.b = &buffer[0];
+  rb->data.rgba.a = NULL;
 }
 
 void OglRenderer::drawRasterBuffer(rasterBufferObj *overlay, double opacity, int srcX, int srcY, int dstX, int dstY, int width, int height)
 {
-    // todo to support all alpha and srcx/y this needs to be done by creating a texture
-    makeCurrent();
-    glDrawPixels(width, height, GL_BGRA, GL_UNSIGNED_BYTE, overlay->data.rgba.pixels);
+  // todo to support all alpha and srcx/y this needs to be done by creating a texture
+  makeCurrent();
+  glDrawPixels(width, height, GL_BGRA, GL_UNSIGNED_BYTE, overlay->data.rgba.pixels);
 }
 
 void OglRenderer::setTransparency(double transparency)
 {
-    this->transparency = transparency;
+  this->transparency = transparency;
 }
 
 void OglRenderer::setColor(colorObj *color)
 {
-    if (color && MS_VALID_COLOR(*color))
-    {
-        glColor4d((double) color->red / 255, (double) color->green / 255, (double) color->blue / 255, transparency);
-    }
-    else
-    {
-        glColor4d(0.0, 0.0, 0.0, 1.0);
-    }
+  if (color && MS_VALID_COLOR(*color)) {
+    glColor4d((double) color->red / 255, (double) color->green / 255, (double) color->blue / 255, transparency);
+  } else {
+    glColor4d(0.0, 0.0, 0.0, 1.0);
+  }
 }
 
 void OglRenderer::drawVectorLineStrip(symbolObj *symbol, double width)
 {
-    glPushMatrix();    
-    glLineWidth(width);
-    glBegin(GL_LINE_STRIP);
-    for (int i = 0; i < symbol->numpoints; i++)
-    {
-        if (symbol->points[i].x < 0 && symbol->points[i].y < 0)
-        {
-            glEnd();
-            glBegin(GL_LINE_STRIP);
-        }
-        else
-        {
-            glVertex2d(symbol->points[i].x, symbol->points[i].y);
-        }
+  glPushMatrix();
+  glLineWidth(width);
+  glBegin(GL_LINE_STRIP);
+  for (int i = 0; i < symbol->numpoints; i++) {
+    if (symbol->points[i].x < 0 && symbol->points[i].y < 0) {
+      glEnd();
+      glBegin(GL_LINE_STRIP);
+    } else {
+      glVertex2d(symbol->points[i].x, symbol->points[i].y);
     }
-    glEnd();
+  }
+  glEnd();
 
-    glPopMatrix();
+  glPopMatrix();
 }
 
 double OglRenderer::drawTriangles(pointObj* p1, pointObj* p2, double width, double tilelength, double textureStart)
 {
-    double dx = p1->x - p2->x;
-    double dy = p1->y - p2->y;
-    double dist = sqrt(dx * dx + dy * dy);
-    double theta;
-    if (dx != 0)
-        theta = atan(dy / dx);
-    else
-        theta = (dy > 0 ? 1 : -1) * OGL_PI / 2;
-
-    double xw = sin(theta) * width / 2;
-    double yw = cos(theta) * width / 2;
-
-    double textureEnd = dist / tilelength;
-
-    glTexCoord2d(textureStart, 1);
-    glVertex2d(p1->x + xw, p1->y - yw); // Bottom Left Of The Texture and Quad
-    glTexCoord2d(textureStart, 0);
-    glVertex2d(p1->x - xw, p1->y + yw); // Bottom Right Of The Texture and Quad
-    glTexCoord2d(textureStart + textureEnd, 1);
-    glVertex2d(p2->x + xw, p2->y - yw); // Top Right Of The Texture and Quad
-    glTexCoord2d(textureStart + textureEnd, 0);
-    glVertex2d(p2->x - xw, p2->y + yw); // Top Left Of The Texture and Quad
-
-    return dist;
+  double dx = p1->x - p2->x;
+  double dy = p1->y - p2->y;
+  double dist = sqrt(dx * dx + dy * dy);
+  double theta;
+  if (dx != 0)
+    theta = atan(dy / dx);
+  else
+    theta = (dy > 0 ? 1 : -1) * OGL_PI / 2;
+
+  double xw = sin(theta) * width / 2;
+  double yw = cos(theta) * width / 2;
+
+  double textureEnd = dist / tilelength;
+
+  glTexCoord2d(textureStart, 1);
+  glVertex2d(p1->x + xw, p1->y - yw); // Bottom Left Of The Texture and Quad
+  glTexCoord2d(textureStart, 0);
+  glVertex2d(p1->x - xw, p1->y + yw); // Bottom Right Of The Texture and Quad
+  glTexCoord2d(textureStart + textureEnd, 1);
+  glVertex2d(p2->x + xw, p2->y - yw); // Top Right Of The Texture and Quad
+  glTexCoord2d(textureStart + textureEnd, 0);
+  glVertex2d(p2->x - xw, p2->y + yw); // Top Left Of The Texture and Quad
+
+  return dist;
 }
 
 double OglRenderer::drawQuad(pointObj* p1, pointObj* p2, double width, double tilelength, double textureStart)
 {
-    double dx = p1->x - p2->x;
-    double dy = p1->y - p2->y;
-    double dist = sqrt(dx * dx + dy * dy);
-    double theta;
-    if (dx)
-        theta = atan(dy / dx);
-    else
-        theta = (dy > 0 ? 1 : -1) * OGL_PI / 2;
-
-    glPushMatrix();
-    glTranslated(p1->x, p1->y, 0);
-    glRotated((p1->x < p2->x ? 0 : 180) + theta * (180 / OGL_PI), 0, 0, 1);
-    glTranslated(-p1->x, -p1->y, 0);
-
-    glBegin(GL_QUADS);
-    glTexCoord2d(textureStart, 1);
-    glVertex2d(p1->x, p1->y - width / 2); // Bottom Left Of The Texture and Quad
-    glTexCoord2d(textureStart + (dist / tilelength), 1);
-    glVertex2d(p1->x + dist, p1->y - width / 2); // Bottom Right Of The Texture and Quad
-    glTexCoord2d(textureStart + (dist / tilelength), 0);
-    glVertex2d(p1->x + dist, p1->y + width / 2); // Top Right Of The Texture and Quad
-    glTexCoord2d(textureStart, 0);
-    glVertex2d(p1->x, p1->y + width / 2); // Top Left Of The Texture and Quad
-    glEnd();
-
-    glPopMatrix();
-
-    return dist;
+  double dx = p1->x - p2->x;
+  double dy = p1->y - p2->y;
+  double dist = sqrt(dx * dx + dy * dy);
+  double theta;
+  if (dx)
+    theta = atan(dy / dx);
+  else
+    theta = (dy > 0 ? 1 : -1) * OGL_PI / 2;
+
+  glPushMatrix();
+  glTranslated(p1->x, p1->y, 0);
+  glRotated((p1->x < p2->x ? 0 : 180) + theta * (180 / OGL_PI), 0, 0, 1);
+  glTranslated(-p1->x, -p1->y, 0);
+
+  glBegin(GL_QUADS);
+  glTexCoord2d(textureStart, 1);
+  glVertex2d(p1->x, p1->y - width / 2); // Bottom Left Of The Texture and Quad
+  glTexCoord2d(textureStart + (dist / tilelength), 1);
+  glVertex2d(p1->x + dist, p1->y - width / 2); // Bottom Right Of The Texture and Quad
+  glTexCoord2d(textureStart + (dist / tilelength), 0);
+  glVertex2d(p1->x + dist, p1->y + width / 2); // Top Right Of The Texture and Quad
+  glTexCoord2d(textureStart, 0);
+  glVertex2d(p1->x, p1->y + width / 2); // Top Left Of The Texture and Quad
+  glEnd();
+
+  glPopMatrix();
+
+  return dist;
 }
 
 void OglRenderer::renderTile(const OglCachePtr& tile, double x, double y, double angle)
 {
-    makeCurrent();
-    glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE_ARB);
-    glBindTexture(GL_TEXTURE_2D, tile->texture);
-    glPushMatrix();
-    glTranslated(x, y, 0);
-    if (angle)
-    {
-        glRotated(angle, 0, 0, 1);
-    }
-    glTranslated(-x, -y, 0);
-    glBegin(GL_QUADS);
-        glTexCoord2d(0, 1); glVertex2d( x-(tile->width/2), y+(tile->height/2));    // Bottom Left Of The Texture and Quad
-        glTexCoord2d(1, 1); glVertex2d( x+(tile->width/2), y+(tile->height/2));    // Bottom Right Of The Texture and Quad
-        glTexCoord2d(1, 0); glVertex2d( x+(tile->width/2), y-(tile->height/2));    // Top Right Of The Texture and Quad
-        glTexCoord2d(0, 0); glVertex2d( x-(tile->width/2), y-(tile->height/2));    // Top Left Of The Texture and Quad
-    glEnd();
-
-    glPopMatrix();
-    glBindTexture(GL_TEXTURE_2D, 0);
-    glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE_ARB);
+  makeCurrent();
+  glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE_ARB);
+  glBindTexture(GL_TEXTURE_2D, tile->texture);
+  glPushMatrix();
+  glTranslated(x, y, 0);
+  if (angle) {
+    glRotated(angle, 0, 0, 1);
+  }
+  glTranslated(-x, -y, 0);
+  glBegin(GL_QUADS);
+  glTexCoord2d(0, 1);
+  glVertex2d( x-(tile->width/2), y+(tile->height/2));    // Bottom Left Of The Texture and Quad
+  glTexCoord2d(1, 1);
+  glVertex2d( x+(tile->width/2), y+(tile->height/2));    // Bottom Right Of The Texture and Quad
+  glTexCoord2d(1, 0);
+  glVertex2d( x+(tile->width/2), y-(tile->height/2));    // Top Right Of The Texture and Quad
+  glTexCoord2d(0, 0);
+  glVertex2d( x-(tile->width/2), y-(tile->height/2));    // Top Left Of The Texture and Quad
+  glEnd();
+
+  glPopMatrix();
+  glBindTexture(GL_TEXTURE_2D, 0);
+  glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE_ARB);
 }
 
-void OglRenderer::renderPolylineTile(shapeObj *shape, const OglCachePtr& tile){
-    makeCurrent();
-    glBindTexture(GL_TEXTURE_2D, tile->texture); // Select Our Texture
-    glBegin(GL_TRIANGLE_STRIP);
-
-    double place = 0.0;
-    for (int i = 0; i < shape->numlines; i++)
-    {
-        for (int j = 0; j < shape->line[i].numpoints - 1; j++)
-        {
-            double dist = drawTriangles(&shape->line[i].point[j], &shape->line[i].point[j + 1], tile->height, tile->width, place / tile->width);
-            place = (place + dist);
-            while (place >= tile->width) place -= tile->width;
-        }
+void OglRenderer::renderPolylineTile(shapeObj *shape, const OglCachePtr& tile)
+{
+  makeCurrent();
+  glBindTexture(GL_TEXTURE_2D, tile->texture); // Select Our Texture
+  glBegin(GL_TRIANGLE_STRIP);
+
+  double place = 0.0;
+  for (int i = 0; i < shape->numlines; i++) {
+    for (int j = 0; j < shape->line[i].numpoints - 1; j++) {
+      double dist = drawTriangles(&shape->line[i].point[j], &shape->line[i].point[j + 1], tile->height, tile->width, place / tile->width);
+      place = (place + dist);
+      while (place >= tile->width) place -= tile->width;
     }
-    glEnd();
-    glBindTexture(GL_TEXTURE_2D, 0);
+  }
+  glEnd();
+  glBindTexture(GL_TEXTURE_2D, 0);
 }
 
 
 void OglRenderer::renderVectorSymbol(double x, double y, symbolObj *symbol, double scale, double angle, colorObj *c, colorObj *oc, double ow)
 {
-    makeCurrent();
-    glPushMatrix();
-    glTranslated(x, y, 0);
-    glRotated(angle, 0, 0, 1);
-    glScaled(scale, scale, 0);
+  makeCurrent();
+  glPushMatrix();
+  glTranslated(x, y, 0);
+  glRotated(angle, 0, 0, 1);
+  glScaled(scale, scale, 0);
 
-    glTranslated(-symbol->sizex/2, -symbol->sizey/2, 0.0);
+  glTranslated(-symbol->sizex/2, -symbol->sizey/2, 0.0);
 
-    if (oc != NULL && MS_VALID_COLOR(*oc) && ow > 0)
-    {
-        setColor(oc);
-        drawVectorLineStrip(symbol, ow);
-    }
+  if (oc != NULL && MS_VALID_COLOR(*oc) && ow > 0) {
+    setColor(oc);
+    drawVectorLineStrip(symbol, ow);
+  }
 
-    if (c != NULL && MS_VALID_COLOR(*c) && ow > 0)
-    {
-        setColor(c);
-        drawVectorLineStrip(symbol, ow);
-    }
+  if (c != NULL && MS_VALID_COLOR(*c) && ow > 0) {
+    setColor(c);
+    drawVectorLineStrip(symbol, ow);
+  }
 
-    glPopMatrix();
+  glPopMatrix();
 }
 
 void OglRenderer::renderPolyline(shapeObj *p, colorObj *c, double width,
-        int patternlength, double* pattern, int lineCap, int joinStyle,
-        colorObj *outlinecolor, double outlinewidth)
+                                 int patternlength, double* pattern, int lineCap, int joinStyle,
+                                 colorObj *outlinecolor, double outlinewidth)
 {
-    makeCurrent();
-    if (outlinecolor)
-    {
-        glEnable(GL_DEPTH_TEST);
-        glPushMatrix();
-        glTranslated(0, 0, 1);
-    }
+  makeCurrent();
+  if (outlinecolor) {
+    glEnable(GL_DEPTH_TEST);
+    glPushMatrix();
+    glTranslated(0, 0, 1);
+  }
 
-    setColor(c);
+  setColor(c);
 
-    if (patternlength > 0)
-    {
-        if (p->renderer_cache == NULL)
-        {
-            loadLine(p, width, patternlength, pattern);
-        }
-        /* FIXME */
-        if (p->renderer_cache == NULL)
-           return;
-        OglCache* cache = (OglCache*) p->renderer_cache;
-        GLuint texture = cache->texture;
-        if (cache->patternDistance > 0)
-        {
-            glBindTexture(GL_TEXTURE_2D, texture);
-            double place = 0;
-            glBegin(GL_TRIANGLE_STRIP);
-            for (int j = 0; j < p->numlines; j++)
-            {
-                for (int i = 0; i < p->line[j].numpoints - 1; i++)
-                {
-                    double dist = drawTriangles(&p->line[j].point[i],
-                            &p->line[j].point[i + 1], width,
-                            cache->patternDistance, place
-                                    / cache->patternDistance);
-                    place = (place + dist);
-                    while (place >= cache->patternDistance)
-                        place -= cache->patternDistance; // better than mod, no rounding
-                }
-            }
-            glEnd();
-            glBindTexture(GL_TEXTURE_2D, 0);
+  if (patternlength > 0) {
+    if (p->renderer_cache == NULL) {
+      loadLine(p, width, patternlength, pattern);
+    }
+    /* FIXME */
+    if (p->renderer_cache == NULL)
+      return;
+    OglCache* cache = (OglCache*) p->renderer_cache;
+    GLuint texture = cache->texture;
+    if (cache->patternDistance > 0) {
+      glBindTexture(GL_TEXTURE_2D, texture);
+      double place = 0;
+      glBegin(GL_TRIANGLE_STRIP);
+      for (int j = 0; j < p->numlines; j++) {
+        for (int i = 0; i < p->line[j].numpoints - 1; i++) {
+          double dist = drawTriangles(&p->line[j].point[i],
+                                      &p->line[j].point[i + 1], width,
+                                      cache->patternDistance, place
+                                      / cache->patternDistance);
+          place = (place + dist);
+          while (place >= cache->patternDistance)
+            place -= cache->patternDistance; // better than mod, no rounding
         }
+      }
+      glEnd();
+      glBindTexture(GL_TEXTURE_2D, 0);
     }
-    else
-    {
-        float widthRange[2];
-        glGetFloatv(GL_LINE_WIDTH_RANGE, widthRange);
-        bool quads = !(width >= widthRange[0] && width <= widthRange[1]);
-        double circleScale = width / SHAPE_CIRCLE_RADIUS / 2;
-        glLineWidth(width);
-        if (quads || (width > 1.0 && (lineCap == MS_CJC_ROUND || joinStyle == MS_CJC_ROUND)))
-        {
-            for (int j = 0; j < p->numlines; j++)
-            {
-                for (int i = 0; i < p->line[j].numpoints; i++)
-                {
-                    if (i != p->line[j].numpoints - 1)
-                    {
-                        if (quads)
-                        {
-                            drawQuad(&p->line[j].point[i], &p->line[j].point[i
-                                    + 1], width);
-                        }
-                        else
-                        {
-                            glBegin(GL_LINES);
-                            glVertex2f(p->line[j].point[i].x, p->line[j].point[i].y);
-                            glVertex2f(p->line[j].point[i + 1].x,p->line[j].point[i + 1].y);
-                            glEnd();
-                        }
-                    }
-                    if ((lineCap == MS_CJC_ROUND && (i == 0 || i == p->line[j].numpoints - 1)) ||
-                        (joinStyle == MS_CJC_ROUND && (i > 0 && i < p->line[j].numpoints - 1)))
-                    {
-                        glPushMatrix();
-                        glTranslated(p->line[j].point[i].x, p->line[j].point[i].y, 0);
-                        glScaled(circleScale, circleScale, 0);
-                        glCallList(shapes[circle]);
-                        glPopMatrix();
-                    }
-                }
+  } else {
+    float widthRange[2];
+    glGetFloatv(GL_LINE_WIDTH_RANGE, widthRange);
+    bool quads = !(width >= widthRange[0] && width <= widthRange[1]);
+    double circleScale = width / SHAPE_CIRCLE_RADIUS / 2;
+    glLineWidth(width);
+    if (quads || (width > 1.0 && (lineCap == MS_CJC_ROUND || joinStyle == MS_CJC_ROUND))) {
+      for (int j = 0; j < p->numlines; j++) {
+        for (int i = 0; i < p->line[j].numpoints; i++) {
+          if (i != p->line[j].numpoints - 1) {
+            if (quads) {
+              drawQuad(&p->line[j].point[i], &p->line[j].point[i
+                       + 1], width);
+            } else {
+              glBegin(GL_LINES);
+              glVertex2f(p->line[j].point[i].x, p->line[j].point[i].y);
+              glVertex2f(p->line[j].point[i + 1].x,p->line[j].point[i + 1].y);
+              glEnd();
             }
+          }
+          if ((lineCap == MS_CJC_ROUND && (i == 0 || i == p->line[j].numpoints - 1)) ||
+              (joinStyle == MS_CJC_ROUND && (i > 0 && i < p->line[j].numpoints - 1))) {
+            glPushMatrix();
+            glTranslated(p->line[j].point[i].x, p->line[j].point[i].y, 0);
+            glScaled(circleScale, circleScale, 0);
+            glCallList(shapes[circle]);
+            glPopMatrix();
+          }
         }
-        else
-        {
-            for (int j = 0; j < p->numlines; j++)
-            {
-                glBegin(GL_LINE_STRIP);
-                for (int i = 0; i < p->line[j].numpoints; i++)
-                {
-                    glVertex2f(p->line[j].point[i].x, p->line[j].point[i].y);
-                }
-                glEnd();
-
-            }
+      }
+    } else {
+      for (int j = 0; j < p->numlines; j++) {
+        glBegin(GL_LINE_STRIP);
+        for (int i = 0; i < p->line[j].numpoints; i++) {
+          glVertex2f(p->line[j].point[i].x, p->line[j].point[i].y);
         }
-    }
+        glEnd();
 
-    if (outlinecolor != NULL && MS_VALID_COLOR(*outlinecolor))
-    {
-        glPopMatrix();
-        double owidth = MS_MAX(width + OUTLINE_WIDTH, outlinewidth);
-        glPushMatrix();
-        glTranslated(0, 0, -1);
-        renderPolyline(p, outlinecolor, owidth, patternlength, pattern, lineCap, joinStyle);
-        glPopMatrix();
-        glDisable(GL_DEPTH_TEST);
+      }
     }
+  }
+
+  if (outlinecolor != NULL && MS_VALID_COLOR(*outlinecolor)) {
+    glPopMatrix();
+    double owidth = MS_MAX(width + OUTLINE_WIDTH, outlinewidth);
+    glPushMatrix();
+    glTranslated(0, 0, -1);
+    renderPolyline(p, outlinecolor, owidth, patternlength, pattern, lineCap, joinStyle);
+    glPopMatrix();
+    glDisable(GL_DEPTH_TEST);
+  }
 
 }
 
 void OglRenderer::renderPolygon(shapeObj *p, colorObj *color, colorObj *outlinecolor, double outlinewidth, const OglCachePtr& tile, int lineCap, int joinStyle)
 {
-    /*
-     OpenGL cannot draw complex polygons so we need to use a Tessallator to draw the polygon using a GL_TRIANGLE_FAN
-
-     ISSUE: There's a problem here. It would seem that changing the dimensions or bounding box area breaks the code.
-     Reports need for a combine callback.
-     */
-    makeCurrent();
-    std::vector<GLdouble*> pointers;
-    double texWidth = 0;
-    double texHeight = 0;
-
-    if (tile)
-    {
-        glBindTexture(GL_TEXTURE_2D, tile->texture); // Select Our Texture
-        texWidth = tile->width;
-        texHeight = tile->height;
+  /*
+   OpenGL cannot draw complex polygons so we need to use a Tessallator to draw the polygon using a GL_TRIANGLE_FAN
+
+   ISSUE: There's a problem here. It would seem that changing the dimensions or bounding box area breaks the code.
+   Reports need for a combine callback.
+   */
+  makeCurrent();
+  std::vector<GLdouble*> pointers;
+  double texWidth = 0;
+  double texHeight = 0;
+
+  if (tile) {
+    glBindTexture(GL_TEXTURE_2D, tile->texture); // Select Our Texture
+    texWidth = tile->width;
+    texHeight = tile->height;
+  }
+  setColor(color);
+  gluTessBeginPolygon(tess, NULL );
+  for (int j = 0; j < p->numlines; j++) {
+    gluTessBeginContour(tess);
+    for (int i = 0; i < p->line[j].numpoints; i++) {
+      // create temp array and place
+      GLdouble* dbls = new GLdouble[5];
+      pointers.push_back(dbls);
+      dbls[0] = p->line[j].point[i].x;
+      dbls[1] = p->line[j].point[i].y;
+      dbls[2] = 0.0;
+      dbls[3] = texWidth;
+      dbls[4] = texHeight;
+      gluTessVertex(tess, dbls, dbls);
     }
-    setColor(color);
-    gluTessBeginPolygon(tess, NULL );
-    for (int j = 0; j < p->numlines; j++)
-    {
-        gluTessBeginContour(tess);
-        for (int i = 0; i < p->line[j].numpoints; i++)
-        {
-            // create temp array and place
-            GLdouble* dbls = new GLdouble[5];
-            pointers.push_back(dbls);
-            dbls[0] = p->line[j].point[i].x;
-            dbls[1] = p->line[j].point[i].y;
-            dbls[2] = 0.0;
-            dbls[3] = texWidth;
-            dbls[4] = texHeight;
-            gluTessVertex(tess, dbls, dbls);
-        }
-        gluTessEndContour(tess);
+    gluTessEndContour(tess);
 
-    }
-    gluTessEndPolygon(tess);
+  }
+  gluTessEndPolygon(tess);
 
-    // destroy temp arrays
-    for (std::vector<GLdouble*>::iterator iter = pointers.begin(); iter
-            != pointers.end(); iter++)
-    {
-        delete[] *iter;
-    }
+  // destroy temp arrays
+  for (std::vector<GLdouble*>::iterator iter = pointers.begin(); iter
+       != pointers.end(); iter++) {
+    delete[] *iter;
+  }
 
-    glBindTexture(GL_TEXTURE_2D, 0); // Select Our Texture
+  glBindTexture(GL_TEXTURE_2D, 0); // Select Our Texture
 
-    if (outlinecolor != NULL && MS_VALID_COLOR(*outlinecolor) && outlinewidth > 0)
-    {
-        renderPolyline(p, outlinecolor, outlinewidth, 0, NULL, lineCap,
-                joinStyle);
-    }
+  if (outlinecolor != NULL && MS_VALID_COLOR(*outlinecolor) && outlinewidth > 0) {
+    renderPolyline(p, outlinecolor, outlinewidth, 0, NULL, lineCap,
+                   joinStyle);
+  }
 }
 
 void OglRenderer::renderGlyphs(double x, double y, colorObj *color,
-        colorObj *outlinecolor, double size, char* font, char *thechars, double angle,
-        colorObj *shadowcolor, double shdx, double shdy)
+                               colorObj *outlinecolor, double size, const char* font, char *thechars, double angle,
+                               colorObj *shadowcolor, double shdx, double shdy)
 {
-    makeCurrent();    
-    FTFont* face = getFTFont(font, size);
-    if (!face) 
-    {
-        msSetError(MS_OGLERR, "Failed to load font (%s).", "OglRenderer::renderGlyphs()", font);
-        return;
-    }
-
-    glPushAttrib(GL_ALL_ATTRIB_BITS);
-    glPushMatrix();
-
-    glTranslated(floor(x), floor(y), 0);    
-    glScaled(1.0, -1.0, 1);
-    glRotated(angle * (180 / OGL_PI), 0, 0, 1);
-    
-    if (outlinecolor && MS_VALID_COLOR(*outlinecolor))
-    {
-        setColor(outlinecolor);
-        for (int i = -1; i <= 1; i++)
-        {
-            for (int j = -1; j <= 1; j++)
-            {
-                if (i || j)
-                {
-                    glPushMatrix();
-                    glTranslated(i, j, 0);
-                    face->Render(thechars);
-                    glPopMatrix();
-                }
-            }
+  makeCurrent();
+  FTFont* face = getFTFont(font, size);
+  if (!face) {
+    msSetError(MS_OGLERR, "Failed to load font (%s).", "OglRenderer::renderGlyphs()", font);
+    return;
+  }
+
+  glPushAttrib(GL_ALL_ATTRIB_BITS);
+  glPushMatrix();
+
+  glTranslated(floor(x), floor(y), 0);
+  glScaled(1.0, -1.0, 1);
+  glRotated(angle * (180 / OGL_PI), 0, 0, 1);
+
+  if (outlinecolor && MS_VALID_COLOR(*outlinecolor)) {
+    setColor(outlinecolor);
+    for (int i = -1; i <= 1; i++) {
+      for (int j = -1; j <= 1; j++) {
+        if (i || j) {
+          glPushMatrix();
+          glTranslated(i, j, 0);
+          face->Render(thechars);
+          glPopMatrix();
         }
+      }
     }
-    if (color != NULL && MS_VALID_COLOR(*color))
-    {
-        setColor(color);
-        face->Render(thechars);
-    }
+  }
+  if (color != NULL && MS_VALID_COLOR(*color)) {
+    setColor(color);
+    face->Render(thechars);
+  }
 
-    glPopMatrix();
-    glPopAttrib();
+  glPopMatrix();
+  glPopAttrib();
 }
 
 void OglRenderer::renderPixmap(symbolObj *symbol, double x, double y,
-        double angle, double scale)
+                               double angle, double scale)
 {
-    makeCurrent();
+  makeCurrent();
+
+  float zoomX, zoomY;
+  glGetFloatv(GL_ZOOM_X, &zoomX);
+  glGetFloatv(GL_ZOOM_Y, &zoomY);
 
-    float zoomX, zoomY;
-    glGetFloatv(GL_ZOOM_X, &zoomX);
-    glGetFloatv(GL_ZOOM_Y, &zoomY);
 
-    
-    GLubyte* imgdata = symbol->pixmap_buffer->data.rgba.pixels;
-    glPixelZoom(zoomX*scale, zoomY*scale);
-    glRasterPos2d(x-symbol->pixmap_buffer->width/2, y-symbol->pixmap_buffer->height/2);    
-    glDrawPixels(symbol->pixmap_buffer->width, symbol->pixmap_buffer->height, GL_BGRA, GL_UNSIGNED_BYTE, imgdata);
-    glPixelZoom(zoomX, zoomY);    
+  GLubyte* imgdata = symbol->pixmap_buffer->data.rgba.pixels;
+  glPixelZoom(zoomX*scale, zoomY*scale);
+  glRasterPos2d(x-symbol->pixmap_buffer->width/2, y-symbol->pixmap_buffer->height/2);
+  glDrawPixels(symbol->pixmap_buffer->width, symbol->pixmap_buffer->height, GL_BGRA, GL_UNSIGNED_BYTE, imgdata);
+  glPixelZoom(zoomX, zoomY);
 }
 
 void OglRenderer::renderEllipse(double x, double y, double angle, double width, double height,
-        colorObj *color, colorObj *outlinecolor, double outlinewidth = 1.0)
+                                colorObj *color, colorObj *outlinecolor, double outlinewidth = 1.0)
 {
-    makeCurrent();
-    if (outlinecolor && MS_VALID_COLOR(*outlinecolor))
-    {
-        glEnable(GL_DEPTH_TEST);
-        glPushMatrix();
-        glTranslated(0, 0, 1);
-    }
+  makeCurrent();
+  if (outlinecolor && MS_VALID_COLOR(*outlinecolor)) {
+    glEnable(GL_DEPTH_TEST);
+    glPushMatrix();
+    glTranslated(0, 0, 1);
+  }
 
-    setColor(color);
+  setColor(color);
 
+  glPushMatrix();
+  if (angle) {
+    glRotated(angle, 0, 0, 1);
+  }
+  glTranslated(x, y, 0);
+  glScaled(width / SHAPE_CIRCLE_RADIUS / 2, height / SHAPE_CIRCLE_RADIUS / 2, 1);
+  glCallList(shapes[circle]);
+  glPopMatrix();
+
+  if (outlinecolor != NULL && MS_VALID_COLOR(*outlinecolor)) {
+    glPopMatrix();
     glPushMatrix();
-    if (angle)
-    {
-        glRotated(angle, 0, 0, 1);
-    }
-    glTranslated(x, y, 0);
-    glScaled(width / SHAPE_CIRCLE_RADIUS / 2, height / SHAPE_CIRCLE_RADIUS / 2, 1);
-    glCallList(shapes[circle]);
+    glTranslated(0, 0, -1);
+    renderEllipse(x, y, angle, width + outlinewidth, height, outlinecolor, NULL, 0);
     glPopMatrix();
-
-    if (outlinecolor != NULL && MS_VALID_COLOR(*outlinecolor))
-    {
-        glPopMatrix();
-        glPushMatrix();
-        glTranslated(0, 0, -1);
-        renderEllipse(x, y, angle, width + outlinewidth, height, outlinecolor, NULL, 0);
-        glPopMatrix();
-        glDisable(GL_DEPTH_TEST);
-    }
+    glDisable(GL_DEPTH_TEST);
+  }
 
 }
 
 bool OglRenderer::loadLine(shapeObj* shape, double width, int patternlength,
-        double* pattern)
+                           double* pattern)
 {
-/*    OglCache* cache = (OglCache*) shape->renderer_cache;
-
-    if (cache->patternDistance == 0)
-    {
-        for (int i = 0; i < patternlength; i++)
-        {
-            cache->patternDistance += pattern[i];
-        }
-    }
-    GLubyte imgdata[TEX_SIZE * TEX_SIZE * 4];
-    int pow2length = min(max(NextPowerOf2(cache->patternDistance), MIN_TEX_SIZE), TEX_SIZE);
-    int pow2width = min(max(NextPowerOf2(width), MIN_TEX_SIZE), TEX_SIZE);
-
-    double lengthScale = (double) pow2length / cache->patternDistance;
-    glColor3d(0, 0, 0);
-    double place = 0;
-    double xRadii = width / 2 * lengthScale;
-    double yRadii = pow2width / 2;
-    for (int i = 0; i < patternlength; i++)
-    {
-        double next = pattern[i] * lengthScale;
-        if (i % 2 == 0)
-        {
-
-            glPushMatrix();
-            glTranslated(place + xRadii, yRadii, 0);
-            glScaled(xRadii / SHAPE_CIRCLE_RADIUS,
-                    yRadii / SHAPE_CIRCLE_RADIUS, 0);
-            glCallList(shapes[circle]);
-            glPopMatrix();
-
-            glBegin(GL_QUADS);
-            glVertex2d(place + pow2width / 2, 0);
-            glVertex2d(place + next - pow2width / 2, 0);
-            glVertex2d(place + next - pow2width / 2, pow2width);
-            glVertex2d(place + pow2width / 2, pow2width);
-            glEnd();
-
-            glPushMatrix();
-            glTranslated(place + next - xRadii, yRadii, 0);
-            glScaled(xRadii / SHAPE_CIRCLE_RADIUS,
-                    yRadii / SHAPE_CIRCLE_RADIUS, 0);
-            glCallList(shapes[circle]);
-            glPopMatrix();
-
-        }
-        place += next;
-    }
-
-    glReadPixels(0, 0, pow2length, pow2width, GL_RGBA, GL_UNSIGNED_BYTE,
-            imgdata);
-    //createTexture(pow2length, pow2width, GL_ALPHA, imgdata);*/
-    return true;
+  /*    OglCache* cache = (OglCache*) shape->renderer_cache;
+
+      if (cache->patternDistance == 0)
+      {
+          for (int i = 0; i < patternlength; i++)
+          {
+              cache->patternDistance += pattern[i];
+          }
+      }
+      GLubyte imgdata[TEX_SIZE * TEX_SIZE * 4];
+      int pow2length = min(max(NextPowerOf2(cache->patternDistance), MIN_TEX_SIZE), TEX_SIZE);
+      int pow2width = min(max(NextPowerOf2(width), MIN_TEX_SIZE), TEX_SIZE);
+
+      double lengthScale = (double) pow2length / cache->patternDistance;
+      glColor3d(0, 0, 0);
+      double place = 0;
+      double xRadii = width / 2 * lengthScale;
+      double yRadii = pow2width / 2;
+      for (int i = 0; i < patternlength; i++)
+      {
+          double next = pattern[i] * lengthScale;
+          if (i % 2 == 0)
+          {
+
+              glPushMatrix();
+              glTranslated(place + xRadii, yRadii, 0);
+              glScaled(xRadii / SHAPE_CIRCLE_RADIUS,
+                      yRadii / SHAPE_CIRCLE_RADIUS, 0);
+              glCallList(shapes[circle]);
+              glPopMatrix();
+
+              glBegin(GL_QUADS);
+              glVertex2d(place + pow2width / 2, 0);
+              glVertex2d(place + next - pow2width / 2, 0);
+              glVertex2d(place + next - pow2width / 2, pow2width);
+              glVertex2d(place + pow2width / 2, pow2width);
+              glEnd();
+
+              glPushMatrix();
+              glTranslated(place + next - xRadii, yRadii, 0);
+              glScaled(xRadii / SHAPE_CIRCLE_RADIUS,
+                      yRadii / SHAPE_CIRCLE_RADIUS, 0);
+              glCallList(shapes[circle]);
+              glPopMatrix();
+
+          }
+          place += next;
+      }
+
+      glReadPixels(0, 0, pow2length, pow2width, GL_RGBA, GL_UNSIGNED_BYTE,
+              imgdata);
+      //createTexture(pow2length, pow2width, GL_ALPHA, imgdata);*/
+  return true;
 }
 
-FTFont* OglRenderer::getFTFont(char* font, double size)
+FTFont* OglRenderer::getFTFont(const char* font, double size)
 {
-    FTFont** face = &fontCache[font][size];
-    if (*face == NULL && ifstream(font))
-    {
-        *face = new FTGLTextureFont( font );
-        if (*face)
-        {
-            (*face)->UseDisplayList(true);
-            (*face)->FaceSize(size*SIZE_RES);        
-        }
-    }    
-    return *face;
+  FTFont** face = &fontCache[font][size];
+  if (*face == NULL && ifstream(font)) {
+    *face = new FTGLTextureFont( font );
+    if (*face) {
+      (*face)->UseDisplayList(true);
+      (*face)->FaceSize(size*SIZE_RES);
+    }
+  }
+  return *face;
 }
 
 GLvoid CALLBACK beginCallback(GLenum which)
 {
-    glBegin(which);
+  glBegin(which);
 }
 
 GLvoid CALLBACK errorCallback(GLenum errorCode)
 {
-    const GLubyte *estring;
-    estring = gluErrorString(errorCode);
-    fprintf(stderr, "Tessellation Error: %d %s\n", errorCode, estring);
-    exit(0);
+  const GLubyte *estring;
+  estring = gluErrorString(errorCode);
+  fprintf(stderr, "Tessellation Error: %d %s\n", errorCode, estring);
+  exit(0);
 }
 
 GLvoid CALLBACK endCallback(void)
 {
-    glEnd();
+  glEnd();
 }
 
 GLvoid CALLBACK combineDataCallback(GLdouble coords[3], GLdouble* vertex_data[4],
-        GLfloat weight[4], void** dataOut, void* polygon_data)
+                                    GLfloat weight[4], void** dataOut, void* polygon_data)
 {
-    GLdouble *vertex;
-    vertex = (GLdouble *) malloc(5 * sizeof(GLdouble));
-    vertex[0] = coords[0];
-    vertex[1] = coords[1];
-    vertex[2] = coords[2];
-    vertex[3] = vertex_data[0][3];
-    vertex[4] = vertex_data[0][4];
-    *dataOut = vertex;
+  GLdouble *vertex;
+  vertex = (GLdouble *) malloc(5 * sizeof(GLdouble));
+  vertex[0] = coords[0];
+  vertex[1] = coords[1];
+  vertex[2] = coords[2];
+  vertex[3] = vertex_data[0][3];
+  vertex[4] = vertex_data[0][4];
+  *dataOut = vertex;
 }
 
 GLvoid CALLBACK vertexCallback(GLdouble *vertex)
 {
-    if (vertex[3] > 0) glTexCoord2d(vertex[0]/vertex[3], vertex[1]/vertex[4]);
-    glVertex3dv(vertex);
+  if (vertex[3] > 0) glTexCoord2d(vertex[0]/vertex[3], vertex[1]/vertex[4]);
+  glVertex3dv(vertex);
 }
 
 void OglRenderer::createShapes()
 {
-    double da = MS_MIN(OGL_PI / 2, OGL_PI / SHAPE_CIRCLE_RES);
-    GLuint circle = glGenLists(1);
-    glNewList(circle, GL_COMPILE);
-    glBegin(GL_TRIANGLE_FAN);
-    glVertex2d(0, 0);
-    for (double a = 0.0; a <= 2 * OGL_PI; a += da)
-    {
-        glVertex2d(0 + cos(a) * SHAPE_CIRCLE_RADIUS, 0 + sin(a) * SHAPE_CIRCLE_RADIUS);
-    }
-    glVertex2d(0 + SHAPE_CIRCLE_RADIUS, 0);
-    glEnd();
-
-    glEndList();
-    shapes.push_back(circle);
+  double da = MS_MIN(OGL_PI / 2, OGL_PI / SHAPE_CIRCLE_RES);
+  GLuint circle = glGenLists(1);
+  glNewList(circle, GL_COMPILE);
+  glBegin(GL_TRIANGLE_FAN);
+  glVertex2d(0, 0);
+  for (double a = 0.0; a <= 2 * OGL_PI; a += da) {
+    glVertex2d(0 + cos(a) * SHAPE_CIRCLE_RADIUS, 0 + sin(a) * SHAPE_CIRCLE_RADIUS);
+  }
+  glVertex2d(0 + SHAPE_CIRCLE_RADIUS, 0);
+  glEnd();
+
+  glEndList();
+  shapes.push_back(circle);
 }
 
 void OglRenderer::makeCurrent()
 {
-    context->makeCurrent();
+  context->makeCurrent();
 }
 
 #endif
diff --git a/mapoglrenderer.h b/mapoglrenderer.h
index b412a9e..5b0d4a9 100644
--- a/mapoglrenderer.h
+++ b/mapoglrenderer.h
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -46,88 +46,94 @@
 class OglCache
 {
 public:
-    ~OglCache()
-    {
-        glDeleteTextures(1, &texture);
-    }
-    GLuint texture;
-    ms_uint32 width;
-    ms_uint32 height;
-    ms_uint32 patternDistance;
+  ~OglCache() {
+    glDeleteTextures(1, &texture);
+  }
+  GLuint texture;
+  ms_uint32 width;
+  ms_uint32 height;
+  ms_uint32 patternDistance;
 };
 
 typedef OglCache* OglCachePtr;
 
-class OglRenderer {
+class OglRenderer
+{
 public:
-    OglRenderer(ms_uint32 width, ms_uint32 height, colorObj* color = NULL);
-    virtual ~OglRenderer();
-
-    void renderPolyline(shapeObj *p, colorObj *c, double width, int patternlength, double* pattern, int lineCap = MS_CJC_ROUND, int joinStyle = MS_CJC_ROUND, colorObj *outlinecolor = NULL, double outlinewidth = 0);
-    void renderPolygon(shapeObj*, colorObj *color, colorObj *outlinecolor, double outlinewidth, const OglCachePtr& tile = OglCachePtr(), int lineCap=MS_CJC_ROUND, int joinStyle=MS_CJC_ROUND);
-    void renderGlyphs(double x, double y, colorObj *color, colorObj *outlinecolor, double size, char* font, char *thechars, double angle, colorObj *shadowcolor, double shdx, double shdy);
-    void renderPixmap(symbolObj *symbol, double x, double y, double angle, double scale);
-    void renderEllipse(double x, double y, double angle, double w, double h, colorObj *color, colorObj *outlinecolor, double outlinewidth);
-    void renderVectorSymbol(double x, double y, symbolObj *symbol, double scale, double angle, colorObj *c, colorObj *oc, double ow);
-    void renderTile(const OglCachePtr& tile, double x, double y, double angle);
-    void renderPolylineTile(shapeObj *p, const OglCachePtr& tile);
-
-    static bool getStringBBox(char *font, double size, char *string, rectObj *rect, double** advances);    
-    void setTransparency(double transparency);    
-    
-    void readRasterBuffer(rasterBufferObj * rb);
-    void drawRasterBuffer(rasterBufferObj *overlay, double opacity, int srcX, int srcY, int dstX, int dstY, int width, int height);
-    static void initializeRasterBuffer(rasterBufferObj * rb, int width, int height, bool useAlpha);    
-
-    OglCachePtr getTexture();
-    int getWidth() const { return width; }
-    int getHeight() const { return height; }
-    bool isValid() const { return valid && context->isValid(); }
+  OglRenderer(ms_uint32 width, ms_uint32 height, colorObj* color = NULL);
+  virtual ~OglRenderer();
+
+  void renderPolyline(shapeObj *p, colorObj *c, double width, int patternlength, double* pattern, int lineCap = MS_CJC_ROUND, int joinStyle = MS_CJC_ROUND, colorObj *outlinecolor = NULL, double outlinewidth = 0);
+  void renderPolygon(shapeObj*, colorObj *color, colorObj *outlinecolor, double outlinewidth, const OglCachePtr& tile = OglCachePtr(), int lineCap=MS_CJC_ROUND, int joinStyle=MS_CJC_ROUND);
+  void renderGlyphs(double x, double y, colorObj *color, colorObj *outlinecolor, double size, const char* font, char *thechars, double angle, colorObj *shadowcolor, double shdx, double shdy);
+  void renderPixmap(symbolObj *symbol, double x, double y, double angle, double scale);
+  void renderEllipse(double x, double y, double angle, double w, double h, colorObj *color, colorObj *outlinecolor, double outlinewidth);
+  void renderVectorSymbol(double x, double y, symbolObj *symbol, double scale, double angle, colorObj *c, colorObj *oc, double ow);
+  void renderTile(const OglCachePtr& tile, double x, double y, double angle);
+  void renderPolylineTile(shapeObj *p, const OglCachePtr& tile);
+
+  static bool getStringBBox(char *font, double size, char *string, rectObj *rect, double** advances);
+  void setTransparency(double transparency);
+
+  void readRasterBuffer(rasterBufferObj * rb);
+  void drawRasterBuffer(rasterBufferObj *overlay, double opacity, int srcX, int srcY, int dstX, int dstY, int width, int height);
+  static void initializeRasterBuffer(rasterBufferObj * rb, int width, int height, bool useAlpha);
+
+  OglCachePtr getTexture();
+  int getWidth() const {
+    return width;
+  }
+  int getHeight() const {
+    return height;
+  }
+  bool isValid() const {
+    return valid && context->isValid();
+  }
 protected:
-    OglCachePtr texture;
-    
-    ms_uint32 width;
-    ms_uint32 height;
-    double transparency;
-    bool valid;
-
-    GLint viewportX;
-    GLint viewportY;
-    GLsizei viewportWidth;
-    GLsizei viewportHeight;
-
-    typedef std::map<char*,std::map<double,FTFont*> > fontCache_t;
-    typedef std::map<symbolObj*,std::map<double,GLuint> > dashCache_t;
-
-    static FTFont* getFTFont(char* font, double size);
-    bool loadLine(shapeObj* shape, double width, int patternlength, double *pattern);
-    double drawQuad(pointObj *p1, pointObj *p2, double width, double tilelength = 0.0, double textureStart = 0.0);
-    double drawTriangles(pointObj *p1, pointObj *p2, double width, double tilelength = 0.0, double textureStart = 0.0);
-    void drawVectorLineStrip(symbolObj *symbol, double width);
-    void drawFan(pointObj* center, pointObj* from, pointObj* to, int resolution);
-    void createShapes();
-    
-    GLuint createTexture(ms_uint32 x, ms_uint32 y);
-
-    void makeCurrent();
-    void setColor(colorObj *color);
-
-    GLUtesselator *tess;
-    enum shapes_t{ circle = 0};
-
-    OglContext* context;
-
-    static dashCache_t dashCache;
-    static fontCache_t fontCache;
-    static std::vector<GLuint> shapes;
-    static std::vector<symbolObj*> testSymbols;
-    static ms_uint32 OUTLINE_WIDTH;
-    static ms_uint32 FONT_SIZE;
-    static ms_uint32 FONT_RES;
-    static double OGL_PI;
-    static ms_uint32 SHAPE_CIRCLE_RES;
-    static double SHAPE_CIRCLE_RADIUS;
-    static double SIZE_RES;
+  OglCachePtr texture;
+
+  ms_uint32 width;
+  ms_uint32 height;
+  double transparency;
+  bool valid;
+
+  GLint viewportX;
+  GLint viewportY;
+  GLsizei viewportWidth;
+  GLsizei viewportHeight;
+
+  typedef std::map<const char*,std::map<double,FTFont*> > fontCache_t;
+  typedef std::map<symbolObj*,std::map<double,GLuint> > dashCache_t;
+
+  static FTFont* getFTFont(const char* font, double size);
+  bool loadLine(shapeObj* shape, double width, int patternlength, double *pattern);
+  double drawQuad(pointObj *p1, pointObj *p2, double width, double tilelength = 0.0, double textureStart = 0.0);
+  double drawTriangles(pointObj *p1, pointObj *p2, double width, double tilelength = 0.0, double textureStart = 0.0);
+  void drawVectorLineStrip(symbolObj *symbol, double width);
+  void drawFan(pointObj* center, pointObj* from, pointObj* to, int resolution);
+  void createShapes();
+
+  GLuint createTexture(ms_uint32 x, ms_uint32 y);
+
+  void makeCurrent();
+  void setColor(colorObj *color);
+
+  GLUtesselator *tess;
+  enum shapes_t { circle = 0};
+
+  OglContext* context;
+
+  static dashCache_t dashCache;
+  static fontCache_t fontCache;
+  static std::vector<GLuint> shapes;
+  static std::vector<symbolObj*> testSymbols;
+  static ms_uint32 OUTLINE_WIDTH;
+  static ms_uint32 FONT_SIZE;
+  static ms_uint32 FONT_RES;
+  static double OGL_PI;
+  static ms_uint32 SHAPE_CIRCLE_RES;
+  static double SHAPE_CIRCLE_RADIUS;
+  static double SIZE_RES;
 };
 
 #endif /* USE_OGL */
diff --git a/mapogr.cpp b/mapogr.cpp
index 4a0cf6b..18d83ba 100644
--- a/mapogr.cpp
+++ b/mapogr.cpp
@@ -15,16 +15,16 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
+ *
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  * DEALINGS IN THE SOFTWARE.
  **********************************************************************/
 
@@ -40,30 +40,16 @@
 #  include "ogr_srs_api.h"
 #endif
 
-MS_CVSID("$Id$")
 
-#if defined(GDAL_VERSION_NUM) && (GDAL_VERSION_NUM < 1400)
-#  define ACQUIRE_OLD_OGR_LOCK   msAcquireLock( TLOCK_OGR )
-#  define RELEASE_OLD_OGR_LOCK   msReleaseLock( TLOCK_OGR )
-#else
-#  define ACQUIRE_OLD_OGR_LOCK 
-#  define RELEASE_OLD_OGR_LOCK 
-#endif
 
 #define ACQUIRE_OGR_LOCK       msAcquireLock( TLOCK_OGR )
 #define RELEASE_OGR_LOCK       msReleaseLock( TLOCK_OGR )
 
 #ifdef USE_OGR
 
-#if GDAL_VERSION_NUM >= 1500 /* Use OGR Style C API */
 #include "ogr_api.h"
-#else /* Use OGR Style C++ */
-#include "ogrsf_frmts.h"
-#include "ogr_featurestyle.h"
-#endif
 
-typedef struct ms_ogr_file_info_t
-{
+typedef struct ms_ogr_file_info_t {
   char        *pszFname;
   int         nLayerIndex;
   OGRDataSourceH hDS;
@@ -81,7 +67,7 @@ typedef struct ms_ogr_file_info_t
 
 static int msOGRLayerIsOpen(layerObj *layer);
 static int msOGRLayerInitItemInfo(layerObj *layer);
-static int msOGRLayerGetAutoStyle(mapObj *map, layerObj *layer, classObj *c, 
+static int msOGRLayerGetAutoStyle(mapObj *map, layerObj *layer, classObj *c,
                                   shapeObj* shape);
 static void msOGRCloseConnection( void *conn_handle );
 
@@ -94,166 +80,145 @@ static void msOGRCloseConnection( void *conn_handle );
  *
  * NOTE: This function assumes the line->point array already has been
  * allocated large enough for the point to be added, but that numpoints
- * does not include this new point. 
+ * does not include this new point.
  **********************************************************************/
-static void ogrPointsAddPoint(lineObj *line, double dX, double dY, 
+static void ogrPointsAddPoint(lineObj *line, double dX, double dY,
                               int lineindex, rectObj *bounds)
 {
-    /* Keep track of shape bounds */
-    if (line->numpoints == 0 && lineindex == 0)
-    {
-        bounds->minx = bounds->maxx = dX;
-        bounds->miny = bounds->maxy = dY;
-    }
-    else
-    {
-        if (dX < bounds->minx)  bounds->minx = dX;
-        if (dX > bounds->maxx)  bounds->maxx = dX;
-        if (dY < bounds->miny)  bounds->miny = dY;
-        if (dY > bounds->maxy)  bounds->maxy = dY;
-    }
-
-    line->point[line->numpoints].x = dX;
-    line->point[line->numpoints].y = dY;
+  /* Keep track of shape bounds */
+  if (line->numpoints == 0 && lineindex == 0) {
+    bounds->minx = bounds->maxx = dX;
+    bounds->miny = bounds->maxy = dY;
+  } else {
+    if (dX < bounds->minx)  bounds->minx = dX;
+    if (dX > bounds->maxx)  bounds->maxx = dX;
+    if (dY < bounds->miny)  bounds->miny = dY;
+    if (dY > bounds->maxy)  bounds->maxy = dY;
+  }
+
+  line->point[line->numpoints].x = dX;
+  line->point[line->numpoints].y = dY;
 #ifdef USE_POINT_Z_M
-    line->point[line->numpoints].z = 0.0;
-    line->point[line->numpoints].m = 0.0;
+  line->point[line->numpoints].z = 0.0;
+  line->point[line->numpoints].m = 0.0;
 #endif
-    line->numpoints++;
+  line->numpoints++;
 }
 
 /**********************************************************************
  *                     ogrGeomPoints()
  **********************************************************************/
-static int ogrGeomPoints(OGRGeometryH hGeom, shapeObj *outshp) 
+static int ogrGeomPoints(OGRGeometryH hGeom, shapeObj *outshp)
 {
   int   i;
   int   numpoints;
 
-  if (hGeom == NULL)   
-      return 0;
+  if (hGeom == NULL)
+    return 0;
 
   OGRwkbGeometryType eGType =  wkbFlatten( OGR_G_GetGeometryType( hGeom ) );
 
-/* -------------------------------------------------------------------- */
-/*      Container types result in recursive invocation on each          */
-/*      subobject to add a set of points to the current list.           */
-/* -------------------------------------------------------------------- */
-  switch( eGType )
-  {
-      case wkbGeometryCollection:
-      case wkbMultiLineString:
-      case wkbMultiPolygon:
-      case wkbPolygon:
-      {
-          /* Treat it as GeometryCollection */
-          for (int iGeom=0; iGeom < OGR_G_GetGeometryCount( hGeom ); iGeom++ )
-          {
-              if( ogrGeomPoints( OGR_G_GetGeometryRef( hGeom, iGeom ), 
-                                 outshp ) == -1 )
-                  return -1;
-          }
-
-          return 0;							
+  /* -------------------------------------------------------------------- */
+  /*      Container types result in recursive invocation on each          */
+  /*      subobject to add a set of points to the current list.           */
+  /* -------------------------------------------------------------------- */
+  switch( eGType ) {
+    case wkbGeometryCollection:
+    case wkbMultiLineString:
+    case wkbMultiPolygon:
+    case wkbPolygon: {
+      /* Treat it as GeometryCollection */
+      for (int iGeom=0; iGeom < OGR_G_GetGeometryCount( hGeom ); iGeom++ ) {
+        if( ogrGeomPoints( OGR_G_GetGeometryRef( hGeom, iGeom ),
+                           outshp ) == -1 )
+          return -1;
       }
-      break;
 
-      case wkbPoint:
-      case wkbMultiPoint:
-      case wkbLineString:
-      case wkbLinearRing:
-          /* We will handle these directly */
-          break;
-
-      default:
-          /* There shouldn't be any more cases should there? */
-          msSetError(MS_OGRERR, 
-                     "OGRGeometry type `%s' not supported yet.", 
-                     "ogrGeomPoints()",
-                     OGR_G_GetGeometryName( hGeom ) );
-          return(-1);
-  }
+      return 0;
+    }
+    break;
 
+    case wkbPoint:
+    case wkbMultiPoint:
+    case wkbLineString:
+    case wkbLinearRing:
+      /* We will handle these directly */
+      break;
 
-/* ------------------------------------------------------------------
- * Count total number of points
- * ------------------------------------------------------------------ */
-  if ( eGType == wkbPoint )
-  {
-      numpoints = 1;
-  }
-  else if ( eGType == wkbLineString 
-            ||  eGType == wkbLinearRing )
-  {
-      numpoints = OGR_G_GetPointCount( hGeom );
-  }
-  else if ( eGType == wkbMultiPoint )
-  {
-      numpoints = OGR_G_GetGeometryCount( hGeom );
-  }
-  else
-  {
-      msSetError(MS_OGRERR, 
-                 "OGRGeometry type `%s' not supported yet.", 
+    default:
+      /* There shouldn't be any more cases should there? */
+      msSetError(MS_OGRERR,
+                 "OGRGeometry type `%s' not supported yet.",
                  "ogrGeomPoints()",
                  OGR_G_GetGeometryName( hGeom ) );
       return(-1);
   }
 
-/* ------------------------------------------------------------------
- * Do we need to allocate a line object to contain all our points? 
- * ------------------------------------------------------------------ */
-  if( outshp->numlines == 0 )
-  {
-      lineObj newline;
-      
-      newline.numpoints = 0;
-      newline.point = NULL;
-      msAddLine(outshp, &newline);
-  }
-  
-/* ------------------------------------------------------------------
- * Extend the point array for the new of points to add from the 
- * current geometry.
- * ------------------------------------------------------------------ */
+
+  /* ------------------------------------------------------------------
+   * Count total number of points
+   * ------------------------------------------------------------------ */
+  if ( eGType == wkbPoint ) {
+    numpoints = 1;
+  } else if ( eGType == wkbLineString
+              ||  eGType == wkbLinearRing ) {
+    numpoints = OGR_G_GetPointCount( hGeom );
+  } else if ( eGType == wkbMultiPoint ) {
+    numpoints = OGR_G_GetGeometryCount( hGeom );
+  } else {
+    msSetError(MS_OGRERR,
+               "OGRGeometry type `%s' not supported yet.",
+               "ogrGeomPoints()",
+               OGR_G_GetGeometryName( hGeom ) );
+    return(-1);
+  }
+
+  /* ------------------------------------------------------------------
+   * Do we need to allocate a line object to contain all our points?
+   * ------------------------------------------------------------------ */
+  if( outshp->numlines == 0 ) {
+    lineObj newline;
+
+    newline.numpoints = 0;
+    newline.point = NULL;
+    msAddLine(outshp, &newline);
+  }
+
+  /* ------------------------------------------------------------------
+   * Extend the point array for the new of points to add from the
+   * current geometry.
+   * ------------------------------------------------------------------ */
   lineObj *line = outshp->line + outshp->numlines-1;
 
   if( line->point == NULL )
-      line->point = (pointObj *) malloc(sizeof(pointObj) * numpoints);
+    line->point = (pointObj *) malloc(sizeof(pointObj) * numpoints);
   else
-      line->point = (pointObj *) 
-          realloc(line->point,sizeof(pointObj) * (numpoints+line->numpoints));
-  
-  if(!line->point) 
-  {
-      msSetError(MS_MEMERR, "Unable to allocate temporary point cache.", 
-                 "ogrGeomPoints()");
-      return(-1);
-  }
-   
-/* ------------------------------------------------------------------
- * alloc buffer and filter/transform points
- * ------------------------------------------------------------------ */
-  if( eGType == wkbPoint )
-  {
-      ogrPointsAddPoint(line, OGR_G_GetX(hGeom, 0), OGR_G_GetY(hGeom, 0), 
+    line->point = (pointObj *)
+                  realloc(line->point,sizeof(pointObj) * (numpoints+line->numpoints));
+
+  if(!line->point) {
+    msSetError(MS_MEMERR, "Unable to allocate temporary point cache.",
+               "ogrGeomPoints()");
+    return(-1);
+  }
+
+  /* ------------------------------------------------------------------
+   * alloc buffer and filter/transform points
+   * ------------------------------------------------------------------ */
+  if( eGType == wkbPoint ) {
+    ogrPointsAddPoint(line, OGR_G_GetX(hGeom, 0), OGR_G_GetY(hGeom, 0),
+                      outshp->numlines-1, &(outshp->bounds));
+  } else if( eGType == wkbLineString
+             || eGType == wkbLinearRing ) {
+    for(i=0; i<numpoints; i++)
+      ogrPointsAddPoint(line, OGR_G_GetX(hGeom, i), OGR_G_GetY(hGeom, i),
                         outshp->numlines-1, &(outshp->bounds));
-  }
-  else if( eGType == wkbLineString 
-           || eGType == wkbLinearRing )
-  {
-      for(i=0; i<numpoints; i++)
-          ogrPointsAddPoint(line, OGR_G_GetX(hGeom, i), OGR_G_GetY(hGeom, i),
-                            outshp->numlines-1, &(outshp->bounds));
-  }
-  else if( eGType == wkbMultiPoint )
-  {
-      for(i=0; i<numpoints; i++)
-      {
-          OGRGeometryH hPoint = OGR_G_GetGeometryRef( hGeom, i );
-          ogrPointsAddPoint(line, OGR_G_GetX(hPoint, 0), OGR_G_GetY(hPoint, 0),
-                            outshp->numlines-1, &(outshp->bounds));
-      }
+  } else if( eGType == wkbMultiPoint ) {
+    for(i=0; i<numpoints; i++) {
+      OGRGeometryH hPoint = OGR_G_GetGeometryRef( hGeom, i );
+      ogrPointsAddPoint(line, OGR_G_GetX(hPoint, 0), OGR_G_GetY(hPoint, 0),
+                        outshp->numlines-1, &(outshp->bounds));
+    }
   }
 
   outshp->type = MS_SHAPE_POINT;
@@ -269,104 +234,104 @@ static int ogrGeomPoints(OGRGeometryH hGeom, shapeObj *outshp)
  * a line in the overall shapeObj.
  **********************************************************************/
 static int ogrGeomLine(OGRGeometryH hGeom, shapeObj *outshp,
-                       int bCloseRings) 
+                       int bCloseRings)
 {
   if (hGeom == NULL)
-      return 0;
+    return 0;
 
-/* ------------------------------------------------------------------
- * Use recursive calls for complex geometries
- * ------------------------------------------------------------------ */
+  /* ------------------------------------------------------------------
+   * Use recursive calls for complex geometries
+   * ------------------------------------------------------------------ */
   OGRwkbGeometryType eGType =  wkbFlatten( OGR_G_GetGeometryType( hGeom ) );
 
-  
+
   if ( eGType == wkbPolygon
        || eGType == wkbGeometryCollection
-       || eGType == wkbMultiLineString 
-       || eGType == wkbMultiPolygon )
-  {
-      if (eGType == wkbPolygon && outshp->type == MS_SHAPE_NULL)
-          outshp->type = MS_SHAPE_POLYGON;
-
-      /* Treat it as GeometryCollection */
-      for (int iGeom=0; iGeom < OGR_G_GetGeometryCount( hGeom ); iGeom++ )
-      {
-          if( ogrGeomLine( OGR_G_GetGeometryRef( hGeom, iGeom ), 
-                           outshp, bCloseRings ) == -1 )
-              return -1;
-      }
-  }
-/* ------------------------------------------------------------------
- * OGRPoint and OGRMultiPoint
- * ------------------------------------------------------------------ */
-  else if ( eGType == wkbPoint || eGType == wkbMultiPoint )
-  {
-      /* Hummmm a point when we're drawing lines/polygons... just drop it! */
+       || eGType == wkbMultiLineString
+       || eGType == wkbMultiPolygon ) {
+    if (eGType == wkbPolygon && outshp->type == MS_SHAPE_NULL)
+      outshp->type = MS_SHAPE_POLYGON;
+
+    /* Treat it as GeometryCollection */
+    for (int iGeom=0; iGeom < OGR_G_GetGeometryCount( hGeom ); iGeom++ ) {
+      if( ogrGeomLine( OGR_G_GetGeometryRef( hGeom, iGeom ),
+                       outshp, bCloseRings ) == -1 )
+        return -1;
+    }
   }
-/* ------------------------------------------------------------------
- * OGRLinearRing/OGRLineString ... both are of type wkbLineString
- * ------------------------------------------------------------------ */
-  else if ( eGType == wkbLineString )
-  {
-      int       j, numpoints;
-      lineObj   line={0,NULL};
-      double    dX, dY;
-
-      if ((numpoints = OGR_G_GetPointCount( hGeom )) < 2)
-          return 0;
-
-      if (outshp->type == MS_SHAPE_NULL)
-          outshp->type = MS_SHAPE_LINE;
-
-      line.numpoints = 0;
-      line.point = (pointObj *)malloc(sizeof(pointObj)*(numpoints+1));
-      if(!line.point) 
-      {
-          msSetError(MS_MEMERR, "Unable to allocate temporary point cache.", 
-                     "ogrGeomLine");
-          return(-1);
-      }
+  /* ------------------------------------------------------------------
+   * OGRPoint and OGRMultiPoint
+   * ------------------------------------------------------------------ */
+  else if ( eGType == wkbPoint || eGType == wkbMultiPoint ) {
+    /* Hummmm a point when we're drawing lines/polygons... just drop it! */
+  }
+  /* ------------------------------------------------------------------
+   * OGRLinearRing/OGRLineString ... both are of type wkbLineString
+   * ------------------------------------------------------------------ */
+  else if ( eGType == wkbLineString ) {
+    int       j, numpoints;
+    lineObj   line= {0,NULL};
+    double    dX, dY;
+
+    if ((numpoints = OGR_G_GetPointCount( hGeom )) < 2)
+      return 0;
 
-      for(j=0; j<numpoints; j++)
-      {
-          dX = line.point[j].x = OGR_G_GetX( hGeom, j); 
-          dY = line.point[j].y = OGR_G_GetY( hGeom, j);
+    if (outshp->type == MS_SHAPE_NULL)
+      outshp->type = MS_SHAPE_LINE;
 
-          /* Keep track of shape bounds */
-          if (j == 0 && outshp->numlines == 0)
-          {
-              outshp->bounds.minx = outshp->bounds.maxx = dX;
-              outshp->bounds.miny = outshp->bounds.maxy = dY;
-          }
-          else
-          {
-              if (dX < outshp->bounds.minx)  outshp->bounds.minx = dX;
-              if (dX > outshp->bounds.maxx)  outshp->bounds.maxx = dX;
-              if (dY < outshp->bounds.miny)  outshp->bounds.miny = dY;
-              if (dY > outshp->bounds.maxy)  outshp->bounds.maxy = dY;
-          }
+    line.numpoints = 0;
+    line.point = (pointObj *)malloc(sizeof(pointObj)*(numpoints+1));
+    if(!line.point) {
+      msSetError(MS_MEMERR, "Unable to allocate temporary point cache.",
+                 "ogrGeomLine");
+      return(-1);
+    }
 
-      }
-      line.numpoints = numpoints; 
-
-      if (bCloseRings &&
-          ( line.point[line.numpoints-1].x != line.point[0].x ||
-            line.point[line.numpoints-1].y != line.point[0].y  ) )
-      {
-          line.point[line.numpoints].x = line.point[0].x;
-          line.point[line.numpoints].y = line.point[0].y;
-          line.numpoints++;
+#if GDAL_VERSION_NUM >= 1900
+    OGR_G_GetPoints(hGeom,
+                    &(line.point[0].x), sizeof(pointObj),
+                    &(line.point[0].y), sizeof(pointObj),
+                    NULL, 0);
+#endif
+
+    for(j=0; j<numpoints; j++) {
+#if GDAL_VERSION_NUM < 1900
+      dX = line.point[j].x = OGR_G_GetX( hGeom, j);
+      dY = line.point[j].y = OGR_G_GetY( hGeom, j);
+#else
+      dX = line.point[j].x;
+      dY = line.point[j].y;
+#endif
+
+      /* Keep track of shape bounds */
+      if (j == 0 && outshp->numlines == 0) {
+        outshp->bounds.minx = outshp->bounds.maxx = dX;
+        outshp->bounds.miny = outshp->bounds.maxy = dY;
+      } else {
+        if (dX < outshp->bounds.minx)  outshp->bounds.minx = dX;
+        if (dX > outshp->bounds.maxx)  outshp->bounds.maxx = dX;
+        if (dY < outshp->bounds.miny)  outshp->bounds.miny = dY;
+        if (dY > outshp->bounds.maxy)  outshp->bounds.maxy = dY;
       }
 
-      msAddLineDirectly(outshp, &line);
-  }
-  else
-  {
-      msSetError(MS_OGRERR, 
-                 "OGRGeometry type `%s' not supported.",
-                 "ogrGeomLine()",
-                 OGR_G_GetGeometryName( hGeom ) );
-      return(-1);
+    }
+    line.numpoints = numpoints;
+
+    if (bCloseRings &&
+        ( line.point[line.numpoints-1].x != line.point[0].x ||
+          line.point[line.numpoints-1].y != line.point[0].y  ) ) {
+      line.point[line.numpoints].x = line.point[0].x;
+      line.point[line.numpoints].y = line.point[0].y;
+      line.numpoints++;
+    }
+
+    msAddLineDirectly(outshp, &line);
+  } else {
+    msSetError(MS_OGRERR,
+               "OGRGeometry type `%s' not supported.",
+               "ogrGeomLine()",
+               OGR_G_GetGeometryName( hGeom ) );
+    return(-1);
   }
 
   return(0);
@@ -376,88 +341,80 @@ static int ogrGeomLine(OGRGeometryH hGeom, shapeObj *outshp,
 /**********************************************************************
  *                     ogrConvertGeometry()
  *
- * Convert OGR geometry into a shape object doing the best possible 
+ * Convert OGR geometry into a shape object doing the best possible
  * job to match OGR Geometry type and layer type.
  *
  * If layer type is incompatible with geometry, then shape is returned with
  * shape->type = MS_SHAPE_NULL
  **********************************************************************/
 static int ogrConvertGeometry(OGRGeometryH hGeom, shapeObj *outshp,
-                              enum MS_LAYER_TYPE layertype) 
+                              enum MS_LAYER_TYPE layertype)
 {
-/* ------------------------------------------------------------------
- * Process geometry according to layer type
- * ------------------------------------------------------------------ */
+  /* ------------------------------------------------------------------
+   * Process geometry according to layer type
+   * ------------------------------------------------------------------ */
   int nStatus = MS_SUCCESS;
 
-  if (hGeom == NULL)
-  {
-      // Empty geometry... this is not an error... we'll just skip it
-      return MS_SUCCESS;
+  if (hGeom == NULL) {
+    // Empty geometry... this is not an error... we'll just skip it
+    return MS_SUCCESS;
   }
 
-  switch(layertype) 
-  {
-/* ------------------------------------------------------------------
- *      POINT layer - Any geometry can be converted to point/multipoint
- * ------------------------------------------------------------------ */
+  switch(layertype) {
+      /* ------------------------------------------------------------------
+       *      POINT layer - Any geometry can be converted to point/multipoint
+       * ------------------------------------------------------------------ */
     case MS_LAYER_POINT:
-      if(ogrGeomPoints(hGeom, outshp) == -1)
-      {
-          nStatus = MS_FAILURE; // Error message already produced.
+      if(ogrGeomPoints(hGeom, outshp) == -1) {
+        nStatus = MS_FAILURE; // Error message already produced.
       }
       break;
-/* ------------------------------------------------------------------
- *      LINE layer
- * ------------------------------------------------------------------ */
+      /* ------------------------------------------------------------------
+       *      LINE layer
+       * ------------------------------------------------------------------ */
     case MS_LAYER_LINE:
-      if(ogrGeomLine(hGeom, outshp, MS_FALSE) == -1)
-      {
-          nStatus = MS_FAILURE; // Error message already produced.
+      if(ogrGeomLine(hGeom, outshp, MS_FALSE) == -1) {
+        nStatus = MS_FAILURE; // Error message already produced.
       }
       if (outshp->type != MS_SHAPE_LINE && outshp->type != MS_SHAPE_POLYGON)
-          outshp->type = MS_SHAPE_NULL;  // Incompatible type for this layer
+        outshp->type = MS_SHAPE_NULL;  // Incompatible type for this layer
       break;
-/* ------------------------------------------------------------------
- *      POLYGON layer
- * ------------------------------------------------------------------ */
+      /* ------------------------------------------------------------------
+       *      POLYGON layer
+       * ------------------------------------------------------------------ */
     case MS_LAYER_POLYGON:
-      if(ogrGeomLine(hGeom, outshp, MS_TRUE) == -1)
-      {
-          nStatus = MS_FAILURE; // Error message already produced.
+      if(ogrGeomLine(hGeom, outshp, MS_TRUE) == -1) {
+        nStatus = MS_FAILURE; // Error message already produced.
       }
       if (outshp->type != MS_SHAPE_POLYGON)
-          outshp->type = MS_SHAPE_NULL;  // Incompatible type for this layer
+        outshp->type = MS_SHAPE_NULL;  // Incompatible type for this layer
       break;
-/* ------------------------------------------------------------------
- *      MS_ANNOTATION layer - return real feature type
- * ------------------------------------------------------------------ */
+      /* ------------------------------------------------------------------
+       *      MS_ANNOTATION layer - return real feature type
+       * ------------------------------------------------------------------ */
     case MS_LAYER_ANNOTATION:
     case MS_LAYER_CHART:
     case MS_LAYER_QUERY:
-      switch( OGR_G_GetGeometryType( hGeom ) )
-      {
+      switch( OGR_G_GetGeometryType( hGeom ) ) {
         case wkbPoint:
         case wkbPoint25D:
         case wkbMultiPoint:
         case wkbMultiPoint25D:
-          if(ogrGeomPoints(hGeom, outshp) == -1)
-          {
-              nStatus = MS_FAILURE; // Error message already produced.
+          if(ogrGeomPoints(hGeom, outshp) == -1) {
+            nStatus = MS_FAILURE; // Error message already produced.
           }
           break;
         default:
           // Handle any non-point types as lines/polygons ... ogrGeomLine()
           // will decide the shape type
-          if(ogrGeomLine(hGeom, outshp, MS_FALSE) == -1)
-          {
-              nStatus = MS_FAILURE; // Error message already produced.
+          if(ogrGeomLine(hGeom, outshp, MS_FALSE) == -1) {
+            nStatus = MS_FAILURE; // Error message already produced.
           }
       }
       break;
 
     default:
-      msSetError(MS_MISCERR, "Unknown or unsupported layer type.", 
+      msSetError(MS_MISCERR, "Unknown or unsupported layer type.",
                  "msOGRLayerNextShape()");
       nStatus = MS_FAILURE;
   } /* switch layertype */
@@ -468,25 +425,23 @@ static int ogrConvertGeometry(OGRGeometryH hGeom, shapeObj *outshp,
 /**********************************************************************
  *                     msOGRGeometryToShape()
  *
- * Utility function to convert from OGR geometry to a mapserver shape 
+ * Utility function to convert from OGR geometry to a mapserver shape
  * object.
  **********************************************************************/
 int msOGRGeometryToShape(OGRGeometryH hGeometry, shapeObj *psShape,
                          OGRwkbGeometryType nType)
 {
-    if (hGeometry && psShape && nType > 0)
-    {
-        if (nType == wkbPoint || nType == wkbMultiPoint )
-            return ogrConvertGeometry(hGeometry, psShape,  MS_LAYER_POINT);
-        else if (nType == wkbLineString || nType == wkbMultiLineString)
-            return ogrConvertGeometry(hGeometry, psShape,  MS_LAYER_LINE);
-        else if (nType == wkbPolygon || nType == wkbMultiPolygon)
-            return ogrConvertGeometry(hGeometry, psShape,  MS_LAYER_POLYGON);
-        else
-            return MS_FAILURE;
-    }
+  if (hGeometry && psShape && nType > 0) {
+    if (nType == wkbPoint || nType == wkbMultiPoint )
+      return ogrConvertGeometry(hGeometry, psShape,  MS_LAYER_POINT);
+    else if (nType == wkbLineString || nType == wkbMultiLineString)
+      return ogrConvertGeometry(hGeometry, psShape,  MS_LAYER_LINE);
+    else if (nType == wkbPolygon || nType == wkbMultiPolygon)
+      return ogrConvertGeometry(hGeometry, psShape,  MS_LAYER_POLYGON);
     else
-        return MS_FAILURE;
+      return MS_FAILURE;
+  } else
+    return MS_FAILURE;
 }
 
 
@@ -558,591 +513,289 @@ static char **msOGRGetValues(layerObj *layer, OGRFeatureH hFeature)
   const char *pszValue = NULL;
   int i;
 
-  if(layer->numitems == 0) 
-      return(NULL);
+  if(layer->numitems == 0)
+    return(NULL);
 
   if(!layer->iteminfo)  // Should not happen... but just in case!
-      if (msOGRLayerInitItemInfo(layer) != MS_SUCCESS)
-          return NULL;
+    if (msOGRLayerInitItemInfo(layer) != MS_SUCCESS)
+      return NULL;
 
-  if((values = (char **)malloc(sizeof(char *)*layer->numitems)) == NULL) 
-  {
+  if((values = (char **)malloc(sizeof(char *)*layer->numitems)) == NULL) {
     msSetError(MS_MEMERR, NULL, "msOGRGetValues()");
     return(NULL);
   }
 
-#if GDAL_VERSION_NUM >= 1500 /* Use OGR Style C API */
   OGRStyleMgrH  hStyleMgr = NULL;
   OGRStyleToolH hLabelStyle = NULL;
-#else
-  OGRStyleMgr *poStyleMgr = NULL;
-  OGRStyleLabel *poLabelStyle = NULL;
-#endif
+
   int *itemindexes = (int*)layer->iteminfo;
 
-  for(i=0;i<layer->numitems;i++)
-  {
-    if (itemindexes[i] >= 0)
-    {
-        // Extract regular attributes
-        values[i] = msStrdup(OGR_F_GetFieldAsString( hFeature, itemindexes[i]));
-    }
-    else
-#if GDAL_VERSION_NUM >= 1500 /* Use OGR Style C API */
-    {
-        // Handle special OGR attributes coming from StyleString
-        if (!hStyleMgr)
-        {
-            hStyleMgr = OGR_SM_Create(NULL);
-            OGR_SM_InitFromFeature(hStyleMgr, hFeature);
-            OGRStyleToolH hStylePart = OGR_SM_GetPart(hStyleMgr, 0, NULL);
-            if (hStylePart && OGR_ST_GetType(hStylePart) == OGRSTCLabel)
-                hLabelStyle = hStylePart;
-            else if (hStylePart)
-            {
-                OGR_ST_Destroy(hStylePart);
-                hStylePart =  NULL;
-            }
-
-          /* Setting up the size units according to msOGRLayerGetAutoStyle*/
-          if (hStylePart && layer->map)
-            OGR_ST_SetUnit(hStylePart, OGRSTUPixel, layer->map->cellsize*72.0*39.37);
-        }
-        int bDefault;
-        if (itemindexes[i] == MSOGR_LABELTEXTINDEX)
-        {
-            if (hLabelStyle == NULL 
-                || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
-                                                          OGRSTLabelTextString,
-                                                          &bDefault)) == NULL))
-                values[i] = msStrdup("");
-            else
-                values[i] = msStrdup(pszValue);
-
-            if (layer->debug >= MS_DEBUGLEVEL_VVV)
-                msDebug(MSOGR_LABELTEXTNAME " = \"%s\"\n", values[i]);
-        }
-        else if (itemindexes[i] == MSOGR_LABELANGLEINDEX)
-        {
-            if (hLabelStyle == NULL 
-                || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
-                                                          OGRSTLabelAngle,
-                                                          &bDefault)) == NULL))
-                values[i] = msStrdup("0");
-            else
-                values[i] = msStrdup(pszValue);
-
-            if (layer->debug >= MS_DEBUGLEVEL_VVV)
-                msDebug(MSOGR_LABELANGLENAME " = \"%s\"\n", values[i]);
-        }
-        else if (itemindexes[i] == MSOGR_LABELSIZEINDEX)
-        {
-            if (hLabelStyle == NULL 
-                || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
-                                                          OGRSTLabelSize,
-                                                          &bDefault)) == NULL))
-                values[i] = msStrdup("0");
-            else
-                values[i] = msStrdup(pszValue);
-
-            if (layer->debug >= MS_DEBUGLEVEL_VVV)
-                msDebug(MSOGR_LABELSIZENAME " = \"%s\"\n", values[i]);
-        }
-        else if (itemindexes[i] == MSOGR_LABELFCOLORINDEX)
-        {
-            if (hLabelStyle == NULL 
-                || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
-                                                          OGRSTLabelFColor,
-                                                          &bDefault)) == NULL))
-                values[i] = msStrdup("#000000");
-            else
-                values[i] = msStrdup(pszValue);
-
-            if (layer->debug >= MS_DEBUGLEVEL_VVV)
-                msDebug(MSOGR_LABELFCOLORNAME " = \"%s\"\n", values[i]);
-        }
-        else if (itemindexes[i] == MSOGR_LABELFONTNAMEINDEX )
-        {
-            if (hLabelStyle == NULL 
-                || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
-                                                          OGRSTLabelFontName,
-                                                          &bDefault)) == NULL))
-                values[i] = msStrdup("Arial");
-            else
-                values[i] = msStrdup(pszValue);
-
-            if (layer->debug >= MS_DEBUGLEVEL_VVV)
-                msDebug(MSOGR_LABELFONTNAMENAME " =       \"%s\"\n", values[i]);
-        }
-        else if (itemindexes[i] == MSOGR_LABELBCOLORINDEX)
-        {
-            if (hLabelStyle == NULL 
-                || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
-                                                          OGRSTLabelBColor,
-                                                          &bDefault)) == NULL))
-                values[i] = msStrdup("#000000");
-            else
-                values[i] = msStrdup(pszValue);
-
-            if (layer->debug >= MS_DEBUGLEVEL_VVV)
-                msDebug(MSOGR_LABELBCOLORNAME " = \"%s\"\n", values[i]);
-        }
-        else if (itemindexes[i] == MSOGR_LABELPLACEMENTINDEX)
-        {
-            if (hLabelStyle == NULL 
-                || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
-                                                          OGRSTLabelPlacement,
-                                                          &bDefault)) == NULL))
-                values[i] = msStrdup("");
-            else
-                values[i] = msStrdup(pszValue);
-
-            if (layer->debug >= MS_DEBUGLEVEL_VVV)
-                msDebug(MSOGR_LABELPLACEMENTNAME " = \"%s\"\n", values[i]);
-        }
-        else if (itemindexes[i] == MSOGR_LABELANCHORINDEX)
-        {
-            if (hLabelStyle == NULL 
-                || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
-                                                          OGRSTLabelAnchor,
-                                                          &bDefault)) == NULL))
-                values[i] = msStrdup("0");
-            else
-                values[i] = msStrdup(pszValue);
-
-            if (layer->debug >= MS_DEBUGLEVEL_VVV)
-                msDebug(MSOGR_LABELANCHORNAME " = \"%s\"\n", values[i]);
-        }
-        else if (itemindexes[i] == MSOGR_LABELDXINDEX)
-        {
-            if (hLabelStyle == NULL 
-                || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
-                                                          OGRSTLabelDx,
-                                                          &bDefault)) == NULL))
-                values[i] = msStrdup("0");
-            else
-                values[i] = msStrdup(pszValue);
-
-            if (layer->debug >= MS_DEBUGLEVEL_VVV)
-                msDebug(MSOGR_LABELDXNAME " = \"%s\"\n", values[i]);
-        }
-        else if (itemindexes[i] == MSOGR_LABELDYINDEX)
-        {
-            if (hLabelStyle == NULL 
-                || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
-                                                          OGRSTLabelDy,
-                                                          &bDefault)) == NULL))
-                values[i] = msStrdup("0");
-            else
-                values[i] = msStrdup(pszValue);
-
-            if (layer->debug >= MS_DEBUGLEVEL_VVV)
-                msDebug(MSOGR_LABELDYNAME " = \"%s\"\n", values[i]);
-        }
-        else if (itemindexes[i] == MSOGR_LABELPERPINDEX)
-        {
-            if (hLabelStyle == NULL 
-                || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
-                                                          OGRSTLabelPerp,
-                                                          &bDefault)) == NULL))
-                values[i] = msStrdup("0");
-            else
-                values[i] = msStrdup(pszValue);
-
-            if (layer->debug >= MS_DEBUGLEVEL_VVV)
-                msDebug(MSOGR_LABELPERPNAME " = \"%s\"\n", values[i]);
-        }
-        else if (itemindexes[i] == MSOGR_LABELBOLDINDEX)
-        {
-            if (hLabelStyle == NULL 
-                || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
-                                                          OGRSTLabelBold,
-                                                          &bDefault)) == NULL))
-                values[i] = msStrdup("0");
-            else
-                values[i] = msStrdup(pszValue);
-
-            if (layer->debug >= MS_DEBUGLEVEL_VVV)
-                msDebug(MSOGR_LABELBOLDNAME " = \"%s\"\n", values[i]);
-        }
-        else if (itemindexes[i] == MSOGR_LABELITALICINDEX)
-        {
-            if (hLabelStyle == NULL 
-                || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
-                                                          OGRSTLabelItalic,
-                                                          &bDefault)) == NULL))
-                values[i] = msStrdup("0");
-            else
-                values[i] = msStrdup(pszValue);
-
-            if (layer->debug >= MS_DEBUGLEVEL_VVV)
-                msDebug(MSOGR_LABELITALICNAME " = \"%s\"\n", values[i]);
-        }
-        else if (itemindexes[i] == MSOGR_LABELUNDERLINEINDEX)
-        {
-            if (hLabelStyle == NULL 
-                || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
-                                                          OGRSTLabelUnderline,
-                                                          &bDefault)) == NULL))
-                values[i] = msStrdup("0");
-            else
-                values[i] = msStrdup(pszValue);
-
-            if (layer->debug >= MS_DEBUGLEVEL_VVV)
-                msDebug(MSOGR_LABELUNDERLINENAME " = \"%s\"\n", values[i]);
-        }
-        else if (itemindexes[i] == MSOGR_LABELPRIORITYINDEX)
-        {
-            if (hLabelStyle == NULL 
-                || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
-                                                          OGRSTLabelPriority,
-                                                          &bDefault)) == NULL))
-                values[i] = msStrdup("0");
-            else
-                values[i] = msStrdup(pszValue);
-
-            if (layer->debug >= MS_DEBUGLEVEL_VVV)
-                msDebug(MSOGR_LABELPRIORITYNAME " = \"%s\"\n", values[i]);
-        }
-        else if (itemindexes[i] == MSOGR_LABELSTRIKEOUTINDEX)
-        {
-            if (hLabelStyle == NULL 
-                || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
-                                                          OGRSTLabelStrikeout,
-                                                          &bDefault)) == NULL))
-                values[i] = msStrdup("0");
-            else
-                values[i] = msStrdup(pszValue);
-
-            if (layer->debug >= MS_DEBUGLEVEL_VVV)
-                msDebug(MSOGR_LABELSTRIKEOUTNAME " = \"%s\"\n", values[i]);
-        }
-        else if (itemindexes[i] == MSOGR_LABELSTRETCHINDEX)
-        {
-            if (hLabelStyle == NULL 
-                || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
-                                                          OGRSTLabelStretch,
-                                                          &bDefault)) == NULL))
-                values[i] = msStrdup("0");
-            else
-                values[i] = msStrdup(pszValue);
-
-            if (layer->debug >= MS_DEBUGLEVEL_VVV)
-                msDebug(MSOGR_LABELSTRETCHNAME " = \"%s\"\n", values[i]);
-        }
-        else if (itemindexes[i] == MSOGR_LABELADJHORINDEX)
-        {
-            if (hLabelStyle == NULL 
-                || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
-                                                          OGRSTLabelAdjHor,
-                                                          &bDefault)) == NULL))
-                values[i] = msStrdup("");
-            else
-                values[i] = msStrdup(pszValue);
-
-            if (layer->debug >= MS_DEBUGLEVEL_VVV)
-                msDebug(MSOGR_LABELADJHORNAME " = \"%s\"\n", values[i]);
-        }
-        else if (itemindexes[i] == MSOGR_LABELADJVERTINDEX)
-        {
-            if (hLabelStyle == NULL 
-                || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
-                                                          OGRSTLabelAdjVert,
-                                                          &bDefault)) == NULL))
-                values[i] = msStrdup("");
-            else
-                values[i] = msStrdup(pszValue);
-
-            if (layer->debug >= MS_DEBUGLEVEL_VVV)
-                msDebug(MSOGR_LABELADJVERTNAME " = \"%s\"\n", values[i]);
-        }
-        else if (itemindexes[i] == MSOGR_LABELHCOLORINDEX)
-        {
-            if (hLabelStyle == NULL 
-                || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
-                                                          OGRSTLabelHColor,
-                                                          &bDefault)) == NULL))
-                values[i] = msStrdup("");
-            else
-                values[i] = msStrdup(pszValue);
-
-            if (layer->debug >= MS_DEBUGLEVEL_VVV)
-                msDebug(MSOGR_LABELHCOLORNAME " = \"%s\"\n", values[i]);
-        }
-#if GDAL_VERSION_NUM >= 1600
-        else if (itemindexes[i] == MSOGR_LABELOCOLORINDEX)
-        {
-            if (hLabelStyle == NULL 
-                || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
-                                                          OGRSTLabelOColor,
-                                                          &bDefault)) == NULL))
-                values[i] = msStrdup("");
-            else
-                values[i] = msStrdup(pszValue);
-
-            if (layer->debug >= MS_DEBUGLEVEL_VVV)
-                msDebug(MSOGR_LABELOCOLORNAME " = \"%s\"\n", values[i]);
-        }
-#endif /* GDAL_VERSION_NUM >= 1600 */
-        else
-        {
-            msSetError(MS_OGRERR,"Invalid field index!?!","msOGRGetValues()");
-            return(NULL);
-        }
-    }
-#else /* OGRStyle C++ */
-    {
-    if (!poStyleMgr)
-    {
-        poStyleMgr = new OGRStyleMgr(NULL);
-        poStyleMgr->InitFromFeature((OGRFeature *)hFeature);
-        OGRStyleTool *poStylePart = poStyleMgr->GetPart(0);
-        if (poStylePart && poStylePart->GetType() == OGRSTCLabel)
-            poLabelStyle = (OGRStyleLabel*)poStylePart;
-        else if (poStylePart)
-        {
-            delete poStylePart;
-            poStylePart = NULL;
+  for(i=0; i<layer->numitems; i++) {
+    if (itemindexes[i] >= 0) {
+      // Extract regular attributes
+      values[i] = msStrdup(OGR_F_GetFieldAsString( hFeature, itemindexes[i]));
+    } else {
+      // Handle special OGR attributes coming from StyleString
+      if (!hStyleMgr) {
+        hStyleMgr = OGR_SM_Create(NULL);
+        OGR_SM_InitFromFeature(hStyleMgr, hFeature);
+        OGRStyleToolH hStylePart = OGR_SM_GetPart(hStyleMgr, 0, NULL);
+        if (hStylePart && OGR_ST_GetType(hStylePart) == OGRSTCLabel)
+          hLabelStyle = hStylePart;
+        else if (hStylePart) {
+          OGR_ST_Destroy(hStylePart);
+          hStylePart =  NULL;
         }
+
         /* Setting up the size units according to msOGRLayerGetAutoStyle*/
-        if (poStylePart && layer->map)
-            poStylePart->SetUnit(OGRSTUPixel, layer->map->cellsize*72.0*39.37);
-    }
-    GBool bDefault;
-    if (itemindexes[i] == MSOGR_LABELTEXTINDEX)
-    {
-        if (poLabelStyle == NULL 
-            || ((pszValue = poLabelStyle->TextString(bDefault)) == NULL))
-           values[i] = msStrdup("");
+        if (hStylePart && layer->map)
+          OGR_ST_SetUnit(hStylePart, OGRSTUPixel, layer->map->cellsize*72.0*39.37);
+      }
+      int bDefault;
+      if (itemindexes[i] == MSOGR_LABELTEXTINDEX) {
+        if (hLabelStyle == NULL
+            || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
+                                               OGRSTLabelTextString,
+                                               &bDefault)) == NULL))
+          values[i] = msStrdup("");
         else
-            values[i] = msStrdup(pszValue);
+          values[i] = msStrdup(pszValue);
+
         if (layer->debug >= MS_DEBUGLEVEL_VVV)
-            msDebug(MSOGR_LABELTEXTNAME " = \"%s\"\n", values[i]);
-    }
-    else if (itemindexes[i] == MSOGR_LABELANGLEINDEX)
-    {
-        if (poLabelStyle == NULL
-            || ((pszValue = poLabelStyle->GetParamStr(OGRSTLabelAngle,bDefault)) == NULL))
-           values[i] = msStrdup("0");
+          msDebug(MSOGR_LABELTEXTNAME " = \"%s\"\n", values[i]);
+      } else if (itemindexes[i] == MSOGR_LABELANGLEINDEX) {
+        if (hLabelStyle == NULL
+            || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
+                                               OGRSTLabelAngle,
+                                               &bDefault)) == NULL))
+          values[i] = msStrdup("0");
         else
-           values[i] = msStrdup(pszValue);
+          values[i] = msStrdup(pszValue);
+
         if (layer->debug >= MS_DEBUGLEVEL_VVV)
-            msDebug(MSOGR_LABELANGLENAME " = \"%s\"\n", values[i]);
-    }
-    else if (itemindexes[i] == MSOGR_LABELSIZEINDEX)
-    {
-        if (poLabelStyle == NULL
-            || ((pszValue = poLabelStyle->GetParamStr(OGRSTLabelSize,bDefault)) == NULL))
-           values[i] = msStrdup("0");
+          msDebug(MSOGR_LABELANGLENAME " = \"%s\"\n", values[i]);
+      } else if (itemindexes[i] == MSOGR_LABELSIZEINDEX) {
+        if (hLabelStyle == NULL
+            || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
+                                               OGRSTLabelSize,
+                                               &bDefault)) == NULL))
+          values[i] = msStrdup("0");
         else
-           values[i] = msStrdup(pszValue);
+          values[i] = msStrdup(pszValue);
+
         if (layer->debug >= MS_DEBUGLEVEL_VVV)
-            msDebug(MSOGR_LABELSIZENAME " = \"%s\"\n", values[i]);
-    }
-    else if (itemindexes[i] == MSOGR_LABELFCOLORINDEX)
-    {
-        if (poLabelStyle == NULL
-            || ((pszValue = poLabelStyle->GetParamStr(OGRSTLabelFColor, bDefault)) == NULL))
-           values[i] = msStrdup("#000000");
+          msDebug(MSOGR_LABELSIZENAME " = \"%s\"\n", values[i]);
+      } else if (itemindexes[i] == MSOGR_LABELFCOLORINDEX) {
+        if (hLabelStyle == NULL
+            || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
+                                               OGRSTLabelFColor,
+                                               &bDefault)) == NULL))
+          values[i] = msStrdup("#000000");
         else
-           values[i] = msStrdup(pszValue);
+          values[i] = msStrdup(pszValue);
 
         if (layer->debug >= MS_DEBUGLEVEL_VVV)
-            msDebug(MSOGR_LABELSIZENAME " = \"%s\"\n", values[i]);
-    }
-    else if (itemindexes[i] == MSOGR_LABELFONTNAMEINDEX)
-    {
-        if (poLabelStyle == NULL
-            || ((pszValue = poLabelStyle->GetParamStr(OGRSTLabelFontName, bDefault)) == NULL))
-           values[i] = msStrdup("Arial");
+          msDebug(MSOGR_LABELFCOLORNAME " = \"%s\"\n", values[i]);
+      } else if (itemindexes[i] == MSOGR_LABELFONTNAMEINDEX ) {
+        if (hLabelStyle == NULL
+            || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
+                                               OGRSTLabelFontName,
+                                               &bDefault)) == NULL))
+          values[i] = msStrdup("Arial");
         else
-           values[i] = msStrdup(pszValue);
+          values[i] = msStrdup(pszValue);
 
         if (layer->debug >= MS_DEBUGLEVEL_VVV)
-            msDebug(MSOGR_LABELFONTNAMENAME " = \"%s\"\n", values[i]);
-    }
-    else if (itemindexes[i] == MSOGR_LABELBCOLORINDEX)
-    {
-        if (poLabelStyle == NULL
-            || ((pszValue = poLabelStyle->GetParamStr(OGRSTLabelBColor, bDefault)) == NULL))
-           values[i] = msStrdup("#000000");
+          msDebug(MSOGR_LABELFONTNAMENAME " =       \"%s\"\n", values[i]);
+      } else if (itemindexes[i] == MSOGR_LABELBCOLORINDEX) {
+        if (hLabelStyle == NULL
+            || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
+                                               OGRSTLabelBColor,
+                                               &bDefault)) == NULL))
+          values[i] = msStrdup("#000000");
         else
-           values[i] = msStrdup(pszValue);
+          values[i] = msStrdup(pszValue);
 
         if (layer->debug >= MS_DEBUGLEVEL_VVV)
-            msDebug(MSOGR_LABELBCOLORNAME " = \"%s\"\n", values[i]);
-    }
-    else if (itemindexes[i] == MSOGR_LABELPLACEMENTINDEX)
-    {
-        if (poLabelStyle == NULL
-            || ((pszValue = poLabelStyle->GetParamStr(OGRSTLabelPlacement, bDefault)) == NULL))
-           values[i] = msStrdup("");
+          msDebug(MSOGR_LABELBCOLORNAME " = \"%s\"\n", values[i]);
+      } else if (itemindexes[i] == MSOGR_LABELPLACEMENTINDEX) {
+        if (hLabelStyle == NULL
+            || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
+                                               OGRSTLabelPlacement,
+                                               &bDefault)) == NULL))
+          values[i] = msStrdup("");
         else
-           values[i] = msStrdup(pszValue);
+          values[i] = msStrdup(pszValue);
 
         if (layer->debug >= MS_DEBUGLEVEL_VVV)
-            msDebug(MSOGR_LABELPLACEMENTNAME " = \"%s\"\n", values[i]);
-    }
-    else if (itemindexes[i] == MSOGR_LABELANCHORINDEX)
-    {
-        if (poLabelStyle == NULL
-            || ((pszValue = poLabelStyle->GetParamStr(OGRSTLabelAnchor, bDefault)) == NULL))
-           values[i] = msStrdup("0");
+          msDebug(MSOGR_LABELPLACEMENTNAME " = \"%s\"\n", values[i]);
+      } else if (itemindexes[i] == MSOGR_LABELANCHORINDEX) {
+        if (hLabelStyle == NULL
+            || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
+                                               OGRSTLabelAnchor,
+                                               &bDefault)) == NULL))
+          values[i] = msStrdup("0");
         else
-           values[i] = msStrdup(pszValue);
+          values[i] = msStrdup(pszValue);
 
         if (layer->debug >= MS_DEBUGLEVEL_VVV)
-            msDebug(MSOGR_LABELANCHORNAME " = \"%s\"\n", values[i]);
-    }
-    else if (itemindexes[i] == MSOGR_LABELDXINDEX)
-    {
-        if (poLabelStyle == NULL
-            || ((pszValue = poLabelStyle->GetParamStr(OGRSTLabelDx, bDefault)) == NULL))
-           values[i] = msStrdup("0");
+          msDebug(MSOGR_LABELANCHORNAME " = \"%s\"\n", values[i]);
+      } else if (itemindexes[i] == MSOGR_LABELDXINDEX) {
+        if (hLabelStyle == NULL
+            || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
+                                               OGRSTLabelDx,
+                                               &bDefault)) == NULL))
+          values[i] = msStrdup("0");
         else
-           values[i] = msStrdup(pszValue);
+          values[i] = msStrdup(pszValue);
 
         if (layer->debug >= MS_DEBUGLEVEL_VVV)
-            msDebug(MSOGR_LABELDXNAME " = \"%s\"\n", values[i]);
-    }
-    else if (itemindexes[i] == MSOGR_LABELDYINDEX)
-    {
-        if (poLabelStyle == NULL
-            || ((pszValue = poLabelStyle->GetParamStr(OGRSTLabelDy, bDefault)) == NULL))
-           values[i] = msStrdup("0");
+          msDebug(MSOGR_LABELDXNAME " = \"%s\"\n", values[i]);
+      } else if (itemindexes[i] == MSOGR_LABELDYINDEX) {
+        if (hLabelStyle == NULL
+            || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
+                                               OGRSTLabelDy,
+                                               &bDefault)) == NULL))
+          values[i] = msStrdup("0");
         else
-           values[i] = msStrdup(pszValue);
+          values[i] = msStrdup(pszValue);
 
         if (layer->debug >= MS_DEBUGLEVEL_VVV)
-            msDebug(MSOGR_LABELDYNAME " = \"%s\"\n", values[i]);
-    }
-    else if (itemindexes[i] == MSOGR_LABELPERPINDEX)
-    {
-        if (poLabelStyle == NULL
-            || ((pszValue = poLabelStyle->GetParamStr(OGRSTLabelPerp, bDefault)) == NULL))
-           values[i] = msStrdup("0");
+          msDebug(MSOGR_LABELDYNAME " = \"%s\"\n", values[i]);
+      } else if (itemindexes[i] == MSOGR_LABELPERPINDEX) {
+        if (hLabelStyle == NULL
+            || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
+                                               OGRSTLabelPerp,
+                                               &bDefault)) == NULL))
+          values[i] = msStrdup("0");
         else
-           values[i] = msStrdup(pszValue);
+          values[i] = msStrdup(pszValue);
 
         if (layer->debug >= MS_DEBUGLEVEL_VVV)
-            msDebug(MSOGR_LABELPERPNAME " = \"%s\"\n", values[i]);
-    }
-    else if (itemindexes[i] == MSOGR_LABELBOLDINDEX)
-    {
-        if (poLabelStyle == NULL
-            || ((pszValue = poLabelStyle->GetParamStr(OGRSTLabelBold, bDefault)) == NULL))
-           values[i] = msStrdup("0");
+          msDebug(MSOGR_LABELPERPNAME " = \"%s\"\n", values[i]);
+      } else if (itemindexes[i] == MSOGR_LABELBOLDINDEX) {
+        if (hLabelStyle == NULL
+            || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
+                                               OGRSTLabelBold,
+                                               &bDefault)) == NULL))
+          values[i] = msStrdup("0");
         else
-           values[i] = msStrdup(pszValue);
+          values[i] = msStrdup(pszValue);
 
         if (layer->debug >= MS_DEBUGLEVEL_VVV)
-            msDebug(MSOGR_LABELBOLDNAME " = \"%s\"\n", values[i]);
-    }
-    else if (itemindexes[i] == MSOGR_LABELITALICINDEX)
-    {
-        if (poLabelStyle == NULL
-            || ((pszValue = poLabelStyle->GetParamStr(OGRSTLabelItalic, bDefault)) == NULL))
-           values[i] = msStrdup("0");
+          msDebug(MSOGR_LABELBOLDNAME " = \"%s\"\n", values[i]);
+      } else if (itemindexes[i] == MSOGR_LABELITALICINDEX) {
+        if (hLabelStyle == NULL
+            || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
+                                               OGRSTLabelItalic,
+                                               &bDefault)) == NULL))
+          values[i] = msStrdup("0");
         else
-           values[i] = msStrdup(pszValue);
+          values[i] = msStrdup(pszValue);
 
         if (layer->debug >= MS_DEBUGLEVEL_VVV)
-            msDebug(MSOGR_LABELITALICNAME " = \"%s\"\n", values[i]);
-    }
-    else if (itemindexes[i] == MSOGR_LABELUNDERLINEINDEX)
-    {
-        if (poLabelStyle == NULL
-            || ((pszValue = poLabelStyle->GetParamStr(OGRSTLabelUnderline, bDefault)) == NULL))
-           values[i] = msStrdup("0");
+          msDebug(MSOGR_LABELITALICNAME " = \"%s\"\n", values[i]);
+      } else if (itemindexes[i] == MSOGR_LABELUNDERLINEINDEX) {
+        if (hLabelStyle == NULL
+            || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
+                                               OGRSTLabelUnderline,
+                                               &bDefault)) == NULL))
+          values[i] = msStrdup("0");
         else
-           values[i] = msStrdup(pszValue);
+          values[i] = msStrdup(pszValue);
+
         if (layer->debug >= MS_DEBUGLEVEL_VVV)
-            msDebug(MSOGR_LABELUNDERLINENAME " = \"%s\"\n", values[i]);
-    }
-    else if (itemindexes[i] == MSOGR_LABELPRIORITYINDEX)
-    {
-        if (poLabelStyle == NULL
-            || ((pszValue = poLabelStyle->GetParamStr(OGRSTLabelPriority, bDefault)) == NULL))
-           values[i] = msStrdup("0");
+          msDebug(MSOGR_LABELUNDERLINENAME " = \"%s\"\n", values[i]);
+      } else if (itemindexes[i] == MSOGR_LABELPRIORITYINDEX) {
+        if (hLabelStyle == NULL
+            || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
+                                               OGRSTLabelPriority,
+                                               &bDefault)) == NULL))
+          values[i] = msStrdup("0");
         else
-           values[i] = msStrdup(pszValue);
+          values[i] = msStrdup(pszValue);
 
         if (layer->debug >= MS_DEBUGLEVEL_VVV)
-            msDebug(MSOGR_LABELPRIORITYNAME " = \"%s\"\n", values[i]);
-    }
-#if GDAL_VERSION_NUM >= 1400
-    else if (itemindexes[i] == MSOGR_LABELSTRIKEOUTINDEX)
-    {
-        if (poLabelStyle == NULL
-            || ((pszValue = poLabelStyle->GetParamStr(OGRSTLabelStrikeout, bDefault)) == NULL))
-            values[i] = msStrdup("0");
+          msDebug(MSOGR_LABELPRIORITYNAME " = \"%s\"\n", values[i]);
+      } else if (itemindexes[i] == MSOGR_LABELSTRIKEOUTINDEX) {
+        if (hLabelStyle == NULL
+            || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
+                                               OGRSTLabelStrikeout,
+                                               &bDefault)) == NULL))
+          values[i] = msStrdup("0");
         else
-           values[i] = msStrdup(pszValue);
+          values[i] = msStrdup(pszValue);
 
         if (layer->debug >= MS_DEBUGLEVEL_VVV)
-            msDebug(MSOGR_LABELSTRIKEOUTNAME " = \"%s\"\n", values[i]);
-    }
-    else if (itemindexes[i] == MSOGR_LABELSTRETCHINDEX)
-    {
-        if (poLabelStyle == NULL
-            || ((pszValue = poLabelStyle->GetParamStr(OGRSTLabelStretch, bDefault)) == NULL))
-           values[i] = msStrdup("0");
+          msDebug(MSOGR_LABELSTRIKEOUTNAME " = \"%s\"\n", values[i]);
+      } else if (itemindexes[i] == MSOGR_LABELSTRETCHINDEX) {
+        if (hLabelStyle == NULL
+            || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
+                                               OGRSTLabelStretch,
+                                               &bDefault)) == NULL))
+          values[i] = msStrdup("0");
         else
-           values[i] = msStrdup(pszValue);
+          values[i] = msStrdup(pszValue);
 
         if (layer->debug >= MS_DEBUGLEVEL_VVV)
-            msDebug(MSOGR_LABELSTRETCHNAME " = \"%s\"\n", values[i]);
-    }
-    else if (itemindexes[i] == MSOGR_LABELADJHORINDEX)
-    {
-        if (poLabelStyle == NULL
-            || ((pszValue = poLabelStyle->GetParamStr(OGRSTLabelAdjHor, bDefault)) == NULL))
-           values[i] = msStrdup("");
+          msDebug(MSOGR_LABELSTRETCHNAME " = \"%s\"\n", values[i]);
+      } else if (itemindexes[i] == MSOGR_LABELADJHORINDEX) {
+        if (hLabelStyle == NULL
+            || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
+                                               OGRSTLabelAdjHor,
+                                               &bDefault)) == NULL))
+          values[i] = msStrdup("");
         else
-           values[i] = msStrdup(pszValue);
+          values[i] = msStrdup(pszValue);
 
         if (layer->debug >= MS_DEBUGLEVEL_VVV)
-            msDebug(MSOGR_LABELADJHORNAME " = \"%s\"\n", values[i]);
-    }
-    else if (itemindexes[i] == MSOGR_LABELADJVERTINDEX)
-    {
-        if (poLabelStyle == NULL
-            || ((pszValue = poLabelStyle->GetParamStr(OGRSTLabelAdjVert, bDefault)) == NULL))
-           values[i] = msStrdup("");
+          msDebug(MSOGR_LABELADJHORNAME " = \"%s\"\n", values[i]);
+      } else if (itemindexes[i] == MSOGR_LABELADJVERTINDEX) {
+        if (hLabelStyle == NULL
+            || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
+                                               OGRSTLabelAdjVert,
+                                               &bDefault)) == NULL))
+          values[i] = msStrdup("");
         else
-           values[i] = msStrdup(pszValue);
+          values[i] = msStrdup(pszValue);
 
         if (layer->debug >= MS_DEBUGLEVEL_VVV)
-            msDebug(MSOGR_LABELADJVERTNAME " = \"%s\"\n", values[i]);
-    }
-    else if (itemindexes[i] == MSOGR_LABELHCOLORINDEX)
-    {
-        if (poLabelStyle == NULL
-            || ((pszValue = poLabelStyle->GetParamStr(OGRSTLabelHColor, bDefault)) == NULL))
-            values[i] = msStrdup("");
+          msDebug(MSOGR_LABELADJVERTNAME " = \"%s\"\n", values[i]);
+      } else if (itemindexes[i] == MSOGR_LABELHCOLORINDEX) {
+        if (hLabelStyle == NULL
+            || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
+                                               OGRSTLabelHColor,
+                                               &bDefault)) == NULL))
+          values[i] = msStrdup("");
         else
-           values[i] = msStrdup(pszValue);
+          values[i] = msStrdup(pszValue);
 
         if (layer->debug >= MS_DEBUGLEVEL_VVV)
-            msDebug(MSOGR_LABELHCOLORNAME " = \"%s\"\n", values[i]);
-    }
-#endif
-    else
-    {
+          msDebug(MSOGR_LABELHCOLORNAME " = \"%s\"\n", values[i]);
+      }
+#if GDAL_VERSION_NUM >= 1600
+      else if (itemindexes[i] == MSOGR_LABELOCOLORINDEX) {
+        if (hLabelStyle == NULL
+            || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
+                                               OGRSTLabelOColor,
+                                               &bDefault)) == NULL))
+          values[i] = msStrdup("");
+        else
+          values[i] = msStrdup(pszValue);
+
+        if (layer->debug >= MS_DEBUGLEVEL_VVV)
+          msDebug(MSOGR_LABELOCOLORNAME " = \"%s\"\n", values[i]);
+      }
+#endif /* GDAL_VERSION_NUM >= 1600 */
+      else {
         msSetError(MS_OGRERR,"Invalid field index!?!","msOGRGetValues()");
         return(NULL);
+      }
     }
   }
-#endif /* OGRStyle C API */
-  }
 
-#if GDAL_VERSION_NUM >= 1500 /* Use OGR Style C API */
   OGR_SM_Destroy(hStyleMgr);
   OGR_ST_Destroy(hLabelStyle);
-#else
-  delete poStyleMgr;
-  delete poLabelStyle;
-#endif
 
   return(values);
 }
@@ -1160,40 +813,34 @@ static char **msOGRGetValues(layerObj *layer, OGRFeatureH hFeature)
  * Returns MS_SUCCESS/MS_FAILURE
  **********************************************************************/
 static int msOGRSpatialRef2ProjectionObj(OGRSpatialReferenceH hSRS,
-                                         projectionObj *proj, int debug_flag )
+    projectionObj *proj, int debug_flag )
 {
 #ifdef USE_PROJ
-  // First flush the "auto" name from the projargs[]... 
+  // First flush the "auto" name from the projargs[]...
   msFreeProjection( proj );
 
-  if (hSRS == NULL || OSRIsLocal( hSRS ) )
-  {
-      // Dataset had no set projection or is NonEarth (LOCAL_CS)... 
-      // Nothing else to do. Leave proj empty and no reprojection will happen!
-      return MS_SUCCESS;  
+  if (hSRS == NULL || OSRIsLocal( hSRS ) ) {
+    // Dataset had no set projection or is NonEarth (LOCAL_CS)...
+    // Nothing else to do. Leave proj empty and no reprojection will happen!
+    return MS_SUCCESS;
   }
 
   // Export OGR SRS to a PROJ4 string
   char *pszProj = NULL;
 
-  ACQUIRE_OLD_OGR_LOCK;
   if (OSRExportToProj4( hSRS, &pszProj ) != OGRERR_NONE ||
-      pszProj == NULL || strlen(pszProj) == 0)
-  {
-      RELEASE_OLD_OGR_LOCK;
-      msSetError(MS_OGRERR, "Conversion from OGR SRS to PROJ4 failed.",
-                 "msOGRSpatialRef2ProjectionObj()");
-      CPLFree(pszProj);
-      return(MS_FAILURE);
+      pszProj == NULL || strlen(pszProj) == 0) {
+    msSetError(MS_OGRERR, "Conversion from OGR SRS to PROJ4 failed.",
+               "msOGRSpatialRef2ProjectionObj()");
+    CPLFree(pszProj);
+    return(MS_FAILURE);
   }
 
-  RELEASE_OLD_OGR_LOCK;
-
   if( debug_flag )
-      msDebug( "AUTO = %s\n", pszProj );
+    msDebug( "AUTO = %s\n", pszProj );
 
   if( msLoadProjectionString( proj, pszProj ) != 0 )
-      return MS_FAILURE;
+    return MS_FAILURE;
 
   CPLFree(pszProj);
 #endif
@@ -1211,49 +858,45 @@ static int msOGRSpatialRef2ProjectionObj(OGRSpatialReferenceH hSRS,
  * Returns MS_SUCCESS/MS_FAILURE
  **********************************************************************/
 
-int msOGCWKT2ProjectionObj( const char *pszWKT, 
+int msOGCWKT2ProjectionObj( const char *pszWKT,
                             projectionObj *proj,
                             int debug_flag )
 
 {
 #if defined(USE_OGR) || defined(USE_GDAL)
 
-    OGRSpatialReferenceH        hSRS;
-    char			*pszAltWKT = (char *) pszWKT;
-    OGRErr  eErr;
-    int     ms_result;
-
-    ACQUIRE_OLD_OGR_LOCK;
-    hSRS = OSRNewSpatialReference( NULL );
+  OGRSpatialReferenceH        hSRS;
+  char      *pszAltWKT = (char *) pszWKT;
+  OGRErr  eErr;
+  int     ms_result;
 
-    if( !EQUALN(pszWKT,"GEOGCS",6) 
-        && !EQUALN(pszWKT,"PROJCS",6)
-        && !EQUALN(pszWKT,"LOCAL_CS",8) )
-        eErr = OSRSetFromUserInput( hSRS, pszWKT );
-    else
-        eErr = OSRImportFromWkt( hSRS, &pszAltWKT );
+  hSRS = OSRNewSpatialReference( NULL );
 
-    RELEASE_OLD_OGR_LOCK;
+  if( !EQUALN(pszWKT,"GEOGCS",6)
+      && !EQUALN(pszWKT,"PROJCS",6)
+      && !EQUALN(pszWKT,"LOCAL_CS",8) )
+    eErr = OSRSetFromUserInput( hSRS, pszWKT );
+  else
+    eErr = OSRImportFromWkt( hSRS, &pszAltWKT );
 
-    if( eErr != OGRERR_NONE )
-    {
-        OSRDestroySpatialReference( hSRS );
-        msSetError(MS_OGRERR, 
-                   "Ingestion of WKT string '%s' failed.",
-                   "msOGCWKT2ProjectionObj()",
-                   pszWKT );
-        return MS_FAILURE;
-    }
+  if( eErr != OGRERR_NONE ) {
+    OSRDestroySpatialReference( hSRS );
+    msSetError(MS_OGRERR,
+               "Ingestion of WKT string '%s' failed.",
+               "msOGCWKT2ProjectionObj()",
+               pszWKT );
+    return MS_FAILURE;
+  }
 
-    ms_result = msOGRSpatialRef2ProjectionObj( hSRS, proj, debug_flag );
+  ms_result = msOGRSpatialRef2ProjectionObj( hSRS, proj, debug_flag );
 
-    OSRDestroySpatialReference( hSRS );
-    return ms_result;
+  OSRDestroySpatialReference( hSRS );
+  return ms_result;
 #else
-    msSetError(MS_OGRERR, 
-               "Not implemented since neither OGR nor GDAL is enabled.",
-               "msOGCWKT2ProjectionObj()");
-    return MS_FAILURE;
+  msSetError(MS_OGRERR,
+             "Not implemented since neither OGR nor GDAL is enabled.",
+             "msOGCWKT2ProjectionObj()");
+  return MS_FAILURE;
 #endif
 }
 
@@ -1263,33 +906,34 @@ int msOGCWKT2ProjectionObj( const char *pszWKT,
  * Open an OGR connection, and initialize a msOGRFileInfo.
  **********************************************************************/
 
+#ifdef USE_OGR
 static int bOGRDriversRegistered = MS_FALSE;
+#endif
 
 void msOGRInitialize(void)
 
 {
 #ifdef USE_OGR
-/* ------------------------------------------------------------------
- * Register OGR Drivers, only once per execution
- * ------------------------------------------------------------------ */
-    if (!bOGRDriversRegistered)
-    {
-        ACQUIRE_OGR_LOCK;
+  /* ------------------------------------------------------------------
+   * Register OGR Drivers, only once per execution
+   * ------------------------------------------------------------------ */
+  if (!bOGRDriversRegistered) {
+    ACQUIRE_OGR_LOCK;
 
-        OGRRegisterAll();
-        CPLPushErrorHandler( CPLQuietErrorHandler );
+    OGRRegisterAll();
+    CPLPushErrorHandler( CPLQuietErrorHandler );
 
-/* ------------------------------------------------------------------
- * Pass config option GML_FIELDTYPES=ALWAYS_STRING to OGR so that all
- * GML attributes are returned as strings to MapServer. This is most efficient
- * and prevents problems with autodetection of some attribute types.
- * ------------------------------------------------------------------ */
-        CPLSetConfigOption("GML_FIELDTYPES","ALWAYS_STRING");
+    /* ------------------------------------------------------------------
+     * Pass config option GML_FIELDTYPES=ALWAYS_STRING to OGR so that all
+     * GML attributes are returned as strings to MapServer. This is most efficient
+     * and prevents problems with autodetection of some attribute types.
+     * ------------------------------------------------------------------ */
+    CPLSetConfigOption("GML_FIELDTYPES","ALWAYS_STRING");
 
-        bOGRDriversRegistered = MS_TRUE;
-      
-        RELEASE_OGR_LOCK;
-    }
+    bOGRDriversRegistered = MS_TRUE;
+
+    RELEASE_OGR_LOCK;
+  }
 #endif /* USE_OGR */
 }
 
@@ -1308,49 +952,43 @@ void msOGRInitialize(void)
  **********************************************************************/
 
 static msOGRFileInfo *
-msOGRFileOpen(layerObj *layer, const char *connection ) 
+msOGRFileOpen(layerObj *layer, const char *connection )
 
 {
   char *conn_decrypted = NULL;
 
   msOGRInitialize();
 
-/* ------------------------------------------------------------------
- * Make sure any encrypted token in the connection string are decrypted
- * ------------------------------------------------------------------ */
-  if (connection)
-  {
-      conn_decrypted = msDecryptStringTokens(layer->map, connection);
-      if (conn_decrypted == NULL)
-          return NULL;  /* An error should already have been reported */
+  /* ------------------------------------------------------------------
+   * Make sure any encrypted token in the connection string are decrypted
+   * ------------------------------------------------------------------ */
+  if (connection) {
+    conn_decrypted = msDecryptStringTokens(layer->map, connection);
+    if (conn_decrypted == NULL)
+      return NULL;  /* An error should already have been reported */
   }
 
-/* ------------------------------------------------------------------
- * Parse connection string into dataset name, and layer name. 
- * ------------------------------------------------------------------ */
+  /* ------------------------------------------------------------------
+   * Parse connection string into dataset name, and layer name.
+   * ------------------------------------------------------------------ */
   char *pszDSName = NULL, *pszLayerDef = NULL;
 
-  if( conn_decrypted == NULL )
-  {
-      /* we don't have anything */
-  }
-  else if( layer->data != NULL )
-  {
-      pszDSName = CPLStrdup(conn_decrypted);
-      pszLayerDef = CPLStrdup(layer->data);
-  }
-  else
-  {
-      char **papszTokens = NULL;
+  if( conn_decrypted == NULL ) {
+    /* we don't have anything */
+  } else if( layer->data != NULL ) {
+    pszDSName = CPLStrdup(conn_decrypted);
+    pszLayerDef = CPLStrdup(layer->data);
+  } else {
+    char **papszTokens = NULL;
 
-      papszTokens = CSLTokenizeStringComplex( conn_decrypted, ",", TRUE, FALSE );
+    papszTokens = CSLTokenizeStringComplex( conn_decrypted, ",", TRUE, FALSE );
 
-      if( CSLCount(papszTokens) > 0 )
-          pszDSName = CPLStrdup( papszTokens[0] );
-      if( CSLCount(papszTokens) > 1 )
-          pszLayerDef = CPLStrdup( papszTokens[1] );
+    if( CSLCount(papszTokens) > 0 )
+      pszDSName = CPLStrdup( papszTokens[0] );
+    if( CSLCount(papszTokens) > 1 )
+      pszLayerDef = CPLStrdup( papszTokens[1] );
 
-      CSLDestroy(papszTokens);
+    CSLDestroy(papszTokens);
   }
 
   /* Get rid of decrypted connection string. We'll use the original (not
@@ -1359,141 +997,135 @@ msOGRFileOpen(layerObj *layer, const char *connection )
   msFree(conn_decrypted);
   conn_decrypted = NULL;
 
-  if( pszDSName == NULL )
-  {
-      msSetError(MS_OGRERR, 
-                 "Error parsing OGR connection information in layer `%s'", 
-                 "msOGRFileOpen()",
-                 layer->name?layer->name:"(null)" );
-      return NULL;
+  if( pszDSName == NULL ) {
+    msSetError(MS_OGRERR,
+               "Error parsing OGR connection information in layer `%s'",
+               "msOGRFileOpen()",
+               layer->name?layer->name:"(null)" );
+    return NULL;
   }
 
   if( pszLayerDef == NULL )
-      pszLayerDef = CPLStrdup("0");
+    pszLayerDef = CPLStrdup("0");
 
-/* -------------------------------------------------------------------- */
-/*      Can we get an existing connection for this layer?               */
-/* -------------------------------------------------------------------- */
+  /* -------------------------------------------------------------------- */
+  /*      Can we get an existing connection for this layer?               */
+  /* -------------------------------------------------------------------- */
   OGRDataSourceH hDS;
 
   hDS = (OGRDataSourceH) msConnPoolRequest( layer );
 
-/* -------------------------------------------------------------------- */
-/*      If not, open now, and register this connection with the         */
-/*      pool.                                                           */
-/* -------------------------------------------------------------------- */
-  if( hDS == NULL )
-  {
-      char szPath[MS_MAXPATHLEN] = "";
-      const char *pszDSSelectedName = pszDSName;
-      
-      if( layer->debug )
-          msDebug("msOGRFileOpen(%s)...\n", connection);
-      
-      CPLErrorReset();
-      if (msTryBuildPath3(szPath, layer->map->mappath, 
-                          layer->map->shapepath, pszDSName) != NULL ||
-          msTryBuildPath(szPath, layer->map->mappath, pszDSName) != NULL)
-      {
-          /* Use relative path */
-          pszDSSelectedName = szPath;
-      }
-      
-      if( layer->debug )
-          msDebug("OGROPen(%s)\n", pszDSSelectedName);
+  /* -------------------------------------------------------------------- */
+  /*      If not, open now, and register this connection with the         */
+  /*      pool.                                                           */
+  /* -------------------------------------------------------------------- */
+  if( hDS == NULL ) {
+    char szPath[MS_MAXPATHLEN] = "";
+    const char *pszDSSelectedName = pszDSName;
+
+    if( layer->debug )
+      msDebug("msOGRFileOpen(%s)...\n", connection);
+
+    CPLErrorReset();
+    if (msTryBuildPath3(szPath, layer->map->mappath,
+                        layer->map->shapepath, pszDSName) != NULL ||
+        msTryBuildPath(szPath, layer->map->mappath, pszDSName) != NULL) {
+      /* Use relative path */
+      pszDSSelectedName = szPath;
+    }
 
-      ACQUIRE_OGR_LOCK;
-      hDS = OGROpen( pszDSSelectedName, MS_FALSE, NULL );
-      RELEASE_OGR_LOCK;
-      
-      if( hDS == NULL )
-      {
-          if( strlen(CPLGetLastErrorMsg()) == 0 )
-              msSetError(MS_OGRERR, 
-                         "Open failed for OGR connection in layer `%s'.  "
-                         "File not found or unsupported format.", 
-                         "msOGRFileOpen()",
-                         layer->name?layer->name:"(null)" );
-          else
-              msSetError(MS_OGRERR, 
-                         "Open failed for OGR connection in layer `%s'.\n%s\n",
-                         "msOGRFileOpen()", 
-                         layer->name?layer->name:"(null)", 
-                         CPLGetLastErrorMsg() );
-          CPLFree( pszDSName );
-          CPLFree( pszLayerDef );
-          return NULL;
-      }
+    if( layer->debug )
+      msDebug("OGROPen(%s)\n", pszDSSelectedName);
+
+    ACQUIRE_OGR_LOCK;
+    hDS = OGROpen( pszDSSelectedName, MS_FALSE, NULL );
+    RELEASE_OGR_LOCK;
+
+    if( hDS == NULL ) {
+      if( strlen(CPLGetLastErrorMsg()) == 0 )
+        msSetError(MS_OGRERR,
+                   "Open failed for OGR connection in layer `%s'.  "
+                   "File not found or unsupported format.",
+                   "msOGRFileOpen()",
+                   layer->name?layer->name:"(null)" );
+      else
+        msSetError(MS_OGRERR,
+                   "Open failed for OGR connection in layer `%s'.\n%s\n",
+                   "msOGRFileOpen()",
+                   layer->name?layer->name:"(null)",
+                   CPLGetLastErrorMsg() );
+      CPLFree( pszDSName );
+      CPLFree( pszLayerDef );
+      return NULL;
+    }
 
-      msConnPoolRegister( layer, hDS, msOGRCloseConnection );
+    msConnPoolRegister( layer, hDS, msOGRCloseConnection );
   }
-      
+
   CPLFree( pszDSName );
   pszDSName = NULL;
 
-/* ------------------------------------------------------------------
- * Find the layer selected.
- * ------------------------------------------------------------------ */
-  
+  /* ------------------------------------------------------------------
+   * Find the layer selected.
+   * ------------------------------------------------------------------ */
+
   int   nLayerIndex = 0;
   OGRLayerH     hLayer = NULL;
 
   int  iLayer;
 
-  for( iLayer = 0; iLayer < OGR_DS_GetLayerCount(hDS); iLayer++ )
-  {
-      hLayer = OGR_DS_GetLayer( hDS, iLayer );
-      if( hLayer != NULL 
-          && EQUAL(OGR_FD_GetName( OGR_L_GetLayerDefn(hLayer) ),pszLayerDef) )
-      {
-          nLayerIndex = iLayer;
-          break;
-      }
-      else
-          hLayer = NULL;
+  if( EQUALN(pszLayerDef,"SELECT ",7) ) {
+    ACQUIRE_OGR_LOCK;
+    hLayer = OGR_DS_ExecuteSQL( hDS, pszLayerDef, NULL, NULL );
+    if( hLayer == NULL ) {
+      msSetError(MS_OGRERR,
+                 "ExecuteSQL(%s) failed.\n%s",
+                 "msOGRFileOpen()",
+                 pszLayerDef, CPLGetLastErrorMsg() );
+      RELEASE_OGR_LOCK;
+      msConnPoolRelease( layer, hDS );
+      CPLFree( pszLayerDef );
+      return NULL;
+    }
+    RELEASE_OGR_LOCK;
+    nLayerIndex = -1;
   }
-  
-  if( hLayer == NULL && (atoi(pszLayerDef) > 0 || EQUAL(pszLayerDef,"0")) )
-  {
-      nLayerIndex = atoi(pszLayerDef);
-      if( nLayerIndex <  OGR_DS_GetLayerCount(hDS) )
-          hLayer = OGR_DS_GetLayer( hDS, nLayerIndex );
+
+  for( iLayer = 0; hLayer == NULL && iLayer < OGR_DS_GetLayerCount(hDS); iLayer++ ) {
+    hLayer = OGR_DS_GetLayer( hDS, iLayer );
+    if( hLayer != NULL
+#if GDAL_VERSION_NUM >= 1800
+        && EQUAL(OGR_L_GetName(hLayer),pszLayerDef) )
+#else
+        && EQUAL(OGR_FD_GetName( OGR_L_GetLayerDefn(hLayer) ),pszLayerDef) )
+#endif
+    {
+      nLayerIndex = iLayer;
+      break;
+    } else
+      hLayer = NULL;
   }
 
-  if( hLayer == NULL && EQUALN(pszLayerDef,"SELECT",6) )
-  {
-      ACQUIRE_OGR_LOCK;
-      hLayer = OGR_DS_ExecuteSQL( hDS, pszLayerDef, NULL, NULL );
-      if( hLayer == NULL )
-      {
-          msSetError(MS_OGRERR, 
-                     "ExecuteSQL(%s) failed.\n%s",
-                     "msOGRFileOpen()", 
-                     pszLayerDef, CPLGetLastErrorMsg() );
-          RELEASE_OGR_LOCK;
-          msConnPoolRelease( layer, hDS );
-          CPLFree( pszLayerDef );
-          return NULL;
-      }
-      RELEASE_OGR_LOCK;
-      nLayerIndex = -1;
+  if( hLayer == NULL && (atoi(pszLayerDef) > 0 || EQUAL(pszLayerDef,"0")) ) {
+    nLayerIndex = atoi(pszLayerDef);
+    if( nLayerIndex <  OGR_DS_GetLayerCount(hDS) )
+      hLayer = OGR_DS_GetLayer( hDS, nLayerIndex );
   }
 
-  if (hLayer == NULL)
-  {
-      msSetError(MS_OGRERR, "GetLayer(%s) failed for OGR connection `%s'.",
-                 "msOGRFileOpen()", 
-                 pszLayerDef, connection );
-      CPLFree( pszLayerDef );
-      msConnPoolRelease( layer, hDS );
-      return NULL;
+  if (hLayer == NULL) {
+    msSetError(MS_OGRERR, "GetLayer(%s) failed for OGR connection `%s'.",
+               "msOGRFileOpen()",
+               pszLayerDef, connection );
+    CPLFree( pszLayerDef );
+    msConnPoolRelease( layer, hDS );
+    return NULL;
   }
 
   CPLFree( pszLayerDef );
 
-/* ------------------------------------------------------------------
- * OK... open succeded... alloc and fill msOGRFileInfo inside layer obj
- * ------------------------------------------------------------------ */
+  /* ------------------------------------------------------------------
+   * OK... open succeded... alloc and fill msOGRFileInfo inside layer obj
+   * ------------------------------------------------------------------ */
   msOGRFileInfo *psInfo =(msOGRFileInfo*)CPLCalloc(1,sizeof(msOGRFileInfo));
 
   psInfo->pszFname = CPLStrdup(OGR_DS_GetName( hDS ));
@@ -1520,34 +1152,34 @@ msOGRFileOpen(layerObj *layer, const char *connection )
 static void msOGRCloseConnection( void *conn_handle )
 
 {
-    OGRDataSourceH hDS = (OGRDataSourceH) conn_handle;
+  OGRDataSourceH hDS = (OGRDataSourceH) conn_handle;
 
-    ACQUIRE_OGR_LOCK;
-    OGR_DS_Destroy( hDS );
-    RELEASE_OGR_LOCK;
+  ACQUIRE_OGR_LOCK;
+  OGR_DS_Destroy( hDS );
+  RELEASE_OGR_LOCK;
 }
 
 /**********************************************************************
  *                     msOGRFileClose()
  **********************************************************************/
-static int msOGRFileClose(layerObj *layer, msOGRFileInfo *psInfo ) 
+static int msOGRFileClose(layerObj *layer, msOGRFileInfo *psInfo )
 {
   if (!psInfo)
-      return MS_SUCCESS;
+    return MS_SUCCESS;
 
   if( layer->debug )
-      msDebug("msOGRFileClose(%s,%d).\n", 
-              psInfo->pszFname, psInfo->nLayerIndex);
+    msDebug("msOGRFileClose(%s,%d).\n",
+            psInfo->pszFname, psInfo->nLayerIndex);
 
   CPLFree(psInfo->pszFname);
 
   ACQUIRE_OGR_LOCK;
   if (psInfo->hLastFeature)
-      OGR_F_Destroy( psInfo->hLastFeature );
+    OGR_F_Destroy( psInfo->hLastFeature );
 
   /* If nLayerIndex == -1 then the layer is an SQL result ... free it */
   if( psInfo->nLayerIndex == -1 )
-      OGR_DS_ReleaseResultSet( psInfo->hDS, psInfo->hLayer );
+    OGR_DS_ReleaseResultSet( psInfo->hDS, psInfo->hLayer );
 
   // Release (potentially close) the datasource connection.
   // Make sure we aren't holding the lock when the callback may need it.
@@ -1557,7 +1189,7 @@ static int msOGRFileClose(layerObj *layer, msOGRFileInfo *psInfo )
 
   // Free current tile if there is one.
   if( psInfo->poCurTile != NULL )
-      msOGRFileClose( layer, psInfo->poCurTile );
+    msOGRFileClose( layer, psInfo->poCurTile );
 
   CPLFree(psInfo);
 
@@ -1575,80 +1207,92 @@ static int msOGRFileClose(layerObj *layer, msOGRFileInfo *psInfo )
  * layer's FILTER overlaps the selected region.
  **********************************************************************/
 static int msOGRFileWhichShapes(layerObj *layer, rectObj rect,
-                                msOGRFileInfo *psInfo ) 
+                                msOGRFileInfo *psInfo )
 {
-  if (psInfo == NULL || psInfo->hLayer == NULL)
-  {
-    msSetError(MS_MISCERR, "Assertion failed: OGR layer not opened!!!", 
+  if (psInfo == NULL || psInfo->hLayer == NULL) {
+    msSetError(MS_MISCERR, "Assertion failed: OGR layer not opened!!!",
                "msOGRFileWhichShapes()");
     return(MS_FAILURE);
   }
 
-/* ------------------------------------------------------------------
- * Set Spatial filter... this may result in no features being returned
- * if layer does not overlap current view.
- *
- * __TODO__ We should return MS_DONE if no shape overlaps the selected 
- * region and matches the layer's FILTER expression, but there is currently
- * no _efficient_ way to do that with OGR.
- * ------------------------------------------------------------------ */
+  /* ------------------------------------------------------------------
+   * Set Spatial filter... this may result in no features being returned
+   * if layer does not overlap current view.
+   *
+   * __TODO__ We should return MS_DONE if no shape overlaps the selected
+   * region and matches the layer's FILTER expression, but there is currently
+   * no _efficient_ way to do that with OGR.
+   * ------------------------------------------------------------------ */
   ACQUIRE_OGR_LOCK;
 
-  OGRGeometryH hSpatialFilterPolygon = OGR_G_CreateGeometry( wkbPolygon );
-  OGRGeometryH hRing = OGR_G_CreateGeometry( wkbLinearRing );
+  if (rect.minx == rect.maxx && rect.miny == rect.maxy)
+  {
+      OGRGeometryH hSpatialFilterPoint = OGR_G_CreateGeometry( wkbPoint );
 
-#if GDAL_VERSION_NUM >= 1310
-  OGR_G_AddPoint_2D( hRing, rect.minx, rect.miny);
-  OGR_G_AddPoint_2D( hRing, rect.maxx, rect.miny);
-  OGR_G_AddPoint_2D( hRing, rect.maxx, rect.maxy);
-  OGR_G_AddPoint_2D( hRing, rect.minx, rect.maxy);
-  OGR_G_AddPoint_2D( hRing, rect.minx, rect.miny);
-#else
-  OGR_G_AddPoint( hRing, rect.minx, rect.miny, 0);
-  OGR_G_AddPoint( hRing, rect.maxx, rect.miny, 0);
-  OGR_G_AddPoint( hRing, rect.maxx, rect.maxy, 0);
-  OGR_G_AddPoint( hRing, rect.minx, rect.maxy, 0);
-  OGR_G_AddPoint( hRing, rect.minx, rect.miny, 0);
-#endif
+      OGR_G_SetPoint_2D( hSpatialFilterPoint, 0, rect.minx, rect.miny );
+      
+      OGR_L_SetSpatialFilter( psInfo->hLayer, hSpatialFilterPoint );
 
-  OGR_G_AddGeometryDirectly( hSpatialFilterPolygon, hRing );
+      OGR_G_DestroyGeometry( hSpatialFilterPoint );
+  }
+  else if (rect.minx == rect.maxx || rect.miny == rect.maxy)
+  {
+      OGRGeometryH hSpatialFilterLine = OGR_G_CreateGeometry( wkbLineString );
 
-  OGR_L_SetSpatialFilter( psInfo->hLayer, hSpatialFilterPolygon );
+      OGR_G_AddPoint_2D( hSpatialFilterLine, rect.minx, rect.miny );
+      OGR_G_AddPoint_2D( hSpatialFilterLine, rect.maxx, rect.maxy );
 
-  OGR_G_DestroyGeometry( hSpatialFilterPolygon );
+      OGR_L_SetSpatialFilter( psInfo->hLayer, hSpatialFilterLine );
+
+      OGR_G_DestroyGeometry( hSpatialFilterLine );
+  }
+  else
+  {
+      OGRGeometryH hSpatialFilterPolygon = OGR_G_CreateGeometry( wkbPolygon );
+      OGRGeometryH hRing = OGR_G_CreateGeometry( wkbLinearRing );
+
+      OGR_G_AddPoint_2D( hRing, rect.minx, rect.miny);
+      OGR_G_AddPoint_2D( hRing, rect.maxx, rect.miny);
+      OGR_G_AddPoint_2D( hRing, rect.maxx, rect.maxy);
+      OGR_G_AddPoint_2D( hRing, rect.minx, rect.maxy);
+      OGR_G_AddPoint_2D( hRing, rect.minx, rect.miny);
+
+      OGR_G_AddGeometryDirectly( hSpatialFilterPolygon, hRing );
+
+      OGR_L_SetSpatialFilter( psInfo->hLayer, hSpatialFilterPolygon );
+
+      OGR_G_DestroyGeometry( hSpatialFilterPolygon );
+  }
 
   psInfo->rect = rect;
 
   if (layer->debug >= MS_DEBUGLEVEL_VVV)
-      msDebug("msOGRFileWhichShapes: Setting spatial filter to %f %f %f %f\n",
-              rect.minx, rect.miny, rect.maxx, rect.maxy );
-
-/* ------------------------------------------------------------------
- * Apply an attribute filter if we have one prefixed with a WHERE 
- * keyword in the filter string.  Otherwise, ensure the attribute
- * filter is clear. 
- * ------------------------------------------------------------------ */
-  if( layer->filter.string && EQUALN(layer->filter.string,"WHERE ",6) )
-  {
-      CPLErrorReset();
-      if( OGR_L_SetAttributeFilter( psInfo->hLayer, layer->filter.string+6 )
-          != OGRERR_NONE )
-      {
-          msSetError(MS_OGRERR,
-                     "SetAttributeFilter(%s) failed on layer %s.\n%s", 
-                     "msOGRFileWhichShapes()",
-                     layer->filter.string+6, layer->name?layer->name:"(null)", 
-                     CPLGetLastErrorMsg() );
-          RELEASE_OGR_LOCK;
-          return MS_FAILURE;
-      }
-  }
-  else
-      OGR_L_SetAttributeFilter( psInfo->hLayer, NULL );
+    msDebug("msOGRFileWhichShapes: Setting spatial filter to %f %f %f %f\n",
+            rect.minx, rect.miny, rect.maxx, rect.maxy );
+
+  /* ------------------------------------------------------------------
+   * Apply an attribute filter if we have one prefixed with a WHERE
+   * keyword in the filter string.  Otherwise, ensure the attribute
+   * filter is clear.
+   * ------------------------------------------------------------------ */
+  if( layer->filter.string && EQUALN(layer->filter.string,"WHERE ",6) ) {
+    CPLErrorReset();
+    if( OGR_L_SetAttributeFilter( psInfo->hLayer, layer->filter.string+6 )
+        != OGRERR_NONE ) {
+      msSetError(MS_OGRERR,
+                 "SetAttributeFilter(%s) failed on layer %s.\n%s",
+                 "msOGRFileWhichShapes()",
+                 layer->filter.string+6, layer->name?layer->name:"(null)",
+                 CPLGetLastErrorMsg() );
+      RELEASE_OGR_LOCK;
+      return MS_FAILURE;
+    }
+  } else
+    OGR_L_SetAttributeFilter( psInfo->hLayer, NULL );
 
-/* ------------------------------------------------------------------
- * Reset current feature pointer
- * ------------------------------------------------------------------ */
+  /* ------------------------------------------------------------------
+   * Reset current feature pointer
+   * ------------------------------------------------------------------ */
   OGR_L_ResetReading( psInfo->hLayer );
   psInfo->last_record_index_read = -1;
 
@@ -1661,79 +1305,77 @@ static int msOGRFileWhichShapes(layerObj *layer, rectObj rect,
  *                     msOGRPassThroughFieldDefinitions()
  *
  * Pass the field definitions through to the layer metadata in the
- * "gml_[item]_{type,width,precision}" set of metadata items for 
+ * "gml_[item]_{type,width,precision}" set of metadata items for
  * defining fields.
  **********************************************************************/
 
-static void 
+static void
 msOGRPassThroughFieldDefinitions( layerObj *layer, msOGRFileInfo *psInfo )
 
 {
-    OGRFeatureDefnH hDefn = OGR_L_GetLayerDefn( psInfo->hLayer );
-    int numitems, i;
-  
-    numitems = OGR_FD_GetFieldCount( hDefn );
+  OGRFeatureDefnH hDefn = OGR_L_GetLayerDefn( psInfo->hLayer );
+  int numitems, i;
+
+  numitems = OGR_FD_GetFieldCount( hDefn );
+
+  for(i=0; i<numitems; i++) {
+    OGRFieldDefnH hField = OGR_FD_GetFieldDefn( hDefn, i );
+    char md_item_name[256];
+    char gml_width[32], gml_precision[32];
+    const char *gml_type = NULL;
+    const char *item = OGR_Fld_GetNameRef( hField );
+
+    gml_width[0] = '\0';
+    gml_precision[0] = '\0';
+
+    switch( OGR_Fld_GetType( hField ) ) {
+      case OFTInteger:
+        gml_type = "Integer";
+        if( OGR_Fld_GetWidth( hField) > 0 )
+          sprintf( gml_width, "%d", OGR_Fld_GetWidth( hField) );
+        break;
+
+      case OFTReal:
+        gml_type = "Real";
+        if( OGR_Fld_GetWidth( hField) > 0 )
+          sprintf( gml_width, "%d", OGR_Fld_GetWidth( hField) );
+        if( OGR_Fld_GetPrecision( hField ) > 0 )
+          sprintf( gml_precision, "%d", OGR_Fld_GetPrecision( hField) );
+        break;
+
+      case OFTString:
+        gml_type = "Character";
+        if( OGR_Fld_GetWidth( hField) > 0 )
+          sprintf( gml_width, "%d", OGR_Fld_GetWidth( hField) );
+        break;
+
+      case OFTDate:
+      case OFTTime:
+      case OFTDateTime:
+        gml_type = "Date";
+        break;
 
-    for(i=0;i<numitems;i++)
-    {
-        OGRFieldDefnH hField = OGR_FD_GetFieldDefn( hDefn, i );
-        char md_item_name[256];
-        char gml_width[32], gml_precision[32];
-        const char *gml_type = NULL;
-        const char *item = OGR_Fld_GetNameRef( hField );
-
-        gml_width[0] = '\0';
-        gml_precision[0] = '\0';
-
-        switch( OGR_Fld_GetType( hField ) )
-        {
-          case OFTInteger:
-            gml_type = "Integer";
-            if( OGR_Fld_GetWidth( hField) > 0 )
-                sprintf( gml_width, "%d", OGR_Fld_GetWidth( hField) ); 
-            break;
-
-          case OFTReal:
-            gml_type = "Real";
-            if( OGR_Fld_GetWidth( hField) > 0 )
-                sprintf( gml_width, "%d", OGR_Fld_GetWidth( hField) ); 
-            if( OGR_Fld_GetPrecision( hField ) > 0 )
-                sprintf( gml_precision, "%d", OGR_Fld_GetPrecision( hField) ); 
-            break;
-
-          case OFTString:
-            gml_type = "Character";
-            if( OGR_Fld_GetWidth( hField) > 0 )
-                sprintf( gml_width, "%d", OGR_Fld_GetWidth( hField) ); 
-            break;
+      default:
+        gml_type = "Character";
+        break;
+    }
 
-          case OFTDate:
-          case OFTTime:
-          case OFTDateTime:
-            gml_type = "Date";
-            break;
+    snprintf( md_item_name, sizeof(md_item_name), "gml_%s_type", item );
+    if( msOWSLookupMetadata(&(layer->metadata), "G", "type") == NULL )
+      msInsertHashTable(&(layer->metadata), md_item_name, gml_type );
 
-          default:
-            gml_type = "Character";
-            break;
-        }
+    snprintf( md_item_name, sizeof(md_item_name), "gml_%s_width", item );
+    if( strlen(gml_width) > 0
+        && msOWSLookupMetadata(&(layer->metadata), "G", "width") == NULL )
+      msInsertHashTable(&(layer->metadata), md_item_name, gml_width );
 
-        snprintf( md_item_name, sizeof(md_item_name), "gml_%s_type", item );
-        if( msOWSLookupMetadata(&(layer->metadata), "G", "type") == NULL )
-            msInsertHashTable(&(layer->metadata), md_item_name, gml_type );
-        
-        snprintf( md_item_name, sizeof(md_item_name), "gml_%s_width", item );
-        if( strlen(gml_width) > 0 
-            && msOWSLookupMetadata(&(layer->metadata), "G", "width") == NULL )
-            msInsertHashTable(&(layer->metadata), md_item_name, gml_width );
-
-        snprintf( md_item_name, sizeof(md_item_name), "gml_%s_precision",item );
-        if( strlen(gml_precision) > 0 
-            && msOWSLookupMetadata(&(layer->metadata), "G", "precision")==NULL )
-            msInsertHashTable(&(layer->metadata), md_item_name, gml_precision );
-    }
+    snprintf( md_item_name, sizeof(md_item_name), "gml_%s_precision",item );
+    if( strlen(gml_precision) > 0
+        && msOWSLookupMetadata(&(layer->metadata), "G", "precision")==NULL )
+      msInsertHashTable(&(layer->metadata), md_item_name, gml_precision );
+  }
 
-    /* Should we try to address style items, or other special items? */
+  /* Should we try to address style items, or other special items? */
 }
 
 /**********************************************************************
@@ -1749,10 +1391,9 @@ static char **msOGRFileGetItems(layerObj *layer, msOGRFileInfo *psInfo )
   char **items;
   const char *getShapeStyleItems, *value;
 
-  if((hDefn = OGR_L_GetLayerDefn( psInfo->hLayer )) == NULL) 
-  {
-    msSetError(MS_OGRERR, 
-               "OGR Connection for layer `%s' contains no field definition.", 
+  if((hDefn = OGR_L_GetLayerDefn( psInfo->hLayer )) == NULL) {
+    msSetError(MS_OGRERR,
+               "OGR Connection for layer `%s' contains no field definition.",
                "msOGRFileGetItems()",
                layer->name?layer->name:"(null)" );
     return NULL;
@@ -1762,53 +1403,50 @@ static char **msOGRFileGetItems(layerObj *layer, msOGRFileInfo *psInfo )
 
   getShapeStyleItems = msLayerGetProcessingKey( layer, "GETSHAPE_STYLE_ITEMS" );
   if (getShapeStyleItems && EQUAL(getShapeStyleItems, "all"))
-      totalnumitems += numStyleItems;
+    totalnumitems += numStyleItems;
 
-  if((items = (char**)malloc(sizeof(char *)*(totalnumitems+1))) == NULL) 
-  {
+  if((items = (char**)malloc(sizeof(char *)*(totalnumitems+1))) == NULL) {
     msSetError(MS_MEMERR, NULL, "msOGRFileGetItems()");
     return NULL;
   }
 
-  for(i=0;i<numitems;i++)
-  {
-      OGRFieldDefnH hField = OGR_FD_GetFieldDefn( hDefn, i );
-      items[i] = msStrdup( OGR_Fld_GetNameRef( hField ));
-  }
-
-  if (getShapeStyleItems && EQUAL(getShapeStyleItems, "all"))
-  {
-      assert(numStyleItems == 21);
-      items[i++] = msStrdup( MSOGR_LABELFONTNAMENAME );
-      items[i++] = msStrdup( MSOGR_LABELSIZENAME );
-      items[i++] = msStrdup( MSOGR_LABELTEXTNAME );
-      items[i++] = msStrdup( MSOGR_LABELANGLENAME );
-      items[i++] = msStrdup( MSOGR_LABELFCOLORNAME );
-      items[i++] = msStrdup( MSOGR_LABELBCOLORNAME );
-      items[i++] = msStrdup( MSOGR_LABELPLACEMENTNAME );
-      items[i++] = msStrdup( MSOGR_LABELANCHORNAME );
-      items[i++] = msStrdup( MSOGR_LABELDXNAME );
-      items[i++] = msStrdup( MSOGR_LABELDYNAME );
-      items[i++] = msStrdup( MSOGR_LABELPERPNAME );
-      items[i++] = msStrdup( MSOGR_LABELBOLDNAME );
-      items[i++] = msStrdup( MSOGR_LABELITALICNAME );
-      items[i++] = msStrdup( MSOGR_LABELUNDERLINENAME );
-      items[i++] = msStrdup( MSOGR_LABELPRIORITYNAME );
-      items[i++] = msStrdup( MSOGR_LABELSTRIKEOUTNAME );
-      items[i++] = msStrdup( MSOGR_LABELSTRETCHNAME );
-      items[i++] = msStrdup( MSOGR_LABELADJHORNAME );
-      items[i++] = msStrdup( MSOGR_LABELADJVERTNAME );
-      items[i++] = msStrdup( MSOGR_LABELHCOLORNAME );
-      items[i++] = msStrdup( MSOGR_LABELOCOLORNAME );
+  for(i=0; i<numitems; i++) {
+    OGRFieldDefnH hField = OGR_FD_GetFieldDefn( hDefn, i );
+    items[i] = msStrdup( OGR_Fld_GetNameRef( hField ));
+  }
+
+  if (getShapeStyleItems && EQUAL(getShapeStyleItems, "all")) {
+    assert(numStyleItems == 21);
+    items[i++] = msStrdup( MSOGR_LABELFONTNAMENAME );
+    items[i++] = msStrdup( MSOGR_LABELSIZENAME );
+    items[i++] = msStrdup( MSOGR_LABELTEXTNAME );
+    items[i++] = msStrdup( MSOGR_LABELANGLENAME );
+    items[i++] = msStrdup( MSOGR_LABELFCOLORNAME );
+    items[i++] = msStrdup( MSOGR_LABELBCOLORNAME );
+    items[i++] = msStrdup( MSOGR_LABELPLACEMENTNAME );
+    items[i++] = msStrdup( MSOGR_LABELANCHORNAME );
+    items[i++] = msStrdup( MSOGR_LABELDXNAME );
+    items[i++] = msStrdup( MSOGR_LABELDYNAME );
+    items[i++] = msStrdup( MSOGR_LABELPERPNAME );
+    items[i++] = msStrdup( MSOGR_LABELBOLDNAME );
+    items[i++] = msStrdup( MSOGR_LABELITALICNAME );
+    items[i++] = msStrdup( MSOGR_LABELUNDERLINENAME );
+    items[i++] = msStrdup( MSOGR_LABELPRIORITYNAME );
+    items[i++] = msStrdup( MSOGR_LABELSTRIKEOUTNAME );
+    items[i++] = msStrdup( MSOGR_LABELSTRETCHNAME );
+    items[i++] = msStrdup( MSOGR_LABELADJHORNAME );
+    items[i++] = msStrdup( MSOGR_LABELADJVERTNAME );
+    items[i++] = msStrdup( MSOGR_LABELHCOLORNAME );
+    items[i++] = msStrdup( MSOGR_LABELOCOLORNAME );
   }
   items[i++] = NULL;
 
-/* -------------------------------------------------------------------- */
-/*      consider populating the field definitions in metadata.          */
-/* -------------------------------------------------------------------- */
+  /* -------------------------------------------------------------------- */
+  /*      consider populating the field definitions in metadata.          */
+  /* -------------------------------------------------------------------- */
   if((value = msOWSLookupMetadata(&(layer->metadata), "G", "types")) != NULL
-     && strcasecmp(value,"auto") == 0 )
-      msOGRPassThroughFieldDefinitions( layer, psInfo );
+      && strcasecmp(value,"auto") == 0 )
+    msOGRPassThroughFieldDefinitions( layer, psInfo );
 
   return items;
 }
@@ -1821,97 +1459,85 @@ static char **msOGRFileGetItems(layerObj *layer, msOGRFileInfo *psInfo )
  *
  * Returns MS_SUCCESS/MS_FAILURE
  **********************************************************************/
-static int 
+static int
 msOGRFileNextShape(layerObj *layer, shapeObj *shape,
-                   msOGRFileInfo *psInfo ) 
+                   msOGRFileInfo *psInfo )
 {
   OGRFeatureH hFeature = NULL;
 
-  if (psInfo == NULL || psInfo->hLayer == NULL)
-  {
-    msSetError(MS_MISCERR, "Assertion failed: OGR layer not opened!!!", 
+  if (psInfo == NULL || psInfo->hLayer == NULL) {
+    msSetError(MS_MISCERR, "Assertion failed: OGR layer not opened!!!",
                "msOGRFileNextShape()");
     return(MS_FAILURE);
   }
 
-/* ------------------------------------------------------------------
- * Read until we find a feature that matches attribute filter and 
- * whose geometry is compatible with current layer type.
- * ------------------------------------------------------------------ */
+  /* ------------------------------------------------------------------
+   * Read until we find a feature that matches attribute filter and
+   * whose geometry is compatible with current layer type.
+   * ------------------------------------------------------------------ */
   msFreeShape(shape);
   shape->type = MS_SHAPE_NULL;
 
   ACQUIRE_OGR_LOCK;
-  while (shape->type == MS_SHAPE_NULL)
-  {
-      if( hFeature )
-          OGR_F_Destroy( hFeature );
-
-      if( (hFeature = OGR_L_GetNextFeature( psInfo->hLayer )) == NULL )
-      {
-          psInfo->last_record_index_read = -1;
-          if( CPLGetLastErrorType() == CE_Failure )
-          {
-              msSetError(MS_OGRERR, "%s", "msOGRFileNextShape()",
-                         CPLGetLastErrorMsg() );
-              RELEASE_OGR_LOCK;
-              return MS_FAILURE;
-          }
-          else
-          {
-              RELEASE_OGR_LOCK;
-              if (layer->debug >= MS_DEBUGLEVEL_VV)
-                  msDebug("msOGRFileNextShape: Returning MS_DONE (no more shapes)\n" );
-              return MS_DONE;  // No more features to read
-          }
+  while (shape->type == MS_SHAPE_NULL) {
+    if( hFeature )
+      OGR_F_Destroy( hFeature );
+
+    if( (hFeature = OGR_L_GetNextFeature( psInfo->hLayer )) == NULL ) {
+      psInfo->last_record_index_read = -1;
+      if( CPLGetLastErrorType() == CE_Failure ) {
+        msSetError(MS_OGRERR, "%s", "msOGRFileNextShape()",
+                   CPLGetLastErrorMsg() );
+        RELEASE_OGR_LOCK;
+        return MS_FAILURE;
+      } else {
+        RELEASE_OGR_LOCK;
+        if (layer->debug >= MS_DEBUGLEVEL_VV)
+          msDebug("msOGRFileNextShape: Returning MS_DONE (no more shapes)\n" );
+        return MS_DONE;  // No more features to read
       }
+    }
 
-      psInfo->last_record_index_read++;
+    psInfo->last_record_index_read++;
 
-      if(layer->numitems > 0) 
-      {
-          shape->values = msOGRGetValues(layer, hFeature);
-          shape->numvalues = layer->numitems;
-          if(!shape->values)
-          {
-              OGR_F_Destroy( hFeature );
-              RELEASE_OGR_LOCK;
-              return(MS_FAILURE);
-          }
+    if(layer->numitems > 0) {
+      shape->values = msOGRGetValues(layer, hFeature);
+      shape->numvalues = layer->numitems;
+      if(!shape->values) {
+        OGR_F_Destroy( hFeature );
+        RELEASE_OGR_LOCK;
+        return(MS_FAILURE);
       }
+    }
 
-      // Check the expression unless it is a WHERE clause already 
-      // handled by OGR. 
-      if( (layer->filter.string && EQUALN(layer->filter.string,"WHERE ",6))
-          || msEvalExpression(layer, shape, &(layer->filter), layer->filteritemindex) == MS_TRUE )
-      {
-          // Feature matched filter expression... process geometry
-          // shape->type will be set if geom is compatible with layer type
-          if (ogrConvertGeometry(OGR_F_GetGeometryRef( hFeature ), shape,
-                                 layer->type) == MS_SUCCESS)
-          {
-              if (shape->type != MS_SHAPE_NULL)
-                  break; // Shape is ready to be returned!
-
-              if (layer->debug >= MS_DEBUGLEVEL_VVV)
-                  msDebug("msOGRFileNextShape: Rejecting feature (shapeid = %d, tileid=%d) of incompatible type for this layer (feature wkbType %d, layer type %d)\n",
-                          OGR_F_GetFID( hFeature ), psInfo->nTileId, 
-                          OGR_F_GetGeometryRef( hFeature )==NULL ? wkbFlatten(wkbUnknown):wkbFlatten( OGR_G_GetGeometryType( OGR_F_GetGeometryRef( hFeature ) ) ), 
-                          layer->type);
+    // Check the expression unless it is a WHERE clause already
+    // handled by OGR.
+    if( (layer->filter.string && EQUALN(layer->filter.string,"WHERE ",6))
+        || msEvalExpression(layer, shape, &(layer->filter), layer->filteritemindex) == MS_TRUE ) {
+      // Feature matched filter expression... process geometry
+      // shape->type will be set if geom is compatible with layer type
+      if (ogrConvertGeometry(OGR_F_GetGeometryRef( hFeature ), shape,
+                             layer->type) == MS_SUCCESS) {
+        if (shape->type != MS_SHAPE_NULL)
+          break; // Shape is ready to be returned!
 
-          }
-          else
-          {
-              msFreeShape(shape);
-              OGR_F_Destroy( hFeature );
-              RELEASE_OGR_LOCK;
-              return MS_FAILURE; // Error message already produced.
-          }
+        if (layer->debug >= MS_DEBUGLEVEL_VVV)
+          msDebug("msOGRFileNextShape: Rejecting feature (shapeid = %d, tileid=%d) of incompatible type for this layer (feature wkbType %d, layer type %d)\n",
+                  OGR_F_GetFID( hFeature ), psInfo->nTileId,
+                  OGR_F_GetGeometryRef( hFeature )==NULL ? wkbFlatten(wkbUnknown):wkbFlatten( OGR_G_GetGeometryType( OGR_F_GetGeometryRef( hFeature ) ) ),
+                  layer->type);
+
+      } else {
+        msFreeShape(shape);
+        OGR_F_Destroy( hFeature );
+        RELEASE_OGR_LOCK;
+        return MS_FAILURE; // Error message already produced.
       }
+    }
 
-      // Feature rejected... free shape to clear attributes values.
-      msFreeShape(shape);
-      shape->type = MS_SHAPE_NULL;
+    // Feature rejected... free shape to clear attributes values.
+    msFreeShape(shape);
+    shape->type = MS_SHAPE_NULL;
   }
 
   shape->index =  OGR_F_GetFID( hFeature );;
@@ -1919,12 +1545,12 @@ msOGRFileNextShape(layerObj *layer, shapeObj *shape,
   shape->tileindex = psInfo->nTileId;
 
   if (layer->debug >= MS_DEBUGLEVEL_VVV)
-      msDebug("msOGRFileNextShape: Returning shape=%d, tile=%d\n",
-              shape->index, shape->tileindex );
+    msDebug("msOGRFileNextShape: Returning shape=%d, tile=%d\n",
+            shape->index, shape->tileindex );
 
   // Keep ref. to last feature read in case we need style info.
   if (psInfo->hLastFeature)
-      OGR_F_Destroy( psInfo->hLastFeature );
+    OGR_F_Destroy( psInfo->hLastFeature );
   psInfo->hLastFeature = hFeature;
 
   RELEASE_OGR_LOCK;
@@ -1939,120 +1565,105 @@ msOGRFileNextShape(layerObj *layer, shapeObj *shape,
  *
  * Returns MS_SUCCESS/MS_FAILURE
  **********************************************************************/
-static int 
+static int
 msOGRFileGetShape(layerObj *layer, shapeObj *shape, long record,
                   msOGRFileInfo *psInfo, int record_is_fid )
 {
   OGRFeatureH hFeature;
 
-  if (psInfo == NULL || psInfo->hLayer == NULL)
-  {
-    msSetError(MS_MISCERR, "Assertion failed: OGR layer not opened!!!", 
+  if (psInfo == NULL || psInfo->hLayer == NULL) {
+    msSetError(MS_MISCERR, "Assertion failed: OGR layer not opened!!!",
                "msOGRFileNextShape()");
     return(MS_FAILURE);
   }
 
-/* -------------------------------------------------------------------- */
-/*      Clear previously loaded shape.                                  */
-/* -------------------------------------------------------------------- */
+  /* -------------------------------------------------------------------- */
+  /*      Clear previously loaded shape.                                  */
+  /* -------------------------------------------------------------------- */
   msFreeShape(shape);
   shape->type = MS_SHAPE_NULL;
 
-/* -------------------------------------------------------------------- */
-/*      Support reading feature by fid.                                 */
-/* -------------------------------------------------------------------- */
-  if( record_is_fid )
-  {
-      ACQUIRE_OGR_LOCK;
-      if( (hFeature = OGR_L_GetFeature( psInfo->hLayer, record )) == NULL )
-      {
-          RELEASE_OGR_LOCK;
-          return MS_FAILURE;
-      }
+  /* -------------------------------------------------------------------- */
+  /*      Support reading feature by fid.                                 */
+  /* -------------------------------------------------------------------- */
+  if( record_is_fid ) {
+    ACQUIRE_OGR_LOCK;
+    if( (hFeature = OGR_L_GetFeature( psInfo->hLayer, record )) == NULL ) {
+      RELEASE_OGR_LOCK;
+      return MS_FAILURE;
+    }
   }
 
-/* -------------------------------------------------------------------- */
-/*      Support reading shape by offset within the current              */
-/*      resultset.                                                      */
-/* -------------------------------------------------------------------- */
-  else if( !record_is_fid )
-  {
-      ACQUIRE_OGR_LOCK;
-      if( record <= psInfo->last_record_index_read 
-          || psInfo->last_record_index_read == -1 )
-      {
-          OGR_L_ResetReading( psInfo->hLayer );
-          psInfo->last_record_index_read = -1;
-      }
+  /* -------------------------------------------------------------------- */
+  /*      Support reading shape by offset within the current              */
+  /*      resultset.                                                      */
+  /* -------------------------------------------------------------------- */
+  else if( !record_is_fid ) {
+    ACQUIRE_OGR_LOCK;
+    if( record <= psInfo->last_record_index_read
+        || psInfo->last_record_index_read == -1 ) {
+      OGR_L_ResetReading( psInfo->hLayer );
+      psInfo->last_record_index_read = -1;
+    }
 
-      hFeature = NULL;
-      while( psInfo->last_record_index_read < record )
-      {
-          if( hFeature != NULL )
-          {
-              OGR_F_Destroy( hFeature );
-              hFeature = NULL;
-          }
-          if( (hFeature = OGR_L_GetNextFeature( psInfo->hLayer )) == NULL )
-          {
-              RELEASE_OGR_LOCK;
-              return MS_FAILURE;
-          }
-          psInfo->last_record_index_read++;
+    hFeature = NULL;
+    while( psInfo->last_record_index_read < record ) {
+      if( hFeature != NULL ) {
+        OGR_F_Destroy( hFeature );
+        hFeature = NULL;
+      }
+      if( (hFeature = OGR_L_GetNextFeature( psInfo->hLayer )) == NULL ) {
+        RELEASE_OGR_LOCK;
+        return MS_FAILURE;
       }
+      psInfo->last_record_index_read++;
+    }
   }
 
-/* ------------------------------------------------------------------
- * Handle shape geometry... 
- * ------------------------------------------------------------------ */
+  /* ------------------------------------------------------------------
+   * Handle shape geometry...
+   * ------------------------------------------------------------------ */
   // shape->type will be set if geom is compatible with layer type
   if (ogrConvertGeometry(OGR_F_GetGeometryRef( hFeature ), shape,
-                         layer->type) != MS_SUCCESS)
-  {
-      RELEASE_OGR_LOCK;
-      return MS_FAILURE; // Error message already produced.
-  }
-  
-  if (shape->type == MS_SHAPE_NULL)
-  {
-      msSetError(MS_OGRERR, 
-                 "Requested feature is incompatible with layer type",
-                 "msOGRLayerGetShape()");
-      RELEASE_OGR_LOCK;
-      return MS_FAILURE;
+                         layer->type) != MS_SUCCESS) {
+    RELEASE_OGR_LOCK;
+    return MS_FAILURE; // Error message already produced.
   }
 
-/* ------------------------------------------------------------------
- * Process shape attributes
- * ------------------------------------------------------------------ */
-  if(layer->numitems > 0) 
-  {
-      shape->values = msOGRGetValues(layer, hFeature);
-      shape->numvalues = layer->numitems;
-      if(!shape->values)
-      {
-          RELEASE_OGR_LOCK;
-          return(MS_FAILURE);
-      }
+  if (shape->type == MS_SHAPE_NULL) {
+    msSetError(MS_OGRERR,
+               "Requested feature is incompatible with layer type",
+               "msOGRLayerGetShape()");
+    RELEASE_OGR_LOCK;
+    return MS_FAILURE;
+  }
 
-  }   
+  /* ------------------------------------------------------------------
+   * Process shape attributes
+   * ------------------------------------------------------------------ */
+  if(layer->numitems > 0) {
+    shape->values = msOGRGetValues(layer, hFeature);
+    shape->numvalues = layer->numitems;
+    if(!shape->values) {
+      RELEASE_OGR_LOCK;
+      return(MS_FAILURE);
+    }
 
-  if (record_is_fid)
-  {
-      shape->index = record;
-      shape->resultindex = -1;
   }
-  else
-  {
-      shape->index = OGR_F_GetFID( hFeature );
-      shape->resultindex = record;
+
+  if (record_is_fid) {
+    shape->index = record;
+    shape->resultindex = -1;
+  } else {
+    shape->index = OGR_F_GetFID( hFeature );
+    shape->resultindex = record;
   }
 
   shape->tileindex = psInfo->nTileId;
 
   // Keep ref. to last feature read in case we need style info.
   if (psInfo->hLastFeature)
-      OGR_F_Destroy( psInfo->hLastFeature );
+    OGR_F_Destroy( psInfo->hLastFeature );
   psInfo->hLastFeature = hFeature;
 
   RELEASE_OGR_LOCK;
@@ -2072,105 +1683,101 @@ msOGRFileGetShape(layerObj *layer, shapeObj *shape, long record,
 /*      the current rectangle.                                          */
 /************************************************************************/
 
-int msOGRFileReadTile( layerObj *layer, msOGRFileInfo *psInfo, 
+int msOGRFileReadTile( layerObj *layer, msOGRFileInfo *psInfo,
                        int targetTile = -1 )
 
 {
-    int nFeatureId;
+  int nFeatureId;
 
-/* -------------------------------------------------------------------- */
-/*      Close old tile if one is open.                                  */
-/* -------------------------------------------------------------------- */
-    if( psInfo->poCurTile != NULL )
-    {
-        msOGRFileClose( layer, psInfo->poCurTile );
-        psInfo->poCurTile = NULL;
-    }
+  /* -------------------------------------------------------------------- */
+  /*      Close old tile if one is open.                                  */
+  /* -------------------------------------------------------------------- */
+  if( psInfo->poCurTile != NULL ) {
+    msOGRFileClose( layer, psInfo->poCurTile );
+    psInfo->poCurTile = NULL;
+  }
 
-/* -------------------------------------------------------------------- */
-/*      If -2 is passed, then seek reset reading of the tileindex.      */
-/*      We want to start from the beginning even if this file is        */
-/*      shared between layers or renders.                               */
-/* -------------------------------------------------------------------- */
-    ACQUIRE_OGR_LOCK;
-    if( targetTile == -2 )
-    {
-        OGR_L_ResetReading( psInfo->hLayer );
-    }
-        
-/* -------------------------------------------------------------------- */
-/*      Get the name (connection string really) of the next tile.       */
-/* -------------------------------------------------------------------- */
-    OGRFeatureH hFeature;
-    char       *connection = NULL;
-    msOGRFileInfo *psTileInfo = NULL;
-    int status;
+  /* -------------------------------------------------------------------- */
+  /*      If -2 is passed, then seek reset reading of the tileindex.      */
+  /*      We want to start from the beginning even if this file is        */
+  /*      shared between layers or renders.                               */
+  /* -------------------------------------------------------------------- */
+  ACQUIRE_OGR_LOCK;
+  if( targetTile == -2 ) {
+    OGR_L_ResetReading( psInfo->hLayer );
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Get the name (connection string really) of the next tile.       */
+  /* -------------------------------------------------------------------- */
+  OGRFeatureH hFeature;
+  char       *connection = NULL;
+  msOGRFileInfo *psTileInfo = NULL;
+  int status;
 
 #ifndef IGNORE_MISSING_DATA
-  NextFile:
+NextFile:
 #endif
 
-    if( targetTile < 0 )
-        hFeature = OGR_L_GetNextFeature( psInfo->hLayer );
-    
+  if( targetTile < 0 )
+    hFeature = OGR_L_GetNextFeature( psInfo->hLayer );
+
+  else
+    hFeature = OGR_L_GetFeature( psInfo->hLayer, targetTile );
+
+  if( hFeature == NULL ) {
+    RELEASE_OGR_LOCK;
+    if( targetTile == -1 )
+      return MS_DONE;
     else
-        hFeature = OGR_L_GetFeature( psInfo->hLayer, targetTile );
+      return MS_FAILURE;
 
-    if( hFeature == NULL )
-    {
-        RELEASE_OGR_LOCK;
-        if( targetTile == -1 )
-            return MS_DONE;
-        else
-            return MS_FAILURE;
-        
-    }
+  }
 
-    connection = msStrdup( OGR_F_GetFieldAsString( hFeature, 
-                                                 layer->tileitemindex ));
-    
-    nFeatureId = OGR_F_GetFID( hFeature );
+  connection = msStrdup( OGR_F_GetFieldAsString( hFeature,
+                         layer->tileitemindex ));
 
-    OGR_F_Destroy( hFeature );
-                        
-    RELEASE_OGR_LOCK;
+  nFeatureId = OGR_F_GetFID( hFeature );
+
+  OGR_F_Destroy( hFeature );
 
-/* -------------------------------------------------------------------- */
-/*      Open the new tile file.                                         */
-/* -------------------------------------------------------------------- */
-    psTileInfo = msOGRFileOpen( layer, connection );
+  RELEASE_OGR_LOCK;
+
+  /* -------------------------------------------------------------------- */
+  /*      Open the new tile file.                                         */
+  /* -------------------------------------------------------------------- */
+  psTileInfo = msOGRFileOpen( layer, connection );
 
-    free( connection );
+  free( connection );
 
 #ifndef IGNORE_MISSING_DATA
-    if( psTileInfo == NULL && targetTile == -1 )
-        goto NextFile;
+  if( psTileInfo == NULL && targetTile == -1 )
+    goto NextFile;
 #endif
 
-    if( psTileInfo == NULL )
-        return MS_FAILURE;
+  if( psTileInfo == NULL )
+    return MS_FAILURE;
 
-    psTileInfo->nTileId = nFeatureId;
+  psTileInfo->nTileId = nFeatureId;
 
-/* -------------------------------------------------------------------- */
-/*      Initialize the spatial query on this file.                      */
-/* -------------------------------------------------------------------- */
-    if( psInfo->rect.minx != 0 || psInfo->rect.maxx != 0 )
-    {
-        status = msOGRFileWhichShapes( layer, psInfo->rect, psTileInfo );
-        if( status != MS_SUCCESS )
-            return status;
-    }
-    
-    psInfo->poCurTile = psTileInfo;
-    
-/* -------------------------------------------------------------------- */
-/*      Update the iteminfo in case this layer has a different field    */
-/*      list.                                                           */
-/* -------------------------------------------------------------------- */
-    msOGRLayerInitItemInfo( layer );
+  /* -------------------------------------------------------------------- */
+  /*      Initialize the spatial query on this file.                      */
+  /* -------------------------------------------------------------------- */
+  if( psInfo->rect.minx != 0 || psInfo->rect.maxx != 0 ) {
+    status = msOGRFileWhichShapes( layer, psInfo->rect, psTileInfo );
+    if( status != MS_SUCCESS )
+      return status;
+  }
 
-    return MS_SUCCESS;
+  psInfo->poCurTile = psTileInfo;
+
+  /* -------------------------------------------------------------------- */
+  /*      Update the iteminfo in case this layer has a different field    */
+  /*      list.                                                           */
+  /* -------------------------------------------------------------------- */
+  msOGRLayerInitItemInfo( layer );
+
+  return MS_SUCCESS;
 }
 
 #endif /* def USE_OGR */
@@ -2198,107 +1805,101 @@ int msOGRFileReadTile( layerObj *layer, msOGRFileInfo *psInfo,
  *
  * Returns MS_SUCCESS/MS_FAILURE
  **********************************************************************/
-int msOGRLayerOpen(layerObj *layer, const char *pszOverrideConnection) 
+int msOGRLayerOpen(layerObj *layer, const char *pszOverrideConnection)
 {
 #ifdef USE_OGR
 
   msOGRFileInfo *psInfo;
 
-  if (layer->layerinfo != NULL)
-  {
-      return MS_SUCCESS;  // Nothing to do... layer is already opened
+  if (layer->layerinfo != NULL) {
+    return MS_SUCCESS;  // Nothing to do... layer is already opened
   }
 
-/* -------------------------------------------------------------------- */
-/*      If this is not a tiled layer, just directly open the target.    */
-/* -------------------------------------------------------------------- */
-  if( layer->tileindex == NULL )
-  {
-      psInfo = msOGRFileOpen( layer, 
-                              (pszOverrideConnection ? pszOverrideConnection:
-                                                       layer->connection) );
-      layer->layerinfo = psInfo;
-      layer->tileitemindex = -1;
-      
-      if( layer->layerinfo == NULL )
-          return MS_FAILURE;
+  /* -------------------------------------------------------------------- */
+  /*      If this is not a tiled layer, just directly open the target.    */
+  /* -------------------------------------------------------------------- */
+  if( layer->tileindex == NULL ) {
+    psInfo = msOGRFileOpen( layer,
+                            (pszOverrideConnection ? pszOverrideConnection:
+                             layer->connection) );
+    layer->layerinfo = psInfo;
+    layer->tileitemindex = -1;
+
+    if( layer->layerinfo == NULL )
+      return MS_FAILURE;
   }
 
-/* -------------------------------------------------------------------- */
-/*      Otherwise we open the tile index, identify the tile item        */
-/*      index and try to select the first file matching our query       */
-/*      region.                                                         */
-/* -------------------------------------------------------------------- */
-  else
-  {
-      // Open tile index
+  /* -------------------------------------------------------------------- */
+  /*      Otherwise we open the tile index, identify the tile item        */
+  /*      index and try to select the first file matching our query       */
+  /*      region.                                                         */
+  /* -------------------------------------------------------------------- */
+  else {
+    // Open tile index
 
-      psInfo = msOGRFileOpen( layer, layer->tileindex );
-      layer->layerinfo = psInfo;
-      
-      if( layer->layerinfo == NULL )
-          return MS_FAILURE;
+    psInfo = msOGRFileOpen( layer, layer->tileindex );
+    layer->layerinfo = psInfo;
 
-      // Identify TILEITEM
-
-      OGRFeatureDefnH hDefn = OGR_L_GetLayerDefn( psInfo->hLayer );
-      for( layer->tileitemindex = 0; 
-           layer->tileitemindex < OGR_FD_GetFieldCount( hDefn )
-           && !EQUAL( OGR_Fld_GetNameRef( OGR_FD_GetFieldDefn( hDefn, layer->tileitemindex) ),
-                      layer->tileitem); 
-           layer->tileitemindex++ ) {}
-
-      if( layer->tileitemindex == OGR_FD_GetFieldCount( hDefn ) )
-      {
-          msSetError(MS_OGRERR, 
-                     "Can't identify TILEITEM %s field in TILEINDEX `%s'.",
-                     "msOGRLayerOpen()", 
-                     layer->tileitem, layer->tileindex );
-          msOGRFileClose( layer, psInfo );
-          layer->layerinfo = NULL;
-          return MS_FAILURE;
-      }
+    if( layer->layerinfo == NULL )
+      return MS_FAILURE;
+
+    // Identify TILEITEM
+
+    OGRFeatureDefnH hDefn = OGR_L_GetLayerDefn( psInfo->hLayer );
+    for( layer->tileitemindex = 0;
+         layer->tileitemindex < OGR_FD_GetFieldCount( hDefn )
+         && !EQUAL( OGR_Fld_GetNameRef( OGR_FD_GetFieldDefn( hDefn, layer->tileitemindex) ),
+                    layer->tileitem);
+         layer->tileitemindex++ ) {}
+
+    if( layer->tileitemindex == OGR_FD_GetFieldCount( hDefn ) ) {
+      msSetError(MS_OGRERR,
+                 "Can't identify TILEITEM %s field in TILEINDEX `%s'.",
+                 "msOGRLayerOpen()",
+                 layer->tileitem, layer->tileindex );
+      msOGRFileClose( layer, psInfo );
+      layer->layerinfo = NULL;
+      return MS_FAILURE;
+    }
   }
 
-/* ------------------------------------------------------------------
- * If projection was "auto" then set proj to the dataset's projection.
- * For a tile index, it is assume the tile index has the projection.
- * ------------------------------------------------------------------ */
+  /* ------------------------------------------------------------------
+   * If projection was "auto" then set proj to the dataset's projection.
+   * For a tile index, it is assume the tile index has the projection.
+   * ------------------------------------------------------------------ */
 #ifdef USE_PROJ
-  if (layer->projection.numargs > 0 && 
-      EQUAL(layer->projection.args[0], "auto"))
-  {
-      ACQUIRE_OGR_LOCK;
-      OGRSpatialReferenceH hSRS = OGR_L_GetSpatialRef( psInfo->hLayer );
-
-      if (msOGRSpatialRef2ProjectionObj(hSRS,
-                                        &(layer->projection),
-                                        layer->debug ) != MS_SUCCESS)
-      {
-          errorObj *ms_error = msGetErrorObj();
-
-          RELEASE_OGR_LOCK;
-          msSetError(MS_OGRERR, 
-                     "%s  "
-                     "PROJECTION AUTO cannot be used for this "
-                     "OGR connection (in layer `%s').",
-                     "msOGRLayerOpen()",
-                     ms_error->message, 
-                     layer->name?layer->name:"(null)" );
-          msOGRFileClose( layer, psInfo );
-          layer->layerinfo = NULL;
-          return(MS_FAILURE);
-      }
+  if (layer->projection.numargs > 0 &&
+      EQUAL(layer->projection.args[0], "auto")) {
+    ACQUIRE_OGR_LOCK;
+    OGRSpatialReferenceH hSRS = OGR_L_GetSpatialRef( psInfo->hLayer );
+
+    if (msOGRSpatialRef2ProjectionObj(hSRS,
+                                      &(layer->projection),
+                                      layer->debug ) != MS_SUCCESS) {
+      errorObj *ms_error = msGetErrorObj();
+
       RELEASE_OGR_LOCK;
+      msSetError(MS_OGRERR,
+                 "%s  "
+                 "PROJECTION AUTO cannot be used for this "
+                 "OGR connection (in layer `%s').",
+                 "msOGRLayerOpen()",
+                 ms_error->message,
+                 layer->name?layer->name:"(null)" );
+      msOGRFileClose( layer, psInfo );
+      layer->layerinfo = NULL;
+      return(MS_FAILURE);
+    }
+    RELEASE_OGR_LOCK;
   }
 #endif
 
   return MS_SUCCESS;
 
 #else
-/* ------------------------------------------------------------------
- * OGR Support not included...
- * ------------------------------------------------------------------ */
+  /* ------------------------------------------------------------------
+   * OGR Support not included...
+   * ------------------------------------------------------------------ */
 
   msSetError(MS_MISCERR, "OGR support is not available.", "msOGRLayerOpen()");
   return(MS_FAILURE);
@@ -2311,34 +1912,33 @@ int msOGRLayerOpen(layerObj *layer, const char *pszOverrideConnection)
  *
  * Overloaded version of msOGRLayerOpen for virtual table architecture
  **********************************************************************/
-static int msOGRLayerOpenVT(layerObj *layer) 
+static int msOGRLayerOpenVT(layerObj *layer)
 {
-    return msOGRLayerOpen(layer, NULL);
+  return msOGRLayerOpen(layer, NULL);
 }
 
 /**********************************************************************
  *                     msOGRLayerClose()
  **********************************************************************/
-int msOGRLayerClose(layerObj *layer) 
+int msOGRLayerClose(layerObj *layer)
 {
 #ifdef USE_OGR
   msOGRFileInfo *psInfo =(msOGRFileInfo*)layer->layerinfo;
 
-  if (psInfo)
-  {
-      if( layer->debug )
-          msDebug("msOGRLayerClose(%s).\n", layer->connection);
+  if (psInfo) {
+    if( layer->debug )
+      msDebug("msOGRLayerClose(%s).\n", layer->connection);
 
-      msOGRFileClose( layer, psInfo );
-      layer->layerinfo = NULL;
+    msOGRFileClose( layer, psInfo );
+    layer->layerinfo = NULL;
   }
 
   return MS_SUCCESS;
 
 #else
-/* ------------------------------------------------------------------
- * OGR Support not included...
- * ------------------------------------------------------------------ */
+  /* ------------------------------------------------------------------
+   * OGR Support not included...
+   * ------------------------------------------------------------------ */
 
   msSetError(MS_MISCERR, "OGR support is not available.", "msOGRLayerClose()");
   return(MS_FAILURE);
@@ -2349,18 +1949,18 @@ int msOGRLayerClose(layerObj *layer)
 /**********************************************************************
  *                     msOGRLayerIsOpen()
  **********************************************************************/
-static int msOGRLayerIsOpen(layerObj *layer) 
+static int msOGRLayerIsOpen(layerObj *layer)
 {
 #ifdef USE_OGR
   if (layer->layerinfo)
-      return MS_TRUE;
+    return MS_TRUE;
 
   return MS_FALSE;
 
 #else
-/* ------------------------------------------------------------------
- * OGR Support not included...
- * ------------------------------------------------------------------ */
+  /* ------------------------------------------------------------------
+   * OGR Support not included...
+   * ------------------------------------------------------------------ */
 
   msSetError(MS_MISCERR, "OGR support is not available.", "msOGRLayerIsOpen()");
   return(MS_FALSE);
@@ -2376,15 +1976,14 @@ static int msOGRLayerIsOpen(layerObj *layer)
  * Returns MS_SUCCESS/MS_FAILURE, or MS_DONE if no shape matching the
  * layer's FILTER overlaps the selected region.
  **********************************************************************/
-int msOGRLayerWhichShapes(layerObj *layer, rectObj rect, int isQuery) 
+int msOGRLayerWhichShapes(layerObj *layer, rectObj rect, int isQuery)
 {
 #ifdef USE_OGR
   msOGRFileInfo *psInfo =(msOGRFileInfo*)layer->layerinfo;
   int   status;
 
-  if (psInfo == NULL || psInfo->hLayer == NULL)
-  {
-    msSetError(MS_MISCERR, "Assertion failed: OGR layer not opened!!!", 
+  if (psInfo == NULL || psInfo->hLayer == NULL) {
+    msSetError(MS_MISCERR, "Assertion failed: OGR layer not opened!!!",
                "msOGRLayerWhichShapes()");
     return(MS_FAILURE);
   }
@@ -2392,19 +1991,19 @@ int msOGRLayerWhichShapes(layerObj *layer, rectObj rect, int isQuery)
   status = msOGRFileWhichShapes( layer, rect, psInfo );
 
   if( status != MS_SUCCESS || layer->tileindex == NULL )
-      return status;
+    return status;
 
   // If we are using a tile index, we need to advance to the first
-  // tile matching the spatial query, and load it. 
+  // tile matching the spatial query, and load it.
 
   return msOGRFileReadTile( layer, psInfo );
 
 #else
-/* ------------------------------------------------------------------
- * OGR Support not included...
- * ------------------------------------------------------------------ */
+  /* ------------------------------------------------------------------
+   * OGR Support not included...
+   * ------------------------------------------------------------------ */
 
-  msSetError(MS_MISCERR, "OGR support is not available.", 
+  msSetError(MS_MISCERR, "OGR support is not available.",
              "msOGRLayerWhichShapes()");
   return(MS_FAILURE);
 
@@ -2416,45 +2015,43 @@ int msOGRLayerWhichShapes(layerObj *layer, rectObj rect, int isQuery)
  *
  * Load item (i.e. field) names in a char array.  If we are working
  * with a tiled layer, ensure a tile is loaded and use it for the items.
- * It is implicitly assumed that the schemas will match on all tiles. 
+ * It is implicitly assumed that the schemas will match on all tiles.
  **********************************************************************/
 int msOGRLayerGetItems(layerObj *layer)
 {
 #ifdef USE_OGR
   msOGRFileInfo *psInfo =(msOGRFileInfo*)layer->layerinfo;
-  
-  if (psInfo == NULL || psInfo->hLayer == NULL)
-  {
-    msSetError(MS_MISCERR, "Assertion failed: OGR layer not opened!!!", 
+
+  if (psInfo == NULL || psInfo->hLayer == NULL) {
+    msSetError(MS_MISCERR, "Assertion failed: OGR layer not opened!!!",
                "msOGRLayerGetItems()");
     return(MS_FAILURE);
   }
 
-  if( layer->tileindex != NULL )
-  {
-      if( psInfo->poCurTile == NULL 
-          && msOGRFileReadTile( layer, psInfo ) != MS_SUCCESS )
-          return MS_FAILURE;
-      
-      psInfo = psInfo->poCurTile;
+  if( layer->tileindex != NULL ) {
+    if( psInfo->poCurTile == NULL
+        && msOGRFileReadTile( layer, psInfo ) != MS_SUCCESS )
+      return MS_FAILURE;
+
+    psInfo = psInfo->poCurTile;
   }
 
   layer->numitems = 0;
   layer->items = msOGRFileGetItems(layer, psInfo);
   if( layer->items == NULL )
-      return MS_FAILURE;
+    return MS_FAILURE;
 
   while( layer->items[layer->numitems] != NULL )
-      layer->numitems++;
+    layer->numitems++;
 
   return msOGRLayerInitItemInfo(layer);
 
 #else
-/* ------------------------------------------------------------------
- * OGR Support not included...
- * ------------------------------------------------------------------ */
+  /* ------------------------------------------------------------------
+   * OGR Support not included...
+   * ------------------------------------------------------------------ */
 
-  msSetError(MS_MISCERR, "OGR support is not available.", 
+  msSetError(MS_MISCERR, "OGR support is not available.",
              "msOGRLayerGetItems()");
   return(MS_FAILURE);
 
@@ -2474,109 +2071,101 @@ static int msOGRLayerInitItemInfo(layerObj *layer)
   OGRFeatureDefnH hDefn;
 
   if (layer->numitems == 0)
-      return MS_SUCCESS;
+    return MS_SUCCESS;
 
-  if( layer->tileindex != NULL )
-  {
-      if( psInfo->poCurTile == NULL 
-          && msOGRFileReadTile( layer, psInfo, -2 ) != MS_SUCCESS )
-          return MS_FAILURE;
-      
-      psInfo = psInfo->poCurTile;
+  if( layer->tileindex != NULL ) {
+    if( psInfo->poCurTile == NULL
+        && msOGRFileReadTile( layer, psInfo, -2 ) != MS_SUCCESS )
+      return MS_FAILURE;
+
+    psInfo = psInfo->poCurTile;
   }
 
-  if (psInfo == NULL || psInfo->hLayer == NULL)
-  {
-      msSetError(MS_MISCERR, "Assertion failed: OGR layer not opened!!!", 
-                 "msOGRLayerInitItemInfo()");
-      return(MS_FAILURE);
+  if (psInfo == NULL || psInfo->hLayer == NULL) {
+    msSetError(MS_MISCERR, "Assertion failed: OGR layer not opened!!!",
+               "msOGRLayerInitItemInfo()");
+    return(MS_FAILURE);
   }
 
-  if((hDefn = OGR_L_GetLayerDefn( psInfo->hLayer )) == NULL) 
-  {
-    msSetError(MS_OGRERR, "Layer contains no fields.",  
+  if((hDefn = OGR_L_GetLayerDefn( psInfo->hLayer )) == NULL) {
+    msSetError(MS_OGRERR, "Layer contains no fields.",
                "msOGRLayerInitItemInfo()");
     return(MS_FAILURE);
   }
 
   if (layer->iteminfo)
-      free(layer->iteminfo);
-  if((layer->iteminfo = (int *)malloc(sizeof(int)*layer->numitems))== NULL) 
-  {
+    free(layer->iteminfo);
+  if((layer->iteminfo = (int *)malloc(sizeof(int)*layer->numitems))== NULL) {
     msSetError(MS_MEMERR, NULL, "msOGRLayerInitItemInfo()");
     return(MS_FAILURE);
   }
 
   int *itemindexes = (int*)layer->iteminfo;
-  for(i=0;i<layer->numitems;i++) 
-  {
-      // Special case for handling text string and angle coming from
-      // OGR style strings.  We use special attribute snames.
-      if (EQUAL(layer->items[i], MSOGR_LABELFONTNAMENAME))
-          itemindexes[i] = MSOGR_LABELFONTNAMEINDEX;
-      else if (EQUAL(layer->items[i], MSOGR_LABELSIZENAME))
-          itemindexes[i] = MSOGR_LABELSIZEINDEX;
-      else if (EQUAL(layer->items[i], MSOGR_LABELTEXTNAME))
-          itemindexes[i] = MSOGR_LABELTEXTINDEX;
-      else if (EQUAL(layer->items[i], MSOGR_LABELANGLENAME))
-          itemindexes[i] = MSOGR_LABELANGLEINDEX;
-      else if (EQUAL(layer->items[i], MSOGR_LABELFCOLORNAME))
-          itemindexes[i] = MSOGR_LABELFCOLORINDEX;
-      else if (EQUAL(layer->items[i], MSOGR_LABELBCOLORNAME))
-          itemindexes[i] = MSOGR_LABELBCOLORINDEX;
-      else if (EQUAL(layer->items[i], MSOGR_LABELPLACEMENTNAME))
-          itemindexes[i] = MSOGR_LABELPLACEMENTINDEX;
-      else if (EQUAL(layer->items[i], MSOGR_LABELANCHORNAME))
-          itemindexes[i] = MSOGR_LABELANCHORINDEX;
-      else if (EQUAL(layer->items[i], MSOGR_LABELDXNAME))
-          itemindexes[i] = MSOGR_LABELDXINDEX;
-      else if (EQUAL(layer->items[i], MSOGR_LABELDYNAME))
-          itemindexes[i] = MSOGR_LABELDYINDEX;
-      else if (EQUAL(layer->items[i], MSOGR_LABELPERPNAME))
-          itemindexes[i] = MSOGR_LABELPERPINDEX;
-      else if (EQUAL(layer->items[i], MSOGR_LABELBOLDNAME))
-          itemindexes[i] = MSOGR_LABELBOLDINDEX;
-      else if (EQUAL(layer->items[i], MSOGR_LABELITALICNAME))
-          itemindexes[i] = MSOGR_LABELITALICINDEX;
-      else if (EQUAL(layer->items[i], MSOGR_LABELUNDERLINENAME))
-          itemindexes[i] = MSOGR_LABELUNDERLINEINDEX;
-      else if (EQUAL(layer->items[i], MSOGR_LABELPRIORITYNAME))
-          itemindexes[i] = MSOGR_LABELPRIORITYINDEX;
-#if GDAL_VERSION_NUM >= 1400
-      else if (EQUAL(layer->items[i], MSOGR_LABELSTRIKEOUTNAME))
-          itemindexes[i] = MSOGR_LABELSTRIKEOUTINDEX;
-      else if (EQUAL(layer->items[i], MSOGR_LABELSTRETCHNAME))
-          itemindexes[i] = MSOGR_LABELSTRETCHINDEX;
-      else if (EQUAL(layer->items[i], MSOGR_LABELADJHORNAME))
-          itemindexes[i] = MSOGR_LABELADJHORINDEX;
-      else if (EQUAL(layer->items[i], MSOGR_LABELADJVERTNAME))
-          itemindexes[i] = MSOGR_LABELADJVERTINDEX;
-      else if (EQUAL(layer->items[i], MSOGR_LABELHCOLORNAME))
-          itemindexes[i] = MSOGR_LABELHCOLORINDEX;
-#endif /* GDAL_VERSION_NUM >= 1400 */
+  for(i=0; i<layer->numitems; i++) {
+    // Special case for handling text string and angle coming from
+    // OGR style strings.  We use special attribute snames.
+    if (EQUAL(layer->items[i], MSOGR_LABELFONTNAMENAME))
+      itemindexes[i] = MSOGR_LABELFONTNAMEINDEX;
+    else if (EQUAL(layer->items[i], MSOGR_LABELSIZENAME))
+      itemindexes[i] = MSOGR_LABELSIZEINDEX;
+    else if (EQUAL(layer->items[i], MSOGR_LABELTEXTNAME))
+      itemindexes[i] = MSOGR_LABELTEXTINDEX;
+    else if (EQUAL(layer->items[i], MSOGR_LABELANGLENAME))
+      itemindexes[i] = MSOGR_LABELANGLEINDEX;
+    else if (EQUAL(layer->items[i], MSOGR_LABELFCOLORNAME))
+      itemindexes[i] = MSOGR_LABELFCOLORINDEX;
+    else if (EQUAL(layer->items[i], MSOGR_LABELBCOLORNAME))
+      itemindexes[i] = MSOGR_LABELBCOLORINDEX;
+    else if (EQUAL(layer->items[i], MSOGR_LABELPLACEMENTNAME))
+      itemindexes[i] = MSOGR_LABELPLACEMENTINDEX;
+    else if (EQUAL(layer->items[i], MSOGR_LABELANCHORNAME))
+      itemindexes[i] = MSOGR_LABELANCHORINDEX;
+    else if (EQUAL(layer->items[i], MSOGR_LABELDXNAME))
+      itemindexes[i] = MSOGR_LABELDXINDEX;
+    else if (EQUAL(layer->items[i], MSOGR_LABELDYNAME))
+      itemindexes[i] = MSOGR_LABELDYINDEX;
+    else if (EQUAL(layer->items[i], MSOGR_LABELPERPNAME))
+      itemindexes[i] = MSOGR_LABELPERPINDEX;
+    else if (EQUAL(layer->items[i], MSOGR_LABELBOLDNAME))
+      itemindexes[i] = MSOGR_LABELBOLDINDEX;
+    else if (EQUAL(layer->items[i], MSOGR_LABELITALICNAME))
+      itemindexes[i] = MSOGR_LABELITALICINDEX;
+    else if (EQUAL(layer->items[i], MSOGR_LABELUNDERLINENAME))
+      itemindexes[i] = MSOGR_LABELUNDERLINEINDEX;
+    else if (EQUAL(layer->items[i], MSOGR_LABELPRIORITYNAME))
+      itemindexes[i] = MSOGR_LABELPRIORITYINDEX;
+    else if (EQUAL(layer->items[i], MSOGR_LABELSTRIKEOUTNAME))
+      itemindexes[i] = MSOGR_LABELSTRIKEOUTINDEX;
+    else if (EQUAL(layer->items[i], MSOGR_LABELSTRETCHNAME))
+      itemindexes[i] = MSOGR_LABELSTRETCHINDEX;
+    else if (EQUAL(layer->items[i], MSOGR_LABELADJHORNAME))
+      itemindexes[i] = MSOGR_LABELADJHORINDEX;
+    else if (EQUAL(layer->items[i], MSOGR_LABELADJVERTNAME))
+      itemindexes[i] = MSOGR_LABELADJVERTINDEX;
+    else if (EQUAL(layer->items[i], MSOGR_LABELHCOLORNAME))
+      itemindexes[i] = MSOGR_LABELHCOLORINDEX;
 #if GDAL_VERSION_NUM >= 1600
-      else if (EQUAL(layer->items[i], MSOGR_LABELOCOLORNAME))
-          itemindexes[i] = MSOGR_LABELOCOLORINDEX;
+    else if (EQUAL(layer->items[i], MSOGR_LABELOCOLORNAME))
+      itemindexes[i] = MSOGR_LABELOCOLORINDEX;
 #endif /* GDAL_VERSION_NUM >= 1600 */
-      else
-          itemindexes[i] = OGR_FD_GetFieldIndex( hDefn, layer->items[i] );
-      if(itemindexes[i] == -1)
-      {
-          msSetError(MS_OGRERR, 
-                     (char*)CPLSPrintf("Invalid Field name: %s", 
-                                       layer->items[i]), 
-                     "msOGRLayerInitItemInfo()");
-          return(MS_FAILURE);
-      }
+    else
+      itemindexes[i] = OGR_FD_GetFieldIndex( hDefn, layer->items[i] );
+    if(itemindexes[i] == -1) {
+      msSetError(MS_OGRERR,
+                 (char*)CPLSPrintf("Invalid Field name: %s",
+                                   layer->items[i]),
+                 "msOGRLayerInitItemInfo()");
+      return(MS_FAILURE);
+    }
   }
 
   return(MS_SUCCESS);
 #else
-/* ------------------------------------------------------------------
- * OGR Support not included...
- * ------------------------------------------------------------------ */
+  /* ------------------------------------------------------------------
+   * OGR Support not included...
+   * ------------------------------------------------------------------ */
 
-  msSetError(MS_MISCERR, "OGR support is not available.", 
+  msSetError(MS_MISCERR, "OGR support is not available.",
              "msOGRLayerInitItemInfo()");
   return(MS_FAILURE);
 
@@ -2593,15 +2182,15 @@ void msOGRLayerFreeItemInfo(layerObj *layer)
 #ifdef USE_OGR
 
   if (layer->iteminfo)
-      free(layer->iteminfo);
+    free(layer->iteminfo);
   layer->iteminfo = NULL;
 
 #else
-/* ------------------------------------------------------------------
- * OGR Support not included...
- * ------------------------------------------------------------------ */
+  /* ------------------------------------------------------------------
+   * OGR Support not included...
+   * ------------------------------------------------------------------ */
 
-  msSetError(MS_MISCERR, "OGR support is not available.", 
+  msSetError(MS_MISCERR, "OGR support is not available.",
              "msOGRLayerFreeItemInfo()");
 
 #endif /* USE_OGR */
@@ -2616,51 +2205,48 @@ void msOGRLayerFreeItemInfo(layerObj *layer)
  *
  * Returns MS_SUCCESS/MS_FAILURE
  **********************************************************************/
-int msOGRLayerNextShape(layerObj *layer, shapeObj *shape) 
+int msOGRLayerNextShape(layerObj *layer, shapeObj *shape)
 {
 #ifdef USE_OGR
   msOGRFileInfo *psInfo =(msOGRFileInfo*)layer->layerinfo;
   int  status;
 
-  if (psInfo == NULL || psInfo->hLayer == NULL)
-  {
-    msSetError(MS_MISCERR, "Assertion failed: OGR layer not opened!!!", 
+  if (psInfo == NULL || psInfo->hLayer == NULL) {
+    msSetError(MS_MISCERR, "Assertion failed: OGR layer not opened!!!",
                "msOGRLayerNextShape()");
     return(MS_FAILURE);
   }
 
   if( layer->tileindex == NULL )
-      return msOGRFileNextShape( layer, shape, psInfo );
+    return msOGRFileNextShape( layer, shape, psInfo );
 
-  // Do we need to load the first tile? 
-  if( psInfo->poCurTile == NULL )
-  {
-      status = msOGRFileReadTile( layer, psInfo );
-      if( status != MS_SUCCESS )
-          return status;
+  // Do we need to load the first tile?
+  if( psInfo->poCurTile == NULL ) {
+    status = msOGRFileReadTile( layer, psInfo );
+    if( status != MS_SUCCESS )
+      return status;
   }
 
-  do 
-  {
-      // Try getting a shape from this tile.
-      status = msOGRFileNextShape( layer, shape, psInfo->poCurTile );
-      if( status != MS_DONE )
-          return status;
-  
-      // try next tile.
-      status = msOGRFileReadTile( layer, psInfo );
-      if( status != MS_SUCCESS )
-          return status;
+  do {
+    // Try getting a shape from this tile.
+    status = msOGRFileNextShape( layer, shape, psInfo->poCurTile );
+    if( status != MS_DONE )
+      return status;
+
+    // try next tile.
+    status = msOGRFileReadTile( layer, psInfo );
+    if( status != MS_SUCCESS )
+      return status;
   } while( status == MS_SUCCESS );
 
   return status;
-  
+
 #else
-/* ------------------------------------------------------------------
- * OGR Support not included...
- * ------------------------------------------------------------------ */
+  /* ------------------------------------------------------------------
+   * OGR Support not included...
+   * ------------------------------------------------------------------ */
 
-  msSetError(MS_MISCERR, "OGR support is not available.", 
+  msSetError(MS_MISCERR, "OGR support is not available.",
              "msOGRLayerNextShape()");
   return(MS_FAILURE);
 
@@ -2685,37 +2271,33 @@ int msOGRLayerGetShape(layerObj *layer, shapeObj *shape, resultObj *record)
   int record_is_fid = TRUE;
 
   /* set the resultindex as shapeindex if available */
-  if (resultindex >= 0)
-  {
+  if (resultindex >= 0) {
     record_is_fid = FALSE;
     shapeindex = resultindex;
   }
 
-  if (psInfo == NULL || psInfo->hLayer == NULL)
-  {
+  if (psInfo == NULL || psInfo->hLayer == NULL) {
     msSetError(MS_MISCERR, "Assertion failed: OGR layer not opened!!!", "msOGRLayerGetShape()");
     return(MS_FAILURE);
   }
 
   if( layer->tileindex == NULL )
-      return msOGRFileGetShape(layer, shape, shapeindex, psInfo, record_is_fid );
-  else
-  {
-      if( psInfo->poCurTile == NULL
-          || psInfo->poCurTile->nTileId != tileindex )
-      {
-          if( msOGRFileReadTile( layer, psInfo, tileindex ) != MS_SUCCESS )
-              return MS_FAILURE;
-      }
+    return msOGRFileGetShape(layer, shape, shapeindex, psInfo, record_is_fid );
+  else {
+    if( psInfo->poCurTile == NULL
+        || psInfo->poCurTile->nTileId != tileindex ) {
+      if( msOGRFileReadTile( layer, psInfo, tileindex ) != MS_SUCCESS )
+        return MS_FAILURE;
+    }
 
-      return msOGRFileGetShape(layer, shape, shapeindex, psInfo->poCurTile, record_is_fid );
+    return msOGRFileGetShape(layer, shape, shapeindex, psInfo->poCurTile, record_is_fid );
   }
 #else
-/* ------------------------------------------------------------------
- * OGR Support not included...
- * ------------------------------------------------------------------ */
+  /* ------------------------------------------------------------------
+   * OGR Support not included...
+   * ------------------------------------------------------------------ */
 
-  msSetError(MS_MISCERR, "OGR support is not available.", 
+  msSetError(MS_MISCERR, "OGR support is not available.",
              "msOGRLayerGetShape()");
   return(MS_FAILURE);
 
@@ -2729,31 +2311,29 @@ int msOGRLayerGetShape(layerObj *layer, shapeObj *shape, resultObj *record)
  *
  * Returns MS_SUCCESS/MS_FAILURE
  **********************************************************************/
-int msOGRLayerGetExtent(layerObj *layer, rectObj *extent) 
+int msOGRLayerGetExtent(layerObj *layer, rectObj *extent)
 {
 #ifdef USE_OGR
   msOGRFileInfo *psInfo =(msOGRFileInfo*)layer->layerinfo;
   OGREnvelope oExtent;
 
-  if (psInfo == NULL || psInfo->hLayer == NULL)
-  {
-    msSetError(MS_MISCERR, "Assertion failed: OGR layer not opened!!!", 
+  if (psInfo == NULL || psInfo->hLayer == NULL) {
+    msSetError(MS_MISCERR, "Assertion failed: OGR layer not opened!!!",
                "msOGRLayerGetExtent()");
     return(MS_FAILURE);
   }
 
-/* ------------------------------------------------------------------
- * Call OGR's GetExtent()... note that for some formats this will
- * result in a scan of the whole layer and can be an expensive call.
- *
- * For tile indexes layers we assume it is sufficient to get the
- * extents of the tile index.
- * ------------------------------------------------------------------ */
+  /* ------------------------------------------------------------------
+   * Call OGR's GetExtent()... note that for some formats this will
+   * result in a scan of the whole layer and can be an expensive call.
+   *
+   * For tile indexes layers we assume it is sufficient to get the
+   * extents of the tile index.
+   * ------------------------------------------------------------------ */
   ACQUIRE_OGR_LOCK;
-  if (OGR_L_GetExtent( psInfo->hLayer, &oExtent, TRUE) != OGRERR_NONE)
-  {
-      RELEASE_OGR_LOCK;
-    msSetError(MS_MISCERR, "Unable to get extents for this layer.", 
+  if (OGR_L_GetExtent( psInfo->hLayer, &oExtent, TRUE) != OGRERR_NONE) {
+    RELEASE_OGR_LOCK;
+    msSetError(MS_MISCERR, "Unable to get extents for this layer.",
                "msOGRLayerGetExtent()");
     return(MS_FAILURE);
   }
@@ -2766,11 +2346,11 @@ int msOGRLayerGetExtent(layerObj *layer, rectObj *extent)
 
   return MS_SUCCESS;
 #else
-/* ------------------------------------------------------------------
- * OGR Support not included...
- * ------------------------------------------------------------------ */
+  /* ------------------------------------------------------------------
+   * OGR Support not included...
+   * ------------------------------------------------------------------ */
 
-  msSetError(MS_MISCERR, "OGR support is not available.", 
+  msSetError(MS_MISCERR, "OGR support is not available.",
              "msOGRLayerGetExtent()");
   return(MS_FAILURE);
 
@@ -2786,43 +2366,39 @@ int msOGRLayerGetExtent(layerObj *layer, rectObj *extent)
  * default symbol name, and if not found return 0.
  **********************************************************************/
 #ifdef USE_OGR
-static int msOGRGetSymbolId(symbolSetObj *symbolset, const char *pszSymbolId, 
+static int msOGRGetSymbolId(symbolSetObj *symbolset, const char *pszSymbolId,
                             const char *pszDefaultSymbol, int try_addimage_if_notfound)
 {
-    // Symbol name mapping:
-    // First look for the native symbol name, then the ogr-...
-    // generic name, and in last resort try pszDefaultSymbol if
-    // provided by user.
-    char  **params;
-    int   numparams;
-    int   nSymbol = -1;
-
-    if (pszSymbolId && pszSymbolId[0] != '\0')
-    {
+  // Symbol name mapping:
+  // First look for the native symbol name, then the ogr-...
+  // generic name, and in last resort try pszDefaultSymbol if
+  // provided by user.
+  char  **params;
+  int   numparams;
+  int   nSymbol = -1;
+
+  if (pszSymbolId && pszSymbolId[0] != '\0') {
 #if GDAL_VERSION_NUM >= 1800 /* Use comma as the separator */
-        params = msStringSplit(pszSymbolId, ',', &numparams);
+    params = msStringSplit(pszSymbolId, ',', &numparams);
 #else
-        params = msStringSplit(pszSymbolId, '.', &numparams);
+    params = msStringSplit(pszSymbolId, '.', &numparams);
 #endif
-        if (params != NULL)
-        {
-            for(int j=0; j<numparams && nSymbol == -1; j++)
-            {
-                nSymbol = msGetSymbolIndex(symbolset, params[j], 
-                                           try_addimage_if_notfound);
-            }
-            msFreeCharArray(params, numparams);
-        }
-    }
-    if (nSymbol == -1 && pszDefaultSymbol)
-    {
-        nSymbol = msGetSymbolIndex(symbolset,(char*)pszDefaultSymbol,
+    if (params != NULL) {
+      for(int j=0; j<numparams && nSymbol == -1; j++) {
+        nSymbol = msGetSymbolIndex(symbolset, params[j],
                                    try_addimage_if_notfound);
+      }
+      msFreeCharArray(params, numparams);
     }
-    if (nSymbol == -1)
-        nSymbol = 0;
+  }
+  if (nSymbol == -1 && pszDefaultSymbol) {
+    nSymbol = msGetSymbolIndex(symbolset,(char*)pszDefaultSymbol,
+                               try_addimage_if_notfound);
+  }
+  if (nSymbol == -1)
+    nSymbol = 0;
 
-    return nSymbol;
+  return nSymbol;
 }
 #endif
 
@@ -2830,699 +2406,374 @@ static int msOGRGetSymbolId(symbolSetObj *symbolset, const char *pszSymbolId,
  *                     msOGRUpdateStyle()
  *
  * Update the mapserver style according to the ogr style.
- * The function is called by msOGRGetAutoStyle and 
+ * The function is called by msOGRGetAutoStyle and
  * msOGRUpdateStyleFromString
  **********************************************************************/
 
 #ifdef USE_OGR
-#if GDAL_VERSION_NUM >= 1500 /* Use OGR Style C API */
 static int msOGRUpdateStyle(OGRStyleMgrH hStyleMgr, mapObj *map, layerObj *layer, classObj *c)
-#else
-static int msOGRUpdateStyle(OGRStyleMgr *poStyleMgr, mapObj *map, layerObj *layer, classObj *c)
-#endif
 {
-    GBool bIsNull, bIsBrush=MS_FALSE, bIsPen=MS_FALSE;
-    int r=0,g=0,b=0,t=0;
-    double dfTmp;
-    int try_addimage_if_notfound = MS_FALSE;
-#if GDAL_VERSION_NUM >= 1500 /* Use OGR Style C API */
-    int numParts = OGR_SM_GetPartCount(hStyleMgr, NULL);
-#else /* OGRStyle C++ */
-    int numParts = poStyleMgr->GetPartCount();
-#endif /* OGRStyle C API */
-
-/* ------------------------------------------------------------------
- * Handle each part
- * ------------------------------------------------------------------ */
-
-    for(int i=0; i<numParts; i++)
-    {
-      OGRSTClassId eStylePartType;
-#if GDAL_VERSION_NUM >= 1500 /* Use OGR Style C API */
-      OGRStyleToolH hStylePart = OGR_SM_GetPart(hStyleMgr, i, NULL);
-      if (!hStylePart)
-          continue;
-      eStylePartType = OGR_ST_GetType(hStylePart);
-#else /* OGRStyle C++ */
-      OGRStyleTool *poStylePart = poStyleMgr->GetPart(i);
-      if (!poStylePart)
-          continue;
-      eStylePartType = poStylePart->GetType();
-#endif /* OGRStyle C API */
-
-      // We want all size values returned in pixels.
-      //
-      // The scale factor that OGR expect is the ground/paper scale
-      // e.g. if 1 ground unit = 0.01 paper unit then scale=1/0.01=100
-      // cellsize if number of ground units/pixel, and OGR assumes that
-      // there is 72*39.37 pixels/ground units (since meter is assumed 
-      // for ground... but what ground units we have does not matter
-      // as long as use the same assumptions everywhere)
-      // That gives scale = cellsize*72*39.37
-
-#if GDAL_VERSION_NUM >= 1500 /* Use OGR Style C API */
-      OGR_ST_SetUnit(hStylePart, OGRSTUPixel, map->cellsize*72.0*39.37);
-#else
-      poStylePart->SetUnit(OGRSTUPixel, map->cellsize*72.0*39.37);
-#endif
+  GBool bIsNull, bIsBrush=MS_FALSE;
+  int r=0,g=0,b=0,t=0;
+  double dfTmp;
+  int try_addimage_if_notfound = MS_FALSE;
+  int numParts = OGR_SM_GetPartCount(hStyleMgr, NULL);
+
+  /* ------------------------------------------------------------------
+   * Handle each part
+   * ------------------------------------------------------------------ */
+
+  for(int i=0; i<numParts; i++) {
+    OGRSTClassId eStylePartType;
+    OGRStyleToolH hStylePart = OGR_SM_GetPart(hStyleMgr, i, NULL);
+    if (!hStylePart)
+      continue;
+    eStylePartType = OGR_ST_GetType(hStylePart);
+
+    // We want all size values returned in pixels.
+    //
+    // The scale factor that OGR expect is the ground/paper scale
+    // e.g. if 1 ground unit = 0.01 paper unit then scale=1/0.01=100
+    // cellsize if number of ground units/pixel, and OGR assumes that
+    // there is 72*39.37 pixels/ground units (since meter is assumed
+    // for ground... but what ground units we have does not matter
+    // as long as use the same assumptions everywhere)
+    // That gives scale = cellsize*72*39.37
+
+    OGR_ST_SetUnit(hStylePart, OGRSTUPixel, map->cellsize*72.0*39.37);
+
+    if (eStylePartType == OGRSTCLabel) {
+      OGRStyleToolH hLabelStyle = hStylePart;
+
+      // Enclose the text string inside quotes to make sure it is seen
+      // as a string by the parser inside loadExpression(). (bug185)
+      /* See bug 3481 about the isalnum hack */
+      const char *labelTextString = OGR_ST_GetParamStr(hLabelStyle,
+                                    OGRSTLabelTextString,
+                                    &bIsNull);
+      msLoadExpressionString(&(c->text),(char*)labelTextString);
+
+      if (c->numlabels == 0) {
+        /* allocate a new label object */
+        if(msGrowClassLabels(c) == NULL) 
+          return MS_FAILURE;
+        c->numlabels++;
+        initLabel(c->labels[0]);
+      }
 
-      if (eStylePartType == OGRSTCLabel)
-#if GDAL_VERSION_NUM >= 1500 /* Use OGR Style C API */
-      {
-          OGRStyleToolH hLabelStyle = hStylePart;
-
-          // Enclose the text string inside quotes to make sure it is seen
-          // as a string by the parser inside loadExpression(). (bug185)
-          /* See bug 3481 about the isalnum hack */
-          const char *labelTextString = OGR_ST_GetParamStr(hLabelStyle, 
-                                                           OGRSTLabelTextString, 
-                                                           &bIsNull);
-          if (labelTextString && isalnum(labelTextString[0]))
-              msLoadExpressionString(&(c->text), (char*)labelTextString);
-          else
-              msLoadExpressionString(&(c->text), 
-                              (char*)CPLSPrintf("\"%s\"", (char*)labelTextString));
-
-          c->label.angle = OGR_ST_GetParamDbl(hLabelStyle, 
-                                              OGRSTLabelAngle, &bIsNull);
-
-          c->label.size = OGR_ST_GetParamDbl(hLabelStyle, 
-                                             OGRSTLabelSize, &bIsNull);
-          if( c->label.size < 1 ) /* no point dropping to zero size */
-              c->label.size = 1;
-
-          // OGR default is anchor point = LL, so label is at UR of anchor
-          c->label.position = MS_UR;
-
-          int nPosition = OGR_ST_GetParamNum(hLabelStyle, 
-                                             OGRSTLabelAnchor,
-                                             &bIsNull);
-          if( !bIsNull )
-          {
-              switch( nPosition ) {
-                case 1: c->label.position = MS_UR; break;
-                case 2: c->label.position = MS_UC; break;
-                case 3: c->label.position = MS_UL; break;
-                case 4: c->label.position = MS_CR; break;
-                case 5: c->label.position = MS_CC; break;
-                case 6: c->label.position = MS_CL; break;
-                case 7: c->label.position = MS_LR; break;
-                case 8: c->label.position = MS_LC; break;
-                case 9: c->label.position = MS_LL; break;
-                case 10: c->label.position = MS_UR; break; /*approximate*/
-                case 11: c->label.position = MS_UC; break;
-                case 12: c->label.position = MS_UL; break;
-                default: break;
-              }
-          }
+      c->labels[0]->angle = OGR_ST_GetParamDbl(hLabelStyle,
+                            OGRSTLabelAngle, &bIsNull);
 
-          const char *pszColor = OGR_ST_GetParamStr(hLabelStyle, 
-                                                    OGRSTLabelFColor,
-                                                    &bIsNull);
-          if (!bIsNull && OGR_ST_GetRGBFromString(hLabelStyle, pszColor,
-                                                  &r, &g, &b, &t))
-          {
-              MS_INIT_COLOR(c->label.color, r, g, b, t);
-          }
+      c->labels[0]->size = OGR_ST_GetParamDbl(hLabelStyle,
+                                              OGRSTLabelSize, &bIsNull);
+      if( c->labels[0]->size < 1 ) /* no point dropping to zero size */
+        c->labels[0]->size = 1;
 
-          pszColor = OGR_ST_GetParamStr(hLabelStyle, 
-                                        OGRSTLabelHColor,
-                                        &bIsNull);
-          if (!bIsNull && OGR_ST_GetRGBFromString(hLabelStyle, pszColor,
-                                                  &r, &g, &b, &t))
-          {
-              MS_INIT_COLOR(c->label.shadowcolor, r, g, b, t);
-          }
+      // OGR default is anchor point = LL, so label is at UR of anchor
+      c->labels[0]->position = MS_UR;
 
-#if GDAL_VERSION_NUM >= 1600
-          pszColor = OGR_ST_GetParamStr(hLabelStyle, 
-                                        OGRSTLabelOColor,
-                                        &bIsNull);
-          if (!bIsNull && OGR_ST_GetRGBFromString(hLabelStyle, pszColor,
-                                                  &r, &g, &b, &t))
-          {
-              MS_INIT_COLOR(c->label.outlinecolor, r, g, b, t);
-          }
-#endif /* GDAL_VERSION_NUM >= 1600 */
+      int nPosition = OGR_ST_GetParamNum(hLabelStyle,
+                                         OGRSTLabelAnchor,
+                                         &bIsNull);
+      if( !bIsNull ) {
+        switch( nPosition ) {
+          case 1:
+            c->labels[0]->position = MS_UR;
+            break;
+          case 2:
+            c->labels[0]->position = MS_UC;
+            break;
+          case 3:
+            c->labels[0]->position = MS_UL;
+            break;
+          case 4:
+            c->labels[0]->position = MS_CR;
+            break;
+          case 5:
+            c->labels[0]->position = MS_CC;
+            break;
+          case 6:
+            c->labels[0]->position = MS_CL;
+            break;
+          case 7:
+            c->labels[0]->position = MS_LR;
+            break;
+          case 8:
+            c->labels[0]->position = MS_LC;
+            break;
+          case 9:
+            c->labels[0]->position = MS_LL;
+            break;
+          case 10:
+            c->labels[0]->position = MS_UR;
+            break; /*approximate*/
+          case 11:
+            c->labels[0]->position = MS_UC;
+            break;
+          case 12:
+            c->labels[0]->position = MS_UL;
+            break;
+          default:
+            break;
+        }
+      }
 
-          // Label font... do our best to use TrueType fonts, otherwise
-          // fallback on bitmap fonts.
-#if defined(USE_GD_TTF) || defined (USE_GD_FT)
-          const char *pszBold = OGR_ST_GetParamNum(hLabelStyle, 
-                                                       OGRSTLabelBold, 
-                                                       &bIsNull) ? "-bold" : "";
-          const char *pszItalic = OGR_ST_GetParamNum(hLabelStyle, 
-                                                       OGRSTLabelItalic, 
-                                                       &bIsNull) ? "-italic" : "";
-          const char *pszFontName = OGR_ST_GetParamStr(hLabelStyle, 
-                                                       OGRSTLabelFontName,
-                                                       &bIsNull);
-          const char *pszName = CPLSPrintf("%s%s%s", pszFontName, pszBold, pszItalic);
-          bool bFont = true;
-
-          if (pszFontName != NULL && !bIsNull && pszFontName[0] != '\0')
-          {
-              if (msLookupHashTable(&(map->fontset.fonts), (char*)pszName) != NULL)
-              {
-                  c->label.type = MS_TRUETYPE;
-                  c->label.font = msStrdup(pszName);
-                  if (layer->debug >= MS_DEBUGLEVEL_VVV)
-                      msDebug("** Using '%s' TTF font **\n", pszName);
-              }
-              else if ( (strcmp(pszFontName,pszName) != 0) &&
-                        msLookupHashTable(&(map->fontset.fonts), (char*)pszFontName) != NULL)
-              {
-                  c->label.type = MS_TRUETYPE;
-                  c->label.font = msStrdup(pszFontName);
-                  if (layer->debug >= MS_DEBUGLEVEL_VVV)
-                      msDebug("** Using '%s' TTF font **\n", pszFontName);
-              }
-              else if (msLookupHashTable(&(map->fontset.fonts),"default") != NULL)
-              {
-                  c->label.type = MS_TRUETYPE;
-                  c->label.font = msStrdup("default");
-                  if (layer->debug >= MS_DEBUGLEVEL_VVV)
-                      msDebug("** Using 'default' TTF font **\n");
-              }
-              else
-                  bFont = false;
-          }
+      const char *pszColor = OGR_ST_GetParamStr(hLabelStyle,
+                             OGRSTLabelFColor,
+                             &bIsNull);
+      if (!bIsNull && OGR_ST_GetRGBFromString(hLabelStyle, pszColor,
+                                              &r, &g, &b, &t)) {
+        MS_INIT_COLOR(c->labels[0]->color, r, g, b, t);
+      }
 
-          if (!bFont)
-#endif /* USE_GD_FT || USE_GD_FT */
-          {
-              c->label.type = MS_BITMAP;
-              c->label.size = MS_MEDIUM;
-              if (layer->debug >= MS_DEBUGLEVEL_VVV)
-                  msDebug("** Using 'medium' BITMAP font **\n");
-          }
+      pszColor = OGR_ST_GetParamStr(hLabelStyle,
+                                    OGRSTLabelHColor,
+                                    &bIsNull);
+      if (!bIsNull && OGR_ST_GetRGBFromString(hLabelStyle, pszColor,
+                                              &r, &g, &b, &t)) {
+        MS_INIT_COLOR(c->labels[0]->shadowcolor, r, g, b, t);
       }
-#else /* OGR Style C++ */
-      {
-          OGRStyleLabel *poLabelStyle = (OGRStyleLabel*)poStylePart;
-
-          // Enclose the text string inside quotes to make sure it is seen
-          // as a string by the parser inside loadExpression(). (bug185)
-          /* See bug 3481 about the isalnum hack */
-          const char *labelTextString = poLabelStyle->TextString(bIsNull);
-
-          if (labelTextString && isalnum(labelTextString[0]))
-              msLoadExpressionString(&(c->text), (char*)labelTextString);
-          else
-              msLoadExpressionString(&(c->text), 
-                              (char*)CPLSPrintf("\"%s\"", (char*)labelTextString));
-
-          c->label.angle = poLabelStyle->Angle(bIsNull);
-
-          c->label.size = (int)poLabelStyle->Size(bIsNull);
-          if( c->label.size < 1 ) /* no point dropping to zero size */
-              c->label.size = 1;
-
-          // OGR default is anchor point = LL, so label is at UR of anchor
-          c->label.position = MS_UR;
-
-          const char *pszColor = poLabelStyle->ForeColor(bIsNull);
-          if (!bIsNull && poLabelStyle->GetRGBFromString(pszColor,r,g,b,t))
-          {
-              MS_INIT_COLOR(c->label.color, r, g, b, t);
-          }
 
-          pszColor = poLabelStyle->BackColor(bIsNull);
-          if (!bIsNull && poLabelStyle->GetRGBFromString(pszColor,r,g,b,t))
-          {
-              MS_INIT_COLOR(c->label.backgroundcolor, r, g, b, t);
-          }
-#if GDAL_VERSION_NUM >= 1400
-          pszColor = poLabelStyle->ShadowColor(bIsNull);
-          if (!bIsNull && poLabelStyle->GetRGBFromString(pszColor,r,g,b,t))
-          {
-              MS_INIT_COLOR(c->label.shadowcolor, r, g, b, t);
-          }
-#endif
-          // Label font... do our best to use TrueType fonts, otherwise
-          // fallback on bitmap fonts.
-#if defined(USE_GD_TTF) || defined (USE_GD_FT)
-          const char *pszBold = poLabelStyle->Bold(bIsNull)  ? "-bold" : "";
-          const char *pszItalic = poLabelStyle->Italic(bIsNull) ? "-italic" : "";
-          const char *pszFontName = poLabelStyle->FontName(bIsNull);
-          const char *pszName = CPLSPrintf("%s%s%s", pszFontName, pszBold, pszItalic);
-          bool bFont = true;
-
-          if (pszFontName != NULL && !bIsNull && pszFontName[0] != '\0')
-          {
-              if (msLookupHashTable(&(map->fontset.fonts), (char*)pszName) != NULL)
-              {
-                  c->label.type = MS_TRUETYPE;
-                  c->label.font = msStrdup(pszName);
-                  if (layer->debug >= MS_DEBUGLEVEL_VVV)
-                      msDebug("** Using '%s' TTF font **\n", pszName);
-              }
-              else if ( (strcmp(pszFontName,pszName) != 0) &&
-                        msLookupHashTable(&(map->fontset.fonts), (char*)pszFontName) != NULL)
-              {
-                  c->label.type = MS_TRUETYPE;
-                  c->label.font = msStrdup(pszFontName);
-                  if (layer->debug >= MS_DEBUGLEVEL_VVV)
-                      msDebug("** Using '%s' TTF font **\n", pszFontName);
-              }
-              else if (msLookupHashTable(&(map->fontset.fonts),"default") != NULL)
-              {
-                  c->label.type = MS_TRUETYPE;
-                  c->label.font = msStrdup("default");
-                  if (layer->debug >= MS_DEBUGLEVEL_VVV)
-                      msDebug("** Using 'default' TTF font **\n");
-              }
-              else
-                  bFont = false;
-          }
+#if GDAL_VERSION_NUM >= 1600
+      pszColor = OGR_ST_GetParamStr(hLabelStyle,
+                                    OGRSTLabelOColor,
+                                    &bIsNull);
+      if (!bIsNull && OGR_ST_GetRGBFromString(hLabelStyle, pszColor,
+                                              &r, &g, &b, &t)) {
+        MS_INIT_COLOR(c->labels[0]->outlinecolor, r, g, b, t);
+      }
+#endif /* GDAL_VERSION_NUM >= 1600 */
 
-          if (!bFont)
-#endif /* USE_GD_FT || USE_GD_FT */
-          {
-              c->label.type = MS_BITMAP;
-              c->label.size = MS_MEDIUM;
-              if (layer->debug >= MS_DEBUGLEVEL_VVV)
-                  msDebug("** Using 'medium' BITMAP font **\n");
-          }
+      const char *pszBold = OGR_ST_GetParamNum(hLabelStyle,
+                            OGRSTLabelBold,
+                            &bIsNull) ? "-bold" : "";
+      const char *pszItalic = OGR_ST_GetParamNum(hLabelStyle,
+                              OGRSTLabelItalic,
+                              &bIsNull) ? "-italic" : "";
+      const char *pszFontName = OGR_ST_GetParamStr(hLabelStyle,
+                                OGRSTLabelFontName,
+                                &bIsNull);
+      /* replace spaces with hyphens to allow mapping to a valid hashtable entry*/
+      char* pszFontNameEscaped = NULL;
+      if (pszFontName != NULL) {
+          pszFontNameEscaped = strdup(pszFontName);
+          msReplaceChar(pszFontNameEscaped, ' ', '-');
       }
-#endif /* OGRStyle C API */
-      else if (eStylePartType == OGRSTCPen)
-#if GDAL_VERSION_NUM >= 1500 /* Use OGR Style C API */
-      {
-          OGRStyleToolH hPenStyle = hStylePart;
-          bIsPen = TRUE;
-
-          const char *pszPenName = OGR_ST_GetParamStr(hPenStyle, 
-                                                      OGRSTPenId, 
-                                                      &bIsNull);
-          if (bIsNull) pszPenName = NULL;
-          colorObj oPenColor;
-          int nPenSymbol = 0;
-          int nPenSize = 1;
-          t =-1;
-
-          // Make sure pen is always initialized
-          MS_INIT_COLOR(oPenColor, -1, -1, -1,255);
-
-          // Check for Pen Pattern "ogr-pen-1": the invisible pen
-          // If that's what we have then set pen color to -1
-          if (pszPenName && strstr(pszPenName, "ogr-pen-1") != NULL)
-          {
-              MS_INIT_COLOR(oPenColor, -1, -1, -1,255);
-          }
-          else
-          {
-              const char *pszColor = OGR_ST_GetParamStr(hPenStyle, 
-                                                        OGRSTPenColor,
-                                                        &bIsNull);
-              if (!bIsNull && OGR_ST_GetRGBFromString(hPenStyle, pszColor,
-                                                      &r, &g, &b, &t))
-              {
-                  MS_INIT_COLOR(oPenColor, r, g, b, t);
-                  if (layer->debug >= MS_DEBUGLEVEL_VVV)
-                      msDebug("** PEN COLOR = %d %d %d **\n", r,g,b);
-              }
-
-              nPenSize = OGR_ST_GetParamNum(hPenStyle, 
-                                            OGRSTPenWidth, &bIsNull);
-              if (bIsNull)
-                  nPenSize = 1;
-              if (pszPenName!=NULL)
-              {
-                  // Try to match pen name in symbol file
-                  nPenSymbol = msOGRGetSymbolId(&(map->symbolset),
-                                                pszPenName, NULL, MS_FALSE);
-              }
-          }
+
+      const char *pszName = CPLSPrintf("%s%s%s", pszFontNameEscaped, pszBold, pszItalic);
+      bool bFont = true;
+
+      if (pszFontNameEscaped != NULL && !bIsNull && pszFontNameEscaped[0] != '\0') {
+        if (msLookupHashTable(&(map->fontset.fonts), (char*)pszName) != NULL) {
+          c->labels[0]->type = MS_TRUETYPE;
+          c->labels[0]->font = msStrdup(pszName);
           if (layer->debug >= MS_DEBUGLEVEL_VVV)
-              msDebug("** PEN COLOR = %d %d %d **\n", oPenColor.red,oPenColor.green,oPenColor.blue);
-          if (bIsBrush || layer->type == MS_LAYER_POLYGON)
-          {
-              // This is a multipart symbology, so pen defn goes in the
-              // overlaysymbol params 
-              if (msMaybeAllocateClassStyle(c, 1))
-              {
-#if GDAL_VERSION_NUM >= 1500 /* Use OGR Style C API */
-                  OGR_ST_Destroy(hStylePart);
-#else
-                  delete poStylePart;
-#endif
-                  return(MS_FAILURE);
-              }
+            msDebug("** Using '%s' TTF font **\n", pszName);
+        } else if ( (strcmp(pszFontNameEscaped,pszName) != 0) &&
+                    msLookupHashTable(&(map->fontset.fonts), (char*)pszFontNameEscaped) != NULL) {
+          c->labels[0]->type = MS_TRUETYPE;
+          c->labels[0]->font = msStrdup(pszFontNameEscaped);
+          if (layer->debug >= MS_DEBUGLEVEL_VVV)
+            msDebug("** Using '%s' TTF font **\n", pszFontNameEscaped);
+        } else if (msLookupHashTable(&(map->fontset.fonts),"default") != NULL) {
+          c->labels[0]->type = MS_TRUETYPE;
+          c->labels[0]->font = msStrdup("default");
+          if (layer->debug >= MS_DEBUGLEVEL_VVV)
+            msDebug("** Using 'default' TTF font **\n");
+        } else
+          bFont = false;
+      }
 
-              c->styles[1]->outlinecolor = oPenColor;
-              c->styles[1]->size = nPenSize;
-              c->styles[1]->symbol = nPenSymbol;
-              c->styles[1]->width = nPenSize;
-          }
-          else
-          {
-              // Single part symbology
-              if (msMaybeAllocateClassStyle(c, 0))
-              {
-#if GDAL_VERSION_NUM >= 1500 /* Use OGR Style C API */
-                  OGR_ST_Destroy(hStylePart);
-#else
-                  delete poStylePart;
-#endif
-                  return(MS_FAILURE);
-              }
-
-              if(layer->type == MS_LAYER_POLYGON)
-                  c->styles[0]->outlinecolor = c->styles[0]->color = 
-                      oPenColor;
-              else
-                  c->styles[0]->color = oPenColor;
-              c->styles[0]->symbol = nPenSymbol;
-              c->styles[0]->size = nPenSize;
-              c->styles[0]->width = nPenSize;
-          }
+      msFree(pszFontNameEscaped);
 
+      if (!bFont) {
+        c->labels[0]->type = MS_BITMAP;
+        c->labels[0]->size = MS_MEDIUM;
+        if (layer->debug >= MS_DEBUGLEVEL_VVV)
+          msDebug("** Using 'medium' BITMAP font **\n");
       }
-#else /* OGR Style C++ */
-      {
-          OGRStylePen *poPenStyle = (OGRStylePen*)poStylePart;
-          bIsPen = TRUE;
-
-          const char *pszPenName = poPenStyle->Id(bIsNull);
-          if (bIsNull) pszPenName = NULL;
-          colorObj oPenColor;
-          int nPenSymbol = 0;
-          int nPenSize = 1;
-          t = -1;
-
-          // Make sure pen is always initialized
-          MS_INIT_COLOR(oPenColor, -1, -1, -1);
-
-          // Check for Pen Pattern "ogr-pen-1": the invisible pen
-          // If that's what we have then set pen color to -1
-          if (pszPenName && strstr(pszPenName, "ogr-pen-1") != NULL)
-          {
-              MS_INIT_COLOR(oPenColor, -1, -1, -1);
-          }
-          else
-          {
-              const char *pszColor = poPenStyle->Color(bIsNull);
-              if (!bIsNull && poPenStyle->GetRGBFromString(pszColor,r,g,b,t))
-              {
-                  MS_INIT_COLOR(oPenColor, r, g, b, t);
-
-                  if (layer->debug >= MS_DEBUGLEVEL_VVV)
-                      msDebug("** PEN COLOR = %d %d %d **\n", r,g,b);
-              }
-
-              nPenSize = (int)poPenStyle->Width(bIsNull);
-              if (bIsNull)
-                  nPenSize = 1;
-              if (pszPenName!=NULL)
-              {
-                  // Try to match pen name in symbol file
-                  nPenSymbol = msOGRGetSymbolId(&(map->symbolset),
-                                                pszPenName, NULL, MS_FALSE);
-              }
-          }
+    } else if (eStylePartType == OGRSTCPen) {
+      OGRStyleToolH hPenStyle = hStylePart;
+
+      const char *pszPenName = OGR_ST_GetParamStr(hPenStyle,
+                               OGRSTPenId,
+                               &bIsNull);
+      if (bIsNull) pszPenName = NULL;
+      colorObj oPenColor;
+      int nPenSymbol = 0;
+      int nPenSize = 1;
+      t =-1;
+
+      // Make sure pen is always initialized
+      MS_INIT_COLOR(oPenColor, -1, -1, -1,255);
+
+      // Check for Pen Pattern "ogr-pen-1": the invisible pen
+      // If that's what we have then set pen color to -1
+      if (pszPenName && strstr(pszPenName, "ogr-pen-1") != NULL) {
+        MS_INIT_COLOR(oPenColor, -1, -1, -1,255);
+      } else {
+        const char *pszColor = OGR_ST_GetParamStr(hPenStyle,
+                               OGRSTPenColor,
+                               &bIsNull);
+        if (!bIsNull && OGR_ST_GetRGBFromString(hPenStyle, pszColor,
+                                                &r, &g, &b, &t)) {
+          MS_INIT_COLOR(oPenColor, r, g, b, t);
           if (layer->debug >= MS_DEBUGLEVEL_VVV)
-              msDebug("** PEN COLOR = %d %d %d **\n", oPenColor.red,oPenColor.green,oPenColor.blue);
-          if (bIsBrush || layer->type == MS_LAYER_POLYGON)
-          {
-              // This is a multipart symbology, so pen defn goes in the
-              // overlaysymbol params 
-              if (msMaybeAllocateClassStyle(c, 1))
-              {
-#if GDAL_VERSION_NUM >= 1500 /* Use OGR Style C API */
-                  OGR_ST_Destroy(hStylePart);
-#else
-                  delete poStylePart;
-#endif
-                  return(MS_FAILURE);
-              }
-
-              c->styles[1]->outlinecolor = oPenColor;
-              c->styles[1]->size = nPenSize;
-              c->styles[1]->symbol = nPenSymbol;
-              c->styles[1]->width = nPenSize;
-          }
-          else
-          {
-              // Single part symbology
-              if (msMaybeAllocateClassStyle(c, 0))
-              {
-#if GDAL_VERSION_NUM >= 1500 /* Use OGR Style C API */
-                  OGR_ST_Destroy(hStylePart);
-#else
-                  delete poStylePart;
-#endif
-                  return(MS_FAILURE);
-              }
-
-              if(layer->type == MS_LAYER_POLYGON)
-                  c->styles[0]->outlinecolor = c->styles[0]->color = 
-                      oPenColor;
-              else
-                  c->styles[0]->color = oPenColor;
-              c->styles[0]->symbol = nPenSymbol;
-              c->styles[0]->size = nPenSize;
-              c->styles[0]->width = nPenSize;
-          }
+            msDebug("** PEN COLOR = %d %d %d **\n", r,g,b);
+        }
 
+        nPenSize = OGR_ST_GetParamNum(hPenStyle,
+                                      OGRSTPenWidth, &bIsNull);
+        if (bIsNull)
+          nPenSize = 1;
+        if (pszPenName!=NULL) {
+          // Try to match pen name in symbol file
+          nPenSymbol = msOGRGetSymbolId(&(map->symbolset),
+                                        pszPenName, NULL, MS_FALSE);
+        }
       }
-#endif /* OGRStyle C API */
-      else if (eStylePartType == OGRSTCBrush)
-#if GDAL_VERSION_NUM >= 1500 /* Use OGR Style C API */
-      {
-          OGRStyleToolH hBrushStyle = hStylePart;
-
-          const char *pszBrushName = OGR_ST_GetParamStr(hBrushStyle, 
-                                                        OGRSTBrushId, 
-                                                        &bIsNull);
-          if (bIsNull) pszBrushName = NULL;
-
-          /* We need 1 style */
-          if (msMaybeAllocateClassStyle(c, 0))
-          {
-#if GDAL_VERSION_NUM >= 1500 /* Use OGR Style C API */
-              OGR_ST_Destroy(hStylePart);
-#else
-              delete poStylePart;
-#endif
-              return(MS_FAILURE);
-          }
+      if (layer->debug >= MS_DEBUGLEVEL_VVV)
+        msDebug("** PEN COLOR = %d %d %d **\n", oPenColor.red,oPenColor.green,oPenColor.blue);
+      if (bIsBrush || layer->type == MS_LAYER_POLYGON) {
+        // This is a multipart symbology, so pen defn goes in the
+        // overlaysymbol params
+        if (msMaybeAllocateClassStyle(c, 1)) {
+          OGR_ST_Destroy(hStylePart);
+          return(MS_FAILURE);
+        }
 
-          // Check for Brush Pattern "ogr-brush-1": the invisible fill
-          // If that's what we have then set fill color to -1
-          if (pszBrushName && strstr(pszBrushName, "ogr-brush-1") != NULL)
-          {
-              MS_INIT_COLOR(c->styles[0]->color, -1, -1, -1, 255);
-          }
-          else
-          {
-              bIsBrush = TRUE;
-              const char *pszColor = OGR_ST_GetParamStr(hBrushStyle, 
-                                                        OGRSTBrushFColor,
-                                                        &bIsNull);
-              if (!bIsNull && OGR_ST_GetRGBFromString(hBrushStyle, 
-                                                      pszColor,
-                                                      &r, &g, &b, &t))
-              {
-                  MS_INIT_COLOR(c->styles[0]->color, r, g, b, t);
-
-                  if (layer->debug >= MS_DEBUGLEVEL_VVV)
-                      msDebug("** BRUSH COLOR = %d %d %d **\n", r,g,b);
-              }
-
-              pszColor = OGR_ST_GetParamStr(hBrushStyle, 
-                                            OGRSTBrushBColor, &bIsNull);
-              if (!bIsNull && OGR_ST_GetRGBFromString(hBrushStyle, 
-                                                      pszColor,
-                                                      &r, &g, &b, &t))
-              {
-                  MS_INIT_COLOR(c->styles[0]->backgroundcolor, r, g, b, t);
-              }
-
-              // Symbol name mapping:
-              // First look for the native symbol name, then the ogr-...
-              // generic name.  
-              // If none provided or found then use 0: solid fill
-          
-              const char *pszName = OGR_ST_GetParamStr(hBrushStyle, 
-                                                        OGRSTBrushId, 
-                                                        &bIsNull);
-              c->styles[0]->symbol = msOGRGetSymbolId(&(map->symbolset), 
-                                                      pszName, NULL, MS_FALSE);
-          }
+        c->styles[1]->outlinecolor = oPenColor;
+        c->styles[1]->size = nPenSize;
+        c->styles[1]->symbol = nPenSymbol;
+        c->styles[1]->width = nPenSize;
+      } else {
+        // Single part symbology
+        if (msMaybeAllocateClassStyle(c, 0)) {
+          OGR_ST_Destroy(hStylePart);
+          return(MS_FAILURE);
+        }
+
+        if(layer->type == MS_LAYER_POLYGON)
+          c->styles[0]->outlinecolor = c->styles[0]->color =
+                                         oPenColor;
+        else
+          c->styles[0]->color = oPenColor;
+        c->styles[0]->symbol = nPenSymbol;
+        c->styles[0]->size = nPenSize;
+        c->styles[0]->width = nPenSize;
       }
-#else /* OGR Style C++ */
-      {
-          OGRStyleBrush *poBrushStyle = (OGRStyleBrush*)poStylePart;
-
-          const char *pszBrushName = poBrushStyle->Id(bIsNull);
-          if (bIsNull) pszBrushName = NULL;
-
-          /* We need 1 style */
-          if (msMaybeAllocateClassStyle(c, 0))
-          {
-#if GDAL_VERSION_NUM >= 1500 /* Use OGR Style C API */
-              OGR_ST_Destroy(hStylePart);
-#else
-              delete poStylePart;
-#endif              
-              return(MS_FAILURE);
-          }
 
-          // Check for Brush Pattern "ogr-brush-1": the invisible fill
-          // If that's what we have then set fill color to -1
-          if (pszBrushName && strstr(pszBrushName, "ogr-brush-1") != NULL)
-          {
-              MS_INIT_COLOR(c->styles[0]->color, -1, -1, -1, 255);
-          }
-          else
-          {
-              bIsBrush = TRUE;
-              const char *pszColor = poBrushStyle->ForeColor(bIsNull);
-              if (!bIsNull && poBrushStyle->GetRGBFromString(pszColor,r,g,b,t))
-              {
-                  MS_INIT_COLOR(c->styles[0]->color, r, g, b, t);
-                  if (layer->debug >= MS_DEBUGLEVEL_VVV)
-                      msDebug("** BRUSH COLOR = %d %d %d **\n", r,g,b);
-              }
-
-              pszColor = poBrushStyle->BackColor(bIsNull);
-              if (!bIsNull && poBrushStyle->GetRGBFromString(pszColor,r,g,b,t))
-              {
-                  MS_INIT_COLOR(c->styles[0]->backgroundcolor, r, g, b, t);
-              }
-
-              // Symbol name mapping:
-              // First look for the native symbol name, then the ogr-...
-              // generic name.  
-              // If none provided or found then use 0: solid fill
-          
-              const char *pszName = poBrushStyle->Id(bIsNull);
-              if (bIsNull)
-                  pszName = NULL;
-              c->styles[0]->symbol = msOGRGetSymbolId(&(map->symbolset), 
-                                                      pszName, NULL, MS_FALSE);
-          }
+    } else if (eStylePartType == OGRSTCBrush) {
+      OGRStyleToolH hBrushStyle = hStylePart;
+
+      const char *pszBrushName = OGR_ST_GetParamStr(hBrushStyle,
+                                 OGRSTBrushId,
+                                 &bIsNull);
+      if (bIsNull) pszBrushName = NULL;
+
+      /* We need 1 style */
+      if (msMaybeAllocateClassStyle(c, 0)) {
+        OGR_ST_Destroy(hStylePart);
+        return(MS_FAILURE);
       }
-#endif /* OGRStyle C API */
-      else if (eStylePartType == OGRSTCSymbol)
-#if GDAL_VERSION_NUM >= 1500 /* Use OGR Style C API */
-      {
-          OGRStyleToolH hSymbolStyle = hStylePart;
-
-          /* We need 1 style */
-          if (msMaybeAllocateClassStyle(c, 0))
-          {
-#if GDAL_VERSION_NUM >= 1500 /* Use OGR Style C API */
-              OGR_ST_Destroy(hStylePart);
-#else
-              delete poStylePart;
-#endif
-              return(MS_FAILURE);
-          }
 
-          const char *pszColor = OGR_ST_GetParamStr(hSymbolStyle, 
-                                                    OGRSTSymbolColor,
-                                                    &bIsNull);
-          if (!bIsNull && OGR_ST_GetRGBFromString(hSymbolStyle, 
-                                                  pszColor,
-                                                  &r, &g, &b, &t))
-          {
-              MS_INIT_COLOR(c->styles[0]->color, r, g, b, t);
-          }
+      // Check for Brush Pattern "ogr-brush-1": the invisible fill
+      // If that's what we have then set fill color to -1
+      if (pszBrushName && strstr(pszBrushName, "ogr-brush-1") != NULL) {
+        MS_INIT_COLOR(c->styles[0]->color, -1, -1, -1, 255);
+      } else {
+        bIsBrush = TRUE;
+        const char *pszColor = OGR_ST_GetParamStr(hBrushStyle,
+                               OGRSTBrushFColor,
+                               &bIsNull);
+        if (!bIsNull && OGR_ST_GetRGBFromString(hBrushStyle,
+                                                pszColor,
+                                                &r, &g, &b, &t)) {
+          MS_INIT_COLOR(c->styles[0]->color, r, g, b, t);
 
-#if GDAL_VERSION_NUM >= 1600              
-          pszColor = OGR_ST_GetParamStr(hSymbolStyle,
-                                        OGRSTSymbolOColor,
-                                        &bIsNull);
-          if (!bIsNull && OGR_ST_GetRGBFromString(hSymbolStyle,
-                                                  pszColor,
-                                                  &r, &g, &b, &t))
-          {
-              MS_INIT_COLOR(c->styles[0]->outlinecolor, r, g, b, t);
-          }
-#endif /* GDAL_VERSION_NUM >= 1600 */
-          c->styles[0]->angle = OGR_ST_GetParamNum(hSymbolStyle,
-                                                   OGRSTSymbolAngle,
-                                                   &bIsNull);
-          dfTmp = OGR_ST_GetParamNum(hSymbolStyle, OGRSTSymbolSize, &bIsNull);
-          if (!bIsNull)
-            c->styles[0]->size = dfTmp;
-
-          // Symbol name mapping:
-          // First look for the native symbol name, then the ogr-...
-          // generic name, and in last resort try "default-marker" if
-          // provided by user.
-          const char *pszName = OGR_ST_GetParamStr(hSymbolStyle, 
-                                                   OGRSTSymbolId, 
-                                                   &bIsNull);
-          if (bIsNull)
-              pszName = NULL;
-
-          try_addimage_if_notfound = MS_FALSE;
-#ifdef USE_CURL
-          if (pszName && strncasecmp(pszName, "http", 4) == 0)
-            try_addimage_if_notfound =MS_TRUE;
-#endif
-          if (!c->styles[0]->symbolname)
-            c->styles[0]->symbol = msOGRGetSymbolId(&(map->symbolset),
-                                                    pszName, 
-                                                    "default-marker",  try_addimage_if_notfound);
+          if (layer->debug >= MS_DEBUGLEVEL_VVV)
+            msDebug("** BRUSH COLOR = %d %d %d **\n", r,g,b);
+        }
+
+        pszColor = OGR_ST_GetParamStr(hBrushStyle,
+                                      OGRSTBrushBColor, &bIsNull);
+        if (!bIsNull && OGR_ST_GetRGBFromString(hBrushStyle,
+                                                pszColor,
+                                                &r, &g, &b, &t)) {
+          MS_INIT_COLOR(c->styles[0]->backgroundcolor, r, g, b, t);
+        }
+
+        // Symbol name mapping:
+        // First look for the native symbol name, then the ogr-...
+        // generic name.
+        // If none provided or found then use 0: solid fill
+
+        const char *pszName = OGR_ST_GetParamStr(hBrushStyle,
+                              OGRSTBrushId,
+                              &bIsNull);
+        c->styles[0]->symbol = msOGRGetSymbolId(&(map->symbolset),
+                                                pszName, NULL, MS_FALSE);
       }
-#else /* OGR Style C++ */
-      {
-          OGRStyleSymbol *poSymbolStyle = (OGRStyleSymbol*)poStylePart;
-
-          /* We need 1 style */
-          if (msMaybeAllocateClassStyle(c, 0))
-          {
-#if GDAL_VERSION_NUM >= 1500 /* Use OGR Style C API */
-              OGR_ST_Destroy(hStylePart);
-#else
-              delete poStylePart;
-#endif
-              return(MS_FAILURE);
-          }
+    } else if (eStylePartType == OGRSTCSymbol) {
+      OGRStyleToolH hSymbolStyle = hStylePart;
 
-          const char *pszColor = poSymbolStyle->Color(bIsNull);
-          if (!bIsNull && poSymbolStyle->GetRGBFromString(pszColor,r,g,b,t))
-          {
-              MS_INIT_COLOR(c->styles[0]->color, r, g, b, t);
-          }
+      /* We need 1 style */
+      if (msMaybeAllocateClassStyle(c, 0)) {
+        OGR_ST_Destroy(hStylePart);
+        return(MS_FAILURE);
+      }
 
-          c->styles[0]->angle = poSymbolStyle->Angle(bIsNull);
-          
-          dfTmp = poSymbolStyle->Size(bIsNull);
-          if (!bIsNull)
-            c->styles[0]->size = dfTmp;
-
-          // Symbol name mapping:
-          // First look for the native symbol name, then the ogr-...
-          // generic name, and in last resort try "default-marker" if
-          // provided by user.
-          const char *pszName = poSymbolStyle->Id(bIsNull);
-          if (bIsNull)
-              pszName = NULL;
-
-          try_addimage_if_notfound = MS_FALSE;
-#ifdef USE_CURL
-          if (pszName && strncasecmp(pszName, "http", 4) == 0)
-            try_addimage_if_notfound =MS_TRUE;
-#endif
-          c->styles[0]->symbol = msOGRGetSymbolId(&(map->symbolset),
-                                                pszName, 
-                                                  "default-marker", try_addimage_if_notfound);
+      const char *pszColor = OGR_ST_GetParamStr(hSymbolStyle,
+                             OGRSTSymbolColor,
+                             &bIsNull);
+      if (!bIsNull && OGR_ST_GetRGBFromString(hSymbolStyle,
+                                              pszColor,
+                                              &r, &g, &b, &t)) {
+        MS_INIT_COLOR(c->styles[0]->color, r, g, b, t);
       }
-#endif /* OGRStyle C API */
 
-#if GDAL_VERSION_NUM >= 1500 /* Use OGR Style C API */
-      OGR_ST_Destroy(hStylePart);
-#else
-      delete poStylePart;
+#if GDAL_VERSION_NUM >= 1600
+      pszColor = OGR_ST_GetParamStr(hSymbolStyle,
+                                    OGRSTSymbolOColor,
+                                    &bIsNull);
+      if (!bIsNull && OGR_ST_GetRGBFromString(hSymbolStyle,
+                                              pszColor,
+                                              &r, &g, &b, &t)) {
+        MS_INIT_COLOR(c->styles[0]->outlinecolor, r, g, b, t);
+      }
+#endif /* GDAL_VERSION_NUM >= 1600 */
+      c->styles[0]->angle = OGR_ST_GetParamNum(hSymbolStyle,
+                            OGRSTSymbolAngle,
+                            &bIsNull);
+      dfTmp = OGR_ST_GetParamNum(hSymbolStyle, OGRSTSymbolSize, &bIsNull);
+      if (!bIsNull)
+        c->styles[0]->size = dfTmp;
+
+      // Symbol name mapping:
+      // First look for the native symbol name, then the ogr-...
+      // generic name, and in last resort try "default-marker" if
+      // provided by user.
+      const char *pszName = OGR_ST_GetParamStr(hSymbolStyle,
+                            OGRSTSymbolId,
+                            &bIsNull);
+      if (bIsNull)
+        pszName = NULL;
+
+      try_addimage_if_notfound = MS_FALSE;
+#ifdef USE_CURL
+      if (pszName && strncasecmp(pszName, "http", 4) == 0)
+        try_addimage_if_notfound =MS_TRUE;
 #endif
-      
+      if (!c->styles[0]->symbolname)
+        c->styles[0]->symbol = msOGRGetSymbolId(&(map->symbolset),
+                                                pszName,
+                                                "default-marker",  try_addimage_if_notfound);
     }
-    return MS_SUCCESS;
+
+    OGR_ST_Destroy(hStylePart);
+
+  }
+  return MS_SUCCESS;
 }
 #endif /* USE_OGR */
 
@@ -3532,7 +2783,7 @@ static int msOGRUpdateStyle(OGRStyleMgr *poStyleMgr, mapObj *map, layerObj *laye
  *                     msOGRLayerGetAutoStyle()
  *
  * Fills a classObj with style info from the specified shape.
- * For optimal results, this should be called immediately after 
+ * For optimal results, this should be called immediately after
  * GetNextShape() or GetShape() so that the shape doesn't have to be read
  * twice.
  *
@@ -3545,73 +2796,62 @@ static int msOGRLayerGetAutoStyle(mapObj *map, layerObj *layer, classObj *c,
 #ifdef USE_OGR
   msOGRFileInfo *psInfo =(msOGRFileInfo*)layer->layerinfo;
 
-  if (psInfo == NULL || psInfo->hLayer == NULL)
-  {
-    msSetError(MS_MISCERR, "Assertion failed: OGR layer not opened!!!", 
+  if (psInfo == NULL || psInfo->hLayer == NULL) {
+    msSetError(MS_MISCERR, "Assertion failed: OGR layer not opened!!!",
                "msOGRLayerGetAutoStyle()");
     return(MS_FAILURE);
   }
 
-  if( layer->tileindex != NULL )
-  {
-      if( (psInfo->poCurTile == NULL || shape->tileindex != psInfo->poCurTile->nTileId)
-          && msOGRFileReadTile( layer, psInfo ) != MS_SUCCESS )
-          return MS_FAILURE;
-      
-      psInfo = psInfo->poCurTile;
+  if( layer->tileindex != NULL ) {
+    if( (psInfo->poCurTile == NULL || shape->tileindex != psInfo->poCurTile->nTileId)
+        && msOGRFileReadTile( layer, psInfo ) != MS_SUCCESS )
+      return MS_FAILURE;
+
+    psInfo = psInfo->poCurTile;
   }
 
-/* ------------------------------------------------------------------
- * Read shape or reuse ref. to last shape read.
- * ------------------------------------------------------------------ */
+  /* ------------------------------------------------------------------
+   * Read shape or reuse ref. to last shape read.
+   * ------------------------------------------------------------------ */
   ACQUIRE_OGR_LOCK;
-  if (psInfo->hLastFeature == NULL || 
-      psInfo->last_record_index_read != shape->resultindex)
-  {
-      RELEASE_OGR_LOCK;
-      msSetError(MS_MISCERR, 
-                 "Assertion failed: AutoStyle not requested on loaded shape.",
-                 "msOGRLayerGetAutoStyle()");
-      return(MS_FAILURE);
+  if (psInfo->hLastFeature == NULL ||
+      psInfo->last_record_index_read != shape->resultindex) {
+    RELEASE_OGR_LOCK;
+    msSetError(MS_MISCERR,
+               "Assertion failed: AutoStyle not requested on loaded shape.",
+               "msOGRLayerGetAutoStyle()");
+    return(MS_FAILURE);
   }
 
-/* ------------------------------------------------------------------
- * Reset style info in the class to defaults
- * the only members we don't touch are name, expression, and join/query stuff
- * ------------------------------------------------------------------ */
+  /* ------------------------------------------------------------------
+   * Reset style info in the class to defaults
+   * the only members we don't touch are name, expression, and join/query stuff
+   * ------------------------------------------------------------------ */
   resetClassStyle(c);
   if (msMaybeAllocateClassStyle(c, 0)) {
-      RELEASE_OGR_LOCK;
-      return(MS_FAILURE);
+    RELEASE_OGR_LOCK;
+    return(MS_FAILURE);
   }
 
   // __TODO__ label cache incompatible with styleitem feature.
   layer->labelcache = MS_OFF;
 
   int nRetVal = MS_SUCCESS;
-  if (psInfo->hLastFeature)
-  {
-#if GDAL_VERSION_NUM >= 1500 /* Use OGR Style C API */
-      OGRStyleMgrH hStyleMgr = OGR_SM_Create(NULL);
-      OGR_SM_InitFromFeature(hStyleMgr, psInfo->hLastFeature);
-      nRetVal = msOGRUpdateStyle(hStyleMgr, map, layer, c);
-      OGR_SM_Destroy(hStyleMgr);
-#else /* OGRStyle C++ */
-      OGRStyleMgr *poStyleMgr = new OGRStyleMgr(NULL);
-      poStyleMgr->InitFromFeature((OGRFeature *)psInfo->hLastFeature);
-      nRetVal = msOGRUpdateStyle(poStyleMgr, map, layer, c);
-      delete poStyleMgr;
-#endif /* OGRStyle C API */
+  if (psInfo->hLastFeature) {
+    OGRStyleMgrH hStyleMgr = OGR_SM_Create(NULL);
+    OGR_SM_InitFromFeature(hStyleMgr, psInfo->hLastFeature);
+    nRetVal = msOGRUpdateStyle(hStyleMgr, map, layer, c);
+    OGR_SM_Destroy(hStyleMgr);
   }
 
   RELEASE_OGR_LOCK;
   return nRetVal;
 #else
-/* ------------------------------------------------------------------
- * OGR Support not included...
- * ------------------------------------------------------------------ */
+  /* ------------------------------------------------------------------
+   * OGR Support not included...
+   * ------------------------------------------------------------------ */
 
-  msSetError(MS_MISCERR, "OGR support is not available.", 
+  msSetError(MS_MISCERR, "OGR support is not available.",
              "msOGRLayerGetAutoStyle()");
   return(MS_FAILURE);
 
@@ -3623,7 +2863,7 @@ static int msOGRLayerGetAutoStyle(mapObj *map, layerObj *layer, classObj *c,
  *                     msOGRUpdateStyleFromString()
  *
  * Fills a classObj with style info from the specified style string.
- * For optimal results, this should be called immediately after 
+ * For optimal results, this should be called immediately after
  * GetNextShape() or GetShape() so that the shape doesn't have to be read
  * twice.
  *
@@ -3631,45 +2871,38 @@ static int msOGRLayerGetAutoStyle(mapObj *map, layerObj *layer, classObj *c,
  * the next call and that shouldn't be freed by the caller.
  **********************************************************************/
 int msOGRUpdateStyleFromString(mapObj *map, layerObj *layer, classObj *c,
-                                  const char *stylestring)
+                               const char *stylestring)
 {
-#ifdef USE_OGR 
-/* ------------------------------------------------------------------
- * Reset style info in the class to defaults
- * the only members we don't touch are name, expression, and join/query stuff
- * ------------------------------------------------------------------ */
-    resetClassStyle(c);
-    if (msMaybeAllocateClassStyle(c, 0)) {
-      return(MS_FAILURE);
-    }
+#ifdef USE_OGR
+  /* ------------------------------------------------------------------
+   * Reset style info in the class to defaults
+   * the only members we don't touch are name, expression, and join/query stuff
+   * ------------------------------------------------------------------ */
+  resetClassStyle(c);
+  if (msMaybeAllocateClassStyle(c, 0)) {
+    return(MS_FAILURE);
+  }
 
-    // __TODO__ label cache incompatible with styleitem feature.
-    layer->labelcache = MS_OFF;
+  // __TODO__ label cache incompatible with styleitem feature.
+  layer->labelcache = MS_OFF;
 
-    int nRetVal = MS_SUCCESS;
+  int nRetVal = MS_SUCCESS;
 
-    ACQUIRE_OGR_LOCK;
+  ACQUIRE_OGR_LOCK;
 
-#if GDAL_VERSION_NUM >= 1500 /* Use OGR Style C API */
-    OGRStyleMgrH hStyleMgr = OGR_SM_Create(NULL);
-    OGR_SM_InitStyleString(hStyleMgr, stylestring);
-    nRetVal = msOGRUpdateStyle(hStyleMgr, map, layer, c);
-    OGR_SM_Destroy(hStyleMgr);
-#else /* OGRStyle C++ */
-    OGRStyleMgr *poStyleMgr = new OGRStyleMgr(NULL);
-    poStyleMgr->InitStyleString(stylestring);
-    nRetVal = msOGRUpdateStyle(poStyleMgr, map, layer, c);
-    delete poStyleMgr;
-#endif /* OGRStyle C API */
-    
-    RELEASE_OGR_LOCK;
-    return nRetVal;
+  OGRStyleMgrH hStyleMgr = OGR_SM_Create(NULL);
+  OGR_SM_InitStyleString(hStyleMgr, stylestring);
+  nRetVal = msOGRUpdateStyle(hStyleMgr, map, layer, c);
+  OGR_SM_Destroy(hStyleMgr);
+
+  RELEASE_OGR_LOCK;
+  return nRetVal;
 #else
-/* ------------------------------------------------------------------
- * OGR Support not included...
- * ------------------------------------------------------------------ */
+  /* ------------------------------------------------------------------
+   * OGR Support not included...
+   * ------------------------------------------------------------------ */
 
-  msSetError(MS_MISCERR, "OGR support is not available.", 
+  msSetError(MS_MISCERR, "OGR support is not available.",
              "msOGRLayerGetAutoStyle()");
   return(MS_FAILURE);
 
@@ -3684,16 +2917,13 @@ void msOGRCleanup( void )
 
 {
 #if defined(USE_OGR)
-    ACQUIRE_OGR_LOCK;
-    if( bOGRDriversRegistered == MS_TRUE )
-    {
-#if GDAL_VERSION_NUM >= 1400
-        CPLPopErrorHandler();
-        OGRCleanupAll();
-        bOGRDriversRegistered = MS_FALSE;
-#endif
-    }
-    RELEASE_OGR_LOCK;
+  ACQUIRE_OGR_LOCK;
+  if( bOGRDriversRegistered == MS_TRUE ) {
+    CPLPopErrorHandler();
+    OGRCleanupAll();
+    bOGRDriversRegistered = MS_FALSE;
+  }
+  RELEASE_OGR_LOCK;
 #endif
 }
 
@@ -3702,26 +2932,25 @@ void msOGRCleanup( void )
 /************************************************************************/
 char *msOGREscapeSQLParam(layerObj *layer, const char *pszString)
 {
-    char* pszEscapedStr =NULL;
 #ifdef USE_OGR
-    if(layer && pszString && strlen(pszString) > 0)
-    {
-        char* pszEscapedOGRStr =  CPLEscapeString(pszString, strlen(pszString),  
-		                                    CPLES_SQL ); 
-	pszEscapedStr = msStrdup(pszEscapedOGRStr);
-        CPLFree(pszEscapedOGRStr);
-	return pszEscapedStr; 
-    }
+  char* pszEscapedStr =NULL;
+  if(layer && pszString && strlen(pszString) > 0) {
+    char* pszEscapedOGRStr =  CPLEscapeString(pszString, strlen(pszString),
+                              CPLES_SQL );
+    pszEscapedStr = msStrdup(pszEscapedOGRStr);
+    CPLFree(pszEscapedOGRStr);
+  }
+  return pszEscapedStr;
 #else
-/* ------------------------------------------------------------------
- * OGR Support not included...
- * ------------------------------------------------------------------ */
+  /* ------------------------------------------------------------------
+   * OGR Support not included...
+   * ------------------------------------------------------------------ */
 
-  msSetError(MS_MISCERR, "OGR support is not available.", 
+  msSetError(MS_MISCERR, "OGR support is not available.",
              "msOGREscapeSQLParam()");
   return NULL;
 
-#endif /* USE_OGR */  
+#endif /* USE_OGR */
 }
 
 
@@ -3730,32 +2959,29 @@ char *msOGREscapeSQLParam(layerObj *layer, const char *pszString)
 /************************************************************************/
 char *msOGREscapePropertyName(layerObj *layer, const char *pszString)
 {
-    char* pszEscapedStr =NULL;
-    int i =0;
 #ifdef USE_OGR
-    if(layer && pszString && strlen(pszString) > 0)
-    {
-        unsigned char ch;
-        for(i=0; (ch = ((unsigned char*)pszString)[i]) != '\0'; i++)
-        {
-            if ( !(isalnum(ch) || ch == '_' || ch > 127) )
-            {
-                return msStrdup("invalid_property_name");
-            }
-        }
-        pszEscapedStr = msStrdup(pszString);
+  char* pszEscapedStr =NULL;
+  int i =0;
+  if(layer && pszString && strlen(pszString) > 0) {
+    unsigned char ch;
+    for(i=0; (ch = ((unsigned char*)pszString)[i]) != '\0'; i++) {
+      if ( !(isalnum(ch) || ch == '_' || ch > 127) ) {
+        return msStrdup("invalid_property_name");
+      }
     }
-    return pszEscapedStr;
+    pszEscapedStr = msStrdup(pszString);
+  }
+  return pszEscapedStr;
 #else
-/* ------------------------------------------------------------------
- * OGR Support not included...
- * ------------------------------------------------------------------ */
+  /* ------------------------------------------------------------------
+   * OGR Support not included...
+   * ------------------------------------------------------------------ */
 
-  msSetError(MS_MISCERR, "OGR support is not available.", 
+  msSetError(MS_MISCERR, "OGR support is not available.",
              "msOGREscapePropertyName()");
   return NULL;
 
-#endif /* USE_OGR */  
+#endif /* USE_OGR */
 }
 /************************************************************************/
 /*                  msOGRLayerInitializeVirtualTable()                  */
@@ -3763,31 +2989,31 @@ char *msOGREscapePropertyName(layerObj *layer, const char *pszString)
 int
 msOGRLayerInitializeVirtualTable(layerObj *layer)
 {
-    assert(layer != NULL);
-    assert(layer->vtable != NULL);
-
-    layer->vtable->LayerInitItemInfo = msOGRLayerInitItemInfo;
-    layer->vtable->LayerFreeItemInfo = msOGRLayerFreeItemInfo;
-    layer->vtable->LayerOpen = msOGRLayerOpenVT;
-    layer->vtable->LayerIsOpen = msOGRLayerIsOpen;
-    layer->vtable->LayerWhichShapes = msOGRLayerWhichShapes;
-    layer->vtable->LayerNextShape = msOGRLayerNextShape;
-    layer->vtable->LayerGetShape = msOGRLayerGetShape;
-    layer->vtable->LayerClose = msOGRLayerClose;
-    layer->vtable->LayerGetItems = msOGRLayerGetItems;
-    layer->vtable->LayerGetExtent = msOGRLayerGetExtent;
-    layer->vtable->LayerGetAutoStyle = msOGRLayerGetAutoStyle;
-    /* layer->vtable->LayerCloseConnection, use default */
-    layer->vtable->LayerApplyFilterToLayer = msLayerApplyCondSQLFilterToLayer;
-    layer->vtable->LayerSetTimeFilter = msLayerMakeBackticsTimeFilter;
-    /* layer->vtable->LayerCreateItems, use default */
-    /* layer->vtable->LayerGetNumFeatures, use default */
-    /* layer->vtable->LayerGetAutoProjection, use defaut*/
-
-    layer->vtable->LayerEscapeSQLParam = msOGREscapeSQLParam;
-    layer->vtable->LayerEscapePropertyName = msOGREscapePropertyName;
+  assert(layer != NULL);
+  assert(layer->vtable != NULL);
+
+  layer->vtable->LayerInitItemInfo = msOGRLayerInitItemInfo;
+  layer->vtable->LayerFreeItemInfo = msOGRLayerFreeItemInfo;
+  layer->vtable->LayerOpen = msOGRLayerOpenVT;
+  layer->vtable->LayerIsOpen = msOGRLayerIsOpen;
+  layer->vtable->LayerWhichShapes = msOGRLayerWhichShapes;
+  layer->vtable->LayerNextShape = msOGRLayerNextShape;
+  layer->vtable->LayerGetShape = msOGRLayerGetShape;
+  layer->vtable->LayerClose = msOGRLayerClose;
+  layer->vtable->LayerGetItems = msOGRLayerGetItems;
+  layer->vtable->LayerGetExtent = msOGRLayerGetExtent;
+  layer->vtable->LayerGetAutoStyle = msOGRLayerGetAutoStyle;
+  /* layer->vtable->LayerCloseConnection, use default */
+  layer->vtable->LayerApplyFilterToLayer = msLayerApplyCondSQLFilterToLayer;
+  layer->vtable->LayerSetTimeFilter = msLayerMakeBackticsTimeFilter;
+  /* layer->vtable->LayerCreateItems, use default */
+  /* layer->vtable->LayerGetNumFeatures, use default */
+  /* layer->vtable->LayerGetAutoProjection, use defaut*/
+
+  layer->vtable->LayerEscapeSQLParam = msOGREscapeSQLParam;
+  layer->vtable->LayerEscapePropertyName = msOGREscapePropertyName;
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 /************************************************************************/
@@ -3796,41 +3022,35 @@ msOGRLayerInitializeVirtualTable(layerObj *layer)
 shapeObj *msOGRShapeFromWKT(const char *string)
 {
 #ifdef USE_OGR
-    OGRGeometryH hGeom = NULL;
-    shapeObj *shape=NULL;
-    
-    if(!string) 
-        return NULL;
-    
-    ACQUIRE_OLD_OGR_LOCK;
-    if( OGR_G_CreateFromWkt( (char **)&string, NULL, &hGeom ) != OGRERR_NONE )
-    {
-        msSetError(MS_OGRERR, "Failed to parse WKT string.", 
-                   "msOGRShapeFromWKT()" );
-        RELEASE_OLD_OGR_LOCK;
-        return NULL;
-    }
+  OGRGeometryH hGeom = NULL;
+  shapeObj *shape=NULL;
+
+  if(!string)
+    return NULL;
 
-    /* Initialize a corresponding shapeObj */
+  if( OGR_G_CreateFromWkt( (char **)&string, NULL, &hGeom ) != OGRERR_NONE ) {
+    msSetError(MS_OGRERR, "Failed to parse WKT string.",
+               "msOGRShapeFromWKT()" );
+    return NULL;
+  }
 
-    shape = (shapeObj *) malloc(sizeof(shapeObj));
-    msInitShape(shape);
+  /* Initialize a corresponding shapeObj */
 
-    /* translate WKT into an OGRGeometry. */
-  
-    if( msOGRGeometryToShape( hGeom, shape, 
-                              wkbFlatten(OGR_G_GetGeometryType(hGeom)) )
-                              == MS_FAILURE )
-    {
-        RELEASE_OLD_OGR_LOCK;
-        free( shape );
-        return NULL;
-    }
+  shape = (shapeObj *) malloc(sizeof(shapeObj));
+  msInitShape(shape);
+
+  /* translate WKT into an OGRGeometry. */
 
-    OGR_G_DestroyGeometry( hGeom );
+  if( msOGRGeometryToShape( hGeom, shape,
+                            wkbFlatten(OGR_G_GetGeometryType(hGeom)) )
+      == MS_FAILURE ) {
+    free( shape );
+    return NULL;
+  }
 
-    RELEASE_OLD_OGR_LOCK;
-    return shape;
+  OGR_G_DestroyGeometry( hGeom );
+
+  return shape;
 #else
   msSetError(MS_OGRERR, "OGR support is not available.","msOGRShapeFromWKT()");
   return NULL;
@@ -3843,141 +3063,86 @@ shapeObj *msOGRShapeFromWKT(const char *string)
 char *msOGRShapeToWKT(shapeObj *shape)
 {
 #ifdef USE_OGR
-    OGRGeometryH hGeom = NULL;
-    int          i;
-    char        *wkt = NULL;
+  OGRGeometryH hGeom = NULL;
+  int          i;
+  char        *wkt = NULL;
 
-    if(!shape) 
-        return NULL;
+  if(!shape)
+    return NULL;
 
-    ACQUIRE_OLD_OGR_LOCK;
-    if( shape->type == MS_SHAPE_POINT && shape->numlines == 1
-        && shape->line[0].numpoints == 1 )
-    {
-        hGeom = OGR_G_CreateGeometry( wkbPoint );
-#if GDAL_VERSION_NUM >= 1310
-        OGR_G_SetPoint_2D( hGeom, 0, 
-                           shape->line[0].point[0].x, 
-                           shape->line[0].point[0].y );
-#else
-        OGR_G_SetPoint( hGeom, 0, 
-                        shape->line[0].point[0].x, 
-                        shape->line[0].point[0].y,
-                        0.0 );
-#endif
+  if( shape->type == MS_SHAPE_POINT && shape->numlines == 1
+      && shape->line[0].numpoints == 1 ) {
+    hGeom = OGR_G_CreateGeometry( wkbPoint );
+    OGR_G_SetPoint_2D( hGeom, 0,
+                       shape->line[0].point[0].x,
+                       shape->line[0].point[0].y );
+  } else if( shape->type == MS_SHAPE_POINT && shape->numlines == 1
+             && shape->line[0].numpoints > 1 ) {
+    hGeom = OGR_G_CreateGeometry( wkbMultiPoint );
+    for( i = 0; i < shape->line[0].numpoints; i++ ) {
+      OGRGeometryH hPoint;
+
+      hPoint = OGR_G_CreateGeometry( wkbPoint );
+      OGR_G_SetPoint_2D( hPoint, 0,
+                         shape->line[0].point[i].x,
+                         shape->line[0].point[i].y );
+      OGR_G_AddGeometryDirectly( hGeom, hPoint );
     }
-    else if( shape->type == MS_SHAPE_POINT && shape->numlines == 1 
-             && shape->line[0].numpoints > 1 )
-    {
-        hGeom = OGR_G_CreateGeometry( wkbMultiPoint );
-        for( i = 0; i < shape->line[0].numpoints; i++ )
-        {
-            OGRGeometryH hPoint;
-            
-            hPoint = OGR_G_CreateGeometry( wkbPoint );
-#if GDAL_VERSION_NUM >= 1310
-            OGR_G_SetPoint_2D( hPoint, 0, 
-                               shape->line[0].point[i].x, 
-                               shape->line[0].point[i].y );
-#else
-            OGR_G_SetPoint( hPoint, 0, 
-                            shape->line[0].point[i].x, 
-                            shape->line[0].point[i].y,
-                            0.0 );
-#endif
-            OGR_G_AddGeometryDirectly( hGeom, hPoint );
-        }
+  } else if( shape->type == MS_SHAPE_LINE && shape->numlines == 1 ) {
+    hGeom = OGR_G_CreateGeometry( wkbLineString );
+    for( i = 0; i < shape->line[0].numpoints; i++ ) {
+      OGR_G_AddPoint_2D( hGeom,
+                         shape->line[0].point[i].x,
+                         shape->line[0].point[i].y );
     }
-    else if( shape->type == MS_SHAPE_LINE && shape->numlines == 1 )
-    {
-        hGeom = OGR_G_CreateGeometry( wkbLineString );
-        for( i = 0; i < shape->line[0].numpoints; i++ )
-        {
-#if GDAL_VERSION_NUM >= 1310
-            OGR_G_AddPoint_2D( hGeom, 
-                               shape->line[0].point[i].x, 
-                               shape->line[0].point[i].y );
-#else
-            OGR_G_AddPoint( hGeom, 
-                            shape->line[0].point[i].x, 
-                            shape->line[0].point[i].y,
-                            0.0 );
-#endif
-        }
+  } else if( shape->type == MS_SHAPE_LINE && shape->numlines > 1 ) {
+    OGRGeometryH hMultiLine = OGR_G_CreateGeometry( wkbMultiLineString );
+    int iLine;
+
+    for( iLine = 0; iLine < shape->numlines; iLine++ ) {
+      hGeom = OGR_G_CreateGeometry( wkbLineString );
+      for( i = 0; i < shape->line[iLine].numpoints; i++ ) {
+        OGR_G_AddPoint_2D( hGeom,
+                           shape->line[iLine].point[i].x,
+                           shape->line[iLine].point[i].y );
+      }
+
+      OGR_G_AddGeometryDirectly( hMultiLine, hGeom );
     }
-    else if( shape->type == MS_SHAPE_LINE && shape->numlines > 1 )
-    {
-        OGRGeometryH hMultiLine = OGR_G_CreateGeometry( wkbMultiLineString );
-        int iLine;
-
-        for( iLine = 0; iLine < shape->numlines; iLine++ )
-        {
-            hGeom = OGR_G_CreateGeometry( wkbLineString );
-            for( i = 0; i < shape->line[iLine].numpoints; i++ )
-            {
-#if GDAL_VERSION_NUM >= 1310
-                OGR_G_AddPoint_2D( hGeom, 
-                                   shape->line[iLine].point[i].x, 
-                                   shape->line[iLine].point[i].y );
-#else
-                OGR_G_AddPoint( hGeom, 
-                            shape->line[iLine].point[i].x, 
-                            shape->line[iLine].point[i].y,
-                            0.0 );
-#endif
-            }
 
-            OGR_G_AddGeometryDirectly( hMultiLine, hGeom );
-        }
+    hGeom = hMultiLine;
+  } else if( shape->type == MS_SHAPE_POLYGON ) {
+    int iLine;
 
-        hGeom = hMultiLine;
-    }
-    else if( shape->type == MS_SHAPE_POLYGON )
-    {
-        int iLine;
-
-        /* actually, it is pretty hard to be sure rings 1+ are interior */
-        hGeom = OGR_G_CreateGeometry( wkbPolygon );
-        for( iLine = 0; iLine < shape->numlines; iLine++ )
-        {
-            OGRGeometryH hRing;
-            hRing = OGR_G_CreateGeometry( wkbLinearRing );
-            
-            for( i = 0; i < shape->line[iLine].numpoints; i++ )
-            {
-#if GDAL_VERSION_NUM >= 1310
-                OGR_G_AddPoint_2D( hRing, 
-                                   shape->line[iLine].point[i].x, 
-                                   shape->line[iLine].point[i].y );
-#else
-                OGR_G_AddPoint( hRing, 
-                                shape->line[iLine].point[i].x, 
-                                shape->line[iLine].point[i].y, 
-                                0.0 );
-#endif
-            }
-            OGR_G_AddGeometryDirectly( hGeom, hRing );
-        }
-    }
-    else
-    {
-        msSetError(MS_OGRERR, "OGR support is not available.", "msOGRShapeToWKT()");
+    /* actually, it is pretty hard to be sure rings 1+ are interior */
+    hGeom = OGR_G_CreateGeometry( wkbPolygon );
+    for( iLine = 0; iLine < shape->numlines; iLine++ ) {
+      OGRGeometryH hRing;
+      hRing = OGR_G_CreateGeometry( wkbLinearRing );
+
+      for( i = 0; i < shape->line[iLine].numpoints; i++ ) {
+        OGR_G_AddPoint_2D( hRing,
+                           shape->line[iLine].point[i].x,
+                           shape->line[iLine].point[i].y );
+      }
+      OGR_G_AddGeometryDirectly( hGeom, hRing );
     }
+  } else {
+    msSetError(MS_OGRERR, "OGR support is not available.", "msOGRShapeToWKT()");
+  }
 
-    if( hGeom != NULL )
-    {
-        char *pszOGRWkt;
+  if( hGeom != NULL ) {
+    char *pszOGRWkt;
 
-        OGR_G_ExportToWkt( hGeom, &pszOGRWkt );
-        wkt = msStrdup( pszOGRWkt );
-        CPLFree( pszOGRWkt );
-    }
+    OGR_G_ExportToWkt( hGeom, &pszOGRWkt );
+    wkt = msStrdup( pszOGRWkt );
+    CPLFree( pszOGRWkt );
+  }
 
-    RELEASE_OLD_OGR_LOCK;
-    return wkt;
+  return wkt;
 #else
-    msSetError(MS_OGRERR, "OGR support is not available.", "msOGRShapeToWKT()");
-    return NULL;
+  msSetError(MS_OGRERR, "OGR support is not available.", "msOGRShapeToWKT()");
+  return NULL;
 #endif
 }
 
diff --git a/mapogroutput.c b/mapogroutput.c
index 0a321fa..0ee8692 100644
--- a/mapogroutput.c
+++ b/mapogroutput.c
@@ -14,16 +14,16 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
+ *
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  * DEALINGS IN THE SOFTWARE.
  **********************************************************************/
 
@@ -41,7 +41,7 @@
 #  include "cpl_string.h"
 #endif
 
-MS_CVSID("$Id$")
+
 
 #ifdef USE_OGR
 
@@ -52,40 +52,38 @@ MS_CVSID("$Id$")
 int msInitDefaultOGROutputFormat( outputFormatObj *format )
 
 {
-    OGRSFDriverH   hDriver;
-
-    msOGRInitialize();
-
-/* -------------------------------------------------------------------- */
-/*      check that this driver exists.  Note visiting drivers should    */
-/*      be pretty threadsafe so don't bother acquiring the GDAL         */
-/*      lock.                                                           */
-/* -------------------------------------------------------------------- */
-    hDriver = OGRGetDriverByName( format->driver+4 );
-    if( hDriver == NULL )
-    {
-        msSetError( MS_MISCERR, "No OGR driver named `%s' available.", 
-                    "msInitOGROutputFormat()", format->driver+4 );
-        return MS_FAILURE;
-    }
+  OGRSFDriverH   hDriver;
+
+  msOGRInitialize();
+
+  /* -------------------------------------------------------------------- */
+  /*      check that this driver exists.  Note visiting drivers should    */
+  /*      be pretty threadsafe so don't bother acquiring the GDAL         */
+  /*      lock.                                                           */
+  /* -------------------------------------------------------------------- */
+  hDriver = OGRGetDriverByName( format->driver+4 );
+  if( hDriver == NULL ) {
+    msSetError( MS_MISCERR, "No OGR driver named `%s' available.",
+                "msInitOGROutputFormat()", format->driver+4 );
+    return MS_FAILURE;
+  }
 
-    if( !OGR_Dr_TestCapability( hDriver, ODrCCreateDataSource ) )
-    {
-        msSetError( MS_MISCERR, "OGR `%s' driver does not support output.", 
-                    "msInitOGROutputFormat()", format->driver+4 );
-        return MS_FAILURE;
-    }
+  if( !OGR_Dr_TestCapability( hDriver, ODrCCreateDataSource ) ) {
+    msSetError( MS_MISCERR, "OGR `%s' driver does not support output.",
+                "msInitOGROutputFormat()", format->driver+4 );
+    return MS_FAILURE;
+  }
 
-/* -------------------------------------------------------------------- */
-/*      Initialize the object.                                          */
-/* -------------------------------------------------------------------- */
-    format->imagemode = MS_IMAGEMODE_FEATURE;
-    format->renderer = MS_RENDER_WITH_OGR;
+  /* -------------------------------------------------------------------- */
+  /*      Initialize the object.                                          */
+  /* -------------------------------------------------------------------- */
+  format->imagemode = MS_IMAGEMODE_FEATURE;
+  format->renderer = MS_RENDER_WITH_OGR;
 
-    /* perhaps we should eventually hardcode mimetypes and extensions
-       for some formats? */
+  /* perhaps we should eventually hardcode mimetypes and extensions
+     for some formats? */
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 /************************************************************************/
@@ -97,66 +95,59 @@ int msInitDefaultOGROutputFormat( outputFormatObj *format )
 
 char **msOGRRecursiveFileList( const char *path )
 {
-    char **file_list;
-    char **result_list = NULL;
-    int i, count, change;
-
-    file_list = CPLReadDir( path );
-    count = CSLCount(file_list);
-
-/* -------------------------------------------------------------------- */
-/*      Sort the file list so we always get them back in the same       */
-/*      order - it makes autotests more stable.                         */
-/* -------------------------------------------------------------------- */
-    do
-    {
-        change = 0;
-        for( i = 0; i < count-1; i++ )
-        {
-            if( strcasecmp(file_list[i],file_list[i+1]) > 0 )
-            {
-                char *temp = file_list[i];
-                file_list[i] = file_list[i+1];
-                file_list[i+1] = temp;
-                change = 1;
-            }
-        }
-    } while( change );
+  char **file_list;
+  char **result_list = NULL;
+  int i, count, change;
+
+  file_list = CPLReadDir( path );
+  count = CSLCount(file_list);
+
+  /* -------------------------------------------------------------------- */
+  /*      Sort the file list so we always get them back in the same       */
+  /*      order - it makes autotests more stable.                         */
+  /* -------------------------------------------------------------------- */
+  do {
+    change = 0;
+    for( i = 0; i < count-1; i++ ) {
+      if( strcasecmp(file_list[i],file_list[i+1]) > 0 ) {
+        char *temp = file_list[i];
+        file_list[i] = file_list[i+1];
+        file_list[i+1] = temp;
+        change = 1;
+      }
+    }
+  } while( change );
 
-/* -------------------------------------------------------------------- */
-/*      collect names we want and process subdirectories.               */
-/* -------------------------------------------------------------------- */
-    for( i = 0; i < count; i++ )
-    {
-        char full_filename[MS_MAXPATHLEN];
-        VSIStatBufL  sStatBuf;
+  /* -------------------------------------------------------------------- */
+  /*      collect names we want and process subdirectories.               */
+  /* -------------------------------------------------------------------- */
+  for( i = 0; i < count; i++ ) {
+    char full_filename[MS_MAXPATHLEN];
+    VSIStatBufL  sStatBuf;
 
-        if( EQUAL(file_list[i],".") || EQUAL(file_list[i],"..") )
-            continue;
+    if( EQUAL(file_list[i],".") || EQUAL(file_list[i],"..") )
+      continue;
 
-        strlcpy( full_filename, 
-                 CPLFormFilename( path, file_list[i], NULL ),
-                 sizeof(full_filename) );
+    strlcpy( full_filename,
+             CPLFormFilename( path, file_list[i], NULL ),
+             sizeof(full_filename) );
 
-        VSIStatL( full_filename, &sStatBuf );
+    VSIStatL( full_filename, &sStatBuf );
 
-        if( VSI_ISREG( sStatBuf.st_mode ) )
-        {
-            result_list = CSLAddString( result_list, full_filename );
-        }
-        else if( VSI_ISDIR( sStatBuf.st_mode ) )
-        {
-            char **subfiles = msOGRRecursiveFileList( full_filename );
+    if( VSI_ISREG( sStatBuf.st_mode ) ) {
+      result_list = CSLAddString( result_list, full_filename );
+    } else if( VSI_ISDIR( sStatBuf.st_mode ) ) {
+      char **subfiles = msOGRRecursiveFileList( full_filename );
 
-            result_list = CSLMerge( result_list, subfiles );
+      result_list = CSLMerge( result_list, subfiles );
 
-            CSLDestroy( subfiles );
-        }
+      CSLDestroy( subfiles );
     }
+  }
 
-    CSLDestroy( file_list );
+  CSLDestroy( file_list );
 
-    return result_list;
+  return result_list;
 }
 
 /************************************************************************/
@@ -165,278 +156,312 @@ char **msOGRRecursiveFileList( const char *path )
 static void msOGRCleanupDS( const char *datasource_name )
 
 {
-    char **file_list;
-    char path[MS_MAXPATHLEN];
-    int i;
-    
-    strlcpy( path, CPLGetPath( datasource_name ), sizeof(path) );
-    file_list = CPLReadDir( path );
-
-    for( i = 0; file_list != NULL && file_list[i] != NULL; i++ )
-    {
-        char full_filename[MS_MAXPATHLEN];
-        VSIStatBufL  sStatBuf;
-
-        if( EQUAL(file_list[i],".") || EQUAL(file_list[i],"..") )
-            continue;
-
-        strlcpy( full_filename, 
-                 CPLFormFilename( path, file_list[i], NULL ),
-                 sizeof(full_filename) );
-
-        VSIStatL( full_filename, &sStatBuf );
-
-        if( VSI_ISREG( sStatBuf.st_mode ) )
-        {
-            VSIUnlink( full_filename );
-        }
-        else if( VSI_ISDIR( sStatBuf.st_mode ) )
-        {
-            char fake_ds_name[MS_MAXPATHLEN];
-            strlcpy( fake_ds_name, 
-                     CPLFormFilename( full_filename, "abc.dat", NULL ),
-                     sizeof(fake_ds_name) );
-            msOGRCleanupDS( fake_ds_name );
-        }
+  char **file_list;
+  char path[MS_MAXPATHLEN];
+  int i;
+
+  strlcpy( path, CPLGetPath( datasource_name ), sizeof(path) );
+  file_list = CPLReadDir( path );
+
+  for( i = 0; file_list != NULL && file_list[i] != NULL; i++ ) {
+    char full_filename[MS_MAXPATHLEN];
+    VSIStatBufL  sStatBuf;
+
+    if( EQUAL(file_list[i],".") || EQUAL(file_list[i],"..") )
+      continue;
+
+    strlcpy( full_filename,
+             CPLFormFilename( path, file_list[i], NULL ),
+             sizeof(full_filename) );
+
+    VSIStatL( full_filename, &sStatBuf );
+
+    if( VSI_ISREG( sStatBuf.st_mode ) ) {
+      VSIUnlink( full_filename );
+    } else if( VSI_ISDIR( sStatBuf.st_mode ) ) {
+      char fake_ds_name[MS_MAXPATHLEN];
+      strlcpy( fake_ds_name,
+               CPLFormFilename( full_filename, "abc.dat", NULL ),
+               sizeof(fake_ds_name) );
+      msOGRCleanupDS( fake_ds_name );
     }
+  }
 
-    CSLDestroy( file_list );
+  CSLDestroy( file_list );
 
-    VSIRmdir( path );
+  VSIRmdir( path );
 }
 
 /************************************************************************/
 /*                          msOGRWriteShape()                           */
 /************************************************************************/
 
-static int msOGRWriteShape( layerObj *map_layer, OGRLayerH hOGRLayer, 
+static int msOGRWriteShape( layerObj *map_layer, OGRLayerH hOGRLayer,
                             shapeObj *shape, gmlItemListObj *item_list )
 
 {
-    OGRGeometryH hGeom = NULL;
-    OGRFeatureH hFeat;
-    OGRErr eErr;
-    int i, out_field;
-    OGRwkbGeometryType eLayerGType, eFeatureGType = wkbUnknown;
-
-/* -------------------------------------------------------------------- */
-/*      Transform point geometry.                                       */
-/* -------------------------------------------------------------------- */
-    if( shape->type == MS_SHAPE_POINT )
-    {
-        if( shape->numlines != 1 || shape->line[0].numpoints != 1 )
-        {
-            msSetError(MS_MISCERR, 
-                       "Failed on odd point geometry.", 
-                       "msOGRWriteShape()");
-            return MS_FAILURE;
-        }
-
-        hGeom = OGR_G_CreateGeometry( wkbPoint );
-        OGR_G_SetPoint( hGeom, 0, 
-                        shape->line[0].point[0].x,
-                        shape->line[0].point[0].y,
-                        0.0 );
+  OGRGeometryH hGeom = NULL;
+  OGRFeatureH hFeat;
+  OGRErr eErr;
+  int i, out_field;
+  OGRwkbGeometryType eLayerGType, eFeatureGType = wkbUnknown;
+
+  eLayerGType = OGR_FD_GetGeomType(OGR_L_GetLayerDefn(hOGRLayer));
+
+  /* -------------------------------------------------------------------- */
+  /*      Transform point geometry.                                       */
+  /* -------------------------------------------------------------------- */
+  if( shape->type == MS_SHAPE_POINT ) {
+    OGRGeometryH hMP = NULL;
+    int j;
+
+    if( shape->numlines < 1 ) {
+      msSetError(MS_MISCERR,
+                 "Failed on odd point geometry.",
+                 "msOGRWriteShape()");
+      return MS_FAILURE;
     }
 
-/* -------------------------------------------------------------------- */
-/*      Transform line geometry.                                        */
-/* -------------------------------------------------------------------- */
-    else if(  shape->type == MS_SHAPE_LINE )
-    {
-        OGRGeometryH hML = NULL;
-        int j;
+    if( shape->numlines > 1 )
+      hMP = OGR_G_CreateGeometry( wkbMultiPoint );
 
-        if( shape->numlines < 1 || shape->line[0].numpoints < 2 )
-        {
-            msSetError(MS_MISCERR, 
-                       "Failed on odd line geometry.", 
-                       "msOGRWriteShape()");
-            return MS_FAILURE;
-        }
+    for( j = 0; j < shape->numlines; j++ ) {
+      if( shape->line[j].numpoints != 1 ) {
+        msSetError(MS_MISCERR,
+                   "Failed on odd point geometry.",
+                   "msOGRWriteShape()");
+        return MS_FAILURE;
+      }
+
+      hGeom = OGR_G_CreateGeometry( wkbPoint );
+      OGR_G_SetPoint( hGeom, 0,
+                      shape->line[j].point[0].x,
+                      shape->line[j].point[0].y,
+#ifdef USE_POINT_Z_M
+                      shape->line[j].point[0].z
+#else
+                      0.0
+#endif
+                    );
 
-        if( shape->numlines > 1 )
-            hML = OGR_G_CreateGeometry( wkbMultiLineString );
-
-        for( j = 0; j < shape->numlines; j++ )
-        {
-            hGeom = OGR_G_CreateGeometry( wkbLineString );
-        
-            for( i = 0; i < shape->line[j].numpoints; i++ )
-            {
-                OGR_G_SetPoint( hGeom, i, 
-                                shape->line[j].point[i].x,
-                                shape->line[j].point[i].y,
-                                0.0 );
-            }
-
-            if( hML != NULL )
-            {
-                OGR_G_AddGeometryDirectly( hML, hGeom );
-                hGeom = hML;
-            }
-        }
+      if( hMP != NULL ) {
+        OGR_G_AddGeometryDirectly( hMP, hGeom );
+        hGeom = hMP;
+      }
+    }
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Transform line geometry.                                        */
+  /* -------------------------------------------------------------------- */
+  else if(  shape->type == MS_SHAPE_LINE ) {
+    OGRGeometryH hML = NULL;
+    int j;
+
+    if( shape->numlines < 1 || shape->line[0].numpoints < 2 ) {
+      msSetError(MS_MISCERR,
+                 "Failed on odd line geometry.",
+                 "msOGRWriteShape()");
+      return MS_FAILURE;
     }
 
-/* -------------------------------------------------------------------- */
-/*      Transform polygon geometry.                                     */
-/* -------------------------------------------------------------------- */
-    else if( shape->type == MS_SHAPE_POLYGON )
-    {
-        int iRing, iOuter;
-        int *outer_flags;
-        OGRGeometryH hMP;
-
-        if( shape->numlines < 1 )
-        {
-            msSetError(MS_MISCERR, 
-                       "Failed on odd polygon geometry.", 
-                       "msOGRWriteShape()");
-            return MS_FAILURE;
-        }
+    if( shape->numlines > 1 )
+      hML = OGR_G_CreateGeometry( wkbMultiLineString );
 
-        outer_flags = msGetOuterList( shape );
-        hMP = OGR_G_CreateGeometry( wkbMultiPolygon );
+    for( j = 0; j < shape->numlines; j++ ) {
+      hGeom = OGR_G_CreateGeometry( wkbLineString );
 
-        for( iOuter = 0; iOuter < shape->numlines; iOuter++ )
-        {
-            int *inner_flags;
-            OGRGeometryH hRing;
+      for( i = 0; i < shape->line[j].numpoints; i++ ) {
+        OGR_G_SetPoint( hGeom, i,
+                        shape->line[j].point[i].x,
+                        shape->line[j].point[i].y,
+#ifdef USE_POINT_Z_M
+                        shape->line[j].point[i].z
+#else
+                        0.0
+#endif
+                      );
+      }
 
-            if( !outer_flags[iOuter] )
-                continue;
+      if( hML != NULL ) {
+        OGR_G_AddGeometryDirectly( hML, hGeom );
+        hGeom = hML;
+      }
+    }
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Transform polygon geometry.                                     */
+  /* -------------------------------------------------------------------- */
+  else if( shape->type == MS_SHAPE_POLYGON ) {
+    int iRing, iOuter;
+    int *outer_flags;
+    OGRGeometryH hMP;
+
+    if( shape->numlines < 1 ) {
+      msSetError(MS_MISCERR,
+                 "Failed on odd polygon geometry.",
+                 "msOGRWriteShape()");
+      return MS_FAILURE;
+    }
 
-            hGeom = OGR_G_CreateGeometry( wkbPolygon );
+    outer_flags = msGetOuterList( shape );
+    hMP = OGR_G_CreateGeometry( wkbMultiPolygon );
 
-            /* handle outer ring */
+    for( iOuter = 0; iOuter < shape->numlines; iOuter++ ) {
+      int *inner_flags;
+      OGRGeometryH hRing;
 
-            hRing = OGR_G_CreateGeometry( wkbLinearRing );
+      if( !outer_flags[iOuter] )
+        continue;
 
-            for( i = 0; i < shape->line[iOuter].numpoints; i++ )
-            {
-                OGR_G_SetPoint( hRing, i, 
-                                shape->line[iOuter].point[i].x,
-                                shape->line[iOuter].point[i].y,
-                                0.0 );
-            }
-            
-            OGR_G_AddGeometryDirectly( hGeom, hRing );
+      hGeom = OGR_G_CreateGeometry( wkbPolygon );
 
+      /* handle outer ring */
 
-            /* handle inner rings (holes) */
-            inner_flags = msGetInnerList( shape, iOuter, outer_flags );
+      hRing = OGR_G_CreateGeometry( wkbLinearRing );
 
-            for( iRing = 0; iRing < shape->numlines; iRing++ )
-            {
-                if( !inner_flags[iRing] )
-                    continue;
-                
-                hRing = OGR_G_CreateGeometry( wkbLinearRing );
+      for( i = 0; i < shape->line[iOuter].numpoints; i++ ) {
+        OGR_G_SetPoint( hRing, i,
+                        shape->line[iOuter].point[i].x,
+                        shape->line[iOuter].point[i].y,
+#ifdef USE_POINT_Z_M
+                        shape->line[iOuter].point[i].z
+#else
+                        0.0
+#endif
+                      );
+      }
 
-                for( i = 0; i < shape->line[iRing].numpoints; i++ )
-                {
-                    OGR_G_SetPoint( hRing, i, 
-                                    shape->line[iRing].point[i].x,
-                                    shape->line[iRing].point[i].y,
-                                    0.0 );
-                }
-                
-                OGR_G_AddGeometryDirectly( hGeom, hRing );
-            }
+      OGR_G_AddGeometryDirectly( hGeom, hRing );
 
-            free(inner_flags);
 
-            OGR_G_AddGeometryDirectly( hMP, hGeom );
-        }
+      /* handle inner rings (holes) */
+      inner_flags = msGetInnerList( shape, iOuter, outer_flags );
 
-        free(outer_flags);
+      for( iRing = 0; iRing < shape->numlines; iRing++ ) {
+        if( !inner_flags[iRing] )
+          continue;
 
-        if( OGR_G_GetGeometryCount( hMP ) == 1 )
-        {
-            hGeom = OGR_G_Clone( OGR_G_GetGeometryRef( hMP, 0 ) );
-            OGR_G_DestroyGeometry( hMP );
-        }
-        else
-        {
-            hGeom = hMP;
+        hRing = OGR_G_CreateGeometry( wkbLinearRing );
+
+        for( i = 0; i < shape->line[iRing].numpoints; i++ ) {
+          OGR_G_SetPoint( hRing, i,
+                          shape->line[iRing].point[i].x,
+                          shape->line[iRing].point[i].y,
+#ifdef USE_POINT_Z_M
+                          shape->line[iRing].point[i].z
+#else
+                          0.0
+#endif
+                        );
         }
+
+        OGR_G_AddGeometryDirectly( hGeom, hRing );
+      }
+
+      free(inner_flags);
+
+      OGR_G_AddGeometryDirectly( hMP, hGeom );
+    }
+
+    free(outer_flags);
+
+    if( OGR_G_GetGeometryCount( hMP ) == 1 ) {
+      hGeom = OGR_G_Clone( OGR_G_GetGeometryRef( hMP, 0 ) );
+      OGR_G_DestroyGeometry( hMP );
+    } else {
+      hGeom = hMP;
     }
+  }
 
-/* -------------------------------------------------------------------- */
-/*      Consider trying to force the geometry to a new type if it       */
-/*      doesn't match the layer.                                        */
-/* -------------------------------------------------------------------- */
-    eLayerGType = 
-        wkbFlatten(OGR_FD_GetGeomType(OGR_L_GetLayerDefn(hOGRLayer)));
+  /* -------------------------------------------------------------------- */
+  /*      Consider trying to force the geometry to a new type if it       */
+  /*      doesn't match the layer.                                        */
+  /* -------------------------------------------------------------------- */
+  eLayerGType =
+    wkbFlatten(OGR_FD_GetGeomType(OGR_L_GetLayerDefn(hOGRLayer)));
+
+  if( hGeom != NULL )
+    eFeatureGType = wkbFlatten(OGR_G_GetGeometryType( hGeom ));
 
-    if( hGeom != NULL )
-        eFeatureGType = wkbFlatten(OGR_G_GetGeometryType( hGeom ));
-    
 #if defined(GDAL_VERSION_NUM) && (GDAL_VERSION_NUM >= 1800)
 
-    if( hGeom != NULL 
-        && eLayerGType == wkbPolygon
-        && eFeatureGType != eLayerGType )
-        hGeom = OGR_G_ForceToPolygon( hGeom );
-
-    else if( hGeom != NULL 
-             && eLayerGType == wkbMultiPolygon
-             && eFeatureGType != eLayerGType )
-        hGeom = OGR_G_ForceToMultiPolygon( hGeom );
-        
-    else if( hGeom != NULL 
-             && eLayerGType == wkbMultiPoint
-             && eFeatureGType != eLayerGType )
-        hGeom = OGR_G_ForceToMultiPoint( hGeom );
-        
-    else if( hGeom != NULL 
-             && eLayerGType == wkbMultiLineString
-             && eFeatureGType != eLayerGType )
-        hGeom = OGR_G_ForceToMultiLineString( hGeom );
-        
+  if( hGeom != NULL
+      && eLayerGType == wkbPolygon
+      && eFeatureGType != eLayerGType )
+    hGeom = OGR_G_ForceToPolygon( hGeom );
+
+  else if( hGeom != NULL
+           && eLayerGType == wkbMultiPolygon
+           && eFeatureGType != eLayerGType )
+    hGeom = OGR_G_ForceToMultiPolygon( hGeom );
+
+  else if( hGeom != NULL
+           && eLayerGType == wkbMultiPoint
+           && eFeatureGType != eLayerGType )
+    hGeom = OGR_G_ForceToMultiPoint( hGeom );
+
+  else if( hGeom != NULL
+           && eLayerGType == wkbMultiLineString
+           && eFeatureGType != eLayerGType )
+    hGeom = OGR_G_ForceToMultiLineString( hGeom );
+
 #endif /* GDAL/OGR 1.8 or later */
 
-/* -------------------------------------------------------------------- */
-/*      Create the feature, and attach the geometry.                    */
-/* -------------------------------------------------------------------- */
-    hFeat = OGR_F_Create( OGR_L_GetLayerDefn( hOGRLayer ) );
-    
-    OGR_F_SetGeometryDirectly( hFeat, hGeom );
-
-/* -------------------------------------------------------------------- */
-/*      Set attributes.                                                 */
-/* -------------------------------------------------------------------- */
-    out_field = 0;
-    for( i = 0; i < item_list->numitems; i++ )
-    {
-        gmlItemObj *item = item_list->items + i;
-
-        if( !item->visible )
-            continue;
-
-        OGR_F_SetFieldString( hFeat, out_field++, shape->values[i] );
-    }
+  /* -------------------------------------------------------------------- */
+  /*      Consider flattening the geometry to 2D if we want 2D            */
+  /*      output.                                                         */
+  /* -------------------------------------------------------------------- */
+  eLayerGType = OGR_FD_GetGeomType(OGR_L_GetLayerDefn(hOGRLayer));
 
-/* -------------------------------------------------------------------- */
-/*      Write out and cleanup.                                          */
-/* -------------------------------------------------------------------- */
-    eErr = OGR_L_CreateFeature( hOGRLayer, hFeat );
+  if( hGeom != NULL )
+    eFeatureGType = OGR_G_GetGeometryType( hGeom );
 
-    OGR_F_Destroy( hFeat );
+  if( eLayerGType == wkbFlatten(eLayerGType)
+      && hGeom != NULL
+      && eFeatureGType != wkbFlatten(eFeatureGType) )
+    OGR_G_FlattenTo2D( hGeom );
 
-    if( eErr != OGRERR_NONE )
-    {
-        msSetError( MS_OGRERR, 
-                    "Attempt to write feature failed (code=%d):\n%s",
-                    "msOGRWriteShape()", 
-                    (int) eErr,
-                    CPLGetLastErrorMsg() );
-    }
+  /* -------------------------------------------------------------------- */
+  /*      Create the feature, and attach the geometry.                    */
+  /* -------------------------------------------------------------------- */
+  hFeat = OGR_F_Create( OGR_L_GetLayerDefn( hOGRLayer ) );
 
-    if( eErr == OGRERR_NONE )
-        return MS_SUCCESS;
-    else
-        return MS_FAILURE;
+  OGR_F_SetGeometryDirectly( hFeat, hGeom );
+
+  /* -------------------------------------------------------------------- */
+  /*      Set attributes.                                                 */
+  /* -------------------------------------------------------------------- */
+  out_field = 0;
+  for( i = 0; i < item_list->numitems; i++ ) {
+    gmlItemObj *item = item_list->items + i;
+
+    if( !item->visible )
+      continue;
+
+    OGR_F_SetFieldString( hFeat, out_field++, shape->values[i] );
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Write out and cleanup.                                          */
+  /* -------------------------------------------------------------------- */
+  eErr = OGR_L_CreateFeature( hOGRLayer, hFeat );
+
+  OGR_F_Destroy( hFeat );
+
+  if( eErr != OGRERR_NONE ) {
+    msSetError( MS_OGRERR,
+                "Attempt to write feature failed (code=%d):\n%s",
+                "msOGRWriteShape()",
+                (int) eErr,
+                CPLGetLastErrorMsg() );
+  }
+
+  if( eErr == OGRERR_NONE )
+    return MS_SUCCESS;
+  else
+    return MS_FAILURE;
 }
 
 #endif /* def USE_OGR */
@@ -449,604 +474,588 @@ int msOGRWriteFromQuery( mapObj *map, outputFormatObj *format, int sendheaders )
 
 {
 #ifndef USE_OGR
-    msSetError(MS_OGRERR, "OGR support is not available.", 
-               "msOGRWriteFromQuery()");
-    return MS_FAILURE;
+  msSetError(MS_OGRERR, "OGR support is not available.",
+             "msOGRWriteFromQuery()");
+  return MS_FAILURE;
 #else
-/* -------------------------------------------------------------------- */
-/*      Variable declarations.                                          */
-/* -------------------------------------------------------------------- */
-    OGRSFDriverH hDriver;
-    OGRDataSourceH hDS;
-    const char *storage;
-    const char *fo_filename;
-    const char *form;
-    char datasource_name[MS_MAXPATHLEN];
-    char base_dir[MS_MAXPATHLEN];
-    char *request_dir = NULL;
-    char **ds_options = NULL;
-    char **layer_options = NULL;
-    char **file_list = NULL;
-    int iLayer, i;
-
-/* -------------------------------------------------------------------- */
-/*      Fetch the output format driver.                                 */
-/* -------------------------------------------------------------------- */
-    msOGRInitialize();
-
-    hDriver = OGRGetDriverByName( format->driver+4 );
-    if( hDriver == NULL )
-    {
-        msSetError( MS_MISCERR, "No OGR driver named `%s' available.", 
-                    "msOGRWriteFromQuery()", format->driver+4 );
-        return MS_FAILURE;
-    }
+  /* -------------------------------------------------------------------- */
+  /*      Variable declarations.                                          */
+  /* -------------------------------------------------------------------- */
+  OGRSFDriverH hDriver;
+  OGRDataSourceH hDS;
+  const char *storage;
+  const char *fo_filename;
+  const char *form;
+  char datasource_name[MS_MAXPATHLEN];
+  char base_dir[MS_MAXPATHLEN];
+  char *request_dir = NULL;
+  char **ds_options = NULL;
+  char **layer_options = NULL;
+  char **file_list = NULL;
+  int iLayer, i;
+
+  /* -------------------------------------------------------------------- */
+  /*      Fetch the output format driver.                                 */
+  /* -------------------------------------------------------------------- */
+  msOGRInitialize();
+
+  hDriver = OGRGetDriverByName( format->driver+4 );
+  if( hDriver == NULL ) {
+    msSetError( MS_MISCERR, "No OGR driver named `%s' available.",
+                "msOGRWriteFromQuery()", format->driver+4 );
+    return MS_FAILURE;
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Capture datasource and layer creation options.                  */
+  /* -------------------------------------------------------------------- */
+  for( i=0; i < format->numformatoptions; i++ ) {
+    if( strncasecmp(format->formatoptions[i],"LCO:",4) == 0 )
+      layer_options = CSLAddString( layer_options,
+                                    format->formatoptions[i] + 4 );
+    if( strncasecmp(format->formatoptions[i],"DSCO:",5) == 0 )
+      ds_options = CSLAddString( ds_options,
+                                 format->formatoptions[i] + 5 );
+  }
+
+  /* ==================================================================== */
+  /*      Determine the output datasource name to use.                    */
+  /* ==================================================================== */
+  storage = msGetOutputFormatOption( format, "STORAGE", "filesystem" );
+
+  /* -------------------------------------------------------------------- */
+  /*      Where are we putting stuff?                                     */
+  /* -------------------------------------------------------------------- */
+  if( EQUAL(storage,"filesystem") ) {
+    base_dir[0] = '\0' ;
+  } else if( EQUAL(storage,"memory") ) {
+    strcpy( base_dir, "/vsimem/ogr_out/" );
+  } else if( EQUAL(storage,"stream") ) {
+    /* handled later */
+  } else {
+    msSetError( MS_MISCERR,
+                "STORAGE=%s value not supported.",
+                "msOGRWriteFromQuery()",
+                storage );
+    return MS_FAILURE;
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Create a subdirectory to handle this request.                   */
+  /* -------------------------------------------------------------------- */
+  if( !EQUAL(storage,"stream") ) {
+    if (strlen(base_dir) > 0)
+      request_dir = msTmpFile(map, NULL, base_dir, "" );
+    else
+      request_dir = msTmpFile(map, NULL, NULL, "" );
 
-/* -------------------------------------------------------------------- */
-/*      Capture datasource and layer creation options.                  */
-/* -------------------------------------------------------------------- */
-    for( i=0; i < format->numformatoptions; i++ )
-    {
-        if( strncasecmp(format->formatoptions[i],"LCO:",4) == 0 )
-            layer_options = CSLAddString( layer_options, 
-                                          format->formatoptions[i] + 4 );
-        if( strncasecmp(format->formatoptions[i],"DSCO:",5) == 0 )
-            ds_options = CSLAddString( ds_options, 
-                                       format->formatoptions[i] + 5 );
-    }
-    
-/* ==================================================================== */
-/*      Determine the output datasource name to use.                    */
-/* ==================================================================== */
-    storage = msGetOutputFormatOption( format, "STORAGE", "filesystem" );
-
-/* -------------------------------------------------------------------- */
-/*      Where are we putting stuff?                                     */
-/* -------------------------------------------------------------------- */
-    if( EQUAL(storage,"filesystem") )
-    {
-        base_dir[0] = '\0' ;
-    }
-    else if( EQUAL(storage,"memory") )
-    {
-        strcpy( base_dir, "/vsimem/ogr_out/" );
+    if( request_dir[strlen(request_dir)-1] == '.' )
+      request_dir[strlen(request_dir)-1] = '\0';
+
+    if( VSIMkdir( request_dir, 0777 ) != 0 ) {
+      msSetError( MS_MISCERR,
+                  "Attempt to create directory '%s' failed.",
+                  "msOGRWriteFromQuery()",
+                  request_dir );
+      return MS_FAILURE;
     }
-    else if( EQUAL(storage,"stream") )
-    {
-        /* handled later */
+  } else
+    /* handled later */;
+
+  /* -------------------------------------------------------------------- */
+  /*      Setup the full datasource name.                                 */
+  /* -------------------------------------------------------------------- */
+  fo_filename = msGetOutputFormatOption( format, "FILENAME", "result.dat" );
+
+  /* Validate that the filename does not contain any directory */
+  /* information, which might lead to removal of unwanted files. (#4086) */
+  if( strchr(fo_filename, '/') != NULL || strchr(fo_filename, ':') != NULL ||
+        strchr(fo_filename, '\\') != NULL ) {
+    msSetError( MS_MISCERR,
+           "Invalid value for FILENAME option. "
+           "It must not contain any directory information.",
+           "msOGRWriteFromQuery()" );
+    return MS_FAILURE;
+  }
+
+  if( !EQUAL(storage,"stream") )
+    msBuildPath( datasource_name, request_dir, fo_filename );
+  else
+    strcpy( datasource_name, "/vsistdout/" );
+
+  msFree( request_dir );
+  request_dir = NULL;
+
+  /* -------------------------------------------------------------------- */
+  /*      Emit content type headers for stream output now.                */
+  /* -------------------------------------------------------------------- */
+  if( EQUAL(storage,"stream") ) {
+    if( sendheaders && format->mimetype ) {
+      msIO_setHeader("Content-Type",format->mimetype);
+      msIO_sendHeaders();
+    } else
+      msIO_fprintf( stdout, "%c", 10 );
+  }
+
+  /* ==================================================================== */
+  /*      Create the datasource.                                          */
+  /* ==================================================================== */
+  hDS = OGR_Dr_CreateDataSource( hDriver,  datasource_name, ds_options );
+  CSLDestroy( ds_options );
+
+  if( hDS == NULL ) {
+    msOGRCleanupDS( datasource_name );
+    msSetError( MS_MISCERR,
+                "OGR CreateDataSource failed for '%s' with driver '%s'.",
+                "msOGRWriteFromQuery()",
+                datasource_name,
+                format->driver+4 );
+    return MS_FAILURE;
+  }
+
+  /* ==================================================================== */
+  /*      Process each layer with a resultset.                            */
+  /* ==================================================================== */
+  for( iLayer = 0; iLayer < map->numlayers; iLayer++ ) {
+    int status;
+    layerObj *layer = GET_LAYER(map, iLayer);
+    shapeObj resultshape;
+    OGRLayerH hOGRLayer;
+    OGRwkbGeometryType eGeomType;
+    OGRSpatialReferenceH srs = NULL;
+    gmlItemListObj *item_list = NULL;
+    const char *value;
+    char *pszWKT;
+    int  reproject = MS_FALSE;
+
+    if( !layer->resultcache || layer->resultcache->numresults == 0 )
+      continue;
+
+    /* -------------------------------------------------------------------- */
+    /*      Will we need to reproject?                                      */
+    /* -------------------------------------------------------------------- */
+    if(layer->transform == MS_TRUE
+        && layer->project
+        && msProjectionsDiffer(&(layer->projection),
+                               &(layer->map->projection)) )
+      reproject = MS_TRUE;
+
+    /* -------------------------------------------------------------------- */
+    /*      Establish the geometry type to use for the created layer.       */
+    /*      First we consult the wfs_geomtype field and fallback to         */
+    /*      deriving something from the type of the mapserver layer.        */
+    /* -------------------------------------------------------------------- */
+    value = msOWSLookupMetadata(&(layer->metadata), "FOG", "geomtype");
+    if( value == NULL ) {
+      if( layer->type == MS_LAYER_POINT )
+        value = "Point";
+      else if( layer->type == MS_LAYER_LINE )
+        value = "LineString";
+      else if( layer->type == MS_LAYER_POLYGON )
+        value = "Polygon";
+      else
+        value = "Geometry";
     }
+
+    if( strcasecmp(value,"Point") == 0 )
+      eGeomType = wkbPoint;
+    else if( strcasecmp(value,"LineString") == 0 )
+      eGeomType = wkbLineString;
+    else if( strcasecmp(value,"Polygon") == 0 )
+      eGeomType = wkbPolygon;
+    else if( strcasecmp(value,"MultiPoint") == 0 )
+      eGeomType = wkbMultiPoint;
+    else if( strcasecmp(value,"MultiLineString") == 0 )
+      eGeomType = wkbMultiLineString;
+    else if( strcasecmp(value,"MultiPolygon") == 0 )
+      eGeomType = wkbMultiPolygon;
+    else if( strcasecmp(value,"GeometryCollection") == 0 )
+      eGeomType = wkbGeometryCollection;
+    else if( strcasecmp(value,"Point25D") == 0 )
+      eGeomType = wkbPoint25D;
+    else if( strcasecmp(value,"LineString25D") == 0 )
+      eGeomType = wkbLineString25D;
+    else if( strcasecmp(value,"Polygon25D") == 0 )
+      eGeomType = wkbPolygon25D;
+    else if( strcasecmp(value,"MultiPoint25D") == 0 )
+      eGeomType = wkbMultiPoint25D;
+    else if( strcasecmp(value,"MultiLineString25D") == 0 )
+      eGeomType = wkbMultiLineString25D;
+    else if( strcasecmp(value,"MultiPolygon25D") == 0 )
+      eGeomType = wkbMultiPolygon25D;
+    else if( strcasecmp(value,"GeometryCollection25D") == 0 )
+      eGeomType = wkbGeometryCollection25D;
+    else if( strcasecmp(value,"Unknown") == 0
+             || strcasecmp(value,"Geometry") == 0 )
+      eGeomType = wkbUnknown;
+    else if( strcasecmp(value,"None") == 0 )
+      eGeomType = wkbNone;
     else
-    {
-        msSetError( MS_MISCERR, 
-                    "STORAGE=%s value not supported.",
-                    "msOGRWriteFromQuery()", 
-                    storage );
-        return MS_FAILURE;
+      eGeomType = wkbUnknown;
+
+    /* -------------------------------------------------------------------- */
+    /*      Create a spatial reference.                                     */
+    /* -------------------------------------------------------------------- */
+    pszWKT = msProjectionObj2OGCWKT( &(map->projection) );
+    if( pszWKT != NULL ) {
+      srs = OSRNewSpatialReference( pszWKT );
+      msFree( pszWKT );
     }
 
-/* -------------------------------------------------------------------- */
-/*      Create a subdirectory to handle this request.                   */
-/* -------------------------------------------------------------------- */
-    if( !EQUAL(storage,"stream") )
-    {
-        if (strlen(base_dir) > 0)
-            request_dir = msTmpFile(map, NULL, base_dir, "" );                
-        else
-            request_dir = msTmpFile(map, NULL, NULL, "" );
-
-        if( request_dir[strlen(request_dir)-1] == '.' )
-            request_dir[strlen(request_dir)-1] = '\0';
-
-        if( VSIMkdir( request_dir, 0777 ) != 0 )
-        {
-            msSetError( MS_MISCERR, 
-                        "Attempt to create directory '%s' failed.",
-                        "msOGRWriteFromQuery()", 
-                        request_dir );
-            return MS_FAILURE;
-        }
+    /* -------------------------------------------------------------------- */
+    /*      Create the corresponding OGR Layer.                             */
+    /* -------------------------------------------------------------------- */
+    hOGRLayer = OGR_DS_CreateLayer( hDS, layer->name, srs, eGeomType,
+                                    layer_options );
+    if( hOGRLayer == NULL ) {
+      OGR_DS_Destroy( hDS );
+      msOGRCleanupDS( datasource_name );
+      msSetError( MS_MISCERR,
+                  "OGR CreateDataSource failed for '%s' with driver '%s'.",
+                  "msOGRWriteFromQuery()",
+                  datasource_name,
+                  format->driver+4 );
+      return MS_FAILURE;
     }
-    else
-        /* handled later */;
 
-/* -------------------------------------------------------------------- */
-/*      Setup the full datasource name.                                 */
-/* -------------------------------------------------------------------- */
-    fo_filename = msGetOutputFormatOption( format, "FILENAME", "result.dat" );
-
-    if( !EQUAL(storage,"stream") )
-        msBuildPath( datasource_name, request_dir, fo_filename );
-    else
-        strcpy( datasource_name, "/vsistdout/" );
-    
-    msFree( request_dir );
-    request_dir = NULL;
-
-/* -------------------------------------------------------------------- */
-/*      Emit content type headers for stream output now.                */
-/* -------------------------------------------------------------------- */
-    if( EQUAL(storage,"stream") )
-    {
-        if( sendheaders && format->mimetype )
-            msIO_fprintf( stdout, 
-                          "Content-Type: %s%c%c",
-                          format->mimetype, 10, 10 );
-        else
-            msIO_fprintf( stdout, "%c", 10 );
-    }
+    if( srs != NULL )
+      OSRDestroySpatialReference( srs );
+
+    /* -------------------------------------------------------------------- */
+    /*      Create appropriate attributes on this layer.                    */
+    /* -------------------------------------------------------------------- */
+    item_list = msGMLGetItems( layer, "G" );
+    assert( item_list->numitems == layer->numitems );
+
+    for( i = 0; i < layer->numitems; i++ ) {
+      OGRFieldDefnH hFldDefn;
+      OGRErr eErr;
+      const char *name;
+      gmlItemObj *item = item_list->items + i;
+      OGRFieldType eType;
+
+      if( !item->visible )
+        continue;
+
+      if( item->alias )
+        name = item->alias;
+      else
+        name = item->name;
+
+      if( item->type == NULL )
+        eType = OFTString;
+      else if( EQUAL(item->type,"Integer") )
+        eType = OFTInteger;
+      else if( EQUAL(item->type,"Real") )
+        eType = OFTReal;
+      else if( EQUAL(item->type,"Character") )
+        eType = OFTString;
+      else if( EQUAL(item->type,"Date") )
+        eType = OFTDateTime;
+      else if( EQUAL(item->type,"Boolean") )
+        eType = OFTInteger;
+      else
+        eType = OFTString;
+
+      hFldDefn = OGR_Fld_Create( name, eType );
+
+      if( item->width != 0 )
+        OGR_Fld_SetWidth( hFldDefn, item->width );
+      if( item->precision != 0 )
+        OGR_Fld_SetPrecision( hFldDefn, item->precision );
+
+      eErr = OGR_L_CreateField( hOGRLayer, hFldDefn, TRUE );
+      OGR_Fld_Destroy( hFldDefn );
+
+      if( eErr != OGRERR_NONE ) {
+        msSetError( MS_OGRERR,
+                    "Failed to create field '%s' in output feature schema:\n%s",
+                    "msOGRWriteFromQuery()",
+                    layer->items[i],
+                    CPLGetLastErrorMsg() );
 
-/* ==================================================================== */
-/*      Create the datasource.                                          */
-/* ==================================================================== */
-    hDS = OGR_Dr_CreateDataSource( hDriver,  datasource_name, ds_options );
-    CSLDestroy( ds_options );
-    
-    if( hDS == NULL )
-    {
+        OGR_DS_Destroy( hDS );
         msOGRCleanupDS( datasource_name );
-        msSetError( MS_MISCERR, 
-                    "OGR CreateDataSource failed for '%s' with driver '%s'.",
-                    "msOGRWriteFromQuery()", 
-                    datasource_name, 
-                    format->driver+4 );
         return MS_FAILURE;
+      }
     }
 
-/* ==================================================================== */
-/*      Process each layer with a resultset.                            */
-/* ==================================================================== */
-    for( iLayer = 0; iLayer < map->numlayers; iLayer++ )
-    {
-        int status;
-        layerObj *layer = GET_LAYER(map, iLayer);
-        shapeObj resultshape;
-        OGRLayerH hOGRLayer;
-        OGRwkbGeometryType eGeomType;
-        OGRSpatialReferenceH srs = NULL;
-        gmlItemListObj *item_list = NULL;
-        const char *value;
-        char *pszWKT;
-        int  reproject = MS_FALSE;
-
-        if( !layer->resultcache || layer->resultcache->numresults == 0 )
-            continue;
-
-/* -------------------------------------------------------------------- */
-/*      Will we need to reproject?                                      */
-/* -------------------------------------------------------------------- */
-        if(layer->transform == MS_TRUE
-           && layer->project 
-           && msProjectionsDiffer(&(layer->projection), 
-                                  &(layer->map->projection)) )
-            reproject = MS_TRUE;
-
-/* -------------------------------------------------------------------- */
-/*      Establish the geometry type to use for the created layer.       */
-/*      First we consult the wfs_geomtype field and fallback to         */
-/*      deriving something from the type of the mapserver layer.        */
-/* -------------------------------------------------------------------- */
-        value = msOWSLookupMetadata(&(layer->metadata), "FOG", "geomtype");
-        if( value == NULL )
-        {
-            if( layer->type == MS_LAYER_POINT )
-                value = "Point";
-            else if( layer->type == MS_LAYER_LINE )
-                value = "LineString";
-            else if( layer->type == MS_LAYER_POLYGON )
-                value = "Polygon";
-            else
-                value = "Geometry";
+    /* -------------------------------------------------------------------- */
+    /*      Setup joins if needed.  This is likely untested.                */
+    /* -------------------------------------------------------------------- */
+    if(layer->numjoins > 0) {
+      int j;
+      for(j=0; j<layer->numjoins; j++) {
+        status = msJoinConnect(layer, &(layer->joins[j]));
+        if(status != MS_SUCCESS) {
+          OGR_DS_Destroy( hDS );
+          msOGRCleanupDS( datasource_name );
+          return status;
         }
+      }
+    }
 
-        if( strcasecmp(value,"Point") == 0 )
-            eGeomType = wkbPoint;
-        else if( strcasecmp(value,"LineString") == 0 )
-            eGeomType = wkbLineString;
-        else if( strcasecmp(value,"Polygon") == 0 )
-            eGeomType = wkbPolygon;
-        else if( strcasecmp(value,"MultiPoint") == 0 )
-            eGeomType = wkbMultiPoint;
-        else if( strcasecmp(value,"MultiLineString") == 0 )
-            eGeomType = wkbMultiLineString;
-        else if( strcasecmp(value,"MultiPolygon") == 0 )
-            eGeomType = wkbMultiPolygon;
-        else if( strcasecmp(value,"GeometryCollection") == 0 )
-            eGeomType = wkbMultiPolygon;
-        else if( strcasecmp(value,"Unknown") == 0 
-                 || strcasecmp(value,"Geometry") == 0 )
-            eGeomType = wkbUnknown;
-        else if( strcasecmp(value,"None") == 0 )
-            eGeomType = wkbNone;
-        else
-            eGeomType = wkbUnknown;
-
-/* -------------------------------------------------------------------- */
-/*      Create a spatial reference.                                     */
-/* -------------------------------------------------------------------- */
-        pszWKT = msProjectionObj2OGCWKT( &(map->projection) );
-        if( pszWKT != NULL )
-        {
-            srs = OSRNewSpatialReference( pszWKT );
-            msFree( pszWKT );
-        }
-        
-/* -------------------------------------------------------------------- */
-/*      Create the corresponding OGR Layer.                             */
-/* -------------------------------------------------------------------- */
-        hOGRLayer = OGR_DS_CreateLayer( hDS, layer->name, srs, eGeomType, 
-                                        layer_options );
-        if( hOGRLayer == NULL )
-        {
-            OGR_DS_Destroy( hDS );
-            msOGRCleanupDS( datasource_name );
-            msSetError( MS_MISCERR, 
-                        "OGR CreateDataSource failed for '%s' with driver '%s'.",
-                        "msOGRWriteFromQuery()", 
-                        datasource_name, 
-                        format->driver+4 );
-            return MS_FAILURE;
-        }
+    msInitShape( &resultshape );
 
-        if( srs != NULL )
-            OSRDestroySpatialReference( srs );
-
-/* -------------------------------------------------------------------- */
-/*      Create appropriate attributes on this layer.                    */
-/* -------------------------------------------------------------------- */
-        item_list = msGMLGetItems( layer, "G" );
-        assert( item_list->numitems == layer->numitems );
-        
-        for( i = 0; i < layer->numitems; i++ )
-        {
-            OGRFieldDefnH hFldDefn;
-            OGRErr eErr;
-            const char *name;
-            gmlItemObj *item = item_list->items + i;
-            OGRFieldType eType;
-            
-            if( !item->visible )
-                continue;
-
-            if( item->alias )
-                name = item->alias;
-            else
-                name = item->name;
-            
-            if( item->type == NULL )
-                eType = OFTString;
-            else if( EQUAL(item->type,"Integer") )
-                eType = OFTInteger;
-            else if( EQUAL(item->type,"Real") )
-                eType = OFTReal;
-            else if( EQUAL(item->type,"Character") )
-                eType = OFTString;
-            else if( EQUAL(item->type,"Date") )
-                eType = OFTDateTime;
-            else if( EQUAL(item->type,"Boolean") )
-                eType = OFTInteger;
-            else 
-                eType = OFTString;
-            
-            hFldDefn = OGR_Fld_Create( name, eType );
-            
-            if( item->width != 0 )
-                OGR_Fld_SetWidth( hFldDefn, item->width );
-            if( item->precision != 0 )
-                OGR_Fld_SetPrecision( hFldDefn, item->precision );
-
-            eErr = OGR_L_CreateField( hOGRLayer, hFldDefn, TRUE );
-            OGR_Fld_Destroy( hFldDefn );
-
-            if( eErr != OGRERR_NONE )
-            {
-                msSetError( MS_OGRERR, 
-                            "Failed to create field '%s' in output feature schema:\n%s", 
-                            "msOGRWriteFromQuery()", 
-                            layer->items[i], 
-                            CPLGetLastErrorMsg() );
-                
-                OGR_DS_Destroy( hDS );
-                msOGRCleanupDS( datasource_name );
-                return MS_FAILURE;
-            }
-        }
+    /* -------------------------------------------------------------------- */
+    /*      Loop over all the shapes in the resultcache.                    */
+    /* -------------------------------------------------------------------- */
+    for(i=0; i < layer->resultcache->numresults; i++) {
 
-/* -------------------------------------------------------------------- */
-/*      Setup joins if needed.  This is likely untested.                */
-/* -------------------------------------------------------------------- */
-        if(layer->numjoins > 0) {
-            int j;
-            for(j=0; j<layer->numjoins; j++) {
-                status = msJoinConnect(layer, &(layer->joins[j]));
-                if(status != MS_SUCCESS) {
-                    OGR_DS_Destroy( hDS );
-                    msOGRCleanupDS( datasource_name );
-                    return status;
-                }
-            }
-        }
+      msFreeShape(&resultshape); /* init too */
+
+      /*
+      ** Read the shape.
+      */
+      status = msLayerGetShape(layer, &resultshape, &(layer->resultcache->results[i]));
+      if(status != MS_SUCCESS) {
+        OGR_DS_Destroy( hDS );
+        msOGRCleanupDS( datasource_name );
+        return status;
+      }
+
+      /*
+      ** Perform classification, and some annotation related magic.
+      */
+      resultshape.classindex =
+        msShapeGetClass(layer, map, &resultshape, NULL, -1);
+
+      if( resultshape.classindex >= 0
+          && (layer->class[resultshape.classindex]->text.string
+              || layer->labelitem)
+          && layer->class[resultshape.classindex]->numlabels > 0
+          && layer->class[resultshape.classindex]->labels[0]->size != -1 ) {
+        msShapeGetAnnotation(layer, &resultshape); /* TODO RFC77: check return value */
+        resultshape.text = msStrdup(layer->class[resultshape.classindex]->labels[0]->annotext);
+      }
+
+      /*
+      ** prepare any necessary JOINs here (one-to-one only)
+      */
+      if( layer->numjoins > 0) {
+        int j;
 
-        msInitShape( &resultshape );
-
-/* -------------------------------------------------------------------- */
-/*      Loop over all the shapes in the resultcache.                    */
-/* -------------------------------------------------------------------- */
-        for(i=0; i < layer->resultcache->numresults; i++) {
-
-            msFreeShape(&resultshape); /* init too */
-
-            /*
-            ** Read the shape.
-            */
-            status = msLayerGetShape(layer, &resultshape, &(layer->resultcache->results[i]));
-            if(status != MS_SUCCESS) {
-                OGR_DS_Destroy( hDS );
-                msOGRCleanupDS( datasource_name );
-                return status;
-            } 
-
-            /* 
-            ** Perform classification, and some annotation related magic.
-            */
-            resultshape.classindex = 
-                msShapeGetClass(layer, map, &resultshape, NULL, -1);
-
-            if( resultshape.classindex >= 0 
-                && (layer->class[resultshape.classindex]->text.string 
-                    || layer->labelitem) 
-                && layer->class[resultshape.classindex]->label.size != -1 )
-            {
-                resultshape.text = msShapeGetAnnotation(layer, &resultshape);
-            }
-
-            /*
-            ** prepare any necessary JOINs here (one-to-one only)
-            */
-            if( layer->numjoins > 0) {
-                int j;
-
-                for(j=0; j < layer->numjoins; j++) {
-                    if(layer->joins[j].type == MS_JOIN_ONE_TO_ONE) {
-                        msJoinPrepare(&(layer->joins[j]), &resultshape);
-                        msJoinNext(&(layer->joins[j])); /* fetch the first row */
-                    }
-                }
-            }
-            
-            if( reproject )
-            {
-                status = 
-                    msProjectShape(&layer->projection, &layer->map->projection, 
-                                   &resultshape);
-            }
-
-            /*
-            ** Write out the feature to OGR.
-            */
-
-            if( status == MS_SUCCESS )
-                status = msOGRWriteShape( layer, hOGRLayer, &resultshape,
-                                          item_list );
-
-            if(status != MS_SUCCESS) {
-                OGR_DS_Destroy( hDS );
-                msOGRCleanupDS( datasource_name );
-                return status;
-            } 
+        for(j=0; j < layer->numjoins; j++) {
+          if(layer->joins[j].type == MS_JOIN_ONE_TO_ONE) {
+            msJoinPrepare(&(layer->joins[j]), &resultshape);
+            msJoinNext(&(layer->joins[j])); /* fetch the first row */
+          }
         }
+      }
 
-        msGMLFreeItems(item_list);
-        msFreeShape(&resultshape); /* init too */
+      if( reproject ) {
+        status =
+          msProjectShape(&layer->projection, &layer->map->projection,
+                         &resultshape);
+      }
+
+      /*
+      ** Write out the feature to OGR.
+      */
+
+      if( status == MS_SUCCESS )
+        status = msOGRWriteShape( layer, hOGRLayer, &resultshape,
+                                  item_list );
+
+      if(status != MS_SUCCESS) {
+        OGR_DS_Destroy( hDS );
+        msOGRCleanupDS( datasource_name );
+        return status;
+      }
     }
-    
-/* -------------------------------------------------------------------- */
-/*      Close the datasource.                                           */
-/* -------------------------------------------------------------------- */
-    OGR_DS_Destroy( hDS );
-    
-/* -------------------------------------------------------------------- */
-/*      Get list of resulting files.                                    */
-/* -------------------------------------------------------------------- */
+
+    msGMLFreeItems(item_list);
+    msFreeShape(&resultshape); /* init too */
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Close the datasource.                                           */
+  /* -------------------------------------------------------------------- */
+  OGR_DS_Destroy( hDS );
+
+  /* -------------------------------------------------------------------- */
+  /*      Get list of resulting files.                                    */
+  /* -------------------------------------------------------------------- */
 #if !defined(CPL_ZIP_API_OFFERED)
-    form = msGetOutputFormatOption( format, "FORM", "multipart" );
+  form = msGetOutputFormatOption( format, "FORM", "multipart" );
 #else
-    form = msGetOutputFormatOption( format, "FORM", "zip" );
+  form = msGetOutputFormatOption( format, "FORM", "zip" );
 #endif
 
-    if( EQUAL(form,"simple") )
-    {
-        file_list = CSLAddString( NULL, datasource_name );
+  if( EQUAL(form,"simple") ) {
+    file_list = CSLAddString( NULL, datasource_name );
+  } else {
+    char datasource_path[MS_MAXPATHLEN];
+
+    strcpy( datasource_path, CPLGetPath( datasource_name ) );
+    file_list = msOGRRecursiveFileList( datasource_path );
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      If our "storage" is stream then the output has already been     */
+  /*      sent back to the client and we don't need to copy it now.       */
+  /* -------------------------------------------------------------------- */
+  if( EQUAL(storage,"stream") ) {
+    /* already done */
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Handle case of simple file written to stdout.                   */
+  /* -------------------------------------------------------------------- */
+  else if( EQUAL(form,"simple") ) {
+    char buffer[1024];
+    int  bytes_read;
+    FILE *fp;
+
+    if( sendheaders ) {
+      msIO_setHeader("Content-Disposition","attachment; filename=%s",
+                     CPLGetFilename( file_list[0] ) );
+      if( format->mimetype )
+        msIO_setHeader("Content-Type",format->mimetype);
+      msIO_sendHeaders();
+    } else
+      msIO_fprintf( stdout, "%c", 10 );
+
+    fp = VSIFOpenL( file_list[0], "r" );
+    if( fp == NULL ) {
+      msSetError( MS_MISCERR,
+                  "Failed to open result file '%s'.",
+                  "msOGRWriteFromQuery()",
+                  file_list[0] );
+      msOGRCleanupDS( datasource_name );
+      return MS_FAILURE;
     }
-    else
-    {
-        char datasource_path[MS_MAXPATHLEN];
 
-        strcpy( datasource_path, CPLGetPath( datasource_name ) );
-        file_list = msOGRRecursiveFileList( datasource_path );
-    }
+    while( (bytes_read = VSIFReadL( buffer, 1, sizeof(buffer), fp )) > 0 )
+      msIO_fwrite( buffer, 1, bytes_read, stdout );
+    VSIFCloseL( fp );
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Handle the case of a multi-part result.                         */
+  /* -------------------------------------------------------------------- */
+  else if( EQUAL(form,"multipart") ) {
+    static const char *boundary = "xxOGRBoundaryxx";
+    msIO_setHeader("Content-Type","multipart/mixed; boundary=%s",boundary);
+    msIO_sendHeaders();
+    msIO_fprintf(stdout,"--%s\r\n",boundary );
+
+    for( i = 0; file_list != NULL && file_list[i] != NULL; i++ ) {
+      FILE *fp;
+      int bytes_read;
+      char buffer[1024];
+
+      if( sendheaders )
+        msIO_fprintf( stdout,
+                      "Content-Disposition: attachment; filename=%s\r\n"
+                      "Content-Type: application/binary\r\n"
+                      "Content-Transfer-Encoding: binary\r\n\r\n",
+                      CPLGetFilename( file_list[i] ));
+
+
+      fp = VSIFOpenL( file_list[i], "r" );
+      if( fp == NULL ) {
+        msSetError( MS_MISCERR,
+                    "Failed to open result file '%s'.",
+                    "msOGRWriteFromQuery()",
+                    file_list[0] );
+        msOGRCleanupDS( datasource_name );
+        return MS_FAILURE;
+      }
+
+      while( (bytes_read = VSIFReadL( buffer, 1, sizeof(buffer), fp )) > 0 )
+        msIO_fwrite( buffer, 1, bytes_read, stdout );
+      VSIFCloseL( fp );
 
-/* -------------------------------------------------------------------- */
-/*      If our "storage" is stream then the output has already been     */
-/*      sent back to the client and we don't need to copy it now.       */
-/* -------------------------------------------------------------------- */
-    if( EQUAL(storage,"stream") )
-    {
-        /* already done */
+      if (file_list[i+1] == NULL)
+        msIO_fprintf( stdout, "\r\n--%s--\r\n", boundary );
+      else
+        msIO_fprintf( stdout, "\r\n--%s\r\n", boundary );
     }
+  }
 
-/* -------------------------------------------------------------------- */
-/*      Handle case of simple file written to stdout.                   */
-/* -------------------------------------------------------------------- */
-    else if( EQUAL(form,"simple") )
-    {
-        char buffer[1024];
-        int  bytes_read;
-        FILE *fp;
-
-        if( sendheaders )
-            msIO_fprintf( stdout, 
-                          "Content-Disposition: attachment; filename=%s\n",
-                          CPLGetFilename( file_list[0] ) );
-
-        if( sendheaders && format->mimetype )
-            msIO_fprintf( stdout, 
-                          "Content-Type: %s%c%c",
-                          format->mimetype, 10, 10 );
-        else
-            msIO_fprintf( stdout, "%c", 10 );
-
-        fp = VSIFOpenL( file_list[0], "r" );
-        if( fp == NULL )
-        {
-            msSetError( MS_MISCERR, 
-                        "Failed to open result file '%s'.",
-                        "msOGRWriteFromQuery()",
-                        file_list[0] );
-            msOGRCleanupDS( datasource_name );
-            return MS_FAILURE;
-        }
+  /* -------------------------------------------------------------------- */
+  /*      Handle the case of a zip file result.                           */
+  /* -------------------------------------------------------------------- */
+  else if( EQUAL(form,"zip") ) {
+#if !defined(CPL_ZIP_API_OFFERED)
+    msSetError( MS_MISCERR, "FORM=zip selected, but CPL ZIP support unavailable, perhaps you need to upgrade to GDAL/OGR 1.8?",
+                "msOGRWriteFromQuery()");
+    msOGRCleanupDS( datasource_name );
+    return MS_FAILURE;
+#else
+    FILE *fp;
+    char *zip_filename = msTmpFile(map, NULL, "/vsimem/ogrzip/", "zip" );
+    void *hZip;
+    int bytes_read;
+    char buffer[1024];
 
-        while( (bytes_read = VSIFReadL( buffer, 1, sizeof(buffer), fp )) > 0 )
-            msIO_fwrite( buffer, 1, bytes_read, stdout );
-        VSIFCloseL( fp );
-    }
+    hZip = CPLCreateZip( zip_filename, NULL );
 
-/* -------------------------------------------------------------------- */
-/*      Handle the case of a multi-part result.                         */
-/* -------------------------------------------------------------------- */
-    else if( EQUAL(form,"multipart") )
-    {
-        static const char *boundary = "xxOGRBoundaryxx";
-        msIO_fprintf( stdout, 
-                      "Content-Type: multipart/mixed; boundary=%s%c%c"
-                      "--%s\n",
-                      boundary, 10, 10, boundary );
-
-        for( i = 0; file_list != NULL && file_list[i] != NULL; i++ )
-        {
-            FILE *fp;
-            int bytes_read;
-            char buffer[1024];
-
-            if( sendheaders )
-                msIO_fprintf( stdout, 
-                              "Content-Disposition: attachment; filename=%s\n"
-                              "Content-Type: application/binary\n"
-                              "Content-Transfer-Encoding: binary%c%c",
-                              CPLGetFilename( file_list[i] ),
-                              10, 10 );
-
-            
-            fp = VSIFOpenL( file_list[i], "r" );
-            if( fp == NULL )
-            {
-                msSetError( MS_MISCERR, 
-                            "Failed to open result file '%s'.",
-                            "msOGRWriteFromQuery()",
-                            file_list[0] );
-                msOGRCleanupDS( datasource_name );
-                return MS_FAILURE;
-            }
-            
-            while( (bytes_read = VSIFReadL( buffer, 1, sizeof(buffer), fp )) > 0 )
-                msIO_fwrite( buffer, 1, bytes_read, stdout );
-            VSIFCloseL( fp );
-
-            if (file_list[i+1] == NULL)
-                msIO_fprintf( stdout, "\n--%s--\n", boundary );
-            else
-                msIO_fprintf( stdout, "\n--%s\n", boundary );
-        }
-    }
+    for( i = 0; file_list != NULL && file_list[i] != NULL; i++ ) {
 
-/* -------------------------------------------------------------------- */
-/*      Handle the case of a zip file result.                           */
-/* -------------------------------------------------------------------- */
-    else if( EQUAL(form,"zip") )
-    {
-#if !defined(CPL_ZIP_API_OFFERED)
-        msSetError( MS_MISCERR, "FORM=zip selected, but CPL ZIP support unavailable, perhaps you need to upgrade to GDAL/OGR 1.8?",
-                    "msOGRWriteFromQuery()");
+      CPLCreateFileInZip( hZip, CPLGetFilename(file_list[i]), NULL );
+
+      fp = VSIFOpenL( file_list[i], "r" );
+      if( fp == NULL ) {
+        CPLCloseZip( hZip );
+        msSetError( MS_MISCERR,
+                    "Failed to open result file '%s'.",
+                    "msOGRWriteFromQuery()",
+                    file_list[0] );
         msOGRCleanupDS( datasource_name );
         return MS_FAILURE;
-#else
-        FILE *fp;
-        char *zip_filename = msTmpFile(map, NULL, "/vsimem/ogrzip/", "zip" );
-        void *hZip;
-        int bytes_read;
-        char buffer[1024];
-        
-        hZip = CPLCreateZip( zip_filename, NULL );
-        
-        for( i = 0; file_list != NULL && file_list[i] != NULL; i++ )
-        {
-
-            CPLCreateFileInZip( hZip, CPLGetFilename(file_list[i]), NULL );
-
-            fp = VSIFOpenL( file_list[i], "r" );
-            if( fp == NULL )
-            {
-                CPLCloseZip( hZip );
-                msSetError( MS_MISCERR, 
-                            "Failed to open result file '%s'.",
-                            "msOGRWriteFromQuery()",
-                            file_list[0] );
-                msOGRCleanupDS( datasource_name );
-                return MS_FAILURE;
-            }
-            
-            while( (bytes_read = VSIFReadL( buffer, 1, sizeof(buffer), fp )) > 0 )
-            {
-                CPLWriteFileInZip( hZip, buffer, bytes_read );
-            }
-            VSIFCloseL( fp );
-            
-            CPLCloseFileInZip( hZip );
-        }
-        CPLCloseZip( hZip );
+      }
 
-        if( sendheaders )
-            msIO_fprintf( stdout, 
-                          "Content-Disposition: attachment; filename=%s\n"
-                          "Content-Type: application/zip%c%c",
-                          fo_filename, 10, 10 );
-
-        fp = VSIFOpenL( zip_filename, "r" );
-        if( fp == NULL )
-        {
-            msSetError( MS_MISCERR, 
-                        "Failed to open zip file '%s'.",
-                        "msOGRWriteFromQuery()",
-                        file_list[0] );
-            msOGRCleanupDS( datasource_name );
-            return MS_FAILURE;
-        }
-            
-        while( (bytes_read = VSIFReadL( buffer, 1, sizeof(buffer), fp )) > 0 )
-            msIO_fwrite( buffer, 1, bytes_read, stdout );
-        VSIFCloseL( fp );
+      while( (bytes_read = VSIFReadL( buffer, 1, sizeof(buffer), fp )) > 0 ) {
+        CPLWriteFileInZip( hZip, buffer, bytes_read );
+      }
+      VSIFCloseL( fp );
 
-        msFree( zip_filename );
-#endif /* defined(CPL_ZIP_API_OFFERED) */
+      CPLCloseFileInZip( hZip );
     }
+    CPLCloseZip( hZip );
 
-/* -------------------------------------------------------------------- */
-/*      Handle illegal form value.                                      */
-/* -------------------------------------------------------------------- */
-    else
-    {
-        msSetError( MS_MISCERR, "Unsupported FORM=%s value.", 
-                    "msOGRWriteFromQuery()", form );
-        msOGRCleanupDS( datasource_name );
-        return MS_FAILURE;
+    if( sendheaders ) {
+      msIO_setHeader("Content-Disposition","attachment; filename=%s",fo_filename);
+      msIO_setHeader("Content-Type","application/zip");
+      msIO_sendHeaders();
+    }
+
+    fp = VSIFOpenL( zip_filename, "r" );
+    if( fp == NULL ) {
+      msSetError( MS_MISCERR,
+                  "Failed to open zip file '%s'.",
+                  "msOGRWriteFromQuery()",
+                  file_list[0] );
+      msOGRCleanupDS( datasource_name );
+      return MS_FAILURE;
     }
 
+    while( (bytes_read = VSIFReadL( buffer, 1, sizeof(buffer), fp )) > 0 )
+      msIO_fwrite( buffer, 1, bytes_read, stdout );
+    VSIFCloseL( fp );
+
+    msFree( zip_filename );
+#endif /* defined(CPL_ZIP_API_OFFERED) */
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Handle illegal form value.                                      */
+  /* -------------------------------------------------------------------- */
+  else {
+    msSetError( MS_MISCERR, "Unsupported FORM=%s value.",
+                "msOGRWriteFromQuery()", form );
     msOGRCleanupDS( datasource_name );
+    return MS_FAILURE;
+  }
 
-    CSLDestroy( layer_options );
-    CSLDestroy( file_list );
+  msOGRCleanupDS( datasource_name );
 
-    return MS_SUCCESS;
+  CSLDestroy( layer_options );
+  CSLDestroy( file_list );
+
+  return MS_SUCCESS;
 #endif /* def USE_OGR */
 }
 
@@ -1057,11 +1066,11 @@ int msOGRWriteFromQuery( mapObj *map, outputFormatObj *format, int sendheaders )
 int msPopulateRendererVTableOGR( rendererVTableObj *renderer )
 {
 #ifdef USE_OGR
-    /* we aren't really a normal renderer so we leave everything default */
-    return MS_SUCCESS;
+  /* we aren't really a normal renderer so we leave everything default */
+  return MS_SUCCESS;
 #else
-    msSetError(MS_OGRERR, "OGR Driver requested but is not built in", 
-               "msPopulateRendererVTableOGR()");
-    return MS_FAILURE;
+  msSetError(MS_OGRERR, "OGR Driver requested but is not built in",
+             "msPopulateRendererVTableOGR()");
+  return MS_FAILURE;
 #endif
 }
diff --git a/maporaclespatial.c b/maporaclespatial.c
index 4969df3..9ea9729 100644
--- a/maporaclespatial.c
+++ b/maporaclespatial.c
@@ -1,13 +1,13 @@
 /******************************************************************************
  * Project: MapServer
- * Purpose: Native access to Oracle Spatial (SDO) data.  
+ * Purpose: Native access to Oracle Spatial (SDO) data.
  * Author:  Fernando Simon (fsimon at univali.br)
  *          Rodrigo Becke Cabral
  *          Adriana Gomes Alves
  *
  * Notes: Developed under several funding agreements:
  *
- *   1) n.45/00 between CTTMAR/UNIVALI (www.cttmar.univali.br) 
+ *   1) n.45/00 between CTTMAR/UNIVALI (www.cttmar.univali.br)
  *      and CEPSUL/IBAMA (www.ibama.gov.br)
  *
  *   2) CNPq (www.cnpq.br) under process 401263.03-7
@@ -24,7 +24,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -39,7 +39,7 @@
 #include "mapserver.h"
 #include <assert.h>
 
-MS_CVSID("$Id$")
+
 
 #ifdef USE_ORACLESPATIAL
 
@@ -65,116 +65,110 @@ MS_CVSID("$Id$")
 #define TABLE_NAME_SIZE            2000
 
 typedef
-    struct
-    {
-        OCINumber x;
-        OCINumber y;
-        OCINumber z;
-    } SDOPointObj;
+struct {
+  OCINumber x;
+  OCINumber y;
+  OCINumber z;
+} SDOPointObj;
 
 typedef
-    struct
-    {
-        OCINumber gtype;
-        OCINumber srid;
-        SDOPointObj point;
-        OCIArray *elem_info;
-        OCIArray *ordinates;
-    } SDOGeometryObj;
+struct {
+  OCINumber gtype;
+  OCINumber srid;
+  SDOPointObj point;
+  OCIArray *elem_info;
+  OCIArray *ordinates;
+} SDOGeometryObj;
 
 typedef
-    struct
-    {
-        OCIInd _atomic;
-        OCIInd x;
-        OCIInd y;
-        OCIInd z;
-    } SDOPointInd;
+struct {
+  OCIInd _atomic;
+  OCIInd x;
+  OCIInd y;
+  OCIInd z;
+} SDOPointInd;
 
 typedef
-    struct
-    {
-        OCIInd _atomic;
-        OCIInd gtype;
-        OCIInd srid;
-        SDOPointInd point;
-        OCIInd elem_info;
-        OCIInd ordinates;
-    } SDOGeometryInd;
+struct {
+  OCIInd _atomic;
+  OCIInd gtype;
+  OCIInd srid;
+  SDOPointInd point;
+  OCIInd elem_info;
+  OCIInd ordinates;
+} SDOGeometryInd;
 
 typedef
-    text item_text[TEXT_SIZE];
+text item_text[TEXT_SIZE];
 
 typedef
-    item_text item_text_array[ARRAY_SIZE];
+item_text item_text_array[ARRAY_SIZE];
 
 typedef
-    item_text item_text_array_query[QUERY_SIZE];
+item_text item_text_array_query[QUERY_SIZE];
 
 typedef
-    struct
-    {
-        /*Oracle handlers (global to connection)*/
-        OCIEnv *envhp;
-        OCIError *errhp;
-        OCISvcCtx *svchp;
-        int last_oci_status;
-        text last_oci_error[2048];
-        /* This references counter is to avoid the cache freed if there are other layers that could use it */
-        int ref_count;
-    } msOracleSpatialHandler;
+struct {
+  /*Oracle handlers (global to connection)*/
+  OCIEnv *envhp;
+  OCIError *errhp;
+  OCISvcCtx *svchp;
+  int last_oci_status;
+  text last_oci_error[2048];
+  /* This references counter is to avoid the cache freed if there are other layers that could use it */
+  int ref_count;
+} msOracleSpatialHandler;
 
 typedef
-    struct
-    {
-        /* Oracle data handlers (global to connection) */
-        OCIDescribe *dschp;
-        OCIType *tdo;        
-    } msOracleSpatialDataHandler;
+struct {
+  /* Oracle data handlers (global to connection) */
+  OCIDescribe *dschp;
+  OCIType *tdo;
+} msOracleSpatialDataHandler;
 
 typedef
-    struct
-    {
-        OCIStmt *stmthp;
+struct {
+  OCIStmt *stmthp;
 
-        /* fetch data buffer */
-        ub4 rows_count; /* total number of rows (so far) within cursor */
-        ub4 row_num; /* current row index within cursor results */
-        ub4 rows_fetched; /* total number of rows fetched into our buffer */
-        ub4 row; /* current row index within our buffer */
+  /* fetch data buffer */
+  ub4 rows_count; /* total number of rows (so far) within cursor */
+  ub4 row_num; /* current row index within cursor results */
+  ub4 rows_fetched; /* total number of rows fetched into our buffer */
+  ub4 row; /* current row index within our buffer */
 
-        item_text_array *items; /* items buffer */
-        item_text_array_query *items_query; /* items buffer */
-        SDOGeometryObj *obj[ARRAY_SIZE]; /* spatial object buffer */
-        SDOGeometryInd *ind[ARRAY_SIZE]; /* object indicator (null) buffer */
+  item_text_array *items; /* items buffer */
+  item_text_array_query *items_query; /* items buffer */
+  SDOGeometryObj *obj[ARRAY_SIZE]; /* spatial object buffer */
+  SDOGeometryInd *ind[ARRAY_SIZE]; /* object indicator (null) buffer */
 
-        int uniqueidindex; /*allows to keep whic attribute id index is used as unique id*/ 
+  int uniqueidindex; /*allows to keep whic attribute id index is used as unique id*/
 
-    } msOracleSpatialStatement;
+} msOracleSpatialStatement;
 
 typedef
-    struct
-    {
-        /* oracle handlers */
-        msOracleSpatialHandler *orahandlers;
-        
-        /* oracle data handlers */
-        msOracleSpatialDataHandler *oradatahandlers;
-        msOracleSpatialStatement *orastmt;
-        
-        /* Following items are setup by WhichShapes
-         * used by NextShape, ResultGetShape
-         * disposed by CloseLayer (if set)
-         */
-        msOracleSpatialStatement *orastmt2;
-        
-    } msOracleSpatialLayerInfo;
-    
+struct {
+  /* oracle handlers */
+  msOracleSpatialHandler *orahandlers;
+
+  /* oracle data handlers */
+  msOracleSpatialDataHandler *oradatahandlers;
+  msOracleSpatialStatement *orastmt;
+
+  /* Following items are setup by WhichShapes
+   * used by NextShape, ResultGetShape
+   * disposed by CloseLayer (if set)
+   */
+  msOracleSpatialStatement *orastmt2;
+  /* Driver handling of pagination, enabled by default */
+  int paging;
+
+} msOracleSpatialLayerInfo;
+
 static OCIType  *ordinates_tdo = NULL;
 static OCIArray *ordinates;
-    
 
-    
+
+
 /* local prototypes */
 static int TRY( msOracleSpatialHandler *hand, sword status );
 static int ERROR( char *routine, msOracleSpatialHandler *hand, msOracleSpatialDataHandler *dthand );
@@ -207,7 +201,7 @@ static void osPoint(msOracleSpatialHandler *hand, shapeObj *shape, SDOGeometryOb
 static void osClosedPolygon(msOracleSpatialHandler *hand, shapeObj *shape, SDOGeometryObj *obj, int start, int end, lineObj points, int elem_type, int data3d, int data4d);
 static void osRectangle(msOracleSpatialHandler *hand, shapeObj *shape, SDOGeometryObj *obj, int start, int end, lineObj points, pointObj *pnt, int data3d, int data4d);
 static void osCircle(msOracleSpatialHandler *hand, shapeObj *shape, SDOGeometryObj *obj, int start, int end, lineObj points, pointObj *pnt, int data3d, int data4d);
-static void osArcPolygon(msOracleSpatialHandler *hand, shapeObj *shape, SDOGeometryObj *obj, int start, int end, lineObj arcpoints,int elem_type,int data3d, int data4d); 
+static void osArcPolygon(msOracleSpatialHandler *hand, shapeObj *shape, SDOGeometryObj *obj, int start, int end, lineObj arcpoints,int elem_type,int data3d, int data4d);
 static int osGetOrdinates(msOracleSpatialDataHandler *dthand, msOracleSpatialHandler *hand, shapeObj *shape, SDOGeometryObj *obj, SDOGeometryInd *ind);
 static int osCheck2DGtype(int pIntGtype);
 static int osCheck3DGtype(int pIntGtype);
@@ -224,62 +218,60 @@ static int osCheck4DGtype(int pIntGtype);
  * otherwise returns 1 */
 static int TRY( msOracleSpatialHandler *hand, sword status )
 {
-    sb4 errcode = 0;
-
-    if (hand->last_oci_status == MS_FAILURE)
-        return 0; /* error from previous call */
-
-    switch (status)
-    {
-        case OCI_SUCCESS_WITH_INFO:
-        case OCI_ERROR:
-            OCIErrorGet((dvoid *)hand->errhp, (ub4)1, (text *)NULL, &errcode, hand->last_oci_error, (ub4)sizeof(hand->last_oci_error), OCI_HTYPE_ERROR );
-            if (errcode == NULLERRCODE)
-            {
-                hand->last_oci_error[0] = (text)'\0';
-                return 1;
-            }
-            hand->last_oci_error[sizeof(hand->last_oci_error)-1] = 0; /* terminate string!? */
-            break;
-        case OCI_NEED_DATA:
-            strlcpy( (char *)hand->last_oci_error, "OCI_NEED_DATA", sizeof(hand->last_oci_error));
-            break;
-        case OCI_INVALID_HANDLE:
-            strlcpy( (char *)hand->last_oci_error, "OCI_INVALID_HANDLE", sizeof(hand->last_oci_error));
-            break;
-        case OCI_STILL_EXECUTING:
-            ((char*)hand->last_oci_error)[sizeof(hand->last_oci_error)-1] = 0;
-            break;
-        case OCI_CONTINUE:
-            strlcpy( (char *)hand->last_oci_error, "OCI_CONTINUE", sizeof(hand->last_oci_error));
-            break;
-        default:
-            return 1; /* no error */
-    }
+  sb4 errcode = 0;
+
+  if (hand->last_oci_status == MS_FAILURE)
+    return 0; /* error from previous call */
+
+  switch (status) {
+    case OCI_SUCCESS_WITH_INFO:
+    case OCI_ERROR:
+      OCIErrorGet((dvoid *)hand->errhp, (ub4)1, (text *)NULL, &errcode, hand->last_oci_error, (ub4)sizeof(hand->last_oci_error), OCI_HTYPE_ERROR );
+      if (errcode == NULLERRCODE) {
+        hand->last_oci_error[0] = (text)'\0';
+        return 1;
+      }
+      hand->last_oci_error[sizeof(hand->last_oci_error)-1] = 0; /* terminate string!? */
+      break;
+    case OCI_NEED_DATA:
+      strlcpy( (char *)hand->last_oci_error, "OCI_NEED_DATA", sizeof(hand->last_oci_error));
+      break;
+    case OCI_INVALID_HANDLE:
+      strlcpy( (char *)hand->last_oci_error, "OCI_INVALID_HANDLE", sizeof(hand->last_oci_error));
+      break;
+    case OCI_STILL_EXECUTING:
+      ((char*)hand->last_oci_error)[sizeof(hand->last_oci_error)-1] = 0;
+      break;
+    case OCI_CONTINUE:
+      strlcpy( (char *)hand->last_oci_error, "OCI_CONTINUE", sizeof(hand->last_oci_error));
+      break;
+    default:
+      return 1; /* no error */
+  }
 
-    /* if I got here, there was an error */
-    hand->last_oci_status = MS_FAILURE;
+  /* if I got here, there was an error */
+  hand->last_oci_status = MS_FAILURE;
 
-    return 0; /* error! */
+  return 0; /* error! */
 }
 
 OCIType *get_tdo(char *typename, msOracleSpatialHandler *hand, msOracleSpatialDataHandler *dthand )
 {
-    OCIParam *paramp = NULL;
-    OCIRef *type_ref = NULL;
-    OCIType *tdoe = NULL;
-    int success = 0;
+  OCIParam *paramp = NULL;
+  OCIRef *type_ref = NULL;
+  OCIType *tdoe = NULL;
+  int success = 0;
 
 
-    success = TRY( hand, OCIDescribeAny(hand->svchp, hand->errhp, (text *)typename,  (ub4)strlen((char *)typename), OCI_OTYPE_NAME, (ub1)1, (ub1)OCI_PTYPE_TYPE, dthand->dschp))
+  success = TRY( hand, OCIDescribeAny(hand->svchp, hand->errhp, (text *)typename,  (ub4)strlen((char *)typename), OCI_OTYPE_NAME, (ub1)1, (ub1)OCI_PTYPE_TYPE, dthand->dschp))
             &&TRY( hand, OCIAttrGet((dvoid *)dthand->dschp, (ub4)OCI_HTYPE_DESCRIBE, (dvoid *)&paramp, (ub4 *)0, (ub4)OCI_ATTR_PARAM, hand->errhp))
             &&TRY( hand, OCIAttrGet((dvoid *)paramp, (ub4)OCI_DTYPE_PARAM, (dvoid *)&type_ref, (ub4 *)0, (ub4)OCI_ATTR_REF_TDO, hand->errhp))
             &&TRY( hand, OCIObjectPin(hand->envhp, hand->errhp, type_ref, (OCIComplexObject *)0, OCI_PIN_ANY, OCI_DURATION_SESSION, OCI_LOCK_NONE, (dvoid **)&tdoe));
-   if (success) 
-        return tdoe;
+  if (success)
+    return tdoe;
 
-   /* if failure, return NULL*/
-   return NULL;
+  /* if failure, return NULL*/
+  return NULL;
 }
 
 
@@ -287,248 +279,238 @@ OCIType *get_tdo(char *typename, msOracleSpatialHandler *hand, msOracleSpatialDa
  * otherwise, returns 0 */
 static int ERROR( char *routine, msOracleSpatialHandler *hand, msOracleSpatialDataHandler *dthand )
 {
-    if (hand->last_oci_status == MS_FAILURE) 
-    {
-        /* there was an error */
-        msSetError( MS_ORACLESPATIALERR, (char *)hand->last_oci_error, routine );
-        return 1; /* error processed */
-     }
-     else
-         return 0; /* no error */
+  if (hand->last_oci_status == MS_FAILURE) {
+    /* there was an error */
+    msSetError( MS_ORACLESPATIALERR, (char *)hand->last_oci_error, routine );
+    
+    /* reset error flag */
+    hand->last_oci_status = MS_SUCCESS;
+    
+    return 1; /* error processed */
+  } else
+    return 0; /* no error */
 }
 
 /* break layer->connection (username/password at dblink) into username, password and dblink */
 static void msSplitLogin( char *connection, mapObj *map, char **username, char **password, char **dblink )
 {
-    char *src, *tgt, *conn_decrypted;
-    size_t buffer_size = 0;
+  char *src, *tgt, *conn_decrypted;
+  size_t buffer_size = 0;
 
-    /* bad 'connection' */
-    if (connection == NULL) return;
+  /* bad 'connection' */
+  if (connection == NULL) return;
 
-    buffer_size = strlen(connection)+1;
-    *username = (char*)malloc(buffer_size);
-    *password = (char*)malloc(buffer_size);
-    *dblink = (char*)malloc(buffer_size);
+  buffer_size = strlen(connection)+1;
+  *username = (char*)malloc(buffer_size);
+  *password = (char*)malloc(buffer_size);
+  *dblink = (char*)malloc(buffer_size);
 
-    /* clearup */
-    **username = **password = **dblink = 0;
+  /* clearup */
+  **username = **password = **dblink = 0;
 
-    /* Decrypt any encrypted token */
-    conn_decrypted = msDecryptStringTokens(map, connection);
-    if (conn_decrypted == NULL) return;
+  /* Decrypt any encrypted token */
+  conn_decrypted = msDecryptStringTokens(map, connection);
+  if (conn_decrypted == NULL) return;
 
-    /* ok, split connection */
-    for( tgt=*username, src=conn_decrypted; *src; src++, tgt++ )
-        if (*src=='/' || *src=='@')
-            break;
-        else
-            *tgt = *src;
+  /* ok, split connection */
+  for( tgt=*username, src=conn_decrypted; *src; src++, tgt++ )
+    if (*src=='/' || *src=='@')
+      break;
+    else
+      *tgt = *src;
+  *tgt = 0;
+  if (*src == '/') {
+    for( tgt=*password, ++src; *src; src++, tgt++ )
+      if (*src == '@')
+        break;
+      else
+        *tgt = *src;
     *tgt = 0;
-    if (*src == '/')
-    {
-        for( tgt=*password, ++src; *src; src++, tgt++ )
-            if (*src == '@')
-                break;
-            else
-                *tgt = *src;
-        *tgt = 0;
-    }
-    if (*src == '@') 
-    {
-        strlcpy( *dblink, ++src, buffer_size);
-    }
+  }
+  if (*src == '@') {
+    strlcpy( *dblink, ++src, buffer_size);
+  }
 
-    msFree(conn_decrypted);
+  msFree(conn_decrypted);
 }
 
 /* break layer->data into geometry_column_name, table_name and srid */
 static int msSplitData( char *data, char **geometry_column_name, char **table_name, char **unique, char **srid, int *function, int *version )
 {
-    char *tok_from = "from";
-    char *tok_using = "using";
-    char *tok_unique = "unique";
-    char *tok_srid = "srid";
-    char *tok_version = "version";
-    char data_version[4] = "";
-    char tok_function[11] = "";
-    int parenthesis, i;
-    char *src = data, *tgt;
-    int table_name_size = TABLE_NAME_SIZE;
-    size_t buffer_size = 0;
-
-    /* bad 'data' */
-    if (data == NULL)
-        return 0;
-
-    buffer_size = strlen(data)+1;
-    *geometry_column_name = (char*)malloc(buffer_size);
-    *unique = (char*)malloc(buffer_size);
-    *srid = (char*)malloc(buffer_size);
+  char *tok_from = "from";
+  char *tok_using = "using";
+  char *tok_unique = "unique";
+  char *tok_srid = "srid";
+  char *tok_version = "version";
+  char data_version[4] = "";
+  char tok_function[11] = "";
+  int parenthesis, i;
+  char *src = data, *tgt;
+  int table_name_size = TABLE_NAME_SIZE;
+  size_t buffer_size = 0;
+
+  /* bad 'data' */
+  if (data == NULL)
+    return 0;
+
+  buffer_size = strlen(data)+1;
+  *geometry_column_name = (char*)malloc(buffer_size);
+  *unique = (char*)malloc(buffer_size);
+  *srid = (char*)malloc(buffer_size);
+
+  /* clearup */
+  **geometry_column_name = **table_name = 0;
+
+  /* parsing 'geometry_column_name' */
+  for( ; *src && isspace( *src ); src++ ); /* skip blanks */
+  for( tgt=*geometry_column_name; *src; src++, tgt++ )
+    if (isspace( *src ))
+      break;
+    else
+      *tgt = *src;
+  *tgt = 0;
+
+  /* parsing 'from' */
+  for( ; *src && isspace( *src ); src++ ) ; /* skip blanks */
+  for( ; *src && *tok_from && tolower(*src)==*tok_from; src++, tok_from++ );
+  if (*tok_from != '\0')
+    return 0;
+
+  /* parsing 'table_name' or '(SELECT stmt)' */
+  i = 0;
+  for( ; *src && isspace( *src ); src++ ); /* skip blanks */
+  for( tgt=*table_name, parenthesis=0; *src; src++, tgt++, ++i ) {
+    if (*src == '(')
+      parenthesis++;
+    else if (*src == ')')
+      parenthesis--;
+    else if (parenthesis==0 && isspace( *src ))
+      break; /* stop on spaces */
+    /* double the size of the table_name array if necessary */
+    if (i == table_name_size) {
+      table_name_size *= 2;
+      *table_name = (char *) realloc(*table_name,sizeof(char *) * table_name_size);
+    }
+    *tgt = *src;
+  }
+  *tgt = 0;
+
+  strlcpy( *unique, "", buffer_size);
+  strlcpy( *srid, "NULL", buffer_size);
+  *function = -1;
+  *version = -1;
+
+  /* parsing 'unique' */
+  for( ; *src && isspace( *src ); src++ ) ; /* skip blanks */
+  if (*src != '\0') {
+    /* parse 'using' */
+    for( ; *src && *tok_using && tolower(*src)==*tok_using; src++, tok_using++ );
+    if (*tok_using != '\0')
+      return 0;
 
-    /* clearup */
-    **geometry_column_name = **table_name = 0;
+    /* parsing 'unique' */
+    for( ; *src && isspace( *src ); src++ ); /* skip blanks */
+    for( ; *src && *tok_unique && tolower(*src)==*tok_unique; src++, tok_unique++ );
 
-    /* parsing 'geometry_column_name' */
-    for( ;*src && isspace( *src ); src++ ); /* skip blanks */
-    for( tgt=*geometry_column_name; *src; src++, tgt++ )
+    if (*tok_unique == '\0') {
+      for( ; *src && isspace( *src ); src++ ); /* skip blanks */
+      if (*src == '\0')
+        return 0;
+      for( tgt=*unique; *src; src++, tgt++ )
         if (isspace( *src ))
-            break;
+          break;
         else
-            *tgt = *src;
-    *tgt = 0;
+          *tgt = *src;
+      *tgt = 0;
 
-    /* parsing 'from' */
-    for( ;*src && isspace( *src ); src++ ) ; /* skip blanks */
-    for( ;*src && *tok_from && tolower(*src)==*tok_from; src++, tok_from++ );
-    if (*tok_from != '\0')
+      if (*tok_unique != '\0')
         return 0;
-
-    /* parsing 'table_name' or '(SELECT stmt)' */
-    i = 0;
-    for( ;*src && isspace( *src ); src++ ); /* skip blanks */
-    for( tgt=*table_name, parenthesis=0; *src; src++, tgt++, ++i )
-    {
-        if (*src == '(')
-            parenthesis++;
-        else if (*src == ')')
-            parenthesis--;
-        else if (parenthesis==0 && isspace( *src ))
-            break; /* stop on spaces */
-        /* double the size of the table_name array if necessary */
-        if (i == table_name_size) {
-            table_name_size *= 2;
-            *table_name = (char *) realloc(*table_name,sizeof(char *) * table_name_size);
-        }
-        *tgt = *src;
     }
-    *tgt = 0;
-
-    strlcpy( *unique, "", buffer_size);
-    strlcpy( *srid, "NULL", buffer_size);
-    *function = -1;
-    *version = -1;
-
-    /* parsing 'unique' */
-    for( ;*src && isspace( *src ); src++ ) ; /* skip blanks */
-    if (*src != '\0')
-    {
-        /* parse 'using' */
-        for( ;*src && *tok_using && tolower(*src)==*tok_using; src++, tok_using++ );
-        if (*tok_using != '\0') 
-            return 0;
-
-        /* parsing 'unique' */
-        for( ;*src && isspace( *src ); src++ ); /* skip blanks */
-        for( ;*src && *tok_unique && tolower(*src)==*tok_unique; src++, tok_unique++ );
-
-        if (*tok_unique == '\0')
-        {
-            for( ;*src && isspace( *src ); src++ ); /* skip blanks */
-            if (*src == '\0') 
-                return 0;
-            for( tgt=*unique; *src; src++, tgt++ )
-                if (isspace( *src )) 
-                    break;
-                else 
-                    *tgt = *src;
-            *tgt = 0;
-
-            if (*tok_unique != '\0')
-                return 0;
-        }
 
-         /* parsing 'srid' */
-        for( ;*src && isspace( *src ); src++ ); /* skip blanks */
-        for( ;*src && *tok_srid && tolower(*src)==*tok_srid; src++, tok_srid++ );
-        if (*tok_srid == '\0')
-        {
-            for( ;*src && isspace( *src ); src++ ); /* skip blanks */
-            if (*src == '\0')
-                 return 0;
-            for( tgt=*srid; *src; src++, tgt++ )
-                if (isspace( *src ))
-                    break;
-                else 
-                    *tgt = *src;
-            *tgt = 0;
-
-            if (*tok_srid != '\0')
-                return 0;
-        }
+    /* parsing 'srid' */
+    for( ; *src && isspace( *src ); src++ ); /* skip blanks */
+    for( ; *src && *tok_srid && tolower(*src)==*tok_srid; src++, tok_srid++ );
+    if (*tok_srid == '\0') {
+      for( ; *src && isspace( *src ); src++ ); /* skip blanks */
+      if (*src == '\0')
+        return 0;
+      for( tgt=*srid; *src; src++, tgt++ )
+        if (isspace( *src ))
+          break;
+        else
+          *tgt = *src;
+      *tgt = 0;
 
-        /*parsing function/version */
-        for( ;*src && isspace( *src ); src++ );
-        if (*src != '\0')
-        {
-            for( tgt=tok_function; *src; src++, tgt++ )
-                if (isspace( *src ))
-                    break;
-                else 
-                    *tgt = *src;
-            *tgt = 0;
-        }
+      if (*tok_srid != '\0')
+        return 0;
+    }
 
-        /*Upcase conversion for the FUNCTION/VERSION token*/
-        for (i=0; tok_function[i] != '\0'; i++)
-            tok_function[i] = toupper(tok_function[i]);
-
-        if (strcmp(tok_function, "VERSION"))
-        {
-            if (!strcmp(tok_function, "FILTER") || !strcmp(tok_function, ""))
-                *function = FUNCTION_FILTER;
-            else if(!strcmp(tok_function, "RELATE"))
-                *function = FUNCTION_RELATE;
-            else if (!strcmp(tok_function,"GEOMRELATE"))
-                *function = FUNCTION_GEOMRELATE;
-            else if (!strcmp(tok_function,"NONE"))
-                *function = FUNCTION_NONE;
-            else
-            {
-                *function = -1;
-                return 0;
-            }
-
-            /*parsing VERSION token when user defined one function*/
-            for( ;*src && isspace( *src ); src++ );
-            for( ;*src && *tok_version && tolower(*src)==*tok_version; src++, tok_version++ );
-        }
+    /*parsing function/version */
+    for( ; *src && isspace( *src ); src++ );
+    if (*src != '\0') {
+      for( tgt=tok_function; *src; src++, tgt++ )
+        if (isspace( *src ))
+          break;
         else
-        {
-            for(tgt = "VERSION";*tgt && *tok_version && toupper(*tgt)==toupper(*tok_version); tgt++, tok_version++ );
-            *function = FUNCTION_FILTER;
-        }
+          *tgt = *src;
+      *tgt = 0;
+    }
+
+    /*Upcase conversion for the FUNCTION/VERSION token*/
+    for (i=0; tok_function[i] != '\0'; i++)
+      tok_function[i] = toupper(tok_function[i]);
+
+    if (strcmp(tok_function, "VERSION")) {
+      if (!strcmp(tok_function, "FILTER") || !strcmp(tok_function, ""))
+        *function = FUNCTION_FILTER;
+      else if(!strcmp(tok_function, "RELATE"))
+        *function = FUNCTION_RELATE;
+      else if (!strcmp(tok_function,"GEOMRELATE"))
+        *function = FUNCTION_GEOMRELATE;
+      else if (!strcmp(tok_function,"NONE"))
+        *function = FUNCTION_NONE;
+      else {
+        *function = -1;
+        return 0;
+      }
 
-        /*parsing version*/
-        if (*tok_version == '\0')
-        {
-            for( ;*src && isspace( *src ); src++ ); /* skip blanks */
-            for( tgt=data_version; *src; src++, tgt++ )
-                if (isspace( *src ))
-                    break;
-                else 
-                    *tgt = *src;
-            *tgt = 0;
-
-            for (i=0; data_version[i] != '\0'; i++)
-                data_version[i] = tolower(data_version[i]);
-
-            if (!strcmp(data_version, "8i"))
-                *version = VERSION_8i;
-            else if(!strcmp(data_version, "9i"))
-                *version = VERSION_9i;
-            else if (!strcmp(data_version, "10g"))
-                *version = VERSION_10g;
-            else
-                return 0;
+      /*parsing VERSION token when user defined one function*/
+      for( ; *src && isspace( *src ); src++ );
+      for( ; *src && *tok_version && tolower(*src)==*tok_version; src++, tok_version++ );
+    } else {
+      for(tgt = "VERSION"; *tgt && *tok_version && toupper(*tgt)==toupper(*tok_version); tgt++, tok_version++ );
+      *function = FUNCTION_FILTER;
+    }
 
-        }
+    /*parsing version*/
+    if (*tok_version == '\0') {
+      for( ; *src && isspace( *src ); src++ ); /* skip blanks */
+      for( tgt=data_version; *src; src++, tgt++ )
+        if (isspace( *src ))
+          break;
+        else
+          *tgt = *src;
+      *tgt = 0;
+
+      for (i=0; data_version[i] != '\0'; i++)
+        data_version[i] = tolower(data_version[i]);
+
+      if (!strcmp(data_version, "8i"))
+        *version = VERSION_8i;
+      else if(!strcmp(data_version, "9i"))
+        *version = VERSION_9i;
+      else if (!strcmp(data_version, "10g"))
+        *version = VERSION_10g;
+      else
+        return 0;
 
     }
-    /* finish parsing */
-    for( ;*src && isspace( *src ); src++ ); /* skip blanks */
 
-    return (*src == '\0');
+  }
+  /* finish parsing */
+  for( ; *src && isspace( *src ); src++ ); /* skip blanks */
+
+  return (*src == '\0');
 }
 
 
@@ -539,650 +521,600 @@ static int msSplitData( char *data, char **geometry_column_name, char **table_na
 /* create statement handle from database connection */
 static int msOCIOpenStatement( msOracleSpatialHandler *hand, msOracleSpatialStatement *sthand)
 {
-    int success = 0;
+  int success = 0;
 
-    /* allocate stmthp */
-    success = TRY( hand, OCIHandleAlloc( (dvoid *)hand->envhp, (dvoid **)&sthand->stmthp, (ub4)OCI_HTYPE_STMT, (size_t)0, (dvoid **)0 ) );
-    
-    sthand->rows_count = 0;
-    sthand->row_num = 0;
-    sthand->rows_fetched = 0;
-    sthand->row = 0;
-    sthand->items = NULL;
-    sthand->items_query = NULL;
-
-    //fprintf(stderr, "Creating statement handle at %p\n", sthand->stmthp);
-    
-    return success;
+  /* allocate stmthp */
+  success = TRY( hand, OCIHandleAlloc( (dvoid *)hand->envhp, (dvoid **)&sthand->stmthp, (ub4)OCI_HTYPE_STMT, (size_t)0, (dvoid **)0 ) );
+
+  sthand->rows_count = 0;
+  sthand->row_num = 0;
+  sthand->rows_fetched = 0;
+  sthand->row = 0;
+  sthand->items = NULL;
+  sthand->items_query = NULL;
+
+  /* fprintf(stderr, "Creating statement handle at %p\n", sthand->stmthp); */
+
+  return success;
 }
 
 /* create statement handle from database connection */
 static void msOCIFinishStatement( msOracleSpatialStatement *sthand )
 {
-    if(sthand != NULL) 
-    {
-        //fprintf(stderr, "Freeing statement handle at %p\n", sthand->stmthp);
-
-        if (sthand->stmthp != NULL)
-            OCIHandleFree( (dvoid *)sthand->stmthp, (ub4)OCI_HTYPE_STMT );
-        if (sthand->items != NULL)
-            free( sthand->items );
-        if (sthand->items_query != NULL)
-            free( sthand->items_query );
-        memset(sthand, 0, sizeof( msOracleSpatialStatement ) );
-        free(sthand);
-    }
+  if(sthand != NULL) {
+    /* fprintf(stderr, "Freeing statement handle at %p\n", sthand->stmthp); */
+
+    if (sthand->stmthp != NULL)
+      OCIHandleFree( (dvoid *)sthand->stmthp, (ub4)OCI_HTYPE_STMT );
+    if (sthand->items != NULL)
+      free( sthand->items );
+    if (sthand->items_query != NULL)
+      free( sthand->items_query );
+    memset(sthand, 0, sizeof( msOracleSpatialStatement ) );
+    free(sthand);
+  }
 }
 
 static int msOCISetDataHandlers(msOracleSpatialHandler *hand, msOracleSpatialDataHandler *dthand)
 {
-    int success = 0;
-    OCIParam *paramp = NULL;
-    OCIRef *type_ref = NULL;
+  int success = 0;
+  OCIParam *paramp = NULL;
+  OCIRef *type_ref = NULL;
 
-    success = TRY( hand,
-        /* allocate dschp */
-        OCIHandleAlloc( hand->envhp, (dvoid **)&dthand->dschp, (ub4)OCI_HTYPE_DESCRIBE, (size_t)0, (dvoid **)0 ) )
-           && TRY( hand,
-        /* describe SDO_GEOMETRY in svchp (dschp) */
-        OCIDescribeAny( hand->svchp, hand->errhp, (text *)SDO_GEOMETRY, (ub4)SDO_GEOMETRY_LEN, OCI_OTYPE_NAME, (ub1)1, (ub1)OCI_PTYPE_TYPE, dthand->dschp ) )
-           && TRY( hand,
-        /* get param for SDO_GEOMETRY */
-        OCIAttrGet( (dvoid *)dthand->dschp, (ub4)OCI_HTYPE_DESCRIBE, (dvoid *)&paramp, (ub4 *)0,  (ub4)OCI_ATTR_PARAM, hand->errhp ) )
-           && TRY( hand,
-        /* get type_ref for SDO_GEOMETRY */
-        OCIAttrGet( (dvoid *)paramp, (ub4)OCI_DTYPE_PARAM, (dvoid *)&type_ref, (ub4 *)0, (ub4)OCI_ATTR_REF_TDO, hand->errhp ) )
-           && TRY( hand,
-        /* get TDO for SDO_GEOMETRY */
-        OCIObjectPin( hand->envhp, hand->errhp, type_ref, (OCIComplexObject *)0, OCI_PIN_ANY, OCI_DURATION_SESSION, OCI_LOCK_NONE, (dvoid **)&dthand->tdo ) );
-
-    return success;
+  success = TRY( hand,
+                 /* allocate dschp */
+                 OCIHandleAlloc( hand->envhp, (dvoid **)&dthand->dschp, (ub4)OCI_HTYPE_DESCRIBE, (size_t)0, (dvoid **)0 ) )
+            && TRY( hand,
+                    /* describe SDO_GEOMETRY in svchp (dschp) */
+                    OCIDescribeAny( hand->svchp, hand->errhp, (text *)SDO_GEOMETRY, (ub4)SDO_GEOMETRY_LEN, OCI_OTYPE_NAME, (ub1)1, (ub1)OCI_PTYPE_TYPE, dthand->dschp ) )
+            && TRY( hand,
+                    /* get param for SDO_GEOMETRY */
+                    OCIAttrGet( (dvoid *)dthand->dschp, (ub4)OCI_HTYPE_DESCRIBE, (dvoid *)&paramp, (ub4 *)0,  (ub4)OCI_ATTR_PARAM, hand->errhp ) )
+            && TRY( hand,
+                    /* get type_ref for SDO_GEOMETRY */
+                    OCIAttrGet( (dvoid *)paramp, (ub4)OCI_DTYPE_PARAM, (dvoid *)&type_ref, (ub4 *)0, (ub4)OCI_ATTR_REF_TDO, hand->errhp ) )
+            && TRY( hand,
+                    /* get TDO for SDO_GEOMETRY */
+                    OCIObjectPin( hand->envhp, hand->errhp, type_ref, (OCIComplexObject *)0, OCI_PIN_ANY, OCI_DURATION_SESSION, OCI_LOCK_NONE, (dvoid **)&dthand->tdo ) );
+
+  return success;
 }
 
 /* connect to database */
 static msOracleSpatialHandler *msOCISetHandlers( char *username, char *password, char *dblink )
 {
-    int success;
+  int success;
 
-    msOracleSpatialHandler *hand = NULL;
+  msOracleSpatialHandler *hand = NULL;
 
-    hand = (msOracleSpatialHandler *) malloc( sizeof(msOracleSpatialHandler));
-    if (hand == NULL)
-    {
-        msSetError(MS_MEMERR, NULL, "msOCISetHandlers()");
-        return NULL;
-    }
-    memset( hand, 0, sizeof(msOracleSpatialHandler) );
+  hand = (msOracleSpatialHandler *) malloc( sizeof(msOracleSpatialHandler));
+  if (hand == NULL) {
+    msSetError(MS_MEMERR, NULL, "msOCISetHandlers()");
+    return NULL;
+  }
+  memset( hand, 0, sizeof(msOracleSpatialHandler) );
 
-    hand->ref_count = 1;
-    hand->last_oci_status = MS_SUCCESS;
-    hand->last_oci_error[0] = (text)'\0';
+  hand->ref_count = 1;
+  hand->last_oci_status = MS_SUCCESS;
+  hand->last_oci_error[0] = (text)'\0';
 
-    success = TRY( hand,
-        /* allocate envhp */
-        OCIEnvCreate( &hand->envhp, OCI_OBJECT, (dvoid *)0, 0, 0, 0, (size_t) 0, (dvoid **)0 ) )
-           && TRY( hand,
-        /* allocate errhp */
-        OCIHandleAlloc( (dvoid *)hand->envhp, (dvoid **)&hand->errhp, (ub4)OCI_HTYPE_ERROR, (size_t)0, (dvoid **)0 ) )
-           && TRY( hand,
-        /* logon */
-        OCILogon( hand->envhp, hand->errhp, &hand->svchp, (text *)username, strlen(username), (text *)password, strlen(password), (text *)dblink, strlen(dblink) ) );
+  success = TRY( hand,
+                 /* allocate envhp */
+                 OCIEnvCreate( &hand->envhp, OCI_OBJECT, (dvoid *)0, 0, 0, 0, (size_t) 0, (dvoid **)0 ) )
+            && TRY( hand,
+                    /* allocate errhp */
+                    OCIHandleAlloc( (dvoid *)hand->envhp, (dvoid **)&hand->errhp, (ub4)OCI_HTYPE_ERROR, (size_t)0, (dvoid **)0 ) )
+            && TRY( hand,
+                    /* logon */
+                    OCILogon( hand->envhp, hand->errhp, &hand->svchp, (text *)username, strlen(username), (text *)password, strlen(password), (text *)dblink, strlen(dblink) ) );
 
-    if ( !success )
-    {
-        msSetError( MS_ORACLESPATIALERR,
-                        "Cannot create OCI Handlers. "
-                        "Connection failure. Check the connection string. "
-                        "Error: %s.",
-                        "msOracleSpatialLayerOpen()", hand->last_oci_error);
+  if ( !success ) {
+    msSetError( MS_ORACLESPATIALERR,
+                "Cannot create OCI Handlers. "
+                "Connection failure. Check the connection string. "
+                "Error: %s.",
+                "msOracleSpatialLayerOpen()", hand->last_oci_error);
 
-        msOCICloseHandlers(hand);
-        return NULL;
-    }
+    msOCICloseHandlers(hand);
+    return NULL;
+  }
 
-    return hand;
+  return hand;
 
 }
 
 /* disconnect from database */
 static void msOCICloseHandlers( msOracleSpatialHandler *hand )
 {
-    if (hand->svchp != NULL)
-        OCILogoff( hand->svchp, hand->errhp );
-    if (hand->errhp != NULL)
-        OCIHandleFree( (dvoid *)hand->errhp, (ub4)OCI_HTYPE_ERROR );
-    if (hand->envhp != NULL)
-        OCIHandleFree( (dvoid *)hand->envhp, (ub4)OCI_HTYPE_ENV );
-    if (hand != NULL)
-        memset( hand, 0, sizeof (msOracleSpatialHandler));
-    free(hand);
+  if (hand->svchp != NULL)
+    OCILogoff( hand->svchp, hand->errhp );
+  if (hand->errhp != NULL)
+    OCIHandleFree( (dvoid *)hand->errhp, (ub4)OCI_HTYPE_ERROR );
+  if (hand->envhp != NULL)
+    OCIHandleFree( (dvoid *)hand->envhp, (ub4)OCI_HTYPE_ENV );
+  if (hand != NULL)
+    memset( hand, 0, sizeof (msOracleSpatialHandler));
+  free(hand);
 }
 
 static void msOCICloseDataHandlers( msOracleSpatialDataHandler *dthand )
 {
-    if (dthand->dschp != NULL)
-        OCIHandleFree( (dvoid *)dthand->dschp, (ub4)OCI_HTYPE_DESCRIBE );
-    if (dthand != NULL)
-        memset( dthand, 0, sizeof (msOracleSpatialDataHandler));
-    free(dthand);
+  if (dthand->dschp != NULL)
+    OCIHandleFree( (dvoid *)dthand->dschp, (ub4)OCI_HTYPE_DESCRIBE );
+  if (dthand != NULL)
+    memset( dthand, 0, sizeof (msOracleSpatialDataHandler));
+  free(dthand);
 }
 
 static void msOCIClearLayerInfo( msOracleSpatialLayerInfo *layerinfo )
 {
-    if (layerinfo != NULL) {
-        memset( layerinfo, 0, sizeof( msOracleSpatialLayerInfo ) );
-        free(layerinfo);
-    }
+  if (layerinfo != NULL) {
+    memset( layerinfo, 0, sizeof( msOracleSpatialLayerInfo ) );
+    free(layerinfo);
+  }
 }
 
 /*function that creates the correct sql for geoditical srid for version 9i*/
 static void osGeodeticData(int function, int version, char *query_str, size_t size, char *geom_column_name, char *srid, rectObj rect)
 {
-    switch (function)
-    {
-        case FUNCTION_FILTER:
-        {
-            snprintf( query_str + strlen(query_str), size-strlen(query_str),
-                      "SDO_FILTER( %s, SDO_CS.VIEWPORT_TRANSFORM(MDSYS.SDO_GEOMETRY("
-                      "2003, 0, NULL,"
-                      "MDSYS.SDO_ELEM_INFO_ARRAY(1,1003,3),"
-                      ":ordinates ), :srid),"
-                      "'querytype=window') = 'TRUE'",
-                      geom_column_name);
-            break;
-        }
-        case FUNCTION_RELATE:
-        {
-            snprintf( query_str + strlen(query_str), size-strlen(query_str),
-                      "SDO_RELATE( %s, SDO_CS.VIEWPORT_TRANSFORM(MDSYS.SDO_GEOMETRY("
-                      "2003, 0, NULL,"
-                      "MDSYS.SDO_ELEM_INFO_ARRAY(1,1003,3),"
-                      ":ordinates ), :srid),"
-                      "'mask=anyinteract querytype=window') = 'TRUE'",
-                      geom_column_name);
-            break;
-        }
-        case FUNCTION_GEOMRELATE:
-        {
-            snprintf( query_str + strlen(query_str), size-strlen(query_str),
-                      "SDO_GEOM.RELATE( %s, 'anyinteract', SDO_CS.VIEWPORT_TRANSFORM(MDSYS.SDO_GEOMETRY("
-                      "2003, 0, NULL,"
-                      "MDSYS.SDO_ELEM_INFO_ARRAY(1,1003,3),"
-                      ":ordinates), :srid),"
-                      "%f) = 'TRUE' AND %s IS NOT NULL",
-                      geom_column_name,  TOLERANCE, geom_column_name );
-            break;
-        }
-        case FUNCTION_NONE:
-        {
-            break;
-        }
-        default:
-        {
-            snprintf( query_str + strlen(query_str),  size-strlen(query_str),
-                      "SDO_FILTER( %s, SDO_CS.VIEWPORT_TRANSFORM(MDSYS.SDO_GEOMETRY("
-                      "2003, 0, NULL,"
-                      "MDSYS.SDO_ELEM_INFO_ARRAY(1,1003,3),"
-                      ":ordinates), :srid),"
-                      "'querytype=window') = 'TRUE'",
-                      geom_column_name );
-        }
+  switch (function) {
+    case FUNCTION_FILTER: {
+      snprintf( query_str + strlen(query_str), size-strlen(query_str),
+                "SDO_FILTER( %s, SDO_CS.VIEWPORT_TRANSFORM(MDSYS.SDO_GEOMETRY("
+                "2003, 0, NULL,"
+                "MDSYS.SDO_ELEM_INFO_ARRAY(1,1003,3),"
+                ":ordinates ), :srid),"
+                "'querytype=window') = 'TRUE'",
+                geom_column_name);
+      break;
+    }
+    case FUNCTION_RELATE: {
+      snprintf( query_str + strlen(query_str), size-strlen(query_str),
+                "SDO_RELATE( %s, SDO_CS.VIEWPORT_TRANSFORM(MDSYS.SDO_GEOMETRY("
+                "2003, 0, NULL,"
+                "MDSYS.SDO_ELEM_INFO_ARRAY(1,1003,3),"
+                ":ordinates ), :srid),"
+                "'mask=anyinteract querytype=window') = 'TRUE'",
+                geom_column_name);
+      break;
+    }
+    case FUNCTION_GEOMRELATE: {
+      snprintf( query_str + strlen(query_str), size-strlen(query_str),
+                "SDO_GEOM.RELATE( %s, 'anyinteract', SDO_CS.VIEWPORT_TRANSFORM(MDSYS.SDO_GEOMETRY("
+                "2003, 0, NULL,"
+                "MDSYS.SDO_ELEM_INFO_ARRAY(1,1003,3),"
+                ":ordinates), :srid),"
+                "%f) = 'TRUE' AND %s IS NOT NULL",
+                geom_column_name,  TOLERANCE, geom_column_name );
+      break;
+    }
+    case FUNCTION_NONE: {
+      break;
+    }
+    default: {
+      snprintf( query_str + strlen(query_str),  size-strlen(query_str),
+                "SDO_FILTER( %s, SDO_CS.VIEWPORT_TRANSFORM(MDSYS.SDO_GEOMETRY("
+                "2003, 0, NULL,"
+                "MDSYS.SDO_ELEM_INFO_ARRAY(1,1003,3),"
+                ":ordinates), :srid),"
+                "'querytype=window') = 'TRUE'",
+                geom_column_name );
     }
+  }
 }
 
 /*function that generate the correct sql for no geoditic srid's*/
 static void osNoGeodeticData(int function, int version, char *query_str, size_t size, char *geom_column_name, char *srid, rectObj rect)
 {
-    switch (function)
-    {
-        case FUNCTION_FILTER:
-        {
-            snprintf( query_str + strlen(query_str), size-strlen(query_str),
-                     "SDO_FILTER( %s, MDSYS.SDO_GEOMETRY("
-                     "2003, :srid, NULL,"
-                     "MDSYS.SDO_ELEM_INFO_ARRAY(1,1003,3),"
-                  //   "MDSYS.SDO_ORDINATE_ARRAY(%.9g,%.9g,%.9g,%.9g)"
-                     ":ordinates"
-                     " ),'querytype=window') = 'TRUE'",
-                     geom_column_name);
-            break;
-        }
-        case FUNCTION_RELATE:
-        {
-            if (version == VERSION_10g)
-            {
-                snprintf( query_str + strlen(query_str), size-strlen(query_str),
-                         "SDO_ANYINTERACT( %s, MDSYS.SDO_GEOMETRY("
-                         "2003, :srid, NULL,"
-                         "MDSYS.SDO_ELEM_INFO_ARRAY(1,1003,3),"
-                         ":ordinates)) = 'TRUE'",
-                         geom_column_name);
-            }
-            else
-            {
-                snprintf( query_str + strlen(query_str), size-strlen(query_str),
-                         "SDO_RELATE( %s, MDSYS.SDO_GEOMETRY("
-                         "2003, :srid, NULL,"
-                         "MDSYS.SDO_ELEM_INFO_ARRAY(1,1003,3),"
-                         ":ordinates),"
-                         "'mask=anyinteract querytype=window') = 'TRUE'",
-                         geom_column_name);
-            }
-            break;
-        }
-        case FUNCTION_GEOMRELATE:
-        {
-            snprintf( query_str + strlen(query_str), size-strlen(query_str),
-                     "SDO_GEOM.RELATE( %s, 'anyinteract', MDSYS.SDO_GEOMETRY("
-                     "2003, :srid, NULL,"
-                     "MDSYS.SDO_ELEM_INFO_ARRAY(1,1003,3),"
-                     ":ordinates),"
-                     "%f) = 'TRUE' AND %s IS NOT NULL",
-                     geom_column_name, TOLERANCE, geom_column_name );
-            break;
-        }
-        case FUNCTION_NONE:
-        {
-            break;
-        }
-        default:
-        {
-            snprintf( query_str + strlen(query_str), size-strlen(query_str),
-                     "SDO_FILTER( %s, MDSYS.SDO_GEOMETRY("
-                     "2003, :srid, NULL,"
-                     "MDSYS.SDO_ELEM_INFO_ARRAY(1,1003,3),"
-                     ":ordinates),"
-                     "'querytype=window') = 'TRUE'",
-                     geom_column_name);
-        }
+  switch (function) {
+    case FUNCTION_FILTER: {
+      snprintf( query_str + strlen(query_str), size-strlen(query_str),
+                "SDO_FILTER( %s, MDSYS.SDO_GEOMETRY("
+                "2003, :srid, NULL,"
+                "MDSYS.SDO_ELEM_INFO_ARRAY(1,1003,3),"
+                /*   "MDSYS.SDO_ORDINATE_ARRAY(%.9g,%.9g,%.9g,%.9g)" */
+                ":ordinates"
+                " ),'querytype=window') = 'TRUE'",
+                geom_column_name);
+      break;
+    }
+    case FUNCTION_RELATE: {
+      if (version == VERSION_10g) {
+        snprintf( query_str + strlen(query_str), size-strlen(query_str),
+                  "SDO_ANYINTERACT( %s, MDSYS.SDO_GEOMETRY("
+                  "2003, :srid, NULL,"
+                  "MDSYS.SDO_ELEM_INFO_ARRAY(1,1003,3),"
+                  ":ordinates)) = 'TRUE'",
+                  geom_column_name);
+      } else {
+        snprintf( query_str + strlen(query_str), size-strlen(query_str),
+                  "SDO_RELATE( %s, MDSYS.SDO_GEOMETRY("
+                  "2003, :srid, NULL,"
+                  "MDSYS.SDO_ELEM_INFO_ARRAY(1,1003,3),"
+                  ":ordinates),"
+                  "'mask=anyinteract querytype=window') = 'TRUE'",
+                  geom_column_name);
+      }
+      break;
+    }
+    case FUNCTION_GEOMRELATE: {
+      snprintf( query_str + strlen(query_str), size-strlen(query_str),
+                "SDO_GEOM.RELATE( %s, 'anyinteract', MDSYS.SDO_GEOMETRY("
+                "2003, :srid, NULL,"
+                "MDSYS.SDO_ELEM_INFO_ARRAY(1,1003,3),"
+                ":ordinates),"
+                "%f) = 'TRUE' AND %s IS NOT NULL",
+                geom_column_name, TOLERANCE, geom_column_name );
+      break;
     }
+    case FUNCTION_NONE: {
+      break;
+    }
+    default: {
+      snprintf( query_str + strlen(query_str), size-strlen(query_str),
+                "SDO_FILTER( %s, MDSYS.SDO_GEOMETRY("
+                "2003, :srid, NULL,"
+                "MDSYS.SDO_ELEM_INFO_ARRAY(1,1003,3),"
+                ":ordinates),"
+                "'querytype=window') = 'TRUE'",
+                geom_column_name);
+    }
+  }
 }
 
 /* get ordinates from SDO buffer */
 static int msOCIGet2DOrdinates( msOracleSpatialHandler *hand, SDOGeometryObj *obj, int s, int e, pointObj *pt )
 {
-    double x, y;
-    int i, n, success = 1;
-    boolean exists;
-    OCINumber *oci_number;
-
-    for( i=s, n=0; i < e && success; i+=2, n++ ) 
-    {
-        success = TRY( hand,
-          OCICollGetElem( hand->envhp, hand->errhp, (OCIColl *)obj->ordinates, (sb4)i, (boolean *)&exists, (dvoid *)&oci_number, (dvoid **)0 ) )
-               && TRY( hand,
-          OCINumberToReal( hand->errhp, oci_number, (uword)sizeof(double), (dvoid *)&x ) )
-               && TRY( hand,
-          OCICollGetElem( hand->envhp, hand->errhp, (OCIColl *)obj->ordinates, (sb4)i+1, (boolean *)&exists, (dvoid *)&oci_number, (dvoid **)0 ) )
-               && TRY( hand,
-          OCINumberToReal( hand->errhp, oci_number, (uword)sizeof(double), (dvoid *)&y ) );
-
-        if (success) 
-        {
-            pt[n].x = x;
-            pt[n].y = y;
-        }
+  double x, y;
+  int i, n, success = 1;
+  boolean exists;
+  OCINumber *oci_number;
+
+  for( i=s, n=0; i < e && success; i+=2, n++ ) {
+    success = TRY( hand,
+                   OCICollGetElem( hand->envhp, hand->errhp, (OCIColl *)obj->ordinates, (sb4)i, (boolean *)&exists, (dvoid *)&oci_number, (dvoid **)0 ) )
+              && TRY( hand,
+                      OCINumberToReal( hand->errhp, oci_number, (uword)sizeof(double), (dvoid *)&x ) )
+              && TRY( hand,
+                      OCICollGetElem( hand->envhp, hand->errhp, (OCIColl *)obj->ordinates, (sb4)i+1, (boolean *)&exists, (dvoid *)&oci_number, (dvoid **)0 ) )
+              && TRY( hand,
+                      OCINumberToReal( hand->errhp, oci_number, (uword)sizeof(double), (dvoid *)&y ) );
+
+    if (success) {
+      pt[n].x = x;
+      pt[n].y = y;
     }
+  }
 
-    return success ? n : 0;
+  return success ? n : 0;
 }
 
 static int msOCIGet3DOrdinates( msOracleSpatialHandler *hand, SDOGeometryObj *obj, int s, int e, pointObj *pt )
 {
-    double x, y;
-    int i, n, success = 1;
-    boolean exists;
+  double x, y;
+  int i, n, success = 1;
+  boolean exists;
 #ifdef USE_POINT_Z_M
-    double z;
-    boolean numnull;
+  double z;
+  boolean numnull;
 #endif /* USE_POINT_Z_M */
-    OCINumber *oci_number;
-
-    for( i=s, n=0; i < e && success; i+=3, n++ ) 
-    {
-        success = TRY( hand,
-          OCICollGetElem( hand->envhp, hand->errhp, (OCIColl *)obj->ordinates, (sb4)i, (boolean *)&exists, (dvoid *)&oci_number, (dvoid **)0 ) )
-               && TRY( hand,
-          OCINumberToReal( hand->errhp, oci_number, (uword)sizeof(double), (dvoid *)&x ) )
-               && TRY( hand,
-          OCICollGetElem( hand->envhp, hand->errhp, (OCIColl *)obj->ordinates, (sb4)i+1, (boolean *)&exists, (dvoid *)&oci_number, (dvoid **)0 ) )
-               && TRY( hand,
-          OCINumberToReal( hand->errhp, oci_number, (uword)sizeof(double), (dvoid *)&y ) )
+  OCINumber *oci_number;
+
+  for( i=s, n=0; i < e && success; i+=3, n++ ) {
+    success = TRY( hand,
+                   OCICollGetElem( hand->envhp, hand->errhp, (OCIColl *)obj->ordinates, (sb4)i, (boolean *)&exists, (dvoid *)&oci_number, (dvoid **)0 ) )
+              && TRY( hand,
+                      OCINumberToReal( hand->errhp, oci_number, (uword)sizeof(double), (dvoid *)&x ) )
+              && TRY( hand,
+                      OCICollGetElem( hand->envhp, hand->errhp, (OCIColl *)obj->ordinates, (sb4)i+1, (boolean *)&exists, (dvoid *)&oci_number, (dvoid **)0 ) )
+              && TRY( hand,
+                      OCINumberToReal( hand->errhp, oci_number, (uword)sizeof(double), (dvoid *)&y ) )
 #ifdef USE_POINT_Z_M
-               && TRY( hand,
-          OCICollGetElem( hand->envhp, hand->errhp, (OCIColl *)obj->ordinates, (sb4)i+2, (boolean *)&exists, (dvoid *)&oci_number, (dvoid **)0 ) )
+              && TRY( hand,
+                      OCICollGetElem( hand->envhp, hand->errhp, (OCIColl *)obj->ordinates, (sb4)i+2, (boolean *)&exists, (dvoid *)&oci_number, (dvoid **)0 ) )
 #endif /* USE_POINT_Z_M */
-            ;
+              ;
 #ifdef USE_POINT_Z_M
-        if (success)
-        {
-            success = TRY(hand, OCINumberIsZero( hand->errhp, oci_number, (boolean *)&numnull));
-            if (success)
-            {
-                success = TRY( hand, OCINumberToReal( hand->errhp, oci_number, (uword)sizeof(double), (dvoid *)&z ) );
-            }
-            else
-            {
-                hand->last_oci_status = MS_SUCCESS;
-                strlcpy( (char *)hand->last_oci_error, "Retrieve z value, but NULL value for z. Setting z to 0.", sizeof(hand->last_oci_error));
-                z = 0;
-                success = 1;
-            }
-        }
+    if (success) {
+      success = TRY(hand, OCINumberIsZero( hand->errhp, oci_number, (boolean *)&numnull));
+      if (success) {
+        success = TRY( hand, OCINumberToReal( hand->errhp, oci_number, (uword)sizeof(double), (dvoid *)&z ) );
+      } else {
+        hand->last_oci_status = MS_SUCCESS;
+        strlcpy( (char *)hand->last_oci_error, "Retrieve z value, but NULL value for z. Setting z to 0.", sizeof(hand->last_oci_error));
+        z = 0;
+        success = 1;
+      }
+    }
 #endif /* USE_POINT_Z_M */
-        if (success) 
-        {
-            pt[n].x = x;
-            pt[n].y = y;
+    if (success) {
+      pt[n].x = x;
+      pt[n].y = y;
 #ifdef USE_POINT_Z_M
-            pt[n].z = z; 
+      pt[n].z = z;
 #endif /* USE_POINT_Z_M */
-        }
     }
+  }
 
-    return success ? n : 0;
+  return success ? n : 0;
 }
 
 static int msOCIGet4DOrdinates( msOracleSpatialHandler *hand, SDOGeometryObj *obj, int s, int e, pointObj *pt )
 {
-    double x, y;
-    int i, n, success = 1;
-    boolean exists;
+  double x, y;
+  int i, n, success = 1;
+  boolean exists;
 #ifdef USE_POINT_Z_M
-    double z;
-    boolean numnull;
+  double z;
+  boolean numnull;
 #endif /* USE_POINT_Z_M */
-    OCINumber *oci_number;
-    
-    for( i=s, n=0; i < e && success; i+=4, n++ ) 
-    {
-        success = TRY( hand,
-          OCICollGetElem( hand->envhp, hand->errhp, (OCIColl *)obj->ordinates, (sb4)i, (boolean *)&exists, (dvoid *)&oci_number, (dvoid **)0 ) )
-               && TRY( hand,
-          OCINumberToReal( hand->errhp, oci_number, (uword)sizeof(double), (dvoid *)&x ) )
-               && TRY( hand,
-          OCICollGetElem( hand->envhp, hand->errhp, (OCIColl *)obj->ordinates, (sb4)i+1, (boolean *)&exists, (dvoid *)&oci_number, (dvoid **)0 ) )
-               && TRY( hand,
-          OCINumberToReal( hand->errhp, oci_number, (uword)sizeof(double), (dvoid *)&y ) )
+  OCINumber *oci_number;
+
+  for( i=s, n=0; i < e && success; i+=4, n++ ) {
+    success = TRY( hand,
+                   OCICollGetElem( hand->envhp, hand->errhp, (OCIColl *)obj->ordinates, (sb4)i, (boolean *)&exists, (dvoid *)&oci_number, (dvoid **)0 ) )
+              && TRY( hand,
+                      OCINumberToReal( hand->errhp, oci_number, (uword)sizeof(double), (dvoid *)&x ) )
+              && TRY( hand,
+                      OCICollGetElem( hand->envhp, hand->errhp, (OCIColl *)obj->ordinates, (sb4)i+1, (boolean *)&exists, (dvoid *)&oci_number, (dvoid **)0 ) )
+              && TRY( hand,
+                      OCINumberToReal( hand->errhp, oci_number, (uword)sizeof(double), (dvoid *)&y ) )
 #ifdef USE_POINT_Z_M
-               && TRY( hand,
-          OCICollGetElem( hand->envhp, hand->errhp, (OCIColl *)obj->ordinates, (sb4)i+2, (boolean *)&exists, (dvoid *)&oci_number, (dvoid **)0 ) )
-              
+              && TRY( hand,
+                      OCICollGetElem( hand->envhp, hand->errhp, (OCIColl *)obj->ordinates, (sb4)i+2, (boolean *)&exists, (dvoid *)&oci_number, (dvoid **)0 ) )
+
 #endif /* USE_POINT_Z_M */
-            ;
+              ;
 #ifdef USE_POINT_Z_M
-        if (success)
-        {
-            success = TRY(hand, OCINumberIsZero( hand->errhp, oci_number, (boolean *)&numnull));
-            if (success)
-            {
-                success = TRY( hand, OCINumberToReal( hand->errhp, oci_number, (uword)sizeof(double), (dvoid *)&z ) );
-            }
-            else
-            {
-                hand->last_oci_status = MS_SUCCESS;
-                strlcpy( (char *)hand->last_oci_error, "Retrieve z value, but NULL value for z. Setting z to 0.", sizeof(hand->last_oci_error));
-                z = 0;
-                success = 1;
-            }
-        }
+    if (success) {
+      success = TRY(hand, OCINumberIsZero( hand->errhp, oci_number, (boolean *)&numnull));
+      if (success) {
+        success = TRY( hand, OCINumberToReal( hand->errhp, oci_number, (uword)sizeof(double), (dvoid *)&z ) );
+      } else {
+        hand->last_oci_status = MS_SUCCESS;
+        strlcpy( (char *)hand->last_oci_error, "Retrieve z value, but NULL value for z. Setting z to 0.", sizeof(hand->last_oci_error));
+        z = 0;
+        success = 1;
+      }
+    }
 #endif /* USE_POINT_Z_M */
-        if (success) 
-        {  
-            pt[n].x = x;
-            pt[n].y = y;
+    if (success) {
+      pt[n].x = x;
+      pt[n].y = y;
 #ifdef USE_POINT_Z_M
-            pt[n].z = z; 
-    
+      pt[n].z = z;
+
 #endif /* USE_POINT_Z_M */
-        }
-    }    return success ? n : 0;
+    }
+  }
+  return success ? n : 0;
 }
 
 /* convert three-point circle to two-point rectangular bounds */
 static int msOCIConvertCircle( pointObj *pt )
 {
-    pointObj ptaux;
-    double dXa, dXb;
-    double ma, mb;
-    double cx, cy, r;
-    int success;
-
+  pointObj ptaux;
+  double dXa, dXb;
+  double ma, mb;
+  double cx, cy, r;
+  int success;
+
+  dXa = pt[1].x - pt[0].x;
+  success = (fabs( dXa ) > 1e-8);
+  if (!success) {
+    /* switch points 1 & 2 */
+    ptaux = pt[1];
+    pt[1] = pt[2];
+    pt[2] = ptaux;
     dXa = pt[1].x - pt[0].x;
     success = (fabs( dXa ) > 1e-8);
-    if (!success)
-    { /* switch points 1 & 2 */
-        ptaux = pt[1];
-        pt[1] = pt[2];
-        pt[2] = ptaux;
-        dXa = pt[1].x - pt[0].x;
-        success = (fabs( dXa ) > 1e-8);
-    }
-    if (success)
-    {
-        dXb = pt[2].x - pt[1].x;
-        success = (fabs( dXb ) > 1e-8);
-        if (!success)
-        { /* insert point 2 before point 0 */
-            ptaux = pt[2];
-            pt[2] = pt[1];
-            pt[1] = pt[0];
-            pt[0] = ptaux;
-            dXb = dXa; /* segment A has become B */
-            dXa = pt[1].x - pt[0].x; /* recalculate new segment A */
-            success = (fabs( dXa ) > 1e-8);
-        }
-    }
-    if (success)
-    {
-        ma = (pt[1].y - pt[0].y)/dXa;
-        mb = (pt[2].y - pt[1].y)/dXb;
-        success = (fabs( mb - ma ) > 1e-8);
-    }
-    if (!success)
-        return 0;
-
-    /* calculate center and radius */
-    cx = (ma*mb*(pt[0].y - pt[2].y) + mb*(pt[0].x + pt[1].x) - ma*(pt[1].x + pt[2].x))/(2*(mb - ma));
-    cy = (fabs( ma ) > 1e-8)
+  }
+  if (success) {
+    dXb = pt[2].x - pt[1].x;
+    success = (fabs( dXb ) > 1e-8);
+    if (!success) {
+      /* insert point 2 before point 0 */
+      ptaux = pt[2];
+      pt[2] = pt[1];
+      pt[1] = pt[0];
+      pt[0] = ptaux;
+      dXb = dXa; /* segment A has become B */
+      dXa = pt[1].x - pt[0].x; /* recalculate new segment A */
+      success = (fabs( dXa ) > 1e-8);
+    }
+  }
+  if (success) {
+    ma = (pt[1].y - pt[0].y)/dXa;
+    mb = (pt[2].y - pt[1].y)/dXb;
+    success = (fabs( mb - ma ) > 1e-8);
+  }
+  if (!success)
+    return 0;
+
+  /* calculate center and radius */
+  cx = (ma*mb*(pt[0].y - pt[2].y) + mb*(pt[0].x + pt[1].x) - ma*(pt[1].x + pt[2].x))/(2*(mb - ma));
+  cy = (fabs( ma ) > 1e-8)
        ? ((pt[0].y + pt[1].y)/2 - (cx - (pt[0].x + pt[1].x)/2)/ma)
        : ((pt[1].y + pt[2].y)/2 - (cx - (pt[1].x + pt[2].x)/2)/mb);
 
-    r  = sqrt( pow( pt[0].x - cx, 2 ) + pow( pt[0].y - cy, 2 ) );
+  r  = sqrt( pow( pt[0].x - cx, 2 ) + pow( pt[0].y - cy, 2 ) );
 
-    /* update pt buffer with rectangular bounds */
-    pt[0].x = cx - r;
-    pt[0].y = cy - r;
-    pt[1].x = cx + r;
-    pt[1].y = cy + r;
+  /* update pt buffer with rectangular bounds */
+  pt[0].x = cx - r;
+  pt[0].y = cy - r;
+  pt[1].x = cx + r;
+  pt[1].y = cy + r;
 
-    return 1;
+  return 1;
 }
 
 /*function that creates the correct sql for filter and filteritem*/
 static void osFilteritem(layerObj *layer, int function, char *query_str, size_t size, int mode)
 {
-    if (layer->filter.string != NULL)
-    {
-        if (mode == 1)
-            strlcat( query_str, " WHERE ", size);
-        else
-            strlcat( query_str, " AND ", size);
+  if (layer->filter.string != NULL) {
+    if (mode == 1)
+      strlcat( query_str, " WHERE ", size);
+    else
+      strlcat( query_str, " AND ", size);
 
-        if (layer->filteritem != NULL)
-        {
-            snprintf (query_str + strlen(query_str), size-strlen(query_str), " %s = ", layer->filteritem);
-            /* snprintf (query_str + strlen(query_str), " %s = ", layer->filteritem); */
-        }
+    if (layer->filteritem != NULL) {
+      snprintf (query_str + strlen(query_str), size-strlen(query_str), " %s = ", layer->filteritem);
+      /* snprintf (query_str + strlen(query_str), " %s = ", layer->filteritem); */
+    }
 
-        snprintf (query_str + strlen(query_str), size-strlen(query_str), " %s ", layer->filter.string);
-        /* snprintf(buffer, n, "gfdg %s %s %s", layer->filter.string, (layer->filteritem != NULL ? layer->filteritem : ""), ); */
+    snprintf (query_str + strlen(query_str), size-strlen(query_str), " %s ", layer->filter.string);
+    /* snprintf(buffer, n, "gfdg %s %s %s", layer->filter.string, (layer->filteritem != NULL ? layer->filteritem : ""), ); */
 
-        if (function != FUNCTION_NONE)
-            snprintf (query_str + strlen(query_str), size-strlen(query_str), " AND ");
-    }
-    else
-    {
-        if (function != FUNCTION_NONE)
-            strlcat( query_str, " WHERE ", size);
-    }
+    if (function != FUNCTION_NONE)
+      snprintf (query_str + strlen(query_str), size-strlen(query_str), " AND ");
+  } else {
+    if (function != FUNCTION_NONE)
+      strlcat( query_str, " WHERE ", size);
+  }
 }
 
 static void osAggrGetExtent(layerObj *layer, char *query_str, size_t size, char *geom_column_name, char *table_name)
 {
-    char query_str2[6000];
-    int i = 0;
+  char query_str2[6000];
+  int i = 0;
 
-    snprintf( query_str2, sizeof(query_str2), "(SELECT");
-    for( i = 0; i < layer->numitems; ++i )
-        snprintf( query_str2 + strlen(query_str2), sizeof(query_str2)-strlen(query_str2), " %s,", layer->items[i] );
+  snprintf( query_str2, sizeof(query_str2), "(SELECT");
+  for( i = 0; i < layer->numitems; ++i )
+    snprintf( query_str2 + strlen(query_str2), sizeof(query_str2)-strlen(query_str2), " %s,", layer->items[i] );
 
-    snprintf( query_str2 + strlen(query_str2), sizeof(query_str2)-strlen(query_str2), " %s FROM %s", geom_column_name, table_name);
+  snprintf( query_str2 + strlen(query_str2), sizeof(query_str2)-strlen(query_str2), " %s FROM %s", geom_column_name, table_name);
 
-    osFilteritem(layer, FUNCTION_NONE, query_str2, sizeof(query_str2), 1);    
+  osFilteritem(layer, FUNCTION_NONE, query_str2, sizeof(query_str2), 1);
 
-    snprintf( query_str, size, "SELECT SDO_AGGR_MBR(%s) AS GEOM from %s)", geom_column_name, query_str2);
+  snprintf( query_str, size, "SELECT SDO_AGGR_MBR(%s) AS GEOM from %s)", geom_column_name, query_str2);
 
-     if (layer->debug)
-       msDebug("osAggrGetExtent was called: %s.\n", query_str);
+  if (layer->debug)
+    msDebug("osAggrGetExtent was called: %s.\n", query_str);
 }
 
 static void osConvexHullGetExtent(layerObj *layer, char *query_str, size_t size, char *geom_column_name, char *table_name)
 {
-    char query_str2[6000];
-    int i = 0;
+  char query_str2[6000];
+  int i = 0;
 
-    snprintf( query_str2, sizeof(query_str2), "(SELECT");
-    for( i = 0; i < layer->numitems; ++i )
-        snprintf( query_str2 + strlen(query_str2), sizeof(query_str2)-strlen(query_str2), " %s,", layer->items[i] );
+  snprintf( query_str2, sizeof(query_str2), "(SELECT");
+  for( i = 0; i < layer->numitems; ++i )
+    snprintf( query_str2 + strlen(query_str2), sizeof(query_str2)-strlen(query_str2), " %s,", layer->items[i] );
 
-    snprintf( query_str2 + strlen(query_str2), sizeof(query_str2)-strlen(query_str2), " %s FROM %s", geom_column_name, table_name);
+  snprintf( query_str2 + strlen(query_str2), sizeof(query_str2)-strlen(query_str2), " %s FROM %s", geom_column_name, table_name);
 
-    osFilteritem(layer, FUNCTION_NONE, query_str2, sizeof(query_str2), 1);
-    
-    
-    snprintf( query_str, size, "SELECT SDO_GEOM.SDO_CONVEXHULL(%s, %f) AS GEOM from %s)", geom_column_name, TOLERANCE, query_str2);
+  osFilteritem(layer, FUNCTION_NONE, query_str2, sizeof(query_str2), 1);
+
+
+  snprintf( query_str, size, "SELECT SDO_GEOM.SDO_CONVEXHULL(%s, %f) AS GEOM from %s)", geom_column_name, TOLERANCE, query_str2);
 }
 
 static double osCalculateArcRadius(pointObj *pnt)
 {
-    double rc;
-    double r1, r2, r3;
+  double rc;
+  double r1, r2, r3;
 
-    r1 = sqrt( pow(pnt[0].x-pnt[1].x,2) + pow(pnt[0].y-pnt[1].y,2) );
-    r2 = sqrt( pow(pnt[1].x-pnt[2].x,2) + pow(pnt[1].y-pnt[2].y,2) );
-    r3 = sqrt( pow(pnt[2].x-pnt[0].x,2) + pow(pnt[2].y-pnt[0].y,2) );
-    rc = ( r1+r2+r3 )/2;
+  r1 = sqrt( pow(pnt[0].x-pnt[1].x,2) + pow(pnt[0].y-pnt[1].y,2) );
+  r2 = sqrt( pow(pnt[1].x-pnt[2].x,2) + pow(pnt[1].y-pnt[2].y,2) );
+  r3 = sqrt( pow(pnt[2].x-pnt[0].x,2) + pow(pnt[2].y-pnt[0].y,2) );
+  rc = ( r1+r2+r3 )/2;
 
-    return ( ( r1*r2*r3 )/( 4*sqrt( rc * (rc-r1) * (rc-r2) * (rc-r3) ) ) );
+  return ( ( r1*r2*r3 )/( 4*sqrt( rc * (rc-r1) * (rc-r2) * (rc-r3) ) ) );
 }
 
 static void osCalculateArc(pointObj *pnt, int data3d, int data4d, double area, double radius, double npoints, int side, lineObj arcline, shapeObj *shape)
 {
-    double length, ctrl, angle;  
-    double divbas, plusbas, cosbas, sinbas = 0;
+  double length, ctrl, angle;
+  double divbas, plusbas, cosbas, sinbas = 0;
 #ifdef USE_POINT_Z_M
-    double zrange = 0;
+  double zrange = 0;
 #endif /* USE_POINT_Z_M */
-    int i = 0;
+  int i = 0;
 
-    if ( npoints > 0 )
-    {
-        length = sqrt(((pnt[1].x-pnt[0].x)*(pnt[1].x-pnt[0].x))+((pnt[1].y-pnt[0].y)*(pnt[1].y-pnt[0].y)));
-        ctrl = length/(2*radius);
+  if ( npoints > 0 ) {
+    length = sqrt(((pnt[1].x-pnt[0].x)*(pnt[1].x-pnt[0].x))+((pnt[1].y-pnt[0].y)*(pnt[1].y-pnt[0].y)));
+    ctrl = length/(2*radius);
 
 #ifdef USE_POINT_Z_M
-        if (data3d||data4d)
-        {
-            zrange = labs(pnt[0].z-pnt[1].z)/npoints;
-            if ((pnt[0].z > pnt[1].z) && side == 1)
-                zrange *= -1;
-            else if ((pnt[0].z < pnt[1].z) && side == 1)
-                    zrange = zrange;
-            else if ((pnt[0].z > pnt[1].z) && side != 1)
-                    zrange *= -1;
-            else if ((pnt[0].z < pnt[1].z) && side != 1)
-                    zrange = zrange;
-        }
+    if (data3d||data4d) {
+      zrange = labs(pnt[0].z-pnt[1].z)/npoints;
+      if ((pnt[0].z > pnt[1].z) && side == 1)
+        zrange *= -1;
+      else if ((pnt[0].z < pnt[1].z) && side == 1)
+        zrange = zrange;
+      else if ((pnt[0].z > pnt[1].z) && side != 1)
+        zrange *= -1;
+      else if ((pnt[0].z < pnt[1].z) && side != 1)
+        zrange = zrange;
+    }
 #endif /* USE_POINT_Z_M */
 
-        if( ctrl <= 1 )
-        {
-            divbas = 2 * asin(ctrl);
-            plusbas = divbas/(npoints);
-            cosbas = (pnt[0].x-pnt[3].x)/radius;
-            sinbas = (pnt[0].y-pnt[3].y)/radius; 
-            angle = plusbas;
-
-            arcline.point = (pointObj *)malloc(sizeof(pointObj)*(npoints+1));
-            arcline.point[0].x = pnt[0].x;
-            arcline.point[0].y = pnt[0].y;
+    if( ctrl <= 1 ) {
+      divbas = 2 * asin(ctrl);
+      plusbas = divbas/(npoints);
+      cosbas = (pnt[0].x-pnt[3].x)/radius;
+      sinbas = (pnt[0].y-pnt[3].y)/radius;
+      angle = plusbas;
+
+      arcline.point = (pointObj *)malloc(sizeof(pointObj)*(npoints+1));
+      arcline.point[0].x = pnt[0].x;
+      arcline.point[0].y = pnt[0].y;
 #ifdef USE_POINT_Z_M
-            if (data3d||data4d)
-                arcline.point[0].z = pnt[0].z;
+      if (data3d||data4d)
+        arcline.point[0].z = pnt[0].z;
 #endif /* USE_POINT_Z_M */
 
-            for (i = 1; i <= npoints; i++)
-            {
-                if( side == 1)
-                {
-                    arcline.point[i].x = pnt[3].x + radius * ((cosbas*cos(angle))-(sinbas*sin(angle)));
-                    arcline.point[i].y = pnt[3].y + radius * ((sinbas*cos(angle))+(cosbas*sin(angle)));
+      for (i = 1; i <= npoints; i++) {
+        if( side == 1) {
+          arcline.point[i].x = pnt[3].x + radius * ((cosbas*cos(angle))-(sinbas*sin(angle)));
+          arcline.point[i].y = pnt[3].y + radius * ((sinbas*cos(angle))+(cosbas*sin(angle)));
 #ifdef USE_POINT_Z_M
-                    if (data3d||data4d)
-                        arcline.point[i].z = pnt[0].z + (zrange*i);
+          if (data3d||data4d)
+            arcline.point[i].z = pnt[0].z + (zrange*i);
 #endif /* USE_POINT_Z_M */
-                }
-                else
-                {
-                    if ( side == -1)
-                    {
-                        arcline.point[i].x = pnt[3].x + radius * ((cosbas*cos(angle))+(sinbas*sin(angle)));
-                        arcline.point[i].y = pnt[3].y + radius * ((sinbas*cos(angle))-(cosbas*sin(angle)));
+        } else {
+          if ( side == -1) {
+            arcline.point[i].x = pnt[3].x + radius * ((cosbas*cos(angle))+(sinbas*sin(angle)));
+            arcline.point[i].y = pnt[3].y + radius * ((sinbas*cos(angle))-(cosbas*sin(angle)));
 #ifdef USE_POINT_Z_M
-                        if (data3d||data4d)
-                            arcline.point[i].z = pnt[0].z + (zrange*i);
+            if (data3d||data4d)
+              arcline.point[i].z = pnt[0].z + (zrange*i);
 #endif /* USE_POINT_Z_M */
-                    }
-                    else
-                    {
-                         arcline.point[i].x = pnt[0].x;
-                         arcline.point[i].y = pnt[0].y;
+          } else {
+            arcline.point[i].x = pnt[0].x;
+            arcline.point[i].y = pnt[0].y;
 #ifdef USE_POINT_Z_M
-                         if (data3d||data4d)
-                             arcline.point[i].z = pnt[0].z;
+            if (data3d||data4d)
+              arcline.point[i].z = pnt[0].z;
 #endif /* USE_POINT_Z_M */
-                    }
-                }
-                angle += plusbas;
-            }
-
-            arcline.numpoints = npoints+1;
-            msAddLine( shape, &arcline );
-            free (arcline.point);
+          }
         }
+        angle += plusbas;
+      }
+
+      arcline.numpoints = npoints+1;
+      msAddLine( shape, &arcline );
+      free (arcline.point);
     }
-    else
-    {
-        arcline.point = (pointObj *)malloc(sizeof(pointObj)*(2));
-        arcline.point[0].x = pnt[0].x;
-        arcline.point[0].y = pnt[0].y;
-        arcline.point[1].x = pnt[1].x;
-        arcline.point[1].y = pnt[1].y;
+  } else {
+    arcline.point = (pointObj *)malloc(sizeof(pointObj)*(2));
+    arcline.point[0].x = pnt[0].x;
+    arcline.point[0].y = pnt[0].y;
+    arcline.point[1].x = pnt[1].x;
+    arcline.point[1].y = pnt[1].y;
 
 #ifdef USE_POINT_Z_M
-        if(data3d||data4d)
-        {
-            arcline.point[0].z = pnt[0].z;
-            arcline.point[1].z = pnt[1].z;
-        }
+    if(data3d||data4d) {
+      arcline.point[0].z = pnt[0].z;
+      arcline.point[1].z = pnt[1].z;
+    }
 #endif /* USE_POINT_Z_M */
 
-        arcline.numpoints = 2;
+    arcline.numpoints = 2;
 
-        msAddLine( shape, &arcline );
-        free (arcline.point);
-    }
+    msAddLine( shape, &arcline );
+    free (arcline.point);
+  }
 }
 
 /* Part of this function was based on Terralib function TeGenerateArc
@@ -1190,1055 +1122,975 @@ static void osCalculateArc(pointObj *pnt, int data3d, int data4d, double area, d
  * Part of this function was based on Dr. Ialo (Univali/Cttmar) functions. */
 static void osGenerateArc(shapeObj *shape, lineObj arcline, lineObj points, int i, int n, int data3d, int data4d)
 {
-    double mult, plus1, plus2, plus3, bpoint;
-    double cx, cy;
-    double radius, side, area, npoints;
-    double dist1 = 0;
-    double dist2 = 0;
-    pointObj point5[4];
-
-    mult = ( points.point[i+1].x - points.point[i].x ) 
-         * ( points.point[i+2].y - points.point[i].y ) 
-         - ( points.point[i+1].y - points.point[i].y ) 
+  double mult, plus1, plus2, plus3, bpoint;
+  double cx, cy;
+  double radius, side, area, npoints;
+  double dist1 = 0;
+  double dist2 = 0;
+  pointObj point5[4];
+
+  mult = ( points.point[i+1].x - points.point[i].x )
+         * ( points.point[i+2].y - points.point[i].y )
+         - ( points.point[i+1].y - points.point[i].y )
          * ( points.point[i+2].x - points.point[i].x );
 
-    if (mult)
-    {
-        /*point5 = (pointObj *)malloc(sizeof(pointObj)*(4));*/
+  if (mult) {
+    /*point5 = (pointObj *)malloc(sizeof(pointObj)*(4));*/
 
-        plus1 = points.point[i].x * points.point[i].x + points.point[i].y * points.point[i].y;
-        plus2 = points.point[i+1].x * points.point[i+1].x + points.point[i+1].y * points.point[i+1].y;
-        plus3 = points.point[i+2].x * points.point[i+2].x + points.point[i+2].y * points.point[i+2].y;
+    plus1 = points.point[i].x * points.point[i].x + points.point[i].y * points.point[i].y;
+    plus2 = points.point[i+1].x * points.point[i+1].x + points.point[i+1].y * points.point[i+1].y;
+    plus3 = points.point[i+2].x * points.point[i+2].x + points.point[i+2].y * points.point[i+2].y;
 
-        bpoint = plus1 * ( points.point[i+1].y - points.point[i+2].y ) 
-               + plus2 * ( points.point[i+2].y - points.point[i].y ) 
-               + plus3 * ( points.point[i].y - points.point[i+1].y );
+    bpoint = plus1 * ( points.point[i+1].y - points.point[i+2].y )
+             + plus2 * ( points.point[i+2].y - points.point[i].y )
+             + plus3 * ( points.point[i].y - points.point[i+1].y );
 
-        cx = bpoint / (2.0 * mult);
+    cx = bpoint / (2.0 * mult);
 
-        bpoint = plus1 * ( points.point[i+2].x - points.point[i+1].x ) 
-               + plus2 * ( points.point[i].x - points.point[i+2].x ) 
-               + plus3 * ( points.point[i+1].x - points.point[i].x );
+    bpoint = plus1 * ( points.point[i+2].x - points.point[i+1].x )
+             + plus2 * ( points.point[i].x - points.point[i+2].x )
+             + plus3 * ( points.point[i+1].x - points.point[i].x );
 
-        cy = bpoint / (2.0 * mult);
+    cy = bpoint / (2.0 * mult);
 
-        dist1 = (points.point[i+1].x - points.point[i].x) * (cy - points.point[i].y);
-        dist2 = (points.point[i+1].y - points.point[i].y) * (cx - points.point[i].x);
-        side = 0;
+    dist1 = (points.point[i+1].x - points.point[i].x) * (cy - points.point[i].y);
+    dist2 = (points.point[i+1].y - points.point[i].y) * (cx - points.point[i].x);
+    side = 0;
 
-        if((dist1-dist2) > 0)
-            side = 1;
-        else
-        {
-            if((dist1-dist2) < 0)
-                side = -1;
-        }
+    if((dist1-dist2) > 0)
+      side = 1;
+    else {
+      if((dist1-dist2) < 0)
+        side = -1;
+    }
 
-        point5[0] = points.point[i];
-        point5[1] = points.point[i+1];
-        point5[2] = points.point[i+2];
-        point5[3].x = cx;
-        point5[3].y = cy;
+    point5[0] = points.point[i];
+    point5[1] = points.point[i+1];
+    point5[2] = points.point[i+2];
+    point5[3].x = cx;
+    point5[3].y = cy;
 
-        radius = osCalculateArcRadius(point5);
+    radius = osCalculateArcRadius(point5);
 
-        area = ((points.point[i].x + points.point[i+1].x) * (points.point[i+1].y - points.point[i].y))
-             + ((points.point[i+1].x + points.point[i+2].x) * (points.point[i+2].y - points.point[i+1].y));
+    area = ((points.point[i].x + points.point[i+1].x) * (points.point[i+1].y - points.point[i].y))
+           + ((points.point[i+1].x + points.point[i+2].x) * (points.point[i+2].y - points.point[i+1].y));
 
-        npoints = labs(area/radius);
+    npoints = labs(area/radius);
 
-        point5[0] = points.point[i];
-        point5[1] = points.point[i+1];
-        osCalculateArc(point5, data3d, data4d, area, radius, (npoints>1000)?1000:npoints, side, arcline, shape);
+    point5[0] = points.point[i];
+    point5[1] = points.point[i+1];
+    osCalculateArc(point5, data3d, data4d, area, radius, (npoints>1000)?1000:npoints, side, arcline, shape);
 
-        point5[0] = points.point[i+1];
-        point5[1] = points.point[i+2];
-        osCalculateArc(point5, data3d, data4d,  area, radius, (npoints>1000)?1000:npoints, side, arcline, shape);
+    point5[0] = points.point[i+1];
+    point5[1] = points.point[i+2];
+    osCalculateArc(point5, data3d, data4d,  area, radius, (npoints>1000)?1000:npoints, side, arcline, shape);
 
-    }
-    else
-    {
-        arcline.point = (pointObj *)malloc(sizeof(pointObj)*(2));
-        arcline.point[0].x = points.point[i].x; 
-        arcline.point[0].y = points.point[i].y;
-        arcline.point[1].x = points.point[i+2].x;
-        arcline.point[1].y = points.point[i+2].y;
+  } else {
+    arcline.point = (pointObj *)malloc(sizeof(pointObj)*(2));
+    arcline.point[0].x = points.point[i].x;
+    arcline.point[0].y = points.point[i].y;
+    arcline.point[1].x = points.point[i+2].x;
+    arcline.point[1].y = points.point[i+2].y;
 
 #ifdef USE_POINT_Z_M
-        if (data3d||data4d)
-        {
-            arcline.point[0].z = points.point[i].z;
-            arcline.point[1].z = points.point[i+2].z;
-        }
+    if (data3d||data4d) {
+      arcline.point[0].z = points.point[i].z;
+      arcline.point[1].z = points.point[i+2].z;
+    }
 #endif /* USE_POINT_Z_M */
 
-        arcline.numpoints = 2;
+    arcline.numpoints = 2;
 
-        msAddLine( shape, &arcline );
-        free (arcline.point);
-    }
+    msAddLine( shape, &arcline );
+    free (arcline.point);
+  }
 }
 
 static void osShapeBounds ( shapeObj *shp )
 {
-    int i, f;
-
-    if ( (shp->numlines > 0) && (shp->line[0].numpoints > 0) )
-    {
-        shp->bounds.minx = shp->line[0].point[0].x;
-        shp->bounds.maxx = shp->line[0].point[0].x;
-        shp->bounds.miny = shp->line[0].point[0].y;
-        shp->bounds.maxy = shp->line[0].point[0].y;
-    }
-
-    for ( i = 0 ; i < shp->numlines; i++)
-    {
-        for( f = 0; f < shp->line[i].numpoints; f++)
-        {
-            if (shp->line[i].point[f].x < shp->bounds.minx)
-                shp->bounds.minx = shp->line[i].point[f].x;
-            if (shp->line[i].point[f].x > shp->bounds.maxx)
-                shp->bounds.maxx = shp->line[i].point[f].x;
-            if (shp->line[i].point[f].y < shp->bounds.miny)
-                shp->bounds.miny = shp->line[i].point[f].y;
-            if (shp->line[i].point[f].y > shp->bounds.maxy)
-                shp->bounds.maxy = shp->line[i].point[f].y;
-        }
-    }
+  int i, f;
+
+  if ( (shp->numlines > 0) && (shp->line[0].numpoints > 0) ) {
+    shp->bounds.minx = shp->line[0].point[0].x;
+    shp->bounds.maxx = shp->line[0].point[0].x;
+    shp->bounds.miny = shp->line[0].point[0].y;
+    shp->bounds.maxy = shp->line[0].point[0].y;
+  }
+
+  for ( i = 0 ; i < shp->numlines; i++) {
+    for( f = 0; f < shp->line[i].numpoints; f++) {
+      if (shp->line[i].point[f].x < shp->bounds.minx)
+        shp->bounds.minx = shp->line[i].point[f].x;
+      if (shp->line[i].point[f].x > shp->bounds.maxx)
+        shp->bounds.maxx = shp->line[i].point[f].x;
+      if (shp->line[i].point[f].y < shp->bounds.miny)
+        shp->bounds.miny = shp->line[i].point[f].y;
+      if (shp->line[i].point[f].y > shp->bounds.maxy)
+        shp->bounds.maxy = shp->line[i].point[f].y;
+    }
+  }
 }
 
 static void osCloneShape(shapeObj *shape, shapeObj *newshape, int data3d, int data4d)
 {
-    int max_points = 0;
-    int i,f,g;
-    lineObj shapeline = {0, NULL};
+  int max_points = 0;
+  int i,f,g;
+  lineObj shapeline = {0, NULL};
 
-    for (i = 0; i < shape->numlines; i++)
-        max_points += shape->line[i].numpoints;
+  for (i = 0; i < shape->numlines; i++)
+    max_points += shape->line[i].numpoints;
 
-    if (max_points > 0)
-        shapeline.point = (pointObj *)malloc( sizeof(pointObj)*max_points );
+  if (max_points > 0)
+    shapeline.point = (pointObj *)malloc( sizeof(pointObj)*max_points );
 
-    g = 0;
-    for ( i = 0 ; i < shape->numlines; i++)
-    {
-        for( f = 0; f < shape->line[i].numpoints && g <= max_points; f++, g++)
-        {
-            shapeline.point[g].x = shape->line[i].point[f].x;
-            shapeline.point[g].y = shape->line[i].point[f].y;
+  g = 0;
+  for ( i = 0 ; i < shape->numlines; i++) {
+    for( f = 0; f < shape->line[i].numpoints && g <= max_points; f++, g++) {
+      shapeline.point[g].x = shape->line[i].point[f].x;
+      shapeline.point[g].y = shape->line[i].point[f].y;
 #ifdef USE_POINT_Z_M
-            if (data3d||data4d)
-                shapeline.point[g].z = shape->line[i].point[f].z;
+      if (data3d||data4d)
+        shapeline.point[g].z = shape->line[i].point[f].z;
 #endif /* USE_POINT_Z_M */
-        }
     }
+  }
 
-    if (g)
-    {
-        shapeline.numpoints = g;
-        newshape->type = shape->type; /* jimk: 2009/09/23 Fixes compound linestrings being converted to polygons */
-        msAddLine( newshape, &shapeline );
-    }
+  if (g) {
+    shapeline.numpoints = g;
+    newshape->type = shape->type; /* jimk: 2009/09/23 Fixes compound linestrings being converted to polygons */
+    msAddLine( newshape, &shapeline );
+  }
 }
 
 static void osPointCluster(msOracleSpatialHandler *hand, shapeObj *shape, SDOGeometryObj *obj, int start, int end, lineObj points, int interpretation, int data3d, int data4d)
 {
-    int n;
-
-    n = (end - start)/2;
-    //n = interpretation;
-    
-    // 
-    
-    //if (n == interpretation)
-   // {
-        points.point = (pointObj *)malloc( sizeof(pointObj)*n );
-
-        if (data3d)
-            n = msOCIGet3DOrdinates( hand, obj, start, end, points.point );
-        else if (data4d)
-            n = msOCIGet4DOrdinates( hand, obj, start, end, points.point );    
-        else
-            n = msOCIGet2DOrdinates( hand, obj, start, end, points.point );
-
-        if (n == interpretation && n>0)
-        {
-            shape->type = MS_SHAPE_POINT;
-            points.numpoints = n;
-            msAddLine( shape, &points );
-        }
-        free( points.point );
-   // }
+  int n;
+
+  n = (end - start)/2;
+  /* n = interpretation; */
+
+  /* if (n == interpretation) { */
+  points.point = (pointObj *)malloc( sizeof(pointObj)*n );
+
+  if (data3d)
+    n = msOCIGet3DOrdinates( hand, obj, start, end, points.point );
+  else if (data4d)
+    n = msOCIGet4DOrdinates( hand, obj, start, end, points.point );
+  else
+    n = msOCIGet2DOrdinates( hand, obj, start, end, points.point );
+
+  if (n == interpretation && n>0) {
+    shape->type = MS_SHAPE_POINT;
+    points.numpoints = n;
+    msAddLine( shape, &points );
+  }
+  free( points.point );
+  /* } */
 }
 
 static void osPoint(msOracleSpatialHandler *hand, shapeObj *shape, SDOGeometryObj *obj, int start, int end, lineObj points, pointObj *pnt, int data3d, int data4d)
 {
-    int n;
-
-    if (data3d)
-        n = msOCIGet3DOrdinates( hand, obj, start, end, pnt );
-    else if (data4d)
-        n = msOCIGet4DOrdinates( hand, obj, start, end,  pnt ); 
-    else
-        n = msOCIGet2DOrdinates( hand, obj, start, end, pnt ); /* n must be < 5 */
-
-    if (n == 1)
-    {
-        shape->type = MS_SHAPE_POINT;
-        points.numpoints = 1;
-        points.point = pnt;
-        msAddLine( shape, &points );
-    }
+  int n;
+
+  if (data3d)
+    n = msOCIGet3DOrdinates( hand, obj, start, end, pnt );
+  else if (data4d)
+    n = msOCIGet4DOrdinates( hand, obj, start, end,  pnt );
+  else
+    n = msOCIGet2DOrdinates( hand, obj, start, end, pnt ); /* n must be < 5 */
+
+  if (n == 1) {
+    shape->type = MS_SHAPE_POINT;
+    points.numpoints = 1;
+    points.point = pnt;
+    msAddLine( shape, &points );
+  }
 }
 
 static void osClosedPolygon(msOracleSpatialHandler *hand, shapeObj *shape, SDOGeometryObj *obj, int start, int end, lineObj points, int elem_type, int data3d, int data4d)
 {
-    int n;
-
-    n = (end - start)/2;
-    points.point = (pointObj *)malloc( sizeof(pointObj)*n );
-
-    if (data3d)
-        n = msOCIGet3DOrdinates( hand, obj, start, end, points.point );
-    else if (data4d)
-          n = msOCIGet4DOrdinates( hand, obj, start, end, points.point );
-    else
-        n = msOCIGet2DOrdinates( hand, obj, start, end, points.point );
-
-    if (n > 0)
-    {
-        shape->type = (elem_type==21) ? MS_SHAPE_LINE : MS_SHAPE_POLYGON;
-        points.numpoints = n;
-        msAddLine( shape, &points );
-    }
-    free( points.point );
+  int n;
+
+  n = (end - start)/2;
+  points.point = (pointObj *)malloc( sizeof(pointObj)*n );
+
+  if (data3d)
+    n = msOCIGet3DOrdinates( hand, obj, start, end, points.point );
+  else if (data4d)
+    n = msOCIGet4DOrdinates( hand, obj, start, end, points.point );
+  else
+    n = msOCIGet2DOrdinates( hand, obj, start, end, points.point );
+
+  if (n > 0) {
+    shape->type = (elem_type==21) ? MS_SHAPE_LINE : MS_SHAPE_POLYGON;
+    points.numpoints = n;
+    msAddLine( shape, &points );
+  }
+  free( points.point );
 }
 
 static void osRectangle(msOracleSpatialHandler *hand, shapeObj *shape, SDOGeometryObj *obj, int start, int end, lineObj points, pointObj *pnt, int data3d, int data4d)
 {
-    int n;
-
-    if (data3d)
-        n = msOCIGet3DOrdinates( hand, obj, start, end, pnt ); /* n must be < 5 */
-    else if (data4d)
-        n = msOCIGet4DOrdinates( hand, obj, start, end, pnt ); /* n must be < 5 */    
-    else
-        n = msOCIGet2DOrdinates( hand, obj, start, end, pnt ); /* n must be < 5 */
-
-    if (n == 2)
-    {
-        shape->type = MS_SHAPE_POLYGON;
-        points.numpoints = 5;
-        points.point = pnt;
-
-        /* point5 [0] & [1] contains the lower-left and upper-right points of the rectangle */
-        pnt[2] = pnt[1];
-        pnt[1].x = pnt[0].x;
-        pnt[3].x = pnt[2].x;
-        pnt[3].y = pnt[0].y;
-        pnt[4] = pnt[0]; 
+  int n;
+
+  if (data3d)
+    n = msOCIGet3DOrdinates( hand, obj, start, end, pnt ); /* n must be < 5 */
+  else if (data4d)
+    n = msOCIGet4DOrdinates( hand, obj, start, end, pnt ); /* n must be < 5 */
+  else
+    n = msOCIGet2DOrdinates( hand, obj, start, end, pnt ); /* n must be < 5 */
+
+  if (n == 2) {
+    shape->type = MS_SHAPE_POLYGON;
+    points.numpoints = 5;
+    points.point = pnt;
+
+    /* point5 [0] & [1] contains the lower-left and upper-right points of the rectangle */
+    pnt[2] = pnt[1];
+    pnt[1].x = pnt[0].x;
+    pnt[3].x = pnt[2].x;
+    pnt[3].y = pnt[0].y;
+    pnt[4] = pnt[0];
 #ifdef USE_POINT_Z_M
-        if (data3d||data4d)
-        {
-            pnt[1].z = pnt[0].z;
-            pnt[3].z = pnt[2].z;
-        }
+    if (data3d||data4d) {
+      pnt[1].z = pnt[0].z;
+      pnt[3].z = pnt[2].z;
+    }
 #endif /* USE_POINT_Z_M */
 
-        msAddLine( shape, &points );
-    }
+    msAddLine( shape, &points );
+  }
 }
 
 static void osCircle(msOracleSpatialHandler *hand, shapeObj *shape, SDOGeometryObj *obj, int start, int end, lineObj points, pointObj *pnt, int data3d, int data4d)
 {
-    int n;
-
-    if (data3d)
-        n = msOCIGet3DOrdinates( hand, obj, start, end, pnt ); /* n must be < 5 */
-    else if (data4d)
-        n = msOCIGet4DOrdinates( hand, obj, start, end, pnt ); /* n must be < 5 */    
-    else
-        n = msOCIGet2DOrdinates( hand, obj, start, end, pnt ); /* n must be < 5 */
-
-    if (n == 3)
-    {
-        if (msOCIConvertCircle( pnt ))
-        {
-            shape->type = MS_SHAPE_POINT;
-            points.numpoints = 2;
-            points.point = pnt;
-            msAddLine( shape, &points );
-        }
-        else
-        {
-            strlcpy( (char *)hand->last_oci_error, "Points in circle object are colinear", sizeof(hand->last_oci_error));
-            hand->last_oci_status = MS_FAILURE;
-        }
-    }
+  int n;
+
+  if (data3d)
+    n = msOCIGet3DOrdinates( hand, obj, start, end, pnt ); /* n must be < 5 */
+  else if (data4d)
+    n = msOCIGet4DOrdinates( hand, obj, start, end, pnt ); /* n must be < 5 */
+  else
+    n = msOCIGet2DOrdinates( hand, obj, start, end, pnt ); /* n must be < 5 */
+
+  if (n == 3) {
+    if (msOCIConvertCircle( pnt )) {
+      shape->type = MS_SHAPE_POINT;
+      points.numpoints = 2;
+      points.point = pnt;
+      msAddLine( shape, &points );
+    } else {
+      strlcpy( (char *)hand->last_oci_error, "Points in circle object are colinear", sizeof(hand->last_oci_error));
+      hand->last_oci_status = MS_FAILURE;
+    }
+  }
 }
 
 static void osArcPolygon(msOracleSpatialHandler *hand, shapeObj *shape, SDOGeometryObj *obj, int start, int end, lineObj arcpoints, int elem_type, int data3d, int data4d)
 {
-    int n, i;
-    lineObj points = {0, NULL};
-
-    n = (end - start)/2;
-    points.point = (pointObj *)malloc( sizeof(pointObj)*n );
-
-    if (data3d)
-        n = msOCIGet3DOrdinates( hand, obj, start, end, points.point );
-    else if (data4d)
-        n = msOCIGet4DOrdinates( hand, obj, start, end, points.point );      
-    else
-        n = msOCIGet2DOrdinates( hand, obj, start, end, points.point );
-
-    if (n > 2)
-    {
-        shape->type = (elem_type==32) ? MS_SHAPE_POLYGON : MS_SHAPE_LINE; 
-        points.numpoints = n;
-
-        for (i = 0; i < n-2; i = i+2)
-            osGenerateArc(shape, arcpoints, points, i, n, data3d, data4d);
-    }
-    free (points.point);
+  int n, i;
+  lineObj points = {0, NULL};
+
+  n = (end - start)/2;
+  points.point = (pointObj *)malloc( sizeof(pointObj)*n );
+
+  if (data3d)
+    n = msOCIGet3DOrdinates( hand, obj, start, end, points.point );
+  else if (data4d)
+    n = msOCIGet4DOrdinates( hand, obj, start, end, points.point );
+  else
+    n = msOCIGet2DOrdinates( hand, obj, start, end, points.point );
+
+  if (n > 2) {
+    shape->type = (elem_type==32) ? MS_SHAPE_POLYGON : MS_SHAPE_LINE;
+    points.numpoints = n;
+
+    for (i = 0; i < n-2; i = i+2)
+      osGenerateArc(shape, arcpoints, points, i, n, data3d, data4d);
+  }
+  free (points.point);
 }
 
 static int osCheck2DGtype(int pIntGtype)
 {
-   if (pIntGtype > 2000 && pIntGtype < 2008)
-   {
-      if (pIntGtype != 2004)
-          return MS_TRUE;
-   }
+  if (pIntGtype > 2000 && pIntGtype < 2008) {
+    if (pIntGtype != 2004)
+      return MS_TRUE;
+  }
 
-   return MS_FALSE;
+  return MS_FALSE;
 }
 
 static int osCheck3DGtype(int pIntGtype)
 {
-   if (pIntGtype > 3000 && pIntGtype < 3308)
-   {
-      if (pIntGtype > 3007)
-          pIntGtype-= 300;
-
-      if (pIntGtype <= 3007 && pIntGtype != 3004)
-          return MS_TRUE;
-   }
-   /*
-   * Future version, untested
-   * return (pIntGtype & 2208 && (pIntGtype & 3000 || pIntGtype & 3296) && pIntGtype & 3);
-   */
-   return MS_FALSE;
+  if (pIntGtype > 3000 && pIntGtype < 3308) {
+    if (pIntGtype > 3007)
+      pIntGtype-= 300;
+
+    if (pIntGtype <= 3007 && pIntGtype != 3004)
+      return MS_TRUE;
+  }
+  /*
+  * Future version, untested
+  * return (pIntGtype & 2208 && (pIntGtype & 3000 || pIntGtype & 3296) && pIntGtype & 3);
+  */
+  return MS_FALSE;
 }
 
 static int osCheck4DGtype(int pIntGtype)
 {
-  
-  if (pIntGtype > 4000 && pIntGtype < 4408)
-   {
-      if (pIntGtype > 4007)
-          pIntGtype-= 400;
 
-      if (pIntGtype <= 4007 && pIntGtype != 4004)
-           return MS_TRUE;
-      
-          
-    }
-    
-   return MS_FALSE;   
+  if (pIntGtype > 4000 && pIntGtype < 4408) {
+    if (pIntGtype > 4007)
+      pIntGtype-= 400;
+
+    if (pIntGtype <= 4007 && pIntGtype != 4004)
+      return MS_TRUE;
+
+
+  }
+
+  return MS_FALSE;
 }
 
 
 
 static int osGetOrdinates(msOracleSpatialDataHandler *dthand, msOracleSpatialHandler *hand, shapeObj *shape, SDOGeometryObj *obj, SDOGeometryInd *ind)
 {
-    int gtype, elem_type, compound_type;
-    float compound_lenght, compound_count;
-    ub4 etype;
-    ub4 interpretation;
-    int nelems, nords, data3d, data4d;
-    int elem, ord_start, ord_end;
-    boolean exists;
-    OCINumber *oci_number;
-    double x, y;
-#ifdef USE_POINT_Z_M
-    double z;
-#endif /* USE_POINT_Z_M */
-    int success;
-    lineObj points = {0, NULL};
-    pointObj point5[5]; /* for quick access */
-    shapeObj newshape; /* for compound polygons */
-
-    /*stat the variables for compound polygons*/
-    compound_lenght = 0;
-    compound_type = 0;
-    compound_count = -1;
-    data3d = 0;
-    data4d = 0;
-
-    if (ind->_atomic != OCI_IND_NULL)  /* not a null object */
-    {
-        nelems = nords = 0;
-        success = TRY( hand, OCICollSize( hand->envhp, hand->errhp, (OCIColl *)obj->elem_info, &nelems ) )
-               && TRY( hand, OCICollSize( hand->envhp, hand->errhp, (OCIColl *)obj->ordinates, &nords ) )
-               && TRY( hand, OCINumberToInt( hand->errhp, &(obj->gtype), (uword)sizeof(int), OCI_NUMBER_SIGNED, (dvoid *)&gtype ) );
-               /*&& (nords%2==0 && nelems%3==0);*/ /* check %2==0 for 2D geometries; and %3==0 for element info triplets */
-
-        if (success && osCheck2DGtype(gtype))
-        {
-            success = (nords%2==0 && nelems%3==0)?1:0; /* check %2==0 for 2D geometries; and %3==0 for element info triplets */
-        }
-        else if (success && osCheck3DGtype(gtype))
-        {
-            success = (nords%3==0 && nelems%3==0)?1:0; /* check %2==0 for 2D geometries; and %3==0 for element info triplets */
-            data3d = 1;
-            
-        }
-         else if (success && osCheck4DGtype(gtype))
-        {   
-            success = (nords%4==0 && nelems%3==0)?1:0; /* check %2==0 for 2D geometries; and %3==0 for element info triplets */
-            data4d = 1;
-                  }
-       
-
-        if (success)
-        {
-             /* reading SDO_POINT from SDO_GEOMETRY for a 2D/3D point geometry */
-            if ((gtype==2001 || gtype==3001 || gtype==4001 ) && ind->point._atomic == OCI_IND_NOTNULL && ind->point.x == OCI_IND_NOTNULL && ind->point.y == OCI_IND_NOTNULL)
-            {   
-                
-            
-                success = TRY( hand, OCINumberToReal( hand->errhp, &(obj->point.x), (uword)sizeof(double), (dvoid *)&x ) )
-                       && TRY( hand, OCINumberToReal( hand->errhp, &(obj->point.y), (uword)sizeof(double), (dvoid *)&y ) );
-
-                if (ERROR( "osGetOrdinates()", hand, dthand ))
-                    return MS_FAILURE;
-
-                shape->type = MS_SHAPE_POINT;
-
-                points.numpoints = 1;
-                points.point = point5;
-                point5[0].x = x;
-                point5[0].y = y;
+  int gtype, elem_type, compound_type;
+  float compound_lenght, compound_count;
+  ub4 etype;
+  ub4 interpretation;
+  int nelems, nords, data3d, data4d;
+  int elem, ord_start, ord_end;
+  boolean exists;
+  OCINumber *oci_number;
+  double x, y;
 #ifdef USE_POINT_Z_M
-                if (data3d || data4d)
-                {   
-                    if (ind->point.z == OCI_IND_NOTNULL)
-                    {
-                        success = TRY( hand, OCINumberToReal( hand->errhp, &(obj->point.z), (uword)sizeof(double), (dvoid *)&z ));
-                        if (ERROR( "osGetOrdinates()", hand, dthand ))
-                            return MS_FAILURE;
-                        else
-                            point5[0].z = z;
-                    }
-                    else
-                        point5[0].z = z;
-                }
+  double z;
 #endif /* USE_POINT_Z_M */
-                msAddLine( shape, &points );
-                return MS_SUCCESS;
-            }
-            /* if SDO_POINT not fetched, proceed reading elements (element info/ordinates) */
-            success = TRY( hand, OCICollGetElem( hand->envhp, hand->errhp, (OCIColl *)obj->elem_info,(sb4)0, (boolean *)&exists, (dvoid *)&oci_number, (dvoid **)0 ) )
-                   && TRY( hand, OCINumberToInt( hand->errhp, oci_number, (uword)sizeof(ub4), OCI_NUMBER_SIGNED, (dvoid *)&ord_end ) );
-
-            elem = 0;
-            ord_end--; /* shifts offset from 1..n to 0..n-1 */
-
-          do{
-              ord_start = ord_end;
-              if (elem+3 >= nelems) /* processing last element */
-              {
-                  ord_end = nords;
-                  success = 1;
-              }
-              else /* get start ordinate position for next element which is ord_end for this element */
-              {
-                  success = TRY( hand, OCICollGetElem( hand->envhp, hand->errhp, (OCIColl *)obj->elem_info, (sb4)elem+3, (boolean *)&exists, (dvoid *)&oci_number, (dvoid **)0 ) )
-                         && TRY( hand, OCINumberToInt( hand->errhp, oci_number, (uword)sizeof(ub4), OCI_NUMBER_SIGNED, (dvoid *)&ord_end ) );
-
-                  ord_end--; /* shifts offset from 1..n to 0..n-1 */
-              }
-              success = (success 
-                        && TRY( hand, OCICollGetElem( hand->envhp, hand->errhp, (OCIColl *)obj->elem_info, (sb4)elem+1, (boolean *)&exists, (dvoid *)&oci_number, (dvoid **)0) )
-                        && TRY( hand, OCINumberToInt( hand->errhp, oci_number, (uword)sizeof(ub4), OCI_NUMBER_UNSIGNED, (dvoid *)&etype ) )
-                        && TRY( hand, OCICollGetElem( hand->envhp, hand->errhp, (OCIColl *)obj->elem_info, (sb4)elem+2, (boolean *)&exists, (dvoid *)&oci_number, (dvoid **)0 ) )
-                        && TRY( hand, OCINumberToInt( hand->errhp, oci_number, (uword)sizeof(ub4), OCI_NUMBER_UNSIGNED, (dvoid *)&interpretation ) ));
-
-              if (ERROR( "osGetOrdinates()", hand, dthand ))
-                  return MS_FAILURE;
-
-              if ( etype == 1005 || etype == 2005  || etype == 4 )
-              {
-                  compound_type = 1;
-                  compound_lenght = interpretation;
-                  compound_count = 0;
-                  msInitShape(&newshape);
-              }
-
-              elem_type = (etype == 1 && interpretation > 1) ? 10 : ((etype%10)*10 + interpretation);
-
-
-              // msDebug("osGetOrdinates shape->index = %ld\telem_type =  %d\n",shape->index, elem_type);
- 
-              switch (elem_type)
-              {
-                  case 10: /* point cluster with 'interpretation'-points */
-                      osPointCluster (hand, shape, obj, ord_start, ord_end, points, interpretation, data3d, data4d);
-                      break;
-                  case 11: /* point type */
-                      osPoint(hand, shape, obj, ord_start, ord_end, points, point5, data3d, data4d);
-                      break;
-                  case 21: /* line string whose vertices are connected by straight line segments */
-                      if (compound_type)
-                          osClosedPolygon(hand, &newshape, obj, ord_start, (compound_count<compound_lenght)?ord_end+2:ord_end, points, elem_type, data3d, data4d);
-                      else
-                          osClosedPolygon(hand, shape, obj, ord_start, ord_end, points, elem_type, data3d, data4d);
-                      break;
-                  case 22: /* compound type */
-                      if (compound_type)
-                          osArcPolygon(hand, &newshape, obj, ord_start, (compound_count<compound_lenght)?ord_end+2:ord_end , points, elem_type, data3d, data4d); 
-                      else
-                          osArcPolygon(hand, shape, obj, ord_start, ord_end, points, elem_type, data3d, data4d); 
-                      break;
-                  case 31: /* simple polygon with n points, last point equals the first one */
-                      osClosedPolygon(hand, shape, obj, ord_start, ord_end, points, elem_type, data3d, data4d);
-                      break;
-                  case 32: /* Polygon with arcs */ 
-                      osArcPolygon(hand, shape, obj, ord_start, ord_end, points, elem_type, data3d, data4d); 
-                      break;
-                  case 33: /* rectangle defined by 2 points */
-                      osRectangle(hand, shape, obj, ord_start, ord_end, points, point5, data3d, data4d);
-                      break;
-                  case 34: /* circle defined by 3 points */
-                      osCircle(hand, shape, obj, ord_start, ord_end, points, point5, data3d, data4d);
-                      break;
-              }
-
-              if (compound_count >= compound_lenght)
-              {
-                  osCloneShape(&newshape, shape, data3d, data4d);
-                  msFreeShape(&newshape);
-              }
-
-              if (ERROR( "osGetOrdinates()", hand, dthand ))
-                  return MS_FAILURE;
-
-              /* prepare for next cycle */
-              ord_start = ord_end; 
-              elem += 3;
-
-              if (compound_type)
-                  compound_count++;
-
-          } while (elem < nelems); /* end of element loop */
-        } /* end of gtype big-if */
-    } /* end of not-null-object if */
-
-    if (compound_type)
-        msFreeShape(&newshape);
+  int success;
+  lineObj points = {0, NULL};
+  pointObj point5[5]; /* for quick access */
+  shapeObj newshape; /* for compound polygons */
 
-    return MS_SUCCESS;
-}
+  /*stat the variables for compound polygons*/
+  compound_lenght = 0;
+  compound_type = 0;
+  compound_count = -1;
+  data3d = 0;
+  data4d = 0;
+
+  if (ind->_atomic != OCI_IND_NULL) { /* not a null object */
+    nelems = nords = 0;
+    success = TRY( hand, OCICollSize( hand->envhp, hand->errhp, (OCIColl *)obj->elem_info, &nelems ) )
+              && TRY( hand, OCICollSize( hand->envhp, hand->errhp, (OCIColl *)obj->ordinates, &nords ) )
+              && TRY( hand, OCINumberToInt( hand->errhp, &(obj->gtype), (uword)sizeof(int), OCI_NUMBER_SIGNED, (dvoid *)&gtype ) );
+    /*&& (nords%2==0 && nelems%3==0);*/ /* check %2==0 for 2D geometries; and %3==0 for element info triplets */
+
+    if (success && osCheck2DGtype(gtype)) {
+      success = (nords%2==0 && nelems%3==0)?1:0; /* check %2==0 for 2D geometries; and %3==0 for element info triplets */
+    } else if (success && osCheck3DGtype(gtype)) {
+      success = (nords%3==0 && nelems%3==0)?1:0; /* check %2==0 for 2D geometries; and %3==0 for element info triplets */
+      data3d = 1;
+
+    } else if (success && osCheck4DGtype(gtype)) {
+      success = (nords%4==0 && nelems%3==0)?1:0; /* check %2==0 for 2D geometries; and %3==0 for element info triplets */
+      data4d = 1;
+    }
+
+
+    if (success) {
+      /* reading SDO_POINT from SDO_GEOMETRY for a 2D/3D point geometry */
+      if ((gtype==2001 || gtype==3001 || gtype==4001 ) && ind->point._atomic == OCI_IND_NOTNULL && ind->point.x == OCI_IND_NOTNULL && ind->point.y == OCI_IND_NOTNULL) {
+
+
+        success = TRY( hand, OCINumberToReal( hand->errhp, &(obj->point.x), (uword)sizeof(double), (dvoid *)&x ) )
+                  && TRY( hand, OCINumberToReal( hand->errhp, &(obj->point.y), (uword)sizeof(double), (dvoid *)&y ) );
+
+        if (ERROR( "osGetOrdinates()", hand, dthand ))
+          return MS_FAILURE;
+
+        shape->type = MS_SHAPE_POINT;
+
+        points.numpoints = 1;
+        points.point = point5;
+        point5[0].x = x;
+        point5[0].y = y;
+#ifdef USE_POINT_Z_M
+        if (data3d || data4d) {
+          if (ind->point.z == OCI_IND_NOTNULL) {
+            success = TRY( hand, OCINumberToReal( hand->errhp, &(obj->point.z), (uword)sizeof(double), (dvoid *)&z ));
+            if (ERROR( "osGetOrdinates()", hand, dthand ))
+              return MS_FAILURE;
+            else
+              point5[0].z = z;
+          } else
+            point5[0].z = z;
+        }
+#endif /* USE_POINT_Z_M */
+        msAddLine( shape, &points );
+        return MS_SUCCESS;
+      }
+      /* if SDO_POINT not fetched, proceed reading elements (element info/ordinates) */
+      success = TRY( hand, OCICollGetElem( hand->envhp, hand->errhp, (OCIColl *)obj->elem_info,(sb4)0, (boolean *)&exists, (dvoid *)&oci_number, (dvoid **)0 ) )
+                && TRY( hand, OCINumberToInt( hand->errhp, oci_number, (uword)sizeof(ub4), OCI_NUMBER_SIGNED, (dvoid *)&ord_end ) );
+
+      elem = 0;
+      ord_end--; /* shifts offset from 1..n to 0..n-1 */
+
+      do {
+        ord_start = ord_end;
+        if (elem+3 >= nelems) { /* processing last element */
+          ord_end = nords;
+          success = 1;
+        } else { /* get start ordinate position for next element which is ord_end for this element */
+          success = TRY( hand, OCICollGetElem( hand->envhp, hand->errhp, (OCIColl *)obj->elem_info, (sb4)elem+3, (boolean *)&exists, (dvoid *)&oci_number, (dvoid **)0 ) )
+                    && TRY( hand, OCINumberToInt( hand->errhp, oci_number, (uword)sizeof(ub4), OCI_NUMBER_SIGNED, (dvoid *)&ord_end ) );
+
+          ord_end--; /* shifts offset from 1..n to 0..n-1 */
+        }
+        success = (success
+                   && TRY( hand, OCICollGetElem( hand->envhp, hand->errhp, (OCIColl *)obj->elem_info, (sb4)elem+1, (boolean *)&exists, (dvoid *)&oci_number, (dvoid **)0) )
+                   && TRY( hand, OCINumberToInt( hand->errhp, oci_number, (uword)sizeof(ub4), OCI_NUMBER_UNSIGNED, (dvoid *)&etype ) )
+                   && TRY( hand, OCICollGetElem( hand->envhp, hand->errhp, (OCIColl *)obj->elem_info, (sb4)elem+2, (boolean *)&exists, (dvoid *)&oci_number, (dvoid **)0 ) )
+                   && TRY( hand, OCINumberToInt( hand->errhp, oci_number, (uword)sizeof(ub4), OCI_NUMBER_UNSIGNED, (dvoid *)&interpretation ) ));
+
+        if (ERROR( "osGetOrdinates()", hand, dthand ))
+          return MS_FAILURE;
+
+        if ( etype == 1005 || etype == 2005  || etype == 4 ) {
+          compound_type = 1;
+          compound_lenght = interpretation;
+          compound_count = 0;
+          msInitShape(&newshape);
+        }
+
+        elem_type = (etype == 1 && interpretation > 1) ? 10 : ((etype%10)*10 + interpretation);
+
+
+        /* msDebug("osGetOrdinates shape->index = %ld\telem_type =  %d\n",shape->index, elem_type); */
+
+        switch (elem_type) {
+          case 10: /* point cluster with 'interpretation'-points */
+            osPointCluster (hand, shape, obj, ord_start, ord_end, points, interpretation, data3d, data4d);
+            break;
+          case 11: /* point type */
+            osPoint(hand, shape, obj, ord_start, ord_end, points, point5, data3d, data4d);
+            break;
+          case 21: /* line string whose vertices are connected by straight line segments */
+            if (compound_type)
+              osClosedPolygon(hand, &newshape, obj, ord_start, (compound_count<compound_lenght)?ord_end+2:ord_end, points, elem_type, data3d, data4d);
+            else
+              osClosedPolygon(hand, shape, obj, ord_start, ord_end, points, elem_type, data3d, data4d);
+            break;
+          case 22: /* compound type */
+            if (compound_type)
+              osArcPolygon(hand, &newshape, obj, ord_start, (compound_count<compound_lenght)?ord_end+2:ord_end , points, elem_type, data3d, data4d);
+            else
+              osArcPolygon(hand, shape, obj, ord_start, ord_end, points, elem_type, data3d, data4d);
+            break;
+          case 31: /* simple polygon with n points, last point equals the first one */
+            osClosedPolygon(hand, shape, obj, ord_start, ord_end, points, elem_type, data3d, data4d);
+            break;
+          case 32: /* Polygon with arcs */
+            osArcPolygon(hand, shape, obj, ord_start, ord_end, points, elem_type, data3d, data4d);
+            break;
+          case 33: /* rectangle defined by 2 points */
+            osRectangle(hand, shape, obj, ord_start, ord_end, points, point5, data3d, data4d);
+            break;
+          case 34: /* circle defined by 3 points */
+            osCircle(hand, shape, obj, ord_start, ord_end, points, point5, data3d, data4d);
+            break;
+        }
+
+        if (compound_count >= compound_lenght) {
+          osCloneShape(&newshape, shape, data3d, data4d);
+          msFreeShape(&newshape);
+        }
+
+        if (ERROR( "osGetOrdinates()", hand, dthand ))
+          return MS_FAILURE;
+
+        /* prepare for next cycle */
+        ord_start = ord_end;
+        elem += 3;
+
+        if (compound_type)
+          compound_count++;
+
+      } while (elem < nelems); /* end of element loop */
+    } /* end of gtype big-if */
+  } /* end of not-null-object if */
+
+  if (compound_type)
+    msFreeShape(&newshape);
+
+  return MS_SUCCESS;
+}
 
 static void msOCICloseConnection( void *hand )
 {
-    msOCICloseHandlers( (msOracleSpatialHandler *)hand );
+  msOCICloseHandlers( (msOracleSpatialHandler *)hand );
 }
 
 /* opens a layer by connecting to db with username/password at database stored in layer->connection */
 int msOracleSpatialLayerOpen( layerObj *layer )
 {
-    char *username = NULL, *password = NULL, *dblink =  NULL;
+  char *username = NULL, *password = NULL, *dblink =  NULL;
 
-    msOracleSpatialLayerInfo *layerinfo = NULL;
-    msOracleSpatialDataHandler *dthand = NULL;
-    msOracleSpatialStatement *sthand = NULL, *sthand2 = NULL;
-    msOracleSpatialHandler *hand = NULL;
-    
-    if (layer->debug)
-        msDebug("msOracleSpatialLayerOpen called with: %s (Layer pointer %p)\n",layer->data, layer);
+  msOracleSpatialLayerInfo *layerinfo = NULL;
+  msOracleSpatialDataHandler *dthand = NULL;
+  msOracleSpatialStatement *sthand = NULL, *sthand2 = NULL;
+  msOracleSpatialHandler *hand = NULL;
 
-    if (layer->layerinfo != NULL) /* Skip if layer is already open */
-        return MS_SUCCESS;
+  if (layer->debug)
+    msDebug("msOracleSpatialLayerOpen called with: %s (Layer pointer %p)\n",layer->data, layer);
 
-    if (layer->data == NULL) 
-    {
-        msSetError( MS_ORACLESPATIALERR, 
-                    "Error parsing OracleSpatial DATA variable. Must be:"
-                    "'geometry_column FROM table_name [USING UNIQUE <column> SRID srid# FUNCTION]' or "
-                    "'geometry_column FROM (SELECT stmt) [USING UNIQUE <column> SRID srid# FUNCTION]'."
-                    "If want to set the FUNCTION statement you can use: FILTER, RELATE, GEOMRELATE or NONE.",
-                    "msOracleSpatialLayerOpen()");
+  if (layer->layerinfo != NULL) /* Skip if layer is already open */
+    return MS_SUCCESS;
 
-        return MS_FAILURE;
-    }
+  if (layer->data == NULL) {
+    msSetError( MS_ORACLESPATIALERR,
+                "Error parsing OracleSpatial DATA variable. Must be:"
+                "'geometry_column FROM table_name [USING UNIQUE <column> SRID srid# FUNCTION]' or "
+                "'geometry_column FROM (SELECT stmt) [USING UNIQUE <column> SRID srid# FUNCTION]'."
+                "If want to set the FUNCTION statement you can use: FILTER, RELATE, GEOMRELATE or NONE.",
+                "msOracleSpatialLayerOpen()");
 
-    layerinfo = (msOracleSpatialLayerInfo *)malloc(sizeof(msOracleSpatialLayerInfo));
-    dthand = (msOracleSpatialDataHandler *)malloc(sizeof(msOracleSpatialDataHandler));
-    sthand = (msOracleSpatialStatement *)malloc(sizeof(msOracleSpatialStatement));
-    sthand2 = (msOracleSpatialStatement *)malloc(sizeof(msOracleSpatialStatement));
+    return MS_FAILURE;
+  }
 
-    if ((dthand == NULL) || (layerinfo == NULL))
-    {
-        msSetError(MS_MEMERR, NULL, "msOracleSpatialLayerOpen()");
-        return MS_FAILURE;
-    }
+  layerinfo = (msOracleSpatialLayerInfo *)malloc(sizeof(msOracleSpatialLayerInfo));
+  dthand = (msOracleSpatialDataHandler *)malloc(sizeof(msOracleSpatialDataHandler));
+  sthand = (msOracleSpatialStatement *)malloc(sizeof(msOracleSpatialStatement));
+  sthand2 = (msOracleSpatialStatement *)malloc(sizeof(msOracleSpatialStatement));
 
-    memset( dthand, 0, sizeof(msOracleSpatialDataHandler) );
-    memset( sthand, 0, sizeof(msOracleSpatialStatement) );
-    memset( sthand2, 0, sizeof(msOracleSpatialStatement) );
-    memset( layerinfo, 0, sizeof(msOracleSpatialLayerInfo) );
+  if ((dthand == NULL) || (layerinfo == NULL)) {
+    msSetError(MS_MEMERR, NULL, "msOracleSpatialLayerOpen()");
+    return MS_FAILURE;
+  }
 
-    msSplitLogin( layer->connection, layer->map, &username, &password, &dblink );
+  memset( dthand, 0, sizeof(msOracleSpatialDataHandler) );
+  memset( sthand, 0, sizeof(msOracleSpatialStatement) );
+  memset( sthand2, 0, sizeof(msOracleSpatialStatement) );
+  memset( layerinfo, 0, sizeof(msOracleSpatialLayerInfo) );
+  layerinfo->paging = MS_TRUE;
 
-    hand = (msOracleSpatialHandler *) msConnPoolRequest( layer );
+  msSplitLogin( layer->connection, layer->map, &username, &password, &dblink );
 
-    if( hand == NULL )
-    {
+  hand = (msOracleSpatialHandler *) msConnPoolRequest( layer );
 
-        hand = msOCISetHandlers( username, password, dblink );
+  if( hand == NULL ) {
 
-        if (hand == NULL)
-        {
-            msOCICloseDataHandlers( dthand );
-            msOCIFinishStatement( sthand );
-            msOCIFinishStatement( sthand2 );
-            msOCIClearLayerInfo( layerinfo );
+    hand = msOCISetHandlers( username, password, dblink );
 
-            if (username) free(username);
-            if (password) free(password);
-            if (dblink) free(dblink);
-               
-            return MS_FAILURE;
-        }
+    if (hand == NULL) {
+      msOCICloseDataHandlers( dthand );
+      msOCIFinishStatement( sthand );
+      msOCIFinishStatement( sthand2 );
+      msOCIClearLayerInfo( layerinfo );
 
-        if ( layer->debug )
-            msDebug("msOracleSpatialLayerOpen. Shared connection not available. Creating one.\n");
+      if (username) free(username);
+      if (password) free(password);
+      if (dblink) free(dblink);
 
-        msConnPoolRegister( layer, hand, msOCICloseConnection );
-    }
-    else
-    {
-        hand->ref_count++;
-        hand->last_oci_status = MS_SUCCESS;
-        hand->last_oci_error[0] = (text)'\0';
+      return MS_FAILURE;
     }
 
-    if (!(msOCISetDataHandlers(hand, dthand) & msOCIOpenStatement(hand, sthand) & msOCIOpenStatement(hand, sthand2)))
-    {
-        msSetError( MS_ORACLESPATIALERR,
-                    "Cannot create OCI LayerInfo. "
-                    "Connection failure.",
-                    "msOracleSpatialLayerOpen()");
+    if ( layer->debug )
+      msDebug("msOracleSpatialLayerOpen. Shared connection not available. Creating one.\n");
 
-        if (layer->debug)
-            msDebug("msOracleSpatialLayerOpen. Cannot create OCI LayerInfo. Connection failure.\n");
+    msConnPoolRegister( layer, hand, msOCICloseConnection );
+  } else {
+    hand->ref_count++;
+    hand->last_oci_status = MS_SUCCESS;
+    hand->last_oci_error[0] = (text)'\0';
+  }
 
-        msOCICloseDataHandlers ( dthand );
-        msOCICloseHandlers( hand );
-        msOCIClearLayerInfo( layerinfo );
-    }
-    layerinfo->orahandlers = hand;
-    layerinfo->oradatahandlers = dthand;
-    layerinfo->orastmt = sthand;
-    layerinfo->orastmt2 = sthand2;
-    layer->layerinfo = layerinfo;
-    
-    if (username) free(username);
-    if (password) free(password);
-    if (dblink) free(dblink);
+  if (!(msOCISetDataHandlers(hand, dthand) & msOCIOpenStatement(hand, sthand) & msOCIOpenStatement(hand, sthand2))) {
+    msSetError( MS_ORACLESPATIALERR,
+                "Cannot create OCI LayerInfo. "
+                "Connection failure.",
+                "msOracleSpatialLayerOpen()");
 
-    return layer->layerinfo != NULL ? MS_SUCCESS : MS_FAILURE;
+    if (layer->debug)
+      msDebug("msOracleSpatialLayerOpen. Cannot create OCI LayerInfo. Connection failure.\n");
+
+    msOCICloseDataHandlers ( dthand );
+    msOCICloseHandlers( hand );
+    msOCIClearLayerInfo( layerinfo );
+  }
+  layerinfo->orahandlers = hand;
+  layerinfo->oradatahandlers = dthand;
+  layerinfo->orastmt = sthand;
+  layerinfo->orastmt2 = sthand2;
+  layer->layerinfo = layerinfo;
+
+  if (username) free(username);
+  if (password) free(password);
+  if (dblink) free(dblink);
+
+  return layer->layerinfo != NULL ? MS_SUCCESS : MS_FAILURE;
 }
 
 /* return MS_TRUE if layer is open, MS_FALSE otherwise.*/
 int msOracleSpatialLayerIsOpen(layerObj *layer)
 {
-    if (layer->layerinfo != NULL)
-        return MS_TRUE;
+  if (layer->layerinfo != NULL)
+    return MS_TRUE;
 
-    return MS_FALSE;
+  return MS_FALSE;
 }
 
 /* closes the layer, disconnecting from db if connected. layer->layerinfo is freed */
 int msOracleSpatialLayerClose( layerObj *layer )
 {
-    msOracleSpatialLayerInfo *layerinfo = (msOracleSpatialLayerInfo *)layer->layerinfo;
-    /*int lIntSuccessFree = 0;*/
+  msOracleSpatialLayerInfo *layerinfo = (msOracleSpatialLayerInfo *)layer->layerinfo;
+  /*int lIntSuccessFree = 0;*/
 
+  if (layer->debug)
+    msDebug("msOracleSpatialLayerClose was called. Layer: %p, Layer name: %s. Layer connection: %s\n", layer, layer->name, layer->connection);
+
+  if (layerinfo != NULL) {
+
+    /*
+     * Some errors with the OCIObjectFree with query function
+     * If uncomment draw mode will work but no query modes
+     * Need to investigate the error cause
+     */
+    /*lIntSuccessFree = TRY (layerinfo->orahandlers, OCIObjectFree(layerinfo->orahandlers->envhp, layerinfo->orahandlers->errhp, (dvoid *)layerinfo->obj, (ub2)OCI_OBJECTFREE_FORCE));
+     *if (!lIntSuccessFree)
+     *  msDebug("Error: %s\n", layerinfo->orahandlers->last_oci_error);
+     */
+    /* Release Statement Handles */
+    if (layerinfo->orastmt != NULL) {
+      msOCIFinishStatement(layerinfo->orastmt);
+      layerinfo->orastmt = NULL;
+    }
+    if (layerinfo->orastmt2 != NULL) {
+      msOCIFinishStatement(layerinfo->orastmt2);
+      layerinfo->orastmt2 = NULL;
+    }
+
+    /* Release Datahandlers */
     if (layer->debug)
-        msDebug("msOracleSpatialLayerClose was called. Layer: %p, Layer name: %s. Layer connection: %s\n", layer, layer->name, layer->connection);
-    
-    if (layerinfo != NULL)
-    {
-
-        /*
-         * Some errors with the OCIObjectFree with query function
-         * If uncomment draw mode will work but no query modes
-         * Need to investigate the error cause
-         */
-        /*lIntSuccessFree = TRY (layerinfo->orahandlers, OCIObjectFree(layerinfo->orahandlers->envhp, layerinfo->orahandlers->errhp, (dvoid *)layerinfo->obj, (ub2)OCI_OBJECTFREE_FORCE));
-         *if (!lIntSuccessFree)
-         *  msDebug("Error: %s\n", layerinfo->orahandlers->last_oci_error);
-         */
-        /* Release Statement Handles */
-        if (layerinfo->orastmt != NULL) 
-        {
-            msOCIFinishStatement(layerinfo->orastmt);
-            layerinfo->orastmt = NULL;
-        } 
-        if (layerinfo->orastmt2 != NULL)
-        {
-            msOCIFinishStatement(layerinfo->orastmt2);
-            layerinfo->orastmt2 = NULL;
-        }
-        
-        /* Release Datahandlers */
-        if (layer->debug)
-          msDebug("msOracleSpatialLayerClose. Cleaning layerinfo handlers.\n");
-        msOCICloseDataHandlers( layerinfo->oradatahandlers );
-        layerinfo->oradatahandlers = NULL;
+      msDebug("msOracleSpatialLayerClose. Cleaning layerinfo handlers.\n");
+    msOCICloseDataHandlers( layerinfo->oradatahandlers );
+    layerinfo->oradatahandlers = NULL;
 
     /* Free the OCI cache only if there is no more layer that could use it */
     layerinfo->orahandlers->ref_count--;
     if (layerinfo->orahandlers->ref_count == 0)
       OCICacheFree (layerinfo->orahandlers->envhp, layerinfo->orahandlers->errhp, layerinfo->orahandlers->svchp);
 
-        /* Release Mapserver Pool */
-        if (layer->debug)
-          msDebug("msOracleSpatialLayerClose. Release the Oracle Pool.\n");
-        msConnPoolRelease( layer, layerinfo->orahandlers );
+    /* Release Mapserver Pool */
+    if (layer->debug)
+      msDebug("msOracleSpatialLayerClose. Release the Oracle Pool.\n");
+    msConnPoolRelease( layer, layerinfo->orahandlers );
 
-        /* Release Layerinfo */
-        layerinfo->orahandlers = NULL;
+    /* Release Layerinfo */
+    layerinfo->orahandlers = NULL;
 
-        msOCIClearLayerInfo( layerinfo );
-        layer->layerinfo = NULL;
-    }
+    msOCIClearLayerInfo( layerinfo );
+    layer->layerinfo = NULL;
+  }
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 /* create SQL statement for retrieving shapes */
 /* Sets up cursor for use in *NextShape and *GetShape */
 int msOracleSpatialLayerWhichShapes( layerObj *layer, rectObj rect, int isQuery)
 {
-    int success, i;
-    int function = 0;
-    int version = 0;
-    char query_str[6000];
-    char query_str2[256];
-    char *tmp_str=NULL, *tmp1_str=NULL;
-    char *table_name;
-    char *geom_column_name = NULL, *unique = NULL, *srid = NULL;
-    OCIDefine *adtp = NULL;
-    OCIDefine **items = NULL;
-    OCINumber oci_number;
-    OCIBind *bnd1p = NULL,  *bnd2p = NULL;
-    
-    int existunique = MS_FALSE;
-    int rownumisuniquekey = MS_FALSE;
-    int numitemsinselect = 0;
+  int success, i;
+  int function = 0;
+  int version = 0;
+  char query_str[6000];
+  char query_str2[256];
+  char *tmp_str=NULL, *tmp1_str=NULL;
+  char *table_name;
+  char *geom_column_name = NULL, *unique = NULL, *srid = NULL;
+  OCIDefine *adtp = NULL;
+  OCIDefine **items = NULL;
+  OCINumber oci_number;
+  OCIBind *bnd1p = NULL,  *bnd2p = NULL;
+
+  int existunique = MS_FALSE;
+  int rownumisuniquekey = MS_FALSE;
+  int numitemsinselect = 0;
+
+  /* get layerinfo */
+  msOracleSpatialLayerInfo *layerinfo = (msOracleSpatialLayerInfo *)layer->layerinfo;
+  msOracleSpatialDataHandler *dthand = NULL;
+  msOracleSpatialHandler *hand = NULL;
+  msOracleSpatialStatement *sthand = NULL;
 
-    /* get layerinfo */
-    msOracleSpatialLayerInfo *layerinfo = (msOracleSpatialLayerInfo *)layer->layerinfo;
-    msOracleSpatialDataHandler *dthand = NULL;
-    msOracleSpatialHandler *hand = NULL;
-    msOracleSpatialStatement *sthand = NULL;
+  if (layer->debug)
+    msDebug("msOracleSpatialLayerWhichShapes was called.\n");
+
+  if (layerinfo == NULL) {
+    msSetError( MS_ORACLESPATIALERR,
+                "msOracleSpatialLayerWhichShapes called on unopened layer",
+                "msOracleSpatialLayerWhichShapes()" );
+
+    return MS_FAILURE;
+  } else {
+    dthand = (msOracleSpatialDataHandler *)layerinfo->oradatahandlers;
+    hand = (msOracleSpatialHandler *)layerinfo->orahandlers;
+    sthand = (msOracleSpatialStatement *)layerinfo->orastmt2;
+  }
+
+  /*init uniqueindex field*/
+  sthand->uniqueidindex=0;
+
+  table_name = (char *) malloc(sizeof(char) * TABLE_NAME_SIZE);
+  /* parse geom_column_name and table_name */
+  if (!msSplitData( layer->data, &geom_column_name, &table_name, &unique, &srid, &function, &version)) {
+    msSetError( MS_ORACLESPATIALERR,
+                "Error parsing OracleSpatial DATA variable. Must be:"
+                "'geometry_column FROM table_name [USING UNIQUE <column> SRID srid# FUNCTION]' or "
+                "'geometry_column FROM (SELECT stmt) [USING UNIQUE <column> SRID srid# FUNCTION]'."
+                "If want to set the FUNCTION statement you can use: FILTER, RELATE, GEOMRELATE or NONE."
+                "Your data statement: %s",
+                "msOracleSpatialLayerWhichShapes()", layer->data );
 
-    if (layer->debug)
-        msDebug("msOracleSpatialLayerWhichShapes was called.\n");
+    if (geom_column_name) free(geom_column_name);
+    if (srid) free(srid);
+    if (unique) free(unique);
+    free(table_name);
+    return MS_FAILURE;
+  }
+
+  /*rownum will be the first in the select if no UNIQUE key is defined or
+    will be added at the end of the select*/
+  rownumisuniquekey = MS_TRUE;
+  /*Define the unique*/
+  if (unique[0] == '\0')
+    strcpy( unique, "rownum" );
+  else
+    rownumisuniquekey = MS_FALSE;
+
+  /* Check if the unique field is already in the items list */
+  existunique = MS_FALSE;
+  if (unique) {
+    for( i=0; i < layer->numitems; ++i ) {
+      if (strcasecmp(unique, layer->items[i])==0) {
+        sthand->uniqueidindex = i;
+        existunique = MS_TRUE;
+        break;
+      }
+    }
+  }
 
-    if (layerinfo == NULL)
-    {
-        msSetError( MS_ORACLESPATIALERR,
-                    "msOracleSpatialLayerWhichShapes called on unopened layer",
-                    "msOracleSpatialLayerWhichShapes()" );
+  /* If no SRID is provided, set it to -1 (NULL) for binding */
+  if (strcmp(srid,"NULL") == 0)
+    strcpy(srid,"-1");
 
-        return MS_FAILURE;
-    }
-    else
-    {
-        dthand = (msOracleSpatialDataHandler *)layerinfo->oradatahandlers;
-        hand = (msOracleSpatialHandler *)layerinfo->orahandlers;
-        sthand = (msOracleSpatialStatement *)layerinfo->orastmt2;
-    }
 
-    /*init uniqueindex field*/
-    sthand->uniqueidindex=0;
+  snprintf( query_str, sizeof(query_str), "SELECT ");
 
-    table_name = (char *) malloc(sizeof(char) * TABLE_NAME_SIZE);
-    /* parse geom_column_name and table_name */
-    if (!msSplitData( layer->data, &geom_column_name, &table_name, &unique, &srid, &function, &version)) 
-    {
-        msSetError( MS_ORACLESPATIALERR, 
-                    "Error parsing OracleSpatial DATA variable. Must be:"
-                    "'geometry_column FROM table_name [USING UNIQUE <column> SRID srid# FUNCTION]' or "
-                    "'geometry_column FROM (SELECT stmt) [USING UNIQUE <column> SRID srid# FUNCTION]'."
-                    "If want to set the FUNCTION statement you can use: FILTER, RELATE, GEOMRELATE or NONE."
-                    "Your data statement: %s", 
-                    "msOracleSpatialLayerWhichShapes()", layer->data );
 
-        if (geom_column_name) free(geom_column_name);
-        if (srid) free(srid);
-        if (unique) free(unique);
-        free(table_name);
-        return MS_FAILURE;
-    }
+  numitemsinselect = layer->numitems;
+  /* allocate enough space for items */
+  if (layer->numitems >= 0) {
+    /*we will always add a rownumber in the selection*/
+    numitemsinselect++;
 
-    /*rownum will be the first in the select if no UNIQUE key is defined or 
-      will be added at the end of the select*/
-    rownumisuniquekey = MS_TRUE;
-    /*Define the unique*/
-    if (unique[0] == '\0')
-        strcpy( unique, "rownum" );
+    /*if unique key in the data is specfied and is not part of the current item lists,
+      we should add it to the select*/
+    if(existunique == MS_FALSE && rownumisuniquekey == MS_FALSE)
+      numitemsinselect++;
+
+    /*the usinque index is there was no uniqueid given or the uniqueid given was not part of the items lists*/
+    if (existunique == MS_FALSE)
+      sthand->uniqueidindex = layer->numitems;
+
+    sthand->items = (item_text_array *)malloc( sizeof(item_text_array) * (numitemsinselect) );
+    if (sthand->items == NULL) {
+      msSetError( MS_ORACLESPATIALERR,"Cannot allocate layerinfo->items buffer","msOracleSpatialLayerWhichShapes()" );
+      if (geom_column_name) free(geom_column_name);
+      if (srid) free(srid);
+      if (unique) free(unique);
+      free(table_name);
+      return MS_FAILURE;
+    }
+
+    items = (OCIDefine **)malloc(sizeof(OCIDefine *)*(numitemsinselect));
+    if (items == NULL) {
+      msSetError( MS_ORACLESPATIALERR,"Cannot allocate items buffer","msOracleSpatialLayerWhichShapes()" );
+      if (geom_column_name) free(geom_column_name);
+      if (srid) free(srid);
+      if (unique) free(unique);
+      free(table_name);
+      return MS_FAILURE;
+    }
+    memset(items ,0,sizeof(OCIDefine *)*(numitemsinselect));
+  }
+
+  /* define SQL query */
+  for( i=0; i < layer->numitems; ++i ) {
+    snprintf( query_str + strlen(query_str), sizeof(query_str)-strlen(query_str), "%s, ", layer->items[i] );
+  }
+
+  /*we add the uniqueid if it was not part of the current item list*/
+  if(existunique == MS_FALSE && rownumisuniquekey == MS_FALSE)
+    snprintf( query_str + strlen(query_str), sizeof(query_str)-strlen(query_str), "%s,", unique);
+
+  /*we always want to add rownum is the selection to allow paging to work*/
+  snprintf( query_str + strlen(query_str), sizeof(query_str)-strlen(query_str), "%s, ", "rownum");
+
+
+  snprintf( query_str + strlen(query_str), sizeof(query_str)-strlen(query_str), "%s FROM %s", geom_column_name, table_name );
+
+  osFilteritem(layer, function, query_str, sizeof(query_str), 1);
+
+  if (layerinfo->paging && layer->maxfeatures > 0 && layer->startindex < 0) {
+    if (function == FUNCTION_NONE && layer->filter.string == NULL)
+      snprintf( query_str + strlen(query_str), sizeof(query_str)-strlen(query_str), "%s"," WHERE ");
+    else if (function == FUNCTION_NONE && layer->filter.string != NULL)
+      snprintf( query_str + strlen(query_str), sizeof(query_str)-strlen(query_str), "%s"," AND ");
+    snprintf( query_str + strlen(query_str), sizeof(query_str)-strlen(query_str), " ROWNUM<=%d ", layer->maxfeatures);
+    if (function != FUNCTION_NONE)
+      snprintf (query_str + strlen(query_str), sizeof(query_str)-strlen(query_str), " AND ");
+
+  }
+
+  if ((((atol(srid) >= 8192) && (atol(srid) <= 8330)) || (atol(srid) == 2) || (atol(srid) == 5242888) || (atol(srid) == 2000001)) && (version == VERSION_9i))
+    osGeodeticData(function, version, query_str, sizeof(query_str), geom_column_name, srid, rect);
+  else
+    osNoGeodeticData(function, version, query_str, sizeof(query_str), geom_column_name, srid, rect);
+
+
+  /*assuming startindex starts at 1*/
+  if (layerinfo->paging && layer->startindex > 0) {
+    tmp1_str = msStrdup("SELECT * from (SELECT atmp.*, ROWNUM rnum from (");
+    tmp_str = msStringConcatenate(tmp_str,  tmp1_str);
+    msFree(tmp1_str);
+    tmp_str = msStringConcatenate(tmp_str, query_str);
+    /*oder by rowid does not seem to work with function using the spatial filter, at least
+      on layers loaded using ogr in a 11g database*/
+    if (function == FUNCTION_NONE  || function == FUNCTION_RELATE || function == FUNCTION_GEOMRELATE)
+      tmp1_str = msStrdup( "order by rowid");
     else
-      rownumisuniquekey = MS_FALSE;
-
-    /* Check if the unique field is already in the items list */
-    existunique = MS_FALSE;
-    if (unique)
-    {
-        for( i=0; i < layer->numitems; ++i ) {
-            if (strcasecmp(unique, layer->items[i])==0) {
-                sthand->uniqueidindex = i;
-                existunique = MS_TRUE;
-                break;
-            }
-        }
-    }
+      tmp1_str = msStrdup("");
 
-    /* If no SRID is provided, set it to -1 (NULL) for binding */
-    if (strcmp(srid,"NULL") == 0)
-        strcpy(srid,"-1");
+    if (layer->maxfeatures > 0)
+      snprintf(query_str2, sizeof(query_str2),  " %s) atmp where ROWNUM<=%d) where rnum >=%d",   tmp1_str,
+               layer->maxfeatures+layer->startindex-1,  layer->startindex);
+    else
+      snprintf( query_str2, sizeof(query_str2),  " %s) atmp) where rnum >=%d",  tmp1_str, layer->startindex);
+    msFree(tmp1_str);
 
+    tmp_str = msStringConcatenate(tmp_str,  query_str2);
+    snprintf(query_str, sizeof(query_str), "%s", tmp_str);
+    msFree(tmp_str);
+  }
 
-    snprintf( query_str, sizeof(query_str), "SELECT ");
 
-    
-    numitemsinselect = layer->numitems;
-    /* allocate enough space for items */
-    if (layer->numitems >= 0)
-    {
-        /*we will always add a rownumber in the selection*/
-        numitemsinselect++;
-
-        /*if unique key in the data is specfied and is not part of the current item lists,
-          we should add it to the select*/
-        if(existunique == MS_FALSE && rownumisuniquekey == MS_FALSE)
-          numitemsinselect++;
-
-        /*the usinque index is there was no uniqueid given or the uniqueid given was not part of the items lists*/
-        if (existunique == MS_FALSE)
-          sthand->uniqueidindex = layer->numitems;
-
-        sthand->items = (item_text_array *)malloc( sizeof(item_text_array) * (numitemsinselect) );
-        if (sthand->items == NULL)
-        {
-            msSetError( MS_ORACLESPATIALERR,"Cannot allocate layerinfo->items buffer","msOracleSpatialLayerWhichShapes()" );
-            if (geom_column_name) free(geom_column_name);
-            if (srid) free(srid);
-            if (unique) free(unique);
-            free(table_name);
-            return MS_FAILURE;
-        }
+  if (layer->debug)
+    msDebug("msOracleSpatialLayerWhichShapes. Using this Sql to retrieve the data: %s\n", query_str);
 
-        items = (OCIDefine **)malloc(sizeof(OCIDefine *)*(numitemsinselect));
-        if (items == NULL)
-        {
-            msSetError( MS_ORACLESPATIALERR,"Cannot allocate items buffer","msOracleSpatialLayerWhichShapes()" );
-            if (geom_column_name) free(geom_column_name);
-            if (srid) free(srid);
-            if (unique) free(unique);
-            free(table_name);
-            return MS_FAILURE;
-        }
-        memset(items ,0,sizeof(OCIDefine *)*(numitemsinselect));
-    }
+  if (layer->debug)
+    msDebug("msOracleSpatialLayerWhichShapes. Bind values: srid:%s   minx:%f   miny:%f  maxx:%f   maxy:%f \n", srid, rect.minx, rect.miny, rect.maxx, rect.maxy);
 
-    /* define SQL query */
-    for( i=0; i < layer->numitems; ++i )
-    {
-        snprintf( query_str + strlen(query_str), sizeof(query_str)-strlen(query_str), "%s, ", layer->items[i] );
-    }
+  /* prepare */
+  success = TRY( hand, OCIStmtPrepare( sthand->stmthp, hand->errhp, (text *)query_str, (ub4)strlen(query_str), (ub4)OCI_NTV_SYNTAX, (ub4)OCI_DEFAULT) );
 
-    /*we add the uniqueid if it was not part of the current item list*/
-    if(existunique == MS_FALSE && rownumisuniquekey == MS_FALSE)
-        snprintf( query_str + strlen(query_str), sizeof(query_str)-strlen(query_str), "%s,", unique);
+  if (layer->debug)
+    msDebug("msOracleSpatialLayerWhichShapes getting ordinate definition.\n");
 
-    /*we always want to add rownum is the selection to allow paging to work*/
-    snprintf( query_str + strlen(query_str), sizeof(query_str)-strlen(query_str), "%s, ", "rownum");
+  /* get the object definition of the ordinate array */
+  ordinates_tdo = get_tdo(SDO_ORDINATE_ARRAY, hand, dthand );
 
+  if (layer->debug)
+    msDebug("msOracleSpatialLayerWhichShapes converting to OCIColl.\n");
 
-    snprintf( query_str + strlen(query_str), sizeof(query_str)-strlen(query_str), "%s FROM %s", geom_column_name, table_name );
+  /* initialized the collection array */
+  success = TRY( hand, OCIObjectNew(hand->envhp, hand->errhp, hand->svchp, OCI_TYPECODE_VARRAY, ordinates_tdo, (dvoid *)NULL, OCI_DURATION_SESSION, FALSE, (dvoid **)&ordinates) );
 
-    osFilteritem(layer, function, query_str, sizeof(query_str), 1);
+  /* convert it to a OCI number and then append minx...maxy to the collection */
+  success = TRY ( hand, OCINumberFromReal(hand->errhp, (dvoid *)&(rect.minx), (uword)sizeof(double),(dvoid *)&oci_number))
+            &&TRY ( hand, OCICollAppend(hand->envhp, hand->errhp,(dvoid *) &oci_number,(dvoid *)0, (OCIColl *)ordinates))
+            &&TRY ( hand, OCINumberFromReal(hand->errhp, (dvoid *)&(rect.miny), (uword)sizeof(double),(dvoid *)&oci_number))
+            &&TRY ( hand, OCICollAppend(hand->envhp, hand->errhp,(dvoid *) &oci_number,(dvoid *)0, (OCIColl *)ordinates))
+            &&TRY ( hand, OCINumberFromReal(hand->errhp, (dvoid *)&(rect.maxx), (uword)sizeof(double),(dvoid *)&oci_number))
+            &&TRY ( hand, OCICollAppend(hand->envhp, hand->errhp,(dvoid *) &oci_number,(dvoid *)0, (OCIColl *)ordinates))
+            &&TRY ( hand, OCINumberFromReal(hand->errhp, (dvoid *)&(rect.maxy), (uword)sizeof(double),(dvoid *)&oci_number))
+            &&TRY ( hand, OCICollAppend(hand->envhp, hand->errhp,(dvoid *) &oci_number,(dvoid *)0, (OCIColl *)ordinates));
 
-    if (layer->maxfeatures > 0 && layer->startindex < 0)
-    {
-       if (function == FUNCTION_NONE && layer->filter.string == NULL)
-           snprintf( query_str + strlen(query_str), sizeof(query_str)-strlen(query_str), "%s"," WHERE ");
-       else if (function == FUNCTION_NONE && layer->filter.string != NULL)
-           snprintf( query_str + strlen(query_str), sizeof(query_str)-strlen(query_str), "%s"," AND ");
-       snprintf( query_str + strlen(query_str), sizeof(query_str)-strlen(query_str), " ROWNUM<=%d ", layer->maxfeatures);
-       if (function != FUNCTION_NONE)
-           snprintf (query_str + strlen(query_str), sizeof(query_str)-strlen(query_str), " AND ");
-      
-    }
 
-    if ((((atol(srid) >= 8192) && (atol(srid) <= 8330)) || (atol(srid) == 2) || (atol(srid) == 5242888) || (atol(srid) == 2000001)) && (version == VERSION_9i))
-        osGeodeticData(function, version, query_str, sizeof(query_str), geom_column_name, srid, rect);
-    else
-        osNoGeodeticData(function, version, query_str, sizeof(query_str), geom_column_name, srid, rect);
-
-
-    /*assuming startindex starts at 1*/
-    if (layer->startindex > 0)
-     {
-       tmp1_str = msStrdup("SELECT * from (SELECT atmp.*, ROWNUM rnum from (");
-       tmp_str = msStringConcatenate(tmp_str,  tmp1_str);
-       msFree(tmp1_str);
-       tmp_str = msStringConcatenate(tmp_str, query_str);
-       /*oder by rowid does not seem to work with function using the spatial filter, at least
-         on layers loaded using ogr in a 11g database*/
-       if (function == FUNCTION_NONE  || function == FUNCTION_RELATE || function == FUNCTION_GEOMRELATE)
-         tmp1_str = msStrdup( "order by rowid");
-       else
-         tmp1_str = msStrdup("");
-
-       if (layer->maxfeatures > 0)
-           snprintf(query_str2, sizeof(query_str2),  " %s) atmp where ROWNUM<=%d) where rnum >=%d",   tmp1_str, 
-                  layer->maxfeatures+layer->startindex-1,  layer->startindex);
-       else
-         snprintf( query_str2, sizeof(query_str2),  " %s) atmp) where rnum >=%d",  tmp1_str, layer->startindex);
-       msFree(tmp1_str);
-       
-       tmp_str = msStringConcatenate(tmp_str,  query_str2);
-       snprintf(query_str, sizeof(query_str), "%s", tmp_str);
-       msFree(tmp_str);
-     } 
-    
-    
-    if (layer->debug)
-        msDebug("msOracleSpatialLayerWhichShapes. Using this Sql to retrieve the data: %s\n", query_str);
-        
-     if (layer->debug)
-        msDebug("msOracleSpatialLayerWhichShapes. Bind values: srid:%s   minx:%f   miny:%f  maxx:%f   maxy:%f \n", srid, rect.minx, rect.miny, rect.maxx, rect.maxy);
-        
-    /* prepare */
-    success = TRY( hand, OCIStmtPrepare( sthand->stmthp, hand->errhp, (text *)query_str, (ub4)strlen(query_str), (ub4)OCI_NTV_SYNTAX, (ub4)OCI_DEFAULT) );
-    
-     if (layer->debug)
-        msDebug("msOracleSpatialLayerWhichShapes getting ordinate definition.\n");
+  if (layer->debug)
+    msDebug("msOracleSpatialLayerWhichShapes bind by name and object.\n");
 
-    /* get the object definition of the ordinate array */
-    ordinates_tdo = get_tdo(SDO_ORDINATE_ARRAY, hand, dthand );
-    
-     if (layer->debug)
-        msDebug("msOracleSpatialLayerWhichShapes converting to OCIColl.\n");
-        
-    /* initialized the collection array */      
-    success = TRY( hand, OCIObjectNew(hand->envhp, hand->errhp, hand->svchp, OCI_TYPECODE_VARRAY, ordinates_tdo, (dvoid *)NULL, OCI_DURATION_SESSION, FALSE, (dvoid **)&ordinates) );
-    
-    /* convert it to a OCI number and then append minx...maxy to the collection */    
-      success = TRY ( hand, OCINumberFromReal(hand->errhp, (dvoid *)&(rect.minx), (uword)sizeof(double),(dvoid *)&oci_number))
-              &&TRY ( hand, OCICollAppend(hand->envhp, hand->errhp,(dvoid *) &oci_number,(dvoid *)0, (OCIColl *)ordinates))              
-              &&TRY ( hand, OCINumberFromReal(hand->errhp, (dvoid *)&(rect.miny), (uword)sizeof(double),(dvoid *)&oci_number))
-              &&TRY ( hand, OCICollAppend(hand->envhp, hand->errhp,(dvoid *) &oci_number,(dvoid *)0, (OCIColl *)ordinates))
-              &&TRY ( hand, OCINumberFromReal(hand->errhp, (dvoid *)&(rect.maxx), (uword)sizeof(double),(dvoid *)&oci_number))
-              &&TRY ( hand, OCICollAppend(hand->envhp, hand->errhp,(dvoid *) &oci_number,(dvoid *)0, (OCIColl *)ordinates))
-              &&TRY ( hand, OCINumberFromReal(hand->errhp, (dvoid *)&(rect.maxy), (uword)sizeof(double),(dvoid *)&oci_number))
-              &&TRY ( hand, OCICollAppend(hand->envhp, hand->errhp,(dvoid *) &oci_number,(dvoid *)0, (OCIColl *)ordinates));
-
-
- if (layer->debug)
-        msDebug("msOracleSpatialLayerWhichShapes bind by name and object.\n");
-        
-  /* do the actual binding */      
-
- if (success && function != FUNCTION_NONE) {
-   const char* bind_key;
-   char* bind_value;
-   char* bind_tag;
-     success = TRY( hand,
-            /* bind in srid */
-            OCIBindByName( sthand->stmthp, &bnd2p,  hand->errhp, (text *) ":srid", strlen(":srid"),(ub1 *) srid,  strlen(srid)+1, SQLT_STR, 
-              (dvoid *) 0, (ub2 *) 0, (ub2) 0, (ub4) 0, (ub4 *) 0, OCI_DEFAULT) )
+  /* do the actual binding */
+
+  if (success && function != FUNCTION_NONE) {
+    const char* bind_key;
+    char* bind_value;
+    char* bind_tag;
+    success = TRY( hand,
+                   /* bind in srid */
+                   OCIBindByName( sthand->stmthp, &bnd2p,  hand->errhp, (text *) ":srid", strlen(":srid"),(ub1 *) srid,  strlen(srid)+1, SQLT_STR,
+                                  (dvoid *) 0, (ub2 *) 0, (ub2) 0, (ub4) 0, (ub4 *) 0, OCI_DEFAULT) )
               && TRY(hand,
-            /* bind in rect by name */
-            OCIBindByName( sthand->stmthp, &bnd1p,  hand->errhp,  (text *)":ordinates", -1, (dvoid *)0, (sb4)0, SQLT_NTY, (dvoid *)0, (ub2 *)0,(ub2 *)0, (ub4)0, (ub4 *)0, (ub4)OCI_DEFAULT))
+                     /* bind in rect by name */
+                     OCIBindByName( sthand->stmthp, &bnd1p,  hand->errhp,  (text *)":ordinates", -1, (dvoid *)0, (sb4)0, SQLT_NTY, (dvoid *)0, (ub2 *)0,(ub2 *)0, (ub4)0, (ub4 *)0, (ub4)OCI_DEFAULT))
               && TRY(hand,
-            /* bind in rect object */
-            OCIBindObject(bnd1p, hand->errhp, ordinates_tdo, (dvoid **)&ordinates, (ub4 *)0, (dvoid **)0, (ub4 *)0));
-
-	/* bind the variables from the bindvals hash */
-	bind_key = (char*)msFirstKeyFromHashTable(&layer->bindvals);
-	while(bind_key != NULL) {
-		bind_value = msLookupHashTable(&layer->bindvals, bind_key);
-		bind_tag = (char*)malloc(sizeof(char) * strlen(bind_key) + 2);
-		sprintf(bind_tag, ":%s", bind_key);
-
-		success = success && TRY(hand, OCIBindByName( sthand->stmthp, &bnd2p,  hand->errhp, (text *)bind_tag, strlen(bind_tag),(ub1 *) bind_value,  strlen(bind_value)+1, SQLT_STR,
-	              (dvoid *) 0, (ub2 *) 0, (ub2) 0, (ub4) 0, (ub4 *) 0, OCI_DEFAULT));
-		bind_key = msNextKeyFromHashTable(&layer->bindvals, bind_key);
-	}
-   }       
-
-          
-  if (layer->debug)
-        msDebug("msOracleSpatialLayerWhichShapes name and object now bound.\n");
-        
+                     /* bind in rect object */
+                     OCIBindObject(bnd1p, hand->errhp, ordinates_tdo, (dvoid **)&ordinates, (ub4 *)0, (dvoid **)0, (ub4 *)0));
 
-    if (success && layer->numitems >= 0)
-    {
-        for( i=0; i < numitemsinselect && success; ++i )
-            success = TRY( hand, OCIDefineByPos( sthand->stmthp, &items[i], hand->errhp, (ub4)i+1, (dvoid *)sthand->items[i], (sb4)TEXT_SIZE, SQLT_STR, (dvoid *)0, (ub2 *)0, (ub2 *)0, (ub4)OCI_DEFAULT ) );
-    }
-    
-    
-    if (success)
-    {
-        int cursor_type = OCI_DEFAULT;
-        if(isQuery) cursor_type =OCI_STMT_SCROLLABLE_READONLY;
-
-        success = TRY( hand,
-            /* define spatial position adtp ADT object */
-            OCIDefineByPos( sthand->stmthp, &adtp, hand->errhp, (ub4)numitemsinselect+1, (dvoid *)0, (sb4)0, SQLT_NTY, (dvoid *)0, (ub2 *)0, (ub2 *)0, (ub4)OCI_DEFAULT) )
-               && TRY( hand,
-            /* define object tdo from adtp */
-            OCIDefineObject( adtp, hand->errhp, dthand->tdo, (dvoid **)sthand->obj, (ub4 *)0, (dvoid **)sthand->ind, (ub4 *)0 ) )
-               && TRY(hand,
-            /* execute */
-            OCIStmtExecute( hand->svchp, sthand->stmthp, hand->errhp, (ub4)ARRAY_SIZE, (ub4)0, (OCISnapshot *)NULL, (OCISnapshot *)NULL, (ub4)cursor_type ) )
-               &&  TRY( hand,
-            /* get rows fetched */
-            OCIAttrGet( (dvoid *)sthand->stmthp, (ub4)OCI_HTYPE_STMT, (dvoid *)&sthand->rows_fetched, (ub4 *)0, (ub4)OCI_ATTR_ROW_COUNT, hand->errhp ) )
-            && TRY( hand,
-            /* get rows count */
-            OCIAttrGet( (dvoid *)sthand->stmthp, (ub4)OCI_HTYPE_STMT, (dvoid *)&sthand->rows_count, (ub4 *)0, (ub4)OCI_ATTR_ROW_COUNT, hand->errhp ) );
+    /* bind the variables from the bindvals hash */
+    bind_key = (char*)msFirstKeyFromHashTable(&layer->bindvals);
+    while(bind_key != NULL) {
+      bind_value = msLookupHashTable(&layer->bindvals, bind_key);
+      bind_tag = (char*)malloc(sizeof(char) * strlen(bind_key) + 2);
+      sprintf(bind_tag, ":%s", bind_key);
+
+      success = success && TRY(hand, OCIBindByName( sthand->stmthp, &bnd2p,  hand->errhp, (text *)bind_tag, strlen(bind_tag),(ub1 *) bind_value,  strlen(bind_value)+1, SQLT_STR,
+                               (dvoid *) 0, (ub2 *) 0, (ub2) 0, (ub4) 0, (ub4 *) 0, OCI_DEFAULT));
+      bind_key = msNextKeyFromHashTable(&layer->bindvals, bind_key);
     }
+  }
 
-    if (!success)
-    {
-        msSetError( MS_ORACLESPATIALERR, 
-                    "Error: %s . "
-                    "Query statement: %s . "
-                    "Check your data statement.", 
-                    "msOracleSpatialLayerWhichShapes()", hand->last_oci_error, query_str );
 
-        /* clean items */
-        free(items);
-        if (geom_column_name) free(geom_column_name);
-        if (srid) free(srid);
-        if (unique) free(unique);
-        free(table_name);
+  if (layer->debug)
+    msDebug("msOracleSpatialLayerWhichShapes name and object now bound.\n");
+
+
+  if (success && layer->numitems >= 0) {
+    for( i=0; i < numitemsinselect && success; ++i )
+      success = TRY( hand, OCIDefineByPos( sthand->stmthp, &items[i], hand->errhp, (ub4)i+1, (dvoid *)sthand->items[i], (sb4)TEXT_SIZE, SQLT_STR, (dvoid *)0, (ub2 *)0, (ub2 *)0, (ub4)OCI_DEFAULT ) );
+  }
 
-        return MS_FAILURE;
-    }
 
-    /* should begin processing first row */
-    sthand->row_num = sthand->row = 0;
+  if (success) {
+    int cursor_type = OCI_DEFAULT;
+    if(isQuery) cursor_type =OCI_STMT_SCROLLABLE_READONLY;
+
+    success = TRY( hand,
+                   /* define spatial position adtp ADT object */
+                   OCIDefineByPos( sthand->stmthp, &adtp, hand->errhp, (ub4)numitemsinselect+1, (dvoid *)0, (sb4)0, SQLT_NTY, (dvoid *)0, (ub2 *)0, (ub2 *)0, (ub4)OCI_DEFAULT) )
+              && TRY( hand,
+                      /* define object tdo from adtp */
+                      OCIDefineObject( adtp, hand->errhp, dthand->tdo, (dvoid **)sthand->obj, (ub4 *)0, (dvoid **)sthand->ind, (ub4 *)0 ) )
+              && TRY(hand,
+                     /* execute */
+                     OCIStmtExecute( hand->svchp, sthand->stmthp, hand->errhp, (ub4)ARRAY_SIZE, (ub4)0, (OCISnapshot *)NULL, (OCISnapshot *)NULL, (ub4)cursor_type ) )
+              &&  TRY( hand,
+                       /* get rows fetched */
+                       OCIAttrGet( (dvoid *)sthand->stmthp, (ub4)OCI_HTYPE_STMT, (dvoid *)&sthand->rows_fetched, (ub4 *)0, (ub4)OCI_ATTR_ROWS_FETCHED, hand->errhp ) )
+              && TRY( hand,
+                      /* get rows count */
+                      OCIAttrGet( (dvoid *)sthand->stmthp, (ub4)OCI_HTYPE_STMT, (dvoid *)&sthand->rows_count, (ub4 *)0, (ub4)OCI_ATTR_ROW_COUNT, hand->errhp ) );
+  }
+
+  if (!success) {
+    msSetError( MS_ORACLESPATIALERR,
+                "Error: %s . "
+                "Query statement: %s . "
+                "Check your data statement.",
+                "msOracleSpatialLayerWhichShapes()", hand->last_oci_error, query_str );
 
     /* clean items */
     free(items);
@@ -2247,527 +2099,447 @@ int msOracleSpatialLayerWhichShapes( layerObj *layer, rectObj rect, int isQuery)
     if (unique) free(unique);
     free(table_name);
 
-    return MS_SUCCESS;
+    return MS_FAILURE;
+  }
+
+  /* should begin processing first row */
+  sthand->row_num = sthand->row = 0;
+
+  /* clean items */
+  free(items);
+  if (geom_column_name) free(geom_column_name);
+  if (srid) free(srid);
+  if (unique) free(unique);
+  free(table_name);
+
+  return MS_SUCCESS;
 }
 
 /* fetch next shape from previous SELECT stmt (see *WhichShape()) */
 int msOracleSpatialLayerNextShape( layerObj *layer, shapeObj *shape )
 {
-    SDOGeometryObj *obj;
-    SDOGeometryInd *ind;
-    int success, /*lIntSuccessFree,*/ i;
+  SDOGeometryObj *obj;
+  SDOGeometryInd *ind;
+  int success, /*lIntSuccessFree,*/ i;
+
+  /* get layerinfo */
+  msOracleSpatialLayerInfo *layerinfo = (msOracleSpatialLayerInfo *)layer->layerinfo;
+  msOracleSpatialDataHandler *dthand = NULL;
+  msOracleSpatialHandler *hand = NULL;
+  msOracleSpatialStatement *sthand = NULL;
+
+
+  if (layerinfo == NULL) {
+    msSetError( MS_ORACLESPATIALERR, "msOracleSpatialLayerWhichShapes called on unopened layer", "msOracleSpatialLayerNextShape()" );
+    return MS_FAILURE;
+  } else {
+    dthand = (msOracleSpatialDataHandler *)layerinfo->oradatahandlers;
+    hand = (msOracleSpatialHandler *)layerinfo->orahandlers;
+    sthand = (msOracleSpatialStatement *)layerinfo->orastmt2;
+  }
+
+  /* no rows fetched */
+  if (sthand->rows_fetched == 0)
+    return MS_DONE;
+
+  if(layer->debug >=5 )
+    msDebug("msOracleSpatialLayerNextShape on layer %p, row_num: %d\n", layer, sthand->row_num);
+
+  do {
+    /* is buffer empty? */
+    if (sthand->row >= sthand->rows_fetched) {
+      /* fetch more */
+      success = TRY( hand, OCIStmtFetch2( sthand->stmthp, hand->errhp, (ub4)ARRAY_SIZE, (ub2)OCI_FETCH_NEXT, (sb4)0, (ub4)OCI_DEFAULT ) )
+                && TRY( hand, OCIAttrGet( (dvoid *)sthand->stmthp, (ub4)OCI_HTYPE_STMT, (dvoid *)&sthand->rows_fetched, (ub4 *)0, (ub4)OCI_ATTR_ROWS_FETCHED, hand->errhp ) )
+                && TRY( hand, OCIAttrGet( (dvoid *)sthand->stmthp, (ub4)OCI_HTYPE_STMT, (dvoid *)&sthand->rows_count, (ub4 *)0, (ub4)OCI_ATTR_ROW_COUNT, hand->errhp ) );
+
+      if(layer->debug >= 4 )
+        msDebug("msOracleSpatialLayerNextShape on layer %p, Fetched %d more rows (%d total)\n", layer, sthand->rows_fetched, sthand->rows_count);
+
+      if (sthand->row_num >= sthand->rows_count)
+        return MS_DONE;
 
-    /* get layerinfo */
-    msOracleSpatialLayerInfo *layerinfo = (msOracleSpatialLayerInfo *)layer->layerinfo;
-    msOracleSpatialDataHandler *dthand = NULL;
-    msOracleSpatialHandler *hand = NULL;
-    msOracleSpatialStatement *sthand = NULL;
+      if (!success || sthand->rows_fetched == 0)
+        return MS_DONE;
+
+      sthand->row = 0; /* reset buffer row index */
+    }
+
+    /* set obj & ind for current row */
+    obj = sthand->obj[ sthand->row ];
+    ind = sthand->ind[ sthand->row ];
 
+    /* get the items for the shape */
+    shape->index = atol( (char *)(sthand->items[sthand->uniqueidindex][ sthand->row ])); /* Primary Key */
+    shape->resultindex = sthand->row_num;
+    shape->numvalues = layer->numitems;
 
-    if (layerinfo == NULL) 
-    {
-        msSetError( MS_ORACLESPATIALERR, "msOracleSpatialLayerWhichShapes called on unopened layer", "msOracleSpatialLayerNextShape()" );
+    shape->values = (char **)malloc( sizeof(char*) * shape->numvalues );
+    if (shape->values == NULL) {
+      msSetError( MS_ORACLESPATIALERR, "No memory avaliable to allocate the values", "msOracleSpatialLayerNextShape()" );
+      return MS_FAILURE;
+    }
+
+    for( i=0; i < shape->numvalues; ++i ) {
+      shape->values[i] = (char *)malloc(strlen((char *)sthand->items[i][ sthand->row ])+1);
+      if (shape->values[i] == NULL) {
+        msSetError( MS_ORACLESPATIALERR, "No memory avaliable to allocate the items", "msOracleSpatialLayerNextShape()" );
         return MS_FAILURE;
+      } else {
+        strcpy(shape->values[i], (char *)sthand->items[i][ sthand->row ]);
+        shape->values[i][strlen((char *)sthand->items[i][ sthand->row ])] = '\0';
+      }
     }
-    else
-    {
-        dthand = (msOracleSpatialDataHandler *)layerinfo->oradatahandlers;
-        hand = (msOracleSpatialHandler *)layerinfo->orahandlers;
-        sthand = (msOracleSpatialStatement *)layerinfo->orastmt2;
+
+    /* fetch a layer->type object */
+    success = osGetOrdinates(dthand, hand, shape, obj, ind);
+
+    /* increment for next row */
+    sthand->row_num++;
+    sthand->row++;
+
+    if (success != MS_SUCCESS) {
+      return MS_FAILURE;
     }
 
-    /* no rows fetched */
-    if (sthand->rows_fetched == 0)
-        return MS_DONE;
+    osShapeBounds(shape);
+  } while(shape->type == MS_SHAPE_NULL);
 
-    if(layer->debug >=5 )
-        msDebug("msOracleSpatialLayerNextShape on layer %p, row_num: %d\n", layer, sthand->row_num);
-    
-    do{
-        /* is buffer empty? */
-        if (sthand->row >= sthand->rows_fetched)
-        {
-            /* fetch more */
-            success = TRY( hand, OCIStmtFetch2( sthand->stmthp, hand->errhp, (ub4)ARRAY_SIZE, (ub2)OCI_FETCH_NEXT, (sb4)0, (ub4)OCI_DEFAULT ) ) 
-                   && TRY( hand, OCIAttrGet( (dvoid *)sthand->stmthp, (ub4)OCI_HTYPE_STMT, (dvoid *)&sthand->rows_fetched, (ub4 *)0, (ub4)OCI_ATTR_ROWS_FETCHED, hand->errhp ) )
-                   && TRY( hand, OCIAttrGet( (dvoid *)sthand->stmthp, (ub4)OCI_HTYPE_STMT, (dvoid *)&sthand->rows_count, (ub4 *)0, (ub4)OCI_ATTR_ROW_COUNT, hand->errhp ) );
-
-            if(layer->debug >= 4 )
-                msDebug("msOracleSpatialLayerNextShape on layer %p, Fetched %d more rows (%d total)\n", layer, sthand->rows_fetched, sthand->rows_count);
-            
-            
-            if (!success || sthand->rows_fetched == 0)
-                return MS_DONE;
-
-            if (sthand->row_num >= sthand->rows_count)
-                return MS_DONE;
-
-            sthand->row = 0; /* reset buffer row index */
-        }
+  return MS_SUCCESS;
+}
 
-        /* set obj & ind for current row */
-        obj = sthand->obj[ sthand->row ];
-        ind = sthand->ind[ sthand->row ];
+int msOracleSpatialLayerGetShape( layerObj *layer, shapeObj *shape, resultObj *record)
+{
+  int success, i;
+  SDOGeometryObj *obj;
+  SDOGeometryInd *ind;
+  msOracleSpatialDataHandler *dthand = NULL;
+  msOracleSpatialHandler *hand = NULL;
+  msOracleSpatialLayerInfo *layerinfo;
+  msOracleSpatialStatement *sthand = NULL;
 
-        /* get the items for the shape */
-        shape->index = atol( (char *)(sthand->items[sthand->uniqueidindex][ sthand->row ])); /* Primary Key */
-        shape->resultindex = sthand->row_num;
-        shape->numvalues = layer->numitems;
+  long shapeindex = record->shapeindex;
+  int resultindex = record->resultindex;
 
-        shape->values = (char **)malloc( sizeof(char*) * shape->numvalues );
-        if (shape->values == NULL)
-        {
-            msSetError( MS_ORACLESPATIALERR, "No memory avaliable to allocate the values", "msOracleSpatialLayerNextShape()" );
-            return MS_FAILURE;
-        }
+  if(layer == NULL) {
+    msSetError( MS_ORACLESPATIALERR, "msOracleSpatialLayerGetShape called on unopened layer","msOracleSpatialLayerGetShape()" );
+    return MS_FAILURE;
+  }
 
-        for( i=0; i < shape->numvalues; ++i )
-        {
-            shape->values[i] = (char *)malloc(strlen((char *)sthand->items[i][ sthand->row ])+1);
-            if (shape->values[i] == NULL)
-            {
-                msSetError( MS_ORACLESPATIALERR, "No memory avaliable to allocate the items", "msOracleSpatialLayerNextShape()" );
-                return MS_FAILURE;
-            }
-            else
-            {
-                strcpy(shape->values[i], (char *)sthand->items[i][ sthand->row ]);
-                shape->values[i][strlen((char *)sthand->items[i][ sthand->row ])] = '\0';
-            }
-        }
+  layerinfo = (msOracleSpatialLayerInfo *)layer->layerinfo;
 
-        /* fetch a layer->type object */
-        success = osGetOrdinates(dthand, hand, shape, obj, ind);
+  if (layerinfo == NULL) {
+    msSetError( MS_ORACLESPATIALERR, "msOracleSpatialLayerGetShape called on unopened layer (layerinfo)","msOracleSpatialLayerGetShape()" );
+    return MS_FAILURE;
+  }
 
-        /* increment for next row */
-        sthand->row_num++;
-        sthand->row++;
+  /* If resultindex is set, fetch the shape from the resultcache, otherwise fetch it from the DB  */
+  if (resultindex >= 0) {
+    long buffer_first_row_num, buffer_last_row_num;
 
-        if (success != MS_SUCCESS)
-        {
-            return MS_FAILURE;
-        }
+    /* get layerinfo */
+    dthand = (msOracleSpatialDataHandler *)layerinfo->oradatahandlers;
+    hand = (msOracleSpatialHandler *)layerinfo->orahandlers;
+    sthand = (msOracleSpatialStatement *)layerinfo->orastmt2;
 
-        osShapeBounds(shape);
-    }while(shape->type == MS_SHAPE_NULL);
+    if (layer->resultcache == NULL) {
+      msSetError( MS_ORACLESPATIALERR, "msOracleSpatialLayerGetShape called before msOracleSpatialLayerWhichShapes()","msOracleSpatialLayerGetShape()" );
+      return MS_FAILURE;
+    }
 
-    return MS_SUCCESS;
-}
+    if (resultindex >= sthand->rows_count) {
+      if (layer->debug >= 5)
+        msDebug("msOracleSpatialLayerGetShape problem with cursor. Trying to fetch record = %ld of %ld, falling back to GetShape\n", resultindex, sthand->rows_count);
 
-int msOracleSpatialLayerGetShape( layerObj *layer, shapeObj *shape, resultObj *record)
-{
-    int success, i;
-    SDOGeometryObj *obj;
-    SDOGeometryInd *ind;
-    msOracleSpatialDataHandler *dthand = NULL;
-    msOracleSpatialHandler *hand = NULL;
-    msOracleSpatialLayerInfo *layerinfo;
-    msOracleSpatialStatement *sthand = NULL;
-    
-    long shapeindex = record->shapeindex;
-    int resultindex = record->resultindex; 
+      msSetError( MS_ORACLESPATIALERR, "msOracleSpatialLayerGetShape record out of range","msOracleSpatialLayerGetShape()" );
+      return MS_FAILURE;
+    }
+
+    if (layer->debug >= 5)
+      msDebug("msOracleSpatialLayerGetShape was called. Using the record = %ld of %ld. (shape: %ld should equal pkey: %ld)\n",
+              resultindex, layer->resultcache->numresults, layer->resultcache->results[resultindex].shapeindex, shapeindex);
+
+    /* NOTE: with the way the resultcache works, we should see items in increasing order, but some may have been filtered out. */
+    /* Best case: item in buffer */
+    /* Next best case: item is in next fetch block */
+    /* Worst case: item is random access */
+    buffer_first_row_num = sthand->row_num - sthand->row; /* cursor id of first item in buffer */
+    buffer_last_row_num  = buffer_first_row_num + sthand->rows_fetched - 1; /* cursor id of last item in buffer */
+    if(resultindex >= buffer_first_row_num && resultindex <= buffer_last_row_num) { /* Item is in buffer. Calculate position in buffer */
+      sthand->row += resultindex - sthand->row_num; /* move sthand row an row_num by offset from last call */
+      sthand->row_num += resultindex - sthand->row_num;
+    } else { /* Item is not in buffer. Fetch item from Oracle */
+      if (layer->debug >= 4)
+        msDebug("msOracleSpatialLayerGetShape: Fetching result from DB start: %ld end:%ld record: %ld\n", buffer_first_row_num, buffer_last_row_num, resultindex);
+
+      success = TRY( hand, OCIStmtFetch2( sthand->stmthp, hand->errhp, (ub4)ARRAY_SIZE, (ub2)OCI_FETCH_ABSOLUTE, (sb4)resultindex+1, (ub4)OCI_DEFAULT ) )
+                && TRY( hand, OCIAttrGet( (dvoid *)sthand->stmthp, (ub4)OCI_HTYPE_STMT, (dvoid *)&sthand->rows_fetched, (ub4 *)0, (ub4)OCI_ATTR_ROWS_FETCHED, hand->errhp ) );
+      
+      sthand->row_num = resultindex;
+      sthand->row = 0; /* reset row index */
+
+      if(ERROR("msOracleSpatialLayerGetShape", hand, dthand))
+          return MS_FAILURE;
 
-    if(layer == NULL) {
-        msSetError( MS_ORACLESPATIALERR, "msOracleSpatialLayerGetShape called on unopened layer","msOracleSpatialLayerGetShape()" );
+      if (!success || sthand->rows_fetched == 0) {
+        msSetError( MS_ORACLESPATIALERR, "msOracleSpatialLayerGetShape could not fetch specified record.", "msOracleSpatialLayerGetShape()" );
         return MS_FAILURE;
+      }
     }
-    
-    layerinfo = (msOracleSpatialLayerInfo *)layer->layerinfo;
-    
-    if (layerinfo == NULL)
-    {
-        msSetError( MS_ORACLESPATIALERR, "msOracleSpatialLayerGetShape called on unopened layer (layerinfo)","msOracleSpatialLayerGetShape()" );
+
+    /* set obj & ind for current row */
+    obj = sthand->obj[ sthand->row ];
+    ind = sthand->ind[ sthand->row ];
+
+    /* get the items for the shape */
+    shape->index = shapeindex; /* By definition this is what we asked for */
+    shape->numvalues = layer->numitems;
+
+    shape->values = (char **)malloc( sizeof(char*) * shape->numvalues );
+    if (shape->values == NULL) {
+      msSetError( MS_ORACLESPATIALERR, "No memory avaliable to allocate the values", "msOracleSpatialLayerNextShape()" );
+      return MS_FAILURE;
+    }
+
+    for( i=0; i < shape->numvalues; ++i ) {
+      shape->values[i] = (char *)malloc(strlen((char *)sthand->items[i][ sthand->row ])+1);
+      if (shape->values[i] == NULL) {
+        msSetError( MS_ORACLESPATIALERR, "No memory avaliable to allocate the items", "msOracleSpatialLayerNextShape()" );
         return MS_FAILURE;
+      } else {
+        strcpy(shape->values[i], (char *)sthand->items[i][ sthand->row ]);
+        shape->values[i][strlen((char *)sthand->items[i][ sthand->row ])] = '\0';
+      }
     }
-    
-    /* If resultindex is set, fetch the shape from the resultcache, otherwise fetch it from the DB  */
-    if (resultindex >= 0)
-    {
-        long buffer_first_row_num, buffer_last_row_num;
-        
-        /* get layerinfo */
-        dthand = (msOracleSpatialDataHandler *)layerinfo->oradatahandlers;
-        hand = (msOracleSpatialHandler *)layerinfo->orahandlers;
-        sthand = (msOracleSpatialStatement *)layerinfo->orastmt2;
-    
-        if (layer->resultcache == NULL)
-        {
-            msSetError( MS_ORACLESPATIALERR, "msOracleSpatialLayerGetShape called before msOracleSpatialLayerWhichShapes()","msOracleSpatialLayerGetShape()" );
-            return MS_FAILURE;
-        }
-        
-        if (resultindex >= sthand->rows_count)
-        {
-            if (layer->debug >= 5)
-                msDebug("msOracleSpatialLayerGetShape problem with cursor. Trying to fetch record = %ld of %ld, falling back to GetShape\n", resultindex, sthand->rows_count);
-        
-            msSetError( MS_ORACLESPATIALERR, "msOracleSpatialLayerGetShape record out of range","msOracleSpatialLayerGetShape()" );
-            return MS_FAILURE;
-        }
-    
-        if (layer->debug >= 5)
-            msDebug("msOracleSpatialLayerGetShape was called. Using the record = %ld of %ld. (shape: %ld should equal pkey: %ld)\n", 
-                    resultindex, layer->resultcache->numresults, layer->resultcache->results[resultindex].shapeindex, shapeindex);
-
-        /* NOTE: with the way the resultcache works, we should see items in increasing order, but some may have been filtered out. */
-        /* Best case: item in buffer */
-        /* Next best case: item is in next fetch block */
-        /* Worst case: item is random access */
-        buffer_first_row_num = sthand->row_num - sthand->row; /* cursor id of first item in buffer */
-        buffer_last_row_num  = buffer_first_row_num + sthand->rows_fetched - 1; /* cursor id of last item in buffer */
-        if(resultindex >= buffer_first_row_num && resultindex <= buffer_last_row_num) /* Item is in buffer. Calculate position in buffer */
-        {
-            sthand->row += resultindex - sthand->row_num; /* move sthand row an row_num by offset from last call */
-            sthand->row_num += resultindex - sthand->row_num;
-        } 
-        else /* Item is not in buffer. Fetch item from Oracle */
-        {
-            if (layer->debug >= 4)
-                msDebug("msOracleSpatialLayerGetShape: Fetching result from DB start: %ld end:%ld record: %ld\n", buffer_first_row_num, buffer_last_row_num, resultindex);
-        
-            success = TRY( hand, OCIStmtFetch2( sthand->stmthp, hand->errhp, (ub4)ARRAY_SIZE, (ub2)OCI_FETCH_ABSOLUTE, (sb4)resultindex+1, (ub4)OCI_DEFAULT ) ) 
-                && TRY( hand, OCIAttrGet( (dvoid *)sthand->stmthp, (ub4)OCI_HTYPE_STMT, (dvoid *)&sthand->rows_fetched, (ub4 *)0, (ub4)OCI_ATTR_ROWS_FETCHED, hand->errhp ) );
 
-            ERROR("msOracleSpatialLayerGetShape", hand, dthand);
+    /* fetch a layer->type object */
+    success = osGetOrdinates(dthand, hand, shape, obj, ind);
 
-            sthand->row_num = resultindex;
-            sthand->row = 0; /* reset row index */
-        
-            if (!success || sthand->rows_fetched == 0) {
-                msSetError( MS_ORACLESPATIALERR, "msOracleSpatialLayerGetShape could not fetch specified record.", "msOracleSpatialLayerGetShape()" );
-                return MS_FAILURE;
-            }
-        }
-    
-        /* set obj & ind for current row */
-        obj = sthand->obj[ sthand->row ];
-        ind = sthand->ind[ sthand->row ];
-    
-        /* get the items for the shape */
-        shape->index = shapeindex; /* By definition this is what we asked for */
-        shape->numvalues = layer->numitems;
-    
-        shape->values = (char **)malloc( sizeof(char*) * shape->numvalues );
-        if (shape->values == NULL)
-        {
-            msSetError( MS_ORACLESPATIALERR, "No memory avaliable to allocate the values", "msOracleSpatialLayerNextShape()" );
-            return MS_FAILURE;
-        }
-    
-        for( i=0; i < shape->numvalues; ++i )
-        {
-            shape->values[i] = (char *)malloc(strlen((char *)sthand->items[i][ sthand->row ])+1);
-            if (shape->values[i] == NULL)
-            {
-                msSetError( MS_ORACLESPATIALERR, "No memory avaliable to allocate the items", "msOracleSpatialLayerNextShape()" );
-                return MS_FAILURE;
-            }
-            else
-            {
-                strcpy(shape->values[i], (char *)sthand->items[i][ sthand->row ]);
-                shape->values[i][strlen((char *)sthand->items[i][ sthand->row ])] = '\0';
-            }
-        }
-    
-        /* fetch a layer->type object */
-        success = osGetOrdinates(dthand, hand, shape, obj, ind);
-    
-        if (success != MS_SUCCESS)
-        {
-            msSetError( MS_ORACLESPATIALERR, "Call to osGetOrdinates failed.", "msOracleSpatialLayerGetShape()" );
-            return MS_FAILURE;
-        }
-    
-        osShapeBounds(shape);
-        if(shape->type == MS_SHAPE_NULL)  { 
-            msSetError( MS_ORACLESPATIALERR, "Shape type is null... this probably means a record number was requested that could not have beeen in a result set (as returned by NextShape).", "msOracleSpatialLayerGetShape()" );
-            return MS_FAILURE;
-        }
-    
-        return (MS_SUCCESS);
-    }
-    else /* no resultindex, fetch the shape from the DB */
-    {
-        char *table_name;
-        char query_str[6000], *geom_column_name = NULL, *unique = NULL, *srid = NULL;
-        int function = 0;
-        int version = 0;
-        sb2 *nullind = NULL;
-        /*OCIDefine *adtp = NULL, *items[QUERY_SIZE] = { NULL };*/
-        OCIDefine *adtp = NULL;
-        OCIDefine  **items = NULL;
-
-        if (layer->debug)
-            msDebug("msOracleSpatialLayerGetShape was called. Using the record = %ld.\n", shapeindex);
-
-        dthand = (msOracleSpatialDataHandler *)layerinfo->oradatahandlers;
-        hand = (msOracleSpatialHandler *)layerinfo->orahandlers;
-        sthand = (msOracleSpatialStatement *) layerinfo->orastmt;
-
-        /* allocate enough space for items */
-        if (layer->numitems > 0)
-        {
-            if (sthand->items_query == NULL)
-                sthand->items_query = (item_text_array_query *)malloc( sizeof(item_text_array_query) * (layer->numitems) );
-
-            if (sthand->items_query == NULL)
-            {
-                msSetError( MS_ORACLESPATIALERR, "Cannot allocate layerinfo->items_query buffer", "msOracleSpatialLayerGetShape()" );
-                return MS_FAILURE;
-            }
-
-            nullind = (sb2 *)malloc( sizeof(sb2) * (layer->numitems) );
-            if (nullind == NULL)
-            {
-                msSetError( MS_ORACLESPATIALERR, "Cannot allocate nullind buffer", "msOracleSpatialLayerGetShape()" );
-                return MS_FAILURE;
-            }
-            memset(nullind ,0, sizeof(sb2) * (layer->numitems) );
-
-            items = (OCIDefine **)malloc(sizeof(OCIDefine *)*layer->numitems);
-            if (items == NULL)
-            {
-                msSetError( MS_ORACLESPATIALERR,"Cannot allocate items buffer","msOracleSpatialLayerWhichShapes()" );
-
-                /* clean nullind  */
-                free(nullind);
-
-                return MS_FAILURE;
-            }
-            memset(items ,0,sizeof(OCIDefine *)*layer->numitems);
-        }
+    if (success != MS_SUCCESS) {
+      msSetError( MS_ORACLESPATIALERR, "Call to osGetOrdinates failed.", "msOracleSpatialLayerGetShape()" );
+      return MS_FAILURE;
+    }
 
-        table_name = (char *) malloc(sizeof(char) * TABLE_NAME_SIZE);
-        if (!msSplitData( layer->data, &geom_column_name, &table_name, &unique, &srid, &function, &version ))
-        {
-            msSetError( MS_ORACLESPATIALERR,
-                        "Error parsing OracleSpatial DATA variable. Must be: "
-                        "'geometry_column FROM table_name [USING UNIQUE <column> SRID srid# FUNCTION]' or "
-                        "'geometry_column FROM (SELECT stmt) [USING UNIQUE <column> SRID srid# FUNCTION]'. "
-                        "If want to set the FUNCTION statement you can use: FILTER, RELATE, GEOMRELATE or NONE. "
-                        "Your data statement: %s",
-                        "msOracleSpatialLayerGetShape()", layer->data );
-
-            /* clean nullind  */
-            free(nullind);
-
-            /* clean items */
-            free(items);
-
-            if (geom_column_name) free(geom_column_name);
-            if (srid) free(srid);
-            if (unique) free(unique);
-            free(table_name);
-
-            return MS_FAILURE;
-        }
+    osShapeBounds(shape);
+    if(shape->type == MS_SHAPE_NULL)  {
+      msSetError( MS_ORACLESPATIALERR, "Shape type is null... this probably means a record number was requested that could not have beeen in a result set (as returned by NextShape).", "msOracleSpatialLayerGetShape()" );
+      return MS_FAILURE;
+    }
+
+    return (MS_SUCCESS);
+  } else { /* no resultindex, fetch the shape from the DB */
+    char *table_name;
+    char query_str[6000], *geom_column_name = NULL, *unique = NULL, *srid = NULL;
+    int function = 0;
+    int version = 0;
+    sb2 *nullind = NULL;
+    /*OCIDefine *adtp = NULL, *items[QUERY_SIZE] = { NULL };*/
+    OCIDefine *adtp = NULL;
+    OCIDefine  **items = NULL;
 
-        /*Define the first query to retrive itens*/
-        if (unique[0] == '\0')
-        {
-            msSetError( MS_ORACLESPATIALERR, 
-                        "Error parsing OracleSpatial DATA variable for query. To execute "
-                        "query functions you need to define one "
-                        "unique column [USING UNIQUE <#column>]", 
-                        "msOracleSpatialLayerGetShape()" );
+    if (layer->debug)
+      msDebug("msOracleSpatialLayerGetShape was called. Using the record = %ld.\n", shapeindex);
 
-            /* clean nullind  */
-            free(nullind);
+    dthand = (msOracleSpatialDataHandler *)layerinfo->oradatahandlers;
+    hand = (msOracleSpatialHandler *)layerinfo->orahandlers;
+    sthand = (msOracleSpatialStatement *) layerinfo->orastmt;
 
-            /* clean items */
-            free(items);
+    /* allocate enough space for items */
+    if (layer->numitems > 0) {
+      if (sthand->items_query == NULL)
+        sthand->items_query = (item_text_array_query *)malloc( sizeof(item_text_array_query) * (layer->numitems) );
 
-            if (geom_column_name) free(geom_column_name);
-            if (srid) free(srid);
-            if (unique) free(unique);
-            free(table_name);
+      if (sthand->items_query == NULL) {
+        msSetError( MS_ORACLESPATIALERR, "Cannot allocate layerinfo->items_query buffer", "msOracleSpatialLayerGetShape()" );
+        return MS_FAILURE;
+      }
 
-            return MS_FAILURE;
-        }
-        else
-            snprintf( query_str, sizeof(query_str), "SELECT");
+      nullind = (sb2 *)malloc( sizeof(sb2) * (layer->numitems) );
+      if (nullind == NULL) {
+        msSetError( MS_ORACLESPATIALERR, "Cannot allocate nullind buffer", "msOracleSpatialLayerGetShape()" );
+        return MS_FAILURE;
+      }
+      memset(nullind ,0, sizeof(sb2) * (layer->numitems) );
 
-        /*Define the query*/
-        for( i = 0; i < layer->numitems; ++i )
-            snprintf( query_str + strlen(query_str), sizeof(query_str)-strlen(query_str), " %s,", layer->items[i] );
-    
-        snprintf( query_str + strlen(query_str), sizeof(query_str)-strlen(query_str), " %s FROM %s WHERE %s = %ld", geom_column_name, table_name, unique, shapeindex);
+      items = (OCIDefine **)malloc(sizeof(OCIDefine *)*layer->numitems);
+      if (items == NULL) {
+        msSetError( MS_ORACLESPATIALERR,"Cannot allocate items buffer","msOracleSpatialLayerWhichShapes()" );
 
-        /*if (layer->filter.string != NULL)
-          sprintf( query_str + strlen(query_str), " AND %s", (layer->filter.string));*/
-        osFilteritem(layer, FUNCTION_NONE, query_str, sizeof(query_str), 2);
+        /* clean nullind  */
+        free(nullind);
 
-    
-        if (layer->debug)
-            msDebug("msOracleSpatialLayerGetShape. Sql: %s\n", query_str);
+        return MS_FAILURE;
+      }
+      memset(items ,0,sizeof(OCIDefine *)*layer->numitems);
+    }
 
-        /*Prepare the handlers to the query*/
-        success = TRY( hand,OCIStmtPrepare( sthand->stmthp, hand->errhp, (text *)query_str, (ub4)strlen(query_str), (ub4)OCI_NTV_SYNTAX, (ub4)OCI_DEFAULT) );
+    table_name = (char *) malloc(sizeof(char) * TABLE_NAME_SIZE);
+    if (!msSplitData( layer->data, &geom_column_name, &table_name, &unique, &srid, &function, &version )) {
+      msSetError( MS_ORACLESPATIALERR,
+                  "Error parsing OracleSpatial DATA variable. Must be: "
+                  "'geometry_column FROM table_name [USING UNIQUE <column> SRID srid# FUNCTION]' or "
+                  "'geometry_column FROM (SELECT stmt) [USING UNIQUE <column> SRID srid# FUNCTION]'. "
+                  "If want to set the FUNCTION statement you can use: FILTER, RELATE, GEOMRELATE or NONE. "
+                  "Your data statement: %s",
+                  "msOracleSpatialLayerGetShape()", layer->data );
 
-        if (success && layer->numitems > 0)
-        {
-            for( i = 0; i < layer->numitems && success; i++ )
-                success = TRY( hand, OCIDefineByPos( sthand->stmthp, &items[i], hand->errhp, (ub4)i+1, (dvoid *)sthand->items_query[i], (sb4)TEXT_SIZE, SQLT_STR, (sb2 *)&nullind[i], (ub2 *)0, (ub2 *)0, (ub4)OCI_DEFAULT ) );
-        }
+      /* clean nullind  */
+      free(nullind);
 
-        if(!success)
-        {
-            msSetError( MS_ORACLESPATIALERR, 
-                        "Error: %s . "
-                        "Query statement: %s . "
-                        "Check your data statement.",
-                        "msOracleSpatialLayerGetShape()", hand->last_oci_error, query_str );
+      /* clean items */
+      free(items);
 
-            /* clean nullind  */
-            free(nullind);
+      if (geom_column_name) free(geom_column_name);
+      if (srid) free(srid);
+      if (unique) free(unique);
+      free(table_name);
 
-            /* clean items */
-            free(items);
+      return MS_FAILURE;
+    }
 
-            if (geom_column_name) free(geom_column_name);
-            if (srid) free(srid);
-            if (unique) free(unique);
-            free(table_name);
+    /*Define the first query to retrive itens*/
+    if (unique[0] == '\0') {
+      msSetError( MS_ORACLESPATIALERR,
+                  "Error parsing OracleSpatial DATA variable for query. To execute "
+                  "query functions you need to define one "
+                  "unique column [USING UNIQUE <#column>]",
+                  "msOracleSpatialLayerGetShape()" );
 
-            return MS_FAILURE;
-        }
+      /* clean nullind  */
+      free(nullind);
 
-        if (success)
-        {
-            success = TRY( hand, OCIDefineByPos( sthand->stmthp, &adtp, hand->errhp, (ub4)layer->numitems+1, (dvoid *)0, (sb4)0, SQLT_NTY, (dvoid *)0, (ub2 *)0, (ub2 *)0, (ub4)OCI_DEFAULT) )
-                && TRY( hand, OCIDefineObject( adtp, hand->errhp, dthand->tdo, (dvoid **)sthand->obj, (ub4 *)0, (dvoid **)sthand->ind, (ub4 *)0 ) )
-                && TRY (hand, OCIStmtExecute( hand->svchp, sthand->stmthp, hand->errhp, (ub4)QUERY_SIZE, (ub4)0, (OCISnapshot *)NULL, (OCISnapshot *)NULL, (ub4)OCI_DEFAULT ))
-                && TRY (hand, OCIAttrGet( (dvoid *)sthand->stmthp, (ub4)OCI_HTYPE_STMT, (dvoid *)&sthand->rows_fetched, (ub4 *)0, (ub4)OCI_ATTR_ROW_COUNT, hand->errhp ));
+      /* clean items */
+      free(items);
 
-        }
+      if (geom_column_name) free(geom_column_name);
+      if (srid) free(srid);
+      if (unique) free(unique);
+      free(table_name);
 
-        if(!success)
-        {
-            msSetError( MS_ORACLESPATIALERR, 
-                        "Error: %s . "
-                        "Query statement: %s ."
-                        "Check your data statement.",
-                        "msOracleSpatialLayerGetShape()", hand->last_oci_error, query_str );
+      return MS_FAILURE;
+    } else
+      snprintf( query_str, sizeof(query_str), "SELECT");
 
-            /* clean nullind  */
-            free(nullind);
+    /*Define the query*/
+    for( i = 0; i < layer->numitems; ++i )
+      snprintf( query_str + strlen(query_str), sizeof(query_str)-strlen(query_str), " %s,", layer->items[i] );
 
-            /* clean items */
-            free(items);
+    snprintf( query_str + strlen(query_str), sizeof(query_str)-strlen(query_str), " %s FROM %s WHERE %s = %ld", geom_column_name, table_name, unique, shapeindex);
 
-            if (geom_column_name) free(geom_column_name);
-            if (srid) free(srid);
-            if (unique) free(unique);
-            free(table_name);
+    /*if (layer->filter.string != NULL)
+      sprintf( query_str + strlen(query_str), " AND %s", (layer->filter.string));*/
+    osFilteritem(layer, FUNCTION_NONE, query_str, sizeof(query_str), 2);
 
-            return MS_FAILURE;
-        }
 
-        shape->type = MS_SHAPE_NULL;
+    if (layer->debug)
+      msDebug("msOracleSpatialLayerGetShape. Sql: %s\n", query_str);
 
-        /* no rows fetched */
-        if (sthand->rows_fetched == 0)
-        {
-            /* clean nullind  */
-            free(nullind);
+    /*Prepare the handlers to the query*/
+    success = TRY( hand,OCIStmtPrepare( sthand->stmthp, hand->errhp, (text *)query_str, (ub4)strlen(query_str), (ub4)OCI_NTV_SYNTAX, (ub4)OCI_DEFAULT) );
 
-            /* clean items */
-            free(items);
+    if (success && layer->numitems > 0) {
+      for( i = 0; i < layer->numitems && success; i++ )
+        success = TRY( hand, OCIDefineByPos( sthand->stmthp, &items[i], hand->errhp, (ub4)i+1, (dvoid *)sthand->items_query[i], (sb4)TEXT_SIZE, SQLT_STR, (sb2 *)&nullind[i], (ub2 *)0, (ub2 *)0, (ub4)OCI_DEFAULT ) );
+    }
 
-            if (geom_column_name) free(geom_column_name);
-            if (srid) free(srid);
-            if (unique) free(unique);
-            free(table_name);
+    if(!success) {
+      msSetError( MS_ORACLESPATIALERR,
+                  "Error: %s . "
+                  "Query statement: %s . "
+                  "Check your data statement.",
+                  "msOracleSpatialLayerGetShape()", hand->last_oci_error, query_str );
 
-            return (MS_DONE);
-        }
+      /* clean nullind  */
+      free(nullind);
+
+      /* clean items */
+      free(items);
+
+      if (geom_column_name) free(geom_column_name);
+      if (srid) free(srid);
+      if (unique) free(unique);
+      free(table_name);
+
+      return MS_FAILURE;
+    }
 
-        obj = sthand->obj[ sthand->row ];
-        ind = sthand->ind[ sthand->row ];
+    if (success) {
+      success = TRY( hand, OCIDefineByPos( sthand->stmthp, &adtp, hand->errhp, (ub4)layer->numitems+1, (dvoid *)0, (sb4)0, SQLT_NTY, (dvoid *)0, (ub2 *)0, (ub2 *)0, (ub4)OCI_DEFAULT) )
+                && TRY( hand, OCIDefineObject( adtp, hand->errhp, dthand->tdo, (dvoid **)sthand->obj, (ub4 *)0, (dvoid **)sthand->ind, (ub4 *)0 ) )
+                && TRY (hand, OCIStmtExecute( hand->svchp, sthand->stmthp, hand->errhp, (ub4)QUERY_SIZE, (ub4)0, (OCISnapshot *)NULL, (OCISnapshot *)NULL, (ub4)OCI_DEFAULT ))
+                && TRY (hand, OCIAttrGet( (dvoid *)sthand->stmthp, (ub4)OCI_HTYPE_STMT, (dvoid *)&sthand->rows_fetched, (ub4 *)0, (ub4)OCI_ATTR_ROW_COUNT, hand->errhp ));
 
-        /* get the items for the shape */
-        shape->numvalues = layer->numitems;
-        shape->values = (char **) malloc(sizeof(char *) * layer->numitems);
-        if (shape->values == NULL)
-        {
-            msSetError( MS_ORACLESPATIALERR, "No memory avaliable to allocate the values.", "msOracleSpatialLayerGetShape()" );
+    }
 
-            /* clean nullind  */
-            free(nullind);
+    if(!success) {
+      msSetError( MS_ORACLESPATIALERR,
+                  "Error: %s . "
+                  "Query statement: %s ."
+                  "Check your data statement.",
+                  "msOracleSpatialLayerGetShape()", hand->last_oci_error, query_str );
 
-            /* clean items */
-            free(items);
+      /* clean nullind  */
+      free(nullind);
 
-            if (geom_column_name) free(geom_column_name);
-            if (srid) free(srid);
-            if (unique) free(unique);
-            free(table_name);
+      /* clean items */
+      free(items);
 
-            return MS_FAILURE;
-        }
+      if (geom_column_name) free(geom_column_name);
+      if (srid) free(srid);
+      if (unique) free(unique);
+      free(table_name);
 
-        shape->index = shapeindex;
+      return MS_FAILURE;
+    }
 
-        for( i = 0; i < layer->numitems; ++i )
-        {
-            shape->values[i] = (char *)malloc(strlen((char *)sthand->items_query[sthand->row][i])+1);
+    shape->type = MS_SHAPE_NULL;
 
-            if (shape->values[i] == NULL)
-            {
-                msSetError( MS_ORACLESPATIALERR, "No memory avaliable to allocate the items buffer.", "msOracleSpatialLayerGetShape()" );
+    /* no rows fetched */
+    if (sthand->rows_fetched == 0) {
+      /* clean nullind  */
+      free(nullind);
 
-                /* clean nullind  */
-                free(nullind);
+      /* clean items */
+      free(items);
 
-                /* clean items */
-                free(items);
+      if (geom_column_name) free(geom_column_name);
+      if (srid) free(srid);
+      if (unique) free(unique);
+      free(table_name);
 
-                if (geom_column_name) free(geom_column_name);
-                if (srid) free(srid);
-                if (unique) free(unique);
-                free(table_name);
+      return (MS_DONE);
+    }
 
-                return MS_FAILURE;
-            }
-            else
-            {
-                if (nullind[i] != OCI_IND_NULL)
-                {
-                    strcpy(shape->values[i], (char *)sthand->items_query[sthand->row][i]);
-                    shape->values[i][strlen((char *)sthand->items_query[sthand->row][i])] = '\0';
-                }
-                else
-                {
-                    shape->values[i][0] = '\0';
-                }
-            }
-        }
+    obj = sthand->obj[ sthand->row ];
+    ind = sthand->ind[ sthand->row ];
 
-        /* increment for next row */
-        sthand->row_num++;
-        sthand->row++;
+    /* get the items for the shape */
+    shape->numvalues = layer->numitems;
+    shape->values = (char **) malloc(sizeof(char *) * layer->numitems);
+    if (shape->values == NULL) {
+      msSetError( MS_ORACLESPATIALERR, "No memory avaliable to allocate the values.", "msOracleSpatialLayerGetShape()" );
 
-        /* fetch a layer->type object */
-        success = osGetOrdinates(dthand, hand, shape, obj, ind);
-        if (success != MS_SUCCESS)
-        {
-            msSetError( MS_ORACLESPATIALERR, "Cannot execute query", "msOracleSpatialLayerGetShape()" );
+      /* clean nullind  */
+      free(nullind);
 
-            /* clean nullind  */
-            free(nullind);
+      /* clean items */
+      free(items);
 
-            /* clean items */
-            free(items);
+      if (geom_column_name) free(geom_column_name);
+      if (srid) free(srid);
+      if (unique) free(unique);
+      free(table_name);
 
-            if (geom_column_name) free(geom_column_name);
-            if (srid) free(srid);
-            if (unique) free(unique);
-            free(table_name);
+      return MS_FAILURE;
+    }
 
-            return MS_FAILURE;
-        }
-        osShapeBounds(shape);
-        sthand->row = sthand->row_num = 0;
+    shape->index = shapeindex;
+
+    for( i = 0; i < layer->numitems; ++i ) {
+      shape->values[i] = (char *)malloc(strlen((char *)sthand->items_query[sthand->row][i])+1);
+
+      if (shape->values[i] == NULL) {
+        msSetError( MS_ORACLESPATIALERR, "No memory avaliable to allocate the items buffer.", "msOracleSpatialLayerGetShape()" );
 
         /* clean nullind  */
         free(nullind);
@@ -2780,36 +2552,82 @@ int msOracleSpatialLayerGetShape( layerObj *layer, shapeObj *shape, resultObj *r
         if (unique) free(unique);
         free(table_name);
 
-        return (MS_SUCCESS);
+        return MS_FAILURE;
+      } else {
+        if (nullind[i] != OCI_IND_NULL) {
+          strcpy(shape->values[i], (char *)sthand->items_query[sthand->row][i]);
+          shape->values[i][strlen((char *)sthand->items_query[sthand->row][i])] = '\0';
+        } else {
+          shape->values[i][0] = '\0';
+        }
+      }
+    }
+
+    /* increment for next row */
+    sthand->row_num++;
+    sthand->row++;
+
+    /* fetch a layer->type object */
+    success = osGetOrdinates(dthand, hand, shape, obj, ind);
+    if (success != MS_SUCCESS) {
+      msSetError( MS_ORACLESPATIALERR, "Cannot execute query", "msOracleSpatialLayerGetShape()" );
+
+      /* clean nullind  */
+      free(nullind);
+
+      /* clean items */
+      free(items);
+
+      if (geom_column_name) free(geom_column_name);
+      if (srid) free(srid);
+      if (unique) free(unique);
+      free(table_name);
+
+      return MS_FAILURE;
     }
+    osShapeBounds(shape);
+    sthand->row = sthand->row_num = 0;
+
+    /* clean nullind  */
+    free(nullind);
+
+    /* clean items */
+    free(items);
+
+    if (geom_column_name) free(geom_column_name);
+    if (srid) free(srid);
+    if (unique) free(unique);
+    free(table_name);
+
+    return (MS_SUCCESS);
+  }
 }
 
 int msOracleSpatialLayerInitItemInfo( layerObj *layer )
 {
-    int i;
-    int *itemindexes ;
+  int i;
+  int *itemindexes ;
 
-    if (layer->debug)
-        msDebug("msOracleSpatialLayerInitItemInfo was called.\n");
+  if (layer->debug)
+    msDebug("msOracleSpatialLayerInitItemInfo was called.\n");
 
-    if (layer->numitems == 0)
-        return MS_SUCCESS;
+  if (layer->numitems == 0)
+    return MS_SUCCESS;
 
-    if (layer->iteminfo)
-        free( layer->iteminfo );
+  if (layer->iteminfo)
+    free( layer->iteminfo );
 
-    if ((layer->iteminfo = (long *)malloc(sizeof(int)*layer->numitems))== NULL)
-    {
-        msSetError(MS_MEMERR, NULL, "msOracleSpatialLayerInitItemInfo()");
-        return MS_FAILURE;
-    }
+  if ((layer->iteminfo = (long *)malloc(sizeof(int)*layer->numitems))== NULL) {
+    msSetError(MS_MEMERR, NULL, "msOracleSpatialLayerInitItemInfo()");
+    return MS_FAILURE;
+  }
 
-    itemindexes = (int*)layer->iteminfo;
+  itemindexes = (int*)layer->iteminfo;
 
-    for(i=0; i < layer->numitems; i++)
-        itemindexes[i] = i;  /*last one is always the geometry one - the rest are non-geom*/
+  for(i=0; i < layer->numitems; i++)
+    itemindexes[i] = i;  /*last one is always the geometry one - the rest are non-geom*/
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 /* AutoProjection Support for RFC 37 #3333
@@ -2817,546 +2635,562 @@ int msOracleSpatialLayerInitItemInfo( layerObj *layer )
  */
 int msOracleSpatialLayerGetAutoProjection( layerObj *layer, projectionObj *projection )
 {
-    char *table_name;
-    char *query_str, *geom_column_name = NULL, *unique = NULL, *srid = NULL;
-    int success;
-    int function = 0;
-    int version = 0;
-    char wktext[4000];
-    
-    OCIDefine *def1p = NULL;
-    OCIBind *bnd1p = NULL,  *bnd2p = NULL;
-    
-    msOracleSpatialLayerInfo *layerinfo = (msOracleSpatialLayerInfo *)layer->layerinfo;
-    msOracleSpatialDataHandler *dthand = NULL;
-    msOracleSpatialHandler *hand = NULL;
-    msOracleSpatialStatement *sthand = NULL;
+  char *table_name;
+  char *query_str, *geom_column_name = NULL, *unique = NULL, *srid = NULL;
+  int success;
+  int function = 0;
+  int version = 0;
+  char wktext[4000];
 
-    if (layer->debug)
-        msDebug("msOracleSpatialLayerGetAutoProjection was called.\n");
-    
-    if (layerinfo == NULL)
-    {
-        msSetError( MS_ORACLESPATIALERR, "msOracleSpatialLayerGetAutoProjection called on unopened layer","msOracleSpatialLayerGetAutoProjection()");
-        return MS_FAILURE;
-    }
-    else
-    {
-        dthand = (msOracleSpatialDataHandler *)layerinfo->oradatahandlers;
-        hand = (msOracleSpatialHandler *)layerinfo->orahandlers;
-        sthand = (msOracleSpatialStatement *) layerinfo->orastmt;
-    }
-    
-    table_name = (char *) malloc(sizeof(char) * TABLE_NAME_SIZE);
-    if (!msSplitData( layer->data, &geom_column_name, &table_name, &unique, &srid, &function, &version )) 
-    {
-        msSetError( MS_ORACLESPATIALERR, 
-                   "Error parsing OracleSpatial DATA variable. Must be: "
-                   "'geometry_column FROM table_name [USING UNIQUE <column> SRID srid# FUNCTION]' or "
-                   "'geometry_column FROM (SELECT stmt) [USING UNIQUE <column> SRID srid# FUNCTION]'. "
-                   "If want to set the FUNCTION statement you can use: FILTER, RELATE, GEOMRELATE or NONE. "
-                   "Your data statement: %s", 
-                   "msOracleSpatialLayerGetAutoProjection()", layer->data );
+  OCIDefine *def1p = NULL;
+  OCIBind *bnd1p = NULL,  *bnd2p = NULL;
 
-        if (geom_column_name) free(geom_column_name);
-        if (srid) free(srid);
-        if (unique) free(unique);
-        free(table_name);
-        
-        return MS_FAILURE;
-    }
+  msOracleSpatialLayerInfo *layerinfo = (msOracleSpatialLayerInfo *)layer->layerinfo;
+  msOracleSpatialDataHandler *dthand = NULL;
+  msOracleSpatialHandler *hand = NULL;
+  msOracleSpatialStatement *sthand = NULL;
 
-    query_str = "SELECT wktext FROM mdsys.all_sdo_geom_metadata m, mdsys.cs_srs c WHERE c.srid = m.srid and m.owner||'.'||m.table_name = :table_name and m.column_name = :geo_col_name "
-                "UNION SELECT wktext from mdsys.user_sdo_geom_metadata m, mdsys.cs_srs c WHERE c.srid = m.srid and m.table_name = :table_name and m.column_name = :geo_col_name";
-    
-    if (layer->debug)
-        msDebug("msOracleSpatialLayerGetAutoProjection. Using this Sql to retrieve the projection: %s.\n", query_str);
-    
-    /*Prepare the handlers to the query*/
-    success = TRY( hand, OCIStmtPrepare( sthand->stmthp, hand->errhp, (text *)query_str, (ub4)strlen(query_str), (ub4)OCI_NTV_SYNTAX, (ub4)OCI_DEFAULT ) )
-           && TRY( hand, OCIBindByName( sthand->stmthp, &bnd2p, hand->errhp, (text *) ":table_name", strlen(":table_name"), (ub1*) table_name, strlen(table_name)+1, SQLT_STR, (dvoid *) 0, (ub2 *) 0, (ub2) 0, (ub4) 0, (ub4 *) 0, OCI_DEFAULT ) )
-           && TRY( hand, OCIBindByName( sthand->stmthp, &bnd1p, hand->errhp, (text *) ":geo_col_name", strlen(":geo_col_name"), (ub1*) geom_column_name, strlen(geom_column_name)+1, SQLT_STR, (dvoid *) 0, (ub2 *) 0, (ub2) 0, (ub4) 0, (ub4 *) 0, OCI_DEFAULT ) )
-           && TRY( hand, OCIDefineByPos( sthand->stmthp, &def1p, hand->errhp, (ub4)1, (dvoid *)wktext, (sb4)4000, SQLT_STR, (dvoid *)0, (ub2 *)0, (ub2 *)0, (ub4)OCI_DEFAULT ) )
-           && TRY( hand, OCIStmtExecute( hand->svchp, sthand->stmthp, hand->errhp, (ub4)0, (ub4)0, (OCISnapshot *)NULL, (OCISnapshot *)NULL, (ub4)OCI_DEFAULT ) )
-           && TRY( hand, OCIAttrGet( (dvoid *)sthand->stmthp, (ub4)OCI_HTYPE_STMT, (dvoid *)&sthand->rows_fetched, (ub4 *)0, (ub4)OCI_ATTR_ROWS_FETCHED, hand->errhp ) );
-    
-    if(!success)
-    {
-        msSetError( MS_ORACLESPATIALERR,
-                   "Error: %s . "
-                   "Query statement: %s . "
-                   "Check your data statement.",
-                   "msOracleSpatialLayerGetAutoProjection()", hand->last_oci_error, query_str );
+  if (layer->debug)
+    msDebug("msOracleSpatialLayerGetAutoProjection was called.\n");
+
+  if (layerinfo == NULL) {
+    msSetError( MS_ORACLESPATIALERR, "msOracleSpatialLayerGetAutoProjection called on unopened layer","msOracleSpatialLayerGetAutoProjection()");
+    return MS_FAILURE;
+  } else {
+    dthand = (msOracleSpatialDataHandler *)layerinfo->oradatahandlers;
+    hand = (msOracleSpatialHandler *)layerinfo->orahandlers;
+    sthand = (msOracleSpatialStatement *) layerinfo->orastmt;
+  }
+
+  table_name = (char *) malloc(sizeof(char) * TABLE_NAME_SIZE);
+  if (!msSplitData( layer->data, &geom_column_name, &table_name, &unique, &srid, &function, &version )) {
+    msSetError( MS_ORACLESPATIALERR,
+                "Error parsing OracleSpatial DATA variable. Must be: "
+                "'geometry_column FROM table_name [USING UNIQUE <column> SRID srid# FUNCTION]' or "
+                "'geometry_column FROM (SELECT stmt) [USING UNIQUE <column> SRID srid# FUNCTION]'. "
+                "If want to set the FUNCTION statement you can use: FILTER, RELATE, GEOMRELATE or NONE. "
+                "Your data statement: %s",
+                "msOracleSpatialLayerGetAutoProjection()", layer->data );
 
-        if (geom_column_name) free(geom_column_name);
-        if (srid) free(srid);
-        if (unique) free(unique);
-        free(table_name);
-        return MS_FAILURE;
-    }
-   do {
-       success = TRY( hand, OCIStmtFetch( sthand->stmthp, hand->errhp, (ub4)1, (ub2)OCI_FETCH_NEXT, (ub4)OCI_DEFAULT ) ) 
-              && TRY( hand, OCIAttrGet( (dvoid *)sthand->stmthp, (ub4)OCI_HTYPE_STMT, (dvoid *)&sthand->rows_fetched, (ub4 *)0, (ub4)OCI_ATTR_ROWS_FETCHED, hand->errhp ) );
-       if (success && sthand->rows_fetched > 0) {
-       
-           if( layer->debug )
-               msDebug("Found WKT projection for table %s: %s\n", table_name, wktext);
-
-           if(wktext != NULL && projection != NULL)
-               if(msOGCWKT2ProjectionObj(wktext, projection, layer->debug) == MS_FAILURE)
-                   return(MS_FAILURE);
-       }
-    } while (sthand->rows_fetched > 0);
-
-   if (geom_column_name) free(geom_column_name);
-   if (srid) free(srid);
-   if (unique) free(unique);
+    if (geom_column_name) free(geom_column_name);
+    if (srid) free(srid);
+    if (unique) free(unique);
+    free(table_name);
+
+    return MS_FAILURE;
+  }
+
+  query_str = "SELECT wktext FROM mdsys.all_sdo_geom_metadata m, mdsys.cs_srs c WHERE c.srid = m.srid and m.owner||'.'||m.table_name = :table_name and m.column_name = :geo_col_name "
+              "UNION SELECT wktext from mdsys.user_sdo_geom_metadata m, mdsys.cs_srs c WHERE c.srid = m.srid and m.table_name = :table_name and m.column_name = :geo_col_name";
+
+  if (layer->debug)
+    msDebug("msOracleSpatialLayerGetAutoProjection. Using this Sql to retrieve the projection: %s.\n", query_str);
+
+  /*Prepare the handlers to the query*/
+  success = TRY( hand, OCIStmtPrepare( sthand->stmthp, hand->errhp, (text *)query_str, (ub4)strlen(query_str), (ub4)OCI_NTV_SYNTAX, (ub4)OCI_DEFAULT ) )
+            && TRY( hand, OCIBindByName( sthand->stmthp, &bnd2p, hand->errhp, (text *) ":table_name", strlen(":table_name"), (ub1*) table_name, strlen(table_name)+1, SQLT_STR, (dvoid *) 0, (ub2 *) 0, (ub2) 0, (ub4) 0, (ub4 *) 0, OCI_DEFAULT ) )
+            && TRY( hand, OCIBindByName( sthand->stmthp, &bnd1p, hand->errhp, (text *) ":geo_col_name", strlen(":geo_col_name"), (ub1*) geom_column_name, strlen(geom_column_name)+1, SQLT_STR, (dvoid *) 0, (ub2 *) 0, (ub2) 0, (ub4) 0, (ub4 *) 0, OCI_DEFAULT ) )
+            && TRY( hand, OCIDefineByPos( sthand->stmthp, &def1p, hand->errhp, (ub4)1, (dvoid *)wktext, (sb4)4000, SQLT_STR, (dvoid *)0, (ub2 *)0, (ub2 *)0, (ub4)OCI_DEFAULT ) )
+            && TRY( hand, OCIStmtExecute( hand->svchp, sthand->stmthp, hand->errhp, (ub4)0, (ub4)0, (OCISnapshot *)NULL, (OCISnapshot *)NULL, (ub4)OCI_DEFAULT ) )
+            && TRY( hand, OCIAttrGet( (dvoid *)sthand->stmthp, (ub4)OCI_HTYPE_STMT, (dvoid *)&sthand->rows_fetched, (ub4 *)0, (ub4)OCI_ATTR_ROWS_FETCHED, hand->errhp ) );
+
+  if(!success) {
+    msSetError( MS_ORACLESPATIALERR,
+                "Error: %s . "
+                "Query statement: %s . "
+                "Check your data statement.",
+                "msOracleSpatialLayerGetAutoProjection()", hand->last_oci_error, query_str );
+
+    if (geom_column_name) free(geom_column_name);
+    if (srid) free(srid);
+    if (unique) free(unique);
     free(table_name);
-    return MS_SUCCESS;    
+    return MS_FAILURE;
+  }
+  do {
+    success = TRY( hand, OCIStmtFetch( sthand->stmthp, hand->errhp, (ub4)1, (ub2)OCI_FETCH_NEXT, (ub4)OCI_DEFAULT ) )
+              && TRY( hand, OCIAttrGet( (dvoid *)sthand->stmthp, (ub4)OCI_HTYPE_STMT, (dvoid *)&sthand->rows_fetched, (ub4 *)0, (ub4)OCI_ATTR_ROWS_FETCHED, hand->errhp ) );
+    if (success && sthand->rows_fetched > 0) {
+
+      if( layer->debug )
+        msDebug("Found WKT projection for table %s: %s\n", table_name, wktext);
+
+      if(wktext != NULL && projection != NULL)
+        if(msOGCWKT2ProjectionObj(wktext, projection, layer->debug) == MS_FAILURE)
+          return(MS_FAILURE);
+    }
+  } while (sthand->rows_fetched > 0);
+
+  if (geom_column_name) free(geom_column_name);
+  if (srid) free(srid);
+  if (unique) free(unique);
+  free(table_name);
+  return MS_SUCCESS;
 }
 
 /**********************************************************************
  *             msOracleSpatialGetFieldDefn()
  *
  * Pass the field definitions through to the layer metadata in the
- * "gml_[item]_{type,width,precision}" set of metadata items for 
+ * "gml_[item]_{type,width,precision}" set of metadata items for
  * defining fields.
  **********************************************************************/
 static void
-msOracleSpatialGetFieldDefn( layerObj *layer, 
+msOracleSpatialGetFieldDefn( layerObj *layer,
                              msOracleSpatialHandler *hand,
                              const char *item,
                              OCIParam *pard )
 
 {
-    const char *gml_type = "Character";
-    char md_item_name[256];
-    char gml_width[32], gml_precision[32];
-    int success;
-    ub2 rzttype, nOCILen;
-        
-    gml_width[0] = '\0';
-    gml_precision[0] = '\0';
-
-/* -------------------------------------------------------------------- */
-/*      Get basic parameter details.                                    */
-/* -------------------------------------------------------------------- */
-    success = 
-        TRY( hand, OCIAttrGet ((dvoid *) pard,(ub4) OCI_DTYPE_PARAM,
-                               (dvoid*)&rzttype,(ub4 *)0, 
-                               (ub4) OCI_ATTR_DATA_TYPE, hand->errhp ))
-        && TRY( hand, OCIAttrGet ((dvoid *) pard,(ub4) OCI_DTYPE_PARAM,
-                                  (dvoid*)&nOCILen ,(ub4 *)0, 
-                                  (ub4) OCI_ATTR_DATA_SIZE, hand->errhp ));
-
-    if( !success )
-        return;
-
-    switch( rzttype )
-    {
-      case SQLT_CHR:
-      case SQLT_AFC:
-        gml_type = "Character";
-        if( nOCILen <= 4000 )
-            sprintf( gml_width, "%d", nOCILen );
-        break;
-
-      case SQLT_NUM:
-      {
-          // NOTE: OCI docs say this should be ub1 type, but we have
-            // determined that oracle is actually returning a short so we
-            // use that type and try to compensate for possible problems by
-            // initializing, and dividing by 256 if it is large. 
-            unsigned short byPrecision = 0;
-            sb1 nScale = 0;
-
-            if( !TRY( hand, OCIAttrGet ((dvoid *) pard,(ub4) OCI_DTYPE_PARAM,
-                                       (dvoid*)&byPrecision ,(ub4 *)0, 
-                                       (ub4) OCI_ATTR_PRECISION, 
-                                        hand->errhp ))
-                || !TRY( hand, OCIAttrGet ((dvoid *) pard,(ub4) OCI_DTYPE_PARAM,
-                                           (dvoid*)&nScale,(ub4 *)0, 
-                                           (ub4) OCI_ATTR_SCALE, 
-                                           hand->errhp )) )
-                return;
-            if( byPrecision > 255 )
-                byPrecision = byPrecision / 256;
-            
-            if( nScale > 0 )
-            {
-                gml_type = "Real";
-                sprintf( gml_width, "%d", byPrecision );
-                sprintf( gml_precision, "%d", nScale );
-            }
-            else if( nScale < 0 )
-                gml_type = "Real";
-            else
-            {
-                gml_type = "Integer";
-                if( byPrecision < 38 )
-                    sprintf( gml_width, "%d", byPrecision );
-            }
-      }
+  const char *gml_type = "Character";
+  char md_item_name[256];
+  char gml_width[32], gml_precision[32];
+  int success;
+  ub2 rzttype, nOCILen;
+
+  gml_width[0] = '\0';
+  gml_precision[0] = '\0';
+
+  /* -------------------------------------------------------------------- */
+  /*      Get basic parameter details.                                    */
+  /* -------------------------------------------------------------------- */
+  success =
+    TRY( hand, OCIAttrGet ((dvoid *) pard,(ub4) OCI_DTYPE_PARAM,
+                           (dvoid*)&rzttype,(ub4 *)0,
+                           (ub4) OCI_ATTR_DATA_TYPE, hand->errhp ))
+    && TRY( hand, OCIAttrGet ((dvoid *) pard,(ub4) OCI_DTYPE_PARAM,
+                              (dvoid*)&nOCILen ,(ub4 *)0,
+                              (ub4) OCI_ATTR_DATA_SIZE, hand->errhp ));
+
+  if( !success )
+    return;
+
+  switch( rzttype ) {
+    case SQLT_CHR:
+    case SQLT_AFC:
+      gml_type = "Character";
+      if( nOCILen <= 4000 )
+        sprintf( gml_width, "%d", nOCILen );
       break;
-      
-      case SQLT_DAT:
-      case SQLT_DATE:
-      case SQLT_TIMESTAMP:
-      case SQLT_TIMESTAMP_TZ:
-      case SQLT_TIMESTAMP_LTZ:
-      case SQLT_TIME:
-      case SQLT_TIME_TZ:
-        gml_type = "Date";
-        break;
 
-      default:
-        gml_type = "Character";
+    case SQLT_NUM: {
+      /* NOTE: OCI docs say this should be ub1 type, but we have
+         determined that oracle is actually returning a short so we
+         use that type and try to compensate for possible problems by
+         initializing, and dividing by 256 if it is large. */
+      unsigned short byPrecision = 0;
+      sb1 nScale = 0;
+
+      if( !TRY( hand, OCIAttrGet ((dvoid *) pard,(ub4) OCI_DTYPE_PARAM,
+                                  (dvoid*)&byPrecision ,(ub4 *)0,
+                                  (ub4) OCI_ATTR_PRECISION,
+                                  hand->errhp ))
+          || !TRY( hand, OCIAttrGet ((dvoid *) pard,(ub4) OCI_DTYPE_PARAM,
+                                     (dvoid*)&nScale,(ub4 *)0,
+                                     (ub4) OCI_ATTR_SCALE,
+                                     hand->errhp )) )
+        return;
+      if( byPrecision > 255 )
+        byPrecision = byPrecision / 256;
+
+      if( nScale > 0 ) {
+        gml_type = "Real";
+        sprintf( gml_width, "%d", byPrecision );
+        sprintf( gml_precision, "%d", nScale );
+      } else if( nScale < 0 )
+        gml_type = "Real";
+      else {
+        gml_type = "Integer";
+        if( byPrecision < 38 )
+          sprintf( gml_width, "%d", byPrecision );
+      }
     }
+    break;
 
-    snprintf( md_item_name, sizeof(md_item_name), "gml_%s_type", item );
-    if( msOWSLookupMetadata(&(layer->metadata), "G", "type") == NULL )
-        msInsertHashTable(&(layer->metadata), md_item_name, gml_type );
-    
-    snprintf( md_item_name, sizeof(md_item_name), "gml_%s_width", item );
-    if( strlen(gml_width) > 0 
-        && msOWSLookupMetadata(&(layer->metadata), "G", "width") == NULL )
-        msInsertHashTable(&(layer->metadata), md_item_name, gml_width );
-    
-    snprintf( md_item_name, sizeof(md_item_name), "gml_%s_precision",item );
-    if( strlen(gml_precision) > 0 
-        && msOWSLookupMetadata(&(layer->metadata), "G", "precision")==NULL )
-        msInsertHashTable(&(layer->metadata), md_item_name, gml_precision );
-}
+    case SQLT_DAT:
+    case SQLT_DATE:
+    case SQLT_TIMESTAMP:
+    case SQLT_TIMESTAMP_TZ:
+    case SQLT_TIMESTAMP_LTZ:
+    case SQLT_TIME:
+    case SQLT_TIME_TZ:
+      gml_type = "Date";
+      break;
 
-int msOracleSpatialLayerGetItems( layerObj *layer )
-{
-    char *rzt = "";
-    ub2 rzttype = 0;
-    char *flk = "";
-    int function = 0;
-    int version = 0;
-    int existgeom;
-    int count_item, flk_len, success, i;
-    char *table_name;
-    char query_str[6000], *geom_column_name = NULL, *unique = NULL, *srid = NULL;
-    OCIParam *pard = (OCIParam *) 0;
+    default:
+      gml_type = "Character";
+  }
 
-    msOracleSpatialLayerInfo *layerinfo = (msOracleSpatialLayerInfo *) layer->layerinfo;
-    msOracleSpatialDataHandler *dthand = NULL;
-    msOracleSpatialHandler *hand = NULL;
-    msOracleSpatialStatement *sthand = NULL;
-    int get_field_details = 0;
-    const char *value;
+  snprintf( md_item_name, sizeof(md_item_name), "gml_%s_type", item );
+  if( msOWSLookupMetadata(&(layer->metadata), "G", "type") == NULL )
+    msInsertHashTable(&(layer->metadata), md_item_name, gml_type );
 
-    if (layer->debug)
-        msDebug("msOracleSpatialLayerGetItems was called.\n");
+  snprintf( md_item_name, sizeof(md_item_name), "gml_%s_width", item );
+  if( strlen(gml_width) > 0
+      && msOWSLookupMetadata(&(layer->metadata), "G", "width") == NULL )
+    msInsertHashTable(&(layer->metadata), md_item_name, gml_width );
 
-    if (layerinfo == NULL)
-    {
-        msSetError( MS_ORACLESPATIALERR, "msOracleSpatialLayerGetItems called on unopened layer", "msOracleSpatialLayerGetItems()" );
-        return MS_FAILURE;
-    }
-    else
-    {
-        dthand = (msOracleSpatialDataHandler *)layerinfo->oradatahandlers;
-        hand = (msOracleSpatialHandler *)layerinfo->orahandlers;
-        sthand = (msOracleSpatialStatement *) layerinfo->orastmt;
-    }
+  snprintf( md_item_name, sizeof(md_item_name), "gml_%s_precision",item );
+  if( strlen(gml_precision) > 0
+      && msOWSLookupMetadata(&(layer->metadata), "G", "precision")==NULL )
+    msInsertHashTable(&(layer->metadata), md_item_name, gml_precision );
+}
 
-    /* Will we want to capture the field details? */
-    if((value = msOWSLookupMetadata(&(layer->metadata), "G", "types")) != NULL
-       && strcasecmp(value,"auto") == 0 )
-        get_field_details = 1;
+int msOracleSpatialLayerGetItems( layerObj *layer )
+{
+  char *rzt = "";
+  ub2 rzttype = 0;
+  char *flk = "";
+  int function = 0;
+  int version = 0;
+  int existgeom;
+  int count_item, flk_len, success, i;
+  char *table_name;
+  char query_str[6000], *geom_column_name = NULL, *unique = NULL, *srid = NULL;
+  OCIParam *pard = (OCIParam *) 0;
+
+  msOracleSpatialLayerInfo *layerinfo = (msOracleSpatialLayerInfo *) layer->layerinfo;
+  msOracleSpatialDataHandler *dthand = NULL;
+  msOracleSpatialHandler *hand = NULL;
+  msOracleSpatialStatement *sthand = NULL;
+  int get_field_details = 0;
+  const char *value;
 
-    table_name = (char *) malloc(sizeof(char) * TABLE_NAME_SIZE);
-    if (!msSplitData(layer->data, &geom_column_name, &table_name, &unique, &srid, &function, &version))
-    {
-        msSetError( MS_ORACLESPATIALERR, 
-                    "Error parsing OracleSpatial DATA variable. Must be: "
-                    "'geometry_column FROM table_name [USING UNIQUE <column> SRID srid# FUNCTION]' or "
-                    "'geometry_column FROM (SELECT stmt) [USING UNIQUE <column> SRID srid# FUNCTION]'. "
-                    "If want to set the FUNCTION statement you can use: FILTER, RELATE, GEOMRELATE or NONE. "
-                    "Your data statement: %s", 
-                    "msOracleSpatialLayerGetItems()", layer->data );
+  if (layer->debug)
+    msDebug("msOracleSpatialLayerGetItems was called.\n");
+
+  if (layerinfo == NULL) {
+    msSetError( MS_ORACLESPATIALERR, "msOracleSpatialLayerGetItems called on unopened layer", "msOracleSpatialLayerGetItems()" );
+    return MS_FAILURE;
+  } else {
+    dthand = (msOracleSpatialDataHandler *)layerinfo->oradatahandlers;
+    hand = (msOracleSpatialHandler *)layerinfo->orahandlers;
+    sthand = (msOracleSpatialStatement *) layerinfo->orastmt;
+  }
+
+  /* Will we want to capture the field details? */
+  if((value = msOWSLookupMetadata(&(layer->metadata), "G", "types")) != NULL
+      && strcasecmp(value,"auto") == 0 )
+    get_field_details = 1;
+
+  table_name = (char *) malloc(sizeof(char) * TABLE_NAME_SIZE);
+  if (!msSplitData(layer->data, &geom_column_name, &table_name, &unique, &srid, &function, &version)) {
+    msSetError( MS_ORACLESPATIALERR,
+                "Error parsing OracleSpatial DATA variable. Must be: "
+                "'geometry_column FROM table_name [USING UNIQUE <column> SRID srid# FUNCTION]' or "
+                "'geometry_column FROM (SELECT stmt) [USING UNIQUE <column> SRID srid# FUNCTION]'. "
+                "If want to set the FUNCTION statement you can use: FILTER, RELATE, GEOMRELATE or NONE. "
+                "Your data statement: %s",
+                "msOracleSpatialLayerGetItems()", layer->data );
 
-        if (geom_column_name) free(geom_column_name);
-        if (srid) free(srid);
-        if (unique) free(unique);
-        free(table_name);
-        return MS_FAILURE;
-    }
+    if (geom_column_name) free(geom_column_name);
+    if (srid) free(srid);
+    if (unique) free(unique);
+    free(table_name);
+    return MS_FAILURE;
+  }
 
-    snprintf( query_str, sizeof(query_str), "SELECT * FROM %s", table_name ); 
+  snprintf( query_str, sizeof(query_str), "SELECT * FROM %s", table_name );
 
-    success =  TRY( hand, OCIStmtPrepare( sthand->stmthp, hand->errhp, (text *)query_str, (ub4)strlen(query_str), (ub4)OCI_NTV_SYNTAX, (ub4)OCI_DESCRIBE_ONLY) )
-            && TRY( hand, OCIStmtExecute( hand->svchp, sthand->stmthp, hand->errhp, (ub4)QUERY_SIZE, (ub4)0, (OCISnapshot *)NULL, (OCISnapshot *)NULL, (ub4)OCI_DESCRIBE_ONLY ) )
-            && TRY( hand, OCIAttrGet( (dvoid *)sthand->stmthp, (ub4)OCI_HTYPE_STMT, (dvoid *)&layer->numitems, (ub4 *)0, OCI_ATTR_PARAM_COUNT, hand->errhp) );
-            
-            
-            
+  success =  TRY( hand, OCIStmtPrepare( sthand->stmthp, hand->errhp, (text *)query_str, (ub4)strlen(query_str), (ub4)OCI_NTV_SYNTAX, (ub4)OCI_DESCRIBE_ONLY) )
+             && TRY( hand, OCIStmtExecute( hand->svchp, sthand->stmthp, hand->errhp, (ub4)QUERY_SIZE, (ub4)0, (OCISnapshot *)NULL, (OCISnapshot *)NULL, (ub4)OCI_DESCRIBE_ONLY ) )
+             && TRY( hand, OCIAttrGet( (dvoid *)sthand->stmthp, (ub4)OCI_HTYPE_STMT, (dvoid *)&layer->numitems, (ub4 *)0, OCI_ATTR_PARAM_COUNT, hand->errhp) );
 
-    if (!success)
-    {
-        msSetError( MS_QUERYERR, "Cannot retrieve column list", "msOracleSpatialLayerGetItems()" );
-        if (geom_column_name) free(geom_column_name);
-        if (srid) free(srid);
-        if (unique) free(unique);
-        free(table_name);
-        return MS_FAILURE;
-    }
 
-    sthand->row_num = sthand->row = 0;
-    layer->numitems = layer->numitems-1;
 
-    layer->items = malloc (sizeof(char *) * (layer->numitems));
-    if (layer->items == NULL)
-    {
-        msSetError( MS_ORACLESPATIALERR,"Cannot allocate items", "msOracleSpatialLayerGetItems()" );
-        if (geom_column_name) free(geom_column_name);
-        if (srid) free(srid);
-        if (unique) free(unique);
-        free(table_name);
-        return MS_FAILURE;
-    }
 
-    if (layer->numitems > 0)
-    {
-        if (sthand->items_query == NULL)
-            sthand->items_query = (item_text_array_query *)malloc( sizeof(item_text_array_query) * (layer->numitems) );
+  if (!success) {
+    msSetError( MS_QUERYERR, "Cannot retrieve column list", "msOracleSpatialLayerGetItems()" );
+    if (geom_column_name) free(geom_column_name);
+    if (srid) free(srid);
+    if (unique) free(unique);
+    free(table_name);
+    return MS_FAILURE;
+  }
 
-        if (sthand->items_query == NULL)
-        {
-            msSetError( MS_ORACLESPATIALERR,"Cannot allocate items buffer", "msOracleSpatialLayerGetItems()" );
-            if (geom_column_name) free(geom_column_name);
-            if (srid) free(srid);
-            if (unique) free(unique);
-            free(table_name);
-            return MS_FAILURE;
-        }
-    }
+  sthand->row_num = sthand->row = 0;
+  layer->numitems = layer->numitems-1;
 
-    count_item = 0;
-    existgeom = 0;
-
-    /*Upcase conversion for the geom_column_name*/
-    for (i=0; geom_column_name[i] != '\0'; i++)
-        geom_column_name[i] = toupper(geom_column_name[i]);
-
-    /*Retrive columns name from the user table*/
-    for (i = 0; i <= layer->numitems; i++)
-    {
-         
-        success = TRY( hand, OCIParamGet ((dvoid*) sthand->stmthp, (ub4)OCI_HTYPE_STMT,hand->errhp,(dvoid*)&pard, (ub4)i+1))
-               && TRY( hand, OCIAttrGet ((dvoid *) pard,(ub4) OCI_DTYPE_PARAM,(dvoid*)&rzttype,(ub4 *)0, (ub4) OCI_ATTR_DATA_TYPE, hand->errhp ))
-               && TRY( hand, OCIParamGet ((dvoid*) sthand->stmthp, (ub4)OCI_HTYPE_STMT,hand->errhp,(dvoid*)&pard, (ub4)i+1))
-               && TRY( hand, OCIAttrGet ((dvoid *) pard,(ub4) OCI_DTYPE_PARAM,(dvoid*)&rzt,(ub4 *)&flk_len, (ub4) OCI_ATTR_NAME, hand->errhp ));
-              
-       /*   if (layer->debug)
-               msDebug("msOracleSpatialLayerGetItems checking type. Column = %s Type = %d\n", rzt, rzttype);  */    
-                      
-        flk = (char *)malloc(sizeof(char*) * flk_len+1);
-        if (flk == NULL)
-        {
-            msSetError( MS_ORACLESPATIALERR, "No memory avaliable to allocate the items", "msOracleSpatialLayerGetItems()" );
-            if (geom_column_name) free(geom_column_name);
-            if (srid) free(srid);
-            if (unique) free(unique);
-            free(table_name);
-            return MS_FAILURE;
-        }
-        else
-        {
-            strlcpy(flk, rzt, flk_len+1);
-        }
- 
-        /*Comapre the column name (flk) with geom_column_name and ignore with true*/
-        if (strcmp(flk, geom_column_name) != 0)
-        {    
-            if (rzttype!=OCI_TYPECODE_BLOB) 
-            {
-                layer->items[count_item] = (char *)malloc(sizeof(char) * flk_len+1);
-                if (layer->items[count_item] == NULL)
-                {
-                    msSetError( MS_ORACLESPATIALERR, "No memory avaliable to allocate the items buffer", "msOracleSpatialLayerGetItems()" );
-                    if (geom_column_name) free(geom_column_name);
-                    if (srid) free(srid);
-                    if (unique) free(unique);
-                    free(table_name);
-                    return MS_FAILURE;
-                }
-                
-                strcpy(layer->items[count_item], flk); 
-                count_item++;
-
-                if( get_field_details )
-                    msOracleSpatialGetFieldDefn( layer, hand, 
-                                                 layer->items[count_item-1], 
-                                                 pard );
-            }
-        }
-        else
-            existgeom = 1;
-     
-        strcpy( rzt, "" );
-        free(flk); /* Better?!*/
-        flk_len = 0;
-    }
+  layer->items = malloc (sizeof(char *) * (layer->numitems));
+  if (layer->items == NULL) {
+    msSetError( MS_ORACLESPATIALERR,"Cannot allocate items", "msOracleSpatialLayerGetItems()" );
+    if (geom_column_name) free(geom_column_name);
+    if (srid) free(srid);
+    if (unique) free(unique);
+    free(table_name);
+    return MS_FAILURE;
+  }
+
+  if (layer->numitems > 0) {
+    if (sthand->items_query == NULL)
+      sthand->items_query = (item_text_array_query *)malloc( sizeof(item_text_array_query) * (layer->numitems) );
+
+    if (sthand->items_query == NULL) {
+      msSetError( MS_ORACLESPATIALERR,"Cannot allocate items buffer", "msOracleSpatialLayerGetItems()" );
+      if (geom_column_name) free(geom_column_name);
+      if (srid) free(srid);
+      if (unique) free(unique);
+      free(table_name);
+      return MS_FAILURE;
+    }
+  }
+
+  count_item = 0;
+  existgeom = 0;
+
+  /*Upcase conversion for the geom_column_name*/
+  for (i=0; geom_column_name[i] != '\0'; i++)
+    geom_column_name[i] = toupper(geom_column_name[i]);
+
+  /*Retrive columns name from the user table*/
+  for (i = 0; i <= layer->numitems; i++) {
+
+    success = TRY( hand, OCIParamGet ((dvoid*) sthand->stmthp, (ub4)OCI_HTYPE_STMT,hand->errhp,(dvoid*)&pard, (ub4)i+1))
+              && TRY( hand, OCIAttrGet ((dvoid *) pard,(ub4) OCI_DTYPE_PARAM,(dvoid*)&rzttype,(ub4 *)0, (ub4) OCI_ATTR_DATA_TYPE, hand->errhp ))
+              && TRY( hand, OCIParamGet ((dvoid*) sthand->stmthp, (ub4)OCI_HTYPE_STMT,hand->errhp,(dvoid*)&pard, (ub4)i+1))
+              && TRY( hand, OCIAttrGet ((dvoid *) pard,(ub4) OCI_DTYPE_PARAM,(dvoid*)&rzt,(ub4 *)&flk_len, (ub4) OCI_ATTR_NAME, hand->errhp ));
+
+    /*   if (layer->debug)
+            msDebug("msOracleSpatialLayerGetItems checking type. Column = %s Type = %d\n", rzt, rzttype);  */
+
+    flk = (char *)malloc(sizeof(char*) * flk_len+1);
+    if (flk == NULL) {
+      msSetError( MS_ORACLESPATIALERR, "No memory avaliable to allocate the items", "msOracleSpatialLayerGetItems()" );
+      if (geom_column_name) free(geom_column_name);
+      if (srid) free(srid);
+      if (unique) free(unique);
+      free(table_name);
+      return MS_FAILURE;
+    } else {
+      strlcpy(flk, rzt, flk_len+1);
+    }
+
+    /*Comapre the column name (flk) with geom_column_name and ignore with true*/
+    if (strcmp(flk, geom_column_name) != 0) {
+      if (rzttype!=OCI_TYPECODE_BLOB) {
+        layer->items[count_item] = (char *)malloc(sizeof(char) * flk_len+1);
+        if (layer->items[count_item] == NULL) {
+          msSetError( MS_ORACLESPATIALERR, "No memory avaliable to allocate the items buffer", "msOracleSpatialLayerGetItems()" );
+          if (geom_column_name) free(geom_column_name);
+          if (srid) free(srid);
+          if (unique) free(unique);
+          free(table_name);
+          return MS_FAILURE;
+        }
+
+        strcpy(layer->items[count_item], flk);
+        count_item++;
+
+        if( get_field_details )
+          msOracleSpatialGetFieldDefn( layer, hand,
+                                       layer->items[count_item-1],
+                                       pard );
+      }
+    } else
+      existgeom = 1;
 
-    layer->numitems = count_item;
+    strcpy( rzt, "" );
+    free(flk); /* Better?!*/
+    flk_len = 0;
+  }
 
-    if (!(existgeom))
-    {
-        msSetError (MS_ORACLESPATIALERR, "No geometry column, check stmt", "msOracleSpatialLayerGetItems()" );
-        if (geom_column_name) free(geom_column_name);
-        if (srid) free(srid);
-        if (unique) free(unique);
-        free(table_name);
-        return MS_FAILURE;
-    }
+  layer->numitems = count_item;
 
+  if (!(existgeom)) {
+    msSetError (MS_ORACLESPATIALERR, "No geometry column, check stmt", "msOracleSpatialLayerGetItems()" );
     if (geom_column_name) free(geom_column_name);
     if (srid) free(srid);
     if (unique) free(unique);
     free(table_name);
-    return msOracleSpatialLayerInitItemInfo( layer );
+    return MS_FAILURE;
+  }
+
+  if (geom_column_name) free(geom_column_name);
+  if (srid) free(srid);
+  if (unique) free(unique);
+  free(table_name);
+  return msOracleSpatialLayerInitItemInfo( layer );
 }
 
 int msOracleSpatialLayerGetExtent(layerObj *layer, rectObj *extent)
 {
-    char *table_name;
-    char query_str[6000], *geom_column_name = NULL, *unique = NULL, *srid = NULL;
-    int success, i;
-    int function = 0;
-    int version = 0;
-    SDOGeometryObj *obj = NULL;
-    SDOGeometryInd *ind = NULL;
-    shapeObj shape;
-    rectObj bounds;
-    /*OCIDefine *adtp = NULL, *items[QUERY_SIZE] = { NULL };*/
-    OCIDefine *adtp = NULL;
-    OCIDefine **items = NULL;
+  char *table_name;
+  char query_str[6000], *geom_column_name = NULL, *unique = NULL, *srid = NULL;
+  int success, i;
+  int function = 0;
+  int version = 0;
+  SDOGeometryObj *obj = NULL;
+  SDOGeometryInd *ind = NULL;
+  shapeObj shape;
+  rectObj bounds;
+  /*OCIDefine *adtp = NULL, *items[QUERY_SIZE] = { NULL };*/
+  OCIDefine *adtp = NULL;
+  OCIDefine **items = NULL;
+
+  msOracleSpatialLayerInfo *layerinfo = (msOracleSpatialLayerInfo *)layer->layerinfo;
+  msOracleSpatialDataHandler *dthand = NULL;
+  msOracleSpatialHandler *hand = NULL;
+  msOracleSpatialStatement *sthand = NULL;
 
-    msOracleSpatialLayerInfo *layerinfo = (msOracleSpatialLayerInfo *)layer->layerinfo;
-    msOracleSpatialDataHandler *dthand = NULL;
-    msOracleSpatialHandler *hand = NULL;
-    msOracleSpatialStatement *sthand = NULL;
+  if (layer->debug)
+    msDebug("msOracleSpatialLayerGetExtent was called.\n");
+
+  if (layerinfo == NULL) {
+    msSetError( MS_ORACLESPATIALERR, "msOracleSpatialLayerGetExtent called on unopened layer","msOracleSpatialLayerGetExtent()");
+    return MS_FAILURE;
+  } else {
+    dthand = (msOracleSpatialDataHandler *)layerinfo->oradatahandlers;
+    hand = (msOracleSpatialHandler *)layerinfo->orahandlers;
+    sthand = (msOracleSpatialStatement *) layerinfo->orastmt;
+  }
+
+  /* allocate enough space for items */
+  if (layer->numitems > 0) {
+    sthand->items_query = (item_text_array_query *)malloc( sizeof(item_text_array_query) * (layer->numitems) );
+    if (sthand->items_query == NULL) {
+      msSetError( MS_ORACLESPATIALERR, "Cannot allocate layerinfo->items buffer", "msOracleSpatialLayerGetExtent()" );
+      return MS_FAILURE;
+    }
+    items = (OCIDefine **)malloc(sizeof(OCIDefine *)*layer->numitems);
+    if (items == NULL) {
+      msSetError( MS_ORACLESPATIALERR,"Cannot allocate items buffer","msOracleSpatialLayerWhichShapes()" );
+      return MS_FAILURE;
+    }
+    memset(items ,0,sizeof(OCIDefine *)*layer->numitems);
+  }
+
+  table_name = (char *) malloc(sizeof(char) * TABLE_NAME_SIZE);
+  if (!msSplitData( layer->data, &geom_column_name, &table_name, &unique, &srid, &function, &version )) {
+    msSetError( MS_ORACLESPATIALERR,
+                "Error parsing OracleSpatial DATA variable. Must be: "
+                "'geometry_column FROM table_name [USING UNIQUE <column> SRID srid# FUNCTION]' or "
+                "'geometry_column FROM (SELECT stmt) [USING UNIQUE <column> SRID srid# FUNCTION]'. "
+                "If want to set the FUNCTION statement you can use: FILTER, RELATE, GEOMRELATE or NONE. "
+                "Your data statement: %s",
+                "msOracleSpatialLayerGetExtent()", layer->data );
+    /* clean items */
+    free(items);
 
-    if (layer->debug)
-        msDebug("msOracleSpatialLayerGetExtent was called.\n");
+    if (geom_column_name) free(geom_column_name);
+    if (srid) free(srid);
+    if (unique) free(unique);
+    free(table_name);
 
-    if (layerinfo == NULL)
-    {
-        msSetError( MS_ORACLESPATIALERR, "msOracleSpatialLayerGetExtent called on unopened layer","msOracleSpatialLayerGetExtent()");
-        return MS_FAILURE;
-    }
-    else
-    {
-        dthand = (msOracleSpatialDataHandler *)layerinfo->oradatahandlers;
-        hand = (msOracleSpatialHandler *)layerinfo->orahandlers;
-        sthand = (msOracleSpatialStatement *) layerinfo->orastmt;
-    }
+    return MS_FAILURE;
+  }
 
-    /* allocate enough space for items */
-    if (layer->numitems > 0)
-    {
-        sthand->items_query = (item_text_array_query *)malloc( sizeof(item_text_array_query) * (layer->numitems) );
-        if (sthand->items_query == NULL)
-        {
-            msSetError( MS_ORACLESPATIALERR, "Cannot allocate layerinfo->items buffer", "msOracleSpatialLayerGetExtent()" );
-            return MS_FAILURE;
-        }
-        items = (OCIDefine **)malloc(sizeof(OCIDefine *)*layer->numitems);
-        if (items == NULL)
-        {
-            msSetError( MS_ORACLESPATIALERR,"Cannot allocate items buffer","msOracleSpatialLayerWhichShapes()" );
-            return MS_FAILURE;
-        }
-        memset(items ,0,sizeof(OCIDefine *)*layer->numitems);
-    }
+  if (version == VERSION_10g)
+    osAggrGetExtent(layer, query_str, sizeof(query_str), geom_column_name, table_name);
+  else {
+    if (((atol(srid) < 8192) || (atol(srid) > 8330)) && (atol(srid) != 2) && (atol(srid) != 5242888) && (atol(srid) != 2000001)) {
+      if (version == VERSION_9i)
+        osAggrGetExtent(layer, query_str, sizeof(query_str), geom_column_name, table_name);
+      else
+        osConvexHullGetExtent(layer, query_str, sizeof(query_str), geom_column_name, table_name);
+    } else
+      osConvexHullGetExtent(layer, query_str, sizeof(query_str), geom_column_name, table_name);
+  }
 
-    table_name = (char *) malloc(sizeof(char) * TABLE_NAME_SIZE);
-    if (!msSplitData( layer->data, &geom_column_name, &table_name, &unique, &srid, &function, &version )) 
-    {
-        msSetError( MS_ORACLESPATIALERR, 
-                    "Error parsing OracleSpatial DATA variable. Must be: "
-                    "'geometry_column FROM table_name [USING UNIQUE <column> SRID srid# FUNCTION]' or "
-                    "'geometry_column FROM (SELECT stmt) [USING UNIQUE <column> SRID srid# FUNCTION]'. "
-                    "If want to set the FUNCTION statement you can use: FILTER, RELATE, GEOMRELATE or NONE. "
-                    "Your data statement: %s", 
-                    "msOracleSpatialLayerGetExtent()", layer->data );
-        /* clean items */
-        free(items);
+  if (layer->debug)
+    msDebug("msOracleSpatialLayerGetExtent. Using this Sql to retrieve the extent: %s.\n", query_str);
 
-        if (geom_column_name) free(geom_column_name);
-        if (srid) free(srid);
-        if (unique) free(unique);
-        free(table_name);
+  /*Prepare the handlers to the query*/
+  success = TRY( hand,OCIStmtPrepare( sthand->stmthp, hand->errhp, (text *)query_str, (ub4)strlen(query_str), (ub4)OCI_NTV_SYNTAX, (ub4)OCI_DEFAULT) );
 
-        return MS_FAILURE;
-    }
+  if (success && layer->numitems > 0) {
+    for( i = 0; i < layer->numitems && success; ++i )
+      success = TRY( hand, OCIDefineByPos( sthand->stmthp, &items[i], hand->errhp, (ub4)i+1, (dvoid *)sthand->items_query[i], (sb4)TEXT_SIZE, SQLT_STR, (dvoid *)0, (ub2 *)0, (ub2 *)0, (ub4)OCI_DEFAULT ) );
+  }
 
-    if (version == VERSION_10g)
-        osAggrGetExtent(layer, query_str, sizeof(query_str), geom_column_name, table_name);
-    else
-    {
-        if (((atol(srid) < 8192) || (atol(srid) > 8330)) && (atol(srid) != 2) && (atol(srid) != 5242888) && (atol(srid) != 2000001))
-        {
-            if (version == VERSION_9i)
-                osAggrGetExtent(layer, query_str, sizeof(query_str), geom_column_name, table_name);
-            else
-                osConvexHullGetExtent(layer, query_str, sizeof(query_str), geom_column_name, table_name);
-        }
-        else
-            osConvexHullGetExtent(layer, query_str, sizeof(query_str), geom_column_name, table_name);
-    }
+  if(!success) {
+    msSetError( MS_ORACLESPATIALERR,
+                "Error: %s . "
+                "Query statement: %s . "
+                "Check your data statement.",
+                "msOracleSpatialLayerGetExtent()", hand->last_oci_error, query_str );
 
-    if (layer->debug)
-        msDebug("msOracleSpatialLayerGetExtent. Using this Sql to retrieve the extent: %s.\n", query_str);
+    /* clean items */
+    free(items);
 
-    /*Prepare the handlers to the query*/
-    success = TRY( hand,OCIStmtPrepare( sthand->stmthp, hand->errhp, (text *)query_str, (ub4)strlen(query_str), (ub4)OCI_NTV_SYNTAX, (ub4)OCI_DEFAULT) );
+    if (geom_column_name) free(geom_column_name);
+    if (srid) free(srid);
+    if (unique) free(unique);
+    free(table_name);
 
-    if (success && layer->numitems > 0)
-    {
-        for( i = 0; i < layer->numitems && success; ++i )
-            success = TRY( hand, OCIDefineByPos( sthand->stmthp, &items[i], hand->errhp, (ub4)i+1, (dvoid *)sthand->items_query[i], (sb4)TEXT_SIZE, SQLT_STR, (dvoid *)0, (ub2 *)0, (ub2 *)0, (ub4)OCI_DEFAULT ) );
-    }
+    return MS_FAILURE;
+  }
 
-    if(!success)
-    {
-        msSetError( MS_ORACLESPATIALERR,
-                    "Error: %s . "
-                    "Query statement: %s . "
-                    "Check your data statement.",
-                    "msOracleSpatialLayerGetExtent()", hand->last_oci_error, query_str );
+  if (success) {
+    success = TRY( hand, OCIDefineByPos( sthand->stmthp, &adtp, hand->errhp, (ub4)layer->numitems+1, (dvoid *)0, (sb4)0, SQLT_NTY, (dvoid *)0, (ub2 *)0, (ub2 *)0, (ub4)OCI_DEFAULT) )
+              && TRY( hand, OCIDefineObject( adtp, hand->errhp, dthand->tdo, (dvoid **)sthand->obj, (ub4 *)0, (dvoid **)sthand->ind, (ub4 *)0 ) )
+              && TRY (hand, OCIStmtExecute( hand->svchp, sthand->stmthp, hand->errhp, (ub4)QUERY_SIZE, (ub4)0, (OCISnapshot *)NULL, (OCISnapshot *)NULL, (ub4)OCI_DEFAULT ))
+              && TRY (hand, OCIAttrGet( (dvoid *)sthand->stmthp, (ub4)OCI_HTYPE_STMT, (dvoid *)&sthand->rows_fetched, (ub4 *)0, (ub4)OCI_ATTR_ROW_COUNT, hand->errhp ));
 
-        /* clean items */
-        free(items);
+  }
 
-        if (geom_column_name) free(geom_column_name);
-        if (srid) free(srid);
-        if (unique) free(unique);
-        free(table_name);
+  if(!success) {
+    msSetError( MS_ORACLESPATIALERR,
+                "Error: %s . "
+                "Query statement: %s ."
+                "Check your data statement.",
+                "msOracleSpatialLayerGetExtent()", hand->last_oci_error, query_str );
 
-        return MS_FAILURE;
+    /* clean items */
+    free(items);
+
+    if (geom_column_name) free(geom_column_name);
+    if (srid) free(srid);
+    if (unique) free(unique);
+    free(table_name);
+
+    return MS_FAILURE;
+  }
+
+  /* should begin processing first row */
+  sthand->row_num = sthand->row = 0;
+  msInitShape( &shape );
+  do {
+    /* is buffer empty? */
+    if (sthand->row_num >= sthand->rows_fetched) {
+      /* fetch more */
+      success = TRY( hand, OCIStmtFetch( sthand->stmthp, hand->errhp, (ub4)ARRAY_SIZE, (ub2)OCI_FETCH_NEXT, (ub4)OCI_DEFAULT ) )
+                && TRY( hand, OCIAttrGet( (dvoid *)sthand->stmthp, (ub4)OCI_HTYPE_STMT, (dvoid *)&sthand->rows_fetched, (ub4 *)0, (ub4)OCI_ATTR_ROW_COUNT, hand->errhp ) );
+
+      if (!success || sthand->rows_fetched == 0)
+        break;
+
+      if (sthand->row_num >= sthand->rows_fetched)
+        break;
+
+      sthand->row = 0; /* reset row index */
     }
 
-    if (success)
-    {
-        success = TRY( hand, OCIDefineByPos( sthand->stmthp, &adtp, hand->errhp, (ub4)layer->numitems+1, (dvoid *)0, (sb4)0, SQLT_NTY, (dvoid *)0, (ub2 *)0, (ub2 *)0, (ub4)OCI_DEFAULT) )
-               && TRY( hand, OCIDefineObject( adtp, hand->errhp, dthand->tdo, (dvoid **)sthand->obj, (ub4 *)0, (dvoid **)sthand->ind, (ub4 *)0 ) )
-               && TRY (hand, OCIStmtExecute( hand->svchp, sthand->stmthp, hand->errhp, (ub4)QUERY_SIZE, (ub4)0, (OCISnapshot *)NULL, (OCISnapshot *)NULL, (ub4)OCI_DEFAULT ))
-               && TRY (hand, OCIAttrGet( (dvoid *)sthand->stmthp, (ub4)OCI_HTYPE_STMT, (dvoid *)&sthand->rows_fetched, (ub4 *)0, (ub4)OCI_ATTR_ROW_COUNT, hand->errhp ));
+    /* no rows fetched */
+    if (sthand->rows_fetched == 0)
+      break;
+
+    obj = sthand->obj[ sthand->row ];
+    ind = sthand->ind[ sthand->row ];
 
+    /* get the items for the shape */
+    shape.numvalues = layer->numitems;
+    shape.values = (char **) malloc(sizeof(char *) * layer->numitems);
+    if (shape.values == NULL) {
+      msSetError( MS_ORACLESPATIALERR, "No memory avaliable to allocate the values.", "msOracleSpatialLayerGetExtent()" );
+      if (geom_column_name) free(geom_column_name);
+      if (srid) free(srid);
+      if (unique) free(unique);
+      free(table_name);
+      return MS_FAILURE;
     }
 
-    if(!success)
-    {
-        msSetError( MS_ORACLESPATIALERR, 
-                    "Error: %s . "
-                    "Query statement: %s ."
-                    "Check your data statement.",
-                    "msOracleSpatialLayerGetExtent()", hand->last_oci_error, query_str );
+    shape.index = sthand->row_num;
+
+    for( i = 0; i < layer->numitems; ++i ) {
+      shape.values[i] = (char *)malloc(strlen((char *)sthand->items_query[sthand->row][i])+1);
+
+      if (shape.values[i] == NULL) {
+        msSetError( MS_ORACLESPATIALERR, "No memory avaliable to allocate the items buffer.", "msOracleSpatialLayerGetExtent()" );
 
         /* clean items */
         free(items);
@@ -3367,137 +3201,107 @@ int msOracleSpatialLayerGetExtent(layerObj *layer, rectObj *extent)
         free(table_name);
 
         return MS_FAILURE;
+      } else {
+        strcpy(shape.values[i], (char *)sthand->items_query[sthand->row][i]);
+        shape.values[i][strlen((char *)sthand->items_query[sthand->row][i])] = '\0';
+      }
     }
 
-    /* should begin processing first row */
-    sthand->row_num = sthand->row = 0;
-    msInitShape( &shape );
-    do{
-        /* is buffer empty? */
-        if (sthand->row_num >= sthand->rows_fetched) 
-        {
-            /* fetch more */
-            success = TRY( hand, OCIStmtFetch( sthand->stmthp, hand->errhp, (ub4)ARRAY_SIZE, (ub2)OCI_FETCH_NEXT, (ub4)OCI_DEFAULT ) ) 
-                   && TRY( hand, OCIAttrGet( (dvoid *)sthand->stmthp, (ub4)OCI_HTYPE_STMT, (dvoid *)&sthand->rows_fetched, (ub4 *)0, (ub4)OCI_ATTR_ROW_COUNT, hand->errhp ) );
-
-            if (!success || sthand->rows_fetched == 0)
-                break;
+    /* increment for next row */
+    sthand->row_num++;
+    sthand->row++;
 
-            if (sthand->row_num >= sthand->rows_fetched)
-                break;
+    /* fetch a layer->type object */
+    success = osGetOrdinates(dthand, hand, &shape, obj, ind);
+    if (success != MS_SUCCESS) {
+      msSetError( MS_ORACLESPATIALERR, "Cannot execute query", "msOracleSpatialLayerGetExtent()" );
 
-            sthand->row = 0; /* reset row index */
-        }
-
-        /* no rows fetched */
-        if (sthand->rows_fetched == 0)
-            break;
-
-        obj = sthand->obj[ sthand->row ];
-        ind = sthand->ind[ sthand->row ];
-
-        /* get the items for the shape */
-        shape.numvalues = layer->numitems;
-        shape.values = (char **) malloc(sizeof(char *) * layer->numitems);
-        if (shape.values == NULL)
-        {
-            msSetError( MS_ORACLESPATIALERR, "No memory avaliable to allocate the values.", "msOracleSpatialLayerGetExtent()" );
-            if (geom_column_name) free(geom_column_name);
-            if (srid) free(srid);
-            if (unique) free(unique);
-            free(table_name);
-            return MS_FAILURE;
-        }
+      /* clean items */
+      free(items);
 
-        shape.index = sthand->row_num;
+      if (geom_column_name) free(geom_column_name);
+      if (srid) free(srid);
+      if (unique) free(unique);
+      free(table_name);
 
-        for( i = 0; i < layer->numitems; ++i )
-        {
-            shape.values[i] = (char *)malloc(strlen((char *)sthand->items_query[sthand->row][i])+1);
+      return MS_FAILURE;
+    }
 
-            if (shape.values[i] == NULL)
-            {
-                msSetError( MS_ORACLESPATIALERR, "No memory avaliable to allocate the items buffer.", "msOracleSpatialLayerGetExtent()" );
+  } while(sthand->row <= sthand->rows_fetched);
 
-                /* clean items */
-                free(items);
+  sthand->row = sthand->row_num = 0;
 
-                if (geom_column_name) free(geom_column_name);
-                if (srid) free(srid);
-                if (unique) free(unique);
-                free(table_name);
+  osShapeBounds(&shape);
+  bounds = shape.bounds;
 
-                return MS_FAILURE;
-            }
-            else
-            {
-                strcpy(shape.values[i], (char *)sthand->items_query[sthand->row][i]);
-                shape.values[i][strlen((char *)sthand->items_query[sthand->row][i])] = '\0';
-            }
-        }
+  extent->minx = bounds.minx;
+  extent->miny = bounds.miny;
+  extent->maxx = bounds.maxx;
+  extent->maxy = bounds.maxy;
 
-        /* increment for next row */
-        sthand->row_num++;
-        sthand->row++;
+  msFreeShape(&shape);
 
-        /* fetch a layer->type object */ 
-        success = osGetOrdinates(dthand, hand, &shape, obj, ind);
-        if (success != MS_SUCCESS)
-        {
-            msSetError( MS_ORACLESPATIALERR, "Cannot execute query", "msOracleSpatialLayerGetExtent()" );
+  /* clean items */
+  free(items);
 
-            /* clean items */
-            free(items);
+  if (geom_column_name) free(geom_column_name);
+  if (srid) free(srid);
+  if (unique) free(unique);
+  free(table_name);
 
-            if (geom_column_name) free(geom_column_name);
-            if (srid) free(srid);
-            if (unique) free(unique);
-            free(table_name);
+  return(MS_SUCCESS);
+}
 
-            return MS_FAILURE;
-        }
+void msOracleSpatialLayerFreeItemInfo( layerObj *layer )
+{
+  if (layer->debug)
+    msDebug("msOracleSpatialLayerFreeItemInfo was called.\n");
 
-    }while(sthand->row <= sthand->rows_fetched);
+  if (layer->iteminfo)
+    free(layer->iteminfo);
 
-    sthand->row = sthand->row_num = 0;
+  layer->iteminfo = NULL;
+  /* nothing to do */
+}
 
-    osShapeBounds(&shape);
-    bounds = shape.bounds;
+int msOracleSpatialLayerGetAutoStyle( mapObj *map, layerObj *layer, classObj *c, shapeObj *shape )
+{
+  msSetError( MS_ORACLESPATIALERR, "Function not implemented yet", "msLayerGetAutoStyle()" );
+  return MS_FAILURE;
+}
 
-    extent->minx = bounds.minx;
-    extent->miny = bounds.miny;
-    extent->maxx = bounds.maxx;
-    extent->maxy = bounds.maxy;
+int msOracleSpatialGetPaging(layerObj *layer)
+{
+  msOracleSpatialLayerInfo *layerinfo = NULL;
 
-    msFreeShape(&shape);
+  if (layer->debug)
+    msDebug("msOracleSpatialLayerGetPaging was called.\n");
 
-    /* clean items */
-    free(items);
+  if(!msOracleSpatialLayerIsOpen(layer))
+    return MS_TRUE;
 
-    if (geom_column_name) free(geom_column_name);
-    if (srid) free(srid);
-    if (unique) free(unique);
-    free(table_name);
+  assert( layer->layerinfo != NULL);
+  layerinfo = (msOracleSpatialLayerInfo *)layer->layerinfo;
 
-    return(MS_SUCCESS);
+  return layerinfo->paging;
 }
 
-void msOracleSpatialLayerFreeItemInfo( layerObj *layer )
+void msOracleSpatialEnablePaging(layerObj *layer, int value)
 {
-    if (layer->debug)
-        msDebug("msOracleSpatialLayerFreeItemInfo was called.\n");
+  msOracleSpatialLayerInfo *layerinfo = NULL;
 
-    if (layer->iteminfo)
-        free(layer->iteminfo);
+  if (layer->debug)
+    msDebug("msOracleSpatialLayerEnablePaging was called.\n");
 
-    layer->iteminfo = NULL;
-    /* nothing to do */
-}
+  if(!msOracleSpatialLayerIsOpen(layer))
+    msOracleSpatialLayerOpen(layer);
 
-int msOracleSpatialLayerGetAutoStyle( mapObj *map, layerObj *layer, classObj *c, shapeObj *shape )
-{
-    msSetError( MS_ORACLESPATIALERR, "Function not implemented yet", "msLayerGetAutoStyle()" );
-    return MS_FAILURE; 
+  assert( layer->layerinfo != NULL);
+  layerinfo = (msOracleSpatialLayerInfo *)layer->layerinfo;
+
+  layerinfo->paging = value;
+
+  return;
 }
 
 #else
@@ -3568,63 +3372,79 @@ int msOracleSpatialLayerGetAutoStyle( mapObj *map, layerObj *layer, classObj *c,
   return MS_FAILURE;
 }
 
+void msOracleSpatialEnablePaging(layerObj *layer, int value)
+{
+  msSetError( MS_ORACLESPATIALERR, "OracleSpatial is not supported", "msLayerEnablePaging()" );
+  return;
+}
+
+int msOracleSpatialGetPaging(layerObj *layer)
+{
+  msSetError( MS_ORACLESPATIALERR, "OracleSpatial is not supported", "msLayerGetPaging()" );
+  return MS_FAILURE;
+}
+
 #endif
 
-#ifdef USE_ORACLE_PLUGIN 
+#ifdef USE_ORACLE_PLUGIN
 #ifdef USE_ORACLESPATIAL
 MS_DLL_EXPORT  int
 PluginInitializeVirtualTable(layerVTableObj* vtable, layerObj *layer)
 {
-    assert(layer != NULL);
-    assert(vtable != NULL);
-    
-
-    vtable->LayerInitItemInfo = msOracleSpatialLayerInitItemInfo;
-    vtable->LayerFreeItemInfo = msOracleSpatialLayerFreeItemInfo;
-    vtable->LayerOpen = msOracleSpatialLayerOpen;
-    vtable->LayerIsOpen = msOracleSpatialLayerIsOpen;
-    vtable->LayerWhichShapes = msOracleSpatialLayerWhichShapes;
-    vtable->LayerNextShape = msOracleSpatialLayerNextShape;
-    vtable->LayerGetShape = msOracleSpatialLayerGetShape;
-    vtable->LayerClose = msOracleSpatialLayerClose;
-    vtable->LayerGetItems = msOracleSpatialLayerGetItems;
-    vtable->LayerGetExtent = msOracleSpatialLayerGetExtent;
-    /* layer->vtable->LayerGetAutoStyle, use default */
-    /* layer->vtable->LayerApplyFilterToLayer, use default */
-    vtable->LayerCloseConnection = msOracleSpatialLayerClose;
-    vtable->LayerApplyFilterToLayer = msLayerApplyCondSQLFilterToLayer;
-    vtable->LayerSetTimeFilter = msLayerMakePlainTimeFilter;
-    /* layer->vtable->LayerGetNumFeatures, use default */
-    /* layer->vtable->LayerGetAutoProjection = msOracleSpatialLayerGetAutoProjection; Disabled until tested */
-
-    return MS_SUCCESS;
+  assert(layer != NULL);
+  assert(vtable != NULL);
+
+
+  vtable->LayerInitItemInfo = msOracleSpatialLayerInitItemInfo;
+  vtable->LayerFreeItemInfo = msOracleSpatialLayerFreeItemInfo;
+  vtable->LayerOpen = msOracleSpatialLayerOpen;
+  vtable->LayerIsOpen = msOracleSpatialLayerIsOpen;
+  vtable->LayerWhichShapes = msOracleSpatialLayerWhichShapes;
+  vtable->LayerNextShape = msOracleSpatialLayerNextShape;
+  vtable->LayerGetShape = msOracleSpatialLayerGetShape;
+  vtable->LayerClose = msOracleSpatialLayerClose;
+  vtable->LayerGetItems = msOracleSpatialLayerGetItems;
+  vtable->LayerGetExtent = msOracleSpatialLayerGetExtent;
+  /* layer->vtable->LayerGetAutoStyle, use default */
+  /* layer->vtable->LayerApplyFilterToLayer, use default */
+  vtable->LayerCloseConnection = msOracleSpatialLayerClose;
+  vtable->LayerApplyFilterToLayer = msLayerApplyCondSQLFilterToLayer;
+  vtable->LayerSetTimeFilter = msLayerMakePlainTimeFilter;
+  /* layer->vtable->LayerGetNumFeatures, use default */
+  /* layer->vtable->LayerGetAutoProjection = msOracleSpatialLayerGetAutoProjection; Disabled until tested */
+  vtable->LayerEnablePaging = msOracleSpatialEnablePaging;
+  vtable->LayerGetPaging = msOracleSpatialGetPaging;
+
+  return MS_SUCCESS;
 }
 #endif
 #endif
 
 int msOracleSpatialLayerInitializeVirtualTable(layerObj *layer)
 {
-    assert(layer != NULL);
-    assert(layer->vtable != NULL);
-
-    layer->vtable->LayerInitItemInfo = msOracleSpatialLayerInitItemInfo;
-    layer->vtable->LayerFreeItemInfo = msOracleSpatialLayerFreeItemInfo;
-    layer->vtable->LayerOpen = msOracleSpatialLayerOpen;
-    layer->vtable->LayerIsOpen = msOracleSpatialLayerIsOpen;
-    layer->vtable->LayerWhichShapes = msOracleSpatialLayerWhichShapes;
-    layer->vtable->LayerNextShape = msOracleSpatialLayerNextShape;
-    layer->vtable->LayerGetShape = msOracleSpatialLayerGetShape;
-    layer->vtable->LayerClose = msOracleSpatialLayerClose;
-    layer->vtable->LayerGetItems = msOracleSpatialLayerGetItems;
-    layer->vtable->LayerGetExtent = msOracleSpatialLayerGetExtent;
-    /* layer->vtable->LayerGetAutoStyle, use default */
-    layer->vtable->LayerCloseConnection = msOracleSpatialLayerClose;
-    layer->vtable->LayerApplyFilterToLayer = msLayerApplyCondSQLFilterToLayer;
-    layer->vtable->LayerSetTimeFilter = msLayerMakePlainTimeFilter;
-    /* layer->vtable->LayerCreateItems, use default */
-    /* layer->vtable->LayerGetNumFeatures, use default */
-    /* layer->vtable->LayerGetAutoProjection = msOracleSpatialLayerGetAutoProjection; Disabled until tested */
-
-    return MS_SUCCESS;
+  assert(layer != NULL);
+  assert(layer->vtable != NULL);
+
+  layer->vtable->LayerInitItemInfo = msOracleSpatialLayerInitItemInfo;
+  layer->vtable->LayerFreeItemInfo = msOracleSpatialLayerFreeItemInfo;
+  layer->vtable->LayerOpen = msOracleSpatialLayerOpen;
+  layer->vtable->LayerIsOpen = msOracleSpatialLayerIsOpen;
+  layer->vtable->LayerWhichShapes = msOracleSpatialLayerWhichShapes;
+  layer->vtable->LayerNextShape = msOracleSpatialLayerNextShape;
+  layer->vtable->LayerGetShape = msOracleSpatialLayerGetShape;
+  layer->vtable->LayerClose = msOracleSpatialLayerClose;
+  layer->vtable->LayerGetItems = msOracleSpatialLayerGetItems;
+  layer->vtable->LayerGetExtent = msOracleSpatialLayerGetExtent;
+  /* layer->vtable->LayerGetAutoStyle, use default */
+  layer->vtable->LayerCloseConnection = msOracleSpatialLayerClose;
+  layer->vtable->LayerApplyFilterToLayer = msLayerApplyCondSQLFilterToLayer;
+  layer->vtable->LayerSetTimeFilter = msLayerMakePlainTimeFilter;
+  /* layer->vtable->LayerCreateItems, use default */
+  /* layer->vtable->LayerGetNumFeatures, use default */
+  /* layer->vtable->LayerGetAutoProjection = msOracleSpatialLayerGetAutoProjection; Disabled until tested */
+  layer->vtable->LayerEnablePaging = msOracleSpatialEnablePaging;
+  layer->vtable->LayerGetPaging = msOracleSpatialGetPaging;
+
+  return MS_SUCCESS;
 }
 
diff --git a/mapoutput.c b/mapoutput.c
index 86236c6..de4a8f1 100644
--- a/mapoutput.c
+++ b/mapoutput.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -30,10 +30,10 @@
 #include <assert.h>
 #include "mapserver.h"
 
-MS_CVSID("$Id$")
 
-static outputFormatObj *msAllocOutputFormat( mapObj *map, const char *name, 
-                                             const char *driver );
+
+static outputFormatObj *msAllocOutputFormat( mapObj *map, const char *name,
+    const char *driver );
 
 /*************************************************************************
 
@@ -58,63 +58,65 @@ typedef struct {
             will be derived from the DRIVER or default to the value for
             untyped binary data will be used.  (optional - may be NULL)
 
- DRIVER - This indicates which internal driver mechanism is to be used. 
+ DRIVER - This indicates which internal driver mechanism is to be used.
           Anything prefixed by "GDAL/" will be handled by the GDAL driver, with
           the remainder taken as the GDAL format name. (required)
 
  IMAGEMODE - Has one of "PC256", "RGB", or "RGBA" indicating whether
              the imaging should be done to a 256 pseudo-colored, 24bit RGB, or
-             32bit RGBA (A=alpha/transparency) result image.  Note that the 
-             IMAGEMODE actually affects how all the rendering for the map is 
-             done, long before it is output to a particular output format.  
-             The default value is the traditional "PC256".  Some output 
+             32bit RGBA (A=alpha/transparency) result image.  Note that the
+             IMAGEMODE actually affects how all the rendering for the map is
+             done, long before it is output to a particular output format.
+             The default value is the traditional "PC256".  Some output
              formats can only support some IMAGEMODE values. (optional)
 
-             Translate as MS_IMAGEMODE_PC256, MS_IMAGEMODE_RGB and 
-             MS_IMAGEMODE_RGBA. 
+             Translate as MS_IMAGEMODE_PC256, MS_IMAGEMODE_RGB and
+             MS_IMAGEMODE_RGBA.
 
              Not too sure what this should be set to for output formats like
              flash and SVG.
 
- TRANSPARENT - A value of "ON" or "OFF" indicating whether transparency 
+ TRANSPARENT - A value of "ON" or "OFF" indicating whether transparency
                support should be enabled.  Same as the old TRANSPARENT flag
                at the MAP level.
 
- FORMATOPTION - Contains an argument for the specific driver used.  There may 
-                be any number of format options for a given OUTPUTFORMAT 
+ FORMATOPTION - Contains an argument for the specific driver used.  There may
+                be any number of format options for a given OUTPUTFORMAT
                 declaration.  FORMATOPTION will be used to encode the older
-                INTERLACE, and QUALITY values. 
+                INTERLACE, and QUALITY values.
 
                 Handled as a MapServer style CharArray.
 
  *************************************************************************/
 
 
-struct defaultOutputFormatEntry{
-   const char *name;
-   const char *driver;
-   const char *mimetype;
+struct defaultOutputFormatEntry {
+  const char *name;
+  const char *driver;
+  const char *mimetype;
 } ;
 
 struct defaultOutputFormatEntry defaultoutputformats[] = {
-   {"png","AGG/PNG","image/png"},
-   {"jpeg","AGG/JPEG","image/jpeg"},
-   {"gif","GD/GIF","image/gif"},
-   {"png8","AGG/PNG8","image/png; mode=8bit"},
-   {"png24","AGG/PNG","image/png; mode=24bit"},
+  {"png","AGG/PNG","image/png"},
+  {"jpeg","AGG/JPEG","image/jpeg"},
+#ifdef USE_GD
+  {"gif","GD/GIF","image/gif"},
+#endif
+  {"png8","AGG/PNG8","image/png; mode=8bit"},
+  {"png24","AGG/PNG","image/png; mode=24bit"},
 #ifdef USE_CAIRO
-   {"pdf","CAIRO/PDF","application/x-pdf"},
-   {"svg","CAIRO/SVG","image/svg+xml"},
-   {"cairopng","CAIRO/PNG","image/png"},
+  {"pdf","CAIRO/PDF","application/x-pdf"},
+  {"svg","CAIRO/SVG","image/svg+xml"},
+  {"cairopng","CAIRO/PNG","image/png"},
 #endif
 #ifdef USE_GDAL
-   {"GTiff","GDAL/GTiff","image/tiff"},
+  {"GTiff","GDAL/GTiff","image/tiff"},
 #endif
 #ifdef USE_KML
-   {"kml","KML","application/vnd.google-earth.kml+xml"},
-   {"kmz","KMZ","application/vnd.google-earth.kmz"},
+  {"kml","KML","application/vnd.google-earth.kml+xml"},
+  {"kmz","KMZ","application/vnd.google-earth.kmz"},
 #endif
-   {NULL,NULL,NULL}
+  {NULL,NULL,NULL}
 };
 
 /************************************************************************/
@@ -124,266 +126,240 @@ struct defaultOutputFormatEntry defaultoutputformats[] = {
 int msPostMapParseOutputFormatSetup( mapObj *map )
 
 {
-    outputFormatObj *format;
-
-    /* If IMAGETYPE not set use the first user defined OUTPUTFORMAT.
-       If none, use the first default format. */
-    if( map->imagetype == NULL && map->numoutputformats > 0 )
-        map->imagetype = msStrdup(map->outputformatlist[0]->name);
-    if( map->imagetype == NULL)
-        map->imagetype = msStrdup(defaultoutputformats[0].name);
-
-    /* select the current outputformat into map->outputformat */
-    format = msSelectOutputFormat( map, map->imagetype );
-    if( format == NULL ) 
-    {
-        msSetError(MS_MISCERR, 
-                   "Unable to select IMAGETYPE `%s'.", 
-                   "msPostMapParseOutputFormatSetup()",
-                   map->imagetype ? map->imagetype : "(null)" );
-        return MS_FAILURE;
-    }
+  outputFormatObj *format;
+
+  /* If IMAGETYPE not set use the first user defined OUTPUTFORMAT.
+     If none, use the first default format. */
+  if( map->imagetype == NULL && map->numoutputformats > 0 )
+    map->imagetype = msStrdup(map->outputformatlist[0]->name);
+  if( map->imagetype == NULL)
+    map->imagetype = msStrdup(defaultoutputformats[0].name);
+
+  /* select the current outputformat into map->outputformat */
+  format = msSelectOutputFormat( map, map->imagetype );
+  if( format == NULL ) {
+    msSetError(MS_MISCERR,
+               "Unable to select IMAGETYPE `%s'.",
+               "msPostMapParseOutputFormatSetup()",
+               map->imagetype ? map->imagetype : "(null)" );
+    return MS_FAILURE;
+  }
 
-    msApplyOutputFormat( &(map->outputformat), format, 
-                         map->transparent, map->interlace, map->imagequality );
+  msApplyOutputFormat( &(map->outputformat), format,
+                       map->transparent, map->interlace, map->imagequality );
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 /************************************************************************/
 /*                    msCreateDefaultOutputFormat()                     */
 /************************************************************************/
 
-outputFormatObj *msCreateDefaultOutputFormat( mapObj *map, 
-                                              const char *driver,
-                                              const char *name )
+outputFormatObj *msCreateDefaultOutputFormat( mapObj *map,
+    const char *driver,
+    const char *name )
 
 {
-    outputFormatObj *format = NULL;
+  outputFormatObj *format = NULL;
+  if( strcasecmp(driver,"GD/PC256") == 0 ) {
+    return msCreateDefaultOutputFormat( map, "GD/PNG", "gdpng" );
+  }
 
-    if( strcasecmp(driver,"GD/PC256") == 0 )
-    {
+  if( strcasecmp(driver,"GD/GIF") == 0 ) {
+    if(!name) name="gif";
 #ifdef USE_GD_GIF
-        return msCreateDefaultOutputFormat( map, "GD/GIF", "gif" );
-#elif defined(USE_GD_PNG)
-        return msCreateDefaultOutputFormat( map, "GD/PNG", "gdpng" );
+    format = msAllocOutputFormat( map, name, driver );
+    format->mimetype = msStrdup("image/gif");
+    format->imagemode = MS_IMAGEMODE_PC256;
+    format->extension = msStrdup("gif");
+    format->renderer = MS_RENDER_WITH_GD;
 #else
-        return NULL;
-#endif
-    }
-
-#ifdef USE_GD_GIF
-    if( strcasecmp(driver,"GD/GIF") == 0 )
-    {
-        if(!name) name="gif";
-        format = msAllocOutputFormat( map, name, driver );
-        format->mimetype = msStrdup("image/gif");
-        format->imagemode = MS_IMAGEMODE_PC256;
-        format->extension = msStrdup("gif");
-        format->renderer = MS_RENDER_WITH_GD;
-    }
+    return msCreateDefaultOutputFormat( map, "AGG/PNG8", name );
 #endif
+  }
 
+  if( strcasecmp(driver,"GD/PNG") == 0 ) {
+    if(!name) name="gdpng";
 #ifdef USE_GD_PNG
-    if( strcasecmp(driver,"GD/PNG") == 0 )
-    {
-        if(!name) name="gdpng";
-        format = msAllocOutputFormat( map, name, driver );
-        format->mimetype = msStrdup("image/png");
-        format->imagemode = MS_IMAGEMODE_PC256;
-        format->extension = msStrdup("png");
-        format->renderer = MS_RENDER_WITH_GD;
-    }
+    format = msAllocOutputFormat( map, name, driver );
+    format->mimetype = msStrdup("image/png");
+    format->imagemode = MS_IMAGEMODE_PC256;
+    format->extension = msStrdup("png");
+    format->renderer = MS_RENDER_WITH_GD;
+#else
+    return msCreateDefaultOutputFormat( map, "AGG/PNG8", name );
 #endif /* USE_GD_PNG */
+  }
+
+  if( strcasecmp(driver,"AGG/PNG") == 0 ) {
+    if(!name) name="png24";
+    format = msAllocOutputFormat( map, name, driver );
+    format->mimetype = msStrdup("image/png");
+    format->imagemode = MS_IMAGEMODE_RGB;
+    format->extension = msStrdup("png");
+    format->renderer = MS_RENDER_WITH_AGG;
+  }
+
+  if( strcasecmp(driver,"AGG/PNG8") == 0 ) {
+    if(!name) name="png8";
+    format = msAllocOutputFormat( map, name, driver );
+    format->mimetype = msStrdup("image/png; mode=8bit");
+    format->imagemode = MS_IMAGEMODE_RGB;
+    format->extension = msStrdup("png");
+    format->renderer = MS_RENDER_WITH_AGG;
+    msSetOutputFormatOption( format, "QUANTIZE_FORCE", "on");
+    msSetOutputFormatOption( format, "QUANTIZE_COLORS", "256");
+  }
+
+  if( strcasecmp(driver,"AGG/JPEG") == 0 ) {
+    if(!name) name="jpeg";
+    format = msAllocOutputFormat( map, name, driver );
+    format->mimetype = msStrdup("image/jpeg");
+    format->imagemode = MS_IMAGEMODE_RGB;
+    format->extension = msStrdup("jpg");
+    format->renderer = MS_RENDER_WITH_AGG;
+  }
 
-    if( strcasecmp(driver,"AGG/PNG") == 0 )
-    {
-        if(!name) name="png24";
-        format = msAllocOutputFormat( map, name, driver );
-        format->mimetype = msStrdup("image/png");
-        format->imagemode = MS_IMAGEMODE_RGB;
-        format->extension = msStrdup("png");
-        format->renderer = MS_RENDER_WITH_AGG;
-    }
-
-    if( strcasecmp(driver,"AGG/PNG8") == 0 )
-    {
-        if(!name) name="png8";
-        format = msAllocOutputFormat( map, name, driver );
-        format->mimetype = msStrdup("image/png; mode=8bit");
-        format->imagemode = MS_IMAGEMODE_RGB;
-        format->extension = msStrdup("png");
-        format->renderer = MS_RENDER_WITH_AGG;
-        msSetOutputFormatOption( format, "QUANTIZE_FORCE", "on");
-        msSetOutputFormatOption( format, "QUANTIZE_COLORS", "256");
-    }
-    
-    if( strcasecmp(driver,"AGG/JPEG") == 0 )
-    {
-        if(!name) name="jpeg";
-        format = msAllocOutputFormat( map, name, driver );
-        format->mimetype = msStrdup("image/jpeg");
-        format->imagemode = MS_IMAGEMODE_RGB;
-        format->extension = msStrdup("jpg");
-        format->renderer = MS_RENDER_WITH_AGG;
-    }
-    
 #if defined(USE_CAIRO)
-    if( strcasecmp(driver,"CAIRO/PNG") == 0 )
-    {
-        if(!name) name="cairopng";
-        format = msAllocOutputFormat( map, name, driver );
-        format->mimetype = msStrdup("image/png; mode=24bit");
-        format->imagemode = MS_IMAGEMODE_RGB;
-        format->extension = msStrdup("png");
-        format->renderer = MS_RENDER_WITH_CAIRO_RASTER;
-    }
-    if( strcasecmp(driver,"CAIRO/JPEG") == 0 )
-    {
-        if(!name) name="cairojpeg";
-        format = msAllocOutputFormat( map, name, driver );
-        format->mimetype = msStrdup("image/jpeg");
-        format->imagemode = MS_IMAGEMODE_RGB;
-        format->extension = msStrdup("jpg");
-        format->renderer = MS_RENDER_WITH_CAIRO_RASTER;
-    }
-    if( strcasecmp(driver,"CAIRO/PDF") == 0 )
-    {
-        if(!name) name="pdf";
-        format = msAllocOutputFormat( map, name, driver );
-        format->mimetype = msStrdup("application/x-pdf");
-        format->imagemode = MS_IMAGEMODE_RGB;
-        format->extension = msStrdup("pdf");
-        format->renderer = MS_RENDER_WITH_CAIRO_PDF;
-    }
-    if( strcasecmp(driver,"CAIRO/SVG") == 0 )
-    {
-        if(!name) name="svg";
-        format = msAllocOutputFormat( map, name, driver );
-        format->mimetype = msStrdup("image/svg+xml");
-        format->imagemode = MS_IMAGEMODE_RGB;
-        format->extension = msStrdup("svg");
-        format->renderer = MS_RENDER_WITH_CAIRO_SVG;
-    }
+  if( strcasecmp(driver,"CAIRO/PNG") == 0 ) {
+    if(!name) name="cairopng";
+    format = msAllocOutputFormat( map, name, driver );
+    format->mimetype = msStrdup("image/png; mode=24bit");
+    format->imagemode = MS_IMAGEMODE_RGB;
+    format->extension = msStrdup("png");
+    format->renderer = MS_RENDER_WITH_CAIRO_RASTER;
+  }
+  if( strcasecmp(driver,"CAIRO/JPEG") == 0 ) {
+    if(!name) name="cairojpeg";
+    format = msAllocOutputFormat( map, name, driver );
+    format->mimetype = msStrdup("image/jpeg");
+    format->imagemode = MS_IMAGEMODE_RGB;
+    format->extension = msStrdup("jpg");
+    format->renderer = MS_RENDER_WITH_CAIRO_RASTER;
+  }
+  if( strcasecmp(driver,"CAIRO/PDF") == 0 ) {
+    if(!name) name="pdf";
+    format = msAllocOutputFormat( map, name, driver );
+    format->mimetype = msStrdup("application/x-pdf");
+    format->imagemode = MS_IMAGEMODE_RGB;
+    format->extension = msStrdup("pdf");
+    format->renderer = MS_RENDER_WITH_CAIRO_PDF;
+  }
+  if( strcasecmp(driver,"CAIRO/SVG") == 0 ) {
+    if(!name) name="svg";
+    format = msAllocOutputFormat( map, name, driver );
+    format->mimetype = msStrdup("image/svg+xml");
+    format->imagemode = MS_IMAGEMODE_RGB;
+    format->extension = msStrdup("svg");
+    format->renderer = MS_RENDER_WITH_CAIRO_SVG;
+  }
 #ifdef _WIN32
-    if( strcasecmp(driver,"CAIRO/WINGDI") == 0 )
-    {
-        if(!name) name="cairowinGDI";
-        format = msAllocOutputFormat( map, name, driver );
-        format->mimetype = msStrdup("");
-        format->imagemode = MS_IMAGEMODE_RGB;
-        format->extension = msStrdup("");
-        format->renderer = MS_RENDER_WITH_CAIRO_RASTER;
-    }
-    if( strcasecmp(driver,"CAIRO/WINGDIPRINT") == 0 )
-    {
-        if(!name) name="cairowinGDIPrint";
-        format = msAllocOutputFormat( map, name, driver );
-        format->mimetype = msStrdup("");
-        format->imagemode = MS_IMAGEMODE_RGB;
-        format->extension = msStrdup("");
-        format->renderer = MS_RENDER_WITH_CAIRO_RASTER;
-    }
+  if( strcasecmp(driver,"CAIRO/WINGDI") == 0 ) {
+    if(!name) name="cairowinGDI";
+    format = msAllocOutputFormat( map, name, driver );
+    format->mimetype = msStrdup("");
+    format->imagemode = MS_IMAGEMODE_RGB;
+    format->extension = msStrdup("");
+    format->renderer = MS_RENDER_WITH_CAIRO_RASTER;
+  }
+  if( strcasecmp(driver,"CAIRO/WINGDIPRINT") == 0 ) {
+    if(!name) name="cairowinGDIPrint";
+    format = msAllocOutputFormat( map, name, driver );
+    format->mimetype = msStrdup("");
+    format->imagemode = MS_IMAGEMODE_RGB;
+    format->extension = msStrdup("");
+    format->renderer = MS_RENDER_WITH_CAIRO_RASTER;
+  }
 #endif
 #endif
 
-#if defined(USE_OGL) 
-    if( strcasecmp(driver,"OGL/PNG") == 0 ) 
-    { 
-        if(!name) name="oglpng24";
-        format = msAllocOutputFormat( map, name, driver );
-        format->mimetype = msStrdup("image/png; mode=24bit"); 
-        format->imagemode = MS_IMAGEMODE_RGB; 
-        format->extension = msStrdup("png"); 
-        format->renderer = MS_RENDER_WITH_OGL; 
-    } 
-#endif 
-
-#if defined(USE_KML) 
-    if( strcasecmp(driver,"KML") == 0 ) 
-    { 
-        if(!name) name="kml";
-        format = msAllocOutputFormat( map, name, driver );
-        format->mimetype = msStrdup("application/vnd.google-earth.kml+xml"); 
-        format->imagemode = MS_IMAGEMODE_RGB; 
-        format->extension = msStrdup("kml"); 
-        format->renderer = MS_RENDER_WITH_KML; 
-        msSetOutputFormatOption( format, "ATTACHMENT", "mapserver.kml");
-    } 
-    if( strcasecmp(driver,"KMZ") == 0 ) 
-    { 
-        if(!name) name="kmz";
-        format = msAllocOutputFormat( map, name, driver );
-        format->mimetype = strdup("application/vnd.google-earth.kmz"); 
-        format->imagemode = MS_IMAGEMODE_RGB; 
-        format->extension = strdup("kmz"); 
-        format->renderer = MS_RENDER_WITH_KML; 
-        msSetOutputFormatOption( format, "ATTACHMENT", "mapserver.kmz");
-    } 
+#if defined(USE_OGL)
+  if( strcasecmp(driver,"OGL/PNG") == 0 ) {
+    if(!name) name="oglpng24";
+    format = msAllocOutputFormat( map, name, driver );
+    format->mimetype = msStrdup("image/png; mode=24bit");
+    format->imagemode = MS_IMAGEMODE_RGB;
+    format->extension = msStrdup("png");
+    format->renderer = MS_RENDER_WITH_OGL;
+  }
+#endif
+
+#if defined(USE_KML)
+  if( strcasecmp(driver,"KML") == 0 ) {
+    if(!name) name="kml";
+    format = msAllocOutputFormat( map, name, driver );
+    format->mimetype = msStrdup("application/vnd.google-earth.kml+xml");
+    format->imagemode = MS_IMAGEMODE_RGB;
+    format->extension = msStrdup("kml");
+    format->renderer = MS_RENDER_WITH_KML;
+    msSetOutputFormatOption( format, "ATTACHMENT", "mapserver.kml");
+  }
+  if( strcasecmp(driver,"KMZ") == 0 ) {
+    if(!name) name="kmz";
+    format = msAllocOutputFormat( map, name, driver );
+    format->mimetype = strdup("application/vnd.google-earth.kmz");
+    format->imagemode = MS_IMAGEMODE_RGB;
+    format->extension = strdup("kmz");
+    format->renderer = MS_RENDER_WITH_KML;
+    msSetOutputFormatOption( format, "ATTACHMENT", "mapserver.kmz");
+  }
 #endif
 
 
 
 #ifdef USE_GDAL
-    if( strncasecmp(driver,"gdal/",5) == 0 )
-    {
-        if(!name) name=driver+5;
-        format = msAllocOutputFormat( map, name, driver );
-        if( msInitDefaultGDALOutputFormat( format ) == MS_FAILURE )
-        {
-            if( map != NULL )
-            {
-                map->numoutputformats--;
-                map->outputformatlist[map->numoutputformats] = NULL;
-            }
-
-            msFreeOutputFormat( format );
-            format = NULL;
-        }
+  if( strncasecmp(driver,"gdal/",5) == 0 ) {
+    if(!name) name=driver+5;
+    format = msAllocOutputFormat( map, name, driver );
+    if( msInitDefaultGDALOutputFormat( format ) == MS_FAILURE ) {
+      if( map != NULL ) {
+        map->numoutputformats--;
+        map->outputformatlist[map->numoutputformats] = NULL;
+      }
+
+      msFreeOutputFormat( format );
+      format = NULL;
     }
+  }
 #endif
 #ifdef USE_OGR
-    if( strncasecmp(driver,"ogr/",4) == 0 )
-    {
-        if(!name) name=driver+4;
-        format = msAllocOutputFormat( map, name, driver );
-        if( msInitDefaultOGROutputFormat( format ) == MS_FAILURE )
-        {
-            if( map != NULL )
-            {
-                map->numoutputformats--;
-                map->outputformatlist[map->numoutputformats] = NULL;
-            }
-
-            msFreeOutputFormat( format );
-            format = NULL;
-        }
-    }
-#endif
-    if( strcasecmp(driver,"imagemap") == 0 )
-    {
-        if(!name) name="imagemap";
-        format = msAllocOutputFormat( map, name, driver );
-        format->mimetype = msStrdup("text/html; driver=imagemap");
-        format->extension = msStrdup("html");
-        format->imagemode = MS_IMAGEMODE_NULL;
-        format->renderer = MS_RENDER_WITH_IMAGEMAP;
-    }
+  if( strncasecmp(driver,"ogr/",4) == 0 ) {
+    if(!name) name=driver+4;
+    format = msAllocOutputFormat( map, name, driver );
+    if( msInitDefaultOGROutputFormat( format ) == MS_FAILURE ) {
+      if( map != NULL ) {
+        map->numoutputformats--;
+        map->outputformatlist[map->numoutputformats] = NULL;
+      }
 
-    if( strcasecmp(driver,"template") == 0 ) {
-        if(!name) name="template";
-        format = msAllocOutputFormat( map, name, driver );
-        format->mimetype = msStrdup("text/html");
-        format->extension = msStrdup("html");
-        format->imagemode = MS_IMAGEMODE_FEATURE;
-        format->renderer = MS_RENDER_WITH_TEMPLATE;
+      msFreeOutputFormat( format );
+      format = NULL;
     }
-
-    if( format != NULL )
-        format->inmapfile = MS_FALSE;
-    
-    
-    return format;
+  }
+#endif
+  if( strcasecmp(driver,"imagemap") == 0 ) {
+    if(!name) name="imagemap";
+    format = msAllocOutputFormat( map, name, driver );
+    format->mimetype = msStrdup("text/html; driver=imagemap");
+    format->extension = msStrdup("html");
+    format->imagemode = MS_IMAGEMODE_NULL;
+    format->renderer = MS_RENDER_WITH_IMAGEMAP;
+  }
+
+  if( strcasecmp(driver,"template") == 0 ) {
+    if(!name) name="template";
+    format = msAllocOutputFormat( map, name, driver );
+    format->mimetype = msStrdup("text/html");
+    format->extension = msStrdup("html");
+    format->imagemode = MS_IMAGEMODE_FEATURE;
+    format->renderer = MS_RENDER_WITH_TEMPLATE;
+  }
+
+  if( format != NULL )
+    format->inmapfile = MS_FALSE;
+
+
+  return format;
 }
 
 /************************************************************************/
@@ -393,23 +369,23 @@ outputFormatObj *msCreateDefaultOutputFormat( mapObj *map,
 
 void msApplyDefaultOutputFormats( mapObj *map )
 {
-    char *saved_imagetype;
-    struct defaultOutputFormatEntry *defEntry;
-
-    if( map->imagetype == NULL )
-        saved_imagetype = NULL;
-    else
-        saved_imagetype = msStrdup(map->imagetype);
-
-    defEntry = defaultoutputformats;
-    while(defEntry->name) {
-       if( msSelectOutputFormat( map, defEntry->name ) == NULL )
-          msCreateDefaultOutputFormat( map, defEntry->driver, defEntry->name );
-       defEntry++;
-    }
-    if( map->imagetype != NULL )
-        free( map->imagetype );
-    map->imagetype = saved_imagetype;
+  char *saved_imagetype;
+  struct defaultOutputFormatEntry *defEntry;
+
+  if( map->imagetype == NULL )
+    saved_imagetype = NULL;
+  else
+    saved_imagetype = msStrdup(map->imagetype);
+
+  defEntry = defaultoutputformats;
+  while(defEntry->name) {
+    if( msSelectOutputFormat( map, defEntry->name ) == NULL )
+      msCreateDefaultOutputFormat( map, defEntry->driver, defEntry->name );
+    defEntry++;
+  }
+  if( map->imagetype != NULL )
+    free( map->imagetype );
+  map->imagetype = saved_imagetype;
 }
 
 /************************************************************************/
@@ -419,69 +395,67 @@ void msApplyDefaultOutputFormats( mapObj *map )
 void msFreeOutputFormat( outputFormatObj *format )
 
 {
-    if( format == NULL )
-        return;
-    if(MS_RENDERER_PLUGIN(format) && format->vtable) {
-       format->vtable->cleanup(MS_RENDERER_CACHE(format->vtable));
-       free( format->vtable );
-    }
-    msFree( format->name );
-    msFree( format->mimetype );
-    msFree( format->driver );
-    msFree( format->extension );
-    msFreeCharArray( format->formatoptions, format->numformatoptions );
-    msFree( format );
+  if( format == NULL )
+    return;
+  if(MS_RENDERER_PLUGIN(format) && format->vtable) {
+    format->vtable->cleanup(MS_RENDERER_CACHE(format->vtable));
+    free( format->vtable );
+  }
+  msFree( format->name );
+  msFree( format->mimetype );
+  msFree( format->driver );
+  msFree( format->extension );
+  msFreeCharArray( format->formatoptions, format->numformatoptions );
+  msFree( format );
 }
 
 /************************************************************************/
 /*                        msAllocOutputFormat()                         */
 /************************************************************************/
 
-static outputFormatObj *msAllocOutputFormat( mapObj *map, const char *name, 
-                                             const char *driver )
+static outputFormatObj *msAllocOutputFormat( mapObj *map, const char *name,
+    const char *driver )
 
 {
-    outputFormatObj *format;
-
-/* -------------------------------------------------------------------- */
-/*      Allocate the format object.                                     */
-/* -------------------------------------------------------------------- */
-    format = (outputFormatObj *) calloc(1,sizeof(outputFormatObj));
-    if( format == NULL )
-    {
-        msSetError( MS_MEMERR, NULL, "msAllocOutputFormat()" );
-        return NULL;
-    }
+  outputFormatObj *format;
+
+  /* -------------------------------------------------------------------- */
+  /*      Allocate the format object.                                     */
+  /* -------------------------------------------------------------------- */
+  format = (outputFormatObj *) calloc(1,sizeof(outputFormatObj));
+  if( format == NULL ) {
+    msSetError( MS_MEMERR, NULL, "msAllocOutputFormat()" );
+    return NULL;
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Initialize various fields.                                      */
+  /* -------------------------------------------------------------------- */
+  format->bands = 1;
+  format->name = msStrdup(name);
+  format->driver = msStrdup(driver);
+  format->refcount = 0;
+  format->vtable = NULL;
+  format->device = NULL;
+  format->imagemode = MS_IMAGEMODE_RGB;
+
+  /* -------------------------------------------------------------------- */
+  /*      Attach to map.                                                  */
+  /* -------------------------------------------------------------------- */
+  if( map != NULL ) {
+    map->numoutputformats++;
+    if( map->outputformatlist == NULL )
+      map->outputformatlist = (outputFormatObj **) malloc(sizeof(void*));
+    else
+      map->outputformatlist = (outputFormatObj **)
+                              realloc(map->outputformatlist,
+                                      sizeof(void*) * map->numoutputformats );
 
-/* -------------------------------------------------------------------- */
-/*      Initialize various fields.                                      */
-/* -------------------------------------------------------------------- */
-    format->bands = 1;
-    format->name = msStrdup(name);
-    format->driver = msStrdup(driver);
-    format->refcount = 0;
-    format->vtable = NULL;
-    format->device = NULL;
-    format->imagemode = MS_IMAGEMODE_PC256;
+    map->outputformatlist[map->numoutputformats-1] = format;
+    format->refcount++;
+  }
 
-/* -------------------------------------------------------------------- */
-/*      Attach to map.                                                  */
-/* -------------------------------------------------------------------- */
-    if( map != NULL )
-    {
-        map->numoutputformats++;
-        if( map->outputformatlist == NULL )
-            map->outputformatlist = (outputFormatObj **) malloc(sizeof(void*));
-        else
-            map->outputformatlist = (outputFormatObj **)
-                realloc(map->outputformatlist,
-                        sizeof(void*) * map->numoutputformats );
-
-        map->outputformatlist[map->numoutputformats-1] = format;
-        format->refcount++;
-    }
-    
-    return format;
+  return format;
 }
 
 /************************************************************************/
@@ -490,26 +464,25 @@ static outputFormatObj *msAllocOutputFormat( mapObj *map, const char *name,
 /*      Add an output format  .                                         */
 /*      http://mapserver.gis.umn.edu/bugs/show_bug.cgi?id=511           */
 /************************************************************************/
-int msAppendOutputFormat(mapObj *map, outputFormatObj *format) 
+int msAppendOutputFormat(mapObj *map, outputFormatObj *format)
 {
-/* -------------------------------------------------------------------- */
-/*      Attach to map.                                                  */
-/* -------------------------------------------------------------------- */
-    if (map != NULL)
-    {
-        map->numoutputformats++;
-        if (map->outputformatlist == NULL)
-            map->outputformatlist = (outputFormatObj **) malloc(sizeof(void*));
-        else
-            map->outputformatlist = (outputFormatObj **)
-                realloc(map->outputformatlist,
-                        sizeof(void*) * map->numoutputformats );
-
-        map->outputformatlist[map->numoutputformats-1] = format;
-        format->refcount++;
-    }
-    
-    return map->numoutputformats;
+  /* -------------------------------------------------------------------- */
+  /*      Attach to map.                                                  */
+  /* -------------------------------------------------------------------- */
+  if (map != NULL) {
+    map->numoutputformats++;
+    if (map->outputformatlist == NULL)
+      map->outputformatlist = (outputFormatObj **) malloc(sizeof(void*));
+    else
+      map->outputformatlist = (outputFormatObj **)
+                              realloc(map->outputformatlist,
+                                      sizeof(void*) * map->numoutputformats );
+
+    map->outputformatlist[map->numoutputformats-1] = format;
+    format->refcount++;
+  }
+
+  return map->numoutputformats;
 }
 
 /************************************************************************/
@@ -520,38 +493,32 @@ int msAppendOutputFormat(mapObj *map, outputFormatObj *format)
 /************************************************************************/
 int msRemoveOutputFormat(mapObj *map, const char *name)
 {
-    int i, j;
-/* -------------------------------------------------------------------- */
-/*      Detach from map.                                                */
-/* -------------------------------------------------------------------- */
-    if (map != NULL)
-    {
-        if (map->outputformatlist == NULL)
-        {
-            msSetError(MS_CHILDERR, "Can't remove format from empty outputformatlist", "msRemoveOutputFormat()");
-            return MS_FAILURE;
-        }
-        else
-        {
-            i = msGetOutputFormatIndex(map, name);
-            if (i >= 0) 
-            {
-                map->numoutputformats--;
-                if( map->outputformatlist[i]->refcount-- < 1 )
-                    msFreeOutputFormat( map->outputformatlist[i] );
-
-                for (j=i; j<map->numoutputformats-1; j++)
-                {
-                    map->outputformatlist[j] = map->outputformatlist[j+1];
-                }
-            }
-            map->outputformatlist = (outputFormatObj **)
-                realloc(map->outputformatlist,
-                    sizeof(void*) * (map->numoutputformats) );
-            return MS_SUCCESS;
+  int i, j;
+  /* -------------------------------------------------------------------- */
+  /*      Detach from map.                                                */
+  /* -------------------------------------------------------------------- */
+  if (map != NULL) {
+    if (map->outputformatlist == NULL) {
+      msSetError(MS_CHILDERR, "Can't remove format from empty outputformatlist", "msRemoveOutputFormat()");
+      return MS_FAILURE;
+    } else {
+      i = msGetOutputFormatIndex(map, name);
+      if (i >= 0) {
+        map->numoutputformats--;
+        if( map->outputformatlist[i]->refcount-- < 1 )
+          msFreeOutputFormat( map->outputformatlist[i] );
+
+        for (j=i; j<map->numoutputformats-1; j++) {
+          map->outputformatlist[j] = map->outputformatlist[j+1];
         }
+      }
+      map->outputformatlist = (outputFormatObj **)
+                              realloc(map->outputformatlist,
+                                      sizeof(void*) * (map->numoutputformats) );
+      return MS_SUCCESS;
     }
-    return MS_FAILURE;
+  }
+  return MS_FAILURE;
 }
 
 /************************************************************************/
@@ -562,26 +529,24 @@ int msRemoveOutputFormat(mapObj *map, const char *name)
 
 int msGetOutputFormatIndex(mapObj *map, const char *imagetype)
 {
-    int i;
-/* -------------------------------------------------------------------- */
-/*      Try to find the format in the maps list of formats, first by    */
-/*      mime type, and then by output format name.                      */
-/* -------------------------------------------------------------------- */
-    for (i = 0; i < map->numoutputformats; i++)
-    {
-        if (map->outputformatlist[i]->mimetype != NULL
-            && strcasecmp(imagetype,
-                          map->outputformatlist[i]->mimetype) == 0 )
-            return i;
-    }
-    
-    for( i = 0; i < map->numoutputformats; i++ )
-    {
-        if( strcasecmp(imagetype,map->outputformatlist[i]->name) == 0 )
-            return i;
-    }
-
-    return -1;
+  int i;
+  /* -------------------------------------------------------------------- */
+  /*      Try to find the format in the maps list of formats, first by    */
+  /*      mime type, and then by output format name.                      */
+  /* -------------------------------------------------------------------- */
+  for (i = 0; i < map->numoutputformats; i++) {
+    if (map->outputformatlist[i]->mimetype != NULL
+        && strcasecmp(imagetype,
+                      map->outputformatlist[i]->mimetype) == 0 )
+      return i;
+  }
+
+  for( i = 0; i < map->numoutputformats; i++ ) {
+    if( strcasecmp(imagetype,map->outputformatlist[i]->name) == 0 )
+      return i;
+  }
+
+  return -1;
 }
 
 /************************************************************************/
@@ -590,135 +555,128 @@ int msGetOutputFormatIndex(mapObj *map, const char *imagetype)
 
 
 
-outputFormatObj *msSelectOutputFormat( mapObj *map, 
+outputFormatObj *msSelectOutputFormat( mapObj *map,
                                        const char *imagetype )
 
 {
-    int index;
-    outputFormatObj *format = NULL;
-
-    if( map == NULL || imagetype == NULL || strlen(imagetype) == 0 )
-        return NULL;
-    
-/* -------------------------------------------------------------------- */
-/*      Try to find the format in the maps list of formats, first by    */
-/*      mime type, and then by output format name.                      */
-/* -------------------------------------------------------------------- */
-    index = msGetOutputFormatIndex(map, imagetype);
-    if (index >= 0) {
-        format = map->outputformatlist[index];
-    } else {
-       struct defaultOutputFormatEntry *formatEntry = defaultoutputformats;
-       while(formatEntry->name) {
-          if(!strcasecmp(imagetype,formatEntry->name) || !strcasecmp(imagetype,formatEntry->mimetype)) {
-             format = msCreateDefaultOutputFormat( map, formatEntry->driver, formatEntry->name );
-             break;
-          }
-          formatEntry++;
-       }
-
+  int index;
+  outputFormatObj *format = NULL;
+
+  if( map == NULL || imagetype == NULL || strlen(imagetype) == 0 )
+    return NULL;
+
+  /* -------------------------------------------------------------------- */
+  /*      Try to find the format in the maps list of formats, first by    */
+  /*      mime type, and then by output format name.                      */
+  /* -------------------------------------------------------------------- */
+  index = msGetOutputFormatIndex(map, imagetype);
+  if (index >= 0) {
+    format = map->outputformatlist[index];
+  } else {
+    struct defaultOutputFormatEntry *formatEntry = defaultoutputformats;
+    while(formatEntry->name) {
+      if(!strcasecmp(imagetype,formatEntry->name) || !strcasecmp(imagetype,formatEntry->mimetype)) {
+        format = msCreateDefaultOutputFormat( map, formatEntry->driver, formatEntry->name );
+        break;
+      }
+      formatEntry++;
     }
 
-    if (format)
-    {
-        if (map->imagetype)
-            free(map->imagetype);
-        map->imagetype = msStrdup(format->name);
-    }
+  }
 
-    if( format != NULL )
-        msOutputFormatValidate( format, MS_FALSE );
+  if (format) {
+    if (map->imagetype)
+      free(map->imagetype);
+    map->imagetype = msStrdup(format->name);
+  }
 
-    return format;
+  if( format != NULL )
+    msOutputFormatValidate( format, MS_FALSE );
+
+  return format;
 }
 
 /************************************************************************/
 /*                        msApplyOutputFormat()                         */
 /************************************************************************/
 
-void msApplyOutputFormat( outputFormatObj **target, 
+void msApplyOutputFormat( outputFormatObj **target,
                           outputFormatObj *format,
-                          int transparent, 
-                          int interlaced, 
+                          int transparent,
+                          int interlaced,
                           int imagequality )
 
 {
-    int       change_needed = MS_FALSE;
-    int       old_imagequality, old_interlaced;
-    outputFormatObj *formatToFree = NULL;
-
-    assert( target != NULL );
-    
-    if( *target != NULL && --((*target)->refcount) < 1 )
-    {
-        formatToFree = *target;
-        *target = NULL;
-    }
-
-    if( format == NULL )
-    {
-        if( formatToFree )
-            msFreeOutputFormat( formatToFree );
-        return;
-    }
+  int       change_needed = MS_FALSE;
+  int       old_imagequality, old_interlaced;
+  outputFormatObj *formatToFree = NULL;
 
-    msOutputFormatValidate( format, MS_FALSE );
+  assert( target != NULL );
 
-/* -------------------------------------------------------------------- */
-/*      Do we need to change any values?  If not, then just apply       */
-/*      and return.                                                     */
-/* -------------------------------------------------------------------- */
-    if( transparent != MS_NOOVERRIDE && !format->transparent != !transparent )
-        change_needed = MS_TRUE;
-
-    old_imagequality = atoi(msGetOutputFormatOption( format, "QUALITY", "75"));
-    if( imagequality != MS_NOOVERRIDE && old_imagequality != imagequality )
-        change_needed = MS_TRUE;
-
-    old_interlaced = 
-        strcasecmp(msGetOutputFormatOption( format, "INTERLACE", "ON"),
-                   "OFF") != 0;
-    if( interlaced != MS_NOOVERRIDE && !interlaced != !old_interlaced )
-        change_needed = MS_TRUE;
-
-    if( change_needed )
-    {
-        char new_value[128];
-
-        if( format->refcount > 0 )
-            format = msCloneOutputFormat( format );
-
-        if( transparent != MS_NOOVERRIDE )
-        {
-            format->transparent = transparent;
-            if( format->imagemode == MS_IMAGEMODE_RGB )
-                format->imagemode = MS_IMAGEMODE_RGBA;
-        }
+  if( *target != NULL && --((*target)->refcount) < 1 ) {
+    formatToFree = *target;
+    *target = NULL;
+  }
 
-        if( imagequality != MS_NOOVERRIDE && imagequality != old_imagequality )
-        {
-            snprintf( new_value, sizeof(new_value), "%d", imagequality );
-            msSetOutputFormatOption( format, "QUALITY", new_value );
-        }
+  if( format == NULL ) {
+    if( formatToFree )
+      msFreeOutputFormat( formatToFree );
+    return;
+  }
+
+  msOutputFormatValidate( format, MS_FALSE );
+
+  /* -------------------------------------------------------------------- */
+  /*      Do we need to change any values?  If not, then just apply       */
+  /*      and return.                                                     */
+  /* -------------------------------------------------------------------- */
+  if( transparent != MS_NOOVERRIDE && !format->transparent != !transparent )
+    change_needed = MS_TRUE;
+
+  old_imagequality = atoi(msGetOutputFormatOption( format, "QUALITY", "75"));
+  if( imagequality != MS_NOOVERRIDE && old_imagequality != imagequality )
+    change_needed = MS_TRUE;
+
+  old_interlaced =
+    strcasecmp(msGetOutputFormatOption( format, "INTERLACE", "ON"),
+               "OFF") != 0;
+  if( interlaced != MS_NOOVERRIDE && !interlaced != !old_interlaced )
+    change_needed = MS_TRUE;
+
+  if( change_needed ) {
+    char new_value[128];
+
+    if( format->refcount > 0 )
+      format = msCloneOutputFormat( format );
+
+    if( transparent != MS_NOOVERRIDE ) {
+      format->transparent = transparent;
+      if( format->imagemode == MS_IMAGEMODE_RGB )
+        format->imagemode = MS_IMAGEMODE_RGBA;
+    }
 
-        if( interlaced != MS_NOOVERRIDE && !interlaced != !old_interlaced )
-        {
-            if( interlaced )
-                msSetOutputFormatOption( format, "INTERLACE", "ON" );
-            else
-                msSetOutputFormatOption( format, "INTERLACE", "OFF" );
-        }
+    if( imagequality != MS_NOOVERRIDE && imagequality != old_imagequality ) {
+      snprintf( new_value, sizeof(new_value), "%d", imagequality );
+      msSetOutputFormatOption( format, "QUALITY", new_value );
     }
 
-    *target = format;
-    format->refcount++;
-    if( MS_RENDERER_PLUGIN(format) ) {
-       msInitializeRendererVTable(format);
+    if( interlaced != MS_NOOVERRIDE && !interlaced != !old_interlaced ) {
+      if( interlaced )
+        msSetOutputFormatOption( format, "INTERLACE", "ON" );
+      else
+        msSetOutputFormatOption( format, "INTERLACE", "OFF" );
     }
-    
+  }
 
-    if( formatToFree )
-        msFreeOutputFormat( formatToFree );
+  *target = format;
+  format->refcount++;
+  if( MS_RENDERER_PLUGIN(format) ) {
+    msInitializeRendererVTable(format);
+  }
+
+
+  if( formatToFree )
+    msFreeOutputFormat( formatToFree );
 }
 
 /************************************************************************/
@@ -728,39 +686,39 @@ void msApplyOutputFormat( outputFormatObj **target,
 outputFormatObj *msCloneOutputFormat( outputFormatObj *src )
 
 {
-    outputFormatObj *dst;
-    int             i;
+  outputFormatObj *dst;
+  int             i;
 
-    dst = msAllocOutputFormat( NULL, src->name, src->driver );
+  dst = msAllocOutputFormat( NULL, src->name, src->driver );
 
-    msFree( dst->mimetype );
-    if( src->mimetype )
-        dst->mimetype = msStrdup( src->mimetype );
-    else
-        dst->mimetype = NULL;
+  msFree( dst->mimetype );
+  if( src->mimetype )
+    dst->mimetype = msStrdup( src->mimetype );
+  else
+    dst->mimetype = NULL;
 
-    msFree( dst->extension );
-    if( src->extension )
-        dst->extension = msStrdup( src->extension );
-    else
-        dst->extension = NULL;
+  msFree( dst->extension );
+  if( src->extension )
+    dst->extension = msStrdup( src->extension );
+  else
+    dst->extension = NULL;
+
+  dst->imagemode = src->imagemode;
+  dst->renderer = src->renderer;
 
-    dst->imagemode = src->imagemode;
-    dst->renderer = src->renderer;
-    
-    dst->transparent = src->transparent;
-    dst->bands = src->bands;
+  dst->transparent = src->transparent;
+  dst->bands = src->bands;
 
-    dst->numformatoptions = src->numformatoptions;
-    dst->formatoptions = (char **) 
-        malloc(sizeof(char *) * src->numformatoptions );
+  dst->numformatoptions = src->numformatoptions;
+  dst->formatoptions = (char **)
+                       malloc(sizeof(char *) * src->numformatoptions );
 
-    for( i = 0; i < src->numformatoptions; i++ )
-        dst->formatoptions[i] = msStrdup(src->formatoptions[i]);
+  for( i = 0; i < src->numformatoptions; i++ )
+    dst->formatoptions[i] = msStrdup(src->formatoptions[i]);
 
-    dst->inmapfile = src->inmapfile;
-    
-    return dst;
+  dst->inmapfile = src->inmapfile;
+
+  return dst;
 }
 
 /************************************************************************/
@@ -770,21 +728,20 @@ outputFormatObj *msCloneOutputFormat( outputFormatObj *src )
 /*      options are in "KEY=VALUE" format.                              */
 /************************************************************************/
 
-const char *msGetOutputFormatOption( outputFormatObj *format, 
-                                     const char *optionkey, 
+const char *msGetOutputFormatOption( outputFormatObj *format,
+                                     const char *optionkey,
                                      const char *defaultresult )
 
 {
-    int    i, len = strlen(optionkey);
+  int    i, len = strlen(optionkey);
 
-    for( i = 0; i < format->numformatoptions; i++ )
-    {
-        if( strncasecmp(format->formatoptions[i],optionkey,len) == 0
-            && format->formatoptions[i][len] == '=' )
-            return format->formatoptions[i] + len + 1;
-    }
+  for( i = 0; i < format->numformatoptions; i++ ) {
+    if( strncasecmp(format->formatoptions[i],optionkey,len) == 0
+        && format->formatoptions[i][len] == '=' )
+      return format->formatoptions[i] + len + 1;
+  }
 
-    return defaultresult;
+  return defaultresult;
 }
 
 /************************************************************************/
@@ -795,52 +752,49 @@ void msSetOutputFormatOption( outputFormatObj *format,
                               const char *key, const char *value )
 
 {
-    char *newline;
-    int   i, len;
-
-/* -------------------------------------------------------------------- */
-/*      Format the name=value pair into a newly allocated string.       */
-/* -------------------------------------------------------------------- */
-    newline = (char *) malloc(strlen(key)+strlen(value)+2);
-    if( newline == NULL )
-    {
-        assert( newline != NULL );
-        return;
+  char *newline;
+  int   i, len;
+
+  /* -------------------------------------------------------------------- */
+  /*      Format the name=value pair into a newly allocated string.       */
+  /* -------------------------------------------------------------------- */
+  newline = (char *) malloc(strlen(key)+strlen(value)+2);
+  if( newline == NULL ) {
+    assert( newline != NULL );
+    return;
+  }
+
+  sprintf( newline, "%s=%s", key, value );
+
+  /* -------------------------------------------------------------------- */
+  /*      Does this key already occur?  If so replace it.                 */
+  /* -------------------------------------------------------------------- */
+  len = strlen(key);
+
+  for( i = 0; i < format->numformatoptions; i++ ) {
+    if( strncasecmp(format->formatoptions[i],key,len) == 0
+        && format->formatoptions[i][len] == '=' ) {
+      free( format->formatoptions[i] );
+      format->formatoptions[i] = newline;
+      return;
     }
-
-    sprintf( newline, "%s=%s", key, value );
-    
-/* -------------------------------------------------------------------- */
-/*      Does this key already occur?  If so replace it.                 */
-/* -------------------------------------------------------------------- */
-    len = strlen(key);
-
-    for( i = 0; i < format->numformatoptions; i++ )
-    {
-        if( strncasecmp(format->formatoptions[i],key,len) == 0
-            && format->formatoptions[i][len] == '=' )
-        {
-            free( format->formatoptions[i] );
-            format->formatoptions[i] = newline;
-            return;
-        }
-    }
-
-/* -------------------------------------------------------------------- */
-/*      otherwise, we need to grow the list.                            */
-/* -------------------------------------------------------------------- */
-    format->numformatoptions++;
-    format->formatoptions = (char **) 
-        realloc( format->formatoptions, 
-                 sizeof(char*) * format->numformatoptions );
-
-    format->formatoptions[format->numformatoptions-1] = newline;
-
-/* -------------------------------------------------------------------- */
-/*      Capture generic value(s) we are interested in.                  */
-/* -------------------------------------------------------------------- */
-    if( strcasecmp(key,"BAND_COUNT") == 0 )
-        format->bands = atoi(value);
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      otherwise, we need to grow the list.                            */
+  /* -------------------------------------------------------------------- */
+  format->numformatoptions++;
+  format->formatoptions = (char **)
+                          realloc( format->formatoptions,
+                                   sizeof(char*) * format->numformatoptions );
+
+  format->formatoptions[format->numformatoptions-1] = newline;
+
+  /* -------------------------------------------------------------------- */
+  /*      Capture generic value(s) we are interested in.                  */
+  /* -------------------------------------------------------------------- */
+  if( strcasecmp(key,"BAND_COUNT") == 0 )
+    format->bands = atoi(value);
 }
 
 /************************************************************************/
@@ -850,29 +804,27 @@ void msSetOutputFormatOption( outputFormatObj *format,
 void msGetOutputFormatMimeList( mapObj *map, char **mime_list, int max_mime )
 
 {
-    int mime_count = 0, i;
-
-    msApplyDefaultOutputFormats(map);
-    for( i = 0; i < map->numoutputformats && mime_count < max_mime; i++ )
-    {
-        int  j;
-        
-        if( map->outputformatlist[i]->mimetype == NULL )
-            continue;
-
-        for( j = 0; j < mime_count; j++ )
-        {
-            if( strcasecmp(mime_list[j],
-                           map->outputformatlist[i]->mimetype) == 0 )
-                break;
-        }
+  int mime_count = 0, i;
+
+  msApplyDefaultOutputFormats(map);
+  for( i = 0; i < map->numoutputformats && mime_count < max_mime; i++ ) {
+    int  j;
 
-        if( j == mime_count )
-            mime_list[mime_count++] = map->outputformatlist[i]->mimetype;
+    if( map->outputformatlist[i]->mimetype == NULL )
+      continue;
+
+    for( j = 0; j < mime_count; j++ ) {
+      if( strcasecmp(mime_list[j],
+                     map->outputformatlist[i]->mimetype) == 0 )
+        break;
     }
 
-    if( mime_count < max_mime )
-        mime_list[mime_count] = NULL;
+    if( j == mime_count )
+      mime_list[mime_count++] = map->outputformatlist[i]->mimetype;
+  }
+
+  if( mime_count < max_mime )
+    mime_list[mime_count] = NULL;
 }
 
 /************************************************************************/
@@ -881,52 +833,49 @@ void msGetOutputFormatMimeList( mapObj *map, char **mime_list, int max_mime )
 void msGetOutputFormatMimeListImg( mapObj *map, char **mime_list, int max_mime )
 
 {
-    int mime_count = 0, i,j;
-    const char *format_list = NULL;
-    char **tokens = NULL;
-    int numtokens = 0;
-    outputFormatObj *format;
-
-    msApplyDefaultOutputFormats(map);
-    format_list = msOWSLookupMetadata(&(map->web.metadata), "M","getlegendgraphic_formatlist");
-    if ( format_list && strlen(format_list) > 0)
-      tokens = msStringSplit(format_list,  ',', &numtokens);
-
-    if (tokens && numtokens > 0)
-    {
-        for(j = 0; j < numtokens; j++ )
-        {
-            format = msSelectOutputFormat(map, tokens[j]);
-            if (format != NULL)
-            {
-                mime_list[mime_count++] = format->mimetype;
-            }
-        }
-        msFreeCharArray(tokens, numtokens);
+  int mime_count = 0, i,j;
+  const char *format_list = NULL;
+  char **tokens = NULL;
+  int numtokens = 0;
+  outputFormatObj *format;
+
+  msApplyDefaultOutputFormats(map);
+  format_list = msOWSLookupMetadata(&(map->web.metadata), "M","getlegendgraphic_formatlist");
+  if ( format_list && strlen(format_list) > 0)
+    tokens = msStringSplit(format_list,  ',', &numtokens);
+
+  if (tokens && numtokens > 0) {
+    for(j = 0; j < numtokens; j++ ) {
+      format = msSelectOutputFormat(map, tokens[j]);
+      if (format != NULL) {
+        mime_list[mime_count++] = format->mimetype;
+      }
     }
-    else
-    for( i = 0; i < map->numoutputformats && mime_count < max_mime; i++ )
-    {
-        int  j;
-        
-        if( map->outputformatlist[i]->mimetype == NULL )
-            continue;
-
-        for( j = 0; j < mime_count; j++ )
-        {
-            if( strcasecmp(mime_list[j],
-                           map->outputformatlist[i]->mimetype) == 0 )
-                break;
-        }
+    msFreeCharArray(tokens, numtokens);
+  } else
+    for( i = 0; i < map->numoutputformats && mime_count < max_mime; i++ ) {
+      int  j;
+
+      if( map->outputformatlist[i]->mimetype == NULL )
+        continue;
+
+      for( j = 0; j < mime_count; j++ ) {
+        if( strcasecmp(mime_list[j],
+                       map->outputformatlist[i]->mimetype) == 0 )
+          break;
+      }
 
-        if( j == mime_count && map->outputformatlist[i]->driver &&
-            (strncasecmp(map->outputformatlist[i]->driver, "GD/", 3)==0 ||
-             strncasecmp(map->outputformatlist[i]->driver, "AGG/", 4)==0))
-            mime_list[mime_count++] = map->outputformatlist[i]->mimetype;
+      if( j == mime_count && map->outputformatlist[i]->driver &&
+          (
+#ifdef USE_GD
+            strncasecmp(map->outputformatlist[i]->driver, "GD/", 3)==0 ||
+#endif
+            strncasecmp(map->outputformatlist[i]->driver, "AGG/", 4)==0))
+        mime_list[mime_count++] = map->outputformatlist[i]->mimetype;
     }
 
-    if( mime_count < max_mime )
-        mime_list[mime_count] = NULL;
+  if( mime_count < max_mime )
+    mime_list[mime_count] = NULL;
 }
 
 /************************************************************************/
@@ -935,57 +884,53 @@ void msGetOutputFormatMimeListImg( mapObj *map, char **mime_list, int max_mime )
 
 void msGetOutputFormatMimeListWMS( mapObj *map, char **mime_list, int max_mime )
 {
-    int mime_count = 0, i,j;
-    const char *format_list = NULL;
-    char **tokens = NULL;
-    int numtokens = 0;
-    outputFormatObj *format;
-    msApplyDefaultOutputFormats(map);
-    format_list = msOWSLookupMetadata(&(map->web.metadata), "M","getmap_formatlist");
-    if ( format_list && strlen(format_list) > 0)
-      tokens = msStringSplit(format_list,  ',', &numtokens);
-
-    if (tokens && numtokens > 0)
-    {
-        for(j = 0; j < numtokens; j++ )
-        {
-            format = msSelectOutputFormat(map, tokens[j]);
-            if (format != NULL)
-            {
-                mime_list[mime_count++] = format->mimetype;
-            }
-        }
-        msFreeCharArray(tokens, numtokens);
+  int mime_count = 0, i,j;
+  const char *format_list = NULL;
+  char **tokens = NULL;
+  int numtokens = 0;
+  outputFormatObj *format;
+  msApplyDefaultOutputFormats(map);
+  format_list = msOWSLookupMetadata(&(map->web.metadata), "M","getmap_formatlist");
+  if ( format_list && strlen(format_list) > 0)
+    tokens = msStringSplit(format_list,  ',', &numtokens);
+
+  if (tokens && numtokens > 0) {
+    for(j = 0; j < numtokens; j++ ) {
+      format = msSelectOutputFormat(map, tokens[j]);
+      if (format != NULL) {
+        mime_list[mime_count++] = format->mimetype;
+      }
     }
-    else
-    {
-        for( i = 0; i < map->numoutputformats && mime_count < max_mime; i++ )
-        {
-            int  j;
-        
-            if( map->outputformatlist[i]->mimetype == NULL )
-              continue;
-
-            for( j = 0; j < mime_count; j++ )
-            {
-                if( strcasecmp(mime_list[j],
-                               map->outputformatlist[i]->mimetype) == 0 )
-                  break;
-            }
-
-            if( j == mime_count && map->outputformatlist[i]->driver &&
-               (strncasecmp(map->outputformatlist[i]->driver, "GD/", 3)==0 ||
-                strncasecmp(map->outputformatlist[i]->driver, "GDAL/", 5)==0 ||
-                strncasecmp(map->outputformatlist[i]->driver, "AGG/", 4)==0 ||
-                strcasecmp(map->outputformatlist[i]->driver, "CAIRO/SVG")==0 ||
-                strcasecmp(map->outputformatlist[i]->driver, "CAIRO/PDF")==0 ||
-                strcasecmp(map->outputformatlist[i]->driver, "kml")==0 ||
-                strcasecmp(map->outputformatlist[i]->driver, "kmz")==0))
-              mime_list[mime_count++] = map->outputformatlist[i]->mimetype;
-        }
+    msFreeCharArray(tokens, numtokens);
+  } else {
+    for( i = 0; i < map->numoutputformats && mime_count < max_mime; i++ ) {
+      int  j;
+
+      if( map->outputformatlist[i]->mimetype == NULL )
+        continue;
+
+      for( j = 0; j < mime_count; j++ ) {
+        if( strcasecmp(mime_list[j],
+                       map->outputformatlist[i]->mimetype) == 0 )
+          break;
+      }
+
+      if( j == mime_count && map->outputformatlist[i]->driver &&
+          (
+#ifdef USE_GD
+            strncasecmp(map->outputformatlist[i]->driver, "GD/", 3)==0 ||
+#endif
+            strncasecmp(map->outputformatlist[i]->driver, "GDAL/", 5)==0 ||
+            strncasecmp(map->outputformatlist[i]->driver, "AGG/", 4)==0 ||
+            strcasecmp(map->outputformatlist[i]->driver, "CAIRO/SVG")==0 ||
+            strcasecmp(map->outputformatlist[i]->driver, "CAIRO/PDF")==0 ||
+            strcasecmp(map->outputformatlist[i]->driver, "kml")==0 ||
+            strcasecmp(map->outputformatlist[i]->driver, "kmz")==0))
+        mime_list[mime_count++] = map->outputformatlist[i]->mimetype;
     }
-    if( mime_count < max_mime )
-        mime_list[mime_count] = NULL;
+  }
+  if( mime_count < max_mime )
+    mime_list[mime_count] = NULL;
 }
 
 
@@ -1000,132 +945,132 @@ void msGetOutputFormatMimeListWMS( mapObj *map, char **mime_list, int max_mime )
 int msOutputFormatValidate( outputFormatObj *format, int issue_error )
 
 {
-    int result = MS_TRUE;
-    char *driver_ext;
-
-    format->bands = atoi(msGetOutputFormatOption( format, "BAND_COUNT", "1" ));
-
-    /* Enforce the requirement that JPEG be RGB and TRANSPARENT=OFF */
-    driver_ext = strstr(format->driver,"/");
-    if( driver_ext && ++driver_ext && !strcasecmp(driver_ext,"JPEG")) {
-      if( format->transparent ){
-        if( issue_error )
-            msSetError( MS_MISCERR,
-                        "JPEG OUTPUTFORMAT %s has TRANSPARENT set ON, but this is not supported.\n"
-                        "It has been disabled.\n", 
-                        "msOutputFormatValidate()", format->name );
-        else
-            msDebug( "JPEG OUTPUTFORMAT %s has TRANSPARENT set ON, but this is not supported.\n"
-                     "It has been disabled.\n", 
-                     format->name );
-
-        format->transparent = MS_FALSE;
-        result = MS_FALSE;
-      }
-      if( format->imagemode == MS_IMAGEMODE_RGBA )
-      {
-        if( issue_error )
-            msSetError( MS_MISCERR,
-                        "JPEG OUTPUTFORMAT %s has IMAGEMODE RGBA, but this is not supported.\n"
-                        "IMAGEMODE forced to RGB.\n", 
-                        "msOutputFormatValidate()", format->name );
-        else
-            msDebug( "JPEG OUTPUTFORMAT %s has IMAGEMODE RGBA, but this is not supported.\n"
-                     "IMAGEMODE forced to RGB.\n", 
-                     format->name );
-
-        format->imagemode = MS_IMAGEMODE_RGB;
-        result = MS_FALSE;
-      }
-    }
-
-    if( format->transparent && format->imagemode == MS_IMAGEMODE_RGB )
-    {
-        if( issue_error )
-            msSetError( MS_MISCERR,
-                   "OUTPUTFORMAT %s has TRANSPARENT set ON, but an IMAGEMODE\n"
-                   "of RGB instead of RGBA.  Changing imagemode to RGBA.\n", 
-                   "msOutputFormatValidate()", format->name );
-        else
-            msDebug("OUTPUTFORMAT %s has TRANSPARENT set ON, but an IMAGEMODE\n"
-                    "of RGB instead of RGBA.  Changing imagemode to RGBA.\n", 
-                    format->name );
+  int result = MS_TRUE;
+  char *driver_ext;
+
+  format->bands = atoi(msGetOutputFormatOption( format, "BAND_COUNT", "1" ));
+
+  /* Enforce the requirement that JPEG be RGB and TRANSPARENT=OFF */
+  driver_ext = strstr(format->driver,"/");
+  if( driver_ext && ++driver_ext && !strcasecmp(driver_ext,"JPEG")) {
+    if( format->transparent ) {
+      if( issue_error )
+        msSetError( MS_MISCERR,
+                    "JPEG OUTPUTFORMAT %s has TRANSPARENT set ON, but this is not supported.\n"
+                    "It has been disabled.\n",
+                    "msOutputFormatValidate()", format->name );
+      else
+        msDebug( "JPEG OUTPUTFORMAT %s has TRANSPARENT set ON, but this is not supported.\n"
+                 "It has been disabled.\n",
+                 format->name );
 
-        format->imagemode = MS_IMAGEMODE_RGBA;
-        result = MS_FALSE;
+      format->transparent = MS_FALSE;
+      result = MS_FALSE;
     }
+    if( format->imagemode == MS_IMAGEMODE_RGBA ) {
+      if( issue_error )
+        msSetError( MS_MISCERR,
+                    "JPEG OUTPUTFORMAT %s has IMAGEMODE RGBA, but this is not supported.\n"
+                    "IMAGEMODE forced to RGB.\n",
+                    "msOutputFormatValidate()", format->name );
+      else
+        msDebug( "JPEG OUTPUTFORMAT %s has IMAGEMODE RGBA, but this is not supported.\n"
+                 "IMAGEMODE forced to RGB.\n",
+                 format->name );
 
-    /* Special checking around RAWMODE image modes. */
-    if( format->imagemode == MS_IMAGEMODE_INT16 
-        || format->imagemode == MS_IMAGEMODE_FLOAT32 
-        || format->imagemode == MS_IMAGEMODE_BYTE )
-    {
-        if( strncmp(format->driver,"GDAL/",5) != 0 )
-        {
-            result = MS_FALSE;
-            if( issue_error )
-                msSetError( MS_MISCERR,
-                            "OUTPUTFORMAT %s has IMAGEMODE BYTE/INT16/FLOAT32, but this is only supported for GDAL drivers.",
-                            "msOutputFormatValidate()", format->name );
-            else
-                msDebug( "OUTPUTFORMAT %s has IMAGEMODE BYTE/INT16/FLOAT32, but this is only supported for GDAL drivers.",
-                         format->name );
-        }
-
-        if( format->renderer != MS_RENDER_WITH_RAWDATA ) /* see bug 724 */
-            format->renderer = MS_RENDER_WITH_RAWDATA;
+      format->imagemode = MS_IMAGEMODE_RGB;
+      result = MS_FALSE;
     }
-    
-    if(format->renderer == MS_RENDER_WITH_GD && format->imagemode != MS_IMAGEMODE_PC256) {
-       if( issue_error )
-           msSetError( MS_MISCERR,
-                       "OUTPUTFORMAT %s has IMAGEMODE RGB/RGBA, which is not supported for GD drivers.",
-                       "msOutputFormatValidate()", format->name );
-       else
-           msDebug( "OUTPUTFORMAT %s has IMAGEMODE RGB/RGBA, which is not supported for GD drivers.",
+  }
+
+  if( format->transparent && format->imagemode == MS_IMAGEMODE_RGB ) {
+    if( issue_error )
+      msSetError( MS_MISCERR,
+                  "OUTPUTFORMAT %s has TRANSPARENT set ON, but an IMAGEMODE\n"
+                  "of RGB instead of RGBA.  Changing imagemode to RGBA.\n",
+                  "msOutputFormatValidate()", format->name );
+    else
+      msDebug("OUTPUTFORMAT %s has TRANSPARENT set ON, but an IMAGEMODE\n"
+              "of RGB instead of RGBA.  Changing imagemode to RGBA.\n",
+              format->name );
+
+    format->imagemode = MS_IMAGEMODE_RGBA;
+    result = MS_FALSE;
+  }
+
+  /* Special checking around RAWMODE image modes. */
+  if( format->imagemode == MS_IMAGEMODE_INT16
+      || format->imagemode == MS_IMAGEMODE_FLOAT32
+      || format->imagemode == MS_IMAGEMODE_BYTE ) {
+    if( strncmp(format->driver,"GDAL/",5) != 0 ) {
+      result = MS_FALSE;
+      if( issue_error )
+        msSetError( MS_MISCERR,
+                    "OUTPUTFORMAT %s has IMAGEMODE BYTE/INT16/FLOAT32, but this is only supported for GDAL drivers.",
+                    "msOutputFormatValidate()", format->name );
+      else
+        msDebug( "OUTPUTFORMAT %s has IMAGEMODE BYTE/INT16/FLOAT32, but this is only supported for GDAL drivers.",
                  format->name );
-       format->renderer = MS_RENDER_WITH_AGG;
     }
 
-    return result;
+    if( format->renderer != MS_RENDER_WITH_RAWDATA ) /* see bug 724 */
+      format->renderer = MS_RENDER_WITH_RAWDATA;
+  }
+#ifdef USE_GD
+  if(format->renderer == MS_RENDER_WITH_GD && format->imagemode != MS_IMAGEMODE_PC256) {
+    if( issue_error )
+      msSetError( MS_MISCERR,
+                  "OUTPUTFORMAT %s has IMAGEMODE RGB/RGBA, which is not supported for GD drivers.",
+                  "msOutputFormatValidate()", format->name );
+    else
+      msDebug( "OUTPUTFORMAT %s has IMAGEMODE RGB/RGBA, which is not supported for GD drivers.",
+               format->name );
+    format->renderer = MS_RENDER_WITH_AGG;
+  }
+#endif
+
+  return result;
 }
 
 /************************************************************************/
 /*                     msInitializeRendererVTable()                     */
 /************************************************************************/
 
-int msInitializeRendererVTable(outputFormatObj *format) {
-    assert(format);
-    if(format->vtable) {
-       return MS_SUCCESS;
-    }
-    format->vtable = (rendererVTableObj*)calloc(1,sizeof(rendererVTableObj));
-    
-    msInitializeDummyRenderer(format->vtable);
-    
-    switch(format->renderer) {
-        case MS_RENDER_WITH_AGG:
-            return msPopulateRendererVTableAGG(format->vtable);
-        case MS_RENDER_WITH_GD:
-            return msPopulateRendererVTableGD(format->vtable);
-        case MS_RENDER_WITH_CAIRO_RASTER:
-            return msPopulateRendererVTableCairoRaster(format->vtable);
-        case MS_RENDER_WITH_CAIRO_PDF:
-            return msPopulateRendererVTableCairoPDF(format->vtable);
-        case MS_RENDER_WITH_CAIRO_SVG:
-            return msPopulateRendererVTableCairoSVG(format->vtable);
-        case MS_RENDER_WITH_OGL:
-            return msPopulateRendererVTableOGL(format->vtable);
-        case MS_RENDER_WITH_KML:
-            return msPopulateRendererVTableKML(format->vtable);    
-        case MS_RENDER_WITH_OGR:
-            return msPopulateRendererVTableOGR(format->vtable);    
-        default:
-            msSetError(MS_MISCERR, "unsupported RendererVtable renderer %d",
-                    "msInitializeRendererVTable()",format->renderer);
-            return MS_FAILURE;            
-    }
-    /* this code should never be executed */
-    return MS_FAILURE;
+int msInitializeRendererVTable(outputFormatObj *format)
+{
+  assert(format);
+  if(format->vtable) {
+    return MS_SUCCESS;
+  }
+  format->vtable = (rendererVTableObj*)calloc(1,sizeof(rendererVTableObj));
+
+  msInitializeDummyRenderer(format->vtable);
+
+  switch(format->renderer) {
+    case MS_RENDER_WITH_AGG:
+      return msPopulateRendererVTableAGG(format->vtable);
+#ifdef USE_GD
+    case MS_RENDER_WITH_GD:
+      return msPopulateRendererVTableGD(format->vtable);
+#endif
+    case MS_RENDER_WITH_CAIRO_RASTER:
+      return msPopulateRendererVTableCairoRaster(format->vtable);
+    case MS_RENDER_WITH_CAIRO_PDF:
+      return msPopulateRendererVTableCairoPDF(format->vtable);
+    case MS_RENDER_WITH_CAIRO_SVG:
+      return msPopulateRendererVTableCairoSVG(format->vtable);
+    case MS_RENDER_WITH_OGL:
+      return msPopulateRendererVTableOGL(format->vtable);
+    case MS_RENDER_WITH_KML:
+      return msPopulateRendererVTableKML(format->vtable);
+    case MS_RENDER_WITH_OGR:
+      return msPopulateRendererVTableOGR(format->vtable);
+    default:
+      msSetError(MS_MISCERR, "unsupported RendererVtable renderer %d",
+                 "msInitializeRendererVTable()",format->renderer);
+      return MS_FAILURE;
+  }
+  /* this code should never be executed */
+  return MS_FAILURE;
 }
 
diff --git a/mapows.c b/mapows.c
index deee4ec..2bb323b 100644
--- a/mapows.c
+++ b/mapows.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -31,11 +31,171 @@
 #include "maptime.h"
 #include "maptemplate.h"
 
+#if defined(USE_LIBXML2)
+#include "maplibxml2.h"
+#elif defined(USE_GDAL)
+#include "cpl_minixml.h"
+#include "cpl_error.h"
+#endif
+
 #include <ctype.h> /* isalnum() */
-#include <stdarg.h> 
+#include <stdarg.h>
 #include <assert.h>
 
-MS_CVSID("$Id$")
+
+
+/*
+** msOWSInitRequestObj() initializes an owsRequestObj; i.e: sets
+** all internal pointers to NULL.
+*/
+static void msOWSInitRequestObj(owsRequestObj *ows_request)
+{
+  ows_request->numlayers = 0;
+  ows_request->enabled_layers = NULL;
+
+  ows_request->service = NULL;
+  ows_request->version = NULL;
+  ows_request->request = NULL;
+  ows_request->document = NULL;
+}
+
+/*
+** msOWSClearRequestObj() releases all resources associated with an
+** owsRequestObj.
+*/
+static void msOWSClearRequestObj(owsRequestObj *ows_request)
+{
+  msFree(ows_request->enabled_layers);
+  msFree(ows_request->service);
+  msFree(ows_request->version);
+  msFree(ows_request->request);
+  if(ows_request->document) {
+#if defined(USE_LIBXML2)
+    xmlFreeDoc(ows_request->document);
+    xmlCleanupParser();
+#elif defined(USE_GDAL)
+    CPLDestroyXMLNode(ows_request->document);
+#endif
+  }
+}
+
+/*
+** msOWSPreParseRequest() parses a cgiRequestObj either with GET/KVP
+** or with POST/XML. Only SERVICE, VERSION (or WMTVER) and REQUEST are
+** being determined, all WxS (or SOS) specific parameters are parsed
+** within the according handler.
+** The results are saved within an owsRequestObj. If the request was
+** transmitted with POST/XML, either the document (if compiled with
+** libxml2) or the root CPLXMLNode is saved to the ows_request->document
+** field.
+** Returns MS_SUCCESS upon success, MS_FAILURE if severe errors occurred
+** or MS_DONE, if the service could not be determined.
+*/
+static int msOWSPreParseRequest(cgiRequestObj *request,
+                                owsRequestObj *ows_request)
+{
+  /* decide if KVP or XML */
+  if (request->type == MS_GET_REQUEST) {
+    int i;
+    /* parse KVP parameters service, version and request */
+    for (i = 0; i < request->NumParams; ++i) {
+      if (EQUAL(request->ParamNames[i], "SERVICE")) {
+        ows_request->service = msStrdup(request->ParamValues[i]);
+      } else if (EQUAL(request->ParamNames[i], "VERSION")
+                 || EQUAL(request->ParamNames[i], "WMTVER")) { /* for WMS */
+        ows_request->version = msStrdup(request->ParamValues[i]);
+      } else if (EQUAL(request->ParamNames[i], "REQUEST")) {
+        ows_request->request = msStrdup(request->ParamValues[i]);
+      }
+
+      /* stop if we have all necessary parameters */
+      if(ows_request->service && ows_request->version && ows_request->request) {
+        break;
+      }
+    }
+  } else if (request->type == MS_POST_REQUEST) {
+#if defined(USE_LIBXML2)
+    xmlNodePtr root = NULL;
+#elif defined(USE_GDAL)
+    CPLXMLNode *temp;
+#endif
+    if (!request->postrequest || !strlen(request->postrequest)) {
+      msSetError(MS_OWSERR, "POST request is empty.",
+                 "msOWSPreParseRequest()");
+      return MS_FAILURE;
+    }
+#if defined(USE_LIBXML2)
+    /* parse to DOM-Structure with libxml2 and get the root element */
+    ows_request->document = xmlParseMemory(request->postrequest,
+                                           strlen(request->postrequest));
+    if (ows_request->document == NULL
+        || (root = xmlDocGetRootElement(ows_request->document)) == NULL) {
+      xmlErrorPtr error = xmlGetLastError();
+      msSetError(MS_OWSERR, "XML parsing error: %s",
+                 "msOWSPreParseRequest()", error->message);
+      return MS_FAILURE;
+    }
+
+    /* Get service, version and request from root */
+    ows_request->service = (char *) xmlGetProp(root, BAD_CAST "service");
+    ows_request->version = (char *) xmlGetProp(root, BAD_CAST "version");
+    ows_request->request = msStrdup((char *) root->name);
+
+#elif defined(USE_GDAL)
+    /* parse with CPLXML */
+    ows_request->document = CPLParseXMLString(request->postrequest);
+    if (ows_request->document == NULL) {
+      msSetError(MS_OWSERR, "XML parsing error: %s",
+                 "msOWSPreParseRequest()", CPLGetLastErrorMsg());
+      return MS_FAILURE;
+    }
+
+    /* remove all namespaces */
+    CPLStripXMLNamespace(ows_request->document, NULL, 1);
+    for (temp = ows_request->document;
+         temp != NULL;
+         temp = temp->psNext) {
+
+      if (temp->eType == CXT_Element) {
+        const char *service, *version;
+        ows_request->request = msStrdup(temp->pszValue);
+
+        if ((service = CPLGetXMLValue(temp, "service", NULL)) != NULL) {
+          ows_request->service = msStrdup(service);
+        }
+        if ((version = CPLGetXMLValue(temp, "version", NULL)) != NULL) {
+          ows_request->version = msStrdup(version);
+        }
+        continue;
+      }
+    }
+#else
+    /* could not parse XML since no parser was compiled */
+    msSetError(MS_OWSERR, "Could not parse the POST XML since MapServer"
+               "was not compiled with libxml2 or GDAL.",
+               "msOWSPreParseRequest()");
+    return MS_FAILURE;
+#endif /* defined(USE_LIBXML2) */
+  } else {
+    msSetError(MS_OWSERR, "Unknown request method. Use either GET or POST.",
+               "msOWSPreParseRequest()");
+    return MS_FAILURE;
+  }
+
+  /* certain WMS requests do not require the service parameter */
+  /* see: http://trac.osgeo.org/mapserver/ticket/2531          */
+  if (ows_request->service == NULL
+      && ows_request->request != NULL) {
+    if (EQUAL(ows_request->request, "GetMap")
+        || EQUAL(ows_request->request, "GetFeatureInfo")) {
+      ows_request->service = msStrdup("WMS");
+    } else { /* service could not be determined */
+      return MS_DONE;
+    }
+  }
+
+  return MS_SUCCESS;
+}
 
 /*
 ** msOWSDispatch() is the entry point for any OWS request (WMS, WFS, ...)
@@ -43,122 +203,84 @@ MS_CVSID("$Id$")
 **   on success, or MS_FAILURE on failure.
 ** - If force_ows_mode is true then an exception will be produced if the
 **   request is not recognized as a valid request.
-** - If force_ows_mode is false and this does not appear to be a valid OWS 
-**   request then MS_DONE is returned and MapServer is expected to process 
+** - If force_ows_mode is false and this does not appear to be a valid OWS
+**   request then MS_DONE is returned and MapServer is expected to process
 **   this as a regular MapServer (traditional CGI) request.
 */
 int msOWSDispatch(mapObj *map, cgiRequestObj *request, int ows_mode)
 {
-    int i, status = MS_DONE;
-    const char *service=NULL;
-    int force_ows_mode = 0;
-    owsRequestObj ows_request;
+  int status = MS_DONE, force_ows_mode = 0;
+  owsRequestObj ows_request;
 
-    if (!request)
-      return status;
+  if (!request) {
+    return status;
+  }
 
-    if (ows_mode == OWS || ows_mode == WFS)
-      force_ows_mode = 1;
-    
-    ows_request.numlayers = 0;
-    ows_request.enabled_layers = NULL;
-    
-    for( i=0; i<request->NumParams; i++ ) 
-    {
-        if(strcasecmp(request->ParamNames[i], "SERVICE") == 0)
-            service = request->ParamValues[i];
-    }
+  force_ows_mode = (ows_mode == OWS || ows_mode == WFS);
 
-#ifdef USE_WMS_SVR
-    /* Note: SERVICE param did not exist in WMS 1.0.0, it was added only in WMS 1.1.0,
-     * so we need to let msWMSDispatch check for known REQUESTs even if SERVICE is not set.
-     */
-    if ((status = msWMSDispatch(map, request, &ows_request, MS_FALSE)) != MS_DONE )
-    {
-        msFree(ows_request.enabled_layers);
-        return status;
+  msOWSInitRequestObj(&ows_request);
+  switch(msOWSPreParseRequest(request, &ows_request)) {
+    case MS_FAILURE: /* a severe error occurred */
+      return MS_FAILURE;
+    case MS_DONE:
+      /* OWS Service could not be determined              */
+      /* continue for now                                 */
+      status = MS_DONE;
+  }
+
+  if (ows_request.service == NULL) {
+    /* exit if service is not set */
+    if(force_ows_mode) {
+      msSetError( MS_MISCERR,
+                  "OWS Common exception: exceptionCode=MissingParameterValue, locator=SERVICE, ExceptionText=SERVICE parameter missing.",
+                  "msOWSDispatch()");
+      status = MS_FAILURE;
+    } else {
+      status = MS_DONE;
     }
+  } else if (EQUAL(ows_request.service, "WMS")) {
+#ifdef USE_WMS_SVR
+    status = msWMSDispatch(map, request, &ows_request, MS_FALSE);
 #else
-    if( service != NULL && strcasecmp(service,"WMS") == 0 )
-        msSetError( MS_WMSERR, 
-                    "SERVICE=WMS requested, but WMS support not configured in MapServer.", 
-                    "msOWSDispatch()" );
+    msSetError( MS_WMSERR,
+                "SERVICE=WMS requested, but WMS support not configured in MapServer.",
+                "msOWSDispatch()" );
 #endif
-
+  } else if (EQUAL(ows_request.service, "WFS")) {
 #ifdef USE_WFS_SVR
-    /* Note: WFS supports POST requests, so the SERVICE param may only be in the post data
-     * and not be present in the GET URL
-     */
-    if ((status = msWFSDispatch(map, request, &ows_request, (ows_mode == WFS))) != MS_DONE )
-    {
-        msFree(ows_request.enabled_layers);
-        return status;
-    }
-
+    status = msWFSDispatch(map, request, &ows_request, (ows_mode == WFS));
 #else
-    if( service != NULL && strcasecmp(service,"WFS") == 0 )
-        msSetError( MS_WFSERR, 
-                    "SERVICE=WFS requested, but WFS support not configured in MapServer.", 
-                    "msOWSDispatch()" );
+    msSetError( MS_WFSERR,
+                "SERVICE=WFS requested, but WFS support not configured in MapServer.",
+                "msOWSDispatch()" );
 #endif
-
+  } else if (EQUAL(ows_request.service, "WCS")) {
 #ifdef USE_WCS_SVR
-    if ((status = msWCSDispatch(map, request, &ows_request)) != MS_DONE )
-    {
-        msFree(ows_request.enabled_layers);
-        return status;
-    }
+    status = msWCSDispatch(map, request, &ows_request);
 #else
-    if( service != NULL && strcasecmp(service,"WCS") == 0 )
-        msSetError( MS_WCSERR, 
-                    "SERVICE=WCS requested, but WCS support not configured in MapServer.", 
-                    "msOWSDispatch()" );
+    msSetError( MS_WCSERR,
+                "SERVICE=WCS requested, but WCS support not configured in MapServer.",
+                "msOWSDispatch()" );
 #endif
-
+  } else if (EQUAL(ows_request.service, "SOS")) {
 #ifdef USE_SOS_SVR
-    if ((status = msSOSDispatch(map, request, &ows_request)) != MS_DONE )
-    {
-        msFree(ows_request.enabled_layers);
-        return status;
-    }
+    status = msSOSDispatch(map, request, &ows_request);
 #else
-    if( service != NULL && strcasecmp(service,"SOS") == 0 )
-        msSetError( MS_SOSERR, 
-                    "SERVICE=SOS requested, but SOS support not configured in MapServer.", 
-                    "msOWSDispatch()" );
+    msSetError( MS_SOSERR,
+                "SERVICE=SOS requested, but SOS support not configured in MapServer.",
+                "msOWSDispatch()" );
 #endif
+  } else if(force_ows_mode) {
+    msSetError( MS_MISCERR,
+                "OWS Common exception: exceptionCode=InvalidParameterValue, locator=SERVICE, ExceptionText=SERVICE parameter value invalid.",
+                "msOWSDispatch()");
+    status = MS_FAILURE;
+  }
 
-    if (force_ows_mode) {
-        if (service == NULL)
-            /* Here we should return real OWS Common exceptions... once 
-             * we have a proper exception handler in mapowscommon.c 
-             */
-            msSetError( MS_MISCERR,
-                        "OWS Common exception: exceptionCode=MissingParameterValue, locator=SERVICE, ExceptionText=SERVICE parameter missing.", 
-                        "msOWSDispatch()");
-        else
-            /* Here we should return real OWS Common exceptions... once 
-             * we have a proper exception handler in mapowscommon.c 
-             */
-            msSetError( MS_MISCERR,
-                        "OWS Common exception: exceptionCode=InvalidParameterValue, locator=SERVICE, ExceptionText=SERVICE parameter value invalid.", 
-                        "msOWSDispatch()");
-        
-        /* Force mapserv to report the error by returning MS_FAILURE. 
-         * The day we have a proper exception handler here then we should 
-         * return MS_SUCCESS since the exception will have been processed 
-         * the OWS way, which is a success as far as mapserv is concerned 
-         */
-        msFree(ows_request.enabled_layers);
-        return MS_FAILURE; 
-    }
-
-    msFree(ows_request.enabled_layers);
-    return MS_DONE;  /* Not a WMS/WFS request... let MapServer handle it 
-                      * since we're not in force_ows_mode*/
+  msOWSClearRequestObj(&ows_request);
+  return status;
 }
 
-
 /*
 ** msOWSRequestIsEnabled()
 **
@@ -169,80 +291,75 @@ int msOWSDispatch(mapObj *map, cgiRequestObj *request, int ows_mode)
 ** namespaces is NULL then this function just does a regular metadata
 ** lookup. If check_all_layers is set to MS_TRUE, the function will check
 ** all layers to see if the request is enable. (returns as soon as one is found) */
-int msOWSRequestIsEnabled(mapObj *map, layerObj *layer, 
+int msOWSRequestIsEnabled(mapObj *map, layerObj *layer,
                           const char *namespaces, const char *request, int check_all_layers)
 {
-    int disabled = MS_FALSE; /* explicitly disabled flag */
-    const char *enable_request;
-    
-    if (request == NULL)
-        return MS_FALSE;
-
-    /* First, we check in the layer metadata */
-    if (layer && check_all_layers == MS_FALSE) 
-    {
-        enable_request = msOWSLookupMetadata(&layer->metadata, namespaces, "enable_request");
-        if (msOWSParseRequestMetadata(enable_request, request, &disabled))
-            return MS_TRUE;
-        if (disabled) return MS_FALSE;
-        
-        enable_request = msOWSLookupMetadata(&layer->metadata, "O", "enable_request");
-        if (msOWSParseRequestMetadata(enable_request, request, &disabled))
-            return MS_TRUE;
-        if (disabled) return MS_FALSE;
-    }
+  int disabled = MS_FALSE; /* explicitly disabled flag */
+  const char *enable_request;
+
+  if (request == NULL)
+    return MS_FALSE;
+
+  /* First, we check in the layer metadata */
+  if (layer && check_all_layers == MS_FALSE) {
+    enable_request = msOWSLookupMetadata(&layer->metadata, namespaces, "enable_request");
+    if (msOWSParseRequestMetadata(enable_request, request, &disabled))
+      return MS_TRUE;
+    if (disabled) return MS_FALSE;
+
+    enable_request = msOWSLookupMetadata(&layer->metadata, "O", "enable_request");
+    if (msOWSParseRequestMetadata(enable_request, request, &disabled))
+      return MS_TRUE;
+    if (disabled) return MS_FALSE;
+  }
+
+  if (map && check_all_layers == MS_FALSE) {
+    /* then we check in the map metadata */
+    enable_request = msOWSLookupMetadata(&map->web.metadata, namespaces, "enable_request");
+    if (msOWSParseRequestMetadata(enable_request, request, &disabled))
+      return MS_TRUE;
+    if (disabled) return MS_FALSE;
 
-    if (map && check_all_layers == MS_FALSE)
-    {
-        /* then we check in the map metadata */
-        enable_request = msOWSLookupMetadata(&map->web.metadata, namespaces, "enable_request");
-        if (msOWSParseRequestMetadata(enable_request, request, &disabled))
-            return MS_TRUE;
-        if (disabled) return MS_FALSE;
-        
-        enable_request = msOWSLookupMetadata(&map->web.metadata, "O", "enable_request");
-        if (msOWSParseRequestMetadata(enable_request, request, &disabled))
-            return MS_TRUE;
-        if (disabled) return MS_FALSE;
+    enable_request = msOWSLookupMetadata(&map->web.metadata, "O", "enable_request");
+    if (msOWSParseRequestMetadata(enable_request, request, &disabled))
+      return MS_TRUE;
+    if (disabled) return MS_FALSE;
+  }
+
+  if (map && (map->numlayers > 0) && check_all_layers == MS_TRUE) {
+    int i, globally_enabled = MS_FALSE;
+    enable_request = msOWSLookupMetadata(&map->web.metadata, namespaces, "enable_request");
+    globally_enabled = msOWSParseRequestMetadata(enable_request, request, &disabled);
+
+    if (!globally_enabled && !disabled) {
+      enable_request = msOWSLookupMetadata(&map->web.metadata, "O", "enable_request");
+      globally_enabled = msOWSParseRequestMetadata(enable_request, request, &disabled);
     }
 
-    if (map && (map->numlayers > 0) && check_all_layers == MS_TRUE)
-    {
-        int i, globally_enabled = MS_FALSE;
-        enable_request = msOWSLookupMetadata(&map->web.metadata, namespaces, "enable_request");
-        globally_enabled = msOWSParseRequestMetadata(enable_request, request, &disabled);
-        
-        if (!globally_enabled && !disabled)
-        {
-            enable_request = msOWSLookupMetadata(&map->web.metadata, "O", "enable_request");
-            globally_enabled = msOWSParseRequestMetadata(enable_request, request, &disabled);
-        }
+    /* Check all layers */
+    for(i=0; i<map->numlayers; i++) {
+      int result = MS_FALSE;
+      layerObj *lp;
+      lp = (GET_LAYER(map, i));
 
-        /* Check all layers */
-        for(i=0; i<map->numlayers; i++)
-        {
-            int result = MS_FALSE;
-            layerObj *lp;
-            lp = (GET_LAYER(map, i));
-
-            enable_request = msOWSLookupMetadata(&lp->metadata, namespaces, "enable_request");
-            result = msOWSParseRequestMetadata(enable_request, request, &disabled);
-            if (!result && disabled) continue; /* if the request has been explicitly set to disabled, continue */
-            
-            if (!result && !disabled) /* if the request has not been found in the wms metadata, */
-            {                         /* check the ows namespace  */
-            
-                enable_request = msOWSLookupMetadata(&lp->metadata, "O", "enable_request");
-                result = msOWSParseRequestMetadata(enable_request, request, &disabled);
-                if (!result && disabled) continue;
-            }
-            
-            if (result || (!disabled && globally_enabled))
-                return MS_TRUE;
-        }
+      enable_request = msOWSLookupMetadata(&lp->metadata, namespaces, "enable_request");
+      result = msOWSParseRequestMetadata(enable_request, request, &disabled);
+      if (!result && disabled) continue; /* if the request has been explicitly set to disabled, continue */
+
+      if (!result && !disabled) { /* if the request has not been found in the wms metadata, */
+        /* check the ows namespace  */
+
+        enable_request = msOWSLookupMetadata(&lp->metadata, "O", "enable_request");
+        result = msOWSParseRequestMetadata(enable_request, request, &disabled);
+        if (!result && disabled) continue;
+      }
+
+      if (result || (!disabled && globally_enabled))
+        return MS_TRUE;
     }
+  }
 
-    return MS_FALSE;
+  return MS_FALSE;
 }
 
 /*
@@ -250,143 +367,135 @@ int msOWSRequestIsEnabled(mapObj *map, layerObj *layer,
 **
 ** Check if the layers are visible for a specific OWS request.
 **
-** 'namespaces' is a string with a letter for each namespace to lookup 
+** 'namespaces' is a string with a letter for each namespace to lookup
 ** in the order they should be looked up. e.g. "MO" to lookup wms_ and ows_
 ** If namespaces is NULL then this function just does a regular metadata
 ** lookup.
 **
 ** Generates an array of the layer ids enabled.
 */
-void msOWSRequestLayersEnabled(mapObj *map, const char *namespaces, 
+void msOWSRequestLayersEnabled(mapObj *map, const char *namespaces,
                                const char *request, owsRequestObj *ows_request)
 {
-    int disabled = MS_FALSE; /* explicitly disabled flag */
-    int globally_enabled = MS_FALSE;
-    const char *enable_request;
+  int disabled = MS_FALSE; /* explicitly disabled flag */
+  int globally_enabled = MS_FALSE;
+  const char *enable_request;
 
-    if (ows_request->numlayers > 0) 
-        msFree(ows_request->enabled_layers);
-    
-    ows_request->numlayers = 0;
-    ows_request->enabled_layers = NULL;
+  if (ows_request->numlayers > 0)
+    msFree(ows_request->enabled_layers);
 
-    if (request == NULL || (map == NULL) || (map->numlayers <= 0))
-        return;
+  ows_request->numlayers = 0;
+  ows_request->enabled_layers = NULL;
 
-    enable_request = msOWSLookupMetadata(&map->web.metadata, namespaces, "enable_request");
+  if (request == NULL || (map == NULL) || (map->numlayers <= 0))
+    return;
+
+  enable_request = msOWSLookupMetadata(&map->web.metadata, namespaces, "enable_request");
+  globally_enabled = msOWSParseRequestMetadata(enable_request, request, &disabled);
+
+  if (!globally_enabled && !disabled) {
+    enable_request = msOWSLookupMetadata(&map->web.metadata, "O", "enable_request");
     globally_enabled = msOWSParseRequestMetadata(enable_request, request, &disabled);
+  }
 
-    if (!globally_enabled && !disabled)
-    {
-        enable_request = msOWSLookupMetadata(&map->web.metadata, "O", "enable_request");
-        globally_enabled = msOWSParseRequestMetadata(enable_request, request, &disabled);
-    }
+  if (map->numlayers) {
+    int i, layers_size = map->numlayers; /* for most of cases, this will be relatively small */
 
-    if (map->numlayers)
-    {
-        int i, layers_size = map->numlayers; //for most of cases, this will be relatively small
-
-        ows_request->enabled_layers = (int*)msSmallMalloc(sizeof(int)*layers_size);
-
-        for(i=0; i<map->numlayers; i++)
-        {
-            int result = MS_FALSE;
-            layerObj *lp;
-            lp = (GET_LAYER(map, i));
-
-            enable_request = msOWSLookupMetadata(&lp->metadata, namespaces, "enable_request");
-            result = msOWSParseRequestMetadata(enable_request, request, &disabled);
-            if (!result && disabled) continue; /* if the request has been explicitly set to disabled, continue */
-            
-            if (!result && !disabled) /* if the request has not been found in the wms metadata, */
-            {                         /* check the ows namespace  */
-            
-                enable_request = msOWSLookupMetadata(&lp->metadata, "O", "enable_request");
-                result = msOWSParseRequestMetadata(enable_request, request, &disabled);
-                if (!result && disabled) continue;
-            }
-            
-            if (result || (!disabled && globally_enabled))
-            {
-                ows_request->enabled_layers[ows_request->numlayers] = lp->index;
-                ows_request->numlayers++;
-            }
-        }
+    ows_request->enabled_layers = (int*)msSmallMalloc(sizeof(int)*layers_size);
 
-        if (ows_request->numlayers == 0) 
-        {
-            msFree(ows_request->enabled_layers);
-            ows_request->enabled_layers = NULL;
-        }
+    for(i=0; i<map->numlayers; i++) {
+      int result = MS_FALSE;
+      layerObj *lp;
+      lp = (GET_LAYER(map, i));
+
+      enable_request = msOWSLookupMetadata(&lp->metadata, namespaces, "enable_request");
+      result = msOWSParseRequestMetadata(enable_request, request, &disabled);
+      if (!result && disabled) continue; /* if the request has been explicitly set to disabled, continue */
+
+      if (!result && !disabled) { /* if the request has not been found in the wms metadata, */
+        /* check the ows namespace  */
+
+        enable_request = msOWSLookupMetadata(&lp->metadata, "O", "enable_request");
+        result = msOWSParseRequestMetadata(enable_request, request, &disabled);
+        if (!result && disabled) continue;
+      }
+
+      if (result || (!disabled && globally_enabled)) {
+        ows_request->enabled_layers[ows_request->numlayers] = lp->index;
+        ows_request->numlayers++;
+      }
+    }
+
+    if (ows_request->numlayers == 0) {
+      msFree(ows_request->enabled_layers);
+      ows_request->enabled_layers = NULL;
     }
+  }
 }
 
-/* msOWSParseRequestMetadata 
- *  
+/* msOWSParseRequestMetadata
+ *
  * This function parse a enable_request metadata string and check if the
  * given request is present and enabled.
  */
 int msOWSParseRequestMetadata(const char *metadata, const char *request, int *disabled)
 {
-    char requestBuffer[32];
-    int wordFlag = MS_FALSE;
-    int disableFlag = MS_FALSE;
-    int allFlag = MS_FALSE;
-    char *bufferPtr, *ptr = NULL;
-    int i;
-    size_t len = 0;
+  char requestBuffer[32];
+  int wordFlag = MS_FALSE;
+  int disableFlag = MS_FALSE;
+  int allFlag = MS_FALSE;
+  char *bufferPtr, *ptr = NULL;
+  int i;
+  size_t len = 0;
 
-    *disabled = MS_FALSE;
-    
-    if (metadata == NULL)
-        return MS_FALSE;
+  *disabled = MS_FALSE;
 
-    ptr = (char*)metadata;
-    len = strlen(ptr);
-    requestBuffer[0] = '\0';
-    bufferPtr = requestBuffer;
-    
-    for (i=0; i<=len;++i,++ptr) {
-        
-        if (!wordFlag && isspace(*ptr))
-            continue;
-        
-        wordFlag = MS_TRUE;
-        
-        if (*ptr == '!') {
-            disableFlag = MS_TRUE;
-            continue;
-        }
-        else if ( (*ptr == ' ') || (*ptr != '\0' && ptr[1] == '\0')) { /* end of word */
-            if (ptr[1] == '\0' && *ptr != ' ') {
-                *bufferPtr = *ptr;
-                ++bufferPtr;
-            }
-            
-            *bufferPtr = '\0'; 
-            if (strcasecmp(request, requestBuffer) == 0) {
-                *disabled =  MS_TRUE; /* explicitly found, will stop the process in msOWSRequestIsEnabled() */
-                return (disableFlag ? MS_FALSE:MS_TRUE);
-            }
-            else {
-                if (strcmp("*", requestBuffer) == 0) { /* check if we read the all flag */
-                    if (disableFlag)
-                        *disabled =  MS_TRUE;
-                    allFlag = disableFlag ? MS_FALSE:MS_TRUE;
-                }
-                /* reset flags */
-                wordFlag = MS_FALSE;
-                disableFlag = MS_FALSE;
-                bufferPtr = requestBuffer;
-            }
+  if (metadata == NULL)
+    return MS_FALSE;
+
+  ptr = (char*)metadata;
+  len = strlen(ptr);
+  requestBuffer[0] = '\0';
+  bufferPtr = requestBuffer;
+
+  for (i=0; i<=len; ++i,++ptr) {
+
+    if (!wordFlag && isspace(*ptr))
+      continue;
+
+    wordFlag = MS_TRUE;
+
+    if (*ptr == '!') {
+      disableFlag = MS_TRUE;
+      continue;
+    } else if ( (*ptr == ' ') || (*ptr != '\0' && ptr[1] == '\0')) { /* end of word */
+      if (ptr[1] == '\0' && *ptr != ' ') {
+        *bufferPtr = *ptr;
+        ++bufferPtr;
+      }
+
+      *bufferPtr = '\0';
+      if (strcasecmp(request, requestBuffer) == 0) {
+        *disabled =  MS_TRUE; /* explicitly found, will stop the process in msOWSRequestIsEnabled() */
+        return (disableFlag ? MS_FALSE:MS_TRUE);
+      } else {
+        if (strcmp("*", requestBuffer) == 0) { /* check if we read the all flag */
+          if (disableFlag)
+            *disabled =  MS_TRUE;
+          allFlag = disableFlag ? MS_FALSE:MS_TRUE;
         }
-        else {
-            *bufferPtr = *ptr;
-            ++bufferPtr;
-        } 
+        /* reset flags */
+        wordFlag = MS_FALSE;
+        disableFlag = MS_FALSE;
+        bufferPtr = requestBuffer;
+      }
+    } else {
+      *bufferPtr = *ptr;
+      ++bufferPtr;
     }
-    
-    return allFlag;
+  }
+
+  return allFlag;
 }
 
 /*
@@ -394,76 +503,101 @@ int msOWSParseRequestMetadata(const char *metadata, const char *request, int *di
 **
 ** Attempts to lookup a given metadata name in multiple OWS namespaces.
 **
-** 'namespaces' is a string with a letter for each namespace to lookup 
+** 'namespaces' is a string with a letter for each namespace to lookup
 ** in the order they should be looked up. e.g. "MO" to lookup wms_ and ows_
 ** If namespaces is NULL then this function just does a regular metadata
 ** lookup.
 */
-const char *msOWSLookupMetadata(hashTableObj *metadata, 
+const char *msOWSLookupMetadata(hashTableObj *metadata,
                                 const char *namespaces, const char *name)
 {
-    const char *value = NULL;
+  const char *value = NULL;
 
-    if (namespaces == NULL)
-    {
-        value = msLookupHashTable(metadata, (char*)name);
-    }
-    else
-    {
-        char buf[100] = "ows_";
-
-        strlcpy(buf+4, name, 96);
-
-        while (value == NULL && *namespaces != '\0')
-        {
-            switch (*namespaces)
-            {
-              case 'O':         /* ows_... */
-                buf[0] = 'o';
-                buf[1] = 'w';
-                buf[2] = 's';
-                break;
-              case 'M':         /* wms_... */
-                buf[0] = 'w';
-                buf[1] = 'm';
-                buf[2] = 's';
-                break;
-              case 'F':         /* wfs_... */
-                buf[0] = 'w';
-                buf[1] = 'f';
-                buf[2] = 's';
-                break;
-              case 'C':         /* wcs_... */
-                buf[0] = 'w';
-                buf[1] = 'c';
-                buf[2] = 's';
-                break;
-              case 'G':         /* gml_... */
-                buf[0] = 'g';
-                buf[1] = 'm';
-                buf[2] = 'l';
-                break;
-                case 'S':         /* sos_... */
-                buf[0] = 's';
-                buf[1] = 'o';
-                buf[2] = 's';
-                break;
-              default:
-                /* We should never get here unless an invalid code (typo) is */
-                /* present in the code, but since this happened before... */
-                msSetError(MS_WMSERR, 
-                           "Unsupported metadata namespace code (%c).",
-                           "msOWSLookupMetadata()", *namespaces );
-                assert(MS_FALSE);
-                return NULL;
-            }
-
-            value = msLookupHashTable(metadata, buf);
-            namespaces++;
-        }
+  if (namespaces == NULL) {
+    value = msLookupHashTable(metadata, (char*)name);
+  } else {
+    char buf[100] = "ows_";
+
+    strlcpy(buf+4, name, 96);
+
+    while (value == NULL && *namespaces != '\0') {
+      switch (*namespaces) {
+        case 'O':         /* ows_... */
+          buf[0] = 'o';
+          buf[1] = 'w';
+          buf[2] = 's';
+          break;
+        case 'M':         /* wms_... */
+          buf[0] = 'w';
+          buf[1] = 'm';
+          buf[2] = 's';
+          break;
+        case 'F':         /* wfs_... */
+          buf[0] = 'w';
+          buf[1] = 'f';
+          buf[2] = 's';
+          break;
+        case 'C':         /* wcs_... */
+          buf[0] = 'w';
+          buf[1] = 'c';
+          buf[2] = 's';
+          break;
+        case 'G':         /* gml_... */
+          buf[0] = 'g';
+          buf[1] = 'm';
+          buf[2] = 'l';
+          break;
+        case 'S':         /* sos_... */
+          buf[0] = 's';
+          buf[1] = 'o';
+          buf[2] = 's';
+          break;
+        default:
+          /* We should never get here unless an invalid code (typo) is */
+          /* present in the code, but since this happened before... */
+          msSetError(MS_WMSERR,
+                     "Unsupported metadata namespace code (%c).",
+                     "msOWSLookupMetadata()", *namespaces );
+          assert(MS_FALSE);
+          return NULL;
+      }
+
+      value = msLookupHashTable(metadata, buf);
+      namespaces++;
     }
+  }
 
-    return value;
+  return value;
+}
+
+
+/*
+** msOWSLookupMetadataWithLanguage()
+**
+** Attempts to lookup a given metadata name in multiple OWS namespaces
+** for a specific language.
+*/
+const char *msOWSLookupMetadataWithLanguage(hashTableObj *metadata,
+    const char *namespaces, const char *name, const char* validated_language)
+{
+  const char *value = NULL;
+  char *name2 = NULL;
+  size_t bufferSize = 0;
+
+  if ( name && validated_language ) {
+    bufferSize = strlen(name)+strlen(validated_language)+2;
+    name2 = (char *) msSmallMalloc( bufferSize );
+    snprintf(name2, bufferSize, "%s.%s", name, validated_language);
+    value = msOWSLookupMetadata(metadata, namespaces, name2);
+  }
+
+  if (value == NULL) {
+    value = msOWSLookupMetadata(metadata, namespaces, name);
+  }
+
+  msFree( name2 );
+
+  return value;
 }
 
 /*
@@ -471,28 +605,27 @@ const char *msOWSLookupMetadata(hashTableObj *metadata,
 **
 ** Attempts to lookup a given metadata name in multiple hashTables, and
 ** in multiple OWS namespaces within each. First searches the primary
-** table and if no result is found, attempts the search using the 
+** table and if no result is found, attempts the search using the
 ** secondary (fallback) table.
 **
-** 'namespaces' is a string with a letter for each namespace to lookup 
+** 'namespaces' is a string with a letter for each namespace to lookup
 ** in the order they should be looked up. e.g. "MO" to lookup wms_ and ows_
 ** If namespaces is NULL then this function just does a regular metadata
 ** lookup.
 */
 const char *msOWSLookupMetadata2(hashTableObj *pri,
-                                        hashTableObj *sec,
-                                        const char *namespaces,
-                                        const char *name)
+                                 hashTableObj *sec,
+                                 const char *namespaces,
+                                 const char *name)
 {
-    const char *result;
-    
-    if ((result = msOWSLookupMetadata(pri, namespaces, name)) == NULL)
-    {
-        /* Try the secondary table */
-        result = msOWSLookupMetadata(sec, namespaces, name);
-    }
+  const char *result;
 
-    return result;
+  if ((result = msOWSLookupMetadata(pri, namespaces, name)) == NULL) {
+    /* Try the secondary table */
+    result = msOWSLookupMetadata(sec, namespaces, name);
+  }
+
+  return result;
 }
 
 
@@ -501,40 +634,38 @@ const char *msOWSLookupMetadata2(hashTableObj *pri,
 ** Parse a version string in the format "a.b.c" or "a.b" and return an
 ** integer in the format 0x0a0b0c suitable for regular integer comparisons.
 **
-** Returns one of OWS_VERSION_NOTSET or OWS_VERSION_BADFORMAT if version 
+** Returns one of OWS_VERSION_NOTSET or OWS_VERSION_BADFORMAT if version
 ** could not be parsed.
 */
 int msOWSParseVersionString(const char *pszVersion)
 {
-    char **digits = NULL;
-    int numDigits = 0;
-
-    if (pszVersion)
-    {
-        int nVersion = 0;
-        digits = msStringSplit(pszVersion, '.', &numDigits);
-        if (digits == NULL || numDigits < 2 || numDigits > 3)
-        {
-            msSetError(MS_OWSERR, 
-                       "Invalid version (%s). Version must be in the "
-                       "format 'x.y' or 'x.y.z'",
-                       "msOWSParseVersionString()", pszVersion);
-            if (digits)
-                msFreeCharArray(digits, numDigits);
-            return OWS_VERSION_BADFORMAT;
-        }
+  char **digits = NULL;
+  int numDigits = 0;
+
+  if (pszVersion) {
+    int nVersion = 0;
+    digits = msStringSplit(pszVersion, '.', &numDigits);
+    if (digits == NULL || numDigits < 2 || numDigits > 3) {
+      msSetError(MS_OWSERR,
+                 "Invalid version (%s). Version must be in the "
+                 "format 'x.y' or 'x.y.z'",
+                 "msOWSParseVersionString()", pszVersion);
+      if (digits)
+        msFreeCharArray(digits, numDigits);
+      return OWS_VERSION_BADFORMAT;
+    }
 
-        nVersion = atoi(digits[0])*0x010000;
-        nVersion += atoi(digits[1])*0x0100;
-        if (numDigits > 2)
-            nVersion += atoi(digits[2]);
+    nVersion = atoi(digits[0])*0x010000;
+    nVersion += atoi(digits[1])*0x0100;
+    if (numDigits > 2)
+      nVersion += atoi(digits[2]);
 
-        msFreeCharArray(digits, numDigits);
+    msFreeCharArray(digits, numDigits);
 
-        return nVersion;
-    }
+    return nVersion;
+  }
 
-    return OWS_VERSION_NOTSET;
+  return OWS_VERSION_NOTSET;
 }
 
 /* msOWSGetVersionString()
@@ -548,11 +679,11 @@ int msOWSParseVersionString(const char *pszVersion)
 const char *msOWSGetVersionString(int nVersion, char *pszBuffer)
 {
 
-    if (pszBuffer)
-        snprintf(pszBuffer, OWS_VERSION_MAXLEN-1, "%d.%d.%d", 
-            (nVersion/0x10000)%0x100, (nVersion/0x100)%0x100, nVersion%0x100);
+  if (pszBuffer)
+    snprintf(pszBuffer, OWS_VERSION_MAXLEN-1, "%d.%d.%d",
+             (nVersion/0x10000)%0x100, (nVersion/0x100)%0x100, nVersion%0x100);
 
-    return pszBuffer;
+  return pszBuffer;
 }
 
 
@@ -567,18 +698,17 @@ const char *msOWSGetVersionString(int nVersion, char *pszBuffer)
 */
 static int msRenameLayer(layerObj *lp, int count)
 {
-    char *newname;
-    newname = (char*)malloc((strlen(lp->name)+5)*sizeof(char));
-    if (!newname) 
-    {
-        msSetError(MS_MEMERR, NULL, "msRenameLayer()");
-        return MS_FAILURE;
-    }
-    sprintf(newname, "%s_%2.2d", lp->name, count);
-    free(lp->name);
-    lp->name = newname;
-    
-    return MS_SUCCESS;
+  char *newname;
+  newname = (char*)malloc((strlen(lp->name)+5)*sizeof(char));
+  if (!newname) {
+    msSetError(MS_MEMERR, NULL, "msRenameLayer()");
+    return MS_FAILURE;
+  }
+  sprintf(newname, "%s_%2.2d", lp->name, count);
+  free(lp->name);
+  lp->name = newname;
+
+  return MS_SUCCESS;
 }
 
 /*
@@ -589,27 +719,22 @@ int msOWSMakeAllLayersUnique(mapObj *map)
   int i, j;
 
   /* Make sure all layers in the map file have valid and unique names */
-  for(i=0; i<map->numlayers; i++)
-  {
-      int count=1;
-      for(j=i+1; j<map->numlayers; j++)
-      {
-          if (GET_LAYER(map, i)->name == NULL || GET_LAYER(map, j)->name == NULL)
-          {
-              continue;
-          }
-          if (strcasecmp(GET_LAYER(map, i)->name, GET_LAYER(map, j)->name) == 0 &&
-              msRenameLayer((GET_LAYER(map, j)), ++count) != MS_SUCCESS)
-          {
-              return MS_FAILURE;
-          }
+  for(i=0; i<map->numlayers; i++) {
+    int count=1;
+    for(j=i+1; j<map->numlayers; j++) {
+      if (GET_LAYER(map, i)->name == NULL || GET_LAYER(map, j)->name == NULL) {
+        continue;
       }
-
-      /* Don't forget to rename the first layer if duplicates were found */
-      if (count > 1 && msRenameLayer((GET_LAYER(map, i)), 1) != MS_SUCCESS)
-      {
-          return MS_FAILURE;
+      if (strcasecmp(GET_LAYER(map, i)->name, GET_LAYER(map, j)->name) == 0 &&
+          msRenameLayer((GET_LAYER(map, j)), ++count) != MS_SUCCESS) {
+        return MS_FAILURE;
       }
+    }
+
+    /* Don't forget to rename the first layer if duplicates were found */
+    if (count > 1 && msRenameLayer((GET_LAYER(map, i)), 1) != MS_SUCCESS) {
+      return MS_FAILURE;
+    }
   }
   return MS_SUCCESS;
 }
@@ -626,7 +751,8 @@ int msOWSMakeAllLayersUnique(mapObj *map)
 **
 */
 
-int msOWSNegotiateVersion(int requested_version, int supported_versions[], int num_supported_versions) {
+int msOWSNegotiateVersion(int requested_version, int supported_versions[], int num_supported_versions)
+{
   int i;
 
   /* if version is not set return highest version */
@@ -658,78 +784,97 @@ int msOWSNegotiateVersion(int requested_version, int supported_versions[], int n
 */
 char * msOWSTerminateOnlineResource(const char *src_url)
 {
-    char *online_resource = NULL;
-    size_t buffer_size = 0;
+  char *online_resource = NULL;
+  size_t buffer_size = 0;
 
-    if (src_url == NULL) 
-        return NULL;
-    
-    buffer_size = strlen(src_url)+2;
-    online_resource = (char*) malloc(buffer_size);
+  if (src_url == NULL)
+    return NULL;
 
-    if (online_resource == NULL)
-    {
-        msSetError(MS_MEMERR, NULL, "msOWSTerminateOnlineResource()");
-        return NULL;
-    }
+  buffer_size = strlen(src_url)+2;
+  online_resource = (char*) malloc(buffer_size);
+
+  if (online_resource == NULL) {
+    msSetError(MS_MEMERR, NULL, "msOWSTerminateOnlineResource()");
+    return NULL;
+  }
 
-    strlcpy(online_resource, src_url, buffer_size);
+  strlcpy(online_resource, src_url, buffer_size);
 
-    /* Append trailing '?' or '&' if missing. */
-    if (strchr(online_resource, '?') == NULL)
-        strlcat(online_resource, "?", buffer_size);
-    else
-    {
-        char *c;
-        c = online_resource+strlen(online_resource)-1;
-        if (*c != '?' && *c != '&') 
-            strlcpy(c+1, "&", buffer_size-strlen(online_resource));
-    }
+  /* Append trailing '?' or '&' if missing. */
+  if (strchr(online_resource, '?') == NULL)
+    strlcat(online_resource, "?", buffer_size);
+  else {
+    char *c;
+    c = online_resource+strlen(online_resource)-1;
+    if (*c != '?' && *c != '&')
+      strlcpy(c+1, "&", buffer_size-strlen(online_resource));
+  }
 
-    return online_resource;
+  return online_resource;
 }
 
 /*
 ** msOWSGetOnlineResource()
 **
-** Return the online resource for this service.  First try to lookup 
+** Return the online resource for this service.  First try to lookup
 ** specified metadata, and if not found then try to build the URL ourselves.
 **
 ** Returns a newly allocated string that should be freed by the caller or
 ** NULL in case of error.
 */
-char * msOWSGetOnlineResource(mapObj *map, const char *namespaces, const char *metadata_name, 
+char * msOWSGetOnlineResource(mapObj *map, const char *namespaces, const char *metadata_name,
                               cgiRequestObj *req)
 {
-    const char *value;
-    char *online_resource = NULL;
-
-    /* We need this script's URL, including hostname. */
-    /* Default to use the value of the "onlineresource" metadata, and if not */
-    /* set then build it: "http://$(SERVER_NAME):$(SERVER_PORT)$(SCRIPT_NAME)?" */
-    /* (+append the map=... param if it was explicitly passed in QUERY_STRING) */
-    /*  */
-    if ((value = msOWSLookupMetadata(&(map->web.metadata), namespaces, metadata_name))) 
-    {
-        online_resource = msOWSTerminateOnlineResource(value);
-    }
-    else 
-    {
-        if ((online_resource = msBuildOnlineResource(map, req)) == NULL)
-        {
-            msSetError(MS_CGIERR, "Impossible to establish server URL.  Please set \"%s\" metadata.", "msOWSGetOnlineResource()", metadata_name);
-            return NULL;
-        }
+  const char *value;
+  char *online_resource = NULL;
+
+  /* We need this script's URL, including hostname. */
+  /* Default to use the value of the "onlineresource" metadata, and if not */
+  /* set then build it: "http://$(SERVER_NAME):$(SERVER_PORT)$(SCRIPT_NAME)?" */
+  /* (+append the map=... param if it was explicitly passed in QUERY_STRING) */
+  /*  */
+  if ((value = msOWSLookupMetadata(&(map->web.metadata), namespaces, metadata_name))) {
+    online_resource = msOWSTerminateOnlineResource(value);
+  } else {
+    if ((online_resource = msBuildOnlineResource(map, req)) == NULL) {
+      msSetError(MS_CGIERR, "Impossible to establish server URL.  Please set \"%s\" metadata.", "msOWSGetOnlineResource()", metadata_name);
+      return NULL;
     }
+  }
 
-    return online_resource;
+  return online_resource;
 }
 
 
+/*
+** msOWSGetOnlineResource()
+**
+** Return the online resource for this service and add language parameter.
+**
+** Returns a newly allocated string that should be freed by the caller or
+** NULL in case of error.
+*/
+char * msOWSGetOnlineResource2(mapObj *map, const char *namespaces, const char *metadata_name,
+                               cgiRequestObj *req, const char* validated_language)
+{
+  char *online_resource = msOWSGetOnlineResource(map, namespaces, metadata_name, req);
+
+  if ( online_resource && validated_language ) {
+    /* online_resource is already terminated, so we can simply add language=...& */
+    /* but first we need to make sure that online_resource has enough capacity */
+    online_resource = (char *)msSmallRealloc(online_resource, strlen(online_resource) + strlen(validated_language) +  11);
+    strcat(online_resource, "language=");
+    strcat(online_resource, validated_language);
+    strcat(online_resource, "&");
+  }
+
+  return online_resource;
+}
+
 /* msOWSGetSchemasLocation()
 **
-** schemas location is the root of the web tree where all WFS-related 
-** schemas can be found on this server.  These URLs must exist in order 
+** schemas location is the root of the web tree where all WFS-related
+** schemas can be found on this server.  These URLs must exist in order
 ** to validate xml.
 **
 ** Use value of "ows_schemas_location" metadata, if not set then
@@ -737,14 +882,14 @@ char * msOWSGetOnlineResource(mapObj *map, const char *namespaces, const char *m
 */
 const char *msOWSGetSchemasLocation(mapObj *map)
 {
-    const char *schemas_location;
+  const char *schemas_location;
 
-    schemas_location = msLookupHashTable(&(map->web.metadata), 
-                                         "ows_schemas_location");
-    if (schemas_location == NULL)
-      schemas_location = OWS_DEFAULT_SCHEMAS_LOCATION;
+  schemas_location = msLookupHashTable(&(map->web.metadata),
+                                       "ows_schemas_location");
+  if (schemas_location == NULL)
+    schemas_location = OWS_DEFAULT_SCHEMAS_LOCATION;
 
-    return schemas_location;
+  return schemas_location;
 }
 
 /* msOWSGetLanguage()
@@ -756,104 +901,299 @@ const char *msOWSGetSchemasLocation(mapObj *map)
 */
 const char *msOWSGetLanguage(mapObj *map, const char *context)
 {
-    const char *language;
+  const char *language;
+
+  /* if this is an exception, MapServer always returns Exception
+     messages in en-US
+  */
+  if (strcmp(context,"exception") == 0) {
+    language = MS_ERROR_LANGUAGE;
+  }
+  /* if not, fetch language from mapfile metadata */
+  else {
+    language = msLookupHashTable(&(map->web.metadata), "ows_language");
 
-    /* if this is an exception, MapServer always returns Exception
-       messages in en-US
-    */
-    if (strcmp(context,"exception") == 0) {
-      language = MS_ERROR_LANGUAGE;
+    if (language == NULL) {
+      language = "undefined";
     }
-    /* if not, fetch language from mapfile metadata */
-    else {
-      language = msLookupHashTable(&(map->web.metadata), "ows_language");
+  }
+  return language;
+}
+
+/* msOWSGetLanguageList
+**
+** Returns the list of languages that this service supports
+**
+** Use value of "languages" metadata (comma-separated list), or NULL if not set
+**
+** Returns a malloced char** of length numitems which must be freed
+** by the caller, or NULL (with numitems = 0)
+*/
+char **msOWSGetLanguageList(mapObj *map, const char *namespaces, int *numitems)
+{
+
+  const char *languages = NULL;
+
+  languages = msOWSLookupMetadata(&(map->web.metadata), namespaces, "languages");
+  if (languages && strlen(languages) > 0) {
+    return msStringSplit(languages, ',', numitems);
+  } else {
+    *numitems = 0;
+    return NULL;
+  }
+}
+
+/* msOWSGetLanguageFromList
+**
+** Returns a language according to the language requested by the client
+**
+** If the requested language is in the languages metadata then use it,
+** otherwise ignore it and use the defaul language, which is the first entry in
+** the languages metadata list. Calling with a NULL requested_langauge
+** therefore returns this default language. If the language metadata list is
+** not defined then the language is set to NULL.
+**
+** Returns a malloced char* which must be freed by the caller, or NULL
+*/
+char *msOWSGetLanguageFromList(mapObj *map, const char *namespaces, const char *requested_language)
+{
+  int num_items = 0;
+  char **languages = msOWSGetLanguageList(map, namespaces, &num_items);
+  char *language = NULL;
+
+  if( languages && num_items > 0 ) {
+    if ( !requested_language || !msStringInArray( requested_language, languages, num_items) ) {
+      language = msStrdup(languages[0]);
+    } else {
+      language = msStrdup(requested_language);
+    }
+  }
+  msFreeCharArray(languages, num_items);
 
-      if (language == NULL) {
-        language = "undefined";
+  return language;
+}
+
+/* msOWSPrintInspireCommonExtendedCapabilities
+**
+** Output INSPIRE common extended capabilities items to stream
+** The currently supported items are metadata and languages
+**
+** tag_name is the name (including ns prefix) of the tag to include the whole
+** extended capabilities block in
+**
+** service is currently included for future compatibility when differing
+** extended capabilities elements are included for different service types
+**
+** Returns a status code; MS_NOERR if all ok, action_if_not_found otherwise
+*/
+int msOWSPrintInspireCommonExtendedCapabilities(FILE *stream, mapObj *map, const char *namespaces,
+    int action_if_not_found, const char *tag_name,
+    const char *validated_language, const int service)
+{
+
+  int metadataStatus = 0;
+  int languageStatus = 0;
+
+  msIO_fprintf(stream, "  <%s>\n", tag_name);
+
+  metadataStatus = msOWSPrintInspireCommonMetadata(stream, map, namespaces, action_if_not_found);
+  languageStatus = msOWSPrintInspireCommonLanguages(stream, map, namespaces, action_if_not_found, validated_language);
+
+  msIO_fprintf(stream, "  </%s>\n", tag_name);
+
+  return (metadataStatus != MS_NOERR) ? metadataStatus : languageStatus;
+}
+
+/* msOWSPrintInspireCommonMetadata
+**
+** Output INSPIRE common metadata items to a stream
+**
+** Returns a status code; MS_NOERR if all OK, action_if_not_found otherwise
+*/
+int msOWSPrintInspireCommonMetadata(FILE *stream, mapObj *map, const char *namespaces,
+                                    int action_if_not_found)
+{
+
+  int status = MS_NOERR;
+  const char *inspire_capabilities = NULL;
+
+  inspire_capabilities = msOWSLookupMetadata(&(map->web.metadata), namespaces, "inspire_capabilities");
+
+  if(!inspire_capabilities) {
+    if (OWS_WARN == action_if_not_found) {
+      msIO_fprintf(stream, "<!-- WARNING: missing metadata entry for 'inspire_capabilities', one of 'embed' and 'url' must be supplied. -->\n");
+    }
+    return action_if_not_found;
+  }
+  if (strcasecmp("url",inspire_capabilities) == 0) {
+    if ( msOWSLookupMetadata(&(map->web.metadata), namespaces, "inspire_metadataurl_href") != NULL ) {
+      msIO_fprintf(stream, "    <inspire_common:MetadataUrl xsi:type=\"inspire_common:resourceLocatorType\">\n");
+      msOWSPrintEncodeMetadata(stream, &(map->web.metadata), namespaces, "inspire_metadataurl_href", OWS_WARN, "      <inspire_common:URL>%s</inspire_common:URL>\n", "");
+      msOWSPrintEncodeMetadata(stream, &(map->web.metadata), namespaces, "inspire_metadataurl_format", OWS_WARN, "      <inspire_common:MediaType>%s</inspire_common:MediaType>\n", "");
+      msIO_fprintf(stream, "    </inspire_common:MetadataUrl>\n");
+    } else {
+      status = action_if_not_found;
+      if (OWS_WARN == action_if_not_found) {
+        msIO_fprintf(stream, "<!-- WARNING: Mandatory metadata '%s%s' was missing in this context. -->\n", (namespaces?"..._":""), "inspire_metadataurl_href");
       }
     }
-    return language;
+  } else if (strcasecmp("embed",inspire_capabilities) == 0) {
+    msOWSPrintEncodeMetadata(stream, &(map->web.metadata), namespaces, "inspire_resourcelocator", OWS_NOERR, "    <inspire_common:ResourceLocator>\n      <inspire_common:URL>%s</inspire_common:URL>\n    </inspire_common:ResourceLocator>\n", NULL);
+    msIO_fprintf(stream,"    <inspire_common:ResourceType>service</inspire_common:ResourceType>\n");
+    msOWSPrintEncodeMetadata(stream, &(map->web.metadata), namespaces, "inspire_temporal_reference", OWS_WARN, "    <inspire_common:TemporalReference>\n      <inspire_common:DateOfLastRevision>%s</inspire_common:DateOfLastRevision>\n    </inspire_common:TemporalReference>\n", "");
+    msIO_fprintf(stream, "    <inspire_common:Conformity>\n");
+    msIO_fprintf(stream, "      <inspire_common:Specification>\n");
+    msIO_fprintf(stream, "        <inspire_common:Title>-</inspire_common:Title>\n");
+    msOWSPrintEncodeMetadata(stream, &(map->web.metadata), namespaces, "inspire_temporal_reference", OWS_NOERR, "        <inspire_common:DateOfLastRevision>%s</inspire_common:DateOfLastRevision>\n", "");
+    msIO_fprintf(stream, "      </inspire_common:Specification>\n");
+    msIO_fprintf(stream, "      <inspire_common:Degree>notEvaluated</inspire_common:Degree>\n");
+    msIO_fprintf(stream, "    </inspire_common:Conformity>\n");
+    msIO_fprintf(stream, "    <inspire_common:MetadataPointOfContact>\n");
+    msOWSPrintEncodeMetadata(stream, &(map->web.metadata), namespaces, "inspire_mpoc_name", OWS_WARN, "      <inspire_common:OrganisationName>%s</inspire_common:OrganisationName>\n", "");
+    msOWSPrintEncodeMetadata(stream, &(map->web.metadata), namespaces, "inspire_mpoc_email", OWS_WARN, "      <inspire_common:EmailAddress>%s</inspire_common:EmailAddress>\n", "");
+    msIO_fprintf(stream, "    </inspire_common:MetadataPointOfContact>\n");
+    msOWSPrintEncodeMetadata(stream, &(map->web.metadata), namespaces, "inspire_metadatadate", OWS_WARN, "      <inspire_common:MetadataDate>%s</inspire_common:MetadataDate>\n", "");
+    msIO_fprintf(stream,"    <inspire_common:SpatialDataServiceType>view</inspire_common:SpatialDataServiceType>\n");
+    msOWSPrintEncodeMetadata(stream, &(map->web.metadata), namespaces, "inspire_keyword", OWS_WARN, "    <inspire_common:MandatoryKeyword xsi:type='inspire_common:classificationOfSpatialDataService'>\n      <inspire_common:KeywordValue>%s</inspire_common:KeywordValue>\n    </inspire_common:MandatoryKeyword>\n", "");
+  } else {
+    status = action_if_not_found;
+    if (OWS_WARN == action_if_not_found) {
+      msIO_fprintf(stream, "<!-- WARNING: invalid value '%s' for 'inspire_capabilities', only 'embed' and 'url' are supported. -->\n", inspire_capabilities);
+    }
+  }
+
+  return status;
+}
+
+/* msOWSPrintInspireCommonLanguages
+**
+** Output INSPIRE supported languages block to stream
+**
+** Returns a status code; MS_NOERR if all OK; action_if_not_found otherwise
+*/
+int msOWSPrintInspireCommonLanguages(FILE *stream, mapObj *map, const char *namespaces,
+                                     int action_if_not_found, const char *validated_language)
+{
+  char *buffer = NULL; /* temp variable for malloced strings that will need freeing */
+  int status = MS_NOERR;
+
+  char *default_language = msOWSGetLanguageFromList(map, namespaces, NULL);
+
+  if(validated_language && default_language) {
+    msIO_fprintf(stream, "    <inspire_common:SupportedLanguages>\n");
+    msIO_fprintf(stream, "      <inspire_common:DefaultLanguage><inspire_common:Language>%s"
+                 "</inspire_common:Language></inspire_common:DefaultLanguage>\n",
+                 buffer = msEncodeHTMLEntities(default_language));
+    msFree(buffer);
+    
+    /* append _exclude to our default_language*/
+    default_language = msSmallRealloc(default_language,strlen(default_language)+strlen("_exclude")+1);
+    strcat(default_language,"_exclude");
+
+    msOWSPrintEncodeMetadataList(stream, &(map->web.metadata), namespaces, "languages", NULL, NULL,
+                                 "      <inspire_common:SupportedLanguage><inspire_common:Language>%s"
+                                 "</inspire_common:Language></inspire_common:SupportedLanguage>\n", default_language);
+    msIO_fprintf(stream, "    </inspire_common:SupportedLanguages>\n");
+    msIO_fprintf(stream, "    <inspire_common:ResponseLanguage><inspire_common:Language>%s"
+                 "</inspire_common:Language></inspire_common:ResponseLanguage>\n", validated_language);
+  } else {
+    status = action_if_not_found;
+    if (OWS_WARN == action_if_not_found) {
+      msIO_fprintf(stream, "<!-- WARNING: Mandatory metadata '%s%s' was missing in this context. -->\n", (namespaces?"..._":""), "languages");
+    }
+  }
+
+  msFree(default_language);
+
+  return status;
 }
 
 /*
 ** msOWSPrintMetadata()
 **
-** Attempt to output a capability item.  If corresponding metadata is not 
-** found then one of a number of predefined actions will be taken. 
-** If a default value is provided and metadata is absent then the 
+** Attempt to output a capability item.  If corresponding metadata is not
+** found then one of a number of predefined actions will be taken.
+** If a default value is provided and metadata is absent then the
 ** default will be used.
 */
 
-int msOWSPrintMetadata(FILE *stream, hashTableObj *metadata, 
-                       const char *namespaces, const char *name, 
-                       int action_if_not_found, const char *format, 
-                       const char *default_value) 
+int msOWSPrintMetadata(FILE *stream, hashTableObj *metadata,
+                       const char *namespaces, const char *name,
+                       int action_if_not_found, const char *format,
+                       const char *default_value)
 {
-    const char *value = NULL;
-    int status = MS_NOERR;
+  const char *value = NULL;
+  int status = MS_NOERR;
 
-    if((value = msOWSLookupMetadata(metadata, namespaces, name)) != NULL)
-    { 
-        msIO_fprintf(stream, format, value);
+  if((value = msOWSLookupMetadata(metadata, namespaces, name)) != NULL) {
+    msIO_fprintf(stream, format, value);
+  } else {
+    if (action_if_not_found == OWS_WARN) {
+      msIO_fprintf(stream, "<!-- WARNING: Mandatory metadata '%s%s' was missing in this context. -->\n", (namespaces?"..._":""), name);
+      status = action_if_not_found;
     }
-    else
-    {
-        if (action_if_not_found == OWS_WARN)
-        {
-            msIO_fprintf(stream, "<!-- WARNING: Mandatory metadata '%s%s' was missing in this context. -->\n", (namespaces?"..._":""), name);
-            status = action_if_not_found;
-        }
 
-        if (default_value)
-            msIO_fprintf(stream, format, default_value);
-    }
+    if (default_value)
+      msIO_fprintf(stream, format, default_value);
+  }
 
-    return status;
+  return status;
 }
 
 
 /*
 ** msOWSPrintEncodeMetadata()
 **
-** Attempt to output a capability item.  If corresponding metadata is not 
-** found then one of a number of predefined actions will be taken. 
-** If a default value is provided and metadata is absent then the 
+** Attempt to output a capability item.  If corresponding metadata is not
+** found then one of a number of predefined actions will be taken.
+** If a default value is provided and metadata is absent then the
 ** default will be used.
 ** Also encode the value with msEncodeHTMLEntities.
 */
 
-int msOWSPrintEncodeMetadata(FILE *stream, hashTableObj *metadata, 
-                             const char *namespaces, const char *name, 
-                             int action_if_not_found, 
-                             const char *format, const char *default_value) 
+int msOWSPrintEncodeMetadata(FILE *stream, hashTableObj *metadata,
+                             const char *namespaces, const char *name,
+                             int action_if_not_found,
+                             const char *format, const char *default_value)
+{
+  return msOWSPrintEncodeMetadata2(stream, metadata, namespaces, name, action_if_not_found, format, default_value, NULL);
+}
+
+
+/*
+** msOWSPrintEncodeMetadata2()
+**
+** Attempt to output a capability item in the requested language.
+** Fallback using no language parameter.
+*/
+int msOWSPrintEncodeMetadata2(FILE *stream, hashTableObj *metadata,
+                              const char *namespaces, const char *name,
+                              int action_if_not_found,
+                              const char *format, const char *default_value,
+                              const char *validated_language)
 {
-    const char *value;
-    char * pszEncodedValue=NULL;
-    int status = MS_NOERR;
-
-    if((value = msOWSLookupMetadata(metadata, namespaces, name)))
-    {
-        pszEncodedValue = msEncodeHTMLEntities(value);
-        msIO_fprintf(stream, format, pszEncodedValue);
-        free(pszEncodedValue);
+  const char *value;
+  char * pszEncodedValue=NULL;
+  int status = MS_NOERR;
+
+  if((value = msOWSLookupMetadataWithLanguage(metadata, namespaces, name, validated_language))) {
+    pszEncodedValue = msEncodeHTMLEntities(value);
+    msIO_fprintf(stream, format, pszEncodedValue);
+    free(pszEncodedValue);
+  } else {
+    if (action_if_not_found == OWS_WARN) {
+      msIO_fprintf(stream, "<!-- WARNING: Mandatory metadata '%s%s%s%s' was missing in this context. -->\n", (namespaces?"..._":""), name, (validated_language?".":""), (validated_language?validated_language:""));
+      status = action_if_not_found;
     }
-    else
-    {
-        if (action_if_not_found == OWS_WARN)
-        {
-            msIO_fprintf(stream, "<!-- WARNING: Mandatory metadata '%s%s' was missing in this context. -->\n", (namespaces?"..._":""), name);
-            status = action_if_not_found;
-        }
 
-        if (default_value)
-        {
-            pszEncodedValue = msEncodeHTMLEntities(default_value);
-            msIO_fprintf(stream, format, default_value);
-            free(pszEncodedValue);
-        }
+    if (default_value) {
+      pszEncodedValue = msEncodeHTMLEntities(default_value);
+      msIO_fprintf(stream, format, default_value);
+      free(pszEncodedValue);
     }
+  }
 
-    return status;
+  return status;
 }
 
 
@@ -864,509 +1204,502 @@ int msOWSPrintEncodeMetadata(FILE *stream, hashTableObj *metadata,
 ** metadata or the default value.
 ** Caller should free the returned string.
 */
-char *msOWSGetEncodeMetadata(hashTableObj *metadata, 
-                             const char *namespaces, const char *name, 
+char *msOWSGetEncodeMetadata(hashTableObj *metadata,
+                             const char *namespaces, const char *name,
                              const char *default_value)
 {
-    const char *value;
-    char * pszEncodedValue=NULL;    
-    if((value = msOWSLookupMetadata(metadata, namespaces, name)))
-      pszEncodedValue = msEncodeHTMLEntities(value);
-    else if (default_value)
-      pszEncodedValue = msEncodeHTMLEntities(default_value);
+  const char *value;
+  char * pszEncodedValue=NULL;
+  if((value = msOWSLookupMetadata(metadata, namespaces, name)))
+    pszEncodedValue = msEncodeHTMLEntities(value);
+  else if (default_value)
+    pszEncodedValue = msEncodeHTMLEntities(default_value);
 
-    return pszEncodedValue;
+  return pszEncodedValue;
 }
-      
+
 
 /*
 ** msOWSPrintValidateMetadata()
 **
-** Attempt to output a capability item.  If corresponding metadata is not 
-** found then one of a number of predefined actions will be taken. 
-** If a default value is provided and metadata is absent then the 
+** Attempt to output a capability item.  If corresponding metadata is not
+** found then one of a number of predefined actions will be taken.
+** If a default value is provided and metadata is absent then the
 ** default will be used.
 ** Also validate the value with msIsXMLTagValid.
 */
 
-int msOWSPrintValidateMetadata(FILE *stream, hashTableObj *metadata, 
-                               const char *namespaces, const char *name, 
-                               int action_if_not_found, 
-                               const char *format, const char *default_value) 
+int msOWSPrintValidateMetadata(FILE *stream, hashTableObj *metadata,
+                               const char *namespaces, const char *name,
+                               int action_if_not_found,
+                               const char *format, const char *default_value)
 {
-    const char *value;
-    int status = MS_NOERR;
-
-    if((value = msOWSLookupMetadata(metadata, namespaces, name)))
-    {
-        if(msIsXMLTagValid(value) == MS_FALSE)
-            msIO_fprintf(stream, "<!-- WARNING: The value '%s' is not valid in a "
-                    "XML tag context. -->\n", value);
-        msIO_fprintf(stream, format, value);
+  const char *value;
+  int status = MS_NOERR;
+
+  if((value = msOWSLookupMetadata(metadata, namespaces, name))) {
+    if(msIsXMLTagValid(value) == MS_FALSE)
+      msIO_fprintf(stream, "<!-- WARNING: The value '%s' is not valid in a "
+                   "XML tag context. -->\n", value);
+    msIO_fprintf(stream, format, value);
+  } else {
+    if (action_if_not_found == OWS_WARN) {
+      msIO_fprintf(stream, "<!-- WARNING: Mandatory metadata '%s%s' was missing in this context. -->\n", (namespaces?"..._":""), name);
+      status = action_if_not_found;
     }
-    else
-    {
-        if (action_if_not_found == OWS_WARN)
-        {
-            msIO_fprintf(stream, "<!-- WARNING: Mandatory metadata '%s%s' was missing in this context. -->\n", (namespaces?"..._":""), name);
-            status = action_if_not_found;
-        }
 
-        if (default_value)
-        {
-            if(msIsXMLTagValid(default_value) == MS_FALSE)
-                msIO_fprintf(stream, "<!-- WARNING: The value '%s' is not valid "
-                        "in a XML tag context. -->\n", default_value);
-            msIO_fprintf(stream, format, default_value);
-        }
+    if (default_value) {
+      if(msIsXMLTagValid(default_value) == MS_FALSE)
+        msIO_fprintf(stream, "<!-- WARNING: The value '%s' is not valid "
+                     "in a XML tag context. -->\n", default_value);
+      msIO_fprintf(stream, format, default_value);
     }
+  }
 
-    return status;
+  return status;
 }
 
 /*
 ** msOWSPrintGroupMetadata()
 **
-** Attempt to output a capability item.  If corresponding metadata is not 
-** found then one of a number of predefined actions will be taken. 
-** If a default value is provided and metadata is absent then the 
+** Attempt to output a capability item.  If corresponding metadata is not
+** found then one of a number of predefined actions will be taken.
+** If a default value is provided and metadata is absent then the
 ** default will be used.
 */
+int msOWSPrintGroupMetadata(FILE *stream, mapObj *map, char* pszGroupName,
+                            const char *namespaces, const char *name,
+                            int action_if_not_found,
+                            const char *format, const char *default_value)
+{
+  return msOWSPrintGroupMetadata2(stream, map, pszGroupName, namespaces, name, action_if_not_found, format, default_value, NULL);
+}
 
-int msOWSPrintGroupMetadata(FILE *stream, mapObj *map, char* pszGroupName, 
-                            const char *namespaces, const char *name, 
-                            int action_if_not_found, 
-                            const char *format, const char *default_value) 
+/*
+** msOWSPrintGroupMetadata2()
+**
+** Attempt to output a capability item in the requested language.
+** Fallback using no language parameter.
+*/
+int msOWSPrintGroupMetadata2(FILE *stream, mapObj *map, char* pszGroupName,
+                             const char *namespaces, const char *name,
+                             int action_if_not_found,
+                             const char *format, const char *default_value,
+                             const char *validated_language)
 {
-    const char *value;
-    char *encoded;
-    int status = MS_NOERR;
-    int i;
+  const char *value;
+  char *encoded;
+  int status = MS_NOERR;
+  int i;
 
-    for (i=0; i<map->numlayers; i++)
-    {
-        if (GET_LAYER(map, i)->group && (strcmp(GET_LAYER(map, i)->group, pszGroupName) == 0) && &(GET_LAYER(map, i)->metadata))
-       {
-         if((value = msOWSLookupMetadata(&(GET_LAYER(map, i)->metadata), namespaces, name)))
-         { 
-            encoded = msEncodeHTMLEntities(value);
-            msIO_fprintf(stream, format, encoded);
-            msFree(encoded);
-            return status;
-         }
-       }
+  for (i=0; i<map->numlayers; i++) {
+    if (GET_LAYER(map, i)->group && (strcmp(GET_LAYER(map, i)->group, pszGroupName) == 0) && &(GET_LAYER(map, i)->metadata)) {
+      if((value = msOWSLookupMetadataWithLanguage(&(GET_LAYER(map, i)->metadata), namespaces, name, validated_language))) {
+        encoded = msEncodeHTMLEntities(value);
+        msIO_fprintf(stream, format, encoded);
+        msFree(encoded);
+        return status;
+      }
     }
+  }
 
-    if (action_if_not_found == OWS_WARN)
-    {
-       msIO_fprintf(stream, "<!-- WARNING: Mandatory metadata '%s%s' was missing in this context. -->\n", (namespaces?"..._":""), name);
-       status = action_if_not_found;
-    }
+  if (action_if_not_found == OWS_WARN) {
+    msIO_fprintf(stream, "<!-- WARNING: Mandatory metadata '%s%s' was missing in this context. -->\n", (namespaces?"..._":""), name);
+    status = action_if_not_found;
+  }
 
-    if (default_value)
-    {
-       encoded = msEncodeHTMLEntities(default_value);
-       msIO_fprintf(stream, format, encoded);
-       msFree(encoded);
-    }
-   
-    return status;
+  if (default_value) {
+    encoded = msEncodeHTMLEntities(default_value);
+    msIO_fprintf(stream, format, encoded);
+    msFree(encoded);
+  }
+
+  return status;
 }
 
 /* msOWSPrintURLType()
 **
-** Attempt to output a URL item in capabilties.  If corresponding metadata 
-** is not found then one of a number of predefined actions will be taken. 
+** Attempt to output a URL item in capabilties.  If corresponding metadata
+** is not found then one of a number of predefined actions will be taken.
 ** Since it's a capability item, five metadata will be used to populate the
 ** XML elements.
 **
-** The 'name' argument is the basename of the metadata items relating to this 
-** URL type and the suffixes _type, _width, _height, _format and _href will 
+** The 'name' argument is the basename of the metadata items relating to this
+** URL type and the suffixes _type, _width, _height, _format and _href will
 ** be appended to the name in the metadata search.
-** e.g. passing name=metadataurl will result in the following medata entries 
+** e.g. passing name=metadataurl will result in the following medata entries
 ** being used:
 **    ows_metadataurl_type
 **    ows_metadataurl_format
 **    ows_metadataurl_href
 **    ... (width and height are unused for metadata)
 **
-** As for all the msOWSPrint*() functions, the namespace argument specifies 
+** As for all the msOWSPrint*() functions, the namespace argument specifies
 ** which prefix (ows_, wms_, wcs_, etc.) is used for the metadata names above.
 **
-** Then the final string will be built from 
+** Then the final string will be built from
 ** the tag_name and the five metadata. The template is:
 ** <tag_name%type%width%height%format>%href</tag_name>
 **
-** For example the width format will usually be " width=\"%s\"". 
+** For example the width format will usually be " width=\"%s\"".
 ** An extern format will be "> <Format>%s</Format"
 **
-** Another template template may be used, but it needs to contains 5 %s, 
-** otherwise leave it to NULL. If tag_format is used then you don't need the 
+** Another template template may be used, but it needs to contains 5 %s,
+** otherwise leave it to NULL. If tag_format is used then you don't need the
 ** tag_name and the tabspace.
 **
 ** Note that all values will be HTML-encoded.
 **/
-int msOWSPrintURLType(FILE *stream, hashTableObj *metadata, 
-                      const char *namespaces, const char *name, 
-                      int action_if_not_found, const char *tag_format, 
-                      const char *tag_name, const char *type_format, 
-                      const char *width_format, const char *height_format, 
+int msOWSPrintURLType(FILE *stream, hashTableObj *metadata,
+                      const char *namespaces, const char *name,
+                      int action_if_not_found, const char *tag_format,
+                      const char *tag_name, const char *type_format,
+                      const char *width_format, const char *height_format,
                       const char *urlfrmt_format, const char *href_format,
-                      int type_is_mandatory, int width_is_mandatory, 
-                      int height_is_mandatory, int format_is_mandatory, 
-                      int href_is_mandatory, const char *default_type, 
-                      const char *default_width, const char *default_height, 
-                      const char *default_urlfrmt, const char *default_href, 
+                      int type_is_mandatory, int width_is_mandatory,
+                      int height_is_mandatory, int format_is_mandatory,
+                      int href_is_mandatory, const char *default_type,
+                      const char *default_width, const char *default_height,
+                      const char *default_urlfrmt, const char *default_href,
                       const char *tabspace)
 {
-    const char *value;
-    char *metadata_name;
-    size_t buffer_size = 0, buffer_size_tmp = 0;
-    char *encoded;
-    int status = MS_NOERR;
-    char *type=NULL, *width=NULL, *height=NULL, *urlfrmt=NULL, *href=NULL;
-
-    buffer_size = strlen(name)+10;
-    metadata_name = (char*)malloc(buffer_size);
-
-    /* Get type */
-    if(type_format != NULL)
-    {
-        snprintf(metadata_name, buffer_size, "%s_type", name);
-        value = msOWSLookupMetadata(metadata, namespaces, metadata_name);
-        if(value != NULL)
-        {
-            encoded = msEncodeHTMLEntities(value);
-            buffer_size_tmp = strlen(type_format)+strlen(encoded);
-            type = (char*)malloc(buffer_size_tmp);
-            snprintf(type, buffer_size_tmp, type_format, encoded);
-            msFree(encoded);
-        }
+  const char *value;
+  char *metadata_name;
+  size_t buffer_size = 0, buffer_size_tmp = 0;
+  char *encoded;
+  int status = MS_NOERR;
+  char *type=NULL, *width=NULL, *height=NULL, *urlfrmt=NULL, *href=NULL;
+
+  buffer_size = strlen(name)+10;
+  metadata_name = (char*)malloc(buffer_size);
+
+  /* Get type */
+  if(type_format != NULL) {
+    snprintf(metadata_name, buffer_size, "%s_type", name);
+    value = msOWSLookupMetadata(metadata, namespaces, metadata_name);
+    if(value != NULL) {
+      encoded = msEncodeHTMLEntities(value);
+      buffer_size_tmp = strlen(type_format)+strlen(encoded);
+      type = (char*)malloc(buffer_size_tmp);
+      snprintf(type, buffer_size_tmp, type_format, encoded);
+      msFree(encoded);
     }
+  }
 
-    /* Get width */
-    if(width_format != NULL)
-    {
-        snprintf(metadata_name, buffer_size, "%s_width", name);
-        value = msOWSLookupMetadata(metadata, namespaces, metadata_name);
-        if(value != NULL)
-        {
-            encoded = msEncodeHTMLEntities(value);
-            buffer_size_tmp = strlen(width_format)+strlen(encoded);
-            width = (char*)malloc(buffer_size_tmp);
-            snprintf(width, buffer_size_tmp, width_format, encoded);
-            msFree(encoded);
-        }
+  /* Get width */
+  if(width_format != NULL) {
+    snprintf(metadata_name, buffer_size, "%s_width", name);
+    value = msOWSLookupMetadata(metadata, namespaces, metadata_name);
+    if(value != NULL) {
+      encoded = msEncodeHTMLEntities(value);
+      buffer_size_tmp = strlen(width_format)+strlen(encoded);
+      width = (char*)malloc(buffer_size_tmp);
+      snprintf(width, buffer_size_tmp, width_format, encoded);
+      msFree(encoded);
     }
+  }
 
-    /* Get height */
-    if(height_format != NULL)
-    {
-        snprintf(metadata_name, buffer_size, "%s_height", name);
-        value = msOWSLookupMetadata(metadata, namespaces, metadata_name);
-        if(value != NULL)
-        {
-            encoded = msEncodeHTMLEntities(value);
-            buffer_size_tmp = strlen(height_format)+strlen(encoded);
-            height = (char*)malloc(buffer_size_tmp);
-            snprintf(height, buffer_size_tmp, height_format, encoded);
-            msFree(encoded);
-        }
+  /* Get height */
+  if(height_format != NULL) {
+    snprintf(metadata_name, buffer_size, "%s_height", name);
+    value = msOWSLookupMetadata(metadata, namespaces, metadata_name);
+    if(value != NULL) {
+      encoded = msEncodeHTMLEntities(value);
+      buffer_size_tmp = strlen(height_format)+strlen(encoded);
+      height = (char*)malloc(buffer_size_tmp);
+      snprintf(height, buffer_size_tmp, height_format, encoded);
+      msFree(encoded);
     }
+  }
 
-    /* Get format */
-    if(urlfrmt_format != NULL)
-    {
-        snprintf(metadata_name, buffer_size, "%s_format", name);
-        value = msOWSLookupMetadata(metadata, namespaces, metadata_name);
-        if(value != NULL)
-        {
-            encoded = msEncodeHTMLEntities(value);
-            buffer_size_tmp = strlen(urlfrmt_format)+strlen(encoded);
-            urlfrmt = (char*)malloc(buffer_size_tmp);
-            snprintf(urlfrmt, buffer_size_tmp, urlfrmt_format, encoded);
-            msFree(encoded);
-        }
+  /* Get format */
+  if(urlfrmt_format != NULL) {
+    snprintf(metadata_name, buffer_size, "%s_format", name);
+    value = msOWSLookupMetadata(metadata, namespaces, metadata_name);
+    if(value != NULL) {
+      encoded = msEncodeHTMLEntities(value);
+      buffer_size_tmp = strlen(urlfrmt_format)+strlen(encoded);
+      urlfrmt = (char*)malloc(buffer_size_tmp);
+      snprintf(urlfrmt, buffer_size_tmp, urlfrmt_format, encoded);
+      msFree(encoded);
     }
+  }
 
-    /* Get href */
-    if(href_format != NULL)
-    {
-        snprintf(metadata_name, buffer_size, "%s_href", name);
-        value = msOWSLookupMetadata(metadata, namespaces, metadata_name);
-        if(value != NULL)
-        {
-            encoded = msEncodeHTMLEntities(value);
-            buffer_size_tmp = strlen(href_format)+strlen(encoded);
-            href = (char*)malloc(buffer_size_tmp);
-            snprintf(href, buffer_size_tmp, href_format, encoded);
-            msFree(encoded);
-        }
+  /* Get href */
+  if(href_format != NULL) {
+    snprintf(metadata_name, buffer_size, "%s_href", name);
+    value = msOWSLookupMetadata(metadata, namespaces, metadata_name);
+    if(value != NULL) {
+      encoded = msEncodeHTMLEntities(value);
+      buffer_size_tmp = strlen(href_format)+strlen(encoded);
+      href = (char*)malloc(buffer_size_tmp);
+      snprintf(href, buffer_size_tmp, href_format, encoded);
+      msFree(encoded);
     }
+  }
 
-    msFree(metadata_name);
-
-    if(type || width || height || urlfrmt || href || 
-       (!metadata && (default_type || default_width || default_height || 
-                      default_urlfrmt || default_href)))
-    {
-        if((!type && type_is_mandatory) || (!width && width_is_mandatory) || 
-           (!height && height_is_mandatory) || 
-           (!urlfrmt && format_is_mandatory) || (!href && href_is_mandatory))
-        {
-            msIO_fprintf(stream, "<!-- WARNING: Some mandatory elements for '%s' are missing in this context. -->\n", tag_name);
-            if (action_if_not_found == OWS_WARN)
-            {
-                msIO_fprintf(stream, "<!-- WARNING: Mandatory metadata '%s%s' was missing in this context. -->\n", (namespaces?"..._":""), name);
-                status = action_if_not_found;
-            }
-        }
-        else
-        {
-            if(!type && type_format && default_type)
-            {
-                buffer_size_tmp = strlen(type_format) + strlen(default_type) + 2;
-                type = (char*) malloc(buffer_size_tmp);
-                snprintf(type, buffer_size_tmp, type_format, default_type);
-            }
-            else if(!type)
-                type = msStrdup("");
-            if(!width && width_format && default_width)
-            {
-                buffer_size_tmp = strlen(width_format) + strlen(default_width) + 2;
-                width = (char*) malloc(buffer_size_tmp);
-                snprintf(width, buffer_size_tmp, width_format, default_width);
-            }
-            else if(!width)
-                width = msStrdup("");
-            if(!height && height_format && default_height)
-            {
-                buffer_size_tmp =  strlen(height_format) + strlen(default_height) + 2;
-                height = (char*) malloc(buffer_size_tmp);
-                snprintf(height, buffer_size_tmp, height_format, default_height);
-            }
-            else if(!height)
-                height = msStrdup("");
-            if(!urlfrmt && urlfrmt_format && default_urlfrmt)
-            {
-                buffer_size_tmp = strlen(urlfrmt_format) + strlen(default_urlfrmt) + 2;
-                urlfrmt = (char*) malloc(buffer_size_tmp);
-                snprintf(urlfrmt, buffer_size_tmp, urlfrmt_format, default_urlfrmt);
-            }
-            else if(!urlfrmt)
-                urlfrmt = msStrdup("");
-            if(!href && href_format && default_href)
-            {
-                buffer_size_tmp = strlen(href_format) + strlen(default_href) + 2;
-                href = (char*) malloc(buffer_size_tmp);
-                snprintf(href, buffer_size_tmp, href_format, default_href);
-            }
-            else if(!href)
-                href = msStrdup("");
-
-            if(tag_format == NULL)
-                msIO_fprintf(stream, "%s<%s%s%s%s%s>%s</%s>\n", tabspace, 
-                             tag_name, type, width, height, urlfrmt, href, 
-                             tag_name);
-            else
-                msIO_fprintf(stream, tag_format, 
-                             type, width, height, urlfrmt, href);
-        }
-
-        msFree(type);
-        msFree(width);
-        msFree(height);
-        msFree(urlfrmt);
-        msFree(href);
+  msFree(metadata_name);
+
+  if(type || width || height || urlfrmt || href ||
+      (!metadata && (default_type || default_width || default_height ||
+                     default_urlfrmt || default_href))) {
+    if((!type && type_is_mandatory) || (!width && width_is_mandatory) ||
+        (!height && height_is_mandatory) ||
+        (!urlfrmt && format_is_mandatory) || (!href && href_is_mandatory)) {
+      msIO_fprintf(stream, "<!-- WARNING: Some mandatory elements for '%s' are missing in this context. -->\n", tag_name);
+      if (action_if_not_found == OWS_WARN) {
+        msIO_fprintf(stream, "<!-- WARNING: Mandatory metadata '%s%s' was missing in this context. -->\n", (namespaces?"..._":""), name);
+        status = action_if_not_found;
+      }
+    } else {
+      if(!type && type_format && default_type) {
+        buffer_size_tmp = strlen(type_format) + strlen(default_type) + 2;
+        type = (char*) malloc(buffer_size_tmp);
+        snprintf(type, buffer_size_tmp, type_format, default_type);
+      } else if(!type)
+        type = msStrdup("");
+      if(!width && width_format && default_width) {
+        buffer_size_tmp = strlen(width_format) + strlen(default_width) + 2;
+        width = (char*) malloc(buffer_size_tmp);
+        snprintf(width, buffer_size_tmp, width_format, default_width);
+      } else if(!width)
+        width = msStrdup("");
+      if(!height && height_format && default_height) {
+        buffer_size_tmp =  strlen(height_format) + strlen(default_height) + 2;
+        height = (char*) malloc(buffer_size_tmp);
+        snprintf(height, buffer_size_tmp, height_format, default_height);
+      } else if(!height)
+        height = msStrdup("");
+      if(!urlfrmt && urlfrmt_format && default_urlfrmt) {
+        buffer_size_tmp = strlen(urlfrmt_format) + strlen(default_urlfrmt) + 2;
+        urlfrmt = (char*) malloc(buffer_size_tmp);
+        snprintf(urlfrmt, buffer_size_tmp, urlfrmt_format, default_urlfrmt);
+      } else if(!urlfrmt)
+        urlfrmt = msStrdup("");
+      if(!href && href_format && default_href) {
+        buffer_size_tmp = strlen(href_format) + strlen(default_href) + 2;
+        href = (char*) malloc(buffer_size_tmp);
+        snprintf(href, buffer_size_tmp, href_format, default_href);
+      } else if(!href)
+        href = msStrdup("");
+
+      if(tag_format == NULL)
+        msIO_fprintf(stream, "%s<%s%s%s%s%s>%s</%s>\n", tabspace,
+                     tag_name, type, width, height, urlfrmt, href,
+                     tag_name);
+      else
+        msIO_fprintf(stream, tag_format,
+                     type, width, height, urlfrmt, href);
     }
-    else
-    {
-        if (action_if_not_found == OWS_WARN)
-        {
-            msIO_fprintf(stream, "<!-- WARNING: Mandatory metadata '%s%s' was missing in this context. -->\n", (namespaces?"..._":""), name);
-            status = action_if_not_found;
-        }
+
+    msFree(type);
+    msFree(width);
+    msFree(height);
+    msFree(urlfrmt);
+    msFree(href);
+  } else {
+    if (action_if_not_found == OWS_WARN) {
+      msIO_fprintf(stream, "<!-- WARNING: Mandatory metadata '%s%s' was missing in this context. -->\n", (namespaces?"..._":""), name);
+      status = action_if_not_found;
     }
+  }
 
-    return status;
+  return status;
 }
 
 /* msOWSPrintParam()
 **
 ** Same as printMetadata() but applied to mapfile parameters.
 **/
-int msOWSPrintParam(FILE *stream, const char *name, const char *value, 
-                    int action_if_not_found, const char *format, 
-                    const char *default_value) 
+int msOWSPrintParam(FILE *stream, const char *name, const char *value,
+                    int action_if_not_found, const char *format,
+                    const char *default_value)
 {
-    int status = MS_NOERR;
+  int status = MS_NOERR;
 
-    if(value && strlen(value) > 0)
-    { 
-        msIO_fprintf(stream, format, value);
+  if(value && strlen(value) > 0) {
+    msIO_fprintf(stream, format, value);
+  } else {
+    if (action_if_not_found == OWS_WARN) {
+      msIO_fprintf(stream, "<!-- WARNING: Mandatory mapfile parameter '%s' was missing in this context. -->\n", name);
+      status = action_if_not_found;
     }
-    else
-    {
-        if (action_if_not_found == OWS_WARN)
-        {
-            msIO_fprintf(stream, "<!-- WARNING: Mandatory mapfile parameter '%s' was missing in this context. -->\n", name);
-            status = action_if_not_found;
-        }
 
-        if (default_value)
-            msIO_fprintf(stream, format, default_value);
-    }
+    if (default_value)
+      msIO_fprintf(stream, format, default_value);
+  }
 
-    return status;
+  return status;
 }
 
 /* msOWSPrintEncodeParam()
 **
 ** Same as printEncodeMetadata() but applied to mapfile parameters.
 **/
-int msOWSPrintEncodeParam(FILE *stream, const char *name, const char *value, 
-                          int action_if_not_found, const char *format, 
-                          const char *default_value) 
+int msOWSPrintEncodeParam(FILE *stream, const char *name, const char *value,
+                          int action_if_not_found, const char *format,
+                          const char *default_value)
 {
-    int status = MS_NOERR;
-    char *encode;
-
-    if(value && strlen(value) > 0)
-    { 
-        encode = msEncodeHTMLEntities(value);
-        msIO_fprintf(stream, format, encode);
-        msFree(encode);
+  int status = MS_NOERR;
+  char *encode;
+
+  if(value && strlen(value) > 0) {
+    encode = msEncodeHTMLEntities(value);
+    msIO_fprintf(stream, format, encode);
+    msFree(encode);
+  } else {
+    if (action_if_not_found == OWS_WARN) {
+      msIO_fprintf(stream, "<!-- WARNING: Mandatory mapfile parameter '%s' was missing in this context. -->\n", name);
+      status = action_if_not_found;
     }
-    else
-    {
-        if (action_if_not_found == OWS_WARN)
-        {
-            msIO_fprintf(stream, "<!-- WARNING: Mandatory mapfile parameter '%s' was missing in this context. -->\n", name);
-            status = action_if_not_found;
-        }
 
-        if (default_value)
-        {
-            encode = msEncodeHTMLEntities(default_value);
-            msIO_fprintf(stream, format, encode);
-            msFree(encode);
-        }
+    if (default_value) {
+      encode = msEncodeHTMLEntities(default_value);
+      msIO_fprintf(stream, format, encode);
+      msFree(encode);
     }
+  }
 
-    return status;
+  return status;
 }
 
 /* msOWSPrintMetadataList()
 **
 ** Prints comma-separated lists metadata.  (e.g. keywordList)
+** default_value serves 2 purposes if specified:
+** - won't be printed if part of MetadataList (default_value == key"_exclude")
+**  (exclusion)
+** - will be printed if MetadataList is empty (fallback)
 **/
-int msOWSPrintMetadataList(FILE *stream, hashTableObj *metadata, 
-                           const char *namespaces, const char *name, 
-                           const char *startTag, 
+int msOWSPrintMetadataList(FILE *stream, hashTableObj *metadata,
+                           const char *namespaces, const char *name,
+                           const char *startTag,
                            const char *endTag, const char *itemFormat,
-                           const char *default_value) 
+                           const char *default_value)
 {
-    const char *value;
-    if((value = msOWSLookupMetadata(metadata, namespaces, name)) ||
-       (value = default_value) != NULL ) 
-    {
-      char **keywords;
-      int numkeywords;
-      
-      keywords = msStringSplit(value, ',', &numkeywords);
-      if(keywords && numkeywords > 0) {
-        int kw;
-	    if(startTag) msIO_fprintf(stream, "%s", startTag);
-	    for(kw=0; kw<numkeywords; kw++) 
-            msIO_fprintf(stream, itemFormat, keywords[kw]);
-	    if(endTag) msIO_fprintf(stream, "%s", endTag);
-	    msFreeCharArray(keywords, numkeywords);
+  const char *value;
+
+  value = msOWSLookupMetadata(metadata, namespaces, name);
+
+  if(value == NULL) {
+    value = default_value;
+    default_value = NULL;
+  }
+
+  if(value != NULL) {
+    char **keywords;
+    int numkeywords;
+
+    keywords = msStringSplit(value, ',', &numkeywords);
+    if(keywords && numkeywords > 0) {
+      int kw;
+      if(startTag) msIO_fprintf(stream, "%s", startTag);
+      for(kw=0; kw<numkeywords; kw++) {
+        if (default_value != NULL
+            && strncasecmp(keywords[kw],default_value,strlen(keywords[kw])) == 0
+            && strncasecmp("_exclude",default_value+strlen(default_value)-8,8) == 0)
+          continue;
+
+        msIO_fprintf(stream, itemFormat, keywords[kw]);
       }
-      return MS_TRUE;
+      if(endTag) msIO_fprintf(stream, "%s", endTag);
+      msFreeCharArray(keywords, numkeywords);
     }
-    return MS_FALSE;
+    return MS_TRUE;
+  }
+  return MS_FALSE;
 }
 
 /* msOWSPrintEncodeMetadataList()
 **
 ** Prints comma-separated lists metadata.  (e.g. keywordList)
 ** This will print HTML encoded values.
+** default_value serves 2 purposes if specified:
+** - won't be printed if part of MetadataList (default_value == key"_exclude")
+**  (exclusion)
+** - will be printed if MetadataList is empty (fallback)
 **/
-int msOWSPrintEncodeMetadataList(FILE *stream, hashTableObj *metadata, 
-                                 const char *namespaces, const char *name, 
-                                 const char *startTag, 
+int msOWSPrintEncodeMetadataList(FILE *stream, hashTableObj *metadata,
+                                 const char *namespaces, const char *name,
+                                 const char *startTag,
                                  const char *endTag, const char *itemFormat,
-                                 const char *default_value) 
+                                 const char *default_value)
 {
-    const char *value;
-    char *encoded;
-    if((value = msOWSLookupMetadata(metadata, namespaces, name)) ||
-       (value = default_value) != NULL ) 
-    {
-      char **keywords;
-      int numkeywords;
-      
-      keywords = msStringSplit(value, ',', &numkeywords);
-      if(keywords && numkeywords > 0) {
-        int kw;
-	    if(startTag) msIO_fprintf(stream, "%s", startTag);
-	    for(kw=0; kw<numkeywords; kw++)
-            {
-                encoded = msEncodeHTMLEntities(keywords[kw]);
-                msIO_fprintf(stream, itemFormat, encoded);
-                msFree(encoded);
-            }
-	    if(endTag) msIO_fprintf(stream, "%s", endTag);
-	    msFreeCharArray(keywords, numkeywords);
+  const char *value;
+  char *encoded;
+
+  value = msOWSLookupMetadata(metadata, namespaces, name);
+
+  if(value == NULL) {
+    value = default_value;
+    default_value = NULL;
+  }
+
+  if(value != NULL) {
+    char **keywords;
+    int numkeywords;
+
+    keywords = msStringSplit(value, ',', &numkeywords);
+    if(keywords && numkeywords > 0) {
+      int kw;
+      if(startTag) msIO_fprintf(stream, "%s", startTag);
+      for(kw=0; kw<numkeywords; kw++) {
+        if (default_value != NULL
+            && strncasecmp(keywords[kw],default_value,strlen(keywords[kw])) == 0
+            && strncasecmp("_exclude",default_value+strlen(default_value)-8,8) == 0)
+          continue;
+
+        encoded = msEncodeHTMLEntities(keywords[kw]);
+        msIO_fprintf(stream, itemFormat, encoded);
+        msFree(encoded);
       }
-      return MS_TRUE;
+      if(endTag) msIO_fprintf(stream, "%s", endTag);
+      msFreeCharArray(keywords, numkeywords);
     }
-    return MS_FALSE;
+    return MS_TRUE;
+  }
+  return MS_FALSE;
 }
 
 /* msOWSPrintEncodeParamList()
 **
 ** Same as msOWSPrintEncodeMetadataList() but applied to mapfile parameters.
 **/
-int msOWSPrintEncodeParamList(FILE *stream, const char *name, 
-                              const char *value, int action_if_not_found, 
-                              char delimiter, const char *startTag, 
-                              const char *endTag, const char *format, 
-                              const char *default_value) 
+int msOWSPrintEncodeParamList(FILE *stream, const char *name,
+                              const char *value, int action_if_not_found,
+                              char delimiter, const char *startTag,
+                              const char *endTag, const char *format,
+                              const char *default_value)
 {
-    int status = MS_NOERR;
-    char *encoded;
-    char **items = NULL;
-    int numitems = 0, i;
+  int status = MS_NOERR;
+  char *encoded;
+  char **items = NULL;
+  int numitems = 0, i;
 
-    if(value && strlen(value) > 0)
-        items = msStringSplit(value, delimiter, &numitems);
-    else
-    {
-        if (action_if_not_found == OWS_WARN)
-        {
-            msIO_fprintf(stream, "<!-- WARNING: Mandatory mapfile parameter '%s' was missing in this context. -->\n", name);
-            status = action_if_not_found;
-        }
-
-        if (default_value)
-            items = msStringSplit(default_value, delimiter, &numitems);
+  if(value && strlen(value) > 0)
+    items = msStringSplit(value, delimiter, &numitems);
+  else {
+    if (action_if_not_found == OWS_WARN) {
+      msIO_fprintf(stream, "<!-- WARNING: Mandatory mapfile parameter '%s' was missing in this context. -->\n", name);
+      status = action_if_not_found;
     }
 
-    if(items && numitems > 0)
-    {
-        if(startTag) msIO_fprintf(stream, "%s", startTag);
-        for(i=0; i<numitems; i++)
-        {
-            encoded = msEncodeHTMLEntities(items[i]);
-            msIO_fprintf(stream, format, encoded);
-            msFree(encoded);
-        }
-        if(endTag) msIO_fprintf(stream, "%s", endTag);
-        msFreeCharArray(items, numitems);
+    if (default_value)
+      items = msStringSplit(default_value, delimiter, &numitems);
+  }
+
+  if(items && numitems > 0) {
+    if(startTag) msIO_fprintf(stream, "%s", startTag);
+    for(i=0; i<numitems; i++) {
+      encoded = msEncodeHTMLEntities(items[i]);
+      msIO_fprintf(stream, format, encoded);
+      msFree(encoded);
     }
+    if(endTag) msIO_fprintf(stream, "%s", endTag);
+    msFreeCharArray(items, numitems);
+  }
 
-    return status;
+  return status;
 }
 
 
@@ -1376,7 +1709,7 @@ int msOWSPrintEncodeParamList(FILE *stream, const char *name,
 ** Print a EX_GeographicBoundingBox tag for WMS1.3.0
 **
 */
-void msOWSPrintEX_GeographicBoundingBox(FILE *stream, const char *tabspace, 
+void msOWSPrintEX_GeographicBoundingBox(FILE *stream, const char *tabspace,
                                         rectObj *extent, projectionObj *srcproj)
 
 {
@@ -1393,7 +1726,7 @@ void msOWSPrintEX_GeographicBoundingBox(FILE *stream, const char *tabspace,
     msProjectRect(srcproj, &wgs84, &ext);
     msFreeProjection(&wgs84);
   }
-  
+
 
   msIO_fprintf(stream, "%s<%s>\n", tabspace, pszTag);
   msIO_fprintf(stream, "%s    <westBoundLongitude>%g</westBoundLongitude>\n", tabspace, ext.minx);
@@ -1402,8 +1735,8 @@ void msOWSPrintEX_GeographicBoundingBox(FILE *stream, const char *tabspace,
   msIO_fprintf(stream, "%s    <northBoundLatitude>%g</northBoundLatitude>\n", tabspace, ext.maxy);
   msIO_fprintf(stream, "%s</%s>\n", tabspace, pszTag);
 
-  //msIO_fprintf(stream, "%s<%s minx=\"%g\" miny=\"%g\" maxx=\"%g\" maxy=\"%g\" />\n", 
-  //      tabspace, pszTag, ext.minx, ext.miny, ext.maxx, ext.maxy);
+  /* msIO_fprintf(stream, "%s<%s minx=\"%g\" miny=\"%g\" maxx=\"%g\" maxy=\"%g\" />\n",
+                  tabspace, pszTag, ext.minx, ext.miny, ext.maxx, ext.maxy); */
 }
 
 /*
@@ -1413,7 +1746,7 @@ void msOWSPrintEX_GeographicBoundingBox(FILE *stream, const char *tabspace,
 ** ... yes, the tag name differs between WMS and WFS, yuck!
 **
 */
-void msOWSPrintLatLonBoundingBox(FILE *stream, const char *tabspace, 
+void msOWSPrintLatLonBoundingBox(FILE *stream, const char *tabspace,
                                  rectObj *extent, projectionObj *srcproj,
                                  projectionObj *wfsproj, int nService)
 {
@@ -1424,29 +1757,29 @@ void msOWSPrintLatLonBoundingBox(FILE *stream, const char *tabspace,
 
   if (nService == OWS_WMS) { /* always project to lat long */
     if (srcproj->numargs > 0 && !pj_is_latlong(srcproj->proj)) {
-        projectionObj wgs84;
-        msInitProjection(&wgs84);
-        msLoadProjectionString(&wgs84, "+proj=longlat +datum=WGS84");
-        msProjectRect(srcproj, &wgs84, &ext);
-        msFreeProjection(&wgs84);
+      projectionObj wgs84;
+      msInitProjection(&wgs84);
+      msLoadProjectionString(&wgs84, "+proj=longlat +datum=WGS84");
+      msProjectRect(srcproj, &wgs84, &ext);
+      msFreeProjection(&wgs84);
     }
   }
 
   if (nService == OWS_WFS) {
-      pszTag = "LatLongBoundingBox";
-      if (wfsproj) {
-          if (msProjectionsDiffer(srcproj, wfsproj) == MS_TRUE)
-              msProjectRect(srcproj, wfsproj, &ext);
-      }
+    pszTag = "LatLongBoundingBox";
+    if (wfsproj) {
+      if (msProjectionsDiffer(srcproj, wfsproj) == MS_TRUE)
+        msProjectRect(srcproj, wfsproj, &ext);
+    }
   }
 
-  msIO_fprintf(stream, "%s<%s minx=\"%g\" miny=\"%g\" maxx=\"%g\" maxy=\"%g\" />\n", 
-         tabspace, pszTag, ext.minx, ext.miny, ext.maxx, ext.maxy);
+  msIO_fprintf(stream, "%s<%s minx=\"%g\" miny=\"%g\" maxx=\"%g\" maxy=\"%g\" />\n",
+               tabspace, pszTag, ext.minx, ext.miny, ext.maxx, ext.maxy);
 }
 
 /*
 ** Emit a bounding box if we can find projection information.
-** If <namespaces>_bbox_extended is not set, emit a single bounding box 
+** If <namespaces>_bbox_extended is not set, emit a single bounding box
 ** using the layer's native SRS (ignoring any <namespaces>_srs metadata).
 **
 ** If <namespaces>_bbox_extended is set to true, emit a bounding box
@@ -1455,15 +1788,15 @@ void msOWSPrintLatLonBoundingBox(FILE *stream, const char *tabspace,
 ** if there is no such metadata at the layer level.
 ** (These settings make more sense at the global/map level anyways)
 */
-void msOWSPrintBoundingBox(FILE *stream, const char *tabspace, 
-                           rectObj *extent, 
+void msOWSPrintBoundingBox(FILE *stream, const char *tabspace,
+                           rectObj *extent,
                            projectionObj *srcproj,
                            hashTableObj *layer_meta,
                            hashTableObj *map_meta,
                            const char *namespaces,
-                           int wms_version) 
+                           int wms_version)
 {
-  const char	*value, *resx, *resy, *wms_bbox_extended, *epsg_str;
+  const char    *value, *resx, *resy, *wms_bbox_extended, *epsg_str;
   char *encoded, *encoded_resx, *encoded_resy;
   char **epsgs;
   int i, num_epsgs;
@@ -1471,12 +1804,10 @@ void msOWSPrintBoundingBox(FILE *stream, const char *tabspace,
   rectObj ext;
 
   wms_bbox_extended = msOWSLookupMetadata2(layer_meta, map_meta, namespaces, "bbox_extended");
-  if( wms_bbox_extended && strncasecmp(wms_bbox_extended, "true", 5) == 0 ) 
-  {
-    /* get a list of all projections from the metadata 
+  if( wms_bbox_extended && strncasecmp(wms_bbox_extended, "true", 5) == 0 ) {
+    /* get a list of all projections from the metadata
        try the layer metadata first, otherwise use the map's */
-    if( msOWSLookupMetadata(layer_meta, namespaces, "srs") ) 
-    {
+    if( msOWSLookupMetadata(layer_meta, namespaces, "srs") ) {
       epsg_str = msOWSGetEPSGProj(srcproj, layer_meta, namespaces, MS_FALSE);
     } else {
       epsg_str = msOWSGetEPSGProj(srcproj, map_meta, namespaces, MS_FALSE);
@@ -1491,58 +1822,52 @@ void msOWSPrintBoundingBox(FILE *stream, const char *tabspace,
     epsgs[0] = msStrdup( msOWSGetEPSGProj(srcproj, layer_meta, namespaces, MS_TRUE) );
   }
 
-  for( i = 0; i < num_epsgs; i++)
-  {
-    value = epsgs[i]; 
+  for( i = 0; i < num_epsgs; i++) {
+    value = epsgs[i];
     memcpy(&ext, extent, sizeof(rectObj));
 
     /* reproject the extents for each SRS's bounding box */
     msInitProjection(&proj);
-    if (msLoadProjectionStringEPSG(&proj, (char *)value) == 0)
-    {
-      if (msProjectionsDiffer(srcproj, &proj) == MS_TRUE)
-      {
+    if (msLoadProjectionStringEPSG(&proj, (char *)value) == 0) {
+      if (msProjectionsDiffer(srcproj, &proj) == MS_TRUE) {
         msProjectRect(srcproj, &proj, &ext);
       }
-      /*for wms 1.3.0 we need to make sure that we present the BBOX with  
+      /*for wms 1.3.0 we need to make sure that we present the BBOX with
         a reversed axes for some espg codes*/
-      if (wms_version >= OWS_1_3_0 && value && strncasecmp(value, "EPSG:", 5) == 0)
-      {
+      if (wms_version >= OWS_1_3_0 && value && strncasecmp(value, "EPSG:", 5) == 0) {
         msAxisNormalizePoints( &proj, 1, &(ext.minx), &(ext.miny) );
         msAxisNormalizePoints( &proj, 1, &(ext.maxx), &(ext.maxy) );
       }
     }
     msFreeProjection( &proj );
 
-    if( value != NULL )
-    {
+    if( value != NULL ) {
       encoded = msEncodeHTMLEntities(value);
       if (wms_version >= OWS_1_3_0)
         msIO_fprintf(stream, "%s<BoundingBox CRS=\"%s\"\n"
-             "%s            minx=\"%g\" miny=\"%g\" maxx=\"%g\" maxy=\"%g\"",
-             tabspace, encoded, 
-             tabspace, ext.minx, ext.miny, 
-             ext.maxx, ext.maxy);
+                     "%s            minx=\"%g\" miny=\"%g\" maxx=\"%g\" maxy=\"%g\"",
+                     tabspace, encoded,
+                     tabspace, ext.minx, ext.miny,
+                     ext.maxx, ext.maxy);
       else
         msIO_fprintf(stream, "%s<BoundingBox SRS=\"%s\"\n"
-             "%s            minx=\"%g\" miny=\"%g\" maxx=\"%g\" maxy=\"%g\"",
-             tabspace, encoded, 
-             tabspace, ext.minx, ext.miny, 
-             ext.maxx, ext.maxy);
+                     "%s            minx=\"%g\" miny=\"%g\" maxx=\"%g\" maxy=\"%g\"",
+                     tabspace, encoded,
+                     tabspace, ext.minx, ext.miny,
+                     ext.maxx, ext.maxy);
 
       msFree(encoded);
 
       if( (resx = msOWSLookupMetadata2( layer_meta, map_meta, "MFO", "resx" )) != NULL &&
-          (resy = msOWSLookupMetadata2( layer_meta, map_meta, "MFO", "resy" )) != NULL )
-      {
-          encoded_resx = msEncodeHTMLEntities(resx);
-          encoded_resy = msEncodeHTMLEntities(resy);
-          msIO_fprintf( stream, "\n%s            resx=\"%s\" resy=\"%s\"",
-                        tabspace, encoded_resx, encoded_resy );
-          msFree(encoded_resx);
-          msFree(encoded_resy);
+          (resy = msOWSLookupMetadata2( layer_meta, map_meta, "MFO", "resy" )) != NULL ) {
+        encoded_resx = msEncodeHTMLEntities(resx);
+        encoded_resy = msEncodeHTMLEntities(resy);
+        msIO_fprintf( stream, "\n%s            resx=\"%s\" resy=\"%s\"",
+                      tabspace, encoded_resx, encoded_resy );
+        msFree(encoded_resx);
+        msFree(encoded_resy);
       }
- 
+
       msIO_fprintf( stream, " />\n" );
     }
   }
@@ -1553,88 +1878,81 @@ void msOWSPrintBoundingBox(FILE *stream, const char *tabspace,
 /*
 ** Print the contact information
 */
-void msOWSPrintContactInfo( FILE *stream, const char *tabspace, 
-                            int nVersion, hashTableObj *metadata, 
+void msOWSPrintContactInfo( FILE *stream, const char *tabspace,
+                            int nVersion, hashTableObj *metadata,
                             const char *namespaces )
 {
   /* contact information is a required element in 1.0.7 but the */
   /* sub-elements such as ContactPersonPrimary, etc. are not! */
   /* In 1.1.0, ContactInformation becomes optional. */
-  if (nVersion > OWS_1_0_0) 
-  {
-    msIO_fprintf(stream, "%s<ContactInformation>\n", tabspace); 
+  if (nVersion > OWS_1_0_0) {
+    msIO_fprintf(stream, "%s<ContactInformation>\n", tabspace);
 
-      /* ContactPersonPrimary is optional, but when present then all its  */
-      /* sub-elements are mandatory */
+    /* ContactPersonPrimary is optional, but when present then all its  */
+    /* sub-elements are mandatory */
 
     if(msOWSLookupMetadata(metadata, namespaces, "contactperson") ||
-       msOWSLookupMetadata(metadata, namespaces, "contactorganization")) 
-    {
+        msOWSLookupMetadata(metadata, namespaces, "contactorganization")) {
       msIO_fprintf(stream, "%s  <ContactPersonPrimary>\n", tabspace);
 
-      msOWSPrintEncodeMetadata(stream, metadata, namespaces, "contactperson", 
-                  OWS_WARN, "      <ContactPerson>%s</ContactPerson>\n", NULL);
-      msOWSPrintEncodeMetadata(stream, metadata, namespaces, "contactorganization", 
-             OWS_WARN, "      <ContactOrganization>%s</ContactOrganization>\n",
-             NULL);
+      msOWSPrintEncodeMetadata(stream, metadata, namespaces, "contactperson",
+                               OWS_WARN, "      <ContactPerson>%s</ContactPerson>\n", NULL);
+      msOWSPrintEncodeMetadata(stream, metadata, namespaces, "contactorganization",
+                               OWS_WARN, "      <ContactOrganization>%s</ContactOrganization>\n",
+                               NULL);
       msIO_fprintf(stream, "%s  </ContactPersonPrimary>\n", tabspace);
     }
 
-    if(msOWSLookupMetadata(metadata, namespaces, "contactposition"))
-    {
-      msOWSPrintEncodeMetadata(stream, metadata, namespaces, "contactposition", 
-                    OWS_NOERR, "      <ContactPosition>%s</ContactPosition>\n",
-                           NULL);
+    if(msOWSLookupMetadata(metadata, namespaces, "contactposition")) {
+      msOWSPrintEncodeMetadata(stream, metadata, namespaces, "contactposition",
+                               OWS_NOERR, "      <ContactPosition>%s</ContactPosition>\n",
+                               NULL);
     }
 
-      /* ContactAdress is optional, but when present then all its  */
-      /* sub-elements are mandatory */
-    if(msOWSLookupMetadata( metadata, namespaces, "addresstype" ) || 
-       msOWSLookupMetadata( metadata, namespaces, "address" ) || 
-       msOWSLookupMetadata( metadata, namespaces, "city" ) ||
-       msOWSLookupMetadata( metadata, namespaces, "stateorprovince" ) || 
-       msOWSLookupMetadata( metadata, namespaces, "postcode" ) ||
-       msOWSLookupMetadata( metadata, namespaces, "country" )) 
-    {
+    /* ContactAdress is optional, but when present then all its  */
+    /* sub-elements are mandatory */
+    if(msOWSLookupMetadata( metadata, namespaces, "addresstype" ) ||
+        msOWSLookupMetadata( metadata, namespaces, "address" ) ||
+        msOWSLookupMetadata( metadata, namespaces, "city" ) ||
+        msOWSLookupMetadata( metadata, namespaces, "stateorprovince" ) ||
+        msOWSLookupMetadata( metadata, namespaces, "postcode" ) ||
+        msOWSLookupMetadata( metadata, namespaces, "country" )) {
       msIO_fprintf(stream, "%s  <ContactAddress>\n", tabspace);
 
       msOWSPrintEncodeMetadata(stream, metadata, namespaces,"addresstype", OWS_WARN,
-                              "        <AddressType>%s</AddressType>\n", NULL);
+                               "        <AddressType>%s</AddressType>\n", NULL);
       msOWSPrintEncodeMetadata(stream, metadata, namespaces, "address", OWS_WARN,
-                       "        <Address>%s</Address>\n", NULL);
+                               "        <Address>%s</Address>\n", NULL);
       msOWSPrintEncodeMetadata(stream, metadata, namespaces, "city", OWS_WARN,
-                    "        <City>%s</City>\n", NULL);
-      msOWSPrintEncodeMetadata(stream, metadata, namespaces, "stateorprovince", 
-           OWS_WARN,"        <StateOrProvince>%s</StateOrProvince>\n", NULL);
+                               "        <City>%s</City>\n", NULL);
+      msOWSPrintEncodeMetadata(stream, metadata, namespaces, "stateorprovince",
+                               OWS_WARN,"        <StateOrProvince>%s</StateOrProvince>\n", NULL);
       msOWSPrintEncodeMetadata(stream, metadata, namespaces, "postcode", OWS_WARN,
-                    "        <PostCode>%s</PostCode>\n", NULL);
+                               "        <PostCode>%s</PostCode>\n", NULL);
       msOWSPrintEncodeMetadata(stream, metadata, namespaces, "country", OWS_WARN,
-                    "        <Country>%s</Country>\n", NULL);
+                               "        <Country>%s</Country>\n", NULL);
       msIO_fprintf(stream, "%s  </ContactAddress>\n", tabspace);
     }
 
-    if(msOWSLookupMetadata(metadata, namespaces, "contactvoicetelephone"))
-    {
-        msOWSPrintEncodeMetadata(stream, metadata, namespaces, 
-                                 "contactvoicetelephone", OWS_NOERR,
-                   "      <ContactVoiceTelephone>%s</ContactVoiceTelephone>\n",
-                           NULL);
+    if(msOWSLookupMetadata(metadata, namespaces, "contactvoicetelephone")) {
+      msOWSPrintEncodeMetadata(stream, metadata, namespaces,
+                               "contactvoicetelephone", OWS_NOERR,
+                               "      <ContactVoiceTelephone>%s</ContactVoiceTelephone>\n",
+                               NULL);
     }
 
-    if(msOWSLookupMetadata(metadata, namespaces, "contactfacsimiletelephone"))
-    {
-        msOWSPrintEncodeMetadata(stream, metadata, 
-                           namespaces, "contactfacsimiletelephone", OWS_NOERR,
-           "      <ContactFacsimileTelephone>%s</ContactFacsimileTelephone>\n",
-                                 NULL);
+    if(msOWSLookupMetadata(metadata, namespaces, "contactfacsimiletelephone")) {
+      msOWSPrintEncodeMetadata(stream, metadata,
+                               namespaces, "contactfacsimiletelephone", OWS_NOERR,
+                               "      <ContactFacsimileTelephone>%s</ContactFacsimileTelephone>\n",
+                               NULL);
     }
 
-    if(msOWSLookupMetadata(metadata, namespaces, "contactelectronicmailaddress"))
-    {
-        msOWSPrintEncodeMetadata(stream, metadata, 
-                           namespaces, "contactelectronicmailaddress", OWS_NOERR,
-         "  <ContactElectronicMailAddress>%s</ContactElectronicMailAddress>\n",
-                                 NULL);
+    if(msOWSLookupMetadata(metadata, namespaces, "contactelectronicmailaddress")) {
+      msOWSPrintEncodeMetadata(stream, metadata,
+                               namespaces, "contactelectronicmailaddress", OWS_NOERR,
+                               "  <ContactElectronicMailAddress>%s</ContactElectronicMailAddress>\n",
+                               NULL);
     }
     msIO_fprintf(stream, "%s</ContactInformation>\n", tabspace);
   }
@@ -1644,7 +1962,7 @@ void msOWSPrintContactInfo( FILE *stream, const char *tabspace,
 ** msOWSGetLayerExtent()
 **
 ** Try to establish layer extent, first looking for "ows_extent" metadata, and
-** if not found then call msLayerGetExtent() which will lookup the 
+** if not found then call msLayerGetExtent() which will lookup the
 ** layer->extent member, and if not found will open layer to read extent.
 **
 */
@@ -1652,8 +1970,7 @@ int msOWSGetLayerExtent(mapObj *map, layerObj *lp, const char *namespaces, rectO
 {
   const char *value;
 
-  if ((value = msOWSLookupMetadata(&(lp->metadata), namespaces, "extent")) != NULL)
-  {
+  if ((value = msOWSLookupMetadata(&(lp->metadata), namespaces, "extent")) != NULL) {
     char **tokens;
     int n;
 
@@ -1670,10 +1987,8 @@ int msOWSGetLayerExtent(mapObj *map, layerObj *lp, const char *namespaces, rectO
 
     msFreeCharArray(tokens, n);
     return MS_SUCCESS;
-  }
-  else
-  {
-      return msLayerGetExtent(lp, ext);
+  } else {
+    return msLayerGetExtent(lp, ext);
   }
 
   return MS_FAILURE;
@@ -1683,162 +1998,151 @@ int msOWSGetLayerExtent(mapObj *map, layerObj *lp, const char *namespaces, rectO
 /**********************************************************************
  *                          msOWSExecuteRequests()
  *
- * Execute a number of WFS/WMS HTTP requests in parallel, and then 
+ * Execute a number of WFS/WMS HTTP requests in parallel, and then
  * update layerObj information with the result of the requests.
  **********************************************************************/
 int msOWSExecuteRequests(httpRequestObj *pasReqInfo, int numRequests,
                          mapObj *map, int bCheckLocalCache)
 {
-    int nStatus, iReq;
+  int nStatus, iReq;
 
-    /* Execute requests */
+  /* Execute requests */
 #if defined(USE_CURL)
-    nStatus = msHTTPExecuteRequests(pasReqInfo, numRequests, bCheckLocalCache);
+  nStatus = msHTTPExecuteRequests(pasReqInfo, numRequests, bCheckLocalCache);
 #else
-    msSetError(MS_WMSERR, "msOWSExecuteRequests() called apparently without libcurl configured, msHTTPExecuteRequests() not available.",
-               "msOWSExecuteRequests()");
-    return MS_FAILURE;
+  msSetError(MS_WMSERR, "msOWSExecuteRequests() called apparently without libcurl configured, msHTTPExecuteRequests() not available.",
+             "msOWSExecuteRequests()");
+  return MS_FAILURE;
 #endif
 
-    /* Scan list of layers and call the handler for each layer type to */
-    /* pass them the request results. */
-    for(iReq=0; iReq<numRequests; iReq++)
-    {
-        if (pasReqInfo[iReq].nLayerId >= 0 && 
-            pasReqInfo[iReq].nLayerId < map->numlayers)
-        {
-            layerObj *lp;
+  /* Scan list of layers and call the handler for each layer type to */
+  /* pass them the request results. */
+  for(iReq=0; iReq<numRequests; iReq++) {
+    if (pasReqInfo[iReq].nLayerId >= 0 &&
+        pasReqInfo[iReq].nLayerId < map->numlayers) {
+      layerObj *lp;
 
-            lp = GET_LAYER(map, pasReqInfo[iReq].nLayerId);
+      lp = GET_LAYER(map, pasReqInfo[iReq].nLayerId);
 
-            if (lp->connectiontype == MS_WFS)
-                msWFSUpdateRequestInfo(lp, &(pasReqInfo[iReq]));
-        }
+      if (lp->connectiontype == MS_WFS)
+        msWFSUpdateRequestInfo(lp, &(pasReqInfo[iReq]));
     }
+  }
 
-    return nStatus;
+  return nStatus;
 }
 
 /**********************************************************************
  *                          msOWSProcessException()
  *
  **********************************************************************/
-void msOWSProcessException(layerObj *lp, const char *pszFname, 
+void msOWSProcessException(layerObj *lp, const char *pszFname,
                            int nErrorCode, const char *pszFuncName)
 {
-    FILE *fp;
-
-    if ((fp = fopen(pszFname, "r")) != NULL)
-    {
-        char *pszBuf=NULL;
-        int   nBufSize=0;
-        char *pszStart, *pszEnd;
-
-        fseek(fp, 0, SEEK_END);
-        nBufSize = ftell(fp);
-        rewind(fp);
-        pszBuf = (char*)malloc((nBufSize+1)*sizeof(char));
-        if (pszBuf == NULL)
-        {
-            msSetError(MS_MEMERR, NULL, "msOWSProcessException()");
-            fclose(fp);
-            return;
-        }
-
-        if ((int) fread(pszBuf, 1, nBufSize, fp) != nBufSize)
-        {
-            msSetError(MS_IOERR, NULL, "msOWSProcessException()");
-            free(pszBuf);
-            fclose(fp);
-            return;
-        }
-
-        pszBuf[nBufSize] = '\0';
-
-
-        /* OK, got the data in the buffer.  Look for the <Message> tags */
-        if ((strstr(pszBuf, "<WFS_Exception>") &&            /* WFS style */
-             (pszStart = strstr(pszBuf, "<Message>")) &&
-             (pszEnd = strstr(pszStart, "</Message>")) ) ||
-            (strstr(pszBuf, "<ServiceExceptionReport>") &&   /* WMS style */
-             (pszStart = strstr(pszBuf, "<ServiceException>")) &&
-             (pszEnd = strstr(pszStart, "</ServiceException>")) ))
-        {
-            pszStart = strchr(pszStart, '>')+1;
-            *pszEnd = '\0';
-            msSetError(nErrorCode, "Got Remote Server Exception for layer %s: %s",
-                       pszFuncName, lp->name?lp->name:"(null)", pszStart);
-        }
-        else
-        {
-            msSetError(MS_WFSCONNERR, "Unable to parse Remote Server Exception Message for layer %s.",
-                       pszFuncName, lp->name?lp->name:"(null)");
-        }
-
-        free(pszBuf);
-        fclose(fp);
+  FILE *fp;
+
+  if ((fp = fopen(pszFname, "r")) != NULL) {
+    char *pszBuf=NULL;
+    int   nBufSize=0;
+    char *pszStart, *pszEnd;
+
+    fseek(fp, 0, SEEK_END);
+    nBufSize = ftell(fp);
+    rewind(fp);
+    pszBuf = (char*)malloc((nBufSize+1)*sizeof(char));
+    if (pszBuf == NULL) {
+      msSetError(MS_MEMERR, NULL, "msOWSProcessException()");
+      fclose(fp);
+      return;
+    }
+
+    if ((int) fread(pszBuf, 1, nBufSize, fp) != nBufSize) {
+      msSetError(MS_IOERR, NULL, "msOWSProcessException()");
+      free(pszBuf);
+      fclose(fp);
+      return;
+    }
+
+    pszBuf[nBufSize] = '\0';
+
+
+    /* OK, got the data in the buffer.  Look for the <Message> tags */
+    if ((strstr(pszBuf, "<WFS_Exception>") &&            /* WFS style */
+         (pszStart = strstr(pszBuf, "<Message>")) &&
+         (pszEnd = strstr(pszStart, "</Message>")) ) ||
+        (strstr(pszBuf, "<ServiceExceptionReport>") &&   /* WMS style */
+         (pszStart = strstr(pszBuf, "<ServiceException>")) &&
+         (pszEnd = strstr(pszStart, "</ServiceException>")) )) {
+      pszStart = strchr(pszStart, '>')+1;
+      *pszEnd = '\0';
+      msSetError(nErrorCode, "Got Remote Server Exception for layer %s: %s",
+                 pszFuncName, lp->name?lp->name:"(null)", pszStart);
+    } else {
+      msSetError(MS_WFSCONNERR, "Unable to parse Remote Server Exception Message for layer %s.",
+                 pszFuncName, lp->name?lp->name:"(null)");
     }
+
+    free(pszBuf);
+    fclose(fp);
+  }
 }
 
 /**********************************************************************
  *                          msOWSBuildURLFilename()
  *
- * Build a unique filename for this URL to use in caching remote server 
+ * Build a unique filename for this URL to use in caching remote server
  * requests.  Slashes and illegal characters will be turned into '_'
  *
  * Returns a newly allocated buffer that should be freed by the caller or
  * NULL in case of error.
  **********************************************************************/
-char *msOWSBuildURLFilename(const char *pszPath, const char *pszURL, 
+char *msOWSBuildURLFilename(const char *pszPath, const char *pszURL,
                             const char *pszExt)
 {
-    char *pszBuf, *pszPtr;
-    int  i;
-    size_t nBufLen = 0;
+  char *pszBuf, *pszPtr;
+  int  i;
+  size_t nBufLen = 0;
 
 
-    nBufLen = strlen(pszURL) + strlen(pszExt) +2;
-    if (pszPath)
-        nBufLen += (strlen(pszPath)+1);
-    
-    pszBuf = (char*)malloc(nBufLen);
-    if (pszBuf == NULL)
-    {
-        msSetError(MS_MEMERR, NULL, "msOWSBuildURLFilename()");
-        return NULL;
-    }
-    pszBuf[0] = '\0';
+  nBufLen = strlen(pszURL) + strlen(pszExt) +2;
+  if (pszPath)
+    nBufLen += (strlen(pszPath)+1);
 
-    if (pszPath)
-    {
+  pszBuf = (char*)malloc(nBufLen);
+  if (pszBuf == NULL) {
+    msSetError(MS_MEMERR, NULL, "msOWSBuildURLFilename()");
+    return NULL;
+  }
+  pszBuf[0] = '\0';
+
+  if (pszPath) {
 #ifdef _WIN32
-        if (pszPath[strlen(pszPath) -1] != '/' &&
-            pszPath[strlen(pszPath) -1] != '\\')
-          snprintf(pszBuf, nBufLen, "%s\\", pszPath);
-        else
-          snprintf(pszBuf, nBufLen, "%s", pszPath);
+    if (pszPath[strlen(pszPath) -1] != '/' &&
+        pszPath[strlen(pszPath) -1] != '\\')
+      snprintf(pszBuf, nBufLen, "%s\\", pszPath);
+    else
+      snprintf(pszBuf, nBufLen, "%s", pszPath);
 #else
-        if (pszPath[strlen(pszPath) -1] != '/')
-          snprintf(pszBuf, nBufLen, "%s/", pszPath);
-        else
-          snprintf(pszBuf, nBufLen, "%s", pszPath);
+    if (pszPath[strlen(pszPath) -1] != '/')
+      snprintf(pszBuf, nBufLen, "%s/", pszPath);
+    else
+      snprintf(pszBuf, nBufLen, "%s", pszPath);
 #endif
-    }
+  }
 
-    pszPtr = pszBuf + strlen(pszBuf);
+  pszPtr = pszBuf + strlen(pszBuf);
 
-    for(i=0; pszURL[i] != '\0'; i++)
-    {
-        if (isalnum(pszURL[i]))
-            *pszPtr = pszURL[i];
-        else
-            *pszPtr = '_';
-        pszPtr++;
-    }
-    
-    strlcpy(pszPtr, pszExt, nBufLen);
+  for(i=0; pszURL[i] != '\0'; i++) {
+    if (isalnum(pszURL[i]))
+      *pszPtr = pszURL[i];
+    else
+      *pszPtr = '_';
+    pszPtr++;
+  }
 
-    return pszBuf;
+  strlcpy(pszPtr, pszExt, nBufLen);
+
+  return pszBuf;
 }
 
 /*
@@ -1846,7 +2150,7 @@ char *msOWSBuildURLFilename(const char *pszPath, const char *pszURL,
 **
 ** Extract projection code for this layer/map.
 **
-** First look for a xxx_srs metadata. If not found then look for an EPSG 
+** First look for a xxx_srs metadata. If not found then look for an EPSG
 ** code in projectionObj, and if not found then return NULL.
 **
 ** If bReturnOnlyFirstOne=TRUE and metadata contains multiple EPSG codes
@@ -1860,14 +2164,14 @@ const char *msOWSGetEPSGProj(projectionObj *proj, hashTableObj *metadata, const
 
   /* metadata value should already be in format "EPSG:n" or "AUTO:..." */
   if (metadata && ((value = (char *) msOWSLookupMetadata(metadata, namespaces, "srs")) != NULL)) {
-    
+
     if (!bReturnOnlyFirstOne) return value;
 
     /* caller requested only first projection code */
     strlcpy(epsgCode, value, 20);
 
     if ((value=strchr(epsgCode, ' ')) != NULL) *value = '\0';
-    
+
     return epsgCode;
   } else if (proj && proj->numargs > 0 && (value = strstr(proj->args[0], "init=epsg:")) != NULL && strlen(value) < 20) {
     snprintf(epsgCode, sizeof(epsgCode), "EPSG:%s", value+10);
@@ -1876,7 +2180,7 @@ const char *msOWSGetEPSGProj(projectionObj *proj, hashTableObj *metadata, const
     snprintf(epsgCode, sizeof(epsgCode), "CRS:%s", value+9);
     return epsgCode;
   } else if (proj && proj->numargs > 0 && (strncasecmp(proj->args[0], "AUTO:", 5) == 0 ||
-                                           strncasecmp(proj->args[0], "AUTO2:", 6) == 0)) {
+             strncasecmp(proj->args[0], "AUTO2:", 6) == 0)) {
     return proj->args[0];
   }
 
@@ -1892,60 +2196,53 @@ const char *msOWSGetEPSGProj(projectionObj *proj, hashTableObj *metadata, const
 */
 char *msOWSGetProjURN(projectionObj *proj, hashTableObj *metadata, const char *namespaces, int bReturnOnlyFirstOne)
 {
-    char *result;
-    char **tokens;
-    int numtokens, i;
-    size_t bufferSize = 0;
-    
-    const char *oldStyle = msOWSGetEPSGProj( proj, metadata, namespaces, 
-                                             bReturnOnlyFirstOne );
+  char *result;
+  char **tokens;
+  int numtokens, i;
+  size_t bufferSize = 0;
 
-    if( oldStyle == NULL || strncmp(oldStyle,"EPSG:",5) != 0 )
-        return NULL;
+  const char *oldStyle = msOWSGetEPSGProj( proj, metadata, namespaces,
+                         bReturnOnlyFirstOne );
 
-    result = msStrdup("");
+  if( oldStyle == NULL || strncmp(oldStyle,"EPSG:",5) != 0 )
+    return NULL;
 
-    tokens = msStringSplit(oldStyle, ' ', &numtokens);
-    for(i=0; tokens != NULL && i<numtokens; i++)
-    {
-        char urn[100];
+  result = msStrdup("");
 
-        if( strncmp(tokens[i],"EPSG:",5) == 0 )
-            snprintf( urn, sizeof(urn), "urn:ogc:def:crs:EPSG::%s", tokens[i]+5 );
-        else if( strcasecmp(tokens[i],"imageCRS") == 0 )
-            snprintf( urn, sizeof(urn), "urn:ogc:def:crs:OGC::imageCRS" );
-        else if( strncmp(tokens[i],"urn:ogc:def:crs:",16) == 0 ) {
-            strlcpy( urn, tokens[i], sizeof(urn));
-        }
-        else {
-            strlcpy( urn, "", sizeof(urn));
-        }
+  tokens = msStringSplit(oldStyle, ' ', &numtokens);
+  for(i=0; tokens != NULL && i<numtokens; i++) {
+    char urn[100];
 
-        if( strlen(urn) > 0 )
-        {
-            bufferSize = strlen(result)+strlen(urn)+2;
-            result = (char *) realloc(result, bufferSize);
-            
-            if( strlen(result) > 0 )
-                strlcat( result, " ", bufferSize);
-            strlcat( result, urn , bufferSize);
-        }
-        else
-        {
-            msDebug( "msOWSGetProjURN(): Failed to process SRS '%s', ignored.", 
-                     tokens[i] );
-        }
+    if( strncmp(tokens[i],"EPSG:",5) == 0 )
+      snprintf( urn, sizeof(urn), "urn:ogc:def:crs:EPSG::%s", tokens[i]+5 );
+    else if( strcasecmp(tokens[i],"imageCRS") == 0 )
+      snprintf( urn, sizeof(urn), "urn:ogc:def:crs:OGC::imageCRS" );
+    else if( strncmp(tokens[i],"urn:ogc:def:crs:",16) == 0 ) {
+      strlcpy( urn, tokens[i], sizeof(urn));
+    } else {
+      strlcpy( urn, "", sizeof(urn));
     }
 
-    msFreeCharArray(tokens, numtokens);
+    if( strlen(urn) > 0 ) {
+      bufferSize = strlen(result)+strlen(urn)+2;
+      result = (char *) realloc(result, bufferSize);
 
-    if( strlen(result) == 0 )
-    {
-        msFree( result );
-        return NULL;
+      if( strlen(result) > 0 )
+        strlcat( result, " ", bufferSize);
+      strlcat( result, urn , bufferSize);
+    } else {
+      msDebug( "msOWSGetProjURN(): Failed to process SRS '%s', ignored.",
+               tokens[i] );
     }
-    else
-        return result;
+  }
+
+  msFreeCharArray(tokens, numtokens);
+
+  if( strlen(result) == 0 ) {
+    msFree( result );
+    return NULL;
+  } else
+    return result;
 }
 
 /*
@@ -1958,56 +2255,50 @@ char *msOWSGetProjURN(projectionObj *proj, hashTableObj *metadata, const char *n
 */
 char *msOWSGetProjURI(projectionObj *proj, hashTableObj *metadata, const char *namespaces, int bReturnOnlyFirstOne)
 {
-    char *result;
-    char **tokens;
-    int numtokens, i;
+  char *result;
+  char **tokens;
+  int numtokens, i;
 
-    const char *oldStyle = msOWSGetEPSGProj( proj, metadata, namespaces,
-                                             bReturnOnlyFirstOne );
+  const char *oldStyle = msOWSGetEPSGProj( proj, metadata, namespaces,
+                         bReturnOnlyFirstOne );
 
-    if( oldStyle == NULL || !EQUALN(oldStyle,"EPSG:",5) )
-        return NULL;
+  if( oldStyle == NULL || !EQUALN(oldStyle,"EPSG:",5) )
+    return NULL;
 
-    result = msStrdup("");
+  result = msStrdup("");
 
-    tokens = msStringSplit(oldStyle, ' ', &numtokens);
-    for(i=0; tokens != NULL && i<numtokens; i++)
-    {
-        char urn[100];
+  tokens = msStringSplit(oldStyle, ' ', &numtokens);
+  for(i=0; tokens != NULL && i<numtokens; i++) {
+    char urn[100];
 
-        if( strncmp(tokens[i],"EPSG:",5) == 0 )
-            snprintf( urn, sizeof(urn), "http://www.opengis.net/def/crs/EPSG/0/%s", tokens[i]+5 );
-        else if( strcasecmp(tokens[i],"imageCRS") == 0 )
-            snprintf( urn, sizeof(urn), "http://www.opengis.net/def/crs/OGC/0/imageCRS" );
-        else if( strncmp(tokens[i],"http://www.opengis.net/def/crs/",16) == 0 )
-            snprintf( urn, sizeof(urn), "%s", tokens[i] );
-        else
-            strlcpy( urn, "", sizeof(urn) );
+    if( strncmp(tokens[i],"EPSG:",5) == 0 )
+      snprintf( urn, sizeof(urn), "http://www.opengis.net/def/crs/EPSG/0/%s", tokens[i]+5 );
+    else if( strcasecmp(tokens[i],"imageCRS") == 0 )
+      snprintf( urn, sizeof(urn), "http://www.opengis.net/def/crs/OGC/0/imageCRS" );
+    else if( strncmp(tokens[i],"http://www.opengis.net/def/crs/",16) == 0 )
+      snprintf( urn, sizeof(urn), "%s", tokens[i] );
+    else
+      strlcpy( urn, "", sizeof(urn) );
 
-        if( strlen(urn) > 0 )
-        {
-            result = (char *) realloc(result,strlen(result)+strlen(urn)+2);
+    if( strlen(urn) > 0 ) {
+      result = (char *) realloc(result,strlen(result)+strlen(urn)+2);
 
-            if( strlen(result) > 0 )
-                strcat( result, " " );
-            strcat( result, urn );
-        }
-        else
-        {
-            msDebug( "msOWSGetProjURI(): Failed to process SRS '%s', ignored.",
-                     tokens[i] );
-        }
+      if( strlen(result) > 0 )
+        strcat( result, " " );
+      strcat( result, urn );
+    } else {
+      msDebug( "msOWSGetProjURI(): Failed to process SRS '%s', ignored.",
+               tokens[i] );
     }
+  }
 
-    msFreeCharArray(tokens, numtokens);
+  msFreeCharArray(tokens, numtokens);
 
-    if( strlen(result) == 0 )
-    {
-        msFree( result );
-        return NULL;
-    }
-    else
-        return result;
+  if( strlen(result) == 0 ) {
+    msFree( result );
+    return NULL;
+  } else
+    return result;
 }
 
 
@@ -2017,91 +2308,84 @@ char *msOWSGetProjURI(projectionObj *proj, hashTableObj *metadata, const char *n
 ** Extract dimension information from a layer's metadata
 **
 ** Before 4.9, only the time dimension was support. With the addition of
-** Web Map Context 1.1.0, we need to support every dimension types. 
+** Web Map Context 1.1.0, we need to support every dimension types.
 ** This function get the dimension information from special metadata in
 ** the layer, but can also return default values for the time dimension.
-** 
+**
 */
-void msOWSGetDimensionInfo(layerObj *layer, const char *pszDimension, 
-                           const char **papszDimUserValue, 
-                           const char **papszDimUnits, 
-                           const char **papszDimDefault, 
-                           const char **papszDimNearValue, 
-                           const char **papszDimUnitSymbol, 
+void msOWSGetDimensionInfo(layerObj *layer, const char *pszDimension,
+                           const char **papszDimUserValue,
+                           const char **papszDimUnits,
+                           const char **papszDimDefault,
+                           const char **papszDimNearValue,
+                           const char **papszDimUnitSymbol,
                            const char **papszDimMultiValue)
 {
-    char *pszDimensionItem;
-    size_t bufferSize = 0;
+  char *pszDimensionItem;
+  size_t bufferSize = 0;
 
-    if(pszDimension == NULL || layer == NULL)
-        return;
+  if(pszDimension == NULL || layer == NULL)
+    return;
 
-    bufferSize = strlen(pszDimension)+50;
-    pszDimensionItem = (char*)malloc(bufferSize);
+  bufferSize = strlen(pszDimension)+50;
+  pszDimensionItem = (char*)malloc(bufferSize);
 
-    /* units (mandatory in map context) */
-    if(papszDimUnits != NULL)
-    {
-        snprintf(pszDimensionItem, bufferSize, "dimension_%s_units",          pszDimension);
-        *papszDimUnits = msOWSLookupMetadata(&(layer->metadata), "MO",
+  /* units (mandatory in map context) */
+  if(papszDimUnits != NULL) {
+    snprintf(pszDimensionItem, bufferSize, "dimension_%s_units",          pszDimension);
+    *papszDimUnits = msOWSLookupMetadata(&(layer->metadata), "MO",
+                                         pszDimensionItem);
+  }
+  /* unitSymbol (mandatory in map context) */
+  if(papszDimUnitSymbol != NULL) {
+    snprintf(pszDimensionItem, bufferSize, "dimension_%s_unitsymbol",     pszDimension);
+    *papszDimUnitSymbol = msOWSLookupMetadata(&(layer->metadata), "MO",
+                          pszDimensionItem);
+  }
+  /* userValue (mandatory in map context) */
+  if(papszDimUserValue != NULL) {
+    snprintf(pszDimensionItem, bufferSize, "dimension_%s_uservalue",      pszDimension);
+    *papszDimUserValue = msOWSLookupMetadata(&(layer->metadata), "MO",
+                         pszDimensionItem);
+  }
+  /* default */
+  if(papszDimDefault != NULL) {
+    snprintf(pszDimensionItem, bufferSize, "dimension_%s_default",        pszDimension);
+    *papszDimDefault = msOWSLookupMetadata(&(layer->metadata), "MO",
                                            pszDimensionItem);
-    }
-    /* unitSymbol (mandatory in map context) */
-    if(papszDimUnitSymbol != NULL)
-    {
-        snprintf(pszDimensionItem, bufferSize, "dimension_%s_unitsymbol",     pszDimension);
-        *papszDimUnitSymbol = msOWSLookupMetadata(&(layer->metadata), "MO", 
-                                                  pszDimensionItem);
-    }
-    /* userValue (mandatory in map context) */
-    if(papszDimUserValue != NULL)
-    {
-        snprintf(pszDimensionItem, bufferSize, "dimension_%s_uservalue",      pszDimension);
-        *papszDimUserValue = msOWSLookupMetadata(&(layer->metadata), "MO", 
-                                                 pszDimensionItem);
-    }
-    /* default */
-    if(papszDimDefault != NULL)
-    {
-        snprintf(pszDimensionItem, bufferSize, "dimension_%s_default",        pszDimension);
-        *papszDimDefault = msOWSLookupMetadata(&(layer->metadata), "MO",
-                                               pszDimensionItem);
-    }
-    /* multipleValues */
-    if(papszDimMultiValue != NULL)
-    {
-        snprintf(pszDimensionItem, bufferSize, "dimension_%s_multiplevalues", pszDimension);
-        *papszDimMultiValue = msOWSLookupMetadata(&(layer->metadata), "MO", 
-                                                  pszDimensionItem);
-    }
-    /* nearestValue */
-    if(papszDimNearValue != NULL)
-    {
-        snprintf(pszDimensionItem, bufferSize, "dimension_%s_nearestvalue",   pszDimension);
-        *papszDimNearValue = msOWSLookupMetadata(&(layer->metadata), "MO", 
-                                                 pszDimensionItem);
-    }
+  }
+  /* multipleValues */
+  if(papszDimMultiValue != NULL) {
+    snprintf(pszDimensionItem, bufferSize, "dimension_%s_multiplevalues", pszDimension);
+    *papszDimMultiValue = msOWSLookupMetadata(&(layer->metadata), "MO",
+                          pszDimensionItem);
+  }
+  /* nearestValue */
+  if(papszDimNearValue != NULL) {
+    snprintf(pszDimensionItem, bufferSize, "dimension_%s_nearestvalue",   pszDimension);
+    *papszDimNearValue = msOWSLookupMetadata(&(layer->metadata), "MO",
+                         pszDimensionItem);
+  }
 
-    /* Use default time value if necessary */
-    if(strcasecmp(pszDimension, "time") == 0)
-    {
-        if(papszDimUserValue != NULL && *papszDimUserValue == NULL)
-            *papszDimUserValue = msOWSLookupMetadata(&(layer->metadata), 
-                                                   "MO", "time");
-        if(papszDimDefault != NULL && *papszDimDefault == NULL)
-            *papszDimDefault = msOWSLookupMetadata(&(layer->metadata), 
-                                                 "MO", "timedefault");
-        if(papszDimUnits != NULL && *papszDimUnits == NULL)
-            *papszDimUnits = "ISO8601";
-        if(papszDimUnitSymbol != NULL && *papszDimUnitSymbol == NULL)
-            *papszDimUnitSymbol = "t";
-        if(papszDimNearValue != NULL && *papszDimNearValue == NULL)
-            *papszDimNearValue = "0";
-    }
+  /* Use default time value if necessary */
+  if(strcasecmp(pszDimension, "time") == 0) {
+    if(papszDimUserValue != NULL && *papszDimUserValue == NULL)
+      *papszDimUserValue = msOWSLookupMetadata(&(layer->metadata),
+                           "MO", "time");
+    if(papszDimDefault != NULL && *papszDimDefault == NULL)
+      *papszDimDefault = msOWSLookupMetadata(&(layer->metadata),
+                                             "MO", "timedefault");
+    if(papszDimUnits != NULL && *papszDimUnits == NULL)
+      *papszDimUnits = "ISO8601";
+    if(papszDimUnitSymbol != NULL && *papszDimUnitSymbol == NULL)
+      *papszDimUnitSymbol = "t";
+    if(papszDimNearValue != NULL && *papszDimNearValue == NULL)
+      *papszDimNearValue = "0";
+  }
 
-    free(pszDimensionItem);
+  free(pszDimensionItem);
 
-    return;
+  return;
 }
 
 /**
@@ -2118,7 +2402,8 @@ void msOWSGetDimensionInfo(layerObj *layer, const char *pszDimension,
  *  0: equal
  */
 
-int msOWSNegotiateUpdateSequence(const char *requested_updatesequence, const char *updatesequence) {
+int msOWSNegotiateUpdateSequence(const char *requested_updatesequence, const char *updatesequence)
+{
   int i;
   int valtype1 = 1; /* default datatype for updatesequence passed by client */
   int valtype2 = 1; /* default datatype for updatesequence set by server */
@@ -2127,7 +2412,7 @@ int msOWSNegotiateUpdateSequence(const char *requested_updatesequence, const cha
   /* if not specified by client, or set by server,
      server responds with latest Capabilities XML */
   if (! requested_updatesequence || ! updatesequence)
-    return -1; 
+    return -1;
 
   /* test to see if server value is an integer (1), string (2) or timestamp (3) */
   if (msStringIsInteger(updatesequence) == MS_FAILURE)
@@ -2187,47 +2472,44 @@ int msOWSNegotiateUpdateSequence(const char *requested_updatesequence, const cha
 /*      Utlity function to parse a comma separated list in a            */
 /*      metedata object and select and outputformat.                    */
 /************************************************************************/
-outputFormatObj* msOwsIsOutputFormatValid(mapObj *map, const char *format, 
-                                          hashTableObj *metadata, 
-                                          const char *namespaces, const char *name)
+outputFormatObj* msOwsIsOutputFormatValid(mapObj *map, const char *format,
+    hashTableObj *metadata,
+    const char *namespaces, const char *name)
 {
-    char **tokens=NULL;
-    int i,n;
-    outputFormatObj *psFormat = NULL;
-    const char * format_list=NULL;
-    
-    if (map && format && metadata && namespaces && name)
-    {
-        msApplyDefaultOutputFormats(map);
-        format_list = msOWSLookupMetadata(metadata, namespaces, name);
-        n = 0;
-        if ( format_list)
-          tokens = msStringSplit(format_list,  ',', &n);
-
-        if (tokens && n > 0)
-        {
-            for (i=0; i<n; i++)
-            {
-                int iFormat = msGetOutputFormatIndex( map, tokens[i]);
-                const char *mimetype;
-                if( iFormat == -1 )
-                    continue;
-
-                mimetype =  map->outputformatlist[iFormat]->mimetype;
-
-                msStringTrim(tokens[i]);
-                if (strcasecmp(tokens[i], format) == 0)
-                  break;
-                if (mimetype && strcasecmp(mimetype, format) == 0)
-                  break;
-            }
-            msFreeCharArray(tokens, n);
-            if (i < n)
-              psFormat = msSelectOutputFormat( map, format);
-        }
+  char **tokens=NULL;
+  int i,n;
+  outputFormatObj *psFormat = NULL;
+  const char * format_list=NULL;
+
+  if (map && format && metadata && namespaces && name) {
+    msApplyDefaultOutputFormats(map);
+    format_list = msOWSLookupMetadata(metadata, namespaces, name);
+    n = 0;
+    if ( format_list)
+      tokens = msStringSplit(format_list,  ',', &n);
+
+    if (tokens && n > 0) {
+      for (i=0; i<n; i++) {
+        int iFormat = msGetOutputFormatIndex( map, tokens[i]);
+        const char *mimetype;
+        if( iFormat == -1 )
+          continue;
+
+        mimetype =  map->outputformatlist[iFormat]->mimetype;
+
+        msStringTrim(tokens[i]);
+        if (strcasecmp(tokens[i], format) == 0)
+          break;
+        if (mimetype && strcasecmp(mimetype, format) == 0)
+          break;
+      }
+      msFreeCharArray(tokens, n);
+      if (i < n)
+        psFormat = msSelectOutputFormat( map, format);
     }
+  }
 
-    return psFormat;
+  return psFormat;
 }
 
 #endif /* USE_WMS_SVR || USE_WFS_SVR  || USE_WCS_SVR */
diff --git a/mapows.h b/mapows.h
index cbca665..571c646 100644
--- a/mapows.h
+++ b/mapows.h
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -34,8 +34,8 @@
 #include "maphttp.h"
 #include <time.h>
 
-/* This is the URL to the official OGC Schema Repository. We use it by 
- * default for OGC services unless the ows_schemas_lcoation web metadata 
+/* This is the URL to the official OGC Schema Repository. We use it by
+ * default for OGC services unless the ows_schemas_lcoation web metadata
  * is set in the mapfile.
  */
 #define OWS_DEFAULT_SCHEMAS_LOCATION   "http://schemas.opengis.net"
@@ -44,14 +44,14 @@
  *   mapows.c
  *====================================================================*/
 
-typedef struct
-{
+typedef struct {
   char *pszVersion;
   char *pszUpdateSequence;
   char *pszRequest;
   char *pszService;
   char *pszTypeName;
   char *pszFilter;
+  char *pszGeometryName;
   int nMaxFeatures;
   char *pszBbox; /* only used with a Get Request */
   char *pszOutputFormat; /* only used with DescibeFeatureType */
@@ -78,7 +78,7 @@ typedef struct {
   char *pszOutputFormat;
   char *pszSensorId;
   char *pszProcedure;
-  char *pszOffering; 
+  char *pszOffering;
   char *pszObservedProperty;
   char *pszEventTime;
   char *pszResult;
@@ -95,8 +95,7 @@ typedef struct {
  * Used to preprocess WMS request parameters and combine layers that can
  * be comined in a GetMap request.
  */
-typedef  struct
-{
+typedef  struct {
   char        *onlineresource;
   hashTableObj *params;
   int          numparams;
@@ -104,27 +103,32 @@ typedef  struct
 } wmsParamsObj;
 
 /* owsRequestObj: Represent a OWS specific request with its enabled layers */
-typedef struct
-{
-    int numlayers;
-    int *enabled_layers;
-    
+typedef struct {
+  int numlayers;
+  int *enabled_layers;
+
+  char *service;
+  char *version;
+  char *request;
+  void *document; /* xmlDocPtr or CPLXMLNode* */
 } owsRequestObj;
 
 MS_DLL_EXPORT int msOWSDispatch(mapObj *map, cgiRequestObj *request, int ows_mode);
 
-MS_DLL_EXPORT const char * msOWSLookupMetadata(hashTableObj *metadata, 
-                                    const char *namespaces, const char *name);
+MS_DLL_EXPORT const char * msOWSLookupMetadata(hashTableObj *metadata,
+    const char *namespaces, const char *name);
+MS_DLL_EXPORT const char * msOWSLookupMetadataWithLanguage(hashTableObj *metadata,
+    const char *namespaces, const char *name, const char *validated_language);
 MS_DLL_EXPORT const char * msOWSLookupMetadata2(hashTableObj *pri,
-                                                hashTableObj *sec,
-                                                const char *namespaces,
-                                                const char *name);
-MS_DLL_EXPORT int msOWSRequestIsEnabled(mapObj *map, layerObj *layer, 
+    hashTableObj *sec,
+    const char *namespaces,
+    const char *name);
+MS_DLL_EXPORT int msOWSRequestIsEnabled(mapObj *map, layerObj *layer,
                                         const char *namespaces, const char *name, int check_all_layers);
-MS_DLL_EXPORT void msOWSRequestLayersEnabled(mapObj *map, const char *namespaces, 
-                                             const char *request, owsRequestObj *request_layers);
-MS_DLL_EXPORT int msOWSParseRequestMetadata(const char *metadata, const char *request, 
-                                            int *disabled);
+MS_DLL_EXPORT void msOWSRequestLayersEnabled(mapObj *map, const char *namespaces,
+    const char *request, owsRequestObj *request_layers);
+MS_DLL_EXPORT int msOWSParseRequestMetadata(const char *metadata, const char *request,
+    int *disabled);
 
 /* Constants for OWS Service version numbers */
 #define OWS_0_1_2   0x000102
@@ -141,6 +145,7 @@ MS_DLL_EXPORT int msOWSParseRequestMetadata(const char *metadata, const char *re
 #define OWS_1_1_2   0x010102
 #define OWS_1_3_0   0x010300
 #define OWS_2_0_0   0x020000
+#define OWS_2_0_1   0x020001
 #define OWS_VERSION_MAXLEN   20  /* Buffer size for msOWSGetVersionString() */
 #define OWS_VERSION_NOTSET    -1
 #define OWS_VERSION_BADFORMAT -2
@@ -154,8 +159,11 @@ MS_DLL_EXPORT int msOWSMakeAllLayersUnique(mapObj *map);
 MS_DLL_EXPORT int msOWSNegotiateVersion(int requested_version, int supported_versions[], int num_supported_versions);
 MS_DLL_EXPORT char *msOWSTerminateOnlineResource(const char *src_url);
 MS_DLL_EXPORT char *msOWSGetOnlineResource(mapObj *map, const char *namespaces, const char *metadata_name, cgiRequestObj *req);
+MS_DLL_EXPORT char *msOWSGetOnlineResource2(mapObj *map, const char *namespaces, const char *metadata_name, cgiRequestObj *req, const char *validated_language);
 MS_DLL_EXPORT const char *msOWSGetSchemasLocation(mapObj *map);
 MS_DLL_EXPORT const char *msOWSGetLanguage(mapObj *map, const char *context);
+MS_DLL_EXPORT char **msOWSGetLanguageList(mapObj *map, const char *namespaces, int *numitems);
+MS_DLL_EXPORT char *msOWSGetLanguageFromList(mapObj *map, const char *namespaces, const char *requested_language);
 
 
 /* OWS_NOERR and OWS_WARN passed as action_if_not_found to printMetadata() */
@@ -167,73 +175,91 @@ MS_DLL_EXPORT const char *msOWSGetLanguage(mapObj *map, const char *context);
 #define OWS_WMS     1
 #define OWS_WFS     2
 
-MS_DLL_EXPORT int msOWSPrintMetadata(FILE *stream, hashTableObj *metadata, 
-                       const char *namespaces, const char *name, 
-                       int action_if_not_found, const char *format, 
-                       const char *default_value);
-int msOWSPrintEncodeMetadata(FILE *stream, hashTableObj *metadata, 
-                             const char *namespaces, const char *name, 
-                             int action_if_not_found, 
+MS_DLL_EXPORT int msOWSPrintInspireCommonExtendedCapabilities(FILE *stream, mapObj *map, const char *namespaces,
+    const int action_if_not_found, const char *tag_name,
+    const char *validated_language, const int service);
+int msOWSPrintInspireCommonMetadata(FILE *stream, mapObj *map, const char *namespaces,
+                                    int action_if_not_found);
+int msOWSPrintInspireCommonLanguages(FILE *stream, mapObj *map, const char *namespaces,
+                                     int action_if_not_found, const char *validated_language);
+
+MS_DLL_EXPORT int msOWSPrintMetadata(FILE *stream, hashTableObj *metadata,
+                                     const char *namespaces, const char *name,
+                                     int action_if_not_found, const char *format,
+                                     const char *default_value);
+int msOWSPrintEncodeMetadata(FILE *stream, hashTableObj *metadata,
+                             const char *namespaces, const char *name,
+                             int action_if_not_found,
                              const char *format, const char *default_value) ;
-char *msOWSGetEncodeMetadata(hashTableObj *metadata, 
-                             const char *namespaces, const char *name, 
+int msOWSPrintEncodeMetadata2(FILE *stream, hashTableObj *metadata,
+                              const char *namespaces, const char *name,
+                              int action_if_not_found,
+                              const char *format, const char *default_value,
+                              const char *validated_language);
+char *msOWSGetEncodeMetadata(hashTableObj *metadata,
+                             const char *namespaces, const char *name,
                              const char *default_value);
 
-int msOWSPrintValidateMetadata(FILE *stream, hashTableObj *metadata, 
-                               const char *namespaces, const char *name, 
-                               int action_if_not_found, 
+int msOWSPrintValidateMetadata(FILE *stream, hashTableObj *metadata,
+                               const char *namespaces, const char *name,
+                               int action_if_not_found,
                                const char *format, const char *default_value);
-int msOWSPrintGroupMetadata(FILE *stream, mapObj *map, char* pszGroupName, 
-                            const char *namespaces, const char *name, 
-                            int action_if_not_found, 
+int msOWSPrintGroupMetadata(FILE *stream, mapObj *map, char* pszGroupName,
+                            const char *namespaces, const char *name,
+                            int action_if_not_found,
                             const char *format, const char *default_value);
-int msOWSPrintURLType(FILE *stream, hashTableObj *metadata, 
-                      const char *namespaces, const char *name, 
-                      int action_if_not_found, const char *tag_format, 
-                      const char *tag_name, const char *type_format, 
-                      const char *width_format, const char *height_format, 
+int msOWSPrintGroupMetadata2(FILE *stream, mapObj *map, char* pszGroupName,
+                             const char *namespaces, const char *name,
+                             int action_if_not_found,
+                             const char *format, const char *default_value,
+                             const char *validated_language);
+int msOWSPrintURLType(FILE *stream, hashTableObj *metadata,
+                      const char *namespaces, const char *name,
+                      int action_if_not_found, const char *tag_format,
+                      const char *tag_name, const char *type_format,
+                      const char *width_format, const char *height_format,
                       const char *urlfrmt_format, const char *href_format,
-                      int type_is_mandatory, int width_is_mandatory, 
-                      int height_is_mandatory, int format_is_mandatory, 
-                      int href_is_mandatory, const char *default_type, 
-                      const char *default_width, const char *default_height, 
-                      const char *default_urlfrmt, const char *default_href, 
+                      int type_is_mandatory, int width_is_mandatory,
+                      int height_is_mandatory, int format_is_mandatory,
+                      int href_is_mandatory, const char *default_type,
+                      const char *default_width, const char *default_height,
+                      const char *default_urlfrmt, const char *default_href,
                       const char *tabspace);
-int msOWSPrintParam(FILE *stream, const char *name, const char *value, 
-                    int action_if_not_found, const char *format, 
+int msOWSPrintParam(FILE *stream, const char *name, const char *value,
+                    int action_if_not_found, const char *format,
                     const char *default_value);
-int msOWSPrintEncodeParam(FILE *stream, const char *name, const char *value, 
-                          int action_if_not_found, const char *format, 
+int msOWSPrintEncodeParam(FILE *stream, const char *name, const char *value,
+                          int action_if_not_found, const char *format,
                           const char *default_value);
-int msOWSPrintMetadataList(FILE *stream, hashTableObj *metadata, 
-                           const char *namespaces, const char *name, 
-                           const char *startTag, 
+int msOWSPrintMetadataList(FILE *stream, hashTableObj *metadata,
+                           const char *namespaces, const char *name,
+                           const char *startTag,
                            const char *endTag, const char *itemFormat,
                            const char *default_value);
-int msOWSPrintEncodeMetadataList(FILE *stream, hashTableObj *metadata, 
-                                 const char *namespaces, const char *name, 
-                                 const char *startTag, 
+int msOWSPrintEncodeMetadataList(FILE *stream, hashTableObj *metadata,
+                                 const char *namespaces, const char *name,
+                                 const char *startTag,
                                  const char *endTag, const char *itemFormat,
                                  const char *default_value);
-int msOWSPrintEncodeParamList(FILE *stream, const char *name, 
-                              const char *value, int action_if_not_found, 
-                              char delimiter, const char *startTag, 
-                              const char *endTag, const char *format, 
+int msOWSPrintEncodeParamList(FILE *stream, const char *name,
+                              const char *value, int action_if_not_found,
+                              char delimiter, const char *startTag,
+                              const char *endTag, const char *format,
                               const char *default_value);
-void msOWSPrintLatLonBoundingBox(FILE *stream, const char *tabspace, 
+void msOWSPrintLatLonBoundingBox(FILE *stream, const char *tabspace,
                                  rectObj *extent, projectionObj *srcproj,
                                  projectionObj *wfsproj, int nService);
-void msOWSPrintEX_GeographicBoundingBox(FILE *stream, const char *tabspace, 
+void msOWSPrintEX_GeographicBoundingBox(FILE *stream, const char *tabspace,
                                         rectObj *extent, projectionObj *srcproj);
 
-void msOWSPrintBoundingBox(FILE *stream, const char *tabspace, 
-                           rectObj *extent, 
+void msOWSPrintBoundingBox(FILE *stream, const char *tabspace,
+                           rectObj *extent,
                            projectionObj *srcproj,
                            hashTableObj *layer_meta,
                            hashTableObj *map_meta,
                            const char *namespaces,
                            int wms_version);
-void msOWSPrintContactInfo( FILE *stream, const char *tabspace, 
+void msOWSPrintContactInfo( FILE *stream, const char *tabspace,
                             int nVersion, hashTableObj *metadata,
                             const char *namespaces  );
 int msOWSGetLayerExtent(mapObj *map, layerObj *lp, const char *namespaces, rectObj *ext);
@@ -241,26 +267,26 @@ int msOWSGetLayerExtent(mapObj *map, layerObj *lp, const char *namespaces, rectO
 int msOWSExecuteRequests(httpRequestObj *pasReqInfo, int numRequests,
                          mapObj *map, int bCheckLocalCache);
 
-void msOWSProcessException(layerObj *lp, const char *pszFname, 
+void msOWSProcessException(layerObj *lp, const char *pszFname,
                            int nErrorCode, const char *pszFuncName);
-char *msOWSBuildURLFilename(const char *pszPath, const char *pszURL, 
+char *msOWSBuildURLFilename(const char *pszPath, const char *pszURL,
                             const char *pszExt);
 const char *msOWSGetEPSGProj(projectionObj *proj, hashTableObj *metadata, const char *namespaces, int bReturnOnlyFirstOne);
 char *msOWSGetProjURN(projectionObj *proj, hashTableObj *metadata, const char *namespaces, int bReturnOnlyFirstOne);
 char *msOWSGetProjURI(projectionObj *proj, hashTableObj *metadata, const char *namespaces, int bReturnOnlyFirstOne);
 
-void msOWSGetDimensionInfo(layerObj *layer, const char *pszDimension, 
-                           const char **pszDimUserValue, 
-                           const char **pszDimUnits, 
-                           const char **pszDimDefault, 
-                           const char **pszDimNearValue, 
-                           const char **pszDimUnitSymbol, 
+void msOWSGetDimensionInfo(layerObj *layer, const char *pszDimension,
+                           const char **pszDimUserValue,
+                           const char **pszDimUnits,
+                           const char **pszDimDefault,
+                           const char **pszDimNearValue,
+                           const char **pszDimUnitSymbol,
                            const char **pszDimMultiValue);
 
 int msOWSNegotiateUpdateSequence(const char *requested_updateSequence, const char *updatesequence);
 
-outputFormatObj *msOwsIsOutputFormatValid(mapObj *map, const char *format, hashTableObj *metadata, 
-                                          const char *namespaces, const char *name);
+outputFormatObj *msOwsIsOutputFormatValid(mapObj *map, const char *format, hashTableObj *metadata,
+    const char *namespaces, const char *name);
 #endif /* #if any wxs service enabled */
 
 /*====================================================================
@@ -279,13 +305,13 @@ typedef struct {
   char *name;     /* name of the item */
   char *alias;    /* is the item aliased for presentation? (NULL if not) */
   char *type;     /* raw type for this item (NULL for a "string") (TODO: should this be a lookup table instead?) */
-#ifndef __cplusplus 
+#ifndef __cplusplus
   char *template;  /* presentation string for this item, needs to be a complete XML tag */
 #else
   char *_template;  /* presentation string for this item, needs to be a complete XML tag */
 #endif
   int encode;     /* should the value be HTML encoded? Default is MS_TRUE */
-  int visible;    /* should this item be output, default is MS_FALSE */  
+  int visible;    /* should this item be output, default is MS_FALSE */
   int width;      /* field width, zero if unknown */
   int precision;  /* field precision (decimal places), zero if unknown or N/A */
 } gmlItemObj;
@@ -330,9 +356,9 @@ typedef struct {
 } gmlGroupListObj;
 
 typedef struct {
-	char *prefix;
-	char *uri;
-	char *schemalocation;
+  char *prefix;
+  char *uri;
+  char *schemalocation;
 } gmlNamespaceObj;
 
 typedef struct {
@@ -360,17 +386,16 @@ MS_DLL_EXPORT int msGMLWriteQuery(mapObj *map, char *filename, const char *names
 
 
 #ifdef USE_WFS_SVR
-MS_DLL_EXPORT int msGMLWriteWFSQuery(mapObj *map, FILE *stream, int startindex, int maxfeatures, char *wfs_namespace, 
-                                     int outputformat);
+MS_DLL_EXPORT int msGMLWriteWFSQuery(mapObj *map, FILE *stream, char *wfs_namespace, int outputformat);
 #endif
 
 
 /*====================================================================
  *   mapwms.c
  *====================================================================*/
-int msWMSDispatch(mapObj *map, cgiRequestObj *req, owsRequestObj *ows_request, int force_wms_mode); 
+int msWMSDispatch(mapObj *map, cgiRequestObj *req, owsRequestObj *ows_request, int force_wms_mode);
 MS_DLL_EXPORT int msWMSLoadGetMapParams(mapObj *map, int nVersion,
-                                        char **names, char **values, int numentries, 
+                                        char **names, char **values, int numentries,
                                         char *wms_exception_format, const char *wms_request, owsRequestObj *ows_request);
 
 
@@ -378,22 +403,26 @@ MS_DLL_EXPORT int msWMSLoadGetMapParams(mapObj *map, int nVersion,
  *   mapwmslayer.c
  *====================================================================*/
 
+#define WMS_GETMAP         1
+#define WMS_GETFEATUREINFO 2
+#define WMS_GETLEGENDGRAPHIC 3
+
 int msInitWmsParamsObj(wmsParamsObj *wmsparams);
 void msFreeWmsParamsObj(wmsParamsObj *wmsparams);
 
 int msPrepareWMSLayerRequest(int nLayerId, mapObj *map, layerObj *lp,
-                             enum MS_CONNECTION_TYPE lastconnectiontype,
+                             int nRequestType, enum MS_CONNECTION_TYPE lastconnectiontype,
                              wmsParamsObj *psLastWMSParams,
+                             int nClickX, int nClickY, int nFeatureCount, const char *pszInfoFormat,
                              httpRequestObj *pasReqInfo, int *numRequests);
-int msDrawWMSLayerLow(int nLayerId, httpRequestObj *pasReqInfo, 
-                      int numRequests, mapObj *map, layerObj *lp, 
+int msDrawWMSLayerLow(int nLayerId, httpRequestObj *pasReqInfo,
+                      int numRequests, mapObj *map, layerObj *lp,
                       imageObj *img);
 MS_DLL_EXPORT char *msWMSGetFeatureInfoURL(mapObj *map, layerObj *lp,
-                             int nClickX, int nClickY, int nFeatureCount,
-                             const char *pszInfoFormat); 
-
-
-
+    int nClickX, int nClickY, int nFeatureCount,
+    const char *pszInfoFormat);
+int msWMSLayerExecuteRequest(mapObj *map, int nOWSLayers, int nClickX, int nClickY,
+                             int nFeatureCount, const char *pszInfoFormat, int type);
 
 /*====================================================================
  *   mapwfs.c
@@ -403,23 +432,23 @@ MS_DLL_EXPORT char *msWMSGetFeatureInfoURL(mapObj *map, layerObj *lp,
 #define OWS_DEFAULT_SCHEMA 0 /* basically a GML 2.1 schema */
 #define OWS_SFE_SCHEMA 1 /* GML for simple feature exchange (formerly GML3L0) */
 
-MS_DLL_EXPORT int msWFSDispatch(mapObj *map, cgiRequestObj *requestobj, 
+MS_DLL_EXPORT int msWFSDispatch(mapObj *map, cgiRequestObj *requestobj,
                                 owsRequestObj *ows_request, int force_wfs_mode);
 int msWFSParseRequest(mapObj *map, cgiRequestObj *, owsRequestObj *ows_request,
                       wfsParamsObj *, int force_wfs_mode);
 wfsParamsObj *msWFSCreateParamsObj(void);
 void msWFSFreeParamsObj(wfsParamsObj *wfsparams);
 int msWFSIsLayerSupported(layerObj *lp);
-int msWFSException(mapObj *map, const char *locator, const char *code, 
+int msWFSException(mapObj *map, const char *locator, const char *code,
                    const char *version);
 
 #ifdef USE_WFS_SVR
 const char *msWFSGetGeomElementName(mapObj *map, layerObj *lp);
 
-int msWFSException11(mapObj *map, const char *locator, 
+int msWFSException11(mapObj *map, const char *locator,
                      const char *exceptionCode, const char *version);
-int msWFSGetCapabilities11(mapObj *map, wfsParamsObj *wfsparams, 
-                           cgiRequestObj *req, owsRequestObj *ows_request); 
+int msWFSGetCapabilities11(mapObj *map, wfsParamsObj *wfsparams,
+                           cgiRequestObj *req, owsRequestObj *ows_request);
 char *msWFSGetOutputFormatList(mapObj *map, layerObj *layer,const char*version);
 #endif
 
@@ -430,9 +459,9 @@ char *msWFSGetOutputFormatList(mapObj *map, layerObj *layer,const char*version);
 int msPrepareWFSLayerRequest(int nLayerId, mapObj *map, layerObj *lp,
                              httpRequestObj *pasReqInfo, int *numRequests);
 void msWFSUpdateRequestInfo(layerObj *lp, httpRequestObj *pasReqInfo);
-int msWFSLayerOpen(layerObj *lp, 
+int msWFSLayerOpen(layerObj *lp,
                    const char *pszGMLFilename, rectObj *defaultBBOX);
-int msWFSLayerIsOpen(layerObj *lp); 
+int msWFSLayerIsOpen(layerObj *lp);
 int msWFSLayerInitItemInfo(layerObj *layer);
 int msWFSLayerGetItems(layerObj *layer);
 int msWFSLayerWhichShapes(layerObj *layer, rectObj rect, int isQuery);
diff --git a/mapowscommon.c b/mapowscommon.c
index 51a0298..eba2d02 100644
--- a/mapowscommon.c
+++ b/mapowscommon.c
@@ -6,7 +6,7 @@
  *           versions:
  *           1.0.0 (OGC Document 05-008c1)
  *           1.1.0 (OGC document 06-121r3)
- *           
+ *
  * Author:   Tom Kralidis (tomkralidis at hotmail.com)
  *
  ******************************************************************************
@@ -42,7 +42,7 @@
 #include "mapowscommon.h"
 #include "maplibxml2.h"
 
-MS_CVSID("$Id$")
+
 
 
 
@@ -62,7 +62,8 @@ MS_CVSID("$Id$")
  *
  */
 
-xmlNodePtr msOWSCommonServiceIdentification(xmlNsPtr psNsOws, mapObj *map, const char *servicetype, const char *version, const char *namespaces) {
+xmlNodePtr msOWSCommonServiceIdentification(xmlNsPtr psNsOws, mapObj *map, const char *servicetype, const char *version, const char *namespaces)
+{
   const char *value    = NULL;
 
   xmlNodePtr   psRootNode = NULL;
@@ -104,7 +105,7 @@ xmlNodePtr msOWSCommonServiceIdentification(xmlNsPtr psNsOws, mapObj *map, const
   }
 
   psNode = xmlNewChild(psRootNode, psNsOws, BAD_CAST "ServiceType", BAD_CAST servicetype);
-  
+
   xmlNewProp(psNode, BAD_CAST "codeSpace", BAD_CAST MS_OWSCOMMON_OGC_CODESPACE);
 
   psNode = xmlNewChild(psRootNode, psNsOws, BAD_CAST "ServiceTypeVersion", BAD_CAST version);
@@ -132,7 +133,7 @@ xmlNodePtr msOWSCommonServiceIdentification(xmlNsPtr psNsOws, mapObj *map, const
  * msOWSCommonServiceProvider()
  *
  * returns an object of ServiceProvider as per:
- * 
+ *
  *
  * 1.0.0 subclause 7.4.4
  * 1.1.0 subclause 7.4.5
@@ -144,7 +145,8 @@ xmlNodePtr msOWSCommonServiceIdentification(xmlNsPtr psNsOws, mapObj *map, const
  */
 
 xmlNodePtr msOWSCommonServiceProvider(xmlNsPtr psNsOws, xmlNsPtr psNsXLink,
-                                      mapObj *map, const char *namespaces) {
+                                      mapObj *map, const char *namespaces)
+{
   const char *value = NULL;
 
   xmlNodePtr   psNode          = NULL;
@@ -192,7 +194,7 @@ xmlNodePtr msOWSCommonServiceProvider(xmlNsPtr psNsOws, xmlNsPtr psNsXLink,
 
   value = msOWSLookupMetadata(&(map->web.metadata), namespaces, "contactposition");
 
-  psSubNode = xmlNewChild(psNode, psNsOws, BAD_CAST "PositionName", BAD_CAST value); 
+  psSubNode = xmlNewChild(psNode, psNsOws, BAD_CAST "PositionName", BAD_CAST value);
 
   if (!value) {
     xmlAddSibling(psSubNode, xmlNewComment(BAD_CAST "WARNING: Optional metadata \"ows_contactposition\" was missing for ows:PositionName"));
@@ -320,7 +322,8 @@ xmlNodePtr msOWSCommonServiceProvider(xmlNsPtr psNsOws, xmlNsPtr psNsXLink,
  *
  */
 
-xmlNodePtr msOWSCommonOperationsMetadata(xmlNsPtr psNsOws) {
+xmlNodePtr msOWSCommonOperationsMetadata(xmlNsPtr psNsOws)
+{
   xmlNodePtr psRootNode = NULL;
 
   if (_validateNamespace(psNsOws) == MS_FAILURE)
@@ -334,7 +337,7 @@ xmlNodePtr msOWSCommonOperationsMetadata(xmlNsPtr psNsOws) {
  * msOWSCommonOperationsMetadataOperation()
  *
  * returns an Operation element of OperationsMetadata as per:
- * 
+ *
  * 1.0.0 subclause 7.4.5
  * 1.1.0 subclause 7.4.6
  *
@@ -345,7 +348,8 @@ xmlNodePtr msOWSCommonOperationsMetadata(xmlNsPtr psNsOws) {
  * @return psRootNode xmlNodePtr pointer of XML construct
  */
 
-xmlNodePtr msOWSCommonOperationsMetadataOperation(xmlNsPtr psNsOws, xmlNsPtr psXLinkNs, char *name, int method, char *url) {
+xmlNodePtr msOWSCommonOperationsMetadataOperation(xmlNsPtr psNsOws, xmlNsPtr psXLinkNs, char *name, int method, char *url)
+{
   xmlNodePtr psRootNode      = NULL;
   xmlNodePtr psNode          = NULL;
   xmlNodePtr psSubNode       = NULL;
@@ -396,7 +400,8 @@ xmlNodePtr msOWSCommonOperationsMetadataOperation(xmlNsPtr psNsOws, xmlNsPtr psX
  *
  */
 
-xmlNodePtr msOWSCommonOperationsMetadataDomainType(int version, xmlNsPtr psNsOws, char *elname, char *name, char *values) {
+xmlNodePtr msOWSCommonOperationsMetadataDomainType(int version, xmlNsPtr psNsOws, char *elname, char *name, char *values)
+{
   xmlNodePtr psRootNode = NULL;
   xmlNodePtr psNode = NULL;
 
@@ -428,21 +433,21 @@ xmlNodePtr msOWSCommonOperationsMetadataDomainType(int version, xmlNsPtr psNsOws
  * @param version the version of the calling specification
  * @param language ISO3166 code of language
  * @param exceptionCode a code from the calling specification's list of exceptions, or from OWS Common
- * @param locator where the exception was encountered (i.e. "layers" keyword) 
+ * @param locator where the exception was encountered (i.e. "layers" keyword)
  * @param ExceptionText the actual error message
  *
  * @return psRootNode xmlNodePtr pointer of XML construct
  *
  */
 
-xmlNodePtr msOWSCommonExceptionReport(xmlNsPtr psNsOws, int ows_version, const char *schemas_location, const char *version, const char *language, const char *exceptionCode, const char *locator, const char *ExceptionText) {
+xmlNodePtr msOWSCommonExceptionReport(xmlNsPtr psNsOws, int ows_version, const char *schemas_location, const char *version, const char *language, const char *exceptionCode, const char *locator, const char *ExceptionText)
+{
   char *xsi_schemaLocation = NULL;
   char szVersionBuf[OWS_VERSION_MAXLEN];
 
   xmlNsPtr     psNsXsi     = NULL;
   xmlNodePtr   psRootNode  = NULL;
   xmlNodePtr   psMainNode  = NULL;
-  xmlNodePtr   psNode      = NULL;
 
   psRootNode = xmlNewNode(psNsOws, BAD_CAST "ExceptionReport");
 
@@ -479,7 +484,7 @@ xmlNodePtr msOWSCommonExceptionReport(xmlNsPtr psNsOws, int ows_version, const c
   }
 
   if (ExceptionText != NULL) {
-    psNode = xmlNewChild(psMainNode, NULL, BAD_CAST "ExceptionText", BAD_CAST ExceptionText);
+    xmlNewChild(psMainNode, NULL, BAD_CAST "ExceptionText", BAD_CAST ExceptionText);
   }
 
   free(xsi_schemaLocation);
@@ -505,23 +510,23 @@ xmlNodePtr msOWSCommonExceptionReport(xmlNsPtr psNsOws, int ows_version, const c
  * @return psRootNode xmlNodePtr pointer of XML construct
  */
 
-xmlNodePtr msOWSCommonBoundingBox(xmlNsPtr psNsOws, const char *crs, int dimensions, double minx, double miny, double maxx, double maxy) {
+xmlNodePtr msOWSCommonBoundingBox(xmlNsPtr psNsOws, const char *crs, int dimensions, double minx, double miny, double maxx, double maxy)
+{
   char LowerCorner[100];
   char UpperCorner[100];
   char dim_string[100];
   xmlNodePtr psRootNode = NULL;
 
   /* Do we need to reorient tuple axes? */
-  {
-      projectionObj proj;
+  if(crs && strstr(crs, "imageCRS") == NULL) {
+    projectionObj proj;
 
-      msInitProjection( &proj );
-      if( msLoadProjectionString( &proj, (char *) crs ) == 0 )
-      {
-          msAxisNormalizePoints( &proj, 1, &minx, &miny );
-          msAxisNormalizePoints( &proj, 1, &maxx, &maxy );
-      }
-      msFreeProjection( &proj );
+    msInitProjection( &proj );
+    if( msLoadProjectionString( &proj, (char *) crs ) == 0 ) {
+      msAxisNormalizePoints( &proj, 1, &minx, &miny );
+      msAxisNormalizePoints( &proj, 1, &maxx, &maxy );
+    }
+    msFreeProjection( &proj );
   }
 
 
@@ -562,13 +567,14 @@ xmlNodePtr msOWSCommonBoundingBox(xmlNsPtr psNsOws, const char *crs, int dimensi
  * @return psRootNode xmlNodePtr pointer of XML construct
  */
 
-xmlNodePtr msOWSCommonWGS84BoundingBox(xmlNsPtr psNsOws, int dimensions, double minx, double miny, double maxx, double maxy) {
+xmlNodePtr msOWSCommonWGS84BoundingBox(xmlNsPtr psNsOws, int dimensions, double minx, double miny, double maxx, double maxy)
+{
   char LowerCorner[100];
   char UpperCorner[100];
   char dim_string[100];
 
   xmlNodePtr psRootNode = NULL;
-  
+
   if (_validateNamespace(psNsOws) == MS_FAILURE)
     psNsOws = xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_OWS_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_OWS_NAMESPACE_PREFIX);
 
@@ -599,30 +605,29 @@ xmlNodePtr msOWSCommonWGS84BoundingBox(xmlNsPtr psNsOws, int dimensions, double
  *
  */
 
-int _validateNamespace(xmlNsPtr psNsOws) {
+int _validateNamespace(xmlNsPtr psNsOws)
+{
   char namespace_prefix[10];
   snprintf(namespace_prefix, sizeof(namespace_prefix), "%s", psNsOws->prefix);
   if (strcmp(namespace_prefix, MS_OWSCOMMON_OWS_NAMESPACE_PREFIX) == 0)
     return MS_SUCCESS;
-  else 
+  else
     return MS_FAILURE;
 }
 
-xmlNodePtr msOWSCommonxmlNewChildEncoded( xmlNodePtr psParent, xmlNsPtr psNs, const char* name, 
-					  const char *content, const char *encoding)
+xmlNodePtr msOWSCommonxmlNewChildEncoded( xmlNodePtr psParent, xmlNsPtr psNs, const char* name,
+    const char *content, const char *encoding)
 {
-    char *encoded = NULL;
-    xmlNodePtr psNode;
-
-    if (encoding && content)
-    {
-	encoded = msGetEncodedString(content, encoding);
-	psNode =  xmlNewChild(psParent, psNs, BAD_CAST name, BAD_CAST encoded);
-	msFree(encoded);
-	return psNode;
-    }
-    else
-      return xmlNewChild(psParent, psNs, BAD_CAST name, BAD_CAST content);
+  char *encoded = NULL;
+  xmlNodePtr psNode;
+
+  if (encoding && content) {
+    encoded = msGetEncodedString(content, encoding);
+    psNode =  xmlNewChild(psParent, psNs, BAD_CAST name, BAD_CAST encoded);
+    msFree(encoded);
+    return psNode;
+  } else
+    return xmlNewChild(psParent, psNs, BAD_CAST name, BAD_CAST content);
 }
 
 /*
@@ -632,61 +637,61 @@ xmlNodePtr msOWSCommonxmlNewChildEncoded( xmlNodePtr psParent, xmlNsPtr psNs, co
  */
 int msOWSSchemaValidation(const char* xml_schema, const char* xml)
 {
-    xmlSchemaPtr schema;
-    xmlSchemaParserCtxtPtr ctxt;
-    xmlSchemaValidCtxtPtr validctxt;
-    int ret;
-    xmlDocPtr doc;
+  xmlSchemaPtr schema;
+  xmlSchemaParserCtxtPtr ctxt;
+  xmlSchemaValidCtxtPtr validctxt;
+  int ret;
+  xmlDocPtr doc;
 
-    if (!xml_schema || !xml)
-      return MS_FAILURE;
+  if (!xml_schema || !xml)
+    return MS_FAILURE;
+
+  xmlInitParser();
+  schema = NULL;
+  ret = -1;
+
+  /* Open XML Schema File */
+  ctxt = xmlSchemaNewParserCtxt(xml_schema);
+  /*
+  else ctxt = xmlSchemaNewMemParserCtxt(xml_schema);
+  */
+  /*
+  xmlSchemaSetParserErrors(ctxt,
+                           (xmlSchemaValidityErrorFunc) libxml2_callback,
+                           (xmlSchemaValidityWarningFunc) libxml2_callback, stderr);
+  */
+
+  schema = xmlSchemaParse(ctxt);
+  xmlSchemaFreeParserCtxt(ctxt);
+
+  /* If XML Schema hasn't been rightly loaded */
+  if (schema == NULL) {
+    xmlSchemaCleanupTypes();
+    xmlMemoryDump();
+    xmlCleanupParser();
+    return ret;
+  }
 
-    xmlInitParser();
-    schema = NULL;
-    ret = -1;
+  doc = xmlParseDoc((xmlChar *)xml);
 
-    /* Open XML Schema File */
-    ctxt = xmlSchemaNewParserCtxt(xml_schema);
-    /*
-    else ctxt = xmlSchemaNewMemParserCtxt(xml_schema);
-    */
+  if (doc != NULL) {
+    /* Loading XML Schema content */
+    validctxt = xmlSchemaNewValidCtxt(schema);
     /*
-    xmlSchemaSetParserErrors(ctxt,
-                             (xmlSchemaValidityErrorFunc) libxml2_callback,
-                             (xmlSchemaValidityWarningFunc) libxml2_callback, stderr);
+    xmlSchemaSetValidErrors(validctxt,
+                            (xmlSchemaValidityErrorFunc) libxml2_callback,
+                            (xmlSchemaValidityWarningFunc) libxml2_callback, stderr);
     */
+    /* validation */
+    ret = xmlSchemaValidateDoc(validctxt, doc);
+    xmlSchemaFreeValidCtxt(validctxt);
+  }
 
-    schema = xmlSchemaParse(ctxt);
-    xmlSchemaFreeParserCtxt(ctxt);
-
-    /* If XML Schema hasn't been rightly loaded */
-    if (schema == NULL) {
-        xmlSchemaCleanupTypes();
-        xmlMemoryDump();
-        xmlCleanupParser();
-        return ret;
-    }
-
-    doc = xmlParseDoc((xmlChar *)xml);
-
-    if (doc != NULL) {
-        /* Loading XML Schema content */
-        validctxt = xmlSchemaNewValidCtxt(schema);
-        /*
-        xmlSchemaSetValidErrors(validctxt,
-                                (xmlSchemaValidityErrorFunc) libxml2_callback,
-                                (xmlSchemaValidityWarningFunc) libxml2_callback, stderr);
-        */
-        /* validation */
-        ret = xmlSchemaValidateDoc(validctxt, doc);
-        xmlSchemaFreeValidCtxt(validctxt);
-    }
-
-    xmlSchemaFree(schema);
-    xmlFreeDoc(doc);
-    xmlCleanupParser();
+  xmlSchemaFree(schema);
+  xmlFreeDoc(doc);
+  xmlCleanupParser();
 
-    return ret;
+  return ret;
 }
 
 #endif /* defined(USE_LIBXML2) */
@@ -705,7 +710,8 @@ int msOWSSchemaValidation(const char* xml_schema, const char* xml)
  *
  */
 
-int msOWSCommonNegotiateVersion(int requested_version, int supported_versions[], int num_supported_versions) {
+int msOWSCommonNegotiateVersion(int requested_version, int supported_versions[], int num_supported_versions)
+{
   int i;
 
   /* if version is not set return error */
diff --git a/mapowscommon.h b/mapowscommon.h
index 00e659f..6d1ba1b 100644
--- a/mapowscommon.h
+++ b/mapowscommon.h
@@ -73,23 +73,23 @@
 
 /* WCS namespaces */
 
-#define MS_OWSCOMMON_WCS_20_NAMESPACE_URI		"http://www.opengis.net/wcs/2.0"
+#define MS_OWSCOMMON_WCS_20_NAMESPACE_URI   "http://www.opengis.net/wcs/2.0"
 #define MS_OWSCOMMON_WCS_20_SCHEMAS_LOCATION    "/wcs/2.0/wcsAll.xsd"
-#define MS_OWSCOMMON_WCS_NAMESPACE_PREFIX		"wcs"
+#define MS_OWSCOMMON_WCS_NAMESPACE_PREFIX   "wcs"
 
 /* GML namespaces */
 
-#define MS_OWSCOMMON_GML_32_NAMESPACE_URI		"http://www.opengis.net/gml/3.2"
-#define MS_OWSCOMMON_GML_NAMESPACE_PREFIX		"gml"
+#define MS_OWSCOMMON_GML_32_NAMESPACE_URI   "http://www.opengis.net/gml/3.2"
+#define MS_OWSCOMMON_GML_NAMESPACE_PREFIX   "gml"
 
 /* GMLCov namespaces */
 
-#define MS_OWSCOMMON_GMLCOV_10_NAMESPACE_URI		"http://www.opengis.net/gmlcov/1.0"
-#define MS_OWSCOMMON_GMLCOV_NAMESPACE_PREFIX		"gmlcov"
+#define MS_OWSCOMMON_GMLCOV_10_NAMESPACE_URI    "http://www.opengis.net/gmlcov/1.0"
+#define MS_OWSCOMMON_GMLCOV_NAMESPACE_PREFIX    "gmlcov"
 
 /* SWE namespaces */
-#define MS_OWSCOMMON_SWE_20_NAMESPACE_URI		"http://www.opengis.net/swe/2.0"
-#define MS_OWSCOMMON_SWE_NAMESPACE_PREFIX		"swe"
+#define MS_OWSCOMMON_SWE_20_NAMESPACE_URI   "http://www.opengis.net/swe/2.0"
+#define MS_OWSCOMMON_SWE_NAMESPACE_PREFIX   "swe"
 
 /* function prototypes */
 
@@ -117,7 +117,7 @@ xmlNodePtr msOWSCommonWGS84BoundingBox(xmlNsPtr psNsOws, int dimensions, double
 int _validateNamespace(xmlNsPtr psNsOws);
 
 xmlNodePtr msOWSCommonxmlNewChildEncoded( xmlNodePtr psParent, xmlNsPtr psNs, const char* name,
-                                          const char *content, const char *encoding);
+    const char *content, const char *encoding);
 
 int msOWSSchemaValidation(const char* xml_schema, const char* xml);
 
diff --git a/mapparser.c b/mapparser.c
index d993309..9c1df10 100644
--- a/mapparser.c
+++ b/mapparser.c
@@ -1,23 +1,24 @@
-
-/* A Bison parser, made by GNU Bison 2.4.1.  */
+/* A Bison parser, made by GNU Bison 2.3.  */
 
 /* Skeleton implementation for Bison's Yacc-like parsers in C
-   
-      Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005, 2006
+
+   Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005, 2006
    Free Software Foundation, Inc.
-   
-   This program is free software: you can redistribute it and/or modify
+
+   This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
-   the Free Software Foundation, either version 3 of the License, or
-   (at your option) any later version.
-   
+   the Free Software Foundation; either version 2, or (at your option)
+   any later version.
+
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
-   
+
    You should have received a copy of the GNU General Public License
-   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+   along with this program; if not, write to the Free Software
+   Foundation, Inc., 51 Franklin Street, Fifth Floor,
+   Boston, MA 02110-1301, USA.  */
 
 /* As a special exception, you may create a larger work that contains
    part or all of the Bison parser skeleton and distribute that work
@@ -28,7 +29,7 @@
    special exception, which will cause the skeleton and the resulting
    Bison output files to be licensed under the GNU General Public
    License without this special exception.
-   
+
    This special exception was added by the Free Software Foundation in
    version 2.2 of Bison.  */
 
@@ -46,7 +47,7 @@
 #define YYBISON 1
 
 /* Bison version.  */
-#define YYBISON_VERSION "2.4.1"
+#define YYBISON_VERSION "2.3"
 
 /* Skeleton name.  */
 #define YYSKELETON_NAME "yacc.c"
@@ -54,61 +55,11 @@
 /* Pure parsers.  */
 #define YYPURE 1
 
-/* Push parsers.  */
-#define YYPUSH 0
-
-/* Pull parsers.  */
-#define YYPULL 1
-
 /* Using locations.  */
 #define YYLSP_NEEDED 0
 
 
 
-/* Copy the first part of user declarations.  */
-
-/* Line 189 of yacc.c  */
-#line 5 "mapparser.y"
-
-/* C declarations */
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <math.h>
-#include <time.h>
-
-#include "mapserver.h" /* for TRUE/FALSE and REGEX includes */
-#include "maptime.h" /* for time comparison routines */
-#include "mapprimitive.h" /* for shapeObj */
-
-#include "mapparser.h" /* for YYSTYPE in the function prototype for yylex() */
-
-int yylex(YYSTYPE *, parseObj *); /* prototype functions, defined after the grammar */
-int yyerror(parseObj *, const char *);
-
-
-/* Line 189 of yacc.c  */
-#line 92 "mapparser.c"
-
-/* Enabling traces.  */
-#ifndef YYDEBUG
-# define YYDEBUG 0
-#endif
-
-/* Enabling verbose error messages.  */
-#ifdef YYERROR_VERBOSE
-# undef YYERROR_VERBOSE
-# define YYERROR_VERBOSE 1
-#else
-# define YYERROR_VERBOSE 0
-#endif
-
-/* Enabling the token table.  */
-#ifndef YYTOKEN_TABLE
-# define YYTOKEN_TABLE 0
-#endif
-
-
 /* Tokens.  */
 #ifndef YYTOKENTYPE
 # define YYTOKENTYPE
@@ -146,8 +97,9 @@ int yyerror(parseObj *, const char *);
      LENGTH = 286,
      AREA = 287,
      TOSTRING = 288,
-     YYBUFFER = 289,
-     NEG = 290
+     DIFFERENCE = 289,
+     YYBUFFER = 290,
+     NEG = 291
    };
 #endif
 /* Tokens.  */
@@ -182,41 +134,76 @@ int yyerror(parseObj *, const char *);
 #define LENGTH 286
 #define AREA 287
 #define TOSTRING 288
-#define YYBUFFER 289
-#define NEG 290
+#define DIFFERENCE 289
+#define YYBUFFER 290
+#define NEG 291
+
+
+
+
+/* Copy the first part of user declarations.  */
+#line 5 "mapparser.y"
+
+/* C declarations */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <math.h>
+#include <time.h>
+
+#include "mapserver.h" /* for TRUE/FALSE and REGEX includes */
+#include "maptime.h" /* for time comparison routines */
+#include "mapprimitive.h" /* for shapeObj */
+
+#include "mapparser.h" /* for YYSTYPE in the function prototype for yylex() */
 
+int yylex(YYSTYPE *, parseObj *); /* prototype functions, defined after the grammar */
+int yyerror(parseObj *, const char *);
+
+
+/* Enabling traces.  */
+#ifndef YYDEBUG
+# define YYDEBUG 0
+#endif
 
+/* Enabling verbose error messages.  */
+#ifdef YYERROR_VERBOSE
+# undef YYERROR_VERBOSE
+# define YYERROR_VERBOSE 1
+#else
+# define YYERROR_VERBOSE 0
+#endif
 
+/* Enabling the token table.  */
+#ifndef YYTOKEN_TABLE
+# define YYTOKEN_TABLE 0
+#endif
 
 #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
 typedef union YYSTYPE
-{
-
-/* Line 214 of yacc.c  */
 #line 30 "mapparser.y"
-
+{
   double dblval;
   int intval;  
   char *strval;  
   struct tm tmval;
   shapeObj *shpval;
-
-
-
-/* Line 214 of yacc.c  */
-#line 208 "mapparser.c"
-} YYSTYPE;
-# define YYSTYPE_IS_TRIVIAL 1
+}
+/* Line 193 of yacc.c.  */
+#line 194 "mapparser.c"
+	YYSTYPE;
 # define yystype YYSTYPE /* obsolescent; will be withdrawn */
 # define YYSTYPE_IS_DECLARED 1
+# define YYSTYPE_IS_TRIVIAL 1
 #endif
 
 
+
 /* Copy the second part of user declarations.  */
 
 
-/* Line 264 of yacc.c  */
-#line 220 "mapparser.c"
+/* Line 216 of yacc.c.  */
+#line 207 "mapparser.c"
 
 #ifdef short
 # undef short
@@ -266,7 +253,7 @@ typedef short int yytype_int16;
 #define YYSIZE_MAXIMUM ((YYSIZE_T) -1)
 
 #ifndef YY_
-# if YYENABLE_NLS
+# if defined YYENABLE_NLS && YYENABLE_NLS
 #  if ENABLE_NLS
 #   include <libintl.h> /* INFRINGES ON USER NAME SPACE */
 #   define YY_(msgid) dgettext ("bison-runtime", msgid)
@@ -291,14 +278,14 @@ typedef short int yytype_int16;
 #if (defined __STDC__ || defined __C99__FUNC__ \
      || defined __cplusplus || defined _MSC_VER)
 static int
-YYID (int yyi)
+YYID (int i)
 #else
 static int
-YYID (yyi)
-    int yyi;
+YYID (i)
+    int i;
 #endif
 {
-  return yyi;
+  return i;
 }
 #endif
 
@@ -379,9 +366,9 @@ void free (void *); /* INFRINGES ON USER NAME SPACE */
 /* A type that is properly aligned for any stack member.  */
 union yyalloc
 {
-  yytype_int16 yyss_alloc;
-  YYSTYPE yyvs_alloc;
-};
+  yytype_int16 yyss;
+  YYSTYPE yyvs;
+  };
 
 /* The size of the maximum gap between one aligned stack and the next.  */
 # define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1)
@@ -415,12 +402,12 @@ union yyalloc
    elements in the stack, and YYPTR gives the new location of the
    stack.  Advance YYPTR to a properly aligned location for the next
    stack.  */
-# define YYSTACK_RELOCATE(Stack_alloc, Stack)				\
+# define YYSTACK_RELOCATE(Stack)					\
     do									\
       {									\
 	YYSIZE_T yynewbytes;						\
-	YYCOPY (&yyptr->Stack_alloc, Stack, yysize);			\
-	Stack = &yyptr->Stack_alloc;					\
+	YYCOPY (&yyptr->Stack, Stack, yysize);				\
+	Stack = &yyptr->Stack;						\
 	yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \
 	yyptr += yynewbytes / sizeof (*yyptr);				\
       }									\
@@ -429,22 +416,22 @@ union yyalloc
 #endif
 
 /* YYFINAL -- State number of the termination state.  */
-#define YYFINAL  37
+#define YYFINAL  39
 /* YYLAST -- Last index in YYTABLE.  */
-#define YYLAST   334
+#define YYLAST   362
 
 /* YYNTOKENS -- Number of terminals.  */
-#define YYNTOKENS  45
+#define YYNTOKENS  46
 /* YYNNTS -- Number of nonterminals.  */
 #define YYNNTS  7
 /* YYNRULES -- Number of rules.  */
-#define YYNRULES  74
+#define YYNRULES  75
 /* YYNRULES -- Number of states.  */
-#define YYNSTATES  164
+#define YYNSTATES  170
 
 /* YYTRANSLATE(YYLEX) -- Bison symbol number corresponding to YYLEX.  */
 #define YYUNDEFTOK  2
-#define YYMAXUTOK   290
+#define YYMAXUTOK   291
 
 #define YYTRANSLATE(YYX)						\
   ((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK)
@@ -455,13 +442,13 @@ static const yytype_uint8 yytranslate[] =
        0,     2,     2,     2,     2,     2,     2,     2,     2,     2,
        2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
        2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
-       2,     2,     2,     2,     2,     2,     2,    39,     2,     2,
-      42,    43,    37,    35,    44,    36,     2,    38,     2,     2,
+       2,     2,     2,     2,     2,     2,     2,    40,     2,     2,
+      43,    44,    38,    36,    45,    37,     2,    39,     2,     2,
        2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
        2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
        2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
        2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
-       2,     2,     2,     2,    41,     2,     2,     2,     2,     2,
+       2,     2,     2,     2,    42,     2,     2,     2,     2,     2,
        2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
        2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
        2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
@@ -481,7 +468,7 @@ static const yytype_uint8 yytranslate[] =
        5,     6,     7,     8,     9,    10,    11,    12,    13,    14,
       15,    16,    17,    18,    19,    20,    21,    22,    23,    24,
       25,    26,    27,    28,    29,    30,    31,    32,    33,    34,
-      40
+      35,    41
 };
 
 #if YYDEBUG
@@ -495,55 +482,56 @@ static const yytype_uint16 yyprhs[] =
      102,   106,   110,   114,   118,   122,   126,   130,   134,   138,
      142,   146,   150,   154,   158,   162,   166,   170,   174,   178,
      182,   186,   190,   194,   196,   200,   204,   208,   212,   216,
-     220,   223,   227,   232,   237,   244,   246,   250,   257,   259,
-     263,   267,   274,   279,   281
+     220,   223,   227,   232,   237,   244,   246,   250,   257,   264,
+     266,   270,   274,   281,   286,   288
 };
 
 /* YYRHS -- A `-1'-separated list of the rules' RHS.  */
 static const yytype_int8 yyrhs[] =
 {
-      46,     0,    -1,    -1,    47,    -1,    48,    -1,    50,    -1,
-      49,    -1,    47,     7,    47,    -1,    47,     8,    47,    -1,
-      47,     7,    48,    -1,    47,     8,    48,    -1,    48,     7,
-      47,    -1,    48,     8,    47,    -1,    48,     7,    48,    -1,
-      48,     8,    48,    -1,     9,    47,    -1,     9,    48,    -1,
-      50,    19,    50,    -1,    50,    10,    50,    -1,    48,    18,
-      48,    -1,    48,    17,    48,    -1,    48,    15,    48,    -1,
-      48,    16,    48,    -1,    48,    13,    48,    -1,    48,    14,
-      48,    -1,    42,    47,    43,    -1,    50,    18,    50,    -1,
-      50,    17,    50,    -1,    50,    15,    50,    -1,    50,    16,
-      50,    -1,    50,    13,    50,    -1,    50,    14,    50,    -1,
-      51,    18,    51,    -1,    51,    17,    51,    -1,    51,    15,
-      51,    -1,    51,    16,    51,    -1,    51,    13,    51,    -1,
-      51,    14,    51,    -1,    50,    12,    50,    -1,    48,    12,
-      50,    -1,    48,    11,    48,    -1,    50,    11,    50,    -1,
-      51,    11,    51,    -1,    49,    18,    49,    -1,    49,    28,
-      49,    -1,    49,    27,    49,    -1,    49,    26,    49,    -1,
-      49,    25,    49,    -1,    49,    24,    49,    -1,    49,    23,
-      49,    -1,    49,    22,    49,    -1,    49,    20,    49,    -1,
-      49,    21,    49,    -1,     3,    -1,    42,    48,    43,    -1,
-      48,    35,    48,    -1,    48,    36,    48,    -1,    48,    37,
-      48,    -1,    48,    39,    48,    -1,    48,    38,    48,    -1,
-      36,    48,    -1,    48,    41,    48,    -1,    31,    42,    50,
-      43,    -1,    32,    42,    49,    43,    -1,    29,    42,    48,
-      44,    48,    43,    -1,     6,    -1,    42,    49,    43,    -1,
-      34,    42,    49,    44,    48,    43,    -1,     4,    -1,    42,
-      50,    43,    -1,    50,    35,    50,    -1,    33,    42,    48,
-      44,    50,    43,    -1,    30,    42,    50,    43,    -1,     5,
-      -1,    42,    51,    43,    -1
+      47,     0,    -1,    -1,    48,    -1,    49,    -1,    51,    -1,
+      50,    -1,    48,     7,    48,    -1,    48,     8,    48,    -1,
+      48,     7,    49,    -1,    48,     8,    49,    -1,    49,     7,
+      48,    -1,    49,     8,    48,    -1,    49,     7,    49,    -1,
+      49,     8,    49,    -1,     9,    48,    -1,     9,    49,    -1,
+      51,    19,    51,    -1,    51,    10,    51,    -1,    49,    18,
+      49,    -1,    49,    17,    49,    -1,    49,    15,    49,    -1,
+      49,    16,    49,    -1,    49,    13,    49,    -1,    49,    14,
+      49,    -1,    43,    48,    44,    -1,    51,    18,    51,    -1,
+      51,    17,    51,    -1,    51,    15,    51,    -1,    51,    16,
+      51,    -1,    51,    13,    51,    -1,    51,    14,    51,    -1,
+      52,    18,    52,    -1,    52,    17,    52,    -1,    52,    15,
+      52,    -1,    52,    16,    52,    -1,    52,    13,    52,    -1,
+      52,    14,    52,    -1,    51,    12,    51,    -1,    49,    12,
+      51,    -1,    49,    11,    49,    -1,    51,    11,    51,    -1,
+      52,    11,    52,    -1,    50,    18,    50,    -1,    50,    28,
+      50,    -1,    50,    27,    50,    -1,    50,    26,    50,    -1,
+      50,    25,    50,    -1,    50,    24,    50,    -1,    50,    23,
+      50,    -1,    50,    22,    50,    -1,    50,    20,    50,    -1,
+      50,    21,    50,    -1,     3,    -1,    43,    49,    44,    -1,
+      49,    36,    49,    -1,    49,    37,    49,    -1,    49,    38,
+      49,    -1,    49,    40,    49,    -1,    49,    39,    49,    -1,
+      37,    49,    -1,    49,    42,    49,    -1,    31,    43,    51,
+      44,    -1,    32,    43,    50,    44,    -1,    29,    43,    49,
+      45,    49,    44,    -1,     6,    -1,    43,    50,    44,    -1,
+      35,    43,    50,    45,    49,    44,    -1,    34,    43,    50,
+      45,    50,    44,    -1,     4,    -1,    43,    51,    44,    -1,
+      51,    36,    51,    -1,    33,    43,    49,    45,    51,    44,
+      -1,    30,    43,    51,    44,    -1,     5,    -1,    43,    52,
+      44,    -1
 };
 
 /* YYRLINE[YYN] -- source line where rule number YYN was defined.  */
 static const yytype_uint16 yyrline[] =
 {
        0,    65,    65,    66,    79,    93,   106,   117,   125,   134,
-     142,   151,   159,   168,   176,   185,   186,   187,   200,   213,
-     219,   225,   231,   237,   243,   249,   250,   258,   266,   275,
-     283,   291,   299,   305,   311,   317,   323,   329,   335,   356,
-     377,   383,   391,   398,   409,   420,   431,   442,   453,   464,
-     475,   486,   496,   508,   509,   510,   511,   512,   513,   514,
-     521,   522,   523,   524,   532,   535,   536,   537,   549,   550,
-     551,   555,   559,   565,   566
+     142,   151,   159,   168,   176,   185,   186,   187,   202,   217,
+     223,   229,   235,   241,   247,   253,   254,   262,   270,   279,
+     287,   295,   303,   309,   315,   321,   327,   333,   339,   360,
+     381,   387,   395,   402,   413,   424,   435,   446,   457,   468,
+     479,   490,   500,   512,   513,   514,   515,   516,   517,   518,
+     525,   526,   527,   528,   536,   539,   540,   541,   551,   563,
+     564,   565,   569,   573,   579,   580
 };
 #endif
 
@@ -556,9 +544,10 @@ static const char *const yytname[] =
   "OR", "AND", "NOT", "IRE", "IEQ", "IN", "GE", "LE", "GT", "LT", "NE",
   "EQ", "RE", "DWITHIN", "BEYOND", "CONTAINS", "WITHIN", "CROSSES",
   "OVERLAPS", "TOUCHES", "DISJOINT", "INTERSECTS", "ROUND", "COMMIFY",
-  "LENGTH", "AREA", "TOSTRING", "YYBUFFER", "'+'", "'-'", "'*'", "'/'",
-  "'%'", "NEG", "'^'", "'('", "')'", "','", "$accept", "input",
-  "logical_exp", "math_exp", "shape_exp", "string_exp", "time_exp", 0
+  "LENGTH", "AREA", "TOSTRING", "DIFFERENCE", "YYBUFFER", "'+'", "'-'",
+  "'*'", "'/'", "'%'", "NEG", "'^'", "'('", "')'", "','", "$accept",
+  "input", "logical_exp", "math_exp", "shape_exp", "string_exp",
+  "time_exp", 0
 };
 #endif
 
@@ -570,22 +559,22 @@ static const yytype_uint16 yytoknum[] =
        0,   256,   257,   258,   259,   260,   261,   262,   263,   264,
      265,   266,   267,   268,   269,   270,   271,   272,   273,   274,
      275,   276,   277,   278,   279,   280,   281,   282,   283,   284,
-     285,   286,   287,   288,   289,    43,    45,    42,    47,    37,
-     290,    94,    40,    41,    44
+     285,   286,   287,   288,   289,   290,    43,    45,    42,    47,
+      37,   291,    94,    40,    41,    44
 };
 # endif
 
 /* YYR1[YYN] -- Symbol number of symbol that rule YYN derives.  */
 static const yytype_uint8 yyr1[] =
 {
-       0,    45,    46,    46,    46,    46,    46,    47,    47,    47,
-      47,    47,    47,    47,    47,    47,    47,    47,    47,    47,
-      47,    47,    47,    47,    47,    47,    47,    47,    47,    47,
-      47,    47,    47,    47,    47,    47,    47,    47,    47,    47,
-      47,    47,    47,    47,    47,    47,    47,    47,    47,    47,
-      47,    47,    47,    48,    48,    48,    48,    48,    48,    48,
-      48,    48,    48,    48,    48,    49,    49,    49,    50,    50,
-      50,    50,    50,    51,    51
+       0,    46,    47,    47,    47,    47,    47,    48,    48,    48,
+      48,    48,    48,    48,    48,    48,    48,    48,    48,    48,
+      48,    48,    48,    48,    48,    48,    48,    48,    48,    48,
+      48,    48,    48,    48,    48,    48,    48,    48,    48,    48,
+      48,    48,    48,    48,    48,    48,    48,    48,    48,    48,
+      48,    48,    48,    49,    49,    49,    49,    49,    49,    49,
+      49,    49,    49,    49,    49,    50,    50,    50,    50,    51,
+      51,    51,    51,    51,    52,    52
 };
 
 /* YYR2[YYN] -- Number of symbols composing right hand side of rule YYN.  */
@@ -597,8 +586,8 @@ static const yytype_uint8 yyr2[] =
        3,     3,     3,     3,     3,     3,     3,     3,     3,     3,
        3,     3,     3,     3,     3,     3,     3,     3,     3,     3,
        3,     3,     3,     1,     3,     3,     3,     3,     3,     3,
-       2,     3,     4,     4,     6,     1,     3,     6,     1,     3,
-       3,     6,     4,     1,     3
+       2,     3,     4,     4,     6,     1,     3,     6,     6,     1,
+       3,     3,     6,     4,     1,     3
 };
 
 /* YYDEFACT[STATE-NAME] -- Default rule to reduce with in state
@@ -606,29 +595,29 @@ static const yytype_uint8 yyr2[] =
    means the default is an error.  */
 static const yytype_uint8 yydefact[] =
 {
-       2,    53,    68,    73,    65,     0,     0,     0,     0,     0,
-       0,     0,     0,     0,     0,     3,     4,     6,     5,     0,
-      15,    16,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,    60,     0,     0,     0,     0,     0,     1,     0,     0,
+       2,    53,    69,    74,    65,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     3,     4,     6,     5,
+       0,    15,    16,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,    60,     0,     0,     0,     0,     0,     1,
        0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
        0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
        0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
        0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
        0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,    25,    54,    66,    69,    74,     7,     9,
-       8,    10,    11,    13,    12,    14,    40,    39,    23,    24,
-      21,    22,    20,    19,    55,    56,    57,    59,    58,    61,
-      43,    51,    52,    50,    49,    48,    47,    46,    45,    44,
-      18,    41,    38,    30,    31,    28,    29,    27,    26,    17,
-      70,     0,    42,    36,    37,    34,    35,    33,    32,     0,
-       0,    72,    62,     0,    63,     0,     0,     0,     0,     0,
-       0,    64,    71,    67
+       0,     0,     0,     0,     0,     0,    25,    54,    66,    70,
+      75,     7,     9,     8,    10,    11,    13,    12,    14,    40,
+      39,    23,    24,    21,    22,    20,    19,    55,    56,    57,
+      59,    58,    61,    43,    51,    52,    50,    49,    48,    47,
+      46,    45,    44,    18,    41,    38,    30,    31,    28,    29,
+      27,    26,    17,    71,     0,    42,    36,    37,    34,    35,
+      33,    32,     0,     0,    73,    62,     0,    63,     0,     0,
+       0,     0,     0,     0,     0,     0,    64,    72,    68,    67
 };
 
 /* YYDEFGOTO[NTERM-NUM].  */
 static const yytype_int8 yydefgoto[] =
 {
-      -1,    14,    15,    16,    22,    23,    19
+      -1,    15,    16,    17,    23,    24,    20
 };
 
 /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing
@@ -636,29 +625,29 @@ static const yytype_int8 yydefgoto[] =
 #define YYPACT_NINF -40
 static const yytype_int16 yypact[] =
 {
-     101,   -40,   -40,   -40,   -40,   101,   -39,   -21,   -14,   -10,
-      -4,     2,    -2,   101,    22,    10,   183,    91,   256,   309,
-     -40,   224,    91,   256,    -2,    59,    59,    -1,    -2,    -1,
-      -2,     9,    95,   133,   258,   215,    -7,   -40,   101,   101,
-     101,   101,    -2,    59,    -2,    -2,    -2,    -2,    -2,    -2,
-      -2,    -2,    -2,    -2,    -2,    -2,    -1,    -1,    -1,    -1,
-      -1,    -1,    -1,    -1,    -1,    -1,    59,    59,    59,    59,
-      59,    59,    59,    59,    59,    59,    59,    -3,    -3,    -3,
-      -3,    -3,    -3,    -3,   208,    59,   -20,   -19,    -1,    45,
-     259,    21,   174,   -40,   -40,   -40,   -40,   -40,    34,   167,
-     -40,   224,    34,   167,   -40,   224,   293,    55,   293,   293,
-     293,   293,   293,   293,   121,   121,     9,     9,     9,     9,
-     -40,   -40,   -40,   -40,   -40,   -40,   -40,   -40,   -40,   -40,
-      55,    55,    55,    55,    55,    55,    55,    55,    55,    55,
-     -40,    -3,   -40,   -40,   -40,   -40,   -40,   -40,   -40,    -2,
-      51,   -40,   -40,    53,   -40,    59,    -2,    54,   269,    52,
-     278,   -40,   -40,   -40
+       7,   -40,   -40,   -40,   -40,     7,   -39,   -38,   -28,    -8,
+       4,     5,     9,    68,     7,     8,    -5,   192,   298,   281,
+     171,   -40,   248,   298,   281,    68,    13,    13,   106,    68,
+     106,   106,    68,    12,    11,   154,   283,   239,   139,   -40,
+       7,     7,     7,     7,    68,    13,    68,    68,    68,    68,
+      68,    68,    68,    68,    68,    68,    68,    68,   106,   106,
+     106,   106,   106,   106,   106,   106,   106,   106,    13,    13,
+      13,    13,    13,    13,    13,    13,    13,    13,    13,     2,
+       2,     2,     2,     2,     2,     2,   231,    13,   -35,   -10,
+     106,    29,   292,    40,    42,   -15,   -40,   -40,   -40,   -40,
+     -40,    45,   206,   -40,   248,    45,   206,   -40,   248,   320,
+      21,   320,   320,   320,   320,   320,   320,    30,    30,    12,
+      12,    12,    12,   -40,   -40,   -40,   -40,   -40,   -40,   -40,
+     -40,   -40,   -40,    21,    21,    21,    21,    21,    21,    21,
+      21,    21,    21,   -40,     2,   -40,   -40,   -40,   -40,   -40,
+     -40,   -40,    68,    52,   -40,   -40,    47,   -40,    13,   106,
+      68,    48,   302,    65,    54,   311,   -40,   -40,   -40,   -40
 };
 
 /* YYPGOTO[NTERM-NUM].  */
 static const yytype_int16 yypgoto[] =
 {
-     -40,   -40,   148,     7,    64,     0,     1
+     -40,   -40,   134,    81,     0,     6,    35
 };
 
 /* YYTABLE[YYPACT[STATE-NUM]].  What to do in state STATE-NUM.  If
@@ -668,78 +657,84 @@ static const yytype_int16 yypgoto[] =
 #define YYTABLE_NINF -1
 static const yytype_uint8 yytable[] =
 {
-      18,     1,     3,    24,    77,     4,    78,    79,    80,    81,
-      82,    83,    21,    35,    36,    76,    76,    38,    39,    31,
-      33,    25,    37,   151,   152,    86,    87,     6,    26,     8,
-       9,    84,    27,    11,    12,    90,    97,    92,    28,   141,
-      30,    88,    39,   107,    29,    99,   101,   103,   105,   106,
-      55,   108,   109,   110,   111,   112,   113,   114,   115,   116,
-     117,   118,   119,     2,    17,   156,   130,   131,   132,   133,
-     134,   135,   136,   137,   138,   139,   140,    34,   142,   143,
-     144,   145,   146,   147,   148,   150,    76,    76,   154,     7,
-      76,    89,    10,    91,    96,   162,    95,    97,     0,     0,
-       0,    85,    38,    39,     1,     2,     3,     4,     0,    56,
-       5,    57,    58,    59,    60,    61,    62,    63,    64,    65,
-     120,   121,   122,   123,   124,   125,   126,   127,   128,   129,
-       6,     7,     8,     9,    10,    11,     0,    12,    93,     0,
-      40,    41,   157,    13,    42,    43,    44,    45,    46,    47,
-      48,    49,   153,    20,     0,   159,   158,     0,    52,    53,
-      54,    32,    55,   160,     0,     0,     0,     0,    50,    51,
-      52,    53,    54,     0,    55,    41,    94,     0,    42,    43,
-      44,    45,    46,    47,    48,    49,    98,   100,   102,   104,
-      40,    41,     0,     0,    42,    43,    44,    45,    46,    47,
-      48,    49,    50,    51,    52,    53,    54,     0,    55,    50,
-      51,    52,    53,    54,     0,    55,     0,    94,    50,    51,
-      52,    53,    54,     0,    55,    66,    67,    68,    69,    70,
-      71,    72,    73,    74,    75,    42,    43,    44,    45,    46,
-      47,    48,    49,    50,    51,    52,    53,    54,     0,    55,
-      76,     0,   149,     0,     0,     0,     0,     0,    96,    50,
-      51,    52,    53,    54,     0,    55,    66,    67,    68,    69,
-      70,    71,    72,    73,    74,    75,    56,     0,    57,    58,
-      59,    60,    61,    62,    63,    64,    65,     0,     0,     0,
-       0,    76,     0,     0,    50,    51,    52,    53,    54,     0,
-      55,    95,     0,   155,    50,    51,    52,    53,    54,     0,
-      55,     0,   161,    50,    51,    52,    53,    54,     0,    55,
-      77,   163,    78,    79,    80,    81,    82,    83,    50,    51,
-      52,    53,    54,     0,    55
+      18,    78,    40,    41,    25,    26,    19,     3,    39,   154,
+       1,     2,     3,     4,    36,    27,     5,     2,    40,    41,
+      37,    52,    53,    54,    55,    56,    78,    57,    91,    97,
+      93,    94,    88,    89,   155,    28,     6,     7,     8,     9,
+      10,    11,    12,     7,    13,   144,    10,    29,    30,    38,
+      14,   110,    31,    41,    57,    96,    87,    78,   123,   124,
+     125,   126,   127,   128,   129,   130,   131,   132,    54,    55,
+      56,     1,    57,   157,   133,   134,   135,   136,   137,   138,
+     139,   140,   141,   142,   143,   159,    22,   160,    78,     0,
+     156,    98,   100,   153,    33,    35,    99,     6,   168,     8,
+       9,    78,     0,     0,     0,    13,    86,     0,     0,   167,
+      92,    32,     4,    95,   145,   146,   147,   148,   149,   150,
+     151,   102,   104,   106,   108,   109,     0,   111,   112,   113,
+     114,   115,   116,   117,   118,   119,   120,   121,   122,    21,
+      11,    12,     0,     0,     0,     0,     0,     0,    34,    90,
+      79,     0,    80,    81,    82,    83,    84,    85,     0,   164,
+       0,    42,    43,     0,   163,    44,    45,    46,    47,    48,
+      49,    50,    51,     0,   101,   103,   105,   107,     0,   161,
+       0,     0,    79,   100,    80,    81,    82,    83,    84,    85,
+      52,    53,    54,    55,    56,     0,    57,     0,    97,    42,
+      43,     0,     0,    44,    45,    46,    47,    48,    49,    50,
+      51,     0,     0,     0,    43,     0,     0,    44,    45,    46,
+      47,    48,    49,    50,    51,     0,     0,     0,    52,    53,
+      54,    55,    56,   162,    57,     0,     0,     0,     0,     0,
+       0,   165,    52,    53,    54,    55,    56,     0,    57,    68,
+      69,    70,    71,    72,    73,    74,    75,    76,    77,    44,
+      45,    46,    47,    48,    49,    50,    51,    52,    53,    54,
+      55,    56,     0,    57,     0,    78,   152,     0,     0,     0,
+       0,     0,     0,    99,    52,    53,    54,    55,    56,     0,
+      57,    68,    69,    70,    71,    72,    73,    74,    75,    76,
+      77,    58,     0,    59,    60,    61,    62,    63,    64,    65,
+      66,    67,     0,     0,     0,     0,    58,    78,    59,    60,
+      61,    62,    63,    64,    65,    66,    67,    98,    52,    53,
+      54,    55,    56,     0,    57,     0,     0,   158,    52,    53,
+      54,    55,    56,     0,    57,     0,   166,    52,    53,    54,
+      55,    56,     0,    57,     0,   169,    52,    53,    54,    55,
+      56,     0,    57
 };
 
 static const yytype_int16 yycheck[] =
 {
-       0,     3,     5,    42,    11,     6,    13,    14,    15,    16,
-      17,    18,     5,    13,    13,    35,    35,     7,     8,    12,
-      13,    42,     0,    43,    43,    25,    26,    29,    42,    31,
-      32,    24,    42,    34,    36,    28,    43,    30,    42,    42,
-      42,    42,     8,    43,    42,    38,    39,    40,    41,    42,
-      41,    44,    45,    46,    47,    48,    49,    50,    51,    52,
-      53,    54,    55,     4,     0,    44,    66,    67,    68,    69,
-      70,    71,    72,    73,    74,    75,    76,    13,    77,    78,
-      79,    80,    81,    82,    83,    85,    35,    35,    43,    30,
-      35,    27,    33,    29,    43,    43,    43,    43,    -1,    -1,
-      -1,    42,     7,     8,     3,     4,     5,     6,    -1,    18,
-       9,    20,    21,    22,    23,    24,    25,    26,    27,    28,
-      56,    57,    58,    59,    60,    61,    62,    63,    64,    65,
-      29,    30,    31,    32,    33,    34,    -1,    36,    43,    -1,
-       7,     8,   141,    42,    11,    12,    13,    14,    15,    16,
-      17,    18,    88,     5,    -1,   155,   149,    -1,    37,    38,
-      39,    13,    41,   156,    -1,    -1,    -1,    -1,    35,    36,
-      37,    38,    39,    -1,    41,     8,    43,    -1,    11,    12,
-      13,    14,    15,    16,    17,    18,    38,    39,    40,    41,
-       7,     8,    -1,    -1,    11,    12,    13,    14,    15,    16,
-      17,    18,    35,    36,    37,    38,    39,    -1,    41,    35,
-      36,    37,    38,    39,    -1,    41,    -1,    43,    35,    36,
-      37,    38,    39,    -1,    41,    10,    11,    12,    13,    14,
-      15,    16,    17,    18,    19,    11,    12,    13,    14,    15,
-      16,    17,    18,    35,    36,    37,    38,    39,    -1,    41,
-      35,    -1,    44,    -1,    -1,    -1,    -1,    -1,    43,    35,
-      36,    37,    38,    39,    -1,    41,    10,    11,    12,    13,
-      14,    15,    16,    17,    18,    19,    18,    -1,    20,    21,
-      22,    23,    24,    25,    26,    27,    28,    -1,    -1,    -1,
-      -1,    35,    -1,    -1,    35,    36,    37,    38,    39,    -1,
-      41,    43,    -1,    44,    35,    36,    37,    38,    39,    -1,
-      41,    -1,    43,    35,    36,    37,    38,    39,    -1,    41,
-      11,    43,    13,    14,    15,    16,    17,    18,    35,    36,
-      37,    38,    39,    -1,    41
+       0,    36,     7,     8,    43,    43,     0,     5,     0,    44,
+       3,     4,     5,     6,    14,    43,     9,     4,     7,     8,
+      14,    36,    37,    38,    39,    40,    36,    42,    28,    44,
+      30,    31,    26,    27,    44,    43,    29,    30,    31,    32,
+      33,    34,    35,    30,    37,    43,    33,    43,    43,    14,
+      43,    45,    43,     8,    42,    44,    43,    36,    58,    59,
+      60,    61,    62,    63,    64,    65,    66,    67,    38,    39,
+      40,     3,    42,    44,    68,    69,    70,    71,    72,    73,
+      74,    75,    76,    77,    78,    45,     5,    45,    36,    -1,
+      90,    44,    44,    87,    13,    14,    44,    29,    44,    31,
+      32,    36,    -1,    -1,    -1,    37,    25,    -1,    -1,    44,
+      29,    43,     6,    32,    79,    80,    81,    82,    83,    84,
+      85,    40,    41,    42,    43,    44,    -1,    46,    47,    48,
+      49,    50,    51,    52,    53,    54,    55,    56,    57,     5,
+      34,    35,    -1,    -1,    -1,    -1,    -1,    -1,    14,    43,
+      11,    -1,    13,    14,    15,    16,    17,    18,    -1,   159,
+      -1,     7,     8,    -1,   158,    11,    12,    13,    14,    15,
+      16,    17,    18,    -1,    40,    41,    42,    43,    -1,   144,
+      -1,    -1,    11,    44,    13,    14,    15,    16,    17,    18,
+      36,    37,    38,    39,    40,    -1,    42,    -1,    44,     7,
+       8,    -1,    -1,    11,    12,    13,    14,    15,    16,    17,
+      18,    -1,    -1,    -1,     8,    -1,    -1,    11,    12,    13,
+      14,    15,    16,    17,    18,    -1,    -1,    -1,    36,    37,
+      38,    39,    40,   152,    42,    -1,    -1,    -1,    -1,    -1,
+      -1,   160,    36,    37,    38,    39,    40,    -1,    42,    10,
+      11,    12,    13,    14,    15,    16,    17,    18,    19,    11,
+      12,    13,    14,    15,    16,    17,    18,    36,    37,    38,
+      39,    40,    -1,    42,    -1,    36,    45,    -1,    -1,    -1,
+      -1,    -1,    -1,    44,    36,    37,    38,    39,    40,    -1,
+      42,    10,    11,    12,    13,    14,    15,    16,    17,    18,
+      19,    18,    -1,    20,    21,    22,    23,    24,    25,    26,
+      27,    28,    -1,    -1,    -1,    -1,    18,    36,    20,    21,
+      22,    23,    24,    25,    26,    27,    28,    44,    36,    37,
+      38,    39,    40,    -1,    42,    -1,    -1,    45,    36,    37,
+      38,    39,    40,    -1,    42,    -1,    44,    36,    37,    38,
+      39,    40,    -1,    42,    -1,    44,    36,    37,    38,    39,
+      40,    -1,    42
 };
 
 /* YYSTOS[STATE-NUM] -- The (internal number of the) accessing
@@ -747,22 +742,22 @@ static const yytype_int16 yycheck[] =
 static const yytype_uint8 yystos[] =
 {
        0,     3,     4,     5,     6,     9,    29,    30,    31,    32,
-      33,    34,    36,    42,    46,    47,    48,    49,    50,    51,
-      47,    48,    49,    50,    42,    42,    42,    42,    42,    42,
-      42,    48,    47,    48,    49,    50,    51,     0,     7,     8,
-       7,     8,    11,    12,    13,    14,    15,    16,    17,    18,
-      35,    36,    37,    38,    39,    41,    18,    20,    21,    22,
-      23,    24,    25,    26,    27,    28,    10,    11,    12,    13,
-      14,    15,    16,    17,    18,    19,    35,    11,    13,    14,
-      15,    16,    17,    18,    48,    42,    50,    50,    42,    49,
-      48,    49,    48,    43,    43,    43,    43,    43,    47,    48,
-      47,    48,    47,    48,    47,    48,    48,    50,    48,    48,
-      48,    48,    48,    48,    48,    48,    48,    48,    48,    48,
-      49,    49,    49,    49,    49,    49,    49,    49,    49,    49,
-      50,    50,    50,    50,    50,    50,    50,    50,    50,    50,
-      50,    42,    51,    51,    51,    51,    51,    51,    51,    44,
-      50,    43,    43,    49,    43,    44,    44,    51,    48,    50,
-      48,    43,    43,    43
+      33,    34,    35,    37,    43,    47,    48,    49,    50,    51,
+      52,    48,    49,    50,    51,    43,    43,    43,    43,    43,
+      43,    43,    43,    49,    48,    49,    50,    51,    52,     0,
+       7,     8,     7,     8,    11,    12,    13,    14,    15,    16,
+      17,    18,    36,    37,    38,    39,    40,    42,    18,    20,
+      21,    22,    23,    24,    25,    26,    27,    28,    10,    11,
+      12,    13,    14,    15,    16,    17,    18,    19,    36,    11,
+      13,    14,    15,    16,    17,    18,    49,    43,    51,    51,
+      43,    50,    49,    50,    50,    49,    44,    44,    44,    44,
+      44,    48,    49,    48,    49,    48,    49,    48,    49,    49,
+      51,    49,    49,    49,    49,    49,    49,    49,    49,    49,
+      49,    49,    49,    50,    50,    50,    50,    50,    50,    50,
+      50,    50,    50,    51,    51,    51,    51,    51,    51,    51,
+      51,    51,    51,    51,    43,    52,    52,    52,    52,    52,
+      52,    52,    45,    51,    44,    44,    50,    44,    45,    45,
+      45,    52,    49,    51,    50,    49,    44,    44,    44,    44
 };
 
 #define yyerrok		(yyerrstatus = 0)
@@ -836,7 +831,7 @@ while (YYID (0))
    we won't break user code: when these are the locations we know.  */
 
 #ifndef YY_LOCATION_PRINT
-# if YYLTYPE_IS_TRIVIAL
+# if defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL
 #  define YY_LOCATION_PRINT(File, Loc)			\
      fprintf (File, "%d.%d-%d.%d",			\
 	      (Loc).first_line, (Loc).first_column,	\
@@ -950,20 +945,17 @@ yy_symbol_print (yyoutput, yytype, yyvaluep, p)
 #if (defined __STDC__ || defined __C99__FUNC__ \
      || defined __cplusplus || defined _MSC_VER)
 static void
-yy_stack_print (yytype_int16 *yybottom, yytype_int16 *yytop)
+yy_stack_print (yytype_int16 *bottom, yytype_int16 *top)
 #else
 static void
-yy_stack_print (yybottom, yytop)
-    yytype_int16 *yybottom;
-    yytype_int16 *yytop;
+yy_stack_print (bottom, top)
+    yytype_int16 *bottom;
+    yytype_int16 *top;
 #endif
 {
   YYFPRINTF (stderr, "Stack now");
-  for (; yybottom <= yytop; yybottom++)
-    {
-      int yybot = *yybottom;
-      YYFPRINTF (stderr, " %d", yybot);
-    }
+  for (; bottom <= top; ++bottom)
+    YYFPRINTF (stderr, " %d", *bottom);
   YYFPRINTF (stderr, "\n");
 }
 
@@ -998,11 +990,11 @@ yy_reduce_print (yyvsp, yyrule, p)
   /* The symbols being reduced.  */
   for (yyi = 0; yyi < yynrhs; yyi++)
     {
-      YYFPRINTF (stderr, "   $%d = ", yyi + 1);
+      fprintf (stderr, "   $%d = ", yyi + 1);
       yy_symbol_print (stderr, yyrhs[yyprhs[yyrule] + yyi],
 		       &(yyvsp[(yyi + 1) - (yynrhs)])
 		       		       , p);
-      YYFPRINTF (stderr, "\n");
+      fprintf (stderr, "\n");
     }
 }
 
@@ -1284,8 +1276,10 @@ yydestruct (yymsg, yytype, yyvaluep, p)
 	break;
     }
 }
+
 
 /* Prevent warnings from -Wmissing-prototypes.  */
+
 #ifdef YYPARSE_PARAM
 #if defined __STDC__ || defined __cplusplus
 int yyparse (void *YYPARSE_PARAM);
@@ -1304,9 +1298,10 @@ int yyparse ();
 
 
 
-/*-------------------------.
-| yyparse or yypush_parse.  |
-`-------------------------*/
+
+/*----------.
+| yyparse.  |
+`----------*/
 
 #ifdef YYPARSE_PARAM
 #if (defined __STDC__ || defined __C99__FUNC__ \
@@ -1330,46 +1325,22 @@ yyparse (p)
 #endif
 #endif
 {
-/* The lookahead symbol.  */
+  /* The look-ahead symbol.  */
 int yychar;
 
-/* The semantic value of the lookahead symbol.  */
+/* The semantic value of the look-ahead symbol.  */
 YYSTYPE yylval;
 
-    /* Number of syntax errors so far.  */
-    int yynerrs;
-
-    int yystate;
-    /* Number of tokens to shift before error messages enabled.  */
-    int yyerrstatus;
-
-    /* The stacks and their tools:
-       `yyss': related to states.
-       `yyvs': related to semantic values.
-
-       Refer to the stacks thru separate pointers, to allow yyoverflow
-       to reallocate them elsewhere.  */
-
-    /* The state stack.  */
-    yytype_int16 yyssa[YYINITDEPTH];
-    yytype_int16 *yyss;
-    yytype_int16 *yyssp;
-
-    /* The semantic value stack.  */
-    YYSTYPE yyvsa[YYINITDEPTH];
-    YYSTYPE *yyvs;
-    YYSTYPE *yyvsp;
-
-    YYSIZE_T yystacksize;
+/* Number of syntax errors so far.  */
+int yynerrs;
 
+  int yystate;
   int yyn;
   int yyresult;
-  /* Lookahead token as an internal (translated) token number.  */
-  int yytoken;
-  /* The variables used to return semantic value and location from the
-     action routines.  */
-  YYSTYPE yyval;
-
+  /* Number of tokens to shift before error messages enabled.  */
+  int yyerrstatus;
+  /* Look-ahead token as an internal (translated) token number.  */
+  int yytoken = 0;
 #if YYERROR_VERBOSE
   /* Buffer for error messages, and its allocated size.  */
   char yymsgbuf[128];
@@ -1377,28 +1348,51 @@ YYSTYPE yylval;
   YYSIZE_T yymsg_alloc = sizeof yymsgbuf;
 #endif
 
+  /* Three stacks and their tools:
+     `yyss': related to states,
+     `yyvs': related to semantic values,
+     `yyls': related to locations.
+
+     Refer to the stacks thru separate pointers, to allow yyoverflow
+     to reallocate them elsewhere.  */
+
+  /* The state stack.  */
+  yytype_int16 yyssa[YYINITDEPTH];
+  yytype_int16 *yyss = yyssa;
+  yytype_int16 *yyssp;
+
+  /* The semantic value stack.  */
+  YYSTYPE yyvsa[YYINITDEPTH];
+  YYSTYPE *yyvs = yyvsa;
+  YYSTYPE *yyvsp;
+
+
+
 #define YYPOPSTACK(N)   (yyvsp -= (N), yyssp -= (N))
 
+  YYSIZE_T yystacksize = YYINITDEPTH;
+
+  /* The variables used to return semantic value and location from the
+     action routines.  */
+  YYSTYPE yyval;
+
+
   /* The number of symbols on the RHS of the reduced rule.
      Keep to zero when no symbol should be popped.  */
   int yylen = 0;
 
-  yytoken = 0;
-  yyss = yyssa;
-  yyvs = yyvsa;
-  yystacksize = YYINITDEPTH;
-
   YYDPRINTF ((stderr, "Starting parse\n"));
 
   yystate = 0;
   yyerrstatus = 0;
   yynerrs = 0;
-  yychar = YYEMPTY; /* Cause a token to be read.  */
+  yychar = YYEMPTY;		/* Cause a token to be read.  */
 
   /* Initialize stack pointers.
      Waste one element of value and location stack
      so that they stay on the same level as the state stack.
      The wasted elements are never initialized.  */
+
   yyssp = yyss;
   yyvsp = yyvs;
 
@@ -1428,6 +1422,7 @@ YYSTYPE yylval;
 	YYSTYPE *yyvs1 = yyvs;
 	yytype_int16 *yyss1 = yyss;
 
+
 	/* Each stack pointer address is followed by the size of the
 	   data in use in that stack, in bytes.  This used to be a
 	   conditional around just the two extra args, but that might
@@ -1435,6 +1430,7 @@ YYSTYPE yylval;
 	yyoverflow (YY_("memory exhausted"),
 		    &yyss1, yysize * sizeof (*yyssp),
 		    &yyvs1, yysize * sizeof (*yyvsp),
+
 		    &yystacksize);
 
 	yyss = yyss1;
@@ -1457,8 +1453,9 @@ YYSTYPE yylval;
 	  (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize));
 	if (! yyptr)
 	  goto yyexhaustedlab;
-	YYSTACK_RELOCATE (yyss_alloc, yyss);
-	YYSTACK_RELOCATE (yyvs_alloc, yyvs);
+	YYSTACK_RELOCATE (yyss);
+	YYSTACK_RELOCATE (yyvs);
+
 #  undef YYSTACK_RELOCATE
 	if (yyss1 != yyssa)
 	  YYSTACK_FREE (yyss1);
@@ -1469,6 +1466,7 @@ YYSTYPE yylval;
       yyssp = yyss + yysize - 1;
       yyvsp = yyvs + yysize - 1;
 
+
       YYDPRINTF ((stderr, "Stack size increased to %lu\n",
 		  (unsigned long int) yystacksize));
 
@@ -1478,9 +1476,6 @@ YYSTYPE yylval;
 
   YYDPRINTF ((stderr, "Entering state %d\n", yystate));
 
-  if (yystate == YYFINAL)
-    YYACCEPT;
-
   goto yybackup;
 
 /*-----------.
@@ -1489,16 +1484,16 @@ YYSTYPE yylval;
 yybackup:
 
   /* Do appropriate processing given the current state.  Read a
-     lookahead token if we need one and don't already have one.  */
+     look-ahead token if we need one and don't already have one.  */
 
-  /* First try to decide what to do without reference to lookahead token.  */
+  /* First try to decide what to do without reference to look-ahead token.  */
   yyn = yypact[yystate];
   if (yyn == YYPACT_NINF)
     goto yydefault;
 
-  /* Not known => get a lookahead token if don't already have one.  */
+  /* Not known => get a look-ahead token if don't already have one.  */
 
-  /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol.  */
+  /* YYCHAR is either YYEMPTY or YYEOF or a valid look-ahead symbol.  */
   if (yychar == YYEMPTY)
     {
       YYDPRINTF ((stderr, "Reading a token: "));
@@ -1530,16 +1525,20 @@ yybackup:
       goto yyreduce;
     }
 
+  if (yyn == YYFINAL)
+    YYACCEPT;
+
   /* Count tokens shifted since error; after three, turn off error
      status.  */
   if (yyerrstatus)
     yyerrstatus--;
 
-  /* Shift the lookahead token.  */
+  /* Shift the look-ahead token.  */
   YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc);
 
-  /* Discard the shifted token.  */
-  yychar = YYEMPTY;
+  /* Discard the shifted token unless it is eof.  */
+  if (yychar != YYEOF)
+    yychar = YYEMPTY;
 
   yystate = yyn;
   *++yyvsp = yylval;
@@ -1579,8 +1578,6 @@ yyreduce:
   switch (yyn)
     {
         case 3:
-
-/* Line 1455 of yacc.c  */
 #line 66 "mapparser.y"
     {
       switch(p->type) {
@@ -1598,8 +1595,6 @@ yyreduce:
     break;
 
   case 4:
-
-/* Line 1455 of yacc.c  */
 #line 79 "mapparser.y"
     {
       switch(p->type) {
@@ -1618,8 +1613,6 @@ yyreduce:
     break;
 
   case 5:
-
-/* Line 1455 of yacc.c  */
 #line 93 "mapparser.y"
     {
       switch(p->type) {
@@ -1637,8 +1630,6 @@ yyreduce:
     break;
 
   case 6:
-
-/* Line 1455 of yacc.c  */
 #line 106 "mapparser.y"
     {
     switch(p->type) {
@@ -1651,8 +1642,6 @@ yyreduce:
     break;
 
   case 7:
-
-/* Line 1455 of yacc.c  */
 #line 117 "mapparser.y"
     {
 	                                 if((yyvsp[(1) - (3)].intval) == MS_TRUE)
@@ -1665,8 +1654,6 @@ yyreduce:
     break;
 
   case 8:
-
-/* Line 1455 of yacc.c  */
 #line 125 "mapparser.y"
     {
 	                                 if((yyvsp[(1) - (3)].intval) == MS_TRUE) {
@@ -1680,8 +1667,6 @@ yyreduce:
     break;
 
   case 9:
-
-/* Line 1455 of yacc.c  */
 #line 134 "mapparser.y"
     {
 	                                 if((yyvsp[(1) - (3)].intval) == MS_TRUE)
@@ -1694,8 +1679,6 @@ yyreduce:
     break;
 
   case 10:
-
-/* Line 1455 of yacc.c  */
 #line 142 "mapparser.y"
     {
 	                                 if((yyvsp[(1) - (3)].intval) == MS_TRUE) {
@@ -1709,8 +1692,6 @@ yyreduce:
     break;
 
   case 11:
-
-/* Line 1455 of yacc.c  */
 #line 151 "mapparser.y"
     {
 	                                 if((yyvsp[(1) - (3)].dblval) != 0)
@@ -1723,8 +1704,6 @@ yyreduce:
     break;
 
   case 12:
-
-/* Line 1455 of yacc.c  */
 #line 159 "mapparser.y"
     {
 	                                 if((yyvsp[(1) - (3)].dblval) != 0) {
@@ -1738,8 +1717,6 @@ yyreduce:
     break;
 
   case 13:
-
-/* Line 1455 of yacc.c  */
 #line 168 "mapparser.y"
     {
 	                                 if((yyvsp[(1) - (3)].dblval) != 0)
@@ -1752,8 +1729,6 @@ yyreduce:
     break;
 
   case 14:
-
-/* Line 1455 of yacc.c  */
 #line 176 "mapparser.y"
     {
 	                                 if((yyvsp[(1) - (3)].dblval) != 0) {
@@ -1767,22 +1742,16 @@ yyreduce:
     break;
 
   case 15:
-
-/* Line 1455 of yacc.c  */
 #line 185 "mapparser.y"
     { (yyval.intval) = !(yyvsp[(2) - (2)].intval); }
     break;
 
   case 16:
-
-/* Line 1455 of yacc.c  */
 #line 186 "mapparser.y"
     { (yyval.intval) = !(yyvsp[(2) - (2)].dblval); }
     break;
 
   case 17:
-
-/* Line 1455 of yacc.c  */
 #line 187 "mapparser.y"
     {
                                          ms_regex_t re;
@@ -1796,13 +1765,13 @@ yyreduce:
 			                   (yyval.intval) = MS_FALSE;
 
                                          ms_regfree(&re);
+                                         free((yyvsp[(1) - (3)].strval));
+                                         free((yyvsp[(3) - (3)].strval));
                                        }
     break;
 
   case 18:
-
-/* Line 1455 of yacc.c  */
-#line 200 "mapparser.y"
+#line 202 "mapparser.y"
     {
                                          ms_regex_t re;
 
@@ -1815,13 +1784,13 @@ yyreduce:
 			                   (yyval.intval) = MS_FALSE;
 
                                          ms_regfree(&re);
+                                         free((yyvsp[(1) - (3)].strval));
+                                         free((yyvsp[(3) - (3)].strval));
                                        }
     break;
 
   case 19:
-
-/* Line 1455 of yacc.c  */
-#line 213 "mapparser.y"
+#line 217 "mapparser.y"
     {
 	                                 if((yyvsp[(1) - (3)].dblval) == (yyvsp[(3) - (3)].dblval))
 	 		                   (yyval.intval) = MS_TRUE;
@@ -1831,9 +1800,7 @@ yyreduce:
     break;
 
   case 20:
-
-/* Line 1455 of yacc.c  */
-#line 219 "mapparser.y"
+#line 223 "mapparser.y"
     {
 	                                 if((yyvsp[(1) - (3)].dblval) != (yyvsp[(3) - (3)].dblval))
 			                   (yyval.intval) = MS_TRUE;
@@ -1843,9 +1810,7 @@ yyreduce:
     break;
 
   case 21:
-
-/* Line 1455 of yacc.c  */
-#line 225 "mapparser.y"
+#line 229 "mapparser.y"
     {	                                 
 	                                 if((yyvsp[(1) - (3)].dblval) > (yyvsp[(3) - (3)].dblval))
 			                   (yyval.intval) = MS_TRUE;
@@ -1855,9 +1820,7 @@ yyreduce:
     break;
 
   case 22:
-
-/* Line 1455 of yacc.c  */
-#line 231 "mapparser.y"
+#line 235 "mapparser.y"
     {
 	                                 if((yyvsp[(1) - (3)].dblval) < (yyvsp[(3) - (3)].dblval))
 			                   (yyval.intval) = MS_TRUE;
@@ -1867,9 +1830,7 @@ yyreduce:
     break;
 
   case 23:
-
-/* Line 1455 of yacc.c  */
-#line 237 "mapparser.y"
+#line 241 "mapparser.y"
     {	                                 
 	                                 if((yyvsp[(1) - (3)].dblval) >= (yyvsp[(3) - (3)].dblval))
 			                   (yyval.intval) = MS_TRUE;
@@ -1879,9 +1840,7 @@ yyreduce:
     break;
 
   case 24:
-
-/* Line 1455 of yacc.c  */
-#line 243 "mapparser.y"
+#line 247 "mapparser.y"
     {
 	                                 if((yyvsp[(1) - (3)].dblval) <= (yyvsp[(3) - (3)].dblval))
 			                   (yyval.intval) = MS_TRUE;
@@ -1891,16 +1850,12 @@ yyreduce:
     break;
 
   case 25:
-
-/* Line 1455 of yacc.c  */
-#line 249 "mapparser.y"
+#line 253 "mapparser.y"
     { (yyval.intval) = (yyvsp[(2) - (3)].intval); }
     break;
 
   case 26:
-
-/* Line 1455 of yacc.c  */
-#line 250 "mapparser.y"
+#line 254 "mapparser.y"
     {
                                          if(strcmp((yyvsp[(1) - (3)].strval), (yyvsp[(3) - (3)].strval)) == 0)
 					   (yyval.intval) = MS_TRUE;
@@ -1912,9 +1867,7 @@ yyreduce:
     break;
 
   case 27:
-
-/* Line 1455 of yacc.c  */
-#line 258 "mapparser.y"
+#line 262 "mapparser.y"
     {
                                          if(strcmp((yyvsp[(1) - (3)].strval), (yyvsp[(3) - (3)].strval)) != 0)
 					   (yyval.intval) = MS_TRUE;
@@ -1926,9 +1879,7 @@ yyreduce:
     break;
 
   case 28:
-
-/* Line 1455 of yacc.c  */
-#line 266 "mapparser.y"
+#line 270 "mapparser.y"
     {
                                          if(strcmp((yyvsp[(1) - (3)].strval), (yyvsp[(3) - (3)].strval)) > 0)
 					   (yyval.intval) = MS_TRUE;
@@ -1941,9 +1892,7 @@ yyreduce:
     break;
 
   case 29:
-
-/* Line 1455 of yacc.c  */
-#line 275 "mapparser.y"
+#line 279 "mapparser.y"
     {
                                          if(strcmp((yyvsp[(1) - (3)].strval), (yyvsp[(3) - (3)].strval)) < 0)
 					   (yyval.intval) = MS_TRUE;
@@ -1955,9 +1904,7 @@ yyreduce:
     break;
 
   case 30:
-
-/* Line 1455 of yacc.c  */
-#line 283 "mapparser.y"
+#line 287 "mapparser.y"
     {
                                          if(strcmp((yyvsp[(1) - (3)].strval), (yyvsp[(3) - (3)].strval)) >= 0)
 					   (yyval.intval) = MS_TRUE;
@@ -1969,9 +1916,7 @@ yyreduce:
     break;
 
   case 31:
-
-/* Line 1455 of yacc.c  */
-#line 291 "mapparser.y"
+#line 295 "mapparser.y"
     {
                                          if(strcmp((yyvsp[(1) - (3)].strval), (yyvsp[(3) - (3)].strval)) <= 0)
 					   (yyval.intval) = MS_TRUE;
@@ -1983,9 +1928,7 @@ yyreduce:
     break;
 
   case 32:
-
-/* Line 1455 of yacc.c  */
-#line 299 "mapparser.y"
+#line 303 "mapparser.y"
     {
                                      if(msTimeCompare(&((yyvsp[(1) - (3)].tmval)), &((yyvsp[(3) - (3)].tmval))) == 0)
 				       (yyval.intval) = MS_TRUE;
@@ -1995,9 +1938,7 @@ yyreduce:
     break;
 
   case 33:
-
-/* Line 1455 of yacc.c  */
-#line 305 "mapparser.y"
+#line 309 "mapparser.y"
     {
                                      if(msTimeCompare(&((yyvsp[(1) - (3)].tmval)), &((yyvsp[(3) - (3)].tmval))) != 0)
 				       (yyval.intval) = MS_TRUE;
@@ -2007,9 +1948,7 @@ yyreduce:
     break;
 
   case 34:
-
-/* Line 1455 of yacc.c  */
-#line 311 "mapparser.y"
+#line 315 "mapparser.y"
     {
                                      if(msTimeCompare(&((yyvsp[(1) - (3)].tmval)), &((yyvsp[(3) - (3)].tmval))) > 0)
 				       (yyval.intval) = MS_TRUE;
@@ -2019,9 +1958,7 @@ yyreduce:
     break;
 
   case 35:
-
-/* Line 1455 of yacc.c  */
-#line 317 "mapparser.y"
+#line 321 "mapparser.y"
     {
                                      if(msTimeCompare(&((yyvsp[(1) - (3)].tmval)), &((yyvsp[(3) - (3)].tmval))) < 0)
 				       (yyval.intval) = MS_TRUE;
@@ -2031,9 +1968,7 @@ yyreduce:
     break;
 
   case 36:
-
-/* Line 1455 of yacc.c  */
-#line 323 "mapparser.y"
+#line 327 "mapparser.y"
     {
                                      if(msTimeCompare(&((yyvsp[(1) - (3)].tmval)), &((yyvsp[(3) - (3)].tmval))) >= 0)
 				       (yyval.intval) = MS_TRUE;
@@ -2043,9 +1978,7 @@ yyreduce:
     break;
 
   case 37:
-
-/* Line 1455 of yacc.c  */
-#line 329 "mapparser.y"
+#line 333 "mapparser.y"
     {
                                      if(msTimeCompare(&((yyvsp[(1) - (3)].tmval)), &((yyvsp[(3) - (3)].tmval))) <= 0)
 				       (yyval.intval) = MS_TRUE;
@@ -2055,9 +1988,7 @@ yyreduce:
     break;
 
   case 38:
-
-/* Line 1455 of yacc.c  */
-#line 335 "mapparser.y"
+#line 339 "mapparser.y"
     {
 					 char *delim,*bufferp;
 
@@ -2082,9 +2013,7 @@ yyreduce:
     break;
 
   case 39:
-
-/* Line 1455 of yacc.c  */
-#line 356 "mapparser.y"
+#line 360 "mapparser.y"
     {
 					 char *delim,*bufferp;
 
@@ -2109,9 +2038,7 @@ yyreduce:
     break;
 
   case 40:
-
-/* Line 1455 of yacc.c  */
-#line 377 "mapparser.y"
+#line 381 "mapparser.y"
     {
 	                                 if((yyvsp[(1) - (3)].dblval) == (yyvsp[(3) - (3)].dblval))
 	 		                   (yyval.intval) = MS_TRUE;
@@ -2121,9 +2048,7 @@ yyreduce:
     break;
 
   case 41:
-
-/* Line 1455 of yacc.c  */
-#line 383 "mapparser.y"
+#line 387 "mapparser.y"
     {
                                          if(strcasecmp((yyvsp[(1) - (3)].strval), (yyvsp[(3) - (3)].strval)) == 0)
 					   (yyval.intval) = MS_TRUE;
@@ -2135,9 +2060,7 @@ yyreduce:
     break;
 
   case 42:
-
-/* Line 1455 of yacc.c  */
-#line 391 "mapparser.y"
+#line 395 "mapparser.y"
     {
                                      if(msTimeCompare(&((yyvsp[(1) - (3)].tmval)), &((yyvsp[(3) - (3)].tmval))) == 0)
 				       (yyval.intval) = MS_TRUE;
@@ -2147,9 +2070,7 @@ yyreduce:
     break;
 
   case 43:
-
-/* Line 1455 of yacc.c  */
-#line 398 "mapparser.y"
+#line 402 "mapparser.y"
     {
       int rval;
       rval = msGEOSEquals((yyvsp[(1) - (3)].shpval), (yyvsp[(3) - (3)].shpval));
@@ -2164,9 +2085,7 @@ yyreduce:
     break;
 
   case 44:
-
-/* Line 1455 of yacc.c  */
-#line 409 "mapparser.y"
+#line 413 "mapparser.y"
     {
       int rval;
       rval = msGEOSIntersects((yyvsp[(1) - (3)].shpval), (yyvsp[(3) - (3)].shpval));      
@@ -2181,9 +2100,7 @@ yyreduce:
     break;
 
   case 45:
-
-/* Line 1455 of yacc.c  */
-#line 420 "mapparser.y"
+#line 424 "mapparser.y"
     {
       int rval;
       rval = msGEOSDisjoint((yyvsp[(1) - (3)].shpval), (yyvsp[(3) - (3)].shpval));
@@ -2198,9 +2115,7 @@ yyreduce:
     break;
 
   case 46:
-
-/* Line 1455 of yacc.c  */
-#line 431 "mapparser.y"
+#line 435 "mapparser.y"
     {
       int rval;
       rval = msGEOSTouches((yyvsp[(1) - (3)].shpval), (yyvsp[(3) - (3)].shpval));
@@ -2215,9 +2130,7 @@ yyreduce:
     break;
 
   case 47:
-
-/* Line 1455 of yacc.c  */
-#line 442 "mapparser.y"
+#line 446 "mapparser.y"
     {
       int rval;
       rval = msGEOSOverlaps((yyvsp[(1) - (3)].shpval), (yyvsp[(3) - (3)].shpval));
@@ -2232,9 +2145,7 @@ yyreduce:
     break;
 
   case 48:
-
-/* Line 1455 of yacc.c  */
-#line 453 "mapparser.y"
+#line 457 "mapparser.y"
     {
       int rval;
       rval = msGEOSCrosses((yyvsp[(1) - (3)].shpval), (yyvsp[(3) - (3)].shpval));
@@ -2249,9 +2160,7 @@ yyreduce:
     break;
 
   case 49:
-
-/* Line 1455 of yacc.c  */
-#line 464 "mapparser.y"
+#line 468 "mapparser.y"
     {
       int rval;
       rval = msGEOSWithin((yyvsp[(1) - (3)].shpval), (yyvsp[(3) - (3)].shpval));
@@ -2266,9 +2175,7 @@ yyreduce:
     break;
 
   case 50:
-
-/* Line 1455 of yacc.c  */
-#line 475 "mapparser.y"
+#line 479 "mapparser.y"
     {
       int rval;
       rval = msGEOSContains((yyvsp[(1) - (3)].shpval), (yyvsp[(3) - (3)].shpval));
@@ -2283,9 +2190,7 @@ yyreduce:
     break;
 
   case 51:
-
-/* Line 1455 of yacc.c  */
-#line 486 "mapparser.y"
+#line 490 "mapparser.y"
     {
       double d;
       d = msGEOSDistance((yyvsp[(1) - (3)].shpval), (yyvsp[(3) - (3)].shpval));
@@ -2299,9 +2204,7 @@ yyreduce:
     break;
 
   case 52:
-
-/* Line 1455 of yacc.c  */
-#line 496 "mapparser.y"
+#line 500 "mapparser.y"
     {
       double d;
       d = msGEOSDistance((yyvsp[(1) - (3)].shpval), (yyvsp[(3) - (3)].shpval));
@@ -2315,44 +2218,32 @@ yyreduce:
     break;
 
   case 54:
-
-/* Line 1455 of yacc.c  */
-#line 509 "mapparser.y"
+#line 513 "mapparser.y"
     { (yyval.dblval) = (yyvsp[(2) - (3)].dblval); }
     break;
 
   case 55:
-
-/* Line 1455 of yacc.c  */
-#line 510 "mapparser.y"
+#line 514 "mapparser.y"
     { (yyval.dblval) = (yyvsp[(1) - (3)].dblval) + (yyvsp[(3) - (3)].dblval); }
     break;
 
   case 56:
-
-/* Line 1455 of yacc.c  */
-#line 511 "mapparser.y"
+#line 515 "mapparser.y"
     { (yyval.dblval) = (yyvsp[(1) - (3)].dblval) - (yyvsp[(3) - (3)].dblval); }
     break;
 
   case 57:
-
-/* Line 1455 of yacc.c  */
-#line 512 "mapparser.y"
+#line 516 "mapparser.y"
     { (yyval.dblval) = (yyvsp[(1) - (3)].dblval) * (yyvsp[(3) - (3)].dblval); }
     break;
 
   case 58:
-
-/* Line 1455 of yacc.c  */
-#line 513 "mapparser.y"
+#line 517 "mapparser.y"
     { (yyval.dblval) = (int)(yyvsp[(1) - (3)].dblval) % (int)(yyvsp[(3) - (3)].dblval); }
     break;
 
   case 59:
-
-/* Line 1455 of yacc.c  */
-#line 514 "mapparser.y"
+#line 518 "mapparser.y"
     {
       if((yyvsp[(3) - (3)].dblval) == 0.0) {
         yyerror(p, "Division by zero.");
@@ -2363,30 +2254,22 @@ yyreduce:
     break;
 
   case 60:
-
-/* Line 1455 of yacc.c  */
-#line 521 "mapparser.y"
+#line 525 "mapparser.y"
     { (yyval.dblval) = (yyvsp[(2) - (2)].dblval); }
     break;
 
   case 61:
-
-/* Line 1455 of yacc.c  */
-#line 522 "mapparser.y"
+#line 526 "mapparser.y"
     { (yyval.dblval) = pow((yyvsp[(1) - (3)].dblval), (yyvsp[(3) - (3)].dblval)); }
     break;
 
   case 62:
-
-/* Line 1455 of yacc.c  */
-#line 523 "mapparser.y"
+#line 527 "mapparser.y"
     { (yyval.dblval) = strlen((yyvsp[(3) - (4)].strval)); }
     break;
 
   case 63:
-
-/* Line 1455 of yacc.c  */
-#line 524 "mapparser.y"
+#line 528 "mapparser.y"
     {
       if((yyvsp[(3) - (4)].shpval)->type != MS_SHAPE_POLYGON) {
         yyerror(p, "Area can only be computed for polygon shapes.");
@@ -2398,23 +2281,17 @@ yyreduce:
     break;
 
   case 64:
-
-/* Line 1455 of yacc.c  */
-#line 532 "mapparser.y"
+#line 536 "mapparser.y"
     { (yyval.dblval) = (MS_NINT((yyvsp[(3) - (6)].dblval)/(yyvsp[(5) - (6)].dblval)))*(yyvsp[(5) - (6)].dblval); }
     break;
 
   case 66:
-
-/* Line 1455 of yacc.c  */
-#line 536 "mapparser.y"
+#line 540 "mapparser.y"
     { (yyval.shpval) = (yyvsp[(2) - (3)].shpval); }
     break;
 
   case 67:
-
-/* Line 1455 of yacc.c  */
-#line 537 "mapparser.y"
+#line 541 "mapparser.y"
     {
       shapeObj *s;
       s = msGEOSBuffer((yyvsp[(3) - (6)].shpval), (yyvsp[(5) - (6)].dblval));
@@ -2427,54 +2304,57 @@ yyreduce:
     }
     break;
 
-  case 69:
-
-/* Line 1455 of yacc.c  */
-#line 550 "mapparser.y"
-    { (yyval.strval) = (yyvsp[(2) - (3)].strval); }
+  case 68:
+#line 551 "mapparser.y"
+    {
+      shapeObj *s;
+      s = msGEOSDifference((yyvsp[(3) - (6)].shpval), (yyvsp[(5) - (6)].shpval));
+      if(!s) {
+        yyerror(p, "Executing difference failed.");
+        return(-1);
+      }
+      s->scratch = MS_TRUE;
+      (yyval.shpval) = s;
+    }
     break;
 
   case 70:
+#line 564 "mapparser.y"
+    { (yyval.strval) = (yyvsp[(2) - (3)].strval); }
+    break;
 
-/* Line 1455 of yacc.c  */
-#line 551 "mapparser.y"
+  case 71:
+#line 565 "mapparser.y"
     { 
       (yyval.strval) = (char *)malloc(strlen((yyvsp[(1) - (3)].strval)) + strlen((yyvsp[(3) - (3)].strval)) + 1);
       sprintf((yyval.strval), "%s%s", (yyvsp[(1) - (3)].strval), (yyvsp[(3) - (3)].strval)); free((yyvsp[(1) - (3)].strval)); free((yyvsp[(3) - (3)].strval)); 
     }
     break;
 
-  case 71:
-
-/* Line 1455 of yacc.c  */
-#line 555 "mapparser.y"
+  case 72:
+#line 569 "mapparser.y"
     {
       (yyval.strval) = (char *) malloc(strlen((yyvsp[(5) - (6)].strval)) + 64); /* Plenty big? Should use snprintf below... */
       sprintf((yyval.strval), (yyvsp[(5) - (6)].strval), (yyvsp[(3) - (6)].dblval));
     }
     break;
 
-  case 72:
-
-/* Line 1455 of yacc.c  */
-#line 559 "mapparser.y"
+  case 73:
+#line 573 "mapparser.y"
     {  
       (yyvsp[(3) - (4)].strval) = msCommifyString((yyvsp[(3) - (4)].strval)); 
       (yyval.strval) = (yyvsp[(3) - (4)].strval); 
     }
     break;
 
-  case 74:
-
-/* Line 1455 of yacc.c  */
-#line 566 "mapparser.y"
+  case 75:
+#line 580 "mapparser.y"
     { (yyval.tmval) = (yyvsp[(2) - (3)].tmval); }
     break;
 
 
-
-/* Line 1455 of yacc.c  */
-#line 2478 "mapparser.c"
+/* Line 1267 of yacc.c.  */
+#line 2358 "mapparser.c"
       default: break;
     }
   YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc);
@@ -2485,6 +2365,7 @@ yyreduce:
 
   *++yyvsp = yyval;
 
+
   /* Now `shift' the result of the reduction.  Determine what state
      that goes to, based on the state we popped back to and the rule
      number reduced by.  */
@@ -2549,7 +2430,7 @@ yyerrlab:
 
   if (yyerrstatus == 3)
     {
-      /* If just tried and failed to reuse lookahead token after an
+      /* If just tried and failed to reuse look-ahead token after an
 	 error, discard it.  */
 
       if (yychar <= YYEOF)
@@ -2566,7 +2447,7 @@ yyerrlab:
 	}
     }
 
-  /* Else will try to reuse lookahead token after shifting the error
+  /* Else will try to reuse look-ahead token after shifting the error
      token.  */
   goto yyerrlab1;
 
@@ -2623,6 +2504,9 @@ yyerrlab1:
       YY_STACK_PRINT (yyss, yyssp);
     }
 
+  if (yyn == YYFINAL)
+    YYACCEPT;
+
   *++yyvsp = yylval;
 
 
@@ -2647,7 +2531,7 @@ yyabortlab:
   yyresult = 1;
   goto yyreturn;
 
-#if !defined(yyoverflow) || YYERROR_VERBOSE
+#ifndef yyoverflow
 /*-------------------------------------------------.
 | yyexhaustedlab -- memory exhaustion comes here.  |
 `-------------------------------------------------*/
@@ -2658,7 +2542,7 @@ yyexhaustedlab:
 #endif
 
 yyreturn:
-  if (yychar != YYEMPTY)
+  if (yychar != YYEOF && yychar != YYEMPTY)
      yydestruct ("Cleanup: discarding lookahead",
 		 yytoken, &yylval, p);
   /* Do not reclaim the symbols of the rule which action triggered
@@ -2684,9 +2568,7 @@ yyreturn:
 }
 
 
-
-/* Line 1675 of yacc.c  */
-#line 569 "mapparser.y"
+#line 583 "mapparser.y"
 
 
 /*
@@ -2776,6 +2658,7 @@ int yylex(YYSTYPE *lvalp, parseObj *p)
   case MS_TOKEN_FUNCTION_ROUND: token = ROUND; break;
 
   case MS_TOKEN_FUNCTION_BUFFER: token = YYBUFFER; break;
+  case MS_TOKEN_FUNCTION_DIFFERENCE: token = DIFFERENCE; break;
 
   default:
     break;
diff --git a/mapparser.h b/mapparser.h
index 3bdd211..47506c1 100644
--- a/mapparser.h
+++ b/mapparser.h
@@ -1,23 +1,24 @@
-
-/* A Bison parser, made by GNU Bison 2.4.1.  */
+/* A Bison parser, made by GNU Bison 2.3.  */
 
 /* Skeleton interface for Bison's Yacc-like parsers in C
-   
-      Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005, 2006
+
+   Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005, 2006
    Free Software Foundation, Inc.
-   
-   This program is free software: you can redistribute it and/or modify
+
+   This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
-   the Free Software Foundation, either version 3 of the License, or
-   (at your option) any later version.
-   
+   the Free Software Foundation; either version 2, or (at your option)
+   any later version.
+
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
-   
+
    You should have received a copy of the GNU General Public License
-   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+   along with this program; if not, write to the Free Software
+   Foundation, Inc., 51 Franklin Street, Fifth Floor,
+   Boston, MA 02110-1301, USA.  */
 
 /* As a special exception, you may create a larger work that contains
    part or all of the Bison parser skeleton and distribute that work
@@ -28,11 +29,10 @@
    special exception, which will cause the skeleton and the resulting
    Bison output files to be licensed under the GNU General Public
    License without this special exception.
-   
+
    This special exception was added by the Free Software Foundation in
    version 2.2 of Bison.  */
 
-
 /* Tokens.  */
 #ifndef YYTOKENTYPE
 # define YYTOKENTYPE
@@ -70,8 +70,9 @@
      LENGTH = 286,
      AREA = 287,
      TOSTRING = 288,
-     YYBUFFER = 289,
-     NEG = 290
+     DIFFERENCE = 289,
+     YYBUFFER = 290,
+     NEG = 291
    };
 #endif
 /* Tokens.  */
@@ -106,35 +107,30 @@
 #define LENGTH 286
 #define AREA 287
 #define TOSTRING 288
-#define YYBUFFER 289
-#define NEG 290
+#define DIFFERENCE 289
+#define YYBUFFER 290
+#define NEG 291
 
 
 
 
 #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
 typedef union YYSTYPE
-{
-
-/* Line 1676 of yacc.c  */
 #line 30 "mapparser.y"
-
+{
   double dblval;
   int intval;  
   char *strval;  
   struct tm tmval;
   shapeObj *shpval;
-
-
-
-/* Line 1676 of yacc.c  */
-#line 132 "mapparser.h"
-} YYSTYPE;
-# define YYSTYPE_IS_TRIVIAL 1
+}
+/* Line 1529 of yacc.c.  */
+#line 129 "mapparser.h"
+	YYSTYPE;
 # define yystype YYSTYPE /* obsolescent; will be withdrawn */
 # define YYSTYPE_IS_DECLARED 1
+# define YYSTYPE_IS_TRIVIAL 1
 #endif
 
 
 
-
diff --git a/mapparser.y b/mapparser.y
index df598cc..5008fe3 100644
--- a/mapparser.y
+++ b/mapparser.y
@@ -46,7 +46,7 @@ int yyerror(parseObj *, const char *);
 %left INTERSECTS DISJOINT TOUCHES OVERLAPS CROSSES WITHIN CONTAINS BEYOND DWITHIN
 %left AREA LENGTH COMMIFY ROUND
 %left TOSTRING
-%left YYBUFFER
+%left YYBUFFER DIFFERENCE
 %left '+' '-'
 %left '*' '/' '%'
 %left NEG
@@ -196,6 +196,8 @@ logical_exp:
 			                   $$ = MS_FALSE;
 
                                          ms_regfree(&re);
+                                         free($1);
+                                         free($3);
                                        }
        | string_exp IRE string_exp     {
                                          ms_regex_t re;
@@ -209,6 +211,8 @@ logical_exp:
 			                   $$ = MS_FALSE;
 
                                          ms_regfree(&re);
+                                         free($1);
+                                         free($3);
                                        }
        | math_exp EQ math_exp          {
 	                                 if($1 == $3)
@@ -544,6 +548,16 @@ shape_exp: SHAPE
       s->scratch = MS_TRUE;
       $$ = s;
     }
+  | DIFFERENCE '(' shape_exp ',' shape_exp ')' {
+      shapeObj *s;
+      s = msGEOSDifference($3, $5);
+      if(!s) {
+        yyerror(p, "Executing difference failed.");
+        return(-1);
+      }
+      s->scratch = MS_TRUE;
+      $$ = s;
+    }
 ;
 
 string_exp: STRING
@@ -655,6 +669,7 @@ int yylex(YYSTYPE *lvalp, parseObj *p)
   case MS_TOKEN_FUNCTION_ROUND: token = ROUND; break;
 
   case MS_TOKEN_FUNCTION_BUFFER: token = YYBUFFER; break;
+  case MS_TOKEN_FUNCTION_DIFFERENCE: token = DIFFERENCE; break;
 
   default:
     break;
diff --git a/mappluginlayer.c b/mappluginlayer.c
index 2c0fe38..8b01508 100644
--- a/mappluginlayer.c
+++ b/mappluginlayer.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -30,17 +30,17 @@
 #include "mapserver.h"
 #include "mapthread.h"
 
-MS_CVSID("$Id$")
+
 
 typedef struct {
-    char *name;
-    layerVTableObj vtable;
+  char *name;
+  layerVTableObj vtable;
 } VTFactoryItemObj;
 
 typedef struct {
-    unsigned int size;
-    unsigned int first_free;
-    VTFactoryItemObj ** vtItems;
+  unsigned int size;
+  unsigned int first_free;
+  VTFactoryItemObj ** vtItems;
 } VTFactoryObj;
 
 static VTFactoryObj gVirtualTableFactory = {0, 0, NULL};
@@ -49,25 +49,25 @@ static VTFactoryObj gVirtualTableFactory = {0, 0, NULL};
 static VTFactoryItemObj *
 createVTFItem(const char *name)
 {
-    VTFactoryItemObj *pVTFI;
+  VTFactoryItemObj *pVTFI;
 
-    pVTFI = (VTFactoryItemObj *)malloc(sizeof(VTFactoryItemObj));
-    MS_CHECK_ALLOC(pVTFI, sizeof(VTFactoryItemObj), NULL);
+  pVTFI = (VTFactoryItemObj *)malloc(sizeof(VTFactoryItemObj));
+  MS_CHECK_ALLOC(pVTFI, sizeof(VTFactoryItemObj), NULL);
 
-    pVTFI->name = msStrdup(name);
-    memset(&pVTFI->vtable, 0, sizeof(layerVTableObj));
+  pVTFI->name = msStrdup(name);
+  memset(&pVTFI->vtable, 0, sizeof(layerVTableObj));
 
-    return pVTFI;
+  return pVTFI;
 }
 
 static void
 destroyVTFItem(VTFactoryItemObj **pVTFI)
 {
-    free((*pVTFI)->name);
-    (*pVTFI)->name = NULL;
-    memset(&(*pVTFI)->vtable, 0, sizeof(layerVTableObj));
-    free(*pVTFI);
-    *pVTFI = NULL;
+  free((*pVTFI)->name);
+  (*pVTFI)->name = NULL;
+  memset(&(*pVTFI)->vtable, 0, sizeof(layerVTableObj));
+  free(*pVTFI);
+  *pVTFI = NULL;
 }
 
 
@@ -75,68 +75,68 @@ static VTFactoryItemObj *
 lookupVTFItem(VTFactoryObj *VTFactory,
               const char *key)
 {
-    unsigned int i;
-    for (i=0; i < VTFactory->size && VTFactory->vtItems[i]; ++i) {
-        if (0 == strcasecmp(key, VTFactory->vtItems[i]->name)) {
-            return VTFactory->vtItems[i];
-        }
+  unsigned int i;
+  for (i=0; i < VTFactory->size && VTFactory->vtItems[i]; ++i) {
+    if (0 == strcasecmp(key, VTFactory->vtItems[i]->name)) {
+      return VTFactory->vtItems[i];
     }
-    return NULL;
+  }
+  return NULL;
 }
 
 static int
-insertNewVTFItem(VTFactoryObj *pVTFactory, 
+insertNewVTFItem(VTFactoryObj *pVTFactory,
                  VTFactoryItemObj *pVTFI)
 {
-    /* Ensure there is room for one more item in the array 
-     * (safe to use for initial alloc of the array as well)
-     */
-    if (pVTFactory->first_free == pVTFactory->size) {
-        int i;
-        VTFactoryItemObj **vtItemPtr;
-        vtItemPtr = (VTFactoryItemObj**)realloc(pVTFactory->vtItems,
-                                                (pVTFactory->size+MS_LAYER_ALLOCSIZE)*sizeof(VTFactoryItemObj*));
-        MS_CHECK_ALLOC(vtItemPtr, (pVTFactory->size+MS_LAYER_ALLOCSIZE)*sizeof(VTFactoryItemObj*), MS_FAILURE);
-
-
-        pVTFactory->size += MS_LAYER_ALLOCSIZE;
-        pVTFactory->vtItems = vtItemPtr;
-
-        for (i=pVTFactory->first_free; i<pVTFactory->size; i++)
-            pVTFactory->vtItems[i] = NULL;
-    }
+  /* Ensure there is room for one more item in the array
+   * (safe to use for initial alloc of the array as well)
+   */
+  if (pVTFactory->first_free == pVTFactory->size) {
+    int i;
+    VTFactoryItemObj **vtItemPtr;
+    vtItemPtr = (VTFactoryItemObj**)realloc(pVTFactory->vtItems,
+                                            (pVTFactory->size+MS_LAYER_ALLOCSIZE)*sizeof(VTFactoryItemObj*));
+    MS_CHECK_ALLOC(vtItemPtr, (pVTFactory->size+MS_LAYER_ALLOCSIZE)*sizeof(VTFactoryItemObj*), MS_FAILURE);
+
+
+    pVTFactory->size += MS_LAYER_ALLOCSIZE;
+    pVTFactory->vtItems = vtItemPtr;
 
-    /* Insert item */
-    pVTFactory->vtItems[pVTFactory->first_free] = pVTFI;
-    pVTFactory->first_free++;
+    for (i=pVTFactory->first_free; i<pVTFactory->size; i++)
+      pVTFactory->vtItems[i] = NULL;
+  }
 
-    return MS_SUCCESS;
+  /* Insert item */
+  pVTFactory->vtItems[pVTFactory->first_free] = pVTFI;
+  pVTFactory->first_free++;
+
+  return MS_SUCCESS;
 }
 
 static VTFactoryItemObj *
 loadCustomLayerDLL(layerObj *layer, const char *library_path)
 {
-    int (*pfnPluginInitVTable)(layerVTableObj *, layerObj *);
+  int (*pfnPluginInitVTable)(layerVTableObj *, layerObj *);
 
-    VTFactoryItemObj *pVTFI;
+  VTFactoryItemObj *pVTFI;
 
-    pfnPluginInitVTable = msGetSymbol(library_path, "PluginInitializeVirtualTable");
-    if ( ! pfnPluginInitVTable) {
-        msSetError(MS_MISCERR, "Failed to load dynamic Layer LIB: %s", "loadCustomLayerDLL", library_path);
-        return NULL;
-    }
+  pfnPluginInitVTable = msGetSymbol(library_path, "PluginInitializeVirtualTable");
+  if ( ! pfnPluginInitVTable) {
+    msSetError(MS_MISCERR, "Failed to load dynamic Layer LIB: %s", "loadCustomLayerDLL", library_path);
+    return NULL;
+  }
 
-    pVTFI = createVTFItem(library_path);
-    if ( ! pVTFI) {
-        return NULL;
-    }
-    
-    if (pfnPluginInitVTable(&pVTFI->vtable, layer)) {
-        destroyVTFItem(&pVTFI);
-        msSetError(MS_MISCERR, "Failed to initialize dynamic Layer: %s", "loadCustomLayerDLL", library_path);
-        return NULL;
-    }
-    return pVTFI;
+  pVTFI = createVTFItem(library_path);
+  if ( ! pVTFI) {
+    return NULL;
+  }
+
+  if (pfnPluginInitVTable(&pVTFI->vtable, layer)) {
+    destroyVTFItem(&pVTFI);
+    msSetError(MS_MISCERR, "Failed to initialize dynamic Layer: %s", "loadCustomLayerDLL", library_path);
+    return NULL;
+  }
+  return pVTFI;
 }
 
 /*
@@ -147,76 +147,76 @@ loadCustomLayerDLL(layerObj *layer, const char *library_path)
  *
  * If src contains NULL fields, those are NOT copied over.
  *
- * Because of that, it is possible for plugin layer to use default 
+ * Because of that, it is possible for plugin layer to use default
  * layer API default functions,  just leave those function pointers to NULL.
  */
 static void
-copyVirtualTable(layerVTableObj *dest, 
+copyVirtualTable(layerVTableObj *dest,
                  const layerVTableObj *src)
 {
-    dest->LayerInitItemInfo = src->LayerInitItemInfo ? src->LayerInitItemInfo : dest->LayerInitItemInfo;
-    dest->LayerFreeItemInfo = src->LayerFreeItemInfo ? src->LayerFreeItemInfo : dest->LayerFreeItemInfo;
-    dest->LayerOpen = src->LayerOpen ? src->LayerOpen : dest->LayerOpen;
-    dest->LayerIsOpen = src->LayerIsOpen ? src->LayerIsOpen : dest->LayerIsOpen;
-    dest->LayerWhichShapes = src->LayerWhichShapes ? src->LayerWhichShapes : dest->LayerWhichShapes;
-    dest->LayerNextShape = src->LayerNextShape ? src->LayerNextShape : dest->LayerNextShape;
-    dest->LayerGetShape = src->LayerGetShape ? src->LayerGetShape : dest->LayerGetShape;
-    // dest->LayerResultsGetShape = src->LayerResultsGetShape ? src->LayerResultsGetShape : dest->LayerResultsGetShape;
-    dest->LayerClose = src->LayerClose ? src->LayerClose : dest->LayerClose;
-    dest->LayerGetItems = src->LayerGetItems ? src->LayerGetItems : dest->LayerGetItems;
-    dest->LayerGetExtent = src->LayerGetExtent ? src->LayerGetExtent : dest->LayerGetExtent;
-    dest->LayerGetAutoStyle = src->LayerGetAutoStyle ? src->LayerGetAutoStyle : dest->LayerGetAutoStyle;
-    dest->LayerCloseConnection = src->LayerCloseConnection ? src->LayerCloseConnection : dest->LayerCloseConnection;
-    dest->LayerSetTimeFilter = src->LayerSetTimeFilter ? src->LayerSetTimeFilter : dest->LayerSetTimeFilter;
-    dest->LayerApplyFilterToLayer = src->LayerApplyFilterToLayer ? src->LayerApplyFilterToLayer : dest->LayerApplyFilterToLayer;
-    dest->LayerCreateItems = src->LayerCreateItems ? src->LayerCreateItems : dest->LayerCreateItems;
-    dest->LayerGetNumFeatures = src->LayerGetNumFeatures ? src->LayerGetNumFeatures : dest->LayerGetNumFeatures;
-    dest->LayerGetAutoProjection = src->LayerGetAutoProjection ? src->LayerGetAutoProjection: dest->LayerGetAutoProjection;
+  dest->LayerInitItemInfo = src->LayerInitItemInfo ? src->LayerInitItemInfo : dest->LayerInitItemInfo;
+  dest->LayerFreeItemInfo = src->LayerFreeItemInfo ? src->LayerFreeItemInfo : dest->LayerFreeItemInfo;
+  dest->LayerOpen = src->LayerOpen ? src->LayerOpen : dest->LayerOpen;
+  dest->LayerIsOpen = src->LayerIsOpen ? src->LayerIsOpen : dest->LayerIsOpen;
+  dest->LayerWhichShapes = src->LayerWhichShapes ? src->LayerWhichShapes : dest->LayerWhichShapes;
+  dest->LayerNextShape = src->LayerNextShape ? src->LayerNextShape : dest->LayerNextShape;
+  dest->LayerGetShape = src->LayerGetShape ? src->LayerGetShape : dest->LayerGetShape;
+  /* dest->LayerResultsGetShape = src->LayerResultsGetShape ? src->LayerResultsGetShape : dest->LayerResultsGetShape; */
+  dest->LayerClose = src->LayerClose ? src->LayerClose : dest->LayerClose;
+  dest->LayerGetItems = src->LayerGetItems ? src->LayerGetItems : dest->LayerGetItems;
+  dest->LayerGetExtent = src->LayerGetExtent ? src->LayerGetExtent : dest->LayerGetExtent;
+  dest->LayerGetAutoStyle = src->LayerGetAutoStyle ? src->LayerGetAutoStyle : dest->LayerGetAutoStyle;
+  dest->LayerCloseConnection = src->LayerCloseConnection ? src->LayerCloseConnection : dest->LayerCloseConnection;
+  dest->LayerSetTimeFilter = src->LayerSetTimeFilter ? src->LayerSetTimeFilter : dest->LayerSetTimeFilter;
+  dest->LayerApplyFilterToLayer = src->LayerApplyFilterToLayer ? src->LayerApplyFilterToLayer : dest->LayerApplyFilterToLayer;
+  dest->LayerCreateItems = src->LayerCreateItems ? src->LayerCreateItems : dest->LayerCreateItems;
+  dest->LayerGetNumFeatures = src->LayerGetNumFeatures ? src->LayerGetNumFeatures : dest->LayerGetNumFeatures;
+  dest->LayerGetAutoProjection = src->LayerGetAutoProjection ? src->LayerGetAutoProjection: dest->LayerGetAutoProjection;
 }
 
 int
 msPluginLayerInitializeVirtualTable(layerObj *layer)
 {
-    VTFactoryItemObj *pVTFI;
+  VTFactoryItemObj *pVTFI;
+
+  msAcquireLock(TLOCK_LAYER_VTABLE);
 
-    msAcquireLock(TLOCK_LAYER_VTABLE);
-    
-    pVTFI = lookupVTFItem(&gVirtualTableFactory, layer->plugin_library);
+  pVTFI = lookupVTFItem(&gVirtualTableFactory, layer->plugin_library);
+  if ( ! pVTFI) {
+    pVTFI = loadCustomLayerDLL(layer, layer->plugin_library);
     if ( ! pVTFI) {
-        pVTFI = loadCustomLayerDLL(layer, layer->plugin_library);
-        if ( ! pVTFI) {
-            msReleaseLock(TLOCK_LAYER_VTABLE);
-            return MS_FAILURE;            
-        }
-        if (insertNewVTFItem(&gVirtualTableFactory, pVTFI) != MS_SUCCESS) {
-            destroyVTFItem(&pVTFI);
-            msReleaseLock(TLOCK_LAYER_VTABLE);
-            return MS_FAILURE;
-        }
+      msReleaseLock(TLOCK_LAYER_VTABLE);
+      return MS_FAILURE;
     }
-    msReleaseLock(TLOCK_LAYER_VTABLE);
+    if (insertNewVTFItem(&gVirtualTableFactory, pVTFI) != MS_SUCCESS) {
+      destroyVTFItem(&pVTFI);
+      msReleaseLock(TLOCK_LAYER_VTABLE);
+      return MS_FAILURE;
+    }
+  }
+  msReleaseLock(TLOCK_LAYER_VTABLE);
 
-    copyVirtualTable(layer->vtable, &pVTFI->vtable);
-    return MS_SUCCESS;
+  copyVirtualTable(layer->vtable, &pVTFI->vtable);
+  return MS_SUCCESS;
 }
 
 /* msPluginFreeVirtualTableFactory()
-** Called by msCleanup() to free the virtual table factory 
+** Called by msCleanup() to free the virtual table factory
 */
 void
 msPluginFreeVirtualTableFactory()
 {
-    int i;
-    msAcquireLock(TLOCK_LAYER_VTABLE);
-
-    for (i=0; i<gVirtualTableFactory.size; i++) {
-        if (gVirtualTableFactory.vtItems[i])
-            destroyVTFItem(&(gVirtualTableFactory.vtItems[i]));
-    }
-    free(gVirtualTableFactory.vtItems);
-    gVirtualTableFactory.vtItems = NULL;
-    gVirtualTableFactory.size = 0;
-    gVirtualTableFactory.first_free = 0;
-
-    msReleaseLock(TLOCK_LAYER_VTABLE);
+  int i;
+  msAcquireLock(TLOCK_LAYER_VTABLE);
+
+  for (i=0; i<gVirtualTableFactory.size; i++) {
+    if (gVirtualTableFactory.vtItems[i])
+      destroyVTFItem(&(gVirtualTableFactory.vtItems[i]));
+  }
+  free(gVirtualTableFactory.vtItems);
+  gVirtualTableFactory.vtItems = NULL;
+  gVirtualTableFactory.size = 0;
+  gVirtualTableFactory.first_free = 0;
+
+  msReleaseLock(TLOCK_LAYER_VTABLE);
 }
diff --git a/mappool.c b/mappool.c
index aca0686..cfb7912 100644
--- a/mappool.c
+++ b/mappool.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -27,24 +27,24 @@
  * DEALINGS IN THE SOFTWARE.
  ******************************************************************************
 
-             New MapServer Connection Pooling 
+             New MapServer Connection Pooling
              ================================
 
 This attempts to describe how the new connection pooling support (introduced
 Sept/2004) works and what the maintainer of a connection type needs to do
-to take advantage of it. 
+to take advantage of it.
 
 First, the new connection pooling support makes the assumption that
 a connection can be abstracted as a void pointer.  Further it assumes that
 the connection identify is unique defined by the connection string and
 the connection type on layers.  So if two layers have the same connection
-type and connection string that they can share a connection handle. 
+type and connection string that they can share a connection handle.
 
 The old connection sharing was based on searching previous layers in the
 same map for a layer to copy an existing connection from.  That was ok for
 sharing connection between layers in the same map, but didn't address the
 need to share connections over a longer term as is the case in a FastCGI
-situation where the cgi is long running and handles many CGI requests.  
+situation where the cgi is long running and handles many CGI requests.
 
 The mapool.c code essentially maintains a cache of open connections with the
 following information for each:
@@ -52,7 +52,7 @@ following information for each:
   - connection handle
   - reference count
   - life span indicator
-  - callback function to close the connection. 
+  - callback function to close the connection.
 
 The life span indicator is controlled by the CLOSE_CONNECTION PROCESSING
 option on the layer(s).  If this is set to NORMAL (or not set at all) the
@@ -65,39 +65,39 @@ till the application closes (msCleanup() will ensure the connection is closed
 on exit if called).  This case is called MS_LIFE_FOREVER.
 The CLOSE_CONNECTION=ALWAYS setting provides to suppress the connection pooling
 for a particular layer. In this case the MS_LIFE_SINGLE setting is used, which
-ensures that a new connection is created for each request and it is always 
+ensures that a new connection is created for each request and it is always
 closed when the connection is released. This kind of connection cannot be reused.
 
 The callback is a function provided with the connection handle when it is
 registered.  It takes a single "void *" argument which is the connection
-handle. 
+handle.
 
 Updating a Driver
 -----------------
 
 The following are the steps to ensure a particular format/database supports
-connection pooling (ie. mapsde.c, mappostgis.c, maporacle.c, mapogr.cpp, etc)  
-We will use POSTGIS names for convenience. 
+connection pooling (ie. mapsde.c, mappostgis.c, maporacle.c, mapogr.cpp, etc)
+We will use POSTGIS names for convenience.
 
 1) in msPOSTGISLayerOpen() call msConnPoolRequest(layer) in order to get
-   a database connection. 
+   a database connection.
 
         layerinfo->conn = (PGconn *) msConnPoolRequest( layer );
 
-2) In msPOSTGISLayerOpen(): if msConnPoolRequest() returned NULL then 
+2) In msPOSTGISLayerOpen(): if msConnPoolRequest() returned NULL then
    manually open a connection to the database (ie. PQconnectcb()) and then
    register this handle with the pool API by calling msmsConnPoolRegister().
 
-	    layerinfo->conn = PQconnectdb( layer->connection );
+      layerinfo->conn = PQconnectdb( layer->connection );
 
             if (PQstatus(layerinfo->conn) == CONNECTION_BAD)
                <report error>
             else
-                msConnPoolRegister( layer, layerinfo->conn, 
+                msConnPoolRegister( layer, layerinfo->conn,
                                     msPOSTGISCloseConnection );
 
-3) Implement a callback function (msPOSTGISCloseConnection) that the 
-   connection pooling API can call when it wants to close the connection. 
+3) Implement a callback function (msPOSTGISCloseConnection) that the
+   connection pooling API can call when it wants to close the connection.
 
    static void msPOSTGISCloseConnection( void *conn_handle )
 
@@ -105,13 +105,13 @@ We will use POSTGIS names for convenience.
        PQfinish( (PGconn*) conn_handle );
    }
 
-4) In msPOSTGISLayerClose() release the connection handle instead of 
-   directly closing it. 
+4) In msPOSTGISLayerClose() release the connection handle instead of
+   directly closing it.
 
             msConnPoolRelease( layer, layerinfo->conn );
             layerinfo->conn = NULL;
 
-5) If there was any use of msCheckConnection() or the "sameconnection" 
+5) If there was any use of msCheckConnection() or the "sameconnection"
    member of the layerObj, then old style connection pooling is already
    present.  Remove it.
 
@@ -120,23 +120,23 @@ Thats it!
 Other Notes
 -----------
 
-o The connection pooling API will report details about connection 
+o The connection pooling API will report details about connection
   registrations, requests, releases and closes if the layer debug flag is
-  on for the layers in question. 
+  on for the layers in question.
 
 o The connection pooling API will let a connection be used/referenced multiple
   times from a single thread, but will not allow a connection to be shared
   between different threads concurrently.  But if a connection is released
-  by one thread, it is available for use by another thread. 
+  by one thread, it is available for use by another thread.
 
  ****************************************************************************/
 
 #include "mapserver.h"
 #include "mapthread.h"
 
-MS_CVSID("$Id$")
 
-/* defines for lifetime.  
+
+/* defines for lifetime.
    A positive number is a time-from-last use in seconds */
 
 #define MS_LIFE_FOREVER       -1
@@ -144,19 +144,19 @@ MS_CVSID("$Id$")
 #define MS_LIFE_SINGLE        -3
 
 typedef struct {
-    enum MS_CONNECTION_TYPE connectiontype;
-    char *connection;
+  enum MS_CONNECTION_TYPE connectiontype;
+  char *connection;
+
+  int   lifespan;
+  int   ref_count;
+  int   thread_id;
+  int   debug;
 
-    int   lifespan;
-    int   ref_count;
-    int   thread_id;
-    int   debug;
+  time_t last_used;
 
-    time_t last_used;
-    
-    void  *conn_handle;
+  void  *conn_handle;
 
-    void  (*close)( void * );
+  void  (*close)( void * );
 } connectionObj;
 
 /*
@@ -173,106 +173,99 @@ static connectionObj *connections = NULL;
 /*      Register a new connection with the connection pool tracker.     */
 /************************************************************************/
 
-void msConnPoolRegister( layerObj *layer, 
-                         void *conn_handle, 
+void msConnPoolRegister( layerObj *layer,
+                         void *conn_handle,
                          void (*close_func)( void * ) )
 
 {
-    const char *close_connection = NULL;
-    connectionObj *conn = NULL;
-
-    if( layer->debug )
-        msDebug( "msConnPoolRegister(%s,%s,%p)\n", 
-                 layer->name, layer->connection, conn_handle );
-
-/* -------------------------------------------------------------------- */
-/*      We can't meaningful keep a connection with no connection or     */
-/*      connection type string on the layer.                            */
-/* -------------------------------------------------------------------- */
-    if( layer->connection == NULL )
-    {
-        if( layer->tileindex != NULL
-            && layer->connectiontype == MS_OGR )
-        {
-            /* this is ok, no need to make a fuss */
-        }
-        else
-        {
-            msDebug( "%s: Missing CONNECTION on layer %s.\n",
-                     "msConnPoolRegister()", 
-                     layer->name );
-            
-            msSetError( MS_MISCERR, 
-                        "Missing CONNECTION on layer %s.",
-                        "msConnPoolRegister()", 
-                        layer->name );
-        }
-        return;
+  const char *close_connection = NULL;
+  connectionObj *conn = NULL;
+
+  if( layer->debug )
+    msDebug( "msConnPoolRegister(%s,%s,%p)\n",
+             layer->name, layer->connection, conn_handle );
+
+  /* -------------------------------------------------------------------- */
+  /*      We can't meaningful keep a connection with no connection or     */
+  /*      connection type string on the layer.                            */
+  /* -------------------------------------------------------------------- */
+  if( layer->connection == NULL ) {
+    if( layer->tileindex != NULL
+        && layer->connectiontype == MS_OGR ) {
+      /* this is ok, no need to make a fuss */
+    } else {
+      msDebug( "%s: Missing CONNECTION on layer %s.\n",
+               "msConnPoolRegister()",
+               layer->name );
+
+      msSetError( MS_MISCERR,
+                  "Missing CONNECTION on layer %s.",
+                  "msConnPoolRegister()",
+                  layer->name );
     }
-
-/* -------------------------------------------------------------------- */
-/*      Grow the array of connection information objects if needed.     */
-/* -------------------------------------------------------------------- */
-    msAcquireLock( TLOCK_POOL );
-
-    if( connectionCount == connectionMax )
-    {
-        connectionMax += 10;
-        connections = (connectionObj *) 
-            realloc(connections,
-                    sizeof(connectionObj) * connectionMax );
-        if( connections == NULL )
-        {
-            msSetError(MS_MEMERR, NULL, "msConnPoolRegister()");
-            msReleaseLock( TLOCK_POOL );
-            return;
-        }
+    return;
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Grow the array of connection information objects if needed.     */
+  /* -------------------------------------------------------------------- */
+  msAcquireLock( TLOCK_POOL );
+
+  if( connectionCount == connectionMax ) {
+    connectionMax += 10;
+    connections = (connectionObj *)
+                  realloc(connections,
+                          sizeof(connectionObj) * connectionMax );
+    if( connections == NULL ) {
+      msSetError(MS_MEMERR, NULL, "msConnPoolRegister()");
+      msReleaseLock( TLOCK_POOL );
+      return;
     }
-
-/* -------------------------------------------------------------------- */
-/*      Set the new connection information.                             */
-/* -------------------------------------------------------------------- */
-    conn = connections + connectionCount;
-
-    connectionCount++;
-
-    conn->connectiontype = layer->connectiontype;
-    conn->connection = msStrdup( layer->connection );
-    conn->close = close_func;
-    conn->ref_count = 1;
-    conn->thread_id = msGetThreadId();
-    conn->last_used = time(NULL);
-    conn->conn_handle = conn_handle;
-    conn->debug = layer->debug;
-
-/* -------------------------------------------------------------------- */
-/*      Categorize the connection handling information.                 */
-/* -------------------------------------------------------------------- */
-    close_connection = 
-        msLayerGetProcessingKey( layer, "CLOSE_CONNECTION" );
-
-    if( close_connection == NULL )
-        close_connection = "NORMAL";
-
-    if( strcasecmp(close_connection,"NORMAL") == 0 )
-        conn->lifespan = MS_LIFE_ZEROREF;
-    else if( strcasecmp(close_connection,"DEFER") == 0 )
-        conn->lifespan = MS_LIFE_FOREVER;
-    else if( strcasecmp(close_connection,"ALWAYS") == 0 )
-        conn->lifespan = MS_LIFE_SINGLE;
-    else
-    {
-        msDebug("msConnPoolRegister(): "
-                "Unrecognised CLOSE_CONNECTION value '%s'\n",
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Set the new connection information.                             */
+  /* -------------------------------------------------------------------- */
+  conn = connections + connectionCount;
+
+  connectionCount++;
+
+  conn->connectiontype = layer->connectiontype;
+  conn->connection = msStrdup( layer->connection );
+  conn->close = close_func;
+  conn->ref_count = 1;
+  conn->thread_id = msGetThreadId();
+  conn->last_used = time(NULL);
+  conn->conn_handle = conn_handle;
+  conn->debug = layer->debug;
+
+  /* -------------------------------------------------------------------- */
+  /*      Categorize the connection handling information.                 */
+  /* -------------------------------------------------------------------- */
+  close_connection =
+    msLayerGetProcessingKey( layer, "CLOSE_CONNECTION" );
+
+  if( close_connection == NULL )
+    close_connection = "NORMAL";
+
+  if( strcasecmp(close_connection,"NORMAL") == 0 )
+    conn->lifespan = MS_LIFE_ZEROREF;
+  else if( strcasecmp(close_connection,"DEFER") == 0 )
+    conn->lifespan = MS_LIFE_FOREVER;
+  else if( strcasecmp(close_connection,"ALWAYS") == 0 )
+    conn->lifespan = MS_LIFE_SINGLE;
+  else {
+    msDebug("msConnPoolRegister(): "
+            "Unrecognised CLOSE_CONNECTION value '%s'\n",
+            close_connection );
+
+    msSetError( MS_MISCERR, "Unrecognised CLOSE_CONNECTION value '%s'",
+                "msConnPoolRegister()",
                 close_connection );
+    conn->lifespan = MS_LIFE_ZEROREF;
+  }
 
-        msSetError( MS_MISCERR, "Unrecognised CLOSE_CONNECTION value '%s'",
-                    "msConnPoolRegister()", 
-                    close_connection );
-        conn->lifespan = MS_LIFE_ZEROREF;
-    }
-
-    msReleaseLock( TLOCK_POOL );
+  msReleaseLock( TLOCK_POOL );
 }
 
 /************************************************************************/
@@ -286,47 +279,43 @@ void msConnPoolRegister( layerObj *layer,
 static void msConnPoolClose( int conn_index )
 
 {
-    connectionObj *conn = connections + conn_index;
-
-    if( conn->ref_count > 0 )
-    {
-        if( conn->debug )
-            msDebug( "msConnPoolClose(): "
-                 "Closing connection %s even though ref_count=%d.\n", 
-                 conn->connection, conn->ref_count );
-
-        msSetError( MS_MISCERR, 
-                    "Closing connection %s even though ref_count=%d.", 
-                    "msConnPoolClose()",
-                    conn->connection, 
-                    conn->ref_count );
-    }
+  connectionObj *conn = connections + conn_index;
 
+  if( conn->ref_count > 0 ) {
     if( conn->debug )
-        msDebug( "msConnPoolClose(%s,%p)\n", 
-                 conn->connection, conn->conn_handle );
-
-    if( conn->close != NULL )
-        conn->close( conn->conn_handle );
-
-    /* free malloced() stuff in this connection */
-    free( conn->connection );
-
-    connectionCount--;
-    if( connectionCount == 0 )
-    {
-        /* if there are no connections left we will "cleanup".  */
-        connectionMax = 0;
-        free( connections );
-        connections = NULL;
-    }
-    else
-    {
-        /* move the last connection in place of our now closed one */
-        memcpy( connections + conn_index, 
-                connections + connectionCount, 
-                sizeof(connectionObj) );
-    }
+      msDebug( "msConnPoolClose(): "
+               "Closing connection %s even though ref_count=%d.\n",
+               conn->connection, conn->ref_count );
+
+    msSetError( MS_MISCERR,
+                "Closing connection %s even though ref_count=%d.",
+                "msConnPoolClose()",
+                conn->connection,
+                conn->ref_count );
+  }
+
+  if( conn->debug )
+    msDebug( "msConnPoolClose(%s,%p)\n",
+             conn->connection, conn->conn_handle );
+
+  if( conn->close != NULL )
+    conn->close( conn->conn_handle );
+
+  /* free malloced() stuff in this connection */
+  free( conn->connection );
+
+  connectionCount--;
+  if( connectionCount == 0 ) {
+    /* if there are no connections left we will "cleanup".  */
+    connectionMax = 0;
+    free( connections );
+    connections = NULL;
+  } else {
+    /* move the last connection in place of our now closed one */
+    memcpy( connections + conn_index,
+            connections + connectionCount,
+            sizeof(connectionObj) );
+  }
 }
 
 /************************************************************************/
@@ -341,50 +330,47 @@ static void msConnPoolClose( int conn_index )
 void *msConnPoolRequest( layerObj *layer )
 
 {
-    int  i;
-    const char* close_connection;
-
-    if( layer->connection == NULL )
-        return NULL;
-
-    /* check if we must always create a new connection */
-    close_connection = msLayerGetProcessingKey( layer, "CLOSE_CONNECTION" );
-    if( close_connection && strcasecmp(close_connection,"ALWAYS") == 0 )
-        return NULL;
-
-    msAcquireLock( TLOCK_POOL );
-    for( i = 0; i < connectionCount; i++ )
-    {
-        connectionObj *conn = connections + i;
-
-        if( layer->connectiontype == conn->connectiontype
-            && strcasecmp( layer->connection, conn->connection ) == 0 
-            && (conn->ref_count == 0 || conn->thread_id == msGetThreadId())
-            && conn->lifespan != MS_LIFE_SINGLE)
-        {
-            void *conn_handle = NULL;
-
-            conn->ref_count++;
-            conn->thread_id = msGetThreadId();
-            conn->last_used = time(NULL);
-
-            if( layer->debug )
-            {
-                msDebug( "msConnPoolRequest(%s,%s) -> got %p\n",
-                         layer->name, layer->connection, conn->conn_handle );
-                conn->debug = layer->debug;
-            }
-
-            conn_handle = conn->conn_handle;
-
-            msReleaseLock( TLOCK_POOL );
-            return conn_handle;
-        }
-    }
+  int  i;
+  const char* close_connection;
 
-    msReleaseLock( TLOCK_POOL );
+  if( layer->connection == NULL )
+    return NULL;
 
+  /* check if we must always create a new connection */
+  close_connection = msLayerGetProcessingKey( layer, "CLOSE_CONNECTION" );
+  if( close_connection && strcasecmp(close_connection,"ALWAYS") == 0 )
     return NULL;
+
+  msAcquireLock( TLOCK_POOL );
+  for( i = 0; i < connectionCount; i++ ) {
+    connectionObj *conn = connections + i;
+
+    if( layer->connectiontype == conn->connectiontype
+        && strcasecmp( layer->connection, conn->connection ) == 0
+        && (conn->ref_count == 0 || conn->thread_id == msGetThreadId())
+        && conn->lifespan != MS_LIFE_SINGLE) {
+      void *conn_handle = NULL;
+
+      conn->ref_count++;
+      conn->thread_id = msGetThreadId();
+      conn->last_used = time(NULL);
+
+      if( layer->debug ) {
+        msDebug( "msConnPoolRequest(%s,%s) -> got %p\n",
+                 layer->name, layer->connection, conn->conn_handle );
+        conn->debug = layer->debug;
+      }
+
+      conn_handle = conn->conn_handle;
+
+      msReleaseLock( TLOCK_POOL );
+      return conn_handle;
+    }
+  }
+
+  msReleaseLock( TLOCK_POOL );
+
+  return NULL;
 }
 
 /************************************************************************/
@@ -399,48 +385,46 @@ void *msConnPoolRequest( layerObj *layer )
 void msConnPoolRelease( layerObj *layer, void *conn_handle )
 
 {
-    int  i;
+  int  i;
 
-    if( layer->debug )
-        msDebug( "msConnPoolRelease(%s,%s,%p)\n",
-                 layer->name, layer->connection, conn_handle );
+  if( layer->debug )
+    msDebug( "msConnPoolRelease(%s,%s,%p)\n",
+             layer->name, layer->connection, conn_handle );
 
-    if( layer->connection == NULL )
-        return;
+  if( layer->connection == NULL )
+    return;
 
-    msAcquireLock( TLOCK_POOL );
-    for( i = 0; i < connectionCount; i++ )
-    {
-        connectionObj *conn = connections + i;
+  msAcquireLock( TLOCK_POOL );
+  for( i = 0; i < connectionCount; i++ ) {
+    connectionObj *conn = connections + i;
 
-        if( layer->connectiontype == conn->connectiontype
-            && strcasecmp( layer->connection, conn->connection ) == 0 
-            && conn->conn_handle == conn_handle )
-        {
-            conn->ref_count--;
-            conn->last_used = time(NULL);
+    if( layer->connectiontype == conn->connectiontype
+        && strcasecmp( layer->connection, conn->connection ) == 0
+        && conn->conn_handle == conn_handle ) {
+      conn->ref_count--;
+      conn->last_used = time(NULL);
 
-            if( conn->ref_count == 0 )
-                conn->thread_id = 0;
+      if( conn->ref_count == 0 )
+        conn->thread_id = 0;
 
-            if( conn->ref_count == 0 && (conn->lifespan == MS_LIFE_ZEROREF || conn->lifespan == MS_LIFE_SINGLE) )
-                msConnPoolClose( i );
+      if( conn->ref_count == 0 && (conn->lifespan == MS_LIFE_ZEROREF || conn->lifespan == MS_LIFE_SINGLE) )
+        msConnPoolClose( i );
 
-            msReleaseLock( TLOCK_POOL );
-            return;
-        }
+      msReleaseLock( TLOCK_POOL );
+      return;
     }
+  }
 
-    msReleaseLock( TLOCK_POOL );
+  msReleaseLock( TLOCK_POOL );
 
-    msDebug( "%s: Unable to find handle for layer '%s'.\n",
-             "msConnPoolRelease()",
-             layer->name );
+  msDebug( "%s: Unable to find handle for layer '%s'.\n",
+           "msConnPoolRelease()",
+           layer->name );
 
-    msSetError( MS_MISCERR, 
-                "Unable to find handle for layer '%s'.",
-                "msConnPoolRelease()",
-                layer->name );
+  msSetError( MS_MISCERR,
+              "Unable to find handle for layer '%s'.",
+              "msConnPoolRelease()",
+              layer->name );
 }
 
 /************************************************************************/
@@ -452,24 +436,22 @@ void msConnPoolRelease( layerObj *layer, void *conn_handle )
 void msConnPoolCloseUnreferenced()
 
 {
-    int  i;
-
-    /* this really needs to be commented out before commiting.  */
-    /* msDebug( "msConnPoolCloseUnreferenced()\n" ); */
-
-    msAcquireLock( TLOCK_POOL );
-    for( i = connectionCount - 1; i >= 0; i-- )
-    {
-        connectionObj *conn = connections + i;
-
-        if( conn->ref_count == 0 )
-        {
-            /* for now we don't assume the locks are re-entrant, so release */
-            /* it so msConnPoolClose() can get it.  */
-            msConnPoolClose( i );
-        }
+  int  i;
+
+  /* this really needs to be commented out before commiting.  */
+  /* msDebug( "msConnPoolCloseUnreferenced()\n" ); */
+
+  msAcquireLock( TLOCK_POOL );
+  for( i = connectionCount - 1; i >= 0; i-- ) {
+    connectionObj *conn = connections + i;
+
+    if( conn->ref_count == 0 ) {
+      /* for now we don't assume the locks are re-entrant, so release */
+      /* it so msConnPoolClose() can get it.  */
+      msConnPoolClose( i );
     }
-    msReleaseLock( TLOCK_POOL );
+  }
+  msReleaseLock( TLOCK_POOL );
 }
 
 /************************************************************************/
@@ -482,11 +464,11 @@ void msConnPoolCloseUnreferenced()
 void msConnPoolFinalCleanup()
 
 {
-    /* this really needs to be commented out before commiting.  */
-    /* msDebug( "msConnPoolFinalCleanup()\n" ); */
+  /* this really needs to be commented out before commiting.  */
+  /* msDebug( "msConnPoolFinalCleanup()\n" ); */
 
-    msAcquireLock( TLOCK_POOL );
-    while( connectionCount > 0 )
-        msConnPoolClose( 0 );
-    msReleaseLock( TLOCK_POOL );
+  msAcquireLock( TLOCK_POOL );
+  while( connectionCount > 0 )
+    msConnPoolClose( 0 );
+  msReleaseLock( TLOCK_POOL );
 }
diff --git a/mappostgis.c b/mappostgis.c
index 3d50563..1f4c64e 100644
--- a/mappostgis.c
+++ b/mappostgis.c
@@ -34,27 +34,23 @@
 **
 ** Build SQL from DATA statement and LAYER state. SQL is always of the form:
 **
-**    SELECT [this, that, other], geometry, uid 
-**      FROM [table|(subquery) as sub] 
+**    SELECT [this, that, other], geometry, uid
+**      FROM [table|(subquery) as sub]
 **      WHERE [box] AND [filter]
-** 
-** So the geometry always resides at layer->numitems and the uid always 
+**
+** So the geometry always resides at layer->numitems and the uid always
 ** resides at layer->numitems + 1
 **
-** Geometry is requested as Base64 encoded WKB. The endian is always requested
+** Geometry is requested as Hex encoded WKB. The endian is always requested
 ** as the client endianness.
 **
-** msPostGISLayerWhichShapes creates SQL based on DATA and LAYER state, 
+** msPostGISLayerWhichShapes creates SQL based on DATA and LAYER state,
 ** executes it, and places the un-read PGresult handle in the layerinfo->pgresult,
 ** setting the layerinfo->rownum to 0.
 **
-** msPostGISNextShape reads a row, increments layerinfo->rownum, and returns 
+** msPostGISNextShape reads a row, increments layerinfo->rownum, and returns
 ** MS_SUCCESS, until rownum reaches ntuples, and it returns MS_DONE instead.
 **
-** Note: The WKB handling functions all assume 2D inputs, and the SQL currently
-** generated by MapServer forces the WKB to be 2D. Upgrading to multi-dimensions
-** will require moving to EWKB as the transfer, and updating the WKB handlers as
-** well.
 */
 
 /* GNU needs this for strcasestr */
@@ -69,10 +65,6 @@
 #include "maptime.h"
 #include "mappostgis.h"
 
-#ifndef FLT_MAX
-#define FLT_MAX 25000000.0
-#endif
-
 #define FP_EPSILON 1e-12
 #define FP_EQ(a, b) (fabs((a)-(b)) < FP_EPSILON)
 #define FP_LEFT -1
@@ -81,10 +73,10 @@
 
 #define SEGMENT_ANGLE 10.0
 #define SEGMENT_MINPOINTS 10
- 
+
 #ifdef USE_POSTGIS
-  
-MS_CVSID("$Id$")
+
+
 
 /*
 ** msPostGISCloseConnection()
@@ -92,43 +84,47 @@ MS_CVSID("$Id$")
 ** Handler registered witih msConnPoolRegister so that Mapserver
 ** can clean up open connections during a shutdown.
 */
-void msPostGISCloseConnection(void *pgconn) {
-    PQfinish((PGconn*)pgconn);
+void msPostGISCloseConnection(void *pgconn)
+{
+  PQfinish((PGconn*)pgconn);
 }
 
 /*
 ** msPostGISCreateLayerInfo()
 */
-msPostGISLayerInfo *msPostGISCreateLayerInfo(void) {
-    msPostGISLayerInfo *layerinfo = msSmallMalloc(sizeof(msPostGISLayerInfo));
-    layerinfo->sql = NULL;
-    layerinfo->srid = NULL;
-    layerinfo->uid = NULL;
-    layerinfo->pgconn = NULL;
-    layerinfo->pgresult = NULL;
-    layerinfo->geomcolumn = NULL;
-    layerinfo->fromsource = NULL;
-    layerinfo->endian = 0;
-    layerinfo->rownum = 0;
-    layerinfo->version = 0;
-    return layerinfo;
+msPostGISLayerInfo *msPostGISCreateLayerInfo(void)
+{
+  msPostGISLayerInfo *layerinfo = msSmallMalloc(sizeof(msPostGISLayerInfo));
+  layerinfo->sql = NULL;
+  layerinfo->srid = NULL;
+  layerinfo->uid = NULL;
+  layerinfo->pgconn = NULL;
+  layerinfo->pgresult = NULL;
+  layerinfo->geomcolumn = NULL;
+  layerinfo->fromsource = NULL;
+  layerinfo->endian = 0;
+  layerinfo->rownum = 0;
+  layerinfo->version = 0;
+  layerinfo->paging = MS_TRUE;
+  return layerinfo;
 }
 
 /*
 ** msPostGISFreeLayerInfo()
 */
-void msPostGISFreeLayerInfo(layerObj *layer) {
-    msPostGISLayerInfo *layerinfo = NULL;
-    layerinfo = (msPostGISLayerInfo*)layer->layerinfo;
-    if ( layerinfo->sql ) free(layerinfo->sql);
-    if ( layerinfo->uid ) free(layerinfo->uid);
-    if ( layerinfo->srid ) free(layerinfo->srid);
-    if ( layerinfo->geomcolumn ) free(layerinfo->geomcolumn);
-    if ( layerinfo->fromsource ) free(layerinfo->fromsource);
-    if ( layerinfo->pgresult ) PQclear(layerinfo->pgresult);
-    if ( layerinfo->pgconn ) msConnPoolRelease(layer, layerinfo->pgconn);
-    free(layerinfo);
-    layer->layerinfo = NULL;
+void msPostGISFreeLayerInfo(layerObj *layer)
+{
+  msPostGISLayerInfo *layerinfo = NULL;
+  layerinfo = (msPostGISLayerInfo*)layer->layerinfo;
+  if ( layerinfo->sql ) free(layerinfo->sql);
+  if ( layerinfo->uid ) free(layerinfo->uid);
+  if ( layerinfo->srid ) free(layerinfo->srid);
+  if ( layerinfo->geomcolumn ) free(layerinfo->geomcolumn);
+  if ( layerinfo->fromsource ) free(layerinfo->fromsource);
+  if ( layerinfo->pgresult ) PQclear(layerinfo->pgresult);
+  if ( layerinfo->pgconn ) msConnPoolRelease(layer, layerinfo->pgconn);
+  free(layerinfo);
+  layer->layerinfo = NULL;
 }
 
 
@@ -138,13 +134,14 @@ void msPostGISFreeLayerInfo(layerObj *layer) {
 ** Propagate messages from the database to the Mapserver log,
 ** set in PQsetNoticeProcessor during layer open.
 */
-void postresqlNoticeHandler(void *arg, const char *message) {
-    layerObj *lp;
-    lp = (layerObj*)arg;
+void postresqlNoticeHandler(void *arg, const char *message)
+{
+  layerObj *lp;
+  lp = (layerObj*)arg;
 
-    if (lp->debug) {
-        msDebug("%s\n", message);
-    }
+  if (lp->debug) {
+    msDebug("%s\n", message);
+  }
 }
 
 
@@ -154,13 +151,13 @@ void postresqlNoticeHandler(void *arg, const char *message) {
 */
 pointArrayObj*
 pointArrayNew(int maxpoints)
-  {
-    pointArrayObj *d = msSmallMalloc(sizeof(pointArrayObj));
-    if ( maxpoints < 1 ) maxpoints = 1; /* Avoid a degenerate case */
-    d->maxpoints = maxpoints;
-    d->data = msSmallMalloc(maxpoints * sizeof(pointObj));
-    d->npoints = 0;
-    return d;
+{
+  pointArrayObj *d = msSmallMalloc(sizeof(pointArrayObj));
+  if ( maxpoints < 1 ) maxpoints = 1; /* Avoid a degenerate case */
+  d->maxpoints = maxpoints;
+  d->data = msSmallMalloc(maxpoints * sizeof(pointObj));
+  d->npoints = 0;
+  return d;
 }
 
 /*
@@ -169,9 +166,9 @@ pointArrayNew(int maxpoints)
 void
 pointArrayFree(pointArrayObj *d)
 {
-    if ( ! d ) return;
-    if ( d->data ) free(d->data);
-    free(d);
+  if ( ! d ) return;
+  if ( d->data ) free(d->data);
+  free(d);
 }
 
 /*
@@ -182,15 +179,15 @@ pointArrayFree(pointArrayObj *d)
 static int
 pointArrayAddPoint(pointArrayObj *d, const pointObj *p)
 {
-    if ( !p || !d ) return MS_FAILURE;
-    /* Avoid overwriting memory buffer */
-    if ( d->maxpoints - d->npoints == 0 ) {
-        d->maxpoints *= 2;
-        d->data = realloc(d->data, d->maxpoints * sizeof(pointObj));
-    }
-    d->data[d->npoints] = *p;
-    d->npoints++;
-    return MS_SUCCESS;
+  if ( !p || !d ) return MS_FAILURE;
+  /* Avoid overwriting memory buffer */
+  if ( d->maxpoints - d->npoints == 0 ) {
+    d->maxpoints *= 2;
+    d->data = realloc(d->data, d->maxpoints * sizeof(pointObj));
+  }
+  d->data[d->npoints] = *p;
+  d->npoints++;
+  return MS_SUCCESS;
 }
 
 /*
@@ -200,34 +197,34 @@ pointArrayAddPoint(pointArrayObj *d, const pointObj *p)
 static int
 wkbTypeMap(wkbObj *w, int type)
 {
-    if ( type < WKB_TYPE_COUNT )
-        return w->typemap[type];
-    else
-        return 0;
+  if ( type < WKB_TYPE_COUNT )
+    return w->typemap[type];
+  else
+    return 0;
 }
 
-/* 
+/*
 ** Read the WKB type number from a wkbObj without
 ** advancing the read pointer.
 */
 static int
 wkbType(wkbObj *w)
 {
-    int t;
-    memcpy(&t, (w->ptr + 1), sizeof(int));
-    return wkbTypeMap(w,t);
+  int t;
+  memcpy(&t, (w->ptr + 1), sizeof(int));
+  return wkbTypeMap(w,t);
 }
 
 /*
-** Read the type number of the first element of a 
+** Read the type number of the first element of a
 ** collection without advancing the read pointer.
 */
 static int
 wkbCollectionSubType(wkbObj *w)
 {
-    int t;
-    memcpy(&t, (w->ptr + 1 + 4 + 4 + 1), sizeof(int));
-    return wkbTypeMap(w,t);
+  int t;
+  memcpy(&t, (w->ptr + 1 + 4 + 4 + 1), sizeof(int));
+  return wkbTypeMap(w,t);
 }
 
 /*
@@ -236,10 +233,10 @@ wkbCollectionSubType(wkbObj *w)
 static char
 wkbReadChar(wkbObj *w)
 {
-    char c;
-    memcpy(&c, w->ptr, sizeof(char));
-    w->ptr += sizeof(char);
-    return c;
+  char c;
+  memcpy(&c, w->ptr, sizeof(char));
+  w->ptr += sizeof(char);
+  return c;
 }
 
 /*
@@ -249,10 +246,10 @@ wkbReadChar(wkbObj *w)
 static inline int
 wkbReadInt(wkbObj *w)
 {
-    int i;
-    memcpy(&i, w->ptr, sizeof(int));
-    w->ptr += sizeof(int);
-    return i;
+  int i;
+  memcpy(&i, w->ptr, sizeof(int));
+  w->ptr += sizeof(int);
+  return i;
 }
 
 /*
@@ -262,10 +259,10 @@ wkbReadInt(wkbObj *w)
 static inline double
 wkbReadDouble(wkbObj *w)
 {
-    double d;
-    memcpy(&d, w->ptr, sizeof(double));
-    w->ptr += sizeof(double);
-    return d;
+  double d;
+  memcpy(&d, w->ptr, sizeof(double));
+  w->ptr += sizeof(double);
+  return d;
 }
 
 /*
@@ -275,10 +272,10 @@ wkbReadDouble(wkbObj *w)
 static inline void
 wkbReadPointP(wkbObj *w, pointObj *p)
 {
-    memcpy(&(p->x), w->ptr, sizeof(double));
-    w->ptr += sizeof(double);
-    memcpy(&(p->y), w->ptr, sizeof(double));
-    w->ptr += sizeof(double);
+  memcpy(&(p->x), w->ptr, sizeof(double));
+  w->ptr += sizeof(double);
+  memcpy(&(p->y), w->ptr, sizeof(double));
+  w->ptr += sizeof(double);
 }
 
 /*
@@ -288,33 +285,31 @@ wkbReadPointP(wkbObj *w, pointObj *p)
 static inline pointObj
 wkbReadPoint(wkbObj *w)
 {
-    pointObj p;
-    wkbReadPointP(w, &p);
-    return p;
+  pointObj p;
+  wkbReadPointP(w, &p);
+  return p;
 }
 
 /*
 ** Read a "point array" and return an allocated lineObj.
-** A point array is a WKB fragment that starts with a 
+** A point array is a WKB fragment that starts with a
 ** point count, which is followed by that number of doubles * 2.
 ** Linestrings, circular strings, polygon rings, all show this
 ** form.
 */
-static lineObj*
-wkbReadLine(wkbObj *w)
+static void
+wkbReadLine(wkbObj *w, lineObj *line)
 {
-    int i;
-    pointObj p;
-    lineObj *line = msSmallMalloc(sizeof(lineObj));
-    int npoints = wkbReadInt(w);
+  int i;
+  pointObj p;
+  int npoints = wkbReadInt(w);
 
-    line->numpoints = npoints;
-    line->point = msSmallMalloc(npoints * sizeof(pointObj));
-    for ( i = 0; i < npoints; i++ ) {
-        wkbReadPointP(w, &p);
-        line->point[i] = p;
-    }
-    return line;
+  line->numpoints = npoints;
+  line->point = msSmallMalloc(npoints * sizeof(pointObj));
+  for ( i = 0; i < npoints; i++ ) {
+    wkbReadPointP(w, &p);
+    line->point[i] = p;
+  }
 }
 
 /*
@@ -324,26 +319,25 @@ wkbReadLine(wkbObj *w)
 static void
 wkbSkipGeometry(wkbObj *w)
 {
-    char endian;
-    int type, npoints, nrings, ngeoms, i;
-    endian = wkbReadChar(w);
-    type = wkbTypeMap(w,wkbReadInt(w));
-    switch(type) {
+  int type, npoints, nrings, ngeoms, i;
+  /*endian = */wkbReadChar(w);
+  type = wkbTypeMap(w,wkbReadInt(w));
+  switch(type) {
     case WKB_POINT:
-        w->ptr += 2 * sizeof(double);
-        break;
+      w->ptr += 2 * sizeof(double);
+      break;
     case WKB_CIRCULARSTRING:
     case WKB_LINESTRING:
+      npoints = wkbReadInt(w);
+      w->ptr += npoints * 2 * sizeof(double);
+      break;
+    case WKB_POLYGON:
+      nrings = wkbReadInt(w);
+      for ( i = 0; i < nrings; i++ ) {
         npoints = wkbReadInt(w);
         w->ptr += npoints * 2 * sizeof(double);
-        break;
-    case WKB_POLYGON:
-        nrings = wkbReadInt(w);
-        for ( i = 0; i < nrings; i++ ) {
-            npoints = wkbReadInt(w);
-            w->ptr += npoints * 2 * sizeof(double);
-          }
-        break;
+      }
+      break;
     case WKB_MULTIPOINT:
     case WKB_MULTILINESTRING:
     case WKB_MULTIPOLYGON:
@@ -352,87 +346,80 @@ wkbSkipGeometry(wkbObj *w)
     case WKB_CURVEPOLYGON:
     case WKB_MULTICURVE:
     case WKB_MULTISURFACE:
-        ngeoms = wkbReadInt(w);
-        for ( i = 0; i < ngeoms; i++ ) {
-            wkbSkipGeometry(w);
-        }
+      ngeoms = wkbReadInt(w);
+      for ( i = 0; i < ngeoms; i++ ) {
+        wkbSkipGeometry(w);
       }
+  }
 }
 
 /*
 ** Convert a WKB point to a shapeObj, advancing the read pointer as we go.
 */
-static int 
+static int
 wkbConvPointToShape(wkbObj *w, shapeObj *shape)
 {
-    char endian;
-    int type;
-    lineObj *line;
-
-    endian = wkbReadChar(w);
-    type = wkbTypeMap(w,wkbReadInt(w));
-
-    if( type != WKB_POINT ) return MS_FAILURE;
-
-    if( ! (shape->type == MS_SHAPE_POINT) ) return MS_FAILURE;
-    line = msSmallMalloc(sizeof(lineObj));
-    line->numpoints = 1;
-    line->point = msSmallMalloc(sizeof(pointObj));
-    line->point[0] = wkbReadPoint(w);
-    msAddLineDirectly(shape, line);
-    free(line);
-    return MS_SUCCESS;
-  }
+  int type;
+  lineObj line;
+
+  /*endian = */wkbReadChar(w);
+  type = wkbTypeMap(w,wkbReadInt(w));
+
+  if( type != WKB_POINT ) return MS_FAILURE;
+
+  if( ! (shape->type == MS_SHAPE_POINT) ) return MS_FAILURE;
+  line.numpoints = 1;
+  line.point = msSmallMalloc(sizeof(pointObj));
+  line.point[0] = wkbReadPoint(w);
+  msAddLineDirectly(shape, &line);
+  return MS_SUCCESS;
+}
 
 /*
 ** Convert a WKB line string to a shapeObj, advancing the read pointer as we go.
 */
-static int 
+static int
 wkbConvLineStringToShape(wkbObj *w, shapeObj *shape)
 {
-    char endian;
-    int type;
-    lineObj *line;
-
-    endian = wkbReadChar(w);
-    type = wkbTypeMap(w,wkbReadInt(w));
-
-    if( type != WKB_LINESTRING ) return MS_FAILURE;
-    
-    line = wkbReadLine(w);
-    msAddLineDirectly(shape, line);
-    free(line);
-    
-    return MS_SUCCESS;
+  int type;
+  lineObj line;
+
+  /*endian = */wkbReadChar(w);
+  type = wkbTypeMap(w,wkbReadInt(w));
+
+  if( type != WKB_LINESTRING ) return MS_FAILURE;
+
+  wkbReadLine(w,&line);
+  msAddLineDirectly(shape, &line);
+
+  return MS_SUCCESS;
 }
 
 /*
 ** Convert a WKB polygon to a shapeObj, advancing the read pointer as we go.
 */
-static int 
+static int
 wkbConvPolygonToShape(wkbObj *w, shapeObj *shape)
-  {
-    char endian;
-    int type;
-    int i, nrings;
-    lineObj *line;
-
-    endian = wkbReadChar(w);
-    type = wkbTypeMap(w,wkbReadInt(w));
-    
-    if( type != WKB_POLYGON ) return MS_FAILURE;
-
-    /* How many rings? */
-    nrings = wkbReadInt(w);
-    
-    /* Add each ring to the shape */
-    for( i = 0; i < nrings; i++ ) { 
-        line = wkbReadLine(w);
-        msAddLineDirectly(shape, line);
-        free(line);
-    }    
+{
+  int type;
+  int i, nrings;
+  lineObj line;
 
-    return MS_SUCCESS;
+  /*endian = */wkbReadChar(w);
+  type = wkbTypeMap(w,wkbReadInt(w));
+
+  if( type != WKB_POLYGON ) return MS_FAILURE;
+
+  /* How many rings? */
+  nrings = wkbReadInt(w);
+
+  /* Add each ring to the shape */
+  for( i = 0; i < nrings; i++ ) {
+    wkbReadLine(w,&line);
+    msAddLineDirectly(shape, &line);
+  }
+
+  return MS_SUCCESS;
 }
 
 /*
@@ -440,301 +427,341 @@ wkbConvPolygonToShape(wkbObj *w, shapeObj *shape)
 ** The arc portions of the rings will be stroked to linestrings as they
 ** are read by the underlying circular string handling.
 */
-static int 
+static int
 wkbConvCurvePolygonToShape(wkbObj *w, shapeObj *shape)
 {
-    char endian;
-    int type, i, ncomponents;
-    int failures = 0;
-    int was_poly = ( shape->type == MS_SHAPE_POLYGON );
-
-    endian = wkbReadChar(w);
-    type = wkbTypeMap(w,wkbReadInt(w));
-    ncomponents = wkbReadInt(w);
-    
-    if( type != WKB_CURVEPOLYGON ) return MS_FAILURE;
-
-    /* Lower the allowed dimensionality so we can
-    *  catch the linear ring components */
-    shape->type = MS_SHAPE_LINE;
-    
-    for ( i = 0; i < ncomponents; i++ ) {
-        if ( wkbConvGeometryToShape(w, shape) == MS_FAILURE ) {
-            wkbSkipGeometry(w);
-            failures++;
-          }
-      }
-    
-    /* Go back to expected dimensionality */
-    if ( was_poly) shape->type = MS_SHAPE_POLYGON;
-    
-    if ( failures == ncomponents ) 
-        return MS_FAILURE;
-    else
-        return MS_SUCCESS;
+  int type, i, ncomponents;
+  int failures = 0;
+  int was_poly = ( shape->type == MS_SHAPE_POLYGON );
+
+  /*endian = */wkbReadChar(w);
+  type = wkbTypeMap(w,wkbReadInt(w));
+  ncomponents = wkbReadInt(w);
+
+  if( type != WKB_CURVEPOLYGON ) return MS_FAILURE;
+
+  /* Lower the allowed dimensionality so we can
+  *  catch the linear ring components */
+  shape->type = MS_SHAPE_LINE;
+
+  for ( i = 0; i < ncomponents; i++ ) {
+    if ( wkbConvGeometryToShape(w, shape) == MS_FAILURE ) {
+      wkbSkipGeometry(w);
+      failures++;
+    }
+  }
+
+  /* Go back to expected dimensionality */
+  if ( was_poly) shape->type = MS_SHAPE_POLYGON;
+
+  if ( failures == ncomponents )
+    return MS_FAILURE;
+  else
+    return MS_SUCCESS;
 }
 
 /*
 ** Convert a WKB circular string to a shapeObj, advancing the read pointer as we go.
 ** Arcs will be stroked to linestrings.
 */
-static int 
+static int
 wkbConvCircularStringToShape(wkbObj *w, shapeObj *shape)
 {
-    char endian;
-    int type;
-    lineObj line = {0, NULL};
-
-    endian = wkbReadChar(w);
-    type = wkbTypeMap(w,wkbReadInt(w));
-
-    if( type != WKB_CIRCULARSTRING ) return MS_FAILURE;
-        
-    /* Stroke the string into a point array */
-    if ( arcStrokeCircularString(w, SEGMENT_ANGLE, &line) == MS_FAILURE ) {
-        if(line.point) free(line.point);
-        return MS_FAILURE;
-    }
-                
-    /* Fill in the lineObj */
-    if ( line.numpoints > 0 ) {
-        msAddLine(shape, &line);
-        if(line.point) free(line.point);
-    }
+  int type;
+  lineObj line = {0, NULL};
+
+  /*endian = */wkbReadChar(w);
+  type = wkbTypeMap(w,wkbReadInt(w));
+
+  if( type != WKB_CIRCULARSTRING ) return MS_FAILURE;
 
-      return MS_SUCCESS;
+  /* Stroke the string into a point array */
+  if ( arcStrokeCircularString(w, SEGMENT_ANGLE, &line) == MS_FAILURE ) {
+    if(line.point) free(line.point);
+    return MS_FAILURE;
+  }
+
+  /* Fill in the lineObj */
+  if ( line.numpoints > 0 ) {
+    msAddLine(shape, &line);
+    if(line.point) free(line.point);
   }
 
+  return MS_SUCCESS;
+}
+
 /*
 ** Compound curves need special handling. First we load
 ** each component of the curve on the a lineObj in a shape.
 ** Then we merge those lineObjs into a single lineObj. This
-** allows compound curves to serve as closed rings in 
+** allows compound curves to serve as closed rings in
 ** curve polygons.
 */
 static int
 wkbConvCompoundCurveToShape(wkbObj *w, shapeObj *shape)
 {
-    char endian;
-    int npoints = 0;
-    int type, ncomponents, i, j;
-    lineObj *line;
-    shapeObj shapebuf;
-
-    endian = wkbReadChar(w);
-    type = wkbTypeMap(w,wkbReadInt(w));
-    
-    /* Init our shape buffer */
-    msInitShape(&shapebuf);
-
-    if( type != WKB_COMPOUNDCURVE ) return MS_FAILURE;
-    
-    /* How many components in the compound curve? */
-    ncomponents = wkbReadInt(w);
-
-    /* We'll load each component onto a line in a shape */
-    for( i = 0; i < ncomponents; i++ ) 
-        wkbConvGeometryToShape(w, &shapebuf);
-    
-    /* Do nothing on empty */
-    if ( shapebuf.numlines == 0 )
-        return MS_FAILURE;
+  int npoints = 0;
+  int type, ncomponents, i, j;
+  lineObj *line;
+  shapeObj shapebuf;
 
-    /* Count the total number of points */
-    for( i = 0; i < shapebuf.numlines; i++ ) 
-        npoints += shapebuf.line[i].numpoints;
+  /*endian = */wkbReadChar(w);
+  type = wkbTypeMap(w,wkbReadInt(w));
 
-    /* Do nothing on empty */
-    if ( npoints == 0 )
-        return MS_FAILURE;
+  /* Init our shape buffer */
+  msInitShape(&shapebuf);
+
+  if( type != WKB_COMPOUNDCURVE ) return MS_FAILURE;
 
-    /* Allocate space for the new line */
-    line = msSmallMalloc(sizeof(lineObj));
-    line->numpoints = npoints;
-    line->point = msSmallMalloc(sizeof(pointObj) * npoints);
-
-    /* Copy in the points */
-    npoints = 0;
-    for ( i = 0; i < shapebuf.numlines; i++ ) {
-        for ( j = 0; j < shapebuf.line[i].numpoints; j++ ) {
-            /* Don't add a start point that duplicates an endpoint */
-            if( j == 0 && i > 0 && 
-                memcmp(&(line->point[npoints - 1]),&(shapebuf.line[i].point[j]),sizeof(pointObj)) == 0 ) {
-                continue;
-              }
-            line->point[npoints++] = shapebuf.line[i].point[j];
-          }
+  /* How many components in the compound curve? */
+  ncomponents = wkbReadInt(w);
+
+  /* We'll load each component onto a line in a shape */
+  for( i = 0; i < ncomponents; i++ )
+    wkbConvGeometryToShape(w, &shapebuf);
+
+  /* Do nothing on empty */
+  if ( shapebuf.numlines == 0 )
+    return MS_FAILURE;
+
+  /* Count the total number of points */
+  for( i = 0; i < shapebuf.numlines; i++ )
+    npoints += shapebuf.line[i].numpoints;
+
+  /* Do nothing on empty */
+  if ( npoints == 0 )
+    return MS_FAILURE;
+
+  /* Allocate space for the new line */
+  line = msSmallMalloc(sizeof(lineObj));
+  line->numpoints = npoints;
+  line->point = msSmallMalloc(sizeof(pointObj) * npoints);
+
+  /* Copy in the points */
+  npoints = 0;
+  for ( i = 0; i < shapebuf.numlines; i++ ) {
+    for ( j = 0; j < shapebuf.line[i].numpoints; j++ ) {
+      /* Don't add a start point that duplicates an endpoint */
+      if( j == 0 && i > 0 &&
+          memcmp(&(line->point[npoints - 1]),&(shapebuf.line[i].point[j]),sizeof(pointObj)) == 0 ) {
+        continue;
       }
-    line->numpoints = npoints;
-    
-    /* Clean up */
-    msFreeShape(&shapebuf);
+      line->point[npoints++] = shapebuf.line[i].point[j];
+    }
+  }
+  line->numpoints = npoints;
 
-    /* Fill in the lineObj */
-    msAddLineDirectly(shape, line);
+  /* Clean up */
+  msFreeShape(&shapebuf);
 
-    return MS_SUCCESS;
+  /* Fill in the lineObj */
+  msAddLineDirectly(shape, line);
+
+  return MS_SUCCESS;
 }
 
 /*
 ** Convert a WKB collection string to a shapeObj, advancing the read pointer as we go.
 ** Many WKB types (MultiPoint, MultiLineString, MultiPolygon, MultiSurface,
-** MultiCurve, GeometryCollection) can be treated identically as collections 
-** (they start with endian, type number and count of sub-elements, then provide the 
+** MultiCurve, GeometryCollection) can be treated identically as collections
+** (they start with endian, type number and count of sub-elements, then provide the
 ** subelements as WKB) so are handled with this one function.
 */
-static int 
+static int
 wkbConvCollectionToShape(wkbObj *w, shapeObj *shape)
 {
-    char endian;
-    int type, i, ncomponents;
-    int failures = 0;
-
-    endian = wkbReadChar(w);
-    type = wkbTypeMap(w,wkbReadInt(w));
-    ncomponents = wkbReadInt(w);
-    
-    /* 
-    * If we can draw any portion of the collection, we will, 
-    * but if all the components fail, we will draw nothing.
-    */
-    for ( i = 0; i < ncomponents; i++ ) {
-        if ( wkbConvGeometryToShape(w, shape) == MS_FAILURE ) {
-            wkbSkipGeometry(w);
-            failures++;
-        }
+  int i, ncomponents;
+  int failures = 0;
+
+  /*endian = */wkbReadChar(w);
+  /*type = */wkbTypeMap(w,wkbReadInt(w));
+  ncomponents = wkbReadInt(w);
+
+  /*
+  * If we can draw any portion of the collection, we will,
+  * but if all the components fail, we will draw nothing.
+  */
+  for ( i = 0; i < ncomponents; i++ ) {
+    if ( wkbConvGeometryToShape(w, shape) == MS_FAILURE ) {
+      wkbSkipGeometry(w);
+      failures++;
     }
-    if ( failures == ncomponents ) 
-        return MS_FAILURE;
-    else
-        return MS_SUCCESS;
+  }
+  if ( failures == ncomponents )
+    return MS_FAILURE;
+  else
+    return MS_SUCCESS;
 }
 
 /*
 ** Generic handler to switch to the appropriate function for the WKB type.
 ** Note that we also handle switching here to avoid processing shapes
-** we will be unable to draw. Example: we can't draw point features as 
-** a MS_SHAPE_LINE layer, so if the type is WKB_POINT and the layer is 
+** we will be unable to draw. Example: we can't draw point features as
+** a MS_SHAPE_LINE layer, so if the type is WKB_POINT and the layer is
 ** MS_SHAPE_LINE, we exit before converting.
 */
-int 
+int
 wkbConvGeometryToShape(wkbObj *w, shapeObj *shape)
 {
-    int wkbtype = wkbType(w); /* Peak at the type number */
-
-    switch(wkbtype) {
-        /* Recurse into anonymous collections */
-        case WKB_GEOMETRYCOLLECTION: return wkbConvCollectionToShape(w, shape);
-        /* Handle area types */
-        case WKB_POLYGON:      return wkbConvPolygonToShape(w, shape);
-        case WKB_MULTIPOLYGON: return wkbConvCollectionToShape(w, shape);
-        case WKB_CURVEPOLYGON: return wkbConvCurvePolygonToShape(w, shape);
-        case WKB_MULTISURFACE: return wkbConvCollectionToShape(w, shape);
-    }
-
-    /* We can't convert any of the following types into polygons */
-    if ( shape->type == MS_SHAPE_POLYGON ) return MS_FAILURE;
-
-    /* Handle linear types */
-    switch(wkbtype) {
-        case WKB_LINESTRING:      return wkbConvLineStringToShape(w, shape);
-        case WKB_CIRCULARSTRING:  return wkbConvCircularStringToShape(w, shape);
-        case WKB_COMPOUNDCURVE:   return wkbConvCompoundCurveToShape(w, shape);
-        case WKB_MULTILINESTRING: return wkbConvCollectionToShape(w, shape);
-        case WKB_MULTICURVE:      return wkbConvCollectionToShape(w, shape);
-      }
+  int wkbtype = wkbType(w); /* Peak at the type number */
+
+  switch(wkbtype) {
+      /* Recurse into anonymous collections */
+    case WKB_GEOMETRYCOLLECTION:
+      return wkbConvCollectionToShape(w, shape);
+      /* Handle area types */
+    case WKB_POLYGON:
+      return wkbConvPolygonToShape(w, shape);
+    case WKB_MULTIPOLYGON:
+      return wkbConvCollectionToShape(w, shape);
+    case WKB_CURVEPOLYGON:
+      return wkbConvCurvePolygonToShape(w, shape);
+    case WKB_MULTISURFACE:
+      return wkbConvCollectionToShape(w, shape);
+  }
 
-    /* We can't convert any of the following types into lines */
-    if ( shape->type == MS_SHAPE_LINE ) return MS_FAILURE;
+  /* We can't convert any of the following types into polygons */
+  if ( shape->type == MS_SHAPE_POLYGON ) return MS_FAILURE;
 
-    /* Handle point types */
-    switch(wkbtype) {
-        case WKB_POINT: return wkbConvPointToShape(w, shape);
-        case WKB_MULTIPOINT: return wkbConvCollectionToShape(w, shape);
-      }
+  /* Handle linear types */
+  switch(wkbtype) {
+    case WKB_LINESTRING:
+      return wkbConvLineStringToShape(w, shape);
+    case WKB_CIRCULARSTRING:
+      return wkbConvCircularStringToShape(w, shape);
+    case WKB_COMPOUNDCURVE:
+      return wkbConvCompoundCurveToShape(w, shape);
+    case WKB_MULTILINESTRING:
+      return wkbConvCollectionToShape(w, shape);
+    case WKB_MULTICURVE:
+      return wkbConvCollectionToShape(w, shape);
+  }
 
-    /* This is a WKB type we don't know about! */
-    return MS_FAILURE;
+  /* We can't convert any of the following types into lines */
+  if ( shape->type == MS_SHAPE_LINE ) return MS_FAILURE;
+
+  /* Handle point types */
+  switch(wkbtype) {
+    case WKB_POINT:
+      return wkbConvPointToShape(w, shape);
+    case WKB_MULTIPOINT:
+      return wkbConvCollectionToShape(w, shape);
+  }
+
+  /* This is a WKB type we don't know about! */
+  return MS_FAILURE;
 }
 
 
 /*
-** Calculate determinant of a 3x3 matrix. Handy for 
+** Calculate determinant of a 3x3 matrix. Handy for
 ** the circle center calculation.
 */
 static inline double
-arcDeterminant3x3(double *m) 
+arcDeterminant3x3(double *m)
 {
-    /* This had better be a 3x3 matrix or we'll fall to bits */
-    return m[0] * ( m[4] * m[8] - m[7] * m[5] ) -
-           m[3] * ( m[1] * m[8] - m[7] * m[2] ) +
-           m[6] * ( m[1] * m[5] - m[4] * m[2] );
-}    
+  /* This had better be a 3x3 matrix or we'll fall to bits */
+  return m[0] * ( m[4] * m[8] - m[7] * m[5] ) -
+         m[3] * ( m[1] * m[8] - m[7] * m[2] ) +
+         m[6] * ( m[1] * m[5] - m[4] * m[2] );
+}
 
 /*
 ** What side of p1->p2 is q on?
 */
-static inline int 
-arcSegmentSide(const pointObj *p1, const pointObj *p2, const pointObj *q) 
+static inline int
+arcSegmentSide(const pointObj *p1, const pointObj *p2, const pointObj *q)
 {
-    double side = ( (q->x - p1->x) * (p2->y - p1->y) - (p2->x - p1->x) * (q->y - p1->y) );
-    if ( FP_EQ(side,0.0) ) {
-        return FP_COLINEAR;
-    }
-    else {
-        if ( side < 0.0 )
-            return FP_LEFT;
-        else
-            return FP_RIGHT;
-    }
+  double side = ( (q->x - p1->x) * (p2->y - p1->y) - (p2->x - p1->x) * (q->y - p1->y) );
+  if ( FP_EQ(side,0.0) ) {
+    return FP_COLINEAR;
+  } else {
+    if ( side < 0.0 )
+      return FP_LEFT;
+    else
+      return FP_RIGHT;
+  }
 }
-    
-/* 
+
+/*
 ** Calculate the center of the circle defined by three points.
-** Using matrix approach from http://mathforum.org/library/drmath/view/55239.html 
+** Using matrix approach from http://mathforum.org/library/drmath/view/55239.html
 */
 int
-arcCircleCenter(const pointObj *p1, const pointObj *p2, const pointObj *p3, pointObj *center, double *radius) 
+arcCircleCenter(const pointObj *p1, const pointObj *p2, const pointObj *p3, pointObj *center, double *radius)
 {
-    pointObj c;
-    double r;
-    
-    /* Components of the matrices. */
-    double x1sq = p1->x * p1->x;
-    double x2sq = p2->x * p2->x;
-    double x3sq = p3->x * p3->x;
-    double y1sq = p1->y * p1->y;
-    double y2sq = p2->y * p2->y;
-    double y3sq = p3->y * p3->y;
-    double matrix_num_x[9] = { x1sq+y1sq, p1->y, 1.0, x2sq+y2sq, p2->y, 1.0, x3sq+y3sq, p3->y, 1.0 };
-    double matrix_num_y[9] = { p1->x, x1sq+y1sq, 1.0, p2->x, x2sq+y2sq, 1.0, p3->x, x3sq+y3sq, 1.0 };
-    double matrix_denom[9] = { p1->x, p1->y, 1.0, p2->x, p2->y, 1.0, p3->x, p3->y, 1.0 };
-
-    /* Circle is closed, so p2 must be opposite p1 & p3. */ 
-    if ( FP_EQ(p1->x,p3->x) && FP_EQ(p1->y,p3->y) ) {
-        c.x = (p1->x + p2->x) / 2.0;
-        c.y = (p1->y + p2->y) / 2.0;
-        r = sqrt( (p1->x - p2->x) * (p1->x - p2->x) + (p1->y - p2->y) * (p1->y - p2->y) ) / 2.0;
-    }
-    /* There is no circle here, the points are actually co-linear */
-    else if ( arcSegmentSide(p1, p3, p2) == FP_COLINEAR ) {
-        return MS_FAILURE;
-    }
-    /* Calculate the center and radius. */
-    else {
-        double denom = 2.0 * arcDeterminant3x3(matrix_denom);
-        /* Center components */
-        c.x = arcDeterminant3x3(matrix_num_x) / denom; 
-        c.y = arcDeterminant3x3(matrix_num_y) / denom; 
+  pointObj c;
+  double r;
+
+  /* Components of the matrices. */
+  double x1sq = p1->x * p1->x;
+  double x2sq = p2->x * p2->x;
+  double x3sq = p3->x * p3->x;
+  double y1sq = p1->y * p1->y;
+  double y2sq = p2->y * p2->y;
+  double y3sq = p3->y * p3->y;
+  double matrix_num_x[9];
+  double matrix_num_y[9];
+  double matrix_denom[9];
+
+  /* Intialize matrix_num_x */
+  matrix_num_x[0] = x1sq+y1sq;
+  matrix_num_x[1] = p1->y;
+  matrix_num_x[2] = 1.0;
+  matrix_num_x[3] = x2sq+y2sq;
+  matrix_num_x[4] = p2->y;
+  matrix_num_x[5] = 1.0;
+  matrix_num_x[6] = x3sq+y3sq;
+  matrix_num_x[7] = p3->y;
+  matrix_num_x[8] = 1.0;
+
+  /* Intialize matrix_num_y */
+  matrix_num_y[0] = p1->x;
+  matrix_num_y[1] = x1sq+y1sq;
+  matrix_num_y[2] = 1.0;
+  matrix_num_y[3] = p2->x;
+  matrix_num_y[4] = x2sq+y2sq;
+  matrix_num_y[5] = 1.0;
+  matrix_num_y[6] = p3->x;
+  matrix_num_y[7] = x3sq+y3sq;
+  matrix_num_y[8] = 1.0;
+
+  /* Intialize matrix_denom */
+  matrix_denom[0] = p1->x;
+  matrix_denom[1] = p1->y;
+  matrix_denom[2] = 1.0;
+  matrix_denom[3] = p2->x;
+  matrix_denom[4] = p2->y;
+  matrix_denom[5] = 1.0;
+  matrix_denom[6] = p3->x;
+  matrix_denom[7] = p3->y;
+  matrix_denom[8] = 1.0;
+
+  /* Circle is closed, so p2 must be opposite p1 & p3. */
+  if ( FP_EQ(p1->x,p3->x) && FP_EQ(p1->y,p3->y) ) {
+    c.x = (p1->x + p2->x) / 2.0;
+    c.y = (p1->y + p2->y) / 2.0;
+    r = sqrt( (p1->x - p2->x) * (p1->x - p2->x) + (p1->y - p2->y) * (p1->y - p2->y) ) / 2.0;
+  }
+  /* There is no circle here, the points are actually co-linear */
+  else if ( arcSegmentSide(p1, p3, p2) == FP_COLINEAR ) {
+    return MS_FAILURE;
+  }
+  /* Calculate the center and radius. */
+  else {
+    double denom = 2.0 * arcDeterminant3x3(matrix_denom);
+    /* Center components */
+    c.x = arcDeterminant3x3(matrix_num_x) / denom;
+    c.y = arcDeterminant3x3(matrix_num_y) / denom;
+
+    /* Radius */
+    r = sqrt((p1->x-c.x) * (p1->x-c.x) + (p1->y-c.y) * (p1->y-c.y));
+  }
 
-        /* Radius */
-        r = sqrt((p1->x-c.x) * (p1->x-c.x) + (p1->y-c.y) * (p1->y-c.y));
-    }
-    
-    if ( radius ) *radius = r;
-    if ( center ) *center = c;
+  if ( radius ) *radius = r;
+  if ( center ) *center = c;
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 /*
@@ -743,327 +770,327 @@ arcCircleCenter(const pointObj *p1, const pointObj *p2, const pointObj *p3, poin
 ** and depending on whether this is the first arc in a circularstring,
 ** you might want to include_first
 */
-int 
+int
 arcStrokeCircle(const pointObj *p1, const pointObj *p2, const pointObj *p3,
                 double segment_angle, int include_first, pointArrayObj *pa)
 {
-    pointObj center; /* Center of our circular arc */
-    double radius; /* Radius of our circular arc */
-    double sweep_angle_r; /* Total angular size of our circular arc in radians */
-    double segment_angle_r; /* Segment angle in radians */
-    double a1, a2, a3; /* Angles represented by p1, p2, p3 relative to center */
-    int side = arcSegmentSide(p1, p3, p2); /* What side of p1,p3 is the middle point? */
-    int num_edges; /* How many edges we will be generating */
-    double current_angle_r; /* What angle are we generating now (radians)? */
-    int i; /* Counter */
-    pointObj p; /* Temporary point */
-    int is_closed = MS_FALSE;
-    
-    /* We need to know if we're dealing with a circle early */
-    if ( FP_EQ(p1->x, p3->x) && FP_EQ(p1->y, p3->y) )
-        is_closed = MS_TRUE;
-    
-    /* Check if the "arc" is actually straight */
-    if ( ! is_closed && side == FP_COLINEAR ) {
-        /* We just need to write in the end points */
-        if ( include_first ) 
-            pointArrayAddPoint(pa, p1);
-        pointArrayAddPoint(pa, p3);
-        return MS_SUCCESS;
-    }
+  pointObj center; /* Center of our circular arc */
+  double radius; /* Radius of our circular arc */
+  double sweep_angle_r; /* Total angular size of our circular arc in radians */
+  double segment_angle_r; /* Segment angle in radians */
+  double a1, /*a2,*/ a3; /* Angles represented by p1, p2, p3 relative to center */
+  int side = arcSegmentSide(p1, p3, p2); /* What side of p1,p3 is the middle point? */
+  int num_edges; /* How many edges we will be generating */
+  double current_angle_r; /* What angle are we generating now (radians)? */
+  int i; /* Counter */
+  pointObj p; /* Temporary point */
+  int is_closed = MS_FALSE;
+
+  /* We need to know if we're dealing with a circle early */
+  if ( FP_EQ(p1->x, p3->x) && FP_EQ(p1->y, p3->y) )
+    is_closed = MS_TRUE;
+
+  /* Check if the "arc" is actually straight */
+  if ( ! is_closed && side == FP_COLINEAR ) {
+    /* We just need to write in the end points */
+    if ( include_first )
+      pointArrayAddPoint(pa, p1);
+    pointArrayAddPoint(pa, p3);
+    return MS_SUCCESS;
+  }
 
-    /* We should always be able to find the center of a non-linear arc */
-    if ( arcCircleCenter(p1, p2, p3, &center, &radius) == MS_FAILURE ) 
-        return MS_FAILURE;
-        
-    /* Calculate the angles that our three points represent */
-    a1 = atan2(p1->y - center.y, p1->x - center.x);
-    a2 = atan2(p2->y - center.y, p2->x - center.x);
-    a3 = atan2(p3->y - center.y, p3->x - center.x);
-    segment_angle_r = M_PI * segment_angle / 180.0;
-
-    /* Closed-circle case, we sweep the whole circle! */
-    if ( is_closed ) {
-        sweep_angle_r = 2.0 * M_PI;
-    }
-    /* Clockwise sweep direction */
-    else if ( side == FP_LEFT ) {
-        if ( a3 > a1 ) /* Wrapping past 180? */
-            sweep_angle_r = a1 + (2.0 * M_PI - a3);
-        else
-            sweep_angle_r = a1 - a3;
-    }
-    /* Counter-clockwise sweep direction */
-    else if ( side == FP_RIGHT ) {
-        if ( a3 > a1 ) /* Wrapping past 180? */
-            sweep_angle_r = a3 - a1;
-        else
-            sweep_angle_r = a3 + (2.0 * M_PI - a1);
-    }
+  /* We should always be able to find the center of a non-linear arc */
+  if ( arcCircleCenter(p1, p2, p3, &center, &radius) == MS_FAILURE )
+    return MS_FAILURE;
+
+  /* Calculate the angles that our three points represent */
+  a1 = atan2(p1->y - center.y, p1->x - center.x);
+  /* UNUSED
+  a2 = atan2(p2->y - center.y, p2->x - center.x);
+   */
+  a3 = atan2(p3->y - center.y, p3->x - center.x);
+  segment_angle_r = M_PI * segment_angle / 180.0;
+
+  /* Closed-circle case, we sweep the whole circle! */
+  if ( is_closed ) {
+    sweep_angle_r = 2.0 * M_PI;
+  }
+  /* Clockwise sweep direction */
+  else if ( side == FP_LEFT ) {
+    if ( a3 > a1 ) /* Wrapping past 180? */
+      sweep_angle_r = a1 + (2.0 * M_PI - a3);
     else
-        sweep_angle_r = 0.0;
-    
-	/* We don't have enough resolution, let's invert our strategy. */
-	if ( (sweep_angle_r / segment_angle_r) < SEGMENT_MINPOINTS )
-	{
-		segment_angle_r = sweep_angle_r / (SEGMENT_MINPOINTS + 1);
-	}
-
-    /* We don't have enough resolution to stroke this arc,
-    *  so just join the start to the end. */
-    if ( sweep_angle_r < segment_angle_r ) {
-        if ( include_first ) 
-            pointArrayAddPoint(pa, p1);
-        pointArrayAddPoint(pa, p3);
-        return MS_SUCCESS;
-    }
-    
-    /* How many edges to generate (we add the final edge
-    *  by sticking on the last point */
-    num_edges = floor(sweep_angle_r / fabs(segment_angle_r));
-
-    /* Go backwards (negative angular steps) if we are stroking clockwise */
-    if ( side == FP_LEFT )    
-        segment_angle_r *= -1;
-
-    /* What point should we start with? */
-    if( include_first ) {
-        current_angle_r = a1;
-    }
-    else {
-        current_angle_r = a1 + segment_angle_r;
-        num_edges--;
-    }
-
-    /* For each edge, increment or decrement by our segment angle */
-    for( i = 0; i < num_edges; i++ ) {
-        if (segment_angle_r > 0.0 && current_angle_r > M_PI) 
-            current_angle_r -= 2*M_PI;
-        if (segment_angle_r < 0.0 && current_angle_r < -1*M_PI) 
-            current_angle_r -= 2*M_PI;
-        p.x = center.x + radius*cos(current_angle_r);
-        p.y = center.y + radius*sin(current_angle_r);
-        pointArrayAddPoint(pa, &p);
-        current_angle_r += segment_angle_r;
-    }
-    
-    /* Add the last point */
+      sweep_angle_r = a1 - a3;
+  }
+  /* Counter-clockwise sweep direction */
+  else if ( side == FP_RIGHT ) {
+    if ( a3 > a1 ) /* Wrapping past 180? */
+      sweep_angle_r = a3 - a1;
+    else
+      sweep_angle_r = a3 + (2.0 * M_PI - a1);
+  } else
+    sweep_angle_r = 0.0;
+
+  /* We don't have enough resolution, let's invert our strategy. */
+  if ( (sweep_angle_r / segment_angle_r) < SEGMENT_MINPOINTS ) {
+    segment_angle_r = sweep_angle_r / (SEGMENT_MINPOINTS + 1);
+  }
+
+  /* We don't have enough resolution to stroke this arc,
+  *  so just join the start to the end. */
+  if ( sweep_angle_r < segment_angle_r ) {
+    if ( include_first )
+      pointArrayAddPoint(pa, p1);
     pointArrayAddPoint(pa, p3);
     return MS_SUCCESS;
+  }
+
+  /* How many edges to generate (we add the final edge
+  *  by sticking on the last point */
+  num_edges = floor(sweep_angle_r / fabs(segment_angle_r));
+
+  /* Go backwards (negative angular steps) if we are stroking clockwise */
+  if ( side == FP_LEFT )
+    segment_angle_r *= -1;
+
+  /* What point should we start with? */
+  if( include_first ) {
+    current_angle_r = a1;
+  } else {
+    current_angle_r = a1 + segment_angle_r;
+    num_edges--;
+  }
+
+  /* For each edge, increment or decrement by our segment angle */
+  for( i = 0; i < num_edges; i++ ) {
+    if (segment_angle_r > 0.0 && current_angle_r > M_PI)
+      current_angle_r -= 2*M_PI;
+    if (segment_angle_r < 0.0 && current_angle_r < -1*M_PI)
+      current_angle_r -= 2*M_PI;
+    p.x = center.x + radius*cos(current_angle_r);
+    p.y = center.y + radius*sin(current_angle_r);
+    pointArrayAddPoint(pa, &p);
+    current_angle_r += segment_angle_r;
+  }
+
+  /* Add the last point */
+  pointArrayAddPoint(pa, p3);
+  return MS_SUCCESS;
 }
 
 /*
 ** This function does not actually take WKB as input, it takes the
 ** WKB starting from the numpoints integer. Each three-point edge
 ** is stroked into a linestring and appended into the lineObj
-** argument. 
+** argument.
 */
-int 
+int
 arcStrokeCircularString(wkbObj *w, double segment_angle, lineObj *line)
 {
-    pointObj p1, p2, p3;
-    int npoints, nedges;
-    int edge = 0;
-    pointArrayObj *pa;
-    
-    if ( ! w || ! line ) return MS_FAILURE;
-    
-    npoints = wkbReadInt(w);
-    nedges = npoints / 2;    
-    
-    /* All CircularStrings have an odd number of points */
-    if ( npoints < 3 || npoints % 2 != 1 )
-        return MS_FAILURE;
+  pointObj p1, p2, p3;
+  int npoints, nedges;
+  int edge = 0;
+  pointArrayObj *pa;
+
+  if ( ! w || ! line ) return MS_FAILURE;
+
+  npoints = wkbReadInt(w);
+  nedges = npoints / 2;
+
+  /* All CircularStrings have an odd number of points */
+  if ( npoints < 3 || npoints % 2 != 1 )
+    return MS_FAILURE;
+
+  /* Make a large guess at how much space we'll need */
+  pa = pointArrayNew(nedges * 180 / segment_angle);
+
+  wkbReadPointP(w,&p3);
 
-    /* Make a large guess at how much space we'll need */
-    pa = pointArrayNew(nedges * 180 / segment_angle);
-    
+  /* Fill out the point array with stroked arcs */
+  while( edge < nedges ) {
+    p1 = p3;
+    wkbReadPointP(w,&p2);
     wkbReadPointP(w,&p3);
+    if ( arcStrokeCircle(&p1, &p2, &p3, segment_angle, edge ? 0 : 1, pa) == MS_FAILURE ) {
+      pointArrayFree(pa);
+      return MS_FAILURE;
+    }
+    edge++;
+  }
 
-    /* Fill out the point array with stroked arcs */
-    while( edge < nedges ) {
-        p1 = p3;
-        wkbReadPointP(w,&p2);
-        wkbReadPointP(w,&p3);
-        if ( arcStrokeCircle(&p1, &p2, &p3, segment_angle, edge ? 0 : 1, pa) == MS_FAILURE ) {
-            pointArrayFree(pa);
-            return MS_FAILURE;
-          }
-        edge++;
-    } 
-    
-    /* Copy the point array into the line */
-    line->numpoints = pa->npoints;
-    line->point = msSmallMalloc(line->numpoints * sizeof(pointObj));
-    memcpy(line->point, pa->data, line->numpoints * sizeof(pointObj));
-
-    /* Clean up */
-    pointArrayFree(pa);
-    
-    return MS_SUCCESS;
+  /* Copy the point array into the line */
+  line->numpoints = pa->npoints;
+  line->point = msSmallMalloc(line->numpoints * sizeof(pointObj));
+  memcpy(line->point, pa->data, line->numpoints * sizeof(pointObj));
+
+  /* Clean up */
+  pointArrayFree(pa);
+
+  return MS_SUCCESS;
 }
 
 
 /*
-** For LAYER types that are not the usual ones (charts, 
+** For LAYER types that are not the usual ones (charts,
 ** annotations, etc) we will convert to a shape type
 ** that "makes sense" given the WKB input. We do this
 ** by peaking at the type number of the first collection
 ** sub-element.
 */
-static int 
+static int
 msPostGISFindBestType(wkbObj *w, shapeObj *shape)
 {
-    int wkbtype;
+  int wkbtype;
 
-    /* What kind of geometry is this? */
-    wkbtype = wkbType(w);
-    
-    /* Generic collection, we need to look a little deeper. */
-    if ( wkbtype == WKB_GEOMETRYCOLLECTION )
-        wkbtype = wkbCollectionSubType(w);
+  /* What kind of geometry is this? */
+  wkbtype = wkbType(w);
 
-    switch ( wkbtype ) {
+  /* Generic collection, we need to look a little deeper. */
+  if ( wkbtype == WKB_GEOMETRYCOLLECTION )
+    wkbtype = wkbCollectionSubType(w);
+
+  switch ( wkbtype ) {
     case WKB_POLYGON:
     case WKB_CURVEPOLYGON:
     case WKB_MULTIPOLYGON:
-        shape->type = MS_SHAPE_POLYGON;
-        break;
+      shape->type = MS_SHAPE_POLYGON;
+      break;
     case WKB_LINESTRING:
     case WKB_CIRCULARSTRING:
     case WKB_COMPOUNDCURVE:
     case WKB_MULTICURVE:
     case WKB_MULTILINESTRING:
-        shape->type = MS_SHAPE_LINE;
-        break;
+      shape->type = MS_SHAPE_LINE;
+      break;
     case WKB_POINT:
     case WKB_MULTIPOINT:
-        shape->type = MS_SHAPE_POINT;
-        break;
+      shape->type = MS_SHAPE_POINT;
+      break;
     default:
-        return MS_FAILURE;
-    }
+      return MS_FAILURE;
+  }
 
-    return wkbConvGeometryToShape(w, shape);
+  return wkbConvGeometryToShape(w, shape);
 }
 
 /*
-** Recent versions of PgSQL provide the version as an int in a 
+** Recent versions of PgSQL provide the version as an int in a
 ** simple call to the connection handle. For earlier ones we have
 ** to parse the version string into a usable number.
 */
-static int 
-msPostGISRetrievePgVersion(PGconn *pgconn) {
-#ifndef POSTGIS_HAS_SERVER_VERSION 
-    int pgVersion = 0; 
-    char *strVersion = NULL; 
-    char *strParts[3] = { NULL, NULL, NULL }; 
-    int i = 0, j = 0, len = 0; 
-    int factor = 10000; 
- 
-    if (pgconn == NULL) { 
-        msSetError(MS_QUERYERR, "Layer does not have a postgis connection.", "msPostGISRetrievePgVersion()"); 
-        return MS_FAILURE; 
-    } 
-
-    if (! PQparameterStatus(pgconn, "server_version") )
-        return MS_FAILURE; 
- 
-    strVersion = msStrdup(PQparameterStatus(pgconn, "server_version"));
-    if( ! strVersion ) 
-        return MS_FAILURE; 
-
-    strParts[j] = strVersion; 
-    j++; 
-    len = strlen(strVersion); 
-    for( i = 0; i < len; i++ ) { 
-        if( strVersion[i] == '.' ) { 
-            strVersion[i] = '\0'; 
- 
-            if( j < 3 ) { 
-                strParts[j] = strVersion + i + 1; 
-                j++; 
-            } 
-            else { 
-                free(strVersion); 
-                msSetError(MS_QUERYERR, "Too many parts in version string.", "msPostGISRetrievePgVersion()"); 
-                return MS_FAILURE; 
-            } 
-        } 
-    } 
-     
-    for( j = 0; j < 3 && strParts[j]; j++ ) { 
-        pgVersion += factor * atoi(strParts[j]); 
-        factor = factor / 100; 
-    } 
-    free(strVersion); 
-    return pgVersion; 
-#else 
-    return PQserverVersion(pgconn); 
-#endif 
-} 
+static int
+msPostGISRetrievePgVersion(PGconn *pgconn)
+{
+#ifndef POSTGIS_HAS_SERVER_VERSION
+  int pgVersion = 0;
+  char *strVersion = NULL;
+  char *strParts[3] = { NULL, NULL, NULL };
+  int i = 0, j = 0, len = 0;
+  int factor = 10000;
+
+  if (pgconn == NULL) {
+    msSetError(MS_QUERYERR, "Layer does not have a postgis connection.", "msPostGISRetrievePgVersion()");
+    return MS_FAILURE;
+  }
+
+  if (! PQparameterStatus(pgconn, "server_version") )
+    return MS_FAILURE;
+
+  strVersion = msStrdup(PQparameterStatus(pgconn, "server_version"));
+  if( ! strVersion )
+    return MS_FAILURE;
+
+  strParts[j] = strVersion;
+  j++;
+  len = strlen(strVersion);
+  for( i = 0; i < len; i++ ) {
+    if( strVersion[i] == '.' ) {
+      strVersion[i] = '\0';
+
+      if( j < 3 ) {
+        strParts[j] = strVersion + i + 1;
+        j++;
+      } else {
+        free(strVersion);
+        msSetError(MS_QUERYERR, "Too many parts in version string.", "msPostGISRetrievePgVersion()");
+        return MS_FAILURE;
+      }
+    }
+  }
+
+  for( j = 0; j < 3 && strParts[j]; j++ ) {
+    pgVersion += factor * atoi(strParts[j]);
+    factor = factor / 100;
+  }
+  free(strVersion);
+  return pgVersion;
+#else
+  return PQserverVersion(pgconn);
+#endif
+}
 
 /*
-** Get the PostGIS version number from the database as integer. 
+** Get the PostGIS version number from the database as integer.
 ** Versions are multiplied out as with PgSQL: 1.5.2 -> 10502, 2.0.0 -> 20000.
 */
-static int 
-msPostGISRetrieveVersion(PGconn *pgconn) { 
-    static char* sql = "SELECT postgis_version()";
-    int version = 0; 
-    size_t strSize;
-    char *strVersion = NULL;
-    char *ptr;
-    char *strParts[3] = { NULL, NULL, NULL }; 
-    int i = 0, j = 0; 
-    int factor = 10000; 
-    PGresult *pgresult = NULL;
- 
-    if ( ! pgconn ) { 
-        msSetError(MS_QUERYERR, "No open connection.", "msPostGISRetrieveVersion()"); 
-        return MS_FAILURE; 
-    } 
-
-    pgresult = PQexecParams(pgconn, sql,0, NULL, NULL, NULL, NULL, 0);
-
-    if ( !pgresult || PQresultStatus(pgresult) != PGRES_TUPLES_OK) {
-        msSetError(MS_QUERYERR, "Error executing SQL: %s", "msPostGISRetrieveVersion()", sql);
-        return MS_FAILURE;
-    }
+static int
+msPostGISRetrieveVersion(PGconn *pgconn)
+{
+  static char* sql = "SELECT postgis_version()";
+  int version = 0;
+  size_t strSize;
+  char *strVersion = NULL;
+  char *ptr;
+  char *strParts[3] = { NULL, NULL, NULL };
+  int i = 0, j = 0;
+  int factor = 10000;
+  PGresult *pgresult = NULL;
+
+  if ( ! pgconn ) {
+    msSetError(MS_QUERYERR, "No open connection.", "msPostGISRetrieveVersion()");
+    return MS_FAILURE;
+  }
 
-    if (PQgetisnull(pgresult, 0, 0)) {
-        PQclear(pgresult);
-        msSetError(MS_QUERYERR,"Null result returned.","msPostGISRetrieveVersion()");
-        return MS_FAILURE;
-    }
+  pgresult = PQexecParams(pgconn, sql,0, NULL, NULL, NULL, NULL, 0);
+
+  if ( !pgresult || PQresultStatus(pgresult) != PGRES_TUPLES_OK) {
+    msSetError(MS_QUERYERR, "Error executing SQL: %s", "msPostGISRetrieveVersion()", sql);
+    return MS_FAILURE;
+  }
 
-    strSize = PQgetlength(pgresult, 0, 0) + 1;
-    strVersion = (char*)msSmallMalloc(strSize);
-    strlcpy(strVersion, PQgetvalue(pgresult, 0, 0), strSize);
+  if (PQgetisnull(pgresult, 0, 0)) {
     PQclear(pgresult);
+    msSetError(MS_QUERYERR,"Null result returned.","msPostGISRetrieveVersion()");
+    return MS_FAILURE;
+  }
 
-    ptr = strVersion;
-    strParts[j++] = strVersion;
-    while( ptr != '\0' && j < 3 ) {
-        if ( *ptr == '.' ) {
-            *ptr = '\0';
-            strParts[j++] = ptr + 1;
-        }
-        if ( *ptr == ' ' ) {
-            *ptr = '\0';
-            break;
-        }
-        ptr++;
+  strSize = PQgetlength(pgresult, 0, 0) + 1;
+  strVersion = (char*)msSmallMalloc(strSize);
+  strlcpy(strVersion, PQgetvalue(pgresult, 0, 0), strSize);
+  PQclear(pgresult);
+
+  ptr = strVersion;
+  strParts[j++] = strVersion;
+  while( ptr != '\0' && j < 3 ) {
+    if ( *ptr == '.' ) {
+      *ptr = '\0';
+      strParts[j++] = ptr + 1;
+    }
+    if ( *ptr == ' ' ) {
+      *ptr = '\0';
+      break;
     }
-    
-    for( i = 0; i < j; i++ ) { 
-        version += factor * atoi(strParts[i]); 
-        factor = factor / 100; 
-    } 
-    free(strVersion); 
+    ptr++;
+  }
+
+  for( i = 0; i < j; i++ ) {
+    version += factor * atoi(strParts[i]);
+    factor = factor / 100;
+  }
+  free(strVersion);
 
-    return version; 
-} 
+  return version;
+}
 
 /*
 ** msPostGISRetrievePK()
@@ -1072,147 +1099,148 @@ msPostGISRetrieveVersion(PGconn *pgconn) {
 ** The layerinfo->fromsource must already be populated and
 ** must not be a subquery.
 */
-static int 
-msPostGISRetrievePK(layerObj *layer) {
-    PGresult *pgresult = NULL;
-    char *sql = 0;
-    size_t size;
-    msPostGISLayerInfo *layerinfo = 0;
-    int length;
-    int pgVersion;
-    char *pos_sep;
-    char *schema = NULL;
-    char *table = NULL;
-
-    if (layer->debug) {
-        msDebug("msPostGISRetrievePK called.\n");
-    }
+static int
+msPostGISRetrievePK(layerObj *layer)
+{
+  PGresult *pgresult = NULL;
+  char *sql = 0;
+  size_t size;
+  msPostGISLayerInfo *layerinfo = 0;
+  int length;
+  int pgVersion;
+  char *pos_sep;
+  char *schema = NULL;
+  char *table = NULL;
+
+  if (layer->debug) {
+    msDebug("msPostGISRetrievePK called.\n");
+  }
 
-    layerinfo = (msPostGISLayerInfo *) layer->layerinfo;
+  layerinfo = (msPostGISLayerInfo *) layer->layerinfo;
 
-    /* Attempt to separate fromsource into schema.table */
-    pos_sep = strstr(layerinfo->fromsource, ".");
-    if (pos_sep) {
-        length = strlen(layerinfo->fromsource) - strlen(pos_sep) + 1;
-        schema = (char*)msSmallMalloc(length);
-        strlcpy(schema, layerinfo->fromsource, length);
+  /* Attempt to separate fromsource into schema.table */
+  pos_sep = strstr(layerinfo->fromsource, ".");
+  if (pos_sep) {
+    length = strlen(layerinfo->fromsource) - strlen(pos_sep) + 1;
+    schema = (char*)msSmallMalloc(length);
+    strlcpy(schema, layerinfo->fromsource, length);
 
-        length = strlen(pos_sep);
-        table = (char*)msSmallMalloc(length);
-        strlcpy(table, pos_sep + 1, length);
+    length = strlen(pos_sep);
+    table = (char*)msSmallMalloc(length);
+    strlcpy(table, pos_sep + 1, length);
 
-        if (layer->debug) {
-            msDebug("msPostGISRetrievePK(): Found schema %s, table %s.\n", schema, table);
-        }
+    if (layer->debug) {
+      msDebug("msPostGISRetrievePK(): Found schema %s, table %s.\n", schema, table);
     }
+  }
 
-    if (layerinfo->pgconn == NULL) {
-        msSetError(MS_QUERYERR, "Layer does not have a postgis connection.", "msPostGISRetrievePK()");
-        return MS_FAILURE;
-    }
-    pgVersion = msPostGISRetrievePgVersion(layerinfo->pgconn);
+  if (layerinfo->pgconn == NULL) {
+    msSetError(MS_QUERYERR, "Layer does not have a postgis connection.", "msPostGISRetrievePK()");
+    return MS_FAILURE;
+  }
+  pgVersion = msPostGISRetrievePgVersion(layerinfo->pgconn);
 
-    if (pgVersion < 70000) {
-        if (layer->debug) {
-            msDebug("msPostGISRetrievePK(): Major version below 7.\n");
-        }
-        return MS_FAILURE;
+  if (pgVersion < 70000) {
+    if (layer->debug) {
+      msDebug("msPostGISRetrievePK(): Major version below 7.\n");
     }
-    if (pgVersion < 70200) {
-        if (layer->debug) {
-            msDebug("msPostGISRetrievePK(): Version below 7.2.\n");
-        }
-        return MS_FAILURE;
+    return MS_FAILURE;
+  }
+  if (pgVersion < 70200) {
+    if (layer->debug) {
+      msDebug("msPostGISRetrievePK(): Version below 7.2.\n");
     }
-    if (pgVersion < 70300) {
-        /*
-        ** PostgreSQL v7.2 has a different representation of primary keys that
-        ** later versions.  This currently does not explicitly exclude
-        ** multicolumn primary keys.
-        */
-        static char *v72sql = "select b.attname from pg_class as a, pg_attribute as b, (select oid from pg_class where relname = '%s') as c, pg_index as d where d.indexrelid = a.oid and d.indrelid = c.oid and d.indisprimary and b.attrelid = a.oid and a.relnatts = 1";
-        sql = msSmallMalloc(strlen(layerinfo->fromsource) + strlen(v72sql));
-        sprintf(sql, v72sql, layerinfo->fromsource);
+    return MS_FAILURE;
+  }
+  if (pgVersion < 70300) {
+    /*
+    ** PostgreSQL v7.2 has a different representation of primary keys that
+    ** later versions.  This currently does not explicitly exclude
+    ** multicolumn primary keys.
+    */
+    static char *v72sql = "select b.attname from pg_class as a, pg_attribute as b, (select oid from pg_class where relname = '%s') as c, pg_index as d where d.indexrelid = a.oid and d.indrelid = c.oid and d.indisprimary and b.attrelid = a.oid and a.relnatts = 1";
+    sql = msSmallMalloc(strlen(layerinfo->fromsource) + strlen(v72sql));
+    sprintf(sql, v72sql, layerinfo->fromsource);
+  } else {
+    /*
+    ** PostgreSQL v7.3 and later treat primary keys as constraints.
+    ** We only support single column primary keys, so multicolumn
+    ** pks are explicitly excluded from the query.
+    */
+    if (schema && table) {
+      static char *v73sql = "select attname from pg_attribute, pg_constraint, pg_class, pg_namespace where pg_constraint.conrelid = pg_class.oid and pg_class.oid = pg_attribute.attrelid and pg_constraint.contype = 'p' and pg_constraint.conkey[1] = pg_attribute.attnum and pg_class.relname = '%s' and pg_class.relnamespace = pg_namespace.oid and pg_namespace.nspname = '%s' and pg_constraint.conkey[2] is null";
+      sql = msSmallMalloc(strlen(schema) + strlen(table) + strlen(v73sql));
+      sprintf(sql, v73sql, table, schema);
+      free(table);
+      free(schema);
     } else {
-        /*
-        ** PostgreSQL v7.3 and later treat primary keys as constraints.
-        ** We only support single column primary keys, so multicolumn
-        ** pks are explicitly excluded from the query.
-        */
-        if (schema && table) {
-            static char *v73sql = "select attname from pg_attribute, pg_constraint, pg_class, pg_namespace where pg_constraint.conrelid = pg_class.oid and pg_class.oid = pg_attribute.attrelid and pg_constraint.contype = 'p' and pg_constraint.conkey[1] = pg_attribute.attnum and pg_class.relname = '%s' and pg_class.relnamespace = pg_namespace.oid and pg_namespace.nspname = '%s' and pg_constraint.conkey[2] is null";
-            sql = msSmallMalloc(strlen(schema) + strlen(table) + strlen(v73sql));
-            sprintf(sql, v73sql, table, schema);
-            free(table);
-            free(schema);
-        } else {
-            static char *v73sql = "select attname from pg_attribute, pg_constraint, pg_class where pg_constraint.conrelid = pg_class.oid and pg_class.oid = pg_attribute.attrelid and pg_constraint.contype = 'p' and pg_constraint.conkey[1] = pg_attribute.attnum and pg_class.relname = '%s' and pg_table_is_visible(pg_class.oid) and pg_constraint.conkey[2] is null";
-            sql = msSmallMalloc(strlen(layerinfo->fromsource) + strlen(v73sql));
-            sprintf(sql, v73sql, layerinfo->fromsource);
-        }
-    }
-
-    if (layer->debug > 1) {
-        msDebug("msPostGISRetrievePK: %s\n", sql);
+      static char *v73sql = "select attname from pg_attribute, pg_constraint, pg_class where pg_constraint.conrelid = pg_class.oid and pg_class.oid = pg_attribute.attrelid and pg_constraint.contype = 'p' and pg_constraint.conkey[1] = pg_attribute.attnum and pg_class.relname = '%s' and pg_table_is_visible(pg_class.oid) and pg_constraint.conkey[2] is null";
+      sql = msSmallMalloc(strlen(layerinfo->fromsource) + strlen(v73sql));
+      sprintf(sql, v73sql, layerinfo->fromsource);
     }
+  }
 
-    layerinfo = (msPostGISLayerInfo *) layer->layerinfo;
+  if (layer->debug > 1) {
+    msDebug("msPostGISRetrievePK: %s\n", sql);
+  }
 
-    if (layerinfo->pgconn == NULL) {
-        msSetError(MS_QUERYERR, "Layer does not have a postgis connection.", "msPostGISRetrievePK()");
-        free(sql);
-        return MS_FAILURE;
-    }
+  layerinfo = (msPostGISLayerInfo *) layer->layerinfo;
 
-    pgresult = PQexecParams(layerinfo->pgconn, sql, 0, NULL, NULL, NULL, NULL, 0);
-    if ( !pgresult || PQresultStatus(pgresult) != PGRES_TUPLES_OK) {
-        static char *tmp1 = "Error executing SQL: ";
-        char *tmp2 = NULL;
-        size_t size2;
+  if (layerinfo->pgconn == NULL) {
+    msSetError(MS_QUERYERR, "Layer does not have a postgis connection.", "msPostGISRetrievePK()");
+    free(sql);
+    return MS_FAILURE;
+  }
 
-        size2 = sizeof(char)*(strlen(tmp1) + strlen(sql) + 1);
-        tmp2 = (char*)msSmallMalloc(size2);
-        strlcpy(tmp2, tmp1, size2);
-        strlcat(tmp2, sql, size2);
-        msSetError(MS_QUERYERR, tmp2, "msPostGISRetrievePK()");
-        free(tmp2);
-        free(sql);
-        return MS_FAILURE;
-    }
+  pgresult = PQexecParams(layerinfo->pgconn, sql, 0, NULL, NULL, NULL, NULL, 0);
+  if ( !pgresult || PQresultStatus(pgresult) != PGRES_TUPLES_OK) {
+    static char *tmp1 = "Error executing SQL: ";
+    char *tmp2 = NULL;
+    size_t size2;
+
+    size2 = sizeof(char)*(strlen(tmp1) + strlen(sql) + 1);
+    tmp2 = (char*)msSmallMalloc(size2);
+    strlcpy(tmp2, tmp1, size2);
+    strlcat(tmp2, sql, size2);
+    msSetError(MS_QUERYERR, tmp2, "msPostGISRetrievePK()");
+    free(tmp2);
+    free(sql);
+    return MS_FAILURE;
+  }
 
-    if (PQntuples(pgresult) < 1) {
-        if (layer->debug) {
-            msDebug("msPostGISRetrievePK: No results found.\n");
-        }
-        PQclear(pgresult);
-        free(sql);
-        return MS_FAILURE;
+  if (PQntuples(pgresult) < 1) {
+    if (layer->debug) {
+      msDebug("msPostGISRetrievePK: No results found.\n");
     }
-    if (PQntuples(pgresult) > 1) {
-        if (layer->debug) {
-            msDebug("msPostGISRetrievePK: Multiple results found.\n");
-        }
-        PQclear(pgresult);
-        free(sql);
-        return MS_FAILURE;
+    PQclear(pgresult);
+    free(sql);
+    return MS_FAILURE;
+  }
+  if (PQntuples(pgresult) > 1) {
+    if (layer->debug) {
+      msDebug("msPostGISRetrievePK: Multiple results found.\n");
     }
+    PQclear(pgresult);
+    free(sql);
+    return MS_FAILURE;
+  }
 
-    if (PQgetisnull(pgresult, 0, 0)) {
-        if (layer->debug) {
-            msDebug("msPostGISRetrievePK: Null result returned.\n");
-        }
-        PQclear(pgresult);
-        free(sql);
-        return MS_FAILURE;
+  if (PQgetisnull(pgresult, 0, 0)) {
+    if (layer->debug) {
+      msDebug("msPostGISRetrievePK: Null result returned.\n");
     }
-
-    size = PQgetlength(pgresult, 0, 0) + 1;
-    layerinfo->uid = (char*)msSmallMalloc(size);
-    strlcpy(layerinfo->uid, PQgetvalue(pgresult, 0, 0), size);
-
     PQclear(pgresult);
     free(sql);
-    return MS_SUCCESS;
+    return MS_FAILURE;
+  }
+
+  size = PQgetlength(pgresult, 0, 0) + 1;
+  layerinfo->uid = (char*)msSmallMalloc(size);
+  strlcpy(layerinfo->uid, PQgetvalue(pgresult, 0, 0), size);
+
+  PQclear(pgresult);
+  free(sql);
+  return MS_SUCCESS;
 }
 
 
@@ -1222,144 +1250,152 @@ msPostGISRetrievePK(layerObj *layer) {
 ** Parse the DATA string for geometry column name, table name,
 ** unique id column, srid, and SQL string.
 */
-int msPostGISParseData(layerObj *layer) {
-    char *pos_opt, *pos_scn, *tmp, *pos_srid, *pos_uid, *data;
-    int slength;
-    msPostGISLayerInfo *layerinfo;
+int msPostGISParseData(layerObj *layer)
+{
+  char *pos_opt, *pos_scn, *tmp, *pos_srid, *pos_uid, *pos_geom, *data;
+  int slength;
+  msPostGISLayerInfo *layerinfo;
 
-    assert(layer != NULL);
-    assert(layer->layerinfo != NULL);
+  assert(layer != NULL);
+  assert(layer->layerinfo != NULL);
 
-    layerinfo = (msPostGISLayerInfo*)(layer->layerinfo);
+  layerinfo = (msPostGISLayerInfo*)(layer->layerinfo);
 
-    if (layer->debug) {
-        msDebug("msPostGISParseData called.\n");
-    }
+  if (layer->debug) {
+    msDebug("msPostGISParseData called.\n");
+  }
 
-    if (!layer->data) {
-        msSetError(MS_QUERYERR, "Missing DATA clause. DATA statement must contain 'geometry_column from table_name' or 'geometry_column from (sub-query) as sub'.", "msPostGISParseData()");
-        return MS_FAILURE;
-    }
-    data = layer->data;
+  if (!layer->data) {
+    msSetError(MS_QUERYERR, "Missing DATA clause. DATA statement must contain 'geometry_column from table_name' or 'geometry_column from (sub-query) as sub'.", "msPostGISParseData()");
+    return MS_FAILURE;
+  }
+  data = layer->data;
 
-    /*
-    ** Clean up any existing strings first, as we will be populating these fields.
-    */
-    if( layerinfo->srid ) {
-        free(layerinfo->srid);
-        layerinfo->srid = NULL;
-    }
-    if( layerinfo->uid ) {
-        free(layerinfo->uid);
-        layerinfo->uid = NULL;
-    }
-    if( layerinfo->geomcolumn ) {
-        free(layerinfo->geomcolumn);
-        layerinfo->geomcolumn = NULL;
-    }
-    if( layerinfo->fromsource ) {
-        free(layerinfo->fromsource);
-        layerinfo->fromsource = NULL;
-    }
-    
-    /*
-    ** Look for the optional ' using unique ID' string first.
-    */
-    pos_uid = strcasestr(data, " using unique ");
-    if (pos_uid) {
-        /* Find the end of this case 'using unique ftab_id using srid=33' */
-        tmp = strstr(pos_uid + 14, " ");
-        /* Find the end of this case 'using srid=33 using unique ftab_id' */
-        if (!tmp) {
-            tmp = pos_uid + strlen(pos_uid);
-        }
-        layerinfo->uid = (char*) msSmallMalloc((tmp - (pos_uid + 14)) + 1);
-        strlcpy(layerinfo->uid, pos_uid + 14, tmp - (pos_uid + 14)+1);
-        msStringTrim(layerinfo->uid);
-    }
+  /*
+  ** Clean up any existing strings first, as we will be populating these fields.
+  */
+  if( layerinfo->srid ) {
+    free(layerinfo->srid);
+    layerinfo->srid = NULL;
+  }
+  if( layerinfo->uid ) {
+    free(layerinfo->uid);
+    layerinfo->uid = NULL;
+  }
+  if( layerinfo->geomcolumn ) {
+    free(layerinfo->geomcolumn);
+    layerinfo->geomcolumn = NULL;
+  }
+  if( layerinfo->fromsource ) {
+    free(layerinfo->fromsource);
+    layerinfo->fromsource = NULL;
+  }
 
-    /*
-    ** Look for the optional ' using srid=333 ' string next.
-    */
-    pos_srid = strcasestr(data, " using srid=");
-    if (!pos_srid) {
-        layerinfo->srid = (char*) msSmallMalloc(1);
-        (layerinfo->srid)[0] = '\0'; /* no SRID, so return just null terminator*/
+  /*
+  ** Look for the optional ' using unique ID' string first.
+  */
+  pos_uid = strcasestr(data, " using unique ");
+  if (pos_uid) {
+    /* Find the end of this case 'using unique ftab_id using srid=33' */
+    tmp = strstr(pos_uid + 14, " ");
+    /* Find the end of this case 'using srid=33 using unique ftab_id' */
+    if (!tmp) {
+      tmp = pos_uid + strlen(pos_uid);
+    }
+    layerinfo->uid = (char*) msSmallMalloc((tmp - (pos_uid + 14)) + 1);
+    strlcpy(layerinfo->uid, pos_uid + 14, tmp - (pos_uid + 14)+1);
+    msStringTrim(layerinfo->uid);
+  }
+
+  /*
+  ** Look for the optional ' using srid=333 ' string next.
+  */
+  pos_srid = strcasestr(data, " using srid=");
+  if (!pos_srid) {
+    layerinfo->srid = (char*) msSmallMalloc(1);
+    (layerinfo->srid)[0] = '\0'; /* no SRID, so return just null terminator*/
+  } else {
+    slength = strspn(pos_srid + 12, "-0123456789");
+    if (!slength) {
+      msSetError(MS_QUERYERR, "Error parsing PostGIS DATA variable. You specified 'USING SRID' but didnt have any numbers! %s", "msPostGISParseData()", data);
+      return MS_FAILURE;
     } else {
-        slength = strspn(pos_srid + 12, "-0123456789");
-        if (!slength) {
-            msSetError(MS_QUERYERR, "Error parsing PostGIS DATA variable. You specified 'USING SRID' but didnt have any numbers! %s", "msPostGISParseData()", data);
-            return MS_FAILURE;
-        } else {
-            layerinfo->srid = (char*) msSmallMalloc(slength + 1);
-            strlcpy(layerinfo->srid, pos_srid + 12, slength+1);
-            msStringTrim(layerinfo->srid);
-        }
+      layerinfo->srid = (char*) msSmallMalloc(slength + 1);
+      strlcpy(layerinfo->srid, pos_srid + 12, slength+1);
+      msStringTrim(layerinfo->srid);
     }
+  }
 
-    /*
-    ** This is a little hack so the rest of the code works. 
-    ** pos_opt should point to the start of the optional blocks.
-    **
-    ** If they are both set, return the smaller one. 
-    */
-    if (pos_srid && pos_uid) {
-        pos_opt = (pos_srid > pos_uid) ? pos_uid : pos_srid;
-    }
-    /* If one or none is set, return the larger one. */
-    else {
-        pos_opt = (pos_srid > pos_uid) ? pos_srid : pos_uid;
-    }
-    /* No pos_opt? Move it to the end of the string. */
-    if (!pos_opt) {
-        pos_opt = data + strlen(data);
-    }
+  /*
+  ** This is a little hack so the rest of the code works.
+  ** pos_opt should point to the start of the optional blocks.
+  **
+  ** If they are both set, return the smaller one.
+  */
+  if (pos_srid && pos_uid) {
+    pos_opt = (pos_srid > pos_uid) ? pos_uid : pos_srid;
+  }
+  /* If one or none is set, return the larger one. */
+  else {
+    pos_opt = (pos_srid > pos_uid) ? pos_srid : pos_uid;
+  }
+  /* No pos_opt? Move it to the end of the string. */
+  if (!pos_opt) {
+    pos_opt = data + strlen(data);
+  }
 
-    /*
-    ** Scan for the 'geometry from table' or 'geometry from () as foo' clause. 
-    */
-    pos_scn = strcasestr(data, " from ");
-    if (!pos_scn) {
-        msSetError(MS_QUERYERR, "Error parsing PostGIS DATA variable. Must contain 'geometry from table' or 'geometry from (subselect) as foo'. %s", "msPostGISParseData()", data);
-        return MS_FAILURE;
-    }
+  /*
+  ** Scan for the 'geometry from table' or 'geometry from () as foo' clause.
+  */
 
-    /* Copy the geometry column name */
-    layerinfo->geomcolumn = (char*) msSmallMalloc((pos_scn - data) + 1);
-    strlcpy(layerinfo->geomcolumn, data, pos_scn - data+1);
-    msStringTrim(layerinfo->geomcolumn);
+  /* Find the first non-white character to start from */
+  pos_geom = data;
+  while( *pos_geom == ' ' || *pos_geom == '\t' || *pos_geom == '\n' || *pos_geom == '\r' )
+    pos_geom++;
 
-    /* Copy the table name or sub-select clause */
-    layerinfo->fromsource = (char*) msSmallMalloc((pos_opt - (pos_scn + 6)) + 1);
-    strlcpy(layerinfo->fromsource, pos_scn + 6, pos_opt - (pos_scn + 6)+1);
-    msStringTrim(layerinfo->fromsource);
+  /* Find the end of the geom column name */
+  pos_scn = strcasestr(data, " from ");
+  if (!pos_scn) {
+    msSetError(MS_QUERYERR, "Error parsing PostGIS DATA variable. Must contain 'geometry from table' or 'geometry from (subselect) as foo'. %s", "msPostGISParseData()", data);
+    return MS_FAILURE;
+  }
 
-    /* Something is wrong, our goemetry column and table references are not there. */
-    if (strlen(layerinfo->fromsource) < 1 || strlen(layerinfo->geomcolumn) < 1) {
-        msSetError(MS_QUERYERR, "Error parsing PostGIS DATA variable.  Must contain 'geometry from table' or 'geometry from (subselect) as foo'. %s", "msPostGISParseData()", data);
-        return MS_FAILURE;
-    }
+  /* Copy the geometry column name */
+  layerinfo->geomcolumn = (char*) msSmallMalloc((pos_scn - pos_geom) + 1);
+  strlcpy(layerinfo->geomcolumn, pos_geom, pos_scn - pos_geom+1);
+  msStringTrim(layerinfo->geomcolumn);
 
-    /*
-    ** We didn't find a ' using unique ' in the DATA string so try and find a 
-    ** primary key on the table.
-    */
-    if ( ! (layerinfo->uid) ) {
-        if ( strstr(layerinfo->fromsource, " ") ) {
-            msSetError(MS_QUERYERR, "Error parsing PostGIS DATA variable.  You must specifiy 'using unique' when supplying a subselect in the data definition.", "msPostGISParseData()");
-            return MS_FAILURE;
-        }
-        if ( msPostGISRetrievePK(layer) != MS_SUCCESS ) {
-            /* No user specified unique id so we will use the PostgreSQL oid */
-            /* TODO: Deprecate this, oids are deprecated in PostgreSQL */
-            layerinfo->uid = msStrdup("oid");
-        }
-    }
+  /* Copy the table name or sub-select clause */
+  layerinfo->fromsource = (char*) msSmallMalloc((pos_opt - (pos_scn + 6)) + 1);
+  strlcpy(layerinfo->fromsource, pos_scn + 6, pos_opt - (pos_scn + 6)+1);
+  msStringTrim(layerinfo->fromsource);
 
-    if (layer->debug) {
-        msDebug("msPostGISParseData: unique_column=%s, srid=%s, geom_column_name=%s, table_name=%s\n", layerinfo->uid, layerinfo->srid, layerinfo->geomcolumn, layerinfo->fromsource);
+  /* Something is wrong, our goemetry column and table references are not there. */
+  if (strlen(layerinfo->fromsource) < 1 || strlen(layerinfo->geomcolumn) < 1) {
+    msSetError(MS_QUERYERR, "Error parsing PostGIS DATA variable.  Must contain 'geometry from table' or 'geometry from (subselect) as foo'. %s", "msPostGISParseData()", data);
+    return MS_FAILURE;
+  }
+
+  /*
+  ** We didn't find a ' using unique ' in the DATA string so try and find a
+  ** primary key on the table.
+  */
+  if ( ! (layerinfo->uid) ) {
+    if ( strstr(layerinfo->fromsource, " ") ) {
+      msSetError(MS_QUERYERR, "Error parsing PostGIS DATA variable.  You must specify 'using unique' when supplying a subselect in the data definition.", "msPostGISParseData()");
+      return MS_FAILURE;
     }
-    return MS_SUCCESS;
+    if ( msPostGISRetrievePK(layer) != MS_SUCCESS ) {
+      /* No user specified unique id so we will use the PostgreSQL oid */
+      /* TODO: Deprecate this, oids are deprecated in PostgreSQL */
+      layerinfo->uid = msStrdup("oid");
+    }
+  }
+
+  if (layer->debug) {
+    msDebug("msPostGISParseData: unique_column=%s, srid=%s, geom_column_name=%s, table_name=%s\n", layerinfo->uid, layerinfo->srid, layerinfo->geomcolumn, layerinfo->fromsource);
+  }
+  return MS_SUCCESS;
 }
 
 
@@ -1368,154 +1404,156 @@ int msPostGISParseData(layerObj *layer) {
 ** Decode a hex character.
 */
 static unsigned char msPostGISHexDecodeChar[256] = {
-    /* not Hex characters */
-    64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
-    64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
-    64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
-    /* 0-9 */
-    0,1,2,3,4,5,6,7,8,9,
-    /* not Hex characters */
-    64,64,64,64,64,64,64,
-    /* A-F */
-    10,11,12,13,14,15,
-    /* not Hex characters */
-    64,64,64,64,64,64,64,64,64,
-    64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
-    64,
-    /* a-f */
-    10,11,12,13,14,15,
-    64,64,64,64,64,64,64,64,64,
-    64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
-    /* not Hex characters (upper 128 characters) */
-    64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
-    64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
-    64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
-    64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
-    64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
-    64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
-    64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
-    64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64
-    };
+  /* not Hex characters */
+  64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
+  64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
+  64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
+  /* 0-9 */
+  0,1,2,3,4,5,6,7,8,9,
+  /* not Hex characters */
+  64,64,64,64,64,64,64,
+  /* A-F */
+  10,11,12,13,14,15,
+  /* not Hex characters */
+  64,64,64,64,64,64,64,64,64,
+  64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
+  64,
+  /* a-f */
+  10,11,12,13,14,15,
+  64,64,64,64,64,64,64,64,64,
+  64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
+  /* not Hex characters (upper 128 characters) */
+  64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
+  64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
+  64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
+  64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
+  64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
+  64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
+  64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
+  64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64
+};
 
 /*
-** Decode hex string "src" (null terminated) 
+** Decode hex string "src" (null terminated)
 ** into "dest" (not null terminated).
 ** Returns length of decoded array or 0 on failure.
 */
-int msPostGISHexDecode(unsigned char *dest, const char *src, int srclen) {
+int msPostGISHexDecode(unsigned char *dest, const char *src, int srclen)
+{
 
-    if (src && *src && (srclen % 2 == 0) ) {
+  if (src && *src && (srclen % 2 == 0) ) {
 
-        unsigned char *p = dest;
-        int i;
+    unsigned char *p = dest;
+    int i;
 
-        for ( i=0; i<srclen; i+=2 ) {
-            register unsigned char b1=0, b2=0;
-            register unsigned char c1 = src[i];
-            register unsigned char c2 = src[i + 1];
+    for ( i=0; i<srclen; i+=2 ) {
+      register unsigned char b1=0, b2=0;
+      register unsigned char c1 = src[i];
+      register unsigned char c2 = src[i + 1];
 
-            b1 = msPostGISHexDecodeChar[c1];
-            b2 = msPostGISHexDecodeChar[c2];
+      b1 = msPostGISHexDecodeChar[c1];
+      b2 = msPostGISHexDecodeChar[c2];
 
-            *p++ = (b1 << 4) | b2;
+      *p++ = (b1 << 4) | b2;
 
-        }
-        return(p-dest);
     }
-    return 0;
+    return(p-dest);
+  }
+  return 0;
 }
 
 /*
 ** Decode a base64 character.
 */
 static unsigned char msPostGISBase64DecodeChar[256] = {
-    /* not Base64 characters */
-    64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
-    64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
-    64,64,64,64,64,64,64,64,64,64,64,
-    /*  +  */
-    62,
-    /* not Base64 characters */
-    64,64,64,
-    /*  /  */
-    63,
-    /* 0-9 */
-    52,53,54,55,56,57,58,59,60,61,
-    /* not Base64 characters */
-    64,64,64,64,64,64,64,
-    /* A-Z */
-    0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,
-    /* not Base64 characters */
-    64,64,64,64,64,64,
-    /* a-z */
-    26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,
-    /* not Base64 characters */
-    64,64,64,64,64,
-    /* not Base64 characters (upper 128 characters) */
-    64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
-    64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
-    64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
-    64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
-    64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
-    64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
-    64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
-    64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64
-    };    
-    
+  /* not Base64 characters */
+  64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
+  64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
+  64,64,64,64,64,64,64,64,64,64,64,
+  /*  +  */
+  62,
+  /* not Base64 characters */
+  64,64,64,
+  /*  /  */
+  63,
+  /* 0-9 */
+  52,53,54,55,56,57,58,59,60,61,
+  /* not Base64 characters */
+  64,64,64,64,64,64,64,
+  /* A-Z */
+  0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,
+  /* not Base64 characters */
+  64,64,64,64,64,64,
+  /* a-z */
+  26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,
+  /* not Base64 characters */
+  64,64,64,64,64,
+  /* not Base64 characters (upper 128 characters) */
+  64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
+  64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
+  64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
+  64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
+  64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
+  64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
+  64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
+  64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64
+};
+
 /*
-** Decode base64 string "src" (null terminated) 
+** Decode base64 string "src" (null terminated)
 ** into "dest" (not null terminated).
 ** Returns length of decoded array or 0 on failure.
 */
-int msPostGISBase64Decode(unsigned char *dest, const char *src, int srclen) {
+int msPostGISBase64Decode(unsigned char *dest, const char *src, int srclen)
+{
 
-    if (src && *src) {
+  if (src && *src) {
 
-        unsigned char *p = dest;
-        int i, j, k;
-        unsigned char *buf = calloc(srclen + 1, sizeof(unsigned char));
+    unsigned char *p = dest;
+    int i, j, k;
+    unsigned char *buf = calloc(srclen + 1, sizeof(unsigned char));
 
-        /* Drop illegal chars first */
-        for (i=0, j=0; src[i]; i++) {
-            unsigned char c = src[i];
-            if ( (msPostGISBase64DecodeChar[c] != 64) || (c == '=') ) {
-                buf[j++] = c;
-            }
-        }
+    /* Drop illegal chars first */
+    for (i=0, j=0; src[i]; i++) {
+      unsigned char c = src[i];
+      if ( (msPostGISBase64DecodeChar[c] != 64) || (c == '=') ) {
+        buf[j++] = c;
+      }
+    }
 
-        for (k=0; k<j; k+=4) {
-            register unsigned char c1='A', c2='A', c3='A', c4='A';
-            register unsigned char b1=0, b2=0, b3=0, b4=0;
-
-            c1 = buf[k];
-
-            if (k+1<j) {
-                c2 = buf[k+1];
-            }
-            if (k+2<j) {
-                c3 = buf[k+2];
-            }
-            if (k+3<j) {
-                c4 = buf[k+3];
-            }
-
-            b1 = msPostGISBase64DecodeChar[c1];
-            b2 = msPostGISBase64DecodeChar[c2];
-            b3 = msPostGISBase64DecodeChar[c3];
-            b4 = msPostGISBase64DecodeChar[c4];
-
-            *p++=((b1<<2)|(b2>>4) );
-            if (c3 != '=') {
-                *p++=(((b2&0xf)<<4)|(b3>>2) );
-            }
-            if (c4 != '=') {
-                *p++=(((b3&0x3)<<6)|b4 );
-            }
-        }
-        free(buf);
-        return(p-dest);
+    for (k=0; k<j; k+=4) {
+      register unsigned char c1='A', c2='A', c3='A', c4='A';
+      register unsigned char b1=0, b2=0, b3=0, b4=0;
+
+      c1 = buf[k];
+
+      if (k+1<j) {
+        c2 = buf[k+1];
+      }
+      if (k+2<j) {
+        c3 = buf[k+2];
+      }
+      if (k+3<j) {
+        c4 = buf[k+3];
+      }
+
+      b1 = msPostGISBase64DecodeChar[c1];
+      b2 = msPostGISBase64DecodeChar[c2];
+      b3 = msPostGISBase64DecodeChar[c3];
+      b4 = msPostGISBase64DecodeChar[c4];
+
+      *p++=((b1<<2)|(b2>>4) );
+      if (c3 != '=') {
+        *p++=(((b2&0xf)<<4)|(b3>>2) );
+      }
+      if (c4 != '=') {
+        *p++=(((b3&0x3)<<6)|b4 );
+      }
     }
-    return 0;
+    free(buf);
+    return(p-dest);
+  }
+  return 0;
 }
 
 /*
@@ -1523,49 +1561,48 @@ int msPostGISBase64Decode(unsigned char *dest, const char *src, int srclen) {
 **
 ** Returns malloc'ed char* that must be freed by caller.
 */
-char *msPostGISBuildSQLBox(layerObj *layer, rectObj *rect, char *strSRID) {
+char *msPostGISBuildSQLBox(layerObj *layer, rectObj *rect, char *strSRID)
+{
 
-    char *strBox = NULL;
-    size_t sz;
+  char *strBox = NULL;
+  size_t sz;
 
-    if (layer->debug) {
-        msDebug("msPostGISBuildSQLBox called.\n");
-    }
-
-    if ( strSRID ) {
-        static char *strBoxTemplate = "ST_GeomFromText('POLYGON((%.15g %.15g,%.15g %.15g,%.15g %.15g,%.15g %.15g,%.15g %.15g))',%s)";
-        /* 10 doubles + 1 integer + template characters */
-        sz = 10 * 22 + strlen(strSRID) + strlen(strBoxTemplate);
-        strBox = (char*)msSmallMalloc(sz+1); /* add space for terminating NULL */
-        if ( sz <= snprintf(strBox, sz, strBoxTemplate,
-                rect->minx, rect->miny,
-                rect->minx, rect->maxy,
-                rect->maxx, rect->maxy,
-                rect->maxx, rect->miny,
-                rect->minx, rect->miny,
-                strSRID))
-            {
-                msSetError(MS_MISCERR,"Bounding box digits truncated.","msPostGISBuildSQLBox");
-                return NULL;
-            }
-        } else {
-            static char *strBoxTemplate = "ST_GeomFromText('POLYGON((%.15g %.15g,%.15g %.15g,%.15g %.15g,%.15g %.15g,%.15g %.15g))')";
-            /* 10 doubles + template characters */
-            sz = 10 * 22 + strlen(strBoxTemplate);
-            strBox = (char*)msSmallMalloc(sz+1); /* add space for terminating NULL */
-            if ( sz <= snprintf(strBox, sz, strBoxTemplate,
-                    rect->minx, rect->miny,
-                    rect->minx, rect->maxy,
-                    rect->maxx, rect->maxy,
-                    rect->maxx, rect->miny,
-                    rect->minx, rect->miny) )
-            {
-                msSetError(MS_MISCERR,"Bounding box digits truncated.","msPostGISBuildSQLBox");
-                return NULL;
-            }
-        }
+  if (layer->debug) {
+    msDebug("msPostGISBuildSQLBox called.\n");
+  }
+
+  if ( strSRID ) {
+    static char *strBoxTemplate = "ST_GeomFromText('POLYGON((%.15g %.15g,%.15g %.15g,%.15g %.15g,%.15g %.15g,%.15g %.15g))',%s)";
+    /* 10 doubles + 1 integer + template characters */
+    sz = 10 * 22 + strlen(strSRID) + strlen(strBoxTemplate);
+    strBox = (char*)msSmallMalloc(sz+1); /* add space for terminating NULL */
+    if ( sz <= snprintf(strBox, sz, strBoxTemplate,
+                        rect->minx, rect->miny,
+                        rect->minx, rect->maxy,
+                        rect->maxx, rect->maxy,
+                        rect->maxx, rect->miny,
+                        rect->minx, rect->miny,
+                        strSRID)) {
+      msSetError(MS_MISCERR,"Bounding box digits truncated.","msPostGISBuildSQLBox");
+      return NULL;
+    }
+  } else {
+    static char *strBoxTemplate = "ST_GeomFromText('POLYGON((%.15g %.15g,%.15g %.15g,%.15g %.15g,%.15g %.15g,%.15g %.15g))')";
+    /* 10 doubles + template characters */
+    sz = 10 * 22 + strlen(strBoxTemplate);
+    strBox = (char*)msSmallMalloc(sz+1); /* add space for terminating NULL */
+    if ( sz <= snprintf(strBox, sz, strBoxTemplate,
+                        rect->minx, rect->miny,
+                        rect->minx, rect->maxy,
+                        rect->maxx, rect->maxy,
+                        rect->maxx, rect->miny,
+                        rect->minx, rect->miny) ) {
+      msSetError(MS_MISCERR,"Bounding box digits truncated.","msPostGISBuildSQLBox");
+      return NULL;
+    }
+  }
 
-    return strBox;
+  return strBox;
 
 }
 
@@ -1575,84 +1612,85 @@ char *msPostGISBuildSQLBox(layerObj *layer, rectObj *rect, char *strSRID) {
 **
 ** Returns malloc'ed char* that must be freed by caller.
 */
-char *msPostGISBuildSQLItems(layerObj *layer) {
+char *msPostGISBuildSQLItems(layerObj *layer)
+{
 
-    char *strEndian = NULL;
-    char *strGeom = NULL;
-    char *strItems = NULL;
-    msPostGISLayerInfo *layerinfo = NULL;
+  char *strEndian = NULL;
+  char *strGeom = NULL;
+  char *strItems = NULL;
+  msPostGISLayerInfo *layerinfo = NULL;
 
-    if (layer->debug) {
-        msDebug("msPostGISBuildSQLItems called.\n");
-    }
+  if (layer->debug) {
+    msDebug("msPostGISBuildSQLItems called.\n");
+  }
 
-    assert( layer->layerinfo != NULL);
+  assert( layer->layerinfo != NULL);
 
-    layerinfo = (msPostGISLayerInfo *)layer->layerinfo;
+  layerinfo = (msPostGISLayerInfo *)layer->layerinfo;
 
-    if ( ! layerinfo->geomcolumn ) {
-        msSetError(MS_MISCERR, "layerinfo->geomcolumn is not initialized.", "msPostGISBuildSQLItems()");
-        return NULL;
-    }
+  if ( ! layerinfo->geomcolumn ) {
+    msSetError(MS_MISCERR, "layerinfo->geomcolumn is not initialized.", "msPostGISBuildSQLItems()");
+    return NULL;
+  }
+
+  /*
+  ** Get the server to transform the geometry into our
+  ** native endian before transmitting it to us..
+  */
+  if (layerinfo->endian == LITTLE_ENDIAN) {
+    strEndian = "NDR";
+  } else {
+    strEndian = "XDR";
+  }
 
+  {
     /*
-    ** Get the server to transform the geometry into our
-    ** native endian before transmitting it to us..
+    ** We transfer the geometry from server to client as a
+    ** hex or base64 encoded WKB byte-array. We will have to decode this
+    ** data once we get it. Forcing to 2D (via the AsBinary function
+    ** which includes a 2D force in it) removes ordinates we don't
+    ** need, saving transfer and encode/decode time.
     */
-    if (layerinfo->endian == LITTLE_ENDIAN) {
-        strEndian = "NDR";
-    } else {
-        strEndian = "XDR";
-    }
-
-    {
-        /*
-        ** We transfer the geometry from server to client as a
-        ** hex or base64 encoded WKB byte-array. We will have to decode this
-        ** data once we get it. Forcing to 2D (via the AsBinary function
-        ** which includes a 2D force in it) removes ordinates we don't
-        ** need, saving transfer and encode/decode time. 
-        */
 #if TRANSFER_ENCODING == 64
-        static char *strGeomTemplate = "encode(ST_AsBinary(ST_Force_2D(\"%s\"),'%s'),'base64') as geom,\"%s\"";
+    static char *strGeomTemplate = "encode(ST_AsBinary(ST_Force_2D(\"%s\"),'%s'),'base64') as geom,\"%s\"";
 #else
-        static char *strGeomTemplate = "encode(ST_AsBinary(ST_Force_2D(\"%s\"),'%s'),'hex') as geom,\"%s\"";
+    static char *strGeomTemplate = "encode(ST_AsBinary(ST_Force_2D(\"%s\"),'%s'),'hex') as geom,\"%s\"";
 #endif
-        strGeom = (char*)msSmallMalloc(strlen(strGeomTemplate) + strlen(strEndian) + strlen(layerinfo->geomcolumn) + strlen(layerinfo->uid));
-        sprintf(strGeom, strGeomTemplate, layerinfo->geomcolumn, strEndian, layerinfo->uid);
-    }
+    strGeom = (char*)msSmallMalloc(strlen(strGeomTemplate) + strlen(strEndian) + strlen(layerinfo->geomcolumn) + strlen(layerinfo->uid));
+    sprintf(strGeom, strGeomTemplate, layerinfo->geomcolumn, strEndian, layerinfo->uid);
+  }
 
-    if( layer->debug > 1 ) {
-        msDebug("msPostGISBuildSQLItems: %d items requested.\n",layer->numitems);
-    }
+  if( layer->debug > 1 ) {
+    msDebug("msPostGISBuildSQLItems: %d items requested.\n",layer->numitems);
+  }
 
-    /*
-    ** Not requesting items? We just need geometry and unique id.
-    */
-    if (layer->numitems == 0) {
-        strItems = msStrdup(strGeom);
-    } 
-    /*
-    ** Build SQL to pull all the items.
-    */
-    else {
-        int length = strlen(strGeom) + 2;
-        int t;
-        for ( t = 0; t < layer->numitems; t++ ) {
-            length += strlen(layer->items[t]) + 3; /* itemname + "", */
-        }
-        strItems = (char*)msSmallMalloc(length);
-        strItems[0] = '\0';
-        for ( t = 0; t < layer->numitems; t++ ) {
-            strlcat(strItems, "\"", length); 
-            strlcat(strItems, layer->items[t], length); 
-            strlcat(strItems, "\",", length); 
-        }
-        strlcat(strItems, strGeom, length);
+  /*
+  ** Not requesting items? We just need geometry and unique id.
+  */
+  if (layer->numitems == 0) {
+    strItems = msStrdup(strGeom);
+  }
+  /*
+  ** Build SQL to pull all the items.
+  */
+  else {
+    int length = strlen(strGeom) + 2;
+    int t;
+    for ( t = 0; t < layer->numitems; t++ ) {
+      length += strlen(layer->items[t]) + 3; /* itemname + "", */
     }
+    strItems = (char*)msSmallMalloc(length);
+    strItems[0] = '\0';
+    for ( t = 0; t < layer->numitems; t++ ) {
+      strlcat(strItems, "\"", length);
+      strlcat(strItems, layer->items[t], length);
+      strlcat(strItems, "\",", length);
+    }
+    strlcat(strItems, strGeom, length);
+  }
 
-    free(strGeom);
-    return strItems;
+  free(strGeom);
+  return strItems;
 }
 
 /*
@@ -1660,134 +1698,133 @@ char *msPostGISBuildSQLItems(layerObj *layer) {
 **
 ** Returns malloc'ed char* that must be freed by caller.
 */
-char *msPostGISBuildSQLSRID(layerObj *layer) {
+char *msPostGISBuildSQLSRID(layerObj *layer)
+{
 
-    char *strSRID = NULL;
-    msPostGISLayerInfo *layerinfo = NULL;
+  char *strSRID = NULL;
+  msPostGISLayerInfo *layerinfo = NULL;
 
-    if (layer->debug) {
-        msDebug("msPostGISBuildSQLSRID called.\n");
-    }
+  if (layer->debug) {
+    msDebug("msPostGISBuildSQLSRID called.\n");
+  }
 
-    assert( layer->layerinfo != NULL);
+  assert( layer->layerinfo != NULL);
 
-    layerinfo = (msPostGISLayerInfo *)layer->layerinfo;
+  layerinfo = (msPostGISLayerInfo *)layer->layerinfo;
 
-    /* An SRID was already provided in the DATA line. */
-    if ( layerinfo->srid && (strlen(layerinfo->srid) > 0) ) {
-        strSRID = msStrdup(layerinfo->srid);
-        if( layer->debug > 1 ) {
-            msDebug("msPostGISBuildSQLSRID: SRID provided (%s)\n", strSRID);
-        }
+  /* An SRID was already provided in the DATA line. */
+  if ( layerinfo->srid && (strlen(layerinfo->srid) > 0) ) {
+    strSRID = msStrdup(layerinfo->srid);
+    if( layer->debug > 1 ) {
+      msDebug("msPostGISBuildSQLSRID: SRID provided (%s)\n", strSRID);
+    }
+  }
+  /*
+  ** No SRID in data line, so extract target table from the 'fromsource'.
+  ** Either of form "thetable" (one word) or "(select ... from thetable)"
+  ** or "(select ... from thetable where ...)".
+  */
+  else {
+    char *f_table_name;
+    char *strSRIDTemplate = "find_srid('','%s','%s')";
+    char *pos = strstr(layerinfo->fromsource, " ");
+    if( layer->debug > 1 ) {
+      msDebug("msPostGISBuildSQLSRID: Building find_srid line.\n", strSRID);
     }
-    /*
-    ** No SRID in data line, so extract target table from the 'fromsource'. 
-    ** Either of form "thetable" (one word) or "(select ... from thetable)"
-    ** or "(select ... from thetable where ...)".
-    */
-    else {
-        char *f_table_name;
-        char *strSRIDTemplate = "find_srid('','%s','%s')";
-        char *pos = strstr(layerinfo->fromsource, " ");
-        if( layer->debug > 1 ) {
-            msDebug("msPostGISBuildSQLSRID: Building find_srid line.\n", strSRID);
-        }
 
-        if ( ! pos ) {
-            /* target table is one word */
-            f_table_name = msStrdup(layerinfo->fromsource);
-            if( layer->debug > 1 ) {
-                msDebug("msPostGISBuildSQLSRID: Found table (%s)\n", f_table_name);
-            }
+    if ( ! pos ) {
+      /* target table is one word */
+      f_table_name = msStrdup(layerinfo->fromsource);
+      if( layer->debug > 1 ) {
+        msDebug("msPostGISBuildSQLSRID: Found table (%s)\n", f_table_name);
+      }
+    } else {
+      /* target table is hiding in sub-select clause */
+      pos = strcasestr(layerinfo->fromsource, " from ");
+      if ( pos ) {
+        char *pos_paren;
+        char *pos_space;
+        pos += 6; /* should be start of table name */
+        pos_paren = strstr(pos, ")"); /* first ) after table name */
+        pos_space = strstr(pos, " "); /* first space after table name */
+        if ( pos_space < pos_paren ) {
+          /* found space first */
+          f_table_name = (char*)msSmallMalloc(pos_space - pos + 1);
+          strlcpy(f_table_name, pos, pos_space - pos+1);
         } else {
-            /* target table is hiding in sub-select clause */
-            pos = strcasestr(layerinfo->fromsource, " from ");
-            if ( pos ) {
-                char *pos_paren;
-                char *pos_space;
-                pos += 6; /* should be start of table name */
-                pos_paren = strstr(pos, ")"); /* first ) after table name */
-                pos_space = strstr(pos, " "); /* first space after table name */
-                if ( pos_space < pos_paren ) {
-                    /* found space first */
-                    f_table_name = (char*)msSmallMalloc(pos_space - pos + 1);
-                    strlcpy(f_table_name, pos, pos_space - pos+1);
-                } else {
-                    /* found ) first */
-                    f_table_name = (char*)msSmallMalloc(pos_paren - pos + 1);
-                    strlcpy(f_table_name, pos, pos_paren - pos+1);
-                }
-            } else {
-                /* should not happen */
-                return NULL;
-            }
+          /* found ) first */
+          f_table_name = (char*)msSmallMalloc(pos_paren - pos + 1);
+          strlcpy(f_table_name, pos, pos_paren - pos+1);
         }
-        strSRID = msSmallMalloc(strlen(strSRIDTemplate) + strlen(f_table_name) + strlen(layerinfo->geomcolumn));
-        sprintf(strSRID, strSRIDTemplate, f_table_name, layerinfo->geomcolumn);
-        if ( f_table_name ) free(f_table_name);
+      } else {
+        /* should not happen */
+        return NULL;
+      }
     }
-    return strSRID;
+    strSRID = msSmallMalloc(strlen(strSRIDTemplate) + strlen(f_table_name) + strlen(layerinfo->geomcolumn));
+    sprintf(strSRID, strSRIDTemplate, f_table_name, layerinfo->geomcolumn);
+    if ( f_table_name ) free(f_table_name);
+  }
+  return strSRID;
 }
 
 
 /*
 ** msPostGISReplaceBoxToken()
-** 
+**
 ** Convert a fromsource data statement into something usable by replacing the !BOX! token.
 **
 ** Returns malloc'ed char* that must be freed by caller.
 */
-static char *msPostGISReplaceBoxToken(layerObj *layer, rectObj *rect, const char *fromsource) 
+static char *msPostGISReplaceBoxToken(layerObj *layer, rectObj *rect, const char *fromsource)
 {
-    char *result = NULL;
-    
-    if ( strstr(fromsource, BOXTOKEN) && rect ) {
-        char *strBox = NULL;
-        char *strSRID = NULL;
-
-        /* We see to set the SRID on the box, but to what SRID? */
-        strSRID = msPostGISBuildSQLSRID(layer);
-        if ( ! strSRID ) {
-            return NULL;
-        }
+  char *result = NULL;
 
-        /* Create a suitable SQL string from the rectangle and SRID. */
-        strBox = msPostGISBuildSQLBox(layer, rect, strSRID);
-        if ( ! strBox ) {
-            msSetError(MS_MISCERR, "Unable to build box SQL.", "msPostGISReplaceBoxToken()");
-            if (strSRID) free(strSRID);
-            return NULL;
-        }
+  if ( strstr(fromsource, BOXTOKEN) && rect ) {
+    char *strBox = NULL;
+    char *strSRID = NULL;
 
-        /* Do the substitution. */
-        while ( strstr(fromsource, BOXTOKEN) ) {
-            char    *start, *end;
-            char    *oldresult = result;
-            size_t buffer_size = 0;
-            start = strstr(fromsource, BOXTOKEN);
-            end = start + BOXTOKENLENGTH;
+    /* We see to set the SRID on the box, but to what SRID? */
+    strSRID = msPostGISBuildSQLSRID(layer);
+    if ( ! strSRID ) {
+      return NULL;
+    }
 
-            buffer_size = (start - fromsource) + strlen(strBox) + strlen(end) +1;
-            result = (char*)msSmallMalloc(buffer_size);
+    /* Create a suitable SQL string from the rectangle and SRID. */
+    strBox = msPostGISBuildSQLBox(layer, rect, strSRID);
+    if ( ! strBox ) {
+      msSetError(MS_MISCERR, "Unable to build box SQL.", "msPostGISReplaceBoxToken()");
+      if (strSRID) free(strSRID);
+      return NULL;
+    }
 
-            strlcpy(result, fromsource, start - fromsource +1);
-            strlcpy(result + (start - fromsource), strBox, buffer_size-(start - fromsource));
-            strlcat(result, end, buffer_size);
+    /* Do the substitution. */
+    while ( strstr(fromsource, BOXTOKEN) ) {
+      char    *start, *end;
+      char    *oldresult = result;
+      size_t buffer_size = 0;
+      start = strstr(fromsource, BOXTOKEN);
+      end = start + BOXTOKENLENGTH;
 
-            fromsource = result;
-            if (oldresult != NULL)
-                free(oldresult);
-        }
+      buffer_size = (start - fromsource) + strlen(strBox) + strlen(end) +1;
+      result = (char*)msSmallMalloc(buffer_size);
 
-        if (strSRID) free(strSRID);
-        if (strBox) free(strBox);
-    }    
-    else
-    {
-        result = msStrdup(fromsource);
+      strlcpy(result, fromsource, start - fromsource +1);
+      strlcpy(result + (start - fromsource), strBox, buffer_size-(start - fromsource));
+      strlcat(result, end, buffer_size);
+
+      fromsource = result;
+      if (oldresult != NULL)
+        free(oldresult);
     }
-    return result;
-    
+
+    if (strSRID) free(strSRID);
+    if (strBox) free(strBox);
+  } else {
+    result = msStrdup(fromsource);
+  }
+  return result;
+
 }
 
 /*
@@ -1795,30 +1832,31 @@ static char *msPostGISReplaceBoxToken(layerObj *layer, rectObj *rect, const char
 **
 ** Returns malloc'ed char* that must be freed by caller.
 */
-char *msPostGISBuildSQLFrom(layerObj *layer, rectObj *rect) {
-    char *strFrom = 0;
-    msPostGISLayerInfo *layerinfo;
+char *msPostGISBuildSQLFrom(layerObj *layer, rectObj *rect)
+{
+  char *strFrom = 0;
+  msPostGISLayerInfo *layerinfo;
 
-    if (layer->debug) {
-        msDebug("msPostGISBuildSQLFrom called.\n");
-    }
+  if (layer->debug) {
+    msDebug("msPostGISBuildSQLFrom called.\n");
+  }
 
-    assert( layer->layerinfo != NULL);
+  assert( layer->layerinfo != NULL);
 
-    layerinfo = (msPostGISLayerInfo *)layer->layerinfo;
+  layerinfo = (msPostGISLayerInfo *)layer->layerinfo;
 
-    if ( ! layerinfo->fromsource ) {
-        msSetError(MS_MISCERR, "Layerinfo->fromsource is not initialized.", "msPostGISBuildSQLFrom()");
-        return NULL;
-    }
+  if ( ! layerinfo->fromsource ) {
+    msSetError(MS_MISCERR, "Layerinfo->fromsource is not initialized.", "msPostGISBuildSQLFrom()");
+    return NULL;
+  }
 
-    /*
-    ** If there's a '!BOX!' in our source we need to substitute the
-    ** current rectangle for it...
-    */
-    strFrom = msPostGISReplaceBoxToken(layer, rect, layerinfo->fromsource);
+  /*
+  ** If there's a '!BOX!' in our source we need to substitute the
+  ** current rectangle for it...
+  */
+  strFrom = msPostGISReplaceBoxToken(layer, rect, layerinfo->fromsource);
 
-    return strFrom;
+  return strFrom;
 }
 
 /*
@@ -1826,116 +1864,131 @@ char *msPostGISBuildSQLFrom(layerObj *layer, rectObj *rect) {
 **
 ** Returns malloc'ed char* that must be freed by caller.
 */
-char *msPostGISBuildSQLWhere(layerObj *layer, rectObj *rect, long *uid) {
-    char *strRect = 0;
-    char *strFilter = 0;
-    char *strUid = 0;
-    char *strWhere = 0;
-    char *strLimit = 0;
-    size_t strRectLength = 0;
-    size_t strFilterLength = 0;
-    size_t strUidLength = 0;
-    size_t strLimitLength = 0;
-    size_t bufferSize = 0;
-    int insert_and = 0;
-    msPostGISLayerInfo *layerinfo;
+char *msPostGISBuildSQLWhere(layerObj *layer, rectObj *rect, long *uid)
+{
+  char *strRect = 0;
+  char *strFilter = 0;
+  char *strUid = 0;
+  char *strWhere = 0;
+  char *strLimit = 0;
+  char *strOffset = 0;
+  size_t strRectLength = 0;
+  size_t strFilterLength = 0;
+  size_t strUidLength = 0;
+  size_t strLimitLength = 0;
+  size_t strOffsetLength = 0;
+  size_t bufferSize = 0;
+  int insert_and = 0;
+  msPostGISLayerInfo *layerinfo;
+
+  if (layer->debug) {
+    msDebug("msPostGISBuildSQLWhere called.\n");
+  }
 
-    if (layer->debug) {
-        msDebug("msPostGISBuildSQLWhere called.\n");
-    }
+  assert( layer->layerinfo != NULL);
 
-    assert( layer->layerinfo != NULL);
+  layerinfo = (msPostGISLayerInfo *)layer->layerinfo;
 
-    layerinfo = (msPostGISLayerInfo *)layer->layerinfo;
+  if ( ! layerinfo->fromsource ) {
+    msSetError(MS_MISCERR, "Layerinfo->fromsource is not initialized.", "msPostGISBuildSQLWhere()");
+    return NULL;
+  }
 
-    if ( ! layerinfo->fromsource ) {
-        msSetError(MS_MISCERR, "Layerinfo->fromsource is not initialized.", "msPostGISBuildSQLWhere()");
-        return NULL;
-    }
+  /* Populate strLimit, if necessary. */
+  if ( layerinfo->paging && layer->maxfeatures >= 0 ) {
+    static char *strLimitTemplate = " limit %d";
+    strLimit = msSmallMalloc(strlen(strLimitTemplate) + 12);
+    sprintf(strLimit, strLimitTemplate, layer->maxfeatures);
+    strLimitLength = strlen(strLimit);
+  }
 
-    /* Populate strLimit, if necessary. */
-    if( layer->maxfeatures >= 0 ) {
-        static char *strLimitTemplate = " limit %d";
-        strLimit = msSmallMalloc(strlen(strLimitTemplate) + 12);
-        sprintf(strLimit, strLimitTemplate, layer->maxfeatures);
-        strLimitLength = strlen(strLimit);
-    }
-    
-    /* Populate strRect, if necessary. */
-    if ( rect && layerinfo->geomcolumn ) {
-        char *strBox = 0;
-        char *strSRID = 0;
-        size_t strBoxLength = 0;
-        static char *strRectTemplate = "%s && %s";
-
-        /* We see to set the SRID on the box, but to what SRID? */
-        strSRID = msPostGISBuildSQLSRID(layer);
-        if ( ! strSRID ) {
-            return NULL;
-        }
+  /* Populate strOffset, if necessary. */
+  if ( layerinfo->paging && layer->startindex > 0 ) {
+    static char *strOffsetTemplate = " offset %d";
+    strOffset = msSmallMalloc(strlen(strOffsetTemplate) + 12);
+    sprintf(strOffset, strOffsetTemplate, layer->startindex-1);
+    strOffsetLength = strlen(strOffset);
+  }
 
-        strBox = msPostGISBuildSQLBox(layer, rect, strSRID);
-        if ( strBox ) {
-            strBoxLength = strlen(strBox);
-        }
-        else {
-            msSetError(MS_MISCERR, "Unable to build box SQL.", "msPostGISBuildSQLWhere()");
-            return NULL;
-        }
+  /* Populate strRect, if necessary. */
+  if ( rect && layerinfo->geomcolumn ) {
+    char *strBox = 0;
+    char *strSRID = 0;
+    size_t strBoxLength = 0;
+    static char *strRectTemplate = "%s && %s";
 
-        strRect = (char*)msSmallMalloc(strlen(strRectTemplate) + strBoxLength + strlen(layerinfo->geomcolumn));
-        sprintf(strRect, strRectTemplate, layerinfo->geomcolumn, strBox);
-        strRectLength = strlen(strRect);
-        if (strBox) free(strBox);
-        if (strSRID) free(strSRID);
+    /* We see to set the SRID on the box, but to what SRID? */
+    strSRID = msPostGISBuildSQLSRID(layer);
+    if ( ! strSRID ) {
+      return NULL;
     }
 
-    /* Populate strFilter, if necessary. */
-    if ( layer->filter.string ) {
-        static char *strFilterTemplate = "(%s)";
-        strFilter = (char*)msSmallMalloc(strlen(strFilterTemplate) + strlen(layer->filter.string));
-        sprintf(strFilter, strFilterTemplate, layer->filter.string);
-        strFilterLength = strlen(strFilter);
+    strBox = msPostGISBuildSQLBox(layer, rect, strSRID);
+    if ( strBox ) {
+      strBoxLength = strlen(strBox);
+    } else {
+      msSetError(MS_MISCERR, "Unable to build box SQL.", "msPostGISBuildSQLWhere()");
+      return NULL;
     }
 
-    /* Populate strUid, if necessary. */
-    if ( uid ) {
-        static char *strUidTemplate = "\"%s\" = %ld";
-        strUid = (char*)msSmallMalloc(strlen(strUidTemplate) + strlen(layerinfo->uid) + 64);
-        sprintf(strUid, strUidTemplate, layerinfo->uid, *uid);
-        strUidLength = strlen(strUid);
-    }
+    strRect = (char*)msSmallMalloc(strlen(strRectTemplate) + strBoxLength + strlen(layerinfo->geomcolumn));
+    sprintf(strRect, strRectTemplate, layerinfo->geomcolumn, strBox);
+    strRectLength = strlen(strRect);
+    if (strBox) free(strBox);
+    if (strSRID) free(strSRID);
+  }
 
-    bufferSize = strRectLength + 5 + strFilterLength + 5 + strUidLength + strLimitLength;
-    strWhere = (char*)msSmallMalloc(bufferSize);
-    *strWhere = '\0';
-    if ( strRect ) {
-        strlcat(strWhere, strRect, bufferSize);
-        insert_and++;
-        free(strRect);
-    }
-    if ( strFilter ) {
-        if ( insert_and ) {
-            strlcat(strWhere, " and ", bufferSize);
-        }
-        strlcat(strWhere, strFilter, bufferSize);
-        free(strFilter);
-        insert_and++;
-    }
-    if ( strUid ) {
-        if ( insert_and ) {
-            strlcat(strWhere, " and ", bufferSize);
-        }
-        strlcat(strWhere, strUid, bufferSize);
-        free(strUid);
-        insert_and++;
+  /* Populate strFilter, if necessary. */
+  if ( layer->filter.string ) {
+    static char *strFilterTemplate = "(%s)";
+    strFilter = (char*)msSmallMalloc(strlen(strFilterTemplate) + strlen(layer->filter.string));
+    sprintf(strFilter, strFilterTemplate, layer->filter.string);
+    strFilterLength = strlen(strFilter);
+  }
+
+  /* Populate strUid, if necessary. */
+  if ( uid ) {
+    static char *strUidTemplate = "\"%s\" = %ld";
+    strUid = (char*)msSmallMalloc(strlen(strUidTemplate) + strlen(layerinfo->uid) + 64);
+    sprintf(strUid, strUidTemplate, layerinfo->uid, *uid);
+    strUidLength = strlen(strUid);
+  }
+
+  bufferSize = strRectLength + 5 + strFilterLength + 5 + strUidLength
+               + strLimitLength + strOffsetLength;
+  strWhere = (char*)msSmallMalloc(bufferSize);
+  *strWhere = '\0';
+  if ( strRect ) {
+    strlcat(strWhere, strRect, bufferSize);
+    insert_and++;
+    free(strRect);
+  }
+  if ( strFilter ) {
+    if ( insert_and ) {
+      strlcat(strWhere, " and ", bufferSize);
     }
-    if ( strLimit ) {
-        strlcat(strWhere, strLimit, bufferSize);
-        free(strLimit);
+    strlcat(strWhere, strFilter, bufferSize);
+    free(strFilter);
+    insert_and++;
+  }
+  if ( strUid ) {
+    if ( insert_and ) {
+      strlcat(strWhere, " and ", bufferSize);
     }
+    strlcat(strWhere, strUid, bufferSize);
+    free(strUid);
+    insert_and++;
+  }
+  if ( strLimit ) {
+    strlcat(strWhere, strLimit, bufferSize);
+    free(strLimit);
+  }
+  if ( strOffset ) {
+    strlcat(strWhere, strOffset, bufferSize);
+    free(strOffset);
+  }
 
-    return strWhere;
+  return strWhere;
 }
 
 /*
@@ -1943,210 +1996,215 @@ char *msPostGISBuildSQLWhere(layerObj *layer, rectObj *rect, long *uid) {
 **
 ** Returns malloc'ed char* that must be freed by caller.
 */
-char *msPostGISBuildSQL(layerObj *layer, rectObj *rect, long *uid) {
+char *msPostGISBuildSQL(layerObj *layer, rectObj *rect, long *uid)
+{
 
-    msPostGISLayerInfo *layerinfo = 0;
-    char *strFrom = 0;
-    char *strItems = 0;
-    char *strWhere = 0;
-    char *strSQL = 0;
-    static char *strSQLTemplate0 = "select %s from %s where %s";
-    static char *strSQLTemplate1 = "select %s from %s%s";
-    char *strSQLTemplate = 0;
+  msPostGISLayerInfo *layerinfo = 0;
+  char *strFrom = 0;
+  char *strItems = 0;
+  char *strWhere = 0;
+  char *strSQL = 0;
+  static char *strSQLTemplate0 = "select %s from %s where %s";
+  static char *strSQLTemplate1 = "select %s from %s%s";
+  char *strSQLTemplate = 0;
+
+  if (layer->debug) {
+    msDebug("msPostGISBuildSQL called.\n");
+  }
 
-    if (layer->debug) {
-        msDebug("msPostGISBuildSQL called.\n");
-    }
+  assert( layer->layerinfo != NULL);
 
-    assert( layer->layerinfo != NULL);
+  layerinfo = (msPostGISLayerInfo *)layer->layerinfo;
 
-    layerinfo = (msPostGISLayerInfo *)layer->layerinfo;
+  strItems = msPostGISBuildSQLItems(layer);
+  if ( ! strItems ) {
+    msSetError(MS_MISCERR, "Failed to build SQL items.", "msPostGISBuildSQL()");
+    return NULL;
+  }
 
-    strItems = msPostGISBuildSQLItems(layer);
-    if ( ! strItems ) {
-        msSetError(MS_MISCERR, "Failed to build SQL items.", "msPostGISBuildSQL()");
-        return NULL;
-    }
+  strFrom = msPostGISBuildSQLFrom(layer, rect);
 
-    strFrom = msPostGISBuildSQLFrom(layer, rect);
+  if ( ! strFrom ) {
+    msSetError(MS_MISCERR, "Failed to build SQL 'from'.", "msPostGISBuildSQL()");
+    return NULL;
+  }
 
-    if ( ! strFrom ) {
-        msSetError(MS_MISCERR, "Failed to build SQL 'from'.", "msPostGISBuildSQL()");
-        return NULL;
-    }
-
-    /* If there's BOX hackery going on, we don't want to append a box index test at
-       the end of the query, the user is going to be responsible for making things
-       work with their hackery. */
-    if ( strstr(layerinfo->fromsource, BOXTOKEN) )
-        strWhere = msPostGISBuildSQLWhere(layer, NULL, uid);
-    else
-        strWhere = msPostGISBuildSQLWhere(layer, rect, uid);
+  /* If there's BOX hackery going on, we don't want to append a box index test at
+     the end of the query, the user is going to be responsible for making things
+     work with their hackery. */
+  if ( strstr(layerinfo->fromsource, BOXTOKEN) )
+    strWhere = msPostGISBuildSQLWhere(layer, NULL, uid);
+  else
+    strWhere = msPostGISBuildSQLWhere(layer, rect, uid);
 
-    if ( ! strWhere ) {
-        msSetError(MS_MISCERR, "Failed to build SQL 'where'.", "msPostGISBuildSQL()");
-        return NULL;
-    }
+  if ( ! strWhere ) {
+    msSetError(MS_MISCERR, "Failed to build SQL 'where'.", "msPostGISBuildSQL()");
+    return NULL;
+  }
 
-    strSQLTemplate = strlen(strWhere) ? strSQLTemplate0 : strSQLTemplate1;
+  strSQLTemplate = strlen(strWhere) ? strSQLTemplate0 : strSQLTemplate1;
 
-    strSQL = msSmallMalloc(strlen(strSQLTemplate) + strlen(strFrom) + strlen(strItems) + strlen(strWhere));
-    sprintf(strSQL, strSQLTemplate, strItems, strFrom, strWhere);
-    if (strItems) free(strItems);
-    if (strFrom) free(strFrom);
-    if (strWhere) free(strWhere);
+  strSQL = msSmallMalloc(strlen(strSQLTemplate) + strlen(strFrom) + strlen(strItems) + strlen(strWhere));
+  sprintf(strSQL, strSQLTemplate, strItems, strFrom, strWhere);
+  if (strItems) free(strItems);
+  if (strFrom) free(strFrom);
+  if (strWhere) free(strWhere);
 
-    return strSQL;
+  return strSQL;
 
 }
 
-int msPostGISReadShape(layerObj *layer, shapeObj *shape) {
+#define wkbstaticsize 4096
+int msPostGISReadShape(layerObj *layer, shapeObj *shape)
+{
 
-    char *wkbstr = NULL;
-    unsigned char *wkb = NULL;
-    wkbObj w;
-    msPostGISLayerInfo *layerinfo = NULL;
-    int result = 0;
-    int wkbstrlen = 0;
+  char *wkbstr = NULL;
+  unsigned char wkbstatic[wkbstaticsize];
+  unsigned char *wkb = NULL;
+  wkbObj w;
+  msPostGISLayerInfo *layerinfo = NULL;
+  int result = 0;
+  int wkbstrlen = 0;
 
-    if (layer->debug) {
-        msDebug("msPostGISReadShape called.\n");
-    }
+  if (layer->debug) {
+    msDebug("msPostGISReadShape called.\n");
+  }
 
-    assert(layer->layerinfo != NULL);
-    layerinfo = (msPostGISLayerInfo*) layer->layerinfo;
+  assert(layer->layerinfo != NULL);
+  layerinfo = (msPostGISLayerInfo*) layer->layerinfo;
 
-    /* Retrieve the geometry. */
-    wkbstr = (char*)PQgetvalue(layerinfo->pgresult, layerinfo->rownum, layer->numitems );
-    wkbstrlen = PQgetlength(layerinfo->pgresult, layerinfo->rownum, layer->numitems);
-    
-    if ( ! wkbstr ) {
-        msSetError(MS_QUERYERR, "Base64 WKB returned is null!", "msPostGISReadShape()");
-        return MS_FAILURE;
-    }
+  /* Retrieve the geometry. */
+  wkbstr = (char*)PQgetvalue(layerinfo->pgresult, layerinfo->rownum, layer->numitems );
+  wkbstrlen = PQgetlength(layerinfo->pgresult, layerinfo->rownum, layer->numitems);
 
+  if ( ! wkbstr ) {
+    msSetError(MS_QUERYERR, "Base64 WKB returned is null!", "msPostGISReadShape()");
+    return MS_FAILURE;
+  }
 
+  if(wkbstrlen > wkbstaticsize) {
     wkb = calloc(wkbstrlen, sizeof(char));
+  } else {
+    wkb = wkbstatic;
+  }
 #if TRANSFER_ENCODING == 64
-    result = msPostGISBase64Decode(wkb, wkbstr, wkbstrlen - 1);
+  result = msPostGISBase64Decode(wkb, wkbstr, wkbstrlen - 1);
 #else
-    result = msPostGISHexDecode(wkb, wkbstr, wkbstrlen);
+  result = msPostGISHexDecode(wkb, wkbstr, wkbstrlen);
 #endif
 
-    if( ! result ) {
-        free(wkb);
-        return MS_FAILURE;
-    }
+  if( ! result ) {
+    if(wkb!=wkbstatic) free(wkb);
+    return MS_FAILURE;
+  }
+
+  /* Initialize our wkbObj */
+  w.wkb = (char*)wkb;
+  w.ptr = w.wkb;
+  w.size = (wkbstrlen - 1)/2;
+
+  /* Set the type map according to what version of PostGIS we are dealing with */
+  if( layerinfo->version >= 20000 ) /* PostGIS 2.0+ */
+    w.typemap = wkb_postgis20;
+  else
+    w.typemap = wkb_postgis15;
+
+  switch (layer->type) {
 
-    /* Initialize our wkbObj */
-    w.wkb = (char*)wkb;
-    w.ptr = w.wkb;
-    w.size = (wkbstrlen - 1)/2;
-    
-    /* Set the type map according to what version of PostGIS we are dealing with */
-    if( layerinfo->version >= 20000 ) /* PostGIS 2.0+ */
-        w.typemap = wkb_postgis20;
-    else
-        w.typemap = wkb_postgis15;
-    
-    switch (layer->type) {
-        
     case MS_LAYER_POINT:
-        shape->type = MS_SHAPE_POINT;
-        result = wkbConvGeometryToShape(&w, shape);
-        break;
-        
+      shape->type = MS_SHAPE_POINT;
+      result = wkbConvGeometryToShape(&w, shape);
+      break;
+
     case MS_LAYER_LINE:
-        shape->type = MS_SHAPE_LINE;
-        result = wkbConvGeometryToShape(&w, shape);
-        break;
-        
+      shape->type = MS_SHAPE_LINE;
+      result = wkbConvGeometryToShape(&w, shape);
+      break;
+
     case MS_LAYER_POLYGON:
-        shape->type = MS_SHAPE_POLYGON;
-        result = wkbConvGeometryToShape(&w, shape);
-        break;
-    
+      shape->type = MS_SHAPE_POLYGON;
+      result = wkbConvGeometryToShape(&w, shape);
+      break;
+
     case MS_LAYER_ANNOTATION:
     case MS_LAYER_QUERY:
     case MS_LAYER_CHART:
-        result = msPostGISFindBestType(&w, shape);
-        break;
+      result = msPostGISFindBestType(&w, shape);
+      break;
 
     case MS_LAYER_RASTER:
-        msDebug("Ignoring MS_LAYER_RASTER in msPostGISReadShape.\n");
-        break;
+      msDebug("Ignoring MS_LAYER_RASTER in msPostGISReadShape.\n");
+      break;
 
     case MS_LAYER_CIRCLE:
-        msDebug("Ignoring MS_LAYER_RASTER in msPostGISReadShape.\n");
-        break;
+      msDebug("Ignoring MS_LAYER_RASTER in msPostGISReadShape.\n");
+      break;
 
     default:
-        msDebug("Unsupported layer type in msPostGISReadShape()!\n");
-        break;
-    }
-
-    /* All done with WKB geometry, free it! */
-    free(wkb);
-
-    if (result != MS_FAILURE) {
-        int t;
-        long uid;
-        char *tmp;
-        /* Found a drawable shape, so now retreive the attributes. */
-
-        shape->values = (char**) msSmallMalloc(sizeof(char*) * layer->numitems);
-        for ( t = 0; t < layer->numitems; t++) {
-            int size = PQgetlength(layerinfo->pgresult, layerinfo->rownum, t);
-            char *val = (char*)PQgetvalue(layerinfo->pgresult, layerinfo->rownum, t);
-            int isnull = PQgetisnull(layerinfo->pgresult, layerinfo->rownum, t);
-            if ( isnull ) {
-                shape->values[t] = msStrdup("");
-            }
-            else {
-                shape->values[t] = (char*) msSmallMalloc(size + 1);
-                memcpy(shape->values[t], val, size);
-                shape->values[t][size] = '\0'; /* null terminate it */
-                msStringTrimBlanks(shape->values[t]);
-            }
-            if( layer->debug > 4 ) {
-                msDebug("msPostGISReadShape: PQgetlength = %d\n", size);
-            }
-            if( layer->debug > 1 ) {
-                msDebug("msPostGISReadShape: [%s] \"%s\"\n", layer->items[t], shape->values[t]);
-            }
-        }
-        
-        /* t is the geometry, t+1 is the uid */
-        tmp = PQgetvalue(layerinfo->pgresult, layerinfo->rownum, t + 1);
-        if( tmp ) {
-            uid = strtol( tmp, NULL, 10 );
-        }
-        else {
-            uid = 0;
-        }
-        if( layer->debug > 4 ) {
-            msDebug("msPostGISReadShape: Setting shape->index = %d\n", uid);
-            msDebug("msPostGISReadShape: Setting shape->resultindex = %d\n", layerinfo->rownum);
-        }
-        shape->index = uid;
-        shape->resultindex = layerinfo->rownum;
-        
-        if( layer->debug > 2 ) {
-            msDebug("msPostGISReadShape: [index] %d\n",  shape->index);
-        }
+      msDebug("Unsupported layer type in msPostGISReadShape()!\n");
+      break;
+  }
+
+  /* All done with WKB geometry, free it! */
+  if(wkb!=wkbstatic) free(wkb);
 
-        shape->numvalues = layer->numitems;
+  if (result != MS_FAILURE) {
+    int t;
+    long uid;
+    char *tmp;
+    /* Found a drawable shape, so now retreive the attributes. */
+
+    shape->values = (char**) msSmallMalloc(sizeof(char*) * layer->numitems);
+    for ( t = 0; t < layer->numitems; t++) {
+      int size = PQgetlength(layerinfo->pgresult, layerinfo->rownum, t);
+      char *val = (char*)PQgetvalue(layerinfo->pgresult, layerinfo->rownum, t);
+      int isnull = PQgetisnull(layerinfo->pgresult, layerinfo->rownum, t);
+      if ( isnull ) {
+        shape->values[t] = msStrdup("");
+      } else {
+        shape->values[t] = (char*) msSmallMalloc(size + 1);
+        memcpy(shape->values[t], val, size);
+        shape->values[t][size] = '\0'; /* null terminate it */
+        msStringTrimBlanks(shape->values[t]);
+      }
+      if( layer->debug > 4 ) {
+        msDebug("msPostGISReadShape: PQgetlength = %d\n", size);
+      }
+      if( layer->debug > 1 ) {
+        msDebug("msPostGISReadShape: [%s] \"%s\"\n", layer->items[t], shape->values[t]);
+      }
+    }
 
-        msComputeBounds(shape);
+    /* t is the geometry, t+1 is the uid */
+    tmp = PQgetvalue(layerinfo->pgresult, layerinfo->rownum, t + 1);
+    if( tmp ) {
+      uid = strtol( tmp, NULL, 10 );
+    } else {
+      uid = 0;
+    }
+    if( layer->debug > 4 ) {
+      msDebug("msPostGISReadShape: Setting shape->index = %d\n", uid);
+      msDebug("msPostGISReadShape: Setting shape->resultindex = %d\n", layerinfo->rownum);
     }
-    
+    shape->index = uid;
+    shape->resultindex = layerinfo->rownum;
+
     if( layer->debug > 2 ) {
-        char *tmp = msShapeToWKT(shape);
-        msDebug("msPostGISReadShape: [shape] %s\n", tmp);
-        free(tmp);
+      msDebug("msPostGISReadShape: [index] %d\n",  shape->index);
     }
-    
-    return MS_SUCCESS;
+
+    shape->numvalues = layer->numitems;
+
+    msComputeBounds(shape);
+  }
+
+  if( layer->debug > 2 ) {
+    char *tmp = msShapeToWKT(shape);
+    msDebug("msPostGISReadShape: [shape] %s\n", tmp);
+    free(tmp);
+  }
+
+  return MS_SUCCESS;
 }
 
 #endif /* USE_POSTGIS */
@@ -2157,128 +2215,128 @@ int msPostGISReadShape(layerObj *layer, shapeObj *shape) {
 **
 ** Registered vtable->LayerOpen function.
 */
-int msPostGISLayerOpen(layerObj *layer) {
+int msPostGISLayerOpen(layerObj *layer)
+{
 #ifdef USE_POSTGIS
-    msPostGISLayerInfo  *layerinfo;
-    int order_test = 1;
+  msPostGISLayerInfo  *layerinfo;
+  int order_test = 1;
 
-    assert(layer != NULL);
+  assert(layer != NULL);
 
+  if (layer->debug) {
+    msDebug("msPostGISLayerOpen called: %s\n", layer->data);
+  }
+
+  if (layer->layerinfo) {
     if (layer->debug) {
-        msDebug("msPostGISLayerOpen called: %s\n", layer->data);
+      msDebug("msPostGISLayerOpen: Layer is already open!\n");
     }
+    return MS_SUCCESS;  /* already open */
+  }
 
-    if (layer->layerinfo) {
-        if (layer->debug) {
-            msDebug("msPostGISLayerOpen: Layer is already open!\n");
-        }
-        return MS_SUCCESS;  /* already open */
+  if (!layer->data) {
+    msSetError(MS_QUERYERR, "Nothing specified in DATA statement.", "msPostGISLayerOpen()");
+    return MS_FAILURE;
+  }
+
+  /*
+  ** Initialize the layerinfo
+  **/
+  layerinfo = msPostGISCreateLayerInfo();
+
+  if (((char*) &order_test)[0] == 1) {
+    layerinfo->endian = LITTLE_ENDIAN;
+  } else {
+    layerinfo->endian = BIG_ENDIAN;
+  }
+
+  /*
+  ** Get a database connection from the pool.
+  */
+  layerinfo->pgconn = (PGconn *) msConnPoolRequest(layer);
+
+  /* No connection in the pool, so set one up. */
+  if (!layerinfo->pgconn) {
+    char *conn_decrypted;
+    if (layer->debug) {
+      msDebug("msPostGISLayerOpen: No connection in pool, creating a fresh one.\n");
     }
 
-    if (!layer->data) {
-        msSetError(MS_QUERYERR, "Nothing specified in DATA statement.", "msPostGISLayerOpen()");
-        return MS_FAILURE;
+    if (!layer->connection) {
+      msSetError(MS_MISCERR, "Missing CONNECTION keyword.", "msPostGISLayerOpen()");
+      return MS_FAILURE;
     }
 
     /*
-    ** Initialize the layerinfo 
-    **/
-    layerinfo = msPostGISCreateLayerInfo();
-
-    if (((char*) &order_test)[0] == 1) {
-        layerinfo->endian = LITTLE_ENDIAN;
-    } else {
-        layerinfo->endian = BIG_ENDIAN;
+    ** Decrypt any encrypted token in connection string and attempt to connect.
+    */
+    conn_decrypted = msDecryptStringTokens(layer->map, layer->connection);
+    if (conn_decrypted == NULL) {
+      return MS_FAILURE;  /* An error should already have been produced */
     }
+    layerinfo->pgconn = PQconnectdb(conn_decrypted);
+    msFree(conn_decrypted);
+    conn_decrypted = NULL;
 
     /*
-    ** Get a database connection from the pool.
+    ** Connection failed, return error message with passwords ***ed out.
     */
-    layerinfo->pgconn = (PGconn *) msConnPoolRequest(layer);
-
-    /* No connection in the pool, so set one up. */
-    if (!layerinfo->pgconn) {
-        char *conn_decrypted;
-        if (layer->debug) {
-            msDebug("msPostGISLayerOpen: No connection in pool, creating a fresh one.\n");
+    if (!layerinfo->pgconn || PQstatus(layerinfo->pgconn) == CONNECTION_BAD) {
+      char *index, *maskeddata;
+      if (layer->debug)
+        msDebug("msPostGISLayerOpen: Connection failure.\n");
+
+      maskeddata = msStrdup(layer->connection);
+      index = strstr(maskeddata, "password=");
+      if (index != NULL) {
+        index = (char*)(index + 9);
+        while (*index != '\0' && *index != ' ') {
+          *index = '*';
+          index++;
         }
+      }
 
-        if (!layer->connection) {
-            msSetError(MS_MISCERR, "Missing CONNECTION keyword.", "msPostGISLayerOpen()");
-            return MS_FAILURE;
-        }
+      msSetError(MS_QUERYERR, "Database connection failed (%s) with connect string '%s'\nIs the database running? Is it allowing connections? Does the specified user exist? Is the password valid? Is the database on the standard port?", "msPostGISLayerOpen()", PQerrorMessage(layerinfo->pgconn), maskeddata);
 
-        /*
-        ** Decrypt any encrypted token in connection string and attempt to connect.
-        */
-        conn_decrypted = msDecryptStringTokens(layer->map, layer->connection);
-        if (conn_decrypted == NULL) {
-            return MS_FAILURE;  /* An error should already have been produced */
-        }
-        layerinfo->pgconn = PQconnectdb(conn_decrypted);
-        msFree(conn_decrypted);
-        conn_decrypted = NULL;
-
-        /*
-        ** Connection failed, return error message with passwords ***ed out.
-        */
-        if (!layerinfo->pgconn || PQstatus(layerinfo->pgconn) == CONNECTION_BAD) {
-            char *index, *maskeddata;
-            if (layer->debug)
-                msDebug("msPostGISLayerOpen: Connection failure.\n");
-
-            maskeddata = msStrdup(layer->connection);
-            index = strstr(maskeddata, "password=");
-            if (index != NULL) {
-                index = (char*)(index + 9);
-                while (*index != '\0' && *index != ' ') {
-                    *index = '*';
-                    index++;
-                }
-            }
-
-            msSetError(MS_QUERYERR, "Database connection failed (%s) with connect string '%s'\nIs the database running? Is it allowing connections? Does the specified user exist? Is the password valid? Is the database on the standard port?", "msPostGISLayerOpen()", PQerrorMessage(layerinfo->pgconn), maskeddata);
-
-            free(maskeddata);
-            free(layerinfo);
-            return MS_FAILURE;
-        }
+      free(maskeddata);
+      free(layerinfo);
+      return MS_FAILURE;
+    }
+
+    /* Register to receive notifications from the database. */
+    PQsetNoticeProcessor(layerinfo->pgconn, postresqlNoticeHandler, (void *) layer);
+
+    /* Save this connection in the pool for later. */
+    msConnPoolRegister(layer, layerinfo->pgconn, msPostGISCloseConnection);
+  } else {
+    /* Connection in the pool should be tested to see if backend is alive. */
+    if( PQstatus(layerinfo->pgconn) != CONNECTION_OK ) {
+      /* Uh oh, bad connection. Can we reset it? */
+      PQreset(layerinfo->pgconn);
+      if( PQstatus(layerinfo->pgconn) != CONNECTION_OK ) {
+        /* Nope, time to bail out. */
+        msSetError(MS_QUERYERR, "PostgreSQL database connection gone bad (%s)", "msPostGISLayerOpen()", PQerrorMessage(layerinfo->pgconn));
+        return MS_FAILURE;
+      }
 
-        /* Register to receive notifications from the database. */
-        PQsetNoticeProcessor(layerinfo->pgconn, postresqlNoticeHandler, (void *) layer);
-
-        /* Save this connection in the pool for later. */
-        msConnPoolRegister(layer, layerinfo->pgconn, msPostGISCloseConnection);
-    }
-    else {
-        /* Connection in the pool should be tested to see if backend is alive. */
-        if( PQstatus(layerinfo->pgconn) != CONNECTION_OK ) {
-            /* Uh oh, bad connection. Can we reset it? */
-            PQreset(layerinfo->pgconn);
-            if( PQstatus(layerinfo->pgconn) != CONNECTION_OK ) {
-                /* Nope, time to bail out. */
-                msSetError(MS_QUERYERR, "PostgreSQL database connection gone bad (%s)", "msPostGISLayerOpen()", PQerrorMessage(layerinfo->pgconn));
-                return MS_FAILURE;
-            }
-            
-        }
     }
+  }
 
-    /* Get the PostGIS version number from the database */
-    layerinfo->version = msPostGISRetrieveVersion(layerinfo->pgconn);
-    if( layerinfo->version == MS_FAILURE ) return MS_FAILURE;
-    if (layer->debug)
-        msDebug("msPostGISLayerOpen: Got PostGIS version %d.\n", layerinfo->version);
-    
-    /* Save the layerinfo in the layerObj. */
-    layer->layerinfo = (void*)layerinfo;
+  /* Get the PostGIS version number from the database */
+  layerinfo->version = msPostGISRetrieveVersion(layerinfo->pgconn);
+  if( layerinfo->version == MS_FAILURE ) return MS_FAILURE;
+  if (layer->debug)
+    msDebug("msPostGISLayerOpen: Got PostGIS version %d.\n", layerinfo->version);
 
-    return MS_SUCCESS;
+  /* Save the layerinfo in the layerObj. */
+  layer->layerinfo = (void*)layerinfo;
+
+  return MS_SUCCESS;
 #else
-    msSetError( MS_MISCERR,
-                "PostGIS support is not available.",
-                "msPostGISLayerOpen()");
-    return MS_FAILURE;
+  msSetError( MS_MISCERR,
+              "PostGIS support is not available.",
+              "msPostGISLayerOpen()");
+  return MS_FAILURE;
 #endif
 }
 
@@ -2287,23 +2345,24 @@ int msPostGISLayerOpen(layerObj *layer) {
 **
 ** Registered vtable->LayerClose function.
 */
-int msPostGISLayerClose(layerObj *layer) {
+int msPostGISLayerClose(layerObj *layer)
+{
 #ifdef USE_POSTGIS
 
-    if (layer->debug) {
-        msDebug("msPostGISLayerClose called: %s\n", layer->data);
-    }
-    
-    if( layer->layerinfo ) {
-        msPostGISFreeLayerInfo(layer); 
-    }
+  if (layer->debug) {
+    msDebug("msPostGISLayerClose called: %s\n", layer->data);
+  }
 
-    return MS_SUCCESS;
+  if( layer->layerinfo ) {
+    msPostGISFreeLayerInfo(layer);
+  }
+
+  return MS_SUCCESS;
 #else
-    msSetError( MS_MISCERR,
-                "PostGIS support is not available.",
-                "msPostGISLayerClose()");
-    return MS_FAILURE;
+  msSetError( MS_MISCERR,
+              "PostGIS support is not available.",
+              "msPostGISLayerClose()");
+  return MS_FAILURE;
 #endif
 }
 
@@ -2313,22 +2372,23 @@ int msPostGISLayerClose(layerObj *layer) {
 **
 ** Registered vtable->LayerIsOpen function.
 */
-int msPostGISLayerIsOpen(layerObj *layer) {
+int msPostGISLayerIsOpen(layerObj *layer)
+{
 #ifdef USE_POSTGIS
 
-    if (layer->debug) {
-        msDebug("msPostGISLayerIsOpen called.\n");
-    }
+  if (layer->debug) {
+    msDebug("msPostGISLayerIsOpen called.\n");
+  }
 
-    if (layer->layerinfo)
-        return MS_TRUE;
-    else
-        return MS_FALSE;
+  if (layer->layerinfo)
+    return MS_TRUE;
+  else
+    return MS_FALSE;
 #else
-    msSetError( MS_MISCERR,
-                "PostGIS support is not available.",
-                "msPostGISLayerIsOpen()");
-    return MS_FAILURE;
+  msSetError( MS_MISCERR,
+              "PostGIS support is not available.",
+              "msPostGISLayerIsOpen()");
+  return MS_FAILURE;
 #endif
 }
 
@@ -2338,16 +2398,17 @@ int msPostGISLayerIsOpen(layerObj *layer) {
 **
 ** Registered vtable->LayerFreeItemInfo function.
 */
-void msPostGISLayerFreeItemInfo(layerObj *layer) {
+void msPostGISLayerFreeItemInfo(layerObj *layer)
+{
 #ifdef USE_POSTGIS
-    if (layer->debug) {
-        msDebug("msPostGISLayerFreeItemInfo called.\n");
-    }
+  if (layer->debug) {
+    msDebug("msPostGISLayerFreeItemInfo called.\n");
+  }
 
-    if (layer->iteminfo) {
-        free(layer->iteminfo);
-    }
-    layer->iteminfo = NULL;
+  if (layer->iteminfo) {
+    free(layer->iteminfo);
+  }
+  layer->iteminfo = NULL;
 #endif
 }
 
@@ -2357,40 +2418,41 @@ void msPostGISLayerFreeItemInfo(layerObj *layer) {
 ** Registered vtable->LayerInitItemInfo function.
 ** Our iteminfo is list of indexes from 1..numitems.
 */
-int msPostGISLayerInitItemInfo(layerObj *layer) {
+int msPostGISLayerInitItemInfo(layerObj *layer)
+{
 #ifdef USE_POSTGIS
-    int i;
-    int *itemindexes ;
+  int i;
+  int *itemindexes ;
 
-    if (layer->debug) {
-        msDebug("msPostGISLayerInitItemInfo called.\n");
-    }
+  if (layer->debug) {
+    msDebug("msPostGISLayerInitItemInfo called.\n");
+  }
 
-    if (layer->numitems == 0) {
-        return MS_SUCCESS;
-    }
+  if (layer->numitems == 0) {
+    return MS_SUCCESS;
+  }
 
-    if (layer->iteminfo) {
-        free(layer->iteminfo);
-    }
+  if (layer->iteminfo) {
+    free(layer->iteminfo);
+  }
 
-    layer->iteminfo = msSmallMalloc(sizeof(int) * layer->numitems);
-    if (!layer->iteminfo) {
-        msSetError(MS_MEMERR, "Out of memory.", "msPostGISLayerInitItemInfo()");
-        return MS_FAILURE;
-    }
-    
-    itemindexes = (int*)layer->iteminfo;
-    for (i = 0; i < layer->numitems; i++) {
-        itemindexes[i] = i; /* Last item is always the geometry. The rest are non-geometry. */
-    }
+  layer->iteminfo = msSmallMalloc(sizeof(int) * layer->numitems);
+  if (!layer->iteminfo) {
+    msSetError(MS_MEMERR, "Out of memory.", "msPostGISLayerInitItemInfo()");
+    return MS_FAILURE;
+  }
 
-    return MS_SUCCESS;
+  itemindexes = (int*)layer->iteminfo;
+  for (i = 0; i < layer->numitems; i++) {
+    itemindexes[i] = i; /* Last item is always the geometry. The rest are non-geometry. */
+  }
+
+  return MS_SUCCESS;
 #else
-    msSetError( MS_MISCERR,
-                "PostGIS support is not available.",
-                "msPostGISLayerInitItemInfo()");
-    return MS_FAILURE;
+  msSetError( MS_MISCERR,
+              "PostGIS support is not available.",
+              "msPostGISLayerInitItemInfo()");
+  return MS_FAILURE;
 #endif
 }
 
@@ -2399,106 +2461,107 @@ int msPostGISLayerInitItemInfo(layerObj *layer) {
 **
 ** Registered vtable->LayerWhichShapes function.
 */
-int msPostGISLayerWhichShapes(layerObj *layer, rectObj rect, int isQuery) {
+int msPostGISLayerWhichShapes(layerObj *layer, rectObj rect, int isQuery)
+{
 #ifdef USE_POSTGIS
-    msPostGISLayerInfo *layerinfo = NULL;
-    char *strSQL = NULL;
-    PGresult *pgresult = NULL;
-    char** layer_bind_values = (char**)msSmallMalloc(sizeof(char*) * 1000);
-    char* bind_value;
-    char* bind_key = (char*)msSmallMalloc(3);
-
-    int num_bind_values = 0;
-
-	/* try to get the first bind value */
-	bind_value = msLookupHashTable(&layer->bindvals, "1");
-	while(bind_value != NULL) {
-		/* put the bind value on the stack */
-		layer_bind_values[num_bind_values] = bind_value;
-		/* increment the counter */
-		num_bind_values++;
-		/* create a new lookup key */
-		sprintf(bind_key, "%d", num_bind_values+1);
-		/* get the bind_value */
-		bind_value = msLookupHashTable(&layer->bindvals, bind_key);
-	}
-
-    assert(layer != NULL);
-    assert(layer->layerinfo != NULL);
+  msPostGISLayerInfo *layerinfo = NULL;
+  char *strSQL = NULL;
+  PGresult *pgresult = NULL;
+  char** layer_bind_values = (char**)msSmallMalloc(sizeof(char*) * 1000);
+  char* bind_value;
+  char* bind_key = (char*)msSmallMalloc(3);
+
+  int num_bind_values = 0;
+
+  /* try to get the first bind value */
+  bind_value = msLookupHashTable(&layer->bindvals, "1");
+  while(bind_value != NULL) {
+    /* put the bind value on the stack */
+    layer_bind_values[num_bind_values] = bind_value;
+    /* increment the counter */
+    num_bind_values++;
+    /* create a new lookup key */
+    sprintf(bind_key, "%d", num_bind_values+1);
+    /* get the bind_value */
+    bind_value = msLookupHashTable(&layer->bindvals, bind_key);
+  }
 
-    if (layer->debug) {
-        msDebug("msPostGISLayerWhichShapes called.\n");
-    }
+  assert(layer != NULL);
+  assert(layer->layerinfo != NULL);
 
-    /* Fill out layerinfo with our current DATA state. */
-    if ( msPostGISParseData(layer) != MS_SUCCESS) {
-        return MS_FAILURE;
-    }
+  if (layer->debug) {
+    msDebug("msPostGISLayerWhichShapes called.\n");
+  }
 
-    /* 
-    ** This comes *after* parsedata, because parsedata fills in 
-    ** layer->layerinfo.
-    */
-    layerinfo = (msPostGISLayerInfo*) layer->layerinfo;
+  /* Fill out layerinfo with our current DATA state. */
+  if ( msPostGISParseData(layer) != MS_SUCCESS) {
+    return MS_FAILURE;
+  }
 
-    /* Build a SQL query based on our current state. */
-    strSQL = msPostGISBuildSQL(layer, &rect, NULL);
-    if ( ! strSQL ) {
-        msSetError(MS_QUERYERR, "Failed to build query SQL.", "msPostGISLayerWhichShapes()");
-        return MS_FAILURE;
-    }
+  /*
+  ** This comes *after* parsedata, because parsedata fills in
+  ** layer->layerinfo.
+  */
+  layerinfo = (msPostGISLayerInfo*) layer->layerinfo;
 
-    if (layer->debug) {
-        msDebug("msPostGISLayerWhichShapes query: %s\n", strSQL);
-    }
+  /* Build a SQL query based on our current state. */
+  strSQL = msPostGISBuildSQL(layer, &rect, NULL);
+  if ( ! strSQL ) {
+    msSetError(MS_QUERYERR, "Failed to build query SQL.", "msPostGISLayerWhichShapes()");
+    return MS_FAILURE;
+  }
 
-    if(num_bind_values > 0) {
-        pgresult = PQexecParams(layerinfo->pgconn, strSQL, num_bind_values, NULL, (const char**)layer_bind_values, NULL, NULL, 1);
-    } else {
-      pgresult = PQexecParams(layerinfo->pgconn, strSQL,0, NULL, NULL, NULL, NULL, 0);
-    }
+  if (layer->debug) {
+    msDebug("msPostGISLayerWhichShapes query: %s\n", strSQL);
+  }
 
-    /* free bind values */
-    free(bind_key);
-    free(layer_bind_values);
+  if(num_bind_values > 0) {
+    pgresult = PQexecParams(layerinfo->pgconn, strSQL, num_bind_values, NULL, (const char**)layer_bind_values, NULL, NULL, 1);
+  } else {
+    pgresult = PQexecParams(layerinfo->pgconn, strSQL,0, NULL, NULL, NULL, NULL, 0);
+  }
 
-    if ( layer->debug > 1 ) {
-        msDebug("msPostGISLayerWhichShapes query status: %s (%d)\n", PQresStatus(PQresultStatus(pgresult)), PQresultStatus(pgresult)); 
-    }
+  /* free bind values */
+  free(bind_key);
+  free(layer_bind_values);
 
-    /* Something went wrong. */
-    if (!pgresult || PQresultStatus(pgresult) != PGRES_TUPLES_OK) {
-        if ( layer->debug ) {
-	    msDebug("Error (%s) executing query: %s", "msPostGISLayerWhichShapes()\n", PQerrorMessage(layerinfo->pgconn), strSQL);
-	}
-        msSetError(MS_QUERYERR, "Error executing query: %s ", "msPostGISLayerWhichShapes()", PQerrorMessage(layerinfo->pgconn));
-        free(strSQL);
-        if (pgresult) {
-            PQclear(pgresult);
-        }
-        return MS_FAILURE;
-    }
+  if ( layer->debug > 1 ) {
+    msDebug("msPostGISLayerWhichShapes query status: %s (%d)\n", PQresStatus(PQresultStatus(pgresult)), PQresultStatus(pgresult));
+  }
 
+  /* Something went wrong. */
+  if (!pgresult || PQresultStatus(pgresult) != PGRES_TUPLES_OK) {
     if ( layer->debug ) {
-        msDebug("msPostGISLayerWhichShapes got %d records in result.\n", PQntuples(pgresult));
+      msDebug("Error (%s) executing query: %s", "msPostGISLayerWhichShapes()\n", PQerrorMessage(layerinfo->pgconn), strSQL);
+    }
+    msSetError(MS_QUERYERR, "Error executing query: %s ", "msPostGISLayerWhichShapes()", PQerrorMessage(layerinfo->pgconn));
+    free(strSQL);
+    if (pgresult) {
+      PQclear(pgresult);
     }
+    return MS_FAILURE;
+  }
 
-    /* Clean any existing pgresult before storing current one. */
-    if(layerinfo->pgresult) PQclear(layerinfo->pgresult);
-    layerinfo->pgresult = pgresult;
-    
-    /* Clean any existing SQL before storing current. */
-    if(layerinfo->sql) free(layerinfo->sql);
-    layerinfo->sql = strSQL;
-    
-    layerinfo->rownum = 0;
+  if ( layer->debug ) {
+    msDebug("msPostGISLayerWhichShapes got %d records in result.\n", PQntuples(pgresult));
+  }
 
-    return MS_SUCCESS;
+  /* Clean any existing pgresult before storing current one. */
+  if(layerinfo->pgresult) PQclear(layerinfo->pgresult);
+  layerinfo->pgresult = pgresult;
+
+  /* Clean any existing SQL before storing current. */
+  if(layerinfo->sql) free(layerinfo->sql);
+  layerinfo->sql = strSQL;
+
+  layerinfo->rownum = 0;
+
+  return MS_SUCCESS;
 #else
-    msSetError( MS_MISCERR,
-                "PostGIS support is not available.",
-                "msPostGISLayerWhichShapes()");
-    return MS_FAILURE;
+  msSetError( MS_MISCERR,
+              "PostGIS support is not available.",
+              "msPostGISLayerWhichShapes()");
+  return MS_FAILURE;
 #endif
 }
 
@@ -2507,194 +2570,191 @@ int msPostGISLayerWhichShapes(layerObj *layer, rectObj rect, int isQuery) {
 **
 ** Registered vtable->LayerNextShape function.
 */
-int msPostGISLayerNextShape(layerObj *layer, shapeObj *shape) {
+int msPostGISLayerNextShape(layerObj *layer, shapeObj *shape)
+{
 #ifdef USE_POSTGIS
-    msPostGISLayerInfo  *layerinfo;
+  msPostGISLayerInfo  *layerinfo;
 
-    if (layer->debug) {
-        msDebug("msPostGISLayerNextShape called.\n");
-    }
+  if (layer->debug) {
+    msDebug("msPostGISLayerNextShape called.\n");
+  }
 
-    assert(layer != NULL);
-    assert(layer->layerinfo != NULL);
+  assert(layer != NULL);
+  assert(layer->layerinfo != NULL);
 
-    layerinfo = (msPostGISLayerInfo*) layer->layerinfo;
+  layerinfo = (msPostGISLayerInfo*) layer->layerinfo;
 
-    shape->type = MS_SHAPE_NULL;
+  shape->type = MS_SHAPE_NULL;
 
-    /* 
-    ** Roll through pgresult until we hit non-null shape (usually right away).
-    */
-    while (shape->type == MS_SHAPE_NULL) {
-        if (layerinfo->rownum < PQntuples(layerinfo->pgresult)) {
-            int rv;
-            /* Retrieve this shape, cursor access mode. */
-            rv = msPostGISReadShape(layer, shape);
-            if( shape->type != MS_SHAPE_NULL ) {
-                (layerinfo->rownum)++; /* move to next shape */
-                return MS_SUCCESS;
-            } else {
-                (layerinfo->rownum)++; /* move to next shape */
-            }
-        } else {
-            return MS_DONE;
-        }
+  /*
+  ** Roll through pgresult until we hit non-null shape (usually right away).
+  */
+  while (shape->type == MS_SHAPE_NULL) {
+    if (layerinfo->rownum < PQntuples(layerinfo->pgresult)) {
+      /* Retrieve this shape, cursor access mode. */
+      msPostGISReadShape(layer, shape);
+      if( shape->type != MS_SHAPE_NULL ) {
+        (layerinfo->rownum)++; /* move to next shape */
+        return MS_SUCCESS;
+      } else {
+        (layerinfo->rownum)++; /* move to next shape */
+      }
+    } else {
+      return MS_DONE;
     }
+  }
 
-    /* Found nothing, clean up and exit. */
-    msFreeShape(shape);
+  /* Found nothing, clean up and exit. */
+  msFreeShape(shape);
 
-    return MS_FAILURE;
+  return MS_FAILURE;
 #else
-    msSetError( MS_MISCERR,
-                "PostGIS support is not available.",
-                "msPostGISLayerNextShape()");
-    return MS_FAILURE;
+  msSetError( MS_MISCERR,
+              "PostGIS support is not available.",
+              "msPostGISLayerNextShape()");
+  return MS_FAILURE;
 #endif
 }
 
 /*
 ** msPostGISLayerGetShape()
 **
-** Registered vtable->LayerGetShape function. For pulling from a prepared and 
+** Registered vtable->LayerGetShape function. For pulling from a prepared and
 ** undisposed result set.
 */
-int msPostGISLayerGetShape(layerObj *layer, shapeObj *shape, resultObj *record) {
+int msPostGISLayerGetShape(layerObj *layer, shapeObj *shape, resultObj *record)
+{
 #ifdef USE_POSTGIS
-    
-    PGresult *pgresult = NULL;
-    msPostGISLayerInfo *layerinfo = NULL;
-    int result = MS_SUCCESS;
 
-    long shapeindex = record->shapeindex;
-    int resultindex = record->resultindex; 
+  PGresult *pgresult = NULL;
+  msPostGISLayerInfo *layerinfo = NULL;
 
-    assert(layer != NULL);
-    assert(layer->layerinfo != NULL);
+  long shapeindex = record->shapeindex;
+  int resultindex = record->resultindex;
 
-    if (layer->debug) {
-        msDebug("msPostGISLayerGetShape called for record = %i\n", resultindex);
-    }
+  assert(layer != NULL);
+  assert(layer->layerinfo != NULL);
 
-    /* If resultindex is set, fetch the shape from the resultcache, otherwise fetch it from the DB  */
-    if (resultindex >= 0)
-    {
-        int status;
+  if (layer->debug) {
+    msDebug("msPostGISLayerGetShape called for record = %i\n", resultindex);
+  }
 
-        layerinfo = (msPostGISLayerInfo*) layer->layerinfo;
+  /* If resultindex is set, fetch the shape from the resultcache, otherwise fetch it from the DB  */
+  if (resultindex >= 0) {
+    int status;
 
-        /* Check the validity of the open result. */
-        pgresult = layerinfo->pgresult;
-        if ( ! pgresult ) {
-            msSetError( MS_MISCERR,
-                        "PostgreSQL result set is null.",
-                        "msPostGISLayerGetShape()");
-            return MS_FAILURE;
-        }
-        status = PQresultStatus(pgresult);
-        if ( layer->debug > 1 ) {
-            msDebug("msPostGISLayerGetShape query status: %s (%d)\n", PQresStatus(status), status);
-        }    
-        if( ! ( status == PGRES_COMMAND_OK || status == PGRES_TUPLES_OK) ) {
-            msSetError( MS_MISCERR,
-                        "PostgreSQL result set is not ready.",
-                        "msPostGISLayerGetShape()");
-            return MS_FAILURE;
-        }
+    layerinfo = (msPostGISLayerInfo*) layer->layerinfo;
 
-        /* Check the validity of the requested record number. */
-        if( resultindex >= PQntuples(pgresult) ) {
-            msDebug("msPostGISLayerGetShape got request for (%d) but only has %d tuples.\n", resultindex, PQntuples(pgresult));
-            msSetError( MS_MISCERR,
-                        "Got request larger than result set.",
-                        "msPostGISLayerGetShape()");
-            return MS_FAILURE;
-        }
+    /* Check the validity of the open result. */
+    pgresult = layerinfo->pgresult;
+    if ( ! pgresult ) {
+      msSetError( MS_MISCERR,
+                  "PostgreSQL result set is null.",
+                  "msPostGISLayerGetShape()");
+      return MS_FAILURE;
+    }
+    status = PQresultStatus(pgresult);
+    if ( layer->debug > 1 ) {
+      msDebug("msPostGISLayerGetShape query status: %s (%d)\n", PQresStatus(status), status);
+    }
+    if( ! ( status == PGRES_COMMAND_OK || status == PGRES_TUPLES_OK) ) {
+      msSetError( MS_MISCERR,
+                  "PostgreSQL result set is not ready.",
+                  "msPostGISLayerGetShape()");
+      return MS_FAILURE;
+    }
+
+    /* Check the validity of the requested record number. */
+    if( resultindex >= PQntuples(pgresult) ) {
+      msDebug("msPostGISLayerGetShape got request for (%d) but only has %d tuples.\n", resultindex, PQntuples(pgresult));
+      msSetError( MS_MISCERR,
+                  "Got request larger than result set.",
+                  "msPostGISLayerGetShape()");
+      return MS_FAILURE;
+    }
 
-        layerinfo->rownum = resultindex; /* Only return one result. */
+    layerinfo->rownum = resultindex; /* Only return one result. */
 
-        /* We don't know the shape type until we read the geometry. */
-        shape->type = MS_SHAPE_NULL;
+    /* We don't know the shape type until we read the geometry. */
+    shape->type = MS_SHAPE_NULL;
 
-        /* Return the shape, cursor access mode. */
-        result = msPostGISReadShape(layer, shape);
+    /* Return the shape, cursor access mode. */
+    msPostGISReadShape(layer, shape);
 
-        return (shape->type == MS_SHAPE_NULL) ? MS_FAILURE : MS_SUCCESS;
-    }
-    else /* no resultindex, fetch the shape from the DB */
-    {
-        int num_tuples;
-        char *strSQL = 0;
+    return (shape->type == MS_SHAPE_NULL) ? MS_FAILURE : MS_SUCCESS;
+  } else { /* no resultindex, fetch the shape from the DB */
+    int num_tuples;
+    char *strSQL = 0;
 
-        /* Fill out layerinfo with our current DATA state. */
-        if ( msPostGISParseData(layer) != MS_SUCCESS) {
-            return MS_FAILURE;
-        }
+    /* Fill out layerinfo with our current DATA state. */
+    if ( msPostGISParseData(layer) != MS_SUCCESS) {
+      return MS_FAILURE;
+    }
 
-        /* 
-        ** This comes *after* parsedata, because parsedata fills in 
-        ** layer->layerinfo.
-        */
-        layerinfo = (msPostGISLayerInfo*) layer->layerinfo;
-
-        /* Build a SQL query based on our current state. */
-        strSQL = msPostGISBuildSQL(layer, 0, &shapeindex);
-        if ( ! strSQL ) {
-            msSetError(MS_QUERYERR, "Failed to build query SQL.", "msPostGISLayerGetShape()");
-            return MS_FAILURE;
-        }
+    /*
+    ** This comes *after* parsedata, because parsedata fills in
+    ** layer->layerinfo.
+    */
+    layerinfo = (msPostGISLayerInfo*) layer->layerinfo;
 
-        if (layer->debug) {
-            msDebug("msPostGISLayerGetShape query: %s\n", strSQL);
-        }
+    /* Build a SQL query based on our current state. */
+    strSQL = msPostGISBuildSQL(layer, 0, &shapeindex);
+    if ( ! strSQL ) {
+      msSetError(MS_QUERYERR, "Failed to build query SQL.", "msPostGISLayerGetShape()");
+      return MS_FAILURE;
+    }
 
-        pgresult = PQexecParams(layerinfo->pgconn, strSQL,0, NULL, NULL, NULL, NULL, 0);
+    if (layer->debug) {
+      msDebug("msPostGISLayerGetShape query: %s\n", strSQL);
+    }
 
-        /* Something went wrong. */
-        if ( (!pgresult) || (PQresultStatus(pgresult) != PGRES_TUPLES_OK) ) {
-	    if ( layer->debug ) {
-	        msDebug("Error (%s) executing SQL: %s", "msPostGISLayerGetShape()\n", PQerrorMessage(layerinfo->pgconn), strSQL );
-	    }            
-            msSetError(MS_QUERYERR, "Error executing SQL: %s", "msPostGISLayerGetShape()", PQerrorMessage(layerinfo->pgconn));
+    pgresult = PQexecParams(layerinfo->pgconn, strSQL,0, NULL, NULL, NULL, NULL, 0);
 
-            if (pgresult) {
-                PQclear(pgresult);
-            }
-            free(strSQL);
+    /* Something went wrong. */
+    if ( (!pgresult) || (PQresultStatus(pgresult) != PGRES_TUPLES_OK) ) {
+      if ( layer->debug ) {
+        msDebug("Error (%s) executing SQL: %s", "msPostGISLayerGetShape()\n", PQerrorMessage(layerinfo->pgconn), strSQL );
+      }
+      msSetError(MS_QUERYERR, "Error executing SQL: %s", "msPostGISLayerGetShape()", PQerrorMessage(layerinfo->pgconn));
 
-            return MS_FAILURE;
-        }
+      if (pgresult) {
+        PQclear(pgresult);
+      }
+      free(strSQL);
 
-        /* Clean any existing pgresult before storing current one. */
-        if(layerinfo->pgresult) PQclear(layerinfo->pgresult);
-        layerinfo->pgresult = pgresult;
+      return MS_FAILURE;
+    }
 
-        /* Clean any existing SQL before storing current. */
-        if(layerinfo->sql) free(layerinfo->sql);
-        layerinfo->sql = strSQL;
+    /* Clean any existing pgresult before storing current one. */
+    if(layerinfo->pgresult) PQclear(layerinfo->pgresult);
+    layerinfo->pgresult = pgresult;
 
-        layerinfo->rownum = 0; /* Only return one result. */
+    /* Clean any existing SQL before storing current. */
+    if(layerinfo->sql) free(layerinfo->sql);
+    layerinfo->sql = strSQL;
 
-        /* We don't know the shape type until we read the geometry. */
-        shape->type = MS_SHAPE_NULL;
+    layerinfo->rownum = 0; /* Only return one result. */
 
-        num_tuples = PQntuples(pgresult);
-        if (layer->debug) {
-            msDebug("msPostGISLayerGetShape number of records: %d\n", num_tuples);
-        }
+    /* We don't know the shape type until we read the geometry. */
+    shape->type = MS_SHAPE_NULL;
 
-        if (num_tuples > 0) {
-            /* Get shape in random access mode. */
-            result = msPostGISReadShape(layer, shape);
-        }
+    num_tuples = PQntuples(pgresult);
+    if (layer->debug) {
+      msDebug("msPostGISLayerGetShape number of records: %d\n", num_tuples);
+    }
 
-        return (shape->type == MS_SHAPE_NULL) ? MS_FAILURE : ( (num_tuples > 0) ? MS_SUCCESS : MS_DONE );
+    if (num_tuples > 0) {
+      /* Get shape in random access mode. */
+      msPostGISReadShape(layer, shape);
     }
+
+    return (shape->type == MS_SHAPE_NULL) ? MS_FAILURE : ( (num_tuples > 0) ? MS_SUCCESS : MS_DONE );
+  }
 #else
-    msSetError( MS_MISCERR,
-                "PostGIS support is not available.",
-                "msPostGISLayerGetShape()");
-    return MS_FAILURE;
+  msSetError( MS_MISCERR,
+              "PostGIS support is not available.",
+              "msPostGISLayerGetShape()");
+  return MS_FAILURE;
 #endif
 }
 
@@ -2702,14 +2762,14 @@ int msPostGISLayerGetShape(layerObj *layer, shapeObj *shape, resultObj *record)
  *                     msPostGISPassThroughFieldDefinitions()
  *
  * Pass the field definitions through to the layer metadata in the
- * "gml_[item]_{type,width,precision}" set of metadata items for 
+ * "gml_[item]_{type,width,precision}" set of metadata items for
  * defining fields.
  **********************************************************************/
 
 /* These are the OIDs for some builtin types, as returned by PQftype(). */
 /* They were copied from pg_type.h in src/include/catalog/pg_type.h */
 
-#ifndef BOOLOID 
+#ifndef BOOLOID
 #define BOOLOID                 16
 #define BYTEAOID                17
 #define CHAROID                 18
@@ -2733,88 +2793,87 @@ int msPostGISLayerGetShape(layerObj *layer, shapeObj *shape, resultObj *record)
 #define VARCHARARRAYOID         1015
 #define FLOAT4ARRAYOID          1021
 #define FLOAT8ARRAYOID          1022
-#define BPCHAROID		1042
-#define VARCHAROID		1043
-#define DATEOID			1082
-#define TIMEOID			1083
-#define TIMESTAMPOID	        1114
-#define TIMESTAMPTZOID	        1184
+#define BPCHAROID   1042
+#define VARCHAROID    1043
+#define DATEOID     1082
+#define TIMEOID     1083
+#define TIMESTAMPOID          1114
+#define TIMESTAMPTZOID          1184
 #define NUMERICOID              1700
 #endif
 
 #ifdef USE_POSTGIS
-static void 
-msPostGISPassThroughFieldDefinitions( layerObj *layer, 
+static void
+msPostGISPassThroughFieldDefinitions( layerObj *layer,
                                       PGresult *pgresult )
 
 {
-    int i, numitems = PQnfields(pgresult);
-    msPostGISLayerInfo *layerinfo = layer->layerinfo;
-
-    for(i=0;i<numitems;i++)
-    {
-        int oid, fmod;
-        const char *gml_type = "Character";
-        const char *item = PQfname(pgresult,i);
-        char md_item_name[256];
-        char gml_width[32], gml_precision[32];
-        
-        gml_width[0] = '\0';
-        gml_precision[0] = '\0';
-
-        /* skip geometry column */
-        if( strcmp(item, layerinfo->geomcolumn) == 0 )
-            continue;
-
-        oid = PQftype(pgresult,i);
-        fmod = PQfmod(pgresult,i);
-
-        if( (oid == BPCHAROID || oid == VARCHAROID) && fmod >= 4 ) {
-            sprintf( gml_width, "%d", fmod-4 ); 
-
-        } else if( oid == BOOLOID ) {
-            gml_type = "Integer";
-            sprintf( gml_width, "%d", 1 ); 
-
-        } else if( oid == INT2OID ) {
-            gml_type = "Integer";
-            sprintf( gml_width, "%d", 5 ); 
-
-        } else if( oid == INT4OID || oid == INT8OID ) {
-            gml_type = "Integer";
-
-        } else if( oid == FLOAT4OID || oid == FLOAT8OID ) {
-            gml_type = "Real";
-            
-        } else if( oid == NUMERICOID ) {
-            gml_type = "Real";
-
-            if( fmod >= 4 && ((fmod - 4) & 0xFFFF) == 0 ) {
-                gml_type = "Integer";
-                sprintf( gml_width, "%d", (fmod - 4) >> 16 );
-            } else if( fmod >= 4 ) {
-                sprintf( gml_width, "%d", (fmod - 4) >> 16 );
-                sprintf( gml_precision, "%d", ((fmod-4) & 0xFFFF) );
-            }
-        } else if( oid == DATEOID 
-                   || oid == TIMESTAMPOID || oid == TIMESTAMPTZOID ) {
-            gml_type = "Date";
-        }
-            
-        snprintf( md_item_name, sizeof(md_item_name), "gml_%s_type", item );
-        if( msOWSLookupMetadata(&(layer->metadata), "G", "type") == NULL )
-            msInsertHashTable(&(layer->metadata), md_item_name, gml_type );
-        
-        snprintf( md_item_name, sizeof(md_item_name), "gml_%s_width", item );
-        if( strlen(gml_width) > 0 
-            && msOWSLookupMetadata(&(layer->metadata), "G", "width") == NULL )
-            msInsertHashTable(&(layer->metadata), md_item_name, gml_width );
-
-        snprintf( md_item_name, sizeof(md_item_name), "gml_%s_precision",item );
-        if( strlen(gml_precision) > 0 
-            && msOWSLookupMetadata(&(layer->metadata), "G", "precision")==NULL )
-            msInsertHashTable(&(layer->metadata), md_item_name, gml_precision );
+  int i, numitems = PQnfields(pgresult);
+  msPostGISLayerInfo *layerinfo = layer->layerinfo;
+
+  for(i=0; i<numitems; i++) {
+    int oid, fmod;
+    const char *gml_type = "Character";
+    const char *item = PQfname(pgresult,i);
+    char md_item_name[256];
+    char gml_width[32], gml_precision[32];
+
+    gml_width[0] = '\0';
+    gml_precision[0] = '\0';
+
+    /* skip geometry column */
+    if( strcmp(item, layerinfo->geomcolumn) == 0 )
+      continue;
+
+    oid = PQftype(pgresult,i);
+    fmod = PQfmod(pgresult,i);
+
+    if( (oid == BPCHAROID || oid == VARCHAROID) && fmod >= 4 ) {
+      sprintf( gml_width, "%d", fmod-4 );
+
+    } else if( oid == BOOLOID ) {
+      gml_type = "Integer";
+      sprintf( gml_width, "%d", 1 );
+
+    } else if( oid == INT2OID ) {
+      gml_type = "Integer";
+      sprintf( gml_width, "%d", 5 );
+
+    } else if( oid == INT4OID || oid == INT8OID ) {
+      gml_type = "Integer";
+
+    } else if( oid == FLOAT4OID || oid == FLOAT8OID ) {
+      gml_type = "Real";
+
+    } else if( oid == NUMERICOID ) {
+      gml_type = "Real";
+
+      if( fmod >= 4 && ((fmod - 4) & 0xFFFF) == 0 ) {
+        gml_type = "Integer";
+        sprintf( gml_width, "%d", (fmod - 4) >> 16 );
+      } else if( fmod >= 4 ) {
+        sprintf( gml_width, "%d", (fmod - 4) >> 16 );
+        sprintf( gml_precision, "%d", ((fmod-4) & 0xFFFF) );
+      }
+    } else if( oid == DATEOID
+               || oid == TIMESTAMPOID || oid == TIMESTAMPTZOID ) {
+      gml_type = "Date";
     }
+
+    snprintf( md_item_name, sizeof(md_item_name), "gml_%s_type", item );
+    if( msOWSLookupMetadata(&(layer->metadata), "G", "type") == NULL )
+      msInsertHashTable(&(layer->metadata), md_item_name, gml_type );
+
+    snprintf( md_item_name, sizeof(md_item_name), "gml_%s_width", item );
+    if( strlen(gml_width) > 0
+        && msOWSLookupMetadata(&(layer->metadata), "G", "width") == NULL )
+      msInsertHashTable(&(layer->metadata), md_item_name, gml_width );
+
+    snprintf( md_item_name, sizeof(md_item_name), "gml_%s_precision",item );
+    if( strlen(gml_precision) > 0
+        && msOWSLookupMetadata(&(layer->metadata), "G", "precision")==NULL )
+      msInsertHashTable(&(layer->metadata), md_item_name, gml_precision );
+  }
 }
 #endif /* defined(USE_POSTGIS) */
 
@@ -2826,550 +2885,498 @@ msPostGISPassThroughFieldDefinitions( layerObj *layer,
 ** system tables, we just run a zero-cost query and read out of the
 ** result header.
 */
-int msPostGISLayerGetItems(layerObj *layer) {
+int msPostGISLayerGetItems(layerObj *layer)
+{
 #ifdef USE_POSTGIS
-    msPostGISLayerInfo *layerinfo = NULL;
-    static char *strSQLTemplate = "select * from %s where false limit 0";
-    PGresult *pgresult = NULL;
-    char *col = NULL;
-    char *sql = NULL;
-    char *strFrom = NULL;
-    char found_geom = 0;
-    const char *value;
-    int t, item_num;
-    rectObj rect;
-
-    /* A useless rectangle for our useless query */
-    rect.minx = rect.miny = rect.maxx = rect.maxy = 0.0;
-
-    assert(layer != NULL);
-    assert(layer->layerinfo != NULL);
-    
-    layerinfo = (msPostGISLayerInfo*) layer->layerinfo;
-    
-    assert(layerinfo->pgconn);
+  msPostGISLayerInfo *layerinfo = NULL;
+  static char *strSQLTemplate = "select * from %s where false limit 0";
+  PGresult *pgresult = NULL;
+  char *col = NULL;
+  char *sql = NULL;
+  char *strFrom = NULL;
+  char found_geom = 0;
+  const char *value;
+  int t, item_num;
+  rectObj rect;
 
-    if (layer->debug) {
-        msDebug("msPostGISLayerGetItems called.\n");
-    }
+  /* A useless rectangle for our useless query */
+  rect.minx = rect.miny = rect.maxx = rect.maxy = 0.0;
 
-    /* Fill out layerinfo with our current DATA state. */
-    if ( msPostGISParseData(layer) != MS_SUCCESS) {
-        return MS_FAILURE;
-    }
+  assert(layer != NULL);
+  assert(layer->layerinfo != NULL);
 
-    layerinfo = (msPostGISLayerInfo*) layer->layerinfo;
+  layerinfo = (msPostGISLayerInfo*) layer->layerinfo;
 
-    /* This allocates a fresh string, so remember to free it... */
-    strFrom = msPostGISReplaceBoxToken(layer, &rect, layerinfo->fromsource);
+  assert(layerinfo->pgconn);
 
-    /*
-    ** Both the "table" and "(select ...) as sub" cases can be handled with the 
-    ** same SQL.
-    */
-    sql = (char*) msSmallMalloc(strlen(strSQLTemplate) + strlen(strFrom));
-    sprintf(sql, strSQLTemplate, strFrom);
-    free(strFrom);
+  if (layer->debug) {
+    msDebug("msPostGISLayerGetItems called.\n");
+  }
 
-    if (layer->debug) {
-        msDebug("msPostGISLayerGetItems executing SQL: %s\n", sql);
-    }
+  /* Fill out layerinfo with our current DATA state. */
+  if ( msPostGISParseData(layer) != MS_SUCCESS) {
+    return MS_FAILURE;
+  }
 
-    pgresult = PQexecParams(layerinfo->pgconn, sql,0, NULL, NULL, NULL, NULL, 0);
-    
-    if ( (!pgresult) || (PQresultStatus(pgresult) != PGRES_TUPLES_OK) ) {
-        if ( layer->debug ) {
-	  msDebug("Error (%s) executing SQL: %s", "msPostGISLayerGetItems()\n", PQerrorMessage(layerinfo->pgconn), sql);
-	}
-        msSetError(MS_QUERYERR, "Error executing SQL: %s", "msPostGISLayerGetItems()", PQerrorMessage(layerinfo->pgconn));
-        if (pgresult) {
-            PQclear(pgresult);
-        }
-        free(sql);
-        return MS_FAILURE;
-    }
+  layerinfo = (msPostGISLayerInfo*) layer->layerinfo;
 
-    free(sql);
+  /* This allocates a fresh string, so remember to free it... */
+  strFrom = msPostGISReplaceBoxToken(layer, &rect, layerinfo->fromsource);
 
-    layer->numitems = PQnfields(pgresult) - 1; /* dont include the geometry column (last entry)*/
-    layer->items = msSmallMalloc(sizeof(char*) * (layer->numitems + 1)); /* +1 in case there is a problem finding geometry column */
+  /*
+  ** Both the "table" and "(select ...) as sub" cases can be handled with the
+  ** same SQL.
+  */
+  sql = (char*) msSmallMalloc(strlen(strSQLTemplate) + strlen(strFrom));
+  sprintf(sql, strSQLTemplate, strFrom);
+  free(strFrom);
 
-    found_geom = 0; /* havent found the geom field */
-    item_num = 0;
+  if (layer->debug) {
+    msDebug("msPostGISLayerGetItems executing SQL: %s\n", sql);
+  }
 
-    for (t = 0; t < PQnfields(pgresult); t++) {
-        col = PQfname(pgresult, t);
-        if ( strcmp(col, layerinfo->geomcolumn) != 0 ) {
-            /* this isnt the geometry column */
-            layer->items[item_num] = msStrdup(col);
-            item_num++;
-        } else {
-            found_geom = 1;
-        }
+  pgresult = PQexecParams(layerinfo->pgconn, sql,0, NULL, NULL, NULL, NULL, 0);
+
+  if ( (!pgresult) || (PQresultStatus(pgresult) != PGRES_TUPLES_OK) ) {
+    if ( layer->debug ) {
+      msDebug("Error (%s) executing SQL: %s", "msPostGISLayerGetItems()\n", PQerrorMessage(layerinfo->pgconn), sql);
+    }
+    msSetError(MS_QUERYERR, "Error executing SQL: %s", "msPostGISLayerGetItems()", PQerrorMessage(layerinfo->pgconn));
+    if (pgresult) {
+      PQclear(pgresult);
     }
+    free(sql);
+    return MS_FAILURE;
+  }
 
-    /*
-    ** consider populating the field definitions in metadata. 
-    */
-    if((value = msOWSLookupMetadata(&(layer->metadata), "G", "types")) != NULL
-       && strcasecmp(value,"auto") == 0 )
-        msPostGISPassThroughFieldDefinitions( layer, pgresult );
+  free(sql);
 
-    /*
-    ** Cleanup 
-    */
-    PQclear(pgresult);
+  layer->numitems = PQnfields(pgresult) - 1; /* dont include the geometry column (last entry)*/
+  layer->items = msSmallMalloc(sizeof(char*) * (layer->numitems + 1)); /* +1 in case there is a problem finding geometry column */
 
-    if (!found_geom) {
-        msSetError(MS_QUERYERR, "Tried to find the geometry column in the database, but couldn't find it.  Is it mis-capitalized? '%s'", "msPostGISLayerGetItems()", layerinfo->geomcolumn);
-        return MS_FAILURE;
+  found_geom = 0; /* havent found the geom field */
+  item_num = 0;
+
+  for (t = 0; t < PQnfields(pgresult); t++) {
+    col = PQfname(pgresult, t);
+    if ( strcmp(col, layerinfo->geomcolumn) != 0 ) {
+      /* this isnt the geometry column */
+      layer->items[item_num] = msStrdup(col);
+      item_num++;
+    } else {
+      found_geom = 1;
     }
+  }
 
-    return msPostGISLayerInitItemInfo(layer);
-#else
-    msSetError( MS_MISCERR,
-                "PostGIS support is not available.",
-                "msPostGISLayerGetItems()");
+  /*
+  ** consider populating the field definitions in metadata.
+  */
+  if((value = msOWSLookupMetadata(&(layer->metadata), "G", "types")) != NULL
+      && strcasecmp(value,"auto") == 0 )
+    msPostGISPassThroughFieldDefinitions( layer, pgresult );
+
+  /*
+  ** Cleanup
+  */
+  PQclear(pgresult);
+
+  if (!found_geom) {
+    msSetError(MS_QUERYERR, "Tried to find the geometry column in the database, but couldn't find it.  Is it mis-capitalized? '%s'", "msPostGISLayerGetItems()", layerinfo->geomcolumn);
     return MS_FAILURE;
+  }
+
+  return msPostGISLayerInitItemInfo(layer);
+#else
+  msSetError( MS_MISCERR,
+              "PostGIS support is not available.",
+              "msPostGISLayerGetItems()");
+  return MS_FAILURE;
 #endif
 }
 
 /*
-** msPostGISLayerGetExtent()
-**
-** Registered vtable->LayerGetExtent function.
-**
-** TODO: Update to use proper PostGIS functions to pull
-** extent quickly and accurately when available.
-*/
-int msPostGISLayerGetExtent(layerObj *layer, rectObj *extent) {
-    if (layer->debug) {
-        msDebug("msPOSTGISLayerGetExtent called.\n");
-    }
+ * make sure that the timestring is complete and acceptable
+ * to the date_trunc function :
+ * - if the resolution is year (2004) or month (2004-01),
+ * a complete string for time would be 2004-01-01
+ * - if the resolluion is hour or minute (2004-01-01 15), a
+ * complete time is 2004-01-01 15:00:00
+ */
+int postgresTimeStampForTimeString(const char *timestring, char *dest, size_t destsize)
+{
+  int nlength = strlen(timestring);
+  int timeresolution = msTimeGetResolution(timestring);
+  int bNoDate = (*timestring == 'T');
+  if (timeresolution < 0)
+    return MS_FALSE;
+
+  switch(timeresolution) {
+    case TIME_RESOLUTION_YEAR:
+      if (timestring[nlength-1] != '-') {
+        snprintf(dest, destsize,"date '%s-01-01'",timestring);
+      } else {
+        snprintf(dest, destsize,"date '%s01-01'",timestring);
+      }
+      break;
+    case TIME_RESOLUTION_MONTH:
+      if (timestring[nlength-1] != '-') {
+        snprintf(dest, destsize,"date '%s-01'",timestring);
+      } else {
+        snprintf(dest, destsize,"date '%s01'",timestring);
+      }
+      break;
+    case TIME_RESOLUTION_DAY:
+      snprintf(dest, destsize,"date '%s'",timestring);
+      break;
+    case TIME_RESOLUTION_HOUR:
+      if (timestring[nlength-1] != ':') {
+        if(bNoDate)
+          snprintf(dest, destsize,"time '%s:00:00'", timestring);
+        else
+          snprintf(dest, destsize,"timestamp '%s:00:00'", timestring);
+      } else {
+        if(bNoDate)
+          snprintf(dest, destsize,"time '%s00:00'", timestring);
+        else
+          snprintf(dest, destsize,"timestamp '%s00:00'", timestring);
+      }
+      break;
+    case TIME_RESOLUTION_MINUTE:
+      if (timestring[nlength-1] != ':') {
+        if(bNoDate)
+          snprintf(dest, destsize,"time '%s:00'", timestring);
+        else
+          snprintf(dest, destsize,"timestamp '%s:00'", timestring);
+      } else {
+        if(bNoDate)
+          snprintf(dest, destsize,"time '%s00'", timestring);
+        else
+          snprintf(dest, destsize,"timestamp '%s00'", timestring);
+      }
+      break;
+    case TIME_RESOLUTION_SECOND:
+      if(bNoDate)
+         snprintf(dest, destsize,"time '%s'", timestring);
+      else
+         snprintf(dest, destsize,"timestamp '%s'", timestring);
+      break;
+    default:
+      return MS_FAILURE;
+  }
+  return MS_SUCCESS;
 
-    extent->minx = extent->miny = -1.0 * FLT_MAX ;
-    extent->maxx = extent->maxy = FLT_MAX;
+}
 
-    return MS_SUCCESS;
 
+/*
+ * create a postgresql where clause for the given timestring, taking into account
+ * the resolution (e.g. second, day, month...) of the given timestring
+ * we apply the date_trunc function on the given timestring and not on the time
+ * column in order for postgres to take advantage of an eventual index on the
+ * time column
+ *
+ * the generated sql is
+ *
+ * (
+ *    timecol >= date_trunc(timestring,resolution)
+ *      and
+ *    timecol < date_trunc(timestring,resolution) + interval '1 resolution'
+ * )
+ */
+int createPostgresTimeCompareSimple(const char *timecol, const char *timestring, char *dest, size_t destsize)
+{
+  int timeresolution = msTimeGetResolution(timestring);
+  char timeStamp[100];
+  char *interval;
+  if (timeresolution < 0)
+    return MS_FALSE;
+  postgresTimeStampForTimeString(timestring,timeStamp,100);
+
+  switch(timeresolution) {
+    case TIME_RESOLUTION_YEAR:
+      interval = "year";
+      break;
+    case TIME_RESOLUTION_MONTH:
+      interval = "month";
+      break;
+    case TIME_RESOLUTION_DAY:
+      interval = "day";
+      break;
+    case TIME_RESOLUTION_HOUR:
+      interval = "hour";
+      break;
+    case TIME_RESOLUTION_MINUTE:
+      interval = "minute";
+      break;
+    case TIME_RESOLUTION_SECOND:
+      interval = "second";
+      break;
+    default:
+      return MS_FAILURE;
+  }
+  snprintf(dest, destsize,"(%s >= date_trunc('%s',%s) and %s < date_trunc('%s',%s) + interval '1 %s')",
+           timecol, interval, timeStamp, timecol, interval, timeStamp, interval);
+  return MS_SUCCESS;
+}
+
+/*
+ * create a postgresql where clause for the range given by the two input timestring,
+ * taking into account the resolution (e.g. second, day, month...) of each of the
+ * given timestrings (both timestrings can have different resolutions, although I don't
+ * know if that's a valid TIME range
+ * we apply the date_trunc function on the given timestrings and not on the time
+ * column in order for postgres to take advantage of an eventual index on the
+ * time column
+ *
+ * the generated sql is
+ *
+ * (
+ *    timecol >= date_trunc(mintimestring,minresolution)
+ *      and
+ *    timecol < date_trunc(maxtimestring,maxresolution) + interval '1 maxresolution'
+ * )
+ */
+int createPostgresTimeCompareRange(const char *timecol, const char *mintime, const char *maxtime,
+                                   char *dest, size_t destsize)
+{
+  int mintimeresolution = msTimeGetResolution(mintime);
+  int maxtimeresolution = msTimeGetResolution(maxtime);
+  char minTimeStamp[100];
+  char maxTimeStamp[100];
+  char *minTimeInterval,*maxTimeInterval;
+  if (mintimeresolution < 0 || maxtimeresolution < 0)
+    return MS_FALSE;
+  postgresTimeStampForTimeString(mintime,minTimeStamp,100);
+  postgresTimeStampForTimeString(maxtime,maxTimeStamp,100);
+
+  switch(maxtimeresolution) {
+    case TIME_RESOLUTION_YEAR:
+      maxTimeInterval = "year";
+      break;
+    case TIME_RESOLUTION_MONTH:
+      maxTimeInterval = "month";
+      break;
+    case TIME_RESOLUTION_DAY:
+      maxTimeInterval = "day";
+      break;
+    case TIME_RESOLUTION_HOUR:
+      maxTimeInterval = "hour";
+      break;
+    case TIME_RESOLUTION_MINUTE:
+      maxTimeInterval = "minute";
+      break;
+    case TIME_RESOLUTION_SECOND:
+      maxTimeInterval = "second";
+      break;
+    default:
+      return MS_FAILURE;
+  }
+  switch(mintimeresolution) {
+    case TIME_RESOLUTION_YEAR:
+      minTimeInterval = "year";
+      break;
+    case TIME_RESOLUTION_MONTH:
+      minTimeInterval = "month";
+      break;
+    case TIME_RESOLUTION_DAY:
+      minTimeInterval = "day";
+      break;
+    case TIME_RESOLUTION_HOUR:
+      minTimeInterval = "hour";
+      break;
+    case TIME_RESOLUTION_MINUTE:
+      minTimeInterval = "minute";
+      break;
+    case TIME_RESOLUTION_SECOND:
+      minTimeInterval = "second";
+      break;
+    default:
+      return MS_FAILURE;
+  }
+  snprintf(dest, destsize,"(%s >= date_trunc('%s',%s) and %s < date_trunc('%s',%s) + interval '1 %s')",
+           timecol, minTimeInterval, minTimeStamp,
+           timecol, maxTimeInterval, maxTimeStamp, maxTimeInterval);
+  return MS_SUCCESS;
 }
 
 int msPostGISLayerSetTimeFilter(layerObj *lp, const char *timestring, const char *timefield)
 {
-    char *tmpstimestring = NULL;
-    char *timeresolution = NULL;
-    int timesresol = -1;
-    char **atimes, **tokens = NULL;
-    int numtimes=0,i=0,ntmp=0,nlength=0;
-    size_t buffer_size = 512;
-    char buffer[512], bufferTmp[512];
-
-    buffer[0] = '\0';
-    bufferTmp[0] = '\0';
-
-    if (!lp || !timestring || !timefield)
-      return MS_FALSE;
+  char **atimes, **aranges = NULL;
+  int numtimes=0,i=0,numranges=0;
+  size_t buffer_size = 512;
+  char buffer[512], bufferTmp[512];
 
-    if (strstr(timestring, ",") == NULL && 
-        strstr(timestring, "/") == NULL) /* discrete time */
-      tmpstimestring = msStrdup(timestring);
-    else
-    {
-        atimes = msStringSplit (timestring, ',', &numtimes);
-        if (atimes == NULL || numtimes < 1)
-          return MS_FALSE;
-
-        if (numtimes >= 1)
-        {
-            tokens = msStringSplit(atimes[0],  '/', &ntmp);
-            if (ntmp == 2) /* ranges */
-            {
-                tmpstimestring = msStrdup(tokens[0]);
-                msFreeCharArray(tokens, ntmp);
-            }
-            else if (ntmp == 1) /* multiple times */
-            {
-                tmpstimestring = msStrdup(atimes[0]);
-            }
-        }
-        msFreeCharArray(atimes, numtimes);
-    }
-    if (!tmpstimestring)
-      return MS_FALSE;
-        
-    timesresol = msTimeGetResolution((const char*)tmpstimestring);
-    if (timesresol < 0)
-      return MS_FALSE;
+  buffer[0] = '\0';
+  bufferTmp[0] = '\0';
 
-    free(tmpstimestring);
+  if (!lp || !timestring || !timefield)
+    return MS_FALSE;
 
-    switch (timesresol)
-    {
-        case (TIME_RESOLUTION_SECOND):
-          timeresolution = msStrdup("second");
-          break;
+  /* discrete time */
+  if (strstr(timestring, ",") == NULL &&
+      strstr(timestring, "/") == NULL) { /* discrete time */
+    createPostgresTimeCompareSimple(timefield, timestring, buffer, buffer_size);
+  } else {
 
-        case (TIME_RESOLUTION_MINUTE):
-          timeresolution = msStrdup("minute");
-          break;
+    /* multiple times, or ranges */
+    atimes = msStringSplit (timestring, ',', &numtimes);
+    if (atimes == NULL || numtimes < 1)
+      return MS_FALSE;
 
-        case (TIME_RESOLUTION_HOUR):
-          timeresolution = msStrdup("hour");
-          break;
+    strlcat(buffer, "(", buffer_size);
+    for(i=0; i<numtimes; i++) {
+      if(i!=0) {
+        strlcat(buffer, " OR ", buffer_size);
+      }
+      strlcat(buffer, "(", buffer_size);
+      aranges = msStringSplit(atimes[i],  '/', &numranges);
+      if(!aranges) return MS_FALSE;
+      if(numranges == 1) {
+        /* we don't have range, just a simple time */
+        createPostgresTimeCompareSimple(timefield, atimes[i], bufferTmp, buffer_size);
+        strlcat(buffer, bufferTmp, buffer_size);
+      } else if(numranges == 2) {
+        /* we have a range */
+        createPostgresTimeCompareRange(timefield, aranges[0], aranges[1], bufferTmp, buffer_size);
+        strlcat(buffer, bufferTmp, buffer_size);
+      } else {
+        return MS_FALSE;
+      }
+      msFreeCharArray(aranges, numranges);
+      strlcat(buffer, ")", buffer_size);
+    }
+    strlcat(buffer, ")", buffer_size);
+    msFreeCharArray(atimes, numtimes);
+  }
+  if(!*buffer) {
+    return MS_FALSE;
+  }
+  if(lp->filteritem) free(lp->filteritem);
+  lp->filteritem = msStrdup(timefield);
+  if (&lp->filter) {
+    /* if the filter is set and it's a string type, concatenate it with
+       the time. If not just free it */
+    if (lp->filter.type == MS_EXPRESSION) {
+      snprintf(bufferTmp, buffer_size, "(%s) and %s", lp->filter.string, buffer);
+      loadExpressionString(&lp->filter, bufferTmp);
+    } else {
+      freeExpression(&lp->filter);
+      loadExpressionString(&lp->filter, buffer);
+    }
+  }
+
+
+  return MS_TRUE;
+}
 
-        case (TIME_RESOLUTION_DAY):
-          timeresolution = msStrdup("day");
-          break;
+char *msPostGISEscapeSQLParam(layerObj *layer, const char *pszString)
+{
+#ifdef USE_POSTGIS
+  msPostGISLayerInfo *layerinfo = NULL;
+  int nError;
+  size_t nSrcLen;
+  char* pszEscapedStr =NULL;
 
-        case (TIME_RESOLUTION_MONTH):
-          timeresolution = msStrdup("month");
-          break;
+  if (layer && pszString && strlen(pszString) > 0) {
+    if(!msPostGISLayerIsOpen(layer))
+      msPostGISLayerOpen(layer);
 
-        case (TIME_RESOLUTION_YEAR):
-          timeresolution = msStrdup("year");
-          break;
+    assert(layer->layerinfo != NULL);
 
-        default:
-          break;
+    layerinfo = (msPostGISLayerInfo *) layer->layerinfo;
+    nSrcLen = strlen(pszString);
+    pszEscapedStr = (char*) msSmallMalloc( 2 * nSrcLen + 1);
+    PQescapeStringConn (layerinfo->pgconn, pszEscapedStr, pszString, nSrcLen, &nError);
+    if (nError != 0) {
+      free(pszEscapedStr);
+      pszEscapedStr = NULL;
     }
+  }
+  return pszEscapedStr;
+#else
+  msSetError( MS_MISCERR,
+              "PostGIS support is not available.",
+              "msPostGISEscapeSQLParam()");
+  return NULL;
+#endif
+}
 
-    if (!timeresolution)
-      return MS_FALSE;
+void msPostGISEnablePaging(layerObj *layer, int value)
+{
+#ifdef USE_POSTGIS
+  msPostGISLayerInfo *layerinfo = NULL;
 
-    /* where date_trunc('month', _cwctstamp) = '2004-08-01' */
-    if (strstr(timestring, ",") == NULL && 
-        strstr(timestring, "/") == NULL) /* discrete time */
-    {
-        if(lp->filteritem) free(lp->filteritem);
-        lp->filteritem = msStrdup(timefield);
-        if (&lp->filter)
-        {
-            /* if the filter is set and it's a string type, concatenate it with
-               the time. If not just free it */
-            if (lp->filter.type == MS_EXPRESSION)
-            {
-                snprintf(bufferTmp, buffer_size, "(%s) and ", lp->filter.string);
-                strlcat(buffer, bufferTmp, buffer_size);
-            }
-            else
-              freeExpression(&lp->filter);
-        }
-        
+  if (layer->debug) {
+    msDebug("msPostGISEnablePaging called.\n");
+  }
 
-        snprintf(bufferTmp, buffer_size, "(date_trunc('%s', %s) = '%s", 
-                 timeresolution, timefield, timestring);
-        strlcat(buffer, bufferTmp, buffer_size);
-         
-        /* make sure that the timestring is complete and acceptable */
-        /* to the date_trunc function : */
-        /* - if the resolution is year (2004) or month (2004-01),  */
-        /* a complete string for time would be 2004-01-01 */
-        /* - if the resolluion is hour or minute (2004-01-01 15), a  */
-        /* complete time is 2004-01-01 15:00:00 */
-        if (strcasecmp(timeresolution, "year")==0)
-        {
-            nlength = strlen(timestring);
-            if (timestring[nlength-1] != '-')
-              strlcat(buffer,"-01-01", buffer_size);
-            else
-              strlcat(buffer,"01-01", buffer_size);
-        }            
-        else if (strcasecmp(timeresolution, "month")==0)
-        {
-            nlength = strlen(timestring);
-            if (timestring[nlength-1] != '-')
-              strlcat(buffer,"-01", buffer_size);
-            else
-              strlcat(buffer,"01", buffer_size);
-        }            
-        else if (strcasecmp(timeresolution, "hour")==0)
-        {
-            nlength = strlen(timestring);
-            if (timestring[nlength-1] != ':')
-              strlcat(buffer,":00:00", buffer_size);
-            else
-              strlcat(buffer,"00:00", buffer_size);
-        }            
-        else if (strcasecmp(timeresolution, "minute")==0)
-        {
-            nlength = strlen(timestring);
-            if (timestring[nlength-1] != ':')
-              strlcat(buffer,":00", buffer_size);
-            else
-              strlcat(buffer,"00", buffer_size);
-        }            
-        
-
-        strlcat(buffer, "')", buffer_size);
-        
-        /* loadExpressionString(&lp->filter, (char *)timestring); */
-        loadExpressionString(&lp->filter, buffer);
-
-        free(timeresolution);
-        return MS_TRUE;
-    }
-    
-    atimes = msStringSplit (timestring, ',', &numtimes);
-    if (atimes == NULL || numtimes < 1)
-      return MS_FALSE;
+  if(!msPostGISLayerIsOpen(layer))
+    msPostGISLayerOpen(layer);
 
-    if (numtimes >= 1)
-    {
-        /* check to see if we have ranges by parsing the first entry */
-        tokens = msStringSplit(atimes[0],  '/', &ntmp);
-        if (ntmp == 2) /* ranges */
-        {
-            msFreeCharArray(tokens, ntmp);
-            for (i=0; i<numtimes; i++)
-            {
-                tokens = msStringSplit(atimes[i],  '/', &ntmp);
-                if (ntmp == 2)
-                {
-                    if (strlen(buffer) > 0)
-                      strlcat(buffer, " OR ", buffer_size);
-                    else
-                      strlcat(buffer, "(", buffer_size);
-
-                    snprintf(bufferTmp, buffer_size, "(date_trunc('%s', %s) >= '%s", 
-                             timeresolution, timefield, tokens[0]);
-                    strlcat(buffer, bufferTmp, buffer_size);
-                    
-                    /* - if the resolution is year (2004) or month (2004-01),  */
-                    /* a complete string for time would be 2004-01-01 */
-                    /* - if the resolluion is hour or minute (2004-01-01 15), a  */
-                    /* complete time is 2004-01-01 15:00:00 */
-                    if (strcasecmp(timeresolution, "year")==0)
-                    {
-                        nlength = strlen(tokens[0]);
-                        if (tokens[0][nlength-1] != '-')
-                          strlcat(buffer,"-01-01", buffer_size);
-                        else
-                          strlcat(buffer,"01-01", buffer_size);
-                    }            
-                    else if (strcasecmp(timeresolution, "month")==0)
-                    {
-                        nlength = strlen(tokens[0]);
-                        if (tokens[0][nlength-1] != '-')
-                          strlcat(buffer,"-01", buffer_size);
-                        else
-                          strlcat(buffer,"01", buffer_size);
-                    }            
-                    else if (strcasecmp(timeresolution, "hour")==0)
-                    {
-                        nlength = strlen(tokens[0]);
-                        if (tokens[0][nlength-1] != ':')
-                          strlcat(buffer,":00:00", buffer_size);
-                        else
-                          strlcat(buffer,"00:00", buffer_size);
-                    }            
-                    else if (strcasecmp(timeresolution, "minute")==0)
-                    {
-                        nlength = strlen(tokens[0]);
-                        if (tokens[0][nlength-1] != ':')
-                          strlcat(buffer,":00", buffer_size);
-                        else
-                          strlcat(buffer,"00", buffer_size);
-                    }            
-
-                    snprintf(bufferTmp, buffer_size, "' AND date_trunc('%s', %s) <= '%s", 
-                             timeresolution, timefield, tokens[1]);
-                    strlcat(buffer, bufferTmp, buffer_size);
-
-                    /* - if the resolution is year (2004) or month (2004-01),  */
-                    /* a complete string for time would be 2004-01-01 */
-                    /* - if the resolluion is hour or minute (2004-01-01 15), a  */
-                    /* complete time is 2004-01-01 15:00:00 */
-                    if (strcasecmp(timeresolution, "year")==0)
-                    {
-                        nlength = strlen(tokens[1]);
-                        if (tokens[1][nlength-1] != '-')
-                          strlcat(buffer,"-01-01", buffer_size);
-                        else
-                          strlcat(buffer,"01-01", buffer_size);
-                    }            
-                    else if (strcasecmp(timeresolution, "month")==0)
-                    {
-                        nlength = strlen(tokens[1]);
-                        if (tokens[1][nlength-1] != '-')
-                          strlcat(buffer,"-01", buffer_size);
-                        else
-                          strlcat(buffer,"01", buffer_size);
-                    }            
-                    else if (strcasecmp(timeresolution, "hour")==0)
-                    {
-                        nlength = strlen(tokens[1]);
-                        if (tokens[1][nlength-1] != ':')
-                          strlcat(buffer,":00:00", buffer_size);
-                        else
-                          strlcat(buffer,"00:00", buffer_size);
-                    }            
-                    else if (strcasecmp(timeresolution, "minute")==0)
-                    {
-                        nlength = strlen(tokens[1]);
-                        if (tokens[1][nlength-1] != ':')
-                          strlcat(buffer,":00", buffer_size);
-                        else
-                          strlcat(buffer,"00", buffer_size);
-                    }            
-
-                    strlcat(buffer,  "')", buffer_size);
-                }
-                 
-                msFreeCharArray(tokens, ntmp);
-            }
-            if (strlen(buffer) > 0)
-              strlcat(buffer, ")", buffer_size);
-        }
-        else if (ntmp == 1) /* multiple times */
-        {
-            msFreeCharArray(tokens, ntmp);
-            strlcat(buffer, "(", buffer_size);
-            for (i=0; i<numtimes; i++)
-            {
-                if (i > 0)
-                  strlcat(buffer, " OR ", buffer_size);
-
-                snprintf(bufferTmp, buffer_size, "(date_trunc('%s', %s) = '%s",
-                         timeresolution, timefield, atimes[i]);
-                strlcat(buffer, bufferTmp, buffer_size);
-                
-                /* make sure that the timestring is complete and acceptable */
-                /* to the date_trunc function : */
-                /* - if the resolution is year (2004) or month (2004-01),  */
-                /* a complete string for time would be 2004-01-01 */
-                /* - if the resolluion is hour or minute (2004-01-01 15), a  */
-                /* complete time is 2004-01-01 15:00:00 */
-                if (strcasecmp(timeresolution, "year")==0)
-                {
-                    nlength = strlen(atimes[i]);
-                    if (atimes[i][nlength-1] != '-')
-                      strlcat(buffer,"-01-01", buffer_size);
-                    else
-                      strlcat(buffer,"01-01", buffer_size);
-                }            
-                else if (strcasecmp(timeresolution, "month")==0)
-                {
-                    nlength = strlen(atimes[i]);
-                    if (atimes[i][nlength-1] != '-')
-                      strlcat(buffer,"-01", buffer_size);
-                    else
-                      strlcat(buffer,"01", buffer_size);
-                }            
-                else if (strcasecmp(timeresolution, "hour")==0)
-                {
-                    nlength = strlen(atimes[i]);
-                    if (atimes[i][nlength-1] != ':')
-                      strlcat(buffer,":00:00", buffer_size);
-                    else
-                      strlcat(buffer,"00:00", buffer_size);
-                }            
-                else if (strcasecmp(timeresolution, "minute")==0)
-                {
-                    nlength = strlen(atimes[i]);
-                    if (atimes[i][nlength-1] != ':')
-                      strlcat(buffer,":00", buffer_size);
-                    else
-                      strlcat(buffer,"00", buffer_size);
-                }            
-
-                strlcat(buffer, "')", buffer_size);
-            } 
-            strlcat(buffer, ")", buffer_size);
-        }
-        else
-        {
-            msFreeCharArray(atimes, numtimes);
-            return MS_FALSE;
-        }
+  assert( layer->layerinfo != NULL);
 
-        msFreeCharArray(atimes, numtimes);
-
-        /* load the string to the filter */
-        if (strlen(buffer) > 0)
-        {
-            if(lp->filteritem) 
-              free(lp->filteritem);
-            lp->filteritem = msStrdup(timefield);     
-            if (&lp->filter)
-            {
-                if (lp->filter.type == MS_EXPRESSION)
-                {
-                    snprintf(bufferTmp, buffer_size, "(%s) and ", lp->filter.string);
-                    strlcat(buffer, bufferTmp, buffer_size);
-                }
-                else
-                  freeExpression(&lp->filter);
-            }
-            loadExpressionString(&lp->filter, buffer);
-        }
+  layerinfo = (msPostGISLayerInfo *)layer->layerinfo;
+  layerinfo->paging = value;
 
-        free(timeresolution);
-        return MS_TRUE;
-                 
-    }
-    
-    return MS_FALSE;
+#else
+  msSetError( MS_MISCERR,
+              "PostGIS support is not available.",
+              "msPostGISEnablePaging()");
+#endif
+  return;
 }
 
-char *msPostGISEscapeSQLParam(layerObj *layer, const char *pszString)
+int msPostGISGetPaging(layerObj *layer)
 {
 #ifdef USE_POSTGIS
-    msPostGISLayerInfo *layerinfo = NULL;
-    int nError;
-    size_t nSrcLen;
-    char* pszEscapedStr =NULL;
-
-    if (layer && pszString && strlen(pszString) > 0)
-    {
-        if(!msPostGISLayerIsOpen(layer))
-          msPostGISLayerOpen(layer);
-    
-        assert(layer->layerinfo != NULL);
-
-        layerinfo = (msPostGISLayerInfo *) layer->layerinfo;
-        nSrcLen = strlen(pszString);
-        pszEscapedStr = (char*) msSmallMalloc( 2 * nSrcLen + 1);
-        PQescapeStringConn (layerinfo->pgconn, pszEscapedStr, pszString, nSrcLen, &nError);
-        if (nError != 0)
-        {
-            free(pszEscapedStr);
-            pszEscapedStr = NULL;
-        }
-    }
-    return pszEscapedStr;
+  msPostGISLayerInfo *layerinfo = NULL;
+
+  if (layer->debug) {
+    msDebug("msPostGISGetPaging called.\n");
+  }
+
+  if(!msPostGISLayerIsOpen(layer))
+    return MS_TRUE;
+
+  assert( layer->layerinfo != NULL);
+
+  layerinfo = (msPostGISLayerInfo *)layer->layerinfo;
+  return layerinfo->paging;
 #else
-    msSetError( MS_MISCERR,
-                "PostGIS support is not available.",
-                "msPostGISEscapeSQLParam()");
-    return NULL;
+  msSetError( MS_MISCERR,
+              "PostGIS support is not available.",
+              "msPostGISEnablePaging()");
+  return MS_FAILURE;
 #endif
 }
 
-
-int msPostGISLayerInitializeVirtualTable(layerObj *layer) {
-    assert(layer != NULL);
-    assert(layer->vtable != NULL);
-
-    layer->vtable->LayerInitItemInfo = msPostGISLayerInitItemInfo;
-    layer->vtable->LayerFreeItemInfo = msPostGISLayerFreeItemInfo;
-    layer->vtable->LayerOpen = msPostGISLayerOpen;
-    layer->vtable->LayerIsOpen = msPostGISLayerIsOpen;
-    layer->vtable->LayerWhichShapes = msPostGISLayerWhichShapes;
-    layer->vtable->LayerNextShape = msPostGISLayerNextShape;
-    layer->vtable->LayerGetShape = msPostGISLayerGetShape;
-    layer->vtable->LayerClose = msPostGISLayerClose;
-    layer->vtable->LayerGetItems = msPostGISLayerGetItems;
-    layer->vtable->LayerGetExtent = msPostGISLayerGetExtent;
-    layer->vtable->LayerApplyFilterToLayer = msLayerApplyCondSQLFilterToLayer;
-    /* layer->vtable->LayerGetAutoStyle, not supported for this layer */
-    layer->vtable->LayerCloseConnection = msPostGISLayerClose;
-    layer->vtable->LayerSetTimeFilter = msPostGISLayerSetTimeFilter; 
-    /* layer->vtable->LayerCreateItems, use default */
-    /* layer->vtable->LayerGetNumFeatures, use default */
-    
-    /* layer->vtable->LayerGetAutoProjection, use defaut*/  
-
-    layer->vtable->LayerEscapeSQLParam = msPostGISEscapeSQLParam;
-
-    return MS_SUCCESS;
+int msPostGISLayerInitializeVirtualTable(layerObj *layer)
+{
+  assert(layer != NULL);
+  assert(layer->vtable != NULL);
+
+  layer->vtable->LayerInitItemInfo = msPostGISLayerInitItemInfo;
+  layer->vtable->LayerFreeItemInfo = msPostGISLayerFreeItemInfo;
+  layer->vtable->LayerOpen = msPostGISLayerOpen;
+  layer->vtable->LayerIsOpen = msPostGISLayerIsOpen;
+  layer->vtable->LayerWhichShapes = msPostGISLayerWhichShapes;
+  layer->vtable->LayerNextShape = msPostGISLayerNextShape;
+  layer->vtable->LayerGetShape = msPostGISLayerGetShape;
+  layer->vtable->LayerClose = msPostGISLayerClose;
+  layer->vtable->LayerGetItems = msPostGISLayerGetItems;
+  /* layer->vtable->LayerGetExtent = msPostGISLayerGetExtent; */
+  layer->vtable->LayerApplyFilterToLayer = msLayerApplyCondSQLFilterToLayer;
+  /* layer->vtable->LayerGetAutoStyle, not supported for this layer */
+  /* layer->vtable->LayerCloseConnection = msPostGISLayerClose; */
+  layer->vtable->LayerSetTimeFilter = msPostGISLayerSetTimeFilter;
+  /* layer->vtable->LayerCreateItems, use default */
+  /* layer->vtable->LayerGetNumFeatures, use default */
+
+  /* layer->vtable->LayerGetAutoProjection, use defaut*/
+
+  layer->vtable->LayerEscapeSQLParam = msPostGISEscapeSQLParam;
+  layer->vtable->LayerEnablePaging = msPostGISEnablePaging;
+  layer->vtable->LayerGetPaging = msPostGISGetPaging;
+
+  return MS_SUCCESS;
 }
diff --git a/mappostgis.h b/mappostgis.h
index 01221b0..4d3ced6 100644
--- a/mappostgis.h
+++ b/mappostgis.h
@@ -53,29 +53,30 @@
 ** Specific information needed for managing this layer.
 */
 typedef struct {
-    char        *sql;        /* SQL query to send to database */
-    PGconn      *pgconn;     /* Connection to database */
-    long        rownum;      /* What row is the next to be read (for random access) */
-    PGresult    *pgresult;   /* For fetching rows from the database */
-    char        *uid;        /* Name of user-specified unique identifier, if set */
-    char        *srid;       /* Name of user-specified SRID: zero-length => calculate; non-zero => use this value! */
-    char        *geomcolumn; /* Specified geometry column, eg "THEGEOM from thetable" */
-    char        *fromsource; /* Specified record source, ed "thegeom from THETABLE" or "thegeom from (SELECT..) AS FOO" */
-    int         endian;      /* Endianness of the mapserver host */
-    int         version;     /* PostGIS version of the database */
+  char        *sql;        /* SQL query to send to database */
+  PGconn      *pgconn;     /* Connection to database */
+  long        rownum;      /* What row is the next to be read (for random access) */
+  PGresult    *pgresult;   /* For fetching rows from the database */
+  char        *uid;        /* Name of user-specified unique identifier, if set */
+  char        *srid;       /* Name of user-specified SRID: zero-length => calculate; non-zero => use this value! */
+  char        *geomcolumn; /* Specified geometry column, eg "THEGEOM from thetable" */
+  char        *fromsource; /* Specified record source, ed "thegeom from THETABLE" or "thegeom from (SELECT..) AS FOO" */
+  int         endian;      /* Endianness of the mapserver host */
+  int         version;     /* PostGIS version of the database */
+  int         paging;      /* Driver handling of pagination, enabled by default */
 }
 msPostGISLayerInfo;
 
 
 /*
-** Utility structure for handling the WKB returned by the database while 
+** Utility structure for handling the WKB returned by the database while
 ** reading.
 */
 typedef struct {
-    char *wkb; /* Pointer to front of WKB */
-    char *ptr; /* Pointer to current write point */
-    size_t size; /* Size of allocated space */
-    int *typemap; /* Look-up array to valid OGC types */
+  char *wkb; /* Pointer to front of WKB */
+  char *ptr; /* Pointer to current write point */
+  size_t size; /* Size of allocated space */
+  int *typemap; /* Look-up array to valid OGC types */
 } wkbObj;
 
 /*
@@ -83,74 +84,74 @@ typedef struct {
 ** handling curved feature types.
 */
 typedef struct {
-    pointObj *data; /* Re-sizeable point buffer */
-    int npoints;  /* How many points are we currently storing */
-    int maxpoints; /* How big is our point buffer */
+  pointObj *data; /* Re-sizeable point buffer */
+  int npoints;  /* How many points are we currently storing */
+  int maxpoints; /* How big is our point buffer */
 } pointArrayObj;
 
 /*
-** All the WKB type numbers from the OGC 
+** All the WKB type numbers from the OGC
 */
 typedef enum {
-    WKB_POINT=1,
-    WKB_LINESTRING=2,
-    WKB_POLYGON=3,
-    WKB_MULTIPOINT=4,
-    WKB_MULTILINESTRING=5,
-    WKB_MULTIPOLYGON=6,
-    WKB_GEOMETRYCOLLECTION=7,
-    WKB_CIRCULARSTRING=8,
-    WKB_COMPOUNDCURVE=9,
-    WKB_CURVEPOLYGON=10,
-    WKB_MULTICURVE=11,
-    WKB_MULTISURFACE=12
+  WKB_POINT=1,
+  WKB_LINESTRING=2,
+  WKB_POLYGON=3,
+  WKB_MULTIPOINT=4,
+  WKB_MULTILINESTRING=5,
+  WKB_MULTIPOLYGON=6,
+  WKB_GEOMETRYCOLLECTION=7,
+  WKB_CIRCULARSTRING=8,
+  WKB_COMPOUNDCURVE=9,
+  WKB_CURVEPOLYGON=10,
+  WKB_MULTICURVE=11,
+  WKB_MULTISURFACE=12
 } wkb_typenum;
 
-/* 
+/*
 ** See below.
 */
 #define WKB_TYPE_COUNT 16
 
 /*
-** Map the WKB type numbers returned by PostGIS < 2.0 to the 
+** Map the WKB type numbers returned by PostGIS < 2.0 to the
 ** valid OGC numbers
 */
 static int wkb_postgis15[WKB_TYPE_COUNT] = {
-    0,
-    WKB_POINT,
-    WKB_LINESTRING,
-    WKB_POLYGON,
-    WKB_MULTIPOINT,
-    WKB_MULTILINESTRING,
-    WKB_MULTIPOLYGON,
-    WKB_GEOMETRYCOLLECTION,
-    WKB_CIRCULARSTRING,
-    WKB_COMPOUNDCURVE,
-    0,0,0,
-    WKB_CURVEPOLYGON,
-    WKB_MULTICURVE,
-    WKB_MULTISURFACE 
+  0,
+  WKB_POINT,
+  WKB_LINESTRING,
+  WKB_POLYGON,
+  WKB_MULTIPOINT,
+  WKB_MULTILINESTRING,
+  WKB_MULTIPOLYGON,
+  WKB_GEOMETRYCOLLECTION,
+  WKB_CIRCULARSTRING,
+  WKB_COMPOUNDCURVE,
+  0,0,0,
+  WKB_CURVEPOLYGON,
+  WKB_MULTICURVE,
+  WKB_MULTISURFACE
 };
 
 /*
-** Map the WKB type numbers returned by PostGIS >= 2.0 to the 
+** Map the WKB type numbers returned by PostGIS >= 2.0 to the
 ** valid OGC numbers
 */
 static int wkb_postgis20[WKB_TYPE_COUNT] = {
-    0,
-    WKB_POINT,
-    WKB_LINESTRING,
-    WKB_POLYGON,
-    WKB_MULTIPOINT,
-    WKB_MULTILINESTRING,
-    WKB_MULTIPOLYGON,
-    WKB_GEOMETRYCOLLECTION,
-    WKB_CIRCULARSTRING,
-    WKB_COMPOUNDCURVE,
-    WKB_CURVEPOLYGON,
-    WKB_MULTICURVE,
-    WKB_MULTISURFACE,
-    0,0,0 
+  0,
+  WKB_POINT,
+  WKB_LINESTRING,
+  WKB_POLYGON,
+  WKB_MULTIPOINT,
+  WKB_MULTILINESTRING,
+  WKB_MULTIPOLYGON,
+  WKB_GEOMETRYCOLLECTION,
+  WKB_CIRCULARSTRING,
+  WKB_COMPOUNDCURVE,
+  WKB_CURVEPOLYGON,
+  WKB_MULTICURVE,
+  WKB_MULTISURFACE,
+  0,0,0
 };
 
 
diff --git a/mappostgresql.c b/mappostgresql.c
index a240e19..d6b2e84 100644
--- a/mappostgresql.c
+++ b/mappostgresql.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -50,17 +50,17 @@
 #include <string.h>
 #include <ctype.h> /* tolower() */
 
-MS_CVSID("$Id$")
+
 
 
 typedef struct {
-    PGconn      *conn;          /* connection to db */
-    long        row_num;        /* what row is the NEXT to be read (for random access) */
-    PGresult    *query_result;  /* for fetching rows from the db */
-    int         from_index;
-    char        *to_column;
-    char        *from_value;
-    int         layer_debug;    /* there's no debug on the join, so use the layer */
+  PGconn      *conn;          /* connection to db */
+  long        row_num;        /* what row is the NEXT to be read (for random access) */
+  PGresult    *query_result;  /* for fetching rows from the db */
+  int         from_index;
+  char        *to_column;
+  char        *from_value;
+  int         layer_debug;    /* there's no debug on the join, so use the layer */
 } msPOSTGRESQLJoinInfo;
 
 /************************************************************************/
@@ -72,147 +72,148 @@ typedef struct {
 /* pooled connections with joins.                                       */
 /************************************************************************/
 
-int msPOSTGRESQLJoinConnect(layerObj *layer, joinObj *join) {
-    char *maskeddata, *temp, *sql, *column;
-    char *conn_decrypted;
-    int i, count, test;
-    PGresult *query_result;
-    msPOSTGRESQLJoinInfo *joininfo;
-
-    if(join->joininfo) 
-        return MS_SUCCESS;
-
-    joininfo = (msPOSTGRESQLJoinInfo *)malloc(sizeof(msPOSTGRESQLJoinInfo));
-    if(!joininfo) {
-        msSetError(MS_MEMERR, "Error allocating join info struct.", 
-                "msPOSTGRESQLJoinConnect()");
-        return MS_FAILURE;
-    }
-    joininfo->conn = NULL;
-    joininfo->row_num = 0;
-    joininfo->query_result = NULL;
-    joininfo->from_index = 0;
-    joininfo->to_column = join->to;
-    joininfo->from_value = NULL;
-    joininfo->layer_debug = layer->debug;
-    join->joininfo = joininfo;
-
-    /* 
-     * We need three things at a minimum, the connection string, a table
-     * name, and a column to join on.
-     */
-    if(!join->connection) {
-        msSetError(MS_QUERYERR, "No connection information provided.", 
-                "MSPOSTGRESQLJoinConnect()");
-        return MS_FAILURE;
-    }
-    if(!join->table) {
-        msSetError(MS_QUERYERR, "No join table name found.", 
-                "msPOSTGRESQLJoinConnect()");
-        return MS_FAILURE;
-    }
-    if(!joininfo->to_column) {
-        msSetError(MS_QUERYERR, "No join to column name found.",
-                "msPOSTGRESQLJoinConnect()");
-        return MS_FAILURE;
-    }
+int msPOSTGRESQLJoinConnect(layerObj *layer, joinObj *join)
+{
+  char *maskeddata, *temp, *sql, *column;
+  char *conn_decrypted;
+  int i, count, test;
+  PGresult *query_result;
+  msPOSTGRESQLJoinInfo *joininfo;
 
-    /* Establish database connection */
-    conn_decrypted = msDecryptStringTokens(layer->map, join->connection);
-    if (conn_decrypted != NULL) {
-      joininfo->conn = PQconnectdb(conn_decrypted);
-      free(conn_decrypted);
-    }
-    if(!joininfo->conn || PQstatus(joininfo->conn) == CONNECTION_BAD) {
-        maskeddata = (char *)malloc(strlen(layer->connection) + 1);
-        strcpy(maskeddata, join->connection);
-        temp = strstr(maskeddata, "password=");
-        if(!temp) {
-            temp = (char *)(temp + 9);
-            count = (int)(strstr(temp, " ") - temp);
-            for(i = 0; i < count; i++) {
-                strlcpy(temp, "*", (int)1);
-                temp++;
-            }
-        }
-        msSetError(MS_QUERYERR, 
-                "Unable to connect to PostgreSQL using the string %s.\n  Error reported: %s\n", 
-                "msPOSTGRESQLJoinConnect()", 
-                maskeddata, PQerrorMessage(joininfo->conn));
-        free(maskeddata);
-        if(!joininfo->conn) {
-            free(joininfo->conn);
-        }
-        free(joininfo);
-        join->joininfo = NULL;
-        return MS_FAILURE;
-    }
+  if(join->joininfo)
+    return MS_SUCCESS;
 
-    /* Determine the number and names of columns in the join table. */
-    sql = (char *)malloc(36 + strlen(join->table) + 1);
-    sprintf(sql, "SELECT * FROM %s WHERE false LIMIT 0", join->table);
-    
-    if(joininfo->layer_debug) {
-        msDebug("msPOSTGRESQLJoinConnect(): executing %s.\n", sql);
+  joininfo = (msPOSTGRESQLJoinInfo *)malloc(sizeof(msPOSTGRESQLJoinInfo));
+  if(!joininfo) {
+    msSetError(MS_MEMERR, "Error allocating join info struct.",
+               "msPOSTGRESQLJoinConnect()");
+    return MS_FAILURE;
+  }
+  joininfo->conn = NULL;
+  joininfo->row_num = 0;
+  joininfo->query_result = NULL;
+  joininfo->from_index = 0;
+  joininfo->to_column = join->to;
+  joininfo->from_value = NULL;
+  joininfo->layer_debug = layer->debug;
+  join->joininfo = joininfo;
+
+  /*
+   * We need three things at a minimum, the connection string, a table
+   * name, and a column to join on.
+   */
+  if(!join->connection) {
+    msSetError(MS_QUERYERR, "No connection information provided.",
+               "MSPOSTGRESQLJoinConnect()");
+    return MS_FAILURE;
+  }
+  if(!join->table) {
+    msSetError(MS_QUERYERR, "No join table name found.",
+               "msPOSTGRESQLJoinConnect()");
+    return MS_FAILURE;
+  }
+  if(!joininfo->to_column) {
+    msSetError(MS_QUERYERR, "No join to column name found.",
+               "msPOSTGRESQLJoinConnect()");
+    return MS_FAILURE;
+  }
+
+  /* Establish database connection */
+  conn_decrypted = msDecryptStringTokens(layer->map, join->connection);
+  if (conn_decrypted != NULL) {
+    joininfo->conn = PQconnectdb(conn_decrypted);
+    free(conn_decrypted);
+  }
+  if(!joininfo->conn || PQstatus(joininfo->conn) == CONNECTION_BAD) {
+    maskeddata = (char *)malloc(strlen(layer->connection) + 1);
+    strcpy(maskeddata, join->connection);
+    temp = strstr(maskeddata, "password=");
+    if(!temp) {
+      temp = (char *)(temp + 9);
+      count = (int)(strstr(temp, " ") - temp);
+      for(i = 0; i < count; i++) {
+        strlcpy(temp, "*", (int)1);
+        temp++;
+      }
     }
-
-    query_result = PQexec(joininfo->conn, sql);
-    if(!query_result || PQresultStatus(query_result) != PGRES_TUPLES_OK) {
-        msSetError(MS_QUERYERR, "Error determining join items: %s.", 
-                "msPOSTGRESQLJoinConnect()", PQerrorMessage(joininfo->conn));
-        if(query_result) {
-            PQclear(query_result);
-            query_result = NULL;
-        }
-        free(sql);
-        return MS_FAILURE;
+    msSetError(MS_QUERYERR,
+               "Unable to connect to PostgreSQL using the string %s.\n  Error reported: %s\n",
+               "msPOSTGRESQLJoinConnect()",
+               maskeddata, PQerrorMessage(joininfo->conn));
+    free(maskeddata);
+    if(!joininfo->conn) {
+      free(joininfo->conn);
     }
-    free(sql);
-    join->numitems = PQnfields(query_result);
-    join->items = malloc(sizeof(char *) * (join->numitems));
-
-    /* We want the join-to column to be first in the list. */
-    test = 1;
-    for(i = 0; i < join->numitems; i++) {
-        column = PQfname(query_result, i);
-        if(strcmp(column, joininfo->to_column) != 0) {
-            join->items[i + test] = (char *)malloc(strlen(column) + 1);
-            strcpy(join->items[i + test], column);
-        } else {
-            test = 0;
-            join->items[0] = (char *)malloc(strlen(column) + 1);
-            strcpy(join->items[0], column);
-        } 
+    free(joininfo);
+    join->joininfo = NULL;
+    return MS_FAILURE;
+  }
+
+  /* Determine the number and names of columns in the join table. */
+  sql = (char *)malloc(36 + strlen(join->table) + 1);
+  sprintf(sql, "SELECT * FROM %s WHERE false LIMIT 0", join->table);
+
+  if(joininfo->layer_debug) {
+    msDebug("msPOSTGRESQLJoinConnect(): executing %s.\n", sql);
+  }
+
+  query_result = PQexec(joininfo->conn, sql);
+  if(!query_result || PQresultStatus(query_result) != PGRES_TUPLES_OK) {
+    msSetError(MS_QUERYERR, "Error determining join items: %s.",
+               "msPOSTGRESQLJoinConnect()", PQerrorMessage(joininfo->conn));
+    if(query_result) {
+      PQclear(query_result);
+      query_result = NULL;
     }
-    PQclear(query_result);
-    query_result = NULL;
-    if(test == 1) {
-        msSetError(MS_QUERYERR, "Unable to find join to column: %s", 
-              "msPOSTGRESQLJoinConnect()", joininfo->to_column);
-        return MS_FAILURE;
+    free(sql);
+    return MS_FAILURE;
+  }
+  free(sql);
+  join->numitems = PQnfields(query_result);
+  join->items = malloc(sizeof(char *) * (join->numitems));
+
+  /* We want the join-to column to be first in the list. */
+  test = 1;
+  for(i = 0; i < join->numitems; i++) {
+    column = PQfname(query_result, i);
+    if(strcmp(column, joininfo->to_column) != 0) {
+      join->items[i + test] = (char *)malloc(strlen(column) + 1);
+      strcpy(join->items[i + test], column);
+    } else {
+      test = 0;
+      join->items[0] = (char *)malloc(strlen(column) + 1);
+      strcpy(join->items[0], column);
     }
-
-    if(joininfo->layer_debug) {
-        for(i = 0; i < join->numitems; i++) {
-            msDebug("msPOSTGRESQLJoinConnect(): Column %d named %s\n", i, join->items[i]);
-        }
+  }
+  PQclear(query_result);
+  query_result = NULL;
+  if(test == 1) {
+    msSetError(MS_QUERYERR, "Unable to find join to column: %s",
+               "msPOSTGRESQLJoinConnect()", joininfo->to_column);
+    return MS_FAILURE;
+  }
+
+  if(joininfo->layer_debug) {
+    for(i = 0; i < join->numitems; i++) {
+      msDebug("msPOSTGRESQLJoinConnect(): Column %d named %s\n", i, join->items[i]);
     }
+  }
 
-    /* Determine the index of the join from column. */
-    for(i = 0; i < layer->numitems; i++) {
-        if(strcasecmp(layer->items[i], join->from) == 0) {
-            joininfo->from_index = i;
-            break;
-        }
+  /* Determine the index of the join from column. */
+  for(i = 0; i < layer->numitems; i++) {
+    if(strcasecmp(layer->items[i], join->from) == 0) {
+      joininfo->from_index = i;
+      break;
     }
+  }
 
-    if(i == layer->numitems) {
-        msSetError(MS_JOINERR, "Item %s not found in layer %s.", 
-                "msPOSTGRESQLJoinConnect()", join->from, layer->name);
-        return MS_FAILURE;
-    }
+  if(i == layer->numitems) {
+    msSetError(MS_JOINERR, "Item %s not found in layer %s.",
+               "msPOSTGRESQLJoinConnect()", join->from, layer->name);
+    return MS_FAILURE;
+  }
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 /************************************************************************/
@@ -223,46 +224,47 @@ int msPOSTGRESQLJoinConnect(layerObj *layer, joinObj *join) {
 /* resources, and setting the next value to join to.                    */
 /************************************************************************/
 
-int msPOSTGRESQLJoinPrepare(joinObj *join, shapeObj *shape) {
-
-    /* We need a connection, and a shape with values to join to. */
-    msPOSTGRESQLJoinInfo *joininfo = join->joininfo;
-    if(!joininfo) {
-        msSetError(MS_JOINERR, "Join has not been connected.", "msPOSTGRESQLJoinPrepare()");
-        return MS_FAILURE;
-    }
-
-    if(!shape) {
-        msSetError(MS_JOINERR, "Null shape provided for join.", "msPOSTGRESQLJoinPrepare()");
-        return MS_FAILURE;
-    }
-
-    if(!shape->values) {
-        msSetError(MS_JOINERR, "Shape has no attributes.  Kinda hard to join against.", "msPOSTGRESQLJoinPrepare()");
-        return MS_FAILURE;
-    }
-    joininfo->row_num = 0;
-
-    /* Free the previous join value, if any. */
-    if(joininfo->from_value) {
-        free(joininfo->from_value);
-    }
-    
-    /* Free the previous results, if any. */
-    if(joininfo->query_result) {
-        PQclear(joininfo->query_result);
-        joininfo->query_result = NULL;
-    }
+int msPOSTGRESQLJoinPrepare(joinObj *join, shapeObj *shape)
+{
+
+  /* We need a connection, and a shape with values to join to. */
+  msPOSTGRESQLJoinInfo *joininfo = join->joininfo;
+  if(!joininfo) {
+    msSetError(MS_JOINERR, "Join has not been connected.", "msPOSTGRESQLJoinPrepare()");
+    return MS_FAILURE;
+  }
+
+  if(!shape) {
+    msSetError(MS_JOINERR, "Null shape provided for join.", "msPOSTGRESQLJoinPrepare()");
+    return MS_FAILURE;
+  }
+
+  if(!shape->values) {
+    msSetError(MS_JOINERR, "Shape has no attributes.  Kinda hard to join against.", "msPOSTGRESQLJoinPrepare()");
+    return MS_FAILURE;
+  }
+  joininfo->row_num = 0;
+
+  /* Free the previous join value, if any. */
+  if(joininfo->from_value) {
+    free(joininfo->from_value);
+  }
+
+  /* Free the previous results, if any. */
+  if(joininfo->query_result) {
+    PQclear(joininfo->query_result);
+    joininfo->query_result = NULL;
+  }
 
-    /* Copy the next join value from the shape. */
-    joininfo->from_value = msStrdup(shape->values[joininfo->from_index]);
+  /* Copy the next join value from the shape. */
+  joininfo->from_value = msStrdup(shape->values[joininfo->from_index]);
 
-    if(joininfo->layer_debug) {
-        msDebug("msPOSTGRESQLJoinPrepare() preping for value %s.\n", 
-                joininfo->from_value);
-    }
+  if(joininfo->layer_debug) {
+    msDebug("msPOSTGRESQLJoinPrepare() preping for value %s.\n",
+            joininfo->from_value);
+  }
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 /************************************************************************/
@@ -276,107 +278,108 @@ int msPOSTGRESQLJoinPrepare(joinObj *join, shapeObj *shape) {
 /* we store the next row number and query results in the joininfo and   */
 /* process the next tuple on each call.                                 */
 /************************************************************************/
-int msPOSTGRESQLJoinNext(joinObj *join) {
-    msPOSTGRESQLJoinInfo *joininfo = join->joininfo;
-    int i, length, row_count;
-    char *sql, *columns;
-
-    /* We need a connection, and a join value. */
-    if(!joininfo || !joininfo->conn) {
-        msSetError(MS_JOINERR, "Join has not been connected.\n", 
-                "msPOSTGRESQLJoinNext()");
-        return MS_FAILURE;
-    }
-
-    if(!joininfo->from_value) {
-        msSetError(MS_JOINERR, "Join has not been prepared.\n", 
-                "msPOSTGRESQLJoinNext()");
-        return MS_FAILURE;
+int msPOSTGRESQLJoinNext(joinObj *join)
+{
+  msPOSTGRESQLJoinInfo *joininfo = join->joininfo;
+  int i, length, row_count;
+  char *sql, *columns;
+
+  /* We need a connection, and a join value. */
+  if(!joininfo || !joininfo->conn) {
+    msSetError(MS_JOINERR, "Join has not been connected.\n",
+               "msPOSTGRESQLJoinNext()");
+    return MS_FAILURE;
+  }
+
+  if(!joininfo->from_value) {
+    msSetError(MS_JOINERR, "Join has not been prepared.\n",
+               "msPOSTGRESQLJoinNext()");
+    return MS_FAILURE;
+  }
+
+  /* Free the previous results. */
+  if(join->values) {
+    msFreeCharArray(join->values, join->numitems);
+    join->values = NULL;
+  }
+
+  /* We only need to execute the query if no results exist. */
+  if(!joininfo->query_result) {
+    /* Write the list of column names. */
+    length = 0;
+    for(i = 0; i < join->numitems; i++) {
+      length += 8 + strlen(join->items[i]) + 2;
     }
 
-    /* Free the previous results. */
-    if(join->values) {
-        msFreeCharArray(join->values, join->numitems);
-        join->values = NULL;
+    columns = (char *)malloc(length);
+    if(!columns) {
+      msSetError(MS_MEMERR, "Failure to malloc.\n",
+                 "msPOSTGRESQLJoinNext()");
+      return MS_FAILURE;
     }
 
-    /* We only need to execute the query if no results exist. */
-    if(!joininfo->query_result) {
-        /* Write the list of column names. */
-        length = 0;
-        for(i = 0; i < join->numitems; i++) {
-            length += 8 + strlen(join->items[i]) + 2;
-        }
-        
-        columns = (char *)malloc(length);
-        if(!columns) {
-            msSetError(MS_MEMERR, "Failure to malloc.\n", 
-                    "msPOSTGRESQLJoinNext()");
-            return MS_FAILURE;
-        }
-        
-        strcpy(columns, "");
-        for(i = 0; i < join->numitems; i++) {
-            strcat(columns, "\"");
-            strcat(columns, join->items[i]);
-            strcat(columns, "\"::text");
-            if(i != join->numitems - 1) {
-                strcat(columns, ", ");
-            }
-        }
-
-        /* Create the query string. */
-        sql = (char *)malloc(26 + strlen(columns) + strlen(join->table) + 
-                strlen(join->to) + strlen(joininfo->from_value));
-        if(!sql) {
-            msSetError(MS_MEMERR, "Failure to malloc.\n", 
-                    "msPOSTGRESQLJoinNext()");
-            return MS_FAILURE;
-        }
-        sprintf(sql, "SELECT %s FROM %s WHERE %s = '%s'", columns, join->table, join->to, joininfo->from_value);
-        if(joininfo->layer_debug) {
-            msDebug("msPOSTGRESQLJoinNext(): executing %s.\n", sql);
-        }
-
-        free(columns);
-
-        joininfo->query_result = PQexec(joininfo->conn, sql);
-        
-        if(!joininfo->query_result || 
-            PQresultStatus(joininfo->query_result) != PGRES_TUPLES_OK) {
-            msSetError(MS_QUERYERR, "Error executing queri %s: %s\n",
-                    "msPOSTGRESQLJoinNext()", sql, 
-                    PQerrorMessage(joininfo->conn));
-            if(joininfo->query_result) {
-                PQclear(joininfo->query_result);
-                joininfo->query_result = NULL;
-            }
-            free(sql);
-            return MS_FAILURE;
-        }
-        free(sql);
+    strcpy(columns, "");
+    for(i = 0; i < join->numitems; i++) {
+      strcat(columns, "\"");
+      strcat(columns, join->items[i]);
+      strcat(columns, "\"::text");
+      if(i != join->numitems - 1) {
+        strcat(columns, ", ");
+      }
     }
-    row_count = PQntuples(joininfo->query_result);
 
-    /* see if we're done processing this set */
-    if(joininfo->row_num >= row_count) {
-        return(MS_DONE);
+    /* Create the query string. */
+    sql = (char *)malloc(26 + strlen(columns) + strlen(join->table) +
+                         strlen(join->to) + strlen(joininfo->from_value));
+    if(!sql) {
+      msSetError(MS_MEMERR, "Failure to malloc.\n",
+                 "msPOSTGRESQLJoinNext()");
+      return MS_FAILURE;
     }
+    sprintf(sql, "SELECT %s FROM %s WHERE %s = '%s'", columns, join->table, join->to, joininfo->from_value);
     if(joininfo->layer_debug) {
-        msDebug("msPOSTGRESQLJoinNext(): fetching row %d.\n", 
-                joininfo->row_num);
+      msDebug("msPOSTGRESQLJoinNext(): executing %s.\n", sql);
     }
 
-    /* Copy the resulting values into the joinObj. */
-    join->values = (char **)malloc(sizeof(char *) * join->numitems);
-    for(i = 0; i < join->numitems; i++) {
-        join->values[i] = msStrdup(PQgetvalue(
-                joininfo->query_result, joininfo->row_num, i));
-    }
+    free(columns);
 
-    joininfo->row_num++;
+    joininfo->query_result = PQexec(joininfo->conn, sql);
 
-    return MS_SUCCESS;
+    if(!joininfo->query_result ||
+        PQresultStatus(joininfo->query_result) != PGRES_TUPLES_OK) {
+      msSetError(MS_QUERYERR, "Error executing queri %s: %s\n",
+                 "msPOSTGRESQLJoinNext()", sql,
+                 PQerrorMessage(joininfo->conn));
+      if(joininfo->query_result) {
+        PQclear(joininfo->query_result);
+        joininfo->query_result = NULL;
+      }
+      free(sql);
+      return MS_FAILURE;
+    }
+    free(sql);
+  }
+  row_count = PQntuples(joininfo->query_result);
+
+  /* see if we're done processing this set */
+  if(joininfo->row_num >= row_count) {
+    return(MS_DONE);
+  }
+  if(joininfo->layer_debug) {
+    msDebug("msPOSTGRESQLJoinNext(): fetching row %d.\n",
+            joininfo->row_num);
+  }
+
+  /* Copy the resulting values into the joinObj. */
+  join->values = (char **)malloc(sizeof(char *) * join->numitems);
+  for(i = 0; i < join->numitems; i++) {
+    join->values[i] = msStrdup(PQgetvalue(
+                                 joininfo->query_result, joininfo->row_num, i));
+  }
+
+  joininfo->row_num++;
+
+  return MS_SUCCESS;
 }
 
 /************************************************************************/
@@ -385,57 +388,62 @@ int msPOSTGRESQLJoinNext(joinObj *join) {
 /* Closes the connection and frees the resources used by the joininfo.  */
 /************************************************************************/
 
-int msPOSTGRESQLJoinClose(joinObj *join) {
-    msPOSTGRESQLJoinInfo *joininfo = join->joininfo;
+int msPOSTGRESQLJoinClose(joinObj *join)
+{
+  msPOSTGRESQLJoinInfo *joininfo = join->joininfo;
 
-    if(!joininfo) {
-      msDebug("msPOSTGRESQLJoinClose() already close or never opened.\n");
-      return MS_SUCCESS;
-    }
+  if(!joininfo) {
+    msDebug("msPOSTGRESQLJoinClose() already close or never opened.\n");
+    return MS_SUCCESS;
+  }
 
-    if(joininfo->query_result) {
-      msDebug("msPOSTGRESQLJoinClose(): clearing query_result.\n");
-      PQclear(joininfo->query_result);
-      joininfo->query_result = NULL;
-    }
+  if(joininfo->query_result) {
+    msDebug("msPOSTGRESQLJoinClose(): clearing query_result.\n");
+    PQclear(joininfo->query_result);
+    joininfo->query_result = NULL;
+  }
 
-    if(joininfo->conn) {
-      msDebug("msPOSTGRESQLJoinClose(): closing connection.\n");
-      PQfinish(joininfo->conn);
-      joininfo->conn = NULL;
-    }
+  if(joininfo->conn) {
+    msDebug("msPOSTGRESQLJoinClose(): closing connection.\n");
+    PQfinish(joininfo->conn);
+    joininfo->conn = NULL;
+  }
 
-    /* removed free(joininfo->to_column), see bug #2936 */
+  /* removed free(joininfo->to_column), see bug #2936 */
 
-    if(joininfo->from_value) {
-      free(joininfo->from_value);
-    }
+  if(joininfo->from_value) {
+    free(joininfo->from_value);
+  }
 
-    free(joininfo);
-    join->joininfo = NULL;
+  free(joininfo);
+  join->joininfo = NULL;
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 #else  /* not USE_POSTGIS */
-int msPOSTGRESQLJoinConnect(layerObj *layer, joinObj *join) {
+int msPOSTGRESQLJoinConnect(layerObj *layer, joinObj *join)
+{
   msSetError(MS_QUERYERR, "PostgreSQL support not available.", "msPOSTGRESQLJoinConnect()");
   return MS_FAILURE;
 }
 
-int msPOSTGRESQLJoinPrepare(joinObj *join, shapeObj *shape) {
+int msPOSTGRESQLJoinPrepare(joinObj *join, shapeObj *shape)
+{
   msSetError(MS_QUERYERR, "PostgreSQL support not available.", "msPOSTGRESQLJoinPrepare()");
   return MS_FAILURE;
 
 }
 
-int msPOSTGRESQLJoinNext(joinObj *join) {
+int msPOSTGRESQLJoinNext(joinObj *join)
+{
   msSetError(MS_QUERYERR, "PostgreSQL support not available.", "msPOSTGRESQLJoinNext()");
   return MS_FAILURE;
 
 }
 
-int msPOSTGRESQLJoinClose(joinObj *join) {
+int msPOSTGRESQLJoinClose(joinObj *join)
+{
   msSetError(MS_QUERYERR, "PostgreSQL support not available.", "msPOSTGRESQLJoinClose()");
   return MS_FAILURE;
 
diff --git a/mapprimitive.c b/mapprimitive.c
index c9a63ca..e5deb27 100644
--- a/mapprimitive.c
+++ b/mapprimitive.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -32,7 +32,7 @@
 #include <assert.h>
 #include <locale.h>
 
-MS_CVSID("$Id$")
+
 
 typedef enum {CLIP_LEFT, CLIP_MIDDLE, CLIP_RIGHT} CLIP_STATE;
 
@@ -46,7 +46,7 @@ typedef enum {CLIP_LEFT, CLIP_MIDDLE, CLIP_RIGHT} CLIP_STATE;
 #endif
 #define NEARZERO (1.0e-30) /* 1/INFINITY */
 
-void msPrintShape(shapeObj *p) 
+void msPrintShape(shapeObj *p)
 {
   int i,j;
 
@@ -96,7 +96,7 @@ void msInitShape(shapeObj *shape)
   shape->type = MS_SHAPE_NULL;
   shape->bounds.minx = shape->bounds.miny = -1;
   shape->bounds.maxx = shape->bounds.maxy = -1;
-  
+
   /* attribute component */
   shape->values = NULL;
   shape->numvalues = 0;
@@ -114,7 +114,8 @@ void msInitShape(shapeObj *shape)
   shape->scratch = MS_FALSE; /* not a temporary/scratch shape */
 }
 
-int msCopyShape(shapeObj *from, shapeObj *to) {
+int msCopyShape(shapeObj *from, shapeObj *to)
+{
   int i;
 
   if(!from || !to) return(-1);
@@ -136,7 +137,7 @@ int msCopyShape(shapeObj *from, shapeObj *to) {
   to->tileindex = from->tileindex;
   to->resultindex = from->resultindex;
 
-  if(from->values) {    
+  if(from->values) {
     to->values = (char **)msSmallMalloc(sizeof(char *)*from->numvalues);
     for(i=0; i<from->numvalues; i++)
       to->values[i] = msStrdup(from->values[i]);
@@ -161,7 +162,7 @@ void msFreeShape(shapeObj *shape)
   if (shape->line) free(shape->line);
   if(shape->values) msFreeCharArray(shape->values, shape->numvalues);
   if(shape->text) free(shape->text);
-  
+
 #ifdef USE_GEOS
   msGEOSFreeGeometry(shape);
 #endif
@@ -186,8 +187,8 @@ void msShapeDeleteLine( shapeObj *shape, int line )
 
   free( shape->line[line].point );
   if( line < shape->numlines - 1 ) {
-    memmove( shape->line + line, 
-             shape->line + line + 1, 
+    memmove( shape->line + line,
+             shape->line + line + 1,
              sizeof(lineObj) * (shape->numlines - line - 1) );
   }
   shape->numlines--;
@@ -197,16 +198,15 @@ void msComputeBounds(shapeObj *shape)
 {
   int i, j;
   if(shape->numlines <= 0) return;
-  for(i=0;i<shape->numlines;i++) {
-     if(shape->line[i].numpoints > 0) {
-        shape->bounds.minx = shape->bounds.maxx = shape->line[i].point[0].x;
-        shape->bounds.miny = shape->bounds.maxy = shape->line[i].point[0].y;
-        break;
-     }
+  for(i=0; i<shape->numlines; i++) {
+    if(shape->line[i].numpoints > 0) {
+      shape->bounds.minx = shape->bounds.maxx = shape->line[i].point[0].x;
+      shape->bounds.miny = shape->bounds.maxy = shape->line[i].point[0].y;
+      break;
+    }
   }
-  if(i == shape->numlines)
-     return; //no lines inside the shape contain any points 
-    
+  if(i == shape->numlines) return;
+
   for( i=0; i<shape->numlines; i++ ) {
     for( j=0; j<shape->line[i].numpoints; j++ ) {
       shape->bounds.minx = MS_MIN(shape->bounds.minx, shape->line[i].point[j].x);
@@ -218,9 +218,9 @@ void msComputeBounds(shapeObj *shape)
 }
 
 /* checks to see if ring r is an outer ring of shape */
-int msIsOuterRing(shapeObj *shape, int r) 
+int msIsOuterRing(shapeObj *shape, int r)
 {
-  int i, status=MS_TRUE; 
+  int i, status=MS_TRUE;
   int result1, result2;
 
   if(shape->numlines == 1) return(MS_TRUE);
@@ -239,7 +239,7 @@ int msIsOuterRing(shapeObj *shape, int r)
       if(result1 == MS_TRUE) status = !status;
     } else { /* one of the first 2 points were on the edge of the ring, the next one isn't */
       if(msPointInPolygon(&(shape->line[r].point[2]), &(shape->line[i])) == MS_TRUE)
-      status = !status;
+        status = !status;
     }
 
   }
@@ -248,10 +248,10 @@ int msIsOuterRing(shapeObj *shape, int r)
 }
 
 /*
-** Returns a list of outer rings for shape (the list has one entry for each ring, 
+** Returns a list of outer rings for shape (the list has one entry for each ring,
 ** MS_TRUE for outer rings).
 */
-int *msGetOuterList(shapeObj *shape) 
+int *msGetOuterList(shapeObj *shape)
 {
   int i;
   int *list;
@@ -268,7 +268,7 @@ int *msGetOuterList(shapeObj *shape)
 /*
 ** Returns a list of inner rings for ring r in shape (given a list of outer rings).
 */
-int *msGetInnerList(shapeObj *shape, int r, int *outerlist) 
+int *msGetInnerList(shapeObj *shape, int r, int *outerlist)
 {
   int i;
   int *list;
@@ -293,15 +293,15 @@ int *msGetInnerList(shapeObj *shape, int r, int *outerlist)
 ** Add point to a line object.
 **
 ** Note that reallocating the point array larger for each point can
-** be pretty inefficient, so use this function sparingly.  Mostly 
-** geometries creators should create their own working lineObj and 
+** be pretty inefficient, so use this function sparingly.  Mostly
+** geometries creators should create their own working lineObj and
 ** then call msAddLine() to add it to a shape.
 */
 
 int msAddPointToLine(lineObj *line, pointObj *point )
 {
   line->numpoints += 1;
-    
+
   line->point = (pointObj *) msSmallRealloc(line->point, sizeof(pointObj) * line->numpoints);
   line->point[line->numpoints-1] = *point;
 
@@ -315,7 +315,7 @@ int msAddLine(shapeObj *p, lineObj *new_line)
   lineCopy.numpoints = new_line->numpoints;
   lineCopy.point = (pointObj *) malloc(new_line->numpoints*sizeof(pointObj));
   MS_CHECK_ALLOC(lineCopy.point, new_line->numpoints*sizeof(pointObj), MS_FAILURE);
-    
+
   memcpy( lineCopy.point, new_line->point, sizeof(pointObj) * new_line->numpoints );
 
   return msAddLineDirectly( p, &lineCopy );
@@ -323,24 +323,23 @@ int msAddLine(shapeObj *p, lineObj *new_line)
 
 /*
 ** Same as msAddLine(), except that this version "seizes" the points
-** array from the passed in line and uses it instead of copying it.  
+** array from the passed in line and uses it instead of copying it.
 */
 int msAddLineDirectly(shapeObj *p, lineObj *new_line)
 {
   int c;
 
   if( p->numlines == 0 ) {
-      p->line = (lineObj *) malloc(sizeof(lineObj));
-      MS_CHECK_ALLOC(p->line, sizeof(lineObj), MS_FAILURE);
-  }
-  else {
-      p->line = (lineObj *) realloc(p->line, (p->numlines+1)*sizeof(lineObj));
-      MS_CHECK_ALLOC(p->line, (p->numlines+1)*sizeof(lineObj), MS_FAILURE);
+    p->line = (lineObj *) malloc(sizeof(lineObj));
+    MS_CHECK_ALLOC(p->line, sizeof(lineObj), MS_FAILURE);
+  } else {
+    p->line = (lineObj *) realloc(p->line, (p->numlines+1)*sizeof(lineObj));
+    MS_CHECK_ALLOC(p->line, (p->numlines+1)*sizeof(lineObj), MS_FAILURE);
   }
 
   /* Copy the new line onto the end of the extended line array */
   c= p->numlines;
-  p->line[c].numpoints = new_line->numpoints;  
+  p->line[c].numpoints = new_line->numpoints;
   p->line[c].point = new_line->point;
 
   /* strip points reference off the passed in lineObj */
@@ -363,10 +362,10 @@ int msAddLineDirectly(shapeObj *p, lineObj *new_line)
 */
 void msRectToPolygon(rectObj rect, shapeObj *poly)
 {
-  lineObj line={0,NULL};
+  lineObj line= {0,NULL};
 
   line.point = (pointObj *)msSmallMalloc(sizeof(pointObj)*5);
-  
+
   line.point[0].x = rect.minx;
   line.point[0].y = rect.miny;
   line.point[1].x = rect.minx;
@@ -377,9 +376,9 @@ void msRectToPolygon(rectObj rect, shapeObj *poly)
   line.point[3].y = rect.miny;
   line.point[4].x = line.point[0].x;
   line.point[4].y = line.point[0].y;
-  
+
   line.numpoints = 5;
-  
+
   msAddLine(poly, &line);
   if(poly->numlines == 1) { /* poly was empty to begin with */
     poly->type = MS_SHAPE_POLYGON;
@@ -465,12 +464,12 @@ static int clipLine(double *x1, double *y1, double *x2, double *y2, rectObj rect
 
 /*
 ** Routine for clipping a polyline, stored in a shapeObj struct, to a
-** rectangle. Uses clipLine() function to create a new shapeObj. 
+** rectangle. Uses clipLine() function to create a new shapeObj.
 */
 void msClipPolylineRect(shapeObj *shape, rectObj rect)
 {
   int i,j;
-  lineObj line={0,NULL};
+  lineObj line= {0,NULL};
   double x1, x2, y1, y2;
   shapeObj tmp;
 
@@ -481,7 +480,7 @@ void msClipPolylineRect(shapeObj *shape, rectObj rect)
 
   /*
   ** Don't do any clip processing of shapes completely within the
-  ** clip rectangle based on a comparison of bounds.   We could do 
+  ** clip rectangle based on a comparison of bounds.   We could do
   ** something similar for completely outside, but that rarely occurs
   ** since the spatial query at the layer read level has generally already
   ** discarded all shapes completely outside the rect.
@@ -489,9 +488,8 @@ void msClipPolylineRect(shapeObj *shape, rectObj rect)
   if( shape->bounds.maxx <= rect.maxx
       && shape->bounds.minx >= rect.minx
       && shape->bounds.maxy <= rect.maxy
-      && shape->bounds.miny >= rect.miny )
-  {
-      return;
+      && shape->bounds.miny >= rect.miny ) {
+    return;
   }
 
   for(i=0; i<shape->numlines; i++) {
@@ -515,7 +513,7 @@ void msClipPolylineRect(shapeObj *shape, rectObj rect)
         } else { /* add just the last point */
           line.point[line.numpoints].x = x2;
           line.point[line.numpoints].y = y2;
-          line.numpoints++;      
+          line.numpoints++;
         }
 
         if((x2 != shape->line[i].point[j].x) || (y2 != shape->line[i].point[j].y)) {
@@ -528,17 +526,20 @@ void msClipPolylineRect(shapeObj *shape, rectObj rect)
       y1 = shape->line[i].point[j].y;
     }
 
-    if(line.numpoints > 0)
-      msAddLine(&tmp, &line);
-    free(line.point);
-    line.numpoints = 0; /* new line */
+    if(line.numpoints > 0) {
+      msAddLineDirectly(&tmp, &line);
+    } else {
+      free(line.point);
+      line.numpoints = 0; /* new line */
+    }
   }
-  
+
   for (i=0; i<shape->numlines; i++) free(shape->line[i].point);
   free(shape->line);
 
   shape->line = tmp.line;
   shape->numlines = tmp.numlines;
+  msComputeBounds(shape);
 }
 
 /*
@@ -552,16 +553,16 @@ void msClipPolygonRect(shapeObj *shape, rectObj rect)
   double x1,y1, x2,y2;
 
   shapeObj tmp;
-  lineObj line={0,NULL};
+  lineObj line= {0,NULL};
 
   msInitShape(&tmp);
-  
+
   if(shape->numlines == 0) /* nothing to clip */
     return;
 
   /*
   ** Don't do any clip processing of shapes completely within the
-  ** clip rectangle based on a comparison of bounds.   We could do 
+  ** clip rectangle based on a comparison of bounds.   We could do
   ** something similar for completely outside, but that rarely occurs
   ** since the spatial query at the layer read level has generally already
   ** discarded all shapes completely outside the rect.
@@ -569,9 +570,8 @@ void msClipPolygonRect(shapeObj *shape, rectObj rect)
   if( shape->bounds.maxx <= rect.maxx
       && shape->bounds.minx >= rect.minx
       && shape->bounds.maxy <= rect.maxy
-      && shape->bounds.miny >= rect.miny )
-  {
-      return;
+      && shape->bounds.miny >= rect.miny ) {
+    return;
   }
 
   for(j=0; j<shape->numlines; j++) {
@@ -580,12 +580,12 @@ void msClipPolygonRect(shapeObj *shape, rectObj rect)
     line.numpoints = 0;
 
     for (i = 0; i < shape->line[j].numpoints-1; i++) {
-      
+
       x1 = shape->line[j].point[i].x;
       y1 = shape->line[j].point[i].y;
       x2 = shape->line[j].point[i+1].x;
       y2 = shape->line[j].point[i+1].y;
-      
+
       deltax = x2-x1;
       if (deltax == 0) { /* bump off of the vertical */
         deltax = (x1 > rect.minx) ? -NEARZERO : NEARZERO ;
@@ -594,7 +594,7 @@ void msClipPolygonRect(shapeObj *shape, rectObj rect)
       if (deltay == 0) { /* bump off of the horizontal */
         deltay = (y1 > rect.miny) ? -NEARZERO : NEARZERO ;
       }
-      
+
       if (deltax > 0) { /*  points to right */
         xin = rect.minx;
         xout = rect.maxx;
@@ -609,10 +609,10 @@ void msClipPolygonRect(shapeObj *shape, rectObj rect)
         yin = rect.maxy;
         yout = rect.miny;
       }
-      
+
       tinx = (xin - x1)/deltax;
       tiny = (yin - y1)/deltay;
-      
+
       if (tinx < tiny) { /* hits x first */
         tin1 = tinx;
         tin2 = tiny;
@@ -620,7 +620,7 @@ void msClipPolygonRect(shapeObj *shape, rectObj rect)
         tin1 = tiny;
         tin2 = tinx;
       }
-      
+
       if (1 >= tin1) {
         if (0 < tin1) {
           line.point[line.numpoints].x = xin;
@@ -630,9 +630,9 @@ void msClipPolygonRect(shapeObj *shape, rectObj rect)
         if (1 >= tin2) {
           toutx = (xout - x1)/deltax;
           touty = (yout - y1)/deltay;
-      
+
           tout = (toutx < touty) ? toutx : touty ;
-      
+
           if (0 < tin2 || 0 < tout) {
             if (tin2 <= tout) {
               if (0 < tin2) {
@@ -681,17 +681,18 @@ void msClipPolygonRect(shapeObj *shape, rectObj rect)
       line.point[line.numpoints].x = line.point[0].x; /* force closure */
       line.point[line.numpoints].y = line.point[0].y;
       line.numpoints++;
-      msAddLine(&tmp, &line);
+      msAddLineDirectly(&tmp, &line);
+    } else {
+      free(line.point);
     }
-
-    free(line.point);
   } /* next line */
-  
+
   for (i=0; i<shape->numlines; i++) free(shape->line[i].point);
   free(shape->line);
 
   shape->line = tmp.line;
   shape->numlines = tmp.numlines;
+  msComputeBounds(shape);
 
   return;
 }
@@ -704,7 +705,7 @@ void msOffsetPointRelativeTo(pointObj *point, layerObj *layer)
   double x=0, y=0;
   if ( msCheckParentPointer(layer->map,"map")==MS_FAILURE )
     return;
-  
+
 
   if(layer->transform == MS_TRUE) return; /* nothing to do */
 
@@ -716,38 +717,38 @@ void msOffsetPointRelativeTo(pointObj *point, layerObj *layer)
   if(layer->transform == MS_FALSE || layer->transform == MS_UL) return; /* done */
 
   switch(layer->transform) {
-  case MS_UC:
-    x = (layer->map->width-1)/2;
-    y = 0;
-    break;
-  case MS_UR:
-    x = layer->map->width-1;
-    y = 0;
-    break;
-  case MS_CL:
-    x = 0;
-    y = layer->map->height/2;
-    break;
-  case MS_CC:
-    x = layer->map->width/2;
-    y = layer->map->height/2;
-    break;
-  case MS_CR:
-    x = layer->map->width-1;
-    y = layer->map->height/2;
-    break;
-  case MS_LL:
-    x = 0;
-    y = layer->map->height-1;
-    break;
-  case MS_LC:
-    x = layer->map->width/2;
-    y = layer->map->height-1;
-    break;
-  case MS_LR:
-    x = layer->map->width-1;
-    y = layer->map->height-1;
-    break;
+    case MS_UC:
+      x = (layer->map->width-1)/2;
+      y = 0;
+      break;
+    case MS_UR:
+      x = layer->map->width-1;
+      y = 0;
+      break;
+    case MS_CL:
+      x = 0;
+      y = layer->map->height/2;
+      break;
+    case MS_CC:
+      x = layer->map->width/2;
+      y = layer->map->height/2;
+      break;
+    case MS_CR:
+      x = layer->map->width-1;
+      y = layer->map->height/2;
+      break;
+    case MS_LL:
+      x = 0;
+      y = layer->map->height-1;
+      break;
+    case MS_LC:
+      x = layer->map->width/2;
+      y = layer->map->height-1;
+      break;
+    case MS_LR:
+      x = layer->map->width-1;
+      y = layer->map->height-1;
+      break;
   }
 
   point->x += x;
@@ -759,7 +760,7 @@ void msOffsetPointRelativeTo(pointObj *point, layerObj *layer)
 /*
 ** offsets a shape relative to an image position
 */
-void msOffsetShapeRelativeTo(shapeObj *shape, layerObj *layer) 
+void msOffsetShapeRelativeTo(shapeObj *shape, layerObj *layer)
 {
   int i, j;
   double x=0, y=0;
@@ -767,7 +768,7 @@ void msOffsetShapeRelativeTo(shapeObj *shape, layerObj *layer)
   if(layer->transform == MS_TRUE) return; /* nothing to do */
   if ( msCheckParentPointer(layer->map,"map")==MS_FAILURE )
     return;
-  
+
 
   if(layer->units == MS_PERCENTAGES) {
     for (i=0; i<shape->numlines; i++) {
@@ -781,38 +782,38 @@ void msOffsetShapeRelativeTo(shapeObj *shape, layerObj *layer)
   if(layer->transform == MS_FALSE || layer->transform == MS_UL) return; /* done */
 
   switch(layer->transform) {
-  case MS_UC:
-    x = (layer->map->width-1)/2;
-    y = 0;
-    break;
-  case MS_UR:
-    x = layer->map->width-1;
-    y = 0;
-    break;
-  case MS_CL:
-    x = 0;
-    y = layer->map->height/2;
-    break;
-  case MS_CC:
-    x = layer->map->width/2;
-    y = layer->map->height/2;
-    break;
-  case MS_CR:
-    x = layer->map->width-1;
-    y = layer->map->height/2;
-    break;
-  case MS_LL:
-    x = 0;
-    y = layer->map->height-1;
-    break;
-  case MS_LC:
-    x = layer->map->width/2;
-    y = layer->map->height-1;
-    break;
-  case MS_LR:
-    x = layer->map->width-1;
-    y = layer->map->height-1;
-    break;
+    case MS_UC:
+      x = (layer->map->width-1)/2;
+      y = 0;
+      break;
+    case MS_UR:
+      x = layer->map->width-1;
+      y = 0;
+      break;
+    case MS_CL:
+      x = 0;
+      y = layer->map->height/2;
+      break;
+    case MS_CC:
+      x = layer->map->width/2;
+      y = layer->map->height/2;
+      break;
+    case MS_CR:
+      x = layer->map->width-1;
+      y = layer->map->height/2;
+      break;
+    case MS_LL:
+      x = 0;
+      y = layer->map->height-1;
+      break;
+    case MS_LC:
+      x = layer->map->width/2;
+      y = layer->map->height-1;
+      break;
+    case MS_LR:
+      x = layer->map->width-1;
+      y = layer->map->height-1;
+      break;
   }
 
   for (i=0; i<shape->numlines; i++) {
@@ -827,97 +828,110 @@ void msOffsetShapeRelativeTo(shapeObj *shape, layerObj *layer)
 
 void msTransformShapeSimplify(shapeObj *shape, rectObj extent, double cellsize)
 {
-    int i,j,k,beforelast; /* loop counters */
-    double dx,dy;
-    pointObj *point;
-    double inv_cs = 1.0 / cellsize; /* invert and multiply much faster */
-    if(shape->numlines == 0) return; /* nothing to transform */
+  int i,j,k,beforelast; /* loop counters */
+  double dx,dy;
+  pointObj *point;
+  double inv_cs = 1.0 / cellsize; /* invert and multiply much faster */
+  int ok = 0;
+  if(shape->numlines == 0) return; /* nothing to transform */
 
-    if(shape->type == MS_SHAPE_LINE) {
-        /*
-         * loop through the shape's lines, and do naive simplification
-         * to discard the points that are too close to one another.
-         * currently the threshold is to discard points if they fall
-         * less than a pixel away from their predecessor.
-         * the simplified line is guaranteed to contain at 
-         * least its first and last point
-         */
-        for(i=0; i<shape->numlines; i++) { /* for each part */
-            if(shape->line[i].numpoints<2) {
-                shape->line[i].numpoints=0;
-                continue; /*skip degenerate lines*/
-            }
-            point=shape->line[i].point;
-            /*always keep first point*/
-            point[0].x = MS_MAP2IMAGE_X_IC_DBL(point[0].x, extent.minx, inv_cs);
-            point[0].y = MS_MAP2IMAGE_Y_IC_DBL(point[0].y, extent.maxy, inv_cs);
-            beforelast=shape->line[i].numpoints-1;
-            for(j=1,k=1; j < beforelast; j++ ) { /*loop from second point to first-before-last point*/
-                point[k].x = MS_MAP2IMAGE_X_IC_DBL(point[j].x, extent.minx, inv_cs);
-                point[k].y = MS_MAP2IMAGE_Y_IC_DBL(point[j].y, extent.maxy, inv_cs);
-                dx=(point[k].x-point[k-1].x);
-                dy=(point[k].y-point[k-1].y);
-                if(dx*dx+dy*dy>1)
-                    k++;
-            }
-            /*try to keep last point*/
-            point[k].x = MS_MAP2IMAGE_X_IC_DBL(point[j].x, extent.minx, inv_cs);
-            point[k].y = MS_MAP2IMAGE_Y_IC_DBL(point[j].y, extent.maxy, inv_cs);
-            /*discard last point if equal to the one before it*/
-            if(point[k].x!=point[k-1].x || point[k].y!=point[k-1].y) {
-                shape->line[i].numpoints=k+1;
-            } else {
-                shape->line[i].numpoints=k;
-            }
-            //skip degenerate line once more
-            if(shape->line[i].numpoints<2)
-               shape->line[i].numpoints=0;
-        }
+  if(shape->type == MS_SHAPE_LINE) {
+    /*
+     * loop through the shape's lines, and do naive simplification
+     * to discard the points that are too close to one another.
+     * currently the threshold is to discard points if they fall
+     * less than a pixel away from their predecessor.
+     * the simplified line is guaranteed to contain at
+     * least its first and last point
+     */
+    for(i=0; i<shape->numlines; i++) { /* for each part */
+      if(shape->line[i].numpoints<2) {
+        shape->line[i].numpoints=0;
+        continue; /*skip degenerate lines*/
+      }
+      point=shape->line[i].point;
+      /*always keep first point*/
+      point[0].x = MS_MAP2IMAGE_X_IC_DBL(point[0].x, extent.minx, inv_cs);
+      point[0].y = MS_MAP2IMAGE_Y_IC_DBL(point[0].y, extent.maxy, inv_cs);
+      beforelast=shape->line[i].numpoints-1;
+      for(j=1,k=1; j < beforelast; j++ ) { /*loop from second point to first-before-last point*/
+        point[k].x = MS_MAP2IMAGE_X_IC_DBL(point[j].x, extent.minx, inv_cs);
+        point[k].y = MS_MAP2IMAGE_Y_IC_DBL(point[j].y, extent.maxy, inv_cs);
+        dx=(point[k].x-point[k-1].x);
+        dy=(point[k].y-point[k-1].y);
+        if(dx*dx+dy*dy>1)
+          k++;
+      }
+      /* try to keep last point */
+      point[k].x = MS_MAP2IMAGE_X_IC_DBL(point[j].x, extent.minx, inv_cs);
+      point[k].y = MS_MAP2IMAGE_Y_IC_DBL(point[j].y, extent.maxy, inv_cs);
+      /* discard last point if equal to the one before it */
+      if(point[k].x!=point[k-1].x || point[k].y!=point[k-1].y) {
+        shape->line[i].numpoints=k+1;
+      } else {
+        shape->line[i].numpoints=k;
+      }
+      /* skip degenerate line once more */
+      if(shape->line[i].numpoints<2) {
+        shape->line[i].numpoints=0;
+      } else {
+        ok = 1; /* we have at least one line with more than two points */
+      }
     }
-    else if(shape->type == MS_SHAPE_POLYGON) {
-        /*
-         * loop through the shape's lines, and do naive simplification
-         * to discard the points that are too close to one another.
-         * currently the threshold is to discard points if they fall
-         * less than a pixel away from their predecessor.
-         * the simplified polygon is guaranteed to contain at 
-         * least its first, second and last point
-         */
-        for(i=0; i<shape->numlines; i++) { /* for each part */
-            if(shape->line[i].numpoints<3) {
-                shape->line[i].numpoints=0;
-                continue; /*skip degenerate lines*/
-            }
-            point=shape->line[i].point;
-            /*always keep first and second point*/
-            point[0].x = MS_MAP2IMAGE_X_IC_DBL(point[0].x, extent.minx, inv_cs);
-            point[0].y = MS_MAP2IMAGE_Y_IC_DBL(point[0].y, extent.maxy, inv_cs);
-            point[1].x = MS_MAP2IMAGE_X_IC_DBL(point[1].x, extent.minx, inv_cs);
-            point[1].y = MS_MAP2IMAGE_Y_IC_DBL(point[1].y, extent.maxy, inv_cs);         
-            beforelast=shape->line[i].numpoints-1;
-            for(j=2,k=2; j < beforelast; j++ ) { /*loop from second point to first-before-last point*/
-                point[k].x = MS_MAP2IMAGE_X_IC_DBL(point[j].x, extent.minx, inv_cs);
-                point[k].y = MS_MAP2IMAGE_Y_IC_DBL(point[j].y, extent.maxy, inv_cs);
-                dx=(point[k].x-point[k-1].x);
-                dy=(point[k].y-point[k-1].y);
-                if(dx*dx+dy*dy>1)
-                    k++;
-            }
-            /*always keep last point*/
-            point[k].x = MS_MAP2IMAGE_X_IC_DBL(point[j].x, extent.minx, inv_cs);
-            point[k].y = MS_MAP2IMAGE_Y_IC_DBL(point[j].y, extent.maxy, inv_cs);
-            shape->line[i].numpoints=k+1;
-        }
+  } else if(shape->type == MS_SHAPE_POLYGON) {
+    /*
+     * loop through the shape's lines, and do naive simplification
+     * to discard the points that are too close to one another.
+     * currently the threshold is to discard points if they fall
+     * less than a pixel away from their predecessor.
+     * the simplified polygon is guaranteed to contain at
+     * least its first, second and last point
+     */
+    for(i=0; i<shape->numlines; i++) { /* for each part */
+      if(shape->line[i].numpoints<4) {
+        shape->line[i].numpoints=0;
+        continue; /*skip degenerate lines*/
+      }
+      point=shape->line[i].point;
+      /*always keep first and second point*/
+      point[0].x = MS_MAP2IMAGE_X_IC_DBL(point[0].x, extent.minx, inv_cs);
+      point[0].y = MS_MAP2IMAGE_Y_IC_DBL(point[0].y, extent.maxy, inv_cs);
+      point[1].x = MS_MAP2IMAGE_X_IC_DBL(point[1].x, extent.minx, inv_cs);
+      point[1].y = MS_MAP2IMAGE_Y_IC_DBL(point[1].y, extent.maxy, inv_cs);
+      beforelast=shape->line[i].numpoints-2;
+      for(j=2,k=2; j < beforelast; j++ ) { /*loop from second point to second-before-last point*/
+        point[k].x = MS_MAP2IMAGE_X_IC_DBL(point[j].x, extent.minx, inv_cs);
+        point[k].y = MS_MAP2IMAGE_Y_IC_DBL(point[j].y, extent.maxy, inv_cs);
+        dx=(point[k].x-point[k-1].x);
+        dy=(point[k].y-point[k-1].y);
+        if(dx*dx+dy*dy>1)
+          k++;
+      }
+      /*always keep last two points (the last point is the repetition of the
+       * first one */
+      point[k].x = MS_MAP2IMAGE_X_IC_DBL(point[j].x, extent.minx, inv_cs);
+      point[k].y = MS_MAP2IMAGE_Y_IC_DBL(point[j].y, extent.maxy, inv_cs);
+      point[k+1].x = MS_MAP2IMAGE_X_IC_DBL(point[j+1].x, extent.minx, inv_cs);
+      point[k+1].y = MS_MAP2IMAGE_Y_IC_DBL(point[j+1].y, extent.maxy, inv_cs);
+      shape->line[i].numpoints = k+2;
+      ok = 1;
     }
-    else { /* only for untyped shapes, as point layers don't go through this function */
-        for(i=0; i<shape->numlines; i++) {
-            point=shape->line[i].point;
-            for(j=0;j<shape->line[i].numpoints;j++) {
-                point[j].x = MS_MAP2IMAGE_X_IC_DBL(point[j].x, extent.minx, inv_cs);
-                point[j].y = MS_MAP2IMAGE_Y_IC_DBL(point[j].y, extent.maxy, inv_cs);
-            }
-        }
+  } else { /* only for untyped shapes, as point layers don't go through this function */
+    for(i=0; i<shape->numlines; i++) {
+      point=shape->line[i].point;
+      for(j=0; j<shape->line[i].numpoints; j++) {
+        point[j].x = MS_MAP2IMAGE_X_IC_DBL(point[j].x, extent.minx, inv_cs);
+        point[j].y = MS_MAP2IMAGE_Y_IC_DBL(point[j].y, extent.maxy, inv_cs);
+      }
+    }
+    ok = 1;
+  }
+  if(!ok) {
+    for(i=0; i<shape->numlines; i++) {
+      free(shape->line[i].point);
     }
+    shape->numlines = 0 ;
+  }
 }
 
 /**
@@ -925,136 +939,136 @@ void msTransformShapeSimplify(shapeObj *shape, rectObj extent, double cellsize)
  */
 void  msTransformShape(shapeObj *shape, rectObj extent, double cellsize, imageObj *image)
 {
-	if (image != NULL && MS_RENDERER_PLUGIN(image->format)) {
-	   rendererVTableObj *renderer = MS_IMAGE_RENDERER(image);
-	   if(renderer->transform_mode == MS_TRANSFORM_SNAPTOGRID) {
-	      msTransformShapeToPixelSnapToGrid(shape, extent, cellsize, renderer->approximation_scale);
-	   } else if(renderer->transform_mode == MS_TRANSFORM_SIMPLIFY) {
-         msTransformShapeSimplify(shape, extent, cellsize);
-      } else if(renderer->transform_mode == MS_TRANSFORM_ROUND) {
-	      msTransformShapeToPixelRound(shape, extent, cellsize);
-      } else if(renderer->transform_mode == MS_TRANSFORM_FULLRESOLUTION) {
-	      msTransformShapeToPixelDoublePrecision(shape,extent,cellsize);
-	   } else if(renderer->transform_mode == MS_TRANSFORM_NONE) {
-         /* nothing to do */
-         return;
-      } 
-	   /* unknown, do nothing */
-		return;
-	}
-   msTransformShapeToPixelRound(shape, extent, cellsize);
+  if (image != NULL && MS_RENDERER_PLUGIN(image->format)) {
+    rendererVTableObj *renderer = MS_IMAGE_RENDERER(image);
+    if(renderer->transform_mode == MS_TRANSFORM_SNAPTOGRID) {
+      msTransformShapeToPixelSnapToGrid(shape, extent, cellsize, renderer->approximation_scale);
+    } else if(renderer->transform_mode == MS_TRANSFORM_SIMPLIFY) {
+      msTransformShapeSimplify(shape, extent, cellsize);
+    } else if(renderer->transform_mode == MS_TRANSFORM_ROUND) {
+      msTransformShapeToPixelRound(shape, extent, cellsize);
+    } else if(renderer->transform_mode == MS_TRANSFORM_FULLRESOLUTION) {
+      msTransformShapeToPixelDoublePrecision(shape,extent,cellsize);
+    } else if(renderer->transform_mode == MS_TRANSFORM_NONE) {
+      /* nothing to do */
+      return;
+    }
+    /* unknown, do nothing */
+    return;
+  }
+  msTransformShapeToPixelRound(shape, extent, cellsize);
 }
 
 void msTransformShapeToPixelSnapToGrid(shapeObj *shape, rectObj extent, double cellsize, double grid_resolution)
 {
-   int i,j,k; /* loop counters */
-   double inv_cs;
-   if(shape->numlines == 0) return;
-   inv_cs = 1.0 / cellsize; /* invert and multiply much faster */
-   
-   
-   if(shape->type == MS_SHAPE_LINE || shape->type == MS_SHAPE_POLYGON) { /* remove duplicate vertices */
-      for(i=0; i<shape->numlines; i++) { /* for each part */
-         int snap = 1;
-         double x0,y0,x1,y1,x2,y2;
-         /*do a quick heuristic: will we risk having a degenerate shape*/
-         if(shape->type == MS_SHAPE_LINE) {
-            /*a line is degenerate if it has a single pixel. we check that the first and last pixel are different*/
-            x0 = MS_MAP2IMAGE_X_IC_SNAP(shape->line[i].point[0].x, extent.minx, inv_cs, grid_resolution);
-            y0 = MS_MAP2IMAGE_Y_IC_SNAP(shape->line[i].point[0].y, extent.maxy, inv_cs, grid_resolution);
-            x1 = MS_MAP2IMAGE_X_IC_SNAP(shape->line[i].point[shape->line[i].numpoints-1].x, extent.minx, inv_cs, grid_resolution);
-            y1 = MS_MAP2IMAGE_Y_IC_SNAP(shape->line[i].point[shape->line[i].numpoints-1].y, extent.maxy, inv_cs, grid_resolution);
-            if(x0 == x1 && y0 == y1) {
-               snap = 0;
-            }
-         } else if(shape->type == MS_SHAPE_POLYGON) {
-            x0 = MS_MAP2IMAGE_X_IC_SNAP(shape->line[i].point[0].x, extent.minx, inv_cs, grid_resolution);
-            y0 = MS_MAP2IMAGE_Y_IC_SNAP(shape->line[i].point[0].y, extent.maxy, inv_cs, grid_resolution);
-            x1 = MS_MAP2IMAGE_X_IC_SNAP(shape->line[i].point[shape->line[i].numpoints/3].x, extent.minx, inv_cs, grid_resolution);
-            y1 = MS_MAP2IMAGE_Y_IC_SNAP(shape->line[i].point[shape->line[i].numpoints/3].y, extent.maxy, inv_cs, grid_resolution);
-            x2 = MS_MAP2IMAGE_X_IC_SNAP(shape->line[i].point[shape->line[i].numpoints/3*2].x, extent.minx, inv_cs, grid_resolution);
-            y2 = MS_MAP2IMAGE_Y_IC_SNAP(shape->line[i].point[shape->line[i].numpoints/3*2].y, extent.maxy, inv_cs, grid_resolution);
-            if((x0 == x1 && y0 == y1) ||
-                  (x0 == x2 && y0 == y2) ||
-                  (x1 == x2 && y1 == y2)) {
-               snap = 0;
-            }
-         }
-         if(snap) {
-               shape->line[i].point[0].x = x0;
-               shape->line[i].point[0].y = y0;
-               for(j=1, k=1; j < shape->line[i].numpoints; j++ ) {
-                  shape->line[i].point[k].x = MS_MAP2IMAGE_X_IC_SNAP(shape->line[i].point[j].x, extent.minx, inv_cs, grid_resolution);
-                  shape->line[i].point[k].y = MS_MAP2IMAGE_Y_IC_SNAP(shape->line[i].point[j].y, extent.maxy, inv_cs, grid_resolution);
-                  if(shape->line[i].point[k].x!=shape->line[i].point[k-1].x || shape->line[i].point[k].y!=shape->line[i].point[k-1].y)
-                     k++;
-               }
-               shape->line[i].numpoints=k;
-         } else {
-            if(shape->type == MS_SHAPE_LINE) {
-               shape->line[i].point[0].x = MS_MAP2IMAGE_X_IC_DBL(shape->line[i].point[0].x, extent.minx, inv_cs);
-               shape->line[i].point[0].y = MS_MAP2IMAGE_Y_IC_DBL(shape->line[i].point[0].y, extent.maxy, inv_cs);
-               shape->line[i].point[1].x = MS_MAP2IMAGE_X_IC_DBL(shape->line[i].point[shape->line[i].numpoints-1].x, extent.minx, inv_cs);
-               shape->line[i].point[1].y = MS_MAP2IMAGE_Y_IC_DBL(shape->line[i].point[shape->line[i].numpoints-1].y, extent.maxy, inv_cs);      
-               shape->line[i].numpoints = 2;
-            } else {
-               for(j=0; j < shape->line[i].numpoints; j++ ) {
-                  shape->line[i].point[j].x = MS_MAP2IMAGE_X_IC_DBL(shape->line[i].point[j].x, extent.minx, inv_cs);
-                  shape->line[i].point[j].y = MS_MAP2IMAGE_Y_IC_DBL(shape->line[i].point[j].y, extent.maxy, inv_cs);
-               }
-            }
-         }
+  int i,j,k; /* loop counters */
+  double inv_cs;
+  if(shape->numlines == 0) return;
+  inv_cs = 1.0 / cellsize; /* invert and multiply much faster */
+
+
+  if(shape->type == MS_SHAPE_LINE || shape->type == MS_SHAPE_POLYGON) { /* remove duplicate vertices */
+    for(i=0; i<shape->numlines; i++) { /* for each part */
+      int snap = 1;
+      double x0,y0,x1,y1,x2,y2;
+      /*do a quick heuristic: will we risk having a degenerate shape*/
+      if(shape->type == MS_SHAPE_LINE) {
+        /*a line is degenerate if it has a single pixel. we check that the first and last pixel are different*/
+        x0 = MS_MAP2IMAGE_X_IC_SNAP(shape->line[i].point[0].x, extent.minx, inv_cs, grid_resolution);
+        y0 = MS_MAP2IMAGE_Y_IC_SNAP(shape->line[i].point[0].y, extent.maxy, inv_cs, grid_resolution);
+        x1 = MS_MAP2IMAGE_X_IC_SNAP(shape->line[i].point[shape->line[i].numpoints-1].x, extent.minx, inv_cs, grid_resolution);
+        y1 = MS_MAP2IMAGE_Y_IC_SNAP(shape->line[i].point[shape->line[i].numpoints-1].y, extent.maxy, inv_cs, grid_resolution);
+        if(x0 == x1 && y0 == y1) {
+          snap = 0;
+        }
+      } else if(shape->type == MS_SHAPE_POLYGON) {
+        x0 = MS_MAP2IMAGE_X_IC_SNAP(shape->line[i].point[0].x, extent.minx, inv_cs, grid_resolution);
+        y0 = MS_MAP2IMAGE_Y_IC_SNAP(shape->line[i].point[0].y, extent.maxy, inv_cs, grid_resolution);
+        x1 = MS_MAP2IMAGE_X_IC_SNAP(shape->line[i].point[shape->line[i].numpoints/3].x, extent.minx, inv_cs, grid_resolution);
+        y1 = MS_MAP2IMAGE_Y_IC_SNAP(shape->line[i].point[shape->line[i].numpoints/3].y, extent.maxy, inv_cs, grid_resolution);
+        x2 = MS_MAP2IMAGE_X_IC_SNAP(shape->line[i].point[shape->line[i].numpoints/3*2].x, extent.minx, inv_cs, grid_resolution);
+        y2 = MS_MAP2IMAGE_Y_IC_SNAP(shape->line[i].point[shape->line[i].numpoints/3*2].y, extent.maxy, inv_cs, grid_resolution);
+        if((x0 == x1 && y0 == y1) ||
+            (x0 == x2 && y0 == y2) ||
+            (x1 == x2 && y1 == y2)) {
+          snap = 0;
+        }
       }
-   } else { /* points or untyped shapes */
-      for(i=0; i<shape->numlines; i++) { /* for each part */
-         for(j=1; j < shape->line[i].numpoints; j++ ) {
+      if(snap) {
+        shape->line[i].point[0].x = x0;
+        shape->line[i].point[0].y = y0;
+        for(j=1, k=1; j < shape->line[i].numpoints; j++ ) {
+          shape->line[i].point[k].x = MS_MAP2IMAGE_X_IC_SNAP(shape->line[i].point[j].x, extent.minx, inv_cs, grid_resolution);
+          shape->line[i].point[k].y = MS_MAP2IMAGE_Y_IC_SNAP(shape->line[i].point[j].y, extent.maxy, inv_cs, grid_resolution);
+          if(shape->line[i].point[k].x!=shape->line[i].point[k-1].x || shape->line[i].point[k].y!=shape->line[i].point[k-1].y)
+            k++;
+        }
+        shape->line[i].numpoints=k;
+      } else {
+        if(shape->type == MS_SHAPE_LINE) {
+          shape->line[i].point[0].x = MS_MAP2IMAGE_X_IC_DBL(shape->line[i].point[0].x, extent.minx, inv_cs);
+          shape->line[i].point[0].y = MS_MAP2IMAGE_Y_IC_DBL(shape->line[i].point[0].y, extent.maxy, inv_cs);
+          shape->line[i].point[1].x = MS_MAP2IMAGE_X_IC_DBL(shape->line[i].point[shape->line[i].numpoints-1].x, extent.minx, inv_cs);
+          shape->line[i].point[1].y = MS_MAP2IMAGE_Y_IC_DBL(shape->line[i].point[shape->line[i].numpoints-1].y, extent.maxy, inv_cs);
+          shape->line[i].numpoints = 2;
+        } else {
+          for(j=0; j < shape->line[i].numpoints; j++ ) {
             shape->line[i].point[j].x = MS_MAP2IMAGE_X_IC_DBL(shape->line[i].point[j].x, extent.minx, inv_cs);
             shape->line[i].point[j].y = MS_MAP2IMAGE_Y_IC_DBL(shape->line[i].point[j].y, extent.maxy, inv_cs);
-         }
+          }
+        }
+      }
+    }
+  } else { /* points or untyped shapes */
+    for(i=0; i<shape->numlines; i++) { /* for each part */
+      for(j=1; j < shape->line[i].numpoints; j++ ) {
+        shape->line[i].point[j].x = MS_MAP2IMAGE_X_IC_DBL(shape->line[i].point[j].x, extent.minx, inv_cs);
+        shape->line[i].point[j].y = MS_MAP2IMAGE_Y_IC_DBL(shape->line[i].point[j].y, extent.maxy, inv_cs);
       }
-   }
+    }
+  }
 
 }
 
 void msTransformShapeToPixelRound(shapeObj *shape, rectObj extent, double cellsize)
 {
-   int i,j,k; /* loop counters */
-   double inv_cs;
-   if(shape->numlines == 0) return;
-   inv_cs = 1.0 / cellsize; /* invert and multiply much faster */
-   if(shape->type == MS_SHAPE_LINE || shape->type == MS_SHAPE_POLYGON) { /* remove duplicate vertices */
-      for(i=0; i<shape->numlines; i++) { /* for each part */
-         shape->line[i].point[0].x = MS_MAP2IMAGE_X_IC(shape->line[i].point[0].x, extent.minx, inv_cs);;
-         shape->line[i].point[0].y = MS_MAP2IMAGE_Y_IC(shape->line[i].point[0].y, extent.maxy, inv_cs);
-         for(j=1, k=1; j < shape->line[i].numpoints; j++ ) {
-            shape->line[i].point[k].x = MS_MAP2IMAGE_X_IC(shape->line[i].point[j].x, extent.minx, inv_cs);
-            shape->line[i].point[k].y = MS_MAP2IMAGE_Y_IC(shape->line[i].point[j].y, extent.maxy, inv_cs);
-            if(shape->line[i].point[k].x!=shape->line[i].point[k-1].x || shape->line[i].point[k].y!=shape->line[i].point[k-1].y)
-               k++;
-         }
-         shape->line[i].numpoints=k;
+  int i,j,k; /* loop counters */
+  double inv_cs;
+  if(shape->numlines == 0) return;
+  inv_cs = 1.0 / cellsize; /* invert and multiply much faster */
+  if(shape->type == MS_SHAPE_LINE || shape->type == MS_SHAPE_POLYGON) { /* remove duplicate vertices */
+    for(i=0; i<shape->numlines; i++) { /* for each part */
+      shape->line[i].point[0].x = MS_MAP2IMAGE_X_IC(shape->line[i].point[0].x, extent.minx, inv_cs);;
+      shape->line[i].point[0].y = MS_MAP2IMAGE_Y_IC(shape->line[i].point[0].y, extent.maxy, inv_cs);
+      for(j=1, k=1; j < shape->line[i].numpoints; j++ ) {
+        shape->line[i].point[k].x = MS_MAP2IMAGE_X_IC(shape->line[i].point[j].x, extent.minx, inv_cs);
+        shape->line[i].point[k].y = MS_MAP2IMAGE_Y_IC(shape->line[i].point[j].y, extent.maxy, inv_cs);
+        if(shape->line[i].point[k].x!=shape->line[i].point[k-1].x || shape->line[i].point[k].y!=shape->line[i].point[k-1].y)
+          k++;
       }
-   } else { /* points or untyped shapes */
-      for(i=0; i<shape->numlines; i++) { /* for each part */
-         for(j=1; j < shape->line[i].numpoints; j++ ) {
-            shape->line[i].point[j].x = MS_MAP2IMAGE_X_IC(shape->line[i].point[j].x, extent.minx, inv_cs);
-            shape->line[i].point[j].y = MS_MAP2IMAGE_Y_IC(shape->line[i].point[j].y, extent.maxy, inv_cs);
-         }
+      shape->line[i].numpoints=k;
+    }
+  } else { /* points or untyped shapes */
+    for(i=0; i<shape->numlines; i++) { /* for each part */
+      for(j=0; j < shape->line[i].numpoints; j++ ) {
+        shape->line[i].point[j].x = MS_MAP2IMAGE_X_IC(shape->line[i].point[j].x, extent.minx, inv_cs);
+        shape->line[i].point[j].y = MS_MAP2IMAGE_Y_IC(shape->line[i].point[j].y, extent.maxy, inv_cs);
       }
-   }
+    }
+  }
 
 }
 
 void msTransformShapeToPixelDoublePrecision(shapeObj *shape, rectObj extent, double cellsize)
 {
-   int i,j; /* loop counters */
-   double inv_cs = 1.0 / cellsize; /* invert and multiply much faster */
-   for(i=0; i<shape->numlines; i++) {
-      for(j=0;j<shape->line[i].numpoints;j++) {
-         shape->line[i].point[j].x = MS_MAP2IMAGE_X_IC_DBL(shape->line[i].point[j].x, extent.minx, inv_cs);
-         shape->line[i].point[j].y = MS_MAP2IMAGE_Y_IC_DBL(shape->line[i].point[j].y, extent.maxy, inv_cs);
-      }
-   }
+  int i,j; /* loop counters */
+  double inv_cs = 1.0 / cellsize; /* invert and multiply much faster */
+  for(i=0; i<shape->numlines; i++) {
+    for(j=0; j<shape->line[i].numpoints; j++) {
+      shape->line[i].point[j].x = MS_MAP2IMAGE_X_IC_DBL(shape->line[i].point[j].x, extent.minx, inv_cs);
+      shape->line[i].point[j].y = MS_MAP2IMAGE_Y_IC_DBL(shape->line[i].point[j].y, extent.maxy, inv_cs);
+    }
+  }
 }
 
 
@@ -1070,7 +1084,7 @@ void msTransformPixelToShape(shapeObj *shape, rectObj extent, double cellsize)
 
   if(shape->type == MS_SHAPE_LINE || shape->type == MS_SHAPE_POLYGON) { /* remove co-linear vertices */
 
-    for(i=0; i<shape->numlines; i++) { /* for each part */         
+    for(i=0; i<shape->numlines; i++) { /* for each part */
       for(j=0; j < shape->line[i].numpoints; j++ ) {
         shape->line[i].point[j].x = MS_IMAGE2MAP_X(shape->line[i].point[j].x, extent.minx, cellsize);
         shape->line[i].point[j].y = MS_IMAGE2MAP_Y(shape->line[i].point[j].y, extent.maxy, cellsize);
@@ -1093,7 +1107,7 @@ void msTransformPixelToShape(shapeObj *shape, rectObj extent, double cellsize)
 ** Not a generic intersection test, we KNOW the lines aren't parallel or coincident. To be used with the next
 ** buffering code only. See code in mapsearch.c for a boolean test for intersection.
 */
-static pointObj generateLineIntersection(pointObj a, pointObj b, pointObj c, pointObj d) 
+static pointObj generateLineIntersection(pointObj a, pointObj b, pointObj c, pointObj d)
 {
   pointObj p;
   double r;
@@ -1101,8 +1115,8 @@ static pointObj generateLineIntersection(pointObj a, pointObj b, pointObj c, poi
 
   if(b.x == c.x && b.y == c.y) return(b);
 
-  numerator = ((a.y-c.y)*(d.x-c.x) - (a.x-c.x)*(d.y-c.y));  
-  denominator = ((b.x-a.x)*(d.y-c.y) - (b.y-a.y)*(d.x-c.x));  
+  numerator = ((a.y-c.y)*(d.x-c.x) - (a.x-c.x)*(d.y-c.y));
+  denominator = ((b.x-a.x)*(d.y-c.y) - (b.y-a.y)*(d.x-c.x));
 
   r = numerator/denominator;
 
@@ -1118,13 +1132,13 @@ void bufferPolyline(shapeObj *p, shapeObj *op, int w)
   pointObj a;
   lineObj inside, outside;
   double angle;
-  double dx, dy;  
+  double dx, dy;
 
   for (i = 0; i < p->numlines; i++) {
 
     inside.point = (pointObj *)msSmallMalloc(sizeof(pointObj)*p->line[i].numpoints);
     outside.point = (pointObj *)msSmallMalloc(sizeof(pointObj)*p->line[i].numpoints);
-    inside.numpoints = outside.numpoints = p->line[i].numpoints;    
+    inside.numpoints = outside.numpoints = p->line[i].numpoints;
 
     angle = asin(MS_ABS(p->line[i].point[1].x - p->line[i].point[0].x)/sqrt((((p->line[i].point[1].x - p->line[i].point[0].x)*(p->line[i].point[1].x - p->line[i].point[0].x)) + ((p->line[i].point[1].y - p->line[i].point[0].y)*(p->line[i].point[1].y - p->line[i].point[0].y)))));
     if(p->line[i].point[0].x < p->line[i].point[1].x)
@@ -1140,7 +1154,7 @@ void bufferPolyline(shapeObj *p, shapeObj *op, int w)
     inside.point[1].x = p->line[i].point[1].x + dx;
     inside.point[0].y = p->line[i].point[0].y + dy;
     inside.point[1].y = p->line[i].point[1].y + dy;
-    
+
     outside.point[0].x = p->line[i].point[0].x - dx;
     outside.point[1].x = p->line[i].point[1].x - dx;
     outside.point[0].y = p->line[i].point[0].y - dy;
@@ -1162,7 +1176,7 @@ void bufferPolyline(shapeObj *p, shapeObj *op, int w)
       inside.point[j].x = p->line[i].point[j].x + dx;
       a.y = p->line[i].point[j-1].y + dy;
       inside.point[j].y = p->line[i].point[j].y + dy;
-      inside.point[j-1] = generateLineIntersection(inside.point[j-2], inside.point[j-1], a, inside.point[j]);      
+      inside.point[j-1] = generateLineIntersection(inside.point[j-2], inside.point[j-1], a, inside.point[j]);
 
       a.x = p->line[i].point[j-1].x - dx;
       outside.point[j].x = p->line[i].point[j].x - dx;
@@ -1179,7 +1193,7 @@ void bufferPolyline(shapeObj *p, shapeObj *op, int w)
     free(inside.point);
     free(outside.point);
   }
-  
+
   return;
 }
 
@@ -1194,7 +1208,7 @@ static double getRingArea(lineObj *ring)
   return (MS_ABS(s/2));
 }
 
-double msGetPolygonArea(shapeObj *p) 
+double msGetPolygonArea(shapeObj *p)
 {
   int i;
   double area=0;
@@ -1212,7 +1226,7 @@ double msGetPolygonArea(shapeObj *p)
 /*
 ** Computes the center of gravity for a polygon based on it's largest outer ring only.
 */
-static int getPolygonCenterOfGravity(shapeObj *p, pointObj *lp) 
+static int getPolygonCenterOfGravity(shapeObj *p, pointObj *lp)
 {
   int i, j;
   double area=0;
@@ -1267,7 +1281,7 @@ int msGetPolygonCentroid(shapeObj *p, pointObj *lp, double *miny, double *maxy)
 
   lp->x = cent_weight_x / total_len;
   lp->y = cent_weight_y / total_len;
-  
+
   return(MS_SUCCESS);
 }
 
@@ -1293,30 +1307,30 @@ int msPolygonLabelPoint(shapeObj *p, pointObj *lp, double min_dimension)
   maxx = p->bounds.maxx;
   maxy = p->bounds.maxy;
 
-  if(min_dimension != -1)
+  if(min_dimension > 0)
     if(MS_MIN(maxx-minx,maxy-miny) < min_dimension) return(MS_FAILURE);
 
   cp.x = (maxx+minx)/2.0;
   cp.y = (maxy+miny)/2.0;
 
   switch (method) {
-  case 0: /* MBR */
-    lp->x = cp.x;
-    lp->y = cp.y;
-    break;
-  case 1: /* centroid */
-    if(msGetPolygonCentroid(p, lp, &miny, &maxy) != MS_SUCCESS) return(MS_FAILURE);  
-    break;
-  case 2: /* center of gravity */
-    if(getPolygonCenterOfGravity(p, lp) != MS_SUCCESS) return(MS_FAILURE);
-    break;
+    case 0: /* MBR */
+      lp->x = cp.x;
+      lp->y = cp.y;
+      break;
+    case 1: /* centroid */
+      if(msGetPolygonCentroid(p, lp, &miny, &maxy) != MS_SUCCESS) return(MS_FAILURE);
+      break;
+    case 2: /* center of gravity */
+      if(getPolygonCenterOfGravity(p, lp) != MS_SUCCESS) return(MS_FAILURE);
+      break;
   }
 
   if(msIntersectPointPolygon(lp, p) == MS_TRUE) {
     double dist, min_dist=-1;
 
     /* compute a distance to the polygon */
-    for(j=0;j<p->numlines;j++) {
+    for(j=0; j<p->numlines; j++) {
       for(i=1; i<p->line[j].numpoints; i++) {
         dist = msSquareDistancePointToSegment(lp, &(p->line[j].point[i-1]), &(p->line[j].point[i]));
         if((dist < min_dist) || (min_dist < 0)) min_dist = dist;
@@ -1328,35 +1342,35 @@ int msPolygonLabelPoint(shapeObj *p, pointObj *lp, double min_dimension)
       return(MS_SUCCESS); /* point is not too close to the edge */
   }
 
-  // printf("label: %s\n", p->text);
-  // printf("    bbox: %g %g %g %g\n",minx, miny, maxx, maxy);
-  // printf("    center: %g %g\n", cp.x, cp.y);
-  // printf("    center of gravity: %g %g\n", lp->x, lp->y);
-  // printf("    dx: %g, dy: %g\n", lp->x-cp.x, lp->y-cp.y);
-  // printf("    distance to parent shape: %g\n", min_dist);
-  // return MS_SUCCESS;
+  /* printf("label: %s\n", p->text);
+     printf("    bbox: %g %g %g %g\n",minx, miny, maxx, maxy);
+     printf("    center: %g %g\n", cp.x, cp.y);
+     printf("    center of gravity: %g %g\n", lp->x, lp->y);
+     printf("    dx: %g, dy: %g\n", lp->x-cp.x, lp->y-cp.y);
+     printf("    distance to parent shape: %g\n", min_dist);
+     return MS_SUCCESS; */
 
   n=0;
   for(j=0; j<p->numlines; j++) /* count total number of points */
     n += p->line[j].numpoints;
   intersect = (double *) calloc(n, sizeof(double));
   MS_CHECK_ALLOC(intersect, n*sizeof(double), MS_FAILURE);
-  
+
 
   if(MS_ABS((int)lp->x - (int)cp.x) > MS_ABS((int)lp->y - (int)cp.y)) { /* center horizontally, fix y */
 
     y = lp->y;
 
-    /* need to find a y that won't intersect any vertices exactly */  
+    /* need to find a y that won't intersect any vertices exactly */
     max = y - 1; /* first initializing min, max to be any 2 pnts on either side of y */
     min = y + 1;
     for(j=0; j<p->numlines; j++) {
       if((min < y) && (max >= y))  break;
       for(i=0; i < p->line[j].numpoints; i++) {
         if((min < y) && (max >= y))  break;
-        if(p->line[j].point[i].y < y) 
+        if(p->line[j].point[i].y < y)
           min = p->line[j].point[i].y;
-        if(p->line[j].point[i].y >= y) 
+        if(p->line[j].point[i].y >= y)
           max = p->line[j].point[i].y;
       }
     }
@@ -1371,33 +1385,33 @@ int msPolygonLabelPoint(shapeObj *p, pointObj *lp, double min_dimension)
       }
     }
 
-    if(min == max) 
+    if(min == max)
       return (MS_FAILURE);
-    else  
-      y = (max + min)/2.0;    
-    
+    else
+      y = (max + min)/2.0;
+
     nfound = 0;
     for(j=0; j<p->numlines; j++) { /* for each line */
-      
+
       point1 = &( p->line[j].point[p->line[j].numpoints-1] );
       for(i=0; i < p->line[j].numpoints; i++) {
         point2 = &( p->line[j].point[i] );
-    
+
         if(EDGE_CHECK(point1->y, y, point2->y) == CLIP_MIDDLE) {
-      
+
           if(point1->y == point2->y)
             continue; /* ignore horizontal edges */
-          else      
+          else
             slope = (point2->x - point1->x) / (point2->y - point1->y);
-      
+
           x = point1->x + (y - point1->y)*slope;
           intersect[nfound++] = x;
         } /* end checking this edge */
-    
+
         point1 = point2; /* next edge */
       }
     } /* finished line */
-    
+
     /* sort the intersections */
     do {
       wrong_order = 0;
@@ -1408,29 +1422,29 @@ int msPolygonLabelPoint(shapeObj *p, pointObj *lp, double min_dimension)
         }
       }
     } while(wrong_order);
-    
+
     /* find longest span */
     for(i=0; i < nfound; i += 2) {
       len = fabs(intersect[i] - intersect[i+1]);
       if(len > max_len) {
         max_len = len;
         lp->x = (intersect[i] + intersect[i+1])/2;
-        // lp->y = y;
+        /* lp->y = y; */
       }
     }
   } else { /* center vertically, fix x */
     x = lp->x;
 
-    /* need to find a x that won't intersect any vertices exactly */  
+    /* need to find a x that won't intersect any vertices exactly */
     max = x - 1; /* first initializing min, max to be any 2 pnts on either side of x */
     min = x + 1;
     for(j=0; j<p->numlines; j++) {
       if((min < x) && (max >= x))  break;
       for(i=0; i < p->line[j].numpoints; i++) {
         if((min < x) && (max >= x))  break;
-        if(p->line[j].point[i].x < x) 
+        if(p->line[j].point[i].x < x)
           min = p->line[j].point[i].x;
-        if(p->line[j].point[i].x >= x) 
+        if(p->line[j].point[i].x >= x)
           max = p->line[j].point[i].x;
       }
     }
@@ -1445,20 +1459,20 @@ int msPolygonLabelPoint(shapeObj *p, pointObj *lp, double min_dimension)
       }
     }
 
-    if(min == max) 
+    if(min == max)
       return (MS_FAILURE);
-    else  
+    else
       x = (max + min)/2.0;
-    
+
     nfound = 0;
     for(j=0; j<p->numlines; j++) { /* for each line */
-      
+
       point1 = &( p->line[j].point[p->line[j].numpoints-1] );
       for(i=0; i < p->line[j].numpoints; i++) {
         point2 = &( p->line[j].point[i] );
-    
+
         if(EDGE_CHECK(point1->x, x, point2->x) == CLIP_MIDDLE) {
-      
+
           if(point1->x == point2->x)
             continue; /* ignore vertical edges */
           else if(point1->y == point2->y)
@@ -1470,11 +1484,11 @@ int msPolygonLabelPoint(shapeObj *p, pointObj *lp, double min_dimension)
 
           intersect[nfound++] = y;
         } /* end checking this edge */
-    
+
         point1 = point2; /* next edge */
       }
     } /* finished line */
-    
+
     /* sort the intersections */
     do {
       wrong_order = 0;
@@ -1485,14 +1499,14 @@ int msPolygonLabelPoint(shapeObj *p, pointObj *lp, double min_dimension)
         }
       }
     } while(wrong_order);
-    
+
     /* find longest span */
     for(i=0; i < nfound; i += 2) {
       len = fabs(intersect[i] - intersect[i+1]);
-      if(len > max_len) {        
+      if(len > max_len) {
         max_len = len;
         lp->y = (intersect[i] + intersect[i+1])/2;
-        // lp->x = x;
+        /* lp->x = x; */
       }
     }
   }
@@ -1505,7 +1519,7 @@ int msPolygonLabelPoint(shapeObj *p, pointObj *lp, double min_dimension)
     return(MS_FAILURE);
 }
 
-/* Compute all the lineString/segment lengths and determine the longest lineString of a multiLineString  
+/* Compute all the lineString/segment lengths and determine the longest lineString of a multiLineString
  * shape: in paramater, the multiLineString to compute.
  * segment_lengths: out parameter, the segment lengths of all lineString.
  * line_lengths: out parameter, the lineString lengths of the multiLineString.
@@ -1527,12 +1541,12 @@ void msPolylineComputeLineSegments(shapeObj *shape, double ***segment_lengths, d
   *total_length = 0;
   *max_line_length = 0;
   for(i=0; i<shape->numlines; i++) {
-    
-    (*segment_lengths)[i] = (double*) msSmallMalloc(sizeof(double) * shape->line[i].numpoints);    
-    
+
+    (*segment_lengths)[i] = (double*) msSmallMalloc(sizeof(double) * shape->line[i].numpoints);
+
     (*line_lengths)[i] = 0;
     max_segment_length = 0;
-    for(j=1;j<shape->line[i].numpoints;j++) {
+    for(j=1; j<shape->line[i].numpoints; j++) {
       segment_length = sqrt((((shape->line[i].point[j].x-shape->line[i].point[j-1].x)*(shape->line[i].point[j].x-shape->line[i].point[j-1].x)) + ((shape->line[i].point[j].y-shape->line[i].point[j-1].y)*(shape->line[i].point[j].y-shape->line[i].point[j-1].y))));
       (*line_lengths)[i] += segment_length;
       (*segment_lengths)[i][j-1] = segment_length;
@@ -1570,7 +1584,7 @@ pointObj** msPolylineLabelPointExtended(shapeObj *p, int min_length, int repeat_
   pointObj** labelpoints;
 
   labelpoints_index = 0;
-  labelpoints_size = p->numlines; // minimal array size
+  labelpoints_size = p->numlines; /* minimal array size */
   *numpoints = 0;
 
   labelpoints = (pointObj **) msSmallMalloc(sizeof(pointObj *) * labelpoints_size);
@@ -1584,15 +1598,14 @@ pointObj** msPolylineLabelPointExtended(shapeObj *p, int min_length, int repeat_
       if (numlines > 0) {
         for (j=0; j<numlines; j++)
           if (regularLines[j] == i) {
-              msPolylineLabelPointLineString(p, min_length, repeat_distance, angles, lengths, segment_lengths, i, line_lengths[i], total_length, segment_index, &labelpoints_index, &labelpoints_size, &labelpoints, anglemode);
+            msPolylineLabelPointLineString(p, min_length, repeat_distance, angles, lengths, segment_lengths, i, line_lengths[i], total_length, segment_index, &labelpoints_index, &labelpoints_size, &labelpoints, anglemode);
             break;
           }
       } else {
-          msPolylineLabelPointLineString(p, min_length, repeat_distance, angles, lengths, segment_lengths, i, line_lengths[i], total_length, segment_index, &labelpoints_index, &labelpoints_size, &labelpoints, anglemode);
+        msPolylineLabelPointLineString(p, min_length, repeat_distance, angles, lengths, segment_lengths, i, line_lengths[i], total_length, segment_index, &labelpoints_index, &labelpoints_size, &labelpoints, anglemode);
       }
-  }
-  else
-      msPolylineLabelPointLineString(p, min_length, repeat_distance, angles, lengths, segment_lengths, max_line_index, max_line_length, total_length, segment_index, &labelpoints_index, &labelpoints_size, &labelpoints, anglemode);
+  } else
+    msPolylineLabelPointLineString(p, min_length, repeat_distance, angles, lengths, segment_lengths, max_line_index, max_line_length, total_length, segment_index, &labelpoints_index, &labelpoints_size, &labelpoints, anglemode);
 
   *numpoints = labelpoints_index;
 
@@ -1604,7 +1617,7 @@ pointObj** msPolylineLabelPointExtended(shapeObj *p, int min_length, int repeat_
   }
 
   free(line_lengths);
-  
+
   return labelpoints;
 }
 
@@ -1614,7 +1627,7 @@ void msPolylineLabelPointLineString(shapeObj *p, int min_length, int repeat_dist
   int i, j, k, l, n, index, point_repeat;
   double t, tmp_length, theta, fwd_length, point_distance;
   double center_point_position, left_point_position, right_point_position, point_position;
-  
+
   tmp_length = total_length;
   if (repeat_distance > 0)
     tmp_length = line_length;
@@ -1625,40 +1638,37 @@ void msPolylineLabelPointLineString(shapeObj *p, int min_length, int repeat_dist
   i = line_index;
 
   if(p->line[i].numpoints < 2)
-	  return;
+    return;
   point_distance = 0;
   point_repeat = 1;
-  left_point_position = right_point_position = center_point_position = line_length / 2.0; 
-  
+  left_point_position = right_point_position = center_point_position = line_length / 2.0;
+
   if (repeat_distance > 0) {
     point_repeat = line_length / repeat_distance;
-   
+
     if (point_repeat > 1) {
       if (point_repeat % 2 == 0)
         point_repeat -= 1;
-      point_distance = (line_length / point_repeat); // buffer allowed per point
+      point_distance = (line_length / point_repeat); /* buffer allowed per point */
 
-      // initial point position
+      /* initial point position */
       left_point_position -= ((point_repeat-1)/2 * point_distance);
       right_point_position += ((point_repeat-1)/2 * point_distance);
 
       point_repeat = (point_repeat-1)/2+1;
-    }
-    else
+    } else
       point_repeat = 1;
   }
 
-  for (l=0; l < point_repeat; ++l)
-  {
-    if (l == point_repeat-1) { // last point to place is always the center point 
+  for (l=0; l < point_repeat; ++l) {
+    if (l == point_repeat-1) { /* last point to place is always the center point */
       point_position = center_point_position;
       n = 1;
-    } 
-    else {
+    } else {
       point_position = right_point_position;
       n = 0;
     }
-    
+
     do {
       if (*labelpoints_index == *labelpoints_size) {
         *labelpoints_size *= 2;
@@ -1666,7 +1676,7 @@ void msPolylineLabelPointLineString(shapeObj *p, int min_length, int repeat_dist
         (*angles) = (double **) msSmallRealloc(*angles,sizeof(double *) * (*labelpoints_size));
         (*lengths) = (double **) msSmallRealloc(*lengths,sizeof(double *) * (*labelpoints_size));
       }
-      
+
       index = (*labelpoints_index)++;
       (*labelpoints)[index] = (pointObj *) msSmallMalloc(sizeof(pointObj));
       (*angles)[index] = (double *) msSmallMalloc(sizeof(double));
@@ -1678,9 +1688,8 @@ void msPolylineLabelPointLineString(shapeObj *p, int min_length, int repeat_dist
         *(*lengths)[index] = total_length;
 
       /* if there is only 1 label to place... put it in the middle of the current segment (as old behavior) */
-      if ( ((anglemode == MS_AUTO) || (anglemode == MS_AUTO2)) &&  
-           (point_repeat == 1) ) 
-      {
+      if ( ((anglemode == MS_AUTO) || (anglemode == MS_AUTO2)) &&
+           (point_repeat == 1) ) {
         j = segment_index;
         (*labelpoints)[index]->x = (p->line[i].point[j].x + p->line[i].point[j-1].x)/2.0;
         (*labelpoints)[index]->y = (p->line[i].point[j].y + p->line[i].point[j-1].y)/2.0;
@@ -1690,7 +1699,7 @@ void msPolylineLabelPointLineString(shapeObj *p, int min_length, int repeat_dist
         while (fwd_length < point_position) {
           fwd_length += segment_lengths[i][j++];
         }
-        
+
         k = j-1;
 
         t = 1 - (fwd_length - point_position) / segment_lengths[i][j-1];
@@ -1698,23 +1707,22 @@ void msPolylineLabelPointLineString(shapeObj *p, int min_length, int repeat_dist
         (*labelpoints)[index]->y = t * (p->line[i].point[k+1].y - p->line[i].point[k].y) + p->line[i].point[k].y;
       }
 
-      theta = asin(MS_ABS(p->line[i].point[j].x - p->line[i].point[j-1].x)/sqrt((((p->line[i].point[j].x - p->line[i].point[j-1].x)*(p->line[i].point[j].x - p->line[i].point[j-1].x)) + ((p->line[i].point[j].y - p->line[i].point[j-1].y)*(p->line[i].point[j].y - p->line[i].point[j-1].y)))));
-    
-      if(p->line[i].point[j-1].x < p->line[i].point[j].x || anglemode == MS_AUTO2) { /* i.e. to the left */
-        if(p->line[i].point[j-1].y < p->line[i].point[j].y) /* i.e. below */
-          *(*angles)[index] = -(90.0 - MS_RAD_TO_DEG*theta);
-        else
-          *(*angles)[index] = (90.0 - MS_RAD_TO_DEG*theta);      
-      } else {
-        if(p->line[i].point[j-1].y < p->line[i].point[j].y) /* i.e. below */
-          *(*angles)[index] = (90.0 - MS_RAD_TO_DEG*theta);
-        else
-          *(*angles)[index] = -(90.0 - MS_RAD_TO_DEG*theta);      
+      if(anglemode != MS_NONE) {
+        theta = atan2(p->line[i].point[j].x - p->line[i].point[j-1].x, p->line[i].point[j].y - p->line[i].point[j-1].y);
+        if(anglemode == MS_AUTO2) {
+          *(*angles)[index] = (MS_RAD_TO_DEG*theta) - 90;
+        } else { /* AUTO, FOLLOW */
+          if(p->line[i].point[j-1].x < p->line[i].point[j].x) { /* i.e. to the left */
+            *(*angles)[index] = (MS_RAD_TO_DEG*theta) - 90;
+          } else {
+            *(*angles)[index] = (MS_RAD_TO_DEG*theta) + 90;
+          }
+        }
       }
-      
+
       point_position = left_point_position;
       n++;
-    } while (n<2); // we place the right point then the left point.
+    } while (n<2); /* we place the right point then the left point. */
 
     right_point_position -= point_distance;
     left_point_position += point_distance;
@@ -1733,25 +1741,28 @@ labelPathObj** msPolylineLabelPath(mapObj *map, imageObj *img,shapeObj *p, int m
   labelPathObj** labelpaths;
 
   labelpaths_index = 0;
-  labelpaths_size = p->numlines; // minimal array size
+  labelpaths_size = p->numlines; /* minimal array size */
   regular_lines_index = 0;
   regular_lines_size = 1;
   *numpaths = 0;
   segment_index = max_line_index = 0;
   total_length = max_line_length = 0.0;
 
+  if(!string) return NULL;
+
+
   labelpaths = (labelPathObj **) msSmallMalloc(sizeof(labelPathObj *) * labelpaths_size);
   (*regular_lines) = (int *) msSmallMalloc(sizeof(int) * regular_lines_size);
 
   msPolylineComputeLineSegments(p, &segment_lengths, &line_lengths, &max_line_index, &max_line_length, &segment_index, &total_length);
- 
-  if (label->repeatdistance > 0)
+
+  if(label->repeatdistance > 0)
     for(i=0; i<p->numlines; i++) {
-      msPolylineLabelPathLineString(map,img, p,min_length, fontset, string, label, scalefactor, i, segment_lengths, line_lengths[i], total_length, 
+      msPolylineLabelPathLineString(map,img, p,min_length, fontset, string, label, scalefactor, i, segment_lengths, line_lengths[i], total_length,
                                     &labelpaths_index, &labelpaths_size, &labelpaths, regular_lines, &regular_lines_index, &regular_lines_size);
     }
   else
-    msPolylineLabelPathLineString(map, img, p,min_length, fontset, string, label, scalefactor, max_line_index, segment_lengths, line_lengths[max_line_index], total_length, 
+    msPolylineLabelPathLineString(map, img, p,min_length, fontset, string, label, scalefactor, max_line_index, segment_lengths, line_lengths[max_line_index], total_length,
                                   &labelpaths_index, &labelpaths_size, &labelpaths, regular_lines, &regular_lines_index, &regular_lines_size);
 
   /* freeing memory: allocated by msPolylineComputeLineSegments */
@@ -1771,20 +1782,20 @@ labelPathObj** msPolylineLabelPath(mapObj *map, imageObj *img,shapeObj *p, int m
 
 /*
  * Calculate a series of label points for each character in the label for a
- * given polyline. The resultant series of points is stored in *labelpath, 
- * which is added to the labelpaths array. Note that the points and bounds 
- * are allocated in this function.  The polyline must be converted to image 
+ * given polyline. The resultant series of points is stored in *labelpath,
+ * which is added to the labelpaths array. Note that the points and bounds
+ * are allocated in this function.  The polyline must be converted to image
  * coordinates before calling this function.
  */
-void msPolylineLabelPathLineString(mapObj *map, imageObj *img, shapeObj *p, int min_length, fontSetObj *fontset, char *string, labelObj *label, double scalefactor, int line_index, 
-                                   double** segment_lengths, double line_length, double total_length, int* labelpaths_index, int* labelpaths_size, labelPathObj*** labelpaths, 
+void msPolylineLabelPathLineString(mapObj *map, imageObj *img, shapeObj *p, int min_length, fontSetObj *fontset, char *string, labelObj *label, double scalefactor, int line_index,
+                                   double** segment_lengths, double line_length, double total_length, int* labelpaths_index, int* labelpaths_size, labelPathObj*** labelpaths,
                                    int** regular_lines, int *regular_lines_index, int* regular_lines_size)
 {
   double distance_along_segment;
   double segment_length, fwd_line_length, rev_line_length, text_length, text_start_length, label_buffer, text_end_length;
   double right_label_position, left_label_position, center_label_position;
   int numchars;
-  
+
   int i,j,k,l,n, inc, final_j, label_repeat;
   double direction;
   rectObj bbox;
@@ -1792,7 +1803,7 @@ void msPolylineLabelPathLineString(mapObj *map, imageObj *img, shapeObj *p, int
   double *offsets;
   double size, t, tmp_length;
   double cx, cy; /* centre of a character, x & y values. */
-  
+
   double theta;
   double dx, dy, w, cos_t, sin_t;
 
@@ -1802,30 +1813,26 @@ void msPolylineLabelPathLineString(mapObj *map, imageObj *img, shapeObj *p, int
   double kernel[] = {0.1, 0.2, 2, 0.2, 0.1}; /* {1.5, 2, 15, 2, 1.5}; */
   double kernel_normal = 2.6; /* Must be sum of kernel elements */
   int kernel_size = 5;
-  
-  double letterspacing = 1.25;
-  /* As per RFC 60, if label->maxoverlapangle == 0 then fall back on pre-6.0 behavior 
+
+  double letterspacing = 1.05;
+  /* As per RFC 60, if label->maxoverlapangle == 0 then fall back on pre-6.0 behavior
      which was to use maxoverlapangle = 0.4*MS_PI ( 40% of 180 degrees ) */
   double maxoverlapangle = 0.4 * MS_PI;
 
   offsets = NULL;
 
-#ifndef GD_HAS_FTEX_XSHOW
-  goto ANGLEFOLLOW_FAILURE; /* we don't have a current enough version of GD, fall back to ANGLE AUTO */
-#else
-
   tmp_length = total_length;
   if (label->repeatdistance > 0)
     tmp_length = line_length;
 
   numchars = msGetNumGlyphs(string);
-  
+
   /* skip the label and use the normal algorithm if it has fewer than 2 characters */
   if(numchars < 2)
     goto ANGLEFOLLOW_FAILURE;
 
   i = line_index;
-  
+
   if (((min_length != -1) && (tmp_length < min_length))) { /* too short */
     goto FAILURE;
   }
@@ -1836,377 +1843,376 @@ void msPolylineLabelPathLineString(mapObj *map, imageObj *img, shapeObj *p, int
 
   if(p->line[i].numpoints == 2) /* use the regular angled text algorithm */
     goto ANGLEFOLLOW_FAILURE;
-  
+
   size = label->size*scalefactor;
   size = MS_MAX(size, label->minsize*img->resolutionfactor);
   size = MS_MIN(size, label->maxsize*img->resolutionfactor);
-  
+
   /* determine the total length of the text */
   if (msGetLabelSize(map,label,string,size,&bbox,&offsets) != MS_SUCCESS) {
     goto FAILURE;
   }
 
-  
+
   scalefactor = size / label->size;
 
   text_length = letterspacing * (bbox.maxx - bbox.minx);
 
-  /* 
+  /*
   ** if the text length is way longer than the line, skip adding the
-  ** label if it isn't forced (long extrapolated labels tend to be ugly) 
+  ** label if it isn't forced (long extrapolated labels tend to be ugly)
   */
   if ( text_length > 1.5 * line_length && label->force == MS_FALSE ) {
     goto FAILURE;
   }
 
-  // We compute the number of labels we can repeat in the line
+  /* We compute the number of labels we can repeat in the line */
   text_end_length = 0;
   left_label_position = right_label_position = center_label_position = (line_length - text_length) / 2.0;
   label_repeat = (line_length / (text_length + label->repeatdistance));
-  label_buffer = (line_length / label_repeat); // buffer allowed per label 
+  label_buffer = (line_length / label_repeat); /* buffer allowed per label */
   if (label->repeatdistance > 0 && label_repeat > 1) {
     if (label_repeat % 2 == 0) {
-        label_repeat -= 1;
-        label_buffer = (line_length / label_repeat);  
+      label_repeat -= 1;
+      label_buffer = (line_length / label_repeat);
     }
-//    text_start_length = (label_buffer / 2) - (text_length / 2);
+    /* text_start_length = (label_buffer / 2) - (text_length / 2); */
 
-    // initial point position
+    /* initial point position */
     left_label_position -= ((label_repeat-1)/2 * label_buffer);
     right_label_position += ((label_repeat-1)/2 * label_buffer);
-    
+
     label_repeat = (label_repeat-1)/2+1;
-  }
-  else
-  {
+  } else {
     label_repeat = 1;
     center_label_position = (line_length - text_length) / 2.0;
   }
-  
+
   if(label->maxoverlapangle >=0)
-    maxoverlapangle = label->maxoverlapangle * MS_DEG_TO_RAD; // radian
+    maxoverlapangle = label->maxoverlapangle * MS_DEG_TO_RAD; /* radian */
 
-  for (l=0; l < label_repeat; l++)
-  {
-    if (l == label_repeat-1) { // last label to place is always the center label
+  for (l=0; l < label_repeat; l++) {
+    if (l == label_repeat-1) { /* last label to place is always the center label */
       text_start_length = center_label_position;
       n = 1;
-    } 
-    else {
+    } else {
       text_start_length = right_label_position;
       n = 0;
     }
 
     do {
-        /* allocate the labelpath */
-        labelpath = (labelPathObj *) msSmallMalloc(sizeof(labelPathObj));
-        labelpath->path.numpoints = numchars;
-        labelpath->path.point = (pointObj *) msSmallCalloc(labelpath->path.numpoints, sizeof(pointObj));
-        labelpath->angles = (double *) msSmallMalloc(sizeof(double) * (labelpath->path.numpoints));
-        msInitShape(&(labelpath->bounds));
-    
-
-        /*     
-        ** The bounds will have two points for each character plus an endpoint:
-        ** the UL corners of each bbox will be tied together and the LL corners
-        ** will be tied together.
-        */
-        bounds.numpoints = 2*numchars + 1;
-        bounds.point = (pointObj *) msSmallMalloc(sizeof(pointObj) * bounds.numpoints);
+      /* allocate the labelpath */
+      labelpath = (labelPathObj *) msSmallMalloc(sizeof(labelPathObj));
+      labelpath->path.numpoints = numchars;
+      labelpath->path.point = (pointObj *) msSmallCalloc(labelpath->path.numpoints, sizeof(pointObj));
+      labelpath->angles = (double *) msSmallMalloc(sizeof(double) * (labelpath->path.numpoints));
+      msInitShape(&(labelpath->bounds));
+
+
+      /*
+      ** The bounds will have two points for each character plus an endpoint:
+      ** the UL corners of each bbox will be tied together and the LL corners
+      ** will be tied together.
+      */
+      bounds.numpoints = 2*numchars + 1;
+      bounds.point = (pointObj *) msSmallMalloc(sizeof(pointObj) * bounds.numpoints);
+
+      /* the points start at (line_length - text_length) / 2 in order to be centred */
+      /* text_start_length = (line_length - text_length) / 2.0; */
+
+      /* the text is longer than the line: extrapolate the first and last segments */
+      if(text_start_length < 0.0) {
+        j = 0;
+        final_j = p->line[i].numpoints - 1;
+        fwd_line_length = rev_line_length = 0;
+      } else {
+        /* proceed until we've traversed text_start_length in distance */
+        fwd_line_length = 0;
+        j = 0;
+        while ( fwd_line_length < text_start_length )
+          fwd_line_length += segment_lengths[i][j++];
+
+        j--;
+
+        /* determine the last segment */
+        rev_line_length = 0;
+        final_j = p->line[i].numpoints - 1;
+
+        text_end_length = line_length - (text_start_length + text_length);
+        while(rev_line_length < text_end_length) {
+          rev_line_length += segment_lengths[i][final_j - 1];
+          final_j--;
+        }
+        final_j++;
+      }
 
-        /* the points start at (line_length - text_length) / 2 in order to be centred */
-        //  text_start_length = (line_length - text_length) / 2.0;
+      if(final_j == 0)
+        final_j = 1;
 
-        /* the text is longer than the line: extrapolate the first and last segments */
-        if(text_start_length < 0.0) {    
-            j = 0;
-            final_j = p->line[i].numpoints - 1;
-            fwd_line_length = rev_line_length = 0;
-        } else {
-            /* proceed until we've traversed text_start_length in distance */
-            fwd_line_length = 0;
-            j = 0;
-            while ( fwd_line_length < text_start_length )
-                fwd_line_length += segment_lengths[i][j++];
-
-            j--;
-
-            /* determine the last segment */ 
-            rev_line_length = 0;
-            final_j = p->line[i].numpoints - 1;
-
-            text_end_length = line_length - (text_start_length + text_length);
-            while(rev_line_length < text_end_length) {
-                rev_line_length += segment_lengths[i][final_j - 1];
-                final_j--;
-            }
-            final_j++;
+      /* determine if the line is mostly left to right or right to left,
+         see bug 1620 discussion by Steve Woodbridge */
+      direction = 0;
+      k = j;
+      while (k < final_j) {
+        direction += p->line[i].point[k+1].x - p->line[i].point[k].x;
+        k++;
+      }
+
+      if(direction > 0) {
+        inc = 1; /* j is already correct */
+
+        /* length of the segment containing the starting point */
+        segment_length = segment_lengths[i][j];
+
+        /* determine how far along the segment we need to go */
+        if(text_start_length < 0.0)
+          t = text_start_length / segment_length;
+        else
+          t = 1 - (fwd_line_length - text_start_length) / segment_length;
+      } else {
+        j = final_j;
+        inc = -1;
+
+        /* length of the segment containing the starting point */
+        segment_length = segment_lengths[i][j-1];
+        if(text_start_length < 0.0)
+          t = text_start_length / segment_length;
+        else
+          t = 1 - (rev_line_length - text_end_length) / segment_length;
+      }
+
+      distance_along_segment = t * segment_length; /* starting point */
+
+      theta = 0;
+      k = 0;
+      w = 0;
+      while ( k < labelpath->path.numpoints ) {
+        int m;
+        double x,y;
+
+        x = t * (p->line[i].point[j+inc].x - p->line[i].point[j].x) + p->line[i].point[j].x;
+        y = t * (p->line[i].point[j+inc].y - p->line[i].point[j].y) + p->line[i].point[j].y;
+
+        /*
+        ** This used to be a series of if-then-else's, but that fails for short (length < 4)
+        ** labels. There may be small speed-ups possible here. (bug 1921)
+        **
+        ** average this label point with its neighbors according to the smoothing kernel
+        */
+        if ( k == 0) {
+          labelpath->path.point[k].x += (kernel[0] + kernel[1]) * x;
+          labelpath->path.point[k].y += (kernel[0] + kernel[1]) * y;
+        }
+        if ( k == 1) {
+          labelpath->path.point[k].x += kernel[0] * x;
+          labelpath->path.point[k].y += kernel[0] * y;
+        }
+        if ( k == labelpath->path.numpoints - 2) {
+          labelpath->path.point[k].x += kernel[4] * x;
+          labelpath->path.point[k].y += kernel[4] * y;
+        }
+        if ( k == labelpath->path.numpoints - 1) {
+          labelpath->path.point[k].x += (kernel[3] + kernel[4]) * x;
+          labelpath->path.point[k].y += (kernel[3] + kernel[4]) * y;
         }
 
-        if(final_j == 0)
-            final_j = 1;
-  
-        /* determine if the line is mostly left to right or right to left, 
-           see bug 1620 discussion by Steve Woodbridge */
-        direction = 0;
-        k = j;
-        while (k < final_j) {
-            direction += p->line[i].point[k+1].x - p->line[i].point[k].x;
-            k++;
+        for(m = 0; m < kernel_size; m++) {
+          if(m + k - 2 < 0 || m + k - 2 > labelpath->path.numpoints - 1)
+            continue;
+          labelpath->path.point[k+m-2].x += kernel[m]*x;
+          labelpath->path.point[k+m-2].y += kernel[m]*y;
         }
 
-        if(direction > 0) {    
-            inc = 1; /* j is already correct */
+        w = letterspacing*offsets[k];
 
-            /* length of the segment containing the starting point */
-            segment_length = segment_lengths[i][j];
+        /* add the character's width to the distance along the line */
+        distance_along_segment += w;
 
-            /* determine how far along the segment we need to go */
-            if(text_start_length < 0.0)
-              t = text_start_length / segment_length;
-            else
-              t = 1 - (fwd_line_length - text_start_length) / segment_length;
-        } else {
-            j = final_j;
-            inc = -1;
-      
-            /* length of the segment containing the starting point */
-            segment_length = segment_lengths[i][j-1];
-            if(text_start_length < 0.0)
-              t = text_start_length / segment_length;
-            else
-              t = 1 - (rev_line_length - text_end_length) / segment_length;    
-        }
-    
-        distance_along_segment = t * segment_length; /* starting point */
-  
-        theta = 0;
-        k = 0;
-        w = 0;
-        while ( k < labelpath->path.numpoints ) {
-            int m;
-            double x,y;
-      
-            x = t * (p->line[i].point[j+inc].x - p->line[i].point[j].x) + p->line[i].point[j].x;
-            y = t * (p->line[i].point[j+inc].y - p->line[i].point[j].y) + p->line[i].point[j].y;
-
-            /* 
-            ** This used to be a series of if-then-else's, but that fails for short (length < 4)
-            ** labels. There may be small speed-ups possible here. (bug 1921)
-            **
-            ** average this label point with its neighbors according to the smoothing kernel
-            */
-            if ( k == 0) {
-                labelpath->path.point[k].x += (kernel[0] + kernel[1]) * x;
-                labelpath->path.point[k].y += (kernel[0] + kernel[1]) * y;
-            } 
-            if ( k == 1) {
-                labelpath->path.point[k].x += kernel[0] * x;
-                labelpath->path.point[k].y += kernel[0] * y;
-            } 
-            if ( k == labelpath->path.numpoints - 2) {
-                labelpath->path.point[k].x += kernel[4] * x;
-                labelpath->path.point[k].y += kernel[4] * y;      
-            } 
-            if ( k == labelpath->path.numpoints - 1) {
-                labelpath->path.point[k].x += (kernel[3] + kernel[4]) * x;
-                labelpath->path.point[k].y += (kernel[3] + kernel[4]) * y;
-            }
-      
-            for(m = 0; m < kernel_size; m++) {
-                if(m + k - 2 < 0 || m + k - 2 > labelpath->path.numpoints - 1)
-                    continue;
-                labelpath->path.point[k+m-2].x += kernel[m]*x;
-                labelpath->path.point[k+m-2].y += kernel[m]*y;
-            }
-    
-            w = letterspacing*offsets[k];
-    
-            /* add the character's width to the distance along the line */
-            distance_along_segment += w;
-
-            /* if we still have segments left and we've past the current segment, move to the next one */    
-            if(inc == 1 && j < p->line[i].numpoints - 2) {      
-
-                while ( j < p->line[i].numpoints - 2 && distance_along_segment > segment_lengths[i][j] ) {
-                    distance_along_segment -= segment_lengths[i][j];                
-                    j += inc; /* move to next segment */
-                }
+        /* if we still have segments left and we've past the current segment, move to the next one */
+        if(inc == 1 && j < p->line[i].numpoints - 2) {
 
-                segment_length = segment_lengths[i][j];
-            
-            } else if( inc == -1 && j > 1 ) {
+          while ( j < p->line[i].numpoints - 2 && distance_along_segment > segment_lengths[i][j] ) {
+            distance_along_segment -= segment_lengths[i][j];
+            j += inc; /* move to next segment */
+          }
 
-                while ( j > 1 && distance_along_segment > segment_lengths[i][j-1] ) {
-                    distance_along_segment -= segment_lengths[i][j-1];
-                    j += inc; /* move to next segment */
-                }
-      
-                segment_length = segment_lengths[i][j-1];
-            }
-    
-            /* Recalculate interpolation parameter */
-            t = distance_along_segment / segment_length;
-    
-            k++;
-        }
-  
-        /* pre-calc the character's centre y value.  Used for rotation adjustment. */
-        cy = -size / 2.0;
+          segment_length = segment_lengths[i][j];
+
+        } else if( inc == -1 && j > 1 ) {
 
-        labelpath->path.point[0].x /= kernel_normal;
-        labelpath->path.point[0].y /= kernel_normal;
+          while ( j > 1 && distance_along_segment > segment_lengths[i][j-1] ) {
+            distance_along_segment -= segment_lengths[i][j-1];
+            j += inc; /* move to next segment */
+          }
 
-        /* Average the points and calculate each angle */
-        for (k = 1; k <= labelpath->path.numpoints; k++) {
+          segment_length = segment_lengths[i][j-1];
+        }
 
-            if ( k < labelpath->path.numpoints ) {  
-                labelpath->path.point[k].x /= kernel_normal;
-                labelpath->path.point[k].y /= kernel_normal;
-                dx = labelpath->path.point[k].x - labelpath->path.point[k-1].x;
-                dy = labelpath->path.point[k].y - labelpath->path.point[k-1].y;
-            } else {
-                /* Handle the last character */
-                dx = t * (p->line[i].point[j+inc].x - p->line[i].point[j].x) + p->line[i].point[j].x - labelpath->path.point[k-1].x;
-                dy = t * (p->line[i].point[j+inc].y - p->line[i].point[j].y) + p->line[i].point[j].y - labelpath->path.point[k-1].y;
-            }
+        /* Recalculate interpolation parameter */
+        t = distance_along_segment / segment_length;
 
-            theta = -atan2(dy,dx);
+        k++;
+      }
 
-            /* If the difference between the last char angle and the current one 
-              is greater than the MAXOVERLAPANGLE value (set at 80% of 180deg by default)
-              , bail the label */
-            if ( maxoverlapangle > 0 && (k > 2 && fabs(theta - labelpath->angles[k-2]) > maxoverlapangle) ) {
-                goto LABEL_FAILURE;
-            }
-      
-            /* msDebug("s: %c (x,y): (%0.2f,%0.2f) t: %0.2f\n", string[k-1], labelpath->path.point[k-1].x, labelpath->path.point[k-1].y, theta); */
-            
-            labelpath->angles[k-1] = theta;
-
-  
-            /* Move the previous point so that when the character is rotated and
-               placed it is centred on the line */
-            cos_t = cos(theta);
-            sin_t = sin(theta);
-
-            w = letterspacing*offsets[k-1];
-
-            cx = 0; /* Center the character vertically only */
-
-            dx = - (cx * cos_t + cy * sin_t);
-            dy = - (cy * cos_t - cx * sin_t);
-  
-            labelpath->path.point[k-1].x += dx;
-            labelpath->path.point[k-1].y += dy;
-
-            /* Calculate the bounds */
-            bbox.minx = 0;
-            bbox.maxx = w;
-            bbox.maxy = 0;
-            bbox.miny = -size;
-  
-            /* Add the label buffer to the bounds */
-            bbox.maxx += label->buffer;
-            bbox.maxy += label->buffer;
-            bbox.minx -= label->buffer;
-            bbox.miny -= label->buffer;
-
-            if ( k < labelpath->path.numpoints ) {
-                /* Transform the bbox too.  We take the UL and LL corners and rotate
-                   then translate them. */
-                bounds.point[k-1].x = (bbox.minx * cos_t + bbox.maxy * sin_t) + labelpath->path.point[k-1].x;
-                bounds.point[k-1].y = (bbox.maxy * cos_t - bbox.minx * sin_t) + labelpath->path.point[k-1].y;
-
-                /* Start at end and work towards the half way point */
-                bounds.point[bounds.numpoints - k - 1].x = (bbox.minx * cos_t + bbox.miny * sin_t) + labelpath->path.point[k-1].x;
-                bounds.point[bounds.numpoints - k - 1].y = (bbox.miny * cos_t - bbox.minx * sin_t) + labelpath->path.point[k-1].y;
+      /* pre-calc the character's centre y value.  Used for rotation adjustment. */
+      cy = -size / 2.0;
 
-            } else {
-    
-                /* This is the last character in the string so we take the UR and LR
-                   corners of the bbox */
-                bounds.point[k-1].x = (bbox.maxx * cos_t + bbox.maxy * sin_t) + labelpath->path.point[k-1].x;
-                bounds.point[k-1].y = (bbox.maxy * cos_t - bbox.maxx * sin_t) + labelpath->path.point[k-1].y;
-  
-                bounds.point[bounds.numpoints - k - 1].x = (bbox.maxx * cos_t + bbox.miny * sin_t) + labelpath->path.point[k-1].x;
-                bounds.point[bounds.numpoints - k - 1].y = (bbox.miny * cos_t - bbox.maxx * sin_t) + labelpath->path.point[k-1].y;
-            }
+      labelpath->path.point[0].x /= kernel_normal;
+      labelpath->path.point[0].y /= kernel_normal;
 
+      /* Average the points and calculate each angle */
+      for (k = 1; k <= labelpath->path.numpoints; k++) {
+        double anglediff;
+        if ( k < labelpath->path.numpoints ) {
+          labelpath->path.point[k].x /= kernel_normal;
+          labelpath->path.point[k].y /= kernel_normal;
+          dx = labelpath->path.point[k].x - labelpath->path.point[k-1].x;
+          dy = labelpath->path.point[k].y - labelpath->path.point[k-1].y;
+        } else {
+          /* Handle the last character */
+          dx = t * (p->line[i].point[j+inc].x - p->line[i].point[j].x) + p->line[i].point[j].x - labelpath->path.point[k-1].x;
+          dy = t * (p->line[i].point[j+inc].y - p->line[i].point[j].y) + p->line[i].point[j].y - labelpath->path.point[k-1].y;
         }
 
-        /* Close the bounds */
-        bounds.point[bounds.numpoints - 1].x = bounds.point[0].x;
-        bounds.point[bounds.numpoints - 1].y = bounds.point[0].y;
-  
-        /* Convert the bounds to a shape and store them in the labelpath */
-        if ( msAddLineDirectly(&(labelpath->bounds), &bounds) == MS_FAILURE ) {
+        theta = -atan2(dy,dx);
+
+        if ( maxoverlapangle > 0 && k > 1) {
+          /* If the difference between the last char angle and the current one
+             is greater than the MAXOVERLAPANGLE value (set at 80% of 180deg by default)
+             , bail the label */
+          anglediff = fabs(theta - labelpath->angles[k-2]);
+          anglediff = MS_MIN(anglediff, MS_2PI - anglediff);
+          if(anglediff > maxoverlapangle ) {
             goto LABEL_FAILURE;
+          }
         }
 
-        msComputeBounds(&(labelpath->bounds));
-      
-        goto LABEL_END;
-    
-    LABEL_FAILURE:
+        /* msDebug("s: %c (x,y): (%0.2f,%0.2f) t: %0.2f\n", string[k-1], labelpath->path.point[k-1].x, labelpath->path.point[k-1].y, theta); */
+
+        labelpath->angles[k-1] = theta;
+
+
+        /* Move the previous point so that when the character is rotated and
+           placed it is centred on the line */
+        cos_t = cos(theta);
+        sin_t = sin(theta);
+
+        w = letterspacing*offsets[k-1];
+
+        cx = 0; /* Center the character vertically only */
 
-        if (bounds.point)
-            free(bounds.point);
-        bounds.point = NULL;
-        bounds.numpoints = 0;
+        dx = - (cx * cos_t + cy * sin_t);
+        dy = - (cy * cos_t - cx * sin_t);
 
-        if ( labelpath ) {
-            msFreeLabelPathObj(labelpath);
-            labelpath = NULL;
+        labelpath->path.point[k-1].x += dx;
+        labelpath->path.point[k-1].y += dy;
+
+        /* Calculate the bounds */
+        bbox.minx = 0;
+        bbox.maxx = w;
+        bbox.maxy = 0;
+        bbox.miny = -size;
+
+        /* Add the label buffer to the bounds */
+        bbox.maxx += label->buffer;
+        bbox.maxy += label->buffer;
+        bbox.minx -= label->buffer;
+        bbox.miny -= label->buffer;
+
+        if ( k < labelpath->path.numpoints ) {
+          /* Transform the bbox too.  We take the UL and LL corners and rotate
+             then translate them. */
+          bounds.point[k-1].x = (bbox.minx * cos_t + bbox.maxy * sin_t) + labelpath->path.point[k-1].x;
+          bounds.point[k-1].y = (bbox.maxy * cos_t - bbox.minx * sin_t) + labelpath->path.point[k-1].y;
+
+          /* Start at end and work towards the half way point */
+          bounds.point[bounds.numpoints - k - 1].x = (bbox.minx * cos_t + bbox.miny * sin_t) + labelpath->path.point[k-1].x;
+          bounds.point[bounds.numpoints - k - 1].y = (bbox.miny * cos_t - bbox.minx * sin_t) + labelpath->path.point[k-1].y;
+
+        } else {
+
+          /* This is the last character in the string so we take the UR and LR
+             corners of the bbox */
+          bounds.point[k-1].x = (bbox.maxx * cos_t + bbox.maxy * sin_t) + labelpath->path.point[k-1].x;
+          bounds.point[k-1].y = (bbox.maxy * cos_t - bbox.maxx * sin_t) + labelpath->path.point[k-1].y;
+
+          bounds.point[bounds.numpoints - k - 1].x = (bbox.maxx * cos_t + bbox.miny * sin_t) + labelpath->path.point[k-1].x;
+          bounds.point[bounds.numpoints - k - 1].y = (bbox.miny * cos_t - bbox.maxx * sin_t) + labelpath->path.point[k-1].y;
         }
-    
-    LABEL_END:
-        if (labelpath) {
-            if (*labelpaths_index == *labelpaths_size) {
-                *labelpaths_size *= 2;
-                (*labelpaths) = (labelPathObj **) msSmallRealloc(*labelpaths,sizeof(labelPathObj *) * (*labelpaths_size));
-            }
-            (*labelpaths)[(*labelpaths_index)++] = labelpath;
+
+      }
+
+      /* Close the bounds */
+      bounds.point[bounds.numpoints - 1].x = bounds.point[0].x;
+      bounds.point[bounds.numpoints - 1].y = bounds.point[0].y;
+
+      /* Convert the bounds to a shape and store them in the labelpath */
+      if ( msAddLineDirectly(&(labelpath->bounds), &bounds) == MS_FAILURE ) {
+        goto LABEL_FAILURE;
+      }
+
+      msComputeBounds(&(labelpath->bounds));
+
+      goto LABEL_END;
+
+LABEL_FAILURE:
+
+      if (bounds.point)
+        free(bounds.point);
+      bounds.point = NULL;
+      bounds.numpoints = 0;
+
+      if ( labelpath ) {
+        msFreeLabelPathObj(labelpath);
+        labelpath = NULL;
+      }
+
+LABEL_END:
+      if (labelpath) {
+        if (*labelpaths_index == *labelpaths_size) {
+          *labelpaths_size *= 2;
+          (*labelpaths) = (labelPathObj **) msSmallRealloc(*labelpaths,sizeof(labelPathObj *) * (*labelpaths_size));
         }
-    
-        text_start_length = left_label_position;
-        n++;
+        (*labelpaths)[(*labelpaths_index)++] = labelpath;
+      }
+
+      text_start_length = left_label_position;
+      n++;
     } while (n<2);
-    
+
     right_label_position -= label_buffer;
     left_label_position += label_buffer;
 
   }
 
-  goto END; // normal exit
-#endif
+  goto END; /* normal exit */
 
-  ANGLEFOLLOW_FAILURE: // Angle follow failure: add the line index in the arrays
+ANGLEFOLLOW_FAILURE: /* Angle follow failure: add the line index in the arrays */
   if (*regular_lines_index == *regular_lines_size) {
-      *regular_lines_size *= 2;
-      (*regular_lines) = (int*) msSmallRealloc(*regular_lines,sizeof(int) * (*regular_lines_size));
+    *regular_lines_size *= 2;
+    (*regular_lines) = (int*) msSmallRealloc(*regular_lines,sizeof(int) * (*regular_lines_size));
   }
   (*regular_lines)[(*regular_lines_index)++] = line_index;
 
-  FAILURE: // Global failure   
+FAILURE: /* Global failure */
 
-  END:
-    if ( offsets )
-      free(offsets);
+END:
+  if ( offsets )
+    free(offsets);
 
-    return;
+  return;
 }
 
 /* ===========================================================================
    Pretty printing of primitive objects
    ======================================================================== */
 
-void msRectToFormattedString(rectObj *rect, char *format, char *buffer, int buffer_length) 
+void msRectToFormattedString(rectObj *rect, char *format, char *buffer, int buffer_length)
 {
   snprintf(buffer, buffer_length, format, rect->minx, rect->miny, rect->maxx, rect->maxy);
 }
 
-void msPointToFormattedString(pointObj *point, const char *format, char *buffer, int buffer_length) 
+void msPointToFormattedString(pointObj *point, const char *format, char *buffer, int buffer_length)
 {
 #ifdef USE_POINT_Z_M
   snprintf(buffer, buffer_length, format, point->x, point->y, point->z, point->m);
@@ -2221,12 +2227,12 @@ int msIsDegenerateShape(shapeObj *shape)
   int i;
   int non_degenerate_parts = 0;
   for(i=0; i<shape->numlines; i++) { /* e.g. part */
-	
-    /* skip degenerate parts, really should only happen with pixel output */ 
+
+    /* skip degenerate parts, really should only happen with pixel output */
     if((shape->type == MS_SHAPE_LINE && shape->line[i].numpoints < 2) ||
-       (shape->type == MS_SHAPE_POLYGON && shape->line[i].numpoints < 3))
-     continue;
-	
+        (shape->type == MS_SHAPE_POLYGON && shape->line[i].numpoints < 3))
+      continue;
+
     non_degenerate_parts++;
   }
   return( non_degenerate_parts == 0 );
diff --git a/mapprimitive.h b/mapprimitive.h
index caa3e2c..15939ee 100644
--- a/mapprimitive.h
+++ b/mapprimitive.h
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -46,27 +46,27 @@ typedef struct {
   double x;
   double y;
 #ifdef USE_POINT_Z_M
-  double z;  
-  double m;  
+  double z;
+  double m;
 #endif
 } pointObj;
 
 typedef struct {
 #ifdef SWIG
-%immutable;
+  %immutable;
 #endif
   int numpoints;
 #ifndef SWIG
   pointObj *point;
 #endif
 #ifdef SWIG
-%mutable;
+  %mutable;
 #endif
 } lineObj;
 
 typedef struct {
 #ifdef SWIG
-%immutable;
+  %immutable;
 #endif
   int numlines;
   int numvalues;
@@ -78,7 +78,7 @@ typedef struct {
 #endif
 
 #ifdef SWIG
-%mutable;
+  %mutable;
 #endif
 
   rectObj bounds;
@@ -87,7 +87,7 @@ typedef struct {
   int tileindex;
   int classindex;
   char *text;
-  
+
   int scratch;
   int resultindex; /* index within a query result set */
 } shapeObj;
@@ -108,7 +108,7 @@ typedef struct {
 #ifndef SWIG
 typedef struct {
   int  need_geotransform;
-  double rotation_angle;  
+  double rotation_angle;
   double geotransform[6];    /* Pixel/line to georef. */
   double invgeotransform[6]; /* georef to pixel/line */
 } geotransformObj;
diff --git a/mapproject.c b/mapproject.c
index 83f0fcb..8d2a5f7 100644
--- a/mapproject.c
+++ b/mapproject.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -33,15 +33,34 @@
 #include <assert.h>
 #include <sys/types.h>
 #include <sys/stat.h>
+#include "mapaxisorder.h"
+
 
-MS_CVSID("$Id$")
 
 #ifdef USE_PROJ
 static int msTestNeedWrap( pointObj pt1, pointObj pt2, pointObj pt2_geo,
-                           projectionObj *src_proj, 
+                           projectionObj *src_proj,
                            projectionObj *dst_proj );
 #endif
 
+
+/************************************************************************/
+/*                           int msIsAxisInverted                       */
+/*      Check to see if we shoud invert the axis.                       */
+/*                                                                      */
+/************************************************************************/
+int msIsAxisInverted(int epsg_code)
+{
+  const unsigned int row = epsg_code / 8;
+  const unsigned char index = epsg_code % 8;
+
+  /*check the static table*/
+  if ((row < sizeof(axisOrientationEpsgCodes)) && (axisOrientationEpsgCodes[row] & (1 << index)))
+    return MS_TRUE;
+  else
+    return MS_FALSE;
+}
+
 /************************************************************************/
 /*                           msProjectPoint()                           */
 /************************************************************************/
@@ -49,114 +68,113 @@ int msProjectPoint(projectionObj *in, projectionObj *out, pointObj *point)
 {
 #ifdef USE_PROJ
   projUV p;
-  int	 error;
+  int  error;
 
-  if( in && in->gt.need_geotransform )
-  {
-      double x_out, y_out;
+  if( in && in->gt.need_geotransform ) {
+    double x_out, y_out;
 
-      x_out = in->gt.geotransform[0]
-          + in->gt.geotransform[1] * point->x 
-          + in->gt.geotransform[2] * point->y;
-      y_out = in->gt.geotransform[3]
-          + in->gt.geotransform[4] * point->x 
-          + in->gt.geotransform[5] * point->y;
+    x_out = in->gt.geotransform[0]
+            + in->gt.geotransform[1] * point->x
+            + in->gt.geotransform[2] * point->y;
+    y_out = in->gt.geotransform[3]
+            + in->gt.geotransform[4] * point->x
+            + in->gt.geotransform[5] * point->y;
 
-      point->x = x_out;
-      point->y = y_out;
+    point->x = x_out;
+    point->y = y_out;
   }
 
-/* -------------------------------------------------------------------- */
-/*      If the source and destination are simple and equal, then do     */
-/*      nothing.                                                        */
-/* -------------------------------------------------------------------- */
+  /* -------------------------------------------------------------------- */
+  /*      If the source and destination are simple and equal, then do     */
+  /*      nothing.                                                        */
+  /* -------------------------------------------------------------------- */
   if( in && in->numargs == 1 && out && out->numargs == 1
-      && strcmp(in->args[0],out->args[0]) == 0 )
-  {
-      /* do nothing, no transformation required */
+      && strcmp(in->args[0],out->args[0]) == 0 ) {
+    /* do nothing, no transformation required */
   }
 
-/* -------------------------------------------------------------------- */
-/*      If we have a fully defined input coordinate system and          */
-/*      output coordinate system, then we will use pj_transform.        */
-/* -------------------------------------------------------------------- */
-  else if( in && in->proj && out && out->proj )
-  {
-      double	z = 0.0;
-
-      if( pj_is_latlong(in->proj) )
-      {
-          point->x *= DEG_TO_RAD;
-          point->y *= DEG_TO_RAD;
-      }
+  /* -------------------------------------------------------------------- */
+  /*      If we have a fully defined input coordinate system and          */
+  /*      output coordinate system, then we will use pj_transform.        */
+  /* -------------------------------------------------------------------- */
+  else if( in && in->proj && out && out->proj ) {
+    double  z = 0.0;
+
+    if( pj_is_latlong(in->proj) ) {
+      point->x *= DEG_TO_RAD;
+      point->y *= DEG_TO_RAD;
+    }
 
-      msAcquireLock( TLOCK_PROJ );
-      error = pj_transform( in->proj, out->proj, 1, 0, 
-                            &(point->x), &(point->y), &z );
-      msReleaseLock( TLOCK_PROJ );
+#if PJ_VERSION < 480
+    msAcquireLock( TLOCK_PROJ );
+#endif
+    error = pj_transform( in->proj, out->proj, 1, 0,
+                          &(point->x), &(point->y), &z );
+#if PJ_VERSION < 480
+    msReleaseLock( TLOCK_PROJ );
+#endif
 
-      if( error || point->x == HUGE_VAL || point->y == HUGE_VAL )
-          return MS_FAILURE;
+    if( error || point->x == HUGE_VAL || point->y == HUGE_VAL ) {
+      msSetError(MS_PROJERR,"proj says: %s","msProjectPoint()",pj_strerrno(error));
+      return MS_FAILURE;
+    }
 
-      if( pj_is_latlong(out->proj) )
-      {
-          point->x *= RAD_TO_DEG;
-          point->y *= RAD_TO_DEG;
-      }
+    if( pj_is_latlong(out->proj) ) {
+      point->x *= RAD_TO_DEG;
+      point->y *= RAD_TO_DEG;
+    }
   }
 
-/* -------------------------------------------------------------------- */
-/*      Otherwise we fallback to using pj_fwd() or pj_inv() and         */
-/*      assuming that the NULL projectionObj is supposed to be          */
-/*      lat/long in the same datum as the other projectionObj.  This    */
-/*      is essentially a backwards compatibility mode.                  */
-/* -------------------------------------------------------------------- */
-  else
-  {
-      /* nothing to do if the other coordinate system is also lat/long */
-      if( in == NULL && out != NULL && pj_is_latlong(out->proj) )
-          return MS_SUCCESS;
-      if( out == NULL && in != NULL && pj_is_latlong(in->proj) )
-          return MS_SUCCESS;
-
-      p.u = point->x;
-      p.v = point->y;
-
-      if(in==NULL || in->proj==NULL) { /* input coordinates are lat/lon */
-          p.u *= DEG_TO_RAD; /* convert to radians */
-          p.v *= DEG_TO_RAD;  
-          p = pj_fwd(p, out->proj);
-      } else {
-          if(out==NULL || out->proj==NULL) { /* output coordinates are lat/lon */
-              p = pj_inv(p, in->proj);
-              p.u *= RAD_TO_DEG; /* convert to decimal degrees */
-              p.v *= RAD_TO_DEG;
-          } else { /* need to go from one projection to another */
-              p = pj_inv(p, in->proj);
-              p = pj_fwd(p, out->proj);
-          }
+  /* -------------------------------------------------------------------- */
+  /*      Otherwise we fallback to using pj_fwd() or pj_inv() and         */
+  /*      assuming that the NULL projectionObj is supposed to be          */
+  /*      lat/long in the same datum as the other projectionObj.  This    */
+  /*      is essentially a backwards compatibility mode.                  */
+  /* -------------------------------------------------------------------- */
+  else {
+    /* nothing to do if the other coordinate system is also lat/long */
+    if( in == NULL && out != NULL && pj_is_latlong(out->proj) )
+      return MS_SUCCESS;
+    if( out == NULL && in != NULL && pj_is_latlong(in->proj) )
+      return MS_SUCCESS;
+
+    p.u = point->x;
+    p.v = point->y;
+
+    if(in==NULL || in->proj==NULL) { /* input coordinates are lat/lon */
+      p.u *= DEG_TO_RAD; /* convert to radians */
+      p.v *= DEG_TO_RAD;
+      p = pj_fwd(p, out->proj);
+    } else {
+      if(out==NULL || out->proj==NULL) { /* output coordinates are lat/lon */
+        p = pj_inv(p, in->proj);
+        p.u *= RAD_TO_DEG; /* convert to decimal degrees */
+        p.v *= RAD_TO_DEG;
+      } else { /* need to go from one projection to another */
+        p = pj_inv(p, in->proj);
+        p = pj_fwd(p, out->proj);
       }
+    }
 
-      if( p.u == HUGE_VAL || p.v == HUGE_VAL )
-          return MS_FAILURE;
+    if( p.u == HUGE_VAL || p.v == HUGE_VAL )
+      return MS_FAILURE;
 
-      point->x = p.u;
-      point->y = p.v;
+    point->x = p.u;
+    point->y = p.v;
   }
 
-  if( out && out->gt.need_geotransform )
-  {
-      double x_out, y_out;
+  if( out && out->gt.need_geotransform ) {
+    double x_out, y_out;
 
-      x_out = out->gt.invgeotransform[0]
-          + out->gt.invgeotransform[1] * point->x 
-          + out->gt.invgeotransform[2] * point->y;
-      y_out = out->gt.invgeotransform[3]
-          + out->gt.invgeotransform[4] * point->x 
-          + out->gt.invgeotransform[5] * point->y;
+    x_out = out->gt.invgeotransform[0]
+            + out->gt.invgeotransform[1] * point->x
+            + out->gt.invgeotransform[2] * point->y;
+    y_out = out->gt.invgeotransform[3]
+            + out->gt.invgeotransform[4] * point->x
+            + out->gt.invgeotransform[5] * point->y;
 
-      point->x = x_out;
-      point->y = y_out;
+    point->x = x_out;
+    point->y = y_out;
   }
 
   return(MS_SUCCESS);
@@ -170,29 +188,24 @@ int msProjectPoint(projectionObj *in, projectionObj *out, pointObj *point)
 /*                         msProjectGrowRect()                          */
 /************************************************************************/
 #ifdef USE_PROJ
-static void msProjectGrowRect(projectionObj *in, projectionObj *out, 
-                              rectObj *prj_rect, int *rect_initialized, 
+static void msProjectGrowRect(projectionObj *in, projectionObj *out,
+                              rectObj *prj_rect, int *rect_initialized,
                               pointObj *prj_point, int *failure )
 
 {
-    if( msProjectPoint(in, out, prj_point) == MS_SUCCESS )
-    {
-        if( *rect_initialized )
-        {
-            prj_rect->miny = MS_MIN(prj_rect->miny, prj_point->y);
-            prj_rect->maxy = MS_MAX(prj_rect->maxy, prj_point->y);
-            prj_rect->minx = MS_MIN(prj_rect->minx, prj_point->x);
-            prj_rect->maxx = MS_MAX(prj_rect->maxx, prj_point->x);
-        }
-        else
-        {
-            prj_rect->minx = prj_rect->maxx = prj_point->x;
-            prj_rect->miny = prj_rect->maxy = prj_point->y;
-            *rect_initialized = MS_TRUE;
-        }
+  if( msProjectPoint(in, out, prj_point) == MS_SUCCESS ) {
+    if( *rect_initialized ) {
+      prj_rect->miny = MS_MIN(prj_rect->miny, prj_point->y);
+      prj_rect->maxy = MS_MAX(prj_rect->maxy, prj_point->y);
+      prj_rect->minx = MS_MIN(prj_rect->minx, prj_point->x);
+      prj_rect->maxx = MS_MAX(prj_rect->maxx, prj_point->x);
+    } else {
+      prj_rect->minx = prj_rect->maxx = prj_point->x;
+      prj_rect->miny = prj_rect->maxy = prj_point->y;
+      *rect_initialized = MS_TRUE;
     }
-    else
-        (*failure)++;
+  } else
+    (*failure)++;
 }
 #endif /* def USE_PROJ */
 
@@ -202,64 +215,63 @@ static void msProjectGrowRect(projectionObj *in, projectionObj *out,
 /*      Interpolate along a line segment for which one end              */
 /*      reprojects and the other end does not.  Finds the horizon.      */
 /************************************************************************/
-
-static int msProjectSegment( projectionObj *in, projectionObj *out, 
+#ifdef USE_PROJ
+static int msProjectSegment( projectionObj *in, projectionObj *out,
                              pointObj *start, pointObj *end )
 
 {
-    pointObj testPoint, subStart, subEnd;
-
-/* -------------------------------------------------------------------- */
-/*      Without loss of generality we assume the first point            */
-/*      reprojects, and the second doesn't.  If that is not the case    */
-/*      then re-call with the points reversed.                          */
-/* -------------------------------------------------------------------- */
-    testPoint = *start;
+  pointObj testPoint, subStart, subEnd;
+
+  /* -------------------------------------------------------------------- */
+  /*      Without loss of generality we assume the first point            */
+  /*      reprojects, and the second doesn't.  If that is not the case    */
+  /*      then re-call with the points reversed.                          */
+  /* -------------------------------------------------------------------- */
+  testPoint = *start;
+  if( msProjectPoint( in, out, &testPoint ) == MS_FAILURE ) {
+    testPoint = *end;
     if( msProjectPoint( in, out, &testPoint ) == MS_FAILURE )
-    {
-        testPoint = *end;
-        if( msProjectPoint( in, out, &testPoint ) == MS_FAILURE )
-            return MS_FAILURE;
-        else
-            return msProjectSegment( in, out, end, start );
-    }
+      return MS_FAILURE;
+    else
+      return msProjectSegment( in, out, end, start );
+  }
 
-/* -------------------------------------------------------------------- */
-/*      We will apply a binary search till we are within out            */
-/*      tolerance.                                                      */
-/* -------------------------------------------------------------------- */
-    subStart = *start;
-    subEnd = *end;
+  /* -------------------------------------------------------------------- */
+  /*      We will apply a binary search till we are within out            */
+  /*      tolerance.                                                      */
+  /* -------------------------------------------------------------------- */
+  subStart = *start;
+  subEnd = *end;
 
 #define TOLERANCE 0.01
-    
-    while( fabs(subStart.x - subEnd.x) 
-           + fabs(subStart.y - subEnd.y) > TOLERANCE )
-    {
-        pointObj midPoint;
-
-        midPoint.x = (subStart.x + subEnd.x) * 0.5;
-        midPoint.y = (subStart.y + subEnd.y) * 0.5;
-        
-        testPoint = midPoint;
-        
-        if( msProjectPoint( in, out, &testPoint ) == MS_FAILURE )
-            subEnd = midPoint;
-        else
-            subStart = midPoint;
-    }
 
-/* -------------------------------------------------------------------- */
-/*      Now reproject the end points and return.                        */
-/* -------------------------------------------------------------------- */
-    *end = subStart;
-    
-    if( msProjectPoint( in, out, end ) == MS_FAILURE
-        || msProjectPoint( in, out, start ) == MS_FAILURE )
-        return MS_FAILURE;
+  while( fabs(subStart.x - subEnd.x)
+         + fabs(subStart.y - subEnd.y) > TOLERANCE ) {
+    pointObj midPoint;
+
+    midPoint.x = (subStart.x + subEnd.x) * 0.5;
+    midPoint.y = (subStart.y + subEnd.y) * 0.5;
+
+    testPoint = midPoint;
+
+    if( msProjectPoint( in, out, &testPoint ) == MS_FAILURE )
+      subEnd = midPoint;
     else
-        return MS_SUCCESS;
+      subStart = midPoint;
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Now reproject the end points and return.                        */
+  /* -------------------------------------------------------------------- */
+  *end = subStart;
+
+  if( msProjectPoint( in, out, end ) == MS_FAILURE
+      || msProjectPoint( in, out, start ) == MS_FAILURE )
+    return MS_FAILURE;
+  else
+    return MS_SUCCESS;
 }
+#endif
 
 /************************************************************************/
 /*                         msProjectShapeLine()                         */
@@ -274,191 +286,198 @@ static int msProjectSegment( projectionObj *in, projectionObj *out,
 /************************************************************************/
 
 #ifdef USE_PROJ
-static int 
-msProjectShapeLine(projectionObj *in, projectionObj *out, 
+static int
+msProjectShapeLine(projectionObj *in, projectionObj *out,
                    shapeObj *shape, int line_index)
 
 {
-    int i;
-    pointObj	lastPoint, thisPoint, wrkPoint, firstPoint;
-    lineObj *line = shape->line + line_index;
-    lineObj *line_out = line;
-    int valid_flag = 0; /* 1=true, -1=false, 0=unknown */
-    int numpoints_in = line->numpoints;
-    int line_alloc = numpoints_in;
-    int wrap_test;
-
-    wrap_test = out != NULL && out->proj != NULL && pj_is_latlong(out->proj)
-        && !pj_is_latlong(in->proj);
-
-    line->numpoints = 0;
-
-    if( numpoints_in > 0 )
-        firstPoint = line->point[0];
-
-    memset( &lastPoint, 0, sizeof(lastPoint) );
-
-/* -------------------------------------------------------------------- */
-/*      Loop over all input points in linestring.                       */
-/* -------------------------------------------------------------------- */
-    for( i=0; i < numpoints_in; i++ )
-    {
-        int ms_err;
-        wrkPoint = thisPoint = line->point[i];
-
-        ms_err = msProjectPoint(in, out, &wrkPoint );
-
-/* -------------------------------------------------------------------- */
-/*      Apply wrap logic.                                               */
-/* -------------------------------------------------------------------- */
-        if( wrap_test && i > 0 && ms_err != MS_FAILURE )
-        {
-            double dist;
-            pointObj pt1Geo;
-
-            if( line_out->numpoints > 0 )
-                pt1Geo = line_out->point[0];
-            else
-                pt1Geo = wrkPoint; /* this is a cop out */
-
-            dist = wrkPoint.x - pt1Geo.x;
-            if( fabs(dist) > 180.0 
-                && msTestNeedWrap( thisPoint, firstPoint, 
-                                   pt1Geo, in, out ) )
-            {
-                if( dist > 0.0 )
-                    wrkPoint.x -= 360.0;
-                else if( dist < 0.0 )
-                    wrkPoint.x += 360.0;
-            }
-        }
+  int i;
+  pointObj  lastPoint, thisPoint, wrkPoint, firstPoint;
+  lineObj *line = shape->line + line_index;
+  lineObj *line_out = line;
+  int valid_flag = 0; /* 1=true, -1=false, 0=unknown */
+  int numpoints_in = line->numpoints;
+  int line_alloc = numpoints_in;
+  int wrap_test;
+
+#ifdef USE_PROJ_FASTPATHS
+#define MAXEXTENT 20037508.34
+#define M_PIby360 .0087266462599716479
+#define MAXEXTENTby180 111319.4907777777777777777
+  if(in->wellknownprojection == wkp_lonlat && out->wellknownprojection == wkp_gmerc) {
+    for( i = line->numpoints-1; i >= 0; i-- ) {
+#define p_x line->point[i].x
+#define p_y line->point[i].y
+      p_x *= MAXEXTENTby180;
+      p_y = log(tan((90 + p_y) * M_PIby360)) * MS_RAD_TO_DEG;
+      p_y *= MAXEXTENTby180;
+      if (p_x > MAXEXTENT) p_x = MAXEXTENT;
+      if (p_x < -MAXEXTENT) p_x = -MAXEXTENT;
+      if (p_y > MAXEXTENT) p_y = MAXEXTENT;
+      if (p_y < -MAXEXTENT) p_y = -MAXEXTENT;
+#undef p_x
+#undef p_y
+    }
+    return MS_SUCCESS;
+  }
+#endif
 
-/* -------------------------------------------------------------------- */
-/*      Put result into output line with appropriate logic for          */
-/*      failure breaking lines, etc.                                    */
-/* -------------------------------------------------------------------- */
-        if( ms_err == MS_FAILURE ) 
-        {
-            /* We have started out invalid */
-            if( i == 0 )
-            {
-                valid_flag = -1;
-            }
-            
-            /* valid data has ended, we need to work out the horizon */
-            else if( valid_flag == 1 )
-            {
-                pointObj startPoint, endPoint;
-                
-                startPoint = lastPoint;
-                endPoint = thisPoint;
-                if( msProjectSegment( in, out, &startPoint, &endPoint ) 
-                    == MS_SUCCESS )
-                {
-                    line_out->point[line_out->numpoints++] = endPoint;
-                }
-                valid_flag = -1;
-            }
 
-            /* Still invalid ... */
-            else if( valid_flag == -1 )
-            {
-                /* do nothing */
-            }
-        }
 
-        else
-        {
-            /* starting out valid. */
-            if( i == 0 )
-            {
-                line_out->point[line_out->numpoints++] = wrkPoint;
-                valid_flag = 1;
-            }
-            
-            /* Still valid, nothing special */
-            else if( valid_flag == 1 )
-            {
-                line_out->point[line_out->numpoints++] = wrkPoint;
-            }
-            
-            /* we have come over the horizon, figure out where, start newline*/
-            else
-            {
-                pointObj startPoint, endPoint;
-                
-                startPoint = lastPoint;
-                endPoint = thisPoint;
-                if( msProjectSegment( in, out, &endPoint, &startPoint ) 
-                    == MS_SUCCESS )
-                {
-                    lineObj newLine;
-
-                    /* force pre-allocation of lots of points room */
-                    if( line_out->numpoints > 0 
-                        && shape->type == MS_SHAPE_LINE )
-                    {
-                        newLine.numpoints = numpoints_in - i + 1;
-                        newLine.point = line->point;
-                        msAddLine( shape, &newLine );
-
-                        /* new line is now lineout, but start without any points */
-                        line_out = shape->line + shape->numlines-1;
-
-                        line_out->numpoints = 0;
-
-                        /* the shape->line array is realloc, refetch "line" */
-                        line = shape->line + line_index;
-                    }
-                    else if( line_out == line
-                             && line->numpoints >= i-2 )
-                    {
-                        newLine.numpoints = numpoints_in;
-                        newLine.point = line->point;
-                        msAddLine( shape, &newLine );
-
-                        line = shape->line + line_index;
-
-                        line_out = shape->line + shape->numlines-1;
-                        line_out->numpoints = line->numpoints;
-                        line->numpoints = 0;
-                        
-                        /*
-                         * Now realloc this array large enough to hold all
-                         * the points we could possibly need to add. 
-                         */
-                        line_alloc = line_alloc * 2;
-
-                        line_out->point = (pointObj *) 
-                            realloc(line_out->point, 
-                                    sizeof(pointObj) * line_alloc);
-                    }
-                     
-                    line_out->point[line_out->numpoints++] = startPoint;
-                }
-                line_out->point[line_out->numpoints++] = wrkPoint;
-                valid_flag = 1;
-            }
+  wrap_test = out != NULL && out->proj != NULL && pj_is_latlong(out->proj)
+              && !pj_is_latlong(in->proj);
+
+  line->numpoints = 0;
+
+  if( numpoints_in > 0 )
+    firstPoint = line->point[0];
+
+  memset( &lastPoint, 0, sizeof(lastPoint) );
+
+  /* -------------------------------------------------------------------- */
+  /*      Loop over all input points in linestring.                       */
+  /* -------------------------------------------------------------------- */
+  for( i=0; i < numpoints_in; i++ ) {
+    int ms_err;
+    wrkPoint = thisPoint = line->point[i];
+
+    ms_err = msProjectPoint(in, out, &wrkPoint );
+
+    /* -------------------------------------------------------------------- */
+    /*      Apply wrap logic.                                               */
+    /* -------------------------------------------------------------------- */
+    if( wrap_test && i > 0 && ms_err != MS_FAILURE ) {
+      double dist;
+      pointObj pt1Geo;
+
+      if( line_out->numpoints > 0 )
+        pt1Geo = line_out->point[0];
+      else
+        pt1Geo = wrkPoint; /* this is a cop out */
+
+      dist = wrkPoint.x - pt1Geo.x;
+      if( fabs(dist) > 180.0
+          && msTestNeedWrap( thisPoint, firstPoint,
+                             pt1Geo, in, out ) ) {
+        if( dist > 0.0 )
+          wrkPoint.x -= 360.0;
+        else if( dist < 0.0 )
+          wrkPoint.x += 360.0;
+      }
+    }
+
+    /* -------------------------------------------------------------------- */
+    /*      Put result into output line with appropriate logic for          */
+    /*      failure breaking lines, etc.                                    */
+    /* -------------------------------------------------------------------- */
+    if( ms_err == MS_FAILURE ) {
+      /* We have started out invalid */
+      if( i == 0 ) {
+        valid_flag = -1;
+      }
+
+      /* valid data has ended, we need to work out the horizon */
+      else if( valid_flag == 1 ) {
+        pointObj startPoint, endPoint;
+
+        startPoint = lastPoint;
+        endPoint = thisPoint;
+        if( msProjectSegment( in, out, &startPoint, &endPoint )
+            == MS_SUCCESS ) {
+          line_out->point[line_out->numpoints++] = endPoint;
         }
+        valid_flag = -1;
+      }
 
-        lastPoint = thisPoint;
+      /* Still invalid ... */
+      else if( valid_flag == -1 ) {
+        /* do nothing */
+      }
     }
 
-/* -------------------------------------------------------------------- */
-/*      Make sure that polygons are closed, even if the trip over       */
-/*      the horizon left them unclosed.                                 */
-/* -------------------------------------------------------------------- */
-    if( shape->type == MS_SHAPE_POLYGON 
-        && line_out->numpoints > 2 
-        && (line_out->point[0].x != line_out->point[line_out->numpoints-1].x
-            || line_out->point[0].y != line_out->point[line_out->numpoints-1].y) )
-    {
-        /* make a copy because msAddPointToLine can realloc the array */
-        pointObj sFirstPoint = line_out->point[0];
-        msAddPointToLine( line_out, &sFirstPoint );
+    else {
+      /* starting out valid. */
+      if( i == 0 ) {
+        line_out->point[line_out->numpoints++] = wrkPoint;
+        valid_flag = 1;
+      }
+
+      /* Still valid, nothing special */
+      else if( valid_flag == 1 ) {
+        line_out->point[line_out->numpoints++] = wrkPoint;
+      }
+
+      /* we have come over the horizon, figure out where, start newline*/
+      else {
+        pointObj startPoint, endPoint;
+
+        startPoint = lastPoint;
+        endPoint = thisPoint;
+        if( msProjectSegment( in, out, &endPoint, &startPoint )
+            == MS_SUCCESS ) {
+          lineObj newLine;
+
+          /* force pre-allocation of lots of points room */
+          if( line_out->numpoints > 0
+              && shape->type == MS_SHAPE_LINE ) {
+            newLine.numpoints = numpoints_in - i + 1;
+            newLine.point = line->point;
+            msAddLine( shape, &newLine );
+
+            /* new line is now lineout, but start without any points */
+            line_out = shape->line + shape->numlines-1;
+
+            line_out->numpoints = 0;
+
+            /* the shape->line array is realloc, refetch "line" */
+            line = shape->line + line_index;
+          } else if( line_out == line
+                     && line->numpoints >= i-2 ) {
+            newLine.numpoints = numpoints_in;
+            newLine.point = line->point;
+            msAddLine( shape, &newLine );
+
+            line = shape->line + line_index;
+
+            line_out = shape->line + shape->numlines-1;
+            line_out->numpoints = line->numpoints;
+            line->numpoints = 0;
+
+            /*
+             * Now realloc this array large enough to hold all
+             * the points we could possibly need to add.
+             */
+            line_alloc = line_alloc * 2;
+
+            line_out->point = (pointObj *)
+                              realloc(line_out->point,
+                                      sizeof(pointObj) * line_alloc);
+          }
+
+          line_out->point[line_out->numpoints++] = startPoint;
+        }
+        line_out->point[line_out->numpoints++] = wrkPoint;
+        valid_flag = 1;
+      }
     }
 
-    return(MS_SUCCESS);
+    lastPoint = thisPoint;
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Make sure that polygons are closed, even if the trip over       */
+  /*      the horizon left them unclosed.                                 */
+  /* -------------------------------------------------------------------- */
+  if( shape->type == MS_SHAPE_POLYGON
+      && line_out->numpoints > 2
+      && (line_out->point[0].x != line_out->point[line_out->numpoints-1].x
+          || line_out->point[0].y != line_out->point[line_out->numpoints-1].y) ) {
+    /* make a copy because msAddPointToLine can realloc the array */
+    pointObj sFirstPoint = line_out->point[0];
+    msAddPointToLine( line_out, &sFirstPoint );
+  }
+
+  return(MS_SUCCESS);
 }
 #endif
 
@@ -469,26 +488,47 @@ int msProjectShape(projectionObj *in, projectionObj *out, shapeObj *shape)
 {
 #ifdef USE_PROJ
   int i;
-
-  for( i = shape->numlines-1; i >= 0; i-- )
-  {
-      if( shape->type == MS_SHAPE_LINE || shape->type == MS_SHAPE_POLYGON )
-      {
-          if( msProjectShapeLine( in, out, shape, i ) == MS_FAILURE )
-              msShapeDeleteLine( shape, i );
-      }
-      else if( msProjectLine(in, out, shape->line+i ) == MS_FAILURE )
-      {
-          msShapeDeleteLine( shape, i );
+#ifdef USE_PROJ_FASTPATHS
+  int j;
+
+  if(in->wellknownprojection == wkp_lonlat && out->wellknownprojection == wkp_gmerc) {
+    for( i = shape->numlines-1; i >= 0; i-- ) {
+      for( j = shape->line[i].numpoints-1; j >= 0; j-- ) {
+#define p_x shape->line[i].point[j].x
+#define p_y shape->line[i].point[j].y
+        p_x *= MAXEXTENTby180;
+        p_y = log(tan((90 + p_y) * M_PIby360)) * MS_RAD_TO_DEG;
+        p_y *= MAXEXTENTby180;
+        if (p_x > MAXEXTENT) p_x = MAXEXTENT;
+        if (p_x < -MAXEXTENT) p_x = -MAXEXTENT;
+        if (p_y > MAXEXTENT) p_y = MAXEXTENT;
+        if (p_y < -MAXEXTENT) p_y = -MAXEXTENT;
+#undef p_x
+#undef p_y
       }
+    }
+    msComputeBounds( shape ); /* fixes bug 1586 */
+    return MS_SUCCESS;
+  }
+#endif
+
+
+
+  for( i = shape->numlines-1; i >= 0; i-- ) {
+    if( shape->type == MS_SHAPE_LINE || shape->type == MS_SHAPE_POLYGON ) {
+      if( msProjectShapeLine( in, out, shape, i ) == MS_FAILURE )
+        msShapeDeleteLine( shape, i );
+    } else if( msProjectLine(in, out, shape->line+i ) == MS_FAILURE ) {
+      msShapeDeleteLine( shape, i );
+    }
   }
 
   if( shape->numlines == 0 ) {
-      msFreeShape( shape );
-      return MS_FAILURE;
+    msFreeShape( shape );
+    return MS_FAILURE;
   } else {
-      msComputeBounds( shape ); /* fixes bug 1586 */
-      return(MS_SUCCESS);
+    msComputeBounds( shape ); /* fixes bug 1586 */
+    return(MS_SUCCESS);
   }
 #else
   msSetError(MS_PROJERR, "Projection support is not available.", "msProjectShape()");
@@ -510,55 +550,44 @@ int msProjectLine(projectionObj *in, projectionObj *out, lineObj *line)
   int i, be_careful = 1;
 
   if( be_careful )
-      be_careful = out->proj != NULL && pj_is_latlong(out->proj)
-          && !pj_is_latlong(in->proj);
-
-  if( be_careful )
-  {
-      pointObj	startPoint, thisPoint; /* locations in projected space */
-
-      startPoint = line->point[0];
-
-      for(i=0; i<line->numpoints; i++)
-      {
-          double	dist;
-
-          thisPoint = line->point[i];
-
-          /* 
-          ** Read comments before msTestNeedWrap() to better understand
-          ** this dateline wrapping logic. 
-          */
-          msProjectPoint(in, out, &(line->point[i]));
-          if( i > 0 )
-          {
-              dist = line->point[i].x - line->point[0].x;
-              if( fabs(dist) > 180.0 )
-              {
-                  if( msTestNeedWrap( thisPoint, startPoint, 
-                                      line->point[0], in, out ) )
-                  {
-                      if( dist > 0.0 )
-                      {
-                          line->point[i].x -= 360.0;
-                      }
-                      else if( dist < 0.0 )
-                      {
-                          line->point[i].x += 360.0;
-                      }
-                  }
-              }
-
+    be_careful = out->proj != NULL && pj_is_latlong(out->proj)
+                 && !pj_is_latlong(in->proj);
+
+  if( be_careful ) {
+    pointObj  startPoint, thisPoint; /* locations in projected space */
+
+    startPoint = line->point[0];
+
+    for(i=0; i<line->numpoints; i++) {
+      double  dist;
+
+      thisPoint = line->point[i];
+
+      /*
+      ** Read comments before msTestNeedWrap() to better understand
+      ** this dateline wrapping logic.
+      */
+      msProjectPoint(in, out, &(line->point[i]));
+      if( i > 0 ) {
+        dist = line->point[i].x - line->point[0].x;
+        if( fabs(dist) > 180.0 ) {
+          if( msTestNeedWrap( thisPoint, startPoint,
+                              line->point[0], in, out ) ) {
+            if( dist > 0.0 ) {
+              line->point[i].x -= 360.0;
+            } else if( dist < 0.0 ) {
+              line->point[i].x += 360.0;
+            }
           }
+        }
+
       }
-  }
-  else
-  {
-      for(i=0; i<line->numpoints; i++)
-      {
-          if( msProjectPoint(in, out, &(line->point[i])) == MS_FAILURE )
-              return MS_FAILURE;
-      }
+    }
+  } else {
+    for(i=0; i<line->numpoints; i++) {
+      if( msProjectPoint(in, out, &(line->point[i])) == MS_FAILURE )
+        return MS_FAILURE;
+    }
   }
 
   return(MS_SUCCESS);
@@ -574,12 +603,12 @@ int msProjectLine(projectionObj *in, projectionObj *out, lineObj *line)
 
 #define NUMBER_OF_SAMPLE_POINTS 100
 
-int msProjectRectGrid(projectionObj *in, projectionObj *out, rectObj *rect) 
+int msProjectRectGrid(projectionObj *in, projectionObj *out, rectObj *rect)
 {
 #ifdef USE_PROJ
   pointObj prj_point;
   rectObj prj_rect;
-  int	  rect_initialized = MS_FALSE, failure=0;
+  int   rect_initialized = MS_FALSE, failure=0;
   int     ix, iy;
 
   double dx, dy;
@@ -602,44 +631,28 @@ int msProjectRectGrid(projectionObj *in, projectionObj *out, rectObj *rect)
                     &failure);
 
   failure = 0;
-  for(ix = 0; ix <= NUMBER_OF_SAMPLE_POINTS; ix++ )
-  {
-      x = rect->minx + ix * dx;
-      
-      for(iy = 0; iy <= NUMBER_OF_SAMPLE_POINTS; iy++ )
-      {
-          y = rect->miny + iy * dy;
-          
-          prj_point.x = x;
-          prj_point.y = y;
-          msProjectGrowRect(in,out,&prj_rect,&rect_initialized,&prj_point,
-                            &failure);
-      }
-  }
-  
-  if( !rect_initialized )
-  {
-      if( out == NULL || out->proj == NULL 
-          || pj_is_latlong(in->proj) )
-      {
-          prj_rect.minx = -180;
-          prj_rect.maxx = 180;
-          prj_rect.miny = -90;
-          prj_rect.maxy = 90;
-      }
-      else
-      {
-          prj_rect.minx = -22000000;
-          prj_rect.maxx = 22000000;
-          prj_rect.miny = -11000000;
-          prj_rect.maxy = 11000000;
-      }
-      
-      msDebug( "msProjectRect(): all points failed to reproject, trying to fall back to using world bounds ... hope this helps.\n" );
+  for(ix = 0; ix <= NUMBER_OF_SAMPLE_POINTS; ix++ ) {
+    x = rect->minx + ix * dx;
+
+    for(iy = 0; iy <= NUMBER_OF_SAMPLE_POINTS; iy++ ) {
+      y = rect->miny + iy * dy;
+
+      prj_point.x = x;
+      prj_point.y = y;
+      msProjectGrowRect(in,out,&prj_rect,&rect_initialized,&prj_point,
+                        &failure);
+    }
   }
-  else
-  {
-      msDebug( "msProjectRect(): some points failed to reproject, doing internal sampling.\n" );
+
+  if( !rect_initialized ) {
+    prj_rect.minx = 0;
+    prj_rect.maxx = 0;
+    prj_rect.miny = 0;
+    prj_rect.maxy = 0;
+
+    msSetError(MS_PROJERR, "All points failed to reproject.", "msProjectRect()");
+  } else {
+    msDebug( "msProjectRect(): some points failed to reproject, doing internal sampling.\n" );
   }
 
   rect->minx = prj_rect.minx;
@@ -648,9 +661,9 @@ int msProjectRectGrid(projectionObj *in, projectionObj *out, rectObj *rect)
   rect->maxy = prj_rect.maxy;
 
   if( !rect_initialized )
-      return MS_FAILURE;
+    return MS_FAILURE;
   else
-      return(MS_SUCCESS);
+    return(MS_SUCCESS);
 #else
   msSetError(MS_PROJERR, "Projection support is not available.", "msProjectRect()");
   return(MS_FAILURE);
@@ -661,14 +674,14 @@ int msProjectRectGrid(projectionObj *in, projectionObj *out, rectObj *rect)
 /*                    msProjectRectTraditionalEdge()                    */
 /************************************************************************/
 #ifdef notdef
-static int 
-msProjectRectTraditionalEdge(projectionObj *in, projectionObj *out, 
-                             rectObj *rect) 
+static int
+msProjectRectTraditionalEdge(projectionObj *in, projectionObj *out,
+                             rectObj *rect)
 {
 #ifdef USE_PROJ
   pointObj prj_point;
   rectObj prj_rect;
-  int	  rect_initialized = MS_FALSE, failure=0;
+  int   rect_initialized = MS_FALSE, failure=0;
   int     ix, iy;
 
   double dx, dy;
@@ -692,15 +705,14 @@ msProjectRectTraditionalEdge(projectionObj *in, projectionObj *out,
 
   /* sample along top and bottom */
   if(dx > 0) {
-    for(ix = 0; ix <= NUMBER_OF_SAMPLE_POINTS; ix++ )
-    {
+    for(ix = 0; ix <= NUMBER_OF_SAMPLE_POINTS; ix++ ) {
       x = rect->minx + ix * dx;
 
       prj_point.x = x;
       prj_point.y = rect->miny;
       msProjectGrowRect(in,out,&prj_rect,&rect_initialized,&prj_point,
                         &failure);
-      
+
       prj_point.x = x;
       prj_point.y = rect->maxy;
       msProjectGrowRect(in,out,&prj_rect,&rect_initialized,&prj_point,
@@ -710,15 +722,14 @@ msProjectRectTraditionalEdge(projectionObj *in, projectionObj *out,
 
   /* sample along left and right */
   if(dy > 0) {
-    for(iy = 0; iy <= NUMBER_OF_SAMPLE_POINTS; iy++ )
-    {
+    for(iy = 0; iy <= NUMBER_OF_SAMPLE_POINTS; iy++ ) {
       y = rect->miny + iy * dy;
 
       prj_point.y = y;
-      prj_point.x = rect->minx;    
+      prj_point.x = rect->minx;
       msProjectGrowRect(in,out,&prj_rect,&rect_initialized,&prj_point,
                         &failure);
-      
+
       prj_point.x = rect->maxx;
       prj_point.y = y;
       msProjectGrowRect(in,out,&prj_rect,&rect_initialized,&prj_point,
@@ -728,10 +739,10 @@ msProjectRectTraditionalEdge(projectionObj *in, projectionObj *out,
 
   /*
   ** If there have been any failures around the edges, then we had better
-  ** try and fill in the interior to get a close bounds. 
+  ** try and fill in the interior to get a close bounds.
   */
   if( failure > 0 )
-      return msProjectRectGrid( in, out, rect );
+    return msProjectRectGrid( in, out, rect );
 
   rect->minx = prj_rect.minx;
   rect->miny = prj_rect.miny;
@@ -739,9 +750,9 @@ msProjectRectTraditionalEdge(projectionObj *in, projectionObj *out,
   rect->maxy = prj_rect.maxy;
 
   if( !rect_initialized )
-      return MS_FAILURE;
+    return MS_FAILURE;
   else
-      return(MS_SUCCESS);
+    return(MS_SUCCESS);
 #else
   msSetError(MS_PROJERR, "Projection support is not available.", "msProjectRect()");
   return(MS_FAILURE);
@@ -753,19 +764,37 @@ msProjectRectTraditionalEdge(projectionObj *in, projectionObj *out,
 /*                       msProjectRectAsPolygon()                       */
 /************************************************************************/
 
-static int 
-msProjectRectAsPolygon(projectionObj *in, projectionObj *out, 
-                       rectObj *rect) 
+static int
+msProjectRectAsPolygon(projectionObj *in, projectionObj *out,
+                       rectObj *rect)
 {
 #ifdef USE_PROJ
   shapeObj polygonObj;
   lineObj  ring;
-//  pointObj ringPoints[NUMBER_OF_SAMPLE_POINTS*4+4];
+  /*  pointObj ringPoints[NUMBER_OF_SAMPLE_POINTS*4+4]; */
   pointObj *ringPoints;
   int     ix, iy;
 
   double dx, dy;
 
+
+  /* -------------------------------------------------------------------- */
+  /*      Build polygon as steps around the source rectangle.             */
+  /* -------------------------------------------------------------------- */
+  dx = (rect->maxx - rect->minx)/NUMBER_OF_SAMPLE_POINTS;
+  dy = (rect->maxy - rect->miny)/NUMBER_OF_SAMPLE_POINTS;
+
+  if(dx==0 && dy==0) {
+    pointObj foo;
+    msDebug( "msProjectRect(): Warning: degenerate rect {%f,%f,%f,%f}\n",rect->minx,rect->miny,rect->minx,rect->miny );
+    foo.x = rect->minx;
+    foo.y = rect->miny;
+    msProjectPoint(in,out,&foo);
+    rect->minx=rect->maxx=foo.x;
+    rect->miny=rect->maxy=foo.y;
+    return MS_SUCCESS;
+  }
+  
   ringPoints = (pointObj*) calloc(sizeof(pointObj),NUMBER_OF_SAMPLE_POINTS*4+4);
   ring.point = ringPoints;
   ring.numpoints = 0;
@@ -773,16 +802,9 @@ msProjectRectAsPolygon(projectionObj *in, projectionObj *out,
   msInitShape( &polygonObj );
   polygonObj.type = MS_SHAPE_POLYGON;
 
-/* -------------------------------------------------------------------- */
-/*      Build polygon as steps around the source rectangle.             */
-/* -------------------------------------------------------------------- */
-  dx = (rect->maxx - rect->minx)/NUMBER_OF_SAMPLE_POINTS;
-  dy = (rect->maxy - rect->miny)/NUMBER_OF_SAMPLE_POINTS;
-
   /* sample along top */
   if(dx != 0) {
-    for(ix = 0; ix <= NUMBER_OF_SAMPLE_POINTS; ix++ )
-    {
+    for(ix = 0; ix <= NUMBER_OF_SAMPLE_POINTS; ix++ ) {
       ringPoints[ring.numpoints].x = rect->minx + ix * dx;
       ringPoints[ring.numpoints++].y = rect->miny;
     }
@@ -790,8 +812,7 @@ msProjectRectAsPolygon(projectionObj *in, projectionObj *out,
 
   /* sample on along right side */
   if(dy != 0) {
-    for(iy = 1; iy <= NUMBER_OF_SAMPLE_POINTS; iy++ )
-    {
+    for(iy = 1; iy <= NUMBER_OF_SAMPLE_POINTS; iy++ ) {
       ringPoints[ring.numpoints].x = rect->maxx;
       ringPoints[ring.numpoints++].y = rect->miny + iy * dy;
     }
@@ -799,8 +820,7 @@ msProjectRectAsPolygon(projectionObj *in, projectionObj *out,
 
   /* sample along bottom */
   if(dx != 0) {
-    for(ix = NUMBER_OF_SAMPLE_POINTS-1; ix >= 0; ix-- )
-    {
+    for(ix = NUMBER_OF_SAMPLE_POINTS-1; ix >= 0; ix-- ) {
       ringPoints[ring.numpoints].x = rect->minx + ix * dx;
       ringPoints[ring.numpoints++].y = rect->maxy;
     }
@@ -808,8 +828,7 @@ msProjectRectAsPolygon(projectionObj *in, projectionObj *out,
 
   /* sample on along left side */
   if(dy != 0) {
-    for(iy = NUMBER_OF_SAMPLE_POINTS-1; iy >= 0; iy-- )
-    {
+    for(iy = NUMBER_OF_SAMPLE_POINTS-1; iy >= 0; iy-- ) {
       ringPoints[ring.numpoints].x = rect->minx;
       ringPoints[ring.numpoints++].y = rect->miny + iy * dy;
     }
@@ -817,47 +836,44 @@ msProjectRectAsPolygon(projectionObj *in, projectionObj *out,
 
   msAddLineDirectly( &polygonObj, &ring );
 
-/* -------------------------------------------------------------------- */
-/*      Attempt to reproject.                                           */
-/* -------------------------------------------------------------------- */
+  /* -------------------------------------------------------------------- */
+  /*      Attempt to reproject.                                           */
+  /* -------------------------------------------------------------------- */
   msProjectShapeLine( in, out, &polygonObj, 0 );
 
   /* If no points reprojected, try a grid sampling */
-  if( polygonObj.numlines == 0 || polygonObj.line[0].numpoints == 0 )
-  {
-      msFreeShape( &polygonObj );
-      return msProjectRectGrid( in, out, rect );
+  if( polygonObj.numlines == 0 || polygonObj.line[0].numpoints == 0 ) {
+    msFreeShape( &polygonObj );
+    return msProjectRectGrid( in, out, rect );
   }
 
-/* -------------------------------------------------------------------- */
-/*      Collect bounds.                                                 */
-/* -------------------------------------------------------------------- */
+  /* -------------------------------------------------------------------- */
+  /*      Collect bounds.                                                 */
+  /* -------------------------------------------------------------------- */
   rect->minx = rect->maxx = polygonObj.line[0].point[0].x;
   rect->miny = rect->maxy = polygonObj.line[0].point[0].y;
-  
-  for( ix = 1; ix < polygonObj.line[0].numpoints; ix++ )
-  {
-      pointObj  *pnt = polygonObj.line[0].point + ix;
-
-      rect->minx = MS_MIN(rect->minx,pnt->x);
-      rect->maxx = MS_MAX(rect->maxx,pnt->x);
-      rect->miny = MS_MIN(rect->miny,pnt->y);
-      rect->maxy = MS_MAX(rect->maxy,pnt->y);
+
+  for( ix = 1; ix < polygonObj.line[0].numpoints; ix++ ) {
+    pointObj  *pnt = polygonObj.line[0].point + ix;
+
+    rect->minx = MS_MIN(rect->minx,pnt->x);
+    rect->maxx = MS_MAX(rect->maxx,pnt->x);
+    rect->miny = MS_MIN(rect->miny,pnt->y);
+    rect->maxy = MS_MAX(rect->maxy,pnt->y);
   }
 
   msFreeShape( &polygonObj );
 
-/* -------------------------------------------------------------------- */
-/*      Special case to handle reprojection from "more than the         */
-/*      whole world" projected coordinates that sometimes produce a     */
-/*      region greater than 360 degrees wide due to various wrapping    */
-/*      logic.                                                          */
-/* -------------------------------------------------------------------- */
-  if( out && pj_is_latlong(out->proj) && in && !pj_is_latlong(in->proj) 
-      && rect->maxx - rect->minx > 360.0 )
-  {
-      rect->maxx = 180;
-      rect->minx = -180;
+  /* -------------------------------------------------------------------- */
+  /*      Special case to handle reprojection from "more than the         */
+  /*      whole world" projected coordinates that sometimes produce a     */
+  /*      region greater than 360 degrees wide due to various wrapping    */
+  /*      logic.                                                          */
+  /* -------------------------------------------------------------------- */
+  if( out && pj_is_latlong(out->proj) && in && !pj_is_latlong(in->proj)
+      && rect->maxx - rect->minx > 360.0 ) {
+    rect->maxx = 180;
+    rect->minx = -180;
   }
 
   return MS_SUCCESS;
@@ -871,13 +887,13 @@ msProjectRectAsPolygon(projectionObj *in, projectionObj *out,
 /*                           msProjectRect()                            */
 /************************************************************************/
 
-int msProjectRect(projectionObj *in, projectionObj *out, rectObj *rect) 
+int msProjectRect(projectionObj *in, projectionObj *out, rectObj *rect)
 {
 #ifdef notdef
-    return msProjectRectTraditionalEdge( in, out, rect );
+  return msProjectRectTraditionalEdge( in, out, rect );
 #else
-    return msProjectRectAsPolygon( in, out, rect );
-#endif    
+  return msProjectRectAsPolygon( in, out, rect );
+#endif
 }
 
 /************************************************************************/
@@ -885,7 +901,7 @@ int msProjectRect(projectionObj *in, projectionObj *out, rectObj *rect)
 /************************************************************************/
 
 /*
-** Compare two projections, and return MS_TRUE if they differ. 
+** Compare two projections, and return MS_TRUE if they differ.
 **
 ** For now this is implemented by exact comparison of the projection
 ** arguments, but eventually this should call a PROJ.4 function with
@@ -898,26 +914,25 @@ int msProjectRect(projectionObj *in, projectionObj *out, rectObj *rect)
 int msProjectionsDiffer( projectionObj *proj1, projectionObj *proj2 )
 
 {
-    int		i;
+  int   i;
 
-    if( proj1->numargs == 0 || proj2->numargs == 0 )
-        return MS_FALSE;
+  if( proj1->numargs == 0 || proj2->numargs == 0 )
+    return MS_FALSE;
 
-    if( proj1->numargs != proj2->numargs )
-        return MS_TRUE;
+  if( proj1->numargs != proj2->numargs )
+    return MS_TRUE;
 
-    /* This test should be more rigerous. */
-    if( proj1->gt.need_geotransform 
-        || proj2->gt.need_geotransform )
-        return MS_TRUE;
+  /* This test should be more rigerous. */
+  if( proj1->gt.need_geotransform
+      || proj2->gt.need_geotransform )
+    return MS_TRUE;
 
-    for( i = 0; i < proj1->numargs; i++ )
-    {
-        if( strcmp(proj1->args[i],proj2->args[i]) != 0 )
-            return MS_TRUE;
-    }
+  for( i = 0; i < proj1->numargs; i++ ) {
+    if( strcmp(proj1->args[i],proj2->args[i]) != 0 )
+      return MS_TRUE;
+  }
 
-    return MS_FALSE;
+  return MS_FALSE;
 }
 
 /************************************************************************/
@@ -925,9 +940,9 @@ int msProjectionsDiffer( projectionObj *proj1, projectionObj *proj2 )
 /************************************************************************/
 /*
 
-Frank Warmerdam, Nov, 2001. 
+Frank Warmerdam, Nov, 2001.
 
-See Also: 
+See Also:
 
 http://mapserver.gis.umn.edu/bugs/show_bug.cgi?id=15
 
@@ -937,30 +952,30 @@ Modify msProjectLine() so that it "dateline wraps" objects when necessary
 in order to preserve their shape when reprojecting to lat/long.  This
 will be accomplished by:
 
-1) As each vertex is reprojected, compare the X distance between that 
+1) As each vertex is reprojected, compare the X distance between that
    vertex and the previous vertex.  If it is less than 180 then proceed to
    the next vertex without any special logic, otherwise:
 
 2) Reproject the center point of the line segment from the last vertex to
    the current vertex into lat/long.  Does it's longitude lie between the
    longitudes of the start and end point.  If yes, return to step 1) for
-   the next vertex ... everything is fine. 
+   the next vertex ... everything is fine.
 
 3) We have determined that this line segment is suffering from 360 degree
    wrap to keep in the -180 to +180 range.  Now add or subtract 360 degrees
-   as determined from the original sign of the distances.  
+   as determined from the original sign of the distances.
 
-This is similar to the code there now (though disabled in CVS); however, 
+This is similar to the code there now (though disabled in CVS); however,
 it will ensure that big boxes will remain big, and not get dateline wrapped
 because of the extra test in step 2).  However step 2 is invoked only very
-rarely so this process takes little more than the normal process.  In fact, 
+rarely so this process takes little more than the normal process.  In fact,
 if we were sufficiently concerned about performance we could do a test on the
 shape MBR in lat/long space, and if the width is less than 180 we know we never
-need to even do test 1). 
+need to even do test 1).
 
 What doesn't this resolve:
 
-This ensures that individual lines are kept in the proper shape when 
+This ensures that individual lines are kept in the proper shape when
 reprojected to geographic space.  However, it does not:
 
  o Ensure that all rings of a polygon will get transformed to the same "side"
@@ -972,57 +987,57 @@ reprojected to geographic space.  However, it does not:
    vertex of the previous ring (or any previous vertex for that matter).
 
  o It does not address the need to cut up lines and polygons into distinct
-   chunks to preserve the correct semantics.  Really a polygon that 
-   spaces the dateline in a -180 to 180 view should get split into two 
+   chunks to preserve the correct semantics.  Really a polygon that
+   spaces the dateline in a -180 to 180 view should get split into two
    polygons.  We haven't addressed that, though if it were to be addressed,
    it could be done as a followon and distinct step from what we are doing
    above.  In fact this sort of improvement (split polygons based on dateline
-   or view window) should be done for all lat/long shapes regardless of 
-   whether they are being reprojected from another projection. 
+   or view window) should be done for all lat/long shapes regardless of
+   whether they are being reprojected from another projection.
 
  o It does not address issues related to viewing rectangles that go outside
    the -180 to 180 longitude range.  For instance, it is entirely reasonable
    to want a 160 to 200 longitude view to see an area on the dateline clearly.
    Currently shapes in the -180 to -160 range which should be displayed in the
    180 to 200 portion of that view will not be because there is no recogition
-   that they belong there. 
+   that they belong there.
 
 
 */
 
 #ifdef USE_PROJ
 static int msTestNeedWrap( pointObj pt1, pointObj pt2, pointObj pt2_geo,
-                           projectionObj *in, 
+                           projectionObj *in,
                            projectionObj *out )
 
 {
-    pointObj	middle;
-
-    middle.x = (pt1.x + pt2.x) * 0.5;
-    middle.y = (pt1.y + pt2.y) * 0.5;
-    
-    if( msProjectPoint( in, out, &pt1 ) == MS_FAILURE 
-        || msProjectPoint( in, out, &pt2 ) == MS_FAILURE
-        || msProjectPoint( in, out, &middle ) == MS_FAILURE )
-        return 0;
-
-    /* 
-     * If the last point was moved, then we are considered due for a
-     * move to.
-     */
-    if( fabs(pt2_geo.x-pt2.x) > 180.0 )
-        return 1;
-
-    /*
-     * Otherwise, test to see if the middle point transforms
-     * to be between the end points. If yes, no wrapping is needed.
-     * Otherwise wrapping is needed.
-     */
-    if( (middle.x < pt1.x && middle.x < pt2_geo.x)
-        || (middle.x > pt1.x && middle.x > pt2_geo.x) )
-        return 1;
-    else
-        return 0;
+  pointObj  middle;
+
+  middle.x = (pt1.x + pt2.x) * 0.5;
+  middle.y = (pt1.y + pt2.y) * 0.5;
+
+  if( msProjectPoint( in, out, &pt1 ) == MS_FAILURE
+      || msProjectPoint( in, out, &pt2 ) == MS_FAILURE
+      || msProjectPoint( in, out, &middle ) == MS_FAILURE )
+    return 0;
+
+  /*
+   * If the last point was moved, then we are considered due for a
+   * move to.
+   */
+  if( fabs(pt2_geo.x-pt2.x) > 180.0 )
+    return 1;
+
+  /*
+   * Otherwise, test to see if the middle point transforms
+   * to be between the end points. If yes, no wrapping is needed.
+   * Otherwise wrapping is needed.
+   */
+  if( (middle.x < pt1.x && middle.x < pt2_geo.x)
+      || (middle.x > pt1.x && middle.x > pt2_geo.x) )
+    return 1;
+  else
+    return 0;
 }
 #endif /* def USE_PROJ */
 
@@ -1036,19 +1051,19 @@ static char *last_filename = NULL;
 static const char *msProjFinder( const char *filename)
 
 {
-    if( last_filename != NULL )
-        free( last_filename );
+  if( last_filename != NULL )
+    free( last_filename );
 
-    if( filename == NULL )
-        return NULL;
+  if( filename == NULL )
+    return NULL;
 
-    if( ms_proj_lib == NULL )
-        return filename;
+  if( ms_proj_lib == NULL )
+    return filename;
 
-    last_filename = (char *) malloc(strlen(filename)+strlen(ms_proj_lib)+2);
-    sprintf( last_filename, "%s/%s", ms_proj_lib, filename );
+  last_filename = (char *) malloc(strlen(filename)+strlen(ms_proj_lib)+2);
+  sprintf( last_filename, "%s/%s", ms_proj_lib, filename );
 
-    return last_filename;
+  return last_filename;
 }
 #endif /* def USE_PROJ */
 
@@ -1059,59 +1074,55 @@ void msSetPROJ_LIB( const char *proj_lib, const char *pszRelToPath )
 
 {
 #ifdef USE_PROJ
-    static int finder_installed = 0;
-    char *extended_path = NULL;
-
-    /* Handle relative path if applicable */
-    if( proj_lib && pszRelToPath
-        && proj_lib[0] != '/'
-        && proj_lib[0] != '\\'
-        && !(proj_lib[0] != '\0' && proj_lib[1] == ':') )
-    {
-        struct stat stat_buf;
-        extended_path = (char*) msSmallMalloc(strlen(pszRelToPath)
-                                              + strlen(proj_lib) + 10);
-        sprintf( extended_path, "%s/%s", pszRelToPath, proj_lib );
+  static int finder_installed = 0;
+  char *extended_path = NULL;
+
+  /* Handle relative path if applicable */
+  if( proj_lib && pszRelToPath
+      && proj_lib[0] != '/'
+      && proj_lib[0] != '\\'
+      && !(proj_lib[0] != '\0' && proj_lib[1] == ':') ) {
+    struct stat stat_buf;
+    extended_path = (char*) msSmallMalloc(strlen(pszRelToPath)
+                                          + strlen(proj_lib) + 10);
+    sprintf( extended_path, "%s/%s", pszRelToPath, proj_lib );
 
 #ifndef S_ISDIR
 #  define S_ISDIR(x) ((x) & S_IFDIR)
-#endif            
-            
-        if( stat( extended_path, &stat_buf ) == 0 
-            && S_ISDIR(stat_buf.st_mode) )
-            proj_lib = extended_path;
-    }
+#endif
 
+    if( stat( extended_path, &stat_buf ) == 0
+        && S_ISDIR(stat_buf.st_mode) )
+      proj_lib = extended_path;
+  }
 
-    msAcquireLock( TLOCK_PROJ );
 
-    if( finder_installed == 0 && proj_lib != NULL)
-    {
-        finder_installed = 1;
-        pj_set_finder( msProjFinder );
-    }
-    
-    if (proj_lib == NULL) pj_set_finder(NULL);
-    
-    if( ms_proj_lib != NULL )
-    {
-        free( ms_proj_lib );
-        ms_proj_lib = NULL;
-    }
+  msAcquireLock( TLOCK_PROJ );
 
-    if( last_filename != NULL )
-    {
-        free( last_filename );
-        last_filename = NULL;
-    }
+  if( finder_installed == 0 && proj_lib != NULL) {
+    finder_installed = 1;
+    pj_set_finder( msProjFinder );
+  }
 
-    if( proj_lib != NULL )
-        ms_proj_lib = msStrdup( proj_lib );
-    
-    msReleaseLock( TLOCK_PROJ );
+  if (proj_lib == NULL) pj_set_finder(NULL);
+
+  if( ms_proj_lib != NULL ) {
+    free( ms_proj_lib );
+    ms_proj_lib = NULL;
+  }
+
+  if( last_filename != NULL ) {
+    free( last_filename );
+    last_filename = NULL;
+  }
+
+  if( proj_lib != NULL )
+    ms_proj_lib = msStrdup( proj_lib );
 
-    if ( extended_path )
-        msFree( extended_path );
+  msReleaseLock( TLOCK_PROJ );
+
+  if ( extended_path )
+    msFree( extended_path );
 #endif
 }
 
@@ -1123,48 +1134,42 @@ void msSetPROJ_LIB( const char *proj_lib, const char *pszRelToPath )
 
 char *msGetProjectionString(projectionObj *proj)
 {
-    char        *pszProjString = NULL;
-    int         i = 0, nLen = 0;
-
-    if (proj)
-    {
-/* -------------------------------------------------------------------- */
-/*      Alloc buffer large enough to hold the whole projection defn     */
-/* -------------------------------------------------------------------- */
-        for (i=0; i<proj->numargs; i++)
-        {
-            if (proj->args[i])
-                nLen += (strlen(proj->args[i]) + 2);
-        }
+  char        *pszProjString = NULL;
+  int         i = 0, nLen = 0;
+
+  if (proj) {
+    /* -------------------------------------------------------------------- */
+    /*      Alloc buffer large enough to hold the whole projection defn     */
+    /* -------------------------------------------------------------------- */
+    for (i=0; i<proj->numargs; i++) {
+      if (proj->args[i])
+        nLen += (strlen(proj->args[i]) + 2);
+    }
 
-        pszProjString = (char*)malloc(sizeof(char) * nLen+1);
-        pszProjString[0] = '\0';
-
-/* -------------------------------------------------------------------- */
-/*      Plug each arg into the string with a '+' prefix                 */
-/* -------------------------------------------------------------------- */
-        for (i=0; i<proj->numargs; i++)
-        {
-            if (!proj->args[i] || strlen(proj->args[i]) == 0)
-                continue;
-            if (pszProjString[0] == '\0')
-            {
-                /* no space at beginning of line */
-                if (proj->args[i][0] != '+')
-                    strcat(pszProjString, "+");
-            }
-            else
-            {
-                if (proj->args[i][0] != '+')
-                    strcat(pszProjString, " +");
-                else
-                    strcat(pszProjString, " ");
-            }
-            strcat(pszProjString, proj->args[i]);
-        }
+    pszProjString = (char*)malloc(sizeof(char) * nLen+1);
+    pszProjString[0] = '\0';
+
+    /* -------------------------------------------------------------------- */
+    /*      Plug each arg into the string with a '+' prefix                 */
+    /* -------------------------------------------------------------------- */
+    for (i=0; i<proj->numargs; i++) {
+      if (!proj->args[i] || strlen(proj->args[i]) == 0)
+        continue;
+      if (pszProjString[0] == '\0') {
+        /* no space at beginning of line */
+        if (proj->args[i][0] != '+')
+          strcat(pszProjString, "+");
+      } else {
+        if (proj->args[i][0] != '+')
+          strcat(pszProjString, " +");
+        else
+          strcat(pszProjString, " ");
+      }
+      strcat(pszProjString, proj->args[i]);
     }
+  }
 
-    return pszProjString;
+  return pszProjString;
 }
 
 /************************************************************************/
@@ -1174,44 +1179,40 @@ char *msGetProjectionString(projectionObj *proj)
 /*      orientation if they are not already.                            */
 /************************************************************************/
 
-void msAxisNormalizePoints( projectionObj *proj, int count, 
+void msAxisNormalizePoints( projectionObj *proj, int count,
                             double *x, double *y )
 
 {
-    int i;
-    const char *axis = NULL;
-
-    for( i = 0; i < proj->numargs; i++ )
-    {
-        if( strstr(proj->args[i],"epsgaxis=") != NULL )
-        {
-            axis = strstr(proj->args[i],"=") + 1;
-            break;
-        }
+  int i;
+  const char *axis = NULL;
+
+  for( i = 0; i < proj->numargs; i++ ) {
+    if( strstr(proj->args[i],"epsgaxis=") != NULL ) {
+      axis = strstr(proj->args[i],"=") + 1;
+      break;
     }
+  }
 
-    if( axis == NULL )
-        return;
+  if( axis == NULL )
+    return;
 
-    if( strcasecmp(axis,"en") == 0 )
-        return;
+  if( strcasecmp(axis,"en") == 0 )
+    return;
 
-    if( strcasecmp(axis,"ne") != 0 )
-    {
-        msDebug( "msAxisNormalizePoints(): odd +epsgaxis= value: '%s'.",
-                 axis );
-        return;
-    }
+  if( strcasecmp(axis,"ne") != 0 ) {
+    msDebug( "msAxisNormalizePoints(): odd +epsgaxis= value: '%s'.",
+             axis );
+    return;
+  }
 
-    /* Switch axes */
-    for( i = 0; i < count; i++ )
-    {
-        double tmp;
+  /* Switch axes */
+  for( i = 0; i < count; i++ ) {
+    double tmp;
 
-        tmp = x[i];
-        x[i] = y[i];
-        y[i] = tmp;
-    }
+    tmp = x[i];
+    x[i] = y[i];
+    y[i] = tmp;
+  }
 }
 
 /************************************************************************/
@@ -1221,10 +1222,10 @@ void msAxisNormalizePoints( projectionObj *proj, int count,
 /*      preferred epsg orientation of this projectionObj.               */
 /************************************************************************/
 
-void msAxisDenormalizePoints( projectionObj *proj, int count, 
+void msAxisDenormalizePoints( projectionObj *proj, int count,
                               double *x, double *y )
 
 {
-    /* For how this is essentially identical to normalizing */
-    msAxisNormalizePoints( proj, count, x, y );
+  /* For how this is essentially identical to normalizing */
+  msAxisNormalizePoints( proj, count, x, y );
 }
diff --git a/mapproject.h b/mapproject.h
index b788a84..716b8f2 100644
--- a/mapproject.h
+++ b/mapproject.h
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -39,59 +39,72 @@ extern "C" {
 
 #ifdef USE_PROJ
 #  include <proj_api.h>
+#if PJ_VERSION >= 470 && PJ_VERSION < 480
+   void pj_clear_initcache();
 #endif
+#endif
+
+#define wkp_none 0
+#define wkp_lonlat 1
+#define wkp_gmerc 2
 
 
-typedef struct {
+  typedef struct {
 #ifdef SWIG
-  %immutable;
+    %immutable;
 #endif
-  int numargs; /* actual number of projection args */
-  int automatic; /* projection object was to fetched from the layer */ 
+    int numargs; /* actual number of projection args */
+    int automatic; /* projection object was to fetched from the layer */
 #ifdef SWIG
-  %mutable;
+    %mutable;
 #endif
 #ifndef SWIG
-  char **args; /* variable number of projection args */
+    char **args; /* variable number of projection args */
 #ifdef USE_PROJ
-  projPJ proj; /* a projection structure for the PROJ package */
+    projPJ proj; /* a projection structure for the PROJ package */
+#if PJ_VERSION >= 480
+    projCtx proj_ctx;
+#endif
 #else
-  void *proj;
+    void *proj;
 #endif
-  geotransformObj gt; /* extra transformation to apply */
+    geotransformObj gt; /* extra transformation to apply */
 #endif
-} projectionObj;
+    int wellknownprojection;
+  } projectionObj;
 
 #ifndef SWIG
-MS_DLL_EXPORT int msProjectPoint(projectionObj *in, projectionObj *out, pointObj *point);
-MS_DLL_EXPORT int msProjectShape(projectionObj *in, projectionObj *out, shapeObj *shape);
-MS_DLL_EXPORT int msProjectLine(projectionObj *in, projectionObj *out, lineObj *line);
-MS_DLL_EXPORT int msProjectRect(projectionObj *in, projectionObj *out, rectObj *rect);
-MS_DLL_EXPORT int msProjectionsDiffer(projectionObj *, projectionObj *);
-MS_DLL_EXPORT int msOGCWKT2ProjectionObj( const char *pszWKT, projectionObj *proj, int
-                            debug_flag );
-MS_DLL_EXPORT char *msProjectionObj2OGCWKT( projectionObj *proj );
 
-MS_DLL_EXPORT void msFreeProjection(projectionObj *p);
-MS_DLL_EXPORT int msInitProjection(projectionObj *p);
-MS_DLL_EXPORT int msProcessProjection(projectionObj *p);
-MS_DLL_EXPORT int msLoadProjectionString(projectionObj *p, const char *value);
-MS_DLL_EXPORT int msLoadProjectionStringEPSG(projectionObj *p, const char *value);
-MS_DLL_EXPORT char *msGetProjectionString(projectionObj *proj);
-MS_DLL_EXPORT void msAxisNormalizePoints( projectionObj *proj, int count,
-                                          double *x, double *y );
-MS_DLL_EXPORT void msAxisDenormalizePoints( projectionObj *proj, int count,
-                                            double *x, double *y );
+  MS_DLL_EXPORT int msIsAxisInverted(int epsg_code);
+  MS_DLL_EXPORT int msProjectPoint(projectionObj *in, projectionObj *out, pointObj *point);
+  MS_DLL_EXPORT int msProjectShape(projectionObj *in, projectionObj *out, shapeObj *shape);
+  MS_DLL_EXPORT int msProjectLine(projectionObj *in, projectionObj *out, lineObj *line);
+  MS_DLL_EXPORT int msProjectRect(projectionObj *in, projectionObj *out, rectObj *rect);
+  MS_DLL_EXPORT int msProjectionsDiffer(projectionObj *, projectionObj *);
+  MS_DLL_EXPORT int msOGCWKT2ProjectionObj( const char *pszWKT, projectionObj *proj, int
+      debug_flag );
+  MS_DLL_EXPORT char *msProjectionObj2OGCWKT( projectionObj *proj );
+
+  MS_DLL_EXPORT void msFreeProjection(projectionObj *p);
+  MS_DLL_EXPORT int msInitProjection(projectionObj *p);
+  MS_DLL_EXPORT int msProcessProjection(projectionObj *p);
+  MS_DLL_EXPORT int msLoadProjectionString(projectionObj *p, const char *value);
+  MS_DLL_EXPORT int msLoadProjectionStringEPSG(projectionObj *p, const char *value);
+  MS_DLL_EXPORT char *msGetProjectionString(projectionObj *proj);
+  MS_DLL_EXPORT void msAxisNormalizePoints( projectionObj *proj, int count,
+      double *x, double *y );
+  MS_DLL_EXPORT void msAxisDenormalizePoints( projectionObj *proj, int count,
+      double *x, double *y );
 
-MS_DLL_EXPORT void msSetPROJ_LIB( const char *, const char * );
+  MS_DLL_EXPORT void msSetPROJ_LIB( const char *, const char * );
 
-/* Provides compatiblity with PROJ.4 4.4.2 */
+  /* Provides compatiblity with PROJ.4 4.4.2 */
 #ifndef PJ_VERSION
-#  define pj_is_latlong(x)	((x)->is_latlong)
+#  define pj_is_latlong(x)  ((x)->is_latlong)
 #endif
 
-/*utility functions */
-MS_DLL_EXPORT int GetMapserverUnitUsingProj(projectionObj *psProj);
+  /*utility functions */
+  MS_DLL_EXPORT int GetMapserverUnitUsingProj(projectionObj *psProj);
 #endif
 
 #ifdef __cplusplus
diff --git a/mapprojhack.c b/mapprojhack.c
index 24bbd64..869e92c 100644
--- a/mapprojhack.c
+++ b/mapprojhack.c
@@ -14,24 +14,20 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
+ *
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  ****************************************************************************/
 
 #include <string.h>
-#include "mapproject.h"
-
-enum MS_UNITS {MS_INCHES, MS_FEET, MS_MILES, MS_METERS, MS_KILOMETERS,
-               MS_DD, MS_PIXELS, MS_NAUTICALMILES};
-
+#include "mapserver.h"
 
 /************************************************************************/
 /*                        ConvertProjUnitStringToMS                     */
@@ -40,35 +36,24 @@ enum MS_UNITS {MS_INCHES, MS_FEET, MS_MILES, MS_METERS, MS_KILOMETERS,
 /*      unit passed as argument.                                        */
 /*       Please refer to ./src/pj_units.c file in the Proj.4 module.    */
 /************************************************************************/
-#ifdef USE_PROJ 
+#ifdef USE_PROJ
 static int ConvertProjUnitStringToMS(const char *pszProjUnit)
 {
-    if (strcmp(pszProjUnit, "m") ==0)
-    {
-        return MS_METERS;
-    }
-    else if (strcmp(pszProjUnit, "km") ==0)
-    {
-        return MS_KILOMETERS;
-    }
-    else if (strcmp(pszProjUnit, "mi") ==0 || strcmp(pszProjUnit, "us-mi") ==0)
-    {
-        return MS_MILES;
-    }
-    else if (strcmp(pszProjUnit, "in") ==0 || strcmp(pszProjUnit, "us-in") ==0 )
-    {
-        return MS_INCHES;
-    }
-    else if (strcmp(pszProjUnit, "ft") ==0 || strcmp(pszProjUnit, "us-ft") ==0)
-    {
-        return MS_FEET;
-    }
-    else if (strcmp(pszProjUnit, "kmi") == 0)
-    {
-        return MS_NAUTICALMILES;
-    }
-    
-    return -1;              
+  if (strcmp(pszProjUnit, "m") ==0) {
+    return MS_METERS;
+  } else if (strcmp(pszProjUnit, "km") ==0) {
+    return MS_KILOMETERS;
+  } else if (strcmp(pszProjUnit, "mi") ==0 || strcmp(pszProjUnit, "us-mi") ==0) {
+    return MS_MILES;
+  } else if (strcmp(pszProjUnit, "in") ==0 || strcmp(pszProjUnit, "us-in") ==0 ) {
+    return MS_INCHES;
+  } else if (strcmp(pszProjUnit, "ft") ==0 || strcmp(pszProjUnit, "us-ft") ==0) {
+    return MS_FEET;
+  } else if (strcmp(pszProjUnit, "kmi") == 0) {
+    return MS_NAUTICALMILES;
+  }
+
+  return -1;
 }
 #endif /* def USE_PROJ */
 
@@ -81,69 +66,67 @@ static int ConvertProjUnitStringToMS(const char *pszProjUnit)
 int GetMapserverUnitUsingProj(projectionObj *psProj)
 {
 #ifdef USE_PROJ
-    char *proj_str;
-
-    if( pj_is_latlong( psProj->proj ) )
-        return MS_DD;
-
-    proj_str = pj_get_def( psProj->proj, 0 );
-
-/* -------------------------------------------------------------------- */
-/*      Handle case of named units.                                     */
-/* -------------------------------------------------------------------- */
-    if( strstr(proj_str,"units=") != NULL )
-    {
-        char units[32];
-        char *blank;
-
-        strncpy( units, (strstr(proj_str,"units=")+6), sizeof(units)-2 );
-        pj_dalloc( proj_str );
-
-        blank = strchr(units, ' ');
-        if( blank != NULL )
-            *blank = '\0';
-
-        return ConvertProjUnitStringToMS( units );
-    }
-
-/* -------------------------------------------------------------------- */
-/*      Handle case of to_meter value.                                  */
-/* -------------------------------------------------------------------- */
-    if( strstr(proj_str,"to_meter=") != NULL )
-    {
-        char to_meter_str[32];
-        char *blank;
-        double to_meter;
-
-        strncpy(to_meter_str,(strstr(proj_str,"to_meter=")+9),
-                sizeof(to_meter_str)-2);
-        pj_dalloc( proj_str );
-
-        blank = strchr(to_meter_str, ' ');
-        if( blank != NULL )
-            *blank = '\0';
-
-        to_meter = atof(to_meter_str);
-
-        if( fabs(to_meter-1.0) < 0.0000001 )
-            return MS_METERS;
-        else if( fabs(to_meter-1000.0) < 0.00001 )
-            return MS_KILOMETERS;
-        else if( fabs(to_meter-0.3048) < 0.0001 )
-            return MS_FEET;
-        else if( fabs(to_meter-0.0254) < 0.0001 )
-            return MS_INCHES;
-        else if( fabs(to_meter-1609.344) < 0.001 )
-            return MS_MILES;
-        else if( fabs(to_meter-1852.0) < 0.1 )
-            return MS_NAUTICALMILES;
-        else
-            return -1;
-    }
+  char *proj_str;
+
+  if( pj_is_latlong( psProj->proj ) )
+    return MS_DD;
+
+  proj_str = pj_get_def( psProj->proj, 0 );
 
+  /* -------------------------------------------------------------------- */
+  /*      Handle case of named units.                                     */
+  /* -------------------------------------------------------------------- */
+  if( strstr(proj_str,"units=") != NULL ) {
+    char units[32];
+    char *blank;
+
+    strlcpy( units, (strstr(proj_str,"units=")+6), sizeof(units) );
     pj_dalloc( proj_str );
+
+    blank = strchr(units, ' ');
+    if( blank != NULL )
+      *blank = '\0';
+
+    return ConvertProjUnitStringToMS( units );
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Handle case of to_meter value.                                  */
+  /* -------------------------------------------------------------------- */
+  if( strstr(proj_str,"to_meter=") != NULL ) {
+    char to_meter_str[32];
+    char *blank;
+    double to_meter;
+
+    strlcpy(to_meter_str,(strstr(proj_str,"to_meter=")+9),
+            sizeof(to_meter_str));
+    pj_dalloc( proj_str );
+
+    blank = strchr(to_meter_str, ' ');
+    if( blank != NULL )
+      *blank = '\0';
+
+    to_meter = atof(to_meter_str);
+
+    if( fabs(to_meter-1.0) < 0.0000001 )
+      return MS_METERS;
+    else if( fabs(to_meter-1000.0) < 0.00001 )
+      return MS_KILOMETERS;
+    else if( fabs(to_meter-0.3048) < 0.0001 )
+      return MS_FEET;
+    else if( fabs(to_meter-0.0254) < 0.0001 )
+      return MS_INCHES;
+    else if( fabs(to_meter-1609.344) < 0.001 )
+      return MS_MILES;
+    else if( fabs(to_meter-1852.0) < 0.1 )
+      return MS_NAUTICALMILES;
+    else
+      return -1;
+  }
+
+  pj_dalloc( proj_str );
 #endif
-    return -1;
+  return -1;
 }
 
 
diff --git a/mapquantization.c b/mapquantization.c
index ebbeb2e..de923af 100644
--- a/mapquantization.c
+++ b/mapquantization.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -27,9 +27,9 @@
  * DEALINGS IN THE SOFTWARE.
  ******************************************************************************
  */
-/* 
+/*
  * derivations from pngquant and ppmquant
- * 
+ *
  ** pngquant.c - quantize the colors in an alphamap down to a specified number
  **
  ** Copyright (C) 1989, 1991 by Jef Poskanzer.
@@ -67,14 +67,14 @@
 
 typedef struct acolorhist_item *acolorhist_vector;
 struct acolorhist_item {
-    rgbaPixel acolor;
-    int value;
+  rgbaPixel acolor;
+  int value;
 };
 
 typedef struct acolorhist_list_item *acolorhist_list;
 struct acolorhist_list_item {
-    struct acolorhist_item ch;
-    acolorhist_list next;
+  struct acolorhist_item ch;
+  acolorhist_list next;
 };
 
 typedef acolorhist_list *acolorhash_table;
@@ -86,9 +86,9 @@ typedef acolorhist_list *acolorhash_table;
 
 typedef struct box *box_vector;
 struct box {
-    int ind;
-    int colors;
-    int sum;
+  int ind;
+  int colors;
+  int sum;
 };
 
 static acolorhist_vector mediancut
@@ -127,139 +127,140 @@ static void pam_freeacolorhash (acolorhash_table acht);
  *   255, and rb's pixels will have been scaled down to maxsize (see bug #3848)
  */
 int msQuantizeRasterBuffer(rasterBufferObj *rb,
-      unsigned int *reqcolors, rgbaPixel *palette,
-      rgbaPixel *forced_palette, int num_forced_palette_entries,
-      unsigned int *palette_scaling_maxval) {
-          rgbaPixel **apixels=NULL; /* pointer to the start rows of truecolor pixels */
-	
-    register rgbaPixel *pP;
-    register int col;
-    
-    unsigned char newmaxval;
-    acolorhist_vector achv, acolormap=NULL;
-    
-    int row;
-    int colors;
-    int newcolors = 0;
-    
-    int x;
-    /*  int channels;  */
-    
-	 assert(rb->type == MS_BUFFER_BYTE_RGBA);
-
-    *palette_scaling_maxval = 255;
-
-    apixels=(rgbaPixel**)msSmallMalloc(rb->height*sizeof(rgbaPixel**));
-    
-    for(row=0;row<rb->height;row++) {
-        apixels[row]=(rgbaPixel*)(&(rb->data.rgba.pixels[row * rb->data.rgba.row_step]));
-    }
-
-    /*
-     ** Step 2: attempt to make a histogram of the colors, unclustered.
-     ** If at first we don't succeed, lower maxval to increase color
-     ** coherence and try again.  This will eventually terminate, with
-     ** maxval at worst 15, since 32^3 is approximately MAXCOLORS.
-                  [GRR POSSIBLE BUG:  what about 32^4 ?]
-     */
-    for ( ; ; ) {
-        achv = pam_computeacolorhist(
-                apixels, rb->width, rb->height, MAXCOLORS, &colors );
-        if ( achv != (acolorhist_vector) 0 )
-            break;
-        newmaxval = *palette_scaling_maxval / 2;
-        for ( row = 0; row < rb->height; ++row )
-            for ( col = 0, pP = apixels[row]; col < rb->width; ++col, ++pP )
-                PAM_DEPTH( *pP, *pP, *palette_scaling_maxval, newmaxval );
-        *palette_scaling_maxval = newmaxval;
-    }
-    newcolors = MS_MIN(colors, *reqcolors);
-    acolormap = mediancut(achv, colors, rb->width*rb->height, *palette_scaling_maxval, newcolors);
-    pam_freeacolorhist(achv);
-    
-    
-    *reqcolors = newcolors;
-
-
-    for (x = 0; x < newcolors; ++x) {
-       palette[x].r = acolormap[x].acolor.r;
-       palette[x].g = acolormap[x].acolor.g;
-       palette[x].b = acolormap[x].acolor.b;
-       palette[x].a = acolormap[x].acolor.a;
-    }
-    
-   free(acolormap);
-   free(apixels);
-   return MS_SUCCESS;
+                           unsigned int *reqcolors, rgbaPixel *palette,
+                           rgbaPixel *forced_palette, int num_forced_palette_entries,
+                           unsigned int *palette_scaling_maxval)
+{
+  rgbaPixel **apixels=NULL; /* pointer to the start rows of truecolor pixels */
+
+  register rgbaPixel *pP;
+  register int col;
+
+  unsigned char newmaxval;
+  acolorhist_vector achv, acolormap=NULL;
+
+  int row;
+  int colors;
+  int newcolors = 0;
+
+  int x;
+  /*  int channels;  */
+
+  assert(rb->type == MS_BUFFER_BYTE_RGBA);
+
+  *palette_scaling_maxval = 255;
+
+  apixels=(rgbaPixel**)msSmallMalloc(rb->height*sizeof(rgbaPixel**));
+
+  for(row=0; row<rb->height; row++) {
+    apixels[row]=(rgbaPixel*)(&(rb->data.rgba.pixels[row * rb->data.rgba.row_step]));
+  }
+
+  /*
+   ** Step 2: attempt to make a histogram of the colors, unclustered.
+   ** If at first we don't succeed, lower maxval to increase color
+   ** coherence and try again.  This will eventually terminate, with
+   ** maxval at worst 15, since 32^3 is approximately MAXCOLORS.
+                [GRR POSSIBLE BUG:  what about 32^4 ?]
+   */
+  for ( ; ; ) {
+    achv = pam_computeacolorhist(
+             apixels, rb->width, rb->height, MAXCOLORS, &colors );
+    if ( achv != (acolorhist_vector) 0 )
+      break;
+    newmaxval = *palette_scaling_maxval / 2;
+    for ( row = 0; row < rb->height; ++row )
+      for ( col = 0, pP = apixels[row]; col < rb->width; ++col, ++pP )
+        PAM_DEPTH( *pP, *pP, *palette_scaling_maxval, newmaxval );
+    *palette_scaling_maxval = newmaxval;
+  }
+  newcolors = MS_MIN(colors, *reqcolors);
+  acolormap = mediancut(achv, colors, rb->width*rb->height, *palette_scaling_maxval, newcolors);
+  pam_freeacolorhist(achv);
+
+
+  *reqcolors = newcolors;
+
+
+  for (x = 0; x < newcolors; ++x) {
+    palette[x].r = acolormap[x].acolor.r;
+    palette[x].g = acolormap[x].acolor.g;
+    palette[x].b = acolormap[x].acolor.b;
+    palette[x].a = acolormap[x].acolor.a;
+  }
+
+  free(acolormap);
+  free(apixels);
+  return MS_SUCCESS;
 }
 
 
-int msClassifyRasterBuffer(rasterBufferObj *rb, rasterBufferObj *qrb) {
-   register int ind;
-   unsigned char *outrow,*pQ;
-   register rgbaPixel *pP;
-   acolorhash_table acht;
-   int usehash, row, col;
-    /*
-     ** Step 4: map the colors in the image to their closest match in the
-     ** new colormap, and write 'em out.
-     */
-    acht = pam_allocacolorhash( );
-    usehash = 1;
-
-    for ( row = 0; row < qrb->height; ++row ) {
-        outrow = &(qrb->data.palette.pixels[row*qrb->width]);
-        col = 0;
-        pP = (rgbaPixel*)(&(rb->data.rgba.pixels[row * rb->data.rgba.row_step]));;
-        pQ = outrow;
-        do {
-            /* Check hash table to see if we have already matched this color. */
-            ind = pam_lookupacolor( acht, pP );
-            if ( ind == -1 ) {
-                /* No; search acolormap for closest match. */
-                register int i, r1, g1, b1, a1, r2, g2, b2, a2;
-                register long dist, newdist;
-
-                r1 = PAM_GETR( *pP );
-                g1 = PAM_GETG( *pP );
-                b1 = PAM_GETB( *pP );
-                a1 = PAM_GETA( *pP );
-                dist = 2000000000;
-                for ( i = 0; i < qrb->data.palette.num_entries; ++i ) {
-                    r2 = PAM_GETR( qrb->data.palette.palette[i] );
-                    g2 = PAM_GETG( qrb->data.palette.palette[i] );
-                    b2 = PAM_GETB( qrb->data.palette.palette[i] );
-                    a2 = PAM_GETA( qrb->data.palette.palette[i] );
-                    /* GRR POSSIBLE BUG */
-                    newdist = ( r1 - r2 ) * ( r1 - r2 ) +  /* may overflow? */
+int msClassifyRasterBuffer(rasterBufferObj *rb, rasterBufferObj *qrb)
+{
+  register int ind;
+  unsigned char *outrow,*pQ;
+  register rgbaPixel *pP;
+  acolorhash_table acht;
+  int usehash, row, col;
+  /*
+   ** Step 4: map the colors in the image to their closest match in the
+   ** new colormap, and write 'em out.
+   */
+  acht = pam_allocacolorhash( );
+  usehash = 1;
+
+  for ( row = 0; row < qrb->height; ++row ) {
+    outrow = &(qrb->data.palette.pixels[row*qrb->width]);
+    col = 0;
+    pP = (rgbaPixel*)(&(rb->data.rgba.pixels[row * rb->data.rgba.row_step]));;
+    pQ = outrow;
+    do {
+      /* Check hash table to see if we have already matched this color. */
+      ind = pam_lookupacolor( acht, pP );
+      if ( ind == -1 ) {
+        /* No; search acolormap for closest match. */
+        register int i, r1, g1, b1, a1, r2, g2, b2, a2;
+        register long dist, newdist;
+
+        r1 = PAM_GETR( *pP );
+        g1 = PAM_GETG( *pP );
+        b1 = PAM_GETB( *pP );
+        a1 = PAM_GETA( *pP );
+        dist = 2000000000;
+        for ( i = 0; i < qrb->data.palette.num_entries; ++i ) {
+          r2 = PAM_GETR( qrb->data.palette.palette[i] );
+          g2 = PAM_GETG( qrb->data.palette.palette[i] );
+          b2 = PAM_GETB( qrb->data.palette.palette[i] );
+          a2 = PAM_GETA( qrb->data.palette.palette[i] );
+          /* GRR POSSIBLE BUG */
+          newdist = ( r1 - r2 ) * ( r1 - r2 ) +  /* may overflow? */
                     ( g1 - g2 ) * ( g1 - g2 ) +
                     ( b1 - b2 ) * ( b1 - b2 ) +
                     ( a1 - a2 ) * ( a1 - a2 );
-                    if ( newdist < dist ) {
-                        ind = i;
-                        dist = newdist;
-                    }
-                }
-                if ( usehash ) {
-                    if ( pam_addtoacolorhash( acht, pP, ind ) < 0 ) {
-                        usehash = 0;
-                    }
-                }
-            }
-
-            /*          *pP = acolormap[ind].acolor;  */
-            *pQ = (unsigned char)ind;
-
-            ++col;
-            ++pP;
-            ++pQ;
-
+          if ( newdist < dist ) {
+            ind = i;
+            dist = newdist;
+          }
         }
-        while ( col != rb->width );
-    }
-    pam_freeacolorhash(acht);
+        if ( usehash ) {
+          if ( pam_addtoacolorhash( acht, pP, ind ) < 0 ) {
+            usehash = 0;
+          }
+        }
+      }
+
+      /*          *pP = acolormap[ind].acolor;  */
+      *pQ = (unsigned char)ind;
+
+      ++col;
+      ++pP;
+      ++pQ;
+
+    } while ( col != rb->width );
+  }
+  pam_freeacolorhash(acht);
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 
@@ -271,293 +272,285 @@ int msClassifyRasterBuffer(rasterBufferObj *rb, rasterBufferObj *qrb) {
  */
 
 static acolorhist_vector
-mediancut( achv, colors, sum, maxval, newcolors )
-acolorhist_vector achv;
-int colors, sum, newcolors;
-unsigned char maxval;
+mediancut( acolorhist_vector achv, int colors, int sum, unsigned char maxval, int newcolors )
 {
-    acolorhist_vector acolormap;
-    box_vector bv;
-    register int bi, i;
-    int boxes;
-
-    bv = (box_vector) malloc( sizeof(struct box) * newcolors );
-    acolormap =
-        (acolorhist_vector) malloc( sizeof(struct acolorhist_item) * newcolors);
-    if ( bv == (box_vector) 0 || acolormap == (acolorhist_vector) 0 ) {
-        fprintf( stderr, "  out of memory allocating box vector\n" );
-        fflush(stderr);
-        exit(6);
-    }
-    for ( i = 0; i < newcolors; ++i )
-        PAM_ASSIGN( acolormap[i].acolor, 0, 0, 0, 0 );
+  acolorhist_vector acolormap;
+  box_vector bv;
+  register int bi, i;
+  int boxes;
+
+  bv = (box_vector) malloc( sizeof(struct box) * newcolors );
+  acolormap =
+    (acolorhist_vector) malloc( sizeof(struct acolorhist_item) * newcolors);
+  if ( bv == (box_vector) 0 || acolormap == (acolorhist_vector) 0 ) {
+    fprintf( stderr, "  out of memory allocating box vector\n" );
+    fflush(stderr);
+    exit(6);
+  }
+  for ( i = 0; i < newcolors; ++i )
+    PAM_ASSIGN( acolormap[i].acolor, 0, 0, 0, 0 );
+
+  /*
+   ** Set up the initial box.
+   */
+  bv[0].ind = 0;
+  bv[0].colors = colors;
+  bv[0].sum = sum;
+  boxes = 1;
+
+  /*
+   ** Main loop: split boxes until we have enough.
+   */
+  while ( boxes < newcolors ) {
+    register int indx, clrs;
+    int sm;
+    register int minr, maxr, ming, mina, maxg, minb, maxb, maxa, v;
+    int halfsum, lowersum;
 
     /*
-     ** Set up the initial box.
+     ** Find the first splittable box.
      */
-    bv[0].ind = 0;
-    bv[0].colors = colors;
-    bv[0].sum = sum;
-    boxes = 1;
+    for ( bi = 0; bi < boxes; ++bi )
+      if ( bv[bi].colors >= 2 )
+        break;
+    if ( bi == boxes )
+      break;        /* ran out of colors! */
+    indx = bv[bi].ind;
+    clrs = bv[bi].colors;
+    sm = bv[bi].sum;
 
     /*
-     ** Main loop: split boxes until we have enough.
+     ** Go through the box finding the minimum and maximum of each
+     ** component - the boundaries of the box.
      */
-    while ( boxes < newcolors ) {
-        register int indx, clrs;
-        int sm;
-        register int minr, maxr, ming, mina, maxg, minb, maxb, maxa, v;
-        int halfsum, lowersum;
-
-        /*
-         ** Find the first splittable box.
-         */
-        for ( bi = 0; bi < boxes; ++bi )
-            if ( bv[bi].colors >= 2 )
-                break;
-        if ( bi == boxes )
-            break;        /* ran out of colors! */
-        indx = bv[bi].ind;
-        clrs = bv[bi].colors;
-        sm = bv[bi].sum;
-
-        /*
-         ** Go through the box finding the minimum and maximum of each
-         ** component - the boundaries of the box.
-         */
-        minr = maxr = PAM_GETR( achv[indx].acolor );
-        ming = maxg = PAM_GETG( achv[indx].acolor );
-        minb = maxb = PAM_GETB( achv[indx].acolor );
-        mina = maxa = PAM_GETA( achv[indx].acolor );
-        for ( i = 1; i < clrs; ++i )
-        {
-            v = PAM_GETR( achv[indx + i].acolor );
-            if ( v < minr ) minr = v;
-            if ( v > maxr ) maxr = v;
-            v = PAM_GETG( achv[indx + i].acolor );
-            if ( v < ming ) ming = v;
-            if ( v > maxg ) maxg = v;
-            v = PAM_GETB( achv[indx + i].acolor );
-            if ( v < minb ) minb = v;
-            if ( v > maxb ) maxb = v;
-            v = PAM_GETA( achv[indx + i].acolor );
-            if ( v < mina ) mina = v;
-            if ( v > maxa ) maxa = v;
-        }
+    minr = maxr = PAM_GETR( achv[indx].acolor );
+    ming = maxg = PAM_GETG( achv[indx].acolor );
+    minb = maxb = PAM_GETB( achv[indx].acolor );
+    mina = maxa = PAM_GETA( achv[indx].acolor );
+    for ( i = 1; i < clrs; ++i ) {
+      v = PAM_GETR( achv[indx + i].acolor );
+      if ( v < minr ) minr = v;
+      if ( v > maxr ) maxr = v;
+      v = PAM_GETG( achv[indx + i].acolor );
+      if ( v < ming ) ming = v;
+      if ( v > maxg ) maxg = v;
+      v = PAM_GETB( achv[indx + i].acolor );
+      if ( v < minb ) minb = v;
+      if ( v > maxb ) maxb = v;
+      v = PAM_GETA( achv[indx + i].acolor );
+      if ( v < mina ) mina = v;
+      if ( v > maxa ) maxa = v;
+    }
 
-        /*
-         ** Find the largest dimension, and sort by that component.  I have
-         ** included two methods for determining the "largest" dimension;
-         ** first by simply comparing the range in RGB space, and second
-         ** by transforming into luminosities before the comparison.  You
-         ** can switch which method is used by switching the commenting on
-         ** the LARGE_ defines at the beginning of this source file.
-         */
+    /*
+     ** Find the largest dimension, and sort by that component.  I have
+     ** included two methods for determining the "largest" dimension;
+     ** first by simply comparing the range in RGB space, and second
+     ** by transforming into luminosities before the comparison.  You
+     ** can switch which method is used by switching the commenting on
+     ** the LARGE_ defines at the beginning of this source file.
+     */
 #ifdef LARGE_NORM
-        if ( maxa - mina >= maxr - minr && maxa - mina >= maxg - ming && maxa - mina >= maxb - minb )
-            qsort(
-                    (char*) &(achv[indx]), clrs, sizeof(struct acolorhist_item),
-                    alphacompare );
-        else if ( maxr - minr >= maxg - ming && maxr - minr >= maxb - minb )
-            qsort(
-                    (char*) &(achv[indx]), clrs, sizeof(struct acolorhist_item),
-                    redcompare );
-        else if ( maxg - ming >= maxb - minb )
-            qsort(
-                    (char*) &(achv[indx]), clrs, sizeof(struct acolorhist_item),
-                    greencompare );
-        else
-            qsort(
-                    (char*) &(achv[indx]), clrs, sizeof(struct acolorhist_item),
-                    bluecompare );
+    if ( maxa - mina >= maxr - minr && maxa - mina >= maxg - ming && maxa - mina >= maxb - minb )
+      qsort(
+        (char*) &(achv[indx]), clrs, sizeof(struct acolorhist_item),
+        alphacompare );
+    else if ( maxr - minr >= maxg - ming && maxr - minr >= maxb - minb )
+      qsort(
+        (char*) &(achv[indx]), clrs, sizeof(struct acolorhist_item),
+        redcompare );
+    else if ( maxg - ming >= maxb - minb )
+      qsort(
+        (char*) &(achv[indx]), clrs, sizeof(struct acolorhist_item),
+        greencompare );
+    else
+      qsort(
+        (char*) &(achv[indx]), clrs, sizeof(struct acolorhist_item),
+        bluecompare );
 #endif /*LARGE_NORM*/
 #ifdef LARGE_LUM
-        {
-            apixel p;
-            float rl, gl, bl, al;
-
-            PAM_ASSIGN(p, maxr - minr, 0, 0, 0);
-            rl = PPM_LUMIN(p);
-            PAM_ASSIGN(p, 0, maxg - ming, 0, 0);
-            gl = PPM_LUMIN(p);
-            PAM_ASSIGN(p, 0, 0, maxb - minb, 0);
-            bl = PPM_LUMIN(p);
-
-            /*
-GRR: treat alpha as grayscale and assign (maxa - mina) to each of R, G, B?
-     assign (maxa - mina)/3 to each?
-     use alpha-fractional luminosity?  (normalized_alpha * lum(r,g,b))
-        al = dunno ...
-     [probably should read Heckbert's paper to decide]
-             */
-
-            if ( al >= rl && al >= gl && al >= bl )
-                qsort(
-                        (char*) &(achv[indx]), clrs, sizeof(struct acolorhist_item),
-                        alphacompare );
-            else if ( rl >= gl && rl >= bl )
-                qsort(
-                        (char*) &(achv[indx]), clrs, sizeof(struct acolorhist_item),
-                        redcompare );
-            else if ( gl >= bl )
-                qsort(
-                        (char*) &(achv[indx]), clrs, sizeof(struct acolorhist_item),
-                        greencompare );
-            else
-                qsort(
-                        (char*) &(achv[indx]), clrs, sizeof(struct acolorhist_item),
-                        bluecompare );
-        }
+    {
+      apixel p;
+      float rl, gl, bl, al;
+
+      PAM_ASSIGN(p, maxr - minr, 0, 0, 0);
+      rl = PPM_LUMIN(p);
+      PAM_ASSIGN(p, 0, maxg - ming, 0, 0);
+      gl = PPM_LUMIN(p);
+      PAM_ASSIGN(p, 0, 0, maxb - minb, 0);
+      bl = PPM_LUMIN(p);
+
+      /*
+      GRR: treat alpha as grayscale and assign (maxa - mina) to each of R, G, B?
+      assign (maxa - mina)/3 to each?
+      use alpha-fractional luminosity?  (normalized_alpha * lum(r,g,b))
+      al = dunno ...
+      [probably should read Heckbert's paper to decide]
+       */
+
+      if ( al >= rl && al >= gl && al >= bl )
+        qsort(
+          (char*) &(achv[indx]), clrs, sizeof(struct acolorhist_item),
+          alphacompare );
+      else if ( rl >= gl && rl >= bl )
+        qsort(
+          (char*) &(achv[indx]), clrs, sizeof(struct acolorhist_item),
+          redcompare );
+      else if ( gl >= bl )
+        qsort(
+          (char*) &(achv[indx]), clrs, sizeof(struct acolorhist_item),
+          greencompare );
+      else
+        qsort(
+          (char*) &(achv[indx]), clrs, sizeof(struct acolorhist_item),
+          bluecompare );
+    }
 #endif /*LARGE_LUM*/
 
-        /*
-         ** Now find the median based on the counts, so that about half the
-         ** pixels (not colors, pixels) are in each subdivision.
-         */
-        lowersum = achv[indx].value;
-        halfsum = sm / 2;
-        for ( i = 1; i < clrs - 1; ++i )
-        {
-            if ( lowersum >= halfsum )
-                break;
-            lowersum += achv[indx + i].value;
-        }
-
-        /*
-         ** Split the box, and sort to bring the biggest boxes to the top.
-         */
-        bv[bi].colors = i;
-        bv[bi].sum = lowersum;
-        bv[boxes].ind = indx + i;
-        bv[boxes].colors = clrs - i;
-        bv[boxes].sum = sm - lowersum;
-        ++boxes;
-        qsort( (char*) bv, boxes, sizeof(struct box), sumcompare );
+    /*
+     ** Now find the median based on the counts, so that about half the
+     ** pixels (not colors, pixels) are in each subdivision.
+     */
+    lowersum = achv[indx].value;
+    halfsum = sm / 2;
+    for ( i = 1; i < clrs - 1; ++i ) {
+      if ( lowersum >= halfsum )
+        break;
+      lowersum += achv[indx + i].value;
     }
 
     /*
-     ** Ok, we've got enough boxes.  Now choose a representative color for
-     ** each box.  There are a number of possible ways to make this choice.
-     ** One would be to choose the center of the box; this ignores any structure
-     ** within the boxes.  Another method would be to average all the colors in
-     ** the box - this is the method specified in Heckbert's paper.  A third
-     ** method is to average all the pixels in the box.  You can switch which
-     ** method is used by switching the commenting on the REP_ defines at
-     ** the beginning of this source file.
+     ** Split the box, and sort to bring the biggest boxes to the top.
      */
-    for ( bi = 0; bi < boxes; ++bi ) {
+    bv[bi].colors = i;
+    bv[bi].sum = lowersum;
+    bv[boxes].ind = indx + i;
+    bv[boxes].colors = clrs - i;
+    bv[boxes].sum = sm - lowersum;
+    ++boxes;
+    qsort( (char*) bv, boxes, sizeof(struct box), sumcompare );
+  }
+
+  /*
+   ** Ok, we've got enough boxes.  Now choose a representative color for
+   ** each box.  There are a number of possible ways to make this choice.
+   ** One would be to choose the center of the box; this ignores any structure
+   ** within the boxes.  Another method would be to average all the colors in
+   ** the box - this is the method specified in Heckbert's paper.  A third
+   ** method is to average all the pixels in the box.  You can switch which
+   ** method is used by switching the commenting on the REP_ defines at
+   ** the beginning of this source file.
+   */
+  for ( bi = 0; bi < boxes; ++bi ) {
 #ifdef REP_CENTER_BOX
-        register int indx = bv[bi].ind;
-        register int clrs = bv[bi].colors;
-        register int minr, maxr, ming, maxg, minb, maxb, mina, maxa, v;
-
-        minr = maxr = PAM_GETR( achv[indx].acolor );
-        ming = maxg = PAM_GETG( achv[indx].acolor );
-        minb = maxb = PAM_GETB( achv[indx].acolor );
-        mina = maxa = PAM_GETA( achv[indx].acolor );
-        for ( i = 1; i < clrs; ++i )
-        {
-            v = PAM_GETR( achv[indx + i].acolor );
-            minr = min( minr, v );
-            maxr = max( maxr, v );
-            v = PAM_GETG( achv[indx + i].acolor );
-            ming = min( ming, v );
-            maxg = max( maxg, v );
-            v = PAM_GETB( achv[indx + i].acolor );
-            minb = min( minb, v );
-            maxb = max( maxb, v );
-            v = PAM_GETA( achv[indx + i].acolor );
-            mina = min( mina, v );
-            maxa = max( maxa, v );
-        }
-        PAM_ASSIGN(
-                acolormap[bi].acolor, ( minr + maxr ) / 2, ( ming + maxg ) / 2,
-                ( minb + maxb ) / 2, ( mina + maxa ) / 2 );
+    register int indx = bv[bi].ind;
+    register int clrs = bv[bi].colors;
+    register int minr, maxr, ming, maxg, minb, maxb, mina, maxa, v;
+
+    minr = maxr = PAM_GETR( achv[indx].acolor );
+    ming = maxg = PAM_GETG( achv[indx].acolor );
+    minb = maxb = PAM_GETB( achv[indx].acolor );
+    mina = maxa = PAM_GETA( achv[indx].acolor );
+    for ( i = 1; i < clrs; ++i ) {
+      v = PAM_GETR( achv[indx + i].acolor );
+      minr = min( minr, v );
+      maxr = max( maxr, v );
+      v = PAM_GETG( achv[indx + i].acolor );
+      ming = min( ming, v );
+      maxg = max( maxg, v );
+      v = PAM_GETB( achv[indx + i].acolor );
+      minb = min( minb, v );
+      maxb = max( maxb, v );
+      v = PAM_GETA( achv[indx + i].acolor );
+      mina = min( mina, v );
+      maxa = max( maxa, v );
+    }
+    PAM_ASSIGN(
+      acolormap[bi].acolor, ( minr + maxr ) / 2, ( ming + maxg ) / 2,
+      ( minb + maxb ) / 2, ( mina + maxa ) / 2 );
 #endif /*REP_CENTER_BOX*/
 #ifdef REP_AVERAGE_COLORS
-        register int indx = bv[bi].ind;
-        register int clrs = bv[bi].colors;
-        register long r = 0, g = 0, b = 0, a = 0;
-
-        for ( i = 0; i < clrs; ++i )
-        {
-            r += PAM_GETR( achv[indx + i].acolor );
-            g += PAM_GETG( achv[indx + i].acolor );
-            b += PAM_GETB( achv[indx + i].acolor );
-            a += PAM_GETA( achv[indx + i].acolor );
-        }
-        r = r / clrs;
-        g = g / clrs;
-        b = b / clrs;
-        a = a / clrs;
-        PAM_ASSIGN( acolormap[bi].acolor, r, g, b, a );
+    register int indx = bv[bi].ind;
+    register int clrs = bv[bi].colors;
+    register long r = 0, g = 0, b = 0, a = 0;
+
+    for ( i = 0; i < clrs; ++i ) {
+      r += PAM_GETR( achv[indx + i].acolor );
+      g += PAM_GETG( achv[indx + i].acolor );
+      b += PAM_GETB( achv[indx + i].acolor );
+      a += PAM_GETA( achv[indx + i].acolor );
+    }
+    r = r / clrs;
+    g = g / clrs;
+    b = b / clrs;
+    a = a / clrs;
+    PAM_ASSIGN( acolormap[bi].acolor, r, g, b, a );
 #endif /*REP_AVERAGE_COLORS*/
 #ifdef REP_AVERAGE_PIXELS
-        register int indx = bv[bi].ind;
-        register int clrs = bv[bi].colors;
-        register long r = 0, g = 0, b = 0, a = 0, sum = 0;
-
-        for ( i = 0; i < clrs; ++i )
-        {
-            r += PAM_GETR( achv[indx + i].acolor ) * achv[indx + i].value;
-            g += PAM_GETG( achv[indx + i].acolor ) * achv[indx + i].value;
-            b += PAM_GETB( achv[indx + i].acolor ) * achv[indx + i].value;
-            a += PAM_GETA( achv[indx + i].acolor ) * achv[indx + i].value;
-            sum += achv[indx + i].value;
-        }
-        r = r / sum;
-        if ( r > maxval ) r = maxval;        /* avoid math errors */
-        g = g / sum;
-        if ( g > maxval ) g = maxval;
-        b = b / sum;
-        if ( b > maxval ) b = maxval;
-        a = a / sum;
-        if ( a > maxval ) a = maxval;
-        /* GRR 20001228:  added casts to quiet warnings; 255 DEPENDENCY */
-        PAM_ASSIGN( acolormap[bi].acolor, (unsigned char)r, (unsigned char)g, (unsigned char)b, (unsigned char)a );
-#endif /*REP_AVERAGE_PIXELS*/
+    register int indx = bv[bi].ind;
+    register int clrs = bv[bi].colors;
+    register long r = 0, g = 0, b = 0, a = 0, sum = 0;
+
+    for ( i = 0; i < clrs; ++i ) {
+      r += PAM_GETR( achv[indx + i].acolor ) * achv[indx + i].value;
+      g += PAM_GETG( achv[indx + i].acolor ) * achv[indx + i].value;
+      b += PAM_GETB( achv[indx + i].acolor ) * achv[indx + i].value;
+      a += PAM_GETA( achv[indx + i].acolor ) * achv[indx + i].value;
+      sum += achv[indx + i].value;
     }
+    r = r / sum;
+    if ( r > maxval ) r = maxval;        /* avoid math errors */
+    g = g / sum;
+    if ( g > maxval ) g = maxval;
+    b = b / sum;
+    if ( b > maxval ) b = maxval;
+    a = a / sum;
+    if ( a > maxval ) a = maxval;
+    /* GRR 20001228:  added casts to quiet warnings; 255 DEPENDENCY */
+    PAM_ASSIGN( acolormap[bi].acolor, (unsigned char)r, (unsigned char)g, (unsigned char)b, (unsigned char)a );
+#endif /*REP_AVERAGE_PIXELS*/
+  }
 
-    /*
-     ** All done.
-     */
-    free(bv);
-    return acolormap;
+  /*
+   ** All done.
+   */
+  free(bv);
+  return acolormap;
 }
 
 static int
 redcompare( const void *ch1, const void *ch2 )
 {
-    return (int) PAM_GETR( ((acolorhist_vector)ch1)->acolor ) -
-    (int) PAM_GETR( ((acolorhist_vector)ch2)->acolor );
+  return (int) PAM_GETR( ((acolorhist_vector)ch1)->acolor ) -
+         (int) PAM_GETR( ((acolorhist_vector)ch2)->acolor );
 }
 
 static int
 greencompare( const void *ch1, const void *ch2 )
 {
-    return (int) PAM_GETG( ((acolorhist_vector)ch1)->acolor ) -
-    (int) PAM_GETG( ((acolorhist_vector)ch2)->acolor );
+  return (int) PAM_GETG( ((acolorhist_vector)ch1)->acolor ) -
+         (int) PAM_GETG( ((acolorhist_vector)ch2)->acolor );
 }
 
 static int
 bluecompare( const void *ch1, const void *ch2 )
 {
-    return (int) PAM_GETB( ((acolorhist_vector)ch1)->acolor ) -
-    (int) PAM_GETB( ((acolorhist_vector)ch2)->acolor );
+  return (int) PAM_GETB( ((acolorhist_vector)ch1)->acolor ) -
+         (int) PAM_GETB( ((acolorhist_vector)ch2)->acolor );
 }
 
 static int
 alphacompare( const void *ch1, const void *ch2 )
 {
-    return (int) PAM_GETA( ((acolorhist_vector)ch1)->acolor ) -
-    (int) PAM_GETA( ((acolorhist_vector)ch2)->acolor );
+  return (int) PAM_GETA( ((acolorhist_vector)ch1)->acolor ) -
+         (int) PAM_GETA( ((acolorhist_vector)ch2)->acolor );
 }
 
 static int
 sumcompare( const void *b1, const void *b2 )
 {
-    return ((box_vector)b2)->sum -
-    ((box_vector)b1)->sum;
+  return ((box_vector)b2)->sum -
+         ((box_vector)b1)->sum;
 }
 
 
@@ -598,15 +591,15 @@ rgbaPixel** apixels;
 int cols, rows, maxacolors;
 int* acolorsP;
 {
-    acolorhash_table acht;
-    acolorhist_vector achv;
-
-    acht = pam_computeacolorhash( apixels, cols, rows, maxacolors, acolorsP );
-    if ( acht == (acolorhash_table) 0 )
-        return (acolorhist_vector) 0;
-    achv = pam_acolorhashtoacolorhist( acht, maxacolors );
-    pam_freeacolorhash( acht );
-    return achv;
+  acolorhash_table acht;
+  acolorhist_vector achv;
+
+  acht = pam_computeacolorhash( apixels, cols, rows, maxacolors, acolorsP );
+  if ( acht == (acolorhash_table) 0 )
+    return (acolorhist_vector) 0;
+  achv = pam_acolorhashtoacolorhist( acht, maxacolors );
+  pam_freeacolorhash( acht );
+  return achv;
 }
 
 
@@ -617,44 +610,41 @@ rgbaPixel** apixels;
 int cols, rows, maxacolors;
 int* acolorsP;
 {
-    acolorhash_table acht;
-    register rgbaPixel* pP;
-    acolorhist_list achl;
-    int col, row, hash;
-
-    acht = pam_allocacolorhash( );
-    *acolorsP = 0;
-
-    /* Go through the entire image, building a hash table of colors. */
-    for ( row = 0; row < rows; ++row )
-        for ( col = 0, pP = apixels[row]; col < cols; ++col, ++pP )
-        {
-            hash = pam_hashapixel( *pP );
-            for ( achl = acht[hash]; achl != (acolorhist_list) 0; achl = achl->next )
-                if ( PAM_EQUAL( achl->ch.acolor, *pP ) )
-                    break;
-            if ( achl != (acolorhist_list) 0 )
-                ++(achl->ch.value);
-            else
-            {
-                if ( ++(*acolorsP) > maxacolors )
-                {
-                    pam_freeacolorhash( acht );
-                    return (acolorhash_table) 0;
-                }
-                achl = (acolorhist_list) malloc( sizeof(struct acolorhist_list_item) );
-                if ( achl == 0 ) {
-                    fprintf( stderr, "  out of memory computing hash table\n" );
-                    exit(7);
-                }
-                achl->ch.acolor = *pP;
-                achl->ch.value = 1;
-                achl->next = acht[hash];
-                acht[hash] = achl;
-            }
+  acolorhash_table acht;
+  register rgbaPixel* pP;
+  acolorhist_list achl;
+  int col, row, hash;
+
+  acht = pam_allocacolorhash( );
+  *acolorsP = 0;
+
+  /* Go through the entire image, building a hash table of colors. */
+  for ( row = 0; row < rows; ++row )
+    for ( col = 0, pP = apixels[row]; col < cols; ++col, ++pP ) {
+      hash = pam_hashapixel( *pP );
+      for ( achl = acht[hash]; achl != (acolorhist_list) 0; achl = achl->next )
+        if ( PAM_EQUAL( achl->ch.acolor, *pP ) )
+          break;
+      if ( achl != (acolorhist_list) 0 )
+        ++(achl->ch.value);
+      else {
+        if ( ++(*acolorsP) > maxacolors ) {
+          pam_freeacolorhash( acht );
+          return (acolorhash_table) 0;
         }
+        achl = (acolorhist_list) malloc( sizeof(struct acolorhist_list_item) );
+        if ( achl == 0 ) {
+          fprintf( stderr, "  out of memory computing hash table\n" );
+          exit(7);
+        }
+        achl->ch.acolor = *pP;
+        achl->ch.value = 1;
+        achl->next = acht[hash];
+        acht[hash] = achl;
+      }
+    }
 
-    return acht;
+  return acht;
 }
 
 
@@ -662,19 +652,19 @@ int* acolorsP;
 static acolorhash_table
 pam_allocacolorhash( )
 {
-    acolorhash_table acht;
-    int i;
+  acolorhash_table acht;
+  int i;
 
-    acht = (acolorhash_table) malloc( HASH_SIZE * sizeof(acolorhist_list) );
-    if ( acht == 0 ) {
-        fprintf( stderr, "  out of memory allocating hash table\n" );
-        exit(8);
-    }
+  acht = (acolorhash_table) malloc( HASH_SIZE * sizeof(acolorhist_list) );
+  if ( acht == 0 ) {
+    fprintf( stderr, "  out of memory allocating hash table\n" );
+    exit(8);
+  }
 
-    for ( i = 0; i < HASH_SIZE; ++i )
-        acht[i] = (acolorhist_list) 0;
+  for ( i = 0; i < HASH_SIZE; ++i )
+    acht[i] = (acolorhist_list) 0;
 
-    return acht;
+  return acht;
 }
 
 
@@ -685,17 +675,17 @@ acolorhash_table acht;
 rgbaPixel* acolorP;
 int value;
 {
-    register int hash;
-    register acolorhist_list achl;
+  register int hash;
+  register acolorhist_list achl;
 
-    achl = (acolorhist_list) msSmallMalloc( sizeof(struct acolorhist_list_item) );
+  achl = (acolorhist_list) msSmallMalloc( sizeof(struct acolorhist_list_item) );
 
-    hash = pam_hashapixel( *acolorP );
-    achl->ch.acolor = *acolorP;
-    achl->ch.value = value;
-    achl->next = acht[hash];
-    acht[hash] = achl;
-    return 0;
+  hash = pam_hashapixel( *acolorP );
+  achl->ch.acolor = *acolorP;
+  achl->ch.value = value;
+  achl->next = acht[hash];
+  acht[hash] = achl;
+  return 0;
 }
 
 
@@ -705,30 +695,29 @@ pam_acolorhashtoacolorhist( acht, maxacolors )
 acolorhash_table acht;
 int maxacolors;
 {
-    acolorhist_vector achv;
-    acolorhist_list achl;
-    int i, j;
-
-    /* Now collate the hash table into a simple acolorhist array. */
-    achv = (acolorhist_vector) malloc( maxacolors * sizeof(struct acolorhist_item) );
-    /* (Leave room for expansion by caller.) */
-    if ( achv == (acolorhist_vector) 0 ) {
-        fprintf( stderr, "  out of memory generating histogram\n" );
-        exit(9);
+  acolorhist_vector achv;
+  acolorhist_list achl;
+  int i, j;
+
+  /* Now collate the hash table into a simple acolorhist array. */
+  achv = (acolorhist_vector) malloc( maxacolors * sizeof(struct acolorhist_item) );
+  /* (Leave room for expansion by caller.) */
+  if ( achv == (acolorhist_vector) 0 ) {
+    fprintf( stderr, "  out of memory generating histogram\n" );
+    exit(9);
+  }
+
+  /* Loop through the hash table. */
+  j = 0;
+  for ( i = 0; i < HASH_SIZE; ++i )
+    for ( achl = acht[i]; achl != (acolorhist_list) 0; achl = achl->next ) {
+      /* Add the new entry. */
+      achv[j] = achl->ch;
+      ++j;
     }
 
-    /* Loop through the hash table. */
-    j = 0;
-    for ( i = 0; i < HASH_SIZE; ++i )
-        for ( achl = acht[i]; achl != (acolorhist_list) 0; achl = achl->next )
-        {
-            /* Add the new entry. */
-            achv[j] = achl->ch;
-            ++j;
-        }
-
-    /* All done. */
-    return achv;
+  /* All done. */
+  return achv;
 }
 
 
@@ -738,15 +727,15 @@ pam_lookupacolor( acht, acolorP )
 acolorhash_table acht;
 rgbaPixel* acolorP;
 {
-    int hash;
-    acolorhist_list achl;
+  int hash;
+  acolorhist_list achl;
 
-    hash = pam_hashapixel( *acolorP );
-    for ( achl = acht[hash]; achl != (acolorhist_list) 0; achl = achl->next )
-        if ( PAM_EQUAL( achl->ch.acolor, *acolorP ) )
-            return achl->ch.value;
+  hash = pam_hashapixel( *acolorP );
+  for ( achl = acht[hash]; achl != (acolorhist_list) 0; achl = achl->next )
+    if ( PAM_EQUAL( achl->ch.acolor, *acolorP ) )
+      return achl->ch.value;
 
-    return -1;
+  return -1;
 }
 
 
@@ -755,7 +744,7 @@ static void
 pam_freeacolorhist( achv )
 acolorhist_vector achv;
 {
-    free( (char*) achv );
+  free( (char*) achv );
 }
 
 
@@ -764,16 +753,15 @@ static void
 pam_freeacolorhash( acht )
 acolorhash_table acht;
 {
-    int i;
-    acolorhist_list achl, achlnext;
-
-    for ( i = 0; i < HASH_SIZE; ++i )
-        for ( achl = acht[i]; achl != (acolorhist_list) 0; achl = achlnext )
-        {
-            achlnext = achl->next;
-            free( (char*) achl );
-        }
-    free( (char*) acht );
+  int i;
+  acolorhist_list achl, achlnext;
+
+  for ( i = 0; i < HASH_SIZE; ++i )
+    for ( achl = acht[i]; achl != (acolorhist_list) 0; achl = achlnext ) {
+      achlnext = achl->next;
+      free( (char*) achl );
+    }
+  free( (char*) acht );
 }
 
 
diff --git a/mapquery.c b/mapquery.c
index 8676fdc..3679e43 100644
--- a/mapquery.c
+++ b/mapquery.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -29,7 +29,7 @@
 
 #include "mapserver.h"
 
-MS_CVSID("$Id$")
+
 
 int msInitQuery(queryObj *query)
 {
@@ -52,6 +52,9 @@ int msInitQuery(queryObj *query)
   query->shapeindex = query->tileindex = -1;
   query->clear_resultcache = MS_TRUE; /* index queries allow the old results to persist */
 
+  query->maxfeatures = -1;
+  query->startindex = -1;
+  
   query->item = query->str = NULL;
   query->filter = NULL;
 
@@ -87,27 +90,27 @@ int msExecuteQuery(mapObj *map)
   }
 
   switch(map->query.type) {
-  case MS_QUERY_BY_POINT:
-    status = msQueryByPoint(map);
-    break;
-  case MS_QUERY_BY_RECT:
-    status = msQueryByRect(map);
-    break;
-  case MS_QUERY_BY_ATTRIBUTE:
-    status = msQueryByAttributes(map);
-    break;
-  case MS_QUERY_BY_FILTER:
-    status = msQueryByFilter(map);
-    break;
-  case MS_QUERY_BY_SHAPE:
-    status = msQueryByShape(map);
-    break;
-  case MS_QUERY_BY_INDEX:
-    status = msQueryByIndex(map);
-    break;
-  default:
-    msSetError(MS_QUERYERR, "Malformed queryObj.", "msExecuteQuery()");
-    return(MS_FAILURE);
+    case MS_QUERY_BY_POINT:
+      status = msQueryByPoint(map);
+      break;
+    case MS_QUERY_BY_RECT:
+      status = msQueryByRect(map);
+      break;
+    case MS_QUERY_BY_ATTRIBUTE:
+      status = msQueryByAttributes(map);
+      break;
+    case MS_QUERY_BY_FILTER:
+      status = msQueryByFilter(map);
+      break;
+    case MS_QUERY_BY_SHAPE:
+      status = msQueryByShape(map);
+      break;
+    case MS_QUERY_BY_INDEX:
+      status = msQueryByIndex(map);
+      break;
+    default:
+      msSetError(MS_QUERYERR, "Malformed queryObj.", "msExecuteQuery()");
+      return(MS_FAILURE);
   }
 
   if(map->query.slayer >= 0) {
@@ -150,7 +153,7 @@ static int addResult(resultCacheObj *cache, shapeObj *shape)
     if(!cache->results) {
       msSetError(MS_MEMERR, "Realloc() error.", "addResult()");
       return(MS_FAILURE);
-    }   
+    }
     cache->cachesize += MS_RESULTCACHEINCREMENT;
   }
 
@@ -173,7 +176,8 @@ static int addResult(resultCacheObj *cache, shapeObj *shape)
 /*
 ** Serialize a query result set to disk.
 */
-static int saveQueryResults(mapObj *map, char *filename) {
+static int saveQueryResults(mapObj *map, char *filename)
+{
   FILE *stream;
   int i, j, n=0;
 
@@ -202,7 +206,7 @@ static int saveQueryResults(mapObj *map, char *filename) {
       fwrite(&(GET_LAYER(map, i)->resultcache->numresults), sizeof(int), 1, stream); /* number of results */
       fwrite(&(GET_LAYER(map, i)->resultcache->bounds), sizeof(rectObj), 1, stream); /* bounding box */
       for(j=0; j<GET_LAYER(map, i)->resultcache->numresults; j++)
-	fwrite(&(GET_LAYER(map, i)->resultcache->results[j]), sizeof(resultObj), 1, stream); /* each result */
+        fwrite(&(GET_LAYER(map, i)->resultcache->results[j]), sizeof(resultObj), 1, stream); /* each result */
     }
   }
 
@@ -210,19 +214,20 @@ static int saveQueryResults(mapObj *map, char *filename) {
   return MS_SUCCESS;
 }
 
-static int loadQueryResults(mapObj *map, FILE *stream) {
+static int loadQueryResults(mapObj *map, FILE *stream)
+{
   int i, j, k, n=0;
 
   if(1 != fread(&n, sizeof(int), 1, stream)) {
-     msSetError(MS_MISCERR,"failed to read query count from query file stream", "loadQueryResults()");
-    return MS_FAILURE; 
+    msSetError(MS_MISCERR,"failed to read query count from query file stream", "loadQueryResults()");
+    return MS_FAILURE;
   }
 
   /* now load the result set for each layer found in the query file */
   for(i=0; i<n; i++) {
     if(1 != fread(&j, sizeof(int), 1, stream)) { /* layer index */
-       msSetError(MS_MISCERR,"failed to read layer index from query file stream", "loadQueryResults()");
-       return MS_FAILURE; 
+      msSetError(MS_MISCERR,"failed to read layer index from query file stream", "loadQueryResults()");
+      return MS_FAILURE;
     }
 
     if(j<0 || j>map->numlayers) {
@@ -235,37 +240,36 @@ static int loadQueryResults(mapObj *map, FILE *stream) {
     MS_CHECK_ALLOC(GET_LAYER(map, j)->resultcache, sizeof(resultCacheObj), MS_FAILURE);
 
     if(1 != fread(&(GET_LAYER(map, j)->resultcache->numresults), sizeof(int), 1, stream)) { /* number of results */
-       msSetError(MS_MISCERR,"failed to read number of results from query file stream", "loadQueryResults()");
-       free(GET_LAYER(map, j)->resultcache);
-       GET_LAYER(map, j)->resultcache = NULL;
-       return MS_FAILURE; 
+      msSetError(MS_MISCERR,"failed to read number of results from query file stream", "loadQueryResults()");
+      free(GET_LAYER(map, j)->resultcache);
+      GET_LAYER(map, j)->resultcache = NULL;
+      return MS_FAILURE;
     }
     GET_LAYER(map, j)->resultcache->cachesize = GET_LAYER(map, j)->resultcache->numresults;
 
     if(1 != fread(&(GET_LAYER(map, j)->resultcache->bounds), sizeof(rectObj), 1, stream)) { /* bounding box */
-       msSetError(MS_MISCERR,"failed to read bounds from query file stream", "loadQueryResults()");
-       free(GET_LAYER(map, j)->resultcache);
-       GET_LAYER(map, j)->resultcache = NULL;
-       return MS_FAILURE; 
+      msSetError(MS_MISCERR,"failed to read bounds from query file stream", "loadQueryResults()");
+      free(GET_LAYER(map, j)->resultcache);
+      GET_LAYER(map, j)->resultcache = NULL;
+      return MS_FAILURE;
     }
 
     GET_LAYER(map, j)->resultcache->results = (resultObj *) malloc(sizeof(resultObj)*GET_LAYER(map, j)->resultcache->numresults);
-    if (GET_LAYER(map, j)->resultcache->results == NULL) 
-    {
-        msSetError(MS_MEMERR, "%s: %d: Out of memory allocating %u bytes.\n", "loadQueryResults()",
-                   __FILE__, __LINE__, sizeof(resultObj)*GET_LAYER(map, j)->resultcache->numresults);       
-        free(GET_LAYER(map, j)->resultcache);
-        GET_LAYER(map, j)->resultcache = NULL;
-        return MS_FAILURE;
+    if (GET_LAYER(map, j)->resultcache->results == NULL) {
+      msSetError(MS_MEMERR, "%s: %d: Out of memory allocating %u bytes.\n", "loadQueryResults()",
+                 __FILE__, __LINE__, sizeof(resultObj)*GET_LAYER(map, j)->resultcache->numresults);
+      free(GET_LAYER(map, j)->resultcache);
+      GET_LAYER(map, j)->resultcache = NULL;
+      return MS_FAILURE;
     }
 
     for(k=0; k<GET_LAYER(map, j)->resultcache->numresults; k++) {
       if(1 != fread(&(GET_LAYER(map, j)->resultcache->results[k]), sizeof(resultObj), 1, stream)) { /* each result */
-         msSetError(MS_MISCERR,"failed to read result %d from query file stream", "loadQueryResults()", k);
-         free(GET_LAYER(map, j)->resultcache->results);
-         free(GET_LAYER(map, j)->resultcache);
-         GET_LAYER(map, j)->resultcache = NULL;
-         return MS_FAILURE; 
+        msSetError(MS_MISCERR,"failed to read result %d from query file stream", "loadQueryResults()", k);
+        free(GET_LAYER(map, j)->resultcache->results);
+        free(GET_LAYER(map, j)->resultcache);
+        GET_LAYER(map, j)->resultcache = NULL;
+        return MS_FAILURE;
       }
       if(!GET_LAYER(map, j)->tileindex) GET_LAYER(map, j)->resultcache->results[k].tileindex = -1; /* reset the tile index for non-tiled layers */
       GET_LAYER(map, j)->resultcache->results[k].resultindex = -1; /* all results loaded this way have a -1 result (set) index */
@@ -278,7 +282,8 @@ static int loadQueryResults(mapObj *map, FILE *stream) {
 /*
 ** Serialize the parameters necessary to duplicate a query to disk. (TODO: add filter query...)
 */
-static int saveQueryParams(mapObj *map, char *filename) {
+static int saveQueryParams(mapObj *map, char *filename)
+{
   FILE *stream;
 
   if(!filename) {
@@ -321,7 +326,8 @@ static int saveQueryParams(mapObj *map, char *filename) {
   return MS_SUCCESS;
 }
 
-static int loadQueryParams(mapObj *map, FILE *stream) {
+static int loadQueryParams(mapObj *map, FILE *stream)
+{
   char buffer[MS_BUFFER_LENGTH];
   int lineno;
 
@@ -332,58 +338,58 @@ static int loadQueryParams(mapObj *map, FILE *stream) {
   lineno = 2; /* line 1 is the magic string */
   while(fgets(buffer, MS_BUFFER_LENGTH, stream) != NULL) {
     switch(lineno) {
-    case 2:
-      if(sscanf(buffer, "%d %d %d %d\n", &(map->query.mode), &(map->query.type), &(map->query.layer), &(map->query.slayer)) != 4) goto parse_error;
-      break;
-    case 3:
-      if(sscanf(buffer, "%lf %lf %lf %d\n", &map->query.point.x, &map->query.point.y, &map->query.buffer, &map->query.maxresults) != 4) goto parse_error;
-      break;
-    case 4:
-      if(sscanf(buffer, "%lf %lf %lf %lf\n", &map->query.rect.minx, &map->query.rect.miny, &map->query.rect.maxx, &map->query.rect.maxy) != 4) goto parse_error;
-      break;
-    case 5:
-      if(sscanf(buffer, "%ld %ld %d\n", &map->query.shapeindex, &map->query.tileindex, &map->query.clear_resultcache) != 3) goto parse_error;
-      break;
-    case 6:
-      if(strncmp(buffer, "NULL", 4) != 0) {
-        map->query.item = msStrdup(buffer);
-        msStringChop(map->query.item);
-      }
-      break;
-    case 7:
-      if(strncmp(buffer, "NULL", 4) != 0) {
-        map->query.str = msStrdup(buffer);
-        msStringChop(map->query.str);
-      }
-      break;
-    case 8:
-      if(sscanf(buffer, "%d\n", &shapetype) != 1) goto parse_error;
+      case 2:
+        if(sscanf(buffer, "%d %d %d %d\n", &(map->query.mode), &(map->query.type), &(map->query.layer), &(map->query.slayer)) != 4) goto parse_error;
+        break;
+      case 3:
+        if(sscanf(buffer, "%lf %lf %lf %d\n", &map->query.point.x, &map->query.point.y, &map->query.buffer, &map->query.maxresults) != 4) goto parse_error;
+        break;
+      case 4:
+        if(sscanf(buffer, "%lf %lf %lf %lf\n", &map->query.rect.minx, &map->query.rect.miny, &map->query.rect.maxx, &map->query.rect.maxy) != 4) goto parse_error;
+        break;
+      case 5:
+        if(sscanf(buffer, "%ld %ld %d\n", &map->query.shapeindex, &map->query.tileindex, &map->query.clear_resultcache) != 3) goto parse_error;
+        break;
+      case 6:
+        if(strncmp(buffer, "NULL", 4) != 0) {
+          map->query.item = msStrdup(buffer);
+          msStringChop(map->query.item);
+        }
+        break;
+      case 7:
+        if(strncmp(buffer, "NULL", 4) != 0) {
+          map->query.str = msStrdup(buffer);
+          msStringChop(map->query.str);
+        }
+        break;
+      case 8:
+        if(sscanf(buffer, "%d\n", &shapetype) != 1) goto parse_error;
 
-      if(shapetype != MS_SHAPE_NULL) { /* load the rest of the shape */
-        int i, j;
-        lineObj line;
+        if(shapetype != MS_SHAPE_NULL) { /* load the rest of the shape */
+          int i, j;
+          lineObj line;
 
-        map->query.shape = (shapeObj *) msSmallMalloc(sizeof(shapeObj));
-        msInitShape(map->query.shape);
-        map->query.shape->type = shapetype;
+          map->query.shape = (shapeObj *) msSmallMalloc(sizeof(shapeObj));
+          msInitShape(map->query.shape);
+          map->query.shape->type = shapetype;
 
-        if(fscanf(stream, "%d\n", &numlines) != 1) goto parse_error;
-	for(i=0; i<numlines; i++) {
-          if(fscanf(stream, "%d\n", &numpoints) != 1) goto parse_error;
+          if(fscanf(stream, "%d\n", &numlines) != 1) goto parse_error;
+          for(i=0; i<numlines; i++) {
+            if(fscanf(stream, "%d\n", &numpoints) != 1) goto parse_error;
 
-	  line.numpoints = numpoints;
-	  line.point = (pointObj *) msSmallMalloc(line.numpoints*sizeof(pointObj));
+            line.numpoints = numpoints;
+            line.point = (pointObj *) msSmallMalloc(line.numpoints*sizeof(pointObj));
 
-          for(j=0; j<numpoints; j++)
-            if(fscanf(stream, "%lf %lf\n", &line.point[j].x, &line.point[j].y) != 2) goto parse_error;
+            for(j=0; j<numpoints; j++)
+              if(fscanf(stream, "%lf %lf\n", &line.point[j].x, &line.point[j].y) != 2) goto parse_error;
 
-          msAddLine(map->query.shape, &line);
-          free(line.point);
+            msAddLine(map->query.shape, &line);
+            free(line.point);
+          }
         }
-      }
-      break;
-    default:
-      break;
+        break;
+      default:
+        break;
     }
 
     lineno++;
@@ -398,9 +404,9 @@ static int loadQueryParams(mapObj *map, FILE *stream) {
   /* now execute the query */
   return msExecuteQuery(map);
 
-  parse_error:
-    msSetError(MS_MISCERR, "Parse error line %d.", "loadQueryParameters()", lineno);    
-    return MS_FAILURE;
+parse_error:
+  msSetError(MS_MISCERR, "Parse error line %d.", "loadQueryParameters()", lineno);
+  return MS_FAILURE;
 }
 
 /*
@@ -408,7 +414,8 @@ static int loadQueryParams(mapObj *map, FILE *stream) {
 ** all the shape indexes. Note the latter can be very slow against certain data sources but has a certain usefulness
 ** on occation.
 */
-int msSaveQuery(mapObj *map, char *filename, int results) {
+int msSaveQuery(mapObj *map, char *filename, int results)
+{
   if(results)
     return saveQueryResults(map, filename);
   else
@@ -418,7 +425,7 @@ int msSaveQuery(mapObj *map, char *filename, int results) {
 /*
 ** Loads a query file contained either serialized 1) query parameters or 2) query results (e.g. indexes).
 */
-int msLoadQuery(mapObj *map, char *filename) 
+int msLoadQuery(mapObj *map, char *filename)
 {
   FILE *stream;
   char buffer[MS_BUFFER_LENGTH];
@@ -429,10 +436,10 @@ int msLoadQuery(mapObj *map, char *filename)
     return MS_FAILURE;
   }
 
-  /*                                                                                                                                               
-  ** Make sure the file at least has the right extension.                                                         
+  /*
+  ** Make sure the file at least has the right extension.
   */
-  if(msEvalRegex("\\.qy$", filename) != MS_TRUE) { 
+  if(msEvalRegex("\\.qy$", filename) != MS_TRUE) {
     msSetError(MS_MISCERR, "Queryfile %s has incorrect file extension.",  "msLoadQuery()", filename);
     return MS_FAILURE;
   }
@@ -447,7 +454,7 @@ int msLoadQuery(mapObj *map, char *filename)
   }
 
   if(fgets(buffer, MS_BUFFER_LENGTH, stream) != NULL) {
-    /* 
+    /*
     ** Call correct reader based on the magic string.
     */
     if(strncasecmp(buffer, MS_QUERY_RESULTS_MAGIC_STRING, strlen(MS_QUERY_RESULTS_MAGIC_STRING)) == 0) {
@@ -483,14 +490,14 @@ int msQueryByIndex(mapObj *map)
   }
 
   if(map->query.layer < 0 || map->query.layer >= map->numlayers) {
-    msSetError(MS_QUERYERR, "No query layer defined.", "msQueryByIndex()"); 
+    msSetError(MS_QUERYERR, "No query layer defined.", "msQueryByIndex()");
     return(MS_FAILURE);
   }
 
   lp = (GET_LAYER(map, map->query.layer));
 
   if(!msIsLayerQueryable(lp)) {
-    msSetError(MS_QUERYERR, "Requested layer has no templates defined.", "msQueryByIndex()"); 
+    msSetError(MS_QUERYERR, "Requested layer has no templates defined.", "msQueryByIndex()");
     return(MS_FAILURE);
   }
 
@@ -505,6 +512,8 @@ int msQueryByIndex(mapObj *map)
   msLayerClose(lp); /* reset */
   status = msLayerOpen(lp);
   if(status != MS_SUCCESS) return(MS_FAILURE);
+  /* disable driver paging */
+  msLayerEnablePaging(lp, MS_FALSE);
 
   /* build item list, we want *all* items */
   status = msLayerWhichItems(lp, MS_TRUE, NULL);
@@ -518,29 +527,28 @@ int msQueryByIndex(mapObj *map)
 
   msInitShape(&shape);
 
+  record.resultindex = -1;
   record.shapeindex = map->query.shapeindex;
   record.tileindex = map->query.tileindex;
 
   status = msLayerGetShape(lp, &shape, &record);
   if(status != MS_SUCCESS) {
-    msSetError(MS_NOTFOUND, "Not valid record request.", "msQueryByIndex()"); 
+    msSetError(MS_NOTFOUND, "Not valid record request.", "msQueryByIndex()");
     return(MS_FAILURE);
   }
 
   if (lp->minfeaturesize > 0)
-      minfeaturesize = Pix2LayerGeoref(map, lp, lp->minfeaturesize);
+    minfeaturesize = Pix2LayerGeoref(map, lp, lp->minfeaturesize);
 
   /* Check if the shape size is ok to be drawn */
-  if ( (shape.type == MS_SHAPE_LINE || shape.type == MS_SHAPE_POLYGON) && (minfeaturesize > 0) )
-  {
+  if ( (shape.type == MS_SHAPE_LINE || shape.type == MS_SHAPE_POLYGON) && (minfeaturesize > 0) ) {
 
-      if (msShapeCheckSize(&shape, minfeaturesize) == MS_FALSE)
-      {
-          msSetError(MS_NOTFOUND, "Requested shape not valid against layer minfeaturesize.", "msQueryByIndex()");
-          msFreeShape(&shape);
-          msLayerClose(lp);
-          return(MS_FAILURE);
-      }
+    if (msShapeCheckSize(&shape, minfeaturesize) == MS_FALSE) {
+      msSetError(MS_NOTFOUND, "Requested shape not valid against layer minfeaturesize.", "msQueryByIndex()");
+      msFreeShape(&shape);
+      msLayerClose(lp);
+      return(MS_FAILURE);
+    }
   }
 
   shape.classindex = msShapeGetClass(lp, map, &shape, NULL, 0);
@@ -557,7 +565,7 @@ int msQueryByIndex(mapObj *map)
     msLayerClose(lp);
     return(MS_FAILURE);
   }
-
+  
   addResult(lp->resultcache, &shape);
 
   msFreeShape(&shape);
@@ -574,12 +582,12 @@ void msRestoreOldFilter(layerObj *lp, int old_filtertype, char *old_filteritem,
     lp->filteritem = NULL;
     lp->filteritemindex = -1;
   }
-  
+
   /* restore any previously defined filter */
   if(old_filterstring) {
     lp->filter.type = old_filtertype;
     lp->filter.string = old_filterstring;
-    if(old_filteritem) { 
+    if(old_filteritem) {
       lp->filteritem = old_filteritem;
     }
   }
@@ -589,17 +597,18 @@ int msQueryByAttributes(mapObj *map)
 {
   layerObj *lp;
   int status;
-  
+
   int old_filtertype=-1;
   char *old_filterstring=NULL, *old_filteritem=NULL;
 
   rectObj searchrect;
 
   shapeObj shape;
-  
+  int paging;
+
   int nclasses = 0;
   int *classgroup = NULL;
-  double minfeaturesize = -1; 
+  double minfeaturesize = -1;
 
   if(map->query.type != MS_QUERY_BY_ATTRIBUTE) {
     msSetError(MS_QUERYERR, "The query is not properly defined.", "msQueryByAttribute()");
@@ -607,15 +616,19 @@ int msQueryByAttributes(mapObj *map)
   }
 
   if(map->query.layer < 0 || map->query.layer >= map->numlayers) {
-    msSetError(MS_MISCERR, "No query layer defined.", "msQueryByAttributes()"); 
+    msSetError(MS_MISCERR, "No query layer defined.", "msQueryByAttributes()");
     return(MS_FAILURE);
   }
 
   lp = (GET_LAYER(map, map->query.layer));
 
-  /* conditions may have changed since this layer last drawn, so set 
-     layer->project true to recheck projection needs (Bug #673) */ 
-  lp->project = MS_TRUE; 
+  /* using mapscript, the map->query.startindex will be unset... */
+  if (lp->startindex > 1 && map->query.startindex < 0)
+    map->query.startindex = lp->startindex;
+  
+  /* conditions may have changed since this layer last drawn, so set
+     layer->project true to recheck projection needs (Bug #673) */
+  lp->project = MS_TRUE;
 
   /* free any previous search results, do now in case one of the following tests fails */
   if(lp->resultcache) {
@@ -625,12 +638,12 @@ int msQueryByAttributes(mapObj *map)
   }
 
   if(!msIsLayerQueryable(lp)) {
-    msSetError(MS_QUERYERR, "Requested layer has no templates defined so is not queryable.", "msQueryByAttributes()"); 
+    msSetError(MS_QUERYERR, "Requested layer has no templates defined so is not queryable.", "msQueryByAttributes()");
     return(MS_FAILURE);
   }
 
   if(!map->query.str) {
-    msSetError(MS_QUERYERR, "No query expression defined.", "msQueryByAttributes()"); 
+    msSetError(MS_QUERYERR, "No query expression defined.", "msQueryByAttributes()");
     return(MS_FAILURE);
   }
 
@@ -638,12 +651,12 @@ int msQueryByAttributes(mapObj *map)
   if(lp->filter.string) {
     old_filtertype = lp->filter.type;
     old_filterstring = msStrdup(lp->filter.string);
-    if(lp->filteritem) 
+    if(lp->filteritem)
       old_filteritem = msStrdup(lp->filteritem);
   }
 
   /* apply the passed query parameters */
-  if(map->query.item && map->query.item[0] != '\0') 
+  if(map->query.item && map->query.item[0] != '\0')
     lp->filteritem = msStrdup(map->query.item);
   else
     lp->filteritem = NULL;
@@ -651,13 +664,16 @@ int msQueryByAttributes(mapObj *map)
 
   msInitShape(&shape);
 
+  /* Paging could have been disabled before */
+  paging = msLayerGetPaging(lp);
   msLayerClose(lp); /* reset */
   status = msLayerOpen(lp);
   if(status != MS_SUCCESS) {
     msRestoreOldFilter(lp, old_filtertype, old_filteritem, old_filterstring); /* manually reset the filter */
     return(MS_FAILURE);
   }
-  
+  msLayerEnablePaging(lp, paging);
+
   /* build item list, we want *all* items */
   status = msLayerWhichItems(lp, MS_TRUE, NULL);
   if(status != MS_SUCCESS) {
@@ -667,8 +683,8 @@ int msQueryByAttributes(mapObj *map)
 
   /* identify candidate shapes */
   searchrect = map->query.rect;
-#ifdef USE_PROJ  
-  if(lp->project && msProjectionsDiffer(&(lp->projection), &(map->projection)))  
+#ifdef USE_PROJ
+  if(lp->project && msProjectionsDiffer(&(lp->projection), &(map->projection)))
     msProjectRect(&(map->projection), &(lp->projection), &searchrect); /* project the searchrect to source coords */
   else
     lp->project = MS_FALSE;
@@ -689,27 +705,25 @@ int msQueryByAttributes(mapObj *map)
   lp->resultcache = (resultCacheObj *)malloc(sizeof(resultCacheObj)); /* allocate and initialize the result cache */
   MS_CHECK_ALLOC(lp->resultcache, sizeof(resultCacheObj), MS_FAILURE);
   initResultCache( lp->resultcache);
-  
+
   nclasses = 0;
   classgroup = NULL;
   if (lp->classgroup && lp->numclasses > 0)
     classgroup = msAllocateValidClassGroups(lp, &nclasses);
 
   if (lp->minfeaturesize > 0)
-      minfeaturesize = Pix2LayerGeoref(map, lp, lp->minfeaturesize);
+    minfeaturesize = Pix2LayerGeoref(map, lp, lp->minfeaturesize);
 
   while((status = msLayerNextShape(lp, &shape)) == MS_SUCCESS) { /* step through the shapes */
-      
+
     /* Check if the shape size is ok to be drawn */
-    if ( (shape.type == MS_SHAPE_LINE || shape.type == MS_SHAPE_POLYGON) && (minfeaturesize > 0) )
-    {
-        if (msShapeCheckSize(&shape, minfeaturesize) == MS_FALSE)
-        {
-            if( lp->debug >= MS_DEBUGLEVEL_V )
-                msDebug("msQueryByAttributes(): Skipping shape (%d) because LAYER::MINFEATURESIZE is bigger than shape size\n", shape.index);
-            msFreeShape(&shape);
-            continue;
-        }
+    if ( (shape.type == MS_SHAPE_LINE || shape.type == MS_SHAPE_POLYGON) && (minfeaturesize > 0) ) {
+      if (msShapeCheckSize(&shape, minfeaturesize) == MS_FALSE) {
+        if( lp->debug >= MS_DEBUGLEVEL_V )
+          msDebug("msQueryByAttributes(): Skipping shape (%d) because LAYER::MINFEATURESIZE is bigger than shape size\n", shape.index);
+        msFreeShape(&shape);
+        continue;
+      }
     }
 
     shape.classindex = msShapeGetClass(lp, map, &shape, classgroup, nclasses);
@@ -730,14 +744,26 @@ int msQueryByAttributes(mapObj *map)
       lp->project = MS_FALSE;
 #endif
 
+    /* Should we skip this feature? */
+    if (!paging && map->query.startindex > 1) {
+      --map->query.startindex;
+      msFreeShape(&shape);
+      continue;
+    }
+
     addResult(lp->resultcache, &shape);
-    
     msFreeShape(&shape);
 
     if(map->query.mode == MS_QUERY_SINGLE) { /* no need to look any further */
       status = MS_DONE;
       break;
     }
+
+    /* check shape count */
+    if(lp->maxfeatures > 0 && lp->maxfeatures == lp->resultcache->numresults) {
+      status = MS_DONE;
+      break;
+    }
   }
 
   if (classgroup)
@@ -755,7 +781,7 @@ int msQueryByAttributes(mapObj *map)
     return(MS_SUCCESS);
 
   msLayerClose(lp);
-  msSetError(MS_NOTFOUND, "No matching record(s) found.", "msQueryByAttributes()"); 
+  msSetError(MS_NOTFOUND, "No matching record(s) found.", "msQueryByAttributes()");
   return(MS_FAILURE);
 }
 
@@ -770,13 +796,13 @@ int msQueryByFilter(mapObj *map)
   layerObj *lp;
 
   char status;
-  
+
   expressionObj old_filter;
 
   rectObj search_rect;
 
   shapeObj shape;
-  
+
   int nclasses = 0;
   int *classgroup = NULL;
   double minfeaturesize = -1;
@@ -785,11 +811,11 @@ int msQueryByFilter(mapObj *map)
     msSetError(MS_QUERYERR, "The query is not properly defined.", "msQueryByFilter()");
     return(MS_FAILURE);
   }
-  if(!map->query.filter) { // TODO: check filter type too
+  if(!map->query.filter) { /* TODO: check filter type too */
     msSetError(MS_QUERYERR, "Filter is not set.", "msQueryByFilter()");
     return(MS_FAILURE);
   }
-  
+
   msInitShape(&shape);
 
   if(map->query.layer < 0 || map->query.layer >= map->numlayers)
@@ -799,10 +825,18 @@ int msQueryByFilter(mapObj *map)
 
   for(l=start; l>=stop; l--) {
     lp = (GET_LAYER(map, l));
-
-    /* conditions may have changed since this layer last drawn, so set 
-       layer->project true to recheck projection needs (Bug #673) */ 
-    lp->project = MS_TRUE; 
+    if (map->query.maxfeatures == 0)
+      break; /* nothing else to do */
+    else if (map->query.maxfeatures > 0)
+      lp->maxfeatures = map->query.maxfeatures;
+
+    /* using mapscript, the map->query.startindex will be unset... */
+    if (lp->startindex > 1 && map->query.startindex < 0)
+      map->query.startindex = lp->startindex;
+    
+    /* conditions may have changed since this layer last drawn, so set
+       layer->project true to recheck projection needs (Bug #673) */
+    lp->project = MS_TRUE;
 
     /* free any previous search results, do it now in case one of the next few tests fail */
     if(lp->resultcache) {
@@ -834,6 +868,8 @@ int msQueryByFilter(mapObj *map)
     msLayerClose(lp); /* reset */
     status = msLayerOpen(lp);
     if(status != MS_SUCCESS) goto query_error;
+    /* disable driver paging */
+    msLayerEnablePaging(lp, MS_FALSE);
 
     /* build item list, we want *all* items */
     status = msLayerWhichItems(lp, MS_TRUE, NULL);
@@ -869,29 +905,27 @@ int msQueryByFilter(mapObj *map)
 
 
     if (lp->minfeaturesize > 0)
-        minfeaturesize = Pix2LayerGeoref(map, lp, lp->minfeaturesize);
+      minfeaturesize = Pix2LayerGeoref(map, lp, lp->minfeaturesize);
 
     while((status = msLayerNextShape(lp, &shape)) == MS_SUCCESS) { /* step through the shapes */
 
       if(!msLayerSupportsCommonFilters(lp)) { /* we have to apply the filter here instead of within the driver */
-	if(msEvalExpression(lp, &shape, map->query.filter, -1) != MS_TRUE) { /* next shape */
+        if(msEvalExpression(lp, &shape, map->query.filter, -1) != MS_TRUE) { /* next shape */
           msFreeShape(&shape);
-	  continue;
+          continue;
         }
       }
 
       /* Check if the shape size is ok to be drawn */
-      if ( (shape.type == MS_SHAPE_LINE || shape.type == MS_SHAPE_POLYGON) && (minfeaturesize > 0) )
-      {
-          if (msShapeCheckSize(&shape, minfeaturesize) == MS_FALSE)
-          {
-              if( lp->debug >= MS_DEBUGLEVEL_V )
-                  msDebug("msQueryByFilter(): Skipping shape (%d) because LAYER::MINFEATURESIZE is bigger than shape size\n", shape.index);
-              msFreeShape(&shape);
-              continue;
-          }
+      if ( (shape.type == MS_SHAPE_LINE || shape.type == MS_SHAPE_POLYGON) && (minfeaturesize > 0) ) {
+        if (msShapeCheckSize(&shape, minfeaturesize) == MS_FALSE) {
+          if( lp->debug >= MS_DEBUGLEVEL_V )
+            msDebug("msQueryByFilter(): Skipping shape (%d) because LAYER::MINFEATURESIZE is bigger than shape size\n", shape.index);
+          msFreeShape(&shape);
+          continue;
+        }
       }
-      
+
       shape.classindex = msShapeGetClass(lp, map, &shape, classgroup, nclasses);
       if(!(lp->template) && ((shape.classindex == -1) || (lp->class[shape.classindex]->status == MS_OFF))) { /* not a valid shape */
         msFreeShape(&shape);
@@ -910,8 +944,21 @@ int msQueryByFilter(mapObj *map)
         lp->project = MS_FALSE;
 #endif
 
+      /* Should we skip this feature? */
+      if (!msLayerGetPaging(lp) && map->query.startindex > 1) {
+        --map->query.startindex;
+        msFreeShape(&shape);
+        continue;
+      }
+      
       addResult(lp->resultcache, &shape);
       msFreeShape(&shape);
+
+      /* check shape count */
+      if(lp->maxfeatures > 0 && lp->maxfeatures == lp->resultcache->numresults) {
+        status = MS_DONE;
+        break;
+      }
     } /* next shape */
 
     if(classgroup) msFree(classgroup);
@@ -925,22 +972,22 @@ int msQueryByFilter(mapObj *map)
   } /* next layer */
 
   /* was anything found? */
-  for(l=start; l>=stop; l--) {    
+  for(l=start; l>=stop; l--) {
     if(GET_LAYER(map, l)->resultcache && GET_LAYER(map, l)->resultcache->numresults > 0)
       return MS_SUCCESS;
   }
 
-  msSetError(MS_NOTFOUND, "No matching record(s) found.", "msQueryByFilter()"); 
+  msSetError(MS_NOTFOUND, "No matching record(s) found.", "msQueryByFilter()");
   return MS_FAILURE;
 
- query_error:
+query_error:
   msCopyExpression(&lp->filter, &old_filter); /* restore old filter */
   freeExpression(&old_filter);
   msLayerClose(lp);
   return MS_FAILURE;
 }
 
-int msQueryByRect(mapObj *map) 
+int msQueryByRect(mapObj *map)
 {
   int l; /* counters */
   int start, stop=0;
@@ -951,7 +998,8 @@ int msQueryByRect(mapObj *map)
   shapeObj shape, searchshape;
   rectObj searchrect;
   double layer_tolerance = 0, tolerance = 0;
-  
+
+  int paging;
   int nclasses = 0;
   int *classgroup = NULL;
   double minfeaturesize = -1;
@@ -971,10 +1019,19 @@ int msQueryByRect(mapObj *map)
 
   for(l=start; l>=stop; l--) {
     lp = (GET_LAYER(map, l));
-
-    /* conditions may have changed since this layer last drawn, so set 
-       layer->project true to recheck projection needs (Bug #673) */ 
-    lp->project = MS_TRUE; 
+    /* Set the global maxfeatures */
+    if (map->query.maxfeatures == 0)
+      break; /* nothing else to do */
+    else if (map->query.maxfeatures > 0)
+      lp->maxfeatures = map->query.maxfeatures;
+
+    /* using mapscript, the map->query.startindex will be unset... */
+    if (lp->startindex > 1 && map->query.startindex < 0)
+      map->query.startindex = lp->startindex;
+    
+    /* conditions may have changed since this layer last drawn, so set
+       layer->project true to recheck projection needs (Bug #673) */
+    lp->project = MS_TRUE;
 
     /* free any previous search results, do it now in case one of the next few tests fail */
     if(lp->resultcache) {
@@ -998,19 +1055,19 @@ int msQueryByRect(mapObj *map)
 
     searchrect = map->query.rect;
     if(lp->tolerance > 0) {
-        layer_tolerance = lp->tolerance;
-        
-        if(lp->toleranceunits == MS_PIXELS)
-            tolerance = layer_tolerance * msAdjustExtent(&(map->extent), map->width, map->height);
-        else
-            tolerance = layer_tolerance * (msInchesPerUnit(lp->toleranceunits,0)/msInchesPerUnit(map->units,0));
-        
-        searchrect.minx -= tolerance;
-        searchrect.maxx += tolerance;
-        searchrect.miny -= tolerance;
-        searchrect.maxy += tolerance;
+      layer_tolerance = lp->tolerance;
+
+      if(lp->toleranceunits == MS_PIXELS)
+        tolerance = layer_tolerance * msAdjustExtent(&(map->extent), map->width, map->height);
+      else
+        tolerance = layer_tolerance * (msInchesPerUnit(lp->toleranceunits,0)/msInchesPerUnit(map->units,0));
+
+      searchrect.minx -= tolerance;
+      searchrect.maxx += tolerance;
+      searchrect.miny -= tolerance;
+      searchrect.maxy += tolerance;
     }
-    
+
     msRectToPolygon(searchrect, &searchshape);
 
     /* Raster layers are handled specially. */
@@ -1021,9 +1078,12 @@ int msQueryByRect(mapObj *map)
       continue;
     }
 
+    /* Paging could have been disabled before */
+    paging = msLayerGetPaging(lp);
     msLayerClose(lp); /* reset */
     status = msLayerOpen(lp);
     if(status != MS_SUCCESS) return(MS_FAILURE);
+    msLayerEnablePaging(lp, paging);
 
     /* build item list, we want *all* items */
     status = msLayerWhichItems(lp, MS_TRUE, NULL);
@@ -1054,20 +1114,18 @@ int msQueryByRect(mapObj *map)
       classgroup = msAllocateValidClassGroups(lp, &nclasses);
 
     if (lp->minfeaturesize > 0)
-        minfeaturesize = Pix2LayerGeoref(map, lp, lp->minfeaturesize);
-    
+      minfeaturesize = Pix2LayerGeoref(map, lp, lp->minfeaturesize);
+
     while((status = msLayerNextShape(lp, &shape)) == MS_SUCCESS) { /* step through the shapes */
-        
+
       /* Check if the shape size is ok to be drawn */
-      if ( (shape.type == MS_SHAPE_LINE || shape.type == MS_SHAPE_POLYGON) && (minfeaturesize > 0) )
-      {
-          if (msShapeCheckSize(&shape, minfeaturesize) == MS_FALSE)
-          {
-              if( lp->debug >= MS_DEBUGLEVEL_V )
-                  msDebug("msQueryByRect(): Skipping shape (%d) because LAYER::MINFEATURESIZE is bigger than shape size\n", shape.index);
-              msFreeShape(&shape);
-              continue;      
-          }
+      if ( (shape.type == MS_SHAPE_LINE || shape.type == MS_SHAPE_POLYGON) && (minfeaturesize > 0) ) {
+        if (msShapeCheckSize(&shape, minfeaturesize) == MS_FALSE) {
+          if( lp->debug >= MS_DEBUGLEVEL_V )
+            msDebug("msQueryByRect(): Skipping shape (%d) because LAYER::MINFEATURESIZE is bigger than shape size\n", shape.index);
+          msFreeShape(&shape);
+          continue;
+        }
       }
 
       shape.classindex = msShapeGetClass(lp, map, &shape, classgroup, nclasses);
@@ -1083,35 +1141,49 @@ int msQueryByRect(mapObj *map)
 
 #ifdef USE_PROJ
       if(lp->project && msProjectionsDiffer(&(lp->projection), &(map->projection)))
-	msProjectShape(&(lp->projection), &(map->projection), &shape);
+        msProjectShape(&(lp->projection), &(map->projection), &shape);
       else
-	lp->project = MS_FALSE;
+        lp->project = MS_FALSE;
 #endif
 
-      if(msRectContained(&shape.bounds, &searchrect) == MS_TRUE) { /* if the whole shape is in, don't intersect */	
+      if(msRectContained(&shape.bounds, &searchrect) == MS_TRUE) { /* if the whole shape is in, don't intersect */
         status = MS_TRUE;
       } else {
-	switch(shape.type) { /* make sure shape actually intersects the qrect (ADD FUNCTIONS SPECIFIC TO RECTOBJ) */
-	case MS_SHAPE_POINT:
-	  status = msIntersectMultipointPolygon(&shape, &searchshape);
-	  break;
-	case MS_SHAPE_LINE:
-	  status = msIntersectPolylinePolygon(&shape, &searchshape);
-	  break;
-	case MS_SHAPE_POLYGON:
-	  status = msIntersectPolygons(&shape, &searchshape);
-	  break;
-	default:
-	  break;
-	}
-      }	
-
-      if(status == MS_TRUE)
-	addResult(lp->resultcache, &shape);
+        switch(shape.type) { /* make sure shape actually intersects the qrect (ADD FUNCTIONS SPECIFIC TO RECTOBJ) */
+          case MS_SHAPE_POINT:
+            status = msIntersectMultipointPolygon(&shape, &searchshape);
+            break;
+          case MS_SHAPE_LINE:
+            status = msIntersectPolylinePolygon(&shape, &searchshape);
+            break;
+          case MS_SHAPE_POLYGON:
+            status = msIntersectPolygons(&shape, &searchshape);
+            break;
+          default:
+            break;
+        }
+      }
 
+      if(status == MS_TRUE) {
+        /* Should we skip this feature? */
+        if (!paging && map->query.startindex > 1) {
+          --map->query.startindex;
+          msFreeShape(&shape);
+          continue;
+        }
+        addResult(lp->resultcache, &shape);
+        --map->query.maxfeatures;
+      }
       msFreeShape(&shape);
-    } /* next shape */
+
+      /* check shape count */
+      if(lp->maxfeatures > 0 && lp->maxfeatures == lp->resultcache->numresults) {
+        status = MS_DONE;
+        break;
+      }
       
+    } /* next shape */
+
     if (classgroup)
       msFree(classgroup);
 
@@ -1119,23 +1191,24 @@ int msQueryByRect(mapObj *map)
 
     if(lp->resultcache->numresults == 0) msLayerClose(lp); /* no need to keep the layer open */
   } /* next layer */
- 
+
   msFreeShape(&searchshape);
- 
+
   /* was anything found? */
-  for(l=start; l>=stop; l--) {    
+  for(l=start; l>=stop; l--) {
     if(GET_LAYER(map, l)->resultcache && GET_LAYER(map, l)->resultcache->numresults > 0)
       return(MS_SUCCESS);
   }
- 
-  msSetError(MS_NOTFOUND, "No matching record(s) found.", "msQueryByRect()"); 
+
+  msSetError(MS_NOTFOUND, "No matching record(s) found.", "msQueryByRect()");
   return(MS_FAILURE);
 }
 
-static int is_duplicate(resultCacheObj *resultcache, int shapeindex, int tileindex) {
+static int is_duplicate(resultCacheObj *resultcache, int shapeindex, int tileindex)
+{
   int i;
 
-  for(i=0; i<resultcache->numresults; i++)    
+  for(i=0; i<resultcache->numresults; i++)
     if(resultcache->results[i].shapeindex == shapeindex && resultcache->results[i].tileindex == tileindex) return(MS_TRUE);
 
   return(MS_FALSE);
@@ -1169,9 +1242,9 @@ int msQueryByFeatures(mapObj *map)
     return(MS_FAILURE);
   }
 
-  /* conditions may have changed since this layer last drawn, so set 
-     layer->project true to recheck projection needs (Bug #673) */ 
-  slp->project = MS_TRUE; 
+  /* conditions may have changed since this layer last drawn, so set
+     layer->project true to recheck projection needs (Bug #673) */
+  slp->project = MS_TRUE;
 
   if(map->query.layer < 0 || map->query.layer >= map->numlayers)
     start = map->numlayers-1;
@@ -1187,12 +1260,20 @@ int msQueryByFeatures(mapObj *map)
 
   for(l=start; l>=stop; l--) {
     if(l == map->query.slayer) continue; /* skip the selection layer */
-    
+
     lp = (GET_LAYER(map, l));
+    if (map->query.maxfeatures == 0)
+      break; /* nothing else to do */
+    else if (map->query.maxfeatures > 0)
+      lp->maxfeatures = map->query.maxfeatures;
+
+    /* using mapscript, the map->query.startindex will be unset... */
+    if (lp->startindex > 1 && map->query.startindex < 0)
+      map->query.startindex = lp->startindex;
 
-    /* conditions may have changed since this layer last drawn, so set 
-       layer->project true to recheck projection needs (Bug #673) */ 
-    lp->project = MS_TRUE; 
+    /* conditions may have changed since this layer last drawn, so set
+       layer->project true to recheck projection needs (Bug #673) */
+    lp->project = MS_TRUE;
 
     /* free any previous search results, do it now in case one of the next few tests fail */
     if(lp->resultcache) {
@@ -1201,7 +1282,7 @@ int msQueryByFeatures(mapObj *map)
       lp->resultcache = NULL;
     }
 
-    if(!msIsLayerQueryable(lp)) continue;    
+    if(!msIsLayerQueryable(lp)) continue;
     if(lp->status == MS_OFF) continue;
 
     if(map->scaledenom > 0) {
@@ -1218,11 +1299,11 @@ int msQueryByFeatures(mapObj *map)
     if(lp->tolerance == -1) {
       if(lp->type == MS_LAYER_POINT || lp->type == MS_LAYER_LINE)
         layer_tolerance = 3;
-       else
+      else
         layer_tolerance = 0;
     } else
       layer_tolerance = lp->tolerance;
-  
+
     if(lp->toleranceunits == MS_PIXELS)
       tolerance = layer_tolerance * msAdjustExtent(&(map->extent), map->width, map->height);
     else
@@ -1231,34 +1312,35 @@ int msQueryByFeatures(mapObj *map)
     msLayerClose(lp); /* reset */
     status = msLayerOpen(lp);
     if(status != MS_SUCCESS) return(MS_FAILURE);
-    
+    msLayerEnablePaging(lp, MS_FALSE);
+
     /* build item list, we want *all* items */
     status = msLayerWhichItems(lp, MS_TRUE, NULL);
     if(status != MS_SUCCESS) return(MS_FAILURE);
-    
+
     /* for each selection shape */
     for(i=0; i<slp->resultcache->numresults; i++) {
 
       status = msLayerGetShape(slp, &selectshape, &(slp->resultcache->results[i]));
       if(status != MS_SUCCESS) {
-	msLayerClose(lp);
-	msLayerClose(slp);
-	return(MS_FAILURE);
+        msLayerClose(lp);
+        msLayerClose(slp);
+        return(MS_FAILURE);
       }
 
       if(selectshape.type != MS_SHAPE_POLYGON && selectshape.type != MS_SHAPE_LINE) {
-	msLayerClose(lp);
-	msLayerClose(slp);
-	msSetError(MS_QUERYERR, "Selection features MUST be polygons or lines.", "msQueryByFeatures()");
-	return(MS_FAILURE);
+        msLayerClose(lp);
+        msLayerClose(slp);
+        msSetError(MS_QUERYERR, "Selection features MUST be polygons or lines.", "msQueryByFeatures()");
+        return(MS_FAILURE);
       }
-      
+
 #ifdef USE_PROJ
       if(slp->project && msProjectionsDiffer(&(slp->projection), &(map->projection))) {
-	msProjectShape(&(slp->projection), &(map->projection), &selectshape);
-	msComputeBounds(&selectshape); /* recompute the bounding box AFTER projection */
+        msProjectShape(&(slp->projection), &(map->projection), &selectshape);
+        msComputeBounds(&selectshape); /* recompute the bounding box AFTER projection */
       } else
-	slp->project = MS_FALSE;
+        slp->project = MS_FALSE;
 #endif
 
       /* identify target shapes */
@@ -1270,28 +1352,28 @@ int msQueryByFeatures(mapObj *map)
       searchrect.maxy += tolerance;
 
 #ifdef USE_PROJ
-      if(lp->project && msProjectionsDiffer(&(lp->projection), &(map->projection)))      
-	msProjectRect(&(map->projection), &(lp->projection), &searchrect); /* project the searchrect to source coords */
+      if(lp->project && msProjectionsDiffer(&(lp->projection), &(map->projection)))
+        msProjectRect(&(map->projection), &(lp->projection), &searchrect); /* project the searchrect to source coords */
       else
-	lp->project = MS_FALSE;
+        lp->project = MS_FALSE;
 #endif
 
       status = msLayerWhichShapes(lp, searchrect, MS_TRUE);
       if(status == MS_DONE) { /* no overlap */
-	msLayerClose(lp);
-	break; /* next layer */
+        msLayerClose(lp);
+        break; /* next layer */
       } else if(status != MS_SUCCESS) {
-	msLayerClose(lp);
-	msLayerClose(slp);
-	return(MS_FAILURE);
+        msLayerClose(lp);
+        msLayerClose(slp);
+        return(MS_FAILURE);
       }
 
       if(i == 0) {
-	lp->resultcache = (resultCacheObj *)malloc(sizeof(resultCacheObj)); /* allocate and initialize the result cache */
+        lp->resultcache = (resultCacheObj *)malloc(sizeof(resultCacheObj)); /* allocate and initialize the result cache */
         MS_CHECK_ALLOC(lp->resultcache, sizeof(resultCacheObj), MS_FAILURE);
         initResultCache( lp->resultcache);
 
-      }      
+      }
 
       nclasses = 0;
       classgroup = NULL;
@@ -1299,116 +1381,126 @@ int msQueryByFeatures(mapObj *map)
         classgroup = msAllocateValidClassGroups(lp, &nclasses);
 
       if (lp->minfeaturesize > 0)
-          minfeaturesize = Pix2LayerGeoref(map, lp, lp->minfeaturesize);
+        minfeaturesize = Pix2LayerGeoref(map, lp, lp->minfeaturesize);
 
       while((status = msLayerNextShape(lp, &shape)) == MS_SUCCESS) { /* step through the shapes */
-          
-	/* check for dups when there are multiple selection shapes */
-	if(i > 0 && is_duplicate(lp->resultcache, shape.index, shape.tileindex)) continue;
-        
+
+        /* check for dups when there are multiple selection shapes */
+        if(i > 0 && is_duplicate(lp->resultcache, shape.index, shape.tileindex)) continue;
+
 
         /* Check if the shape size is ok to be drawn */
-        if ( (shape.type == MS_SHAPE_LINE || shape.type == MS_SHAPE_POLYGON) && (minfeaturesize > 0) )
-        {
-            if (msShapeCheckSize(&shape, minfeaturesize) == MS_FALSE)
-            {
-                if( lp->debug >= MS_DEBUGLEVEL_V )
-                    msDebug("msQueryByFeature(): Skipping shape (%d) because LAYER::MINFEATURESIZE is bigger than shape size\n", shape.index);
-                msFreeShape(&shape);
-                continue;      
-            }
+        if ( (shape.type == MS_SHAPE_LINE || shape.type == MS_SHAPE_POLYGON) && (minfeaturesize > 0) ) {
+          if (msShapeCheckSize(&shape, minfeaturesize) == MS_FALSE) {
+            if( lp->debug >= MS_DEBUGLEVEL_V )
+              msDebug("msQueryByFeature(): Skipping shape (%d) because LAYER::MINFEATURESIZE is bigger than shape size\n", shape.index);
+            msFreeShape(&shape);
+            continue;
+          }
+        }
+
+        shape.classindex = msShapeGetClass(lp, map, &shape, classgroup, nclasses);
+        if(!(lp->template) && ((shape.classindex == -1) || (lp->class[shape.classindex]->status == MS_OFF))) { /* not a valid shape */
+          msFreeShape(&shape);
+          continue;
+        }
+
+        if(!(lp->template) && !(lp->class[shape.classindex]->template)) { /* no valid template */
+          msFreeShape(&shape);
+          continue;
         }
 
-	shape.classindex = msShapeGetClass(lp, map, &shape, classgroup, nclasses);
-	if(!(lp->template) && ((shape.classindex == -1) || (lp->class[shape.classindex]->status == MS_OFF))) { /* not a valid shape */
-	  msFreeShape(&shape);
-	  continue;
-	}
-
-	if(!(lp->template) && !(lp->class[shape.classindex]->template)) { /* no valid template */
-	  msFreeShape(&shape);
-	  continue;
-	}
-	
 #ifdef USE_PROJ
-	if(lp->project && msProjectionsDiffer(&(lp->projection), &(map->projection)))	
-	  msProjectShape(&(lp->projection), &(map->projection), &shape);
+        if(lp->project && msProjectionsDiffer(&(lp->projection), &(map->projection)))
+          msProjectShape(&(lp->projection), &(map->projection), &shape);
         else
-	  lp->project = MS_FALSE;
+          lp->project = MS_FALSE;
 #endif
- 
-	switch(selectshape.type) { /* may eventually support types other than polygon on line */
-	case MS_SHAPE_POLYGON:	  
-	  switch(shape.type) { /* make sure shape actually intersects the selectshape */
-	  case MS_SHAPE_POINT:
-	    if(tolerance == 0) /* just test for intersection */
-	      status = msIntersectMultipointPolygon(&shape, &selectshape);
-	    else { /* check distance, distance=0 means they intersect */
-	      distance = msDistanceShapeToShape(&selectshape, &shape);
-	      if(distance < tolerance) status = MS_TRUE;
-            }
-	    break;
-	  case MS_SHAPE_LINE:
-	    if(tolerance == 0) { /* just test for intersection */
-	      status = msIntersectPolylinePolygon(&shape, &selectshape);
-	    } else { /* check distance, distance=0 means they intersect */
-	      distance = msDistanceShapeToShape(&selectshape, &shape);
-	      if(distance < tolerance) status = MS_TRUE;
-            }
-	    break;
-	  case MS_SHAPE_POLYGON:
-	    if(tolerance == 0) /* just test for intersection */
-	      status = msIntersectPolygons(&shape, &selectshape);
-	    else { /* check distance, distance=0 means they intersect */
-	      distance = msDistanceShapeToShape(&selectshape, &shape);
-	      if(distance < tolerance) status = MS_TRUE;
-            }
-	    break;
-	  default:
-            status = MS_FALSE;
-	    break;
-	  }
-	  break;
-	case MS_SHAPE_LINE:
-          switch(shape.type) { /* make sure shape actually intersects the selectshape */
-          case MS_SHAPE_POINT:
-            if(tolerance == 0) { /* just test for intersection */
-              distance = msDistanceShapeToShape(&selectshape, &shape);
-              if(distance == 0) status = MS_TRUE;
-            } else {
-	      distance = msDistanceShapeToShape(&selectshape, &shape);
-              if(distance < tolerance) status = MS_TRUE;
+
+        switch(selectshape.type) { /* may eventually support types other than polygon on line */
+          case MS_SHAPE_POLYGON:
+            switch(shape.type) { /* make sure shape actually intersects the selectshape */
+              case MS_SHAPE_POINT:
+                if(tolerance == 0) /* just test for intersection */
+                  status = msIntersectMultipointPolygon(&shape, &selectshape);
+                else { /* check distance, distance=0 means they intersect */
+                  distance = msDistanceShapeToShape(&selectshape, &shape);
+                  if(distance < tolerance) status = MS_TRUE;
+                }
+                break;
+              case MS_SHAPE_LINE:
+                if(tolerance == 0) { /* just test for intersection */
+                  status = msIntersectPolylinePolygon(&shape, &selectshape);
+                } else { /* check distance, distance=0 means they intersect */
+                  distance = msDistanceShapeToShape(&selectshape, &shape);
+                  if(distance < tolerance) status = MS_TRUE;
+                }
+                break;
+              case MS_SHAPE_POLYGON:
+                if(tolerance == 0) /* just test for intersection */
+                  status = msIntersectPolygons(&shape, &selectshape);
+                else { /* check distance, distance=0 means they intersect */
+                  distance = msDistanceShapeToShape(&selectshape, &shape);
+                  if(distance < tolerance) status = MS_TRUE;
+                }
+                break;
+              default:
+                status = MS_FALSE;
+                break;
             }
             break;
           case MS_SHAPE_LINE:
-            if(tolerance == 0) { /* just test for intersection */
-              status = msIntersectPolylines(&shape, &selectshape);
-            } else { /* check distance, distance=0 means they intersect */
-              distance = msDistanceShapeToShape(&selectshape, &shape);
-              if(distance < tolerance) status = MS_TRUE;
-            }
-            break;
-          case MS_SHAPE_POLYGON:
-            if(tolerance == 0) /* just test for intersection */
-              status = msIntersectPolylinePolygon(&selectshape, &shape);
-            else { /* check distance, distance=0 means they intersect */
-              distance = msDistanceShapeToShape(&selectshape, &shape);
-              if(distance < tolerance) status = MS_TRUE;
+            switch(shape.type) { /* make sure shape actually intersects the selectshape */
+              case MS_SHAPE_POINT:
+                if(tolerance == 0) { /* just test for intersection */
+                  distance = msDistanceShapeToShape(&selectshape, &shape);
+                  if(distance == 0) status = MS_TRUE;
+                } else {
+                  distance = msDistanceShapeToShape(&selectshape, &shape);
+                  if(distance < tolerance) status = MS_TRUE;
+                }
+                break;
+              case MS_SHAPE_LINE:
+                if(tolerance == 0) { /* just test for intersection */
+                  status = msIntersectPolylines(&shape, &selectshape);
+                } else { /* check distance, distance=0 means they intersect */
+                  distance = msDistanceShapeToShape(&selectshape, &shape);
+                  if(distance < tolerance) status = MS_TRUE;
+                }
+                break;
+              case MS_SHAPE_POLYGON:
+                if(tolerance == 0) /* just test for intersection */
+                  status = msIntersectPolylinePolygon(&selectshape, &shape);
+                else { /* check distance, distance=0 means they intersect */
+                  distance = msDistanceShapeToShape(&selectshape, &shape);
+                  if(distance < tolerance) status = MS_TRUE;
+                }
+                break;
+              default:
+                status = MS_FALSE;
+                break;
             }
             break;
           default:
-            status = MS_FALSE;
-            break;
-          }
-          break;
-	default:
-	  break; /* should never get here as we test for selection shape type explicitly earlier */
-	}
+            break; /* should never get here as we test for selection shape type explicitly earlier */
+        }
 
-	if(status == MS_TRUE)
-	  addResult(lp->resultcache, &shape);
+        if(status == MS_TRUE) {
+          /* Should we skip this feature? */
+          if (!msLayerGetPaging(lp) && map->query.startindex > 1) {
+            --map->query.startindex;
+            msFreeShape(&shape);
+            continue;
+          }
+          addResult(lp->resultcache, &shape);
+        }
+        msFreeShape(&shape);
 
-	msFreeShape(&shape);
+        /* check shape count */
+        if(lp->maxfeatures > 0 && lp->maxfeatures == lp->resultcache->numresults) {
+          status = MS_DONE;
+          break;
+        }
       } /* next shape */
 
       if (classgroup)
@@ -1423,12 +1515,12 @@ int msQueryByFeatures(mapObj *map)
   } /* next layer */
 
   /* was anything found? */
-  for(l=start; l>=stop; l--) {  
+  for(l=start; l>=stop; l--) {
     if(l == map->query.slayer) continue; /* skip the selection layer */
     if(GET_LAYER(map, l)->resultcache && GET_LAYER(map, l)->resultcache->numresults > 0) return(MS_SUCCESS);
   }
 
-  msSetError(MS_NOTFOUND, "No matching record(s) found.", "msQueryByFeatures()"); 
+  msSetError(MS_NOTFOUND, "No matching record(s) found.", "msQueryByFeatures()");
   return(MS_FAILURE);
 }
 
@@ -1456,6 +1548,7 @@ int msQueryByPoint(mapObj *map)
 
   layerObj *lp;
 
+  int paging;
   char status;
   rectObj rect, searchrect;
   shapeObj shape;
@@ -1476,11 +1569,19 @@ int msQueryByPoint(mapObj *map)
     start = stop = map->query.layer;
 
   for(l=start; l>=stop; l--) {
-      lp = (GET_LAYER(map, l));    
-
-    /* conditions may have changed since this layer last drawn, so set 
-       layer->project true to recheck projection needs (Bug #673) */ 
-    lp->project = MS_TRUE; 
+    lp = (GET_LAYER(map, l));
+    if (map->query.maxfeatures == 0)
+      break; /* nothing else to do */
+    else if (map->query.maxfeatures > 0)
+      lp->maxfeatures = map->query.maxfeatures;
+
+    /* using mapscript, the map->query.startindex will be unset... */
+    if (lp->startindex > 1 && map->query.startindex < 0)
+      map->query.startindex = lp->startindex;
+    
+    /* conditions may have changed since this layer last drawn, so set
+       layer->project true to recheck projection needs (Bug #673) */
+    lp->project = MS_TRUE;
 
     /* free any previous search results, do it now in case one of the next few tests fail */
     if(lp->resultcache) {
@@ -1519,11 +1620,11 @@ int msQueryByPoint(mapObj *map)
       layer_tolerance = lp->tolerance;
 
     if(map->query.buffer <= 0) { /* use layer tolerance */
-      if(lp->toleranceunits == MS_PIXELS)       
-	t = layer_tolerance * MS_MAX(MS_CELLSIZE(map->extent.minx, map->extent.maxx, map->width), 
+      if(lp->toleranceunits == MS_PIXELS)
+        t = layer_tolerance * MS_MAX(MS_CELLSIZE(map->extent.minx, map->extent.maxx, map->width),
                                      MS_CELLSIZE(map->extent.miny, map->extent.maxy, map->height));
       else
-	t = layer_tolerance * (msInchesPerUnit(lp->toleranceunits,0)/msInchesPerUnit(map->units,0));
+        t = layer_tolerance * (msInchesPerUnit(lp->toleranceunits,0)/msInchesPerUnit(map->units,0));
     } else /* use buffer distance */
       t = map->query.buffer;
 
@@ -1532,9 +1633,12 @@ int msQueryByPoint(mapObj *map)
     rect.miny = map->query.point.y - t;
     rect.maxy = map->query.point.y + t;
 
+    /* Paging could have been disabled before */
+    paging = msLayerGetPaging(lp);
     msLayerClose(lp); /* reset */
     status = msLayerOpen(lp);
     if(status != MS_SUCCESS) return(MS_FAILURE);
+    msLayerEnablePaging(lp, paging);
 
     /* build item list, we want *all* items */
     status = msLayerWhichItems(lp, MS_TRUE, NULL);
@@ -1567,57 +1671,69 @@ int msQueryByPoint(mapObj *map)
       classgroup = msAllocateValidClassGroups(lp, &nclasses);
 
     if (lp->minfeaturesize > 0)
-        minfeaturesize = Pix2LayerGeoref(map, lp, lp->minfeaturesize);
+      minfeaturesize = Pix2LayerGeoref(map, lp, lp->minfeaturesize);
 
     while((status = msLayerNextShape(lp, &shape)) == MS_SUCCESS) { /* step through the shapes */
-        
+
       /* Check if the shape size is ok to be drawn */
-      if ( (shape.type == MS_SHAPE_LINE || shape.type == MS_SHAPE_POLYGON) && (minfeaturesize > 0) )
-      {
-          if (msShapeCheckSize(&shape, minfeaturesize) == MS_FALSE)
-          {
-              if( lp->debug >= MS_DEBUGLEVEL_V )
-                  msDebug("msQueryByPoint(): Skipping shape (%d) because LAYER::MINFEATURESIZE is bigger than shape size\n", shape.index);
-              msFreeShape(&shape);
-              continue;      
-          }
+      if ( (shape.type == MS_SHAPE_LINE || shape.type == MS_SHAPE_POLYGON) && (minfeaturesize > 0) ) {
+        if (msShapeCheckSize(&shape, minfeaturesize) == MS_FALSE) {
+          if( lp->debug >= MS_DEBUGLEVEL_V )
+            msDebug("msQueryByPoint(): Skipping shape (%d) because LAYER::MINFEATURESIZE is bigger than shape size\n", shape.index);
+          msFreeShape(&shape);
+          continue;
+        }
       }
-      
+
       shape.classindex = msShapeGetClass(lp, map, &shape, classgroup, nclasses);
       if(!(lp->template) && ((shape.classindex == -1) || (lp->class[shape.classindex]->status == MS_OFF))) { /* not a valid shape */
-	msFreeShape(&shape);
-	continue;
+        msFreeShape(&shape);
+        continue;
       }
 
       if(!(lp->template) && !(lp->class[shape.classindex]->template)) { /* no valid template */
-	msFreeShape(&shape);
-	continue;
+        msFreeShape(&shape);
+        continue;
       }
 
 #ifdef USE_PROJ
       if(lp->project && msProjectionsDiffer(&(lp->projection), &(map->projection)))
-	msProjectShape(&(lp->projection), &(map->projection), &shape);
+        msProjectShape(&(lp->projection), &(map->projection), &shape);
       else
-	lp->project = MS_FALSE;
+        lp->project = MS_FALSE;
 #endif
 
       d = msDistancePointToShape(&(map->query.point), &shape);
       if( d <= t ) { /* found one */
-	if(map->query.mode == MS_QUERY_SINGLE) {
-	  lp->resultcache->numresults = 0;
-	  addResult(lp->resultcache, &shape);	  
-	  t = d; /* next one must be closer */
-	} else {
-	  addResult(lp->resultcache, &shape);
-	}
+
+        /* Should we skip this feature? */
+        if (!paging && map->query.startindex > 1) {
+          --map->query.startindex;
+          msFreeShape(&shape);
+          continue;
+        }
+
+        if(map->query.mode == MS_QUERY_SINGLE) {
+          lp->resultcache->numresults = 0;
+          addResult(lp->resultcache, &shape);
+          t = d; /* next one must be closer */
+        } else {
+          addResult(lp->resultcache, &shape);
+        }
       }
- 
+
       msFreeShape(&shape);
 
       if(map->query.mode == MS_QUERY_MULTIPLE && map->query.maxresults > 0 && lp->resultcache->numresults == map->query.maxresults) {
         status = MS_DONE;   /* got enough results for this layer */
         break;
       }
+
+      /* check shape count */
+      if(lp->maxfeatures > 0 && lp->maxfeatures == lp->resultcache->numresults) {
+        status = MS_DONE;
+        break;
+      }
     } /* next shape */
 
     if (classgroup)
@@ -1627,17 +1743,17 @@ int msQueryByPoint(mapObj *map)
 
     if(lp->resultcache->numresults == 0) msLayerClose(lp); /* no need to keep the layer open */
 
-    if((lp->resultcache->numresults > 0) && (map->query.mode == MS_QUERY_SINGLE) && (map->query.maxresults == 0)) 
+    if((lp->resultcache->numresults > 0) && (map->query.mode == MS_QUERY_SINGLE) && (map->query.maxresults == 0))
       break;   /* no need to search any further */
   } /* next layer */
 
   /* was anything found? */
-  for(l=start; l>=stop; l--) {    
+  for(l=start; l>=stop; l--) {
     if(GET_LAYER(map, l)->resultcache && GET_LAYER(map, l)->resultcache->numresults > 0)
       return(MS_SUCCESS);
   }
- 
-  msSetError(MS_NOTFOUND, "No matching record(s) found.", "msQueryByPoint()"); 
+
+  msSetError(MS_NOTFOUND, "No matching record(s) found.", "msQueryByPoint()");
   return(MS_FAILURE);
 }
 
@@ -1677,13 +1793,21 @@ int msQueryByShape(mapObj *map)
     start = stop = map->query.layer;
 
   msComputeBounds(qshape); /* make sure an accurate extent exists */
- 
+
   for(l=start; l>=stop; l--) { /* each layer */
     lp = (GET_LAYER(map, l));
+    if (map->query.maxfeatures == 0)
+      break; /* nothing else to do */
+    else if (map->query.maxfeatures > 0)
+      lp->maxfeatures = map->query.maxfeatures;
 
-    /* conditions may have changed since this layer last drawn, so set 
-       layer->project true to recheck projection needs (Bug #673) */ 
-    lp->project = MS_TRUE; 
+    /* using mapscript, the map->query.startindex will be unset... */
+    if (lp->startindex > 1 && map->query.startindex < 0)
+      map->query.startindex = lp->startindex;
+
+    /* conditions may have changed since this layer last drawn, so set
+       layer->project true to recheck projection needs (Bug #673) */
+    lp->project = MS_TRUE;
 
     /* free any previous search results, do it now in case one of the next few tests fail */
     if(lp->resultcache) {
@@ -1694,7 +1818,7 @@ int msQueryByShape(mapObj *map)
 
     if(!msIsLayerQueryable(lp)) continue;
     if(lp->status == MS_OFF) continue;
-    
+
     if(map->scaledenom > 0) {
       if((lp->maxscaledenom > 0) && (map->scaledenom > lp->maxscaledenom)) continue;
       if((lp->minscaledenom > 0) && (map->scaledenom <= lp->minscaledenom)) continue;
@@ -1725,10 +1849,12 @@ int msQueryByShape(mapObj *map)
       tolerance = layer_tolerance * msAdjustExtent(&(map->extent), map->width, map->height);
     else
       tolerance = layer_tolerance * (msInchesPerUnit(lp->toleranceunits,0)/msInchesPerUnit(map->units,0));
-   
+
     msLayerClose(lp); /* reset */
     status = msLayerOpen(lp);
     if(status != MS_SUCCESS) return(MS_FAILURE);
+    /* disable driver paging */
+    msLayerEnablePaging(lp, MS_FALSE);
 
     /* build item list, we want *all* items */
     status = msLayerWhichItems(lp, MS_TRUE, NULL);
@@ -1768,117 +1894,127 @@ int msQueryByShape(mapObj *map)
       classgroup = msAllocateValidClassGroups(lp, &nclasses);
 
     if (lp->minfeaturesize > 0)
-        minfeaturesize = Pix2LayerGeoref(map, lp, lp->minfeaturesize);
+      minfeaturesize = Pix2LayerGeoref(map, lp, lp->minfeaturesize);
 
     while((status = msLayerNextShape(lp, &shape)) == MS_SUCCESS) { /* step through the shapes */
 
       /* Check if the shape size is ok to be drawn */
-      if ( (shape.type == MS_SHAPE_LINE || shape.type == MS_SHAPE_POLYGON) && (minfeaturesize > 0) )
-      {
-          if (msShapeCheckSize(&shape, minfeaturesize) == MS_FALSE)
-          {
-              if( lp->debug >= MS_DEBUGLEVEL_V )
-                  msDebug("msQueryByShape(): Skipping shape (%d) because LAYER::MINFEATURESIZE is bigger than shape size\n", shape.index);
-              msFreeShape(&shape);
-              continue;      
-          }
+      if ( (shape.type == MS_SHAPE_LINE || shape.type == MS_SHAPE_POLYGON) && (minfeaturesize > 0) ) {
+        if (msShapeCheckSize(&shape, minfeaturesize) == MS_FALSE) {
+          if( lp->debug >= MS_DEBUGLEVEL_V )
+            msDebug("msQueryByShape(): Skipping shape (%d) because LAYER::MINFEATURESIZE is bigger than shape size\n", shape.index);
+          msFreeShape(&shape);
+          continue;
+        }
       }
 
       shape.classindex = msShapeGetClass(lp, map, &shape, classgroup, nclasses);
       if(!(lp->template) && ((shape.classindex == -1) || (lp->class[shape.classindex]->status == MS_OFF))) { /* not a valid shape */
-	msFreeShape(&shape);
-	continue;
+        msFreeShape(&shape);
+        continue;
       }
 
       if(!(lp->template) && !(lp->class[shape.classindex]->template)) { /* no valid template */
-	msFreeShape(&shape);
-	continue;
+        msFreeShape(&shape);
+        continue;
       }
 
 #ifdef USE_PROJ
       if(lp->project && msProjectionsDiffer(&(lp->projection), &(map->projection)))
-	msProjectShape(&(lp->projection), &(map->projection), &shape);
+        msProjectShape(&(lp->projection), &(map->projection), &shape);
       else
-	lp->project = MS_FALSE;
+        lp->project = MS_FALSE;
 #endif
 
       switch(qshape->type) { /* may eventually support types other than polygon or line */
-      case MS_SHAPE_POLYGON:
-        switch(shape.type) { /* make sure shape actually intersects the shape */
-        case MS_SHAPE_POINT:
-          if(tolerance == 0) /* just test for intersection */
-	     status = msIntersectMultipointPolygon(&shape, qshape);
-	  else { /* check distance, distance=0 means they intersect */
-	    distance = msDistanceShapeToShape(qshape, &shape);
-	    if(distance < tolerance) status = MS_TRUE;
+        case MS_SHAPE_POLYGON:
+          switch(shape.type) { /* make sure shape actually intersects the shape */
+            case MS_SHAPE_POINT:
+              if(tolerance == 0) /* just test for intersection */
+                status = msIntersectMultipointPolygon(&shape, qshape);
+              else { /* check distance, distance=0 means they intersect */
+                distance = msDistanceShapeToShape(qshape, &shape);
+                if(distance < tolerance) status = MS_TRUE;
+              }
+              break;
+            case MS_SHAPE_LINE:
+              if(tolerance == 0) { /* just test for intersection */
+                status = msIntersectPolylinePolygon(&shape, qshape);
+              } else { /* check distance, distance=0 means they intersect */
+                distance = msDistanceShapeToShape(qshape, &shape);
+                if(distance < tolerance) status = MS_TRUE;
+              }
+              break;
+            case MS_SHAPE_POLYGON:
+              if(tolerance == 0) /* just test for intersection */
+                status = msIntersectPolygons(&shape, qshape);
+              else { /* check distance, distance=0 means they intersect */
+                distance = msDistanceShapeToShape(qshape, &shape);
+                if(distance < tolerance) status = MS_TRUE;
+              }
+              break;
+            default:
+              break;
           }
-	  break;
+          break;
         case MS_SHAPE_LINE:
-          if(tolerance == 0) { /* just test for intersection */
-	    status = msIntersectPolylinePolygon(&shape, qshape);
-	  } else { /* check distance, distance=0 means they intersect */
-	    distance = msDistanceShapeToShape(qshape, &shape);
-	    if(distance < tolerance) status = MS_TRUE;
-          }
-	  break;
-        case MS_SHAPE_POLYGON:	
-	  if(tolerance == 0) /* just test for intersection */
-	    status = msIntersectPolygons(&shape, qshape);
-	  else { /* check distance, distance=0 means they intersect */
-	    distance = msDistanceShapeToShape(qshape, &shape);
-	    if(distance < tolerance) status = MS_TRUE;
+          switch(shape.type) { /* make sure shape actually intersects the selectshape */
+            case MS_SHAPE_POINT:
+              if(tolerance == 0) { /* just test for intersection */
+                distance = msDistanceShapeToShape(qshape, &shape);
+                if(distance == 0) status = MS_TRUE;
+              } else {
+                distance = msDistanceShapeToShape(qshape, &shape);
+                if(distance < tolerance) status = MS_TRUE;
+              }
+              break;
+            case MS_SHAPE_LINE:
+              if(tolerance == 0) { /* just test for intersection */
+                status = msIntersectPolylines(&shape, qshape);
+              } else { /* check distance, distance=0 means they intersect */
+                distance = msDistanceShapeToShape(qshape, &shape);
+                if(distance < tolerance) status = MS_TRUE;
+              }
+              break;
+            case MS_SHAPE_POLYGON:
+              if(tolerance == 0) /* just test for intersection */
+                status = msIntersectPolylinePolygon(qshape, &shape);
+              else { /* check distance, distance=0 means they intersect */
+                distance = msDistanceShapeToShape(qshape, &shape);
+                if(distance < tolerance) status = MS_TRUE;
+              }
+              break;
+            default:
+              status = MS_FALSE;
+              break;
           }
           break;
+        case MS_SHAPE_POINT:
+          distance = msDistanceShapeToShape(qshape, &shape);
+          status = MS_FALSE;
+          if(tolerance == 0 && distance == 0) status = MS_TRUE; /* shapes intersect */
+          else if(distance < tolerance) status = MS_TRUE; /* shapes are close enough */
+          break;
         default:
-	  break;
-        }
-        break;
-      case MS_SHAPE_LINE:
-	switch(shape.type) { /* make sure shape actually intersects the selectshape */
-	case MS_SHAPE_POINT:
-	  if(tolerance == 0) { /* just test for intersection */
-	    distance = msDistanceShapeToShape(qshape, &shape);
-	    if(distance == 0) status = MS_TRUE;
-	  } else {
-	    distance = msDistanceShapeToShape(qshape, &shape);
-	    if(distance < tolerance) status = MS_TRUE;
-	  }
-	  break;
-	case MS_SHAPE_LINE:
-	  if(tolerance == 0) { /* just test for intersection */
-	    status = msIntersectPolylines(&shape, qshape);
-	  } else { /* check distance, distance=0 means they intersect */
-	    distance = msDistanceShapeToShape(qshape, &shape);
-	    if(distance < tolerance) status = MS_TRUE;
-	  }
-	  break;
-	case MS_SHAPE_POLYGON:
-	  if(tolerance == 0) /* just test for intersection */
-	    status = msIntersectPolylinePolygon(qshape, &shape);
-	  else { /* check distance, distance=0 means they intersect */
-	    distance = msDistanceShapeToShape(qshape, &shape);
-	    if(distance < tolerance) status = MS_TRUE;
-	  }
-	  break;
-	default:
-	  status = MS_FALSE;
-	  break;
-	}
-	break;
-      case MS_SHAPE_POINT:
-        distance = msDistanceShapeToShape(qshape, &shape);
-        status = MS_FALSE;
-        if(tolerance == 0 && distance == 0) status = MS_TRUE; /* shapes intersect */
-        else if(distance < tolerance) status = MS_TRUE; /* shapes are close enough */
-        break;
-      default:
-	break; /* should never get here as we test for selection shape type explicitly earlier */
+          break; /* should never get here as we test for selection shape type explicitly earlier */
       }
 
-      if(status == MS_TRUE)
-	addResult(lp->resultcache, &shape);
-
+      if(status == MS_TRUE) {
+        /* Should we skip this feature? */
+        if (!msLayerGetPaging(lp) && map->query.startindex > 1) {
+          --map->query.startindex;
+          msFreeShape(&shape);
+          continue;
+        }
+        addResult(lp->resultcache, &shape);
+      }
       msFreeShape(&shape);
+
+      /* check shape count */
+      if(lp->maxfeatures > 0 && lp->maxfeatures == lp->resultcache->numresults) {
+        status = MS_DONE;
+        break;
+      }
     } /* next shape */
 
     if(status != MS_DONE) return(MS_FAILURE);
@@ -1887,12 +2023,12 @@ int msQueryByShape(mapObj *map)
   } /* next layer */
 
   /* was anything found? */
-  for(l=start; l>=stop; l--) {    
+  for(l=start; l>=stop; l--) {
     if(GET_LAYER(map, l)->resultcache && GET_LAYER(map, l)->resultcache->numresults > 0)
       return(MS_SUCCESS);
   }
- 
-  msSetError(MS_NOTFOUND, "No matching record(s) found.", "msQueryByShape()"); 
+
+  msSetError(MS_NOTFOUND, "No matching record(s) found.", "msQueryByShape()");
   return(MS_FAILURE);
 }
 
@@ -1939,7 +2075,7 @@ void msQueryFree(mapObj *map, int qlayer)
   int l; /* counters */
   int start, stop=0;
   layerObj *lp;
-    
+
   if(qlayer < 0 || qlayer >= map->numlayers)
     start = map->numlayers-1;
   else
@@ -1947,9 +2083,9 @@ void msQueryFree(mapObj *map, int qlayer)
 
   for(l=start; l>=stop; l--) {
     lp = (GET_LAYER(map, l));
-        
+
     if(lp->resultcache) {
-      if(lp->resultcache->results) 
+      if(lp->resultcache->results)
         free(lp->resultcache->results);
       free(lp->resultcache);
       lp->resultcache = NULL;
diff --git a/mapraster.c b/mapraster.c
index 2dc31fa..6ba9049 100644
--- a/mapraster.c
+++ b/mapraster.c
@@ -4,7 +4,7 @@
  * Project:  MapServer
  * Purpose:  msDrawRasterLayer(): generic raster layer drawing.
  * Author:   Frank Warmerdam, warmerdam at pobox.com
- *           Pete Olson (LMIC)            
+ *           Pete Olson (LMIC)
  *           Steve Lime
  *
  ******************************************************************************
@@ -17,7 +17,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -35,7 +35,7 @@
 #include "mapresample.h"
 #include "mapthread.h"
 
-MS_CVSID("$Id$")
+
 
 extern int msyylex_destroy(void);
 extern int yyparse(parseObj *);
@@ -51,7 +51,7 @@ extern parseResultObj yypresult; /* result of parsing, true/false */
 #define BUFLEN 1024
 #define HDRLEN 8
 
-#define	CVT(x) ((x) >> 8) /* converts to 8-bit color value */
+#define CVT(x) ((x) >> 8) /* converts to 8-bit color value */
 
 #define NUMGRAYS 16
 
@@ -62,119 +62,123 @@ extern parseResultObj yypresult; /* result of parsing, true/false */
 static int msGetClass_String( layerObj *layer, colorObj *color, const char *pixel_value )
 
 {
-    int i;
-    const char *tmpstr1=NULL;
-    int numitems;
-    char *item_names[4] = { "pixel", "red", "green", "blue" };
-    char *item_values[4];
-    char red_value[8], green_value[8], blue_value[8];
-
-/* -------------------------------------------------------------------- */
-/*      No need to do a lookup in the case of one default class.        */
-/* -------------------------------------------------------------------- */
-    if((layer->numclasses == 1) && !(layer->class[0]->expression.string)) /* no need to do lookup */
-        return(0);
-
-/* -------------------------------------------------------------------- */
-/*      Setup values list for expressions.                              */
-/* -------------------------------------------------------------------- */
-    numitems = 4;
-    sprintf( red_value, "%d", color->red );
-    sprintf( green_value, "%d", color->green );
-    sprintf( blue_value, "%d", color->blue );
-
-    item_values[0] = (char *)pixel_value;
-    item_values[1] = red_value;
-    item_values[2] = green_value;
-    item_values[3] = blue_value;
-        
-/* -------------------------------------------------------------------- */
-/*      Loop over classes till we find a match.                         */
-/* -------------------------------------------------------------------- */
-    for(i=0; i<layer->numclasses; i++) {
-
-        /* Empty expression - always matches */
-        if (layer->class[i]->expression.string == NULL)
-            return(i);
-
-        switch(layer->class[i]->expression.type) {
-
-/* -------------------------------------------------------------------- */
-/*      Simple string match                                             */
-/* -------------------------------------------------------------------- */
-          case(MS_STRING):
-            /* trim junk white space */
-            tmpstr1= pixel_value;
-            while( *tmpstr1 == ' ' )
-                tmpstr1++;
-
-            if(strcmp(layer->class[i]->expression.string, tmpstr1) == 0) return(i); /* matched */
-            break;
-
-/* -------------------------------------------------------------------- */
-/*      Regular expression.  Rarely used for raster.                    */
-/* -------------------------------------------------------------------- */
-          case(MS_REGEX):
-            if(!layer->class[i]->expression.compiled) {
-                if(ms_regcomp(&(layer->class[i]->expression.regex), layer->class[i]->expression.string, MS_REG_EXTENDED|MS_REG_NOSUB) != 0) { /* compile the expression  */
-                    msSetError(MS_REGEXERR, "Invalid regular expression.", "msGetClass()");
-                    return(-1);
-                }
-                layer->class[i]->expression.compiled = MS_TRUE;
-            }
-
-            if(ms_regexec(&(layer->class[i]->expression.regex), pixel_value, 0, NULL, 0) == 0) return(i); /* got a match */
-            break;
-
-/* -------------------------------------------------------------------- */
-/*      Parsed expression.                                              */
-/* -------------------------------------------------------------------- */
-          case(MS_EXPRESSION):
-          {
-              int status;
-              parseObj p;
-              shapeObj dummy_shape;
-              expressionObj *expression = &(layer->class[i]->expression);
- 
-              dummy_shape.numvalues = numitems;
-              dummy_shape.values = item_values;
-
-              if( expression->tokens == NULL )
-                  msTokenizeExpression( expression, item_names, &numitems );
-
-              p.shape = &dummy_shape;
-              p.expr = expression;
-              p.expr->curtoken = p.expr->tokens; /* reset */
-              p.type = MS_PARSE_TYPE_BOOLEAN;
-              
-              status = yyparse(&p);
-              
-              if (status != 0) {
-                  msSetError(MS_PARSEERR, "Failed to parse expression: %s", "msGetClass_FloatRGB", expression->string);
-                  return -1;
-              }
-              
-              if( p.result.intval )
-                  return i;
-              break;
+  int i;
+  const char *tmpstr1=NULL;
+  int numitems;
+  char *item_names[4] = { "pixel", "red", "green", "blue" };
+  char *item_values[4];
+  char red_value[8], green_value[8], blue_value[8];
+
+  /* -------------------------------------------------------------------- */
+  /*      No need to do a lookup in the case of one default class.        */
+  /* -------------------------------------------------------------------- */
+  if((layer->numclasses == 1) && !(layer->class[0]->expression.string)) /* no need to do lookup */
+    return(0);
+
+  /* -------------------------------------------------------------------- */
+  /*      Setup values list for expressions.                              */
+  /* -------------------------------------------------------------------- */
+  numitems = 4;
+  sprintf( red_value, "%d", color->red );
+  sprintf( green_value, "%d", color->green );
+  sprintf( blue_value, "%d", color->blue );
+
+  item_values[0] = (char *)pixel_value;
+  item_values[1] = red_value;
+  item_values[2] = green_value;
+  item_values[3] = blue_value;
+
+  /* -------------------------------------------------------------------- */
+  /*      Loop over classes till we find a match.                         */
+  /* -------------------------------------------------------------------- */
+  for(i=0; i<layer->numclasses; i++) {
+
+    /* check for correct classgroup, if set */
+    if ( layer->class[i]->group && layer->classgroup &&
+         strcasecmp(layer->class[i]->group, layer->classgroup) != 0 )
+      continue;
+
+    /* Empty expression - always matches */
+    if (layer->class[i]->expression.string == NULL)
+      return(i);
+
+    switch(layer->class[i]->expression.type) {
+
+        /* -------------------------------------------------------------------- */
+        /*      Simple string match                                             */
+        /* -------------------------------------------------------------------- */
+      case(MS_STRING):
+        /* trim junk white space */
+        tmpstr1= pixel_value;
+        while( *tmpstr1 == ' ' )
+          tmpstr1++;
+
+        if(strcmp(layer->class[i]->expression.string, tmpstr1) == 0) return(i); /* matched */
+        break;
+
+        /* -------------------------------------------------------------------- */
+        /*      Regular expression.  Rarely used for raster.                    */
+        /* -------------------------------------------------------------------- */
+      case(MS_REGEX):
+        if(!layer->class[i]->expression.compiled) {
+          if(ms_regcomp(&(layer->class[i]->expression.regex), layer->class[i]->expression.string, MS_REG_EXTENDED|MS_REG_NOSUB) != 0) { /* compile the expression  */
+            msSetError(MS_REGEXERR, "Invalid regular expression.", "msGetClass()");
+            return(-1);
           }
+          layer->class[i]->expression.compiled = MS_TRUE;
         }
+
+        if(ms_regexec(&(layer->class[i]->expression.regex), pixel_value, 0, NULL, 0) == 0) return(i); /* got a match */
+        break;
+
+        /* -------------------------------------------------------------------- */
+        /*      Parsed expression.                                              */
+        /* -------------------------------------------------------------------- */
+      case(MS_EXPRESSION): {
+        int status;
+        parseObj p;
+        shapeObj dummy_shape;
+        expressionObj *expression = &(layer->class[i]->expression);
+
+        dummy_shape.numvalues = numitems;
+        dummy_shape.values = item_values;
+
+        if( expression->tokens == NULL )
+          msTokenizeExpression( expression, item_names, &numitems );
+
+        p.shape = &dummy_shape;
+        p.expr = expression;
+        p.expr->curtoken = p.expr->tokens; /* reset */
+        p.type = MS_PARSE_TYPE_BOOLEAN;
+
+        status = yyparse(&p);
+
+        if (status != 0) {
+          msSetError(MS_PARSEERR, "Failed to parse expression: %s", "msGetClass_FloatRGB", expression->string);
+          return -1;
+        }
+
+        if( p.result.intval )
+          return i;
+        break;
+      }
     }
+  }
 
-    return(-1); /* not found */
+  return(-1); /* not found */
 }
 
 /************************************************************************/
 /*                             msGetClass()                             */
 /************************************************************************/
 
-int msGetClass(layerObj *layer, colorObj *color )
+int msGetClass(layerObj *layer, colorObj *color, int colormap_index)
 {
-    char pixel_value[12];
+  char pixel_value[12];
 
-    snprintf( pixel_value, sizeof(pixel_value), "%d", color->pen );
+  snprintf( pixel_value, sizeof(pixel_value), "%d", colormap_index );
 
-    return msGetClass_String( layer, color, pixel_value );
+  return msGetClass_String( layer, color, pixel_value );
 }
 
 /************************************************************************/
@@ -186,18 +190,19 @@ int msGetClass(layerObj *layer, colorObj *color )
 
 int msGetClass_FloatRGB(layerObj *layer, float fValue, int red, int green, int blue )
 {
-    char pixel_value[100];
-    colorObj color;
+  char pixel_value[100];
+  colorObj color;
 
-    color.red = red;
-    color.green = green;
-    color.blue = blue;
+  color.red = red;
+  color.green = green;
+  color.blue = blue;
 
-    snprintf( pixel_value, sizeof(pixel_value), "%18g", fValue );
+  snprintf( pixel_value, sizeof(pixel_value), "%18g", fValue );
 
-    return msGetClass_String( layer, &color, pixel_value );
+  return msGetClass_String( layer, &color, pixel_value );
 }
 
+#ifdef USE_GD
 /************************************************************************/
 /*                            msAddColorGD()                            */
 /*                                                                      */
@@ -209,45 +214,37 @@ int msGetClass_FloatRGB(layerObj *layer, float fValue, int red, int green, int b
 
 int msAddColorGD(mapObj *map, gdImagePtr img, int cmt, int r, int g, int b)
 {
-  int c; 
+  int c;
   int ct = -1;
   int op = -1;
   long rd, gd, bd, dist;
   long mindist = 3*255*255;  /* init to max poss dist */
 
   if( gdImageTrueColor( img ) )
-      return gdTrueColor( r, g, b );
-  
+    return gdTrueColor( r, g, b );
+
   /*
   ** We want to avoid using a color that matches a transparent background
   ** color exactly.  If this is the case, we will permute the value slightly.
   ** When perterbing greyscale images we try to keep them greyscale, otherwise
   ** we just perterb the red component.
   */
-  if( map->outputformat && map->outputformat->transparent 
-      && map->imagecolor.red == r 
-      && map->imagecolor.green == g 
-      && map->imagecolor.blue == b )
-  {
-      if( r == 0 && g == 0 && b == 0 )
-      {
-          r = g = b = 1;
-      }
-      else if( r == g && r == b )
-      {
-          r = g = b = r-1;
-      }
-      else if( r == 0 )
-      {
-          r = 1;
-      }
-      else
-      {
-          r = r-1;
-      }
+  if( map->outputformat && map->outputformat->transparent
+      && map->imagecolor.red == r
+      && map->imagecolor.green == g
+      && map->imagecolor.blue == b ) {
+    if( r == 0 && g == 0 && b == 0 ) {
+      r = g = b = 1;
+    } else if( r == g && r == b ) {
+      r = g = b = r-1;
+    } else if( r == 0 ) {
+      r = 1;
+    } else {
+      r = r-1;
+    }
   }
 
-  /* 
+  /*
   ** Find the nearest color in the color table.  If we get an exact match
   ** return it right away.
   */
@@ -257,34 +254,32 @@ int msAddColorGD(mapObj *map, gdImagePtr img, int cmt, int r, int g, int b)
       op = c; /* Save open slot */
       continue; /* Color not in use */
     }
-    
+
     /* don't try to use the transparent color */
-    if (map->outputformat && map->outputformat->transparent 
+    if (map->outputformat && map->outputformat->transparent
         && img->red  [c] == map->imagecolor.red
         && img->green[c] == map->imagecolor.green
         && img->blue [c] == map->imagecolor.blue )
-        continue;
+      continue;
 
     rd = (long)(img->red  [c] - r);
     gd = (long)(img->green[c] - g);
     bd = (long)(img->blue [c] - b);
-/* -------------------------------------------------------------------- */
-/*      special case for grey colors (r=g=b). we will try to find       */
-/*      either the nearest grey or a color that is almost grey.         */
-/* -------------------------------------------------------------------- */
-    if (r == g && r == b)
-    {
-        if (img->red == img->green && img->red ==  img->blue)
-          dist = rd*rd;
-        else
-          dist = rd * rd + gd * gd + bd * bd;
-    }
-    else
+    /* -------------------------------------------------------------------- */
+    /*      special case for grey colors (r=g=b). we will try to find       */
+    /*      either the nearest grey or a color that is almost grey.         */
+    /* -------------------------------------------------------------------- */
+    if (r == g && r == b) {
+      if (img->red == img->green && img->red ==  img->blue)
+        dist = rd*rd;
+      else
+        dist = rd * rd + gd * gd + bd * bd;
+    } else
       dist = rd * rd + gd * gd + bd * bd;
 
     if (dist < mindist) {
       if (dist == 0) {
-	return c; /* Return exact match color */
+        return c; /* Return exact match color */
       }
       mindist = dist;
       ct = c;
@@ -293,7 +288,7 @@ int msAddColorGD(mapObj *map, gdImagePtr img, int cmt, int r, int g, int b)
 
   /* no exact match, is the closest within our "color match threshold"? */
   if( mindist <= cmt*cmt )
-      return ct;
+    return ct;
 
   /* no exact match.  If there are no open colors we return the closest
      color found.  */
@@ -311,9 +306,11 @@ int msAddColorGD(mapObj *map, gdImagePtr img, int cmt, int r, int g, int b)
   img->blue [op] = b;
   img->open [op] = 0;
 
-  return op; /* Return newly allocated color */  
+  return op; /* Return newly allocated color */
 }
 
+#endif
+
 /************************************************************************/
 /*                        msDrawRasterLayerLow()                        */
 /*                                                                      */
@@ -322,14 +319,14 @@ int msAddColorGD(mapObj *map, gdImagePtr img, int cmt, int r, int g, int b)
 /************************************************************************/
 
 int msDrawRasterLayerLow(mapObj *map, layerObj *layer, imageObj *image,
-                         rasterBufferObj *rb ) 
+                         rasterBufferObj *rb )
 {
-/* -------------------------------------------------------------------- */
-/*      As of MapServer 6.0 GDAL is required for rendering raster       */
-/*      imagery.                                                        */
-/* -------------------------------------------------------------------- */
+  /* -------------------------------------------------------------------- */
+  /*      As of MapServer 6.0 GDAL is required for rendering raster       */
+  /*      imagery.                                                        */
+  /* -------------------------------------------------------------------- */
 #if !defined(USE_GDAL)
-  msSetError(MS_MISCERR, 
+  msSetError(MS_MISCERR,
              "Attempt to render a RASTER (or WMS) layer but without\n"
              "GDAL support enabled.  Raster rendering requires GDAL.",
              "msDrawRasterLayerLow()" );
@@ -352,7 +349,7 @@ int msDrawRasterLayerLow(mapObj *map, layerObj *layer, imageObj *image,
   char tiAbsFilePath[MS_MAXPATHLEN];
   char *tiAbsDirPath = NULL;
   GDALDatasetH  hDS;
-  double	adfGeoTransform[6];
+  double  adfGeoTransform[6];
   const char *close_connection;
 
   msGDALInitialize();
@@ -361,51 +358,51 @@ int msDrawRasterLayerLow(mapObj *map, layerObj *layer, imageObj *image,
     msDebug( "msDrawRasterLayerLow(%s): entering.\n", layer->name );
 
   if(!layer->data && !layer->tileindex) {
-    if(layer->debug == MS_TRUE) 
-        msDebug( "msDrawRasterLayerLow(%s): layer data and tileindex NULL ... doing nothing.", layer->name );
+    if(layer->debug == MS_TRUE)
+      msDebug( "msDrawRasterLayerLow(%s): layer data and tileindex NULL ... doing nothing.", layer->name );
     return(0);
   }
 
   if((layer->status != MS_ON) && (layer->status != MS_DEFAULT)) {
-    if(layer->debug == MS_TRUE) 
-        msDebug( "msDrawRasterLayerLow(%s): not status ON or DEFAULT, doing nothing.", layer->name );
+    if(layer->debug == MS_TRUE)
+      msDebug( "msDrawRasterLayerLow(%s): not status ON or DEFAULT, doing nothing.", layer->name );
     return(0);
   }
 
   if(map->scaledenom > 0) {
     if((layer->maxscaledenom > 0) && (map->scaledenom > layer->maxscaledenom)) {
-      if(layer->debug == MS_TRUE) 
-          msDebug( "msDrawRasterLayerLow(%s): skipping, map scale %.2g > MAXSCALEDENOM=%g\n", 
-                   layer->name, map->scaledenom, layer->maxscaledenom );
+      if(layer->debug == MS_TRUE)
+        msDebug( "msDrawRasterLayerLow(%s): skipping, map scale %.2g > MAXSCALEDENOM=%g\n",
+                 layer->name, map->scaledenom, layer->maxscaledenom );
       return(0);
     }
     if((layer->minscaledenom > 0) && (map->scaledenom <= layer->minscaledenom)) {
-      if(layer->debug == MS_TRUE) 
-          msDebug( "msDrawRasterLayerLow(%s): skipping, map scale %.2g < MINSCALEDENOM=%g\n", 
-                   layer->name, map->scaledenom, layer->minscaledenom );
+      if(layer->debug == MS_TRUE)
+        msDebug( "msDrawRasterLayerLow(%s): skipping, map scale %.2g < MINSCALEDENOM=%g\n",
+                 layer->name, map->scaledenom, layer->minscaledenom );
       return(0);
     }
   }
 
   if(layer->maxscaledenom <= 0 && layer->minscaledenom <= 0) {
     if((layer->maxgeowidth > 0) && ((map->extent.maxx - map->extent.minx) > layer->maxgeowidth)) {
-      if(layer->debug == MS_TRUE) 
-          msDebug( "msDrawRasterLayerLow(%s): skipping, map width %.2g > MAXSCALEDENOM=%g\n", layer->name, 
-                   (map->extent.maxx - map->extent.minx), layer->maxgeowidth );
+      if(layer->debug == MS_TRUE)
+        msDebug( "msDrawRasterLayerLow(%s): skipping, map width %.2g > MAXSCALEDENOM=%g\n", layer->name,
+                 (map->extent.maxx - map->extent.minx), layer->maxgeowidth );
       return(0);
     }
     if((layer->mingeowidth > 0) && ((map->extent.maxx - map->extent.minx) < layer->mingeowidth)) {
-      if(layer->debug == MS_TRUE) 
-          msDebug( "msDrawRasterLayerLow(%s): skipping, map width %.2g < MINSCALEDENOM=%g\n", layer->name, 
-          (map->extent.maxx - map->extent.minx), layer->mingeowidth );
+      if(layer->debug == MS_TRUE)
+        msDebug( "msDrawRasterLayerLow(%s): skipping, map width %.2g < MINSCALEDENOM=%g\n", layer->name,
+                 (map->extent.maxx - map->extent.minx), layer->mingeowidth );
       return(0);
     }
   }
 
   if(layer->tileindex) { /* we have an index file */
-    
+
     msInitShape(&tshp);
-    
+
     tilelayerindex = msGetLayerIndex(layer->map, layer->tileindex);
     if(tilelayerindex == -1) { /* the tileindex references a file, not a layer */
 
@@ -421,50 +418,43 @@ int msDrawRasterLayerLow(mapObj *map, layerObj *layer, imageObj *image,
       tlp->data = msStrdup(layer->tileindex);
       if (layer->filteritem)
         tlp->filteritem = msStrdup(layer->filteritem);
-      if (layer->filter.string)
-      {
-          if (layer->filter.type == MS_EXPRESSION)
-          {
-              pszTmp = 
-                (char *)msSmallMalloc(sizeof(char)*(strlen(layer->filter.string)+3));
-              sprintf(pszTmp,"(%s)",layer->filter.string);
-              msLoadExpressionString(&tlp->filter, pszTmp);
-              free(pszTmp);
-          }
-          else if (layer->filter.type == MS_REGEX || 
-                   layer->filter.type == MS_IREGEX)
-          {
-              pszTmp = 
-                (char *)msSmallMalloc(sizeof(char)*(strlen(layer->filter.string)+3));
-              sprintf(pszTmp,"/%s/",layer->filter.string);
-              msLoadExpressionString(&tlp->filter, pszTmp);
-              free(pszTmp);
-          }
-          else
-            msLoadExpressionString(&tlp->filter, layer->filter.string);
-                   
-          tlp->filter.type = layer->filter.type;
+      if (layer->filter.string) {
+        if (layer->filter.type == MS_EXPRESSION) {
+          pszTmp =
+            (char *)msSmallMalloc(sizeof(char)*(strlen(layer->filter.string)+3));
+          sprintf(pszTmp,"(%s)",layer->filter.string);
+          msLoadExpressionString(&tlp->filter, pszTmp);
+          free(pszTmp);
+        } else if (layer->filter.type == MS_REGEX ||
+                   layer->filter.type == MS_IREGEX) {
+          pszTmp =
+            (char *)msSmallMalloc(sizeof(char)*(strlen(layer->filter.string)+3));
+          sprintf(pszTmp,"/%s/",layer->filter.string);
+          msLoadExpressionString(&tlp->filter, pszTmp);
+          free(pszTmp);
+        } else
+          msLoadExpressionString(&tlp->filter, layer->filter.string);
+
+        tlp->filter.type = layer->filter.type;
       }
 
     } else {
-    	if ( msCheckParentPointer(layer->map,"map")==MS_FAILURE )
-			return MS_FAILURE;
-	tlp = (GET_LAYER(layer->map, tilelayerindex));
+      if ( msCheckParentPointer(layer->map,"map")==MS_FAILURE )
+        return MS_FAILURE;
+      tlp = (GET_LAYER(layer->map, tilelayerindex));
     }
     status = msLayerOpen(tlp);
-    if(status != MS_SUCCESS)
-    {
-        final_status = status;
-        goto cleanup;
+    if(status != MS_SUCCESS) {
+      final_status = status;
+      goto cleanup;
     }
 
     status = msLayerWhichItems(tlp, MS_FALSE, layer->tileitem);
-    if(status != MS_SUCCESS)
-    {
-        final_status = status;
-        goto cleanup;
+    if(status != MS_SUCCESS) {
+      final_status = status;
+      goto cleanup;
     }
- 
+
     /* get the tileitem index */
     for(i=0; i<tlp->numitems; i++) {
       if(strcasecmp(tlp->items[i], layer->tileitem) == 0) {
@@ -473,49 +463,53 @@ int msDrawRasterLayerLow(mapObj *map, layerObj *layer, imageObj *image,
       }
     }
     if(i == tlp->numitems) { /* didn't find it */
-        msSetError(MS_MEMERR, 
-                   "Could not find attribute %s in tileindex.", 
-                   "msDrawRasterLayerLow()", 
-                   layer->tileitem);
-        final_status = MS_FAILURE;
-        goto cleanup;
+      msSetError(MS_MEMERR,
+                 "Could not find attribute %s in tileindex.",
+                 "msDrawRasterLayerLow()",
+                 layer->tileitem);
+      final_status = MS_FAILURE;
+      goto cleanup;
     }
- 
+
     searchrect = map->extent;
 #ifdef USE_PROJ
     /* if necessary, project the searchrect to source coords */
-    if((map->projection.numargs > 0) && (layer->projection.numargs > 0)) msProjectRect(&map->projection, &layer->projection, &searchrect);
+    if((map->projection.numargs > 0) && (layer->projection.numargs > 0)) {
+      if( msProjectRect(&map->projection, &layer->projection, &searchrect)
+          != MS_SUCCESS ) {
+        msDebug( "msDrawRasterLayerLow(%s): unable to reproject map request rectangle into layer projection, canceling.\n", layer->name );
+        final_status = MS_FAILURE;
+        goto cleanup;
+      }
+    }
 #endif
     status = msLayerWhichShapes(tlp, searchrect, MS_FALSE);
     if (status != MS_SUCCESS) {
-        /* Can be either MS_DONE or MS_FAILURE */
-        if (status != MS_DONE) 
-            final_status = status;
+      /* Can be either MS_DONE or MS_FAILURE */
+      if (status != MS_DONE)
+        final_status = status;
 
-        goto cleanup;
+      goto cleanup;
     }
   }
 
   done = MS_FALSE;
-  while(done != MS_TRUE) { 
+  while(done != MS_TRUE) {
     if(layer->tileindex) {
       status = msLayerNextShape(tlp, &tshp);
-      if( status == MS_FAILURE)
-      {
-          final_status = MS_FAILURE;
-          break;
+      if( status == MS_FAILURE) {
+        final_status = MS_FAILURE;
+        break;
       }
 
       if(status == MS_DONE) break; /* no more tiles/images */
-       
-      if(layer->data == NULL || strlen(layer->data) == 0 ) /* assume whole filename is in attribute field */
-      {
-          strlcpy( tilename, tshp.values[tileitemindex], sizeof(tilename));
-      }
-      else
-          snprintf(tilename, sizeof(tilename), "%s/%s", tshp.values[tileitemindex], layer->data);
+
+      if(layer->data == NULL || strlen(layer->data) == 0 ) { /* assume whole filename is in attribute field */
+        strlcpy( tilename, tshp.values[tileitemindex], sizeof(tilename));
+      } else
+        snprintf(tilename, sizeof(tilename), "%s/%s", tshp.values[tileitemindex], layer->data);
       filename = tilename;
-      
+
       msFreeShape(&tshp); /* done with the shape */
     } else {
       filename = layer->data;
@@ -524,84 +518,81 @@ int msDrawRasterLayerLow(mapObj *map, layerObj *layer, imageObj *image,
 
     if(strlen(filename) == 0) continue;
 
-    if(layer->debug == MS_TRUE) 
+    if(layer->debug == MS_TRUE)
       msDebug( "msDrawRasterLayerLow(%s): Filename is: %s\n", layer->name, filename);
 
     /*
     ** If using a tileindex then build the path relative to that file if SHAPEPATH is not set.
     */
-    if(layer->tileindex && !map->shapepath) { 
+    if(layer->tileindex && !map->shapepath) {
       msTryBuildPath(tiAbsFilePath, map->mappath, layer->tileindex); /* absolute path to tileindex file */
       tiAbsDirPath = msGetPath(tiAbsFilePath); /* tileindex file's directory */
-      msBuildPath(szPath, tiAbsDirPath, filename); 
+      msBuildPath(szPath, tiAbsDirPath, filename);
       free(tiAbsDirPath);
     } else {
       msTryBuildPath3(szPath, map->mappath, map->shapepath, filename);
     }
-    if(layer->debug == MS_TRUE) 
+    if(layer->debug == MS_TRUE)
       msDebug("msDrawRasterLayerLow(%s): Path is: %s\n", layer->name, szPath);
 
-    /* 
-    ** Note: because we do decryption after the above path expansion 
+    /*
+    ** Note: because we do decryption after the above path expansion
     ** which depends on actually finding a file, it essentially means that
     ** fancy path manipulation is essentially disabled when using encrypted
     ** components. But that is mostly ok, since stuff like sde,postgres and
-    ** oracle georaster do not use real paths. 
+    ** oracle georaster do not use real paths.
     */
     decrypted_path = msDecryptStringTokens( map, szPath );
     if( decrypted_path == NULL )
-        return MS_FAILURE;
+      return MS_FAILURE;
 
     msAcquireLock( TLOCK_GDAL );
     hDS = GDALOpenShared( decrypted_path, GA_ReadOnly );
 
     /*
-    ** If GDAL doesn't recognise it, and it wasn't successfully opened 
+    ** If GDAL doesn't recognise it, and it wasn't successfully opened
     ** Generate an error.
     */
     if(hDS == NULL) {
-        int ignore_missing = msMapIgnoreMissingData(map);
-        const char *cpl_error_msg = CPLGetLastErrorMsg();
-
-        /* we wish to avoid reporting decrypted paths */
-        if( cpl_error_msg != NULL 
-            && strstr(cpl_error_msg,decrypted_path) != NULL
-            && strcmp(decrypted_path,szPath) != 0 )
-            cpl_error_msg = NULL;
-
-        /* we wish to avoid reporting the stock GDALOpen error messages */
-        if( cpl_error_msg != NULL
-            && (strstr(cpl_error_msg,"not recognised as a supported") != NULL
-                || strstr(cpl_error_msg,"does not exist") != NULL) )
-            cpl_error_msg = NULL;
-
-        if( cpl_error_msg == NULL )
-            cpl_error_msg = "";
-
-        msFree( decrypted_path );
-        decrypted_path = NULL;
-
-        msReleaseLock( TLOCK_GDAL );
-
-        if(ignore_missing == MS_MISSING_DATA_FAIL) {
-          msSetError(MS_IOERR, "Corrupt, empty or missing file '%s' for layer '%s'. %s", "msDrawRasterLayerLow()", szPath, layer->name, cpl_error_msg );
-          return(MS_FAILURE); 
-        }
-        else if( ignore_missing == MS_MISSING_DATA_LOG ) {
-          if( layer->debug || layer->map->debug ) {
-            msDebug( "Corrupt, empty or missing file '%s' for layer '%s' ... ignoring this missing data.  %s\n", szPath, layer->name, cpl_error_msg );
-          }
-          continue;
+      int ignore_missing = msMapIgnoreMissingData(map);
+      const char *cpl_error_msg = CPLGetLastErrorMsg();
+
+      /* we wish to avoid reporting decrypted paths */
+      if( cpl_error_msg != NULL
+          && strstr(cpl_error_msg,decrypted_path) != NULL
+          && strcmp(decrypted_path,szPath) != 0 )
+        cpl_error_msg = NULL;
+
+      /* we wish to avoid reporting the stock GDALOpen error messages */
+      if( cpl_error_msg != NULL
+          && (strstr(cpl_error_msg,"not recognised as a supported") != NULL
+              || strstr(cpl_error_msg,"does not exist") != NULL) )
+        cpl_error_msg = NULL;
+
+      if( cpl_error_msg == NULL )
+        cpl_error_msg = "";
+
+      msFree( decrypted_path );
+      decrypted_path = NULL;
+
+      msReleaseLock( TLOCK_GDAL );
+
+      if(ignore_missing == MS_MISSING_DATA_FAIL) {
+        msSetError(MS_IOERR, "Corrupt, empty or missing file '%s' for layer '%s'. %s", "msDrawRasterLayerLow()", szPath, layer->name, cpl_error_msg );
+        return(MS_FAILURE);
+      } else if( ignore_missing == MS_MISSING_DATA_LOG ) {
+        if( layer->debug || layer->map->debug ) {
+          msDebug( "Corrupt, empty or missing file '%s' for layer '%s' ... ignoring this missing data.  %s\n", szPath, layer->name, cpl_error_msg );
         }
-        else if( ignore_missing == MS_MISSING_DATA_IGNORE ) {
-          continue;
-        }
-        else {
-          /* never get here */
-          msSetError(MS_IOERR, "msIgnoreMissingData returned unexpected value.", "msDrawRasterLayerLow()");
-          return(MS_FAILURE);
-        }
-    }        
+        continue;
+      } else if( ignore_missing == MS_MISSING_DATA_IGNORE ) {
+        continue;
+      } else {
+        /* never get here */
+        msSetError(MS_IOERR, "msIgnoreMissingData returned unexpected value.", "msDrawRasterLayerLow()");
+        return(MS_FAILURE);
+      }
+    }
 
     msFree( decrypted_path );
     decrypted_path = NULL;
@@ -609,41 +600,38 @@ int msDrawRasterLayerLow(mapObj *map, layerObj *layer, imageObj *image,
     /*
     ** Generate the projection information if using AUTO.
     */
-    if (layer->projection.numargs > 0 && 
-        EQUAL(layer->projection.args[0], "auto"))
-    {
-        const char *pszWKT;
-        
-        pszWKT = GDALGetProjectionRef( hDS );
-        
-        if( pszWKT != NULL && strlen(pszWKT) > 0 )
-        {
-            if( msOGCWKT2ProjectionObj(pszWKT, &(layer->projection),
-                                       layer->debug ) != MS_SUCCESS )
-            {
-                char	szLongMsg[MESSAGELENGTH*2];
-                errorObj *ms_error = msGetErrorObj();
-                
-                snprintf( szLongMsg, sizeof(szLongMsg),
-                         "%s\n"
-                         "PROJECTION AUTO cannot be used for this "
-                         "GDAL raster (`%s').",
-                         ms_error->message, filename);
-                szLongMsg[MESSAGELENGTH-1] = '\0';
-                
-                msSetError(MS_OGRERR, "%s","msDrawRasterLayer()",
-                           szLongMsg);
-                
-                msReleaseLock( TLOCK_GDAL );
-                final_status = MS_FAILURE;
-                break;
-            }
+    if (layer->projection.numargs > 0 &&
+        EQUAL(layer->projection.args[0], "auto")) {
+      const char *pszWKT;
+
+      pszWKT = GDALGetProjectionRef( hDS );
+
+      if( pszWKT != NULL && strlen(pszWKT) > 0 ) {
+        if( msOGCWKT2ProjectionObj(pszWKT, &(layer->projection),
+                                   layer->debug ) != MS_SUCCESS ) {
+          char  szLongMsg[MESSAGELENGTH*2];
+          errorObj *ms_error = msGetErrorObj();
+
+          snprintf( szLongMsg, sizeof(szLongMsg),
+                    "%s\n"
+                    "PROJECTION AUTO cannot be used for this "
+                    "GDAL raster (`%s').",
+                    ms_error->message, filename);
+          szLongMsg[MESSAGELENGTH-1] = '\0';
+
+          msSetError(MS_OGRERR, "%s","msDrawRasterLayer()",
+                     szLongMsg);
+
+          msReleaseLock( TLOCK_GDAL );
+          final_status = MS_FAILURE;
+          break;
         }
+      }
     }
 
     msGetGDALGeoTransform( hDS, map, layer, adfGeoTransform );
 
-    /* 
+    /*
     ** We want to resample if the source image is rotated, if
     ** the projections differ or if resampling has been explicitly
     ** requested, or if the image has north-down instead of north-up.
@@ -652,56 +640,49 @@ int msDrawRasterLayerLow(mapObj *map, layerObj *layer, imageObj *image,
     if( ((adfGeoTransform[2] != 0.0 || adfGeoTransform[4] != 0.0
           || adfGeoTransform[5] > 0.0 || adfGeoTransform[1] < 0.0 )
          && layer->transform )
-        || msProjectionsDiffer( &(map->projection), 
-                                &(layer->projection) ) 
-        || CSLFetchNameValue( layer->processing, "RESAMPLE" ) != NULL )
-    {
-        status = msResampleGDALToMap( map, layer, image, rb, hDS );
-    }
-    else
+        || msProjectionsDiffer( &(map->projection),
+                                &(layer->projection) )
+        || CSLFetchNameValue( layer->processing, "RESAMPLE" ) != NULL ) {
+      status = msResampleGDALToMap( map, layer, image, rb, hDS );
+    } else
 #endif
     {
-        if( adfGeoTransform[2] != 0.0 || adfGeoTransform[4] != 0.0 )
-        {
-            if( layer->debug || map->debug )
-                msDebug( 
-                    "Layer %s has rotational coefficients but we\n"
-                    "are unable to use them, projections support\n"
-                    "needs to be built in.", 
-                    layer->name );
-            
-        }
-        status = msDrawRasterLayerGDAL(map, layer, image, rb, hDS );
+      if( adfGeoTransform[2] != 0.0 || adfGeoTransform[4] != 0.0 ) {
+        if( layer->debug || map->debug )
+          msDebug(
+            "Layer %s has rotational coefficients but we\n"
+            "are unable to use them, projections support\n"
+            "needs to be built in.",
+            layer->name );
+
+      }
+      status = msDrawRasterLayerGDAL(map, layer, image, rb, hDS );
     }
 
-    if( status == -1 )
-    {
-        GDALClose( hDS );
-        msReleaseLock( TLOCK_GDAL );
-        final_status = MS_FAILURE;
-        break;
+    if( status == -1 ) {
+      GDALClose( hDS );
+      msReleaseLock( TLOCK_GDAL );
+      final_status = MS_FAILURE;
+      break;
     }
 
     /*
-    ** Should we keep this file open for future use?  
-    ** default to keeping open for single data files, and 
+    ** Should we keep this file open for future use?
+    ** default to keeping open for single data files, and
     ** to closing for tile indexes
     */
 
-    close_connection = msLayerGetProcessingKey( layer, 
-                                                "CLOSE_CONNECTION" );
-            
+    close_connection = msLayerGetProcessingKey( layer,
+                       "CLOSE_CONNECTION" );
+
     if( close_connection == NULL && layer->tileindex == NULL )
-        close_connection = "DEFER";
-    
+      close_connection = "DEFER";
+
     if( close_connection != NULL
-        && strcasecmp(close_connection,"DEFER") == 0 )
-    {
-        GDALDereferenceDataset( hDS );
-    }
-    else
-    {
-        GDALClose( hDS );
+        && strcasecmp(close_connection,"DEFER") == 0 ) {
+      GDALDereferenceDataset( hDS );
+    } else {
+      GDALClose( hDS );
     }
     msReleaseLock( TLOCK_GDAL );
   } /* next tile */
@@ -724,7 +705,8 @@ cleanup:
 /*                         msDrawReferenceMap()                         */
 /************************************************************************/
 
-imageObj *msDrawReferenceMap(mapObj *map) {
+imageObj *msDrawReferenceMap(mapObj *map)
+{
   double cellsize;
   int x1,y1,x2,y2;
   char szPath[MS_MAXPATHLEN];
@@ -738,143 +720,133 @@ imageObj *msDrawReferenceMap(mapObj *map) {
   MS_CHECK_ALLOC(refImage, sizeof(rasterBufferObj), NULL);
 
   if(MS_SUCCESS != renderer->loadImageFromFile(msBuildPath(szPath, map->mappath, map->reference.image),refImage)) {
-	  msSetError(MS_MISCERR,"error loading reference image %s","msDrawREferenceMap()",szPath);
-	  return NULL;
+    msSetError(MS_MISCERR,"error loading reference image %s","msDrawREferenceMap()",szPath);
+    return NULL;
   }
 
   image = msImageCreate(refImage->width, refImage->height, map->outputformat,
-          map->web.imagepath, map->web.imageurl, map->resolution, map->defresolution, &(map->reference.color));
+                        map->web.imagepath, map->web.imageurl, map->resolution, map->defresolution, &(map->reference.color));
 
   renderer->mergeRasterBuffer(image,refImage,1.0,0,0,0,0,refImage->width, refImage->height);
-  
+
   msFreeRasterBuffer(refImage);
   free(refImage);
 
   /* make sure the extent given in mapfile fits the image */
-  cellsize = msAdjustExtent(&(map->reference.extent), 
+  cellsize = msAdjustExtent(&(map->reference.extent),
                             image->width, image->height);
 
   /* convert map extent to reference image coordinates */
   x1 = MS_MAP2IMAGE_X(map->extent.minx,  map->reference.extent.minx, cellsize);
-  x2 = MS_MAP2IMAGE_X(map->extent.maxx,  map->reference.extent.minx, cellsize);  
+  x2 = MS_MAP2IMAGE_X(map->extent.maxx,  map->reference.extent.minx, cellsize);
   y1 = MS_MAP2IMAGE_Y(map->extent.maxy,  map->reference.extent.maxy, cellsize);
   y2 = MS_MAP2IMAGE_Y(map->extent.miny,  map->reference.extent.maxy, cellsize);
-  
+
   initStyle(&style);
   style.color = map->reference.color;
   style.outlinecolor = map->reference.outlinecolor;
-  
+
   /* if extent are smaller than minbox size */
   /* draw that extent on the reference image */
-  if( (abs(x2 - x1) > map->reference.minboxsize) || 
-          (abs(y2 - y1) > map->reference.minboxsize) )
-  {
-      shapeObj rect;
-      lineObj line;
-      pointObj points[5];
-      msInitShape(&rect);
-
-      line.point = points;
-      line.numpoints = 5;
-      rect.line = &line;
-      rect.numlines = 1;
-      rect.type = MS_SHAPE_POLYGON;
-  
-      line.point[0].x = x1;
-      line.point[0].y = y1;
-      line.point[1].x = x1;
-      line.point[1].y = y2;
-      line.point[2].x = x2;
-      line.point[2].y = y2;
-      line.point[3].x = x2;
-      line.point[3].y = y1;
-      line.point[4].x = line.point[0].x;
-      line.point[4].y = line.point[0].y;
-  
-      line.numpoints = 5;
-
-      if( map->reference.maxboxsize == 0 || 
-              ((abs(x2 - x1) < map->reference.maxboxsize) && 
-                  (abs(y2 - y1) < map->reference.maxboxsize)) )
-      {
-          msDrawShadeSymbol(&(map->symbolset), image, &rect, &style, 1.0); 
-      }
-  
-  }
-  else /* else draw the marker symbol */
-  {
-      if( map->reference.maxboxsize == 0 || 
-              ((abs(x2 - x1) < map->reference.maxboxsize) && 
-                  (abs(y2 - y1) < map->reference.maxboxsize)) )
-      {
-          style.size = map->reference.markersize;
-
-          /* if the marker symbol is specify draw this symbol else draw a cross */
-          if(map->reference.marker != 0)
-          {
-              pointObj *point = NULL;
-
-              point = msSmallMalloc(sizeof(pointObj));
-              point->x = (double)(x1 + x2)/2;
-              point->y = (double)(y1 + y2)/2;
-              
-              style.symbol = map->reference.marker;
-
-              msDrawMarkerSymbol(&map->symbolset, image, point, &style, 1.0);
-              free(point);
-          }
-          else if(map->reference.markername != NULL)
-          {              
-              pointObj *point = NULL;
-
-              point = msSmallMalloc(sizeof(pointObj));
-              point->x = (double)(x1 + x2)/2;
-              point->y = (double)(y1 + y2)/2;
-              
-              style.symbol = msGetSymbolIndex(&map->symbolset,  map->reference.markername, MS_TRUE);
-
-              msDrawMarkerSymbol(&map->symbolset, image, point, &style, 1.0);
-              free(point);
-          }
-          else
-          {
-              int x21, y21;
-              shapeObj cross;
-              lineObj lines[4];
-              pointObj point[8];
-              int i;
-              /* determine the center point */
-              x21 = MS_NINT((x1 + x2)/2);
-              y21 = MS_NINT((y1 + y2)/2);
-
-              msInitShape(&cross);
-              cross.numlines = 4;
-              cross.line = lines;
-              for(i=0;i<4;i++) {
-                cross.line[i].numpoints = 2;
-                cross.line[i].point = &(point[2*i]);
-              }
-              /* draw a cross */
-              cross.line[0].point[0].x = x21-8;
-              cross.line[0].point[0].y = y21;
-              cross.line[0].point[1].x = x21-3;
-              cross.line[0].point[1].y = y21;
-              cross.line[1].point[0].x = x21;
-              cross.line[1].point[0].y = y21-8;
-              cross.line[1].point[1].x = x21;
-              cross.line[1].point[1].y = y21-3;
-              cross.line[2].point[0].x = x21;
-              cross.line[2].point[0].y = y21+3;
-              cross.line[2].point[1].x = x21;
-              cross.line[2].point[1].y = y21+8;
-              cross.line[3].point[0].x = x21+3;
-              cross.line[3].point[0].y = y21;
-              cross.line[3].point[1].x = x21+8;
-              cross.line[3].point[1].y = y21;
-              
-              msDrawLineSymbol(&(map->symbolset),image,&cross,&style,1.0);
-          }
+  if( (abs(x2 - x1) > map->reference.minboxsize) ||
+      (abs(y2 - y1) > map->reference.minboxsize) ) {
+    shapeObj rect;
+    lineObj line;
+    pointObj points[5];
+    msInitShape(&rect);
+
+    line.point = points;
+    line.numpoints = 5;
+    rect.line = &line;
+    rect.numlines = 1;
+    rect.type = MS_SHAPE_POLYGON;
+
+    line.point[0].x = x1;
+    line.point[0].y = y1;
+    line.point[1].x = x1;
+    line.point[1].y = y2;
+    line.point[2].x = x2;
+    line.point[2].y = y2;
+    line.point[3].x = x2;
+    line.point[3].y = y1;
+    line.point[4].x = line.point[0].x;
+    line.point[4].y = line.point[0].y;
+
+    line.numpoints = 5;
+
+    if( map->reference.maxboxsize == 0 ||
+        ((abs(x2 - x1) < map->reference.maxboxsize) &&
+         (abs(y2 - y1) < map->reference.maxboxsize)) ) {
+      msDrawShadeSymbol(&(map->symbolset), image, &rect, &style, 1.0);
+    }
+
+  } else { /* else draw the marker symbol */
+    if( map->reference.maxboxsize == 0 ||
+        ((abs(x2 - x1) < map->reference.maxboxsize) &&
+         (abs(y2 - y1) < map->reference.maxboxsize)) ) {
+      style.size = map->reference.markersize;
+
+      /* if the marker symbol is specify draw this symbol else draw a cross */
+      if(map->reference.marker != 0) {
+        pointObj *point = NULL;
+
+        point = msSmallMalloc(sizeof(pointObj));
+        point->x = (double)(x1 + x2)/2;
+        point->y = (double)(y1 + y2)/2;
+
+        style.symbol = map->reference.marker;
+
+        msDrawMarkerSymbol(&map->symbolset, image, point, &style, 1.0);
+        free(point);
+      } else if(map->reference.markername != NULL) {
+        pointObj *point = NULL;
+
+        point = msSmallMalloc(sizeof(pointObj));
+        point->x = (double)(x1 + x2)/2;
+        point->y = (double)(y1 + y2)/2;
+
+        style.symbol = msGetSymbolIndex(&map->symbolset,  map->reference.markername, MS_TRUE);
+
+        msDrawMarkerSymbol(&map->symbolset, image, point, &style, 1.0);
+        free(point);
+      } else {
+        int x21, y21;
+        shapeObj cross;
+        lineObj lines[4];
+        pointObj point[8];
+        int i;
+        /* determine the center point */
+        x21 = MS_NINT((x1 + x2)/2);
+        y21 = MS_NINT((y1 + y2)/2);
+
+        msInitShape(&cross);
+        cross.numlines = 4;
+        cross.line = lines;
+        for(i=0; i<4; i++) {
+          cross.line[i].numpoints = 2;
+          cross.line[i].point = &(point[2*i]);
+        }
+        /* draw a cross */
+        cross.line[0].point[0].x = x21-8;
+        cross.line[0].point[0].y = y21;
+        cross.line[0].point[1].x = x21-3;
+        cross.line[0].point[1].y = y21;
+        cross.line[1].point[0].x = x21;
+        cross.line[1].point[0].y = y21-8;
+        cross.line[1].point[1].x = x21;
+        cross.line[1].point[1].y = y21-3;
+        cross.line[2].point[0].x = x21;
+        cross.line[2].point[0].y = y21+3;
+        cross.line[2].point[1].x = x21;
+        cross.line[2].point[1].y = y21+8;
+        cross.line[3].point[0].x = x21+3;
+        cross.line[3].point[0].y = y21;
+        cross.line[3].point[1].x = x21+8;
+        cross.line[3].point[1].y = y21;
+
+        msDrawLineSymbol(&(map->symbolset),image,&cross,&style,1.0);
       }
+    }
   }
 
   return(image);
diff --git a/maprasterquery.c b/maprasterquery.c
index 0b6a0cb..0e4a7a7 100644
--- a/maprasterquery.c
+++ b/maprasterquery.c
@@ -2,7 +2,7 @@
  * $Id$
  *
  * Project:  MapServer
- * Purpose:  Implementation of query operations on rasters. 
+ * Purpose:  Implementation of query operations on rasters.
  * Author:   Frank Warmerdam, warmerdam at pobox.com
  *
  ******************************************************************************
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -32,7 +32,7 @@
 #include "mapresample.h"
 #include "mapthread.h"
 
-MS_CVSID("$Id$");
+
 
 int msRASTERLayerGetShape(layerObj *layer, shapeObj *shape, resultObj *record);
 int msRASTERLayerGetItems(layerObj *layer);
@@ -45,40 +45,42 @@ int msRASTERLayerGetItems(layerObj *layer);
 /* ==================================================================== */
 typedef struct {
 
-    /* query cache results */
-    int query_results;
-    int query_alloc_max;
-    int query_request_max;
-    int query_result_hard_max;
-    int raster_query_mode;
-    int band_count;
+  /* query cache results */
+  int query_results;
+  int query_alloc_max;
+  int query_request_max;
+  int query_result_hard_max;
+  int raster_query_mode;
+  int band_count;
 
-    int refcount;
+  int refcount;
 
-    rectObj which_rect;
-    int     next_shape;
+  rectObj which_rect;
+  int     next_shape;
 
-    double *qc_x;
-    double *qc_y;
-    float *qc_values;
-    int    *qc_class;
-    int    *qc_red;
-    int    *qc_green;
-    int    *qc_blue;
-    int    *qc_count;
-    int    *qc_tileindex;
+  double *qc_x;
+  double *qc_y;
+  double *qc_x_reproj;
+  double *qc_y_reproj;
+  float *qc_values;
+  int    *qc_class;
+  int    *qc_red;
+  int    *qc_green;
+  int    *qc_blue;
+  int    *qc_count;
+  int    *qc_tileindex;
 
-    /* query bound in force */
-    shapeObj *searchshape;
+  /* query bound in force */
+  shapeObj *searchshape;
 
-    /* Only nearest result to this point. */
-    int      range_mode; /* MS_QUERY_SINGLE, MS_QUERY_MULTIPLE or -1 (skip test) */
-    double   range_dist;
-    pointObj target_point;
+  /* Only nearest result to this point. */
+  int      range_mode; /* MS_QUERY_SINGLE, MS_QUERY_MULTIPLE or -1 (skip test) */
+  double   range_dist;
+  pointObj target_point;
 
-    GDALColorTableH hCT;
+  GDALColorTableH hCT;
 
-    double   shape_tolerance;
+  double   shape_tolerance;
 
 } rasterLayerInfo;
 
@@ -109,7 +111,7 @@ static int addResult(resultCacheObj *cache, int classindex, int shapeindex, int
     if(!cache->results) {
       msSetError(MS_MEMERR, "Realloc() error.", "addResult()");
       return(MS_FAILURE);
-    }   
+    }
     cache->cachesize += MS_RESULTCACHEINCREMENT;
   }
 
@@ -131,41 +133,40 @@ static int addResult(resultCacheObj *cache, int classindex, int shapeindex, int
 static void msRasterLayerInfoFree( layerObj *layer )
 
 {
-    rasterLayerInfo *rlinfo = (rasterLayerInfo *) layer->layerinfo;
+  rasterLayerInfo *rlinfo = (rasterLayerInfo *) layer->layerinfo;
 
-    if( rlinfo == NULL )
-        return;
+  if( rlinfo == NULL )
+    return;
 
-    if( rlinfo->qc_x != NULL )
-    {
-        free( rlinfo->qc_x );
-        free( rlinfo->qc_y );
-    }
+  if( rlinfo->qc_x != NULL ) {
+    free( rlinfo->qc_x );
+    free( rlinfo->qc_y );
+    free( rlinfo->qc_x_reproj );
+    free( rlinfo->qc_y_reproj );
+  }
 
-    if( rlinfo->qc_values )
-        free( rlinfo->qc_values );
+  if( rlinfo->qc_values )
+    free( rlinfo->qc_values );
 
-    if( rlinfo->qc_class )
-    {
-        free( rlinfo->qc_class );
-    }
+  if( rlinfo->qc_class ) {
+    free( rlinfo->qc_class );
+  }
 
-    if( rlinfo->qc_red )
-    {
-        free( rlinfo->qc_red );
-        free( rlinfo->qc_green );
-        free( rlinfo->qc_blue );
-    }
-    
-    if( rlinfo->qc_count != NULL )
-        free( rlinfo->qc_count );
+  if( rlinfo->qc_red ) {
+    free( rlinfo->qc_red );
+    free( rlinfo->qc_green );
+    free( rlinfo->qc_blue );
+  }
 
-    if( rlinfo->qc_tileindex != NULL )
-        free( rlinfo->qc_tileindex );
+  if( rlinfo->qc_count != NULL )
+    free( rlinfo->qc_count );
+
+  if( rlinfo->qc_tileindex != NULL )
+    free( rlinfo->qc_tileindex );
 
-    free( rlinfo );
+  free( rlinfo );
 
-    layer->layerinfo = NULL;
+  layer->layerinfo = NULL;
 }
 
 /************************************************************************/
@@ -175,499 +176,473 @@ static void msRasterLayerInfoFree( layerObj *layer )
 static void msRasterLayerInfoInitialize( layerObj *layer )
 
 {
-    rasterLayerInfo *rlinfo = (rasterLayerInfo *) layer->layerinfo;
-
-    if( rlinfo != NULL )
-        return;
-
-    rlinfo = (rasterLayerInfo *) msSmallCalloc(1,sizeof(rasterLayerInfo));
-    layer->layerinfo = rlinfo;
-    
-    rlinfo->band_count = -1;
-    rlinfo->raster_query_mode = RQM_ENTRY_PER_PIXEL;
-    rlinfo->range_mode = -1; /* inactive */
-    rlinfo->refcount = 0;
-    rlinfo->shape_tolerance = 0.0;
-    
-    /* We need to do this or the layer->layerinfo will be interpreted */
-    /* as shapefile access info because the default connectiontype is */
-    /* MS_SHAPEFILE. */
-    if (layer->connectiontype != MS_WMS)
-        layer->connectiontype = MS_RASTER;
-
-    rlinfo->query_result_hard_max = 1000000;
-
-    if( CSLFetchNameValue( layer->processing, "RASTER_QUERY_MAX_RESULT" ) 
-        != NULL )
-    {
-        rlinfo->query_result_hard_max = 
-            atoi(CSLFetchNameValue( layer->processing, "RASTER_QUERY_MAX_RESULT" ));
-    }
+  rasterLayerInfo *rlinfo = (rasterLayerInfo *) layer->layerinfo;
+
+  if( rlinfo != NULL )
+    return;
+
+  rlinfo = (rasterLayerInfo *) msSmallCalloc(1,sizeof(rasterLayerInfo));
+  layer->layerinfo = rlinfo;
+
+  rlinfo->band_count = -1;
+  rlinfo->raster_query_mode = RQM_ENTRY_PER_PIXEL;
+  rlinfo->range_mode = -1; /* inactive */
+  rlinfo->refcount = 0;
+  rlinfo->shape_tolerance = 0.0;
+
+  /* We need to do this or the layer->layerinfo will be interpreted */
+  /* as shapefile access info because the default connectiontype is */
+  /* MS_SHAPEFILE. */
+  if (layer->connectiontype != MS_WMS)
+    layer->connectiontype = MS_RASTER;
+
+  rlinfo->query_result_hard_max = 1000000;
+
+  if( CSLFetchNameValue( layer->processing, "RASTER_QUERY_MAX_RESULT" )
+      != NULL ) {
+    rlinfo->query_result_hard_max =
+      atoi(CSLFetchNameValue( layer->processing, "RASTER_QUERY_MAX_RESULT" ));
+  }
 }
 
 /************************************************************************/
 /*                       msRasterQueryAddPixel()                        */
 /************************************************************************/
 
-static void msRasterQueryAddPixel( layerObj *layer, pointObj *location, 
+static void msRasterQueryAddPixel( layerObj *layer, pointObj *location,
+                                   pointObj *reprojectedLocation,
                                    float *values )
 
 {
-    rasterLayerInfo *rlinfo = (rasterLayerInfo *) layer->layerinfo;
-    int red = 0, green = 0, blue = 0, nodata = FALSE;
-    int p_class = -1;
-
-    if( rlinfo->query_results == rlinfo->query_result_hard_max )
-        return;
-
-/* -------------------------------------------------------------------- */
-/*      Is this our first time in?  If so, do an initial allocation     */
-/*      for the data arrays suitable to our purposes.                   */
-/* -------------------------------------------------------------------- */
-    if( rlinfo->query_alloc_max == 0 )
-    {
-        rlinfo->query_alloc_max = 2;
-
-        switch( rlinfo->raster_query_mode )
-        {
-          case RQM_ENTRY_PER_PIXEL:
-            rlinfo->qc_x = (double *) 
-                msSmallCalloc(sizeof(double),rlinfo->query_alloc_max);
-            rlinfo->qc_y = (double *) 
-                msSmallCalloc(sizeof(double),rlinfo->query_alloc_max);
-            rlinfo->qc_values = (float *) 
-                msSmallCalloc(sizeof(float),
-                       rlinfo->query_alloc_max*rlinfo->band_count);
-            rlinfo->qc_red = (int *) 
-                msSmallCalloc(sizeof(int),rlinfo->query_alloc_max);
-            rlinfo->qc_green = (int *) 
-                msSmallCalloc(sizeof(int),rlinfo->query_alloc_max);
-            rlinfo->qc_blue = (int *) 
-                msSmallCalloc(sizeof(int),rlinfo->query_alloc_max);
-            if( layer->numclasses > 0 )
-                rlinfo->qc_class = (int *) 
-                    msSmallCalloc(sizeof(int),rlinfo->query_alloc_max);
-            break;
-           
-          case RQM_HIST_ON_CLASS:
-            break;
-            
-          case RQM_HIST_ON_VALUE:
-            break;
-
-          default:
-            assert( FALSE );
-        }
+  rasterLayerInfo *rlinfo = (rasterLayerInfo *) layer->layerinfo;
+  int red = 0, green = 0, blue = 0, nodata = FALSE;
+  int p_class = -1;
+
+  if( rlinfo->query_results == rlinfo->query_result_hard_max )
+    return;
+
+  /* -------------------------------------------------------------------- */
+  /*      Is this our first time in?  If so, do an initial allocation     */
+  /*      for the data arrays suitable to our purposes.                   */
+  /* -------------------------------------------------------------------- */
+  if( rlinfo->query_alloc_max == 0 ) {
+    rlinfo->query_alloc_max = 2;
+
+    switch( rlinfo->raster_query_mode ) {
+      case RQM_ENTRY_PER_PIXEL:
+        rlinfo->qc_x = (double *)
+                       msSmallCalloc(sizeof(double),rlinfo->query_alloc_max);
+        rlinfo->qc_y = (double *)
+                       msSmallCalloc(sizeof(double),rlinfo->query_alloc_max);
+        rlinfo->qc_x_reproj = (double *)
+                       msSmallCalloc(sizeof(double),rlinfo->query_alloc_max);
+        rlinfo->qc_y_reproj = (double *)
+                       msSmallCalloc(sizeof(double),rlinfo->query_alloc_max);
+        rlinfo->qc_values = (float *)
+                            msSmallCalloc(sizeof(float),
+                                          rlinfo->query_alloc_max*rlinfo->band_count);
+        rlinfo->qc_red = (int *)
+                         msSmallCalloc(sizeof(int),rlinfo->query_alloc_max);
+        rlinfo->qc_green = (int *)
+                           msSmallCalloc(sizeof(int),rlinfo->query_alloc_max);
+        rlinfo->qc_blue = (int *)
+                          msSmallCalloc(sizeof(int),rlinfo->query_alloc_max);
+        if( layer->numclasses > 0 )
+          rlinfo->qc_class = (int *)
+                             msSmallCalloc(sizeof(int),rlinfo->query_alloc_max);
+        break;
+
+      case RQM_HIST_ON_CLASS:
+        break;
+
+      case RQM_HIST_ON_VALUE:
+        break;
+
+      default:
+        assert( FALSE );
     }
+  }
 
-/* -------------------------------------------------------------------- */
-/*      Reallocate the data arrays larger if they are near the max      */
-/*      now.                                                            */
-/* -------------------------------------------------------------------- */
-    if( rlinfo->query_results == rlinfo->query_alloc_max )
-    {
-        rlinfo->query_alloc_max = rlinfo->query_alloc_max * 2 + 100;
-
-        if( rlinfo->qc_x != NULL )
-            rlinfo->qc_x = msSmallRealloc(rlinfo->qc_x,
-                                   sizeof(double) * rlinfo->query_alloc_max);
-        if( rlinfo->qc_y != NULL )
-            rlinfo->qc_y = msSmallRealloc(rlinfo->qc_y,
-                                   sizeof(double) * rlinfo->query_alloc_max);
-        if( rlinfo->qc_values != NULL )
-            rlinfo->qc_values = 
-                msSmallRealloc(rlinfo->qc_values,
-                        sizeof(float) * rlinfo->query_alloc_max 
-                        * rlinfo->band_count );
-        if( rlinfo->qc_class != NULL )
-            rlinfo->qc_class = msSmallRealloc(rlinfo->qc_class,
-                                       sizeof(int) * rlinfo->query_alloc_max);
-        if( rlinfo->qc_red != NULL )
-            rlinfo->qc_red = msSmallRealloc(rlinfo->qc_red,
-                                       sizeof(int) * rlinfo->query_alloc_max);
-        if( rlinfo->qc_green != NULL )
-            rlinfo->qc_green = msSmallRealloc(rlinfo->qc_green,
-                                       sizeof(int) * rlinfo->query_alloc_max);
-        if( rlinfo->qc_blue != NULL )
-            rlinfo->qc_blue = msSmallRealloc(rlinfo->qc_blue,
-                                       sizeof(int) * rlinfo->query_alloc_max);
-        if( rlinfo->qc_count != NULL )
-            rlinfo->qc_count = msSmallRealloc(rlinfo->qc_count,
-                                       sizeof(int) * rlinfo->query_alloc_max);
-        if( rlinfo->qc_tileindex != NULL )
-            rlinfo->qc_tileindex = msSmallRealloc(rlinfo->qc_tileindex,
+  /* -------------------------------------------------------------------- */
+  /*      Reallocate the data arrays larger if they are near the max      */
+  /*      now.                                                            */
+  /* -------------------------------------------------------------------- */
+  if( rlinfo->query_results == rlinfo->query_alloc_max ) {
+    rlinfo->query_alloc_max = rlinfo->query_alloc_max * 2 + 100;
+
+    if( rlinfo->qc_x != NULL )
+      rlinfo->qc_x = msSmallRealloc(rlinfo->qc_x,
+                                    sizeof(double) * rlinfo->query_alloc_max);
+    if( rlinfo->qc_y != NULL )
+      rlinfo->qc_y = msSmallRealloc(rlinfo->qc_y,
+                                    sizeof(double) * rlinfo->query_alloc_max);
+    if( rlinfo->qc_x_reproj != NULL )
+      rlinfo->qc_x_reproj = msSmallRealloc(rlinfo->qc_x_reproj,
+                                    sizeof(double) * rlinfo->query_alloc_max);
+    if( rlinfo->qc_y_reproj != NULL )
+      rlinfo->qc_y_reproj = msSmallRealloc(rlinfo->qc_y_reproj,
+                                    sizeof(double) * rlinfo->query_alloc_max);
+    if( rlinfo->qc_values != NULL )
+      rlinfo->qc_values =
+        msSmallRealloc(rlinfo->qc_values,
+                       sizeof(float) * rlinfo->query_alloc_max
+                       * rlinfo->band_count );
+    if( rlinfo->qc_class != NULL )
+      rlinfo->qc_class = msSmallRealloc(rlinfo->qc_class,
+                                        sizeof(int) * rlinfo->query_alloc_max);
+    if( rlinfo->qc_red != NULL )
+      rlinfo->qc_red = msSmallRealloc(rlinfo->qc_red,
+                                      sizeof(int) * rlinfo->query_alloc_max);
+    if( rlinfo->qc_green != NULL )
+      rlinfo->qc_green = msSmallRealloc(rlinfo->qc_green,
+                                        sizeof(int) * rlinfo->query_alloc_max);
+    if( rlinfo->qc_blue != NULL )
+      rlinfo->qc_blue = msSmallRealloc(rlinfo->qc_blue,
                                        sizeof(int) * rlinfo->query_alloc_max);
-    }
+    if( rlinfo->qc_count != NULL )
+      rlinfo->qc_count = msSmallRealloc(rlinfo->qc_count,
+                                        sizeof(int) * rlinfo->query_alloc_max);
+    if( rlinfo->qc_tileindex != NULL )
+      rlinfo->qc_tileindex = msSmallRealloc(rlinfo->qc_tileindex,
+                                            sizeof(int) * rlinfo->query_alloc_max);
+  }
 
-/* -------------------------------------------------------------------- */
-/*      Handle colormap                                                 */
-/* -------------------------------------------------------------------- */
-    if( rlinfo->hCT != NULL )
-    {
-        int pct_index = (int) floor(values[0]);
-        GDALColorEntry sEntry;
-
-        if( GDALGetColorEntryAsRGB( rlinfo->hCT, pct_index, &sEntry ) )
-        {
-            red = sEntry.c1;
-            green = sEntry.c2;
-            blue = sEntry.c3;
-
-            if( sEntry.c4 == 0 )
-                nodata = TRUE;
-        }
-        else
-            nodata = TRUE;
-    }
+  /* -------------------------------------------------------------------- */
+  /*      Handle colormap                                                 */
+  /* -------------------------------------------------------------------- */
+  if( rlinfo->hCT != NULL ) {
+    int pct_index = (int) floor(values[0]);
+    GDALColorEntry sEntry;
+
+    if( GDALGetColorEntryAsRGB( rlinfo->hCT, pct_index, &sEntry ) ) {
+      red = sEntry.c1;
+      green = sEntry.c2;
+      blue = sEntry.c3;
+
+      if( sEntry.c4 == 0 )
+        nodata = TRUE;
+    } else
+      nodata = TRUE;
+  }
 
-/* -------------------------------------------------------------------- */
-/*      Color derived from greyscale value.                             */
-/* -------------------------------------------------------------------- */
-    else
-    {
-        if( rlinfo->band_count >= 3 )
-        {
-            red = (int) MAX(0,MIN(255,values[0]));
-            green = (int) MAX(0,MIN(255,values[1]));
-            blue = (int) MAX(0,MIN(255,values[2]));
-        }
-        else
-        {
-            red = green = blue = (int) MAX(0,MIN(255,values[0]));
-        }
+  /* -------------------------------------------------------------------- */
+  /*      Color derived from greyscale value.                             */
+  /* -------------------------------------------------------------------- */
+  else {
+    if( rlinfo->band_count >= 3 ) {
+      red = (int) MAX(0,MIN(255,values[0]));
+      green = (int) MAX(0,MIN(255,values[1]));
+      blue = (int) MAX(0,MIN(255,values[2]));
+    } else {
+      red = green = blue = (int) MAX(0,MIN(255,values[0]));
     }
+  }
 
-/* -------------------------------------------------------------------- */
-/*      Handle classification.                                          */
-/*                                                                      */
-/*      NOTE: The following is really quite inadequate to deal with     */
-/*      classifications based on [red], [green] and [blue] as           */
-/*      described in:                                                   */
-/*       http://mapserver.gis.umn.edu/bugs/show_bug.cgi?id=1021         */
-/* -------------------------------------------------------------------- */
-    if( rlinfo->qc_class != NULL )
-    {
-        p_class = msGetClass_FloatRGB(layer, values[0],
-                                      red, green, blue );
-
-        if( p_class == -1 )
-            nodata = TRUE;
-        else
-        {
-            nodata = FALSE;
-            rlinfo->qc_class[rlinfo->query_results] = p_class;
-            if( layer->class[p_class]->numstyles > 0 )
-            {
-                red   = layer->class[p_class]->styles[0]->color.red;
-                green = layer->class[p_class]->styles[0]->color.green;
-                blue  = layer->class[p_class]->styles[0]->color.blue;
-            }
-            else
-            {
-                red = green = blue = 0;
-            }
-        }
+  /* -------------------------------------------------------------------- */
+  /*      Handle classification.                                          */
+  /*                                                                      */
+  /*      NOTE: The following is really quite inadequate to deal with     */
+  /*      classifications based on [red], [green] and [blue] as           */
+  /*      described in:                                                   */
+  /*       http://mapserver.gis.umn.edu/bugs/show_bug.cgi?id=1021         */
+  /* -------------------------------------------------------------------- */
+  if( rlinfo->qc_class != NULL ) {
+    p_class = msGetClass_FloatRGB(layer, values[0],
+                                  red, green, blue );
+
+    if( p_class == -1 )
+      nodata = TRUE;
+    else {
+      nodata = FALSE;
+      rlinfo->qc_class[rlinfo->query_results] = p_class;
+      if( layer->class[p_class]->numstyles > 0 ) {
+        red   = layer->class[p_class]->styles[0]->color.red;
+        green = layer->class[p_class]->styles[0]->color.green;
+        blue  = layer->class[p_class]->styles[0]->color.blue;
+      } else {
+        red = green = blue = 0;
+      }
     }
+  }
 
-/* -------------------------------------------------------------------- */
-/*      Record the color.                                               */
-/* -------------------------------------------------------------------- */
-    rlinfo->qc_red[rlinfo->query_results] = red;
-    rlinfo->qc_green[rlinfo->query_results] = green;
-    rlinfo->qc_blue[rlinfo->query_results] = blue;
-
-/* -------------------------------------------------------------------- */
-/*      Record spatial location.                                        */
-/* -------------------------------------------------------------------- */
-    if( rlinfo->qc_x != NULL )
-    {
-        rlinfo->qc_x[rlinfo->query_results] = location->x;
-        rlinfo->qc_y[rlinfo->query_results] = location->y;
-    }
+  /* -------------------------------------------------------------------- */
+  /*      Record the color.                                               */
+  /* -------------------------------------------------------------------- */
+  rlinfo->qc_red[rlinfo->query_results] = red;
+  rlinfo->qc_green[rlinfo->query_results] = green;
+  rlinfo->qc_blue[rlinfo->query_results] = blue;
+
+  /* -------------------------------------------------------------------- */
+  /*      Record spatial location.                                        */
+  /* -------------------------------------------------------------------- */
+  if( rlinfo->qc_x != NULL ) {
+    rlinfo->qc_x[rlinfo->query_results] = location->x;
+    rlinfo->qc_y[rlinfo->query_results] = location->y;
+    rlinfo->qc_x_reproj[rlinfo->query_results] = reprojectedLocation->x;
+    rlinfo->qc_y_reproj[rlinfo->query_results] = reprojectedLocation->y;
+  }
 
-/* -------------------------------------------------------------------- */
-/*      Record actual pixel value(s).                                   */
-/* -------------------------------------------------------------------- */
-    if( rlinfo->qc_values != NULL )
-        memcpy( rlinfo->qc_values + rlinfo->query_results * rlinfo->band_count,
-                values, sizeof(float) * rlinfo->band_count );
-
-/* -------------------------------------------------------------------- */
-/*      Add to the results cache.                                       */
-/* -------------------------------------------------------------------- */
-    if( ! nodata )
-    {
-        addResult( layer->resultcache, p_class, rlinfo->query_results, 0 );
-        rlinfo->query_results++;
-    }
+  /* -------------------------------------------------------------------- */
+  /*      Record actual pixel value(s).                                   */
+  /* -------------------------------------------------------------------- */
+  if( rlinfo->qc_values != NULL )
+    memcpy( rlinfo->qc_values + rlinfo->query_results * rlinfo->band_count,
+            values, sizeof(float) * rlinfo->band_count );
+
+  /* -------------------------------------------------------------------- */
+  /*      Add to the results cache.                                       */
+  /* -------------------------------------------------------------------- */
+  if( ! nodata ) {
+    addResult( layer->resultcache, p_class, rlinfo->query_results, 0 );
+    rlinfo->query_results++;
+  }
 }
 
 /************************************************************************/
 /*                       msRasterQueryByRectLow()                       */
 /************************************************************************/
 
-static int 
+static int
 msRasterQueryByRectLow(mapObj *map, layerObj *layer, GDALDatasetH hDS,
-                       rectObj queryRect) 
+                       rectObj queryRect)
 
 {
-    double	adfGeoTransform[6], adfInvGeoTransform[6];
-    double      dfXMin, dfYMin, dfXMax, dfYMax, dfX, dfY, dfAdjustedRange;
-    int         nWinXOff, nWinYOff, nWinXSize, nWinYSize;
-    int         nRXSize, nRYSize;
-    float       *pafRaster;
-    int         nBandCount, *panBandMap, iPixel, iLine;
-    CPLErr      eErr;
-    rasterLayerInfo *rlinfo;
-    rectObj     searchrect;
-    int         needReproject = MS_FALSE;
-
-    rlinfo = (rasterLayerInfo *) layer->layerinfo;
-
-/* -------------------------------------------------------------------- */
-/*      Reproject the search rect into the projection of this           */
-/*      layer/file if needed.                                           */
-/* -------------------------------------------------------------------- */
-    searchrect = queryRect;
+  double  adfGeoTransform[6], adfInvGeoTransform[6];
+  double      dfXMin, dfYMin, dfXMax, dfYMax, dfX, dfY, dfAdjustedRange;
+  int         nWinXOff, nWinYOff, nWinXSize, nWinYSize;
+  int         nRXSize, nRYSize;
+  float       *pafRaster;
+  int         nBandCount, *panBandMap, iPixel, iLine;
+  CPLErr      eErr;
+  rasterLayerInfo *rlinfo;
+  rectObj     searchrect;
+  int         needReproject = MS_FALSE;
+
+  rlinfo = (rasterLayerInfo *) layer->layerinfo;
+
+  /* -------------------------------------------------------------------- */
+  /*      Reproject the search rect into the projection of this           */
+  /*      layer/file if needed.                                           */
+  /* -------------------------------------------------------------------- */
+  searchrect = queryRect;
 #ifdef USE_PROJ
-    if(layer->project 
-       && msProjectionsDiffer(&(layer->projection), &(map->projection)))
-    {
-        msProjectRect(&(map->projection), &(layer->projection), &searchrect);
-        needReproject = MS_TRUE;
-    }
-    else
-        layer->project = MS_FALSE;
+  if(layer->project
+      && msProjectionsDiffer(&(layer->projection), &(map->projection))) {
+    msProjectRect(&(map->projection), &(layer->projection), &searchrect);
+    needReproject = MS_TRUE;
+  } else
+    layer->project = MS_FALSE;
 #endif
 
-/* -------------------------------------------------------------------- */
-/*      Transform the rectangle in target ground coordinates to         */
-/*      pixel/line extents on the file.  Process all 4 corners, to      */
-/*      build extents.                                                  */
-/* -------------------------------------------------------------------- */
-    nRXSize = GDALGetRasterXSize( hDS );
-    nRYSize = GDALGetRasterYSize( hDS );
-
-    msGetGDALGeoTransform( hDS, map, layer, adfGeoTransform );
-    InvGeoTransform( adfGeoTransform, adfInvGeoTransform );
-
-    /* top left */
-    dfXMin = dfXMax = GEO_TRANS(adfInvGeoTransform,
-                                searchrect.minx, searchrect.maxy);
-    dfYMin = dfYMax = GEO_TRANS(adfInvGeoTransform+3,
-                                searchrect.minx, searchrect.maxy);
-                                
-    /* top right */
-    dfX = GEO_TRANS(adfInvGeoTransform  , searchrect.maxx, searchrect.maxy);
-    dfY = GEO_TRANS(adfInvGeoTransform+3, searchrect.maxx, searchrect.maxy);
-    dfXMin = MIN(dfXMin,dfX);
-    dfXMax = MAX(dfXMax,dfX);
-    dfYMin = MIN(dfYMin,dfY);
-    dfYMax = MAX(dfYMax,dfY);
-    
-    /* bottom left */
-    dfX = GEO_TRANS(adfInvGeoTransform  , searchrect.minx, searchrect.miny);
-    dfY = GEO_TRANS(adfInvGeoTransform+3, searchrect.minx, searchrect.miny);
-    dfXMin = MIN(dfXMin,dfX);
-    dfXMax = MAX(dfXMax,dfX);
-    dfYMin = MIN(dfYMin,dfY);
-    dfYMax = MAX(dfYMax,dfY);
-    
-    /* bottom right */
-    dfX = GEO_TRANS(adfInvGeoTransform  , searchrect.maxx, searchrect.miny);
-    dfY = GEO_TRANS(adfInvGeoTransform+3, searchrect.maxx, searchrect.miny);
-    dfXMin = MIN(dfXMin,dfX);
-    dfXMax = MAX(dfXMax,dfX);
-    dfYMin = MIN(dfYMin,dfY);
-    dfYMax = MAX(dfYMax,dfY);
-
-/* -------------------------------------------------------------------- */
-/*      Trim the rectangle to the area of the file itself, but out      */
-/*      to the edges of the touched edge pixels.                        */
-/* -------------------------------------------------------------------- */
-    dfXMin = MAX(0.0,MIN(nRXSize,floor(dfXMin)));
-    dfYMin = MAX(0.0,MIN(nRYSize,floor(dfYMin)));
-    dfXMax = MAX(0.0,MIN(nRXSize,ceil(dfXMax)));
-    dfYMax = MAX(0.0,MIN(nRYSize,ceil(dfYMax)));
-
-/* -------------------------------------------------------------------- */
-/*      Convert to integer offset/size values.                          */
-/* -------------------------------------------------------------------- */
-    nWinXOff = (int) dfXMin;
-    nWinYOff = (int) dfYMin;
-    nWinXSize = (int) (dfXMax - dfXMin);
-    nWinYSize = (int) (dfYMax - dfYMin);
-
-/* -------------------------------------------------------------------- */
-/*      What bands are we operating on?                                 */
-/* -------------------------------------------------------------------- */
-    panBandMap = msGetGDALBandList( layer, hDS, 0, &nBandCount );
-    
-    if( rlinfo->band_count == -1 )
-        rlinfo->band_count = nBandCount;
-
-    if( nBandCount != rlinfo->band_count )
-    {
-        msSetError( MS_IMGERR, 
-                    "Got %d bands, but expected %d bands.", 
-                    "msRasterQueryByRectLow()", 
-                    nBandCount, rlinfo->band_count );
-
-        return -1;
-    }
+  /* -------------------------------------------------------------------- */
+  /*      Transform the rectangle in target ground coordinates to         */
+  /*      pixel/line extents on the file.  Process all 4 corners, to      */
+  /*      build extents.                                                  */
+  /* -------------------------------------------------------------------- */
+  nRXSize = GDALGetRasterXSize( hDS );
+  nRYSize = GDALGetRasterYSize( hDS );
+
+  msGetGDALGeoTransform( hDS, map, layer, adfGeoTransform );
+  InvGeoTransform( adfGeoTransform, adfInvGeoTransform );
+
+  /* top left */
+  dfXMin = dfXMax = GEO_TRANS(adfInvGeoTransform,
+                              searchrect.minx, searchrect.maxy);
+  dfYMin = dfYMax = GEO_TRANS(adfInvGeoTransform+3,
+                              searchrect.minx, searchrect.maxy);
+
+  /* top right */
+  dfX = GEO_TRANS(adfInvGeoTransform  , searchrect.maxx, searchrect.maxy);
+  dfY = GEO_TRANS(adfInvGeoTransform+3, searchrect.maxx, searchrect.maxy);
+  dfXMin = MIN(dfXMin,dfX);
+  dfXMax = MAX(dfXMax,dfX);
+  dfYMin = MIN(dfYMin,dfY);
+  dfYMax = MAX(dfYMax,dfY);
+
+  /* bottom left */
+  dfX = GEO_TRANS(adfInvGeoTransform  , searchrect.minx, searchrect.miny);
+  dfY = GEO_TRANS(adfInvGeoTransform+3, searchrect.minx, searchrect.miny);
+  dfXMin = MIN(dfXMin,dfX);
+  dfXMax = MAX(dfXMax,dfX);
+  dfYMin = MIN(dfYMin,dfY);
+  dfYMax = MAX(dfYMax,dfY);
+
+  /* bottom right */
+  dfX = GEO_TRANS(adfInvGeoTransform  , searchrect.maxx, searchrect.miny);
+  dfY = GEO_TRANS(adfInvGeoTransform+3, searchrect.maxx, searchrect.miny);
+  dfXMin = MIN(dfXMin,dfX);
+  dfXMax = MAX(dfXMax,dfX);
+  dfYMin = MIN(dfYMin,dfY);
+  dfYMax = MAX(dfYMax,dfY);
+
+  /* -------------------------------------------------------------------- */
+  /*      Trim the rectangle to the area of the file itself, but out      */
+  /*      to the edges of the touched edge pixels.                        */
+  /* -------------------------------------------------------------------- */
+  dfXMin = MAX(0.0,MIN(nRXSize,floor(dfXMin)));
+  dfYMin = MAX(0.0,MIN(nRYSize,floor(dfYMin)));
+  dfXMax = MAX(0.0,MIN(nRXSize,ceil(dfXMax)));
+  dfYMax = MAX(0.0,MIN(nRYSize,ceil(dfYMax)));
+
+  /* -------------------------------------------------------------------- */
+  /*      Convert to integer offset/size values.                          */
+  /* -------------------------------------------------------------------- */
+  nWinXOff = (int) dfXMin;
+  nWinYOff = (int) dfYMin;
+  nWinXSize = (int) (dfXMax - dfXMin);
+  nWinYSize = (int) (dfYMax - dfYMin);
+
+  /* -------------------------------------------------------------------- */
+  /*      What bands are we operating on?                                 */
+  /* -------------------------------------------------------------------- */
+  panBandMap = msGetGDALBandList( layer, hDS, 0, &nBandCount );
+
+  if( rlinfo->band_count == -1 )
+    rlinfo->band_count = nBandCount;
+
+  if( nBandCount != rlinfo->band_count ) {
+    msSetError( MS_IMGERR,
+                "Got %d bands, but expected %d bands.",
+                "msRasterQueryByRectLow()",
+                nBandCount, rlinfo->band_count );
+
+    return -1;
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Try to load the raster data.  For now we just load the first    */
+  /*      band in the file.  Later we will deal with the various band     */
+  /*      selection criteria.                                             */
+  /* -------------------------------------------------------------------- */
+  pafRaster = (float *)
+              calloc(sizeof(float),nWinXSize*nWinYSize*nBandCount);
+  MS_CHECK_ALLOC(pafRaster, sizeof(float)*nWinXSize*nWinYSize*nBandCount, -1);
+
+  eErr = GDALDatasetRasterIO( hDS, GF_Read,
+                              nWinXOff, nWinYOff, nWinXSize, nWinYSize,
+                              pafRaster, nWinXSize, nWinYSize, GDT_Float32,
+                              nBandCount, panBandMap,
+                              4 * nBandCount,
+                              4 * nBandCount * nWinXSize,
+                              4 );
+
+  if( eErr != CE_None ) {
+    msSetError( MS_IOERR, "GDALDatasetRasterIO() failed: %s",
+                "msRasterQueryByRectLow()", CPLGetLastErrorMsg() );
 
-/* -------------------------------------------------------------------- */
-/*      Try to load the raster data.  For now we just load the first    */
-/*      band in the file.  Later we will deal with the various band     */
-/*      selection criteria.                                             */
-/* -------------------------------------------------------------------- */
-    pafRaster = (float *) 
-        calloc(sizeof(float),nWinXSize*nWinYSize*nBandCount);
-    MS_CHECK_ALLOC(pafRaster, sizeof(float)*nWinXSize*nWinYSize*nBandCount, -1);
-
-#if defined(GDAL_VERSION_NUM) && GDAL_VERSION_NUM >= 1199
-    eErr = GDALDatasetRasterIO( hDS, GF_Read, 
-                                nWinXOff, nWinYOff, nWinXSize, nWinYSize,
-                                pafRaster, nWinXSize, nWinYSize, GDT_Float32,
-                                nBandCount, panBandMap, 
-                                4 * nBandCount, 
-                                4 * nBandCount * nWinXSize, 
-                                4 );
-#else
-    /*
-     * The above could actually be implemented for pre-1.2.0 GDALs
-     * reading band by band, but it would be hard to do and test and would
-     * be very rarely useful so we skip it.
-     */
-    msSetError(MS_IMGERR, 
-               "Raster query support requires GDAL 1.2.0 or newer.", 
-               "msRasterQueryByRectLow()" );
     free( pafRaster );
-    return MS_FAILURE;
-#endif
+    return -1;
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Fetch color table for intepreting colors if needed.             */
+  /* -------------------------------------------------------------------- */
+  rlinfo->hCT = GDALGetRasterColorTable(
+                  GDALGetRasterBand( hDS, panBandMap[0] ) );
+
+  free( panBandMap );
+
+  /* -------------------------------------------------------------------- */
+  /*      When computing whether pixels are within range we do it         */
+  /*      based on the center of the pixel to the target point but        */
+  /*      really it ought to be the nearest point on the pixel.  It       */
+  /*      would be too much trouble to do this rigerously, so we just     */
+  /*      add a fudge factor so that a range of zero will find the        */
+  /*      pixel the target falls in at least.                             */
+  /* -------------------------------------------------------------------- */
+  dfAdjustedRange =
+    sqrt(adfGeoTransform[1] * adfGeoTransform[1]
+         + adfGeoTransform[2] * adfGeoTransform[2]
+         + adfGeoTransform[4] * adfGeoTransform[4]
+         + adfGeoTransform[5] * adfGeoTransform[5]) * 0.5 * 1.41421356237
+    + sqrt( rlinfo->range_dist );
+  dfAdjustedRange = dfAdjustedRange * dfAdjustedRange;
+
+  /* -------------------------------------------------------------------- */
+  /*      Loop over all pixels determining which are "in".                */
+  /* -------------------------------------------------------------------- */
+  for( iLine = 0; iLine < nWinYSize; iLine++ ) {
+    for( iPixel = 0; iPixel < nWinXSize; iPixel++ ) {
+      pointObj  sPixelLocation,sReprojectedPixelLocation;
+
+      if( rlinfo->query_results == rlinfo->query_result_hard_max )
+        break;
+
+      /* transform pixel/line to georeferenced */
+      sPixelLocation.x =
+        GEO_TRANS(adfGeoTransform,
+                  iPixel + nWinXOff + 0.5, iLine + nWinYOff + 0.5 );
+      sPixelLocation.y =
+        GEO_TRANS(adfGeoTransform+3,
+                  iPixel + nWinXOff + 0.5, iLine + nWinYOff + 0.5 );
+
+      /* If projections differ, convert this back into the map  */
+      /* projection for distance testing, and comprison to the  */
+      /* search shape.  Save the original pixel location coordinates */
+      /* in sPixelLocationInLayerSRS, so that we can return those */
+      /* coordinates if we have a hit */
+      sReprojectedPixelLocation = sPixelLocation;
+      if( needReproject )
+        msProjectPoint( &(layer->projection), &(map->projection),
+                        &sReprojectedPixelLocation);
+
+      /* If we are doing QueryByShape, check against the shape now */
+      if( rlinfo->searchshape != NULL ) {
+        if( rlinfo->shape_tolerance == 0.0
+            && rlinfo->searchshape->type == MS_SHAPE_POLYGON ) {
+          if( msIntersectPointPolygon(
+                &sReprojectedPixelLocation, rlinfo->searchshape ) == MS_FALSE )
+            continue;
+        } else {
+          shapeObj  tempShape;
+          lineObj   tempLine;
+
+          memset( &tempShape, 0, sizeof(shapeObj) );
+          tempShape.type = MS_SHAPE_POINT;
+          tempShape.numlines = 1;
+          tempShape.line = &tempLine;
+          tempLine.numpoints = 1;
+          tempLine.point = &sReprojectedPixelLocation;
+
+          if( msDistanceShapeToShape(rlinfo->searchshape, &tempShape)
+              > rlinfo->shape_tolerance )
+            continue;
+        }
+      }
 
-    
-    if( eErr != CE_None )
-    {
-        msSetError( MS_IOERR, "GDALDatasetRasterIO() failed: %s", 
-                    "msRasterQueryByRectLow()", CPLGetLastErrorMsg() );
+      if( rlinfo->range_mode >= 0 ) {
+        double dist;
 
-        free( pafRaster );
-        return -1;
-    }
+        dist = (rlinfo->target_point.x - sReprojectedPixelLocation.x)
+               * (rlinfo->target_point.x - sReprojectedPixelLocation.x)
+               + (rlinfo->target_point.y - sReprojectedPixelLocation.y)
+               * (rlinfo->target_point.y - sReprojectedPixelLocation.y);
 
-/* -------------------------------------------------------------------- */
-/*      Fetch color table for intepreting colors if needed.             */
-/* -------------------------------------------------------------------- */
-    rlinfo->hCT = GDALGetRasterColorTable( 
-        GDALGetRasterBand( hDS, panBandMap[0] ) );
-
-    free( panBandMap );
-
-/* -------------------------------------------------------------------- */
-/*      When computing whether pixels are within range we do it         */
-/*      based on the center of the pixel to the target point but        */
-/*      really it ought to be the nearest point on the pixel.  It       */
-/*      would be too much trouble to do this rigerously, so we just     */
-/*      add a fudge factor so that a range of zero will find the        */
-/*      pixel the target falls in at least.                             */
-/* -------------------------------------------------------------------- */
-    dfAdjustedRange = 
-        sqrt(adfGeoTransform[1] * adfGeoTransform[1]
-             + adfGeoTransform[2] * adfGeoTransform[2]
-             + adfGeoTransform[4] * adfGeoTransform[4]
-             + adfGeoTransform[5] * adfGeoTransform[5]) * 0.5 * 1.41421356237
-        + sqrt( rlinfo->range_dist );
-    dfAdjustedRange = dfAdjustedRange * dfAdjustedRange;
-
-/* -------------------------------------------------------------------- */
-/*      Loop over all pixels determining which are "in".                */
-/* -------------------------------------------------------------------- */
-    for( iLine = 0; iLine < nWinYSize; iLine++ )
-    {
-        for( iPixel = 0; iPixel < nWinXSize; iPixel++ )
-        {
-            pointObj  sPixelLocation;
-
-            if( rlinfo->query_results == rlinfo->query_result_hard_max )
-                break;
-
-            /* transform pixel/line to georeferenced */
-            sPixelLocation.x = 
-                GEO_TRANS(adfGeoTransform, 
-                          iPixel + nWinXOff + 0.5, iLine + nWinYOff + 0.5 );
-            sPixelLocation.y = 
-                GEO_TRANS(adfGeoTransform+3, 
-                          iPixel + nWinXOff + 0.5, iLine + nWinYOff + 0.5 );
-
-            /* If projections differ, convert this back into the map  */
-            /* projection for distance testing, and comprison to the  */
-            /* search shape.  */
-            if( needReproject )
-                msProjectPoint( &(layer->projection), &(map->projection), 
-                                &sPixelLocation );
-
-            /* If we are doing QueryByShape, check against the shape now */
-            if( rlinfo->searchshape != NULL )
-            {
-                if( rlinfo->shape_tolerance == 0.0 
-                    && rlinfo->searchshape->type == MS_SHAPE_POLYGON )
-                {
-                    if( msIntersectPointPolygon( 
-                            &sPixelLocation, rlinfo->searchshape ) == MS_FALSE )
-                        continue;
-                }
-                else
-                {
-                    shapeObj  tempShape;
-                    lineObj   tempLine;
-                    
-                    memset( &tempShape, 0, sizeof(shapeObj) );
-                    tempShape.type = MS_SHAPE_POINT;
-                    tempShape.numlines = 1;
-                    tempShape.line = &tempLine;
-                    tempLine.numpoints = 1;
-                    tempLine.point = &sPixelLocation;
-                    
-                    if( msDistanceShapeToShape(rlinfo->searchshape, &tempShape)
-                        > rlinfo->shape_tolerance )
-                        continue;
-                }
-            }
-
-            if( rlinfo->range_mode >= 0 )
-            {
-                double dist;
-
-                dist = (rlinfo->target_point.x - sPixelLocation.x) 
-                    * (rlinfo->target_point.x - sPixelLocation.x) 
-                    + (rlinfo->target_point.y - sPixelLocation.y)
-                    * (rlinfo->target_point.y - sPixelLocation.y);
-
-                if( dist >= dfAdjustedRange )
-                    continue;
-
-                /* If we can only have one feature, trim range and clear */
-                /* previous result.  */
-                if( rlinfo->range_mode == MS_QUERY_SINGLE )
-                {
-                    rlinfo->range_dist = dist;
-                    rlinfo->query_results = 0;
-                }
-            }
-
-            msRasterQueryAddPixel( layer, &sPixelLocation, 
-                                   pafRaster 
-                                   + (iLine*nWinXSize + iPixel) * nBandCount );
+        if( dist >= dfAdjustedRange )
+          continue;
+
+        /* If we can only have one feature, trim range and clear */
+        /* previous result.  */
+        if( rlinfo->range_mode == MS_QUERY_SINGLE ) {
+          rlinfo->range_dist = dist;
+          rlinfo->query_results = 0;
         }
+      }
+
+      msRasterQueryAddPixel( layer,
+			                       &sPixelLocation, // return coords in layer SRS
+                             &sReprojectedPixelLocation,
+                             pafRaster
+                             + (iLine*nWinXSize + iPixel) * nBandCount );
     }
+  }
 
-/* -------------------------------------------------------------------- */
-/*      Cleanup.                                                        */
-/* -------------------------------------------------------------------- */
-    free( pafRaster );
+  /* -------------------------------------------------------------------- */
+  /*      Cleanup.                                                        */
+  /* -------------------------------------------------------------------- */
+  free( pafRaster );
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 #endif /* def USE_GDAL */
 
@@ -675,333 +650,320 @@ msRasterQueryByRectLow(mapObj *map, layerObj *layer, GDALDatasetH hDS,
 /*                        msRasterQueryByRect()                         */
 /************************************************************************/
 
-int msRasterQueryByRect(mapObj *map, layerObj *layer, rectObj queryRect) 
+int msRasterQueryByRect(mapObj *map, layerObj *layer, rectObj queryRect)
 
 {
 #ifndef USE_GDAL
-    msSetError( MS_IMGERR, 
-                "Rasters queries only supported with GDAL support enabled.",
-                "msRasterQueryByRect()" );
-    return MS_FAILURE;
+  msSetError( MS_IMGERR,
+              "Rasters queries only supported with GDAL support enabled.",
+              "msRasterQueryByRect()" );
+  return MS_FAILURE;
 #else
-    int status = MS_SUCCESS;
-    char *filename=NULL;
-
-    layerObj *tlp=NULL; /* pointer to the tile layer either real or temporary */
-    int tileitemindex=-1, tilelayerindex=-1;
-    shapeObj tshp;
-    char tilename[MS_PATH_LENGTH];
-    int  done;
-
-    char szPath[MS_MAXPATHLEN];
-    rectObj searchrect;
-    rasterLayerInfo *rlinfo = NULL;
-    char tiAbsFilePath[MS_MAXPATHLEN];
-    char *tiAbsDirPath = NULL;
-
-/* -------------------------------------------------------------------- */
-/*      Get the layer info.                                             */
-/* -------------------------------------------------------------------- */
-    msRasterLayerInfoInitialize( layer );
-    rlinfo = (rasterLayerInfo *) layer->layerinfo;
-
-/* -------------------------------------------------------------------- */
-/*      Clear old results cache.                                        */
-/* -------------------------------------------------------------------- */
-    if(layer->resultcache) {
-      if(layer->resultcache->results) free(layer->resultcache->results);
-      free(layer->resultcache);
-      layer->resultcache = NULL;
-    }
+  int status = MS_SUCCESS;
+  char *filename=NULL;
+
+  layerObj *tlp=NULL; /* pointer to the tile layer either real or temporary */
+  int tileitemindex=-1, tilelayerindex=-1;
+  shapeObj tshp;
+  char tilename[MS_PATH_LENGTH];
+  int  done;
 
-/* -------------------------------------------------------------------- */
-/*      Initialize the results cache.                                   */
-/* -------------------------------------------------------------------- */
-    layer->resultcache = (resultCacheObj *)msSmallMalloc(sizeof(resultCacheObj));
-    layer->resultcache->results = NULL;
-    layer->resultcache->numresults = layer->resultcache->cachesize = 0;
-    layer->resultcache->bounds.minx =
-        layer->resultcache->bounds.miny =
-        layer->resultcache->bounds.maxx =
+  char szPath[MS_MAXPATHLEN];
+  rectObj searchrect;
+  rasterLayerInfo *rlinfo = NULL;
+  char tiAbsFilePath[MS_MAXPATHLEN];
+  char *tiAbsDirPath = NULL;
+
+  /* -------------------------------------------------------------------- */
+  /*      Get the layer info.                                             */
+  /* -------------------------------------------------------------------- */
+  msRasterLayerInfoInitialize( layer );
+  rlinfo = (rasterLayerInfo *) layer->layerinfo;
+
+  /* -------------------------------------------------------------------- */
+  /*      Clear old results cache.                                        */
+  /* -------------------------------------------------------------------- */
+  if(layer->resultcache) {
+    if(layer->resultcache->results) free(layer->resultcache->results);
+    free(layer->resultcache);
+    layer->resultcache = NULL;
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Initialize the results cache.                                   */
+  /* -------------------------------------------------------------------- */
+  layer->resultcache = (resultCacheObj *)msSmallMalloc(sizeof(resultCacheObj));
+  layer->resultcache->results = NULL;
+  layer->resultcache->numresults = layer->resultcache->cachesize = 0;
+  layer->resultcache->bounds.minx =
+    layer->resultcache->bounds.miny =
+      layer->resultcache->bounds.maxx =
         layer->resultcache->bounds.maxy = -1;
 
-/* -------------------------------------------------------------------- */
-/*      Check if we should really be acting on this layer and           */
-/*      provide debug info in various cases.                            */
-/* -------------------------------------------------------------------- */
-    if(layer->debug > 0 || map->debug > 1)
-        msDebug( "msRasterQueryByRect(%s): entering.\n", layer->name );
-
-    if(!layer->data && !layer->tileindex) {
-        if(layer->debug > 0 || map->debug > 0 )
-            msDebug( "msRasterQueryByRect(%s): layer data and tileindex NULL ... doing nothing.", layer->name );
-        return MS_SUCCESS;
-    }
+  /* -------------------------------------------------------------------- */
+  /*      Check if we should really be acting on this layer and           */
+  /*      provide debug info in various cases.                            */
+  /* -------------------------------------------------------------------- */
+  if(layer->debug > 0 || map->debug > 1)
+    msDebug( "msRasterQueryByRect(%s): entering.\n", layer->name );
+
+  if(!layer->data && !layer->tileindex) {
+    if(layer->debug > 0 || map->debug > 0 )
+      msDebug( "msRasterQueryByRect(%s): layer data and tileindex NULL ... doing nothing.", layer->name );
+    return MS_SUCCESS;
+  }
+
+  if((layer->status != MS_ON) && layer->status != MS_DEFAULT ) {
+    if(layer->debug > 0 )
+      msDebug( "msRasterQueryByRect(%s): not status ON or DEFAULT, doing nothing.", layer->name );
+    return MS_SUCCESS;
+  }
+
+  /* ==================================================================== */
+  /*      Handle setting up tileindex layer.                              */
+  /* ==================================================================== */
+  if(layer->tileindex) { /* we have an index file */
+    int i;
+
+    msInitShape(&tshp);
 
-    if((layer->status != MS_ON) && layer->status != MS_DEFAULT ) {
-        if(layer->debug > 0 )
-            msDebug( "msRasterQueryByRect(%s): not status ON or DEFAULT, doing nothing.", layer->name );
-        return MS_SUCCESS;
+    tilelayerindex = msGetLayerIndex(layer->map, layer->tileindex);
+    if(tilelayerindex == -1) { /* the tileindex references a file, not a layer */
+
+      /* so we create a temporary layer */
+      tlp = (layerObj *) malloc(sizeof(layerObj));
+      MS_CHECK_ALLOC(tlp, sizeof(layerObj), MS_FAILURE);
+
+      initLayer(tlp, map);
+
+      /* set a few parameters for a very basic shapefile-based layer */
+      tlp->name = msStrdup("TILE");
+      tlp->type = MS_LAYER_TILEINDEX;
+      tlp->data = msStrdup(layer->tileindex);
+      if (layer->filteritem)
+        tlp->filteritem = msStrdup(layer->filteritem);
+      if (layer->filter.string) {
+        char *pszTmp;
+        if (layer->filter.type == MS_EXPRESSION) {
+          pszTmp =
+            (char *)msSmallMalloc(sizeof(char)*(strlen(layer->filter.string)+3));
+          sprintf(pszTmp,"(%s)",layer->filter.string);
+          msLoadExpressionString(&tlp->filter, pszTmp);
+          free(pszTmp);
+        } else if (layer->filter.type == MS_REGEX ||
+                   layer->filter.type == MS_IREGEX) {
+          pszTmp =
+            (char *)msSmallMalloc(sizeof(char)*(strlen(layer->filter.string)+3));
+          sprintf(pszTmp,"/%s/",layer->filter.string);
+          msLoadExpressionString(&tlp->filter, pszTmp);
+          free(pszTmp);
+        } else
+          msLoadExpressionString(&tlp->filter, layer->filter.string);
+
+        tlp->filter.type = layer->filter.type;
+      }
+
+    } else {
+      if ( msCheckParentPointer(layer->map,"map")==MS_FAILURE )
+        return MS_FAILURE;
+      tlp = (GET_LAYER(layer->map, tilelayerindex));
+    }
+    status = msLayerOpen(tlp);
+    if(status != MS_SUCCESS) {
+      goto cleanup;
     }
 
-/* ==================================================================== */
-/*      Handle setting up tileindex layer.                              */
-/* ==================================================================== */
-    if(layer->tileindex) { /* we have an index file */
-        int i;
-
-        msInitShape(&tshp);
-    
-        tilelayerindex = msGetLayerIndex(layer->map, layer->tileindex);
-        if(tilelayerindex == -1) { /* the tileindex references a file, not a layer */
-            
-            /* so we create a temporary layer */
-            tlp = (layerObj *) malloc(sizeof(layerObj));
-            MS_CHECK_ALLOC(tlp, sizeof(layerObj), MS_FAILURE);
-
-            initLayer(tlp, map);
-            
-            /* set a few parameters for a very basic shapefile-based layer */
-            tlp->name = msStrdup("TILE");
-            tlp->type = MS_LAYER_TILEINDEX;
-            tlp->data = msStrdup(layer->tileindex);
-            if (layer->filteritem)
-                tlp->filteritem = msStrdup(layer->filteritem);
-            if (layer->filter.string)
-            {
-                char *pszTmp;
-                if (layer->filter.type == MS_EXPRESSION)
-                {
-                    pszTmp = 
-                        (char *)msSmallMalloc(sizeof(char)*(strlen(layer->filter.string)+3));
-                    sprintf(pszTmp,"(%s)",layer->filter.string);
-                    msLoadExpressionString(&tlp->filter, pszTmp);
-                    free(pszTmp);
-                }
-                else if (layer->filter.type == MS_REGEX || 
-                         layer->filter.type == MS_IREGEX)
-                {
-                    pszTmp = 
-                        (char *)msSmallMalloc(sizeof(char)*(strlen(layer->filter.string)+3));
-                    sprintf(pszTmp,"/%s/",layer->filter.string);
-                    msLoadExpressionString(&tlp->filter, pszTmp);
-                    free(pszTmp);
-                }
-                else
-                    msLoadExpressionString(&tlp->filter, layer->filter.string);
-                
-                tlp->filter.type = layer->filter.type;
-            }
+    status = msLayerWhichItems(tlp, MS_FALSE, layer->tileitem);
+    if(status != MS_SUCCESS) {
+      goto cleanup;
+    }
 
-        } else {
-            if ( msCheckParentPointer(layer->map,"map")==MS_FAILURE )
-                return MS_FAILURE;
-            tlp = (GET_LAYER(layer->map, tilelayerindex));
-        }
-        status = msLayerOpen(tlp);
-        if(status != MS_SUCCESS)
-        {
-            goto cleanup;
-        }
+    /* get the tileitem index */
+    for(i=0; i<tlp->numitems; i++) {
+      if(strcasecmp(tlp->items[i], layer->tileitem) == 0) {
+        tileitemindex = i;
+        break;
+      }
+    }
+    if(i == tlp->numitems) { /* didn't find it */
+      msSetError(MS_MEMERR,
+                 "Could not find attribute %s in tileindex.",
+                 "msDrawRasterLayerLow()",
+                 layer->tileitem);
+      status = MS_FAILURE;
+      goto cleanup;
+    }
 
-        status = msLayerWhichItems(tlp, MS_FALSE, layer->tileitem);
-        if(status != MS_SUCCESS)
-        {
-            goto cleanup;
-        }
- 
-        /* get the tileitem index */
-        for(i=0; i<tlp->numitems; i++) {
-            if(strcasecmp(tlp->items[i], layer->tileitem) == 0) {
-                tileitemindex = i;
-                break;
-            }
-        }
-        if(i == tlp->numitems) { /* didn't find it */
-            msSetError(MS_MEMERR, 
-                       "Could not find attribute %s in tileindex.", 
-                       "msDrawRasterLayerLow()", 
-                       layer->tileitem);
-            status = MS_FAILURE;
-            goto cleanup;
-        }
- 
-        searchrect = queryRect;
+    searchrect = queryRect;
 #ifdef USE_PROJ
-        /* if necessary, project the searchrect to source coords */
-        if((map->projection.numargs > 0) && (layer->projection.numargs > 0)) msProjectRect(&map->projection, &layer->projection, &searchrect);
+    /* if necessary, project the searchrect to source coords */
+    if((map->projection.numargs > 0) && (layer->projection.numargs > 0)) msProjectRect(&map->projection, &layer->projection, &searchrect);
 #endif
-        status = msLayerWhichShapes(tlp, searchrect, MS_TRUE);
-        if (status != MS_SUCCESS) {
-            goto cleanup;
-        }
+    status = msLayerWhichShapes(tlp, searchrect, MS_TRUE);
+    if (status != MS_SUCCESS) {
+      goto cleanup;
     }
+  }
 
-/* -------------------------------------------------------------------- */
-/*      Iterate over all tiles (just one in untiled case).              */
-/* -------------------------------------------------------------------- */
-    done = MS_FALSE;
-    while( done == MS_FALSE && status == MS_SUCCESS ) { 
-
-        GDALDatasetH  hDS;
-        char *decrypted_path = NULL;
-
-/* -------------------------------------------------------------------- */
-/*      Get filename.                                                   */
-/* -------------------------------------------------------------------- */
-        if(layer->tileindex) {
-            status = msLayerNextShape(tlp, &tshp);
-            if( status == MS_FAILURE)
-                break;
-            
-            if(status == MS_DONE) break; /* no more tiles/images */
-            
-            if(layer->data == NULL || strlen(layer->data) == 0 ) /* assume whole filename is in attribute field */
-            {
-                strlcpy( tilename, tshp.values[tileitemindex], sizeof(tilename));
-            }
-            else
-                snprintf(tilename, sizeof(tilename), "%s/%s", tshp.values[tileitemindex], layer->data);
-            filename = tilename;
-            
-            msFreeShape(&tshp); /* done with the shape */
-        } else {
-            filename = layer->data;
-            done = MS_TRUE; /* only one image so we're done after this */
-        }
+  /* -------------------------------------------------------------------- */
+  /*      Iterate over all tiles (just one in untiled case).              */
+  /* -------------------------------------------------------------------- */
+  done = MS_FALSE;
+  while( done == MS_FALSE && status == MS_SUCCESS ) {
+
+    GDALDatasetH  hDS;
+    char *decrypted_path = NULL;
+
+    /* -------------------------------------------------------------------- */
+    /*      Get filename.                                                   */
+    /* -------------------------------------------------------------------- */
+    if(layer->tileindex) {
+      status = msLayerNextShape(tlp, &tshp);
+      if( status == MS_FAILURE)
+        break;
+
+      if(status == MS_DONE) break; /* no more tiles/images */
+
+      if(layer->data == NULL || strlen(layer->data) == 0 ) { /* assume whole filename is in attribute field */
+        strlcpy( tilename, tshp.values[tileitemindex], sizeof(tilename));
+      } else
+        snprintf(tilename, sizeof(tilename), "%s/%s", tshp.values[tileitemindex], layer->data);
+      filename = tilename;
+
+      msFreeShape(&tshp); /* done with the shape */
+    } else {
+      filename = layer->data;
+      done = MS_TRUE; /* only one image so we're done after this */
+    }
 
-        if(strlen(filename) == 0) continue;
-
-/* -------------------------------------------------------------------- */
-/*      Open the file.                                                  */
-/* -------------------------------------------------------------------- */
-        msGDALInitialize();
-
-        /*
-        ** If using a tileindex then build the path relative to that file if SHAPEPATH is not set.
-        */
-        if(layer->tileindex && !map->shapepath) { 
-            msBuildPath(tiAbsFilePath, map->mappath, layer->tileindex); /* absolute path to tileindex file */
-            tiAbsDirPath = msGetPath(tiAbsFilePath); /* tileindex file's directory */
-            msBuildPath(szPath, tiAbsDirPath, filename); 
-            free(tiAbsDirPath);
-        } else {
-            msTryBuildPath3(szPath, map->mappath, map->shapepath, filename);
-        }
+    if(strlen(filename) == 0) continue;
 
-        decrypted_path = msDecryptStringTokens( map, szPath );
-        if( !decrypted_path )
-            return MS_FAILURE;
-
-        msAcquireLock( TLOCK_GDAL );
-        hDS = GDALOpen(decrypted_path, GA_ReadOnly );
-        
-        if( hDS == NULL )
-        {
-            int ignore_missing = msMapIgnoreMissingData( map );
-            const char *cpl_error_msg = CPLGetLastErrorMsg();
-        
-            /* we wish to avoid reporting decrypted paths */
-            if( cpl_error_msg != NULL 
-                && strstr(cpl_error_msg,decrypted_path) != NULL
-                && strcmp(decrypted_path,szPath) != 0 )
-                cpl_error_msg = NULL;
-            if( cpl_error_msg == NULL )
-                cpl_error_msg = "";
-
-            msFree( decrypted_path );
-            decrypted_path = NULL;
-            
-            msReleaseLock( TLOCK_GDAL );
-
-            if ( ignore_missing == MS_MISSING_DATA_FAIL ) {
-              if( layer->debug || map->debug )
-                msSetError( MS_IMGERR, 
-                            "Unable to open file %s for layer %s ... fatal error.\n%s", 
-                            "msRasterQueryByRect()",
-                            szPath, layer->name, cpl_error_msg);
-              return(MS_FAILURE);
-            }
-            if( ignore_missing == MS_MISSING_DATA_LOG ) {
-              if( layer->debug || map->debug )
-                msDebug( "Unable to open file %s for layer %s ... ignoring this missing data.\n%s", 
-                         filename, layer->name, cpl_error_msg );
-            }
-            continue;
-        }
+    /* -------------------------------------------------------------------- */
+    /*      Open the file.                                                  */
+    /* -------------------------------------------------------------------- */
+    msGDALInitialize();
 
-        msFree( decrypted_path );
-        decrypted_path = NULL;
-
-/* -------------------------------------------------------------------- */
-/*      Update projectionObj if AUTO.                                   */
-/* -------------------------------------------------------------------- */
-        if (layer->projection.numargs > 0 && 
-            EQUAL(layer->projection.args[0], "auto"))
-        {
-            const char *pszWKT;
-
-            pszWKT = GDALGetProjectionRef( hDS );
-
-            if( pszWKT != NULL && strlen(pszWKT) > 0 )
-            {
-                if( msOGCWKT2ProjectionObj(pszWKT, &(layer->projection),
-                                           layer->debug ) != MS_SUCCESS )
-                {
-                    char	szLongMsg[MESSAGELENGTH*2];
-                    errorObj *ms_error = msGetErrorObj();
-
-                    snprintf( szLongMsg, sizeof(szLongMsg),
-                             "%s\n"
-                             "PROJECTION AUTO cannot be used for this "
-                             "GDAL raster (`%s').",
-                             ms_error->message, filename);
-                    szLongMsg[MESSAGELENGTH-1] = '\0';
-
-                    msSetError(MS_OGRERR, "%s","msDrawRasterLayer()",
-                               szLongMsg);
-
-                    msReleaseLock( TLOCK_GDAL );
-                    return(MS_FAILURE);
-                }
-            }
-        }
+    /*
+    ** If using a tileindex then build the path relative to that file if SHAPEPATH is not set.
+    */
+    if(layer->tileindex && !map->shapepath) {
+      msBuildPath(tiAbsFilePath, map->mappath, layer->tileindex); /* absolute path to tileindex file */
+      tiAbsDirPath = msGetPath(tiAbsFilePath); /* tileindex file's directory */
+      msBuildPath(szPath, tiAbsDirPath, filename);
+      free(tiAbsDirPath);
+    } else {
+      msTryBuildPath3(szPath, map->mappath, map->shapepath, filename);
+    }
 
-/* -------------------------------------------------------------------- */
-/*      Perform actual query on this file.                              */
-/* -------------------------------------------------------------------- */
-        if( status == MS_SUCCESS )
-            status = msRasterQueryByRectLow( map, layer, hDS, queryRect );
-
-        GDALClose( hDS );
-        msReleaseLock( TLOCK_GDAL );
-
-    } /* next tile */
-
-/* -------------------------------------------------------------------- */
-/*      Cleanup tileindex if it is open.                                */
-/* -------------------------------------------------------------------- */
-  cleanup:
-    if(layer->tileindex) { /* tiling clean-up */
-        msLayerClose(tlp);
-        if(tilelayerindex == -1) {
-            freeLayer(tlp);
-            free(tlp);
+    decrypted_path = msDecryptStringTokens( map, szPath );
+    if( !decrypted_path )
+      return MS_FAILURE;
+
+    msAcquireLock( TLOCK_GDAL );
+    hDS = GDALOpen(decrypted_path, GA_ReadOnly );
+
+    if( hDS == NULL ) {
+      int ignore_missing = msMapIgnoreMissingData( map );
+      const char *cpl_error_msg = CPLGetLastErrorMsg();
+
+      /* we wish to avoid reporting decrypted paths */
+      if( cpl_error_msg != NULL
+          && strstr(cpl_error_msg,decrypted_path) != NULL
+          && strcmp(decrypted_path,szPath) != 0 )
+        cpl_error_msg = NULL;
+      if( cpl_error_msg == NULL )
+        cpl_error_msg = "";
+
+      msFree( decrypted_path );
+      decrypted_path = NULL;
+
+      msReleaseLock( TLOCK_GDAL );
+
+      if ( ignore_missing == MS_MISSING_DATA_FAIL ) {
+        if( layer->debug || map->debug )
+          msSetError( MS_IMGERR,
+                      "Unable to open file %s for layer %s ... fatal error.\n%s",
+                      "msRasterQueryByRect()",
+                      szPath, layer->name, cpl_error_msg);
+        return(MS_FAILURE);
+      }
+      if( ignore_missing == MS_MISSING_DATA_LOG ) {
+        if( layer->debug || map->debug )
+          msDebug( "Unable to open file %s for layer %s ... ignoring this missing data.\n%s",
+                   filename, layer->name, cpl_error_msg );
+      }
+      continue;
+    }
+
+    msFree( decrypted_path );
+    decrypted_path = NULL;
+
+    /* -------------------------------------------------------------------- */
+    /*      Update projectionObj if AUTO.                                   */
+    /* -------------------------------------------------------------------- */
+    if (layer->projection.numargs > 0 &&
+        EQUAL(layer->projection.args[0], "auto")) {
+      const char *pszWKT;
+
+      pszWKT = GDALGetProjectionRef( hDS );
+
+      if( pszWKT != NULL && strlen(pszWKT) > 0 ) {
+        if( msOGCWKT2ProjectionObj(pszWKT, &(layer->projection),
+                                   layer->debug ) != MS_SUCCESS ) {
+          char  szLongMsg[MESSAGELENGTH*2];
+          errorObj *ms_error = msGetErrorObj();
+
+          snprintf( szLongMsg, sizeof(szLongMsg),
+                    "%s\n"
+                    "PROJECTION AUTO cannot be used for this "
+                    "GDAL raster (`%s').",
+                    ms_error->message, filename);
+          szLongMsg[MESSAGELENGTH-1] = '\0';
+
+          msSetError(MS_OGRERR, "%s","msDrawRasterLayer()",
+                     szLongMsg);
+
+          msReleaseLock( TLOCK_GDAL );
+          return(MS_FAILURE);
         }
+      }
+    }
+
+    /* -------------------------------------------------------------------- */
+    /*      Perform actual query on this file.                              */
+    /* -------------------------------------------------------------------- */
+    if( status == MS_SUCCESS )
+      status = msRasterQueryByRectLow( map, layer, hDS, queryRect );
+
+    GDALClose( hDS );
+    msReleaseLock( TLOCK_GDAL );
+
+  } /* next tile */
+
+  /* -------------------------------------------------------------------- */
+  /*      Cleanup tileindex if it is open.                                */
+  /* -------------------------------------------------------------------- */
+cleanup:
+  if(layer->tileindex) { /* tiling clean-up */
+    msLayerClose(tlp);
+    if(tilelayerindex == -1) {
+      freeLayer(tlp);
+      free(tlp);
     }
+  }
 
-/* -------------------------------------------------------------------- */
-/*      On failure, or empty result set, cleanup the rlinfo since we    */
-/*      likely won't ever have it accessed or cleaned up later.         */
-/* -------------------------------------------------------------------- */
-    if( status == MS_FAILURE || rlinfo->query_results == 0 )
-        msRasterLayerInfoFree( layer );
+  /* -------------------------------------------------------------------- */
+  /*      On failure, or empty result set, cleanup the rlinfo since we    */
+  /*      likely won't ever have it accessed or cleaned up later.         */
+  /* -------------------------------------------------------------------- */
+  if( status == MS_FAILURE || rlinfo->query_results == 0 )
+    msRasterLayerInfoFree( layer );
 
-    /* populate the items/numitems layer-level values */
-    if( layer->layerinfo != NULL )
-        msRASTERLayerGetItems(layer);
+  /* populate the items/numitems layer-level values */
+  if( layer->layerinfo != NULL )
+    msRASTERLayerGetItems(layer);
 
-    return status;
+  return status;
 #endif /* def USE_GDAL */
 }
 
@@ -1013,59 +975,57 @@ int msRasterQueryByShape(mapObj *map, layerObj *layer, shapeObj *selectshape)
 
 {
 #ifndef USE_GDAL
-    msSetError( MS_IMGERR, 
-                "Rasters queries only supported with GDAL support enabled.",
-                "msRasterQueryByRect()" );
-    return MS_FAILURE;
+  msSetError( MS_IMGERR,
+              "Rasters queries only supported with GDAL support enabled.",
+              "msRasterQueryByRect()" );
+  return MS_FAILURE;
 #else
-    rasterLayerInfo *rlinfo = NULL;
-    int status;
-    double tolerance;
-    rectObj searchrect;
+  rasterLayerInfo *rlinfo = NULL;
+  int status;
+  double tolerance;
+  rectObj searchrect;
 
-    msRasterLayerInfoInitialize( layer );
+  msRasterLayerInfoInitialize( layer );
 
-    rlinfo = (rasterLayerInfo *) layer->layerinfo;
+  rlinfo = (rasterLayerInfo *) layer->layerinfo;
 
-    /* If the selection shape is point or line we use the default tolerance of 
-       3, but for polygons we require an exact hit. */
-    if(layer->tolerance == -1)
-    {
-        if(selectshape->type == MS_SHAPE_POINT || 
-           selectshape->type == MS_SHAPE_LINE)
-            tolerance = 3;
-        else
-            tolerance = 0;
-    }
+  /* If the selection shape is point or line we use the default tolerance of
+     3, but for polygons we require an exact hit. */
+  if(layer->tolerance == -1) {
+    if(selectshape->type == MS_SHAPE_POINT ||
+        selectshape->type == MS_SHAPE_LINE)
+      tolerance = 3;
     else
-        tolerance = layer->tolerance;
-    
-    if(layer->toleranceunits == MS_PIXELS)
-        tolerance = tolerance 
-            * msAdjustExtent(&(map->extent), map->width, map->height);
-    else
-        tolerance = tolerance
-            * (msInchesPerUnit(layer->toleranceunits,0)
-               / msInchesPerUnit(map->units,0));
-    
-    rlinfo->searchshape = selectshape;
-    rlinfo->shape_tolerance = tolerance;
-    
-    msComputeBounds( selectshape );
-    searchrect = selectshape->bounds;
-
-    searchrect.minx -= tolerance; /* expand the search box to account for layer tolerances (e.g. buffered searches) */
-    searchrect.maxx += tolerance;
-    searchrect.miny -= tolerance;
-    searchrect.maxy += tolerance;
-    
-    status = msRasterQueryByRect( map, layer, searchrect );
-
-    rlinfo = (rasterLayerInfo *) layer->layerinfo;
-    if( rlinfo )
-        rlinfo->searchshape = NULL;
-
-    return status;
+      tolerance = 0;
+  } else
+    tolerance = layer->tolerance;
+
+  if(layer->toleranceunits == MS_PIXELS)
+    tolerance = tolerance
+                * msAdjustExtent(&(map->extent), map->width, map->height);
+  else
+    tolerance = tolerance
+                * (msInchesPerUnit(layer->toleranceunits,0)
+                   / msInchesPerUnit(map->units,0));
+
+  rlinfo->searchshape = selectshape;
+  rlinfo->shape_tolerance = tolerance;
+
+  msComputeBounds( selectshape );
+  searchrect = selectshape->bounds;
+
+  searchrect.minx -= tolerance; /* expand the search box to account for layer tolerances (e.g. buffered searches) */
+  searchrect.maxx += tolerance;
+  searchrect.miny -= tolerance;
+  searchrect.maxy += tolerance;
+
+  status = msRasterQueryByRect( map, layer, searchrect );
+
+  rlinfo = (rasterLayerInfo *) layer->layerinfo;
+  if( rlinfo )
+    rlinfo->searchshape = NULL;
+
+  return status;
 #endif /* USE_GDAL  */
 }
 
@@ -1073,100 +1033,98 @@ int msRasterQueryByShape(mapObj *map, layerObj *layer, shapeObj *selectshape)
 /*                        msRasterQueryByPoint()                        */
 /************************************************************************/
 
-int msRasterQueryByPoint(mapObj *map, layerObj *layer, int mode, pointObj p, 
+int msRasterQueryByPoint(mapObj *map, layerObj *layer, int mode, pointObj p,
                          double buffer, int maxresults)
 {
 #ifndef USE_GDAL
-    msSetError( MS_IMGERR, 
-                "Rasters queries only supported with GDAL support enabled.",
-                "msRasterQueryByRect()" );
-    return MS_FAILURE;
+  msSetError( MS_IMGERR,
+              "Rasters queries only supported with GDAL support enabled.",
+              "msRasterQueryByRect()" );
+  return MS_FAILURE;
 #else
-    int result;
-    int previous_maxresults;
-    double layer_tolerance;
-    rectObj bufferRect;
-    rasterLayerInfo *rlinfo = NULL;
+  int result;
+  int previous_maxresults;
+  double layer_tolerance;
+  rectObj bufferRect;
+  rasterLayerInfo *rlinfo = NULL;
+
+  msRasterLayerInfoInitialize( layer );
+
+  rlinfo = (rasterLayerInfo *) layer->layerinfo;
+
+  /* -------------------------------------------------------------------- */
+  /*      If the buffer is not set, then use layer tolerances             */
+  /*      instead.   The "buffer" distince is now in georeferenced        */
+  /*      units.  Note that tolerances in pixels are basically map        */
+  /*      display pixels, not underlying raster pixels.  It isn't         */
+  /*      clear that there is any way of requesting a buffer size in      */
+  /*      underlying pixels.                                              */
+  /* -------------------------------------------------------------------- */
+  if(buffer <= 0) { /* use layer tolerance */
+    if(layer->tolerance == -1)
+      layer_tolerance = 3;
+    else
+      layer_tolerance = layer->tolerance;
 
-    msRasterLayerInfoInitialize( layer );
+    if(layer->toleranceunits == MS_PIXELS)
+      buffer = layer_tolerance
+               * msAdjustExtent(&(map->extent), map->width, map->height);
+    else
+      buffer = layer_tolerance
+               * (msInchesPerUnit(layer->toleranceunits,0)
+                  / msInchesPerUnit(map->units,0));
+  }
 
-    rlinfo = (rasterLayerInfo *) layer->layerinfo;
-
-/* -------------------------------------------------------------------- */
-/*      If the buffer is not set, then use layer tolerances             */
-/*      instead.   The "buffer" distince is now in georeferenced        */
-/*      units.  Note that tolerances in pixels are basically map        */
-/*      display pixels, not underlying raster pixels.  It isn't         */
-/*      clear that there is any way of requesting a buffer size in      */
-/*      underlying pixels.                                              */
-/* -------------------------------------------------------------------- */
-    if(buffer <= 0) { /* use layer tolerance */
-        if(layer->tolerance == -1)
-            layer_tolerance = 3;
-        else
-            layer_tolerance = layer->tolerance;
+  /* -------------------------------------------------------------------- */
+  /*      Setup target point information, at this point they are in       */
+  /*      map coordinates.                                                */
+  /* -------------------------------------------------------------------- */
+  rlinfo->range_dist = buffer * buffer;
+  rlinfo->target_point = p;
+
+  /* -------------------------------------------------------------------- */
+  /*      if we are in the MS_QUERY_SINGLE mode, first try a query with   */
+  /*      zero tolerance.  If this gets a raster pixel then we can be     */
+  /*      reasonably assured that it is the closest to the query          */
+  /*      point.  This will potentially be must more efficient than       */
+  /*      processing all pixels within the tolerance.                     */
+  /* -------------------------------------------------------------------- */
+  if( mode == MS_QUERY_SINGLE ) {
+    rectObj pointRect;
+
+    pointRect.minx = p.x;
+    pointRect.maxx = p.x;
+    pointRect.miny = p.y;
+    pointRect.maxy = p.y;
+
+    rlinfo->range_mode = MS_QUERY_SINGLE;
+    result = msRasterQueryByRect( map, layer, pointRect );
+    if( rlinfo->query_results > 0 )
+      return result;
+  }
 
-        if(layer->toleranceunits == MS_PIXELS)
-            buffer = layer_tolerance 
-                * msAdjustExtent(&(map->extent), map->width, map->height);
-        else
-            buffer = layer_tolerance 
-                * (msInchesPerUnit(layer->toleranceunits,0)
-                   / msInchesPerUnit(map->units,0));
-    }
+  /* -------------------------------------------------------------------- */
+  /*      Setup a rectangle that is everything within the designated      */
+  /*      range and do a search against that.                             */
+  /* -------------------------------------------------------------------- */
+  bufferRect.minx = p.x - buffer;
+  bufferRect.maxx = p.x + buffer;
+  bufferRect.miny = p.y - buffer;
+  bufferRect.maxy = p.y + buffer;
 
-/* -------------------------------------------------------------------- */
-/*      Setup target point information, at this point they are in       */
-/*      map coordinates.                                                */
-/* -------------------------------------------------------------------- */
-    rlinfo->range_dist = buffer * buffer;
-    rlinfo->target_point = p;
-
-/* -------------------------------------------------------------------- */
-/*      if we are in the MS_QUERY_SINGLE mode, first try a query with   */
-/*      zero tolerance.  If this gets a raster pixel then we can be     */
-/*      reasonably assured that it is the closest to the query          */
-/*      point.  This will potentially be must more efficient than       */
-/*      processing all pixels within the tolerance.                     */
-/* -------------------------------------------------------------------- */
-    if( mode == MS_QUERY_SINGLE )
-    {
-        rectObj pointRect;
-
-        pointRect.minx = p.x;
-        pointRect.maxx = p.x;
-        pointRect.miny = p.y;
-        pointRect.maxy = p.y;
-
-        rlinfo->range_mode = MS_QUERY_SINGLE;
-        result = msRasterQueryByRect( map, layer, pointRect );
-        if( rlinfo->query_results > 0 )
-            return result;
-    }
+  rlinfo->range_mode = mode;
 
-/* -------------------------------------------------------------------- */
-/*      Setup a rectangle that is everything within the designated      */
-/*      range and do a search against that.                             */
-/* -------------------------------------------------------------------- */
-    bufferRect.minx = p.x - buffer;
-    bufferRect.maxx = p.x + buffer;
-    bufferRect.miny = p.y - buffer;
-    bufferRect.maxy = p.y + buffer;
-
-    rlinfo->range_mode = mode;
-
-    if( maxresults != 0 )
-    {
-        previous_maxresults = rlinfo->query_result_hard_max;
-        rlinfo->query_result_hard_max = maxresults;
-    }
+  if( maxresults != 0 ) {
+    previous_maxresults = rlinfo->query_result_hard_max;
+    rlinfo->query_result_hard_max = maxresults;
+  }
 
-    result = msRasterQueryByRect( map, layer, bufferRect );
+  result = msRasterQueryByRect( map, layer, bufferRect );
 
-    if( rlinfo != NULL && maxresults != 0 )
-        rlinfo->query_result_hard_max = previous_maxresults;
+  if( rlinfo != NULL && maxresults != 0 )
+    rlinfo->query_result_hard_max = previous_maxresults;
 
-    return result;
+  return result;
 #endif /* USE_GDAL  */
 }
 
@@ -1183,25 +1141,25 @@ int msRasterQueryByPoint(mapObj *map, layerObj *layer, int mode, pointObj p,
 /*                         msRASTERLayerOpen()                          */
 /************************************************************************/
 
-int msRASTERLayerOpen(layerObj *layer) 
+int msRASTERLayerOpen(layerObj *layer)
 {
 #ifndef USE_GDAL
-    msSetError( MS_IMGERR, 
-                "Rasters queries only supported with GDAL support enabled.",
-                "msRasterQueryByRect()" );
-    return MS_FAILURE;
+  msSetError( MS_IMGERR,
+              "Rasters queries only supported with GDAL support enabled.",
+              "msRASTERLayerOpen()" );
+  return MS_FAILURE;
 #else
-    rasterLayerInfo *rlinfo;
+  rasterLayerInfo *rlinfo;
 
-    /* If we don't have info, initialize an empty one now */
-    if( layer->layerinfo == NULL )
-        msRasterLayerInfoInitialize( layer );
-        
-    rlinfo = (rasterLayerInfo *) layer->layerinfo;
+  /* If we don't have info, initialize an empty one now */
+  if( layer->layerinfo == NULL )
+    msRasterLayerInfoInitialize( layer );
 
-    rlinfo->refcount = rlinfo->refcount + 1;
+  rlinfo = (rasterLayerInfo *) layer->layerinfo;
 
-    return MS_SUCCESS;
+  rlinfo->refcount = rlinfo->refcount + 1;
+
+  return MS_SUCCESS;
 #endif /* def USE_GDAL */
 }
 
@@ -1209,17 +1167,17 @@ int msRASTERLayerOpen(layerObj *layer)
 /*                         msRASTERIsLayerOpen()                        */
 /************************************************************************/
 
-int msRASTERLayerIsOpen(layerObj *layer) 
+int msRASTERLayerIsOpen(layerObj *layer)
 {
 #ifndef USE_GDAL
-    msSetError( MS_IMGERR, 
-                "Rasters queries only supported with GDAL support enabled.",
-                "msRasterLayerIsOpen()" );
-    return MS_FALSE;
+  msSetError( MS_IMGERR,
+              "Rasters queries only supported with GDAL support enabled.",
+              "msRasterLayerIsOpen()" );
+  return MS_FALSE;
 #else
-    if (layer->layerinfo)
-        return MS_TRUE;
-    return MS_FALSE;
+  if (layer->layerinfo)
+    return MS_TRUE;
+  return MS_FALSE;
 #endif
 }
 
@@ -1227,8 +1185,8 @@ int msRASTERLayerIsOpen(layerObj *layer)
 /************************************************************************/
 /*                     msRASTERLayerFreeItemInfo()                      */
 /************************************************************************/
-void msRASTERLayerFreeItemInfo(layerObj *layer) 
-	{}
+void msRASTERLayerFreeItemInfo(layerObj *layer)
+{}
 
 /************************************************************************/
 /*                     msRASTERLayerInitItemInfo()                      */
@@ -1236,24 +1194,26 @@ void msRASTERLayerFreeItemInfo(layerObj *layer)
 /*      Perhaps we should be validating the requested items here?       */
 /************************************************************************/
 
-int msRASTERLayerInitItemInfo(layerObj *layer) 
-	{ return MS_SUCCESS; }
+int msRASTERLayerInitItemInfo(layerObj *layer)
+{
+  return MS_SUCCESS;
+}
 
 /************************************************************************/
 /*                      msRASTERLayerWhichShapes()                      */
 /************************************************************************/
-int msRASTERLayerWhichShapes(layerObj *layer, rectObj rect, int isQuery) 
+int msRASTERLayerWhichShapes(layerObj *layer, rectObj rect, int isQuery)
 
 {
 #ifndef USE_GDAL
-    return MS_FAILURE;
+  return MS_FAILURE;
 #else
-    rasterLayerInfo *rlinfo = (rasterLayerInfo *) layer->layerinfo;
+  rasterLayerInfo *rlinfo = (rasterLayerInfo *) layer->layerinfo;
 
-    rlinfo->which_rect = rect;
-    rlinfo->next_shape = 0;
+  rlinfo->which_rect = rect;
+  rlinfo->next_shape = 0;
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 #endif /* def USE_GDAL */
 }
 
@@ -1261,21 +1221,20 @@ int msRASTERLayerWhichShapes(layerObj *layer, rectObj rect, int isQuery)
 /*                         msRASTERLayerClose()                         */
 /************************************************************************/
 
-int msRASTERLayerClose(layerObj *layer) 
+int msRASTERLayerClose(layerObj *layer)
 {
 #ifndef USE_GDAL
-    return MS_FAILURE;
+  return MS_FAILURE;
 #else
-    rasterLayerInfo *rlinfo = (rasterLayerInfo *) layer->layerinfo;
+  rasterLayerInfo *rlinfo = (rasterLayerInfo *) layer->layerinfo;
 
-    if( rlinfo != NULL )
-    {
-        rlinfo->refcount--;
+  if( rlinfo != NULL ) {
+    rlinfo->refcount--;
 
-        if( rlinfo->refcount < 0 )
-            msRasterLayerInfoFree( layer );
-    }
-    return MS_SUCCESS;
+    if( rlinfo->refcount < 0 )
+      msRasterLayerInfoFree( layer );
+  }
+  return MS_SUCCESS;
 #endif /* def USE_GDAL */
 }
 
@@ -1286,26 +1245,24 @@ int msRASTERLayerClose(layerObj *layer)
 int msRASTERLayerNextShape(layerObj *layer, shapeObj *shape)
 {
 #ifndef USE_GDAL
-    return MS_FAILURE;
+  return MS_FAILURE;
 #else
-    rasterLayerInfo *rlinfo = (rasterLayerInfo *) layer->layerinfo;
-
-    if( rlinfo->next_shape < 0 
-        || rlinfo->next_shape >= rlinfo->query_results )
-    {
-        msFreeShape(shape);
-        shape->type = MS_SHAPE_NULL;
-        return MS_DONE;
-    }
-    else {
-      resultObj record;
+  rasterLayerInfo *rlinfo = (rasterLayerInfo *) layer->layerinfo;
+
+  if( rlinfo->next_shape < 0
+      || rlinfo->next_shape >= rlinfo->query_results ) {
+    msFreeShape(shape);
+    shape->type = MS_SHAPE_NULL;
+    return MS_DONE;
+  } else {
+    resultObj record;
 
-      record.shapeindex = rlinfo->next_shape++;
-      record.tileindex = 0;
-      record.classindex = record.resultindex = -1;
+    record.shapeindex = rlinfo->next_shape++;
+    record.tileindex = 0;
+    record.classindex = record.resultindex = -1;
 
-      return msRASTERLayerGetShape( layer, shape, &record);
-    }
+    return msRASTERLayerGetShape( layer, shape, &record);
+  }
 #endif /* def USE_GDAL */
 }
 
@@ -1316,118 +1273,107 @@ int msRASTERLayerNextShape(layerObj *layer, shapeObj *shape)
 int msRASTERLayerGetShape(layerObj *layer, shapeObj *shape, resultObj *record)
 {
 #ifndef USE_GDAL
-    return MS_FAILURE;
+  return MS_FAILURE;
 #else
-    rasterLayerInfo *rlinfo = (rasterLayerInfo *) layer->layerinfo;
-    int i;
+  rasterLayerInfo *rlinfo = (rasterLayerInfo *) layer->layerinfo;
+  int i;
 
-    long shapeindex = record->shapeindex;
+  long shapeindex = record->shapeindex;
 
-    msFreeShape(shape);
-    shape->type = MS_SHAPE_NULL;
+  msFreeShape(shape);
+  shape->type = MS_SHAPE_NULL;
 
-/* -------------------------------------------------------------------- */
-/*      Validate requested record id.                                   */
-/* -------------------------------------------------------------------- */
-    if( shapeindex < 0 || shapeindex >= rlinfo->query_results )
-    {
-        msSetError(MS_MISCERR, 
-                   "Out of range shape index requested.  Requested %d\n"
-                   "but only %d shapes available.",
-                   "msRASTERLayerGetShape()",
-                   shapeindex, rlinfo->query_results );
-        return MS_FAILURE;
-    }
+  /* -------------------------------------------------------------------- */
+  /*      Validate requested record id.                                   */
+  /* -------------------------------------------------------------------- */
+  if( shapeindex < 0 || shapeindex >= rlinfo->query_results ) {
+    msSetError(MS_MISCERR,
+               "Out of range shape index requested.  Requested %d\n"
+               "but only %d shapes available.",
+               "msRASTERLayerGetShape()",
+               shapeindex, rlinfo->query_results );
+    return MS_FAILURE;
+  }
 
-/* -------------------------------------------------------------------- */
-/*      Apply the geometry.                                             */
-/* -------------------------------------------------------------------- */
-    if( rlinfo->qc_x != NULL )
-    {
-	lineObj	line;
-        pointObj point;
-
-        shape->type = MS_SHAPE_POINT;
-        
-        line.numpoints = 1;
-        line.point = &point;
-        
-        point.x = rlinfo->qc_x[shapeindex];
-        point.y = rlinfo->qc_y[shapeindex];
+  /* -------------------------------------------------------------------- */
+  /*      Apply the geometry.                                             */
+  /* -------------------------------------------------------------------- */
+  if( rlinfo->qc_x != NULL ) {
+    lineObj line;
+    pointObj point;
+
+    shape->type = MS_SHAPE_POINT;
+
+    line.numpoints = 1;
+    line.point = &point;
+
+    point.x = rlinfo->qc_x[shapeindex];
+    point.y = rlinfo->qc_y[shapeindex];
 #ifdef USE_POINT_Z_M
-        point.m = 0.0;
+    point.m = 0.0;
 #endif
 
-        msAddLine( shape, &line );
-        msComputeBounds( shape );
-    }
+    msAddLine( shape, &line );
+    msComputeBounds( shape );
+  }
 
-/* -------------------------------------------------------------------- */
-/*      Apply the requested items.                                      */
-/* -------------------------------------------------------------------- */
-    if( layer->numitems > 0 )
-    {
-        shape->values = (char **) msSmallMalloc(sizeof(char *) * layer->numitems);
-        shape->numvalues = layer->numitems;
-        
-        for( i = 0; i < layer->numitems; i++ )
-        {
-            const size_t bufferSize = 1000;
-            char szWork[1000];
-
-            szWork[0] = '\0';
-            if( EQUAL(layer->items[i],"x") && rlinfo->qc_x )
-                snprintf( szWork, bufferSize, "%.8g", rlinfo->qc_x[shapeindex] );
-            else if( EQUAL(layer->items[i],"y") && rlinfo->qc_y )
-                snprintf( szWork, bufferSize, "%.8g", rlinfo->qc_y[shapeindex] );
-
-            else if( EQUAL(layer->items[i],"value_list") && rlinfo->qc_values )
-            {
-                int iValue;
-
-                for( iValue = 0; iValue < rlinfo->band_count; iValue++ )
-                {
-                    if( iValue != 0 )
-                        strlcat( szWork, ",", bufferSize);
-
-                    snprintf( szWork+strlen(szWork), bufferSize-strlen(szWork), "%.8g", 
-                              rlinfo->qc_values[shapeindex * rlinfo->band_count
-                                                + iValue] );
-                }
-            }
-            else if( EQUALN(layer->items[i],"value_",6) && rlinfo->qc_values )
-            {
-                int iValue = atoi(layer->items[i]+6);
-                snprintf( szWork, bufferSize, "%.8g", 
-                          rlinfo->qc_values[shapeindex*rlinfo->band_count+iValue] );
-            }
-            else if( EQUAL(layer->items[i],"class") && rlinfo->qc_class ) 
-            {
-                int p_class = rlinfo->qc_class[shapeindex];
-                if( layer->class[p_class]->name != NULL )
-                    snprintf( szWork, bufferSize, "%.999s", layer->class[p_class]->name );
-                else
-                    snprintf( szWork, bufferSize, "%d", p_class );
-            }
-            else if( EQUAL(layer->items[i],"red") && rlinfo->qc_red )
-                snprintf( szWork, bufferSize, "%d", rlinfo->qc_red[shapeindex] );
-            else if( EQUAL(layer->items[i],"green") && rlinfo->qc_green )
-                snprintf( szWork, bufferSize, "%d", rlinfo->qc_green[shapeindex] );
-            else if( EQUAL(layer->items[i],"blue") && rlinfo->qc_blue )
-                snprintf( szWork, bufferSize, "%d", rlinfo->qc_blue[shapeindex] );
-            else if( EQUAL(layer->items[i],"count") && rlinfo->qc_count )
-                snprintf( szWork, bufferSize, "%d", rlinfo->qc_count[shapeindex] );
-
-            shape->values[i] = msStrdup(szWork);
+  /* -------------------------------------------------------------------- */
+  /*      Apply the requested items.                                      */
+  /* -------------------------------------------------------------------- */
+  if( layer->numitems > 0 ) {
+    shape->values = (char **) msSmallMalloc(sizeof(char *) * layer->numitems);
+    shape->numvalues = layer->numitems;
+
+    for( i = 0; i < layer->numitems; i++ ) {
+      const size_t bufferSize = 1000;
+      char szWork[1000];
+
+      szWork[0] = '\0';
+      if( EQUAL(layer->items[i],"x") && rlinfo->qc_x_reproj )
+        snprintf( szWork, bufferSize, "%.8g", rlinfo->qc_x_reproj[shapeindex] );
+      else if( EQUAL(layer->items[i],"y") && rlinfo->qc_y_reproj )
+        snprintf( szWork, bufferSize, "%.8g", rlinfo->qc_y_reproj[shapeindex] );
+
+      else if( EQUAL(layer->items[i],"value_list") && rlinfo->qc_values ) {
+        int iValue;
+
+        for( iValue = 0; iValue < rlinfo->band_count; iValue++ ) {
+          if( iValue != 0 )
+            strlcat( szWork, ",", bufferSize);
+
+          snprintf( szWork+strlen(szWork), bufferSize-strlen(szWork), "%.8g",
+                    rlinfo->qc_values[shapeindex * rlinfo->band_count
+                                      + iValue] );
         }
+      } else if( EQUALN(layer->items[i],"value_",6) && rlinfo->qc_values ) {
+        int iValue = atoi(layer->items[i]+6);
+        snprintf( szWork, bufferSize, "%.8g",
+                  rlinfo->qc_values[shapeindex*rlinfo->band_count+iValue] );
+      } else if( EQUAL(layer->items[i],"class") && rlinfo->qc_class ) {
+        int p_class = rlinfo->qc_class[shapeindex];
+        if( layer->class[p_class]->name != NULL )
+          snprintf( szWork, bufferSize, "%.999s", layer->class[p_class]->name );
+        else
+          snprintf( szWork, bufferSize, "%d", p_class );
+      } else if( EQUAL(layer->items[i],"red") && rlinfo->qc_red )
+        snprintf( szWork, bufferSize, "%d", rlinfo->qc_red[shapeindex] );
+      else if( EQUAL(layer->items[i],"green") && rlinfo->qc_green )
+        snprintf( szWork, bufferSize, "%d", rlinfo->qc_green[shapeindex] );
+      else if( EQUAL(layer->items[i],"blue") && rlinfo->qc_blue )
+        snprintf( szWork, bufferSize, "%d", rlinfo->qc_blue[shapeindex] );
+      else if( EQUAL(layer->items[i],"count") && rlinfo->qc_count )
+        snprintf( szWork, bufferSize, "%d", rlinfo->qc_count[shapeindex] );
+
+      shape->values[i] = msStrdup(szWork);
     }
+  }
 
-/* -------------------------------------------------------------------- */
-/*      Eventually we should likey apply the geometry properly but      */
-/*      we don't really care about the geometry for query purposes.     */
-/* -------------------------------------------------------------------- */
+  /* -------------------------------------------------------------------- */
+  /*      Eventually we should likey apply the geometry properly but      */
+  /*      we don't really care about the geometry for query purposes.     */
+  /* -------------------------------------------------------------------- */
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 #endif /* def USE_GDAL */
 }
 
@@ -1438,43 +1384,41 @@ int msRASTERLayerGetShape(layerObj *layer, shapeObj *shape, resultObj *record)
 int msRASTERLayerGetItems(layerObj *layer)
 {
 #ifndef USE_GDAL
-    return MS_FAILURE;
+  return MS_FAILURE;
 #else
-    rasterLayerInfo *rlinfo = (rasterLayerInfo *) layer->layerinfo;
+  rasterLayerInfo *rlinfo = (rasterLayerInfo *) layer->layerinfo;
 
-    if( rlinfo == NULL )
-        return MS_FAILURE;
+  if( rlinfo == NULL )
+    return MS_FAILURE;
 
-    layer->items = (char **) msSmallCalloc(sizeof(char *),10);
-
-    layer->numitems = 0;
-    if( rlinfo->qc_x )
-        layer->items[layer->numitems++] = msStrdup("x");
-    if( rlinfo->qc_y )
-        layer->items[layer->numitems++] = msStrdup("y");
-    if( rlinfo->qc_values )
-    {
-        int i;
-        for( i = 0; i < rlinfo->band_count; i++ )
-        {
-            char szName[100];
-            snprintf( szName, sizeof(szName), "value_%d", i );
-            layer->items[layer->numitems++] = msStrdup(szName);
-        }
-        layer->items[layer->numitems++] = msStrdup("value_list");
+  layer->items = (char **) msSmallCalloc(sizeof(char *),10);
+
+  layer->numitems = 0;
+  if( rlinfo->qc_x_reproj )
+    layer->items[layer->numitems++] = msStrdup("x");
+  if( rlinfo->qc_y_reproj )
+    layer->items[layer->numitems++] = msStrdup("y");
+  if( rlinfo->qc_values ) {
+    int i;
+    for( i = 0; i < rlinfo->band_count; i++ ) {
+      char szName[100];
+      snprintf( szName, sizeof(szName), "value_%d", i );
+      layer->items[layer->numitems++] = msStrdup(szName);
     }
-    if( rlinfo->qc_class )
-        layer->items[layer->numitems++] = msStrdup("class");
-    if( rlinfo->qc_red )
-        layer->items[layer->numitems++] = msStrdup("red");
-    if( rlinfo->qc_green )
-        layer->items[layer->numitems++] = msStrdup("green");
-    if( rlinfo->qc_blue )
-        layer->items[layer->numitems++] = msStrdup("blue");
-    if( rlinfo->qc_count )
-        layer->items[layer->numitems++] = msStrdup("count");
-
-    return msRASTERLayerInitItemInfo(layer);
+    layer->items[layer->numitems++] = msStrdup("value_list");
+  }
+  if( rlinfo->qc_class )
+    layer->items[layer->numitems++] = msStrdup("class");
+  if( rlinfo->qc_red )
+    layer->items[layer->numitems++] = msStrdup("red");
+  if( rlinfo->qc_green )
+    layer->items[layer->numitems++] = msStrdup("green");
+  if( rlinfo->qc_blue )
+    layer->items[layer->numitems++] = msStrdup("blue");
+  if( rlinfo->qc_count )
+    layer->items[layer->numitems++] = msStrdup("count");
+
+  return msRASTERLayerInitItemInfo(layer);
 #endif /* def USE_GDAL */
 }
 
@@ -1484,9 +1428,9 @@ int msRASTERLayerGetItems(layerObj *layer)
 
 int msRASTERLayerGetExtent(layerObj *layer, rectObj *extent)
 
-{ 
+{
 #ifndef USE_GDAL
-    return MS_FAILURE;
+  return MS_FAILURE;
 #else
   char szPath[MS_MAXPATHLEN];
   mapObj *map = layer->map;
@@ -1494,14 +1438,13 @@ int msRASTERLayerGetExtent(layerObj *layer, rectObj *extent)
   int nXSize, nYSize;
   GDALDatasetH hDS;
   shapefileObj *tileshpfile;
-  int tilelayerindex = -1; 
+  int tilelayerindex = -1;
   CPLErr eErr = CE_Failure;
   char *decrypted_path;
 
-  if( (!layer->data || strlen(layer->data) == 0) 
-      && layer->tileindex == NULL)
-  {
-    /* should we be issuing a specific error about not supporting 
+  if( (!layer->data || strlen(layer->data) == 0)
+      && layer->tileindex == NULL) {
+    /* should we be issuing a specific error about not supporting
        extents for tileindexed raster layers? */
     return MS_FAILURE;
   }
@@ -1510,20 +1453,18 @@ int msRASTERLayerGetExtent(layerObj *layer, rectObj *extent)
     return MS_FAILURE;
 
   /* If the layer use a tileindex, return the extent of the tileindex shapefile/referenced layer */
-  if (layer->tileindex)
-  {
+  if (layer->tileindex) {
     tilelayerindex = msGetLayerIndex(map, layer->tileindex);
     if(tilelayerindex != -1) /* does the tileindex reference another layer */
       return msLayerGetExtent(GET_LAYER(map, tilelayerindex), extent);
-    else 
-    {
+    else {
       tileshpfile = (shapefileObj *) malloc(sizeof(shapefileObj));
       MS_CHECK_ALLOC(tileshpfile, sizeof(shapefileObj), MS_FAILURE);
 
       if(msShapefileOpen(tileshpfile, "rb", msBuildPath3(szPath, map->mappath, map->shapepath, layer->tileindex), MS_TRUE) == -1)
         if(msShapefileOpen(tileshpfile, "rb", msBuildPath(szPath, map->mappath, layer->tileindex), MS_TRUE) == -1)
           return MS_FAILURE;
-      
+
       *extent = tileshpfile->bounds;
       msShapefileClose(tileshpfile);
       free(tileshpfile);
@@ -1535,44 +1476,39 @@ int msRASTERLayerGetExtent(layerObj *layer, rectObj *extent)
   decrypted_path = msDecryptStringTokens( map, szPath );
 
   msAcquireLock( TLOCK_GDAL );
-  if( decrypted_path )
-  {
-      hDS = GDALOpen(decrypted_path, GA_ReadOnly );
-      msFree( decrypted_path );
-  }
-  else
-      hDS = NULL;
-  
-  if( hDS != NULL )
-  {
+  if( decrypted_path ) {
+    hDS = GDALOpen(decrypted_path, GA_ReadOnly );
+    msFree( decrypted_path );
+  } else
+    hDS = NULL;
+
+  if( hDS != NULL ) {
     nXSize = GDALGetRasterXSize( hDS );
     nYSize = GDALGetRasterYSize( hDS );
     eErr = GDALGetGeoTransform( hDS, adfGeoTransform );
-    
+
     GDALClose( hDS );
   }
-  
+
   msReleaseLock( TLOCK_GDAL );
 
-  if( hDS == NULL || eErr != CE_None )
-  {
-      return MS_FAILURE;
+  if( hDS == NULL || eErr != CE_None ) {
+    return MS_FAILURE;
   }
 
   /* If this appears to be an ungeoreferenced raster than flip it for
      mapservers purposes. */
-  if( adfGeoTransform[5] == 1.0 && adfGeoTransform[3] == 0.0 )
-  {
-      adfGeoTransform[5] = -1.0;
-      adfGeoTransform[3] = nYSize;
+  if( adfGeoTransform[5] == 1.0 && adfGeoTransform[3] == 0.0 ) {
+    adfGeoTransform[5] = -1.0;
+    adfGeoTransform[3] = nYSize;
   }
-  
+
   extent->minx = adfGeoTransform[0];
   extent->maxy = adfGeoTransform[3];
-  
+
   extent->maxx = adfGeoTransform[0] + nXSize * adfGeoTransform[1];
   extent->miny = adfGeoTransform[3] + nYSize * adfGeoTransform[5];
-  
+
   return MS_SUCCESS;
 #endif /* def USE_GDAL */
 }
@@ -1593,40 +1529,40 @@ int msRASTERLayerGetExtent(layerObj *layer, rectObj *extent)
 /*      place, we do nothing.                                           */
 /************************************************************************/
 
-int msRASTERLayerSetTimeFilter(layerObj *layer, const char *timestring, 
+int msRASTERLayerSetTimeFilter(layerObj *layer, const char *timestring,
                                const char *timefield)
 {
-    int tilelayerindex;
-
-/* -------------------------------------------------------------------- */
-/*      If we don't have a tileindex the time filter has no effect.     */
-/* -------------------------------------------------------------------- */
-    if( layer->tileindex == NULL ) 
-        return MS_SUCCESS;
+  int tilelayerindex;
 
-/* -------------------------------------------------------------------- */
-/*      Find the tileindex layer.                                       */
-/* -------------------------------------------------------------------- */
-    tilelayerindex = msGetLayerIndex(layer->map, layer->tileindex);
+  /* -------------------------------------------------------------------- */
+  /*      If we don't have a tileindex the time filter has no effect.     */
+  /* -------------------------------------------------------------------- */
+  if( layer->tileindex == NULL )
+    return MS_SUCCESS;
 
-/* -------------------------------------------------------------------- */
-/*      If we are using a local shapefile as our tileindex (that is     */
-/*      to say, the tileindex name is not of another layer), then we    */
-/*      just install a backtics style filter on the raster layer.       */
-/*      This is propogated to the "working layer" created for the       */
-/*      tileindex by code in mapraster.c.                               */
-/* -------------------------------------------------------------------- */
-    if( tilelayerindex == -1 )
-        return msLayerMakeBackticsTimeFilter( layer, timestring, timefield );
-
-/* -------------------------------------------------------------------- */
-/*      Otherwise we invoke the tileindex layers SetTimeFilter          */
-/*      method.                                                         */
-/* -------------------------------------------------------------------- */
-	if ( msCheckParentPointer(layer->map,"map")==MS_FAILURE )
-		return MS_FAILURE;
-    return msLayerSetTimeFilter( layer->GET_LAYER(map,tilelayerindex),
-                                 timestring, timefield );
+  /* -------------------------------------------------------------------- */
+  /*      Find the tileindex layer.                                       */
+  /* -------------------------------------------------------------------- */
+  tilelayerindex = msGetLayerIndex(layer->map, layer->tileindex);
+
+  /* -------------------------------------------------------------------- */
+  /*      If we are using a local shapefile as our tileindex (that is     */
+  /*      to say, the tileindex name is not of another layer), then we    */
+  /*      just install a backtics style filter on the raster layer.       */
+  /*      This is propogated to the "working layer" created for the       */
+  /*      tileindex by code in mapraster.c.                               */
+  /* -------------------------------------------------------------------- */
+  if( tilelayerindex == -1 )
+    return msLayerMakeBackticsTimeFilter( layer, timestring, timefield );
+
+  /* -------------------------------------------------------------------- */
+  /*      Otherwise we invoke the tileindex layers SetTimeFilter          */
+  /*      method.                                                         */
+  /* -------------------------------------------------------------------- */
+  if ( msCheckParentPointer(layer->map,"map")==MS_FAILURE )
+    return MS_FAILURE;
+  return msLayerSetTimeFilter( layer->GET_LAYER(map,tilelayerindex),
+                               timestring, timefield );
 }
 
 /************************************************************************/
@@ -1636,27 +1572,27 @@ int msRASTERLayerSetTimeFilter(layerObj *layer, const char *timestring,
 int
 msRASTERLayerInitializeVirtualTable(layerObj *layer)
 {
-    assert(layer != NULL);
-    assert(layer->vtable != NULL);
-
-    layer->vtable->LayerInitItemInfo = msRASTERLayerInitItemInfo;
-    layer->vtable->LayerFreeItemInfo = msRASTERLayerFreeItemInfo;
-    layer->vtable->LayerOpen = msRASTERLayerOpen;
-    layer->vtable->LayerIsOpen = msRASTERLayerIsOpen;
-    layer->vtable->LayerWhichShapes = msRASTERLayerWhichShapes;
-    layer->vtable->LayerNextShape = msRASTERLayerNextShape;
-    layer->vtable->LayerGetShape = msRASTERLayerGetShape;
-    layer->vtable->LayerClose = msRASTERLayerClose;
-    layer->vtable->LayerGetItems = msRASTERLayerGetItems;
-    layer->vtable->LayerGetExtent = msRASTERLayerGetExtent;
-    /* layer->vtable->LayerGetAutoStyle, use default */
-    /* layer->vtable->LayerApplyFilterToLayer, use default */
-    layer->vtable->LayerCloseConnection = msRASTERLayerClose;
-    /* we use backtics for proper tileindex shapefile functioning */
-    layer->vtable->LayerSetTimeFilter = msRASTERLayerSetTimeFilter;
-    /* layer->vtable->LayerCreateItems, use default */
-    /* layer->vtable->LayerGetNumFeatures, use default */
+  assert(layer != NULL);
+  assert(layer->vtable != NULL);
+
+  layer->vtable->LayerInitItemInfo = msRASTERLayerInitItemInfo;
+  layer->vtable->LayerFreeItemInfo = msRASTERLayerFreeItemInfo;
+  layer->vtable->LayerOpen = msRASTERLayerOpen;
+  layer->vtable->LayerIsOpen = msRASTERLayerIsOpen;
+  layer->vtable->LayerWhichShapes = msRASTERLayerWhichShapes;
+  layer->vtable->LayerNextShape = msRASTERLayerNextShape;
+  layer->vtable->LayerGetShape = msRASTERLayerGetShape;
+  layer->vtable->LayerClose = msRASTERLayerClose;
+  layer->vtable->LayerGetItems = msRASTERLayerGetItems;
+  layer->vtable->LayerGetExtent = msRASTERLayerGetExtent;
+  /* layer->vtable->LayerGetAutoStyle, use default */
+  /* layer->vtable->LayerApplyFilterToLayer, use default */
+  /* layer->vtable->LayerCloseConnection = msRASTERLayerClose; */
+  /* we use backtics for proper tileindex shapefile functioning */
+  layer->vtable->LayerSetTimeFilter = msRASTERLayerSetTimeFilter;
+  /* layer->vtable->LayerCreateItems, use default */
+  /* layer->vtable->LayerGetNumFeatures, use default */
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
diff --git a/mapregex.c b/mapregex.c
index f65c239..00eac84 100644
--- a/mapregex.c
+++ b/mapregex.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -70,9 +70,9 @@ MS_API_EXPORT(int) ms_regexec(const ms_regex_t *regex, const char *string, size_
 {
   /*This next line only works because we know that regmatch_t
     and ms_regmatch_t are exactly alike (POSIX STANDARD)*/
-  return regexec((const regex_t*)(regex->sys_regex), 
-	       string, nmatch, 
-	       (regmatch_t*) pmatch, eflags);
+  return regexec((const regex_t*)(regex->sys_regex),
+                 string, nmatch,
+                 (regmatch_t*) pmatch, eflags);
 }
 
 MS_API_EXPORT(void) ms_regfree(ms_regex_t *regex)
diff --git a/mapregex.h b/mapregex.h
index 674e4f3..166c8d4 100644
--- a/mapregex.h
+++ b/mapregex.h
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -33,7 +33,7 @@
 #ifdef __cplusplus
 extern "C" {
 #endif
-  
+
   /* We want these to match the POSIX standard, so we need these*/
   /* === regex2.h === */
 #ifdef WIN32
@@ -43,18 +43,17 @@ extern "C" {
 #else
 #define MS_API_EXPORT(type)  type
 #endif
-  
+
   typedef struct {
     void* sys_regex;
   } ms_regex_t;
-  
+
   typedef int ms_regoff_t;
-  typedef struct
-  {
+  typedef struct {
     ms_regoff_t rm_so;  /* Byte offset from string's start to substring's start.  */
     ms_regoff_t rm_eo;  /* Byte offset from string's start to substring's end.  */
   } ms_regmatch_t;
-  
+
   MS_API_EXPORT(int) ms_regcomp(ms_regex_t *, const char *, int);
   MS_API_EXPORT(size_t) ms_regerror(int, const ms_regex_t *, char *, size_t);
   MS_API_EXPORT(int) ms_regexec(const ms_regex_t *, const char *, size_t, ms_regmatch_t [], int);
@@ -63,45 +62,45 @@ extern "C" {
 #ifndef BUILDING_REGEX_PROXY
 
   /* === regcomp.c === */
-#define	MS_REG_BASIC	0000
-#define	MS_REG_EXTENDED	0001
-#define	MS_REG_ICASE	0002
-#define	MS_REG_NOSUB	0004
-#define	MS_REG_NEWLINE	0010
-#define	MS_REG_NOSPEC	0020
-#define	MS_REG_PEND	0040
-#define	MS_REG_DUMP	0200
-
-
-/* === regerror.c === */
-#define	MS_REG_OKAY	 0
-#define	MS_REG_NOMATCH	 1
-#define	MS_REG_BADPAT	 2
-#define	MS_REG_ECOLLATE	 3
-#define	MS_REG_ECTYPE	 4
-#define	MS_REG_EESCAPE	 5
-#define	MS_REG_ESUBREG	 6
-#define	MS_REG_EBRACK	 7
-#define	MS_REG_EPAREN	 8
-#define	MS_REG_EBRACE	 9
-#define	MS_REG_BADBR	10
-#define	MS_REG_ERANGE	11
-#define	MS_REG_ESPACE	12
-#define	MS_REG_BADRPT	13
-#define	MS_REG_EMPTY	14
-#define	MS_REG_ASSERT	15
-#define	MS_REG_INVARG	16
-#define	MS_REG_ATOI	255	/* convert name to number (!) */
-#define	MS_REG_ITOA	0400	/* convert number to name (!) */
-
-
-/* === regexec.c === */
-#define	MS_REG_NOTBOL	00001
-#define	MS_REG_NOTEOL	00002
-#define	MS_REG_STARTEND	00004
-#define	MS_REG_TRACE	00400	/* tracing of execution */
-#define	MS_REG_LARGE	01000	/* force large representation */
-#define	MS_REG_BACKR	02000	/* force use of backref code */
+#define MS_REG_BASIC  0000
+#define MS_REG_EXTENDED 0001
+#define MS_REG_ICASE  0002
+#define MS_REG_NOSUB  0004
+#define MS_REG_NEWLINE  0010
+#define MS_REG_NOSPEC 0020
+#define MS_REG_PEND 0040
+#define MS_REG_DUMP 0200
+
+
+  /* === regerror.c === */
+#define MS_REG_OKAY  0
+#define MS_REG_NOMATCH   1
+#define MS_REG_BADPAT  2
+#define MS_REG_ECOLLATE  3
+#define MS_REG_ECTYPE  4
+#define MS_REG_EESCAPE   5
+#define MS_REG_ESUBREG   6
+#define MS_REG_EBRACK  7
+#define MS_REG_EPAREN  8
+#define MS_REG_EBRACE  9
+#define MS_REG_BADBR  10
+#define MS_REG_ERANGE 11
+#define MS_REG_ESPACE 12
+#define MS_REG_BADRPT 13
+#define MS_REG_EMPTY  14
+#define MS_REG_ASSERT 15
+#define MS_REG_INVARG 16
+#define MS_REG_ATOI 255 /* convert name to number (!) */
+#define MS_REG_ITOA 0400  /* convert number to name (!) */
+
+
+  /* === regexec.c === */
+#define MS_REG_NOTBOL 00001
+#define MS_REG_NOTEOL 00002
+#define MS_REG_STARTEND 00004
+#define MS_REG_TRACE  00400 /* tracing of execution */
+#define MS_REG_LARGE  01000 /* force large representation */
+#define MS_REG_BACKR  02000 /* force use of backref code */
 
 #endif
 
diff --git a/maprendering.c b/maprendering.c
index 5beb690..64f2a5b 100644
--- a/maprendering.c
+++ b/maprendering.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -31,82 +31,83 @@
 #include "mapcopy.h"
 
 int computeLabelStyle(labelStyleObj *s, labelObj *l, fontSetObj *fontset,
-                      double scalefactor) {
-   INIT_LABEL_STYLE(*s);
-   if(!MS_VALID_COLOR(l->color))
-      return MS_FAILURE;
-   if(l->size == -1)
+                      double scalefactor, double resolutionfactor)
+{
+  INIT_LABEL_STYLE(*s);
+  if(!MS_VALID_COLOR(l->color))
+    return MS_FAILURE;
+  if(l->size == -1)
+    return MS_FAILURE;
+
+  s->size = l->size;
+  if(l->type == MS_TRUETYPE) {
+    s->size *=  scalefactor;
+    s->size = MS_MAX(s->size, l->minsize*resolutionfactor);
+    s->size = MS_MIN(s->size, l->maxsize*resolutionfactor);
+    if (!fontset) {
+      msSetError(MS_TTFERR, "No fontset defined.","computeLabelStyle()");
+      return (MS_FAILURE);
+    }
+
+    if (!l->font || !(*l->font)) {
+      return (MS_FAILURE);
+    }
+
+    if(MS_FAILURE == msFontsetLookupFonts(l->font,&s->numfonts,fontset,s->fonts)) {
       return MS_FAILURE;
-
-   s->size = l->size;
-   if(l->type == MS_TRUETYPE) {
-      s->size *=  scalefactor;
-      s->size = MS_MAX(s->size, l->minsize);
-      s->size = MS_MIN(s->size, l->maxsize);
-      if (!fontset) {
-         msSetError(MS_TTFERR, "No fontset defined.","msDrawText()");
-         return (MS_FAILURE);
-      }
-
-      if (!l->font) {
-         msSetError(MS_TTFERR, "No Trueype font defined.","msDrawText()");
-         return (MS_FAILURE);
-      }
-
-      s->font = msLookupHashTable(&(fontset->fonts), l->font);
-      if (!s->font) {
-         msSetError(MS_TTFERR, "Requested font (%s) not found.",
-                    "msDrawText()", l->font);
-         return (MS_FAILURE);
-      }
-   }
-   s->rotation = l->angle * MS_DEG_TO_RAD;
-   return MS_SUCCESS;
+    }
+  }
+  s->rotation = l->angle * MS_DEG_TO_RAD;
+  s->antialias = l->antialias;
+  return MS_SUCCESS;
 }
-void computeSymbolStyle(symbolStyleObj *s, styleObj *src, symbolObj *symbol, double scalefactor) {
-   double default_size;
-   double target_size;
-   double style_size;
-
-   default_size = msSymbolGetDefaultSize(symbol);
-   style_size = (src->size==-1)?default_size:src->size;
-
-   INIT_SYMBOL_STYLE(*s);
-   if(symbol->type == MS_SYMBOL_PIXMAP) {
-      s->color = s->outlinecolor = NULL;
-   } else if(symbol->filled || symbol->type == MS_SYMBOL_TRUETYPE) {
-      if(MS_VALID_COLOR(src->color))
-         s->color = &src->color;
-      if(MS_VALID_COLOR(src->outlinecolor))
-         s->outlinecolor = &src->outlinecolor;
-   } else {
-      if(MS_VALID_COLOR(src->color))
-         s->outlinecolor = &(src->color);
-      else if(MS_VALID_COLOR(src->outlinecolor))
-         s->outlinecolor = &(src->outlinecolor);
-      s->color = NULL;
-   }
-
-
-   if(MS_VALID_COLOR(src->backgroundcolor)) {
-      s->backgroundcolor = &(src->backgroundcolor);
-   }
-
-   target_size = style_size * scalefactor;
-   target_size = MS_MAX(target_size, src->minsize);
-   target_size = MS_MIN(target_size, src->maxsize);
-   s->scale = target_size / default_size;
-   s->gap = src->gap * target_size / style_size;
-
-   if(s->outlinecolor) {
-      s->outlinewidth =  src->width * scalefactor;
-      s->outlinewidth = MS_MAX(s->outlinewidth, src->minwidth);
-      s->outlinewidth = MS_MIN(s->outlinewidth, src->maxwidth);
-   } else {
-      s->outlinewidth = 0;
-   }
-
-   s->rotation = src->angle * MS_DEG_TO_RAD;
+
+void computeSymbolStyle(symbolStyleObj *s, styleObj *src, symbolObj *symbol, double scalefactor,
+    double resolutionfactor)
+{
+  double default_size;
+  double target_size;
+  double style_size;
+
+  default_size = msSymbolGetDefaultSize(symbol);
+  style_size = (src->size==-1)?default_size:src->size;
+
+  INIT_SYMBOL_STYLE(*s);
+  if(symbol->type == MS_SYMBOL_PIXMAP) {
+    s->color = s->outlinecolor = NULL;
+  } else if(symbol->filled || symbol->type == MS_SYMBOL_TRUETYPE) {
+    if(MS_VALID_COLOR(src->color))
+      s->color = &src->color;
+    if(MS_VALID_COLOR(src->outlinecolor))
+      s->outlinecolor = &src->outlinecolor;
+  } else {
+    if(MS_VALID_COLOR(src->color))
+      s->outlinecolor = &(src->color);
+    else if(MS_VALID_COLOR(src->outlinecolor))
+      s->outlinecolor = &(src->outlinecolor);
+    s->color = NULL;
+  }
+
+
+  if(MS_VALID_COLOR(src->backgroundcolor)) {
+    s->backgroundcolor = &(src->backgroundcolor);
+  }
+
+  target_size = style_size * scalefactor;
+  target_size = MS_MAX(target_size, src->minsize*resolutionfactor);
+  target_size = MS_MIN(target_size, src->maxsize*resolutionfactor);
+  s->scale = target_size / default_size;
+  s->gap = src->gap * target_size / style_size;
+
+  if(s->outlinecolor) {
+    s->outlinewidth =  src->width * scalefactor;
+    s->outlinewidth = MS_MAX(s->outlinewidth, src->minwidth*resolutionfactor);
+    s->outlinewidth = MS_MIN(s->outlinewidth, src->maxwidth*resolutionfactor);
+  } else {
+    s->outlinewidth = 0;
+  }
+
+  s->rotation = src->angle * MS_DEG_TO_RAD;
 }
 
 
@@ -116,669 +117,822 @@ void computeSymbolStyle(symbolStyleObj *s, styleObj *src, symbolObj *symbol, dou
     ((a).blue==(b).blue) && \
     ((a).alpha==(b).alpha))
 
-tileCacheObj *searchTileCache(imageObj *img, symbolObj *symbol, symbolStyleObj *s, int width, int height) {
-   tileCacheObj *cur = img->tilecache;
-   while(cur != NULL) {
-      if( cur->width == width
-            && cur->height == height
-            && cur->symbol == symbol
-            && cur->outlinewidth == s->outlinewidth
-            && cur->rotation == s->rotation
-            && cur->scale == s->scale
-            && (!s->color || COMPARE_COLORS(cur->color,*s->color))
-            && (!s->backgroundcolor || COMPARE_COLORS(cur->backgroundcolor,*s->backgroundcolor))
-            && (!s->outlinecolor || COMPARE_COLORS(cur->outlinecolor,*s->outlinecolor)))
-         return cur;
-      cur = cur->next;
-   }
-   return NULL;
+tileCacheObj *searchTileCache(imageObj *img, symbolObj *symbol, symbolStyleObj *s, int width, int height)
+{
+  tileCacheObj *cur = img->tilecache;
+  while(cur != NULL) {
+    if( cur->width == width
+        && cur->height == height
+        && cur->symbol == symbol
+        && cur->outlinewidth == s->outlinewidth
+        && cur->rotation == s->rotation
+        && cur->scale == s->scale
+        && (!s->color || COMPARE_COLORS(cur->color,*s->color))
+        && (!s->backgroundcolor || COMPARE_COLORS(cur->backgroundcolor,*s->backgroundcolor))
+        && (!s->outlinecolor || COMPARE_COLORS(cur->outlinecolor,*s->outlinecolor)))
+      return cur;
+    cur = cur->next;
+  }
+  return NULL;
 }
 
 /* add a cached tile to the current image's cache */
 tileCacheObj *addTileCache(imageObj *img,
-                           imageObj *tile, symbolObj *symbol, symbolStyleObj *style, int width, int height) {
-   tileCacheObj *cachep;
-
-   if(img->ntiles >= MS_IMAGECACHESIZE) { /* remove last element, size stays the same */
-      cachep = img->tilecache;
-
-      /*go to the before last cache object*/
-      while(cachep->next && cachep->next->next) cachep = cachep->next;
-
-      /*free the last tile's data*/
-      msFreeImage(cachep->next->image);
-
-      /*reuse the last tile object*/
-      /* make the cache point to the start of the list*/
-      cachep->next->next = img->tilecache;
-      /* point the global cache to the new first */
-      img->tilecache = cachep->next;
-      /* the before last cache is now last, so it has no successor*/
-      cachep->next = NULL;
-
-   } else {
-      img->ntiles += 1;
-      cachep = (tileCacheObj*)malloc(sizeof(tileCacheObj));
-      MS_CHECK_ALLOC(cachep, sizeof(tileCacheObj), NULL);
-      cachep->next = img->tilecache;
-      img->tilecache = cachep;
-   }
-
-   cachep = img->tilecache;
-
-   cachep->image = tile;
-   cachep->outlinewidth = style->outlinewidth;
-   cachep->scale = style->scale;
-   cachep->rotation = style->rotation;
-   cachep->outlinewidth = style->outlinewidth;
-   if(style->color) MS_COPYCOLOR(&cachep->color,style->color);
-   if(style->outlinecolor) MS_COPYCOLOR(&cachep->outlinecolor,style->outlinecolor);
-   if(style->backgroundcolor) MS_COPYCOLOR(&cachep->backgroundcolor,style->backgroundcolor);
-   cachep->width = width;
-   cachep->height = height;
-   cachep->symbol = symbol;
-   return(cachep);
+                           imageObj *tile, symbolObj *symbol, symbolStyleObj *style, int width, int height)
+{
+  tileCacheObj *cachep;
+
+  if(img->ntiles >= MS_IMAGECACHESIZE) { /* remove last element, size stays the same */
+    cachep = img->tilecache;
+
+    /*go to the before last cache object*/
+    while(cachep->next && cachep->next->next) cachep = cachep->next;
+
+    /*free the last tile's data*/
+    msFreeImage(cachep->next->image);
+
+    /*reuse the last tile object*/
+    /* make the cache point to the start of the list*/
+    cachep->next->next = img->tilecache;
+    /* point the global cache to the new first */
+    img->tilecache = cachep->next;
+    /* the before last cache is now last, so it has no successor*/
+    cachep->next = NULL;
+
+  } else {
+    img->ntiles += 1;
+    cachep = (tileCacheObj*)malloc(sizeof(tileCacheObj));
+    MS_CHECK_ALLOC(cachep, sizeof(tileCacheObj), NULL);
+    cachep->next = img->tilecache;
+    img->tilecache = cachep;
+  }
+
+  cachep = img->tilecache;
+
+  cachep->image = tile;
+  cachep->outlinewidth = style->outlinewidth;
+  cachep->scale = style->scale;
+  cachep->rotation = style->rotation;
+  cachep->outlinewidth = style->outlinewidth;
+  if(style->color) MS_COPYCOLOR(&cachep->color,style->color);
+  if(style->outlinecolor) MS_COPYCOLOR(&cachep->outlinecolor,style->outlinecolor);
+  if(style->backgroundcolor) MS_COPYCOLOR(&cachep->backgroundcolor,style->backgroundcolor);
+  cachep->width = width;
+  cachep->height = height;
+  cachep->symbol = symbol;
+  return(cachep);
 }
 
 imageObj *getTile(imageObj *img, symbolObj *symbol,  symbolStyleObj *s, int width, int height,
-      int seamlessmode) {
-   tileCacheObj *tile;
-   rendererVTableObj *renderer = img->format->vtable;
-   if(width==-1 || height == -1) {
-      width=height=MS_MAX(symbol->sizex,symbol->sizey);
-   }
-   tile = searchTileCache(img,symbol,s,width,height);
-   if(tile==NULL) {
-      imageObj *tileimg;
-      double p_x,p_y;
-      tileimg = msImageCreate(width,height,img->format,NULL,NULL,img->resolution, img->resolution, NULL);
-      if(!seamlessmode) {
-         p_x = width/2.0;
-         p_y = height/2.0;
-         switch(symbol->type) {
+                  int seamlessmode)
+{
+  tileCacheObj *tile;
+  rendererVTableObj *renderer = img->format->vtable;
+  if(width==-1 || height == -1) {
+    width=height=MS_MAX(symbol->sizex,symbol->sizey);
+  }
+  tile = searchTileCache(img,symbol,s,width,height);
+  if(tile==NULL) {
+    imageObj *tileimg;
+    double p_x,p_y;
+    tileimg = msImageCreate(width,height,img->format,NULL,NULL,img->resolution, img->resolution, NULL);
+    if(!seamlessmode) {
+      p_x = width/2.0;
+      p_y = height/2.0;
+      switch(symbol->type) {
+        case (MS_SYMBOL_TRUETYPE):
+          renderer->renderTruetypeSymbol(tileimg, p_x, p_y, symbol, s);
+          break;
+        case (MS_SYMBOL_PIXMAP):
+          if(msPreloadImageSymbol(renderer,symbol) != MS_SUCCESS) {
+            return NULL; /* failed to load image, renderer should have set the error message */
+          }
+          renderer->renderPixmapSymbol(tileimg, p_x, p_y, symbol, s);
+          break;
+        case (MS_SYMBOL_ELLIPSE):
+          renderer->renderEllipseSymbol(tileimg, p_x, p_y,symbol, s);
+          break;
+        case (MS_SYMBOL_VECTOR):
+          renderer->renderVectorSymbol(tileimg, p_x, p_y, symbol, s);
+          break;
+
+        case (MS_SYMBOL_SVG):
+#ifdef USE_SVG_CAIRO
+          if(msPreloadSVGSymbol(symbol) != MS_SUCCESS) {
+            return NULL; //failed to load image, renderer should have set the error message
+          }
+          if (renderer->supports_svg) {
+            if(renderer->renderSVGSymbol(tileimg, p_x, p_y, symbol, s) != MS_SUCCESS) {
+              return NULL;
+            }
+          } else {
+            if (msRenderRasterizedSVGSymbol(tileimg,p_x,p_y,symbol, s) != MS_SUCCESS) {
+              return NULL;
+            }
+          }
+#else
+          msSetError(MS_SYMERR, "SVG symbol support is not enabled.", "getTile()");
+          return NULL;
+#endif
+          break;
+        default:
+          break;
+      }
+    } else {
+      /*
+       * in seamless mode, we render the the symbol 9 times on a 3x3 grid to account for
+       * antialiasing blending from one tile to the next. We finally keep the center tile
+       */
+      imageObj *tile3img = msImageCreate(width*3,height*3,img->format,NULL,NULL,
+                                         img->resolution, img->resolution, NULL);
+      int i,j;
+      rasterBufferObj tmpraster;
+      for(i=1; i<=3; i++) {
+        p_x = (i+0.5)*width;
+        for(j=1; j<=3; j++) {
+          p_y = (j+0.5) * height;
+          switch(symbol->type) {
             case (MS_SYMBOL_TRUETYPE):
-               renderer->renderTruetypeSymbol(tileimg, p_x, p_y, symbol, s);
-               break;
+              renderer->renderTruetypeSymbol(tile3img, p_x, p_y, symbol, s);
+              break;
             case (MS_SYMBOL_PIXMAP):
-               if(msPreloadImageSymbol(renderer,symbol) != MS_SUCCESS) {
-                  return NULL; //failed to load image, renderer should have set the error message
-               }
-               renderer->renderPixmapSymbol(tileimg, p_x, p_y, symbol, s);
-               break;
+              if(msPreloadImageSymbol(renderer,symbol) != MS_SUCCESS) {
+                return NULL; /* failed to load image, renderer should have set the error message */
+              }
+              renderer->renderPixmapSymbol(tile3img, p_x, p_y, symbol, s);
+              break;
             case (MS_SYMBOL_ELLIPSE):
-               renderer->renderEllipseSymbol(tileimg, p_x, p_y,symbol, s);
-               break;
+              renderer->renderEllipseSymbol(tile3img, p_x, p_y,symbol, s);
+              break;
             case (MS_SYMBOL_VECTOR):
-               renderer->renderVectorSymbol(tileimg, p_x, p_y, symbol, s);
-               break;
+              renderer->renderVectorSymbol(tile3img, p_x, p_y, symbol, s);
+              break;
+              /*we should never get into these cases since the seamlessmode mode seems to
+                only be for vector symbols. But if that changes ...*/
+            case (MS_SYMBOL_SVG):
+#ifdef USE_SVG_CAIRO
+              if(msPreloadSVGSymbol(symbol) != MS_SUCCESS) {
+                return NULL; //failed to load image, renderer should have set the error message
+              }
+              if (renderer->supports_svg) {
+                renderer->renderSVGSymbol(tile3img, p_x, p_y, symbol, s);
+              } else {
+                msRenderRasterizedSVGSymbol(tile3img,p_x,p_y,symbol, s);
+              }
+#else
+              msSetError(MS_SYMERR, "SVG symbol support is not enabled.", "getTile()");
+              return NULL;
+#endif
+              break;
             default:
-               break;
-         }
-      } else {
-         /*
-          * in seamless mode, we render the the symbol 9 times on a 3x3 grid to account for
-          * antialiasing blending from one tile to the next. We finally keep the center tile
-          */
-         imageObj *tile3img = msImageCreate(width*3,height*3,img->format,NULL,NULL,
-               img->resolution, img->resolution, NULL);
-         int i,j;
-         rasterBufferObj tmpraster;
-         for(i=1;i<=3;i++) {
-            p_x = (i+0.5)*width;  
-            for(j=1;j<=3;j++) {
-               p_y = (j+0.5) * height;
-               switch(symbol->type) {
-                  case (MS_SYMBOL_TRUETYPE):
-                     renderer->renderTruetypeSymbol(tile3img, p_x, p_y, symbol, s);
-                     break;
-                  case (MS_SYMBOL_PIXMAP):
-                     if(msPreloadImageSymbol(renderer,symbol) != MS_SUCCESS) {
-                        return NULL; //failed to load image, renderer should have set the error message
-                     }
-                     renderer->renderPixmapSymbol(tile3img, p_x, p_y, symbol, s);
-                     break;
-                  case (MS_SYMBOL_ELLIPSE):
-                     renderer->renderEllipseSymbol(tile3img, p_x, p_y,symbol, s);
-                     break;
-                  case (MS_SYMBOL_VECTOR):
-                     renderer->renderVectorSymbol(tile3img, p_x, p_y, symbol, s);
-                     break;
-                  default:
-                     break;
-               }
-            }
-         }
-        
-         MS_IMAGE_RENDERER(tile3img)->getRasterBufferHandle(tile3img,&tmpraster);
-         renderer->mergeRasterBuffer(tileimg, 
-               &tmpraster,
-               1.0,width,height,0,0,width,height
-               );
-         msFreeImage(tile3img);
+              break;
+          }
+        }
       }
-      tile = addTileCache(img,tileimg,symbol,s,width,height);
-   }
-   return tile->image;
+
+      MS_IMAGE_RENDERER(tile3img)->getRasterBufferHandle(tile3img,&tmpraster);
+      renderer->mergeRasterBuffer(tileimg,
+                                  &tmpraster,
+                                  1.0,width,height,0,0,width,height
+                                 );
+      msFreeImage(tile3img);
+    }
+    tile = addTileCache(img,tileimg,symbol,s,width,height);
+  }
+  return tile->image;
 }
 
 int msImagePolylineMarkers(imageObj *image, shapeObj *p, symbolObj *symbol,
-                           symbolStyleObj *style, double spacing, int auto_angle) {
-   rendererVTableObj *renderer = MS_IMAGE_RENDERER(image);
-   int i,j;
-   pointObj point;
-   double original_rotation = style->rotation;
-   double symbol_width;
-   int ret = MS_FAILURE;
-   if(symbol->type != MS_SYMBOL_TRUETYPE)
-      symbol_width = MS_MAX(1,symbol->sizex*style->scale);
-   else {
-      rectObj rect;
-      if(MS_SUCCESS != renderer->getTruetypeTextBBox(renderer,symbol->full_font_path,style->scale,
-            symbol->character,&rect,NULL))
-         return MS_FAILURE;
-      symbol_width=rect.maxx-rect.minx;
-   }
-   for(i=0; i<p->numlines; i++)
-   {
-      int line_in = 0;
-      double current_length = (spacing+symbol_width)/2.0; // initial padding for each line
-      double line_length=0;
-      for(j=1; j<p->line[i].numpoints; j++)
-      {
-         double rx,ry,theta,length;
-         int in;
-         length = sqrt((pow((p->line[i].point[j].x - p->line[i].point[j-1].x),2) + pow((p->line[i].point[j].y - p->line[i].point[j-1].y),2)));
-         line_length += length;
-         if(length==0)continue;
-         rx = (p->line[i].point[j].x - p->line[i].point[j-1].x)/length;
-         ry = (p->line[i].point[j].y - p->line[i].point[j-1].y)/length;
-
-         if (auto_angle) {
+                           symbolStyleObj *style, double spacing,
+                           double initialgap, int auto_angle)
+{
+  rendererVTableObj *renderer = MS_IMAGE_RENDERER(image);
+  int i,j;
+  pointObj point;
+  double original_rotation = style->rotation;
+  double symbol_width,symbol_height;
+  int ret = MS_FAILURE;
+  if(symbol->type != MS_SYMBOL_TRUETYPE) {
+    symbol_width = MS_MAX(1,symbol->sizex*style->scale);
+    symbol_height = MS_MAX(1,symbol->sizey*style->scale);
+  } else {
+    rectObj rect;
+    if(MS_SUCCESS != renderer->getTruetypeTextBBox(renderer,&symbol->full_font_path,1,style->scale,
+        symbol->character,&rect,NULL,0))
+      return MS_FAILURE;
+    symbol_width=rect.maxx-rect.minx;
+    symbol_height=rect.maxy-rect.miny;
+  }
+  for(i=0; i<p->numlines; i++) {
+    int line_in = 0;
+    double line_length=0;
+    double current_length;
+    if(initialgap < 0) {
+      current_length = spacing/2.0; /* initial padding for each line */
+    } else {
+      current_length = initialgap; /* initial padding for each line */
+    }
+    for(j=1; j<p->line[i].numpoints; j++) {
+      double rx,ry,theta,length;
+      length = sqrt((pow((p->line[i].point[j].x - p->line[i].point[j-1].x),2) + pow((p->line[i].point[j].y - p->line[i].point[j-1].y),2)));
+      line_length += length;
+      if(length==0)continue;
+      rx = (p->line[i].point[j].x - p->line[i].point[j-1].x)/length;
+      ry = (p->line[i].point[j].y - p->line[i].point[j-1].y)/length;
+
+      if (auto_angle) {
+        theta = asin(ry);
+        if(rx < 0) {
+          theta += MS_PI;
+        } else theta = -theta;
+        style->rotation = original_rotation + theta;
+      }
+      while (current_length <= length) {
+
+        point.x = p->line[i].point[j - 1].x + current_length * rx;
+        point.y = p->line[i].point[j - 1].y + current_length * ry;
+        if(symbol->anchorpoint_x != 0.5 || symbol->anchorpoint_y != 0.5) {
+          double ox, oy;
+          ox = (0.5 - symbol->anchorpoint_x) * symbol_width;
+          oy = (0.5 - symbol->anchorpoint_y) * symbol_height;
+          if(style->rotation != 0) {
+            double sina,cosa;
+            double rox,roy;
+            sina = sin(-style->rotation);
+            cosa = cos(-style->rotation);
+            rox = ox * cosa - oy * sina;
+            roy = ox * sina + oy * cosa;
+            point.x += rox;
+            point.y += roy;
+          } else {
+            point.x += ox;
+            point.y += oy;
+          }
+        }
+
+        /* if the point is not in the map extent, skip it. (POLYLINE_NO_CLIP) */
+        if ( (point.x < -(symbol_width) || point.x > (image->width+symbol_width)) ||
+             (point.y < -(symbol_height) || point.y > (image->height+symbol_height)) ) {
+          current_length += spacing;
+          line_in=1;          
+          continue;
+        }
+          
+        switch (symbol->type) {
+          case MS_SYMBOL_PIXMAP:
+            ret = renderer->renderPixmapSymbol(image, point.x, point.y, symbol, style);
+            break;
+          case MS_SYMBOL_ELLIPSE:
+            ret = renderer->renderEllipseSymbol(image, point.x, point.y, symbol, style);
+            break;
+          case MS_SYMBOL_VECTOR:
+            ret = renderer->renderVectorSymbol(image, point.x, point.y, symbol, style);
+            break;
+          case MS_SYMBOL_TRUETYPE:
+            ret = renderer->renderTruetypeSymbol(image, point.x, point.y, symbol, style);
+            break;
+        }
+        if( ret != MS_SUCCESS)
+          return ret;
+        current_length += spacing;
+        line_in=1;
+      }
+
+      current_length -= length;
+    }
+
+    /*
+     * if we couldn't place a symbol on the line and no initialgap was
+     * specified,  add one now we don't add the symbol if the line is shorter
+     * than the length of the symbol itself
+     */
+    if(initialgap < 0 && !line_in && line_length>symbol_width) {
+
+      /* total lengths of beginnning and end of current segment */
+      double before_length=0,after_length=0;
+
+      /*optimize*/
+      line_length /= 2.0;
+
+      for(j=1; j<p->line[i].numpoints; j++) {
+        double length;
+        length = sqrt((pow((p->line[i].point[j].x - p->line[i].point[j-1].x),2) + pow((p->line[i].point[j].y - p->line[i].point[j-1].y),2)));
+        after_length += length;
+        if(after_length>line_length) {
+          double rx,ry,theta;
+          /* offset where the symbol should be drawn on the current
+           * segment */
+          double offset = line_length - before_length;
+
+          rx = (p->line[i].point[j].x - p->line[i].point[j-1].x)/length;
+          ry = (p->line[i].point[j].y - p->line[i].point[j-1].y)/length;
+          if (auto_angle) {
             theta = asin(ry);
             if(rx < 0) {
-               theta += MS_PI;
-            }
-            else theta = -theta;
+              theta += MS_PI;
+            } else theta = -theta;
             style->rotation = original_rotation + theta;
-         }
-         in = 0;
-         while (current_length <= length) {
+          }
 
-            point.x = p->line[i].point[j - 1].x + current_length * rx;
-            point.y = p->line[i].point[j - 1].y + current_length * ry;
-            switch (symbol->type) {
+          point.x = p->line[i].point[j - 1].x + offset * rx;
+          point.y = p->line[i].point[j - 1].y + offset * ry;
+          switch (symbol->type) {
             case MS_SYMBOL_PIXMAP:
-               ret = renderer->renderPixmapSymbol(image, point.x, point.y, symbol, style);
-               break;
+              ret = renderer->renderPixmapSymbol(image, point.x, point.y, symbol, style);
+              break;
             case MS_SYMBOL_ELLIPSE:
-               ret = renderer->renderEllipseSymbol(image, point.x, point.y, symbol, style);
-               break;
+              ret = renderer->renderEllipseSymbol(image, point.x, point.y, symbol, style);
+              break;
             case MS_SYMBOL_VECTOR:
-               ret = renderer->renderVectorSymbol(image, point.x, point.y, symbol, style);
-               break;
+              ret = renderer->renderVectorSymbol(image, point.x, point.y, symbol, style);
+              break;
             case MS_SYMBOL_TRUETYPE:
-               ret = renderer->renderTruetypeSymbol(image, point.x, point.y, symbol, style);
-               break;
-            }
-            if( ret != MS_SUCCESS)
-               return ret;
-            current_length += symbol_width + spacing;
-            in = 1;
-            line_in=1;
-         }
-
-         if (in)
-         {
-            current_length -= length + symbol_width/2.0;
-         }
-         else current_length -= length;
+              ret = renderer->renderTruetypeSymbol(image, point.x, point.y, symbol, style);
+              break;
+          }
+          break; /* we have rendered the single marker for this line */
+        }
+        before_length += length;
       }
+    }
 
-      /* if we couldn't place a symbol on the line, add one now
-      we don't add the symbol if the line is shorter than the
-      length of the symbol itself */
-      if(!line_in && line_length>symbol_width) {
-
-         /* total lengths of beginnning and end of current segment */
-         double before_length=0,after_length=0;
-
-         /*optimize*/
-         line_length /= 2.0;
-
-         for(j=1; j<p->line[i].numpoints; j++)
-         {
-            double length;
-            length = sqrt((pow((p->line[i].point[j].x - p->line[i].point[j-1].x),2) + pow((p->line[i].point[j].y - p->line[i].point[j-1].y),2)));
-            after_length += length;
-            if(after_length>line_length) {
-               double rx,ry,theta;
-               /* offset where the symbol should be drawn on the current
-                * segment */
-               double offset = line_length - before_length;
-
-               rx = (p->line[i].point[j].x - p->line[i].point[j-1].x)/length;
-               ry = (p->line[i].point[j].y - p->line[i].point[j-1].y)/length;
-               if (auto_angle) {
-                  theta = asin(ry);
-                  if(rx < 0) {
-                     theta += MS_PI;
-                  }
-                  else theta = -theta;
-                  style->rotation = original_rotation + theta;
-               }
-
-               point.x = p->line[i].point[j - 1].x + offset * rx;
-               point.y = p->line[i].point[j - 1].y + offset * ry;
-               switch (symbol->type) {
-               case MS_SYMBOL_PIXMAP:
-                  ret = renderer->renderPixmapSymbol(image, point.x, point.y, symbol, style);
-                  break;
-               case MS_SYMBOL_ELLIPSE:
-                  ret = renderer->renderEllipseSymbol(image, point.x, point.y, symbol, style);
-                  break;
-               case MS_SYMBOL_VECTOR:
-                  ret = renderer->renderVectorSymbol(image, point.x, point.y, symbol, style);
-                  break;
-               case MS_SYMBOL_TRUETYPE:
-                  ret = renderer->renderTruetypeSymbol(image, point.x, point.y, symbol, style);
-                  break;
-               }
-            }
-            before_length += length;
-         }
-      }
-
-   }
-   return ret;
+  }
+  return ret;
 }
 
 int msDrawLineSymbol(symbolSetObj *symbolset, imageObj *image, shapeObj *p,
                      styleObj *style, double scalefactor)
 {
-   if (image)
-   {
-      if (MS_RENDERER_PLUGIN(image->format)) {
-         rendererVTableObj *renderer = image->format->vtable;
-         symbolObj *symbol;
-         shapeObj *offsetLine = p;
-         int i;
-         double width;
-
-         if (p->numlines == 0)
-            return MS_SUCCESS;
-
-         if (style->symbol >= symbolset->numsymbols || style->symbol < 0)
-            return MS_SUCCESS; /* no such symbol, 0 is OK   */
-
-         symbol = symbolset->symbol[style->symbol];
-         /* store a reference to the renderer to be used for freeing */
-         symbol->renderer = renderer;
-
-         width = style->width * scalefactor;
-         width = MS_MIN(width,style->maxwidth);
-         width = MS_MAX(width,style->minwidth);
-
-         if(style->offsety==-99) {
-            offsetLine = msOffsetPolyline(p,style->offsetx * width/style->width,-99);
-         } else if(style->offsetx!=0 || style->offsety!=0) {
-            offsetLine = msOffsetPolyline(p, style->offsetx * width/style->width,
-                  style->offsety * width/style->width);
-         }
-         if(style->symbol == 0 || (symbol->type==MS_SYMBOL_SIMPLE)) {
-            strokeStyleObj s;
-            s.linecap = style->linecap;
-            s.linejoin = style->linejoin;
-            s.linejoinmaxsize = style->linejoinmaxsize;
-            s.width = width;
-            s.patternlength = style->patternlength;
-            for(i=0; i<s.patternlength; i++)
-               s.pattern[i] = style->pattern[i]*s.width/style->width;
-
-            if(MS_VALID_COLOR(style->color))
-               s.color = &style->color;
-            else if(MS_VALID_COLOR(style->outlinecolor))
-               s.color = &style->outlinecolor;
-            else {
-               /* msSetError(MS_MISCERR,"no color defined for line styling","msDrawLineSymbol()"); 
-                * not really an error */
-               return MS_SUCCESS;
-            }
-            renderer->renderLine(image,offsetLine,&s);
-         }
-         else {
-            symbolStyleObj s;
-            switch (symbol->type) {
-            case (MS_SYMBOL_TRUETYPE): {
-               if(!symbol->full_font_path)
-                  symbol->full_font_path =  msStrdup(msLookupHashTable(&(symbolset->fontset->fonts),
-                                                     symbol->font));
-               if(!symbol->full_font_path) {
-                  msSetError(MS_MEMERR,"allocation error", "msDrawMArkerSymbol()");
-                  return MS_FAILURE;
-               }
-            }
-            break;
-            case (MS_SYMBOL_PIXMAP): {
-               if(!symbol->pixmap_buffer) {
-                  if(MS_SUCCESS != msPreloadImageSymbol(renderer,symbol))
-                     return MS_FAILURE;
-               }
-            }
-            break;
-            }
+  if (image) {
+    if (MS_RENDERER_PLUGIN(image->format)) {
+      rendererVTableObj *renderer = image->format->vtable;
+      symbolObj *symbol;
+      shapeObj *offsetLine = p;
+      int i;
+      double width;
+      double finalscalefactor;
+
+      if (p->numlines == 0)
+        return MS_SUCCESS;
+
+      if (style->symbol >= symbolset->numsymbols || style->symbol < 0)
+        return MS_SUCCESS; /* no such symbol, 0 is OK   */
+
+      symbol = symbolset->symbol[style->symbol];
+      /* store a reference to the renderer to be used for freeing */
+      symbol->renderer = renderer;
+
+      width = style->width * scalefactor;
+      width = MS_MIN(width,style->maxwidth*image->resolutionfactor);
+      width = MS_MAX(width,style->minwidth*image->resolutionfactor);
+      if(style->width != 0) {
+        finalscalefactor = width / style->width;
+      } else {
+        finalscalefactor = 1.0;
+      }
 
-            INIT_SYMBOL_STYLE(s);
-            computeSymbolStyle(&s,style,symbol,scalefactor);
-            s.style = style;
-            if(symbol->type == MS_SYMBOL_TRUETYPE) {
-               if(!symbol->full_font_path)
-                  symbol->full_font_path =  msStrdup(msLookupHashTable(&(symbolset->fontset->fonts),
-                                                     symbol->font));
-               assert(symbol->full_font_path);
+      if(style->offsety==-99) {
+        offsetLine = msOffsetPolyline(p,style->offsetx * finalscalefactor ,-99);
+      } else if(style->offsetx!=0 || style->offsety!=0) {
+        offsetLine = msOffsetPolyline(p, style->offsetx * finalscalefactor,
+                                      style->offsety * finalscalefactor);
+      }
+      if(style->symbol == 0 || (symbol->type==MS_SYMBOL_SIMPLE)) {
+        strokeStyleObj s;
+        s.linecap = style->linecap;
+        s.linejoin = style->linejoin;
+        s.linejoinmaxsize = style->linejoinmaxsize;
+        s.width = width;
+        s.patternlength = style->patternlength;
+        for(i=0; i<s.patternlength; i++)
+          s.pattern[i] = style->pattern[i] * finalscalefactor;
+        s.patternoffset = (style->initialgap<=0) ? 0 : (style->initialgap * finalscalefactor);
+
+        if(MS_VALID_COLOR(style->color))
+          s.color = &style->color;
+        else if(MS_VALID_COLOR(style->outlinecolor))
+          s.color = &style->outlinecolor;
+        else {
+          /* msSetError(MS_MISCERR,"no color defined for line styling","msDrawLineSymbol()");
+           * not really an error */
+          return MS_SUCCESS;
+        }
+        renderer->renderLine(image,offsetLine,&s);
+      } else {
+        symbolStyleObj s;
+        switch (symbol->type) {
+          case (MS_SYMBOL_TRUETYPE): {
+            if(!symbol->full_font_path)
+              symbol->full_font_path =  msStrdup(msLookupHashTable(&(symbolset->fontset->fonts),
+                                                 symbol->font));
+            if(!symbol->full_font_path) {
+              msSetError(MS_MEMERR,"allocation error", "msDrawMArkerSymbol()");
+              return MS_FAILURE;
             }
-
-            //compute a markerStyle and use it on the line
-            if(style->gap<0) {
-               //special function that treats any other symbol used as a marker, not a brush
-               msImagePolylineMarkers(image,offsetLine,symbol,&s,-s.gap,1);
+          }
+          break;
+          case (MS_SYMBOL_PIXMAP): {
+            if(!symbol->pixmap_buffer) {
+              if(MS_SUCCESS != msPreloadImageSymbol(renderer,symbol))
+                return MS_FAILURE;
             }
-            else if(style->gap>0) {
-               msImagePolylineMarkers(image,offsetLine,symbol,&s,s.gap,0);
+          }
+          break;
+        }
+
+        INIT_SYMBOL_STYLE(s);
+        computeSymbolStyle(&s,style,symbol,scalefactor,image->resolutionfactor);
+        s.style = style;
+        if(symbol->type == MS_SYMBOL_TRUETYPE) {
+          if(!symbol->full_font_path)
+            symbol->full_font_path =  msStrdup(msLookupHashTable(&(symbolset->fontset->fonts),
+                                               symbol->font));
+          assert(symbol->full_font_path);
+        }
+
+        /* compute a markerStyle and use it on the line */
+        if(style->gap<0) {
+          /* special function that treats any other symbol used as a marker, not a brush */
+          msImagePolylineMarkers(image,offsetLine,symbol,&s,-s.gap,
+                                 style->initialgap * finalscalefactor, 1);
+        } else if(style->gap>0) {
+          msImagePolylineMarkers(image,offsetLine,symbol,&s,s.gap,
+                                 style->initialgap * finalscalefactor,0);
+        } else {
+          if(renderer->renderLineTiled != NULL) {
+            int pw,ph;
+            imageObj* tile=NULL;
+            if(s.scale != 1) {
+              pw = MS_NINT(symbol->sizex * s.scale);
+              ph = MS_NINT(symbol->sizey * s.scale);
             } else {
-               if(renderer->renderLineTiled != NULL) {
-                  int pw,ph;
-                  imageObj* tile=NULL;
-                  if(s.scale != 1) {
-                     pw = MS_NINT(symbol->sizex * s.scale)+1;
-                     ph = MS_NINT(symbol->sizey * s.scale)+1;
-                  } else {
-                     pw = symbol->sizex;
-                     ph = symbol->sizey;
-                  }
-                  if(pw<1) pw=1;
-                  if(ph<1) ph=1;
-                  tile = getTile(image, symbol,&s,pw,ph,0);
-                  renderer->renderLineTiled(image, offsetLine, tile);
-               } else {
-                  msSetError(MS_RENDERERERR, "renderer does not support brushed lines", "msDrawLineSymbol()");
-                  return MS_FAILURE;
-               }
+              pw = symbol->sizex;
+              ph = symbol->sizey;
             }
-         }
-
-         if(offsetLine!=p) {
-            msFreeShape(offsetLine);
-            msFree(offsetLine);
-         }
+            if(pw<1) pw=1;
+            if(ph<1) ph=1;
+            tile = getTile(image, symbol,&s,pw,ph,0);
+            renderer->renderLineTiled(image, offsetLine, tile);
+          } else {
+            msSetError(MS_RENDERERERR, "renderer does not support brushed lines", "msDrawLineSymbol()");
+            return MS_FAILURE;
+          }
+        }
       }
-      else if( MS_RENDERER_IMAGEMAP(image->format) )
-         msDrawLineSymbolIM(symbolset, image, p, style, scalefactor);
-      else {
-         msSetError(MS_RENDERERERR, "unsupported renderer", "msDrawShadeSymbol()");
-         return MS_FAILURE;
+
+      if(offsetLine!=p) {
+        msFreeShape(offsetLine);
+        msFree(offsetLine);
       }
-   } else {
+    } else if( MS_RENDERER_IMAGEMAP(image->format) )
+      msDrawLineSymbolIM(symbolset, image, p, style, scalefactor);
+    else {
+      msSetError(MS_RENDERERERR, "unsupported renderer", "msDrawShadeSymbol()");
       return MS_FAILURE;
-   }
-   return MS_SUCCESS;
+    }
+  } else {
+    return MS_FAILURE;
+  }
+  return MS_SUCCESS;
 }
 
 int msDrawShadeSymbol(symbolSetObj *symbolset, imageObj *image, shapeObj *p, styleObj *style, double scalefactor)
 {
-   int ret = MS_SUCCESS;
-   if (!p)
-      return MS_SUCCESS;
-   if (p->numlines <= 0)
-      return MS_SUCCESS;
-
-   if (style->symbol >= symbolset->numsymbols || style->symbol < 0)
-      return MS_SUCCESS; // no such symbol, 0 is OK
-
-   /*
-    * if only an outlinecolor was defined, and not a color,
-    * switch to the line drawing function
-    *
-    * this behavior is kind of a mapfile hack, and must be
-    * kept for backwards compatibility
-    */
-   if (symbolset->symbol[style->symbol]->type != MS_SYMBOL_PIXMAP) {
-      if (!MS_VALID_COLOR(style->color)) {
-         if(MS_VALID_COLOR(style->outlinecolor))
-            return msDrawLineSymbol(symbolset, image, p, style, scalefactor);
-         else {
-            /* just do nothing if no color has been set */
-            return MS_SUCCESS;
-         }
+  int ret = MS_SUCCESS;
+  if (!p)
+    return MS_SUCCESS;
+  if (p->numlines <= 0)
+    return MS_SUCCESS;
+
+  if (style->symbol >= symbolset->numsymbols || style->symbol < 0)
+    return MS_SUCCESS; /* no such symbol, 0 is OK */
+
+  /*
+   * if only an outlinecolor was defined, and not a color,
+   * switch to the line drawing function
+   *
+   * this behavior is kind of a mapfile hack, and must be
+   * kept for backwards compatibility
+   */
+  if (symbolset->symbol[style->symbol]->type != MS_SYMBOL_PIXMAP && symbolset->symbol[style->symbol]->type != MS_SYMBOL_SVG ) {
+    if (!MS_VALID_COLOR(style->color)) {
+      if(MS_VALID_COLOR(style->outlinecolor))
+        return msDrawLineSymbol(symbolset, image, p, style, scalefactor);
+      else {
+        /* just do nothing if no color has been set */
+        return MS_SUCCESS;
       }
-   }
-   if (image)
-   {
-      if (MS_RENDERER_PLUGIN(image->format)) {
-         rendererVTableObj *renderer = image->format->vtable;
-         shapeObj *offsetPolygon = NULL;
-         symbolObj *symbol = symbolset->symbol[style->symbol];
-         /* store a reference to the renderer to be used for freeing */
-         if(style->symbol)
-            symbol->renderer = renderer;
-
-         if (style->offsetx != 0 || style->offsety != 0) {
-            if(style->offsety==-99)
-               offsetPolygon = msOffsetPolyline(p, style->offsetx*scalefactor, -99);
-            else
-               offsetPolygon = msOffsetPolyline(p, style->offsetx*scalefactor,style->offsety*scalefactor);
-         } else {
-            offsetPolygon=p;
-         }
-         /* simple polygon drawing, without any specific symbol.
-          * also draws an optional outline */
-         if(style->symbol == 0 || symbol->type == MS_SYMBOL_SIMPLE) {
-            ret = renderer->renderPolygon(image,offsetPolygon,&style->color);
-            if(ret != MS_SUCCESS) goto cleanup;
-            if(MS_VALID_COLOR(style->outlinecolor)) {
-               strokeStyleObj s;
-               INIT_STROKE_STYLE(s);
-               s.color = &style->outlinecolor;
-               s.color->alpha = style->color.alpha;
-               s.width = (style->width == 0)?scalefactor:style->width*scalefactor;
-               s.width = MS_MIN(s.width, style->maxwidth);
-               s.width = MS_MAX(s.width, style->minwidth);
-               ret = renderer->renderLine(image,offsetPolygon,&s);
-            }
-            goto cleanup; /*finished plain polygon*/
-         } else if(symbol->type == MS_SYMBOL_HATCH) {
-            double width, spacing;
-
-            if(MS_VALID_COLOR(style->backgroundcolor)) {
-               ret = renderer->renderPolygon(image,offsetPolygon, &style->backgroundcolor);
-               if(ret != MS_SUCCESS) goto cleanup;
-            }
-            width = (style->width <= 0)?scalefactor:style->width*scalefactor;
-            width = MS_MIN(width, style->maxwidth);
-            width = MS_MAX(width, style->minwidth);
-            spacing = (style->size <= 0)?scalefactor:style->size*scalefactor;
-            spacing = MS_MIN(spacing, style->maxsize);
-            spacing = MS_MAX(spacing, style->minsize);
-            if(renderer->renderPolygonHatched) {
-               ret = renderer->renderPolygonHatched(image,offsetPolygon,spacing,width,style->angle, &style->color);
-            } else {
-               ret = msHatchPolygon(image,offsetPolygon,spacing,width,style->angle, &style->color);
-            }
-            goto cleanup;
-         }
-         else {
-            symbolStyleObj s;
-            int pw,ph;
-            imageObj *tile;
-            int seamless = 0;
-            switch(symbol->type) {
-            case MS_SYMBOL_PIXMAP:
-               if(MS_SUCCESS != msPreloadImageSymbol(renderer,symbol)) {
-                  ret = MS_FAILURE;
-                  goto cleanup;
-               }
-               break;
-            case MS_SYMBOL_TRUETYPE:
-               if(!symbol->full_font_path)
-                  symbol->full_font_path =  msStrdup(msLookupHashTable(&(symbolset->fontset->fonts),
-                                                     symbol->font));
-               if(!symbol->full_font_path) {
-                  msSetError(MS_MEMERR,"allocation error", "msDrawMArkerSymbol()");
-                  ret = MS_FAILURE;
-                  goto cleanup;
-               }
-               break;
-            case MS_SYMBOL_VECTOR:
-            case MS_SYMBOL_ELLIPSE:
-               break;
-            default:
-               msSetError(MS_MISCERR,"unsupported symbol type %d", "msDrawShadeSymbol()", symbol->type);
-               ret = MS_FAILURE;
-               goto cleanup;
-            }
+    }
+  }
+  if (image) {
+    if (MS_RENDERER_PLUGIN(image->format)) {
+      rendererVTableObj *renderer = image->format->vtable;
+      shapeObj *offsetPolygon = NULL;
+      symbolObj *symbol = symbolset->symbol[style->symbol];
+      /* store a reference to the renderer to be used for freeing */
+      if(style->symbol)
+        symbol->renderer = renderer;
+
+      if (style->offsetx != 0 || style->offsety != 0) {
+        if(style->offsety==-99)
+          offsetPolygon = msOffsetPolyline(p, style->offsetx*scalefactor, -99);
+        else
+          offsetPolygon = msOffsetPolyline(p, style->offsetx*scalefactor,style->offsety*scalefactor);
+      } else {
+        offsetPolygon=p;
+      }
+      /* simple polygon drawing, without any specific symbol.
+       * also draws an optional outline */
+      if(style->symbol == 0 || symbol->type == MS_SYMBOL_SIMPLE) {
+        ret = renderer->renderPolygon(image,offsetPolygon,&style->color);
+        if(ret != MS_SUCCESS) goto cleanup;
+        if(MS_VALID_COLOR(style->outlinecolor)) {
+          strokeStyleObj s;
+          INIT_STROKE_STYLE(s);
+          s.color = &style->outlinecolor;
+          s.color->alpha = style->color.alpha;
+          s.width = (style->width == 0)?scalefactor:style->width*scalefactor;
+          s.width = MS_MIN(s.width, style->maxwidth);
+          s.width = MS_MAX(s.width, style->minwidth);
+          ret = renderer->renderLine(image,offsetPolygon,&s);
+        }
+        goto cleanup; /*finished plain polygon*/
+      } else if(symbol->type == MS_SYMBOL_HATCH) {
+        double width, spacing;
+        double pattern[MS_MAXPATTERNLENGTH];
+        int i;
+
+        if(MS_VALID_COLOR(style->backgroundcolor)) {
+          ret = renderer->renderPolygon(image,offsetPolygon, &style->backgroundcolor);
+          if(ret != MS_SUCCESS) goto cleanup;
+        }
+        width = (style->width <= 0)?scalefactor:style->width*scalefactor;
+        width = MS_MIN(width, style->maxwidth*image->resolutionfactor);
+        width = MS_MAX(width, style->minwidth*image->resolutionfactor);
+        spacing = (style->size <= 0)?scalefactor:style->size*scalefactor;
+        spacing = MS_MIN(spacing, style->maxsize*image->resolutionfactor);
+        spacing = MS_MAX(spacing, style->minsize*image->resolutionfactor);
+
+        /* scale the pattern by the factor applied to the width */
+        for(i=0; i<style->patternlength; i++) {
+          pattern[i] = style->pattern[i]*width/style->width;
+        }
+
+        ret = msHatchPolygon(image,offsetPolygon,spacing,width,pattern,style->patternlength,style->angle, &style->color);
+        goto cleanup;
+      } else {
+        symbolStyleObj s;
+        int pw,ph;
+        imageObj *tile;
+        int seamless = 0;
 
-            INIT_SYMBOL_STYLE(s);
-            computeSymbolStyle(&s,style,symbol,scalefactor);
-            s.style = style;
 
-            if (!s.color && !s.outlinecolor && symbol->type != MS_SYMBOL_PIXMAP) {
-               ret = MS_SUCCESS; // nothing to do (colors are required except for PIXMAP symbols
-               goto cleanup;
+        switch(symbol->type) {
+          case MS_SYMBOL_PIXMAP:
+            if(MS_SUCCESS != msPreloadImageSymbol(renderer,symbol)) {
+              ret = MS_FAILURE;
+              goto cleanup;
             }
-
-            if(s.backgroundcolor) {
-               ret = renderer->renderPolygon(image,offsetPolygon, s.backgroundcolor);
-               if(ret != MS_SUCCESS) goto cleanup;
-            }
-
-            if(s.scale != 1) {
-               pw = MS_NINT(symbol->sizex * s.scale + s.gap)+1;
-               ph = MS_NINT(symbol->sizey * s.scale + s.gap)+1;
-            } else {
-               pw = symbol->sizex + s.gap;
-               ph = symbol->sizey + s.gap;
+            break;
+          case MS_SYMBOL_TRUETYPE:
+            if(!symbol->full_font_path)
+              symbol->full_font_path =  msStrdup(msLookupHashTable(&(symbolset->fontset->fonts),
+                                                 symbol->font));
+            if(!symbol->full_font_path) {
+              msSetError(MS_MEMERR,"allocation error", "msDrawMarkerSymbol()");
+              ret = MS_FAILURE;
+              goto cleanup;
             }
-            if(pw<1) pw=1;
-            if(ph<1) ph=1;
-
-            /* if we're doing vector symbols with an antialiased pixel rendererer, we want to enable
-             * seamless mode, i.e. comute a tile that accounts for the blending of neighbouring
-             * tiles at the tile border
-             */
-            if(symbol->type == MS_SYMBOL_VECTOR && style->gap == 0 &&
-                  (image->format->renderer == MS_RENDER_WITH_AGG ||
-                   image->format->renderer == MS_RENDER_WITH_CAIRO_RASTER)) {
-               seamless = 1;
+            break;
+          case MS_SYMBOL_SVG:
+#ifdef USE_SVG_CAIRO
+            if(MS_SUCCESS != msPreloadSVGSymbol(symbol)) {
+              ret = MS_FAILURE;
+              goto cleanup;
             }
-            tile = getTile(image,symbol,&s,pw,ph,seamless);
-            ret = renderer->renderPolygonTiled(image,offsetPolygon, tile);
-         }
+#else
+            msSetError(MS_SYMERR, "SVG symbol support is not enabled.", "msDrawMarkerSymbol()");
+            return MS_FAILURE;
+#endif
+            break;
+          case MS_SYMBOL_VECTOR:
+          case MS_SYMBOL_ELLIPSE:
+            break;
+          default:
+            msSetError(MS_MISCERR,"unsupported symbol type %d", "msDrawShadeSymbol()", symbol->type);
+            ret = MS_FAILURE;
+            goto cleanup;
+        }
+
+        INIT_SYMBOL_STYLE(s);
+        computeSymbolStyle(&s,style,symbol,scalefactor,image->resolutionfactor);
+        s.style = style;
+
+        if (!s.color && !s.outlinecolor && symbol->type != MS_SYMBOL_PIXMAP && symbol->type != MS_SYMBOL_SVG) {
+          ret = MS_SUCCESS; /* nothing to do (colors are required except for PIXMAP symbols */
+          goto cleanup;
+        }
+
+        if(s.backgroundcolor) {
+          ret = renderer->renderPolygon(image,offsetPolygon, s.backgroundcolor);
+          if(ret != MS_SUCCESS) goto cleanup;
+        }
+
+        if(s.scale != 1) {
+          if (s.gap > 0) {
+            pw = MS_MAX(MS_NINT(s.gap),symbol->sizex * s.scale);
+            ph = MS_MAX(MS_NINT(s.gap),symbol->sizey * s.scale);
+          } else {
+            pw = MS_NINT(symbol->sizex * s.scale);
+            ph = MS_NINT(symbol->sizey * s.scale);
+          }
+        } else {
+          if (s.gap > 0) {
+            pw = MS_MAX(s.gap,symbol->sizex);
+            ph = MS_MAX(s.gap,symbol->sizey);
+          } else {
+            pw = symbol->sizex;
+            ph = symbol->sizey;
+          }
+        }
+        if(pw<1) pw=1;
+        if(ph<1) ph=1;
+
+        /* if we're doing vector symbols with an antialiased pixel rendererer, we want to enable
+         * seamless mode, i.e. comute a tile that accounts for the blending of neighbouring
+         * tiles at the tile border
+         */
+        if(symbol->type == MS_SYMBOL_VECTOR && style->gap == 0 &&
+            (image->format->renderer == MS_RENDER_WITH_AGG ||
+             image->format->renderer == MS_RENDER_WITH_CAIRO_RASTER)) {
+          seamless = 1;
+        }
+        tile = getTile(image,symbol,&s,pw,ph,seamless);
+        ret = renderer->renderPolygonTiled(image,offsetPolygon, tile);
+      }
 
 cleanup:
-         if (offsetPolygon != p) {
-            msFreeShape(offsetPolygon);
-            msFree(offsetPolygon);
-         }
-         return ret;
+      if (offsetPolygon != p) {
+        msFreeShape(offsetPolygon);
+        msFree(offsetPolygon);
       }
-      else if( MS_RENDERER_IMAGEMAP(image->format) )
-         msDrawShadeSymbolIM(symbolset, image, p, style, scalefactor);
-   }
-   return ret;
+      return ret;
+    } else if( MS_RENDERER_IMAGEMAP(image->format) )
+      msDrawShadeSymbolIM(symbolset, image, p, style, scalefactor);
+  }
+  return ret;
 }
 
 int msDrawMarkerSymbol(symbolSetObj *symbolset,imageObj *image, pointObj *p, styleObj *style,
                        double scalefactor)
 {
-   int ret = MS_SUCCESS;
-   if (!p)
-      return MS_SUCCESS;
-   if (style->symbol >= symbolset->numsymbols || style->symbol <= 0)
-      return MS_SUCCESS; /* no such symbol, 0 is OK   */
-
-   if (image)
-   {
-      if(MS_RENDERER_PLUGIN(image->format)) {
-         rendererVTableObj *renderer = image->format->vtable;
-         symbolStyleObj s;
-         double p_x,p_y;
-         symbolObj *symbol = symbolset->symbol[style->symbol];
-         /* store a reference to the renderer to be used for freeing */
-         symbol->renderer = renderer;
-         switch (symbol->type) {
-         case (MS_SYMBOL_TRUETYPE): {
-            if(!symbol->full_font_path)
-               symbol->full_font_path =  msStrdup(msLookupHashTable(&(symbolset->fontset->fonts),
-                                                  symbol->font));
-            if(!symbol->full_font_path) {
-               msSetError(MS_MEMERR,"allocation error", "msDrawMArkerSymbol()");
-               return MS_FAILURE;
-            }
-         }
-         break;
-         case (MS_SYMBOL_PIXMAP): {
-            if(!symbol->pixmap_buffer) {
-               if(MS_SUCCESS != msPreloadImageSymbol(renderer,symbol))
-                  return MS_FAILURE;
-            }
-         }
-         break;
-         }
-         s.style = style;
-         computeSymbolStyle(&s,style,symbol,scalefactor);
-         s.style = style;
-         if (!s.color && !s.outlinecolor && symbol->type != MS_SYMBOL_PIXMAP)
-            return MS_SUCCESS; // nothing to do if no color, except for pixmap symbols
-
-
-
-         //TODO: skip the drawing of the symbol if it's smaller than a pixel ?
-         /*
-         if (s.size < 1)
-         	return; // size too small
-          */
-
-         p_x = p->x + style->offsetx * scalefactor;
-         p_y = p->y + style->offsety * scalefactor;
-
-         if(renderer->use_imagecache) {
-            imageObj *tile = getTile(image, symbol, &s, -1, -1,0);
-            if(tile!=NULL)
-               return renderer->renderTile(image, tile, p_x, p_y);
-            else {
-               msSetError(MS_RENDERERERR, "problem creating cached tile", "msDrawMarkerSymbol()");
-               return MS_FAILURE;
-            }
-         }
-         switch (symbol->type) {
-         case (MS_SYMBOL_TRUETYPE): {
-            assert(symbol->full_font_path);
-            ret = renderer->renderTruetypeSymbol(image, p_x, p_y, symbol, &s);
-
-         }
-         break;
-         case (MS_SYMBOL_PIXMAP): {
-            assert(symbol->pixmap_buffer);
-            ret = renderer->renderPixmapSymbol(image,p_x,p_y,symbol,&s);
-         }
-         break;
-         case (MS_SYMBOL_ELLIPSE): {
-            ret = renderer->renderEllipseSymbol(image, p_x, p_y,symbol, &s);
-         }
-         break;
-         case (MS_SYMBOL_VECTOR): {
-            ret = renderer->renderVectorSymbol(image, p_x, p_y, symbol, &s);
-         }
-         break;
-         default:
-            break;
-         }
-         return ret;
+  int ret = MS_SUCCESS;
+  if (!p)
+    return MS_SUCCESS;
+  if (style->symbol >= symbolset->numsymbols || style->symbol <= 0)
+    return MS_SUCCESS; /* no such symbol, 0 is OK   */
+
+  if (image) {
+    if(MS_RENDERER_PLUGIN(image->format)) {
+      rendererVTableObj *renderer = image->format->vtable;
+      symbolStyleObj s;
+      double p_x,p_y;
+      symbolObj *symbol = symbolset->symbol[style->symbol];
+      /* store a reference to the renderer to be used for freeing */
+      symbol->renderer = renderer;
+      switch (symbol->type) {
+        case (MS_SYMBOL_TRUETYPE): {
+          if (!symbol->full_font_path)
+            symbol->full_font_path = msStrdup(msLookupHashTable(&(symbolset->fontset->fonts),
+                                              symbol->font));
+          if (!symbol->full_font_path) {
+            msSetError(MS_MEMERR, "allocation error", "msDrawMarkerSymbol()");
+            return MS_FAILURE;
+          }
+        }
+        break;
+        case (MS_SYMBOL_PIXMAP): {
+          if (!symbol->pixmap_buffer) {
+            if (MS_SUCCESS != msPreloadImageSymbol(renderer, symbol))
+              return MS_FAILURE;
+          }
+        }
+        break;
+
+        case (MS_SYMBOL_SVG): {
+#ifdef USE_SVG_CAIRO
+          if (!symbol->renderer_cache) {
+            if (MS_SUCCESS != msPreloadSVGSymbol(symbol))
+              return MS_FAILURE;
+          }
+#else
+          msSetError(MS_SYMERR, "SVG symbol support is not enabled.", "msDrawMarkerSymbol()");
+          return MS_FAILURE;
+#endif
+        }
+        break;
+      }
+
+      s.style = style;
+      computeSymbolStyle(&s,style,symbol,scalefactor,image->resolutionfactor);
+      s.style = style;
+      if (!s.color && !s.outlinecolor && symbol->type != MS_SYMBOL_PIXMAP &&
+          symbol->type != MS_SYMBOL_SVG) {
+        return MS_SUCCESS; // nothing to do if no color, except for pixmap symbols
+      }
+
+
+
+      /* TODO: skip the drawing of the symbol if it's smaller than a pixel ?
+      if (s.size < 1)
+       return; // size too small
+       */
+
+      p_x = p->x;
+      p_y = p->y;
+
+      if (style->polaroffsetpixel != 0 ||
+          style->polaroffsetangle != 0) {
+        double angle = style->polaroffsetangle * MS_DEG_TO_RAD;
+        p_x +=  (style->polaroffsetpixel * cos(-angle)) * scalefactor;
+        p_y +=  (style->polaroffsetpixel * sin(-angle)) * scalefactor;
+      }
+
+      p_x +=  style->offsetx * scalefactor;
+      p_y +=  style->offsety * scalefactor;
+
+      if(symbol->anchorpoint_x != 0.5 || symbol->anchorpoint_y != 0.5) {
+        double sx,sy;
+        double ox, oy;
+        msGetMarkerSize(symbolset, style, &sx, &sy, scalefactor);
+        ox = (0.5 - symbol->anchorpoint_x) * sx;
+        oy = (0.5 - symbol->anchorpoint_y) * sy;
+        if(s.rotation != 0) {
+          double sina, cosa;
+          double rox,roy;
+          sina = sin(-s.rotation);
+          cosa = cos(-s.rotation);
+          rox = ox * cosa - oy * sina;
+          roy = ox * sina + oy * cosa;
+          p_x += rox;
+          p_y += roy;
+        } else {
+          p_x += ox;
+          p_y += oy;
+        }
+      }
+
+      if(renderer->use_imagecache) {
+        imageObj *tile = getTile(image, symbol, &s, -1, -1,0);
+        if(tile!=NULL)
+          return renderer->renderTile(image, tile, p_x, p_y);
+        else {
+          msSetError(MS_RENDERERERR, "problem creating cached tile", "msDrawMarkerSymbol()");
+          return MS_FAILURE;
+        }
+      }
+      switch (symbol->type) {
+        case (MS_SYMBOL_TRUETYPE): {
+          assert(symbol->full_font_path);
+          ret = renderer->renderTruetypeSymbol(image, p_x, p_y, symbol, &s);
+
+        }
+        break;
+        case (MS_SYMBOL_PIXMAP): {
+          assert(symbol->pixmap_buffer);
+          ret = renderer->renderPixmapSymbol(image,p_x,p_y,symbol,&s);
+        }
+        break;
+        case (MS_SYMBOL_ELLIPSE): {
+          ret = renderer->renderEllipseSymbol(image, p_x, p_y,symbol, &s);
+        }
+        break;
+        case (MS_SYMBOL_VECTOR): {
+          ret = renderer->renderVectorSymbol(image, p_x, p_y, symbol, &s);
+        }
+        break;
+        case (MS_SYMBOL_SVG): {
+          if (renderer->supports_svg) {
+            ret = renderer->renderSVGSymbol(image, p_x, p_y, symbol, &s);
+          } else {
+#ifdef USE_SVG_CAIRO
+            ret = msRenderRasterizedSVGSymbol(image, p_x,p_y, symbol, &s);
+#else
+            msSetError(MS_SYMERR, "SVG symbol support is not enabled.", "msDrawMarkerSymbol()");
+            return MS_FAILURE;
+#endif
+          }
+        }
+        break;
+        default:
+          break;
       }
-      else if( MS_RENDERER_IMAGEMAP(image->format) )
-         msDrawMarkerSymbolIM(symbolset, image, p, style, scalefactor);
+      return ret;
+    } else if( MS_RENDERER_IMAGEMAP(image->format) )
+      msDrawMarkerSymbolIM(symbolset, image, p, style, scalefactor);
 
-   }
-   return ret;
+  }
+  return ret;
 }
 
 
@@ -789,106 +943,133 @@ int msDrawMarkerSymbol(symbolSetObj *symbolset,imageObj *image, pointObj *p, sty
 ** Render the text (no background effects) for a label.
  */
 int msDrawText(imageObj *image, pointObj labelPnt, char *string,
-               labelObj *label, fontSetObj *fontset, double scalefactor) {
-   int nReturnVal = -1;
-   if (image) {
-      if (MS_RENDERER_PLUGIN(image->format)) {
-         labelStyleObj s;
-         rendererVTableObj *renderer = image->format->vtable;
-         double x, y;
-         if (!string || !strlen(string))
-            return (0); // not errors, just don't want to do anything
-
-
-         if(computeLabelStyle(&s,label,fontset,scalefactor) == MS_FAILURE) {
-            return MS_FAILURE;
-         }
-         if(s.rotation == 0 && !MS_RENDERER_KML(image->format)) {
-            x = MS_NINT(labelPnt.x);
-            y = MS_NINT(labelPnt.y);
-         } else {
-            x = labelPnt.x;
-            y = labelPnt.y;
-         }
-         if (label->type == MS_TRUETYPE) {
-            if(MS_VALID_COLOR(label->shadowcolor)) {
-               s.color = &label->shadowcolor;
-               //FIXME labelpoint for rotated label
-               renderer->renderGlyphs(image,
-                                      x + scalefactor * label->shadowsizex,y + scalefactor * label->shadowsizey,
-                                      &s,string);
-            }
-
-            s.color= &label->color;
-            if(MS_VALID_COLOR(label->outlinecolor)) {
-               s.outlinecolor = &label->outlinecolor;
-               s.outlinewidth = label->outlinewidth * s.size/label->size;
-            }
-            return renderer->renderGlyphs(image,x,y,&s,string);
-         } else if(label->type == MS_BITMAP) {
-            s.size = MS_NINT(s.size);
-            s.color= &label->color;
-            s.size = MS_MIN(s.size,5); /* only have 5 bitmap fonts */
-            if(!renderer->supports_bitmap_fonts || !renderer->bitmapFontMetrics[MS_NINT(s.size)]) {
-               msSetError(MS_RENDERERERR, "selected renderer does not support bitmap fonts or this particular size", "msDrawText()");
-               return MS_FAILURE;
-            }
-            return renderer->renderBitmapGlyphs(image,x,y,&s,string);
-         }
+               labelObj *label, fontSetObj *fontset, double scalefactor)
+{
+  int nReturnVal = -1;
+  if (image) {
+    if (MS_RENDERER_PLUGIN(image->format)) {
+      labelStyleObj s;
+      rendererVTableObj *renderer = image->format->vtable;
+      double x, y;
+      if (!string || !strlen(string))
+        return (0); /* not errors, just don't want to do anything */
+
+
+      if(computeLabelStyle(&s,label,fontset,scalefactor,image->resolutionfactor) == MS_FAILURE) {
+        return MS_FAILURE;
+      }
+      if(s.rotation == 0 && !MS_RENDERER_KML(image->format)) {
+        x = MS_NINT(labelPnt.x);
+        y = MS_NINT(labelPnt.y);
+      } else {
+        x = labelPnt.x;
+        y = labelPnt.y;
+      }
+      if (label->type == MS_TRUETYPE) {
+        if(MS_VALID_COLOR(label->shadowcolor)) {
+          s.color = &label->shadowcolor;
+          /* FIXME labelpoint for rotated label */
+          renderer->renderGlyphs(image,
+                                 x + scalefactor * label->shadowsizex,y + scalefactor * label->shadowsizey,
+                                 &s,string);
+        }
+
+        s.color= &label->color;
+        if(MS_VALID_COLOR(label->outlinecolor)) {
+          s.outlinecolor = &label->outlinecolor;
+          s.outlinewidth = label->outlinewidth * s.size/label->size;
+        }
+        return renderer->renderGlyphs(image,x,y,&s,string);
+      } else if(label->type == MS_BITMAP) {
+        s.size = MS_NINT(s.size);
+        s.color= &label->color;
+        s.size = MS_MIN(s.size,5); /* only have 5 bitmap fonts */
+        if(!renderer->supports_bitmap_fonts || !renderer->bitmapFontMetrics[MS_NINT(s.size)]) {
+          msSetError(MS_RENDERERERR, "selected renderer does not support bitmap fonts or this particular size", "msDrawText()");
+          return MS_FAILURE;
+        }
+        return renderer->renderBitmapGlyphs(image,x,y,&s,string);
       }
-      else if( MS_RENDERER_IMAGEMAP(image->format) )
-         nReturnVal = msDrawTextIM(image, labelPnt, string, label, fontset, scalefactor);
-   }
-   return nReturnVal;
+    } else if( MS_RENDERER_IMAGEMAP(image->format) )
+      nReturnVal = msDrawTextIM(image, labelPnt, string, label, fontset, scalefactor);
+  }
+  return nReturnVal;
 }
 
 int msDrawTextLine(imageObj *image, char *string, labelObj *label, labelPathObj *labelpath, fontSetObj *fontset, double scalefactor)
 {
-   int nReturnVal = -1;
-   if(image) {
-      if (MS_RENDERER_PLUGIN(image->format)) {
-
-         rendererVTableObj *renderer = image->format->vtable;
-         labelStyleObj s;
-         if (!string || !strlen(string))
-            return (0); // not errors, just don't want to do anything
-         computeLabelStyle(&s, label, fontset, scalefactor);
-         if (label->type == MS_TRUETYPE) {
-            const char* string_ptr = string;
-            int i;
-            double x, y;
-            char glyph[11];
-            if(MS_VALID_COLOR(label->outlinecolor)) {
-               s.outlinecolor = &(label->outlinecolor);
-               s.outlinewidth = s.size/label->size * label->outlinewidth;
-               for (i = 0; i < labelpath->path.numpoints; i++) {
-                  if (msGetNextGlyph(&string_ptr, glyph) == -1)
-                     break; /* Premature end of string??? */
-                  s.rotation = labelpath->angles[i];
-                  x = labelpath->path.point[i].x;
-                  y = labelpath->path.point[i].y;
-                  renderer->renderGlyphs(image, x, y, &s, glyph);
-               }
-               string_ptr = string;
-            }
-            s.outlinecolor = NULL;
+  int nReturnVal = MS_SUCCESS;
+  if(image) {
+    if (MS_RENDERER_PLUGIN(image->format)) {
+
+      rendererVTableObj *renderer = image->format->vtable;
+      labelStyleObj s;
+      if (!string || !strlen(string))
+        return (MS_SUCCESS); /* not errors, just don't want to do anything */
+      if(computeLabelStyle(&s, label, fontset, scalefactor,image->resolutionfactor) != MS_SUCCESS) return MS_FAILURE;
+      if (label->type == MS_TRUETYPE) {
+        if(renderer->renderGlyphsLine) {
+          if(MS_VALID_COLOR(label->outlinecolor)) {
+            s.outlinecolor = &(label->outlinecolor);
+            s.outlinewidth = s.size/label->size * label->outlinewidth;
+          } else {
             s.outlinewidth = 0;
-            s.color = &(label->color);
+            s.outlinecolor = NULL;
+          }
+          s.color = &(label->color);
+          nReturnVal = renderer->renderGlyphsLine(image,labelpath,&s,string);
+        } else {
+          /*
+           * if the renderer doesn't support direct labelPath usage,
+           * decompose the string and send it down character by character
+           */
+          const char* string_ptr = string;
+          int i;
+          double x, y;
+          char glyph[11];
+
+          /*
+           * we first render all the outlines if present, so that the
+           * joining of characters stays correct
+           */
+          if(MS_VALID_COLOR(label->outlinecolor)) {
+            s.outlinecolor = &(label->outlinecolor);
+            s.outlinewidth = s.size/label->size * label->outlinewidth;
             for (i = 0; i < labelpath->path.numpoints; i++) {
-               if (msGetNextGlyph(&string_ptr, glyph) == -1)
-                  break; /* Premature end of string??? */
-
-               s.rotation = labelpath->angles[i];
-               x = labelpath->path.point[i].x;
-               y = labelpath->path.point[i].y;
-
-               renderer->renderGlyphs(image, x, y, &s, glyph);
+              if (msGetNextGlyph(&string_ptr, glyph) == -1)
+                break; /* Premature end of string??? */
+              s.rotation = labelpath->angles[i];
+              x = labelpath->path.point[i].x;
+              y = labelpath->path.point[i].y;
+              nReturnVal = renderer->renderGlyphs(image, x, y, &s, glyph);
+              if(nReturnVal != MS_SUCCESS) {
+                return nReturnVal;
+              }
+            }
+            string_ptr = string; /* reset to beginning of string */
+          }
+          s.outlinecolor = NULL;
+          s.outlinewidth = 0;
+          s.color = &(label->color);
+          for (i = 0; i < labelpath->path.numpoints; i++) {
+            if (msGetNextGlyph(&string_ptr, glyph) == -1)
+              break; /* Premature end of string??? */
+
+            s.rotation = labelpath->angles[i];
+            x = labelpath->path.point[i].x;
+            y = labelpath->path.point[i].y;
+
+            nReturnVal = renderer->renderGlyphs(image, x, y, &s, glyph);
+            if(nReturnVal != MS_SUCCESS) {
+              return nReturnVal;
             }
-         }
+          }
+        }
       }
-   }
+    }
+  }
 
-   return nReturnVal;
+  return nReturnVal;
 }
 
 
@@ -898,42 +1079,43 @@ int msDrawTextLine(imageObj *image, char *string, labelObj *label, labelPathObj
 /************************************************************************/
 int msCircleDrawLineSymbol(symbolSetObj *symbolset, imageObj *image, pointObj *p, double r, styleObj *style, double scalefactor)
 {
-   shapeObj *circle;
-   if (!image) return MS_FAILURE;
-   circle = msRasterizeArc(p->x, p->y, r, 0, 360, 0);
-   if (!circle) return MS_FAILURE;
-   msDrawLineSymbol(symbolset, image, circle, style, scalefactor);
-   msFreeShape(circle);
-   msFree(circle);
-   return MS_SUCCESS;
+  shapeObj *circle;
+  if (!image) return MS_FAILURE;
+  circle = msRasterizeArc(p->x, p->y, r, 0, 360, 0);
+  if (!circle) return MS_FAILURE;
+  msDrawLineSymbol(symbolset, image, circle, style, scalefactor);
+  msFreeShape(circle);
+  msFree(circle);
+  return MS_SUCCESS;
 }
 
 int msCircleDrawShadeSymbol(symbolSetObj *symbolset, imageObj *image, pointObj *p, double r, styleObj *style, double scalefactor)
 {
-   shapeObj *circle;
-   if (!image) return MS_FAILURE;
-   circle = msRasterizeArc(p->x, p->y, r, 0, 360, 0);
-   if (!circle) return MS_FAILURE;
-   msDrawShadeSymbol(symbolset, image, circle, style, scalefactor);
-   msFreeShape(circle);
-   msFree(circle);
-   return MS_SUCCESS;
+  shapeObj *circle;
+  if (!image) return MS_FAILURE;
+  circle = msRasterizeArc(p->x, p->y, r, 0, 360, 0);
+  if (!circle) return MS_FAILURE;
+  msDrawShadeSymbol(symbolset, image, circle, style, scalefactor);
+  msFreeShape(circle);
+  msFree(circle);
+  return MS_SUCCESS;
 }
 
-int msDrawPieSlice(symbolSetObj *symbolset, imageObj *image, pointObj *p, styleObj *style, double radius, double start, double end) {
-
-   shapeObj *circle;
-   double center_x = p->x;
-   double center_y = p->y;
-   if (!image) return MS_FAILURE;
-   if(style->offsetx>0) {
-      center_x+=style->offsetx*cos(((-start-end)*MS_PI/360.));
-      center_y-=style->offsetx*sin(((-start-end)*MS_PI/360.));
-   }
-   circle = msRasterizeArc(center_x, center_y, radius, start, end, 1);
-   if (!circle) return MS_FAILURE;
-   msDrawShadeSymbol(symbolset, image, circle, style, 1.0);
-   msFreeShape(circle);
-   msFree(circle);
-   return MS_SUCCESS;
+int msDrawPieSlice(symbolSetObj *symbolset, imageObj *image, pointObj *p, styleObj *style, double radius, double start, double end)
+{
+
+  shapeObj *circle;
+  double center_x = p->x;
+  double center_y = p->y;
+  if (!image) return MS_FAILURE;
+  if(style->offsetx>0) {
+    center_x+=style->offsetx*cos(((-start-end)*MS_PI/360.));
+    center_y-=style->offsetx*sin(((-start-end)*MS_PI/360.));
+  }
+  circle = msRasterizeArc(center_x, center_y, radius, start, end, 1);
+  if (!circle) return MS_FAILURE;
+  msDrawShadeSymbol(symbolset, image, circle, style, 1.0);
+  msFreeShape(circle);
+  msFree(circle);
+  return MS_SUCCESS;
 }
diff --git a/mapresample.c b/mapresample.c
index e283a70..087bec7 100644
--- a/mapresample.c
+++ b/mapresample.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -31,7 +31,7 @@
 #include "mapresample.h"
 #include "mapthread.h"
 
-MS_CVSID("$Id$")
+
 
 #ifndef MAX
 #  define MIN(a,b)      ((a<b) ? a : b)
@@ -48,31 +48,31 @@ MS_CVSID("$Id$")
 int InvGeoTransform( double *gt_in, double *gt_out )
 
 {
-    double	det, inv_det;
+  double  det, inv_det;
 
-    /* we assume a 3rd row that is [1 0 0] */
+  /* we assume a 3rd row that is [1 0 0] */
 
-    /* Compute determinate */
+  /* Compute determinate */
 
-    det = gt_in[1] * gt_in[5] - gt_in[2] * gt_in[4];
+  det = gt_in[1] * gt_in[5] - gt_in[2] * gt_in[4];
 
-    if( fabs(det) < 0.000000000000001 )
-        return 0;
+  if( fabs(det) < 0.000000000000001 )
+    return 0;
 
-    inv_det = 1.0 / det;
+  inv_det = 1.0 / det;
 
-    /* compute adjoint, and devide by determinate */
+  /* compute adjoint, and devide by determinate */
 
-    gt_out[1] =  gt_in[5] * inv_det;
-    gt_out[4] = -gt_in[4] * inv_det;
+  gt_out[1] =  gt_in[5] * inv_det;
+  gt_out[4] = -gt_in[4] * inv_det;
 
-    gt_out[2] = -gt_in[2] * inv_det;
-    gt_out[5] =  gt_in[1] * inv_det;
+  gt_out[2] = -gt_in[2] * inv_det;
+  gt_out[5] =  gt_in[1] * inv_det;
 
-    gt_out[0] = ( gt_in[2] * gt_in[3] - gt_in[0] * gt_in[5]) * inv_det;
-    gt_out[3] = (-gt_in[1] * gt_in[3] + gt_in[0] * gt_in[4]) * inv_det;
+  gt_out[0] = ( gt_in[2] * gt_in[3] - gt_in[0] * gt_in[5]) * inv_det;
+  gt_out[3] = (-gt_in[1] * gt_in[3] + gt_in[0] * gt_in[4]) * inv_det;
 
-    return 1;
+  return 1;
 }
 
 #if defined(USE_PROJ) && defined(USE_GDAL)
@@ -81,185 +81,169 @@ int InvGeoTransform( double *gt_in, double *gt_out )
 /*                      msNearestRasterResample()                       */
 /************************************************************************/
 
-static int 
-msNearestRasterResampler( imageObj *psSrcImage, rasterBufferObj *src_rb, 
+static int
+msNearestRasterResampler( imageObj *psSrcImage, rasterBufferObj *src_rb,
                           imageObj *psDstImage, rasterBufferObj *dst_rb,
                           int *panCMap,
                           SimpleTransformer pfnTransform, void *pCBData,
                           int debug )
 
 {
-    double	*x, *y; 
-    int		nDstX, nDstY;
-    int         *panSuccess;
-    int		nDstXSize = psDstImage->width;
-    int		nDstYSize = psDstImage->height;
-    int		nSrcXSize = psSrcImage->width;
-    int		nSrcYSize = psSrcImage->height;
-    int		nFailedPoints = 0, nSetPoints = 0;
-    
-
-    x = (double *) msSmallMalloc( sizeof(double) * nDstXSize );
-    y = (double *) msSmallMalloc( sizeof(double) * nDstXSize );
-    panSuccess = (int *) msSmallMalloc( sizeof(int) * nDstXSize );
-
-    for( nDstY = 0; nDstY < nDstYSize; nDstY++ )
-    {        
-        for( nDstX = 0; nDstX < nDstXSize; nDstX++ )
-        {
-            x[nDstX] = nDstX + 0.5;
-            y[nDstX] = nDstY + 0.5;
-        }
+  double  *x, *y;
+  int   nDstX, nDstY;
+  int         *panSuccess;
+  int   nDstXSize = psDstImage->width;
+  int   nDstYSize = psDstImage->height;
+  int   nSrcXSize = psSrcImage->width;
+  int   nSrcYSize = psSrcImage->height;
+  int   nFailedPoints = 0, nSetPoints = 0;
+#ifndef USE_GD
+  assert(!MS_RENDERER_PLUGIN(psSrcImage->format) || src_rb->type != MS_BUFFER_GD);
+#endif
 
-        pfnTransform( pCBData, nDstXSize, x, y, panSuccess );
-        
-        for( nDstX = 0; nDstX < nDstXSize; nDstX++ )
-        {
-            int		nSrcX, nSrcY;
-            int		nValue = 0;
-
-            if( !panSuccess[nDstX] )
-            {
-                nFailedPoints++;
-                continue;
-            }
 
-            nSrcX = (int) x[nDstX];
-            nSrcY = (int) y[nDstX];
-
-            /*
-             * We test the original floating point values to 
-             * avoid errors related to asymmetric rounding around zero.
-             * (Also note bug #3120 regarding nearly redundent x/y < 0 checks).
-             */
-            if( x[nDstX] < 0.0 || y[nDstX] < 0.0
-                || nSrcX < 0 || nSrcY < 0 
-                || nSrcX >= nSrcXSize || nSrcY >= nSrcYSize )
-            {
-                continue;
-            }
+  x = (double *) msSmallMalloc( sizeof(double) * nDstXSize );
+  y = (double *) msSmallMalloc( sizeof(double) * nDstXSize );
+  panSuccess = (int *) msSmallMalloc( sizeof(int) * nDstXSize );
 
-            if( MS_RENDERER_PLUGIN(psSrcImage->format) )
-            {
-            	if(src_rb->type == MS_BUFFER_GD) {
-                    assert(!gdImageTrueColor(src_rb->data.gd_img));
-                    nValue = panCMap[src_rb->data.gd_img->pixels[nSrcY][nSrcX]];
-
-                    if( nValue == -1 )
-                        continue;
-
-                    nSetPoints++;
-                    dst_rb->data.gd_img->pixels[nDstY][nDstX] = nValue; 
-
-            	}
-            	else if( src_rb->type == MS_BUFFER_BYTE_RGBA )
-            	{
-                    int src_rb_off;
-                    rgbaArrayObj *src = &src_rb->data.rgba, *dst = &dst_rb->data.rgba;
-                    assert( src_rb && dst_rb );
-                    src_rb_off = nSrcX * src->pixel_step 
-                        + nSrcY * src->row_step;
-
-                    if( src->a == NULL || src->a[src_rb_off] == 255 )
-                    {
-                        int dst_rb_off;
-
-                        dst_rb_off = nDstX * dst->pixel_step 
-                            + nDstY * dst->row_step;
-
-                        nSetPoints++;
-
-                        dst->r[dst_rb_off] = src->r[src_rb_off];
-                        dst->g[dst_rb_off] = src->g[src_rb_off];
-                        dst->b[dst_rb_off] = src->b[src_rb_off];
-                        if( dst->a )
-                            dst->a[dst_rb_off] = 255;
-                    }
-                    else if( src->a[src_rb_off] != 0 )
-                    {
-                        int dst_rb_off;
-
-                        dst_rb_off = nDstX * dst->pixel_step 
-                            + nDstY * dst->row_step;
-
-                        nSetPoints++;
-
-                        /* actual alpha blending is required */
-                        msAlphaBlendPM( src->r[src_rb_off],
-                                        src->g[src_rb_off],
-                                        src->b[src_rb_off],
-                                        src->a[src_rb_off],
-                                        dst->r + dst_rb_off, 
-                                        dst->g + dst_rb_off, 
-                                        dst->b + dst_rb_off, 
-                                        dst->a ? dst->a + dst_rb_off : NULL  );
-
-                    }
-            	}
-            }
-            else if( MS_RENDERER_RAWDATA(psSrcImage->format) )
-            {
-                int band, src_off, dst_off;
-                
-                src_off = nSrcX + nSrcY * psSrcImage->width;
-
-                if( !MS_GET_BIT(psSrcImage->img_mask,src_off) )
-                    continue;
-
-                nSetPoints++;
-
-                dst_off = nDstX + nDstY * psDstImage->width;
-
-                MS_SET_BIT(psDstImage->img_mask,dst_off);
-
-                for( band = 0; band < psSrcImage->format->bands; band++ )
-                {
-                    if( psSrcImage->format->imagemode == MS_IMAGEMODE_INT16 )
-                    {
-                        psDstImage->img.raw_16bit[dst_off] 
-                            = psSrcImage->img.raw_16bit[src_off];
-                    }
-                    else if( psSrcImage->format->imagemode 
-                             == MS_IMAGEMODE_FLOAT32)
-                    {
-                        psDstImage->img.raw_float[dst_off] 
-                            = psSrcImage->img.raw_float[src_off];
-                    }
-                    else if(psSrcImage->format->imagemode == MS_IMAGEMODE_BYTE)
-                    {
-                        psDstImage->img.raw_byte[dst_off] 
-                            = psSrcImage->img.raw_byte[src_off];
-                    }
-                    else
-                    {
-                        assert( 0 );
-                    }
-                    src_off += psSrcImage->width * psSrcImage->height;
-                    dst_off += psDstImage->width * psDstImage->height;
-                }
-            }
-        }
+  for( nDstY = 0; nDstY < nDstYSize; nDstY++ ) {
+    for( nDstX = 0; nDstX < nDstXSize; nDstX++ ) {
+      x[nDstX] = nDstX + 0.5;
+      y[nDstX] = nDstY + 0.5;
     }
 
-    free( panSuccess );
-    free( x );
-    free( y );
+    pfnTransform( pCBData, nDstXSize, x, y, panSuccess );
+
+    for( nDstX = 0; nDstX < nDstXSize; nDstX++ ) {
+      int   nSrcX, nSrcY;
+
+      if( !panSuccess[nDstX] ) {
+        nFailedPoints++;
+        continue;
+      }
+
+      nSrcX = (int) x[nDstX];
+      nSrcY = (int) y[nDstX];
+
+      /*
+       * We test the original floating point values to
+       * avoid errors related to asymmetric rounding around zero.
+       * (Also note bug #3120 regarding nearly redundent x/y < 0 checks).
+       */
+      if( x[nDstX] < 0.0 || y[nDstX] < 0.0
+          || nSrcX < 0 || nSrcY < 0
+          || nSrcX >= nSrcXSize || nSrcY >= nSrcYSize ) {
+        continue;
+      }
+
+      if( MS_RENDERER_PLUGIN(psSrcImage->format) ) {
+#ifdef USE_GD
+        if(src_rb->type == MS_BUFFER_GD) {
+          int   nValue = 0;
+          assert(!gdImageTrueColor(src_rb->data.gd_img));
+          nValue = panCMap[src_rb->data.gd_img->pixels[nSrcY][nSrcX]];
+
+          if( nValue == -1 )
+            continue;
 
-/* -------------------------------------------------------------------- */
-/*      Some debugging output.                                          */
-/* -------------------------------------------------------------------- */
-    if( nFailedPoints > 0 && debug )
-    {
-        char	szMsg[256];
-        
-        sprintf( szMsg, 
-                 "msNearestRasterResampler: "
-                 "%d failed to transform, %d actually set.\n", 
-                 nFailedPoints, nSetPoints );
-        msDebug( szMsg );
-    }
+          nSetPoints++;
+          dst_rb->data.gd_img->pixels[nDstY][nDstX] = nValue;
 
-    return 0;
+        } else
+#endif
+          if( src_rb->type == MS_BUFFER_BYTE_RGBA ) {
+            int src_rb_off;
+            rgbaArrayObj *src = &src_rb->data.rgba, *dst = &dst_rb->data.rgba;
+            assert( src_rb && dst_rb );
+            src_rb_off = nSrcX * src->pixel_step
+                         + nSrcY * src->row_step;
+
+            if( src->a == NULL || src->a[src_rb_off] == 255 ) {
+              int dst_rb_off;
+
+              dst_rb_off = nDstX * dst->pixel_step
+                           + nDstY * dst->row_step;
+
+              nSetPoints++;
+
+              dst->r[dst_rb_off] = src->r[src_rb_off];
+              dst->g[dst_rb_off] = src->g[src_rb_off];
+              dst->b[dst_rb_off] = src->b[src_rb_off];
+              if( dst->a )
+                dst->a[dst_rb_off] = 255;
+            } else if( src->a[src_rb_off] != 0 ) {
+              int dst_rb_off;
+
+              dst_rb_off = nDstX * dst->pixel_step
+                           + nDstY * dst->row_step;
+
+              nSetPoints++;
+
+              /* actual alpha blending is required */
+              msAlphaBlendPM( src->r[src_rb_off],
+                              src->g[src_rb_off],
+                              src->b[src_rb_off],
+                              src->a[src_rb_off],
+                              dst->r + dst_rb_off,
+                              dst->g + dst_rb_off,
+                              dst->b + dst_rb_off,
+                              dst->a ? dst->a + dst_rb_off : NULL  );
+
+            }
+          }
+      } else if( MS_RENDERER_RAWDATA(psSrcImage->format) ) {
+        int band, src_off, dst_off;
+
+        src_off = nSrcX + nSrcY * psSrcImage->width;
+
+        if( !MS_GET_BIT(psSrcImage->img_mask,src_off) )
+          continue;
+
+        nSetPoints++;
+
+        dst_off = nDstX + nDstY * psDstImage->width;
+
+        MS_SET_BIT(psDstImage->img_mask,dst_off);
+
+        for( band = 0; band < psSrcImage->format->bands; band++ ) {
+          if( psSrcImage->format->imagemode == MS_IMAGEMODE_INT16 ) {
+            psDstImage->img.raw_16bit[dst_off]
+              = psSrcImage->img.raw_16bit[src_off];
+          } else if( psSrcImage->format->imagemode
+                     == MS_IMAGEMODE_FLOAT32) {
+            psDstImage->img.raw_float[dst_off]
+              = psSrcImage->img.raw_float[src_off];
+          } else if(psSrcImage->format->imagemode == MS_IMAGEMODE_BYTE) {
+            psDstImage->img.raw_byte[dst_off]
+              = psSrcImage->img.raw_byte[src_off];
+          } else {
+            assert( 0 );
+          }
+          src_off += psSrcImage->width * psSrcImage->height;
+          dst_off += psDstImage->width * psDstImage->height;
+        }
+      }
+    }
+  }
+
+  free( panSuccess );
+  free( x );
+  free( y );
+
+  /* -------------------------------------------------------------------- */
+  /*      Some debugging output.                                          */
+  /* -------------------------------------------------------------------- */
+  if( nFailedPoints > 0 && debug ) {
+    char  szMsg[256];
+
+    sprintf( szMsg,
+             "msNearestRasterResampler: "
+             "%d failed to transform, %d actually set.\n",
+             nFailedPoints, nSetPoints );
+    msDebug( szMsg );
+  }
+
+  return 0;
 }
 
 /************************************************************************/
@@ -268,274 +252,259 @@ msNearestRasterResampler( imageObj *psSrcImage, rasterBufferObj *src_rb,
 
 static void msSourceSample( imageObj *psSrcImage, rasterBufferObj *rb,
                             int iSrcX, int iSrcY, double *padfPixelSum,
-                            double dfWeight, double *pdfWeightSum )    
+                            double dfWeight, double *pdfWeightSum )
 
 {
-    if( MS_RENDERER_PLUGIN(psSrcImage->format) )
-    {
-        assert(rb);
-        if(rb->type == MS_BUFFER_GD) {
-            assert(!gdImageTrueColor(rb->data.gd_img) );
-            padfPixelSum[0] += (dfWeight * rb->data.gd_img->pixels[iSrcY][iSrcX]);
-            *pdfWeightSum += dfWeight;
-        } else if(rb->type == MS_BUFFER_BYTE_RGBA) {
-            rgbaArrayObj *rgba = &(rb->data.rgba);
-            int rb_off = iSrcX * rgba->pixel_step + iSrcY * rgba->row_step;
-
-            if( rgba->a == NULL || rgba->a[rb_off] > 1 )
-            {
-                padfPixelSum[0] += rgba->r[rb_off] * dfWeight;
-                padfPixelSum[1] += rgba->g[rb_off] * dfWeight;
-                padfPixelSum[2] += rgba->b[rb_off] * dfWeight;
-                
-                if( rgba->a == NULL )
-                    *pdfWeightSum += dfWeight;
-                else
-                    *pdfWeightSum += dfWeight * (rgba->a[rb_off] / 255.0);
-            }
-        }
+  if( MS_RENDERER_PLUGIN(psSrcImage->format) ) {
+    rgbaArrayObj *rgba;
+    int rb_off;
+    assert(rb);
+#ifdef USE_GD
+    if(rb->type == MS_BUFFER_GD) {
+      assert(!gdImageTrueColor(rb->data.gd_img) );
+      padfPixelSum[0] += (dfWeight * rb->data.gd_img->pixels[iSrcY][iSrcX]);
+      *pdfWeightSum += dfWeight;
+      return;
     }
-    else if( MS_RENDERER_RAWDATA(psSrcImage->format) )
-    {
-        int band;
-        int src_off;
+#endif
+    assert(rb->type == MS_BUFFER_BYTE_RGBA);
+    rgba = &(rb->data.rgba);
+    rb_off = iSrcX * rgba->pixel_step + iSrcY * rgba->row_step;
 
-        src_off = iSrcX + iSrcY * psSrcImage->width;
+    if( rgba->a == NULL || rgba->a[rb_off] > 1 ) {
+      padfPixelSum[0] += rgba->r[rb_off] * dfWeight;
+      padfPixelSum[1] += rgba->g[rb_off] * dfWeight;
+      padfPixelSum[2] += rgba->b[rb_off] * dfWeight;
 
-        if( !MS_GET_BIT(psSrcImage->img_mask,src_off) )
-            return;
+      if( rgba->a == NULL )
+        *pdfWeightSum += dfWeight;
+      else
+        *pdfWeightSum += dfWeight * (rgba->a[rb_off] / 255.0);
+    }
+  } else if( MS_RENDERER_RAWDATA(psSrcImage->format) ) {
+    int band;
+    int src_off;
 
-        for( band = 0; band < psSrcImage->format->bands; band++ )
-        {
-            if( psSrcImage->format->imagemode == MS_IMAGEMODE_INT16 )
-            {
-                int	nValue;
+    src_off = iSrcX + iSrcY * psSrcImage->width;
 
-                nValue = psSrcImage->img.raw_16bit[src_off];
+    if( !MS_GET_BIT(psSrcImage->img_mask,src_off) )
+      return;
 
-                padfPixelSum[band] += dfWeight * nValue;
-            }
-            else if( psSrcImage->format->imagemode 
-                     == MS_IMAGEMODE_FLOAT32)
-            {
-                float fValue;
-
-                fValue = psSrcImage->img.raw_float[src_off];
-                    
-                padfPixelSum[band] += fValue * dfWeight;
-            }
-            else if(psSrcImage->format->imagemode == MS_IMAGEMODE_BYTE)
-            {
-                int nValue;
+    for( band = 0; band < psSrcImage->format->bands; band++ ) {
+      if( psSrcImage->format->imagemode == MS_IMAGEMODE_INT16 ) {
+        int nValue;
 
-                nValue = psSrcImage->img.raw_byte[src_off];
+        nValue = psSrcImage->img.raw_16bit[src_off];
 
-                padfPixelSum[band] += nValue * dfWeight;
-            }
-            else
-            {
-                assert( 0 );
-                return;
-            }
+        padfPixelSum[band] += dfWeight * nValue;
+      } else if( psSrcImage->format->imagemode
+                 == MS_IMAGEMODE_FLOAT32) {
+        float fValue;
 
-            src_off += psSrcImage->width * psSrcImage->height;
-        }
-        *pdfWeightSum += dfWeight;
+        fValue = psSrcImage->img.raw_float[src_off];
+
+        padfPixelSum[band] += fValue * dfWeight;
+      } else if(psSrcImage->format->imagemode == MS_IMAGEMODE_BYTE) {
+        int nValue;
+
+        nValue = psSrcImage->img.raw_byte[src_off];
+
+        padfPixelSum[band] += nValue * dfWeight;
+      } else {
+        assert( 0 );
+        return;
+      }
+
+      src_off += psSrcImage->width * psSrcImage->height;
     }
+    *pdfWeightSum += dfWeight;
+  }
 }
 
 /************************************************************************/
 /*                      msBilinearRasterResample()                      */
 /************************************************************************/
 
-static int 
-msBilinearRasterResampler( imageObj *psSrcImage, rasterBufferObj *src_rb, 
+static int
+msBilinearRasterResampler( imageObj *psSrcImage, rasterBufferObj *src_rb,
                            imageObj *psDstImage, rasterBufferObj *dst_rb,
                            int *panCMap,
                            SimpleTransformer pfnTransform, void *pCBData,
                            int debug )
 
 {
-    double	*x, *y; 
-    int		nDstX, nDstY, i;
-    int         *panSuccess;
-    int		nDstXSize = psDstImage->width;
-    int		nDstYSize = psDstImage->height;
-    int		nSrcXSize = psSrcImage->width;
-    int		nSrcYSize = psSrcImage->height;
-    int		nFailedPoints = 0, nSetPoints = 0;
-    double     *padfPixelSum;
-    int         bandCount = MAX(4,psSrcImage->format->bands);
-
-    padfPixelSum = (double *) msSmallMalloc(sizeof(double) * bandCount);
-    
-    
-
-    x = (double *) msSmallMalloc( sizeof(double) * nDstXSize );
-    y = (double *) msSmallMalloc( sizeof(double) * nDstXSize );
-    panSuccess = (int *) msSmallMalloc( sizeof(int) * nDstXSize );
-
-    for( nDstY = 0; nDstY < nDstYSize; nDstY++ )
-    {        
-        for( nDstX = 0; nDstX < nDstXSize; nDstX++ )
-        {
-            x[nDstX] = nDstX + 0.5;
-            y[nDstX] = nDstY + 0.5;
-        }
+  double  *x, *y;
+  int   nDstX, nDstY, i;
+  int         *panSuccess;
+  int   nDstXSize = psDstImage->width;
+  int   nDstYSize = psDstImage->height;
+  int   nSrcXSize = psSrcImage->width;
+  int   nSrcYSize = psSrcImage->height;
+  int   nFailedPoints = 0, nSetPoints = 0;
+  double     *padfPixelSum;
+  int         bandCount = MAX(4,psSrcImage->format->bands);
 
-        pfnTransform( pCBData, nDstXSize, x, y, panSuccess );
-        
-        for( nDstX = 0; nDstX < nDstXSize; nDstX++ )
-        {
-            int		nSrcX, nSrcY, nSrcX2, nSrcY2;
-            double      dfRatioX2, dfRatioY2, dfWeightSum = 0.0;
-
-            if( !panSuccess[nDstX] )
-            {
-                nFailedPoints++;
-                continue;
-            }
+  padfPixelSum = (double *) msSmallMalloc(sizeof(double) * bandCount);
 
-            /* 
-            ** Offset to treat TL pixel corners as pixel location instead
-            ** of the center. 
-            */
-            x[nDstX] -= 0.5; 
-            y[nDstX] -= 0.5;
-
-            nSrcX = (int) floor(x[nDstX]);
-            nSrcY = (int) floor(y[nDstX]);
-
-            nSrcX2 = nSrcX+1;
-            nSrcY2 = nSrcY+1;
-            
-            dfRatioX2 = x[nDstX] - nSrcX;
-            dfRatioY2 = y[nDstX] - nSrcY;
-
-            /* If we are right off the source, skip this pixel */
-            if( nSrcX2 < 0 || nSrcX >= nSrcXSize
-                || nSrcY2 < 0 || nSrcY >= nSrcYSize )
-                continue;
-
-            /* Trim in stuff one pixel off the edge */
-            nSrcX = MAX(nSrcX,0);
-            nSrcY = MAX(nSrcY,0);
-            nSrcX2 = MIN(nSrcX2,nSrcXSize-1);
-            nSrcY2 = MIN(nSrcY2,nSrcYSize-1);
-
-            memset( padfPixelSum, 0, sizeof(double) * bandCount);
-
-            msSourceSample( psSrcImage, src_rb, nSrcX, nSrcY, padfPixelSum, 
-                            (1.0 - dfRatioX2) * (1.0 - dfRatioY2),
-                            &dfWeightSum );
-            
-            msSourceSample( psSrcImage, src_rb, nSrcX2, nSrcY, padfPixelSum, 
-                            (dfRatioX2) * (1.0 - dfRatioY2),
-                            &dfWeightSum );
-            
-            msSourceSample( psSrcImage, src_rb, nSrcX, nSrcY2, padfPixelSum, 
-                            (1.0 - dfRatioX2) * (dfRatioY2),
-                            &dfWeightSum );
-            
-            msSourceSample( psSrcImage, src_rb, nSrcX2, nSrcY2, padfPixelSum, 
-                            (dfRatioX2) * (dfRatioY2),
-                            &dfWeightSum );
-
-            if( dfWeightSum == 0.0 )
-                continue;
-
-            for( i = 0; i < bandCount; i++ )
-                padfPixelSum[i] /= dfWeightSum;
-
-            if( MS_RENDERER_PLUGIN(psSrcImage->format) )
-            {
-            	assert(src_rb && dst_rb);
-            	if(src_rb->type == MS_BUFFER_GD) {
-                    int nResult;
-                    assert( !gdImageTrueColor(src_rb->data.gd_img) &&  !gdImageTrueColor(dst_rb->data.gd_img));
-                    nResult = panCMap[(int) padfPixelSum[0]];
-                    if( nResult != -1 )
-                    {                        
-                        nSetPoints++;
-                        dst_rb->data.gd_img->pixels[nDstY][nDstX] = nResult;
-                    }
-                }
-                else if( src_rb->type == MS_BUFFER_BYTE_RGBA ) {
-                    int dst_rb_off;
-                    assert( src_rb->type == dst_rb->type );
-	
-                    dst_rb_off = nDstX * dst_rb->data.rgba.pixel_step + nDstY * dst_rb->data.rgba.row_step;
-	
-                    nSetPoints++;
-	
-                    if( dfWeightSum > 0.001 )
-                    {
-                        unsigned char red, green, blue, alpha;
-                        
-                        red   = (unsigned char) MAX(0,MIN(255,padfPixelSum[0]));
-                        green = (unsigned char) MAX(0,MIN(255,padfPixelSum[1]));
-                        blue  = (unsigned char) MAX(0,MIN(255,padfPixelSum[2]));
-                        alpha = (unsigned char)MAX(0,MIN(255,255.5*dfWeightSum));
-                        
-                        msAlphaBlendPM( red, green, blue, alpha,
-                                        dst_rb->data.rgba.r + dst_rb_off, 
-                                        dst_rb->data.rgba.g + dst_rb_off, 
-                                        dst_rb->data.rgba.b + dst_rb_off, 
-                                        (dst_rb->data.rgba.a == NULL) ? NULL : dst_rb->data.rgba.a + dst_rb_off );
-                    }
-                }
-            }
-            else if( MS_RENDERER_RAWDATA(psSrcImage->format) )
-            {
-                int band;
-                int dst_off = nDstX + nDstY * psDstImage->width;
-
-                MS_SET_BIT(psDstImage->img_mask,dst_off);
-
-                for( band = 0; band < psSrcImage->format->bands; band++ )
-                {
-                    if( psSrcImage->format->imagemode == MS_IMAGEMODE_INT16 )
-                    {
-                        psDstImage->img.raw_16bit[dst_off]
-                            = (short) padfPixelSum[band];
-                    }
-                    else if( psSrcImage->format->imagemode == MS_IMAGEMODE_FLOAT32)
-                    {
-                        psDstImage->img.raw_float[dst_off]
-                            = (float) padfPixelSum[band];
-                    }
-                    else if( psSrcImage->format->imagemode == MS_IMAGEMODE_BYTE )
-                    {
-                        psDstImage->img.raw_byte[dst_off]
-                            = (unsigned char)MAX(0,MIN(255,padfPixelSum[band]));
-                    } 
-
-                    dst_off += psDstImage->width*psDstImage->height;
-                }
-            }
-        }
-    }
 
-    free( padfPixelSum );
-    free( panSuccess );
-    free( x );
-    free( y );
 
-/* -------------------------------------------------------------------- */
-/*      Some debugging output.                                          */
-/* -------------------------------------------------------------------- */
-    if( nFailedPoints > 0 && debug )
-    {
-        char	szMsg[256];
-        
-        sprintf( szMsg, 
-                 "msBilinearRasterResampler: "
-                 "%d failed to transform, %d actually set.\n", 
-                 nFailedPoints, nSetPoints );
-        msDebug( szMsg );
+  x = (double *) msSmallMalloc( sizeof(double) * nDstXSize );
+  y = (double *) msSmallMalloc( sizeof(double) * nDstXSize );
+  panSuccess = (int *) msSmallMalloc( sizeof(int) * nDstXSize );
+
+  for( nDstY = 0; nDstY < nDstYSize; nDstY++ ) {
+    for( nDstX = 0; nDstX < nDstXSize; nDstX++ ) {
+      x[nDstX] = nDstX + 0.5;
+      y[nDstX] = nDstY + 0.5;
     }
 
-    return 0;
+    pfnTransform( pCBData, nDstXSize, x, y, panSuccess );
+
+    for( nDstX = 0; nDstX < nDstXSize; nDstX++ ) {
+      int   nSrcX, nSrcY, nSrcX2, nSrcY2;
+      double      dfRatioX2, dfRatioY2, dfWeightSum = 0.0;
+
+      if( !panSuccess[nDstX] ) {
+        nFailedPoints++;
+        continue;
+      }
+
+      /*
+      ** Offset to treat TL pixel corners as pixel location instead
+      ** of the center.
+      */
+      x[nDstX] -= 0.5;
+      y[nDstX] -= 0.5;
+
+      nSrcX = (int) floor(x[nDstX]);
+      nSrcY = (int) floor(y[nDstX]);
+
+      nSrcX2 = nSrcX+1;
+      nSrcY2 = nSrcY+1;
+
+      dfRatioX2 = x[nDstX] - nSrcX;
+      dfRatioY2 = y[nDstX] - nSrcY;
+
+      /* If we are right off the source, skip this pixel */
+      if( nSrcX2 < 0 || nSrcX >= nSrcXSize
+          || nSrcY2 < 0 || nSrcY >= nSrcYSize )
+        continue;
+
+      /* Trim in stuff one pixel off the edge */
+      nSrcX = MAX(nSrcX,0);
+      nSrcY = MAX(nSrcY,0);
+      nSrcX2 = MIN(nSrcX2,nSrcXSize-1);
+      nSrcY2 = MIN(nSrcY2,nSrcYSize-1);
+
+      memset( padfPixelSum, 0, sizeof(double) * bandCount);
+
+      msSourceSample( psSrcImage, src_rb, nSrcX, nSrcY, padfPixelSum,
+                      (1.0 - dfRatioX2) * (1.0 - dfRatioY2),
+                      &dfWeightSum );
+
+      msSourceSample( psSrcImage, src_rb, nSrcX2, nSrcY, padfPixelSum,
+                      (dfRatioX2) * (1.0 - dfRatioY2),
+                      &dfWeightSum );
+
+      msSourceSample( psSrcImage, src_rb, nSrcX, nSrcY2, padfPixelSum,
+                      (1.0 - dfRatioX2) * (dfRatioY2),
+                      &dfWeightSum );
+
+      msSourceSample( psSrcImage, src_rb, nSrcX2, nSrcY2, padfPixelSum,
+                      (dfRatioX2) * (dfRatioY2),
+                      &dfWeightSum );
+
+      if( dfWeightSum == 0.0 )
+        continue;
+
+      for( i = 0; i < bandCount; i++ )
+        padfPixelSum[i] /= dfWeightSum;
+
+      if( MS_RENDERER_PLUGIN(psSrcImage->format) ) {
+        assert(src_rb && dst_rb);
+#ifdef USE_GD
+        if(src_rb->type == MS_BUFFER_GD) {
+          int nResult;
+          assert( !gdImageTrueColor(src_rb->data.gd_img) &&  !gdImageTrueColor(dst_rb->data.gd_img));
+          nResult = panCMap[(int) padfPixelSum[0]];
+          if( nResult != -1 ) {
+            nSetPoints++;
+            dst_rb->data.gd_img->pixels[nDstY][nDstX] = nResult;
+          }
+        } else
+#endif
+#ifdef USE_GD
+          if( src_rb->type == MS_BUFFER_BYTE_RGBA ) {
+#else
+          assert( src_rb->type == MS_BUFFER_BYTE_RGBA );
+#endif
+            assert( src_rb->type == dst_rb->type );
+
+
+            nSetPoints++;
+
+            if( dfWeightSum > 0.001 ) {
+              int dst_rb_off = nDstX * dst_rb->data.rgba.pixel_step + nDstY * dst_rb->data.rgba.row_step;
+              unsigned char red, green, blue, alpha;
+
+              red   = (unsigned char) MAX(0,MIN(255,padfPixelSum[0]));
+              green = (unsigned char) MAX(0,MIN(255,padfPixelSum[1]));
+              blue  = (unsigned char) MAX(0,MIN(255,padfPixelSum[2]));
+              alpha = (unsigned char)MAX(0,MIN(255,255.5*dfWeightSum));
+
+              msAlphaBlendPM( red, green, blue, alpha,
+                              dst_rb->data.rgba.r + dst_rb_off,
+                              dst_rb->data.rgba.g + dst_rb_off,
+                              dst_rb->data.rgba.b + dst_rb_off,
+                              (dst_rb->data.rgba.a == NULL) ? NULL : dst_rb->data.rgba.a + dst_rb_off );
+            }
+#ifdef USE_GD
+          }
+#endif
+      } else if( MS_RENDERER_RAWDATA(psSrcImage->format) ) {
+        int band;
+        int dst_off = nDstX + nDstY * psDstImage->width;
+
+        MS_SET_BIT(psDstImage->img_mask,dst_off);
+
+        for( band = 0; band < psSrcImage->format->bands; band++ ) {
+          if( psSrcImage->format->imagemode == MS_IMAGEMODE_INT16 ) {
+            psDstImage->img.raw_16bit[dst_off]
+              = (short) padfPixelSum[band];
+          } else if( psSrcImage->format->imagemode == MS_IMAGEMODE_FLOAT32) {
+            psDstImage->img.raw_float[dst_off]
+              = (float) padfPixelSum[band];
+          } else if( psSrcImage->format->imagemode == MS_IMAGEMODE_BYTE ) {
+            psDstImage->img.raw_byte[dst_off]
+              = (unsigned char)MAX(0,MIN(255,padfPixelSum[band]));
+          }
+
+          dst_off += psDstImage->width*psDstImage->height;
+        }
+      }
+    }
+  }
+
+  free( padfPixelSum );
+  free( panSuccess );
+  free( x );
+  free( y );
+
+  /* -------------------------------------------------------------------- */
+  /*      Some debugging output.                                          */
+  /* -------------------------------------------------------------------- */
+  if( nFailedPoints > 0 && debug )
+  {
+    char  szMsg[256];
+
+    sprintf( szMsg,
+             "msBilinearRasterResampler: "
+             "%d failed to transform, %d actually set.\n",
+             nFailedPoints, nSetPoints );
+    msDebug( szMsg );
+  }
+
+  return 0;
 }
 
 /************************************************************************/
@@ -545,59 +514,57 @@ msBilinearRasterResampler( imageObj *psSrcImage, rasterBufferObj *src_rb,
 static int
 msAverageSample( imageObj *psSrcImage, rasterBufferObj *src_rb,
                  double dfXMin, double dfYMin, double dfXMax, double dfYMax,
-                 double *padfPixelSum, 
+                 double *padfPixelSum,
                  double *pdfAlpha01 )
 
 {
-    int nXMin, nXMax, nYMin, nYMax, iX, iY;
-    double dfWeightSum = 0.0;
-    double dfMaxWeight = 0.0;
+  int nXMin, nXMax, nYMin, nYMax, iX, iY;
+  double dfWeightSum = 0.0;
+  double dfMaxWeight = 0.0;
 
-    nXMin = (int) dfXMin;
-    nYMin = (int) dfYMin;
-    nXMax = (int) ceil(dfXMax);
-    nYMax = (int) ceil(dfYMax);
+  nXMin = (int) dfXMin;
+  nYMin = (int) dfYMin;
+  nXMax = (int) ceil(dfXMax);
+  nYMax = (int) ceil(dfYMax);
 
-    *pdfAlpha01 = 0.0;
+  *pdfAlpha01 = 0.0;
 
-    for( iY = nYMin; iY < nYMax; iY++ )
-    {
-        double dfYCellMin, dfYCellMax;
-        
-        dfYCellMin = MAX(iY,dfYMin);
-        dfYCellMax = MIN(iY+1,dfYMax);
+  for( iY = nYMin; iY < nYMax; iY++ ) {
+    double dfYCellMin, dfYCellMax;
 
-        for( iX = nXMin; iX < nXMax; iX++ )
-        {
-            double dfXCellMin, dfXCellMax, dfWeight;
+    dfYCellMin = MAX(iY,dfYMin);
+    dfYCellMax = MIN(iY+1,dfYMax);
 
-            dfXCellMin = MAX(iX,dfXMin);
-            dfXCellMax = MIN(iX+1,dfXMax);
+    for( iX = nXMin; iX < nXMax; iX++ ) {
+      double dfXCellMin, dfXCellMax, dfWeight;
 
-            dfWeight = (dfXCellMax-dfXCellMin) * (dfYCellMax-dfYCellMin);
+      dfXCellMin = MAX(iX,dfXMin);
+      dfXCellMax = MIN(iX+1,dfXMax);
 
-            msSourceSample( psSrcImage, src_rb, iX, iY, padfPixelSum, 
-                            dfWeight, &dfWeightSum );
-            dfMaxWeight += dfWeight;
-        }
+      dfWeight = (dfXCellMax-dfXCellMin) * (dfYCellMax-dfYCellMin);
+
+      msSourceSample( psSrcImage, src_rb, iX, iY, padfPixelSum,
+                      dfWeight, &dfWeightSum );
+      dfMaxWeight += dfWeight;
     }
+  }
 
-    if( dfWeightSum == 0.0 )
-        return MS_FALSE;
+  if( dfWeightSum == 0.0 )
+    return MS_FALSE;
 
-    for( iX = 0; iX < 4; iX++ )
-        padfPixelSum[iX] /= dfWeightSum;
+  for( iX = 0; iX < 4; iX++ )
+    padfPixelSum[iX] /= dfWeightSum;
 
-    *pdfAlpha01 = dfWeightSum / dfMaxWeight;
+  *pdfAlpha01 = dfWeightSum / dfMaxWeight;
 
-    return MS_TRUE;
+  return MS_TRUE;
 }
 
 /************************************************************************/
 /*                      msAverageRasterResample()                       */
 /************************************************************************/
 
-static int 
+static int
 msAverageRasterResampler( imageObj *psSrcImage, rasterBufferObj *src_rb,
                           imageObj *psDstImage, rasterBufferObj *dst_rb,
                           int *panCMap,
@@ -605,237 +572,229 @@ msAverageRasterResampler( imageObj *psSrcImage, rasterBufferObj *src_rb,
                           int debug )
 
 {
-    double	*x1, *y1, *x2, *y2; 
-    int		nDstX, nDstY;
-    int         *panSuccess1, *panSuccess2;
-    int		nDstXSize = psDstImage->width;
-    int		nDstYSize = psDstImage->height;
-    int		nFailedPoints = 0, nSetPoints = 0;
-    double     *padfPixelSum;
-    
-    int         bandCount = MAX(4,psSrcImage->format->bands);
-
-    padfPixelSum = (double *) msSmallMalloc(sizeof(double) * bandCount);
-    
-    
-
-    x1 = (double *) msSmallMalloc( sizeof(double) * (nDstXSize+1) );
-    y1 = (double *) msSmallMalloc( sizeof(double) * (nDstXSize+1) );
-    x2 = (double *) msSmallMalloc( sizeof(double) * (nDstXSize+1) );
-    y2 = (double *) msSmallMalloc( sizeof(double) * (nDstXSize+1) );
-    panSuccess1 = (int *) msSmallMalloc( sizeof(int) * (nDstXSize+1) );
-    panSuccess2 = (int *) msSmallMalloc( sizeof(int) * (nDstXSize+1) );
-
-    for( nDstY = 0; nDstY < nDstYSize; nDstY++ )
-    {        
-        for( nDstX = 0; nDstX <= nDstXSize; nDstX++ )
-        {
-            x1[nDstX] = nDstX;
-            y1[nDstX] = nDstY;
-            x2[nDstX] = nDstX;
-            y2[nDstX] = nDstY+1;
-        }
+  double  *x1, *y1, *x2, *y2;
+  int   nDstX, nDstY;
+  int         *panSuccess1, *panSuccess2;
+  int   nDstXSize = psDstImage->width;
+  int   nDstYSize = psDstImage->height;
+  int   nFailedPoints = 0, nSetPoints = 0;
+  double     *padfPixelSum;
 
-        pfnTransform( pCBData, nDstXSize+1, x1, y1, panSuccess1 );
-        pfnTransform( pCBData, nDstXSize+1, x2, y2, panSuccess2 );
-        
-        for( nDstX = 0; nDstX < nDstXSize; nDstX++ )
-        {
-            double  dfXMin, dfYMin, dfXMax, dfYMax;
-            double  dfAlpha01;
-
-            /* Do not generate a pixel unless all four corners transformed */
-            if( !panSuccess1[nDstX] || !panSuccess1[nDstX+1]
-                || !panSuccess2[nDstX] || !panSuccess2[nDstX+1] )
-            {
-                nFailedPoints++;
-                continue;
-            }
-            
-            dfXMin = MIN(MIN(x1[nDstX],x1[nDstX+1]),
-                         MIN(x2[nDstX],x2[nDstX+1]));
-            dfYMin = MIN(MIN(y1[nDstX],y1[nDstX+1]),
-                         MIN(y2[nDstX],y2[nDstX+1]));
-            dfXMax = MAX(MAX(x1[nDstX],x1[nDstX+1]),
-                         MAX(x2[nDstX],x2[nDstX+1]));
-            dfYMax = MAX(MAX(y1[nDstX],y1[nDstX+1]),
-                         MAX(y2[nDstX],y2[nDstX+1]));
-
-            dfXMin = MIN(MAX(dfXMin,0),psSrcImage->width+1);
-            dfYMin = MIN(MAX(dfYMin,0),psSrcImage->height+1);
-            dfXMax = MIN(MAX(-1,dfXMax),psSrcImage->width);
-            dfYMax = MIN(MAX(-1,dfYMax),psSrcImage->height);
-                
-            memset( padfPixelSum, 0, sizeof(double)*bandCount );
-    
-            if( !msAverageSample( psSrcImage, src_rb,
-                                  dfXMin, dfYMin, dfXMax, dfYMax,
-                                  padfPixelSum, &dfAlpha01 ) )
-                continue;
-
-            if( MS_RENDERER_PLUGIN(psSrcImage->format) )
-            {
-            	assert(dst_rb && src_rb);
-            	if(dst_rb->type == MS_BUFFER_GD) {
-                    int nResult = panCMap[(int) padfPixelSum[0]];
-                    assert( !gdImageTrueColor(dst_rb->data.gd_img) );
-                    if( nResult != -1 )
-                    {                        
-                        nSetPoints++;
-                        dst_rb->data.gd_img->pixels[nDstY][nDstX] = nResult;
-                    }
-                }
-            	else if( dst_rb->type == MS_BUFFER_BYTE_RGBA )
-                {
-	
-                    assert( src_rb->type == dst_rb ->type );
-	
-                    nSetPoints++;
-	
-                    if( dfAlpha01 > 0 )
-                    {
-                        unsigned char red, green, blue, alpha;
-                        
-                        red   = (unsigned char) 
-                            MAX(0,MIN(255,padfPixelSum[0]+0.5));
-                        green = (unsigned char) 
-                            MAX(0,MIN(255,padfPixelSum[1]+0.5));
-                        blue  = (unsigned char) 
-                            MAX(0,MIN(255,padfPixelSum[2]+0.5));
-                        alpha = (unsigned char) 
-                            MAX(0,MIN(255,255*dfAlpha01+0.5));
-                        
-                        RB_SET_PIXEL(dst_rb,nDstX,nDstY, 
-                                     red, green, blue, alpha );
-                    }
-                }
-            }
-            else if( MS_RENDERER_RAWDATA(psSrcImage->format) )
-            {
-                int band;
-                int dst_off = nDstX + nDstY * psDstImage->width;
-
-                MS_SET_BIT(psDstImage->img_mask,dst_off);
-
-                for( band = 0; band < psSrcImage->format->bands; band++ )
-                {
-                    if( psSrcImage->format->imagemode == MS_IMAGEMODE_INT16 )
-                    {
-                        psDstImage->img.raw_16bit[dst_off] 
-                            = (short) (padfPixelSum[band]+0.5);
-                    }
-                    else if( psSrcImage->format->imagemode == MS_IMAGEMODE_FLOAT32)
-                    {
-                        psDstImage->img.raw_float[dst_off]
-                            = (float) padfPixelSum[band];
-                    }
-                    else if( psSrcImage->format->imagemode == MS_IMAGEMODE_BYTE )
-                    {
-                        psDstImage->img.raw_byte[dst_off]
-                            = (unsigned char) padfPixelSum[band];
-                    }
-
-                    dst_off += psDstImage->width * psDstImage->height;
-                }
-            }
-        }
-    }
+  int         bandCount = MAX(4,psSrcImage->format->bands);
 
-    free( padfPixelSum );
-    free( panSuccess1 );
-    free( x1 );
-    free( y1 );
-    free( panSuccess2 );
-    free( x2 );
-    free( y2 );
-
-/* -------------------------------------------------------------------- */
-/*      Some debugging output.                                          */
-/* -------------------------------------------------------------------- */
-    if( nFailedPoints > 0 && debug )
-    {
-        char	szMsg[256];
-        
-        sprintf( szMsg, 
-                 "msAverageRasterResampler: "
-                 "%d failed to transform, %d actually set.\n", 
-                 nFailedPoints, nSetPoints );
-        msDebug( szMsg );
+  padfPixelSum = (double *) msSmallMalloc(sizeof(double) * bandCount);
+
+
+
+  x1 = (double *) msSmallMalloc( sizeof(double) * (nDstXSize+1) );
+  y1 = (double *) msSmallMalloc( sizeof(double) * (nDstXSize+1) );
+  x2 = (double *) msSmallMalloc( sizeof(double) * (nDstXSize+1) );
+  y2 = (double *) msSmallMalloc( sizeof(double) * (nDstXSize+1) );
+  panSuccess1 = (int *) msSmallMalloc( sizeof(int) * (nDstXSize+1) );
+  panSuccess2 = (int *) msSmallMalloc( sizeof(int) * (nDstXSize+1) );
+
+  for( nDstY = 0; nDstY < nDstYSize; nDstY++ ) {
+    for( nDstX = 0; nDstX <= nDstXSize; nDstX++ ) {
+      x1[nDstX] = nDstX;
+      y1[nDstX] = nDstY;
+      x2[nDstX] = nDstX;
+      y2[nDstX] = nDstY+1;
     }
 
-    return 0;
+    pfnTransform( pCBData, nDstXSize+1, x1, y1, panSuccess1 );
+    pfnTransform( pCBData, nDstXSize+1, x2, y2, panSuccess2 );
+
+    for( nDstX = 0; nDstX < nDstXSize; nDstX++ ) {
+      double  dfXMin, dfYMin, dfXMax, dfYMax;
+      double  dfAlpha01;
+
+      /* Do not generate a pixel unless all four corners transformed */
+      if( !panSuccess1[nDstX] || !panSuccess1[nDstX+1]
+          || !panSuccess2[nDstX] || !panSuccess2[nDstX+1] ) {
+        nFailedPoints++;
+        continue;
+      }
+
+      dfXMin = MIN(MIN(x1[nDstX],x1[nDstX+1]),
+                   MIN(x2[nDstX],x2[nDstX+1]));
+      dfYMin = MIN(MIN(y1[nDstX],y1[nDstX+1]),
+                   MIN(y2[nDstX],y2[nDstX+1]));
+      dfXMax = MAX(MAX(x1[nDstX],x1[nDstX+1]),
+                   MAX(x2[nDstX],x2[nDstX+1]));
+      dfYMax = MAX(MAX(y1[nDstX],y1[nDstX+1]),
+                   MAX(y2[nDstX],y2[nDstX+1]));
+
+      dfXMin = MIN(MAX(dfXMin,0),psSrcImage->width+1);
+      dfYMin = MIN(MAX(dfYMin,0),psSrcImage->height+1);
+      dfXMax = MIN(MAX(-1,dfXMax),psSrcImage->width);
+      dfYMax = MIN(MAX(-1,dfYMax),psSrcImage->height);
+
+      memset( padfPixelSum, 0, sizeof(double)*bandCount );
+
+      if( !msAverageSample( psSrcImage, src_rb,
+                            dfXMin, dfYMin, dfXMax, dfYMax,
+                            padfPixelSum, &dfAlpha01 ) )
+        continue;
+
+      if( MS_RENDERER_PLUGIN(psSrcImage->format) ) {
+        assert(dst_rb && src_rb);
+#ifdef USE_GD
+        if(dst_rb->type == MS_BUFFER_GD) {
+          int nResult = panCMap[(int) padfPixelSum[0]];
+          assert( !gdImageTrueColor(dst_rb->data.gd_img) );
+          if( nResult != -1 ) {
+            nSetPoints++;
+            dst_rb->data.gd_img->pixels[nDstY][nDstX] = nResult;
+          }
+        } else
+#endif
+#ifdef USE_GD
+          if( dst_rb->type == MS_BUFFER_BYTE_RGBA ) {
+#else
+          assert( dst_rb->type == MS_BUFFER_BYTE_RGBA );
+#endif
+
+
+            assert( src_rb->type == dst_rb ->type );
+
+            nSetPoints++;
+
+            if( dfAlpha01 > 0 ) {
+              unsigned char red, green, blue, alpha;
+
+              red   = (unsigned char)
+                      MAX(0,MIN(255,padfPixelSum[0]+0.5));
+              green = (unsigned char)
+                      MAX(0,MIN(255,padfPixelSum[1]+0.5));
+              blue  = (unsigned char)
+                      MAX(0,MIN(255,padfPixelSum[2]+0.5));
+              alpha = (unsigned char)
+                      MAX(0,MIN(255,255*dfAlpha01+0.5));
+
+              RB_SET_PIXEL(dst_rb,nDstX,nDstY,
+                           red, green, blue, alpha );
+            }
+#ifdef USE_GD
+          }
+#endif
+      } else if( MS_RENDERER_RAWDATA(psSrcImage->format) ) {
+        int band;
+        int dst_off = nDstX + nDstY * psDstImage->width;
+
+        MS_SET_BIT(psDstImage->img_mask,dst_off);
+
+        for( band = 0; band < psSrcImage->format->bands; band++ ) {
+          if( psSrcImage->format->imagemode == MS_IMAGEMODE_INT16 ) {
+            psDstImage->img.raw_16bit[dst_off]
+              = (short) (padfPixelSum[band]+0.5);
+          } else if( psSrcImage->format->imagemode == MS_IMAGEMODE_FLOAT32) {
+            psDstImage->img.raw_float[dst_off]
+              = (float) padfPixelSum[band];
+          } else if( psSrcImage->format->imagemode == MS_IMAGEMODE_BYTE ) {
+            psDstImage->img.raw_byte[dst_off]
+              = (unsigned char) padfPixelSum[band];
+          }
+
+          dst_off += psDstImage->width * psDstImage->height;
+        }
+      }
+    }
+  }
+
+  free( padfPixelSum );
+  free( panSuccess1 );
+  free( x1 );
+  free( y1 );
+  free( panSuccess2 );
+  free( x2 );
+  free( y2 );
+
+  /* -------------------------------------------------------------------- */
+  /*      Some debugging output.                                          */
+  /* -------------------------------------------------------------------- */
+  if( nFailedPoints > 0 && debug )
+  {
+    char  szMsg[256];
+
+    sprintf( szMsg,
+             "msAverageRasterResampler: "
+             "%d failed to transform, %d actually set.\n",
+             nFailedPoints, nSetPoints );
+    msDebug( szMsg );
+  }
+
+  return 0;
 }
 
 /************************************************************************/
 /* ==================================================================== */
-/*      PROJ.4 based transformer.					*/
+/*      PROJ.4 based transformer.         */
 /* ==================================================================== */
 /************************************************************************/
 
-typedef struct 
-{
-    projectionObj *psSrcProjObj;
-    projPJ psSrcProj;
-    int bSrcIsGeographic;
-    double adfInvSrcGeoTransform[6];
+typedef struct {
+  projectionObj *psSrcProjObj;
+  projPJ psSrcProj;
+  int bSrcIsGeographic;
+  double adfInvSrcGeoTransform[6];
 
-    projectionObj *psDstProjObj;
-    projPJ psDstProj;
-    int bDstIsGeographic;
-    double adfDstGeoTransform[6];
+  projectionObj *psDstProjObj;
+  projPJ psDstProj;
+  int bDstIsGeographic;
+  double adfDstGeoTransform[6];
 
-    int  bUseProj;
+  int  bUseProj;
 } msProjTransformInfo;
 
 /************************************************************************/
 /*                       msInitProjTransformer()                        */
 /************************************************************************/
 
-void *msInitProjTransformer( projectionObj *psSrc, 
-                             double *padfSrcGeoTransform, 
-                             projectionObj *psDst, 
+void *msInitProjTransformer( projectionObj *psSrc,
+                             double *padfSrcGeoTransform,
+                             projectionObj *psDst,
                              double *padfDstGeoTransform )
 
 {
-    msProjTransformInfo	*psPTInfo;
-
-    psPTInfo = (msProjTransformInfo *) msSmallCalloc(1,sizeof(msProjTransformInfo));
-
-/* -------------------------------------------------------------------- */
-/*      We won't even use PROJ.4 if either coordinate system is         */
-/*      NULL.                                                           */
-/* -------------------------------------------------------------------- */
-    psPTInfo->bUseProj = 
-        (psSrc->proj != NULL && psDst->proj != NULL
-         && msProjectionsDiffer( psSrc, psDst ) );
-
-/* -------------------------------------------------------------------- */
-/*      Record source image information.  We invert the source          */
-/*      transformation for more convenient inverse application in       */
-/*      the transformer.                                                */
-/* -------------------------------------------------------------------- */
-    psPTInfo->psSrcProj = psSrc->proj;
-    if( psPTInfo->bUseProj )
-        psPTInfo->bSrcIsGeographic = pj_is_latlong(psSrc->proj);
-    else
-        psPTInfo->bSrcIsGeographic = MS_FALSE;
-    
-    if( !InvGeoTransform(padfSrcGeoTransform, 
-                         psPTInfo->adfInvSrcGeoTransform) )
-        return NULL;
-
-/* -------------------------------------------------------------------- */
-/*      Record destination image information.                           */
-/* -------------------------------------------------------------------- */
-    psPTInfo->psDstProj = psDst->proj;
-    if( psPTInfo->bUseProj )
-        psPTInfo->bDstIsGeographic = pj_is_latlong(psDst->proj);
-    else
-        psPTInfo->bDstIsGeographic = MS_FALSE;
-    memcpy( psPTInfo->adfDstGeoTransform, padfDstGeoTransform, 
-            sizeof(double) * 6 );
-
-    return psPTInfo;
+  msProjTransformInfo *psPTInfo;
+
+  psPTInfo = (msProjTransformInfo *) msSmallCalloc(1,sizeof(msProjTransformInfo));
+
+  /* -------------------------------------------------------------------- */
+  /*      We won't even use PROJ.4 if either coordinate system is         */
+  /*      NULL.                                                           */
+  /* -------------------------------------------------------------------- */
+  psPTInfo->bUseProj =
+    (psSrc->proj != NULL && psDst->proj != NULL
+     && msProjectionsDiffer( psSrc, psDst ) );
+
+  /* -------------------------------------------------------------------- */
+  /*      Record source image information.  We invert the source          */
+  /*      transformation for more convenient inverse application in       */
+  /*      the transformer.                                                */
+  /* -------------------------------------------------------------------- */
+  psPTInfo->psSrcProj = psSrc->proj;
+  if( psPTInfo->bUseProj )
+    psPTInfo->bSrcIsGeographic = pj_is_latlong(psSrc->proj);
+  else
+    psPTInfo->bSrcIsGeographic = MS_FALSE;
+
+  if( !InvGeoTransform(padfSrcGeoTransform,
+                       psPTInfo->adfInvSrcGeoTransform) )
+    return NULL;
+
+  /* -------------------------------------------------------------------- */
+  /*      Record destination image information.                           */
+  /* -------------------------------------------------------------------- */
+  psPTInfo->psDstProj = psDst->proj;
+  if( psPTInfo->bUseProj )
+    psPTInfo->bDstIsGeographic = pj_is_latlong(psDst->proj);
+  else
+    psPTInfo->bDstIsGeographic = MS_FALSE;
+  memcpy( psPTInfo->adfDstGeoTransform, padfDstGeoTransform,
+          sizeof(double) * 6 );
+
+  return psPTInfo;
 }
 
 /************************************************************************/
@@ -845,119 +804,106 @@ void *msInitProjTransformer( projectionObj *psSrc,
 void msFreeProjTransformer( void * pCBData )
 
 {
-    free( pCBData );
+  free( pCBData );
 }
 
 /************************************************************************/
 /*                          msProjTransformer                           */
 /************************************************************************/
 
-int msProjTransformer( void *pCBData, int nPoints, 
+int msProjTransformer( void *pCBData, int nPoints,
                        double *x, double *y, int *panSuccess )
 
 {
-    int		i;
-    msProjTransformInfo	*psPTInfo = (msProjTransformInfo*) pCBData;
-    double	x_out;
-
-/* -------------------------------------------------------------------- */
-/*      Transform into destination georeferenced space.                 */
-/* -------------------------------------------------------------------- */
-    for( i = 0; i < nPoints; i++ )
-    {
-        x_out = psPTInfo->adfDstGeoTransform[0] 
+  int   i;
+  msProjTransformInfo *psPTInfo = (msProjTransformInfo*) pCBData;
+  double  x_out;
+
+  /* -------------------------------------------------------------------- */
+  /*      Transform into destination georeferenced space.                 */
+  /* -------------------------------------------------------------------- */
+  for( i = 0; i < nPoints; i++ ) {
+    x_out = psPTInfo->adfDstGeoTransform[0]
             + psPTInfo->adfDstGeoTransform[1] * x[i]
             + psPTInfo->adfDstGeoTransform[2] * y[i];
-        y[i] = psPTInfo->adfDstGeoTransform[3] 
-            + psPTInfo->adfDstGeoTransform[4] * x[i]
-            + psPTInfo->adfDstGeoTransform[5] * y[i];
-        x[i] = x_out;
-
-        panSuccess[i] = 1;
-    }
-        
-/* -------------------------------------------------------------------- */
-/*      Transform from degrees to radians if geographic.                */
-/* -------------------------------------------------------------------- */
-    if( psPTInfo->bDstIsGeographic )
-    {
-        for( i = 0; i < nPoints; i++ )
-        {
-            x[i] = x[i] * DEG_TO_RAD;
-            y[i] = y[i] * DEG_TO_RAD;
-        }
+    y[i] = psPTInfo->adfDstGeoTransform[3]
+           + psPTInfo->adfDstGeoTransform[4] * x[i]
+           + psPTInfo->adfDstGeoTransform[5] * y[i];
+    x[i] = x_out;
+
+    panSuccess[i] = 1;
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Transform from degrees to radians if geographic.                */
+  /* -------------------------------------------------------------------- */
+  if( psPTInfo->bDstIsGeographic ) {
+    for( i = 0; i < nPoints; i++ ) {
+      x[i] = x[i] * DEG_TO_RAD;
+      y[i] = y[i] * DEG_TO_RAD;
     }
+  }
 
-/* -------------------------------------------------------------------- */
-/*      Transform back to source projection space.                      */
-/* -------------------------------------------------------------------- */
-    if( psPTInfo->bUseProj )
-    {
-        double *z;
-        int tr_result;
-        
-        z = (double *) msSmallCalloc(sizeof(double),nPoints);
-
-        msAcquireLock( TLOCK_PROJ );
-        tr_result = pj_transform( psPTInfo->psDstProj, psPTInfo->psSrcProj, 
-                                  nPoints, 1, x, y,  z);
-        msReleaseLock( TLOCK_PROJ );
-
-        if( tr_result != 0 )
-        {
-            free( z );
-            for( i = 0; i < nPoints; i++ )
-                panSuccess[i] = 0;
-
-            return MS_FALSE;
-        }
-        free( z );
+  /* -------------------------------------------------------------------- */
+  /*      Transform back to source projection space.                      */
+  /* -------------------------------------------------------------------- */
+  if( psPTInfo->bUseProj ) {
+    double *z;
+    int tr_result;
 
-        for( i = 0; i < nPoints; i++ )
-        {
-            if( x[i] == HUGE_VAL || y[i] == HUGE_VAL )
-                panSuccess[i] = 0;
-        }
-    }
-    
-/* -------------------------------------------------------------------- */
-/*      Transform back to degrees if source is geographic.              */
-/* -------------------------------------------------------------------- */
-    if( psPTInfo->bSrcIsGeographic )
-    {
-        for( i = 0; i < nPoints; i++ )
-        {
-            if( panSuccess[i] )
-            {
-                x[i] = x[i] * RAD_TO_DEG;
-                y[i] = y[i] * RAD_TO_DEG;
-            }
-        }
+    z = (double *) msSmallCalloc(sizeof(double),nPoints);
+
+    msAcquireLock( TLOCK_PROJ );
+    tr_result = pj_transform( psPTInfo->psDstProj, psPTInfo->psSrcProj,
+                              nPoints, 1, x, y,  z);
+    msReleaseLock( TLOCK_PROJ );
+
+    if( tr_result != 0 ) {
+      free( z );
+      for( i = 0; i < nPoints; i++ )
+        panSuccess[i] = 0;
+
+      return MS_FALSE;
     }
+    free( z );
 
-/* -------------------------------------------------------------------- */
-/*      Transform to source raster space.                               */
-/* -------------------------------------------------------------------- */
-    for( i = 0; i < nPoints; i++ )
-    {
-        if( panSuccess[i] )
-        {
-            x_out = psPTInfo->adfInvSrcGeoTransform[0] 
-                + psPTInfo->adfInvSrcGeoTransform[1] * x[i]
-                + psPTInfo->adfInvSrcGeoTransform[2] * y[i];
-            y[i] = psPTInfo->adfInvSrcGeoTransform[3] 
-                + psPTInfo->adfInvSrcGeoTransform[4] * x[i]
-                + psPTInfo->adfInvSrcGeoTransform[5] * y[i];
-            x[i] = x_out;
-        }
-        else
-        {
-            x[i] = -1;
-            y[i] = -1;
-        }
+    for( i = 0; i < nPoints; i++ ) {
+      if( x[i] == HUGE_VAL || y[i] == HUGE_VAL )
+        panSuccess[i] = 0;
+    }
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Transform back to degrees if source is geographic.              */
+  /* -------------------------------------------------------------------- */
+  if( psPTInfo->bSrcIsGeographic ) {
+    for( i = 0; i < nPoints; i++ ) {
+      if( panSuccess[i] ) {
+        x[i] = x[i] * RAD_TO_DEG;
+        y[i] = y[i] * RAD_TO_DEG;
+      }
+    }
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Transform to source raster space.                               */
+  /* -------------------------------------------------------------------- */
+  for( i = 0; i < nPoints; i++ ) {
+    if( panSuccess[i] ) {
+      x_out = psPTInfo->adfInvSrcGeoTransform[0]
+              + psPTInfo->adfInvSrcGeoTransform[1] * x[i]
+              + psPTInfo->adfInvSrcGeoTransform[2] * y[i];
+      y[i] = psPTInfo->adfInvSrcGeoTransform[3]
+             + psPTInfo->adfInvSrcGeoTransform[4] * x[i]
+             + psPTInfo->adfInvSrcGeoTransform[5] * y[i];
+      x[i] = x_out;
+    } else {
+      x[i] = -1;
+      y[i] = -1;
     }
+  }
 
-    return 1;
+  return 1;
 }
 
 /************************************************************************/
@@ -966,31 +912,30 @@ int msProjTransformer( void *pCBData, int nPoints,
 /* ==================================================================== */
 /************************************************************************/
 
-typedef struct 
-{
-    SimpleTransformer pfnBaseTransformer;
-    void             *pBaseCBData;
+typedef struct {
+  SimpleTransformer pfnBaseTransformer;
+  void             *pBaseCBData;
 
-    double	      dfMaxError;
+  double        dfMaxError;
 } msApproxTransformInfo;
 
 /************************************************************************/
 /*                      msInitApproxTransformer()                       */
 /************************************************************************/
 
-static void *msInitApproxTransformer( SimpleTransformer pfnBaseTransformer, 
+static void *msInitApproxTransformer( SimpleTransformer pfnBaseTransformer,
                                       void *pBaseCBData,
                                       double dfMaxError )
 
 {
-    msApproxTransformInfo	*psATInfo;
+  msApproxTransformInfo *psATInfo;
 
-    psATInfo = (msApproxTransformInfo *) msSmallMalloc(sizeof(msApproxTransformInfo));
-    psATInfo->pfnBaseTransformer = pfnBaseTransformer;
-    psATInfo->pBaseCBData = pBaseCBData;
-    psATInfo->dfMaxError = dfMaxError;
+  psATInfo = (msApproxTransformInfo *) msSmallMalloc(sizeof(msApproxTransformInfo));
+  psATInfo->pfnBaseTransformer = pfnBaseTransformer;
+  psATInfo->pBaseCBData = pBaseCBData;
+  psATInfo->dfMaxError = dfMaxError;
 
-    return psATInfo;
+  return psATInfo;
 }
 
 /************************************************************************/
@@ -1000,100 +945,95 @@ static void *msInitApproxTransformer( SimpleTransformer pfnBaseTransformer,
 static void msFreeApproxTransformer( void * pCBData )
 
 {
-    free( pCBData );
+  free( pCBData );
 }
 
 /************************************************************************/
 /*                         msApproxTransformer                          */
 /************************************************************************/
 
-static int msApproxTransformer( void *pCBData, int nPoints, 
+static int msApproxTransformer( void *pCBData, int nPoints,
                                 double *x, double *y, int *panSuccess )
 
 {
-    msApproxTransformInfo *psATInfo = (msApproxTransformInfo *) pCBData;
-    double x2[3], y2[3], dfDeltaX, dfDeltaY, dfError, dfDist;
-    int nMiddle, anSuccess2[3], i, bSuccess;
-
-    nMiddle = (nPoints-1)/2;
-
-/* -------------------------------------------------------------------- */
-/*      Bail if our preconditions are not met, or if error is not       */
-/*      acceptable.                                                     */
-/* -------------------------------------------------------------------- */
-    if( y[0] != y[nPoints-1] || y[0] != y[nMiddle]
-        || x[0] == x[nPoints-1] || x[0] == x[nMiddle]
-        || psATInfo->dfMaxError == 0.0 || nPoints <= 5 )
-    {
-        return psATInfo->pfnBaseTransformer( psATInfo->pBaseCBData, nPoints,
-                                             x, y, panSuccess );
+  msApproxTransformInfo *psATInfo = (msApproxTransformInfo *) pCBData;
+  double x2[3], y2[3], dfDeltaX, dfDeltaY, dfError, dfDist;
+  int nMiddle, anSuccess2[3], i, bSuccess;
+
+  nMiddle = (nPoints-1)/2;
+
+  /* -------------------------------------------------------------------- */
+  /*      Bail if our preconditions are not met, or if error is not       */
+  /*      acceptable.                                                     */
+  /* -------------------------------------------------------------------- */
+  if( y[0] != y[nPoints-1] || y[0] != y[nMiddle]
+      || x[0] == x[nPoints-1] || x[0] == x[nMiddle]
+      || psATInfo->dfMaxError == 0.0 || nPoints <= 5 ) {
+    return psATInfo->pfnBaseTransformer( psATInfo->pBaseCBData, nPoints,
+                                         x, y, panSuccess );
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Transform first, last and middle point.                         */
+  /* -------------------------------------------------------------------- */
+  x2[0] = x[0];
+  y2[0] = y[0];
+  x2[1] = x[nMiddle];
+  y2[1] = y[nMiddle];
+  x2[2] = x[nPoints-1];
+  y2[2] = y[nPoints-1];
+
+  bSuccess =
+    psATInfo->pfnBaseTransformer( psATInfo->pBaseCBData, 3, x2, y2,
+                                  anSuccess2 );
+  if( !bSuccess || !anSuccess2[0] || !anSuccess2[1] || !anSuccess2[2] )
+    return psATInfo->pfnBaseTransformer( psATInfo->pBaseCBData, nPoints,
+                                         x, y, panSuccess );
+
+  /* -------------------------------------------------------------------- */
+  /*      Is the error at the middle acceptable relative to an            */
+  /*      interpolation of the middle position?                           */
+  /* -------------------------------------------------------------------- */
+  dfDeltaX = (x2[2] - x2[0]) / (x[nPoints-1] - x[0]);
+  dfDeltaY = (y2[2] - y2[0]) / (x[nPoints-1] - x[0]);
+
+  dfError = fabs((x2[0] + dfDeltaX * (x[nMiddle] - x[0])) - x2[1])
+            + fabs((y2[0] + dfDeltaY * (x[nMiddle] - x[0])) - y2[1]);
+
+  if( dfError > psATInfo->dfMaxError ) {
+    bSuccess =
+      msApproxTransformer( psATInfo, nMiddle, x, y, panSuccess );
+
+    if( !bSuccess ) {
+      return psATInfo->pfnBaseTransformer( psATInfo->pBaseCBData,
+                                           nPoints,
+                                           x, y, panSuccess );
     }
 
-/* -------------------------------------------------------------------- */
-/*      Transform first, last and middle point.                         */
-/* -------------------------------------------------------------------- */
-    x2[0] = x[0];
-    y2[0] = y[0];
-    x2[1] = x[nMiddle];
-    y2[1] = y[nMiddle];
-    x2[2] = x[nPoints-1];
-    y2[2] = y[nPoints-1];
-
-    bSuccess = 
-        psATInfo->pfnBaseTransformer( psATInfo->pBaseCBData, 3, x2, y2, 
-                                      anSuccess2 );
-    if( !bSuccess || !anSuccess2[0] || !anSuccess2[1] || !anSuccess2[2] )
-        return psATInfo->pfnBaseTransformer( psATInfo->pBaseCBData, nPoints,
-                                             x, y, panSuccess );
-    
-/* -------------------------------------------------------------------- */
-/*      Is the error at the middle acceptable relative to an            */
-/*      interpolation of the middle position?                           */
-/* -------------------------------------------------------------------- */
-    dfDeltaX = (x2[2] - x2[0]) / (x[nPoints-1] - x[0]);
-    dfDeltaY = (y2[2] - y2[0]) / (x[nPoints-1] - x[0]);
-
-    dfError = fabs((x2[0] + dfDeltaX * (x[nMiddle] - x[0])) - x2[1])
-        + fabs((y2[0] + dfDeltaY * (x[nMiddle] - x[0])) - y2[1]);
-
-    if( dfError > psATInfo->dfMaxError )
-    {
-        bSuccess = 
-            msApproxTransformer( psATInfo, nMiddle, x, y, panSuccess );
-            
-        if( !bSuccess )
-        {
-            return psATInfo->pfnBaseTransformer( psATInfo->pBaseCBData, 
-                                                 nPoints,
-                                                 x, y, panSuccess );
-        }
-
-        bSuccess = 
-            msApproxTransformer( psATInfo, nPoints - nMiddle, 
-                                 x+nMiddle, y+nMiddle, panSuccess+nMiddle );
+    bSuccess =
+      msApproxTransformer( psATInfo, nPoints - nMiddle,
+                           x+nMiddle, y+nMiddle, panSuccess+nMiddle );
 
-        if( !bSuccess )
-        {
-            return psATInfo->pfnBaseTransformer( psATInfo->pBaseCBData, 
-                                                 nPoints,
-                                                 x, y, panSuccess );
-        }
-
-        return 1;
+    if( !bSuccess ) {
+      return psATInfo->pfnBaseTransformer( psATInfo->pBaseCBData,
+                                           nPoints,
+                                           x, y, panSuccess );
     }
 
-/* -------------------------------------------------------------------- */
-/*      Error is OK, linearly interpolate all points along line.        */
-/* -------------------------------------------------------------------- */
-    for( i = nPoints-1; i >= 0; i-- )
-    {
-        dfDist = (x[i] - x[0]);
-        y[i] = y2[0] + dfDeltaY * dfDist;
-        x[i] = x2[0] + dfDeltaX * dfDist;
-        panSuccess[i] = 1;
-    }
-    
     return 1;
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Error is OK, linearly interpolate all points along line.        */
+  /* -------------------------------------------------------------------- */
+  for( i = nPoints-1; i >= 0; i-- ) {
+    dfDist = (x[i] - x[0]);
+    y[i] = y2[0] + dfDeltaY * dfDist;
+    x[i] = x2[0] + dfDeltaX * dfDist;
+    panSuccess[i] = 1;
+  }
+
+  return 1;
 }
 
 /************************************************************************/
@@ -1103,194 +1043,173 @@ static int msApproxTransformer( void *pCBData, int nPoints,
 /*      onto the source raster.                                         */
 /************************************************************************/
 
-static int msTransformMapToSource( int nDstXSize, int nDstYSize, 
+static int msTransformMapToSource( int nDstXSize, int nDstYSize,
                                    double * adfDstGeoTransform,
                                    projectionObj *psDstProj,
-                                   int nSrcXSize, int nSrcYSize, 
+                                   int nSrcXSize, int nSrcYSize,
                                    double * adfInvSrcGeoTransform,
                                    projectionObj *psSrcProj,
                                    rectObj *psSrcExtent,
                                    int bUseGrid )
 
 {
-    int nFailures = 0;
+  int nFailures = 0;
 
 #define EDGE_STEPS    10
 #define MAX_SIZE      ((EDGE_STEPS+1)*(EDGE_STEPS+1))
 
-    int		i, nSamples = 0, bOutInit = 0;
-    double      dfRatio;
-    double	x[MAX_SIZE], y[MAX_SIZE], z[MAX_SIZE];
-
-/* -------------------------------------------------------------------- */
-/*      Collect edges in map image pixel/line coordinates               */
-/* -------------------------------------------------------------------- */
-    if( !bUseGrid )
-    {
-        for( dfRatio = 0.0; dfRatio <= 1.001; dfRatio += (1.0/EDGE_STEPS) )
-        {
-            assert( nSamples < MAX_SIZE );
-            x[nSamples  ] = dfRatio * nDstXSize;
-            y[nSamples++] = 0.0;
-            x[nSamples  ] = dfRatio * nDstXSize;
-            y[nSamples++] = nDstYSize;
-            x[nSamples  ] = 0.0;
-            y[nSamples++] = dfRatio * nDstYSize;
-            x[nSamples  ] = nDstXSize;
-            y[nSamples++] = dfRatio * nDstYSize;
-        }
+  int   i, nSamples = 0, bOutInit = 0;
+  double      dfRatio;
+  double  x[MAX_SIZE], y[MAX_SIZE], z[MAX_SIZE];
+
+  /* -------------------------------------------------------------------- */
+  /*      Collect edges in map image pixel/line coordinates               */
+  /* -------------------------------------------------------------------- */
+  if( !bUseGrid ) {
+    for( dfRatio = 0.0; dfRatio <= 1.001; dfRatio += (1.0/EDGE_STEPS) ) {
+      assert( nSamples < MAX_SIZE );
+      x[nSamples  ] = dfRatio * nDstXSize;
+      y[nSamples++] = 0.0;
+      x[nSamples  ] = dfRatio * nDstXSize;
+      y[nSamples++] = nDstYSize;
+      x[nSamples  ] = 0.0;
+      y[nSamples++] = dfRatio * nDstYSize;
+      x[nSamples  ] = nDstXSize;
+      y[nSamples++] = dfRatio * nDstYSize;
     }
-
-/* -------------------------------------------------------------------- */
-/*      Collect a grid in the hopes of a more accurate region.          */
-/* -------------------------------------------------------------------- */
-    else
-    {
-        double dfRatio2;
-
-        for( dfRatio = 0.0; dfRatio <= 1.001; dfRatio += (1.0/EDGE_STEPS) )
-        {
-            for( dfRatio2=0.0; dfRatio2 <= 1.001; dfRatio2 += (1.0/EDGE_STEPS))
-            {
-                assert( nSamples < MAX_SIZE );
-                x[nSamples  ] = dfRatio2 * nDstXSize;
-                y[nSamples++] = dfRatio * nDstYSize;
-            }
-        }
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Collect a grid in the hopes of a more accurate region.          */
+  /* -------------------------------------------------------------------- */
+  else {
+    double dfRatio2;
+
+    for( dfRatio = 0.0; dfRatio <= 1.001; dfRatio += (1.0/EDGE_STEPS) ) {
+      for( dfRatio2=0.0; dfRatio2 <= 1.001; dfRatio2 += (1.0/EDGE_STEPS)) {
+        assert( nSamples < MAX_SIZE );
+        x[nSamples  ] = dfRatio2 * nDstXSize;
+        y[nSamples++] = dfRatio * nDstYSize;
+      }
     }
+  }
 
-/* -------------------------------------------------------------------- */
-/*      transform to map georeferenced units                            */
-/* -------------------------------------------------------------------- */
-    for( i = 0; i < nSamples; i++ )
-    {
-        double		x_out, y_out; 
+  /* -------------------------------------------------------------------- */
+  /*      transform to map georeferenced units                            */
+  /* -------------------------------------------------------------------- */
+  for( i = 0; i < nSamples; i++ ) {
+    double    x_out, y_out;
 
-        x_out = adfDstGeoTransform[0] 
+    x_out = adfDstGeoTransform[0]
             + x[i] * adfDstGeoTransform[1]
             + y[i] * adfDstGeoTransform[2];
 
-        y_out = adfDstGeoTransform[3] 
+    y_out = adfDstGeoTransform[3]
             + x[i] * adfDstGeoTransform[4]
             + y[i] * adfDstGeoTransform[5];
 
-        x[i] = x_out;
-        y[i] = y_out;
-        z[i] = 0.0;
-    }
-
-/* -------------------------------------------------------------------- */
-/*      Transform to layer georeferenced coordinates.                   */
-/* -------------------------------------------------------------------- */
-    if( psDstProj->proj && psSrcProj->proj )
-    {
-        int tr_result;
-
-        if( pj_is_latlong(psDstProj->proj) )
-        {
-            for( i = 0; i < nSamples; i++ )
-            {
-                x[i] = x[i] * DEG_TO_RAD;
-                y[i] = y[i] * DEG_TO_RAD;
-            }
-        }
-        
-        msAcquireLock( TLOCK_PROJ );
-        tr_result = pj_transform( psDstProj->proj, psSrcProj->proj,
-                                  nSamples, 1, x, y, z );
-        msReleaseLock( TLOCK_PROJ );
-
-        if( tr_result != 0 )
-            return MS_FALSE;
-        
-        if( pj_is_latlong(psSrcProj->proj) )
-        {
-            for( i = 0; i < nSamples; i++ )
-            {
-                if( x[i] != HUGE_VAL && y[i] != HUGE_VAL )
-                {
-                    x[i] = x[i] * RAD_TO_DEG;
-                    y[i] = y[i] * RAD_TO_DEG;
-                }
-            }
-        }
-    }
-
-/* -------------------------------------------------------------------- */
-/*      If we just using the edges (not a grid) and we go some          */
-/*      errors, then we need to restart using a grid pattern.           */
-/* -------------------------------------------------------------------- */
-    if( !bUseGrid )
-    {
-        for( i = 0; i < nSamples; i++ )
-        {
-            if( x[i] == HUGE_VAL || y[i] == HUGE_VAL )
-            {
-                return msTransformMapToSource( nDstXSize, nDstYSize, 
-                                               adfDstGeoTransform, psDstProj,
-                                               nSrcXSize, nSrcYSize, 
-                                               adfInvSrcGeoTransform,psSrcProj,
-                                               psSrcExtent, 1 );
-            }
-        }
+    x[i] = x_out;
+    y[i] = y_out;
+    z[i] = 0.0;
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Transform to layer georeferenced coordinates.                   */
+  /* -------------------------------------------------------------------- */
+  if( psDstProj->proj && psSrcProj->proj ) {
+    int tr_result;
+
+    if( pj_is_latlong(psDstProj->proj) ) {
+      for( i = 0; i < nSamples; i++ ) {
+        x[i] = x[i] * DEG_TO_RAD;
+        y[i] = y[i] * DEG_TO_RAD;
+      }
     }
 
-/* -------------------------------------------------------------------- */
-/*      transform to layer raster coordinates, and collect bounds.      */
-/* -------------------------------------------------------------------- */
-    for( i = 0; i < nSamples; i++ )
-    {
-        double		x_out, y_out; 
+    msAcquireLock( TLOCK_PROJ );
+    tr_result = pj_transform( psDstProj->proj, psSrcProj->proj,
+                              nSamples, 1, x, y, z );
+    msReleaseLock( TLOCK_PROJ );
 
-        if( x[i] == HUGE_VAL || y[i] == HUGE_VAL )
-        {
-            nFailures++;
-            continue;
-        }
+    if( tr_result != 0 )
+      return MS_FALSE;
 
-        x_out =      adfInvSrcGeoTransform[0]
-            +   x[i]*adfInvSrcGeoTransform[1]
-            +   y[i]*adfInvSrcGeoTransform[2];
-        y_out =      adfInvSrcGeoTransform[3]
-            +   x[i]*adfInvSrcGeoTransform[4]
-            +   y[i]*adfInvSrcGeoTransform[5];
-
-        if( !bOutInit )
-        {
-            psSrcExtent->minx = psSrcExtent->maxx = x_out;
-            psSrcExtent->miny = psSrcExtent->maxy = y_out;
-            bOutInit = 1;
-        }
-        else
-        {
-            psSrcExtent->minx = MIN(psSrcExtent->minx, x_out);
-            psSrcExtent->maxx = MAX(psSrcExtent->maxx, x_out);
-            psSrcExtent->miny = MIN(psSrcExtent->miny, y_out);
-            psSrcExtent->maxy = MAX(psSrcExtent->maxy, y_out);
+    if( pj_is_latlong(psSrcProj->proj) ) {
+      for( i = 0; i < nSamples; i++ ) {
+        if( x[i] != HUGE_VAL && y[i] != HUGE_VAL ) {
+          x[i] = x[i] * RAD_TO_DEG;
+          y[i] = y[i] * RAD_TO_DEG;
         }
+      }
     }
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      If we just using the edges (not a grid) and we go some          */
+  /*      errors, then we need to restart using a grid pattern.           */
+  /* -------------------------------------------------------------------- */
+  if( !bUseGrid ) {
+    for( i = 0; i < nSamples; i++ ) {
+      if( x[i] == HUGE_VAL || y[i] == HUGE_VAL ) {
+        return msTransformMapToSource( nDstXSize, nDstYSize,
+                                       adfDstGeoTransform, psDstProj,
+                                       nSrcXSize, nSrcYSize,
+                                       adfInvSrcGeoTransform,psSrcProj,
+                                       psSrcExtent, 1 );
+      }
+    }
+  }
 
-    if( !bOutInit )
-        return MS_FALSE;
+  /* -------------------------------------------------------------------- */
+  /*      transform to layer raster coordinates, and collect bounds.      */
+  /* -------------------------------------------------------------------- */
+  for( i = 0; i < nSamples; i++ ) {
+    double    x_out, y_out;
 
-/* -------------------------------------------------------------------- */
-/*      If we had some failures, we need to expand the region to        */
-/*      represent our very coarse sampling grid.                        */
-/* -------------------------------------------------------------------- */
-    if( nFailures > 0 )
-    {
-        int nGrowAmountX = (int) 
-            (psSrcExtent->maxx - psSrcExtent->minx)/EDGE_STEPS + 1;
-        int nGrowAmountY = (int) 
-            (psSrcExtent->maxy - psSrcExtent->miny)/EDGE_STEPS + 1;
-
-        psSrcExtent->minx = MAX(psSrcExtent->minx - nGrowAmountX,0);
-        psSrcExtent->miny = MAX(psSrcExtent->miny - nGrowAmountY,0);
-        psSrcExtent->maxx = MIN(psSrcExtent->maxx + nGrowAmountX,nSrcXSize);
-        psSrcExtent->maxy = MIN(psSrcExtent->maxy + nGrowAmountY,nSrcYSize);
+    if( x[i] == HUGE_VAL || y[i] == HUGE_VAL ) {
+      nFailures++;
+      continue;
     }
 
-    return MS_TRUE;
+    x_out =      adfInvSrcGeoTransform[0]
+                 +   x[i]*adfInvSrcGeoTransform[1]
+                 +   y[i]*adfInvSrcGeoTransform[2];
+    y_out =      adfInvSrcGeoTransform[3]
+                 +   x[i]*adfInvSrcGeoTransform[4]
+                 +   y[i]*adfInvSrcGeoTransform[5];
+
+    if( !bOutInit ) {
+      psSrcExtent->minx = psSrcExtent->maxx = x_out;
+      psSrcExtent->miny = psSrcExtent->maxy = y_out;
+      bOutInit = 1;
+    } else {
+      psSrcExtent->minx = MIN(psSrcExtent->minx, x_out);
+      psSrcExtent->maxx = MAX(psSrcExtent->maxx, x_out);
+      psSrcExtent->miny = MIN(psSrcExtent->miny, y_out);
+      psSrcExtent->maxy = MAX(psSrcExtent->maxy, y_out);
+    }
+  }
+
+  if( !bOutInit )
+    return MS_FALSE;
+
+  /* -------------------------------------------------------------------- */
+  /*      If we had some failures, we need to expand the region to        */
+  /*      represent our very coarse sampling grid.                        */
+  /* -------------------------------------------------------------------- */
+  if( nFailures > 0 ) {
+    int nGrowAmountX = (int)
+                       (psSrcExtent->maxx - psSrcExtent->minx)/EDGE_STEPS + 1;
+    int nGrowAmountY = (int)
+                       (psSrcExtent->maxy - psSrcExtent->miny)/EDGE_STEPS + 1;
+
+    psSrcExtent->minx = MAX(psSrcExtent->minx - nGrowAmountX,0);
+    psSrcExtent->miny = MAX(psSrcExtent->miny - nGrowAmountY,0);
+    psSrcExtent->maxx = MIN(psSrcExtent->maxx + nGrowAmountX,nSrcXSize);
+    psSrcExtent->maxy = MIN(psSrcExtent->maxy + nGrowAmountY,nSrcYSize);
+  }
+
+  return MS_TRUE;
 }
 
 #endif /* def USE_PROJ */
@@ -1304,373 +1223,369 @@ int msResampleGDALToMap( mapObj *map, layerObj *layer, imageObj *image,
                          rasterBufferObj *rb, GDALDatasetH hDS )
 
 {
-/* -------------------------------------------------------------------- */
-/*      We require PROJ.4 4.4.2 or later.  Earlier versions don't       */
-/*      have PJD_GRIDSHIFT.                                             */
-/* -------------------------------------------------------------------- */
+  /* -------------------------------------------------------------------- */
+  /*      We require PROJ.4 4.4.2 or later.  Earlier versions don't       */
+  /*      have PJD_GRIDSHIFT.                                             */
+  /* -------------------------------------------------------------------- */
 #if !defined(PJD_GRIDSHIFT) && !defined(PJ_VERSION)
-    msSetError(MS_PROJERR, 
-               "Projection support is not available, so msResampleGDALToMap() fails.", 
-               "msProjectRect()");
-    return(MS_FAILURE);
+  msSetError(MS_PROJERR,
+             "Projection support is not available, so msResampleGDALToMap() fails.",
+             "msProjectRect()");
+  return(MS_FAILURE);
 #else
-    int		nSrcXSize, nSrcYSize, nDstXSize, nDstYSize;
-    int		result, bSuccess;
-    double	adfSrcGeoTransform[6], adfDstGeoTransform[6];
-    double      adfInvSrcGeoTransform[6], dfNominalCellSize;
-    rectObj	sSrcExtent, sOrigSrcExtent;
-    mapObj	sDummyMap;
-    imageObj   *srcImage;
-    void	*pTCBData;
-    void	*pACBData;
-    int         anCMap[256];
-    char       **papszAlteredProcessing = NULL;
-    int         nLoadImgXSize, nLoadImgYSize;
-    double      dfOversampleRatio;
-    rasterBufferObj src_rb, *psrc_rb = NULL;
-   
-    
-    const char *resampleMode = CSLFetchNameValue( layer->processing, 
-                                                  "RESAMPLE" );
-
-    if( resampleMode == NULL )
-        resampleMode = "NEAREST";
-
-/* -------------------------------------------------------------------- */
-/*      We will require source and destination to have a valid          */
-/*      projection object.                                              */
-/* -------------------------------------------------------------------- */
-    if( map->projection.proj == NULL
-        || layer->projection.proj == NULL )
-    {
-        if( layer->debug )
-            msDebug( "msResampleGDALToMap(): "
-                     "Either map or layer projection is NULL, assuming compatible.\n" );
+  int   nSrcXSize, nSrcYSize, nDstXSize, nDstYSize;
+  int   result, bSuccess;
+  double  adfSrcGeoTransform[6], adfDstGeoTransform[6];
+  double      adfInvSrcGeoTransform[6], dfNominalCellSize;
+  rectObj sSrcExtent, sOrigSrcExtent;
+  mapObj  sDummyMap;
+  imageObj   *srcImage;
+  void  *pTCBData;
+  void  *pACBData;
+  int         anCMap[256];
+  char       **papszAlteredProcessing = NULL;
+  int         nLoadImgXSize, nLoadImgYSize;
+  double      dfOversampleRatio;
+  rasterBufferObj src_rb, *psrc_rb = NULL;
+
+
+  const char *resampleMode = CSLFetchNameValue( layer->processing,
+                             "RESAMPLE" );
+
+  if( resampleMode == NULL )
+    resampleMode = "NEAREST";
+
+  /* -------------------------------------------------------------------- */
+  /*      We will require source and destination to have a valid          */
+  /*      projection object.                                              */
+  /* -------------------------------------------------------------------- */
+  if( map->projection.proj == NULL
+      || layer->projection.proj == NULL ) {
+    if( layer->debug )
+      msDebug( "msResampleGDALToMap(): "
+               "Either map or layer projection is NULL, assuming compatible.\n" );
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Initialize some information.                                    */
+  /* -------------------------------------------------------------------- */
+  nDstXSize = image->width;
+  nDstYSize = image->height;
+
+  memcpy( adfDstGeoTransform, map->gt.geotransform, sizeof(double)*6 );
+
+  msGetGDALGeoTransform( hDS, map, layer, adfSrcGeoTransform );
+
+  nSrcXSize = GDALGetRasterXSize( hDS );
+  nSrcYSize = GDALGetRasterYSize( hDS );
+
+  InvGeoTransform( adfSrcGeoTransform, adfInvSrcGeoTransform );
+
+  /* -------------------------------------------------------------------- */
+  /*      We need to find the extents in the source layer projection      */
+  /*      of the output requested region.  We will accomplish this by     */
+  /*      collecting the extents of a region around the edge of the       */
+  /*      destination chunk.                                              */
+  /* -------------------------------------------------------------------- */
+  if( CSLFetchBoolean( layer->processing, "LOAD_WHOLE_IMAGE", FALSE ) )
+    bSuccess = FALSE;
+  else
+    bSuccess =
+      msTransformMapToSource( nDstXSize, nDstYSize, adfDstGeoTransform,
+                              &(map->projection),
+                              nSrcXSize, nSrcYSize,adfInvSrcGeoTransform,
+                              &(layer->projection),
+                              &sSrcExtent, FALSE );
+
+  /* -------------------------------------------------------------------- */
+  /*      If the transformation failed, it is likely that we have such    */
+  /*      broad extents that the projection transformation failed at      */
+  /*      points around the extents.  If so, we will assume we need       */
+  /*      the whole raster.  This and later assumptions are likely to     */
+  /*      result in the raster being loaded at a higher resolution        */
+  /*      than really needed but should give decent results.              */
+  /* -------------------------------------------------------------------- */
+  if( !bSuccess ) {
+    if( layer->debug ) {
+      if( CSLFetchBoolean( layer->processing, "LOAD_WHOLE_IMAGE", FALSE ))
+        msDebug( "msResampleGDALToMap(): "
+                 "LOAD_WHOLE_IMAGE set, loading whole image.\n" );
+      else
+        msDebug( "msTransformMapToSource(): "
+                 "pj_transform() failed.  Out of bounds?  Loading whole image.\n" );
     }
 
-/* -------------------------------------------------------------------- */
-/*      Initialize some information.                                    */
-/* -------------------------------------------------------------------- */
-    nDstXSize = image->width;
-    nDstYSize = image->height;
-
-    memcpy( adfDstGeoTransform, map->gt.geotransform, sizeof(double)*6 );
-
-    msGetGDALGeoTransform( hDS, map, layer, adfSrcGeoTransform );
-
-    nSrcXSize = GDALGetRasterXSize( hDS );
-    nSrcYSize = GDALGetRasterYSize( hDS );
-
-    InvGeoTransform( adfSrcGeoTransform, adfInvSrcGeoTransform );
-
-/* -------------------------------------------------------------------- */
-/*      We need to find the extents in the source layer projection      */
-/*      of the output requested region.  We will accomplish this by     */
-/*      collecting the extents of a region around the edge of the       */
-/*      destination chunk.                                              */
-/* -------------------------------------------------------------------- */
-    if( CSLFetchBoolean( layer->processing, "LOAD_WHOLE_IMAGE", FALSE ) )
-        bSuccess = FALSE;
+    sSrcExtent.minx = 0;
+    sSrcExtent.maxx = nSrcXSize;
+    sSrcExtent.miny = 0;
+    sSrcExtent.maxy = nSrcYSize;
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Project desired extents out by 2 pixels, and then strip to      */
+  /*      available data.                                                 */
+  /* -------------------------------------------------------------------- */
+  memcpy( &sOrigSrcExtent, &sSrcExtent, sizeof(sSrcExtent) );
+
+  sSrcExtent.minx = floor(sSrcExtent.minx-1.0);
+  sSrcExtent.maxx = ceil (sSrcExtent.maxx+1.0);
+  sSrcExtent.miny = floor(sSrcExtent.miny-1.0);
+  sSrcExtent.maxy = ceil (sSrcExtent.maxy+1.0);
+
+  sSrcExtent.minx = MAX(0,sSrcExtent.minx);
+  sSrcExtent.maxx = MIN(sSrcExtent.maxx, nSrcXSize );
+  sSrcExtent.miny = MAX(sSrcExtent.miny, 0 );
+  sSrcExtent.maxy = MIN(sSrcExtent.maxy, nSrcYSize );
+
+  if( sSrcExtent.maxx <= sSrcExtent.minx
+      || sSrcExtent.maxy <= sSrcExtent.miny ) {
+    if( layer->debug )
+      msDebug( "msResampleGDALToMap(): no overlap ... no result.\n" );
+    return 0;
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Determine desired oversampling ratio.  Default to 2.0 if not    */
+  /*      otherwise set.                                                  */
+  /* -------------------------------------------------------------------- */
+  dfOversampleRatio = 2.0;
+
+  if( CSLFetchNameValue( layer->processing, "OVERSAMPLE_RATIO" ) != NULL ) {
+    dfOversampleRatio =
+      atof(CSLFetchNameValue( layer->processing, "OVERSAMPLE_RATIO" ));
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Decide on a resolution to read from the source image at.  We    */
+  /*      will operate from full resolution data, if we are requesting    */
+  /*      at near to full resolution.  Otherwise we will read the data    */
+  /*      at twice the resolution of the eventual map.                    */
+  /* -------------------------------------------------------------------- */
+  dfNominalCellSize =
+    sqrt(adfSrcGeoTransform[1] * adfSrcGeoTransform[1]
+         + adfSrcGeoTransform[2] * adfSrcGeoTransform[2]);
+
+  if( (sOrigSrcExtent.maxx - sOrigSrcExtent.minx) > dfOversampleRatio * nDstXSize
+      && !CSLFetchBoolean( layer->processing, "LOAD_FULL_RES_IMAGE", FALSE ))
+    sDummyMap.cellsize =
+      (dfNominalCellSize * (sOrigSrcExtent.maxx - sOrigSrcExtent.minx))
+      / (dfOversampleRatio * nDstXSize);
+  else
+    sDummyMap.cellsize = dfNominalCellSize;
+
+  nLoadImgXSize = MAX(1, (int) (sSrcExtent.maxx - sSrcExtent.minx)
+                      * (dfNominalCellSize / sDummyMap.cellsize));
+  nLoadImgYSize = MAX(1, (int) (sSrcExtent.maxy - sSrcExtent.miny)
+                      * (dfNominalCellSize / sDummyMap.cellsize));
+
+  /*
+  ** Because the previous calculation involved some round off, we need
+  ** to fixup the cellsize to ensure the map region represents the whole
+  ** RAW_WINDOW (at least in X).  Re: bug 1715.
+  */
+  sDummyMap.cellsize =
+    ((sSrcExtent.maxx - sSrcExtent.minx) * dfNominalCellSize)
+    / nLoadImgXSize;
+
+  if( layer->debug )
+    msDebug( "msResampleGDALToMap in effect: cellsize = %f\n",
+             sDummyMap.cellsize );
+
+  adfSrcGeoTransform[0] +=
+    + adfSrcGeoTransform[1] * sSrcExtent.minx
+    + adfSrcGeoTransform[2] * sSrcExtent.miny;
+  adfSrcGeoTransform[1] *= (sDummyMap.cellsize / dfNominalCellSize);
+  adfSrcGeoTransform[2] *= (sDummyMap.cellsize / dfNominalCellSize);
+
+  adfSrcGeoTransform[3] +=
+    + adfSrcGeoTransform[4] * sSrcExtent.minx
+    + adfSrcGeoTransform[5] * sSrcExtent.miny;
+  adfSrcGeoTransform[4] *= (sDummyMap.cellsize / dfNominalCellSize);
+  adfSrcGeoTransform[5] *= (sDummyMap.cellsize / dfNominalCellSize);
+
+  papszAlteredProcessing = CSLDuplicate( layer->processing );
+  papszAlteredProcessing =
+    CSLSetNameValue( papszAlteredProcessing, "RAW_WINDOW",
+                     CPLSPrintf( "%d %d %d %d",
+                                 (int) sSrcExtent.minx,
+                                 (int) sSrcExtent.miny,
+                                 (int) (sSrcExtent.maxx-sSrcExtent.minx),
+                                 (int) (sSrcExtent.maxy-sSrcExtent.miny)));
+
+  /* -------------------------------------------------------------------- */
+  /*      We clone this without referencing it knowing that the           */
+  /*      srcImage will take a reference on it.  The sDummyMap is         */
+  /*      destroyed off the stack, so the missing map reference is        */
+  /*      never a problem.  The image's dereference of the                */
+  /*      outputformat during the msFreeImage() calls will result in      */
+  /*      the output format being cleaned up.                             */
+  /*                                                                      */
+  /*      We make a copy so we can easily modify the outputformat used    */
+  /*      for the temporary image to include transparentency support.     */
+  /* -------------------------------------------------------------------- */
+  sDummyMap.outputformat = msCloneOutputFormat( image->format );
+  sDummyMap.width = nLoadImgXSize;
+  sDummyMap.height = nLoadImgYSize;
+  sDummyMap.mappath = map->mappath;
+  sDummyMap.shapepath = map->shapepath;
+
+  /* -------------------------------------------------------------------- */
+  /*      If we are working in 256 color GD mode, allocate 0 as the       */
+  /*      transparent color on the temporary image so it will be          */
+  /*      initialized to see-through.  We pick an arbitrary rgb tuple     */
+  /*      as our transparent color, but ensure it is initalized in the    */
+  /*      map so that normal transparent avoidance will apply.            */
+  /* -------------------------------------------------------------------- */
+  if( MS_RENDERER_PLUGIN(sDummyMap.outputformat) ) {
+    assert(rb);
+    msInitializeRendererVTable(sDummyMap.outputformat);
+#ifdef USE_GD
+    if( rb->type == MS_BUFFER_GD ) {
+      assert( !gdImageTrueColor( rb->data.gd_img ) );
+      sDummyMap.outputformat->transparent = MS_TRUE;
+      sDummyMap.imagecolor.red = 117;
+      sDummyMap.imagecolor.green = 17;
+      sDummyMap.imagecolor.blue = 191;
+    }
+    /* -------------------------------------------------------------------- */
+    /*      If we are working in RGB mode ensure we produce an RGBA         */
+    /*      image so the transparency can be preserved.                     */
+    /* -------------------------------------------------------------------- */
     else
-        bSuccess = 
-            msTransformMapToSource( nDstXSize, nDstYSize, adfDstGeoTransform,
-                                    &(map->projection),
-                                    nSrcXSize, nSrcYSize,adfInvSrcGeoTransform,
-                                    &(layer->projection),
-                                    &sSrcExtent, FALSE );
-
-/* -------------------------------------------------------------------- */
-/*      If the transformation failed, it is likely that we have such    */
-/*      broad extents that the projection transformation failed at      */
-/*      points around the extents.  If so, we will assume we need       */
-/*      the whole raster.  This and later assumptions are likely to     */
-/*      result in the raster being loaded at a higher resolution        */
-/*      than really needed but should give decent results.              */
-/* -------------------------------------------------------------------- */
-    if( !bSuccess )
+#endif
     {
-        if( layer->debug )
-        {
-            if( CSLFetchBoolean( layer->processing, "LOAD_WHOLE_IMAGE", FALSE ))
-                msDebug( "msResampleGDALToMap(): "
-                         "LOAD_WHOLE_IMAGE set, loading whole image.\n" );
-            else
-                msDebug( "msTransformMapToSource(): "
-                         "pj_transform() failed.  Out of bounds?  Loading whole image.\n" );
-        }
-
-        sSrcExtent.minx = 0;
-        sSrcExtent.maxx = nSrcXSize;
-        sSrcExtent.miny = 0;
-        sSrcExtent.maxy = nSrcYSize;
-    }
+      assert( sDummyMap.outputformat->imagemode == MS_IMAGEMODE_RGB
+              || sDummyMap.outputformat->imagemode == MS_IMAGEMODE_RGBA );
 
-/* -------------------------------------------------------------------- */
-/*      Project desired extents out by 2 pixels, and then strip to      */
-/*      available data.                                                 */
-/* -------------------------------------------------------------------- */
-    memcpy( &sOrigSrcExtent, &sSrcExtent, sizeof(sSrcExtent) );
-
-    sSrcExtent.minx = floor(sSrcExtent.minx-1.0);
-    sSrcExtent.maxx = ceil (sSrcExtent.maxx+1.0);
-    sSrcExtent.miny = floor(sSrcExtent.miny-1.0);
-    sSrcExtent.maxy = ceil (sSrcExtent.maxy+1.0);
-        
-    sSrcExtent.minx = MAX(0,sSrcExtent.minx);
-    sSrcExtent.maxx = MIN(sSrcExtent.maxx, nSrcXSize );
-    sSrcExtent.miny = MAX(sSrcExtent.miny, 0 );
-    sSrcExtent.maxy = MIN(sSrcExtent.maxy, nSrcYSize );
-        
-    if( sSrcExtent.maxx <= sSrcExtent.minx 
-        || sSrcExtent.maxy <= sSrcExtent.miny )
-    {
-        if( layer->debug )
-            msDebug( "msResampleGDALToMap(): no overlap ... no result.\n" );
-        return 0;
-    }
-    
-/* -------------------------------------------------------------------- */
-/*      Determine desired oversampling ratio.  Default to 2.0 if not    */
-/*      otherwise set.                                                  */
-/* -------------------------------------------------------------------- */
-    dfOversampleRatio = 2.0;
-
-    if( CSLFetchNameValue( layer->processing, "OVERSAMPLE_RATIO" ) != NULL )
-    {
-        dfOversampleRatio = 
-            atof(CSLFetchNameValue( layer->processing, "OVERSAMPLE_RATIO" ));
+      sDummyMap.outputformat->transparent = MS_TRUE;
+      sDummyMap.outputformat->imagemode = MS_IMAGEMODE_RGBA;
+      MS_INIT_COLOR(sDummyMap.imagecolor,-1,-1,-1,255);
     }
-    
-/* -------------------------------------------------------------------- */
-/*      Decide on a resolution to read from the source image at.  We    */
-/*      will operate from full resolution data, if we are requesting    */
-/*      at near to full resolution.  Otherwise we will read the data    */
-/*      at twice the resolution of the eventual map.                    */
-/* -------------------------------------------------------------------- */
-    dfNominalCellSize = 
-        sqrt(adfSrcGeoTransform[1] * adfSrcGeoTransform[1]
-             + adfSrcGeoTransform[2] * adfSrcGeoTransform[2]);
-    
-    if( (sOrigSrcExtent.maxx - sOrigSrcExtent.minx) > dfOversampleRatio * nDstXSize 
-        && !CSLFetchBoolean( layer->processing, "LOAD_FULL_RES_IMAGE", FALSE ))
-        sDummyMap.cellsize = 
-            (dfNominalCellSize * (sOrigSrcExtent.maxx - sOrigSrcExtent.minx))
-            / (dfOversampleRatio * nDstXSize);
-    else
-        sDummyMap.cellsize = dfNominalCellSize;
-
-    nLoadImgXSize = MAX(1, (int) (sSrcExtent.maxx - sSrcExtent.minx) 
-                              * (dfNominalCellSize / sDummyMap.cellsize));
-    nLoadImgYSize = MAX(1, (int) (sSrcExtent.maxy - sSrcExtent.miny) 
-                              * (dfNominalCellSize / sDummyMap.cellsize));
-        
-    /*
-    ** Because the previous calculation involved some round off, we need
-    ** to fixup the cellsize to ensure the map region represents the whole
-    ** RAW_WINDOW (at least in X).  Re: bug 1715. 
-    */
-    sDummyMap.cellsize = 
-        ((sSrcExtent.maxx - sSrcExtent.minx) * dfNominalCellSize) 
-        / nLoadImgXSize;
-
-    if( layer->debug )
-        msDebug( "msResampleGDALToMap in effect: cellsize = %f\n", 
-                 sDummyMap.cellsize );
-
-    adfSrcGeoTransform[0] += 
-        + adfSrcGeoTransform[1] * sSrcExtent.minx
-        + adfSrcGeoTransform[2] * sSrcExtent.miny;
-    adfSrcGeoTransform[1] *= (sDummyMap.cellsize / dfNominalCellSize);
-    adfSrcGeoTransform[2] *= (sDummyMap.cellsize / dfNominalCellSize);
-
-    adfSrcGeoTransform[3] += 
-        + adfSrcGeoTransform[4] * sSrcExtent.minx
-        + adfSrcGeoTransform[5] * sSrcExtent.miny;
-    adfSrcGeoTransform[4] *= (sDummyMap.cellsize / dfNominalCellSize);
-    adfSrcGeoTransform[5] *= (sDummyMap.cellsize / dfNominalCellSize);
-
-    papszAlteredProcessing = CSLDuplicate( layer->processing );
-    papszAlteredProcessing = 
-        CSLSetNameValue( papszAlteredProcessing, "RAW_WINDOW", 
-                         CPLSPrintf( "%d %d %d %d", 
-                                     (int) sSrcExtent.minx,
-                                     (int) sSrcExtent.miny, 
-                                     (int) (sSrcExtent.maxx-sSrcExtent.minx),
-                                     (int) (sSrcExtent.maxy-sSrcExtent.miny)));
-    
-/* -------------------------------------------------------------------- */
-/*      We clone this without referencing it knowing that the           */
-/*      srcImage will take a reference on it.  The sDummyMap is         */
-/*      destroyed off the stack, so the missing map reference is        */
-/*      never a problem.  The image's dereference of the                */
-/*      outputformat during the msFreeImage() calls will result in      */
-/*      the output format being cleaned up.                             */
-/*                                                                      */
-/*      We make a copy so we can easily modify the outputformat used    */
-/*      for the temporary image to include transparentency support.     */
-/* -------------------------------------------------------------------- */
-    sDummyMap.outputformat = msCloneOutputFormat( image->format );
-    sDummyMap.width = nLoadImgXSize;
-    sDummyMap.height = nLoadImgYSize;
-    
-/* -------------------------------------------------------------------- */
-/*      If we are working in 256 color GD mode, allocate 0 as the       */
-/*      transparent color on the temporary image so it will be          */
-/*      initialized to see-through.  We pick an arbitrary rgb tuple     */
-/*      as our transparent color, but ensure it is initalized in the    */
-/*      map so that normal transparent avoidance will apply.            */
-/* -------------------------------------------------------------------- */
-    if( MS_RENDERER_PLUGIN(sDummyMap.outputformat) ) {
-    	assert(rb);
-    	msInitializeRendererVTable(sDummyMap.outputformat);
-    	if( rb->type == MS_BUFFER_GD ) {
-            assert( !gdImageTrueColor( rb->data.gd_img ) );
-            sDummyMap.outputformat->transparent = MS_TRUE;
-            sDummyMap.imagecolor.red = 117;
-            sDummyMap.imagecolor.green = 17;
-            sDummyMap.imagecolor.blue = 191;
-        }
-/* -------------------------------------------------------------------- */
-/*      If we are working in RGB mode ensure we produce an RGBA         */
-/*      image so the transparency can be preserved.                     */
-/* -------------------------------------------------------------------- */
-        else
-        {
-            assert( sDummyMap.outputformat->imagemode == MS_IMAGEMODE_RGB
-                    || sDummyMap.outputformat->imagemode == MS_IMAGEMODE_RGBA );
-	
-            sDummyMap.outputformat->transparent = MS_TRUE;
-            sDummyMap.outputformat->imagemode = MS_IMAGEMODE_RGBA;
-            MS_INIT_COLOR(sDummyMap.imagecolor,-1,-1,-1,255);
-        }
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Setup a dummy map object we can use to read from the source     */
+  /*      raster, with the newly established extents, and resolution.     */
+  /* -------------------------------------------------------------------- */
+  srcImage = msImageCreate( nLoadImgXSize, nLoadImgYSize,
+                            sDummyMap.outputformat, NULL, NULL,
+                            map->resolution, map->defresolution, &(sDummyMap.imagecolor));
+
+  if (srcImage == NULL)
+    return -1; /* msSetError() should have been called already */
+
+  if( MS_RENDERER_PLUGIN( srcImage->format ) ) {
+    psrc_rb = &src_rb;
+    memset( psrc_rb, 0, sizeof(rasterBufferObj) );
+    if( srcImage->format->vtable->supports_pixel_buffer ) {
+      srcImage->format->vtable->getRasterBufferHandle( srcImage, psrc_rb );
+    } else {
+      srcImage->format->vtable->initializeRasterBuffer(psrc_rb,nLoadImgXSize, nLoadImgYSize,MS_IMAGEMODE_RGBA);
     }
+  }
 
-/* -------------------------------------------------------------------- */
-/*      Setup a dummy map object we can use to read from the source     */
-/*      raster, with the newly established extents, and resolution.     */
-/* -------------------------------------------------------------------- */
-    srcImage = msImageCreate( nLoadImgXSize, nLoadImgYSize,
-                              sDummyMap.outputformat, NULL, NULL, 
-                              map->resolution, map->defresolution, &(sDummyMap.imagecolor));
+  /* -------------------------------------------------------------------- */
+  /*      Draw into the temporary image.  Temporarily replace the         */
+  /*      layer processing directive so that we use our RAW_WINDOW.       */
+  /* -------------------------------------------------------------------- */
+  {
+    char **papszSavedProcessing = layer->processing;
 
-    if (srcImage == NULL)
-        return -1; /* msSetError() should have been called already */
+    layer->processing = papszAlteredProcessing;
 
-    if( MS_RENDERER_PLUGIN( srcImage->format ) )
-    {
-        psrc_rb = &src_rb;
-        memset( psrc_rb, 0, sizeof(rasterBufferObj) );
-        if( srcImage->format->vtable->supports_pixel_buffer )
-        {
-            srcImage->format->vtable->getRasterBufferHandle( srcImage, psrc_rb );
-        } else {
-            srcImage->format->vtable->initializeRasterBuffer(psrc_rb,nLoadImgXSize, nLoadImgYSize,MS_IMAGEMODE_RGBA);
-        }
-    }
-
-/* -------------------------------------------------------------------- */
-/*      Draw into the temporary image.  Temporarily replace the         */
-/*      layer processing directive so that we use our RAW_WINDOW.       */
-/* -------------------------------------------------------------------- */
-    {
-        char **papszSavedProcessing = layer->processing;
+    result = msDrawRasterLayerGDAL( &sDummyMap, layer, srcImage,
+                                    psrc_rb, hDS );
 
-        layer->processing = papszAlteredProcessing;
+    layer->processing = papszSavedProcessing;
+    CSLDestroy( papszAlteredProcessing );
 
-        result = msDrawRasterLayerGDAL( &sDummyMap, layer, srcImage, 
-                                        psrc_rb, hDS );
+    if( result ) {
+      if( MS_RENDERER_PLUGIN( srcImage->format ) && !srcImage->format->vtable->supports_pixel_buffer)
+        msFreeRasterBuffer(psrc_rb);
 
-        layer->processing = papszSavedProcessing;
-        CSLDestroy( papszAlteredProcessing );
+      msFreeImage( srcImage );
 
-        if( result )
-        {
-            if( MS_RENDERER_PLUGIN( srcImage->format ) && !srcImage->format->vtable->supports_pixel_buffer)
-                msFreeRasterBuffer(psrc_rb);
-            
-            msFreeImage( srcImage );
-            
-            return result;
-        }
+      return result;
     }
-
-/* -------------------------------------------------------------------- */
-/*      Do we need to generate a colormap remapping, potentially        */
-/*      allocating new colors on the destination color map?             */
-/* -------------------------------------------------------------------- */
-    if( psrc_rb && psrc_rb->type == MS_BUFFER_GD )
-    {
-        int  iColor, nColorCount;
-
-        anCMap[0] = -1; /* color zero is always transparent */
-
-        nColorCount = gdImageColorsTotal( psrc_rb->data.gd_img );
-        for( iColor = 1; iColor < nColorCount; iColor++ )
-        {
-            anCMap[iColor] = 
-                msAddColorGD( map, rb->data.gd_img, 0, 
-                              gdImageRed( psrc_rb->data.gd_img, iColor ),
-                              gdImageGreen( psrc_rb->data.gd_img, iColor ),
-                              gdImageBlue( psrc_rb->data.gd_img, iColor ) );
-        }
-        for( iColor = nColorCount; iColor < 256; iColor++ )
-            anCMap[iColor] = -1;
-    }
-/* -------------------------------------------------------------------- */
-/*      Setup transformations between our source image, and the         */
-/*      target map image.                                               */
-/* -------------------------------------------------------------------- */
-    pTCBData = msInitProjTransformer( &(layer->projection), 
-                                      adfSrcGeoTransform, 
-                                      &(map->projection), 
-                                      adfDstGeoTransform );
-    
-    if( pTCBData == NULL )
-    {
-        if( layer->debug )
-            msDebug( "msInitProjTransformer() returned NULL.\n" );
-        if( MS_RENDERER_PLUGIN( srcImage->format ) && !srcImage->format->vtable->supports_pixel_buffer)
-            msFreeRasterBuffer(psrc_rb);
-        msFreeImage( srcImage );
-        return MS_PROJERR;
+  }
+
+#ifdef USE_GD
+  /* -------------------------------------------------------------------- */
+  /*      Do we need to generate a colormap remapping, potentially        */
+  /*      allocating new colors on the destination color map?             */
+  /* -------------------------------------------------------------------- */
+  if( psrc_rb && psrc_rb->type == MS_BUFFER_GD ) {
+    int  iColor, nColorCount;
+
+    anCMap[0] = -1; /* color zero is always transparent */
+
+    nColorCount = gdImageColorsTotal( psrc_rb->data.gd_img );
+    for( iColor = 1; iColor < nColorCount; iColor++ ) {
+      anCMap[iColor] =
+        msAddColorGD( map, rb->data.gd_img, 0,
+                      gdImageRed( psrc_rb->data.gd_img, iColor ),
+                      gdImageGreen( psrc_rb->data.gd_img, iColor ),
+                      gdImageBlue( psrc_rb->data.gd_img, iColor ) );
     }
+    for( iColor = nColorCount; iColor < 256; iColor++ )
+      anCMap[iColor] = -1;
+  }
+#endif
 
-/* -------------------------------------------------------------------- */
-/*      It is cheaper to use linear approximations as long as our       */
-/*      error is modest (less than 0.333 pixels).                       */
-/* -------------------------------------------------------------------- */
-    pACBData = msInitApproxTransformer( msProjTransformer, pTCBData, 0.333 );
-
-/* -------------------------------------------------------------------- */
-/*      Perform the resampling.                                         */
-/* -------------------------------------------------------------------- */
-    if( EQUAL(resampleMode,"AVERAGE") )
-        result = 
-            msAverageRasterResampler( srcImage, psrc_rb, image, rb, 
-                                      anCMap, msApproxTransformer, pACBData,
-                                      layer->debug );
-    else if( EQUAL(resampleMode,"BILINEAR") )
-        result = 
-            msBilinearRasterResampler( srcImage, psrc_rb, image, rb,
-                                       anCMap, msApproxTransformer, pACBData,
-                                       layer->debug );
-    else
-        result = 
-            msNearestRasterResampler( srcImage, psrc_rb, image, rb,
-                                      anCMap, msApproxTransformer, pACBData,
-                                      layer->debug );
-
-/* -------------------------------------------------------------------- */
-/*      cleanup                                                         */
-/* -------------------------------------------------------------------- */
+  /* -------------------------------------------------------------------- */
+  /*      Setup transformations between our source image, and the         */
+  /*      target map image.                                               */
+  /* -------------------------------------------------------------------- */
+  pTCBData = msInitProjTransformer( &(layer->projection),
+                                    adfSrcGeoTransform,
+                                    &(map->projection),
+                                    adfDstGeoTransform );
+
+  if( pTCBData == NULL ) {
+    if( layer->debug )
+      msDebug( "msInitProjTransformer() returned NULL.\n" );
     if( MS_RENDERER_PLUGIN( srcImage->format ) && !srcImage->format->vtable->supports_pixel_buffer)
-        msFreeRasterBuffer(psrc_rb);
+      msFreeRasterBuffer(psrc_rb);
     msFreeImage( srcImage );
-
-    msFreeProjTransformer( pTCBData );
-    msFreeApproxTransformer( pACBData );
-    
-    return result;
+    return MS_PROJERR;
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      It is cheaper to use linear approximations as long as our       */
+  /*      error is modest (less than 0.333 pixels).                       */
+  /* -------------------------------------------------------------------- */
+  pACBData = msInitApproxTransformer( msProjTransformer, pTCBData, 0.333 );
+
+  /* -------------------------------------------------------------------- */
+  /*      Perform the resampling.                                         */
+  /* -------------------------------------------------------------------- */
+  if( EQUAL(resampleMode,"AVERAGE") )
+    result =
+      msAverageRasterResampler( srcImage, psrc_rb, image, rb,
+                                anCMap, msApproxTransformer, pACBData,
+                                layer->debug );
+  else if( EQUAL(resampleMode,"BILINEAR") )
+    result =
+      msBilinearRasterResampler( srcImage, psrc_rb, image, rb,
+                                 anCMap, msApproxTransformer, pACBData,
+                                 layer->debug );
+  else
+    result =
+      msNearestRasterResampler( srcImage, psrc_rb, image, rb,
+                                anCMap, msApproxTransformer, pACBData,
+                                layer->debug );
+
+  /* -------------------------------------------------------------------- */
+  /*      cleanup                                                         */
+  /* -------------------------------------------------------------------- */
+  if( MS_RENDERER_PLUGIN( srcImage->format ) && !srcImage->format->vtable->supports_pixel_buffer)
+    msFreeRasterBuffer(psrc_rb);
+  msFreeImage( srcImage );
+
+  msFreeProjTransformer( pTCBData );
+  msFreeApproxTransformer( pACBData );
+
+  return result;
 #endif
 }
 
diff --git a/mapresample.h b/mapresample.h
index 6a46b55..f17ee77 100644
--- a/mapresample.h
+++ b/mapresample.h
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -30,7 +30,6 @@
 #ifndef RESAMPLE_H
 #define RESAMPLE_H
 
-#include <gd.h>
 #include "mapserver.h"
 #include "mapproject.h"
 
@@ -39,19 +38,19 @@
 #  include <cpl_string.h>
 #endif
 
-typedef int (*SimpleTransformer)( void *pCBData, int nPoints, 
+typedef int (*SimpleTransformer)( void *pCBData, int nPoints,
                                   double *x, double *y, int *panSuccess );
 
-void *msInitProjTransformer( projectionObj *psSrc, 
-                             double *padfSrcGeoTransform, 
-                             projectionObj *psDst, 
+void *msInitProjTransformer( projectionObj *psSrc,
+                             double *padfSrcGeoTransform,
+                             projectionObj *psDst,
                              double *padfDstGeoTransform );
 void msFreeProjTransformer( void * );
-int msProjTransformer( void *pCBData, int nPoints, 
+int msProjTransformer( void *pCBData, int nPoints,
                        double *x, double *y, int *panSuccess );
 #ifdef USE_GDAL
-int msResampleGDALToMap( mapObj *map, layerObj *layer, 
-                         imageObj *image, rasterBufferObj *rb, 
+int msResampleGDALToMap( mapObj *map, layerObj *layer,
+                         imageObj *image, rasterBufferObj *rb,
                          GDALDatasetH hDS );
 #endif
 #endif /* ndef RESAMPLE_H */
diff --git a/mapscale.c b/mapscale.c
index 4f1cf11..2770ce1 100644
--- a/mapscale.c
+++ b/mapscale.c
@@ -2,7 +2,7 @@
  * $Id$
  *
  * Project:  MapServer
- * Purpose:  Scale object rendering. 
+ * Purpose:  Scale object rendering.
  * Author:   Steve Lime and the MapServer team.
  *
  ******************************************************************************
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -29,7 +29,7 @@
 
 #include "mapserver.h"
 
-MS_CVSID("$Id$")
+
 
 #define VMARGIN 3 /* buffer around the scalebar */
 #define HMARGIN 3
@@ -39,8 +39,8 @@ MS_CVSID("$Id$")
 /*
 ** Match this with with unit enumerations is mapserver.h
 */
-static char *unitText[9]={"in", "ft", "mi", "m", "km", "dd", "??", "??", "NM"}; //MS_PIXEL and MS_PERCENTAGE not used
-double inchesPerUnit[9]={1, 12, 63360.0, 39.3701, 39370.1, 4374754, 1, 1, 72913.3858 };
+static char *unitText[9]= {"in", "ft", "mi", "m", "km", "dd", "??", "??", "NM"}; /* MS_PIXEL and MS_PERCENTAGE not used */
+double inchesPerUnit[9]= {1, 12, 63360.0, 39.3701, 39370.1, 4374754, 1, 1, 72913.3858 };
 
 static double roundInterval(double d)
 {
@@ -83,28 +83,28 @@ int msCalculateScale(rectObj extent, int units, int width, int height, double re
     msSetError(MS_MISCERR, "Invalid image extent, minx=%lf, miny=%lf, maxx=%lf, maxy=%lf.", "msCalculateScale()", extent.minx, extent.miny, extent.maxx, extent.maxy);
     return(MS_FAILURE);
   }
-  
+
   if((width <= 0) || (height <= 0)) {
     msSetError(MS_MISCERR, "Invalid image width or height.", "msCalculateScale()");
     return(MS_FAILURE);
   }
 
   switch (units) {
-  case(MS_DD):
-  case(MS_METERS):    
-  case(MS_KILOMETERS):
-  case(MS_MILES):
-  case(MS_NAUTICALMILES):
-  case(MS_INCHES):  
-  case(MS_FEET):
-    center_y = (extent.miny+extent.maxy)/2.0;
-    md = (width-1)/(resolution*msInchesPerUnit(units, center_y)); /* remember, we use a pixel-center to pixel-center extent, hence the width-1 */
-    gd = extent.maxx - extent.minx;
-    *scale = gd/md;
-    break;
-  default:
-    *scale = -1; /* this is not an error */
-    break;
+    case(MS_DD):
+    case(MS_METERS):
+    case(MS_KILOMETERS):
+    case(MS_MILES):
+    case(MS_NAUTICALMILES):
+    case(MS_INCHES):
+    case(MS_FEET):
+      center_y = (extent.miny+extent.maxy)/2.0;
+      md = (width-1)/(resolution*msInchesPerUnit(units, center_y)); /* remember, we use a pixel-center to pixel-center extent, hence the width-1 */
+      gd = extent.maxx - extent.minx;
+      *scale = gd/md;
+      break;
+    default:
+      *scale = -1; /* this is not an error */
+      break;
   }
 
   return(MS_SUCCESS);
@@ -115,31 +115,30 @@ double msInchesPerUnit(int units, double center_lat)
   double lat_adj = 1.0, ipu = 1.0;
 
   switch (units) {
-  case(MS_METERS):    
-  case(MS_KILOMETERS):
-  case(MS_MILES):
-  case(MS_NAUTICALMILES):
-  case(MS_INCHES):  
-  case(MS_FEET):
-    ipu = inchesPerUnit[units]; 
-    break;
-  case(MS_DD):
-    /* With geographical (DD) coordinates, we adjust the inchesPerUnit
-     * based on the latitude of the center of the view. For this we assume
-     * we have a perfect sphere and just use cos(lat) in our calculation.
-     */
+    case(MS_METERS):
+    case(MS_KILOMETERS):
+    case(MS_MILES):
+    case(MS_NAUTICALMILES):
+    case(MS_INCHES):
+    case(MS_FEET):
+      ipu = inchesPerUnit[units];
+      break;
+    case(MS_DD):
+      /* With geographical (DD) coordinates, we adjust the inchesPerUnit
+       * based on the latitude of the center of the view. For this we assume
+       * we have a perfect sphere and just use cos(lat) in our calculation.
+       */
 #ifdef ENABLE_VARIABLE_INCHES_PER_DEGREE
-    if (center_lat != 0.0)
-    {
+      if (center_lat != 0.0) {
         double cos_lat;
         cos_lat = cos(MS_PI*center_lat/180.0);
         lat_adj = sqrt(1+cos_lat*cos_lat)/sqrt(2.0);
-    }
+      }
 #endif
-    ipu = inchesPerUnit[units]*lat_adj;
-    break;
-  default:
-    break;
+      ipu = inchesPerUnit[units]*lat_adj;
+      break;
+    default:
+      break;
   }
 
   return ipu;
@@ -168,7 +167,7 @@ imageObj *msDrawScalebar(mapObj *map)
   rendererVTableObj *renderer;
 
   strokeStyle.patternlength=0;
-  
+
   if(map->units == -1) {
     msSetError(MS_MISCERR, "Map units not set.", "msDrawScalebar()");
     return(NULL);
@@ -176,33 +175,32 @@ imageObj *msDrawScalebar(mapObj *map)
 
   renderer = MS_MAP_RENDERER(map);
   if(!renderer || !MS_MAP_RENDERER(map)->supports_pixel_buffer) {
-	msSetError(MS_MISCERR, "Outputformat not supported for scalebar", "msDrawScalebar()");
-	return(NULL);
+    msSetError(MS_MISCERR, "Outputformat not supported for scalebar", "msDrawScalebar()");
+    return(NULL);
   }
-  
-/*
- *  A string containing the ten decimal digits is rendered to compute an average cell size 
- *  for each number, which is used later to place labels on the scalebar.
- */
-  
+
+  /*
+   *  A string containing the ten decimal digits is rendered to compute an average cell size
+   *  for each number, which is used later to place labels on the scalebar.
+   */
+
   if(msGetLabelSize(map,&map->scalebar.label,"0123456789",map->scalebar.label.size,&r,NULL) != MS_SUCCESS) {
-	  return NULL;
+    return NULL;
   }
   fontWidth = (r.maxx-r.minx)/10.0;
   fontHeight = r.maxy -r.miny;
 
   map->cellsize = msAdjustExtent(&(map->extent), map->width, map->height);
   status = msCalculateScale(map->extent, map->units, map->width, map->height, map->resolution, &map->scaledenom);
-  if(status != MS_SUCCESS)
-  { 	
-	return(NULL);
+  if(status != MS_SUCCESS) {
+    return(NULL);
   }
   dsx = map->scalebar.width - 2*HMARGIN;
   do {
     msx = (map->cellsize * dsx)/(msInchesPerUnit(map->scalebar.units,0)/msInchesPerUnit(map->units,0));
     i = roundInterval(msx/map->scalebar.intervals);
     snprintf(label, sizeof(label), "%g", map->scalebar.intervals*i); /* last label */
-    isx = MS_NINT((i/(msInchesPerUnit(map->units,0)/msInchesPerUnit(map->scalebar.units,0)))/map->cellsize);  
+    isx = MS_NINT((i/(msInchesPerUnit(map->units,0)/msInchesPerUnit(map->scalebar.units,0)))/map->cellsize);
     sx = (map->scalebar.intervals*isx) + MS_NINT((1.5 + strlen(label)/2.0 + strlen(unitText[map->scalebar.units]))*fontWidth);
 
     if(sx <= (map->scalebar.width - 2*HMARGIN)) break; /* it will fit */
@@ -213,20 +211,20 @@ imageObj *msDrawScalebar(mapObj *map)
   sy = (2*VMARGIN) + MS_NINT(VSPACING*fontHeight) + fontHeight + map->scalebar.height - VSLOP;
 
   /*Ensure we have an image format representing the options for the scalebar.*/
-  msApplyOutputFormat( &format, map->outputformat, 
-                       map->scalebar.transparent, 
-                       map->scalebar.interlace, 
+  msApplyOutputFormat( &format, map->outputformat,
+                       map->scalebar.transparent,
+                       map->scalebar.interlace,
                        MS_NOOVERRIDE );
 
   if(map->scalebar.transparent == MS_OFF) {
-     if(!MS_VALID_COLOR(map->scalebar.imagecolor))
-        MS_INIT_COLOR(map->scalebar.imagecolor,255,255,255,255);
+    if(!MS_VALID_COLOR(map->scalebar.imagecolor))
+      MS_INIT_COLOR(map->scalebar.imagecolor,255,255,255,255);
   }
   image = msImageCreate(map->scalebar.width, sy, format,
-          map->web.imagepath, map->web.imageurl, map->resolution, map->defresolution, &map->scalebar.imagecolor);
+                        map->web.imagepath, map->web.imageurl, map->resolution, map->defresolution, &map->scalebar.imagecolor);
 
   /* drop this reference to output format */
-  msApplyOutputFormat( &format, NULL, 
+  msApplyOutputFormat( &format, NULL,
                        MS_NOOVERRIDE, MS_NOOVERRIDE, MS_NOOVERRIDE );
 
   /* did we succeed in creating the image? */
@@ -234,106 +232,103 @@ imageObj *msDrawScalebar(mapObj *map)
     msSetError(MS_MISCERR, "Unable to initialize image.", "msDrawScalebar()");
     return NULL;
   }
-  
+
   switch(map->scalebar.align) {
-  case(MS_ALIGN_LEFT):
-    ox = HMARGIN;
-    break;
-  case(MS_ALIGN_RIGHT):
-    ox = MS_NINT((map->scalebar.width - sx) + fontWidth);
-    break;
-  default:
-    ox = MS_NINT((map->scalebar.width - sx)/2.0 + fontWidth/2.0); /* center the computed scalebar */
+    case(MS_ALIGN_LEFT):
+      ox = HMARGIN;
+      break;
+    case(MS_ALIGN_RIGHT):
+      ox = MS_NINT((map->scalebar.width - sx) + fontWidth);
+      break;
+    default:
+      ox = MS_NINT((map->scalebar.width - sx)/2.0 + fontWidth/2.0); /* center the computed scalebar */
   }
   oy = VMARGIN;
 
   switch(map->scalebar.style) {
-  case(0):
-		{
-	  
-	  line.numpoints = 5;
-	  line.point = points;
-	  shape.line = &line;
-	  shape.numlines = 1;
-	  if(MS_VALID_COLOR(map->scalebar.color)) {
-	     INIT_STROKE_STYLE(strokeStyle);
-	     strokeStyle.color = &map->scalebar.outlinecolor;
-	     strokeStyle.color->alpha = 255;
-	     strokeStyle.width = 1;
-	  }
-	  map->scalebar.backgroundcolor.alpha = 255;
-	  map->scalebar.color.alpha = 255;
-	  state = 1; /* 1 means filled */
-	  for(j=0; j<map->scalebar.intervals; j++) {
-		  points[0].x = points[4].x = points[3].x = ox + j*isx + 0.5;
-		  points[0].y = points[4].y = points[1].y = oy + 0.5;
-		  points[1].x = points[2].x = ox + (j+1)*isx + 0.5;
-		  points[2].y = points[3].y = oy + map->scalebar.height + 0.5;
-		  if(state == 1 && MS_VALID_COLOR(map->scalebar.color))
-			  renderer->renderPolygon(image,&shape,&map->scalebar.color);
-		  else 
-			  if(MS_VALID_COLOR(map->scalebar.backgroundcolor))
-				  renderer->renderPolygon(image,&shape,&map->scalebar.backgroundcolor);
-
-		  if(strokeStyle.color)
-			  renderer->renderLine(image,&shape,&strokeStyle);
-
-		  sprintf(label, "%g", j*i);
-		  map->scalebar.label.position = MS_CC;
-		  p.x = ox + j*isx; /* + MS_NINT(fontPtr->w/2); */
-		  p.y = oy + map->scalebar.height + MS_NINT(VSPACING*fontHeight);
-		  msDrawLabel(map,image,p,label,&map->scalebar.label,1.0);
-		  state = -state;
-	  }
-	  sprintf(label, "%g", j*i);
-	  ox = ox + j*isx - MS_NINT((strlen(label)*fontWidth)/2.0);
-	  sprintf(label, "%g %s", j*i, unitText[map->scalebar.units]);
-	  map->scalebar.label.position = MS_CR;
-	  p.x = ox; /* + MS_NINT(fontPtr->w/2); */
-	  p.y = oy + map->scalebar.height + MS_NINT(VSPACING*fontHeight);
-	  msDrawLabel(map,image,p,label,&map->scalebar.label,1.0);
-
-	  break;
-		}
-  case(1):
-		{
-	  line.numpoints = 2;
-	  line.point = points;
-	  shape.line = &line;
-	  shape.numlines = 1;
-	  if(MS_VALID_COLOR(map->scalebar.color)) {
+    case(0): {
+
+      line.numpoints = 5;
+      line.point = points;
+      shape.line = &line;
+      shape.numlines = 1;
+      if(MS_VALID_COLOR(map->scalebar.color)) {
+        INIT_STROKE_STYLE(strokeStyle);
+        strokeStyle.color = &map->scalebar.outlinecolor;
+        strokeStyle.color->alpha = 255;
+        strokeStyle.width = 1;
+      }
+      map->scalebar.backgroundcolor.alpha = 255;
+      map->scalebar.color.alpha = 255;
+      state = 1; /* 1 means filled */
+      for(j=0; j<map->scalebar.intervals; j++) {
+        points[0].x = points[4].x = points[3].x = ox + j*isx + 0.5;
+        points[0].y = points[4].y = points[1].y = oy + 0.5;
+        points[1].x = points[2].x = ox + (j+1)*isx + 0.5;
+        points[2].y = points[3].y = oy + map->scalebar.height + 0.5;
+        if(state == 1 && MS_VALID_COLOR(map->scalebar.color))
+          renderer->renderPolygon(image,&shape,&map->scalebar.color);
+        else if(MS_VALID_COLOR(map->scalebar.backgroundcolor))
+          renderer->renderPolygon(image,&shape,&map->scalebar.backgroundcolor);
+
+        if(strokeStyle.color)
+          renderer->renderLine(image,&shape,&strokeStyle);
+
+        sprintf(label, "%g", j*i);
+        map->scalebar.label.position = MS_CC;
+        p.x = ox + j*isx; /* + MS_NINT(fontPtr->w/2); */
+        p.y = oy + map->scalebar.height + MS_NINT(VSPACING*fontHeight);
+        msDrawLabel(map,image,p,label,&map->scalebar.label,1.0);
+        state = -state;
+      }
+      sprintf(label, "%g", j*i);
+      ox = ox + j*isx - MS_NINT((strlen(label)*fontWidth)/2.0);
+      sprintf(label, "%g %s", j*i, unitText[map->scalebar.units]);
+      map->scalebar.label.position = MS_CR;
+      p.x = ox; /* + MS_NINT(fontPtr->w/2); */
+      p.y = oy + map->scalebar.height + MS_NINT(VSPACING*fontHeight);
+      msDrawLabel(map,image,p,label,&map->scalebar.label,1.0);
+
+      break;
+    }
+    case(1): {
+      line.numpoints = 2;
+      line.point = points;
+      shape.line = &line;
+      shape.numlines = 1;
+      if(MS_VALID_COLOR(map->scalebar.color)) {
         strokeStyle.width = 1;
         strokeStyle.color = &map->scalebar.color;
-	  }
-	  
-	  points[0].y = points[1].y = oy;
-	  points[0].x = ox;
-	  points[1].x = ox + isx*map->scalebar.intervals;
-	  renderer->renderLine(image,&shape,&strokeStyle);
-	  
-	  points[0].y = oy;
-	  points[1].y = oy + map->scalebar.height;
-	  p.y = oy + map->scalebar.height + MS_NINT(VSPACING*fontHeight);
-	  for(j=0; j<=map->scalebar.intervals; j++) {
-		  points[0].x = points[1].x = ox + j*isx;
-		  renderer->renderLine(image,&shape,&strokeStyle);
-		  
-		  sprintf(label, "%g", j*i);
-		  if(j!=map->scalebar.intervals) {
-			  map->scalebar.label.position = MS_CC;
-			  p.x = ox + j*isx; /* + MS_NINT(fontPtr->w/2); */
-		  } else {
-			  sprintf(label, "%g %s", j*i, unitText[map->scalebar.units]);
-			  map->scalebar.label.position = MS_CR;
-			  p.x = ox + j*isx - MS_NINT((strlen(label)*fontWidth)/2.0);
-		  }
-		  msDrawLabel(map,image,p,label,&map->scalebar.label,1.0);
-	  }
-	  break;
-		}
-  default:
-	  msSetError(MS_MISCERR, "Unsupported scalebar style.", "msDrawScalebar()");
-	  return(NULL);
+      }
+
+      points[0].y = points[1].y = oy;
+      points[0].x = ox;
+      points[1].x = ox + isx*map->scalebar.intervals;
+      renderer->renderLine(image,&shape,&strokeStyle);
+
+      points[0].y = oy;
+      points[1].y = oy + map->scalebar.height;
+      p.y = oy + map->scalebar.height + MS_NINT(VSPACING*fontHeight);
+      for(j=0; j<=map->scalebar.intervals; j++) {
+        points[0].x = points[1].x = ox + j*isx;
+        renderer->renderLine(image,&shape,&strokeStyle);
+
+        sprintf(label, "%g", j*i);
+        if(j!=map->scalebar.intervals) {
+          map->scalebar.label.position = MS_CC;
+          p.x = ox + j*isx; /* + MS_NINT(fontPtr->w/2); */
+        } else {
+          sprintf(label, "%g %s", j*i, unitText[map->scalebar.units]);
+          map->scalebar.label.position = MS_CR;
+          p.x = ox + j*isx - MS_NINT((strlen(label)*fontWidth)/2.0);
+        }
+        msDrawLabel(map,image,p,label,&map->scalebar.label,1.0);
+      }
+      break;
+    }
+    default:
+      msSetError(MS_MISCERR, "Unsupported scalebar style.", "msDrawScalebar()");
+      return(NULL);
   }
   return(image);
 
@@ -341,110 +336,120 @@ imageObj *msDrawScalebar(mapObj *map)
 
 int msEmbedScalebar(mapObj *map, imageObj *img)
 {
-  int l,index;
+  int l,index,s;
   pointObj point;
   imageObj *image = NULL;
   rendererVTableObj *renderer = MS_MAP_RENDERER(map);
   symbolObj *embededSymbol;
-  
+
   if( ! renderer ) {
-	  msSetError(MS_MISCERR,"unsupported outputformat","msEmbedScalebar()");
-	  return MS_FAILURE;
+    msSetError(MS_MISCERR,"unsupported outputformat","msEmbedScalebar()");
+    return MS_FAILURE;
   }
   index = msGetSymbolIndex(&(map->symbolset), "scalebar", MS_FALSE);
   if(index != -1)
-	  msRemoveSymbol(&(map->symbolset), index); /* remove cached symbol in case the function is called multiple
-											times with different zoom levels */
+    msRemoveSymbol(&(map->symbolset), index); /* remove cached symbol in case the function is called multiple
+                      times with different zoom levels */
 
   if((embededSymbol=msGrowSymbolSet(&map->symbolset)) == NULL)
     return MS_FAILURE;
+  s = map->symbolset.numsymbols;
   map->symbolset.numsymbols++;
-  
+
   image = msDrawScalebar(map);
   if(!image) {
-	  msSetError(MS_RENDERERERR,"failed to create scalebar image","msEmbedScalebar()");
-	  return MS_FAILURE;
+    return MS_FAILURE;
   }
   embededSymbol->pixmap_buffer = calloc(1,sizeof(rasterBufferObj));
   MS_CHECK_ALLOC(embededSymbol->pixmap_buffer, sizeof(rasterBufferObj), MS_FAILURE);
 
   if(MS_SUCCESS != renderer->getRasterBufferCopy(image,embededSymbol->pixmap_buffer)) {
-	  return MS_FAILURE;
+    return MS_FAILURE;
   }
-  
+
   embededSymbol->type = MS_SYMBOL_PIXMAP; /* intialize a few things */
-  embededSymbol->name = msStrdup("scalebar");  
+  embededSymbol->name = msStrdup("scalebar");
   embededSymbol->sizex = embededSymbol->pixmap_buffer->width;
   embededSymbol->sizey = embededSymbol->pixmap_buffer->height;
   if(map->scalebar.transparent) {
-      embededSymbol->transparent = MS_TRUE;
-      embededSymbol->transparentcolor = 0;
+    embededSymbol->transparent = MS_TRUE;
+    embededSymbol->transparentcolor = 0;
   }
 
   switch(map->scalebar.position) {
-  case(MS_LL):
-    point.x = MS_NINT(embededSymbol->pixmap_buffer->width/2.0);
-    point.y = map->height - MS_NINT(embededSymbol->pixmap_buffer->height/2.0);
-    break;
-  case(MS_LR):
-    point.x = map->width - MS_NINT(embededSymbol->pixmap_buffer->width/2.0);
-    point.y = map->height - MS_NINT(embededSymbol->pixmap_buffer->height/2.0);
-    break;
-  case(MS_LC):
-    point.x = MS_NINT(map->width/2.0);
-    point.y = map->height - MS_NINT(embededSymbol->pixmap_buffer->height/2.0);
-    break;
-  case(MS_UR):
-    point.x = map->width - MS_NINT(embededSymbol->pixmap_buffer->width/2.0);
-    point.y = MS_NINT(embededSymbol->pixmap_buffer->height/2.0);
-    break;
-  case(MS_UL):
-    point.x = MS_NINT(embededSymbol->pixmap_buffer->width/2.0);
-    point.y = MS_NINT(embededSymbol->pixmap_buffer->height/2.0);
-    break;
-  case(MS_UC):
-    point.x = MS_NINT(map->width/2.0);
-    point.y = MS_NINT(embededSymbol->pixmap_buffer->height/2.0);
-    break;
+    case(MS_LL):
+      point.x = MS_NINT(embededSymbol->pixmap_buffer->width/2.0);
+      point.y = map->height - MS_NINT(embededSymbol->pixmap_buffer->height/2.0);
+      break;
+    case(MS_LR):
+      point.x = map->width - MS_NINT(embededSymbol->pixmap_buffer->width/2.0);
+      point.y = map->height - MS_NINT(embededSymbol->pixmap_buffer->height/2.0);
+      break;
+    case(MS_LC):
+      point.x = MS_NINT(map->width/2.0);
+      point.y = map->height - MS_NINT(embededSymbol->pixmap_buffer->height/2.0);
+      break;
+    case(MS_UR):
+      point.x = map->width - MS_NINT(embededSymbol->pixmap_buffer->width/2.0);
+      point.y = MS_NINT(embededSymbol->pixmap_buffer->height/2.0);
+      break;
+    case(MS_UL):
+      point.x = MS_NINT(embededSymbol->pixmap_buffer->width/2.0);
+      point.y = MS_NINT(embededSymbol->pixmap_buffer->height/2.0);
+      break;
+    case(MS_UC):
+      point.x = MS_NINT(map->width/2.0);
+      point.y = MS_NINT(embededSymbol->pixmap_buffer->height/2.0);
+      break;
   }
 
   l = msGetLayerIndex(map, "__embed__scalebar");
   if(l == -1) {
     if (msGrowMapLayers(map) == NULL)
-        return(-1);
+      return(-1);
     l = map->numlayers;
     map->numlayers++;
     if(initLayer((GET_LAYER(map, l)), map) == -1) return(-1);
     GET_LAYER(map, l)->name = msStrdup("__embed__scalebar");
-    GET_LAYER(map, l)->type = MS_LAYER_ANNOTATION;
+    GET_LAYER(map, l)->type = MS_LAYER_POINT;
 
     if (msGrowLayerClasses( GET_LAYER(map, l) ) == NULL)
-        return(-1);
+      return(-1);
 
     if(initClass(GET_LAYER(map, l)->class[0]) == -1) return(-1);
     GET_LAYER(map, l)->numclasses = 1; /* so we make sure to free it */
-    
+
     /* update the layer order list with the layer's index. */
     map->layerorder[l] = l;
   }
 
   GET_LAYER(map, l)->status = MS_ON;
-
-  /* TODO: Change this when we get rid of MS_MAXSTYLES */
-  if (msMaybeAllocateClassStyle(GET_LAYER(map, l)->class[0], 0)==MS_FAILURE) return MS_FAILURE;
-  GET_LAYER(map, l)->class[0]->styles[0]->symbol = map->symbolset.numsymbols -1 ;
-  GET_LAYER(map, l)->class[0]->styles[0]->color.pen = -1;
-  GET_LAYER(map, l)->class[0]->label.force = MS_TRUE;
-  GET_LAYER(map, l)->class[0]->label.size = MS_MEDIUM; /* must set a size to have a valid label definition */
-  GET_LAYER(map, l)->class[0]->label.priority = MS_MAX_LABEL_PRIORITY;
-
-  if(map->scalebar.postlabelcache) /* add it directly to the image //TODO */
-  {
-      msDrawMarkerSymbol(&map->symbolset, img, &point, GET_LAYER(map, l)->class[0]->styles[0], 1.0);
+  if(map->scalebar.postlabelcache) { /* add it directly to the image */
+    if(msMaybeAllocateClassStyle(GET_LAYER(map, l)->class[0], 0)==MS_FAILURE) return MS_FAILURE;
+    GET_LAYER(map, l)->class[0]->styles[0]->symbol = s;
+    msDrawMarkerSymbol(&map->symbolset, img, &point, GET_LAYER(map, l)->class[0]->styles[0], 1.0);
   } else {
-    msAddLabel(map, l, 0, NULL, &point, NULL, "", 1.0, NULL);
+    if(!GET_LAYER(map, l)->class[0]->labels) {
+      if(msGrowClassLabels(GET_LAYER(map, l)->class[0]) == NULL) return MS_FAILURE;
+      initLabel(GET_LAYER(map, l)->class[0]->labels[0]);
+      GET_LAYER(map, l)->class[0]->numlabels = 1;
+      GET_LAYER(map, l)->class[0]->labels[0]->force = MS_TRUE;
+      GET_LAYER(map, l)->class[0]->labels[0]->size = MS_MEDIUM; /* must set a size to have a valid label definition */
+      GET_LAYER(map, l)->class[0]->labels[0]->priority = MS_MAX_LABEL_PRIORITY;
+      GET_LAYER(map, l)->class[0]->labels[0]->annotext = NULL;
+    }
+    if(GET_LAYER(map, l)->class[0]->labels[0]->numstyles == 0) {
+      if(msGrowLabelStyles(GET_LAYER(map,l)->class[0]->labels[0]) == NULL)
+        return(MS_FAILURE);
+      GET_LAYER(map,l)->class[0]->labels[0]->numstyles = 1;
+      initStyle(GET_LAYER(map,l)->class[0]->labels[0]->styles[0]);
+      GET_LAYER(map,l)->class[0]->labels[0]->styles[0]->_geomtransform.type = MS_GEOMTRANSFORM_LABELPOINT;
+    }
+    GET_LAYER(map,l)->class[0]->labels[0]->styles[0]->symbol = s;
+    msAddLabel(map, GET_LAYER(map, l)->class[0]->labels[0], l, 0, NULL, &point, NULL, -1);
   }
 
+
   /* Mark layer as deleted so that it doesn't interfere with html legends or with saving maps */
   GET_LAYER(map, l)->status = MS_DELETE;
 
@@ -469,31 +474,30 @@ int msEmbedScalebar(mapObj *map, imageObj *img)
 /************************************************************************/
 double GetDeltaExtentsUsingScale(double scale, int units, double centerLat, int width, double resolution)
 {
-    double md = 0.0;
-    double dfDelta = -1.0;
-
-    if (scale <= 0 || width <=0)
-      return -1;
-
-    switch (units) 
-    {
-      case(MS_DD):
-      case(MS_METERS):    
-      case(MS_KILOMETERS):
-      case(MS_MILES):
-      case(MS_NAUTICALMILES):
-      case(MS_INCHES):  
-      case(MS_FEET):
-        /* remember, we use a pixel-center to pixel-center extent, hence the width-1 */
-        md = (width-1)/(resolution*msInchesPerUnit(units,centerLat));
-        dfDelta = md * scale;
-        break;
-          
-      default:
-        break;
-    }
+  double md = 0.0;
+  double dfDelta = -1.0;
+
+  if (scale <= 0 || width <=0)
+    return -1;
+
+  switch (units) {
+    case(MS_DD):
+    case(MS_METERS):
+    case(MS_KILOMETERS):
+    case(MS_MILES):
+    case(MS_NAUTICALMILES):
+    case(MS_INCHES):
+    case(MS_FEET):
+      /* remember, we use a pixel-center to pixel-center extent, hence the width-1 */
+      md = (width-1)/(resolution*msInchesPerUnit(units,centerLat));
+      dfDelta = md * scale;
+      break;
+
+    default:
+      break;
+  }
 
-    return dfDelta;
+  return dfDelta;
 }
 
 /************************************************************************/
@@ -506,33 +510,32 @@ double GetDeltaExtentsUsingScale(double scale, int units, double centerLat, int
 /*      considered to be the Y origin.                                  */
 /*                                                                      */
 /************************************************************************/
-double Pix2Georef(int nPixPos, int nPixMin, int nPixMax, 
-                         double dfGeoMin, double dfGeoMax, int bULisYOrig)
+double Pix2Georef(int nPixPos, int nPixMin, int nPixMax,
+                  double dfGeoMin, double dfGeoMax, int bULisYOrig)
 {
-    double      dfWidthGeo = 0.0;
-    int         nWidthPix = 0;
-    double      dfPixToGeo = 0.0;
-    double      dfPosGeo = 0.0;
-    double      dfDeltaGeo = 0.0;
-    int         nDeltaPix = 0;
-
-    dfWidthGeo = dfGeoMax - dfGeoMin;
-    nWidthPix = nPixMax - nPixMin;
-   
-    if (dfWidthGeo > 0.0 && nWidthPix > 0)
-    {
-        dfPixToGeo = dfWidthGeo / (double)nWidthPix;
-
-        if (!bULisYOrig)
-            nDeltaPix = nPixPos - nPixMin;
-        else
-            nDeltaPix = nPixMax - nPixPos;
-        
-        dfDeltaGeo = nDeltaPix * dfPixToGeo;
-
-        dfPosGeo = dfGeoMin + dfDeltaGeo;
-    }
-    return (dfPosGeo);
+  double      dfWidthGeo = 0.0;
+  int         nWidthPix = 0;
+  double      dfPixToGeo = 0.0;
+  double      dfPosGeo = 0.0;
+  double      dfDeltaGeo = 0.0;
+  int         nDeltaPix = 0;
+
+  dfWidthGeo = dfGeoMax - dfGeoMin;
+  nWidthPix = nPixMax - nPixMin;
+
+  if (dfWidthGeo > 0.0 && nWidthPix > 0) {
+    dfPixToGeo = dfWidthGeo / (double)nWidthPix;
+
+    if (!bULisYOrig)
+      nDeltaPix = nPixPos - nPixMin;
+    else
+      nDeltaPix = nPixMax - nPixPos;
+
+    dfDeltaGeo = nDeltaPix * dfPixToGeo;
+
+    dfPosGeo = dfGeoMin + dfDeltaGeo;
+  }
+  return (dfPosGeo);
 }
 
 /* This function converts a pixel value in geo ref. The return value is in
@@ -540,14 +543,14 @@ double Pix2Georef(int nPixPos, int nPixMin, int nPixMax,
 
 double Pix2LayerGeoref(mapObj *map, layerObj *layer, int value)
 {
-    double cellsize = MS_MAX(MS_CELLSIZE(map->extent.minx, map->extent.maxx, map->width), 
-                             MS_CELLSIZE(map->extent.miny, map->extent.maxy, map->height));
-    
-    double resolutionFactor = map->resolution/map->defresolution;
-    double unitsFactor = 1;
-    
-    if (layer->sizeunits != MS_PIXELS)
-        unitsFactor = msInchesPerUnit(map->units,0)/msInchesPerUnit(layer->sizeunits,0);
-    
-    return value*cellsize*resolutionFactor*unitsFactor;
+  double cellsize = MS_MAX(MS_CELLSIZE(map->extent.minx, map->extent.maxx, map->width),
+                           MS_CELLSIZE(map->extent.miny, map->extent.maxy, map->height));
+
+  double resolutionFactor = map->resolution/map->defresolution;
+  double unitsFactor = 1;
+
+  if (layer->sizeunits != MS_PIXELS)
+    unitsFactor = msInchesPerUnit(map->units,0)/msInchesPerUnit(layer->sizeunits,0);
+
+  return value*cellsize*resolutionFactor*unitsFactor;
 }
diff --git a/mapscript/csharp/MS_CONNECTION_TYPE.cs b/mapscript/csharp/MS_CONNECTION_TYPE.cs
index 5e4d296..75bd289 100644
--- a/mapscript/csharp/MS_CONNECTION_TYPE.cs
+++ b/mapscript/csharp/MS_CONNECTION_TYPE.cs
@@ -22,5 +22,6 @@ public enum MS_CONNECTION_TYPE {
   MS_MYSQL,
   MS_RASTER,
   MS_PLUGIN,
-  MS_UNION
+  MS_UNION,
+  MS_UVRASTER
 }
diff --git a/mapscript/csharp/MS_STYLE_BINDING_ENUM.cs b/mapscript/csharp/MS_STYLE_BINDING_ENUM.cs
index b609995..665304d 100644
--- a/mapscript/csharp/MS_STYLE_BINDING_ENUM.cs
+++ b/mapscript/csharp/MS_STYLE_BINDING_ENUM.cs
@@ -15,5 +15,9 @@ public enum MS_STYLE_BINDING_ENUM {
   MS_STYLE_BINDING_OUTLINECOLOR,
   MS_STYLE_BINDING_SYMBOL,
   MS_STYLE_BINDING_OUTLINEWIDTH,
-  MS_STYLE_BINDING_OPACITY
+  MS_STYLE_BINDING_OPACITY,
+  MS_STYLE_BINDING_OFFSET_X,
+  MS_STYLE_BINDING_OFFSET_Y,
+  MS_STYLE_BINDING_POLAROFFSET_PIXEL,
+  MS_STYLE_BINDING_POLAROFFSET_ANGLE
 }
diff --git a/mapscript/csharp/MS_TOKEN_BINDING_ENUM.cs b/mapscript/csharp/MS_TOKEN_BINDING_ENUM.cs
index 65a8bf1..25bf6f0 100644
--- a/mapscript/csharp/MS_TOKEN_BINDING_ENUM.cs
+++ b/mapscript/csharp/MS_TOKEN_BINDING_ENUM.cs
@@ -8,7 +8,7 @@
 
 
 public enum MS_TOKEN_BINDING_ENUM {
-  MS_TOKEN_BINDING_DOUBLE = 150,
+  MS_TOKEN_BINDING_DOUBLE = 350,
   MS_TOKEN_BINDING_INTEGER,
   MS_TOKEN_BINDING_STRING,
   MS_TOKEN_BINDING_TIME,
diff --git a/mapscript/csharp/MS_TOKEN_COMPARISON_ENUM.cs b/mapscript/csharp/MS_TOKEN_COMPARISON_ENUM.cs
index 450ba2c..d5ef96f 100644
--- a/mapscript/csharp/MS_TOKEN_COMPARISON_ENUM.cs
+++ b/mapscript/csharp/MS_TOKEN_COMPARISON_ENUM.cs
@@ -8,7 +8,7 @@
 
 
 public enum MS_TOKEN_COMPARISON_ENUM {
-  MS_TOKEN_COMPARISON_EQ = 120,
+  MS_TOKEN_COMPARISON_EQ = 320,
   MS_TOKEN_COMPARISON_NE,
   MS_TOKEN_COMPARISON_GT,
   MS_TOKEN_COMPARISON_LT,
diff --git a/mapscript/csharp/MS_TOKEN_FUNCTION_ENUM.cs b/mapscript/csharp/MS_TOKEN_FUNCTION_ENUM.cs
index a97963f..d24a8ac 100644
--- a/mapscript/csharp/MS_TOKEN_FUNCTION_ENUM.cs
+++ b/mapscript/csharp/MS_TOKEN_FUNCTION_ENUM.cs
@@ -8,11 +8,12 @@
 
 
 public enum MS_TOKEN_FUNCTION_ENUM {
-  MS_TOKEN_FUNCTION_LENGTH = 140,
+  MS_TOKEN_FUNCTION_LENGTH = 340,
   MS_TOKEN_FUNCTION_TOSTRING,
   MS_TOKEN_FUNCTION_COMMIFY,
   MS_TOKEN_FUNCTION_AREA,
   MS_TOKEN_FUNCTION_ROUND,
   MS_TOKEN_FUNCTION_FROMTEXT,
-  MS_TOKEN_FUNCTION_BUFFER
+  MS_TOKEN_FUNCTION_BUFFER,
+  MS_TOKEN_FUNCTION_DIFFERENCE
 }
diff --git a/mapscript/csharp/MS_TOKEN_LITERAL_ENUM.cs b/mapscript/csharp/MS_TOKEN_LITERAL_ENUM.cs
index 9fe3e1b..812f0f3 100644
--- a/mapscript/csharp/MS_TOKEN_LITERAL_ENUM.cs
+++ b/mapscript/csharp/MS_TOKEN_LITERAL_ENUM.cs
@@ -8,7 +8,7 @@
 
 
 public enum MS_TOKEN_LITERAL_ENUM {
-  MS_TOKEN_LITERAL_NUMBER = 110,
+  MS_TOKEN_LITERAL_NUMBER = 310,
   MS_TOKEN_LITERAL_STRING,
   MS_TOKEN_LITERAL_TIME,
   MS_TOKEN_LITERAL_SHAPE
diff --git a/mapscript/csharp/MS_TOKEN_LOGICAL_ENUM.cs b/mapscript/csharp/MS_TOKEN_LOGICAL_ENUM.cs
index de0bba1..0473f91 100644
--- a/mapscript/csharp/MS_TOKEN_LOGICAL_ENUM.cs
+++ b/mapscript/csharp/MS_TOKEN_LOGICAL_ENUM.cs
@@ -8,7 +8,7 @@
 
 
 public enum MS_TOKEN_LOGICAL_ENUM {
-  MS_TOKEN_LOGICAL_AND = 100,
+  MS_TOKEN_LOGICAL_AND = 300,
   MS_TOKEN_LOGICAL_OR,
   MS_TOKEN_LOGICAL_NOT
 }
diff --git a/mapscript/csharp/Makefile.vc b/mapscript/csharp/Makefile.vc
index 63cb86a..9fdc747 100755
--- a/mapscript/csharp/Makefile.vc
+++ b/mapscript/csharp/Makefile.vc
@@ -88,7 +88,7 @@ $(CSHARP_DLL)::
 	$(CSC) $(CSFLAGS) /t:library /out:mapscript_csharp.dll *.cs config\AssemblyInfo.cs
 	$(CSC) $(CSFLAGS) /r:mapscript_csharp.dll /out:shpdump.exe examples\shpdump.cs
 	$(CSC) $(CSFLAGS) /r:mapscript_csharp.dll /out:drawmap.exe examples\drawmap.cs
-	$(CSC) $(CSFLAGS) /r:mapscript_csharp.dll /out:inline.exe examples\inline.cs
+#	$(CSC) $(CSFLAGS) /r:mapscript_csharp.dll /out:inline.exe examples\inline.cs
 	$(CSC) $(CSFLAGS) /r:mapscript_csharp.dll /out:shapeinfo.exe examples\shapeinfo.cs
 	$(CSC) $(CSFLAGS) /r:mapscript_csharp.dll /out:drawquery.exe examples\drawquery.cs
 	$(CSC) $(CSFLAGS) /r:mapscript_csharp.dll /r:System.Drawing.dll /out:getbytes.exe examples\getbytes.cs
@@ -101,13 +101,13 @@ test:
 !IFDEF MONO
 	mono shpdump.exe ../../tests/point.shp
 	mono shapeinfo.exe ../../tests/point.shp
-	mono inline.exe aggpng24 inline_test.png
+#	mono inline.exe aggpng24 inline_test.png
 	mono getbytes.exe ../../tests/test.map test_csharp2.png
 	mono RFC24.exe ../../tests/test.map
 !ELSE
 	shpdump ../../tests/point.shp
 	shapeinfo ../../tests/point.shp
-	inline png24 inline_test.png
+#	inline png24 inline_test.png
 	getbytes ../../tests/test.map test_csharp2.png
 	RFC24.exe ../../tests/test.map
 !ENDIF
diff --git a/mapscript/csharp/OWSRequest.cs b/mapscript/csharp/OWSRequest.cs
index fcd3755..1586eff 100644
--- a/mapscript/csharp/OWSRequest.cs
+++ b/mapscript/csharp/OWSRequest.cs
@@ -156,6 +156,11 @@ public class OWSRequest : IDisposable {
     if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
   }
 
+  public void addParameter(string name, string value) {
+    mapscriptPINVOKE.OWSRequest_addParameter(swigCPtr, name, value);
+    if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
+  }
+
   public string getName(int index) {
     string ret = mapscriptPINVOKE.OWSRequest_getName(swigCPtr, index);
     if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
diff --git a/mapscript/csharp/SWIGTYPE_p_double.cs b/mapscript/csharp/SWIGTYPE_p_p_char.cs
similarity index 77%
copy from mapscript/csharp/SWIGTYPE_p_double.cs
copy to mapscript/csharp/SWIGTYPE_p_p_char.cs
index 4e5fe05..8453c7d 100644
--- a/mapscript/csharp/SWIGTYPE_p_double.cs
+++ b/mapscript/csharp/SWIGTYPE_p_p_char.cs
@@ -10,18 +10,18 @@
 using System;
 using System.Runtime.InteropServices;
 
-public class SWIGTYPE_p_double {
+public class SWIGTYPE_p_p_char {
   private HandleRef swigCPtr;
 
-  internal SWIGTYPE_p_double(IntPtr cPtr, bool futureUse, object parent) {
+  internal SWIGTYPE_p_p_char(IntPtr cPtr, bool futureUse, object parent) {
     swigCPtr = new HandleRef(this, cPtr);
   }
 
-  protected SWIGTYPE_p_double() {
+  protected SWIGTYPE_p_p_char() {
     swigCPtr = new HandleRef(null, IntPtr.Zero);
   }
 
-  internal static HandleRef getCPtr(SWIGTYPE_p_double obj) {
+  internal static HandleRef getCPtr(SWIGTYPE_p_p_char obj) {
     return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr;
   }
 }
diff --git a/mapscript/csharp/classObj.cs b/mapscript/csharp/classObj.cs
index 1455804..2e60556 100644
--- a/mapscript/csharp/classObj.cs
+++ b/mapscript/csharp/classObj.cs
@@ -92,10 +92,6 @@ public class classObj : IDisposable {
   }
 
   public int numstyles {
-    set {
-      mapscriptPINVOKE.classObj_numstyles_set(swigCPtr, value);
-      if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
-    } 
     get {
       int ret = mapscriptPINVOKE.classObj_numstyles_get(swigCPtr);
       if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
@@ -103,10 +99,13 @@ public class classObj : IDisposable {
     } 
   }
 
-  public labelObj label {
+  public int numlabels {
+    set {
+      mapscriptPINVOKE.classObj_numlabels_set(swigCPtr, value);
+      if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
+    } 
     get {
-      IntPtr cPtr = mapscriptPINVOKE.classObj_label_get(swigCPtr);
-      labelObj ret = (cPtr == IntPtr.Zero) ? null : new labelObj(cPtr, false, ThisOwn_false());
+      int ret = mapscriptPINVOKE.classObj_numlabels_get(swigCPtr);
       if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
       return ret;
     } 
@@ -267,6 +266,19 @@ public class classObj : IDisposable {
     } 
   }
 
+  public labelLeaderObj leader {
+    set {
+      mapscriptPINVOKE.classObj_leader_set(swigCPtr, labelLeaderObj.getCPtr(value));
+      if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
+    } 
+    get {
+      IntPtr cPtr = mapscriptPINVOKE.classObj_leader_get(swigCPtr);
+      labelLeaderObj ret = (cPtr == IntPtr.Zero) ? null : new labelLeaderObj(cPtr, false, ThisOwn_false());
+      if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
+      return ret;
+    } 
+  }
+
   public classObj(layerObj layer) : this(mapscriptPINVOKE.new_classObj(layerObj.getCPtr(layer)), true, layer) {
   
     if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
@@ -346,6 +358,26 @@ public class classObj : IDisposable {
     return ret;
   }
 
+  public labelObj getLabel(int i) {
+    IntPtr cPtr = mapscriptPINVOKE.classObj_getLabel(swigCPtr, i);
+    labelObj ret = (cPtr == IntPtr.Zero) ? null : new labelObj(cPtr, true, ThisOwn_true());
+    if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
+    return ret;
+  }
+
+  public int addLabel(labelObj label) {
+    int ret = mapscriptPINVOKE.classObj_addLabel(swigCPtr, labelObj.getCPtrAndSetReference(label, ThisOwn_false()));
+    if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
+    return ret;
+  }
+
+  public labelObj removeLabel(int index) {
+    IntPtr cPtr = mapscriptPINVOKE.classObj_removeLabel(swigCPtr, index);
+    labelObj ret = (cPtr == IntPtr.Zero) ? null : new labelObj(cPtr, true, ThisOwn_true());
+    if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
+    return ret;
+  }
+
   public styleObj getStyle(int i) {
     IntPtr cPtr = mapscriptPINVOKE.classObj_getStyle(swigCPtr, i);
     styleObj ret = (cPtr == IntPtr.Zero) ? null : new styleObj(cPtr, true, ThisOwn_false());
diff --git a/mapscript/csharp/colorObj.cs b/mapscript/csharp/colorObj.cs
index d2ca377..f6b04a8 100644
--- a/mapscript/csharp/colorObj.cs
+++ b/mapscript/csharp/colorObj.cs
@@ -79,18 +79,6 @@ public class colorObj : IDisposable {
     return swigCPtr.Handle.GetHashCode();
   }
 
-  public int pen {
-    set {
-      mapscriptPINVOKE.colorObj_pen_set(swigCPtr, value);
-      if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
-    } 
-    get {
-      int ret = mapscriptPINVOKE.colorObj_pen_get(swigCPtr);
-      if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
-      return ret;
-    } 
-  }
-
   public int red {
     set {
       mapscriptPINVOKE.colorObj_red_set(swigCPtr, value);
diff --git a/mapscript/csharp/csmodule.i b/mapscript/csharp/csmodule.i
index 8a19d4a..92a176f 100644
--- a/mapscript/csharp/csmodule.i
+++ b/mapscript/csharp/csmodule.i
@@ -320,7 +320,7 @@ static SWIG_CSharpByteArrayHelperCallback SWIG_csharp_bytearray_callback = NULL;
 
 %typemap(out, null="") gdBuffer
 %{ SWIG_csharp_bytearray_callback($1.data, $1.size);
-	if( $1.owns_data ) gdFree($1.data); %}
+	if( $1.owns_data ) msFree($1.data); %}
 
 // SWIGEXCODE is a macro used by many other csout typemaps
 #ifdef SWIGEXCODE
diff --git a/mapscript/csharp/labelCacheMemberObj.cs b/mapscript/csharp/labelCacheMemberObj.cs
index ee7f858..69694c3 100644
--- a/mapscript/csharp/labelCacheMemberObj.cs
+++ b/mapscript/csharp/labelCacheMemberObj.cs
@@ -79,14 +79,6 @@ public class labelCacheMemberObj : IDisposable {
     return swigCPtr.Handle.GetHashCode();
   }
 
-  public string text {
-    get {
-      string ret = mapscriptPINVOKE.labelCacheMemberObj_text_get(swigCPtr);
-      if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
-      return ret;
-    } 
-  }
-
   public double featuresize {
     get {
       double ret = mapscriptPINVOKE.labelCacheMemberObj_featuresize_get(swigCPtr);
@@ -112,42 +104,34 @@ public class labelCacheMemberObj : IDisposable {
     } 
   }
 
-  public labelObj label {
+  public labelObj labels {
     get {
-      IntPtr cPtr = mapscriptPINVOKE.labelCacheMemberObj_label_get(swigCPtr);
+      IntPtr cPtr = mapscriptPINVOKE.labelCacheMemberObj_labels_get(swigCPtr);
       labelObj ret = (cPtr == IntPtr.Zero) ? null : new labelObj(cPtr, false, ThisOwn_false());
       if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
       return ret;
     } 
   }
 
-  public int layerindex {
-    get {
-      int ret = mapscriptPINVOKE.labelCacheMemberObj_layerindex_get(swigCPtr);
-      if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
-      return ret;
-    } 
-  }
-
-  public int classindex {
+  public int numlabels {
     get {
-      int ret = mapscriptPINVOKE.labelCacheMemberObj_classindex_get(swigCPtr);
+      int ret = mapscriptPINVOKE.labelCacheMemberObj_numlabels_get(swigCPtr);
       if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
       return ret;
     } 
   }
 
-  public int tileindex {
+  public int layerindex {
     get {
-      int ret = mapscriptPINVOKE.labelCacheMemberObj_tileindex_get(swigCPtr);
+      int ret = mapscriptPINVOKE.labelCacheMemberObj_layerindex_get(swigCPtr);
       if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
       return ret;
     } 
   }
 
-  public int shapeindex {
+  public int classindex {
     get {
-      int ret = mapscriptPINVOKE.labelCacheMemberObj_shapeindex_get(swigCPtr);
+      int ret = mapscriptPINVOKE.labelCacheMemberObj_classindex_get(swigCPtr);
       if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
       return ret;
     } 
@@ -195,6 +179,24 @@ public class labelCacheMemberObj : IDisposable {
     } 
   }
 
+  public lineObj leaderline {
+    get {
+      IntPtr cPtr = mapscriptPINVOKE.labelCacheMemberObj_leaderline_get(swigCPtr);
+      lineObj ret = (cPtr == IntPtr.Zero) ? null : new lineObj(cPtr, false, ThisOwn_false());
+      if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
+      return ret;
+    } 
+  }
+
+  public rectObj leaderbbox {
+    get {
+      IntPtr cPtr = mapscriptPINVOKE.labelCacheMemberObj_leaderbbox_get(swigCPtr);
+      rectObj ret = (cPtr == IntPtr.Zero) ? null : new rectObj(cPtr, false, ThisOwn_false());
+      if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
+      return ret;
+    } 
+  }
+
   public labelCacheMemberObj() : this(mapscriptPINVOKE.new_labelCacheMemberObj(), true, null) {
     if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
   }
diff --git a/mapscript/csharp/labelCacheObj.cs b/mapscript/csharp/labelCacheObj.cs
index f8ba58e..a748c0b 100644
--- a/mapscript/csharp/labelCacheObj.cs
+++ b/mapscript/csharp/labelCacheObj.cs
@@ -96,6 +96,14 @@ public class labelCacheObj : IDisposable {
     } 
   }
 
+  public int gutter {
+    get {
+      int ret = mapscriptPINVOKE.labelCacheObj_gutter_get(swigCPtr);
+      if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
+      return ret;
+    } 
+  }
+
   public void freeCache() {
     mapscriptPINVOKE.labelCacheObj_freeCache(swigCPtr);
     if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
diff --git a/mapscript/csharp/resultObj.cs b/mapscript/csharp/labelLeaderObj.cs
similarity index 67%
copy from mapscript/csharp/resultObj.cs
copy to mapscript/csharp/labelLeaderObj.cs
index e1ebac0..034c7b6 100644
--- a/mapscript/csharp/resultObj.cs
+++ b/mapscript/csharp/labelLeaderObj.cs
@@ -10,7 +10,7 @@
 using System;
 using System.Runtime.InteropServices;
 
-public class resultObj : IDisposable {
+public class labelLeaderObj : IDisposable {
   private HandleRef swigCPtr;
   protected bool swigCMemOwn;
   protected object swigParentRef;
@@ -18,16 +18,16 @@ public class resultObj : IDisposable {
   protected static object ThisOwn_true() { return null; }
   protected object ThisOwn_false() { return this; }
 
-  internal resultObj(IntPtr cPtr, bool cMemoryOwn, object parent) {
+  internal labelLeaderObj(IntPtr cPtr, bool cMemoryOwn, object parent) {
     swigCMemOwn = cMemoryOwn;
     swigParentRef = parent;
     swigCPtr = new HandleRef(this, cPtr);
   }
 
-  internal static HandleRef getCPtr(resultObj obj) {
+  internal static HandleRef getCPtr(labelLeaderObj obj) {
     return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr;
   }
-  internal static HandleRef getCPtrAndDisown(resultObj obj, object parent) {
+  internal static HandleRef getCPtrAndDisown(labelLeaderObj obj, object parent) {
     if (obj != null)
     {
       obj.swigCMemOwn = false;
@@ -39,7 +39,7 @@ public class resultObj : IDisposable {
       return new HandleRef(null, IntPtr.Zero);
     }
   }
-  internal static HandleRef getCPtrAndSetReference(resultObj obj, object parent) {
+  internal static HandleRef getCPtrAndSetReference(labelLeaderObj obj, object parent) {
     if (obj != null)
     {
       obj.swigParentRef = parent;
@@ -51,7 +51,7 @@ public class resultObj : IDisposable {
     }
   }
 
-  ~resultObj() {
+  ~labelLeaderObj() {
     Dispose();
   }
 
@@ -59,7 +59,7 @@ public class resultObj : IDisposable {
   lock(this) {
       if(swigCPtr.Handle != IntPtr.Zero && swigCMemOwn) {
         swigCMemOwn = false;
-        mapscriptPINVOKE.delete_resultObj(swigCPtr);
+        mapscriptPINVOKE.delete_labelLeaderObj(swigCPtr);
       }
       swigCPtr = new HandleRef(null, IntPtr.Zero);
       swigParentRef = null;
@@ -72,46 +72,46 @@ public class resultObj : IDisposable {
         return false;
     if (this.GetType() != obj.GetType())
         return false;
-    return swigCPtr.Handle.Equals(resultObj.getCPtr((resultObj)obj).Handle);
+    return swigCPtr.Handle.Equals(labelLeaderObj.getCPtr((labelLeaderObj)obj).Handle);
   }
 
   public override int GetHashCode() {
     return swigCPtr.Handle.GetHashCode();
   }
 
-  public int shapeindex {
-    get {
-      int ret = mapscriptPINVOKE.resultObj_shapeindex_get(swigCPtr);
+  public int maxdistance {
+    set {
+      mapscriptPINVOKE.labelLeaderObj_maxdistance_set(swigCPtr, value);
       if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
-      return ret;
     } 
-  }
-
-  public int tileindex {
     get {
-      int ret = mapscriptPINVOKE.resultObj_tileindex_get(swigCPtr);
+      int ret = mapscriptPINVOKE.labelLeaderObj_maxdistance_get(swigCPtr);
       if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
       return ret;
     } 
   }
 
-  public int resultindex {
+  public int gridstep {
+    set {
+      mapscriptPINVOKE.labelLeaderObj_gridstep_set(swigCPtr, value);
+      if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
+    } 
     get {
-      int ret = mapscriptPINVOKE.resultObj_resultindex_get(swigCPtr);
+      int ret = mapscriptPINVOKE.labelLeaderObj_gridstep_get(swigCPtr);
       if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
       return ret;
     } 
   }
 
-  public int classindex {
+  public int numstyles {
     get {
-      int ret = mapscriptPINVOKE.resultObj_classindex_get(swigCPtr);
+      int ret = mapscriptPINVOKE.labelLeaderObj_numstyles_get(swigCPtr);
       if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
       return ret;
     } 
   }
 
-  public resultObj(int shapeindex) : this(mapscriptPINVOKE.new_resultObj(shapeindex), true, null) {
+  public labelLeaderObj() : this(mapscriptPINVOKE.new_labelLeaderObj(), true, null) {
     if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
   }
 
diff --git a/mapscript/csharp/labelObj.cs b/mapscript/csharp/labelObj.cs
index f39f4f2..5ff727e 100644
--- a/mapscript/csharp/labelObj.cs
+++ b/mapscript/csharp/labelObj.cs
@@ -79,6 +79,14 @@ public class labelObj : IDisposable {
     return swigCPtr.Handle.GetHashCode();
   }
 
+  public int refcount {
+    get {
+      int ret = mapscriptPINVOKE.labelObj_refcount_get(swigCPtr);
+      if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
+      return ret;
+    } 
+  }
+
   public string font {
     set {
       mapscriptPINVOKE.labelObj_font_set(swigCPtr, value);
@@ -490,6 +498,18 @@ public class labelObj : IDisposable {
     } 
   }
 
+  public int status {
+    set {
+      mapscriptPINVOKE.labelObj_status_set(swigCPtr, value);
+      if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
+    } 
+    get {
+      int ret = mapscriptPINVOKE.labelObj_status_get(swigCPtr);
+      if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
+      return ret;
+    } 
+  }
+
   public int numstyles {
     set {
       mapscriptPINVOKE.labelObj_numstyles_set(swigCPtr, value);
@@ -502,6 +522,61 @@ public class labelObj : IDisposable {
     } 
   }
 
+  public string annotext {
+    set {
+      mapscriptPINVOKE.labelObj_annotext_set(swigCPtr, value);
+      if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
+    } 
+    get {
+      string ret = mapscriptPINVOKE.labelObj_annotext_get(swigCPtr);
+      if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
+      return ret;
+    } 
+  }
+
+  public pointObj annopoint {
+    set {
+      mapscriptPINVOKE.labelObj_annopoint_set(swigCPtr, pointObj.getCPtr(value));
+      if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
+    } 
+    get {
+      IntPtr cPtr = mapscriptPINVOKE.labelObj_annopoint_get(swigCPtr);
+      pointObj ret = (cPtr == IntPtr.Zero) ? null : new pointObj(cPtr, false, ThisOwn_false());
+      if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
+      return ret;
+    } 
+  }
+
+  public shapeObj annopoly {
+    set {
+      mapscriptPINVOKE.labelObj_annopoly_set(swigCPtr, shapeObj.getCPtr(value));
+      if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
+    } 
+    get {
+      IntPtr cPtr = mapscriptPINVOKE.labelObj_annopoly_get(swigCPtr);
+      shapeObj ret = (cPtr == IntPtr.Zero) ? null : new shapeObj(cPtr, false, ThisOwn_false());
+      if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
+      return ret;
+    } 
+  }
+
+  public labelLeaderObj leader {
+    set {
+      mapscriptPINVOKE.labelObj_leader_set(swigCPtr, labelLeaderObj.getCPtr(value));
+      if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
+    } 
+    get {
+      IntPtr cPtr = mapscriptPINVOKE.labelObj_leader_get(swigCPtr);
+      labelLeaderObj ret = (cPtr == IntPtr.Zero) ? null : new labelLeaderObj(cPtr, false, ThisOwn_false());
+      if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
+      return ret;
+    } 
+  }
+
+  public labelObj() : this(mapscriptPINVOKE.new_labelObj(), true, null) {
+    if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
+  }
+
   public int updateFromString(string snippet) {
     int ret = mapscriptPINVOKE.labelObj_updateFromString(swigCPtr, snippet);
     if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
@@ -526,6 +601,30 @@ public class labelObj : IDisposable {
     return ret;
   }
 
+  public int setExpression(string expression) {
+    int ret = mapscriptPINVOKE.labelObj_setExpression(swigCPtr, expression);
+    if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
+    return ret;
+  }
+
+  public string getExpressionString() {
+    string ret = mapscriptPINVOKE.labelObj_getExpressionString(swigCPtr);
+    if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
+    return ret;
+  }
+
+  public int setText(string text) {
+    int ret = mapscriptPINVOKE.labelObj_setText(swigCPtr, text);
+    if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
+    return ret;
+  }
+
+  public string getTextString() {
+    string ret = mapscriptPINVOKE.labelObj_getTextString(swigCPtr);
+    if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
+    return ret;
+  }
+
   public styleObj getStyle(int i) {
     IntPtr cPtr = mapscriptPINVOKE.labelObj_getStyle(swigCPtr, i);
     styleObj ret = (cPtr == IntPtr.Zero) ? null : new styleObj(cPtr, true, ThisOwn_false());
@@ -558,8 +657,4 @@ public class labelObj : IDisposable {
     return ret;
   }
 
-  public labelObj() : this(mapscriptPINVOKE.new_labelObj(), true, null) {
-    if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
-  }
-
 }
diff --git a/mapscript/csharp/labelStyleObj.cs b/mapscript/csharp/labelStyleObj.cs
index 31939b4..366c62a 100644
--- a/mapscript/csharp/labelStyleObj.cs
+++ b/mapscript/csharp/labelStyleObj.cs
@@ -79,13 +79,26 @@ public class labelStyleObj : IDisposable {
     return swigCPtr.Handle.GetHashCode();
   }
 
-  public string font {
+  public SWIGTYPE_p_p_char fonts {
     set {
-      mapscriptPINVOKE.labelStyleObj_font_set(swigCPtr, value);
+      mapscriptPINVOKE.labelStyleObj_fonts_set(swigCPtr, SWIGTYPE_p_p_char.getCPtr(value));
       if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
     } 
     get {
-      string ret = mapscriptPINVOKE.labelStyleObj_font_get(swigCPtr);
+      IntPtr cPtr = mapscriptPINVOKE.labelStyleObj_fonts_get(swigCPtr);
+      SWIGTYPE_p_p_char ret = (cPtr == IntPtr.Zero) ? null : new SWIGTYPE_p_p_char(cPtr, false, ThisOwn_false());
+      if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
+      return ret;
+    } 
+  }
+
+  public int numfonts {
+    set {
+      mapscriptPINVOKE.labelStyleObj_numfonts_set(swigCPtr, value);
+      if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
+    } 
+    get {
+      int ret = mapscriptPINVOKE.labelStyleObj_numfonts_get(swigCPtr);
       if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
       return ret;
     } 
@@ -153,6 +166,18 @@ public class labelStyleObj : IDisposable {
     } 
   }
 
+  public int antialias {
+    set {
+      mapscriptPINVOKE.labelStyleObj_antialias_set(swigCPtr, value);
+      if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
+    } 
+    get {
+      int ret = mapscriptPINVOKE.labelStyleObj_antialias_get(swigCPtr);
+      if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
+      return ret;
+    } 
+  }
+
   public labelStyleObj() : this(mapscriptPINVOKE.new_labelStyleObj(), true, null) {
     if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
   }
diff --git a/mapscript/csharp/layerObj.cs b/mapscript/csharp/layerObj.cs
index 190f4b5..e08d7ff 100644
--- a/mapscript/csharp/layerObj.cs
+++ b/mapscript/csharp/layerObj.cs
@@ -706,6 +706,18 @@ public class layerObj : IDisposable {
     } 
   }
 
+  public string mask {
+    set {
+      mapscriptPINVOKE.layerObj_mask_set(swigCPtr, value);
+      if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
+    } 
+    get {
+      string ret = mapscriptPINVOKE.layerObj_mask_get(swigCPtr);
+      if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
+      return ret;
+    } 
+  }
+
   public layerObj(mapObj map) : this(mapscriptPINVOKE.new_layerObj(mapObj.getCPtr(map)), true, map) {
   
     if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
@@ -801,6 +813,12 @@ public class layerObj : IDisposable {
     return ret;
   }
 
+  public int setItems(string[] items, int numitems) {
+    int ret = mapscriptPINVOKE.layerObj_setItems(swigCPtr, new mapscriptPINVOKE.StringArrayMarshal(items)._ar, numitems);
+    if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
+    return ret;
+  }
+
   public int draw(mapObj map, imageObj image) {
     int ret = mapscriptPINVOKE.layerObj_draw(swigCPtr, mapObj.getCPtr(map), imageObj.getCPtr(image));
     if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
diff --git a/mapscript/csharp/mapscript.cs b/mapscript/csharp/mapscript.cs
index 2c4731f..e16d551 100644
--- a/mapscript/csharp/mapscript.cs
+++ b/mapscript/csharp/mapscript.cs
@@ -41,8 +41,8 @@ public class mapscript {
     return ret;
   }
 
-  public static void msCleanup() {
-    mapscriptPINVOKE.msCleanup();
+  public static void msCleanup(int signal) {
+    mapscriptPINVOKE.msCleanup(signal);
     if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
   }
 
@@ -132,7 +132,6 @@ public class mapscript {
   public static readonly int MS_VERSION_MINOR = mapscriptPINVOKE.MS_VERSION_MINOR_get();
   public static readonly int MS_VERSION_REV = mapscriptPINVOKE.MS_VERSION_REV_get();
   public static readonly int MS_VERSION_NUM = mapscriptPINVOKE.MS_VERSION_NUM_get();
-  public static readonly string __FUNCTION__ = mapscriptPINVOKE.__FUNCTION___get();
   public static readonly int MS_TRUE = mapscriptPINVOKE.MS_TRUE_get();
   public static readonly int MS_FALSE = mapscriptPINVOKE.MS_FALSE_get();
   public static readonly int MS_UNKNOWN = mapscriptPINVOKE.MS_UNKNOWN_get();
@@ -147,8 +146,11 @@ public class mapscript {
   public static readonly int MS_LAYER_ALLOCSIZE = mapscriptPINVOKE.MS_LAYER_ALLOCSIZE_get();
   public static readonly int MS_CLASS_ALLOCSIZE = mapscriptPINVOKE.MS_CLASS_ALLOCSIZE_get();
   public static readonly int MS_STYLE_ALLOCSIZE = mapscriptPINVOKE.MS_STYLE_ALLOCSIZE_get();
+  public static readonly int MS_LABEL_ALLOCSIZE = mapscriptPINVOKE.MS_LABEL_ALLOCSIZE_get();
   public static readonly int MS_MAX_LABEL_PRIORITY = mapscriptPINVOKE.MS_MAX_LABEL_PRIORITY_get();
+  public static readonly int MS_MAX_LABEL_FONTS = mapscriptPINVOKE.MS_MAX_LABEL_FONTS_get();
   public static readonly int MS_DEFAULT_LABEL_PRIORITY = mapscriptPINVOKE.MS_DEFAULT_LABEL_PRIORITY_get();
+  public static readonly int MS_LABEL_FORCE_GROUP = mapscriptPINVOKE.MS_LABEL_FORCE_GROUP_get();
   public static readonly int MS_RENDER_WITH_SWF = mapscriptPINVOKE.MS_RENDER_WITH_SWF_get();
   public static readonly int MS_RENDER_WITH_RAWDATA = mapscriptPINVOKE.MS_RENDER_WITH_RAWDATA_get();
   public static readonly int MS_RENDER_WITH_IMAGEMAP = mapscriptPINVOKE.MS_RENDER_WITH_IMAGEMAP_get();
@@ -182,6 +184,9 @@ public class mapscript {
   public static readonly int MS_SHP_ARCM = mapscriptPINVOKE.MS_SHP_ARCM_get();
   public static readonly int MS_SHP_POLYGONM = mapscriptPINVOKE.MS_SHP_POLYGONM_get();
   public static readonly int MS_SHP_MULTIPOINTM = mapscriptPINVOKE.MS_SHP_MULTIPOINTM_get();
+  public static readonly int wkp_none = mapscriptPINVOKE.wkp_none_get();
+  public static readonly int wkp_lonlat = mapscriptPINVOKE.wkp_lonlat_get();
+  public static readonly int wkp_gmerc = mapscriptPINVOKE.wkp_gmerc_get();
   public static readonly int MS_SYMBOL_ALLOCSIZE = mapscriptPINVOKE.MS_SYMBOL_ALLOCSIZE_get();
   public static readonly int MS_MAXVECTORPOINTS = mapscriptPINVOKE.MS_MAXVECTORPOINTS_get();
   public static readonly int MS_MAXPATTERNLENGTH = mapscriptPINVOKE.MS_MAXPATTERNLENGTH_get();
diff --git a/mapscript/csharp/mapscriptPINVOKE.cs b/mapscript/csharp/mapscriptPINVOKE.cs
index 815d2e1..d29a1a0 100644
--- a/mapscript/csharp/mapscriptPINVOKE.cs
+++ b/mapscript/csharp/mapscriptPINVOKE.cs
@@ -284,9 +284,6 @@ class mapscriptPINVOKE {
   [DllImport("mapscript", EntryPoint="CSharp_MS_VERSION_NUM_get")]
   public static extern int MS_VERSION_NUM_get();
 
-  [DllImport("mapscript", EntryPoint="CSharp___FUNCTION___get")]
-  public static extern string __FUNCTION___get();
-
   [DllImport("mapscript", EntryPoint="CSharp_MS_TRUE_get")]
   public static extern int MS_TRUE_get();
 
@@ -329,12 +326,21 @@ class mapscriptPINVOKE {
   [DllImport("mapscript", EntryPoint="CSharp_MS_STYLE_ALLOCSIZE_get")]
   public static extern int MS_STYLE_ALLOCSIZE_get();
 
+  [DllImport("mapscript", EntryPoint="CSharp_MS_LABEL_ALLOCSIZE_get")]
+  public static extern int MS_LABEL_ALLOCSIZE_get();
+
   [DllImport("mapscript", EntryPoint="CSharp_MS_MAX_LABEL_PRIORITY_get")]
   public static extern int MS_MAX_LABEL_PRIORITY_get();
 
+  [DllImport("mapscript", EntryPoint="CSharp_MS_MAX_LABEL_FONTS_get")]
+  public static extern int MS_MAX_LABEL_FONTS_get();
+
   [DllImport("mapscript", EntryPoint="CSharp_MS_DEFAULT_LABEL_PRIORITY_get")]
   public static extern int MS_DEFAULT_LABEL_PRIORITY_get();
 
+  [DllImport("mapscript", EntryPoint="CSharp_MS_LABEL_FORCE_GROUP_get")]
+  public static extern int MS_LABEL_FORCE_GROUP_get();
+
   [DllImport("mapscript", EntryPoint="CSharp_MS_RENDER_WITH_SWF_get")]
   public static extern int MS_RENDER_WITH_SWF_get();
 
@@ -821,6 +827,12 @@ class mapscriptPINVOKE {
   [DllImport("mapscript", EntryPoint="CSharp_styleObj_gap_get")]
   public static extern double styleObj_gap_get(HandleRef jarg1);
 
+  [DllImport("mapscript", EntryPoint="CSharp_styleObj_initialgap_set")]
+  public static extern void styleObj_initialgap_set(HandleRef jarg1, double jarg2);
+
+  [DllImport("mapscript", EntryPoint="CSharp_styleObj_initialgap_get")]
+  public static extern double styleObj_initialgap_get(HandleRef jarg1);
+
   [DllImport("mapscript", EntryPoint="CSharp_styleObj_position_set")]
   public static extern void styleObj_position_set(HandleRef jarg1, int jarg2);
 
@@ -881,6 +893,18 @@ class mapscriptPINVOKE {
   [DllImport("mapscript", EntryPoint="CSharp_styleObj_offsety_get")]
   public static extern double styleObj_offsety_get(HandleRef jarg1);
 
+  [DllImport("mapscript", EntryPoint="CSharp_styleObj_polaroffsetpixel_set")]
+  public static extern void styleObj_polaroffsetpixel_set(HandleRef jarg1, double jarg2);
+
+  [DllImport("mapscript", EntryPoint="CSharp_styleObj_polaroffsetpixel_get")]
+  public static extern double styleObj_polaroffsetpixel_get(HandleRef jarg1);
+
+  [DllImport("mapscript", EntryPoint="CSharp_styleObj_polaroffsetangle_set")]
+  public static extern void styleObj_polaroffsetangle_set(HandleRef jarg1, double jarg2);
+
+  [DllImport("mapscript", EntryPoint="CSharp_styleObj_polaroffsetangle_get")]
+  public static extern double styleObj_polaroffsetangle_get(HandleRef jarg1);
+
   [DllImport("mapscript", EntryPoint="CSharp_styleObj_angle_set")]
   public static extern void styleObj_angle_set(HandleRef jarg1, double jarg2);
 
@@ -935,6 +959,30 @@ class mapscriptPINVOKE {
   [DllImport("mapscript", EntryPoint="CSharp_styleObj_setGeomTransform")]
   public static extern void styleObj_setGeomTransform(HandleRef jarg1, string jarg2);
 
+  [DllImport("mapscript", EntryPoint="CSharp_labelLeaderObj_maxdistance_set")]
+  public static extern void labelLeaderObj_maxdistance_set(HandleRef jarg1, int jarg2);
+
+  [DllImport("mapscript", EntryPoint="CSharp_labelLeaderObj_maxdistance_get")]
+  public static extern int labelLeaderObj_maxdistance_get(HandleRef jarg1);
+
+  [DllImport("mapscript", EntryPoint="CSharp_labelLeaderObj_gridstep_set")]
+  public static extern void labelLeaderObj_gridstep_set(HandleRef jarg1, int jarg2);
+
+  [DllImport("mapscript", EntryPoint="CSharp_labelLeaderObj_gridstep_get")]
+  public static extern int labelLeaderObj_gridstep_get(HandleRef jarg1);
+
+  [DllImport("mapscript", EntryPoint="CSharp_labelLeaderObj_numstyles_get")]
+  public static extern int labelLeaderObj_numstyles_get(HandleRef jarg1);
+
+  [DllImport("mapscript", EntryPoint="CSharp_new_labelLeaderObj")]
+  public static extern IntPtr new_labelLeaderObj();
+
+  [DllImport("mapscript", EntryPoint="CSharp_delete_labelLeaderObj")]
+  public static extern void delete_labelLeaderObj(HandleRef jarg1);
+
+  [DllImport("mapscript", EntryPoint="CSharp_labelObj_refcount_get")]
+  public static extern int labelObj_refcount_get(HandleRef jarg1);
+
   [DllImport("mapscript", EntryPoint="CSharp_labelObj_font_set")]
   public static extern void labelObj_font_set(HandleRef jarg1, string jarg2);
 
@@ -1139,12 +1187,48 @@ class mapscriptPINVOKE {
   [DllImport("mapscript", EntryPoint="CSharp_labelObj_priority_get")]
   public static extern int labelObj_priority_get(HandleRef jarg1);
 
+  [DllImport("mapscript", EntryPoint="CSharp_labelObj_status_set")]
+  public static extern void labelObj_status_set(HandleRef jarg1, int jarg2);
+
+  [DllImport("mapscript", EntryPoint="CSharp_labelObj_status_get")]
+  public static extern int labelObj_status_get(HandleRef jarg1);
+
   [DllImport("mapscript", EntryPoint="CSharp_labelObj_numstyles_set")]
   public static extern void labelObj_numstyles_set(HandleRef jarg1, int jarg2);
 
   [DllImport("mapscript", EntryPoint="CSharp_labelObj_numstyles_get")]
   public static extern int labelObj_numstyles_get(HandleRef jarg1);
 
+  [DllImport("mapscript", EntryPoint="CSharp_labelObj_annotext_set")]
+  public static extern void labelObj_annotext_set(HandleRef jarg1, string jarg2);
+
+  [DllImport("mapscript", EntryPoint="CSharp_labelObj_annotext_get")]
+  public static extern string labelObj_annotext_get(HandleRef jarg1);
+
+  [DllImport("mapscript", EntryPoint="CSharp_labelObj_annopoint_set")]
+  public static extern void labelObj_annopoint_set(HandleRef jarg1, HandleRef jarg2);
+
+  [DllImport("mapscript", EntryPoint="CSharp_labelObj_annopoint_get")]
+  public static extern IntPtr labelObj_annopoint_get(HandleRef jarg1);
+
+  [DllImport("mapscript", EntryPoint="CSharp_labelObj_annopoly_set")]
+  public static extern void labelObj_annopoly_set(HandleRef jarg1, HandleRef jarg2);
+
+  [DllImport("mapscript", EntryPoint="CSharp_labelObj_annopoly_get")]
+  public static extern IntPtr labelObj_annopoly_get(HandleRef jarg1);
+
+  [DllImport("mapscript", EntryPoint="CSharp_labelObj_leader_set")]
+  public static extern void labelObj_leader_set(HandleRef jarg1, HandleRef jarg2);
+
+  [DllImport("mapscript", EntryPoint="CSharp_labelObj_leader_get")]
+  public static extern IntPtr labelObj_leader_get(HandleRef jarg1);
+
+  [DllImport("mapscript", EntryPoint="CSharp_new_labelObj")]
+  public static extern IntPtr new_labelObj();
+
+  [DllImport("mapscript", EntryPoint="CSharp_delete_labelObj")]
+  public static extern void delete_labelObj(HandleRef jarg1);
+
   [DllImport("mapscript", EntryPoint="CSharp_labelObj_updateFromString")]
   public static extern int labelObj_updateFromString(HandleRef jarg1, string jarg2);
 
@@ -1157,6 +1241,18 @@ class mapscriptPINVOKE {
   [DllImport("mapscript", EntryPoint="CSharp_labelObj_setBinding")]
   public static extern int labelObj_setBinding(HandleRef jarg1, int jarg2, string jarg3);
 
+  [DllImport("mapscript", EntryPoint="CSharp_labelObj_setExpression")]
+  public static extern int labelObj_setExpression(HandleRef jarg1, string jarg2);
+
+  [DllImport("mapscript", EntryPoint="CSharp_labelObj_getExpressionString")]
+  public static extern string labelObj_getExpressionString(HandleRef jarg1);
+
+  [DllImport("mapscript", EntryPoint="CSharp_labelObj_setText")]
+  public static extern int labelObj_setText(HandleRef jarg1, string jarg2);
+
+  [DllImport("mapscript", EntryPoint="CSharp_labelObj_getTextString")]
+  public static extern string labelObj_getTextString(HandleRef jarg1);
+
   [DllImport("mapscript", EntryPoint="CSharp_labelObj_getStyle")]
   public static extern IntPtr labelObj_getStyle(HandleRef jarg1, int jarg2);
 
@@ -1172,26 +1268,20 @@ class mapscriptPINVOKE {
   [DllImport("mapscript", EntryPoint="CSharp_labelObj_moveStyleDown")]
   public static extern int labelObj_moveStyleDown(HandleRef jarg1, int jarg2);
 
-  [DllImport("mapscript", EntryPoint="CSharp_new_labelObj")]
-  public static extern IntPtr new_labelObj();
-
-  [DllImport("mapscript", EntryPoint="CSharp_delete_labelObj")]
-  public static extern void delete_labelObj(HandleRef jarg1);
-
   [DllImport("mapscript", EntryPoint="CSharp_classObj_status_set")]
   public static extern void classObj_status_set(HandleRef jarg1, int jarg2);
 
   [DllImport("mapscript", EntryPoint="CSharp_classObj_status_get")]
   public static extern int classObj_status_get(HandleRef jarg1);
 
-  [DllImport("mapscript", EntryPoint="CSharp_classObj_numstyles_set")]
-  public static extern void classObj_numstyles_set(HandleRef jarg1, int jarg2);
-
   [DllImport("mapscript", EntryPoint="CSharp_classObj_numstyles_get")]
   public static extern int classObj_numstyles_get(HandleRef jarg1);
 
-  [DllImport("mapscript", EntryPoint="CSharp_classObj_label_get")]
-  public static extern IntPtr classObj_label_get(HandleRef jarg1);
+  [DllImport("mapscript", EntryPoint="CSharp_classObj_numlabels_set")]
+  public static extern void classObj_numlabels_set(HandleRef jarg1, int jarg2);
+
+  [DllImport("mapscript", EntryPoint="CSharp_classObj_numlabels_get")]
+  public static extern int classObj_numlabels_get(HandleRef jarg1);
 
   [DllImport("mapscript", EntryPoint="CSharp_classObj_name_set")]
   public static extern void classObj_name_set(HandleRef jarg1, string jarg2);
@@ -1265,6 +1355,12 @@ class mapscriptPINVOKE {
   [DllImport("mapscript", EntryPoint="CSharp_classObj_group_get")]
   public static extern string classObj_group_get(HandleRef jarg1);
 
+  [DllImport("mapscript", EntryPoint="CSharp_classObj_leader_set")]
+  public static extern void classObj_leader_set(HandleRef jarg1, HandleRef jarg2);
+
+  [DllImport("mapscript", EntryPoint="CSharp_classObj_leader_get")]
+  public static extern IntPtr classObj_leader_get(HandleRef jarg1);
+
   [DllImport("mapscript", EntryPoint="CSharp_new_classObj")]
   public static extern IntPtr new_classObj(HandleRef jarg1);
 
@@ -1307,6 +1403,15 @@ class mapscriptPINVOKE {
   [DllImport("mapscript", EntryPoint="CSharp_classObj_createLegendIcon")]
   public static extern IntPtr classObj_createLegendIcon(HandleRef jarg1, HandleRef jarg2, HandleRef jarg3, int jarg4, int jarg5);
 
+  [DllImport("mapscript", EntryPoint="CSharp_classObj_getLabel")]
+  public static extern IntPtr classObj_getLabel(HandleRef jarg1, int jarg2);
+
+  [DllImport("mapscript", EntryPoint="CSharp_classObj_addLabel")]
+  public static extern int classObj_addLabel(HandleRef jarg1, HandleRef jarg2);
+
+  [DllImport("mapscript", EntryPoint="CSharp_classObj_removeLabel")]
+  public static extern IntPtr classObj_removeLabel(HandleRef jarg1, int jarg2);
+
   [DllImport("mapscript", EntryPoint="CSharp_classObj_getStyle")]
   public static extern IntPtr classObj_getStyle(HandleRef jarg1, int jarg2);
 
@@ -1322,9 +1427,6 @@ class mapscriptPINVOKE {
   [DllImport("mapscript", EntryPoint="CSharp_classObj_moveStyleDown")]
   public static extern int classObj_moveStyleDown(HandleRef jarg1, int jarg2);
 
-  [DllImport("mapscript", EntryPoint="CSharp_labelCacheMemberObj_text_get")]
-  public static extern string labelCacheMemberObj_text_get(HandleRef jarg1);
-
   [DllImport("mapscript", EntryPoint="CSharp_labelCacheMemberObj_featuresize_get")]
   public static extern double labelCacheMemberObj_featuresize_get(HandleRef jarg1);
 
@@ -1334,8 +1436,11 @@ class mapscriptPINVOKE {
   [DllImport("mapscript", EntryPoint="CSharp_labelCacheMemberObj_numstyles_get")]
   public static extern int labelCacheMemberObj_numstyles_get(HandleRef jarg1);
 
-  [DllImport("mapscript", EntryPoint="CSharp_labelCacheMemberObj_label_get")]
-  public static extern IntPtr labelCacheMemberObj_label_get(HandleRef jarg1);
+  [DllImport("mapscript", EntryPoint="CSharp_labelCacheMemberObj_labels_get")]
+  public static extern IntPtr labelCacheMemberObj_labels_get(HandleRef jarg1);
+
+  [DllImport("mapscript", EntryPoint="CSharp_labelCacheMemberObj_numlabels_get")]
+  public static extern int labelCacheMemberObj_numlabels_get(HandleRef jarg1);
 
   [DllImport("mapscript", EntryPoint="CSharp_labelCacheMemberObj_layerindex_get")]
   public static extern int labelCacheMemberObj_layerindex_get(HandleRef jarg1);
@@ -1343,12 +1448,6 @@ class mapscriptPINVOKE {
   [DllImport("mapscript", EntryPoint="CSharp_labelCacheMemberObj_classindex_get")]
   public static extern int labelCacheMemberObj_classindex_get(HandleRef jarg1);
 
-  [DllImport("mapscript", EntryPoint="CSharp_labelCacheMemberObj_tileindex_get")]
-  public static extern int labelCacheMemberObj_tileindex_get(HandleRef jarg1);
-
-  [DllImport("mapscript", EntryPoint="CSharp_labelCacheMemberObj_shapeindex_get")]
-  public static extern int labelCacheMemberObj_shapeindex_get(HandleRef jarg1);
-
   [DllImport("mapscript", EntryPoint="CSharp_labelCacheMemberObj_shapetype_get")]
   public static extern int labelCacheMemberObj_shapetype_get(HandleRef jarg1);
 
@@ -1364,6 +1463,12 @@ class mapscriptPINVOKE {
   [DllImport("mapscript", EntryPoint="CSharp_labelCacheMemberObj_markerid_get")]
   public static extern int labelCacheMemberObj_markerid_get(HandleRef jarg1);
 
+  [DllImport("mapscript", EntryPoint="CSharp_labelCacheMemberObj_leaderline_get")]
+  public static extern IntPtr labelCacheMemberObj_leaderline_get(HandleRef jarg1);
+
+  [DllImport("mapscript", EntryPoint="CSharp_labelCacheMemberObj_leaderbbox_get")]
+  public static extern IntPtr labelCacheMemberObj_leaderbbox_get(HandleRef jarg1);
+
   [DllImport("mapscript", EntryPoint="CSharp_new_labelCacheMemberObj")]
   public static extern IntPtr new_labelCacheMemberObj();
 
@@ -1412,6 +1517,9 @@ class mapscriptPINVOKE {
   [DllImport("mapscript", EntryPoint="CSharp_labelCacheObj_numlabels_get")]
   public static extern int labelCacheObj_numlabels_get(HandleRef jarg1);
 
+  [DllImport("mapscript", EntryPoint="CSharp_labelCacheObj_gutter_get")]
+  public static extern int labelCacheObj_gutter_get(HandleRef jarg1);
+
   [DllImport("mapscript", EntryPoint="CSharp_labelCacheObj_freeCache")]
   public static extern void labelCacheObj_freeCache(HandleRef jarg1);
 
@@ -1766,6 +1874,42 @@ class mapscriptPINVOKE {
   [DllImport("mapscript", EntryPoint="CSharp_delete_legendObj")]
   public static extern void delete_legendObj(HandleRef jarg1);
 
+  [DllImport("mapscript", EntryPoint="CSharp_imageObj_getBytes")]
+  public static extern void imageObj_getBytes(HandleRef jarg1, SWIGByteArrayDelegate jarg2);
+
+  [DllImport("mapscript", EntryPoint="CSharp_imageObj_width_get")]
+  public static extern int imageObj_width_get(HandleRef jarg1);
+
+  [DllImport("mapscript", EntryPoint="CSharp_imageObj_height_get")]
+  public static extern int imageObj_height_get(HandleRef jarg1);
+
+  [DllImport("mapscript", EntryPoint="CSharp_imageObj_resolution_get")]
+  public static extern double imageObj_resolution_get(HandleRef jarg1);
+
+  [DllImport("mapscript", EntryPoint="CSharp_imageObj_resolutionfactor_get")]
+  public static extern double imageObj_resolutionfactor_get(HandleRef jarg1);
+
+  [DllImport("mapscript", EntryPoint="CSharp_imageObj_imagepath_get")]
+  public static extern string imageObj_imagepath_get(HandleRef jarg1);
+
+  [DllImport("mapscript", EntryPoint="CSharp_imageObj_imageurl_get")]
+  public static extern string imageObj_imageurl_get(HandleRef jarg1);
+
+  [DllImport("mapscript", EntryPoint="CSharp_imageObj_format_get")]
+  public static extern IntPtr imageObj_format_get(HandleRef jarg1);
+
+  [DllImport("mapscript", EntryPoint="CSharp_new_imageObj")]
+  public static extern IntPtr new_imageObj(int jarg1, int jarg2, HandleRef jarg3, string jarg4, double jarg5, double jarg6);
+
+  [DllImport("mapscript", EntryPoint="CSharp_delete_imageObj")]
+  public static extern void delete_imageObj(HandleRef jarg1);
+
+  [DllImport("mapscript", EntryPoint="CSharp_imageObj_save")]
+  public static extern void imageObj_save(HandleRef jarg1, string jarg2, HandleRef jarg3);
+
+  [DllImport("mapscript", EntryPoint="CSharp_imageObj_getSize")]
+  public static extern int imageObj_getSize(HandleRef jarg1);
+
   [DllImport("mapscript", EntryPoint="CSharp_layerObj_classitem_set")]
   public static extern void layerObj_classitem_set(HandleRef jarg1, string jarg2);
 
@@ -2063,6 +2207,12 @@ class mapscriptPINVOKE {
   [DllImport("mapscript", EntryPoint="CSharp_layerObj_classgroup_get")]
   public static extern string layerObj_classgroup_get(HandleRef jarg1);
 
+  [DllImport("mapscript", EntryPoint="CSharp_layerObj_mask_set")]
+  public static extern void layerObj_mask_set(HandleRef jarg1, string jarg2);
+
+  [DllImport("mapscript", EntryPoint="CSharp_layerObj_mask_get")]
+  public static extern string layerObj_mask_get(HandleRef jarg1);
+
   [DllImport("mapscript", EntryPoint="CSharp_new_layerObj")]
   public static extern IntPtr new_layerObj(HandleRef jarg1);
 
@@ -2111,6 +2261,9 @@ class mapscriptPINVOKE {
   [DllImport("mapscript", EntryPoint="CSharp_layerObj_getItem")]
   public static extern string layerObj_getItem(HandleRef jarg1, int jarg2);
 
+  [DllImport("mapscript", EntryPoint="CSharp_layerObj_setItems")]
+  public static extern int layerObj_setItems(HandleRef jarg1, IntPtr[] jarg2, int jarg3);
+
   [DllImport("mapscript", EntryPoint="CSharp_layerObj_draw")]
   public static extern int layerObj_draw(HandleRef jarg1, HandleRef jarg2, HandleRef jarg3);
 
@@ -2624,42 +2777,6 @@ class mapscriptPINVOKE {
   [DllImport("mapscript", EntryPoint="CSharp_mapObj_zoomScale")]
   public static extern int mapObj_zoomScale(HandleRef jarg1, double jarg2, HandleRef jarg3, int jarg4, int jarg5, HandleRef jarg6, HandleRef jarg7);
 
-  [DllImport("mapscript", EntryPoint="CSharp_imageObj_getBytes")]
-  public static extern void imageObj_getBytes(HandleRef jarg1, SWIGByteArrayDelegate jarg2);
-
-  [DllImport("mapscript", EntryPoint="CSharp_imageObj_width_get")]
-  public static extern int imageObj_width_get(HandleRef jarg1);
-
-  [DllImport("mapscript", EntryPoint="CSharp_imageObj_height_get")]
-  public static extern int imageObj_height_get(HandleRef jarg1);
-
-  [DllImport("mapscript", EntryPoint="CSharp_imageObj_resolution_get")]
-  public static extern double imageObj_resolution_get(HandleRef jarg1);
-
-  [DllImport("mapscript", EntryPoint="CSharp_imageObj_resolutionfactor_get")]
-  public static extern double imageObj_resolutionfactor_get(HandleRef jarg1);
-
-  [DllImport("mapscript", EntryPoint="CSharp_imageObj_imagepath_get")]
-  public static extern string imageObj_imagepath_get(HandleRef jarg1);
-
-  [DllImport("mapscript", EntryPoint="CSharp_imageObj_imageurl_get")]
-  public static extern string imageObj_imageurl_get(HandleRef jarg1);
-
-  [DllImport("mapscript", EntryPoint="CSharp_imageObj_format_get")]
-  public static extern IntPtr imageObj_format_get(HandleRef jarg1);
-
-  [DllImport("mapscript", EntryPoint="CSharp_new_imageObj")]
-  public static extern IntPtr new_imageObj(int jarg1, int jarg2, HandleRef jarg3, string jarg4, double jarg5, double jarg6);
-
-  [DllImport("mapscript", EntryPoint="CSharp_delete_imageObj")]
-  public static extern void delete_imageObj(HandleRef jarg1);
-
-  [DllImport("mapscript", EntryPoint="CSharp_imageObj_save")]
-  public static extern void imageObj_save(HandleRef jarg1, string jarg2, HandleRef jarg3);
-
-  [DllImport("mapscript", EntryPoint="CSharp_imageObj_getSize")]
-  public static extern int imageObj_getSize(HandleRef jarg1);
-
   [DllImport("mapscript", EntryPoint="CSharp_msSaveImage")]
   public static extern int msSaveImage(HandleRef jarg1, HandleRef jarg2, string jarg3);
 
@@ -2670,7 +2787,7 @@ class mapscriptPINVOKE {
   public static extern int msSetup();
 
   [DllImport("mapscript", EntryPoint="CSharp_msCleanup")]
-  public static extern void msCleanup();
+  public static extern void msCleanup(int jarg1);
 
   [DllImport("mapscript", EntryPoint="CSharp_msLoadMapFromString")]
   public static extern IntPtr msLoadMapFromString(string jarg1, string jarg2);
@@ -2693,6 +2810,12 @@ class mapscriptPINVOKE {
   [DllImport("mapscript", EntryPoint="CSharp_strokeStyleObj_pattern_get")]
   public static extern IntPtr strokeStyleObj_pattern_get(HandleRef jarg1);
 
+  [DllImport("mapscript", EntryPoint="CSharp_strokeStyleObj_patternoffset_set")]
+  public static extern void strokeStyleObj_patternoffset_set(HandleRef jarg1, double jarg2);
+
+  [DllImport("mapscript", EntryPoint="CSharp_strokeStyleObj_patternoffset_get")]
+  public static extern double strokeStyleObj_patternoffset_get(HandleRef jarg1);
+
   [DllImport("mapscript", EntryPoint="CSharp_strokeStyleObj_color_set")]
   public static extern void strokeStyleObj_color_set(HandleRef jarg1, HandleRef jarg2);
 
@@ -2849,11 +2972,17 @@ class mapscriptPINVOKE {
   [DllImport("mapscript", EntryPoint="CSharp_delete_tileCacheObj")]
   public static extern void delete_tileCacheObj(HandleRef jarg1);
 
-  [DllImport("mapscript", EntryPoint="CSharp_labelStyleObj_font_set")]
-  public static extern void labelStyleObj_font_set(HandleRef jarg1, string jarg2);
+  [DllImport("mapscript", EntryPoint="CSharp_labelStyleObj_fonts_set")]
+  public static extern void labelStyleObj_fonts_set(HandleRef jarg1, HandleRef jarg2);
+
+  [DllImport("mapscript", EntryPoint="CSharp_labelStyleObj_fonts_get")]
+  public static extern IntPtr labelStyleObj_fonts_get(HandleRef jarg1);
 
-  [DllImport("mapscript", EntryPoint="CSharp_labelStyleObj_font_get")]
-  public static extern string labelStyleObj_font_get(HandleRef jarg1);
+  [DllImport("mapscript", EntryPoint="CSharp_labelStyleObj_numfonts_set")]
+  public static extern void labelStyleObj_numfonts_set(HandleRef jarg1, int jarg2);
+
+  [DllImport("mapscript", EntryPoint="CSharp_labelStyleObj_numfonts_get")]
+  public static extern int labelStyleObj_numfonts_get(HandleRef jarg1);
 
   [DllImport("mapscript", EntryPoint="CSharp_labelStyleObj_size_set")]
   public static extern void labelStyleObj_size_set(HandleRef jarg1, double jarg2);
@@ -2885,6 +3014,12 @@ class mapscriptPINVOKE {
   [DllImport("mapscript", EntryPoint="CSharp_labelStyleObj_outlinecolor_get")]
   public static extern IntPtr labelStyleObj_outlinecolor_get(HandleRef jarg1);
 
+  [DllImport("mapscript", EntryPoint="CSharp_labelStyleObj_antialias_set")]
+  public static extern void labelStyleObj_antialias_set(HandleRef jarg1, int jarg2);
+
+  [DllImport("mapscript", EntryPoint="CSharp_labelStyleObj_antialias_get")]
+  public static extern int labelStyleObj_antialias_get(HandleRef jarg1);
+
   [DllImport("mapscript", EntryPoint="CSharp_new_labelStyleObj")]
   public static extern IntPtr new_labelStyleObj();
 
@@ -3335,12 +3470,27 @@ class mapscriptPINVOKE {
   [DllImport("mapscript", EntryPoint="CSharp_shapefileObj_getDBF")]
   public static extern IntPtr shapefileObj_getDBF(HandleRef jarg1);
 
+  [DllImport("mapscript", EntryPoint="CSharp_wkp_none_get")]
+  public static extern int wkp_none_get();
+
+  [DllImport("mapscript", EntryPoint="CSharp_wkp_lonlat_get")]
+  public static extern int wkp_lonlat_get();
+
+  [DllImport("mapscript", EntryPoint="CSharp_wkp_gmerc_get")]
+  public static extern int wkp_gmerc_get();
+
   [DllImport("mapscript", EntryPoint="CSharp_projectionObj_numargs_get")]
   public static extern int projectionObj_numargs_get(HandleRef jarg1);
 
   [DllImport("mapscript", EntryPoint="CSharp_projectionObj_automatic_get")]
   public static extern int projectionObj_automatic_get(HandleRef jarg1);
 
+  [DllImport("mapscript", EntryPoint="CSharp_projectionObj_wellknownprojection_set")]
+  public static extern void projectionObj_wellknownprojection_set(HandleRef jarg1, int jarg2);
+
+  [DllImport("mapscript", EntryPoint="CSharp_projectionObj_wellknownprojection_get")]
+  public static extern int projectionObj_wellknownprojection_get(HandleRef jarg1);
+
   [DllImport("mapscript", EntryPoint="CSharp_new_projectionObj")]
   public static extern IntPtr new_projectionObj(string jarg1);
 
@@ -3365,12 +3515,6 @@ class mapscriptPINVOKE {
   [DllImport("mapscript", EntryPoint="CSharp_MS_IMAGECACHESIZE_get")]
   public static extern int MS_IMAGECACHESIZE_get();
 
-  [DllImport("mapscript", EntryPoint="CSharp_colorObj_pen_set")]
-  public static extern void colorObj_pen_set(HandleRef jarg1, int jarg2);
-
-  [DllImport("mapscript", EntryPoint="CSharp_colorObj_pen_get")]
-  public static extern int colorObj_pen_get(HandleRef jarg1);
-
   [DllImport("mapscript", EntryPoint="CSharp_colorObj_red_set")]
   public static extern void colorObj_red_set(HandleRef jarg1, int jarg2);
 
@@ -3476,6 +3620,18 @@ class mapscriptPINVOKE {
   [DllImport("mapscript", EntryPoint="CSharp_symbolObj_filled_get")]
   public static extern int symbolObj_filled_get(HandleRef jarg1);
 
+  [DllImport("mapscript", EntryPoint="CSharp_symbolObj_anchorpoint_x_set")]
+  public static extern void symbolObj_anchorpoint_x_set(HandleRef jarg1, double jarg2);
+
+  [DllImport("mapscript", EntryPoint="CSharp_symbolObj_anchorpoint_x_get")]
+  public static extern double symbolObj_anchorpoint_x_get(HandleRef jarg1);
+
+  [DllImport("mapscript", EntryPoint="CSharp_symbolObj_anchorpoint_y_set")]
+  public static extern void symbolObj_anchorpoint_y_set(HandleRef jarg1, double jarg2);
+
+  [DllImport("mapscript", EntryPoint="CSharp_symbolObj_anchorpoint_y_get")]
+  public static extern double symbolObj_anchorpoint_y_get(HandleRef jarg1);
+
   [DllImport("mapscript", EntryPoint="CSharp_symbolObj_imagepath_get")]
   public static extern string symbolObj_imagepath_get(HandleRef jarg1);
 
@@ -3797,6 +3953,9 @@ class mapscriptPINVOKE {
   [DllImport("mapscript", EntryPoint="CSharp_OWSRequest_setParameter")]
   public static extern void OWSRequest_setParameter(HandleRef jarg1, string jarg2, string jarg3);
 
+  [DllImport("mapscript", EntryPoint="CSharp_OWSRequest_addParameter")]
+  public static extern void OWSRequest_addParameter(HandleRef jarg1, string jarg2, string jarg3);
+
   [DllImport("mapscript", EntryPoint="CSharp_OWSRequest_getName")]
   public static extern string OWSRequest_getName(HandleRef jarg1, int jarg2);
 
diff --git a/mapscript/csharp/mapscript_wrap.c b/mapscript/csharp/mapscript_wrap.c
index cf78b5b..e3b8f77 100644
--- a/mapscript/csharp/mapscript_wrap.c
+++ b/mapscript/csharp/mapscript_wrap.c
@@ -555,7 +555,7 @@ SWIGINTERN int styleObj_setSymbolByName(styleObj *self,mapObj *map,char *symboln
         return self->symbol;
     }
 SWIGINTERN int styleObj_removeBinding(styleObj *self,int binding){
-    if(binding < 0 || binding >= 8) return MS_FAILURE;
+    if(binding < 0 || binding >= 12) return MS_FAILURE;
 
     if(self->bindings[binding].item) {
       free(self->bindings[binding].item);
@@ -568,7 +568,7 @@ SWIGINTERN int styleObj_removeBinding(styleObj *self,int binding){
   }
 SWIGINTERN int styleObj_setBinding(styleObj *self,int binding,char *item){
     if(!item) return MS_FAILURE;
-    if(binding < 0 || binding >= 8) return MS_FAILURE;
+    if(binding < 0 || binding >= 12) return MS_FAILURE;
 
     if(self->bindings[binding].item) {
       free(self->bindings[binding].item);
@@ -583,7 +583,7 @@ SWIGINTERN int styleObj_setBinding(styleObj *self,int binding,char *item){
     return MS_SUCCESS;
   }
 SWIGINTERN char *styleObj_getBinding(styleObj *self,int binding){
-    if(binding < 0 || binding >= 8) return NULL;
+    if(binding < 0 || binding >= 12) return NULL;
 
     return self->bindings[binding].item;
   }
@@ -593,6 +593,20 @@ SWIGINTERN char *styleObj_getGeomTransform(styleObj *self){
 SWIGINTERN void styleObj_setGeomTransform(styleObj *self,char *transform){
     msStyleSetGeomTransform(self, transform);
   }
+SWIGINTERN labelObj *new_labelObj(){
+      labelObj *label;
+        
+      label = (labelObj *)calloc(1, sizeof(labelObj));
+      if (!label)
+        return(NULL);
+    
+      initLabel(label);
+      
+      return(label);    	
+    }
+SWIGINTERN void delete_labelObj(labelObj *self){
+      freeLabel(self);
+    }
 SWIGINTERN int labelObj_updateFromString(labelObj *self,char *snippet){
     return msUpdateLabelFromString(self, snippet);
   }
@@ -629,6 +643,26 @@ SWIGINTERN int labelObj_setBinding(labelObj *self,int binding,char *item){
 
     return MS_SUCCESS;
   }
+SWIGINTERN int labelObj_setExpression(labelObj *self,char *expression){
+    if (!expression || strlen(expression) == 0) {
+       freeExpression(&self->expression);
+       return MS_SUCCESS;
+    }
+    else return msLoadExpressionString(&self->expression, expression);
+  }
+SWIGINTERN char *labelObj_getExpressionString(labelObj *self){
+    return msGetExpressionString(&(self->expression));
+  }
+SWIGINTERN int labelObj_setText(labelObj *self,char *text){
+    if (!text || strlen(text) == 0) {
+      freeExpression(&self->text);
+      return MS_SUCCESS;
+    }	
+    else return msLoadExpressionString(&self->text, text);
+  }
+SWIGINTERN char *labelObj_getTextString(labelObj *self){
+    return msGetExpressionString(&(self->text));
+  }
 SWIGINTERN styleObj *labelObj_getStyle(labelObj *self,int i){
       if (i >= 0 && i < self->numstyles) {
           MS_REFCNT_INCR(self->styles[i]);
@@ -774,30 +808,46 @@ SWIGINTERN int classObj_drawLegendIcon(classObj *self,mapObj *map,layerObj *laye
 SWIGINTERN imageObj *classObj_createLegendIcon(classObj *self,mapObj *map,layerObj *layer,int width,int height){
     return msCreateLegendIcon(map, layer, self, width, height);
   }
+SWIGINTERN labelObj *classObj_getLabel(classObj *self,int i){
+    if (i >= 0 && i < self->numlabels) {
+      MS_REFCNT_INCR(self->labels[i]);
+      return self->labels[i];
+    } else {
+      msSetError(31, "Invalid index: %d.", "getLabel()", i);
+      return NULL;
+    }
+  }
+SWIGINTERN int classObj_addLabel(classObj *self,labelObj *label){
+    return msAddLabelToClass(self, label);
+  }
+SWIGINTERN labelObj *classObj_removeLabel(classObj *self,int index){
+    labelObj* label = (labelObj *) msRemoveLabelFromClass(self, index);
+    if (label) MS_REFCNT_INCR(label);
+    return label;
+  }
 SWIGINTERN styleObj *classObj_getStyle(classObj *self,int i){
-        if (i >= 0 && i < self->numstyles) {
-	    MS_REFCNT_INCR(self->styles[i]);
-            return self->styles[i];
-	} else {
-            msSetError(31, "Invalid index: %d", "getStyle()", i);
-            return NULL;
-        }
+    if (i >= 0 && i < self->numstyles) {
+      MS_REFCNT_INCR(self->styles[i]);
+      return self->styles[i];
+    } else {
+      msSetError(31, "Invalid index: %d", "getStyle()", i);
+      return NULL;
     }
+  }
 SWIGINTERN int classObj_insertStyle(classObj *self,styleObj *style,int index){
-        return msInsertStyle(self, style, index);
-    }
+    return msInsertStyle(self, style, index);
+  }
 SWIGINTERN styleObj *classObj_removeStyle(classObj *self,int index){
-	styleObj* style = (styleObj *) msRemoveStyle(self, index);
-	if (style)
-		MS_REFCNT_INCR(style);
-        return style;
-    }
+    styleObj* style = (styleObj *) msRemoveStyle(self, index);
+    if (style) MS_REFCNT_INCR(style);
+    return style;
+  }
 SWIGINTERN int classObj_moveStyleUp(classObj *self,int index){
-        return msMoveStyleUp(self, index);
-    }
+    return msMoveStyleUp(self, index);
+  }
 SWIGINTERN int classObj_moveStyleDown(classObj *self,int index){
-       return msMoveStyleDown(self, index);
-    }
+    return msMoveStyleDown(self, index);
+  }
 SWIGINTERN void labelCacheObj_freeCache(labelCacheObj *self){
         msFreeLabelCache(self);    
     }
@@ -884,6 +934,89 @@ SWIGINTERN int scalebarObj_updateFromString(scalebarObj *self,char *snippet){
 SWIGINTERN int legendObj_updateFromString(legendObj *self,char *snippet){
     return msUpdateLegendFromString(self, snippet, 0);
   }
+SWIGINTERN void imageObj_getBytes(imageObj *self,SWIG_CSharpByteArrayHelperCallback callback){
+        gdBuffer buffer;
+        
+        buffer.owns_data = MS_TRUE;
+        
+        buffer.data = msSaveImageBuffer(self, &buffer.size, self->format);
+            
+        if( buffer.data == NULL || buffer.size == 0 )
+        {
+            msSetError(MS_MISCERR, "Failed to get image buffer", "getBytes");
+            return;
+        }
+        callback(buffer.data, buffer.size);
+        msFree(buffer.data);
+	}
+SWIGINTERN imageObj *new_imageObj(int width,int height,outputFormatObj *input_format,char const *file,double resolution,double defresolution){
+        imageObj *image=NULL;
+        outputFormatObj *format;
+        rendererVTableObj *renderer = NULL;
+        rasterBufferObj *rb = NULL;
+
+        if (input_format) {
+            format = input_format;
+        }
+        else {
+            format = msCreateDefaultOutputFormat(NULL, "GD/GIF", "gdgif");
+            if (format == NULL)
+                format = msCreateDefaultOutputFormat(NULL, "GD/PNG", "gdpng");
+            if (format == NULL)
+
+            if (format)
+                msInitializeRendererVTable(format);
+        }
+        if (format == NULL) {
+            msSetError(15, "Could not create output format",
+                       "imageObj()");
+            return NULL;
+        }
+
+        if (file) {
+            
+            renderer = format->vtable;
+            rb = (rasterBufferObj*) malloc(sizeof(rasterBufferObj));
+            if (!rb) {
+                msSetError(2, NULL, "imageObj()");
+                return NULL;
+            }
+            if ( (renderer->loadImageFromFile((char *)file, rb)) == MS_FAILURE)
+                return NULL;
+
+            image = msImageCreate(rb->width, rb->height, format, NULL, NULL, 
+                                  resolution, defresolution, NULL);
+            renderer->mergeRasterBuffer(image, rb, 1.0, 0, 0, 0, 0, rb->width, rb->height);
+
+            msFreeRasterBuffer(rb);
+            free(rb);
+
+            return image;
+        }
+
+        image = msImageCreate(width, height, format, NULL, NULL, resolution, defresolution, NULL);
+        return image;
+    }
+SWIGINTERN void delete_imageObj(imageObj *self){
+        msFreeImage(self);    
+    }
+SWIGINTERN void imageObj_save(imageObj *self,char *filename,mapObj *map){
+        msSaveImage(map, self, filename );
+    }
+SWIGINTERN int imageObj_getSize(imageObj *self){
+        gdBuffer buffer;
+	int size=0;
+        
+        buffer.data = msSaveImageBuffer(self, &buffer.size, self->format);
+	size = buffer.size;
+            
+        if( buffer.data == NULL || buffer.size == 0 ) {
+            buffer.data = NULL;
+            msSetError(12, "Failed to get image buffer size", "getSize");
+        }
+	free(buffer.data);
+        return size;
+    }
 SWIGINTERN layerObj *new_layerObj(mapObj *map){
         layerObj *layer;
         int result;
@@ -1056,6 +1189,9 @@ SWIGINTERN char *layerObj_getItem(layerObj *self,int i){
         else
             return NULL;
     }
+SWIGINTERN int layerObj_setItems(layerObj *self,char **items,int numitems){
+        return msLayerSetItems(self, items, numitems);
+    }
 SWIGINTERN int layerObj_draw(layerObj *self,mapObj *map,imageObj *image){
         return msDrawLayer(map, self, image);    
     }
@@ -1073,7 +1209,10 @@ SWIGINTERN int layerObj_queryByFilter(layerObj *self,mapObj *map,char *string){
         map->query.filter = (expressionObj *) malloc(sizeof(expressionObj));
         map->query.filter->string = strdup(string);
 	map->query.filter->type = 2000; /* MS_EXPRESSION: lot's of conflicts in mapfile.h */
-
+        map->query.filter->compiled = 0;
+        map->query.filter->flags = 0;
+        map->query.filter->tokens = map->query.filter->curtoken = NULL;
+        
         map->query.layer = self->index;
      	map->query.rect = map->extent;
 
@@ -1100,6 +1239,7 @@ SWIGINTERN int layerObj_queryByAttributes(layerObj *self,mapObj *map,char *qitem
         self->status = 1;
         retval = msQueryByAttributes(map);
         self->status = status;
+
         return retval;
     }
 SWIGINTERN int layerObj_queryByPoint(layerObj *self,mapObj *map,pointObj *point,int mode,double buffer){
@@ -1118,6 +1258,7 @@ SWIGINTERN int layerObj_queryByPoint(layerObj *self,mapObj *map,pointObj *point,
         self->status = 1;
         retval = msQueryByPoint(map);
         self->status = status;
+
         return retval;
     }
 SWIGINTERN int layerObj_queryByRect(layerObj *self,mapObj *map,rectObj rect){
@@ -1135,6 +1276,7 @@ SWIGINTERN int layerObj_queryByRect(layerObj *self,mapObj *map,rectObj rect){
         self->status = 1;
         retval = msQueryByRect(map);
         self->status = status;
+
         return retval;
     }
 SWIGINTERN int layerObj_queryByFeatures(layerObj *self,mapObj *map,int slayer){
@@ -1284,10 +1426,10 @@ SWIGINTERN char *layerObj_executeWFSGetFeature(layerObj *self,layerObj *layer){
         return (char *) msWFSExecuteGetFeature(layer);
     }
 SWIGINTERN int layerObj_applySLD(layerObj *self,char *sld,char *stylelayer){
-        return msSLDApplySLD(self->map, sld, self->index, stylelayer);
+      return msSLDApplySLD(self->map, sld, self->index, stylelayer, NULL);
     }
 SWIGINTERN int layerObj_applySLDURL(layerObj *self,char *sld,char *stylelayer){
-        return msSLDApplySLDURL(self->map, sld, self->index, stylelayer);
+      return msSLDApplySLDURL(self->map, sld, self->index, stylelayer, NULL);
     }
 SWIGINTERN char *layerObj_generateSLD(layerObj *self){
         return (char *) msSLDGenerateSLD(self->map, self->index, NULL);
@@ -1491,7 +1633,10 @@ SWIGINTERN int mapObj_queryByFilter(mapObj *self,char *string){
     self->query.filter = (expressionObj *) malloc(sizeof(expressionObj));
     self->query.filter->string = strdup(string);
     self->query.filter->type = 2000; /* MS_EXPRESSION: lot's of conflicts in mapfile.h */
-
+    self->query.filter->compiled = 0;
+    self->query.filter->flags = 0;
+    self->query.filter->tokens = self->query.filter->curtoken = NULL;
+    
     self->query.rect = self->extent;
 
     return msQueryByFilter(self);
@@ -1640,10 +1785,10 @@ SWIGINTERN void mapObj_applyConfigOptions(mapObj *self){
     msApplyMapConfigOptions( self );
   }
 SWIGINTERN int mapObj_applySLD(mapObj *self,char *sld){
-        return msSLDApplySLD(self, sld, -1, NULL);
+      return msSLDApplySLD(self, sld, -1, NULL, NULL);
     }
 SWIGINTERN int mapObj_applySLDURL(mapObj *self,char *sld){
-        return msSLDApplySLDURL(self, sld, -1, NULL);
+      return msSLDApplySLDURL(self, sld, -1, NULL, NULL);
     }
 SWIGINTERN char *mapObj_generateSLD(mapObj *self){
         return (char *) msSLDGenerateSLD(self, -1, NULL);
@@ -2199,89 +2344,6 @@ SWIGINTERN int mapObj_zoomScale(mapObj *self,double scale,pointObj *poPixPos,int
 
         return MS_SUCCESS;
     }
-SWIGINTERN void imageObj_getBytes(imageObj *self,SWIG_CSharpByteArrayHelperCallback callback){
-        gdBuffer buffer;
-        
-        buffer.owns_data = MS_TRUE;
-        
-        buffer.data = msSaveImageBuffer(self, &buffer.size, self->format);
-            
-        if( buffer.data == NULL || buffer.size == 0 )
-        {
-            msSetError(MS_MISCERR, "Failed to get image buffer", "getBytes");
-            return;
-        }
-        callback(buffer.data, buffer.size);
-        msFree(buffer.data);
-	}
-SWIGINTERN imageObj *new_imageObj(int width,int height,outputFormatObj *input_format,char const *file,double resolution,double defresolution){
-        imageObj *image=NULL;
-        outputFormatObj *format;
-        rendererVTableObj *renderer = NULL;
-        rasterBufferObj *rb = NULL;
-
-        if (input_format) {
-            format = input_format;
-        }
-        else {
-            format = msCreateDefaultOutputFormat(NULL, "GD/GIF", "gdgif");
-            if (format == NULL)
-                format = msCreateDefaultOutputFormat(NULL, "GD/PNG", "gdpng");
-            if (format == NULL)
-
-            if (format)
-                msInitializeRendererVTable(format);
-        }
-        if (format == NULL) {
-            msSetError(15, "Could not create output format",
-                       "imageObj()");
-            return NULL;
-        }
-
-        if (file) {
-            
-            renderer = format->vtable;
-            rb = (rasterBufferObj*) malloc(sizeof(rasterBufferObj));
-            if (!rb) {
-                msSetError(2, NULL, "imageObj()");
-                return NULL;
-            }
-            if ( (renderer->loadImageFromFile(file, rb)) == MS_FAILURE)
-                return NULL;
-
-            image = msImageCreate(rb->width, rb->height, format, NULL, NULL, 
-                                  resolution, defresolution, NULL);
-            renderer->mergeRasterBuffer(image, rb, 1.0, 0, 0, 0, 0, rb->width, rb->height);
-
-            msFreeRasterBuffer(rb);
-            free(rb);
-
-            return image;
-        }
-
-        image = msImageCreate(width, height, format, NULL, NULL, resolution, defresolution, NULL);
-        return image;
-    }
-SWIGINTERN void delete_imageObj(imageObj *self){
-        msFreeImage(self);    
-    }
-SWIGINTERN void imageObj_save(imageObj *self,char *filename,mapObj *map){
-        msSaveImage(map, self, filename );
-    }
-SWIGINTERN int imageObj_getSize(imageObj *self){
-        gdBuffer buffer;
-	int size=0;
-        
-        buffer.data = msSaveImageBuffer(self, &buffer.size, self->format);
-	size = buffer.size;
-            
-        if( buffer.data == NULL || buffer.size == 0 ) {
-            buffer.data = NULL;
-            msSetError(12, "Failed to get image buffer size", "getSize");
-        }
-	free(buffer.data);
-        return size;
-    }
 SWIGINTERN rectObj *new_rectObj(double minx,double miny,double maxx,double maxy,int imageunits){	
         rectObj *rect;
     
@@ -2334,7 +2396,7 @@ SWIGINTERN int rectObj_draw(rectObj *self,mapObj *map,layerObj *layer,imageObj *
         shape.classindex = classindex;
         shape.text = strdup(text);
 
-        msDrawShape(map, layer, &shape, image, -1, 0);
+        msDrawShape(map, layer, &shape, image, -1, MS_DRAWMODE_FEATURES|MS_DRAWMODE_LABELS);
 
         msFreeShape(&shape);
     
@@ -2573,7 +2635,7 @@ SWIGINTERN int shapeObj_add(shapeObj *self,lineObj *line){
         return msAddLine(self, line);
     }
 SWIGINTERN int shapeObj_draw(shapeObj *self,mapObj *map,layerObj *layer,imageObj *image){
-        return msDrawShape(map, layer, self, image, -1, 0);
+        return msDrawShape(map, layer, self, image, -1, MS_DRAWMODE_FEATURES|MS_DRAWMODE_LABELS);
     }
 SWIGINTERN void shapeObj_setBounds(shapeObj *self){    
         msComputeBounds(self);
@@ -2944,7 +3006,7 @@ SWIGINTERN lineObj *symbolObj_getPoints(symbolObj *self){
         return line;
     }
 SWIGINTERN imageObj *symbolObj_getImage(symbolObj *self,outputFormatObj *input_format){
-        imageObj *image;
+        imageObj *image = NULL;
         outputFormatObj *format = NULL;
         rendererVTableObj *renderer = NULL;
 
@@ -3003,7 +3065,6 @@ SWIGINTERN int symbolObj_setImage(symbolObj *self,imageObj *image){
             msSetError(2, NULL, "setImage()");
             return MS_FAILURE;
         }
-        renderer->initializeRasterBuffer(self->pixmap_buffer, image->width, image->height, image->format->imagemode);
         self->type = MS_SYMBOL_PIXMAP;
         renderer->getRasterBufferCopy(image, self->pixmap_buffer);
 
@@ -3125,6 +3186,14 @@ SWIGINTERN void cgiRequestObj_setParameter(cgiRequestObj *self,char *name,char *
             self->NumParams++;
         }
     }
+SWIGINTERN void cgiRequestObj_addParameter(cgiRequestObj *self,char *name,char *value){
+        if (self->NumParams == 100) {
+            msSetError(31, "Maximum number of items, %d, has been reached", "addParameter()", 100);
+        }
+        self->ParamNames[self->NumParams] = strdup(name);
+        self->ParamValues[self->NumParams] = strdup(value);
+        self->NumParams++;
+    }
 SWIGINTERN char *cgiRequestObj_getName(cgiRequestObj *self,int index){
         if (index < 0 || index >= self->NumParams) {
             msSetError(31, "Invalid index, valid range is [0, %d]", "getName()", self->NumParams-1);
@@ -3281,7 +3350,7 @@ SWIGEXPORT char * SWIGSTDCALL CSharp_MS_VERSION_get() {
   char * jresult ;
   char *result = 0 ;
   
-  result = (char *) "6.0.3";
+  result = (char *) "6.2.0";
   jresult = SWIG_csharp_string_callback((const char *)result); 
   return jresult;
 }
@@ -3301,7 +3370,7 @@ SWIGEXPORT int SWIGSTDCALL CSharp_MS_VERSION_MINOR_get() {
   int jresult ;
   int result;
   
-  result = (int) 0;
+  result = (int) 2;
   jresult = result; 
   return jresult;
 }
@@ -3311,7 +3380,7 @@ SWIGEXPORT int SWIGSTDCALL CSharp_MS_VERSION_REV_get() {
   int jresult ;
   int result;
   
-  result = (int) 3;
+  result = (int) 0;
   jresult = result; 
   return jresult;
 }
@@ -3321,22 +3390,12 @@ SWIGEXPORT int SWIGSTDCALL CSharp_MS_VERSION_NUM_get() {
   int jresult ;
   int result;
   
-  result = (int) (6*10000+0*100+3);
+  result = (int) (6*10000+2*100+0);
   jresult = result; 
   return jresult;
 }
 
 
-SWIGEXPORT char * SWIGSTDCALL CSharp___FUNCTION___get() {
-  char * jresult ;
-  char *result = 0 ;
-  
-  result = (char *) "MapServer";
-  jresult = SWIG_csharp_string_callback((const char *)result); 
-  return jresult;
-}
-
-
 SWIGEXPORT int SWIGSTDCALL CSharp_MS_TRUE_get() {
   int jresult ;
   int result;
@@ -3477,6 +3536,16 @@ SWIGEXPORT int SWIGSTDCALL CSharp_MS_STYLE_ALLOCSIZE_get() {
 }
 
 
+SWIGEXPORT int SWIGSTDCALL CSharp_MS_LABEL_ALLOCSIZE_get() {
+  int jresult ;
+  int result;
+  
+  result = (int) 2;
+  jresult = result; 
+  return jresult;
+}
+
+
 SWIGEXPORT int SWIGSTDCALL CSharp_MS_MAX_LABEL_PRIORITY_get() {
   int jresult ;
   int result;
@@ -3487,6 +3556,16 @@ SWIGEXPORT int SWIGSTDCALL CSharp_MS_MAX_LABEL_PRIORITY_get() {
 }
 
 
+SWIGEXPORT int SWIGSTDCALL CSharp_MS_MAX_LABEL_FONTS_get() {
+  int jresult ;
+  int result;
+  
+  result = (int) 5;
+  jresult = result; 
+  return jresult;
+}
+
+
 SWIGEXPORT int SWIGSTDCALL CSharp_MS_DEFAULT_LABEL_PRIORITY_get() {
   int jresult ;
   int result;
@@ -3497,6 +3576,16 @@ SWIGEXPORT int SWIGSTDCALL CSharp_MS_DEFAULT_LABEL_PRIORITY_get() {
 }
 
 
+SWIGEXPORT int SWIGSTDCALL CSharp_MS_LABEL_FORCE_GROUP_get() {
+  int jresult ;
+  int result;
+  
+  result = (int) 2;
+  jresult = result; 
+  return jresult;
+}
+
+
 SWIGEXPORT int SWIGSTDCALL CSharp_MS_RENDER_WITH_SWF_get() {
   int jresult ;
   int result;
@@ -3671,7 +3760,7 @@ SWIGEXPORT int SWIGSTDCALL CSharp_MS_STYLE_BINDING_LENGTH_get() {
   int jresult ;
   int result;
   
-  result = (int) 8;
+  result = (int) 12;
   jresult = result; 
   return jresult;
 }
@@ -4905,10 +4994,10 @@ SWIGEXPORT char * SWIGSTDCALL CSharp_webObj_temppath_get(void * jarg1) {
 SWIGEXPORT void * SWIGSTDCALL CSharp_webObj_map_get(void * jarg1) {
   void * jresult ;
   webObj *arg1 = (webObj *) 0 ;
-  struct map_obj *result = 0 ;
+  struct mapObj *result = 0 ;
   
   arg1 = (webObj *)jarg1; 
-  result = (struct map_obj *) ((arg1)->map);
+  result = (struct mapObj *) ((arg1)->map);
   jresult = (void *)result; 
   return jresult;
 }
@@ -5837,6 +5926,28 @@ SWIGEXPORT double SWIGSTDCALL CSharp_styleObj_gap_get(void * jarg1) {
 }
 
 
+SWIGEXPORT void SWIGSTDCALL CSharp_styleObj_initialgap_set(void * jarg1, double jarg2) {
+  styleObj *arg1 = (styleObj *) 0 ;
+  double arg2 ;
+  
+  arg1 = (styleObj *)jarg1; 
+  arg2 = (double)jarg2; 
+  if (arg1) (arg1)->initialgap = arg2;
+}
+
+
+SWIGEXPORT double SWIGSTDCALL CSharp_styleObj_initialgap_get(void * jarg1) {
+  double jresult ;
+  styleObj *arg1 = (styleObj *) 0 ;
+  double result;
+  
+  arg1 = (styleObj *)jarg1; 
+  result = (double) ((arg1)->initialgap);
+  jresult = result; 
+  return jresult;
+}
+
+
 SWIGEXPORT void SWIGSTDCALL CSharp_styleObj_position_set(void * jarg1, int jarg2) {
   styleObj *arg1 = (styleObj *) 0 ;
   int arg2 ;
@@ -6057,6 +6168,50 @@ SWIGEXPORT double SWIGSTDCALL CSharp_styleObj_offsety_get(void * jarg1) {
 }
 
 
+SWIGEXPORT void SWIGSTDCALL CSharp_styleObj_polaroffsetpixel_set(void * jarg1, double jarg2) {
+  styleObj *arg1 = (styleObj *) 0 ;
+  double arg2 ;
+  
+  arg1 = (styleObj *)jarg1; 
+  arg2 = (double)jarg2; 
+  if (arg1) (arg1)->polaroffsetpixel = arg2;
+}
+
+
+SWIGEXPORT double SWIGSTDCALL CSharp_styleObj_polaroffsetpixel_get(void * jarg1) {
+  double jresult ;
+  styleObj *arg1 = (styleObj *) 0 ;
+  double result;
+  
+  arg1 = (styleObj *)jarg1; 
+  result = (double) ((arg1)->polaroffsetpixel);
+  jresult = result; 
+  return jresult;
+}
+
+
+SWIGEXPORT void SWIGSTDCALL CSharp_styleObj_polaroffsetangle_set(void * jarg1, double jarg2) {
+  styleObj *arg1 = (styleObj *) 0 ;
+  double arg2 ;
+  
+  arg1 = (styleObj *)jarg1; 
+  arg2 = (double)jarg2; 
+  if (arg1) (arg1)->polaroffsetangle = arg2;
+}
+
+
+SWIGEXPORT double SWIGSTDCALL CSharp_styleObj_polaroffsetangle_get(void * jarg1) {
+  double jresult ;
+  styleObj *arg1 = (styleObj *) 0 ;
+  double result;
+  
+  arg1 = (styleObj *)jarg1; 
+  result = (double) ((arg1)->polaroffsetangle);
+  jresult = result; 
+  return jresult;
+}
+
+
 SWIGEXPORT void SWIGSTDCALL CSharp_styleObj_angle_set(void * jarg1, double jarg2) {
   styleObj *arg1 = (styleObj *) 0 ;
   double arg2 ;
@@ -6443,6 +6598,126 @@ SWIGEXPORT void SWIGSTDCALL CSharp_styleObj_setGeomTransform(void * jarg1, char
 }
 
 
+SWIGEXPORT void SWIGSTDCALL CSharp_labelLeaderObj_maxdistance_set(void * jarg1, int jarg2) {
+  labelLeaderObj *arg1 = (labelLeaderObj *) 0 ;
+  int arg2 ;
+  
+  arg1 = (labelLeaderObj *)jarg1; 
+  arg2 = (int)jarg2; 
+  if (arg1) (arg1)->maxdistance = arg2;
+}
+
+
+SWIGEXPORT int SWIGSTDCALL CSharp_labelLeaderObj_maxdistance_get(void * jarg1) {
+  int jresult ;
+  labelLeaderObj *arg1 = (labelLeaderObj *) 0 ;
+  int result;
+  
+  arg1 = (labelLeaderObj *)jarg1; 
+  result = (int) ((arg1)->maxdistance);
+  jresult = result; 
+  return jresult;
+}
+
+
+SWIGEXPORT void SWIGSTDCALL CSharp_labelLeaderObj_gridstep_set(void * jarg1, int jarg2) {
+  labelLeaderObj *arg1 = (labelLeaderObj *) 0 ;
+  int arg2 ;
+  
+  arg1 = (labelLeaderObj *)jarg1; 
+  arg2 = (int)jarg2; 
+  if (arg1) (arg1)->gridstep = arg2;
+}
+
+
+SWIGEXPORT int SWIGSTDCALL CSharp_labelLeaderObj_gridstep_get(void * jarg1) {
+  int jresult ;
+  labelLeaderObj *arg1 = (labelLeaderObj *) 0 ;
+  int result;
+  
+  arg1 = (labelLeaderObj *)jarg1; 
+  result = (int) ((arg1)->gridstep);
+  jresult = result; 
+  return jresult;
+}
+
+
+SWIGEXPORT int SWIGSTDCALL CSharp_labelLeaderObj_numstyles_get(void * jarg1) {
+  int jresult ;
+  labelLeaderObj *arg1 = (labelLeaderObj *) 0 ;
+  int result;
+  
+  arg1 = (labelLeaderObj *)jarg1; 
+  result = (int) ((arg1)->numstyles);
+  jresult = result; 
+  return jresult;
+}
+
+
+SWIGEXPORT void * SWIGSTDCALL CSharp_new_labelLeaderObj() {
+  void * jresult ;
+  labelLeaderObj *result = 0 ;
+  
+  {
+    errorObj *ms_error;
+    result = (labelLeaderObj *)calloc(1, sizeof(labelLeaderObj));
+    ms_error = msGetErrorObj();
+    if (ms_error != NULL && ms_error->code != MS_NOERR) {
+      if (ms_error->code != MS_NOTFOUND && ms_error->code != -1) {
+        char* msg = msGetErrorString(";"); 
+        if (msg) {
+          SWIG_CSharpException(SWIG_SystemError, msg);
+          free(msg);
+        }
+        else SWIG_CSharpException(SWIG_SystemError, "MapScript unknown error");
+        msResetErrorList();
+        return 0;
+      }
+      msResetErrorList();
+    }
+  }
+  jresult = (void *)result; 
+  return jresult;
+}
+
+
+SWIGEXPORT void SWIGSTDCALL CSharp_delete_labelLeaderObj(void * jarg1) {
+  labelLeaderObj *arg1 = (labelLeaderObj *) 0 ;
+  
+  arg1 = (labelLeaderObj *)jarg1; 
+  {
+    errorObj *ms_error;
+    free((char *) arg1);
+    ms_error = msGetErrorObj();
+    if (ms_error != NULL && ms_error->code != MS_NOERR) {
+      if (ms_error->code != MS_NOTFOUND && ms_error->code != -1) {
+        char* msg = msGetErrorString(";"); 
+        if (msg) {
+          SWIG_CSharpException(SWIG_SystemError, msg);
+          free(msg);
+        }
+        else SWIG_CSharpException(SWIG_SystemError, "MapScript unknown error");
+        msResetErrorList();
+        return ;
+      }
+      msResetErrorList();
+    }
+  }
+}
+
+
+SWIGEXPORT int SWIGSTDCALL CSharp_labelObj_refcount_get(void * jarg1) {
+  int jresult ;
+  labelObj *arg1 = (labelObj *) 0 ;
+  int result;
+  
+  arg1 = (labelObj *)jarg1; 
+  result = (int) ((arg1)->refcount);
+  jresult = result; 
+  return jresult;
+}
+
+
 SWIGEXPORT void SWIGSTDCALL CSharp_labelObj_font_set(void * jarg1, char * jarg2) {
   labelObj *arg1 = (labelObj *) 0 ;
   char *arg2 = (char *) 0 ;
@@ -7207,6 +7482,28 @@ SWIGEXPORT int SWIGSTDCALL CSharp_labelObj_priority_get(void * jarg1) {
 }
 
 
+SWIGEXPORT void SWIGSTDCALL CSharp_labelObj_status_set(void * jarg1, int jarg2) {
+  labelObj *arg1 = (labelObj *) 0 ;
+  int arg2 ;
+  
+  arg1 = (labelObj *)jarg1; 
+  arg2 = (int)jarg2; 
+  if (arg1) (arg1)->status = arg2;
+}
+
+
+SWIGEXPORT int SWIGSTDCALL CSharp_labelObj_status_get(void * jarg1) {
+  int jresult ;
+  labelObj *arg1 = (labelObj *) 0 ;
+  int result;
+  
+  arg1 = (labelObj *)jarg1; 
+  result = (int) ((arg1)->status);
+  jresult = result; 
+  return jresult;
+}
+
+
 SWIGEXPORT void SWIGSTDCALL CSharp_labelObj_numstyles_set(void * jarg1, int jarg2) {
   labelObj *arg1 = (labelObj *) 0 ;
   int arg2 ;
@@ -7229,17 +7526,109 @@ SWIGEXPORT int SWIGSTDCALL CSharp_labelObj_numstyles_get(void * jarg1) {
 }
 
 
-SWIGEXPORT int SWIGSTDCALL CSharp_labelObj_updateFromString(void * jarg1, char * jarg2) {
-  int jresult ;
+SWIGEXPORT void SWIGSTDCALL CSharp_labelObj_annotext_set(void * jarg1, char * jarg2) {
   labelObj *arg1 = (labelObj *) 0 ;
   char *arg2 = (char *) 0 ;
-  int result;
   
   arg1 = (labelObj *)jarg1; 
   arg2 = (char *)jarg2; 
   {
+    if (arg1->annotext) free((char*)arg1->annotext);
+    if (arg2) {
+      arg1->annotext = (char *) malloc(strlen(arg2)+1);
+      strcpy((char*)arg1->annotext,arg2);
+    } else {
+      arg1->annotext = 0;
+    }
+  }
+}
+
+
+SWIGEXPORT char * SWIGSTDCALL CSharp_labelObj_annotext_get(void * jarg1) {
+  char * jresult ;
+  labelObj *arg1 = (labelObj *) 0 ;
+  char *result = 0 ;
+  
+  arg1 = (labelObj *)jarg1; 
+  result = (char *) ((arg1)->annotext);
+  jresult = SWIG_csharp_string_callback((const char *)result); 
+  return jresult;
+}
+
+
+SWIGEXPORT void SWIGSTDCALL CSharp_labelObj_annopoint_set(void * jarg1, void * jarg2) {
+  labelObj *arg1 = (labelObj *) 0 ;
+  pointObj *arg2 = (pointObj *) 0 ;
+  
+  arg1 = (labelObj *)jarg1; 
+  arg2 = (pointObj *)jarg2; 
+  if (arg1) (arg1)->annopoint = *arg2;
+}
+
+
+SWIGEXPORT void * SWIGSTDCALL CSharp_labelObj_annopoint_get(void * jarg1) {
+  void * jresult ;
+  labelObj *arg1 = (labelObj *) 0 ;
+  pointObj *result = 0 ;
+  
+  arg1 = (labelObj *)jarg1; 
+  result = (pointObj *)& ((arg1)->annopoint);
+  jresult = (void *)result; 
+  return jresult;
+}
+
+
+SWIGEXPORT void SWIGSTDCALL CSharp_labelObj_annopoly_set(void * jarg1, void * jarg2) {
+  labelObj *arg1 = (labelObj *) 0 ;
+  shapeObj *arg2 = (shapeObj *) 0 ;
+  
+  arg1 = (labelObj *)jarg1; 
+  arg2 = (shapeObj *)jarg2; 
+  if (arg1) (arg1)->annopoly = arg2;
+}
+
+
+SWIGEXPORT void * SWIGSTDCALL CSharp_labelObj_annopoly_get(void * jarg1) {
+  void * jresult ;
+  labelObj *arg1 = (labelObj *) 0 ;
+  shapeObj *result = 0 ;
+  
+  arg1 = (labelObj *)jarg1; 
+  result = (shapeObj *) ((arg1)->annopoly);
+  jresult = (void *)result; 
+  return jresult;
+}
+
+
+SWIGEXPORT void SWIGSTDCALL CSharp_labelObj_leader_set(void * jarg1, void * jarg2) {
+  labelObj *arg1 = (labelObj *) 0 ;
+  labelLeaderObj *arg2 = (labelLeaderObj *) 0 ;
+  
+  arg1 = (labelObj *)jarg1; 
+  arg2 = (labelLeaderObj *)jarg2; 
+  if (arg1) (arg1)->leader = *arg2;
+}
+
+
+SWIGEXPORT void * SWIGSTDCALL CSharp_labelObj_leader_get(void * jarg1) {
+  void * jresult ;
+  labelObj *arg1 = (labelObj *) 0 ;
+  labelLeaderObj *result = 0 ;
+  
+  arg1 = (labelObj *)jarg1; 
+  result = (labelLeaderObj *)& ((arg1)->leader);
+  jresult = (void *)result; 
+  return jresult;
+}
+
+
+SWIGEXPORT void * SWIGSTDCALL CSharp_new_labelObj() {
+  void * jresult ;
+  labelObj *result = 0 ;
+  
+  {
     errorObj *ms_error;
-    result = (int)labelObj_updateFromString(arg1,arg2);
+    result = (labelObj *)new_labelObj();
     ms_error = msGetErrorObj();
     if (ms_error != NULL && ms_error->code != MS_NOERR) {
       if (ms_error->code != MS_NOTFOUND && ms_error->code != -1) {
@@ -7255,19 +7644,75 @@ SWIGEXPORT int SWIGSTDCALL CSharp_labelObj_updateFromString(void * jarg1, char *
       msResetErrorList();
     }
   }
-  jresult = result; 
+  jresult = (void *)result; 
   return jresult;
 }
 
 
-SWIGEXPORT int SWIGSTDCALL CSharp_labelObj_removeBinding(void * jarg1, int jarg2) {
-  int jresult ;
+SWIGEXPORT void SWIGSTDCALL CSharp_delete_labelObj(void * jarg1) {
   labelObj *arg1 = (labelObj *) 0 ;
-  int arg2 ;
-  int result;
   
   arg1 = (labelObj *)jarg1; 
-  arg2 = (int)jarg2; 
+  {
+    errorObj *ms_error;
+    delete_labelObj(arg1);
+    ms_error = msGetErrorObj();
+    if (ms_error != NULL && ms_error->code != MS_NOERR) {
+      if (ms_error->code != MS_NOTFOUND && ms_error->code != -1) {
+        char* msg = msGetErrorString(";"); 
+        if (msg) {
+          SWIG_CSharpException(SWIG_SystemError, msg);
+          free(msg);
+        }
+        else SWIG_CSharpException(SWIG_SystemError, "MapScript unknown error");
+        msResetErrorList();
+        return ;
+      }
+      msResetErrorList();
+    }
+  }
+}
+
+
+SWIGEXPORT int SWIGSTDCALL CSharp_labelObj_updateFromString(void * jarg1, char * jarg2) {
+  int jresult ;
+  labelObj *arg1 = (labelObj *) 0 ;
+  char *arg2 = (char *) 0 ;
+  int result;
+  
+  arg1 = (labelObj *)jarg1; 
+  arg2 = (char *)jarg2; 
+  {
+    errorObj *ms_error;
+    result = (int)labelObj_updateFromString(arg1,arg2);
+    ms_error = msGetErrorObj();
+    if (ms_error != NULL && ms_error->code != MS_NOERR) {
+      if (ms_error->code != MS_NOTFOUND && ms_error->code != -1) {
+        char* msg = msGetErrorString(";"); 
+        if (msg) {
+          SWIG_CSharpException(SWIG_SystemError, msg);
+          free(msg);
+        }
+        else SWIG_CSharpException(SWIG_SystemError, "MapScript unknown error");
+        msResetErrorList();
+        return 0;
+      }
+      msResetErrorList();
+    }
+  }
+  jresult = result; 
+  return jresult;
+}
+
+
+SWIGEXPORT int SWIGSTDCALL CSharp_labelObj_removeBinding(void * jarg1, int jarg2) {
+  int jresult ;
+  labelObj *arg1 = (labelObj *) 0 ;
+  int arg2 ;
+  int result;
+  
+  arg1 = (labelObj *)jarg1; 
+  arg2 = (int)jarg2; 
   {
     errorObj *ms_error;
     result = (int)labelObj_removeBinding(arg1,arg2);
@@ -7355,17 +7800,17 @@ SWIGEXPORT int SWIGSTDCALL CSharp_labelObj_setBinding(void * jarg1, int jarg2, c
 }
 
 
-SWIGEXPORT void * SWIGSTDCALL CSharp_labelObj_getStyle(void * jarg1, int jarg2) {
-  void * jresult ;
+SWIGEXPORT int SWIGSTDCALL CSharp_labelObj_setExpression(void * jarg1, char * jarg2) {
+  int jresult ;
   labelObj *arg1 = (labelObj *) 0 ;
-  int arg2 ;
-  styleObj *result = 0 ;
+  char *arg2 = (char *) 0 ;
+  int result;
   
   arg1 = (labelObj *)jarg1; 
-  arg2 = (int)jarg2; 
+  arg2 = (char *)jarg2; 
   {
     errorObj *ms_error;
-    result = (styleObj *)labelObj_getStyle(arg1,arg2);
+    result = (int)labelObj_setExpression(arg1,arg2);
     ms_error = msGetErrorObj();
     if (ms_error != NULL && ms_error->code != MS_NOERR) {
       if (ms_error->code != MS_NOTFOUND && ms_error->code != -1) {
@@ -7381,24 +7826,52 @@ SWIGEXPORT void * SWIGSTDCALL CSharp_labelObj_getStyle(void * jarg1, int jarg2)
       msResetErrorList();
     }
   }
-  jresult = (void *)result; 
+  jresult = result; 
   return jresult;
 }
 
 
-SWIGEXPORT int SWIGSTDCALL CSharp_labelObj_insertStyle(void * jarg1, void * jarg2, int jarg3) {
+SWIGEXPORT char * SWIGSTDCALL CSharp_labelObj_getExpressionString(void * jarg1) {
+  char * jresult ;
+  labelObj *arg1 = (labelObj *) 0 ;
+  char *result = 0 ;
+  
+  arg1 = (labelObj *)jarg1; 
+  {
+    errorObj *ms_error;
+    result = (char *)labelObj_getExpressionString(arg1);
+    ms_error = msGetErrorObj();
+    if (ms_error != NULL && ms_error->code != MS_NOERR) {
+      if (ms_error->code != MS_NOTFOUND && ms_error->code != -1) {
+        char* msg = msGetErrorString(";"); 
+        if (msg) {
+          SWIG_CSharpException(SWIG_SystemError, msg);
+          free(msg);
+        }
+        else SWIG_CSharpException(SWIG_SystemError, "MapScript unknown error");
+        msResetErrorList();
+        return 0;
+      }
+      msResetErrorList();
+    }
+  }
+  jresult = SWIG_csharp_string_callback((const char *)result); 
+  free(result);
+  return jresult;
+}
+
+
+SWIGEXPORT int SWIGSTDCALL CSharp_labelObj_setText(void * jarg1, char * jarg2) {
   int jresult ;
   labelObj *arg1 = (labelObj *) 0 ;
-  styleObj *arg2 = (styleObj *) 0 ;
-  int arg3 = (int) -1 ;
+  char *arg2 = (char *) 0 ;
   int result;
   
   arg1 = (labelObj *)jarg1; 
-  arg2 = (styleObj *)jarg2; 
-  arg3 = (int)jarg3; 
+  arg2 = (char *)jarg2; 
   {
     errorObj *ms_error;
-    result = (int)labelObj_insertStyle(arg1,arg2,arg3);
+    result = (int)labelObj_setText(arg1,arg2);
     ms_error = msGetErrorObj();
     if (ms_error != NULL && ms_error->code != MS_NOERR) {
       if (ms_error->code != MS_NOTFOUND && ms_error->code != -1) {
@@ -7419,7 +7892,37 @@ SWIGEXPORT int SWIGSTDCALL CSharp_labelObj_insertStyle(void * jarg1, void * jarg
 }
 
 
-SWIGEXPORT void * SWIGSTDCALL CSharp_labelObj_removeStyle(void * jarg1, int jarg2) {
+SWIGEXPORT char * SWIGSTDCALL CSharp_labelObj_getTextString(void * jarg1) {
+  char * jresult ;
+  labelObj *arg1 = (labelObj *) 0 ;
+  char *result = 0 ;
+  
+  arg1 = (labelObj *)jarg1; 
+  {
+    errorObj *ms_error;
+    result = (char *)labelObj_getTextString(arg1);
+    ms_error = msGetErrorObj();
+    if (ms_error != NULL && ms_error->code != MS_NOERR) {
+      if (ms_error->code != MS_NOTFOUND && ms_error->code != -1) {
+        char* msg = msGetErrorString(";"); 
+        if (msg) {
+          SWIG_CSharpException(SWIG_SystemError, msg);
+          free(msg);
+        }
+        else SWIG_CSharpException(SWIG_SystemError, "MapScript unknown error");
+        msResetErrorList();
+        return 0;
+      }
+      msResetErrorList();
+    }
+  }
+  jresult = SWIG_csharp_string_callback((const char *)result); 
+  free(result);
+  return jresult;
+}
+
+
+SWIGEXPORT void * SWIGSTDCALL CSharp_labelObj_getStyle(void * jarg1, int jarg2) {
   void * jresult ;
   labelObj *arg1 = (labelObj *) 0 ;
   int arg2 ;
@@ -7429,7 +7932,7 @@ SWIGEXPORT void * SWIGSTDCALL CSharp_labelObj_removeStyle(void * jarg1, int jarg
   arg2 = (int)jarg2; 
   {
     errorObj *ms_error;
-    result = (styleObj *)labelObj_removeStyle(arg1,arg2);
+    result = (styleObj *)labelObj_getStyle(arg1,arg2);
     ms_error = msGetErrorObj();
     if (ms_error != NULL && ms_error->code != MS_NOERR) {
       if (ms_error->code != MS_NOTFOUND && ms_error->code != -1) {
@@ -7450,17 +7953,19 @@ SWIGEXPORT void * SWIGSTDCALL CSharp_labelObj_removeStyle(void * jarg1, int jarg
 }
 
 
-SWIGEXPORT int SWIGSTDCALL CSharp_labelObj_moveStyleUp(void * jarg1, int jarg2) {
+SWIGEXPORT int SWIGSTDCALL CSharp_labelObj_insertStyle(void * jarg1, void * jarg2, int jarg3) {
   int jresult ;
   labelObj *arg1 = (labelObj *) 0 ;
-  int arg2 ;
+  styleObj *arg2 = (styleObj *) 0 ;
+  int arg3 = (int) -1 ;
   int result;
   
   arg1 = (labelObj *)jarg1; 
-  arg2 = (int)jarg2; 
+  arg2 = (styleObj *)jarg2; 
+  arg3 = (int)jarg3; 
   {
     errorObj *ms_error;
-    result = (int)labelObj_moveStyleUp(arg1,arg2);
+    result = (int)labelObj_insertStyle(arg1,arg2,arg3);
     ms_error = msGetErrorObj();
     if (ms_error != NULL && ms_error->code != MS_NOERR) {
       if (ms_error->code != MS_NOTFOUND && ms_error->code != -1) {
@@ -7481,17 +7986,17 @@ SWIGEXPORT int SWIGSTDCALL CSharp_labelObj_moveStyleUp(void * jarg1, int jarg2)
 }
 
 
-SWIGEXPORT int SWIGSTDCALL CSharp_labelObj_moveStyleDown(void * jarg1, int jarg2) {
-  int jresult ;
+SWIGEXPORT void * SWIGSTDCALL CSharp_labelObj_removeStyle(void * jarg1, int jarg2) {
+  void * jresult ;
   labelObj *arg1 = (labelObj *) 0 ;
   int arg2 ;
-  int result;
+  styleObj *result = 0 ;
   
   arg1 = (labelObj *)jarg1; 
   arg2 = (int)jarg2; 
   {
     errorObj *ms_error;
-    result = (int)labelObj_moveStyleDown(arg1,arg2);
+    result = (styleObj *)labelObj_removeStyle(arg1,arg2);
     ms_error = msGetErrorObj();
     if (ms_error != NULL && ms_error->code != MS_NOERR) {
       if (ms_error->code != MS_NOTFOUND && ms_error->code != -1) {
@@ -7507,18 +8012,22 @@ SWIGEXPORT int SWIGSTDCALL CSharp_labelObj_moveStyleDown(void * jarg1, int jarg2
       msResetErrorList();
     }
   }
-  jresult = result; 
+  jresult = (void *)result; 
   return jresult;
 }
 
 
-SWIGEXPORT void * SWIGSTDCALL CSharp_new_labelObj() {
-  void * jresult ;
-  labelObj *result = 0 ;
+SWIGEXPORT int SWIGSTDCALL CSharp_labelObj_moveStyleUp(void * jarg1, int jarg2) {
+  int jresult ;
+  labelObj *arg1 = (labelObj *) 0 ;
+  int arg2 ;
+  int result;
   
+  arg1 = (labelObj *)jarg1; 
+  arg2 = (int)jarg2; 
   {
     errorObj *ms_error;
-    result = (labelObj *)calloc(1, sizeof(labelObj));
+    result = (int)labelObj_moveStyleUp(arg1,arg2);
     ms_error = msGetErrorObj();
     if (ms_error != NULL && ms_error->code != MS_NOERR) {
       if (ms_error->code != MS_NOTFOUND && ms_error->code != -1) {
@@ -7534,18 +8043,22 @@ SWIGEXPORT void * SWIGSTDCALL CSharp_new_labelObj() {
       msResetErrorList();
     }
   }
-  jresult = (void *)result; 
+  jresult = result; 
   return jresult;
 }
 
 
-SWIGEXPORT void SWIGSTDCALL CSharp_delete_labelObj(void * jarg1) {
+SWIGEXPORT int SWIGSTDCALL CSharp_labelObj_moveStyleDown(void * jarg1, int jarg2) {
+  int jresult ;
   labelObj *arg1 = (labelObj *) 0 ;
+  int arg2 ;
+  int result;
   
   arg1 = (labelObj *)jarg1; 
+  arg2 = (int)jarg2; 
   {
     errorObj *ms_error;
-    free((char *) arg1);
+    result = (int)labelObj_moveStyleDown(arg1,arg2);
     ms_error = msGetErrorObj();
     if (ms_error != NULL && ms_error->code != MS_NOERR) {
       if (ms_error->code != MS_NOTFOUND && ms_error->code != -1) {
@@ -7556,11 +8069,13 @@ SWIGEXPORT void SWIGSTDCALL CSharp_delete_labelObj(void * jarg1) {
         }
         else SWIG_CSharpException(SWIG_SystemError, "MapScript unknown error");
         msResetErrorList();
-        return ;
+        return 0;
       }
       msResetErrorList();
     }
   }
+  jresult = result; 
+  return jresult;
 }
 
 
@@ -7586,16 +8101,6 @@ SWIGEXPORT int SWIGSTDCALL CSharp_classObj_status_get(void * jarg1) {
 }
 
 
-SWIGEXPORT void SWIGSTDCALL CSharp_classObj_numstyles_set(void * jarg1, int jarg2) {
-  classObj *arg1 = (classObj *) 0 ;
-  int arg2 ;
-  
-  arg1 = (classObj *)jarg1; 
-  arg2 = (int)jarg2; 
-  if (arg1) (arg1)->numstyles = arg2;
-}
-
-
 SWIGEXPORT int SWIGSTDCALL CSharp_classObj_numstyles_get(void * jarg1) {
   int jresult ;
   classObj *arg1 = (classObj *) 0 ;
@@ -7608,14 +8113,24 @@ SWIGEXPORT int SWIGSTDCALL CSharp_classObj_numstyles_get(void * jarg1) {
 }
 
 
-SWIGEXPORT void * SWIGSTDCALL CSharp_classObj_label_get(void * jarg1) {
-  void * jresult ;
+SWIGEXPORT void SWIGSTDCALL CSharp_classObj_numlabels_set(void * jarg1, int jarg2) {
   classObj *arg1 = (classObj *) 0 ;
-  labelObj *result = 0 ;
+  int arg2 ;
   
   arg1 = (classObj *)jarg1; 
-  result = (labelObj *)& ((arg1)->label);
-  jresult = (void *)result; 
+  arg2 = (int)jarg2; 
+  if (arg1) (arg1)->numlabels = arg2;
+}
+
+
+SWIGEXPORT int SWIGSTDCALL CSharp_classObj_numlabels_get(void * jarg1) {
+  int jresult ;
+  classObj *arg1 = (classObj *) 0 ;
+  int result;
+  
+  arg1 = (classObj *)jarg1; 
+  result = (int) ((arg1)->numlabels);
+  jresult = result; 
   return jresult;
 }
 
@@ -7837,10 +8352,10 @@ SWIGEXPORT int SWIGSTDCALL CSharp_classObj_refcount_get(void * jarg1) {
 SWIGEXPORT void * SWIGSTDCALL CSharp_classObj_layer_get(void * jarg1) {
   void * jresult ;
   classObj *arg1 = (classObj *) 0 ;
-  struct layer_obj *result = 0 ;
+  struct layerObj *result = 0 ;
   
   arg1 = (classObj *)jarg1; 
-  result = (struct layer_obj *) ((arg1)->layer);
+  result = (struct layerObj *) ((arg1)->layer);
   jresult = (void *)result; 
   return jresult;
 }
@@ -7928,6 +8443,28 @@ SWIGEXPORT char * SWIGSTDCALL CSharp_classObj_group_get(void * jarg1) {
 }
 
 
+SWIGEXPORT void SWIGSTDCALL CSharp_classObj_leader_set(void * jarg1, void * jarg2) {
+  classObj *arg1 = (classObj *) 0 ;
+  labelLeaderObj *arg2 = (labelLeaderObj *) 0 ;
+  
+  arg1 = (classObj *)jarg1; 
+  arg2 = (labelLeaderObj *)jarg2; 
+  if (arg1) (arg1)->leader = *arg2;
+}
+
+
+SWIGEXPORT void * SWIGSTDCALL CSharp_classObj_leader_get(void * jarg1) {
+  void * jresult ;
+  classObj *arg1 = (classObj *) 0 ;
+  labelLeaderObj *result = 0 ;
+  
+  arg1 = (classObj *)jarg1; 
+  result = (labelLeaderObj *)& ((arg1)->leader);
+  jresult = (void *)result; 
+  return jresult;
+}
+
+
 SWIGEXPORT void * SWIGSTDCALL CSharp_new_classObj(void * jarg1) {
   void * jresult ;
   layerObj *arg1 = (layerObj *) NULL ;
@@ -8368,17 +8905,17 @@ SWIGEXPORT void * SWIGSTDCALL CSharp_classObj_createLegendIcon(void * jarg1, voi
 }
 
 
-SWIGEXPORT void * SWIGSTDCALL CSharp_classObj_getStyle(void * jarg1, int jarg2) {
+SWIGEXPORT void * SWIGSTDCALL CSharp_classObj_getLabel(void * jarg1, int jarg2) {
   void * jresult ;
   classObj *arg1 = (classObj *) 0 ;
   int arg2 ;
-  styleObj *result = 0 ;
+  labelObj *result = 0 ;
   
   arg1 = (classObj *)jarg1; 
   arg2 = (int)jarg2; 
   {
     errorObj *ms_error;
-    result = (styleObj *)classObj_getStyle(arg1,arg2);
+    result = (labelObj *)classObj_getLabel(arg1,arg2);
     ms_error = msGetErrorObj();
     if (ms_error != NULL && ms_error->code != MS_NOERR) {
       if (ms_error->code != MS_NOTFOUND && ms_error->code != -1) {
@@ -8399,19 +8936,17 @@ SWIGEXPORT void * SWIGSTDCALL CSharp_classObj_getStyle(void * jarg1, int jarg2)
 }
 
 
-SWIGEXPORT int SWIGSTDCALL CSharp_classObj_insertStyle(void * jarg1, void * jarg2, int jarg3) {
+SWIGEXPORT int SWIGSTDCALL CSharp_classObj_addLabel(void * jarg1, void * jarg2) {
   int jresult ;
   classObj *arg1 = (classObj *) 0 ;
-  styleObj *arg2 = (styleObj *) 0 ;
-  int arg3 = (int) -1 ;
+  labelObj *arg2 = (labelObj *) 0 ;
   int result;
   
   arg1 = (classObj *)jarg1; 
-  arg2 = (styleObj *)jarg2; 
-  arg3 = (int)jarg3; 
+  arg2 = (labelObj *)jarg2; 
   {
     errorObj *ms_error;
-    result = (int)classObj_insertStyle(arg1,arg2,arg3);
+    result = (int)classObj_addLabel(arg1,arg2);
     ms_error = msGetErrorObj();
     if (ms_error != NULL && ms_error->code != MS_NOERR) {
       if (ms_error->code != MS_NOTFOUND && ms_error->code != -1) {
@@ -8432,17 +8967,17 @@ SWIGEXPORT int SWIGSTDCALL CSharp_classObj_insertStyle(void * jarg1, void * jarg
 }
 
 
-SWIGEXPORT void * SWIGSTDCALL CSharp_classObj_removeStyle(void * jarg1, int jarg2) {
+SWIGEXPORT void * SWIGSTDCALL CSharp_classObj_removeLabel(void * jarg1, int jarg2) {
   void * jresult ;
   classObj *arg1 = (classObj *) 0 ;
   int arg2 ;
-  styleObj *result = 0 ;
+  labelObj *result = 0 ;
   
   arg1 = (classObj *)jarg1; 
   arg2 = (int)jarg2; 
   {
     errorObj *ms_error;
-    result = (styleObj *)classObj_removeStyle(arg1,arg2);
+    result = (labelObj *)classObj_removeLabel(arg1,arg2);
     ms_error = msGetErrorObj();
     if (ms_error != NULL && ms_error->code != MS_NOERR) {
       if (ms_error->code != MS_NOTFOUND && ms_error->code != -1) {
@@ -8463,17 +8998,17 @@ SWIGEXPORT void * SWIGSTDCALL CSharp_classObj_removeStyle(void * jarg1, int jarg
 }
 
 
-SWIGEXPORT int SWIGSTDCALL CSharp_classObj_moveStyleUp(void * jarg1, int jarg2) {
-  int jresult ;
+SWIGEXPORT void * SWIGSTDCALL CSharp_classObj_getStyle(void * jarg1, int jarg2) {
+  void * jresult ;
   classObj *arg1 = (classObj *) 0 ;
   int arg2 ;
-  int result;
+  styleObj *result = 0 ;
   
   arg1 = (classObj *)jarg1; 
   arg2 = (int)jarg2; 
   {
     errorObj *ms_error;
-    result = (int)classObj_moveStyleUp(arg1,arg2);
+    result = (styleObj *)classObj_getStyle(arg1,arg2);
     ms_error = msGetErrorObj();
     if (ms_error != NULL && ms_error->code != MS_NOERR) {
       if (ms_error->code != MS_NOTFOUND && ms_error->code != -1) {
@@ -8489,22 +9024,24 @@ SWIGEXPORT int SWIGSTDCALL CSharp_classObj_moveStyleUp(void * jarg1, int jarg2)
       msResetErrorList();
     }
   }
-  jresult = result; 
+  jresult = (void *)result; 
   return jresult;
 }
 
 
-SWIGEXPORT int SWIGSTDCALL CSharp_classObj_moveStyleDown(void * jarg1, int jarg2) {
+SWIGEXPORT int SWIGSTDCALL CSharp_classObj_insertStyle(void * jarg1, void * jarg2, int jarg3) {
   int jresult ;
   classObj *arg1 = (classObj *) 0 ;
-  int arg2 ;
+  styleObj *arg2 = (styleObj *) 0 ;
+  int arg3 = (int) -1 ;
   int result;
   
   arg1 = (classObj *)jarg1; 
-  arg2 = (int)jarg2; 
+  arg2 = (styleObj *)jarg2; 
+  arg3 = (int)jarg3; 
   {
     errorObj *ms_error;
-    result = (int)classObj_moveStyleDown(arg1,arg2);
+    result = (int)classObj_insertStyle(arg1,arg2,arg3);
     ms_error = msGetErrorObj();
     if (ms_error != NULL && ms_error->code != MS_NOERR) {
       if (ms_error->code != MS_NOTFOUND && ms_error->code != -1) {
@@ -8525,14 +9062,95 @@ SWIGEXPORT int SWIGSTDCALL CSharp_classObj_moveStyleDown(void * jarg1, int jarg2
 }
 
 
-SWIGEXPORT char * SWIGSTDCALL CSharp_labelCacheMemberObj_text_get(void * jarg1) {
-  char * jresult ;
-  labelCacheMemberObj *arg1 = (labelCacheMemberObj *) 0 ;
-  char *result = 0 ;
+SWIGEXPORT void * SWIGSTDCALL CSharp_classObj_removeStyle(void * jarg1, int jarg2) {
+  void * jresult ;
+  classObj *arg1 = (classObj *) 0 ;
+  int arg2 ;
+  styleObj *result = 0 ;
   
-  arg1 = (labelCacheMemberObj *)jarg1; 
-  result = (char *) ((arg1)->text);
-  jresult = SWIG_csharp_string_callback((const char *)result); 
+  arg1 = (classObj *)jarg1; 
+  arg2 = (int)jarg2; 
+  {
+    errorObj *ms_error;
+    result = (styleObj *)classObj_removeStyle(arg1,arg2);
+    ms_error = msGetErrorObj();
+    if (ms_error != NULL && ms_error->code != MS_NOERR) {
+      if (ms_error->code != MS_NOTFOUND && ms_error->code != -1) {
+        char* msg = msGetErrorString(";"); 
+        if (msg) {
+          SWIG_CSharpException(SWIG_SystemError, msg);
+          free(msg);
+        }
+        else SWIG_CSharpException(SWIG_SystemError, "MapScript unknown error");
+        msResetErrorList();
+        return 0;
+      }
+      msResetErrorList();
+    }
+  }
+  jresult = (void *)result; 
+  return jresult;
+}
+
+
+SWIGEXPORT int SWIGSTDCALL CSharp_classObj_moveStyleUp(void * jarg1, int jarg2) {
+  int jresult ;
+  classObj *arg1 = (classObj *) 0 ;
+  int arg2 ;
+  int result;
+  
+  arg1 = (classObj *)jarg1; 
+  arg2 = (int)jarg2; 
+  {
+    errorObj *ms_error;
+    result = (int)classObj_moveStyleUp(arg1,arg2);
+    ms_error = msGetErrorObj();
+    if (ms_error != NULL && ms_error->code != MS_NOERR) {
+      if (ms_error->code != MS_NOTFOUND && ms_error->code != -1) {
+        char* msg = msGetErrorString(";"); 
+        if (msg) {
+          SWIG_CSharpException(SWIG_SystemError, msg);
+          free(msg);
+        }
+        else SWIG_CSharpException(SWIG_SystemError, "MapScript unknown error");
+        msResetErrorList();
+        return 0;
+      }
+      msResetErrorList();
+    }
+  }
+  jresult = result; 
+  return jresult;
+}
+
+
+SWIGEXPORT int SWIGSTDCALL CSharp_classObj_moveStyleDown(void * jarg1, int jarg2) {
+  int jresult ;
+  classObj *arg1 = (classObj *) 0 ;
+  int arg2 ;
+  int result;
+  
+  arg1 = (classObj *)jarg1; 
+  arg2 = (int)jarg2; 
+  {
+    errorObj *ms_error;
+    result = (int)classObj_moveStyleDown(arg1,arg2);
+    ms_error = msGetErrorObj();
+    if (ms_error != NULL && ms_error->code != MS_NOERR) {
+      if (ms_error->code != MS_NOTFOUND && ms_error->code != -1) {
+        char* msg = msGetErrorString(";"); 
+        if (msg) {
+          SWIG_CSharpException(SWIG_SystemError, msg);
+          free(msg);
+        }
+        else SWIG_CSharpException(SWIG_SystemError, "MapScript unknown error");
+        msResetErrorList();
+        return 0;
+      }
+      msResetErrorList();
+    }
+  }
+  jresult = result; 
   return jresult;
 }
 
@@ -8573,61 +9191,49 @@ SWIGEXPORT int SWIGSTDCALL CSharp_labelCacheMemberObj_numstyles_get(void * jarg1
 }
 
 
-SWIGEXPORT void * SWIGSTDCALL CSharp_labelCacheMemberObj_label_get(void * jarg1) {
+SWIGEXPORT void * SWIGSTDCALL CSharp_labelCacheMemberObj_labels_get(void * jarg1) {
   void * jresult ;
   labelCacheMemberObj *arg1 = (labelCacheMemberObj *) 0 ;
   labelObj *result = 0 ;
   
   arg1 = (labelCacheMemberObj *)jarg1; 
-  result = (labelObj *)& ((arg1)->label);
+  result = (labelObj *) ((arg1)->labels);
   jresult = (void *)result; 
   return jresult;
 }
 
 
-SWIGEXPORT int SWIGSTDCALL CSharp_labelCacheMemberObj_layerindex_get(void * jarg1) {
-  int jresult ;
-  labelCacheMemberObj *arg1 = (labelCacheMemberObj *) 0 ;
-  int result;
-  
-  arg1 = (labelCacheMemberObj *)jarg1; 
-  result = (int) ((arg1)->layerindex);
-  jresult = result; 
-  return jresult;
-}
-
-
-SWIGEXPORT int SWIGSTDCALL CSharp_labelCacheMemberObj_classindex_get(void * jarg1) {
+SWIGEXPORT int SWIGSTDCALL CSharp_labelCacheMemberObj_numlabels_get(void * jarg1) {
   int jresult ;
   labelCacheMemberObj *arg1 = (labelCacheMemberObj *) 0 ;
   int result;
   
   arg1 = (labelCacheMemberObj *)jarg1; 
-  result = (int) ((arg1)->classindex);
+  result = (int) ((arg1)->numlabels);
   jresult = result; 
   return jresult;
 }
 
 
-SWIGEXPORT int SWIGSTDCALL CSharp_labelCacheMemberObj_tileindex_get(void * jarg1) {
+SWIGEXPORT int SWIGSTDCALL CSharp_labelCacheMemberObj_layerindex_get(void * jarg1) {
   int jresult ;
   labelCacheMemberObj *arg1 = (labelCacheMemberObj *) 0 ;
   int result;
   
   arg1 = (labelCacheMemberObj *)jarg1; 
-  result = (int) ((arg1)->tileindex);
+  result = (int) ((arg1)->layerindex);
   jresult = result; 
   return jresult;
 }
 
 
-SWIGEXPORT int SWIGSTDCALL CSharp_labelCacheMemberObj_shapeindex_get(void * jarg1) {
+SWIGEXPORT int SWIGSTDCALL CSharp_labelCacheMemberObj_classindex_get(void * jarg1) {
   int jresult ;
   labelCacheMemberObj *arg1 = (labelCacheMemberObj *) 0 ;
   int result;
   
   arg1 = (labelCacheMemberObj *)jarg1; 
-  result = (int) ((arg1)->shapeindex);
+  result = (int) ((arg1)->classindex);
   jresult = result; 
   return jresult;
 }
@@ -8693,6 +9299,30 @@ SWIGEXPORT int SWIGSTDCALL CSharp_labelCacheMemberObj_markerid_get(void * jarg1)
 }
 
 
+SWIGEXPORT void * SWIGSTDCALL CSharp_labelCacheMemberObj_leaderline_get(void * jarg1) {
+  void * jresult ;
+  labelCacheMemberObj *arg1 = (labelCacheMemberObj *) 0 ;
+  lineObj *result = 0 ;
+  
+  arg1 = (labelCacheMemberObj *)jarg1; 
+  result = (lineObj *) ((arg1)->leaderline);
+  jresult = (void *)result; 
+  return jresult;
+}
+
+
+SWIGEXPORT void * SWIGSTDCALL CSharp_labelCacheMemberObj_leaderbbox_get(void * jarg1) {
+  void * jresult ;
+  labelCacheMemberObj *arg1 = (labelCacheMemberObj *) 0 ;
+  rectObj *result = 0 ;
+  
+  arg1 = (labelCacheMemberObj *)jarg1; 
+  result = (rectObj *) ((arg1)->leaderbbox);
+  jresult = (void *)result; 
+  return jresult;
+}
+
+
 SWIGEXPORT void * SWIGSTDCALL CSharp_new_labelCacheMemberObj() {
   void * jresult ;
   labelCacheMemberObj *result = 0 ;
@@ -8969,6 +9599,18 @@ SWIGEXPORT int SWIGSTDCALL CSharp_labelCacheObj_numlabels_get(void * jarg1) {
 }
 
 
+SWIGEXPORT int SWIGSTDCALL CSharp_labelCacheObj_gutter_get(void * jarg1) {
+  int jresult ;
+  labelCacheObj *arg1 = (labelCacheObj *) 0 ;
+  int result;
+  
+  arg1 = (labelCacheObj *)jarg1; 
+  result = (int) ((arg1)->gutter);
+  jresult = result; 
+  return jresult;
+}
+
+
 SWIGEXPORT void SWIGSTDCALL CSharp_labelCacheObj_freeCache(void * jarg1) {
   labelCacheObj *arg1 = (labelCacheObj *) 0 ;
   
@@ -9876,10 +10518,10 @@ SWIGEXPORT int SWIGSTDCALL CSharp_referenceMapObj_maxboxsize_get(void * jarg1) {
 SWIGEXPORT void * SWIGSTDCALL CSharp_referenceMapObj_map_get(void * jarg1) {
   void * jresult ;
   referenceMapObj *arg1 = (referenceMapObj *) 0 ;
-  struct map_obj *result = 0 ;
+  struct mapObj *result = 0 ;
   
   arg1 = (referenceMapObj *)jarg1; 
-  result = (struct map_obj *) ((arg1)->map);
+  result = (struct mapObj *) ((arg1)->map);
   jresult = (void *)result; 
   return jresult;
 }
@@ -10646,10 +11288,10 @@ SWIGEXPORT char * SWIGSTDCALL CSharp_legendObj_template_get(void * jarg1) {
 SWIGEXPORT void * SWIGSTDCALL CSharp_legendObj_map_get(void * jarg1) {
   void * jresult ;
   legendObj *arg1 = (legendObj *) 0 ;
-  struct map_obj *result = 0 ;
+  struct mapObj *result = 0 ;
   
   arg1 = (legendObj *)jarg1; 
-  result = (struct map_obj *) ((arg1)->map);
+  result = (struct mapObj *) ((arg1)->map);
   jresult = (void *)result; 
   return jresult;
 }
@@ -10738,100 +11380,333 @@ SWIGEXPORT void SWIGSTDCALL CSharp_delete_legendObj(void * jarg1) {
 }
 
 
-SWIGEXPORT void SWIGSTDCALL CSharp_layerObj_classitem_set(void * jarg1, char * jarg2) {
-  layerObj *arg1 = (layerObj *) 0 ;
-  char *arg2 = (char *) 0 ;
+SWIGEXPORT void SWIGSTDCALL CSharp_imageObj_getBytes(void * jarg1, SWIG_CSharpByteArrayHelperCallback jarg2) {
+  imageObj *arg1 = (imageObj *) 0 ;
+  SWIG_CSharpByteArrayHelperCallback arg2 ;
   
-  arg1 = (layerObj *)jarg1; 
-  arg2 = (char *)jarg2; 
+  arg1 = (imageObj *)jarg1; 
+  arg2 = (SWIG_CSharpByteArrayHelperCallback)jarg2; 
   {
-    if (arg1->classitem) free((char*)arg1->classitem);
-    if (arg2) {
-      arg1->classitem = (char *) malloc(strlen(arg2)+1);
-      strcpy((char*)arg1->classitem,arg2);
-    } else {
-      arg1->classitem = 0;
+    errorObj *ms_error;
+    imageObj_getBytes(arg1,arg2);
+    ms_error = msGetErrorObj();
+    if (ms_error != NULL && ms_error->code != MS_NOERR) {
+      if (ms_error->code != MS_NOTFOUND && ms_error->code != -1) {
+        char* msg = msGetErrorString(";"); 
+        if (msg) {
+          SWIG_CSharpException(SWIG_SystemError, msg);
+          free(msg);
+        }
+        else SWIG_CSharpException(SWIG_SystemError, "MapScript unknown error");
+        msResetErrorList();
+        return ;
+      }
+      msResetErrorList();
     }
   }
 }
 
 
-SWIGEXPORT char * SWIGSTDCALL CSharp_layerObj_classitem_get(void * jarg1) {
-  char * jresult ;
-  layerObj *arg1 = (layerObj *) 0 ;
-  char *result = 0 ;
+SWIGEXPORT int SWIGSTDCALL CSharp_imageObj_width_get(void * jarg1) {
+  int jresult ;
+  imageObj *arg1 = (imageObj *) 0 ;
+  int result;
   
-  arg1 = (layerObj *)jarg1; 
-  result = (char *) ((arg1)->classitem);
-  jresult = SWIG_csharp_string_callback((const char *)result); 
+  arg1 = (imageObj *)jarg1; 
+  result = (int) ((arg1)->width);
+  jresult = result; 
   return jresult;
 }
 
 
-SWIGEXPORT int SWIGSTDCALL CSharp_layerObj_refcount_get(void * jarg1) {
+SWIGEXPORT int SWIGSTDCALL CSharp_imageObj_height_get(void * jarg1) {
   int jresult ;
-  layerObj *arg1 = (layerObj *) 0 ;
+  imageObj *arg1 = (imageObj *) 0 ;
   int result;
   
-  arg1 = (layerObj *)jarg1; 
-  result = (int) ((arg1)->refcount);
+  arg1 = (imageObj *)jarg1; 
+  result = (int) ((arg1)->height);
   jresult = result; 
   return jresult;
 }
 
 
-SWIGEXPORT int SWIGSTDCALL CSharp_layerObj_numclasses_get(void * jarg1) {
-  int jresult ;
-  layerObj *arg1 = (layerObj *) 0 ;
-  int result;
+SWIGEXPORT double SWIGSTDCALL CSharp_imageObj_resolution_get(void * jarg1) {
+  double jresult ;
+  imageObj *arg1 = (imageObj *) 0 ;
+  double result;
   
-  arg1 = (layerObj *)jarg1; 
-  result = (int) ((arg1)->numclasses);
+  arg1 = (imageObj *)jarg1; 
+  result = (double) ((arg1)->resolution);
   jresult = result; 
   return jresult;
 }
 
 
-SWIGEXPORT int SWIGSTDCALL CSharp_layerObj_maxclasses_get(void * jarg1) {
-  int jresult ;
-  layerObj *arg1 = (layerObj *) 0 ;
-  int result;
+SWIGEXPORT double SWIGSTDCALL CSharp_imageObj_resolutionfactor_get(void * jarg1) {
+  double jresult ;
+  imageObj *arg1 = (imageObj *) 0 ;
+  double result;
   
-  arg1 = (layerObj *)jarg1; 
-  result = (int) ((arg1)->maxclasses);
+  arg1 = (imageObj *)jarg1; 
+  result = (double) ((arg1)->resolutionfactor);
   jresult = result; 
   return jresult;
 }
 
 
-SWIGEXPORT int SWIGSTDCALL CSharp_layerObj_index_get(void * jarg1) {
-  int jresult ;
-  layerObj *arg1 = (layerObj *) 0 ;
-  int result;
+SWIGEXPORT char * SWIGSTDCALL CSharp_imageObj_imagepath_get(void * jarg1) {
+  char * jresult ;
+  imageObj *arg1 = (imageObj *) 0 ;
+  char *result = 0 ;
   
-  arg1 = (layerObj *)jarg1; 
-  result = (int) ((arg1)->index);
-  jresult = result; 
+  arg1 = (imageObj *)jarg1; 
+  result = (char *) ((arg1)->imagepath);
+  jresult = SWIG_csharp_string_callback((const char *)result); 
   return jresult;
 }
 
 
-SWIGEXPORT void * SWIGSTDCALL CSharp_layerObj_map_get(void * jarg1) {
-  void * jresult ;
-  layerObj *arg1 = (layerObj *) 0 ;
-  struct map_obj *result = 0 ;
+SWIGEXPORT char * SWIGSTDCALL CSharp_imageObj_imageurl_get(void * jarg1) {
+  char * jresult ;
+  imageObj *arg1 = (imageObj *) 0 ;
+  char *result = 0 ;
   
-  arg1 = (layerObj *)jarg1; 
-  result = (struct map_obj *) ((arg1)->map);
-  jresult = (void *)result; 
+  arg1 = (imageObj *)jarg1; 
+  result = (char *) ((arg1)->imageurl);
+  jresult = SWIG_csharp_string_callback((const char *)result); 
   return jresult;
 }
 
 
-SWIGEXPORT void SWIGSTDCALL CSharp_layerObj_header_set(void * jarg1, char * jarg2) {
-  layerObj *arg1 = (layerObj *) 0 ;
-  char *arg2 = (char *) 0 ;
-  
+SWIGEXPORT void * SWIGSTDCALL CSharp_imageObj_format_get(void * jarg1) {
+  void * jresult ;
+  imageObj *arg1 = (imageObj *) 0 ;
+  outputFormatObj *result = 0 ;
+  
+  arg1 = (imageObj *)jarg1; 
+  result = (outputFormatObj *) ((arg1)->format);
+  jresult = (void *)result; 
+  return jresult;
+}
+
+
+SWIGEXPORT void * SWIGSTDCALL CSharp_new_imageObj(int jarg1, int jarg2, void * jarg3, char * jarg4, double jarg5, double jarg6) {
+  void * jresult ;
+  int arg1 ;
+  int arg2 ;
+  outputFormatObj *arg3 = (outputFormatObj *) NULL ;
+  char *arg4 = (char *) NULL ;
+  double arg5 = (double) MS_DEFAULT_RESOLUTION ;
+  double arg6 = (double) MS_DEFAULT_RESOLUTION ;
+  imageObj *result = 0 ;
+  
+  arg1 = (int)jarg1; 
+  arg2 = (int)jarg2; 
+  arg3 = (outputFormatObj *)jarg3; 
+  arg4 = (char *)jarg4; 
+  arg5 = (double)jarg5; 
+  arg6 = (double)jarg6; 
+  {
+    errorObj *ms_error;
+    result = (imageObj *)new_imageObj(arg1,arg2,arg3,(char const *)arg4,arg5,arg6);
+    ms_error = msGetErrorObj();
+    if (ms_error != NULL && ms_error->code != MS_NOERR) {
+      if (ms_error->code != MS_NOTFOUND && ms_error->code != -1) {
+        char* msg = msGetErrorString(";"); 
+        if (msg) {
+          SWIG_CSharpException(SWIG_SystemError, msg);
+          free(msg);
+        }
+        else SWIG_CSharpException(SWIG_SystemError, "MapScript unknown error");
+        msResetErrorList();
+        return 0;
+      }
+      msResetErrorList();
+    }
+  }
+  jresult = (void *)result; 
+  return jresult;
+}
+
+
+SWIGEXPORT void SWIGSTDCALL CSharp_delete_imageObj(void * jarg1) {
+  imageObj *arg1 = (imageObj *) 0 ;
+  
+  arg1 = (imageObj *)jarg1; 
+  {
+    errorObj *ms_error;
+    delete_imageObj(arg1);
+    ms_error = msGetErrorObj();
+    if (ms_error != NULL && ms_error->code != MS_NOERR) {
+      if (ms_error->code != MS_NOTFOUND && ms_error->code != -1) {
+        char* msg = msGetErrorString(";"); 
+        if (msg) {
+          SWIG_CSharpException(SWIG_SystemError, msg);
+          free(msg);
+        }
+        else SWIG_CSharpException(SWIG_SystemError, "MapScript unknown error");
+        msResetErrorList();
+        return ;
+      }
+      msResetErrorList();
+    }
+  }
+}
+
+
+SWIGEXPORT void SWIGSTDCALL CSharp_imageObj_save(void * jarg1, char * jarg2, void * jarg3) {
+  imageObj *arg1 = (imageObj *) 0 ;
+  char *arg2 = (char *) 0 ;
+  mapObj *arg3 = (mapObj *) NULL ;
+  
+  arg1 = (imageObj *)jarg1; 
+  arg2 = (char *)jarg2; 
+  arg3 = (mapObj *)jarg3; 
+  {
+    errorObj *ms_error;
+    imageObj_save(arg1,arg2,arg3);
+    ms_error = msGetErrorObj();
+    if (ms_error != NULL && ms_error->code != MS_NOERR) {
+      if (ms_error->code != MS_NOTFOUND && ms_error->code != -1) {
+        char* msg = msGetErrorString(";"); 
+        if (msg) {
+          SWIG_CSharpException(SWIG_SystemError, msg);
+          free(msg);
+        }
+        else SWIG_CSharpException(SWIG_SystemError, "MapScript unknown error");
+        msResetErrorList();
+        return ;
+      }
+      msResetErrorList();
+    }
+  }
+}
+
+
+SWIGEXPORT int SWIGSTDCALL CSharp_imageObj_getSize(void * jarg1) {
+  int jresult ;
+  imageObj *arg1 = (imageObj *) 0 ;
+  int result;
+  
+  arg1 = (imageObj *)jarg1; 
+  {
+    errorObj *ms_error;
+    result = (int)imageObj_getSize(arg1);
+    ms_error = msGetErrorObj();
+    if (ms_error != NULL && ms_error->code != MS_NOERR) {
+      if (ms_error->code != MS_NOTFOUND && ms_error->code != -1) {
+        char* msg = msGetErrorString(";"); 
+        if (msg) {
+          SWIG_CSharpException(SWIG_SystemError, msg);
+          free(msg);
+        }
+        else SWIG_CSharpException(SWIG_SystemError, "MapScript unknown error");
+        msResetErrorList();
+        return 0;
+      }
+      msResetErrorList();
+    }
+  }
+  jresult = result; 
+  return jresult;
+}
+
+
+SWIGEXPORT void SWIGSTDCALL CSharp_layerObj_classitem_set(void * jarg1, char * jarg2) {
+  layerObj *arg1 = (layerObj *) 0 ;
+  char *arg2 = (char *) 0 ;
+  
+  arg1 = (layerObj *)jarg1; 
+  arg2 = (char *)jarg2; 
+  {
+    if (arg1->classitem) free((char*)arg1->classitem);
+    if (arg2) {
+      arg1->classitem = (char *) malloc(strlen(arg2)+1);
+      strcpy((char*)arg1->classitem,arg2);
+    } else {
+      arg1->classitem = 0;
+    }
+  }
+}
+
+
+SWIGEXPORT char * SWIGSTDCALL CSharp_layerObj_classitem_get(void * jarg1) {
+  char * jresult ;
+  layerObj *arg1 = (layerObj *) 0 ;
+  char *result = 0 ;
+  
+  arg1 = (layerObj *)jarg1; 
+  result = (char *) ((arg1)->classitem);
+  jresult = SWIG_csharp_string_callback((const char *)result); 
+  return jresult;
+}
+
+
+SWIGEXPORT int SWIGSTDCALL CSharp_layerObj_refcount_get(void * jarg1) {
+  int jresult ;
+  layerObj *arg1 = (layerObj *) 0 ;
+  int result;
+  
+  arg1 = (layerObj *)jarg1; 
+  result = (int) ((arg1)->refcount);
+  jresult = result; 
+  return jresult;
+}
+
+
+SWIGEXPORT int SWIGSTDCALL CSharp_layerObj_numclasses_get(void * jarg1) {
+  int jresult ;
+  layerObj *arg1 = (layerObj *) 0 ;
+  int result;
+  
+  arg1 = (layerObj *)jarg1; 
+  result = (int) ((arg1)->numclasses);
+  jresult = result; 
+  return jresult;
+}
+
+
+SWIGEXPORT int SWIGSTDCALL CSharp_layerObj_maxclasses_get(void * jarg1) {
+  int jresult ;
+  layerObj *arg1 = (layerObj *) 0 ;
+  int result;
+  
+  arg1 = (layerObj *)jarg1; 
+  result = (int) ((arg1)->maxclasses);
+  jresult = result; 
+  return jresult;
+}
+
+
+SWIGEXPORT int SWIGSTDCALL CSharp_layerObj_index_get(void * jarg1) {
+  int jresult ;
+  layerObj *arg1 = (layerObj *) 0 ;
+  int result;
+  
+  arg1 = (layerObj *)jarg1; 
+  result = (int) ((arg1)->index);
+  jresult = result; 
+  return jresult;
+}
+
+
+SWIGEXPORT void * SWIGSTDCALL CSharp_layerObj_map_get(void * jarg1) {
+  void * jresult ;
+  layerObj *arg1 = (layerObj *) 0 ;
+  struct mapObj *result = 0 ;
+  
+  arg1 = (layerObj *)jarg1; 
+  result = (struct mapObj *) ((arg1)->map);
+  jresult = (void *)result; 
+  return jresult;
+}
+
+
+SWIGEXPORT void SWIGSTDCALL CSharp_layerObj_header_set(void * jarg1, char * jarg2) {
+  layerObj *arg1 = (layerObj *) 0 ;
+  char *arg2 = (char *) 0 ;
+  
   arg1 = (layerObj *)jarg1; 
   arg2 = (char *)jarg2; 
   {
@@ -11992,6 +12867,36 @@ SWIGEXPORT char * SWIGSTDCALL CSharp_layerObj_classgroup_get(void * jarg1) {
 }
 
 
+SWIGEXPORT void SWIGSTDCALL CSharp_layerObj_mask_set(void * jarg1, char * jarg2) {
+  layerObj *arg1 = (layerObj *) 0 ;
+  char *arg2 = (char *) 0 ;
+  
+  arg1 = (layerObj *)jarg1; 
+  arg2 = (char *)jarg2; 
+  {
+    if (arg1->mask) free((char*)arg1->mask);
+    if (arg2) {
+      arg1->mask = (char *) malloc(strlen(arg2)+1);
+      strcpy((char*)arg1->mask,arg2);
+    } else {
+      arg1->mask = 0;
+    }
+  }
+}
+
+
+SWIGEXPORT char * SWIGSTDCALL CSharp_layerObj_mask_get(void * jarg1) {
+  char * jresult ;
+  layerObj *arg1 = (layerObj *) 0 ;
+  char *result = 0 ;
+  
+  arg1 = (layerObj *)jarg1; 
+  result = (char *) ((arg1)->mask);
+  jresult = SWIG_csharp_string_callback((const char *)result); 
+  return jresult;
+}
+
+
 SWIGEXPORT void * SWIGSTDCALL CSharp_new_layerObj(void * jarg1) {
   void * jresult ;
   mapObj *arg1 = (mapObj *) NULL ;
@@ -12472,16 +13377,49 @@ SWIGEXPORT char * SWIGSTDCALL CSharp_layerObj_getItem(void * jarg1, int jarg2) {
 }
 
 
-SWIGEXPORT int SWIGSTDCALL CSharp_layerObj_draw(void * jarg1, void * jarg2, void * jarg3) {
+SWIGEXPORT int SWIGSTDCALL CSharp_layerObj_setItems(void * jarg1, void * jarg2, int jarg3) {
   int jresult ;
   layerObj *arg1 = (layerObj *) 0 ;
-  mapObj *arg2 = (mapObj *) 0 ;
-  imageObj *arg3 = (imageObj *) 0 ;
+  char **arg2 = (char **) 0 ;
+  int arg3 ;
   int result;
   
   arg1 = (layerObj *)jarg1; 
-  arg2 = (mapObj *)jarg2; 
-  arg3 = (imageObj *)jarg3; 
+  arg2 = (char **)jarg2; 
+  arg3 = (int)jarg3; 
+  {
+    errorObj *ms_error;
+    result = (int)layerObj_setItems(arg1,arg2,arg3);
+    ms_error = msGetErrorObj();
+    if (ms_error != NULL && ms_error->code != MS_NOERR) {
+      if (ms_error->code != MS_NOTFOUND && ms_error->code != -1) {
+        char* msg = msGetErrorString(";"); 
+        if (msg) {
+          SWIG_CSharpException(SWIG_SystemError, msg);
+          free(msg);
+        }
+        else SWIG_CSharpException(SWIG_SystemError, "MapScript unknown error");
+        msResetErrorList();
+        return 0;
+      }
+      msResetErrorList();
+    }
+  }
+  jresult = result; 
+  return jresult;
+}
+
+
+SWIGEXPORT int SWIGSTDCALL CSharp_layerObj_draw(void * jarg1, void * jarg2, void * jarg3) {
+  int jresult ;
+  layerObj *arg1 = (layerObj *) 0 ;
+  mapObj *arg2 = (mapObj *) 0 ;
+  imageObj *arg3 = (imageObj *) 0 ;
+  int result;
+  
+  arg1 = (layerObj *)jarg1; 
+  arg2 = (mapObj *)jarg2; 
+  arg3 = (imageObj *)jarg3; 
   {
     errorObj *ms_error;
     result = (int)layerObj_draw(arg1,arg2,arg3);
@@ -16639,282 +17577,35 @@ SWIGEXPORT int SWIGSTDCALL CSharp_mapObj_zoomPoint(void * jarg1, int jarg2, void
         }
         else SWIG_CSharpException(SWIG_SystemError, "MapScript unknown error");
         msResetErrorList();
-        return 0;
-      }
-      msResetErrorList();
-    }
-  }
-  jresult = result; 
-  return jresult;
-}
-
-
-SWIGEXPORT int SWIGSTDCALL CSharp_mapObj_zoomRectangle(void * jarg1, void * jarg2, int jarg3, int jarg4, void * jarg5, void * jarg6) {
-  int jresult ;
-  mapObj *arg1 = (mapObj *) 0 ;
-  rectObj *arg2 = (rectObj *) 0 ;
-  int arg3 ;
-  int arg4 ;
-  rectObj *arg5 = (rectObj *) 0 ;
-  rectObj *arg6 = (rectObj *) 0 ;
-  int result;
-  
-  arg1 = (mapObj *)jarg1; 
-  arg2 = (rectObj *)jarg2; 
-  arg3 = (int)jarg3; 
-  arg4 = (int)jarg4; 
-  arg5 = (rectObj *)jarg5; 
-  arg6 = (rectObj *)jarg6; 
-  {
-    errorObj *ms_error;
-    result = (int)mapObj_zoomRectangle(arg1,arg2,arg3,arg4,arg5,arg6);
-    ms_error = msGetErrorObj();
-    if (ms_error != NULL && ms_error->code != MS_NOERR) {
-      if (ms_error->code != MS_NOTFOUND && ms_error->code != -1) {
-        char* msg = msGetErrorString(";"); 
-        if (msg) {
-          SWIG_CSharpException(SWIG_SystemError, msg);
-          free(msg);
-        }
-        else SWIG_CSharpException(SWIG_SystemError, "MapScript unknown error");
-        msResetErrorList();
-        return 0;
-      }
-      msResetErrorList();
-    }
-  }
-  jresult = result; 
-  return jresult;
-}
-
-
-SWIGEXPORT int SWIGSTDCALL CSharp_mapObj_zoomScale(void * jarg1, double jarg2, void * jarg3, int jarg4, int jarg5, void * jarg6, void * jarg7) {
-  int jresult ;
-  mapObj *arg1 = (mapObj *) 0 ;
-  double arg2 ;
-  pointObj *arg3 = (pointObj *) 0 ;
-  int arg4 ;
-  int arg5 ;
-  rectObj *arg6 = (rectObj *) 0 ;
-  rectObj *arg7 = (rectObj *) 0 ;
-  int result;
-  
-  arg1 = (mapObj *)jarg1; 
-  arg2 = (double)jarg2; 
-  arg3 = (pointObj *)jarg3; 
-  arg4 = (int)jarg4; 
-  arg5 = (int)jarg5; 
-  arg6 = (rectObj *)jarg6; 
-  arg7 = (rectObj *)jarg7; 
-  {
-    errorObj *ms_error;
-    result = (int)mapObj_zoomScale(arg1,arg2,arg3,arg4,arg5,arg6,arg7);
-    ms_error = msGetErrorObj();
-    if (ms_error != NULL && ms_error->code != MS_NOERR) {
-      if (ms_error->code != MS_NOTFOUND && ms_error->code != -1) {
-        char* msg = msGetErrorString(";"); 
-        if (msg) {
-          SWIG_CSharpException(SWIG_SystemError, msg);
-          free(msg);
-        }
-        else SWIG_CSharpException(SWIG_SystemError, "MapScript unknown error");
-        msResetErrorList();
-        return 0;
-      }
-      msResetErrorList();
-    }
-  }
-  jresult = result; 
-  return jresult;
-}
-
-
-SWIGEXPORT void SWIGSTDCALL CSharp_imageObj_getBytes(void * jarg1, SWIG_CSharpByteArrayHelperCallback jarg2) {
-  imageObj *arg1 = (imageObj *) 0 ;
-  SWIG_CSharpByteArrayHelperCallback arg2 ;
-  
-  arg1 = (imageObj *)jarg1; 
-  arg2 = (SWIG_CSharpByteArrayHelperCallback)jarg2; 
-  {
-    errorObj *ms_error;
-    imageObj_getBytes(arg1,arg2);
-    ms_error = msGetErrorObj();
-    if (ms_error != NULL && ms_error->code != MS_NOERR) {
-      if (ms_error->code != MS_NOTFOUND && ms_error->code != -1) {
-        char* msg = msGetErrorString(";"); 
-        if (msg) {
-          SWIG_CSharpException(SWIG_SystemError, msg);
-          free(msg);
-        }
-        else SWIG_CSharpException(SWIG_SystemError, "MapScript unknown error");
-        msResetErrorList();
-        return ;
-      }
-      msResetErrorList();
-    }
-  }
-}
-
-
-SWIGEXPORT int SWIGSTDCALL CSharp_imageObj_width_get(void * jarg1) {
-  int jresult ;
-  imageObj *arg1 = (imageObj *) 0 ;
-  int result;
-  
-  arg1 = (imageObj *)jarg1; 
-  result = (int) ((arg1)->width);
-  jresult = result; 
-  return jresult;
-}
-
-
-SWIGEXPORT int SWIGSTDCALL CSharp_imageObj_height_get(void * jarg1) {
-  int jresult ;
-  imageObj *arg1 = (imageObj *) 0 ;
-  int result;
-  
-  arg1 = (imageObj *)jarg1; 
-  result = (int) ((arg1)->height);
-  jresult = result; 
-  return jresult;
-}
-
-
-SWIGEXPORT double SWIGSTDCALL CSharp_imageObj_resolution_get(void * jarg1) {
-  double jresult ;
-  imageObj *arg1 = (imageObj *) 0 ;
-  double result;
-  
-  arg1 = (imageObj *)jarg1; 
-  result = (double) ((arg1)->resolution);
-  jresult = result; 
-  return jresult;
-}
-
-
-SWIGEXPORT double SWIGSTDCALL CSharp_imageObj_resolutionfactor_get(void * jarg1) {
-  double jresult ;
-  imageObj *arg1 = (imageObj *) 0 ;
-  double result;
-  
-  arg1 = (imageObj *)jarg1; 
-  result = (double) ((arg1)->resolutionfactor);
-  jresult = result; 
-  return jresult;
-}
-
-
-SWIGEXPORT char * SWIGSTDCALL CSharp_imageObj_imagepath_get(void * jarg1) {
-  char * jresult ;
-  imageObj *arg1 = (imageObj *) 0 ;
-  char *result = 0 ;
-  
-  arg1 = (imageObj *)jarg1; 
-  result = (char *) ((arg1)->imagepath);
-  jresult = SWIG_csharp_string_callback((const char *)result); 
-  return jresult;
-}
-
-
-SWIGEXPORT char * SWIGSTDCALL CSharp_imageObj_imageurl_get(void * jarg1) {
-  char * jresult ;
-  imageObj *arg1 = (imageObj *) 0 ;
-  char *result = 0 ;
-  
-  arg1 = (imageObj *)jarg1; 
-  result = (char *) ((arg1)->imageurl);
-  jresult = SWIG_csharp_string_callback((const char *)result); 
-  return jresult;
-}
-
-
-SWIGEXPORT void * SWIGSTDCALL CSharp_imageObj_format_get(void * jarg1) {
-  void * jresult ;
-  imageObj *arg1 = (imageObj *) 0 ;
-  outputFormatObj *result = 0 ;
-  
-  arg1 = (imageObj *)jarg1; 
-  result = (outputFormatObj *) ((arg1)->format);
-  jresult = (void *)result; 
-  return jresult;
-}
-
-
-SWIGEXPORT void * SWIGSTDCALL CSharp_new_imageObj(int jarg1, int jarg2, void * jarg3, char * jarg4, double jarg5, double jarg6) {
-  void * jresult ;
-  int arg1 ;
-  int arg2 ;
-  outputFormatObj *arg3 = (outputFormatObj *) NULL ;
-  char *arg4 = (char *) NULL ;
-  double arg5 = (double) MS_DEFAULT_RESOLUTION ;
-  double arg6 = (double) MS_DEFAULT_RESOLUTION ;
-  imageObj *result = 0 ;
-  
-  arg1 = (int)jarg1; 
-  arg2 = (int)jarg2; 
-  arg3 = (outputFormatObj *)jarg3; 
-  arg4 = (char *)jarg4; 
-  arg5 = (double)jarg5; 
-  arg6 = (double)jarg6; 
-  {
-    errorObj *ms_error;
-    result = (imageObj *)new_imageObj(arg1,arg2,arg3,(char const *)arg4,arg5,arg6);
-    ms_error = msGetErrorObj();
-    if (ms_error != NULL && ms_error->code != MS_NOERR) {
-      if (ms_error->code != MS_NOTFOUND && ms_error->code != -1) {
-        char* msg = msGetErrorString(";"); 
-        if (msg) {
-          SWIG_CSharpException(SWIG_SystemError, msg);
-          free(msg);
-        }
-        else SWIG_CSharpException(SWIG_SystemError, "MapScript unknown error");
-        msResetErrorList();
-        return 0;
-      }
-      msResetErrorList();
-    }
-  }
-  jresult = (void *)result; 
-  return jresult;
-}
-
-
-SWIGEXPORT void SWIGSTDCALL CSharp_delete_imageObj(void * jarg1) {
-  imageObj *arg1 = (imageObj *) 0 ;
-  
-  arg1 = (imageObj *)jarg1; 
-  {
-    errorObj *ms_error;
-    delete_imageObj(arg1);
-    ms_error = msGetErrorObj();
-    if (ms_error != NULL && ms_error->code != MS_NOERR) {
-      if (ms_error->code != MS_NOTFOUND && ms_error->code != -1) {
-        char* msg = msGetErrorString(";"); 
-        if (msg) {
-          SWIG_CSharpException(SWIG_SystemError, msg);
-          free(msg);
-        }
-        else SWIG_CSharpException(SWIG_SystemError, "MapScript unknown error");
-        msResetErrorList();
-        return ;
+        return 0;
       }
       msResetErrorList();
     }
   }
+  jresult = result; 
+  return jresult;
 }
 
 
-SWIGEXPORT void SWIGSTDCALL CSharp_imageObj_save(void * jarg1, char * jarg2, void * jarg3) {
-  imageObj *arg1 = (imageObj *) 0 ;
-  char *arg2 = (char *) 0 ;
-  mapObj *arg3 = (mapObj *) NULL ;
+SWIGEXPORT int SWIGSTDCALL CSharp_mapObj_zoomRectangle(void * jarg1, void * jarg2, int jarg3, int jarg4, void * jarg5, void * jarg6) {
+  int jresult ;
+  mapObj *arg1 = (mapObj *) 0 ;
+  rectObj *arg2 = (rectObj *) 0 ;
+  int arg3 ;
+  int arg4 ;
+  rectObj *arg5 = (rectObj *) 0 ;
+  rectObj *arg6 = (rectObj *) 0 ;
+  int result;
   
-  arg1 = (imageObj *)jarg1; 
-  arg2 = (char *)jarg2; 
-  arg3 = (mapObj *)jarg3; 
+  arg1 = (mapObj *)jarg1; 
+  arg2 = (rectObj *)jarg2; 
+  arg3 = (int)jarg3; 
+  arg4 = (int)jarg4; 
+  arg5 = (rectObj *)jarg5; 
+  arg6 = (rectObj *)jarg6; 
   {
     errorObj *ms_error;
-    imageObj_save(arg1,arg2,arg3);
+    result = (int)mapObj_zoomRectangle(arg1,arg2,arg3,arg4,arg5,arg6);
     ms_error = msGetErrorObj();
     if (ms_error != NULL && ms_error->code != MS_NOERR) {
       if (ms_error->code != MS_NOTFOUND && ms_error->code != -1) {
@@ -16925,23 +17616,37 @@ SWIGEXPORT void SWIGSTDCALL CSharp_imageObj_save(void * jarg1, char * jarg2, voi
         }
         else SWIG_CSharpException(SWIG_SystemError, "MapScript unknown error");
         msResetErrorList();
-        return ;
+        return 0;
       }
       msResetErrorList();
     }
   }
+  jresult = result; 
+  return jresult;
 }
 
 
-SWIGEXPORT int SWIGSTDCALL CSharp_imageObj_getSize(void * jarg1) {
+SWIGEXPORT int SWIGSTDCALL CSharp_mapObj_zoomScale(void * jarg1, double jarg2, void * jarg3, int jarg4, int jarg5, void * jarg6, void * jarg7) {
   int jresult ;
-  imageObj *arg1 = (imageObj *) 0 ;
+  mapObj *arg1 = (mapObj *) 0 ;
+  double arg2 ;
+  pointObj *arg3 = (pointObj *) 0 ;
+  int arg4 ;
+  int arg5 ;
+  rectObj *arg6 = (rectObj *) 0 ;
+  rectObj *arg7 = (rectObj *) 0 ;
   int result;
   
-  arg1 = (imageObj *)jarg1; 
+  arg1 = (mapObj *)jarg1; 
+  arg2 = (double)jarg2; 
+  arg3 = (pointObj *)jarg3; 
+  arg4 = (int)jarg4; 
+  arg5 = (int)jarg5; 
+  arg6 = (rectObj *)jarg6; 
+  arg7 = (rectObj *)jarg7; 
   {
     errorObj *ms_error;
-    result = (int)imageObj_getSize(arg1);
+    result = (int)mapObj_zoomScale(arg1,arg2,arg3,arg4,arg5,arg6,arg7);
     ms_error = msGetErrorObj();
     if (ms_error != NULL && ms_error->code != MS_NOERR) {
       if (ms_error->code != MS_NOTFOUND && ms_error->code != -1) {
@@ -17047,10 +17752,13 @@ SWIGEXPORT int SWIGSTDCALL CSharp_msSetup() {
 }
 
 
-SWIGEXPORT void SWIGSTDCALL CSharp_msCleanup() {
+SWIGEXPORT void SWIGSTDCALL CSharp_msCleanup(int jarg1) {
+  int arg1 ;
+  
+  arg1 = (int)jarg1; 
   {
     errorObj *ms_error;
-    msCleanup();
+    msCleanup(arg1);
     ms_error = msGetErrorObj();
     if (ms_error != NULL && ms_error->code != MS_NOERR) {
       if (ms_error->code != MS_NOTFOUND && ms_error->code != -1) {
@@ -17170,6 +17878,28 @@ SWIGEXPORT void * SWIGSTDCALL CSharp_strokeStyleObj_pattern_get(void * jarg1) {
 }
 
 
+SWIGEXPORT void SWIGSTDCALL CSharp_strokeStyleObj_patternoffset_set(void * jarg1, double jarg2) {
+  strokeStyleObj *arg1 = (strokeStyleObj *) 0 ;
+  double arg2 ;
+  
+  arg1 = (strokeStyleObj *)jarg1; 
+  arg2 = (double)jarg2; 
+  if (arg1) (arg1)->patternoffset = arg2;
+}
+
+
+SWIGEXPORT double SWIGSTDCALL CSharp_strokeStyleObj_patternoffset_get(void * jarg1) {
+  double jresult ;
+  strokeStyleObj *arg1 = (strokeStyleObj *) 0 ;
+  double result;
+  
+  arg1 = (strokeStyleObj *)jarg1; 
+  result = (double) ((arg1)->patternoffset);
+  jresult = result; 
+  return jresult;
+}
+
+
 SWIGEXPORT void SWIGSTDCALL CSharp_strokeStyleObj_color_set(void * jarg1, void * jarg2) {
   strokeStyleObj *arg1 = (strokeStyleObj *) 0 ;
   colorObj *arg2 = (colorObj *) 0 ;
@@ -17832,32 +18562,50 @@ SWIGEXPORT void SWIGSTDCALL CSharp_delete_tileCacheObj(void * jarg1) {
 }
 
 
-SWIGEXPORT void SWIGSTDCALL CSharp_labelStyleObj_font_set(void * jarg1, char * jarg2) {
+SWIGEXPORT void SWIGSTDCALL CSharp_labelStyleObj_fonts_set(void * jarg1, void * jarg2) {
   labelStyleObj *arg1 = (labelStyleObj *) 0 ;
-  char *arg2 = (char *) 0 ;
+  char **arg2 ;
   
   arg1 = (labelStyleObj *)jarg1; 
-  arg2 = (char *)jarg2; 
+  arg2 = (char **)jarg2; 
   {
-    if (arg1->font) free((char*)arg1->font);
-    if (arg2) {
-      arg1->font = (char *) malloc(strlen(arg2)+1);
-      strcpy((char*)arg1->font,arg2);
-    } else {
-      arg1->font = 0;
-    }
+    size_t ii;
+    char * *b = (char * *) arg1->fonts;
+    for (ii = 0; ii < (size_t)5; ii++) b[ii] = *((char * *) arg2 + ii);
   }
 }
 
 
-SWIGEXPORT char * SWIGSTDCALL CSharp_labelStyleObj_font_get(void * jarg1) {
-  char * jresult ;
+SWIGEXPORT void * SWIGSTDCALL CSharp_labelStyleObj_fonts_get(void * jarg1) {
+  void * jresult ;
   labelStyleObj *arg1 = (labelStyleObj *) 0 ;
-  char *result = 0 ;
+  char **result = 0 ;
   
   arg1 = (labelStyleObj *)jarg1; 
-  result = (char *) ((arg1)->font);
-  jresult = SWIG_csharp_string_callback((const char *)result); 
+  result = (char **)(char **) ((arg1)->fonts);
+  jresult = result; 
+  return jresult;
+}
+
+
+SWIGEXPORT void SWIGSTDCALL CSharp_labelStyleObj_numfonts_set(void * jarg1, int jarg2) {
+  labelStyleObj *arg1 = (labelStyleObj *) 0 ;
+  int arg2 ;
+  
+  arg1 = (labelStyleObj *)jarg1; 
+  arg2 = (int)jarg2; 
+  if (arg1) (arg1)->numfonts = arg2;
+}
+
+
+SWIGEXPORT int SWIGSTDCALL CSharp_labelStyleObj_numfonts_get(void * jarg1) {
+  int jresult ;
+  labelStyleObj *arg1 = (labelStyleObj *) 0 ;
+  int result;
+  
+  arg1 = (labelStyleObj *)jarg1; 
+  result = (int) ((arg1)->numfonts);
+  jresult = result; 
   return jresult;
 }
 
@@ -17972,6 +18720,28 @@ SWIGEXPORT void * SWIGSTDCALL CSharp_labelStyleObj_outlinecolor_get(void * jarg1
 }
 
 
+SWIGEXPORT void SWIGSTDCALL CSharp_labelStyleObj_antialias_set(void * jarg1, int jarg2) {
+  labelStyleObj *arg1 = (labelStyleObj *) 0 ;
+  int arg2 ;
+  
+  arg1 = (labelStyleObj *)jarg1; 
+  arg2 = (int)jarg2; 
+  if (arg1) (arg1)->antialias = arg2;
+}
+
+
+SWIGEXPORT int SWIGSTDCALL CSharp_labelStyleObj_antialias_get(void * jarg1) {
+  int jresult ;
+  labelStyleObj *arg1 = (labelStyleObj *) 0 ;
+  int result;
+  
+  arg1 = (labelStyleObj *)jarg1; 
+  result = (int) ((arg1)->antialias);
+  jresult = result; 
+  return jresult;
+}
+
+
 SWIGEXPORT void * SWIGSTDCALL CSharp_new_labelStyleObj() {
   void * jresult ;
   labelStyleObj *result = 0 ;
@@ -21259,6 +22029,36 @@ SWIGEXPORT void * SWIGSTDCALL CSharp_shapefileObj_getDBF(void * jarg1) {
 }
 
 
+SWIGEXPORT int SWIGSTDCALL CSharp_wkp_none_get() {
+  int jresult ;
+  int result;
+  
+  result = (int) 0;
+  jresult = result; 
+  return jresult;
+}
+
+
+SWIGEXPORT int SWIGSTDCALL CSharp_wkp_lonlat_get() {
+  int jresult ;
+  int result;
+  
+  result = (int) 1;
+  jresult = result; 
+  return jresult;
+}
+
+
+SWIGEXPORT int SWIGSTDCALL CSharp_wkp_gmerc_get() {
+  int jresult ;
+  int result;
+  
+  result = (int) 2;
+  jresult = result; 
+  return jresult;
+}
+
+
 SWIGEXPORT int SWIGSTDCALL CSharp_projectionObj_numargs_get(void * jarg1) {
   int jresult ;
   projectionObj *arg1 = (projectionObj *) 0 ;
@@ -21283,6 +22083,28 @@ SWIGEXPORT int SWIGSTDCALL CSharp_projectionObj_automatic_get(void * jarg1) {
 }
 
 
+SWIGEXPORT void SWIGSTDCALL CSharp_projectionObj_wellknownprojection_set(void * jarg1, int jarg2) {
+  projectionObj *arg1 = (projectionObj *) 0 ;
+  int arg2 ;
+  
+  arg1 = (projectionObj *)jarg1; 
+  arg2 = (int)jarg2; 
+  if (arg1) (arg1)->wellknownprojection = arg2;
+}
+
+
+SWIGEXPORT int SWIGSTDCALL CSharp_projectionObj_wellknownprojection_get(void * jarg1) {
+  int jresult ;
+  projectionObj *arg1 = (projectionObj *) 0 ;
+  int result;
+  
+  arg1 = (projectionObj *)jarg1; 
+  result = (int) ((arg1)->wellknownprojection);
+  jresult = result; 
+  return jresult;
+}
+
+
 SWIGEXPORT void * SWIGSTDCALL CSharp_new_projectionObj(char * jarg1) {
   void * jresult ;
   char *arg1 = (char *) 0 ;
@@ -21437,28 +22259,6 @@ SWIGEXPORT int SWIGSTDCALL CSharp_MS_IMAGECACHESIZE_get() {
 }
 
 
-SWIGEXPORT void SWIGSTDCALL CSharp_colorObj_pen_set(void * jarg1, int jarg2) {
-  colorObj *arg1 = (colorObj *) 0 ;
-  int arg2 ;
-  
-  arg1 = (colorObj *)jarg1; 
-  arg2 = (int)jarg2; 
-  if (arg1) (arg1)->pen = arg2;
-}
-
-
-SWIGEXPORT int SWIGSTDCALL CSharp_colorObj_pen_get(void * jarg1) {
-  int jresult ;
-  colorObj *arg1 = (colorObj *) 0 ;
-  int result;
-  
-  arg1 = (colorObj *)jarg1; 
-  result = (int) ((arg1)->pen);
-  jresult = result; 
-  return jresult;
-}
-
-
 SWIGEXPORT void SWIGSTDCALL CSharp_colorObj_red_set(void * jarg1, int jarg2) {
   colorObj *arg1 = (colorObj *) 0 ;
   int arg2 ;
@@ -21955,6 +22755,50 @@ SWIGEXPORT int SWIGSTDCALL CSharp_symbolObj_filled_get(void * jarg1) {
 }
 
 
+SWIGEXPORT void SWIGSTDCALL CSharp_symbolObj_anchorpoint_x_set(void * jarg1, double jarg2) {
+  symbolObj *arg1 = (symbolObj *) 0 ;
+  double arg2 ;
+  
+  arg1 = (symbolObj *)jarg1; 
+  arg2 = (double)jarg2; 
+  if (arg1) (arg1)->anchorpoint_x = arg2;
+}
+
+
+SWIGEXPORT double SWIGSTDCALL CSharp_symbolObj_anchorpoint_x_get(void * jarg1) {
+  double jresult ;
+  symbolObj *arg1 = (symbolObj *) 0 ;
+  double result;
+  
+  arg1 = (symbolObj *)jarg1; 
+  result = (double) ((arg1)->anchorpoint_x);
+  jresult = result; 
+  return jresult;
+}
+
+
+SWIGEXPORT void SWIGSTDCALL CSharp_symbolObj_anchorpoint_y_set(void * jarg1, double jarg2) {
+  symbolObj *arg1 = (symbolObj *) 0 ;
+  double arg2 ;
+  
+  arg1 = (symbolObj *)jarg1; 
+  arg2 = (double)jarg2; 
+  if (arg1) (arg1)->anchorpoint_y = arg2;
+}
+
+
+SWIGEXPORT double SWIGSTDCALL CSharp_symbolObj_anchorpoint_y_get(void * jarg1) {
+  double jresult ;
+  symbolObj *arg1 = (symbolObj *) 0 ;
+  double result;
+  
+  arg1 = (symbolObj *)jarg1; 
+  result = (double) ((arg1)->anchorpoint_y);
+  jresult = result; 
+  return jresult;
+}
+
+
 SWIGEXPORT char * SWIGSTDCALL CSharp_symbolObj_imagepath_get(void * jarg1) {
   char * jresult ;
   symbolObj *arg1 = (symbolObj *) 0 ;
@@ -23619,6 +24463,35 @@ SWIGEXPORT void SWIGSTDCALL CSharp_OWSRequest_setParameter(void * jarg1, char *
 }
 
 
+SWIGEXPORT void SWIGSTDCALL CSharp_OWSRequest_addParameter(void * jarg1, char * jarg2, char * jarg3) {
+  cgiRequestObj *arg1 = (cgiRequestObj *) 0 ;
+  char *arg2 = (char *) 0 ;
+  char *arg3 = (char *) 0 ;
+  
+  arg1 = (cgiRequestObj *)jarg1; 
+  arg2 = (char *)jarg2; 
+  arg3 = (char *)jarg3; 
+  {
+    errorObj *ms_error;
+    cgiRequestObj_addParameter(arg1,arg2,arg3);
+    ms_error = msGetErrorObj();
+    if (ms_error != NULL && ms_error->code != MS_NOERR) {
+      if (ms_error->code != MS_NOTFOUND && ms_error->code != -1) {
+        char* msg = msGetErrorString(";"); 
+        if (msg) {
+          SWIG_CSharpException(SWIG_SystemError, msg);
+          free(msg);
+        }
+        else SWIG_CSharpException(SWIG_SystemError, "MapScript unknown error");
+        msResetErrorList();
+        return ;
+      }
+      msResetErrorList();
+    }
+  }
+}
+
+
 SWIGEXPORT char * SWIGSTDCALL CSharp_OWSRequest_getName(void * jarg1, int jarg2) {
   char * jresult ;
   cgiRequestObj *arg1 = (cgiRequestObj *) 0 ;
@@ -23899,7 +24772,7 @@ SWIGEXPORT void SWIGSTDCALL CSharp_msIO_getStdoutBufferBytes() {
     }
   }
   SWIG_csharp_bytearray_callback((&result)->data, (&result)->size);
-  if( (&result)->owns_data ) gdFree((&result)->data); 
+  if( (&result)->owns_data ) msFree((&result)->data); 
 }
 
 
diff --git a/mapscript/csharp/projectionObj.cs b/mapscript/csharp/projectionObj.cs
index 2062e95..e5d3ed2 100644
--- a/mapscript/csharp/projectionObj.cs
+++ b/mapscript/csharp/projectionObj.cs
@@ -95,6 +95,18 @@ public class projectionObj : IDisposable {
     } 
   }
 
+  public int wellknownprojection {
+    set {
+      mapscriptPINVOKE.projectionObj_wellknownprojection_set(swigCPtr, value);
+      if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
+    } 
+    get {
+      int ret = mapscriptPINVOKE.projectionObj_wellknownprojection_get(swigCPtr);
+      if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
+      return ret;
+    } 
+  }
+
   public projectionObj(string proj4) : this(mapscriptPINVOKE.new_projectionObj(proj4), true, null) {
     if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
   }
diff --git a/mapscript/csharp/strokeStyleObj.cs b/mapscript/csharp/strokeStyleObj.cs
index 2caa345..72e7bd9 100644
--- a/mapscript/csharp/strokeStyleObj.cs
+++ b/mapscript/csharp/strokeStyleObj.cs
@@ -116,6 +116,18 @@ public class strokeStyleObj : IDisposable {
     } 
   }
 
+  public double patternoffset {
+    set {
+      mapscriptPINVOKE.strokeStyleObj_patternoffset_set(swigCPtr, value);
+      if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
+    } 
+    get {
+      double ret = mapscriptPINVOKE.strokeStyleObj_patternoffset_get(swigCPtr);
+      if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
+      return ret;
+    } 
+  }
+
   public colorObj color {
     set {
       mapscriptPINVOKE.strokeStyleObj_color_set(swigCPtr, colorObj.getCPtr(value));
diff --git a/mapscript/csharp/styleObj.cs b/mapscript/csharp/styleObj.cs
index f2dbcb7..01f9d6a 100644
--- a/mapscript/csharp/styleObj.cs
+++ b/mapscript/csharp/styleObj.cs
@@ -321,6 +321,18 @@ public class styleObj : IDisposable {
     } 
   }
 
+  public double initialgap {
+    set {
+      mapscriptPINVOKE.styleObj_initialgap_set(swigCPtr, value);
+      if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
+    } 
+    get {
+      double ret = mapscriptPINVOKE.styleObj_initialgap_get(swigCPtr);
+      if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
+      return ret;
+    } 
+  }
+
   public int position {
     set {
       mapscriptPINVOKE.styleObj_position_set(swigCPtr, value);
@@ -441,6 +453,30 @@ public class styleObj : IDisposable {
     } 
   }
 
+  public double polaroffsetpixel {
+    set {
+      mapscriptPINVOKE.styleObj_polaroffsetpixel_set(swigCPtr, value);
+      if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
+    } 
+    get {
+      double ret = mapscriptPINVOKE.styleObj_polaroffsetpixel_get(swigCPtr);
+      if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
+      return ret;
+    } 
+  }
+
+  public double polaroffsetangle {
+    set {
+      mapscriptPINVOKE.styleObj_polaroffsetangle_set(swigCPtr, value);
+      if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
+    } 
+    get {
+      double ret = mapscriptPINVOKE.styleObj_polaroffsetangle_get(swigCPtr);
+      if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
+      return ret;
+    } 
+  }
+
   public double angle {
     set {
       mapscriptPINVOKE.styleObj_angle_set(swigCPtr, value);
diff --git a/mapscript/csharp/symbolObj.cs b/mapscript/csharp/symbolObj.cs
index 7198d9d..995e76f 100644
--- a/mapscript/csharp/symbolObj.cs
+++ b/mapscript/csharp/symbolObj.cs
@@ -215,6 +215,30 @@ public class symbolObj : IDisposable {
     } 
   }
 
+  public double anchorpoint_x {
+    set {
+      mapscriptPINVOKE.symbolObj_anchorpoint_x_set(swigCPtr, value);
+      if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
+    } 
+    get {
+      double ret = mapscriptPINVOKE.symbolObj_anchorpoint_x_get(swigCPtr);
+      if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
+      return ret;
+    } 
+  }
+
+  public double anchorpoint_y {
+    set {
+      mapscriptPINVOKE.symbolObj_anchorpoint_y_set(swigCPtr, value);
+      if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
+    } 
+    get {
+      double ret = mapscriptPINVOKE.symbolObj_anchorpoint_y_get(swigCPtr);
+      if (mapscriptPINVOKE.SWIGPendingException.Pending) throw mapscriptPINVOKE.SWIGPendingException.Retrieve();
+      return ret;
+    } 
+  }
+
   public string imagepath {
     get {
       string ret = mapscriptPINVOKE.symbolObj_imagepath_get(swigCPtr);
diff --git a/mapscript/java/Makefile.in b/mapscript/java/Makefile.in
index 3212c85..d958e0d 100644
--- a/mapscript/java/Makefile.in
+++ b/mapscript/java/Makefile.in
@@ -3,249 +3,21 @@
 
 prefix		=	@prefix@
 exec_prefix	=	@exec_prefix@
-INST_PREFIX	=	@exec_prefix@
-INST_LIB	=	@libdir@
-INST_BIN	=	@bindir@
-
-#
-# If you want to ignore missing datafile errors uncomment the following
-# line. This is especially useful with large tiled datasets that may not
-# have complete data for each tile.
-#
-#IGNORE_MISSING_DATA=-DIGNORE_MISSING_DATA
-IGNORE_MISSING_DATA = @IGNORE_MISSING_DATA@
-
-#
-# If you want to use shape Z and M parameter this option must be set.
-# It's OFF by default.
-#
-#USE_POINT_Z_M=-DUSE_POINT_Z_M
-USE_POINT_Z_M = @USE_POINT_Z_M@
-
-#
-# If you want to use disable fast versions of NINT (used by default) then
-# define the following
-# It's OFF by default.
-#
-#USE_NINT=-DUSE_GENERIC_MS_NINT
-USE_NINT = @USE_NINT@
-
-#
-# Apparently these aren't as commonplace as I'd hoped. Edit the
-# following line to reflect the missing functions on your platform.
-#
-# STRINGS=-DNEED_STRCASECMP -DNEED_STRNCASECMP -DNEED_STRDUP -DNEED_STRLCAT
-STRINGS= @STRINGS@
-
-# Proj.4 distribution (cartographic projection routines). Not required for normal use. (EXPERIMENTAL)
-PROJ_INC= @PROJ_INC@
-PROJ_LIBS= @PROJ_LIBS@
-PROJ=     @PROJ_ENABLED@
-
-# GD distribution (graphics library GIF and/or PNG support). (REQUIRED)
-#
-#   - Versions 1.3 to 1.5 write non-LZW GIF (-DUSE_GD_1_3).
-#   - Versions 1.6 and greater write PNG (-DUSE_GD_1_6). Add -lpng -lz to GD_LIB line.
-#
-#
-GDFONT_OBJ=gd-1.2/gdfontt.o gd-1.2/gdfonts.o gd-1.2/gdfontmb.o gd-1.2/gdfontl.o gd-1.2/gdfontg.o
-GD_INC=  @GD_INC@
-GD_LIB=  @GD_LIB@
-GD=      @GD_DEF@
-GD_STATIC = @GD_STATIC@
-
-#
-# Optional Anti-Grain Geometry Support.
-#
-#AGG=     @AGG_ENABLED@ commented because it breaks the build
-AGG_INC=  @AGG_INC@
-AGG_OBJ=  @AGG_OBJ@
-AGG_LIB= @AGG_LIB@
-
-#
-# Optional Opengl Support.
-#
-FTGL=     @FTGL_ENABLED@
-FTGL_LIB=  @FTGL_LIB@
-FTGL_INC=  @FTGL_INC@
-
-#Freetype support
-FT_ENABLE=     @FT_ENABLED@
-FT_LIB=  @FT_LIB@
-FT_INC=  @FT_INC@
-
-#
-# Optional Opengl Support.
-#
-OGL=     @OGL_ENABLED@
-OGL_LIB=  @OGL_LIB@
-OGL_INC=  @OGL_INC@
-
-PNG_INC= @PNG_INC@
-PNG_LIB= @PNG_LIB@
-
-#
-# Giflib support
-#
-GIF_INC= @GIF_INC@
-GIF_LIB= @GIF_LIB@
-GIF=     @GIF_ENABLED@
-
-# 
-# ZLIB option (compressed SVG)
-#
-ZLIB_INC=  @ZLIB_INC@
-ZLIB_LIB=  @ZLIB_LIB@
-ZLIB=      @ZLIB_ENABLED@
-
-# JPEG distribution (raster support for grayscale JPEG images, INPUT ONLY).
-JPEG_INC= @JPEG_INC@
-JPEG_LIB= @JPEG_LIB@
-JPEG=     @JPEG_ENABLED@
-
-# ESRI SDE Support. You MUST have the SDE Client libraries and include files
-# on your system someplace. The actual SDE server you wish to connect to can
-# be elsewhere.
-SDE=	  @SDE_ENABLED@
-SDE_LIB=  @SDE_LIB@
-SDE_INC=  @SDE_INC@
-
-# Optional OGR Support.  OGC Simple Feature inspired interface for vector
-# formats.  See http://ogr.maptools.org/
-# Note that since OGR is part of the GDAL library, it uses GDAL_LIB + GDAL_INC
-OGR=	  @OGR_ENABLED@
-
-# Optional GDAL Support (provides read access to a variety of raster formats)
-# See http://www.remotesensing.org/gdal/
-GDAL=	  @GDAL_ENABLED@
-GDAL_LIB=  @GDAL_LIB@
-GDAL_INC=  @GDAL_INC@
-
-# Optional GEOS Support.
-# See http://geos.refractions.net/
-GEOS=     @GEOS_ENABLED@
-GEOS_LIB=  @GEOS_LIB@
-GEOS_INC=  @GEOS_INC@
-
-# Optional PostGIS Support.  See http://postgis.refractions.net/
-POSTGIS=      @POSTGIS_ENABLED@
-POSTGIS_LIB=  @POSTGIS_LIB@
-POSTGIS_INC=  @POSTGIS_INC@
-
-# Optional Mysql Support.  See http://postgis.refractions.net/
-MYSQL=      @MYSQL_ENABLED@
-MYSQL_LIB=  @MYSQL_LIB@
-MYSQL_INC=  @MYSQL_INC@
-
-# Optional ORACLESPATIAL Support. Contact: cabral at cttmar.univali.br
-ORACLESPATIAL=@ORACLESPATIAL_ENABLED@
-ORACLESPATIAL_LIB=@ORACLESPATIAL_LIB@
-ORACLESPATIAL_INC=@ORACLESPATIAL_INC@
-
-# libcurl ... required for WMS/WFS Client Connections
-CURL_INC=@CURL_INC@
-CURL_LIB=@CURL_LIB@
-
-# libfribibi ... 
-FRIBIDI=@FRIBIDI_ENABLED@
-FRIBIDI_INC=@FRIBIDI_INC@
-FRIBIDI_LIB=@FRIBIDI_LIB@
-
-
-# libxml2 ... required for OGC SOS Server
-XML2_INC=@XML2_INC@
-XML2_LIB=@XML2_LIB@
-
-# libxslt ... required for xml mapfile
-XSLT_INC=@XSLT_INC@
-XSLT_LIB=@XSLT_LIB@
-
-# libexslt ... required for xml mapfile
-EXSLT_INC=@EXSLT_INC@
-EXSLT_LIB=@EXSLT_LIB@
-
-# OWS: OGC Web Services support
-# OGC WMS Server:  -DUSE_WMS_SVR (Requires PROJ4 support)
-# OGC WMS Client Connections:  -DUSE_WMS_LYR (Requires PROJ4 and libcurl)
-# OGC WFS Server: -DUSE_WFS_SVR (Requires OGR, PROJ4 recommended)
-# OGC WFS Client: -DUSE_WFS_LYR (Requires OGR, PROJ4 and libcurl)
-# OGC WCS Server: -DUSE_WCS_SVR (Requires GDAL and PROJ4)
-# OGC SOS Server: -DUSE_SOS_SVR (Requires PROJ4 and libxml2)
-OWS=@WMS_SVR_ENABLED@ @WMS_LYR_ENABLED@ @WFS_SVR_ENABLED@ @WFS_LYR_ENABLED@ @WCS_SVR_ENABLED@ @SOS_SVR_ENABLED@
-
-#
-# IMPORTANT NOTE ABOUT REGEX FOR PHP_MAPSCRIPT USERS:
-#
-# In order to compile the PHP_MAPSCRIPT module, we have to make MapServer
-# uses the same version of the REGEX library that PHP was compiled with:
-#
-REGEX_OBJ=@PHP_REGEX_OBJ@
-REGEX_INC=@PHP_REGEX_INC@
-
-#
-# Multithreading support.
-#
-THREAD=@THREAD_FLAG@
-THREAD_LIB=@THREAD_LIB@
-
-#
-# libiconv - Enables Internationalization
-#
-ICONV=@ICONV_ENABLED@
-ICONV_LIB=@ICONV_LIB@
-ICONV_INC=@ICONV_INC@
-
-CAIRO=@CAIRO_ENABLED@
-CAIRO_LIB=@CAIRO_LIB@
-CAIRO_INC=@CAIRO_INC@
-
-#
-# Pick a compiler, etc. Flex and bison are only required if you need to modify the mapserver lexer (maplexer.l) or expression parser (mapparser.y).
-#
+libdir	=	@libdir@
+bindir	=	@bindir@
+top_builddir = @top_builddir@
+SHELL = @SHELL@
 CXX=	@CXX@
 CC=     @CC@
 LD=     @CXX@
-AR= ar rc
-RANLIB= @RANLIB@
-LEX=    @LEX@
-YACC=   @YACC@
-LD_SHARED = @LD_SHARED@
-
-XTRALIBS= @XTRALIBS@
-RUNPATHS= @RPATHS@
-
-CCFLAGS= @CFLAGS@ @DEBUG_FLAGS@ \
-        $(IGNORE_MISSING_DATA) $(STRINGS) $(PROJ) $(OWS) \
-	$(ORACLESPATIAL) $(JPEG) $(GD) $(AGG) $(PDF) $(SDE) $(OGR) $(GDAL) $(GEOS) $(ICONV) \
-	$(POSTGIS) $(MYSQL) $(THREAD) $(GD_INC) $(AGG_INC) \
-	$(PROJ_INC) $(JPEG_INC) $(EGIS_INC) $(SDE_INC) \
-	$(REGEX_INC) $(GDAL_INC) $(POSTGIS_INC) $(MYSQL_INC) \
-	$(CURL_INC) $(ORACLESPATIAL_INC) $(GEOS_INC) $(ICONV_INC) $(XML2_INC) \
-	$(FRIBIDI_INC) $(CAIRO_INC) $(OGL_INC) $(FTGL_INC)
-
-# Link flags and shared libs only
-SUP_LIBS =  $(FT_LIB) $(GD_LIB) $(AGG_LIB) $(OGL_LIB) $(FTGL_LIB) $(PROJ_LIBS) \
-          $(JPEG_LIB) $(PNG_LIB) $(GIF_LIB) $(SDE_LIB) $(GDAL_LIB) $(POSTGIS_LIB) \
-	  $(MYSQL_LIB) $(CURL_LIB) $(ORACLESPATIAL_LIB) $(GEOS_LIB) \
-          $(THREAD_LIB) $(ICONV_LIB) $(FASTCGI_LIB) $(XSLT_LIB) $(EXSLT_LIB) \
-          $(ZLIB_LIB) $(XML2_LIB) $(FRIBIDI_LIB) $(XTRALIBS) $(CAIRO_LIB)
-
-# STATIC_LIBS is full filename with path of libs that will be statically linked
-STATIC_LIBS= $(GD_STATIC)
-
-EXE_LDFLAGS =	$(RUNPATHS) -L. -lmapserver $(SUP_LIBS) $(STATIC_LIBS)
-
-LDFLAGS= $(RUNPATHS) -L../.. -lmapserver $(SUP_LIBS) $(STATIC_LIBS)
-
-LIBMAPSCRIPT_SHARED= libmapscript. at SO_EXT@
-LD_SHARED= @LD_SHARED@
-
-# END OF CONFIGURE----
+LIBTOOL=@LIBTOOL@
+INSTALL=@INSTALL@
+SWIG=swig
 
 #
-# SWIG Stuff
+# MS_VERSION - Set by configure based in mapserver.h
 #
-SWIG=swig
+MS_VERSION=	@MS_VERSION@
 
 #
 # Java Stuff
@@ -254,62 +26,76 @@ JAVADOC=javadoc
 JAVAC=javac
 JAVA=java
 JAR=jar
-JAVA_INCLUDE=-I${JAVA_HOME}/include -I${JAVA_HOME}/include/@OS_INCLUDE_DIR@
+JAVA_INCLUDE=@JAVA_INCLUDE@
 
-CC=gcc
+LTCC=$(LIBTOOL) --mode=compile --tag=CC
+LTCXX=$(LIBTOOL) --mode=compile --tag=CXX
+LTLD=$(LIBTOOL) --mode=link --tag=CXX
+LTINSTALL=$(LIBTOOL) --mode=install
 
-#
-# --- You shouldn't have to edit anything else. ---
-#
-all: mapscript_jar
+XTRALIBS= @XTRALIBS@
 
-# This target is for users who are generating their own interface
-# with SWIG versions lower than 1.3.19 (no -outdir)
-# It is here for bacwkards compatibilty as swig <1.3.24 is no longer supported
-interface: interface_release
+RUNPATH= -rpath $(libdir)
+DEFINES=@ALL_ENABLED@
+CFLAGS = $(DEFINES) @CFLAGS@ -I$(PYINCDIR) @MS_INC@ @ALL_INC@
 
-interface_release: mapscript_wrap.c
+LT_LDFLAGS= $(RUNPATH) -module
+OBJ_SUFFIX=lo
+LINK=$(LTLD) $(LD) $(LT_LDFLAGS)
+MS_LIB =   $(top_builddir)/libmapserver.la
 
-# This target will be used in the release script
-mapscript_wrap.c: ../mapscript.i
-	mkdir -p edu/umn/gis/mapscript 
-	$(SWIG) -java -package edu.umn.gis.mapscript -outdir edu/umn/gis/mapscript -o mapscript_wrap.c ../mapscript.i
 
-mapscript_so: mapscript_wrap.c
-	$(CC) -fpic -c $(CCFLAGS) $(JAVA_INCLUDE) -fno-strict-aliasing mapscript_wrap.c
-	$(LD_SHARED) -fpic mapscript_wrap.o -o $(LIBMAPSCRIPT_SHARED) $(LDFLAGS)
+.SUFFIXES:
+.SUFFIXES: .cpp .c .$(OBJ_SUFFIX)
+
+all: javamapscript.jar
+
+libjavamapscript.la: javamapscript_wrap.lo $(MS_LIB)
+	$(LINK) -release $(MS_VERSION) -o $@ javamapscript_wrap.lo $(MS_LIB)
 
-mapscript_java: mapscript_wrap.c
+%.lo: %.c
+	$(LTCC) $(CC) -fno-strict-aliasing -fpic -c $(CFLAGS) $(JAVA_INCLUDE) -c -o $@ $<
+
+javamapscript_wrap.c: ../mapscript.i
+	mkdir -p edu/umn/gis/mapscript 
+	$(SWIG) -java -package edu.umn.gis.mapscript $(DEFINES) -outdir edu/umn/gis/mapscript -o javamapscript_wrap.c ../mapscript.i
+
+javamapscript_java: javamapscript_wrap.c
 	$(JAVAC) edu/umn/gis/mapscript/*.java
 
-mapscript_javadoc: mapscript_wrap.c
+mapscript_javadoc: javamapscript_wrap.c
 	$(JAVADOC) -d doc -sourcepath edu/umn/gis/mapscript/*.java
 
-mapscript_jar: mapscript_java mapscript_so
+javamapscript.jar: javamapscript_java libjavamapscript.la
 	$(JAR) cf mapscript.jar edu
 
+install: mapscript.jar
+	$(LTINSTALL) $(INSTALL) libjavamapscript.la $(DESTDIR)$(libdir)
+
 clean:
+	-rm -rf .libs *.lo *.la *.so *.o pygdioctx/*.o pygdioctx/*.lo
 	rm -rf edu *.o *.c *. at SO_EXT@ *.java *.jar *.png
 	rm -rf examples/*.class
 	rm -rf tests/threadtest/*.class
 
-ifneq ($(PROJ),)
-ifneq ($(GDAL),)
+
+ifneq ($(findstring PROJ, $(DEFINES)),)
+ifneq ($(findstring GDAL, $(DEFINES)),)
 test:
 	$(JAVAC) -classpath ./:examples/:./mapscript.jar -d examples/ examples/RFC24.java examples/ConnPool.java examples/DrawMap.java examples/DumpShp.java examples/MakePoint.java examples/QueryByAttribute.java examples/ShapeInfo.java examples/WxSTest.java examples/Metadata.java examples/RunTimeBuiltWMSClient.java
 	$(JAVAC) -encoding utf8 -classpath ./:examples/:./mapscript.jar -d examples/ examples/QueryByAttributeUnicode.java 
-	$(JAVA) -classpath ./:examples/:./mapscript.jar -Djava.library.path=. DumpShp ../../tests/point.shp
-	$(JAVA) -classpath ./:examples/:./mapscript.jar -Djava.library.path=. ShapeInfo ../../tests/point.shp ../../tests/point.dbf
-	$(JAVA) -classpath ./:examples/:./mapscript.jar -Djava.library.path=. DrawMap ../../tests/test.map ./map.png
-	$(JAVA) -classpath ./:examples/:./mapscript.jar -Djava.library.path=. ConnPool
-	$(JAVA) -classpath ./:examples/:./mapscript.jar -Djava.library.path=. QueryByAttribute ../../tests/test.map
-ifneq ($(findstring USE_WCS_SVR, $(OWS)),)
-	$(JAVA) -classpath ./:examples/:./mapscript.jar -Djava.library.path=. WxSTest ../../tests/test.map
+	$(JAVA) -classpath ./:examples/:./mapscript.jar -Djava.library.path=.libs/ DumpShp ../../tests/point.shp
+	$(JAVA) -classpath ./:examples/:./mapscript.jar -Djava.library.path=.libs/ ShapeInfo ../../tests/point.shp ../../tests/point.dbf
+	$(JAVA) -classpath ./:examples/:./mapscript.jar -Djava.library.path=.libs/ DrawMap ../../tests/test.map ./map.png
+	$(JAVA) -classpath ./:examples/:./mapscript.jar -Djava.library.path=.libs/ ConnPool
+	$(JAVA) -classpath ./:examples/:./mapscript.jar -Djava.library.path=.libs/ QueryByAttribute ../../tests/test.map
+ifneq ($(findstring USE_WCS_SVR, $(DEFINES)),)
+	$(JAVA) -classpath ./:examples/:./mapscript.jar -Djava.library.path=.libs/ WxSTest ../../tests/test.map
 else
 	@echo "WARN: Skipping WxSTest because OWS is not enabled"
 endif
-	$(JAVA) -classpath ./:examples/:./mapscript.jar -Djava.library.path=. RFC24 ../../tests/test.map
-	LC_ALL=en_US.UTF-8 $(JAVA) -classpath ./:examples/:./mapscript.jar -Djava.library.path=. QueryByAttributeUnicode data/subset-umlauts.map
+	$(JAVA) -classpath ./:examples/:./mapscript.jar -Djava.library.path=.libs/ RFC24 ../../tests/test.map
+	LC_ALL=en_US.UTF-8 $(JAVA) -classpath ./:examples/:./mapscript.jar -Djava.library.path=.libs/ QueryByAttributeUnicode data/subset-umlauts.map
 else
 test:
 	@echo "To run the tests GDAL and PROJ must be enabled"
@@ -325,5 +111,5 @@ threadtests:
 	@echo "   You can use your own map! Copy the following command in your shell"
 	@echo "        and change the file to the map file (the last argument)"
 	@echo "-------------------------------------------------------------------------"
-	$(JAVA) -Djava.library.path=./ -cp tests/threadtest/:./mapscript.jar MapTest -t 10 -i 5 ../../tests/test.map
+	$(JAVA) -Djava.library.path=./ -Djava.library.path=.libs/ -cp tests/threadtest/:./mapscript.jar MapTest -t 10 -i 5 ../../tests/test.map
 
diff --git a/mapscript/java/README b/mapscript/java/README
index c9dc0ac..197bb83 100644
--- a/mapscript/java/README
+++ b/mapscript/java/README
@@ -1,18 +1,14 @@
 Java mapscript
 ==============
 
-Before you begin, the JAVA_HOME environment variable must be properly set
-and the Java programs "java" and "javac" must be on your path.
+WARNING: Starting with version 6.1 Mapserver (and Mapscript) uses libtool to build
+the shared libraries. Some files have changed names and the javamapscript.so shared
+library now depends on libmapserver.so.
+The easiest way way to handle the dependency is to simply use the 'make install'
+target.
 
 To generate the SWIG wrappers you need swig > 1.3.24.
 
-+----------------------------------------------------------------------------+
-| IMPORTANT API CHANGE: swig 1.3.24 introduced a new way of wrapping         |
-| enumerations in Java which breaks compatibility with the mapscript         |
-| generated by previous versions of swig.                                    |
-| This will change again in the next major version of mapserver (version 5). |
-+----------------------------------------------------------------------------+
-
 MAPSCRIPT Reference
 -------------------
 
@@ -32,7 +28,7 @@ MapServer releases, beginning with 4.2.4, contain pre-generated wrapper code
 Nevertheless it is recommended that you generate your own using the "interface"
 target in the Java Makefile.
 
-Requires swig > 1.3.24. Version 1.3.28 or 1.3.29 are recommended.
+Requires swig > 1.3.24. Version above 1.3.28 or 1.3.29 are recommended.
 
 Installation
 ------------
@@ -41,15 +37,13 @@ After MapServer is configured and compiled, change directory to the Java
 mapscript location and execute:
 
     $ cd mapscript/java
-    $ make interface
     $ make
-    $ make test (optional)
+    $ make test (recommended)
     $ make threadtests (optional)
+    $ make install (required as of 6.1)
 
-The 'make interface' step is optional, but strongly recommended, see 'SWIG Wrappers'
-above for the details.
-
-Copy libmapscript.so and mapscript.jar to the appropriate location.
+Remember to set the appropriate variable (LD_LIBRARY_PATH, java.library.path
+or edit /etc/ld.so.conf) to make sure Java can locate and load the libraries.
 
 Windows
 -------
diff --git a/mapscript/java/examples/QueryByAttribute.java b/mapscript/java/examples/QueryByAttribute.java
index d38561d..f991707 100644
--- a/mapscript/java/examples/QueryByAttribute.java
+++ b/mapscript/java/examples/QueryByAttribute.java
@@ -1,6 +1,7 @@
 import edu.umn.gis.mapscript.imageObj;
 import edu.umn.gis.mapscript.mapObj;
 import edu.umn.gis.mapscript.layerObj;
+import edu.umn.gis.mapscript.shapeObj;
 import edu.umn.gis.mapscript.mapscriptConstants;
 
 
@@ -22,7 +23,12 @@ public class QueryByAttribute {
 	layer.queryByAttributes(map,"FNAME", filter, mapscriptConstants.MS_MULTIPLE);
 	layer.open();
 	System.out.println( "Searched for: " +filter );        
-	System.out.println( "Results number (should be always 1): " +layer.getNumResults() );
+	int results=layer.getNumResults();
+	System.out.println( "Results number (should be always 1): " +results );
+	for(int i=0;i<results;i++) {
+		shapeObj shape=layer.getShape(layer.getResult(i));
+		System.out.println( "shape["+i+"]=" +shape );
+	}
 	layer.close();
 
 
diff --git a/mapscript/java/examples/QueryByAttributeUnicode.java b/mapscript/java/examples/QueryByAttributeUnicode.java
index b23988a..80684e7 100644
--- a/mapscript/java/examples/QueryByAttributeUnicode.java
+++ b/mapscript/java/examples/QueryByAttributeUnicode.java
@@ -38,7 +38,13 @@ public class QueryByAttributeUnicode {
 			layer.queryByAttributes(map,"KREIS_NAME", filter, mapscriptConstants.MS_MULTIPLE);
 			layer.open();
 
-			System.out.println( "Results number (should be always 1): " +layer.getNumResults() );
+        		int results=layer.getNumResults();
+		        System.out.println( "Results number (should be always 1): " +results );
+        		for(int i=0;i<results;i++) {
+                		shapeObj shape=layer.getShape(layer.getResult(i));
+		                System.out.println( "shape["+i+"]=" +shape );
+        		}
+
 			layer.close();     
 		}
 	}
diff --git a/mapscript/java/javamodule.i b/mapscript/java/javamodule.i
index 8bcf0db..640aa0d 100644
--- a/mapscript/java/javamodule.i
+++ b/mapscript/java/javamodule.i
@@ -9,7 +9,7 @@
 
 %pragma(java) jniclasscode=%{
     static {
-        String  library = System.getProperty("mapserver.library.name", "mapscript");
+        String  library = System.getProperty("mapserver.library.name", "javamapscript");
 
         System.loadLibrary(library);
         /* TODO Throw when return value not MS_SUCCESS? */
@@ -23,7 +23,7 @@
 
 %typemap(out) gdBuffer
 %{ $result = SWIG_JavaArrayOutSchar(jenv, $1.data, $1.size); 
-   if( $1.owns_data ) gdFree($1.data); %}
+   if( $1.owns_data ) msFree($1.data); %}
 
 %typemap(javain) gdBuffer "$javainput"
 %typemap(javaout) gdBuffer {
@@ -211,12 +211,12 @@ RFC-24 implementation follows
         return clazz;
 }
                 
-%typemap(javacode) layerObj %{
+%typemap(javacode) struct layerObj %{
         /* parent reference, RFC-24 item 3.2 */
         mapObj map=null;
 %}
 
-%typemap(javacode) classObj %{
+%typemap(javacode) struct classObj %{
         /* parent reference, RFC-24 item 3.2 */
         layerObj layer=null;
 %}
diff --git a/mapscript/java/makefile.vc b/mapscript/java/makefile.vc
index 786ab76..fd8fd84 100644
--- a/mapscript/java/makefile.vc
+++ b/mapscript/java/makefile.vc
@@ -22,8 +22,9 @@ JAVA_INCLUDE=-I$(JAVA_HOME)\include -I$(JAVA_HOME)\include\win32
 CC=     cl /MD
 LINK=   link
 
-MS_DLL = mapscript.dll
+MS_DLL = javamapscript.dll
 
+BASE_CFLAGS = 	$(OPTFLAGS) -DWIN32 -D_WIN32
 LDFLAGS =	/NODEFAULTLIB:"MSVCRTD" /NODEFAULTLIB:libcd /NODEFAULTLIB:libcmtd /NODEFAULTLIB:msvcrtd /NODEFAULTLIB:LIBC /DEBUG
 
 
@@ -38,10 +39,10 @@ mapscript_java:
 	$(JAVAC) edu\umn\gis\mapscript\*.java
 
 mapscript_wrap:
-        $(CC) $(MS_CFLAGS) $(JAVA_INCLUDE) /c mapscript_wrap.c  /Fomapscript_wrap.obj
+        $(CC) $(BASE_CFLAGS) $(MS_CFLAGS) $(JAVA_INCLUDE) /c mapscript_wrap.c  /Fomapscript_wrap.obj
 
 .c.obj:	
-	$(CC) $(MS_CFLAGS) $(JAVA_INCLUDE) /c $*.c /Fo$*.obj
+	$(CC) $(BASE_CFLAGS) $(MS_CFLAGS) $(JAVA_INCLUDE) /c $*.c /Fo$*.obj
 
 mapscript_lib: mapscript_wrap.obj
         link /dll /debug \
diff --git a/mapscript/java/tests/threadtest/MapThread.java b/mapscript/java/tests/threadtest/MapThread.java
index 8ef9e88..2bbdf13 100644
--- a/mapscript/java/tests/threadtest/MapThread.java
+++ b/mapscript/java/tests/threadtest/MapThread.java
@@ -43,7 +43,7 @@ public class MapThread extends Thread {
 	       }
 	    }
    	    // We use this to test swig's memory management code
-	    System.gc();
+	    //System.gc();
             //map.draw().save("/tmp/mapthread"+id+"-"+i+".png", map);
             map.draw();
 	    
@@ -57,8 +57,8 @@ public class MapThread extends Thread {
 	layerObj layer = map.getLayer(3);
 	if (layer!=null) {
 		layer.open();
-                layer.queryByIndex(map,0,-1,mapscriptConstants.MS_FALSE);
-                shapeObj shape=layer.getShape(layer.getResults().getResult(0));
+		layer.queryByIndex(map,0,-1,mapscriptConstants.MS_FALSE);
+		shapeObj shape=layer.getShape(layer.getResults().getResult(0));
 		if (shape!=null) {
 			shapeObj buffer=shape.buffer(0.1);
 			if (buffer != null) {
diff --git a/mapscript/mapscript.i b/mapscript/mapscript.i
index e92481c..8eab93a 100644
--- a/mapscript/mapscript.i
+++ b/mapscript/mapscript.i
@@ -38,7 +38,7 @@
 #endif
 
 #ifdef SWIGJAVA
-%ignore layer_obj::extent;
+%ignore layerObj::extent;
 #endif
 
 %{
diff --git a/mapscript/perl/.gitignore b/mapscript/perl/.gitignore
new file mode 100644
index 0000000..494b952
--- /dev/null
+++ b/mapscript/perl/.gitignore
@@ -0,0 +1,5 @@
+blib/*
+mapscript.bs
+mapscript.pm
+mapscript_wrap.c
+pm_to_blib
diff --git a/mapscript/perl/Makefile.PL b/mapscript/perl/Makefile.PL.in
similarity index 95%
rename from mapscript/perl/Makefile.PL
rename to mapscript/perl/Makefile.PL.in
index 1495c42..5b2a13c 100644
--- a/mapscript/perl/Makefile.PL
+++ b/mapscript/perl/Makefile.PL.in
@@ -3,6 +3,9 @@ use ExtUtils::MakeMaker;
 
 open(STREAM, '../../mapscriptvars') or die('Unable to open mapscriptvars, have you built the MapServer yet?'); 
 
+$prefix="@prefix@";
+$exec_prefix="@exec_prefix@";
+$libdir="@libdir@";
 $home = <STREAM>;
 chomp $home;
 
@@ -15,7 +18,7 @@ $inc =~ s/\-I\./\-I$home/g;
 
 $libs = <STREAM>;
 chomp $libs;
-$libs =~ s/\-L\./\-L$home/g;
+$libs = "-L$libdir -lmapserver";
 
 $static_libs = <STREAM>;
 chomp $static_libs;
diff --git a/mapscript/perl/mapscript.pm b/mapscript/perl/mapscript.pm
index cdacc61..9eb6cda 100644
--- a/mapscript/perl/mapscript.pm
+++ b/mapscript/perl/mapscript.pm
@@ -440,6 +440,8 @@ use vars qw(@ISA %OWNER %ITERATORS %BLESSEDMEMBERS);
 *swig_pattern_set = *mapscriptc::styleObj_pattern_set;
 *swig_gap_get = *mapscriptc::styleObj_gap_get;
 *swig_gap_set = *mapscriptc::styleObj_gap_set;
+*swig_initialgap_get = *mapscriptc::styleObj_initialgap_get;
+*swig_initialgap_set = *mapscriptc::styleObj_initialgap_set;
 *swig_position_get = *mapscriptc::styleObj_position_get;
 *swig_position_set = *mapscriptc::styleObj_position_set;
 *swig_linecap_get = *mapscriptc::styleObj_linecap_get;
@@ -460,6 +462,10 @@ use vars qw(@ISA %OWNER %ITERATORS %BLESSEDMEMBERS);
 *swig_offsetx_set = *mapscriptc::styleObj_offsetx_set;
 *swig_offsety_get = *mapscriptc::styleObj_offsety_get;
 *swig_offsety_set = *mapscriptc::styleObj_offsety_set;
+*swig_polaroffsetpixel_get = *mapscriptc::styleObj_polaroffsetpixel_get;
+*swig_polaroffsetpixel_set = *mapscriptc::styleObj_polaroffsetpixel_set;
+*swig_polaroffsetangle_get = *mapscriptc::styleObj_polaroffsetangle_get;
+*swig_polaroffsetangle_set = *mapscriptc::styleObj_polaroffsetangle_set;
 *swig_angle_get = *mapscriptc::styleObj_angle_get;
 *swig_angle_set = *mapscriptc::styleObj_angle_set;
 *swig_antialias_get = *mapscriptc::styleObj_antialias_get;
@@ -506,6 +512,49 @@ sub ACQUIRE {
 }
 
 
+############# Class : mapscript::labelLeaderObj ##############
+
+package mapscript::labelLeaderObj;
+use vars qw(@ISA %OWNER %ITERATORS %BLESSEDMEMBERS);
+ at ISA = qw( mapscript );
+%OWNER = ();
+%ITERATORS = ();
+*swig_maxdistance_get = *mapscriptc::labelLeaderObj_maxdistance_get;
+*swig_maxdistance_set = *mapscriptc::labelLeaderObj_maxdistance_set;
+*swig_gridstep_get = *mapscriptc::labelLeaderObj_gridstep_get;
+*swig_gridstep_set = *mapscriptc::labelLeaderObj_gridstep_set;
+*swig_numstyles_get = *mapscriptc::labelLeaderObj_numstyles_get;
+*swig_numstyles_set = *mapscriptc::labelLeaderObj_numstyles_set;
+sub new {
+    my $pkg = shift;
+    my $self = mapscriptc::new_labelLeaderObj(@_);
+    bless $self, $pkg if defined($self);
+}
+
+sub DESTROY {
+    return unless $_[0]->isa('HASH');
+    my $self = tied(%{$_[0]});
+    return unless defined $self;
+    delete $ITERATORS{$self};
+    if (exists $OWNER{$self}) {
+        mapscriptc::delete_labelLeaderObj($self);
+        delete $OWNER{$self};
+    }
+}
+
+sub DISOWN {
+    my $self = shift;
+    my $ptr = tied(%$self);
+    delete $OWNER{$ptr};
+}
+
+sub ACQUIRE {
+    my $self = shift;
+    my $ptr = tied(%$self);
+    $OWNER{$ptr} = 1;
+}
+
+
 ############# Class : mapscript::labelObj ##############
 
 package mapscript::labelObj;
@@ -513,6 +562,8 @@ use vars qw(@ISA %OWNER %ITERATORS %BLESSEDMEMBERS);
 @ISA = qw( mapscript );
 %OWNER = ();
 %ITERATORS = ();
+*swig_refcount_get = *mapscriptc::labelObj_refcount_get;
+*swig_refcount_set = *mapscriptc::labelObj_refcount_set;
 *swig_font_get = *mapscriptc::labelObj_font_get;
 *swig_font_set = *mapscriptc::labelObj_font_set;
 *swig_type_get = *mapscriptc::labelObj_type_get;
@@ -581,17 +632,18 @@ use vars qw(@ISA %OWNER %ITERATORS %BLESSEDMEMBERS);
 *swig_encoding_set = *mapscriptc::labelObj_encoding_set;
 *swig_priority_get = *mapscriptc::labelObj_priority_get;
 *swig_priority_set = *mapscriptc::labelObj_priority_set;
+*swig_status_get = *mapscriptc::labelObj_status_get;
+*swig_status_set = *mapscriptc::labelObj_status_set;
 *swig_numstyles_get = *mapscriptc::labelObj_numstyles_get;
 *swig_numstyles_set = *mapscriptc::labelObj_numstyles_set;
-*updateFromString = *mapscriptc::labelObj_updateFromString;
-*removeBinding = *mapscriptc::labelObj_removeBinding;
-*getBinding = *mapscriptc::labelObj_getBinding;
-*setBinding = *mapscriptc::labelObj_setBinding;
-*getStyle = *mapscriptc::labelObj_getStyle;
-*insertStyle = *mapscriptc::labelObj_insertStyle;
-*removeStyle = *mapscriptc::labelObj_removeStyle;
-*moveStyleUp = *mapscriptc::labelObj_moveStyleUp;
-*moveStyleDown = *mapscriptc::labelObj_moveStyleDown;
+*swig_annotext_get = *mapscriptc::labelObj_annotext_get;
+*swig_annotext_set = *mapscriptc::labelObj_annotext_set;
+*swig_annopoint_get = *mapscriptc::labelObj_annopoint_get;
+*swig_annopoint_set = *mapscriptc::labelObj_annopoint_set;
+*swig_annopoly_get = *mapscriptc::labelObj_annopoly_get;
+*swig_annopoly_set = *mapscriptc::labelObj_annopoly_set;
+*swig_leader_get = *mapscriptc::labelObj_leader_get;
+*swig_leader_set = *mapscriptc::labelObj_leader_set;
 sub new {
     my $pkg = shift;
     my $self = mapscriptc::new_labelObj(@_);
@@ -609,6 +661,19 @@ sub DESTROY {
     }
 }
 
+*updateFromString = *mapscriptc::labelObj_updateFromString;
+*removeBinding = *mapscriptc::labelObj_removeBinding;
+*getBinding = *mapscriptc::labelObj_getBinding;
+*setBinding = *mapscriptc::labelObj_setBinding;
+*setExpression = *mapscriptc::labelObj_setExpression;
+*getExpressionString = *mapscriptc::labelObj_getExpressionString;
+*setText = *mapscriptc::labelObj_setText;
+*getTextString = *mapscriptc::labelObj_getTextString;
+*getStyle = *mapscriptc::labelObj_getStyle;
+*insertStyle = *mapscriptc::labelObj_insertStyle;
+*removeStyle = *mapscriptc::labelObj_removeStyle;
+*moveStyleUp = *mapscriptc::labelObj_moveStyleUp;
+*moveStyleDown = *mapscriptc::labelObj_moveStyleDown;
 sub DISOWN {
     my $self = shift;
     my $ptr = tied(%$self);
@@ -633,8 +698,8 @@ use vars qw(@ISA %OWNER %ITERATORS %BLESSEDMEMBERS);
 *swig_status_set = *mapscriptc::classObj_status_set;
 *swig_numstyles_get = *mapscriptc::classObj_numstyles_get;
 *swig_numstyles_set = *mapscriptc::classObj_numstyles_set;
-*swig_label_get = *mapscriptc::classObj_label_get;
-*swig_label_set = *mapscriptc::classObj_label_set;
+*swig_numlabels_get = *mapscriptc::classObj_numlabels_get;
+*swig_numlabels_set = *mapscriptc::classObj_numlabels_set;
 *swig_name_get = *mapscriptc::classObj_name_get;
 *swig_name_set = *mapscriptc::classObj_name_set;
 *swig_title_get = *mapscriptc::classObj_title_get;
@@ -663,6 +728,8 @@ use vars qw(@ISA %OWNER %ITERATORS %BLESSEDMEMBERS);
 *swig_keyimage_set = *mapscriptc::classObj_keyimage_set;
 *swig_group_get = *mapscriptc::classObj_group_get;
 *swig_group_set = *mapscriptc::classObj_group_set;
+*swig_leader_get = *mapscriptc::classObj_leader_get;
+*swig_leader_set = *mapscriptc::classObj_leader_set;
 sub new {
         my $pkg = shift;
         my $self = mapscriptc::new_classObj(@_);
@@ -696,6 +763,9 @@ sub DESTROY {
 *getNextMetaDataKey = *mapscriptc::classObj_getNextMetaDataKey;
 *drawLegendIcon = *mapscriptc::classObj_drawLegendIcon;
 *createLegendIcon = *mapscriptc::classObj_createLegendIcon;
+*getLabel = *mapscriptc::classObj_getLabel;
+*addLabel = *mapscriptc::classObj_addLabel;
+*removeLabel = *mapscriptc::classObj_removeLabel;
 *getStyle = *mapscriptc::classObj_getStyle;
 *insertStyle = *mapscriptc::classObj_insertStyle;
 *removeStyle = *mapscriptc::classObj_removeStyle;
@@ -721,24 +791,20 @@ use vars qw(@ISA %OWNER %ITERATORS %BLESSEDMEMBERS);
 @ISA = qw( mapscript );
 %OWNER = ();
 %ITERATORS = ();
-*swig_text_get = *mapscriptc::labelCacheMemberObj_text_get;
-*swig_text_set = *mapscriptc::labelCacheMemberObj_text_set;
 *swig_featuresize_get = *mapscriptc::labelCacheMemberObj_featuresize_get;
 *swig_featuresize_set = *mapscriptc::labelCacheMemberObj_featuresize_set;
 *swig_styles_get = *mapscriptc::labelCacheMemberObj_styles_get;
 *swig_styles_set = *mapscriptc::labelCacheMemberObj_styles_set;
 *swig_numstyles_get = *mapscriptc::labelCacheMemberObj_numstyles_get;
 *swig_numstyles_set = *mapscriptc::labelCacheMemberObj_numstyles_set;
-*swig_label_get = *mapscriptc::labelCacheMemberObj_label_get;
-*swig_label_set = *mapscriptc::labelCacheMemberObj_label_set;
+*swig_labels_get = *mapscriptc::labelCacheMemberObj_labels_get;
+*swig_labels_set = *mapscriptc::labelCacheMemberObj_labels_set;
+*swig_numlabels_get = *mapscriptc::labelCacheMemberObj_numlabels_get;
+*swig_numlabels_set = *mapscriptc::labelCacheMemberObj_numlabels_set;
 *swig_layerindex_get = *mapscriptc::labelCacheMemberObj_layerindex_get;
 *swig_layerindex_set = *mapscriptc::labelCacheMemberObj_layerindex_set;
 *swig_classindex_get = *mapscriptc::labelCacheMemberObj_classindex_get;
 *swig_classindex_set = *mapscriptc::labelCacheMemberObj_classindex_set;
-*swig_tileindex_get = *mapscriptc::labelCacheMemberObj_tileindex_get;
-*swig_tileindex_set = *mapscriptc::labelCacheMemberObj_tileindex_set;
-*swig_shapeindex_get = *mapscriptc::labelCacheMemberObj_shapeindex_get;
-*swig_shapeindex_set = *mapscriptc::labelCacheMemberObj_shapeindex_set;
 *swig_shapetype_get = *mapscriptc::labelCacheMemberObj_shapetype_get;
 *swig_shapetype_set = *mapscriptc::labelCacheMemberObj_shapetype_set;
 *swig_point_get = *mapscriptc::labelCacheMemberObj_point_get;
@@ -749,6 +815,10 @@ use vars qw(@ISA %OWNER %ITERATORS %BLESSEDMEMBERS);
 *swig_status_set = *mapscriptc::labelCacheMemberObj_status_set;
 *swig_markerid_get = *mapscriptc::labelCacheMemberObj_markerid_get;
 *swig_markerid_set = *mapscriptc::labelCacheMemberObj_markerid_set;
+*swig_leaderline_get = *mapscriptc::labelCacheMemberObj_leaderline_get;
+*swig_leaderline_set = *mapscriptc::labelCacheMemberObj_leaderline_set;
+*swig_leaderbbox_get = *mapscriptc::labelCacheMemberObj_leaderbbox_get;
+*swig_leaderbbox_set = *mapscriptc::labelCacheMemberObj_leaderbbox_set;
 sub new {
     my $pkg = shift;
     my $self = mapscriptc::new_labelCacheMemberObj(@_);
@@ -880,6 +950,8 @@ use vars qw(@ISA %OWNER %ITERATORS %BLESSEDMEMBERS);
 *swig_slots_set = *mapscriptc::labelCacheObj_slots_set;
 *swig_numlabels_get = *mapscriptc::labelCacheObj_numlabels_get;
 *swig_numlabels_set = *mapscriptc::labelCacheObj_numlabels_set;
+*swig_gutter_get = *mapscriptc::labelCacheObj_gutter_get;
+*swig_gutter_set = *mapscriptc::labelCacheObj_gutter_set;
 *freeCache = *mapscriptc::labelCacheObj_freeCache;
 sub new {
     my $pkg = shift;
@@ -1247,6 +1319,61 @@ sub ACQUIRE {
 }
 
 
+############# Class : mapscript::imageObj ##############
+
+package mapscript::imageObj;
+use vars qw(@ISA %OWNER %ITERATORS %BLESSEDMEMBERS);
+ at ISA = qw( mapscript );
+%OWNER = ();
+%ITERATORS = ();
+*swig_width_get = *mapscriptc::imageObj_width_get;
+*swig_width_set = *mapscriptc::imageObj_width_set;
+*swig_height_get = *mapscriptc::imageObj_height_get;
+*swig_height_set = *mapscriptc::imageObj_height_set;
+*swig_resolution_get = *mapscriptc::imageObj_resolution_get;
+*swig_resolution_set = *mapscriptc::imageObj_resolution_set;
+*swig_resolutionfactor_get = *mapscriptc::imageObj_resolutionfactor_get;
+*swig_resolutionfactor_set = *mapscriptc::imageObj_resolutionfactor_set;
+*swig_imagepath_get = *mapscriptc::imageObj_imagepath_get;
+*swig_imagepath_set = *mapscriptc::imageObj_imagepath_set;
+*swig_imageurl_get = *mapscriptc::imageObj_imageurl_get;
+*swig_imageurl_set = *mapscriptc::imageObj_imageurl_set;
+*swig_format_get = *mapscriptc::imageObj_format_get;
+*swig_format_set = *mapscriptc::imageObj_format_set;
+sub new {
+    my $pkg = shift;
+    my $self = mapscriptc::new_imageObj(@_);
+    bless $self, $pkg if defined($self);
+}
+
+sub DESTROY {
+    return unless $_[0]->isa('HASH');
+    my $self = tied(%{$_[0]});
+    return unless defined $self;
+    delete $ITERATORS{$self};
+    if (exists $OWNER{$self}) {
+        mapscriptc::delete_imageObj($self);
+        delete $OWNER{$self};
+    }
+}
+
+*save = *mapscriptc::imageObj_save;
+*write = *mapscriptc::imageObj_write;
+*getBytes = *mapscriptc::imageObj_getBytes;
+*getSize = *mapscriptc::imageObj_getSize;
+sub DISOWN {
+    my $self = shift;
+    my $ptr = tied(%$self);
+    delete $OWNER{$ptr};
+}
+
+sub ACQUIRE {
+    my $self = shift;
+    my $ptr = tied(%$self);
+    $OWNER{$ptr} = 1;
+}
+
+
 ############# Class : mapscript::layerObj ##############
 
 package mapscript::layerObj;
@@ -1366,6 +1493,8 @@ use vars qw(@ISA %OWNER %ITERATORS %BLESSEDMEMBERS);
 *swig_numjoins_set = *mapscriptc::layerObj_numjoins_set;
 *swig_classgroup_get = *mapscriptc::layerObj_classgroup_get;
 *swig_classgroup_set = *mapscriptc::layerObj_classgroup_set;
+*swig_mask_get = *mapscriptc::layerObj_mask_get;
+*swig_mask_set = *mapscriptc::layerObj_mask_set;
 sub new {
         my $pkg = shift;
         my $self = mapscriptc::new_layerObj(@_);
@@ -1416,6 +1545,7 @@ sub getClass {
 }
 
 *getItem = *mapscriptc::layerObj_getItem;
+*setItems = *mapscriptc::layerObj_setItems;
 *draw = *mapscriptc::layerObj_draw;
 *drawQuery = *mapscriptc::layerObj_drawQuery;
 *queryByFilter = *mapscriptc::layerObj_queryByFilter;
@@ -1676,61 +1806,6 @@ sub ACQUIRE {
 }
 
 
-############# Class : mapscript::imageObj ##############
-
-package mapscript::imageObj;
-use vars qw(@ISA %OWNER %ITERATORS %BLESSEDMEMBERS);
- at ISA = qw( mapscript );
-%OWNER = ();
-%ITERATORS = ();
-*swig_width_get = *mapscriptc::imageObj_width_get;
-*swig_width_set = *mapscriptc::imageObj_width_set;
-*swig_height_get = *mapscriptc::imageObj_height_get;
-*swig_height_set = *mapscriptc::imageObj_height_set;
-*swig_resolution_get = *mapscriptc::imageObj_resolution_get;
-*swig_resolution_set = *mapscriptc::imageObj_resolution_set;
-*swig_resolutionfactor_get = *mapscriptc::imageObj_resolutionfactor_get;
-*swig_resolutionfactor_set = *mapscriptc::imageObj_resolutionfactor_set;
-*swig_imagepath_get = *mapscriptc::imageObj_imagepath_get;
-*swig_imagepath_set = *mapscriptc::imageObj_imagepath_set;
-*swig_imageurl_get = *mapscriptc::imageObj_imageurl_get;
-*swig_imageurl_set = *mapscriptc::imageObj_imageurl_set;
-*swig_format_get = *mapscriptc::imageObj_format_get;
-*swig_format_set = *mapscriptc::imageObj_format_set;
-sub new {
-    my $pkg = shift;
-    my $self = mapscriptc::new_imageObj(@_);
-    bless $self, $pkg if defined($self);
-}
-
-sub DESTROY {
-    return unless $_[0]->isa('HASH');
-    my $self = tied(%{$_[0]});
-    return unless defined $self;
-    delete $ITERATORS{$self};
-    if (exists $OWNER{$self}) {
-        mapscriptc::delete_imageObj($self);
-        delete $OWNER{$self};
-    }
-}
-
-*save = *mapscriptc::imageObj_save;
-*write = *mapscriptc::imageObj_write;
-*getBytes = *mapscriptc::imageObj_getBytes;
-*getSize = *mapscriptc::imageObj_getSize;
-sub DISOWN {
-    my $self = shift;
-    my $ptr = tied(%$self);
-    delete $OWNER{$ptr};
-}
-
-sub ACQUIRE {
-    my $self = shift;
-    my $ptr = tied(%$self);
-    $OWNER{$ptr} = 1;
-}
-
-
 ############# Class : mapscript::strokeStyleObj ##############
 
 package mapscript::strokeStyleObj;
@@ -1744,6 +1819,8 @@ use vars qw(@ISA %OWNER %ITERATORS %BLESSEDMEMBERS);
 *swig_patternlength_set = *mapscriptc::strokeStyleObj_patternlength_set;
 *swig_pattern_get = *mapscriptc::strokeStyleObj_pattern_get;
 *swig_pattern_set = *mapscriptc::strokeStyleObj_pattern_set;
+*swig_patternoffset_get = *mapscriptc::strokeStyleObj_patternoffset_get;
+*swig_patternoffset_set = *mapscriptc::strokeStyleObj_patternoffset_set;
 *swig_color_get = *mapscriptc::strokeStyleObj_color_get;
 *swig_color_set = *mapscriptc::strokeStyleObj_color_set;
 *swig_linecap_get = *mapscriptc::strokeStyleObj_linecap_get;
@@ -1901,8 +1978,10 @@ use vars qw(@ISA %OWNER %ITERATORS %BLESSEDMEMBERS);
 @ISA = qw( mapscript );
 %OWNER = ();
 %ITERATORS = ();
-*swig_font_get = *mapscriptc::labelStyleObj_font_get;
-*swig_font_set = *mapscriptc::labelStyleObj_font_set;
+*swig_fonts_get = *mapscriptc::labelStyleObj_fonts_get;
+*swig_fonts_set = *mapscriptc::labelStyleObj_fonts_set;
+*swig_numfonts_get = *mapscriptc::labelStyleObj_numfonts_get;
+*swig_numfonts_set = *mapscriptc::labelStyleObj_numfonts_set;
 *swig_size_get = *mapscriptc::labelStyleObj_size_get;
 *swig_size_set = *mapscriptc::labelStyleObj_size_set;
 *swig_rotation_get = *mapscriptc::labelStyleObj_rotation_get;
@@ -1913,6 +1992,8 @@ use vars qw(@ISA %OWNER %ITERATORS %BLESSEDMEMBERS);
 *swig_outlinewidth_set = *mapscriptc::labelStyleObj_outlinewidth_set;
 *swig_outlinecolor_get = *mapscriptc::labelStyleObj_outlinecolor_get;
 *swig_outlinecolor_set = *mapscriptc::labelStyleObj_outlinecolor_set;
+*swig_antialias_get = *mapscriptc::labelStyleObj_antialias_get;
+*swig_antialias_set = *mapscriptc::labelStyleObj_antialias_set;
 sub new {
     my $pkg = shift;
     my $self = mapscriptc::new_labelStyleObj(@_);
@@ -2327,6 +2408,8 @@ use vars qw(@ISA %OWNER %ITERATORS %BLESSEDMEMBERS);
 *swig_numargs_set = *mapscriptc::projectionObj_numargs_set;
 *swig_automatic_get = *mapscriptc::projectionObj_automatic_get;
 *swig_automatic_set = *mapscriptc::projectionObj_automatic_set;
+*swig_wellknownprojection_get = *mapscriptc::projectionObj_wellknownprojection_get;
+*swig_wellknownprojection_set = *mapscriptc::projectionObj_wellknownprojection_set;
 sub new {
     my $pkg = shift;
     my $self = mapscriptc::new_projectionObj(@_);
@@ -2366,8 +2449,6 @@ use vars qw(@ISA %OWNER %ITERATORS %BLESSEDMEMBERS);
 @ISA = qw( mapscript );
 %OWNER = ();
 %ITERATORS = ();
-*swig_pen_get = *mapscriptc::colorObj_pen_get;
-*swig_pen_set = *mapscriptc::colorObj_pen_set;
 *swig_red_get = *mapscriptc::colorObj_red_get;
 *swig_red_set = *mapscriptc::colorObj_red_set;
 *swig_green_get = *mapscriptc::colorObj_green_get;
@@ -2440,6 +2521,10 @@ use vars qw(@ISA %OWNER %ITERATORS %BLESSEDMEMBERS);
 *swig_numpoints_set = *mapscriptc::symbolObj_numpoints_set;
 *swig_filled_get = *mapscriptc::symbolObj_filled_get;
 *swig_filled_set = *mapscriptc::symbolObj_filled_set;
+*swig_anchorpoint_x_get = *mapscriptc::symbolObj_anchorpoint_x_get;
+*swig_anchorpoint_x_set = *mapscriptc::symbolObj_anchorpoint_x_set;
+*swig_anchorpoint_y_get = *mapscriptc::symbolObj_anchorpoint_y_get;
+*swig_anchorpoint_y_set = *mapscriptc::symbolObj_anchorpoint_y_set;
 *swig_imagepath_get = *mapscriptc::symbolObj_imagepath_get;
 *swig_imagepath_set = *mapscriptc::symbolObj_imagepath_set;
 *swig_transparent_get = *mapscriptc::symbolObj_transparent_get;
@@ -2616,6 +2701,7 @@ sub DESTROY {
 *loadParams = *mapscriptc::OWSRequest_loadParams;
 *loadParamsFromURL = *mapscriptc::OWSRequest_loadParamsFromURL;
 *setParameter = *mapscriptc::OWSRequest_setParameter;
+*addParameter = *mapscriptc::OWSRequest_addParameter;
 *getName = *mapscriptc::OWSRequest_getName;
 *getValue = *mapscriptc::OWSRequest_getValue;
 *getValueByName = *mapscriptc::OWSRequest_getValueByName;
@@ -2641,7 +2727,6 @@ package mapscript;
 *MS_VERSION_MINOR = *mapscriptc::MS_VERSION_MINOR;
 *MS_VERSION_REV = *mapscriptc::MS_VERSION_REV;
 *MS_VERSION_NUM = *mapscriptc::MS_VERSION_NUM;
-*__FUNCTION__ = *mapscriptc::__FUNCTION__;
 *MS_TRUE = *mapscriptc::MS_TRUE;
 *MS_FALSE = *mapscriptc::MS_FALSE;
 *MS_UNKNOWN = *mapscriptc::MS_UNKNOWN;
@@ -2656,8 +2741,11 @@ package mapscript;
 *MS_LAYER_ALLOCSIZE = *mapscriptc::MS_LAYER_ALLOCSIZE;
 *MS_CLASS_ALLOCSIZE = *mapscriptc::MS_CLASS_ALLOCSIZE;
 *MS_STYLE_ALLOCSIZE = *mapscriptc::MS_STYLE_ALLOCSIZE;
+*MS_LABEL_ALLOCSIZE = *mapscriptc::MS_LABEL_ALLOCSIZE;
 *MS_MAX_LABEL_PRIORITY = *mapscriptc::MS_MAX_LABEL_PRIORITY;
+*MS_MAX_LABEL_FONTS = *mapscriptc::MS_MAX_LABEL_FONTS;
 *MS_DEFAULT_LABEL_PRIORITY = *mapscriptc::MS_DEFAULT_LABEL_PRIORITY;
+*MS_LABEL_FORCE_GROUP = *mapscriptc::MS_LABEL_FORCE_GROUP;
 *MS_RENDER_WITH_SWF = *mapscriptc::MS_RENDER_WITH_SWF;
 *MS_RENDER_WITH_RAWDATA = *mapscriptc::MS_RENDER_WITH_RAWDATA;
 *MS_RENDER_WITH_IMAGEMAP = *mapscriptc::MS_RENDER_WITH_IMAGEMAP;
@@ -2735,6 +2823,7 @@ package mapscript;
 *MS_RASTER = *mapscriptc::MS_RASTER;
 *MS_PLUGIN = *mapscriptc::MS_PLUGIN;
 *MS_UNION = *mapscriptc::MS_UNION;
+*MS_UVRASTER = *mapscriptc::MS_UVRASTER;
 *MS_DB_XBASE = *mapscriptc::MS_DB_XBASE;
 *MS_DB_CSV = *mapscriptc::MS_DB_CSV;
 *MS_DB_MYSQL = *mapscriptc::MS_DB_MYSQL;
@@ -2799,6 +2888,10 @@ package mapscript;
 *MS_STYLE_BINDING_SYMBOL = *mapscriptc::MS_STYLE_BINDING_SYMBOL;
 *MS_STYLE_BINDING_OUTLINEWIDTH = *mapscriptc::MS_STYLE_BINDING_OUTLINEWIDTH;
 *MS_STYLE_BINDING_OPACITY = *mapscriptc::MS_STYLE_BINDING_OPACITY;
+*MS_STYLE_BINDING_OFFSET_X = *mapscriptc::MS_STYLE_BINDING_OFFSET_X;
+*MS_STYLE_BINDING_OFFSET_Y = *mapscriptc::MS_STYLE_BINDING_OFFSET_Y;
+*MS_STYLE_BINDING_POLAROFFSET_PIXEL = *mapscriptc::MS_STYLE_BINDING_POLAROFFSET_PIXEL;
+*MS_STYLE_BINDING_POLAROFFSET_ANGLE = *mapscriptc::MS_STYLE_BINDING_POLAROFFSET_ANGLE;
 *MS_LABEL_BINDING_LENGTH = *mapscriptc::MS_LABEL_BINDING_LENGTH;
 *MS_LABEL_BINDING_SIZE = *mapscriptc::MS_LABEL_BINDING_SIZE;
 *MS_LABEL_BINDING_ANGLE = *mapscriptc::MS_LABEL_BINDING_ANGLE;
@@ -2843,6 +2936,7 @@ package mapscript;
 *MS_TOKEN_FUNCTION_ROUND = *mapscriptc::MS_TOKEN_FUNCTION_ROUND;
 *MS_TOKEN_FUNCTION_FROMTEXT = *mapscriptc::MS_TOKEN_FUNCTION_FROMTEXT;
 *MS_TOKEN_FUNCTION_BUFFER = *mapscriptc::MS_TOKEN_FUNCTION_BUFFER;
+*MS_TOKEN_FUNCTION_DIFFERENCE = *mapscriptc::MS_TOKEN_FUNCTION_DIFFERENCE;
 *MS_TOKEN_BINDING_DOUBLE = *mapscriptc::MS_TOKEN_BINDING_DOUBLE;
 *MS_TOKEN_BINDING_INTEGER = *mapscriptc::MS_TOKEN_BINDING_INTEGER;
 *MS_TOKEN_BINDING_STRING = *mapscriptc::MS_TOKEN_BINDING_STRING;
@@ -2869,6 +2963,9 @@ package mapscript;
 *FTInteger = *mapscriptc::FTInteger;
 *FTDouble = *mapscriptc::FTDouble;
 *FTInvalid = *mapscriptc::FTInvalid;
+*wkp_none = *mapscriptc::wkp_none;
+*wkp_lonlat = *mapscriptc::wkp_lonlat;
+*wkp_gmerc = *mapscriptc::wkp_gmerc;
 *MS_SYMBOL_SIMPLE = *mapscriptc::MS_SYMBOL_SIMPLE;
 *MS_SYMBOL_VECTOR = *mapscriptc::MS_SYMBOL_VECTOR;
 *MS_SYMBOL_ELLIPSE = *mapscriptc::MS_SYMBOL_ELLIPSE;
diff --git a/mapscript/perl/mapscript_wrap.c b/mapscript/perl/mapscript_wrap.c
index 36bf859..d46fea5 100644
--- a/mapscript/perl/mapscript_wrap.c
+++ b/mapscript/perl/mapscript_wrap.c
@@ -1496,12 +1496,12 @@ SWIG_Perl_SetModule(swig_module_info *module) {
 #define SWIGTYPE_p_FILE swig_types[2]
 #define SWIGTYPE_p_cgiRequestObj swig_types[3]
 #define SWIGTYPE_p_char swig_types[4]
-#define SWIGTYPE_p_class_obj swig_types[5]
+#define SWIGTYPE_p_classObj swig_types[5]
 #define SWIGTYPE_p_clusterObj swig_types[6]
 #define SWIGTYPE_p_colorObj swig_types[7]
 #define SWIGTYPE_p_debugLevel swig_types[8]
 #define SWIGTYPE_p_double swig_types[9]
-#define SWIGTYPE_p_error_obj swig_types[10]
+#define SWIGTYPE_p_errorObj swig_types[10]
 #define SWIGTYPE_p_fontSetObj swig_types[11]
 #define SWIGTYPE_p_hashTableObj swig_types[12]
 #define SWIGTYPE_p_imageObj swig_types[13]
@@ -1511,37 +1511,38 @@ SWIG_Perl_SetModule(swig_module_info *module) {
 #define SWIGTYPE_p_labelCacheMemberObj swig_types[17]
 #define SWIGTYPE_p_labelCacheObj swig_types[18]
 #define SWIGTYPE_p_labelCacheSlotObj swig_types[19]
-#define SWIGTYPE_p_labelObj swig_types[20]
-#define SWIGTYPE_p_labelStyleObj swig_types[21]
-#define SWIGTYPE_p_layer_obj swig_types[22]
-#define SWIGTYPE_p_legendObj swig_types[23]
-#define SWIGTYPE_p_lineObj swig_types[24]
-#define SWIGTYPE_p_map_obj swig_types[25]
-#define SWIGTYPE_p_markerCacheMemberObj swig_types[26]
-#define SWIGTYPE_p_outputFormatObj swig_types[27]
-#define SWIGTYPE_p_p_char swig_types[28]
-#define SWIGTYPE_p_p_outputFormatObj swig_types[29]
-#define SWIGTYPE_p_pointObj swig_types[30]
-#define SWIGTYPE_p_projectionObj swig_types[31]
-#define SWIGTYPE_p_queryMapObj swig_types[32]
-#define SWIGTYPE_p_rectObj swig_types[33]
-#define SWIGTYPE_p_referenceMapObj swig_types[34]
-#define SWIGTYPE_p_rendererVTableObj swig_types[35]
-#define SWIGTYPE_p_resultCacheObj swig_types[36]
-#define SWIGTYPE_p_resultObj swig_types[37]
-#define SWIGTYPE_p_scalebarObj swig_types[38]
-#define SWIGTYPE_p_shapeObj swig_types[39]
-#define SWIGTYPE_p_shapefileObj swig_types[40]
-#define SWIGTYPE_p_strokeStyleObj swig_types[41]
-#define SWIGTYPE_p_styleObj swig_types[42]
-#define SWIGTYPE_p_symbolObj swig_types[43]
-#define SWIGTYPE_p_symbolSetObj swig_types[44]
-#define SWIGTYPE_p_symbolStyleObj swig_types[45]
-#define SWIGTYPE_p_tileCacheObj swig_types[46]
-#define SWIGTYPE_p_uint32_t swig_types[47]
-#define SWIGTYPE_p_webObj swig_types[48]
-static swig_type_info *swig_types[50];
-static swig_module_info swig_module = {swig_types, 49, 0, 0, 0, 0};
+#define SWIGTYPE_p_labelLeaderObj swig_types[20]
+#define SWIGTYPE_p_labelObj swig_types[21]
+#define SWIGTYPE_p_labelStyleObj swig_types[22]
+#define SWIGTYPE_p_layerObj swig_types[23]
+#define SWIGTYPE_p_legendObj swig_types[24]
+#define SWIGTYPE_p_lineObj swig_types[25]
+#define SWIGTYPE_p_mapObj swig_types[26]
+#define SWIGTYPE_p_markerCacheMemberObj swig_types[27]
+#define SWIGTYPE_p_outputFormatObj swig_types[28]
+#define SWIGTYPE_p_p_char swig_types[29]
+#define SWIGTYPE_p_p_outputFormatObj swig_types[30]
+#define SWIGTYPE_p_pointObj swig_types[31]
+#define SWIGTYPE_p_projectionObj swig_types[32]
+#define SWIGTYPE_p_queryMapObj swig_types[33]
+#define SWIGTYPE_p_rectObj swig_types[34]
+#define SWIGTYPE_p_referenceMapObj swig_types[35]
+#define SWIGTYPE_p_rendererVTableObj swig_types[36]
+#define SWIGTYPE_p_resultCacheObj swig_types[37]
+#define SWIGTYPE_p_resultObj swig_types[38]
+#define SWIGTYPE_p_scalebarObj swig_types[39]
+#define SWIGTYPE_p_shapeObj swig_types[40]
+#define SWIGTYPE_p_shapefileObj swig_types[41]
+#define SWIGTYPE_p_strokeStyleObj swig_types[42]
+#define SWIGTYPE_p_styleObj swig_types[43]
+#define SWIGTYPE_p_symbolObj swig_types[44]
+#define SWIGTYPE_p_symbolSetObj swig_types[45]
+#define SWIGTYPE_p_symbolStyleObj swig_types[46]
+#define SWIGTYPE_p_tileCacheObj swig_types[47]
+#define SWIGTYPE_p_uint32_t swig_types[48]
+#define SWIGTYPE_p_webObj swig_types[49]
+static swig_type_info *swig_types[51];
+static swig_module_info swig_module = {swig_types, 50, 0, 0, 0, 0};
 #define SWIG_TypeQuery(name) SWIG_TypeQueryModule(&swig_module, &swig_module, name)
 #define SWIG_MangledTypeQuery(name) SWIG_MangledTypeQueryModule(&swig_module, &swig_module, name)
 
@@ -2073,7 +2074,7 @@ SWIGINTERN int styleObj_setSymbolByName(styleObj *self,mapObj *map,char *symboln
         return self->symbol;
     }
 SWIGINTERN int styleObj_removeBinding(styleObj *self,int binding){
-    if(binding < 0 || binding >= 8) return MS_FAILURE;
+    if(binding < 0 || binding >= 12) return MS_FAILURE;
 
     if(self->bindings[binding].item) {
       free(self->bindings[binding].item);
@@ -2086,7 +2087,7 @@ SWIGINTERN int styleObj_removeBinding(styleObj *self,int binding){
   }
 SWIGINTERN int styleObj_setBinding(styleObj *self,int binding,char *item){
     if(!item) return MS_FAILURE;
-    if(binding < 0 || binding >= 8) return MS_FAILURE;
+    if(binding < 0 || binding >= 12) return MS_FAILURE;
 
     if(self->bindings[binding].item) {
       free(self->bindings[binding].item);
@@ -2101,7 +2102,7 @@ SWIGINTERN int styleObj_setBinding(styleObj *self,int binding,char *item){
     return MS_SUCCESS;
   }
 SWIGINTERN char *styleObj_getBinding(styleObj *self,int binding){
-    if(binding < 0 || binding >= 8) return NULL;
+    if(binding < 0 || binding >= 12) return NULL;
 
     return self->bindings[binding].item;
   }
@@ -2161,6 +2162,20 @@ SWIG_From_char  SWIG_PERL_DECL_ARGS_1(char c)
   return SWIG_FromCharPtrAndSize(&c,1);
 }
 
+SWIGINTERN labelObj *new_labelObj(){
+      labelObj *label;
+        
+      label = (labelObj *)calloc(1, sizeof(labelObj));
+      if (!label)
+        return(NULL);
+    
+      initLabel(label);
+      
+      return(label);    	
+    }
+SWIGINTERN void delete_labelObj(labelObj *self){
+      freeLabel(self);
+    }
 SWIGINTERN int labelObj_updateFromString(labelObj *self,char *snippet){
     return msUpdateLabelFromString(self, snippet);
   }
@@ -2197,6 +2212,26 @@ SWIGINTERN int labelObj_setBinding(labelObj *self,int binding,char *item){
 
     return MS_SUCCESS;
   }
+SWIGINTERN int labelObj_setExpression(labelObj *self,char *expression){
+    if (!expression || strlen(expression) == 0) {
+       freeExpression(&self->expression);
+       return MS_SUCCESS;
+    }
+    else return msLoadExpressionString(&self->expression, expression);
+  }
+SWIGINTERN char *labelObj_getExpressionString(labelObj *self){
+    return msGetExpressionString(&(self->expression));
+  }
+SWIGINTERN int labelObj_setText(labelObj *self,char *text){
+    if (!text || strlen(text) == 0) {
+      freeExpression(&self->text);
+      return MS_SUCCESS;
+    }	
+    else return msLoadExpressionString(&self->text, text);
+  }
+SWIGINTERN char *labelObj_getTextString(labelObj *self){
+    return msGetExpressionString(&(self->text));
+  }
 SWIGINTERN styleObj *labelObj_getStyle(labelObj *self,int i){
       if (i >= 0 && i < self->numstyles) {
           MS_REFCNT_INCR(self->styles[i]);
@@ -2342,30 +2377,46 @@ SWIGINTERN int classObj_drawLegendIcon(classObj *self,mapObj *map,layerObj *laye
 SWIGINTERN imageObj *classObj_createLegendIcon(classObj *self,mapObj *map,layerObj *layer,int width,int height){
     return msCreateLegendIcon(map, layer, self, width, height);
   }
+SWIGINTERN labelObj *classObj_getLabel(classObj *self,int i){
+    if (i >= 0 && i < self->numlabels) {
+      MS_REFCNT_INCR(self->labels[i]);
+      return self->labels[i];
+    } else {
+      msSetError(31, "Invalid index: %d.", "getLabel()", i);
+      return NULL;
+    }
+  }
+SWIGINTERN int classObj_addLabel(classObj *self,labelObj *label){
+    return msAddLabelToClass(self, label);
+  }
+SWIGINTERN labelObj *classObj_removeLabel(classObj *self,int index){
+    labelObj* label = (labelObj *) msRemoveLabelFromClass(self, index);
+    if (label) MS_REFCNT_INCR(label);
+    return label;
+  }
 SWIGINTERN styleObj *classObj_getStyle(classObj *self,int i){
-        if (i >= 0 && i < self->numstyles) {
-	    MS_REFCNT_INCR(self->styles[i]);
-            return self->styles[i];
-	} else {
-            msSetError(31, "Invalid index: %d", "getStyle()", i);
-            return NULL;
-        }
+    if (i >= 0 && i < self->numstyles) {
+      MS_REFCNT_INCR(self->styles[i]);
+      return self->styles[i];
+    } else {
+      msSetError(31, "Invalid index: %d", "getStyle()", i);
+      return NULL;
     }
+  }
 SWIGINTERN int classObj_insertStyle(classObj *self,styleObj *style,int index){
-        return msInsertStyle(self, style, index);
-    }
+    return msInsertStyle(self, style, index);
+  }
 SWIGINTERN styleObj *classObj_removeStyle(classObj *self,int index){
-	styleObj* style = (styleObj *) msRemoveStyle(self, index);
-	if (style)
-		MS_REFCNT_INCR(style);
-        return style;
-    }
+    styleObj* style = (styleObj *) msRemoveStyle(self, index);
+    if (style) MS_REFCNT_INCR(style);
+    return style;
+  }
 SWIGINTERN int classObj_moveStyleUp(classObj *self,int index){
-        return msMoveStyleUp(self, index);
-    }
+    return msMoveStyleUp(self, index);
+  }
 SWIGINTERN int classObj_moveStyleDown(classObj *self,int index){
-       return msMoveStyleDown(self, index);
-    }
+    return msMoveStyleDown(self, index);
+  }
 SWIGINTERN void labelCacheObj_freeCache(labelCacheObj *self){
         msFreeLabelCache(self);    
     }
@@ -2452,6 +2503,115 @@ SWIGINTERN int scalebarObj_updateFromString(scalebarObj *self,char *snippet){
 SWIGINTERN int legendObj_updateFromString(legendObj *self,char *snippet){
     return msUpdateLegendFromString(self, snippet, 0);
   }
+SWIGINTERN imageObj *new_imageObj(int width,int height,outputFormatObj *input_format,char const *file,double resolution,double defresolution){
+        imageObj *image=NULL;
+        outputFormatObj *format;
+        rendererVTableObj *renderer = NULL;
+        rasterBufferObj *rb = NULL;
+
+        if (input_format) {
+            format = input_format;
+        }
+        else {
+            format = msCreateDefaultOutputFormat(NULL, "GD/GIF", "gdgif");
+            if (format == NULL)
+                format = msCreateDefaultOutputFormat(NULL, "GD/PNG", "gdpng");
+            if (format == NULL)
+
+            if (format)
+                msInitializeRendererVTable(format);
+        }
+        if (format == NULL) {
+            msSetError(15, "Could not create output format",
+                       "imageObj()");
+            return NULL;
+        }
+
+        if (file) {
+            
+            renderer = format->vtable;
+            rb = (rasterBufferObj*) malloc(sizeof(rasterBufferObj));
+            if (!rb) {
+                msSetError(2, NULL, "imageObj()");
+                return NULL;
+            }
+            if ( (renderer->loadImageFromFile((char *)file, rb)) == MS_FAILURE)
+                return NULL;
+
+            image = msImageCreate(rb->width, rb->height, format, NULL, NULL, 
+                                  resolution, defresolution, NULL);
+            renderer->mergeRasterBuffer(image, rb, 1.0, 0, 0, 0, 0, rb->width, rb->height);
+
+            msFreeRasterBuffer(rb);
+            free(rb);
+
+            return image;
+        }
+
+        image = msImageCreate(width, height, format, NULL, NULL, resolution, defresolution, NULL);
+        return image;
+    }
+SWIGINTERN void delete_imageObj(imageObj *self){
+        msFreeImage(self);    
+    }
+SWIGINTERN void imageObj_save(imageObj *self,char *filename,mapObj *map){
+        msSaveImage(map, self, filename );
+    }
+SWIGINTERN int imageObj_write(imageObj *self,FILE *file){
+        int retval=MS_FAILURE;
+        rendererVTableObj *renderer = NULL;
+
+        if (MS_RENDERER_PLUGIN(self->format))
+        {
+            if (file)
+            {
+                renderer = self->format->vtable;
+                /* FIXME? as an improvement, pass a map argument instead of the NULL (see #4216) */
+                retval = renderer->saveImage(self, NULL, file, self->format);
+            }
+            else
+            {
+                retval = msSaveImage(NULL, self, NULL);
+            }
+        }
+        else
+        {
+            msSetError(15, "Writing of %s format not implemented",
+                       "imageObj::write");
+        }
+
+        return retval;
+    }
+SWIGINTERN gdBuffer imageObj_getBytes(imageObj *self){
+        gdBuffer buffer;
+        
+        buffer.owns_data = 1;
+        
+        buffer.data = msSaveImageBuffer(self, &buffer.size, self->format);
+            
+        if( buffer.data == NULL || buffer.size == 0 )
+        {
+            buffer.data = NULL;
+            msSetError(12, "Failed to get image buffer", "getBytes");
+            return buffer;
+        }
+
+        return buffer;
+    }
+SWIGINTERN int imageObj_getSize(imageObj *self){
+        gdBuffer buffer;
+	int size=0;
+        
+        buffer.data = msSaveImageBuffer(self, &buffer.size, self->format);
+	size = buffer.size;
+            
+        if( buffer.data == NULL || buffer.size == 0 ) {
+            buffer.data = NULL;
+            msSetError(12, "Failed to get image buffer size", "getSize");
+        }
+	free(buffer.data);
+        return size;
+    }
 SWIGINTERN layerObj *new_layerObj(mapObj *map){
         layerObj *layer;
         int result;
@@ -2624,6 +2784,9 @@ SWIGINTERN char *layerObj_getItem(layerObj *self,int i){
         else
             return NULL;
     }
+SWIGINTERN int layerObj_setItems(layerObj *self,char **items,int numitems){
+        return msLayerSetItems(self, items, numitems);
+    }
 SWIGINTERN int layerObj_draw(layerObj *self,mapObj *map,imageObj *image){
         return msDrawLayer(map, self, image);    
     }
@@ -2641,7 +2804,10 @@ SWIGINTERN int layerObj_queryByFilter(layerObj *self,mapObj *map,char *string){
         map->query.filter = (expressionObj *) malloc(sizeof(expressionObj));
         map->query.filter->string = strdup(string);
 	map->query.filter->type = 2000; /* MS_EXPRESSION: lot's of conflicts in mapfile.h */
-
+        map->query.filter->compiled = 0;
+        map->query.filter->flags = 0;
+        map->query.filter->tokens = map->query.filter->curtoken = NULL;
+        
         map->query.layer = self->index;
      	map->query.rect = map->extent;
 
@@ -2668,6 +2834,7 @@ SWIGINTERN int layerObj_queryByAttributes(layerObj *self,mapObj *map,char *qitem
         self->status = 1;
         retval = msQueryByAttributes(map);
         self->status = status;
+
         return retval;
     }
 SWIGINTERN int layerObj_queryByPoint(layerObj *self,mapObj *map,pointObj *point,int mode,double buffer){
@@ -2686,6 +2853,7 @@ SWIGINTERN int layerObj_queryByPoint(layerObj *self,mapObj *map,pointObj *point,
         self->status = 1;
         retval = msQueryByPoint(map);
         self->status = status;
+
         return retval;
     }
 SWIGINTERN int layerObj_queryByRect(layerObj *self,mapObj *map,rectObj rect){
@@ -2703,6 +2871,7 @@ SWIGINTERN int layerObj_queryByRect(layerObj *self,mapObj *map,rectObj rect){
         self->status = 1;
         retval = msQueryByRect(map);
         self->status = status;
+
         return retval;
     }
 SWIGINTERN int layerObj_queryByFeatures(layerObj *self,mapObj *map,int slayer){
@@ -2852,10 +3021,10 @@ SWIGINTERN char *layerObj_executeWFSGetFeature(layerObj *self,layerObj *layer){
         return (char *) msWFSExecuteGetFeature(layer);
     }
 SWIGINTERN int layerObj_applySLD(layerObj *self,char *sld,char *stylelayer){
-        return msSLDApplySLD(self->map, sld, self->index, stylelayer);
+      return msSLDApplySLD(self->map, sld, self->index, stylelayer, NULL);
     }
 SWIGINTERN int layerObj_applySLDURL(layerObj *self,char *sld,char *stylelayer){
-        return msSLDApplySLDURL(self->map, sld, self->index, stylelayer);
+      return msSLDApplySLDURL(self->map, sld, self->index, stylelayer, NULL);
     }
 SWIGINTERN char *layerObj_generateSLD(layerObj *self){
         return (char *) msSLDGenerateSLD(self->map, self->index, NULL);
@@ -3059,7 +3228,10 @@ SWIGINTERN int mapObj_queryByFilter(mapObj *self,char *string){
     self->query.filter = (expressionObj *) malloc(sizeof(expressionObj));
     self->query.filter->string = strdup(string);
     self->query.filter->type = 2000; /* MS_EXPRESSION: lot's of conflicts in mapfile.h */
-
+    self->query.filter->compiled = 0;
+    self->query.filter->flags = 0;
+    self->query.filter->tokens = self->query.filter->curtoken = NULL;
+    
     self->query.rect = self->extent;
 
     return msQueryByFilter(self);
@@ -3208,10 +3380,10 @@ SWIGINTERN void mapObj_applyConfigOptions(mapObj *self){
     msApplyMapConfigOptions( self );
   }
 SWIGINTERN int mapObj_applySLD(mapObj *self,char *sld){
-        return msSLDApplySLD(self, sld, -1, NULL);
+      return msSLDApplySLD(self, sld, -1, NULL, NULL);
     }
 SWIGINTERN int mapObj_applySLDURL(mapObj *self,char *sld){
-        return msSLDApplySLDURL(self, sld, -1, NULL);
+      return msSLDApplySLDURL(self, sld, -1, NULL, NULL);
     }
 SWIGINTERN char *mapObj_generateSLD(mapObj *self){
         return (char *) msSLDGenerateSLD(self, -1, NULL);
@@ -3767,114 +3939,6 @@ SWIGINTERN int mapObj_zoomScale(mapObj *self,double scale,pointObj *poPixPos,int
 
         return MS_SUCCESS;
     }
-SWIGINTERN imageObj *new_imageObj(int width,int height,outputFormatObj *input_format,char const *file,double resolution,double defresolution){
-        imageObj *image=NULL;
-        outputFormatObj *format;
-        rendererVTableObj *renderer = NULL;
-        rasterBufferObj *rb = NULL;
-
-        if (input_format) {
-            format = input_format;
-        }
-        else {
-            format = msCreateDefaultOutputFormat(NULL, "GD/GIF", "gdgif");
-            if (format == NULL)
-                format = msCreateDefaultOutputFormat(NULL, "GD/PNG", "gdpng");
-            if (format == NULL)
-
-            if (format)
-                msInitializeRendererVTable(format);
-        }
-        if (format == NULL) {
-            msSetError(15, "Could not create output format",
-                       "imageObj()");
-            return NULL;
-        }
-
-        if (file) {
-            
-            renderer = format->vtable;
-            rb = (rasterBufferObj*) malloc(sizeof(rasterBufferObj));
-            if (!rb) {
-                msSetError(2, NULL, "imageObj()");
-                return NULL;
-            }
-            if ( (renderer->loadImageFromFile(file, rb)) == MS_FAILURE)
-                return NULL;
-
-            image = msImageCreate(rb->width, rb->height, format, NULL, NULL, 
-                                  resolution, defresolution, NULL);
-            renderer->mergeRasterBuffer(image, rb, 1.0, 0, 0, 0, 0, rb->width, rb->height);
-
-            msFreeRasterBuffer(rb);
-            free(rb);
-
-            return image;
-        }
-
-        image = msImageCreate(width, height, format, NULL, NULL, resolution, defresolution, NULL);
-        return image;
-    }
-SWIGINTERN void delete_imageObj(imageObj *self){
-        msFreeImage(self);    
-    }
-SWIGINTERN void imageObj_save(imageObj *self,char *filename,mapObj *map){
-        msSaveImage(map, self, filename );
-    }
-SWIGINTERN int imageObj_write(imageObj *self,FILE *file){
-        int retval=MS_FAILURE;
-        rendererVTableObj *renderer = NULL;
-
-        if (MS_RENDERER_PLUGIN(self->format))
-        {
-            if (file)
-            {
-                renderer = self->format->vtable;
-                retval = renderer->saveImage(self, file, self->format);
-            }
-            else
-            {
-                retval = msSaveImage(NULL, self, NULL);
-            }
-        }
-        else
-        {
-            msSetError(15, "Writing of %s format not implemented",
-                       "imageObj::write");
-        }
-
-        return retval;
-    }
-SWIGINTERN gdBuffer imageObj_getBytes(imageObj *self){
-        gdBuffer buffer;
-        
-        buffer.owns_data = 1;
-        
-        buffer.data = msSaveImageBuffer(self, &buffer.size, self->format);
-            
-        if( buffer.data == NULL || buffer.size == 0 )
-        {
-            buffer.data = NULL;
-            msSetError(12, "Failed to get image buffer", "getBytes");
-            return buffer;
-        }
-
-        return buffer;
-    }
-SWIGINTERN int imageObj_getSize(imageObj *self){
-        gdBuffer buffer;
-	int size=0;
-        
-        buffer.data = msSaveImageBuffer(self, &buffer.size, self->format);
-	size = buffer.size;
-            
-        if( buffer.data == NULL || buffer.size == 0 ) {
-            buffer.data = NULL;
-            msSetError(12, "Failed to get image buffer size", "getSize");
-        }
-	free(buffer.data);
-        return size;
-    }
 SWIGINTERN rectObj *new_rectObj(double minx,double miny,double maxx,double maxy,int imageunits){	
         rectObj *rect;
     
@@ -3927,7 +3991,7 @@ SWIGINTERN int rectObj_draw(rectObj *self,mapObj *map,layerObj *layer,imageObj *
         shape.classindex = classindex;
         shape.text = strdup(text);
 
-        msDrawShape(map, layer, &shape, image, -1, 0);
+        msDrawShape(map, layer, &shape, image, -1, MS_DRAWMODE_FEATURES|MS_DRAWMODE_LABELS);
 
         msFreeShape(&shape);
     
@@ -4166,7 +4230,7 @@ SWIGINTERN int shapeObj_add(shapeObj *self,lineObj *line){
         return msAddLine(self, line);
     }
 SWIGINTERN int shapeObj_draw(shapeObj *self,mapObj *map,layerObj *layer,imageObj *image){
-        return msDrawShape(map, layer, self, image, -1, 0);
+        return msDrawShape(map, layer, self, image, -1, MS_DRAWMODE_FEATURES|MS_DRAWMODE_LABELS);
     }
 SWIGINTERN void shapeObj_setBounds(shapeObj *self){    
         msComputeBounds(self);
@@ -4553,7 +4617,7 @@ SWIGINTERN lineObj *symbolObj_getPoints(symbolObj *self){
         return line;
     }
 SWIGINTERN imageObj *symbolObj_getImage(symbolObj *self,outputFormatObj *input_format){
-        imageObj *image;
+        imageObj *image = NULL;
         outputFormatObj *format = NULL;
         rendererVTableObj *renderer = NULL;
 
@@ -4612,7 +4676,6 @@ SWIGINTERN int symbolObj_setImage(symbolObj *self,imageObj *image){
             msSetError(2, NULL, "setImage()");
             return MS_FAILURE;
         }
-        renderer->initializeRasterBuffer(self->pixmap_buffer, image->width, image->height, image->format->imagemode);
         self->type = MS_SYMBOL_PIXMAP;
         renderer->getRasterBufferCopy(image, self->pixmap_buffer);
 
@@ -4732,6 +4795,14 @@ SWIGINTERN void cgiRequestObj_setParameter(cgiRequestObj *self,char *name,char *
             self->NumParams++;
         }
     }
+SWIGINTERN void cgiRequestObj_addParameter(cgiRequestObj *self,char *name,char *value){
+        if (self->NumParams == 100) {
+            msSetError(31, "Maximum number of items, %d, has been reached", "addParameter()", 100);
+        }
+        self->ParamNames[self->NumParams] = strdup(name);
+        self->ParamValues[self->NumParams] = strdup(value);
+        self->NumParams++;
+    }
 SWIGINTERN char *cgiRequestObj_getName(cgiRequestObj *self,int index){
         if (index < 0 || index >= self->NumParams) {
             msSetError(31, "Invalid index, valid range is [0, %d]", "getName()", self->NumParams-1);
@@ -7426,7 +7497,7 @@ XS(_wrap_webObj_map_get) {
     void *argp1 = 0 ;
     int res1 = 0 ;
     int argvi = 0;
-    struct map_obj *result = 0 ;
+    struct mapObj *result = 0 ;
     dXSARGS;
     
     if ((items < 1) || (items > 1)) {
@@ -7439,10 +7510,10 @@ XS(_wrap_webObj_map_get) {
     arg1 = (webObj *)(argp1);
     {
       /* Accessing map */
-      result = (struct map_obj *) ((arg1)->map);;
+      result = (struct mapObj *) ((arg1)->map);;
       MS_REFCNT_INCR(result);
     }
-    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_map_obj, 0 | SWIG_SHADOW); argvi++ ;
+    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_mapObj, 0 | SWIG_SHADOW); argvi++ ;
     
     XSRETURN(argvi);
   fail:
@@ -9815,6 +9886,71 @@ XS(_wrap_styleObj_gap_get) {
 }
 
 
+XS(_wrap_styleObj_initialgap_set) {
+  {
+    styleObj *arg1 = (styleObj *) 0 ;
+    double arg2 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    double val2 ;
+    int ecode2 = 0 ;
+    int argvi = 0;
+    dXSARGS;
+    
+    if ((items < 2) || (items > 2)) {
+      SWIG_croak("Usage: styleObj_initialgap_set(self,initialgap);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_styleObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "styleObj_initialgap_set" "', argument " "1"" of type '" "styleObj *""'"); 
+    }
+    arg1 = (styleObj *)(argp1);
+    ecode2 = SWIG_AsVal_double SWIG_PERL_CALL_ARGS_2(ST(1), &val2);
+    if (!SWIG_IsOK(ecode2)) {
+      SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "styleObj_initialgap_set" "', argument " "2"" of type '" "double""'");
+    } 
+    arg2 = (double)(val2);
+    if (arg1) (arg1)->initialgap = arg2;
+    ST(argvi) = sv_newmortal();
+    
+    
+    XSRETURN(argvi);
+  fail:
+    
+    
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_styleObj_initialgap_get) {
+  {
+    styleObj *arg1 = (styleObj *) 0 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int argvi = 0;
+    double result;
+    dXSARGS;
+    
+    if ((items < 1) || (items > 1)) {
+      SWIG_croak("Usage: styleObj_initialgap_get(self);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_styleObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "styleObj_initialgap_get" "', argument " "1"" of type '" "styleObj *""'"); 
+    }
+    arg1 = (styleObj *)(argp1);
+    result = (double) ((arg1)->initialgap);
+    ST(argvi) = SWIG_From_double  SWIG_PERL_CALL_ARGS_1((double)(result)); argvi++ ;
+    
+    XSRETURN(argvi);
+  fail:
+    
+    SWIG_croak_null();
+  }
+}
+
+
 XS(_wrap_styleObj_position_set) {
   {
     styleObj *arg1 = (styleObj *) 0 ;
@@ -10465,6 +10601,136 @@ XS(_wrap_styleObj_offsety_get) {
 }
 
 
+XS(_wrap_styleObj_polaroffsetpixel_set) {
+  {
+    styleObj *arg1 = (styleObj *) 0 ;
+    double arg2 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    double val2 ;
+    int ecode2 = 0 ;
+    int argvi = 0;
+    dXSARGS;
+    
+    if ((items < 2) || (items > 2)) {
+      SWIG_croak("Usage: styleObj_polaroffsetpixel_set(self,polaroffsetpixel);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_styleObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "styleObj_polaroffsetpixel_set" "', argument " "1"" of type '" "styleObj *""'"); 
+    }
+    arg1 = (styleObj *)(argp1);
+    ecode2 = SWIG_AsVal_double SWIG_PERL_CALL_ARGS_2(ST(1), &val2);
+    if (!SWIG_IsOK(ecode2)) {
+      SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "styleObj_polaroffsetpixel_set" "', argument " "2"" of type '" "double""'");
+    } 
+    arg2 = (double)(val2);
+    if (arg1) (arg1)->polaroffsetpixel = arg2;
+    ST(argvi) = sv_newmortal();
+    
+    
+    XSRETURN(argvi);
+  fail:
+    
+    
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_styleObj_polaroffsetpixel_get) {
+  {
+    styleObj *arg1 = (styleObj *) 0 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int argvi = 0;
+    double result;
+    dXSARGS;
+    
+    if ((items < 1) || (items > 1)) {
+      SWIG_croak("Usage: styleObj_polaroffsetpixel_get(self);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_styleObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "styleObj_polaroffsetpixel_get" "', argument " "1"" of type '" "styleObj *""'"); 
+    }
+    arg1 = (styleObj *)(argp1);
+    result = (double) ((arg1)->polaroffsetpixel);
+    ST(argvi) = SWIG_From_double  SWIG_PERL_CALL_ARGS_1((double)(result)); argvi++ ;
+    
+    XSRETURN(argvi);
+  fail:
+    
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_styleObj_polaroffsetangle_set) {
+  {
+    styleObj *arg1 = (styleObj *) 0 ;
+    double arg2 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    double val2 ;
+    int ecode2 = 0 ;
+    int argvi = 0;
+    dXSARGS;
+    
+    if ((items < 2) || (items > 2)) {
+      SWIG_croak("Usage: styleObj_polaroffsetangle_set(self,polaroffsetangle);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_styleObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "styleObj_polaroffsetangle_set" "', argument " "1"" of type '" "styleObj *""'"); 
+    }
+    arg1 = (styleObj *)(argp1);
+    ecode2 = SWIG_AsVal_double SWIG_PERL_CALL_ARGS_2(ST(1), &val2);
+    if (!SWIG_IsOK(ecode2)) {
+      SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "styleObj_polaroffsetangle_set" "', argument " "2"" of type '" "double""'");
+    } 
+    arg2 = (double)(val2);
+    if (arg1) (arg1)->polaroffsetangle = arg2;
+    ST(argvi) = sv_newmortal();
+    
+    
+    XSRETURN(argvi);
+  fail:
+    
+    
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_styleObj_polaroffsetangle_get) {
+  {
+    styleObj *arg1 = (styleObj *) 0 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int argvi = 0;
+    double result;
+    dXSARGS;
+    
+    if ((items < 1) || (items > 1)) {
+      SWIG_croak("Usage: styleObj_polaroffsetangle_get(self);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_styleObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "styleObj_polaroffsetangle_get" "', argument " "1"" of type '" "styleObj *""'"); 
+    }
+    arg1 = (styleObj *)(argp1);
+    result = (double) ((arg1)->polaroffsetangle);
+    ST(argvi) = SWIG_From_double  SWIG_PERL_CALL_ARGS_1((double)(result)); argvi++ ;
+    
+    XSRETURN(argvi);
+  fail:
+    
+    SWIG_croak_null();
+  }
+}
+
+
 XS(_wrap_styleObj_angle_set) {
   {
     styleObj *arg1 = (styleObj *) 0 ;
@@ -10738,7 +11004,7 @@ XS(_wrap_new_styleObj) {
       SWIG_croak("Usage: new_styleObj(parent_class);");
     }
     if (items > 0) {
-      res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+      res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
       if (!SWIG_IsOK(res1)) {
         SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "new_styleObj" "', argument " "1"" of type '" "classObj *""'"); 
       }
@@ -10873,7 +11139,7 @@ XS(_wrap_styleObj_setSymbolByName) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "styleObj_setSymbolByName" "', argument " "1"" of type '" "styleObj *""'"); 
     }
     arg1 = (styleObj *)(argp1);
-    res2 = SWIG_ConvertPtr(ST(1), &argp2,SWIGTYPE_p_map_obj, 0 |  0 );
+    res2 = SWIG_ConvertPtr(ST(1), &argp2,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res2)) {
       SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "styleObj_setSymbolByName" "', argument " "2"" of type '" "mapObj *""'"); 
     }
@@ -11089,6 +11355,237 @@ XS(_wrap_styleObj_setGeomTransform) {
 }
 
 
+XS(_wrap_labelLeaderObj_maxdistance_set) {
+  {
+    labelLeaderObj *arg1 = (labelLeaderObj *) 0 ;
+    int arg2 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int val2 ;
+    int ecode2 = 0 ;
+    int argvi = 0;
+    dXSARGS;
+    
+    if ((items < 2) || (items > 2)) {
+      SWIG_croak("Usage: labelLeaderObj_maxdistance_set(self,maxdistance);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_labelLeaderObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelLeaderObj_maxdistance_set" "', argument " "1"" of type '" "labelLeaderObj *""'"); 
+    }
+    arg1 = (labelLeaderObj *)(argp1);
+    ecode2 = SWIG_AsVal_int SWIG_PERL_CALL_ARGS_2(ST(1), &val2);
+    if (!SWIG_IsOK(ecode2)) {
+      SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "labelLeaderObj_maxdistance_set" "', argument " "2"" of type '" "int""'");
+    } 
+    arg2 = (int)(val2);
+    if (arg1) (arg1)->maxdistance = arg2;
+    ST(argvi) = sv_newmortal();
+    
+    
+    XSRETURN(argvi);
+  fail:
+    
+    
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_labelLeaderObj_maxdistance_get) {
+  {
+    labelLeaderObj *arg1 = (labelLeaderObj *) 0 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int argvi = 0;
+    int result;
+    dXSARGS;
+    
+    if ((items < 1) || (items > 1)) {
+      SWIG_croak("Usage: labelLeaderObj_maxdistance_get(self);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_labelLeaderObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelLeaderObj_maxdistance_get" "', argument " "1"" of type '" "labelLeaderObj *""'"); 
+    }
+    arg1 = (labelLeaderObj *)(argp1);
+    result = (int) ((arg1)->maxdistance);
+    ST(argvi) = SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(result)); argvi++ ;
+    
+    XSRETURN(argvi);
+  fail:
+    
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_labelLeaderObj_gridstep_set) {
+  {
+    labelLeaderObj *arg1 = (labelLeaderObj *) 0 ;
+    int arg2 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int val2 ;
+    int ecode2 = 0 ;
+    int argvi = 0;
+    dXSARGS;
+    
+    if ((items < 2) || (items > 2)) {
+      SWIG_croak("Usage: labelLeaderObj_gridstep_set(self,gridstep);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_labelLeaderObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelLeaderObj_gridstep_set" "', argument " "1"" of type '" "labelLeaderObj *""'"); 
+    }
+    arg1 = (labelLeaderObj *)(argp1);
+    ecode2 = SWIG_AsVal_int SWIG_PERL_CALL_ARGS_2(ST(1), &val2);
+    if (!SWIG_IsOK(ecode2)) {
+      SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "labelLeaderObj_gridstep_set" "', argument " "2"" of type '" "int""'");
+    } 
+    arg2 = (int)(val2);
+    if (arg1) (arg1)->gridstep = arg2;
+    ST(argvi) = sv_newmortal();
+    
+    
+    XSRETURN(argvi);
+  fail:
+    
+    
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_labelLeaderObj_gridstep_get) {
+  {
+    labelLeaderObj *arg1 = (labelLeaderObj *) 0 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int argvi = 0;
+    int result;
+    dXSARGS;
+    
+    if ((items < 1) || (items > 1)) {
+      SWIG_croak("Usage: labelLeaderObj_gridstep_get(self);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_labelLeaderObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelLeaderObj_gridstep_get" "', argument " "1"" of type '" "labelLeaderObj *""'"); 
+    }
+    arg1 = (labelLeaderObj *)(argp1);
+    result = (int) ((arg1)->gridstep);
+    ST(argvi) = SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(result)); argvi++ ;
+    
+    XSRETURN(argvi);
+  fail:
+    
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_labelLeaderObj_numstyles_get) {
+  {
+    labelLeaderObj *arg1 = (labelLeaderObj *) 0 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int argvi = 0;
+    int result;
+    dXSARGS;
+    
+    if ((items < 1) || (items > 1)) {
+      SWIG_croak("Usage: labelLeaderObj_numstyles_get(self);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_labelLeaderObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelLeaderObj_numstyles_get" "', argument " "1"" of type '" "labelLeaderObj *""'"); 
+    }
+    arg1 = (labelLeaderObj *)(argp1);
+    result = (int) ((arg1)->numstyles);
+    ST(argvi) = SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(result)); argvi++ ;
+    
+    XSRETURN(argvi);
+  fail:
+    
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_new_labelLeaderObj) {
+  {
+    int argvi = 0;
+    labelLeaderObj *result = 0 ;
+    dXSARGS;
+    
+    if ((items < 0) || (items > 0)) {
+      SWIG_croak("Usage: new_labelLeaderObj();");
+    }
+    result = (labelLeaderObj *)calloc(1, sizeof(labelLeaderObj));
+    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_labelLeaderObj, SWIG_OWNER | SWIG_SHADOW); argvi++ ;
+    XSRETURN(argvi);
+  fail:
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_delete_labelLeaderObj) {
+  {
+    labelLeaderObj *arg1 = (labelLeaderObj *) 0 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int argvi = 0;
+    dXSARGS;
+    
+    if ((items < 1) || (items > 1)) {
+      SWIG_croak("Usage: delete_labelLeaderObj(self);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_labelLeaderObj, SWIG_POINTER_DISOWN |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_labelLeaderObj" "', argument " "1"" of type '" "labelLeaderObj *""'"); 
+    }
+    arg1 = (labelLeaderObj *)(argp1);
+    free((char *) arg1);
+    ST(argvi) = sv_newmortal();
+    
+    XSRETURN(argvi);
+  fail:
+    
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_labelObj_refcount_get) {
+  {
+    labelObj *arg1 = (labelObj *) 0 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int argvi = 0;
+    int result;
+    dXSARGS;
+    
+    if ((items < 1) || (items > 1)) {
+      SWIG_croak("Usage: labelObj_refcount_get(self);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_labelObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelObj_refcount_get" "', argument " "1"" of type '" "labelObj *""'"); 
+    }
+    arg1 = (labelObj *)(argp1);
+    result = (int) ((arg1)->refcount);
+    ST(argvi) = SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(result)); argvi++ ;
+    
+    XSRETURN(argvi);
+  fail:
+    
+    SWIG_croak_null();
+  }
+}
+
+
 XS(_wrap_labelObj_font_set) {
   {
     labelObj *arg1 = (labelObj *) 0 ;
@@ -13317,6 +13814,71 @@ XS(_wrap_labelObj_priority_get) {
 }
 
 
+XS(_wrap_labelObj_status_set) {
+  {
+    labelObj *arg1 = (labelObj *) 0 ;
+    int arg2 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int val2 ;
+    int ecode2 = 0 ;
+    int argvi = 0;
+    dXSARGS;
+    
+    if ((items < 2) || (items > 2)) {
+      SWIG_croak("Usage: labelObj_status_set(self,status);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_labelObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelObj_status_set" "', argument " "1"" of type '" "labelObj *""'"); 
+    }
+    arg1 = (labelObj *)(argp1);
+    ecode2 = SWIG_AsVal_int SWIG_PERL_CALL_ARGS_2(ST(1), &val2);
+    if (!SWIG_IsOK(ecode2)) {
+      SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "labelObj_status_set" "', argument " "2"" of type '" "int""'");
+    } 
+    arg2 = (int)(val2);
+    if (arg1) (arg1)->status = arg2;
+    ST(argvi) = sv_newmortal();
+    
+    
+    XSRETURN(argvi);
+  fail:
+    
+    
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_labelObj_status_get) {
+  {
+    labelObj *arg1 = (labelObj *) 0 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int argvi = 0;
+    int result;
+    dXSARGS;
+    
+    if ((items < 1) || (items > 1)) {
+      SWIG_croak("Usage: labelObj_status_get(self);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_labelObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelObj_status_get" "', argument " "1"" of type '" "labelObj *""'"); 
+    }
+    arg1 = (labelObj *)(argp1);
+    result = (int) ((arg1)->status);
+    ST(argvi) = SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(result)); argvi++ ;
+    
+    XSRETURN(argvi);
+  fail:
+    
+    SWIG_croak_null();
+  }
+}
+
+
 XS(_wrap_labelObj_numstyles_set) {
   {
     labelObj *arg1 = (labelObj *) 0 ;
@@ -13382,6 +13944,320 @@ XS(_wrap_labelObj_numstyles_get) {
 }
 
 
+XS(_wrap_labelObj_annotext_set) {
+  {
+    labelObj *arg1 = (labelObj *) 0 ;
+    char *arg2 = (char *) 0 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int res2 ;
+    char *buf2 = 0 ;
+    int alloc2 = 0 ;
+    int argvi = 0;
+    dXSARGS;
+    
+    if ((items < 2) || (items > 2)) {
+      SWIG_croak("Usage: labelObj_annotext_set(self,annotext);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_labelObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelObj_annotext_set" "', argument " "1"" of type '" "labelObj *""'"); 
+    }
+    arg1 = (labelObj *)(argp1);
+    res2 = SWIG_AsCharPtrAndSize(ST(1), &buf2, NULL, &alloc2);
+    if (!SWIG_IsOK(res2)) {
+      SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "labelObj_annotext_set" "', argument " "2"" of type '" "char *""'");
+    }
+    arg2 = (char *)(buf2);
+    {
+      if (arg1->annotext) free((char*)arg1->annotext);
+      if (arg2) {
+        arg1->annotext = (char *) malloc(strlen(arg2)+1);
+        strcpy((char*)arg1->annotext,arg2);
+      } else {
+        arg1->annotext = 0;
+      }
+    }
+    ST(argvi) = sv_newmortal();
+    
+    if (alloc2 == SWIG_NEWOBJ) free((char*)buf2);
+    XSRETURN(argvi);
+  fail:
+    
+    if (alloc2 == SWIG_NEWOBJ) free((char*)buf2);
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_labelObj_annotext_get) {
+  {
+    labelObj *arg1 = (labelObj *) 0 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int argvi = 0;
+    char *result = 0 ;
+    dXSARGS;
+    
+    if ((items < 1) || (items > 1)) {
+      SWIG_croak("Usage: labelObj_annotext_get(self);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_labelObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelObj_annotext_get" "', argument " "1"" of type '" "labelObj *""'"); 
+    }
+    arg1 = (labelObj *)(argp1);
+    result = (char *) ((arg1)->annotext);
+    ST(argvi) = SWIG_FromCharPtr((const char *)result); argvi++ ;
+    
+    XSRETURN(argvi);
+  fail:
+    
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_labelObj_annopoint_set) {
+  {
+    labelObj *arg1 = (labelObj *) 0 ;
+    pointObj *arg2 = (pointObj *) 0 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    void *argp2 = 0 ;
+    int res2 = 0 ;
+    int argvi = 0;
+    dXSARGS;
+    
+    if ((items < 2) || (items > 2)) {
+      SWIG_croak("Usage: labelObj_annopoint_set(self,annopoint);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_labelObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelObj_annopoint_set" "', argument " "1"" of type '" "labelObj *""'"); 
+    }
+    arg1 = (labelObj *)(argp1);
+    res2 = SWIG_ConvertPtr(ST(1), &argp2,SWIGTYPE_p_pointObj, 0 |  0 );
+    if (!SWIG_IsOK(res2)) {
+      SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "labelObj_annopoint_set" "', argument " "2"" of type '" "pointObj *""'"); 
+    }
+    arg2 = (pointObj *)(argp2);
+    if (arg1) (arg1)->annopoint = *arg2;
+    ST(argvi) = sv_newmortal();
+    
+    
+    XSRETURN(argvi);
+  fail:
+    
+    
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_labelObj_annopoint_get) {
+  {
+    labelObj *arg1 = (labelObj *) 0 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int argvi = 0;
+    pointObj *result = 0 ;
+    dXSARGS;
+    
+    if ((items < 1) || (items > 1)) {
+      SWIG_croak("Usage: labelObj_annopoint_get(self);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_labelObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelObj_annopoint_get" "', argument " "1"" of type '" "labelObj *""'"); 
+    }
+    arg1 = (labelObj *)(argp1);
+    result = (pointObj *)& ((arg1)->annopoint);
+    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_pointObj, 0 | SWIG_SHADOW); argvi++ ;
+    
+    XSRETURN(argvi);
+  fail:
+    
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_labelObj_annopoly_set) {
+  {
+    labelObj *arg1 = (labelObj *) 0 ;
+    shapeObj *arg2 = (shapeObj *) 0 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    void *argp2 = 0 ;
+    int res2 = 0 ;
+    int argvi = 0;
+    dXSARGS;
+    
+    if ((items < 2) || (items > 2)) {
+      SWIG_croak("Usage: labelObj_annopoly_set(self,annopoly);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_labelObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelObj_annopoly_set" "', argument " "1"" of type '" "labelObj *""'"); 
+    }
+    arg1 = (labelObj *)(argp1);
+    res2 = SWIG_ConvertPtr(ST(1), &argp2,SWIGTYPE_p_shapeObj, SWIG_POINTER_DISOWN |  0 );
+    if (!SWIG_IsOK(res2)) {
+      SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "labelObj_annopoly_set" "', argument " "2"" of type '" "shapeObj *""'"); 
+    }
+    arg2 = (shapeObj *)(argp2);
+    if (arg1) (arg1)->annopoly = arg2;
+    ST(argvi) = sv_newmortal();
+    
+    
+    XSRETURN(argvi);
+  fail:
+    
+    
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_labelObj_annopoly_get) {
+  {
+    labelObj *arg1 = (labelObj *) 0 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int argvi = 0;
+    shapeObj *result = 0 ;
+    dXSARGS;
+    
+    if ((items < 1) || (items > 1)) {
+      SWIG_croak("Usage: labelObj_annopoly_get(self);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_labelObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelObj_annopoly_get" "', argument " "1"" of type '" "labelObj *""'"); 
+    }
+    arg1 = (labelObj *)(argp1);
+    result = (shapeObj *) ((arg1)->annopoly);
+    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_shapeObj, 0 | SWIG_SHADOW); argvi++ ;
+    
+    XSRETURN(argvi);
+  fail:
+    
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_labelObj_leader_set) {
+  {
+    labelObj *arg1 = (labelObj *) 0 ;
+    labelLeaderObj *arg2 = (labelLeaderObj *) 0 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    void *argp2 = 0 ;
+    int res2 = 0 ;
+    int argvi = 0;
+    dXSARGS;
+    
+    if ((items < 2) || (items > 2)) {
+      SWIG_croak("Usage: labelObj_leader_set(self,leader);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_labelObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelObj_leader_set" "', argument " "1"" of type '" "labelObj *""'"); 
+    }
+    arg1 = (labelObj *)(argp1);
+    res2 = SWIG_ConvertPtr(ST(1), &argp2,SWIGTYPE_p_labelLeaderObj, 0 |  0 );
+    if (!SWIG_IsOK(res2)) {
+      SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "labelObj_leader_set" "', argument " "2"" of type '" "labelLeaderObj *""'"); 
+    }
+    arg2 = (labelLeaderObj *)(argp2);
+    if (arg1) (arg1)->leader = *arg2;
+    ST(argvi) = sv_newmortal();
+    
+    
+    XSRETURN(argvi);
+  fail:
+    
+    
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_labelObj_leader_get) {
+  {
+    labelObj *arg1 = (labelObj *) 0 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int argvi = 0;
+    labelLeaderObj *result = 0 ;
+    dXSARGS;
+    
+    if ((items < 1) || (items > 1)) {
+      SWIG_croak("Usage: labelObj_leader_get(self);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_labelObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelObj_leader_get" "', argument " "1"" of type '" "labelObj *""'"); 
+    }
+    arg1 = (labelObj *)(argp1);
+    result = (labelLeaderObj *)& ((arg1)->leader);
+    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_labelLeaderObj, 0 | SWIG_SHADOW); argvi++ ;
+    
+    XSRETURN(argvi);
+  fail:
+    
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_new_labelObj) {
+  {
+    int argvi = 0;
+    labelObj *result = 0 ;
+    dXSARGS;
+    
+    if ((items < 0) || (items > 0)) {
+      SWIG_croak("Usage: new_labelObj();");
+    }
+    result = (labelObj *)new_labelObj();
+    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_labelObj, SWIG_OWNER | SWIG_SHADOW); argvi++ ;
+    XSRETURN(argvi);
+  fail:
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_delete_labelObj) {
+  {
+    labelObj *arg1 = (labelObj *) 0 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int argvi = 0;
+    dXSARGS;
+    
+    if ((items < 1) || (items > 1)) {
+      SWIG_croak("Usage: delete_labelObj(self);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_labelObj, SWIG_POINTER_DISOWN |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_labelObj" "', argument " "1"" of type '" "labelObj *""'"); 
+    }
+    arg1 = (labelObj *)(argp1);
+    delete_labelObj(arg1);
+    ST(argvi) = sv_newmortal();
+    
+    XSRETURN(argvi);
+  fail:
+    
+    SWIG_croak_null();
+  }
+}
+
+
 XS(_wrap_labelObj_updateFromString) {
   {
     labelObj *arg1 = (labelObj *) 0 ;
@@ -13546,6 +14422,142 @@ XS(_wrap_labelObj_setBinding) {
 }
 
 
+XS(_wrap_labelObj_setExpression) {
+  {
+    labelObj *arg1 = (labelObj *) 0 ;
+    char *arg2 = (char *) 0 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int res2 ;
+    char *buf2 = 0 ;
+    int alloc2 = 0 ;
+    int argvi = 0;
+    int result;
+    dXSARGS;
+    
+    if ((items < 2) || (items > 2)) {
+      SWIG_croak("Usage: labelObj_setExpression(self,expression);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_labelObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelObj_setExpression" "', argument " "1"" of type '" "labelObj *""'"); 
+    }
+    arg1 = (labelObj *)(argp1);
+    res2 = SWIG_AsCharPtrAndSize(ST(1), &buf2, NULL, &alloc2);
+    if (!SWIG_IsOK(res2)) {
+      SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "labelObj_setExpression" "', argument " "2"" of type '" "char *""'");
+    }
+    arg2 = (char *)(buf2);
+    result = (int)labelObj_setExpression(arg1,arg2);
+    ST(argvi) = SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(result)); argvi++ ;
+    
+    if (alloc2 == SWIG_NEWOBJ) free((char*)buf2);
+    XSRETURN(argvi);
+  fail:
+    
+    if (alloc2 == SWIG_NEWOBJ) free((char*)buf2);
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_labelObj_getExpressionString) {
+  {
+    labelObj *arg1 = (labelObj *) 0 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int argvi = 0;
+    char *result = 0 ;
+    dXSARGS;
+    
+    if ((items < 1) || (items > 1)) {
+      SWIG_croak("Usage: labelObj_getExpressionString(self);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_labelObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelObj_getExpressionString" "', argument " "1"" of type '" "labelObj *""'"); 
+    }
+    arg1 = (labelObj *)(argp1);
+    result = (char *)labelObj_getExpressionString(arg1);
+    ST(argvi) = SWIG_FromCharPtr((const char *)result); argvi++ ;
+    
+    free((char*)result);
+    XSRETURN(argvi);
+  fail:
+    
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_labelObj_setText) {
+  {
+    labelObj *arg1 = (labelObj *) 0 ;
+    char *arg2 = (char *) 0 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int res2 ;
+    char *buf2 = 0 ;
+    int alloc2 = 0 ;
+    int argvi = 0;
+    int result;
+    dXSARGS;
+    
+    if ((items < 2) || (items > 2)) {
+      SWIG_croak("Usage: labelObj_setText(self,text);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_labelObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelObj_setText" "', argument " "1"" of type '" "labelObj *""'"); 
+    }
+    arg1 = (labelObj *)(argp1);
+    res2 = SWIG_AsCharPtrAndSize(ST(1), &buf2, NULL, &alloc2);
+    if (!SWIG_IsOK(res2)) {
+      SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "labelObj_setText" "', argument " "2"" of type '" "char *""'");
+    }
+    arg2 = (char *)(buf2);
+    result = (int)labelObj_setText(arg1,arg2);
+    ST(argvi) = SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(result)); argvi++ ;
+    
+    if (alloc2 == SWIG_NEWOBJ) free((char*)buf2);
+    XSRETURN(argvi);
+  fail:
+    
+    if (alloc2 == SWIG_NEWOBJ) free((char*)buf2);
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_labelObj_getTextString) {
+  {
+    labelObj *arg1 = (labelObj *) 0 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int argvi = 0;
+    char *result = 0 ;
+    dXSARGS;
+    
+    if ((items < 1) || (items > 1)) {
+      SWIG_croak("Usage: labelObj_getTextString(self);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_labelObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelObj_getTextString" "', argument " "1"" of type '" "labelObj *""'"); 
+    }
+    arg1 = (labelObj *)(argp1);
+    result = (char *)labelObj_getTextString(arg1);
+    ST(argvi) = SWIG_FromCharPtr((const char *)result); argvi++ ;
+    
+    free((char*)result);
+    XSRETURN(argvi);
+  fail:
+    
+    SWIG_croak_null();
+  }
+}
+
+
 XS(_wrap_labelObj_getStyle) {
   {
     labelObj *arg1 = (labelObj *) 0 ;
@@ -13748,51 +14760,6 @@ XS(_wrap_labelObj_moveStyleDown) {
 }
 
 
-XS(_wrap_new_labelObj) {
-  {
-    int argvi = 0;
-    labelObj *result = 0 ;
-    dXSARGS;
-    
-    if ((items < 0) || (items > 0)) {
-      SWIG_croak("Usage: new_labelObj();");
-    }
-    result = (labelObj *)calloc(1, sizeof(labelObj));
-    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_labelObj, SWIG_OWNER | SWIG_SHADOW); argvi++ ;
-    XSRETURN(argvi);
-  fail:
-    SWIG_croak_null();
-  }
-}
-
-
-XS(_wrap_delete_labelObj) {
-  {
-    labelObj *arg1 = (labelObj *) 0 ;
-    void *argp1 = 0 ;
-    int res1 = 0 ;
-    int argvi = 0;
-    dXSARGS;
-    
-    if ((items < 1) || (items > 1)) {
-      SWIG_croak("Usage: delete_labelObj(self);");
-    }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_labelObj, SWIG_POINTER_DISOWN |  0 );
-    if (!SWIG_IsOK(res1)) {
-      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_labelObj" "', argument " "1"" of type '" "labelObj *""'"); 
-    }
-    arg1 = (labelObj *)(argp1);
-    free((char *) arg1);
-    ST(argvi) = sv_newmortal();
-    
-    XSRETURN(argvi);
-  fail:
-    
-    SWIG_croak_null();
-  }
-}
-
-
 XS(_wrap_classObj_status_set) {
   {
     classObj *arg1 = (classObj *) 0 ;
@@ -13807,7 +14774,7 @@ XS(_wrap_classObj_status_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: classObj_status_set(self,status);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_status_set" "', argument " "1"" of type '" "classObj *""'"); 
     }
@@ -13842,7 +14809,7 @@ XS(_wrap_classObj_status_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: classObj_status_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_status_get" "', argument " "1"" of type '" "classObj *""'"); 
     }
@@ -13858,90 +14825,90 @@ XS(_wrap_classObj_status_get) {
 }
 
 
-XS(_wrap_classObj_numstyles_set) {
+XS(_wrap_classObj_numstyles_get) {
   {
     classObj *arg1 = (classObj *) 0 ;
-    int arg2 ;
     void *argp1 = 0 ;
     int res1 = 0 ;
-    int val2 ;
-    int ecode2 = 0 ;
     int argvi = 0;
+    int result;
     dXSARGS;
     
-    if ((items < 2) || (items > 2)) {
-      SWIG_croak("Usage: classObj_numstyles_set(self,numstyles);");
+    if ((items < 1) || (items > 1)) {
+      SWIG_croak("Usage: classObj_numstyles_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
-      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_numstyles_set" "', argument " "1"" of type '" "classObj *""'"); 
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_numstyles_get" "', argument " "1"" of type '" "classObj *""'"); 
     }
     arg1 = (classObj *)(argp1);
-    ecode2 = SWIG_AsVal_int SWIG_PERL_CALL_ARGS_2(ST(1), &val2);
-    if (!SWIG_IsOK(ecode2)) {
-      SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "classObj_numstyles_set" "', argument " "2"" of type '" "int""'");
-    } 
-    arg2 = (int)(val2);
-    if (arg1) (arg1)->numstyles = arg2;
-    ST(argvi) = sv_newmortal();
-    
+    result = (int) ((arg1)->numstyles);
+    ST(argvi) = SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(result)); argvi++ ;
     
     XSRETURN(argvi);
   fail:
     
-    
     SWIG_croak_null();
   }
 }
 
 
-XS(_wrap_classObj_numstyles_get) {
+XS(_wrap_classObj_numlabels_set) {
   {
     classObj *arg1 = (classObj *) 0 ;
+    int arg2 ;
     void *argp1 = 0 ;
     int res1 = 0 ;
+    int val2 ;
+    int ecode2 = 0 ;
     int argvi = 0;
-    int result;
     dXSARGS;
     
-    if ((items < 1) || (items > 1)) {
-      SWIG_croak("Usage: classObj_numstyles_get(self);");
+    if ((items < 2) || (items > 2)) {
+      SWIG_croak("Usage: classObj_numlabels_set(self,numlabels);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
-      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_numstyles_get" "', argument " "1"" of type '" "classObj *""'"); 
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_numlabels_set" "', argument " "1"" of type '" "classObj *""'"); 
     }
     arg1 = (classObj *)(argp1);
-    result = (int) ((arg1)->numstyles);
-    ST(argvi) = SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(result)); argvi++ ;
+    ecode2 = SWIG_AsVal_int SWIG_PERL_CALL_ARGS_2(ST(1), &val2);
+    if (!SWIG_IsOK(ecode2)) {
+      SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "classObj_numlabels_set" "', argument " "2"" of type '" "int""'");
+    } 
+    arg2 = (int)(val2);
+    if (arg1) (arg1)->numlabels = arg2;
+    ST(argvi) = sv_newmortal();
+    
     
     XSRETURN(argvi);
   fail:
     
+    
     SWIG_croak_null();
   }
 }
 
 
-XS(_wrap_classObj_label_get) {
+XS(_wrap_classObj_numlabels_get) {
   {
     classObj *arg1 = (classObj *) 0 ;
     void *argp1 = 0 ;
     int res1 = 0 ;
     int argvi = 0;
-    labelObj *result = 0 ;
+    int result;
     dXSARGS;
     
     if ((items < 1) || (items > 1)) {
-      SWIG_croak("Usage: classObj_label_get(self);");
+      SWIG_croak("Usage: classObj_numlabels_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
-      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_label_get" "', argument " "1"" of type '" "classObj *""'"); 
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_numlabels_get" "', argument " "1"" of type '" "classObj *""'"); 
     }
     arg1 = (classObj *)(argp1);
-    result = (labelObj *)& ((arg1)->label);
-    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_labelObj, 0 | SWIG_SHADOW); argvi++ ;
+    result = (int) ((arg1)->numlabels);
+    ST(argvi) = SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(result)); argvi++ ;
     
     XSRETURN(argvi);
   fail:
@@ -13966,7 +14933,7 @@ XS(_wrap_classObj_name_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: classObj_name_set(self,name);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_name_set" "', argument " "1"" of type '" "classObj *""'"); 
     }
@@ -14009,7 +14976,7 @@ XS(_wrap_classObj_name_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: classObj_name_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_name_get" "', argument " "1"" of type '" "classObj *""'"); 
     }
@@ -14040,7 +15007,7 @@ XS(_wrap_classObj_title_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: classObj_title_set(self,title);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_title_set" "', argument " "1"" of type '" "classObj *""'"); 
     }
@@ -14083,7 +15050,7 @@ XS(_wrap_classObj_title_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: classObj_title_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_title_get" "', argument " "1"" of type '" "classObj *""'"); 
     }
@@ -14114,7 +15081,7 @@ XS(_wrap_classObj_template_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: classObj_template_set(self,template);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_template_set" "', argument " "1"" of type '" "classObj *""'"); 
     }
@@ -14157,7 +15124,7 @@ XS(_wrap_classObj_template_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: classObj_template_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_template_get" "', argument " "1"" of type '" "classObj *""'"); 
     }
@@ -14187,7 +15154,7 @@ XS(_wrap_classObj_type_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: classObj_type_set(self,type);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_type_set" "', argument " "1"" of type '" "classObj *""'"); 
     }
@@ -14222,7 +15189,7 @@ XS(_wrap_classObj_type_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: classObj_type_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_type_get" "', argument " "1"" of type '" "classObj *""'"); 
     }
@@ -14250,7 +15217,7 @@ XS(_wrap_classObj_metadata_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: classObj_metadata_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_metadata_get" "', argument " "1"" of type '" "classObj *""'"); 
     }
@@ -14278,7 +15245,7 @@ XS(_wrap_classObj_validation_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: classObj_validation_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_validation_get" "', argument " "1"" of type '" "classObj *""'"); 
     }
@@ -14308,7 +15275,7 @@ XS(_wrap_classObj_minscaledenom_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: classObj_minscaledenom_set(self,minscaledenom);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_minscaledenom_set" "', argument " "1"" of type '" "classObj *""'"); 
     }
@@ -14343,7 +15310,7 @@ XS(_wrap_classObj_minscaledenom_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: classObj_minscaledenom_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_minscaledenom_get" "', argument " "1"" of type '" "classObj *""'"); 
     }
@@ -14373,7 +15340,7 @@ XS(_wrap_classObj_maxscaledenom_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: classObj_maxscaledenom_set(self,maxscaledenom);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_maxscaledenom_set" "', argument " "1"" of type '" "classObj *""'"); 
     }
@@ -14408,7 +15375,7 @@ XS(_wrap_classObj_maxscaledenom_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: classObj_maxscaledenom_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_maxscaledenom_get" "', argument " "1"" of type '" "classObj *""'"); 
     }
@@ -14438,7 +15405,7 @@ XS(_wrap_classObj_minfeaturesize_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: classObj_minfeaturesize_set(self,minfeaturesize);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_minfeaturesize_set" "', argument " "1"" of type '" "classObj *""'"); 
     }
@@ -14473,7 +15440,7 @@ XS(_wrap_classObj_minfeaturesize_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: classObj_minfeaturesize_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_minfeaturesize_get" "', argument " "1"" of type '" "classObj *""'"); 
     }
@@ -14501,7 +15468,7 @@ XS(_wrap_classObj_refcount_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: classObj_refcount_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_refcount_get" "', argument " "1"" of type '" "classObj *""'"); 
     }
@@ -14523,23 +15490,23 @@ XS(_wrap_classObj_layer_get) {
     void *argp1 = 0 ;
     int res1 = 0 ;
     int argvi = 0;
-    struct layer_obj *result = 0 ;
+    struct layerObj *result = 0 ;
     dXSARGS;
     
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: classObj_layer_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_layer_get" "', argument " "1"" of type '" "classObj *""'"); 
     }
     arg1 = (classObj *)(argp1);
     {
       /* Accessing layer */
-      result = (struct layer_obj *) ((arg1)->layer);;
+      result = (struct layerObj *) ((arg1)->layer);;
       MS_REFCNT_INCR(result);
     }
-    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_layer_obj, 0 | SWIG_SHADOW); argvi++ ;
+    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_layerObj, 0 | SWIG_SHADOW); argvi++ ;
     
     XSRETURN(argvi);
   fail:
@@ -14563,7 +15530,7 @@ XS(_wrap_classObj_debug_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: classObj_debug_set(self,debug);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_debug_set" "', argument " "1"" of type '" "classObj *""'"); 
     }
@@ -14598,7 +15565,7 @@ XS(_wrap_classObj_debug_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: classObj_debug_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_debug_get" "', argument " "1"" of type '" "classObj *""'"); 
     }
@@ -14629,7 +15596,7 @@ XS(_wrap_classObj_keyimage_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: classObj_keyimage_set(self,keyimage);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_keyimage_set" "', argument " "1"" of type '" "classObj *""'"); 
     }
@@ -14672,7 +15639,7 @@ XS(_wrap_classObj_keyimage_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: classObj_keyimage_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_keyimage_get" "', argument " "1"" of type '" "classObj *""'"); 
     }
@@ -14703,7 +15670,7 @@ XS(_wrap_classObj_group_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: classObj_group_set(self,group);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_group_set" "', argument " "1"" of type '" "classObj *""'"); 
     }
@@ -14746,7 +15713,7 @@ XS(_wrap_classObj_group_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: classObj_group_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_group_get" "', argument " "1"" of type '" "classObj *""'"); 
     }
@@ -14762,6 +15729,71 @@ XS(_wrap_classObj_group_get) {
 }
 
 
+XS(_wrap_classObj_leader_set) {
+  {
+    classObj *arg1 = (classObj *) 0 ;
+    labelLeaderObj *arg2 = (labelLeaderObj *) 0 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    void *argp2 = 0 ;
+    int res2 = 0 ;
+    int argvi = 0;
+    dXSARGS;
+    
+    if ((items < 2) || (items > 2)) {
+      SWIG_croak("Usage: classObj_leader_set(self,leader);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_leader_set" "', argument " "1"" of type '" "classObj *""'"); 
+    }
+    arg1 = (classObj *)(argp1);
+    res2 = SWIG_ConvertPtr(ST(1), &argp2,SWIGTYPE_p_labelLeaderObj, 0 |  0 );
+    if (!SWIG_IsOK(res2)) {
+      SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "classObj_leader_set" "', argument " "2"" of type '" "labelLeaderObj *""'"); 
+    }
+    arg2 = (labelLeaderObj *)(argp2);
+    if (arg1) (arg1)->leader = *arg2;
+    ST(argvi) = sv_newmortal();
+    
+    
+    XSRETURN(argvi);
+  fail:
+    
+    
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_classObj_leader_get) {
+  {
+    classObj *arg1 = (classObj *) 0 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int argvi = 0;
+    labelLeaderObj *result = 0 ;
+    dXSARGS;
+    
+    if ((items < 1) || (items > 1)) {
+      SWIG_croak("Usage: classObj_leader_get(self);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_leader_get" "', argument " "1"" of type '" "classObj *""'"); 
+    }
+    arg1 = (classObj *)(argp1);
+    result = (labelLeaderObj *)& ((arg1)->leader);
+    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_labelLeaderObj, 0 | SWIG_SHADOW); argvi++ ;
+    
+    XSRETURN(argvi);
+  fail:
+    
+    SWIG_croak_null();
+  }
+}
+
+
 XS(_wrap_new_classObj) {
   {
     layerObj *arg1 = (layerObj *) NULL ;
@@ -14775,14 +15807,14 @@ XS(_wrap_new_classObj) {
       SWIG_croak("Usage: new_classObj(layer);");
     }
     if (items > 0) {
-      res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+      res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
       if (!SWIG_IsOK(res1)) {
         SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "new_classObj" "', argument " "1"" of type '" "layerObj *""'"); 
       }
       arg1 = (layerObj *)(argp1);
     }
     result = (classObj *)new_classObj(arg1);
-    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_class_obj, SWIG_OWNER | SWIG_SHADOW); argvi++ ;
+    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_classObj, SWIG_OWNER | SWIG_SHADOW); argvi++ ;
     
     XSRETURN(argvi);
   fail:
@@ -14803,7 +15835,7 @@ XS(_wrap_delete_classObj) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: delete_classObj(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_class_obj, SWIG_POINTER_DISOWN |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, SWIG_POINTER_DISOWN |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_classObj" "', argument " "1"" of type '" "classObj *""'"); 
     }
@@ -14835,7 +15867,7 @@ XS(_wrap_classObj_updateFromString) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: classObj_updateFromString(self,snippet);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_updateFromString" "', argument " "1"" of type '" "classObj *""'"); 
     }
@@ -14870,13 +15902,13 @@ XS(_wrap_classObj_clone) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: classObj_clone(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_clone" "', argument " "1"" of type '" "classObj *""'"); 
     }
     arg1 = (classObj *)(argp1);
     result = (classObj *)classObj_clone(arg1);
-    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_class_obj, SWIG_OWNER | SWIG_SHADOW); argvi++ ;
+    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_classObj, SWIG_OWNER | SWIG_SHADOW); argvi++ ;
     
     XSRETURN(argvi);
   fail:
@@ -14902,7 +15934,7 @@ XS(_wrap_classObj_setExpression) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: classObj_setExpression(self,expression);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_setExpression" "', argument " "1"" of type '" "classObj *""'"); 
     }
@@ -14937,7 +15969,7 @@ XS(_wrap_classObj_getExpressionString) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: classObj_getExpressionString(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_getExpressionString" "', argument " "1"" of type '" "classObj *""'"); 
     }
@@ -14970,7 +16002,7 @@ XS(_wrap_classObj_setText) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: classObj_setText(self,text);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_setText" "', argument " "1"" of type '" "classObj *""'"); 
     }
@@ -15005,7 +16037,7 @@ XS(_wrap_classObj_getTextString) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: classObj_getTextString(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_getTextString" "', argument " "1"" of type '" "classObj *""'"); 
     }
@@ -15038,7 +16070,7 @@ XS(_wrap_classObj_getMetaData) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: classObj_getMetaData(self,name);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_getMetaData" "', argument " "1"" of type '" "classObj *""'"); 
     }
@@ -15081,7 +16113,7 @@ XS(_wrap_classObj_setMetaData) {
     if ((items < 3) || (items > 3)) {
       SWIG_croak("Usage: classObj_setMetaData(self,name,value);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_setMetaData" "', argument " "1"" of type '" "classObj *""'"); 
     }
@@ -15123,7 +16155,7 @@ XS(_wrap_classObj_getFirstMetaDataKey) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: classObj_getFirstMetaDataKey(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_getFirstMetaDataKey" "', argument " "1"" of type '" "classObj *""'"); 
     }
@@ -15155,7 +16187,7 @@ XS(_wrap_classObj_getNextMetaDataKey) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: classObj_getNextMetaDataKey(self,lastkey);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_getNextMetaDataKey" "', argument " "1"" of type '" "classObj *""'"); 
     }
@@ -15211,17 +16243,17 @@ XS(_wrap_classObj_drawLegendIcon) {
     if ((items < 8) || (items > 8)) {
       SWIG_croak("Usage: classObj_drawLegendIcon(self,map,layer,width,height,dstImage,dstX,dstY);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_drawLegendIcon" "', argument " "1"" of type '" "classObj *""'"); 
     }
     arg1 = (classObj *)(argp1);
-    res2 = SWIG_ConvertPtr(ST(1), &argp2,SWIGTYPE_p_map_obj, 0 |  0 );
+    res2 = SWIG_ConvertPtr(ST(1), &argp2,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res2)) {
       SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "classObj_drawLegendIcon" "', argument " "2"" of type '" "mapObj *""'"); 
     }
     arg2 = (mapObj *)(argp2);
-    res3 = SWIG_ConvertPtr(ST(2), &argp3,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res3 = SWIG_ConvertPtr(ST(2), &argp3,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res3)) {
       SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "classObj_drawLegendIcon" "', argument " "3"" of type '" "layerObj *""'"); 
     }
@@ -15300,17 +16332,17 @@ XS(_wrap_classObj_createLegendIcon) {
     if ((items < 5) || (items > 5)) {
       SWIG_croak("Usage: classObj_createLegendIcon(self,map,layer,width,height);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_createLegendIcon" "', argument " "1"" of type '" "classObj *""'"); 
     }
     arg1 = (classObj *)(argp1);
-    res2 = SWIG_ConvertPtr(ST(1), &argp2,SWIGTYPE_p_map_obj, 0 |  0 );
+    res2 = SWIG_ConvertPtr(ST(1), &argp2,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res2)) {
       SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "classObj_createLegendIcon" "', argument " "2"" of type '" "mapObj *""'"); 
     }
     arg2 = (mapObj *)(argp2);
-    res3 = SWIG_ConvertPtr(ST(2), &argp3,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res3 = SWIG_ConvertPtr(ST(2), &argp3,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res3)) {
       SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "classObj_createLegendIcon" "', argument " "3"" of type '" "layerObj *""'"); 
     }
@@ -15344,6 +16376,120 @@ XS(_wrap_classObj_createLegendIcon) {
 }
 
 
+XS(_wrap_classObj_getLabel) {
+  {
+    classObj *arg1 = (classObj *) 0 ;
+    int arg2 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int val2 ;
+    int ecode2 = 0 ;
+    int argvi = 0;
+    labelObj *result = 0 ;
+    dXSARGS;
+    
+    if ((items < 2) || (items > 2)) {
+      SWIG_croak("Usage: classObj_getLabel(self,i);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_getLabel" "', argument " "1"" of type '" "classObj *""'"); 
+    }
+    arg1 = (classObj *)(argp1);
+    ecode2 = SWIG_AsVal_int SWIG_PERL_CALL_ARGS_2(ST(1), &val2);
+    if (!SWIG_IsOK(ecode2)) {
+      SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "classObj_getLabel" "', argument " "2"" of type '" "int""'");
+    } 
+    arg2 = (int)(val2);
+    result = (labelObj *)classObj_getLabel(arg1,arg2);
+    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_labelObj, SWIG_OWNER | SWIG_SHADOW); argvi++ ;
+    
+    
+    XSRETURN(argvi);
+  fail:
+    
+    
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_classObj_addLabel) {
+  {
+    classObj *arg1 = (classObj *) 0 ;
+    labelObj *arg2 = (labelObj *) 0 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    void *argp2 = 0 ;
+    int res2 = 0 ;
+    int argvi = 0;
+    int result;
+    dXSARGS;
+    
+    if ((items < 2) || (items > 2)) {
+      SWIG_croak("Usage: classObj_addLabel(self,label);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_addLabel" "', argument " "1"" of type '" "classObj *""'"); 
+    }
+    arg1 = (classObj *)(argp1);
+    res2 = SWIG_ConvertPtr(ST(1), &argp2,SWIGTYPE_p_labelObj, 0 |  0 );
+    if (!SWIG_IsOK(res2)) {
+      SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "classObj_addLabel" "', argument " "2"" of type '" "labelObj *""'"); 
+    }
+    arg2 = (labelObj *)(argp2);
+    result = (int)classObj_addLabel(arg1,arg2);
+    ST(argvi) = SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(result)); argvi++ ;
+    
+    
+    XSRETURN(argvi);
+  fail:
+    
+    
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_classObj_removeLabel) {
+  {
+    classObj *arg1 = (classObj *) 0 ;
+    int arg2 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int val2 ;
+    int ecode2 = 0 ;
+    int argvi = 0;
+    labelObj *result = 0 ;
+    dXSARGS;
+    
+    if ((items < 2) || (items > 2)) {
+      SWIG_croak("Usage: classObj_removeLabel(self,index);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_removeLabel" "', argument " "1"" of type '" "classObj *""'"); 
+    }
+    arg1 = (classObj *)(argp1);
+    ecode2 = SWIG_AsVal_int SWIG_PERL_CALL_ARGS_2(ST(1), &val2);
+    if (!SWIG_IsOK(ecode2)) {
+      SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "classObj_removeLabel" "', argument " "2"" of type '" "int""'");
+    } 
+    arg2 = (int)(val2);
+    result = (labelObj *)classObj_removeLabel(arg1,arg2);
+    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_labelObj, SWIG_OWNER | SWIG_SHADOW); argvi++ ;
+    
+    
+    XSRETURN(argvi);
+  fail:
+    
+    
+    SWIG_croak_null();
+  }
+}
+
+
 XS(_wrap_classObj_getStyle) {
   {
     classObj *arg1 = (classObj *) 0 ;
@@ -15359,7 +16505,7 @@ XS(_wrap_classObj_getStyle) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: classObj_getStyle(self,i);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_getStyle" "', argument " "1"" of type '" "classObj *""'"); 
     }
@@ -15400,7 +16546,7 @@ XS(_wrap_classObj_insertStyle) {
     if ((items < 2) || (items > 3)) {
       SWIG_croak("Usage: classObj_insertStyle(self,style,index);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_insertStyle" "', argument " "1"" of type '" "classObj *""'"); 
     }
@@ -15447,7 +16593,7 @@ XS(_wrap_classObj_removeStyle) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: classObj_removeStyle(self,index);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_removeStyle" "', argument " "1"" of type '" "classObj *""'"); 
     }
@@ -15485,7 +16631,7 @@ XS(_wrap_classObj_moveStyleUp) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: classObj_moveStyleUp(self,index);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_moveStyleUp" "', argument " "1"" of type '" "classObj *""'"); 
     }
@@ -15523,7 +16669,7 @@ XS(_wrap_classObj_moveStyleDown) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: classObj_moveStyleDown(self,index);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_classObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_moveStyleDown" "', argument " "1"" of type '" "classObj *""'"); 
     }
@@ -15546,25 +16692,25 @@ XS(_wrap_classObj_moveStyleDown) {
 }
 
 
-XS(_wrap_labelCacheMemberObj_text_get) {
+XS(_wrap_labelCacheMemberObj_featuresize_get) {
   {
     labelCacheMemberObj *arg1 = (labelCacheMemberObj *) 0 ;
     void *argp1 = 0 ;
     int res1 = 0 ;
     int argvi = 0;
-    char *result = 0 ;
+    double result;
     dXSARGS;
     
     if ((items < 1) || (items > 1)) {
-      SWIG_croak("Usage: labelCacheMemberObj_text_get(self);");
+      SWIG_croak("Usage: labelCacheMemberObj_featuresize_get(self);");
     }
     res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_labelCacheMemberObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
-      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelCacheMemberObj_text_get" "', argument " "1"" of type '" "labelCacheMemberObj *""'"); 
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelCacheMemberObj_featuresize_get" "', argument " "1"" of type '" "labelCacheMemberObj *""'"); 
     }
     arg1 = (labelCacheMemberObj *)(argp1);
-    result = (char *) ((arg1)->text);
-    ST(argvi) = SWIG_FromCharPtr((const char *)result); argvi++ ;
+    result = (double) ((arg1)->featuresize);
+    ST(argvi) = SWIG_From_double  SWIG_PERL_CALL_ARGS_1((double)(result)); argvi++ ;
     
     XSRETURN(argvi);
   fail:
@@ -15574,25 +16720,25 @@ XS(_wrap_labelCacheMemberObj_text_get) {
 }
 
 
-XS(_wrap_labelCacheMemberObj_featuresize_get) {
+XS(_wrap_labelCacheMemberObj_styles_get) {
   {
     labelCacheMemberObj *arg1 = (labelCacheMemberObj *) 0 ;
     void *argp1 = 0 ;
     int res1 = 0 ;
     int argvi = 0;
-    double result;
+    styleObj *result = 0 ;
     dXSARGS;
     
     if ((items < 1) || (items > 1)) {
-      SWIG_croak("Usage: labelCacheMemberObj_featuresize_get(self);");
+      SWIG_croak("Usage: labelCacheMemberObj_styles_get(self);");
     }
     res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_labelCacheMemberObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
-      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelCacheMemberObj_featuresize_get" "', argument " "1"" of type '" "labelCacheMemberObj *""'"); 
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelCacheMemberObj_styles_get" "', argument " "1"" of type '" "labelCacheMemberObj *""'"); 
     }
     arg1 = (labelCacheMemberObj *)(argp1);
-    result = (double) ((arg1)->featuresize);
-    ST(argvi) = SWIG_From_double  SWIG_PERL_CALL_ARGS_1((double)(result)); argvi++ ;
+    result = (styleObj *) ((arg1)->styles);
+    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_styleObj, 0 | SWIG_SHADOW); argvi++ ;
     
     XSRETURN(argvi);
   fail:
@@ -15602,25 +16748,25 @@ XS(_wrap_labelCacheMemberObj_featuresize_get) {
 }
 
 
-XS(_wrap_labelCacheMemberObj_styles_get) {
+XS(_wrap_labelCacheMemberObj_numstyles_get) {
   {
     labelCacheMemberObj *arg1 = (labelCacheMemberObj *) 0 ;
     void *argp1 = 0 ;
     int res1 = 0 ;
     int argvi = 0;
-    styleObj *result = 0 ;
+    int result;
     dXSARGS;
     
     if ((items < 1) || (items > 1)) {
-      SWIG_croak("Usage: labelCacheMemberObj_styles_get(self);");
+      SWIG_croak("Usage: labelCacheMemberObj_numstyles_get(self);");
     }
     res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_labelCacheMemberObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
-      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelCacheMemberObj_styles_get" "', argument " "1"" of type '" "labelCacheMemberObj *""'"); 
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelCacheMemberObj_numstyles_get" "', argument " "1"" of type '" "labelCacheMemberObj *""'"); 
     }
     arg1 = (labelCacheMemberObj *)(argp1);
-    result = (styleObj *) ((arg1)->styles);
-    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_styleObj, 0 | SWIG_SHADOW); argvi++ ;
+    result = (int) ((arg1)->numstyles);
+    ST(argvi) = SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(result)); argvi++ ;
     
     XSRETURN(argvi);
   fail:
@@ -15630,25 +16776,25 @@ XS(_wrap_labelCacheMemberObj_styles_get) {
 }
 
 
-XS(_wrap_labelCacheMemberObj_numstyles_get) {
+XS(_wrap_labelCacheMemberObj_labels_get) {
   {
     labelCacheMemberObj *arg1 = (labelCacheMemberObj *) 0 ;
     void *argp1 = 0 ;
     int res1 = 0 ;
     int argvi = 0;
-    int result;
+    labelObj *result = 0 ;
     dXSARGS;
     
     if ((items < 1) || (items > 1)) {
-      SWIG_croak("Usage: labelCacheMemberObj_numstyles_get(self);");
+      SWIG_croak("Usage: labelCacheMemberObj_labels_get(self);");
     }
     res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_labelCacheMemberObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
-      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelCacheMemberObj_numstyles_get" "', argument " "1"" of type '" "labelCacheMemberObj *""'"); 
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelCacheMemberObj_labels_get" "', argument " "1"" of type '" "labelCacheMemberObj *""'"); 
     }
     arg1 = (labelCacheMemberObj *)(argp1);
-    result = (int) ((arg1)->numstyles);
-    ST(argvi) = SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(result)); argvi++ ;
+    result = (labelObj *) ((arg1)->labels);
+    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_labelObj, 0 | SWIG_SHADOW); argvi++ ;
     
     XSRETURN(argvi);
   fail:
@@ -15658,25 +16804,25 @@ XS(_wrap_labelCacheMemberObj_numstyles_get) {
 }
 
 
-XS(_wrap_labelCacheMemberObj_label_get) {
+XS(_wrap_labelCacheMemberObj_numlabels_get) {
   {
     labelCacheMemberObj *arg1 = (labelCacheMemberObj *) 0 ;
     void *argp1 = 0 ;
     int res1 = 0 ;
     int argvi = 0;
-    labelObj *result = 0 ;
+    int result;
     dXSARGS;
     
     if ((items < 1) || (items > 1)) {
-      SWIG_croak("Usage: labelCacheMemberObj_label_get(self);");
+      SWIG_croak("Usage: labelCacheMemberObj_numlabels_get(self);");
     }
     res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_labelCacheMemberObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
-      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelCacheMemberObj_label_get" "', argument " "1"" of type '" "labelCacheMemberObj *""'"); 
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelCacheMemberObj_numlabels_get" "', argument " "1"" of type '" "labelCacheMemberObj *""'"); 
     }
     arg1 = (labelCacheMemberObj *)(argp1);
-    result = (labelObj *)& ((arg1)->label);
-    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_labelObj, 0 | SWIG_SHADOW); argvi++ ;
+    result = (int) ((arg1)->numlabels);
+    ST(argvi) = SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(result)); argvi++ ;
     
     XSRETURN(argvi);
   fail:
@@ -15742,7 +16888,7 @@ XS(_wrap_labelCacheMemberObj_classindex_get) {
 }
 
 
-XS(_wrap_labelCacheMemberObj_tileindex_get) {
+XS(_wrap_labelCacheMemberObj_shapetype_get) {
   {
     labelCacheMemberObj *arg1 = (labelCacheMemberObj *) 0 ;
     void *argp1 = 0 ;
@@ -15752,14 +16898,14 @@ XS(_wrap_labelCacheMemberObj_tileindex_get) {
     dXSARGS;
     
     if ((items < 1) || (items > 1)) {
-      SWIG_croak("Usage: labelCacheMemberObj_tileindex_get(self);");
+      SWIG_croak("Usage: labelCacheMemberObj_shapetype_get(self);");
     }
     res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_labelCacheMemberObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
-      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelCacheMemberObj_tileindex_get" "', argument " "1"" of type '" "labelCacheMemberObj *""'"); 
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelCacheMemberObj_shapetype_get" "', argument " "1"" of type '" "labelCacheMemberObj *""'"); 
     }
     arg1 = (labelCacheMemberObj *)(argp1);
-    result = (int) ((arg1)->tileindex);
+    result = (int) ((arg1)->shapetype);
     ST(argvi) = SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(result)); argvi++ ;
     
     XSRETURN(argvi);
@@ -15770,25 +16916,25 @@ XS(_wrap_labelCacheMemberObj_tileindex_get) {
 }
 
 
-XS(_wrap_labelCacheMemberObj_shapeindex_get) {
+XS(_wrap_labelCacheMemberObj_point_get) {
   {
     labelCacheMemberObj *arg1 = (labelCacheMemberObj *) 0 ;
     void *argp1 = 0 ;
     int res1 = 0 ;
     int argvi = 0;
-    int result;
+    pointObj *result = 0 ;
     dXSARGS;
     
     if ((items < 1) || (items > 1)) {
-      SWIG_croak("Usage: labelCacheMemberObj_shapeindex_get(self);");
+      SWIG_croak("Usage: labelCacheMemberObj_point_get(self);");
     }
     res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_labelCacheMemberObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
-      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelCacheMemberObj_shapeindex_get" "', argument " "1"" of type '" "labelCacheMemberObj *""'"); 
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelCacheMemberObj_point_get" "', argument " "1"" of type '" "labelCacheMemberObj *""'"); 
     }
     arg1 = (labelCacheMemberObj *)(argp1);
-    result = (int) ((arg1)->shapeindex);
-    ST(argvi) = SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(result)); argvi++ ;
+    result = (pointObj *)& ((arg1)->point);
+    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_pointObj, 0 | SWIG_SHADOW); argvi++ ;
     
     XSRETURN(argvi);
   fail:
@@ -15798,25 +16944,25 @@ XS(_wrap_labelCacheMemberObj_shapeindex_get) {
 }
 
 
-XS(_wrap_labelCacheMemberObj_shapetype_get) {
+XS(_wrap_labelCacheMemberObj_poly_get) {
   {
     labelCacheMemberObj *arg1 = (labelCacheMemberObj *) 0 ;
     void *argp1 = 0 ;
     int res1 = 0 ;
     int argvi = 0;
-    int result;
+    shapeObj *result = 0 ;
     dXSARGS;
     
     if ((items < 1) || (items > 1)) {
-      SWIG_croak("Usage: labelCacheMemberObj_shapetype_get(self);");
+      SWIG_croak("Usage: labelCacheMemberObj_poly_get(self);");
     }
     res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_labelCacheMemberObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
-      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelCacheMemberObj_shapetype_get" "', argument " "1"" of type '" "labelCacheMemberObj *""'"); 
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelCacheMemberObj_poly_get" "', argument " "1"" of type '" "labelCacheMemberObj *""'"); 
     }
     arg1 = (labelCacheMemberObj *)(argp1);
-    result = (int) ((arg1)->shapetype);
-    ST(argvi) = SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(result)); argvi++ ;
+    result = (shapeObj *) ((arg1)->poly);
+    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_shapeObj, 0 | SWIG_SHADOW); argvi++ ;
     
     XSRETURN(argvi);
   fail:
@@ -15826,25 +16972,25 @@ XS(_wrap_labelCacheMemberObj_shapetype_get) {
 }
 
 
-XS(_wrap_labelCacheMemberObj_point_get) {
+XS(_wrap_labelCacheMemberObj_status_get) {
   {
     labelCacheMemberObj *arg1 = (labelCacheMemberObj *) 0 ;
     void *argp1 = 0 ;
     int res1 = 0 ;
     int argvi = 0;
-    pointObj *result = 0 ;
+    int result;
     dXSARGS;
     
     if ((items < 1) || (items > 1)) {
-      SWIG_croak("Usage: labelCacheMemberObj_point_get(self);");
+      SWIG_croak("Usage: labelCacheMemberObj_status_get(self);");
     }
     res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_labelCacheMemberObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
-      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelCacheMemberObj_point_get" "', argument " "1"" of type '" "labelCacheMemberObj *""'"); 
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelCacheMemberObj_status_get" "', argument " "1"" of type '" "labelCacheMemberObj *""'"); 
     }
     arg1 = (labelCacheMemberObj *)(argp1);
-    result = (pointObj *)& ((arg1)->point);
-    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_pointObj, 0 | SWIG_SHADOW); argvi++ ;
+    result = (int) ((arg1)->status);
+    ST(argvi) = SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(result)); argvi++ ;
     
     XSRETURN(argvi);
   fail:
@@ -15854,25 +17000,25 @@ XS(_wrap_labelCacheMemberObj_point_get) {
 }
 
 
-XS(_wrap_labelCacheMemberObj_poly_get) {
+XS(_wrap_labelCacheMemberObj_markerid_get) {
   {
     labelCacheMemberObj *arg1 = (labelCacheMemberObj *) 0 ;
     void *argp1 = 0 ;
     int res1 = 0 ;
     int argvi = 0;
-    shapeObj *result = 0 ;
+    int result;
     dXSARGS;
     
     if ((items < 1) || (items > 1)) {
-      SWIG_croak("Usage: labelCacheMemberObj_poly_get(self);");
+      SWIG_croak("Usage: labelCacheMemberObj_markerid_get(self);");
     }
     res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_labelCacheMemberObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
-      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelCacheMemberObj_poly_get" "', argument " "1"" of type '" "labelCacheMemberObj *""'"); 
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelCacheMemberObj_markerid_get" "', argument " "1"" of type '" "labelCacheMemberObj *""'"); 
     }
     arg1 = (labelCacheMemberObj *)(argp1);
-    result = (shapeObj *) ((arg1)->poly);
-    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_shapeObj, 0 | SWIG_SHADOW); argvi++ ;
+    result = (int) ((arg1)->markerid);
+    ST(argvi) = SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(result)); argvi++ ;
     
     XSRETURN(argvi);
   fail:
@@ -15882,25 +17028,25 @@ XS(_wrap_labelCacheMemberObj_poly_get) {
 }
 
 
-XS(_wrap_labelCacheMemberObj_status_get) {
+XS(_wrap_labelCacheMemberObj_leaderline_get) {
   {
     labelCacheMemberObj *arg1 = (labelCacheMemberObj *) 0 ;
     void *argp1 = 0 ;
     int res1 = 0 ;
     int argvi = 0;
-    int result;
+    lineObj *result = 0 ;
     dXSARGS;
     
     if ((items < 1) || (items > 1)) {
-      SWIG_croak("Usage: labelCacheMemberObj_status_get(self);");
+      SWIG_croak("Usage: labelCacheMemberObj_leaderline_get(self);");
     }
     res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_labelCacheMemberObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
-      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelCacheMemberObj_status_get" "', argument " "1"" of type '" "labelCacheMemberObj *""'"); 
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelCacheMemberObj_leaderline_get" "', argument " "1"" of type '" "labelCacheMemberObj *""'"); 
     }
     arg1 = (labelCacheMemberObj *)(argp1);
-    result = (int) ((arg1)->status);
-    ST(argvi) = SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(result)); argvi++ ;
+    result = (lineObj *) ((arg1)->leaderline);
+    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_lineObj, 0 | SWIG_SHADOW); argvi++ ;
     
     XSRETURN(argvi);
   fail:
@@ -15910,25 +17056,25 @@ XS(_wrap_labelCacheMemberObj_status_get) {
 }
 
 
-XS(_wrap_labelCacheMemberObj_markerid_get) {
+XS(_wrap_labelCacheMemberObj_leaderbbox_get) {
   {
     labelCacheMemberObj *arg1 = (labelCacheMemberObj *) 0 ;
     void *argp1 = 0 ;
     int res1 = 0 ;
     int argvi = 0;
-    int result;
+    rectObj *result = 0 ;
     dXSARGS;
     
     if ((items < 1) || (items > 1)) {
-      SWIG_croak("Usage: labelCacheMemberObj_markerid_get(self);");
+      SWIG_croak("Usage: labelCacheMemberObj_leaderbbox_get(self);");
     }
     res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_labelCacheMemberObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
-      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelCacheMemberObj_markerid_get" "', argument " "1"" of type '" "labelCacheMemberObj *""'"); 
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelCacheMemberObj_leaderbbox_get" "', argument " "1"" of type '" "labelCacheMemberObj *""'"); 
     }
     arg1 = (labelCacheMemberObj *)(argp1);
-    result = (int) ((arg1)->markerid);
-    ST(argvi) = SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(result)); argvi++ ;
+    result = (rectObj *) ((arg1)->leaderbbox);
+    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_rectObj, 0 | SWIG_SHADOW); argvi++ ;
     
     XSRETURN(argvi);
   fail:
@@ -16353,6 +17499,34 @@ XS(_wrap_labelCacheObj_numlabels_get) {
 }
 
 
+XS(_wrap_labelCacheObj_gutter_get) {
+  {
+    labelCacheObj *arg1 = (labelCacheObj *) 0 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int argvi = 0;
+    int result;
+    dXSARGS;
+    
+    if ((items < 1) || (items > 1)) {
+      SWIG_croak("Usage: labelCacheObj_gutter_get(self);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_labelCacheObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelCacheObj_gutter_get" "', argument " "1"" of type '" "labelCacheObj *""'"); 
+    }
+    arg1 = (labelCacheObj *)(argp1);
+    result = (int) ((arg1)->gutter);
+    ST(argvi) = SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(result)); argvi++ ;
+    
+    XSRETURN(argvi);
+  fail:
+    
+    SWIG_croak_null();
+  }
+}
+
+
 XS(_wrap_labelCacheObj_freeCache) {
   {
     labelCacheObj *arg1 = (labelCacheObj *) 0 ;
@@ -18084,7 +19258,7 @@ XS(_wrap_referenceMapObj_map_get) {
     void *argp1 = 0 ;
     int res1 = 0 ;
     int argvi = 0;
-    struct map_obj *result = 0 ;
+    struct mapObj *result = 0 ;
     dXSARGS;
     
     if ((items < 1) || (items > 1)) {
@@ -18097,10 +19271,10 @@ XS(_wrap_referenceMapObj_map_get) {
     arg1 = (referenceMapObj *)(argp1);
     {
       /* Accessing map */
-      result = (struct map_obj *) ((arg1)->map);;
+      result = (struct mapObj *) ((arg1)->map);;
       MS_REFCNT_INCR(result);
     }
-    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_map_obj, 0 | SWIG_SHADOW); argvi++ ;
+    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_mapObj, 0 | SWIG_SHADOW); argvi++ ;
     
     XSRETURN(argvi);
   fail:
@@ -19633,19 +20807,497 @@ XS(_wrap_legendObj_status_set) {
     if (arg1) (arg1)->status = arg2;
     ST(argvi) = sv_newmortal();
     
-    
+    
+    XSRETURN(argvi);
+  fail:
+    
+    
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_legendObj_status_get) {
+  {
+    legendObj *arg1 = (legendObj *) 0 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int argvi = 0;
+    int result;
+    dXSARGS;
+    
+    if ((items < 1) || (items > 1)) {
+      SWIG_croak("Usage: legendObj_status_get(self);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_legendObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "legendObj_status_get" "', argument " "1"" of type '" "legendObj *""'"); 
+    }
+    arg1 = (legendObj *)(argp1);
+    result = (int) ((arg1)->status);
+    ST(argvi) = SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(result)); argvi++ ;
+    
+    XSRETURN(argvi);
+  fail:
+    
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_legendObj_height_set) {
+  {
+    legendObj *arg1 = (legendObj *) 0 ;
+    int arg2 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int val2 ;
+    int ecode2 = 0 ;
+    int argvi = 0;
+    dXSARGS;
+    
+    if ((items < 2) || (items > 2)) {
+      SWIG_croak("Usage: legendObj_height_set(self,height);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_legendObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "legendObj_height_set" "', argument " "1"" of type '" "legendObj *""'"); 
+    }
+    arg1 = (legendObj *)(argp1);
+    ecode2 = SWIG_AsVal_int SWIG_PERL_CALL_ARGS_2(ST(1), &val2);
+    if (!SWIG_IsOK(ecode2)) {
+      SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "legendObj_height_set" "', argument " "2"" of type '" "int""'");
+    } 
+    arg2 = (int)(val2);
+    if (arg1) (arg1)->height = arg2;
+    ST(argvi) = sv_newmortal();
+    
+    
+    XSRETURN(argvi);
+  fail:
+    
+    
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_legendObj_height_get) {
+  {
+    legendObj *arg1 = (legendObj *) 0 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int argvi = 0;
+    int result;
+    dXSARGS;
+    
+    if ((items < 1) || (items > 1)) {
+      SWIG_croak("Usage: legendObj_height_get(self);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_legendObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "legendObj_height_get" "', argument " "1"" of type '" "legendObj *""'"); 
+    }
+    arg1 = (legendObj *)(argp1);
+    result = (int) ((arg1)->height);
+    ST(argvi) = SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(result)); argvi++ ;
+    
+    XSRETURN(argvi);
+  fail:
+    
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_legendObj_width_set) {
+  {
+    legendObj *arg1 = (legendObj *) 0 ;
+    int arg2 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int val2 ;
+    int ecode2 = 0 ;
+    int argvi = 0;
+    dXSARGS;
+    
+    if ((items < 2) || (items > 2)) {
+      SWIG_croak("Usage: legendObj_width_set(self,width);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_legendObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "legendObj_width_set" "', argument " "1"" of type '" "legendObj *""'"); 
+    }
+    arg1 = (legendObj *)(argp1);
+    ecode2 = SWIG_AsVal_int SWIG_PERL_CALL_ARGS_2(ST(1), &val2);
+    if (!SWIG_IsOK(ecode2)) {
+      SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "legendObj_width_set" "', argument " "2"" of type '" "int""'");
+    } 
+    arg2 = (int)(val2);
+    if (arg1) (arg1)->width = arg2;
+    ST(argvi) = sv_newmortal();
+    
+    
+    XSRETURN(argvi);
+  fail:
+    
+    
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_legendObj_width_get) {
+  {
+    legendObj *arg1 = (legendObj *) 0 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int argvi = 0;
+    int result;
+    dXSARGS;
+    
+    if ((items < 1) || (items > 1)) {
+      SWIG_croak("Usage: legendObj_width_get(self);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_legendObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "legendObj_width_get" "', argument " "1"" of type '" "legendObj *""'"); 
+    }
+    arg1 = (legendObj *)(argp1);
+    result = (int) ((arg1)->width);
+    ST(argvi) = SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(result)); argvi++ ;
+    
+    XSRETURN(argvi);
+  fail:
+    
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_legendObj_position_set) {
+  {
+    legendObj *arg1 = (legendObj *) 0 ;
+    int arg2 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int val2 ;
+    int ecode2 = 0 ;
+    int argvi = 0;
+    dXSARGS;
+    
+    if ((items < 2) || (items > 2)) {
+      SWIG_croak("Usage: legendObj_position_set(self,position);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_legendObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "legendObj_position_set" "', argument " "1"" of type '" "legendObj *""'"); 
+    }
+    arg1 = (legendObj *)(argp1);
+    ecode2 = SWIG_AsVal_int SWIG_PERL_CALL_ARGS_2(ST(1), &val2);
+    if (!SWIG_IsOK(ecode2)) {
+      SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "legendObj_position_set" "', argument " "2"" of type '" "int""'");
+    } 
+    arg2 = (int)(val2);
+    if (arg1) (arg1)->position = arg2;
+    ST(argvi) = sv_newmortal();
+    
+    
+    XSRETURN(argvi);
+  fail:
+    
+    
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_legendObj_position_get) {
+  {
+    legendObj *arg1 = (legendObj *) 0 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int argvi = 0;
+    int result;
+    dXSARGS;
+    
+    if ((items < 1) || (items > 1)) {
+      SWIG_croak("Usage: legendObj_position_get(self);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_legendObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "legendObj_position_get" "', argument " "1"" of type '" "legendObj *""'"); 
+    }
+    arg1 = (legendObj *)(argp1);
+    result = (int) ((arg1)->position);
+    ST(argvi) = SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(result)); argvi++ ;
+    
+    XSRETURN(argvi);
+  fail:
+    
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_legendObj_postlabelcache_set) {
+  {
+    legendObj *arg1 = (legendObj *) 0 ;
+    int arg2 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int val2 ;
+    int ecode2 = 0 ;
+    int argvi = 0;
+    dXSARGS;
+    
+    if ((items < 2) || (items > 2)) {
+      SWIG_croak("Usage: legendObj_postlabelcache_set(self,postlabelcache);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_legendObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "legendObj_postlabelcache_set" "', argument " "1"" of type '" "legendObj *""'"); 
+    }
+    arg1 = (legendObj *)(argp1);
+    ecode2 = SWIG_AsVal_int SWIG_PERL_CALL_ARGS_2(ST(1), &val2);
+    if (!SWIG_IsOK(ecode2)) {
+      SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "legendObj_postlabelcache_set" "', argument " "2"" of type '" "int""'");
+    } 
+    arg2 = (int)(val2);
+    if (arg1) (arg1)->postlabelcache = arg2;
+    ST(argvi) = sv_newmortal();
+    
+    
+    XSRETURN(argvi);
+  fail:
+    
+    
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_legendObj_postlabelcache_get) {
+  {
+    legendObj *arg1 = (legendObj *) 0 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int argvi = 0;
+    int result;
+    dXSARGS;
+    
+    if ((items < 1) || (items > 1)) {
+      SWIG_croak("Usage: legendObj_postlabelcache_get(self);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_legendObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "legendObj_postlabelcache_get" "', argument " "1"" of type '" "legendObj *""'"); 
+    }
+    arg1 = (legendObj *)(argp1);
+    result = (int) ((arg1)->postlabelcache);
+    ST(argvi) = SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(result)); argvi++ ;
+    
+    XSRETURN(argvi);
+  fail:
+    
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_legendObj_template_set) {
+  {
+    legendObj *arg1 = (legendObj *) 0 ;
+    char *arg2 = (char *) 0 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int res2 ;
+    char *buf2 = 0 ;
+    int alloc2 = 0 ;
+    int argvi = 0;
+    dXSARGS;
+    
+    if ((items < 2) || (items > 2)) {
+      SWIG_croak("Usage: legendObj_template_set(self,template);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_legendObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "legendObj_template_set" "', argument " "1"" of type '" "legendObj *""'"); 
+    }
+    arg1 = (legendObj *)(argp1);
+    res2 = SWIG_AsCharPtrAndSize(ST(1), &buf2, NULL, &alloc2);
+    if (!SWIG_IsOK(res2)) {
+      SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "legendObj_template_set" "', argument " "2"" of type '" "char *""'");
+    }
+    arg2 = (char *)(buf2);
+    {
+      if (arg1->template) free((char*)arg1->template);
+      if (arg2) {
+        arg1->template = (char *) malloc(strlen(arg2)+1);
+        strcpy((char*)arg1->template,arg2);
+      } else {
+        arg1->template = 0;
+      }
+    }
+    ST(argvi) = sv_newmortal();
+    
+    if (alloc2 == SWIG_NEWOBJ) free((char*)buf2);
+    XSRETURN(argvi);
+  fail:
+    
+    if (alloc2 == SWIG_NEWOBJ) free((char*)buf2);
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_legendObj_template_get) {
+  {
+    legendObj *arg1 = (legendObj *) 0 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int argvi = 0;
+    char *result = 0 ;
+    dXSARGS;
+    
+    if ((items < 1) || (items > 1)) {
+      SWIG_croak("Usage: legendObj_template_get(self);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_legendObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "legendObj_template_get" "', argument " "1"" of type '" "legendObj *""'"); 
+    }
+    arg1 = (legendObj *)(argp1);
+    result = (char *) ((arg1)->template);
+    ST(argvi) = SWIG_FromCharPtr((const char *)result); argvi++ ;
+    
+    XSRETURN(argvi);
+  fail:
+    
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_legendObj_map_get) {
+  {
+    legendObj *arg1 = (legendObj *) 0 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int argvi = 0;
+    struct mapObj *result = 0 ;
+    dXSARGS;
+    
+    if ((items < 1) || (items > 1)) {
+      SWIG_croak("Usage: legendObj_map_get(self);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_legendObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "legendObj_map_get" "', argument " "1"" of type '" "legendObj *""'"); 
+    }
+    arg1 = (legendObj *)(argp1);
+    {
+      /* Accessing map */
+      result = (struct mapObj *) ((arg1)->map);;
+      MS_REFCNT_INCR(result);
+    }
+    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_mapObj, 0 | SWIG_SHADOW); argvi++ ;
+    
+    XSRETURN(argvi);
+  fail:
+    
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_legendObj_updateFromString) {
+  {
+    legendObj *arg1 = (legendObj *) 0 ;
+    char *arg2 = (char *) 0 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int res2 ;
+    char *buf2 = 0 ;
+    int alloc2 = 0 ;
+    int argvi = 0;
+    int result;
+    dXSARGS;
+    
+    if ((items < 2) || (items > 2)) {
+      SWIG_croak("Usage: legendObj_updateFromString(self,snippet);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_legendObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "legendObj_updateFromString" "', argument " "1"" of type '" "legendObj *""'"); 
+    }
+    arg1 = (legendObj *)(argp1);
+    res2 = SWIG_AsCharPtrAndSize(ST(1), &buf2, NULL, &alloc2);
+    if (!SWIG_IsOK(res2)) {
+      SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "legendObj_updateFromString" "', argument " "2"" of type '" "char *""'");
+    }
+    arg2 = (char *)(buf2);
+    result = (int)legendObj_updateFromString(arg1,arg2);
+    ST(argvi) = SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(result)); argvi++ ;
+    
+    if (alloc2 == SWIG_NEWOBJ) free((char*)buf2);
+    XSRETURN(argvi);
+  fail:
+    
+    if (alloc2 == SWIG_NEWOBJ) free((char*)buf2);
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_new_legendObj) {
+  {
+    int argvi = 0;
+    legendObj *result = 0 ;
+    dXSARGS;
+    
+    if ((items < 0) || (items > 0)) {
+      SWIG_croak("Usage: new_legendObj();");
+    }
+    result = (legendObj *)calloc(1, sizeof(legendObj));
+    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_legendObj, SWIG_OWNER | SWIG_SHADOW); argvi++ ;
+    XSRETURN(argvi);
+  fail:
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_delete_legendObj) {
+  {
+    legendObj *arg1 = (legendObj *) 0 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int argvi = 0;
+    dXSARGS;
+    
+    if ((items < 1) || (items > 1)) {
+      SWIG_croak("Usage: delete_legendObj(self);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_legendObj, SWIG_POINTER_DISOWN |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_legendObj" "', argument " "1"" of type '" "legendObj *""'"); 
+    }
+    arg1 = (legendObj *)(argp1);
+    free((char *) arg1);
+    ST(argvi) = sv_newmortal();
+    
     XSRETURN(argvi);
   fail:
     
-    
     SWIG_croak_null();
   }
 }
 
 
-XS(_wrap_legendObj_status_get) {
+XS(_wrap_imageObj_width_get) {
   {
-    legendObj *arg1 = (legendObj *) 0 ;
+    imageObj *arg1 = (imageObj *) 0 ;
     void *argp1 = 0 ;
     int res1 = 0 ;
     int argvi = 0;
@@ -19653,14 +21305,14 @@ XS(_wrap_legendObj_status_get) {
     dXSARGS;
     
     if ((items < 1) || (items > 1)) {
-      SWIG_croak("Usage: legendObj_status_get(self);");
+      SWIG_croak("Usage: imageObj_width_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_legendObj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_imageObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
-      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "legendObj_status_get" "', argument " "1"" of type '" "legendObj *""'"); 
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "imageObj_width_get" "', argument " "1"" of type '" "imageObj *""'"); 
     }
-    arg1 = (legendObj *)(argp1);
-    result = (int) ((arg1)->status);
+    arg1 = (imageObj *)(argp1);
+    result = (int) ((arg1)->width);
     ST(argvi) = SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(result)); argvi++ ;
     
     XSRETURN(argvi);
@@ -19671,62 +21323,53 @@ XS(_wrap_legendObj_status_get) {
 }
 
 
-XS(_wrap_legendObj_height_set) {
+XS(_wrap_imageObj_height_get) {
   {
-    legendObj *arg1 = (legendObj *) 0 ;
-    int arg2 ;
+    imageObj *arg1 = (imageObj *) 0 ;
     void *argp1 = 0 ;
     int res1 = 0 ;
-    int val2 ;
-    int ecode2 = 0 ;
     int argvi = 0;
+    int result;
     dXSARGS;
     
-    if ((items < 2) || (items > 2)) {
-      SWIG_croak("Usage: legendObj_height_set(self,height);");
+    if ((items < 1) || (items > 1)) {
+      SWIG_croak("Usage: imageObj_height_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_legendObj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_imageObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
-      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "legendObj_height_set" "', argument " "1"" of type '" "legendObj *""'"); 
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "imageObj_height_get" "', argument " "1"" of type '" "imageObj *""'"); 
     }
-    arg1 = (legendObj *)(argp1);
-    ecode2 = SWIG_AsVal_int SWIG_PERL_CALL_ARGS_2(ST(1), &val2);
-    if (!SWIG_IsOK(ecode2)) {
-      SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "legendObj_height_set" "', argument " "2"" of type '" "int""'");
-    } 
-    arg2 = (int)(val2);
-    if (arg1) (arg1)->height = arg2;
-    ST(argvi) = sv_newmortal();
-    
+    arg1 = (imageObj *)(argp1);
+    result = (int) ((arg1)->height);
+    ST(argvi) = SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(result)); argvi++ ;
     
     XSRETURN(argvi);
   fail:
     
-    
     SWIG_croak_null();
   }
 }
 
 
-XS(_wrap_legendObj_height_get) {
+XS(_wrap_imageObj_resolution_get) {
   {
-    legendObj *arg1 = (legendObj *) 0 ;
+    imageObj *arg1 = (imageObj *) 0 ;
     void *argp1 = 0 ;
     int res1 = 0 ;
     int argvi = 0;
-    int result;
+    double result;
     dXSARGS;
     
     if ((items < 1) || (items > 1)) {
-      SWIG_croak("Usage: legendObj_height_get(self);");
+      SWIG_croak("Usage: imageObj_resolution_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_legendObj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_imageObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
-      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "legendObj_height_get" "', argument " "1"" of type '" "legendObj *""'"); 
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "imageObj_resolution_get" "', argument " "1"" of type '" "imageObj *""'"); 
     }
-    arg1 = (legendObj *)(argp1);
-    result = (int) ((arg1)->height);
-    ST(argvi) = SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(result)); argvi++ ;
+    arg1 = (imageObj *)(argp1);
+    result = (double) ((arg1)->resolution);
+    ST(argvi) = SWIG_From_double  SWIG_PERL_CALL_ARGS_1((double)(result)); argvi++ ;
     
     XSRETURN(argvi);
   fail:
@@ -19736,62 +21379,53 @@ XS(_wrap_legendObj_height_get) {
 }
 
 
-XS(_wrap_legendObj_width_set) {
+XS(_wrap_imageObj_resolutionfactor_get) {
   {
-    legendObj *arg1 = (legendObj *) 0 ;
-    int arg2 ;
+    imageObj *arg1 = (imageObj *) 0 ;
     void *argp1 = 0 ;
     int res1 = 0 ;
-    int val2 ;
-    int ecode2 = 0 ;
     int argvi = 0;
+    double result;
     dXSARGS;
     
-    if ((items < 2) || (items > 2)) {
-      SWIG_croak("Usage: legendObj_width_set(self,width);");
+    if ((items < 1) || (items > 1)) {
+      SWIG_croak("Usage: imageObj_resolutionfactor_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_legendObj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_imageObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
-      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "legendObj_width_set" "', argument " "1"" of type '" "legendObj *""'"); 
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "imageObj_resolutionfactor_get" "', argument " "1"" of type '" "imageObj *""'"); 
     }
-    arg1 = (legendObj *)(argp1);
-    ecode2 = SWIG_AsVal_int SWIG_PERL_CALL_ARGS_2(ST(1), &val2);
-    if (!SWIG_IsOK(ecode2)) {
-      SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "legendObj_width_set" "', argument " "2"" of type '" "int""'");
-    } 
-    arg2 = (int)(val2);
-    if (arg1) (arg1)->width = arg2;
-    ST(argvi) = sv_newmortal();
-    
+    arg1 = (imageObj *)(argp1);
+    result = (double) ((arg1)->resolutionfactor);
+    ST(argvi) = SWIG_From_double  SWIG_PERL_CALL_ARGS_1((double)(result)); argvi++ ;
     
     XSRETURN(argvi);
   fail:
     
-    
     SWIG_croak_null();
   }
 }
 
 
-XS(_wrap_legendObj_width_get) {
+XS(_wrap_imageObj_imagepath_get) {
   {
-    legendObj *arg1 = (legendObj *) 0 ;
+    imageObj *arg1 = (imageObj *) 0 ;
     void *argp1 = 0 ;
     int res1 = 0 ;
     int argvi = 0;
-    int result;
+    char *result = 0 ;
     dXSARGS;
     
     if ((items < 1) || (items > 1)) {
-      SWIG_croak("Usage: legendObj_width_get(self);");
+      SWIG_croak("Usage: imageObj_imagepath_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_legendObj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_imageObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
-      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "legendObj_width_get" "', argument " "1"" of type '" "legendObj *""'"); 
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "imageObj_imagepath_get" "', argument " "1"" of type '" "imageObj *""'"); 
     }
-    arg1 = (legendObj *)(argp1);
-    result = (int) ((arg1)->width);
-    ST(argvi) = SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(result)); argvi++ ;
+    arg1 = (imageObj *)(argp1);
+    result = (char *) ((arg1)->imagepath);
+    ST(argvi) = SWIG_FromCharPtr((const char *)result); argvi++ ;
     
     XSRETURN(argvi);
   fail:
@@ -19801,62 +21435,53 @@ XS(_wrap_legendObj_width_get) {
 }
 
 
-XS(_wrap_legendObj_position_set) {
+XS(_wrap_imageObj_imageurl_get) {
   {
-    legendObj *arg1 = (legendObj *) 0 ;
-    int arg2 ;
+    imageObj *arg1 = (imageObj *) 0 ;
     void *argp1 = 0 ;
     int res1 = 0 ;
-    int val2 ;
-    int ecode2 = 0 ;
     int argvi = 0;
+    char *result = 0 ;
     dXSARGS;
     
-    if ((items < 2) || (items > 2)) {
-      SWIG_croak("Usage: legendObj_position_set(self,position);");
+    if ((items < 1) || (items > 1)) {
+      SWIG_croak("Usage: imageObj_imageurl_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_legendObj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_imageObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
-      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "legendObj_position_set" "', argument " "1"" of type '" "legendObj *""'"); 
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "imageObj_imageurl_get" "', argument " "1"" of type '" "imageObj *""'"); 
     }
-    arg1 = (legendObj *)(argp1);
-    ecode2 = SWIG_AsVal_int SWIG_PERL_CALL_ARGS_2(ST(1), &val2);
-    if (!SWIG_IsOK(ecode2)) {
-      SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "legendObj_position_set" "', argument " "2"" of type '" "int""'");
-    } 
-    arg2 = (int)(val2);
-    if (arg1) (arg1)->position = arg2;
-    ST(argvi) = sv_newmortal();
-    
+    arg1 = (imageObj *)(argp1);
+    result = (char *) ((arg1)->imageurl);
+    ST(argvi) = SWIG_FromCharPtr((const char *)result); argvi++ ;
     
     XSRETURN(argvi);
   fail:
     
-    
     SWIG_croak_null();
   }
 }
 
 
-XS(_wrap_legendObj_position_get) {
+XS(_wrap_imageObj_format_get) {
   {
-    legendObj *arg1 = (legendObj *) 0 ;
+    imageObj *arg1 = (imageObj *) 0 ;
     void *argp1 = 0 ;
     int res1 = 0 ;
     int argvi = 0;
-    int result;
+    outputFormatObj *result = 0 ;
     dXSARGS;
     
     if ((items < 1) || (items > 1)) {
-      SWIG_croak("Usage: legendObj_position_get(self);");
+      SWIG_croak("Usage: imageObj_format_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_legendObj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_imageObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
-      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "legendObj_position_get" "', argument " "1"" of type '" "legendObj *""'"); 
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "imageObj_format_get" "', argument " "1"" of type '" "imageObj *""'"); 
     }
-    arg1 = (legendObj *)(argp1);
-    result = (int) ((arg1)->position);
-    ST(argvi) = SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(result)); argvi++ ;
+    arg1 = (imageObj *)(argp1);
+    result = (outputFormatObj *) ((arg1)->format);
+    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_outputFormatObj, 0 | SWIG_SHADOW); argvi++ ;
     
     XSRETURN(argvi);
   fail:
@@ -19866,62 +21491,111 @@ XS(_wrap_legendObj_position_get) {
 }
 
 
-XS(_wrap_legendObj_postlabelcache_set) {
+XS(_wrap_new_imageObj) {
   {
-    legendObj *arg1 = (legendObj *) 0 ;
+    int arg1 ;
     int arg2 ;
-    void *argp1 = 0 ;
-    int res1 = 0 ;
+    outputFormatObj *arg3 = (outputFormatObj *) NULL ;
+    char *arg4 = (char *) NULL ;
+    double arg5 = (double) MS_DEFAULT_RESOLUTION ;
+    double arg6 = (double) MS_DEFAULT_RESOLUTION ;
+    int val1 ;
+    int ecode1 = 0 ;
     int val2 ;
     int ecode2 = 0 ;
+    void *argp3 = 0 ;
+    int res3 = 0 ;
+    int res4 ;
+    char *buf4 = 0 ;
+    int alloc4 = 0 ;
+    double val5 ;
+    int ecode5 = 0 ;
+    double val6 ;
+    int ecode6 = 0 ;
     int argvi = 0;
+    imageObj *result = 0 ;
     dXSARGS;
     
-    if ((items < 2) || (items > 2)) {
-      SWIG_croak("Usage: legendObj_postlabelcache_set(self,postlabelcache);");
-    }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_legendObj, 0 |  0 );
-    if (!SWIG_IsOK(res1)) {
-      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "legendObj_postlabelcache_set" "', argument " "1"" of type '" "legendObj *""'"); 
+    if ((items < 2) || (items > 6)) {
+      SWIG_croak("Usage: new_imageObj(width,height,input_format,file,resolution,defresolution);");
     }
-    arg1 = (legendObj *)(argp1);
+    ecode1 = SWIG_AsVal_int SWIG_PERL_CALL_ARGS_2(ST(0), &val1);
+    if (!SWIG_IsOK(ecode1)) {
+      SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "new_imageObj" "', argument " "1"" of type '" "int""'");
+    } 
+    arg1 = (int)(val1);
     ecode2 = SWIG_AsVal_int SWIG_PERL_CALL_ARGS_2(ST(1), &val2);
     if (!SWIG_IsOK(ecode2)) {
-      SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "legendObj_postlabelcache_set" "', argument " "2"" of type '" "int""'");
+      SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "new_imageObj" "', argument " "2"" of type '" "int""'");
     } 
     arg2 = (int)(val2);
-    if (arg1) (arg1)->postlabelcache = arg2;
-    ST(argvi) = sv_newmortal();
+    if (items > 2) {
+      res3 = SWIG_ConvertPtr(ST(2), &argp3,SWIGTYPE_p_outputFormatObj, 0 |  0 );
+      if (!SWIG_IsOK(res3)) {
+        SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "new_imageObj" "', argument " "3"" of type '" "outputFormatObj *""'"); 
+      }
+      arg3 = (outputFormatObj *)(argp3);
+    }
+    if (items > 3) {
+      res4 = SWIG_AsCharPtrAndSize(ST(3), &buf4, NULL, &alloc4);
+      if (!SWIG_IsOK(res4)) {
+        SWIG_exception_fail(SWIG_ArgError(res4), "in method '" "new_imageObj" "', argument " "4"" of type '" "char const *""'");
+      }
+      arg4 = (char *)(buf4);
+    }
+    if (items > 4) {
+      ecode5 = SWIG_AsVal_double SWIG_PERL_CALL_ARGS_2(ST(4), &val5);
+      if (!SWIG_IsOK(ecode5)) {
+        SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "new_imageObj" "', argument " "5"" of type '" "double""'");
+      } 
+      arg5 = (double)(val5);
+    }
+    if (items > 5) {
+      ecode6 = SWIG_AsVal_double SWIG_PERL_CALL_ARGS_2(ST(5), &val6);
+      if (!SWIG_IsOK(ecode6)) {
+        SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "new_imageObj" "', argument " "6"" of type '" "double""'");
+      } 
+      arg6 = (double)(val6);
+    }
+    result = (imageObj *)new_imageObj(arg1,arg2,arg3,(char const *)arg4,arg5,arg6);
+    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_imageObj, SWIG_OWNER | SWIG_SHADOW); argvi++ ;
+    
+    
+    
+    if (alloc4 == SWIG_NEWOBJ) free((char*)buf4);
     
     
     XSRETURN(argvi);
   fail:
     
     
+    
+    if (alloc4 == SWIG_NEWOBJ) free((char*)buf4);
+    
+    
     SWIG_croak_null();
   }
 }
 
 
-XS(_wrap_legendObj_postlabelcache_get) {
+XS(_wrap_delete_imageObj) {
   {
-    legendObj *arg1 = (legendObj *) 0 ;
+    imageObj *arg1 = (imageObj *) 0 ;
     void *argp1 = 0 ;
     int res1 = 0 ;
     int argvi = 0;
-    int result;
     dXSARGS;
     
     if ((items < 1) || (items > 1)) {
-      SWIG_croak("Usage: legendObj_postlabelcache_get(self);");
+      SWIG_croak("Usage: delete_imageObj(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_legendObj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_imageObj, SWIG_POINTER_DISOWN |  0 );
     if (!SWIG_IsOK(res1)) {
-      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "legendObj_postlabelcache_get" "', argument " "1"" of type '" "legendObj *""'"); 
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_imageObj" "', argument " "1"" of type '" "imageObj *""'"); 
     }
-    arg1 = (legendObj *)(argp1);
-    result = (int) ((arg1)->postlabelcache);
-    ST(argvi) = SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(result)); argvi++ ;
+    arg1 = (imageObj *)(argp1);
+    delete_imageObj(arg1);
+    ST(argvi) = sv_newmortal();
     
     XSRETURN(argvi);
   fail:
@@ -19931,103 +21605,123 @@ XS(_wrap_legendObj_postlabelcache_get) {
 }
 
 
-XS(_wrap_legendObj_template_set) {
+XS(_wrap_imageObj_save) {
   {
-    legendObj *arg1 = (legendObj *) 0 ;
+    imageObj *arg1 = (imageObj *) 0 ;
     char *arg2 = (char *) 0 ;
+    mapObj *arg3 = (mapObj *) NULL ;
     void *argp1 = 0 ;
     int res1 = 0 ;
     int res2 ;
     char *buf2 = 0 ;
     int alloc2 = 0 ;
+    void *argp3 = 0 ;
+    int res3 = 0 ;
     int argvi = 0;
     dXSARGS;
     
-    if ((items < 2) || (items > 2)) {
-      SWIG_croak("Usage: legendObj_template_set(self,template);");
+    if ((items < 2) || (items > 3)) {
+      SWIG_croak("Usage: imageObj_save(self,filename,map);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_legendObj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_imageObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
-      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "legendObj_template_set" "', argument " "1"" of type '" "legendObj *""'"); 
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "imageObj_save" "', argument " "1"" of type '" "imageObj *""'"); 
     }
-    arg1 = (legendObj *)(argp1);
+    arg1 = (imageObj *)(argp1);
     res2 = SWIG_AsCharPtrAndSize(ST(1), &buf2, NULL, &alloc2);
     if (!SWIG_IsOK(res2)) {
-      SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "legendObj_template_set" "', argument " "2"" of type '" "char *""'");
+      SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "imageObj_save" "', argument " "2"" of type '" "char *""'");
     }
     arg2 = (char *)(buf2);
-    {
-      if (arg1->template) free((char*)arg1->template);
-      if (arg2) {
-        arg1->template = (char *) malloc(strlen(arg2)+1);
-        strcpy((char*)arg1->template,arg2);
-      } else {
-        arg1->template = 0;
+    if (items > 2) {
+      res3 = SWIG_ConvertPtr(ST(2), &argp3,SWIGTYPE_p_mapObj, 0 |  0 );
+      if (!SWIG_IsOK(res3)) {
+        SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "imageObj_save" "', argument " "3"" of type '" "mapObj *""'"); 
       }
+      arg3 = (mapObj *)(argp3);
     }
+    imageObj_save(arg1,arg2,arg3);
     ST(argvi) = sv_newmortal();
     
     if (alloc2 == SWIG_NEWOBJ) free((char*)buf2);
+    
     XSRETURN(argvi);
   fail:
     
     if (alloc2 == SWIG_NEWOBJ) free((char*)buf2);
+    
     SWIG_croak_null();
   }
 }
 
 
-XS(_wrap_legendObj_template_get) {
+XS(_wrap_imageObj_write) {
   {
-    legendObj *arg1 = (legendObj *) 0 ;
+    imageObj *arg1 = (imageObj *) 0 ;
+    FILE *arg2 = (FILE *) NULL ;
     void *argp1 = 0 ;
     int res1 = 0 ;
     int argvi = 0;
-    char *result = 0 ;
+    int result;
     dXSARGS;
     
-    if ((items < 1) || (items > 1)) {
-      SWIG_croak("Usage: legendObj_template_get(self);");
+    if ((items < 1) || (items > 2)) {
+      SWIG_croak("Usage: imageObj_write(self,file);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_legendObj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_imageObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
-      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "legendObj_template_get" "', argument " "1"" of type '" "legendObj *""'"); 
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "imageObj_write" "', argument " "1"" of type '" "imageObj *""'"); 
     }
-    arg1 = (legendObj *)(argp1);
-    result = (char *) ((arg1)->template);
-    ST(argvi) = SWIG_FromCharPtr((const char *)result); argvi++ ;
+    arg1 = (imageObj *)(argp1);
+    if (items > 1) {
+      {
+        arg2 = PerlIO_exportFILE (IoIFP (sv_2io (ST(1))), NULL);
+      }
+    }
+    result = (int)imageObj_write(arg1,arg2);
+    ST(argvi) = SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(result)); argvi++ ;
+    
     
     XSRETURN(argvi);
   fail:
     
+    
     SWIG_croak_null();
   }
 }
 
 
-XS(_wrap_legendObj_map_get) {
+XS(_wrap_imageObj_getBytes) {
   {
-    legendObj *arg1 = (legendObj *) 0 ;
+    imageObj *arg1 = (imageObj *) 0 ;
     void *argp1 = 0 ;
     int res1 = 0 ;
     int argvi = 0;
-    struct map_obj *result = 0 ;
+    gdBuffer result;
     dXSARGS;
     
     if ((items < 1) || (items > 1)) {
-      SWIG_croak("Usage: legendObj_map_get(self);");
+      SWIG_croak("Usage: imageObj_getBytes(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_legendObj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_imageObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
-      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "legendObj_map_get" "', argument " "1"" of type '" "legendObj *""'"); 
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "imageObj_getBytes" "', argument " "1"" of type '" "imageObj *""'"); 
     }
-    arg1 = (legendObj *)(argp1);
+    arg1 = (imageObj *)(argp1);
+    result = imageObj_getBytes(arg1);
     {
-      /* Accessing map */
-      result = (struct map_obj *) ((arg1)->map);;
-      MS_REFCNT_INCR(result);
+      SV *mysv;
+      mysv = sv_newmortal();
+      if ((&result)->data == NULL)
+      sv_setpv(mysv,"");
+      else
+      sv_setpvn(mysv,(const char*)(&result)->data,(&result)->size);
+      ST(argvi) = newRV(mysv);
+      sv_2mortal(ST(argvi));
+      argvi++;
+      if( (&result)->owns_data )
+      msFree((&result)->data);
     }
-    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_map_obj, 0 | SWIG_SHADOW); argvi++ ;
     
     XSRETURN(argvi);
   fail:
@@ -20037,81 +21731,25 @@ XS(_wrap_legendObj_map_get) {
 }
 
 
-XS(_wrap_legendObj_updateFromString) {
+XS(_wrap_imageObj_getSize) {
   {
-    legendObj *arg1 = (legendObj *) 0 ;
-    char *arg2 = (char *) 0 ;
+    imageObj *arg1 = (imageObj *) 0 ;
     void *argp1 = 0 ;
     int res1 = 0 ;
-    int res2 ;
-    char *buf2 = 0 ;
-    int alloc2 = 0 ;
     int argvi = 0;
     int result;
     dXSARGS;
     
-    if ((items < 2) || (items > 2)) {
-      SWIG_croak("Usage: legendObj_updateFromString(self,snippet);");
-    }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_legendObj, 0 |  0 );
-    if (!SWIG_IsOK(res1)) {
-      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "legendObj_updateFromString" "', argument " "1"" of type '" "legendObj *""'"); 
-    }
-    arg1 = (legendObj *)(argp1);
-    res2 = SWIG_AsCharPtrAndSize(ST(1), &buf2, NULL, &alloc2);
-    if (!SWIG_IsOK(res2)) {
-      SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "legendObj_updateFromString" "', argument " "2"" of type '" "char *""'");
-    }
-    arg2 = (char *)(buf2);
-    result = (int)legendObj_updateFromString(arg1,arg2);
-    ST(argvi) = SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(result)); argvi++ ;
-    
-    if (alloc2 == SWIG_NEWOBJ) free((char*)buf2);
-    XSRETURN(argvi);
-  fail:
-    
-    if (alloc2 == SWIG_NEWOBJ) free((char*)buf2);
-    SWIG_croak_null();
-  }
-}
-
-
-XS(_wrap_new_legendObj) {
-  {
-    int argvi = 0;
-    legendObj *result = 0 ;
-    dXSARGS;
-    
-    if ((items < 0) || (items > 0)) {
-      SWIG_croak("Usage: new_legendObj();");
-    }
-    result = (legendObj *)calloc(1, sizeof(legendObj));
-    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_legendObj, SWIG_OWNER | SWIG_SHADOW); argvi++ ;
-    XSRETURN(argvi);
-  fail:
-    SWIG_croak_null();
-  }
-}
-
-
-XS(_wrap_delete_legendObj) {
-  {
-    legendObj *arg1 = (legendObj *) 0 ;
-    void *argp1 = 0 ;
-    int res1 = 0 ;
-    int argvi = 0;
-    dXSARGS;
-    
     if ((items < 1) || (items > 1)) {
-      SWIG_croak("Usage: delete_legendObj(self);");
+      SWIG_croak("Usage: imageObj_getSize(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_legendObj, SWIG_POINTER_DISOWN |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_imageObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
-      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_legendObj" "', argument " "1"" of type '" "legendObj *""'"); 
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "imageObj_getSize" "', argument " "1"" of type '" "imageObj *""'"); 
     }
-    arg1 = (legendObj *)(argp1);
-    free((char *) arg1);
-    ST(argvi) = sv_newmortal();
+    arg1 = (imageObj *)(argp1);
+    result = (int)imageObj_getSize(arg1);
+    ST(argvi) = SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(result)); argvi++ ;
     
     XSRETURN(argvi);
   fail:
@@ -20136,7 +21774,7 @@ XS(_wrap_layerObj_classitem_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_classitem_set(self,classitem);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_classitem_set" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -20179,7 +21817,7 @@ XS(_wrap_layerObj_classitem_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_classitem_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_classitem_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -20207,7 +21845,7 @@ XS(_wrap_layerObj_refcount_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_refcount_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_refcount_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -20235,7 +21873,7 @@ XS(_wrap_layerObj_numclasses_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_numclasses_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_numclasses_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -20263,7 +21901,7 @@ XS(_wrap_layerObj_maxclasses_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_maxclasses_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_maxclasses_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -20291,7 +21929,7 @@ XS(_wrap_layerObj_index_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_index_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_index_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -20313,23 +21951,23 @@ XS(_wrap_layerObj_map_get) {
     void *argp1 = 0 ;
     int res1 = 0 ;
     int argvi = 0;
-    struct map_obj *result = 0 ;
+    struct mapObj *result = 0 ;
     dXSARGS;
     
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_map_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_map_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
     arg1 = (layerObj *)(argp1);
     {
       /* Accessing map */
-      result = (struct map_obj *) ((arg1)->map);;
+      result = (struct mapObj *) ((arg1)->map);;
       MS_REFCNT_INCR(result);
     }
-    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_map_obj, 0 | SWIG_SHADOW); argvi++ ;
+    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_mapObj, 0 | SWIG_SHADOW); argvi++ ;
     
     XSRETURN(argvi);
   fail:
@@ -20354,7 +21992,7 @@ XS(_wrap_layerObj_header_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_header_set(self,header);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_header_set" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -20397,7 +22035,7 @@ XS(_wrap_layerObj_header_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_header_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_header_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -20428,7 +22066,7 @@ XS(_wrap_layerObj_footer_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_footer_set(self,footer);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_footer_set" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -20471,7 +22109,7 @@ XS(_wrap_layerObj_footer_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_footer_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_footer_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -20502,7 +22140,7 @@ XS(_wrap_layerObj_template_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_template_set(self,template);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_template_set" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -20545,7 +22183,7 @@ XS(_wrap_layerObj_template_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_template_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_template_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -20576,7 +22214,7 @@ XS(_wrap_layerObj_name_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_name_set(self,name);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_name_set" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -20619,7 +22257,7 @@ XS(_wrap_layerObj_name_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_name_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_name_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -20650,7 +22288,7 @@ XS(_wrap_layerObj_group_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_group_set(self,group);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_group_set" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -20693,7 +22331,7 @@ XS(_wrap_layerObj_group_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_group_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_group_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -20723,7 +22361,7 @@ XS(_wrap_layerObj_status_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_status_set(self,status);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_status_set" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -20758,7 +22396,7 @@ XS(_wrap_layerObj_status_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_status_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_status_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -20789,7 +22427,7 @@ XS(_wrap_layerObj_data_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_data_set(self,data);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_data_set" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -20832,7 +22470,7 @@ XS(_wrap_layerObj_data_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_data_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_data_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -20862,7 +22500,7 @@ XS(_wrap_layerObj_type_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_type_set(self,type);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_type_set" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -20897,7 +22535,7 @@ XS(_wrap_layerObj_type_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_type_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_type_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -20927,7 +22565,7 @@ XS(_wrap_layerObj_tolerance_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_tolerance_set(self,tolerance);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_tolerance_set" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -20962,7 +22600,7 @@ XS(_wrap_layerObj_tolerance_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_tolerance_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_tolerance_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -20992,7 +22630,7 @@ XS(_wrap_layerObj_toleranceunits_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_toleranceunits_set(self,toleranceunits);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_toleranceunits_set" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -21027,7 +22665,7 @@ XS(_wrap_layerObj_toleranceunits_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_toleranceunits_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_toleranceunits_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -21057,7 +22695,7 @@ XS(_wrap_layerObj_symbolscaledenom_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_symbolscaledenom_set(self,symbolscaledenom);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_symbolscaledenom_set" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -21092,7 +22730,7 @@ XS(_wrap_layerObj_symbolscaledenom_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_symbolscaledenom_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_symbolscaledenom_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -21122,7 +22760,7 @@ XS(_wrap_layerObj_minscaledenom_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_minscaledenom_set(self,minscaledenom);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_minscaledenom_set" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -21157,7 +22795,7 @@ XS(_wrap_layerObj_minscaledenom_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_minscaledenom_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_minscaledenom_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -21187,7 +22825,7 @@ XS(_wrap_layerObj_maxscaledenom_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_maxscaledenom_set(self,maxscaledenom);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_maxscaledenom_set" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -21222,7 +22860,7 @@ XS(_wrap_layerObj_maxscaledenom_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_maxscaledenom_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_maxscaledenom_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -21252,7 +22890,7 @@ XS(_wrap_layerObj_minfeaturesize_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_minfeaturesize_set(self,minfeaturesize);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_minfeaturesize_set" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -21287,7 +22925,7 @@ XS(_wrap_layerObj_minfeaturesize_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_minfeaturesize_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_minfeaturesize_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -21317,7 +22955,7 @@ XS(_wrap_layerObj_labelminscaledenom_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_labelminscaledenom_set(self,labelminscaledenom);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_labelminscaledenom_set" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -21352,7 +22990,7 @@ XS(_wrap_layerObj_labelminscaledenom_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_labelminscaledenom_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_labelminscaledenom_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -21382,7 +23020,7 @@ XS(_wrap_layerObj_labelmaxscaledenom_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_labelmaxscaledenom_set(self,labelmaxscaledenom);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_labelmaxscaledenom_set" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -21417,7 +23055,7 @@ XS(_wrap_layerObj_labelmaxscaledenom_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_labelmaxscaledenom_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_labelmaxscaledenom_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -21447,7 +23085,7 @@ XS(_wrap_layerObj_mingeowidth_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_mingeowidth_set(self,mingeowidth);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_mingeowidth_set" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -21482,7 +23120,7 @@ XS(_wrap_layerObj_mingeowidth_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_mingeowidth_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_mingeowidth_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -21512,7 +23150,7 @@ XS(_wrap_layerObj_maxgeowidth_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_maxgeowidth_set(self,maxgeowidth);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_maxgeowidth_set" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -21547,7 +23185,7 @@ XS(_wrap_layerObj_maxgeowidth_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_maxgeowidth_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_maxgeowidth_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -21577,7 +23215,7 @@ XS(_wrap_layerObj_sizeunits_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_sizeunits_set(self,sizeunits);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_sizeunits_set" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -21612,7 +23250,7 @@ XS(_wrap_layerObj_sizeunits_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_sizeunits_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_sizeunits_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -21642,7 +23280,7 @@ XS(_wrap_layerObj_maxfeatures_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_maxfeatures_set(self,maxfeatures);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_maxfeatures_set" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -21677,7 +23315,7 @@ XS(_wrap_layerObj_maxfeatures_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_maxfeatures_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_maxfeatures_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -21707,7 +23345,7 @@ XS(_wrap_layerObj_startindex_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_startindex_set(self,startindex);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_startindex_set" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -21742,7 +23380,7 @@ XS(_wrap_layerObj_startindex_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_startindex_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_startindex_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -21772,7 +23410,7 @@ XS(_wrap_layerObj_offsite_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_offsite_set(self,offsite);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_offsite_set" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -21807,7 +23445,7 @@ XS(_wrap_layerObj_offsite_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_offsite_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_offsite_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -21837,7 +23475,7 @@ XS(_wrap_layerObj_transform_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_transform_set(self,transform);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_transform_set" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -21872,7 +23510,7 @@ XS(_wrap_layerObj_transform_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_transform_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_transform_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -21902,7 +23540,7 @@ XS(_wrap_layerObj_labelcache_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_labelcache_set(self,labelcache);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_labelcache_set" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -21937,7 +23575,7 @@ XS(_wrap_layerObj_labelcache_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_labelcache_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_labelcache_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -21967,7 +23605,7 @@ XS(_wrap_layerObj_postlabelcache_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_postlabelcache_set(self,postlabelcache);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_postlabelcache_set" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -22002,7 +23640,7 @@ XS(_wrap_layerObj_postlabelcache_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_postlabelcache_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_postlabelcache_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -22033,7 +23671,7 @@ XS(_wrap_layerObj_labelitem_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_labelitem_set(self,labelitem);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_labelitem_set" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -22076,7 +23714,7 @@ XS(_wrap_layerObj_labelitem_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_labelitem_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_labelitem_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -22107,7 +23745,7 @@ XS(_wrap_layerObj_tileitem_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_tileitem_set(self,tileitem);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_tileitem_set" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -22150,7 +23788,7 @@ XS(_wrap_layerObj_tileitem_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_tileitem_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_tileitem_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -22181,7 +23819,7 @@ XS(_wrap_layerObj_tileindex_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_tileindex_set(self,tileindex);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_tileindex_set" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -22224,7 +23862,7 @@ XS(_wrap_layerObj_tileindex_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_tileindex_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_tileindex_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -22254,7 +23892,7 @@ XS(_wrap_layerObj_units_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_units_set(self,units);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_units_set" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -22289,7 +23927,7 @@ XS(_wrap_layerObj_units_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_units_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_units_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -22320,7 +23958,7 @@ XS(_wrap_layerObj_connection_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_connection_set(self,connection);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_connection_set" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -22363,7 +24001,7 @@ XS(_wrap_layerObj_connection_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_connection_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_connection_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -22394,7 +24032,7 @@ XS(_wrap_layerObj_plugin_library_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_plugin_library_set(self,plugin_library);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_plugin_library_set" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -22437,7 +24075,7 @@ XS(_wrap_layerObj_plugin_library_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_plugin_library_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_plugin_library_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -22468,7 +24106,7 @@ XS(_wrap_layerObj_plugin_library_original_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_plugin_library_original_set(self,plugin_library_original);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_plugin_library_original_set" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -22511,7 +24149,7 @@ XS(_wrap_layerObj_plugin_library_original_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_plugin_library_original_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_plugin_library_original_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -22541,7 +24179,7 @@ XS(_wrap_layerObj_connectiontype_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_connectiontype_set(self,connectiontype);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_connectiontype_set" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -22576,7 +24214,7 @@ XS(_wrap_layerObj_connectiontype_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_connectiontype_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_connectiontype_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -22604,7 +24242,7 @@ XS(_wrap_layerObj_numitems_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_numitems_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_numitems_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -22635,7 +24273,7 @@ XS(_wrap_layerObj_bandsitem_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_bandsitem_set(self,bandsitem);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_bandsitem_set" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -22678,7 +24316,7 @@ XS(_wrap_layerObj_bandsitem_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_bandsitem_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_bandsitem_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -22709,7 +24347,7 @@ XS(_wrap_layerObj_filteritem_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_filteritem_set(self,filteritem);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_filteritem_set" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -22752,7 +24390,7 @@ XS(_wrap_layerObj_filteritem_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_filteritem_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_filteritem_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -22783,7 +24421,7 @@ XS(_wrap_layerObj_styleitem_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_styleitem_set(self,styleitem);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_styleitem_set" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -22826,7 +24464,7 @@ XS(_wrap_layerObj_styleitem_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_styleitem_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_styleitem_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -22857,7 +24495,7 @@ XS(_wrap_layerObj_requires_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_requires_set(self,requires);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_requires_set" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -22900,7 +24538,7 @@ XS(_wrap_layerObj_requires_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_requires_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_requires_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -22931,7 +24569,7 @@ XS(_wrap_layerObj_labelrequires_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_labelrequires_set(self,labelrequires);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_labelrequires_set" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -22974,7 +24612,7 @@ XS(_wrap_layerObj_labelrequires_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_labelrequires_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_labelrequires_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -23002,7 +24640,7 @@ XS(_wrap_layerObj_metadata_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_metadata_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_metadata_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -23030,7 +24668,7 @@ XS(_wrap_layerObj_validation_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_validation_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_validation_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -23058,7 +24696,7 @@ XS(_wrap_layerObj_bindvals_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_bindvals_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_bindvals_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -23086,7 +24724,7 @@ XS(_wrap_layerObj_cluster_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_cluster_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_cluster_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -23116,7 +24754,7 @@ XS(_wrap_layerObj_opacity_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_opacity_set(self,opacity);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_opacity_set" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -23151,7 +24789,7 @@ XS(_wrap_layerObj_opacity_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_opacity_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_opacity_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -23181,7 +24819,7 @@ XS(_wrap_layerObj_dump_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_dump_set(self,dump);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_dump_set" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -23216,7 +24854,7 @@ XS(_wrap_layerObj_dump_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_dump_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_dump_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -23246,7 +24884,7 @@ XS(_wrap_layerObj_debug_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_debug_set(self,debug);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_debug_set" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -23281,7 +24919,7 @@ XS(_wrap_layerObj_debug_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_debug_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_debug_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -23309,7 +24947,7 @@ XS(_wrap_layerObj_extent_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_extent_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_extent_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -23337,7 +24975,7 @@ XS(_wrap_layerObj_numprocessing_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_numprocessing_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_numprocessing_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -23365,7 +25003,7 @@ XS(_wrap_layerObj_numjoins_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_numjoins_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_numjoins_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -23396,7 +25034,7 @@ XS(_wrap_layerObj_classgroup_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_classgroup_set(self,classgroup);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_classgroup_set" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -23439,7 +25077,7 @@ XS(_wrap_layerObj_classgroup_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_classgroup_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_classgroup_get" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -23455,6 +25093,80 @@ XS(_wrap_layerObj_classgroup_get) {
 }
 
 
+XS(_wrap_layerObj_mask_set) {
+  {
+    layerObj *arg1 = (layerObj *) 0 ;
+    char *arg2 = (char *) 0 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int res2 ;
+    char *buf2 = 0 ;
+    int alloc2 = 0 ;
+    int argvi = 0;
+    dXSARGS;
+    
+    if ((items < 2) || (items > 2)) {
+      SWIG_croak("Usage: layerObj_mask_set(self,mask);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_mask_set" "', argument " "1"" of type '" "layerObj *""'"); 
+    }
+    arg1 = (layerObj *)(argp1);
+    res2 = SWIG_AsCharPtrAndSize(ST(1), &buf2, NULL, &alloc2);
+    if (!SWIG_IsOK(res2)) {
+      SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "layerObj_mask_set" "', argument " "2"" of type '" "char *""'");
+    }
+    arg2 = (char *)(buf2);
+    {
+      if (arg1->mask) free((char*)arg1->mask);
+      if (arg2) {
+        arg1->mask = (char *) malloc(strlen(arg2)+1);
+        strcpy((char*)arg1->mask,arg2);
+      } else {
+        arg1->mask = 0;
+      }
+    }
+    ST(argvi) = sv_newmortal();
+    
+    if (alloc2 == SWIG_NEWOBJ) free((char*)buf2);
+    XSRETURN(argvi);
+  fail:
+    
+    if (alloc2 == SWIG_NEWOBJ) free((char*)buf2);
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_layerObj_mask_get) {
+  {
+    layerObj *arg1 = (layerObj *) 0 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int argvi = 0;
+    char *result = 0 ;
+    dXSARGS;
+    
+    if ((items < 1) || (items > 1)) {
+      SWIG_croak("Usage: layerObj_mask_get(self);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_mask_get" "', argument " "1"" of type '" "layerObj *""'"); 
+    }
+    arg1 = (layerObj *)(argp1);
+    result = (char *) ((arg1)->mask);
+    ST(argvi) = SWIG_FromCharPtr((const char *)result); argvi++ ;
+    
+    XSRETURN(argvi);
+  fail:
+    
+    SWIG_croak_null();
+  }
+}
+
+
 XS(_wrap_new_layerObj) {
   {
     mapObj *arg1 = (mapObj *) NULL ;
@@ -23468,14 +25180,14 @@ XS(_wrap_new_layerObj) {
       SWIG_croak("Usage: new_layerObj(map);");
     }
     if (items > 0) {
-      res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+      res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
       if (!SWIG_IsOK(res1)) {
         SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "new_layerObj" "', argument " "1"" of type '" "mapObj *""'"); 
       }
       arg1 = (mapObj *)(argp1);
     }
     result = (layerObj *)new_layerObj(arg1);
-    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_layer_obj, SWIG_OWNER | SWIG_SHADOW); argvi++ ;
+    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_layerObj, SWIG_OWNER | SWIG_SHADOW); argvi++ ;
     
     XSRETURN(argvi);
   fail:
@@ -23496,7 +25208,7 @@ XS(_wrap_delete_layerObj) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: delete_layerObj(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, SWIG_POINTER_DISOWN |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, SWIG_POINTER_DISOWN |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_layerObj" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -23524,13 +25236,13 @@ XS(_wrap_layerObj_clone) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_clone(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_clone" "', argument " "1"" of type '" "layerObj *""'"); 
     }
     arg1 = (layerObj *)(argp1);
     result = (layerObj *)layerObj_clone(arg1);
-    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_layer_obj, SWIG_OWNER | SWIG_SHADOW); argvi++ ;
+    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_layerObj, SWIG_OWNER | SWIG_SHADOW); argvi++ ;
     
     XSRETURN(argvi);
   fail:
@@ -23556,7 +25268,7 @@ XS(_wrap_layerObj_updateFromString) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_updateFromString(self,snippet);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_updateFromString" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -23597,12 +25309,12 @@ XS(_wrap_layerObj_insertClass) {
     if ((items < 2) || (items > 3)) {
       SWIG_croak("Usage: layerObj_insertClass(self,classobj,index);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_insertClass" "', argument " "1"" of type '" "layerObj *""'"); 
     }
     arg1 = (layerObj *)(argp1);
-    res2 = SWIG_ConvertPtr(ST(1), &argp2,SWIGTYPE_p_class_obj, 0 |  0 );
+    res2 = SWIG_ConvertPtr(ST(1), &argp2,SWIGTYPE_p_classObj, 0 |  0 );
     if (!SWIG_IsOK(res2)) {
       SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "layerObj_insertClass" "', argument " "2"" of type '" "classObj *""'"); 
     }
@@ -23644,7 +25356,7 @@ XS(_wrap_layerObj_removeClass) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_removeClass(self,index);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_removeClass" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -23655,7 +25367,7 @@ XS(_wrap_layerObj_removeClass) {
     } 
     arg2 = (int)(val2);
     result = (classObj *)layerObj_removeClass(arg1,arg2);
-    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_class_obj, SWIG_OWNER | SWIG_SHADOW); argvi++ ;
+    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_classObj, SWIG_OWNER | SWIG_SHADOW); argvi++ ;
     
     
     XSRETURN(argvi);
@@ -23679,7 +25391,7 @@ XS(_wrap_layerObj_open) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_open(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_open" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -23710,7 +25422,7 @@ XS(_wrap_layerObj_whichShapes) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_whichShapes(self,rect);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_whichShapes" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -23749,7 +25461,7 @@ XS(_wrap_layerObj_nextShape) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_nextShape(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_nextShape" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -23776,7 +25488,7 @@ XS(_wrap_layerObj_close) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_close(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_close" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -23807,7 +25519,7 @@ XS(_wrap_layerObj_getShape) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_getShape(self,record);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_getShape" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -23842,7 +25554,7 @@ XS(_wrap_layerObj_getNumResults) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_getNumResults(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_getNumResults" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -23870,7 +25582,7 @@ XS(_wrap_layerObj_getResultsBounds) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_getResultsBounds(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_getResultsBounds" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -23901,7 +25613,7 @@ XS(_wrap_layerObj_getResult) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_getResult(self,i);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_getResult" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -23939,7 +25651,7 @@ XS(_wrap_layerObj_getClass) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_getClass(self,i);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_getClass" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -23950,7 +25662,7 @@ XS(_wrap_layerObj_getClass) {
     } 
     arg2 = (int)(val2);
     result = (classObj *)layerObj_getClass(arg1,arg2);
-    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_class_obj, SWIG_OWNER | SWIG_SHADOW); argvi++ ;
+    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_classObj, SWIG_OWNER | SWIG_SHADOW); argvi++ ;
     
     
     XSRETURN(argvi);
@@ -23977,7 +25689,7 @@ XS(_wrap_layerObj_getItem) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_getItem(self,i);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_getItem" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -24000,6 +25712,54 @@ XS(_wrap_layerObj_getItem) {
 }
 
 
+XS(_wrap_layerObj_setItems) {
+  {
+    layerObj *arg1 = (layerObj *) 0 ;
+    char **arg2 = (char **) 0 ;
+    int arg3 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    void *argp2 = 0 ;
+    int res2 = 0 ;
+    int val3 ;
+    int ecode3 = 0 ;
+    int argvi = 0;
+    int result;
+    dXSARGS;
+    
+    if ((items < 3) || (items > 3)) {
+      SWIG_croak("Usage: layerObj_setItems(self,items,numitems);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_setItems" "', argument " "1"" of type '" "layerObj *""'"); 
+    }
+    arg1 = (layerObj *)(argp1);
+    res2 = SWIG_ConvertPtr(ST(1), &argp2,SWIGTYPE_p_p_char, 0 |  0 );
+    if (!SWIG_IsOK(res2)) {
+      SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "layerObj_setItems" "', argument " "2"" of type '" "char **""'"); 
+    }
+    arg2 = (char **)(argp2);
+    ecode3 = SWIG_AsVal_int SWIG_PERL_CALL_ARGS_2(ST(2), &val3);
+    if (!SWIG_IsOK(ecode3)) {
+      SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "layerObj_setItems" "', argument " "3"" of type '" "int""'");
+    } 
+    arg3 = (int)(val3);
+    result = (int)layerObj_setItems(arg1,arg2,arg3);
+    ST(argvi) = SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(result)); argvi++ ;
+    
+    
+    
+    XSRETURN(argvi);
+  fail:
+    
+    
+    
+    SWIG_croak_null();
+  }
+}
+
+
 XS(_wrap_layerObj_draw) {
   {
     layerObj *arg1 = (layerObj *) 0 ;
@@ -24018,12 +25778,12 @@ XS(_wrap_layerObj_draw) {
     if ((items < 3) || (items > 3)) {
       SWIG_croak("Usage: layerObj_draw(self,map,image);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_draw" "', argument " "1"" of type '" "layerObj *""'"); 
     }
     arg1 = (layerObj *)(argp1);
-    res2 = SWIG_ConvertPtr(ST(1), &argp2,SWIGTYPE_p_map_obj, 0 |  0 );
+    res2 = SWIG_ConvertPtr(ST(1), &argp2,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res2)) {
       SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "layerObj_draw" "', argument " "2"" of type '" "mapObj *""'"); 
     }
@@ -24066,12 +25826,12 @@ XS(_wrap_layerObj_drawQuery) {
     if ((items < 3) || (items > 3)) {
       SWIG_croak("Usage: layerObj_drawQuery(self,map,image);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_drawQuery" "', argument " "1"" of type '" "layerObj *""'"); 
     }
     arg1 = (layerObj *)(argp1);
-    res2 = SWIG_ConvertPtr(ST(1), &argp2,SWIGTYPE_p_map_obj, 0 |  0 );
+    res2 = SWIG_ConvertPtr(ST(1), &argp2,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res2)) {
       SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "layerObj_drawQuery" "', argument " "2"" of type '" "mapObj *""'"); 
     }
@@ -24115,12 +25875,12 @@ XS(_wrap_layerObj_queryByFilter) {
     if ((items < 3) || (items > 3)) {
       SWIG_croak("Usage: layerObj_queryByFilter(self,map,string);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_queryByFilter" "', argument " "1"" of type '" "layerObj *""'"); 
     }
     arg1 = (layerObj *)(argp1);
-    res2 = SWIG_ConvertPtr(ST(1), &argp2,SWIGTYPE_p_map_obj, 0 |  0 );
+    res2 = SWIG_ConvertPtr(ST(1), &argp2,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res2)) {
       SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "layerObj_queryByFilter" "', argument " "2"" of type '" "mapObj *""'"); 
     }
@@ -24171,12 +25931,12 @@ XS(_wrap_layerObj_queryByAttributes) {
     if ((items < 5) || (items > 5)) {
       SWIG_croak("Usage: layerObj_queryByAttributes(self,map,qitem,qstring,mode);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_queryByAttributes" "', argument " "1"" of type '" "layerObj *""'"); 
     }
     arg1 = (layerObj *)(argp1);
-    res2 = SWIG_ConvertPtr(ST(1), &argp2,SWIGTYPE_p_map_obj, 0 |  0 );
+    res2 = SWIG_ConvertPtr(ST(1), &argp2,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res2)) {
       SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "layerObj_queryByAttributes" "', argument " "2"" of type '" "mapObj *""'"); 
     }
@@ -24239,12 +25999,12 @@ XS(_wrap_layerObj_queryByPoint) {
     if ((items < 5) || (items > 5)) {
       SWIG_croak("Usage: layerObj_queryByPoint(self,map,point,mode,buffer);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_queryByPoint" "', argument " "1"" of type '" "layerObj *""'"); 
     }
     arg1 = (layerObj *)(argp1);
-    res2 = SWIG_ConvertPtr(ST(1), &argp2,SWIGTYPE_p_map_obj, 0 |  0 );
+    res2 = SWIG_ConvertPtr(ST(1), &argp2,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res2)) {
       SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "layerObj_queryByPoint" "', argument " "2"" of type '" "mapObj *""'"); 
     }
@@ -24301,12 +26061,12 @@ XS(_wrap_layerObj_queryByRect) {
     if ((items < 3) || (items > 3)) {
       SWIG_croak("Usage: layerObj_queryByRect(self,map,rect);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_queryByRect" "', argument " "1"" of type '" "layerObj *""'"); 
     }
     arg1 = (layerObj *)(argp1);
-    res2 = SWIG_ConvertPtr(ST(1), &argp2,SWIGTYPE_p_map_obj, 0 |  0 );
+    res2 = SWIG_ConvertPtr(ST(1), &argp2,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res2)) {
       SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "layerObj_queryByRect" "', argument " "2"" of type '" "mapObj *""'"); 
     }
@@ -24353,12 +26113,12 @@ XS(_wrap_layerObj_queryByFeatures) {
     if ((items < 3) || (items > 3)) {
       SWIG_croak("Usage: layerObj_queryByFeatures(self,map,slayer);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_queryByFeatures" "', argument " "1"" of type '" "layerObj *""'"); 
     }
     arg1 = (layerObj *)(argp1);
-    res2 = SWIG_ConvertPtr(ST(1), &argp2,SWIGTYPE_p_map_obj, 0 |  0 );
+    res2 = SWIG_ConvertPtr(ST(1), &argp2,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res2)) {
       SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "layerObj_queryByFeatures" "', argument " "2"" of type '" "mapObj *""'"); 
     }
@@ -24401,12 +26161,12 @@ XS(_wrap_layerObj_queryByShape) {
     if ((items < 3) || (items > 3)) {
       SWIG_croak("Usage: layerObj_queryByShape(self,map,shape);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_queryByShape" "', argument " "1"" of type '" "layerObj *""'"); 
     }
     arg1 = (layerObj *)(argp1);
-    res2 = SWIG_ConvertPtr(ST(1), &argp2,SWIGTYPE_p_map_obj, 0 |  0 );
+    res2 = SWIG_ConvertPtr(ST(1), &argp2,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res2)) {
       SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "layerObj_queryByShape" "', argument " "2"" of type '" "mapObj *""'"); 
     }
@@ -24455,12 +26215,12 @@ XS(_wrap_layerObj_queryByIndex) {
     if ((items < 4) || (items > 5)) {
       SWIG_croak("Usage: layerObj_queryByIndex(self,map,tileindex,shapeindex,bAddToQuery);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_queryByIndex" "', argument " "1"" of type '" "layerObj *""'"); 
     }
     arg1 = (layerObj *)(argp1);
-    res2 = SWIG_ConvertPtr(ST(1), &argp2,SWIGTYPE_p_map_obj, 0 |  0 );
+    res2 = SWIG_ConvertPtr(ST(1), &argp2,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res2)) {
       SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "layerObj_queryByIndex" "', argument " "2"" of type '" "mapObj *""'"); 
     }
@@ -24513,7 +26273,7 @@ XS(_wrap_layerObj_getResults) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_getResults(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_getResults" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -24545,7 +26305,7 @@ XS(_wrap_layerObj_setFilter) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_setFilter(self,filter);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_setFilter" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -24580,7 +26340,7 @@ XS(_wrap_layerObj_getFilterString) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_getFilterString(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_getFilterString" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -24613,7 +26373,7 @@ XS(_wrap_layerObj_setWKTProjection) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_setWKTProjection(self,wkt);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_setWKTProjection" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -24648,7 +26408,7 @@ XS(_wrap_layerObj_getProjection) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_getProjection(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_getProjection" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -24681,7 +26441,7 @@ XS(_wrap_layerObj_setProjection) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_setProjection(self,proj4);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_setProjection" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -24719,7 +26479,7 @@ XS(_wrap_layerObj_addFeature) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_addFeature(self,shape);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_addFeature" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -24754,7 +26514,7 @@ XS(_wrap_layerObj_getNumFeatures) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_getNumFeatures(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_getNumFeatures" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -24782,7 +26542,7 @@ XS(_wrap_layerObj_getExtent) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_getExtent(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_getExtent" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -24822,7 +26582,7 @@ XS(_wrap_layerObj_setExtent) {
     if ((items < 1) || (items > 5)) {
       SWIG_croak("Usage: layerObj_setExtent(self,minx,miny,maxx,maxy);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_setExtent" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -24890,7 +26650,7 @@ XS(_wrap_layerObj_getMetaData) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_getMetaData(self,name);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_getMetaData" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -24933,7 +26693,7 @@ XS(_wrap_layerObj_setMetaData) {
     if ((items < 3) || (items > 3)) {
       SWIG_croak("Usage: layerObj_setMetaData(self,name,value);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_setMetaData" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -24979,7 +26739,7 @@ XS(_wrap_layerObj_removeMetaData) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_removeMetaData(self,name);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_removeMetaData" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -25014,7 +26774,7 @@ XS(_wrap_layerObj_getFirstMetaDataKey) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_getFirstMetaDataKey(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_getFirstMetaDataKey" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -25046,7 +26806,7 @@ XS(_wrap_layerObj_getNextMetaDataKey) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_getNextMetaDataKey(self,lastkey);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_getNextMetaDataKey" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -25097,12 +26857,12 @@ XS(_wrap_layerObj_getWMSFeatureInfoURL) {
     if ((items < 6) || (items > 6)) {
       SWIG_croak("Usage: layerObj_getWMSFeatureInfoURL(self,map,click_x,click_y,feature_count,info_format);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_getWMSFeatureInfoURL" "', argument " "1"" of type '" "layerObj *""'"); 
     }
     arg1 = (layerObj *)(argp1);
-    res2 = SWIG_ConvertPtr(ST(1), &argp2,SWIGTYPE_p_map_obj, 0 |  0 );
+    res2 = SWIG_ConvertPtr(ST(1), &argp2,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res2)) {
       SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "layerObj_getWMSFeatureInfoURL" "', argument " "2"" of type '" "mapObj *""'"); 
     }
@@ -25164,12 +26924,12 @@ XS(_wrap_layerObj_executeWFSGetFeature) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_executeWFSGetFeature(self,layer);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_executeWFSGetFeature" "', argument " "1"" of type '" "layerObj *""'"); 
     }
     arg1 = (layerObj *)(argp1);
-    res2 = SWIG_ConvertPtr(ST(1), &argp2,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res2 = SWIG_ConvertPtr(ST(1), &argp2,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res2)) {
       SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "layerObj_executeWFSGetFeature" "', argument " "2"" of type '" "layerObj *""'"); 
     }
@@ -25208,7 +26968,7 @@ XS(_wrap_layerObj_applySLD) {
     if ((items < 3) || (items > 3)) {
       SWIG_croak("Usage: layerObj_applySLD(self,sld,stylelayer);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_applySLD" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -25258,7 +27018,7 @@ XS(_wrap_layerObj_applySLDURL) {
     if ((items < 3) || (items > 3)) {
       SWIG_croak("Usage: layerObj_applySLDURL(self,sld,stylelayer);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_applySLDURL" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -25300,7 +27060,7 @@ XS(_wrap_layerObj_generateSLD) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_generateSLD(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_generateSLD" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -25329,7 +27089,7 @@ XS(_wrap_layerObj_isVisible) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_isVisible(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_isVisible" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -25360,7 +27120,7 @@ XS(_wrap_layerObj_moveClassUp) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_moveClassUp(self,index);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_moveClassUp" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -25398,7 +27158,7 @@ XS(_wrap_layerObj_moveClassDown) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_moveClassDown(self,index);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_moveClassDown" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -25440,7 +27200,7 @@ XS(_wrap_layerObj_setProcessingKey) {
     if ((items < 3) || (items > 3)) {
       SWIG_croak("Usage: layerObj_setProcessingKey(self,key,value);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_setProcessingKey" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -25485,7 +27245,7 @@ XS(_wrap_layerObj_setProcessing) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_setProcessing(self,directive);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_setProcessing" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -25523,7 +27283,7 @@ XS(_wrap_layerObj_addProcessing) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_addProcessing(self,directive);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_addProcessing" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -25561,7 +27321,7 @@ XS(_wrap_layerObj_getProcessing) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_getProcessing(self,index);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_getProcessing" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -25600,7 +27360,7 @@ XS(_wrap_layerObj_getProcessingKey) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: layerObj_getProcessingKey(self,key);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_getProcessingKey" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -25635,7 +27395,7 @@ XS(_wrap_layerObj_clearProcessing) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: layerObj_clearProcessing(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_clearProcessing" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -25670,7 +27430,7 @@ XS(_wrap_layerObj_setConnectionType) {
     if ((items < 3) || (items > 3)) {
       SWIG_croak("Usage: layerObj_setConnectionType(self,connectiontype,library_str);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_setConnectionType" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -25724,12 +27484,12 @@ XS(_wrap_layerObj_getClassIndex) {
     if ((items < 3) || (items > 5)) {
       SWIG_croak("Usage: layerObj_getClassIndex(self,map,shape,classgroup,numclasses);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_getClassIndex" "', argument " "1"" of type '" "layerObj *""'"); 
     }
     arg1 = (layerObj *)(argp1);
-    res2 = SWIG_ConvertPtr(ST(1), &argp2,SWIGTYPE_p_map_obj, 0 |  0 );
+    res2 = SWIG_ConvertPtr(ST(1), &argp2,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res2)) {
       SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "layerObj_getClassIndex" "', argument " "2"" of type '" "mapObj *""'"); 
     }
@@ -25787,7 +27547,7 @@ XS(_wrap_mapObj_name_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_name_set(self,name);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_name_set" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -25830,7 +27590,7 @@ XS(_wrap_mapObj_name_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_name_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_name_get" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -25860,7 +27620,7 @@ XS(_wrap_mapObj_status_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_status_set(self,status);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_status_set" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -25895,7 +27655,7 @@ XS(_wrap_mapObj_status_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_status_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_status_get" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -25925,7 +27685,7 @@ XS(_wrap_mapObj_height_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_height_set(self,height);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_height_set" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -25960,7 +27720,7 @@ XS(_wrap_mapObj_height_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_height_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_height_get" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -25990,7 +27750,7 @@ XS(_wrap_mapObj_width_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_width_set(self,width);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_width_set" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -26025,7 +27785,7 @@ XS(_wrap_mapObj_width_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_width_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_width_get" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -26055,7 +27815,7 @@ XS(_wrap_mapObj_maxsize_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_maxsize_set(self,maxsize);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_maxsize_set" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -26090,7 +27850,7 @@ XS(_wrap_mapObj_maxsize_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_maxsize_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_maxsize_get" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -26118,7 +27878,7 @@ XS(_wrap_mapObj_refcount_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_refcount_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_refcount_get" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -26146,7 +27906,7 @@ XS(_wrap_mapObj_numlayers_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_numlayers_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_numlayers_get" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -26174,7 +27934,7 @@ XS(_wrap_mapObj_maxlayers_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_maxlayers_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_maxlayers_get" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -26202,7 +27962,7 @@ XS(_wrap_mapObj_symbolset_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_symbolset_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_symbolset_get" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -26230,7 +27990,7 @@ XS(_wrap_mapObj_fontset_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_fontset_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_fontset_get" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -26258,7 +28018,7 @@ XS(_wrap_mapObj_labelcache_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_labelcache_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_labelcache_get" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -26288,7 +28048,7 @@ XS(_wrap_mapObj_transparent_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_transparent_set(self,transparent);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_transparent_set" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -26323,7 +28083,7 @@ XS(_wrap_mapObj_transparent_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_transparent_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_transparent_get" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -26353,7 +28113,7 @@ XS(_wrap_mapObj_interlace_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_interlace_set(self,interlace);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_interlace_set" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -26388,7 +28148,7 @@ XS(_wrap_mapObj_interlace_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_interlace_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_interlace_get" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -26418,7 +28178,7 @@ XS(_wrap_mapObj_imagequality_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_imagequality_set(self,imagequality);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_imagequality_set" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -26453,7 +28213,7 @@ XS(_wrap_mapObj_imagequality_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_imagequality_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_imagequality_get" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -26483,7 +28243,7 @@ XS(_wrap_mapObj_extent_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_extent_set(self,extent);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_extent_set" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -26518,7 +28278,7 @@ XS(_wrap_mapObj_extent_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_extent_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_extent_get" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -26548,7 +28308,7 @@ XS(_wrap_mapObj_cellsize_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_cellsize_set(self,cellsize);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_cellsize_set" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -26583,7 +28343,7 @@ XS(_wrap_mapObj_cellsize_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_cellsize_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_cellsize_get" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -26613,7 +28373,7 @@ XS(_wrap_mapObj_units_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_units_set(self,units);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_units_set" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -26648,7 +28408,7 @@ XS(_wrap_mapObj_units_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_units_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_units_get" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -26678,7 +28438,7 @@ XS(_wrap_mapObj_scaledenom_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_scaledenom_set(self,scaledenom);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_scaledenom_set" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -26713,7 +28473,7 @@ XS(_wrap_mapObj_scaledenom_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_scaledenom_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_scaledenom_get" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -26743,7 +28503,7 @@ XS(_wrap_mapObj_resolution_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_resolution_set(self,resolution);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_resolution_set" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -26778,7 +28538,7 @@ XS(_wrap_mapObj_resolution_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_resolution_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_resolution_get" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -26808,7 +28568,7 @@ XS(_wrap_mapObj_defresolution_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_defresolution_set(self,defresolution);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_defresolution_set" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -26843,7 +28603,7 @@ XS(_wrap_mapObj_defresolution_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_defresolution_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_defresolution_get" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -26874,7 +28634,7 @@ XS(_wrap_mapObj_shapepath_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_shapepath_set(self,shapepath);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_shapepath_set" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -26917,7 +28677,7 @@ XS(_wrap_mapObj_shapepath_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_shapepath_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_shapepath_get" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -26948,7 +28708,7 @@ XS(_wrap_mapObj_mappath_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_mappath_set(self,mappath);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_mappath_set" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -26991,7 +28751,7 @@ XS(_wrap_mapObj_mappath_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_mappath_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_mappath_get" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -27021,7 +28781,7 @@ XS(_wrap_mapObj_imagecolor_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_imagecolor_set(self,imagecolor);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_imagecolor_set" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -27056,7 +28816,7 @@ XS(_wrap_mapObj_imagecolor_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_imagecolor_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_imagecolor_get" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -27084,7 +28844,7 @@ XS(_wrap_mapObj_numoutputformats_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_numoutputformats_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_numoutputformats_get" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -27112,7 +28872,7 @@ XS(_wrap_mapObj_outputformatlist_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_outputformatlist_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_outputformatlist_get" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -27140,7 +28900,7 @@ XS(_wrap_mapObj_outputformat_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_outputformat_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_outputformat_get" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -27168,7 +28928,7 @@ XS(_wrap_mapObj_imagetype_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_imagetype_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_imagetype_get" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -27196,7 +28956,7 @@ XS(_wrap_mapObj_reference_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_reference_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_reference_get" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -27224,7 +28984,7 @@ XS(_wrap_mapObj_scalebar_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_scalebar_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_scalebar_get" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -27252,7 +29012,7 @@ XS(_wrap_mapObj_legend_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_legend_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_legend_get" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -27280,7 +29040,7 @@ XS(_wrap_mapObj_querymap_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_querymap_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_querymap_get" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -27308,7 +29068,7 @@ XS(_wrap_mapObj_web_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_web_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_web_get" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -27338,7 +29098,7 @@ XS(_wrap_mapObj_layerorder_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_layerorder_set(self,layerorder);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_layerorder_set" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -27373,7 +29133,7 @@ XS(_wrap_mapObj_layerorder_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_layerorder_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_layerorder_get" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -27403,7 +29163,7 @@ XS(_wrap_mapObj_debug_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_debug_set(self,debug);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_debug_set" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -27438,7 +29198,7 @@ XS(_wrap_mapObj_debug_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_debug_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_debug_get" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -27469,7 +29229,7 @@ XS(_wrap_mapObj_datapattern_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_datapattern_set(self,datapattern);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_datapattern_set" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -27512,7 +29272,7 @@ XS(_wrap_mapObj_datapattern_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_datapattern_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_datapattern_get" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -27543,7 +29303,7 @@ XS(_wrap_mapObj_templatepattern_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_templatepattern_set(self,templatepattern);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_templatepattern_set" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -27586,7 +29346,7 @@ XS(_wrap_mapObj_templatepattern_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_templatepattern_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_templatepattern_get" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -27614,7 +29374,7 @@ XS(_wrap_mapObj_configoptions_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_configoptions_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_configoptions_get" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -27651,7 +29411,7 @@ XS(_wrap_new_mapObj) {
       arg1 = (char *)(buf1);
     }
     result = (mapObj *)new_mapObj(arg1);
-    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_map_obj, SWIG_OWNER | SWIG_SHADOW); argvi++ ;
+    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_mapObj, SWIG_OWNER | SWIG_SHADOW); argvi++ ;
     if (alloc1 == SWIG_NEWOBJ) free((char*)buf1);
     XSRETURN(argvi);
   fail:
@@ -27672,7 +29432,7 @@ XS(_wrap_delete_mapObj) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: delete_mapObj(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, SWIG_POINTER_DISOWN |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, SWIG_POINTER_DISOWN |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_mapObj" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -27700,13 +29460,13 @@ XS(_wrap_mapObj_clone) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_clone(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_clone" "', argument " "1"" of type '" "mapObj *""'"); 
     }
     arg1 = (mapObj *)(argp1);
     result = (mapObj *)mapObj_clone(arg1);
-    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_map_obj, SWIG_OWNER | SWIG_SHADOW); argvi++ ;
+    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_mapObj, SWIG_OWNER | SWIG_SHADOW); argvi++ ;
     
     XSRETURN(argvi);
   fail:
@@ -27734,12 +29494,12 @@ XS(_wrap_mapObj_insertLayer) {
     if ((items < 2) || (items > 3)) {
       SWIG_croak("Usage: mapObj_insertLayer(self,layer,index);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_insertLayer" "', argument " "1"" of type '" "mapObj *""'"); 
     }
     arg1 = (mapObj *)(argp1);
-    res2 = SWIG_ConvertPtr(ST(1), &argp2,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res2 = SWIG_ConvertPtr(ST(1), &argp2,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res2)) {
       SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "mapObj_insertLayer" "', argument " "2"" of type '" "layerObj *""'"); 
     }
@@ -27781,7 +29541,7 @@ XS(_wrap_mapObj_removeLayer) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_removeLayer(self,index);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_removeLayer" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -27792,7 +29552,7 @@ XS(_wrap_mapObj_removeLayer) {
     } 
     arg2 = (int)(val2);
     result = (layerObj *)mapObj_removeLayer(arg1,arg2);
-    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_layer_obj, SWIG_OWNER | SWIG_SHADOW); argvi++ ;
+    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_layerObj, SWIG_OWNER | SWIG_SHADOW); argvi++ ;
     
     
     XSRETURN(argvi);
@@ -27828,7 +29588,7 @@ XS(_wrap_mapObj_setExtent) {
     if ((items < 5) || (items > 5)) {
       SWIG_croak("Usage: mapObj_setExtent(self,minx,miny,maxx,maxy);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_setExtent" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -27890,7 +29650,7 @@ XS(_wrap_mapObj_offsetExtent) {
     if ((items < 3) || (items > 3)) {
       SWIG_croak("Usage: mapObj_offsetExtent(self,x,y);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_offsetExtent" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -27941,7 +29701,7 @@ XS(_wrap_mapObj_scaleExtent) {
     if ((items < 4) || (items > 4)) {
       SWIG_croak("Usage: mapObj_scaleExtent(self,zoomfactor,minscaledenom,maxscaledenom);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_scaleExtent" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -27993,7 +29753,7 @@ XS(_wrap_mapObj_setCenter) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_setCenter(self,center);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_setCenter" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -28034,7 +29794,7 @@ XS(_wrap_mapObj_setSize) {
     if ((items < 3) || (items > 3)) {
       SWIG_croak("Usage: mapObj_setSize(self,width,height);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_setSize" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -28079,7 +29839,7 @@ XS(_wrap_mapObj_setRotation) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_setRotation(self,rotation_angle);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_setRotation" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -28117,7 +29877,7 @@ XS(_wrap_mapObj_getLayer) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_getLayer(self,i);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_getLayer" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -28128,7 +29888,7 @@ XS(_wrap_mapObj_getLayer) {
     } 
     arg2 = (int)(val2);
     result = (layerObj *)mapObj_getLayer(arg1,arg2);
-    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_layer_obj, SWIG_OWNER | SWIG_SHADOW); argvi++ ;
+    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_layerObj, SWIG_OWNER | SWIG_SHADOW); argvi++ ;
     
     
     XSRETURN(argvi);
@@ -28156,7 +29916,7 @@ XS(_wrap_mapObj_getLayerByName) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_getLayerByName(self,name);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_getLayerByName" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -28167,7 +29927,7 @@ XS(_wrap_mapObj_getLayerByName) {
     }
     arg2 = (char *)(buf2);
     result = (layerObj *)mapObj_getLayerByName(arg1,arg2);
-    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_layer_obj, SWIG_OWNER | SWIG_SHADOW); argvi++ ;
+    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_layerObj, SWIG_OWNER | SWIG_SHADOW); argvi++ ;
     
     if (alloc2 == SWIG_NEWOBJ) free((char*)buf2);
     XSRETURN(argvi);
@@ -28195,7 +29955,7 @@ XS(_wrap_mapObj_getSymbolByName) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_getSymbolByName(self,name);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_getSymbolByName" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -28229,7 +29989,7 @@ XS(_wrap_mapObj_prepareQuery) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_prepareQuery(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_prepareQuery" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -28257,7 +30017,7 @@ XS(_wrap_mapObj_prepareImage) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_prepareImage(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_prepareImage" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -28288,7 +30048,7 @@ XS(_wrap_mapObj_setImageType) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_setImageType(self,imagetype);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_setImageType" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -28326,7 +30086,7 @@ XS(_wrap_mapObj_selectOutputFormat) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_selectOutputFormat(self,imagetype);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_selectOutputFormat" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -28363,7 +30123,7 @@ XS(_wrap_mapObj_setOutputFormat) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_setOutputFormat(self,format);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_setOutputFormat" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -28398,7 +30158,7 @@ XS(_wrap_mapObj_draw) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_draw(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_draw" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -28426,7 +30186,7 @@ XS(_wrap_mapObj_drawQuery) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_drawQuery(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_drawQuery" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -28454,7 +30214,7 @@ XS(_wrap_mapObj_drawLegend) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_drawLegend(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_drawLegend" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -28482,7 +30242,7 @@ XS(_wrap_mapObj_drawScalebar) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_drawScalebar(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_drawScalebar" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -28510,7 +30270,7 @@ XS(_wrap_mapObj_drawReferenceMap) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_drawReferenceMap(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_drawReferenceMap" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -28541,7 +30301,7 @@ XS(_wrap_mapObj_embedScalebar) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_embedScalebar(self,image);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_embedScalebar" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -28579,7 +30339,7 @@ XS(_wrap_mapObj_embedLegend) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_embedLegend(self,image);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_embedLegend" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -28617,7 +30377,7 @@ XS(_wrap_mapObj_drawLabelCache) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_drawLabelCache(self,image);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_drawLabelCache" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -28655,7 +30415,7 @@ XS(_wrap_mapObj_getLabel) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_getLabel(self,i);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_getLabel" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -28690,7 +30450,7 @@ XS(_wrap_mapObj_nextLabel) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_nextLabel(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_nextLabel" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -28722,7 +30482,7 @@ XS(_wrap_mapObj_queryByFilter) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_queryByFilter(self,string);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_queryByFilter" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -28766,7 +30526,7 @@ XS(_wrap_mapObj_queryByPoint) {
     if ((items < 4) || (items > 4)) {
       SWIG_croak("Usage: mapObj_queryByPoint(self,point,mode,buffer);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_queryByPoint" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -28818,7 +30578,7 @@ XS(_wrap_mapObj_queryByRect) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_queryByRect(self,rect);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_queryByRect" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -28860,7 +30620,7 @@ XS(_wrap_mapObj_queryByFeatures) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_queryByFeatures(self,slayer);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_queryByFeatures" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -28898,7 +30658,7 @@ XS(_wrap_mapObj_queryByShape) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_queryByShape(self,shape);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_queryByShape" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -28937,7 +30697,7 @@ XS(_wrap_mapObj_setWKTProjection) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_setWKTProjection(self,wkt);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_setWKTProjection" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -28972,7 +30732,7 @@ XS(_wrap_mapObj_getProjection) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_getProjection(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_getProjection" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -29005,7 +30765,7 @@ XS(_wrap_mapObj_setProjection) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_setProjection(self,proj4);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_setProjection" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -29044,7 +30804,7 @@ XS(_wrap_mapObj_save) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_save(self,filename);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_save" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -29086,7 +30846,7 @@ XS(_wrap_mapObj_saveQuery) {
     if ((items < 2) || (items > 3)) {
       SWIG_croak("Usage: mapObj_saveQuery(self,filename,results);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_saveQuery" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -29134,7 +30894,7 @@ XS(_wrap_mapObj_loadQuery) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_loadQuery(self,filename);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_loadQuery" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -29171,7 +30931,7 @@ XS(_wrap_mapObj_freeQuery) {
     if ((items < 1) || (items > 2)) {
       SWIG_croak("Usage: mapObj_freeQuery(self,qlayer);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_freeQuery" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -29216,7 +30976,7 @@ XS(_wrap_mapObj_saveQueryAsGML) {
     if ((items < 2) || (items > 3)) {
       SWIG_croak("Usage: mapObj_saveQueryAsGML(self,filename,ns);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_saveQueryAsGML" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -29264,7 +31024,7 @@ XS(_wrap_mapObj_getMetaData) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_getMetaData(self,name);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_getMetaData" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -29307,7 +31067,7 @@ XS(_wrap_mapObj_setMetaData) {
     if ((items < 3) || (items > 3)) {
       SWIG_croak("Usage: mapObj_setMetaData(self,name,value);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_setMetaData" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -29353,7 +31113,7 @@ XS(_wrap_mapObj_removeMetaData) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_removeMetaData(self,name);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_removeMetaData" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -29388,7 +31148,7 @@ XS(_wrap_mapObj_getFirstMetaDataKey) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_getFirstMetaDataKey(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_getFirstMetaDataKey" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -29420,7 +31180,7 @@ XS(_wrap_mapObj_getNextMetaDataKey) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_getNextMetaDataKey(self,lastkey);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_getNextMetaDataKey" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -29459,7 +31219,7 @@ XS(_wrap_mapObj_setSymbolSet) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_setSymbolSet(self,szFileName);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_setSymbolSet" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -29494,7 +31254,7 @@ XS(_wrap_mapObj_getNumSymbols) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_getNumSymbols(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_getNumSymbols" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -29526,7 +31286,7 @@ XS(_wrap_mapObj_setFontSet) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_setFontSet(self,filename);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_setFontSet" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -29565,7 +31325,7 @@ XS(_wrap_mapObj_saveMapContext) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_saveMapContext(self,szFileName);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_saveMapContext" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -29607,7 +31367,7 @@ XS(_wrap_mapObj_loadMapContext) {
     if ((items < 2) || (items > 3)) {
       SWIG_croak("Usage: mapObj_loadMapContext(self,szFileName,useUniqueNames);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_loadMapContext" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -29654,7 +31414,7 @@ XS(_wrap_mapObj_moveLayerUp) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_moveLayerUp(self,layerindex);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_moveLayerUp" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -29692,7 +31452,7 @@ XS(_wrap_mapObj_moveLayerDown) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_moveLayerDown(self,layerindex);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_moveLayerDown" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -29727,7 +31487,7 @@ XS(_wrap_mapObj_getLayersDrawingOrder) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_getLayersDrawingOrder(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_getLayersDrawingOrder" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -29758,7 +31518,7 @@ XS(_wrap_mapObj_setLayersDrawingOrder) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_setLayersDrawingOrder(self,panIndexes);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_setLayersDrawingOrder" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -29800,7 +31560,7 @@ XS(_wrap_mapObj_setConfigOption) {
     if ((items < 3) || (items > 3)) {
       SWIG_croak("Usage: mapObj_setConfigOption(self,key,value);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_setConfigOption" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -29846,7 +31606,7 @@ XS(_wrap_mapObj_getConfigOption) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_getConfigOption(self,key);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_getConfigOption" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -29880,7 +31640,7 @@ XS(_wrap_mapObj_applyConfigOptions) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_applyConfigOptions(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_applyConfigOptions" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -29912,7 +31672,7 @@ XS(_wrap_mapObj_applySLD) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_applySLD(self,sld);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_applySLD" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -29951,7 +31711,7 @@ XS(_wrap_mapObj_applySLDURL) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_applySLDURL(self,sld);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_applySLDURL" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -29986,7 +31746,7 @@ XS(_wrap_mapObj_generateSLD) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: mapObj_generateSLD(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_generateSLD" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -30027,7 +31787,7 @@ XS(_wrap_mapObj_processTemplate) {
     if ((items < 5) || (items > 5)) {
       SWIG_croak("Usage: mapObj_processTemplate(self,bGenerateImages,names,values,numentries);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_processTemplate" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -30093,7 +31853,7 @@ XS(_wrap_mapObj_processLegendTemplate) {
     if ((items < 4) || (items > 4)) {
       SWIG_croak("Usage: mapObj_processLegendTemplate(self,names,values,numentries);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_processLegendTemplate" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -30152,7 +31912,7 @@ XS(_wrap_mapObj_processQueryTemplate) {
     if ((items < 4) || (items > 4)) {
       SWIG_croak("Usage: mapObj_processQueryTemplate(self,names,values,numentries);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_processQueryTemplate" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -30206,7 +31966,7 @@ XS(_wrap_mapObj_getOutputFormatByName) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_getOutputFormatByName(self,name);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_getOutputFormatByName" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -30244,7 +32004,7 @@ XS(_wrap_mapObj_appendOutputFormat) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_appendOutputFormat(self,format);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_appendOutputFormat" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -30283,7 +32043,7 @@ XS(_wrap_mapObj_removeOutputFormat) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_removeOutputFormat(self,name);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_removeOutputFormat" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -30325,7 +32085,7 @@ XS(_wrap_mapObj_loadOWSParameters) {
     if ((items < 2) || (items > 3)) {
       SWIG_croak("Usage: mapObj_loadOWSParameters(self,request,wmtver_string);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_loadOWSParameters" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -30372,7 +32132,7 @@ XS(_wrap_mapObj_OWSDispatch) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: mapObj_OWSDispatch(self,req);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_OWSDispatch" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -30425,7 +32185,7 @@ XS(_wrap_mapObj_zoomPoint) {
     if ((items < 7) || (items > 7)) {
       SWIG_croak("Usage: mapObj_zoomPoint(self,zoomfactor,poPixPos,width,height,poGeorefExt,poMaxGeorefExt);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_zoomPoint" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -30510,7 +32270,7 @@ XS(_wrap_mapObj_zoomRectangle) {
     if ((items < 6) || (items > 6)) {
       SWIG_croak("Usage: mapObj_zoomRectangle(self,poPixRect,width,height,poGeorefExt,poMaxGeorefExt);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_zoomRectangle" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -30591,7 +32351,7 @@ XS(_wrap_mapObj_zoomScale) {
     if ((items < 7) || (items > 7)) {
       SWIG_croak("Usage: mapObj_zoomScale(self,scale,poPixPos,width,height,poGeorefExt,poMaxGeorefExt);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_zoomScale" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -30649,470 +32409,6 @@ XS(_wrap_mapObj_zoomScale) {
 }
 
 
-XS(_wrap_imageObj_width_get) {
-  {
-    imageObj *arg1 = (imageObj *) 0 ;
-    void *argp1 = 0 ;
-    int res1 = 0 ;
-    int argvi = 0;
-    int result;
-    dXSARGS;
-    
-    if ((items < 1) || (items > 1)) {
-      SWIG_croak("Usage: imageObj_width_get(self);");
-    }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_imageObj, 0 |  0 );
-    if (!SWIG_IsOK(res1)) {
-      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "imageObj_width_get" "', argument " "1"" of type '" "imageObj *""'"); 
-    }
-    arg1 = (imageObj *)(argp1);
-    result = (int) ((arg1)->width);
-    ST(argvi) = SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(result)); argvi++ ;
-    
-    XSRETURN(argvi);
-  fail:
-    
-    SWIG_croak_null();
-  }
-}
-
-
-XS(_wrap_imageObj_height_get) {
-  {
-    imageObj *arg1 = (imageObj *) 0 ;
-    void *argp1 = 0 ;
-    int res1 = 0 ;
-    int argvi = 0;
-    int result;
-    dXSARGS;
-    
-    if ((items < 1) || (items > 1)) {
-      SWIG_croak("Usage: imageObj_height_get(self);");
-    }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_imageObj, 0 |  0 );
-    if (!SWIG_IsOK(res1)) {
-      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "imageObj_height_get" "', argument " "1"" of type '" "imageObj *""'"); 
-    }
-    arg1 = (imageObj *)(argp1);
-    result = (int) ((arg1)->height);
-    ST(argvi) = SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(result)); argvi++ ;
-    
-    XSRETURN(argvi);
-  fail:
-    
-    SWIG_croak_null();
-  }
-}
-
-
-XS(_wrap_imageObj_resolution_get) {
-  {
-    imageObj *arg1 = (imageObj *) 0 ;
-    void *argp1 = 0 ;
-    int res1 = 0 ;
-    int argvi = 0;
-    double result;
-    dXSARGS;
-    
-    if ((items < 1) || (items > 1)) {
-      SWIG_croak("Usage: imageObj_resolution_get(self);");
-    }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_imageObj, 0 |  0 );
-    if (!SWIG_IsOK(res1)) {
-      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "imageObj_resolution_get" "', argument " "1"" of type '" "imageObj *""'"); 
-    }
-    arg1 = (imageObj *)(argp1);
-    result = (double) ((arg1)->resolution);
-    ST(argvi) = SWIG_From_double  SWIG_PERL_CALL_ARGS_1((double)(result)); argvi++ ;
-    
-    XSRETURN(argvi);
-  fail:
-    
-    SWIG_croak_null();
-  }
-}
-
-
-XS(_wrap_imageObj_resolutionfactor_get) {
-  {
-    imageObj *arg1 = (imageObj *) 0 ;
-    void *argp1 = 0 ;
-    int res1 = 0 ;
-    int argvi = 0;
-    double result;
-    dXSARGS;
-    
-    if ((items < 1) || (items > 1)) {
-      SWIG_croak("Usage: imageObj_resolutionfactor_get(self);");
-    }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_imageObj, 0 |  0 );
-    if (!SWIG_IsOK(res1)) {
-      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "imageObj_resolutionfactor_get" "', argument " "1"" of type '" "imageObj *""'"); 
-    }
-    arg1 = (imageObj *)(argp1);
-    result = (double) ((arg1)->resolutionfactor);
-    ST(argvi) = SWIG_From_double  SWIG_PERL_CALL_ARGS_1((double)(result)); argvi++ ;
-    
-    XSRETURN(argvi);
-  fail:
-    
-    SWIG_croak_null();
-  }
-}
-
-
-XS(_wrap_imageObj_imagepath_get) {
-  {
-    imageObj *arg1 = (imageObj *) 0 ;
-    void *argp1 = 0 ;
-    int res1 = 0 ;
-    int argvi = 0;
-    char *result = 0 ;
-    dXSARGS;
-    
-    if ((items < 1) || (items > 1)) {
-      SWIG_croak("Usage: imageObj_imagepath_get(self);");
-    }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_imageObj, 0 |  0 );
-    if (!SWIG_IsOK(res1)) {
-      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "imageObj_imagepath_get" "', argument " "1"" of type '" "imageObj *""'"); 
-    }
-    arg1 = (imageObj *)(argp1);
-    result = (char *) ((arg1)->imagepath);
-    ST(argvi) = SWIG_FromCharPtr((const char *)result); argvi++ ;
-    
-    XSRETURN(argvi);
-  fail:
-    
-    SWIG_croak_null();
-  }
-}
-
-
-XS(_wrap_imageObj_imageurl_get) {
-  {
-    imageObj *arg1 = (imageObj *) 0 ;
-    void *argp1 = 0 ;
-    int res1 = 0 ;
-    int argvi = 0;
-    char *result = 0 ;
-    dXSARGS;
-    
-    if ((items < 1) || (items > 1)) {
-      SWIG_croak("Usage: imageObj_imageurl_get(self);");
-    }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_imageObj, 0 |  0 );
-    if (!SWIG_IsOK(res1)) {
-      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "imageObj_imageurl_get" "', argument " "1"" of type '" "imageObj *""'"); 
-    }
-    arg1 = (imageObj *)(argp1);
-    result = (char *) ((arg1)->imageurl);
-    ST(argvi) = SWIG_FromCharPtr((const char *)result); argvi++ ;
-    
-    XSRETURN(argvi);
-  fail:
-    
-    SWIG_croak_null();
-  }
-}
-
-
-XS(_wrap_imageObj_format_get) {
-  {
-    imageObj *arg1 = (imageObj *) 0 ;
-    void *argp1 = 0 ;
-    int res1 = 0 ;
-    int argvi = 0;
-    outputFormatObj *result = 0 ;
-    dXSARGS;
-    
-    if ((items < 1) || (items > 1)) {
-      SWIG_croak("Usage: imageObj_format_get(self);");
-    }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_imageObj, 0 |  0 );
-    if (!SWIG_IsOK(res1)) {
-      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "imageObj_format_get" "', argument " "1"" of type '" "imageObj *""'"); 
-    }
-    arg1 = (imageObj *)(argp1);
-    result = (outputFormatObj *) ((arg1)->format);
-    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_outputFormatObj, 0 | SWIG_SHADOW); argvi++ ;
-    
-    XSRETURN(argvi);
-  fail:
-    
-    SWIG_croak_null();
-  }
-}
-
-
-XS(_wrap_new_imageObj) {
-  {
-    int arg1 ;
-    int arg2 ;
-    outputFormatObj *arg3 = (outputFormatObj *) NULL ;
-    char *arg4 = (char *) NULL ;
-    double arg5 = (double) MS_DEFAULT_RESOLUTION ;
-    double arg6 = (double) MS_DEFAULT_RESOLUTION ;
-    int val1 ;
-    int ecode1 = 0 ;
-    int val2 ;
-    int ecode2 = 0 ;
-    void *argp3 = 0 ;
-    int res3 = 0 ;
-    int res4 ;
-    char *buf4 = 0 ;
-    int alloc4 = 0 ;
-    double val5 ;
-    int ecode5 = 0 ;
-    double val6 ;
-    int ecode6 = 0 ;
-    int argvi = 0;
-    imageObj *result = 0 ;
-    dXSARGS;
-    
-    if ((items < 2) || (items > 6)) {
-      SWIG_croak("Usage: new_imageObj(width,height,input_format,file,resolution,defresolution);");
-    }
-    ecode1 = SWIG_AsVal_int SWIG_PERL_CALL_ARGS_2(ST(0), &val1);
-    if (!SWIG_IsOK(ecode1)) {
-      SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "new_imageObj" "', argument " "1"" of type '" "int""'");
-    } 
-    arg1 = (int)(val1);
-    ecode2 = SWIG_AsVal_int SWIG_PERL_CALL_ARGS_2(ST(1), &val2);
-    if (!SWIG_IsOK(ecode2)) {
-      SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "new_imageObj" "', argument " "2"" of type '" "int""'");
-    } 
-    arg2 = (int)(val2);
-    if (items > 2) {
-      res3 = SWIG_ConvertPtr(ST(2), &argp3,SWIGTYPE_p_outputFormatObj, 0 |  0 );
-      if (!SWIG_IsOK(res3)) {
-        SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "new_imageObj" "', argument " "3"" of type '" "outputFormatObj *""'"); 
-      }
-      arg3 = (outputFormatObj *)(argp3);
-    }
-    if (items > 3) {
-      res4 = SWIG_AsCharPtrAndSize(ST(3), &buf4, NULL, &alloc4);
-      if (!SWIG_IsOK(res4)) {
-        SWIG_exception_fail(SWIG_ArgError(res4), "in method '" "new_imageObj" "', argument " "4"" of type '" "char const *""'");
-      }
-      arg4 = (char *)(buf4);
-    }
-    if (items > 4) {
-      ecode5 = SWIG_AsVal_double SWIG_PERL_CALL_ARGS_2(ST(4), &val5);
-      if (!SWIG_IsOK(ecode5)) {
-        SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "new_imageObj" "', argument " "5"" of type '" "double""'");
-      } 
-      arg5 = (double)(val5);
-    }
-    if (items > 5) {
-      ecode6 = SWIG_AsVal_double SWIG_PERL_CALL_ARGS_2(ST(5), &val6);
-      if (!SWIG_IsOK(ecode6)) {
-        SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "new_imageObj" "', argument " "6"" of type '" "double""'");
-      } 
-      arg6 = (double)(val6);
-    }
-    result = (imageObj *)new_imageObj(arg1,arg2,arg3,(char const *)arg4,arg5,arg6);
-    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_imageObj, SWIG_OWNER | SWIG_SHADOW); argvi++ ;
-    
-    
-    
-    if (alloc4 == SWIG_NEWOBJ) free((char*)buf4);
-    
-    
-    XSRETURN(argvi);
-  fail:
-    
-    
-    
-    if (alloc4 == SWIG_NEWOBJ) free((char*)buf4);
-    
-    
-    SWIG_croak_null();
-  }
-}
-
-
-XS(_wrap_delete_imageObj) {
-  {
-    imageObj *arg1 = (imageObj *) 0 ;
-    void *argp1 = 0 ;
-    int res1 = 0 ;
-    int argvi = 0;
-    dXSARGS;
-    
-    if ((items < 1) || (items > 1)) {
-      SWIG_croak("Usage: delete_imageObj(self);");
-    }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_imageObj, SWIG_POINTER_DISOWN |  0 );
-    if (!SWIG_IsOK(res1)) {
-      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_imageObj" "', argument " "1"" of type '" "imageObj *""'"); 
-    }
-    arg1 = (imageObj *)(argp1);
-    delete_imageObj(arg1);
-    ST(argvi) = sv_newmortal();
-    
-    XSRETURN(argvi);
-  fail:
-    
-    SWIG_croak_null();
-  }
-}
-
-
-XS(_wrap_imageObj_save) {
-  {
-    imageObj *arg1 = (imageObj *) 0 ;
-    char *arg2 = (char *) 0 ;
-    mapObj *arg3 = (mapObj *) NULL ;
-    void *argp1 = 0 ;
-    int res1 = 0 ;
-    int res2 ;
-    char *buf2 = 0 ;
-    int alloc2 = 0 ;
-    void *argp3 = 0 ;
-    int res3 = 0 ;
-    int argvi = 0;
-    dXSARGS;
-    
-    if ((items < 2) || (items > 3)) {
-      SWIG_croak("Usage: imageObj_save(self,filename,map);");
-    }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_imageObj, 0 |  0 );
-    if (!SWIG_IsOK(res1)) {
-      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "imageObj_save" "', argument " "1"" of type '" "imageObj *""'"); 
-    }
-    arg1 = (imageObj *)(argp1);
-    res2 = SWIG_AsCharPtrAndSize(ST(1), &buf2, NULL, &alloc2);
-    if (!SWIG_IsOK(res2)) {
-      SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "imageObj_save" "', argument " "2"" of type '" "char *""'");
-    }
-    arg2 = (char *)(buf2);
-    if (items > 2) {
-      res3 = SWIG_ConvertPtr(ST(2), &argp3,SWIGTYPE_p_map_obj, 0 |  0 );
-      if (!SWIG_IsOK(res3)) {
-        SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "imageObj_save" "', argument " "3"" of type '" "mapObj *""'"); 
-      }
-      arg3 = (mapObj *)(argp3);
-    }
-    imageObj_save(arg1,arg2,arg3);
-    ST(argvi) = sv_newmortal();
-    
-    if (alloc2 == SWIG_NEWOBJ) free((char*)buf2);
-    
-    XSRETURN(argvi);
-  fail:
-    
-    if (alloc2 == SWIG_NEWOBJ) free((char*)buf2);
-    
-    SWIG_croak_null();
-  }
-}
-
-
-XS(_wrap_imageObj_write) {
-  {
-    imageObj *arg1 = (imageObj *) 0 ;
-    FILE *arg2 = (FILE *) NULL ;
-    void *argp1 = 0 ;
-    int res1 = 0 ;
-    int argvi = 0;
-    int result;
-    dXSARGS;
-    
-    if ((items < 1) || (items > 2)) {
-      SWIG_croak("Usage: imageObj_write(self,file);");
-    }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_imageObj, 0 |  0 );
-    if (!SWIG_IsOK(res1)) {
-      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "imageObj_write" "', argument " "1"" of type '" "imageObj *""'"); 
-    }
-    arg1 = (imageObj *)(argp1);
-    if (items > 1) {
-      {
-        arg2 = PerlIO_exportFILE (IoIFP (sv_2io (ST(1))), NULL);
-      }
-    }
-    result = (int)imageObj_write(arg1,arg2);
-    ST(argvi) = SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(result)); argvi++ ;
-    
-    
-    XSRETURN(argvi);
-  fail:
-    
-    
-    SWIG_croak_null();
-  }
-}
-
-
-XS(_wrap_imageObj_getBytes) {
-  {
-    imageObj *arg1 = (imageObj *) 0 ;
-    void *argp1 = 0 ;
-    int res1 = 0 ;
-    int argvi = 0;
-    gdBuffer result;
-    dXSARGS;
-    
-    if ((items < 1) || (items > 1)) {
-      SWIG_croak("Usage: imageObj_getBytes(self);");
-    }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_imageObj, 0 |  0 );
-    if (!SWIG_IsOK(res1)) {
-      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "imageObj_getBytes" "', argument " "1"" of type '" "imageObj *""'"); 
-    }
-    arg1 = (imageObj *)(argp1);
-    result = imageObj_getBytes(arg1);
-    {
-      SV *mysv;
-      mysv = sv_newmortal();
-      if ((&result)->data == NULL)
-      sv_setpv(mysv,"");
-      else
-      sv_setpvn(mysv,(const char*)(&result)->data,(&result)->size);
-      ST(argvi) = newRV(mysv);
-      sv_2mortal(ST(argvi));
-      argvi++;
-      if( (&result)->owns_data )
-      gdFree((&result)->data);
-    }
-    
-    XSRETURN(argvi);
-  fail:
-    
-    SWIG_croak_null();
-  }
-}
-
-
-XS(_wrap_imageObj_getSize) {
-  {
-    imageObj *arg1 = (imageObj *) 0 ;
-    void *argp1 = 0 ;
-    int res1 = 0 ;
-    int argvi = 0;
-    int result;
-    dXSARGS;
-    
-    if ((items < 1) || (items > 1)) {
-      SWIG_croak("Usage: imageObj_getSize(self);");
-    }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_imageObj, 0 |  0 );
-    if (!SWIG_IsOK(res1)) {
-      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "imageObj_getSize" "', argument " "1"" of type '" "imageObj *""'"); 
-    }
-    arg1 = (imageObj *)(argp1);
-    result = (int)imageObj_getSize(arg1);
-    ST(argvi) = SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(result)); argvi++ ;
-    
-    XSRETURN(argvi);
-  fail:
-    
-    SWIG_croak_null();
-  }
-}
-
-
 XS(_wrap_msSaveImage) {
   {
     mapObj *arg1 = (mapObj *) 0 ;
@@ -31132,7 +32428,7 @@ XS(_wrap_msSaveImage) {
     if ((items < 3) || (items > 3)) {
       SWIG_croak("Usage: msSaveImage(map,img,filename);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "msSaveImage" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -31209,16 +32505,26 @@ XS(_wrap_msSetup) {
 
 XS(_wrap_msCleanup) {
   {
+    int arg1 ;
+    int val1 ;
+    int ecode1 = 0 ;
     int argvi = 0;
     dXSARGS;
     
-    if ((items < 0) || (items > 0)) {
-      SWIG_croak("Usage: msCleanup();");
+    if ((items < 1) || (items > 1)) {
+      SWIG_croak("Usage: msCleanup(signal);");
     }
-    msCleanup();
+    ecode1 = SWIG_AsVal_int SWIG_PERL_CALL_ARGS_2(ST(0), &val1);
+    if (!SWIG_IsOK(ecode1)) {
+      SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "msCleanup" "', argument " "1"" of type '" "int""'");
+    } 
+    arg1 = (int)(val1);
+    msCleanup(arg1);
     ST(argvi) = sv_newmortal();
+    
     XSRETURN(argvi);
   fail:
+    
     SWIG_croak_null();
   }
 }
@@ -31252,7 +32558,7 @@ XS(_wrap_msLoadMapFromString) {
     }
     arg2 = (char *)(buf2);
     result = (mapObj *)msLoadMapFromString(arg1,arg2);
-    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_map_obj, 0 | SWIG_SHADOW); argvi++ ;
+    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_mapObj, 0 | SWIG_SHADOW); argvi++ ;
     if (alloc1 == SWIG_NEWOBJ) free((char*)buf1);
     if (alloc2 == SWIG_NEWOBJ) free((char*)buf2);
     XSRETURN(argvi);
@@ -31466,6 +32772,71 @@ XS(_wrap_strokeStyleObj_pattern_get) {
 }
 
 
+XS(_wrap_strokeStyleObj_patternoffset_set) {
+  {
+    strokeStyleObj *arg1 = (strokeStyleObj *) 0 ;
+    double arg2 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    double val2 ;
+    int ecode2 = 0 ;
+    int argvi = 0;
+    dXSARGS;
+    
+    if ((items < 2) || (items > 2)) {
+      SWIG_croak("Usage: strokeStyleObj_patternoffset_set(self,patternoffset);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_strokeStyleObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "strokeStyleObj_patternoffset_set" "', argument " "1"" of type '" "strokeStyleObj *""'"); 
+    }
+    arg1 = (strokeStyleObj *)(argp1);
+    ecode2 = SWIG_AsVal_double SWIG_PERL_CALL_ARGS_2(ST(1), &val2);
+    if (!SWIG_IsOK(ecode2)) {
+      SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "strokeStyleObj_patternoffset_set" "', argument " "2"" of type '" "double""'");
+    } 
+    arg2 = (double)(val2);
+    if (arg1) (arg1)->patternoffset = arg2;
+    ST(argvi) = sv_newmortal();
+    
+    
+    XSRETURN(argvi);
+  fail:
+    
+    
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_strokeStyleObj_patternoffset_get) {
+  {
+    strokeStyleObj *arg1 = (strokeStyleObj *) 0 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int argvi = 0;
+    double result;
+    dXSARGS;
+    
+    if ((items < 1) || (items > 1)) {
+      SWIG_croak("Usage: strokeStyleObj_patternoffset_get(self);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_strokeStyleObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "strokeStyleObj_patternoffset_get" "', argument " "1"" of type '" "strokeStyleObj *""'"); 
+    }
+    arg1 = (strokeStyleObj *)(argp1);
+    result = (double) ((arg1)->patternoffset);
+    ST(argvi) = SWIG_From_double  SWIG_PERL_CALL_ARGS_1((double)(result)); argvi++ ;
+    
+    XSRETURN(argvi);
+  fail:
+    
+    SWIG_croak_null();
+  }
+}
+
+
 XS(_wrap_strokeStyleObj_color_set) {
   {
     strokeStyleObj *arg1 = (strokeStyleObj *) 0 ;
@@ -33096,71 +34467,134 @@ XS(_wrap_delete_tileCacheObj) {
 }
 
 
-XS(_wrap_labelStyleObj_font_set) {
+XS(_wrap_labelStyleObj_fonts_set) {
   {
     labelStyleObj *arg1 = (labelStyleObj *) 0 ;
-    char *arg2 = (char *) 0 ;
+    char **arg2 ;
     void *argp1 = 0 ;
     int res1 = 0 ;
-    int res2 ;
-    char *buf2 = 0 ;
-    int alloc2 = 0 ;
+    void *argp2 = 0 ;
+    int res2 = 0 ;
     int argvi = 0;
     dXSARGS;
     
     if ((items < 2) || (items > 2)) {
-      SWIG_croak("Usage: labelStyleObj_font_set(self,font);");
+      SWIG_croak("Usage: labelStyleObj_fonts_set(self,fonts);");
     }
     res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_labelStyleObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
-      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelStyleObj_font_set" "', argument " "1"" of type '" "labelStyleObj *""'"); 
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelStyleObj_fonts_set" "', argument " "1"" of type '" "labelStyleObj *""'"); 
     }
     arg1 = (labelStyleObj *)(argp1);
-    res2 = SWIG_AsCharPtrAndSize(ST(1), &buf2, NULL, &alloc2);
+    res2 = SWIG_ConvertPtr(ST(1), &argp2,SWIGTYPE_p_p_char, 0 |  0 );
     if (!SWIG_IsOK(res2)) {
-      SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "labelStyleObj_font_set" "', argument " "2"" of type '" "char *""'");
-    }
-    arg2 = (char *)(buf2);
+      SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "labelStyleObj_fonts_set" "', argument " "2"" of type '" "char *[5]""'"); 
+    } 
+    arg2 = (char **)(argp2);
     {
-      if (arg1->font) free((char*)arg1->font);
       if (arg2) {
-        arg1->font = (char *) malloc(strlen(arg2)+1);
-        strcpy((char*)arg1->font,arg2);
+        size_t ii = 0;
+        for (; ii < (size_t)5; ++ii) arg1->fonts[ii] = arg2[ii];
       } else {
-        arg1->font = 0;
+        SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in variable '""fonts""' of type '""char *[5]""'");
       }
     }
     ST(argvi) = sv_newmortal();
     
-    if (alloc2 == SWIG_NEWOBJ) free((char*)buf2);
+    
     XSRETURN(argvi);
   fail:
     
-    if (alloc2 == SWIG_NEWOBJ) free((char*)buf2);
+    
     SWIG_croak_null();
   }
 }
 
 
-XS(_wrap_labelStyleObj_font_get) {
+XS(_wrap_labelStyleObj_fonts_get) {
   {
     labelStyleObj *arg1 = (labelStyleObj *) 0 ;
     void *argp1 = 0 ;
     int res1 = 0 ;
     int argvi = 0;
-    char *result = 0 ;
+    char **result = 0 ;
     dXSARGS;
     
     if ((items < 1) || (items > 1)) {
-      SWIG_croak("Usage: labelStyleObj_font_get(self);");
+      SWIG_croak("Usage: labelStyleObj_fonts_get(self);");
     }
     res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_labelStyleObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
-      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelStyleObj_font_get" "', argument " "1"" of type '" "labelStyleObj *""'"); 
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelStyleObj_fonts_get" "', argument " "1"" of type '" "labelStyleObj *""'"); 
     }
     arg1 = (labelStyleObj *)(argp1);
-    result = (char *) ((arg1)->font);
-    ST(argvi) = SWIG_FromCharPtr((const char *)result); argvi++ ;
+    result = (char **)(char **) ((arg1)->fonts);
+    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_p_char, 0 | 0); argvi++ ;
+    
+    XSRETURN(argvi);
+  fail:
+    
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_labelStyleObj_numfonts_set) {
+  {
+    labelStyleObj *arg1 = (labelStyleObj *) 0 ;
+    int arg2 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int val2 ;
+    int ecode2 = 0 ;
+    int argvi = 0;
+    dXSARGS;
+    
+    if ((items < 2) || (items > 2)) {
+      SWIG_croak("Usage: labelStyleObj_numfonts_set(self,numfonts);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_labelStyleObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelStyleObj_numfonts_set" "', argument " "1"" of type '" "labelStyleObj *""'"); 
+    }
+    arg1 = (labelStyleObj *)(argp1);
+    ecode2 = SWIG_AsVal_int SWIG_PERL_CALL_ARGS_2(ST(1), &val2);
+    if (!SWIG_IsOK(ecode2)) {
+      SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "labelStyleObj_numfonts_set" "', argument " "2"" of type '" "int""'");
+    } 
+    arg2 = (int)(val2);
+    if (arg1) (arg1)->numfonts = arg2;
+    ST(argvi) = sv_newmortal();
+    
+    
+    XSRETURN(argvi);
+  fail:
+    
+    
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_labelStyleObj_numfonts_get) {
+  {
+    labelStyleObj *arg1 = (labelStyleObj *) 0 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int argvi = 0;
+    int result;
+    dXSARGS;
+    
+    if ((items < 1) || (items > 1)) {
+      SWIG_croak("Usage: labelStyleObj_numfonts_get(self);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_labelStyleObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelStyleObj_numfonts_get" "', argument " "1"" of type '" "labelStyleObj *""'"); 
+    }
+    arg1 = (labelStyleObj *)(argp1);
+    result = (int) ((arg1)->numfonts);
+    ST(argvi) = SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(result)); argvi++ ;
     
     XSRETURN(argvi);
   fail:
@@ -33495,6 +34929,71 @@ XS(_wrap_labelStyleObj_outlinecolor_get) {
 }
 
 
+XS(_wrap_labelStyleObj_antialias_set) {
+  {
+    labelStyleObj *arg1 = (labelStyleObj *) 0 ;
+    int arg2 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int val2 ;
+    int ecode2 = 0 ;
+    int argvi = 0;
+    dXSARGS;
+    
+    if ((items < 2) || (items > 2)) {
+      SWIG_croak("Usage: labelStyleObj_antialias_set(self,antialias);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_labelStyleObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelStyleObj_antialias_set" "', argument " "1"" of type '" "labelStyleObj *""'"); 
+    }
+    arg1 = (labelStyleObj *)(argp1);
+    ecode2 = SWIG_AsVal_int SWIG_PERL_CALL_ARGS_2(ST(1), &val2);
+    if (!SWIG_IsOK(ecode2)) {
+      SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "labelStyleObj_antialias_set" "', argument " "2"" of type '" "int""'");
+    } 
+    arg2 = (int)(val2);
+    if (arg1) (arg1)->antialias = arg2;
+    ST(argvi) = sv_newmortal();
+    
+    
+    XSRETURN(argvi);
+  fail:
+    
+    
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_labelStyleObj_antialias_get) {
+  {
+    labelStyleObj *arg1 = (labelStyleObj *) 0 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int argvi = 0;
+    int result;
+    dXSARGS;
+    
+    if ((items < 1) || (items > 1)) {
+      SWIG_croak("Usage: labelStyleObj_antialias_get(self);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_labelStyleObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelStyleObj_antialias_get" "', argument " "1"" of type '" "labelStyleObj *""'"); 
+    }
+    arg1 = (labelStyleObj *)(argp1);
+    result = (int) ((arg1)->antialias);
+    ST(argvi) = SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(result)); argvi++ ;
+    
+    XSRETURN(argvi);
+  fail:
+    
+    SWIG_croak_null();
+  }
+}
+
+
 XS(_wrap_new_labelStyleObj) {
   {
     int argvi = 0;
@@ -34034,12 +35533,12 @@ XS(_wrap_rectObj_draw) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "rectObj_draw" "', argument " "1"" of type '" "rectObj *""'"); 
     }
     arg1 = (rectObj *)(argp1);
-    res2 = SWIG_ConvertPtr(ST(1), &argp2,SWIGTYPE_p_map_obj, 0 |  0 );
+    res2 = SWIG_ConvertPtr(ST(1), &argp2,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res2)) {
       SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "rectObj_draw" "', argument " "2"" of type '" "mapObj *""'"); 
     }
     arg2 = (mapObj *)(argp2);
-    res3 = SWIG_ConvertPtr(ST(2), &argp3,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res3 = SWIG_ConvertPtr(ST(2), &argp3,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res3)) {
       SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "rectObj_draw" "', argument " "3"" of type '" "layerObj *""'"); 
     }
@@ -34469,12 +35968,12 @@ XS(_wrap_pointObj_draw) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "pointObj_draw" "', argument " "1"" of type '" "pointObj *""'"); 
     }
     arg1 = (pointObj *)(argp1);
-    res2 = SWIG_ConvertPtr(ST(1), &argp2,SWIGTYPE_p_map_obj, 0 |  0 );
+    res2 = SWIG_ConvertPtr(ST(1), &argp2,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res2)) {
       SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "pointObj_draw" "', argument " "2"" of type '" "mapObj *""'"); 
     }
     arg2 = (mapObj *)(argp2);
-    res3 = SWIG_ConvertPtr(ST(2), &argp3,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res3 = SWIG_ConvertPtr(ST(2), &argp3,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res3)) {
       SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "pointObj_draw" "', argument " "3"" of type '" "layerObj *""'"); 
     }
@@ -35960,12 +37459,12 @@ XS(_wrap_shapeObj_draw) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "shapeObj_draw" "', argument " "1"" of type '" "shapeObj *""'"); 
     }
     arg1 = (shapeObj *)(argp1);
-    res2 = SWIG_ConvertPtr(ST(1), &argp2,SWIGTYPE_p_map_obj, 0 |  0 );
+    res2 = SWIG_ConvertPtr(ST(1), &argp2,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res2)) {
       SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "shapeObj_draw" "', argument " "2"" of type '" "mapObj *""'"); 
     }
     arg2 = (mapObj *)(argp2);
-    res3 = SWIG_ConvertPtr(ST(2), &argp3,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res3 = SWIG_ConvertPtr(ST(2), &argp3,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res3)) {
       SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "shapeObj_draw" "', argument " "3"" of type '" "layerObj *""'"); 
     }
@@ -37862,11 +39361,8 @@ XS(_wrap_shapefileObj_source_get) {
     arg1 = (shapefileObj *)(argp1);
     result = (char *)(char *) ((arg1)->source);
     {
-      size_t size = MS_PATH_LENGTH;
-      
-      while (size && (result[size - 1] == '\0')) --size;
-      
-      ST(argvi) = SWIG_FromCharPtrAndSize(result, size); argvi++ ;
+      ST(argvi) = newSVpvn(result, strlen(result));
+      argvi++;
     }
     
     XSRETURN(argvi);
@@ -38301,7 +39797,7 @@ XS(_wrap_shapefileObj_getTransformed) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "shapefileObj_getTransformed" "', argument " "1"" of type '" "shapefileObj *""'"); 
     }
     arg1 = (shapefileObj *)(argp1);
-    res2 = SWIG_ConvertPtr(ST(1), &argp2,SWIGTYPE_p_map_obj, 0 |  0 );
+    res2 = SWIG_ConvertPtr(ST(1), &argp2,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res2)) {
       SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "shapefileObj_getTransformed" "', argument " "2"" of type '" "mapObj *""'"); 
     }
@@ -38540,6 +40036,71 @@ XS(_wrap_projectionObj_automatic_get) {
 }
 
 
+XS(_wrap_projectionObj_wellknownprojection_set) {
+  {
+    projectionObj *arg1 = (projectionObj *) 0 ;
+    int arg2 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int val2 ;
+    int ecode2 = 0 ;
+    int argvi = 0;
+    dXSARGS;
+    
+    if ((items < 2) || (items > 2)) {
+      SWIG_croak("Usage: projectionObj_wellknownprojection_set(self,wellknownprojection);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_projectionObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "projectionObj_wellknownprojection_set" "', argument " "1"" of type '" "projectionObj *""'"); 
+    }
+    arg1 = (projectionObj *)(argp1);
+    ecode2 = SWIG_AsVal_int SWIG_PERL_CALL_ARGS_2(ST(1), &val2);
+    if (!SWIG_IsOK(ecode2)) {
+      SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "projectionObj_wellknownprojection_set" "', argument " "2"" of type '" "int""'");
+    } 
+    arg2 = (int)(val2);
+    if (arg1) (arg1)->wellknownprojection = arg2;
+    ST(argvi) = sv_newmortal();
+    
+    
+    XSRETURN(argvi);
+  fail:
+    
+    
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_projectionObj_wellknownprojection_get) {
+  {
+    projectionObj *arg1 = (projectionObj *) 0 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int argvi = 0;
+    int result;
+    dXSARGS;
+    
+    if ((items < 1) || (items > 1)) {
+      SWIG_croak("Usage: projectionObj_wellknownprojection_get(self);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_projectionObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "projectionObj_wellknownprojection_get" "', argument " "1"" of type '" "projectionObj *""'"); 
+    }
+    arg1 = (projectionObj *)(argp1);
+    result = (int) ((arg1)->wellknownprojection);
+    ST(argvi) = SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(result)); argvi++ ;
+    
+    XSRETURN(argvi);
+  fail:
+    
+    SWIG_croak_null();
+  }
+}
+
+
 XS(_wrap_new_projectionObj) {
   {
     char *arg1 = (char *) 0 ;
@@ -38663,71 +40224,6 @@ XS(_wrap_projectionObj_getUnits) {
 }
 
 
-XS(_wrap_colorObj_pen_set) {
-  {
-    colorObj *arg1 = (colorObj *) 0 ;
-    int arg2 ;
-    void *argp1 = 0 ;
-    int res1 = 0 ;
-    int val2 ;
-    int ecode2 = 0 ;
-    int argvi = 0;
-    dXSARGS;
-    
-    if ((items < 2) || (items > 2)) {
-      SWIG_croak("Usage: colorObj_pen_set(self,pen);");
-    }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_colorObj, 0 |  0 );
-    if (!SWIG_IsOK(res1)) {
-      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "colorObj_pen_set" "', argument " "1"" of type '" "colorObj *""'"); 
-    }
-    arg1 = (colorObj *)(argp1);
-    ecode2 = SWIG_AsVal_int SWIG_PERL_CALL_ARGS_2(ST(1), &val2);
-    if (!SWIG_IsOK(ecode2)) {
-      SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "colorObj_pen_set" "', argument " "2"" of type '" "int""'");
-    } 
-    arg2 = (int)(val2);
-    if (arg1) (arg1)->pen = arg2;
-    ST(argvi) = sv_newmortal();
-    
-    
-    XSRETURN(argvi);
-  fail:
-    
-    
-    SWIG_croak_null();
-  }
-}
-
-
-XS(_wrap_colorObj_pen_get) {
-  {
-    colorObj *arg1 = (colorObj *) 0 ;
-    void *argp1 = 0 ;
-    int res1 = 0 ;
-    int argvi = 0;
-    int result;
-    dXSARGS;
-    
-    if ((items < 1) || (items > 1)) {
-      SWIG_croak("Usage: colorObj_pen_get(self);");
-    }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_colorObj, 0 |  0 );
-    if (!SWIG_IsOK(res1)) {
-      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "colorObj_pen_get" "', argument " "1"" of type '" "colorObj *""'"); 
-    }
-    arg1 = (colorObj *)(argp1);
-    result = (int) ((arg1)->pen);
-    ST(argvi) = SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(result)); argvi++ ;
-    
-    XSRETURN(argvi);
-  fail:
-    
-    SWIG_croak_null();
-  }
-}
-
-
 XS(_wrap_colorObj_red_set) {
   {
     colorObj *arg1 = (colorObj *) 0 ;
@@ -39922,6 +41418,136 @@ XS(_wrap_symbolObj_filled_get) {
 }
 
 
+XS(_wrap_symbolObj_anchorpoint_x_set) {
+  {
+    symbolObj *arg1 = (symbolObj *) 0 ;
+    double arg2 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    double val2 ;
+    int ecode2 = 0 ;
+    int argvi = 0;
+    dXSARGS;
+    
+    if ((items < 2) || (items > 2)) {
+      SWIG_croak("Usage: symbolObj_anchorpoint_x_set(self,anchorpoint_x);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_symbolObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "symbolObj_anchorpoint_x_set" "', argument " "1"" of type '" "symbolObj *""'"); 
+    }
+    arg1 = (symbolObj *)(argp1);
+    ecode2 = SWIG_AsVal_double SWIG_PERL_CALL_ARGS_2(ST(1), &val2);
+    if (!SWIG_IsOK(ecode2)) {
+      SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "symbolObj_anchorpoint_x_set" "', argument " "2"" of type '" "double""'");
+    } 
+    arg2 = (double)(val2);
+    if (arg1) (arg1)->anchorpoint_x = arg2;
+    ST(argvi) = sv_newmortal();
+    
+    
+    XSRETURN(argvi);
+  fail:
+    
+    
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_symbolObj_anchorpoint_x_get) {
+  {
+    symbolObj *arg1 = (symbolObj *) 0 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int argvi = 0;
+    double result;
+    dXSARGS;
+    
+    if ((items < 1) || (items > 1)) {
+      SWIG_croak("Usage: symbolObj_anchorpoint_x_get(self);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_symbolObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "symbolObj_anchorpoint_x_get" "', argument " "1"" of type '" "symbolObj *""'"); 
+    }
+    arg1 = (symbolObj *)(argp1);
+    result = (double) ((arg1)->anchorpoint_x);
+    ST(argvi) = SWIG_From_double  SWIG_PERL_CALL_ARGS_1((double)(result)); argvi++ ;
+    
+    XSRETURN(argvi);
+  fail:
+    
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_symbolObj_anchorpoint_y_set) {
+  {
+    symbolObj *arg1 = (symbolObj *) 0 ;
+    double arg2 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    double val2 ;
+    int ecode2 = 0 ;
+    int argvi = 0;
+    dXSARGS;
+    
+    if ((items < 2) || (items > 2)) {
+      SWIG_croak("Usage: symbolObj_anchorpoint_y_set(self,anchorpoint_y);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_symbolObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "symbolObj_anchorpoint_y_set" "', argument " "1"" of type '" "symbolObj *""'"); 
+    }
+    arg1 = (symbolObj *)(argp1);
+    ecode2 = SWIG_AsVal_double SWIG_PERL_CALL_ARGS_2(ST(1), &val2);
+    if (!SWIG_IsOK(ecode2)) {
+      SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "symbolObj_anchorpoint_y_set" "', argument " "2"" of type '" "double""'");
+    } 
+    arg2 = (double)(val2);
+    if (arg1) (arg1)->anchorpoint_y = arg2;
+    ST(argvi) = sv_newmortal();
+    
+    
+    XSRETURN(argvi);
+  fail:
+    
+    
+    SWIG_croak_null();
+  }
+}
+
+
+XS(_wrap_symbolObj_anchorpoint_y_get) {
+  {
+    symbolObj *arg1 = (symbolObj *) 0 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int argvi = 0;
+    double result;
+    dXSARGS;
+    
+    if ((items < 1) || (items > 1)) {
+      SWIG_croak("Usage: symbolObj_anchorpoint_y_get(self);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_symbolObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "symbolObj_anchorpoint_y_get" "', argument " "1"" of type '" "symbolObj *""'"); 
+    }
+    arg1 = (symbolObj *)(argp1);
+    result = (double) ((arg1)->anchorpoint_y);
+    ST(argvi) = SWIG_From_double  SWIG_PERL_CALL_ARGS_1((double)(result)); argvi++ ;
+    
+    XSRETURN(argvi);
+  fail:
+    
+    SWIG_croak_null();
+  }
+}
+
+
 XS(_wrap_symbolObj_imagepath_get) {
   {
     symbolObj *arg1 = (symbolObj *) 0 ;
@@ -40631,7 +42257,7 @@ XS(_wrap_errorObj_code_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: errorObj_code_set(self,code);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_error_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_errorObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "errorObj_code_set" "', argument " "1"" of type '" "errorObj *""'"); 
     }
@@ -40666,7 +42292,7 @@ XS(_wrap_errorObj_code_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: errorObj_code_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_error_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_errorObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "errorObj_code_get" "', argument " "1"" of type '" "errorObj *""'"); 
     }
@@ -40696,7 +42322,7 @@ XS(_wrap_errorObj_routine_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: errorObj_routine_set(self,routine);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_error_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_errorObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "errorObj_routine_set" "', argument " "1"" of type '" "errorObj *""'"); 
     }
@@ -40732,18 +42358,15 @@ XS(_wrap_errorObj_routine_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: errorObj_routine_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_error_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_errorObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "errorObj_routine_get" "', argument " "1"" of type '" "errorObj *""'"); 
     }
     arg1 = (errorObj *)(argp1);
     result = (char *)(char *) ((arg1)->routine);
     {
-      size_t size = 64;
-      
-      while (size && (result[size - 1] == '\0')) --size;
-      
-      ST(argvi) = SWIG_FromCharPtrAndSize(result, size); argvi++ ;
+      ST(argvi) = newSVpvn(result, strlen(result));
+      argvi++;
     }
     
     XSRETURN(argvi);
@@ -40768,7 +42391,7 @@ XS(_wrap_errorObj_message_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: errorObj_message_set(self,message);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_error_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_errorObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "errorObj_message_set" "', argument " "1"" of type '" "errorObj *""'"); 
     }
@@ -40804,18 +42427,15 @@ XS(_wrap_errorObj_message_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: errorObj_message_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_error_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_errorObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "errorObj_message_get" "', argument " "1"" of type '" "errorObj *""'"); 
     }
     arg1 = (errorObj *)(argp1);
     result = (char *)(char *) ((arg1)->message);
     {
-      size_t size = 2048;
-      
-      while (size && (result[size - 1] == '\0')) --size;
-      
-      ST(argvi) = SWIG_FromCharPtrAndSize(result, size); argvi++ ;
+      ST(argvi) = newSVpvn(result, strlen(result));
+      argvi++;
     }
     
     XSRETURN(argvi);
@@ -40840,7 +42460,7 @@ XS(_wrap_errorObj_isreported_set) {
     if ((items < 2) || (items > 2)) {
       SWIG_croak("Usage: errorObj_isreported_set(self,isreported);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_error_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_errorObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "errorObj_isreported_set" "', argument " "1"" of type '" "errorObj *""'"); 
     }
@@ -40875,7 +42495,7 @@ XS(_wrap_errorObj_isreported_get) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: errorObj_isreported_get(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_error_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_errorObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "errorObj_isreported_get" "', argument " "1"" of type '" "errorObj *""'"); 
     }
@@ -40901,7 +42521,7 @@ XS(_wrap_new_errorObj) {
       SWIG_croak("Usage: new_errorObj();");
     }
     result = (errorObj *)new_errorObj();
-    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_error_obj, SWIG_OWNER | SWIG_SHADOW); argvi++ ;
+    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_errorObj, SWIG_OWNER | SWIG_SHADOW); argvi++ ;
     XSRETURN(argvi);
   fail:
     SWIG_croak_null();
@@ -40920,7 +42540,7 @@ XS(_wrap_delete_errorObj) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: delete_errorObj(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_error_obj, SWIG_POINTER_DISOWN |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_errorObj, SWIG_POINTER_DISOWN |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_errorObj" "', argument " "1"" of type '" "errorObj *""'"); 
     }
@@ -40948,13 +42568,13 @@ XS(_wrap_errorObj_next) {
     if ((items < 1) || (items > 1)) {
       SWIG_croak("Usage: errorObj_next(self);");
     }
-    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_error_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_errorObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "errorObj_next" "', argument " "1"" of type '" "errorObj *""'"); 
     }
     arg1 = (errorObj *)(argp1);
     result = (errorObj *)errorObj_next(arg1);
-    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_error_obj, 0 | SWIG_SHADOW); argvi++ ;
+    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_errorObj, 0 | SWIG_SHADOW); argvi++ ;
     
     XSRETURN(argvi);
   fail:
@@ -40974,7 +42594,7 @@ XS(_wrap_msGetErrorObj) {
       SWIG_croak("Usage: msGetErrorObj();");
     }
     result = (errorObj *)msGetErrorObj();
-    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_error_obj, 0 | SWIG_SHADOW); argvi++ ;
+    ST(argvi) = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_errorObj, 0 | SWIG_SHADOW); argvi++ ;
     XSRETURN(argvi);
   fail:
     SWIG_croak_null();
@@ -41822,6 +43442,55 @@ XS(_wrap_OWSRequest_setParameter) {
 }
 
 
+XS(_wrap_OWSRequest_addParameter) {
+  {
+    cgiRequestObj *arg1 = (cgiRequestObj *) 0 ;
+    char *arg2 = (char *) 0 ;
+    char *arg3 = (char *) 0 ;
+    void *argp1 = 0 ;
+    int res1 = 0 ;
+    int res2 ;
+    char *buf2 = 0 ;
+    int alloc2 = 0 ;
+    int res3 ;
+    char *buf3 = 0 ;
+    int alloc3 = 0 ;
+    int argvi = 0;
+    dXSARGS;
+    
+    if ((items < 3) || (items > 3)) {
+      SWIG_croak("Usage: OWSRequest_addParameter(self,name,value);");
+    }
+    res1 = SWIG_ConvertPtr(ST(0), &argp1,SWIGTYPE_p_cgiRequestObj, 0 |  0 );
+    if (!SWIG_IsOK(res1)) {
+      SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "OWSRequest_addParameter" "', argument " "1"" of type '" "cgiRequestObj *""'"); 
+    }
+    arg1 = (cgiRequestObj *)(argp1);
+    res2 = SWIG_AsCharPtrAndSize(ST(1), &buf2, NULL, &alloc2);
+    if (!SWIG_IsOK(res2)) {
+      SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "OWSRequest_addParameter" "', argument " "2"" of type '" "char *""'");
+    }
+    arg2 = (char *)(buf2);
+    res3 = SWIG_AsCharPtrAndSize(ST(2), &buf3, NULL, &alloc3);
+    if (!SWIG_IsOK(res3)) {
+      SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "OWSRequest_addParameter" "', argument " "3"" of type '" "char *""'");
+    }
+    arg3 = (char *)(buf3);
+    cgiRequestObj_addParameter(arg1,arg2,arg3);
+    ST(argvi) = sv_newmortal();
+    
+    if (alloc2 == SWIG_NEWOBJ) free((char*)buf2);
+    if (alloc3 == SWIG_NEWOBJ) free((char*)buf3);
+    XSRETURN(argvi);
+  fail:
+    
+    if (alloc2 == SWIG_NEWOBJ) free((char*)buf2);
+    if (alloc3 == SWIG_NEWOBJ) free((char*)buf3);
+    SWIG_croak_null();
+  }
+}
+
+
 XS(_wrap_OWSRequest_getName) {
   {
     cgiRequestObj *arg1 = (cgiRequestObj *) 0 ;
@@ -42080,7 +43749,7 @@ XS(_wrap_msIO_getStdoutBufferBytes) {
       sv_2mortal(ST(argvi));
       argvi++;
       if( (&result)->owns_data )
-      gdFree((&result)->data);
+      msFree((&result)->data);
     }
     XSRETURN(argvi);
   fail:
@@ -42100,12 +43769,12 @@ static swig_type_info _swigt__p_DBFInfo = {"_p_DBFInfo", "DBFInfo *", 0, 0, (voi
 static swig_type_info _swigt__p_FILE = {"_p_FILE", "FILE *", 0, 0, (void*)0, 0};
 static swig_type_info _swigt__p_cgiRequestObj = {"_p_cgiRequestObj", "cgiRequestObj *", 0, 0, (void*)"mapscript::OWSRequest", 0};
 static swig_type_info _swigt__p_char = {"_p_char", "char *", 0, 0, (void*)0, 0};
-static swig_type_info _swigt__p_class_obj = {"_p_class_obj", "classObj *|struct class_obj *", 0, 0, (void*)"mapscript::classObj", 0};
+static swig_type_info _swigt__p_classObj = {"_p_classObj", "struct classObj *|classObj *", 0, 0, (void*)"mapscript::classObj", 0};
 static swig_type_info _swigt__p_clusterObj = {"_p_clusterObj", "clusterObj *", 0, 0, (void*)"mapscript::clusterObj", 0};
 static swig_type_info _swigt__p_colorObj = {"_p_colorObj", "colorObj *", 0, 0, (void*)"mapscript::colorObj", 0};
 static swig_type_info _swigt__p_debugLevel = {"_p_debugLevel", "enum debugLevel *|debugLevel *", 0, 0, (void*)0, 0};
 static swig_type_info _swigt__p_double = {"_p_double", "double *", 0, 0, (void*)0, 0};
-static swig_type_info _swigt__p_error_obj = {"_p_error_obj", "struct error_obj *|errorObj *", 0, 0, (void*)"mapscript::errorObj", 0};
+static swig_type_info _swigt__p_errorObj = {"_p_errorObj", "struct errorObj *|errorObj *", 0, 0, (void*)"mapscript::errorObj", 0};
 static swig_type_info _swigt__p_fontSetObj = {"_p_fontSetObj", "fontSetObj *", 0, 0, (void*)"mapscript::fontSetObj", 0};
 static swig_type_info _swigt__p_hashTableObj = {"_p_hashTableObj", "hashTableObj *", 0, 0, (void*)"mapscript::hashTableObj", 0};
 static swig_type_info _swigt__p_imageObj = {"_p_imageObj", "imageObj *", 0, 0, (void*)"mapscript::imageObj", 0};
@@ -42115,12 +43784,13 @@ static swig_type_info _swigt__p_intarray = {"_p_intarray", "struct intarray *|in
 static swig_type_info _swigt__p_labelCacheMemberObj = {"_p_labelCacheMemberObj", "labelCacheMemberObj *", 0, 0, (void*)"mapscript::labelCacheMemberObj", 0};
 static swig_type_info _swigt__p_labelCacheObj = {"_p_labelCacheObj", "labelCacheObj *", 0, 0, (void*)"mapscript::labelCacheObj", 0};
 static swig_type_info _swigt__p_labelCacheSlotObj = {"_p_labelCacheSlotObj", "labelCacheSlotObj *", 0, 0, (void*)"mapscript::labelCacheSlotObj", 0};
+static swig_type_info _swigt__p_labelLeaderObj = {"_p_labelLeaderObj", "labelLeaderObj *", 0, 0, (void*)"mapscript::labelLeaderObj", 0};
 static swig_type_info _swigt__p_labelObj = {"_p_labelObj", "labelObj *", 0, 0, (void*)"mapscript::labelObj", 0};
 static swig_type_info _swigt__p_labelStyleObj = {"_p_labelStyleObj", "labelStyleObj *", 0, 0, (void*)"mapscript::labelStyleObj", 0};
-static swig_type_info _swigt__p_layer_obj = {"_p_layer_obj", "struct layer_obj *|layerObj *", 0, 0, (void*)"mapscript::layerObj", 0};
+static swig_type_info _swigt__p_layerObj = {"_p_layerObj", "struct layerObj *|layerObj *", 0, 0, (void*)"mapscript::layerObj", 0};
 static swig_type_info _swigt__p_legendObj = {"_p_legendObj", "legendObj *", 0, 0, (void*)"mapscript::legendObj", 0};
 static swig_type_info _swigt__p_lineObj = {"_p_lineObj", "lineObj *|multipointObj *", 0, 0, (void*)"mapscript::lineObj", 0};
-static swig_type_info _swigt__p_map_obj = {"_p_map_obj", "mapObj *|struct map_obj *", 0, 0, (void*)"mapscript::mapObj", 0};
+static swig_type_info _swigt__p_mapObj = {"_p_mapObj", "struct mapObj *|mapObj *", 0, 0, (void*)"mapscript::mapObj", 0};
 static swig_type_info _swigt__p_markerCacheMemberObj = {"_p_markerCacheMemberObj", "markerCacheMemberObj *", 0, 0, (void*)"mapscript::markerCacheMemberObj", 0};
 static swig_type_info _swigt__p_outputFormatObj = {"_p_outputFormatObj", "outputFormatObj *", 0, 0, (void*)"mapscript::outputFormatObj", 0};
 static swig_type_info _swigt__p_p_char = {"_p_p_char", "char **", 0, 0, (void*)0, 0};
@@ -42151,12 +43821,12 @@ static swig_type_info *swig_type_initial[] = {
   &_swigt__p_FILE,
   &_swigt__p_cgiRequestObj,
   &_swigt__p_char,
-  &_swigt__p_class_obj,
+  &_swigt__p_classObj,
   &_swigt__p_clusterObj,
   &_swigt__p_colorObj,
   &_swigt__p_debugLevel,
   &_swigt__p_double,
-  &_swigt__p_error_obj,
+  &_swigt__p_errorObj,
   &_swigt__p_fontSetObj,
   &_swigt__p_hashTableObj,
   &_swigt__p_imageObj,
@@ -42166,12 +43836,13 @@ static swig_type_info *swig_type_initial[] = {
   &_swigt__p_labelCacheMemberObj,
   &_swigt__p_labelCacheObj,
   &_swigt__p_labelCacheSlotObj,
+  &_swigt__p_labelLeaderObj,
   &_swigt__p_labelObj,
   &_swigt__p_labelStyleObj,
-  &_swigt__p_layer_obj,
+  &_swigt__p_layerObj,
   &_swigt__p_legendObj,
   &_swigt__p_lineObj,
-  &_swigt__p_map_obj,
+  &_swigt__p_mapObj,
   &_swigt__p_markerCacheMemberObj,
   &_swigt__p_outputFormatObj,
   &_swigt__p_p_char,
@@ -42202,12 +43873,12 @@ static swig_cast_info _swigc__p_DBFInfo[] = {  {&_swigt__p_DBFInfo, 0, 0, 0},{0,
 static swig_cast_info _swigc__p_FILE[] = {  {&_swigt__p_FILE, 0, 0, 0},{0, 0, 0, 0}};
 static swig_cast_info _swigc__p_cgiRequestObj[] = {  {&_swigt__p_cgiRequestObj, 0, 0, 0},{0, 0, 0, 0}};
 static swig_cast_info _swigc__p_char[] = {  {&_swigt__p_char, 0, 0, 0},{0, 0, 0, 0}};
-static swig_cast_info _swigc__p_class_obj[] = {  {&_swigt__p_class_obj, 0, 0, 0},{0, 0, 0, 0}};
+static swig_cast_info _swigc__p_classObj[] = {  {&_swigt__p_classObj, 0, 0, 0},{0, 0, 0, 0}};
 static swig_cast_info _swigc__p_clusterObj[] = {  {&_swigt__p_clusterObj, 0, 0, 0},{0, 0, 0, 0}};
 static swig_cast_info _swigc__p_colorObj[] = {  {&_swigt__p_colorObj, 0, 0, 0},{0, 0, 0, 0}};
 static swig_cast_info _swigc__p_debugLevel[] = {  {&_swigt__p_debugLevel, 0, 0, 0},{0, 0, 0, 0}};
 static swig_cast_info _swigc__p_double[] = {  {&_swigt__p_double, 0, 0, 0},{0, 0, 0, 0}};
-static swig_cast_info _swigc__p_error_obj[] = {  {&_swigt__p_error_obj, 0, 0, 0},{0, 0, 0, 0}};
+static swig_cast_info _swigc__p_errorObj[] = {  {&_swigt__p_errorObj, 0, 0, 0},{0, 0, 0, 0}};
 static swig_cast_info _swigc__p_fontSetObj[] = {  {&_swigt__p_fontSetObj, 0, 0, 0},{0, 0, 0, 0}};
 static swig_cast_info _swigc__p_hashTableObj[] = {  {&_swigt__p_hashTableObj, 0, 0, 0},{0, 0, 0, 0}};
 static swig_cast_info _swigc__p_imageObj[] = {  {&_swigt__p_imageObj, 0, 0, 0},{0, 0, 0, 0}};
@@ -42217,12 +43888,13 @@ static swig_cast_info _swigc__p_intarray[] = {  {&_swigt__p_intarray, 0, 0, 0},{
 static swig_cast_info _swigc__p_labelCacheMemberObj[] = {  {&_swigt__p_labelCacheMemberObj, 0, 0, 0},{0, 0, 0, 0}};
 static swig_cast_info _swigc__p_labelCacheObj[] = {  {&_swigt__p_labelCacheObj, 0, 0, 0},{0, 0, 0, 0}};
 static swig_cast_info _swigc__p_labelCacheSlotObj[] = {  {&_swigt__p_labelCacheSlotObj, 0, 0, 0},{0, 0, 0, 0}};
+static swig_cast_info _swigc__p_labelLeaderObj[] = {  {&_swigt__p_labelLeaderObj, 0, 0, 0},{0, 0, 0, 0}};
 static swig_cast_info _swigc__p_labelObj[] = {  {&_swigt__p_labelObj, 0, 0, 0},{0, 0, 0, 0}};
 static swig_cast_info _swigc__p_labelStyleObj[] = {  {&_swigt__p_labelStyleObj, 0, 0, 0},{0, 0, 0, 0}};
-static swig_cast_info _swigc__p_layer_obj[] = {  {&_swigt__p_layer_obj, 0, 0, 0},{0, 0, 0, 0}};
+static swig_cast_info _swigc__p_layerObj[] = {  {&_swigt__p_layerObj, 0, 0, 0},{0, 0, 0, 0}};
 static swig_cast_info _swigc__p_legendObj[] = {  {&_swigt__p_legendObj, 0, 0, 0},{0, 0, 0, 0}};
 static swig_cast_info _swigc__p_lineObj[] = {  {&_swigt__p_lineObj, 0, 0, 0},{0, 0, 0, 0}};
-static swig_cast_info _swigc__p_map_obj[] = {  {&_swigt__p_map_obj, 0, 0, 0},{0, 0, 0, 0}};
+static swig_cast_info _swigc__p_mapObj[] = {  {&_swigt__p_mapObj, 0, 0, 0},{0, 0, 0, 0}};
 static swig_cast_info _swigc__p_markerCacheMemberObj[] = {  {&_swigt__p_markerCacheMemberObj, 0, 0, 0},{0, 0, 0, 0}};
 static swig_cast_info _swigc__p_outputFormatObj[] = {  {&_swigt__p_outputFormatObj, 0, 0, 0},{0, 0, 0, 0}};
 static swig_cast_info _swigc__p_p_char[] = {  {&_swigt__p_p_char, 0, 0, 0},{0, 0, 0, 0}};
@@ -42253,12 +43925,12 @@ static swig_cast_info *swig_cast_initial[] = {
   _swigc__p_FILE,
   _swigc__p_cgiRequestObj,
   _swigc__p_char,
-  _swigc__p_class_obj,
+  _swigc__p_classObj,
   _swigc__p_clusterObj,
   _swigc__p_colorObj,
   _swigc__p_debugLevel,
   _swigc__p_double,
-  _swigc__p_error_obj,
+  _swigc__p_errorObj,
   _swigc__p_fontSetObj,
   _swigc__p_hashTableObj,
   _swigc__p_imageObj,
@@ -42268,12 +43940,13 @@ static swig_cast_info *swig_cast_initial[] = {
   _swigc__p_labelCacheMemberObj,
   _swigc__p_labelCacheObj,
   _swigc__p_labelCacheSlotObj,
+  _swigc__p_labelLeaderObj,
   _swigc__p_labelObj,
   _swigc__p_labelStyleObj,
-  _swigc__p_layer_obj,
+  _swigc__p_layerObj,
   _swigc__p_legendObj,
   _swigc__p_lineObj,
-  _swigc__p_map_obj,
+  _swigc__p_mapObj,
   _swigc__p_markerCacheMemberObj,
   _swigc__p_outputFormatObj,
   _swigc__p_p_char,
@@ -42460,6 +44133,8 @@ static swig_command_info swig_commands[] = {
 {"mapscriptc::styleObj_pattern_get", _wrap_styleObj_pattern_get},
 {"mapscriptc::styleObj_gap_set", _wrap_styleObj_gap_set},
 {"mapscriptc::styleObj_gap_get", _wrap_styleObj_gap_get},
+{"mapscriptc::styleObj_initialgap_set", _wrap_styleObj_initialgap_set},
+{"mapscriptc::styleObj_initialgap_get", _wrap_styleObj_initialgap_get},
 {"mapscriptc::styleObj_position_set", _wrap_styleObj_position_set},
 {"mapscriptc::styleObj_position_get", _wrap_styleObj_position_get},
 {"mapscriptc::styleObj_linecap_set", _wrap_styleObj_linecap_set},
@@ -42480,6 +44155,10 @@ static swig_command_info swig_commands[] = {
 {"mapscriptc::styleObj_offsetx_get", _wrap_styleObj_offsetx_get},
 {"mapscriptc::styleObj_offsety_set", _wrap_styleObj_offsety_set},
 {"mapscriptc::styleObj_offsety_get", _wrap_styleObj_offsety_get},
+{"mapscriptc::styleObj_polaroffsetpixel_set", _wrap_styleObj_polaroffsetpixel_set},
+{"mapscriptc::styleObj_polaroffsetpixel_get", _wrap_styleObj_polaroffsetpixel_get},
+{"mapscriptc::styleObj_polaroffsetangle_set", _wrap_styleObj_polaroffsetangle_set},
+{"mapscriptc::styleObj_polaroffsetangle_get", _wrap_styleObj_polaroffsetangle_get},
 {"mapscriptc::styleObj_angle_set", _wrap_styleObj_angle_set},
 {"mapscriptc::styleObj_angle_get", _wrap_styleObj_angle_get},
 {"mapscriptc::styleObj_antialias_set", _wrap_styleObj_antialias_set},
@@ -42498,6 +44177,14 @@ static swig_command_info swig_commands[] = {
 {"mapscriptc::styleObj_getBinding", _wrap_styleObj_getBinding},
 {"mapscriptc::styleObj_getGeomTransform", _wrap_styleObj_getGeomTransform},
 {"mapscriptc::styleObj_setGeomTransform", _wrap_styleObj_setGeomTransform},
+{"mapscriptc::labelLeaderObj_maxdistance_set", _wrap_labelLeaderObj_maxdistance_set},
+{"mapscriptc::labelLeaderObj_maxdistance_get", _wrap_labelLeaderObj_maxdistance_get},
+{"mapscriptc::labelLeaderObj_gridstep_set", _wrap_labelLeaderObj_gridstep_set},
+{"mapscriptc::labelLeaderObj_gridstep_get", _wrap_labelLeaderObj_gridstep_get},
+{"mapscriptc::labelLeaderObj_numstyles_get", _wrap_labelLeaderObj_numstyles_get},
+{"mapscriptc::new_labelLeaderObj", _wrap_new_labelLeaderObj},
+{"mapscriptc::delete_labelLeaderObj", _wrap_delete_labelLeaderObj},
+{"mapscriptc::labelObj_refcount_get", _wrap_labelObj_refcount_get},
 {"mapscriptc::labelObj_font_set", _wrap_labelObj_font_set},
 {"mapscriptc::labelObj_font_get", _wrap_labelObj_font_get},
 {"mapscriptc::labelObj_type_set", _wrap_labelObj_type_set},
@@ -42566,24 +44253,38 @@ static swig_command_info swig_commands[] = {
 {"mapscriptc::labelObj_encoding_get", _wrap_labelObj_encoding_get},
 {"mapscriptc::labelObj_priority_set", _wrap_labelObj_priority_set},
 {"mapscriptc::labelObj_priority_get", _wrap_labelObj_priority_get},
+{"mapscriptc::labelObj_status_set", _wrap_labelObj_status_set},
+{"mapscriptc::labelObj_status_get", _wrap_labelObj_status_get},
 {"mapscriptc::labelObj_numstyles_set", _wrap_labelObj_numstyles_set},
 {"mapscriptc::labelObj_numstyles_get", _wrap_labelObj_numstyles_get},
+{"mapscriptc::labelObj_annotext_set", _wrap_labelObj_annotext_set},
+{"mapscriptc::labelObj_annotext_get", _wrap_labelObj_annotext_get},
+{"mapscriptc::labelObj_annopoint_set", _wrap_labelObj_annopoint_set},
+{"mapscriptc::labelObj_annopoint_get", _wrap_labelObj_annopoint_get},
+{"mapscriptc::labelObj_annopoly_set", _wrap_labelObj_annopoly_set},
+{"mapscriptc::labelObj_annopoly_get", _wrap_labelObj_annopoly_get},
+{"mapscriptc::labelObj_leader_set", _wrap_labelObj_leader_set},
+{"mapscriptc::labelObj_leader_get", _wrap_labelObj_leader_get},
+{"mapscriptc::new_labelObj", _wrap_new_labelObj},
+{"mapscriptc::delete_labelObj", _wrap_delete_labelObj},
 {"mapscriptc::labelObj_updateFromString", _wrap_labelObj_updateFromString},
 {"mapscriptc::labelObj_removeBinding", _wrap_labelObj_removeBinding},
 {"mapscriptc::labelObj_getBinding", _wrap_labelObj_getBinding},
 {"mapscriptc::labelObj_setBinding", _wrap_labelObj_setBinding},
+{"mapscriptc::labelObj_setExpression", _wrap_labelObj_setExpression},
+{"mapscriptc::labelObj_getExpressionString", _wrap_labelObj_getExpressionString},
+{"mapscriptc::labelObj_setText", _wrap_labelObj_setText},
+{"mapscriptc::labelObj_getTextString", _wrap_labelObj_getTextString},
 {"mapscriptc::labelObj_getStyle", _wrap_labelObj_getStyle},
 {"mapscriptc::labelObj_insertStyle", _wrap_labelObj_insertStyle},
 {"mapscriptc::labelObj_removeStyle", _wrap_labelObj_removeStyle},
 {"mapscriptc::labelObj_moveStyleUp", _wrap_labelObj_moveStyleUp},
 {"mapscriptc::labelObj_moveStyleDown", _wrap_labelObj_moveStyleDown},
-{"mapscriptc::new_labelObj", _wrap_new_labelObj},
-{"mapscriptc::delete_labelObj", _wrap_delete_labelObj},
 {"mapscriptc::classObj_status_set", _wrap_classObj_status_set},
 {"mapscriptc::classObj_status_get", _wrap_classObj_status_get},
-{"mapscriptc::classObj_numstyles_set", _wrap_classObj_numstyles_set},
 {"mapscriptc::classObj_numstyles_get", _wrap_classObj_numstyles_get},
-{"mapscriptc::classObj_label_get", _wrap_classObj_label_get},
+{"mapscriptc::classObj_numlabels_set", _wrap_classObj_numlabels_set},
+{"mapscriptc::classObj_numlabels_get", _wrap_classObj_numlabels_get},
 {"mapscriptc::classObj_name_set", _wrap_classObj_name_set},
 {"mapscriptc::classObj_name_get", _wrap_classObj_name_get},
 {"mapscriptc::classObj_title_set", _wrap_classObj_title_set},
@@ -42608,6 +44309,8 @@ static swig_command_info swig_commands[] = {
 {"mapscriptc::classObj_keyimage_get", _wrap_classObj_keyimage_get},
 {"mapscriptc::classObj_group_set", _wrap_classObj_group_set},
 {"mapscriptc::classObj_group_get", _wrap_classObj_group_get},
+{"mapscriptc::classObj_leader_set", _wrap_classObj_leader_set},
+{"mapscriptc::classObj_leader_get", _wrap_classObj_leader_get},
 {"mapscriptc::new_classObj", _wrap_new_classObj},
 {"mapscriptc::delete_classObj", _wrap_delete_classObj},
 {"mapscriptc::classObj_updateFromString", _wrap_classObj_updateFromString},
@@ -42622,25 +44325,28 @@ static swig_command_info swig_commands[] = {
 {"mapscriptc::classObj_getNextMetaDataKey", _wrap_classObj_getNextMetaDataKey},
 {"mapscriptc::classObj_drawLegendIcon", _wrap_classObj_drawLegendIcon},
 {"mapscriptc::classObj_createLegendIcon", _wrap_classObj_createLegendIcon},
+{"mapscriptc::classObj_getLabel", _wrap_classObj_getLabel},
+{"mapscriptc::classObj_addLabel", _wrap_classObj_addLabel},
+{"mapscriptc::classObj_removeLabel", _wrap_classObj_removeLabel},
 {"mapscriptc::classObj_getStyle", _wrap_classObj_getStyle},
 {"mapscriptc::classObj_insertStyle", _wrap_classObj_insertStyle},
 {"mapscriptc::classObj_removeStyle", _wrap_classObj_removeStyle},
 {"mapscriptc::classObj_moveStyleUp", _wrap_classObj_moveStyleUp},
 {"mapscriptc::classObj_moveStyleDown", _wrap_classObj_moveStyleDown},
-{"mapscriptc::labelCacheMemberObj_text_get", _wrap_labelCacheMemberObj_text_get},
 {"mapscriptc::labelCacheMemberObj_featuresize_get", _wrap_labelCacheMemberObj_featuresize_get},
 {"mapscriptc::labelCacheMemberObj_styles_get", _wrap_labelCacheMemberObj_styles_get},
 {"mapscriptc::labelCacheMemberObj_numstyles_get", _wrap_labelCacheMemberObj_numstyles_get},
-{"mapscriptc::labelCacheMemberObj_label_get", _wrap_labelCacheMemberObj_label_get},
+{"mapscriptc::labelCacheMemberObj_labels_get", _wrap_labelCacheMemberObj_labels_get},
+{"mapscriptc::labelCacheMemberObj_numlabels_get", _wrap_labelCacheMemberObj_numlabels_get},
 {"mapscriptc::labelCacheMemberObj_layerindex_get", _wrap_labelCacheMemberObj_layerindex_get},
 {"mapscriptc::labelCacheMemberObj_classindex_get", _wrap_labelCacheMemberObj_classindex_get},
-{"mapscriptc::labelCacheMemberObj_tileindex_get", _wrap_labelCacheMemberObj_tileindex_get},
-{"mapscriptc::labelCacheMemberObj_shapeindex_get", _wrap_labelCacheMemberObj_shapeindex_get},
 {"mapscriptc::labelCacheMemberObj_shapetype_get", _wrap_labelCacheMemberObj_shapetype_get},
 {"mapscriptc::labelCacheMemberObj_point_get", _wrap_labelCacheMemberObj_point_get},
 {"mapscriptc::labelCacheMemberObj_poly_get", _wrap_labelCacheMemberObj_poly_get},
 {"mapscriptc::labelCacheMemberObj_status_get", _wrap_labelCacheMemberObj_status_get},
 {"mapscriptc::labelCacheMemberObj_markerid_get", _wrap_labelCacheMemberObj_markerid_get},
+{"mapscriptc::labelCacheMemberObj_leaderline_get", _wrap_labelCacheMemberObj_leaderline_get},
+{"mapscriptc::labelCacheMemberObj_leaderbbox_get", _wrap_labelCacheMemberObj_leaderbbox_get},
 {"mapscriptc::new_labelCacheMemberObj", _wrap_new_labelCacheMemberObj},
 {"mapscriptc::delete_labelCacheMemberObj", _wrap_delete_labelCacheMemberObj},
 {"mapscriptc::markerCacheMemberObj_id_get", _wrap_markerCacheMemberObj_id_get},
@@ -42657,6 +44363,7 @@ static swig_command_info swig_commands[] = {
 {"mapscriptc::delete_labelCacheSlotObj", _wrap_delete_labelCacheSlotObj},
 {"mapscriptc::labelCacheObj_slots_get", _wrap_labelCacheObj_slots_get},
 {"mapscriptc::labelCacheObj_numlabels_get", _wrap_labelCacheObj_numlabels_get},
+{"mapscriptc::labelCacheObj_gutter_get", _wrap_labelCacheObj_gutter_get},
 {"mapscriptc::labelCacheObj_freeCache", _wrap_labelCacheObj_freeCache},
 {"mapscriptc::new_labelCacheObj", _wrap_new_labelCacheObj},
 {"mapscriptc::delete_labelCacheObj", _wrap_delete_labelCacheObj},
@@ -42775,6 +44482,19 @@ static swig_command_info swig_commands[] = {
 {"mapscriptc::legendObj_updateFromString", _wrap_legendObj_updateFromString},
 {"mapscriptc::new_legendObj", _wrap_new_legendObj},
 {"mapscriptc::delete_legendObj", _wrap_delete_legendObj},
+{"mapscriptc::imageObj_width_get", _wrap_imageObj_width_get},
+{"mapscriptc::imageObj_height_get", _wrap_imageObj_height_get},
+{"mapscriptc::imageObj_resolution_get", _wrap_imageObj_resolution_get},
+{"mapscriptc::imageObj_resolutionfactor_get", _wrap_imageObj_resolutionfactor_get},
+{"mapscriptc::imageObj_imagepath_get", _wrap_imageObj_imagepath_get},
+{"mapscriptc::imageObj_imageurl_get", _wrap_imageObj_imageurl_get},
+{"mapscriptc::imageObj_format_get", _wrap_imageObj_format_get},
+{"mapscriptc::new_imageObj", _wrap_new_imageObj},
+{"mapscriptc::delete_imageObj", _wrap_delete_imageObj},
+{"mapscriptc::imageObj_save", _wrap_imageObj_save},
+{"mapscriptc::imageObj_write", _wrap_imageObj_write},
+{"mapscriptc::imageObj_getBytes", _wrap_imageObj_getBytes},
+{"mapscriptc::imageObj_getSize", _wrap_imageObj_getSize},
 {"mapscriptc::layerObj_classitem_set", _wrap_layerObj_classitem_set},
 {"mapscriptc::layerObj_classitem_get", _wrap_layerObj_classitem_get},
 {"mapscriptc::layerObj_refcount_get", _wrap_layerObj_refcount_get},
@@ -42874,6 +44594,8 @@ static swig_command_info swig_commands[] = {
 {"mapscriptc::layerObj_numjoins_get", _wrap_layerObj_numjoins_get},
 {"mapscriptc::layerObj_classgroup_set", _wrap_layerObj_classgroup_set},
 {"mapscriptc::layerObj_classgroup_get", _wrap_layerObj_classgroup_get},
+{"mapscriptc::layerObj_mask_set", _wrap_layerObj_mask_set},
+{"mapscriptc::layerObj_mask_get", _wrap_layerObj_mask_get},
 {"mapscriptc::new_layerObj", _wrap_new_layerObj},
 {"mapscriptc::delete_layerObj", _wrap_delete_layerObj},
 {"mapscriptc::layerObj_clone", _wrap_layerObj_clone},
@@ -42890,6 +44612,7 @@ static swig_command_info swig_commands[] = {
 {"mapscriptc::layerObj_getResult", _wrap_layerObj_getResult},
 {"mapscriptc::layerObj_getClass", _wrap_layerObj_getClass},
 {"mapscriptc::layerObj_getItem", _wrap_layerObj_getItem},
+{"mapscriptc::layerObj_setItems", _wrap_layerObj_setItems},
 {"mapscriptc::layerObj_draw", _wrap_layerObj_draw},
 {"mapscriptc::layerObj_drawQuery", _wrap_layerObj_drawQuery},
 {"mapscriptc::layerObj_queryByFilter", _wrap_layerObj_queryByFilter},
@@ -43061,19 +44784,6 @@ static swig_command_info swig_commands[] = {
 {"mapscriptc::mapObj_zoomPoint", _wrap_mapObj_zoomPoint},
 {"mapscriptc::mapObj_zoomRectangle", _wrap_mapObj_zoomRectangle},
 {"mapscriptc::mapObj_zoomScale", _wrap_mapObj_zoomScale},
-{"mapscriptc::imageObj_width_get", _wrap_imageObj_width_get},
-{"mapscriptc::imageObj_height_get", _wrap_imageObj_height_get},
-{"mapscriptc::imageObj_resolution_get", _wrap_imageObj_resolution_get},
-{"mapscriptc::imageObj_resolutionfactor_get", _wrap_imageObj_resolutionfactor_get},
-{"mapscriptc::imageObj_imagepath_get", _wrap_imageObj_imagepath_get},
-{"mapscriptc::imageObj_imageurl_get", _wrap_imageObj_imageurl_get},
-{"mapscriptc::imageObj_format_get", _wrap_imageObj_format_get},
-{"mapscriptc::new_imageObj", _wrap_new_imageObj},
-{"mapscriptc::delete_imageObj", _wrap_delete_imageObj},
-{"mapscriptc::imageObj_save", _wrap_imageObj_save},
-{"mapscriptc::imageObj_write", _wrap_imageObj_write},
-{"mapscriptc::imageObj_getBytes", _wrap_imageObj_getBytes},
-{"mapscriptc::imageObj_getSize", _wrap_imageObj_getSize},
 {"mapscriptc::msSaveImage", _wrap_msSaveImage},
 {"mapscriptc::msFreeImage", _wrap_msFreeImage},
 {"mapscriptc::msSetup", _wrap_msSetup},
@@ -43085,6 +44795,8 @@ static swig_command_info swig_commands[] = {
 {"mapscriptc::strokeStyleObj_patternlength_get", _wrap_strokeStyleObj_patternlength_get},
 {"mapscriptc::strokeStyleObj_pattern_set", _wrap_strokeStyleObj_pattern_set},
 {"mapscriptc::strokeStyleObj_pattern_get", _wrap_strokeStyleObj_pattern_get},
+{"mapscriptc::strokeStyleObj_patternoffset_set", _wrap_strokeStyleObj_patternoffset_set},
+{"mapscriptc::strokeStyleObj_patternoffset_get", _wrap_strokeStyleObj_patternoffset_get},
 {"mapscriptc::strokeStyleObj_color_set", _wrap_strokeStyleObj_color_set},
 {"mapscriptc::strokeStyleObj_color_get", _wrap_strokeStyleObj_color_get},
 {"mapscriptc::strokeStyleObj_linecap_set", _wrap_strokeStyleObj_linecap_set},
@@ -43137,8 +44849,10 @@ static swig_command_info swig_commands[] = {
 {"mapscriptc::tileCacheObj_next_get", _wrap_tileCacheObj_next_get},
 {"mapscriptc::new_tileCacheObj", _wrap_new_tileCacheObj},
 {"mapscriptc::delete_tileCacheObj", _wrap_delete_tileCacheObj},
-{"mapscriptc::labelStyleObj_font_set", _wrap_labelStyleObj_font_set},
-{"mapscriptc::labelStyleObj_font_get", _wrap_labelStyleObj_font_get},
+{"mapscriptc::labelStyleObj_fonts_set", _wrap_labelStyleObj_fonts_set},
+{"mapscriptc::labelStyleObj_fonts_get", _wrap_labelStyleObj_fonts_get},
+{"mapscriptc::labelStyleObj_numfonts_set", _wrap_labelStyleObj_numfonts_set},
+{"mapscriptc::labelStyleObj_numfonts_get", _wrap_labelStyleObj_numfonts_get},
 {"mapscriptc::labelStyleObj_size_set", _wrap_labelStyleObj_size_set},
 {"mapscriptc::labelStyleObj_size_get", _wrap_labelStyleObj_size_get},
 {"mapscriptc::labelStyleObj_rotation_set", _wrap_labelStyleObj_rotation_set},
@@ -43149,6 +44863,8 @@ static swig_command_info swig_commands[] = {
 {"mapscriptc::labelStyleObj_outlinewidth_get", _wrap_labelStyleObj_outlinewidth_get},
 {"mapscriptc::labelStyleObj_outlinecolor_set", _wrap_labelStyleObj_outlinecolor_set},
 {"mapscriptc::labelStyleObj_outlinecolor_get", _wrap_labelStyleObj_outlinecolor_get},
+{"mapscriptc::labelStyleObj_antialias_set", _wrap_labelStyleObj_antialias_set},
+{"mapscriptc::labelStyleObj_antialias_get", _wrap_labelStyleObj_antialias_get},
 {"mapscriptc::new_labelStyleObj", _wrap_new_labelStyleObj},
 {"mapscriptc::delete_labelStyleObj", _wrap_delete_labelStyleObj},
 {"mapscriptc::rectObj_minx_set", _wrap_rectObj_minx_set},
@@ -43288,12 +45004,12 @@ static swig_command_info swig_commands[] = {
 {"mapscriptc::shapefileObj_getDBF", _wrap_shapefileObj_getDBF},
 {"mapscriptc::projectionObj_numargs_get", _wrap_projectionObj_numargs_get},
 {"mapscriptc::projectionObj_automatic_get", _wrap_projectionObj_automatic_get},
+{"mapscriptc::projectionObj_wellknownprojection_set", _wrap_projectionObj_wellknownprojection_set},
+{"mapscriptc::projectionObj_wellknownprojection_get", _wrap_projectionObj_wellknownprojection_get},
 {"mapscriptc::new_projectionObj", _wrap_new_projectionObj},
 {"mapscriptc::delete_projectionObj", _wrap_delete_projectionObj},
 {"mapscriptc::projectionObj_setWKTProjection", _wrap_projectionObj_setWKTProjection},
 {"mapscriptc::projectionObj_getUnits", _wrap_projectionObj_getUnits},
-{"mapscriptc::colorObj_pen_set", _wrap_colorObj_pen_set},
-{"mapscriptc::colorObj_pen_get", _wrap_colorObj_pen_get},
 {"mapscriptc::colorObj_red_set", _wrap_colorObj_red_set},
 {"mapscriptc::colorObj_red_get", _wrap_colorObj_red_get},
 {"mapscriptc::colorObj_green_set", _wrap_colorObj_green_set},
@@ -43329,6 +45045,10 @@ static swig_command_info swig_commands[] = {
 {"mapscriptc::symbolObj_numpoints_get", _wrap_symbolObj_numpoints_get},
 {"mapscriptc::symbolObj_filled_set", _wrap_symbolObj_filled_set},
 {"mapscriptc::symbolObj_filled_get", _wrap_symbolObj_filled_get},
+{"mapscriptc::symbolObj_anchorpoint_x_set", _wrap_symbolObj_anchorpoint_x_set},
+{"mapscriptc::symbolObj_anchorpoint_x_get", _wrap_symbolObj_anchorpoint_x_get},
+{"mapscriptc::symbolObj_anchorpoint_y_set", _wrap_symbolObj_anchorpoint_y_set},
+{"mapscriptc::symbolObj_anchorpoint_y_get", _wrap_symbolObj_anchorpoint_y_get},
 {"mapscriptc::symbolObj_imagepath_get", _wrap_symbolObj_imagepath_get},
 {"mapscriptc::symbolObj_transparent_set", _wrap_symbolObj_transparent_set},
 {"mapscriptc::symbolObj_transparent_get", _wrap_symbolObj_transparent_get},
@@ -43387,6 +45107,7 @@ static swig_command_info swig_commands[] = {
 {"mapscriptc::OWSRequest_loadParams", _wrap_OWSRequest_loadParams},
 {"mapscriptc::OWSRequest_loadParamsFromURL", _wrap_OWSRequest_loadParamsFromURL},
 {"mapscriptc::OWSRequest_setParameter", _wrap_OWSRequest_setParameter},
+{"mapscriptc::OWSRequest_addParameter", _wrap_OWSRequest_addParameter},
 {"mapscriptc::OWSRequest_getName", _wrap_OWSRequest_getName},
 {"mapscriptc::OWSRequest_getValue", _wrap_OWSRequest_getValue},
 {"mapscriptc::OWSRequest_getValueByName", _wrap_OWSRequest_getValueByName},
@@ -43700,7 +45421,7 @@ XS(SWIG_init) {
   
   /*@SWIG:/usr/share/swig1.3/perl5/perltypemaps.swg,65,%set_constant@*/ do {
     SV *sv = get_sv((char*) SWIG_prefix "MS_VERSION", TRUE | 0x2 | GV_ADDMULTI);
-    sv_setsv(sv, SWIG_FromCharPtr("6.0.3"));
+    sv_setsv(sv, SWIG_FromCharPtr("6.2.0"));
     SvREADONLY_on(sv);
   } while(0) /*@SWIG@*/;
   /*@SWIG:/usr/share/swig1.3/perl5/perltypemaps.swg,65,%set_constant@*/ do {
@@ -43710,22 +45431,17 @@ XS(SWIG_init) {
   } while(0) /*@SWIG@*/;
   /*@SWIG:/usr/share/swig1.3/perl5/perltypemaps.swg,65,%set_constant@*/ do {
     SV *sv = get_sv((char*) SWIG_prefix "MS_VERSION_MINOR", TRUE | 0x2 | GV_ADDMULTI);
-    sv_setsv(sv, SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(0)));
+    sv_setsv(sv, SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(2)));
     SvREADONLY_on(sv);
   } while(0) /*@SWIG@*/;
   /*@SWIG:/usr/share/swig1.3/perl5/perltypemaps.swg,65,%set_constant@*/ do {
     SV *sv = get_sv((char*) SWIG_prefix "MS_VERSION_REV", TRUE | 0x2 | GV_ADDMULTI);
-    sv_setsv(sv, SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(3)));
+    sv_setsv(sv, SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(0)));
     SvREADONLY_on(sv);
   } while(0) /*@SWIG@*/;
   /*@SWIG:/usr/share/swig1.3/perl5/perltypemaps.swg,65,%set_constant@*/ do {
     SV *sv = get_sv((char*) SWIG_prefix "MS_VERSION_NUM", TRUE | 0x2 | GV_ADDMULTI);
-    sv_setsv(sv, SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)((6*10000+0*100+3))));
-    SvREADONLY_on(sv);
-  } while(0) /*@SWIG@*/;
-  /*@SWIG:/usr/share/swig1.3/perl5/perltypemaps.swg,65,%set_constant@*/ do {
-    SV *sv = get_sv((char*) SWIG_prefix "__FUNCTION__", TRUE | 0x2 | GV_ADDMULTI);
-    sv_setsv(sv, SWIG_FromCharPtr("MapServer"));
+    sv_setsv(sv, SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)((6*10000+2*100+0))));
     SvREADONLY_on(sv);
   } while(0) /*@SWIG@*/;
   /*@SWIG:/usr/share/swig1.3/perl5/perltypemaps.swg,65,%set_constant@*/ do {
@@ -43799,16 +45515,31 @@ XS(SWIG_init) {
     SvREADONLY_on(sv);
   } while(0) /*@SWIG@*/;
   /*@SWIG:/usr/share/swig1.3/perl5/perltypemaps.swg,65,%set_constant@*/ do {
+    SV *sv = get_sv((char*) SWIG_prefix "MS_LABEL_ALLOCSIZE", TRUE | 0x2 | GV_ADDMULTI);
+    sv_setsv(sv, SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(2)));
+    SvREADONLY_on(sv);
+  } while(0) /*@SWIG@*/;
+  /*@SWIG:/usr/share/swig1.3/perl5/perltypemaps.swg,65,%set_constant@*/ do {
     SV *sv = get_sv((char*) SWIG_prefix "MS_MAX_LABEL_PRIORITY", TRUE | 0x2 | GV_ADDMULTI);
     sv_setsv(sv, SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(10)));
     SvREADONLY_on(sv);
   } while(0) /*@SWIG@*/;
   /*@SWIG:/usr/share/swig1.3/perl5/perltypemaps.swg,65,%set_constant@*/ do {
+    SV *sv = get_sv((char*) SWIG_prefix "MS_MAX_LABEL_FONTS", TRUE | 0x2 | GV_ADDMULTI);
+    sv_setsv(sv, SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(5)));
+    SvREADONLY_on(sv);
+  } while(0) /*@SWIG@*/;
+  /*@SWIG:/usr/share/swig1.3/perl5/perltypemaps.swg,65,%set_constant@*/ do {
     SV *sv = get_sv((char*) SWIG_prefix "MS_DEFAULT_LABEL_PRIORITY", TRUE | 0x2 | GV_ADDMULTI);
     sv_setsv(sv, SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(1)));
     SvREADONLY_on(sv);
   } while(0) /*@SWIG@*/;
   /*@SWIG:/usr/share/swig1.3/perl5/perltypemaps.swg,65,%set_constant@*/ do {
+    SV *sv = get_sv((char*) SWIG_prefix "MS_LABEL_FORCE_GROUP", TRUE | 0x2 | GV_ADDMULTI);
+    sv_setsv(sv, SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(2)));
+    SvREADONLY_on(sv);
+  } while(0) /*@SWIG@*/;
+  /*@SWIG:/usr/share/swig1.3/perl5/perltypemaps.swg,65,%set_constant@*/ do {
     SV *sv = get_sv((char*) SWIG_prefix "MS_RENDER_WITH_SWF", TRUE | 0x2 | GV_ADDMULTI);
     sv_setsv(sv, SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(2)));
     SvREADONLY_on(sv);
@@ -44194,6 +45925,11 @@ XS(SWIG_init) {
     SvREADONLY_on(sv);
   } while(0) /*@SWIG@*/;
   /*@SWIG:/usr/share/swig1.3/perl5/perltypemaps.swg,65,%set_constant@*/ do {
+    SV *sv = get_sv((char*) SWIG_prefix "MS_UVRASTER", TRUE | 0x2 | GV_ADDMULTI);
+    sv_setsv(sv, SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(MS_UVRASTER)));
+    SvREADONLY_on(sv);
+  } while(0) /*@SWIG@*/;
+  /*@SWIG:/usr/share/swig1.3/perl5/perltypemaps.swg,65,%set_constant@*/ do {
     SV *sv = get_sv((char*) SWIG_prefix "MS_DB_XBASE", TRUE | 0x2 | GV_ADDMULTI);
     sv_setsv(sv, SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(MS_DB_XBASE)));
     SvREADONLY_on(sv);
@@ -44470,7 +46206,7 @@ XS(SWIG_init) {
   } while(0) /*@SWIG@*/;
   /*@SWIG:/usr/share/swig1.3/perl5/perltypemaps.swg,65,%set_constant@*/ do {
     SV *sv = get_sv((char*) SWIG_prefix "MS_STYLE_BINDING_LENGTH", TRUE | 0x2 | GV_ADDMULTI);
-    sv_setsv(sv, SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(8)));
+    sv_setsv(sv, SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(12)));
     SvREADONLY_on(sv);
   } while(0) /*@SWIG@*/;
   /*@SWIG:/usr/share/swig1.3/perl5/perltypemaps.swg,65,%set_constant@*/ do {
@@ -44514,6 +46250,26 @@ XS(SWIG_init) {
     SvREADONLY_on(sv);
   } while(0) /*@SWIG@*/;
   /*@SWIG:/usr/share/swig1.3/perl5/perltypemaps.swg,65,%set_constant@*/ do {
+    SV *sv = get_sv((char*) SWIG_prefix "MS_STYLE_BINDING_OFFSET_X", TRUE | 0x2 | GV_ADDMULTI);
+    sv_setsv(sv, SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(MS_STYLE_BINDING_OFFSET_X)));
+    SvREADONLY_on(sv);
+  } while(0) /*@SWIG@*/;
+  /*@SWIG:/usr/share/swig1.3/perl5/perltypemaps.swg,65,%set_constant@*/ do {
+    SV *sv = get_sv((char*) SWIG_prefix "MS_STYLE_BINDING_OFFSET_Y", TRUE | 0x2 | GV_ADDMULTI);
+    sv_setsv(sv, SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(MS_STYLE_BINDING_OFFSET_Y)));
+    SvREADONLY_on(sv);
+  } while(0) /*@SWIG@*/;
+  /*@SWIG:/usr/share/swig1.3/perl5/perltypemaps.swg,65,%set_constant@*/ do {
+    SV *sv = get_sv((char*) SWIG_prefix "MS_STYLE_BINDING_POLAROFFSET_PIXEL", TRUE | 0x2 | GV_ADDMULTI);
+    sv_setsv(sv, SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(MS_STYLE_BINDING_POLAROFFSET_PIXEL)));
+    SvREADONLY_on(sv);
+  } while(0) /*@SWIG@*/;
+  /*@SWIG:/usr/share/swig1.3/perl5/perltypemaps.swg,65,%set_constant@*/ do {
+    SV *sv = get_sv((char*) SWIG_prefix "MS_STYLE_BINDING_POLAROFFSET_ANGLE", TRUE | 0x2 | GV_ADDMULTI);
+    sv_setsv(sv, SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(MS_STYLE_BINDING_POLAROFFSET_ANGLE)));
+    SvREADONLY_on(sv);
+  } while(0) /*@SWIG@*/;
+  /*@SWIG:/usr/share/swig1.3/perl5/perltypemaps.swg,65,%set_constant@*/ do {
     SV *sv = get_sv((char*) SWIG_prefix "MS_LABEL_BINDING_LENGTH", TRUE | 0x2 | GV_ADDMULTI);
     sv_setsv(sv, SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(9)));
     SvREADONLY_on(sv);
@@ -44735,6 +46491,11 @@ XS(SWIG_init) {
     SvREADONLY_on(sv);
   } while(0) /*@SWIG@*/;
   /*@SWIG:/usr/share/swig1.3/perl5/perltypemaps.swg,65,%set_constant@*/ do {
+    SV *sv = get_sv((char*) SWIG_prefix "MS_TOKEN_FUNCTION_DIFFERENCE", TRUE | 0x2 | GV_ADDMULTI);
+    sv_setsv(sv, SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(MS_TOKEN_FUNCTION_DIFFERENCE)));
+    SvREADONLY_on(sv);
+  } while(0) /*@SWIG@*/;
+  /*@SWIG:/usr/share/swig1.3/perl5/perltypemaps.swg,65,%set_constant@*/ do {
     SV *sv = get_sv((char*) SWIG_prefix "MS_TOKEN_BINDING_DOUBLE", TRUE | 0x2 | GV_ADDMULTI);
     sv_setsv(sv, SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(MS_TOKEN_BINDING_DOUBLE)));
     SvREADONLY_on(sv);
@@ -44784,8 +46545,9 @@ XS(SWIG_init) {
   SWIG_TypeClientData(SWIGTYPE_p_queryMapObj, (void*) "mapscript::queryMapObj");
   SWIG_TypeClientData(SWIGTYPE_p_webObj, (void*) "mapscript::webObj");
   SWIG_TypeClientData(SWIGTYPE_p_styleObj, (void*) "mapscript::styleObj");
+  SWIG_TypeClientData(SWIGTYPE_p_labelLeaderObj, (void*) "mapscript::labelLeaderObj");
   SWIG_TypeClientData(SWIGTYPE_p_labelObj, (void*) "mapscript::labelObj");
-  SWIG_TypeClientData(SWIGTYPE_p_class_obj, (void*) "mapscript::classObj");
+  SWIG_TypeClientData(SWIGTYPE_p_classObj, (void*) "mapscript::classObj");
   SWIG_TypeClientData(SWIGTYPE_p_labelCacheMemberObj, (void*) "mapscript::labelCacheMemberObj");
   SWIG_TypeClientData(SWIGTYPE_p_markerCacheMemberObj, (void*) "mapscript::markerCacheMemberObj");
   SWIG_TypeClientData(SWIGTYPE_p_labelCacheSlotObj, (void*) "mapscript::labelCacheSlotObj");
@@ -44796,9 +46558,9 @@ XS(SWIG_init) {
   SWIG_TypeClientData(SWIGTYPE_p_referenceMapObj, (void*) "mapscript::referenceMapObj");
   SWIG_TypeClientData(SWIGTYPE_p_scalebarObj, (void*) "mapscript::scalebarObj");
   SWIG_TypeClientData(SWIGTYPE_p_legendObj, (void*) "mapscript::legendObj");
-  SWIG_TypeClientData(SWIGTYPE_p_layer_obj, (void*) "mapscript::layerObj");
-  SWIG_TypeClientData(SWIGTYPE_p_map_obj, (void*) "mapscript::mapObj");
   SWIG_TypeClientData(SWIGTYPE_p_imageObj, (void*) "mapscript::imageObj");
+  SWIG_TypeClientData(SWIGTYPE_p_layerObj, (void*) "mapscript::layerObj");
+  SWIG_TypeClientData(SWIGTYPE_p_mapObj, (void*) "mapscript::mapObj");
   SWIG_TypeClientData(SWIGTYPE_p_strokeStyleObj, (void*) "mapscript::strokeStyleObj");
   SWIG_TypeClientData(SWIGTYPE_p_symbolStyleObj, (void*) "mapscript::symbolStyleObj");
   SWIG_TypeClientData(SWIGTYPE_p_tileCacheObj, (void*) "mapscript::tileCacheObj");
@@ -44894,6 +46656,21 @@ XS(SWIG_init) {
     SvREADONLY_on(sv);
   } while(0) /*@SWIG@*/;
   SWIG_TypeClientData(SWIGTYPE_p_shapefileObj, (void*) "mapscript::shapefileObj");
+  /*@SWIG:/usr/share/swig1.3/perl5/perltypemaps.swg,65,%set_constant@*/ do {
+    SV *sv = get_sv((char*) SWIG_prefix "wkp_none", TRUE | 0x2 | GV_ADDMULTI);
+    sv_setsv(sv, SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(0)));
+    SvREADONLY_on(sv);
+  } while(0) /*@SWIG@*/;
+  /*@SWIG:/usr/share/swig1.3/perl5/perltypemaps.swg,65,%set_constant@*/ do {
+    SV *sv = get_sv((char*) SWIG_prefix "wkp_lonlat", TRUE | 0x2 | GV_ADDMULTI);
+    sv_setsv(sv, SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(1)));
+    SvREADONLY_on(sv);
+  } while(0) /*@SWIG@*/;
+  /*@SWIG:/usr/share/swig1.3/perl5/perltypemaps.swg,65,%set_constant@*/ do {
+    SV *sv = get_sv((char*) SWIG_prefix "wkp_gmerc", TRUE | 0x2 | GV_ADDMULTI);
+    sv_setsv(sv, SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(2)));
+    SvREADONLY_on(sv);
+  } while(0) /*@SWIG@*/;
   SWIG_TypeClientData(SWIGTYPE_p_projectionObj, (void*) "mapscript::projectionObj");
   /*@SWIG:/usr/share/swig1.3/perl5/perltypemaps.swg,65,%set_constant@*/ do {
     SV *sv = get_sv((char*) SWIG_prefix "MS_SYMBOL_SIMPLE", TRUE | 0x2 | GV_ADDMULTI);
@@ -45187,7 +46964,7 @@ XS(SWIG_init) {
     sv_setsv(sv, SWIG_FromCharPtr("en-US"));
     SvREADONLY_on(sv);
   } while(0) /*@SWIG@*/;
-  SWIG_TypeClientData(SWIGTYPE_p_error_obj, (void*) "mapscript::errorObj");
+  SWIG_TypeClientData(SWIGTYPE_p_errorObj, (void*) "mapscript::errorObj");
   /*@SWIG:/usr/share/swig1.3/perl5/perltypemaps.swg,65,%set_constant@*/ do {
     SV *sv = get_sv((char*) SWIG_prefix "MS_DEBUGLEVEL_ERRORSONLY", TRUE | 0x2 | GV_ADDMULTI);
     sv_setsv(sv, SWIG_From_int  SWIG_PERL_CALL_ARGS_1((int)(MS_DEBUGLEVEL_ERRORSONLY)));
diff --git a/mapscript/perl/plmodule.i b/mapscript/perl/plmodule.i
index c44df98..6a8f3d5 100644
--- a/mapscript/perl/plmodule.i
+++ b/mapscript/perl/plmodule.i
@@ -41,7 +41,12 @@
         sv_2mortal($result);
         argvi++;
         if( $1.owns_data )
-            gdFree($1.data);
+            msFree($1.data);
+}
+
+%typemap(out) char[ANY] {
+        $result = newSVpvn($1, strlen($1));
+        argvi++;
 }
 
 /*
diff --git a/mapscript/php/Makefile.in b/mapscript/php/Makefile.in
index 15c9bfb..20c9adb 100644
--- a/mapscript/php/Makefile.in
+++ b/mapscript/php/Makefile.in
@@ -33,19 +33,34 @@
 # | contact core at php.net.                                                |
 # +----------------------------------------------------------------------+
 
-CC =     @PHP_CC@
-LD =     @PHP_LD@
-CFLAGS = @CFLAGS@ @USE_PHP_REGEX@ -DCOMPILE_DL=1 @PHP_VERSION_FLAG@
-RUNPATHS= @RPATHS@
-
 #
-# Set PHP_SRC_DIR to point to the root of the PHP source tree
+# Pick a compiler, etc. Flex and bison are only required if you need to modify the mapserver lexer (maplexer.l) or expression parser (mapparser.y).
 #
-PHP_SRC_DIR = @PHP_SRC_DIR@
+prefix		=	@prefix@
+exec_prefix	=	@exec_prefix@
+libdir	=	@libdir@
+bindir	=	@bindir@
+top_builddir = @top_builddir@
+SHELL = @SHELL@
+CXX=	@CXX@
+CC=     @CC@
+LD=     @CXX@
+LIBTOOL=@LIBTOOL@
+INSTALL=@INSTALL@
+PHPCONFIG=@PHPCONFIG@
+
+LTCC=$(LIBTOOL) --mode=compile --tag=CC
+LTCXX=$(LIBTOOL) --mode=compile --tag=CXX
+LTLD=$(LIBTOOL) --mode=link --tag=CXX
+LTINSTALL=$(LIBTOOL) --mode=install
+
+XTRALIBS= @XTRALIBS@
+RUNPATHS= -rpath $(libdir)
+
+CFLAGS = @CFLAGS@ @USE_PHP_REGEX@ -DCOMPILE_DL=1 @PHP_VERSION_FLAG@
+
 
-PHP_INC = -I$(PHP_SRC_DIR) -I$(PHP_SRC_DIR)/dl -I$(PHP_SRC_DIR)/main \
-	  -I$(PHP_SRC_DIR)/Zend -I$(PHP_SRC_DIR)/include \
-	  -I$(PHP_SRC_DIR)/TSRM @APACHE_INC@
+PHP_INC = `$(PHPCONFIG) --includes ` @APACHE_INC@
 
 #
 # IMPORTANT NOTE ABOUT REGEX FOR PHP_MAPSCRIPT USERS:
@@ -69,7 +84,12 @@ MS_DEFINE = @ALL_ENABLED@
 MS_INC =    @MS_INC@ @ALL_INC@
 MS_STATIC = @ALL_STATIC_LIB@
 MS_LIBS =   $(RUNPATHS) @MS_LIB@ @ALL_LIB@ @XTRALIBS@ $(MS_STATIC)
+PHP_EXT_DIR=`$(PHPCONFIG) --extension-dir`
 
+LT_LDFLAGS=-rpath $(PHP_EXT_DIR) -module
+OBJ_SUFFIX=lo
+LINK=$(LTLD) $(LD) $(LT_LDFLAGS)
+MS_LIBS =   ../../libmapserver.la
 
 #
 # The rest of the file should not have to be edited...
@@ -77,24 +97,35 @@ MS_LIBS =   $(RUNPATHS) @MS_LIB@ @ALL_LIB@ @XTRALIBS@ $(MS_STATIC)
 
 CFLAGS112 = $(CFLAGS) $(MS_DEFINE) $(MS_INC) $(PHP_INC) $(PHP_REGEX_INC)
 
-all: php_mapscript.so
+.SUFFIXES:
+.SUFFIXES: .cpp .c .$(OBJ_SUFFIX)
+
+all: php_mapscript.la
 
-PHPMS_CLASS_OBJS =  mapscript_error.o color.o rect.o hashtable.o web.o grid.o error.o referencemap.o querymap.o outputformat.o scalebar.o label.o legend.o symbol.o style.o image.o class.o projection.o line.o shape.o shapefile.o point.o labelcache.o labelcachemember.o result.o owsrequest.o cluster.o layer.o map.o
-PHPMS_OBJS =  php_mapscript_util.o $(PHPMS_CLASS_OBJS) php_mapscript.o mapscript_i.o $(PHP_REGEX_OBJ)
+PHPMS_CLASS_OBJS =  mapscript_error.$(OBJ_SUFFIX) color.$(OBJ_SUFFIX) rect.$(OBJ_SUFFIX) hashtable.$(OBJ_SUFFIX) web.$(OBJ_SUFFIX) grid.$(OBJ_SUFFIX) error.$(OBJ_SUFFIX)\
+						  referencemap.$(OBJ_SUFFIX) querymap.$(OBJ_SUFFIX) outputformat.$(OBJ_SUFFIX) scalebar.$(OBJ_SUFFIX) label.$(OBJ_SUFFIX) legend.$(OBJ_SUFFIX)\
+						  symbol.$(OBJ_SUFFIX) style.$(OBJ_SUFFIX) image.$(OBJ_SUFFIX) class.$(OBJ_SUFFIX) projection.$(OBJ_SUFFIX) line.$(OBJ_SUFFIX) shape.$(OBJ_SUFFIX) shapefile.$(OBJ_SUFFIX)\
+						  point.$(OBJ_SUFFIX) labelcache.$(OBJ_SUFFIX) labelleader.$(OBJ_SUFFIX) labelcachemember.$(OBJ_SUFFIX) result.$(OBJ_SUFFIX) owsrequest.$(OBJ_SUFFIX) cluster.$(OBJ_SUFFIX)\
+						  layer.$(OBJ_SUFFIX) map.$(OBJ_SUFFIX)
+PHPMS_OBJS =  php_mapscript_util.$(OBJ_SUFFIX) $(PHPMS_CLASS_OBJS) php_mapscript.$(OBJ_SUFFIX) mapscript_i.$(OBJ_SUFFIX)\
+				  $(PHP_REGEX_OBJ)
 
-PHPPROJ_OBJS = php_mapscript_util.o php_proj.o $(PHP_REGEX_OBJ)
+PHPPROJ_OBJS = php_mapscript_util.$(OBJ_SUFFIX) php_proj.$(OBJ_SUFFIX) $(PHP_REGEX_OBJ)
 
 
-php_mapscript.so: $(PHPMS_OBJS) ../../libmapserver.a
-	$(LD) -o $@ $(PHPMS_OBJS) $(MS_LIBS)
+php_mapscript.la: $(PHPMS_OBJS) ../../libmapserver.la
+	$(LINK) -o $@ $(PHPMS_OBJS) $(MS_LIBS)
 
-php_proj.so:  $(PHPPROJ_OBJS)
-	$(LD) -o $@ $(PHPPROJ_OBJS) $(MS_LIBS)
+php_proj.la:  $(PHPPROJ_OBJS) ../libmapserver.la
+	$(LINK) -o $@ $(PHPPROJ_OBJS) $(MS_LIBS)
 
-%.o: %.c php_mapscript_util.h php_mapscript.h
-	$(CC) $(CFLAGS112) -c -o $@ $<
+%.lo: %.c php_mapscript_util.h php_mapscript.h
+	$(LTCC) $(CC) $(CFLAGS112) -c -o $@ $<
 
+install: php_mapscript.la
+	$(INSTALL) -d $(DESTDIR)$(PHP_EXT_DIR)
+	$(LTINSTALL) $(INSTALL) php_mapscript.la $(DESTDIR)$(PHP_EXT_DIR)
 
 clean:
-	-rm -f *.so *.o perl.out
+	-rm -rf .libs *.lo *.la *.so *.o perl.out
 
diff --git a/mapscript/php/Makefile.vc b/mapscript/php/Makefile.vc
index 439ed89..c54969a 100644
--- a/mapscript/php/Makefile.vc
+++ b/mapscript/php/Makefile.vc
@@ -56,7 +56,7 @@ MS_LIBS = $(EXTERNAL_LIBS) ../../mapserver.lib
 # The rest of the file should not have to be edited...
 #
 
-PHPMS_CLASS_OBJS =  mapscript_error.obj color.obj rect.obj hashtable.obj web.obj grid.obj error.obj referencemap.obj querymap.obj outputformat.obj scalebar.obj label.obj legend.obj symbol.obj style.obj image.obj class.obj projection.obj line.obj shape.obj shapefile.obj point.obj labelcache.obj labelcachemember.obj result.obj owsrequest.obj cluster.obj layer.obj map.obj
+PHPMS_CLASS_OBJS =  mapscript_error.obj color.obj rect.obj hashtable.obj web.obj grid.obj error.obj referencemap.obj querymap.obj outputformat.obj scalebar.obj label.obj legend.obj symbol.obj style.obj image.obj class.obj projection.obj line.obj shape.obj shapefile.obj point.obj labelcache.obj labelleader.obj labelcachemember.obj result.obj owsrequest.obj cluster.obj layer.obj map.obj
 
 PHPMS_OBJS =  php_mapscript_util.obj $(PHPMS_CLASS_OBJS) php_mapscript.obj mapscript_i.obj
 
@@ -82,7 +82,7 @@ install:	all
 $(PHPMS_DLL):	$(PHPMS_OBJS)
 	link $(LDFLAGS) /out:$(PHPMS_DLL) $(PHPMS_OBJS) $(MS_LIBS) \
 		$(PHP_HOME)\lib\$(PHP_TS_LIB_NAME)
-    if exist $(PHPMS_DLL).manifest mt -manifest $(PHPMS_DLL).manifest -outputresource:$(PHPMS_DLL);2
+	if exist $(PHPMS_DLL).manifest mt -manifest $(PHPMS_DLL).manifest -outputresource:$(PHPMS_DLL);2
 
 $(PHPPROJ_DLL):	$(PHPPROJ_OBJS)
 	link $(LDFLAGS) /out:$(PHPPROJ_DLL) $(PHPPROJ_OBJS) $(MS_LIBS) \
@@ -104,4 +104,5 @@ clean:
 	del *.pdb
 	del *.exp
 	del *.ilk
-    del *.manifest
+	del *.manifest
+
diff --git a/mapscript/php/README b/mapscript/php/README
index 86a2608..b5ab0f8 100644
--- a/mapscript/php/README
+++ b/mapscript/php/README
@@ -1,2 +1,2 @@
 Please see the PHP MapScript documentation at: 
-http://www.mapserver.org/mapscript/php/index.html
\ No newline at end of file
+http://www.mapserver.org/mapscript/php/index.html
diff --git a/mapscript/php/class.c b/mapscript/php/class.c
index 29b8a98..00367fb 100644
--- a/mapscript/php/class.c
+++ b/mapscript/php/class.c
@@ -1,33 +1,33 @@
- /**********************************************************************
- * $Id: php_mapscript.c 9765 2010-01-28 15:32:10Z aboudreault $
- *
- * Project:  MapServer
- * Purpose:  PHP/MapScript extension for MapServer.  External interface 
- *           functions
- * Author:   Daniel Morissette, DM Solutions Group (dmorissette at dmsolutions.ca)
- *           Alan Boudreault, Mapgears
- *
- **********************************************************************
- * Copyright (c) 2000-2010, Daniel Morissette, DM Solutions Group Inc.
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
- * and/or sell copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
- * all copies of this Software or works derived from this Software.
- * 
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
- * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
- * DEALINGS IN THE SOFTWARE.
- **********************************************************************/
+/**********************************************************************
+* $Id: php_mapscript.c 9765 2010-01-28 15:32:10Z aboudreault $
+*
+* Project:  MapServer
+* Purpose:  PHP/MapScript extension for MapServer.  External interface
+*           functions
+* Author:   Daniel Morissette, DM Solutions Group (dmorissette at dmsolutions.ca)
+*           Alan Boudreault, Mapgears
+*
+**********************************************************************
+* Copyright (c) 2000-2010, Daniel Morissette, DM Solutions Group Inc.
+*
+* Permission is hereby granted, free of charge, to any person obtaining a
+* copy of this software and associated documentation files (the "Software"),
+* to deal in the Software without restriction, including without limitation
+* the rights to use, copy, modify, merge, publish, distribute, sublicense,
+* and/or sell copies of the Software, and to permit persons to whom the
+* Software is furnished to do so, subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in
+* all copies of this Software or works derived from this Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+* DEALINGS IN THE SOFTWARE.
+**********************************************************************/
 
 #include "php_mapscript.h"
 
@@ -35,222 +35,333 @@ zend_class_entry *mapscript_ce_class;
 zend_object_handlers mapscript_class_object_handlers;
 
 ZEND_BEGIN_ARG_INFO_EX(class___construct_args, 0, 0, 1)
-  ZEND_ARG_OBJ_INFO(0, layer, layerObj, 0)
-  ZEND_ARG_OBJ_INFO(0, class, classObj, 0)
+ZEND_ARG_OBJ_INFO(0, layer, layerObj, 0)
+ZEND_ARG_OBJ_INFO(0, class, classObj, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(class___get_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, property)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(class___set_args, 0, 0, 2)
-  ZEND_ARG_INFO(0, property)
-  ZEND_ARG_INFO(0, value)
+ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, value)
+ZEND_END_ARG_INFO()
+
+ZEND_BEGIN_ARG_INFO_EX(class_addLabel_args, 0, 0, 1)
+ZEND_ARG_OBJ_INFO(0, label, labelObj, 0)
+ZEND_END_ARG_INFO()
+
+ZEND_BEGIN_ARG_INFO_EX(class_removeLabel_args, 0, 0, 1)
+ZEND_ARG_INFO(0, index)
+ZEND_END_ARG_INFO()
+
+ZEND_BEGIN_ARG_INFO_EX(class_getLabel_args, 0, 0, 1)
+ZEND_ARG_INFO(0, index)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(class_updateFromString_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, snippet)
+ZEND_ARG_INFO(0, snippet)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(class_setExpression_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, expression)
+ZEND_ARG_INFO(0, expression)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(class_setText_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, text)
+ZEND_ARG_INFO(0, text)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(class_getStyle_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, index)
+ZEND_ARG_INFO(0, index)
+ZEND_END_ARG_INFO()
+
+ZEND_BEGIN_ARG_INFO_EX(class_insertStyle_args, 0, 0, 1)
+ZEND_ARG_OBJ_INFO(0, style, styleObj, 0)
+ZEND_ARG_INFO(0, index)
+ZEND_END_ARG_INFO()
+
+ZEND_BEGIN_ARG_INFO_EX(class_removeStyle_args, 0, 0, 1)
+ZEND_ARG_INFO(0, index)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(class_moveStyleUp_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, index)
+ZEND_ARG_INFO(0, index)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(class_moveStyleDown_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, index)
+ZEND_ARG_INFO(0, index)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(class_deleteStyle_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, index)
+ZEND_ARG_INFO(0, index)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(class_getMetaData_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, name)
+ZEND_ARG_INFO(0, name)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(class_setMetaData_args, 0, 0, 2)
-  ZEND_ARG_INFO(0, name)
-  ZEND_ARG_INFO(0, value)
+ZEND_ARG_INFO(0, name)
+ZEND_ARG_INFO(0, value)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(class_removeMetaData_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, name)
+ZEND_ARG_INFO(0, name)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(class_createLegendIcon_args, 0, 0, 2)
-  ZEND_ARG_INFO(0, width)
-  ZEND_ARG_INFO(0, height)
+ZEND_ARG_INFO(0, width)
+ZEND_ARG_INFO(0, height)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(class_drawLegendIcon_args, 0, 0, 5)
-  ZEND_ARG_INFO(0, width)
-  ZEND_ARG_INFO(0, height)
-  ZEND_ARG_OBJ_INFO(0, image, imageObj, 0)
-  ZEND_ARG_INFO(0, dstX)
-  ZEND_ARG_INFO(0, dstY)
+ZEND_ARG_INFO(0, width)
+ZEND_ARG_INFO(0, height)
+ZEND_ARG_OBJ_INFO(0, image, imageObj, 0)
+ZEND_ARG_INFO(0, dstX)
+ZEND_ARG_INFO(0, dstY)
 ZEND_END_ARG_INFO()
 
 /* {{{ proto void __construct(layerObj layer [, classObj class])
    Create a new class instance in the specified layer.. */
 PHP_METHOD(classObj, __construct)
 {
-    zval *zobj = getThis();
-    zval *zlayer, *zclass = NULL;
-    classObj *class;
-    php_layer_object *php_layer;
-    php_class_object *php_class, *php_class2;
-    parent_object parent;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O|O",
-                              &zlayer, mapscript_ce_layer,
-                              &zclass, mapscript_ce_class) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  zval *zlayer, *zclass = NULL;
+  classObj *class;
+  php_layer_object *php_layer;
+  php_class_object *php_class, *php_class2;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O|O",
+                            &zlayer, mapscript_ce_layer,
+                            &zclass, mapscript_ce_class) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_class = (php_class_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_layer = (php_layer_object *) zend_object_store_get_object(zlayer TSRMLS_CC);
-    if (zclass)
-        php_class2 = (php_class_object *) zend_object_store_get_object(zclass TSRMLS_CC);
-
-
-    if ((class = classObj_new(php_layer->layer, (zclass ? php_class2->class:NULL))) == NULL)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
-
-    php_class->class = class;
-    
-    MAPSCRIPT_MAKE_PARENT(zlayer,NULL);
-    php_class->parent = parent;
-    MAPSCRIPT_ADDREF(parent.val);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_class = (php_class_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_layer = (php_layer_object *) zend_object_store_get_object(zlayer TSRMLS_CC);
+  if (zclass)
+    php_class2 = (php_class_object *) zend_object_store_get_object(zclass TSRMLS_CC);
+
+
+  if ((class = classObj_new(php_layer->layer, (zclass ? php_class2->class:NULL))) == NULL) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
+
+  php_class->class = class;
+
+  MAPSCRIPT_MAKE_PARENT(zlayer,NULL);
+  php_class->parent = parent;
+  MAPSCRIPT_ADDREF(parent.val);
 }
 /* }}} */
 
 PHP_METHOD(classObj, __get)
 {
-    char *property;
-    long property_len;
-    zval *zobj = getThis();
-    php_class_object *php_class;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &property, &property_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *zobj = getThis();
+  php_class_object *php_class;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &property, &property_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_class = (php_class_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-
-    IF_GET_STRING("name", php_class->class->name)
-    else IF_GET_STRING("title", php_class->class->title)
-    else IF_GET_LONG("type", php_class->class->type) 
-    else IF_GET_LONG("status", php_class->class->status) 
-    else IF_GET_DOUBLE("minscaledenom", php_class->class->minscaledenom) 
-    else IF_GET_DOUBLE("maxscaledenom", php_class->class->maxscaledenom) 
-    else IF_GET_LONG("minfeaturesize", php_class->class->minfeaturesize) 
-    else IF_GET_STRING("template", php_class->class->template)
-    else IF_GET_STRING("keyimage", php_class->class->keyimage)
-    else IF_GET_STRING("group", php_class->class->group)
-    else IF_GET_LONG("numstyles", php_class->class->numstyles) 
-    else IF_GET_OBJECT("label", mapscript_ce_label, php_class->label, &php_class->class->label) 
-    else IF_GET_OBJECT("metadata", mapscript_ce_hashtable, php_class->metadata, &php_class->class->metadata) 
-    else 
-    {
-        mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_class = (php_class_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  IF_GET_STRING("name", php_class->class->name)
+  else IF_GET_STRING("title", php_class->class->title)
+    else IF_GET_LONG("type", php_class->class->type)
+      else IF_GET_LONG("status", php_class->class->status)
+        else IF_GET_DOUBLE("minscaledenom", php_class->class->minscaledenom)
+          else IF_GET_DOUBLE("maxscaledenom", php_class->class->maxscaledenom)
+            else IF_GET_LONG("minfeaturesize", php_class->class->minfeaturesize)
+              else IF_GET_LONG("numlabels", php_class->class->numlabels)
+                else IF_GET_STRING("template", php_class->class->template)
+                  else IF_GET_STRING("keyimage", php_class->class->keyimage)
+                    else IF_GET_STRING("group", php_class->class->group)
+                      else IF_GET_LONG("numstyles", php_class->class->numstyles)
+                        else IF_GET_OBJECT("metadata", mapscript_ce_hashtable, php_class->metadata, &php_class->class->metadata)
+                          else IF_GET_OBJECT("leader", mapscript_ce_labelleader, php_class->leader, &php_class->class->leader)
+                            else {
+                              mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+                            }
 }
 
 PHP_METHOD(classObj, __set)
 {
-    char *property;
-    long property_len;
-    zval *value;
-    zval *zobj = getThis();
-    php_class_object *php_class;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
-                              &property, &property_len, &value) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *value;
+  zval *zobj = getThis();
+  php_class_object *php_class;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
+                            &property, &property_len, &value) == FAILURE) {
+    PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_class = (php_class_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  /* special case for "template" which we want to set to NULL and not an empty string */
+  if(Z_TYPE_P(value)==IS_NULL && !strcmp(property,"template")) {
+    msFree(php_class->class->template);
+    php_class->class->template = NULL;
+  } else
+  IF_SET_STRING("name", php_class->class->name, value)
+  else IF_SET_STRING("title", php_class->class->title, value)
+    else IF_SET_LONG("type", php_class->class->type, value)
+      else IF_SET_LONG("status", php_class->class->status, value)
+        else IF_SET_DOUBLE("minscaledenom", php_class->class->minscaledenom, value)
+          else IF_SET_DOUBLE("maxscaledenom", php_class->class->maxscaledenom, value)
+            else IF_SET_LONG("minfeaturesize", php_class->class->minfeaturesize, value)
+              else IF_SET_STRING("template", php_class->class->template, value)
+                else IF_SET_STRING("keyimage", php_class->class->keyimage, value)
+                  else IF_SET_STRING("group", php_class->class->group, value)
+                    else if ( (STRING_EQUAL("metadata", property)) ||
+                              (STRING_EQUAL("leader", property)) ) {
+                      mapscript_throw_exception("Property '%s' is an object and can only be modified through its accessors." TSRMLS_CC, property);
+                    } else if ( (STRING_EQUAL("numstyles", property)) ||
+                                (STRING_EQUAL("numstyles", property)) ) {
+                      mapscript_throw_exception("Property '%s' is read-only and cannot be set." TSRMLS_CC, property);
+                    } else {
+                      mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+                    }
+}
+
+/* {{{ proto int addLabel(labelObj *label)
+   Add a label to the class.  Returns MS_SUCCESS/MS_FAILURE */
+PHP_METHOD(classObj, addLabel)
+{
+  zval *zobj = getThis();
+  zval *zlabel;
+  php_class_object *php_class;
+  php_label_object *php_label;
+  int status = MS_FAILURE;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
+                            &zlabel, mapscript_ce_label) == FAILURE) {
+    PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_class = (php_class_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_label = (php_label_object *) zend_object_store_get_object(zlabel TSRMLS_CC);
+
+  status = classObj_addLabel(php_class->class, php_label->label);
+  php_label->is_ref = 1;
+
+  RETURN_LONG(status);
+}
+/* }}} */
+
+/* {{{ proto int removeLabel(int index)
+   Removes the label indicated and returns a copy, or NULL in the case of a
+   failure. */
+PHP_METHOD(classObj, removeLabel)
+{
+  zval *zobj = getThis();
+  long index;
+  labelObj *label;
+  php_class_object *php_class;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
+                            &index) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_class = (php_class_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-
-    IF_SET_STRING("name", php_class->class->name, value)
-    else IF_SET_STRING("title", php_class->class->title, value)
-    else IF_SET_LONG("type", php_class->class->type, value) 
-    else IF_SET_LONG("status", php_class->class->status, value) 
-    else IF_SET_DOUBLE("minscaledenom", php_class->class->minscaledenom, value) 
-    else IF_SET_DOUBLE("maxscaledenom", php_class->class->maxscaledenom, value) 
-    else IF_SET_LONG("minfeaturesize", php_class->class->minfeaturesize, value) 
-    else IF_SET_STRING("template", php_class->class->template, value)
-    else IF_SET_STRING("keyimage", php_class->class->keyimage, value)
-    else IF_SET_STRING("group", php_class->class->group, value)
-    else if ( (STRING_EQUAL("label", property)) ||
-              (STRING_EQUAL("metadata", property)))
-    {
-        mapscript_throw_exception("Property '%s' is an object and can only be modified through its accessors." TSRMLS_CC, property);
-    }
-    else if (STRING_EQUAL("numstyles", property))
-    {
-        mapscript_throw_exception("Property '%s' is read-only and cannot be set." TSRMLS_CC, property);
-    }
-    else 
-    {
-        mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_class = (php_class_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  if ((label = classObj_removeLabel(php_class->class, index)) == NULL) {
+    mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
+    RETURN_NULL();
+  }
+
+  /* Return a copy of the class object just removed */
+  MAPSCRIPT_MAKE_PARENT(NULL, NULL);
+  mapscript_create_label(label, parent, return_value TSRMLS_CC);
 }
+/* }}} */
+
+/* {{{ proto int class.getLabel(int i)
+   Returns a labelObj from the class given an index value (0=first label) */
+PHP_METHOD(classObj, getLabel)
+{
+  zval *zobj = getThis();
+  long index;
+  labelObj *label = NULL;
+  php_class_object *php_class;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
+                            &index) == FAILURE) {
+    PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_class = (php_class_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  if ((label = classObj_getLabel(php_class->class, index)) == NULL) {
+    mapscript_throw_exception("Invalid label index." TSRMLS_CC);
+    return;
+  }
+
+  /* Return class object */
+  MAPSCRIPT_MAKE_PARENT(zobj, NULL);
+  mapscript_create_label(label, parent, return_value TSRMLS_CC);
+}
+/* }}} */
 
 /* {{{ proto int updateFromString(string snippet)
    Update a class from a string snippet.  Returns MS_SUCCESS/MS_FAILURE */
 PHP_METHOD(classObj, updateFromString)
 {
-    char *snippet;
-    long snippet_len;
-    zval *zobj = getThis();
-    php_class_object *php_class;
-    int status = MS_FAILURE;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &snippet, &snippet_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *snippet;
+  long snippet_len;
+  zval *zobj = getThis();
+  php_class_object *php_class;
+  int status = MS_FAILURE;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &snippet, &snippet_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_class = (php_class_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_class = (php_class_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    status = classObj_updateFromString(php_class->class, snippet);
-    
-    if (status != MS_SUCCESS)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
+  status = classObj_updateFromString(php_class->class, snippet);
 
+  if (status != MS_SUCCESS) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
 
-    RETURN_LONG(status);
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -258,32 +369,31 @@ PHP_METHOD(classObj, updateFromString)
    Set the expression string for a class object. */
 PHP_METHOD(classObj, setExpression)
 {
-    char *expression;
-    long expression_len;
-    zval *zobj = getThis();
-    php_class_object *php_class;
-    int status = MS_FAILURE;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &expression, &expression_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *expression;
+  long expression_len;
+  zval *zobj = getThis();
+  php_class_object *php_class;
+  int status = MS_FAILURE;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &expression, &expression_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_class = (php_class_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_class = (php_class_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    status = classObj_setExpression(php_class->class, expression);
-    
-    if (status != MS_SUCCESS)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
+  status = classObj_setExpression(php_class->class, expression);
 
+  if (status != MS_SUCCESS) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
 
-    RETURN_LONG(status);
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -291,26 +401,26 @@ PHP_METHOD(classObj, setExpression)
    Get the expression string for a class object. */
 PHP_METHOD(classObj, getExpressionString)
 {
-    zval *zobj = getThis();
-    php_class_object *php_class;
-    char *value = NULL;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  php_class_object *php_class;
+  char *value = NULL;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_class = (php_class_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_class = (php_class_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    value = classObj_getExpressionString(php_class->class);
-    
-    if (value == NULL)
-        RETURN_STRING("", 1);
+  value = classObj_getExpressionString(php_class->class);
 
-    RETVAL_STRING(value, 1);
-    free(value);
+  if (value == NULL)
+    RETURN_STRING("", 1);
+
+  RETVAL_STRING(value, 1);
+  free(value);
 }
 /* }}} */
 
@@ -318,34 +428,33 @@ PHP_METHOD(classObj, getExpressionString)
    Set the text string for a class object. */
 PHP_METHOD(classObj, setText)
 {
-    char *text;
-    long text_len;
-    zval *zobj = getThis();
-    php_class_object *php_class;
-    php_layer_object *php_layer;
-    int status = MS_FAILURE;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &text, &text_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *text;
+  long text_len;
+  zval *zobj = getThis();
+  php_class_object *php_class;
+  php_layer_object *php_layer;
+  int status = MS_FAILURE;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &text, &text_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_class = (php_class_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_layer = (php_layer_object *) zend_object_store_get_object(php_class->parent.val TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_class = (php_class_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_layer = (php_layer_object *) zend_object_store_get_object(php_class->parent.val TSRMLS_CC);
+
+  status = classObj_setText(php_class->class, php_layer->layer, text);
 
-    status = classObj_setText(php_class->class, php_layer->layer, text);
-    
-    if (status != MS_SUCCESS)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
+  if (status != MS_SUCCESS) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
 
 
-    RETURN_LONG(status);
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -353,59 +462,111 @@ PHP_METHOD(classObj, setText)
    Get the text string for a class object. */
 PHP_METHOD(classObj, getTextString)
 {
-    zval *zobj = getThis();
-    php_class_object *php_class;
-    char *value = NULL;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  php_class_object *php_class;
+  char *value = NULL;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_class = (php_class_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_class = (php_class_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  value =  classObj_getTextString(php_class->class);
 
-    value =  classObj_getTextString(php_class->class);
-    
-    if (value == NULL)
-        RETURN_STRING("", 1);
+  if (value == NULL)
+    RETURN_STRING("", 1);
 
-    RETVAL_STRING(value, 1);
-    free(value);
+  RETVAL_STRING(value, 1);
+  free(value);
 }
 /* }}} */
 
-/* {{{ proto int getstyle(int index)
+/* {{{ proto styleObj getstyle(int index)
    return the style object. */
 PHP_METHOD(classObj, getStyle)
 {
-    long index;
-    zval *zobj = getThis();
-    php_class_object *php_class;
-    styleObj *style = NULL;
-    parent_object parent;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
-                              &index) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  long index;
+  zval *zobj = getThis();
+  php_class_object *php_class;
+  styleObj *style = NULL;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
+                            &index) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_class = (php_class_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-
-    if (index < 0 || index >= php_class->class->numstyles)
-    {
-        mapscript_throw_exception("Invalid style index." TSRMLS_CC);
-        return;
-    }
-    
-    style = php_class->class->styles[index];
-
-    MAPSCRIPT_MAKE_PARENT(zobj, NULL);
-    mapscript_create_style(style, parent, return_value TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_class = (php_class_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  if (index < 0 || index >= php_class->class->numstyles) {
+    mapscript_throw_exception("Invalid style index." TSRMLS_CC);
+    return;
+  }
+
+  style = php_class->class->styles[index];
+
+  MAPSCRIPT_MAKE_PARENT(zobj, NULL);
+  mapscript_create_style(style, parent, return_value TSRMLS_CC);
+}
+/* }}} */
+
+/* {{{ proto int insertStyle(styleObj style)
+   return MS_SUCCESS or MS_FAILURE. */
+PHP_METHOD(classObj, insertStyle)
+{
+  zval *zobj = getThis();
+  zval *zstyle = NULL;
+  long index = -1;
+  php_class_object *php_class;
+  php_style_object *php_style;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O|l",
+                            &zstyle, mapscript_ce_style, &index) == FAILURE) {
+    PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_class = (php_class_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_style = (php_style_object *) zend_object_store_get_object(zstyle TSRMLS_CC);
+
+  RETURN_LONG(msInsertStyle(php_class->class, php_style->style, index));
+}
+/* }}} */
+
+/* {{{ proto styleObj removeStyle(int index)
+   return the styleObj removed. */
+PHP_METHOD(classObj, removeStyle)
+{
+  zval *zobj = getThis();
+  long index;
+  styleObj *style;
+  php_class_object *php_class;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
+                            &index) == FAILURE) {
+    PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_class = (php_class_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  style = msRemoveStyle(php_class->class, index);
+
+  /* Return a copy of the class object just removed */
+  MAPSCRIPT_MAKE_PARENT(NULL, NULL);
+  mapscript_create_style(style, parent, return_value TSRMLS_CC);
 }
 /* }}} */
 
@@ -416,24 +577,24 @@ PHP_METHOD(classObj, getStyle)
    position 1. */
 PHP_METHOD(classObj, moveStyleUp)
 {
-    long index;
-    zval *zobj = getThis();
-    php_class_object *php_class;
-    int status = MS_FAILURE;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
-                              &index) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  long index;
+  zval *zobj = getThis();
+  php_class_object *php_class;
+  int status = MS_FAILURE;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
+                            &index) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_class = (php_class_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_class = (php_class_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    status = classObj_moveStyleUp(php_class->class, index);
+  status = classObj_moveStyleUp(php_class->class, index);
 
-    RETURN_LONG(status);
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -444,50 +605,50 @@ PHP_METHOD(classObj, moveStyleUp)
    will be moved to position 0. */
 PHP_METHOD(classObj, moveStyleDown)
 {
-    long index;
-    zval *zobj = getThis();
-    php_class_object *php_class;
-    int status = MS_FAILURE;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
-                              &index) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  long index;
+  zval *zobj = getThis();
+  php_class_object *php_class;
+  int status = MS_FAILURE;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
+                            &index) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_class = (php_class_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    status = classObj_moveStyleDown(php_class->class, index);
+  php_class = (php_class_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    RETURN_LONG(status);
+  status = classObj_moveStyleDown(php_class->class, index);
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
- /* {{{ proto int deleteStyle(int index) Delete the style specified
-    by the style index. If there are any style that follow the deleted
-  style, their index will decrease by 1. */
+/* {{{ proto int deleteStyle(int index) Delete the style specified
+   by the style index. If there are any style that follow the deleted
+ style, their index will decrease by 1. */
 PHP_METHOD(classObj, deleteStyle)
 {
-    long index;
-    zval *zobj = getThis();
-    php_class_object *php_class;
-    int status = MS_FAILURE;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
-                              &index) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  long index;
+  zval *zobj = getThis();
+  php_class_object *php_class;
+  int status = MS_FAILURE;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
+                            &index) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_class = (php_class_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_class = (php_class_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    status =  classObj_deleteStyle(php_class->class, index);
+  status =  classObj_deleteStyle(php_class->class, index);
 
-    RETURN_LONG(status);
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -495,25 +656,25 @@ PHP_METHOD(classObj, deleteStyle)
    Return MetaData entry by name, or empty string if not found. */
 PHP_METHOD(classObj, getMetaData)
 {
-    zval *zname;
-    zval *zobj = getThis();
-    php_class_object *php_class;
-    zval *retval;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z",
-                              &zname) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zname;
+  zval *zobj = getThis();
+  php_class_object *php_class;
+  zval *retval;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z",
+                            &zname) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_class = (php_class_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    CHECK_OBJECT(mapscript_ce_hashtable, php_class->metadata, &php_class->class->metadata);
-    
-    MAPSCRIPT_CALL_METHOD_1(php_class->metadata, "get", retval, zname);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    RETURN_STRING(Z_STRVAL_P(retval),1);
+  php_class = (php_class_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  CHECK_OBJECT(mapscript_ce_hashtable, php_class->metadata, &php_class->class->metadata);
+
+  MAPSCRIPT_CALL_METHOD_1(php_class->metadata, "get", retval, zname);
+
+  RETURN_STRING(Z_STRVAL_P(retval),1);
 }
 /* }}} */
 
@@ -521,25 +682,25 @@ PHP_METHOD(classObj, getMetaData)
    Set MetaData entry by name.  Returns MS_SUCCESS/MS_FAILURE */
 PHP_METHOD(classObj, setMetaData)
 {
-    zval *zname, *zvalue;
-    zval *zobj = getThis();
-    php_class_object *php_class;
-    zval *retval;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz",
-                              &zname, &zvalue) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zname, *zvalue;
+  zval *zobj = getThis();
+  php_class_object *php_class;
+  zval *retval;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz",
+                            &zname, &zvalue) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_class = (php_class_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    CHECK_OBJECT(mapscript_ce_hashtable, php_class->metadata, &php_class->class->metadata);
-    
-    MAPSCRIPT_CALL_METHOD_2(php_class->metadata, "set", retval, zname, zvalue);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_class = (php_class_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  CHECK_OBJECT(mapscript_ce_hashtable, php_class->metadata, &php_class->class->metadata);
 
-    RETURN_LONG(Z_LVAL_P(retval));
+  MAPSCRIPT_CALL_METHOD_2(php_class->metadata, "set", retval, zname, zvalue);
+
+  RETURN_LONG(Z_LVAL_P(retval));
 }
 /* }}} */
 
@@ -547,25 +708,25 @@ PHP_METHOD(classObj, setMetaData)
    Remove MetaData entry by name.  Returns MS_SUCCESS/MS_FAILURE */
 PHP_METHOD(classObj, removeMetaData)
 {
-    zval *zname;
-    zval *zobj = getThis();
-    php_class_object *php_class;
-    zval *retval;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z",
-                              &zname) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zname;
+  zval *zobj = getThis();
+  php_class_object *php_class;
+  zval *retval;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z",
+                            &zname) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_class = (php_class_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    CHECK_OBJECT(mapscript_ce_hashtable, php_class->metadata, &php_class->class->metadata);
-    
-    MAPSCRIPT_CALL_METHOD_1(php_class->metadata, "remove", retval, zname);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_class = (php_class_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  CHECK_OBJECT(mapscript_ce_hashtable, php_class->metadata, &php_class->class->metadata);
 
-    RETURN_LONG(Z_LVAL_P(retval));
+  MAPSCRIPT_CALL_METHOD_1(php_class->metadata, "remove", retval, zname);
+
+  RETURN_LONG(Z_LVAL_P(retval));
 }
 /* }}} */
 
@@ -573,43 +734,41 @@ PHP_METHOD(classObj, removeMetaData)
    Return the legend icon. */
 PHP_METHOD(classObj, createLegendIcon)
 {
-    zval *zobj = getThis();
-    long width, height;
-    imageObj *image = NULL;
-    php_class_object *php_class;
-    php_layer_object *php_layer;
-    php_map_object *php_map;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ll",
-                              &width, &height) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  long width, height;
+  imageObj *image = NULL;
+  php_class_object *php_class;
+  php_layer_object *php_layer;
+  php_map_object *php_map;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ll",
+                            &width, &height) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_class = (php_class_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_layer = (php_layer_object *) zend_object_store_get_object(php_class->parent.val TSRMLS_CC);
-    
-    if (!php_layer->parent.val)
-    {
-        mapscript_throw_exception("No map object associated with this class object." TSRMLS_CC);
-        return;
-    }
-
-    php_map = (php_map_object *) zend_object_store_get_object(php_layer->parent.val TSRMLS_CC);
-
-    if ((image = classObj_createLegendIcon(php_class->class,
-                                           php_map->map, 
-                                           php_layer->layer, 
-                                           width, height)) == NULL)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
-    
-    /* Return an image object */
-    mapscript_create_image(image, return_value TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_class = (php_class_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_layer = (php_layer_object *) zend_object_store_get_object(php_class->parent.val TSRMLS_CC);
+
+  if (!php_layer->parent.val) {
+    mapscript_throw_exception("No map object associated with this class object." TSRMLS_CC);
+    return;
+  }
+
+  php_map = (php_map_object *) zend_object_store_get_object(php_layer->parent.val TSRMLS_CC);
+
+  if ((image = classObj_createLegendIcon(php_class->class,
+                                         php_map->map,
+                                         php_layer->layer,
+                                         width, height)) == NULL) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
+
+  /* Return an image object */
+  mapscript_create_image(image, return_value TSRMLS_CC);
 }
 /* }}} */
 
@@ -617,56 +776,53 @@ PHP_METHOD(classObj, createLegendIcon)
    set the lengend icon in img. */
 PHP_METHOD(classObj, drawLegendIcon)
 {
-    zval *zobj = getThis();
-    zval *zimage;
-    long width, height, dstX, dstY;
-    int status = MS_FAILURE;
-    php_class_object *php_class;
-    php_image_object *php_image;
-    php_layer_object *php_layer;
-    php_map_object *php_map;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "llOll",
-                              &width, &height,
-                              &zimage, mapscript_ce_image,
-                              &dstX, &dstY) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  zval *zimage;
+  long width, height, dstX, dstY;
+  int status = MS_FAILURE;
+  php_class_object *php_class;
+  php_image_object *php_image;
+  php_layer_object *php_layer;
+  php_map_object *php_map;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "llOll",
+                            &width, &height,
+                            &zimage, mapscript_ce_image,
+                            &dstX, &dstY) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_class = (php_class_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_image = (php_image_object *) zend_object_store_get_object(zimage TSRMLS_CC);
-    php_layer = (php_layer_object *) zend_object_store_get_object(php_class->parent.val TSRMLS_CC);
-    
-
-    if (!php_layer->parent.val)
-    {
-        mapscript_throw_exception("No map object associated with this class object." TSRMLS_CC);
-        return;
-    }
-
-    php_map = (php_map_object *) zend_object_store_get_object(php_layer->parent.val TSRMLS_CC);
-
-    if (!MS_RENDERER_PLUGIN(php_image->image->format))
-    {
-        mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
-        mapscript_report_php_error(E_WARNING, "DrawLegendicon function is only available for renderer plugin drivers" TSRMLS_CC);
-        RETURN_LONG(MS_FAILURE);
-    }
-
-    if ((status = classObj_drawLegendIcon(php_class->class, 
-                                          php_map->map, 
-                                          php_layer->layer, 
-                                          width, height, 
-                                          php_image->image, 
-                                          dstX, dstY)) != MS_SUCCESS)
-    {
-        mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
-    }
-   
-    RETURN_LONG(status);       
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_class = (php_class_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_image = (php_image_object *) zend_object_store_get_object(zimage TSRMLS_CC);
+  php_layer = (php_layer_object *) zend_object_store_get_object(php_class->parent.val TSRMLS_CC);
+
+
+  if (!php_layer->parent.val) {
+    mapscript_throw_exception("No map object associated with this class object." TSRMLS_CC);
+    return;
+  }
+
+  php_map = (php_map_object *) zend_object_store_get_object(php_layer->parent.val TSRMLS_CC);
+
+  if (!MS_RENDERER_PLUGIN(php_image->image->format)) {
+    mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
+    mapscript_report_php_error(E_WARNING, "DrawLegendicon function is only available for renderer plugin drivers" TSRMLS_CC);
+    RETURN_LONG(MS_FAILURE);
+  }
+
+  if ((status = classObj_drawLegendIcon(php_class->class,
+                                        php_map->map,
+                                        php_layer->layer,
+                                        width, height,
+                                        php_image->image,
+                                        dstX, dstY)) != MS_SUCCESS) {
+    mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
+  }
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -674,130 +830,135 @@ PHP_METHOD(classObj, drawLegendIcon)
    Free the object */
 PHP_METHOD(classObj, free)
 {
-    zval *zobj = getThis();
-    php_class_object *php_class;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  php_class_object *php_class;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_class = (php_class_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_class = (php_class_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    MAPSCRIPT_DELREF(php_class->label);
-    MAPSCRIPT_DELREF(php_class->metadata);
+  MAPSCRIPT_DELREF(php_class->metadata);
 }
 /* }}} */
 
 zend_function_entry class_functions[] = {
-    PHP_ME(classObj, __construct, class___construct_args, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
-    PHP_ME(classObj, __get, class___get_args, ZEND_ACC_PUBLIC)
-    PHP_ME(classObj, __set, class___set_args, ZEND_ACC_PUBLIC)
-    PHP_MALIAS(classObj, set, __set, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(classObj, updateFromString, class_updateFromString_args, ZEND_ACC_PUBLIC)
-    PHP_ME(classObj, setExpression, class_setExpression_args, ZEND_ACC_PUBLIC)
-    PHP_ME(classObj, getExpressionString, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(classObj, setText, class_setText_args, ZEND_ACC_PUBLIC)
-    PHP_ME(classObj, getTextString, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(classObj, getStyle, class_getStyle_args, ZEND_ACC_PUBLIC)
-    PHP_ME(classObj, moveStyleUp, class_moveStyleUp_args, ZEND_ACC_PUBLIC)
-    PHP_ME(classObj, moveStyleDown, class_moveStyleDown_args, ZEND_ACC_PUBLIC)
-    PHP_ME(classObj, deleteStyle, class_deleteStyle_args, ZEND_ACC_PUBLIC)
-    PHP_ME(classObj, getMetaData, class_getMetaData_args, ZEND_ACC_PUBLIC)
-    PHP_ME(classObj, setMetaData, class_setMetaData_args, ZEND_ACC_PUBLIC)
-    PHP_ME(classObj, removeMetaData, class_removeMetaData_args, ZEND_ACC_PUBLIC)
-    PHP_ME(classObj, createLegendIcon, class_createLegendIcon_args, ZEND_ACC_PUBLIC)
-    PHP_ME(classObj, drawLegendIcon, class_drawLegendIcon_args, ZEND_ACC_PUBLIC)
-    PHP_ME(classObj, free, NULL, ZEND_ACC_PUBLIC)
-    {NULL, NULL, NULL}
+  PHP_ME(classObj, __construct, class___construct_args, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
+  PHP_ME(classObj, __get, class___get_args, ZEND_ACC_PUBLIC)
+  PHP_ME(classObj, __set, class___set_args, ZEND_ACC_PUBLIC)
+  PHP_MALIAS(classObj, set, __set, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(classObj, addLabel, class_addLabel_args, ZEND_ACC_PUBLIC)
+  PHP_ME(classObj, removeLabel, class_removeLabel_args, ZEND_ACC_PUBLIC)
+  PHP_ME(classObj, getLabel, class_getLabel_args, ZEND_ACC_PUBLIC)
+  PHP_ME(classObj, updateFromString, class_updateFromString_args, ZEND_ACC_PUBLIC)
+  PHP_ME(classObj, setExpression, class_setExpression_args, ZEND_ACC_PUBLIC)
+  PHP_ME(classObj, getExpressionString, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(classObj, setText, class_setText_args, ZEND_ACC_PUBLIC)
+  PHP_ME(classObj, getTextString, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(classObj, getStyle, class_getStyle_args, ZEND_ACC_PUBLIC)
+  PHP_ME(classObj, insertStyle, class_insertStyle_args, ZEND_ACC_PUBLIC)
+  PHP_ME(classObj, removeStyle, class_removeStyle_args, ZEND_ACC_PUBLIC)
+  PHP_ME(classObj, moveStyleUp, class_moveStyleUp_args, ZEND_ACC_PUBLIC)
+  PHP_ME(classObj, moveStyleDown, class_moveStyleDown_args, ZEND_ACC_PUBLIC)
+  PHP_ME(classObj, deleteStyle, class_deleteStyle_args, ZEND_ACC_PUBLIC)
+  PHP_ME(classObj, getMetaData, class_getMetaData_args, ZEND_ACC_PUBLIC)
+  PHP_ME(classObj, setMetaData, class_setMetaData_args, ZEND_ACC_PUBLIC)
+  PHP_ME(classObj, removeMetaData, class_removeMetaData_args, ZEND_ACC_PUBLIC)
+  PHP_ME(classObj, createLegendIcon, class_createLegendIcon_args, ZEND_ACC_PUBLIC)
+  PHP_ME(classObj, drawLegendIcon, class_drawLegendIcon_args, ZEND_ACC_PUBLIC)
+  PHP_ME(classObj, free, NULL, ZEND_ACC_PUBLIC) {
+    NULL, NULL, NULL
+  }
 };
 
 void mapscript_create_class(classObj *class, parent_object parent, zval *return_value TSRMLS_DC)
 {
-    php_class_object * php_class;
-    object_init_ex(return_value, mapscript_ce_class); 
-    php_class = (php_class_object *)zend_object_store_get_object(return_value TSRMLS_CC);
-    php_class->class = class;
+  php_class_object * php_class;
+  object_init_ex(return_value, mapscript_ce_class);
+  php_class = (php_class_object *)zend_object_store_get_object(return_value TSRMLS_CC);
+  php_class->class = class;
 
-    php_class->parent = parent;
-    MAPSCRIPT_ADDREF(parent.val);
+  php_class->parent = parent;
+  MAPSCRIPT_ADDREF(parent.val);
 }
 
 static void mapscript_class_object_destroy(void *object TSRMLS_DC)
 {
-    php_class_object *php_class = (php_class_object *)object;
+  php_class_object *php_class = (php_class_object *)object;
 
-    MAPSCRIPT_FREE_OBJECT(php_class);
+  MAPSCRIPT_FREE_OBJECT(php_class);
 
-    MAPSCRIPT_FREE_PARENT(php_class->parent);
+  MAPSCRIPT_FREE_PARENT(php_class->parent);
 
-    MAPSCRIPT_DELREF(php_class->label);
-    MAPSCRIPT_DELREF(php_class->metadata);
+  MAPSCRIPT_DELREF(php_class->metadata);
+  MAPSCRIPT_DELREF(php_class->leader);
 
-    /* We don't need to free the classObj */ 
-    
-    efree(object);
+  /* We don't need to free the classObj */
+
+  efree(object);
 }
 
 static zend_object_value mapscript_class_object_new_ex(zend_class_entry *ce, php_class_object **ptr TSRMLS_DC)
 {
-    zend_object_value retval;
-    php_class_object *php_class;
+  zend_object_value retval;
+  php_class_object *php_class;
 
-    MAPSCRIPT_ALLOC_OBJECT(php_class, php_class_object);
+  MAPSCRIPT_ALLOC_OBJECT(php_class, php_class_object);
 
-    retval = mapscript_object_new_ex(&php_class->std, ce,
-                                     &mapscript_class_object_destroy,
-                                     &mapscript_class_object_handlers TSRMLS_CC);
+  retval = mapscript_object_new_ex(&php_class->std, ce,
+                                   &mapscript_class_object_destroy,
+                                   &mapscript_class_object_handlers TSRMLS_CC);
 
-    if (ptr)
-        *ptr = php_class;
+  if (ptr)
+    *ptr = php_class;
 
-    MAPSCRIPT_INIT_PARENT(php_class->parent);
+  MAPSCRIPT_INIT_PARENT(php_class->parent);
 
-    php_class->label = NULL;
-    php_class->metadata = NULL;
+  php_class->metadata = NULL;
+  php_class->leader = NULL;
 
-    return retval;
+  return retval;
 }
 
 static zend_object_value mapscript_class_object_new(zend_class_entry *ce TSRMLS_DC)
 {
-    return mapscript_class_object_new_ex(ce, NULL TSRMLS_CC);
+  return mapscript_class_object_new_ex(ce, NULL TSRMLS_CC);
 }
 
 static zend_object_value mapscript_class_object_clone(zval *zobj TSRMLS_DC)
 {
-    php_class_object *php_class_old, *php_class_new;
-    php_layer_object *php_layer;
-    zend_object_value new_ov;
+  php_class_object *php_class_old, *php_class_new;
+  php_layer_object *php_layer;
+  zend_object_value new_ov;
 
-    php_class_old = (php_class_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_layer = (php_layer_object *) zend_object_store_get_object(php_class_old->parent.val TSRMLS_CC);
+  php_class_old = (php_class_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_layer = (php_layer_object *) zend_object_store_get_object(php_class_old->parent.val TSRMLS_CC);
 
-    new_ov = mapscript_class_object_new_ex(mapscript_ce_class, &php_class_new TSRMLS_CC); 
-    zend_objects_clone_members(&php_class_new->std, new_ov, &php_class_old->std, Z_OBJ_HANDLE_P(zobj) TSRMLS_CC);
+  new_ov = mapscript_class_object_new_ex(mapscript_ce_class, &php_class_new TSRMLS_CC);
+  zend_objects_clone_members(&php_class_new->std, new_ov, &php_class_old->std, Z_OBJ_HANDLE_P(zobj) TSRMLS_CC);
 
-    php_class_new->class = classObj_clone(php_class_old->class, php_layer->layer);
+  php_class_new->class = classObj_clone(php_class_old->class, php_layer->layer);
 
-    return new_ov;
+  return new_ov;
 }
 
 PHP_MINIT_FUNCTION(class)
 {
-    zend_class_entry ce;
+  zend_class_entry ce;
+
+  memcpy(&mapscript_class_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
+  mapscript_class_object_handlers.clone_obj = mapscript_class_object_clone;
 
-    memcpy(&mapscript_class_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
-    mapscript_class_object_handlers.clone_obj = mapscript_class_object_clone;
+  MAPSCRIPT_REGISTER_CLASS("classObj",
+                           class_functions,
+                           mapscript_ce_class,
+                           mapscript_class_object_new);
 
-    MAPSCRIPT_REGISTER_CLASS("classObj", 
-                             class_functions,
-                             mapscript_ce_class,
-                             mapscript_class_object_new);
+  mapscript_ce_class->ce_flags |= ZEND_ACC_FINAL_CLASS;
 
-    mapscript_ce_class->ce_flags |= ZEND_ACC_FINAL_CLASS; 
-    
-    return SUCCESS;
+  return SUCCESS;
 }
diff --git a/mapscript/php/cluster.c b/mapscript/php/cluster.c
index 27e7076..c592bbb 100644
--- a/mapscript/php/cluster.c
+++ b/mapscript/php/cluster.c
@@ -2,7 +2,7 @@
  * $Id: php_mapscript.c 9765 2010-01-28 15:32:10Z aboudreault $
  *
  * Project:  MapServer
- * Purpose:  PHP/MapScript extension for MapServer.  External interface 
+ * Purpose:  PHP/MapScript extension for MapServer.  External interface
  *           functions
  * Author:   Daniel Morissette, DM Solutions Group (dmorissette at dmsolutions.ca)
  *           Alan Boudreault, Mapgears
@@ -16,16 +16,16 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
+ *
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  * DEALINGS IN THE SOFTWARE.
  **********************************************************************/
 
@@ -34,24 +34,24 @@
 zend_class_entry *mapscript_ce_cluster;
 
 ZEND_BEGIN_ARG_INFO_EX(cluster___get_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, property)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(cluster___set_args, 0, 0, 2)
-  ZEND_ARG_INFO(0, property)
-  ZEND_ARG_INFO(0, value)
+ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, value)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(cluster_updateFromString_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, snippet)
+ZEND_ARG_INFO(0, snippet)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(cluster_setGroup_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, group)
+ZEND_ARG_INFO(0, group)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(cluster_setFilter_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, filter)
+ZEND_ARG_INFO(0, filter)
 ZEND_END_ARG_INFO()
 
 
@@ -59,93 +59,90 @@ ZEND_END_ARG_INFO()
    clusterObj CANNOT be instanciated, this will throw an exception on use */
 PHP_METHOD(clusterObj, __construct)
 {
-    mapscript_throw_exception("clusterObj cannot be constructed" TSRMLS_CC);
+  mapscript_throw_exception("clusterObj cannot be constructed" TSRMLS_CC);
 }
 /* }}} */
 
 PHP_METHOD(clusterObj, __get)
 {
-    char *property;
-    long property_len;
-    zval *zobj = getThis();
-    php_cluster_object *php_cluster;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &property, &property_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *zobj = getThis();
+  php_cluster_object *php_cluster;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &property, &property_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_cluster = (php_cluster_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-
-    IF_GET_DOUBLE("maxdistance", php_cluster->cluster->maxdistance)
-    else IF_GET_DOUBLE("buffer", php_cluster->cluster->buffer) 
-    else IF_GET_STRING("region", php_cluster->cluster->region) 
-    else 
-    {
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_cluster = (php_cluster_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  IF_GET_DOUBLE("maxdistance", php_cluster->cluster->maxdistance)
+  else IF_GET_DOUBLE("buffer", php_cluster->cluster->buffer)
+    else IF_GET_STRING("region", php_cluster->cluster->region)
+      else {
         mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }
+      }
 }
 
 PHP_METHOD(clusterObj, __set)
 {
-    char *property;
-    long property_len;
-    zval *value;
-    zval *zobj = getThis();
-    php_cluster_object *php_cluster;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
-                              &property, &property_len, &value) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *value;
+  zval *zobj = getThis();
+  php_cluster_object *php_cluster;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
+                            &property, &property_len, &value) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_cluster = (php_cluster_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-
-    IF_SET_DOUBLE("maxdistance", php_cluster->cluster->maxdistance, value)
-    else IF_SET_DOUBLE("buffer", php_cluster->cluster->buffer, value) 
-    else IF_SET_STRING("region", php_cluster->cluster->region, value) 
-    else 
-    {
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_cluster = (php_cluster_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  IF_SET_DOUBLE("maxdistance", php_cluster->cluster->maxdistance, value)
+  else IF_SET_DOUBLE("buffer", php_cluster->cluster->buffer, value)
+    else IF_SET_STRING("region", php_cluster->cluster->region, value)
+      else {
         mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }
+      }
 }
 
 /* {{{ proto int updateFromString(string snippet)
    Update a cluster from a string snippet.  Returns MS_SUCCESS/MS_FAILURE */
 PHP_METHOD(clusterObj, updateFromString)
 {
-    char *snippet;
-    long snippet_len;
-    zval *zobj = getThis();
-    php_cluster_object *php_cluster;
-    int status = MS_FAILURE;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &snippet, &snippet_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *snippet;
+  long snippet_len;
+  zval *zobj = getThis();
+  php_cluster_object *php_cluster;
+  int status = MS_FAILURE;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &snippet, &snippet_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_cluster = (php_cluster_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    status = clusterObj_updateFromString(php_cluster->cluster, snippet);
-    
-    if (status != MS_SUCCESS)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
+  php_cluster = (php_cluster_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
+  status = clusterObj_updateFromString(php_cluster->cluster, snippet);
 
-    RETURN_LONG(status);
+  if (status != MS_SUCCESS) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
+
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -153,29 +150,28 @@ PHP_METHOD(clusterObj, updateFromString)
    Set the group expression string.  Returns MS_SUCCESS/MS_FAILURE */
 PHP_METHOD(clusterObj, setGroup)
 {
-    char *group = NULL;
-    long group_len;
-    zval *zobj = getThis();
-    php_cluster_object *php_cluster;
-    int status = MS_FAILURE;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &group, &group_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *group = NULL;
+  long group_len;
+  zval *zobj = getThis();
+  php_cluster_object *php_cluster;
+  int status = MS_FAILURE;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &group, &group_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_cluster = (php_cluster_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    if ((status = clusterObj_setGroup(php_cluster->cluster, group)) != MS_SUCCESS)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
-    
-    RETURN_LONG(status);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_cluster = (php_cluster_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  if ((status = clusterObj_setGroup(php_cluster->cluster, group)) != MS_SUCCESS) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -183,27 +179,26 @@ PHP_METHOD(clusterObj, setGroup)
    Return the cluster's group expression. Returns NULL on error. */
 PHP_METHOD(clusterObj, getGroupString)
 {
-    zval *zobj = getThis();
-    char *value = NULL;
-    php_cluster_object *php_cluster;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  char *value = NULL;
+  php_cluster_object *php_cluster;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_cluster = (php_cluster_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-
-    value = clusterObj_getGroupString(php_cluster->cluster);
-    if (value == NULL)
-    {
-        RETURN_NULL();
-    }
-    
-    RETVAL_STRING(value, 1);
-    free(value);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_cluster = (php_cluster_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  value = clusterObj_getGroupString(php_cluster->cluster);
+  if (value == NULL) {
+    RETURN_NULL();
+  }
+
+  RETVAL_STRING(value, 1);
+  free(value);
 }
 /* }}} */
 
@@ -211,29 +206,28 @@ PHP_METHOD(clusterObj, getGroupString)
    Set the filter expression string.  Returns MS_SUCCESS/MS_FAILURE */
 PHP_METHOD(clusterObj, setFilter)
 {
-    char *filter = NULL;
-    long filter_len;
-    zval *zobj = getThis();
-    php_cluster_object *php_cluster;
-    int status = MS_FAILURE;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &filter, &filter_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *filter = NULL;
+  long filter_len;
+  zval *zobj = getThis();
+  php_cluster_object *php_cluster;
+  int status = MS_FAILURE;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &filter, &filter_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_cluster = (php_cluster_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    if ((status = clusterObj_setFilter(php_cluster->cluster, filter)) != MS_SUCCESS)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
-    
-    RETURN_LONG(status);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_cluster = (php_cluster_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  if ((status = clusterObj_setFilter(php_cluster->cluster, filter)) != MS_SUCCESS) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -241,96 +235,96 @@ PHP_METHOD(clusterObj, setFilter)
    Return the cluster's filter expression. Returns NULL on error. */
 PHP_METHOD(clusterObj, getFilterString)
 {
-    zval *zobj = getThis();
-    char *value = NULL;
-    php_cluster_object *php_cluster;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  char *value = NULL;
+  php_cluster_object *php_cluster;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_cluster = (php_cluster_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-
-    value = clusterObj_getFilterString(php_cluster->cluster);
-    if (value == NULL)
-    {
-        RETURN_NULL();
-    }
-    
-    RETVAL_STRING(value, 1);
-    free(value);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_cluster = (php_cluster_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  value = clusterObj_getFilterString(php_cluster->cluster);
+  if (value == NULL) {
+    RETURN_NULL();
+  }
+
+  RETVAL_STRING(value, 1);
+  free(value);
 }
 /* }}} */
 
 zend_function_entry cluster_functions[] = {
-    PHP_ME(clusterObj, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
-    PHP_ME(clusterObj, __get, cluster___get_args, ZEND_ACC_PUBLIC)
-    PHP_ME(clusterObj, __set, cluster___set_args, ZEND_ACC_PUBLIC)
-    PHP_ME(clusterObj, updateFromString, cluster_updateFromString_args, ZEND_ACC_PUBLIC)
-    PHP_ME(clusterObj, setGroup, cluster_setGroup_args, ZEND_ACC_PUBLIC)
-    PHP_ME(clusterObj, getGroupString, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(clusterObj, setFilter, cluster_setFilter_args, ZEND_ACC_PUBLIC)
-    PHP_ME(clusterObj, getFilterString, NULL, ZEND_ACC_PUBLIC)
-    {NULL, NULL, NULL}
+  PHP_ME(clusterObj, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
+  PHP_ME(clusterObj, __get, cluster___get_args, ZEND_ACC_PUBLIC)
+  PHP_ME(clusterObj, __set, cluster___set_args, ZEND_ACC_PUBLIC)
+  PHP_ME(clusterObj, updateFromString, cluster_updateFromString_args, ZEND_ACC_PUBLIC)
+  PHP_ME(clusterObj, setGroup, cluster_setGroup_args, ZEND_ACC_PUBLIC)
+  PHP_ME(clusterObj, getGroupString, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(clusterObj, setFilter, cluster_setFilter_args, ZEND_ACC_PUBLIC)
+  PHP_ME(clusterObj, getFilterString, NULL, ZEND_ACC_PUBLIC) {
+    NULL, NULL, NULL
+  }
 };
 
 
 void mapscript_create_cluster(clusterObj *cluster, parent_object parent, zval *return_value TSRMLS_DC)
 {
-    php_cluster_object * php_cluster;
-    object_init_ex(return_value, mapscript_ce_cluster); 
-    php_cluster = (php_cluster_object *)zend_object_store_get_object(return_value TSRMLS_CC);
-    php_cluster->cluster = cluster;
+  php_cluster_object * php_cluster;
+  object_init_ex(return_value, mapscript_ce_cluster);
+  php_cluster = (php_cluster_object *)zend_object_store_get_object(return_value TSRMLS_CC);
+  php_cluster->cluster = cluster;
 
-    if (parent.val) 
-        php_cluster->is_ref = 1;
+  if (parent.val)
+    php_cluster->is_ref = 1;
 
-    php_cluster->parent = parent;
-    MAPSCRIPT_ADDREF(parent.val);
+  php_cluster->parent = parent;
+  MAPSCRIPT_ADDREF(parent.val);
 }
 
 static void mapscript_cluster_object_destroy(void *object TSRMLS_DC)
 {
-    php_cluster_object *php_cluster = (php_cluster_object *)object;
+  php_cluster_object *php_cluster = (php_cluster_object *)object;
 
-    MAPSCRIPT_FREE_OBJECT(php_cluster);
+  MAPSCRIPT_FREE_OBJECT(php_cluster);
 
-    MAPSCRIPT_FREE_PARENT(php_cluster->parent);
+  MAPSCRIPT_FREE_PARENT(php_cluster->parent);
 
-    /* We don't need to free the clusterObj */ 
+  /* We don't need to free the clusterObj */
 
-    efree(object);
+  efree(object);
 }
 
 static zend_object_value mapscript_cluster_object_new(zend_class_entry *ce TSRMLS_DC)
 {
-    zend_object_value retval;
-    php_cluster_object *php_cluster;
+  zend_object_value retval;
+  php_cluster_object *php_cluster;
 
-    MAPSCRIPT_ALLOC_OBJECT(php_cluster, php_cluster_object);
+  MAPSCRIPT_ALLOC_OBJECT(php_cluster, php_cluster_object);
 
-    retval = mapscript_object_new(&php_cluster->std, ce,
-                                  &mapscript_cluster_object_destroy TSRMLS_CC);
+  retval = mapscript_object_new(&php_cluster->std, ce,
+                                &mapscript_cluster_object_destroy TSRMLS_CC);
 
-    php_cluster->is_ref = 0;
-    MAPSCRIPT_INIT_PARENT(php_cluster->parent)
+  php_cluster->is_ref = 0;
+  MAPSCRIPT_INIT_PARENT(php_cluster->parent)
 
-    return retval;
+  return retval;
 }
 
 PHP_MINIT_FUNCTION(cluster)
 {
-    zend_class_entry ce;
+  zend_class_entry ce;
+
+  MAPSCRIPT_REGISTER_CLASS("clusterObj",
+                           cluster_functions,
+                           mapscript_ce_cluster,
+                           mapscript_cluster_object_new);
 
-    MAPSCRIPT_REGISTER_CLASS("clusterObj", 
-                             cluster_functions,
-                             mapscript_ce_cluster,
-                             mapscript_cluster_object_new);
+  mapscript_ce_cluster->ce_flags |= ZEND_ACC_FINAL_CLASS;
 
-    mapscript_ce_cluster->ce_flags |= ZEND_ACC_FINAL_CLASS; 
-    
-    return SUCCESS;
+  return SUCCESS;
 }
diff --git a/mapscript/php/color.c b/mapscript/php/color.c
index 641857e..ac7a614 100644
--- a/mapscript/php/color.c
+++ b/mapscript/php/color.c
@@ -2,7 +2,7 @@
  * $Id: php_mapscript.c 9765 2010-01-28 15:32:10Z aboudreault $
  *
  * Project:  MapServer
- * Purpose:  PHP/MapScript extension for MapServer.  External interface 
+ * Purpose:  PHP/MapScript extension for MapServer.  External interface
  *           functions
  * Author:   Daniel Morissette, DM Solutions Group (dmorissette at dmsolutions.ca)
  *           Alan Boudreault, Mapgears
@@ -16,16 +16,16 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
+ *
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  * DEALINGS IN THE SOFTWARE.
  **********************************************************************/
 
@@ -34,167 +34,168 @@
 zend_class_entry *mapscript_ce_color;
 
 ZEND_BEGIN_ARG_INFO_EX(color___get_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, property)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(color___set_args, 0, 0, 2)
-  ZEND_ARG_INFO(0, property)
-  ZEND_ARG_INFO(0, value)
+ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, value)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(color_setRGB_args, 0, 0, 3)
-  ZEND_ARG_INFO(0, red)
-  ZEND_ARG_INFO(0, green)
-  ZEND_ARG_INFO(0, blue)
+ZEND_ARG_INFO(0, red)
+ZEND_ARG_INFO(0, green)
+ZEND_ARG_INFO(0, blue)
 ZEND_END_ARG_INFO()
 
-/* {{{ proto void __construct() 
+/* {{{ proto void __construct()
    colorObj CANNOT be instanciated, this will throw an exception on use */
 PHP_METHOD(colorObj, __construct)
 {
-    mapscript_throw_exception("colorObj cannot be constructed" TSRMLS_CC);
+  mapscript_throw_exception("colorObj cannot be constructed" TSRMLS_CC);
 }
 /* }}} */
 
 PHP_METHOD(colorObj, __get)
 {
-    char *property;
-    long property_len;
-    zval *zobj = getThis();
-    php_color_object *php_color;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &property, &property_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *zobj = getThis();
+  php_color_object *php_color;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &property, &property_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_color = (php_color_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_color = (php_color_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    IF_GET_LONG("red", php_color->color->red)
-    else IF_GET_LONG("green", php_color->color->green)
+  IF_GET_LONG("red", php_color->color->red)
+  else IF_GET_LONG("green", php_color->color->green)
     else IF_GET_LONG("blue", php_color->color->blue)
-    else 
-    {
-        mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }
+      else IF_GET_LONG("alpha", php_color->color->alpha)
+        else {
+          mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+        }
 }
 
 PHP_METHOD(colorObj, __set)
 {
-    char *property;
-    long property_len;
-    zval *value;
-    zval *zobj = getThis();
-    php_color_object *php_color;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
-                              &property, &property_len, &value) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *value;
+  zval *zobj = getThis();
+  php_color_object *php_color;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
+                            &property, &property_len, &value) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_color = (php_color_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    IF_SET_COLOR("red", php_color->color->red, value)
-    else IF_SET_COLOR("green", php_color->color->green, value)
+  php_color = (php_color_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  IF_SET_COLOR("red", php_color->color->red, value)
+  else IF_SET_COLOR("green", php_color->color->green, value)
     else IF_SET_COLOR("blue", php_color->color->blue, value)
-    else 
-    {
-        mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }
-         
+      else IF_SET_COLOR("alpha", php_color->color->alpha, value)
+        else {
+          mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+        }
+
 }
 
 /* {{{ proto int color.setRGB(int R, int G, int B)
     Set new RGB color. */
 PHP_METHOD(colorObj, setRGB)
 {
-    zval *zobj = getThis();
-    long red, green, blue;
-    php_color_object *php_color;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "lll",
-                              &red, &green, &blue) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  long red, green, blue;
+  php_color_object *php_color;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "lll",
+                            &red, &green, &blue) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_color = (php_color_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    MS_INIT_COLOR(*(php_color->color), red, green, blue,255);
+  php_color = (php_color_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    RETURN_LONG(MS_SUCCESS);
+
+  MS_INIT_COLOR(*(php_color->color), red, green, blue,255);
+
+  RETURN_LONG(MS_SUCCESS);
 }
 /* }}} */
 
 zend_function_entry color_functions[] = {
-    PHP_ME(colorObj, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
-    PHP_ME(colorObj, __get, color___get_args, ZEND_ACC_PUBLIC)
-    PHP_ME(colorObj, __set, color___set_args, ZEND_ACC_PUBLIC)
-    PHP_ME(colorObj, setRGB, color_setRGB_args, ZEND_ACC_PUBLIC)
-    {NULL, NULL, NULL}
+  PHP_ME(colorObj, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
+  PHP_ME(colorObj, __get, color___get_args, ZEND_ACC_PUBLIC)
+  PHP_ME(colorObj, __set, color___set_args, ZEND_ACC_PUBLIC)
+  PHP_ME(colorObj, setRGB, color_setRGB_args, ZEND_ACC_PUBLIC) {
+    NULL, NULL, NULL
+  }
 };
 
 
 void mapscript_create_color(colorObj *color, parent_object parent, zval *return_value TSRMLS_DC)
 {
-    php_color_object * php_color;
-    object_init_ex(return_value, mapscript_ce_color); 
-    php_color = (php_color_object *)zend_object_store_get_object(return_value TSRMLS_CC);
-    php_color->color = color;
-
-    php_color->parent = parent;
-    
-    MAPSCRIPT_ADDREF(parent.val);
+  php_color_object * php_color;
+  object_init_ex(return_value, mapscript_ce_color);
+  php_color = (php_color_object *)zend_object_store_get_object(return_value TSRMLS_CC);
+  php_color->color = color;
+
+  php_color->parent = parent;
+
+  MAPSCRIPT_ADDREF(parent.val);
 }
 
 static void mapscript_color_object_destroy(void *object TSRMLS_DC)
 {
-    php_color_object *php_color = (php_color_object *)object;
+  php_color_object *php_color = (php_color_object *)object;
+
+  MAPSCRIPT_FREE_OBJECT(php_color);
 
-    MAPSCRIPT_FREE_OBJECT(php_color);
+  MAPSCRIPT_FREE_PARENT(php_color->parent);
 
-    MAPSCRIPT_FREE_PARENT(php_color->parent);
-    
-    /* We don't need to free the colorObj, the mapObj will do it */ 
+  /* We don't need to free the colorObj, the mapObj will do it */
 
-    efree(object);
+  efree(object);
 }
 
 static zend_object_value mapscript_color_object_new(zend_class_entry *ce TSRMLS_DC)
 {
-    zend_object_value retval;
-    php_color_object *php_color;
+  zend_object_value retval;
+  php_color_object *php_color;
 
-    MAPSCRIPT_ALLOC_OBJECT(php_color, php_color_object);
+  MAPSCRIPT_ALLOC_OBJECT(php_color, php_color_object);
 
-    retval = mapscript_object_new(&php_color->std, ce,
-                                  &mapscript_color_object_destroy TSRMLS_CC);
+  retval = mapscript_object_new(&php_color->std, ce,
+                                &mapscript_color_object_destroy TSRMLS_CC);
 
-    MAPSCRIPT_INIT_PARENT(php_color->parent);
+  MAPSCRIPT_INIT_PARENT(php_color->parent);
 
-    return retval;
+  return retval;
 }
 
 PHP_MINIT_FUNCTION(color)
 {
-    zend_class_entry ce;
+  zend_class_entry ce;
+
+  MAPSCRIPT_REGISTER_CLASS("colorObj",
+                           color_functions,
+                           mapscript_ce_color,
+                           mapscript_color_object_new);
 
-    MAPSCRIPT_REGISTER_CLASS("colorObj", 
-                             color_functions,
-                             mapscript_ce_color,
-                             mapscript_color_object_new);
+  mapscript_ce_color->ce_flags |= ZEND_ACC_FINAL_CLASS;
 
-    mapscript_ce_color->ce_flags |= ZEND_ACC_FINAL_CLASS; 
-    
-    return SUCCESS;
+  return SUCCESS;
 }
 
diff --git a/mapscript/php/error.c b/mapscript/php/error.c
index 0114aa3..71f617e 100644
--- a/mapscript/php/error.c
+++ b/mapscript/php/error.c
@@ -2,7 +2,7 @@
  * $Id: php_mapscript.c 9765 2010-01-28 15:32:10Z aboudreault $
  *
  * Project:  MapServer
- * Purpose:  PHP/MapScript extension for MapServer.  External interface 
+ * Purpose:  PHP/MapScript extension for MapServer.  External interface
  *           functions
  * Author:   Daniel Morissette, DM Solutions Group (dmorissette at dmsolutions.ca)
  *           Alan Boudreault, Mapgears
@@ -16,16 +16,16 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
+ *
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  * DEALINGS IN THE SOFTWARE.
  **********************************************************************/
 
@@ -34,168 +34,165 @@
 zend_class_entry *mapscript_ce_error;
 
 ZEND_BEGIN_ARG_INFO_EX(error___get_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, property)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(error___set_args, 0, 0, 2)
-  ZEND_ARG_INFO(0, property)
-  ZEND_ARG_INFO(0, value)
+ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, value)
 ZEND_END_ARG_INFO()
 
 /* {{{ proto error __construct()
    errorObj CANNOT be instanciated, this will throw an exception on use */
 PHP_METHOD(errorObj, __construct)
 {
-    mapscript_throw_exception("errorObj cannot be constructed" TSRMLS_CC);
+  mapscript_throw_exception("errorObj cannot be constructed" TSRMLS_CC);
 }
 /* }}} */
 
 PHP_METHOD(errorObj, __get)
 {
-    char *property;
-    long property_len;
-    zval *zobj = getThis();
-    php_error_object *php_error;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &property, &property_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *zobj = getThis();
+  php_error_object *php_error;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &property, &property_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_error = (php_error_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_error = (php_error_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    IF_GET_LONG("code", php_error->error->code)
-    else IF_GET_STRING("routine", php_error->error->routine)
+  IF_GET_LONG("code", php_error->error->code)
+  else IF_GET_STRING("routine", php_error->error->routine)
     else IF_GET_STRING("message", php_error->error->message)
-    else 
-    {
-        mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }
+      else IF_GET_LONG("isreported", php_error->error->isreported)
+        else {
+          mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+        }
 }
 
 PHP_METHOD(errorObj, __set)
 {
-    char *property;
-    long property_len;
-    zval *value;
-    zval *zobj = getThis();
-    php_error_object *php_error;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
-                              &property, &property_len, &value) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *value;
+  zval *zobj = getThis();
+  php_error_object *php_error;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
+                            &property, &property_len, &value) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_error = (php_error_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-
-    if ( (STRING_EQUAL("code", property)) ||
-         (STRING_EQUAL("routine", property)) ||
-         (STRING_EQUAL("message", property)))
-    {
-        mapscript_throw_exception("Property '%s' is read-only and cannot be set." TSRMLS_CC, property);
-    }
-    else 
-    {
-        mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_error = (php_error_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  if ( (STRING_EQUAL("code", property)) ||
+       (STRING_EQUAL("routine", property)) ||
+       (STRING_EQUAL("isreported", property)) ||
+       (STRING_EQUAL("message", property))) {
+    mapscript_throw_exception("Property '%s' is read-only and cannot be set." TSRMLS_CC, property);
+  } else {
+    mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+  }
 }
 
 /* {{{ proto int error.next()
    Returns a ref to the next errorObj in the list, or NULL if we reached the last one */
 PHP_METHOD(errorObj, next)
 {
-    zval *zobj = getThis();
-    php_error_object *php_error;
-    errorObj *error = NULL;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  php_error_object *php_error;
+  errorObj *error = NULL;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_error = (php_error_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-
-    if (php_error->error->next == NULL)
-        RETURN_NULL();
-
-    /* Make sure 'self' is still valid.  It may have been deleted by 
-     * msResetErrorList() */
-    error = msGetErrorObj();
-    while(error != php_error->error)
-    {
-        if (error->next == NULL)
-        {
-            mapscript_throw_exception("Trying to access an errorObj that has expired." TSRMLS_CC);
-            return;
-        }
-        error = error->next;
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_error = (php_error_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  if (php_error->error->next == NULL)
+    RETURN_NULL();
+
+  /* Make sure 'self' is still valid.  It may have been deleted by
+   * msResetErrorList() */
+  error = msGetErrorObj();
+  while(error != php_error->error) {
+    if (error->next == NULL) {
+      mapscript_throw_exception("Trying to access an errorObj that has expired." TSRMLS_CC);
+      return;
     }
-   
-    php_error->error = php_error->error->next;
-    *return_value = *zobj;              
-    zval_copy_ctor(return_value);        
-    INIT_PZVAL(return_value);
+    error = error->next;
+  }
+
+  php_error->error = php_error->error->next;
+  *return_value = *zobj;
+  zval_copy_ctor(return_value);
+  INIT_PZVAL(return_value);
 }
 /* }}} */
 
 zend_function_entry error_functions[] = {
-    PHP_ME(errorObj, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
-    PHP_ME(errorObj, __get, error___get_args, ZEND_ACC_PUBLIC)
-    PHP_ME(errorObj, __set, error___set_args, ZEND_ACC_PUBLIC)
-    PHP_ME(errorObj, next, NULL, ZEND_ACC_PUBLIC)
-    {NULL, NULL, NULL}
+  PHP_ME(errorObj, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
+  PHP_ME(errorObj, __get, error___get_args, ZEND_ACC_PUBLIC)
+  PHP_ME(errorObj, __set, error___set_args, ZEND_ACC_PUBLIC)
+  PHP_ME(errorObj, next, NULL, ZEND_ACC_PUBLIC) {
+    NULL, NULL, NULL
+  }
 };
 
 void mapscript_create_error(errorObj *error, zval *return_value TSRMLS_DC)
 {
-    php_error_object * php_error;
-    object_init_ex(return_value, mapscript_ce_error); 
-    php_error = (php_error_object *)zend_object_store_get_object(return_value TSRMLS_CC);
-    php_error->error = error;
+  php_error_object * php_error;
+  object_init_ex(return_value, mapscript_ce_error);
+  php_error = (php_error_object *)zend_object_store_get_object(return_value TSRMLS_CC);
+  php_error->error = error;
 }
 
 static void mapscript_error_object_destroy(void *object TSRMLS_DC)
 {
-    php_error_object *php_error = (php_error_object *)object;
+  php_error_object *php_error = (php_error_object *)object;
+
+  MAPSCRIPT_FREE_OBJECT(php_error);
 
-    MAPSCRIPT_FREE_OBJECT(php_error);
+  /* We don't need to free the errorObj */
 
-    /* We don't need to free the errorObj */ 
-    
-    efree(object);
+  efree(object);
 }
 
 static zend_object_value mapscript_error_object_new(zend_class_entry *ce TSRMLS_DC)
 {
-    zend_object_value retval;
-    php_error_object *php_error;
+  zend_object_value retval;
+  php_error_object *php_error;
 
-    MAPSCRIPT_ALLOC_OBJECT(php_error, php_error_object);
+  MAPSCRIPT_ALLOC_OBJECT(php_error, php_error_object);
 
-    retval = mapscript_object_new(&php_error->std, ce,
-                                  &mapscript_error_object_destroy TSRMLS_CC);
+  retval = mapscript_object_new(&php_error->std, ce,
+                                &mapscript_error_object_destroy TSRMLS_CC);
 
-    return retval;
+  return retval;
 }
 
 PHP_MINIT_FUNCTION(error)
 {
-    zend_class_entry ce;
+  zend_class_entry ce;
+
+  MAPSCRIPT_REGISTER_CLASS("errorObj",
+                           error_functions,
+                           mapscript_ce_error,
+                           mapscript_error_object_new);
 
-    MAPSCRIPT_REGISTER_CLASS("errorObj", 
-                             error_functions,
-                             mapscript_ce_error,
-                             mapscript_error_object_new);
+  mapscript_ce_error->ce_flags |= ZEND_ACC_FINAL_CLASS;
 
-    mapscript_ce_error->ce_flags |= ZEND_ACC_FINAL_CLASS; 
-    
-    return SUCCESS;
+  return SUCCESS;
 }
diff --git a/mapscript/php/grid.c b/mapscript/php/grid.c
index da65368..bb25866 100644
--- a/mapscript/php/grid.c
+++ b/mapscript/php/grid.c
@@ -2,7 +2,7 @@
  * $Id: php_mapscript.c 9765 2010-01-28 15:32:10Z aboudreault $
  *
  * Project:  MapServer
- * Purpose:  PHP/MapScript extension for MapServer.  External interface 
+ * Purpose:  PHP/MapScript extension for MapServer.  External interface
  *           functions
  * Author:   Daniel Morissette, DM Solutions Group (dmorissette at dmsolutions.ca)
  *           Alan Boudreault, Mapgears
@@ -16,16 +16,16 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
+ *
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  * DEALINGS IN THE SOFTWARE.
  **********************************************************************/
 
@@ -34,182 +34,181 @@
 zend_class_entry *mapscript_ce_grid;
 
 ZEND_BEGIN_ARG_INFO_EX(grid___construct_args, 0, 1, 1)
-  ZEND_ARG_OBJ_INFO(0, layer, layerObj, 0)
+ZEND_ARG_OBJ_INFO(0, layer, layerObj, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(grid___get_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, property)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(grid___set_args, 0, 0, 2)
-  ZEND_ARG_INFO(0, property)
-  ZEND_ARG_INFO(0, value)
+ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, value)
 ZEND_END_ARG_INFO()
 
 /* {{{ proto void __construct(layerObj layer)
    Create a new intance of gridObj. */
 PHP_METHOD(gridObj, __construct)
 {
-    zval *zlayer;
-    php_layer_object *php_layer;
-    php_grid_object *php_grid, *php_old_grid;
-    parent_object parent;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
-                              &zlayer, mapscript_ce_layer) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zlayer;
+  php_layer_object *php_layer;
+  php_grid_object *php_grid, *php_old_grid;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
+                            &zlayer, mapscript_ce_layer) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_grid = (php_grid_object *) zend_object_store_get_object(getThis() TSRMLS_CC);
-    php_layer = (php_layer_object *) zend_object_store_get_object(zlayer TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_grid = (php_grid_object *) zend_object_store_get_object(getThis() TSRMLS_CC);
+  php_layer = (php_layer_object *) zend_object_store_get_object(zlayer TSRMLS_CC);
+
+  php_layer->layer->connectiontype = MS_GRATICULE;
 
-    php_layer->layer->connectiontype = MS_GRATICULE;
 
+  if (php_layer->layer->layerinfo != NULL)
+    free(php_layer->layer->layerinfo);
 
-    if (php_layer->layer->layerinfo != NULL)
-        free(php_layer->layer->layerinfo);
 
+  php_layer->layer->layerinfo = (graticuleObj *)malloc( sizeof( graticuleObj ) );
+  initGrid((graticuleObj *)php_layer->layer->layerinfo);
 
-    php_layer->layer->layerinfo = (graticuleObj *)malloc( sizeof( graticuleObj ) );
-    initGrid((graticuleObj *)php_layer->layer->layerinfo);
+  php_grid->grid = (graticuleObj *)php_layer->layer->layerinfo;
 
-    php_grid->grid = (graticuleObj *)php_layer->layer->layerinfo;
+  if (php_layer->grid && (Z_TYPE_P(php_layer->grid) == IS_OBJECT)) {
+    php_old_grid = (php_grid_object *) zend_object_store_get_object(php_layer->grid TSRMLS_CC);
+    php_old_grid->parent.child_ptr = NULL;
+    zend_objects_store_del_ref(php_layer->grid TSRMLS_CC);
+  }
 
-    if (php_layer->grid && (Z_TYPE_P(php_layer->grid) == IS_OBJECT)) {
-        php_old_grid = (php_grid_object *) zend_object_store_get_object(php_layer->grid TSRMLS_CC); 
-        php_old_grid->parent.child_ptr = NULL;
-        zend_objects_store_del_ref(php_layer->grid TSRMLS_CC);
-    }
+  MAKE_STD_ZVAL(php_layer->grid);
+  MAPSCRIPT_MAKE_PARENT(zlayer, &php_layer->grid);
+  mapscript_create_grid((graticuleObj *)(php_layer->layer->layerinfo), parent, php_layer->grid TSRMLS_CC);
 
-    MAKE_STD_ZVAL(php_layer->grid);
-    MAPSCRIPT_MAKE_PARENT(zlayer, &php_layer->grid);
-    mapscript_create_grid((graticuleObj *)(php_layer->layer->layerinfo), parent, php_layer->grid TSRMLS_CC);
-    
-    return_value_ptr = &php_layer->grid;
+  return_value_ptr = &php_layer->grid;
 }
 /* }}} */
 
 PHP_METHOD(gridObj, __get)
 {
-    char *property;
-    long property_len;
-    zval *zobj = getThis();
-    php_grid_object *php_grid;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &property, &property_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *zobj = getThis();
+  php_grid_object *php_grid;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &property, &property_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_grid = (php_grid_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    IF_GET_DOUBLE("minsubdivide", php_grid->grid->minsubdivides)
-    else IF_GET_DOUBLE("maxsubdivide", php_grid->grid->maxsubdivides)
+  php_grid = (php_grid_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  IF_GET_DOUBLE("minsubdivide", php_grid->grid->minsubdivides)
+  else IF_GET_DOUBLE("maxsubdivide", php_grid->grid->maxsubdivides)
     else IF_GET_DOUBLE("minarcs", php_grid->grid->minarcs)
-    else IF_GET_DOUBLE("maxarcs", php_grid->grid->maxarcs)
-    else IF_GET_DOUBLE("mininterval", php_grid->grid->minincrement)
-    else IF_GET_DOUBLE("maxinterval", php_grid->grid->maxincrement)
-    else IF_GET_STRING("labelformat", php_grid->grid->labelformat)
-    else 
-    {
-        mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }
+      else IF_GET_DOUBLE("maxarcs", php_grid->grid->maxarcs)
+        else IF_GET_DOUBLE("mininterval", php_grid->grid->minincrement)
+          else IF_GET_DOUBLE("maxinterval", php_grid->grid->maxincrement)
+            else IF_GET_STRING("labelformat", php_grid->grid->labelformat)
+              else {
+                mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+              }
 }
 
 PHP_METHOD(gridObj, __set)
 {
-    char *property;
-    long property_len;
-    zval *value;
-    zval *zobj = getThis();
-    php_grid_object *php_grid;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
-                              &property, &property_len, &value) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *value;
+  zval *zobj = getThis();
+  php_grid_object *php_grid;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
+                            &property, &property_len, &value) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_grid = (php_grid_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_grid = (php_grid_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    IF_SET_DOUBLE("minsubdivide", php_grid->grid->minsubdivides, value)
-    else IF_SET_DOUBLE("maxsubdivide", php_grid->grid->maxsubdivides, value)
+  IF_SET_DOUBLE("minsubdivide", php_grid->grid->minsubdivides, value)
+  else IF_SET_DOUBLE("maxsubdivide", php_grid->grid->maxsubdivides, value)
     else IF_SET_DOUBLE("minarcs", php_grid->grid->minarcs, value)
-    else IF_SET_DOUBLE("maxarcs", php_grid->grid->maxarcs, value)
-    else IF_SET_DOUBLE("mininterval", php_grid->grid->minincrement, value)
-    else IF_SET_DOUBLE("maxinterval", php_grid->grid->maxincrement, value)
-    else IF_SET_STRING("labelformat", php_grid->grid->labelformat, value)
-    else 
-    {
-        mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }
+      else IF_SET_DOUBLE("maxarcs", php_grid->grid->maxarcs, value)
+        else IF_SET_DOUBLE("mininterval", php_grid->grid->minincrement, value)
+          else IF_SET_DOUBLE("maxinterval", php_grid->grid->maxincrement, value)
+            else IF_SET_STRING("labelformat", php_grid->grid->labelformat, value)
+              else {
+                mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+              }
 }
 
 zend_function_entry grid_functions[] = {
-    PHP_ME(gridObj, __construct, grid___construct_args, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
-    PHP_ME(gridObj, __get, grid___get_args, ZEND_ACC_PUBLIC)
-    PHP_ME(gridObj, __set, grid___set_args, ZEND_ACC_PUBLIC)
-    PHP_MALIAS(gridObj, set, __set, NULL, ZEND_ACC_PUBLIC)
-    {NULL, NULL, NULL}
+  PHP_ME(gridObj, __construct, grid___construct_args, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
+  PHP_ME(gridObj, __get, grid___get_args, ZEND_ACC_PUBLIC)
+  PHP_ME(gridObj, __set, grid___set_args, ZEND_ACC_PUBLIC)
+  PHP_MALIAS(gridObj, set, __set, NULL, ZEND_ACC_PUBLIC) {
+    NULL, NULL, NULL
+  }
 };
 
 void mapscript_create_grid(graticuleObj *grid, parent_object parent, zval *return_value TSRMLS_DC)
 {
-    php_grid_object * php_grid;
-    object_init_ex(return_value, mapscript_ce_grid); 
-    php_grid = (php_grid_object *)zend_object_store_get_object(return_value TSRMLS_CC);
-    php_grid->grid = grid;
+  php_grid_object * php_grid;
+  object_init_ex(return_value, mapscript_ce_grid);
+  php_grid = (php_grid_object *)zend_object_store_get_object(return_value TSRMLS_CC);
+  php_grid->grid = grid;
 
-    php_grid->parent = parent;
-    MAPSCRIPT_ADDREF(parent.val);
+  php_grid->parent = parent;
+  MAPSCRIPT_ADDREF(parent.val);
 }
 
 static void mapscript_grid_object_destroy(void *object TSRMLS_DC)
 {
-    php_grid_object *php_grid = (php_grid_object *)object;
+  php_grid_object *php_grid = (php_grid_object *)object;
 
-    MAPSCRIPT_FREE_OBJECT(php_grid);
+  MAPSCRIPT_FREE_OBJECT(php_grid);
 
-    MAPSCRIPT_FREE_PARENT(php_grid->parent);
+  MAPSCRIPT_FREE_PARENT(php_grid->parent);
 
-    /* We don't need to free the gridObj */ 
+  /* We don't need to free the gridObj */
 
-    efree(object);
+  efree(object);
 }
 
 static zend_object_value mapscript_grid_object_new(zend_class_entry *ce TSRMLS_DC)
 {
-    zend_object_value retval;
-    php_grid_object *php_grid;
+  zend_object_value retval;
+  php_grid_object *php_grid;
 
-    MAPSCRIPT_ALLOC_OBJECT(php_grid, php_grid_object);
+  MAPSCRIPT_ALLOC_OBJECT(php_grid, php_grid_object);
 
-    retval = mapscript_object_new(&php_grid->std, ce,
-                                  &mapscript_grid_object_destroy TSRMLS_CC);
+  retval = mapscript_object_new(&php_grid->std, ce,
+                                &mapscript_grid_object_destroy TSRMLS_CC);
 
-    MAPSCRIPT_INIT_PARENT(php_grid->parent);
+  MAPSCRIPT_INIT_PARENT(php_grid->parent);
 
-    return retval;
+  return retval;
 }
 
 PHP_MINIT_FUNCTION(grid)
 {
-    zend_class_entry ce;
+  zend_class_entry ce;
+
+  MAPSCRIPT_REGISTER_CLASS("gridObj",
+                           grid_functions,
+                           mapscript_ce_grid,
+                           mapscript_grid_object_new);
 
-    MAPSCRIPT_REGISTER_CLASS("gridObj", 
-                             grid_functions,
-                             mapscript_ce_grid,
-                             mapscript_grid_object_new);
+  mapscript_ce_grid->ce_flags |= ZEND_ACC_FINAL_CLASS;
 
-    mapscript_ce_grid->ce_flags |= ZEND_ACC_FINAL_CLASS; 
-    
-    return SUCCESS;
+  return SUCCESS;
 }
diff --git a/mapscript/php/hashtable.c b/mapscript/php/hashtable.c
index 1882f48..25ab33d 100644
--- a/mapscript/php/hashtable.c
+++ b/mapscript/php/hashtable.c
@@ -2,7 +2,7 @@
  * $Id: php_mapscript.c 9765 2010-01-28 15:32:10Z aboudreault $
  *
  * Project:  MapServer
- * Purpose:  PHP/MapScript extension for MapServer.  External interface 
+ * Purpose:  PHP/MapScript extension for MapServer.  External interface
  *           functions
  * Author:   Daniel Morissette, DM Solutions Group (dmorissette at dmsolutions.ca)
  *           Alan Boudreault, Mapgears
@@ -16,16 +16,16 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
+ *
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  * DEALINGS IN THE SOFTWARE.
  **********************************************************************/
 
@@ -34,76 +34,109 @@
 zend_class_entry *mapscript_ce_hashtable;
 
 ZEND_BEGIN_ARG_INFO_EX(hashtable___get_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, property)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(hashtable___set_args, 0, 0, 2)
-  ZEND_ARG_INFO(0, property)
-  ZEND_ARG_INFO(0, value)
+ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, value)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(hashtable_get_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, key)
+ZEND_ARG_INFO(0, key)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(hashtable_set_args, 0, 0, 2)
-  ZEND_ARG_INFO(0, key)
-  ZEND_ARG_INFO(0, value)
+ZEND_ARG_INFO(0, key)
+ZEND_ARG_INFO(0, value)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(hashtable_remove_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, key)
+ZEND_ARG_INFO(0, key)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(hashtable_nextkey_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, previousKey)
+ZEND_ARG_INFO(0, previousKey)
 ZEND_END_ARG_INFO()
 
 /* {{{ proto hashtable __construct()
    Create a new hashtableObj instance. */
 PHP_METHOD(hashtableObj, __construct)
 {
-    mapscript_throw_exception("hashTableObj cannot be constructed" TSRMLS_CC);
+  mapscript_throw_exception("hashTableObj cannot be constructed" TSRMLS_CC);
 }
 /* }}} */
 
 PHP_METHOD(hashtableObj, __get)
 {
-    mapscript_throw_exception("hashTableObj has no property." TSRMLS_CC);
+  char *property;
+  long property_len;
+  zval *zobj = getThis();
+  php_hashtable_object *php_hashtable;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &property, &property_len) == FAILURE) {
+    PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_hashtable = (php_hashtable_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  IF_GET_LONG("numitems", php_hashtable->hashtable->numitems)
+  else {
+    mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+  }
 }
 
 PHP_METHOD(hashtableObj, __set)
 {
-    mapscript_throw_exception("hashTableObj has no property." TSRMLS_CC);
+  char *property;
+  long property_len;
+  zval *value;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
+                            &property, &property_len, &value) == FAILURE) {
+    PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  if ( (STRING_EQUAL("numitems", property))) {
+    mapscript_throw_exception("Property '%s' is read-only and cannot be set." TSRMLS_CC, property);
+  } else {
+    mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+  }
 }
 
 /* {{{ proto int hashtable.get(string key)
    Get a value from item by its key. Returns empty string if not found. */
 PHP_METHOD(hashtableObj, get)
 {
-    char *key;
-    long key_len;
-    zval *zobj = getThis();
-    const char *value = NULL;
-    php_hashtable_object *php_hashtable;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &key, &key_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *key;
+  long key_len;
+  zval *zobj = getThis();
+  const char *value = NULL;
+  php_hashtable_object *php_hashtable;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &key, &key_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_hashtable = (php_hashtable_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    value = hashTableObj_get(php_hashtable->hashtable, key);
-    if (value == NULL)
-    {
-        RETURN_STRING("",1);
-    }
+  php_hashtable = (php_hashtable_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    RETURN_STRING((char *)value, 1);
+  value = hashTableObj_get(php_hashtable->hashtable, key);
+  if (value == NULL) {
+    RETURN_STRING("",1);
+  }
+
+  RETURN_STRING((char *)value, 1);
 }
 /* }}} */
 
@@ -111,29 +144,28 @@ PHP_METHOD(hashtableObj, get)
    Set a hash item given key and value. Returns MS_FAILURE on error. */
 PHP_METHOD(hashtableObj, set)
 {
-    char *key, *value;
-    long key_len, value_len;
-    zval *zobj = getThis();
-    int status = MS_FAILURE;
-    php_hashtable_object *php_hashtable;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss",
-                              &key, &key_len, &value, &value_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *key, *value;
+  long key_len, value_len;
+  zval *zobj = getThis();
+  int status = MS_FAILURE;
+  php_hashtable_object *php_hashtable;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss",
+                            &key, &key_len, &value, &value_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_hashtable = (php_hashtable_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_hashtable = (php_hashtable_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    if ((status = hashTableObj_set(php_hashtable->hashtable, key, value)) != MS_SUCCESS)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
+  if ((status = hashTableObj_set(php_hashtable->hashtable, key, value)) != MS_SUCCESS) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
 
-    RETURN_LONG(status);
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -141,29 +173,28 @@ PHP_METHOD(hashtableObj, set)
    Remove one item from hash table. Returns MS_FAILURE on error. */
 PHP_METHOD(hashtableObj, remove)
 {
-    char *key;
-    long key_len;
-    zval *zobj = getThis();
-    int status = MS_FAILURE;
-    php_hashtable_object *php_hashtable;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &key, &key_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *key;
+  long key_len;
+  zval *zobj = getThis();
+  int status = MS_FAILURE;
+  php_hashtable_object *php_hashtable;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &key, &key_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_hashtable = (php_hashtable_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-
-    if ((status = hashTableObj_remove(php_hashtable->hashtable, key)) != MS_SUCCESS)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
-    
-    RETURN_LONG(status);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_hashtable = (php_hashtable_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  if ((status = hashTableObj_remove(php_hashtable->hashtable, key)) != MS_SUCCESS) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -171,114 +202,115 @@ PHP_METHOD(hashtableObj, remove)
    Clear all items in hash table (to NULL). */
 PHP_METHOD(hashtableObj, clear)
 {
-    zval *zobj = getThis();
-    php_hashtable_object *php_hashtable;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  php_hashtable_object *php_hashtable;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_hashtable = (php_hashtable_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    hashTableObj_clear(php_hashtable->hashtable);
+  php_hashtable = (php_hashtable_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  hashTableObj_clear(php_hashtable->hashtable);
 }
 /* }}} */
 
 /* {{{ proto int hashtable.nextkey(string previousKey)
-   Return the next key or first key if previousKey == NULL. 
+   Return the next key or first key if previousKey == NULL.
    Returns NULL if no item is in the hashTable or end of hashTable reached */
 PHP_METHOD(hashtableObj, nextKey)
 {
-    char *key;
-    long key_len;
-    zval *zobj = getThis();
-    const char *value = NULL;
-    php_hashtable_object *php_hashtable;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s!",
-                              &key, &key_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *key;
+  long key_len;
+  zval *zobj = getThis();
+  const char *value = NULL;
+  php_hashtable_object *php_hashtable;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s!",
+                            &key, &key_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_hashtable = (php_hashtable_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_hashtable = (php_hashtable_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    value = hashTableObj_nextKey(php_hashtable->hashtable, key);
+  value = hashTableObj_nextKey(php_hashtable->hashtable, key);
 
-    if (value == NULL) 
-        RETURN_NULL();
+  if (value == NULL)
+    RETURN_NULL();
 
-    RETURN_STRING(value, 1);
+  RETURN_STRING(value, 1);
 }
 /* }}} */
 
 zend_function_entry hashtable_functions[] = {
-    PHP_ME(hashtableObj, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
-    PHP_ME(hashtableObj, __get, hashtable___get_args, ZEND_ACC_PUBLIC)
-    PHP_ME(hashtableObj, __set, hashtable___set_args, ZEND_ACC_PUBLIC)
-    PHP_ME(hashtableObj, get, hashtable_get_args, ZEND_ACC_PUBLIC)
-    PHP_ME(hashtableObj, set, hashtable_set_args, ZEND_ACC_PUBLIC)
-    PHP_ME(hashtableObj, remove, hashtable_remove_args, ZEND_ACC_PUBLIC)
-    PHP_ME(hashtableObj, clear, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(hashtableObj, nextKey, hashtable_nextkey_args, ZEND_ACC_PUBLIC)
-    {NULL, NULL, NULL}
+  PHP_ME(hashtableObj, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
+  PHP_ME(hashtableObj, __get, hashtable___get_args, ZEND_ACC_PUBLIC)
+  PHP_ME(hashtableObj, __set, hashtable___set_args, ZEND_ACC_PUBLIC)
+  PHP_ME(hashtableObj, get, hashtable_get_args, ZEND_ACC_PUBLIC)
+  PHP_ME(hashtableObj, set, hashtable_set_args, ZEND_ACC_PUBLIC)
+  PHP_ME(hashtableObj, remove, hashtable_remove_args, ZEND_ACC_PUBLIC)
+  PHP_ME(hashtableObj, clear, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(hashtableObj, nextKey, hashtable_nextkey_args, ZEND_ACC_PUBLIC) {
+    NULL, NULL, NULL
+  }
 };
 
 void mapscript_create_hashtable(hashTableObj *hashtable, parent_object parent, zval *return_value TSRMLS_DC)
 {
-    php_hashtable_object * php_hashtable;
-    object_init_ex(return_value, mapscript_ce_hashtable); 
-    php_hashtable = (php_hashtable_object *)zend_object_store_get_object(return_value TSRMLS_CC);
-    php_hashtable->hashtable = hashtable;
+  php_hashtable_object * php_hashtable;
+  object_init_ex(return_value, mapscript_ce_hashtable);
+  php_hashtable = (php_hashtable_object *)zend_object_store_get_object(return_value TSRMLS_CC);
+  php_hashtable->hashtable = hashtable;
 
-    php_hashtable->parent = parent;
+  php_hashtable->parent = parent;
 
-    MAPSCRIPT_ADDREF(parent.val);
+  MAPSCRIPT_ADDREF(parent.val);
 }
 
 static void mapscript_hashtable_object_destroy(void *object TSRMLS_DC)
 {
-    php_hashtable_object *php_hashtable = (php_hashtable_object *)object;
+  php_hashtable_object *php_hashtable = (php_hashtable_object *)object;
 
-    MAPSCRIPT_FREE_OBJECT(php_hashtable);
+  MAPSCRIPT_FREE_OBJECT(php_hashtable);
 
-    MAPSCRIPT_FREE_PARENT(php_hashtable->parent);
+  MAPSCRIPT_FREE_PARENT(php_hashtable->parent);
 
-    /* We don't need to free the hashTableObj */ 
-    
-    efree(object);
+  /* We don't need to free the hashTableObj */
+
+  efree(object);
 }
 
 static zend_object_value mapscript_hashtable_object_new(zend_class_entry *ce TSRMLS_DC)
 {
-    zend_object_value retval;
-    php_hashtable_object *php_hashtable;
+  zend_object_value retval;
+  php_hashtable_object *php_hashtable;
 
-    MAPSCRIPT_ALLOC_OBJECT(php_hashtable, php_hashtable_object);
+  MAPSCRIPT_ALLOC_OBJECT(php_hashtable, php_hashtable_object);
 
-    retval = mapscript_object_new(&php_hashtable->std, ce,
-                                  &mapscript_hashtable_object_destroy TSRMLS_CC);
+  retval = mapscript_object_new(&php_hashtable->std, ce,
+                                &mapscript_hashtable_object_destroy TSRMLS_CC);
 
-    MAPSCRIPT_INIT_PARENT(php_hashtable->parent);
+  MAPSCRIPT_INIT_PARENT(php_hashtable->parent);
 
-    return retval;
+  return retval;
 }
 
 PHP_MINIT_FUNCTION(hashtable)
 {
-    zend_class_entry ce;
+  zend_class_entry ce;
+
+  MAPSCRIPT_REGISTER_CLASS("hashTableObj",
+                           hashtable_functions,
+                           mapscript_ce_hashtable,
+                           mapscript_hashtable_object_new);
 
-    MAPSCRIPT_REGISTER_CLASS("hashTableObj", 
-                             hashtable_functions,
-                             mapscript_ce_hashtable,
-                             mapscript_hashtable_object_new);
+  mapscript_ce_hashtable->ce_flags |= ZEND_ACC_FINAL_CLASS;
 
-    mapscript_ce_hashtable->ce_flags |= ZEND_ACC_FINAL_CLASS; 
-    
-    return SUCCESS;
+  return SUCCESS;
 }
diff --git a/mapscript/php/image.c b/mapscript/php/image.c
index 2c270a2..ae26394 100644
--- a/mapscript/php/image.c
+++ b/mapscript/php/image.c
@@ -2,7 +2,7 @@
  * $Id: php_mapscript.c 9765 2010-01-28 15:32:10Z aboudreault $
  *
  * Project:  MapServer
- * Purpose:  PHP/MapScript extension for MapServer.  External interface 
+ * Purpose:  PHP/MapScript extension for MapServer.  External interface
  *           functions
  * Author:   Daniel Morissette, DM Solutions Group (dmorissette at dmsolutions.ca)
  *           Alan Boudreault, Mapgears
@@ -16,16 +16,16 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
+ *
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  * DEALINGS IN THE SOFTWARE.
  **********************************************************************/
 
@@ -36,25 +36,25 @@
 zend_class_entry *mapscript_ce_image;
 
 ZEND_BEGIN_ARG_INFO_EX(image___get_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, property)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(image___set_args, 0, 0, 2)
-  ZEND_ARG_INFO(0, property)
-  ZEND_ARG_INFO(0, value)
+ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, value)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(image_pasteImage_args, 0, 0, 2)
-  ZEND_ARG_INFO(0, srcImg)
-  ZEND_ARG_INFO(0, transparentColorHex)
-  ZEND_ARG_INFO(0, dstX)
-  ZEND_ARG_INFO(0, dstY)
-  ZEND_ARG_INFO(0, angle)
+ZEND_ARG_INFO(0, srcImg)
+ZEND_ARG_INFO(0, transparentColorHex)
+ZEND_ARG_INFO(0, dstX)
+ZEND_ARG_INFO(0, dstY)
+ZEND_ARG_INFO(0, angle)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(image_saveImage_args, 0, 0, 2)
-  ZEND_ARG_INFO(0, filename)
-  ZEND_ARG_OBJ_INFO(0, map, mapObj, 0)
+ZEND_ARG_INFO(0, filename)
+ZEND_ARG_OBJ_INFO(0, map, mapObj, 0)
 ZEND_END_ARG_INFO()
 
 
@@ -62,107 +62,102 @@ ZEND_END_ARG_INFO()
    imageObj CANNOT be instanciated, this will throw an exception on use */
 PHP_METHOD(imageObj, __construct)
 {
-    mapscript_throw_exception("imageObj cannot be constructed" TSRMLS_CC);
+  mapscript_throw_exception("imageObj cannot be constructed" TSRMLS_CC);
 }
 /* }}} */
 
 PHP_METHOD(imageObj, __get)
 {
-    char *property;
-    long property_len;
-    zval *zobj = getThis();
-    php_image_object *php_image;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &property, &property_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *zobj = getThis();
+  php_image_object *php_image;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &property, &property_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_image = (php_image_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-
-    IF_GET_LONG("width", php_image->image->width)
-    else IF_GET_LONG("height", php_image->image->height) 
-    else IF_GET_LONG("resolution", php_image->image->resolution) 
-    else IF_GET_LONG("resolutionfactor", php_image->image->resolutionfactor) 
-    else IF_GET_STRING("imagepath", php_image->image->imagepath) 
-    else IF_GET_STRING("imageurl", php_image->image->imageurl) 
-    else IF_GET_STRING("imagetype", php_image->image->format->name) 
-    else 
-    {
-        mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_image = (php_image_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  IF_GET_LONG("width", php_image->image->width)
+  else IF_GET_LONG("height", php_image->image->height)
+    else IF_GET_LONG("resolution", php_image->image->resolution)
+      else IF_GET_LONG("resolutionfactor", php_image->image->resolutionfactor)
+        else IF_GET_STRING("imagepath", php_image->image->imagepath)
+          else IF_GET_STRING("imageurl", php_image->image->imageurl)
+            else IF_GET_STRING("imagetype", php_image->image->format->name)
+              else {
+                mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+              }
 }
 
 PHP_METHOD(imageObj, __set)
 {
-    char *property;
-    long property_len;
-    zval *value;
-    zval *zobj = getThis();
-    php_image_object *php_image;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
-                              &property, &property_len, &value) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *value;
+  zval *zobj = getThis();
+  php_image_object *php_image;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
+                            &property, &property_len, &value) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_image = (php_image_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-
-    IF_SET_STRING("imagepath", php_image->image->imagepath, value)
-    else IF_SET_STRING("imageurl", php_image->image->imageurl, value) 
-    else IF_SET_STRING("imagetype", php_image->image->format->name, value) 
-    else if ( (STRING_EQUAL("width", property)) ||
-              (STRING_EQUAL("resolution", property)) ||
-              (STRING_EQUAL("resolutionfactor", property)) ||
-              (STRING_EQUAL("height", property)) )
-    {
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_image = (php_image_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  IF_SET_STRING("imagepath", php_image->image->imagepath, value)
+  else IF_SET_STRING("imageurl", php_image->image->imageurl, value)
+    else IF_SET_STRING("imagetype", php_image->image->format->name, value)
+      else if ( (STRING_EQUAL("width", property)) ||
+                (STRING_EQUAL("resolution", property)) ||
+                (STRING_EQUAL("resolutionfactor", property)) ||
+                (STRING_EQUAL("height", property)) ) {
         mapscript_throw_exception("Property '%s' is read-only and cannot be set." TSRMLS_CC, property);
-    }
-    else 
-    {
+      } else {
         mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }
+      }
 }
 
 /* {{{ proto int saveWebImage()
    Writes image to temp directory.  Returns image URL. */
 PHP_METHOD(imageObj, saveWebImage)
 {
-    zval *zobj = getThis();
-    php_image_object *php_image;
-    char *imageFile = NULL;
-    char *imageFilename = NULL;
-    char path[MS_MAXPATHLEN];
-    char *imageUrlFull = NULL;
- 
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  php_image_object *php_image;
+  char *imageFile = NULL;
+  char *imageFilename = NULL;
+  char path[MS_MAXPATHLEN];
+  char *imageUrlFull = NULL;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_image = (php_image_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    imageFilename = msTmpFilename(php_image->image->format->extension);
-    imageFile = msBuildPath(path, php_image->image->imagepath, imageFilename);
+  php_image = (php_image_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    if (msSaveImage(NULL, php_image->image, imageFile) != MS_SUCCESS)
-    {
-        mapscript_throw_mapserver_exception("Failed writing image to %s" TSRMLS_CC, imageFile);
-        return;
-    }
+  imageFilename = msTmpFilename(php_image->image->format->extension);
+  imageFile = msBuildPath(path, php_image->image->imagepath, imageFilename);
+
+  if (msSaveImage(NULL, php_image->image, imageFile) != MS_SUCCESS) {
+    mapscript_throw_mapserver_exception("Failed writing image to %s" TSRMLS_CC, imageFile);
+    return;
+  }
 
-    imageUrlFull = msBuildPath(path, php_image->image->imageurl, imageFilename);
-    msFree(imageFilename);
-    
-    RETURN_STRING(imageUrlFull, 1);
+  imageUrlFull = msBuildPath(path, php_image->image->imageurl, imageFilename);
+  msFree(imageFilename);
+
+  RETURN_STRING(imageUrlFull, 1);
 }
 /* }}} */
 
@@ -179,80 +174,78 @@ PHP_METHOD(imageObj, saveWebImage)
 */
 PHP_METHOD(imageObj, pasteImage)
 {
-    long transparent=-1, dstx=0, dsty=0, angle=0;
-    int angleSet=MS_FALSE;
-    zval *zimage;
-    zval *zobj = getThis();
-    php_image_object *php_image, *php_imageSrc;
-    /*int oldTransparentColor, newTransparentColor=-1, r, g, b;*/
-    rendererVTableObj *renderer = NULL;
-    rasterBufferObj rb;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Ol|lll",
-                              &zimage, mapscript_ce_image, &transparent,
-                              &dstx, &dsty, &angle) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  long transparent=-1, dstx=0, dsty=0, angle=0;
+  int angleSet=MS_FALSE;
+  zval *zimage;
+  zval *zobj = getThis();
+  php_image_object *php_image, *php_imageSrc;
+  /*int oldTransparentColor, newTransparentColor=-1, r, g, b;*/
+  rendererVTableObj *renderer = NULL;
+  rasterBufferObj rb;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Ol|lll",
+                            &zimage, mapscript_ce_image, &transparent,
+                            &dstx, &dsty, &angle) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    if  (ZEND_NUM_ARGS() == 3) {
-        mapscript_report_php_error(E_WARNING, "dstX parameter given but not dstY" TSRMLS_CC);
-    }
-    else 
-        angleSet = MS_TRUE;
-
-    php_image = (php_image_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_imageSrc = (php_image_object *) zend_object_store_get_object(zimage TSRMLS_CC);
-        
-    if (!MS_RENDERER_PLUGIN(php_imageSrc->image->format) ||
- 	!MS_RENDERER_PLUGIN(php_image->image->format))
-        {
-            mapscript_throw_exception("PasteImage function should only be used with renderer plugin drivers." TSRMLS_CC);
-            return;
-        }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  if  (ZEND_NUM_ARGS() == 3) {
+    mapscript_report_php_error(E_WARNING, "dstX parameter given but not dstY" TSRMLS_CC);
+  } else
+    angleSet = MS_TRUE;
+
+  php_image = (php_image_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_imageSrc = (php_image_object *) zend_object_store_get_object(zimage TSRMLS_CC);
+
+  if (!MS_RENDERER_PLUGIN(php_imageSrc->image->format) ||
+      !MS_RENDERER_PLUGIN(php_image->image->format)) {
+    mapscript_throw_exception("PasteImage function should only be used with renderer plugin drivers." TSRMLS_CC);
+    return;
+  }
 
 #ifdef undef //USE_AGG
-    if( MS_RENDERER_AGG(php_imageSrc->image->format)) 
-      msAlphaAGG2GD(php_imageSrc->image); 
-    if( MS_RENDERER_AGG(php_image->image->format)) 
-      msAlphaAGG2GD(php_image->image); 
+  if( MS_RENDERER_AGG(php_imageSrc->image->format))
+    msAlphaAGG2GD(php_imageSrc->image);
+  if( MS_RENDERER_AGG(php_image->image->format))
+    msAlphaAGG2GD(php_image->image);
 #endif
 
 
-    renderer = MS_IMAGE_RENDERER(php_image->image);
-    memset(&rb,0,sizeof(rasterBufferObj));
-    
-    renderer->getRasterBufferHandle(php_imageSrc->image, &rb);
-    renderer->mergeRasterBuffer(php_image->image, &rb, 1.0, 0, 0, dstx, dsty, rb.width, rb.height);
-
-    /* Look for r,g,b in color table and make it transparent.
-     * will return -1 if there is no exact match which will result in
-     * no transparent color in the call to gdImageColorTransparent().
-     */
-/*    if (transparent != -1)
-    {
-        r = (transparent / 0x010000) & 0xff;
-        g = (transparent / 0x0100) & 0xff;
-        b = transparent & 0xff;
-        newTransparentColor = gdImageColorExact(php_imageSrc->image->img.gd, r, g, b);
-    }
+  renderer = MS_IMAGE_RENDERER(php_image->image);
+  memset(&rb,0,sizeof(rasterBufferObj));
+
+  renderer->getRasterBufferHandle(php_imageSrc->image, &rb);
+  renderer->mergeRasterBuffer(php_image->image, &rb, 1.0, 0, 0, dstx, dsty, rb.width, rb.height);
 
-    oldTransparentColor = gdImageGetTransparent(php_imageSrc->image->img.gd);
-    gdImageColorTransparent(php_imageSrc->image->img.gd, newTransparentColor);
+  /* Look for r,g,b in color table and make it transparent.
+   * will return -1 if there is no exact match which will result in
+   * no transparent color in the call to gdImageColorTransparent().
+   */
+  /*    if (transparent != -1)
+      {
+          r = (transparent / 0x010000) & 0xff;
+          g = (transparent / 0x0100) & 0xff;
+          b = transparent & 0xff;
+          newTransparentColor = gdImageColorExact(php_imageSrc->image->img.gd, r, g, b);
+      }
 
-    if (!angleSet)
-        gdImageCopy(php_image->image->img.gd, php_imageSrc->image->img.gd, dstx, dsty, 
-                    0, 0, php_imageSrc->image->img.gd->sx, php_imageSrc->image->img.gd->sy);
-    else
-        gdImageCopyRotated(php_image->image->img.gd, php_imageSrc->image->img.gd, dstx, dsty, 
-                           0, 0, php_imageSrc->image->img.gd->sx, php_imageSrc->image->img.gd->sy,
-                           angle);
+      oldTransparentColor = gdImageGetTransparent(php_imageSrc->image->img.gd);
+      gdImageColorTransparent(php_imageSrc->image->img.gd, newTransparentColor);
 
-                           gdImageColorTransparent(php_imageSrc->image->img.gd, oldTransparentColor);*/
+      if (!angleSet)
+          gdImageCopy(php_image->image->img.gd, php_imageSrc->image->img.gd, dstx, dsty,
+                      0, 0, php_imageSrc->image->img.gd->sx, php_imageSrc->image->img.gd->sy);
+      else
+          gdImageCopyRotated(php_image->image->img.gd, php_imageSrc->image->img.gd, dstx, dsty,
+                             0, 0, php_imageSrc->image->img.gd->sx, php_imageSrc->image->img.gd->sy,
+                             angle);
 
-    RETURN_LONG(MS_SUCCESS);
+                             gdImageColorTransparent(php_imageSrc->image->img.gd, oldTransparentColor);*/
+
+  RETURN_LONG(MS_SUCCESS);
 
 }
 /* }}} */
@@ -265,130 +258,129 @@ PHP_METHOD(imageObj, pasteImage)
 
 PHP_METHOD(imageObj, saveImage)
 {
-    zval *zobj = getThis();
-    zval *zmap = NULL;
-    char *filename = NULL;
-    long filename_len = 0;
-    php_image_object *php_image;
-    php_map_object *php_map;
-    int status = MS_SUCCESS;
-    /* stdout specific vars */
-    int size=0;
-    void *iptr=NULL;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sO",
-                              &filename, &filename_len,
-                              &zmap, mapscript_ce_map) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  zval *zmap = NULL;
+  char *filename = NULL;
+  long filename_len = 0;
+  php_image_object *php_image;
+  php_map_object *php_map;
+  int status = MS_SUCCESS;
+  /* stdout specific vars */
+  int size=0;
+  void *iptr=NULL;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sO",
+                            &filename, &filename_len,
+                            &zmap, mapscript_ce_map) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_image = (php_image_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    if (zmap)
-        php_map = (php_map_object *) zend_object_store_get_object(zmap TSRMLS_CC);
-
-    if(filename_len > 0)
-    {
-        if ((status = msSaveImage((zmap ? php_map->map:NULL), php_image->image, filename) != MS_SUCCESS))
-        {
-            mapscript_throw_mapserver_exception("Failed writing image to %s" TSRMLS_CC, filename);
-            return;
-        }
-
-        RETURN_LONG(status);
-    }
-
-    /* no filename - read stdout */
-
-    /* if there is no output buffer active, set the header */
-    if (OG(ob_nesting_level)<=0)
-    {
-        php_header(TSRMLS_C);
-    }
-   
-
-    if (MS_RENDERER_PLUGIN(php_image->image->format))
-    {
-        iptr = (void *)msSaveImageBuffer(php_image->image, &size, php_image->image->format);
-    }
-    else if (php_image->image->format->name && (strcasecmp(php_image->image->format->name, "imagemap")==0))
-    {
-        iptr = php_image->image->img.imagemap;
-        size = strlen(php_image->image->img.imagemap);
-    }
-
-    if (size == 0) {
-        mapscript_throw_mapserver_exception("Failed writing image to stdout" TSRMLS_CC);
-        return;
-    } 
-    else
-    {
-        php_write(iptr, size TSRMLS_CC);
-        status = MS_SUCCESS;
-        /* status = size;  why should we return the size ?? */
-        gdFree(iptr);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_image = (php_image_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  if (zmap)
+    php_map = (php_map_object *) zend_object_store_get_object(zmap TSRMLS_CC);
+
+  if(filename_len > 0) {
+    if ((status = msSaveImage((zmap ? php_map->map:NULL), php_image->image, filename) != MS_SUCCESS)) {
+      mapscript_throw_mapserver_exception("Failed writing image to %s" TSRMLS_CC, filename);
+      return;
     }
 
     RETURN_LONG(status);
+  }
+
+  /* no filename - read stdout */
+
+  /* if there is no output buffer active, set the header */
+  //handle changes in PHP 5.4.x
+#if PHP_VERSION_ID < 50399
+  if (OG(ob_nesting_level)<=0) {
+    php_header(TSRMLS_C);
+  }
+#else
+  if (php_output_get_level(TSRMLS_C)<=0) {
+    php_header(TSRMLS_C);
+  }
+#endif
+
+  if (MS_RENDERER_PLUGIN(php_image->image->format)) {
+    iptr = (void *)msSaveImageBuffer(php_image->image, &size, php_image->image->format);
+  } else if (php_image->image->format->name && (strcasecmp(php_image->image->format->name, "imagemap")==0)) {
+    iptr = php_image->image->img.imagemap;
+    size = strlen(php_image->image->img.imagemap);
+  }
+
+  if (size == 0) {
+    mapscript_throw_mapserver_exception("Failed writing image to stdout" TSRMLS_CC);
+    return;
+  } else {
+    php_write(iptr, size TSRMLS_CC);
+    status = MS_SUCCESS;
+    /* status = size;  why should we return the size ?? */
+    msFree(iptr);
+  }
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
 zend_function_entry image_functions[] = {
-    PHP_ME(imageObj, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
-    PHP_ME(imageObj, __get, image___get_args, ZEND_ACC_PUBLIC)
-    PHP_ME(imageObj, __set, image___set_args, ZEND_ACC_PUBLIC)
-    PHP_MALIAS(imageObj, set, __set, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(imageObj, saveWebImage, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(imageObj, pasteImage, image_pasteImage_args, ZEND_ACC_PUBLIC)
-    PHP_ME(imageObj, saveImage, image_saveImage_args, ZEND_ACC_PUBLIC)
-    {NULL, NULL, NULL}
+  PHP_ME(imageObj, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
+  PHP_ME(imageObj, __get, image___get_args, ZEND_ACC_PUBLIC)
+  PHP_ME(imageObj, __set, image___set_args, ZEND_ACC_PUBLIC)
+  PHP_MALIAS(imageObj, set, __set, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(imageObj, saveWebImage, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(imageObj, pasteImage, image_pasteImage_args, ZEND_ACC_PUBLIC)
+  PHP_ME(imageObj, saveImage, image_saveImage_args, ZEND_ACC_PUBLIC) {
+    NULL, NULL, NULL
+  }
 };
 
 
 void mapscript_create_image(imageObj *image, zval *return_value TSRMLS_DC)
 {
-    php_image_object * php_image;
-    object_init_ex(return_value, mapscript_ce_image); 
-    php_image = (php_image_object *)zend_object_store_get_object(return_value TSRMLS_CC);
-    php_image->image = image;    
+  php_image_object * php_image;
+  object_init_ex(return_value, mapscript_ce_image);
+  php_image = (php_image_object *)zend_object_store_get_object(return_value TSRMLS_CC);
+  php_image->image = image;
 }
 
 static void mapscript_image_object_destroy(void *object TSRMLS_DC)
 {
-    php_image_object *php_image = (php_image_object *)object;
+  php_image_object *php_image = (php_image_object *)object;
 
-    MAPSCRIPT_FREE_OBJECT(php_image);
+  MAPSCRIPT_FREE_OBJECT(php_image);
 
-    msFreeImage(php_image->image);
-    
-    efree(object);
+  msFreeImage(php_image->image);
+
+  efree(object);
 }
 
 static zend_object_value mapscript_image_object_new(zend_class_entry *ce TSRMLS_DC)
 {
-    zend_object_value retval;
-    php_image_object *php_image;
+  zend_object_value retval;
+  php_image_object *php_image;
 
-    MAPSCRIPT_ALLOC_OBJECT(php_image, php_image_object);
+  MAPSCRIPT_ALLOC_OBJECT(php_image, php_image_object);
 
-    retval = mapscript_object_new(&php_image->std, ce,
-                                  &mapscript_image_object_destroy TSRMLS_CC);
+  retval = mapscript_object_new(&php_image->std, ce,
+                                &mapscript_image_object_destroy TSRMLS_CC);
 
-    return retval;
+  return retval;
 }
 
 PHP_MINIT_FUNCTION(image)
 {
-    zend_class_entry ce;
+  zend_class_entry ce;
+
+  MAPSCRIPT_REGISTER_CLASS("imageObj",
+                           image_functions,
+                           mapscript_ce_image,
+                           mapscript_image_object_new);
 
-    MAPSCRIPT_REGISTER_CLASS("imageObj", 
-                             image_functions,
-                             mapscript_ce_image,
-                             mapscript_image_object_new);
+  mapscript_ce_image->ce_flags |= ZEND_ACC_FINAL_CLASS;
 
-    mapscript_ce_image->ce_flags |= ZEND_ACC_FINAL_CLASS; 
-    
-    return SUCCESS;
+  return SUCCESS;
 }
diff --git a/mapscript/php/label.c b/mapscript/php/label.c
index 95ab2ea..1ca908b 100644
--- a/mapscript/php/label.c
+++ b/mapscript/php/label.c
@@ -1,9 +1,8 @@
-
 /**********************************************************************
  * $Id: php_mapscript.c 9765 2010-01-28 15:32:10Z aboudreault $
  *
  * Project:  MapServer
- * Purpose:  PHP/MapScript extension for MapServer.  External interface 
+ * Purpose:  PHP/MapScript extension for MapServer.  External interface
  *           functions
  * Author:   Daniel Morissette, DM Solutions Group (dmorissette at dmsolutions.ca)
  *           Alan Boudreault, Mapgears
@@ -17,218 +16,241 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
+ *
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  * DEALINGS IN THE SOFTWARE.
  **********************************************************************/
 
 #include "php_mapscript.h"
 
 zend_class_entry *mapscript_ce_label;
+zend_object_handlers mapscript_label_object_handlers;
 
 ZEND_BEGIN_ARG_INFO_EX(label___get_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, property)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(label___set_args, 0, 0, 2)
-  ZEND_ARG_INFO(0, property)
-  ZEND_ARG_INFO(0, value)
+ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, value)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(label_updateFromString_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, snippet)
+ZEND_ARG_INFO(0, snippet)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(label_setBinding_args, 0, 0, 2)
-  ZEND_ARG_INFO(0, labelBinding)
-  ZEND_ARG_INFO(0, value)
+ZEND_ARG_INFO(0, labelBinding)
+ZEND_ARG_INFO(0, value)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(label_getBinding_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, labelBinding)
+ZEND_ARG_INFO(0, labelBinding)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(label_removeBinding_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, labelBinding)
+ZEND_ARG_INFO(0, labelBinding)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(label_getStyle_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, index)
+ZEND_ARG_INFO(0, index)
+ZEND_END_ARG_INFO()
+
+ZEND_BEGIN_ARG_INFO_EX(label_insertStyle_args, 0, 0, 1)
+ZEND_ARG_OBJ_INFO(0, style, styleObj, 0)
+ZEND_ARG_INFO(0, index)
+ZEND_END_ARG_INFO()
+
+ZEND_BEGIN_ARG_INFO_EX(label_removeStyle_args, 0, 0, 1)
+ZEND_ARG_INFO(0, index)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(label_moveStyleUp_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, index)
+ZEND_ARG_INFO(0, index)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(label_moveStyleDown_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, index)
+ZEND_ARG_INFO(0, index)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(label_deleteStyle_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, index)
+ZEND_ARG_INFO(0, index)
 ZEND_END_ARG_INFO()
 
-/* {{{ proto void __construct() 
-   labelObj CANNOT be instanciated, this will throw an exception on use */
+/* {{{ proto void __construct()
+   Create a new label instance. */
 PHP_METHOD(labelObj, __construct)
 {
-    mapscript_throw_exception("labelObj cannot be constructed" TSRMLS_CC);
+  php_label_object *php_label;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
+    PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_label = (php_label_object *)zend_object_store_get_object(getThis() TSRMLS_CC);
+
+  if ((php_label->label = labelObj_new()) == NULL) {
+    mapscript_throw_exception("Unable to construct labelObj." TSRMLS_CC);
+    return;
+  }
 }
 /* }}} */
 
 PHP_METHOD(labelObj, __get)
 {
-    char *property;
-    long property_len;
-    zval *zobj = getThis();
-    php_label_object *php_label;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &property, &property_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *zobj = getThis();
+  php_label_object *php_label;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &property, &property_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_label = (php_label_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    IF_GET_STRING("font",  php_label->label->font)
-    else IF_GET_STRING("encoding", php_label->label->encoding)
+  php_label = (php_label_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  IF_GET_STRING("font",  php_label->label->font)
+  else IF_GET_STRING("encoding", php_label->label->encoding)
     else IF_GET_LONG("type", php_label->label->type)
-    else IF_GET_LONG("shadowsizex",  php_label->label->shadowsizex)
-    else IF_GET_LONG("shadowsizey",  php_label->label->shadowsizey)
-    else IF_GET_DOUBLE("size", php_label->label->size)
-    else IF_GET_DOUBLE("minsize", php_label->label->minsize)
-    else IF_GET_DOUBLE("maxsize", php_label->label->maxsize)
-    else IF_GET_LONG("position", php_label->label->position)
-    else IF_GET_LONG("offsetx", php_label->label->offsetx)
-    else IF_GET_LONG("offsety", php_label->label->offsety)
-    else IF_GET_DOUBLE("angle", php_label->label->angle)
-    else IF_GET_LONG("anglemode", php_label->label->anglemode)
-    else IF_GET_LONG("buffer", php_label->label->buffer)
-    else IF_GET_LONG("antialias", php_label->label->antialias)
-    else IF_GET_LONG("wrap", php_label->label->wrap)
-    else IF_GET_LONG("minfeaturesize", php_label->label->minfeaturesize)
-    else IF_GET_LONG("autominfeaturesize", php_label->label->autominfeaturesize)
-    else IF_GET_LONG("repeatdistance", php_label->label->repeatdistance)
-    else IF_GET_LONG("numstyles", php_label->label->numstyles) 
-    else IF_GET_LONG("mindistance", php_label->label->mindistance)
-    else IF_GET_LONG("partials", php_label->label->partials)
-    else IF_GET_LONG("force", php_label->label->force)
-    else IF_GET_LONG("outlinewidth", php_label->label->outlinewidth)
-    else IF_GET_LONG("align", php_label->label->align)
-    else IF_GET_LONG("maxlength", php_label->label->maxlength)
-    else IF_GET_LONG("minlength", php_label->label->minlength)
-    else IF_GET_LONG("maxoverlapangle", php_label->label->maxoverlapangle)
-    else IF_GET_LONG("priority", php_label->label->priority)
-    else IF_GET_OBJECT("color", mapscript_ce_color, php_label->color, &php_label->label->color) 
-    else IF_GET_OBJECT("outlinecolor", mapscript_ce_color, php_label->outlinecolor, &php_label->label->outlinecolor) 
-    else IF_GET_OBJECT("shadowcolor", mapscript_ce_color, php_label->shadowcolor, &php_label->label->shadowcolor) 
-    else 
-    {
-        mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }
+      else IF_GET_LONG("shadowsizex",  php_label->label->shadowsizex)
+        else IF_GET_LONG("shadowsizey",  php_label->label->shadowsizey)
+          else IF_GET_DOUBLE("size", php_label->label->size)
+            else IF_GET_DOUBLE("minsize", php_label->label->minsize)
+              else IF_GET_DOUBLE("maxsize", php_label->label->maxsize)
+                else IF_GET_DOUBLE("minscaledenom", php_label->label->minscaledenom)
+                  else IF_GET_DOUBLE("maxscaledenom", php_label->label->maxscaledenom)
+                    else IF_GET_LONG("position", php_label->label->position)
+                      else IF_GET_LONG("offsetx", php_label->label->offsetx)
+                        else IF_GET_LONG("offsety", php_label->label->offsety)
+                          else IF_GET_DOUBLE("angle", php_label->label->angle)
+                            else IF_GET_LONG("anglemode", php_label->label->anglemode)
+                              else IF_GET_LONG("buffer", php_label->label->buffer)
+                                else IF_GET_LONG("antialias", php_label->label->antialias)
+                                  else IF_GET_LONG("wrap", php_label->label->wrap)
+                                    else IF_GET_LONG("minfeaturesize", php_label->label->minfeaturesize)
+                                      else IF_GET_LONG("autominfeaturesize", php_label->label->autominfeaturesize)
+                                        else IF_GET_LONG("repeatdistance", php_label->label->repeatdistance)
+                                          else IF_GET_LONG("numstyles", php_label->label->numstyles)
+                                            else IF_GET_LONG("mindistance", php_label->label->mindistance)
+                                              else IF_GET_LONG("partials", php_label->label->partials)
+                                                else IF_GET_LONG("force", php_label->label->force)
+                                                  else IF_GET_LONG("outlinewidth", php_label->label->outlinewidth)
+                                                    else IF_GET_LONG("align", php_label->label->align)
+                                                      else IF_GET_LONG("maxlength", php_label->label->maxlength)
+                                                        else IF_GET_LONG("minlength", php_label->label->minlength)
+                                                          else IF_GET_LONG("maxoverlapangle", php_label->label->maxoverlapangle)
+                                                            else IF_GET_LONG("priority", php_label->label->priority)
+                                                              else IF_GET_OBJECT("color", mapscript_ce_color, php_label->color, &php_label->label->color)
+                                                                else IF_GET_OBJECT("leader", mapscript_ce_labelleader, php_label->leader, &php_label->label->leader)
+                                                                  else IF_GET_OBJECT("outlinecolor", mapscript_ce_color, php_label->outlinecolor, &php_label->label->outlinecolor)
+                                                                    else IF_GET_OBJECT("shadowcolor", mapscript_ce_color, php_label->shadowcolor, &php_label->label->shadowcolor)
+                                                                      else {
+                                                                        mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+                                                                      }
 }
 
 PHP_METHOD(labelObj, __set)
 {
-    char *property;
-    long property_len;
-    zval *value;
-    zval *zobj = getThis();
-    php_label_object *php_label;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
-                              &property, &property_len, &value) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *value;
+  zval *zobj = getThis();
+  php_label_object *php_label;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
+                            &property, &property_len, &value) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_label = (php_label_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_label = (php_label_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    IF_SET_STRING("font",  php_label->label->font, value)
-    else IF_SET_STRING("encoding", php_label->label->encoding, value)
+  IF_SET_STRING("font",  php_label->label->font, value)
+  else IF_SET_STRING("encoding", php_label->label->encoding, value)
     else IF_SET_LONG("type", php_label->label->type, value)
-    else IF_SET_LONG("shadowsizex",  php_label->label->shadowsizex, value)
-    else IF_SET_LONG("shadowsizey",  php_label->label->shadowsizey, value)
-    else IF_SET_DOUBLE("size", php_label->label->size, value)
-    else IF_SET_DOUBLE("minsize", php_label->label->minsize, value)
-    else IF_SET_DOUBLE("maxsize", php_label->label->maxsize, value)
-    else IF_SET_LONG("position", php_label->label->position, value)
-    else IF_SET_LONG("offsetx", php_label->label->offsetx, value)
-    else IF_SET_LONG("offsety", php_label->label->offsety, value)
-    else IF_SET_DOUBLE("angle", php_label->label->angle, value)
-    else IF_SET_LONG("anglemode", php_label->label->anglemode, value)
-    else IF_SET_LONG("buffer", php_label->label->buffer, value)
-    else IF_SET_LONG("antialias", php_label->label->antialias, value)
-    else IF_SET_BYTE("wrap", php_label->label->wrap, value)
-    else IF_SET_LONG("minfeaturesize", php_label->label->minfeaturesize, value)
-    else IF_SET_LONG("autominfeaturesize", php_label->label->autominfeaturesize, value)
-    else IF_SET_LONG("repeatdistance", php_label->label->repeatdistance, value)
-    else IF_SET_LONG("mindistance", php_label->label->mindistance, value)
-    else IF_SET_LONG("partials", php_label->label->partials, value)
-    else IF_SET_LONG("force", php_label->label->force, value)
-    else IF_SET_LONG("outlinewidth", php_label->label->outlinewidth, value)
-    else IF_SET_LONG("align", php_label->label->align, value)
-    else IF_SET_LONG("maxlength", php_label->label->maxlength, value)
-    else IF_SET_LONG("minlength", php_label->label->minlength, value)
-    else IF_SET_LONG("maxoverlapangle", php_label->label->maxoverlapangle, value)
-    else IF_SET_LONG("priority", php_label->label->priority, value)
-    else if ( (STRING_EQUAL("color", property)) ||
-              (STRING_EQUAL("outlinecolor", property)) ||
-              (STRING_EQUAL("shadowcolor", property)) )
-    {
-        mapscript_throw_exception("Property '%s' is an object and can only be modified through its accessors." TSRMLS_CC, property);
-    }
-    else if (STRING_EQUAL("numstyles", property))
-    {
-        mapscript_throw_exception("Property '%s' is read-only and cannot be set." TSRMLS_CC, property);
-    }
-    else 
-    {
-        mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }
-         
+      else IF_SET_LONG("shadowsizex",  php_label->label->shadowsizex, value)
+        else IF_SET_LONG("shadowsizey",  php_label->label->shadowsizey, value)
+          else IF_SET_DOUBLE("size", php_label->label->size, value)
+            else IF_SET_DOUBLE("minsize", php_label->label->minsize, value)
+              else IF_SET_DOUBLE("maxsize", php_label->label->maxsize, value)
+                else IF_SET_LONG("position", php_label->label->position, value)
+                  else IF_SET_LONG("offsetx", php_label->label->offsetx, value)
+                    else IF_SET_LONG("offsety", php_label->label->offsety, value)
+                      else IF_SET_DOUBLE("angle", php_label->label->angle, value)
+                        else IF_SET_LONG("anglemode", php_label->label->anglemode, value)
+                          else IF_SET_LONG("buffer", php_label->label->buffer, value)
+                            else IF_SET_LONG("antialias", php_label->label->antialias, value)
+                              else IF_SET_BYTE("wrap", php_label->label->wrap, value)
+                                else IF_SET_LONG("minfeaturesize", php_label->label->minfeaturesize, value)
+                                  else IF_SET_LONG("autominfeaturesize", php_label->label->autominfeaturesize, value)
+                                    else IF_SET_LONG("repeatdistance", php_label->label->repeatdistance, value)
+                                      else IF_SET_LONG("mindistance", php_label->label->mindistance, value)
+                                        else IF_SET_LONG("partials", php_label->label->partials, value)
+                                          else IF_SET_LONG("force", php_label->label->force, value)
+                                            else IF_SET_LONG("outlinewidth", php_label->label->outlinewidth, value)
+                                              else IF_SET_LONG("align", php_label->label->align, value)
+                                                else IF_SET_LONG("maxlength", php_label->label->maxlength, value)
+                                                  else IF_SET_LONG("minlength", php_label->label->minlength, value)
+                                                    else IF_SET_LONG("maxoverlapangle", php_label->label->maxoverlapangle, value)
+                                                      else IF_SET_LONG("priority", php_label->label->priority, value)
+                                                        else IF_SET_DOUBLE("maxscaledenom", php_label->label->maxscaledenom, value)
+                                                          else IF_SET_DOUBLE("minscaledenom", php_label->label->minscaledenom, value)
+                                                            else if ( (STRING_EQUAL("color", property)) ||
+                                                                      (STRING_EQUAL("outlinecolor", property)) ||
+                                                                      (STRING_EQUAL("leader", property)) ||
+                                                                      (STRING_EQUAL("shadowcolor", property)) ) {
+                                                              mapscript_throw_exception("Property '%s' is an object and can only be modified through its accessors." TSRMLS_CC, property);
+                                                            } else if (STRING_EQUAL("numstyles", property)) {
+                                                              mapscript_throw_exception("Property '%s' is read-only and cannot be set." TSRMLS_CC, property);
+                                                            } else {
+                                                              mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+                                                            }
+
 }
 
 /* {{{ proto int label.updateFromString(string snippet)
    Update a label from a string snippet.  Returns MS_SUCCESS/MS_FAILURE */
 PHP_METHOD(labelObj, updateFromString)
 {
-    zval *zobj = getThis();
-    char *snippet;
-    long snippet_len;
-    int status = MS_FAILURE;
-    php_label_object *php_label;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &snippet, &snippet_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  char *snippet;
+  long snippet_len;
+  int status = MS_FAILURE;
+  php_label_object *php_label;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &snippet, &snippet_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_label = (php_label_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_label = (php_label_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    if ((status = labelObj_updateFromString(php_label->label, snippet)) != MS_SUCCESS)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
+  if ((status = labelObj_updateFromString(php_label->label, snippet)) != MS_SUCCESS) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
 
-    RETURN_LONG(status);
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -236,81 +258,76 @@ PHP_METHOD(labelObj, updateFromString)
    Set the attribute binding for a specfiled label property. Returns MS_SUCCESS on success. */
 PHP_METHOD(labelObj, setBinding)
 {
-    zval *zobj = getThis();
-    char *value;
-    long value_len;
-    long bindingId;
-    php_label_object *php_label;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ls",
-                              &bindingId, &value, &value_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  char *value;
+  long value_len;
+  long bindingId;
+  php_label_object *php_label;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ls",
+                            &bindingId, &value, &value_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_label = (php_label_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_label = (php_label_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    if (bindingId < 0 || bindingId > MS_LABEL_BINDING_LENGTH)
-    {
-        mapscript_throw_exception("Invalid binding id." TSRMLS_CC);
-        return;
-    }
+  if (bindingId < 0 || bindingId > MS_LABEL_BINDING_LENGTH) {
+    mapscript_throw_exception("Invalid binding id." TSRMLS_CC);
+    return;
+  }
 
-    if (!value || strlen(value) <= 0)
-    {
-        mapscript_throw_exception("Invalid binding value." TSRMLS_CC);
-        return;
-    }
+  if (!value || strlen(value) <= 0) {
+    mapscript_throw_exception("Invalid binding value." TSRMLS_CC);
+    return;
+  }
 
-    if(php_label->label->bindings[bindingId].item) 
-    {
-        msFree(php_label->label->bindings[bindingId].item);
-        php_label->label->bindings[bindingId].index = -1; 
-        php_label->label->numbindings--;
-    }
+  if(php_label->label->bindings[bindingId].item) {
+    msFree(php_label->label->bindings[bindingId].item);
+    php_label->label->bindings[bindingId].index = -1;
+    php_label->label->numbindings--;
+  }
 
-    php_label->label->bindings[bindingId].item = strdup(value); 
-    php_label->label->numbindings++;
+  php_label->label->bindings[bindingId].item = strdup(value);
+  php_label->label->numbindings++;
 
-    RETURN_LONG(MS_SUCCESS);
+  RETURN_LONG(MS_SUCCESS);
 }
 /* }}} */
 
 /* {{{ proto int label.getbinding(const bindingid)
-   Get the value of a attribute binding for a specfiled label property. 
+   Get the value of a attribute binding for a specfiled label property.
    Returns the string value if exist, else null. */
 PHP_METHOD(labelObj, getBinding)
 {
-    zval *zobj = getThis();
-    long bindingId;
-    char *value = NULL;
-    php_label_object *php_label;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
-                              &bindingId) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  long bindingId;
+  char *value = NULL;
+  php_label_object *php_label;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
+                            &bindingId) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_label = (php_label_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-
-    if (bindingId < 0 || bindingId > MS_LABEL_BINDING_LENGTH)
-    {
-        mapscript_throw_exception("Invalid binding id." TSRMLS_CC);
-        return;
-    }
-
-    if( (value = php_label->label->bindings[bindingId].item) != NULL)
-    {
-       RETURN_STRING(value, 1);                
-    }
-
-    RETURN_NULL();
-    
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_label = (php_label_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  if (bindingId < 0 || bindingId > MS_LABEL_BINDING_LENGTH) {
+    mapscript_throw_exception("Invalid binding id." TSRMLS_CC);
+    return;
+  }
+
+  if( (value = php_label->label->bindings[bindingId].item) != NULL) {
+    RETURN_STRING(value, 1);
+  }
+
+  RETURN_NULL();
+
 }
 /* }}} */
 
@@ -318,37 +335,35 @@ PHP_METHOD(labelObj, getBinding)
    Remove attribute binding for a specfiled label property. Returns MS_SUCCESS on success. */
 PHP_METHOD(labelObj, removeBinding)
 {
-    zval *zobj = getThis();
-    long bindingId;
-    php_label_object *php_label;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
-                              &bindingId) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  long bindingId;
+  php_label_object *php_label;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
+                            &bindingId) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_label = (php_label_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-
-    if (bindingId < 0 || bindingId > MS_LABEL_BINDING_LENGTH)
-    {
-        mapscript_throw_exception("Invalid binding id." TSRMLS_CC);
-        return;
-    }
-
-
-    if(php_label->label->bindings[bindingId].item) 
-    {
-        msFree(php_label->label->bindings[bindingId].item);
-        php_label->label->bindings[bindingId].item =  NULL;
-        php_label->label->bindings[bindingId].index = -1; 
-        php_label->label->numbindings--;
-    }
-
-    RETURN_LONG(MS_SUCCESS);
-    
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_label = (php_label_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  if (bindingId < 0 || bindingId > MS_LABEL_BINDING_LENGTH) {
+    mapscript_throw_exception("Invalid binding id." TSRMLS_CC);
+    return;
+  }
+
+
+  if(php_label->label->bindings[bindingId].item) {
+    msFree(php_label->label->bindings[bindingId].item);
+    php_label->label->bindings[bindingId].item =  NULL;
+    php_label->label->bindings[bindingId].index = -1;
+    php_label->label->numbindings--;
+  }
+
+  RETURN_LONG(MS_SUCCESS);
+
 }
 /* }}} */
 
@@ -356,104 +371,156 @@ PHP_METHOD(labelObj, removeBinding)
    return the style object. */
 PHP_METHOD(labelObj, getStyle)
 {
-    long index;
-    zval *zobj = getThis();
-    php_label_object *php_label;
-    styleObj *style = NULL;
-    parent_object parent;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
-                              &index) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  long index;
+  zval *zobj = getThis();
+  php_label_object *php_label;
+  styleObj *style = NULL;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
+                            &index) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_label = (php_label_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-
-    if (index < 0 || index >= php_label->label->numstyles)
-    {
-        mapscript_throw_exception("Invalid style index." TSRMLS_CC);
-        return;
-    }
-    
-    style = php_label->label->styles[index];
-
-    MAPSCRIPT_MAKE_PARENT(zobj, NULL);
-    mapscript_create_style(style, parent, return_value TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_label = (php_label_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  if (index < 0 || index >= php_label->label->numstyles) {
+    mapscript_throw_exception("Invalid style index." TSRMLS_CC);
+    return;
+  }
+
+  style = php_label->label->styles[index];
+
+  MAPSCRIPT_MAKE_PARENT(zobj, NULL);
+  mapscript_create_style(style, parent, return_value TSRMLS_CC);
+}
+/* }}} */
+
+/* {{{ proto int insertStyle(styleObj style)
+   return MS_SUCCESS or MS_FAILURE. */
+PHP_METHOD(labelObj, insertStyle)
+{
+  zval *zobj = getThis();
+  zval *zstyle = NULL;
+  long index = -1;
+  php_label_object *php_label;
+  php_style_object *php_style;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O|l",
+                            &zstyle, mapscript_ce_style, &index) == FAILURE) {
+    PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_label = (php_label_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_style = (php_style_object *) zend_object_store_get_object(zstyle TSRMLS_CC);
+
+  RETURN_LONG(msInsertLabelStyle(php_label->label, php_style->style, index));
+}
+/* }}} */
+
+/* {{{ proto styleObj removeStyle(int index)
+   return the styleObj removed. */
+PHP_METHOD(labelObj, removeStyle)
+{
+  zval *zobj = getThis();
+  long index;
+  styleObj *style;
+  php_label_object *php_label;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
+                            &index) == FAILURE) {
+    PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_label = (php_label_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  style = msRemoveLabelStyle(php_label->label, index);
+
+  /* Return a copy of the class object just removed */
+  MAPSCRIPT_MAKE_PARENT(NULL, NULL);
+  mapscript_create_style(style, parent, return_value TSRMLS_CC);
 }
 /* }}} */
 
 /* {{{ proto int moveStyleUp(int index)  */
 PHP_METHOD(labelObj, moveStyleUp)
 {
-    long index;
-    zval *zobj = getThis();
-    php_label_object *php_label;
-    int status = MS_FAILURE;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
-                              &index) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  long index;
+  zval *zobj = getThis();
+  php_label_object *php_label;
+  int status = MS_FAILURE;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
+                            &index) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_label = (php_label_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_label = (php_label_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    status = labelObj_moveStyleUp(php_label->label, index);
+  status = labelObj_moveStyleUp(php_label->label, index);
 
-    RETURN_LONG(status);
+  RETURN_LONG(status);
 }
 /* }}} */
 
 /* {{{ proto int moveStyleDown(int index) */
 PHP_METHOD(labelObj, moveStyleDown)
 {
-    long index;
-    zval *zobj = getThis();
-    php_label_object *php_label;
-    int status = MS_FAILURE;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
-                              &index) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  long index;
+  zval *zobj = getThis();
+  php_label_object *php_label;
+  int status = MS_FAILURE;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
+                            &index) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_label = (php_label_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    status = labelObj_moveStyleDown(php_label->label, index);
+  php_label = (php_label_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    RETURN_LONG(status);
+  status = labelObj_moveStyleDown(php_label->label, index);
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
- /* {{{ proto int deleteStyle(int index) */
+/* {{{ proto int deleteStyle(int index) */
 PHP_METHOD(labelObj, deleteStyle)
 {
-    long index;
-    zval *zobj = getThis();
-    php_label_object *php_label;
-    int status = MS_FAILURE;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
-                              &index) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  long index;
+  zval *zobj = getThis();
+  php_label_object *php_label;
+  int status = MS_FAILURE;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
+                            &index) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_label = (php_label_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_label = (php_label_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    status =  labelObj_deleteStyle(php_label->label, index);
+  status =  labelObj_deleteStyle(php_label->label, index);
 
-    RETURN_LONG(status);
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -461,99 +528,136 @@ PHP_METHOD(labelObj, deleteStyle)
    Free the object */
 PHP_METHOD(labelObj, free)
 {
-    zval *zobj = getThis();
-    php_label_object *php_label;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  php_label_object *php_label;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_label = (php_label_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_label = (php_label_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    MAPSCRIPT_DELREF(php_label->color);
-    MAPSCRIPT_DELREF(php_label->outlinecolor);
-    MAPSCRIPT_DELREF(php_label->shadowcolor);
+  MAPSCRIPT_DELREF(php_label->color);
+  MAPSCRIPT_DELREF(php_label->outlinecolor);
+  MAPSCRIPT_DELREF(php_label->shadowcolor);
 }
 /* }}} */
 
 zend_function_entry label_functions[] = {
-    PHP_ME(labelObj, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
-    PHP_ME(labelObj, __get, label___get_args, ZEND_ACC_PUBLIC)
-    PHP_ME(labelObj, __set, label___set_args, ZEND_ACC_PUBLIC)
-    PHP_MALIAS(labelObj, set, __set, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(labelObj, updateFromString, label_updateFromString_args, ZEND_ACC_PUBLIC)
-    PHP_ME(labelObj, setBinding, label_setBinding_args, ZEND_ACC_PUBLIC)
-    PHP_ME(labelObj, getBinding, label_getBinding_args, ZEND_ACC_PUBLIC)
-    PHP_ME(labelObj, removeBinding, label_removeBinding_args, ZEND_ACC_PUBLIC)
-    PHP_ME(labelObj, getStyle, label_getStyle_args, ZEND_ACC_PUBLIC)
-    PHP_ME(labelObj, moveStyleUp, label_moveStyleUp_args, ZEND_ACC_PUBLIC)
-    PHP_ME(labelObj, moveStyleDown, label_moveStyleDown_args, ZEND_ACC_PUBLIC)
-    PHP_ME(labelObj, deleteStyle, label_deleteStyle_args, ZEND_ACC_PUBLIC)
-    PHP_ME(labelObj, free, NULL, ZEND_ACC_PUBLIC)
-    {NULL, NULL, NULL}
+  PHP_ME(labelObj, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
+  PHP_ME(labelObj, __get, label___get_args, ZEND_ACC_PUBLIC)
+  PHP_ME(labelObj, __set, label___set_args, ZEND_ACC_PUBLIC)
+  PHP_MALIAS(labelObj, set, __set, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(labelObj, updateFromString, label_updateFromString_args, ZEND_ACC_PUBLIC)
+  PHP_ME(labelObj, setBinding, label_setBinding_args, ZEND_ACC_PUBLIC)
+  PHP_ME(labelObj, getBinding, label_getBinding_args, ZEND_ACC_PUBLIC)
+  PHP_ME(labelObj, removeBinding, label_removeBinding_args, ZEND_ACC_PUBLIC)
+  PHP_ME(labelObj, getStyle, label_getStyle_args, ZEND_ACC_PUBLIC)
+  PHP_ME(labelObj, insertStyle, label_insertStyle_args, ZEND_ACC_PUBLIC)
+  PHP_ME(labelObj, removeStyle, label_removeStyle_args, ZEND_ACC_PUBLIC)
+  PHP_ME(labelObj, moveStyleUp, label_moveStyleUp_args, ZEND_ACC_PUBLIC)
+  PHP_ME(labelObj, moveStyleDown, label_moveStyleDown_args, ZEND_ACC_PUBLIC)
+  PHP_ME(labelObj, deleteStyle, label_deleteStyle_args, ZEND_ACC_PUBLIC)
+  PHP_ME(labelObj, free, NULL, ZEND_ACC_PUBLIC) {
+    NULL, NULL, NULL
+  }
 };
 
 
 void mapscript_create_label(labelObj *label, parent_object parent, zval *return_value TSRMLS_DC)
 {
-    php_label_object * php_label;
-    object_init_ex(return_value, mapscript_ce_label); 
-    php_label = (php_label_object *)zend_object_store_get_object(return_value TSRMLS_CC);
-    php_label->label = label;
-
-    php_label->parent = parent;
-    
-    MAPSCRIPT_ADDREF(parent.val);
+  php_label_object * php_label;
+  object_init_ex(return_value, mapscript_ce_label);
+  php_label = (php_label_object *)zend_object_store_get_object(return_value TSRMLS_CC);
+  php_label->label = label;
+
+  if (parent.val)
+    php_label->is_ref = 1;
+
+  php_label->parent = parent;
+  MAPSCRIPT_ADDREF(parent.val);
 }
 
 static void mapscript_label_object_destroy(void *object TSRMLS_DC)
 {
-    php_label_object *php_label = (php_label_object *)object;
+  php_label_object *php_label = (php_label_object *)object;
+
+  MAPSCRIPT_FREE_OBJECT(php_label);
+
+  MAPSCRIPT_FREE_PARENT(php_label->parent);
+  MAPSCRIPT_DELREF(php_label->color);
+  MAPSCRIPT_DELREF(php_label->outlinecolor);
+  MAPSCRIPT_DELREF(php_label->shadowcolor);
+  MAPSCRIPT_DELREF(php_label->leader);
+
+  if (php_label->label && !php_label->is_ref) {
+    labelObj_destroy(php_label->label);
+  }
+
+  efree(object);
+}
+
+static zend_object_value mapscript_label_object_new_ex(zend_class_entry *ce, php_label_object **ptr TSRMLS_DC)
+{
+  zend_object_value retval;
+  php_label_object *php_label;
+
+  MAPSCRIPT_ALLOC_OBJECT(php_label, php_label_object);
 
-    MAPSCRIPT_FREE_OBJECT(php_label);
+  retval = mapscript_object_new_ex(&php_label->std, ce,
+                                   &mapscript_label_object_destroy,
+                                   &mapscript_label_object_handlers TSRMLS_CC);
 
-    MAPSCRIPT_FREE_PARENT(php_label->parent);
-    MAPSCRIPT_DELREF(php_label->color);
-    MAPSCRIPT_DELREF(php_label->outlinecolor);
-    MAPSCRIPT_DELREF(php_label->shadowcolor);
-    
-    /* We don't need to free the labelObj, the mapObj will do it */ 
+  if (ptr)
+    *ptr = php_label;
 
-    efree(object);
+  php_label->is_ref = 0;
+  MAPSCRIPT_INIT_PARENT(php_label->parent);
+  php_label->color = NULL;
+  php_label->outlinecolor = NULL;
+  php_label->shadowcolor = NULL;
+  php_label->leader = NULL;
+
+  return retval;
 }
 
 static zend_object_value mapscript_label_object_new(zend_class_entry *ce TSRMLS_DC)
 {
-    zend_object_value retval;
-    php_label_object *php_label;
+  return mapscript_label_object_new_ex(ce, NULL TSRMLS_CC);
+}
+
+static zend_object_value mapscript_label_object_clone(zval *zobj TSRMLS_DC)
+{
+  php_label_object *php_label_old, *php_label_new;
+  zend_object_value new_ov;
 
-    MAPSCRIPT_ALLOC_OBJECT(php_label, php_label_object);
+  php_label_old = (php_label_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    retval = mapscript_object_new(&php_label->std, ce,
-                                  &mapscript_label_object_destroy TSRMLS_CC);
+  new_ov = mapscript_label_object_new_ex(mapscript_ce_label, &php_label_new TSRMLS_CC);
+  zend_objects_clone_members(&php_label_new->std, new_ov, &php_label_old->std, Z_OBJ_HANDLE_P(zobj) TSRMLS_CC);
 
-    MAPSCRIPT_INIT_PARENT(php_label->parent);
-    php_label->color = NULL;
-    php_label->outlinecolor = NULL;
-    php_label->shadowcolor = NULL;
+  php_label_new->label = labelObj_clone(php_label_old->label);
 
-    return retval;
+  return new_ov;
 }
 
 PHP_MINIT_FUNCTION(label)
 {
-    zend_class_entry ce;
+  zend_class_entry ce;
+
+  memcpy(&mapscript_label_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
+  mapscript_label_object_handlers.clone_obj = mapscript_label_object_clone;
+
+  MAPSCRIPT_REGISTER_CLASS("labelObj",
+                           label_functions,
+                           mapscript_ce_label,
+                           mapscript_label_object_new);
 
-    MAPSCRIPT_REGISTER_CLASS("labelObj", 
-                             label_functions,
-                             mapscript_ce_label,
-                             mapscript_label_object_new);
+  mapscript_ce_label->ce_flags |= ZEND_ACC_FINAL_CLASS;
 
-    mapscript_ce_label->ce_flags |= ZEND_ACC_FINAL_CLASS; 
-    
-    return SUCCESS;
+  return SUCCESS;
 }
 
diff --git a/mapscript/php/labelcache.c b/mapscript/php/labelcache.c
index 228ef75..43f6ef5 100644
--- a/mapscript/php/labelcache.c
+++ b/mapscript/php/labelcache.c
@@ -2,7 +2,7 @@
  * $Id: php_mapscript.c 9765 2010-01-28 15:32:10Z aboudreault $
  *
  * Project:  MapServer
- * Purpose:  PHP/MapScript extension for MapServer.  External interface 
+ * Purpose:  PHP/MapScript extension for MapServer.  External interface
  *           functions
  * Author:   Daniel Morissette, DM Solutions Group (dmorissette at dmsolutions.ca)
  *           Alan Boudreault, Mapgears
@@ -16,16 +16,16 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
+ *
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  * DEALINGS IN THE SOFTWARE.
  **********************************************************************/
 
@@ -34,30 +34,30 @@
 zend_class_entry *mapscript_ce_labelcache;
 
 ZEND_BEGIN_ARG_INFO_EX(labelcache___get_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, property)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(labelcache___set_args, 0, 0, 2)
-  ZEND_ARG_INFO(0, property)
-  ZEND_ARG_INFO(0, value)
+ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, value)
 ZEND_END_ARG_INFO()
 
 /* {{{ proto labelcache __construct()
    labelCacheObj CANNOT be instanciated, this will throw an exception on use */
 PHP_METHOD(labelCacheObj, __construct)
 {
-    mapscript_throw_exception("labelCacheObj cannot be constructed" TSRMLS_CC);
+  mapscript_throw_exception("labelCacheObj cannot be constructed" TSRMLS_CC);
 }
 /* }}} */
 
 PHP_METHOD(labelCacheObj, __get)
 {
-    mapscript_throw_exception("labelCacheObj has no property." TSRMLS_CC);
+  mapscript_throw_exception("labelCacheObj has no property." TSRMLS_CC);
 }
 
 PHP_METHOD(labelCacheObj, __set)
 {
-    mapscript_throw_exception("labelCacheObj has no property." TSRMLS_CC);
+  mapscript_throw_exception("labelCacheObj has no property." TSRMLS_CC);
 }
 
 /* {{{ proto int labelcache->freeCache(()
@@ -65,81 +65,82 @@ PHP_METHOD(labelCacheObj, __set)
    an error occurs. */
 PHP_METHOD(labelCacheObj, freeCache)
 {
-    zval *zobj = getThis();
-    php_labelcache_object *php_labelcache;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  php_labelcache_object *php_labelcache;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_labelcache = (php_labelcache_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_labelcache = (php_labelcache_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    labelCacheObj_freeCache(php_labelcache->labelcache);
-    
-    RETURN_LONG(MS_SUCCESS);
+  labelCacheObj_freeCache(php_labelcache->labelcache);
+
+  RETURN_LONG(MS_SUCCESS);
 }
 /* }}}} */
 
 zend_function_entry labelcache_functions[] = {
-    PHP_ME(labelCacheObj, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
-    PHP_ME(labelCacheObj, __get, labelcache___get_args, ZEND_ACC_PUBLIC)
-    PHP_ME(labelCacheObj, __set, labelcache___set_args, ZEND_ACC_PUBLIC)
-    PHP_ME(labelCacheObj, freeCache, NULL, ZEND_ACC_PUBLIC)
-    {NULL, NULL, NULL}
+  PHP_ME(labelCacheObj, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
+  PHP_ME(labelCacheObj, __get, labelcache___get_args, ZEND_ACC_PUBLIC)
+  PHP_ME(labelCacheObj, __set, labelcache___set_args, ZEND_ACC_PUBLIC)
+  PHP_ME(labelCacheObj, freeCache, NULL, ZEND_ACC_PUBLIC) {
+    NULL, NULL, NULL
+  }
 };
 
 void mapscript_create_labelcache(labelCacheObj *labelcache, parent_object parent, zval *return_value TSRMLS_DC)
 {
-    php_labelcache_object * php_labelcache;
-    object_init_ex(return_value, mapscript_ce_labelcache); 
-    php_labelcache = (php_labelcache_object *)zend_object_store_get_object(return_value TSRMLS_CC);
-    php_labelcache->labelcache = labelcache;
+  php_labelcache_object * php_labelcache;
+  object_init_ex(return_value, mapscript_ce_labelcache);
+  php_labelcache = (php_labelcache_object *)zend_object_store_get_object(return_value TSRMLS_CC);
+  php_labelcache->labelcache = labelcache;
 
-    php_labelcache->parent = parent;
-    MAPSCRIPT_ADDREF(parent.val);
+  php_labelcache->parent = parent;
+  MAPSCRIPT_ADDREF(parent.val);
 }
 
 static void mapscript_labelcache_object_destroy(void *object TSRMLS_DC)
 {
-    php_labelcache_object *php_labelcache = (php_labelcache_object *)object;
+  php_labelcache_object *php_labelcache = (php_labelcache_object *)object;
+
+  MAPSCRIPT_FREE_OBJECT(php_labelcache);
 
-    MAPSCRIPT_FREE_OBJECT(php_labelcache);
+  MAPSCRIPT_FREE_PARENT(php_labelcache->parent);
 
-    MAPSCRIPT_FREE_PARENT(php_labelcache->parent);
+  /* We don't need to free the labelCacheObj */
 
-    /* We don't need to free the labelCacheObj */ 
-    
-    efree(object);
+  efree(object);
 }
 
 static zend_object_value mapscript_labelcache_object_new(zend_class_entry *ce TSRMLS_DC)
 {
-    zend_object_value retval;
-    php_labelcache_object *php_labelcache;
+  zend_object_value retval;
+  php_labelcache_object *php_labelcache;
 
-    MAPSCRIPT_ALLOC_OBJECT(php_labelcache, php_labelcache_object);
+  MAPSCRIPT_ALLOC_OBJECT(php_labelcache, php_labelcache_object);
 
-    retval = mapscript_object_new(&php_labelcache->std, ce,
-                                  &mapscript_labelcache_object_destroy TSRMLS_CC);
+  retval = mapscript_object_new(&php_labelcache->std, ce,
+                                &mapscript_labelcache_object_destroy TSRMLS_CC);
 
-    MAPSCRIPT_INIT_PARENT(php_labelcache->parent);
+  MAPSCRIPT_INIT_PARENT(php_labelcache->parent);
 
-    return retval;
+  return retval;
 }
 
 PHP_MINIT_FUNCTION(labelcache)
 {
-    zend_class_entry ce;
+  zend_class_entry ce;
+
+  MAPSCRIPT_REGISTER_CLASS("labelCacheObj",
+                           labelcache_functions,
+                           mapscript_ce_labelcache,
+                           mapscript_labelcache_object_new);
 
-    MAPSCRIPT_REGISTER_CLASS("labelCacheObj", 
-                             labelcache_functions,
-                             mapscript_ce_labelcache,
-                             mapscript_labelcache_object_new);
+  mapscript_ce_labelcache->ce_flags |= ZEND_ACC_FINAL_CLASS;
 
-    mapscript_ce_labelcache->ce_flags |= ZEND_ACC_FINAL_CLASS; 
-    
-    return SUCCESS;
+  return SUCCESS;
 }
diff --git a/mapscript/php/labelcachemember.c b/mapscript/php/labelcachemember.c
index e37bfc3..5a876b2 100644
--- a/mapscript/php/labelcachemember.c
+++ b/mapscript/php/labelcachemember.c
@@ -2,7 +2,7 @@
  * $Id: php_mapscript.c 9765 2010-01-28 15:32:10Z aboudreault $
  *
  * Project:  MapServer
- * Purpose:  PHP/MapScript extension for MapServer.  External interface 
+ * Purpose:  PHP/MapScript extension for MapServer.  External interface
  *           functions
  * Author:   Daniel Morissette, DM Solutions Group (dmorissette at dmsolutions.ca)
  *           Alan Boudreault, Mapgears
@@ -16,16 +16,16 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
+ *
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  * DEALINGS IN THE SOFTWARE.
  **********************************************************************/
 
@@ -34,191 +34,188 @@
 zend_class_entry *mapscript_ce_labelcachemember;
 
 ZEND_BEGIN_ARG_INFO_EX(labelcachemember___get_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, property)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(labelcachemember___set_args, 0, 0, 2)
-  ZEND_ARG_INFO(0, property)
-  ZEND_ARG_INFO(0, value)
+ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, value)
 ZEND_END_ARG_INFO()
 
-/* {{{ proto void __construct() 
+/* {{{ proto void __construct()
    labelCacheMemberObj CANNOT be instanciated, this will throw an exception on use */
 PHP_METHOD(labelCacheMemberObj, __construct)
 {
-    mapscript_throw_exception("labelCacheMemberObj cannot be constructed" TSRMLS_CC);
+  mapscript_throw_exception("labelCacheMemberObj cannot be constructed" TSRMLS_CC);
 }
 /* }}} */
 
 PHP_METHOD(labelCacheMemberObj, __get)
 {
-    char *property;
-    long property_len;
-    zval *zobj = getThis();
-    php_labelcachemember_object *php_labelcachemember;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &property, &property_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *zobj = getThis();
+  php_labelcachemember_object *php_labelcachemember;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &property, &property_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_labelcachemember = (php_labelcachemember_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-
-    IF_GET_STRING("text", php_labelcachemember->labelcachemember->text)
-    else IF_GET_LONG("classindex", php_labelcachemember->labelcachemember->classindex)
-    else IF_GET_LONG("featuresize", php_labelcachemember->labelcachemember->featuresize) 
-    else IF_GET_LONG("layerindex", php_labelcachemember->labelcachemember->layerindex) 
-    else IF_GET_LONG("numstyles", php_labelcachemember->labelcachemember->numstyles) 
-    else IF_GET_LONG("shapeindex", php_labelcachemember->labelcachemember->shapeindex) 
-    else IF_GET_LONG("status", php_labelcachemember->labelcachemember->status) 
-    else IF_GET_LONG("markerid", php_labelcachemember->labelcachemember->markerid) 
-    else IF_GET_LONG("tileindex", php_labelcachemember->labelcachemember->tileindex) 
-    else IF_GET_OBJECT("point", mapscript_ce_point, php_labelcachemember->point, &php_labelcachemember->labelcachemember->point) 
-    else IF_GET_OBJECT("label", mapscript_ce_label, php_labelcachemember->label, &php_labelcachemember->labelcachemember->label) 
-    else IF_GET_OBJECT("styles", mapscript_ce_style, php_labelcachemember->styles, php_labelcachemember->labelcachemember->styles) 
-    else IF_GET_OBJECT("poly", mapscript_ce_shape, php_labelcachemember->poly, php_labelcachemember->labelcachemember->poly) 
-    else 
-    {
-        mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_labelcachemember = (php_labelcachemember_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  IF_GET_LONG("classindex", php_labelcachemember->labelcachemember->classindex)
+  else IF_GET_LONG("featuresize", php_labelcachemember->labelcachemember->featuresize)
+    else IF_GET_LONG("layerindex", php_labelcachemember->labelcachemember->layerindex)
+      else IF_GET_LONG("numstyles", php_labelcachemember->labelcachemember->numstyles)
+        else IF_GET_LONG("numlabels", php_labelcachemember->labelcachemember->numlabels)
+          /* else IF_GET_LONG("shapeindex", php_labelcachemember->labelcachemember->shapeindex) */
+          else IF_GET_LONG("status", php_labelcachemember->labelcachemember->status)
+            else IF_GET_LONG("markerid", php_labelcachemember->labelcachemember->markerid)
+              /* else IF_GET_LONG("tileindex", php_labelcachemember->labelcachemember->tileindex) */
+              else IF_GET_OBJECT("point", mapscript_ce_point, php_labelcachemember->point, &php_labelcachemember->labelcachemember->point)
+                else IF_GET_OBJECT("labels", mapscript_ce_label, php_labelcachemember->labels, &php_labelcachemember->labelcachemember->labels)
+                  else IF_GET_OBJECT("styles", mapscript_ce_style, php_labelcachemember->styles, php_labelcachemember->labelcachemember->styles)
+                    else IF_GET_OBJECT("poly", mapscript_ce_shape, php_labelcachemember->poly, php_labelcachemember->labelcachemember->poly)
+                      else {
+                        mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+                      }
 }
 
 PHP_METHOD(labelCacheMemberObj, __set)
 {
-    char *property;
-    long property_len;
-    zval *value;
-    zval *zobj = getThis();
-    php_labelcachemember_object *php_labelcachemember;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
-                              &property, &property_len, &value) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *value;
+  zval *zobj = getThis();
+  php_labelcachemember_object *php_labelcachemember;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
+                            &property, &property_len, &value) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_labelcachemember = (php_labelcachemember_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-
-    if ( (STRING_EQUAL("text", property)) ||
-         (STRING_EQUAL("classindex", property)) ||
-         (STRING_EQUAL("featuresize", property)) ||
-         (STRING_EQUAL("layerindex", property)) ||
-         (STRING_EQUAL("numstyles", property)) ||
-         (STRING_EQUAL("shapeindex", property)) ||
-         (STRING_EQUAL("status", property)) ||
-         (STRING_EQUAL("markerid", property)) ||
-         (STRING_EQUAL("tileindex", property)) ||
-         (STRING_EQUAL("label", property)) ||
-         (STRING_EQUAL("styles", property)) ||
-         (STRING_EQUAL("poly", property)) ||
-         (STRING_EQUAL("point", property)))
-    {
-        mapscript_throw_exception("Property '%s' is read-only and cannot be set." TSRMLS_CC, property);
-    }
-    else 
-    {
-        mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }      
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_labelcachemember = (php_labelcachemember_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  if ( (STRING_EQUAL("classindex", property)) ||
+       (STRING_EQUAL("featuresize", property)) ||
+       (STRING_EQUAL("layerindex", property)) ||
+       (STRING_EQUAL("numstyles", property)) ||
+       (STRING_EQUAL("numlabels", property)) ||
+       (STRING_EQUAL("shapeindex", property)) ||
+       (STRING_EQUAL("status", property)) ||
+       (STRING_EQUAL("markerid", property)) ||
+       (STRING_EQUAL("tileindex", property)) ||
+       (STRING_EQUAL("labels", property)) ||
+       (STRING_EQUAL("styles", property)) ||
+       (STRING_EQUAL("poly", property)) ||
+       (STRING_EQUAL("point", property))) {
+    mapscript_throw_exception("Property '%s' is read-only and cannot be set." TSRMLS_CC, property);
+  } else {
+    mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+  }
 }
 
 /* proto void free()
    Free the object */
 PHP_METHOD(labelCacheMemberObj, free)
 {
-    zval *zobj = getThis();
-    php_labelcachemember_object *php_labelcachemember;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  php_labelcachemember_object *php_labelcachemember;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_labelcachemember = (php_labelcachemember_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    MAPSCRIPT_DELREF(php_labelcachemember->point);
-    MAPSCRIPT_DELREF(php_labelcachemember->label);
-    MAPSCRIPT_DELREF(php_labelcachemember->styles);
-    MAPSCRIPT_DELREF(php_labelcachemember->poly);
+  php_labelcachemember = (php_labelcachemember_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  MAPSCRIPT_DELREF(php_labelcachemember->point);
+  MAPSCRIPT_DELREF(php_labelcachemember->labels);
+  MAPSCRIPT_DELREF(php_labelcachemember->styles);
+  MAPSCRIPT_DELREF(php_labelcachemember->poly);
 }
 /* }}} */
 
 zend_function_entry labelcachemember_functions[] = {
-    PHP_ME(labelCacheMemberObj, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
-    PHP_ME(labelCacheMemberObj, __get, labelcachemember___get_args, ZEND_ACC_PUBLIC)
-    PHP_ME(labelCacheMemberObj, __set, labelcachemember___set_args, ZEND_ACC_PUBLIC)
-    PHP_MALIAS(labelCacheMemberObj, setProperty, __set, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(labelCacheMemberObj, free, NULL, ZEND_ACC_PUBLIC)
-    {NULL, NULL, NULL}
+  PHP_ME(labelCacheMemberObj, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
+  PHP_ME(labelCacheMemberObj, __get, labelcachemember___get_args, ZEND_ACC_PUBLIC)
+  PHP_ME(labelCacheMemberObj, __set, labelcachemember___set_args, ZEND_ACC_PUBLIC)
+  PHP_MALIAS(labelCacheMemberObj, setProperty, __set, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(labelCacheMemberObj, free, NULL, ZEND_ACC_PUBLIC) {
+    NULL, NULL, NULL
+  }
 };
 
 
-void mapscript_create_labelcachemember(labelCacheMemberObj *labelcachemember, 
-                                        parent_object parent, zval *return_value TSRMLS_DC)
+void mapscript_create_labelcachemember(labelCacheMemberObj *labelcachemember,
+                                       parent_object parent, zval *return_value TSRMLS_DC)
 {
-    php_labelcachemember_object * php_labelcachemember;
-    object_init_ex(return_value, mapscript_ce_labelcachemember); 
-    php_labelcachemember = (php_labelcachemember_object *)zend_object_store_get_object(return_value TSRMLS_CC);
-    php_labelcachemember->labelcachemember = labelcachemember;
+  php_labelcachemember_object * php_labelcachemember;
+  object_init_ex(return_value, mapscript_ce_labelcachemember);
+  php_labelcachemember = (php_labelcachemember_object *)zend_object_store_get_object(return_value TSRMLS_CC);
+  php_labelcachemember->labelcachemember = labelcachemember;
 
-    php_labelcachemember->parent = parent;
+  php_labelcachemember->parent = parent;
 
-    MAPSCRIPT_ADDREF(parent.val);
+  MAPSCRIPT_ADDREF(parent.val);
 }
 
 static void mapscript_labelcachemember_object_destroy(void *object TSRMLS_DC)
 {
-    php_labelcachemember_object *php_labelcachemember = (php_labelcachemember_object *)object;
+  php_labelcachemember_object *php_labelcachemember = (php_labelcachemember_object *)object;
 
-    MAPSCRIPT_FREE_OBJECT(php_labelcachemember);
+  MAPSCRIPT_FREE_OBJECT(php_labelcachemember);
 
-    MAPSCRIPT_FREE_PARENT(php_labelcachemember->parent);
-    MAPSCRIPT_DELREF(php_labelcachemember->point);
-    MAPSCRIPT_DELREF(php_labelcachemember->label);
-    MAPSCRIPT_DELREF(php_labelcachemember->styles);
-    MAPSCRIPT_DELREF(php_labelcachemember->poly);
+  MAPSCRIPT_FREE_PARENT(php_labelcachemember->parent);
+  MAPSCRIPT_DELREF(php_labelcachemember->point);
+  MAPSCRIPT_DELREF(php_labelcachemember->labels);
+  MAPSCRIPT_DELREF(php_labelcachemember->styles);
+  MAPSCRIPT_DELREF(php_labelcachemember->poly);
 
-    /* We don't need to free the labelCacheMemberObj, the mapObj will do it */ 
+  /* We don't need to free the labelCacheMemberObj, the mapObj will do it */
 
-    efree(object);
+  efree(object);
 }
 
 static zend_object_value mapscript_labelcachemember_object_new(zend_class_entry *ce TSRMLS_DC)
 {
-    zend_object_value retval;
-    php_labelcachemember_object *php_labelcachemember;
+  zend_object_value retval;
+  php_labelcachemember_object *php_labelcachemember;
 
-    MAPSCRIPT_ALLOC_OBJECT(php_labelcachemember, php_labelcachemember_object);
+  MAPSCRIPT_ALLOC_OBJECT(php_labelcachemember, php_labelcachemember_object);
 
-    retval = mapscript_object_new(&php_labelcachemember->std, ce,
-                                  &mapscript_labelcachemember_object_destroy TSRMLS_CC);
+  retval = mapscript_object_new(&php_labelcachemember->std, ce,
+                                &mapscript_labelcachemember_object_destroy TSRMLS_CC);
 
-    MAPSCRIPT_INIT_PARENT(php_labelcachemember->parent);
-    php_labelcachemember->point = NULL;
-    php_labelcachemember->label = NULL;
-    php_labelcachemember->styles = NULL;
-    php_labelcachemember->poly = NULL;
+  MAPSCRIPT_INIT_PARENT(php_labelcachemember->parent);
+  php_labelcachemember->point = NULL;
+  php_labelcachemember->labels = NULL;
+  php_labelcachemember->styles = NULL;
+  php_labelcachemember->poly = NULL;
 
-    return retval;
+  return retval;
 }
 
 PHP_MINIT_FUNCTION(labelcachemember)
 {
-    zend_class_entry ce;
+  zend_class_entry ce;
+
+  MAPSCRIPT_REGISTER_CLASS("labelCacheMemberObj",
+                           labelcachemember_functions,
+                           mapscript_ce_labelcachemember,
+                           mapscript_labelcachemember_object_new);
 
-    MAPSCRIPT_REGISTER_CLASS("labelCacheMemberObj", 
-                             labelcachemember_functions,
-                             mapscript_ce_labelcachemember,
-                             mapscript_labelcachemember_object_new);
+  mapscript_ce_labelcachemember->ce_flags |= ZEND_ACC_FINAL_CLASS;
 
-    mapscript_ce_labelcachemember->ce_flags |= ZEND_ACC_FINAL_CLASS; 
-    
-    return SUCCESS;
+  return SUCCESS;
 }
 
diff --git a/mapscript/php/labelleader.c b/mapscript/php/labelleader.c
new file mode 100644
index 0000000..af51e2b
--- /dev/null
+++ b/mapscript/php/labelleader.c
@@ -0,0 +1,156 @@
+/**********************************************************************
+ * Project:  MapServer
+ * Purpose:  PHP/MapScript extension for MapServer.  External interface
+ *           functions
+ * Author:   Daniel Morissette, DM Solutions Group (dmorissette at dmsolutions.ca)
+ *           Alan Boudreault, Mapgears
+ *
+ **********************************************************************
+ * Copyright (c) 2000-2010, Daniel Morissette, DM Solutions Group Inc.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies of this Software or works derived from this Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ **********************************************************************/
+
+#include "php_mapscript.h"
+
+zend_class_entry *mapscript_ce_labelleader;
+
+ZEND_BEGIN_ARG_INFO_EX(labelleader___get_args, 0, 0, 1)
+ZEND_ARG_INFO(0, property)
+ZEND_END_ARG_INFO()
+
+ZEND_BEGIN_ARG_INFO_EX(labelleader___set_args, 0, 0, 2)
+ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, value)
+ZEND_END_ARG_INFO()
+
+/* {{{ proto labelleader __construct()
+   labelLeaderObj CANNOT be instanciated, this will throw an exception on use */
+PHP_METHOD(labelLeaderObj, __construct)
+{
+  mapscript_throw_exception("labelLeaderObj cannot be constructed" TSRMLS_CC);
+}
+/* }}} */
+
+PHP_METHOD(labelLeaderObj, __get)
+{
+  char *property;
+  long property_len;
+  zval *zobj = getThis();
+  php_labelleader_object *php_labelleader;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &property, &property_len) == FAILURE) {
+    PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_labelleader = (php_labelleader_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  IF_GET_LONG("maxdistance", php_labelleader->labelleader->maxdistance)
+  else IF_GET_LONG("gridstep", php_labelleader->labelleader->gridstep)
+    else {
+      mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+    }
+}
+
+PHP_METHOD(labelLeaderObj, __set)
+{
+  char *property;
+  long property_len;
+  zval *value;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
+                            &property, &property_len, &value) == FAILURE) {
+    PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  if ( (STRING_EQUAL("maxdistance", property)) ||
+       (STRING_EQUAL("gridstep", property)) ) {
+    mapscript_throw_exception("Property '%s' is read-only and cannot be set." TSRMLS_CC, property);
+  } else {
+    mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+  }
+}
+
+zend_function_entry labelleader_functions[] = {
+  PHP_ME(labelLeaderObj, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
+  PHP_ME(labelLeaderObj, __get, labelleader___get_args, ZEND_ACC_PUBLIC)
+  PHP_ME(labelLeaderObj, __set, labelleader___set_args, ZEND_ACC_PUBLIC) {
+    NULL, NULL, NULL
+  }
+};
+
+void mapscript_create_labelleader(labelLeaderObj *labelleader, parent_object parent, zval *return_value TSRMLS_DC)
+{
+  php_labelleader_object * php_labelleader;
+  object_init_ex(return_value, mapscript_ce_labelleader);
+  php_labelleader = (php_labelleader_object *)zend_object_store_get_object(return_value TSRMLS_CC);
+  php_labelleader->labelleader = labelleader;
+
+  php_labelleader->parent = parent;
+  MAPSCRIPT_ADDREF(parent.val);
+}
+
+static void mapscript_labelleader_object_destroy(void *object TSRMLS_DC)
+{
+  php_labelleader_object *php_labelleader = (php_labelleader_object *)object;
+
+  MAPSCRIPT_FREE_OBJECT(php_labelleader);
+
+  MAPSCRIPT_FREE_PARENT(php_labelleader->parent);
+
+  /* We don't need to free the labelLeaderObj */
+
+  efree(object);
+}
+
+static zend_object_value mapscript_labelleader_object_new(zend_class_entry *ce TSRMLS_DC)
+{
+  zend_object_value retval;
+  php_labelleader_object *php_labelleader;
+
+  MAPSCRIPT_ALLOC_OBJECT(php_labelleader, php_labelleader_object);
+
+  retval = mapscript_object_new(&php_labelleader->std, ce,
+                                &mapscript_labelleader_object_destroy TSRMLS_CC);
+
+  MAPSCRIPT_INIT_PARENT(php_labelleader->parent);
+
+  return retval;
+}
+
+PHP_MINIT_FUNCTION(labelleader)
+{
+  zend_class_entry ce;
+
+  MAPSCRIPT_REGISTER_CLASS("labelLeaderObj",
+                           labelleader_functions,
+                           mapscript_ce_labelleader,
+                           mapscript_labelleader_object_new);
+
+  mapscript_ce_labelleader->ce_flags |= ZEND_ACC_FINAL_CLASS;
+
+  return SUCCESS;
+}
diff --git a/mapscript/php/layer.c b/mapscript/php/layer.c
index 43310bc..59eff2f 100644
--- a/mapscript/php/layer.c
+++ b/mapscript/php/layer.c
@@ -2,7 +2,7 @@
  * $Id: php_mapscript.c 9765 2010-01-28 15:32:10Z aboudreault $
  *
  * Project:  MapServer
- * Purpose:  PHP/MapScript extension for MapServer.  External interface 
+ * Purpose:  PHP/MapScript extension for MapServer.  External interface
  *           functions
  * Author:   Daniel Morissette, DM Solutions Group (dmorissette at dmsolutions.ca)
  *           Alan Boudreault, Mapgears
@@ -16,398 +16,432 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
+ *
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  * DEALINGS IN THE SOFTWARE.
  **********************************************************************/
 
 #include "php_mapscript.h"
 
 zend_class_entry *mapscript_ce_layer;
+zend_object_handlers mapscript_layer_object_handlers;
 
 ZEND_BEGIN_ARG_INFO_EX(layer___construct_args, 0, 0, 1)
-  ZEND_ARG_OBJ_INFO(0, map, mapObj, 0)
-  ZEND_ARG_OBJ_INFO(0, layer, layerObj, 0)
+ZEND_ARG_OBJ_INFO(0, map, mapObj, 0)
+ZEND_ARG_OBJ_INFO(0, layer, layerObj, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(layer___get_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, property)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(layer___set_args, 0, 0, 2)
-  ZEND_ARG_INFO(0, property)
-  ZEND_ARG_INFO(0, value)
+ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, value)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(layer_updateFromString_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, snippet)
+ZEND_ARG_INFO(0, snippet)
+ZEND_END_ARG_INFO()
+
+ZEND_BEGIN_ARG_INFO_EX(layer_setExtent_args, 0, 0, 4)
+ZEND_ARG_INFO(0, minx)
+ZEND_ARG_INFO(0, miny)
+ZEND_ARG_INFO(0, maxx)
+ZEND_ARG_INFO(0, maxy)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(layer_getClass_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, index)
+ZEND_ARG_INFO(0, index)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(layer_getClassIndex_args, 0, 0, 2)
-  ZEND_ARG_OBJ_INFO(0, shape, shapeObj, 0)
-  ZEND_ARG_INFO(0, classGroup)
-  ZEND_ARG_INFO(0, numClasses)
+ZEND_ARG_OBJ_INFO(0, shape, shapeObj, 0)
+ZEND_ARG_INFO(0, classGroup)
+ZEND_ARG_INFO(0, numClasses)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(layer_setFilter_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, expression)
+ZEND_ARG_INFO(0, expression)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(layer_setProjection_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, projectionParams)
+ZEND_ARG_INFO(0, projectionParams)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(layer_setWKTProjection_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, projectionParams)
+ZEND_ARG_INFO(0, projectionParams)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(layer_getResult_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, index)
+ZEND_ARG_INFO(0, index)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(layer_whichShapes_args, 0, 0, 1)
-  ZEND_ARG_OBJ_INFO(0, extent, rectObj, 0)
+ZEND_ARG_OBJ_INFO(0, extent, rectObj, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(layer_addFeature_args, 0, 0, 1)
-  ZEND_ARG_OBJ_INFO(0, shape, shapeObj, 0)
+ZEND_ARG_OBJ_INFO(0, shape, shapeObj, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(layer_getMetaData_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, name)
+ZEND_ARG_INFO(0, name)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(layer_setMetaData_args, 0, 0, 2)
-  ZEND_ARG_INFO(0, name)
-  ZEND_ARG_INFO(0, value)
+ZEND_ARG_INFO(0, name)
+ZEND_ARG_INFO(0, value)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(layer_removeMetaData_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, name)
+ZEND_ARG_INFO(0, name)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(layer_getWMSFeatureInfoURL_args, 0, 0, 4)
-  ZEND_ARG_INFO(0, clickX)
-  ZEND_ARG_INFO(0, clickY)
-  ZEND_ARG_INFO(0, featureCount)
-  ZEND_ARG_INFO(0, infoFormat)
+ZEND_ARG_INFO(0, clickX)
+ZEND_ARG_INFO(0, clickY)
+ZEND_ARG_INFO(0, featureCount)
+ZEND_ARG_INFO(0, infoFormat)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(layer_setProcessing_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, string)
+ZEND_ARG_INFO(0, string)
+ZEND_END_ARG_INFO()
+
+ZEND_BEGIN_ARG_INFO_EX(layer_setProcessingKey_args, 0, 0, 2)
+ZEND_ARG_INFO(0, key)
+ZEND_ARG_INFO(0, value)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(layer_applySLD_args, 0, 0, 2)
-  ZEND_ARG_INFO(0, sldxml)
-  ZEND_ARG_INFO(0, namedLayer)
+ZEND_ARG_INFO(0, sldxml)
+ZEND_ARG_INFO(0, namedLayer)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(layer_applySLDURL_args, 0, 0, 2)
-  ZEND_ARG_INFO(0, sldurl)
-  ZEND_ARG_INFO(0, namedLayer)
+ZEND_ARG_INFO(0, sldurl)
+ZEND_ARG_INFO(0, namedLayer)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(layer_moveClassUp_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, index)
+ZEND_ARG_INFO(0, index)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(layer_moveClassDown_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, index)
+ZEND_ARG_INFO(0, index)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(layer_removeClass_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, index)
+ZEND_ARG_INFO(0, index)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(layer_setConnectionType_args, 0, 0, 2)
-  ZEND_ARG_INFO(0, connectionType)
-  ZEND_ARG_INFO(0, pluginLibrary)
+ZEND_ARG_INFO(0, connectionType)
+ZEND_ARG_INFO(0, pluginLibrary)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(layer_draw_args, 0, 0, 1)
-  ZEND_ARG_OBJ_INFO(0, image, imageObj, 0)
+ZEND_ARG_OBJ_INFO(0, image, imageObj, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(layer_drawQuery_args, 0, 0, 1)
-  ZEND_ARG_OBJ_INFO(0, image, imageObj, 0)
+ZEND_ARG_OBJ_INFO(0, image, imageObj, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(layer_queryByPoint_args, 0, 0, 3)
-  ZEND_ARG_OBJ_INFO(0, point, pointObj, 0)
-  ZEND_ARG_INFO(0, mode)
-  ZEND_ARG_INFO(0, buffer)
+ZEND_ARG_OBJ_INFO(0, point, pointObj, 0)
+ZEND_ARG_INFO(0, mode)
+ZEND_ARG_INFO(0, buffer)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(layer_queryByRect_args, 0, 0, 1)
-  ZEND_ARG_OBJ_INFO(0, rect, rectObj, 0)
+ZEND_ARG_OBJ_INFO(0, rect, rectObj, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(layer_queryByShape_args, 0, 0, 1)
-  ZEND_ARG_OBJ_INFO(0, shape, shapeObj, 0)
+ZEND_ARG_OBJ_INFO(0, shape, shapeObj, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(layer_queryByFeatures_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, slayer)
+ZEND_ARG_INFO(0, slayer)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(layer_queryByAttributes_args, 0, 0, 3)
-  ZEND_ARG_INFO(0, item)
-  ZEND_ARG_INFO(0, string)
-  ZEND_ARG_INFO(0, mode)
+ZEND_ARG_INFO(0, item)
+ZEND_ARG_INFO(0, string)
+ZEND_ARG_INFO(0, mode)
+ZEND_END_ARG_INFO()
+
+ZEND_BEGIN_ARG_INFO_EX(layer_queryByFilter_args, 0, 0, 1)
+ZEND_ARG_INFO(0, string)
+ZEND_END_ARG_INFO()
+
+ZEND_BEGIN_ARG_INFO_EX(layer_queryByIndex_args, 0, 0, 2)
+ZEND_ARG_INFO(0, tileindex)
+ZEND_ARG_INFO(0, shapeindex)
+ZEND_ARG_INFO(0, addtoquery)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(layer_getShape_args, 0, 0, 1)
-  ZEND_ARG_OBJ_INFO(0, record, resultObj, 0)
+ZEND_ARG_OBJ_INFO(0, record, resultObj, 0)
 ZEND_END_ARG_INFO()
 
-/* {{{ proto void __construct(mapObj map [, layerObj layer]) 
+/* {{{ proto void __construct(mapObj map [, layerObj layer])
    Create a new layerObj instance. */
 PHP_METHOD(layerObj, __construct)
 {
-    zval *zobj = getThis();
-    zval *zmap, *zlayer = NULL;
-    layerObj *layer;
-    int index;
-    php_map_object *php_map;
-    php_layer_object *php_layer, *php_layer2;
-    parent_object parent;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O|O",
-                              &zmap, mapscript_ce_map,
-                              &zlayer, mapscript_ce_layer) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  zval *zmap, *zlayer = NULL;
+  layerObj *layer;
+  int index;
+  php_map_object *php_map;
+  php_layer_object *php_layer, *php_layer2=NULL;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O|O",
+                            &zmap, mapscript_ce_map,
+                            &zlayer, mapscript_ce_layer) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-
-    php_layer = (php_layer_object *)zend_object_store_get_object(zobj TSRMLS_CC);
-    php_map = (php_map_object *)zend_object_store_get_object(zmap TSRMLS_CC);
-    if (zlayer)
-        php_layer2 = (php_layer_object *)zend_object_store_get_object(zlayer TSRMLS_CC);
-
-    if ((layer = layerObj_new(php_map->map)) == NULL)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
-
-    php_layer->layer = layer;
-    php_layer->is_ref = 1;
-    
-    MAPSCRIPT_MAKE_PARENT(zmap, NULL);
-    php_layer->parent = parent;
-    MAPSCRIPT_ADDREF(zmap);
-
-    /* if a layer is passed as argument, copy the layer into
-       the new one */
-    if (zlayer)
-    {
-        index = layer->index;
-        msCopyLayer(layer, php_layer2->layer);
-        layer->index = index;
-    }
-
-
-    if (layer->connectiontype != MS_GRATICULE || layer->layerinfo == NULL)
-    {
-        MAKE_STD_ZVAL(php_layer->grid);
-        ZVAL_NULL(php_layer->grid);
-    }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_layer = (php_layer_object *)zend_object_store_get_object(zobj TSRMLS_CC);
+  php_map = (php_map_object *)zend_object_store_get_object(zmap TSRMLS_CC);
+  if (zlayer)
+    php_layer2 = (php_layer_object *)zend_object_store_get_object(zlayer TSRMLS_CC);
+
+  if ((layer = layerObj_new(php_map->map)) == NULL) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
+
+  php_layer->layer = layer;
+  php_layer->is_ref = 1;
+
+  MAPSCRIPT_MAKE_PARENT(zmap, NULL);
+  php_layer->parent = parent;
+  MAPSCRIPT_ADDREF(zmap);
+
+  /* if a layer is passed as argument, copy the layer into
+     the new one */
+  if (zlayer) {
+    index = layer->index;
+    msCopyLayer(layer, php_layer2->layer);
+    layer->index = index;
+  }
+
+
+  if (layer->connectiontype != MS_GRATICULE || layer->layerinfo == NULL) {
+    MAKE_STD_ZVAL(php_layer->grid);
+    ZVAL_NULL(php_layer->grid);
+  }
 }
 /* }}} */
 
 PHP_METHOD(layerObj, __get)
 {
-    char *property;
-    long property_len;
-    zval *zobj = getThis();
-    php_layer_object *php_layer;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &property, &property_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *zobj = getThis();
+  php_layer_object *php_layer;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &property, &property_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    IF_GET_LONG("numclasses",  php_layer->layer->numclasses)
-    else IF_GET_LONG("index", php_layer->layer->index)
+  IF_GET_LONG("numclasses",  php_layer->layer->numclasses)
+  else IF_GET_LONG("index", php_layer->layer->index)
     else IF_GET_LONG("status", php_layer->layer->status)
-    else IF_GET_LONG("debug",  php_layer->layer->debug)
-    else IF_GET_STRING("classitem", php_layer->layer->classitem)
-    else IF_GET_STRING("classgroup", php_layer->layer->classgroup)
-    else IF_GET_STRING("name", php_layer->layer->name)
-    else IF_GET_STRING("group", php_layer->layer->group)
-    else IF_GET_STRING("data", php_layer->layer->data)
-    else IF_GET_LONG("type",  php_layer->layer->type)
-    else IF_GET_LONG("dump", php_layer->layer->dump)
-    else IF_GET_DOUBLE("tolerance", php_layer->layer->tolerance)
-    else IF_GET_LONG("toleranceunits", php_layer->layer->toleranceunits)
-    else IF_GET_LONG("sizeunits", php_layer->layer->sizeunits)
-    else IF_GET_DOUBLE("symbolscaledenom", php_layer->layer->symbolscaledenom)
-    else IF_GET_DOUBLE("minscaledenom", php_layer->layer->minscaledenom)
-    else IF_GET_DOUBLE("maxscaledenom", php_layer->layer->maxscaledenom)
-    else IF_GET_DOUBLE("labelminscaledenom", php_layer->layer->labelminscaledenom)
-    else IF_GET_DOUBLE("labelmaxscaledenom", php_layer->layer->labelmaxscaledenom)
-    else IF_GET_LONG("minfeaturesize", php_layer->layer->minfeaturesize)
-    else IF_GET_LONG("maxfeatures", php_layer->layer->maxfeatures)
-    else IF_GET_LONG("startindex", php_layer->layer->startindex)
-    else IF_GET_LONG("annotate", php_layer->layer->annotate)
-    else IF_GET_LONG("transform", php_layer->layer->transform)
-    else IF_GET_LONG("labelcache", php_layer->layer->labelcache)
-    else IF_GET_LONG("postlabelcache", php_layer->layer->postlabelcache)
-    else IF_GET_STRING("labelitem", php_layer->layer->labelitem)
-    else IF_GET_STRING("tileitem", php_layer->layer->tileitem)
-    else IF_GET_STRING("tileindex", php_layer->layer->tileindex)
-    else IF_GET_STRING("header", php_layer->layer->header)
-    else IF_GET_STRING("footer", php_layer->layer->footer)
-    else IF_GET_STRING("connection", php_layer->layer->connection)
-    else IF_GET_LONG("connectiontype", php_layer->layer->connectiontype)
-    else IF_GET_STRING("filteritem", php_layer->layer->filteritem)
-    else IF_GET_STRING("template", php_layer->layer->template)
-    else IF_GET_LONG("opacity", php_layer->layer->opacity)
-    else IF_GET_STRING("styleitem", php_layer->layer->styleitem)
-    else IF_GET_LONG("num_processing", php_layer->layer->numprocessing)
-    else IF_GET_STRING("requires", php_layer->layer->requires)
-    else IF_GET_STRING("labelrequires", php_layer->layer->labelrequires)
-    else IF_GET_OBJECT("offsite", mapscript_ce_color, php_layer->offsite, &php_layer->layer->offsite) 
-    else IF_GET_OBJECT("grid",  mapscript_ce_grid, php_layer->grid, (graticuleObj *)(php_layer->layer->layerinfo)) 
-    else IF_GET_OBJECT("metadata", mapscript_ce_hashtable, php_layer->metadata, &php_layer->layer->metadata) 
-    else IF_GET_OBJECT("bindvals", mapscript_ce_hashtable, php_layer->bindvals, &php_layer->layer->bindvals) 
-    else IF_GET_OBJECT("cluster", mapscript_ce_cluster, php_layer->cluster, &php_layer->layer->cluster) 
-    else IF_GET_OBJECT("projection", mapscript_ce_projection, php_layer->projection, &php_layer->layer->projection) 
-    else 
-    {
-        mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }
+      else IF_GET_LONG("debug",  php_layer->layer->debug)
+        else IF_GET_STRING("bandsitem", php_layer->layer->bandsitem)
+          else IF_GET_STRING("classitem", php_layer->layer->classitem)
+            else IF_GET_STRING("classgroup", php_layer->layer->classgroup)
+              else IF_GET_STRING("name", php_layer->layer->name)
+                else IF_GET_STRING("group", php_layer->layer->group)
+                  else IF_GET_STRING("data", php_layer->layer->data)
+                    else IF_GET_LONG("type",  php_layer->layer->type)
+                      else IF_GET_LONG("dump", php_layer->layer->dump)
+                        else IF_GET_DOUBLE("tolerance", php_layer->layer->tolerance)
+                          else IF_GET_LONG("toleranceunits", php_layer->layer->toleranceunits)
+                            else IF_GET_LONG("sizeunits", php_layer->layer->sizeunits)
+                              else IF_GET_DOUBLE("symbolscaledenom", php_layer->layer->symbolscaledenom)
+                                else IF_GET_LONG("maxclasses",  php_layer->layer->maxclasses)
+                                  else IF_GET_DOUBLE("minscaledenom", php_layer->layer->minscaledenom)
+                                    else IF_GET_DOUBLE("maxscaledenom", php_layer->layer->maxscaledenom)
+                                      else IF_GET_DOUBLE("labelminscaledenom", php_layer->layer->labelminscaledenom)
+                                        else IF_GET_DOUBLE("labelmaxscaledenom", php_layer->layer->labelmaxscaledenom)
+                                          else IF_GET_DOUBLE("maxgeowidth", php_layer->layer->maxgeowidth)
+                                            else IF_GET_DOUBLE("mingeowidth", php_layer->layer->mingeowidth)
+                                              else IF_GET_STRING("mask", php_layer->layer->mask)
+                                                else IF_GET_LONG("minfeaturesize", php_layer->layer->minfeaturesize)
+                                                  else IF_GET_LONG("maxfeatures", php_layer->layer->maxfeatures)
+                                                    else IF_GET_LONG("startindex", php_layer->layer->startindex)
+                                                      else IF_GET_LONG("annotate", php_layer->layer->annotate)
+                                                        else IF_GET_LONG("transform", php_layer->layer->transform)
+                                                          else IF_GET_LONG("labelcache", php_layer->layer->labelcache)
+                                                            else IF_GET_LONG("postlabelcache", php_layer->layer->postlabelcache)
+                                                              else IF_GET_STRING("labelitem", php_layer->layer->labelitem)
+                                                                else IF_GET_STRING("tileitem", php_layer->layer->tileitem)
+                                                                  else IF_GET_STRING("tileindex", php_layer->layer->tileindex)
+                                                                    else IF_GET_STRING("header", php_layer->layer->header)
+                                                                      else IF_GET_STRING("footer", php_layer->layer->footer)
+                                                                        else IF_GET_STRING("connection", php_layer->layer->connection)
+                                                                          else IF_GET_LONG("connectiontype", php_layer->layer->connectiontype)
+                                                                            else IF_GET_STRING("filteritem", php_layer->layer->filteritem)
+                                                                              else IF_GET_STRING("template", php_layer->layer->template)
+                                                                                else IF_GET_LONG("opacity", php_layer->layer->opacity)
+                                                                                  else IF_GET_STRING("styleitem", php_layer->layer->styleitem)
+                                                                                    else IF_GET_LONG("numitems", php_layer->layer->numitems)
+                                                                                      else IF_GET_LONG("numjoins", php_layer->layer->numjoins)
+                                                                                        else IF_GET_LONG("num_processing", php_layer->layer->numprocessing)
+                                                                                          else IF_GET_STRING("requires", php_layer->layer->requires)
+                                                                                            else IF_GET_STRING("labelrequires", php_layer->layer->labelrequires)
+                                                                                              else IF_GET_OBJECT("offsite", mapscript_ce_color, php_layer->offsite, &php_layer->layer->offsite)
+                                                                                                else IF_GET_OBJECT("extent", mapscript_ce_rect, php_layer->extent, &php_layer->layer->extent)
+                                                                                                  else IF_GET_OBJECT("grid",  mapscript_ce_grid, php_layer->grid, (graticuleObj *)(php_layer->layer->layerinfo))
+                                                                                                    else IF_GET_OBJECT("metadata", mapscript_ce_hashtable, php_layer->metadata, &php_layer->layer->metadata)
+                                                                                                      else IF_GET_OBJECT("bindvals", mapscript_ce_hashtable, php_layer->bindvals, &php_layer->layer->bindvals)
+                                                                                                        else IF_GET_OBJECT("cluster", mapscript_ce_cluster, php_layer->cluster, &php_layer->layer->cluster)
+                                                                                                          else IF_GET_OBJECT("projection", mapscript_ce_projection, php_layer->projection, &php_layer->layer->projection)
+                                                                                                            else {
+                                                                                                              mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+                                                                                                            }
 }
 
 PHP_METHOD(layerObj, __set)
 {
-    char *property;
-    long property_len;
-    zval *value;
-    zval *zobj = getThis();
-    php_layer_object *php_layer;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
-                              &property, &property_len, &value) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *value;
+  zval *zobj = getThis();
+  php_layer_object *php_layer;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
+                            &property, &property_len, &value) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-
-    IF_SET_LONG("status", php_layer->layer->status, value)
-    else IF_SET_LONG("debug",  php_layer->layer->debug, value)
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  /* special case for "template" which we want to set to NULL and not an empty string */
+  if(Z_TYPE_P(value)==IS_NULL && !strcmp(property,"template")) {
+    msFree(php_layer->layer->template);
+    php_layer->layer->template = NULL;
+  } else
+  IF_SET_LONG("status", php_layer->layer->status, value)
+  else IF_SET_LONG("debug",  php_layer->layer->debug, value)
     else IF_SET_STRING("classitem", php_layer->layer->classitem, value)
-    else IF_SET_STRING("classgroup", php_layer->layer->classgroup, value)
-    else IF_SET_STRING("name", php_layer->layer->name, value)
-    else IF_SET_STRING("group", php_layer->layer->group, value)
-    else IF_SET_STRING("data", php_layer->layer->data, value)
-    else IF_SET_LONG("type",  php_layer->layer->type, value)
-    else IF_SET_LONG("dump", php_layer->layer->dump, value)
-    else IF_SET_DOUBLE("tolerance", php_layer->layer->tolerance, value)
-    else IF_SET_LONG("toleranceunits", php_layer->layer->toleranceunits, value)
-    else IF_SET_LONG("sizeunits", php_layer->layer->sizeunits, value)
-    else IF_SET_DOUBLE("symbolscaledenom", php_layer->layer->symbolscaledenom, value)
-    else IF_SET_DOUBLE("minscaledenom", php_layer->layer->minscaledenom, value)
-    else IF_SET_DOUBLE("maxscaledenom", php_layer->layer->maxscaledenom, value)
-    else IF_SET_LONG("minfeaturesize", php_layer->layer->minfeaturesize, value)
-    else IF_SET_DOUBLE("labelminscaledenom", php_layer->layer->labelminscaledenom, value)
-    else IF_SET_DOUBLE("labelmaxscaledenom", php_layer->layer->labelmaxscaledenom, value)
-    else IF_SET_LONG("maxfeatures", php_layer->layer->maxfeatures, value)
-    else IF_SET_LONG("startindex", php_layer->layer->startindex, value)
-    else IF_SET_LONG("annotate", php_layer->layer->annotate, value)
-    else IF_SET_LONG("transform", php_layer->layer->transform, value)
-    else IF_SET_LONG("labelcache", php_layer->layer->labelcache, value)
-    else IF_SET_LONG("postlabelcache", php_layer->layer->postlabelcache, value)
-    else IF_SET_STRING("labelitem", php_layer->layer->labelitem, value)
-    else IF_SET_STRING("tileitem", php_layer->layer->tileitem, value)
-    else IF_SET_STRING("tileindex", php_layer->layer->tileindex, value)
-    else IF_SET_STRING("header", php_layer->layer->header, value)
-    else IF_SET_STRING("footer", php_layer->layer->footer, value)
-    else IF_SET_STRING("connection", php_layer->layer->connection, value)
-    else IF_SET_STRING("filteritem", php_layer->layer->filteritem, value)
-    else IF_SET_STRING("template", php_layer->layer->template, value)
-    else IF_SET_LONG("opacity", php_layer->layer->opacity, value)
-    else IF_SET_STRING("styleitem", php_layer->layer->styleitem, value)
-    else IF_SET_LONG("num_processing", php_layer->layer->numprocessing, value)
-    else IF_SET_STRING("requires", php_layer->layer->requires, value)
-    else IF_SET_STRING("labelrequires", php_layer->layer->labelrequires, value)
-    else if ( (STRING_EQUAL("offsite", property)) ||
-              (STRING_EQUAL("grid", property)) ||
-              (STRING_EQUAL("metadata", property)) ||
-              (STRING_EQUAL("bindvals", property)) ||
-              (STRING_EQUAL("projection", property)) ||
-              (STRING_EQUAL("cluster", property)) )
-    {
-        mapscript_throw_exception("Property '%s' is an object and can only be modified through its accessors." TSRMLS_CC, property);
-    }
-    else if ( (STRING_EQUAL("numclasses", property)) ||
-              (STRING_EQUAL("index", property)) ||
-              (STRING_EQUAL("connectiontype", property)) )
-    {
-        mapscript_throw_exception("Property '%s' is read-only and cannot be set." TSRMLS_CC, property);
-    }
-    else 
-    {
-        mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }         
+      else IF_SET_STRING("bandsitem", php_layer->layer->bandsitem, value)
+        else IF_SET_STRING("classgroup", php_layer->layer->classgroup, value)
+          else IF_SET_STRING("name", php_layer->layer->name, value)
+            else IF_SET_STRING("group", php_layer->layer->group, value)
+              else IF_SET_STRING("data", php_layer->layer->data, value)
+                else IF_SET_LONG("type",  php_layer->layer->type, value)
+                  else IF_SET_LONG("dump", php_layer->layer->dump, value)
+                    else IF_SET_DOUBLE("tolerance", php_layer->layer->tolerance, value)
+                      else IF_SET_LONG("toleranceunits", php_layer->layer->toleranceunits, value)
+                        else IF_SET_LONG("sizeunits", php_layer->layer->sizeunits, value)
+                          else IF_SET_DOUBLE("symbolscaledenom", php_layer->layer->symbolscaledenom, value)
+                            else IF_SET_DOUBLE("minscaledenom", php_layer->layer->minscaledenom, value)
+                              else IF_SET_DOUBLE("maxscaledenom", php_layer->layer->maxscaledenom, value)
+                                else IF_SET_LONG("minfeaturesize", php_layer->layer->minfeaturesize, value)
+                                  else IF_SET_DOUBLE("labelminscaledenom", php_layer->layer->labelminscaledenom, value)
+                                    else IF_SET_DOUBLE("labelmaxscaledenom", php_layer->layer->labelmaxscaledenom, value)
+                                      else IF_SET_DOUBLE("maxgeowidth", php_layer->layer->maxgeowidth, value)
+                                        else IF_SET_DOUBLE("mingeowidth", php_layer->layer->mingeowidth, value)
+                                          else IF_SET_STRING("mask", php_layer->layer->mask, value)
+                                            else IF_SET_LONG("maxfeatures", php_layer->layer->maxfeatures, value)
+                                              else IF_SET_LONG("startindex", php_layer->layer->startindex, value)
+                                                else IF_SET_LONG("annotate", php_layer->layer->annotate, value)
+                                                  else IF_SET_LONG("transform", php_layer->layer->transform, value)
+                                                    else IF_SET_LONG("labelcache", php_layer->layer->labelcache, value)
+                                                      else IF_SET_LONG("postlabelcache", php_layer->layer->postlabelcache, value)
+                                                        else IF_SET_STRING("labelitem", php_layer->layer->labelitem, value)
+                                                          else IF_SET_STRING("tileitem", php_layer->layer->tileitem, value)
+                                                            else IF_SET_STRING("tileindex", php_layer->layer->tileindex, value)
+                                                              else IF_SET_STRING("header", php_layer->layer->header, value)
+                                                                else IF_SET_STRING("footer", php_layer->layer->footer, value)
+                                                                  else IF_SET_STRING("connection", php_layer->layer->connection, value)
+                                                                    else IF_SET_STRING("filteritem", php_layer->layer->filteritem, value)
+                                                                      else IF_SET_STRING("template", php_layer->layer->template, value)
+                                                                        else IF_SET_LONG("opacity", php_layer->layer->opacity, value)
+                                                                          else IF_SET_STRING("styleitem", php_layer->layer->styleitem, value)
+                                                                            else IF_SET_LONG("num_processing", php_layer->layer->numprocessing, value)
+                                                                              else IF_SET_STRING("requires", php_layer->layer->requires, value)
+                                                                                else IF_SET_STRING("labelrequires", php_layer->layer->labelrequires, value)
+                                                                                  else if ( (STRING_EQUAL("offsite", property)) ||
+                                                                                            (STRING_EQUAL("grid", property)) ||
+                                                                                            (STRING_EQUAL("metadata", property)) ||
+                                                                                            (STRING_EQUAL("bindvals", property)) ||
+                                                                                            (STRING_EQUAL("projection", property)) ||
+                                                                                            (STRING_EQUAL("maxclasses", property)) ||
+                                                                                            (STRING_EQUAL("numitems", property)) ||
+                                                                                            (STRING_EQUAL("numjoins", property)) ||
+                                                                                            (STRING_EQUAL("extent", property)) ||
+                                                                                            (STRING_EQUAL("cluster", property)) ) {
+                                                                                    mapscript_throw_exception("Property '%s' is an object and can only be modified through its accessors." TSRMLS_CC, property);
+                                                                                  } else if ( (STRING_EQUAL("numclasses", property)) ||
+                                                                                              (STRING_EQUAL("index", property)) ||
+                                                                                              (STRING_EQUAL("connectiontype", property)) ) {
+                                                                                    mapscript_throw_exception("Property '%s' is read-only and cannot be set." TSRMLS_CC, property);
+                                                                                  } else {
+                                                                                    mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+                                                                                  }
 }
 
 /* {{{ proto int draw(imageObj image)
    Draw a single layer, add labels to cache if required. Returns MS_FAILURE on error. */
 PHP_METHOD(layerObj, draw)
 {
-    zval *zobj = getThis();
-    zval *zimage;
-    int status = MS_FAILURE;
-    php_layer_object *php_layer;
-    php_map_object *php_map;
-    php_image_object *php_image;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
-                              &zimage, mapscript_ce_image) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  zval *zimage;
+  int status = MS_FAILURE;
+  php_layer_object *php_layer;
+  php_map_object *php_map;
+  php_image_object *php_image;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
+                            &zimage, mapscript_ce_image) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_image = (php_image_object *) zend_object_store_get_object(zimage TSRMLS_CC);
-
-    if (!php_layer->parent.val)
-    {
-        mapscript_throw_exception("No map object associated with this layer object." TSRMLS_CC);
-        return;
-    }
-    
-    php_map = (php_map_object *) zend_object_store_get_object(php_layer->parent.val TSRMLS_CC);
-    
-    if ((status = layerObj_draw(php_layer->layer, php_map->map, php_image->image)) != MS_SUCCESS)
-        mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
-    
-    RETURN_LONG(status);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_image = (php_image_object *) zend_object_store_get_object(zimage TSRMLS_CC);
+
+  if (!php_layer->parent.val) {
+    mapscript_throw_exception("No map object associated with this layer object." TSRMLS_CC);
+    return;
+  }
+
+  php_map = (php_map_object *) zend_object_store_get_object(php_layer->parent.val TSRMLS_CC);
+
+  if ((status = layerObj_draw(php_layer->layer, php_map->map, php_image->image)) != MS_SUCCESS)
+    mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -415,36 +449,35 @@ PHP_METHOD(layerObj, draw)
    Draw query results for a layer. */
 PHP_METHOD(layerObj, drawQuery)
 {
-    zval *zobj = getThis();
-    zval *zimage;
-    int status = MS_FAILURE;
-    php_layer_object *php_layer;
-    php_map_object *php_map;
-    php_image_object *php_image;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
-                              &zimage, mapscript_ce_image) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  zval *zimage;
+  int status = MS_FAILURE;
+  php_layer_object *php_layer;
+  php_map_object *php_map;
+  php_image_object *php_image;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
+                            &zimage, mapscript_ce_image) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_image = (php_image_object *) zend_object_store_get_object(zimage TSRMLS_CC);
-
-    if (!php_layer->parent.val)
-    {
-        mapscript_throw_exception("No map object associated with this layer object." TSRMLS_CC);
-        return;
-    }
-    
-    php_map = (php_map_object *) zend_object_store_get_object(php_layer->parent.val TSRMLS_CC);
-    
-    if ((status = layerObj_drawQuery(php_layer->layer, php_map->map, php_image->image)) != MS_SUCCESS)
-        mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
-    
-    RETURN_LONG(status);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_image = (php_image_object *) zend_object_store_get_object(zimage TSRMLS_CC);
+
+  if (!php_layer->parent.val) {
+    mapscript_throw_exception("No map object associated with this layer object." TSRMLS_CC);
+    return;
+  }
+
+  php_map = (php_map_object *) zend_object_store_get_object(php_layer->parent.val TSRMLS_CC);
+
+  if ((status = layerObj_drawQuery(php_layer->layer, php_map->map, php_image->image)) != MS_SUCCESS)
+    mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -452,40 +485,39 @@ PHP_METHOD(layerObj, drawQuery)
    Query at point location. */
 PHP_METHOD(layerObj, queryByPoint)
 {
-    zval *zobj = getThis();
-    zval *zpoint;
-    int status = MS_FAILURE;
-    long mode;
-    double buffer;
-    php_layer_object *php_layer;
-    php_map_object *php_map;
-    php_point_object *php_point;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Old",
-                              &zpoint, mapscript_ce_point,
-                              &mode, &buffer) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  zval *zpoint;
+  int status = MS_FAILURE;
+  long mode;
+  double buffer;
+  php_layer_object *php_layer;
+  php_map_object *php_map;
+  php_point_object *php_point;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Old",
+                            &zpoint, mapscript_ce_point,
+                            &mode, &buffer) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_point = (php_point_object *) zend_object_store_get_object(zpoint TSRMLS_CC);
-
-    if (!php_layer->parent.val)
-    {
-        mapscript_throw_exception("No map object associated with this layer object." TSRMLS_CC);
-        return;
-    }
-    
-    php_map = (php_map_object *) zend_object_store_get_object(php_layer->parent.val TSRMLS_CC);
-    
-    if ((status = layerObj_queryByPoint(php_layer->layer, php_map->map, php_point->point, 
-                                        mode, buffer)) != MS_SUCCESS)
-        mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
-    
-    RETURN_LONG(status);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_point = (php_point_object *) zend_object_store_get_object(zpoint TSRMLS_CC);
+
+  if (!php_layer->parent.val) {
+    mapscript_throw_exception("No map object associated with this layer object." TSRMLS_CC);
+    return;
+  }
+
+  php_map = (php_map_object *) zend_object_store_get_object(php_layer->parent.val TSRMLS_CC);
+
+  if ((status = layerObj_queryByPoint(php_layer->layer, php_map->map, php_point->point,
+                                      mode, buffer)) != MS_SUCCESS)
+    mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -493,36 +525,35 @@ PHP_METHOD(layerObj, queryByPoint)
    Query using rectangular extent. */
 PHP_METHOD(layerObj, queryByRect)
 {
-    zval *zobj = getThis();
-    zval *zrect;
-    int status = MS_FAILURE;
-    php_layer_object *php_layer;
-    php_map_object *php_map;
-    php_rect_object *php_rect;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
-                              &zrect, mapscript_ce_rect) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  zval *zrect;
+  int status = MS_FAILURE;
+  php_layer_object *php_layer;
+  php_map_object *php_map;
+  php_rect_object *php_rect;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
+                            &zrect, mapscript_ce_rect) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_rect = (php_rect_object *) zend_object_store_get_object(zrect TSRMLS_CC);
-
-    if (!php_layer->parent.val)
-    {
-        mapscript_throw_exception("No map object associated with this layer object." TSRMLS_CC);
-        return;
-    }
-    
-    php_map = (php_map_object *) zend_object_store_get_object(php_layer->parent.val TSRMLS_CC);
-    
-    if ((status = layerObj_queryByRect(php_layer->layer, php_map->map, *(php_rect->rect))) != MS_SUCCESS)
-        mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
-    
-    RETURN_LONG(status);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_rect = (php_rect_object *) zend_object_store_get_object(zrect TSRMLS_CC);
+
+  if (!php_layer->parent.val) {
+    mapscript_throw_exception("No map object associated with this layer object." TSRMLS_CC);
+    return;
+  }
+
+  php_map = (php_map_object *) zend_object_store_get_object(php_layer->parent.val TSRMLS_CC);
+
+  if ((status = layerObj_queryByRect(php_layer->layer, php_map->map, *(php_rect->rect))) != MS_SUCCESS)
+    mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -530,36 +561,35 @@ PHP_METHOD(layerObj, queryByRect)
    Query using a shape */
 PHP_METHOD(layerObj, queryByShape)
 {
-    zval *zobj = getThis();
-    zval *zshape;
-    int status = MS_FAILURE;
-    php_layer_object *php_layer;
-    php_map_object *php_map;
-    php_shape_object *php_shape;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
-                              &zshape, mapscript_ce_shape) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  zval *zshape;
+  int status = MS_FAILURE;
+  php_layer_object *php_layer;
+  php_map_object *php_map;
+  php_shape_object *php_shape;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
+                            &zshape, mapscript_ce_shape) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_shape = (php_shape_object *) zend_object_store_get_object(zshape TSRMLS_CC);
-
-    if (!php_layer->parent.val)
-    {
-        mapscript_throw_exception("No map object associated with this layer object." TSRMLS_CC);
-        return;
-    }
-    
-    php_map = (php_map_object *) zend_object_store_get_object(php_layer->parent.val TSRMLS_CC);
-    
-    if ((status = layerObj_queryByShape(php_layer->layer, php_map->map, php_shape->shape)) != MS_SUCCESS)
-        mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
-    
-    RETURN_LONG(status);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_shape = (php_shape_object *) zend_object_store_get_object(zshape TSRMLS_CC);
+
+  if (!php_layer->parent.val) {
+    mapscript_throw_exception("No map object associated with this layer object." TSRMLS_CC);
+    return;
+  }
+
+  php_map = (php_map_object *) zend_object_store_get_object(php_layer->parent.val TSRMLS_CC);
+
+  if ((status = layerObj_queryByShape(php_layer->layer, php_map->map, php_shape->shape)) != MS_SUCCESS)
+    mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -567,34 +597,33 @@ PHP_METHOD(layerObj, queryByShape)
    Query on a layer using query object. */
 PHP_METHOD(layerObj, queryByFeatures)
 {
-    zval *zobj = getThis();
-    long slayer;
-    int status = MS_FAILURE;
-    php_layer_object *php_layer;
-    php_map_object *php_map;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
-                              &slayer) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  long slayer;
+  int status = MS_FAILURE;
+  php_layer_object *php_layer;
+  php_map_object *php_map;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
+                            &slayer) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    if (!php_layer->parent.val)
-    {
-        mapscript_throw_exception("No map object associated with this layer object." TSRMLS_CC);
-        return;
-    }
-    
-    php_map = (php_map_object *) zend_object_store_get_object(php_layer->parent.val TSRMLS_CC);
-    
-    if ((status = layerObj_queryByFeatures(php_layer->layer, php_map->map, slayer)) != MS_SUCCESS)
-        mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
-    
-    RETURN_LONG(status);
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  if (!php_layer->parent.val) {
+    mapscript_throw_exception("No map object associated with this layer object." TSRMLS_CC);
+    return;
+  }
+
+  php_map = (php_map_object *) zend_object_store_get_object(php_layer->parent.val TSRMLS_CC);
+
+  if ((status = layerObj_queryByFeatures(php_layer->layer, php_map->map, slayer)) != MS_SUCCESS)
+    mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -602,41 +631,112 @@ PHP_METHOD(layerObj, queryByFeatures)
    Query at point location. */
 PHP_METHOD(layerObj, queryByAttributes)
 {
-    zval *zobj = getThis();
-    char *item;
-    long item_len;
-    char *string;
-    long string_len;
-    long mode;
-    int status = MS_FAILURE;
-    php_layer_object *php_layer;
-    php_map_object *php_map;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ssl",
-                              &item, &item_len,
-                              &string, &string_len,
-                              &mode) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  char *item;
+  long item_len;
+  char *string;
+  long string_len;
+  long mode;
+  int status = MS_FAILURE;
+  php_layer_object *php_layer;
+  php_map_object *php_map;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ssl",
+                            &item, &item_len,
+                            &string, &string_len,
+                            &mode) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    if (!php_layer->parent.val)
-    {
-        mapscript_throw_exception("No map object associated with this layer object." TSRMLS_CC);
-        return;
-    }
-    
-    php_map = (php_map_object *) zend_object_store_get_object(php_layer->parent.val TSRMLS_CC);
-    
-    if ((status = layerObj_queryByAttributes(php_layer->layer, php_map->map,
-                                             item, string, mode)) != MS_SUCCESS)
-        mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
-    
-    RETURN_LONG(status);
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  if (!php_layer->parent.val) {
+    mapscript_throw_exception("No map object associated with this layer object." TSRMLS_CC);
+    return;
+  }
+
+  php_map = (php_map_object *) zend_object_store_get_object(php_layer->parent.val TSRMLS_CC);
+
+  if ((status = layerObj_queryByAttributes(php_layer->layer, php_map->map,
+                item, string, mode)) != MS_SUCCESS)
+    mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
+
+  RETURN_LONG(status);
+}
+/* }}} */
+
+/* {{{ proto int layer.queryByFilter(string string)
+   Query by filter. */
+PHP_METHOD(layerObj, queryByFilter)
+{
+  zval *zobj = getThis();
+  char *string;
+  long string_len;
+  int status = MS_FAILURE;
+  php_layer_object *php_layer;
+  php_map_object *php_map;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &string, &string_len) == FAILURE) {
+    PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  if (!php_layer->parent.val) {
+    mapscript_throw_exception("No map object associated with this layer object." TSRMLS_CC);
+    return;
+  }
+
+  php_map = (php_map_object *) zend_object_store_get_object(php_layer->parent.val TSRMLS_CC);
+
+  if ((status = layerObj_queryByFilter(php_layer->layer, php_map->map,
+                                       string)) != MS_SUCCESS)
+    mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
+
+  RETURN_LONG(status);
+}
+/* }}} */
+
+/* {{{ proto int layer.queryByIndex(int tileindex, int shapeindex, int addtoquery)
+   Query by index. */
+PHP_METHOD(layerObj, queryByIndex)
+{
+  zval *zobj = getThis();
+  long tileindex, shapeindex;
+  long addtoquery=MS_FALSE;
+  int status = MS_FAILURE;
+  php_layer_object *php_layer;
+  php_map_object *php_map;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ll|l",
+                            &tileindex, &shapeindex, &addtoquery) == FAILURE) {
+    PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  if (!php_layer->parent.val) {
+    mapscript_throw_exception("No map object associated with this layer object." TSRMLS_CC);
+    return;
+  }
+
+  php_map = (php_map_object *) zend_object_store_get_object(php_layer->parent.val TSRMLS_CC);
+
+  if ((status = layerObj_queryByIndex(php_layer->layer, php_map->map,
+                                      tileindex, shapeindex, addtoquery)) != MS_SUCCESS)
+    mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -644,29 +744,28 @@ PHP_METHOD(layerObj, queryByAttributes)
    Update a layer from a string snippet.  Returns MS_SUCCESS/MS_FAILURE */
 PHP_METHOD(layerObj, updateFromString)
 {
-    zval *zobj = getThis();
-    char *snippet;
-    long snippet_len;
-    int status = MS_FAILURE;
-    php_layer_object *php_layer;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &snippet, &snippet_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  char *snippet;
+  long snippet_len;
+  int status = MS_FAILURE;
+  php_layer_object *php_layer;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &snippet, &snippet_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    if ((status = layerObj_updateFromString(php_layer->layer, snippet)) != MS_SUCCESS)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    RETURN_LONG(status);
+  if ((status = layerObj_updateFromString(php_layer->layer, snippet)) != MS_SUCCESS) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -674,31 +773,30 @@ PHP_METHOD(layerObj, updateFromString)
    Returns a classObj from the layer given an index value (0=first class) */
 PHP_METHOD(layerObj, getClass)
 {
-    zval *zobj = getThis();
-    long index;
-    classObj *class = NULL;
-    php_layer_object *php_layer;
-    parent_object parent;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
-                              &index) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  long index;
+  classObj *class = NULL;
+  php_layer_object *php_layer;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
+                            &index) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    if ((class = layerObj_getClass(php_layer->layer, index)) == NULL)
-    {
-        mapscript_throw_exception("Invalid class index." TSRMLS_CC);
-        return;
-    }
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  if ((class = layerObj_getClass(php_layer->layer, index)) == NULL) {
+    mapscript_throw_exception("Invalid class index." TSRMLS_CC);
+    return;
+  }
 
-    /* Return class object */
-    MAPSCRIPT_MAKE_PARENT(zobj, NULL);
-    mapscript_create_class(class, parent, return_value TSRMLS_CC);
+  /* Return class object */
+  MAPSCRIPT_MAKE_PARENT(zobj, NULL);
+  mapscript_create_class(class, parent, return_value TSRMLS_CC);
 }
 /* }}} */
 
@@ -706,58 +804,55 @@ PHP_METHOD(layerObj, getClass)
    Returns the class index for the shape */
 PHP_METHOD(layerObj, getClassIndex)
 {
-    zval *zobj = getThis();
-    zval *zshape, **ppzval, *zclassgroup = NULL;
-    int numElements, *classGroups = NULL;
-    int retval = -1, i = 0;
-    long numClasses = 0;
-    HashTable *classgroup_hash = NULL;
-    php_shape_object *php_shape;
-    php_layer_object *php_layer;
-    php_map_object *php_map;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O|a!l",
-                              &zshape, mapscript_ce_shape,
-                              &zclassgroup,
-                              &numClasses) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  zval *zshape, **ppzval, *zclassgroup = NULL;
+  int numElements, *classGroups = NULL;
+  int retval = -1, i = 0;
+  long numClasses = 0;
+  HashTable *classgroup_hash = NULL;
+  php_shape_object *php_shape;
+  php_layer_object *php_layer;
+  php_map_object *php_map;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O|a!l",
+                            &zshape, mapscript_ce_shape,
+                            &zclassgroup,
+                            &numClasses) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_shape = (php_shape_object *) zend_object_store_get_object(zshape TSRMLS_CC);
-
-    if (!php_layer->parent.val)
-    {
-        mapscript_throw_exception("No map object associated with this layer object." TSRMLS_CC);
-        return;
-    }
-    
-    php_map = (php_map_object *) zend_object_store_get_object(php_layer->parent.val TSRMLS_CC);
-
-    if (zclassgroup)
-    {
-        classgroup_hash = Z_ARRVAL_P(zclassgroup);
-        numElements = zend_hash_num_elements(classgroup_hash);
-        classGroups = (int*)malloc(sizeof(int)*numElements);
-        
-        for(zend_hash_internal_pointer_reset(classgroup_hash); 
-            zend_hash_has_more_elements(classgroup_hash) == SUCCESS; 
-            zend_hash_move_forward(classgroup_hash), ++i)
-        {     
-            zend_hash_get_current_data(classgroup_hash, (void **)&ppzval);
-            classGroups[i] = Z_LVAL_PP(ppzval);
-        }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_shape = (php_shape_object *) zend_object_store_get_object(zshape TSRMLS_CC);
+
+  if (!php_layer->parent.val) {
+    mapscript_throw_exception("No map object associated with this layer object." TSRMLS_CC);
+    return;
+  }
+
+  php_map = (php_map_object *) zend_object_store_get_object(php_layer->parent.val TSRMLS_CC);
+
+  if (zclassgroup) {
+    classgroup_hash = Z_ARRVAL_P(zclassgroup);
+    numElements = zend_hash_num_elements(classgroup_hash);
+    classGroups = (int*)malloc(sizeof(int)*numElements);
+
+    for(zend_hash_internal_pointer_reset(classgroup_hash);
+        zend_hash_has_more_elements(classgroup_hash) == SUCCESS;
+        zend_hash_move_forward(classgroup_hash), ++i) {
+      zend_hash_get_current_data(classgroup_hash, (void **)&ppzval);
+      classGroups[i] = Z_LVAL_PP(ppzval);
     }
-    
-    retval = layerObj_getClassIndex(php_layer->layer, php_map->map, php_shape->shape, classGroups, numClasses);
-  
-    if (zclassgroup)
-        free(classGroups);
+  }
+
+  retval = layerObj_getClassIndex(php_layer->layer, php_map->map, php_shape->shape, classGroups, numClasses);
+
+  if (zclassgroup)
+    free(classGroups);
 
-    RETURN_LONG(retval);
+  RETURN_LONG(retval);
 }
 /* }}} */
 
@@ -766,29 +861,28 @@ PHP_METHOD(layerObj, getClassIndex)
    Set layer filter expression.  Returns 0 on success, -1 in error. */
 PHP_METHOD(layerObj, setFilter)
 {
-    zval *zobj = getThis();
-    char *expression;
-    long expression_len;
-    int status = MS_FAILURE;
-    php_layer_object *php_layer;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &expression, &expression_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  char *expression;
+  long expression_len;
+  int status = MS_FAILURE;
+  php_layer_object *php_layer;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &expression, &expression_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    if ((status = layerObj_setFilter(php_layer->layer, expression)) != MS_SUCCESS)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    RETURN_LONG(status);
+  if ((status = layerObj_setFilter(php_layer->layer, expression)) != MS_SUCCESS) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -796,27 +890,26 @@ PHP_METHOD(layerObj, setFilter)
     Return the layer's filter expression. Returns NULL on error. */
 PHP_METHOD(layerObj, getFilterString)
 {
-    zval *zobj = getThis();
-    char *value = NULL;
-    php_layer_object *php_layer;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  char *value = NULL;
+  php_layer_object *php_layer;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    value = layerObj_getFilter(php_layer->layer);
-    if (value == NULL)
-    {
-        RETURN_NULL();
-    }
-    
-    RETVAL_STRING(value, 1);
-    free(value);
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  value = layerObj_getFilter(php_layer->layer);
+  if (value == NULL) {
+    RETURN_NULL();
+  }
+
+  RETVAL_STRING(value, 1);
+  free(value);
 }
 /* }}} */
 
@@ -824,35 +917,34 @@ PHP_METHOD(layerObj, getFilterString)
    Set projection and coord. system for the layer. */
 PHP_METHOD(layerObj, setProjection)
 {
-    zval *zobj = getThis();
-    char *projection;
-    long projection_len;
-    int status = MS_FAILURE;
-    php_layer_object *php_layer;
-    php_projection_object *php_projection;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &projection, &projection_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  char *projection;
+  long projection_len;
+  int status = MS_FAILURE;
+  php_layer_object *php_layer;
+  php_projection_object *php_projection=NULL;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &projection, &projection_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    if (php_layer->projection)
-        php_projection = (php_projection_object *) zend_object_store_get_object(php_layer->projection TSRMLS_CC);
-
-    if ((status = layerObj_setProjection(php_layer->layer, projection)) != MS_SUCCESS)
-    {
-        mapscript_report_php_error(E_WARNING, "setProjection failed" TSRMLS_CC);
-        RETURN_LONG(status);
-    }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    if (php_layer->projection)
-        php_projection->projection = &(php_layer->layer->projection);
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  if (php_layer->projection)
+    php_projection = (php_projection_object *) zend_object_store_get_object(php_layer->projection TSRMLS_CC);
 
+  if ((status = layerObj_setProjection(php_layer->layer, projection)) != MS_SUCCESS) {
+    mapscript_report_php_error(E_WARNING, "setProjection failed" TSRMLS_CC);
     RETURN_LONG(status);
+  }
+
+  if (php_layer->projection)
+    php_projection->projection = &(php_layer->layer->projection);
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -860,27 +952,26 @@ PHP_METHOD(layerObj, setProjection)
     Return the projection string of the layer. Returns NULL on error. */
 PHP_METHOD(layerObj, getProjection)
 {
-    zval *zobj = getThis();
-    char *projection = NULL;
-    php_layer_object *php_layer;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  char *projection = NULL;
+  php_layer_object *php_layer;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    projection = layerObj_getProjection(php_layer->layer);
-    if (projection == NULL)
-    {
-        RETURN_NULL();
-    }
-    
-    RETVAL_STRING(projection, 1);
-    free(projection);
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  projection = layerObj_getProjection(php_layer->layer);
+  if (projection == NULL) {
+    RETURN_NULL();
+  }
+
+  RETVAL_STRING(projection, 1);
+  free(projection);
 }
 /* }}} */
 
@@ -888,35 +979,34 @@ PHP_METHOD(layerObj, getProjection)
    Set projection and coord. system for the layer. */
 PHP_METHOD(layerObj, setWKTProjection)
 {
-    zval *zobj = getThis();
-    char *projection;
-    long projection_len;
-    int status = MS_FAILURE;
-    php_layer_object *php_layer;
-    php_projection_object *php_projection;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &projection, &projection_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  char *projection;
+  long projection_len;
+  int status = MS_FAILURE;
+  php_layer_object *php_layer;
+  php_projection_object *php_projection=NULL;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &projection, &projection_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    if (php_layer->projection)
-        php_projection = (php_projection_object *) zend_object_store_get_object(php_layer->projection TSRMLS_CC);
-
-    if ((status = layerObj_setWKTProjection(php_layer->layer, projection)) != MS_SUCCESS)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    if (php_layer->projection)
-        php_projection->projection = &(php_layer->layer->projection);
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  if (php_layer->projection)
+    php_projection = (php_projection_object *) zend_object_store_get_object(php_layer->projection TSRMLS_CC);
 
-    RETURN_LONG(status);
+  if ((status = layerObj_setWKTProjection(php_layer->layer, projection)) != MS_SUCCESS) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
+
+  if (php_layer->projection)
+    php_projection->projection = &(php_layer->layer->projection);
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -924,23 +1014,23 @@ PHP_METHOD(layerObj, setWKTProjection)
    Returns the number of results from this layer in the last query. */
 PHP_METHOD(layerObj, getNumResults)
 {
-    zval *zobj = getThis();
-    php_layer_object *php_layer;
+  zval *zobj = getThis();
+  php_layer_object *php_layer;
 
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
 
-    if (!php_layer->layer->resultcache)
-        RETURN_LONG(0);
+  if (!php_layer->layer->resultcache)
+    RETURN_LONG(0);
 
-    RETURN_LONG(php_layer->layer->resultcache->numresults);
+  RETURN_LONG(php_layer->layer->resultcache->numresults);
 }
 /* }}} */
 
@@ -948,59 +1038,58 @@ PHP_METHOD(layerObj, getNumResults)
    Returns the bounds of results from this layer in the last query. */
 PHP_METHOD(layerObj, getResultsBounds)
 {
-    zval *zobj = getThis();
-    php_layer_object *php_layer;
-    parent_object parent;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  php_layer_object *php_layer;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    if (!php_layer->layer->resultcache)
-        RETURN_NULL();
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    /* Return result object */
-    MAPSCRIPT_MAKE_PARENT(zobj, NULL);
-    mapscript_create_rect(&(php_layer->layer->resultcache->bounds), 
-                          parent, return_value TSRMLS_CC);
+  if (!php_layer->layer->resultcache)
+    RETURN_NULL();
+
+  /* Return result object */
+  MAPSCRIPT_MAKE_PARENT(zobj, NULL);
+  mapscript_create_rect(&(php_layer->layer->resultcache->bounds),
+                        parent, return_value TSRMLS_CC);
 }
 /* }}} */
 
 /* {{{ proto int layer.getResult(int i)
-   Returns a resultObj by index from a layer object.*/  
+   Returns a resultObj by index from a layer object.*/
 PHP_METHOD(layerObj, getResult)
 {
-    zval *zobj = getThis();
-    long index;
-    resultObj *result = NULL;
-    php_layer_object *php_layer;
-    parent_object parent;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
-                              &index) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  long index;
+  resultObj *result = NULL;
+  php_layer_object *php_layer;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
+                            &index) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    if ((result = layerObj_getResult(php_layer->layer, index)) == NULL)
-    {
-        mapscript_throw_exception("Invalid result index." TSRMLS_CC);
-        return;
-    }
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  if ((result = layerObj_getResult(php_layer->layer, index)) == NULL) {
+    mapscript_throw_exception("Invalid result index." TSRMLS_CC);
+    return;
+  }
 
-    /* Return result object */
-    MAPSCRIPT_MAKE_PARENT(zobj, NULL);
-    mapscript_create_result(&(php_layer->layer->resultcache->results[index]), 
-                            parent, return_value TSRMLS_CC);
+  /* Return result object */
+  MAPSCRIPT_MAKE_PARENT(zobj, NULL);
+  mapscript_create_result(&(php_layer->layer->resultcache->results[index]),
+                          parent, return_value TSRMLS_CC);
 }
 /* }}} */
 
@@ -1008,32 +1097,29 @@ PHP_METHOD(layerObj, getResult)
    Open the layer for use with getShape(). Returns MS_SUCCESS/MS_FAILURE. */
 PHP_METHOD(layerObj, open)
 {
-    zval *zobj = getThis();
-    int status = MS_FAILURE;
-    php_layer_object *php_layer;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  int status = MS_FAILURE;
+  php_layer_object *php_layer;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    status = layerObj_open(php_layer->layer);
-    if (status != MS_SUCCESS) 
-    {
-        mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
-        RETURN_LONG(status);
-    }
-    else
-    {
-        msLayerGetItems(php_layer->layer);
-    }
-        
+
+  status = layerObj_open(php_layer->layer);
+  if (status != MS_SUCCESS) {
+    mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
     RETURN_LONG(status);
+  } else {
+    msLayerGetItems(php_layer->layer);
+  }
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -1050,55 +1136,55 @@ PHP_METHOD(layerObj, open)
 */
 PHP_METHOD(layerObj, whichShapes)
 {
-    zval *zobj = getThis();
-    zval *zrect;
-    int status = MS_FAILURE;
-    php_layer_object *php_layer;
-    php_rect_object *php_rect;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
-                              &zrect, mapscript_ce_rect) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  zval *zrect;
+  int status = MS_FAILURE;
+  php_layer_object *php_layer;
+  php_rect_object *php_rect;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
+                            &zrect, mapscript_ce_rect) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_rect = (php_rect_object *) zend_object_store_get_object(zrect TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_rect = (php_rect_object *) zend_object_store_get_object(zrect TSRMLS_CC);
 
-    status = layerObj_whichShapes(php_layer->layer, php_rect->rect);
 
-    RETURN_LONG(status);
+  status = layerObj_whichShapes(php_layer->layer, php_rect->rect);
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
 /* {{{ proto int layer.nextshape() Returns a shape or NULL. */
 PHP_METHOD(layerObj, nextShape)
 {
-    zval *zobj = getThis();
-    shapeObj *shape = NULL;
-    php_layer_object *php_layer;
-    parent_object parent;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  shapeObj *shape = NULL;
+  php_layer_object *php_layer;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    shape = layerObj_nextShape(php_layer->layer);
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    if (!shape)
-        RETURN_NULL();
+  shape = layerObj_nextShape(php_layer->layer);
 
-    /* Return valid object */
-    MAPSCRIPT_MAKE_PARENT(NULL, NULL);
-    mapscript_create_shape(shape, parent, php_layer, return_value TSRMLS_CC);
+  if (!shape)
+    RETURN_NULL();
+
+  /* Return valid object */
+  MAPSCRIPT_MAKE_PARENT(NULL, NULL);
+  mapscript_create_shape(shape, parent, php_layer, return_value TSRMLS_CC);
 }
 /* }}} */
 
@@ -1106,19 +1192,19 @@ PHP_METHOD(layerObj, nextShape)
    Close layer previously opened with open(). */
 PHP_METHOD(layerObj, close)
 {
-    zval *zobj = getThis();
-    php_layer_object *php_layer;
+  zval *zobj = getThis();
+  php_layer_object *php_layer;
 
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    layerObj_close(php_layer->layer);
+  layerObj_close(php_layer->layer);
 }
 /* }}} */
 
@@ -1126,64 +1212,89 @@ PHP_METHOD(layerObj, close)
    Retrieve or calculate a layer's extents. */
 PHP_METHOD(layerObj, getExtent)
 {
-    zval *zobj = getThis();
-    rectObj *rect = NULL;
-    php_layer_object *php_layer;
-    parent_object parent;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  rectObj *rect = NULL;
+  php_layer_object *php_layer;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-
-    /* Create a new rectObj to hold the result */
-    if ((rect = rectObj_new()) == NULL)
-    {
-        mapscript_throw_mapserver_exception("Failed creating new rectObj (out of memory?)" TSRMLS_CC);
-        return;
-    }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  /* Create a new rectObj to hold the result */
+  if ((rect = rectObj_new()) == NULL) {
+    mapscript_throw_mapserver_exception("Failed creating new rectObj (out of memory?)" TSRMLS_CC);
+    return;
+  }
+
+  if (msLayerGetExtent(php_layer->layer, rect) != MS_SUCCESS) {
+    mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
+    RETURN_NULL();
+  }
+
+  /* Return rectObj */
+  MAPSCRIPT_MAKE_PARENT(NULL, NULL);
+  mapscript_create_rect(rect, parent, return_value TSRMLS_CC);
+}
+/* }}} */
 
-    if (msLayerGetExtent(php_layer->layer, rect) != MS_SUCCESS)
-    {
-        mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
-        RETURN_NULL();
-    }
+/* {{{ proto int layer.setExtent(int minx, int miny, int maxx, int maxy)
+   Set the layer extent. */
+PHP_METHOD(layerObj, setExtent)
+{
+  zval *zobj = getThis();
+  long minx, miny, maxx, maxy;
+  php_layer_object *php_layer;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "llll",
+                            &minx, &miny, &maxx, &maxy) == FAILURE) {
+    PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  if (minx > maxx || miny > maxy) {
+    mapscript_throw_mapserver_exception("Invalid min/max values" TSRMLS_CC);
+    return;
+  }
 
-    /* Return rectObj */
-    MAPSCRIPT_MAKE_PARENT(NULL, NULL);   
-    mapscript_create_rect(rect, parent, return_value TSRMLS_CC);
+  RETURN_LONG(msLayerSetExtent(php_layer->layer, minx, miny, maxx, maxy))
 }
 /* }}} */
 
+
 /* {{{ proto int layer.addFeature(ShapeObj poShape)
    Add a shape */
 PHP_METHOD(layerObj, addFeature)
 {
-    zval *zobj = getThis();
-    zval *zshape;
-    int status = MS_FAILURE;
-    php_layer_object *php_layer;
-    php_shape_object *php_shape;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
-                              &zshape, mapscript_ce_shape) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  zval *zshape;
+  int status = MS_FAILURE;
+  php_layer_object *php_layer;
+  php_shape_object *php_shape;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
+                            &zshape, mapscript_ce_shape) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_shape = (php_shape_object *) zend_object_store_get_object(zshape TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_shape = (php_shape_object *) zend_object_store_get_object(zshape TSRMLS_CC);
 
-    status = layerObj_addFeature(php_layer->layer, php_shape->shape);
 
-    RETURN_LONG(status);
+  status = layerObj_addFeature(php_layer->layer, php_shape->shape);
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -1191,25 +1302,25 @@ PHP_METHOD(layerObj, addFeature)
    Return MetaData entry by name, or empty string if not found. */
 PHP_METHOD(layerObj, getMetaData)
 {
-    zval *zname;
-    zval *zobj = getThis();
-    php_layer_object *php_layer;
-    zval *retval;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z",
-                              &zname) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zname;
+  zval *zobj = getThis();
+  php_layer_object *php_layer;
+  zval *retval;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z",
+                            &zname) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    CHECK_OBJECT(mapscript_ce_hashtable, php_layer->metadata, &php_layer->layer->metadata);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    MAPSCRIPT_CALL_METHOD_1(php_layer->metadata, "get", retval, zname);
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  CHECK_OBJECT(mapscript_ce_hashtable, php_layer->metadata, &php_layer->layer->metadata);
 
-    RETURN_STRING(Z_STRVAL_P(retval),1);
+  MAPSCRIPT_CALL_METHOD_1(php_layer->metadata, "get", retval, zname);
+
+  RETURN_STRING(Z_STRVAL_P(retval),1);
 }
 /* }}} */
 
@@ -1217,25 +1328,25 @@ PHP_METHOD(layerObj, getMetaData)
    Set MetaData entry by name.  Returns MS_SUCCESS/MS_FAILURE */
 PHP_METHOD(layerObj, setMetaData)
 {
-    zval *zname, *zvalue;
-    zval *zobj = getThis();
-    php_layer_object *php_layer;
-    zval *retval;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz",
-                              &zname, &zvalue) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zname, *zvalue;
+  zval *zobj = getThis();
+  php_layer_object *php_layer;
+  zval *retval;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz",
+                            &zname, &zvalue) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    CHECK_OBJECT(mapscript_ce_hashtable, php_layer->metadata, &php_layer->layer->metadata);
-    
-    MAPSCRIPT_CALL_METHOD_2(php_layer->metadata, "set", retval, zname, zvalue);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  CHECK_OBJECT(mapscript_ce_hashtable, php_layer->metadata, &php_layer->layer->metadata);
 
-    RETURN_LONG(Z_LVAL_P(retval));
+  MAPSCRIPT_CALL_METHOD_2(php_layer->metadata, "set", retval, zname, zvalue);
+
+  RETURN_LONG(Z_LVAL_P(retval));
 }
 /* }}} */
 
@@ -1243,25 +1354,25 @@ PHP_METHOD(layerObj, setMetaData)
    Remove MetaData entry by name.  Returns MS_SUCCESS/MS_FAILURE */
 PHP_METHOD(layerObj, removeMetaData)
 {
-    zval *zname;
-    zval *zobj = getThis();
-    php_layer_object *php_layer;
-    zval *retval;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z",
-                              &zname) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zname;
+  zval *zobj = getThis();
+  php_layer_object *php_layer;
+  zval *retval;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z",
+                            &zname) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    CHECK_OBJECT(mapscript_ce_hashtable, php_layer->metadata, &php_layer->layer->metadata);
-    
-    MAPSCRIPT_CALL_METHOD_1(php_layer->metadata, "remove", retval, zname);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    RETURN_LONG(Z_LVAL_P(retval));
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  CHECK_OBJECT(mapscript_ce_hashtable, php_layer->metadata, &php_layer->layer->metadata);
+
+  MAPSCRIPT_CALL_METHOD_1(php_layer->metadata, "remove", retval, zname);
+
+  RETURN_LONG(Z_LVAL_P(retval));
 }
 /* }}} */
 
@@ -1269,45 +1380,43 @@ PHP_METHOD(layerObj, removeMetaData)
    Return a WMS GetFeatureInfo URL (only for WMS layers). */
 PHP_METHOD(layerObj, getWMSFeatureInfoURL)
 {
-    zval *zobj = getThis();
-    long clickx, clicky, featureCount;
-    char *infoFormat = NULL;
-    long infoFormat_len;
-    char *value =  NULL;
-    php_layer_object *php_layer;
-    php_map_object *php_map;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "llls",
-                              &clickx, &clicky, &featureCount,
-                              &infoFormat, &infoFormat_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  long clickx, clicky, featureCount;
+  char *infoFormat = NULL;
+  long infoFormat_len;
+  char *value =  NULL;
+  php_layer_object *php_layer;
+  php_map_object *php_map;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "llls",
+                            &clickx, &clicky, &featureCount,
+                            &infoFormat, &infoFormat_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-
-    if (!php_layer->parent.val)
-    {
-        mapscript_throw_exception("No map object associated with this layer object." TSRMLS_CC);
-        return;
-    }
-    
-    php_map = (php_map_object *) zend_object_store_get_object(php_layer->parent.val TSRMLS_CC);
-    
-    if ((value = layerObj_getWMSFeatureInfoURL(php_layer->layer, php_map->map, 
-                                               clickx,
-                                               clicky,
-                                               featureCount,
-                                               infoFormat)) == NULL)
-    {
-        mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
-        RETURN_STRING("", 1);
-    }
-
-    RETVAL_STRING(value, 1);
-    free(value);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  if (!php_layer->parent.val) {
+    mapscript_throw_exception("No map object associated with this layer object." TSRMLS_CC);
+    return;
+  }
+
+  php_map = (php_map_object *) zend_object_store_get_object(php_layer->parent.val TSRMLS_CC);
+
+  if ((value = layerObj_getWMSFeatureInfoURL(php_layer->layer, php_map->map,
+               clickx,
+               clicky,
+               featureCount,
+               infoFormat)) == NULL) {
+    mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
+    RETURN_STRING("", 1);
+  }
+
+  RETVAL_STRING(value, 1);
+  free(value);
 }
 /* }}} */
 
@@ -1315,30 +1424,28 @@ PHP_METHOD(layerObj, getWMSFeatureInfoURL)
    Return an array containing all the layer items.*/
 PHP_METHOD(layerObj, getItems)
 {
-    zval *zobj = getThis();
-    int i, status = MS_FAILURE;
-    php_layer_object *php_layer;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  int i, status = MS_FAILURE;
+  php_layer_object *php_layer;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-
-    array_init(return_value);
-    status = msLayerGetItems(php_layer->layer);
-     
-    if (status != MS_FAILURE &&  php_layer->layer->numitems > 0)
-    {    
-        for (i=0; i<php_layer->layer->numitems; i++)
-        {
-            /* add a copy of the group name to the PHP array */
-            add_next_index_string(return_value, php_layer->layer->items[i], 1);
-        }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  array_init(return_value);
+  status = msLayerGetItems(php_layer->layer);
+
+  if (status != MS_FAILURE &&  php_layer->layer->numitems > 0) {
+    for (i=0; i<php_layer->layer->numitems; i++) {
+      /* add a copy of the group name to the PHP array */
+      add_next_index_string(return_value, php_layer->layer->items[i], 1);
     }
+  }
 }
 /* }}} */
 
@@ -1346,31 +1453,58 @@ PHP_METHOD(layerObj, getItems)
   set a processing string to the layer*/
 PHP_METHOD(layerObj, setProcessing)
 {
-    zval *zobj = getThis();
-    char *string = NULL;
-    long string_len;
-    php_layer_object *php_layer;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &string, &string_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  char *string = NULL;
+  long string_len;
+  php_layer_object *php_layer;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &string, &string_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    php_layer->layer->numprocessing++;
-    if(php_layer->layer->numprocessing == 1)
-        php_layer->layer->processing = (char **) malloc(2*sizeof(char *));
-    else
-        php_layer->layer->processing = (char **) realloc(php_layer->layer->processing, sizeof(char*) * (php_layer->layer->numprocessing+1));
-    
-    php_layer->layer->processing[php_layer->layer->numprocessing-1] = strdup(string);
-    php_layer->layer->processing[php_layer->layer->numprocessing] = NULL;
-    
-    RETURN_LONG(MS_SUCCESS);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  php_layer->layer->numprocessing++;
+  if(php_layer->layer->numprocessing == 1)
+    php_layer->layer->processing = (char **) malloc(2*sizeof(char *));
+  else
+    php_layer->layer->processing = (char **) realloc(php_layer->layer->processing, sizeof(char*) * (php_layer->layer->numprocessing+1));
+
+  php_layer->layer->processing[php_layer->layer->numprocessing-1] = strdup(string);
+  php_layer->layer->processing[php_layer->layer->numprocessing] = NULL;
+
+  RETURN_LONG(MS_SUCCESS);
+}
+/* }}} */
+
+/* {{{ boolean layer.setProcessingKey(string key, string value)
+  set a processing key string to the layer*/
+PHP_METHOD(layerObj, setProcessingKey)
+{
+  zval *zobj = getThis();
+  char *key = NULL;
+  long key_len;
+  char *value = NULL;
+  long value_len;
+  php_layer_object *php_layer;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss",
+                            &key, &key_len, &value, &value_len) == FAILURE) {
+    PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  msLayerSetProcessingKey( php_layer->layer, key, value );
+
+  RETURN_LONG(MS_SUCCESS);
 }
 /* }}} */
 
@@ -1378,27 +1512,25 @@ PHP_METHOD(layerObj, setProcessing)
    Return an array containing all the processing strings.*/
 PHP_METHOD(layerObj, getProcessing)
 {
-    zval *zobj = getThis();
-    int i;
-    php_layer_object *php_layer;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  int i;
+  php_layer_object *php_layer;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-
-    array_init(return_value);
-    if (php_layer->layer->numprocessing > 0)
-    {
-        for (i=0; i<php_layer->layer->numprocessing; i++)
-        {
-            add_next_index_string(return_value, php_layer->layer->processing[i], 1);
-        }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  array_init(return_value);
+  if (php_layer->layer->numprocessing > 0) {
+    for (i=0; i<php_layer->layer->numprocessing; i++) {
+      add_next_index_string(return_value, php_layer->layer->processing[i], 1);
     }
+  }
 }
 /* }}} */
 
@@ -1406,27 +1538,26 @@ PHP_METHOD(layerObj, getProcessing)
    clear the processing strings in the layer*/
 PHP_METHOD(layerObj, clearProcessing)
 {
-    zval *zobj = getThis();
-    int i;
-    php_layer_object *php_layer;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  int i;
+  php_layer_object *php_layer;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    if (php_layer->layer->numprocessing > 0)
-    {
-        for(i=0; i<php_layer->layer->numprocessing; i++)
-            free(php_layer->layer->processing[i]);
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-        php_layer->layer->numprocessing = 0;
-        free(php_layer->layer->processing);
-    }
+  if (php_layer->layer->numprocessing > 0) {
+    for(i=0; i<php_layer->layer->numprocessing; i++)
+      free(php_layer->layer->processing[i]);
+
+    php_layer->layer->numprocessing = 0;
+    free(php_layer->layer->processing);
+  }
 }
 /* }}} */
 
@@ -1434,24 +1565,24 @@ PHP_METHOD(layerObj, clearProcessing)
    Executes a GetFeature request on a WFS layer and returns the name of the temporary GML file created. Returns an empty string on error.*/
 PHP_METHOD(layerObj, executeWFSGetFeature)
 {
-    zval *zobj = getThis();
-    char *value = NULL;
-    php_layer_object *php_layer;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  char *value = NULL;
+  php_layer_object *php_layer;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    if ((value=layerObj_executeWFSGetFeature(php_layer->layer)) == NULL)
-        RETURN_STRING("", 1);
+  if ((value=layerObj_executeWFSGetFeature(php_layer->layer)) == NULL)
+    RETURN_STRING("", 1);
 
-    RETVAL_STRING(value, 1);
-    free(value);
+  RETVAL_STRING(value, 1);
+  free(value);
 }
 /* }}} */
 
@@ -1462,28 +1593,28 @@ PHP_METHOD(layerObj, executeWFSGetFeature)
    the sld that matchs it will be used to style the layer. */
 PHP_METHOD(layerObj, applySLD)
 {
-    zval *zobj = getThis();
-    char *sldxml;
-    long sldxml_len;
-    char *namedLayer = NULL;
-    long namedLayer_len;
-    int status = MS_FAILURE;
-    php_layer_object *php_layer;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s",
-                              &sldxml, &sldxml_len,
-                              &namedLayer, &namedLayer_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  char *sldxml;
+  long sldxml_len;
+  char *namedLayer = NULL;
+  long namedLayer_len;
+  int status = MS_FAILURE;
+  php_layer_object *php_layer;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s",
+                            &sldxml, &sldxml_len,
+                            &namedLayer, &namedLayer_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    status = layerObj_applySLD(php_layer->layer, sldxml, namedLayer);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    RETURN_LONG(status);
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  status = layerObj_applySLD(php_layer->layer, sldxml, namedLayer);
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -1495,28 +1626,28 @@ PHP_METHOD(layerObj, applySLD)
    layer. */
 PHP_METHOD(layerObj, applySLDURL)
 {
-    zval *zobj = getThis();
-    char *sldurl;
-    long sldurl_len;
-    char *namedLayer = NULL;
-    long namedLayer_len;
-    int status = MS_FAILURE;
-    php_layer_object *php_layer;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s",
-                              &sldurl, &sldurl_len,
-                              &namedLayer, &namedLayer_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  char *sldurl;
+  long sldurl_len;
+  char *namedLayer = NULL;
+  long namedLayer_len;
+  int status = MS_FAILURE;
+  php_layer_object *php_layer;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s",
+                            &sldurl, &sldurl_len,
+                            &namedLayer, &namedLayer_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    status = layerObj_applySLDURL(php_layer->layer, sldurl, namedLayer);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    RETURN_LONG(status);
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  status = layerObj_applySLDURL(php_layer->layer, sldurl, namedLayer);
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -1525,31 +1656,28 @@ PHP_METHOD(layerObj, applySLDURL)
    Returns an SLD XML string based on all the classes found in the layers.*/
 PHP_METHOD(layerObj, generateSLD)
 {
-    zval *zobj = getThis();
-    char *buffer = NULL;
-    php_layer_object *php_layer;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  char *buffer = NULL;
+  php_layer_object *php_layer;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    buffer = layerObj_generateSLD(php_layer->layer);
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    if (buffer)
-    {
-        RETVAL_STRING(buffer, 1);
-        free(buffer);
-    }
-    else
-    {
-        mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
-        RETURN_STRING("", 1);
-    }
+  buffer = layerObj_generateSLD(php_layer->layer);
+
+  if (buffer) {
+    RETVAL_STRING(buffer, 1);
+    free(buffer);
+  } else {
+    mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
+    RETURN_STRING("", 1);
+  }
 }
 /* }}} */
 
@@ -1558,24 +1686,24 @@ PHP_METHOD(layerObj, generateSLD)
     of layers. Returns MS_SUCCESS or MS_FAILURE. */
 PHP_METHOD(layerObj, moveClassUp)
 {
-    zval *zobj = getThis();
-    long index;
-    int status = MS_FAILURE;
-    php_layer_object *php_layer;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
-                              &index) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  long index;
+  int status = MS_FAILURE;
+  php_layer_object *php_layer;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
+                            &index) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    status = layerObj_moveClassUp(php_layer->layer, index);
-    
-    RETURN_LONG(status);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  status = layerObj_moveClassUp(php_layer->layer, index);
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -1584,24 +1712,24 @@ PHP_METHOD(layerObj, moveClassUp)
    of layers. Returns MS_SUCCESS or MS_FAILURE.*/
 PHP_METHOD(layerObj, moveClassDown)
 {
-    zval *zobj = getThis();
-    long index;
-    int status = MS_FAILURE;
-    php_layer_object *php_layer;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
-                              &index) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  long index;
+  int status = MS_FAILURE;
+  php_layer_object *php_layer;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
+                            &index) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    status = layerObj_moveClassDown(php_layer->layer, index);
-    
-    RETURN_LONG(status);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  status = layerObj_moveClassDown(php_layer->layer, index);
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -1610,31 +1738,30 @@ PHP_METHOD(layerObj, moveClassDown)
    failure.*/
 PHP_METHOD(layerObj, removeClass)
 {
-    zval *zobj = getThis();
-    long index;
-    classObj *class;
-    php_layer_object *php_layer;
-    parent_object parent;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
-                              &index) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  long index;
+  classObj *class;
+  php_layer_object *php_layer;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
+                            &index) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    if ((class = layerObj_removeClass(php_layer->layer, index)) == NULL)
-    {
-        mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
-        RETURN_NULL();
-    }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    /* Return a copy of the class object just removed */
-    MAPSCRIPT_MAKE_PARENT(NULL, NULL);
-    mapscript_create_class(class, parent, return_value TSRMLS_CC);
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  if ((class = layerObj_removeClass(php_layer->layer, index)) == NULL) {
+    mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
+    RETURN_NULL();
+  }
+
+  /* Return a copy of the class object just removed */
+  MAPSCRIPT_MAKE_PARENT(NULL, NULL);
+  mapscript_create_class(class, parent, return_value TSRMLS_CC);
 }
 /* }}} */
 
@@ -1643,31 +1770,30 @@ PHP_METHOD(layerObj, removeClass)
    visible in the map (i.e. turned on, in scale, etc.). */
 PHP_METHOD(layerObj, isVisible)
 {
-    zval *zobj = getThis();
-    int retval = MS_FALSE;
-    php_layer_object *php_layer;
-    php_map_object *php_map;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  int retval = MS_FALSE;
+  php_layer_object *php_layer;
+  php_map_object *php_map;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    if (!php_layer->parent.val)
-    {
-        mapscript_throw_exception("No map object associated with this layer object." TSRMLS_CC);
-        return;
-    }
-    
-    php_map = (php_map_object *) zend_object_store_get_object(php_layer->parent.val TSRMLS_CC);
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    retval = msLayerIsVisible(php_map->map, php_layer->layer);
+  if (!php_layer->parent.val) {
+    mapscript_throw_exception("No map object associated with this layer object." TSRMLS_CC);
+    return;
+  }
 
-    RETURN_LONG(retval);
+  php_map = (php_map_object *) zend_object_store_get_object(php_layer->parent.val TSRMLS_CC);
+
+  retval = msLayerIsVisible(php_map->map, php_layer->layer);
+
+  RETURN_LONG(retval);
 }
 /* }}} */
 
@@ -1675,187 +1801,175 @@ PHP_METHOD(layerObj, isVisible)
    Set layer connectiontype.  Returns MS_SUCCESS/MS_FAILURE. */
 PHP_METHOD(layerObj, setConnectionType)
 {
-    zval *zobj = getThis();
-    long type;
-    char *plugin = "";
-    long plugin_len;
-    int status = MS_FAILURE;
-    php_layer_object *php_layer;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|s",
-                              &type,
-                              &plugin, &plugin_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  long type;
+  char *plugin = "";
+  long plugin_len;
+  int status = MS_FAILURE;
+  php_layer_object *php_layer;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|s",
+                            &type,
+                            &plugin, &plugin_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    if ((status = layerObj_setConnectionType(php_layer->layer, 
-                                             type,
-                                             plugin)) != MS_SUCCESS)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    if (php_layer->layer->connectiontype != MS_GRATICULE || php_layer->layer->layerinfo == NULL)
-    {
-        if (php_layer->grid && Z_TYPE_P(php_layer->grid) == IS_OBJECT) {
-            MAPSCRIPT_DELREF(php_layer->grid);
-            MAKE_STD_ZVAL(php_layer->grid);
-            ZVAL_NULL(php_layer->grid);
-        }
+  if ((status = layerObj_setConnectionType(php_layer->layer,
+                type,
+                plugin)) != MS_SUCCESS) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
+
+  if (php_layer->layer->connectiontype != MS_GRATICULE || php_layer->layer->layerinfo == NULL) {
+    if (php_layer->grid && Z_TYPE_P(php_layer->grid) == IS_OBJECT) {
+      MAPSCRIPT_DELREF(php_layer->grid);
+      MAKE_STD_ZVAL(php_layer->grid);
+      ZVAL_NULL(php_layer->grid);
     }
+  }
 
-    RETURN_LONG(status);
+  RETURN_LONG(status);
 }
 /* }}} */
 
-/* {{{ proto int getGridIntersctionCoordinates() 
+/* {{{ proto int getGridIntersctionCoordinates()
    Not sure if this function is often used, let it as it is. */
 PHP_METHOD(layerObj, getGridIntersectionCoordinates)
 {
-    zval *zobj = getThis();
-    graticuleIntersectionObj *values=NULL;
-    zval *tmp_arr1;
-    int i=0;
-    php_layer_object *php_layer;
-    php_map_object *php_map;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  graticuleIntersectionObj *values=NULL;
+  zval *tmp_arr1;
+  int i=0;
+  php_layer_object *php_layer;
+  php_map_object *php_map;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    if (!php_layer->parent.val)
-    {
-        mapscript_throw_exception("No map object associated with this layer object." TSRMLS_CC);
-        return;
-    }
-    
-    php_map = (php_map_object *) zend_object_store_get_object(php_layer->parent.val TSRMLS_CC);
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    
-    array_init(return_value);
+  if (!php_layer->parent.val) {
+    mapscript_throw_exception("No map object associated with this layer object." TSRMLS_CC);
+    return;
+  }
 
-    if (php_layer->layer->connectiontype != MS_GRATICULE)
-    {
-        mapscript_throw_exception("Layer is not of graticule type" TSRMLS_CC); 
-        return;
-    }
- 
-    values = msGraticuleLayerGetIntersectionPoints(php_map->map, php_layer->layer);
+  php_map = (php_map_object *) zend_object_store_get_object(php_layer->parent.val TSRMLS_CC);
 
-    if (values == NULL)
-        return; /* empty array is returned */
 
-    /*TOP*/
-    add_assoc_double(return_value, "topnumpoints", values->nTop);
+  array_init(return_value);
 
-    MAKE_STD_ZVAL(tmp_arr1);
-    array_init(tmp_arr1);
-    for (i=0; i<values->nTop; i++)
-    {
-        add_next_index_string(tmp_arr1, values->papszTopLabels[i],1);
-    }
-    zend_hash_update(Z_ARRVAL_P(return_value), "toplabels", strlen("toplabels")+1, &tmp_arr1, 
-                     sizeof(tmp_arr1), NULL);
-
-    MAKE_STD_ZVAL(tmp_arr1);
-    array_init(tmp_arr1);
-    for (i=0; i<values->nTop; i++)
-    {
-        add_next_index_double(tmp_arr1, values->pasTop[i].x);
-        add_next_index_double(tmp_arr1, values->pasTop[i].y);
-            
-    }
+  if (php_layer->layer->connectiontype != MS_GRATICULE) {
+    mapscript_throw_exception("Layer is not of graticule type" TSRMLS_CC);
+    return;
+  }
 
-    zend_hash_update(Z_ARRVAL_P(return_value), "toppoints", strlen("toppoints")+1, &tmp_arr1, 
-                     sizeof(tmp_arr1), NULL);
+  values = msGraticuleLayerGetIntersectionPoints(php_map->map, php_layer->layer);
 
-    /*BOTTOM*/
+  if (values == NULL)
+    return; /* empty array is returned */
 
-    add_assoc_double(return_value, "bottomnumpoints", values->nBottom);
+  /*TOP*/
+  add_assoc_double(return_value, "topnumpoints", values->nTop);
 
-    MAKE_STD_ZVAL(tmp_arr1);
-    array_init(tmp_arr1);
-    for (i=0; i<values->nBottom; i++)
-    {
-        add_next_index_string(tmp_arr1, values->papszBottomLabels[i],1);
-    }
-    zend_hash_update(Z_ARRVAL_P(return_value), "bottomlabels", strlen("bottomlabels")+1, &tmp_arr1, 
-                     sizeof(tmp_arr1), NULL);
-
-    MAKE_STD_ZVAL(tmp_arr1);
-    array_init(tmp_arr1);
-    for (i=0; i<values->nBottom; i++)
-    {
-        add_next_index_double(tmp_arr1, values->pasBottom[i].x);
-        add_next_index_double(tmp_arr1, values->pasBottom[i].y);
-            
-    }
+  MAKE_STD_ZVAL(tmp_arr1);
+  array_init(tmp_arr1);
+  for (i=0; i<values->nTop; i++) {
+    add_next_index_string(tmp_arr1, values->papszTopLabels[i],1);
+  }
+  zend_hash_update(Z_ARRVAL_P(return_value), "toplabels", strlen("toplabels")+1, &tmp_arr1,
+                   sizeof(tmp_arr1), NULL);
 
-    zend_hash_update(Z_ARRVAL_P(return_value), "bottompoints", strlen("bottompoints")+1, &tmp_arr1, 
-                     sizeof(tmp_arr1), NULL);
+  MAKE_STD_ZVAL(tmp_arr1);
+  array_init(tmp_arr1);
+  for (i=0; i<values->nTop; i++) {
+    add_next_index_double(tmp_arr1, values->pasTop[i].x);
+    add_next_index_double(tmp_arr1, values->pasTop[i].y);
 
+  }
 
-    /*LEFT*/
-    add_assoc_double(return_value, "leftnumpoints", values->nLeft);
+  zend_hash_update(Z_ARRVAL_P(return_value), "toppoints", strlen("toppoints")+1, &tmp_arr1,
+                   sizeof(tmp_arr1), NULL);
 
-    MAKE_STD_ZVAL(tmp_arr1);
-    array_init(tmp_arr1);
-    for (i=0; i<values->nLeft; i++)
-    {
-        add_next_index_string(tmp_arr1, values->papszLeftLabels[i],1);
-    }
-    zend_hash_update(Z_ARRVAL_P(return_value), "leftlabels", strlen("leftlabels")+1, &tmp_arr1, 
-                     sizeof(tmp_arr1), NULL);
-
-    MAKE_STD_ZVAL(tmp_arr1);
-    array_init(tmp_arr1);
-    for (i=0; i<values->nLeft; i++)
-    {
-        add_next_index_double(tmp_arr1, values->pasLeft[i].x);
-        add_next_index_double(tmp_arr1, values->pasLeft[i].y);
-            
-    }
+  /*BOTTOM*/
 
-    zend_hash_update(Z_ARRVAL_P(return_value), "leftpoints", strlen("leftpoints")+1, &tmp_arr1, 
-                     sizeof(tmp_arr1), NULL);
+  add_assoc_double(return_value, "bottomnumpoints", values->nBottom);
 
+  MAKE_STD_ZVAL(tmp_arr1);
+  array_init(tmp_arr1);
+  for (i=0; i<values->nBottom; i++) {
+    add_next_index_string(tmp_arr1, values->papszBottomLabels[i],1);
+  }
+  zend_hash_update(Z_ARRVAL_P(return_value), "bottomlabels", strlen("bottomlabels")+1, &tmp_arr1,
+                   sizeof(tmp_arr1), NULL);
 
-    /*RIGHT*/
-    add_assoc_double(return_value, "rightnumpoints", values->nRight);
+  MAKE_STD_ZVAL(tmp_arr1);
+  array_init(tmp_arr1);
+  for (i=0; i<values->nBottom; i++) {
+    add_next_index_double(tmp_arr1, values->pasBottom[i].x);
+    add_next_index_double(tmp_arr1, values->pasBottom[i].y);
 
-    MAKE_STD_ZVAL(tmp_arr1);
-    array_init(tmp_arr1);
-    for (i=0; i<values->nRight; i++)
-    {
-        add_next_index_string(tmp_arr1, values->papszRightLabels[i],1);
-    }
-    zend_hash_update(Z_ARRVAL_P(return_value), "rightlabels", strlen("rightlabels")+1, &tmp_arr1, 
-                     sizeof(tmp_arr1), NULL);
-
-    MAKE_STD_ZVAL(tmp_arr1);
-    array_init(tmp_arr1);
-    for (i=0; i<values->nRight; i++)
-    {
-        add_next_index_double(tmp_arr1, values->pasRight[i].x);
-        add_next_index_double(tmp_arr1, values->pasRight[i].y);
-            
-    }
+  }
+
+  zend_hash_update(Z_ARRVAL_P(return_value), "bottompoints", strlen("bottompoints")+1, &tmp_arr1,
+                   sizeof(tmp_arr1), NULL);
+
+
+  /*LEFT*/
+  add_assoc_double(return_value, "leftnumpoints", values->nLeft);
+
+  MAKE_STD_ZVAL(tmp_arr1);
+  array_init(tmp_arr1);
+  for (i=0; i<values->nLeft; i++) {
+    add_next_index_string(tmp_arr1, values->papszLeftLabels[i],1);
+  }
+  zend_hash_update(Z_ARRVAL_P(return_value), "leftlabels", strlen("leftlabels")+1, &tmp_arr1,
+                   sizeof(tmp_arr1), NULL);
+
+  MAKE_STD_ZVAL(tmp_arr1);
+  array_init(tmp_arr1);
+  for (i=0; i<values->nLeft; i++) {
+    add_next_index_double(tmp_arr1, values->pasLeft[i].x);
+    add_next_index_double(tmp_arr1, values->pasLeft[i].y);
+
+  }
 
-    zend_hash_update(Z_ARRVAL_P(return_value), "rightpoints", strlen("rightpoints")+1, &tmp_arr1, 
-                     sizeof(tmp_arr1), NULL);
-        
-    msGraticuleLayerFreeIntersectionPoints(values);
+  zend_hash_update(Z_ARRVAL_P(return_value), "leftpoints", strlen("leftpoints")+1, &tmp_arr1,
+                   sizeof(tmp_arr1), NULL);
+
+
+  /*RIGHT*/
+  add_assoc_double(return_value, "rightnumpoints", values->nRight);
+
+  MAKE_STD_ZVAL(tmp_arr1);
+  array_init(tmp_arr1);
+  for (i=0; i<values->nRight; i++) {
+    add_next_index_string(tmp_arr1, values->papszRightLabels[i],1);
+  }
+  zend_hash_update(Z_ARRVAL_P(return_value), "rightlabels", strlen("rightlabels")+1, &tmp_arr1,
+                   sizeof(tmp_arr1), NULL);
+
+  MAKE_STD_ZVAL(tmp_arr1);
+  array_init(tmp_arr1);
+  for (i=0; i<values->nRight; i++) {
+    add_next_index_double(tmp_arr1, values->pasRight[i].x);
+    add_next_index_double(tmp_arr1, values->pasRight[i].y);
+
+  }
+
+  zend_hash_update(Z_ARRVAL_P(return_value), "rightpoints", strlen("rightpoints")+1, &tmp_arr1,
+                   sizeof(tmp_arr1), NULL);
+
+  msGraticuleLayerFreeIntersectionPoints(values);
 }
 /* }}} */
 
@@ -1863,44 +1977,42 @@ PHP_METHOD(layerObj, getGridIntersectionCoordinates)
    Retrieve shapeObj from a resultset by index. */
 PHP_METHOD(layerObj, getShape)
 {
-    zval *zobj = getThis();
-    zval *zresult;
-    shapeObj *shape = NULL;
-    php_result_object *php_result;
-    php_layer_object *php_layer;
-    parent_object parent;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
-                              &zresult, mapscript_ce_result) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  zval *zresult;
+  shapeObj *shape = NULL;
+  php_result_object *php_result;
+  php_layer_object *php_layer;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
+                            &zresult, mapscript_ce_result) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_result = (php_result_object *) zend_object_store_get_object(zresult TSRMLS_CC);
-
-    /* Create a new shapeObj to hold the result 
-     * Note that the type used to create the shape (MS_NULL) does not matter
-     * at this point since it will be set by SHPReadShape().
-     */
-    if ((shape = shapeObj_new(MS_SHAPE_NULL)) == NULL)
-    {
-        mapscript_throw_mapserver_exception("Failed creating new shape (out of memory?)" TSRMLS_CC);
-        return;
-    }
-
-    if (msLayerGetShape(php_layer->layer, shape, php_result->result) != MS_SUCCESS)
-    {
-        shapeObj_destroy(shape);
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
-
-    /* Return valid object */
-    MAPSCRIPT_MAKE_PARENT(NULL, NULL);
-    mapscript_create_shape(shape, parent, php_layer, return_value TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_result = (php_result_object *) zend_object_store_get_object(zresult TSRMLS_CC);
+
+  /* Create a new shapeObj to hold the result
+   * Note that the type used to create the shape (MS_NULL) does not matter
+   * at this point since it will be set by SHPReadShape().
+   */
+  if ((shape = shapeObj_new(MS_SHAPE_NULL)) == NULL) {
+    mapscript_throw_mapserver_exception("Failed creating new shape (out of memory?)" TSRMLS_CC);
+    return;
+  }
+
+  if (msLayerGetShape(php_layer->layer, shape, php_result->result) != MS_SUCCESS) {
+    shapeObj_destroy(shape);
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
+
+  /* Return valid object */
+  MAPSCRIPT_MAKE_PARENT(NULL, NULL);
+  mapscript_create_shape(shape, parent, php_layer, return_value TSRMLS_CC);
 }
 /* }}} */
 
@@ -1909,155 +2021,188 @@ PHP_METHOD(layerObj, getShape)
    Free the object */
 PHP_METHOD(layerObj, free)
 {
-    zval *zobj = getThis();
-    php_layer_object *php_layer;
+  zval *zobj = getThis();
+  php_layer_object *php_layer;
 
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-
-    MAPSCRIPT_DELREF(php_layer->offsite);
-    if (php_layer->grid && Z_TYPE_P(php_layer->grid) == IS_OBJECT)
-        MAPSCRIPT_DELREF(php_layer->grid);
-    MAPSCRIPT_DELREF(php_layer->metadata);
-    MAPSCRIPT_DELREF(php_layer->bindvals);
-    MAPSCRIPT_DELREF(php_layer->cluster);
-    MAPSCRIPT_DELREF(php_layer->projection);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_layer = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  MAPSCRIPT_DELREF(php_layer->offsite);
+  if (php_layer->grid && Z_TYPE_P(php_layer->grid) == IS_OBJECT)
+    MAPSCRIPT_DELREF(php_layer->grid);
+  MAPSCRIPT_DELREF(php_layer->metadata);
+  MAPSCRIPT_DELREF(php_layer->bindvals);
+  MAPSCRIPT_DELREF(php_layer->cluster);
+  MAPSCRIPT_DELREF(php_layer->projection);
 }
 /* }}} */
 
 zend_function_entry layer_functions[] = {
-    PHP_ME(layerObj, __construct, layer___construct_args, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
-    PHP_ME(layerObj, __get, layer___get_args, ZEND_ACC_PUBLIC)
-    PHP_ME(layerObj, __set, layer___set_args, ZEND_ACC_PUBLIC)
-    PHP_MALIAS(layerObj, set, __set, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(layerObj, draw, layer_draw_args, ZEND_ACC_PUBLIC)
-    PHP_ME(layerObj, drawQuery, layer_drawQuery_args, ZEND_ACC_PUBLIC)
-    PHP_ME(layerObj, updateFromString, layer_updateFromString_args, ZEND_ACC_PUBLIC)
-    PHP_ME(layerObj, getClass, layer_getClass_args, ZEND_ACC_PUBLIC)
-    PHP_ME(layerObj, getClassIndex, layer_getClassIndex_args, ZEND_ACC_PUBLIC)
-    PHP_ME(layerObj, queryByPoint, layer_queryByPoint_args, ZEND_ACC_PUBLIC)
-    PHP_ME(layerObj, queryByRect, layer_queryByRect_args, ZEND_ACC_PUBLIC)
-    PHP_ME(layerObj, queryByShape, layer_queryByShape_args, ZEND_ACC_PUBLIC)
-    PHP_ME(layerObj, queryByFeatures, layer_queryByFeatures_args, ZEND_ACC_PUBLIC)
-    PHP_ME(layerObj, queryByAttributes, layer_queryByAttributes_args, ZEND_ACC_PUBLIC)
-    PHP_ME(layerObj, setFilter, layer_setFilter_args, ZEND_ACC_PUBLIC)
-    PHP_ME(layerObj, getFilterString, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(layerObj, setProjection, layer_setProjection_args, ZEND_ACC_PUBLIC)
-    PHP_ME(layerObj, getProjection, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(layerObj, setWKTProjection, layer_setWKTProjection_args, ZEND_ACC_PUBLIC)
-    PHP_ME(layerObj, getNumResults, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(layerObj, getResultsBounds, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(layerObj, getResult, layer_getResult_args, ZEND_ACC_PUBLIC)
-    PHP_ME(layerObj, open, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(layerObj, whichShapes, layer_whichShapes_args, ZEND_ACC_PUBLIC)
-    PHP_ME(layerObj, nextShape, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(layerObj, close, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(layerObj, getExtent, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(layerObj, addFeature, layer_addFeature_args, ZEND_ACC_PUBLIC)
-    PHP_ME(layerObj, getMetaData, layer_getMetaData_args, ZEND_ACC_PUBLIC)
-    PHP_ME(layerObj, setMetaData, layer_setMetaData_args, ZEND_ACC_PUBLIC)
-    PHP_ME(layerObj, removeMetaData, layer_removeMetaData_args, ZEND_ACC_PUBLIC)
-    PHP_ME(layerObj, getWMSFeatureInfoURL, layer_getWMSFeatureInfoURL_args, ZEND_ACC_PUBLIC)
-    PHP_ME(layerObj, getItems, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(layerObj, setProcessing, layer_setProcessing_args, ZEND_ACC_PUBLIC)
-    PHP_ME(layerObj, getProcessing, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(layerObj, clearProcessing, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(layerObj, executeWFSGetFeature, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(layerObj, applySLD, layer_applySLD_args, ZEND_ACC_PUBLIC)
-    PHP_ME(layerObj, applySLDURL, layer_applySLDURL_args, ZEND_ACC_PUBLIC)
-    PHP_ME(layerObj, generateSLD, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(layerObj, moveClassUp, layer_moveClassUp_args, ZEND_ACC_PUBLIC)
-    PHP_ME(layerObj, moveClassDown, layer_moveClassDown_args, ZEND_ACC_PUBLIC)
-    PHP_ME(layerObj, removeClass, layer_removeClass_args, ZEND_ACC_PUBLIC)
-    PHP_ME(layerObj, isVisible, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(layerObj, setConnectionType, layer_setConnectionType_args, ZEND_ACC_PUBLIC)
-    PHP_ME(layerObj, getGridIntersectionCoordinates, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(layerObj, getShape, layer_getShape_args, ZEND_ACC_PUBLIC)
-    PHP_ME(layerObj, free, NULL, ZEND_ACC_PUBLIC)
-    {NULL, NULL, NULL}
+  PHP_ME(layerObj, __construct, layer___construct_args, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
+  PHP_ME(layerObj, __get, layer___get_args, ZEND_ACC_PUBLIC)
+  PHP_ME(layerObj, __set, layer___set_args, ZEND_ACC_PUBLIC)
+  PHP_MALIAS(layerObj, set, __set, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(layerObj, draw, layer_draw_args, ZEND_ACC_PUBLIC)
+  PHP_ME(layerObj, drawQuery, layer_drawQuery_args, ZEND_ACC_PUBLIC)
+  PHP_ME(layerObj, updateFromString, layer_updateFromString_args, ZEND_ACC_PUBLIC)
+  PHP_ME(layerObj, getClass, layer_getClass_args, ZEND_ACC_PUBLIC)
+  PHP_ME(layerObj, getClassIndex, layer_getClassIndex_args, ZEND_ACC_PUBLIC)
+  PHP_ME(layerObj, queryByPoint, layer_queryByPoint_args, ZEND_ACC_PUBLIC)
+  PHP_ME(layerObj, queryByRect, layer_queryByRect_args, ZEND_ACC_PUBLIC)
+  PHP_ME(layerObj, queryByShape, layer_queryByShape_args, ZEND_ACC_PUBLIC)
+  PHP_ME(layerObj, queryByFeatures, layer_queryByFeatures_args, ZEND_ACC_PUBLIC)
+  PHP_ME(layerObj, queryByAttributes, layer_queryByAttributes_args, ZEND_ACC_PUBLIC)
+  PHP_ME(layerObj, queryByFilter, layer_queryByFilter_args, ZEND_ACC_PUBLIC)
+  PHP_ME(layerObj, queryByIndex, layer_queryByIndex_args, ZEND_ACC_PUBLIC)
+  PHP_ME(layerObj, setFilter, layer_setFilter_args, ZEND_ACC_PUBLIC)
+  PHP_ME(layerObj, getFilterString, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(layerObj, setProjection, layer_setProjection_args, ZEND_ACC_PUBLIC)
+  PHP_ME(layerObj, getProjection, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(layerObj, setWKTProjection, layer_setWKTProjection_args, ZEND_ACC_PUBLIC)
+  PHP_ME(layerObj, getNumResults, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(layerObj, getResultsBounds, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(layerObj, getResult, layer_getResult_args, ZEND_ACC_PUBLIC)
+  PHP_ME(layerObj, open, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(layerObj, whichShapes, layer_whichShapes_args, ZEND_ACC_PUBLIC)
+  PHP_ME(layerObj, nextShape, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(layerObj, close, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(layerObj, getExtent, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(layerObj, setExtent, layer_setExtent_args, ZEND_ACC_PUBLIC)
+  PHP_ME(layerObj, addFeature, layer_addFeature_args, ZEND_ACC_PUBLIC)
+  PHP_ME(layerObj, getMetaData, layer_getMetaData_args, ZEND_ACC_PUBLIC)
+  PHP_ME(layerObj, setMetaData, layer_setMetaData_args, ZEND_ACC_PUBLIC)
+  PHP_ME(layerObj, removeMetaData, layer_removeMetaData_args, ZEND_ACC_PUBLIC)
+  PHP_ME(layerObj, getWMSFeatureInfoURL, layer_getWMSFeatureInfoURL_args, ZEND_ACC_PUBLIC)
+  PHP_ME(layerObj, getItems, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(layerObj, setProcessing, layer_setProcessing_args, ZEND_ACC_PUBLIC)
+  PHP_ME(layerObj, setProcessingKey, layer_setProcessingKey_args, ZEND_ACC_PUBLIC)
+  PHP_ME(layerObj, getProcessing, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(layerObj, clearProcessing, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(layerObj, executeWFSGetFeature, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(layerObj, applySLD, layer_applySLD_args, ZEND_ACC_PUBLIC)
+  PHP_ME(layerObj, applySLDURL, layer_applySLDURL_args, ZEND_ACC_PUBLIC)
+  PHP_ME(layerObj, generateSLD, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(layerObj, moveClassUp, layer_moveClassUp_args, ZEND_ACC_PUBLIC)
+  PHP_ME(layerObj, moveClassDown, layer_moveClassDown_args, ZEND_ACC_PUBLIC)
+  PHP_ME(layerObj, removeClass, layer_removeClass_args, ZEND_ACC_PUBLIC)
+  PHP_ME(layerObj, isVisible, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(layerObj, setConnectionType, layer_setConnectionType_args, ZEND_ACC_PUBLIC)
+  PHP_ME(layerObj, getGridIntersectionCoordinates, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(layerObj, getShape, layer_getShape_args, ZEND_ACC_PUBLIC)
+  PHP_ME(layerObj, free, NULL, ZEND_ACC_PUBLIC) {
+    NULL, NULL, NULL
+  }
 };
 
 
 void mapscript_create_layer(layerObj *layer, parent_object parent, zval *return_value TSRMLS_DC)
 {
-    php_layer_object * php_layer;
-    object_init_ex(return_value, mapscript_ce_layer); 
-    php_layer = (php_layer_object *)zend_object_store_get_object(return_value TSRMLS_CC);
-    php_layer->layer = layer;
-
-    if (layer->connectiontype != MS_GRATICULE || layer->layerinfo == NULL)
-    {
-        MAKE_STD_ZVAL(php_layer->grid);
-        ZVAL_NULL(php_layer->grid);
-    }
+  php_layer_object * php_layer;
+  object_init_ex(return_value, mapscript_ce_layer);
+  php_layer = (php_layer_object *)zend_object_store_get_object(return_value TSRMLS_CC);
+  php_layer->layer = layer;
 
-    if (parent.val)
-        php_layer->is_ref = 1;
+  if (layer->connectiontype != MS_GRATICULE || layer->layerinfo == NULL) {
+    MAKE_STD_ZVAL(php_layer->grid);
+    ZVAL_NULL(php_layer->grid);
+  }
 
-    php_layer->parent = parent;
-    MAPSCRIPT_ADDREF(parent.val);
+  if (parent.val)
+    php_layer->is_ref = 1;
+
+  php_layer->parent = parent;
+  MAPSCRIPT_ADDREF(parent.val);
 }
 
 static void mapscript_layer_object_destroy(void *object TSRMLS_DC)
 {
-    php_layer_object *php_layer = (php_layer_object *)object;
+  php_layer_object *php_layer = (php_layer_object *)object;
+
+  MAPSCRIPT_FREE_OBJECT(php_layer);
+
+  MAPSCRIPT_FREE_PARENT(php_layer->parent);
+  MAPSCRIPT_DELREF(php_layer->offsite);
+  if (php_layer->grid && Z_TYPE_P(php_layer->grid) == IS_OBJECT)
+    MAPSCRIPT_DELREF(php_layer->grid);
+  MAPSCRIPT_DELREF(php_layer->metadata);
+  MAPSCRIPT_DELREF(php_layer->bindvals);
+  MAPSCRIPT_DELREF(php_layer->cluster);
+  MAPSCRIPT_DELREF(php_layer->projection);
+  MAPSCRIPT_DELREF(php_layer->extent);
+
+  if (php_layer->layer && !php_layer->is_ref) {
+    layerObj_destroy(php_layer->layer);
+  }
+  efree(object);
+}
+
+static zend_object_value mapscript_layer_object_new_ex(zend_class_entry *ce, php_layer_object **ptr TSRMLS_DC)
+{
+  zend_object_value retval;
+  php_layer_object *php_layer;
 
-    MAPSCRIPT_FREE_OBJECT(php_layer);
+  MAPSCRIPT_ALLOC_OBJECT(php_layer, php_layer_object);
 
-    MAPSCRIPT_FREE_PARENT(php_layer->parent);
-    MAPSCRIPT_DELREF(php_layer->offsite);
-    if (php_layer->grid && Z_TYPE_P(php_layer->grid) == IS_OBJECT)
-        MAPSCRIPT_DELREF(php_layer->grid);
-    MAPSCRIPT_DELREF(php_layer->metadata);
-    MAPSCRIPT_DELREF(php_layer->bindvals);
-    MAPSCRIPT_DELREF(php_layer->cluster);
-    MAPSCRIPT_DELREF(php_layer->projection);
+  retval = mapscript_object_new_ex(&php_layer->std, ce,
+                                   &mapscript_layer_object_destroy,
+                                   &mapscript_layer_object_handlers TSRMLS_CC);
 
-    if (php_layer->layer && !php_layer->is_ref) {
-        layerObj_destroy(php_layer->layer);
-    }
-    efree(object);
+  if (ptr)
+    *ptr = php_layer;
+
+  php_layer->is_ref = 0;
+  MAPSCRIPT_INIT_PARENT(php_layer->parent);
+  php_layer->offsite = NULL;
+  php_layer->grid = NULL;
+  php_layer->metadata = NULL;
+  php_layer->bindvals = NULL;
+  php_layer->cluster = NULL;
+  php_layer->projection = NULL;
+  php_layer->extent = NULL;
+
+  return retval;
 }
 
 static zend_object_value mapscript_layer_object_new(zend_class_entry *ce TSRMLS_DC)
 {
-    zend_object_value retval;
-    php_layer_object *php_layer;
+  return mapscript_layer_object_new_ex(ce, NULL TSRMLS_CC);
+}
 
-    MAPSCRIPT_ALLOC_OBJECT(php_layer, php_layer_object);
+static zend_object_value mapscript_layer_object_clone(zval *zobj TSRMLS_DC)
+{
+  php_layer_object *php_layer_old, *php_layer_new;
+  zend_object_value new_ov;
+
+  php_layer_old = (php_layer_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    retval = mapscript_object_new(&php_layer->std, ce,
-                                  &mapscript_layer_object_destroy TSRMLS_CC);
+  new_ov = mapscript_layer_object_new_ex(mapscript_ce_layer, &php_layer_new TSRMLS_CC);
+  zend_objects_clone_members(&php_layer_new->std, new_ov, &php_layer_old->std, Z_OBJ_HANDLE_P(zobj) TSRMLS_CC);
 
-    php_layer->is_ref = 0;
-    MAPSCRIPT_INIT_PARENT(php_layer->parent);
-    php_layer->offsite = NULL;
-    php_layer->grid = NULL;
-    php_layer->metadata = NULL;
-    php_layer->bindvals = NULL;
-    php_layer->cluster = NULL;
-    php_layer->projection = NULL;
+  php_layer_new->layer = layerObj_clone(php_layer_old->layer);
 
-    return retval;
+  return new_ov;
 }
 
 PHP_MINIT_FUNCTION(layer)
 {
-    zend_class_entry ce;
+  zend_class_entry ce;
+
+  memcpy(&mapscript_layer_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
+  mapscript_layer_object_handlers.clone_obj = mapscript_layer_object_clone;
+
+  MAPSCRIPT_REGISTER_CLASS("layerObj",
+                           layer_functions,
+                           mapscript_ce_layer,
+                           mapscript_layer_object_new);
 
-    MAPSCRIPT_REGISTER_CLASS("layerObj", 
-                             layer_functions,
-                             mapscript_ce_layer,
-                             mapscript_layer_object_new);
+  mapscript_ce_layer->ce_flags |= ZEND_ACC_FINAL_CLASS;
 
-    mapscript_ce_layer->ce_flags |= ZEND_ACC_FINAL_CLASS; 
-    
-    return SUCCESS;
+  return SUCCESS;
 }
 
diff --git a/mapscript/php/legend.c b/mapscript/php/legend.c
index a0f7a08..a03b55c 100644
--- a/mapscript/php/legend.c
+++ b/mapscript/php/legend.c
@@ -2,7 +2,7 @@
  * $Id: php_mapscript.c 9765 2010-01-28 15:32:10Z aboudreault $
  *
  * Project:  MapServer
- * Purpose:  PHP/MapScript extension for MapServer.  External interface 
+ * Purpose:  PHP/MapScript extension for MapServer.  External interface
  *           functions
  * Author:   Daniel Morissette, DM Solutions Group (dmorissette at dmsolutions.ca)
  *           Alan Boudreault, Mapgears
@@ -16,16 +16,16 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
+ *
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  * DEALINGS IN THE SOFTWARE.
  **********************************************************************/
 
@@ -34,131 +34,126 @@
 zend_class_entry *mapscript_ce_legend;
 
 ZEND_BEGIN_ARG_INFO_EX(legend___get_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, property)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(legend___set_args, 0, 0, 2)
-  ZEND_ARG_INFO(0, property)
-  ZEND_ARG_INFO(0, value)
+ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, value)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(legend_updateFromString_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, snippet)
+ZEND_ARG_INFO(0, snippet)
 ZEND_END_ARG_INFO()
 
 /* {{{ proto legend __construct()
    legendObj CANNOT be instanciated, this will throw an exception on use */
 PHP_METHOD(legendObj, __construct)
 {
-    mapscript_throw_exception("legendObj cannot be constructed" TSRMLS_CC);
+  mapscript_throw_exception("legendObj cannot be constructed" TSRMLS_CC);
 }
 /* }}} */
 
 PHP_METHOD(legendObj, __get)
 {
-    char *property;
-    long property_len;
-    zval *zobj = getThis();
-    php_legend_object *php_legend;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &property, &property_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *zobj = getThis();
+  php_legend_object *php_legend;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &property, &property_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_legend = (php_legend_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_legend = (php_legend_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    IF_GET_LONG("height", php_legend->legend->height)
-    else IF_GET_LONG("width", php_legend->legend->width)
+  IF_GET_LONG("height", php_legend->legend->height)
+  else IF_GET_LONG("width", php_legend->legend->width)
     else IF_GET_LONG("keysizex", php_legend->legend->keysizex)
-    else IF_GET_LONG("keysizey", php_legend->legend->keysizey)
-    else IF_GET_LONG("keyspacingx", php_legend->legend->keyspacingx)
-    else IF_GET_LONG("keyspacingy", php_legend->legend->keyspacingy)
-    else IF_GET_LONG("status", php_legend->legend->status)
-    else IF_GET_LONG("position", php_legend->legend->position)
-    else IF_GET_LONG("postlabelcache", php_legend->legend->postlabelcache)
-    else IF_GET_STRING("template", php_legend->legend->template)
-    else IF_GET_OBJECT("outlinecolor", mapscript_ce_color, php_legend->outlinecolor, &php_legend->legend->outlinecolor)
-    else IF_GET_OBJECT("label", mapscript_ce_label, php_legend->label, &php_legend->legend->label)
-    else IF_GET_OBJECT("imagecolor", mapscript_ce_color, php_legend->imagecolor, &php_legend->legend->imagecolor)
-    else 
-    {
-        mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }
+      else IF_GET_LONG("keysizey", php_legend->legend->keysizey)
+        else IF_GET_LONG("keyspacingx", php_legend->legend->keyspacingx)
+          else IF_GET_LONG("keyspacingy", php_legend->legend->keyspacingy)
+            else IF_GET_LONG("status", php_legend->legend->status)
+              else IF_GET_LONG("position", php_legend->legend->position)
+                else IF_GET_LONG("postlabelcache", php_legend->legend->postlabelcache)
+                  else IF_GET_STRING("template", php_legend->legend->template)
+                    else IF_GET_OBJECT("outlinecolor", mapscript_ce_color, php_legend->outlinecolor, &php_legend->legend->outlinecolor)
+                      else IF_GET_OBJECT("label", mapscript_ce_label, php_legend->label, &php_legend->legend->label)
+                        else IF_GET_OBJECT("imagecolor", mapscript_ce_color, php_legend->imagecolor, &php_legend->legend->imagecolor)
+                          else {
+                            mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+                          }
 }
 
 PHP_METHOD(legendObj, __set)
 {
-    char *property;
-    long property_len;
-    zval *value;
-    zval *zobj = getThis();
-    php_legend_object *php_legend;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
-                              &property, &property_len, &value) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *value;
+  zval *zobj = getThis();
+  php_legend_object *php_legend;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
+                            &property, &property_len, &value) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_legend = (php_legend_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    IF_SET_LONG("height", php_legend->legend->height, value)
-    else IF_SET_LONG("width", php_legend->legend->width, value)
+  php_legend = (php_legend_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  IF_SET_LONG("height", php_legend->legend->height, value)
+  else IF_SET_LONG("width", php_legend->legend->width, value)
     else IF_SET_LONG("keysizex", php_legend->legend->keysizex, value)
-    else IF_SET_LONG("keysizey", php_legend->legend->keysizey, value)
-    else IF_SET_LONG("keyspacingx", php_legend->legend->keyspacingx, value)
-    else IF_SET_LONG("keyspacingy", php_legend->legend->keyspacingy, value)
-    else IF_SET_LONG("status", php_legend->legend->status, value)
-    else IF_SET_LONG("position", php_legend->legend->position, value)
-    else IF_SET_LONG("postlabelcache", php_legend->legend->postlabelcache, value)
-    else IF_SET_STRING("template", php_legend->legend->template, value)
-    else if ( (STRING_EQUAL("outlinecolor", property)) ||
-              (STRING_EQUAL("imagecolor", property)) ||
-              (STRING_EQUAL("label", property)))
-    {
-        mapscript_throw_exception("Property '%s' is an object and can only be modified through its accessors." TSRMLS_CC, property);
-    }
-    else 
-    {
-        mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }
+      else IF_SET_LONG("keysizey", php_legend->legend->keysizey, value)
+        else IF_SET_LONG("keyspacingx", php_legend->legend->keyspacingx, value)
+          else IF_SET_LONG("keyspacingy", php_legend->legend->keyspacingy, value)
+            else IF_SET_LONG("status", php_legend->legend->status, value)
+              else IF_SET_LONG("position", php_legend->legend->position, value)
+                else IF_SET_LONG("postlabelcache", php_legend->legend->postlabelcache, value)
+                  else IF_SET_STRING("template", php_legend->legend->template, value)
+                    else if ( (STRING_EQUAL("outlinecolor", property)) ||
+                              (STRING_EQUAL("imagecolor", property)) ||
+                              (STRING_EQUAL("label", property))) {
+                      mapscript_throw_exception("Property '%s' is an object and can only be modified through its accessors." TSRMLS_CC, property);
+                    } else {
+                      mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+                    }
 }
 
 /* {{{ proto int legend.updateFromString(string snippet)
    Update a legend from a string snippet.  Returns MS_SUCCESS/MS_FAILURE */
 PHP_METHOD(legendObj, updateFromString)
 {
-    char *snippet;
-    long snippet_len;
-    zval *zobj = getThis();
-    php_legend_object *php_legend;
-    int status = MS_FAILURE;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &snippet, &snippet_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *snippet;
+  long snippet_len;
+  zval *zobj = getThis();
+  php_legend_object *php_legend;
+  int status = MS_FAILURE;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &snippet, &snippet_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_legend = (php_legend_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-
-    status =  legendObj_updateFromString(php_legend->legend, snippet);
-    
-    if (status != MS_SUCCESS)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
-
-    RETURN_LONG(status);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_legend = (php_legend_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  status =  legendObj_updateFromString(php_legend->legend, snippet);
+
+  if (status != MS_SUCCESS) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -166,88 +161,89 @@ PHP_METHOD(legendObj, updateFromString)
    Free the object */
 PHP_METHOD(legendObj, free)
 {
-    zval *zobj = getThis();
-    php_legend_object *php_legend;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  php_legend_object *php_legend;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_legend = (php_legend_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    MAPSCRIPT_DELREF(php_legend->outlinecolor);
-    MAPSCRIPT_DELREF(php_legend->imagecolor);
-    MAPSCRIPT_DELREF(php_legend->label);
+  php_legend = (php_legend_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  MAPSCRIPT_DELREF(php_legend->outlinecolor);
+  MAPSCRIPT_DELREF(php_legend->imagecolor);
+  MAPSCRIPT_DELREF(php_legend->label);
 }
 /* }}} */
 
 zend_function_entry legend_functions[] = {
-    PHP_ME(legendObj, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
-    PHP_ME(legendObj, __get, legend___get_args, ZEND_ACC_PUBLIC)
-    PHP_ME(legendObj, __set, legend___set_args, ZEND_ACC_PUBLIC)
-    PHP_MALIAS(legendObj, set, __set, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(legendObj, updateFromString, legend_updateFromString_args, ZEND_ACC_PUBLIC)
-    {NULL, NULL, NULL}
+  PHP_ME(legendObj, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
+  PHP_ME(legendObj, __get, legend___get_args, ZEND_ACC_PUBLIC)
+  PHP_ME(legendObj, __set, legend___set_args, ZEND_ACC_PUBLIC)
+  PHP_MALIAS(legendObj, set, __set, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(legendObj, updateFromString, legend_updateFromString_args, ZEND_ACC_PUBLIC) {
+    NULL, NULL, NULL
+  }
 };
 
 void mapscript_create_legend(legendObj *legend, parent_object parent, zval *return_value TSRMLS_DC)
 {
-    php_legend_object * php_legend;
-    object_init_ex(return_value, mapscript_ce_legend); 
-    php_legend = (php_legend_object *)zend_object_store_get_object(return_value TSRMLS_CC);
-    php_legend->legend = legend;
+  php_legend_object * php_legend;
+  object_init_ex(return_value, mapscript_ce_legend);
+  php_legend = (php_legend_object *)zend_object_store_get_object(return_value TSRMLS_CC);
+  php_legend->legend = legend;
 
-    php_legend->parent = parent;
-    MAPSCRIPT_ADDREF(parent.val);
+  php_legend->parent = parent;
+  MAPSCRIPT_ADDREF(parent.val);
 }
 
 static void mapscript_legend_object_destroy(void *object TSRMLS_DC)
 {
-    php_legend_object *php_legend = (php_legend_object *)object;
+  php_legend_object *php_legend = (php_legend_object *)object;
+
+  MAPSCRIPT_FREE_OBJECT(php_legend);
 
-    MAPSCRIPT_FREE_OBJECT(php_legend);
+  MAPSCRIPT_FREE_PARENT(php_legend->parent);
+  MAPSCRIPT_DELREF(php_legend->outlinecolor);
+  MAPSCRIPT_DELREF(php_legend->imagecolor);
+  MAPSCRIPT_DELREF(php_legend->label);
 
-    MAPSCRIPT_FREE_PARENT(php_legend->parent);
-    MAPSCRIPT_DELREF(php_legend->outlinecolor);
-    MAPSCRIPT_DELREF(php_legend->imagecolor);
-    MAPSCRIPT_DELREF(php_legend->label);
+  /* We don't need to free the legendObj */
 
-    /* We don't need to free the legendObj */ 
-    
-    efree(object);
+  efree(object);
 }
 
 static zend_object_value mapscript_legend_object_new(zend_class_entry *ce TSRMLS_DC)
 {
-    zend_object_value retval;
-    php_legend_object *php_legend;
+  zend_object_value retval;
+  php_legend_object *php_legend;
 
-    MAPSCRIPT_ALLOC_OBJECT(php_legend, php_legend_object);
+  MAPSCRIPT_ALLOC_OBJECT(php_legend, php_legend_object);
 
-    retval = mapscript_object_new(&php_legend->std, ce,
-                                  &mapscript_legend_object_destroy TSRMLS_CC);
+  retval = mapscript_object_new(&php_legend->std, ce,
+                                &mapscript_legend_object_destroy TSRMLS_CC);
 
-    MAPSCRIPT_INIT_PARENT(php_legend->parent);
-    php_legend->outlinecolor = NULL;
-    php_legend->imagecolor = NULL;
-    php_legend->label = NULL;
+  MAPSCRIPT_INIT_PARENT(php_legend->parent);
+  php_legend->outlinecolor = NULL;
+  php_legend->imagecolor = NULL;
+  php_legend->label = NULL;
 
-    return retval;
+  return retval;
 }
 
 PHP_MINIT_FUNCTION(legend)
 {
-    zend_class_entry ce;
+  zend_class_entry ce;
+
+  MAPSCRIPT_REGISTER_CLASS("legendObj",
+                           legend_functions,
+                           mapscript_ce_legend,
+                           mapscript_legend_object_new);
 
-    MAPSCRIPT_REGISTER_CLASS("legendObj", 
-                             legend_functions,
-                             mapscript_ce_legend,
-                             mapscript_legend_object_new);
+  mapscript_ce_legend->ce_flags |= ZEND_ACC_FINAL_CLASS;
 
-    mapscript_ce_legend->ce_flags |= ZEND_ACC_FINAL_CLASS; 
-    
-    return SUCCESS;
+  return SUCCESS;
 }
diff --git a/mapscript/php/line.c b/mapscript/php/line.c
index 4c286fb..c28df7a 100644
--- a/mapscript/php/line.c
+++ b/mapscript/php/line.c
@@ -2,7 +2,7 @@
  * $Id: php_mapscript.c 9765 2010-01-28 15:32:10Z aboudreault $
  *
  * Project:  MapServer
- * Purpose:  PHP/MapScript extension for MapServer.  External interface 
+ * Purpose:  PHP/MapScript extension for MapServer.  External interface
  *           functions
  * Author:   Daniel Morissette, DM Solutions Group (dmorissette at dmsolutions.ca)
  *           Alan Boudreault, Mapgears
@@ -16,157 +16,158 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
+ *
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  * DEALINGS IN THE SOFTWARE.
  **********************************************************************/
 
 #include "php_mapscript.h"
 
 zend_class_entry *mapscript_ce_line;
+zend_object_handlers mapscript_line_object_handlers;
 
 ZEND_BEGIN_ARG_INFO_EX(line___get_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, property)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(line___set_args, 0, 0, 2)
-  ZEND_ARG_INFO(0, property)
-  ZEND_ARG_INFO(0, value)
+ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, value)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(line_add_args, 0, 0, 1)
-  ZEND_ARG_OBJ_INFO(0, point, pointObj, 0)
+ZEND_ARG_OBJ_INFO(0, point, pointObj, 0)
+ZEND_END_ARG_INFO()
+
+ZEND_BEGIN_ARG_INFO_EX(line_set_args, 0, 0, 2)
+ZEND_ARG_INFO(0, index)
+ZEND_ARG_OBJ_INFO(0, point, pointObj, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(line_addXY_args, 0, 0, 2)
-  ZEND_ARG_INFO(0, x)
-  ZEND_ARG_INFO(0, y)
-  ZEND_ARG_INFO(0, m)
+ZEND_ARG_INFO(0, x)
+ZEND_ARG_INFO(0, y)
+ZEND_ARG_INFO(0, m)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(line_addXYZ_args, 0, 0, 3)
-  ZEND_ARG_INFO(0, x)
-  ZEND_ARG_INFO(0, y)
-  ZEND_ARG_INFO(0, z)
-  ZEND_ARG_INFO(0, m)
+ZEND_ARG_INFO(0, x)
+ZEND_ARG_INFO(0, y)
+ZEND_ARG_INFO(0, z)
+ZEND_ARG_INFO(0, m)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(line_project_args, 0, 0, 2)
-  ZEND_ARG_OBJ_INFO(0, projIn, projectionObj, 0)
-  ZEND_ARG_OBJ_INFO(0, projOut, projectionObj, 0)
+ZEND_ARG_OBJ_INFO(0, projIn, projectionObj, 0)
+ZEND_ARG_OBJ_INFO(0, projOut, projectionObj, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(line_point_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, index)
+ZEND_ARG_INFO(0, index)
 ZEND_END_ARG_INFO()
 
 /* {{{ proto line __construct()
    Create a new lineObj instance. */
 PHP_METHOD(lineObj, __construct)
 {
-    php_line_object *php_line;
+  php_line_object *php_line;
 
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_line = (php_line_object *)zend_object_store_get_object(getThis() TSRMLS_CC);
 
-    php_line = (php_line_object *)zend_object_store_get_object(getThis() TSRMLS_CC);
-    
-    if ((php_line->line = lineObj_new()) == NULL)
-    {
-        mapscript_throw_exception("Unable to construct lineObj." TSRMLS_CC);
-        return;
-    }
+  if ((php_line->line = lineObj_new()) == NULL) {
+    mapscript_throw_exception("Unable to construct lineObj." TSRMLS_CC);
+    return;
+  }
 }
 /* }}} */
 
 PHP_METHOD(lineObj, __get)
 {
-    char *property;
-    long property_len;
-    zval *zobj = getThis();
-    php_line_object *php_line;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &property, &property_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *zobj = getThis();
+  php_line_object *php_line;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &property, &property_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_line = (php_line_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-
-    IF_GET_LONG("numpoints", php_line->line->numpoints) 
-    else 
-    {
-        mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_line = (php_line_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  IF_GET_LONG("numpoints", php_line->line->numpoints)
+  else {
+    mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+  }
 }
 
 PHP_METHOD(lineObj, __set)
 {
-    char *property;
-    long property_len;
-    zval *value;
-    zval *zobj = getThis();
-    php_line_object *php_line;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
-                              &property, &property_len, &value) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *value;
+  zval *zobj = getThis();
+  php_line_object *php_line;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
+                            &property, &property_len, &value) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_line = (php_line_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-
-    if (STRING_EQUAL("numpoints", property))
-    {
-        mapscript_throw_exception("Property '%s' is read-only and cannot be set." TSRMLS_CC, property);
-    }
-    else
-    {
-        mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_line = (php_line_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  if (STRING_EQUAL("numpoints", property)) {
+    mapscript_throw_exception("Property '%s' is read-only and cannot be set." TSRMLS_CC, property);
+  } else {
+    mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+  }
 }
 
 /* {{{ proto int line.add(pointObj point)
    Adds a point to the end of a line */
 PHP_METHOD(lineObj, add)
 {
-    zval *zobj =  getThis();
-    zval *zobj_point;
-    php_line_object *php_line;
-    php_point_object *php_point;
-    int status = MS_FAILURE;
-    
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
-                              &zobj_point, mapscript_ce_point) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj =  getThis();
+  zval *zobj_point;
+  php_line_object *php_line;
+  php_point_object *php_point;
+  int status = MS_FAILURE;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
+                            &zobj_point, mapscript_ce_point) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_line = (php_line_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_point = (php_point_object *) zend_object_store_get_object(zobj_point TSRMLS_CC);
+  php_line = (php_line_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_point = (php_point_object *) zend_object_store_get_object(zobj_point TSRMLS_CC);
 
-    status = lineObj_add(php_line->line, php_point->point);
+  status = lineObj_add(php_line->line, php_point->point);
 
-    RETURN_LONG(status);
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -175,32 +176,32 @@ PHP_METHOD(lineObj, add)
    Adds a point to the end of a line */
 PHP_METHOD(lineObj, addXY)
 {
-    zval *zobj = getThis();
-    pointObj point;
-    double x, y, m = 0;
-    int status = MS_FAILURE;
-    php_line_object *php_line;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "dd|d", &x, &y, &m) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  pointObj point;
+  double x, y, m = 0;
+  int status = MS_FAILURE;
+  php_line_object *php_line;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "dd|d", &x, &y, &m) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_line = (php_line_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    point.x = x;
-    point.y = y;
+  php_line = (php_line_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  point.x = x;
+  point.y = y;
 
 #ifdef USE_LINE_Z_M
-    point.z = 0;
-    point.m = m;
+  point.z = 0;
+  point.m = m;
 #endif
 
-    status = lineObj_add(php_line->line, &point);
-    
-    RETURN_LONG(status);
+  status = lineObj_add(php_line->line, &point);
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -209,33 +210,33 @@ PHP_METHOD(lineObj, addXY)
    Adds a point to the end of a line */
 PHP_METHOD(lineObj, addXYZ)
 {
-    zval *zobj = getThis();
-    pointObj point;
-    double x, y, z, m = 0;
-    int status = MS_FAILURE;
-    php_line_object *php_line;
-    
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ddd|d",
-                              &x, &y, &z, &m) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  pointObj point;
+  double x, y, z, m = 0;
+  int status = MS_FAILURE;
+  php_line_object *php_line;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ddd|d",
+                            &x, &y, &z, &m) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_line = (php_line_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    point.x = x;
-    point.y = y;
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_line = (php_line_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  point.x = x;
+  point.y = y;
 
 #ifdef USE_LINE_Z_M
-    point.z = z;
-    point.m = m;
+  point.z = z;
+  point.m = m;
 #endif
 
-    status = lineObj_add(php_line->line, &point);
-    
-    RETURN_LONG(status);
+  status = lineObj_add(php_line->line, &point);
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -243,32 +244,31 @@ PHP_METHOD(lineObj, addXYZ)
    Project the point. returns MS_SUCCESS/MS_FAILURE */
 PHP_METHOD(lineObj, project)
 {
-    zval *zobj_proj_in, *zobj_proj_out;
-    zval *zobj =  getThis();
-    php_line_object *php_line;
-    php_projection_object *php_proj_in, *php_proj_out;
-    int status = MS_FAILURE;
-    
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "OO",
-                              &zobj_proj_in, mapscript_ce_projection,
-                              &zobj_proj_out, mapscript_ce_projection) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
-PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-
-    php_line = (php_line_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_proj_in = (php_projection_object *) zend_object_store_get_object(zobj_proj_in TSRMLS_CC);
-    php_proj_out = (php_projection_object *) zend_object_store_get_object(zobj_proj_out TSRMLS_CC);
-    
-    status = lineObj_project(php_line->line, php_proj_in->projection, php_proj_out->projection);
-    if (status != MS_SUCCESS)
-    {
-        mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
-    }
-
-    RETURN_LONG(status);
+  zval *zobj_proj_in, *zobj_proj_out;
+  zval *zobj =  getThis();
+  php_line_object *php_line;
+  php_projection_object *php_proj_in, *php_proj_out;
+  int status = MS_FAILURE;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "OO",
+                            &zobj_proj_in, mapscript_ce_projection,
+                            &zobj_proj_out, mapscript_ce_projection) == FAILURE) {
+    PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_line = (php_line_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_proj_in = (php_projection_object *) zend_object_store_get_object(zobj_proj_in TSRMLS_CC);
+  php_proj_out = (php_projection_object *) zend_object_store_get_object(zobj_proj_out TSRMLS_CC);
+
+  status = lineObj_project(php_line->line, php_proj_in->projection, php_proj_out->projection);
+  if (status != MS_SUCCESS) {
+    mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
+  }
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -276,98 +276,163 @@ PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
    Returns point number i.  First point is number 0. */
 PHP_METHOD(lineObj, point)
 {
-    zval *zobj = getThis();
-    php_line_object *php_line;
-    long index;
-    parent_object parent;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &index) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  php_line_object *php_line;
+  long index;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &index) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_line = (php_line_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_line = (php_line_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    if ( (index < 0) || (index >= php_line->line->numpoints))
-    {
-        mapscript_throw_exception("Point '%d' does not exist in this object." TSRMLS_CC, index);
-        return;
-    }
+  if ( (index < 0) || (index >= php_line->line->numpoints)) {
+    mapscript_throw_exception("Point '%d' does not exist in this object." TSRMLS_CC, index);
+    return;
+  }
 
-    MAPSCRIPT_MAKE_PARENT(zobj, NULL);
-    mapscript_create_point(&(php_line->line->point[index]), parent, return_value TSRMLS_CC);
+  MAPSCRIPT_MAKE_PARENT(zobj, NULL);
+  mapscript_create_point(&(php_line->line->point[index]), parent, return_value TSRMLS_CC);
+}
+/* }}} */
+
+/* {{{ proto int line.set(int, index, pointObj point)
+   Set the point values at the specified index */
+PHP_METHOD(lineObj, set)
+{
+  zval *zobj =  getThis();
+  zval *zobj_point;
+  long index;
+  php_line_object *php_line;
+  php_point_object *php_point;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "lO",
+                            &index, &zobj_point, mapscript_ce_point) == FAILURE) {
+    PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_line = (php_line_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  if ( (index < 0) || (index >= php_line->line->numpoints)) {
+    mapscript_throw_exception("Point '%d' does not exist in this object." TSRMLS_CC, index);
+    return;
+  }
+
+  php_point = (php_point_object *) zend_object_store_get_object(zobj_point TSRMLS_CC);
+
+  php_line->line->point[index].x = php_point->point->x;
+  php_line->line->point[index].y = php_point->point->y;
+
+  RETURN_LONG(MS_SUCCESS);
 }
 /* }}} */
 
 zend_function_entry line_functions[] = {
-    PHP_ME(lineObj, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
-    PHP_ME(lineObj, __get, line___get_args, ZEND_ACC_PUBLIC)
-    PHP_ME(lineObj, __set, line___set_args, ZEND_ACC_PUBLIC)
-    PHP_ME(lineObj, add, line_add_args, ZEND_ACC_PUBLIC)
-    PHP_ME(lineObj, addXY, line_addXY_args, ZEND_ACC_PUBLIC)
-    PHP_ME(lineObj, addXYZ, line_addXYZ_args, ZEND_ACC_PUBLIC)
-    PHP_ME(lineObj, project, line_project_args, ZEND_ACC_PUBLIC)
-    PHP_ME(lineObj, point, line_point_args, ZEND_ACC_PUBLIC)
-    {NULL, NULL, NULL}
+  PHP_ME(lineObj, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
+  PHP_ME(lineObj, __get, line___get_args, ZEND_ACC_PUBLIC)
+  PHP_ME(lineObj, __set, line___set_args, ZEND_ACC_PUBLIC)
+  PHP_ME(lineObj, add, line_add_args, ZEND_ACC_PUBLIC)
+  PHP_ME(lineObj, addXY, line_addXY_args, ZEND_ACC_PUBLIC)
+  PHP_ME(lineObj, addXYZ, line_addXYZ_args, ZEND_ACC_PUBLIC)
+  PHP_ME(lineObj, project, line_project_args, ZEND_ACC_PUBLIC)
+  PHP_ME(lineObj, point, line_point_args, ZEND_ACC_PUBLIC)
+  PHP_MALIAS(lineObj, get, point, line_point_args, ZEND_ACC_PUBLIC)
+  PHP_ME(lineObj, set, line_set_args, ZEND_ACC_PUBLIC) {
+    NULL, NULL, NULL
+  }
 };
 
 
 void mapscript_create_line(lineObj *line, parent_object parent, zval *return_value TSRMLS_DC)
 {
-    php_line_object * php_line;
-    object_init_ex(return_value, mapscript_ce_line); 
-    php_line = (php_line_object *)zend_object_store_get_object(return_value TSRMLS_CC);
-    php_line->line = line;
+  php_line_object * php_line;
+  object_init_ex(return_value, mapscript_ce_line);
+  php_line = (php_line_object *)zend_object_store_get_object(return_value TSRMLS_CC);
+  php_line->line = line;
 
-    if (parent.val)
-        php_line->is_ref = 1;
+  if (parent.val)
+    php_line->is_ref = 1;
 
-    php_line->parent = parent;
-    MAPSCRIPT_ADDREF(parent.val);
+  php_line->parent = parent;
+  MAPSCRIPT_ADDREF(parent.val);
 }
 
 static void mapscript_line_object_destroy(void *object TSRMLS_DC)
 {
-    php_line_object *php_line = (php_line_object *)object;
+  php_line_object *php_line = (php_line_object *)object;
+
+  MAPSCRIPT_FREE_OBJECT(php_line);
+
+  MAPSCRIPT_FREE_PARENT(php_line->parent);
+
+  if (php_line->line && !php_line->is_ref) {
+    lineObj_destroy(php_line->line);
+  }
+
+  efree(object);
+}
+
+static zend_object_value mapscript_line_object_new_ex(zend_class_entry *ce, php_line_object **ptr TSRMLS_DC)
+{
+  zend_object_value retval;
+  php_line_object *php_line;
+
+  MAPSCRIPT_ALLOC_OBJECT(php_line, php_line_object);
 
-    MAPSCRIPT_FREE_OBJECT(php_line);
+  retval = mapscript_object_new_ex(&php_line->std, ce,
+                                   &mapscript_line_object_destroy,
+                                   &mapscript_line_object_handlers TSRMLS_CC);
 
-    MAPSCRIPT_FREE_PARENT(php_line->parent);
+  if (ptr)
+    *ptr = php_line;
 
-    if (php_line->line && !php_line->is_ref) {
-        lineObj_destroy(php_line->line);
-    }
-    
-    efree(object);
+  php_line->is_ref = 0;
+  MAPSCRIPT_INIT_PARENT(php_line->parent);
+
+  return retval;
 }
 
 static zend_object_value mapscript_line_object_new(zend_class_entry *ce TSRMLS_DC)
 {
-    zend_object_value retval;
-    php_line_object *php_line;
+  return mapscript_line_object_new_ex(ce, NULL TSRMLS_CC);
+}
 
-    MAPSCRIPT_ALLOC_OBJECT(php_line, php_line_object);
+static zend_object_value mapscript_line_object_clone(zval *zobj TSRMLS_DC)
+{
+  php_line_object *php_line_old, *php_line_new;
+  zend_object_value new_ov;
 
-    retval = mapscript_object_new(&php_line->std, ce,
-                                  &mapscript_line_object_destroy TSRMLS_CC);
-    php_line->is_ref = 0;
-    MAPSCRIPT_INIT_PARENT(php_line->parent);
+  php_line_old = (php_line_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    return retval;
+  new_ov = mapscript_line_object_new_ex(mapscript_ce_line, &php_line_new TSRMLS_CC);
+  zend_objects_clone_members(&php_line_new->std, new_ov, &php_line_old->std, Z_OBJ_HANDLE_P(zobj) TSRMLS_CC);
+
+  php_line_new->line = lineObj_clone(php_line_old->line);
+
+  return new_ov;
 }
 
 PHP_MINIT_FUNCTION(line)
 {
-    zend_class_entry ce;
+  zend_class_entry ce;
+
+  memcpy(&mapscript_line_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
+  mapscript_line_object_handlers.clone_obj = mapscript_line_object_clone;
+
+
+  MAPSCRIPT_REGISTER_CLASS("lineObj",
+                           line_functions,
+                           mapscript_ce_line,
+                           mapscript_line_object_new);
 
-    MAPSCRIPT_REGISTER_CLASS("lineObj", 
-                             line_functions,
-                             mapscript_ce_line,
-                             mapscript_line_object_new);
+  mapscript_ce_line->ce_flags |= ZEND_ACC_FINAL_CLASS;
 
-    mapscript_ce_line->ce_flags |= ZEND_ACC_FINAL_CLASS; 
-    
-    return SUCCESS;
+  return SUCCESS;
 }
diff --git a/mapscript/php/map.c b/mapscript/php/map.c
index 07c8efc..384f491 100644
--- a/mapscript/php/map.c
+++ b/mapscript/php/map.c
@@ -2,7 +2,7 @@
  * $Id: php_mapscript.c 9765 2010-01-28 15:32:10Z aboudreault $
  *
  * Project:  MapServer
- * Purpose:  PHP/MapScript extension for MapServer.  External interface 
+ * Purpose:  PHP/MapScript extension for MapServer.  External interface
  *           functions
  * Author:   Daniel Morissette, DM Solutions Group (dmorissette at dmsolutions.ca)
  *           Alan Boudreault, Mapgears
@@ -16,16 +16,16 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
+ *
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  * DEALINGS IN THE SOFTWARE.
  **********************************************************************/
 
@@ -38,471 +38,490 @@ static int mapscript_map_setProjection(int isWKTProj, php_map_object *php_map,
                                        char *projString, int setUnitsAndExtents TSRMLS_DC);
 
 ZEND_BEGIN_ARG_INFO_EX(map___construct_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, mapFileName)
-  ZEND_ARG_INFO(0, newMapPath)
+ZEND_ARG_INFO(0, mapFileName)
+ZEND_ARG_INFO(0, newMapPath)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map___get_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, property)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map___set_args, 0, 0, 2)
-  ZEND_ARG_INFO(0, property)
-  ZEND_ARG_INFO(0, value)
+ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, value)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_getSymbolByName_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, symbolName)
+ZEND_ARG_INFO(0, symbolName)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_getSymbolObjectById_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, symbolId)
+ZEND_ARG_INFO(0, symbolId)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_embedLegend_args, 0, 0, 1)
-  ZEND_ARG_OBJ_INFO(0, image, imageObj, 0)
+ZEND_ARG_OBJ_INFO(0, image, imageObj, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_embedScaleBar_args, 0, 0, 1)
-  ZEND_ARG_OBJ_INFO(0, image, imageObj, 0)
+ZEND_ARG_OBJ_INFO(0, image, imageObj, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_drawLabelCache_args, 0, 0, 1)
-  ZEND_ARG_OBJ_INFO(0, image, imageObj, 0)
+ZEND_ARG_OBJ_INFO(0, image, imageObj, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_getLayer_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, index)
+ZEND_ARG_INFO(0, index)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_getLayerByName_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, layerName)
+ZEND_ARG_INFO(0, layerName)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_getColorByIndex_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, index)
+ZEND_ARG_INFO(0, index)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_setExtent_args, 0, 0, 4)
-  ZEND_ARG_INFO(0, minx)
-  ZEND_ARG_INFO(0, miny)
-  ZEND_ARG_INFO(0, maxx)
-  ZEND_ARG_INFO(0, maxy)
+ZEND_ARG_INFO(0, minx)
+ZEND_ARG_INFO(0, miny)
+ZEND_ARG_INFO(0, maxx)
+ZEND_ARG_INFO(0, maxy)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_setCenter_args, 0, 0, 1)
-  ZEND_ARG_OBJ_INFO(0, point, pointObj, 0)
+ZEND_ARG_OBJ_INFO(0, point, pointObj, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_offsetExtent_args, 0, 0, 2)
-  ZEND_ARG_INFO(0, x)
-  ZEND_ARG_INFO(0, y)
+ZEND_ARG_INFO(0, x)
+ZEND_ARG_INFO(0, y)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_scaleExtent_args, 0, 0, 3)
-  ZEND_ARG_INFO(0, zoomFactor)
-  ZEND_ARG_INFO(0, minScaleDenom)
-  ZEND_ARG_INFO(0, maxScaleDenom)
+ZEND_ARG_INFO(0, zoomFactor)
+ZEND_ARG_INFO(0, minScaleDenom)
+ZEND_ARG_INFO(0, maxScaleDenom)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_setRotation_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, angle)
+ZEND_ARG_INFO(0, angle)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_setSize_args, 0, 0, 2)
-  ZEND_ARG_INFO(0, width)
-  ZEND_ARG_INFO(0, height)
+ZEND_ARG_INFO(0, width)
+ZEND_ARG_INFO(0, height)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_zoomPoint_args, 0, 0, 5)
-  ZEND_ARG_INFO(0, zoomFactor)
-  ZEND_ARG_OBJ_INFO(0, pixelPosition, pointObj, 0)
-  ZEND_ARG_INFO(0, width)
-  ZEND_ARG_INFO(0, height)
-  ZEND_ARG_OBJ_INFO(0, geoRefExtent, rectObj, 0)
-  ZEND_ARG_OBJ_INFO(0, maxGeoRefExtent, rectObj, 0)
+ZEND_ARG_INFO(0, zoomFactor)
+ZEND_ARG_OBJ_INFO(0, pixelPosition, pointObj, 0)
+ZEND_ARG_INFO(0, width)
+ZEND_ARG_INFO(0, height)
+ZEND_ARG_OBJ_INFO(0, geoRefExtent, rectObj, 0)
+ZEND_ARG_OBJ_INFO(0, maxGeoRefExtent, rectObj, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_zoomRectangle_args, 0, 0, 4)
-  ZEND_ARG_OBJ_INFO(0, pixelExtent, rectObj, 0)
-  ZEND_ARG_INFO(0, width)
-  ZEND_ARG_INFO(0, height)
-  ZEND_ARG_OBJ_INFO(0, geoRefExtent, rectObj, 0)
-  ZEND_ARG_OBJ_INFO(0, maxGeoRefExtent, rectObj, 0)
+ZEND_ARG_OBJ_INFO(0, pixelExtent, rectObj, 0)
+ZEND_ARG_INFO(0, width)
+ZEND_ARG_INFO(0, height)
+ZEND_ARG_OBJ_INFO(0, geoRefExtent, rectObj, 0)
+ZEND_ARG_OBJ_INFO(0, maxGeoRefExtent, rectObj, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_zoomScale_args, 0, 0, 5)
-  ZEND_ARG_INFO(0, scaleDenom)
-  ZEND_ARG_OBJ_INFO(0, pixelPosition, pointObj, 0)
-  ZEND_ARG_INFO(0, width)
-  ZEND_ARG_INFO(0, height)
-  ZEND_ARG_OBJ_INFO(0, geoRefExtent, rectObj, 0)
-  ZEND_ARG_OBJ_INFO(0, maxGeoRefExtent, rectObj, 0)
+ZEND_ARG_INFO(0, scaleDenom)
+ZEND_ARG_OBJ_INFO(0, pixelPosition, pointObj, 0)
+ZEND_ARG_INFO(0, width)
+ZEND_ARG_INFO(0, height)
+ZEND_ARG_OBJ_INFO(0, geoRefExtent, rectObj, 0)
+ZEND_ARG_OBJ_INFO(0, maxGeoRefExtent, rectObj, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_queryByPoint_args, 0, 0, 3)
-  ZEND_ARG_OBJ_INFO(0, point, pointObj, 0)
-  ZEND_ARG_INFO(0, mode)
-  ZEND_ARG_INFO(0, buffer)
+ZEND_ARG_OBJ_INFO(0, point, pointObj, 0)
+ZEND_ARG_INFO(0, mode)
+ZEND_ARG_INFO(0, buffer)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_queryByRect_args, 0, 0, 1)
-  ZEND_ARG_OBJ_INFO(0, rect, rectObj, 0)
+ZEND_ARG_OBJ_INFO(0, rect, rectObj, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_queryByShape_args, 0, 0, 1)
-  ZEND_ARG_OBJ_INFO(0, shape, shapeObj, 0)
+ZEND_ARG_OBJ_INFO(0, shape, shapeObj, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_queryByFeatures_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, slayer)
+ZEND_ARG_INFO(0, slayer)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_queryByIndex_args, 0, 0, 3)
-  ZEND_ARG_INFO(0, layerIndex)
-  ZEND_ARG_INFO(0, tileIndex)
-  ZEND_ARG_INFO(0, shapeIndex)
-  ZEND_ARG_INFO(0, addToQuery)
+ZEND_ARG_INFO(0, layerIndex)
+ZEND_ARG_INFO(0, tileIndex)
+ZEND_ARG_INFO(0, shapeIndex)
+ZEND_ARG_INFO(0, addToQuery)
+ZEND_END_ARG_INFO()
+
+ZEND_BEGIN_ARG_INFO_EX(map_queryByFilter_args, 0, 0, 1)
+ZEND_ARG_INFO(0, string)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_saveQuery_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, filename)
-  ZEND_ARG_INFO(0, results)
+ZEND_ARG_INFO(0, filename)
+ZEND_ARG_INFO(0, results)
+ZEND_END_ARG_INFO()
+
+ZEND_BEGIN_ARG_INFO_EX(map_saveQueryAsGML_args, 0, 0, 1)
+ZEND_ARG_INFO(0, filename)
+ZEND_ARG_INFO(0, namespace)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_loadQuery_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, filename)
+ZEND_ARG_INFO(0, filename)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_freeQuery_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, layerIndex)
+ZEND_ARG_INFO(0, layerIndex)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_save_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, filename)
+ZEND_ARG_INFO(0, filename)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_setProjection_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, projectionParams)
-  ZEND_ARG_INFO(0, setUnitsAndExtents)
+ZEND_ARG_INFO(0, projectionParams)
+ZEND_ARG_INFO(0, setUnitsAndExtents)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_setWKTProjection_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, projectionParams)
-  ZEND_ARG_INFO(0, setUnitsAndExtents)
+ZEND_ARG_INFO(0, projectionParams)
+ZEND_ARG_INFO(0, setUnitsAndExtents)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_getMetaData_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, name)
+ZEND_ARG_INFO(0, name)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_setMetaData_args, 0, 0, 2)
-  ZEND_ARG_INFO(0, name)
-  ZEND_ARG_INFO(0, value)
+ZEND_ARG_INFO(0, name)
+ZEND_ARG_INFO(0, value)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_removeMetaData_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, name)
+ZEND_ARG_INFO(0, name)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_getLayersIndexByGroup_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, groupName)
+ZEND_ARG_INFO(0, groupName)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_moveLayerUp_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, index)
+ZEND_ARG_INFO(0, index)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_moveLayerDown_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, index)
+ZEND_ARG_INFO(0, index)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_setLayersDrawingOrder_args, 0, 0, 1)
-  ZEND_ARG_ARRAY_INFO(0, layerIndexes, 0)
+ZEND_ARG_ARRAY_INFO(0, layerIndexes, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_processTemplate_args, 0, 0, 2)
-  ZEND_ARG_ARRAY_INFO(0, params, 0)
-  ZEND_ARG_INFO(0, generateImages)
+ZEND_ARG_ARRAY_INFO(0, params, 0)
+ZEND_ARG_INFO(0, generateImages)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_processQueryTemplate_args, 0, 0, 1)
-  ZEND_ARG_ARRAY_INFO(0, params, 0)
-  ZEND_ARG_INFO(0, generateImages)
+ZEND_ARG_ARRAY_INFO(0, params, 0)
+ZEND_ARG_INFO(0, generateImages)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_processLegendTemplate_args, 0, 0, 1)
-  ZEND_ARG_ARRAY_INFO(0, params, 0)
+ZEND_ARG_ARRAY_INFO(0, params, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_setSymbolSet_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, filename)
+ZEND_ARG_INFO(0, filename)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_setFontSet_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, filename)
+ZEND_ARG_INFO(0, filename)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_selectOutputFormat_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, type)
+ZEND_ARG_INFO(0, type)
+ZEND_END_ARG_INFO()
+
+ZEND_BEGIN_ARG_INFO_EX(map_appendOutputFormat_args, 0, 0, 1)
+ZEND_ARG_OBJ_INFO(0, outputformat, outputFormatObj, 0)
+ZEND_END_ARG_INFO()
+
+ZEND_BEGIN_ARG_INFO_EX(map_removeOutputFormat_args, 0, 0, 1)
+ZEND_ARG_INFO(0, name)
+ZEND_END_ARG_INFO()
+
+ZEND_BEGIN_ARG_INFO_EX(map_getOutputFormat_args, 0, 0, 1)
+ZEND_ARG_INFO(0, index)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_saveMapContext_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, filename)
+ZEND_ARG_INFO(0, filename)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_loadMapContext_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, filename)
-  ZEND_ARG_INFO(0, uniqueLayerName)
+ZEND_ARG_INFO(0, filename)
+ZEND_ARG_INFO(0, uniqueLayerName)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_applySLD_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, sldxml)
+ZEND_ARG_INFO(0, sldxml)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_applySLDURL_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, sldurl)
+ZEND_ARG_INFO(0, sldurl)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_getConfigOption_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, key)
+ZEND_ARG_INFO(0, key)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_setConfigOption_args, 0, 0, 2)
-  ZEND_ARG_INFO(0, key)
-  ZEND_ARG_INFO(0, value)
+ZEND_ARG_INFO(0, key)
+ZEND_ARG_INFO(0, value)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_loadOwsParameters_args, 0, 0, 1)
-  ZEND_ARG_OBJ_INFO(0, request, owsRequestObj, 0)
-  ZEND_ARG_INFO(0, version)
+ZEND_ARG_OBJ_INFO(0, request, owsRequestObj, 0)
+ZEND_ARG_INFO(0, version)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_owsDispatch_args, 0, 0, 1)
-  ZEND_ARG_OBJ_INFO(0, request, owsRequestObj, 0)
+ZEND_ARG_OBJ_INFO(0, request, owsRequestObj, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_insertLayer_args, 0, 0, 1)
-  ZEND_ARG_OBJ_INFO(0, layer, layerObj, 0)
-  ZEND_ARG_INFO(0, index)
+ZEND_ARG_OBJ_INFO(0, layer, layerObj, 0)
+ZEND_ARG_INFO(0, index)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_removeLayer_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, index)
+ZEND_ARG_INFO(0, index)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(map_getLabel_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, index)
+ZEND_ARG_INFO(0, index)
 ZEND_END_ARG_INFO()
 
-/* {{{ proto void __construct(string mapFileName, newMapPath) 
+/* {{{ proto void __construct(string mapFileName, newMapPath)
    Create a new mapObj instance. */
 PHP_METHOD(mapObj, __construct)
 {
-    zval *zobj = getThis();
-    char *filename;
-    long filename_len;
-    char *path = NULL;
-    long path_len;
-    mapObj *map;
-    php_map_object *php_map;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s",
-                              &filename, &filename_len,
-                              &path, &path_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  char *filename;
+  long filename_len;
+  char *path = NULL;
+  long path_len;
+  mapObj *map;
+  php_map_object *php_map;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s",
+                            &filename, &filename_len,
+                            &path, &path_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_map = (php_map_object *)zend_object_store_get_object(zobj TSRMLS_CC);
+  php_map = (php_map_object *)zend_object_store_get_object(zobj TSRMLS_CC);
 
-    map = mapObj_new(filename, path);
+  map = mapObj_new(filename, path);
 
-    if (map == NULL)
-    {
-        mapscript_throw_mapserver_exception("Failed to open map file %s" TSRMLS_CC,  filename);
-        return;
-    }
+  if (map == NULL) {
+    mapscript_throw_mapserver_exception("Failed to open map file %s" TSRMLS_CC,  filename);
+    return;
+  }
 
-    php_map->map = map;
+  php_map->map = map;
 }
 /* }}} */
 
 PHP_METHOD(mapObj, __get)
 {
-    char *property;
-    long property_len;
-    zval *zobj = getThis();
-    php_map_object *php_map;
+  char *property;
+  long property_len;
+  zval *zobj = getThis();
+  php_map_object *php_map;
 
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &property, &property_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &property, &property_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    IF_GET_LONG("numlayers",  php_map->map->numlayers)
-    else IF_GET_STRING("name", php_map->map->name)
+  IF_GET_LONG("numlayers",  php_map->map->numlayers)
+  else IF_GET_STRING("name", php_map->map->name)
     else IF_GET_STRING("mappath", php_map->map->mappath)
-    else IF_GET_LONG("status",  php_map->map->status)
-    else IF_GET_LONG("debug", php_map->map->debug)
-    else IF_GET_LONG("width", php_map->map->width)
-    else IF_GET_LONG("height", php_map->map->height)
-    else IF_GET_LONG("maxsize", php_map->map->maxsize)
-    else IF_GET_DOUBLE("resolution", php_map->map->resolution)
-    else IF_GET_DOUBLE("defresolution", php_map->map->defresolution)
-    else IF_GET_DOUBLE("cellsize", php_map->map->cellsize)
-    else IF_GET_LONG("units", php_map->map->units)
-    else IF_GET_DOUBLE("scaledenom", php_map->map->scaledenom)
-    else IF_GET_STRING("shapepath", php_map->map->shapepath)
-    else IF_GET_LONG("keysizex", php_map->map->legend.keysizex)
-    else IF_GET_LONG("keysizey", php_map->map->legend.keysizey)
-    else IF_GET_LONG("keyspacingx", php_map->map->legend.keyspacingx)
-    else IF_GET_LONG("keyspacingy", php_map->map->legend.keyspacingy)
-    else IF_GET_STRING("symbolsetfilename", php_map->map->symbolset.filename)
-    else IF_GET_STRING("fontsetfilename", php_map->map->fontset.filename)
-    else IF_GET_OBJECT("outputformat", mapscript_ce_outputformat, php_map->outputformat, php_map->map->outputformat) 
-    else IF_GET_OBJECT("extent", mapscript_ce_rect, php_map->extent, &php_map->map->extent) 
-    else IF_GET_OBJECT("web", mapscript_ce_web, php_map->web, &php_map->map->web) 
-    else IF_GET_OBJECT("reference", mapscript_ce_referencemap, php_map->reference, &php_map->map->reference) 
-    else IF_GET_OBJECT("imagecolor", mapscript_ce_color, php_map->imagecolor, &php_map->map->imagecolor) 
-    else IF_GET_OBJECT("scalebar", mapscript_ce_scalebar, php_map->scalebar, &php_map->map->scalebar) 
-    else IF_GET_OBJECT("legend", mapscript_ce_legend, php_map->legend, &php_map->map->legend) 
-    else IF_GET_OBJECT("querymap", mapscript_ce_querymap, php_map->querymap, &php_map->map->querymap) 
-    else IF_GET_OBJECT("labelcache", mapscript_ce_labelcache, php_map->labelcache, &php_map->map->labelcache) 
-    else IF_GET_OBJECT("projection", mapscript_ce_projection, php_map->projection, &php_map->map->projection) 
-    else IF_GET_OBJECT("metadata", mapscript_ce_hashtable, php_map->metadata, &php_map->map->web.metadata) 
-    else 
-    {
-        mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }
+      else IF_GET_STRING("imagetype", php_map->map->imagetype)
+        else IF_GET_LONG("status",  php_map->map->status)
+          else IF_GET_LONG("debug", php_map->map->debug)
+            else IF_GET_LONG("width", php_map->map->width)
+              else IF_GET_LONG("height", php_map->map->height)
+                else IF_GET_LONG("maxsize", php_map->map->maxsize)
+                  else IF_GET_DOUBLE("resolution", php_map->map->resolution)
+                    else IF_GET_DOUBLE("defresolution", php_map->map->defresolution)
+                      else IF_GET_DOUBLE("cellsize", php_map->map->cellsize)
+                        else IF_GET_LONG("units", php_map->map->units)
+                          else IF_GET_DOUBLE("scaledenom", php_map->map->scaledenom)
+                            else IF_GET_STRING("shapepath", php_map->map->shapepath)
+                              else IF_GET_LONG("keysizex", php_map->map->legend.keysizex)
+                                else IF_GET_LONG("keysizey", php_map->map->legend.keysizey)
+                                  else IF_GET_LONG("keyspacingx", php_map->map->legend.keyspacingx)
+                                    else IF_GET_LONG("keyspacingy", php_map->map->legend.keyspacingy)
+                                      else IF_GET_STRING("symbolsetfilename", php_map->map->symbolset.filename)
+                                        else IF_GET_LONG("numoutputformats", php_map->map->numoutputformats)
+                                          else IF_GET_STRING("fontsetfilename", php_map->map->fontset.filename)
+                                            else IF_GET_OBJECT("outputformat", mapscript_ce_outputformat, php_map->outputformat, php_map->map->outputformat)
+                                              else IF_GET_OBJECT("configoptions", mapscript_ce_hashtable, php_map->configoptions, &php_map->map->configoptions)
+                                                else IF_GET_OBJECT("extent", mapscript_ce_rect, php_map->extent, &php_map->map->extent)
+                                                  else IF_GET_OBJECT("web", mapscript_ce_web, php_map->web, &php_map->map->web)
+                                                    else IF_GET_OBJECT("reference", mapscript_ce_referencemap, php_map->reference, &php_map->map->reference)
+                                                      else IF_GET_OBJECT("imagecolor", mapscript_ce_color, php_map->imagecolor, &php_map->map->imagecolor)
+                                                        else IF_GET_OBJECT("scalebar", mapscript_ce_scalebar, php_map->scalebar, &php_map->map->scalebar)
+                                                          else IF_GET_OBJECT("legend", mapscript_ce_legend, php_map->legend, &php_map->map->legend)
+                                                            else IF_GET_OBJECT("querymap", mapscript_ce_querymap, php_map->querymap, &php_map->map->querymap)
+                                                              else IF_GET_OBJECT("labelcache", mapscript_ce_labelcache, php_map->labelcache, &php_map->map->labelcache)
+                                                                else IF_GET_OBJECT("projection", mapscript_ce_projection, php_map->projection, &php_map->map->projection)
+                                                                  else IF_GET_OBJECT("metadata", mapscript_ce_hashtable, php_map->metadata, &php_map->map->web.metadata)
+                                                                    else {
+                                                                      mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+                                                                    }
 }
 
 PHP_METHOD(mapObj, __set)
 {
-    char *property;
-    long property_len;
-    zval *value;
-    zval *zobj = getThis();
-    php_map_object *php_map;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
-                              &property, &property_len, &value) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *value;
+  zval *zobj = getThis();
+  php_map_object *php_map;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
+                            &property, &property_len, &value) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    IF_SET_STRING("name", php_map->map->name, value)
-    else IF_SET_LONG("status",  php_map->map->status, value)
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  IF_SET_STRING("name", php_map->map->name, value)
+  else IF_SET_LONG("status",  php_map->map->status, value)
     else IF_SET_LONG("debug", php_map->map->debug, value)
-    else IF_SET_LONG("width", php_map->map->width, value)
-    else IF_SET_LONG("height", php_map->map->height, value)
-    else IF_SET_LONG("maxsize", php_map->map->maxsize, value)
-    else IF_SET_DOUBLE("resolution", php_map->map->resolution, value)
-    else IF_SET_DOUBLE("defresolution", php_map->map->defresolution, value)
-    else IF_SET_DOUBLE("cellsize", php_map->map->cellsize, value)
-    else IF_SET_LONG("units", php_map->map->units, value)
-    else IF_SET_DOUBLE("scaledenom", php_map->map->scaledenom, value)
-    else IF_SET_STRING("shapepath", php_map->map->shapepath, value)
-    else IF_SET_LONG("keysizex", php_map->map->legend.keysizex, value)
-    else IF_SET_LONG("keysizey", php_map->map->legend.keysizey, value)
-    else IF_SET_LONG("keyspacingx", php_map->map->legend.keyspacingx, value)
-    else IF_SET_LONG("keyspacingy", php_map->map->legend.keyspacingy, value)
-    else if ( (STRING_EQUAL("outputformat", property)) ||
-              (STRING_EQUAL("extent", property)) ||
-              (STRING_EQUAL("web", property)) ||
-              (STRING_EQUAL("reference", property)) ||
-              (STRING_EQUAL("scalebar", property)) ||
-              (STRING_EQUAL("legend", property)) ||
-              (STRING_EQUAL("querymap", property)) ||
-              (STRING_EQUAL("labelcache", property)) ||
-              (STRING_EQUAL("projection", property)) ||
-              (STRING_EQUAL("metadata", property)) ||
-              (STRING_EQUAL("imagecolor", property)) )
-    {
-        mapscript_throw_exception("Property '%s' is an object and can only be modified through its accessors." TSRMLS_CC, property);
-    }
-    else if ( (STRING_EQUAL("numlayers", property)) ||
-              (STRING_EQUAL("symbolsetfilename", property)) ||
-              (STRING_EQUAL("mappath", property)) ||
-              (STRING_EQUAL("fontsetfilename", property)) )
-    {
-        mapscript_throw_exception("Property '%s' is read-only and cannot be set." TSRMLS_CC, property);
-    }
-    else 
-    {
-        mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }         
+      else IF_SET_LONG("width", php_map->map->width, value)
+        else IF_SET_LONG("height", php_map->map->height, value)
+          else IF_SET_LONG("maxsize", php_map->map->maxsize, value)
+            else IF_SET_DOUBLE("resolution", php_map->map->resolution, value)
+              else IF_SET_DOUBLE("defresolution", php_map->map->defresolution, value)
+                else IF_SET_DOUBLE("cellsize", php_map->map->cellsize, value)
+                  else IF_SET_LONG("units", php_map->map->units, value)
+                    else IF_SET_DOUBLE("scaledenom", php_map->map->scaledenom, value)
+                      else IF_SET_STRING("shapepath", php_map->map->shapepath, value)
+                        else IF_SET_LONG("keysizex", php_map->map->legend.keysizex, value)
+                          else IF_SET_LONG("keysizey", php_map->map->legend.keysizey, value)
+                            else IF_SET_LONG("keyspacingx", php_map->map->legend.keyspacingx, value)
+                              else IF_SET_LONG("keyspacingy", php_map->map->legend.keyspacingy, value)
+                                else if ( (STRING_EQUAL("outputformat", property)) ||
+                                          (STRING_EQUAL("extent", property)) ||
+                                          (STRING_EQUAL("web", property)) ||
+                                          (STRING_EQUAL("reference", property)) ||
+                                          (STRING_EQUAL("scalebar", property)) ||
+                                          (STRING_EQUAL("legend", property)) ||
+                                          (STRING_EQUAL("querymap", property)) ||
+                                          (STRING_EQUAL("labelcache", property)) ||
+                                          (STRING_EQUAL("projection", property)) ||
+                                          (STRING_EQUAL("metadata", property)) ||
+                                          (STRING_EQUAL("configoptions", property)) ||
+                                          (STRING_EQUAL("imagecolor", property)) ) {
+                                  mapscript_throw_exception("Property '%s' is an object and can only be modified through its accessors." TSRMLS_CC, property);
+                                } else if ( (STRING_EQUAL("numlayers", property)) ||
+                                            (STRING_EQUAL("symbolsetfilename", property)) ||
+                                            (STRING_EQUAL("imagetype", property)) ||
+                                            (STRING_EQUAL("numoutputformats", property)) ||
+                                            (STRING_EQUAL("mappath", property)) ||
+                                            (STRING_EQUAL("fontsetfilename", property)) ) {
+                                  mapscript_throw_exception("Property '%s' is read-only and cannot be set." TSRMLS_CC, property);
+                                } else {
+                                  mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+                                }
 }
 
 /* {{{ proto int map.getSymbolByName(string symbolName)
    Returns the symbol index using the name. */
 PHP_METHOD(mapObj, getSymbolByName)
 {
-    zval *zobj = getThis();
-    char *symbolName;
-    long symbolName_len;
-    int symbolId = -1;
-    php_map_object *php_map;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &symbolName, &symbolName_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  char *symbolName;
+  long symbolName_len;
+  int symbolId = -1;
+  php_map_object *php_map;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &symbolName, &symbolName_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    symbolId = mapObj_getSymbolByName(php_map->map, symbolName);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  symbolId = mapObj_getSymbolByName(php_map->map, symbolName);
 
-    RETURN_LONG(symbolId);
+  RETURN_LONG(symbolId);
 }
 /* }}} */
 
 /* {{{ proto symbolObj map.getSymbolObjectById(int symbolId)
-   Returns the symbol object using a symbol id. Refer to the symbol object 
-   reference section for more details. */     
+   Returns the symbol object using a symbol id. Refer to the symbol object
+   reference section for more details. */
 PHP_METHOD(mapObj, getSymbolObjectById)
 {
-    zval *zobj = getThis();
-    long symbolId;
-    symbolObj *symbol = NULL;
-    php_map_object *php_map;
-    parent_object parent;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
-                              &symbolId) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  long symbolId;
+  symbolObj *symbol = NULL;
+  php_map_object *php_map;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
+                            &symbolId) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    if ( symbolId < 0 || symbolId >= php_map->map->symbolset.numsymbols)
-    {
-        mapscript_throw_exception("Invalid symbol index." TSRMLS_CC);
-        return;
-    }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    symbol = php_map->map->symbolset.symbol[symbolId];
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    /* Return style object */
-    MAPSCRIPT_MAKE_PARENT(zobj, NULL);
-    mapscript_create_symbol(symbol, parent, return_value TSRMLS_CC);
+  if ( symbolId < 0 || symbolId >= php_map->map->symbolset.numsymbols) {
+    mapscript_throw_exception("Invalid symbol index." TSRMLS_CC);
+    return;
+  }
+
+  symbol = php_map->map->symbolset.symbol[symbolId];
+
+  /* Return style object */
+  MAPSCRIPT_MAKE_PARENT(zobj, NULL);
+  mapscript_create_symbol(symbol, parent, return_value TSRMLS_CC);
 }
 /* }}} */
 
@@ -510,19 +529,19 @@ PHP_METHOD(mapObj, getSymbolObjectById)
    Calculate the scale of the map and assign it to the map->scaledenom */
 PHP_METHOD(mapObj, prepareQuery)
 {
-    zval *zobj = getThis();
-    php_map_object *php_map;
+  zval *zobj = getThis();
+  php_map_object *php_map;
 
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    mapObj_prepareQuery(php_map->map);
+  mapObj_prepareQuery(php_map->map);
 }
 /* }}} */
 
@@ -530,29 +549,28 @@ PHP_METHOD(mapObj, prepareQuery)
    Return handle on blank image object. */
 PHP_METHOD(mapObj, prepareImage)
 {
-    zval *zobj = getThis();
-    imageObj *image = NULL;
-    php_map_object *php_map;
+  zval *zobj = getThis();
+  imageObj *image = NULL;
+  php_map_object *php_map;
 
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    image = mapObj_prepareImage(php_map->map);
-    if (image == NULL)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  image = mapObj_prepareImage(php_map->map);
+  if (image == NULL) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
 
 
-    /* Return an image object */
-    mapscript_create_image(image, return_value TSRMLS_CC);
+  /* Return an image object */
+  mapscript_create_image(image, return_value TSRMLS_CC);
 }
 /* }}} */
 
@@ -560,27 +578,26 @@ PHP_METHOD(mapObj, prepareImage)
    Render map and return handle on image object. */
 PHP_METHOD(mapObj, draw)
 {
-    zval *zobj = getThis();
-    imageObj *image = NULL;
-    php_map_object *php_map;
+  zval *zobj = getThis();
+  imageObj *image = NULL;
+  php_map_object *php_map;
 
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    image = mapObj_draw(php_map->map);
-    if (image == NULL)
-    {
-        mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
-        RETURN_NULL();
-    }
-     
-    mapscript_create_image(image, return_value TSRMLS_CC);
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  image = mapObj_draw(php_map->map);
+  if (image == NULL) {
+    mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
+    RETURN_NULL();
+  }
+
+  mapscript_create_image(image, return_value TSRMLS_CC);
 }
 /* }}} */
 
@@ -588,27 +605,26 @@ PHP_METHOD(mapObj, draw)
    Renders a query map, returns an image.. */
 PHP_METHOD(mapObj, drawQuery)
 {
-    zval *zobj = getThis();
-    imageObj *image = NULL;
-    php_map_object *php_map;
+  zval *zobj = getThis();
+  imageObj *image = NULL;
+  php_map_object *php_map;
 
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    image = mapObj_drawQuery(php_map->map);
-    if (image == NULL)
-    {
-        mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
-        RETURN_NULL();
-    }
-     
-    mapscript_create_image(image, return_value TSRMLS_CC);
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  image = mapObj_drawQuery(php_map->map);
+  if (image == NULL) {
+    mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
+    RETURN_NULL();
+  }
+
+  mapscript_create_image(image, return_value TSRMLS_CC);
 }
 /* }}} */
 
@@ -616,28 +632,27 @@ PHP_METHOD(mapObj, drawQuery)
    Render legend and return handle on image object. */
 PHP_METHOD(mapObj, drawLegend)
 {
-    zval *zobj = getThis();
-    imageObj *image = NULL;
-    php_map_object *php_map;
+  zval *zobj = getThis();
+  imageObj *image = NULL;
+  php_map_object *php_map;
 
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    image = mapObj_drawLegend(php_map->map);
-    if (image == NULL)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-     
-    mapscript_create_image(image, return_value TSRMLS_CC);
+  image = mapObj_drawLegend(php_map->map);
+  if (image == NULL) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
+
+
+  mapscript_create_image(image, return_value TSRMLS_CC);
 }
 /* }}} */
 
@@ -645,28 +660,27 @@ PHP_METHOD(mapObj, drawLegend)
    Render reference map and return handle on image object. */
 PHP_METHOD(mapObj, drawReferenceMap)
 {
-    zval *zobj = getThis();
-    imageObj *image = NULL;
-    php_map_object *php_map;
+  zval *zobj = getThis();
+  imageObj *image = NULL;
+  php_map_object *php_map;
 
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    image = mapObj_drawReferenceMap(php_map->map);
-    if (image == NULL)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  image = mapObj_drawReferenceMap(php_map->map);
+  if (image == NULL) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
 
-     
-    mapscript_create_image(image, return_value TSRMLS_CC);
+
+  mapscript_create_image(image, return_value TSRMLS_CC);
 }
 /* }}} */
 
@@ -674,28 +688,27 @@ PHP_METHOD(mapObj, drawReferenceMap)
    Render scale bar and return handle on image object. */
 PHP_METHOD(mapObj, drawScaleBar)
 {
-    zval *zobj = getThis();
-    imageObj *image = NULL;
-    php_map_object *php_map;
+  zval *zobj = getThis();
+  imageObj *image = NULL;
+  php_map_object *php_map;
 
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    image = mapObj_drawScalebar(php_map->map);
-    if (image == NULL)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-     
-    mapscript_create_image(image, return_value TSRMLS_CC);
+  image = mapObj_drawScalebar(php_map->map);
+  if (image == NULL) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
+
+
+  mapscript_create_image(image, return_value TSRMLS_CC);
 }
 /* }}} */
 
@@ -703,32 +716,31 @@ PHP_METHOD(mapObj, drawScaleBar)
    Renders the legend within the map. Returns MS_FAILURE on error. */
 PHP_METHOD(mapObj, embedLegend)
 {
-    zval *zobj = getThis();
-    zval *zimage;
-    int retval = MS_FAILURE;
-    php_map_object *php_map;
-    php_image_object *php_image;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
-                              &zimage, mapscript_ce_image) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  zval *zimage;
+  int retval = MS_FAILURE;
+  php_map_object *php_map;
+  php_image_object *php_image;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
+                            &zimage, mapscript_ce_image) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_image = (php_image_object *) zend_object_store_get_object(zimage TSRMLS_CC);
+
+  retval = mapObj_embedLegend(php_map->map, php_image->image);
+  if ( (retval == MS_FAILURE) || (retval == -1) ) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
 
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_image = (php_image_object *) zend_object_store_get_object(zimage TSRMLS_CC);
-    
-    retval = mapObj_embedLegend(php_map->map, php_image->image);
-    if ( (retval == MS_FAILURE) || (retval == -1) )
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
 
-     
-    RETURN_LONG(retval);
+  RETURN_LONG(retval);
 }
 /* }}} */
 
@@ -736,32 +748,31 @@ PHP_METHOD(mapObj, embedLegend)
    Renders the scalebar within the map. Returns MS_FAILURE on error. */
 PHP_METHOD(mapObj, embedScaleBar)
 {
-    zval *zobj = getThis();
-    zval *zimage;
-    int retval = MS_FAILURE;
-    php_map_object *php_map;
-    php_image_object *php_image;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
-                              &zimage, mapscript_ce_image) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  zval *zimage;
+  int retval = MS_FAILURE;
+  php_map_object *php_map;
+  php_image_object *php_image;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
+                            &zimage, mapscript_ce_image) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_image = (php_image_object *) zend_object_store_get_object(zimage TSRMLS_CC);
-    
-    retval = mapObj_embedScalebar(php_map->map, php_image->image);
-    if ( (retval == MS_FAILURE) || (retval == -1) )
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_image = (php_image_object *) zend_object_store_get_object(zimage TSRMLS_CC);
+
+  retval = mapObj_embedScalebar(php_map->map, php_image->image);
+  if ( (retval == MS_FAILURE) || (retval == -1) ) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
 
-     
-    RETURN_LONG(retval);
+
+  RETURN_LONG(retval);
 }
 /* }}} */
 
@@ -769,32 +780,31 @@ PHP_METHOD(mapObj, embedScaleBar)
    Renders the labels for a map. Returns MS_FAILURE on error. */
 PHP_METHOD(mapObj, drawLabelCache)
 {
-    zval *zobj = getThis();
-    zval *zimage;
-    int retval = MS_FAILURE;
-    php_map_object *php_map;
-    php_image_object *php_image;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
-                              &zimage, mapscript_ce_image) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  zval *zimage;
+  int retval = MS_FAILURE;
+  php_map_object *php_map;
+  php_image_object *php_image;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
+                            &zimage, mapscript_ce_image) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_image = (php_image_object *) zend_object_store_get_object(zimage TSRMLS_CC);
+
+  retval = mapObj_drawLabelCache(php_map->map, php_image->image);
+  if ( (retval == MS_FAILURE) || (retval == -1) ) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
 
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_image = (php_image_object *) zend_object_store_get_object(zimage TSRMLS_CC);
-    
-    retval = mapObj_drawLabelCache(php_map->map, php_image->image);
-    if ( (retval == MS_FAILURE) || (retval == -1) )
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
 
-     
-    RETURN_LONG(retval);
+  RETURN_LONG(retval);
 }
 /* }}} */
 
@@ -802,33 +812,32 @@ PHP_METHOD(mapObj, drawLabelCache)
    Returns a layerObj from the map given an index value (0=first layer, etc.) */
 PHP_METHOD(mapObj, getLayer)
 {
-    zval *zobj = getThis();
-    long index;
-    layerObj *layer = NULL;
-    php_map_object *php_map;
-    parent_object parent;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
-                              &index) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  long index;
+  layerObj *layer = NULL;
+  php_map_object *php_map;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
+                            &index) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    layer = mapObj_getLayer(php_map->map, index);
-    if  (layer == NULL)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    /* Return layer object */
-    MAPSCRIPT_MAKE_PARENT(zobj, NULL);
-    mapscript_create_layer(layer, parent, return_value TSRMLS_CC);
+  layer = mapObj_getLayer(php_map->map, index);
+  if  (layer == NULL) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
+
+
+  /* Return layer object */
+  MAPSCRIPT_MAKE_PARENT(zobj, NULL);
+  mapscript_create_layer(layer, parent, return_value TSRMLS_CC);
 }
 /* }}} */
 
@@ -836,33 +845,32 @@ PHP_METHOD(mapObj, getLayer)
    Returns a layerObj from the map given a layer name */
 PHP_METHOD(mapObj, getLayerByName)
 {
-    zval *zobj = getThis();
-    char *layerName;
-    long layerName_len;
-    layerObj *layer = NULL;
-    php_map_object *php_map;
-    parent_object parent;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &layerName, &layerName_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  char *layerName;
+  long layerName_len;
+  layerObj *layer = NULL;
+  php_map_object *php_map;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &layerName, &layerName_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    layer = mapObj_getLayerByName(php_map->map, layerName);
-    if  (layer == NULL)
-    {
-        mapscript_report_php_error(E_WARNING, "getLayerByName failed for : %s\n" TSRMLS_CC, layerName);
-        RETURN_NULL();
-    }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    /* Return layer object */
-    MAPSCRIPT_MAKE_PARENT(zobj, NULL);
-    mapscript_create_layer(layer, parent, return_value TSRMLS_CC);
+  layer = mapObj_getLayerByName(php_map->map, layerName);
+  if  (layer == NULL) {
+    mapscript_report_php_error(E_WARNING, "getLayerByName failed for : %s\n" TSRMLS_CC, layerName);
+    RETURN_NULL();
+  }
+
+  /* Return layer object */
+  MAPSCRIPT_MAKE_PARENT(zobj, NULL);
+  mapscript_create_layer(layer, parent, return_value TSRMLS_CC);
 }
 /* }}} */
 
@@ -871,40 +879,37 @@ PHP_METHOD(mapObj, getLayerByName)
    Returns a colorObj from the map given a color index */
 PHP_METHOD(mapObj, getColorByIndex)
 {
-    zval *zobj = getThis();
-    long index;
-    paletteObj palette;
-    colorObj color;
-    php_map_object *php_map;
-    parent_object parent;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
-                              &index) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  long index;
+  paletteObj palette;
+  colorObj color;
+  php_map_object *php_map;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
+                            &index) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    palette = php_map->map->palette;
-    
-    if (index < palette.numcolors)
-    {
-        color.red = palette.colors[index].red;
-        color.green = palette.colors[index].green;
-        color.blue = palette.colors[index].blue;
-    }
-    else
-    {
-        mapscript_throw_mapserver_exception("Index shoud not be higher than %d\n" TSRMLS_CC, palette.numcolors-1);
-        return;
-    }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  palette = php_map->map->palette;
 
-    /* Return color object */
-    MAPSCRIPT_MAKE_PARENT(zobj, NULL);
-    mapscript_create_color(&color, parent, return_value TSRMLS_CC);    
+  if (index < palette.numcolors) {
+    color.red = palette.colors[index].red;
+    color.green = palette.colors[index].green;
+    color.blue = palette.colors[index].blue;
+  } else {
+    mapscript_throw_mapserver_exception("Index shoud not be higher than %d\n" TSRMLS_CC, palette.numcolors-1);
+    return;
+  }
+
+  /* Return color object */
+  MAPSCRIPT_MAKE_PARENT(zobj, NULL);
+  mapscript_create_color(&color, parent, return_value TSRMLS_CC);
 }
 /* }}} */
 
@@ -912,32 +917,31 @@ PHP_METHOD(mapObj, getColorByIndex)
    Set map extent property to new value. Returns MS_FAILURE on error. */
 PHP_METHOD(mapObj, setExtent)
 {
-    zval *zobj = getThis();
-    double minx, miny, maxx, maxy;
-    int status = MS_FAILURE;
-    php_map_object *php_map;
+  zval *zobj = getThis();
+  double minx, miny, maxx, maxy;
+  int status = MS_FAILURE;
+  php_map_object *php_map;
 
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "dddd",
-                              &minx, &miny, &maxx, &maxy) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "dddd",
+                            &minx, &miny, &maxx, &maxy) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    status = msMapSetExtent( php_map->map, 
-                             minx, miny,
-                             maxx, maxy);
-    
-    if (status != MS_SUCCESS)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
-    
-    RETURN_LONG(status);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  status = msMapSetExtent( php_map->map,
+                           minx, miny,
+                           maxx, maxy);
+
+  if (status != MS_SUCCESS) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -945,30 +949,29 @@ PHP_METHOD(mapObj, setExtent)
    Returns MS_SUCCESS or MS_FAILURE */
 PHP_METHOD(mapObj, setCenter)
 {
-    zval *zobj = getThis();
-    zval *zpoint;
-    int status = MS_FAILURE;
-    php_map_object *php_map;
-    php_point_object *php_point;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
-                              &zpoint, mapscript_ce_point) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  zval *zpoint;
+  int status = MS_FAILURE;
+  php_map_object *php_map;
+  php_point_object *php_point;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
+                            &zpoint, mapscript_ce_point) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_point = (php_point_object *) zend_object_store_get_object(zpoint TSRMLS_CC);
-    
-    status = mapObj_setCenter(php_map->map, php_point->point);
-    if (status != MS_SUCCESS)
-    {
-        mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
-    }
- 
-    RETURN_LONG(status);
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_point = (php_point_object *) zend_object_store_get_object(zpoint TSRMLS_CC);
+
+  status = mapObj_setCenter(php_map->map, php_point->point);
+  if (status != MS_SUCCESS) {
+    mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
+  }
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -976,58 +979,56 @@ PHP_METHOD(mapObj, setCenter)
    Returns MS_SUCCESS or MS_FAILURE */
 PHP_METHOD(mapObj, offsetExtent)
 {
-    zval *zobj = getThis();
-    double x, y;
-    int status = MS_FAILURE;
-    php_map_object *php_map;
+  zval *zobj = getThis();
+  double x, y;
+  int status = MS_FAILURE;
+  php_map_object *php_map;
 
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "dd",
-                              &x, &y) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "dd",
+                            &x, &y) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    status = mapObj_offsetExtent(php_map->map, x, y);
-    if (status != MS_SUCCESS)
-    {
-        mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
-    }
-    
-    RETURN_LONG(status);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  status = mapObj_offsetExtent(php_map->map, x, y);
+  if (status != MS_SUCCESS) {
+    mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
+  }
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
 /* {{{ proto int map.scaleExtent(double zoomfactor, double minscaledenom,
-                                 double maxscaledenom) 
+                                 double maxscaledenom)
    Returns MS_SUCCESS or MS_FAILURE */
 PHP_METHOD(mapObj, scaleExtent)
 {
-    zval *zobj = getThis();
-    double zoomFactor, minScaleDenom, maxScaleDenom;
-    int status = MS_FAILURE;
-    php_map_object *php_map;
-    
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ddd",
-                              &zoomFactor, &minScaleDenom, &maxScaleDenom) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  double zoomFactor, minScaleDenom, maxScaleDenom;
+  int status = MS_FAILURE;
+  php_map_object *php_map;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ddd",
+                            &zoomFactor, &minScaleDenom, &maxScaleDenom) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    status = mapObj_scaleExtent(php_map->map, zoomFactor, minScaleDenom, maxScaleDenom);
-    if (status != MS_SUCCESS)
-    {
-        mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
-    }
-    
-    RETURN_LONG(status);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  status = mapObj_scaleExtent(php_map->map, zoomFactor, minScaleDenom, maxScaleDenom);
+  if (status != MS_SUCCESS) {
+    mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
+  }
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -1038,306 +1039,278 @@ PHP_METHOD(mapObj, scaleExtent)
    clockwise direction. */
 PHP_METHOD(mapObj, setRotation)
 {
-    zval *zobj = getThis();
-    double angle;
-    int status = MS_FAILURE;
-    php_map_object *php_map;
-    
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "d",
-                              &angle) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  double angle;
+  int status = MS_FAILURE;
+  php_map_object *php_map;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "d",
+                            &angle) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    status = mapObj_setRotation(php_map->map, angle);
-    if (status != MS_SUCCESS)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
-    
-    RETURN_LONG(status);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  status = mapObj_setRotation(php_map->map, angle);
+  if (status != MS_SUCCESS) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
 /* {{{ proto int map.setSize(int width, int height)
-   Set map size (width, height) properties to new values and upddate internal geotransform. 
+   Set map size (width, height) properties to new values and upddate internal geotransform.
    Returns MS_SUCCESS/MS_FAILURE. */
 PHP_METHOD(mapObj, setSize)
 {
-    zval *zobj = getThis();
-    long width, height;
-    int status = MS_FAILURE;
-    php_map_object *php_map;
+  zval *zobj = getThis();
+  long width, height;
+  int status = MS_FAILURE;
+  php_map_object *php_map;
 
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ll",
-                              &width, &height) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ll",
+                            &width, &height) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    status = msMapSetSize(php_map->map, width, height);
-    if (status != MS_SUCCESS)
-    {
-        mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
-    }
-    
-    RETURN_LONG(status);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  status = msMapSetSize(php_map->map, width, height);
+  if (status != MS_SUCCESS) {
+    mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
+  }
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
-/* {{{ proto int zoompoint(int zoomFactor, pointObj pixelPosition, int width, int height, 
+/* {{{ proto int zoompoint(int zoomFactor, pointObj pixelPosition, int width, int height,
                            rectObj geoRefExtent, [rectObj mapGeoRefExtent])
    Zoom to a given XY postion. */
 PHP_METHOD(mapObj, zoomPoint)
 {
-    zval *zobj = getThis();
-    zval *zpoint, *zgeoRefExtent, *zmaxGeoRefExtent = NULL;
-    long zoomFactor, width, height;
-    double      dfGeoPosX, dfGeoPosY;
-    double      dfDeltaX, dfDeltaY;
-    rectObj     newGeoRefExtent;    
-    double      dfNewScale = 0.0;
-    double      dfDeltaExt = -1.0;
-    php_point_object *php_pixelPosition;
-    php_rect_object *php_geoRefExtent, *php_maxGeoRefExtent;
-    php_map_object *php_map;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "lOllO|O",
-                              &zoomFactor,
-                              &zpoint, mapscript_ce_point,
-                              &width, &height,
-                              &zgeoRefExtent , mapscript_ce_rect,
-                              &zmaxGeoRefExtent , mapscript_ce_rect) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-return;
-    }
-PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_pixelPosition = (php_point_object *) zend_object_store_get_object(zpoint TSRMLS_CC);
-    php_geoRefExtent = (php_rect_object *) zend_object_store_get_object(zgeoRefExtent TSRMLS_CC);
-    if (zmaxGeoRefExtent)
-        php_maxGeoRefExtent = (php_rect_object *) zend_object_store_get_object(zmaxGeoRefExtent TSRMLS_CC);
-    
-/* -------------------------------------------------------------------- */
-/*      check the validity of the parameters.                           */
-/* -------------------------------------------------------------------- */
-    if (zoomFactor == 0 || 
-        width <= 0 ||
-        height <= 0 ||
-        php_geoRefExtent->rect == NULL ||
-        php_pixelPosition->point == NULL ||
-        (zmaxGeoRefExtent && php_maxGeoRefExtent->rect == NULL))
-    {
-        mapscript_throw_mapserver_exception("Incorrect parameters\n" TSRMLS_CC);
-        return;
-    }
-
-/* -------------------------------------------------------------------- */
-/*      check if the values passed are consistent min > max.             */
-/* -------------------------------------------------------------------- */
-    if (php_geoRefExtent->rect->minx >= php_geoRefExtent->rect->maxx)
-    {
-        mapscript_throw_mapserver_exception("Georeferenced coordinates minx >= maxx\n" TSRMLS_CC);
-        return;
-    }
-    if (php_geoRefExtent->rect->miny >= php_geoRefExtent->rect->maxy)
-    {
-        mapscript_throw_mapserver_exception("Georeferenced coordinates miny >= maxy\n" TSRMLS_CC);
-        return;
-    }
-
-    if (zmaxGeoRefExtent)
-    {
-        if (php_maxGeoRefExtent->rect->minx >= php_maxGeoRefExtent->rect->maxx)
-        {
-            mapscript_throw_mapserver_exception("Max Georeferenced coordinates minx >= maxx\n" TSRMLS_CC);
-            return;
-        }
-        if (php_maxGeoRefExtent->rect->miny >= php_maxGeoRefExtent->rect->maxy)
-        {
-            mapscript_throw_mapserver_exception("Max Georeferenced coordinates miny >= maxy\n" TSRMLS_CC);
-            return;
-        }
-    }
-
-    
-    dfGeoPosX = Pix2Georef((int)php_pixelPosition->point->x, 0, width, 
-                           php_geoRefExtent->rect->minx, php_geoRefExtent->rect->maxx, 0); 
-    dfGeoPosY = Pix2Georef((int)php_pixelPosition->point->y, 0, height, 
-                           php_geoRefExtent->rect->miny, php_geoRefExtent->rect->maxy, 1); 
-    dfDeltaX = php_geoRefExtent->rect->maxx - php_geoRefExtent->rect->minx;
-    dfDeltaY = php_geoRefExtent->rect->maxy - php_geoRefExtent->rect->miny;
-
-   
-/* -------------------------------------------------------------------- */
-/*      zoom in                                                         */
-/* -------------------------------------------------------------------- */
-    if (zoomFactor > 1)
-    {
-        newGeoRefExtent.minx = 
-            dfGeoPosX - (dfDeltaX/(2*zoomFactor));        
-         newGeoRefExtent.miny = 
-             dfGeoPosY - (dfDeltaY/(2*zoomFactor));        
-         newGeoRefExtent.maxx = 
-             dfGeoPosX + (dfDeltaX/(2*zoomFactor));        
-         newGeoRefExtent.maxy = 
-             dfGeoPosY + (dfDeltaY/(2*zoomFactor));
-    }
-
-    if (zoomFactor < 0)
-    {
-        newGeoRefExtent.minx = 
-            dfGeoPosX - (dfDeltaX/2)*(abs(zoomFactor));    
-        newGeoRefExtent.miny = 
-            dfGeoPosY - (dfDeltaY/2)*(abs(zoomFactor));    
-        newGeoRefExtent.maxx = 
-            dfGeoPosX + (dfDeltaX/2)*(abs(zoomFactor));    
-        newGeoRefExtent.maxy = 
-            dfGeoPosY + (dfDeltaY/2)*(abs(zoomFactor));
-    }
-    if (zoomFactor == 1)
-    {
-        newGeoRefExtent.minx = dfGeoPosX - (dfDeltaX/2);
-        newGeoRefExtent.miny = dfGeoPosY - (dfDeltaY/2);
-        newGeoRefExtent.maxx = dfGeoPosX + (dfDeltaX/2);
-        newGeoRefExtent.maxy = dfGeoPosY + (dfDeltaY/2);
-    }
-
-/* -------------------------------------------------------------------- */
-/*      if the min and max scale are set in the map file, we will       */
-/*      use them to test before zooming.                                */
-/* -------------------------------------------------------------------- */
-    msAdjustExtent(&newGeoRefExtent, php_map->map->width, php_map->map->height);
-    if (msCalculateScale(newGeoRefExtent, php_map->map->units, 
-                         php_map->map->width, php_map->map->height, 
-                         php_map->map->resolution, &dfNewScale) != MS_SUCCESS)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
-
-    if (php_map->map->web.maxscaledenom > 0)
-    {
-        if (zoomFactor < 0 && dfNewScale >  php_map->map->web.maxscaledenom)
-        {
-            RETURN_LONG(MS_FAILURE);
-        }
-    }
+  zval *zobj = getThis();
+  zval *zpoint, *zgeoRefExtent, *zmaxGeoRefExtent = NULL;
+  long zoomFactor, width, height;
+  double      dfGeoPosX, dfGeoPosY;
+  double      dfDeltaX, dfDeltaY;
+  rectObj     newGeoRefExtent;
+  double      dfNewScale = 0.0;
+  double      dfDeltaExt = -1.0;
+  php_point_object *php_pixelPosition;
+  php_rect_object *php_geoRefExtent=NULL, *php_maxGeoRefExtent=NULL;
+  php_map_object *php_map;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "lOllO|O",
+                            &zoomFactor,
+                            &zpoint, mapscript_ce_point,
+                            &width, &height,
+                            &zgeoRefExtent , mapscript_ce_rect,
+                            &zmaxGeoRefExtent , mapscript_ce_rect) == FAILURE) {
+    PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_pixelPosition = (php_point_object *) zend_object_store_get_object(zpoint TSRMLS_CC);
+  php_geoRefExtent = (php_rect_object *) zend_object_store_get_object(zgeoRefExtent TSRMLS_CC);
+  if (zmaxGeoRefExtent)
+    php_maxGeoRefExtent = (php_rect_object *) zend_object_store_get_object(zmaxGeoRefExtent TSRMLS_CC);
+
+  /* -------------------------------------------------------------------- */
+  /*      check the validity of the parameters.                           */
+  /* -------------------------------------------------------------------- */
+  if (zoomFactor == 0 ||
+      width <= 0 ||
+      height <= 0 ||
+      php_geoRefExtent->rect == NULL ||
+      php_pixelPosition->point == NULL ||
+      (zmaxGeoRefExtent && php_maxGeoRefExtent->rect == NULL)) {
+    mapscript_throw_mapserver_exception("Incorrect parameters\n" TSRMLS_CC);
+    return;
+  }
 
-/* ==================================================================== */
-/*      we do a spcial case for zoom in : we try to zoom as much as     */
-/*      possible using the mincale set in the .map.                     */
-/* ==================================================================== */
-    if (php_map->map->web.minscaledenom > 0 && dfNewScale <  php_map->map->web.minscaledenom &&
-        zoomFactor > 1)
-    {
-        dfDeltaExt = 
-            GetDeltaExtentsUsingScale(php_map->map->web.minscaledenom, php_map->map->units,
-                                      dfGeoPosY, php_map->map->width, 
-                                      php_map->map->resolution);
-        if (dfDeltaExt > 0.0)
-        {
-            newGeoRefExtent.minx = dfGeoPosX - (dfDeltaExt/2);
-            newGeoRefExtent.miny = dfGeoPosY - (dfDeltaExt/2);
-            newGeoRefExtent.maxx = dfGeoPosX + (dfDeltaExt/2);
-            newGeoRefExtent.maxy = dfGeoPosY + (dfDeltaExt/2);
-        }
-        else
-            RETURN_LONG(MS_FAILURE);
-    }
-/* -------------------------------------------------------------------- */
-/*      If the buffer is set, make sure that the extents do not go      */
-/*      beyond the buffer.                                              */
-/* -------------------------------------------------------------------- */
-    if (zmaxGeoRefExtent)
-    {
-        dfDeltaX = newGeoRefExtent.maxx - newGeoRefExtent.minx;
-        dfDeltaY = newGeoRefExtent.maxy - newGeoRefExtent.miny;
-        
-        /* Make sure Current georef extents is not bigger than max extents */
-        if (dfDeltaX > (php_maxGeoRefExtent->rect->maxx-php_maxGeoRefExtent->rect->minx))
-            dfDeltaX = php_maxGeoRefExtent->rect->maxx-php_maxGeoRefExtent->rect->minx;
-        if (dfDeltaY > (php_maxGeoRefExtent->rect->maxy-php_maxGeoRefExtent->rect->miny))
-            dfDeltaY = php_maxGeoRefExtent->rect->maxy-php_maxGeoRefExtent->rect->miny;
-
-        if (newGeoRefExtent.minx < php_maxGeoRefExtent->rect->minx)
-        {
-            newGeoRefExtent.minx = php_maxGeoRefExtent->rect->minx;
-            newGeoRefExtent.maxx =  newGeoRefExtent.minx + dfDeltaX;
-        }
-        if (newGeoRefExtent.maxx > php_maxGeoRefExtent->rect->maxx)
-        {
-            newGeoRefExtent.maxx = php_maxGeoRefExtent->rect->maxx;
-            newGeoRefExtent.minx = newGeoRefExtent.maxx - dfDeltaX;
-        }
-        if (newGeoRefExtent.miny < php_maxGeoRefExtent->rect->miny)
-        {
-            newGeoRefExtent.miny = php_maxGeoRefExtent->rect->miny;
-            newGeoRefExtent.maxy =  newGeoRefExtent.miny + dfDeltaY;
-        }
-        if (newGeoRefExtent.maxy > php_maxGeoRefExtent->rect->maxy)
-        {
-            newGeoRefExtent.maxy = php_maxGeoRefExtent->rect->maxy;
-            newGeoRefExtent.miny = newGeoRefExtent.maxy - dfDeltaY;
-        }
-    }
-    
-/* -------------------------------------------------------------------- */
-/*      set the map extents with new values.                            */
-/* -------------------------------------------------------------------- */
-    php_map->map->extent.minx = newGeoRefExtent.minx;
-    php_map->map->extent.miny = newGeoRefExtent.miny;
-    php_map->map->extent.maxx = newGeoRefExtent.maxx;
-    php_map->map->extent.maxy = newGeoRefExtent.maxy;
-    
-    php_map->map->cellsize = msAdjustExtent(&(php_map->map->extent), php_map->map->width, 
-                                    php_map->map->height);      
-    dfDeltaX = php_map->map->extent.maxx - php_map->map->extent.minx;
-    dfDeltaY = php_map->map->extent.maxy - php_map->map->extent.miny; 
-
-    if (zmaxGeoRefExtent)
-    {
-        if (php_map->map->extent.minx < php_maxGeoRefExtent->rect->minx)
-        {
-            php_map->map->extent.minx = php_maxGeoRefExtent->rect->minx;
-            php_map->map->extent.maxx = php_map->map->extent.minx + dfDeltaX;
-        }
-        if (php_map->map->extent.maxx > php_maxGeoRefExtent->rect->maxx)
-        {
-            php_map->map->extent.maxx = php_maxGeoRefExtent->rect->maxx;
-            newGeoRefExtent.minx = newGeoRefExtent.maxx - dfDeltaX;
-        }
-        if (php_map->map->extent.miny < php_maxGeoRefExtent->rect->miny)
-        {
-            php_map->map->extent.miny = php_maxGeoRefExtent->rect->miny;
-            php_map->map->extent.maxy =  php_map->map->extent.miny + dfDeltaY;
-        }
-        if (php_map->map->extent.maxy > php_maxGeoRefExtent->rect->maxy)
-        {
-            php_map->map->extent.maxy = php_maxGeoRefExtent->rect->maxy;
-            newGeoRefExtent.miny = newGeoRefExtent.maxy - dfDeltaY;
-        }
-    }
-    
-    if (msCalculateScale(php_map->map->extent, php_map->map->units, php_map->map->width, php_map->map->height, 
-                         php_map->map->resolution, &(php_map->map->scaledenom)) != MS_SUCCESS)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
+  /* -------------------------------------------------------------------- */
+  /*      check if the values passed are consistent min > max.             */
+  /* -------------------------------------------------------------------- */
+  if (php_geoRefExtent->rect->minx >= php_geoRefExtent->rect->maxx) {
+    mapscript_throw_mapserver_exception("Georeferenced coordinates minx >= maxx\n" TSRMLS_CC);
+    return;
+  }
+  if (php_geoRefExtent->rect->miny >= php_geoRefExtent->rect->maxy) {
+    mapscript_throw_mapserver_exception("Georeferenced coordinates miny >= maxy\n" TSRMLS_CC);
+    return;
+  }
+
+  if (zmaxGeoRefExtent) {
+    if (php_maxGeoRefExtent->rect->minx >= php_maxGeoRefExtent->rect->maxx) {
+      mapscript_throw_mapserver_exception("Max Georeferenced coordinates minx >= maxx\n" TSRMLS_CC);
+      return;
+    }
+    if (php_maxGeoRefExtent->rect->miny >= php_maxGeoRefExtent->rect->maxy) {
+      mapscript_throw_mapserver_exception("Max Georeferenced coordinates miny >= maxy\n" TSRMLS_CC);
+      return;
+    }
+  }
+
+
+  dfGeoPosX = Pix2Georef((int)php_pixelPosition->point->x, 0, width,
+                         php_geoRefExtent->rect->minx, php_geoRefExtent->rect->maxx, 0);
+  dfGeoPosY = Pix2Georef((int)php_pixelPosition->point->y, 0, height,
+                         php_geoRefExtent->rect->miny, php_geoRefExtent->rect->maxy, 1);
+  dfDeltaX = php_geoRefExtent->rect->maxx - php_geoRefExtent->rect->minx;
+  dfDeltaY = php_geoRefExtent->rect->maxy - php_geoRefExtent->rect->miny;
+
+
+  /* -------------------------------------------------------------------- */
+  /*      zoom in                                                         */
+  /* -------------------------------------------------------------------- */
+  if (zoomFactor > 1) {
+    newGeoRefExtent.minx =
+      dfGeoPosX - (dfDeltaX/(2*zoomFactor));
+    newGeoRefExtent.miny =
+      dfGeoPosY - (dfDeltaY/(2*zoomFactor));
+    newGeoRefExtent.maxx =
+      dfGeoPosX + (dfDeltaX/(2*zoomFactor));
+    newGeoRefExtent.maxy =
+      dfGeoPosY + (dfDeltaY/(2*zoomFactor));
+  }
+
+  if (zoomFactor < 0) {
+    newGeoRefExtent.minx =
+      dfGeoPosX - (dfDeltaX/2)*(abs(zoomFactor));
+    newGeoRefExtent.miny =
+      dfGeoPosY - (dfDeltaY/2)*(abs(zoomFactor));
+    newGeoRefExtent.maxx =
+      dfGeoPosX + (dfDeltaX/2)*(abs(zoomFactor));
+    newGeoRefExtent.maxy =
+      dfGeoPosY + (dfDeltaY/2)*(abs(zoomFactor));
+  }
+  if (zoomFactor == 1) {
+    newGeoRefExtent.minx = dfGeoPosX - (dfDeltaX/2);
+    newGeoRefExtent.miny = dfGeoPosY - (dfDeltaY/2);
+    newGeoRefExtent.maxx = dfGeoPosX + (dfDeltaX/2);
+    newGeoRefExtent.maxy = dfGeoPosY + (dfDeltaY/2);
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      if the min and max scale are set in the map file, we will       */
+  /*      use them to test before zooming.                                */
+  /* -------------------------------------------------------------------- */
+  msAdjustExtent(&newGeoRefExtent, php_map->map->width, php_map->map->height);
+  if (msCalculateScale(newGeoRefExtent, php_map->map->units,
+                       php_map->map->width, php_map->map->height,
+                       php_map->map->resolution, &dfNewScale) != MS_SUCCESS) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
+
+  if (php_map->map->web.maxscaledenom > 0) {
+    if (zoomFactor < 0 && dfNewScale >  php_map->map->web.maxscaledenom) {
+      RETURN_LONG(MS_FAILURE);
+    }
+  }
+
+  /* ==================================================================== */
+  /*      we do a spcial case for zoom in : we try to zoom as much as     */
+  /*      possible using the mincale set in the .map.                     */
+  /* ==================================================================== */
+  if (php_map->map->web.minscaledenom > 0 && dfNewScale <  php_map->map->web.minscaledenom &&
+      zoomFactor > 1) {
+    dfDeltaExt =
+      GetDeltaExtentsUsingScale(php_map->map->web.minscaledenom, php_map->map->units,
+                                dfGeoPosY, php_map->map->width,
+                                php_map->map->resolution);
+    if (dfDeltaExt > 0.0) {
+      newGeoRefExtent.minx = dfGeoPosX - (dfDeltaExt/2);
+      newGeoRefExtent.miny = dfGeoPosY - (dfDeltaExt/2);
+      newGeoRefExtent.maxx = dfGeoPosX + (dfDeltaExt/2);
+      newGeoRefExtent.maxy = dfGeoPosY + (dfDeltaExt/2);
+    } else
+      RETURN_LONG(MS_FAILURE);
+  }
+  /* -------------------------------------------------------------------- */
+  /*      If the buffer is set, make sure that the extents do not go      */
+  /*      beyond the buffer.                                              */
+  /* -------------------------------------------------------------------- */
+  if (zmaxGeoRefExtent) {
+    dfDeltaX = newGeoRefExtent.maxx - newGeoRefExtent.minx;
+    dfDeltaY = newGeoRefExtent.maxy - newGeoRefExtent.miny;
+
+    /* Make sure Current georef extents is not bigger than max extents */
+    if (dfDeltaX > (php_maxGeoRefExtent->rect->maxx-php_maxGeoRefExtent->rect->minx))
+      dfDeltaX = php_maxGeoRefExtent->rect->maxx-php_maxGeoRefExtent->rect->minx;
+    if (dfDeltaY > (php_maxGeoRefExtent->rect->maxy-php_maxGeoRefExtent->rect->miny))
+      dfDeltaY = php_maxGeoRefExtent->rect->maxy-php_maxGeoRefExtent->rect->miny;
+
+    if (newGeoRefExtent.minx < php_maxGeoRefExtent->rect->minx) {
+      newGeoRefExtent.minx = php_maxGeoRefExtent->rect->minx;
+      newGeoRefExtent.maxx =  newGeoRefExtent.minx + dfDeltaX;
+    }
+    if (newGeoRefExtent.maxx > php_maxGeoRefExtent->rect->maxx) {
+      newGeoRefExtent.maxx = php_maxGeoRefExtent->rect->maxx;
+      newGeoRefExtent.minx = newGeoRefExtent.maxx - dfDeltaX;
+    }
+    if (newGeoRefExtent.miny < php_maxGeoRefExtent->rect->miny) {
+      newGeoRefExtent.miny = php_maxGeoRefExtent->rect->miny;
+      newGeoRefExtent.maxy =  newGeoRefExtent.miny + dfDeltaY;
+    }
+    if (newGeoRefExtent.maxy > php_maxGeoRefExtent->rect->maxy) {
+      newGeoRefExtent.maxy = php_maxGeoRefExtent->rect->maxy;
+      newGeoRefExtent.miny = newGeoRefExtent.maxy - dfDeltaY;
+    }
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      set the map extents with new values.                            */
+  /* -------------------------------------------------------------------- */
+  php_map->map->extent.minx = newGeoRefExtent.minx;
+  php_map->map->extent.miny = newGeoRefExtent.miny;
+  php_map->map->extent.maxx = newGeoRefExtent.maxx;
+  php_map->map->extent.maxy = newGeoRefExtent.maxy;
+
+  php_map->map->cellsize = msAdjustExtent(&(php_map->map->extent), php_map->map->width,
+                                          php_map->map->height);
+  dfDeltaX = php_map->map->extent.maxx - php_map->map->extent.minx;
+  dfDeltaY = php_map->map->extent.maxy - php_map->map->extent.miny;
+
+  if (zmaxGeoRefExtent) {
+    if (php_map->map->extent.minx < php_maxGeoRefExtent->rect->minx) {
+      php_map->map->extent.minx = php_maxGeoRefExtent->rect->minx;
+      php_map->map->extent.maxx = php_map->map->extent.minx + dfDeltaX;
+    }
+    if (php_map->map->extent.maxx > php_maxGeoRefExtent->rect->maxx) {
+      php_map->map->extent.maxx = php_maxGeoRefExtent->rect->maxx;
+      newGeoRefExtent.minx = newGeoRefExtent.maxx - dfDeltaX;
+    }
+    if (php_map->map->extent.miny < php_maxGeoRefExtent->rect->miny) {
+      php_map->map->extent.miny = php_maxGeoRefExtent->rect->miny;
+      php_map->map->extent.maxy =  php_map->map->extent.miny + dfDeltaY;
+    }
+    if (php_map->map->extent.maxy > php_maxGeoRefExtent->rect->maxy) {
+      php_map->map->extent.maxy = php_maxGeoRefExtent->rect->maxy;
+      newGeoRefExtent.miny = newGeoRefExtent.maxy - dfDeltaY;
+    }
+  }
+
+  if (msCalculateScale(php_map->map->extent, php_map->map->units, php_map->map->width, php_map->map->height,
+                       php_map->map->resolution, &(php_map->map->scaledenom)) != MS_SUCCESS) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
 
-    RETURN_LONG(MS_SUCCESS);
+  RETURN_LONG(MS_SUCCESS);
 }
 /* }}} */
 
@@ -1345,470 +1318,422 @@ PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
    Set the map extents to a given extents.*/
 PHP_METHOD(mapObj, zoomRectangle)
 {
-    zval *zobj = getThis();
-    zval *zpixelExtent, *zgeoRefExtent, *zmaxGeoRefExtent = NULL;
-    long width, height;
-    double      dfDeltaX, dfDeltaY;
-    rectObj     newGeoRefExtent;    
-    double      dfNewScale = 0.0;
-    double      dfDeltaExt = -1.0;
-    double      dfMiddleX =0.0;
-    double      dfMiddleY =0.0;
-    php_rect_object *php_geoRefExtent, *php_maxGeoRefExtent, *php_pixelExtent;
-    php_map_object *php_map;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "OllO|O",
-                              &zpixelExtent , mapscript_ce_rect,
-                              &width, &height,
-                              &zgeoRefExtent , mapscript_ce_rect,
-                              &zmaxGeoRefExtent , mapscript_ce_rect) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  zval *zpixelExtent, *zgeoRefExtent, *zmaxGeoRefExtent = NULL;
+  long width, height;
+  double      dfDeltaX, dfDeltaY;
+  rectObj     newGeoRefExtent;
+  double      dfNewScale = 0.0;
+  double      dfDeltaExt = -1.0;
+  double      dfMiddleX =0.0;
+  double      dfMiddleY =0.0;
+  php_rect_object *php_geoRefExtent=NULL, *php_maxGeoRefExtent=NULL, *php_pixelExtent=NULL;
+  php_map_object *php_map;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "OllO|O",
+                            &zpixelExtent , mapscript_ce_rect,
+                            &width, &height,
+                            &zgeoRefExtent , mapscript_ce_rect,
+                            &zmaxGeoRefExtent , mapscript_ce_rect) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_pixelExtent = (php_rect_object *) zend_object_store_get_object(zpixelExtent TSRMLS_CC);
-    php_geoRefExtent = (php_rect_object *) zend_object_store_get_object(zgeoRefExtent TSRMLS_CC);
-    if (zmaxGeoRefExtent)
-        php_maxGeoRefExtent = (php_rect_object *) zend_object_store_get_object(zmaxGeoRefExtent TSRMLS_CC);
-
-
-/* -------------------------------------------------------------------- */
-/*      check the validity of the parameters.                           */
-/* -------------------------------------------------------------------- */
-    if (width <= 0 ||
-        height <= 0 ||
-        php_geoRefExtent->rect == NULL ||
-        php_pixelExtent->rect == NULL ||
-        (zmaxGeoRefExtent && php_maxGeoRefExtent->rect == NULL))
-    {
-        mapscript_throw_mapserver_exception("Incorrect parameters\n" TSRMLS_CC);
-        return;
-    }
-
-/* -------------------------------------------------------------------- */
-/*      check if the values passed are consistent min > max.            */
-/* -------------------------------------------------------------------- */
-    if (php_geoRefExtent->rect->minx >= php_geoRefExtent->rect->maxx)
-    {
-        mapscript_throw_mapserver_exception("Georeferenced coordinates minx >= maxx\n" TSRMLS_CC);
-        return;
-    }
-    if (php_geoRefExtent->rect->miny >= php_geoRefExtent->rect->maxy)
-    {
-        mapscript_throw_mapserver_exception("Georeferenced coordinates miny >= maxy\n" TSRMLS_CC);
-        return;
-    }
-    if (zmaxGeoRefExtent)
-    {
-        if (php_maxGeoRefExtent->rect->minx >= php_maxGeoRefExtent->rect->maxx)
-        {
-            mapscript_throw_mapserver_exception("Max Georeferenced coordinates minx >= maxx\n" TSRMLS_CC);
-            return;
-        }
-        if (php_maxGeoRefExtent->rect->miny >= php_maxGeoRefExtent->rect->maxy)
-        {
-            mapscript_throw_mapserver_exception("Max Georeferenced coordinates miny >= maxy\n" TSRMLS_CC);
-            return;
-        }
-    }
-
-
-    newGeoRefExtent.minx = Pix2Georef((int)php_pixelExtent->rect->minx, 0, 
-                                    width, 
-                                    php_geoRefExtent->rect->minx, php_geoRefExtent->rect->maxx, 0); 
-    newGeoRefExtent.maxx = Pix2Georef((int)php_pixelExtent->rect->maxx, 0, 
-                                    width, 
-                                    php_geoRefExtent->rect->minx, php_geoRefExtent->rect->maxx, 0); 
-    newGeoRefExtent.miny = Pix2Georef((int)php_pixelExtent->rect->miny, 0, 
-                                    height, 
-                                    php_geoRefExtent->rect->miny, php_geoRefExtent->rect->maxy, 1); 
-    newGeoRefExtent.maxy = Pix2Georef((int)php_pixelExtent->rect->maxy, 0, 
-                                    height, 
-                                    php_geoRefExtent->rect->miny, php_geoRefExtent->rect->maxy, 1); 
-    
-    msAdjustExtent(&newGeoRefExtent, php_map->map->width, php_map->map->height);
-
-/* -------------------------------------------------------------------- */
-/*      if the min and max scale are set in the map file, we will       */
-/*      use them to test before setting extents.                        */
-/* -------------------------------------------------------------------- */
-    if (msCalculateScale(newGeoRefExtent, php_map->map->units, 
-                         php_map->map->width, php_map->map->height, 
-                         php_map->map->resolution, &dfNewScale) != MS_SUCCESS)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
-
-    if (php_map->map->web.maxscaledenom > 0 &&  dfNewScale > php_map->map->web.maxscaledenom)
-    {
-        RETURN_LONG(MS_FAILURE);
-    }
-
-    if (php_map->map->web.minscaledenom > 0 && dfNewScale <  php_map->map->web.minscaledenom)
-    {
-        dfMiddleX = newGeoRefExtent.minx + 
-            ((newGeoRefExtent.maxx - newGeoRefExtent.minx)/2);
-        dfMiddleY = newGeoRefExtent.miny + 
-            ((newGeoRefExtent.maxy - newGeoRefExtent.miny)/2);
-        
-        dfDeltaExt = 
-            GetDeltaExtentsUsingScale(php_map->map->web.minscaledenom, php_map->map->units, 
-                                      dfMiddleY, php_map->map->width, 
-                                      php_map->map->resolution);
-
-        if (dfDeltaExt > 0.0)
-        {
-            newGeoRefExtent.minx = dfMiddleX - (dfDeltaExt/2);
-            newGeoRefExtent.miny = dfMiddleY - (dfDeltaExt/2);
-            newGeoRefExtent.maxx = dfMiddleX + (dfDeltaExt/2);
-            newGeoRefExtent.maxy = dfMiddleY + (dfDeltaExt/2);
-        }
-        else
-            RETURN_LONG(MS_FAILURE);
-    }
-
-/* -------------------------------------------------------------------- */
-/*      If the buffer is set, make sure that the extents do not go      */
-/*      beyond the buffer.                                              */
-/* -------------------------------------------------------------------- */
-    if (zmaxGeoRefExtent)
-    {
-        dfDeltaX = newGeoRefExtent.maxx - newGeoRefExtent.minx;
-        dfDeltaY = newGeoRefExtent.maxy - newGeoRefExtent.miny;
-        
-        /* Make sure Current georef extents is not bigger than max extents */
-        if (dfDeltaX > (php_maxGeoRefExtent->rect->maxx-php_maxGeoRefExtent->rect->minx))
-            dfDeltaX = php_maxGeoRefExtent->rect->maxx-php_maxGeoRefExtent->rect->minx;
-        if (dfDeltaY > (php_maxGeoRefExtent->rect->maxy-php_maxGeoRefExtent->rect->miny))
-            dfDeltaY = php_maxGeoRefExtent->rect->maxy-php_maxGeoRefExtent->rect->miny;
-
-        if (newGeoRefExtent.minx < php_maxGeoRefExtent->rect->minx)
-        {
-            newGeoRefExtent.minx = php_maxGeoRefExtent->rect->minx;
-            newGeoRefExtent.maxx =  newGeoRefExtent.minx + dfDeltaX;
-        }
-        if (newGeoRefExtent.maxx > php_maxGeoRefExtent->rect->maxx)
-        {
-            newGeoRefExtent.maxx = php_maxGeoRefExtent->rect->maxx;
-            newGeoRefExtent.minx = newGeoRefExtent.maxx - dfDeltaX;
-        }
-        if (newGeoRefExtent.miny < php_maxGeoRefExtent->rect->miny)
-        {
-            newGeoRefExtent.miny = php_maxGeoRefExtent->rect->miny;
-            newGeoRefExtent.maxy =  newGeoRefExtent.miny + dfDeltaY;
-        }
-        if (newGeoRefExtent.maxy > php_maxGeoRefExtent->rect->maxy)
-        {
-            newGeoRefExtent.maxy = php_maxGeoRefExtent->rect->maxy;
-            newGeoRefExtent.miny = newGeoRefExtent.maxy - dfDeltaY;
-        }
-    }
-
-    php_map->map->extent.minx = newGeoRefExtent.minx;
-    php_map->map->extent.miny = newGeoRefExtent.miny;
-    php_map->map->extent.maxx = newGeoRefExtent.maxx;
-    php_map->map->extent.maxy = newGeoRefExtent.maxy;
-
-    php_map->map->cellsize = msAdjustExtent(&(php_map->map->extent), php_map->map->width, 
-                                    php_map->map->height);    
-    dfDeltaX = php_map->map->extent.maxx - php_map->map->extent.minx;
-    dfDeltaY = php_map->map->extent.maxy - php_map->map->extent.miny; 
-
-    if (zmaxGeoRefExtent)
-    {
-        if (php_map->map->extent.minx < php_maxGeoRefExtent->rect->minx)
-        {
-            php_map->map->extent.minx = php_maxGeoRefExtent->rect->minx;
-            php_map->map->extent.maxx = php_map->map->extent.minx + dfDeltaX;
-        }
-        if (php_map->map->extent.maxx > php_maxGeoRefExtent->rect->maxx)
-        {
-            php_map->map->extent.maxx = php_maxGeoRefExtent->rect->maxx;
-            newGeoRefExtent.minx = newGeoRefExtent.maxx - dfDeltaX;
-        }
-        if (php_map->map->extent.miny < php_maxGeoRefExtent->rect->miny)
-        {
-            php_map->map->extent.miny = php_maxGeoRefExtent->rect->miny;
-            php_map->map->extent.maxy =  php_map->map->extent.miny + dfDeltaY;
-        }
-        if (php_map->map->extent.maxy > php_maxGeoRefExtent->rect->maxy)
-        {
-            php_map->map->extent.maxy = php_maxGeoRefExtent->rect->maxy;
-            newGeoRefExtent.miny = newGeoRefExtent.maxy - dfDeltaY;
-        }
-    }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_pixelExtent = (php_rect_object *) zend_object_store_get_object(zpixelExtent TSRMLS_CC);
+  php_geoRefExtent = (php_rect_object *) zend_object_store_get_object(zgeoRefExtent TSRMLS_CC);
+  if (zmaxGeoRefExtent)
+    php_maxGeoRefExtent = (php_rect_object *) zend_object_store_get_object(zmaxGeoRefExtent TSRMLS_CC);
+
+
+  /* -------------------------------------------------------------------- */
+  /*      check the validity of the parameters.                           */
+  /* -------------------------------------------------------------------- */
+  if (width <= 0 ||
+      height <= 0 ||
+      php_geoRefExtent->rect == NULL ||
+      php_pixelExtent->rect == NULL ||
+      (zmaxGeoRefExtent && php_maxGeoRefExtent->rect == NULL)) {
+    mapscript_throw_mapserver_exception("Incorrect parameters\n" TSRMLS_CC);
+    return;
+  }
 
-    if (msCalculateScale(php_map->map->extent, php_map->map->units, php_map->map->width, php_map->map->height, 
-                         php_map->map->resolution, &(php_map->map->scaledenom)) != MS_SUCCESS)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
+  /* -------------------------------------------------------------------- */
+  /*      check if the values passed are consistent min > max.            */
+  /* -------------------------------------------------------------------- */
+  if (php_geoRefExtent->rect->minx >= php_geoRefExtent->rect->maxx) {
+    mapscript_throw_mapserver_exception("Georeferenced coordinates minx >= maxx\n" TSRMLS_CC);
+    return;
+  }
+  if (php_geoRefExtent->rect->miny >= php_geoRefExtent->rect->maxy) {
+    mapscript_throw_mapserver_exception("Georeferenced coordinates miny >= maxy\n" TSRMLS_CC);
+    return;
+  }
+  if (zmaxGeoRefExtent) {
+    if (php_maxGeoRefExtent->rect->minx >= php_maxGeoRefExtent->rect->maxx) {
+      mapscript_throw_mapserver_exception("Max Georeferenced coordinates minx >= maxx\n" TSRMLS_CC);
+      return;
+    }
+    if (php_maxGeoRefExtent->rect->miny >= php_maxGeoRefExtent->rect->maxy) {
+      mapscript_throw_mapserver_exception("Max Georeferenced coordinates miny >= maxy\n" TSRMLS_CC);
+      return;
+    }
+  }
+
+
+  newGeoRefExtent.minx = Pix2Georef((int)php_pixelExtent->rect->minx, 0,
+                                    width,
+                                    php_geoRefExtent->rect->minx, php_geoRefExtent->rect->maxx, 0);
+  newGeoRefExtent.maxx = Pix2Georef((int)php_pixelExtent->rect->maxx, 0,
+                                    width,
+                                    php_geoRefExtent->rect->minx, php_geoRefExtent->rect->maxx, 0);
+  newGeoRefExtent.miny = Pix2Georef((int)php_pixelExtent->rect->miny, 0,
+                                    height,
+                                    php_geoRefExtent->rect->miny, php_geoRefExtent->rect->maxy, 1);
+  newGeoRefExtent.maxy = Pix2Georef((int)php_pixelExtent->rect->maxy, 0,
+                                    height,
+                                    php_geoRefExtent->rect->miny, php_geoRefExtent->rect->maxy, 1);
+
+  msAdjustExtent(&newGeoRefExtent, php_map->map->width, php_map->map->height);
+
+  /* -------------------------------------------------------------------- */
+  /*      if the min and max scale are set in the map file, we will       */
+  /*      use them to test before setting extents.                        */
+  /* -------------------------------------------------------------------- */
+  if (msCalculateScale(newGeoRefExtent, php_map->map->units,
+                       php_map->map->width, php_map->map->height,
+                       php_map->map->resolution, &dfNewScale) != MS_SUCCESS) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
+
+  if (php_map->map->web.maxscaledenom > 0 &&  dfNewScale > php_map->map->web.maxscaledenom) {
+    RETURN_LONG(MS_FAILURE);
+  }
+
+  if (php_map->map->web.minscaledenom > 0 && dfNewScale <  php_map->map->web.minscaledenom) {
+    dfMiddleX = newGeoRefExtent.minx +
+                ((newGeoRefExtent.maxx - newGeoRefExtent.minx)/2);
+    dfMiddleY = newGeoRefExtent.miny +
+                ((newGeoRefExtent.maxy - newGeoRefExtent.miny)/2);
+
+    dfDeltaExt =
+      GetDeltaExtentsUsingScale(php_map->map->web.minscaledenom, php_map->map->units,
+                                dfMiddleY, php_map->map->width,
+                                php_map->map->resolution);
+
+    if (dfDeltaExt > 0.0) {
+      newGeoRefExtent.minx = dfMiddleX - (dfDeltaExt/2);
+      newGeoRefExtent.miny = dfMiddleY - (dfDeltaExt/2);
+      newGeoRefExtent.maxx = dfMiddleX + (dfDeltaExt/2);
+      newGeoRefExtent.maxy = dfMiddleY + (dfDeltaExt/2);
+    } else
+      RETURN_LONG(MS_FAILURE);
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      If the buffer is set, make sure that the extents do not go      */
+  /*      beyond the buffer.                                              */
+  /* -------------------------------------------------------------------- */
+  if (zmaxGeoRefExtent) {
+    dfDeltaX = newGeoRefExtent.maxx - newGeoRefExtent.minx;
+    dfDeltaY = newGeoRefExtent.maxy - newGeoRefExtent.miny;
+
+    /* Make sure Current georef extents is not bigger than max extents */
+    if (dfDeltaX > (php_maxGeoRefExtent->rect->maxx-php_maxGeoRefExtent->rect->minx))
+      dfDeltaX = php_maxGeoRefExtent->rect->maxx-php_maxGeoRefExtent->rect->minx;
+    if (dfDeltaY > (php_maxGeoRefExtent->rect->maxy-php_maxGeoRefExtent->rect->miny))
+      dfDeltaY = php_maxGeoRefExtent->rect->maxy-php_maxGeoRefExtent->rect->miny;
+
+    if (newGeoRefExtent.minx < php_maxGeoRefExtent->rect->minx) {
+      newGeoRefExtent.minx = php_maxGeoRefExtent->rect->minx;
+      newGeoRefExtent.maxx =  newGeoRefExtent.minx + dfDeltaX;
+    }
+    if (newGeoRefExtent.maxx > php_maxGeoRefExtent->rect->maxx) {
+      newGeoRefExtent.maxx = php_maxGeoRefExtent->rect->maxx;
+      newGeoRefExtent.minx = newGeoRefExtent.maxx - dfDeltaX;
+    }
+    if (newGeoRefExtent.miny < php_maxGeoRefExtent->rect->miny) {
+      newGeoRefExtent.miny = php_maxGeoRefExtent->rect->miny;
+      newGeoRefExtent.maxy =  newGeoRefExtent.miny + dfDeltaY;
+    }
+    if (newGeoRefExtent.maxy > php_maxGeoRefExtent->rect->maxy) {
+      newGeoRefExtent.maxy = php_maxGeoRefExtent->rect->maxy;
+      newGeoRefExtent.miny = newGeoRefExtent.maxy - dfDeltaY;
+    }
+  }
+
+  php_map->map->extent.minx = newGeoRefExtent.minx;
+  php_map->map->extent.miny = newGeoRefExtent.miny;
+  php_map->map->extent.maxx = newGeoRefExtent.maxx;
+  php_map->map->extent.maxy = newGeoRefExtent.maxy;
+
+  php_map->map->cellsize = msAdjustExtent(&(php_map->map->extent), php_map->map->width,
+                                          php_map->map->height);
+  dfDeltaX = php_map->map->extent.maxx - php_map->map->extent.minx;
+  dfDeltaY = php_map->map->extent.maxy - php_map->map->extent.miny;
+
+  if (zmaxGeoRefExtent) {
+    if (php_map->map->extent.minx < php_maxGeoRefExtent->rect->minx) {
+      php_map->map->extent.minx = php_maxGeoRefExtent->rect->minx;
+      php_map->map->extent.maxx = php_map->map->extent.minx + dfDeltaX;
+    }
+    if (php_map->map->extent.maxx > php_maxGeoRefExtent->rect->maxx) {
+      php_map->map->extent.maxx = php_maxGeoRefExtent->rect->maxx;
+      newGeoRefExtent.minx = newGeoRefExtent.maxx - dfDeltaX;
+    }
+    if (php_map->map->extent.miny < php_maxGeoRefExtent->rect->miny) {
+      php_map->map->extent.miny = php_maxGeoRefExtent->rect->miny;
+      php_map->map->extent.maxy =  php_map->map->extent.miny + dfDeltaY;
+    }
+    if (php_map->map->extent.maxy > php_maxGeoRefExtent->rect->maxy) {
+      php_map->map->extent.maxy = php_maxGeoRefExtent->rect->maxy;
+      newGeoRefExtent.miny = newGeoRefExtent.maxy - dfDeltaY;
+    }
+  }
+
+  if (msCalculateScale(php_map->map->extent, php_map->map->units, php_map->map->width, php_map->map->height,
+                       php_map->map->resolution, &(php_map->map->scaledenom)) != MS_SUCCESS) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
 
-    RETURN_LONG(MS_SUCCESS);
+  RETURN_LONG(MS_SUCCESS);
 }
 /* }}} */
 
-/* {{{ proto int zoomScale(int scaleDenom, pointObj pixelPosition, int width, int height, 
+/* {{{ proto int zoomScale(int scaleDenom, pointObj pixelPosition, int width, int height,
                            rectObj geoRefExtent, [rectObj mapGeoRefExtent])
    Zoom to a given XY postion. */
 PHP_METHOD(mapObj, zoomScale)
 {
-    zval *zobj = getThis();
-    zval *zpoint, *zgeoRefExtent, *zmaxGeoRefExtent = NULL;
-    long width, height;
-    double scaleDenom;
-    double      dfGeoPosX, dfGeoPosY;
-    double      dfDeltaX, dfDeltaY;
-    double      dfCurrentScale = 0.0;
-    rectObj     newGeoRefExtent;    
-    double      dfNewScale = 0.0;
-    double      dfDeltaExt = -1.0;
-    int         tmp = 0;
-    php_point_object *php_pixelPosition;
-    php_rect_object *php_geoRefExtent, *php_maxGeoRefExtent;
-    php_map_object *php_map;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "dOllO|O",
-                              &scaleDenom,
-                              &zpoint, mapscript_ce_point,
-                              &width, &height,
-                              &zgeoRefExtent , mapscript_ce_rect,
-                              &zmaxGeoRefExtent , mapscript_ce_rect) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-return;
-    }
-PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_pixelPosition = (php_point_object *) zend_object_store_get_object(zpoint TSRMLS_CC);
-    php_geoRefExtent = (php_rect_object *) zend_object_store_get_object(zgeoRefExtent TSRMLS_CC);
-    if (zmaxGeoRefExtent)
-        php_maxGeoRefExtent = (php_rect_object *) zend_object_store_get_object(zmaxGeoRefExtent TSRMLS_CC);
-
-/* -------------------------------------------------------------------- */
-/*      check the validity of the parameters.                           */
-/* -------------------------------------------------------------------- */
-    if (scaleDenom <= 0.0 || 
-        width <= 0 ||
-        height <= 0 ||
-        php_geoRefExtent->rect == NULL ||
-        php_pixelPosition->point == NULL ||
-        (zmaxGeoRefExtent && php_maxGeoRefExtent->rect == NULL))
-    {
-        mapscript_throw_mapserver_exception("Incorrect parameters\n" TSRMLS_CC);
-        return;
-    }
-
-/* -------------------------------------------------------------------- */
-/*      check if the values passed are consistent min > max.             */
-/* -------------------------------------------------------------------- */
-    if (php_geoRefExtent->rect->minx >= php_geoRefExtent->rect->maxx)
-    {
-        mapscript_throw_mapserver_exception("Georeferenced coordinates minx >= maxx\n" TSRMLS_CC);
-        return;
-    }
-    if (php_geoRefExtent->rect->miny >= php_geoRefExtent->rect->maxy)
-    {
-        mapscript_throw_mapserver_exception("Georeferenced coordinates miny >= maxy\n" TSRMLS_CC);
-        return;
-    }
-    if (zmaxGeoRefExtent)
-    {
-        if (php_maxGeoRefExtent->rect->minx >= php_maxGeoRefExtent->rect->maxx)
-        {
-            mapscript_throw_mapserver_exception("Max Georeferenced coordinates minx >= maxx\n" TSRMLS_CC);
-            return;
-        }
-        if (php_maxGeoRefExtent->rect->miny >= php_maxGeoRefExtent->rect->maxy)
-        {
-            mapscript_throw_mapserver_exception("Max Georeferenced coordinates miny >= maxy\n" TSRMLS_CC);
-            return;
-        }
-    }
-    
-
-    dfGeoPosX = Pix2Georef((int)php_pixelPosition->point->x, 0, width, 
-                           php_geoRefExtent->rect->minx, php_geoRefExtent->rect->maxx, 0); 
-    dfGeoPosY = Pix2Georef((int)php_pixelPosition->point->y, 0, height, 
-                           php_geoRefExtent->rect->miny, php_geoRefExtent->rect->maxy, 1); 
-    dfDeltaX = php_geoRefExtent->rect->maxx - php_geoRefExtent->rect->minx;
-    dfDeltaY = php_geoRefExtent->rect->maxy - php_geoRefExtent->rect->miny;
-
-   
-/* -------------------------------------------------------------------- */
-/*      Calculate new extents based on the sacle.                       */
-/* -------------------------------------------------------------------- */
-
-/* ==================================================================== */
-/*      make sure to take the smallest size because this is the one     */
-/*      that will be used to ajust the scale.                           */
-/* ==================================================================== */
-
-    if (php_map->map->width <  php_map->map->height)
-      tmp = php_map->map->width;
-    else
-      tmp = php_map->map->height;
-
-    dfDeltaExt = 
-        GetDeltaExtentsUsingScale(scaleDenom, php_map->map->units, dfGeoPosY,
-                                  tmp, php_map->map->resolution);
-                                  
-    if (dfDeltaExt > 0.0)
-    {
-        newGeoRefExtent.minx = dfGeoPosX - (dfDeltaExt/2);
-        newGeoRefExtent.miny = dfGeoPosY - (dfDeltaExt/2);
-        newGeoRefExtent.maxx = dfGeoPosX + (dfDeltaExt/2);
-        newGeoRefExtent.maxy = dfGeoPosY + (dfDeltaExt/2);
-    }
-    else
-        RETURN_LONG(MS_FAILURE);
-
-/* -------------------------------------------------------------------- */
-/*      get current scale.                                              */
-/* -------------------------------------------------------------------- */
-    if (msCalculateScale(*php_geoRefExtent->rect, php_map->map->units, 
-                         php_map->map->width, php_map->map->height,
-                         php_map->map->resolution, &dfCurrentScale) != MS_SUCCESS)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
-
-/* -------------------------------------------------------------------- */
-/*      if the min and max scale are set in the map file, we will       */
-/*      use them to test before zooming.                                */
-/*                                                                      */
-/*       This function has the same effect as zoomin or zoom out. If    */
-/*      the current scale is > newscale we zoom in; else it is a        */
-/*      zoom out.                                                       */
-/* -------------------------------------------------------------------- */
-    msAdjustExtent(&newGeoRefExtent, php_map->map->width, php_map->map->height);
-    if (msCalculateScale(newGeoRefExtent, php_map->map->units, 
-                         php_map->map->width, php_map->map->height,
-                         php_map->map->resolution, &dfNewScale) != MS_SUCCESS)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
-
-    if (php_map->map->web.maxscaledenom > 0)
-    {
-        if (dfCurrentScale < dfNewScale && dfNewScale >  php_map->map->web.maxscaledenom)
-        {
-            RETURN_LONG(MS_FAILURE);
-        }
-    }
+  zval *zobj = getThis();
+  zval *zpoint, *zgeoRefExtent, *zmaxGeoRefExtent = NULL;
+  long width, height;
+  double scaleDenom;
+  double      dfGeoPosX, dfGeoPosY;
+  double      dfDeltaX, dfDeltaY;
+  double      dfCurrentScale = 0.0;
+  rectObj     newGeoRefExtent;
+  double      dfNewScale = 0.0;
+  double      dfDeltaExt = -1.0;
+  int         tmp = 0;
+  php_point_object *php_pixelPosition;
+  php_rect_object *php_geoRefExtent=NULL, *php_maxGeoRefExtent=NULL;
+  php_map_object *php_map;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "dOllO|O",
+                            &scaleDenom,
+                            &zpoint, mapscript_ce_point,
+                            &width, &height,
+                            &zgeoRefExtent , mapscript_ce_rect,
+                            &zmaxGeoRefExtent , mapscript_ce_rect) == FAILURE) {
+    PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_pixelPosition = (php_point_object *) zend_object_store_get_object(zpoint TSRMLS_CC);
+  php_geoRefExtent = (php_rect_object *) zend_object_store_get_object(zgeoRefExtent TSRMLS_CC);
+  if (zmaxGeoRefExtent)
+    php_maxGeoRefExtent = (php_rect_object *) zend_object_store_get_object(zmaxGeoRefExtent TSRMLS_CC);
+
+  /* -------------------------------------------------------------------- */
+  /*      check the validity of the parameters.                           */
+  /* -------------------------------------------------------------------- */
+  if (scaleDenom <= 0.0 ||
+      width <= 0 ||
+      height <= 0 ||
+      php_geoRefExtent->rect == NULL ||
+      php_pixelPosition->point == NULL ||
+      (zmaxGeoRefExtent && php_maxGeoRefExtent->rect == NULL)) {
+    mapscript_throw_mapserver_exception("Incorrect parameters\n" TSRMLS_CC);
+    return;
+  }
 
-/* ==================================================================== */
-/*      we do a special case for zoom in : we try to zoom as much as    */
-/*      possible using the mincale set in the .map.                     */
-/* ==================================================================== */
-    if (php_map->map->web.minscaledenom > 0 && dfNewScale <  php_map->map->web.minscaledenom &&
-        dfCurrentScale > dfNewScale)
-    {
-        dfDeltaExt = 
-            GetDeltaExtentsUsingScale(php_map->map->web.minscaledenom, php_map->map->units, 
-                                      dfGeoPosY, php_map->map->width, 
-                                      php_map->map->resolution);
-        if (dfDeltaExt > 0.0)
-        {
-            newGeoRefExtent.minx = dfGeoPosX - (dfDeltaExt/2);
-            newGeoRefExtent.miny = dfGeoPosY - (dfDeltaExt/2);
-            newGeoRefExtent.maxx = dfGeoPosX + (dfDeltaExt/2);
-            newGeoRefExtent.maxy = dfGeoPosY + (dfDeltaExt/2);
-        }
-        else
-            RETURN_LONG(MS_FAILURE);
-    }
-/* -------------------------------------------------------------------- */
-/*      If the buffer is set, make sure that the extents do not go      */
-/*      beyond the buffer.                                              */
-/* -------------------------------------------------------------------- */
-    if (zmaxGeoRefExtent)
-    {
-        dfDeltaX = newGeoRefExtent.maxx - newGeoRefExtent.minx;
-        dfDeltaY = newGeoRefExtent.maxy - newGeoRefExtent.miny;
-        
-        /* Make sure Current georef extents is not bigger than max extents */
-        if (dfDeltaX > (php_maxGeoRefExtent->rect->maxx-php_maxGeoRefExtent->rect->minx))
-            dfDeltaX = php_maxGeoRefExtent->rect->maxx-php_maxGeoRefExtent->rect->minx;
-        if (dfDeltaY > (php_maxGeoRefExtent->rect->maxy-php_maxGeoRefExtent->rect->miny))
-            dfDeltaY = php_maxGeoRefExtent->rect->maxy-php_maxGeoRefExtent->rect->miny;
-
-        if (newGeoRefExtent.minx < php_maxGeoRefExtent->rect->minx)
-        {
-            newGeoRefExtent.minx = php_maxGeoRefExtent->rect->minx;
-            newGeoRefExtent.maxx =  newGeoRefExtent.minx + dfDeltaX;
-        }
-        if (newGeoRefExtent.maxx > php_maxGeoRefExtent->rect->maxx)
-        {
-            newGeoRefExtent.maxx = php_maxGeoRefExtent->rect->maxx;
-            newGeoRefExtent.minx = newGeoRefExtent.maxx - dfDeltaX;
-        }
-        if (newGeoRefExtent.miny < php_maxGeoRefExtent->rect->miny)
-        {
-            newGeoRefExtent.miny = php_maxGeoRefExtent->rect->miny;
-            newGeoRefExtent.maxy =  newGeoRefExtent.miny + dfDeltaY;
-        }
-        if (newGeoRefExtent.maxy > php_maxGeoRefExtent->rect->maxy)
-        {
-            newGeoRefExtent.maxy = php_maxGeoRefExtent->rect->maxy;
-            newGeoRefExtent.miny = newGeoRefExtent.maxy - dfDeltaY;
-        }
-    }
-    
-/* -------------------------------------------------------------------- */
-/*      set the map extents with new values.                            */
-/* -------------------------------------------------------------------- */
-    php_map->map->extent.minx = newGeoRefExtent.minx;
-    php_map->map->extent.miny = newGeoRefExtent.miny;
-    php_map->map->extent.maxx = newGeoRefExtent.maxx;
-    php_map->map->extent.maxy = newGeoRefExtent.maxy;
-    
-
-    php_map->map->cellsize = msAdjustExtent(&(php_map->map->extent), php_map->map->width, 
-                                    php_map->map->height);      
-    dfDeltaX = php_map->map->extent.maxx - php_map->map->extent.minx;
-    dfDeltaY = php_map->map->extent.maxy - php_map->map->extent.miny; 
-    
-    if (zmaxGeoRefExtent)
-    {
-        if (php_map->map->extent.minx < php_maxGeoRefExtent->rect->minx)
-        {
-            php_map->map->extent.minx = php_maxGeoRefExtent->rect->minx;
-            php_map->map->extent.maxx = php_map->map->extent.minx + dfDeltaX;
-        }
-        if (php_map->map->extent.maxx > php_maxGeoRefExtent->rect->maxx)
-        {
-            php_map->map->extent.maxx = php_maxGeoRefExtent->rect->maxx;
-            newGeoRefExtent.minx = newGeoRefExtent.maxx - dfDeltaX;
-        }
-        if (php_map->map->extent.miny < php_maxGeoRefExtent->rect->miny)
-        {
-            php_map->map->extent.miny = php_maxGeoRefExtent->rect->miny;
-            php_map->map->extent.maxy =  php_map->map->extent.miny + dfDeltaY;
-        }
-        if (php_map->map->extent.maxy > php_maxGeoRefExtent->rect->maxy)
-        {
-            php_map->map->extent.maxy = php_maxGeoRefExtent->rect->maxy;
-            newGeoRefExtent.miny = newGeoRefExtent.maxy - dfDeltaY;
-        }
-    }
-    
-    if (msCalculateScale(php_map->map->extent, php_map->map->units, php_map->map->width, php_map->map->height, 
-                         php_map->map->resolution, &(php_map->map->scaledenom)) != MS_SUCCESS)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
+  /* -------------------------------------------------------------------- */
+  /*      check if the values passed are consistent min > max.             */
+  /* -------------------------------------------------------------------- */
+  if (php_geoRefExtent->rect->minx >= php_geoRefExtent->rect->maxx) {
+    mapscript_throw_mapserver_exception("Georeferenced coordinates minx >= maxx\n" TSRMLS_CC);
+    return;
+  }
+  if (php_geoRefExtent->rect->miny >= php_geoRefExtent->rect->maxy) {
+    mapscript_throw_mapserver_exception("Georeferenced coordinates miny >= maxy\n" TSRMLS_CC);
+    return;
+  }
+  if (zmaxGeoRefExtent) {
+    if (php_maxGeoRefExtent->rect->minx >= php_maxGeoRefExtent->rect->maxx) {
+      mapscript_throw_mapserver_exception("Max Georeferenced coordinates minx >= maxx\n" TSRMLS_CC);
+      return;
+    }
+    if (php_maxGeoRefExtent->rect->miny >= php_maxGeoRefExtent->rect->maxy) {
+      mapscript_throw_mapserver_exception("Max Georeferenced coordinates miny >= maxy\n" TSRMLS_CC);
+      return;
+    }
+  }
+
+
+  dfGeoPosX = Pix2Georef((int)php_pixelPosition->point->x, 0, width,
+                         php_geoRefExtent->rect->minx, php_geoRefExtent->rect->maxx, 0);
+  dfGeoPosY = Pix2Georef((int)php_pixelPosition->point->y, 0, height,
+                         php_geoRefExtent->rect->miny, php_geoRefExtent->rect->maxy, 1);
+  dfDeltaX = php_geoRefExtent->rect->maxx - php_geoRefExtent->rect->minx;
+  dfDeltaY = php_geoRefExtent->rect->maxy - php_geoRefExtent->rect->miny;
+
+
+  /* -------------------------------------------------------------------- */
+  /*      Calculate new extents based on the sacle.                       */
+  /* -------------------------------------------------------------------- */
+
+  /* ==================================================================== */
+  /*      make sure to take the smallest size because this is the one     */
+  /*      that will be used to ajust the scale.                           */
+  /* ==================================================================== */
+
+  if (php_map->map->width <  php_map->map->height)
+    tmp = php_map->map->width;
+  else
+    tmp = php_map->map->height;
+
+  dfDeltaExt =
+    GetDeltaExtentsUsingScale(scaleDenom, php_map->map->units, dfGeoPosY,
+                              tmp, php_map->map->resolution);
+
+  if (dfDeltaExt > 0.0) {
+    newGeoRefExtent.minx = dfGeoPosX - (dfDeltaExt/2);
+    newGeoRefExtent.miny = dfGeoPosY - (dfDeltaExt/2);
+    newGeoRefExtent.maxx = dfGeoPosX + (dfDeltaExt/2);
+    newGeoRefExtent.maxy = dfGeoPosY + (dfDeltaExt/2);
+  } else
+    RETURN_LONG(MS_FAILURE);
+
+  /* -------------------------------------------------------------------- */
+  /*      get current scale.                                              */
+  /* -------------------------------------------------------------------- */
+  if (msCalculateScale(*php_geoRefExtent->rect, php_map->map->units,
+                       php_map->map->width, php_map->map->height,
+                       php_map->map->resolution, &dfCurrentScale) != MS_SUCCESS) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      if the min and max scale are set in the map file, we will       */
+  /*      use them to test before zooming.                                */
+  /*                                                                      */
+  /*       This function has the same effect as zoomin or zoom out. If    */
+  /*      the current scale is > newscale we zoom in; else it is a        */
+  /*      zoom out.                                                       */
+  /* -------------------------------------------------------------------- */
+  msAdjustExtent(&newGeoRefExtent, php_map->map->width, php_map->map->height);
+  if (msCalculateScale(newGeoRefExtent, php_map->map->units,
+                       php_map->map->width, php_map->map->height,
+                       php_map->map->resolution, &dfNewScale) != MS_SUCCESS) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
+
+  if (php_map->map->web.maxscaledenom > 0) {
+    if (dfCurrentScale < dfNewScale && dfNewScale >  php_map->map->web.maxscaledenom) {
+      RETURN_LONG(MS_FAILURE);
+    }
+  }
+
+  /* ==================================================================== */
+  /*      we do a special case for zoom in : we try to zoom as much as    */
+  /*      possible using the mincale set in the .map.                     */
+  /* ==================================================================== */
+  if (php_map->map->web.minscaledenom > 0 && dfNewScale <  php_map->map->web.minscaledenom &&
+      dfCurrentScale > dfNewScale) {
+    dfDeltaExt =
+      GetDeltaExtentsUsingScale(php_map->map->web.minscaledenom, php_map->map->units,
+                                dfGeoPosY, php_map->map->width,
+                                php_map->map->resolution);
+    if (dfDeltaExt > 0.0) {
+      newGeoRefExtent.minx = dfGeoPosX - (dfDeltaExt/2);
+      newGeoRefExtent.miny = dfGeoPosY - (dfDeltaExt/2);
+      newGeoRefExtent.maxx = dfGeoPosX + (dfDeltaExt/2);
+      newGeoRefExtent.maxy = dfGeoPosY + (dfDeltaExt/2);
+    } else
+      RETURN_LONG(MS_FAILURE);
+  }
+  /* -------------------------------------------------------------------- */
+  /*      If the buffer is set, make sure that the extents do not go      */
+  /*      beyond the buffer.                                              */
+  /* -------------------------------------------------------------------- */
+  if (zmaxGeoRefExtent) {
+    dfDeltaX = newGeoRefExtent.maxx - newGeoRefExtent.minx;
+    dfDeltaY = newGeoRefExtent.maxy - newGeoRefExtent.miny;
+
+    /* Make sure Current georef extents is not bigger than max extents */
+    if (dfDeltaX > (php_maxGeoRefExtent->rect->maxx-php_maxGeoRefExtent->rect->minx))
+      dfDeltaX = php_maxGeoRefExtent->rect->maxx-php_maxGeoRefExtent->rect->minx;
+    if (dfDeltaY > (php_maxGeoRefExtent->rect->maxy-php_maxGeoRefExtent->rect->miny))
+      dfDeltaY = php_maxGeoRefExtent->rect->maxy-php_maxGeoRefExtent->rect->miny;
+
+    if (newGeoRefExtent.minx < php_maxGeoRefExtent->rect->minx) {
+      newGeoRefExtent.minx = php_maxGeoRefExtent->rect->minx;
+      newGeoRefExtent.maxx =  newGeoRefExtent.minx + dfDeltaX;
+    }
+    if (newGeoRefExtent.maxx > php_maxGeoRefExtent->rect->maxx) {
+      newGeoRefExtent.maxx = php_maxGeoRefExtent->rect->maxx;
+      newGeoRefExtent.minx = newGeoRefExtent.maxx - dfDeltaX;
+    }
+    if (newGeoRefExtent.miny < php_maxGeoRefExtent->rect->miny) {
+      newGeoRefExtent.miny = php_maxGeoRefExtent->rect->miny;
+      newGeoRefExtent.maxy =  newGeoRefExtent.miny + dfDeltaY;
+    }
+    if (newGeoRefExtent.maxy > php_maxGeoRefExtent->rect->maxy) {
+      newGeoRefExtent.maxy = php_maxGeoRefExtent->rect->maxy;
+      newGeoRefExtent.miny = newGeoRefExtent.maxy - dfDeltaY;
+    }
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      set the map extents with new values.                            */
+  /* -------------------------------------------------------------------- */
+  php_map->map->extent.minx = newGeoRefExtent.minx;
+  php_map->map->extent.miny = newGeoRefExtent.miny;
+  php_map->map->extent.maxx = newGeoRefExtent.maxx;
+  php_map->map->extent.maxy = newGeoRefExtent.maxy;
+
+
+  php_map->map->cellsize = msAdjustExtent(&(php_map->map->extent), php_map->map->width,
+                                          php_map->map->height);
+  dfDeltaX = php_map->map->extent.maxx - php_map->map->extent.minx;
+  dfDeltaY = php_map->map->extent.maxy - php_map->map->extent.miny;
+
+  if (zmaxGeoRefExtent) {
+    if (php_map->map->extent.minx < php_maxGeoRefExtent->rect->minx) {
+      php_map->map->extent.minx = php_maxGeoRefExtent->rect->minx;
+      php_map->map->extent.maxx = php_map->map->extent.minx + dfDeltaX;
+    }
+    if (php_map->map->extent.maxx > php_maxGeoRefExtent->rect->maxx) {
+      php_map->map->extent.maxx = php_maxGeoRefExtent->rect->maxx;
+      newGeoRefExtent.minx = newGeoRefExtent.maxx - dfDeltaX;
+    }
+    if (php_map->map->extent.miny < php_maxGeoRefExtent->rect->miny) {
+      php_map->map->extent.miny = php_maxGeoRefExtent->rect->miny;
+      php_map->map->extent.maxy =  php_map->map->extent.miny + dfDeltaY;
+    }
+    if (php_map->map->extent.maxy > php_maxGeoRefExtent->rect->maxy) {
+      php_map->map->extent.maxy = php_maxGeoRefExtent->rect->maxy;
+      newGeoRefExtent.miny = newGeoRefExtent.maxy - dfDeltaY;
+    }
+  }
+
+  if (msCalculateScale(php_map->map->extent, php_map->map->units, php_map->map->width, php_map->map->height,
+                       php_map->map->resolution, &(php_map->map->scaledenom)) != MS_SUCCESS) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
 
-    RETURN_LONG(MS_SUCCESS);
+  RETURN_LONG(MS_SUCCESS);
 }
 /* }}} */
 
@@ -1816,8 +1741,8 @@ PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
  *                        map->queryByPoint()
  *
  * Type is MS_SINGLE or MS_MULTIPLE depending on number of results
- * you want. Passing buffer <=0 defaults to tolerances set in the map 
- * file (in pixels) but you can use a constant buffer (specified in 
+ * you want. Passing buffer <=0 defaults to tolerances set in the map
+ * file (in pixels) but you can use a constant buffer (specified in
  * ground units) instead.
  **********************************************************************/
 
@@ -1825,63 +1750,61 @@ PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
    Query at point location. */
 PHP_METHOD(mapObj, queryByPoint)
 {
-    zval *zobj = getThis();
-    zval *zpoint;
-    long mode;
-    double buffer;
-    int status = MS_FAILURE;
-    php_point_object *php_point;
-    php_map_object *php_map;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Old",
-                              &zpoint, mapscript_ce_point,
-                              &mode, &buffer) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
-PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_point = (php_point_object *) zend_object_store_get_object(zpoint TSRMLS_CC);
-    
-    status = mapObj_queryByPoint(php_map->map, php_point->point, mode, buffer);
-    if (status != MS_SUCCESS)
-    {
-        mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
-    }
+  zval *zobj = getThis();
+  zval *zpoint;
+  long mode;
+  double buffer;
+  int status = MS_FAILURE;
+  php_point_object *php_point;
+  php_map_object *php_map;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Old",
+                            &zpoint, mapscript_ce_point,
+                            &mode, &buffer) == FAILURE) {
+    PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    RETURN_LONG(status);
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_point = (php_point_object *) zend_object_store_get_object(zpoint TSRMLS_CC);
+
+  status = mapObj_queryByPoint(php_map->map, php_point->point, mode, buffer);
+  if (status != MS_SUCCESS) {
+    mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
+  }
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
 /* {{{ proto int map.queryByRect(rectObj rect) */
 PHP_METHOD(mapObj, queryByRect)
 {
-    zval *zobj = getThis();
-    zval *zrect;
-    int status = MS_FAILURE;
-    php_rect_object *php_rect;
-    php_map_object *php_map;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
-                              &zrect, mapscript_ce_rect) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  zval *zrect;
+  int status = MS_FAILURE;
+  php_rect_object *php_rect;
+  php_map_object *php_map;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
+                            &zrect, mapscript_ce_rect) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_rect = (php_rect_object *) zend_object_store_get_object(zrect TSRMLS_CC);
-    
-    status = mapObj_queryByRect(php_map->map, *(php_rect->rect));
-    if (status != MS_SUCCESS)
-    {
-        mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
-    }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_rect = (php_rect_object *) zend_object_store_get_object(zrect TSRMLS_CC);
+
+  status = mapObj_queryByRect(php_map->map, *(php_rect->rect));
+  if (status != MS_SUCCESS) {
+    mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
+  }
 
-    RETURN_LONG(status);
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -1895,58 +1818,56 @@ PHP_METHOD(mapObj, queryByRect)
 /* {{{ proto int map.queryByShape(shapeObj poShape) */
 PHP_METHOD(mapObj, queryByShape)
 {
-    zval *zobj = getThis();
-    zval *zshape;
-    int status = MS_FAILURE;
-    php_shape_object *php_shape;
-    php_map_object *php_map;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
-                              &zshape, mapscript_ce_shape) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  zval *zshape;
+  int status = MS_FAILURE;
+  php_shape_object *php_shape;
+  php_map_object *php_map;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
+                            &zshape, mapscript_ce_shape) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_shape = (php_shape_object *) zend_object_store_get_object(zshape TSRMLS_CC);
-    
-    status = mapObj_queryByShape(php_map->map, php_shape->shape);
-    if (status != MS_SUCCESS)
-    {
-        mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
-    }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    RETURN_LONG(status);
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_shape = (php_shape_object *) zend_object_store_get_object(zshape TSRMLS_CC);
+
+  status = mapObj_queryByShape(php_map->map, php_shape->shape);
+  if (status != MS_SUCCESS) {
+    mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
+  }
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
 /* {{{ proto int map.queryByFeatures(int slayer) */
 PHP_METHOD(mapObj, queryByFeatures)
 {
-    zval *zobj = getThis();
-    long slayer;
-    int status = MS_FAILURE;
-    php_map_object *php_map;
+  zval *zobj = getThis();
+  long slayer;
+  int status = MS_FAILURE;
+  php_map_object *php_map;
 
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
-                              &slayer) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
+                            &slayer) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    status = mapObj_queryByFeatures(php_map->map, slayer);
-    if (status != MS_SUCCESS)
-    {
-        mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
-    }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  status = mapObj_queryByFeatures(php_map->map, slayer);
+  if (status != MS_SUCCESS) {
+    mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
+  }
 
-    RETURN_LONG(status);
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -1955,118 +1876,173 @@ PHP_METHOD(mapObj, queryByFeatures)
  *
  *
  * Add a shape into the query result on a specific layer.
- * if bAddtoQuery (not mandatory) isset to true, the sahpe will be added to 
- * the existing query result. Else the query result is cleared before adding 
+ * if bAddtoQuery (not mandatory) isset to true, the sahpe will be added to
+ * the existing query result. Else the query result is cleared before adding
  * the sahpe (which is the default behavior).
  **********************************************************************/
-/* {{{ proto int map.queryByIndex(int layerIndex, int tileIndex, 
+/* {{{ proto int map.queryByIndex(int layerIndex, int tileIndex,
                                   int shapeIndex, int addToQuery) */
 PHP_METHOD(mapObj, queryByIndex)
 {
-    zval *zobj = getThis();
-    long layerIndex, tileIndex, shapeIndex, addToQuery = MS_FALSE;
-    int status = MS_FAILURE;
-    php_map_object *php_map;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "lll|l",
-                              &layerIndex, &tileIndex, 
-                              &shapeIndex, &addToQuery) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
-PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    status = mapObj_queryByIndex(php_map->map, layerIndex,
-                                 tileIndex, 
-                                 shapeIndex,
-                                 addToQuery);
-    if (status != MS_SUCCESS)
-    {
-        mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
-    }
+  zval *zobj = getThis();
+  long layerIndex, tileIndex, shapeIndex, addToQuery = MS_FALSE;
+  int status = MS_FAILURE;
+  php_map_object *php_map;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "lll|l",
+                            &layerIndex, &tileIndex,
+                            &shapeIndex, &addToQuery) == FAILURE) {
+    PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  status = mapObj_queryByIndex(php_map->map, layerIndex,
+                               tileIndex,
+                               shapeIndex,
+                               addToQuery);
+  if (status != MS_SUCCESS) {
+    mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
+  }
+
+  RETURN_LONG(status);
+}
+/* }}} */
+
+/* {{{ proto int map.queryByFilter(char string) */
+PHP_METHOD(mapObj, queryByFilter)
+{
+  zval *zobj = getThis();
+  char *string;
+  long string_len;
+  int status = MS_FAILURE;
+  php_map_object *php_map;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &string, &string_len) == FAILURE) {
+    PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    RETURN_LONG(status);
+  status = mapObj_queryByFilter(php_map->map, string);
+  if (status != MS_SUCCESS) {
+    mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
+  }
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
-/* {{{ proto int map.savequery(string filename, int results) 
+/* {{{ proto int map.savequery(string filename, int results)
    Save the current query to a specfied file. Can be used with loadquery */
 PHP_METHOD(mapObj, saveQuery)
 {
-    zval *zobj = getThis();
-    char *filename;
-    long filename_len;
-    int results = MS_FALSE;
-    int status = MS_FAILURE;
-    php_map_object *php_map;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l",
-                              &filename, &filename_len, &results) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  char *filename;
+  long filename_len;
+  int results = MS_FALSE;
+  int status = MS_FAILURE;
+  php_map_object *php_map;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l",
+                            &filename, &filename_len, &results) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    status = mapObj_saveQuery(php_map->map, filename, results);    
+  status = mapObj_saveQuery(php_map->map, filename, results);
 
-    RETURN_LONG(status);
+  RETURN_LONG(status);
 }
 /* }}} */
 
-/* {{{ proto int map.loadquery(filename) 
+/* {{{ proto int map.savequeryasgml(string filename, string namespace)
+   Save the current query to a specfied file as GML. */
+PHP_METHOD(mapObj, saveQueryAsGML)
+{
+  zval *zobj = getThis();
+  char *filename;
+  long filename_len;
+  char *namespace = "GOMF";
+  long namespace_len;
+  int status = MS_FAILURE;
+  php_map_object *php_map;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s",
+                            &filename, &filename_len, &namespace, &namespace_len) == FAILURE) {
+    PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  status = msGMLWriteQuery(php_map->map, filename, namespace);
+
+  RETURN_LONG(status);
+}
+/* }}} */
+
+/* {{{ proto int map.loadquery(filename)
    Load the query from a specfied file. Used with savequery */
 PHP_METHOD(mapObj, loadQuery)
 {
-    zval *zobj = getThis();
-    char *filename;
-    long filename_len;
-    int status = MS_FAILURE;
-    php_map_object *php_map;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &filename, &filename_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  char *filename;
+  long filename_len;
+  int status = MS_FAILURE;
+  php_map_object *php_map;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &filename, &filename_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    status = mapObj_loadQuery(php_map->map, filename);    
+  status = mapObj_loadQuery(php_map->map, filename);
 
-    RETURN_LONG(status);
+  RETURN_LONG(status);
 }
 /* }}} */
 
-/* {{{ proto int map->freeQuery(int qlayer) 
+/* {{{ proto int map->freeQuery(int qlayer)
    Free the query on a specified layer. If qlayer is set to -1
    all queries on all layers will be freed. */
 PHP_METHOD(mapObj, freeQuery)
 {
-    zval *zobj = getThis();
-    long qlayer;
-    php_map_object *php_map;
+  zval *zobj = getThis();
+  long qlayer;
+  php_map_object *php_map;
 
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
-                              &qlayer) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
+                            &qlayer) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    mapObj_freeQuery(php_map->map, qlayer);    
+  mapObj_freeQuery(php_map->map, qlayer);
 
-    RETURN_LONG(MS_SUCCESS);
+  RETURN_LONG(MS_SUCCESS);
 }
 /* }}} */
 
@@ -2074,30 +2050,29 @@ PHP_METHOD(mapObj, freeQuery)
    Write map object to a file. */
 PHP_METHOD(mapObj, save)
 {
-    zval *zobj = getThis();
-    char *filename;
-    long filename_len;
-    int status = MS_FAILURE;
-    php_map_object *php_map;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &filename, &filename_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  char *filename;
+  long filename_len;
+  int status = MS_FAILURE;
+  php_map_object *php_map;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &filename, &filename_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    status = mapObj_save(php_map->map, filename); 
-    if (status != MS_SUCCESS)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    RETURN_LONG(status);
+  status = mapObj_save(php_map->map, filename);
+  if (status != MS_SUCCESS) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -2106,26 +2081,26 @@ PHP_METHOD(mapObj, save)
    Set projection and coord. system for the map. */
 PHP_METHOD(mapObj, setProjection)
 {
-    zval *zobj = getThis();
-    char *projection;
-    long projection_len;
-    int status = MS_FAILURE;
-    long setUnitsAndExtents = MS_FALSE;
-    php_map_object *php_map;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l",
-                              &projection, &projection_len, &setUnitsAndExtents) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  char *projection;
+  long projection_len;
+  int status = MS_FAILURE;
+  long setUnitsAndExtents = MS_FALSE;
+  php_map_object *php_map;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l",
+                            &projection, &projection_len, &setUnitsAndExtents) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    status = mapscript_map_setProjection(MS_FALSE, php_map, 
-                                         projection, setUnitsAndExtents TSRMLS_CC);
-    RETURN_LONG(status);
+  status = mapscript_map_setProjection(MS_FALSE, php_map,
+                                       projection, setUnitsAndExtents TSRMLS_CC);
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -2133,27 +2108,26 @@ PHP_METHOD(mapObj, setProjection)
     Return the projection string of the layer. Returns NULL on error. */
 PHP_METHOD(mapObj, getProjection)
 {
-    zval *zobj = getThis();
-    char *projection = NULL;
-    php_map_object *php_map;
+  zval *zobj = getThis();
+  char *projection = NULL;
+  php_map_object *php_map;
 
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    projection = mapObj_getProjection(php_map->map);
-    if (projection == NULL)
-    {
-        RETURN_NULL();
-    }
-    
-    RETVAL_STRING(projection, 1);
-    free(projection);
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  projection = mapObj_getProjection(php_map->map);
+  if (projection == NULL) {
+    RETURN_NULL();
+  }
+
+  RETVAL_STRING(projection, 1);
+  free(projection);
 }
 /* }}} */
 
@@ -2161,26 +2135,26 @@ PHP_METHOD(mapObj, getProjection)
    Set projection and coord. system for the map. Returns MS_FAILURE on error. */
 PHP_METHOD(mapObj, setWKTProjection)
 {
-    zval *zobj = getThis();
-    char *projection;
-    long projection_len;
-    int status = MS_FAILURE;
-    long setUnitsAndExtents = MS_FALSE;
-    php_map_object *php_map;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l",
-                              &projection, &projection_len, &setUnitsAndExtents) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  char *projection;
+  long projection_len;
+  int status = MS_FAILURE;
+  long setUnitsAndExtents = MS_FALSE;
+  php_map_object *php_map;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l",
+                            &projection, &projection_len, &setUnitsAndExtents) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    status = mapscript_map_setProjection(MS_TRUE, php_map, 
-                                         projection, setUnitsAndExtents TSRMLS_CC);
-    RETURN_LONG(status);
+  status = mapscript_map_setProjection(MS_TRUE, php_map,
+                                       projection, setUnitsAndExtents TSRMLS_CC);
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -2188,25 +2162,25 @@ PHP_METHOD(mapObj, setWKTProjection)
    Return MetaData entry by name, or empty string if not found. */
 PHP_METHOD(mapObj, getMetaData)
 {
-    zval *zname;
-    zval *zobj = getThis();
-    php_map_object *php_map;
-    zval *retval;
+  zval *zname;
+  zval *zobj = getThis();
+  php_map_object *php_map;
+  zval *retval;
 
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z",
-                              &zname) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z",
+                            &zname) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    CHECK_OBJECT(mapscript_ce_hashtable, php_map->metadata, &php_map->map->web.metadata);
-    
-    MAPSCRIPT_CALL_METHOD_1(php_map->metadata, "get", retval, zname); 
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  CHECK_OBJECT(mapscript_ce_hashtable, php_map->metadata, &php_map->map->web.metadata);
 
-    RETURN_STRING(Z_STRVAL_P(retval),1);
+  MAPSCRIPT_CALL_METHOD_1(php_map->metadata, "get", retval, zname);
+
+  RETURN_STRING(Z_STRVAL_P(retval),1);
 }
 /* }}} */
 
@@ -2214,25 +2188,25 @@ PHP_METHOD(mapObj, getMetaData)
    Set MetaData entry by name.  Returns MS_SUCCESS/MS_FAILURE */
 PHP_METHOD(mapObj, setMetaData)
 {
-    zval *zname, *zvalue;
-    zval *zobj = getThis();
-    php_map_object *php_map;
-    zval *retval;
+  zval *zname, *zvalue;
+  zval *zobj = getThis();
+  php_map_object *php_map;
+  zval *retval;
 
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz",
-                              &zname, &zvalue) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz",
+                            &zname, &zvalue) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    CHECK_OBJECT(mapscript_ce_hashtable, php_map->metadata, &php_map->map->web.metadata);
-    
-    MAPSCRIPT_CALL_METHOD_2(php_map->metadata, "set", retval, zname, zvalue);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  CHECK_OBJECT(mapscript_ce_hashtable, php_map->metadata, &php_map->map->web.metadata);
+
+  MAPSCRIPT_CALL_METHOD_2(php_map->metadata, "set", retval, zname, zvalue);
 
-    RETURN_LONG(Z_LVAL_P(retval));
+  RETURN_LONG(Z_LVAL_P(retval));
 }
 /* }}} */
 
@@ -2240,25 +2214,25 @@ PHP_METHOD(mapObj, setMetaData)
    Remove MetaData entry by name.  Returns MS_SUCCESS/MS_FAILURE */
 PHP_METHOD(mapObj, removeMetaData)
 {
-    zval *zname;
-    zval *zobj = getThis();
-    php_map_object *php_map;
-    zval *retval;
+  zval *zname;
+  zval *zobj = getThis();
+  php_map_object *php_map;
+  zval *retval;
 
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z",
-                              &zname) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z",
+                            &zname) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    CHECK_OBJECT(mapscript_ce_hashtable, php_map->metadata, &php_map->map->web.metadata);
-    
-    MAPSCRIPT_CALL_METHOD_1(php_map->metadata, "remove", retval, zname); 
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  CHECK_OBJECT(mapscript_ce_hashtable, php_map->metadata, &php_map->map->web.metadata);
 
-    RETURN_LONG(Z_LVAL_P(retval));
+  MAPSCRIPT_CALL_METHOD_1(php_map->metadata, "remove", retval, zname);
+
+  RETURN_LONG(Z_LVAL_P(retval));
 }
 /* }}} */
 
@@ -2266,35 +2240,33 @@ PHP_METHOD(mapObj, removeMetaData)
    Return an array of layer's index given a group name. */
 PHP_METHOD(mapObj, getLayersIndexByGroup)
 {
-    zval *zobj = getThis();
-    char *groupName;
-    long groupName_len;
-    int *indexes = NULL;
-    int count = 0;
-    int i;
-    php_map_object *php_map;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &groupName, &groupName_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  char *groupName;
+  long groupName_len;
+  int *indexes = NULL;
+  int count = 0;
+  int i;
+  php_map_object *php_map;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &groupName, &groupName_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    array_init(return_value);
-    indexes = mapObj_getLayersIndexByGroup(php_map->map, groupName, &count);
-    
-    if (indexes && count > 0)
-    {
-        for (i=0; i<count; i++)
-        {
-            add_next_index_long(return_value, indexes[i]);
-        }
-        free (indexes);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  array_init(return_value);
+  indexes = mapObj_getLayersIndexByGroup(php_map->map, groupName, &count);
+
+  if (indexes && count > 0) {
+    for (i=0; i<count; i++) {
+      add_next_index_long(return_value, indexes[i]);
     }
+    free (indexes);
+  }
 }
 /* }}} */
 
@@ -2302,33 +2274,31 @@ PHP_METHOD(mapObj, getLayersIndexByGroup)
    Return an array containing all the group names.*/
 PHP_METHOD(mapObj, getAllGroupNames)
 {
-    zval *zobj = getThis();
-    int i, numTok;
-    char **groups = NULL;
-    php_map_object *php_map;
+  zval *zobj = getThis();
+  int i, numTok;
+  char **groups = NULL;
+  php_map_object *php_map;
 
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    array_init(return_value);
-    if (php_map->map->numlayers > 0)
-    {
-        groups = msGetAllGroupNames(php_map->map, &numTok);
-       
-        for (i=0; i<numTok; i++)
-        {
-            /* add a copy of the group name to the PHP array */
-            add_next_index_string(return_value, groups[i], 1);   
-            free(groups[i]);
-        }
-        free(groups);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  array_init(return_value);
+  if (php_map->map->numlayers > 0) {
+    groups = msGetAllGroupNames(php_map->map, &numTok);
+
+    for (i=0; i<numTok; i++) {
+      /* add a copy of the group name to the PHP array */
+      add_next_index_string(return_value, groups[i], 1);
+      free(groups[i]);
     }
+    free(groups);
+  }
 }
 /* }}} */
 
@@ -2336,26 +2306,25 @@ PHP_METHOD(mapObj, getAllGroupNames)
    Return an array conating all the layers name.*/
 PHP_METHOD(mapObj, getAllLayerNames)
 {
-    zval *zobj = getThis();
-    int count = 0;
-    int i;
-    php_map_object *php_map;
+  zval *zobj = getThis();
+  int count = 0;
+  int i;
+  php_map_object *php_map;
 
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    array_init(return_value);
-    count = php_map->map->numlayers;
-    for (i=0; i<count; i++)
-    {
-        add_next_index_string(return_value,  php_map->map->layers[i]->name, 1);
-    }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  array_init(return_value);
+  count = php_map->map->numlayers;
+  for (i=0; i<count; i++) {
+    add_next_index_string(return_value,  php_map->map->layers[i]->name, 1);
+  }
 }
 /* }}} */
 
@@ -2363,24 +2332,24 @@ PHP_METHOD(mapObj, getAllLayerNames)
    Returns MS_SUCCESS/MS_FAILURE. */
 PHP_METHOD(mapObj, moveLayerUp)
 {
-    zval *zobj = getThis();
-    long index;
-    int status = MS_FAILURE;
-    php_map_object *php_map;
+  zval *zobj = getThis();
+  long index;
+  int status = MS_FAILURE;
+  php_map_object *php_map;
 
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
-                              &index) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
+                            &index) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    status = mapObj_moveLayerup(php_map->map, index);
-    
-    RETURN_LONG(status);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  status = mapObj_moveLayerup(php_map->map, index);
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -2388,24 +2357,24 @@ PHP_METHOD(mapObj, moveLayerUp)
    Returns MS_SUCCESS/MS_FAILURE. */
 PHP_METHOD(mapObj, moveLayerDown)
 {
-    zval *zobj = getThis();
-    long index;
-    int status = MS_FAILURE;
-    php_map_object *php_map;
+  zval *zobj = getThis();
+  long index;
+  int status = MS_FAILURE;
+  php_map_object *php_map;
 
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
-                              &index) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
+                            &index) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    status = mapObj_moveLayerdown(php_map->map, index);
-    
-    RETURN_LONG(status);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  status = mapObj_moveLayerdown(php_map->map, index);
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -2414,48 +2383,45 @@ PHP_METHOD(mapObj, moveLayerDown)
    Note : the first element in the array is the one drawn first.*/
 PHP_METHOD(mapObj, getLayersDrawingOrder)
 {
-    zval *zobj = getThis();
-    int count = 0;
-    int i;
-    int *layerIndexes = NULL;
-    php_map_object *php_map;
+  zval *zobj = getThis();
+  int count = 0;
+  int i;
+  int *layerIndexes = NULL;
+  php_map_object *php_map;
 
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    array_init(return_value);
-
-    layerIndexes = mapObj_getLayersdrawingOrder(php_map->map);
-    count = php_map->map->numlayers;
-
-/* -------------------------------------------------------------------- */
-/*      Go through the prioriy list and return the layers index. If     */
-/*      the priority list is not set, it will return the layer          */
-/*      indexs as they were at the load time.                           */
-/* -------------------------------------------------------------------- */
-    for (i=0; i<count; i++)
-    {
-        if (layerIndexes)
-        {
-            add_next_index_long(return_value,  layerIndexes[i]);
-        }
-        else
-            add_next_index_long(return_value, i);
-    }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  array_init(return_value);
+
+  layerIndexes = mapObj_getLayersdrawingOrder(php_map->map);
+  count = php_map->map->numlayers;
+
+  /* -------------------------------------------------------------------- */
+  /*      Go through the prioriy list and return the layers index. If     */
+  /*      the priority list is not set, it will return the layer          */
+  /*      indexs as they were at the load time.                           */
+  /* -------------------------------------------------------------------- */
+  for (i=0; i<count; i++) {
+    if (layerIndexes) {
+      add_next_index_long(return_value,  layerIndexes[i]);
+    } else
+      add_next_index_long(return_value, i);
+  }
 }
 /* }}} */
 
 /* {{{ proto int map.setLayersDrawingOrder(array_layer_index)
-   Set the array used for the drawing order. 
+   Set the array used for the drawing order.
    array_layers_index : an array containing all the layer's index ordered
                         by the drawing priority.
-                        Ex : for 3 layers in the map file, if 
+                        Ex : for 3 layers in the map file, if
                             array[0] = 2
                             array[1] = 0
                             array[2] = 1
@@ -2465,327 +2431,301 @@ PHP_METHOD(mapObj, getLayersDrawingOrder)
    Note : the first element in the array is the one drawn first.*/
 PHP_METHOD(mapObj, setLayersDrawingOrder)
 {
-    zval *zobj = getThis();
-    zval *zindexes, **ppzval;
-    HashTable *indexes_hash = NULL;
-    int    *indexes = NULL;
-    int numElements = 0;
-    int i = 0;
-    php_map_object *php_map;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a",
-                              &zindexes) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
-    PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);    
-    indexes_hash = Z_ARRVAL_P(zindexes);
-
-    numElements = zend_hash_num_elements(indexes_hash);
-
-/* -------------------------------------------------------------------- */
-/*      validate that the array of index given has the same size as     */
-/*      the number of layers and also the the indexs are valid.         */
-/* -------------------------------------------------------------------- */
-   if (php_map->map->numlayers != numElements)
-    {
-        RETURN_LONG(MS_FAILURE);
-    }
-    indexes = (int*)malloc(sizeof(int)*numElements);
-
-    for(zend_hash_internal_pointer_reset(indexes_hash); 
-        zend_hash_has_more_elements(indexes_hash) == SUCCESS; 
-        zend_hash_move_forward(indexes_hash), ++i)
-    {     
-        zend_hash_get_current_data(indexes_hash, (void **)&ppzval);
-        indexes[i] = Z_LVAL_PP(ppzval);
-    }
+  zval *zobj = getThis();
+  zval *zindexes, **ppzval;
+  HashTable *indexes_hash = NULL;
+  int    *indexes = NULL;
+  int numElements = 0;
+  int i = 0;
+  php_map_object *php_map;
 
-    if (!mapObj_setLayersdrawingOrder(php_map->map, indexes))
-    {
-        free(indexes);
-        RETURN_LONG(MS_FAILURE);
-    }
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a",
+                            &zindexes) == FAILURE) {
+    PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  indexes_hash = Z_ARRVAL_P(zindexes);
+
+  numElements = zend_hash_num_elements(indexes_hash);
+
+  /* -------------------------------------------------------------------- */
+  /*      validate that the array of index given has the same size as     */
+  /*      the number of layers and also the the indexs are valid.         */
+  /* -------------------------------------------------------------------- */
+  if (php_map->map->numlayers != numElements) {
+    RETURN_LONG(MS_FAILURE);
+  }
+  indexes = (int*)malloc(sizeof(int)*numElements);
+
+  for(zend_hash_internal_pointer_reset(indexes_hash);
+      zend_hash_has_more_elements(indexes_hash) == SUCCESS;
+      zend_hash_move_forward(indexes_hash), ++i) {
+    zend_hash_get_current_data(indexes_hash, (void **)&ppzval);
+    indexes[i] = Z_LVAL_PP(ppzval);
+  }
+
+  if (!mapObj_setLayersdrawingOrder(php_map->map, indexes)) {
     free(indexes);
+    RETURN_LONG(MS_FAILURE);
+  }
+  free(indexes);
 
-    RETURN_LONG(MS_SUCCESS);
+  RETURN_LONG(MS_SUCCESS);
 }
 /* }}} */
 
 /* {{{ proto int map.processTemplate(array params, int generateImages)*/
 PHP_METHOD(mapObj, processTemplate)
 {
-    zval *zobj = getThis();
-    zval *zindexes;
-    HashTable *indexes_hash = NULL;
-    long generateImages;
-    char *buffer = NULL;
-    int index = 0;
-    int numElements = 0;
-    int i, size;
-    char        **papszNameValue = NULL;
-    char        **papszName = NULL;
-    char        **papszValue = NULL;
-    php_map_object *php_map;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "al",
-                              &zindexes, &generateImages) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  zval *zindexes;
+  HashTable *indexes_hash = NULL;
+  long generateImages;
+  char *buffer = NULL;
+  int index = 0;
+  int numElements = 0;
+  int i, size;
+  char        **papszNameValue = NULL;
+  char        **papszName = NULL;
+  char        **papszValue = NULL;
+  php_map_object *php_map;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "al",
+                            &zindexes, &generateImages) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);    
-    indexes_hash = Z_ARRVAL_P(zindexes);
-
-    /**
-     * Allocate 2 times the number of elements in
-     * the array, since with associative arrays in PHP
-     * keys are not counted.
-     */
-    
-    numElements = zend_hash_num_elements(indexes_hash);
-    size = (numElements * 2 + 1) * sizeof(char *);
-    
-    papszNameValue = (char **)emalloc(size+1);
-    memset((char *)papszNameValue, 0, size);
-
-    if (mapscript_extract_associative_array(indexes_hash, papszNameValue))
-    {
-        papszName = (char **)malloc(sizeof(char *)*numElements);
-        papszValue = (char **)malloc(sizeof(char *)*numElements);
-            
-        for (i=0; i<numElements; i++)
-        {
-            index = i*2;
-            papszName[i] = papszNameValue[index];
-            papszValue[i] = papszNameValue[index+1];
-        }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  indexes_hash = Z_ARRVAL_P(zindexes);
+
+  /**
+   * Allocate 2 times the number of elements in
+   * the array, since with associative arrays in PHP
+   * keys are not counted.
+   */
+
+  numElements = zend_hash_num_elements(indexes_hash);
+  size = (numElements * 2 + 1) * sizeof(char *);
+
+  papszNameValue = (char **)emalloc(size+1);
+  memset((char *)papszNameValue, 0, size);
+
+  if (mapscript_extract_associative_array(indexes_hash, papszNameValue)) {
+    papszName = (char **)malloc(sizeof(char *)*numElements);
+    papszValue = (char **)malloc(sizeof(char *)*numElements);
+
+    for (i=0; i<numElements; i++) {
+      index = i*2;
+      papszName[i] = papszNameValue[index];
+      papszValue[i] = papszNameValue[index+1];
     }
-    else
-    {
-        // Failed for some reason
-        mapscript_report_php_error(E_WARNING, "processTemplate: failed reading array" TSRMLS_CC);
-        RETURN_STRING("", 1);
-    }
-    efree(papszNameValue);
-
-    buffer = mapObj_processTemplate(php_map->map, generateImages,
-                                    papszName, papszValue, numElements);
-            
-    msFree(papszName);  // The strings inside the array are just refs
-    msFree(papszValue);
-
-    if (buffer)
-    {
-        RETVAL_STRING(buffer, 1);
-        free(buffer);
-    }
-    else
-    {
-        mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
-        RETURN_STRING("", 1);
-    }
+
+  } else {
+    // Failed for some reason
+    mapscript_report_php_error(E_WARNING, "processTemplate: failed reading array" TSRMLS_CC);
+    RETURN_STRING("", 1);
+  }
+  efree(papszNameValue);
+
+  buffer = mapObj_processTemplate(php_map->map, generateImages,
+                                  papszName, papszValue, numElements);
+
+  msFree(papszName);  // The strings inside the array are just refs
+  msFree(papszValue);
+
+  if (buffer) {
+    RETVAL_STRING(buffer, 1);
+    free(buffer);
+  } else {
+    mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
+    RETURN_STRING("", 1);
+  }
 }
 /* }}} */
 
 /* {{{ proto int map.processQueryTemplate(array params, int generateImages)*/
 PHP_METHOD(mapObj, processQueryTemplate)
 {
-    zval *zobj = getThis();
-    zval *zindexes;
-    HashTable *indexes_hash = NULL;
-    long generateImages = MS_TRUE;
-    char *buffer = NULL;
-    int index = 0;
-    int numElements = 0;
-    int i, size;
-    char        **papszNameValue = NULL;
-    char        **papszName = NULL;
-    char        **papszValue = NULL;
-    php_map_object *php_map;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|l",
-                              &zindexes, &generateImages) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  zval *zindexes;
+  HashTable *indexes_hash = NULL;
+  long generateImages = MS_TRUE;
+  char *buffer = NULL;
+  int index = 0;
+  int numElements = 0;
+  int i, size;
+  char        **papszNameValue = NULL;
+  char        **papszName = NULL;
+  char        **papszValue = NULL;
+  php_map_object *php_map;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|l",
+                            &zindexes, &generateImages) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);    
-    indexes_hash = Z_ARRVAL_P(zindexes);
-
-    /**
-     * Allocate 2 times the number of elements in
-     * the array, since with associative arrays in PHP
-     * keys are not counted.
-     */
-    
-    numElements = zend_hash_num_elements(indexes_hash);
-    size = (numElements * 2 + 1) * sizeof(char *);
-    
-    papszNameValue = (char **)emalloc(size+1);
-    memset((char *)papszNameValue, 0, size);
-        
-    if (mapscript_extract_associative_array(indexes_hash, papszNameValue))
-    {
-        papszName = (char **)malloc(sizeof(char *)*numElements);
-        papszValue = (char **)malloc(sizeof(char *)*numElements);
-            
-            
-        for (i=0; i<numElements; i++)
-        {
-            index = i*2;
-            papszName[i] = papszNameValue[index];
-            papszValue[i] = papszNameValue[index+1];
-        }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    }
-    else
-    {
-        // Failed for some reason
-        mapscript_report_php_error(E_WARNING, "processQueryTemplate: failed reading array" TSRMLS_CC);
-        RETURN_STRING("", 1);
-    }
-    efree(papszNameValue);
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  indexes_hash = Z_ARRVAL_P(zindexes);
 
+  /**
+   * Allocate 2 times the number of elements in
+   * the array, since with associative arrays in PHP
+   * keys are not counted.
+   */
 
-    buffer = mapObj_processQueryTemplate(php_map->map, generateImages,
-                                         papszName, papszValue, numElements);
-            
-    msFree(papszName);  // The strings inside the array are just refs
-    msFree(papszValue);
+  numElements = zend_hash_num_elements(indexes_hash);
+  size = (numElements * 2 + 1) * sizeof(char *);
 
-    if (buffer)
-    {
-        RETVAL_STRING(buffer, 1);
-        free(buffer);
-    }
-    else
-    {
-        mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
-        RETURN_STRING("", 1);
+  papszNameValue = (char **)emalloc(size+1);
+  memset((char *)papszNameValue, 0, size);
+
+  if (mapscript_extract_associative_array(indexes_hash, papszNameValue)) {
+    papszName = (char **)malloc(sizeof(char *)*numElements);
+    papszValue = (char **)malloc(sizeof(char *)*numElements);
+
+
+    for (i=0; i<numElements; i++) {
+      index = i*2;
+      papszName[i] = papszNameValue[index];
+      papszValue[i] = papszNameValue[index+1];
     }
+
+  } else {
+    // Failed for some reason
+    mapscript_report_php_error(E_WARNING, "processQueryTemplate: failed reading array" TSRMLS_CC);
+    RETURN_STRING("", 1);
+  }
+  efree(papszNameValue);
+
+
+  buffer = mapObj_processQueryTemplate(php_map->map, generateImages,
+                                       papszName, papszValue, numElements);
+
+  msFree(papszName);  // The strings inside the array are just refs
+  msFree(papszValue);
+
+  if (buffer) {
+    RETVAL_STRING(buffer, 1);
+    free(buffer);
+  } else {
+    mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
+    RETURN_STRING("", 1);
+  }
 }
 /* }}} */
 
 /* {{{ proto int map.processLegendTemplate(array params)*/
 PHP_METHOD(mapObj, processLegendTemplate)
 {
-    zval *zobj = getThis();
-    zval *zindexes;
-    HashTable *indexes_hash = NULL;
-    char *buffer = NULL;
-    int index = 0;
-    int numElements = 0;
-    int i, size;
-    char        **papszNameValue = NULL;
-    char        **papszName = NULL;
-    char        **papszValue = NULL;
-    php_map_object *php_map;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a",
-                              &zindexes) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  zval *zindexes;
+  HashTable *indexes_hash = NULL;
+  char *buffer = NULL;
+  int index = 0;
+  int numElements = 0;
+  int i, size;
+  char        **papszNameValue = NULL;
+  char        **papszName = NULL;
+  char        **papszValue = NULL;
+  php_map_object *php_map;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a",
+                            &zindexes) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);    
-    indexes_hash = Z_ARRVAL_P(zindexes);
-
-    /**
-     * Allocate 2 times the number of elements in
-     * the array, since with associative arrays in PHP
-     * keys are not counted.
-     */
-    
-    numElements = zend_hash_num_elements(indexes_hash);
-    size = (numElements * 2 + 1) * sizeof(char *);
-    
-    papszNameValue = (char **)emalloc(size+1);
-    memset((char *)papszNameValue, 0, size);
-        
-    if (mapscript_extract_associative_array(indexes_hash, papszNameValue))
-    {
-        papszName = (char **)malloc(sizeof(char *)*numElements);
-        papszValue = (char **)malloc(sizeof(char *)*numElements);
-            
-            
-        for (i=0; i<numElements; i++)
-        {
-            index = i*2;
-            papszName[i] = papszNameValue[index];
-            papszValue[i] = papszNameValue[index+1];
-        }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    }
-    else
-    {
-        // Failed for some reason
-        mapscript_report_php_error(E_WARNING, "processLegendTemplate: failed reading array" TSRMLS_CC);
-        RETURN_STRING("", 1);
-    }
-    efree(papszNameValue);
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  indexes_hash = Z_ARRVAL_P(zindexes);
 
+  /**
+   * Allocate 2 times the number of elements in
+   * the array, since with associative arrays in PHP
+   * keys are not counted.
+   */
 
-    buffer = mapObj_processLegendTemplate(php_map->map, papszName, 
-                                          papszValue, numElements);
-            
-    msFree(papszName);  // The strings inside the array are just refs
-    msFree(papszValue);
+  numElements = zend_hash_num_elements(indexes_hash);
+  size = (numElements * 2 + 1) * sizeof(char *);
 
-    if (buffer)
-    {
-        RETVAL_STRING(buffer, 1);
-        free(buffer);
-    }
-    else
-    {
-        mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
-        RETURN_STRING("", 1);
+  papszNameValue = (char **)emalloc(size+1);
+  memset((char *)papszNameValue, 0, size);
+
+  if (mapscript_extract_associative_array(indexes_hash, papszNameValue)) {
+    papszName = (char **)malloc(sizeof(char *)*numElements);
+    papszValue = (char **)malloc(sizeof(char *)*numElements);
+
+
+    for (i=0; i<numElements; i++) {
+      index = i*2;
+      papszName[i] = papszNameValue[index];
+      papszValue[i] = papszNameValue[index+1];
     }
+
+  } else {
+    // Failed for some reason
+    mapscript_report_php_error(E_WARNING, "processLegendTemplate: failed reading array" TSRMLS_CC);
+    RETURN_STRING("", 1);
+  }
+  efree(papszNameValue);
+
+
+  buffer = mapObj_processLegendTemplate(php_map->map, papszName,
+                                        papszValue, numElements);
+
+  msFree(papszName);  // The strings inside the array are just refs
+  msFree(papszValue);
+
+  if (buffer) {
+    RETVAL_STRING(buffer, 1);
+    free(buffer);
+  } else {
+    mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
+    RETURN_STRING("", 1);
+  }
 }
 /* }}} */
 
 /* {{{ proto int map.setSymbolSet(fileName)*/
 PHP_METHOD(mapObj, setSymbolSet)
 {
-    zval *zobj = getThis();
-    char *filename;
-    long filename_len;
-    int status = MS_FAILURE;
-    php_map_object *php_map;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &filename, &filename_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  char *filename;
+  long filename_len;
+  int status = MS_FAILURE;
+  php_map_object *php_map;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &filename, &filename_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    if(filename_len > 0)
-    {
-        if ((status = mapObj_setSymbolSet(php_map->map, 
-                                          filename)) != 0)
-        {
-            mapscript_throw_mapserver_exception("Failed loading symbolset from %s" TSRMLS_CC,
-                                                filename);
-            return;
-        }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  if(filename_len > 0) {
+    if ((status = mapObj_setSymbolSet(php_map->map,
+                                      filename)) != 0) {
+      mapscript_throw_mapserver_exception("Failed loading symbolset from %s" TSRMLS_CC,
+                                          filename);
+      return;
     }
-    
-    RETURN_LONG(status);
+  }
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -2794,53 +2734,51 @@ PHP_METHOD(mapObj, setSymbolSet)
    Returns the number of sumbols from this map. */
 PHP_METHOD(mapObj, getNumSymbols)
 {
-    zval *zobj = getThis();
-    php_map_object *php_map;
+  zval *zobj = getThis();
+  php_map_object *php_map;
 
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    RETURN_LONG(php_map->map->symbolset.numsymbols);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  RETURN_LONG(php_map->map->symbolset.numsymbols);
 }
 /* }}} */
 
 /* {{{ proto int map.setFontName(fileName)*/
 PHP_METHOD(mapObj, setFontSet)
 {
-    zval *zobj = getThis();
-    char *filename;
-    long filename_len;
-    int status = MS_FAILURE;
-    php_map_object *php_map;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &filename, &filename_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  char *filename;
+  long filename_len;
+  int status = MS_FAILURE;
+  php_map_object *php_map;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &filename, &filename_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    if(filename_len > 0)
-    {
-        if ((status = mapObj_setFontSet(php_map->map, 
-                                        filename)) != 0)
-        {
-            mapscript_throw_mapserver_exception("Failed loading fontset from %s" TSRMLS_CC,
-                                                filename);
-            return;
-        }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  if(filename_len > 0) {
+    if ((status = mapObj_setFontSet(php_map->map,
+                                    filename)) != 0) {
+      mapscript_throw_mapserver_exception("Failed loading fontset from %s" TSRMLS_CC,
+                                          filename);
+      return;
     }
-    
-    RETURN_LONG(status);
+  }
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -2848,107 +2786,189 @@ PHP_METHOD(mapObj, setFontSet)
    Selects the output format to be used in the map. Returns MS_SUCCESS/MS_FAILURE. */
 PHP_METHOD(mapObj, selectOutputFormat)
 {
-    zval *zobj = getThis();
-    char *type;
-    long type_len;
-    int status = MS_FAILURE;
-    php_map_object *php_map;
-    php_outputformat_object *php_outputformat;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &type, &type_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  char *type;
+  long type_len;
+  int status = MS_FAILURE;
+  php_map_object *php_map;
+  php_outputformat_object *php_outputformat = NULL;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &type, &type_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    if (php_map->outputformat)
-        php_outputformat = (php_outputformat_object *) zend_object_store_get_object(php_map->outputformat TSRMLS_CC);
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  if (php_map->outputformat)
+    php_outputformat = (php_outputformat_object *) zend_object_store_get_object(php_map->outputformat TSRMLS_CC);
 
-    if ((status = mapObj_selectOutputFormat(php_map->map, 
-                                            type)) != MS_SUCCESS)
+  if ((status = mapObj_selectOutputFormat(php_map->map,
+                                          type)) != MS_SUCCESS)
 
-    {
-        mapscript_report_php_error(E_WARNING, "Unable to set output format to '%s'" TSRMLS_CC, 
-                                   type);
-    }
-    else if (php_map->outputformat)
-    {
-        php_outputformat->outputformat = php_map->map->outputformat;
-    }
+  {
+    mapscript_report_php_error(E_WARNING, "Unable to set output format to '%s'" TSRMLS_CC,
+                               type);
+  } else if (php_map->outputformat) {
+    php_outputformat->outputformat = php_map->map->outputformat;
+  }
+
+  RETURN_LONG(status);
+}
+/* }}} */
+
+/* {{{ proto int appendOutputFormat(outputFormatObj outputformat)
+   Appends outputformat object in the map object. Returns the new numoutputformats value */
+PHP_METHOD(mapObj, appendOutputFormat)
+{
+  zval *zobj = getThis();
+  zval *zoutputformat = NULL;
+  int retval = 0;
+  php_map_object *php_map;
+  php_outputformat_object *php_outputformat;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
+                            &zoutputformat, mapscript_ce_outputformat) == FAILURE) {
+    PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_outputformat = (php_outputformat_object *) zend_object_store_get_object(zoutputformat TSRMLS_CC);
+
+  retval = msAppendOutputFormat(php_map->map, php_outputformat->outputformat);
+
+  RETURN_LONG(retval);
+}
+/* }}} */
+
+/* {{{ proto int removeOutputFormat(string name)
+   Remove outputformat from the map. Returns MS_SUCCESS/MS_FAILURE. */
+PHP_METHOD(mapObj, removeOutputFormat)
+{
+  zval *zobj = getThis();
+  char *name;
+  long name_len;
+  int status = MS_FAILURE;
+  php_map_object *php_map;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &name, &name_len) == FAILURE) {
+    PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  if ((status = msRemoveOutputFormat(php_map->map, name)) != MS_SUCCESS)
+
+  {
+    mapscript_report_php_error(E_WARNING, "Unable to remove output format to '%s'" TSRMLS_CC,
+                               name);
+  }
 
-    RETURN_LONG(status);
+  RETURN_LONG(status);
+}
+/* }}} */
+
+/* {{{ proto int map.getOutputFormat(int index).
+   Return the outputformat at index position. */
+PHP_METHOD(mapObj, getOutputFormat)
+{
+  zval *zobj = getThis();
+  long index = -1;
+  php_map_object *php_map;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
+                            &index) == FAILURE) {
+    PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  if (index < 0 || index >= php_map->map->numoutputformats) {
+    mapscript_throw_mapserver_exception("Invalid outputformat index." TSRMLS_CC);
+    return;
+  }
+
+  MAPSCRIPT_MAKE_PARENT(zobj, NULL);
+  mapscript_create_outputformat(php_map->map->outputformatlist[index],
+                                parent, return_value TSRMLS_CC);
 }
 /* }}} */
 
 /* {{{ proto int map.saveMapContext(fileName) */
 PHP_METHOD(mapObj, saveMapContext)
 {
-    zval *zobj = getThis();
-    char *filename;
-    long filename_len;
-    int status = MS_FAILURE;
-    php_map_object *php_map;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &filename, &filename_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  char *filename;
+  long filename_len;
+  int status = MS_FAILURE;
+  php_map_object *php_map;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &filename, &filename_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    if(filename_len > 0)
-    {
-        if ((status = mapObj_saveMapContext(php_map->map, filename)) != MS_SUCCESS)
-        {
-            mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
-            mapscript_report_php_error(E_WARNING, "Failed saving map context from %s" TSRMLS_CC,
-                                       filename);
-            RETURN_LONG(MS_FAILURE);
-        }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  if(filename_len > 0) {
+    if ((status = mapObj_saveMapContext(php_map->map, filename)) != MS_SUCCESS) {
+      mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
+      mapscript_report_php_error(E_WARNING, "Failed saving map context from %s" TSRMLS_CC,
+                                 filename);
+      RETURN_LONG(MS_FAILURE);
     }
+  }
 
-    RETURN_LONG(status);
+  RETURN_LONG(status);
 }
 /* }}} */
 
 /* {{{ proto int map.loadMapContext(fileName) */
 PHP_METHOD(mapObj, loadMapContext)
 {
-    zval *zobj = getThis();
-    char *filename;
-    long filename_len;
-    long unique = MS_FALSE;
-    int status = MS_FAILURE;
-    php_map_object *php_map;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l",
-                              &filename, &filename_len, &unique) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  char *filename;
+  long filename_len;
+  long unique = MS_FALSE;
+  int status = MS_FAILURE;
+  php_map_object *php_map;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l",
+                            &filename, &filename_len, &unique) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    if(filename_len > 0)
-    {
-        if ((status = mapObj_loadMapContext(php_map->map, filename, unique)) != MS_SUCCESS)
-        {
-            mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
-            mapscript_report_php_error(E_WARNING, "Failed loading map context from %s" TSRMLS_CC,
-                                       filename);
-            RETURN_LONG(MS_FAILURE);
-        }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  if(filename_len > 0) {
+    if ((status = mapObj_loadMapContext(php_map->map, filename, unique)) != MS_SUCCESS) {
+      mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
+      mapscript_report_php_error(E_WARNING, "Failed loading map context from %s" TSRMLS_CC,
+                                 filename);
+      RETURN_LONG(MS_FAILURE);
     }
+  }
 
-    RETURN_LONG(status);
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -2956,25 +2976,25 @@ PHP_METHOD(mapObj, loadMapContext)
    Apply the SLD document to the map file. */
 PHP_METHOD(mapObj, applySLD)
 {
-    zval *zobj = getThis();
-    char *sldxml;
-    long sldxml_len;
-    int status = MS_FAILURE;
-    php_map_object *php_map;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &sldxml, &sldxml_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  char *sldxml;
+  long sldxml_len;
+  int status = MS_FAILURE;
+  php_map_object *php_map;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &sldxml, &sldxml_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    status = mapObj_applySLD(php_map->map, sldxml);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    RETURN_LONG(status);
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  status = mapObj_applySLD(php_map->map, sldxml);
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -2983,25 +3003,25 @@ PHP_METHOD(mapObj, applySLD)
    Apply the SLD document pointed by the URL to the map file. */
 PHP_METHOD(mapObj, applySLDURL)
 {
-    zval *zobj = getThis();
-    char *sldurl;
-    long sldurl_len;
-    int status = MS_FAILURE;
-    php_map_object *php_map;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &sldurl, &sldurl_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  char *sldurl;
+  long sldurl_len;
+  int status = MS_FAILURE;
+  php_map_object *php_map;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &sldurl, &sldurl_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    status = mapObj_applySLDURL(php_map->map, sldurl);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    RETURN_LONG(status);
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  status = mapObj_applySLDURL(php_map->map, sldurl);
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -3009,64 +3029,58 @@ PHP_METHOD(mapObj, applySLDURL)
    Generates an sld based on the map layers/class. */
 PHP_METHOD(mapObj, generateSLD)
 {
-    zval *zobj = getThis();
-    char *buffer = NULL;
-    php_map_object *php_map;
+  zval *zobj = getThis();
+  char *buffer = NULL;
+  php_map_object *php_map;
 
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    buffer = mapObj_generateSLD(php_map->map);
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    if (buffer)
-    {
-        RETVAL_STRING(buffer, 1);
-        free(buffer);
-    }
-    else
-    {
-        mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
-        RETURN_STRING("", 1);
-    }
+  buffer = mapObj_generateSLD(php_map->map);
+
+  if (buffer) {
+    RETVAL_STRING(buffer, 1);
+    free(buffer);
+  } else {
+    mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
+    RETURN_STRING("", 1);
+  }
 }
 /* }}} */
 
 /* {{{ proto string map.getConfigOption(string key)
-      Returns the configuation value associated with the key          
-      passed as argument. Returns an empty string on error.         
+      Returns the configuation value associated with the key
+      passed as argument. Returns an empty string on error.
       prototype : value = $map->getconfigoption(key) */
 PHP_METHOD(mapObj, getConfigOption)
 {
-    zval *zobj = getThis();
-    char *key;
-    long key_len;
-    char *value = NULL;
-    php_map_object *php_map;
-    
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &key, &key_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  char *key;
+  long key_len;
+  char *value = NULL;
+  php_map_object *php_map;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &key, &key_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    if ((value = (char *)msGetConfigOption(php_map->map, key)) == NULL)
-    {
-        RETURN_STRING("", 1);
-    }
-    else
-    {
-        RETURN_STRING(value, 1);
-    }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  if ((value = (char *)msGetConfigOption(php_map->map, key)) == NULL) {
+    RETURN_STRING("", 1);
+  } else {
+    RETURN_STRING(value, 1);
+  }
 }
 /* }}} */
 
@@ -3074,26 +3088,26 @@ PHP_METHOD(mapObj, getConfigOption)
    Sets a config parameter using the key and the value passed. */
 PHP_METHOD(mapObj, setConfigOption)
 {
-    zval *zobj = getThis();
-    char *key;
-    long key_len;
-    char *value;
-    long value_len;
-    php_map_object *php_map;
-    
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss",
-                              &key, &key_len, &value, &value_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  char *key;
+  long key_len;
+  char *value;
+  long value_len;
+  php_map_object *php_map;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss",
+                            &key, &key_len, &value, &value_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    msSetConfigOption(php_map->map, key,value);
-    
-    RETURN_LONG(MS_SUCCESS);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  msSetConfigOption(php_map->map, key,value);
+
+  RETURN_LONG(MS_SUCCESS);
 }
 /* }}} */
 
@@ -3101,20 +3115,20 @@ PHP_METHOD(mapObj, setConfigOption)
    Applies the config options set in the map file. */
 PHP_METHOD(mapObj, applyConfigOptions)
 {
-    zval *zobj = getThis();
-    php_map_object *php_map;
-    
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  php_map_object *php_map;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    msApplyMapConfigOptions(php_map->map);
-    RETURN_LONG(MS_SUCCESS);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  msApplyMapConfigOptions(php_map->map);
+  RETURN_LONG(MS_SUCCESS);
 }
 /* }}} */
 
@@ -3122,39 +3136,38 @@ PHP_METHOD(mapObj, applyConfigOptions)
    Load OWS request parameters (BBOX, LAYERS, &c.) into map. Returns MS_SUCCESS or MS_FAILURE */
 PHP_METHOD(mapObj, loadOwsParameters)
 {
-    zval *zobj = getThis();
-    zval *zrequest;
-    char *version = NULL;
-    long version_len;
-    int isZval = 1;
-    int status = MS_FAILURE;
-    php_owsrequest_object *php_request;
-    php_map_object *php_map;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O|s",
-                              &zrequest, mapscript_ce_owsrequest,
-                              &version, &version_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  zval *zrequest;
+  char *version = NULL;
+  long version_len;
+  int isZval = 1;
+  int status = MS_FAILURE;
+  php_owsrequest_object *php_request;
+  php_map_object *php_map;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O|s",
+                            &zrequest, mapscript_ce_owsrequest,
+                            &version, &version_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_request = (php_owsrequest_object *) zend_object_store_get_object(zrequest TSRMLS_CC);
-    
-    if (!version)
-    {
-        version = strdup("1.1.1");
-        isZval = 0;
-    }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_request = (php_owsrequest_object *) zend_object_store_get_object(zrequest TSRMLS_CC);
+
+  if (!version) {
+    version = strdup("1.1.1");
+    isZval = 0;
+  }
 
-     status = mapObj_loadOWSParameters(php_map->map, php_request->cgirequest, version);
-     
-    if (!isZval)
-        free(version);
+  status = mapObj_loadOWSParameters(php_map->map, php_request->cgirequest, version);
 
-    RETURN_LONG(status);
+  if (!isZval)
+    free(version);
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -3162,26 +3175,26 @@ PHP_METHOD(mapObj, loadOwsParameters)
    Processes and executes the passed OpenGIS Web Services request on the map. */
 PHP_METHOD(mapObj, owsDispatch)
 {
-    zval *zobj = getThis();
-    zval *zrequest;
-    int status = MS_FAILURE;
-    php_owsrequest_object *php_request;
-    php_map_object *php_map;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
-                              &zrequest, mapscript_ce_owsrequest) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  zval *zrequest;
+  int status = MS_FAILURE;
+  php_owsrequest_object *php_request;
+  php_map_object *php_map;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
+                            &zrequest, mapscript_ce_owsrequest) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_request = (php_owsrequest_object *) zend_object_store_get_object(zrequest TSRMLS_CC);
-    
-    status = mapObj_OWSDispatch(php_map->map, php_request->cgirequest);
-     
-    RETURN_LONG(status);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_request = (php_owsrequest_object *) zend_object_store_get_object(zrequest TSRMLS_CC);
+
+  status = mapObj_OWSDispatch(php_map->map, php_request->cgirequest);
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -3189,33 +3202,32 @@ PHP_METHOD(mapObj, owsDispatch)
    Returns the index where the layer had been inserted*/
 PHP_METHOD(mapObj, insertLayer)
 {
-    zval *zobj = getThis();
-    zval *zlayer;
-    long index = -1;
-    int retval = -1;
-    php_layer_object *php_layer;
-    php_map_object *php_map;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O|l",
-                              &zlayer, mapscript_ce_layer, &index) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  zval *zlayer;
+  long index = -1;
+  int retval = -1;
+  php_layer_object *php_layer;
+  php_map_object *php_map;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O|l",
+                            &zlayer, mapscript_ce_layer, &index) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_layer = (php_layer_object *) zend_object_store_get_object(zlayer TSRMLS_CC);
-    
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    if ((retval = mapObj_insertLayer(php_map->map, php_layer->layer, index)) < 0)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_layer = (php_layer_object *) zend_object_store_get_object(zlayer TSRMLS_CC);
 
-    /* return layer index */
-    RETURN_LONG(retval);
+
+  if ((retval = mapObj_insertLayer(php_map->map, php_layer->layer, index)) < 0) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
+
+  /* return layer index */
+  RETURN_LONG(retval);
 
 }
 /* }}} */
@@ -3224,63 +3236,62 @@ PHP_METHOD(mapObj, insertLayer)
    Returns layerObj removed on sucesss, else null. */
 PHP_METHOD(mapObj, removeLayer)
 {
-    zval *zobj = getThis();
-    long index = -1;
-    layerObj *layer = NULL;
-    php_map_object *php_map;
-    parent_object parent;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
-                              &index) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  long index = -1;
+  layerObj *layer = NULL;
+  php_map_object *php_map;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
+                            &index) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    if ((layer = mapObj_removeLayer(php_map->map, index)) == NULL)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  if ((layer = mapObj_removeLayer(php_map->map, index)) == NULL) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
 
-     /* return layer object */
-    MAPSCRIPT_MAKE_PARENT(NULL, NULL);
-    mapscript_create_layer(layer, parent, return_value TSRMLS_CC);
+  /* return layer object */
+  MAPSCRIPT_MAKE_PARENT(NULL, NULL);
+  mapscript_create_layer(layer, parent, return_value TSRMLS_CC);
 }
 /* }}} */
 
-/* {{{ proto int map.getLabel(). 
-   Return the next label from the map’s labelcache, allowing iteration 
+/* {{{ proto int map.getLabel().
+   Return the next label from the map’s labelcache, allowing iteration
    over labels. Return NULL when the labelcache is empty. */
 PHP_METHOD(mapObj, getLabel)
 {
-    zval *zobj = getThis();
-    long index = -1;
-    labelCacheMemberObj *labelCacheMember = NULL; 
-    php_map_object *php_map;
-    parent_object parent;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
-                              &index) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  long index = -1;
+  labelCacheMemberObj *labelCacheMember = NULL;
+  php_map_object *php_map;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
+                            &index) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    labelCacheMember=mapObj_getLabel(php_map->map, index);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  labelCacheMember=mapObj_getLabel(php_map->map, index);
 
-    if (labelCacheMember == NULL)
-        RETURN_NULL();
+  if (labelCacheMember == NULL)
+    RETURN_NULL();
 
-    /* Return labelCacheMember object */
-    MAPSCRIPT_MAKE_PARENT(zobj, NULL);
-    mapscript_create_labelcachemember(labelCacheMember, parent, return_value TSRMLS_CC);
+  /* Return labelCacheMember object */
+  MAPSCRIPT_MAKE_PARENT(zobj, NULL);
+  mapscript_create_labelcachemember(labelCacheMember, parent, return_value TSRMLS_CC);
 }
 /* }}} */
 
@@ -3296,322 +3307,322 @@ PHP_METHOD(mapObj, getLabel)
 PHP_METHOD(mapObj, getLatLongExtent)
 {
 #ifdef USE_PROJ
-    zval *zobj = getThis();
-    rectObj     geoRefExt;
-    php_map_object *php_map;
-    parent_object parent;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  rectObj     geoRefExt;
+  php_map_object *php_map;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    geoRefExt.minx = php_map->map->extent.minx;
-    geoRefExt.miny = php_map->map->extent.miny;
-    geoRefExt.maxx = php_map->map->extent.maxx;
-    geoRefExt.maxy = php_map->map->extent.maxy;
-    
-    if (php_map->map->projection.proj != NULL)
-    {
-        msProjectRect(&(php_map->map->projection), NULL, &geoRefExt);
-    }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    /* Return rectObj */
-    MAPSCRIPT_MAKE_PARENT(NULL, NULL);
-    mapscript_create_rect(&geoRefExt, parent, return_value TSRMLS_CC);
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  geoRefExt.minx = php_map->map->extent.minx;
+  geoRefExt.miny = php_map->map->extent.miny;
+  geoRefExt.maxx = php_map->map->extent.maxx;
+  geoRefExt.maxy = php_map->map->extent.maxy;
+
+  if (php_map->map->projection.proj != NULL) {
+    msProjectRect(&(php_map->map->projection), NULL, &geoRefExt);
+  }
+
+  /* Return rectObj */
+  MAPSCRIPT_MAKE_PARENT(NULL, NULL);
+  mapscript_create_rect(&geoRefExt, parent, return_value TSRMLS_CC);
 
 #else
-    mapscript_throw_exception("Available only with PROJ.4 support." TSRMLS_CC);
-    return;
+  mapscript_throw_exception("Available only with PROJ.4 support." TSRMLS_CC);
+  return;
 #endif
 }
 
-/* {{{ proto int map.free(). 
+/* {{{ proto int map.free().
    Free explicitly the map object.
    Breaks the internal circular references between the map object and its children.
 */
 PHP_METHOD(mapObj, free)
 {
-    zval *zobj = getThis();
-    php_map_object *php_map;
+  zval *zobj = getThis();
+  php_map_object *php_map;
 
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    MAPSCRIPT_DELREF(php_map->outputformat);
-    MAPSCRIPT_DELREF(php_map->extent);
-    MAPSCRIPT_DELREF(php_map->web);
-    MAPSCRIPT_DELREF(php_map->reference);
-    MAPSCRIPT_DELREF(php_map->imagecolor);
-    MAPSCRIPT_DELREF(php_map->scalebar);
-    MAPSCRIPT_DELREF(php_map->legend);
-    MAPSCRIPT_DELREF(php_map->querymap);
-    MAPSCRIPT_DELREF(php_map->labelcache);
-    MAPSCRIPT_DELREF(php_map->projection);
-    MAPSCRIPT_DELREF(php_map->metadata);
+  MAPSCRIPT_DELREF(php_map->outputformat);
+  MAPSCRIPT_DELREF(php_map->extent);
+  MAPSCRIPT_DELREF(php_map->web);
+  MAPSCRIPT_DELREF(php_map->reference);
+  MAPSCRIPT_DELREF(php_map->imagecolor);
+  MAPSCRIPT_DELREF(php_map->scalebar);
+  MAPSCRIPT_DELREF(php_map->legend);
+  MAPSCRIPT_DELREF(php_map->querymap);
+  MAPSCRIPT_DELREF(php_map->labelcache);
+  MAPSCRIPT_DELREF(php_map->projection);
+  MAPSCRIPT_DELREF(php_map->metadata);
 }
 /* }}} */
 
 zend_function_entry map_functions[] = {
-    PHP_ME(mapObj, __construct, map___construct_args, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
-    PHP_ME(mapObj, __get, map___get_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, __set, map___set_args, ZEND_ACC_PUBLIC)
-    PHP_MALIAS(mapObj, set, __set, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, getSymbolByName, map_getSymbolByName_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, getSymbolObjectById, map_getSymbolObjectById_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, prepareQuery, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, prepareImage, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, draw, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, drawQuery, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, drawLegend, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, drawReferenceMap, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, drawScaleBar, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, embedLegend, map_embedLegend_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, embedScaleBar, map_embedScaleBar_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, drawLabelCache, map_drawLabelCache_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, getLayer, map_getLayer_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, getLayerByName, map_getLayerByName_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, getColorByIndex, map_getColorByIndex_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, setExtent, map_setExtent_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, setCenter, map_setCenter_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, offsetExtent, map_offsetExtent_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, scaleExtent, map_scaleExtent_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, setRotation, map_setRotation_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, setSize, map_setSize_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, zoomPoint, map_zoomPoint_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, zoomRectangle, map_zoomRectangle_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, zoomScale, map_zoomScale_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, queryByPoint, map_queryByPoint_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, queryByRect, map_queryByRect_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, queryByShape, map_queryByShape_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, queryByFeatures, map_queryByFeatures_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, queryByIndex, map_queryByIndex_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, saveQuery, map_saveQuery_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, loadQuery, map_loadQuery_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, freeQuery, map_freeQuery_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, save, map_save_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, getProjection, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, setProjection, map_setProjection_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, setWKTProjection, map_setWKTProjection_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, getMetaData, map_getMetaData_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, setMetaData, map_setMetaData_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, removeMetaData, map_removeMetaData_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, getLayersIndexByGroup, map_getLayersIndexByGroup_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, getAllGroupNames, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, getAllLayerNames, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, moveLayerUp, map_moveLayerUp_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, moveLayerDown, map_moveLayerDown_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, getLayersDrawingOrder, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, setLayersDrawingOrder, map_setLayersDrawingOrder_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, processTemplate, map_processTemplate_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, processQueryTemplate, map_processQueryTemplate_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, processLegendTemplate, map_processLegendTemplate_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, setSymbolSet, map_setSymbolSet_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, getNumSymbols, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, setFontSet, map_setFontSet_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, selectOutputFormat, map_selectOutputFormat_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, saveMapContext, map_saveMapContext_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, loadMapContext, map_loadMapContext_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, applySLD, map_applySLD_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, applySLDURL, map_applySLDURL_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, generateSLD, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, getConfigOption, map_getConfigOption_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, setConfigOption, map_setConfigOption_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, applyConfigOptions, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, loadOwsParameters, map_loadOwsParameters_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, owsDispatch, map_owsDispatch_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, insertLayer, map_insertLayer_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, removeLayer, map_removeLayer_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, getLabel, map_getLabel_args, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, getLatLongExtent, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(mapObj, free, NULL, ZEND_ACC_PUBLIC)
-    {NULL, NULL, NULL}
+  PHP_ME(mapObj, __construct, map___construct_args, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
+  PHP_ME(mapObj, __get, map___get_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, __set, map___set_args, ZEND_ACC_PUBLIC)
+  PHP_MALIAS(mapObj, set, __set, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, getSymbolByName, map_getSymbolByName_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, getSymbolObjectById, map_getSymbolObjectById_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, prepareQuery, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, prepareImage, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, draw, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, drawQuery, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, drawLegend, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, drawReferenceMap, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, drawScaleBar, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, embedLegend, map_embedLegend_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, embedScaleBar, map_embedScaleBar_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, drawLabelCache, map_drawLabelCache_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, getLayer, map_getLayer_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, getLayerByName, map_getLayerByName_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, getColorByIndex, map_getColorByIndex_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, setExtent, map_setExtent_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, setCenter, map_setCenter_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, offsetExtent, map_offsetExtent_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, scaleExtent, map_scaleExtent_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, setRotation, map_setRotation_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, setSize, map_setSize_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, zoomPoint, map_zoomPoint_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, zoomRectangle, map_zoomRectangle_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, zoomScale, map_zoomScale_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, queryByPoint, map_queryByPoint_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, queryByRect, map_queryByRect_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, queryByShape, map_queryByShape_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, queryByFeatures, map_queryByFeatures_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, queryByFilter, map_queryByFilter_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, queryByIndex, map_queryByIndex_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, saveQuery, map_saveQuery_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, saveQueryAsGML, map_saveQueryAsGML_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, loadQuery, map_loadQuery_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, freeQuery, map_freeQuery_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, save, map_save_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, getProjection, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, setProjection, map_setProjection_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, setWKTProjection, map_setWKTProjection_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, getMetaData, map_getMetaData_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, setMetaData, map_setMetaData_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, removeMetaData, map_removeMetaData_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, getLayersIndexByGroup, map_getLayersIndexByGroup_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, getAllGroupNames, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, getAllLayerNames, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, moveLayerUp, map_moveLayerUp_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, moveLayerDown, map_moveLayerDown_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, getLayersDrawingOrder, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, setLayersDrawingOrder, map_setLayersDrawingOrder_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, processTemplate, map_processTemplate_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, processQueryTemplate, map_processQueryTemplate_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, processLegendTemplate, map_processLegendTemplate_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, setSymbolSet, map_setSymbolSet_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, getNumSymbols, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, setFontSet, map_setFontSet_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, selectOutputFormat, map_selectOutputFormat_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, appendOutputFormat, map_appendOutputFormat_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, removeOutputFormat, map_removeOutputFormat_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, getOutputFormat, map_getOutputFormat_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, saveMapContext, map_saveMapContext_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, loadMapContext, map_loadMapContext_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, applySLD, map_applySLD_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, applySLDURL, map_applySLDURL_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, generateSLD, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, getConfigOption, map_getConfigOption_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, setConfigOption, map_setConfigOption_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, applyConfigOptions, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, loadOwsParameters, map_loadOwsParameters_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, owsDispatch, map_owsDispatch_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, insertLayer, map_insertLayer_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, removeLayer, map_removeLayer_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, getLabel, map_getLabel_args, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, getLatLongExtent, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(mapObj, free, NULL, ZEND_ACC_PUBLIC) {
+    NULL, NULL, NULL
+  }
 };
 
 static int mapscript_map_setProjection(int isWKTProj, php_map_object *php_map,
                                        char *projString, int setUnitsAndExtents TSRMLS_DC)
 {
 #ifdef USE_PROJ
-    int                 status = MS_SUCCESS;
-    int                 units =   MS_METERS;  
-    projectionObj       in;
-    projectionObj       out;
-    rectObj             rect;
-    int                 setNewExtents = 0; 
-    php_projection_object *php_projection;
-    php_rect_object *php_extent;
-
-    if (php_map->projection)
-        php_projection = (php_projection_object *) zend_object_store_get_object(php_map->projection TSRMLS_CC);
-    if (php_map->extent)
-        php_extent = (php_rect_object *) zend_object_store_get_object(php_map->extent TSRMLS_CC);
-
-    in = php_map->map->projection;
-    msInitProjection(&out);
-    if (isWKTProj)
-        msOGCWKT2ProjectionObj(projString, &(out),php_map->map->debug);
-    else
-        msLoadProjectionString(&(out),  projString);
-    rect = php_map->map->extent;
- 
-    if (in.proj!= NULL && out.proj!=NULL)
-    {
-        if (msProjectionsDiffer(&in, &out))
-        {
-            if (msProjectRect(&in, &out, &rect) == MS_SUCCESS)
-              setNewExtents =1;
-        }
-    }
-    /* Free the temporary projection object */
-    msFreeProjection(&out);
-
-    if (isWKTProj) 
-        status = mapObj_setWKTProjection(php_map->map, projString);
-    else
-        status = mapObj_setProjection(php_map->map, projString);
-
-    if (status == -1)
-    {
-        mapscript_report_php_error(E_WARNING, "setProjection failed" TSRMLS_CC);
-        return MS_FAILURE;
-    }
-    else if (php_map->projection)
-    { 
-        php_projection->projection = &(php_map->map->projection);
-    }
-    
-    units = GetMapserverUnitUsingProj(&(php_map->map->projection));
-    if (units != -1 && setUnitsAndExtents)
-    {
-/* -------------------------------------------------------------------- 
-      set the units and php_map->map extents.                                  
- -------------------------------------------------------------------- */
-        php_map->map->units = units;
-
-        if (setNewExtents)
-        {
-            php_map->map->extent = rect;
-
-            php_map->map->cellsize = msAdjustExtent(&(php_map->map->extent), php_map->map->width, 
-                                            php_map->map->height); 
-            msCalculateScale(php_map->map->extent, php_map->map->units, php_map->map->width, php_map->map->height, 
-                             php_map->map->resolution, &(php_map->map->scaledenom));
-
-            if (php_map->extent)
-                php_extent->rect = &(php_map->map->extent);
-        }
+  int                 status = MS_SUCCESS;
+  int                 units =   MS_METERS;
+  projectionObj       in;
+  projectionObj       out;
+  rectObj             rect;
+  int                 setNewExtents = 0;
+  php_projection_object *php_projection = NULL;
+  php_rect_object *php_extent = NULL;
+
+  if (php_map->projection)
+    php_projection = (php_projection_object *) zend_object_store_get_object(php_map->projection TSRMLS_CC);
+  if (php_map->extent)
+    php_extent = (php_rect_object *) zend_object_store_get_object(php_map->extent TSRMLS_CC);
+
+  in = php_map->map->projection;
+  msInitProjection(&out);
+  if (isWKTProj)
+    msOGCWKT2ProjectionObj(projString, &(out),php_map->map->debug);
+  else
+    msLoadProjectionString(&(out),  projString);
+  rect = php_map->map->extent;
+
+  if (in.proj!= NULL && out.proj!=NULL) {
+    if (msProjectionsDiffer(&in, &out)) {
+      if (msProjectRect(&in, &out, &rect) == MS_SUCCESS)
+        setNewExtents =1;
+    }
+  }
+  /* Free the temporary projection object */
+  msFreeProjection(&out);
+
+  if (isWKTProj)
+    status = mapObj_setWKTProjection(php_map->map, projString);
+  else
+    status = mapObj_setProjection(php_map->map, projString);
+
+  if (status == -1) {
+    mapscript_report_php_error(E_WARNING, "setProjection failed" TSRMLS_CC);
+    return MS_FAILURE;
+  } else if (php_map->projection) {
+    php_projection->projection = &(php_map->map->projection);
+  }
+
+  units = GetMapserverUnitUsingProj(&(php_map->map->projection));
+  if (units != -1 && setUnitsAndExtents) {
+    /* --------------------------------------------------------------------
+          set the units and php_map->map extents.
+     -------------------------------------------------------------------- */
+    php_map->map->units = units;
+
+    if (setNewExtents) {
+      php_map->map->extent = rect;
+
+      php_map->map->cellsize = msAdjustExtent(&(php_map->map->extent), php_map->map->width,
+                                              php_map->map->height);
+      msCalculateScale(php_map->map->extent, php_map->map->units, php_map->map->width, php_map->map->height,
+                       php_map->map->resolution, &(php_map->map->scaledenom));
+
+      if (php_map->extent)
+        php_extent->rect = &(php_map->map->extent);
     }
+  }
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 #else
-    mapscript_throw_exception("Available only with PROJ.4 support." TSRMLS_CC);
-    return MS_FAILURE;
+  mapscript_throw_exception("Available only with PROJ.4 support." TSRMLS_CC);
+  return MS_FAILURE;
 #endif
 }
 
 void mapscript_create_map(mapObj *map, zval *return_value TSRMLS_DC)
 {
-    php_map_object * php_map;
-    object_init_ex(return_value, mapscript_ce_map); 
-    php_map = (php_map_object *)zend_object_store_get_object(return_value TSRMLS_CC);
-    php_map->map = map;
+  php_map_object * php_map;
+  object_init_ex(return_value, mapscript_ce_map);
+  php_map = (php_map_object *)zend_object_store_get_object(return_value TSRMLS_CC);
+  php_map->map = map;
 }
 
 static void mapscript_map_object_destroy(void *object TSRMLS_DC)
 {
-    php_map_object *php_map = (php_map_object *)object;
+  php_map_object *php_map = (php_map_object *)object;
 
-    MAPSCRIPT_FREE_OBJECT(php_map);
- 
-    MAPSCRIPT_DELREF(php_map->outputformat);
-    MAPSCRIPT_DELREF(php_map->extent);
-    MAPSCRIPT_DELREF(php_map->web);
-    MAPSCRIPT_DELREF(php_map->reference);
-    MAPSCRIPT_DELREF(php_map->imagecolor);
-    MAPSCRIPT_DELREF(php_map->scalebar);
-    MAPSCRIPT_DELREF(php_map->legend);
-    MAPSCRIPT_DELREF(php_map->querymap);
-    MAPSCRIPT_DELREF(php_map->labelcache);
-    MAPSCRIPT_DELREF(php_map->projection);
-    MAPSCRIPT_DELREF(php_map->metadata);
+  MAPSCRIPT_FREE_OBJECT(php_map);
 
-    mapObj_destroy(php_map->map);
-    efree(object);
+  MAPSCRIPT_DELREF(php_map->outputformat);
+  MAPSCRIPT_DELREF(php_map->extent);
+  MAPSCRIPT_DELREF(php_map->web);
+  MAPSCRIPT_DELREF(php_map->reference);
+  MAPSCRIPT_DELREF(php_map->imagecolor);
+  MAPSCRIPT_DELREF(php_map->scalebar);
+  MAPSCRIPT_DELREF(php_map->legend);
+  MAPSCRIPT_DELREF(php_map->querymap);
+  MAPSCRIPT_DELREF(php_map->labelcache);
+  MAPSCRIPT_DELREF(php_map->projection);
+  MAPSCRIPT_DELREF(php_map->metadata);
+  MAPSCRIPT_DELREF(php_map->configoptions);
+
+  mapObj_destroy(php_map->map);
+  efree(object);
 }
 
 static zend_object_value mapscript_map_object_new_ex(zend_class_entry *ce, php_map_object **ptr TSRMLS_DC)
 {
-    zend_object_value retval;
-    php_map_object *php_map;
+  zend_object_value retval;
+  php_map_object *php_map;
 
-    MAPSCRIPT_ALLOC_OBJECT(php_map, php_map_object);
+  MAPSCRIPT_ALLOC_OBJECT(php_map, php_map_object);
 
-    retval = mapscript_object_new_ex(&php_map->std, ce,
-                                     &mapscript_map_object_destroy,
-                                     &mapscript_map_object_handlers TSRMLS_CC);
+  retval = mapscript_object_new_ex(&php_map->std, ce,
+                                   &mapscript_map_object_destroy,
+                                   &mapscript_map_object_handlers TSRMLS_CC);
 
-    if (ptr)
-        *ptr = php_map;
+  if (ptr)
+    *ptr = php_map;
 
-    php_map->outputformat = NULL;
-    php_map->extent = NULL;
-    php_map->web = NULL;
-    php_map->reference = NULL;
-    php_map->imagecolor = NULL;
-    php_map->scalebar = NULL;
-    php_map->legend = NULL;
-    php_map->querymap = NULL;
-    php_map->labelcache = NULL;
-    php_map->projection = NULL;
-    php_map->metadata = NULL;
+  php_map->outputformat = NULL;
+  php_map->extent = NULL;
+  php_map->web = NULL;
+  php_map->reference = NULL;
+  php_map->imagecolor = NULL;
+  php_map->scalebar = NULL;
+  php_map->legend = NULL;
+  php_map->querymap = NULL;
+  php_map->labelcache = NULL;
+  php_map->projection = NULL;
+  php_map->metadata = NULL;
+  php_map->configoptions = NULL;
 
-    return retval;
+  return retval;
 }
 
 static zend_object_value mapscript_map_object_new(zend_class_entry *ce TSRMLS_DC)
 {
-    return mapscript_map_object_new_ex(ce, NULL TSRMLS_CC);
+  return mapscript_map_object_new_ex(ce, NULL TSRMLS_CC);
 }
 
 static zend_object_value mapscript_map_object_clone(zval *zobj TSRMLS_DC)
 {
-    php_map_object *php_map_old, *php_map_new;
-    zend_object_value new_ov;
+  php_map_object *php_map_old, *php_map_new;
+  zend_object_value new_ov;
 
-    php_map_old = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_map_old = (php_map_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    new_ov = mapscript_map_object_new_ex(mapscript_ce_map, &php_map_new TSRMLS_CC); 
-    zend_objects_clone_members(&php_map_new->std, new_ov, &php_map_old->std, Z_OBJ_HANDLE_P(zobj) TSRMLS_CC);
+  new_ov = mapscript_map_object_new_ex(mapscript_ce_map, &php_map_new TSRMLS_CC);
+  zend_objects_clone_members(&php_map_new->std, new_ov, &php_map_old->std, Z_OBJ_HANDLE_P(zobj) TSRMLS_CC);
 
-    php_map_new->map = mapObj_clone(php_map_old->map);
+  php_map_new->map = mapObj_clone(php_map_old->map);
 
-    return new_ov;
+  return new_ov;
 }
 
 PHP_MINIT_FUNCTION(map)
 {
-    zend_class_entry ce;
+  zend_class_entry ce;
+
+  memcpy(&mapscript_map_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
+  mapscript_map_object_handlers.clone_obj = mapscript_map_object_clone;
 
-    memcpy(&mapscript_map_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
-    mapscript_map_object_handlers.clone_obj = mapscript_map_object_clone;
+  MAPSCRIPT_REGISTER_CLASS("mapObj",
+                           map_functions,
+                           mapscript_ce_map,
+                           mapscript_map_object_new);
 
-    MAPSCRIPT_REGISTER_CLASS("mapObj", 
-                             map_functions,
-                             mapscript_ce_map,
-                             mapscript_map_object_new);
+  mapscript_ce_map->ce_flags |= ZEND_ACC_FINAL_CLASS;
 
-    mapscript_ce_map->ce_flags |= ZEND_ACC_FINAL_CLASS; 
-    
-    return SUCCESS;
+  return SUCCESS;
 }
 
diff --git a/mapscript/php/mapscript_error.c b/mapscript/php/mapscript_error.c
index bc4691f..e2bef8a 100644
--- a/mapscript/php/mapscript_error.c
+++ b/mapscript/php/mapscript_error.c
@@ -2,7 +2,7 @@
  * $Id: php_mapscript.c 9765 2010-01-28 15:32:10Z aboudreault $
  *
  * Project:  MapServer
- * Purpose:  PHP/MapScript extension for MapServer.  External interface 
+ * Purpose:  PHP/MapScript extension for MapServer.  External interface
  *           functions
  * Author:   Daniel Morissette, DM Solutions Group (dmorissette at dmsolutions.ca)
  *           Alan Boudreault, Mapgears
@@ -16,16 +16,16 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
+ *
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  * DEALINGS IN THE SOFTWARE.
  **********************************************************************/
 
@@ -33,7 +33,7 @@
 #include "zend_exceptions.h"
 #include "php_mapscript_util.h"
 #include <stdarg.h>
-#include "maperror.h"
+#include "../../maperror.h"
 
 #define MAX_EXCEPTION_MSG 256
 
@@ -41,79 +41,77 @@ zend_class_entry *mapscript_ce_mapscriptexception;
 
 zval* mapscript_throw_exception(char *format TSRMLS_DC, ...)
 {
-    va_list args;
-    char message[MAX_EXCEPTION_MSG];
+  va_list args;
+  char message[MAX_EXCEPTION_MSG];
 #ifdef ZTS
-    va_start(args, TSRMLS_C);
+  va_start(args, TSRMLS_C);
 #else
-    va_start(args, format);
+  va_start(args, format);
 #endif
-    vsprintf(message, format, args);
-    va_end(args);
-    return zend_throw_exception(mapscript_ce_mapscriptexception, message, 0 TSRMLS_CC);
+  vsprintf(message, format, args);
+  va_end(args);
+  return zend_throw_exception(mapscript_ce_mapscriptexception, message, 0 TSRMLS_CC);
 }
 
 zval* mapscript_throw_mapserver_exception(char *format TSRMLS_DC, ...)
 {
-    va_list args;
-    char message[MAX_EXCEPTION_MSG];
-    errorObj *ms_error;
+  va_list args;
+  char message[MAX_EXCEPTION_MSG];
+  errorObj *ms_error;
 
-    ms_error = msGetErrorObj();
+  ms_error = msGetErrorObj();
 
-    while (ms_error && ms_error->code != MS_NOERR)
-    {
-        php_error_docref(NULL TSRMLS_CC, E_WARNING, 
-                   "[MapServer Error]: %s: %s\n", 
-                   ms_error->routine, ms_error->message);
-        ms_error = ms_error->next;
-    }
+  while (ms_error && ms_error->code != MS_NOERR) {
+    php_error_docref(NULL TSRMLS_CC, E_WARNING,
+                     "[MapServer Error]: %s: %s\n",
+                     ms_error->routine, ms_error->message);
+    ms_error = ms_error->next;
+  }
 
 #ifdef ZTS
-    va_start(args, TSRMLS_C);
+  va_start(args, TSRMLS_C);
 #else
-    va_start(args, format);
+  va_start(args, format);
 #endif
-    vsprintf(message, format, args);
-    va_end(args);
-    return mapscript_throw_exception(message TSRMLS_CC);
+  vsprintf(message, format, args);
+  va_end(args);
+  return mapscript_throw_exception(message TSRMLS_CC);
 }
 
 void mapscript_report_php_error(int error_type, char *format TSRMLS_DC, ...)
 {
-    va_list args;
-    char message[MAX_EXCEPTION_MSG];
+  va_list args;
+  char message[MAX_EXCEPTION_MSG];
 #ifdef ZTS
-    va_start(args, TSRMLS_C);
+  va_start(args, TSRMLS_C);
 #else
-    va_start(args, format);
+  va_start(args, format);
 #endif
-    vsprintf(message, format, args);
-    va_end(args);
-    php_error_docref(NULL TSRMLS_CC, error_type, "%s,", message);
+  vsprintf(message, format, args);
+  va_end(args);
+  php_error_docref(NULL TSRMLS_CC, error_type, "%s,", message);
 }
 
 void mapscript_report_mapserver_error(int error_type TSRMLS_DC)
 {
-    errorObj *ms_error;
+  errorObj *ms_error;
 
-    ms_error = msGetErrorObj();
+  ms_error = msGetErrorObj();
 
-    while (ms_error && ms_error->code != MS_NOERR)
-    {
-        php_error_docref(NULL TSRMLS_CC, error_type, 
-                   "[MapServer Error]: %s: %s\n", 
-                   ms_error->routine, ms_error->message);
-        ms_error = ms_error->next;
-    }
+  while (ms_error && ms_error->code != MS_NOERR) {
+    php_error_docref(NULL TSRMLS_CC, error_type,
+                     "[MapServer Error]: %s: %s\n",
+                     ms_error->routine, ms_error->message);
+    ms_error = ms_error->next;
+  }
 }
 
 PHP_MINIT_FUNCTION(mapscript_error)
 {
-    zend_class_entry ce;
+  zend_class_entry ce;
 
-    INIT_CLASS_ENTRY(ce, "MapScriptException", NULL);
-    mapscript_ce_mapscriptexception = zend_register_internal_class_ex(&ce, zend_exception_get_default(TSRMLS_C), "Exception" TSRMLS_CC);
+  INIT_CLASS_ENTRY(ce, "MapScriptException", NULL);
+  mapscript_ce_mapscriptexception = zend_register_internal_class_ex(&ce, zend_exception_get_default(TSRMLS_C), "Exception" TSRMLS_CC);
 
-    return SUCCESS;
+  return SUCCESS;
 }
diff --git a/mapscript/php/mapscript_i.c b/mapscript/php/mapscript_i.c
index 42e604b..7fb400c 100644
--- a/mapscript/php/mapscript_i.c
+++ b/mapscript/php/mapscript_i.c
@@ -2,8 +2,8 @@
  * $Id$
  *
  * Project:  MapServer
- * Purpose:  Interface file for MapServer PHP scripting extension 
- *           called MapScript. This file was originally based on 
+ * Purpose:  Interface file for MapServer PHP scripting extension
+ *           called MapScript. This file was originally based on
  *           the SWIG interface file mapscript.i
  * Author:   Daniel Morissette, DM Solutions Group (dmorissette at dmsolutions.ca)
  *
@@ -16,18 +16,18 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
+ *
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  * DEALINGS IN THE SOFTWARE.
- **********************************************************************/ 
+ **********************************************************************/
 
 #include "php_mapscript.h"
 
@@ -44,291 +44,346 @@
 /**********************************************************************
  * class extensions for mapObj
  **********************************************************************/
-mapObj *mapObj_new(char *filename, char *new_path) {
-    if(filename && strlen(filename))
-        return msLoadMap(filename, new_path);
-    else { /* create an empty map, no layers etc... */
-        return msNewMapObj();
-    } 
+mapObj *mapObj_new(char *filename, char *new_path)
+{
+  if(filename && strlen(filename))
+    return msLoadMap(filename, new_path);
+  else { /* create an empty map, no layers etc... */
+    return msNewMapObj();
+  }
 }
 
-mapObj *mapObj_newFromString(char *map_text, char *new_path) {
+mapObj *mapObj_newFromString(char *map_text, char *new_path)
+{
 
-      if(map_text && strlen(map_text))
-        return msLoadMapFromString(map_text, new_path);
-      else { /* create an empty map, no layers etc... */
-        return msNewMapObj();
-      }
+  if(map_text && strlen(map_text))
+    return msLoadMapFromString(map_text, new_path);
+  else { /* create an empty map, no layers etc... */
+    return msNewMapObj();
+  }
 }
 
-void  mapObj_destroy(mapObj* self) {
-    msFreeMap(self);
-  }
+void  mapObj_destroy(mapObj* self)
+{
+  msFreeMap(self);
+}
 
-mapObj *mapObj_clone(mapObj* self) {
-    mapObj *dstMap;
-    dstMap = msNewMapObj();
-    if (msCopyMap(dstMap, self) != MS_SUCCESS)
-    {
-        msFreeMap(dstMap);
-        dstMap = NULL;
-    }
-    return dstMap;
+mapObj *mapObj_clone(mapObj* self)
+{
+  mapObj *dstMap;
+  dstMap = msNewMapObj();
+  if (msCopyMap(dstMap, self) != MS_SUCCESS) {
+    msFreeMap(dstMap);
+    dstMap = NULL;
   }
+  return dstMap;
+}
 
-int mapObj_setRotation(mapObj* self, double rotation_angle ) {
-        return msMapSetRotation( self, rotation_angle );
-    }
+int mapObj_setRotation(mapObj* self, double rotation_angle )
+{
+  return msMapSetRotation( self, rotation_angle );
+}
 
-layerObj *mapObj_getLayer(mapObj* self, int i) {
-    if(i >= 0 && i < self->numlayers)	
-      return (self->layers[i]); /* returns an EXISTING layer */
-    else
-      return NULL;
-  }
+layerObj *mapObj_getLayer(mapObj* self, int i)
+{
+  if(i >= 0 && i < self->numlayers)
+    return (self->layers[i]); /* returns an EXISTING layer */
+  else
+    return NULL;
+}
 
-layerObj *mapObj_getLayerByName(mapObj* self, char *name) {
-    int i;
+layerObj *mapObj_getLayerByName(mapObj* self, char *name)
+{
+  int i;
 
-    i = msGetLayerIndex(self, name);
+  i = msGetLayerIndex(self, name);
 
-    if(i != -1)
-      return (self->layers[i]); /* returns an EXISTING layer */
-    else
-      return NULL;
-  }
+  if(i != -1)
+    return (self->layers[i]); /* returns an EXISTING layer */
+  else
+    return NULL;
+}
 
-int *mapObj_getLayersIndexByGroup(mapObj* self, char *groupname, 
-                                 int *pnCount) {
-    return msGetLayersIndexByGroup(self, groupname, pnCount);
+int *mapObj_getLayersIndexByGroup(mapObj* self, char *groupname,
+                                  int *pnCount)
+{
+  return msGetLayersIndexByGroup(self, groupname, pnCount);
 }
 
 
-int mapObj_getSymbolByName(mapObj* self, char *name) {
-    return msGetSymbolIndex(&self->symbolset, name, MS_TRUE);
-  }
+int mapObj_getSymbolByName(mapObj* self, char *name)
+{
+  return msGetSymbolIndex(&self->symbolset, name, MS_TRUE);
+}
 
-void mapObj_prepareQuery(mapObj* self) {
-    int status;
+void mapObj_prepareQuery(mapObj* self)
+{
+  int status;
 
-    status = msCalculateScale(self->extent, self->units, self->width, self->height, self->resolution, &self->scaledenom);
-    if(status != MS_SUCCESS) self->scaledenom = -1; // degenerate extents ok here
-  }
+  status = msCalculateScale(self->extent, self->units, self->width, self->height, self->resolution, &self->scaledenom);
+  if(status != MS_SUCCESS) self->scaledenom = -1; // degenerate extents ok here
+}
 
-imageObj *mapObj_prepareImage(mapObj* self) {
-    return msPrepareImage(self, MS_FALSE);
-  }
+imageObj *mapObj_prepareImage(mapObj* self)
+{
+  return msPrepareImage(self, MS_FALSE);
+}
 
-imageObj *mapObj_draw(mapObj* self) {
-    return msDrawMap(self, MS_FALSE);
-  }
+imageObj *mapObj_draw(mapObj* self)
+{
+  return msDrawMap(self, MS_FALSE);
+}
 
-imageObj *mapObj_drawQuery(mapObj* self) {
-    return msDrawMap(self, MS_TRUE);
-  }
+imageObj *mapObj_drawQuery(mapObj* self)
+{
+  return msDrawMap(self, MS_TRUE);
+}
 
-imageObj *mapObj_drawLegend(mapObj* self) {
-    return msDrawLegend(self, MS_FALSE);
-  }
+imageObj *mapObj_drawLegend(mapObj* self)
+{
+  return msDrawLegend(self, MS_FALSE);
+}
 
 
-imageObj *mapObj_drawScalebar(mapObj* self) {
-    return msDrawScalebar(self);
-  }
+imageObj *mapObj_drawScalebar(mapObj* self)
+{
+  return msDrawScalebar(self);
+}
 
-imageObj *mapObj_drawReferenceMap(mapObj* self) {
-    return msDrawReferenceMap(self);
-  }
+imageObj *mapObj_drawReferenceMap(mapObj* self)
+{
+  return msDrawReferenceMap(self);
+}
 
 //TODO
-int mapObj_embedScalebar(mapObj* self, imageObj *img) {	
-    return msEmbedScalebar(self, img);
-  }
+int mapObj_embedScalebar(mapObj* self, imageObj *img)
+{
+  return msEmbedScalebar(self, img);
+}
 
 //TODO
-int mapObj_embedLegend(mapObj* self, imageObj *img) {	
-    return msEmbedLegend(self, img);
-  }
+int mapObj_embedLegend(mapObj* self, imageObj *img)
+{
+  return msEmbedLegend(self, img);
+}
 
-int mapObj_drawLabelCache(mapObj* self, imageObj *img) {
-    return msDrawLabelCache(img, self);
-  }
+int mapObj_drawLabelCache(mapObj* self, imageObj *img)
+{
+  return msDrawLabelCache(img, self);
+}
 
 labelCacheMemberObj* mapObj_getLabel(mapObj* self, int i)
 {
-    return msGetLabelCacheMember(&(self->labelcache), i);
+  return msGetLabelCacheMember(&(self->labelcache), i);
 }
 
-int mapObj_queryByPoint(mapObj* self, pointObj *point, int mode, double buffer) {
-    msInitQuery(&(self->query));
+int mapObj_queryByPoint(mapObj* self, pointObj *point, int mode, double buffer)
+{
+  msInitQuery(&(self->query));
 
-    self->query.type = MS_QUERY_BY_POINT;
-    self->query.mode = mode;
-    self->query.point = *point;
-    self->query.buffer = buffer;
+  self->query.type = MS_QUERY_BY_POINT;
+  self->query.mode = mode;
+  self->query.point = *point;
+  self->query.buffer = buffer;
 
-    return msQueryByPoint(self);
-  }
+  return msQueryByPoint(self);
+}
+
+int mapObj_queryByRect(mapObj* self, rectObj rect)
+{
+  msInitQuery(&(self->query));
 
-int mapObj_queryByRect(mapObj* self, rectObj rect) {
-    msInitQuery(&(self->query));
+  self->query.type = MS_QUERY_BY_RECT;
+  self->query.mode = MS_QUERY_MULTIPLE;
+  self->query.rect = rect;
 
-    self->query.type = MS_QUERY_BY_RECT;
-    self->query.mode = MS_QUERY_MULTIPLE;
-    self->query.rect = rect;
+  return msQueryByRect(self);
+}
 
-    return msQueryByRect(self);
-  }
+int mapObj_queryByFeatures(mapObj* self, int slayer)
+{
+  self->query.slayer = slayer;
+  return msQueryByFeatures(self);
+}
 
-int mapObj_queryByFeatures(mapObj* self, int slayer) {
-    self->query.slayer = slayer;
-    return msQueryByFeatures(self);
-  }
+int mapObj_queryByFilter(mapObj* self, char *string)
+{
+  msInitQuery(&(self->query));
 
-int mapObj_queryByShape(mapObj *self, shapeObj *shape) {
-    msInitQuery(&(self->query));
+  self->query.type = MS_QUERY_BY_FILTER;
 
-    self->query.type = MS_QUERY_BY_SHAPE;
-    self->query.mode = MS_QUERY_MULTIPLE;
-    self->query.shape = (shapeObj *) malloc(sizeof(shapeObj));
-    msInitShape(self->query.shape);
-    msCopyShape(shape, self->query.shape);
+  self->query.filter = (expressionObj *) malloc(sizeof(expressionObj));
+  self->query.filter->compiled = MS_FALSE;
+  self->query.filter->flags = 0;
+  self->query.filter->tokens = self->query.filter->curtoken = NULL;
+  self->query.filter->string = strdup(string);
+  self->query.filter->type = 2000; /* MS_EXPRESSION: lot's of conflicts in mapfile.h */
 
-    return msQueryByShape(self);
-  }
+  self->query.rect = self->extent;
 
-int mapObj_queryByIndex(mapObj *self, int qlayer, int tileindex, int shapeindex, int bAddToQuery) {
-    msInitQuery(&(self->query));
+  return msQueryByFilter(self);
+}
+
+int mapObj_queryByShape(mapObj *self, shapeObj *shape)
+{
+  msInitQuery(&(self->query));
+
+  self->query.type = MS_QUERY_BY_SHAPE;
+  self->query.mode = MS_QUERY_MULTIPLE;
+  self->query.shape = (shapeObj *) malloc(sizeof(shapeObj));
+  msInitShape(self->query.shape);
+  msCopyShape(shape, self->query.shape);
+
+  return msQueryByShape(self);
+}
+
+int mapObj_queryByIndex(mapObj *self, int qlayer, int tileindex, int shapeindex, int bAddToQuery)
+{
+  msInitQuery(&(self->query));
 
-    self->query.type = MS_QUERY_BY_INDEX;
-    self->query.mode = MS_QUERY_SINGLE;
-    self->query.tileindex = tileindex;
-    self->query.shapeindex = shapeindex;
-    self->query.clear_resultcache = !bAddToQuery;
-    self->query.layer = qlayer;
+  self->query.type = MS_QUERY_BY_INDEX;
+  self->query.mode = MS_QUERY_SINGLE;
+  self->query.tileindex = tileindex;
+  self->query.shapeindex = shapeindex;
+  self->query.clear_resultcache = !bAddToQuery;
+  self->query.layer = qlayer;
 
-    return msQueryByIndex(self);
+  return msQueryByIndex(self);
 }
 
-int mapObj_saveQuery(mapObj *self, char *filename, int results) {
+int mapObj_saveQuery(mapObj *self, char *filename, int results)
+{
   return msSaveQuery(self, filename, results);
 }
-int mapObj_loadQuery(mapObj *self, char *filename) {
+int mapObj_loadQuery(mapObj *self, char *filename)
+{
   return msLoadQuery(self, filename);
 }
-void mapObj_freeQuery(mapObj *self, int qlayer) {
+void mapObj_freeQuery(mapObj *self, int qlayer)
+{
   msQueryFree(self, qlayer);
 }
 
-int mapObj_setWKTProjection(mapObj *self, char *string) {
-    return msOGCWKT2ProjectionObj(string, &(self->projection), self->debug);
-  }
+int mapObj_setWKTProjection(mapObj *self, char *string)
+{
+  return msOGCWKT2ProjectionObj(string, &(self->projection), self->debug);
+}
 
-char *mapObj_getProjection(mapObj* self) {
-    return msGetProjectionString(&self->projection);
- }
+char *mapObj_getProjection(mapObj* self)
+{
+  return msGetProjectionString(&self->projection);
+}
 
-int mapObj_setProjection(mapObj* self, char *string) {
-    return(msLoadProjectionString(&(self->projection), string));
-  }
+int mapObj_setProjection(mapObj* self, char *string)
+{
+  return(msLoadProjectionString(&(self->projection), string));
+}
 
-int mapObj_save(mapObj* self, char *filename) {
-    return msSaveMap(self, filename);
-  }
+int mapObj_save(mapObj* self, char *filename)
+{
+  return msSaveMap(self, filename);
+}
 
-char *mapObj_getMetaData(mapObj *self, char *name) {
-    return(msLookupHashTable(&(self->web.metadata), name));
-  }
+char *mapObj_getMetaData(mapObj *self, char *name)
+{
+  return(msLookupHashTable(&(self->web.metadata), name));
+}
 
-int mapObj_setMetaData(mapObj *self, char *name, char *value) {
-    if (msInsertHashTable(&(self->web.metadata), name, value) == NULL)
-	return MS_FAILURE;
-    return MS_SUCCESS;
-  }
+int mapObj_setMetaData(mapObj *self, char *name, char *value)
+{
+  if (msInsertHashTable(&(self->web.metadata), name, value) == NULL)
+    return MS_FAILURE;
+  return MS_SUCCESS;
+}
 
-int mapObj_removeMetaData(mapObj *self, char *name) {
-    return(msRemoveHashTable(&(self->web.metadata), name));
+int mapObj_removeMetaData(mapObj *self, char *name)
+{
+  return(msRemoveHashTable(&(self->web.metadata), name));
 }
 
-int mapObj_moveLayerup(mapObj *self, int layerindex){
-    return msMoveLayerUp(self, layerindex);
+int mapObj_moveLayerup(mapObj *self, int layerindex)
+{
+  return msMoveLayerUp(self, layerindex);
 }
 
-int mapObj_moveLayerdown(mapObj *self, int layerindex){
-    return msMoveLayerDown(self, layerindex);
+int mapObj_moveLayerdown(mapObj *self, int layerindex)
+{
+  return msMoveLayerDown(self, layerindex);
 }
 
-int *mapObj_getLayersdrawingOrder(mapObj *self){
-    return self->layerorder;
+int *mapObj_getLayersdrawingOrder(mapObj *self)
+{
+  return self->layerorder;
 }
- 
-int mapObj_setLayersdrawingOrder(mapObj *self, int *panIndexes){
-    return msSetLayersdrawingOrder(self, panIndexes);
+
+int mapObj_setLayersdrawingOrder(mapObj *self, int *panIndexes)
+{
+  return msSetLayersdrawingOrder(self, panIndexes);
 }
 
-char *mapObj_processTemplate(mapObj *self, int bGenerateImages, 
-                             char **names, char **values, 
+char *mapObj_processTemplate(mapObj *self, int bGenerateImages,
+                             char **names, char **values,
                              int numentries)
 {
-    return msProcessTemplate(self, bGenerateImages,
-                             names, values, numentries);
+  return msProcessTemplate(self, bGenerateImages,
+                           names, values, numentries);
 }
-  
+
 char *mapObj_processLegendTemplate(mapObj *self,
-                                   char **names, char **values, 
+                                   char **names, char **values,
                                    int numentries)
 {
-    return msProcessLegendTemplate(self, names, values, numentries);
+  return msProcessLegendTemplate(self, names, values, numentries);
 }
-  
+
 
 char *mapObj_processQueryTemplate(mapObj *self, int bGenerateImages,
-                                   char **names, char **values, 
-                                   int numentries)
+                                  char **names, char **values,
+                                  int numentries)
 {
-    return msProcessQueryTemplate(self, bGenerateImages, names, values, 
-                                  numentries);
+  return msProcessQueryTemplate(self, bGenerateImages, names, values,
+                                numentries);
 }
 
 int mapObj_setSymbolSet(mapObj *self,
                         char *szFileName)
 {
-    msFreeSymbolSet(&self->symbolset);
-    msInitSymbolSet(&self->symbolset);
-   
-    // Set symbolset filename
-    self->symbolset.filename = strdup(szFileName);
+  msFreeSymbolSet(&self->symbolset);
+  msInitSymbolSet(&self->symbolset);
 
-    // Symbolset shares same fontset as main mapfile
-    self->symbolset.fontset = &(self->fontset);
+  // Set symbolset filename
+  self->symbolset.filename = strdup(szFileName);
 
-    return msLoadSymbolSet(&self->symbolset, self);
+  // Symbolset shares same fontset as main mapfile
+  self->symbolset.fontset = &(self->fontset);
+
+  return msLoadSymbolSet(&self->symbolset, self);
 }
 
 int mapObj_getNumSymbols(mapObj *self)
 {
-    return self->symbolset.numsymbols;
+  return self->symbolset.numsymbols;
 }
 
 int mapObj_setFontSet(mapObj *self, char *szFileName)
 {
-    msFreeFontSet(&(self->fontset));
-    msInitFontSet(&(self->fontset));
-   
-    // Set fontset filename
-    self->fontset.filename = strdup(szFileName);
+  msFreeFontSet(&(self->fontset));
+  msInitFontSet(&(self->fontset));
+
+  // Set fontset filename
+  self->fontset.filename = strdup(szFileName);
 
-    return msLoadFontSet(&(self->fontset), self);
+  return msLoadFontSet(&(self->fontset), self);
 }
 
 int mapObj_saveMapContext(mapObj *self, char *szFilename)
 {
-    return msSaveMapContext(self, szFilename);
+  return msSaveMapContext(self, szFilename);
 }
 
 int mapObj_loadMapContext(mapObj *self, char *szFilename, int bUniqueLayerName)
 {
-    return msLoadMapContext(self, szFilename, bUniqueLayerName);
+  return msLoadMapContext(self, szFilename, bUniqueLayerName);
 }
 
 
@@ -336,27 +391,26 @@ int mapObj_loadMapContext(mapObj *self, char *szFilename, int bUniqueLayerName)
 int mapObj_selectOutputFormat(mapObj *self,
                               const char *imagetype)
 {
-    outputFormatObj *format = NULL;
-    
-    format = msSelectOutputFormat(self, imagetype);
-    if (format)
-    {
-        msApplyOutputFormat( &(self->outputformat), format, 
-                             self->transparent, self->interlace, 
-                             self->imagequality );
-        return(MS_SUCCESS);
-    }
-    return(MS_FAILURE);
-    
+  outputFormatObj *format = NULL;
+
+  format = msSelectOutputFormat(self, imagetype);
+  if (format) {
+    msApplyOutputFormat( &(self->outputformat), format,
+                         self->transparent, self->interlace,
+                         self->imagequality );
+    return(MS_SUCCESS);
+  }
+  return(MS_FAILURE);
+
 }
 
 int mapObj_applySLD(mapObj *self, char *sld)
 {
-    return msSLDApplySLD(self, sld, -1, NULL);
+  return msSLDApplySLD(self, sld, -1, NULL, NULL);
 }
 int mapObj_applySLDURL(mapObj *self, char *sld)
 {
-    return msSLDApplySLDURL(self, sld, -1, NULL);
+  return msSLDApplySLDURL(self, sld, -1, NULL, NULL);
 }
 
 char *mapObj_generateSLD(mapObj *self)
@@ -365,103 +419,118 @@ char *mapObj_generateSLD(mapObj *self)
 }
 
 
-int mapObj_loadOWSParameters(mapObj *self, cgiRequestObj *request, 
-                              char *wmtver_string)
+int mapObj_loadOWSParameters(mapObj *self, cgiRequestObj *request,
+                             char *wmtver_string)
 {
-    return msMapLoadOWSParameters(self, request, wmtver_string);
+  return msMapLoadOWSParameters(self, request, wmtver_string);
 }
 
 int mapObj_OWSDispatch(mapObj *self, cgiRequestObj *req )
 {
-    return msOWSDispatch( self, req, MS_TRUE);
+  return msOWSDispatch( self, req, MS_TRUE);
 }
 
 int mapObj_insertLayer(mapObj *self, layerObj *layer, int index)
 {
-    if (self && layer)
-      return msInsertLayer(self, layer, index);
+  if (self && layer)
+    return msInsertLayer(self, layer, index);
 
-    return -1;
+  return -1;
 }
 
 layerObj *mapObj_removeLayer(mapObj *self, int layerindex)
 {
-    return msRemoveLayer(self, layerindex);
+  return msRemoveLayer(self, layerindex);
 }
 
 int mapObj_setCenter(mapObj *self, pointObj *center)
 {
-    return msMapSetCenter(self, center);    
+  return msMapSetCenter(self, center);
 }
 
 int mapObj_offsetExtent(mapObj *self, double x, double y)
 {
-    return msMapOffsetExtent(self, x, y);    
+  return msMapOffsetExtent(self, x, y);
 }
 
-int mapObj_scaleExtent(mapObj *self, double zoomfactor, double minscaledenom, 
+int mapObj_scaleExtent(mapObj *self, double zoomfactor, double minscaledenom,
                        double maxscaledenom)
 {
-    return msMapScaleExtent(self, zoomfactor, minscaledenom, maxscaledenom);    
+  return msMapScaleExtent(self, zoomfactor, minscaledenom, maxscaledenom);
 }
 
 /**********************************************************************
  * class extensions for layerObj, always within the context of a map
  **********************************************************************/
-layerObj *layerObj_new(mapObj *map) {
-    if(msGrowMapLayers(map) == NULL)
-      return(NULL);
+layerObj *layerObj_new(mapObj *map)
+{
+  if(msGrowMapLayers(map) == NULL)
+    return(NULL);
 
-    if(initLayer((map->layers[map->numlayers]), map) == -1)
-      return(NULL);
+  if(initLayer((map->layers[map->numlayers]), map) == -1)
+    return(NULL);
 
-    map->layers[map->numlayers]->index = map->numlayers;
-    //Update the layer order list with the layer's index.
-    map->layerorder[map->numlayers] = map->numlayers;
+  map->layers[map->numlayers]->index = map->numlayers;
+  //Update the layer order list with the layer's index.
+  map->layerorder[map->numlayers] = map->numlayers;
 
-    map->numlayers++;
+  map->numlayers++;
 
-    return (map->layers[map->numlayers-1]);
+  return (map->layers[map->numlayers-1]);
+}
+
+void layerObj_destroy(layerObj *self)
+{
+  /* if the layer has a parent_map, let's the map object destroy it */
+  if ((self->map == NULL) && (self->refcount == 1)) {
+    /* if there is no other PHP Object that use this C layer object, delete it */
+    freeLayer(self);
+    free(self);
+    self = NULL;
+  } else {
+    MS_REFCNT_DECR(self);
   }
+  return;
+}
+
+layerObj *layerObj_clone(layerObj *layer)
+{
+  layerObj *dstLayer;
+  dstLayer = (layerObj *)malloc(sizeof(layerObj));
+  initLayer(dstLayer, layer->map);
+  msCopyLayer(dstLayer, layer);
+  return dstLayer;
+}
 
-void layerObj_destroy(layerObj *self) {
-   /* if the layer has a parent_map, let's the map object destroy it */
-   if ((self->map == NULL) && (self->refcount == 1)) {
-      /* if there is no other PHP Object that use this C layer object, delete it */
-         freeLayer(self);
-         free(self);
-         self = NULL;
-   } else 
-   {
-      MS_REFCNT_DECR(self);  
-   }
-   return;
+
+int layerObj_updateFromString(layerObj *self, char *snippet)
+{
+  return msUpdateLayerFromString(self, snippet, MS_FALSE);
 }
 
-int layerObj_updateFromString(layerObj *self, char *snippet) {
-   return msUpdateLayerFromString(self, snippet, MS_FALSE);
+int layerObj_open(layerObj *self)
+{
+  return msLayerOpen(self);
 }
 
-int layerObj_open(layerObj *self) {
-    return msLayerOpen(self);
-  }
 
+int layerObj_whichShapes(layerObj *self, rectObj *poRect)
+{
+  int oldconnectiontype = self->connectiontype;
+  self->connectiontype = MS_INLINE;
 
-int layerObj_whichShapes(layerObj *self, rectObj *poRect) {
-    int oldconnectiontype = self->connectiontype;
-    self->connectiontype = MS_INLINE;
-    
-    if(msLayerWhichItems(self, MS_FALSE, NULL) != MS_SUCCESS) {
-        self->connectiontype = oldconnectiontype;
-        return MS_FAILURE;
-    }
+  if(msLayerWhichItems(self, MS_FALSE, NULL) != MS_SUCCESS) {
     self->connectiontype = oldconnectiontype;
+    return MS_FAILURE;
+  }
+  self->connectiontype = oldconnectiontype;
 
-    return msLayerWhichShapes(self, *poRect, MS_FALSE);
+  return msLayerWhichShapes(self, *poRect, MS_FALSE);
 }
 
 
-shapeObj *layerObj_nextShape(layerObj *self) {
+shapeObj *layerObj_nextShape(layerObj *self)
+{
   int status;
   shapeObj *shape;
 
@@ -478,210 +547,280 @@ shapeObj *layerObj_nextShape(layerObj *self) {
     return shape;
 }
 
-void layerObj_close(layerObj *self) {
-    msLayerClose(self);
-  }
+void layerObj_close(layerObj *self)
+{
+  msLayerClose(self);
+}
 
-resultObj *layerObj_getResult(layerObj *self, int i) {
-    if(!self->resultcache) return NULL;
+resultObj *layerObj_getResult(layerObj *self, int i)
+{
+  if(!self->resultcache) return NULL;
 
-    if(i >= 0 && i < self->resultcache->numresults)
-      return &self->resultcache->results[i]; 
-    else
-      return NULL;
-  }
+  if(i >= 0 && i < self->resultcache->numresults)
+    return &self->resultcache->results[i];
+  else
+    return NULL;
+}
 
-classObj *layerObj_getClass(layerObj *self, int i) { // returns an EXISTING class
-    if(i >= 0 && i < self->numclasses)
-      return (self->class[i]); 
-    else
-      return(NULL);
-  }
+classObj *layerObj_getClass(layerObj *self, int i)   // returns an EXISTING class
+{
+  if(i >= 0 && i < self->numclasses)
+    return (self->class[i]);
+  else
+    return(NULL);
+}
 
-int layerObj_getClassIndex(layerObj *self, mapObj *map, shapeObj *shape, 
-                           int *classgroup, int numclasses) {
-    return msShapeGetClass(self, map, shape, classgroup, numclasses);
+int layerObj_getClassIndex(layerObj *self, mapObj *map, shapeObj *shape,
+                           int *classgroup, int numclasses)
+{
+  return msShapeGetClass(self, map, shape, classgroup, numclasses);
 }
 
-int layerObj_draw(layerObj *self, mapObj *map, imageObj *img) {
-    return msDrawLayer(map, self, img);
-  }
+int layerObj_draw(layerObj *self, mapObj *map, imageObj *img)
+{
+  return msDrawLayer(map, self, img);
+}
 
-int layerObj_drawQuery(layerObj *self, mapObj *map, imageObj *img) {
-    return msDrawQueryLayer(map, self, img);    
-  }
+int layerObj_drawQuery(layerObj *self, mapObj *map, imageObj *img)
+{
+  return msDrawQueryLayer(map, self, img);
+}
+
+int layerObj_queryByAttributes(layerObj *self, mapObj *map, char *qitem, char *qstring, int mode)
+{
+  int status;
+  int retval;
 
-int layerObj_queryByAttributes(layerObj *self, mapObj *map, char *qitem, char *qstring, int mode) {
-    int status;
-    int retval;
+  msInitQuery(&(map->query));
 
-    msInitQuery(&(map->query));
+  map->query.type = MS_QUERY_BY_ATTRIBUTE;
+  map->query.mode = mode;
+  if(qitem) map->query.item = strdup(qitem);
+  if(qstring) map->query.str = strdup(qstring);
+  map->query.layer = self->index;
+  map->query.rect = map->extent;
 
-    map->query.type = MS_QUERY_BY_ATTRIBUTE;
-    map->query.mode = mode;
-    if(qitem) map->query.item = strdup(qitem);
-    if(qstring) map->query.str = strdup(qstring);
-    map->query.layer = self->index;
-    map->query.rect = map->extent;        
+  status = self->status;
+  self->status = MS_ON;
+  retval = msQueryByAttributes(map);
+  self->status = status;
 
-    status = self->status;
-    self->status = MS_ON;
-    retval = msQueryByAttributes(map);
-    self->status = status;
+  return retval;
+}
 
-    return retval;
-  }
+int layerObj_queryByPoint(layerObj *self, mapObj *map, pointObj *point, int mode, double buffer)
+{
+  int status;
+  int retval;
 
-int layerObj_queryByPoint(layerObj *self, mapObj *map, pointObj *point, int mode, double buffer) {
-    int status;
-    int retval;
+  msInitQuery(&(map->query));
 
-    msInitQuery(&(map->query));
+  map->query.type = MS_QUERY_BY_POINT;
+  map->query.mode = mode;
+  map->query.point = *point;
+  map->query.buffer = buffer;
+  map->query.layer = self->index;
 
-    map->query.type = MS_QUERY_BY_POINT;
-    map->query.mode = mode;
-    map->query.point = *point;
-    map->query.buffer = buffer;
-    map->query.layer = self->index;
+  status = self->status;
+  self->status = MS_ON;
+  retval = msQueryByPoint(map);
+  self->status = status;
 
-    status = self->status;
-    self->status = MS_ON;
-    retval = msQueryByPoint(map);
-    self->status = status;
+  return retval;
+}
 
-    return retval;
-  }
+int layerObj_queryByRect(layerObj *self, mapObj *map, rectObj rect)
+{
+  int status;
+  int retval;
 
-int layerObj_queryByRect(layerObj *self, mapObj *map, rectObj rect) {
-    int status;
-    int retval;
+  msInitQuery(&(map->query));
 
-    msInitQuery(&(map->query));
+  map->query.type = MS_QUERY_BY_RECT;
+  map->query.mode = MS_QUERY_MULTIPLE;
+  map->query.rect = rect;
+  map->query.layer = self->index;
 
-    map->query.type = MS_QUERY_BY_RECT;
-    map->query.mode = MS_QUERY_MULTIPLE;
-    map->query.rect = rect;
-    map->query.layer = self->index;
+  status = self->status;
+  self->status = MS_ON;
+  retval = msQueryByRect(map);
+  self->status = status;
 
-    status = self->status;
-    self->status = MS_ON;
-    retval = msQueryByRect(map);
-    self->status = status;
+  return retval;
+}
 
-    return retval;
-  }
+int layerObj_queryByFeatures(layerObj *self, mapObj *map, int slayer)
+{
+  int status;
+  int retval;
 
-int layerObj_queryByFeatures(layerObj *self, mapObj *map, int slayer) {
-    int status;
-    int retval;
+  map->query.slayer = slayer;
+  map->query.layer = self->index;
 
-    map->query.slayer = slayer;
-    map->query.layer = self->index;
+  status = self->status;
+  self->status = MS_ON;
+  retval = msQueryByFeatures(map);
+  self->status = status;
 
-    status = self->status;
-    self->status = MS_ON;
-    retval = msQueryByFeatures(map);
-    self->status = status;
+  return retval;
+}
 
-    return retval;
-  }
+int layerObj_queryByShape(layerObj *self, mapObj *map, shapeObj *shape)
+{
+  int status;
+  int retval;
 
-int layerObj_queryByShape(layerObj *self, mapObj *map, shapeObj *shape) {
-    int status;
-    int retval;
+  msInitQuery(&(map->query));
 
-    msInitQuery(&(map->query));
+  map->query.type = MS_QUERY_BY_SHAPE;
+  map->query.mode = MS_QUERY_MULTIPLE;
+  map->query.shape = (shapeObj *) malloc(sizeof(shapeObj));
+  msInitShape(map->query.shape);
+  msCopyShape(shape, map->query.shape);
+  map->query.layer = self->index;
 
-    map->query.type = MS_QUERY_BY_SHAPE;
-    map->query.mode = MS_QUERY_MULTIPLE;
-    map->query.shape = (shapeObj *) malloc(sizeof(shapeObj));
-    msInitShape(map->query.shape);
-    msCopyShape(shape, map->query.shape);
-    map->query.layer = self->index;
+  status = self->status;
+  self->status = MS_ON;
+  retval = msQueryByShape(map);
+  self->status = status;
 
-    status = self->status;
-    self->status = MS_ON;
-    retval = msQueryByShape(map);
-    self->status = status;
+  return retval;
+}
 
-    return retval;
-  }
+int layerObj_queryByFilter(layerObj *self, mapObj *map, char *string)
+{
+  int status;
+  int retval;
 
-int layerObj_setFilter(layerObj *self, char *string) {
-    if (!string || strlen(string) == 0) {
-        freeExpression(&self->filter);
-        return MS_SUCCESS;
-    }
-    else return msLoadExpressionString(&self->filter, string);
-  }
+  msInitQuery(&(map->query));
 
-char *layerObj_getFilter(layerObj *self) {
-    return msGetExpressionString(&(self->filter));
-  }
+  map->query.type = MS_QUERY_BY_FILTER;
 
-int layerObj_setWKTProjection(layerObj *self, char *string) {
-    self->project = MS_TRUE;
-    return msOGCWKT2ProjectionObj(string, &(self->projection), self->debug);
-  }
+  map->query.filter = (expressionObj *) malloc(sizeof(expressionObj));
+  map->query.filter->string = strdup(string);
+  map->query.filter->type = 2000; /* MS_EXPRESSION: lot's of conflicts in mapfile.h */
+  map->query.filter->compiled = MS_FALSE;
+  map->query.filter->flags = 0;
+  map->query.filter->tokens = map->query.filter->curtoken = NULL;
+
+  map->query.layer = self->index;
+  map->query.rect = map->extent;
+
+  status = self->status;
+  self->status = MS_ON;
+  retval = msQueryByFilter(map);
+  self->status = status;
+
+  return retval;
+}
+
+int layerObj_queryByIndex(layerObj *self, mapObj *map, int tileindex, int shapeindex, int addtoquery)
+{
+  int status;
+  int retval;
+
+  msInitQuery(&(map->query));
+
+  map->query.type = MS_QUERY_BY_INDEX;
+  map->query.mode = MS_QUERY_SINGLE;
+  map->query.tileindex = tileindex;
+  map->query.shapeindex = shapeindex;
+  map->query.clear_resultcache = !addtoquery;
+  map->query.layer = self->index;
+
+  status = self->status;
+  self->status = MS_ON;
+  retval = msQueryByIndex(map);
+  self->status = status;
 
-char *layerObj_getProjection(layerObj* self) {
-    return msGetProjectionString(&self->projection);
- }
+  return retval;
+}
+
+int layerObj_setFilter(layerObj *self, char *string)
+{
+  if (!string || strlen(string) == 0) {
+    freeExpression(&self->filter);
+    return MS_SUCCESS;
+  } else return msLoadExpressionString(&self->filter, string);
+}
+
+char *layerObj_getFilter(layerObj *self)
+{
+  return msGetExpressionString(&(self->filter));
+}
 
-int layerObj_setProjection(layerObj *self, char *string) {
+int layerObj_setWKTProjection(layerObj *self, char *string)
+{
+  self->project = MS_TRUE;
+  return msOGCWKT2ProjectionObj(string, &(self->projection), self->debug);
+}
+
+char *layerObj_getProjection(layerObj* self)
+{
+  return msGetProjectionString(&self->projection);
+}
+
+int layerObj_setProjection(layerObj *self, char *string)
+{
   int nReturn;
   nReturn = msLoadProjectionString(&(self->projection), string);
   if (nReturn == MS_SUCCESS)
     self->project = MS_TRUE;
   return nReturn;
 
-  }
+}
 
-int layerObj_addFeature(layerObj *self, shapeObj *shape) {
-    if(self->features != NULL && self->features->tailifhead != NULL) 
-          shape->index = self->features->tailifhead->shape.index + 1;
-      else 
-          shape->index = 0;
-    if(insertFeatureList(&(self->features), shape) == NULL) 
-      return MS_FAILURE;
-    else
-      return MS_SUCCESS;
-  }
+int layerObj_addFeature(layerObj *self, shapeObj *shape)
+{
+  if(self->features != NULL && self->features->tailifhead != NULL)
+    shape->index = self->features->tailifhead->shape.index + 1;
+  else
+    shape->index = 0;
+  if(insertFeatureList(&(self->features), shape) == NULL)
+    return MS_FAILURE;
+  else
+    return MS_SUCCESS;
+}
 
-char *layerObj_getMetaData(layerObj *self, char *name) {
-    return(msLookupHashTable(&(self->metadata), name));
-  }
+char *layerObj_getMetaData(layerObj *self, char *name)
+{
+  return(msLookupHashTable(&(self->metadata), name));
+}
 
 
-int layerObj_setMetaData(layerObj *self, char *name, char *value) {
-    if (msInsertHashTable(&(self->metadata), name, value) == NULL)
-	return MS_FAILURE;
-    return MS_SUCCESS;
-  }
+int layerObj_setMetaData(layerObj *self, char *name, char *value)
+{
+  if (msInsertHashTable(&(self->metadata), name, value) == NULL)
+    return MS_FAILURE;
+  return MS_SUCCESS;
+}
 
-int layerObj_removeMetaData(layerObj *self, char *name) {
-    return(msRemoveHashTable(&(self->metadata), name));
-  }
+int layerObj_removeMetaData(layerObj *self, char *name)
+{
+  return(msRemoveHashTable(&(self->metadata), name));
+}
 
-char *layerObj_getWMSFeatureInfoURL(layerObj *self, mapObj *map, int click_x, int click_y,     
-                                    int feature_count, char *info_format) {
-    // NOTE: the returned string should be freed by the caller but right 
-    // now we're leaking it.
-    return(msWMSGetFeatureInfoURL(map, self, click_x, click_y,
-                                  feature_count, info_format));
-  }
+char *layerObj_getWMSFeatureInfoURL(layerObj *self, mapObj *map, int click_x, int click_y,
+                                    int feature_count, char *info_format)
+{
+  // NOTE: the returned string should be freed by the caller but right
+  // now we're leaking it.
+  return(msWMSGetFeatureInfoURL(map, self, click_x, click_y,
+                                feature_count, info_format));
+}
 
-char *layerObj_executeWFSGetFeature(layerObj *self) {
+char *layerObj_executeWFSGetFeature(layerObj *self)
+{
   return (msWFSExecuteGetFeature(self));
 }
 
 int layerObj_applySLD(layerObj *self, char *sld, char *stylelayer)
 {
-    return msSLDApplySLD(self->map, sld, self->index, stylelayer);
+  return msSLDApplySLD(self->map, sld, self->index, stylelayer, NULL);
 }
 int layerObj_applySLDURL(layerObj *self, char *sld, char *stylelayer)
 {
-    return msSLDApplySLDURL(self->map, sld, self->index, stylelayer);
+  return msSLDApplySLDURL(self->map, sld, self->index, stylelayer, NULL);
 }
 
 char *layerObj_generateSLD(layerObj *self)
@@ -691,745 +830,880 @@ char *layerObj_generateSLD(layerObj *self)
 
 int layerObj_moveClassUp(layerObj *self, int index)
 {
-    return msMoveClassUp(self, index);
+  return msMoveClassUp(self, index);
 }
 
 int layerObj_moveClassDown(layerObj *self, int index)
 {
-    return msMoveClassDown(self, index);
+  return msMoveClassDown(self, index);
 }
 
 classObj *layerObj_removeClass(layerObj *self, int index)
 {
-    return msRemoveClass(self, index);
+  return msRemoveClass(self, index);
 }
 
-int layerObj_setConnectionType(layerObj *self, int connectiontype, 
-                               const char *library_str) 
+int layerObj_setConnectionType(layerObj *self, int connectiontype,
+                               const char *library_str)
 {
-    /* Caller is responsible to close previous layer correctly before calling
-     * msConnectLayer() 
-     */
-    if (msLayerIsOpen(self))
-        msLayerClose(self);
+  /* Caller is responsible to close previous layer correctly before calling
+   * msConnectLayer()
+   */
+  if (msLayerIsOpen(self))
+    msLayerClose(self);
 
-    return msConnectLayer(self, connectiontype, library_str);
+  return msConnectLayer(self, connectiontype, library_str);
 }
 
 /**********************************************************************
  * class extensions for labelObj
  **********************************************************************/
-int labelObj_updateFromString(labelObj *self, char *snippet) {
-   return msUpdateLabelFromString(self, snippet);
+labelObj *labelObj_new()
+{
+  labelObj *label;
+
+  label = (labelObj *)malloc(sizeof(labelObj));
+  if(!label)
+    return(NULL);
+
+  initLabel(label);
+
+  return label;
+}
+
+void labelObj_destroy(labelObj *self)
+{
+  if (freeLabel(self) == MS_SUCCESS)
+    free(self);
+
+}
+
+labelObj *labelObj_clone(labelObj *label)
+{
+  labelObj *dstLabel;
+  dstLabel = (labelObj *)malloc(sizeof(labelObj));
+  initLabel(dstLabel);
+  dstLabel->font = NULL;
+  msCopyLabel(dstLabel, label);
+
+  return dstLabel;
+}
+
+int labelObj_updateFromString(labelObj *self, char *snippet)
+{
+  return msUpdateLabelFromString(self, snippet);
 }
 
 int labelObj_moveStyleUp(labelObj *self, int index)
 {
-    return msMoveLabelStyleUp(self, index);
+  return msMoveLabelStyleUp(self, index);
 }
 
 int labelObj_moveStyleDown(labelObj *self, int index)
 {
-    return msMoveLabelStyleDown(self, index);
+  return msMoveLabelStyleDown(self, index);
 }
 
 int labelObj_deleteStyle(labelObj *self, int index)
 {
-    return msDeleteLabelStyle(self, index);
+  return msDeleteLabelStyle(self, index);
 }
 
 /**********************************************************************
  * class extensions for legendObj
  **********************************************************************/
-int legendObj_updateFromString(legendObj *self, char *snippet) {
-   return msUpdateLegendFromString(self, snippet, MS_FALSE);
+int legendObj_updateFromString(legendObj *self, char *snippet)
+{
+  return msUpdateLegendFromString(self, snippet, MS_FALSE);
 }
 
 /**********************************************************************
  * class extensions for queryMapObj
  **********************************************************************/
-int queryMapObj_updateFromString(queryMapObj *self, char *snippet) {
-   return msUpdateQueryMapFromString(self, snippet, MS_FALSE);
+int queryMapObj_updateFromString(queryMapObj *self, char *snippet)
+{
+  return msUpdateQueryMapFromString(self, snippet, MS_FALSE);
 }
 
 /**********************************************************************
  * class extensions for referenceMapObj
  **********************************************************************/
 
-int referenceMapObj_updateFromString(referenceMapObj *self, char *snippet) {
-   return msUpdateReferenceMapFromString(self, snippet, MS_FALSE);
+int referenceMapObj_updateFromString(referenceMapObj *self, char *snippet)
+{
+  return msUpdateReferenceMapFromString(self, snippet, MS_FALSE);
 }
 
 /**********************************************************************
  * class extensions for scaleBarObj
  **********************************************************************/
 
-int scalebarObj_updateFromString(scalebarObj *self, char *snippet) {
-   return msUpdateScalebarFromString(self, snippet, MS_FALSE);
+int scalebarObj_updateFromString(scalebarObj *self, char *snippet)
+{
+  return msUpdateScalebarFromString(self, snippet, MS_FALSE);
 }
 
 /**********************************************************************
  * class extensions for webObj
  **********************************************************************/
 
-int webObj_updateFromString(webObj *self, char *snippet) {
-   return msUpdateWebFromString(self, snippet, MS_FALSE);
+int webObj_updateFromString(webObj *self, char *snippet)
+{
+  return msUpdateWebFromString(self, snippet, MS_FALSE);
 }
 
 /**********************************************************************
  * class extensions for classObj, always within the context of a layer
  **********************************************************************/
-classObj *classObj_new(layerObj *layer, classObj *class) {
-    if(msGrowLayerClasses(layer) == NULL)
-      return NULL;
-
-    if(initClass((layer->class[layer->numclasses])) == -1)
-      return NULL;
+classObj *classObj_new(layerObj *layer, classObj *class)
+{
+  if(msGrowLayerClasses(layer) == NULL)
+    return NULL;
 
-    if (class){
-      msCopyClass((layer->class[layer->numclasses]), class, layer);
-      layer->class[layer->numclasses]->layer = layer;
-    }
+  if(initClass((layer->class[layer->numclasses])) == -1)
+    return NULL;
 
-    layer->class[layer->numclasses]->type = layer->type;
+  if (class) {
+    msCopyClass((layer->class[layer->numclasses]), class, layer);
     layer->class[layer->numclasses]->layer = layer;
+  }
 
-    layer->numclasses++;
+  layer->class[layer->numclasses]->type = layer->type;
+  layer->class[layer->numclasses]->layer = layer;
 
-    return (layer->class[layer->numclasses-1]);
-  }
+  layer->numclasses++;
 
-int classObj_updateFromString(classObj *self, char *snippet) {
-   return msUpdateClassFromString(self, snippet, MS_FALSE);
+  return (layer->class[layer->numclasses-1]);
 }
 
-void  classObj_destroy(classObj *self) {
-    return; /* do nothing, map deconstrutor takes care of it all */
-  }
+int classObj_addLabel(classObj *self, labelObj *label)
+{
+  return msAddLabelToClass(self, label);
+}
 
-int classObj_setExpression(classObj *self, char *string) {
-    if (!string || strlen(string) == 0) {
-        freeExpression(&self->expression);
-        return MS_SUCCESS;
-    }
-    else return msLoadExpressionString(&self->expression, string);
-  }
+labelObj *classObj_removeLabel(classObj *self, int index)
+{
+  return msRemoveLabelFromClass(self, index);
+}
 
-char *classObj_getExpressionString(classObj *self) {
-    return msGetExpressionString(&(self->expression));
+labelObj *classObj_getLabel(classObj *self, int i)   // returns an EXISTING label
+{
+  if(i >= 0 && i < self->numlabels)
+    return (self->labels[i]);
+  else
+    return(NULL);
 }
 
-int classObj_setText(classObj *self, layerObj *layer, char *string) {
-    if (!string || strlen(string) == 0) {
-        freeExpression(&self->text);
-        return MS_SUCCESS;
-    }
-    return msLoadExpressionString(&self->text, string);
+int classObj_updateFromString(classObj *self, char *snippet)
+{
+  return msUpdateClassFromString(self, snippet, MS_FALSE);
 }
 
-char *classObj_getTextString(classObj *self) {
-    return msGetExpressionString(&(self->text));
+void  classObj_destroy(classObj *self)
+{
+  return; /* do nothing, map deconstrutor takes care of it all */
 }
 
-int classObj_drawLegendIcon(classObj *self, mapObj *map, layerObj *layer, int width, int height, imageObj *dstImg, int dstX, int dstY) {
-  msClearLayerPenValues(layer); // just in case the mapfile has already been processed
-    return msDrawLegendIcon(map, layer, self, width, height, dstImg, dstX, dstY);
+int classObj_setExpression(classObj *self, char *string)
+{
+  if (!string || strlen(string) == 0) {
+    freeExpression(&self->expression);
+    return MS_SUCCESS;
+  } else return msLoadExpressionString(&self->expression, string);
+}
+
+char *classObj_getExpressionString(classObj *self)
+{
+  return msGetExpressionString(&(self->expression));
 }
 
-imageObj *classObj_createLegendIcon(classObj *self, mapObj *map, layerObj *layer, int width, int height) {
-    return msCreateLegendIcon(map, layer, self, width, height);
+int classObj_setText(classObj *self, layerObj *layer, char *string)
+{
+  if (!string || strlen(string) == 0) {
+    freeExpression(&self->text);
+    return MS_SUCCESS;
   }
+  return msLoadExpressionString(&self->text, string);
+}
+
+char *classObj_getTextString(classObj *self)
+{
+  return msGetExpressionString(&(self->text));
+}
+
+int classObj_drawLegendIcon(classObj *self, mapObj *map, layerObj *layer, int width, int height, imageObj *dstImg, int dstX, int dstY)
+{
+  msClearLayerPenValues(layer); // just in case the mapfile has already been processed
+  return msDrawLegendIcon(map, layer, self, width, height, dstImg, dstX, dstY);
+}
+
+imageObj *classObj_createLegendIcon(classObj *self, mapObj *map, layerObj *layer, int width, int height)
+{
+  return msCreateLegendIcon(map, layer, self, width, height);
+}
 
 
-int classObj_setSymbolByName(classObj *self, mapObj *map, char* pszSymbolName) {
+int classObj_setSymbolByName(classObj *self, mapObj *map, char* pszSymbolName)
+{
   /*
    self->symbol = msGetSymbolIndex(&map->symbolset, pszSymbolName, MS_TRUE);
     return self->symbol;
   */
   return -1;
 }
-  
-int classObj_setOverlaySymbolByName(classObj *self, mapObj *map, char* pszOverlaySymbolName) {
+
+int classObj_setOverlaySymbolByName(classObj *self, mapObj *map, char* pszOverlaySymbolName)
+{
   /*
     self->overlaysymbol = msGetSymbolIndex(&map->symbolset, pszOverlaySymbolName, MS_TRUE);
     return self->overlaysymbol;
   */
   return -1;
 
-  }
+}
 
 classObj *classObj_clone(classObj *class, layerObj *layer)
 {
-    classObj *dstClass;
-    dstClass = (classObj *)malloc(sizeof(classObj));
-    
-    initClass(dstClass);
-    msCopyClass(dstClass, class, layer);
+  classObj *dstClass;
+  dstClass = (classObj *)malloc(sizeof(classObj));
 
-    dstClass->type = layer->type;
+  initClass(dstClass);
+  msCopyClass(dstClass, class, layer);
 
-    return dstClass;
+  dstClass->type = layer->type;
+
+  return dstClass;
 }
 
 int classObj_moveStyleUp(classObj *self, int index)
 {
-    return msMoveStyleUp(self, index);
+  return msMoveStyleUp(self, index);
 }
 
 int classObj_moveStyleDown(classObj *self, int index)
 {
-    return msMoveStyleDown(self, index);
+  return msMoveStyleDown(self, index);
 }
 
 int classObj_deleteStyle(classObj *self, int index)
 {
-    return msDeleteStyle(self, index);
+  return msDeleteStyle(self, index);
 }
 
 /**********************************************************************
  * class extensions for pointObj, useful many places
  **********************************************************************/
-pointObj *pointObj_new() {
-    return (pointObj *)malloc(sizeof(pointObj));
-  }
+pointObj *pointObj_new()
+{
+  return (pointObj *)malloc(sizeof(pointObj));
+}
 
-void pointObj_destroy(pointObj *self) {
-    free(self);
-  }
+void pointObj_destroy(pointObj *self)
+{
+  free(self);
+}
 
-int pointObj_project(pointObj *self, projectionObj *in, projectionObj *out) {
-    return msProjectPoint(in, out, self);
-  }	
+int pointObj_project(pointObj *self, projectionObj *in, projectionObj *out)
+{
+  return msProjectPoint(in, out, self);
+}
 
-int pointObj_draw(pointObj *self, mapObj *map, layerObj *layer, 
-                  imageObj *img, int class_index, char *label_string) {
-    return msDrawPoint(map, layer, self, img, class_index, label_string);
-  }
+int pointObj_draw(pointObj *self, mapObj *map, layerObj *layer,
+                  imageObj *img, int class_index, char *label_string)
+{
+  return msDrawPoint(map, layer, self, img, class_index, label_string);
+}
 
-double pointObj_distanceToPoint(pointObj *self, pointObj *point) {
-    return msDistancePointToPoint(self, point);
-  }
+double pointObj_distanceToPoint(pointObj *self, pointObj *point)
+{
+  return msDistancePointToPoint(self, point);
+}
 
-double pointObj_distanceToLine(pointObj *self, pointObj *a, pointObj *b) {
-    return msDistancePointToSegment(self, a, b);
-  }
+double pointObj_distanceToLine(pointObj *self, pointObj *a, pointObj *b)
+{
+  return msDistancePointToSegment(self, a, b);
+}
 
-double pointObj_distanceToShape(pointObj *self, shapeObj *shape) {
-   return msDistancePointToShape(self, shape);
-  }
+double pointObj_distanceToShape(pointObj *self, shapeObj *shape)
+{
+  return msDistancePointToShape(self, shape);
+}
 
 /**********************************************************************
- * class extensions for lineObj (eg. a line or group of points), 
+ * class extensions for lineObj (eg. a line or group of points),
  * useful many places
  **********************************************************************/
-lineObj *lineObj_new() {
-    lineObj *line;
+lineObj *lineObj_new()
+{
+  lineObj *line;
 
-    line = (lineObj *)malloc(sizeof(lineObj));
-    if(!line)
-      return(NULL);
+  line = (lineObj *)malloc(sizeof(lineObj));
+  if(!line)
+    return(NULL);
 
-    line->numpoints=0;
-    line->point=NULL;
+  line->numpoints=0;
+  line->point=NULL;
 
-    return line;
-  }
+  return line;
+}
 
-void lineObj_destroy(lineObj *self) {
-    free(self->point);
-    free(self);		
-  }
+void lineObj_destroy(lineObj *self)
+{
+  free(self->point);
+  free(self);
+}
 
-int lineObj_project(lineObj *self, projectionObj *in, projectionObj *out) {
-    return msProjectLine(in, out, self);
-  }
+lineObj *lineObj_clone(lineObj *line)
+{
+  lineObj *dstLine;
+  dstLine = (lineObj *)malloc(sizeof(lineObj));
+  dstLine->numpoints= line->numpoints;
+  dstLine->point = (pointObj *)malloc(sizeof(pointObj)*(dstLine->numpoints));
+  msCopyLine(dstLine, line);
 
-pointObj *lineObj_get(lineObj *self, int i) {
-    if(i<0 || i>=self->numpoints)
-      return NULL;
-    else
-      return &(self->point[i]);
-  }
 
-int lineObj_add(lineObj *self, pointObj *p) {
-    if(self->numpoints == 0) { /* new */	
-      self->point = (pointObj *)malloc(sizeof(pointObj));      
-      if(!self->point)
-	return MS_FAILURE;
-    } else { /* extend array */
-      self->point = (pointObj *)realloc(self->point, sizeof(pointObj)*(self->numpoints+1));
-      if(!self->point)
-	return MS_FAILURE;
-    }
+  return dstLine;
+}
+
+int lineObj_project(lineObj *self, projectionObj *in, projectionObj *out)
+{
+  return msProjectLine(in, out, self);
+}
+
+pointObj *lineObj_get(lineObj *self, int i)
+{
+  if(i<0 || i>=self->numpoints)
+    return NULL;
+  else
+    return &(self->point[i]);
+}
+
+int lineObj_add(lineObj *self, pointObj *p)
+{
+  if(self->numpoints == 0) { /* new */
+    self->point = (pointObj *)malloc(sizeof(pointObj));
+    if(!self->point)
+      return MS_FAILURE;
+  } else { /* extend array */
+    self->point = (pointObj *)realloc(self->point, sizeof(pointObj)*(self->numpoints+1));
+    if(!self->point)
+      return MS_FAILURE;
+  }
 
-    self->point[self->numpoints].x = p->x;
-    self->point[self->numpoints].y = p->y;
+  self->point[self->numpoints].x = p->x;
+  self->point[self->numpoints].y = p->y;
 #ifdef USE_POINT_Z_M
-    self->point[self->numpoints].m = p->m;
+  self->point[self->numpoints].m = p->m;
 #endif
-    self->numpoints++;
+  self->numpoints++;
 
-    return MS_SUCCESS;
-  }
+  return MS_SUCCESS;
+}
 
 
 /**********************************************************************
  * class extensions for shapeObj
  **********************************************************************/
-shapeObj *shapeObj_new(int type) {
-    shapeObj *shape;
+shapeObj *shapeObj_new(int type)
+{
+  shapeObj *shape;
 
-    shape = (shapeObj *)malloc(sizeof(shapeObj));
-    if(!shape)
-      return NULL;
+  shape = (shapeObj *)malloc(sizeof(shapeObj));
+  if(!shape)
+    return NULL;
 
-    msInitShape(shape);
-    shape->type = type;
-    return shape;
-  }
+  msInitShape(shape);
+  shape->type = type;
+  return shape;
+}
 
-void shapeObj_destroy(shapeObj *self) {
-    msFreeShape(self);
-    free(self);		
-  }
+void shapeObj_destroy(shapeObj *self)
+{
+  msFreeShape(self);
+  free(self);
+}
 
-int shapeObj_project(shapeObj *self, projectionObj *in, projectionObj *out) {
-    return msProjectShape(in, out, self);
-  }
+int shapeObj_project(shapeObj *self, projectionObj *in, projectionObj *out)
+{
+  return msProjectShape(in, out, self);
+}
 
-lineObj *shapeObj_get(shapeObj *self, int i) {
-    if(i<0 || i>=self->numlines)
-      return NULL;
-    else
-      return &(self->line[i]);
-  }
+lineObj *shapeObj_get(shapeObj *self, int i)
+{
+  if(i<0 || i>=self->numlines)
+    return NULL;
+  else
+    return &(self->line[i]);
+}
 
-int shapeObj_add(shapeObj *self, lineObj *line) {
-    return msAddLine(self, line);
-  }
+int shapeObj_add(shapeObj *self, lineObj *line)
+{
+  return msAddLine(self, line);
+}
 
-int shapeObj_draw(shapeObj *self, mapObj *map, layerObj *layer, 
-                  imageObj *img) {
-    return msDrawShape(map, layer, self, img, -1, MS_FALSE);
-  }
+int shapeObj_draw(shapeObj *self, mapObj *map, layerObj *layer,
+                  imageObj *img)
+{
+  return msDrawShape(map, layer, self, img, -1, MS_DRAWMODE_FEATURES|MS_DRAWMODE_LABELS);
+}
 
-void shapeObj_setBounds(shapeObj *self) {
-    int i, j;
-
-    self->bounds.minx = self->bounds.maxx = self->line[0].point[0].x;
-    self->bounds.miny = self->bounds.maxy = self->line[0].point[0].y;
-    
-    for( i=0; i<self->numlines; i++ ) {
-      for( j=0; j<self->line[i].numpoints; j++ ) {
-	self->bounds.minx = MS_MIN(self->bounds.minx, self->line[i].point[j].x);
-	self->bounds.maxx = MS_MAX(self->bounds.maxx, self->line[i].point[j].x);
-	self->bounds.miny = MS_MIN(self->bounds.miny, self->line[i].point[j].y);
-	self->bounds.maxy = MS_MAX(self->bounds.maxy, self->line[i].point[j].y);
-      }
-    }
+void shapeObj_setBounds(shapeObj *self)
+{
+  int i, j;
 
-    return;
-  }
+  self->bounds.minx = self->bounds.maxx = self->line[0].point[0].x;
+  self->bounds.miny = self->bounds.maxy = self->line[0].point[0].y;
 
-int shapeObj_copy(shapeObj *self, shapeObj *dest) {
-    return(msCopyShape(self, dest));
+  for( i=0; i<self->numlines; i++ ) {
+    for( j=0; j<self->line[i].numpoints; j++ ) {
+      self->bounds.minx = MS_MIN(self->bounds.minx, self->line[i].point[j].x);
+      self->bounds.maxx = MS_MAX(self->bounds.maxx, self->line[i].point[j].x);
+      self->bounds.miny = MS_MIN(self->bounds.miny, self->line[i].point[j].y);
+      self->bounds.maxy = MS_MAX(self->bounds.maxy, self->line[i].point[j].y);
+    }
   }
 
-int shapeObj_contains(shapeObj *self, pointObj *point) {
-    if(self->type == MS_SHAPE_POLYGON)
-      return msIntersectPointPolygon(point, self);
+  return;
+}
 
-    return -1;
-  }
+int shapeObj_copy(shapeObj *self, shapeObj *dest)
+{
+  return(msCopyShape(self, dest));
+}
+
+int shapeObj_contains(shapeObj *self, pointObj *point)
+{
+  if(self->type == MS_SHAPE_POLYGON)
+    return msIntersectPointPolygon(point, self);
 
-int shapeObj_intersects(shapeObj *self, shapeObj *shape) {
-    switch(self->type) {
+  return -1;
+}
+
+int shapeObj_intersects(shapeObj *self, shapeObj *shape)
+{
+  switch(self->type) {
     case(MS_SHAPE_LINE):
       switch(shape->type) {
-      case(MS_SHAPE_LINE):
-	return msIntersectPolylines(self, shape);
-      case(MS_SHAPE_POLYGON):
-	return msIntersectPolylinePolygon(self, shape);
+        case(MS_SHAPE_LINE):
+          return msIntersectPolylines(self, shape);
+        case(MS_SHAPE_POLYGON):
+          return msIntersectPolylinePolygon(self, shape);
       }
       break;
     case(MS_SHAPE_POLYGON):
       switch(shape->type) {
-      case(MS_SHAPE_LINE):
-	return msIntersectPolylinePolygon(shape, self);
-      case(MS_SHAPE_POLYGON):
-	return msIntersectPolygons(self, shape);
+        case(MS_SHAPE_LINE):
+          return msIntersectPolylinePolygon(shape, self);
+        case(MS_SHAPE_POLYGON):
+          return msIntersectPolygons(self, shape);
       }
       break;
-    }
-
-    return -1;
   }
 
-pointObj *shapeObj_getpointusingmeasure(shapeObj *self, double m) 
-{       
-   if (self)
-     return msGetPointUsingMeasure(self, m);
-   
-   return NULL;
+  return -1;
+}
+
+pointObj *shapeObj_getpointusingmeasure(shapeObj *self, double m)
+{
+  if (self)
+    return msGetPointUsingMeasure(self, m);
+
+  return NULL;
 }
 
-pointObj *shapeObj_getmeasureusingpoint(shapeObj *self, pointObj *point) 
-{       
-   if (self)
-     return msGetMeasureUsingPoint(self, point);
-   
-   return NULL;
+pointObj *shapeObj_getmeasureusingpoint(shapeObj *self, pointObj *point)
+{
+  if (self)
+    return msGetMeasureUsingPoint(self, point);
+
+  return NULL;
 }
 
 
 shapeObj *shapeObj_buffer(shapeObj *self, double width)
 {
-    return msGEOSBuffer(self, width);
+  return msGEOSBuffer(self, width);
 }
 
 
 shapeObj *shapeObj_simplify(shapeObj *self, double tolerance)
 {
-    return msGEOSSimplify(self, tolerance);
+  return msGEOSSimplify(self, tolerance);
 }
 
 
 shapeObj *shapeObj_topologypreservingsimplify(shapeObj *self, double tolerance)
 {
-    return msGEOSTopologyPreservingSimplify(self, tolerance);
+  return msGEOSTopologyPreservingSimplify(self, tolerance);
 }
 
- 
+
 shapeObj *shapeObj_convexHull(shapeObj *self)
 {
-    return msGEOSConvexHull(self);
+  return msGEOSConvexHull(self);
 }
 
 shapeObj *shapeObj_boundary(shapeObj *self)
 {
-    return msGEOSBoundary(self);
+  return msGEOSBoundary(self);
 }
 
 int shapeObj_contains_geos(shapeObj *self, shapeObj *shape)
 {
-    return msGEOSContains(self, shape);
+  return msGEOSContains(self, shape);
 }
 
 shapeObj *shapeObj_Union(shapeObj *self, shapeObj *shape)
 {
-     return msGEOSUnion(self, shape);
+  return msGEOSUnion(self, shape);
 }
 
 shapeObj *shapeObj_intersection(shapeObj *self, shapeObj *shape)
 {
-     return msGEOSIntersection(self, shape);
+  return msGEOSIntersection(self, shape);
 }
 
 shapeObj *shapeObj_difference(shapeObj *self, shapeObj *shape)
 {
-     return msGEOSDifference(self, shape);
+  return msGEOSDifference(self, shape);
 }
- 
+
 shapeObj *shapeObj_symdifference(shapeObj *self, shapeObj *shape)
 {
-     return msGEOSSymDifference(self, shape);
+  return msGEOSSymDifference(self, shape);
 }
 
 int shapeObj_overlaps(shapeObj *self, shapeObj *shape)
 {
-    return msGEOSOverlaps(self, shape);
+  return msGEOSOverlaps(self, shape);
 }
- 
+
 int shapeObj_within(shapeObj *self, shapeObj *shape)
 {
-    return msGEOSWithin(self, shape);
+  return msGEOSWithin(self, shape);
 }
 
 int shapeObj_crosses(shapeObj *self, shapeObj *shape)
 {
-    return msGEOSCrosses(self, shape);
+  return msGEOSCrosses(self, shape);
 }
 
 int shapeObj_touches(shapeObj *self, shapeObj *shape)
 {
-    return msGEOSTouches(self, shape);
+  return msGEOSTouches(self, shape);
 }
- 
+
 int shapeObj_equals(shapeObj *self, shapeObj *shape)
 {
-    return msGEOSEquals(self, shape);
+  return msGEOSEquals(self, shape);
 }
- 
+
 int shapeObj_disjoint(shapeObj *self, shapeObj *shape)
 {
-    return msGEOSDisjoint(self, shape);
+  return msGEOSDisjoint(self, shape);
 }
- 
+
 
 pointObj *shapeObj_getcentroid(shapeObj *self)
 {
-    return msGEOSGetCentroid(self);
+  return msGEOSGetCentroid(self);
 }
 
 double shapeObj_getarea(shapeObj *self)
 {
-    return msGEOSArea(self);
+  return msGEOSArea(self);
 }
 
 double shapeObj_getlength(shapeObj *self)
 {
-    return msGEOSLength(self);
+  return msGEOSLength(self);
 }
 
 pointObj *shapeObj_getLabelPoint(shapeObj *self)
 {
-    pointObj *point = (pointObj *)calloc(1, sizeof(pointObj));
-    if (point == NULL) {
-        msSetError(MS_MEMERR, "Failed to allocate memory for point", "getLabelPoint()");
-        return NULL;
-    }
+  pointObj *point = (pointObj *)calloc(1, sizeof(pointObj));
+  if (point == NULL) {
+    msSetError(MS_MEMERR, "Failed to allocate memory for point", "getLabelPoint()");
+    return NULL;
+  }
 
-    if(self->type == MS_SHAPE_POLYGON && msPolygonLabelPoint(self, point, -1) == MS_SUCCESS)
-        return point;
+  if(self->type == MS_SHAPE_POLYGON && msPolygonLabelPoint(self, point, -1) == MS_SUCCESS)
+    return point;
 
-    free(point);
-    return NULL;
+  free(point);
+  return NULL;
 }
 
 
 /**********************************************************************
  * class extensions for rectObj
  **********************************************************************/
-rectObj *rectObj_new() {	
-    rectObj *rect;
-
-    rect = (rectObj *)calloc(1, sizeof(rectObj));
-    if(!rect)
-      return(NULL);
-    
-    rect->minx = -1;
-    rect->miny = -1;
-    rect->maxx = -1;
-    rect->maxy = -1;
-    
-    return(rect);    	
-  }
+rectObj *rectObj_new()
+{
+  rectObj *rect;
 
-void rectObj_destroy(rectObj *self) {
-    free(self);
-  }
+  rect = (rectObj *)calloc(1, sizeof(rectObj));
+  if(!rect)
+    return(NULL);
 
-int rectObj_project(rectObj *self, projectionObj *in, projectionObj *out) {
-    return msProjectRect(in, out, self);
-  }
+  rect->minx = -1;
+  rect->miny = -1;
+  rect->maxx = -1;
+  rect->maxy = -1;
+
+  return(rect);
+}
+
+void rectObj_destroy(rectObj *self)
+{
+  free(self);
+}
+
+int rectObj_project(rectObj *self, projectionObj *in, projectionObj *out)
+{
+  return msProjectRect(in, out, self);
+}
 
-double rectObj_fit(rectObj *self, int width, int height) {
-    return  msAdjustExtent(self, width, height);
-  } 
+double rectObj_fit(rectObj *self, int width, int height)
+{
+  return  msAdjustExtent(self, width, height);
+}
 
 int rectObj_draw(rectObj *self, mapObj *map, layerObj *layer,
-                 imageObj *img, int classindex, char *text) {
-    shapeObj shape;
+                 imageObj *img, int classindex, char *text)
+{
+  shapeObj shape;
 
-    msInitShape(&shape);
-    msRectToPolygon(*self, &shape);
-    shape.classindex = classindex;
-    shape.text = strdup(text);
+  msInitShape(&shape);
+  msRectToPolygon(*self, &shape);
+  shape.classindex = classindex;
+  shape.text = strdup(text);
 
-    msDrawShape(map, layer, &shape, img, -1, MS_FALSE);
+  msDrawShape(map, layer, &shape, img, -1, MS_FALSE);
 
-    msFreeShape(&shape);
-    
-    return 0;
-  }
+  msFreeShape(&shape);
+
+  return 0;
+}
 
 /**********************************************************************
  * class extensions for shapefileObj
  **********************************************************************/
-shapefileObj *shapefileObj_new(char *filename, int type) {    
-    shapefileObj *shapefile;
-    int status;
-
-    shapefile = (shapefileObj *)calloc(1,sizeof(shapefileObj));
-    if(!shapefile)
-      return NULL;
-
-    if(type == -1)
-      status = msShapefileOpen(shapefile, "rb", filename, MS_TRUE);
-    else if (type == -2)
-      status = msShapefileOpen(shapefile, "rb+", filename, MS_TRUE);
-    else
-      status = msShapefileCreate(shapefile, filename, type);
-
-    if(status == -1) {
-      msShapefileClose(shapefile);
-      free(shapefile);
-      return NULL;
-    }
- 
-    return(shapefile);
+shapefileObj *shapefileObj_new(char *filename, int type)
+{
+  shapefileObj *shapefile;
+  int status;
+
+  shapefile = (shapefileObj *)calloc(1,sizeof(shapefileObj));
+  if(!shapefile)
+    return NULL;
+
+  if(type == -1)
+    status = msShapefileOpen(shapefile, "rb", filename, MS_TRUE);
+  else if (type == -2)
+    status = msShapefileOpen(shapefile, "rb+", filename, MS_TRUE);
+  else
+    status = msShapefileCreate(shapefile, filename, type);
+
+  if(status == -1) {
+    msShapefileClose(shapefile);
+    free(shapefile);
+    return NULL;
   }
 
-void shapefileObj_destroy(shapefileObj *self) {
-    msShapefileClose(self);
-    free(self);  
+  return(shapefile);
 }
 
-int shapefileObj_get(shapefileObj *self, int i, shapeObj *shape) {
-    if(i<0 || i>=self->numshapes)
-      return -1;
+void shapefileObj_destroy(shapefileObj *self)
+{
+  msShapefileClose(self);
+  free(self);
+}
 
-    msFreeShape(shape); /* frees all lines and points before re-filling */
-    msSHPReadShape(self->hSHP, i, shape);
+int shapefileObj_get(shapefileObj *self, int i, shapeObj *shape)
+{
+  if(i<0 || i>=self->numshapes)
+    return -1;
 
-    return MS_SUCCESS;
-  }
+  msFreeShape(shape); /* frees all lines and points before re-filling */
+  msSHPReadShape(self->hSHP, i, shape);
+  self->lastshape = i;
 
-int shapefileObj_getPoint(shapefileObj *self, int i, pointObj *point) {
-    if(i<0 || i>=self->numshapes)
-      return -1;
+  return MS_SUCCESS;
+}
 
-    return msSHPReadPoint(self->hSHP, i, point);
-  }
+int shapefileObj_getPoint(shapefileObj *self, int i, pointObj *point)
+{
+  if(i<0 || i>=self->numshapes)
+    return -1;
 
-int shapefileObj_getTransformed(shapefileObj *self, mapObj *map, 
-                                int i, shapeObj *shape) {
-    if(i<0 || i>=self->numshapes)
-      return -1;
+  return msSHPReadPoint(self->hSHP, i, point);
+}
 
-    msFreeShape(shape); /* frees all lines and points before re-filling */
-    msSHPReadShape(self->hSHP, i, shape);
-    msTransformShapeSimplify(shape, map->extent, map->cellsize);
+int shapefileObj_getTransformed(shapefileObj *self, mapObj *map,
+                                int i, shapeObj *shape)
+{
+  if(i<0 || i>=self->numshapes)
+    return -1;
 
-    return 0;
-  }
+  msFreeShape(shape); /* frees all lines and points before re-filling */
+  msSHPReadShape(self->hSHP, i, shape);
+  msTransformShapeSimplify(shape, map->extent, map->cellsize);
 
-void shapefileObj_getExtent(shapefileObj *self, int i, rectObj *rect) {
-    msSHPReadBounds(self->hSHP, i, rect);
-  }
+  return 0;
+}
 
-int shapefileObj_add(shapefileObj *self, shapeObj *shape) {
-    return msSHPWriteShape(self->hSHP, shape);	
-  }	
+void shapefileObj_getExtent(shapefileObj *self, int i, rectObj *rect)
+{
+  msSHPReadBounds(self->hSHP, i, rect);
+}
 
-int shapefileObj_addPoint(shapefileObj *self, pointObj *point) {    
-    return msSHPWritePoint(self->hSHP, point);	
-  }
+int shapefileObj_add(shapefileObj *self, shapeObj *shape)
+{
+  return msSHPWriteShape(self->hSHP, shape);
+}
+
+int shapefileObj_addPoint(shapefileObj *self, pointObj *point)
+{
+  return msSHPWritePoint(self->hSHP, point);
+}
 
 /**********************************************************************
  * class extensions for projectionObj
  **********************************************************************/
-projectionObj *projectionObj_new(char *string) {	
-
-    int status;
-    projectionObj *proj=NULL;
+projectionObj *projectionObj_new(char *string)
+{
 
-    proj = (projectionObj *)malloc(sizeof(projectionObj));
-    if(!proj) return NULL;
-    msInitProjection(proj);
+  int status;
+  projectionObj *proj=NULL;
 
-    status = msLoadProjectionString(proj, string);
-    if(status == -1) {
-      msFreeProjection(proj);
-      free(proj);
-      return NULL;
-    }
+  proj = (projectionObj *)malloc(sizeof(projectionObj));
+  if(!proj) return NULL;
+  msInitProjection(proj);
 
-    return proj;
+  status = msLoadProjectionString(proj, string);
+  if(status == -1) {
+    msFreeProjection(proj);
+    free(proj);
+    return NULL;
   }
 
+  return proj;
+}
+
 int projectionObj_getUnits(projectionObj *self)
 {
-   return GetMapserverUnitUsingProj(self);
+  return GetMapserverUnitUsingProj(self);
 }
 
-void projectionObj_destroy(projectionObj *self) {
-    msFreeProjection(self);
-    free(self);
-  }
+void projectionObj_destroy(projectionObj *self)
+{
+  msFreeProjection(self);
+  free(self);
+}
+
+projectionObj *projectionObj_clone(projectionObj *projection)
+{
+  projectionObj *dstProjection;
+  dstProjection = (projectionObj *)malloc(sizeof(projectionObj));
+  msInitProjection(dstProjection);
+  msCopyProjection(dstProjection, projection);
+
+  return dstProjection;
+}
 
 /**********************************************************************
  * class extensions for labelCacheObj - TP mods
  **********************************************************************/
-void labelCacheObj_freeCache(labelCacheObj *self) {
-  msFreeLabelCache(self);    
-  
-  }
+void labelCacheObj_freeCache(labelCacheObj *self)
+{
+  msFreeLabelCache(self);
+
+}
 
 /**********************************************************************
  * class extensions for DBFInfo - TP mods
  **********************************************************************/
-char *DBFInfo_getFieldName(DBFInfo *self, int iField) {
-        static char pszFieldName[1000];
-	int pnWidth;
-	int pnDecimals;
-	msDBFGetFieldInfo(self, iField, &pszFieldName[0], &pnWidth, &pnDecimals);
-	return pszFieldName;
-    }
+char *DBFInfo_getFieldName(DBFInfo *self, int iField)
+{
+  static char pszFieldName[1000];
+  int pnWidth;
+  int pnDecimals;
+  msDBFGetFieldInfo(self, iField, &pszFieldName[0], &pnWidth, &pnDecimals);
+  return pszFieldName;
+}
 
-int DBFInfo_getFieldWidth(DBFInfo *self, int iField) {
-        char pszFieldName[1000];
-	int pnWidth;
-	int pnDecimals;
-	msDBFGetFieldInfo(self, iField, &pszFieldName[0], &pnWidth, &pnDecimals);
-	return pnWidth;
-    }
+int DBFInfo_getFieldWidth(DBFInfo *self, int iField)
+{
+  char pszFieldName[1000];
+  int pnWidth;
+  int pnDecimals;
+  msDBFGetFieldInfo(self, iField, &pszFieldName[0], &pnWidth, &pnDecimals);
+  return pnWidth;
+}
 
-int DBFInfo_getFieldDecimals(DBFInfo *self, int iField) {
-        char pszFieldName[1000];
-	int pnWidth;
-	int pnDecimals;
-	msDBFGetFieldInfo(self, iField, &pszFieldName[0], &pnWidth, &pnDecimals);
-	return pnDecimals;
-    }
-    
-DBFFieldType DBFInfo_getFieldType(DBFInfo *self, int iField) {
-	return msDBFGetFieldInfo(self, iField, NULL, NULL, NULL);
-    }    
+int DBFInfo_getFieldDecimals(DBFInfo *self, int iField)
+{
+  char pszFieldName[1000];
+  int pnWidth;
+  int pnDecimals;
+  msDBFGetFieldInfo(self, iField, &pszFieldName[0], &pnWidth, &pnDecimals);
+  return pnDecimals;
+}
+
+DBFFieldType DBFInfo_getFieldType(DBFInfo *self, int iField)
+{
+  return msDBFGetFieldInfo(self, iField, NULL, NULL, NULL);
+}
 
 /**********************************************************************
  * class extensions for styleObj, always within the context of a class
  **********************************************************************/
-styleObj *styleObj_new(classObj *class, styleObj *style) {
-    if(msGrowClassStyles(class) == NULL)
-      return NULL;
+styleObj *styleObj_new(classObj *class, styleObj *style)
+{
+  if(msGrowClassStyles(class) == NULL)
+    return NULL;
 
-    if(initStyle(class->styles[class->numstyles]) == -1)
-      return NULL;
+  if(initStyle(class->styles[class->numstyles]) == -1)
+    return NULL;
 
-    if (style)
-      msCopyStyle(class->styles[class->numstyles], style);
-        
-    class->numstyles++;
+  if (style)
+    msCopyStyle(class->styles[class->numstyles], style);
 
-    return class->styles[class->numstyles-1];
-  }
+  class->numstyles++;
+
+  return class->styles[class->numstyles-1];
+}
 
-styleObj *styleObj_label_new(labelObj *label, styleObj *style) {
-    if(msGrowLabelStyles(label) == NULL)
-      return NULL;
+styleObj *styleObj_label_new(labelObj *label, styleObj *style)
+{
+  if(msGrowLabelStyles(label) == NULL)
+    return NULL;
 
-    if(initStyle(label->styles[label->numstyles]) == -1)
-      return NULL;
+  if(initStyle(label->styles[label->numstyles]) == -1)
+    return NULL;
 
-    if (style)
-      msCopyStyle(label->styles[label->numstyles], style);
-        
-    label->numstyles++;
+  if (style)
+    msCopyStyle(label->styles[label->numstyles], style);
 
-    return label->styles[label->numstyles-1];
-  }
+  label->numstyles++;
 
-int styleObj_updateFromString(styleObj *self, char *snippet) {
-   return msUpdateStyleFromString(self, snippet, MS_FALSE);
+  return label->styles[label->numstyles-1];
 }
 
-int styleObj_setSymbolByName(styleObj *self, mapObj *map, char* pszSymbolName) {
-    self->symbol = msGetSymbolIndex(&map->symbolset, pszSymbolName, MS_TRUE);
-    return self->symbol;
+int styleObj_updateFromString(styleObj *self, char *snippet)
+{
+  return msUpdateStyleFromString(self, snippet, MS_FALSE);
+}
+
+int styleObj_setSymbolByName(styleObj *self, mapObj *map, char* pszSymbolName)
+{
+  self->symbol = msGetSymbolIndex(&map->symbolset, pszSymbolName, MS_TRUE);
+  return self->symbol;
 }
 
-styleObj *styleObj_clone(styleObj *style){
+styleObj *styleObj_clone(styleObj *style)
+{
   styleObj *newstyle = NULL;
   if (!style)
     return NULL;
@@ -1438,11 +1712,12 @@ styleObj *styleObj_clone(styleObj *style){
   initStyle(newstyle);
 
   msCopyStyle(newstyle, style);
-  
+
   return newstyle;
 }
 
-void styleObj_setGeomTransform(styleObj *style, char *transform){
+void styleObj_setGeomTransform(styleObj *style, char *transform)
+{
   if (!style)
     return;
 
@@ -1452,76 +1727,86 @@ void styleObj_setGeomTransform(styleObj *style, char *transform){
 
 cgiRequestObj *cgirequestObj_new()
 {
-    cgiRequestObj *request;
-    request = msAllocCgiObj();
+  cgiRequestObj *request;
+  request = msAllocCgiObj();
 
-    return request;
+  return request;
 }
 
-int cgirequestObj_loadParams(cgiRequestObj *self, 
-                             char* (*getenv2)(const char*, void* thread_context), 
+int cgirequestObj_loadParams(cgiRequestObj *self,
+                             char* (*getenv2)(const char*, void* thread_context),
                              char *raw_post_data,
                              ms_uint32 raw_post_data_length,
                              void* thread_context)
 {
-    self->NumParams = loadParams(self, getenv2, raw_post_data, raw_post_data_length, thread_context);
-    return self->NumParams;
+  self->NumParams = loadParams(self, getenv2, raw_post_data, raw_post_data_length, thread_context);
+  return self->NumParams;
 }
 
 
 void cgirequestObj_setParameter(cgiRequestObj *self, char *name, char *value)
 {
-    int i;
-        
-    if (self->NumParams == MS_DEFAULT_CGI_PARAMS) {
-      msSetError(MS_CHILDERR, "Maximum number of items, %d, has been reached", "setItem()", MS_DEFAULT_CGI_PARAMS);
-    }
-        
-    for (i=0; i<self->NumParams; i++) {
-      if (strcasecmp(self->ParamNames[i], name) == 0) {
-        free(self->ParamValues[i]);
-                self->ParamValues[i] = strdup(value);
-                break;
-      }
-    }
-    if (i == self->NumParams) {
-      self->ParamNames[self->NumParams] = strdup(name);
-      self->ParamValues[self->NumParams] = strdup(value);
-      self->NumParams++;
+  int i;
+
+  if (self->NumParams == MS_DEFAULT_CGI_PARAMS) {
+    msSetError(MS_CHILDERR, "Maximum number of items, %d, has been reached", "setItem()", MS_DEFAULT_CGI_PARAMS);
+  }
+
+  for (i=0; i<self->NumParams; i++) {
+    if (strcasecmp(self->ParamNames[i], name) == 0) {
+      free(self->ParamValues[i]);
+      self->ParamValues[i] = strdup(value);
+      break;
     }
+  }
+  if (i == self->NumParams) {
+    self->ParamNames[self->NumParams] = strdup(name);
+    self->ParamValues[self->NumParams] = strdup(value);
+    self->NumParams++;
+  }
+}
+
+void cgirequestObj_addParameter(cgiRequestObj *self, char *name, char *value)
+{
+  if (self->NumParams == MS_DEFAULT_CGI_PARAMS) {
+    msSetError(MS_CHILDERR, "Maximum number of items, %d, has been reached", "addParameter()", MS_DEFAULT_CGI_PARAMS);
+  }
+  self->ParamNames[self->NumParams] = strdup(name);
+  self->ParamValues[self->NumParams] = strdup(value);
+  self->NumParams++;
 }
 
 char *cgirequestObj_getName(cgiRequestObj *self, int index)
 {
-    if (index < 0 || index >= self->NumParams) {
-            msSetError(MS_CHILDERR, "Invalid index, valid range is [0, %d]", "getName()", self->NumParams-1);
-            return NULL;
-        }
-        return self->ParamNames[index];
+  if (index < 0 || index >= self->NumParams) {
+    msSetError(MS_CHILDERR, "Invalid index, valid range is [0, %d]", "getName()", self->NumParams-1);
+    return NULL;
+  }
+  return self->ParamNames[index];
 }
 
-char *cgirequestObj_getValue(cgiRequestObj *self, int index) 
+char *cgirequestObj_getValue(cgiRequestObj *self, int index)
 {
-    if (index < 0 || index >= self->NumParams) {
-            msSetError(MS_CHILDERR, "Invalid index, valid range is [0, %d]", "getValue()", self->NumParams-1);
-            return NULL;
-        }
-        return self->ParamValues[index];
+  if (index < 0 || index >= self->NumParams) {
+    msSetError(MS_CHILDERR, "Invalid index, valid range is [0, %d]", "getValue()", self->NumParams-1);
+    return NULL;
+  }
+  return self->ParamValues[index];
 }
- 
-char *cgirequestObj_getValueByName(cgiRequestObj *self, const char *name) 
+
+char *cgirequestObj_getValueByName(cgiRequestObj *self, const char *name)
 {
-    int i;
-    for (i=0; i<self->NumParams; i++) {
-        if (strcasecmp(self->ParamNames[i], name) == 0) {
-            return self->ParamValues[i];
-        }
+  int i;
+  for (i=0; i<self->NumParams; i++) {
+    if (strcasecmp(self->ParamNames[i], name) == 0) {
+      return self->ParamValues[i];
     }
-    return NULL;
+  }
+  return NULL;
 }
 void cgirequestObj_destroy(cgiRequestObj *self)
 {
-    free(self);
+  free(self);
 }
 
 
@@ -1530,75 +1815,177 @@ void cgirequestObj_destroy(cgiRequestObj *self)
  **********************************************************************/
 
 // New instance
-hashTableObj *hashTableObj_new() {
-   return msCreateHashTable();
+hashTableObj *hashTableObj_new()
+{
+  return msCreateHashTable();
 }
 
 // set a hash item given key and value
-int hashTableObj_set(hashTableObj *self, const char *key, const char *value) {
-   if (msInsertHashTable(self, key, value) == NULL) {
-      return MS_FAILURE;
-   }
-   return MS_SUCCESS;
+int hashTableObj_set(hashTableObj *self, const char *key, const char *value)
+{
+  if (msInsertHashTable(self, key, value) == NULL) {
+    return MS_FAILURE;
+  }
+  return MS_SUCCESS;
 }
 
 // get value from item by its key
-const char *hashTableObj_get(hashTableObj *self, const char *key) {
-   return (msLookupHashTable(self, key));
+const char *hashTableObj_get(hashTableObj *self, const char *key)
+{
+  return (msLookupHashTable(self, key));
 }
 
 // Remove one item from hash table
-int hashTableObj_remove(hashTableObj *self, const char *key) {
-   return (msRemoveHashTable(self, key));
+int hashTableObj_remove(hashTableObj *self, const char *key)
+{
+  return (msRemoveHashTable(self, key));
 }
 
 // Clear all items in hash table (to NULL)
-void hashTableObj_clear(hashTableObj *self) {
-   msFreeHashItems(self);
-   initHashTable(self);
+void hashTableObj_clear(hashTableObj *self)
+{
+  msFreeHashItems(self);
+  initHashTable(self);
 }
 
 // Return the next key or first key if previousKey == NULL
-char *hashTableObj_nextKey(hashTableObj *self, const char *previousKey) {
-   return ((char *)msNextKeyFromHashTable(self, previousKey));
+char *hashTableObj_nextKey(hashTableObj *self, const char *previousKey)
+{
+  return ((char *)msNextKeyFromHashTable(self, previousKey));
 }
 
-resultObj *resultObj_new() {
-    resultObj *r = (resultObj *) msSmallMalloc(sizeof(resultObj));
-    r->tileindex = -1;
-    r->shapeindex = -1;
-    r->resultindex = -1;
-    return r;
+resultObj *resultObj_new()
+{
+  resultObj *r = (resultObj *) msSmallMalloc(sizeof(resultObj));
+  r->tileindex = -1;
+  r->shapeindex = -1;
+  r->resultindex = -1;
+  return r;
 }
 
 /**********************************************************************
  * class extensions clusterObj
  **********************************************************************/
 
-int clusterObj_updateFromString(clusterObj *self, char *snippet) {
-    return msUpdateClusterFromString(self, snippet);
+int clusterObj_updateFromString(clusterObj *self, char *snippet)
+{
+  return msUpdateClusterFromString(self, snippet);
 }
 
-int clusterObj_setGroup(clusterObj *self, char *string) {
-    if (!string || strlen(string) == 0) {
-        freeExpression(&self->group);
-        return MS_SUCCESS;
-    }
-    else return msLoadExpressionString(&self->group, string);
+int clusterObj_setGroup(clusterObj *self, char *string)
+{
+  if (!string || strlen(string) == 0) {
+    freeExpression(&self->group);
+    return MS_SUCCESS;
+  } else return msLoadExpressionString(&self->group, string);
+}
+
+char *clusterObj_getGroupString(clusterObj *self)
+{
+  return msGetExpressionString(&(self->group));
 }
 
-char *clusterObj_getGroupString(clusterObj *self) {
-    return msGetExpressionString(&(self->group));
+int clusterObj_setFilter(clusterObj *self, char *string)
+{
+  if (!string || strlen(string) == 0) {
+    freeExpression(&self->filter);
+    return MS_SUCCESS;
+  } else return msLoadExpressionString(&self->filter, string);
+}
+
+char *clusterObj_getFilterString(clusterObj *self)
+{
+  return msGetExpressionString(&(self->filter));
+}
+
+outputFormatObj* outputFormatObj_new(const char *driver, char *name)
+{
+  outputFormatObj *format;
+
+  format = msCreateDefaultOutputFormat(NULL, driver, name);
+
+  /* in the case of unsupported formats, msCreateDefaultOutputFormat
+     should return NULL */
+  if (!format) {
+    msSetError(MS_MISCERR, "Unsupported format driver: %s",
+               "outputFormatObj()", driver);
+    return NULL;
   }
 
-int clusterObj_setFilter(clusterObj *self, char *string) {
-    if (!string || strlen(string) == 0) {
-        freeExpression(&self->filter);
-        return MS_SUCCESS;
-    }
-    else return msLoadExpressionString(&self->filter, string);
+  msInitializeRendererVTable(format);
+
+  /* Else, continue */
+  format->refcount++;
+  format->inmapfile = MS_TRUE;
+
+  return format;
+}
+
+void  outputFormatObj_destroy(outputFormatObj* self)
+{
+  if ( --self->refcount < 1 )
+    msFreeOutputFormat( self );
+}
+
+imageObj *symbolObj_getImage(symbolObj *self, outputFormatObj *input_format)
+{
+  imageObj *image = NULL;
+  outputFormatObj *format = NULL;
+  rendererVTableObj *renderer = NULL;
+
+  if (self->type != MS_SYMBOL_PIXMAP) {
+    msSetError(MS_SYMERR, "Can't return image from non-pixmap symbol",
+               "getImage()");
+    return NULL;
+  }
+
+  if (input_format) {
+    format = input_format;
+  } else {
+    format = msCreateDefaultOutputFormat(NULL, "GD/GIF", "gdgif");
+    if (format == NULL)
+      format = msCreateDefaultOutputFormat(NULL, "GD/PNG", "gdpng");
+
+    if (format)
+      msInitializeRendererVTable(format);
+  }
+
+  if (format == NULL) {
+    msSetError(MS_IMGERR, "Could not create output format",
+               "getImage()");
+    return NULL;
+  }
+
+  renderer = format->vtable;
+  msPreloadImageSymbol(renderer, self);
+  if (self->pixmap_buffer) {
+    image = msImageCreate(self->pixmap_buffer->width, self->pixmap_buffer->height, format, NULL, NULL,
+                          MS_DEFAULT_RESOLUTION, MS_DEFAULT_RESOLUTION, NULL);
+    renderer->mergeRasterBuffer(image, self->pixmap_buffer, 1.0, 0, 0, 0, 0,
+                                self->pixmap_buffer->width, self->pixmap_buffer->height);
+  }
+
+  return image;
 }
 
-char *clusterObj_getFilterString(clusterObj *self) {
-    return msGetExpressionString(&(self->filter));
+int symbolObj_setImage(symbolObj *self, imageObj *image)
+{
+  rendererVTableObj *renderer = NULL;
+
+  renderer = image->format->vtable;
+
+  if (self->pixmap_buffer) {
+    msFreeRasterBuffer(self->pixmap_buffer);
+    free(self->pixmap_buffer);
+  }
+
+  self->pixmap_buffer = (rasterBufferObj*)malloc(sizeof(rasterBufferObj));
+  if (!self->pixmap_buffer) {
+    msSetError(MS_MEMERR, NULL, "setImage()");
+    return MS_FAILURE;
   }
+  self->type = MS_SYMBOL_PIXMAP;
+  renderer->getRasterBufferCopy(image, self->pixmap_buffer);
+
+  return MS_SUCCESS;
+}
diff --git a/mapscript/php/outputformat.c b/mapscript/php/outputformat.c
index 4ab28d1..a2e30e5 100644
--- a/mapscript/php/outputformat.c
+++ b/mapscript/php/outputformat.c
@@ -2,7 +2,7 @@
  * $Id: php_mapscript.c 9765 2010-01-28 15:32:10Z aboudreault $
  *
  * Project:  MapServer
- * Purpose:  PHP/MapScript extension for MapServer.  External interface 
+ * Purpose:  PHP/MapScript extension for MapServer.  External interface
  *           functions
  * Author:   Daniel Morissette, DM Solutions Group (dmorissette at dmsolutions.ca)
  *           Alan Boudreault, Mapgears
@@ -16,16 +16,16 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
+ *
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  * DEALINGS IN THE SOFTWARE.
  **********************************************************************/
 
@@ -33,118 +33,152 @@
 
 zend_class_entry *mapscript_ce_outputformat;
 
-ZEND_BEGIN_ARG_INFO_EX(outputformat___get_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, property)
+ZEND_BEGIN_ARG_INFO_EX(outputformat___construct_args, 0, 0, 1)
+ZEND_ARG_INFO(0, driver)
+ZEND_ARG_INFO(0, name)
 ZEND_END_ARG_INFO()
 
+ZEND_BEGIN_ARG_INFO_EX(outputformat___get_args, 0, 0, 1)
+ZEND_ARG_INFO(0, property)
+
+ZEND_END_ARG_INFO()
 ZEND_BEGIN_ARG_INFO_EX(outputformat___set_args, 0, 0, 2)
-  ZEND_ARG_INFO(0, property)
-  ZEND_ARG_INFO(0, value)
+ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, value)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(outputformat_setOption_args, 0, 0, 2)
-  ZEND_ARG_INFO(0, property)
-  ZEND_ARG_INFO(0, value)
+ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, value)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(outputformat_getOption_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, property)
+ZEND_END_ARG_INFO()
+
+ZEND_BEGIN_ARG_INFO_EX(outputformat_getOptionByIndex_args, 0, 0, 1)
+ZEND_ARG_INFO(0, index)
 ZEND_END_ARG_INFO()
 
 /* {{{ proto outputformat __construct()
-   outputFormatObj CANNOT be instanciated, this will throw an exception on use */
+   instanciate outputFormatObj */
 PHP_METHOD(outputFormatObj, __construct)
 {
-    mapscript_throw_exception("outputFormatObj cannot be constructed" TSRMLS_CC);
+  zval *zobj = getThis();
+  php_outputformat_object *php_outputformat;
+  char *driver;
+  long driver_len;
+  char *name = NULL;
+  long name_len;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s",
+                            &driver, &driver_len, &name, &name_len) == FAILURE) {
+    PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_outputformat = (php_outputformat_object *)zend_object_store_get_object(zobj TSRMLS_CC);
+
+  if ((php_outputformat->outputformat = outputFormatObj_new(driver, name)) == NULL) {
+    mapscript_throw_exception("Unable to construct outputFormatObj." TSRMLS_CC);
+    return;
+  }
 }
 /* }}} */
 
 PHP_METHOD(outputFormatObj, __get)
 {
-    char *property;
-    long property_len;
-    zval *zobj = getThis();
-    php_outputformat_object *php_outputformat;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &property, &property_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *zobj = getThis();
+  php_outputformat_object *php_outputformat;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &property, &property_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_outputformat = (php_outputformat_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_outputformat = (php_outputformat_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
 
-    IF_GET_STRING("name", php_outputformat->outputformat->name)
-    else IF_GET_STRING("mimetype", php_outputformat->outputformat->mimetype)
+  IF_GET_STRING("name", php_outputformat->outputformat->name)
+  else IF_GET_STRING("mimetype", php_outputformat->outputformat->mimetype)
     else IF_GET_STRING("driver", php_outputformat->outputformat->driver)
-    else IF_GET_STRING("extension", php_outputformat->outputformat->extension)
-    else IF_GET_LONG("renderer", php_outputformat->outputformat->renderer)
-    else IF_GET_LONG("imagemode", php_outputformat->outputformat->imagemode)
-    else IF_GET_LONG("transparent", php_outputformat->outputformat->transparent)
-    else 
-    {
-        mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }
+      else IF_GET_STRING("extension", php_outputformat->outputformat->extension)
+        else IF_GET_LONG("renderer", php_outputformat->outputformat->renderer)
+          else IF_GET_LONG("imagemode", php_outputformat->outputformat->imagemode)
+            else IF_GET_LONG("transparent", php_outputformat->outputformat->transparent)
+              else IF_GET_LONG("bands", php_outputformat->outputformat->bands)
+                else IF_GET_LONG("numformatoptions", php_outputformat->outputformat->numformatoptions)
+                  else {
+                    mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+                  }
 }
 
 PHP_METHOD(outputFormatObj, __set)
 {
-    char *property;
-    long property_len;
-    zval *value;
-    zval *zobj = getThis();
-    php_outputformat_object *php_outputformat;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
-                              &property, &property_len, &value) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *value;
+  zval *zobj = getThis();
+  php_outputformat_object *php_outputformat;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
+                            &property, &property_len, &value) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_outputformat = (php_outputformat_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    IF_SET_STRING("name", php_outputformat->outputformat->name, value)
-    else IF_SET_STRING("mimetype", php_outputformat->outputformat->mimetype, value)
+  php_outputformat = (php_outputformat_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  IF_SET_STRING("name", php_outputformat->outputformat->name, value)
+  else IF_SET_STRING("mimetype", php_outputformat->outputformat->mimetype, value)
     else IF_SET_STRING("driver", php_outputformat->outputformat->driver, value)
-    else IF_SET_STRING("extension", php_outputformat->outputformat->extension, value)
-    else IF_SET_LONG("renderer", php_outputformat->outputformat->renderer, value)
-    else IF_SET_LONG("imagemode", php_outputformat->outputformat->imagemode, value)
-    else IF_SET_LONG("transparent", php_outputformat->outputformat->transparent, value)
-    else 
-    {
-        mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }
+      else IF_SET_STRING("extension", php_outputformat->outputformat->extension, value)
+        else IF_SET_LONG("renderer", php_outputformat->outputformat->renderer, value)
+          else IF_SET_LONG("imagemode", php_outputformat->outputformat->imagemode, value)
+            else IF_SET_LONG("transparent", php_outputformat->outputformat->transparent, value)
+              else if ( (STRING_EQUAL("bands", property)) ||
+                        (STRING_EQUAL("numformatoptions", property)) ) {
+                mapscript_throw_exception("Property '%s' is read-only and cannot be set." TSRMLS_CC, property);
+              }
+
+              else {
+                mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+              }
 }
 
 /* {{{ proto int outputFormat.setOption(string property_name, new_value)
    Add or Modify the format option list. return true on success.*/
 PHP_METHOD(outputFormatObj, setOption)
 {
-    char *property;
-    long property_len;
-    char *value;
-    long value_len;
-    zval *zobj = getThis();
-    php_outputformat_object *php_outputformat;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss",
-                              &property, &property_len, &value, &value_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  char *value;
+  long value_len;
+  zval *zobj = getThis();
+  php_outputformat_object *php_outputformat;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss",
+                            &property, &property_len, &value, &value_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_outputformat = (php_outputformat_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    msSetOutputFormatOption(php_outputformat->outputformat, property, value);
+  php_outputformat = (php_outputformat_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    RETURN_LONG(MS_SUCCESS);
+  msSetOutputFormatOption(php_outputformat->outputformat, property, value);
+
+  RETURN_LONG(MS_SUCCESS);
 }
 /* }}} */
 
@@ -153,25 +187,25 @@ PHP_METHOD(outputFormatObj, setOption)
    argument. Returns an empty string if property not found.*/
 PHP_METHOD(outputFormatObj, getOption)
 {
-    char *property;
-    long property_len;
-    zval *zobj = getThis();
-    const char *value = NULL;
-    php_outputformat_object *php_outputformat;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &property, &property_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *zobj = getThis();
+  const char *value = NULL;
+  php_outputformat_object *php_outputformat;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &property, &property_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_outputformat = (php_outputformat_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_outputformat = (php_outputformat_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    value = msGetOutputFormatOption(php_outputformat->outputformat, property, "");
+  value = msGetOutputFormatOption(php_outputformat->outputformat, property, "");
 
-    RETURN_STRING((char*)value,1);
+  RETURN_STRING((char*)value,1);
 }
 /* }}} */
 
@@ -181,90 +215,123 @@ PHP_METHOD(outputFormatObj, getOption)
    internally. May produce debug output if issues encountered.*/
 PHP_METHOD(outputFormatObj, validate)
 {
-    zval *zobj = getThis();
-    int status = MS_FALSE;
-    php_outputformat_object *php_outputformat;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  int status = MS_FALSE;
+  php_outputformat_object *php_outputformat;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_outputformat = (php_outputformat_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-
-    status = msOutputFormatValidate(php_outputformat->outputformat, MS_TRUE);
-    if (status != MS_TRUE)
-    {
-        mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
-        RETURN_LONG(MS_FAILURE);
-    }
-    else
-        RETURN_LONG(MS_SUCCESS);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_outputformat = (php_outputformat_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  status = msOutputFormatValidate(php_outputformat->outputformat, MS_TRUE);
+  if (status != MS_TRUE) {
+    mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
+    RETURN_LONG(MS_FAILURE);
+  } else
+    RETURN_LONG(MS_SUCCESS);
+}
+/* }}} */
+
+/* {{{ proto int outputformat.getOptionByIndex(int index).
+   Return the option at index position. */
+PHP_METHOD(outputFormatObj, getOptionByIndex)
+{
+  zval *zobj = getThis();
+  long index = -1;
+  php_outputformat_object *php_outputformat;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
+                            &index) == FAILURE) {
+    PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_outputformat = (php_outputformat_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  if (index < 0 || index >= php_outputformat->outputformat->numformatoptions) {
+    mapscript_throw_mapserver_exception("Invalid format option index." TSRMLS_CC);
+    return;
+  }
+
+  RETURN_STRING(php_outputformat->outputformat->formatoptions[index],1);
 }
 /* }}} */
 
 zend_function_entry outputformat_functions[] = {
-    PHP_ME(outputFormatObj, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
-    PHP_ME(outputFormatObj, __get, outputformat___get_args, ZEND_ACC_PUBLIC)
-    PHP_ME(outputFormatObj, __set, outputformat___set_args, ZEND_ACC_PUBLIC)
-    PHP_MALIAS(outputFormatObj, set, __set, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(outputFormatObj, setOption, outputformat_setOption_args, ZEND_ACC_PUBLIC)
-    PHP_ME(outputFormatObj, getOption, outputformat_getOption_args, ZEND_ACC_PUBLIC)
-    PHP_ME(outputFormatObj, validate, NULL, ZEND_ACC_PUBLIC)
-    {NULL, NULL, NULL}
+  PHP_ME(outputFormatObj, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
+  PHP_ME(outputFormatObj, __get, outputformat___get_args, ZEND_ACC_PUBLIC)
+  PHP_ME(outputFormatObj, __set, outputformat___set_args, ZEND_ACC_PUBLIC)
+  PHP_MALIAS(outputFormatObj, set, __set, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(outputFormatObj, setOption, outputformat_setOption_args, ZEND_ACC_PUBLIC)
+  PHP_ME(outputFormatObj, getOption, outputformat_getOption_args, ZEND_ACC_PUBLIC)
+  PHP_ME(outputFormatObj, getOptionByIndex, outputformat_getOptionByIndex_args, ZEND_ACC_PUBLIC)
+  PHP_ME(outputFormatObj, validate, NULL, ZEND_ACC_PUBLIC) {
+    NULL, NULL, NULL
+  }
 };
 
 void mapscript_create_outputformat(outputFormatObj *outputformat, parent_object parent, zval *return_value TSRMLS_DC)
 {
-    php_outputformat_object * php_outputformat;
-    object_init_ex(return_value, mapscript_ce_outputformat); 
-    php_outputformat = (php_outputformat_object *)zend_object_store_get_object(return_value TSRMLS_CC);
-    php_outputformat->outputformat = outputformat;
+  php_outputformat_object * php_outputformat;
+  object_init_ex(return_value, mapscript_ce_outputformat);
+  php_outputformat = (php_outputformat_object *)zend_object_store_get_object(return_value TSRMLS_CC);
+  php_outputformat->outputformat = outputformat;
+
+  if (parent.val)
+    php_outputformat->is_ref = 1;
 
-    php_outputformat->parent = parent;
-    MAPSCRIPT_ADDREF(parent.val);
+  php_outputformat->parent = parent;
+  MAPSCRIPT_ADDREF(parent.val);
 }
 
 static void mapscript_outputformat_object_destroy(void *object TSRMLS_DC)
 {
-    php_outputformat_object *php_outputformat = (php_outputformat_object *)object;
+  php_outputformat_object *php_outputformat = (php_outputformat_object *)object;
 
-    MAPSCRIPT_FREE_OBJECT(php_outputformat);
+  MAPSCRIPT_FREE_OBJECT(php_outputformat);
 
-    MAPSCRIPT_FREE_PARENT(php_outputformat->parent);
+  MAPSCRIPT_FREE_PARENT(php_outputformat->parent);
 
-    /* We don't need to free the outputFormatObj */ 
+  if (php_outputformat->outputformat && !php_outputformat->is_ref) {
+    outputFormatObj_destroy(php_outputformat->outputformat);
+  }
 
-    efree(object);
+  efree(object);
 }
 
 static zend_object_value mapscript_outputformat_object_new(zend_class_entry *ce TSRMLS_DC)
 {
-    zend_object_value retval;
-    php_outputformat_object *php_outputformat;
+  zend_object_value retval;
+  php_outputformat_object *php_outputformat;
 
-    MAPSCRIPT_ALLOC_OBJECT(php_outputformat, php_outputformat_object);
+  MAPSCRIPT_ALLOC_OBJECT(php_outputformat, php_outputformat_object);
 
-    retval = mapscript_object_new(&php_outputformat->std, ce,
-                                  &mapscript_outputformat_object_destroy TSRMLS_CC);
+  retval = mapscript_object_new(&php_outputformat->std, ce,
+                                &mapscript_outputformat_object_destroy TSRMLS_CC);
 
-    MAPSCRIPT_INIT_PARENT(php_outputformat->parent);
+  php_outputformat->is_ref = 0;
+  MAPSCRIPT_INIT_PARENT(php_outputformat->parent);
 
-    return retval;
+  return retval;
 }
 
 PHP_MINIT_FUNCTION(outputformat)
 {
-    zend_class_entry ce;
+  zend_class_entry ce;
+
+  MAPSCRIPT_REGISTER_CLASS("outputFormatObj",
+                           outputformat_functions,
+                           mapscript_ce_outputformat,
+                           mapscript_outputformat_object_new);
 
-    MAPSCRIPT_REGISTER_CLASS("outputFormatObj", 
-                             outputformat_functions,
-                             mapscript_ce_outputformat,
-                             mapscript_outputformat_object_new);
+  mapscript_ce_outputformat->ce_flags |= ZEND_ACC_FINAL_CLASS;
 
-    mapscript_ce_outputformat->ce_flags |= ZEND_ACC_FINAL_CLASS; 
-    
-    return SUCCESS;
+  return SUCCESS;
 }
diff --git a/mapscript/php/owsrequest.c b/mapscript/php/owsrequest.c
index da94cf1..6ed943a 100644
--- a/mapscript/php/owsrequest.c
+++ b/mapscript/php/owsrequest.c
@@ -2,7 +2,7 @@
  * $Id: php_mapscript.c 9765 2010-01-28 15:32:10Z aboudreault $
  *
  * Project:  MapServer
- * Purpose:  PHP/MapScript extension for MapServer.  External interface 
+ * Purpose:  PHP/MapScript extension for MapServer.  External interface
  *           functions
  * Author:   Daniel Morissette, DM Solutions Group (dmorissette at dmsolutions.ca)
  *           Alan Boudreault, Mapgears
@@ -16,16 +16,16 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
+ *
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  * DEALINGS IN THE SOFTWARE.
  **********************************************************************/
 
@@ -38,111 +38,117 @@ char *owsrequest_getenv(const char *name, void *thread_context);
 zend_class_entry *mapscript_ce_owsrequest;
 
 ZEND_BEGIN_ARG_INFO_EX(owsrequest___get_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, property)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(owsrequest___set_args, 0, 0, 2)
-  ZEND_ARG_INFO(0, property)
-  ZEND_ARG_INFO(0, value)
+ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, value)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(owsrequest_setParameter_args, 0, 0, 2)
-  ZEND_ARG_INFO(0, name)
-  ZEND_ARG_INFO(0, value)
+ZEND_ARG_INFO(0, name)
+ZEND_ARG_INFO(0, value)
+ZEND_END_ARG_INFO()
+
+ZEND_BEGIN_ARG_INFO_EX(owsrequest_addParameter_args, 0, 0, 2)
+ZEND_ARG_INFO(0, name)
+ZEND_ARG_INFO(0, value)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(owsrequest_getName_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, index)
+ZEND_ARG_INFO(0, index)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(owsrequest_getValue_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, index)
+ZEND_ARG_INFO(0, index)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(owsrequest_getValueByName_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, name)
+ZEND_ARG_INFO(0, name)
 ZEND_END_ARG_INFO()
 
 /* {{{ proto owsrequest __construct()
    Create a new OWSRequestObj instance. */
 PHP_METHOD(OWSRequestObj, __construct)
 {
-    zval *zobj = getThis();
-    php_owsrequest_object *php_owsrequest;
-    cgiRequestObj *request;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  php_owsrequest_object *php_owsrequest;
+  cgiRequestObj *request;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_owsrequest = (php_owsrequest_object *) zend_object_store_get_object(zobj TSRMLS_CC);
- 
-    if ((request = cgirequestObj_new()) == NULL)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
-    
-    php_owsrequest->cgirequest = request;
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_owsrequest = (php_owsrequest_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  if ((request = cgirequestObj_new()) == NULL) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
+
+  php_owsrequest->cgirequest = request;
 }
 /* }}} */
 
 PHP_METHOD(OWSRequestObj, __get)
 {
-    char *property;
-    long property_len;
-    zval *zobj = getThis();
-    php_owsrequest_object *php_owsrequest;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &property, &property_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *zobj = getThis();
+  php_owsrequest_object *php_owsrequest;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &property, &property_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_owsrequest = (php_owsrequest_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
+  php_owsrequest = (php_owsrequest_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    IF_GET_LONG("numparams", php_owsrequest->cgirequest->NumParams)
-    else IF_GET_LONG("type", php_owsrequest->cgirequest->type)
-    else 
-    {
-        mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }
+
+  IF_GET_LONG("numparams", php_owsrequest->cgirequest->NumParams)
+  else IF_GET_STRING("contenttype", php_owsrequest->cgirequest->contenttype)
+    else IF_GET_STRING("postrequest", php_owsrequest->cgirequest->postrequest)
+      else IF_GET_STRING("httpcookiedata", php_owsrequest->cgirequest->httpcookiedata)
+        else IF_GET_LONG("type", php_owsrequest->cgirequest->type)
+          else {
+            mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+          }
 }
 
 PHP_METHOD(OWSRequestObj, __set)
 {
-    char *property;
-    long property_len;
-    zval *value;
-    zval *zobj = getThis();
-    php_owsrequest_object *php_owsrequest;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
-                              &property, &property_len, &value) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *value;
+  zval *zobj = getThis();
+  php_owsrequest_object *php_owsrequest;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
+                            &property, &property_len, &value) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_owsrequest = (php_owsrequest_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-
-    if ( (STRING_EQUAL("numparams", property)) ||
-         (STRING_EQUAL("type", property)))
-    {
-        mapscript_throw_exception("Property '%s' is read-only and cannot be set." TSRMLS_CC, property);
-    }
-    else 
-    {
-        mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_owsrequest = (php_owsrequest_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  if ( (STRING_EQUAL("numparams", property)) ||
+       (STRING_EQUAL("type", property)) ||
+       (STRING_EQUAL("contenttype", property)) ||
+       (STRING_EQUAL("postrequest", property)) ||
+       (STRING_EQUAL("httpcookiedata", property))) {
+    mapscript_throw_exception("Property '%s' is read-only and cannot be set." TSRMLS_CC, property);
+  } else {
+    mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+  }
 }
 
 /* {{{ proto int owsrequest.loadParams()
@@ -151,56 +157,49 @@ PHP_METHOD(OWSRequestObj, __set)
    name/value pairs collected. */
 PHP_METHOD(OWSRequestObj, loadParams)
 {
-    zval *zobj = getThis();
-    zval **val;
-    php_owsrequest_object *php_owsrequest;
-    void *thread_context;
+  zval *zobj = getThis();
+  zval **val;
+  php_owsrequest_object *php_owsrequest;
+  void *thread_context;
 
 #ifdef ZTS
-    thread_context = (void*)TSRMLS_C;
+  thread_context = (void*)TSRMLS_C;
 #else
-    thread_context = NULL;
+  thread_context = NULL;
 #endif
 
-    //PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-      //PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  //PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     //PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_owsrequest = (php_owsrequest_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-
-    if ( (STRING_EQUAL(sapi_module.name,"cli")) || 
-         (STRING_EQUAL(sapi_module.name,"cgi")) ||
-         (STRING_EQUAL(sapi_module.name,"cgi-fcgi")) )
-    {
-        cgirequestObj_loadParams(php_owsrequest->cgirequest, NULL, NULL, 0, thread_context);
-    }
-    else
-    {
-        // check if we have input data for GET method
-        if (SG(request_info).request_method &&
-            STRING_EQUAL(SG(request_info).request_method, "GET"))
-        {
-            zend_is_auto_global("_SERVER", sizeof("_SERVER")-1 TSRMLS_CC);
-            if ( PG(http_globals)[TRACK_VARS_SERVER] &&
-                 (zend_hash_find(PG(http_globals)[TRACK_VARS_SERVER]->value.ht, "QUERY_STRING", sizeof("QUERY_STRING"), (void **) &val) == SUCCESS) &&
-                 (Z_TYPE_PP(val) == IS_STRING) &&
-                 (Z_STRLEN_PP(val) > 0) ) 
-            {
-                cgirequestObj_loadParams(php_owsrequest->cgirequest, owsrequest_getenv, NULL, 0, thread_context);
-            }
-        }
-        else
-        {
-            cgirequestObj_loadParams(php_owsrequest->cgirequest, owsrequest_getenv, 
-                                     SG(request_info).raw_post_data,
-                                     SG(request_info).raw_post_data_length, thread_context);
-        }
+    return;
+  }
+  //PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_owsrequest = (php_owsrequest_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  if ( (STRING_EQUAL(sapi_module.name,"cli")) ||
+       (STRING_EQUAL(sapi_module.name,"cgi")) ||
+       (STRING_EQUAL(sapi_module.name,"cgi-fcgi")) ) {
+    cgirequestObj_loadParams(php_owsrequest->cgirequest, NULL, NULL, 0, thread_context);
+  } else {
+    // check if we have input data for GET method
+    if (SG(request_info).request_method &&
+        STRING_EQUAL(SG(request_info).request_method, "GET")) {
+      zend_is_auto_global("_SERVER", sizeof("_SERVER")-1 TSRMLS_CC);
+      if ( PG(http_globals)[TRACK_VARS_SERVER] &&
+           (zend_hash_find(PG(http_globals)[TRACK_VARS_SERVER]->value.ht, "QUERY_STRING", sizeof("QUERY_STRING"), (void **) &val) == SUCCESS) &&
+           (Z_TYPE_PP(val) == IS_STRING) &&
+           (Z_STRLEN_PP(val) > 0) ) {
+        cgirequestObj_loadParams(php_owsrequest->cgirequest, owsrequest_getenv, NULL, 0, thread_context);
+      }
+    } else {
+      cgirequestObj_loadParams(php_owsrequest->cgirequest, owsrequest_getenv,
+                               SG(request_info).raw_post_data,
+                               SG(request_info).raw_post_data_length, thread_context);
     }
-    
-    RETURN_LONG(php_owsrequest->cgirequest->NumParams);
+  }
+
+  RETURN_LONG(php_owsrequest->cgirequest->NumParams);
 }
 /* }}} */
 
@@ -208,80 +207,107 @@ PHP_METHOD(OWSRequestObj, loadParams)
    Set a request parameter. */
 PHP_METHOD(OWSRequestObj, setParameter)
 {
-    char *name;
-    long name_len;
-    char *value;
-    long value_len;
-    zval *zobj = getThis();
-    php_owsrequest_object *php_owsrequest;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss",
-                              &name, &name_len, &value, &value_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *name;
+  long name_len;
+  char *value;
+  long value_len;
+  zval *zobj = getThis();
+  php_owsrequest_object *php_owsrequest;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss",
+                            &name, &name_len, &value, &value_len) == FAILURE) {
+    PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_owsrequest = (php_owsrequest_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  cgirequestObj_setParameter(php_owsrequest->cgirequest, name, value);
+
+  RETURN_LONG(MS_SUCCESS);
+}
+/* }}} */
+
+/* {{{ proto int owsrequest.addParameter(string name, string value)
+   Add a request parameter. */
+PHP_METHOD(OWSRequestObj, addParameter)
+{
+  char *name;
+  long name_len;
+  char *value;
+  long value_len;
+  zval *zobj = getThis();
+  php_owsrequest_object *php_owsrequest;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss",
+                            &name, &name_len, &value, &value_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_owsrequest = (php_owsrequest_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_owsrequest = (php_owsrequest_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    cgirequestObj_setParameter(php_owsrequest->cgirequest, name, value);
+  cgirequestObj_addParameter(php_owsrequest->cgirequest, name, value);
 
-    RETURN_LONG(MS_SUCCESS);
+  RETURN_LONG(MS_SUCCESS);
 }
 /* }}} */
 
-/* {{{ proto string owsrequest.getName(int index) 
+/* {{{ proto string owsrequest.getName(int index)
    Return the name of the parameter at index in the request’s array of parameter names. */
 PHP_METHOD(OWSRequestObj, getName)
 {
-    long index;
-    zval *zobj = getThis();
-    char *value = NULL;
-    php_owsrequest_object *php_owsrequest;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
-                              &index) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  long index;
+  zval *zobj = getThis();
+  char *value = NULL;
+  php_owsrequest_object *php_owsrequest;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
+                            &index) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_owsrequest = (php_owsrequest_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-
-    value = cgirequestObj_getName(php_owsrequest->cgirequest, index);
-    if (!value)
-        RETURN_STRING("", 1);
-    
-    RETURN_STRING(value,1);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_owsrequest = (php_owsrequest_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  value = cgirequestObj_getName(php_owsrequest->cgirequest, index);
+  if (!value)
+    RETURN_STRING("", 1);
+
+  RETURN_STRING(value,1);
 }
 /* }}} */
 
-/* {{{ proto string owsrequest.getValue(int index) 
+/* {{{ proto string owsrequest.getValue(int index)
    Return the value of the parameter at index in the request’s array of parameter values.*/
 PHP_METHOD(OWSRequestObj, getValue)
 {
-    long index;
-    zval *zobj = getThis();
-    char *value = NULL;
-    php_owsrequest_object *php_owsrequest;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
-                              &index) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  long index;
+  zval *zobj = getThis();
+  char *value = NULL;
+  php_owsrequest_object *php_owsrequest;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
+                            &index) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_owsrequest = (php_owsrequest_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-
-    value = cgirequestObj_getValue(php_owsrequest->cgirequest, index);
-    if (!value)
-        RETURN_STRING("", 1);
-    
-    RETURN_STRING(value,1);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_owsrequest = (php_owsrequest_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  value = cgirequestObj_getValue(php_owsrequest->cgirequest, index);
+  if (!value)
+    RETURN_STRING("", 1);
+
+  RETURN_STRING(value,1);
 }
 /* }}} */
 
@@ -289,130 +315,127 @@ PHP_METHOD(OWSRequestObj, getValue)
    Return the value associated with the parameter name.*/
 PHP_METHOD(OWSRequestObj, getValueByName)
 {
-    char *name;
-    long name_len;
-    zval *zobj = getThis();
-    char *value = NULL;
-    php_owsrequest_object *php_owsrequest;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &name, &name_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *name;
+  long name_len;
+  zval *zobj = getThis();
+  char *value = NULL;
+  php_owsrequest_object *php_owsrequest;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &name, &name_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_owsrequest = (php_owsrequest_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-
-    value = cgirequestObj_getValueByName(php_owsrequest->cgirequest, name);
-    if (!value)
-        RETURN_STRING("", 1);
-    
-    RETURN_STRING(value,1);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_owsrequest = (php_owsrequest_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  value = cgirequestObj_getValueByName(php_owsrequest->cgirequest, name);
+  if (!value)
+    RETURN_STRING("", 1);
+
+  RETURN_STRING(value,1);
 }
 /* }}} */
 
 zend_function_entry owsrequest_functions[] = {
-    PHP_ME(OWSRequestObj, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
-    PHP_ME(OWSRequestObj, __get, owsrequest___get_args, ZEND_ACC_PUBLIC)
-    PHP_ME(OWSRequestObj, __set, owsrequest___set_args, ZEND_ACC_PUBLIC)
-    PHP_ME(OWSRequestObj, loadParams, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(OWSRequestObj, setParameter, owsrequest_setParameter_args, ZEND_ACC_PUBLIC)
-    PHP_ME(OWSRequestObj, getName, owsrequest_getName_args, ZEND_ACC_PUBLIC)
-    PHP_ME(OWSRequestObj, getValue, owsrequest_getValue_args, ZEND_ACC_PUBLIC)
-    PHP_ME(OWSRequestObj, getValueByName, owsrequest_getValueByName_args, ZEND_ACC_PUBLIC)
-    {NULL, NULL, NULL}
+  PHP_ME(OWSRequestObj, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
+  PHP_ME(OWSRequestObj, __get, owsrequest___get_args, ZEND_ACC_PUBLIC)
+  PHP_ME(OWSRequestObj, __set, owsrequest___set_args, ZEND_ACC_PUBLIC)
+  PHP_ME(OWSRequestObj, loadParams, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(OWSRequestObj, setParameter, owsrequest_setParameter_args, ZEND_ACC_PUBLIC)
+  PHP_ME(OWSRequestObj, addParameter, owsrequest_addParameter_args, ZEND_ACC_PUBLIC)
+  PHP_ME(OWSRequestObj, getName, owsrequest_getName_args, ZEND_ACC_PUBLIC)
+  PHP_ME(OWSRequestObj, getValue, owsrequest_getValue_args, ZEND_ACC_PUBLIC)
+  PHP_ME(OWSRequestObj, getValueByName, owsrequest_getValueByName_args, ZEND_ACC_PUBLIC) {
+    NULL, NULL, NULL
+  }
 };
 
 char *owsrequest_getenv(const char *name, void *thread_context)
 {
-    zval **val, **ppzval;
-    zval *cookie_result, *key;
-    HashTable *cookies;
-    char *string_key = NULL, *cookie_tmp;
-    ulong num_key;
-    int numElements, i = 0;
-    TSRMLS_FETCH_FROM_CTX(thread_context);
-
-    if  (STRING_EQUAL(name, "HTTP_COOKIE"))
-    {
-        cookies = PG(http_globals)[TRACK_VARS_COOKIE]->value.ht;
-        numElements = zend_hash_num_elements(cookies);
-        MAKE_STD_ZVAL(cookie_result);
-        ZVAL_STRING(cookie_result, "",1);
-        for(zend_hash_internal_pointer_reset(cookies); 
-            zend_hash_has_more_elements(cookies) == SUCCESS; 
-            zend_hash_move_forward(cookies), ++i)
-        { 
-            zend_hash_get_current_data(cookies, (void **)&ppzval);
-            zend_hash_get_current_key(cookies, &string_key, &num_key, 1);
-            cookie_tmp = malloc((strlen(string_key)+Z_STRLEN_PP(ppzval)+3) * sizeof(char));
-            sprintf(cookie_tmp, "%s=%s;",string_key,Z_STRVAL_PP(ppzval));
-            MAKE_STD_ZVAL(key);
-            ZVAL_STRING(key, cookie_tmp,1);
-            add_string_to_string(cookie_result,cookie_result, key);
-            zval_dtor(key);
-            free(cookie_tmp);
-        }
-        return Z_STRVAL_P(cookie_result);
+  zval **val, **ppzval;
+  zval *cookie_result, *key;
+  HashTable *cookies;
+  char *string_key = NULL, *cookie_tmp;
+  ulong num_key;
+  int numElements, i = 0;
+  TSRMLS_FETCH_FROM_CTX(thread_context);
+
+  if  (STRING_EQUAL(name, "HTTP_COOKIE")) {
+    cookies = PG(http_globals)[TRACK_VARS_COOKIE]->value.ht;
+    numElements = zend_hash_num_elements(cookies);
+    MAKE_STD_ZVAL(cookie_result);
+    ZVAL_STRING(cookie_result, "",1);
+    for(zend_hash_internal_pointer_reset(cookies);
+        zend_hash_has_more_elements(cookies) == SUCCESS;
+        zend_hash_move_forward(cookies), ++i) {
+      zend_hash_get_current_data(cookies, (void **)&ppzval);
+      zend_hash_get_current_key(cookies, &string_key, &num_key, 1);
+      cookie_tmp = malloc((strlen(string_key)+Z_STRLEN_PP(ppzval)+3) * sizeof(char));
+      sprintf(cookie_tmp, "%s=%s;",string_key,Z_STRVAL_PP(ppzval));
+      MAKE_STD_ZVAL(key);
+      ZVAL_STRING(key, cookie_tmp,1);
+      add_string_to_string(cookie_result,cookie_result, key);
+      zval_dtor(key);
+      free(cookie_tmp);
     }
-    else 
-    {
-        zend_is_auto_global("_SERVER", sizeof("_SERVER")-1 TSRMLS_CC);
-        if ( PG(http_globals)[TRACK_VARS_SERVER] &&
-             (zend_hash_find(PG(http_globals)[TRACK_VARS_SERVER]->value.ht, name, strlen(name)+1, (void **) &val) == SUCCESS) &&
-             (Z_TYPE_PP(val) == IS_STRING))
-        {
-            return Z_STRVAL_PP(val);
-        }
+    return Z_STRVAL_P(cookie_result);
+  } else {
+    zend_is_auto_global("_SERVER", sizeof("_SERVER")-1 TSRMLS_CC);
+    if ( PG(http_globals)[TRACK_VARS_SERVER] &&
+         (zend_hash_find(PG(http_globals)[TRACK_VARS_SERVER]->value.ht, name, strlen(name)+1, (void **) &val) == SUCCESS) &&
+         (Z_TYPE_PP(val) == IS_STRING)) {
+      return Z_STRVAL_PP(val);
     }
-    
-    return NULL;
+  }
+
+  return NULL;
 }
 
 void mapscript_create_owsrequest(cgiRequestObj *cgirequest, zval *return_value TSRMLS_DC)
 {
-    php_owsrequest_object * php_owsrequest;
-    object_init_ex(return_value, mapscript_ce_owsrequest); 
-    php_owsrequest = (php_owsrequest_object *)zend_object_store_get_object(return_value TSRMLS_CC);
-    php_owsrequest->cgirequest = cgirequest;
+  php_owsrequest_object * php_owsrequest;
+  object_init_ex(return_value, mapscript_ce_owsrequest);
+  php_owsrequest = (php_owsrequest_object *)zend_object_store_get_object(return_value TSRMLS_CC);
+  php_owsrequest->cgirequest = cgirequest;
 }
 
 static void mapscript_owsrequest_object_destroy(void *object TSRMLS_DC)
 {
-    php_owsrequest_object *php_owsrequest = (php_owsrequest_object *)object;
+  php_owsrequest_object *php_owsrequest = (php_owsrequest_object *)object;
+
+  MAPSCRIPT_FREE_OBJECT(php_owsrequest);
 
-    MAPSCRIPT_FREE_OBJECT(php_owsrequest);
+  cgirequestObj_destroy(php_owsrequest->cgirequest);
 
-    cgirequestObj_destroy(php_owsrequest->cgirequest); 
-    
-    efree(object);
+  efree(object);
 }
 
 static zend_object_value mapscript_owsrequest_object_new(zend_class_entry *ce TSRMLS_DC)
 {
-    zend_object_value retval;
-    php_owsrequest_object *php_owsrequest;
+  zend_object_value retval;
+  php_owsrequest_object *php_owsrequest;
 
-    MAPSCRIPT_ALLOC_OBJECT(php_owsrequest, php_owsrequest_object);
+  MAPSCRIPT_ALLOC_OBJECT(php_owsrequest, php_owsrequest_object);
 
-    retval = mapscript_object_new(&php_owsrequest->std, ce,
-                                  &mapscript_owsrequest_object_destroy TSRMLS_CC);
-    return retval;
+  retval = mapscript_object_new(&php_owsrequest->std, ce,
+                                &mapscript_owsrequest_object_destroy TSRMLS_CC);
+  return retval;
 }
 
 PHP_MINIT_FUNCTION(owsrequest)
 {
-    zend_class_entry ce;
+  zend_class_entry ce;
 
-    MAPSCRIPT_REGISTER_CLASS("OWSRequestObj", 
-                             owsrequest_functions,
-                             mapscript_ce_owsrequest,
-                             mapscript_owsrequest_object_new);
+  MAPSCRIPT_REGISTER_CLASS("OWSRequestObj",
+                           owsrequest_functions,
+                           mapscript_ce_owsrequest,
+                           mapscript_owsrequest_object_new);
 
-    mapscript_ce_owsrequest->ce_flags |= ZEND_ACC_FINAL_CLASS; 
+  mapscript_ce_owsrequest->ce_flags |= ZEND_ACC_FINAL_CLASS;
 
-    return SUCCESS;
+  return SUCCESS;
 }
 
diff --git a/mapscript/php/php_mapscript.c b/mapscript/php/php_mapscript.c
index 201f3fa..f757d9f 100644
--- a/mapscript/php/php_mapscript.c
+++ b/mapscript/php/php_mapscript.c
@@ -2,7 +2,7 @@
  * $Id$
  *
  * Project:  MapServer
- * Purpose:  PHP/MapScript extension for MapServer.  External interface 
+ * Purpose:  PHP/MapScript extension for MapServer.  External interface
  *           functions
  * Author:   Daniel Morissette, DM Solutions Group (dmorissette at dmsolutions.ca)
  *
@@ -15,19 +15,19 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
+ *
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  * DEALINGS IN THE SOFTWARE.
  **********************************************************************/
- 
+
 
 #include "php_mapscript.h"
 #include "php_mapscript_util.h"
@@ -37,7 +37,7 @@
 #include "ext/standard/info.h"
 #include "ext/standard/head.h"
 
-#include "maperror.h"
+#include "../../maperror.h"
 
 #include <time.h>
 
@@ -51,12 +51,12 @@
    "main/php_compat.h" file of php source) should be added here too for
    compatibility reasons: when php compiles gd as a shared extention */
 #if defined(HAVE_GD_BUNDLED)
-#undef gdImageColorExact                                                                    
+#undef gdImageColorExact
 #undef gdImageColorTransparent
 #undef gdImageCopy
 #endif
 
-#ifndef DLEXPORT 
+#ifndef DLEXPORT
 #define DLEXPORT ZEND_DLEXPORT
 #endif
 
@@ -67,159 +67,155 @@
 zend_object_handlers mapscript_std_object_handlers;
 
 ZEND_BEGIN_ARG_INFO_EX(ms_newShapeObj_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, type)
+ZEND_ARG_INFO(0, type)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(ms_shapeObjFromWkt_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, wkt)
+ZEND_ARG_INFO(0, wkt)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(ms_newShapeFileObj_args, 0, 0, 2)
-  ZEND_ARG_INFO(0, filename)
-  ZEND_ARG_INFO(0, type)
+ZEND_ARG_INFO(0, filename)
+ZEND_ARG_INFO(0, type)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(ms_newMapObj_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, mapFileName)
-  ZEND_ARG_INFO(0, newMapPath)
+ZEND_ARG_INFO(0, mapFileName)
+ZEND_ARG_INFO(0, newMapPath)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(ms_newMapObjFromString_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, mapFileString)
-  ZEND_ARG_INFO(0, newMapPath)
+ZEND_ARG_INFO(0, mapFileString)
+ZEND_ARG_INFO(0, newMapPath)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(ms_newLayerObj_args, 0, 0, 1)
-  ZEND_ARG_OBJ_INFO(0, map, mapObj, 0)
-  ZEND_ARG_OBJ_INFO(0, layer, layerObj, 0)
+ZEND_ARG_OBJ_INFO(0, map, mapObj, 0)
+ZEND_ARG_OBJ_INFO(0, layer, layerObj, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(ms_newProjectionObj_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, projString)
+ZEND_ARG_INFO(0, projString)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(ms_newStyleObj_args, 0, 0, 1)
-  ZEND_ARG_OBJ_INFO(0, class, classObj, 0)
-  ZEND_ARG_OBJ_INFO(0, style, styleObj, 0)
+ZEND_ARG_OBJ_INFO(0, class, classObj, 0)
+ZEND_ARG_OBJ_INFO(0, style, styleObj, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(ms_newClassObj_args, 0, 0, 1)
-  ZEND_ARG_OBJ_INFO(0, layer, layerObj, 0)
-  ZEND_ARG_OBJ_INFO(0, class, classObj, 0)
+ZEND_ARG_OBJ_INFO(0, layer, layerObj, 0)
+ZEND_ARG_OBJ_INFO(0, class, classObj, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(ms_newSymbolObj_args, 0, 0, 2)
-  ZEND_ARG_OBJ_INFO(0, map, mapObj, 0)
-  ZEND_ARG_INFO(0, symbolName)
+ZEND_ARG_OBJ_INFO(0, map, mapObj, 0)
+ZEND_ARG_INFO(0, symbolName)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(ms_newGridObj_args, 0, 0, 1)
-  ZEND_ARG_OBJ_INFO(0, layer, layerObj, 0)
+ZEND_ARG_OBJ_INFO(0, layer, layerObj, 0)
 ZEND_END_ARG_INFO()
 
-/* {{{ proto mapObj ms_newMapObj(string mapFileName, newMapPath) 
+/* {{{ proto mapObj ms_newMapObj(string mapFileName, newMapPath)
    Create a new mapObj instance. */
 PHP_FUNCTION(ms_newMapObj)
 {
-    char *filename;
-    long filename_len;
-    char *path = NULL;
-    long path_len;
-    mapObj *map = NULL;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s",
-                              &filename, &filename_len,
-                              &path, &path_len) == FAILURE) {
-        return;
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    }    
+  char *filename;
+  long filename_len;
+  char *path = NULL;
+  long path_len;
+  mapObj *map = NULL;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s",
+                            &filename, &filename_len,
+                            &path, &path_len) == FAILURE) {
+    return;
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    map = mapObj_new(filename, path);
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    if (map == NULL)
-    {
-        mapscript_throw_mapserver_exception("Failed to open map file \"%s\"" TSRMLS_CC,  filename);
-        return;
-    }
+  map = mapObj_new(filename, path);
+
+  if (map == NULL) {
+    mapscript_throw_mapserver_exception("Failed to open map file \"%s\", or map file error." TSRMLS_CC,  filename);
+    return;
+  }
 
-    mapscript_create_map(map, return_value TSRMLS_CC);
+  mapscript_create_map(map, return_value TSRMLS_CC);
 }
 /* }}} */
 
-/* {{{ proto mapObj ms_newMapObj(string mapFileString, newMapPath) 
+/* {{{ proto mapObj ms_newMapObj(string mapFileString, newMapPath)
    Create a new mapObj instance. */
 PHP_FUNCTION(ms_newMapObjFromString)
 {
-    char *string;
-    long string_len;
-    char *path = NULL;
-    long path_len;
-    mapObj *map = NULL;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s",
-                              &string, &string_len,
-                              &path, &path_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *string;
+  long string_len;
+  char *path = NULL;
+  long path_len;
+  mapObj *map = NULL;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s",
+                            &string, &string_len,
+                            &path, &path_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    map = mapObj_newFromString(string, path);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    if (map == NULL)
-    {
-        mapscript_throw_mapserver_exception("Failed to open map file \"%s\"" TSRMLS_CC,  string);
-        return;
-    }
+  map = mapObj_newFromString(string, path);
+
+  if (map == NULL) {
+    mapscript_throw_mapserver_exception("Failed to open map file \"%s\", or map file error." TSRMLS_CC,  string);
+    return;
+  }
 
-    mapscript_create_map(map, return_value TSRMLS_CC);
+  mapscript_create_map(map, return_value TSRMLS_CC);
 }
 /* }}} */
 
-/* {{{ proto layerObj ms_newLayerObj(mapObj map [, layerObj layer]) 
+/* {{{ proto layerObj ms_newLayerObj(mapObj map [, layerObj layer])
    Create a new layerObj instance. */
 PHP_FUNCTION(ms_newLayerObj)
 {
-    zval *zmap, *zlayer = NULL;
-    layerObj *layer;
-    int index;
-    php_map_object *php_map;
-    php_layer_object *php_layer;
-    parent_object parent;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O|O",
-                              &zmap, mapscript_ce_map,
-                              &zlayer, mapscript_ce_layer) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zmap, *zlayer = NULL;
+  layerObj *layer;
+  int index;
+  php_map_object *php_map;
+  php_layer_object *php_layer;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O|O",
+                            &zmap, mapscript_ce_map,
+                            &zlayer, mapscript_ce_layer) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-
-    php_map = (php_map_object *)zend_object_store_get_object(zmap TSRMLS_CC);
-    if (zlayer)
-        php_layer = (php_layer_object *)zend_object_store_get_object(zlayer TSRMLS_CC);
-
-    if ((layer = layerObj_new(php_map->map)) == NULL)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
-
-    /* if a layer is passed as argument, copy the layer into
-       the new one */
-    if (zlayer)
-    {
-        index = layer->index;
-        msCopyLayer(layer, php_layer->layer);
-        layer->index = index;
-    }
-
-    MAPSCRIPT_MAKE_PARENT(zmap, NULL);
-    mapscript_create_layer(layer, parent, return_value TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *)zend_object_store_get_object(zmap TSRMLS_CC);
+  if (zlayer)
+    php_layer = (php_layer_object *)zend_object_store_get_object(zlayer TSRMLS_CC);
+
+  if ((layer = layerObj_new(php_map->map)) == NULL) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
+
+  /* if a layer is passed as argument, copy the layer into
+     the new one */
+  if (zlayer) {
+    index = layer->index;
+    msCopyLayer(layer, php_layer->layer);
+    layer->index = index;
+  }
+
+  MAPSCRIPT_MAKE_PARENT(zmap, NULL);
+  mapscript_create_layer(layer, parent, return_value TSRMLS_CC);
 }
 /* }}} */
 
@@ -227,27 +223,26 @@ PHP_FUNCTION(ms_newLayerObj)
    Create a new projectionObj instance. */
 PHP_FUNCTION(ms_newProjectionObj)
 {
-    char *projString;
-    long projString_len;
-    projectionObj *projection = NULL;
-    parent_object parent;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &projString, &projString_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
-    PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);    
+  char *projString;
+  long projString_len;
+  projectionObj *projection = NULL;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &projString, &projString_len) == FAILURE) {
+    PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    if ((projection = projectionObj_new(projString)) == NULL)
-    {
-        mapscript_throw_mapserver_exception("Unable to construct projectionObj." TSRMLS_CC);
-        return;
-    }
-    
-    MAPSCRIPT_MAKE_PARENT(NULL, NULL);
-    mapscript_create_projection(projection, parent, return_value TSRMLS_CC);
+  if ((projection = projectionObj_new(projString)) == NULL) {
+    mapscript_throw_mapserver_exception("Unable to construct projectionObj." TSRMLS_CC);
+    return;
+  }
+
+  MAPSCRIPT_MAKE_PARENT(NULL, NULL);
+  mapscript_create_projection(projection, parent, return_value TSRMLS_CC);
 }
 /* }}} */
 
@@ -255,148 +250,143 @@ PHP_FUNCTION(ms_newProjectionObj)
    Create a new rectObj instance. */
 PHP_FUNCTION(ms_newRectObj)
 {
-    php_rect_object * php_rect;
+  php_rect_object * php_rect;
 
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    object_init_ex(return_value, mapscript_ce_rect); 
-    php_rect = (php_rect_object *)zend_object_store_get_object(return_value TSRMLS_CC);
-    
-    if ((php_rect->rect = rectObj_new()) == NULL)
-    {
-        mapscript_throw_exception("Unable to construct rectObj." TSRMLS_CC);
-        return;
-    }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  object_init_ex(return_value, mapscript_ce_rect);
+  php_rect = (php_rect_object *)zend_object_store_get_object(return_value TSRMLS_CC);
+
+  if ((php_rect->rect = rectObj_new()) == NULL) {
+    mapscript_throw_exception("Unable to construct rectObj." TSRMLS_CC);
+    return;
+  }
 }
 /* }}} */
 
-/* {{{ proto pointObj ms_newPointObj()                                                                                                    
-   Create a new pointObj instance. */ 
+/* {{{ proto pointObj ms_newPointObj()
+   Create a new pointObj instance. */
 PHP_FUNCTION(ms_newPointObj)
 {
-    pointObj *point = NULL;
-    parent_object parent;
+  pointObj *point = NULL;
+  parent_object parent;
 
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    if ((point = pointObj_new()) == NULL)
-    {
-        mapscript_throw_mapserver_exception("Unable to construct pointObj." TSRMLS_CC);
-        return;
-    }
+  if ((point = pointObj_new()) == NULL) {
+    mapscript_throw_mapserver_exception("Unable to construct pointObj." TSRMLS_CC);
+    return;
+  }
 
-    point->x = 0;
-    point->y = 0;
+  point->x = 0;
+  point->y = 0;
 #ifdef USE_POINT_Z_M
-    point->z = 0;
-    point->m = 0;
+  point->z = 0;
+  point->m = 0;
 #endif
 
-    /* Return point object */
-    MAPSCRIPT_MAKE_PARENT(NULL, NULL);
-    mapscript_create_point(point, parent, return_value TSRMLS_CC);
+  /* Return point object */
+  MAPSCRIPT_MAKE_PARENT(NULL, NULL);
+  mapscript_create_point(point, parent, return_value TSRMLS_CC);
 }
 
 /* {{{ proto lineObj ms_newLineObj()
    Create a new lineObj instance. */
 PHP_FUNCTION(ms_newLineObj)
 {
-    php_line_object * php_line;
+  php_line_object * php_line;
 
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    object_init_ex(return_value, mapscript_ce_line); 
-    php_line = (php_line_object *)zend_object_store_get_object(return_value TSRMLS_CC);
-    
-    if ((php_line->line = lineObj_new()) == NULL)
-    {
-        mapscript_throw_exception("Unable to construct lineObj." TSRMLS_CC);
-        return;
-    }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  object_init_ex(return_value, mapscript_ce_line);
+  php_line = (php_line_object *)zend_object_store_get_object(return_value TSRMLS_CC);
+
+  if ((php_line->line = lineObj_new()) == NULL) {
+    mapscript_throw_exception("Unable to construct lineObj." TSRMLS_CC);
+    return;
+  }
 }
 /* }}} */
 
-/* {{{ proto styleObj __construct(classObj class [, styleObj style]) 
+/* {{{ proto styleObj __construct(classObj class [, styleObj style])
    Create a new styleObj instance */
 PHP_FUNCTION(ms_newStyleObj)
 {
-    zval *zclass, *zstyle = NULL;
-    styleObj *style;
-    php_class_object *php_class;
-    php_style_object *php_style;
-    parent_object parent;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O|O",
-                              &zclass, mapscript_ce_class,
-                              &zstyle, mapscript_ce_style) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zclass, *zstyle = NULL;
+  styleObj *style;
+  php_class_object *php_class;
+  php_style_object *php_style;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O|O",
+                            &zclass, mapscript_ce_class,
+                            &zstyle, mapscript_ce_style) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-
-    php_class = (php_class_object *)zend_object_store_get_object(zclass TSRMLS_CC);
-    if (zstyle)
-        php_style = (php_style_object *)zend_object_store_get_object(zstyle TSRMLS_CC);
-
-    if ((style = styleObj_new(php_class->class, (zstyle ? php_style->style : NULL))) == NULL)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
-
-    /* Return point object */
-    MAPSCRIPT_MAKE_PARENT(zclass, NULL);
-    mapscript_create_style(style, parent, return_value TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_class = (php_class_object *)zend_object_store_get_object(zclass TSRMLS_CC);
+  if (zstyle)
+    php_style = (php_style_object *)zend_object_store_get_object(zstyle TSRMLS_CC);
+
+  if ((style = styleObj_new(php_class->class, (zstyle ? php_style->style : NULL))) == NULL) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
+
+  /* Return point object */
+  MAPSCRIPT_MAKE_PARENT(zclass, NULL);
+  mapscript_create_style(style, parent, return_value TSRMLS_CC);
 }
 
 /* {{{ proto classObj ms_newClassObj(layerObj layer [, classObj class])
    Create a new class instance in the specified layer.. */
 PHP_FUNCTION(ms_newClassObj)
 {
-    zval *zlayer, *zclass = NULL;
-    classObj *class;
-    php_layer_object *php_layer;
-    php_class_object *php_class;
-    parent_object parent;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O|O",
-                              &zlayer, mapscript_ce_layer,
-                              &zclass, mapscript_ce_class) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zlayer, *zclass = NULL;
+  classObj *class;
+  php_layer_object *php_layer;
+  php_class_object *php_class;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O|O",
+                            &zlayer, mapscript_ce_layer,
+                            &zclass, mapscript_ce_class) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_layer = (php_layer_object *) zend_object_store_get_object(zlayer TSRMLS_CC);
-    if (zclass)
-        php_class = (php_class_object *) zend_object_store_get_object(zclass TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
+  php_layer = (php_layer_object *) zend_object_store_get_object(zlayer TSRMLS_CC);
+  if (zclass)
+    php_class = (php_class_object *) zend_object_store_get_object(zclass TSRMLS_CC);
 
-    if ((class = classObj_new(php_layer->layer, (zclass ? php_class->class:NULL))) == NULL)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
 
-    MAPSCRIPT_MAKE_PARENT(zlayer, NULL);
-    mapscript_create_class(class, parent, return_value TSRMLS_CC);
+  if ((class = classObj_new(php_layer->layer, (zclass ? php_class->class:NULL))) == NULL) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
+
+  MAPSCRIPT_MAKE_PARENT(zlayer, NULL);
+  mapscript_create_class(class, parent, return_value TSRMLS_CC);
 }
 /* }}} */
 
@@ -404,26 +394,26 @@ PHP_FUNCTION(ms_newClassObj)
    Create a new symbolObj instance and return its index. */
 PHP_FUNCTION(ms_newSymbolObj)
 {
-    zval *zmap;
-    char *symbolName;
-    long symbolName_len;
-    int retval = 0;
-    php_map_object *php_map;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Os",
-                              &zmap, mapscript_ce_map, 
-                              &symbolName, &symbolName_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zmap;
+  char *symbolName;
+  long symbolName_len;
+  int retval = 0;
+  php_map_object *php_map;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Os",
+                            &zmap, mapscript_ce_map,
+                            &symbolName, &symbolName_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_map = (php_map_object *)zend_object_store_get_object(zmap TSRMLS_CC);
-    
-    retval = msAddNewSymbol(php_map->map, symbolName);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_map = (php_map_object *)zend_object_store_get_object(zmap TSRMLS_CC);
 
-    RETURN_LONG(retval);
+  retval = msAddNewSymbol(php_map->map, symbolName);
+
+  RETURN_LONG(retval);
 }
 /* }}} */
 
@@ -431,28 +421,27 @@ PHP_FUNCTION(ms_newSymbolObj)
    Create a new shapeObj instance. */
 PHP_FUNCTION(ms_newShapeObj)
 {
-    php_shape_object * php_shape;
-    long type;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
-                              &type) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  php_shape_object * php_shape;
+  long type;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
+                            &type) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    object_init_ex(return_value, mapscript_ce_shape); 
-    php_shape = (php_shape_object *)zend_object_store_get_object(return_value TSRMLS_CC);
-    
-    if ((php_shape->shape = shapeObj_new(type)) == NULL)
-    {
-        mapscript_throw_exception("Unable to construct shapeObj." TSRMLS_CC);
-        return;
-    }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  object_init_ex(return_value, mapscript_ce_shape);
+  php_shape = (php_shape_object *)zend_object_store_get_object(return_value TSRMLS_CC);
+
+  if ((php_shape->shape = shapeObj_new(type)) == NULL) {
+    mapscript_throw_exception("Unable to construct shapeObj." TSRMLS_CC);
+    return;
+  }
 
-    MAKE_STD_ZVAL(php_shape->values);
-    array_init(php_shape->values);
+  MAKE_STD_ZVAL(php_shape->values);
+  array_init(php_shape->values);
 }
 /* }}} */
 
@@ -460,29 +449,28 @@ PHP_FUNCTION(ms_newShapeObj)
    Creates new shape object from WKT string. */
 PHP_FUNCTION(ms_shapeObjFromWkt)
 {
-    php_shape_object * php_shape;
-    char *wkt;
-    long str_len;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &wkt, &str_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  php_shape_object * php_shape;
+  char *wkt;
+  long str_len;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &wkt, &str_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    object_init_ex(return_value, mapscript_ce_shape); 
-    php_shape = (php_shape_object *)zend_object_store_get_object(return_value TSRMLS_CC);
-    
-    if ((php_shape->shape = msShapeFromWKT(wkt)) == NULL)
-    {
-        mapscript_throw_exception("Unable to construct shapeObj." TSRMLS_CC);
-        return;
-    }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    MAKE_STD_ZVAL(php_shape->values);
-    array_init(php_shape->values);
+  object_init_ex(return_value, mapscript_ce_shape);
+  php_shape = (php_shape_object *)zend_object_store_get_object(return_value TSRMLS_CC);
+
+  if ((php_shape->shape = msShapeFromWKT(wkt)) == NULL) {
+    mapscript_throw_exception("Unable to construct shapeObj." TSRMLS_CC);
+    return;
+  }
+
+  MAKE_STD_ZVAL(php_shape->values);
+  array_init(php_shape->values);
 }
 /* }}} */
 
@@ -490,92 +478,90 @@ PHP_FUNCTION(ms_shapeObjFromWkt)
    Create a new shapeFileObj instance. */
 PHP_FUNCTION(ms_newShapeFileObj)
 {
-    char *filename;
-    long filename_len;
-    long type;
-    shapefileObj *shapefile;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sl",
-                              &filename, &filename_len, &type) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *filename;
+  long filename_len;
+  long type;
+  shapefileObj *shapefile;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sl",
+                            &filename, &filename_len, &type) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    shapefile = shapefileObj_new(filename, type);
-    if (shapefile == NULL)
-    {
-        mapscript_throw_mapserver_exception("Failed to open shapefile %s" TSRMLS_CC, filename);
-        return;
-    }
-    
-    mapscript_create_shapefile(shapefile, return_value TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  shapefile = shapefileObj_new(filename, type);
+  if (shapefile == NULL) {
+    mapscript_throw_mapserver_exception("Failed to open shapefile %s" TSRMLS_CC, filename);
+    return;
+  }
+
+  mapscript_create_shapefile(shapefile, return_value TSRMLS_CC);
 }
 /* }}} */
 
 PHP_FUNCTION(ms_newOWSRequestObj)
 {
-    cgiRequestObj *request;
+  cgiRequestObj *request;
 
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    if ((request = cgirequestObj_new()) == NULL)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
+  if ((request = cgirequestObj_new()) == NULL) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
 
-    /* Return owsrequest object */
-    mapscript_create_owsrequest(request, return_value TSRMLS_CC);
+  /* Return owsrequest object */
+  mapscript_create_owsrequest(request, return_value TSRMLS_CC);
 }
 
 /* {{{ proto gridObj ms_newGridObj(layerObj layer)
    Create a new intance of gridObj. */
 PHP_FUNCTION(ms_newGridObj)
 {
-    zval *zlayer;
-    php_layer_object *php_layer;
-    php_grid_object *php_grid;
-    parent_object parent;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
-                              &zlayer, mapscript_ce_layer) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zlayer;
+  php_layer_object *php_layer;
+  php_grid_object *php_grid;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
+                            &zlayer, mapscript_ce_layer) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_layer = (php_layer_object *) zend_object_store_get_object(zlayer TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_layer->layer->connectiontype = MS_GRATICULE;
+  php_layer = (php_layer_object *) zend_object_store_get_object(zlayer TSRMLS_CC);
 
-    if (php_layer->layer->layerinfo != NULL)
-        free(php_layer->layer->layerinfo);
+  php_layer->layer->connectiontype = MS_GRATICULE;
 
+  if (php_layer->layer->layerinfo != NULL)
+    free(php_layer->layer->layerinfo);
 
-    php_layer->layer->layerinfo = (graticuleObj *)malloc( sizeof( graticuleObj ) );
-    initGrid((graticuleObj *)php_layer->layer->layerinfo);
 
-    if (php_layer->grid && (Z_TYPE_P(php_layer->grid) == IS_OBJECT)) {
-        php_grid = (php_grid_object *) zend_object_store_get_object(php_layer->grid TSRMLS_CC);
-        php_grid->parent.child_ptr = NULL;
-        zend_objects_store_del_ref(php_layer->grid TSRMLS_CC);
-    }
-    
-    MAKE_STD_ZVAL(php_layer->grid);
+  php_layer->layer->layerinfo = (graticuleObj *)malloc( sizeof( graticuleObj ) );
+  initGrid((graticuleObj *)php_layer->layer->layerinfo);
+
+  if (php_layer->grid && (Z_TYPE_P(php_layer->grid) == IS_OBJECT)) {
+    php_grid = (php_grid_object *) zend_object_store_get_object(php_layer->grid TSRMLS_CC);
+    php_grid->parent.child_ptr = NULL;
+    zend_objects_store_del_ref(php_layer->grid TSRMLS_CC);
+  }
+
+  MAKE_STD_ZVAL(php_layer->grid);
 
-    MAPSCRIPT_MAKE_PARENT(zlayer, &php_layer->grid);
-    mapscript_create_grid((graticuleObj *)(php_layer->layer->layerinfo), parent, php_layer->grid TSRMLS_CC);
-    zend_objects_store_add_ref(php_layer->grid TSRMLS_CC);
+  MAPSCRIPT_MAKE_PARENT(zlayer, &php_layer->grid);
+  mapscript_create_grid((graticuleObj *)(php_layer->layer->layerinfo), parent, php_layer->grid TSRMLS_CC);
+  zend_objects_store_add_ref(php_layer->grid TSRMLS_CC);
 
-    *return_value = *(php_layer->grid);
+  *return_value = *(php_layer->grid);
 }
 /* }}} */
 
@@ -583,23 +569,22 @@ PHP_FUNCTION(ms_newGridObj)
    Return the head of the MapServer errorObj list. */
 PHP_FUNCTION(ms_GetErrorObj)
 {
-    errorObj *error;
-    
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  errorObj *error;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    if ((error = msGetErrorObj()) == NULL)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
+  if ((error = msGetErrorObj()) == NULL) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
 
-    /* Return error object */
-    mapscript_create_error(error, return_value TSRMLS_CC);
+  /* Return error object */
+  mapscript_create_error(error, return_value TSRMLS_CC);
 }
 /* }}} */
 
@@ -607,7 +592,7 @@ PHP_FUNCTION(ms_GetErrorObj)
    Clear the MapServer errorObj list. */
 PHP_FUNCTION(ms_ResetErrorList)
 {
-    msResetErrorList();
+  msResetErrorList();
 }
 /* }} */
 
@@ -623,14 +608,14 @@ PHP_FUNCTION(ms_ResetErrorList)
 /************************************************************************/
 PHP_FUNCTION(ms_GetVersion)
 {
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    RETURN_STRING(msGetVersion(), 1);
+  RETURN_STRING(msGetVersion(), 1);
 }
 
 /************************************************************************/
@@ -641,14 +626,14 @@ PHP_FUNCTION(ms_GetVersion)
 /************************************************************************/
 PHP_FUNCTION(ms_GetVersionInt)
 {
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    RETURN_LONG(msGetVersionInt());
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  RETURN_LONG(msGetVersionInt());
 }
 
 /* ==================================================================== */
@@ -656,105 +641,105 @@ PHP_FUNCTION(ms_GetVersionInt)
 /* ==================================================================== */
 PHP_FUNCTION(ms_ioInstallStdoutToBuffer)
 {
-    msIO_installStdoutToBuffer();
+  msIO_installStdoutToBuffer();
 
-    RETURN_TRUE;
+  RETURN_TRUE;
 }
 
 
 PHP_FUNCTION(ms_ioResetHandlers)
 {
-    msIO_resetHandlers();
-    RETURN_TRUE;
+  msIO_resetHandlers();
+  RETURN_TRUE;
 }
 
 
 PHP_FUNCTION(ms_ioInstallStdinFromBuffer)
 {
-    msIO_installStdinFromBuffer();
+  msIO_installStdinFromBuffer();
 
-    RETURN_TRUE;
+  RETURN_TRUE;
 }
 
 PHP_FUNCTION(ms_ioGetStdoutBufferString)
 {
-    char *buffer;
+  char *buffer;
 
-    msIOContext *ctx = msIO_getHandler( (FILE *) "stdout" );
-    msIOBuffer  *buf;
+  msIOContext *ctx = msIO_getHandler( (FILE *) "stdout" );
+  msIOBuffer  *buf;
 
-    if(ctx == NULL ||  ctx->write_channel == MS_FALSE
-        || strcmp(ctx->label,"buffer") != 0 )
-    {
-        php_error(E_ERROR, "Can't identify msIO buffer");
-        RETURN_FALSE;
-    }
-    
-    buf = (msIOBuffer *) ctx->cbData;
+  if(ctx == NULL ||  ctx->write_channel == MS_FALSE
+      || strcmp(ctx->label,"buffer") != 0 ) {
+    php_error(E_ERROR, "Can't identify msIO buffer");
+    RETURN_FALSE;
+  }
 
-    /* write one zero byte and backtrack if it isn't already there */
-    if( buf->data_len == 0 || buf->data[buf->data_offset] != '\0' ) {
-        msIO_bufferWrite( buf, "", 1 );
-	buf->data_offset--;
-    }
+  buf = (msIOBuffer *) ctx->cbData;
+
+  /* write one zero byte and backtrack if it isn't already there */
+  if( buf->data_len == 0 || buf->data[buf->data_offset] != '\0' ) {
+    msIO_bufferWrite( buf, "", 1 );
+    buf->data_offset--;
+  }
 
-    buffer = (char *) (buf->data);
+  buffer = (char *) (buf->data);
 
-    RETURN_STRING(buffer, 1);
+  RETURN_STRINGL(buffer, buf->data_offset, 1);
 }
-  
+
 
 typedef struct {
-    unsigned char *data;
-    int size;
-    int owns_data;
+  unsigned char *data;
+  int size;
+  int owns_data;
 } gdBuffer;
 
 
 PHP_FUNCTION(ms_ioGetStdoutBufferBytes)
 {
-    msIOContext *ctx = msIO_getHandler( (FILE *) "stdout" );
-    msIOBuffer  *buf;
-    gdBuffer     gdBuf;
-
-    if( ctx == NULL || ctx->write_channel == MS_FALSE 
-        || strcmp(ctx->label,"buffer") != 0 )
-    {
-        php_error(E_ERROR, "Can't identify msIO buffer");
-        RETURN_FALSE;
-    }
+  msIOContext *ctx = msIO_getHandler( (FILE *) "stdout" );
+  msIOBuffer  *buf;
+  gdBuffer     gdBuf;
+
+  if( ctx == NULL || ctx->write_channel == MS_FALSE
+      || strcmp(ctx->label,"buffer") != 0 ) {
+    php_error(E_ERROR, "Can't identify msIO buffer");
+    RETURN_FALSE;
+  }
 
-    buf = (msIOBuffer *) ctx->cbData;
+  buf = (msIOBuffer *) ctx->cbData;
 
-    gdBuf.data = buf->data;
-    gdBuf.size = buf->data_offset;
-    gdBuf.owns_data = MS_FALSE;
+  gdBuf.data = buf->data;
+  gdBuf.size = buf->data_offset;
+  gdBuf.owns_data = MS_FALSE;
 
-    /* we are seizing ownership of the buffer contents */
-    buf->data_offset = 0;
-    buf->data_len = 0;
-    buf->data = NULL;
+  /* we are seizing ownership of the buffer contents */
+  buf->data_offset = 0;
+  buf->data_len = 0;
+  buf->data = NULL;
 
-    php_write(gdBuf.data, gdBuf.size TSRMLS_CC);
-   
-    /* return the gdBuf.size, which is the "really used length" of the msIOBuffer */
-    RETURN_LONG(gdBuf.size);
+  php_write(gdBuf.data, gdBuf.size TSRMLS_CC);
+
+  /* return the gdBuf.size, which is the "really used length" of the msIOBuffer */
+  RETURN_LONG(gdBuf.size);
 }
 
 PHP_FUNCTION(ms_ioStripStdoutBufferContentType)
 {
-    const char *buf = NULL;
+  const char *buf = NULL;
 
-    buf = msIO_stripStdoutBufferContentType();
+  buf = msIO_stripStdoutBufferContentType();
 
-    if (buf)
-    {
-        RETURN_STRING((char *)buf, 1);
-    }
-    else
-    {
-        RETURN_FALSE;
-    }
+  if (buf) {
+    RETURN_STRING((char *)buf, 1);
+  } else {
+    RETURN_FALSE;
+  }
+}
+
+PHP_FUNCTION(ms_ioStripStdoutBufferContentHeaders)
+{
+  msIO_stripStdoutBufferContentHeaders();
 }
 
 /* ==================================================================== */
@@ -787,22 +772,22 @@ PHP_FUNCTION(ms_ioStripStdoutBufferContentType)
 
 PHP_FUNCTION(ms_getCwd)
 {
-    char  buffer[PATH_MAX];
-    char *p;
-   
-    p = getcwd(buffer, PATH_MAX);
-    if (!p) {
-      //php3_error(E_WARNING, "posix_getcwd() failed with '%s'",
-      //            strerror(errno));
-        RETURN_FALSE;
-    }
+  char  buffer[PATH_MAX];
+  char *p;
+
+  p = getcwd(buffer, PATH_MAX);
+  if (!p) {
+    //php3_error(E_WARNING, "posix_getcwd() failed with '%s'",
+    //            strerror(errno));
+    RETURN_FALSE;
+  }
 
-    RETURN_STRING(buffer, 1);
+  RETURN_STRING(buffer, 1);
 }
 
 PHP_FUNCTION(ms_getPid)
 {
-    RETURN_LONG(getpid());
+  RETURN_LONG(getpid());
 }
 
 
@@ -823,36 +808,35 @@ PHP_FUNCTION(ms_getPid)
 /************************************************************************/
 PHP_FUNCTION(ms_getScale)
 {
-    zval *zgeoRefExt = NULL;
-    long width, height,unit;
-    double resolution;
-    php_rect_object *php_geoRefExt;
-    double dfScale = 0.0;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Ollld",
-                              &zgeoRefExt, mapscript_ce_rect,
-                              &width, &height, &unit, &resolution) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zgeoRefExt = NULL;
+  long width, height,unit;
+  double resolution;
+  php_rect_object *php_geoRefExt;
+  double dfScale = 0.0;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Ollld",
+                            &zgeoRefExt, mapscript_ce_rect,
+                            &width, &height, &unit, &resolution) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_geoRefExt = (php_rect_object *)zend_object_store_get_object(zgeoRefExt TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    if (msCalculateScale(*(php_geoRefExt->rect), unit, width, height, resolution, &dfScale) != MS_SUCCESS)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
-    
-    RETURN_DOUBLE(dfScale);
+  php_geoRefExt = (php_rect_object *)zend_object_store_get_object(zgeoRefExt TSRMLS_CC);
+
+  if (msCalculateScale(*(php_geoRefExt->rect), unit, width, height, resolution, &dfScale) != MS_SUCCESS) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
+
+  RETURN_DOUBLE(dfScale);
 }
 
 /**********************************************************************
  *                        ms_tokenizeMap()
  *
- * Preparse mapfile and return an array containg one item for each 
+ * Preparse mapfile and return an array containg one item for each
  * token in the map.
  **********************************************************************/
 
@@ -860,97 +844,94 @@ PHP_FUNCTION(ms_getScale)
    Preparse mapfile and return an array containg one item for each token in the map.*/
 
 PHP_FUNCTION(ms_tokenizeMap)
-{ 
-    char *filename;
-    long filename_len;
-    char  **tokens;
-    int i, numtokens=0;
-
-  
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &filename, &filename_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
-    PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+{
+  char *filename;
+  long filename_len;
+  char  **tokens;
+  int i, numtokens=0;
 
-    if ((tokens = msTokenizeMap(filename, &numtokens)) == NULL)
-    {
-        mapscript_throw_mapserver_exception("Failed tokenizing map file %s" TSRMLS_CC, 
-                                            filename);
-        return;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &filename, &filename_len) == FAILURE) {
+    PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  if ((tokens = msTokenizeMap(filename, &numtokens)) == NULL) {
+    mapscript_throw_mapserver_exception("Failed tokenizing map file %s" TSRMLS_CC,
+                                        filename);
+    return;
+  } else {
+    if (array_init(return_value) == FAILURE) {
+      RETURN_FALSE;
     }
-    else
-    {
-        if (array_init(return_value) == FAILURE) 
-        {
-            RETURN_FALSE;
-        }
-
-        for (i=0; i<numtokens; i++)
-        {
-            add_next_index_string(return_value,  tokens[i], 1);
-        }
-
-        msFreeCharArray(tokens, numtokens);
+
+    for (i=0; i<numtokens; i++) {
+      add_next_index_string(return_value,  tokens[i], 1);
     }
 
+    msFreeCharArray(tokens, numtokens);
+  }
+
 
 }
 
-function_entry mapscript_functions[] = {
-    PHP_FE(ms_GetVersion, NULL)
-    PHP_FE(ms_GetVersionInt,  NULL)
-    PHP_FE(ms_newLineObj, NULL)
-    PHP_FE(ms_newRectObj, NULL)
-    PHP_FE(ms_newShapeObj, ms_newShapeObj_args)
-    PHP_FE(ms_shapeObjFromWkt, ms_shapeObjFromWkt_args)
-    PHP_FE(ms_GetErrorObj, NULL)
-    PHP_FE(ms_ResetErrorList, NULL)
-    PHP_FE(ms_newOWSRequestObj, NULL)
-    PHP_FE(ms_newShapeFileObj, ms_newShapeFileObj_args)
-    PHP_FE(ms_newMapObj, ms_newMapObj_args)
-    PHP_FE(ms_newMapObjFromString, ms_newMapObjFromString_args)
-    PHP_FE(ms_newLayerObj, ms_newLayerObj_args)
-    PHP_FE(ms_newPointObj, NULL)
-    PHP_FE(ms_newProjectionObj, ms_newProjectionObj_args)
-    PHP_FE(ms_newStyleObj, ms_newStyleObj_args)
-    PHP_FE(ms_newSymbolObj, ms_newSymbolObj_args)
-    PHP_FE(ms_newClassObj, ms_newClassObj_args)
-    PHP_FE(ms_newGridObj, ms_newGridObj_args)
-    PHP_FE(ms_getCwd, NULL)
-    PHP_FE(ms_getPid, NULL)
-    PHP_FE(ms_getScale, NULL)
-    PHP_FE(ms_tokenizeMap, NULL)
-    PHP_FE(ms_ioInstallStdoutToBuffer, NULL)
-    PHP_FE(ms_ioInstallStdinFromBuffer, NULL)
-    PHP_FE(ms_ioGetStdoutBufferString, NULL)
-    PHP_FE(ms_ioResetHandlers, NULL)
-    PHP_FE(ms_ioStripStdoutBufferContentType, NULL)
-    PHP_FE(ms_ioGetStdoutBufferBytes, NULL)
-    {NULL, NULL, NULL}
+zend_function_entry mapscript_functions[] = {
+  PHP_FE(ms_GetVersion, NULL)
+  PHP_FE(ms_GetVersionInt,  NULL)
+  PHP_FE(ms_newLineObj, NULL)
+  PHP_FE(ms_newRectObj, NULL)
+  PHP_FE(ms_newShapeObj, ms_newShapeObj_args)
+  PHP_FE(ms_shapeObjFromWkt, ms_shapeObjFromWkt_args)
+  PHP_FE(ms_GetErrorObj, NULL)
+  PHP_FE(ms_ResetErrorList, NULL)
+  PHP_FE(ms_newOWSRequestObj, NULL)
+  PHP_FE(ms_newShapeFileObj, ms_newShapeFileObj_args)
+  PHP_FE(ms_newMapObj, ms_newMapObj_args)
+  PHP_FE(ms_newMapObjFromString, ms_newMapObjFromString_args)
+  PHP_FE(ms_newLayerObj, ms_newLayerObj_args)
+  PHP_FE(ms_newPointObj, NULL)
+  PHP_FE(ms_newProjectionObj, ms_newProjectionObj_args)
+  PHP_FE(ms_newStyleObj, ms_newStyleObj_args)
+  PHP_FE(ms_newSymbolObj, ms_newSymbolObj_args)
+  PHP_FE(ms_newClassObj, ms_newClassObj_args)
+  PHP_FE(ms_newGridObj, ms_newGridObj_args)
+  PHP_FE(ms_getCwd, NULL)
+  PHP_FE(ms_getPid, NULL)
+  PHP_FE(ms_getScale, NULL)
+  PHP_FE(ms_tokenizeMap, NULL)
+  PHP_FE(ms_ioInstallStdoutToBuffer, NULL)
+  PHP_FE(ms_ioInstallStdinFromBuffer, NULL)
+  PHP_FE(ms_ioGetStdoutBufferString, NULL)
+  PHP_FE(ms_ioResetHandlers, NULL)
+  PHP_FE(ms_ioStripStdoutBufferContentType, NULL)
+  PHP_FE(ms_ioStripStdoutBufferContentHeaders, NULL)
+  PHP_FE(ms_ioGetStdoutBufferBytes, NULL) {
+    NULL, NULL, NULL
+  }
 };
 
 zend_module_entry mapscript_module_entry = {
-    STANDARD_MODULE_HEADER,
-    "MapScript", 
-    mapscript_functions,
-    /* MINIT()/MSHUTDOWN() are called once only when PHP starts up and 
-     * shutdowns.  They're really called only once and *not* when a new Apache
-     * child process is created.
-     */
-    PHP_MINIT(mapscript),
-    PHP_MSHUTDOWN(mapscript),
-    /* RINIT()/RSHUTDOWN() are called once per request 
-     * We shouldn't really be using them since they are run on every request
-     * and can hit performance.
-     */
-    NULL /* PHP_RINIT(mapscript)     */,
-    NULL /* PHP_RSHUTDOWN(mapscript) */,
-    PHP_MINFO(mapscript),
-    MAPSCRIPT_VERSION,          /* extension version number (string) */
-    STANDARD_MODULE_PROPERTIES 
+  STANDARD_MODULE_HEADER,
+  "MapScript",
+  mapscript_functions,
+  /* MINIT()/MSHUTDOWN() are called once only when PHP starts up and
+   * shutdowns.  They're really called only once and *not* when a new Apache
+   * child process is created.
+   */
+  PHP_MINIT(mapscript),
+  PHP_MSHUTDOWN(mapscript),
+  /* RINIT()/RSHUTDOWN() are called once per request
+   * We shouldn't really be using them since they are run on every request
+   * and can hit performance.
+   */
+  NULL /* PHP_RINIT(mapscript)     */,
+  NULL /* PHP_RSHUTDOWN(mapscript) */,
+  PHP_MINFO(mapscript),
+  MAPSCRIPT_VERSION,          /* extension version number (string) */
+  STANDARD_MODULE_PROPERTIES
 };
 
 #if COMPILE_DL
@@ -968,292 +949,377 @@ PHP_MINFO_FUNCTION(mapscript)
 
 PHP_MINIT_FUNCTION(mapscript)
 {
-    int const_flag = CONST_CS|CONST_PERSISTENT;
-
-    /* Init MapServer resources */
-    if (msSetup() != MS_SUCCESS)
-    {
-        mapscript_report_php_error(E_ERROR, "msSetup(): MapScript initialization failed." TSRMLS_CC);
-        return FAILURE;
-    }
-
-    memcpy(&mapscript_std_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
-    mapscript_std_object_handlers.clone_obj = NULL;
-
-    /* If you have defined globals, uncomment this line
-    ZEND_INIT_MODULE_GLOBALS(mapscript, phpms_init_globals, NULL);
-    */
-
-    /* If you have INI entries, uncomment this line
-    REGISTER_INI_ENTRIES();
-    */
-
-    /* boolean constants*/
-    REGISTER_LONG_CONSTANT("MS_TRUE",       MS_TRUE,        const_flag);
-    REGISTER_LONG_CONSTANT("MS_FALSE",      MS_FALSE,       const_flag);
-    REGISTER_LONG_CONSTANT("MS_ON",         MS_ON,          const_flag);
-    REGISTER_LONG_CONSTANT("MS_OFF",        MS_OFF,         const_flag);
-    REGISTER_LONG_CONSTANT("MS_YES",        MS_YES,         const_flag);
-    REGISTER_LONG_CONSTANT("MS_NO",         MS_NO,          const_flag);
-
-    /* map units constants*/
-    REGISTER_LONG_CONSTANT("MS_INCHES",     MS_INCHES,      const_flag);
-    REGISTER_LONG_CONSTANT("MS_FEET",       MS_FEET,        const_flag);
-    REGISTER_LONG_CONSTANT("MS_MILES",      MS_MILES,       const_flag);
-    REGISTER_LONG_CONSTANT("MS_METERS",     MS_METERS,      const_flag);
-    REGISTER_LONG_CONSTANT("MS_NAUTICALMILES",MS_NAUTICALMILES,const_flag);
-    REGISTER_LONG_CONSTANT("MS_KILOMETERS", MS_KILOMETERS,  const_flag);
-    REGISTER_LONG_CONSTANT("MS_DD",         MS_DD,          const_flag);
-    REGISTER_LONG_CONSTANT("MS_PIXELS",     MS_PIXELS,      const_flag);
-
-    /* layer type constants*/
-    REGISTER_LONG_CONSTANT("MS_LAYER_POINT",MS_LAYER_POINT, const_flag);
-    REGISTER_LONG_CONSTANT("MS_LAYER_LINE", MS_LAYER_LINE,  const_flag);
-    REGISTER_LONG_CONSTANT("MS_LAYER_POLYGON",MS_LAYER_POLYGON, const_flag);
-    REGISTER_LONG_CONSTANT("MS_LAYER_RASTER",MS_LAYER_RASTER, const_flag);
-    REGISTER_LONG_CONSTANT("MS_LAYER_ANNOTATION",MS_LAYER_ANNOTATION,const_flag);
-    REGISTER_LONG_CONSTANT("MS_LAYER_QUERY",MS_LAYER_QUERY, const_flag);
-    REGISTER_LONG_CONSTANT("MS_LAYER_CIRCLE",MS_LAYER_CIRCLE, const_flag);
-    REGISTER_LONG_CONSTANT("MS_LAYER_TILEINDEX",MS_LAYER_TILEINDEX, const_flag);    REGISTER_LONG_CONSTANT("MS_LAYER_CHART",MS_LAYER_CHART, const_flag);
-
-
-    /* layer status constants (see also MS_ON, MS_OFF) */
-    REGISTER_LONG_CONSTANT("MS_DEFAULT",    MS_DEFAULT,     const_flag);
-    REGISTER_LONG_CONSTANT("MS_EMBED",      MS_EMBED,       const_flag);
-    REGISTER_LONG_CONSTANT("MS_DELETE",     MS_DELETE,       const_flag);
-
-    //For layer transparency, allows alpha transparent pixmaps to be used
-    // with RGB map images
-    //#define MS_GD_ALPHA 1000
-    REGISTER_LONG_CONSTANT("MS_GD_ALPHA",     MS_GD_ALPHA,       const_flag);
-
-    /* font type constants*/
-    REGISTER_LONG_CONSTANT("MS_TRUETYPE",   MS_TRUETYPE,    const_flag);
-    REGISTER_LONG_CONSTANT("MS_BITMAP",     MS_BITMAP,      const_flag);
-
-    /* bitmap font style constants */
-    REGISTER_LONG_CONSTANT("MS_TINY",       MS_TINY,        const_flag);
-    REGISTER_LONG_CONSTANT("MS_SMALL",      MS_SMALL,       const_flag);
-    REGISTER_LONG_CONSTANT("MS_MEDIUM",     MS_MEDIUM,      const_flag);
-    REGISTER_LONG_CONSTANT("MS_LARGE",      MS_LARGE,       const_flag);
-    REGISTER_LONG_CONSTANT("MS_GIANT",      MS_GIANT,       const_flag);
-
-    /* label position constants*/
-    REGISTER_LONG_CONSTANT("MS_UL",         MS_UL,          const_flag);
-    REGISTER_LONG_CONSTANT("MS_LR",         MS_LR,          const_flag);
-    REGISTER_LONG_CONSTANT("MS_UR",         MS_UR,          const_flag);
-    REGISTER_LONG_CONSTANT("MS_LL",         MS_LL,          const_flag);
-    REGISTER_LONG_CONSTANT("MS_CR",         MS_CR,          const_flag);
-    REGISTER_LONG_CONSTANT("MS_CL",         MS_CL,          const_flag);
-    REGISTER_LONG_CONSTANT("MS_UC",         MS_UC,          const_flag);
-    REGISTER_LONG_CONSTANT("MS_LC",         MS_LC,          const_flag);
-    REGISTER_LONG_CONSTANT("MS_CC",         MS_CC,          const_flag);
-    REGISTER_LONG_CONSTANT("MS_AUTO",       MS_AUTO,        const_flag);
-    REGISTER_LONG_CONSTANT("MS_XY",         MS_XY,          const_flag);
-    REGISTER_LONG_CONSTANT("MS_FOLLOW",     MS_FOLLOW,      const_flag);
-    REGISTER_LONG_CONSTANT("MS_AUTO2",      MS_AUTO2,       const_flag);
-    REGISTER_LONG_CONSTANT("MS_NONE",       MS_NONE,        const_flag);
-
-    /* alignment constants*/
-    REGISTER_LONG_CONSTANT("MS_ALIGN_LEFT",  MS_ALIGN_LEFT,  const_flag);
-    REGISTER_LONG_CONSTANT("MS_ALIGN_CENTER",MS_ALIGN_CENTER,const_flag);
-    REGISTER_LONG_CONSTANT("MS_ALIGN_RIGHT", MS_ALIGN_RIGHT, const_flag);
-
-    /* shape type constants*/
-    REGISTER_LONG_CONSTANT("MS_SHAPE_POINT",MS_SHAPE_POINT, const_flag);
-    REGISTER_LONG_CONSTANT("MS_SHAPE_LINE",  MS_SHAPE_LINE, const_flag);
-    REGISTER_LONG_CONSTANT("MS_SHAPE_POLYGON",MS_SHAPE_POLYGON, const_flag);
-    REGISTER_LONG_CONSTANT("MS_SHAPE_NULL", MS_SHAPE_NULL,  const_flag);
-
-    /* shapefile type constants*/
-    /* Old names ... */
-    REGISTER_LONG_CONSTANT("MS_SHP_POINT",  SHP_POINT,      const_flag);
-    REGISTER_LONG_CONSTANT("MS_SHP_ARC",    SHP_ARC,        const_flag);
-    REGISTER_LONG_CONSTANT("MS_SHP_POLYGON",SHP_POLYGON,    const_flag);
-    REGISTER_LONG_CONSTANT("MS_SHP_MULTIPOINT",SHP_MULTIPOINT, const_flag);
-    REGISTER_LONG_CONSTANT("MS_SHP_POINTM",  SHP_POINTM,      const_flag);
-    REGISTER_LONG_CONSTANT("MS_SHP_ARCM",    SHP_ARCM,        const_flag);
-    REGISTER_LONG_CONSTANT("MS_SHP_POLYGONM",SHP_POLYGONM,    const_flag);
-    REGISTER_LONG_CONSTANT("MS_SHP_MULTIPOINTM",SHP_MULTIPOINTM, const_flag);
-    /* new names??? */
-    REGISTER_LONG_CONSTANT("SHP_POINT",     SHP_POINT,      const_flag);
-    REGISTER_LONG_CONSTANT("SHP_ARC",       SHP_ARC,        const_flag);
-    REGISTER_LONG_CONSTANT("SHP_POLYGON",   SHP_POLYGON,    const_flag);
-    REGISTER_LONG_CONSTANT("SHP_MULTIPOINT",SHP_MULTIPOINT, const_flag);
-    REGISTER_LONG_CONSTANT("SHP_POINTM",     SHP_POINTM,      const_flag);
-    REGISTER_LONG_CONSTANT("SHP_ARCM",       SHP_ARCM,        const_flag);
-    REGISTER_LONG_CONSTANT("SHP_POLYGONM",   SHP_POLYGONM,    const_flag);
-    REGISTER_LONG_CONSTANT("SHP_MULTIPOINTM",SHP_MULTIPOINTM, const_flag);
-
-    /* query/join type constants*/
-    REGISTER_LONG_CONSTANT("MS_SINGLE",     MS_SINGLE,      const_flag);
-    REGISTER_LONG_CONSTANT("MS_MULTIPLE",   MS_MULTIPLE,    const_flag);
-
-    /* connection type constants*/
-    REGISTER_LONG_CONSTANT("MS_INLINE",     MS_INLINE,      const_flag);
-    REGISTER_LONG_CONSTANT("MS_SHAPEFILE",  MS_SHAPEFILE,   const_flag);
-    REGISTER_LONG_CONSTANT("MS_TILED_SHAPEFILE",MS_TILED_SHAPEFILE,const_flag);
-    REGISTER_LONG_CONSTANT("MS_SDE",        MS_SDE,         const_flag);
-    REGISTER_LONG_CONSTANT("MS_OGR",        MS_OGR,         const_flag);
-    REGISTER_LONG_CONSTANT("MS_POSTGIS",    MS_POSTGIS,     const_flag);
-    REGISTER_LONG_CONSTANT("MS_WMS",        MS_WMS,         const_flag);
-    REGISTER_LONG_CONSTANT("MS_ORACLESPATIAL", MS_ORACLESPATIAL,const_flag);
-    REGISTER_LONG_CONSTANT("MS_WFS",        MS_WFS,         const_flag);
-    REGISTER_LONG_CONSTANT("MS_GRATICULE",  MS_GRATICULE,   const_flag);
-    REGISTER_LONG_CONSTANT("MS_RASTER",     MS_RASTER,      const_flag);
-    REGISTER_LONG_CONSTANT("MS_PLUGIN",     MS_PLUGIN,      const_flag);
-    REGISTER_LONG_CONSTANT("MS_UNION",      MS_UNION,      const_flag);
- 
-    /* output image type constants*/
-    /*
-    REGISTER_LONG_CONSTANT("MS_GIF",        MS_GIF,         const_flag);
-    REGISTER_LONG_CONSTANT("MS_PNG",        MS_PNG,         const_flag);
-    REGISTER_LONG_CONSTANT("MS_JPEG",       MS_JPEG,        const_flag);
-    REGISTER_LONG_CONSTANT("MS_WBMP",       MS_WBMP,        const_flag);
-    REGISTER_LONG_CONSTANT("MS_SWF",        MS_SWF,        const_flag);
-    */
-
-    /* querymap style constants */
-    REGISTER_LONG_CONSTANT("MS_NORMAL",     MS_NORMAL,      const_flag);
-    REGISTER_LONG_CONSTANT("MS_HILITE",     MS_HILITE,      const_flag);
-    REGISTER_LONG_CONSTANT("MS_SELECTED",   MS_SELECTED,    const_flag);
-
-    /* return value constants */
-    REGISTER_LONG_CONSTANT("MS_SUCCESS",    MS_SUCCESS,     const_flag);
-    REGISTER_LONG_CONSTANT("MS_FAILURE",    MS_FAILURE,     const_flag);
-    REGISTER_LONG_CONSTANT("MS_DONE",       MS_DONE,        const_flag);
-   
-    /* error code constants */
-    REGISTER_LONG_CONSTANT("MS_NOERR",      MS_NOERR,       const_flag);
-    REGISTER_LONG_CONSTANT("MS_IOERR",      MS_IOERR,       const_flag);
-    REGISTER_LONG_CONSTANT("MS_MEMERR",     MS_MEMERR,      const_flag);
-    REGISTER_LONG_CONSTANT("MS_TYPEERR",    MS_TYPEERR,     const_flag);
-    REGISTER_LONG_CONSTANT("MS_SYMERR",     MS_SYMERR,      const_flag);
-    REGISTER_LONG_CONSTANT("MS_REGEXERR",   MS_REGEXERR,    const_flag);
-    REGISTER_LONG_CONSTANT("MS_TTFERR",     MS_TTFERR,      const_flag);
-    REGISTER_LONG_CONSTANT("MS_DBFERR",     MS_DBFERR,      const_flag);
-    REGISTER_LONG_CONSTANT("MS_GDERR",      MS_GDERR,       const_flag);
-    REGISTER_LONG_CONSTANT("MS_IDENTERR",   MS_IDENTERR,    const_flag);
-    REGISTER_LONG_CONSTANT("MS_EOFERR",     MS_EOFERR,      const_flag);
-    REGISTER_LONG_CONSTANT("MS_PROJERR",    MS_PROJERR,     const_flag);
-    REGISTER_LONG_CONSTANT("MS_MISCERR",    MS_MISCERR,     const_flag);
-    REGISTER_LONG_CONSTANT("MS_CGIERR",     MS_CGIERR,      const_flag);
-    REGISTER_LONG_CONSTANT("MS_WEBERR",     MS_WEBERR,      const_flag);
-    REGISTER_LONG_CONSTANT("MS_IMGERR",     MS_IMGERR,      const_flag);
-    REGISTER_LONG_CONSTANT("MS_HASHERR",    MS_HASHERR,     const_flag);
-    REGISTER_LONG_CONSTANT("MS_JOINERR",    MS_JOINERR,     const_flag);
-    REGISTER_LONG_CONSTANT("MS_NOTFOUND",   MS_NOTFOUND,    const_flag);
-    REGISTER_LONG_CONSTANT("MS_SHPERR",     MS_SHPERR,      const_flag);
-    REGISTER_LONG_CONSTANT("MS_PARSEERR",   MS_PARSEERR,    const_flag);
-    REGISTER_LONG_CONSTANT("MS_SDEERR",     MS_SDEERR,      const_flag);
-    REGISTER_LONG_CONSTANT("MS_OGRERR",     MS_OGRERR,      const_flag);
-    REGISTER_LONG_CONSTANT("MS_QUERYERR",   MS_QUERYERR,    const_flag);
-    REGISTER_LONG_CONSTANT("MS_WMSERR",     MS_WMSERR,      const_flag);
-    REGISTER_LONG_CONSTANT("MS_WMSCONNERR", MS_WMSCONNERR,  const_flag);
-    REGISTER_LONG_CONSTANT("MS_ORACLESPATIALERR", MS_ORACLESPATIALERR, const_flag);
-    REGISTER_LONG_CONSTANT("MS_WFSERR",     MS_WFSERR,      const_flag);
-    REGISTER_LONG_CONSTANT("MS_WFSCONNERR", MS_WFSCONNERR,  const_flag);
-    REGISTER_LONG_CONSTANT("MS_MAPCONTEXTERR", MS_MAPCONTEXTERR, const_flag);
-    REGISTER_LONG_CONSTANT("MS_HTTPERR",    MS_HTTPERR,     const_flag);
-    REGISTER_LONG_CONSTANT("MS_WCSERR",    MS_WCSERR,     const_flag);
- 
-    /*symbol types */
-    REGISTER_LONG_CONSTANT("MS_SYMBOL_SIMPLE", MS_SYMBOL_SIMPLE, const_flag);
-    REGISTER_LONG_CONSTANT("MS_SYMBOL_VECTOR", MS_SYMBOL_VECTOR, const_flag);
-    REGISTER_LONG_CONSTANT("MS_SYMBOL_ELLIPSE", MS_SYMBOL_ELLIPSE, const_flag);
-    REGISTER_LONG_CONSTANT("MS_SYMBOL_PIXMAP", MS_SYMBOL_PIXMAP, const_flag);
-    REGISTER_LONG_CONSTANT("MS_SYMBOL_TRUETYPE", MS_SYMBOL_TRUETYPE, const_flag);
-    /* MS_IMAGEMODE types for use with outputFormatObj */
-    REGISTER_LONG_CONSTANT("MS_IMAGEMODE_PC256", MS_IMAGEMODE_PC256, const_flag);
-    REGISTER_LONG_CONSTANT("MS_IMAGEMODE_RGB",  MS_IMAGEMODE_RGB, const_flag);
-    REGISTER_LONG_CONSTANT("MS_IMAGEMODE_RGBA", MS_IMAGEMODE_RGBA, const_flag);
-    REGISTER_LONG_CONSTANT("MS_IMAGEMODE_INT16", MS_IMAGEMODE_INT16, const_flag);
-    REGISTER_LONG_CONSTANT("MS_IMAGEMODE_FLOAT32", MS_IMAGEMODE_FLOAT32, const_flag);
-    REGISTER_LONG_CONSTANT("MS_IMAGEMODE_BYTE", MS_IMAGEMODE_BYTE, const_flag);
-    REGISTER_LONG_CONSTANT("MS_IMAGEMODE_FEATURE", MS_IMAGEMODE_FEATURE, const_flag);
-    REGISTER_LONG_CONSTANT("MS_IMAGEMODE_NULL", MS_IMAGEMODE_NULL, const_flag);
-
-    /*binding types*/
-    REGISTER_LONG_CONSTANT("MS_STYLE_BINDING_SIZE",  MS_STYLE_BINDING_SIZE, const_flag);
-    REGISTER_LONG_CONSTANT("MS_STYLE_BINDING_WIDTH",  MS_STYLE_BINDING_WIDTH, const_flag);
-    REGISTER_LONG_CONSTANT("MS_STYLE_BINDING_ANGLE", MS_STYLE_BINDING_ANGLE, const_flag);
-    REGISTER_LONG_CONSTANT("MS_STYLE_BINDING_COLOR", MS_STYLE_BINDING_COLOR, const_flag);
-    REGISTER_LONG_CONSTANT("MS_STYLE_BINDING_OUTLINECOLOR", MS_STYLE_BINDING_OUTLINECOLOR, const_flag);
-    REGISTER_LONG_CONSTANT("MS_STYLE_BINDING_SYMBOL", MS_STYLE_BINDING_SYMBOL, const_flag);
-    REGISTER_LONG_CONSTANT("MS_STYLE_BINDING_OUTLINEWIDTH", MS_STYLE_BINDING_OUTLINEWIDTH, const_flag);
-    REGISTER_LONG_CONSTANT("MS_STYLE_BINDING_OPACITY", MS_STYLE_BINDING_OPACITY, const_flag);
-      
-    REGISTER_LONG_CONSTANT("MS_LABEL_BINDING_SIZE",  MS_LABEL_BINDING_SIZE, const_flag);
-    REGISTER_LONG_CONSTANT("MS_LABEL_BINDING_ANGLE", MS_LABEL_BINDING_ANGLE, const_flag);
-    REGISTER_LONG_CONSTANT("MS_LABEL_BINDING_COLOR", MS_LABEL_BINDING_COLOR, const_flag);
-    REGISTER_LONG_CONSTANT("MS_LABEL_BINDING_OUTLINECOLOR", MS_LABEL_BINDING_OUTLINECOLOR, const_flag);
-    REGISTER_LONG_CONSTANT("MS_LABEL_BINDING_FONT",  MS_LABEL_BINDING_FONT, const_flag);
-    REGISTER_LONG_CONSTANT("MS_LABEL_BINDING_PRIORITY", MS_LABEL_BINDING_PRIORITY, const_flag);
-    REGISTER_LONG_CONSTANT("MS_LABEL_BINDING_POSITION", MS_LABEL_BINDING_POSITION, const_flag);
-    REGISTER_LONG_CONSTANT("MS_LABEL_BINDING_SHADOWSIZEX", MS_LABEL_BINDING_SHADOWSIZEX, const_flag);
-    REGISTER_LONG_CONSTANT("MS_LABEL_BINDING_SHADOWSIZEY", MS_LABEL_BINDING_SHADOWSIZEY, const_flag);
-
-    /* MS_CAPS_JOINS_AND_CORNERS */
-    REGISTER_LONG_CONSTANT("MS_CJC_NONE", MS_CJC_NONE, const_flag);
-    REGISTER_LONG_CONSTANT("MS_CJC_BEVEL", MS_CJC_BEVEL, const_flag);
-    REGISTER_LONG_CONSTANT("MS_CJC_BUTT", MS_CJC_BUTT, const_flag); 
-    REGISTER_LONG_CONSTANT("MS_CJC_MITER", MS_CJC_MITER, const_flag); 
-    REGISTER_LONG_CONSTANT("MS_CJC_ROUND", MS_CJC_ROUND, const_flag); 
-    REGISTER_LONG_CONSTANT("MS_CJC_SQUARE", MS_CJC_SQUARE, const_flag); 
-    REGISTER_LONG_CONSTANT("MS_CJC_TRIANGLE", MS_CJC_TRIANGLE, const_flag); 
-
-    /*cgi request types*/
-    REGISTER_LONG_CONSTANT("MS_GET_REQUEST", MS_GET_REQUEST, const_flag);
-    REGISTER_LONG_CONSTANT("MS_POST_REQUEST", MS_POST_REQUEST, const_flag);
-           
-    
-    PHP_MINIT(mapscript_error)(INIT_FUNC_ARGS_PASSTHRU);
-    PHP_MINIT(color)(INIT_FUNC_ARGS_PASSTHRU);
-    PHP_MINIT(rect)(INIT_FUNC_ARGS_PASSTHRU);
-    PHP_MINIT(hashtable)(INIT_FUNC_ARGS_PASSTHRU);
-    PHP_MINIT(label)(INIT_FUNC_ARGS_PASSTHRU);
-    PHP_MINIT(style)(INIT_FUNC_ARGS_PASSTHRU);
-    PHP_MINIT(symbol)(INIT_FUNC_ARGS_PASSTHRU);
-    PHP_MINIT(image)(INIT_FUNC_ARGS_PASSTHRU);
-    PHP_MINIT(web)(INIT_FUNC_ARGS_PASSTHRU);
-    PHP_MINIT(legend)(INIT_FUNC_ARGS_PASSTHRU);
-    PHP_MINIT(outputformat)(INIT_FUNC_ARGS_PASSTHRU);
-    PHP_MINIT(querymap)(INIT_FUNC_ARGS_PASSTHRU);
-    PHP_MINIT(grid)(INIT_FUNC_ARGS_PASSTHRU);
-    PHP_MINIT(error)(INIT_FUNC_ARGS_PASSTHRU);
-    PHP_MINIT(referencemap)(INIT_FUNC_ARGS_PASSTHRU);
-    PHP_MINIT(class)(INIT_FUNC_ARGS_PASSTHRU);
-    PHP_MINIT(projection)(INIT_FUNC_ARGS_PASSTHRU);
-    PHP_MINIT(labelcachemember)(INIT_FUNC_ARGS_PASSTHRU);
-    PHP_MINIT(labelcache)(INIT_FUNC_ARGS_PASSTHRU);
-    PHP_MINIT(result)(INIT_FUNC_ARGS_PASSTHRU);
-    PHP_MINIT(scalebar)(INIT_FUNC_ARGS_PASSTHRU);
-    PHP_MINIT(owsrequest)(INIT_FUNC_ARGS_PASSTHRU);
-    PHP_MINIT(point)(INIT_FUNC_ARGS_PASSTHRU);
-    PHP_MINIT(line)(INIT_FUNC_ARGS_PASSTHRU);
-    PHP_MINIT(shape)(INIT_FUNC_ARGS_PASSTHRU);
-    PHP_MINIT(shapefile)(INIT_FUNC_ARGS_PASSTHRU);
-    PHP_MINIT(cluster)(INIT_FUNC_ARGS_PASSTHRU);
-    PHP_MINIT(layer)(INIT_FUNC_ARGS_PASSTHRU);
-    PHP_MINIT(map)(INIT_FUNC_ARGS_PASSTHRU);
-
-    return SUCCESS;
+  int const_flag = CONST_CS|CONST_PERSISTENT;
+
+  /* Init MapServer resources */
+  if (msSetup() != MS_SUCCESS) {
+    mapscript_report_php_error(E_ERROR, "msSetup(): MapScript initialization failed." TSRMLS_CC);
+    return FAILURE;
+  }
+
+  memcpy(&mapscript_std_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
+  mapscript_std_object_handlers.clone_obj = NULL;
+
+  /* If you have defined globals, uncomment this line
+  ZEND_INIT_MODULE_GLOBALS(mapscript, phpms_init_globals, NULL);
+  */
+
+  /* If you have INI entries, uncomment this line
+  REGISTER_INI_ENTRIES();
+  */
+
+  /* boolean constants*/
+  REGISTER_LONG_CONSTANT("MS_TRUE",       MS_TRUE,        const_flag);
+  REGISTER_LONG_CONSTANT("MS_FALSE",      MS_FALSE,       const_flag);
+  REGISTER_LONG_CONSTANT("MS_ON",         MS_ON,          const_flag);
+  REGISTER_LONG_CONSTANT("MS_OFF",        MS_OFF,         const_flag);
+  REGISTER_LONG_CONSTANT("MS_YES",        MS_YES,         const_flag);
+  REGISTER_LONG_CONSTANT("MS_NO",         MS_NO,          const_flag);
+
+  /* map units constants*/
+  REGISTER_LONG_CONSTANT("MS_INCHES",     MS_INCHES,      const_flag);
+  REGISTER_LONG_CONSTANT("MS_FEET",       MS_FEET,        const_flag);
+  REGISTER_LONG_CONSTANT("MS_MILES",      MS_MILES,       const_flag);
+  REGISTER_LONG_CONSTANT("MS_METERS",     MS_METERS,      const_flag);
+  REGISTER_LONG_CONSTANT("MS_NAUTICALMILES",MS_NAUTICALMILES,const_flag);
+  REGISTER_LONG_CONSTANT("MS_KILOMETERS", MS_KILOMETERS,  const_flag);
+  REGISTER_LONG_CONSTANT("MS_DD",         MS_DD,          const_flag);
+  REGISTER_LONG_CONSTANT("MS_PIXELS",     MS_PIXELS,      const_flag);
+
+  /* layer type constants*/
+  REGISTER_LONG_CONSTANT("MS_LAYER_POINT",MS_LAYER_POINT, const_flag);
+  REGISTER_LONG_CONSTANT("MS_LAYER_LINE", MS_LAYER_LINE,  const_flag);
+  REGISTER_LONG_CONSTANT("MS_LAYER_POLYGON",MS_LAYER_POLYGON, const_flag);
+  REGISTER_LONG_CONSTANT("MS_LAYER_RASTER",MS_LAYER_RASTER, const_flag);
+  REGISTER_LONG_CONSTANT("MS_LAYER_ANNOTATION",MS_LAYER_ANNOTATION,const_flag);
+  REGISTER_LONG_CONSTANT("MS_LAYER_QUERY",MS_LAYER_QUERY, const_flag);
+  REGISTER_LONG_CONSTANT("MS_LAYER_CIRCLE",MS_LAYER_CIRCLE, const_flag);
+  REGISTER_LONG_CONSTANT("MS_LAYER_TILEINDEX",MS_LAYER_TILEINDEX, const_flag);
+  REGISTER_LONG_CONSTANT("MS_LAYER_CHART",MS_LAYER_CHART, const_flag);
+
+
+  /* layer status constants (see also MS_ON, MS_OFF) */
+  REGISTER_LONG_CONSTANT("MS_DEFAULT",    MS_DEFAULT,     const_flag);
+  REGISTER_LONG_CONSTANT("MS_EMBED",      MS_EMBED,       const_flag);
+  REGISTER_LONG_CONSTANT("MS_DELETE",     MS_DELETE,       const_flag);
+
+  //For layer transparency, allows alpha transparent pixmaps to be used
+  // with RGB map images
+  //#define MS_GD_ALPHA 1000
+  REGISTER_LONG_CONSTANT("MS_GD_ALPHA",     MS_GD_ALPHA,       const_flag);
+
+  /* font type constants*/
+  REGISTER_LONG_CONSTANT("MS_TRUETYPE",   MS_TRUETYPE,    const_flag);
+  REGISTER_LONG_CONSTANT("MS_BITMAP",     MS_BITMAP,      const_flag);
+
+  /* bitmap font style constants */
+  REGISTER_LONG_CONSTANT("MS_TINY",       MS_TINY,        const_flag);
+  REGISTER_LONG_CONSTANT("MS_SMALL",      MS_SMALL,       const_flag);
+  REGISTER_LONG_CONSTANT("MS_MEDIUM",     MS_MEDIUM,      const_flag);
+  REGISTER_LONG_CONSTANT("MS_LARGE",      MS_LARGE,       const_flag);
+  REGISTER_LONG_CONSTANT("MS_GIANT",      MS_GIANT,       const_flag);
+
+  /* label position constants*/
+  REGISTER_LONG_CONSTANT("MS_UL",         MS_UL,          const_flag);
+  REGISTER_LONG_CONSTANT("MS_LR",         MS_LR,          const_flag);
+  REGISTER_LONG_CONSTANT("MS_UR",         MS_UR,          const_flag);
+  REGISTER_LONG_CONSTANT("MS_LL",         MS_LL,          const_flag);
+  REGISTER_LONG_CONSTANT("MS_CR",         MS_CR,          const_flag);
+  REGISTER_LONG_CONSTANT("MS_CL",         MS_CL,          const_flag);
+  REGISTER_LONG_CONSTANT("MS_UC",         MS_UC,          const_flag);
+  REGISTER_LONG_CONSTANT("MS_LC",         MS_LC,          const_flag);
+  REGISTER_LONG_CONSTANT("MS_CC",         MS_CC,          const_flag);
+  REGISTER_LONG_CONSTANT("MS_AUTO",       MS_AUTO,        const_flag);
+  REGISTER_LONG_CONSTANT("MS_XY",         MS_XY,          const_flag);
+  REGISTER_LONG_CONSTANT("MS_FOLLOW",     MS_FOLLOW,      const_flag);
+  REGISTER_LONG_CONSTANT("MS_AUTO2",      MS_AUTO2,       const_flag);
+  REGISTER_LONG_CONSTANT("MS_NONE",       MS_NONE,        const_flag);
+
+  /* alignment constants*/
+  REGISTER_LONG_CONSTANT("MS_ALIGN_LEFT",  MS_ALIGN_LEFT,  const_flag);
+  REGISTER_LONG_CONSTANT("MS_ALIGN_CENTER",MS_ALIGN_CENTER,const_flag);
+  REGISTER_LONG_CONSTANT("MS_ALIGN_RIGHT", MS_ALIGN_RIGHT, const_flag);
+
+  /* shape type constants*/
+  REGISTER_LONG_CONSTANT("MS_SHAPE_POINT",MS_SHAPE_POINT, const_flag);
+  REGISTER_LONG_CONSTANT("MS_SHAPE_LINE",  MS_SHAPE_LINE, const_flag);
+  REGISTER_LONG_CONSTANT("MS_SHAPE_POLYGON",MS_SHAPE_POLYGON, const_flag);
+  REGISTER_LONG_CONSTANT("MS_SHAPE_NULL", MS_SHAPE_NULL,  const_flag);
+
+  /* shapefile type constants*/
+  /* Old names ... */
+  REGISTER_LONG_CONSTANT("MS_SHP_POINT",  SHP_POINT,      const_flag);
+  REGISTER_LONG_CONSTANT("MS_SHP_ARC",    SHP_ARC,        const_flag);
+  REGISTER_LONG_CONSTANT("MS_SHP_POLYGON",SHP_POLYGON,    const_flag);
+  REGISTER_LONG_CONSTANT("MS_SHP_MULTIPOINT",SHP_MULTIPOINT, const_flag);
+  REGISTER_LONG_CONSTANT("MS_SHP_POINTM",  SHP_POINTM,      const_flag);
+  REGISTER_LONG_CONSTANT("MS_SHP_ARCM",    SHP_ARCM,        const_flag);
+  REGISTER_LONG_CONSTANT("MS_SHP_POLYGONM",SHP_POLYGONM,    const_flag);
+  REGISTER_LONG_CONSTANT("MS_SHP_MULTIPOINTM",SHP_MULTIPOINTM, const_flag);
+  /* new names??? */
+  REGISTER_LONG_CONSTANT("SHP_POINT",     SHP_POINT,      const_flag);
+  REGISTER_LONG_CONSTANT("SHP_ARC",       SHP_ARC,        const_flag);
+  REGISTER_LONG_CONSTANT("SHP_POLYGON",   SHP_POLYGON,    const_flag);
+  REGISTER_LONG_CONSTANT("SHP_MULTIPOINT",SHP_MULTIPOINT, const_flag);
+  REGISTER_LONG_CONSTANT("SHP_POINTM",     SHP_POINTM,      const_flag);
+  REGISTER_LONG_CONSTANT("SHP_ARCM",       SHP_ARCM,        const_flag);
+  REGISTER_LONG_CONSTANT("SHP_POLYGONM",   SHP_POLYGONM,    const_flag);
+  REGISTER_LONG_CONSTANT("SHP_MULTIPOINTM",SHP_MULTIPOINTM, const_flag);
+
+  /* query/join type constants*/
+  REGISTER_LONG_CONSTANT("MS_SINGLE",     MS_SINGLE,      const_flag);
+  REGISTER_LONG_CONSTANT("MS_MULTIPLE",   MS_MULTIPLE,    const_flag);
+
+  /* connection type constants*/
+  REGISTER_LONG_CONSTANT("MS_INLINE",     MS_INLINE,      const_flag);
+  REGISTER_LONG_CONSTANT("MS_SHAPEFILE",  MS_SHAPEFILE,   const_flag);
+  REGISTER_LONG_CONSTANT("MS_TILED_SHAPEFILE",MS_TILED_SHAPEFILE,const_flag);
+  REGISTER_LONG_CONSTANT("MS_SDE",        MS_SDE,         const_flag);
+  REGISTER_LONG_CONSTANT("MS_OGR",        MS_OGR,         const_flag);
+  REGISTER_LONG_CONSTANT("MS_POSTGIS",    MS_POSTGIS,     const_flag);
+  REGISTER_LONG_CONSTANT("MS_WMS",        MS_WMS,         const_flag);
+  REGISTER_LONG_CONSTANT("MS_ORACLESPATIAL", MS_ORACLESPATIAL,const_flag);
+  REGISTER_LONG_CONSTANT("MS_WFS",        MS_WFS,         const_flag);
+  REGISTER_LONG_CONSTANT("MS_GRATICULE",  MS_GRATICULE,   const_flag);
+  REGISTER_LONG_CONSTANT("MS_RASTER",     MS_RASTER,      const_flag);
+  REGISTER_LONG_CONSTANT("MS_PLUGIN",     MS_PLUGIN,      const_flag);
+  REGISTER_LONG_CONSTANT("MS_UNION",      MS_UNION,      const_flag);
+  REGISTER_LONG_CONSTANT("MS_UVRASTER",   MS_UVRASTER, const_flag);
+
+  /* output image type constants*/
+  /*
+  REGISTER_LONG_CONSTANT("MS_GIF",        MS_GIF,         const_flag);
+  REGISTER_LONG_CONSTANT("MS_PNG",        MS_PNG,         const_flag);
+  REGISTER_LONG_CONSTANT("MS_JPEG",       MS_JPEG,        const_flag);
+  REGISTER_LONG_CONSTANT("MS_WBMP",       MS_WBMP,        const_flag);
+  REGISTER_LONG_CONSTANT("MS_SWF",        MS_SWF,        const_flag);
+  */
+
+  /* querymap style constants */
+  REGISTER_LONG_CONSTANT("MS_NORMAL",     MS_NORMAL,      const_flag);
+  REGISTER_LONG_CONSTANT("MS_HILITE",     MS_HILITE,      const_flag);
+  REGISTER_LONG_CONSTANT("MS_SELECTED",   MS_SELECTED,    const_flag);
+
+  /* return value constants */
+  REGISTER_LONG_CONSTANT("MS_SUCCESS",    MS_SUCCESS,     const_flag);
+  REGISTER_LONG_CONSTANT("MS_FAILURE",    MS_FAILURE,     const_flag);
+  REGISTER_LONG_CONSTANT("MS_DONE",       MS_DONE,        const_flag);
+
+  /* error code constants */
+  REGISTER_LONG_CONSTANT("MS_NOERR",      MS_NOERR,       const_flag);
+  REGISTER_LONG_CONSTANT("MS_IOERR",      MS_IOERR,       const_flag);
+  REGISTER_LONG_CONSTANT("MS_MEMERR",     MS_MEMERR,      const_flag);
+  REGISTER_LONG_CONSTANT("MS_TYPEERR",    MS_TYPEERR,     const_flag);
+  REGISTER_LONG_CONSTANT("MS_SYMERR",     MS_SYMERR,      const_flag);
+  REGISTER_LONG_CONSTANT("MS_REGEXERR",   MS_REGEXERR,    const_flag);
+  REGISTER_LONG_CONSTANT("MS_TTFERR",     MS_TTFERR,      const_flag);
+  REGISTER_LONG_CONSTANT("MS_DBFERR",     MS_DBFERR,      const_flag);
+  REGISTER_LONG_CONSTANT("MS_GDERR",      MS_GDERR,       const_flag);
+  REGISTER_LONG_CONSTANT("MS_IDENTERR",   MS_IDENTERR,    const_flag);
+  REGISTER_LONG_CONSTANT("MS_EOFERR",     MS_EOFERR,      const_flag);
+  REGISTER_LONG_CONSTANT("MS_PROJERR",    MS_PROJERR,     const_flag);
+  REGISTER_LONG_CONSTANT("MS_MISCERR",    MS_MISCERR,     const_flag);
+  REGISTER_LONG_CONSTANT("MS_CGIERR",     MS_CGIERR,      const_flag);
+  REGISTER_LONG_CONSTANT("MS_WEBERR",     MS_WEBERR,      const_flag);
+  REGISTER_LONG_CONSTANT("MS_IMGERR",     MS_IMGERR,      const_flag);
+  REGISTER_LONG_CONSTANT("MS_HASHERR",    MS_HASHERR,     const_flag);
+  REGISTER_LONG_CONSTANT("MS_JOINERR",    MS_JOINERR,     const_flag);
+  REGISTER_LONG_CONSTANT("MS_NOTFOUND",   MS_NOTFOUND,    const_flag);
+  REGISTER_LONG_CONSTANT("MS_SHPERR",     MS_SHPERR,      const_flag);
+  REGISTER_LONG_CONSTANT("MS_PARSEERR",   MS_PARSEERR,    const_flag);
+  REGISTER_LONG_CONSTANT("MS_SDEERR",     MS_SDEERR,      const_flag);
+  REGISTER_LONG_CONSTANT("MS_OGRERR",     MS_OGRERR,      const_flag);
+  REGISTER_LONG_CONSTANT("MS_QUERYERR",   MS_QUERYERR,    const_flag);
+  REGISTER_LONG_CONSTANT("MS_WMSERR",     MS_WMSERR,      const_flag);
+  REGISTER_LONG_CONSTANT("MS_WMSCONNERR", MS_WMSCONNERR,  const_flag);
+  REGISTER_LONG_CONSTANT("MS_ORACLESPATIALERR", MS_ORACLESPATIALERR, const_flag);
+  REGISTER_LONG_CONSTANT("MS_WFSERR",     MS_WFSERR,      const_flag);
+  REGISTER_LONG_CONSTANT("MS_WFSCONNERR", MS_WFSCONNERR,  const_flag);
+  REGISTER_LONG_CONSTANT("MS_MAPCONTEXTERR", MS_MAPCONTEXTERR, const_flag);
+  REGISTER_LONG_CONSTANT("MS_HTTPERR",    MS_HTTPERR,     const_flag);
+  REGISTER_LONG_CONSTANT("MS_WCSERR",    MS_WCSERR,     const_flag);
+
+  /*symbol types */
+  REGISTER_LONG_CONSTANT("MS_SYMBOL_SIMPLE", MS_SYMBOL_SIMPLE, const_flag);
+  REGISTER_LONG_CONSTANT("MS_SYMBOL_VECTOR", MS_SYMBOL_VECTOR, const_flag);
+  REGISTER_LONG_CONSTANT("MS_SYMBOL_ELLIPSE", MS_SYMBOL_ELLIPSE, const_flag);
+  REGISTER_LONG_CONSTANT("MS_SYMBOL_PIXMAP", MS_SYMBOL_PIXMAP, const_flag);
+  REGISTER_LONG_CONSTANT("MS_SYMBOL_TRUETYPE", MS_SYMBOL_TRUETYPE, const_flag);
+  /* MS_IMAGEMODE types for use with outputFormatObj */
+  REGISTER_LONG_CONSTANT("MS_IMAGEMODE_PC256", MS_IMAGEMODE_PC256, const_flag);
+  REGISTER_LONG_CONSTANT("MS_IMAGEMODE_RGB",  MS_IMAGEMODE_RGB, const_flag);
+  REGISTER_LONG_CONSTANT("MS_IMAGEMODE_RGBA", MS_IMAGEMODE_RGBA, const_flag);
+  REGISTER_LONG_CONSTANT("MS_IMAGEMODE_INT16", MS_IMAGEMODE_INT16, const_flag);
+  REGISTER_LONG_CONSTANT("MS_IMAGEMODE_FLOAT32", MS_IMAGEMODE_FLOAT32, const_flag);
+  REGISTER_LONG_CONSTANT("MS_IMAGEMODE_BYTE", MS_IMAGEMODE_BYTE, const_flag);
+  REGISTER_LONG_CONSTANT("MS_IMAGEMODE_FEATURE", MS_IMAGEMODE_FEATURE, const_flag);
+  REGISTER_LONG_CONSTANT("MS_IMAGEMODE_NULL", MS_IMAGEMODE_NULL, const_flag);
+
+  /*binding types*/
+  REGISTER_LONG_CONSTANT("MS_STYLE_BINDING_SIZE",  MS_STYLE_BINDING_SIZE, const_flag);
+  REGISTER_LONG_CONSTANT("MS_STYLE_BINDING_WIDTH",  MS_STYLE_BINDING_WIDTH, const_flag);
+  REGISTER_LONG_CONSTANT("MS_STYLE_BINDING_ANGLE", MS_STYLE_BINDING_ANGLE, const_flag);
+  REGISTER_LONG_CONSTANT("MS_STYLE_BINDING_COLOR", MS_STYLE_BINDING_COLOR, const_flag);
+  REGISTER_LONG_CONSTANT("MS_STYLE_BINDING_OUTLINECOLOR", MS_STYLE_BINDING_OUTLINECOLOR, const_flag);
+  REGISTER_LONG_CONSTANT("MS_STYLE_BINDING_SYMBOL", MS_STYLE_BINDING_SYMBOL, const_flag);
+  REGISTER_LONG_CONSTANT("MS_STYLE_BINDING_OUTLINEWIDTH", MS_STYLE_BINDING_OUTLINEWIDTH, const_flag);
+  REGISTER_LONG_CONSTANT("MS_STYLE_BINDING_OPACITY", MS_STYLE_BINDING_OPACITY, const_flag);
+  REGISTER_LONG_CONSTANT("MS_STYLE_BINDING_OFFSET_X", MS_STYLE_BINDING_OFFSET_X, const_flag);
+  REGISTER_LONG_CONSTANT("MS_STYLE_BINDING_OFFSET_Y", MS_STYLE_BINDING_OFFSET_Y, const_flag);
+  REGISTER_LONG_CONSTANT("MS_STYLE_BINDING_POLAROFFSET_PIXEL", MS_STYLE_BINDING_POLAROFFSET_PIXEL, const_flag);
+  REGISTER_LONG_CONSTANT("MS_STYLE_BINDING_POLAROFFSET_ANGLE", MS_STYLE_BINDING_POLAROFFSET_ANGLE, const_flag);
+
+  REGISTER_LONG_CONSTANT("MS_LABEL_BINDING_SIZE",  MS_LABEL_BINDING_SIZE, const_flag);
+  REGISTER_LONG_CONSTANT("MS_LABEL_BINDING_ANGLE", MS_LABEL_BINDING_ANGLE, const_flag);
+  REGISTER_LONG_CONSTANT("MS_LABEL_BINDING_COLOR", MS_LABEL_BINDING_COLOR, const_flag);
+  REGISTER_LONG_CONSTANT("MS_LABEL_BINDING_OUTLINECOLOR", MS_LABEL_BINDING_OUTLINECOLOR, const_flag);
+  REGISTER_LONG_CONSTANT("MS_LABEL_BINDING_FONT",  MS_LABEL_BINDING_FONT, const_flag);
+  REGISTER_LONG_CONSTANT("MS_LABEL_BINDING_PRIORITY", MS_LABEL_BINDING_PRIORITY, const_flag);
+  REGISTER_LONG_CONSTANT("MS_LABEL_BINDING_POSITION", MS_LABEL_BINDING_POSITION, const_flag);
+  REGISTER_LONG_CONSTANT("MS_LABEL_BINDING_SHADOWSIZEX", MS_LABEL_BINDING_SHADOWSIZEX, const_flag);
+  REGISTER_LONG_CONSTANT("MS_LABEL_BINDING_SHADOWSIZEY", MS_LABEL_BINDING_SHADOWSIZEY, const_flag);
+
+  /* MS_CAPS_JOINS_AND_CORNERS */
+  REGISTER_LONG_CONSTANT("MS_CJC_NONE", MS_CJC_NONE, const_flag);
+  REGISTER_LONG_CONSTANT("MS_CJC_BEVEL", MS_CJC_BEVEL, const_flag);
+  REGISTER_LONG_CONSTANT("MS_CJC_BUTT", MS_CJC_BUTT, const_flag);
+  REGISTER_LONG_CONSTANT("MS_CJC_MITER", MS_CJC_MITER, const_flag);
+  REGISTER_LONG_CONSTANT("MS_CJC_ROUND", MS_CJC_ROUND, const_flag);
+  REGISTER_LONG_CONSTANT("MS_CJC_SQUARE", MS_CJC_SQUARE, const_flag);
+  REGISTER_LONG_CONSTANT("MS_CJC_TRIANGLE", MS_CJC_TRIANGLE, const_flag);
+
+  /*cgi request types*/
+  REGISTER_LONG_CONSTANT("MS_GET_REQUEST", MS_GET_REQUEST, const_flag);
+  REGISTER_LONG_CONSTANT("MS_POST_REQUEST", MS_POST_REQUEST, const_flag);
+
+  REGISTER_LONG_CONSTANT("MS_DB_CSV", MS_DB_CSV, const_flag);
+  REGISTER_LONG_CONSTANT("MS_DB_MYSQL", MS_DB_MYSQL, const_flag);
+  REGISTER_LONG_CONSTANT("MS_DB_ORACLE", MS_DB_ORACLE, const_flag);
+  REGISTER_LONG_CONSTANT("MS_DB_POSTGRES", MS_DB_POSTGRES, const_flag);
+  REGISTER_LONG_CONSTANT("MS_DB_XBASE", MS_DB_XBASE, const_flag);
+  REGISTER_LONG_CONSTANT("MS_DEBUGLEVEL_DEBUG", MS_DEBUGLEVEL_DEBUG, const_flag);
+  REGISTER_LONG_CONSTANT("MS_DEBUGLEVEL_ERRORSONLY", MS_DEBUGLEVEL_ERRORSONLY, const_flag);
+  REGISTER_LONG_CONSTANT("MS_DEBUGLEVEL_TUNING", MS_DEBUGLEVEL_TUNING, const_flag);
+  REGISTER_LONG_CONSTANT("MS_DEBUGLEVEL_V", MS_DEBUGLEVEL_V, const_flag);
+  REGISTER_LONG_CONSTANT("MS_DEBUGLEVEL_VV", MS_DEBUGLEVEL_VV, const_flag);
+  REGISTER_LONG_CONSTANT("MS_DEBUGLEVEL_VVV", MS_DEBUGLEVEL_VVV, const_flag);
+  REGISTER_LONG_CONSTANT("MS_DEFAULT_CGI_PARAMS", MS_DEFAULT_CGI_PARAMS, const_flag);
+  REGISTER_LONG_CONSTANT("MS_DEFAULT_LABEL_PRIORITY", MS_DEFAULT_LABEL_PRIORITY, const_flag);
+  REGISTER_LONG_CONSTANT("MS_ERROR_LANGUAGE", MS_ERROR_LANGUAGE, const_flag);
+  REGISTER_LONG_CONSTANT("MS_FILE_MAP", MS_FILE_MAP, const_flag);
+  REGISTER_LONG_CONSTANT("MS_FILE_SYMBOL", MS_FILE_SYMBOL, const_flag);
+  REGISTER_LONG_CONSTANT("MS_GEOS_BEYOND", MS_GEOS_BEYOND, const_flag);
+  REGISTER_LONG_CONSTANT("MS_GEOS_CONTAINS", MS_GEOS_CONTAINS, const_flag);
+  REGISTER_LONG_CONSTANT("MS_GEOS_CROSSES", MS_GEOS_CROSSES, const_flag);
+  REGISTER_LONG_CONSTANT("MS_GEOS_DISJOINT", MS_GEOS_DISJOINT, const_flag);
+  REGISTER_LONG_CONSTANT("MS_GEOS_DWITHIN", MS_GEOS_DWITHIN, const_flag);
+  REGISTER_LONG_CONSTANT("MS_GEOS_EQUALS", MS_GEOS_EQUALS, const_flag);
+  REGISTER_LONG_CONSTANT("MS_GEOS_INTERSECTS", MS_GEOS_INTERSECTS, const_flag);
+  REGISTER_LONG_CONSTANT("MS_GEOS_OVERLAPS", MS_GEOS_OVERLAPS, const_flag);
+  REGISTER_LONG_CONSTANT("MS_GEOS_TOUCHES", MS_GEOS_TOUCHES, const_flag);
+  REGISTER_LONG_CONSTANT("MS_GEOS_WITHIN", MS_GEOS_WITHIN, const_flag);
+  REGISTER_LONG_CONSTANT("MS_JOIN_ONE_TO_MANY", MS_JOIN_ONE_TO_MANY, const_flag);
+  REGISTER_LONG_CONSTANT("MS_JOIN_ONE_TO_ONE", MS_JOIN_ONE_TO_ONE, const_flag);
+  REGISTER_LONG_CONSTANT("MS_MAXPATTERNLENGTH", MS_MAXPATTERNLENGTH, const_flag);
+  REGISTER_LONG_CONSTANT("MS_MAXVECTORPOINTS", MS_MAXVECTORPOINTS, const_flag);
+  REGISTER_LONG_CONSTANT("MS_MAX_LABEL_FONTS", MS_MAX_LABEL_FONTS, const_flag);
+  REGISTER_LONG_CONSTANT("MS_MAX_LABEL_PRIORITY", MS_MAX_LABEL_PRIORITY, const_flag);
+  REGISTER_LONG_CONSTANT("MS_MYSQL", MS_MYSQL, const_flag);
+  REGISTER_LONG_CONSTANT("MS_NOOVERRIDE", MS_NOOVERRIDE, const_flag);
+  REGISTER_LONG_CONSTANT("MS_NULLPARENTERR", MS_NULLPARENTERR, const_flag);
+  REGISTER_LONG_CONSTANT("MS_NUMERRORCODES", MS_NUMERRORCODES, const_flag);
+  REGISTER_LONG_CONSTANT("MS_PARSE_TYPE_BOOLEAN", MS_PARSE_TYPE_BOOLEAN, const_flag);
+  REGISTER_LONG_CONSTANT("MS_PARSE_TYPE_SHAPE", MS_PARSE_TYPE_SHAPE, const_flag);
+  REGISTER_LONG_CONSTANT("MS_PARSE_TYPE_STRING", MS_PARSE_TYPE_STRING, const_flag);
+  REGISTER_LONG_CONSTANT("MS_PERCENTAGES", MS_PERCENTAGES, const_flag);
+  REGISTER_LONG_CONSTANT("MS_QUERY_BY_ATTRIBUTE", MS_QUERY_BY_ATTRIBUTE, const_flag);
+  REGISTER_LONG_CONSTANT("MS_QUERY_BY_FILTER", MS_QUERY_BY_FILTER, const_flag);
+  REGISTER_LONG_CONSTANT("MS_QUERY_BY_INDEX", MS_QUERY_BY_INDEX, const_flag);
+  REGISTER_LONG_CONSTANT("MS_QUERY_BY_POINT", MS_QUERY_BY_POINT, const_flag);
+  REGISTER_LONG_CONSTANT("MS_QUERY_BY_RECT", MS_QUERY_BY_RECT, const_flag);
+  REGISTER_LONG_CONSTANT("MS_QUERY_BY_SHAPE", MS_QUERY_BY_SHAPE, const_flag);
+  REGISTER_LONG_CONSTANT("MS_QUERY_IS_NULL", MS_QUERY_IS_NULL, const_flag);
+  REGISTER_LONG_CONSTANT("MS_QUERY_MULTIPLE", MS_QUERY_MULTIPLE, const_flag);
+  REGISTER_LONG_CONSTANT("MS_QUERY_SINGLE", MS_QUERY_SINGLE, const_flag);
+  REGISTER_LONG_CONSTANT("MS_RENDERERERR", MS_RENDERERERR, const_flag);
+  REGISTER_LONG_CONSTANT("MS_RENDER_WITH_AGG", MS_RENDER_WITH_AGG, const_flag);
+  REGISTER_LONG_CONSTANT("MS_RENDER_WITH_CAIRO_PDF", MS_RENDER_WITH_CAIRO_PDF, const_flag);
+  REGISTER_LONG_CONSTANT("MS_RENDER_WITH_CAIRO_RASTER", MS_RENDER_WITH_CAIRO_RASTER, const_flag);
+  REGISTER_LONG_CONSTANT("MS_RENDER_WITH_CAIRO_SVG", MS_RENDER_WITH_CAIRO_SVG, const_flag);
+  REGISTER_LONG_CONSTANT("MS_RENDER_WITH_GD", MS_RENDER_WITH_GD, const_flag);
+  REGISTER_LONG_CONSTANT("MS_RENDER_WITH_IMAGEMAP", MS_RENDER_WITH_IMAGEMAP, const_flag);
+  REGISTER_LONG_CONSTANT("MS_RENDER_WITH_KML", MS_RENDER_WITH_KML, const_flag);
+  REGISTER_LONG_CONSTANT("MS_RENDER_WITH_OGL", MS_RENDER_WITH_OGL, const_flag);
+  REGISTER_LONG_CONSTANT("MS_RENDER_WITH_OGR", MS_RENDER_WITH_OGR, const_flag);
+  REGISTER_LONG_CONSTANT("MS_RENDER_WITH_PLUGIN", MS_RENDER_WITH_PLUGIN, const_flag);
+  REGISTER_LONG_CONSTANT("MS_RENDER_WITH_RAWDATA", MS_RENDER_WITH_RAWDATA, const_flag);
+  REGISTER_LONG_CONSTANT("MS_RENDER_WITH_SWF", MS_RENDER_WITH_SWF, const_flag);
+  REGISTER_LONG_CONSTANT("MS_RENDER_WITH_TEMPLATE", MS_RENDER_WITH_TEMPLATE, const_flag);
+  REGISTER_LONG_CONSTANT("MS_SHAPEFILE_ARC", MS_SHAPEFILE_ARC, const_flag);
+  REGISTER_LONG_CONSTANT("MS_SHAPEFILE_MULTIPOINT", MS_SHAPEFILE_MULTIPOINT, const_flag);
+  REGISTER_LONG_CONSTANT("MS_SHAPEFILE_POINT", MS_SHAPEFILE_POINT, const_flag);
+  REGISTER_LONG_CONSTANT("MS_SHAPEFILE_POLYGON", MS_SHAPEFILE_POLYGON, const_flag);
+  REGISTER_LONG_CONSTANT("MS_SHP_ARCZ", MS_SHP_ARCZ, const_flag);
+  REGISTER_LONG_CONSTANT("MS_SHP_MULTIPOINTZ", MS_SHP_MULTIPOINTZ, const_flag);
+  REGISTER_LONG_CONSTANT("MS_SHP_POINTZ", MS_SHP_POINTZ, const_flag);
+  REGISTER_LONG_CONSTANT("MS_SHP_POLYGONZ", MS_SHP_POLYGONZ, const_flag);
+  REGISTER_LONG_CONSTANT("MS_SOSERR", MS_SOSERR, const_flag);
+  REGISTER_LONG_CONSTANT("MS_SYMBOL_HATCH", MS_SYMBOL_HATCH, const_flag);
+  REGISTER_LONG_CONSTANT("MS_SYMBOL_SVG", MS_SYMBOL_SVG, const_flag);
+  REGISTER_LONG_CONSTANT("MS_TRANSFORM_FULLRESOLUTION", MS_TRANSFORM_FULLRESOLUTION, const_flag);
+  REGISTER_LONG_CONSTANT("MS_TRANSFORM_NONE", MS_TRANSFORM_NONE, const_flag);
+  REGISTER_LONG_CONSTANT("MS_TRANSFORM_ROUND", MS_TRANSFORM_ROUND, const_flag);
+  REGISTER_LONG_CONSTANT("MS_TRANSFORM_SIMPLIFY", MS_TRANSFORM_SIMPLIFY, const_flag);
+  REGISTER_LONG_CONSTANT("MS_TRANSFORM_SNAPTOGRID", MS_TRANSFORM_SNAPTOGRID, const_flag);
+
+  PHP_MINIT(mapscript_error)(INIT_FUNC_ARGS_PASSTHRU);
+  PHP_MINIT(color)(INIT_FUNC_ARGS_PASSTHRU);
+  PHP_MINIT(rect)(INIT_FUNC_ARGS_PASSTHRU);
+  PHP_MINIT(hashtable)(INIT_FUNC_ARGS_PASSTHRU);
+  PHP_MINIT(label)(INIT_FUNC_ARGS_PASSTHRU);
+  PHP_MINIT(style)(INIT_FUNC_ARGS_PASSTHRU);
+  PHP_MINIT(symbol)(INIT_FUNC_ARGS_PASSTHRU);
+  PHP_MINIT(image)(INIT_FUNC_ARGS_PASSTHRU);
+  PHP_MINIT(web)(INIT_FUNC_ARGS_PASSTHRU);
+  PHP_MINIT(legend)(INIT_FUNC_ARGS_PASSTHRU);
+  PHP_MINIT(outputformat)(INIT_FUNC_ARGS_PASSTHRU);
+  PHP_MINIT(querymap)(INIT_FUNC_ARGS_PASSTHRU);
+  PHP_MINIT(grid)(INIT_FUNC_ARGS_PASSTHRU);
+  PHP_MINIT(error)(INIT_FUNC_ARGS_PASSTHRU);
+  PHP_MINIT(referencemap)(INIT_FUNC_ARGS_PASSTHRU);
+  PHP_MINIT(class)(INIT_FUNC_ARGS_PASSTHRU);
+  PHP_MINIT(projection)(INIT_FUNC_ARGS_PASSTHRU);
+  PHP_MINIT(labelcachemember)(INIT_FUNC_ARGS_PASSTHRU);
+  PHP_MINIT(labelcache)(INIT_FUNC_ARGS_PASSTHRU);
+  PHP_MINIT(labelleader)(INIT_FUNC_ARGS_PASSTHRU);
+  PHP_MINIT(result)(INIT_FUNC_ARGS_PASSTHRU);
+  PHP_MINIT(scalebar)(INIT_FUNC_ARGS_PASSTHRU);
+  PHP_MINIT(owsrequest)(INIT_FUNC_ARGS_PASSTHRU);
+  PHP_MINIT(point)(INIT_FUNC_ARGS_PASSTHRU);
+  PHP_MINIT(line)(INIT_FUNC_ARGS_PASSTHRU);
+  PHP_MINIT(shape)(INIT_FUNC_ARGS_PASSTHRU);
+  PHP_MINIT(shapefile)(INIT_FUNC_ARGS_PASSTHRU);
+  PHP_MINIT(cluster)(INIT_FUNC_ARGS_PASSTHRU);
+  PHP_MINIT(layer)(INIT_FUNC_ARGS_PASSTHRU);
+  PHP_MINIT(map)(INIT_FUNC_ARGS_PASSTHRU);
+
+  return SUCCESS;
 }
 
 PHP_MSHUTDOWN_FUNCTION(mapscript)
 {
-    /* Cleanup MapServer resources */
-    msCleanup();    
-    
-    return SUCCESS;
+  /* Cleanup MapServer resources */
+  msCleanup(0);
+
+  return SUCCESS;
 }
 
 PHP_RINIT_FUNCTION(mapscript)
 {
-    return SUCCESS;
+  return SUCCESS;
 }
 
 PHP_RSHUTDOWN_FUNCTION(mapscript)
 {
-    return SUCCESS;
+  return SUCCESS;
 }
diff --git a/mapscript/php/php_mapscript.h b/mapscript/php/php_mapscript.h
index 065c6dd..9491333 100644
--- a/mapscript/php/php_mapscript.h
+++ b/mapscript/php/php_mapscript.h
@@ -2,7 +2,7 @@
  * $Id$
  *
  * Project:  MapServer
- * Purpose:  PHP/MapScript extension for MapServer. Header file 
+ * Purpose:  PHP/MapScript extension for MapServer. Header file
  *           - prototypes / module definitions
  * Author:   Daniel Morissette, DM Solutions Group (dmorissette at dmsolutions.ca)
  *
@@ -15,16 +15,16 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
+ *
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  * DEALINGS IN THE SOFTWARE.
  **********************************************************************/
 
@@ -50,13 +50,13 @@
 #include <unistd.h>
 #endif
 
-#include "mapserver.h"
-#include "mapregex.h"
+#include "../../mapserver.h"
+#include "../../mapregex.h"
 #endif /* USE_PHP_REGEX */
 
 
-#include "maptemplate.h"
-#include "mapogcsld.h"
+#include "../../maptemplate.h"
+#include "../../mapogcsld.h"
 
 #define MAPSCRIPT_VERSION "($Revision$ $Date$)"
 
@@ -64,8 +64,8 @@ extern zend_module_entry mapscript_module_entry;
 #define phpext_mapscript_ptr &mapscript_module_entry
 
 #ifndef zend_parse_parameters_none
-#define zend_parse_parameters_none()			  \
-	zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "")
+#define zend_parse_parameters_none()        \
+  zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "")
 #endif
 
 /* it looks like that macro is not always defined: ticket #3926 */
@@ -78,255 +78,267 @@ extern zend_module_entry mapscript_module_entry;
 #if defined(PHP_VERSION_ID) && PHP_VERSION_ID >= 50300
 /* 5.3 version of the macros */
 #define PHP_MAPSCRIPT_ERROR_HANDLING(force_exceptions) \
-	zend_error_handling error_handling; \
-	if(force_exceptions || getThis()) { \
-		zend_replace_error_handling(EH_THROW, mapscript_ce_mapscriptexception, &error_handling TSRMLS_CC); \
-	}
+  zend_error_handling error_handling; \
+  if(force_exceptions || getThis()) { \
+    zend_replace_error_handling(EH_THROW, mapscript_ce_mapscriptexception, &error_handling TSRMLS_CC); \
+  }
 
 #define PHP_MAPSCRIPT_RESTORE_ERRORS(force_exceptions) \
-	if(force_exceptions || getThis()) { \
-		zend_restore_error_handling(&error_handling TSRMLS_CC); \
-	}
+  if(force_exceptions || getThis()) { \
+    zend_restore_error_handling(&error_handling TSRMLS_CC); \
+  }
 
 #else
 /* 5.2 versions of the macros */
 #define PHP_MAPSCRIPT_ERROR_HANDLING(force_exceptions) \
-	if(force_exceptions || getThis()) { \
-		php_set_error_handling(EH_THROW, mapscript_ce_mapscriptexception TSRMLS_CC); \
-	}
+  if(force_exceptions || getThis()) { \
+    php_set_error_handling(EH_THROW, mapscript_ce_mapscriptexception TSRMLS_CC); \
+  }
 
 #define PHP_MAPSCRIPT_RESTORE_ERRORS(force_exceptions) \
-	if(force_exceptions || getThis()) { \
-		php_std_error_handling(); \
-	}
+  if(force_exceptions || getThis()) { \
+    php_std_error_handling(); \
+  }
 
 #endif
 
 /* MapScript objects */
 typedef struct _parent_object {
-    zval *val; // the zval of the parent
-    zval **child_ptr; // a ptr to a parent property, which point to the child object.
-                           // should be set to NULL when the child is destroyed
+  zval *val; // the zval of the parent
+  zval **child_ptr; // a ptr to a parent property, which point to the child object.
+  // should be set to NULL when the child is destroyed
 } parent_object;
 
 typedef struct _php_color_object {
-    zend_object std;
-    parent_object parent;
-    colorObj *color;
+  zend_object std;
+  parent_object parent;
+  colorObj *color;
 } php_color_object;
 
 typedef struct _php_rect_object {
-    zend_object std;
-    parent_object parent;
-    int is_ref;
-    rectObj *rect;
+  zend_object std;
+  parent_object parent;
+  int is_ref;
+  rectObj *rect;
 } php_rect_object;
 
 typedef struct _php_hashtable_object {
-    zend_object std;
-    parent_object parent;
-    hashTableObj *hashtable;
+  zend_object std;
+  parent_object parent;
+  hashTableObj *hashtable;
 } php_hashtable_object;
 
 typedef struct _php_symbol_object {
-    zend_object std;
-    parent_object parent;
-    symbolObj *symbol;
+  zend_object std;
+  parent_object parent;
+  symbolObj *symbol;
 } php_symbol_object;
 
 typedef struct _php_class_object {
-    zend_object std;
-    parent_object parent; //old layer
-    zval *metadata;
-    zval *label;
-    classObj *class;
+  zend_object std;
+  parent_object parent; //old layer
+  zval *metadata;
+  zval *leader;
+  classObj *class;
 } php_class_object;
 
 typedef struct _php_image_object {
-    zend_object std;
-    imageObj *image;
+  zend_object std;
+  imageObj *image;
 } php_image_object;
 
 typedef struct _php_web_object {
-    zend_object std;
-    parent_object parent;
-    zval *extent;
-    zval *metadata;
-    webObj *web;
+  zend_object std;
+  parent_object parent;
+  zval *extent;
+  zval *metadata;
+  zval *validation;
+  webObj *web;
 } php_web_object;
 
 typedef struct _php_legend_object {
-    zend_object std;
-    parent_object parent;
-    zval *outlinecolor;
-    zval *label;
-    zval *imagecolor;
-    legendObj *legend;
+  zend_object std;
+  parent_object parent;
+  zval *outlinecolor;
+  zval *label;
+  zval *imagecolor;
+  legendObj *legend;
 } php_legend_object;
 
 typedef struct _php_outputformat_object {
-    zend_object std;
-    parent_object parent;
-    outputFormatObj *outputformat;
+  zend_object std;
+  parent_object parent;
+  int is_ref;
+  outputFormatObj *outputformat;
 } php_outputformat_object;
 
 typedef struct _php_querymap_object {
-    zend_object std;
-    parent_object parent;
-    zval *color;
-    queryMapObj *querymap;
+  zend_object std;
+  parent_object parent;
+  zval *color;
+  queryMapObj *querymap;
 } php_querymap_object;
 
 typedef struct _php_grid_object {
-    zend_object std;
-    parent_object parent;
-    graticuleObj *grid;
+  zend_object std;
+  parent_object parent;
+  graticuleObj *grid;
 } php_grid_object;
 
 typedef struct _php_error_object {
-    zend_object std;
-    errorObj *error;
+  zend_object std;
+  errorObj *error;
 } php_error_object;
 
 typedef struct _php_referencemap_object {
-    zend_object std;
-    parent_object parent;
-    zval *extent;
-    zval *color;
-    zval *outlinecolor;
-    referenceMapObj *referencemap;
+  zend_object std;
+  parent_object parent;
+  zval *extent;
+  zval *color;
+  zval *outlinecolor;
+  referenceMapObj *referencemap;
 } php_referencemap_object;
 
 typedef struct _php_label_object {
-    zend_object std;
-    parent_object parent;
-    zval *color;
-    zval *outlinecolor;
-    zval *shadowcolor;
-    zval *backgroundcolor;
-    zval *backgroundshadowcolor;
-    labelObj *label;
+  zend_object std;
+  parent_object parent;
+  int is_ref;
+  zval *color;
+  zval *outlinecolor;
+  zval *shadowcolor;
+  zval *backgroundcolor;
+  zval *backgroundshadowcolor;
+  zval *leader;
+  labelObj *label;
 } php_label_object;
 
 typedef struct _php_style_object {
-    zend_object std;
-    parent_object parent;
-    zval *color;
-    zval *outlinecolor;
-    zval *backgroundcolor;
-    zval *mincolor;
-    zval *maxcolor;
-    styleObj *style;
+  zend_object std;
+  parent_object parent;
+  zval *color;
+  zval *outlinecolor;
+  zval *backgroundcolor;
+  zval *mincolor;
+  zval *maxcolor;
+  styleObj *style;
 } php_style_object;
 
 typedef struct _php_projection_object {
-    zend_object std;
-    parent_object parent;
-    int is_ref;
-    projectionObj *projection;
+  zend_object std;
+  parent_object parent;
+  int is_ref;
+  projectionObj *projection;
 } php_projection_object;
 
 typedef struct _php_point_object {
-    zend_object std;
-    parent_object parent;
-    int is_ref;
-    pointObj *point;
+  zend_object std;
+  parent_object parent;
+  int is_ref;
+  pointObj *point;
 } php_point_object;
 
 typedef struct _php_line_object {
-    zend_object std;
-    parent_object parent;
-    int is_ref;
-    lineObj *line;
+  zend_object std;
+  parent_object parent;
+  int is_ref;
+  lineObj *line;
 } php_line_object;
 
 typedef struct _php_shape_object {
-    zend_object std;
-    parent_object parent;
-    zval *bounds;
-    zval *values;
-    int is_ref;
-    shapeObj *shape;
+  zend_object std;
+  parent_object parent;
+  zval *bounds;
+  zval *values;
+  int is_ref;
+  shapeObj *shape;
 } php_shape_object;
 
 typedef struct _php_shapefile_object {
-    zend_object std;
-    zval *bounds;
-    shapefileObj *shapefile;
+  zend_object std;
+  zval *bounds;
+  shapefileObj *shapefile;
 } php_shapefile_object;
 
 typedef struct _php_labelcache_object {
-    zend_object std;
-    parent_object parent;
-    labelCacheObj *labelcache;
+  zend_object std;
+  parent_object parent;
+  labelCacheObj *labelcache;
 } php_labelcache_object;
 
+typedef struct _php_labelleader_object {
+  zend_object std;
+  parent_object parent;
+  labelLeaderObj *labelleader;
+} php_labelleader_object;
+
 typedef struct _php_labelcachemember_object {
-    zend_object std;
-    parent_object parent;
-    zval *label; /* should be immutable */
-    zval *point; /* should be immutable */
-    zval *styles; /* should be immutable */
-    zval *poly; /* should be immutable */
-    labelCacheMemberObj *labelcachemember;
+  zend_object std;
+  parent_object parent;
+  zval *labels; /* should be immutable */
+  zval *point; /* should be immutable */
+  zval *styles; /* should be immutable */
+  zval *poly; /* should be immutable */
+  labelCacheMemberObj *labelcachemember;
 } php_labelcachemember_object;
 
 typedef struct _php_result_object {
-    zend_object std;
-    parent_object parent;
-    resultObj *result;
+  zend_object std;
+  parent_object parent;
+  resultObj *result;
 } php_result_object;
 
 typedef struct _php_scalebar_object {
-    zend_object std;
-    parent_object parent;
-    zval *color;
-    zval *backgroundcolor;
-    zval *outlinecolor;
-    zval *label;
-    zval *imagecolor;
-    scalebarObj *scalebar;
+  zend_object std;
+  parent_object parent;
+  zval *color;
+  zval *backgroundcolor;
+  zval *outlinecolor;
+  zval *label;
+  zval *imagecolor;
+  scalebarObj *scalebar;
 } php_scalebar_object;
 
 typedef struct _php_owsrequest_object {
-    zend_object std;
-    cgiRequestObj *cgirequest;
+  zend_object std;
+  cgiRequestObj *cgirequest;
 } php_owsrequest_object;
 
 typedef struct _php_layer_object {
-    zend_object std;
-    parent_object parent; //old map
-    zval *offsite;
-    zval *grid;
-    zval *metadata;
-    zval *bindvals;
-    zval *projection;
-    zval *cluster;
-    int is_ref;
-    layerObj *layer;
+  zend_object std;
+  parent_object parent; //old map
+  zval *offsite;
+  zval *grid;
+  zval *metadata;
+  zval *bindvals;
+  zval *projection;
+  zval *cluster;
+  zval *extent;
+  int is_ref;
+  layerObj *layer;
 } php_layer_object;
 
 typedef struct _php_map_object {
-    zend_object std;
-    zval *outputformat;
-    zval *extent;
-    zval *web;
-    zval *reference;
-    zval *imagecolor;
-    zval *scalebar;
-    zval *legend;
-    zval *querymap;
-    zval *labelcache;
-    zval *projection;
-    zval *metadata;
-    mapObj *map;
+  zend_object std;
+  zval *outputformat;
+  zval *extent;
+  zval *web;
+  zval *reference;
+  zval *imagecolor;
+  zval *scalebar;
+  zval *legend;
+  zval *querymap;
+  zval *labelcache;
+  zval *projection;
+  zval *metadata;
+  zval *configoptions;
+  mapObj *map;
 } php_map_object;
 
 typedef struct _php_cluster_object {
-    zend_object std;
-    parent_object parent;
-    int is_ref;
-    clusterObj *cluster;
+  zend_object std;
+  parent_object parent;
+  int is_ref;
+  clusterObj *cluster;
 } php_cluster_object;
 
 /* Lifecyle functions*/
@@ -353,6 +365,7 @@ PHP_MINIT_FUNCTION(class);
 PHP_MINIT_FUNCTION(projection);
 PHP_MINIT_FUNCTION(labelcachemember);
 PHP_MINIT_FUNCTION(labelcache);
+PHP_MINIT_FUNCTION(labelleader);
 PHP_MINIT_FUNCTION(result);
 PHP_MINIT_FUNCTION(scalebar);
 PHP_MINIT_FUNCTION(owsrequest);
@@ -380,6 +393,7 @@ PHP_FUNCTION(ms_ioInstallStdinFromBuffer);
 PHP_FUNCTION(ms_ioGetStdoutBufferString);
 PHP_FUNCTION(ms_ioResetHandlers);
 PHP_FUNCTION(ms_ioStripStdoutBufferContentType);
+PHP_FUNCTION(ms_ioStripStdoutBufferContentHeaders);
 PHP_FUNCTION(ms_ioGetStdoutBufferBytes);
 
 /* object constructors */
@@ -424,6 +438,7 @@ extern zend_class_entry *mapscript_ce_shape;
 extern zend_class_entry *mapscript_ce_shapefile;
 extern zend_class_entry *mapscript_ce_labelcachemember;
 extern zend_class_entry *mapscript_ce_labelcache;
+extern zend_class_entry *mapscript_ce_labelleader;
 extern zend_class_entry *mapscript_ce_result;
 extern zend_class_entry *mapscript_ce_scalebar;
 extern zend_class_entry *mapscript_ce_owsrequest;
@@ -433,11 +448,11 @@ extern zend_class_entry *mapscript_ce_cluster;
 
 /* PHP Object constructors */
 extern zend_object_value mapscript_object_new(zend_object *zobj, zend_class_entry *ce,
-                                              void (*zend_objects_free_object) TSRMLS_DC);
+    void (*zend_objects_free_object) TSRMLS_DC);
 extern zend_object_value mapscript_object_new_ex(zend_object *zobj, zend_class_entry *ce,
-                                                 void (*zend_objects_free_object),
-                                                 zend_object_handlers *object_handlers TSRMLS_DC);
-extern void mapscript_fetch_object(zend_class_entry *ce, zval* zval_parent, php_layer_object* layer, 
+    void (*zend_objects_free_object),
+    zend_object_handlers *object_handlers TSRMLS_DC);
+extern void mapscript_fetch_object(zend_class_entry *ce, zval* zval_parent, php_layer_object* layer,
                                    void *internal_object, zval **php_object_storage TSRMLS_DC);
 extern void mapscript_create_color(colorObj *color, parent_object parent, zval *return_value TSRMLS_DC);
 extern void mapscript_create_rect(rectObj *rect, parent_object php_parent, zval *return_value TSRMLS_DC);
@@ -446,11 +461,13 @@ extern void mapscript_create_label(labelObj *label, parent_object parent, zval *
 extern void mapscript_create_style(styleObj *style, parent_object parent, zval *return_value TSRMLS_DC);
 extern void mapscript_create_symbol(symbolObj *symbol, parent_object parent, zval *return_value TSRMLS_DC);
 extern void mapscript_create_class(classObj *class, parent_object parent, zval *return_value TSRMLS_DC);
-extern void mapscript_create_labelcachemember(labelCacheMemberObj *labelcachemember, 
-                                              parent_object parent, zval *return_value TSRMLS_DC);
-extern void mapscript_create_labelcache(labelCacheObj *labelcache, 
-                                              parent_object parent, zval *return_value TSRMLS_DC);
-extern void mapscript_create_result(resultObj *result, 
+extern void mapscript_create_labelcachemember(labelCacheMemberObj *labelcachemember,
+    parent_object parent, zval *return_value TSRMLS_DC);
+extern void mapscript_create_labelcache(labelCacheObj *labelcache,
+                                        parent_object parent, zval *return_value TSRMLS_DC);
+extern void mapscript_create_labelleader(labelLeaderObj *labelleader,
+    parent_object parent, zval *return_value TSRMLS_DC);
+extern void mapscript_create_result(resultObj *result,
                                     parent_object parent, zval *return_value TSRMLS_DC);
 extern void mapscript_create_scalebar(scalebarObj *scalebar, parent_object parent, zval *return_value TSRMLS_DC);
 extern void mapscript_create_owsrequest(cgiRequestObj *cgirequest, zval *return_value TSRMLS_DC);
@@ -463,7 +480,7 @@ extern void mapscript_create_grid(graticuleObj *grid, parent_object parent, zval
 extern void mapscript_create_error(errorObj *error, zval *return_value TSRMLS_DC);
 extern void mapscript_create_referencemap(referenceMapObj *referenceMap, parent_object parent, zval *return_value TSRMLS_DC);
 extern void mapscript_create_point(pointObj *point, parent_object parent, zval *return_value TSRMLS_DC);
-extern void mapscript_create_projection(projectionObj *projection, 
+extern void mapscript_create_projection(projectionObj *projection,
                                         parent_object parent, zval *return_value TSRMLS_DC);
 extern void mapscript_create_line(lineObj *line, parent_object parent, zval *return_value TSRMLS_DC);
 extern void mapscript_create_shape(shapeObj *shape, parent_object parent, php_layer_object *php_layer, zval *return_value TSRMLS_DC);
@@ -491,8 +508,8 @@ mapObj         *mapObj_clone(mapObj* self);
 int             mapObj_setRotation(mapObj* self, double rotation_angle );
 layerObj       *mapObj_getLayer(mapObj* self, int i);
 layerObj       *mapObj_getLayerByName(mapObj* self, char *name);
-int             *mapObj_getLayersIndexByGroup(mapObj* self, char *groupname, 
-                                             int *pnCount);
+int             *mapObj_getLayersIndexByGroup(mapObj* self, char *groupname,
+    int *pnCount);
 int             mapObj_getSymbolByName(mapObj* self, char *name);
 void            mapObj_prepareQuery(mapObj* self);
 imageObj        *mapObj_prepareImage(mapObj* self);
@@ -505,14 +522,15 @@ int             mapObj_embedScalebar(mapObj* self, imageObj *img);
 int             mapObj_embedLegend(mapObj* self, imageObj *img);
 int             mapObj_drawLabelCache(mapObj* self, imageObj *img);
 labelCacheMemberObj *mapObj_getLabel(mapObj* self, int i);
-int             mapObj_queryByPoint(mapObj* self, pointObj *point, 
+int             mapObj_queryByPoint(mapObj* self, pointObj *point,
                                     int mode, double buffer);
 int             mapObj_queryByRect(mapObj* self, rectObj rect);
 int             mapObj_queryByFeatures(mapObj* self, int slayer);
 int             mapObj_queryByShape(mapObj *self, shapeObj *shape);
-int              mapObj_queryByIndex(mapObj *self, int qlayer, 
+int              mapObj_queryByIndex(mapObj *self, int qlayer,
                                      int tileindex, int shapeindex,
                                      int bAddToQuery);
+int             mapObj_queryByFilter(mapObj* self, char *string);
 int             mapObj_saveQuery(mapObj *self, char *filename, int results);
 int             mapObj_loadQuery(mapObj *self, char *filename);
 
@@ -529,16 +547,16 @@ int             mapObj_moveLayerdown(mapObj *self, int layerindex);
 int             *mapObj_getLayersdrawingOrder(mapObj *self);
 int             mapObj_setLayersdrawingOrder(mapObj *self, int *panIndexes);
 
-char            *mapObj_processTemplate(mapObj *self, int bGenerateImages, 
-                                        char **names, char **values, 
+char            *mapObj_processTemplate(mapObj *self, int bGenerateImages,
+                                        char **names, char **values,
                                         int numentries);
 char            *mapObj_processLegendTemplate(mapObj *self,
-                                              char **names, char **values, 
-                                              int numentries);
+    char **names, char **values,
+    int numentries);
 char            *mapObj_processQueryTemplate(mapObj *self,
-                                             int bGenerateImages,
-                                             char **names, char **values, 
-                                             int numentries);
+    int bGenerateImages,
+    char **names, char **values,
+    int numentries);
 int             mapObj_setSymbolSet(mapObj *self, char *szFileName);
 int             mapObj_getNumSymbols(mapObj *self);
 int             mapObj_setFontSet(mapObj *self, char *szFileName);
@@ -546,19 +564,19 @@ int             mapObj_saveMapContext(mapObj *self, char *szFileName);
 int             mapObj_loadMapContext(mapObj *self, char *szFileName,
                                       int bUniqueLayerName);
 int             mapObj_selectOutputFormat(mapObj *self,
-                                          const char *imagetype);
+    const char *imagetype);
 int             mapObj_applySLD(mapObj *self, char *sld);
 int             mapObj_applySLDURL(mapObj *self, char *sld);
 char            *mapObj_generateSLD(mapObj *self);
-int             mapObj_loadOWSParameters(mapObj *self, cgiRequestObj *request, 
-                                          char *wmtver_string);
+int             mapObj_loadOWSParameters(mapObj *self, cgiRequestObj *request,
+    char *wmtver_string);
 int             mapObj_OWSDispatch(mapObj *self, cgiRequestObj *req );
 int             mapObj_insertLayer(mapObj *self, layerObj *layer, int index);
 layerObj        *mapObj_removeLayer(mapObj *self, int layerindex);
 
 int             mapObj_setCenter(mapObj *self, pointObj *center);
 int             mapObj_offsetExtent(mapObj *self, double x, double y);
-int             mapObj_scaleExtent(mapObj *self, double zoomfactor, double minscaledenom, 
+int             mapObj_scaleExtent(mapObj *self, double zoomfactor, double minscaledenom,
                                    double maxscaledenom);
 
 layerObj       *layerObj_new(mapObj *map);
@@ -572,20 +590,23 @@ int             layerObj_getShape(layerObj *self, shapeObj *shape,
                                   int tileindex, int shapeindex);
 resultObj *layerObj_getResult(layerObj *self, int i);
 classObj       *layerObj_getClass(layerObj *self, int i);
-int layerObj_getClassIndex(layerObj *self, mapObj *map, shapeObj *shape, 
+int layerObj_getClassIndex(layerObj *self, mapObj *map, shapeObj *shape,
                            int *classgroup, int numclasses);
 int             layerObj_draw(layerObj *self, mapObj *map, imageObj *img);
 int             layerObj_drawQuery(layerObj *self, mapObj *map, imageObj *img);
-int             layerObj_queryByAttributes(layerObj *self, mapObj *map, 
-                                           char *qitem, char *qstring, 
-                                           int mode);
-int             layerObj_queryByPoint(layerObj *self, mapObj *map, 
-                          pointObj *point, int mode, double buffer);
+int             layerObj_queryByAttributes(layerObj *self, mapObj *map,
+    char *qitem, char *qstring,
+    int mode);
+int             layerObj_queryByPoint(layerObj *self, mapObj *map,
+                                      pointObj *point, int mode, double buffer);
 int             layerObj_queryByRect(layerObj *self, mapObj *map,rectObj rect);
-int             layerObj_queryByFeatures(layerObj *self, mapObj *map, 
-                                         int slayer);
-int             layerObj_queryByShape(layerObj *self, mapObj *map, 
+int             layerObj_queryByFeatures(layerObj *self, mapObj *map,
+    int slayer);
+int             layerObj_queryByShape(layerObj *self, mapObj *map,
                                       shapeObj *shape);
+int             layerObj_queryByFilter(layerObj *self, mapObj *map, char *string);
+int             layerObj_queryByIndex(layerObj *self, mapObj *map, int tileindex,
+                                      int shapeindex, int addtoquery);
 int             layerObj_setFilter(layerObj *self, char *string);
 char*           layerObj_getFilter(layerObj *self);
 int             layerObj_setWKTProjection(layerObj *self, char *string);
@@ -595,10 +616,10 @@ int             layerObj_addFeature(layerObj *self, shapeObj *shape);
 char            *layerObj_getMetaData(layerObj *self, char *name);
 int             layerObj_setMetaData(layerObj *self, char *name, char *value);
 int             layerObj_removeMetaData(layerObj *self, char *name);
-char            *layerObj_getWMSFeatureInfoURL(layerObj *self, mapObj *map, 
-                                               int click_x, int click_y,     
-                                               int feature_count, 
-                                               char *info_format);
+char            *layerObj_getWMSFeatureInfoURL(layerObj *self, mapObj *map,
+    int click_x, int click_y,
+    int feature_count,
+    char *info_format);
 char            *layerObj_executeWFSGetFeature(layerObj *self);
 int             layerObj_applySLD(layerObj *self, char *sld, char *stylelayer);
 int             layerObj_applySLDURL(layerObj *self, char *sld, char *stylelayer);
@@ -606,13 +627,17 @@ char            *layerObj_generateSLD(layerObj *self);
 int             layerObj_moveClassUp(layerObj *self, int index);
 int             layerObj_moveClassDown(layerObj *self, int index);
 classObj        *layerObj_removeClass(layerObj *self, int index);
-int             layerObj_setConnectionType(layerObj *self, int connectiontype, 
-                                           const char *library_str) ;
+int             layerObj_setConnectionType(layerObj *self, int connectiontype,
+    const char *library_str) ;
+layerObj        *layerObj_clone(layerObj *layer);
 
+labelObj        *labelObj_new();
 int             labelObj_updateFromString(labelObj *self, char *snippet);
+void            labelObj_destroy(labelObj *self);
 int             labelObj_moveStyleUp(labelObj *self, int index);
 int             labelObj_moveStyleDown(labelObj *self, int index);
 int             labelObj_deleteStyle(labelObj *self, int index);
+labelObj        *labelObj_clone(labelObj *label);
 
 int             legendObj_updateFromString(legendObj *self, char *snippet);
 
@@ -625,6 +650,9 @@ int             scalebarObj_updateFromString(scalebarObj *self, char *snippet);
 int             webObj_updateFromString(webObj *self, char *snippet);
 
 classObj       *classObj_new(layerObj *layer, classObj *class);
+labelObj       *classObj_getLabel(classObj *self, int i);
+int             classObj_addLabel(classObj *self, labelObj *label);
+labelObj       *classObj_removeLabel(classObj *self, int index);
 int             classObj_updateFromString(classObj *self, char *snippet);
 void            classObj_destroy(classObj* self);
 int             classObj_setExpression(classObj *self, char *string);
@@ -633,20 +661,20 @@ int             classObj_setText(classObj *self,layerObj *layer,char *string);
 char           *classObj_getTextString(classObj *self);
 int             classObj_drawLegendIcon(classObj *self,
                                         mapObj *map,
-                                        layerObj *layer, 
-                                        int width, int height, 
-                                        imageObj *im, 
+                                        layerObj *layer,
+                                        int width, int height,
+                                        imageObj *im,
                                         int dstX, int dstY);
-imageObj       *classObj_createLegendIcon(classObj *self, 
-                                          mapObj *map, 
-                                          layerObj *layer, 
-                                          int width, int height);
+imageObj       *classObj_createLegendIcon(classObj *self,
+    mapObj *map,
+    layerObj *layer,
+    int width, int height);
 int             classObj_setSymbolByName(classObj *self,
-                                         mapObj *map,
-                                         char *pszSymbolName);
+    mapObj *map,
+    char *pszSymbolName);
 int             classObj_setOverlaySymbolByName(classObj *self,
-                                                mapObj *map,
-                                                char *pszOverlaySymbolName);
+    mapObj *map,
+    char *pszOverlaySymbolName);
 classObj        *classObj_clone(classObj *class, layerObj *layer);
 int             classObj_moveStyleUp(classObj *self, int index);
 int             classObj_moveStyleDown(classObj *self, int index);
@@ -657,20 +685,21 @@ int             classObj_removeMetaData(classObj *self, char *name);
 
 pointObj       *pointObj_new();
 void            pointObj_destroy(pointObj *self);
-int             pointObj_project(pointObj *self, projectionObj *in, 
+int             pointObj_project(pointObj *self, projectionObj *in,
                                  projectionObj *out);
-int             pointObj_draw(pointObj *self, mapObj *map, layerObj *layer, 
-                              imageObj *img, int class_index, 
+int             pointObj_draw(pointObj *self, mapObj *map, layerObj *layer,
+                              imageObj *img, int class_index,
                               char *label_string);
 double          pointObj_distanceToPoint(pointObj *self, pointObj *point);
-double          pointObj_distanceToLine(pointObj *self, pointObj *a, 
+double          pointObj_distanceToLine(pointObj *self, pointObj *a,
                                         pointObj *b);
 double          pointObj_distanceToShape(pointObj *self, shapeObj *shape);
 
 
 lineObj        *lineObj_new();
 void            lineObj_destroy(lineObj *self);
-int             lineObj_project(lineObj *self, projectionObj *in, 
+lineObj        *lineObj_clone(lineObj *line);
+int             lineObj_project(lineObj *self, projectionObj *in,
                                 projectionObj *out);
 pointObj       *lineObj_get(lineObj *self, int i);
 int             lineObj_add(lineObj *self, pointObj *p);
@@ -678,11 +707,11 @@ int             lineObj_add(lineObj *self, pointObj *p);
 
 shapeObj       *shapeObj_new(int type);
 void            shapeObj_destroy(shapeObj *self);
-int             shapeObj_project(shapeObj *self, projectionObj *in, 
+int             shapeObj_project(shapeObj *self, projectionObj *in,
                                  projectionObj *out);
 lineObj        *shapeObj_get(shapeObj *self, int i);
 int             shapeObj_add(shapeObj *self, lineObj *line);
-int             shapeObj_draw(shapeObj *self, mapObj *map, layerObj *layer, 
+int             shapeObj_draw(shapeObj *self, mapObj *map, layerObj *layer,
                               imageObj *img);
 void            shapeObj_setBounds(shapeObj *self);
 int             shapeObj_copy(shapeObj *self, shapeObj *dest);
@@ -714,7 +743,7 @@ pointObj        *shapeObj_getLabelPoint(shapeObj *self);
 
 rectObj        *rectObj_new();
 void            rectObj_destroy(rectObj *self);
-int             rectObj_project(rectObj *self, projectionObj *in, 
+int             rectObj_project(rectObj *self, projectionObj *in,
                                 projectionObj *out);
 double          rectObj_fit(rectObj *self, int width, int height);
 int             rectObj_draw(rectObj *self, mapObj *map, layerObj *layer,
@@ -725,14 +754,15 @@ shapefileObj   *shapefileObj_new(char *filename, int type);
 void            shapefileObj_destroy(shapefileObj *self);
 int             shapefileObj_get(shapefileObj *self, int i, shapeObj *shape);
 int             shapefileObj_getPoint(shapefileObj *self, int i, pointObj *point);
-int             shapefileObj_getTransformed(shapefileObj *self, mapObj *map, 
-                                            int i, shapeObj *shape);
-void            shapefileObj_getExtent(shapefileObj *self, int i, 
+int             shapefileObj_getTransformed(shapefileObj *self, mapObj *map,
+    int i, shapeObj *shape);
+void            shapefileObj_getExtent(shapefileObj *self, int i,
                                        rectObj *rect);
 int             shapefileObj_add(shapefileObj *self, shapeObj *shape);
 int             shapefileObj_addPoint(shapefileObj *self, pointObj *point);
 
 projectionObj   *projectionObj_new(char *string);
+projectionObj   *projectionObj_clone(projectionObj *projection);
 int             projectionObj_getUnits(projectionObj *self);
 void            projectionObj_destroy(projectionObj *self);
 
@@ -746,13 +776,13 @@ DBFFieldType    DBFInfo_getFieldType(DBFInfo *self, int iField);
 styleObj       *styleObj_new(classObj *class, styleObj *style);
 styleObj       *styleObj_label_new(labelObj *label, styleObj *style);
 int             styleObj_updateFromString(styleObj *self, char *snippet);
-int             styleObj_setSymbolByName(styleObj *self, mapObj *map, 
-                                         char* pszSymbolName);
+int             styleObj_setSymbolByName(styleObj *self, mapObj *map,
+    char* pszSymbolName);
 styleObj       *styleObj_clone(styleObj *style);
 void           styleObj_setGeomTransform(styleObj *style, char *transform);
 
 hashTableObj   *hashTableObj_new();
-int             hashTableObj_set(hashTableObj *self, const char *key, 
+int             hashTableObj_set(hashTableObj *self, const char *key,
                                  const char *value);
 const char     *hashTableObj_get(hashTableObj *self, const char *key);
 int            hashTableObj_remove(hashTableObj *self, const char *key);
@@ -761,12 +791,13 @@ char           *hashTableObj_nextKey(hashTableObj *self, const char *prevkey);
 
 
 cgiRequestObj *cgirequestObj_new();
-int cgirequestObj_loadParams(cgiRequestObj *self, 
-                             char* (*getenv2)(const char*, void* thread_context), 
+int cgirequestObj_loadParams(cgiRequestObj *self,
+                             char* (*getenv2)(const char*, void* thread_context),
                              char *raw_post_data,
                              ms_uint32 raw_post_data_length,
                              void* thread_context);
 void cgirequestObj_setParameter(cgiRequestObj *self, char *name, char *value);
+void cgirequestObj_addParameter(cgiRequestObj *self, char *name, char *value);
 char *cgirequestObj_getName(cgiRequestObj *self, int index);
 char *cgirequestObj_getValue(cgiRequestObj *self, int index);
 char *cgirequestObj_getValueByName(cgiRequestObj *self, const char *name);
@@ -780,4 +811,10 @@ char *clusterObj_getGroupString(clusterObj *self);
 int clusterObj_setFilter(clusterObj *self, char *string);
 char *clusterObj_getFilterString(clusterObj *self);
 
+outputFormatObj *outputFormatObj_new(const char *driver, char *name);
+void  outputFormatObj_destroy(outputFormatObj* self);
+
+int symbolObj_setImage(symbolObj *self, imageObj *image);
+imageObj *symbolObj_getImage(symbolObj *self, outputFormatObj *input_format);
+
 #endif /* PHP_MAPSCRIPT_H */
diff --git a/mapscript/php/php_mapscript_util.c b/mapscript/php/php_mapscript_util.c
index 528f2c6..2bd2d48 100644
--- a/mapscript/php/php_mapscript_util.c
+++ b/mapscript/php/php_mapscript_util.c
@@ -14,141 +14,151 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
+ *
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  * DEALINGS IN THE SOFTWARE.
  **********************************************************************/
 
 
 #include "php_mapscript_util.h"
-#include "maperror.h"
+#include "../../maperror.h"
 
 
 zend_object_value mapscript_object_new(zend_object *zobj,
                                        zend_class_entry *ce,
                                        void (*zend_objects_free_object) TSRMLS_DC)
 {
-    zend_object_value retval;
-    zval *temp;
-    
-    zobj->ce = ce;
-    ALLOC_HASHTABLE(zobj->properties);
-    zend_hash_init(zobj->properties, 0, NULL, ZVAL_PTR_DTOR, 0);
-    zend_hash_copy(zobj->properties, &ce->default_properties, (copy_ctor_func_t) zval_add_ref,(void *) &temp, sizeof(zval *));
-    retval.handle = zend_objects_store_put(zobj, NULL, (zend_objects_free_object_storage_t)zend_objects_free_object, NULL TSRMLS_CC);
-    retval.handlers = &mapscript_std_object_handlers;
-    return retval;
+  zend_object_value retval;
+  zval *temp;
+
+  zobj->ce = ce;
+  ALLOC_HASHTABLE(zobj->properties);
+  zend_hash_init(zobj->properties, 0, NULL, ZVAL_PTR_DTOR, 0);
+  //handle changes in PHP 5.4.x
+#if PHP_VERSION_ID < 50399
+  zend_hash_copy(zobj->properties, &ce->default_properties, (copy_ctor_func_t) zval_add_ref,(void *) &temp, sizeof(zval *));
+#else
+  object_properties_init(zobj, ce);
+#endif
+  retval.handle = zend_objects_store_put(zobj, NULL, (zend_objects_free_object_storage_t)zend_objects_free_object, NULL TSRMLS_CC);
+  retval.handlers = &mapscript_std_object_handlers;
+  return retval;
 }
 
 zend_object_value mapscript_object_new_ex(zend_object *zobj,
-                                          zend_class_entry *ce,
-                                          void (*zend_objects_free_object),
-                                          zend_object_handlers *object_handlers TSRMLS_DC)
+    zend_class_entry *ce,
+    void (*zend_objects_free_object),
+    zend_object_handlers *object_handlers TSRMLS_DC)
 {
-    zend_object_value retval;
-    zval *temp;
-    
-    zobj->ce = ce;
-    ALLOC_HASHTABLE(zobj->properties);
-    zend_hash_init(zobj->properties, 0, NULL, ZVAL_PTR_DTOR, 0);
-    zend_hash_copy(zobj->properties, &ce->default_properties, (copy_ctor_func_t) zval_add_ref,(void *) &temp, sizeof(zval *));
-    retval.handle = zend_objects_store_put(zobj, NULL, (zend_objects_free_object_storage_t)zend_objects_free_object, NULL TSRMLS_CC);
-    retval.handlers = object_handlers;
-    return retval;
+  zend_object_value retval;
+  zval *temp;
+
+  zobj->ce = ce;
+  ALLOC_HASHTABLE(zobj->properties);
+  zend_hash_init(zobj->properties, 0, NULL, ZVAL_PTR_DTOR, 0);
+  //handle changes in PHP 5.4.x
+#if PHP_VERSION_ID < 50399
+  zend_hash_copy(zobj->properties, &ce->default_properties, (copy_ctor_func_t) zval_add_ref,(void *) &temp, sizeof(zval *));
+#else
+  object_properties_init(zobj, ce);
+#endif
+  retval.handle = zend_objects_store_put(zobj, NULL, (zend_objects_free_object_storage_t)zend_objects_free_object, NULL TSRMLS_CC);
+  retval.handlers = object_handlers;
+  return retval;
 }
 
 int mapscript_extract_associative_array(HashTable *php, char **array)
 {
-    zval **value;
-    char *string_key = NULL;
-    ulong num_key;
-    int i = 0;    
+  zval **value;
+  char *string_key = NULL;
+  ulong num_key;
+  int i = 0;
 
-    for(zend_hash_internal_pointer_reset(php); 
-        zend_hash_has_more_elements(php) == SUCCESS; 
-        zend_hash_move_forward(php))
-    { 
-        zend_hash_get_current_data(php, (void **)&value);
+  for(zend_hash_internal_pointer_reset(php);
+      zend_hash_has_more_elements(php) == SUCCESS;
+      zend_hash_move_forward(php)) {
+    zend_hash_get_current_data(php, (void **)&value);
 
-        switch (zend_hash_get_current_key(php, &string_key, &num_key, 1)) 
-        {
-            case HASH_KEY_IS_STRING:
-                array[i++] = string_key;
-                array[i++] = Z_STRVAL_PP(value);
-                break;
-        }
+    switch (zend_hash_get_current_key(php, &string_key, &num_key, 1)) {
+      case HASH_KEY_IS_STRING:
+        array[i++] = string_key;
+        array[i++] = Z_STRVAL_PP(value);
+        break;
     }
-    array[i++] = NULL;
+  }
+  array[i++] = NULL;
 
-    return 1;
+  return 1;
 }
 
-/* This method returns an object property of a php class. If the object exists, it returns a reference to it, 
+/* This method returns an object property of a php class. If the object exists, it returns a reference to it,
    otherwise it creates it */
-void mapscript_fetch_object(zend_class_entry *ce, zval* zval_parent, php_layer_object* layer, 
-                            void *internal_object, 
+void mapscript_fetch_object(zend_class_entry *ce, zval* zval_parent, php_layer_object* layer,
+                            void *internal_object,
                             zval **php_object_storage TSRMLS_DC)
 {
-    parent_object p;
+  parent_object p;
+
+  // create the parent struct
+  p.val = zval_parent;
+  p.child_ptr = &*php_object_storage;
+  MAKE_STD_ZVAL(*php_object_storage);
 
-    // create the parent struct
-    p.val = zval_parent;
-    p.child_ptr = &*php_object_storage;
-    MAKE_STD_ZVAL(*php_object_storage);
-        
-    if (ce == mapscript_ce_outputformat)
-        mapscript_create_outputformat((outputFormatObj*)internal_object, p, *php_object_storage TSRMLS_CC);
-    else if (ce == mapscript_ce_color)
-        mapscript_create_color((colorObj*)internal_object, p, *php_object_storage TSRMLS_CC);
-    else if (ce == mapscript_ce_rect)
-        mapscript_create_rect((rectObj*)internal_object, p, *php_object_storage TSRMLS_CC);
-    else if (ce == mapscript_ce_class)
-        mapscript_create_class((classObj*)internal_object, p, *php_object_storage TSRMLS_CC);
-    else if (ce == mapscript_ce_hashtable)
-        mapscript_create_hashtable((hashTableObj*)internal_object, p, *php_object_storage TSRMLS_CC);
-    else if (ce == mapscript_ce_label)
-        mapscript_create_label((labelObj*)internal_object, p, *php_object_storage TSRMLS_CC);
-    else if (ce == mapscript_ce_style)
-        mapscript_create_style((styleObj*)internal_object, p, *php_object_storage TSRMLS_CC);
-    else if (ce == mapscript_ce_symbol)
-        mapscript_create_symbol((symbolObj*)internal_object, p, *php_object_storage TSRMLS_CC);
-    else if (ce == mapscript_ce_labelcachemember)
-        mapscript_create_labelcachemember((labelCacheMemberObj*)internal_object, p, *php_object_storage TSRMLS_CC);
-    else if (ce == mapscript_ce_labelcache)
-        mapscript_create_labelcache((labelCacheObj*)internal_object, p, *php_object_storage TSRMLS_CC);
-    else if (ce == mapscript_ce_result)
-        mapscript_create_result((resultObj*)internal_object, p, *php_object_storage TSRMLS_CC);
-    else if (ce == mapscript_ce_scalebar)
-        mapscript_create_scalebar((scalebarObj*)internal_object, p, *php_object_storage TSRMLS_CC);
-    else if (ce == mapscript_ce_web)
-        mapscript_create_web((webObj*)internal_object, p, *php_object_storage TSRMLS_CC);
-    else if (ce == mapscript_ce_legend)
-        mapscript_create_legend((legendObj*)internal_object, p, *php_object_storage TSRMLS_CC);
-    else if (ce == mapscript_ce_querymap)
-        mapscript_create_querymap((queryMapObj*)internal_object, p, *php_object_storage TSRMLS_CC);
-    else if (ce == mapscript_ce_grid)
-        mapscript_create_grid((graticuleObj*)internal_object, p, *php_object_storage TSRMLS_CC);
-    else if (ce == mapscript_ce_referencemap)
-        mapscript_create_referencemap((referenceMapObj*)internal_object, p, *php_object_storage TSRMLS_CC);
-    else if (ce == mapscript_ce_point)
-        mapscript_create_point((pointObj*)internal_object, p, *php_object_storage TSRMLS_CC);
-    else if (ce == mapscript_ce_projection)
-        mapscript_create_projection((projectionObj*)internal_object, p, *php_object_storage TSRMLS_CC);
-    else if (ce == mapscript_ce_line)
-        mapscript_create_line((lineObj*)internal_object, p, *php_object_storage TSRMLS_CC);
-    else if (ce == mapscript_ce_shape)
-        mapscript_create_shape((shapeObj*)internal_object, p, layer, *php_object_storage TSRMLS_CC);
-    else if (ce == mapscript_ce_layer)
-        mapscript_create_layer((layerObj*)internal_object, p, *php_object_storage TSRMLS_CC);
-    else if (ce == mapscript_ce_cluster)
-        mapscript_create_cluster((clusterObj*)internal_object, p, *php_object_storage TSRMLS_CC);
+  if (ce == mapscript_ce_outputformat)
+    mapscript_create_outputformat((outputFormatObj*)internal_object, p, *php_object_storage TSRMLS_CC);
+  else if (ce == mapscript_ce_color)
+    mapscript_create_color((colorObj*)internal_object, p, *php_object_storage TSRMLS_CC);
+  else if (ce == mapscript_ce_rect)
+    mapscript_create_rect((rectObj*)internal_object, p, *php_object_storage TSRMLS_CC);
+  else if (ce == mapscript_ce_class)
+    mapscript_create_class((classObj*)internal_object, p, *php_object_storage TSRMLS_CC);
+  else if (ce == mapscript_ce_hashtable)
+    mapscript_create_hashtable((hashTableObj*)internal_object, p, *php_object_storage TSRMLS_CC);
+  else if (ce == mapscript_ce_label)
+    mapscript_create_label((labelObj*)internal_object, p, *php_object_storage TSRMLS_CC);
+  else if (ce == mapscript_ce_style)
+    mapscript_create_style((styleObj*)internal_object, p, *php_object_storage TSRMLS_CC);
+  else if (ce == mapscript_ce_symbol)
+    mapscript_create_symbol((symbolObj*)internal_object, p, *php_object_storage TSRMLS_CC);
+  else if (ce == mapscript_ce_labelcachemember)
+    mapscript_create_labelcachemember((labelCacheMemberObj*)internal_object, p, *php_object_storage TSRMLS_CC);
+  else if (ce == mapscript_ce_labelcache)
+    mapscript_create_labelcache((labelCacheObj*)internal_object, p, *php_object_storage TSRMLS_CC);
+  else if (ce == mapscript_ce_result)
+    mapscript_create_result((resultObj*)internal_object, p, *php_object_storage TSRMLS_CC);
+  else if (ce == mapscript_ce_scalebar)
+    mapscript_create_scalebar((scalebarObj*)internal_object, p, *php_object_storage TSRMLS_CC);
+  else if (ce == mapscript_ce_web)
+    mapscript_create_web((webObj*)internal_object, p, *php_object_storage TSRMLS_CC);
+  else if (ce == mapscript_ce_legend)
+    mapscript_create_legend((legendObj*)internal_object, p, *php_object_storage TSRMLS_CC);
+  else if (ce == mapscript_ce_querymap)
+    mapscript_create_querymap((queryMapObj*)internal_object, p, *php_object_storage TSRMLS_CC);
+  else if (ce == mapscript_ce_grid)
+    mapscript_create_grid((graticuleObj*)internal_object, p, *php_object_storage TSRMLS_CC);
+  else if (ce == mapscript_ce_referencemap)
+    mapscript_create_referencemap((referenceMapObj*)internal_object, p, *php_object_storage TSRMLS_CC);
+  else if (ce == mapscript_ce_point)
+    mapscript_create_point((pointObj*)internal_object, p, *php_object_storage TSRMLS_CC);
+  else if (ce == mapscript_ce_projection)
+    mapscript_create_projection((projectionObj*)internal_object, p, *php_object_storage TSRMLS_CC);
+  else if (ce == mapscript_ce_line)
+    mapscript_create_line((lineObj*)internal_object, p, *php_object_storage TSRMLS_CC);
+  else if (ce == mapscript_ce_shape)
+    mapscript_create_shape((shapeObj*)internal_object, p, layer, *php_object_storage TSRMLS_CC);
+  else if (ce == mapscript_ce_layer)
+    mapscript_create_layer((layerObj*)internal_object, p, *php_object_storage TSRMLS_CC);
+  else if (ce == mapscript_ce_cluster)
+    mapscript_create_cluster((clusterObj*)internal_object, p, *php_object_storage TSRMLS_CC);
+  else if (ce == mapscript_ce_labelleader)
+    mapscript_create_labelleader((labelLeaderObj*)internal_object, p, *php_object_storage TSRMLS_CC);
 }
 
diff --git a/mapscript/php/php_mapscript_util.h b/mapscript/php/php_mapscript_util.h
index cbb9ed9..73ae02d 100644
--- a/mapscript/php/php_mapscript_util.h
+++ b/mapscript/php/php_mapscript_util.h
@@ -15,19 +15,19 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
+ *
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  * DEALINGS IN THE SOFTWARE.
  **********************************************************************/
- 
+
 
 #ifndef PHP_MAPSCRIPT_UTIL_H
 #define PHP_MAPSCRIPT_UTIL_H
@@ -37,7 +37,7 @@
 #include "php_mapscript.h"
 
 #if ZEND_MODULE_API_NO < 20010901
-#define TSRMLS_D	void
+#define TSRMLS_D  void
 #define TSRMLS_DC
 #define TSRMLS_C
 #define TSRMLS_CC
@@ -46,32 +46,32 @@
 /* Add pseudo refcount macros for PHP version < 5.3 */
 #ifndef Z_REFCOUNT_PP
 
-#define Z_REFCOUNT_PP(ppz)				Z_REFCOUNT_P(*(ppz))
-#define Z_SET_REFCOUNT_PP(ppz, rc)		Z_SET_REFCOUNT_P(*(ppz), rc)
-#define Z_ADDREF_PP(ppz)				Z_ADDREF_P(*(ppz))
-#define Z_DELREF_PP(ppz)				Z_DELREF_P(*(ppz))
-#define Z_ISREF_PP(ppz)					Z_ISREF_P(*(ppz))
-#define Z_SET_ISREF_PP(ppz)				Z_SET_ISREF_P(*(ppz))
-#define Z_UNSET_ISREF_PP(ppz)			Z_UNSET_ISREF_P(*(ppz))
-#define Z_SET_ISREF_TO_PP(ppz, isref)	Z_SET_ISREF_TO_P(*(ppz), isref)
-
-#define Z_REFCOUNT_P(pz)				zval_refcount_p(pz)
-#define Z_SET_REFCOUNT_P(pz, rc)		zval_set_refcount_p(pz, rc)
-#define Z_ADDREF_P(pz)					zval_addref_p(pz)
-#define Z_DELREF_P(pz)					zval_delref_p(pz)
-#define Z_ISREF_P(pz)					zval_isref_p(pz)
-#define Z_SET_ISREF_P(pz)				zval_set_isref_p(pz)
-#define Z_UNSET_ISREF_P(pz)				zval_unset_isref_p(pz)
-#define Z_SET_ISREF_TO_P(pz, isref)		zval_set_isref_to_p(pz, isref)
-
-#define Z_REFCOUNT(z)					Z_REFCOUNT_P(&(z))
-#define Z_SET_REFCOUNT(z, rc)			Z_SET_REFCOUNT_P(&(z), rc)
-#define Z_ADDREF(z)						Z_ADDREF_P(&(z))
-#define Z_DELREF(z)						Z_DELREF_P(&(z))
-#define Z_ISREF(z)						Z_ISREF_P(&(z))
-#define Z_SET_ISREF(z)					Z_SET_ISREF_P(&(z))
-#define Z_UNSET_ISREF(z)				Z_UNSET_ISREF_P(&(z))
-#define Z_SET_ISREF_TO(z, isref)		Z_SET_ISREF_TO_P(&(z), isref)
+#define Z_REFCOUNT_PP(ppz)        Z_REFCOUNT_P(*(ppz))
+#define Z_SET_REFCOUNT_PP(ppz, rc)    Z_SET_REFCOUNT_P(*(ppz), rc)
+#define Z_ADDREF_PP(ppz)        Z_ADDREF_P(*(ppz))
+#define Z_DELREF_PP(ppz)        Z_DELREF_P(*(ppz))
+#define Z_ISREF_PP(ppz)         Z_ISREF_P(*(ppz))
+#define Z_SET_ISREF_PP(ppz)       Z_SET_ISREF_P(*(ppz))
+#define Z_UNSET_ISREF_PP(ppz)     Z_UNSET_ISREF_P(*(ppz))
+#define Z_SET_ISREF_TO_PP(ppz, isref) Z_SET_ISREF_TO_P(*(ppz), isref)
+
+#define Z_REFCOUNT_P(pz)        zval_refcount_p(pz)
+#define Z_SET_REFCOUNT_P(pz, rc)    zval_set_refcount_p(pz, rc)
+#define Z_ADDREF_P(pz)          zval_addref_p(pz)
+#define Z_DELREF_P(pz)          zval_delref_p(pz)
+#define Z_ISREF_P(pz)         zval_isref_p(pz)
+#define Z_SET_ISREF_P(pz)       zval_set_isref_p(pz)
+#define Z_UNSET_ISREF_P(pz)       zval_unset_isref_p(pz)
+#define Z_SET_ISREF_TO_P(pz, isref)   zval_set_isref_to_p(pz, isref)
+
+#define Z_REFCOUNT(z)         Z_REFCOUNT_P(&(z))
+#define Z_SET_REFCOUNT(z, rc)     Z_SET_REFCOUNT_P(&(z), rc)
+#define Z_ADDREF(z)           Z_ADDREF_P(&(z))
+#define Z_DELREF(z)           Z_DELREF_P(&(z))
+#define Z_ISREF(z)            Z_ISREF_P(&(z))
+#define Z_SET_ISREF(z)          Z_SET_ISREF_P(&(z))
+#define Z_UNSET_ISREF(z)        Z_UNSET_ISREF_P(&(z))
+#define Z_SET_ISREF_TO(z, isref)    Z_SET_ISREF_TO_P(&(z), isref)
 
 #if defined(__GNUC__)
 #define zend_always_inline inline __attribute__((always_inline))
@@ -81,36 +81,44 @@
 #define zend_always_inline inline
 #endif
 
-static zend_always_inline zend_uint zval_refcount_p(zval* pz) {
-	return pz->refcount;
+static zend_always_inline zend_uint zval_refcount_p(zval* pz)
+{
+  return pz->refcount;
 }
 
-static zend_always_inline zend_uint zval_set_refcount_p(zval* pz, zend_uint rc) {
-	return pz->refcount = rc;
+static zend_always_inline zend_uint zval_set_refcount_p(zval* pz, zend_uint rc)
+{
+  return pz->refcount = rc;
 }
 
-static zend_always_inline zend_uint zval_addref_p(zval* pz) {
-	return ++pz->refcount;
+static zend_always_inline zend_uint zval_addref_p(zval* pz)
+{
+  return ++pz->refcount;
 }
 
-static zend_always_inline zend_uint zval_delref_p(zval* pz) {
-	return --pz->refcount;
+static zend_always_inline zend_uint zval_delref_p(zval* pz)
+{
+  return --pz->refcount;
 }
 
-static zend_always_inline zend_bool zval_isref_p(zval* pz) {
-	return pz->is_ref;
+static zend_always_inline zend_bool zval_isref_p(zval* pz)
+{
+  return pz->is_ref;
 }
 
-static zend_always_inline zend_bool zval_set_isref_p(zval* pz) {
-	return pz->is_ref = 1;
+static zend_always_inline zend_bool zval_set_isref_p(zval* pz)
+{
+  return pz->is_ref = 1;
 }
 
-static zend_always_inline zend_bool zval_unset_isref_p(zval* pz) {
-	return pz->is_ref = 0;
+static zend_always_inline zend_bool zval_unset_isref_p(zval* pz)
+{
+  return pz->is_ref = 0;
 }
 
-static zend_always_inline zend_bool zval_set_isref_to_p(zval* pz, zend_bool isref) {
-	return pz->is_ref = isref;
+static zend_always_inline zend_bool zval_set_isref_to_p(zval* pz, zend_bool isref)
+{
+  return pz->is_ref = isref;
 }
 
 #endif
@@ -177,19 +185,19 @@ static zend_always_inline zend_bool zval_set_isref_to_p(zval* pz, zend_bool isre
     { \
         RETVAL_STRING( (value ? value:"") , 1);    \
     } \
-
+ 
 #define IF_GET_LONG(property_name, value)  \
     if (strcmp(property, property_name)==0) \
     { \
         RETVAL_LONG(value); \
     } \
-
+ 
 #define IF_GET_DOUBLE(property_name, value)  \
     if (strcmp(property, property_name)==0) \
     { \
         RETVAL_DOUBLE(value); \
     } \
-
+ 
 #define IF_GET_OBJECT(property_name, mapscript_ce, php_object_storage, internal_object) \
     if (strcmp(property, property_name)==0)  \
     {   \
@@ -198,7 +206,7 @@ static zend_always_inline zend_bool zval_set_isref_to_p(zval* pz, zend_bool isre
                                    &php_object_storage TSRMLS_CC); \
         }                                                               \
         RETURN_ZVAL(php_object_storage, 1, 0);                          \
-    } 
+    }
 
 #define CHECK_OBJECT(mapscript_ce, php_object_storage, internal_object) \
     if (!php_object_storage) {                                          \
@@ -214,28 +222,28 @@ static zend_always_inline zend_bool zval_set_isref_to_p(zval* pz, zend_bool isre
         if (internal) free(internal);    \
         if (Z_STRVAL_P(value))                        \
             internal = strdup(Z_STRVAL_P(value));     \
-    } 
+    }
 
 #define IF_SET_LONG(property_name, internal, value)        \
     if (strcmp(property, property_name)==0)                  \
     { \
         convert_to_long(value); \
         internal = Z_LVAL_P(value);             \
-    } 
+    }
 
 #define IF_SET_DOUBLE(property_name, internal, value)        \
     if (strcmp(property, property_name)==0)                  \
     { \
         convert_to_double(value); \
         internal = Z_DVAL_P(value);             \
-    } 
+    }
 
 #define IF_SET_BYTE(property_name, internal, value)        \
     if (strcmp(property, property_name)==0)                  \
     { \
         convert_to_long(value); \
         internal = (unsigned char)Z_LVAL_P(value);            \
-    } 
+    }
 
 #define IF_SET_COLOR(property_name, internal, value)        \
     if (strcmp(property, property_name)==0)                  \
@@ -247,7 +255,7 @@ static zend_always_inline zend_bool zval_set_isref_to_p(zval* pz, zend_bool isre
             return;   \
         }             \
         internal = Z_LVAL_P(value);             \
-    } 
+    }
 
 
 zend_object_value mapscript_object_new(zend_object *zobj,
diff --git a/mapscript/php/php_proj.c b/mapscript/php/php_proj.c
index 2a17885..ab6f0e6 100644
--- a/mapscript/php/php_proj.c
+++ b/mapscript/php/php_proj.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
@@ -188,45 +188,45 @@ static zend_class_entry *proj_class_entry_ptr;
 static int le_projobj;
 
 function_entry php_proj_functions[] = {
-    {"pj_fwd",  php_proj_pj_fwd,   NULL},
-    {"pj_inv",  php_proj_pj_inv,   NULL},
-    {"pj_init",  php_proj_pj_init,   NULL},
-    {"pj_transform",  php_proj_pj_transform,   NULL},
-    {"pj_datum_transform",  php_proj_pj_datum_transform,   NULL},
-    {"pj_free",  php_proj_pj_free,   NULL},
-    {NULL, NULL, NULL}
+  {"pj_fwd",  php_proj_pj_fwd,   NULL},
+  {"pj_inv",  php_proj_pj_inv,   NULL},
+  {"pj_init",  php_proj_pj_init,   NULL},
+  {"pj_transform",  php_proj_pj_transform,   NULL},
+  {"pj_datum_transform",  php_proj_pj_datum_transform,   NULL},
+  {"pj_free",  php_proj_pj_free,   NULL},
+  {NULL, NULL, NULL}
 };
 
 
 php3_module_entry php_proj_module_entry = {
 #if ZEND_MODULE_API_NO >= 20010901
-    STANDARD_MODULE_HEADER,
+  STANDARD_MODULE_HEADER,
 #endif
-    "PHPPROJ", php_proj_functions, php_init_proj, php_end_proj,
-    NULL, NULL,
+  "PHPPROJ", php_proj_functions, php_init_proj, php_end_proj,
+  NULL, NULL,
 #ifdef ZEND_VERSION
-    PHP_MINFO(phpproj),
+  PHP_MINFO(phpproj),
 #else
-    php_info_proj,
+  php_info_proj,
 #endif
 #if ZEND_MODULE_API_NO >= 20010901
-    "phpproj, php4.1version",          /* extension version number (string) */
+  "phpproj, php4.1version",          /* extension version number (string) */
 #endif
-    STANDARD_MODULE_PROPERTIES
+  STANDARD_MODULE_PROPERTIES
 };
 
 
 #if COMPILE_DL
 DLEXPORT php3_module_entry *get_module(void)
 {
-    return &php_proj_module_entry;
+  return &php_proj_module_entry;
 }
 #endif
 
 
 function_entry php_proj_class_functions[] = {
-    {"ttt",             ttt,        NULL},
-    {NULL, NULL, NULL}
+  {"ttt",             ttt,        NULL},
+  {NULL, NULL, NULL}
 };
 
 DLEXPORT void ttt(INTERNAL_FUNCTION_PARAMETERS)
@@ -239,28 +239,28 @@ PHP_MINFO_FUNCTION(phpproj)
 DLEXPORT void php_info_proj(void)
 #endif
 {
-    php3_printf(" Version %s<br>\n", PHP_PROJ_VERSION);
+  php3_printf(" Version %s<br>\n", PHP_PROJ_VERSION);
 
-    php3_printf("<BR>\n");
+  php3_printf("<BR>\n");
 }
 
 DLEXPORT int php_init_proj(INIT_FUNC_ARGS)
 {
-    zend_class_entry tmp_class_entry;
+  zend_class_entry tmp_class_entry;
 
-    PHPMS_GLOBAL(le_projobj)  =
-        register_list_destructors(php_proj_pj_free,
-                                  NULL);
+  PHPMS_GLOBAL(le_projobj)  =
+    register_list_destructors(php_proj_pj_free,
+                              NULL);
 
-    INIT_CLASS_ENTRY(tmp_class_entry, "proj", php_proj_class_functions);
-    proj_class_entry_ptr = zend_register_internal_class(&tmp_class_entry TSRMLS_CC);
+  INIT_CLASS_ENTRY(tmp_class_entry, "proj", php_proj_class_functions);
+  proj_class_entry_ptr = zend_register_internal_class(&tmp_class_entry TSRMLS_CC);
 
-    return SUCCESS;
+  return SUCCESS;
 }
 
 DLEXPORT int php_end_proj(SHUTDOWN_FUNC_ARGS)
 {
-    return SUCCESS;
+  return SUCCESS;
 }
 
 
@@ -269,7 +269,7 @@ DLEXPORT int php_end_proj(SHUTDOWN_FUNC_ARGS)
 #endif
 
 #if !defined RAD_TO_DEG
-#define RAD_TO_DEG	57.29577951308232
+#define RAD_TO_DEG  57.29577951308232
 #endif
 
 /**********************************************************************
@@ -278,17 +278,17 @@ DLEXPORT int php_end_proj(SHUTDOWN_FUNC_ARGS)
 static long _php_proj_build_proj_object(PJ *pj,
                                         HashTable *list, pval *return_value TSRMLS_DC)
 {
-    int pj_id;
+  int pj_id;
 
-    if (pj == NULL)
-        return 0;
+  if (pj == NULL)
+    return 0;
 
-    pj_id = php3_list_insert(pj, PHPMS_GLOBAL(le_projobj));
+  pj_id = php3_list_insert(pj, PHPMS_GLOBAL(le_projobj));
 
-    _phpms_object_init(return_value, pj_id, php_proj_class_functions,
-                       PHP4_CLASS_ENTRY(proj_class_entry_ptr) TSRMLS_CC);
+  _phpms_object_init(return_value, pj_id, php_proj_class_functions,
+                     PHP4_CLASS_ENTRY(proj_class_entry_ptr) TSRMLS_CC);
 
-    return pj_id;
+  return pj_id;
 }
 
 
@@ -316,54 +316,51 @@ static long _php_proj_build_proj_object(PJ *pj,
 /************************************************************************/
 DLEXPORT void php_proj_pj_init(INTERNAL_FUNCTION_PARAMETERS)
 {
-    pval        *pArrayOfParams = NULL;
+  pval        *pArrayOfParams = NULL;
 
-    pval        **pParam = NULL;
-    HashTable   *list=NULL;
+  pval        **pParam = NULL;
+  HashTable   *list=NULL;
 
-    int         nParamCount = 0;
-    int         i = 0;
-    PJ          *pj = NULL;
+  int         nParamCount = 0;
+  int         i = 0;
+  PJ          *pj = NULL;
 
-    char        **papszBuf = NULL;
+  char        **papszBuf = NULL;
 
 //    char        *strttt = NULL;
 //    int         ttt;
 
-    //ttt = strlen(strttt);
-/* -------------------------------------------------------------------- */
-/*      extract parameters.                                             */
-/* -------------------------------------------------------------------- */
-    if (getParameters(ht, 1, &pArrayOfParams) != SUCCESS)
-    {
-        WRONG_PARAM_COUNT;
+  //ttt = strlen(strttt);
+  /* -------------------------------------------------------------------- */
+  /*      extract parameters.                                             */
+  /* -------------------------------------------------------------------- */
+  if (getParameters(ht, 1, &pArrayOfParams) != SUCCESS) {
+    WRONG_PARAM_COUNT;
+  }
+
+  if (pArrayOfParams->type == IS_ARRAY)
+    nParamCount = _php3_hash_num_elements(pArrayOfParams->value.ht);
+  else
+    nParamCount = 0;
+
+  if (nParamCount <= 0)
+    RETURN_LONG(-1);
+
+  papszBuf = (char **) malloc((nParamCount+2)*sizeof(char *));
+
+  for (i = 0; i < nParamCount; i++) {
+    if (_php3_hash_index_find(pArrayOfParams->value.ht, i,
+                              (void **)&pParam) != FAILURE) {
+      convert_to_string((*pParam));
+      if ((*pParam)->value.str.val != NULL)
+        papszBuf[i] = strdup((*pParam)->value.str.val);
     }
+  }
+  papszBuf[i] = NULL;
 
-    if (pArrayOfParams->type == IS_ARRAY)
-        nParamCount = _php3_hash_num_elements(pArrayOfParams->value.ht);
-    else
-      nParamCount = 0;
-
-    if (nParamCount <= 0)
-      RETURN_LONG(-1);
-
-    papszBuf = (char **) malloc((nParamCount+2)*sizeof(char *));
-
-    for (i = 0; i < nParamCount; i++)
-    {
-        if (_php3_hash_index_find(pArrayOfParams->value.ht, i,
-                                  (void **)&pParam) != FAILURE)
-        {
-            convert_to_string((*pParam));
-            if ((*pParam)->value.str.val != NULL)
-              papszBuf[i] = strdup((*pParam)->value.str.val);
-        }
-    }
-     papszBuf[i] = NULL;
-
-    pj = pj_init(nParamCount, papszBuf);
+  pj = pj_init(nParamCount, papszBuf);
 
-    _php_proj_build_proj_object(pj, list, return_value TSRMLS_CC);
+  _php_proj_build_proj_object(pj, list, return_value TSRMLS_CC);
 }
 
 
@@ -389,45 +386,42 @@ DLEXPORT void php_proj_pj_init(INTERNAL_FUNCTION_PARAMETERS)
 /************************************************************************/
 DLEXPORT void php_proj_pj_fwd(INTERNAL_FUNCTION_PARAMETERS)
 {
-    HashTable   *list=NULL;
-    pval        *p1, *p2;
-    pval        *pj = NULL;
-    PJ          *popj = NULL;
-    projUV      pnt;
-    projUV      pntReturn = {0,0};
-
-/* -------------------------------------------------------------------- */
-/*      extract parameters.                                             */
-/* -------------------------------------------------------------------- */
-    if (getParameters(ht, 3, &p1, &p2, &pj) != SUCCESS)
-    {
-        WRONG_PARAM_COUNT;
-    }
-
-/* -------------------------------------------------------------------- */
-/*      initilize return array.                                         */
-/* -------------------------------------------------------------------- */
-    if (array_init(return_value) == FAILURE)
-    {
-        RETURN_FALSE;
-    }
-
-    convert_to_double(p1);
-    convert_to_double(p2);
-
-    popj = (PJ *)_phpms_fetch_handle(pj,
-                                     PHPMS_GLOBAL(le_projobj), list TSRMLS_CC);
+  HashTable   *list=NULL;
+  pval        *p1, *p2;
+  pval        *pj = NULL;
+  PJ          *popj = NULL;
+  projUV      pnt;
+  projUV      pntReturn = {0,0};
+
+  /* -------------------------------------------------------------------- */
+  /*      extract parameters.                                             */
+  /* -------------------------------------------------------------------- */
+  if (getParameters(ht, 3, &p1, &p2, &pj) != SUCCESS) {
+    WRONG_PARAM_COUNT;
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      initilize return array.                                         */
+  /* -------------------------------------------------------------------- */
+  if (array_init(return_value) == FAILURE) {
+    RETURN_FALSE;
+  }
+
+  convert_to_double(p1);
+  convert_to_double(p2);
+
+  popj = (PJ *)_phpms_fetch_handle(pj,
+                                   PHPMS_GLOBAL(le_projobj), list TSRMLS_CC);
 
-    if (popj)
-    {
-        pnt.u = p2->value.dval * DEG_TO_RAD;
-        pnt.v = p1->value.dval * DEG_TO_RAD;
+  if (popj) {
+    pnt.u = p2->value.dval * DEG_TO_RAD;
+    pnt.v = p1->value.dval * DEG_TO_RAD;
 
-        pntReturn = pj_fwd(pnt, popj);
-    }
+    pntReturn = pj_fwd(pnt, popj);
+  }
 
-    add_assoc_double(return_value, "u", pntReturn.u);
-    add_assoc_double(return_value, "v", pntReturn.v);
+  add_assoc_double(return_value, "u", pntReturn.u);
+  add_assoc_double(return_value, "v", pntReturn.v);
 }
 
 
@@ -457,46 +451,43 @@ DLEXPORT void php_proj_pj_fwd(INTERNAL_FUNCTION_PARAMETERS)
 /************************************************************************/
 DLEXPORT void php_proj_pj_inv(INTERNAL_FUNCTION_PARAMETERS)
 {
-    HashTable   *list=NULL;
-    pval        *p1, *p2;
-    pval        *pj = NULL;
-    PJ          *popj = NULL;
-    projUV      pnt;
-    projUV      pntReturn = {0,0};
-/* -------------------------------------------------------------------- */
-/*      extract parameters.                                             */
-/* -------------------------------------------------------------------- */
-    if (getParameters(ht, 3, &p1, &p2, &pj) != SUCCESS)
-    {
-        WRONG_PARAM_COUNT;
-    }
-
-/* -------------------------------------------------------------------- */
-/*      initilize return array.                                         */
-/* -------------------------------------------------------------------- */
-    if (array_init(return_value) == FAILURE)
-    {
-        RETURN_FALSE;
-    }
-
-    convert_to_double(p1);
-    convert_to_double(p2);
-
-    popj = (PJ *)_phpms_fetch_handle(pj,
-                                     PHPMS_GLOBAL(le_projobj), list TSRMLS_CC);
+  HashTable   *list=NULL;
+  pval        *p1, *p2;
+  pval        *pj = NULL;
+  PJ          *popj = NULL;
+  projUV      pnt;
+  projUV      pntReturn = {0,0};
+  /* -------------------------------------------------------------------- */
+  /*      extract parameters.                                             */
+  /* -------------------------------------------------------------------- */
+  if (getParameters(ht, 3, &p1, &p2, &pj) != SUCCESS) {
+    WRONG_PARAM_COUNT;
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      initilize return array.                                         */
+  /* -------------------------------------------------------------------- */
+  if (array_init(return_value) == FAILURE) {
+    RETURN_FALSE;
+  }
+
+  convert_to_double(p1);
+  convert_to_double(p2);
+
+  popj = (PJ *)_phpms_fetch_handle(pj,
+                                   PHPMS_GLOBAL(le_projobj), list TSRMLS_CC);
 
-    if (popj)
-    {
-        pnt.u = p1->value.dval;
-        pnt.v = p2->value.dval;
+  if (popj) {
+    pnt.u = p1->value.dval;
+    pnt.v = p2->value.dval;
 
-        pntReturn = pj_inv(pnt, popj);
-        pntReturn.u *= RAD_TO_DEG;
-        pntReturn.v *= RAD_TO_DEG;
-    }
+    pntReturn = pj_inv(pnt, popj);
+    pntReturn.u *= RAD_TO_DEG;
+    pntReturn.v *= RAD_TO_DEG;
+  }
 
-    add_assoc_double(return_value, "u", pntReturn.v);
-    add_assoc_double(return_value, "v", pntReturn.u);
+  add_assoc_double(return_value, "u", pntReturn.v);
+  add_assoc_double(return_value, "v", pntReturn.u);
 }
 
 /************************************************************************/
@@ -515,71 +506,63 @@ DLEXPORT void php_proj_pj_inv(INTERNAL_FUNCTION_PARAMETERS)
 /************************************************************************/
 DLEXPORT void php_proj_pj_transform(INTERNAL_FUNCTION_PARAMETERS)
 {
-    HashTable   *list=NULL;
-    pval        *p1, *p2;
-    pval        *pjin, *pjout = NULL;
-    PJ          *in = NULL;
-    PJ          *out = NULL;
-    projUV      pnt = {0, 0};
-    double      z = 0;
-    int         error = -1;
-/* -------------------------------------------------------------------- */
-/*      extract parameters.                                             */
-/* -------------------------------------------------------------------- */
-    if (getParameters(ht, 4, &pjin , &pjout, &p1, &p2) != SUCCESS)
-    {
-        WRONG_PARAM_COUNT;
-    }
-
-/* -------------------------------------------------------------------- */
-/*      initilize return array.                                         */
-/* -------------------------------------------------------------------- */
-    if (array_init(return_value) == FAILURE)
-    {
-        RETURN_FALSE;
+  HashTable   *list=NULL;
+  pval        *p1, *p2;
+  pval        *pjin, *pjout = NULL;
+  PJ          *in = NULL;
+  PJ          *out = NULL;
+  projUV      pnt = {0, 0};
+  double      z = 0;
+  int         error = -1;
+  /* -------------------------------------------------------------------- */
+  /*      extract parameters.                                             */
+  /* -------------------------------------------------------------------- */
+  if (getParameters(ht, 4, &pjin , &pjout, &p1, &p2) != SUCCESS) {
+    WRONG_PARAM_COUNT;
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      initilize return array.                                         */
+  /* -------------------------------------------------------------------- */
+  if (array_init(return_value) == FAILURE) {
+    RETURN_FALSE;
+  }
+
+  convert_to_double(p1);
+  convert_to_double(p2);
+
+  in = (PJ *)_phpms_fetch_handle(pjin,
+                                 PHPMS_GLOBAL(le_projobj), list TSRMLS_CC);
+
+  out = (PJ *)_phpms_fetch_handle(pjout,
+                                  PHPMS_GLOBAL(le_projobj), list TSRMLS_CC);
+
+  if (in && out) {
+    pnt.u = p1->value.dval;
+    pnt.v = p2->value.dval;
+
+    if( pj_is_latlong(in) ) {
+      pnt.u *= DEG_TO_RAD;
+      pnt.v *= DEG_TO_RAD;
     }
 
-    convert_to_double(p1);
-    convert_to_double(p2);
+    error = pj_transform(in, out, 1, 0,
+                         &(pnt.u), &(pnt.v), &z );
 
-    in = (PJ *)_phpms_fetch_handle(pjin,
-                                   PHPMS_GLOBAL(le_projobj), list TSRMLS_CC);
-
-    out = (PJ *)_phpms_fetch_handle(pjout,
-                                    PHPMS_GLOBAL(le_projobj), list TSRMLS_CC);
-
-    if (in && out)
-    {
-        pnt.u = p1->value.dval;
-        pnt.v = p2->value.dval;
-
-        if( pj_is_latlong(in) )
-        {
-            pnt.u *= DEG_TO_RAD;
-            pnt.v *= DEG_TO_RAD;
-        }
-
-        error = pj_transform(in, out, 1, 0,
-                             &(pnt.u), &(pnt.v), &z );
-
-        if( pj_is_latlong(out) )
-        {
-            pnt.u *= RAD_TO_DEG;
-            pnt.v *= RAD_TO_DEG;
-        }
+    if( pj_is_latlong(out) ) {
+      pnt.u *= RAD_TO_DEG;
+      pnt.v *= RAD_TO_DEG;
     }
+  }
 
-    if (error)
-    {
-        php_error(E_ERROR,"Error in pj_transform");
+  if (error) {
+    php_error(E_ERROR,"Error in pj_transform");
 
-        RETURN_LONG(-1);
-    }
-    else
-    {
-        add_assoc_double(return_value, "u", pnt.u);
-        add_assoc_double(return_value, "v", pnt.v);
-    }
+    RETURN_LONG(-1);
+  } else {
+    add_assoc_double(return_value, "u", pnt.u);
+    add_assoc_double(return_value, "v", pnt.v);
+  }
 }
 
 
@@ -601,74 +584,65 @@ DLEXPORT void php_proj_pj_transform(INTERNAL_FUNCTION_PARAMETERS)
 /************************************************************************/
 DLEXPORT void php_proj_pj_datum_transform(INTERNAL_FUNCTION_PARAMETERS)
 {
-    HashTable   *list=NULL;
-    pval        *p1, *p2;
-    pval        *pjin, *pjout = NULL;
-    PJ          *in = NULL;
-    PJ          *out = NULL;
-    projUV      pnt = {0, 0};
-    double      z = 0;
-    int         error = -1;
-/* -------------------------------------------------------------------- */
-/*      extract parameters.                                             */
-/* -------------------------------------------------------------------- */
-    if (getParameters(ht, 4, &pjin , &pjout, &p1, &p2) != SUCCESS)
-    {
-        WRONG_PARAM_COUNT;
-    }
-
-/* -------------------------------------------------------------------- */
-/*      initilize return array.                                         */
-/* -------------------------------------------------------------------- */
-    if (array_init(return_value) == FAILURE)
-    {
-        RETURN_FALSE;
+  HashTable   *list=NULL;
+  pval        *p1, *p2;
+  pval        *pjin, *pjout = NULL;
+  PJ          *in = NULL;
+  PJ          *out = NULL;
+  projUV      pnt = {0, 0};
+  double      z = 0;
+  int         error = -1;
+  /* -------------------------------------------------------------------- */
+  /*      extract parameters.                                             */
+  /* -------------------------------------------------------------------- */
+  if (getParameters(ht, 4, &pjin , &pjout, &p1, &p2) != SUCCESS) {
+    WRONG_PARAM_COUNT;
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      initilize return array.                                         */
+  /* -------------------------------------------------------------------- */
+  if (array_init(return_value) == FAILURE) {
+    RETURN_FALSE;
+  }
+
+  convert_to_double(p1);
+  convert_to_double(p2);
+
+  in = (PJ *)_phpms_fetch_handle(pjin,
+                                 PHPMS_GLOBAL(le_projobj), list TSRMLS_CC);
+
+  out = (PJ *)_phpms_fetch_handle(pjout,
+                                  PHPMS_GLOBAL(le_projobj), list TSRMLS_CC);
+
+  if (in && out) {
+    pnt.u = p1->value.dval;
+    pnt.v = p2->value.dval;
+
+    if( pj_is_latlong(in) ) {
+      pnt.u *= DEG_TO_RAD;
+      pnt.v *= DEG_TO_RAD;
     }
 
-    convert_to_double(p1);
-    convert_to_double(p2);
-
-    in = (PJ *)_phpms_fetch_handle(pjin,
-                                   PHPMS_GLOBAL(le_projobj), list TSRMLS_CC);
+    error = pj_transform(in, out, 1, 0,
+                         &(pnt.u), &(pnt.v), &z );
 
-    out = (PJ *)_phpms_fetch_handle(pjout,
-                                    PHPMS_GLOBAL(le_projobj), list TSRMLS_CC);
-
-    if (in && out)
-    {
-        pnt.u = p1->value.dval;
-        pnt.v = p2->value.dval;
-
-        if( pj_is_latlong(in) )
-        {
-            pnt.u *= DEG_TO_RAD;
-            pnt.v *= DEG_TO_RAD;
-        }
-
-        error = pj_transform(in, out, 1, 0,
-                             &(pnt.u), &(pnt.v), &z );
-
-        if (!error)
-        {
-            if( pj_is_latlong(out) )
-            {
-                pnt.u *= RAD_TO_DEG;
-                pnt.v *= RAD_TO_DEG;
-            }
-        }
+    if (!error) {
+      if( pj_is_latlong(out) ) {
+        pnt.u *= RAD_TO_DEG;
+        pnt.v *= RAD_TO_DEG;
+      }
     }
+  }
 
-    if (error)
-    {
-        php_error(E_ERROR,"Error in pj_datum_transform");
+  if (error) {
+    php_error(E_ERROR,"Error in pj_datum_transform");
 
-        RETURN_LONG(-1);
-    }
-    else
-    {
-        add_assoc_double(return_value, "u", pnt.u);
-        add_assoc_double(return_value, "v", pnt.v);
-    }
+    RETURN_LONG(-1);
+  } else {
+    add_assoc_double(return_value, "u", pnt.u);
+    add_assoc_double(return_value, "v", pnt.v);
+  }
 }
 
 /************************************************************************/
@@ -677,29 +651,27 @@ DLEXPORT void php_proj_pj_datum_transform(INTERNAL_FUNCTION_PARAMETERS)
 DLEXPORT void php_proj_pj_free(INTERNAL_FUNCTION_PARAMETERS)
 {
 
-/* ==================================================================== */
-/*      TODO : freeing does not work properly on PHP4.                  */
-/* ==================================================================== */
+  /* ==================================================================== */
+  /*      TODO : freeing does not work properly on PHP4.                  */
+  /* ==================================================================== */
 #ifdef PHP4_BAD_FREEING
 
-    HashTable   *list=NULL;
-    pval        *pj = NULL;
-    PJ          *popj = NULL;
-/* -------------------------------------------------------------------- */
-/*      extract parameters.                                             */
-/* -------------------------------------------------------------------- */
-    if (getParameters(ht, 1, &pj) != SUCCESS)
-    {
-        WRONG_PARAM_COUNT;
-    }
-
-    popj = (PJ *)_phpms_fetch_handle(pj,
-                                     PHPMS_GLOBAL(le_projobj), list TSRMLS_CC);
+  HashTable   *list=NULL;
+  pval        *pj = NULL;
+  PJ          *popj = NULL;
+  /* -------------------------------------------------------------------- */
+  /*      extract parameters.                                             */
+  /* -------------------------------------------------------------------- */
+  if (getParameters(ht, 1, &pj) != SUCCESS) {
+    WRONG_PARAM_COUNT;
+  }
+
+  popj = (PJ *)_phpms_fetch_handle(pj,
+                                   PHPMS_GLOBAL(le_projobj), list TSRMLS_CC);
 
-    if (popj)
-    {
-        pj_free(popj);
-    }
+  if (popj) {
+    pj_free(popj);
+  }
 #endif
 }
 
diff --git a/mapscript/php/php_regex.c b/mapscript/php/php_regex.c
index 1b1ff0d..715a244 100644
--- a/mapscript/php/php_regex.c
+++ b/mapscript/php/php_regex.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -52,7 +52,7 @@
   doesn't #define away our ms_*/
 #define BUILDING_REGEX_PROXY 1
 
-#include "mapregex.h"
+#include "../../mapregex.h"
 
 /* regex_extra.h doesn't exist in PHP >=5.3 */
 #include "php.h"
@@ -83,8 +83,8 @@ MS_API_EXPORT(int) ms_regexec(const ms_regex_t *regex, const char *string, size_
 {
   /*This next line only works because we know that regmatch_t
     and ms_regmatch_t are exactly alike (POSIX STANDARD)*/
-  return regexec((const regex_t*)(regex->sys_regex), 
-                 string, nmatch, 
+  return regexec((const regex_t*)(regex->sys_regex),
+                 string, nmatch,
                  (regmatch_t*) pmatch, eflags);
 }
 
diff --git a/mapscript/php/point.c b/mapscript/php/point.c
index f0ceb38..4690915 100644
--- a/mapscript/php/point.c
+++ b/mapscript/php/point.c
@@ -2,7 +2,7 @@
  * $Id: php_mapscript.c 9765 2010-01-28 15:32:10Z aboudreault $
  *
  * Project:  MapServer
- * Purpose:  PHP/MapScript extension for MapServer.  External interface 
+ * Purpose:  PHP/MapScript extension for MapServer.  External interface
  *           functions
  * Author:   Daniel Morissette, DM Solutions Group (dmorissette at dmsolutions.ca)
  *           Alan Boudreault, Mapgears
@@ -16,16 +16,16 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
+ *
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  * DEALINGS IN THE SOFTWARE.
  **********************************************************************/
 
@@ -34,140 +34,137 @@
 zend_class_entry *mapscript_ce_point;
 
 ZEND_BEGIN_ARG_INFO_EX(point___get_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, property)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(point___set_args, 0, 0, 2)
-  ZEND_ARG_INFO(0, property)
-  ZEND_ARG_INFO(0, value)
+ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, value)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(point_setXY_args, 0, 0, 2)
-  ZEND_ARG_INFO(0, x)
-  ZEND_ARG_INFO(0, y)
-  ZEND_ARG_INFO(0, m)
+ZEND_ARG_INFO(0, x)
+ZEND_ARG_INFO(0, y)
+ZEND_ARG_INFO(0, m)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(point_setXYZ_args, 0, 0, 3)
-  ZEND_ARG_INFO(0, x)
-  ZEND_ARG_INFO(0, y)
-  ZEND_ARG_INFO(0, z)
-  ZEND_ARG_INFO(0, m)
+ZEND_ARG_INFO(0, x)
+ZEND_ARG_INFO(0, y)
+ZEND_ARG_INFO(0, z)
+ZEND_ARG_INFO(0, m)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(point_project_args, 0, 0, 2)
-  ZEND_ARG_OBJ_INFO(0, projIn, projectionObj, 0)
-  ZEND_ARG_OBJ_INFO(0, projOut, projectionObj, 0)
+ZEND_ARG_OBJ_INFO(0, projIn, projectionObj, 0)
+ZEND_ARG_OBJ_INFO(0, projOut, projectionObj, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(point_distanceToPoint_args, 0, 0, 1)
-  ZEND_ARG_OBJ_INFO(0, point, pointObj, 0)
+ZEND_ARG_OBJ_INFO(0, point, pointObj, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(point_distanceToLine_args, 0, 0, 2)
-  ZEND_ARG_OBJ_INFO(0, point, pointObj, 0)
-  ZEND_ARG_OBJ_INFO(0, point2, pointObj, 0)
+ZEND_ARG_OBJ_INFO(0, point, pointObj, 0)
+ZEND_ARG_OBJ_INFO(0, point2, pointObj, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(point_distanceToShape_args, 0, 0, 1)
-  ZEND_ARG_OBJ_INFO(0, shape, shapeObj, 0)
+ZEND_ARG_OBJ_INFO(0, shape, shapeObj, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(point_draw_args, 0, 0, 5)
-  ZEND_ARG_OBJ_INFO(0, map, mapObj, 0)
-  ZEND_ARG_OBJ_INFO(0, layer, layerObj, 0)
-  ZEND_ARG_OBJ_INFO(0, image, imageObj, 0)
-  ZEND_ARG_INFO(0, classIndex)
-  ZEND_ARG_INFO(0, text)
+ZEND_ARG_OBJ_INFO(0, map, mapObj, 0)
+ZEND_ARG_OBJ_INFO(0, layer, layerObj, 0)
+ZEND_ARG_OBJ_INFO(0, image, imageObj, 0)
+ZEND_ARG_INFO(0, classIndex)
+ZEND_ARG_INFO(0, text)
 ZEND_END_ARG_INFO()
 
 /* {{{ proto point __construct()
    Create a new pointObj instance. */
 PHP_METHOD(pointObj, __construct)
 {
-    php_point_object *php_point;
+  php_point_object *php_point;
 
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_point = (php_point_object *)zend_object_store_get_object(getThis() TSRMLS_CC);
 
-    php_point = (php_point_object *)zend_object_store_get_object(getThis() TSRMLS_CC);
-    
-    if ((php_point->point = pointObj_new()) == NULL)
-    {
-        mapscript_throw_exception("Unable to construct pointObj." TSRMLS_CC);
-        return;
-    }
+  if ((php_point->point = pointObj_new()) == NULL) {
+    mapscript_throw_exception("Unable to construct pointObj." TSRMLS_CC);
+    return;
+  }
 
-    php_point->point->x = 0;
-    php_point->point->y = 0;
+  php_point->point->x = 0;
+  php_point->point->y = 0;
 #ifdef USE_POINT_Z_M
-    php_point->point->z = 0;
-    php_point->point->m = 0;
+  php_point->point->z = 0;
+  php_point->point->m = 0;
 #endif
 }
 /* }}} */
 
 PHP_METHOD(pointObj, __get)
 {
-    char *property;
-    long property_len;
-    zval *zobj = getThis();
-    php_point_object *php_point;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &property, &property_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *zobj = getThis();
+  php_point_object *php_point;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &property, &property_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_point = (php_point_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    IF_GET_DOUBLE("x", php_point->point->x)
-    else IF_GET_DOUBLE("y", php_point->point->y) 
+  php_point = (php_point_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  IF_GET_DOUBLE("x", php_point->point->x)
+  else IF_GET_DOUBLE("y", php_point->point->y)
 #ifdef USE_POINT_Z_M
-    else IF_GET_DOUBLE("z", php_point->point->z) 
-    else IF_GET_DOUBLE("m", php_point->point->m) 
+    else IF_GET_DOUBLE("z", php_point->point->z)
+      else IF_GET_DOUBLE("m", php_point->point->m)
 #endif
-    else 
-    {
-        mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }
+        else {
+          mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+        }
 }
 
 PHP_METHOD(pointObj, __set)
 {
-    char *property;
-    long property_len;
-    zval *value;
-    zval *zobj = getThis();
-    php_point_object *php_point;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
-                              &property, &property_len, &value) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *value;
+  zval *zobj = getThis();
+  php_point_object *php_point;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
+                            &property, &property_len, &value) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_point = (php_point_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_point = (php_point_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    IF_SET_DOUBLE("x", php_point->point->x, value)
-    else IF_SET_DOUBLE("y", php_point->point->y, value)
+  IF_SET_DOUBLE("x", php_point->point->x, value)
+  else IF_SET_DOUBLE("y", php_point->point->y, value)
 #ifdef USE_POINT_Z_M
     else IF_SET_DOUBLE("z", php_point->point->z, value)
-    else IF_SET_DOUBLE("m", php_point->point->m, value)
+      else IF_SET_DOUBLE("m", php_point->point->m, value)
 #endif
-    else 
-    {
-        mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }
+        else {
+          mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+        }
 }
 
 /* {{{ proto int point.setXY(double x, double y, double m)
@@ -175,31 +172,30 @@ PHP_METHOD(pointObj, __set)
    Set new point. Returns MS_FAILURE on error. */
 PHP_METHOD(pointObj, setXY)
 {
-    double x, y, m;
-    zval *zobj = getThis();
-    php_point_object *php_point;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "dd|d",
-                              &x, &y, &m) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  double x, y, m;
+  zval *zobj = getThis();
+  php_point_object *php_point;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "dd|d",
+                            &x, &y, &m) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_point = (php_point_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    php_point->point->x = x;
-    php_point->point->y = y;
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_point = (php_point_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  php_point->point->x = x;
+  php_point->point->y = y;
 
 #ifdef USE_POINT_Z_M
-    if (ZEND_NUM_ARGS() == 3)
-    {
-            php_point->point->m = m;
-    }
+  if (ZEND_NUM_ARGS() == 3) {
+    php_point->point->m = m;
+  }
 #endif
 
-    RETURN_LONG(MS_SUCCESS);
+  RETURN_LONG(MS_SUCCESS);
 }
 /* }}} */
 
@@ -208,33 +204,32 @@ PHP_METHOD(pointObj, setXY)
    Set new point. Returns MS_FAILURE on error. */
 PHP_METHOD(pointObj, setXYZ)
 {
-    double x, y, z, m;
-    zval *zobj = getThis();
-    php_point_object *php_point;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ddd|d",
-                              &x, &y, &z, &m) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  double x, y, z, m;
+  zval *zobj = getThis();
+  php_point_object *php_point;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ddd|d",
+                            &x, &y, &z, &m) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_point = (php_point_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    php_point->point->x = x;
-    php_point->point->y = y;
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_point = (php_point_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  php_point->point->x = x;
+  php_point->point->y = y;
 
 #ifdef USE_POINT_Z_M
-    php_point->point->z = z;
+  php_point->point->z = z;
 
-    if (ZEND_NUM_ARGS() == 4)
-    {
-        php_point->point->m = m;
-    }
+  if (ZEND_NUM_ARGS() == 4) {
+    php_point->point->m = m;
+  }
 #endif
 
-    RETURN_LONG(MS_SUCCESS);
+  RETURN_LONG(MS_SUCCESS);
 }
 /* }}} */
 
@@ -243,32 +238,31 @@ PHP_METHOD(pointObj, setXYZ)
    Project the point. returns MS_SUCCESS/MS_FAILURE */
 PHP_METHOD(pointObj, project)
 {
-    zval *zobj_proj_in, *zobj_proj_out;
-    zval *zobj =  getThis();
-    php_point_object *php_point;
-    php_projection_object *php_proj_in, *php_proj_out;
-    int status = MS_FAILURE;
-    
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "OO",
-                              &zobj_proj_in, mapscript_ce_projection,
-                              &zobj_proj_out, mapscript_ce_projection) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj_proj_in, *zobj_proj_out;
+  zval *zobj =  getThis();
+  php_point_object *php_point;
+  php_projection_object *php_proj_in, *php_proj_out;
+  int status = MS_FAILURE;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "OO",
+                            &zobj_proj_in, mapscript_ce_projection,
+                            &zobj_proj_out, mapscript_ce_projection) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_point = (php_point_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_proj_in = (php_projection_object *) zend_object_store_get_object(zobj_proj_in TSRMLS_CC);
+  php_proj_out = (php_projection_object *) zend_object_store_get_object(zobj_proj_out TSRMLS_CC);
+
+  status = pointObj_project(php_point->point, php_proj_in->projection, php_proj_out->projection);
+  if (status != MS_SUCCESS) {
+    mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
+  }
 
-    php_point = (php_point_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_proj_in = (php_projection_object *) zend_object_store_get_object(zobj_proj_in TSRMLS_CC);
-    php_proj_out = (php_projection_object *) zend_object_store_get_object(zobj_proj_out TSRMLS_CC);
-    
-    status = pointObj_project(php_point->point, php_proj_in->projection, php_proj_out->projection);
-    if (status != MS_SUCCESS)
-    {
-        mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
-    }
-
-    RETURN_LONG(status);
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -276,25 +270,25 @@ PHP_METHOD(pointObj, project)
    Calculates distance between two points. */
 PHP_METHOD(pointObj, distanceToPoint)
 {
-    zval *zobj_point2;
-    zval *zobj =  getThis();
-    php_point_object *php_point, *php_point2;
-    double distance = -1;
-    
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
-                              &zobj_point2, mapscript_ce_point) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj_point2;
+  zval *zobj =  getThis();
+  php_point_object *php_point, *php_point2;
+  double distance = -1;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
+                            &zobj_point2, mapscript_ce_point) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_point = (php_point_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_point2 = (php_point_object *) zend_object_store_get_object(zobj_point2 TSRMLS_CC);
+  php_point = (php_point_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_point2 = (php_point_object *) zend_object_store_get_object(zobj_point2 TSRMLS_CC);
 
-    distance = pointObj_distanceToPoint(php_point->point, php_point2->point);
+  distance = pointObj_distanceToPoint(php_point->point, php_point2->point);
 
-    RETURN_DOUBLE(distance);
+  RETURN_DOUBLE(distance);
 }
 /* }}} */
 
@@ -303,27 +297,27 @@ PHP_METHOD(pointObj, distanceToPoint)
    two points passed in argument. */
 PHP_METHOD(pointObj, distanceToLine)
 {
-    zval *zobj =  getThis();
-    zval *zobj_line_point, *zobj_line_point2;
-    php_point_object *php_point, *php_line_point, *php_line_point2;
-    double distance = -1;
-    
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "OO",
-                              &zobj_line_point, mapscript_ce_point, 
-                              &zobj_line_point2, mapscript_ce_point) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj =  getThis();
+  zval *zobj_line_point, *zobj_line_point2;
+  php_point_object *php_point, *php_line_point, *php_line_point2;
+  double distance = -1;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "OO",
+                            &zobj_line_point, mapscript_ce_point,
+                            &zobj_line_point2, mapscript_ce_point) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_point = (php_point_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_line_point = (php_point_object *) zend_object_store_get_object(zobj_line_point TSRMLS_CC);
-    php_line_point2 = (php_point_object *) zend_object_store_get_object(zobj_line_point2 TSRMLS_CC);
+  php_point = (php_point_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_line_point = (php_point_object *) zend_object_store_get_object(zobj_line_point TSRMLS_CC);
+  php_line_point2 = (php_point_object *) zend_object_store_get_object(zobj_line_point2 TSRMLS_CC);
 
-    distance = pointObj_distanceToLine(php_point->point, php_line_point->point, php_line_point2->point);
+  distance = pointObj_distanceToLine(php_point->point, php_line_point->point, php_line_point2->point);
 
-    RETURN_DOUBLE(distance);
+  RETURN_DOUBLE(distance);
 }
 /* }}} */
 
@@ -331,26 +325,26 @@ PHP_METHOD(pointObj, distanceToLine)
    Calculates the minimum distance between a point and a shape. */
 PHP_METHOD(pointObj, distanceToShape)
 {
-    zval *zobj =  getThis();
-    zval *zshape;
-    php_point_object *php_point;
-    php_shape_object *php_shape;
-    double distance = -1;
-    
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
-                              &zshape, mapscript_ce_shape) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj =  getThis();
+  zval *zshape;
+  php_point_object *php_point;
+  php_shape_object *php_shape;
+  double distance = -1;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
+                            &zshape, mapscript_ce_shape) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_point = (php_point_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_shape = (php_shape_object *) zend_object_store_get_object(zshape TSRMLS_CC);
+  php_point = (php_point_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_shape = (php_shape_object *) zend_object_store_get_object(zshape TSRMLS_CC);
 
-    distance = pointObj_distanceToShape(php_point->point, php_shape->shape);
+  distance = pointObj_distanceToShape(php_point->point, php_shape->shape);
 
-    RETURN_DOUBLE(distance);
+  RETURN_DOUBLE(distance);
 }
 /* }}} */
 
@@ -358,114 +352,115 @@ PHP_METHOD(pointObj, distanceToShape)
    Draws the individual point using layer. Returns MS_SUCCESS/MS_FAILURE */
 PHP_METHOD(pointObj, draw)
 {
-    zval *zobj =  getThis();
-    zval *zmap, *zlayer, *zimage;
-    char *text;
-    long text_len;
-    long classIndex;
-    int status = MS_FAILURE;
-    php_point_object *php_point;
-    php_map_object *php_map;
-    php_layer_object *php_layer;
-    php_image_object *php_image;
-    
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "OOOls",
-                              &zmap, mapscript_ce_map,
-                              &zlayer, mapscript_ce_layer,
-                              &zimage, mapscript_ce_image,
-                              &classIndex, &text, &text_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj =  getThis();
+  zval *zmap, *zlayer, *zimage;
+  char *text;
+  long text_len;
+  long classIndex;
+  int status = MS_FAILURE;
+  php_point_object *php_point;
+  php_map_object *php_map;
+  php_layer_object *php_layer;
+  php_image_object *php_image;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "OOOls",
+                            &zmap, mapscript_ce_map,
+                            &zlayer, mapscript_ce_layer,
+                            &zimage, mapscript_ce_image,
+                            &classIndex, &text, &text_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-
-    php_point = (php_point_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_map = (php_map_object *) zend_object_store_get_object(zmap TSRMLS_CC);
-    php_layer = (php_layer_object *) zend_object_store_get_object(zlayer TSRMLS_CC);
-    php_image = (php_image_object *) zend_object_store_get_object(zimage TSRMLS_CC);
-
-    if ((status = pointObj_draw(php_point->point, php_map->map, php_layer->layer, php_image->image, 
-                                classIndex, text)) != MS_SUCCESS)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
-
-    RETURN_LONG(status);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_point = (php_point_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_map = (php_map_object *) zend_object_store_get_object(zmap TSRMLS_CC);
+  php_layer = (php_layer_object *) zend_object_store_get_object(zlayer TSRMLS_CC);
+  php_image = (php_image_object *) zend_object_store_get_object(zimage TSRMLS_CC);
+
+  if ((status = pointObj_draw(php_point->point, php_map->map, php_layer->layer, php_image->image,
+                              classIndex, text)) != MS_SUCCESS) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
 zend_function_entry point_functions[] = {
-    PHP_ME(pointObj, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
-    PHP_ME(pointObj, __get, point___get_args, ZEND_ACC_PUBLIC)
-    PHP_ME(pointObj, __set, point___set_args, ZEND_ACC_PUBLIC)
-    PHP_ME(pointObj, setXY, point_setXY_args, ZEND_ACC_PUBLIC)
-    PHP_ME(pointObj, setXYZ, point_setXYZ_args, ZEND_ACC_PUBLIC)
-    PHP_ME(pointObj, project, point_project_args, ZEND_ACC_PUBLIC)
-    PHP_ME(pointObj, distanceToPoint, point_distanceToPoint_args, ZEND_ACC_PUBLIC)
-    PHP_ME(pointObj, distanceToLine, point_distanceToLine_args, ZEND_ACC_PUBLIC)
-    PHP_ME(pointObj, distanceToShape, point_distanceToShape_args, ZEND_ACC_PUBLIC)
-    PHP_ME(pointObj, draw, point_draw_args, ZEND_ACC_PUBLIC)
-    {NULL, NULL, NULL}
+  PHP_ME(pointObj, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
+  PHP_ME(pointObj, __get, point___get_args, ZEND_ACC_PUBLIC)
+  PHP_ME(pointObj, __set, point___set_args, ZEND_ACC_PUBLIC)
+  PHP_ME(pointObj, setXY, point_setXY_args, ZEND_ACC_PUBLIC)
+  PHP_ME(pointObj, setXYZ, point_setXYZ_args, ZEND_ACC_PUBLIC)
+  PHP_ME(pointObj, project, point_project_args, ZEND_ACC_PUBLIC)
+  PHP_ME(pointObj, distanceToPoint, point_distanceToPoint_args, ZEND_ACC_PUBLIC)
+  PHP_ME(pointObj, distanceToLine, point_distanceToLine_args, ZEND_ACC_PUBLIC)
+  PHP_MALIAS(pointObj, distanceToSegment, distanceToLine, point_distanceToLine_args, ZEND_ACC_PUBLIC)
+  PHP_ME(pointObj, distanceToShape, point_distanceToShape_args, ZEND_ACC_PUBLIC)
+  PHP_ME(pointObj, draw, point_draw_args, ZEND_ACC_PUBLIC) {
+    NULL, NULL, NULL
+  }
 };
 
 
 void mapscript_create_point(pointObj *point, parent_object parent, zval *return_value TSRMLS_DC)
 {
-    php_point_object * php_point;
-    object_init_ex(return_value, mapscript_ce_point); 
-    php_point = (php_point_object *)zend_object_store_get_object(return_value TSRMLS_CC);
-    php_point->point = point;
-    
-    if (parent.val)
-        php_point->is_ref = 1;
-    
-    php_point->parent = parent;
-    MAPSCRIPT_ADDREF(parent.val);
+  php_point_object * php_point;
+  object_init_ex(return_value, mapscript_ce_point);
+  php_point = (php_point_object *)zend_object_store_get_object(return_value TSRMLS_CC);
+  php_point->point = point;
+
+  if (parent.val)
+    php_point->is_ref = 1;
+
+  php_point->parent = parent;
+  MAPSCRIPT_ADDREF(parent.val);
 }
 
 static void mapscript_point_object_destroy(void *object TSRMLS_DC)
 {
-    php_point_object *php_point = (php_point_object *)object;
+  php_point_object *php_point = (php_point_object *)object;
 
-    MAPSCRIPT_FREE_OBJECT(php_point);
+  MAPSCRIPT_FREE_OBJECT(php_point);
 
-    MAPSCRIPT_FREE_PARENT(php_point->parent);
+  MAPSCRIPT_FREE_PARENT(php_point->parent);
 
-    if (php_point->point && !php_point->is_ref) {
-        pointObj_destroy(php_point->point);
-    }
-    
-    efree(object);
+  if (php_point->point && !php_point->is_ref) {
+    pointObj_destroy(php_point->point);
+  }
+
+  efree(object);
 }
 
 static zend_object_value mapscript_point_object_new(zend_class_entry *ce TSRMLS_DC)
 {
-    zend_object_value retval;
-    php_point_object *php_point;
+  zend_object_value retval;
+  php_point_object *php_point;
 
-    MAPSCRIPT_ALLOC_OBJECT(php_point, php_point_object);
+  MAPSCRIPT_ALLOC_OBJECT(php_point, php_point_object);
 
-    retval = mapscript_object_new(&php_point->std, ce,
-                                  &mapscript_point_object_destroy TSRMLS_CC);
+  retval = mapscript_object_new(&php_point->std, ce,
+                                &mapscript_point_object_destroy TSRMLS_CC);
 
-    php_point->is_ref = 0;
-    MAPSCRIPT_INIT_PARENT(php_point->parent);
+  php_point->is_ref = 0;
+  MAPSCRIPT_INIT_PARENT(php_point->parent);
 
-    return retval;
+  return retval;
 }
 
 PHP_MINIT_FUNCTION(point)
 {
-    zend_class_entry ce;
+  zend_class_entry ce;
+
+  MAPSCRIPT_REGISTER_CLASS("pointObj",
+                           point_functions,
+                           mapscript_ce_point,
+                           mapscript_point_object_new);
 
-    MAPSCRIPT_REGISTER_CLASS("pointObj", 
-                             point_functions,
-                             mapscript_ce_point,
-                             mapscript_point_object_new);
+  mapscript_ce_point->ce_flags |= ZEND_ACC_FINAL_CLASS;
 
-    mapscript_ce_point->ce_flags |= ZEND_ACC_FINAL_CLASS; 
-    
-    return SUCCESS;
+  return SUCCESS;
 }
diff --git a/mapscript/php/projection.c b/mapscript/php/projection.c
index f20118c..961264a 100644
--- a/mapscript/php/projection.c
+++ b/mapscript/php/projection.c
@@ -2,7 +2,7 @@
  * $Id: php_mapscript.c 9765 2010-01-28 15:32:10Z aboudreault $
  *
  * Project:  MapServer
- * Purpose:  PHP/MapScript extension for MapServer.  External interface 
+ * Purpose:  PHP/MapScript extension for MapServer.  External interface
  *           functions
  * Author:   Daniel Morissette, DM Solutions Group (dmorissette at dmsolutions.ca)
  *           Alan Boudreault, Mapgears
@@ -16,49 +16,75 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
+ *
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  * DEALINGS IN THE SOFTWARE.
  **********************************************************************/
 
 #include "php_mapscript.h"
 
 zend_class_entry *mapscript_ce_projection;
+zend_object_handlers mapscript_projection_object_handlers;
 
 ZEND_BEGIN_ARG_INFO_EX(projection___construct_args, 0, 0, 1)
-	ZEND_ARG_INFO(0, projString)
+ZEND_ARG_INFO(0, projString)
+ZEND_END_ARG_INFO()
+
+ZEND_BEGIN_ARG_INFO_EX(projection_setWKTProjection_args, 0, 0, 1)
+ZEND_ARG_INFO(0, wkt)
 ZEND_END_ARG_INFO()
 
 /* {{{ proto projectionObj __construct(string projString)
    Create a new projectionObj instance. */
 PHP_METHOD(projectionObj, __construct)
 {
-    char *projString;
-    long projString_len;
-    php_projection_object *php_projection;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &projString, &projString_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *projString;
+  long projString_len;
+  php_projection_object *php_projection;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &projString, &projString_len) == FAILURE) {
+    PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_projection = (php_projection_object *)zend_object_store_get_object(getThis() TSRMLS_CC);
+
+  if ((php_projection->projection = projectionObj_new(projString)) == NULL) {
+    mapscript_throw_mapserver_exception("Unable to construct projectionObj." TSRMLS_CC);
+    return;
+  }
+}
+/* }}} */
+
+/* {{{ proto projectionObj setWKTProjection(string wkt)
+   Set the wkt projection. Return MS_SUCCESS or MS_FAILURE .*/
+PHP_METHOD(projectionObj, setWKTProjection)
+{
+  char *wkt;
+  long wkt_len;
+  php_projection_object *php_projection;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &wkt, &wkt_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_projection = (php_projection_object *)zend_object_store_get_object(getThis() TSRMLS_CC);
 
-    php_projection = (php_projection_object *)zend_object_store_get_object(getThis() TSRMLS_CC);
-    
-    if ((php_projection->projection = projectionObj_new(projString)) == NULL)
-    {
-        mapscript_throw_mapserver_exception("Unable to construct projectionObj." TSRMLS_CC);
-        return;
-    }
+  RETURN_LONG(msOGCWKT2ProjectionObj(wkt, php_projection->projection, MS_FALSE));
 }
 /* }}} */
 
@@ -66,82 +92,112 @@ PHP_METHOD(projectionObj, __construct)
    Returns the units of a projection object */
 PHP_METHOD(projectionObj, getUnits)
 {
-    php_projection_object *php_projection;
+  php_projection_object *php_projection;
 
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_projection = (php_projection_object *)zend_object_store_get_object(getThis() TSRMLS_CC);
+  php_projection = (php_projection_object *)zend_object_store_get_object(getThis() TSRMLS_CC);
 
-    RETURN_LONG(projectionObj_getUnits(php_projection->projection));
+  RETURN_LONG(projectionObj_getUnits(php_projection->projection));
 }
 /* }}} */
 
 zend_function_entry projection_functions[] = {
-    PHP_ME(projectionObj, __construct, projection___construct_args, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
-    PHP_ME(projectionObj, getUnits, NULL, ZEND_ACC_PUBLIC)
-    {NULL, NULL, NULL}
+  PHP_ME(projectionObj, __construct, projection___construct_args, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
+  PHP_ME(projectionObj, setWKTProjection, projection_setWKTProjection_args, ZEND_ACC_PUBLIC)
+  PHP_ME(projectionObj, getUnits, NULL, ZEND_ACC_PUBLIC) {
+    NULL, NULL, NULL
+  }
 };
 
 
 void mapscript_create_projection(projectionObj *projection, parent_object parent, zval *return_value TSRMLS_DC)
 {
-    php_projection_object * php_projection;
-    object_init_ex(return_value, mapscript_ce_projection); 
-    php_projection = (php_projection_object *)zend_object_store_get_object(return_value TSRMLS_CC);
-    php_projection->projection = projection;
+  php_projection_object * php_projection;
+  object_init_ex(return_value, mapscript_ce_projection);
+  php_projection = (php_projection_object *)zend_object_store_get_object(return_value TSRMLS_CC);
+  php_projection->projection = projection;
 
-    if (parent.val)
-        php_projection->is_ref = 1;
+  if (parent.val)
+    php_projection->is_ref = 1;
 
-    php_projection->parent = parent;
-    MAPSCRIPT_ADDREF(parent.val);
+  php_projection->parent = parent;
+  MAPSCRIPT_ADDREF(parent.val);
 }
 
 static void mapscript_projection_object_destroy(void *object TSRMLS_DC)
 {
-    php_projection_object *php_projection = (php_projection_object *)object;
+  php_projection_object *php_projection = (php_projection_object *)object;
+
+  MAPSCRIPT_FREE_OBJECT(php_projection);
+
+  MAPSCRIPT_FREE_PARENT(php_projection->parent);
 
-    MAPSCRIPT_FREE_OBJECT(php_projection);
-    
-    MAPSCRIPT_FREE_PARENT(php_projection->parent);
+  if (php_projection->projection && !php_projection->is_ref) {
+    projectionObj_destroy(php_projection->projection);
+  }
 
-    if (php_projection->projection && !php_projection->is_ref) {
-        projectionObj_destroy(php_projection->projection);
-    }
-    
-    efree(object);
+  efree(object);
+}
+
+static zend_object_value mapscript_projection_object_new_ex(zend_class_entry *ce, php_projection_object **ptr TSRMLS_DC)
+{
+  zend_object_value retval;
+  php_projection_object *php_projection;
+
+  MAPSCRIPT_ALLOC_OBJECT(php_projection, php_projection_object);
+
+  retval = mapscript_object_new_ex(&php_projection->std, ce,
+                                   &mapscript_projection_object_destroy,
+                                   &mapscript_projection_object_handlers TSRMLS_CC);
+
+  if (ptr)
+    *ptr = php_projection;
+
+  php_projection->is_ref = 0;
+  MAPSCRIPT_INIT_PARENT(php_projection->parent);
+
+  return retval;
 }
 
 static zend_object_value mapscript_projection_object_new(zend_class_entry *ce TSRMLS_DC)
 {
-    zend_object_value retval;
-    php_projection_object *php_projection;
+  return mapscript_projection_object_new_ex(ce, NULL TSRMLS_CC);
+}
+
+static zend_object_value mapscript_projection_object_clone(zval *zobj TSRMLS_DC)
+{
+  php_projection_object *php_projection_old, *php_projection_new;
+  zend_object_value new_ov;
+
+  php_projection_old = (php_projection_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    MAPSCRIPT_ALLOC_OBJECT(php_projection, php_projection_object);
+  new_ov = mapscript_projection_object_new_ex(mapscript_ce_projection, &php_projection_new TSRMLS_CC);
+  zend_objects_clone_members(&php_projection_new->std, new_ov, &php_projection_old->std, Z_OBJ_HANDLE_P(zobj) TSRMLS_CC);
 
-    retval = mapscript_object_new(&php_projection->std, ce,
-                                  &mapscript_projection_object_destroy TSRMLS_CC);
-    php_projection->is_ref = 0;
-    MAPSCRIPT_INIT_PARENT(php_projection->parent);
-    
-    return retval;
+  php_projection_new->projection = projectionObj_clone(php_projection_old->projection);
+
+  return new_ov;
 }
 
 PHP_MINIT_FUNCTION(projection)
 {
-    zend_class_entry ce;
+  zend_class_entry ce;
+
+  memcpy(&mapscript_projection_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
+  mapscript_projection_object_handlers.clone_obj = mapscript_projection_object_clone;
+
+  MAPSCRIPT_REGISTER_CLASS("projectionObj",
+                           projection_functions,
+                           mapscript_ce_projection,
+                           mapscript_projection_object_new);
 
-    MAPSCRIPT_REGISTER_CLASS("projectionObj", 
-                             projection_functions,
-                             mapscript_ce_projection,
-                             mapscript_projection_object_new);
+  mapscript_ce_projection->ce_flags |= ZEND_ACC_FINAL_CLASS;
 
-    mapscript_ce_projection->ce_flags |= ZEND_ACC_FINAL_CLASS; 
-    
-    return SUCCESS;
+  return SUCCESS;
 }
diff --git a/mapscript/php/querymap.c b/mapscript/php/querymap.c
index e460ee5..7f3d532 100644
--- a/mapscript/php/querymap.c
+++ b/mapscript/php/querymap.c
@@ -2,7 +2,7 @@
  * $Id: php_mapscript.c 9765 2010-01-28 15:32:10Z aboudreault $
  *
  * Project:  MapServer
- * Purpose:  PHP/MapScript extension for MapServer.  External interface 
+ * Purpose:  PHP/MapScript extension for MapServer.  External interface
  *           functions
  * Author:   Daniel Morissette, DM Solutions Group (dmorissette at dmsolutions.ca)
  *           Alan Boudreault, Mapgears
@@ -16,16 +16,16 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
+ *
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  * DEALINGS IN THE SOFTWARE.
  **********************************************************************/
 
@@ -34,113 +34,110 @@
 zend_class_entry *mapscript_ce_querymap;
 
 ZEND_BEGIN_ARG_INFO_EX(querymap___get_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, property)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(querymap___set_args, 0, 0, 2)
-  ZEND_ARG_INFO(0, property)
-  ZEND_ARG_INFO(0, value)
+ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, value)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(querymap_updateFromString_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, snippet)
+ZEND_ARG_INFO(0, snippet)
 ZEND_END_ARG_INFO()
 
 /* {{{ proto querymap __construct()
    queryMapObj CANNOT be instanciated, this will throw an exception on use */
 PHP_METHOD(queryMapObj, __construct)
 {
-    mapscript_throw_exception("queryMapObj cannot be constructed" TSRMLS_CC);
+  mapscript_throw_exception("queryMapObj cannot be constructed" TSRMLS_CC);
 }
 /* }}} */
 
 PHP_METHOD(queryMapObj, __get)
 {
-    char *property;
-    long property_len;
-    zval *zobj = getThis();
-    php_querymap_object *php_querymap;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &property, &property_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *zobj = getThis();
+  php_querymap_object *php_querymap;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &property, &property_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_querymap = (php_querymap_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    IF_GET_LONG("width", php_querymap->querymap->width)
-    else IF_GET_LONG("height", php_querymap->querymap->height)
+  php_querymap = (php_querymap_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  IF_GET_LONG("width", php_querymap->querymap->width)
+  else IF_GET_LONG("height", php_querymap->querymap->height)
     else IF_GET_LONG("style", php_querymap->querymap->style)
-    else IF_GET_OBJECT("color", mapscript_ce_color, php_querymap->color, &php_querymap->querymap->color)
-    else 
-    {
-        mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }
+      else IF_GET_LONG("status", php_querymap->querymap->status)
+        else IF_GET_OBJECT("color", mapscript_ce_color, php_querymap->color, &php_querymap->querymap->color)
+          else {
+            mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+          }
 }
 
 PHP_METHOD(queryMapObj, __set)
 {
-    char *property;
-    long property_len;
-    zval *value;
-    zval *zobj = getThis();
-    php_querymap_object *php_querymap;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
-                              &property, &property_len, &value) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *value;
+  zval *zobj = getThis();
+  php_querymap_object *php_querymap;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
+                            &property, &property_len, &value) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_querymap = (php_querymap_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_querymap = (php_querymap_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    IF_SET_LONG("width", php_querymap->querymap->width, value)
-    else IF_SET_LONG("height", php_querymap->querymap->height, value)
+  IF_SET_LONG("width", php_querymap->querymap->width, value)
+  else IF_SET_LONG("height", php_querymap->querymap->height, value)
     else IF_SET_LONG("style", php_querymap->querymap->style, value)
-    else if ( (STRING_EQUAL("color", property)))
-    {
-        mapscript_throw_exception("Property '%s' is an object and can only be modified through its accessors." TSRMLS_CC, property);
-    }
-    else 
-    {
-        mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }
+      else IF_SET_LONG("status", php_querymap->querymap->status, value)
+        else if ( (STRING_EQUAL("color", property))) {
+          mapscript_throw_exception("Property '%s' is an object and can only be modified through its accessors." TSRMLS_CC, property);
+        } else {
+          mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+        }
 }
 
 /* {{{ proto int querymap.updateFromString(string snippet)
    Update a querymap from a string snippet.  Returns MS_SUCCESS/MS_FAILURE */
 PHP_METHOD(queryMapObj, updateFromString)
 {
-    char *snippet;
-    long snippet_len;
-    zval *zobj = getThis();
-    php_querymap_object *php_querymap;
-    int status = MS_FAILURE;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &snippet, &snippet_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *snippet;
+  long snippet_len;
+  zval *zobj = getThis();
+  php_querymap_object *php_querymap;
+  int status = MS_FAILURE;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &snippet, &snippet_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_querymap = (php_querymap_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-
-    status =  queryMapObj_updateFromString(php_querymap->querymap, snippet);
-    
-    if (status != MS_SUCCESS)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
-
-    RETURN_LONG(status);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_querymap = (php_querymap_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  status =  queryMapObj_updateFromString(php_querymap->querymap, snippet);
+
+  if (status != MS_SUCCESS) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -148,84 +145,85 @@ PHP_METHOD(queryMapObj, updateFromString)
    Free the object */
 PHP_METHOD(queryMapObj, free)
 {
-    zval *zobj = getThis();
-    php_querymap_object *php_querymap;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  php_querymap_object *php_querymap;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_querymap = (php_querymap_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    MAPSCRIPT_DELREF(php_querymap->color);    
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_querymap = (php_querymap_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  MAPSCRIPT_DELREF(php_querymap->color);
 }
 /* }}} */
 
 zend_function_entry querymap_functions[] = {
-    PHP_ME(queryMapObj, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
-    PHP_ME(queryMapObj, __get, querymap___get_args, ZEND_ACC_PUBLIC)
-    PHP_ME(queryMapObj, __set, querymap___set_args, ZEND_ACC_PUBLIC)
-    PHP_MALIAS(queryMapObj, set, __set, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(queryMapObj, updateFromString, querymap_updateFromString_args, ZEND_ACC_PUBLIC)
-    PHP_ME(queryMapObj, free, NULL, ZEND_ACC_PUBLIC)
-    {NULL, NULL, NULL}
+  PHP_ME(queryMapObj, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
+  PHP_ME(queryMapObj, __get, querymap___get_args, ZEND_ACC_PUBLIC)
+  PHP_ME(queryMapObj, __set, querymap___set_args, ZEND_ACC_PUBLIC)
+  PHP_MALIAS(queryMapObj, set, __set, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(queryMapObj, updateFromString, querymap_updateFromString_args, ZEND_ACC_PUBLIC)
+  PHP_ME(queryMapObj, free, NULL, ZEND_ACC_PUBLIC) {
+    NULL, NULL, NULL
+  }
 };
 
 void mapscript_create_querymap(queryMapObj *querymap, parent_object parent, zval *return_value TSRMLS_DC)
 {
-    php_querymap_object * php_querymap;
-    object_init_ex(return_value, mapscript_ce_querymap); 
-    php_querymap = (php_querymap_object *)zend_object_store_get_object(return_value TSRMLS_CC);
-    php_querymap->querymap = querymap;
+  php_querymap_object * php_querymap;
+  object_init_ex(return_value, mapscript_ce_querymap);
+  php_querymap = (php_querymap_object *)zend_object_store_get_object(return_value TSRMLS_CC);
+  php_querymap->querymap = querymap;
 
-    php_querymap->parent = parent;
-    MAPSCRIPT_ADDREF(parent.val);
+  php_querymap->parent = parent;
+  MAPSCRIPT_ADDREF(parent.val);
 
 }
 
 static void mapscript_querymap_object_destroy(void *object TSRMLS_DC)
 {
-    php_querymap_object *php_querymap = (php_querymap_object *)object;
+  php_querymap_object *php_querymap = (php_querymap_object *)object;
+
+  MAPSCRIPT_FREE_OBJECT(php_querymap);
 
-    MAPSCRIPT_FREE_OBJECT(php_querymap);
+  MAPSCRIPT_FREE_PARENT(php_querymap->parent);
+  MAPSCRIPT_DELREF(php_querymap->color);
 
-    MAPSCRIPT_FREE_PARENT(php_querymap->parent);
-    MAPSCRIPT_DELREF(php_querymap->color);
+  /* We don't need to free the queryMapObj */
 
-    /* We don't need to free the queryMapObj */ 
-    
-    efree(object);
+  efree(object);
 }
 
 static zend_object_value mapscript_querymap_object_new(zend_class_entry *ce TSRMLS_DC)
 {
-    zend_object_value retval;
-    php_querymap_object *php_querymap;
+  zend_object_value retval;
+  php_querymap_object *php_querymap;
 
-    MAPSCRIPT_ALLOC_OBJECT(php_querymap, php_querymap_object);
+  MAPSCRIPT_ALLOC_OBJECT(php_querymap, php_querymap_object);
 
-    retval = mapscript_object_new(&php_querymap->std, ce,
-                                  &mapscript_querymap_object_destroy TSRMLS_CC);
+  retval = mapscript_object_new(&php_querymap->std, ce,
+                                &mapscript_querymap_object_destroy TSRMLS_CC);
 
-    MAPSCRIPT_INIT_PARENT(php_querymap->parent);
-    php_querymap->color = NULL;
+  MAPSCRIPT_INIT_PARENT(php_querymap->parent);
+  php_querymap->color = NULL;
 
-    return retval;
+  return retval;
 }
 
 PHP_MINIT_FUNCTION(querymap)
 {
-    zend_class_entry ce;
+  zend_class_entry ce;
+
+  MAPSCRIPT_REGISTER_CLASS("queryMapObj",
+                           querymap_functions,
+                           mapscript_ce_querymap,
+                           mapscript_querymap_object_new);
 
-    MAPSCRIPT_REGISTER_CLASS("queryMapObj", 
-                             querymap_functions,
-                             mapscript_ce_querymap,
-                             mapscript_querymap_object_new);
+  mapscript_ce_querymap->ce_flags |= ZEND_ACC_FINAL_CLASS;
 
-    mapscript_ce_querymap->ce_flags |= ZEND_ACC_FINAL_CLASS; 
-    
-    return SUCCESS;
+  return SUCCESS;
 }
diff --git a/mapscript/php/rect.c b/mapscript/php/rect.c
index 591716d..2274ac3 100644
--- a/mapscript/php/rect.c
+++ b/mapscript/php/rect.c
@@ -2,7 +2,7 @@
  * $Id: php_mapscript.c 9765 2010-01-28 15:32:10Z aboudreault $
  *
  * Project:  MapServer
- * Purpose:  PHP/MapScript extension for MapServer.  External interface 
+ * Purpose:  PHP/MapScript extension for MapServer.  External interface
  *           functions
  * Author:   Daniel Morissette, DM Solutions Group (dmorissette at dmsolutions.ca)
  *           Alan Boudreault, Mapgears
@@ -16,16 +16,16 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
+ *
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  * DEALINGS IN THE SOFTWARE.
  **********************************************************************/
 
@@ -34,189 +34,184 @@
 zend_class_entry *mapscript_ce_rect;
 
 ZEND_BEGIN_ARG_INFO_EX(rect___get_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, property)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(rect___set_args, 0, 0, 2)
-  ZEND_ARG_INFO(0, property)
-  ZEND_ARG_INFO(0, value)
+ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, value)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(rect_draw_args, 0, 0, 5)
-  ZEND_ARG_OBJ_INFO(0, map, mapObj, 0)
-  ZEND_ARG_OBJ_INFO(0, layer, layerObj, 0)
-  ZEND_ARG_OBJ_INFO(0, image, imageObj, 0)
-  ZEND_ARG_INFO(0, classIndex)
-  ZEND_ARG_INFO(0, text)
+ZEND_ARG_OBJ_INFO(0, map, mapObj, 0)
+ZEND_ARG_OBJ_INFO(0, layer, layerObj, 0)
+ZEND_ARG_OBJ_INFO(0, image, imageObj, 0)
+ZEND_ARG_INFO(0, classIndex)
+ZEND_ARG_INFO(0, text)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(rect_project_args, 0, 0, 2)
-  ZEND_ARG_OBJ_INFO(0, projIn, projectionObj, 0)
-  ZEND_ARG_OBJ_INFO(0, projOut, projectionObj, 0)
+ZEND_ARG_OBJ_INFO(0, projIn, projectionObj, 0)
+ZEND_ARG_OBJ_INFO(0, projOut, projectionObj, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(rect_setExtent_args, 0, 0, 4)
-  ZEND_ARG_INFO(0, minx)
-  ZEND_ARG_INFO(0, miny)
-  ZEND_ARG_INFO(0, maxx)
-  ZEND_ARG_INFO(0, maxy)
+ZEND_ARG_INFO(0, minx)
+ZEND_ARG_INFO(0, miny)
+ZEND_ARG_INFO(0, maxx)
+ZEND_ARG_INFO(0, maxy)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(rect_fit_args, 0, 0, 2)
-  ZEND_ARG_INFO(0, width)
-  ZEND_ARG_INFO(0, height)
+ZEND_ARG_INFO(0, width)
+ZEND_ARG_INFO(0, height)
 ZEND_END_ARG_INFO()
 
 /* {{{ proto rect __construct()
    Create a new rectObj instance. */
 PHP_METHOD(rectObj, __construct)
 {
-    php_rect_object *php_rect;
+  php_rect_object *php_rect;
 
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_rect = (php_rect_object *)zend_object_store_get_object(getThis() TSRMLS_CC);
 
-    php_rect = (php_rect_object *)zend_object_store_get_object(getThis() TSRMLS_CC);
-    
-    if ((php_rect->rect = rectObj_new()) == NULL)
-    {
-        mapscript_throw_exception("Unable to construct rectObj." TSRMLS_CC);
-        return;
-    }
+  if ((php_rect->rect = rectObj_new()) == NULL) {
+    mapscript_throw_exception("Unable to construct rectObj." TSRMLS_CC);
+    return;
+  }
 }
 /* }}} */
 
 PHP_METHOD(rectObj, __get)
 {
-    char *property;
-    long property_len;
-    zval *zobj = getThis();
-    php_rect_object *php_rect;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &property, &property_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *zobj = getThis();
+  php_rect_object *php_rect;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &property, &property_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_rect = (php_rect_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-
-    IF_GET_DOUBLE("minx", php_rect->rect->minx)
-    else IF_GET_DOUBLE("miny", php_rect->rect->miny) 
-    else IF_GET_DOUBLE("maxx", php_rect->rect->maxx) 
-    else IF_GET_DOUBLE("maxy", php_rect->rect->maxy) 
-    else 
-    {
-        mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_rect = (php_rect_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  IF_GET_DOUBLE("minx", php_rect->rect->minx)
+  else IF_GET_DOUBLE("miny", php_rect->rect->miny)
+    else IF_GET_DOUBLE("maxx", php_rect->rect->maxx)
+      else IF_GET_DOUBLE("maxy", php_rect->rect->maxy)
+        else {
+          mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+        }
 }
 
 /* {{{ proto int draw(mapObj map, layerObj layer, imageObj img, string class_name, string text)
    Draws the individual rect using layer. Returns MS_SUCCESS/MS_FAILURE. */
 PHP_METHOD(rectObj, draw)
 {
-    zval *zobj =  getThis();
-    zval *zmap, *zlayer, *zimage;
-    char *text;
-    long text_len;
-    long classIndex;
-    int status = MS_FAILURE;
-    php_rect_object *php_rect;
-    php_map_object *php_map;
-    php_layer_object *php_layer;
-    php_image_object *php_image;
-    
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "OOOls",
-                              &zmap, mapscript_ce_map,
-                              &zlayer, mapscript_ce_layer,
-                              &zimage, mapscript_ce_image,
-                              &classIndex, &text, &text_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj =  getThis();
+  zval *zmap, *zlayer, *zimage;
+  char *text;
+  long text_len;
+  long classIndex;
+  int status = MS_FAILURE;
+  php_rect_object *php_rect;
+  php_map_object *php_map;
+  php_layer_object *php_layer;
+  php_image_object *php_image;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "OOOls",
+                            &zmap, mapscript_ce_map,
+                            &zlayer, mapscript_ce_layer,
+                            &zimage, mapscript_ce_image,
+                            &classIndex, &text, &text_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-
-    php_rect = (php_rect_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_map = (php_map_object *) zend_object_store_get_object(zmap TSRMLS_CC);
-    php_layer = (php_layer_object *) zend_object_store_get_object(zlayer TSRMLS_CC);
-    php_image = (php_image_object *) zend_object_store_get_object(zimage TSRMLS_CC);
-
-    if ((status = rectObj_draw(php_rect->rect, php_map->map, php_layer->layer, php_image->image, 
-                               classIndex, text)) != MS_SUCCESS)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
-
-    RETURN_LONG(status);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_rect = (php_rect_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_map = (php_map_object *) zend_object_store_get_object(zmap TSRMLS_CC);
+  php_layer = (php_layer_object *) zend_object_store_get_object(zlayer TSRMLS_CC);
+  php_image = (php_image_object *) zend_object_store_get_object(zimage TSRMLS_CC);
+
+  if ((status = rectObj_draw(php_rect->rect, php_map->map, php_layer->layer, php_image->image,
+                             classIndex, text)) != MS_SUCCESS) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
 PHP_METHOD(rectObj, __set)
 {
-    char *property;
-    long property_len;
-    zval *value;
-    zval *zobj = getThis();
-    php_rect_object *php_rect;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
-                              &property, &property_len, &value) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *value;
+  zval *zobj = getThis();
+  php_rect_object *php_rect;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
+                            &property, &property_len, &value) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_rect = (php_rect_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-
-    IF_SET_DOUBLE("minx", php_rect->rect->minx, value)
-    else IF_SET_DOUBLE("miny", php_rect->rect->miny, value) 
-    else IF_SET_DOUBLE("maxx", php_rect->rect->maxx, value) 
-    else IF_SET_DOUBLE("maxy", php_rect->rect->maxy, value) 
-    else 
-    {
-        mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_rect = (php_rect_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  IF_SET_DOUBLE("minx", php_rect->rect->minx, value)
+  else IF_SET_DOUBLE("miny", php_rect->rect->miny, value)
+    else IF_SET_DOUBLE("maxx", php_rect->rect->maxx, value)
+      else IF_SET_DOUBLE("maxy", php_rect->rect->maxy, value)
+        else {
+          mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+        }
 }
 
 /* {{{ proto int rect.project(projectionObj in, projectionObj out)
    Project a Rect object Returns MS_SUCCESS/MS_FAILURE */
 PHP_METHOD(rectObj, project)
 {
-    zval *zobj_proj_in, *zobj_proj_out;
-    zval *zobj =  getThis();
-    php_rect_object *php_rect;
-    php_projection_object *php_proj_in, *php_proj_out;
-    int status = MS_FAILURE;
-    
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "OO",
-                              &zobj_proj_in, mapscript_ce_projection,
-                              &zobj_proj_out, mapscript_ce_projection) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj_proj_in, *zobj_proj_out;
+  zval *zobj =  getThis();
+  php_rect_object *php_rect;
+  php_projection_object *php_proj_in, *php_proj_out;
+  int status = MS_FAILURE;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "OO",
+                            &zobj_proj_in, mapscript_ce_projection,
+                            &zobj_proj_out, mapscript_ce_projection) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_rect = (php_rect_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_proj_in = (php_projection_object *) zend_object_store_get_object(zobj_proj_in TSRMLS_CC);
-    php_proj_out = (php_projection_object *) zend_object_store_get_object(zobj_proj_out TSRMLS_CC);
-    
-    status = rectObj_project(php_rect->rect, php_proj_in->projection, php_proj_out->projection);
-    if (status != MS_SUCCESS)
-    {
-        mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
-    }
-
-    RETURN_LONG(status);
+  php_rect = (php_rect_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_proj_in = (php_projection_object *) zend_object_store_get_object(zobj_proj_in TSRMLS_CC);
+  php_proj_out = (php_projection_object *) zend_object_store_get_object(zobj_proj_out TSRMLS_CC);
+
+  status = rectObj_project(php_rect->rect, php_proj_in->projection, php_proj_out->projection);
+  if (status != MS_SUCCESS) {
+    mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
+  }
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -224,26 +219,26 @@ PHP_METHOD(rectObj, project)
    Set object property using four values. */
 PHP_METHOD(rectObj, setExtent)
 {
-    zval *zobj =  getThis();
-    double minx, miny, maxx, maxy;
-    php_rect_object *php_rect;
-    
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "dddd",
-                              &minx, &miny, &maxx, &maxy) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj =  getThis();
+  double minx, miny, maxx, maxy;
+  php_rect_object *php_rect;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "dddd",
+                            &minx, &miny, &maxx, &maxy) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_rect = (php_rect_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_rect = (php_rect_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    php_rect->rect->minx = minx;
-    php_rect->rect->miny = miny;
-    php_rect->rect->maxx = maxx;
-    php_rect->rect->maxy = maxy;
+  php_rect->rect->minx = minx;
+  php_rect->rect->miny = miny;
+  php_rect->rect->maxx = maxx;
+  php_rect->rect->maxy = maxy;
 
-    RETURN_LONG(MS_SUCCESS);
+  RETURN_LONG(MS_SUCCESS);
 }
 /* }}} */
 
@@ -251,95 +246,129 @@ PHP_METHOD(rectObj, setExtent)
    Adjust extents of the rectangle to fit the width/height specified. */
 PHP_METHOD(rectObj, fit)
 {
-    zval *zobj =  getThis();
-    long width, height;
-    double retval=0.0;
-    php_rect_object *php_rect;
-    
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ll",
-                              &width, &height) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj =  getThis();
+  long width, height;
+  double retval=0.0;
+  php_rect_object *php_rect;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ll",
+                            &width, &height) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_rect = (php_rect_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_rect = (php_rect_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    retval = rectObj_fit(php_rect->rect, width, height);
+  retval = rectObj_fit(php_rect->rect, width, height);
 
-    RETURN_DOUBLE(retval);
+  RETURN_DOUBLE(retval);
+}
+/* }}} */
+
+/* {{{ proto rect getCenter()
+   Get center point of the extent. */
+PHP_METHOD(rectObj, getCenter)
+{
+  php_rect_object *php_rect;
+  pointObj *center;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
+    PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_rect = (php_rect_object *)zend_object_store_get_object(getThis() TSRMLS_CC);
+
+  center = (pointObj *)calloc(1, sizeof(pointObj));
+  if (!center) {
+    mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
+    RETURN_NULL();
+  }
+
+  center->x = (php_rect->rect->minx + php_rect->rect->maxx)/2;
+  center->y = (php_rect->rect->miny + php_rect->rect->maxy)/2;
+
+  /* Return result object */
+  MAPSCRIPT_MAKE_PARENT(NULL, NULL);
+  mapscript_create_point(center, parent, return_value TSRMLS_CC);
 }
 /* }}} */
 
 zend_function_entry rect_functions[] = {
-    PHP_ME(rectObj, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
-    PHP_ME(rectObj, __get, rect___get_args, ZEND_ACC_PUBLIC)
-    PHP_ME(rectObj, __set, rect___set_args, ZEND_ACC_PUBLIC)
-    PHP_MALIAS(rectObj, set, __set, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(rectObj, draw, rect_draw_args, ZEND_ACC_PUBLIC)
-    PHP_ME(rectObj, project, rect_project_args, ZEND_ACC_PUBLIC)
-    PHP_ME(rectObj, setExtent, rect_setExtent_args, ZEND_ACC_PUBLIC)
-    PHP_ME(rectObj, fit, rect_fit_args, ZEND_ACC_PUBLIC)
-    {NULL, NULL, NULL}
+  PHP_ME(rectObj, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
+  PHP_ME(rectObj, getCenter, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(rectObj, __get, rect___get_args, ZEND_ACC_PUBLIC)
+  PHP_ME(rectObj, __set, rect___set_args, ZEND_ACC_PUBLIC)
+  PHP_MALIAS(rectObj, set, __set, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(rectObj, draw, rect_draw_args, ZEND_ACC_PUBLIC)
+  PHP_ME(rectObj, project, rect_project_args, ZEND_ACC_PUBLIC)
+  PHP_ME(rectObj, setExtent, rect_setExtent_args, ZEND_ACC_PUBLIC)
+  PHP_ME(rectObj, fit, rect_fit_args, ZEND_ACC_PUBLIC) {
+    NULL, NULL, NULL
+  }
 };
 
 
 void mapscript_create_rect(rectObj *rect, parent_object parent, zval *return_value TSRMLS_DC)
 {
-    php_rect_object * php_rect;
-    object_init_ex(return_value, mapscript_ce_rect); 
-    php_rect = (php_rect_object *)zend_object_store_get_object(return_value TSRMLS_CC);
-    php_rect->rect = rect;
+  php_rect_object * php_rect;
+  object_init_ex(return_value, mapscript_ce_rect);
+  php_rect = (php_rect_object *)zend_object_store_get_object(return_value TSRMLS_CC);
+  php_rect->rect = rect;
 
-    if (parent.val) 
-        php_rect->is_ref = 1;
+  if (parent.val)
+    php_rect->is_ref = 1;
 
-    php_rect->parent = parent;
-    MAPSCRIPT_ADDREF(parent.val);
+  php_rect->parent = parent;
+  MAPSCRIPT_ADDREF(parent.val);
 }
 
 static void mapscript_rect_object_destroy(void *object TSRMLS_DC)
 {
-    php_rect_object *php_rect = (php_rect_object *)object;
+  php_rect_object *php_rect = (php_rect_object *)object;
 
-    MAPSCRIPT_FREE_OBJECT(php_rect);
+  MAPSCRIPT_FREE_OBJECT(php_rect);
 
-    MAPSCRIPT_FREE_PARENT(php_rect->parent);
+  MAPSCRIPT_FREE_PARENT(php_rect->parent);
 
-    if (php_rect->rect && !php_rect->is_ref) {
-        rectObj_destroy(php_rect->rect);  
-    }
-    
-    efree(object);
+  if (php_rect->rect && !php_rect->is_ref) {
+    rectObj_destroy(php_rect->rect);
+  }
+
+  efree(object);
 }
 
 static zend_object_value mapscript_rect_object_new(zend_class_entry *ce TSRMLS_DC)
 {
-    zend_object_value retval;
-    php_rect_object *php_rect;
+  zend_object_value retval;
+  php_rect_object *php_rect;
 
-    MAPSCRIPT_ALLOC_OBJECT(php_rect, php_rect_object);
+  MAPSCRIPT_ALLOC_OBJECT(php_rect, php_rect_object);
 
-    retval = mapscript_object_new(&php_rect->std, ce,
-                                  &mapscript_rect_object_destroy TSRMLS_CC);
+  retval = mapscript_object_new(&php_rect->std, ce,
+                                &mapscript_rect_object_destroy TSRMLS_CC);
 
-    php_rect->is_ref = 0;
-    MAPSCRIPT_INIT_PARENT(php_rect->parent)
+  php_rect->is_ref = 0;
+  MAPSCRIPT_INIT_PARENT(php_rect->parent)
 
-    return retval;
+  return retval;
 }
 
 PHP_MINIT_FUNCTION(rect)
 {
-    zend_class_entry ce;
+  zend_class_entry ce;
+
+  MAPSCRIPT_REGISTER_CLASS("rectObj",
+                           rect_functions,
+                           mapscript_ce_rect,
+                           mapscript_rect_object_new);
 
-    MAPSCRIPT_REGISTER_CLASS("rectObj", 
-                             rect_functions,
-                             mapscript_ce_rect,
-                             mapscript_rect_object_new);
+  mapscript_ce_rect->ce_flags |= ZEND_ACC_FINAL_CLASS;
 
-    mapscript_ce_rect->ce_flags |= ZEND_ACC_FINAL_CLASS; 
-    
-    return SUCCESS;
+  return SUCCESS;
 }
diff --git a/mapscript/php/referencemap.c b/mapscript/php/referencemap.c
index 61a8a70..22958e3 100644
--- a/mapscript/php/referencemap.c
+++ b/mapscript/php/referencemap.c
@@ -2,7 +2,7 @@
  * $Id: php_mapscript.c 9765 2010-01-28 15:32:10Z aboudreault $
  *
  * Project:  MapServer
- * Purpose:  PHP/MapScript extension for MapServer.  External interface 
+ * Purpose:  PHP/MapScript extension for MapServer.  External interface
  *           functions
  * Author:   Daniel Morissette, DM Solutions Group (dmorissette at dmsolutions.ca)
  *           Alan Boudreault, Mapgears
@@ -16,16 +16,16 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
+ *
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  * DEALINGS IN THE SOFTWARE.
  **********************************************************************/
 
@@ -34,129 +34,124 @@
 zend_class_entry *mapscript_ce_referencemap;
 
 ZEND_BEGIN_ARG_INFO_EX(referenceMap___get_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, property)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(referenceMap___set_args, 0, 0, 2)
-  ZEND_ARG_INFO(0, property)
-  ZEND_ARG_INFO(0, value)
+ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, value)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(referenceMap_updateFromString_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, snippet)
+ZEND_ARG_INFO(0, snippet)
 ZEND_END_ARG_INFO()
 
 /* {{{ proto referenceMapObj __construct()
    referenceMapObj CANNOT be instanciated, this will throw an exception on use */
 PHP_METHOD(referenceMapObj, __construct)
 {
-    mapscript_throw_exception("referenceMapObj cannot be constructed" TSRMLS_CC);
+  mapscript_throw_exception("referenceMapObj cannot be constructed" TSRMLS_CC);
 }
 /* }}} */
 
 PHP_METHOD(referenceMapObj, __get)
 {
-    char *property;
-    long property_len;
-    zval *zobj = getThis();
-    php_referencemap_object *php_referencemap;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &property, &property_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *zobj = getThis();
+  php_referencemap_object *php_referencemap;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &property, &property_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_referencemap = (php_referencemap_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_referencemap = (php_referencemap_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    IF_GET_STRING("image", php_referencemap->referencemap->image)
-    else IF_GET_LONG("width", php_referencemap->referencemap->width)
+  IF_GET_STRING("image", php_referencemap->referencemap->image)
+  else IF_GET_LONG("width", php_referencemap->referencemap->width)
     else IF_GET_LONG("height", php_referencemap->referencemap->height)
-    else IF_GET_LONG("status", php_referencemap->referencemap->status)
-    else IF_GET_LONG("marker", php_referencemap->referencemap->marker)
-    else IF_GET_STRING("markername", php_referencemap->referencemap->markername)
-    else IF_GET_LONG("markersize", php_referencemap->referencemap->markersize)
-    else IF_GET_LONG("maxboxsize", php_referencemap->referencemap->maxboxsize)
-    else IF_GET_LONG("minboxsize", php_referencemap->referencemap->minboxsize)
-    else IF_GET_OBJECT("extent", mapscript_ce_rect, php_referencemap->extent, &php_referencemap->referencemap->extent)
-    else IF_GET_OBJECT("color", mapscript_ce_color, php_referencemap->color, &php_referencemap->referencemap->color)
-    else IF_GET_OBJECT("outlinecolor", mapscript_ce_color, php_referencemap->outlinecolor, &php_referencemap->referencemap->outlinecolor)
-    else 
-    {
-        mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }
+      else IF_GET_LONG("status", php_referencemap->referencemap->status)
+        else IF_GET_LONG("marker", php_referencemap->referencemap->marker)
+          else IF_GET_STRING("markername", php_referencemap->referencemap->markername)
+            else IF_GET_LONG("markersize", php_referencemap->referencemap->markersize)
+              else IF_GET_LONG("maxboxsize", php_referencemap->referencemap->maxboxsize)
+                else IF_GET_LONG("minboxsize", php_referencemap->referencemap->minboxsize)
+                  else IF_GET_OBJECT("extent", mapscript_ce_rect, php_referencemap->extent, &php_referencemap->referencemap->extent)
+                    else IF_GET_OBJECT("color", mapscript_ce_color, php_referencemap->color, &php_referencemap->referencemap->color)
+                      else IF_GET_OBJECT("outlinecolor", mapscript_ce_color, php_referencemap->outlinecolor, &php_referencemap->referencemap->outlinecolor)
+                        else {
+                          mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+                        }
 }
 
 PHP_METHOD(referenceMapObj, __set)
 {
-    char *property;
-    long property_len;
-    zval *value;
-    zval *zobj = getThis();
-    php_referencemap_object *php_referencemap;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
-                              &property, &property_len, &value) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *value;
+  zval *zobj = getThis();
+  php_referencemap_object *php_referencemap;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
+                            &property, &property_len, &value) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_referencemap = (php_referencemap_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    IF_SET_STRING("image", php_referencemap->referencemap->image, value)
-    else IF_SET_LONG("width", php_referencemap->referencemap->width, value)
+  php_referencemap = (php_referencemap_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  IF_SET_STRING("image", php_referencemap->referencemap->image, value)
+  else IF_SET_LONG("width", php_referencemap->referencemap->width, value)
     else IF_SET_LONG("height", php_referencemap->referencemap->height, value)
-    else IF_SET_LONG("status", php_referencemap->referencemap->status, value)
-    else IF_SET_LONG("marker", php_referencemap->referencemap->marker, value)
-    else IF_SET_STRING("markername", php_referencemap->referencemap->markername, value)
-    else IF_SET_LONG("markersize", php_referencemap->referencemap->markersize, value)
-    else IF_SET_LONG("maxboxsize", php_referencemap->referencemap->maxboxsize, value)
-    else IF_SET_LONG("minboxsize", php_referencemap->referencemap->minboxsize, value)
-    else if ( (STRING_EQUAL("extent", property)) ||
-              (STRING_EQUAL("color", property)) ||
-              (STRING_EQUAL("outlinecolor", property)))
-    {
-        mapscript_throw_exception("Property '%s' is an object and can only be modified through its accessors." TSRMLS_CC, property);
-    }
-    else 
-    {
-        mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }
+      else IF_SET_LONG("status", php_referencemap->referencemap->status, value)
+        else IF_SET_LONG("marker", php_referencemap->referencemap->marker, value)
+          else IF_SET_STRING("markername", php_referencemap->referencemap->markername, value)
+            else IF_SET_LONG("markersize", php_referencemap->referencemap->markersize, value)
+              else IF_SET_LONG("maxboxsize", php_referencemap->referencemap->maxboxsize, value)
+                else IF_SET_LONG("minboxsize", php_referencemap->referencemap->minboxsize, value)
+                  else if ( (STRING_EQUAL("extent", property)) ||
+                            (STRING_EQUAL("color", property)) ||
+                            (STRING_EQUAL("outlinecolor", property))) {
+                    mapscript_throw_exception("Property '%s' is an object and can only be modified through its accessors." TSRMLS_CC, property);
+                  } else {
+                    mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+                  }
 }
 
 /* {{{ proto int referencemap.updateFromString(string snippet)
    Update a referencemap from a string snippet.  Returns MS_SUCCESS/MS_FAILURE */
 PHP_METHOD(referenceMapObj, updateFromString)
 {
-    char *snippet;
-    long snippet_len;
-    zval *zobj = getThis();
-    php_referencemap_object *php_referencemap;
-    int status = MS_FAILURE;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &snippet, &snippet_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *snippet;
+  long snippet_len;
+  zval *zobj = getThis();
+  php_referencemap_object *php_referencemap;
+  int status = MS_FAILURE;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &snippet, &snippet_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_referencemap = (php_referencemap_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-
-    status =  referenceMapObj_updateFromString(php_referencemap->referencemap, snippet);
-    
-    if (status != MS_SUCCESS)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
-    
-    RETURN_LONG(status);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_referencemap = (php_referencemap_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  status =  referenceMapObj_updateFromString(php_referencemap->referencemap, snippet);
+
+  if (status != MS_SUCCESS) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -164,89 +159,90 @@ PHP_METHOD(referenceMapObj, updateFromString)
    Free the object. */
 PHP_METHOD(referenceMapObj, free)
 {
-    zval *zobj = getThis();
-    php_referencemap_object *php_referencemap;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  php_referencemap_object *php_referencemap;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_referencemap = (php_referencemap_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    MAPSCRIPT_DELREF(php_referencemap->extent);
-    MAPSCRIPT_DELREF(php_referencemap->color);
-    MAPSCRIPT_DELREF(php_referencemap->outlinecolor);
+  php_referencemap = (php_referencemap_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  MAPSCRIPT_DELREF(php_referencemap->extent);
+  MAPSCRIPT_DELREF(php_referencemap->color);
+  MAPSCRIPT_DELREF(php_referencemap->outlinecolor);
 }
 /* }}} */
 
 zend_function_entry referencemap_functions[] = {
-    PHP_ME(referenceMapObj, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
-    PHP_ME(referenceMapObj, __get, referenceMap___get_args, ZEND_ACC_PUBLIC)
-    PHP_ME(referenceMapObj, __set, referenceMap___set_args, ZEND_ACC_PUBLIC)
-    PHP_MALIAS(referenceMapObj, set, __set, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(referenceMapObj, updateFromString, referenceMap_updateFromString_args, ZEND_ACC_PUBLIC)
-    PHP_ME(referenceMapObj, free, NULL, ZEND_ACC_PUBLIC)
-    {NULL, NULL, NULL}
+  PHP_ME(referenceMapObj, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
+  PHP_ME(referenceMapObj, __get, referenceMap___get_args, ZEND_ACC_PUBLIC)
+  PHP_ME(referenceMapObj, __set, referenceMap___set_args, ZEND_ACC_PUBLIC)
+  PHP_MALIAS(referenceMapObj, set, __set, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(referenceMapObj, updateFromString, referenceMap_updateFromString_args, ZEND_ACC_PUBLIC)
+  PHP_ME(referenceMapObj, free, NULL, ZEND_ACC_PUBLIC) {
+    NULL, NULL, NULL
+  }
 };
 
 void mapscript_create_referencemap(referenceMapObj *referencemap, parent_object parent, zval *return_value TSRMLS_DC)
 {
-    php_referencemap_object * php_referencemap;
-    object_init_ex(return_value, mapscript_ce_referencemap); 
-    php_referencemap = (php_referencemap_object *)zend_object_store_get_object(return_value TSRMLS_CC);
-    php_referencemap->referencemap = referencemap;
+  php_referencemap_object * php_referencemap;
+  object_init_ex(return_value, mapscript_ce_referencemap);
+  php_referencemap = (php_referencemap_object *)zend_object_store_get_object(return_value TSRMLS_CC);
+  php_referencemap->referencemap = referencemap;
 
-    php_referencemap->parent = parent;
-    MAPSCRIPT_ADDREF(parent.val); 
+  php_referencemap->parent = parent;
+  MAPSCRIPT_ADDREF(parent.val);
 }
 
 static void mapscript_referencemap_object_destroy(void *object TSRMLS_DC)
 {
-    php_referencemap_object *php_referencemap = (php_referencemap_object *)object;
+  php_referencemap_object *php_referencemap = (php_referencemap_object *)object;
+
+  MAPSCRIPT_FREE_OBJECT(php_referencemap);
 
-    MAPSCRIPT_FREE_OBJECT(php_referencemap);
+  MAPSCRIPT_FREE_PARENT(php_referencemap->parent);
+  MAPSCRIPT_DELREF(php_referencemap->extent);
+  MAPSCRIPT_DELREF(php_referencemap->color);
+  MAPSCRIPT_DELREF(php_referencemap->outlinecolor);
 
-    MAPSCRIPT_FREE_PARENT(php_referencemap->parent);
-    MAPSCRIPT_DELREF(php_referencemap->extent);
-    MAPSCRIPT_DELREF(php_referencemap->color);
-    MAPSCRIPT_DELREF(php_referencemap->outlinecolor);
+  /* We don't need to free the referenceMapObj */
 
-    /* We don't need to free the referenceMapObj */ 
-    
-    efree(object);
+  efree(object);
 }
 
 static zend_object_value mapscript_referencemap_object_new(zend_class_entry *ce TSRMLS_DC)
 {
-    zend_object_value retval;
-    php_referencemap_object *php_referencemap;
+  zend_object_value retval;
+  php_referencemap_object *php_referencemap;
 
-    MAPSCRIPT_ALLOC_OBJECT(php_referencemap, php_referencemap_object);
+  MAPSCRIPT_ALLOC_OBJECT(php_referencemap, php_referencemap_object);
 
-    retval = mapscript_object_new(&php_referencemap->std, ce,
-                                  &mapscript_referencemap_object_destroy TSRMLS_CC);
+  retval = mapscript_object_new(&php_referencemap->std, ce,
+                                &mapscript_referencemap_object_destroy TSRMLS_CC);
 
-    MAPSCRIPT_INIT_PARENT(php_referencemap->parent);
-    php_referencemap->extent = NULL;
-    php_referencemap->color = NULL;
-    php_referencemap->outlinecolor = NULL;
+  MAPSCRIPT_INIT_PARENT(php_referencemap->parent);
+  php_referencemap->extent = NULL;
+  php_referencemap->color = NULL;
+  php_referencemap->outlinecolor = NULL;
 
-    return retval;
+  return retval;
 }
 
 PHP_MINIT_FUNCTION(referencemap)
 {
-    zend_class_entry ce;
+  zend_class_entry ce;
+
+  MAPSCRIPT_REGISTER_CLASS("referenceMapObj",
+                           referencemap_functions,
+                           mapscript_ce_referencemap,
+                           mapscript_referencemap_object_new);
 
-    MAPSCRIPT_REGISTER_CLASS("referenceMapObj", 
-                             referencemap_functions,
-                             mapscript_ce_referencemap,
-                             mapscript_referencemap_object_new);
+  mapscript_ce_referencemap->ce_flags |= ZEND_ACC_FINAL_CLASS;
 
-    mapscript_ce_referencemap->ce_flags |= ZEND_ACC_FINAL_CLASS; 
-    
-    return SUCCESS;
+  return SUCCESS;
 }
diff --git a/mapscript/php/result.c b/mapscript/php/result.c
index b6a76bd..692a94d 100644
--- a/mapscript/php/result.c
+++ b/mapscript/php/result.c
@@ -2,7 +2,7 @@
  * $Id: php_mapscript.c 9765 2010-01-28 15:32:10Z aboudreault $
  *
  * Project:  MapServer
- * Purpose:  PHP/MapScript extension for MapServer.  External interface 
+ * Purpose:  PHP/MapScript extension for MapServer.  External interface
  *           functions
  * Author:   Daniel Morissette, DM Solutions Group (dmorissette at dmsolutions.ca)
  *           Alan Boudreault, Mapgears
@@ -16,16 +16,16 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
+ *
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  * DEALINGS IN THE SOFTWARE.
  **********************************************************************/
 
@@ -34,16 +34,16 @@
 zend_class_entry *mapscript_ce_result;
 
 ZEND_BEGIN_ARG_INFO_EX(result___construct_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, shapeindex)
+ZEND_ARG_INFO(0, shapeindex)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(result___get_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, property)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(result___set_args, 0, 0, 2)
-  ZEND_ARG_INFO(0, property)
-  ZEND_ARG_INFO(0, value)
+ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, value)
 ZEND_END_ARG_INFO()
 
 
@@ -51,144 +51,140 @@ ZEND_END_ARG_INFO()
    Create a new resultObj instance */
 PHP_METHOD(resultObj, __construct)
 {
-    long shapeindex;
-    php_result_object *php_result;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
-                              &shapeindex) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  long shapeindex;
+  php_result_object *php_result;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
+                            &shapeindex) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_result = (php_result_object *)zend_object_store_get_object(getThis() TSRMLS_CC);
 
-    php_result = (php_result_object *)zend_object_store_get_object(getThis() TSRMLS_CC);
-    
-    if ((php_result->result = resultObj_new()) == NULL)
-    {
-        mapscript_throw_exception("Unable to construct resultObj." TSRMLS_CC);
-        return;
-    }
-    
-    php_result->result->shapeindex = shapeindex;
+  if ((php_result->result = resultObj_new()) == NULL) {
+    mapscript_throw_exception("Unable to construct resultObj." TSRMLS_CC);
+    return;
+  }
+
+  php_result->result->shapeindex = shapeindex;
 }
 /* }}} */
 
 PHP_METHOD(resultObj, __get)
 {
-    char *property;
-    long property_len;
-    zval *zobj = getThis();
-    php_result_object *php_result;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &property, &property_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *zobj = getThis();
+  php_result_object *php_result;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &property, &property_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_result = (php_result_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_result = (php_result_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    IF_GET_LONG("shapeindex", php_result->result->shapeindex)
-    else IF_GET_LONG("tileindex", php_result->result->tileindex)
+  IF_GET_LONG("shapeindex", php_result->result->shapeindex)
+  else IF_GET_LONG("tileindex", php_result->result->tileindex)
     else IF_GET_LONG("classindex", php_result->result->classindex)
-    else IF_GET_LONG("resultindex", php_result->result->resultindex)
-    else 
-    {
-        mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }
+      else IF_GET_LONG("resultindex", php_result->result->resultindex)
+        else {
+          mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+        }
 }
 
 PHP_METHOD(resultObj, __set)
 {
-    char *property;
-    long property_len;
-    zval *value;
-    zval *zobj = getThis();
-    php_result_object *php_result;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
-                              &property, &property_len, &value) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *value;
+  zval *zobj = getThis();
+  php_result_object *php_result;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
+                            &property, &property_len, &value) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_result = (php_result_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-
-    if ( (STRING_EQUAL("shapeindex", property)) ||
-         (STRING_EQUAL("tileindex", property)) ||
-         (STRING_EQUAL("resultindex", property)) ||
-         (STRING_EQUAL("classindex", property)))
-    {
-        mapscript_throw_exception("Property '%s' is an object and can only be modified through its accessors." TSRMLS_CC, property);
-    }
-    else 
-    {
-        mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_result = (php_result_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  if ( (STRING_EQUAL("shapeindex", property)) ||
+       (STRING_EQUAL("tileindex", property)) ||
+       (STRING_EQUAL("resultindex", property)) ||
+       (STRING_EQUAL("classindex", property))) {
+    mapscript_throw_exception("Property '%s' is an object and can only be modified through its accessors." TSRMLS_CC, property);
+  } else {
+    mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+  }
 }
 
 zend_function_entry result_functions[] = {
-    PHP_ME(resultObj, __construct, result___construct_args, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
-    PHP_ME(resultObj, __get, result___get_args, ZEND_ACC_PUBLIC)
-    PHP_ME(resultObj, __set, result___set_args, ZEND_ACC_PUBLIC)
-    {NULL, NULL, NULL}
+  PHP_ME(resultObj, __construct, result___construct_args, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
+  PHP_ME(resultObj, __get, result___get_args, ZEND_ACC_PUBLIC)
+  PHP_ME(resultObj, __set, result___set_args, ZEND_ACC_PUBLIC) {
+    NULL, NULL, NULL
+  }
 };
 
 void mapscript_create_result(resultObj *result, parent_object parent,
-                                        zval *return_value TSRMLS_DC)
+                             zval *return_value TSRMLS_DC)
 {
-    php_result_object * php_result;
-    object_init_ex(return_value, mapscript_ce_result); 
-    php_result = (php_result_object *)zend_object_store_get_object(return_value TSRMLS_CC);
-    php_result->result = result;
+  php_result_object * php_result;
+  object_init_ex(return_value, mapscript_ce_result);
+  php_result = (php_result_object *)zend_object_store_get_object(return_value TSRMLS_CC);
+  php_result->result = result;
 
-    php_result->parent = parent;
-    MAPSCRIPT_ADDREF(parent.val);
+  php_result->parent = parent;
+  MAPSCRIPT_ADDREF(parent.val);
 }
 
 static void mapscript_result_object_destroy(void *object TSRMLS_DC)
 {
-    php_result_object *php_result = (php_result_object *)object;
+  php_result_object *php_result = (php_result_object *)object;
 
-    MAPSCRIPT_FREE_OBJECT(php_result);
+  MAPSCRIPT_FREE_OBJECT(php_result);
 
-    MAPSCRIPT_FREE_PARENT(php_result->parent);
+  MAPSCRIPT_FREE_PARENT(php_result->parent);
 
-    /* We don't need to free the resultObj */ 
-    
-    efree(object);
+  /* We don't need to free the resultObj */
+
+  efree(object);
 }
 
 static zend_object_value mapscript_result_object_new(zend_class_entry *ce TSRMLS_DC)
 {
-    zend_object_value retval;
-    php_result_object *php_result;
+  zend_object_value retval;
+  php_result_object *php_result;
 
-    MAPSCRIPT_ALLOC_OBJECT(php_result, php_result_object);
+  MAPSCRIPT_ALLOC_OBJECT(php_result, php_result_object);
 
-    retval = mapscript_object_new(&php_result->std, ce,
-                                  &mapscript_result_object_destroy TSRMLS_CC);
+  retval = mapscript_object_new(&php_result->std, ce,
+                                &mapscript_result_object_destroy TSRMLS_CC);
 
-    MAPSCRIPT_INIT_PARENT(php_result->parent);
+  MAPSCRIPT_INIT_PARENT(php_result->parent);
 
-    return retval;
+  return retval;
 }
 
 PHP_MINIT_FUNCTION(result)
 {
-    zend_class_entry ce;
+  zend_class_entry ce;
+
+  MAPSCRIPT_REGISTER_CLASS("resultObj",
+                           result_functions,
+                           mapscript_ce_result,
+                           mapscript_result_object_new);
 
-    MAPSCRIPT_REGISTER_CLASS("resultObj", 
-                             result_functions,
-                             mapscript_ce_result,
-                             mapscript_result_object_new);
+  mapscript_ce_result->ce_flags |= ZEND_ACC_FINAL_CLASS;
 
-    mapscript_ce_result->ce_flags |= ZEND_ACC_FINAL_CLASS; 
-    
-    return SUCCESS;
+  return SUCCESS;
 }
diff --git a/mapscript/php/scalebar.c b/mapscript/php/scalebar.c
index 8724e74..5a303bc 100644
--- a/mapscript/php/scalebar.c
+++ b/mapscript/php/scalebar.c
@@ -2,7 +2,7 @@
  * $Id: php_mapscript.c 9765 2010-01-28 15:32:10Z aboudreault $
  *
  * Project:  MapServer
- * Purpose:  PHP/MapScript extension for MapServer.  External interface 
+ * Purpose:  PHP/MapScript extension for MapServer.  External interface
  *           functions
  * Author:   Daniel Morissette, DM Solutions Group (dmorissette at dmsolutions.ca)
  *           Alan Boudreault, Mapgears
@@ -16,16 +16,16 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
+ *
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  * DEALINGS IN THE SOFTWARE.
  **********************************************************************/
 
@@ -34,139 +34,134 @@
 zend_class_entry *mapscript_ce_scalebar;
 
 ZEND_BEGIN_ARG_INFO_EX(scalebar___get_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, property)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(scalebar___set_args, 0, 0, 2)
-  ZEND_ARG_INFO(0, property)
-  ZEND_ARG_INFO(0, value)
+ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, value)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(scalebar_updateFromString_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, snippet)
+ZEND_ARG_INFO(0, snippet)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(scalebar_setImageColor_args, 0, 0, 3)
-  ZEND_ARG_INFO(0, red)
-  ZEND_ARG_INFO(0, green)
-  ZEND_ARG_INFO(0, blue)
+ZEND_ARG_INFO(0, red)
+ZEND_ARG_INFO(0, green)
+ZEND_ARG_INFO(0, blue)
 ZEND_END_ARG_INFO()
 
 /* {{{ proto scalebar __construct()
    scalebarObj CANNOT be instanciated, this will throw an exception on use */
 PHP_METHOD(scalebarObj, __construct)
 {
-    mapscript_throw_exception("scalebarObj cannot be constructed" TSRMLS_CC);
+  mapscript_throw_exception("scalebarObj cannot be constructed" TSRMLS_CC);
 }
 /* }}} */
 
 PHP_METHOD(scalebarObj, __get)
 {
-    char *property;
-    long property_len;
-    zval *zobj = getThis();
-    php_scalebar_object *php_scalebar;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &property, &property_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *zobj = getThis();
+  php_scalebar_object *php_scalebar;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &property, &property_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_scalebar = (php_scalebar_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    IF_GET_LONG("height", php_scalebar->scalebar->height)
-    else IF_GET_LONG("width", php_scalebar->scalebar->width)
+  php_scalebar = (php_scalebar_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  IF_GET_LONG("height", php_scalebar->scalebar->height)
+  else IF_GET_LONG("width", php_scalebar->scalebar->width)
     else IF_GET_LONG("style", php_scalebar->scalebar->style)
-    else IF_GET_LONG("intervals", php_scalebar->scalebar->intervals)
-    else IF_GET_LONG("units", php_scalebar->scalebar->units)
-    else IF_GET_LONG("status", php_scalebar->scalebar->status)
-    else IF_GET_LONG("position", php_scalebar->scalebar->position)
-    else IF_GET_LONG("postlabelcache", php_scalebar->scalebar->postlabelcache)
-    else IF_GET_LONG("align", php_scalebar->scalebar->align)
-    else IF_GET_OBJECT("color", mapscript_ce_color, php_scalebar->color, &php_scalebar->scalebar->color)
-    else IF_GET_OBJECT("backgroundcolor", mapscript_ce_color, php_scalebar->backgroundcolor, &php_scalebar->scalebar->backgroundcolor)
-    else IF_GET_OBJECT("outlinecolor", mapscript_ce_color, php_scalebar->outlinecolor, &php_scalebar->scalebar->outlinecolor)
-    else IF_GET_OBJECT("label", mapscript_ce_label, php_scalebar->label, &php_scalebar->scalebar->label)
-    else IF_GET_OBJECT("imagecolor", mapscript_ce_color, php_scalebar->imagecolor, &php_scalebar->scalebar->imagecolor)
-    else 
-    {
-        mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }
+      else IF_GET_LONG("intervals", php_scalebar->scalebar->intervals)
+        else IF_GET_LONG("units", php_scalebar->scalebar->units)
+          else IF_GET_LONG("status", php_scalebar->scalebar->status)
+            else IF_GET_LONG("position", php_scalebar->scalebar->position)
+              else IF_GET_LONG("postlabelcache", php_scalebar->scalebar->postlabelcache)
+                else IF_GET_LONG("align", php_scalebar->scalebar->align)
+                  else IF_GET_OBJECT("color", mapscript_ce_color, php_scalebar->color, &php_scalebar->scalebar->color)
+                    else IF_GET_OBJECT("backgroundcolor", mapscript_ce_color, php_scalebar->backgroundcolor, &php_scalebar->scalebar->backgroundcolor)
+                      else IF_GET_OBJECT("outlinecolor", mapscript_ce_color, php_scalebar->outlinecolor, &php_scalebar->scalebar->outlinecolor)
+                        else IF_GET_OBJECT("label", mapscript_ce_label, php_scalebar->label, &php_scalebar->scalebar->label)
+                          else IF_GET_OBJECT("imagecolor", mapscript_ce_color, php_scalebar->imagecolor, &php_scalebar->scalebar->imagecolor)
+                            else {
+                              mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+                            }
 }
 
 PHP_METHOD(scalebarObj, __set)
 {
-    char *property;
-    long property_len;
-    zval *value;
-    zval *zobj = getThis();
-    php_scalebar_object *php_scalebar;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
-                              &property, &property_len, &value) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *value;
+  zval *zobj = getThis();
+  php_scalebar_object *php_scalebar;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
+                            &property, &property_len, &value) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_scalebar = (php_scalebar_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_scalebar = (php_scalebar_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    IF_SET_LONG("height", php_scalebar->scalebar->height, value)
-    else IF_SET_LONG("width", php_scalebar->scalebar->width, value)
+  IF_SET_LONG("height", php_scalebar->scalebar->height, value)
+  else IF_SET_LONG("width", php_scalebar->scalebar->width, value)
     else IF_SET_LONG("style", php_scalebar->scalebar->style, value)
-    else IF_SET_LONG("intervals", php_scalebar->scalebar->intervals, value)
-    else IF_SET_LONG("units", php_scalebar->scalebar->units, value)
-    else IF_SET_LONG("status", php_scalebar->scalebar->status, value)
-    else IF_SET_LONG("position", php_scalebar->scalebar->position, value)
-    else IF_SET_LONG("postlabelcache", php_scalebar->scalebar->postlabelcache, value)
-    else IF_SET_LONG("align", php_scalebar->scalebar->align, value)
-    else if ( (STRING_EQUAL("color", property)) ||
-              (STRING_EQUAL("backgroundcolor", property)) ||
-              (STRING_EQUAL("outlinecolor", property)) ||
-              (STRING_EQUAL("label", property)) ||
-              (STRING_EQUAL("imagecolor", property)))
-    {
-        mapscript_throw_exception("Property '%s' is an object and can only be modified through its accessors." TSRMLS_CC, property);
-    }
-    else 
-    {
-        mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }
+      else IF_SET_LONG("intervals", php_scalebar->scalebar->intervals, value)
+        else IF_SET_LONG("units", php_scalebar->scalebar->units, value)
+          else IF_SET_LONG("status", php_scalebar->scalebar->status, value)
+            else IF_SET_LONG("position", php_scalebar->scalebar->position, value)
+              else IF_SET_LONG("postlabelcache", php_scalebar->scalebar->postlabelcache, value)
+                else IF_SET_LONG("align", php_scalebar->scalebar->align, value)
+                  else if ( (STRING_EQUAL("color", property)) ||
+                            (STRING_EQUAL("backgroundcolor", property)) ||
+                            (STRING_EQUAL("outlinecolor", property)) ||
+                            (STRING_EQUAL("label", property)) ||
+                            (STRING_EQUAL("imagecolor", property))) {
+                    mapscript_throw_exception("Property '%s' is an object and can only be modified through its accessors." TSRMLS_CC, property);
+                  } else {
+                    mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+                  }
 }
 
 /* {{{ proto int scalebar.updateFromString(string snippet)
    Update a scalebar from a string snippet.  Returns MS_SUCCESS/MS_FAILURE */
 PHP_METHOD(scalebarObj, updateFromString)
 {
-    char *snippet;
-    long snippet_len;
-    zval *zobj = getThis();
-    php_scalebar_object *php_scalebar;
-    int status = MS_FAILURE;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &snippet, &snippet_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *snippet;
+  long snippet_len;
+  zval *zobj = getThis();
+  php_scalebar_object *php_scalebar;
+  int status = MS_FAILURE;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &snippet, &snippet_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_scalebar = (php_scalebar_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-
-    status =  scalebarObj_updateFromString(php_scalebar->scalebar, snippet);
-    
-    if (status != MS_SUCCESS)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
-
-    RETURN_LONG(status);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_scalebar = (php_scalebar_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  status =  scalebarObj_updateFromString(php_scalebar->scalebar, snippet);
+
+  if (status != MS_SUCCESS) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -174,28 +169,28 @@ PHP_METHOD(scalebarObj, updateFromString)
    Set the imagecolor property of the scalebar. Returns -1 on error. */
 PHP_METHOD(scalebarObj, setImageColor)
 {
-    zval *zobj = getThis();
-    long red, green, blue;
-    php_scalebar_object *php_scalebar;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "lll",
-                              &red, &green, &blue) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  long red, green, blue;
+  php_scalebar_object *php_scalebar;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "lll",
+                            &red, &green, &blue) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_scalebar = (php_scalebar_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    if (red < 0 || red > 255 || green < 0 || green > 255 || blue < 0 || blue > 255)
-        RETURN_LONG(MS_FAILURE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_scalebar = (php_scalebar_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    php_scalebar->scalebar->imagecolor.red = red;
-    php_scalebar->scalebar->imagecolor.green = green;
-    php_scalebar->scalebar->imagecolor.blue = blue;
+  if (red < 0 || red > 255 || green < 0 || green > 255 || blue < 0 || blue > 255)
+    RETURN_LONG(MS_FAILURE);
 
-    RETURN_LONG(MS_SUCCESS);
+  php_scalebar->scalebar->imagecolor.red = red;
+  php_scalebar->scalebar->imagecolor.green = green;
+  php_scalebar->scalebar->imagecolor.blue = blue;
+
+  RETURN_LONG(MS_SUCCESS);
 }
 /* }}} */
 
@@ -203,96 +198,97 @@ PHP_METHOD(scalebarObj, setImageColor)
    Free the object */
 PHP_METHOD(scalebarObj, free)
 {
-    zval *zobj = getThis();
-    php_scalebar_object *php_scalebar;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  php_scalebar_object *php_scalebar;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_scalebar = (php_scalebar_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    MAPSCRIPT_DELREF(php_scalebar->color);
-    MAPSCRIPT_DELREF(php_scalebar->backgroundcolor);
-    MAPSCRIPT_DELREF(php_scalebar->outlinecolor);
-    MAPSCRIPT_DELREF(php_scalebar->imagecolor);
-    MAPSCRIPT_DELREF(php_scalebar->label);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_scalebar = (php_scalebar_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  MAPSCRIPT_DELREF(php_scalebar->color);
+  MAPSCRIPT_DELREF(php_scalebar->backgroundcolor);
+  MAPSCRIPT_DELREF(php_scalebar->outlinecolor);
+  MAPSCRIPT_DELREF(php_scalebar->imagecolor);
+  MAPSCRIPT_DELREF(php_scalebar->label);
 }
 /* }}} */
 
 zend_function_entry scalebar_functions[] = {
-    PHP_ME(scalebarObj, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
-    PHP_ME(scalebarObj, __get, scalebar___get_args, ZEND_ACC_PUBLIC)
-    PHP_ME(scalebarObj, __set, scalebar___set_args, ZEND_ACC_PUBLIC)
-    PHP_MALIAS(scalebarObj, set, __set, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(scalebarObj, updateFromString, scalebar_updateFromString_args, ZEND_ACC_PUBLIC)
-    PHP_ME(scalebarObj, setImageColor, scalebar_setImageColor_args, ZEND_ACC_PUBLIC)
-    PHP_ME(scalebarObj, free, NULL, ZEND_ACC_PUBLIC)
-    {NULL, NULL, NULL}
+  PHP_ME(scalebarObj, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
+  PHP_ME(scalebarObj, __get, scalebar___get_args, ZEND_ACC_PUBLIC)
+  PHP_ME(scalebarObj, __set, scalebar___set_args, ZEND_ACC_PUBLIC)
+  PHP_MALIAS(scalebarObj, set, __set, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(scalebarObj, updateFromString, scalebar_updateFromString_args, ZEND_ACC_PUBLIC)
+  PHP_ME(scalebarObj, setImageColor, scalebar_setImageColor_args, ZEND_ACC_PUBLIC)
+  PHP_ME(scalebarObj, free, NULL, ZEND_ACC_PUBLIC) {
+    NULL, NULL, NULL
+  }
 };
 
 void mapscript_create_scalebar(scalebarObj *scalebar, parent_object parent, zval *return_value TSRMLS_DC)
 {
-    php_scalebar_object * php_scalebar;
-    object_init_ex(return_value, mapscript_ce_scalebar); 
-    php_scalebar = (php_scalebar_object *)zend_object_store_get_object(return_value TSRMLS_CC);
-    php_scalebar->scalebar = scalebar;
+  php_scalebar_object * php_scalebar;
+  object_init_ex(return_value, mapscript_ce_scalebar);
+  php_scalebar = (php_scalebar_object *)zend_object_store_get_object(return_value TSRMLS_CC);
+  php_scalebar->scalebar = scalebar;
 
-    php_scalebar->parent = parent;
-    MAPSCRIPT_ADDREF(parent.val);
+  php_scalebar->parent = parent;
+  MAPSCRIPT_ADDREF(parent.val);
 }
 
 static void mapscript_scalebar_object_destroy(void *object TSRMLS_DC)
 {
-    php_scalebar_object *php_scalebar = (php_scalebar_object *)object;
+  php_scalebar_object *php_scalebar = (php_scalebar_object *)object;
 
-    MAPSCRIPT_FREE_OBJECT(php_scalebar);
+  MAPSCRIPT_FREE_OBJECT(php_scalebar);
 
-    MAPSCRIPT_FREE_PARENT(php_scalebar->parent);
-    MAPSCRIPT_DELREF(php_scalebar->color);
-    MAPSCRIPT_DELREF(php_scalebar->backgroundcolor);
-    MAPSCRIPT_DELREF(php_scalebar->outlinecolor);
-    MAPSCRIPT_DELREF(php_scalebar->imagecolor);
-    MAPSCRIPT_DELREF(php_scalebar->label);
+  MAPSCRIPT_FREE_PARENT(php_scalebar->parent);
+  MAPSCRIPT_DELREF(php_scalebar->color);
+  MAPSCRIPT_DELREF(php_scalebar->backgroundcolor);
+  MAPSCRIPT_DELREF(php_scalebar->outlinecolor);
+  MAPSCRIPT_DELREF(php_scalebar->imagecolor);
+  MAPSCRIPT_DELREF(php_scalebar->label);
 
-    /* We don't need to free the scalebarObj */ 
-    
-    efree(object);
+  /* We don't need to free the scalebarObj */
+
+  efree(object);
 }
 
 static zend_object_value mapscript_scalebar_object_new(zend_class_entry *ce TSRMLS_DC)
 {
-    zend_object_value retval;
-    php_scalebar_object *php_scalebar;
+  zend_object_value retval;
+  php_scalebar_object *php_scalebar;
 
-    MAPSCRIPT_ALLOC_OBJECT(php_scalebar, php_scalebar_object);
+  MAPSCRIPT_ALLOC_OBJECT(php_scalebar, php_scalebar_object);
 
-    retval = mapscript_object_new(&php_scalebar->std, ce,
-                                  &mapscript_scalebar_object_destroy TSRMLS_CC);
+  retval = mapscript_object_new(&php_scalebar->std, ce,
+                                &mapscript_scalebar_object_destroy TSRMLS_CC);
 
-    MAPSCRIPT_INIT_PARENT(php_scalebar->parent);
-    php_scalebar->color = NULL;
-    php_scalebar->backgroundcolor = NULL;
-    php_scalebar->outlinecolor = NULL;
-    php_scalebar->imagecolor = NULL;
-    php_scalebar->label = NULL;
+  MAPSCRIPT_INIT_PARENT(php_scalebar->parent);
+  php_scalebar->color = NULL;
+  php_scalebar->backgroundcolor = NULL;
+  php_scalebar->outlinecolor = NULL;
+  php_scalebar->imagecolor = NULL;
+  php_scalebar->label = NULL;
 
-    return retval;
+  return retval;
 }
 
 PHP_MINIT_FUNCTION(scalebar)
 {
-    zend_class_entry ce;
+  zend_class_entry ce;
+
+  MAPSCRIPT_REGISTER_CLASS("scalebarObj",
+                           scalebar_functions,
+                           mapscript_ce_scalebar,
+                           mapscript_scalebar_object_new);
 
-    MAPSCRIPT_REGISTER_CLASS("scalebarObj", 
-                             scalebar_functions,
-                             mapscript_ce_scalebar,
-                             mapscript_scalebar_object_new);
+  mapscript_ce_scalebar->ce_flags |= ZEND_ACC_FINAL_CLASS;
 
-    mapscript_ce_scalebar->ce_flags |= ZEND_ACC_FINAL_CLASS; 
-    
-    return SUCCESS;
+  return SUCCESS;
 }
diff --git a/mapscript/php/shape.c b/mapscript/php/shape.c
index 5726640..28e93f9 100644
--- a/mapscript/php/shape.c
+++ b/mapscript/php/shape.c
@@ -2,7 +2,7 @@
  * $Id: php_mapscript.c 9765 2010-01-28 15:32:10Z aboudreault $
  *
  * Project:  MapServer
- * Purpose:  PHP/MapScript extension for MapServer.  External interface 
+ * Purpose:  PHP/MapScript extension for MapServer.  External interface
  *           functions
  * Author:   Daniel Morissette, DM Solutions Group (dmorissette at dmsolutions.ca)
  *           Alan Boudreault, Mapgears
@@ -16,16 +16,16 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
+ *
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  * DEALINGS IN THE SOFTWARE.
  **********************************************************************/
 
@@ -34,235 +34,240 @@
 zend_class_entry *mapscript_ce_shape;
 
 ZEND_BEGIN_ARG_INFO_EX(shape___construct_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, type)
+ZEND_ARG_INFO(0, type)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(shape___get_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, property)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(shape___set_args, 0, 0, 2)
-  ZEND_ARG_INFO(0, property)
-  ZEND_ARG_INFO(0, value)
+ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, value)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(shape_project_args, 0, 0, 2)
-  ZEND_ARG_OBJ_INFO(0, projIn, projectionObj, 0)
-  ZEND_ARG_OBJ_INFO(0, projOut, projectionObj, 0)
+ZEND_ARG_OBJ_INFO(0, projIn, projectionObj, 0)
+ZEND_ARG_OBJ_INFO(0, projOut, projectionObj, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(shape_add_args, 0, 0, 1)
-  ZEND_ARG_OBJ_INFO(0, line, lineObj, 0)
+ZEND_ARG_OBJ_INFO(0, line, lineObj, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(shape_line_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, index)
+ZEND_ARG_INFO(0, index)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(shape_contains_args, 0, 0, 1)
-  ZEND_ARG_OBJ_INFO(0, point, pointObj, 0)
+ZEND_ARG_OBJ_INFO(0, point, pointObj, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(shape_intersects_args, 0, 0, 1)
-  ZEND_ARG_OBJ_INFO(0, shape, shapeObj, 0)
+ZEND_ARG_OBJ_INFO(0, shape, shapeObj, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(shape_getPointUsingMeasure_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, measure)
+ZEND_ARG_INFO(0, measure)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(shape_getMeasureUsingPoint_args, 0, 0, 1)
-  ZEND_ARG_OBJ_INFO(0, point, pointObj, 0)
+ZEND_ARG_OBJ_INFO(0, point, pointObj, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(shape_getValue_args, 0, 0, 2)
-  ZEND_ARG_OBJ_INFO(0, layer, layerObj, 0)
-  ZEND_ARG_INFO(0, fieldName)
+ZEND_ARG_OBJ_INFO(0, layer, layerObj, 0)
+ZEND_ARG_INFO(0, fieldName)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(shape_buffer_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, width)
+ZEND_ARG_INFO(0, width)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(shape_containsShape_args, 0, 0, 1)
-  ZEND_ARG_OBJ_INFO(0, shape, shapeObj, 0)
+ZEND_ARG_OBJ_INFO(0, shape, shapeObj, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(shape_union_args, 0, 0, 1)
-  ZEND_ARG_OBJ_INFO(0, shape, shapeObj, 0)
+ZEND_ARG_OBJ_INFO(0, shape, shapeObj, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(shape_intersection_args, 0, 0, 1)
-  ZEND_ARG_OBJ_INFO(0, shape, shapeObj, 0)
+ZEND_ARG_OBJ_INFO(0, shape, shapeObj, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(shape_difference_args, 0, 0, 1)
-  ZEND_ARG_OBJ_INFO(0, shape, shapeObj, 0)
+ZEND_ARG_OBJ_INFO(0, shape, shapeObj, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(shape_symdifference_args, 0, 0, 1)
-  ZEND_ARG_OBJ_INFO(0, shape, shapeObj, 0)
+ZEND_ARG_OBJ_INFO(0, shape, shapeObj, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(shape_overlaps_args, 0, 0, 1)
-  ZEND_ARG_OBJ_INFO(0, shape, shapeObj, 0)
+ZEND_ARG_OBJ_INFO(0, shape, shapeObj, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(shape_within_args, 0, 0, 1)
-  ZEND_ARG_OBJ_INFO(0, shape, shapeObj, 0)
+ZEND_ARG_OBJ_INFO(0, shape, shapeObj, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(shape_crosses_args, 0, 0, 1)
-  ZEND_ARG_OBJ_INFO(0, shape, shapeObj, 0)
+ZEND_ARG_OBJ_INFO(0, shape, shapeObj, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(shape_touches_args, 0, 0, 1)
-  ZEND_ARG_OBJ_INFO(0, shape, shapeObj, 0)
+ZEND_ARG_OBJ_INFO(0, shape, shapeObj, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(shape_equals_args, 0, 0, 1)
-  ZEND_ARG_OBJ_INFO(0, shape, shapeObj, 0)
+ZEND_ARG_OBJ_INFO(0, shape, shapeObj, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(shape_disjoint_args, 0, 0, 1)
-  ZEND_ARG_OBJ_INFO(0, shape, shapeObj, 0)
+ZEND_ARG_OBJ_INFO(0, shape, shapeObj, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(shape_simplify_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, tolerance)
+ZEND_ARG_INFO(0, tolerance)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(shape_topologyPreservingSimplify_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, tolerance)
+ZEND_ARG_INFO(0, tolerance)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(shape_draw_args, 0, 0, 3)
-  ZEND_ARG_OBJ_INFO(0, map, mapObj, 0)
-  ZEND_ARG_OBJ_INFO(0, layer, layerObj, 0)
-  ZEND_ARG_OBJ_INFO(0, image, imageObj, 0)
+ZEND_ARG_OBJ_INFO(0, map, mapObj, 0)
+ZEND_ARG_OBJ_INFO(0, layer, layerObj, 0)
+ZEND_ARG_OBJ_INFO(0, image, imageObj, 0)
+ZEND_END_ARG_INFO()
+
+ZEND_BEGIN_ARG_INFO_EX(shape_distanceToPoint_args, 0, 0, 1)
+ZEND_ARG_OBJ_INFO(0, point, pointObj, 0)
+ZEND_END_ARG_INFO()
+
+ZEND_BEGIN_ARG_INFO_EX(shape_distanceToShape_args, 0, 0, 1)
+ZEND_ARG_OBJ_INFO(0, shape, shapeObj, 0)
 ZEND_END_ARG_INFO()
 
 /* {{{ proto shape __construct(int type)
    Create a new shapeObj instance. */
 PHP_METHOD(shapeObj, __construct)
 {
-    zval *zobj = getThis();
-    php_shape_object *php_shape;
-    long type;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
-                              &type) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  php_shape_object *php_shape;
+  long type;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
+                            &type) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_shape = (php_shape_object *)zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    if ((php_shape->shape = shapeObj_new(type)) == NULL)
-    {
-        mapscript_throw_exception("Unable to construct shapeObj." TSRMLS_CC);
-        return;
-    }
+  php_shape = (php_shape_object *)zend_object_store_get_object(zobj TSRMLS_CC);
+
+  if ((php_shape->shape = shapeObj_new(type)) == NULL) {
+    mapscript_throw_exception("Unable to construct shapeObj." TSRMLS_CC);
+    return;
+  }
 
-    MAKE_STD_ZVAL(php_shape->values);
-    array_init(php_shape->values);    
+  MAKE_STD_ZVAL(php_shape->values);
+  array_init(php_shape->values);
 }
 /* }}} */
 
 PHP_METHOD(shapeObj, __get)
 {
-    char *property;
-    long property_len;
-    zval *zobj = getThis();
-    php_shape_object *php_shape;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &property, &property_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *zobj = getThis();
+  php_shape_object *php_shape;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &property, &property_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-
-    IF_GET_STRING("text", php_shape->shape->text)
-    else IF_GET_LONG("classindex", php_shape->shape->classindex) 
-    else IF_GET_LONG("index", php_shape->shape->index) 
-    else IF_GET_LONG("tileindex", php_shape->shape->tileindex) 
-    else IF_GET_LONG("numlines", php_shape->shape->numlines) 
-    else IF_GET_LONG("numvalues", php_shape->shape->numvalues) 
-    else IF_GET_LONG("type", php_shape->shape->type) 
-    else IF_GET_OBJECT("bounds", mapscript_ce_rect, php_shape->bounds, &php_shape->shape->bounds) 
-    else IF_GET_OBJECT("values", NULL, php_shape->values, NULL) 
-    else 
-    {
-        mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  IF_GET_STRING("text", php_shape->shape->text)
+  else IF_GET_LONG("classindex", php_shape->shape->classindex)
+    else IF_GET_LONG("index", php_shape->shape->index)
+      else IF_GET_LONG("tileindex", php_shape->shape->tileindex)
+        else IF_GET_LONG("resultindex", php_shape->shape->resultindex)
+          else IF_GET_LONG("numlines", php_shape->shape->numlines)
+            else IF_GET_LONG("numvalues", php_shape->shape->numvalues)
+              else IF_GET_LONG("type", php_shape->shape->type)
+                else IF_GET_OBJECT("bounds", mapscript_ce_rect, php_shape->bounds, &php_shape->shape->bounds)
+                  else IF_GET_OBJECT("values", NULL, php_shape->values, NULL)
+                    else {
+                      mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+                    }
 }
 
 PHP_METHOD(shapeObj, __set)
 {
-    char *property;
-    long property_len;
-    zval *value;
-    zval *zobj = getThis();
-    php_shape_object *php_shape;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
-                              &property, &property_len, &value) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *value;
+  zval *zobj = getThis();
+  php_shape_object *php_shape;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
+                            &property, &property_len, &value) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-
-    IF_SET_STRING("text", php_shape->shape->text, value)
-    else IF_SET_LONG("classindex", php_shape->shape->classindex, value) 
-    else IF_SET_LONG("index", php_shape->shape->index, value) 
-    else if ( (STRING_EQUAL("type", property)) ||
-              (STRING_EQUAL("numlines", property)) ||
-              (STRING_EQUAL("tileindex", property)) ||
-              (STRING_EQUAL("bounds", property)) ||
-              (STRING_EQUAL("values", property)) ||
-              (STRING_EQUAL("numvalues", property)) )
-    {
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  IF_SET_STRING("text", php_shape->shape->text, value)
+  else IF_SET_LONG("classindex", php_shape->shape->classindex, value)
+    else IF_SET_LONG("index", php_shape->shape->index, value)
+      else if ( (STRING_EQUAL("type", property)) ||
+                (STRING_EQUAL("numlines", property)) ||
+                (STRING_EQUAL("tileindex", property)) ||
+                (STRING_EQUAL("resultindex", property)) ||
+                (STRING_EQUAL("bounds", property)) ||
+                (STRING_EQUAL("values", property)) ||
+                (STRING_EQUAL("numvalues", property)) ) {
         mapscript_throw_exception("Property '%s' is read-only and cannot be set." TSRMLS_CC, property);
-    }
-    else 
-    {
+      } else {
         mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }
+      }
 }
 
 /* {{{ proto int shape.add(lineObj line)
    Adds a line (i.e. a part) to a shape */
 PHP_METHOD(shapeObj, add)
 {
-    zval *zobj =  getThis();
-    zval *zline;
-    php_shape_object *php_shape;
-    php_line_object *php_line;
-    int retval = MS_FAILURE;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
-                              &zline, mapscript_ce_line) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj =  getThis();
+  zval *zline;
+  php_shape_object *php_shape;
+  php_line_object *php_line;
+  int retval = MS_FAILURE;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
+                            &zline, mapscript_ce_line) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_line = (php_line_object *) zend_object_store_get_object(zline TSRMLS_CC);
+  php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_line = (php_line_object *) zend_object_store_get_object(zline TSRMLS_CC);
 
-    retval = shapeObj_add(php_shape->shape, php_line->line);
+  retval = shapeObj_add(php_shape->shape, php_line->line);
 
-    RETURN_LONG(retval);
+  RETURN_LONG(retval);
 }
 /* }}} */
 
@@ -270,30 +275,29 @@ PHP_METHOD(shapeObj, add)
    Returns line (part) number i.  First line is number 0. */
 PHP_METHOD(shapeObj, line)
 {
-    zval *zobj =  getThis();
-    long index;
-    php_shape_object *php_shape;
-    parent_object parent;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
-                              &index) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj =  getThis();
+  long index;
+  php_shape_object *php_shape;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
+                            &index) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    
-    if (index < 0 || index >= php_shape->shape->numlines)
-    {
-        mapscript_throw_exception("Line '%d' does not exist in this object." TSRMLS_CC, index);
-        return;
-    }
-    
-    MAPSCRIPT_MAKE_PARENT(zobj, NULL);
-    mapscript_create_line(&(php_shape->shape->line[index]), parent, return_value TSRMLS_CC);
+
+  if (index < 0 || index >= php_shape->shape->numlines) {
+    mapscript_throw_exception("Line '%d' does not exist in this object." TSRMLS_CC, index);
+    return;
+  }
+
+  MAPSCRIPT_MAKE_PARENT(zobj, NULL);
+  mapscript_create_line(&(php_shape->shape->line[index]), parent, return_value TSRMLS_CC);
 }
 /* }}} */
 
@@ -301,26 +305,26 @@ PHP_METHOD(shapeObj, line)
    Returns true or false if the the point is in a polygone shape.*/
 PHP_METHOD(shapeObj, contains)
 {
-    zval *zobj =  getThis();
-    zval *zpoint;
-    php_shape_object *php_shape;
-    php_point_object *php_point;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
-                              &zpoint, mapscript_ce_point) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj =  getThis();
+  zval *zpoint;
+  php_shape_object *php_shape;
+  php_point_object *php_point;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
+                            &zpoint, mapscript_ce_point) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_point = (php_point_object *) zend_object_store_get_object(zpoint TSRMLS_CC);
+  php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_point = (php_point_object *) zend_object_store_get_object(zpoint TSRMLS_CC);
 
-    if (!shapeObj_contains(php_shape->shape, php_point->point))
-        RETURN_FALSE;
+  if (!shapeObj_contains(php_shape->shape, php_point->point))
+    RETURN_FALSE;
 
-    RETURN_TRUE;
+  RETURN_TRUE;
 }
 /* }}} */
 
@@ -328,25 +332,25 @@ PHP_METHOD(shapeObj, contains)
    Returns true if the two shapes intersect. Else false.*/
 PHP_METHOD(shapeObj, intersects)
 {
-    zval *zobj =  getThis();
-    zval *zshape;
-    php_shape_object *php_shape, *php_shape2;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
-                              &zshape, mapscript_ce_shape) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj =  getThis();
+  zval *zshape;
+  php_shape_object *php_shape, *php_shape2;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
+                            &zshape, mapscript_ce_shape) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_shape2 = (php_shape_object *) zend_object_store_get_object(zshape TSRMLS_CC);
+  php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_shape2 = (php_shape_object *) zend_object_store_get_object(zshape TSRMLS_CC);
 
-    if (!shapeObj_intersects(php_shape->shape, php_shape2->shape))
-        RETURN_FALSE;
+  if (!shapeObj_intersects(php_shape->shape, php_shape2->shape))
+    RETURN_FALSE;
 
-    RETURN_TRUE;
+  RETURN_TRUE;
 }
 /* }}} */
 
@@ -354,32 +358,31 @@ PHP_METHOD(shapeObj, intersects)
    Project a Shape. Returns MS_SUCCESS/MS_FAILURE */
 PHP_METHOD(shapeObj, project)
 {
-    zval *zobj_proj_in, *zobj_proj_out;
-    zval *zobj =  getThis();
-    php_shape_object *php_shape;
-    php_projection_object *php_proj_in, *php_proj_out;
-    int status = MS_FAILURE;
-    
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "OO",
-                              &zobj_proj_in, mapscript_ce_projection,
-                              &zobj_proj_out, mapscript_ce_projection) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj_proj_in, *zobj_proj_out;
+  zval *zobj =  getThis();
+  php_shape_object *php_shape;
+  php_projection_object *php_proj_in, *php_proj_out;
+  int status = MS_FAILURE;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "OO",
+                            &zobj_proj_in, mapscript_ce_projection,
+                            &zobj_proj_out, mapscript_ce_projection) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_proj_in = (php_projection_object *) zend_object_store_get_object(zobj_proj_in TSRMLS_CC);
-    php_proj_out = (php_projection_object *) zend_object_store_get_object(zobj_proj_out TSRMLS_CC);
-    
-    status = shapeObj_project(php_shape->shape, php_proj_in->projection, php_proj_out->projection);
-    if (status != MS_SUCCESS)
-    {
-        mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
-    }
+  php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_proj_in = (php_projection_object *) zend_object_store_get_object(zobj_proj_in TSRMLS_CC);
+  php_proj_out = (php_projection_object *) zend_object_store_get_object(zobj_proj_out TSRMLS_CC);
+
+  status = shapeObj_project(php_shape->shape, php_proj_in->projection, php_proj_out->projection);
+  if (status != MS_SUCCESS) {
+    mapscript_report_mapserver_error(E_WARNING TSRMLS_CC);
+  }
 
-    RETURN_LONG(status);
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -388,28 +391,28 @@ PHP_METHOD(shapeObj, project)
    location corresponding to the measure */
 PHP_METHOD(shapeObj, getPointUsingMeasure)
 {
-    zval *zobj =  getThis();
-    double measure;
-    pointObj *point = NULL;
-    php_shape_object *php_shape;
-    parent_object parent;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "d",
-                              &measure) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj =  getThis();
+  double measure;
+  pointObj *point = NULL;
+  php_shape_object *php_shape;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "d",
+                            &measure) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    point = shapeObj_getpointusingmeasure(php_shape->shape, measure);
-    if (point == NULL)
-        RETURN_FALSE;
-    
-    MAPSCRIPT_MAKE_PARENT(zobj, NULL);
-    mapscript_create_point(point, parent, return_value TSRMLS_CC);
+  point = shapeObj_getpointusingmeasure(php_shape->shape, measure);
+  if (point == NULL)
+    RETURN_FALSE;
+
+  MAPSCRIPT_MAKE_PARENT(zobj, NULL);
+  mapscript_create_point(point, parent, return_value TSRMLS_CC);
 }
 /* }}} */
 
@@ -419,30 +422,30 @@ PHP_METHOD(shapeObj, getPointUsingMeasure)
    return contains also the extrapolated M value at the intersection. */
 PHP_METHOD(shapeObj, getMeasureUsingPoint)
 {
-    zval *zobj =  getThis();
-    zval *zpoint;
-    pointObj *intersection = NULL;
-    php_shape_object *php_shape;
-    php_point_object *php_point;
-    parent_object parent;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
-                              &zpoint, mapscript_ce_point) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj =  getThis();
+  zval *zpoint;
+  pointObj *intersection = NULL;
+  php_shape_object *php_shape;
+  php_point_object *php_point;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
+                            &zpoint, mapscript_ce_point) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_point = (php_point_object *) zend_object_store_get_object(zpoint TSRMLS_CC);
+  php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_point = (php_point_object *) zend_object_store_get_object(zpoint TSRMLS_CC);
 
-    intersection = shapeObj_getmeasureusingpoint(php_shape->shape, php_point->point);
-    if (intersection == NULL)
-        RETURN_FALSE;
+  intersection = shapeObj_getmeasureusingpoint(php_shape->shape, php_point->point);
+  if (intersection == NULL)
+    RETURN_FALSE;
 
-    MAPSCRIPT_MAKE_PARENT(NULL, NULL);
-    mapscript_create_point(intersection, parent, return_value TSRMLS_CC);
+  MAPSCRIPT_MAKE_PARENT(NULL, NULL);
+  mapscript_create_point(intersection, parent, return_value TSRMLS_CC);
 }
 /* }}} */
 
@@ -450,36 +453,34 @@ PHP_METHOD(shapeObj, getMeasureUsingPoint)
    Returns value for specified field name. */
 PHP_METHOD(shapeObj, getValue)
 {
-    zval *zobj =  getThis();
-    zval *zlayer;
-    char *fieldName;
-    long fieldName_len;
-    int i;
-    php_layer_object *php_layer;
-    php_shape_object *php_shape;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Os",
-                              &zlayer, mapscript_ce_layer,
-                              &fieldName, &fieldName_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj =  getThis();
+  zval *zlayer;
+  char *fieldName;
+  long fieldName_len;
+  int i;
+  php_layer_object *php_layer;
+  php_shape_object *php_shape;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Os",
+                            &zlayer, mapscript_ce_layer,
+                            &fieldName, &fieldName_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_layer = (php_layer_object *) zend_object_store_get_object(zlayer TSRMLS_CC);
+  php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_layer = (php_layer_object *) zend_object_store_get_object(zlayer TSRMLS_CC);
 
-    if (php_shape->shape->numvalues != php_layer->layer->numitems)
-        RETURN_STRING("", 1);
+  if (php_shape->shape->numvalues != php_layer->layer->numitems)
+    RETURN_STRING("", 1);
 
-    for(i=0; i<php_layer->layer->numitems; i++)
-    {
-        if (strcasecmp(php_layer->layer->items[i], fieldName)==0)
-        {
-            RETURN_STRING(php_shape->shape->values[i], 1);
-        }
+  for(i=0; i<php_layer->layer->numitems; i++) {
+    if (strcasecmp(php_layer->layer->items[i], fieldName)==0) {
+      RETURN_STRING(php_shape->shape->values[i], 1);
     }
+  }
 }
 /* }}} */
 
@@ -488,28 +489,28 @@ PHP_METHOD(shapeObj, getValue)
    underlying GEOS library*/
 PHP_METHOD(shapeObj, buffer)
 {
-    zval *zobj =  getThis();
-    double width;
-    shapeObj *shape = NULL;
-    php_shape_object *php_shape;
-    parent_object parent;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "d",
-                              &width) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj =  getThis();
+  double width;
+  shapeObj *shape = NULL;
+  php_shape_object *php_shape;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "d",
+                            &width) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    shape = shapeObj_buffer(php_shape->shape, width);
-    if (shape == NULL)
-        RETURN_FALSE;
+  shape = shapeObj_buffer(php_shape->shape, width);
+  if (shape == NULL)
+    RETURN_FALSE;
 
-    MAPSCRIPT_MAKE_PARENT(NULL, NULL);
-    mapscript_create_shape(shape, parent, NULL, return_value TSRMLS_CC);
+  MAPSCRIPT_MAKE_PARENT(NULL, NULL);
+  mapscript_create_shape(shape, parent, NULL, return_value TSRMLS_CC);
 }
 /* }}} */
 
@@ -518,54 +519,54 @@ PHP_METHOD(shapeObj, buffer)
    underlying GEOS library */
 PHP_METHOD(shapeObj, convexhull)
 {
-    zval *zobj =  getThis();
-    shapeObj *shape = NULL;
-    php_shape_object *php_shape;
-    parent_object parent;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj =  getThis();
+  shapeObj *shape = NULL;
+  php_shape_object *php_shape;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    shape = shapeObj_convexHull(php_shape->shape);
-    if (shape == NULL)
-        RETURN_FALSE;
+  shape = shapeObj_convexHull(php_shape->shape);
+  if (shape == NULL)
+    RETURN_FALSE;
 
-    MAPSCRIPT_MAKE_PARENT(NULL, NULL);
-    mapscript_create_shape(shape, parent, NULL, return_value TSRMLS_CC);
+  MAPSCRIPT_MAKE_PARENT(NULL, NULL);
+  mapscript_create_shape(shape, parent, NULL, return_value TSRMLS_CC);
 }
 /* }}} */
 
 /* {{{ proto int shape.boundary()
-   Returns the boundary of the shape. Only available if php/mapscript 
+   Returns the boundary of the shape. Only available if php/mapscript
    is built with GEOS library.*/
 PHP_METHOD(shapeObj, boundary)
 {
-    zval *zobj =  getThis();
-    shapeObj *shape = NULL;
-    php_shape_object *php_shape;
-    parent_object parent;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj =  getThis();
+  shapeObj *shape = NULL;
+  php_shape_object *php_shape;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    shape = shapeObj_boundary(php_shape->shape);
-    if (shape == NULL)
-        RETURN_FALSE;
+  shape = shapeObj_boundary(php_shape->shape);
+  if (shape == NULL)
+    RETURN_FALSE;
 
-    MAPSCRIPT_MAKE_PARENT(NULL, NULL);
-    mapscript_create_shape(shape, parent, NULL, return_value TSRMLS_CC);
+  MAPSCRIPT_MAKE_PARENT(NULL, NULL);
+  mapscript_create_shape(shape, parent, NULL, return_value TSRMLS_CC);
 }
 /* }}} */
 
@@ -574,27 +575,25 @@ PHP_METHOD(shapeObj, boundary)
    in the shape. Use3d underlying msGEOSContains GEOS library*/
 PHP_METHOD(shapeObj, containsShape)
 {
-    zval *zobj =  getThis();
-    zval *zshape;
-    php_shape_object *php_shape, *php_shape2;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
-                              &zshape, mapscript_ce_shape) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj =  getThis();
+  zval *zshape;
+  php_shape_object *php_shape, *php_shape2;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
+                            &zshape, mapscript_ce_shape) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_shape2 = (php_shape_object *) zend_object_store_get_object(zshape TSRMLS_CC);
+  php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_shape2 = (php_shape_object *) zend_object_store_get_object(zshape TSRMLS_CC);
 
-    if (shapeObj_contains_geos(php_shape->shape, php_shape2->shape))
-    {
-      RETURN_TRUE;
-    }
-    else
-      RETURN_FALSE; 
+  if (shapeObj_contains_geos(php_shape->shape, php_shape2->shape)) {
+    RETURN_TRUE;
+  } else
+    RETURN_FALSE;
 
 }
 /* }}} */
@@ -604,30 +603,30 @@ PHP_METHOD(shapeObj, containsShape)
    given in argument 1 . Uses underlying GEOS library*/
 PHP_METHOD(shapeObj, union)
 {
-    zval *zobj =  getThis();
-    zval *zshape;
-    shapeObj *shape;
-    php_shape_object *php_shape, *php_shape2;
-    parent_object parent;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
-                              &zshape, mapscript_ce_shape) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj =  getThis();
+  zval *zshape;
+  shapeObj *shape;
+  php_shape_object *php_shape, *php_shape2;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
+                            &zshape, mapscript_ce_shape) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_shape2 = (php_shape_object *) zend_object_store_get_object(zshape TSRMLS_CC);
 
-    php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_shape2 = (php_shape_object *) zend_object_store_get_object(zshape TSRMLS_CC);
+  shape = shapeObj_Union(php_shape->shape, php_shape2->shape);
 
-    shape = shapeObj_Union(php_shape->shape, php_shape2->shape);
-    
-    if (shape  == NULL)
-        RETURN_FALSE;
+  if (shape  == NULL)
+    RETURN_FALSE;
 
-    MAPSCRIPT_MAKE_PARENT(NULL, NULL);
-    mapscript_create_shape(shape, parent, NULL, return_value TSRMLS_CC);
+  MAPSCRIPT_MAKE_PARENT(NULL, NULL);
+  mapscript_create_shape(shape, parent, NULL, return_value TSRMLS_CC);
 }
 /* }}} */
 
@@ -636,30 +635,30 @@ PHP_METHOD(shapeObj, union)
    given in argument 1 . Uses underlying GEOS library*/
 PHP_METHOD(shapeObj, intersection)
 {
-    zval *zobj =  getThis();
-    zval *zshape;
-    shapeObj *shape;
-    php_shape_object *php_shape, *php_shape2;
-    parent_object parent;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
-                              &zshape, mapscript_ce_shape) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj =  getThis();
+  zval *zshape;
+  shapeObj *shape;
+  php_shape_object *php_shape, *php_shape2;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
+                            &zshape, mapscript_ce_shape) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_shape2 = (php_shape_object *) zend_object_store_get_object(zshape TSRMLS_CC);
 
-    php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_shape2 = (php_shape_object *) zend_object_store_get_object(zshape TSRMLS_CC);
+  shape = shapeObj_intersection(php_shape->shape, php_shape2->shape);
 
-    shape = shapeObj_intersection(php_shape->shape, php_shape2->shape);
-    
-    if (shape  == NULL)
-        RETURN_FALSE;
+  if (shape  == NULL)
+    RETURN_FALSE;
 
-    MAPSCRIPT_MAKE_PARENT(NULL, NULL);
-    mapscript_create_shape(shape, parent, NULL, return_value TSRMLS_CC);
+  MAPSCRIPT_MAKE_PARENT(NULL, NULL);
+  mapscript_create_shape(shape, parent, NULL, return_value TSRMLS_CC);
 }
 /* }}} */
 
@@ -668,62 +667,62 @@ PHP_METHOD(shapeObj, intersection)
    given in argument 1 . Uses underlying GEOS library*/
 PHP_METHOD(shapeObj, difference)
 {
-    zval *zobj =  getThis();
-    zval *zshape;
-    shapeObj *shape;
-    php_shape_object *php_shape, *php_shape2;
-    parent_object parent;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
-                              &zshape, mapscript_ce_shape) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj =  getThis();
+  zval *zshape;
+  shapeObj *shape;
+  php_shape_object *php_shape, *php_shape2;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
+                            &zshape, mapscript_ce_shape) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_shape2 = (php_shape_object *) zend_object_store_get_object(zshape TSRMLS_CC);
 
-    php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_shape2 = (php_shape_object *) zend_object_store_get_object(zshape TSRMLS_CC);
+  shape = shapeObj_difference(php_shape->shape, php_shape2->shape);
 
-    shape = shapeObj_difference(php_shape->shape, php_shape2->shape);
-    
-    if (shape  == NULL)
-        RETURN_FALSE;
+  if (shape  == NULL)
+    RETURN_FALSE;
 
-    MAPSCRIPT_MAKE_PARENT(NULL, NULL);
-    mapscript_create_shape(shape, parent, NULL, return_value TSRMLS_CC);
+  MAPSCRIPT_MAKE_PARENT(NULL, NULL);
+  mapscript_create_shape(shape, parent, NULL, return_value TSRMLS_CC);
 }
 /* }}} */
 
 /* {{{ proto int shape.symdifference(shapeobj shape)
-   Return a shape which is the symetrical difference of the current shape and 
+   Return a shape which is the symetrical difference of the current shape and
    the one given in argument 1 . Uses underlying GEOS library*/
 PHP_METHOD(shapeObj, symdifference)
 {
-    zval *zobj =  getThis();
-    zval *zshape;
-    shapeObj *shape;
-    php_shape_object *php_shape, *php_shape2;
-    parent_object parent;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
-                              &zshape, mapscript_ce_shape) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj =  getThis();
+  zval *zshape;
+  shapeObj *shape;
+  php_shape_object *php_shape, *php_shape2;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
+                            &zshape, mapscript_ce_shape) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_shape2 = (php_shape_object *) zend_object_store_get_object(zshape TSRMLS_CC);
 
-    php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_shape2 = (php_shape_object *) zend_object_store_get_object(zshape TSRMLS_CC);
+  shape = shapeObj_symdifference(php_shape->shape, php_shape2->shape);
 
-    shape = shapeObj_symdifference(php_shape->shape, php_shape2->shape);
-    
-    if (shape  == NULL)
-        RETURN_FALSE;
+  if (shape  == NULL)
+    RETURN_FALSE;
 
-    MAPSCRIPT_MAKE_PARENT(NULL, NULL);
-    mapscript_create_shape(shape, parent, NULL, return_value TSRMLS_CC);
+  MAPSCRIPT_MAKE_PARENT(NULL, NULL);
+  mapscript_create_shape(shape, parent, NULL, return_value TSRMLS_CC);
 }
 /* }}} */
 
@@ -732,27 +731,25 @@ PHP_METHOD(shapeObj, symdifference)
    the shape. Else return false. */
 PHP_METHOD(shapeObj, overlaps)
 {
-    zval *zobj =  getThis();
-    zval *zshape;
-    php_shape_object *php_shape, *php_shape2;
-    
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
-                              &zshape, mapscript_ce_shape) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj =  getThis();
+  zval *zshape;
+  php_shape_object *php_shape, *php_shape2;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
+                            &zshape, mapscript_ce_shape) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_shape2 = (php_shape_object *) zend_object_store_get_object(zshape TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    if (shapeObj_overlaps(php_shape->shape, php_shape2->shape))
-    {
-      RETURN_TRUE;
-    }
-    else
-      RETURN_FALSE; 
+  php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_shape2 = (php_shape_object *) zend_object_store_get_object(zshape TSRMLS_CC);
+
+  if (shapeObj_overlaps(php_shape->shape, php_shape2->shape)) {
+    RETURN_TRUE;
+  } else
+    RETURN_FALSE;
 }
 /* }}} */
 
@@ -761,27 +758,25 @@ PHP_METHOD(shapeObj, overlaps)
    the shape. Else return false. */
 PHP_METHOD(shapeObj, within)
 {
-    zval *zobj =  getThis();
-    zval *zshape;
-    php_shape_object *php_shape, *php_shape2;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
-                              &zshape, mapscript_ce_shape) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj =  getThis();
+  zval *zshape;
+  php_shape_object *php_shape, *php_shape2;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
+                            &zshape, mapscript_ce_shape) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_shape2 = (php_shape_object *) zend_object_store_get_object(zshape TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    if (shapeObj_within(php_shape->shape, php_shape2->shape))
-    {
-      RETURN_TRUE;
-    }
-    else
-      RETURN_FALSE; 
+  php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_shape2 = (php_shape_object *) zend_object_store_get_object(zshape TSRMLS_CC);
+
+  if (shapeObj_within(php_shape->shape, php_shape2->shape)) {
+    RETURN_TRUE;
+  } else
+    RETURN_FALSE;
 
 }
 /* }}} */
@@ -791,27 +786,25 @@ PHP_METHOD(shapeObj, within)
    the shape. Else return false. */
 PHP_METHOD(shapeObj, crosses)
 {
-    zval *zobj =  getThis();
-    zval *zshape;
-    php_shape_object *php_shape, *php_shape2;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
-                              &zshape, mapscript_ce_shape) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj =  getThis();
+  zval *zshape;
+  php_shape_object *php_shape, *php_shape2;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
+                            &zshape, mapscript_ce_shape) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_shape2 = (php_shape_object *) zend_object_store_get_object(zshape TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    if (shapeObj_crosses(php_shape->shape, php_shape2->shape))
-    {
-      RETURN_TRUE;
-    }
-    else
-      RETURN_FALSE;
+  php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_shape2 = (php_shape_object *) zend_object_store_get_object(zshape TSRMLS_CC);
+
+  if (shapeObj_crosses(php_shape->shape, php_shape2->shape)) {
+    RETURN_TRUE;
+  } else
+    RETURN_FALSE;
 }
 /* }}} */
 
@@ -820,27 +813,25 @@ PHP_METHOD(shapeObj, crosses)
    the shape. Else return false. */
 PHP_METHOD(shapeObj, touches)
 {
-    zval *zobj =  getThis();
-    zval *zshape;
-    php_shape_object *php_shape, *php_shape2;
-    
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
-                              &zshape, mapscript_ce_shape) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj =  getThis();
+  zval *zshape;
+  php_shape_object *php_shape, *php_shape2;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
+                            &zshape, mapscript_ce_shape) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_shape2 = (php_shape_object *) zend_object_store_get_object(zshape TSRMLS_CC);
+  php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_shape2 = (php_shape_object *) zend_object_store_get_object(zshape TSRMLS_CC);
 
-    if (shapeObj_touches(php_shape->shape, php_shape2->shape))
-    {
-      RETURN_TRUE;
-    }
-    else
-      RETURN_FALSE;
+  if (shapeObj_touches(php_shape->shape, php_shape2->shape)) {
+    RETURN_TRUE;
+  } else
+    RETURN_FALSE;
 }
 /* }}} */
 
@@ -849,27 +840,25 @@ PHP_METHOD(shapeObj, touches)
    the shape. Else return false. */
 PHP_METHOD(shapeObj, equals)
 {
-    zval *zobj =  getThis();
-    zval *zshape;
-    php_shape_object *php_shape, *php_shape2;
-    
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
-                              &zshape, mapscript_ce_shape) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj =  getThis();
+  zval *zshape;
+  php_shape_object *php_shape, *php_shape2;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
+                            &zshape, mapscript_ce_shape) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_shape2 = (php_shape_object *) zend_object_store_get_object(zshape TSRMLS_CC);
+  php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_shape2 = (php_shape_object *) zend_object_store_get_object(zshape TSRMLS_CC);
 
-    if (shapeObj_equals(php_shape->shape, php_shape2->shape))
-    {
-      RETURN_TRUE;
-    }
-    else
-      RETURN_FALSE;
+  if (shapeObj_equals(php_shape->shape, php_shape2->shape)) {
+    RETURN_TRUE;
+  } else
+    RETURN_FALSE;
 }
 /* }}} */
 
@@ -878,27 +867,25 @@ PHP_METHOD(shapeObj, equals)
    the shape. Else return false. */
 PHP_METHOD(shapeObj, disjoint)
 {
-    zval *zobj =  getThis();
-    zval *zshape;
-    php_shape_object *php_shape, *php_shape2;
-    
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
-                              &zshape, mapscript_ce_shape) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj =  getThis();
+  zval *zshape;
+  php_shape_object *php_shape, *php_shape2;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
+                            &zshape, mapscript_ce_shape) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_shape2 = (php_shape_object *) zend_object_store_get_object(zshape TSRMLS_CC);
+  php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_shape2 = (php_shape_object *) zend_object_store_get_object(zshape TSRMLS_CC);
 
-    if (shapeObj_disjoint(php_shape->shape, php_shape2->shape))
-    {
-      RETURN_TRUE;
-    }
-    else
-      RETURN_FALSE;
+  if (shapeObj_disjoint(php_shape->shape, php_shape2->shape)) {
+    RETURN_TRUE;
+  } else
+    RETURN_FALSE;
 }
 /* }}} */
 
@@ -906,27 +893,27 @@ PHP_METHOD(shapeObj, disjoint)
    Given a shape, return a point object representing the centroid */
 PHP_METHOD(shapeObj, getCentroid)
 {
-    zval *zobj =  getThis();
-    pointObj *point;
-    php_shape_object *php_shape;
-    parent_object parent;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj =  getThis();
+  pointObj *point;
+  php_shape_object *php_shape;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  point = shapeObj_getcentroid(php_shape->shape);
 
-    point = shapeObj_getcentroid(php_shape->shape);
-    
-    if (point  == NULL)
-        RETURN_FALSE;
+  if (point  == NULL)
+    RETURN_FALSE;
 
-    MAPSCRIPT_MAKE_PARENT(NULL, NULL);
-    mapscript_create_point(point, parent, return_value TSRMLS_CC);
+  MAPSCRIPT_MAKE_PARENT(NULL, NULL);
+  mapscript_create_point(point, parent, return_value TSRMLS_CC);
 }
 /* }}} */
 
@@ -934,22 +921,22 @@ PHP_METHOD(shapeObj, getCentroid)
    Returns the area  of the shape */
 PHP_METHOD(shapeObj, getArea)
 {
-    zval *zobj =  getThis();
-    double area = 0;
-    php_shape_object *php_shape;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj =  getThis();
+  double area = 0;
+  php_shape_object *php_shape;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    area = shapeObj_getarea(php_shape->shape);
-    
-    RETURN_DOUBLE(area);
+  area = shapeObj_getarea(php_shape->shape);
+
+  RETURN_DOUBLE(area);
 }
 /* }}} */
 
@@ -957,22 +944,22 @@ PHP_METHOD(shapeObj, getArea)
    Returns the length  of the shape */
 PHP_METHOD(shapeObj, getLength)
 {
-    zval *zobj =  getThis();
-    double length = 0;
-    php_shape_object *php_shape;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj =  getThis();
+  double length = 0;
+  php_shape_object *php_shape;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  length = shapeObj_getlength(php_shape->shape);
 
-    length = shapeObj_getlength(php_shape->shape);
-    
-    RETURN_DOUBLE(length);
+  RETURN_DOUBLE(length);
 }
 /* }}} */
 
@@ -980,27 +967,27 @@ PHP_METHOD(shapeObj, getLength)
    Given a shape, return a point object suitable for labelling it */
 PHP_METHOD(shapeObj, getLabelPoint)
 {
-    zval *zobj =  getThis();
-    pointObj *point;
-    php_shape_object *php_shape;
-    parent_object parent;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj =  getThis();
+  pointObj *point;
+  php_shape_object *php_shape;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  point =  shapeObj_getLabelPoint(php_shape->shape);
 
-    point =  shapeObj_getLabelPoint(php_shape->shape);
-    
-    if (point  == NULL)
-        RETURN_FALSE;
+  if (point  == NULL)
+    RETURN_FALSE;
 
-    MAPSCRIPT_MAKE_PARENT(NULL, NULL);
-    mapscript_create_point(point, parent, return_value TSRMLS_CC);
+  MAPSCRIPT_MAKE_PARENT(NULL, NULL);
+  mapscript_create_point(point, parent, return_value TSRMLS_CC);
 }
 /* }}} */
 
@@ -1008,112 +995,111 @@ PHP_METHOD(shapeObj, getLabelPoint)
    Returns WKT representation of geometry. */
 PHP_METHOD(shapeObj, toWkt)
 {
-    zval *zobj =  getThis();
-    char *wkt = NULL;
-    php_shape_object *php_shape;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj =  getThis();
+  char *wkt = NULL;
+  php_shape_object *php_shape;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    wkt = msShapeToWKT(php_shape->shape);
-    if (wkt)
-    {
-        RETVAL_STRING(wkt, 1);
-        msFree(wkt);
-        return;
-    }
+  wkt = msShapeToWKT(php_shape->shape);
+  if (wkt) {
+    RETVAL_STRING(wkt, 1);
+    msFree(wkt);
+    return;
+  }
 
-    RETURN_STRING("", 1);
+  RETURN_STRING("", 1);
 }
 /* }}} */
 
-/* {{{ proto int shape.setBounds() 
+/* {{{ proto int shape.setBounds()
    Updates the bounds property of the shape. Must be called to calculate new
    bounding box after new parts have been added. Returns true if
    successful, else return false.*/
 PHP_METHOD(shapeObj, setBounds)
 {
-    zval *zobj =  getThis();
-    php_shape_object *php_shape;
+  zval *zobj =  getThis();
+  php_shape_object *php_shape;
 
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  shapeObj_setBounds(php_shape->shape);
 
-    shapeObj_setBounds(php_shape->shape);
-    
-    RETURN_LONG(MS_SUCCESS);
+  RETURN_LONG(MS_SUCCESS);
 }
 /* }}} */
 
 /* {{{ proto int shape.simplify(double tolerance)
-   Given a shape and a tolerance, return a simplified shape object using 
+   Given a shape and a tolerance, return a simplified shape object using
    underlying GEOS library */
 PHP_METHOD(shapeObj, simplify)
 {
-    zval *zobj =  getThis();
-    double tolerance;
-    shapeObj *shape = NULL;
-    php_shape_object *php_shape;
-    parent_object parent;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "d",
-                              &tolerance) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj =  getThis();
+  double tolerance;
+  shapeObj *shape = NULL;
+  php_shape_object *php_shape;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "d",
+                            &tolerance) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    shape = shapeObj_simplify(php_shape->shape, tolerance);
-    if (shape  == NULL)
-        RETURN_NULL();
+  shape = shapeObj_simplify(php_shape->shape, tolerance);
+  if (shape  == NULL)
+    RETURN_NULL();
 
-    MAPSCRIPT_MAKE_PARENT(NULL, NULL);
-    mapscript_create_shape(shape, parent, NULL, return_value TSRMLS_CC);
+  MAPSCRIPT_MAKE_PARENT(NULL, NULL);
+  mapscript_create_shape(shape, parent, NULL, return_value TSRMLS_CC);
 }
 /* }}} */
 
 /* {{{ proto int shape.topologypreservingsimplify(double tolerance)
-   Given a shape and a tolerance, return a simplified shape object using 
+   Given a shape and a tolerance, return a simplified shape object using
    underlying GEOS library */
 PHP_METHOD(shapeObj, topologyPreservingSimplify)
 {
-    zval *zobj =  getThis();
-    double tolerance;
-    shapeObj *shape = NULL;
-    php_shape_object *php_shape;
-    parent_object parent;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "d",
-                              &tolerance) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj =  getThis();
+  double tolerance;
+  shapeObj *shape = NULL;
+  php_shape_object *php_shape;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "d",
+                            &tolerance) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    shape = shapeObj_topologypreservingsimplify(php_shape->shape, tolerance);
-    if (shape  == NULL)
-        RETURN_NULL();
+  shape = shapeObj_topologypreservingsimplify(php_shape->shape, tolerance);
+  if (shape  == NULL)
+    RETURN_NULL();
 
-    MAPSCRIPT_MAKE_PARENT(NULL, NULL);
-    mapscript_create_shape(shape, parent, NULL, return_value TSRMLS_CC);
+  MAPSCRIPT_MAKE_PARENT(NULL, NULL);
+  mapscript_create_shape(shape, parent, NULL, return_value TSRMLS_CC);
 }
 /* }}} */
 
@@ -1121,37 +1107,36 @@ PHP_METHOD(shapeObj, topologyPreservingSimplify)
    Draws the individual shape using layer. Returns MS_SUCCESS/MS_FAILURE */
 PHP_METHOD(shapeObj, draw)
 {
-    zval *zobj =  getThis();
-    zval *zmap, *zlayer, *zimage;
-    int status = MS_FAILURE;
-    php_shape_object *php_shape;
-    php_map_object *php_map;
-    php_layer_object *php_layer;
-    php_image_object *php_image;
-    
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "OOO",
-                              &zmap, mapscript_ce_map,
-                              &zlayer, mapscript_ce_layer,
-                              &zimage, mapscript_ce_image) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj =  getThis();
+  zval *zmap, *zlayer, *zimage;
+  int status = MS_FAILURE;
+  php_shape_object *php_shape;
+  php_map_object *php_map;
+  php_layer_object *php_layer;
+  php_image_object *php_image;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "OOO",
+                            &zmap, mapscript_ce_map,
+                            &zlayer, mapscript_ce_layer,
+                            &zimage, mapscript_ce_image) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-
-    php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_map = (php_map_object *) zend_object_store_get_object(zmap TSRMLS_CC);
-    php_layer = (php_layer_object *) zend_object_store_get_object(zlayer TSRMLS_CC);
-    php_image = (php_image_object *) zend_object_store_get_object(zimage TSRMLS_CC);
-
-    if ((status = shapeObj_draw(php_shape->shape, php_map->map, php_layer->layer, 
-                                php_image->image)) != MS_SUCCESS)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
-
-    RETURN_LONG(status);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_map = (php_map_object *) zend_object_store_get_object(zmap TSRMLS_CC);
+  php_layer = (php_layer_object *) zend_object_store_get_object(zlayer TSRMLS_CC);
+  php_image = (php_image_object *) zend_object_store_get_object(zimage TSRMLS_CC);
+
+  if ((status = shapeObj_draw(php_shape->shape, php_map->map, php_layer->layer,
+                              php_image->image)) != MS_SUCCESS) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -1159,146 +1144,192 @@ PHP_METHOD(shapeObj, draw)
    Free the object */
 PHP_METHOD(shapeObj, free)
 {
-    zval *zobj =  getThis();
-    php_shape_object *php_shape;
+  zval *zobj =  getThis();
+  php_shape_object *php_shape;
 
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
+    PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  MAPSCRIPT_DELREF(php_shape->bounds);
+}
+/* }}} */
+
+/* {{{ proto int shape.distanceToPoint(pointObj point)
+   Returns the distance from the point to shape. */
+PHP_METHOD(shapeObj, distanceToPoint)
+{
+  zval *zobj =  getThis();
+  zval *zpoint;
+  php_shape_object *php_shape;
+  php_point_object *php_point;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
+                            &zpoint, mapscript_ce_point) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_point = (php_point_object *) zend_object_store_get_object(zpoint TSRMLS_CC);
 
-    MAPSCRIPT_DELREF(php_shape->bounds);
+  RETURN_DOUBLE(msDistancePointToShape(php_point->point, php_shape->shape));
+}
+/* }}} */
+
+/* {{{ proto int shape.distanceToShape(shapeObj shape)
+   Returns the distance from the shape to shape2. */
+PHP_METHOD(shapeObj, distanceToShape)
+{
+  zval *zobj =  getThis();
+  zval *zshape;
+  php_shape_object *php_shape;
+  php_shape_object *php_shape2;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
+                            &zshape, mapscript_ce_shape) == FAILURE) {
+    PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_shape = (php_shape_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_shape2 = (php_shape_object *) zend_object_store_get_object(zshape TSRMLS_CC);
+
+  RETURN_DOUBLE(msGEOSDistance(php_shape->shape, php_shape2->shape));
 }
 /* }}} */
 
 zend_function_entry shape_functions[] = {
-    PHP_ME(shapeObj, __construct, shape___construct_args, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
-    PHP_ME(shapeObj, __get, shape___get_args, ZEND_ACC_PUBLIC)
-    PHP_ME(shapeObj, __set, shape___set_args, ZEND_ACC_PUBLIC)
-    PHP_MALIAS(shapeObj, set, __set, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(shapeObj, project, shape_project_args, ZEND_ACC_PUBLIC)
-    PHP_ME(shapeObj, add, shape_add_args, ZEND_ACC_PUBLIC)
-    PHP_ME(shapeObj, line, shape_line_args, ZEND_ACC_PUBLIC)
-    PHP_ME(shapeObj, contains, shape_contains_args, ZEND_ACC_PUBLIC)
-    PHP_ME(shapeObj, intersects, shape_intersects_args, ZEND_ACC_PUBLIC)
-    PHP_ME(shapeObj, getPointUsingMeasure, shape_getPointUsingMeasure_args, ZEND_ACC_PUBLIC)
-    PHP_ME(shapeObj, getMeasureUsingPoint, shape_getMeasureUsingPoint_args, ZEND_ACC_PUBLIC)
-    PHP_ME(shapeObj, getValue, shape_getValue_args, ZEND_ACC_PUBLIC)
-    PHP_ME(shapeObj, buffer, shape_buffer_args, ZEND_ACC_PUBLIC)
-    PHP_ME(shapeObj, convexhull, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(shapeObj, boundary, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(shapeObj, containsShape, shape_containsShape_args, ZEND_ACC_PUBLIC)
-    PHP_ME(shapeObj, union, shape_union_args, ZEND_ACC_PUBLIC)
-    PHP_ME(shapeObj, intersection, shape_intersection_args, ZEND_ACC_PUBLIC)
-    PHP_ME(shapeObj, difference, shape_difference_args, ZEND_ACC_PUBLIC)
-    PHP_ME(shapeObj, symdifference, shape_symdifference_args, ZEND_ACC_PUBLIC)
-    PHP_ME(shapeObj, overlaps, shape_overlaps_args, ZEND_ACC_PUBLIC)
-    PHP_ME(shapeObj, within, shape_within_args, ZEND_ACC_PUBLIC)
-    PHP_ME(shapeObj, crosses, shape_crosses_args, ZEND_ACC_PUBLIC)
-    PHP_ME(shapeObj, touches, shape_touches_args, ZEND_ACC_PUBLIC)
-    PHP_ME(shapeObj, equals, shape_equals_args, ZEND_ACC_PUBLIC)
-    PHP_ME(shapeObj, disjoint, shape_disjoint_args, ZEND_ACC_PUBLIC)
-    PHP_ME(shapeObj, getCentroid, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(shapeObj, getArea, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(shapeObj, getLength, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(shapeObj, getLabelPoint, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(shapeObj, toWkt, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(shapeObj, setBounds, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(shapeObj, simplify, shape_simplify_args, ZEND_ACC_PUBLIC)
-    PHP_ME(shapeObj, topologyPreservingSimplify, shape_topologyPreservingSimplify_args, ZEND_ACC_PUBLIC)
-    PHP_ME(shapeObj, draw, shape_draw_args, ZEND_ACC_PUBLIC)
-    PHP_ME(shapeObj, free, NULL, ZEND_ACC_PUBLIC)
-    {NULL, NULL, NULL}
+  PHP_ME(shapeObj, __construct, shape___construct_args, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
+  PHP_ME(shapeObj, __get, shape___get_args, ZEND_ACC_PUBLIC)
+  PHP_ME(shapeObj, __set, shape___set_args, ZEND_ACC_PUBLIC)
+  PHP_MALIAS(shapeObj, set, __set, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(shapeObj, project, shape_project_args, ZEND_ACC_PUBLIC)
+  PHP_ME(shapeObj, add, shape_add_args, ZEND_ACC_PUBLIC)
+  PHP_ME(shapeObj, line, shape_line_args, ZEND_ACC_PUBLIC)
+  PHP_ME(shapeObj, contains, shape_contains_args, ZEND_ACC_PUBLIC)
+  PHP_ME(shapeObj, intersects, shape_intersects_args, ZEND_ACC_PUBLIC)
+  PHP_ME(shapeObj, getPointUsingMeasure, shape_getPointUsingMeasure_args, ZEND_ACC_PUBLIC)
+  PHP_ME(shapeObj, getMeasureUsingPoint, shape_getMeasureUsingPoint_args, ZEND_ACC_PUBLIC)
+  PHP_ME(shapeObj, getValue, shape_getValue_args, ZEND_ACC_PUBLIC)
+  PHP_ME(shapeObj, buffer, shape_buffer_args, ZEND_ACC_PUBLIC)
+  PHP_ME(shapeObj, convexhull, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(shapeObj, boundary, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(shapeObj, containsShape, shape_containsShape_args, ZEND_ACC_PUBLIC)
+  PHP_ME(shapeObj, union, shape_union_args, ZEND_ACC_PUBLIC)
+  PHP_ME(shapeObj, intersection, shape_intersection_args, ZEND_ACC_PUBLIC)
+  PHP_ME(shapeObj, difference, shape_difference_args, ZEND_ACC_PUBLIC)
+  PHP_ME(shapeObj, symdifference, shape_symdifference_args, ZEND_ACC_PUBLIC)
+  PHP_ME(shapeObj, overlaps, shape_overlaps_args, ZEND_ACC_PUBLIC)
+  PHP_ME(shapeObj, within, shape_within_args, ZEND_ACC_PUBLIC)
+  PHP_ME(shapeObj, crosses, shape_crosses_args, ZEND_ACC_PUBLIC)
+  PHP_ME(shapeObj, touches, shape_touches_args, ZEND_ACC_PUBLIC)
+  PHP_ME(shapeObj, equals, shape_equals_args, ZEND_ACC_PUBLIC)
+  PHP_ME(shapeObj, disjoint, shape_disjoint_args, ZEND_ACC_PUBLIC)
+  PHP_ME(shapeObj, getCentroid, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(shapeObj, getArea, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(shapeObj, getLength, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(shapeObj, getLabelPoint, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(shapeObj, toWkt, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(shapeObj, setBounds, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(shapeObj, simplify, shape_simplify_args, ZEND_ACC_PUBLIC)
+  PHP_ME(shapeObj, topologyPreservingSimplify, shape_topologyPreservingSimplify_args, ZEND_ACC_PUBLIC)
+  PHP_ME(shapeObj, draw, shape_draw_args, ZEND_ACC_PUBLIC)
+  PHP_ME(shapeObj, distanceToPoint, shape_distanceToPoint_args, ZEND_ACC_PUBLIC)
+  PHP_ME(shapeObj, distanceToShape, shape_distanceToShape_args, ZEND_ACC_PUBLIC)
+  PHP_ME(shapeObj, free, NULL, ZEND_ACC_PUBLIC) {
+    NULL, NULL, NULL
+  }
 };
 
 
 void mapscript_create_shape(shapeObj *shape, parent_object parent, php_layer_object *php_layer, zval *return_value TSRMLS_DC)
 {
-    php_shape_object *php_shape;
-
-    int i;
-
-    object_init_ex(return_value, mapscript_ce_shape); 
-    php_shape = (php_shape_object *)zend_object_store_get_object(return_value TSRMLS_CC);
-    php_shape->shape = shape;
-
-    MAKE_STD_ZVAL(php_shape->values);
-    array_init(php_shape->values);
-
-    if (php_layer)
-    {
-        if ((php_shape->shape->numvalues == php_layer->layer->numitems) ||
-            (php_shape->shape->numvalues == 0 && php_layer->layer->numitems == -1))
-        {
-            for(i=0; i<php_shape->shape->numvalues; i++)
-            {
-                add_assoc_string(php_shape->values, php_layer->layer->items[i], php_shape->shape->values[i], 1);
-            }
-        }
-        else
-        {
-            mapscript_throw_exception("Assertion failed, Could not set shape values: %d, %d" TSRMLS_CC,
-                                      php_shape->shape->numvalues, php_layer->layer->numitems);
-            return;
-        }
+  php_shape_object *php_shape;
+
+  int i;
+
+  object_init_ex(return_value, mapscript_ce_shape);
+  php_shape = (php_shape_object *)zend_object_store_get_object(return_value TSRMLS_CC);
+  php_shape->shape = shape;
+
+  MAKE_STD_ZVAL(php_shape->values);
+  array_init(php_shape->values);
+
+  if (php_layer) {
+    if ((php_shape->shape->numvalues == php_layer->layer->numitems) ||
+        (php_shape->shape->numvalues == 0 && php_layer->layer->numitems == -1)) {
+      for(i=0; i<php_shape->shape->numvalues; i++) {
+        add_assoc_string(php_shape->values, php_layer->layer->items[i], php_shape->shape->values[i], 1);
+      }
+    } else {
+      mapscript_throw_exception("Assertion failed, Could not set shape values: %d, %d" TSRMLS_CC,
+                                php_shape->shape->numvalues, php_layer->layer->numitems);
+      return;
     }
+  }
 
-    if (parent.val)
-        php_shape->is_ref = 1;
+  if (parent.val)
+    php_shape->is_ref = 1;
 
-    php_shape->parent = parent;
-    MAPSCRIPT_ADDREF(parent.val);
+  php_shape->parent = parent;
+  MAPSCRIPT_ADDREF(parent.val);
 }
 
 static void mapscript_shape_object_destroy(void *object TSRMLS_DC)
 {
-    php_shape_object *php_shape = (php_shape_object *)object;
+  php_shape_object *php_shape = (php_shape_object *)object;
 
-    MAPSCRIPT_FREE_OBJECT(php_shape);
+  MAPSCRIPT_FREE_OBJECT(php_shape);
 
-    MAPSCRIPT_FREE_PARENT(php_shape->parent);
-    MAPSCRIPT_DELREF(php_shape->bounds);
-    MAPSCRIPT_DELREF(php_shape->values);
+  MAPSCRIPT_FREE_PARENT(php_shape->parent);
+  MAPSCRIPT_DELREF(php_shape->bounds);
+  MAPSCRIPT_DELREF(php_shape->values);
 
-    if (php_shape->shape && !php_shape->is_ref) {
-        shapeObj_destroy(php_shape->shape);
-    }
+  if (php_shape->shape && !php_shape->is_ref) {
+    shapeObj_destroy(php_shape->shape);
+  }
 
-    efree(object);
+  efree(object);
 }
 
 static zend_object_value mapscript_shape_object_new(zend_class_entry *ce TSRMLS_DC)
 {
-    zend_object_value retval;
-    php_shape_object *php_shape;
+  zend_object_value retval;
+  php_shape_object *php_shape;
 
-    MAPSCRIPT_ALLOC_OBJECT(php_shape, php_shape_object);
+  MAPSCRIPT_ALLOC_OBJECT(php_shape, php_shape_object);
 
-    retval = mapscript_object_new(&php_shape->std, ce,
-                                  &mapscript_shape_object_destroy TSRMLS_CC);
+  retval = mapscript_object_new(&php_shape->std, ce,
+                                &mapscript_shape_object_destroy TSRMLS_CC);
 
-    php_shape->is_ref = 0;
-    MAPSCRIPT_INIT_PARENT(php_shape->parent);
-    php_shape->bounds = NULL;
-    php_shape->values = NULL;
+  php_shape->is_ref = 0;
+  MAPSCRIPT_INIT_PARENT(php_shape->parent);
+  php_shape->bounds = NULL;
+  php_shape->values = NULL;
 
-    return retval;
+  return retval;
 }
 
 PHP_MINIT_FUNCTION(shape)
 {
-    zend_class_entry ce;
+  zend_class_entry ce;
+
+  MAPSCRIPT_REGISTER_CLASS("shapeObj",
+                           shape_functions,
+                           mapscript_ce_shape,
+                           mapscript_shape_object_new);
 
-    MAPSCRIPT_REGISTER_CLASS("shapeObj", 
-                             shape_functions,
-                             mapscript_ce_shape,
-                             mapscript_shape_object_new);
+  mapscript_ce_shape->ce_flags |= ZEND_ACC_FINAL_CLASS;
 
-    mapscript_ce_shape->ce_flags |= ZEND_ACC_FINAL_CLASS; 
-    
-    return SUCCESS;
+  return SUCCESS;
 }
diff --git a/mapscript/php/shapefile.c b/mapscript/php/shapefile.c
index cb02ccc..aa654cf 100644
--- a/mapscript/php/shapefile.c
+++ b/mapscript/php/shapefile.c
@@ -2,7 +2,7 @@
  * $Id: php_mapscript.c 9765 2010-01-28 15:32:10Z aboudreault $
  *
  * Project:  MapServer
- * Purpose:  PHP/MapScript extension for MapServer.  External interface 
+ * Purpose:  PHP/MapScript extension for MapServer.  External interface
  *           functions
  * Author:   Daniel Morissette, DM Solutions Group (dmorissette at dmsolutions.ca)
  *           Alan Boudreault, Mapgears
@@ -16,16 +16,16 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
+ *
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  * DEALINGS IN THE SOFTWARE.
  **********************************************************************/
 
@@ -34,171 +34,168 @@
 zend_class_entry *mapscript_ce_shapefile;
 
 ZEND_BEGIN_ARG_INFO_EX(shapefile___construct_args, 0, 0, 2)
-  ZEND_ARG_INFO(0, filename)
-  ZEND_ARG_INFO(0, type)
+ZEND_ARG_INFO(0, filename)
+ZEND_ARG_INFO(0, type)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(shapefile___get_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, property)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(shapefile___set_args, 0, 0, 2)
-  ZEND_ARG_INFO(0, property)
-  ZEND_ARG_INFO(0, value)
+ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, value)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(shapefile_getShape_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, index)
+ZEND_ARG_INFO(0, index)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(shapefile_getPoint_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, index)
+ZEND_ARG_INFO(0, index)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(shapefile_getExtent_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, index)
+ZEND_ARG_INFO(0, index)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(shapefile_addShape_args, 0, 0, 1)
-  ZEND_ARG_OBJ_INFO(0, shape, shapeObj, 0)
+ZEND_ARG_OBJ_INFO(0, shape, shapeObj, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(shapefile_addPoint_args, 0, 0, 1)
-  ZEND_ARG_OBJ_INFO(0, point, pointObj, 0)
+ZEND_ARG_OBJ_INFO(0, point, pointObj, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(shapefile_getTransformed_args, 0, 0, 2)
-  ZEND_ARG_OBJ_INFO(0, map, mapObj, 0)
-  ZEND_ARG_INFO(0, index)
+ZEND_ARG_OBJ_INFO(0, map, mapObj, 0)
+ZEND_ARG_INFO(0, index)
 ZEND_END_ARG_INFO()
 
 /* {{{ proto shapefile __construct(string filename, int type)
    Create a new shapeFileObj instance. */
 PHP_METHOD(shapeFileObj, __construct)
 {
-    zval *zobj = getThis();
-    php_shapefile_object *php_shapefile;
-    char *filename;
-    long filename_len;
-    long type;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sl",
-                              &filename, &filename_len, &type) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  php_shapefile_object *php_shapefile;
+  char *filename;
+  long filename_len;
+  long type;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sl",
+                            &filename, &filename_len, &type) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_shapefile = (php_shapefile_object *)zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    php_shapefile->shapefile = shapefileObj_new(filename, type);
+  php_shapefile = (php_shapefile_object *)zend_object_store_get_object(zobj TSRMLS_CC);
 
-    if (php_shapefile->shapefile == NULL)
-    {
-        mapscript_throw_mapserver_exception("Failed to open shapefile %s" TSRMLS_CC, filename);
-        return;
-    }
+  php_shapefile->shapefile = shapefileObj_new(filename, type);
+
+  if (php_shapefile->shapefile == NULL) {
+    mapscript_throw_mapserver_exception("Failed to open shapefile %s" TSRMLS_CC, filename);
+    return;
+  }
 }
 /* }}} */
 
 PHP_METHOD(shapeFileObj, __get)
 {
-    char *property;
-    long property_len;
-    zval *zobj = getThis();
-    php_shapefile_object *php_shapefile;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &property, &property_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *zobj = getThis();
+  php_shapefile_object *php_shapefile;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &property, &property_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_shapefile = (php_shapefile_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-
-    IF_GET_LONG("numshapes", php_shapefile->shapefile->numshapes) 
-    else IF_GET_LONG("type", php_shapefile->shapefile->type) 
-    else IF_GET_STRING("source", php_shapefile->shapefile->source) 
-    else IF_GET_OBJECT("bounds", mapscript_ce_rect, php_shapefile->bounds, &php_shapefile->shapefile->bounds) 
-    else 
-    {
-        mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_shapefile = (php_shapefile_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  IF_GET_LONG("numshapes", php_shapefile->shapefile->numshapes)
+  else IF_GET_LONG("type", php_shapefile->shapefile->type)
+    else IF_GET_LONG("isopen", php_shapefile->shapefile->isopen)
+      else IF_GET_LONG("lastshape", php_shapefile->shapefile->lastshape)
+        else IF_GET_STRING("source", php_shapefile->shapefile->source)
+          else IF_GET_OBJECT("bounds", mapscript_ce_rect, php_shapefile->bounds, &php_shapefile->shapefile->bounds)
+            else {
+              mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+            }
 }
 
 PHP_METHOD(shapeFileObj, __set)
 {
-    char *property;
-    long property_len;
-    zval *value;
-    zval *zobj = getThis();
-    php_shapefile_object *php_shapefile;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
-                              &property, &property_len, &value) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *value;
+  zval *zobj = getThis();
+  php_shapefile_object *php_shapefile;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
+                            &property, &property_len, &value) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_shapefile = (php_shapefile_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-
-    if ( (STRING_EQUAL("numshapes", property)) ||
-         (STRING_EQUAL("type", property)) ||
-         (STRING_EQUAL("source", property)) ||
-         (STRING_EQUAL("bounds", property)) )
-    {
-        mapscript_throw_exception("Property '%s' is read-only and cannot be set." TSRMLS_CC, property);
-    }
-    else 
-    {
-        mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_shapefile = (php_shapefile_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  if ( (STRING_EQUAL("numshapes", property)) ||
+       (STRING_EQUAL("type", property)) ||
+       (STRING_EQUAL("source", property)) ||
+       (STRING_EQUAL("isopen", property)) ||
+       (STRING_EQUAL("lastshape", property)) ||
+       (STRING_EQUAL("bounds", property)) ) {
+    mapscript_throw_exception("Property '%s' is read-only and cannot be set." TSRMLS_CC, property);
+  } else {
+    mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+  }
 }
 
 /* {{{ proto int shapefile.getShape(int i)
    Retrieve shape by index. */
 PHP_METHOD(shapeFileObj, getShape)
 {
-    zval *zobj =  getThis();
-    long index;
-    shapeObj *shape;
-    php_shapefile_object *php_shapefile;
-    parent_object parent;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
-                              &index) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj =  getThis();
+  long index;
+  shapeObj *shape;
+  php_shapefile_object *php_shapefile;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
+                            &index) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-
-    php_shapefile = (php_shapefile_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-
-    /* Create a new shapeObj to hold the result 
-     * Note that the type used to create the shape (MS_NULL) does not matter
-     * at this point since it will be set by SHPReadShape().
-     */
-    if ((shape = shapeObj_new(MS_SHAPE_NULL)) == NULL)
-    {
-        mapscript_throw_mapserver_exception("Failed creating new shape (out of memory?)" TSRMLS_CC);
-        return;
-    }
-
-    if (shapefileObj_get(php_shapefile->shapefile, index, shape) != MS_SUCCESS) 
-    {
-        shapeObj_destroy(shape);
-        mapscript_throw_mapserver_exception("Failed reading shape %ld." TSRMLS_CC, index);
-        return;
-    }
-
-    MAPSCRIPT_MAKE_PARENT(NULL, NULL);
-    mapscript_create_shape(shape, parent, NULL, return_value TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_shapefile = (php_shapefile_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  /* Create a new shapeObj to hold the result
+   * Note that the type used to create the shape (MS_NULL) does not matter
+   * at this point since it will be set by SHPReadShape().
+   */
+  if ((shape = shapeObj_new(MS_SHAPE_NULL)) == NULL) {
+    mapscript_throw_mapserver_exception("Failed creating new shape (out of memory?)" TSRMLS_CC);
+    return;
+  }
+
+  if (shapefileObj_get(php_shapefile->shapefile, index, shape) != MS_SUCCESS) {
+    shapeObj_destroy(shape);
+    mapscript_throw_mapserver_exception("Failed reading shape %ld." TSRMLS_CC, index);
+    return;
+  }
+
+  MAPSCRIPT_MAKE_PARENT(NULL, NULL);
+  mapscript_create_shape(shape, parent, NULL, return_value TSRMLS_CC);
 }
 /* }}} */
 
@@ -206,43 +203,41 @@ PHP_METHOD(shapeFileObj, getShape)
    Retrieve a point by index. */
 PHP_METHOD(shapeFileObj, getPoint)
 {
-    zval *zobj =  getThis();
-    long index;
-    pointObj *point;
-    php_shapefile_object *php_shapefile;
-    parent_object parent;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
-                              &index) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj =  getThis();
+  long index;
+  pointObj *point;
+  php_shapefile_object *php_shapefile;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
+                            &index) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-
-    php_shapefile = (php_shapefile_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-
-    /* Create a new shapeObj to hold the result 
-     * Note that the type used to create the shape (MS_NULL) does not matter
-     * at this point since it will be set by SHPReadShape().
-     */
-    /* Create a new PointObj to hold the result */
-    if ((point = pointObj_new()) == NULL)
-    {
-        mapscript_throw_mapserver_exception("Failed creating new point (out of memory?)" TSRMLS_CC);
-        return;
-    }
-
-    /* Read from the file */
-    if (shapefileObj_getPoint(php_shapefile->shapefile, index, point) != MS_SUCCESS)
-    {
-        pointObj_destroy(point);
-        mapscript_throw_mapserver_exception("Failed reading point %ld." TSRMLS_CC, index);
-        return;
-    }
-
-    MAPSCRIPT_MAKE_PARENT(NULL, NULL);
-    mapscript_create_point(point, parent, return_value TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_shapefile = (php_shapefile_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  /* Create a new shapeObj to hold the result
+   * Note that the type used to create the shape (MS_NULL) does not matter
+   * at this point since it will be set by SHPReadShape().
+   */
+  /* Create a new PointObj to hold the result */
+  if ((point = pointObj_new()) == NULL) {
+    mapscript_throw_mapserver_exception("Failed creating new point (out of memory?)" TSRMLS_CC);
+    return;
+  }
+
+  /* Read from the file */
+  if (shapefileObj_getPoint(php_shapefile->shapefile, index, point) != MS_SUCCESS) {
+    pointObj_destroy(point);
+    mapscript_throw_mapserver_exception("Failed reading point %ld." TSRMLS_CC, index);
+    return;
+  }
+
+  MAPSCRIPT_MAKE_PARENT(NULL, NULL);
+  mapscript_create_point(point, parent, return_value TSRMLS_CC);
 }
 /* }}} */
 
@@ -251,37 +246,36 @@ PHP_METHOD(shapeFileObj, getPoint)
 
 PHP_METHOD(shapeFileObj, getExtent)
 {
-    zval *zobj =  getThis();
-    long index;
-    rectObj *rect;
-    php_shapefile_object *php_shapefile;
-    parent_object p;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
-                              &index) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj =  getThis();
+  long index;
+  rectObj *rect;
+  php_shapefile_object *php_shapefile;
+  parent_object p;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
+                            &index) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-
-    php_shapefile = (php_shapefile_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-
-    /* Create a new rectObj to hold the result */
-    if ((rect = rectObj_new()) == NULL)
-    {
-        mapscript_throw_mapserver_exception("Failed creating new rectObj (out of memory?)" TSRMLS_CC);
-        return;
-    }
-
-    /* Read from the file 
-     * shapefileObj_getExtent() has no return value!  How do we catch errors?
-     */
-    shapefileObj_getExtent(php_shapefile->shapefile, index, rect);
-
-    /* Return rectObj */
-    MAPSCRIPT_INIT_PARENT(p);
-    mapscript_create_rect(rect, p, return_value TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_shapefile = (php_shapefile_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  /* Create a new rectObj to hold the result */
+  if ((rect = rectObj_new()) == NULL) {
+    mapscript_throw_mapserver_exception("Failed creating new rectObj (out of memory?)" TSRMLS_CC);
+    return;
+  }
+
+  /* Read from the file
+   * shapefileObj_getExtent() has no return value!  How do we catch errors?
+   */
+  shapefileObj_getExtent(php_shapefile->shapefile, index, rect);
+
+  /* Return rectObj */
+  MAPSCRIPT_INIT_PARENT(p);
+  mapscript_create_rect(rect, p, return_value TSRMLS_CC);
 }
 /* }}} */
 
@@ -289,26 +283,26 @@ PHP_METHOD(shapeFileObj, getExtent)
    Appends a shape to an open shapefile. */
 PHP_METHOD(shapeFileObj, addShape)
 {
-    zval *zobj =  getThis();
-    zval *zshape;
-    php_shapefile_object *php_shapefile;
-    php_shape_object *php_shape;
-    int retval = MS_FAILURE;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
-                              &zshape, mapscript_ce_shape) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj =  getThis();
+  zval *zshape;
+  php_shapefile_object *php_shapefile;
+  php_shape_object *php_shape;
+  int retval = MS_FAILURE;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
+                            &zshape, mapscript_ce_shape) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_shapefile = (php_shapefile_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_shape = (php_shape_object *) zend_object_store_get_object(zshape TSRMLS_CC);
+  php_shapefile = (php_shapefile_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_shape = (php_shape_object *) zend_object_store_get_object(zshape TSRMLS_CC);
 
-    retval = shapefileObj_add(php_shapefile->shapefile, php_shape->shape);
+  retval = shapefileObj_add(php_shapefile->shapefile, php_shape->shape);
 
-    RETURN_LONG(retval);
+  RETURN_LONG(retval);
 }
 /* }}} */
 
@@ -316,26 +310,26 @@ PHP_METHOD(shapeFileObj, addShape)
    Appends a point to a poin layer. */
 PHP_METHOD(shapeFileObj, addPoint)
 {
-    zval *zobj =  getThis();
-    zval *zpoint;
-    php_shapefile_object *php_shapefile;
-    php_point_object *php_point;
-    int retval = MS_FAILURE;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
-                              &zpoint, mapscript_ce_point) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj =  getThis();
+  zval *zpoint;
+  php_shapefile_object *php_shapefile;
+  php_point_object *php_point;
+  int retval = MS_FAILURE;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
+                            &zpoint, mapscript_ce_point) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_shapefile = (php_shapefile_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_point = (php_point_object *) zend_object_store_get_object(zpoint TSRMLS_CC);
+  php_shapefile = (php_shapefile_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_point = (php_point_object *) zend_object_store_get_object(zpoint TSRMLS_CC);
 
-    retval = shapefileObj_addPoint(php_shapefile->shapefile, php_point->point);
+  retval = shapefileObj_addPoint(php_shapefile->shapefile, php_point->point);
 
-    RETURN_LONG(retval);
+  RETURN_LONG(retval);
 }
 /* }}} */
 
@@ -343,47 +337,45 @@ PHP_METHOD(shapeFileObj, addPoint)
    Retrieve shape by index. */
 PHP_METHOD(shapeFileObj, getTransformed)
 {
-    zval *zobj =  getThis();
-    zval *zmap;
-    long index;
-    php_shapefile_object *php_shapefile;
-    php_map_object *php_map;
-    shapeObj *shape = NULL;    
-    parent_object parent;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Ol",
-                              &zmap, mapscript_ce_map, &index) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj =  getThis();
+  zval *zmap;
+  long index;
+  php_shapefile_object *php_shapefile;
+  php_map_object *php_map;
+  shapeObj *shape = NULL;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Ol",
+                            &zmap, mapscript_ce_map, &index) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-
-    php_shapefile = (php_shapefile_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    php_map = (php_map_object *) zend_object_store_get_object(zmap TSRMLS_CC);
-
-    /* Create a new shapeObj to hold the result 
-     * Note that the type used to create the shape (MS_NULL) does not matter
-     * at this point since it will be set by SHPReadShape().
-     */
-    if ((shape = shapeObj_new(MS_SHAPE_NULL)) == NULL)
-    {
-        mapscript_throw_mapserver_exception("Failed creating new shape (out of memory?)" TSRMLS_CC);
-        return;
-    }
-
-    /* Read from the file */
-    if (shapefileObj_getTransformed(php_shapefile->shapefile, php_map->map, 
-                                    index, shape) != MS_SUCCESS)
-    {
-        shapeObj_destroy(shape);
-        mapscript_throw_mapserver_exception("Failed reading shape %ld." TSRMLS_CC, index);
-        return;
-    }
-
-    /* Return shape object */
-    MAPSCRIPT_MAKE_PARENT(NULL, NULL);
-    mapscript_create_shape(shape, parent, NULL, return_value TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_shapefile = (php_shapefile_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_map = (php_map_object *) zend_object_store_get_object(zmap TSRMLS_CC);
+
+  /* Create a new shapeObj to hold the result
+   * Note that the type used to create the shape (MS_NULL) does not matter
+   * at this point since it will be set by SHPReadShape().
+   */
+  if ((shape = shapeObj_new(MS_SHAPE_NULL)) == NULL) {
+    mapscript_throw_mapserver_exception("Failed creating new shape (out of memory?)" TSRMLS_CC);
+    return;
+  }
+
+  /* Read from the file */
+  if (shapefileObj_getTransformed(php_shapefile->shapefile, php_map->map,
+                                  index, shape) != MS_SUCCESS) {
+    shapeObj_destroy(shape);
+    mapscript_throw_mapserver_exception("Failed reading shape %ld." TSRMLS_CC, index);
+    return;
+  }
+
+  /* Return shape object */
+  MAPSCRIPT_MAKE_PARENT(NULL, NULL);
+  mapscript_create_shape(shape, parent, NULL, return_value TSRMLS_CC);
 }
 /* }}} */
 
@@ -391,84 +383,85 @@ PHP_METHOD(shapeFileObj, getTransformed)
    Free the object  */
 PHP_METHOD(shapeFileObj, free)
 {
-    zval *zobj =  getThis();
-    php_shapefile_object *php_shapefile;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj =  getThis();
+  php_shapefile_object *php_shapefile;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_shapefile = (php_shapefile_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    php_shapefile = (php_shapefile_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    MAPSCRIPT_DELREF(php_shapefile->bounds);
+  MAPSCRIPT_DELREF(php_shapefile->bounds);
 }
 /* }}} */
 
 zend_function_entry shapefile_functions[] = {
-    PHP_ME(shapeFileObj, __construct, shapefile___construct_args, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
-    PHP_ME(shapeFileObj, __get, shapefile___get_args, ZEND_ACC_PUBLIC)
-    PHP_ME(shapeFileObj, __set, shapefile___set_args, ZEND_ACC_PUBLIC)
-    PHP_ME(shapeFileObj, getShape, shapefile_getShape_args, ZEND_ACC_PUBLIC)
-    PHP_ME(shapeFileObj, getPoint, shapefile_getPoint_args, ZEND_ACC_PUBLIC)
-    PHP_ME(shapeFileObj, getExtent, shapefile_getExtent_args, ZEND_ACC_PUBLIC)
-    PHP_ME(shapeFileObj, addShape, shapefile_addShape_args, ZEND_ACC_PUBLIC)
-    PHP_ME(shapeFileObj, addPoint, shapefile_addPoint_args, ZEND_ACC_PUBLIC)
-    PHP_ME(shapeFileObj, getTransformed, shapefile_getTransformed_args, ZEND_ACC_PUBLIC)
-    PHP_ME(shapeFileObj, free, NULL, ZEND_ACC_PUBLIC)
-    {NULL, NULL, NULL}
+  PHP_ME(shapeFileObj, __construct, shapefile___construct_args, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
+  PHP_ME(shapeFileObj, __get, shapefile___get_args, ZEND_ACC_PUBLIC)
+  PHP_ME(shapeFileObj, __set, shapefile___set_args, ZEND_ACC_PUBLIC)
+  PHP_ME(shapeFileObj, getShape, shapefile_getShape_args, ZEND_ACC_PUBLIC)
+  PHP_ME(shapeFileObj, getPoint, shapefile_getPoint_args, ZEND_ACC_PUBLIC)
+  PHP_ME(shapeFileObj, getExtent, shapefile_getExtent_args, ZEND_ACC_PUBLIC)
+  PHP_ME(shapeFileObj, addShape, shapefile_addShape_args, ZEND_ACC_PUBLIC)
+  PHP_ME(shapeFileObj, addPoint, shapefile_addPoint_args, ZEND_ACC_PUBLIC)
+  PHP_ME(shapeFileObj, getTransformed, shapefile_getTransformed_args, ZEND_ACC_PUBLIC)
+  PHP_ME(shapeFileObj, free, NULL, ZEND_ACC_PUBLIC) {
+    NULL, NULL, NULL
+  }
 };
 
 
 void mapscript_create_shapefile(shapefileObj *shapefile, zval *return_value TSRMLS_DC)
 {
-    php_shapefile_object * php_shapefile;
+  php_shapefile_object * php_shapefile;
 
-    object_init_ex(return_value, mapscript_ce_shapefile); 
-    php_shapefile = (php_shapefile_object *)zend_object_store_get_object(return_value TSRMLS_CC);
-    php_shapefile->shapefile = shapefile;
+  object_init_ex(return_value, mapscript_ce_shapefile);
+  php_shapefile = (php_shapefile_object *)zend_object_store_get_object(return_value TSRMLS_CC);
+  php_shapefile->shapefile = shapefile;
 }
 
 static void mapscript_shapefile_object_destroy(void *object TSRMLS_DC)
 {
-    php_shapefile_object *php_shapefile = (php_shapefile_object *)object;
+  php_shapefile_object *php_shapefile = (php_shapefile_object *)object;
 
-    MAPSCRIPT_FREE_OBJECT(php_shapefile);
+  MAPSCRIPT_FREE_OBJECT(php_shapefile);
 
-    MAPSCRIPT_DELREF(php_shapefile->bounds);
+  MAPSCRIPT_DELREF(php_shapefile->bounds);
 
-    shapefileObj_destroy(php_shapefile->shapefile);
+  shapefileObj_destroy(php_shapefile->shapefile);
 
-    efree(object);
+  efree(object);
 }
 
 static zend_object_value mapscript_shapefile_object_new(zend_class_entry *ce TSRMLS_DC)
 {
-    zend_object_value retval;
-    php_shapefile_object *php_shapefile;
+  zend_object_value retval;
+  php_shapefile_object *php_shapefile;
 
-    MAPSCRIPT_ALLOC_OBJECT(php_shapefile, php_shapefile_object);
+  MAPSCRIPT_ALLOC_OBJECT(php_shapefile, php_shapefile_object);
 
-    retval = mapscript_object_new(&php_shapefile->std, ce,
-                                  &mapscript_shapefile_object_destroy TSRMLS_CC);
+  retval = mapscript_object_new(&php_shapefile->std, ce,
+                                &mapscript_shapefile_object_destroy TSRMLS_CC);
 
-    php_shapefile->bounds = NULL;
+  php_shapefile->bounds = NULL;
 
-    return retval;
+  return retval;
 }
 
 PHP_MINIT_FUNCTION(shapefile)
 {
-    zend_class_entry ce;
+  zend_class_entry ce;
+
+  MAPSCRIPT_REGISTER_CLASS("shapeFileObj",
+                           shapefile_functions,
+                           mapscript_ce_shapefile,
+                           mapscript_shapefile_object_new);
 
-    MAPSCRIPT_REGISTER_CLASS("shapeFileObj", 
-                             shapefile_functions,
-                             mapscript_ce_shapefile,
-                             mapscript_shapefile_object_new);
+  mapscript_ce_shapefile->ce_flags |= ZEND_ACC_FINAL_CLASS;
 
-    mapscript_ce_shapefile->ce_flags |= ZEND_ACC_FINAL_CLASS; 
-    
-    return SUCCESS;
+  return SUCCESS;
 }
diff --git a/mapscript/php/style.c b/mapscript/php/style.c
index 54c1425..a2dada0 100644
--- a/mapscript/php/style.c
+++ b/mapscript/php/style.c
@@ -2,7 +2,7 @@
  * $Id: php_mapscript.c 9765 2010-01-28 15:32:10Z aboudreault $
  *
  * Project:  MapServer
- * Purpose:  PHP/MapScript extension for MapServer.  External interface 
+ * Purpose:  PHP/MapScript extension for MapServer.  External interface
  *           functions
  * Author:   Daniel Morissette, DM Solutions Group (dmorissette at dmsolutions.ca)
  *           Alan Boudreault, Mapgears
@@ -16,16 +16,16 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
+ *
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  * DEALINGS IN THE SOFTWARE.
  **********************************************************************/
 
@@ -35,320 +35,306 @@ zend_class_entry *mapscript_ce_style;
 zend_object_handlers mapscript_style_object_handlers;
 
 ZEND_BEGIN_ARG_INFO_EX(style___construct_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, parent)
-  ZEND_ARG_OBJ_INFO(0, style, styleObj, 0)
+ZEND_ARG_INFO(0, parent)
+ZEND_ARG_OBJ_INFO(0, style, styleObj, 0)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(style___get_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, property)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(style___set_args, 0, 0, 2)
-  ZEND_ARG_INFO(0, property)
-  ZEND_ARG_INFO(0, value)
+ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, value)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(style_updateFromString_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, snippet)
+ZEND_ARG_INFO(0, snippet)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(style_setBinding_args, 0, 0, 2)
-  ZEND_ARG_INFO(0, styleBinding)
-  ZEND_ARG_INFO(0, value)
+ZEND_ARG_INFO(0, styleBinding)
+ZEND_ARG_INFO(0, value)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(style_getBinding_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, styleBinding)
+ZEND_ARG_INFO(0, styleBinding)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(style_removeBinding_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, styleBinding)
+ZEND_ARG_INFO(0, styleBinding)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(style_setGeomTransform_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, transform)
+ZEND_ARG_INFO(0, transform)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(style_setPattern_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, pattern)
+ZEND_ARG_INFO(0, pattern)
 ZEND_END_ARG_INFO()
 
-/* {{{ proto void __construct(parent [, styleObj style]) 
+/* {{{ proto void __construct(parent [, styleObj style])
    Create a new styleObj instance. parent has to be a classObj or labelObj. */
 PHP_METHOD(styleObj, __construct)
 {
-    zval *zobj = getThis();
-    zval *zparent, *zstyle = NULL;
-    styleObj *style;
-    php_class_object *php_class = NULL;
-    php_label_object *php_label = NULL;
-    php_style_object *php_style, *php_style2;
-    parent_object parent;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|O",
-                              &zparent,
-                              &zstyle, mapscript_ce_style) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  zval *zparent, *zstyle = NULL;
+  styleObj *style;
+  php_class_object *php_class = NULL;
+  php_label_object *php_label = NULL;
+  php_style_object *php_style, *php_style2 = NULL;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|O",
+                            &zparent,
+                            &zstyle, mapscript_ce_style) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_style = (php_style_object *)zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    if (Z_TYPE_P(zparent) == IS_OBJECT && Z_OBJCE_P(zparent) == mapscript_ce_class)
-        php_class = (php_class_object *)zend_object_store_get_object(zparent TSRMLS_CC);
-    else if (Z_TYPE_P(zparent) == IS_OBJECT && Z_OBJCE_P(zparent) == mapscript_ce_label)
-        php_label = (php_label_object *)zend_object_store_get_object(zparent TSRMLS_CC);
-    else 
-    {
-        mapscript_throw_mapserver_exception("Invalid argument 1: should be a classObj or labelObj" TSRMLS_CC);
-        return;
-    }
+  php_style = (php_style_object *)zend_object_store_get_object(zobj TSRMLS_CC);
 
-    if (zstyle)
-        php_style2 = (php_style_object *)zend_object_store_get_object(zstyle TSRMLS_CC);
+  if (Z_TYPE_P(zparent) == IS_OBJECT && Z_OBJCE_P(zparent) == mapscript_ce_class)
+    php_class = (php_class_object *)zend_object_store_get_object(zparent TSRMLS_CC);
+  else if (Z_TYPE_P(zparent) == IS_OBJECT && Z_OBJCE_P(zparent) == mapscript_ce_label)
+    php_label = (php_label_object *)zend_object_store_get_object(zparent TSRMLS_CC);
+  else {
+    mapscript_throw_mapserver_exception("Invalid argument 1: should be a classObj or labelObj" TSRMLS_CC);
+    return;
+  }
 
-    if (php_class)
-    {
-        if ((style = styleObj_new(php_class->class, (zstyle ? php_style2->style : NULL))) == NULL)
-        {
-            mapscript_throw_mapserver_exception("" TSRMLS_CC);
-            return;
-        }
+  if (zstyle)
+    php_style2 = (php_style_object *)zend_object_store_get_object(zstyle TSRMLS_CC);
+
+  if (php_class) {
+    if ((style = styleObj_new(php_class->class, (zstyle ? php_style2->style : NULL))) == NULL) {
+      mapscript_throw_mapserver_exception("" TSRMLS_CC);
+      return;
     }
-    else
-    {
-        if ((style = styleObj_label_new(php_label->label, (zstyle ? php_style2->style : NULL))) == NULL)
-        {
-            mapscript_throw_mapserver_exception("" TSRMLS_CC);
-            return;
-        }
+  } else {
+    if ((style = styleObj_label_new(php_label->label, (zstyle ? php_style2->style : NULL))) == NULL) {
+      mapscript_throw_mapserver_exception("" TSRMLS_CC);
+      return;
     }
+  }
 
-    php_style->style = style;
+  php_style->style = style;
 
-    MAPSCRIPT_MAKE_PARENT(zparent, NULL);
-    php_style->parent = parent;
-    MAPSCRIPT_ADDREF(zparent);  
+  MAPSCRIPT_MAKE_PARENT(zparent, NULL);
+  php_style->parent = parent;
+  MAPSCRIPT_ADDREF(zparent);
 }
 /* }}} */
 
 PHP_METHOD(styleObj, __get)
 {
-    char *property;
-    long property_len;
-    zval *zobj = getThis();
-    php_style_object *php_style;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &property, &property_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *zobj = getThis();
+  php_style_object *php_style;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &property, &property_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_style = (php_style_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_style = (php_style_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    IF_GET_LONG("symbol", php_style->style->symbol)
-    else IF_GET_STRING("symbolname", php_style->style->symbolname)
+  IF_GET_LONG("symbol", php_style->style->symbol)
+  else IF_GET_STRING("symbolname", php_style->style->symbolname)
     else IF_GET_DOUBLE("size", php_style->style->size)
-    else IF_GET_DOUBLE("minsize", php_style->style->minsize)
-    else IF_GET_DOUBLE("maxsize", php_style->style->maxsize)
-    else IF_GET_DOUBLE("width", php_style->style->width)
-    else IF_GET_DOUBLE("outlinewidth", php_style->style->outlinewidth)
-    else IF_GET_DOUBLE("minwidth", php_style->style->minwidth)
-    else IF_GET_DOUBLE("maxwidth", php_style->style->maxwidth)
-    else IF_GET_LONG("offsetx", php_style->style->offsetx)
-    else IF_GET_LONG("offsety", php_style->style->offsety)
-    else IF_GET_DOUBLE("angle", php_style->style->angle)
-    else IF_GET_LONG("antialias", php_style->style->antialias)
-    else IF_GET_DOUBLE("minvalue", php_style->style->minvalue)
-    else IF_GET_DOUBLE("maxvalue", php_style->style->maxvalue)
-    else IF_GET_STRING("rangeitem", php_style->style->rangeitem)
-    else IF_GET_LONG("rangeitemindex", php_style->style->rangeitemindex)
-    else IF_GET_DOUBLE("gap", php_style->style->gap)
-    else IF_GET_LONG("patternlength", php_style->style->patternlength)  
-    else IF_GET_LONG("position", php_style->style->position)
-    else IF_GET_LONG("linecap", php_style->style->linecap)
-    else IF_GET_LONG("linejoin", php_style->style->linejoin)
-    else IF_GET_LONG("linejoinmaxsize", php_style->style->linejoinmaxsize)
-    else IF_GET_DOUBLE("angle", php_style->style->angle)
-    else IF_GET_LONG("autoangle", php_style->style->autoangle)
-    else IF_GET_LONG("opacity", php_style->style->opacity)
-    else IF_GET_OBJECT("color", mapscript_ce_color, php_style->color, &php_style->style->color) 
-    else IF_GET_OBJECT("outlinecolor", mapscript_ce_color, php_style->outlinecolor, &php_style->style->outlinecolor) 
-    else IF_GET_OBJECT("backgroundcolor", mapscript_ce_color, php_style->backgroundcolor, &php_style->style->backgroundcolor) 
-    else IF_GET_OBJECT("mincolor", mapscript_ce_color, php_style->mincolor, &php_style->style->mincolor) 
-    else IF_GET_OBJECT("maxcolor", mapscript_ce_color, php_style->maxcolor, &php_style->style->maxcolor) 
-    else 
-    {
-        mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }
+      else IF_GET_DOUBLE("minsize", php_style->style->minsize)
+        else IF_GET_DOUBLE("maxsize", php_style->style->maxsize)
+          else IF_GET_DOUBLE("width", php_style->style->width)
+            else IF_GET_DOUBLE("outlinewidth", php_style->style->outlinewidth)
+              else IF_GET_DOUBLE("minwidth", php_style->style->minwidth)
+                else IF_GET_DOUBLE("maxwidth", php_style->style->maxwidth)
+                  else IF_GET_LONG("offsetx", php_style->style->offsetx)
+                    else IF_GET_LONG("offsety", php_style->style->offsety)
+                      else IF_GET_LONG("polaroffsetpixel", php_style->style->polaroffsetpixel)
+                        else IF_GET_LONG("polaroffsetangle", php_style->style->polaroffsetangle)
+                          else IF_GET_DOUBLE("angle", php_style->style->angle)
+                            else IF_GET_LONG("antialias", php_style->style->antialias)
+                              else IF_GET_DOUBLE("minvalue", php_style->style->minvalue)
+                                else IF_GET_DOUBLE("maxvalue", php_style->style->maxvalue)
+                                  else IF_GET_STRING("rangeitem", php_style->style->rangeitem)
+                                    else IF_GET_LONG("rangeitemindex", php_style->style->rangeitemindex)
+                                      else IF_GET_DOUBLE("gap", php_style->style->gap)
+                                        else IF_GET_DOUBLE("initialgap", php_style->style->initialgap)
+                                          else IF_GET_DOUBLE("maxscaledenom", php_style->style->maxscaledenom)
+                                            else IF_GET_DOUBLE("minscaledenom", php_style->style->minscaledenom)
+                                              else IF_GET_LONG("patternlength", php_style->style->patternlength)
+                                                else IF_GET_LONG("position", php_style->style->position)
+                                                  else IF_GET_LONG("linecap", php_style->style->linecap)
+                                                    else IF_GET_LONG("linejoin", php_style->style->linejoin)
+                                                      else IF_GET_LONG("linejoinmaxsize", php_style->style->linejoinmaxsize)
+                                                        else IF_GET_DOUBLE("angle", php_style->style->angle)
+                                                          else IF_GET_LONG("autoangle", php_style->style->autoangle)
+                                                            else IF_GET_LONG("opacity", php_style->style->opacity)
+                                                              else IF_GET_OBJECT("color", mapscript_ce_color, php_style->color, &php_style->style->color)
+                                                                else IF_GET_OBJECT("outlinecolor", mapscript_ce_color, php_style->outlinecolor, &php_style->style->outlinecolor)
+                                                                  else IF_GET_OBJECT("backgroundcolor", mapscript_ce_color, php_style->backgroundcolor, &php_style->style->backgroundcolor)
+                                                                    else IF_GET_OBJECT("mincolor", mapscript_ce_color, php_style->mincolor, &php_style->style->mincolor)
+                                                                      else IF_GET_OBJECT("maxcolor", mapscript_ce_color, php_style->maxcolor, &php_style->style->maxcolor)
+                                                                        else {
+                                                                          mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+                                                                        }
 }
 
 PHP_METHOD(styleObj, __set)
 {
-    char *property;
-    long property_len;
-    zval *value;
-    zval *zobj = getThis();
-    php_style_object *php_style;
-    php_map_object *php_map;
-    php_class_object *php_class;
-    php_layer_object *php_layer;
-    php_labelcachemember_object *php_labelcachemember;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
-                              &property, &property_len, &value) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *value;
+  zval *zobj = getThis();
+  php_style_object *php_style;
+  php_map_object *php_map = NULL;
+  php_class_object *php_class;
+  php_layer_object *php_layer;
+  php_labelcachemember_object *php_labelcachemember;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
+                            &property, &property_len, &value) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_style = (php_style_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    IF_SET_LONG("symbol", php_style->style->symbol, value)
-    else IF_SET_DOUBLE("size", php_style->style->size, value)
+  php_style = (php_style_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  IF_SET_LONG("symbol", php_style->style->symbol, value)
+  else IF_SET_DOUBLE("size", php_style->style->size, value)
     else IF_SET_DOUBLE("minsize", php_style->style->minsize, value)
-    else IF_SET_DOUBLE("maxsize", php_style->style->maxsize, value)
-    else IF_SET_DOUBLE("width", php_style->style->width, value)
-    else IF_SET_DOUBLE("outlinewidth", php_style->style->outlinewidth, value)
-    else IF_SET_DOUBLE("minwidth", php_style->style->minwidth, value)
-    else IF_SET_DOUBLE("maxwidth", php_style->style->maxwidth, value)
-    else IF_SET_LONG("offsetx", php_style->style->offsetx, value)
-    else IF_SET_LONG("offsety", php_style->style->offsety, value)
-    else IF_SET_DOUBLE("angle", php_style->style->angle, value)
-    else IF_SET_LONG("antialias", php_style->style->antialias, value)
-    else IF_SET_DOUBLE("minvalue", php_style->style->minvalue, value)
-    else IF_SET_DOUBLE("maxvalue", php_style->style->maxvalue, value)
-    else IF_SET_STRING("rangeitem", php_style->style->rangeitem, value)
-    else IF_SET_LONG("rangeitemindex", php_style->style->rangeitemindex, value)
-    else IF_SET_DOUBLE("gap", php_style->style->gap, value)
-    else IF_SET_LONG("patternlength", php_style->style->patternlength, value)  
-    else IF_SET_LONG("position", php_style->style->position, value)
-    else IF_SET_LONG("linecap", php_style->style->linecap, value)
-    else IF_SET_LONG("linejoin", php_style->style->linejoin, value)
-    else IF_SET_LONG("linejoinmaxsize", php_style->style->linejoinmaxsize, value)
-    else IF_SET_DOUBLE("angle", php_style->style->angle, value)
-    else IF_SET_LONG("autoangle", php_style->style->autoangle, value)
-    else if (STRING_EQUAL("opacity", property))
-    {
-        int alpha;
-        convert_to_long(value);
-        php_style->style->opacity = Z_LVAL_P(value);
-
-        /* apply opacity as the alpha channel color(s) */
-        if(php_style->style->opacity < 100)
-          alpha = MS_NINT(php_style->style->opacity*2.55);
-        else
-            alpha = 255;
-
-        php_style->style->color.alpha = alpha; 
-        php_style->style->outlinecolor.alpha = alpha;
-        php_style->style->backgroundcolor.alpha = alpha;
-        php_style->style->mincolor.alpha = alpha;
-        php_style->style->maxcolor.alpha = alpha;
-    }
-    else if (STRING_EQUAL("symbolname", property))
-    {
-        convert_to_string(value);
-        if (php_style->style->symbolname) free(php_style->style->symbolname);    
-        if (Z_STRVAL_P(value))                        
-            php_style->style->symbolname = strdup(Z_STRVAL_P(value));     
-
-        /* The parent can be a classObj or a labelCacheMemberObj */
-        if (Z_OBJCE_P(php_style->parent.val) == mapscript_ce_class)
-        {
-            php_class = (php_class_object *) zend_object_store_get_object(php_style->parent.val TSRMLS_CC); 
-            /* Can a class have no layer object ? */
-            php_layer = (php_layer_object *) zend_object_store_get_object(php_class->parent.val TSRMLS_CC);
-            if (!php_layer->parent.val)
-            {
-                mapscript_throw_exception("No map object associated with this style object." TSRMLS_CC);
-                return;
-            }
-            php_map = (php_map_object *) zend_object_store_get_object(php_layer->parent.val TSRMLS_CC);
-        }
-        else if (Z_OBJCE_P(php_style->parent.val) == mapscript_ce_labelcachemember)
-        {
-            /* The parent is always a map */
-            php_labelcachemember = (php_labelcachemember_object *) zend_object_store_get_object(php_style->parent.val TSRMLS_CC);
-            if (!php_labelcachemember->parent.val)
-            {
-                mapscript_throw_exception("No map object associated with this style object." TSRMLS_CC);
-                return;
-            }
-            php_map = (php_map_object *) zend_object_store_get_object(php_labelcachemember->parent.val TSRMLS_CC);
-        }
-
-        if (styleObj_setSymbolByName(php_style->style,
-                                     php_map->map,
-                                     php_style->style->symbolname) == -1)
-        {
-            mapscript_throw_exception("Symbol not found." TSRMLS_CC);
-            return;
-        }
-    }
-    else if ( (STRING_EQUAL("color", property)) ||
-              (STRING_EQUAL("outlinecolor", property)) ||
-              (STRING_EQUAL("backgroundcolor", property)) ||
-              (STRING_EQUAL("maxcolor", property)) ||
-              (STRING_EQUAL("mincolor", property)))
-    {
-        mapscript_throw_exception("Property '%s' is an object and can only be modified through its accessors." TSRMLS_CC, property);
-    }
-    else if ( (STRING_EQUAL("patternlength", property)))    {
-        mapscript_throw_exception("Property '%s' is read-only and cannot be set." TSRMLS_CC, property);
-    }
-    else 
-    {
-        mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }
-         
+      else IF_SET_DOUBLE("maxsize", php_style->style->maxsize, value)
+        else IF_SET_DOUBLE("width", php_style->style->width, value)
+          else IF_SET_DOUBLE("outlinewidth", php_style->style->outlinewidth, value)
+            else IF_SET_DOUBLE("minwidth", php_style->style->minwidth, value)
+              else IF_SET_DOUBLE("maxwidth", php_style->style->maxwidth, value)
+                else IF_SET_LONG("offsetx", php_style->style->offsetx, value)
+                  else IF_SET_LONG("offsety", php_style->style->offsety, value)
+                    else IF_SET_LONG("polaroffsetpixel", php_style->style->polaroffsetpixel, value)
+                      else IF_SET_LONG("polaroffsetangle", php_style->style->polaroffsetangle, value)
+                        else IF_SET_DOUBLE("angle", php_style->style->angle, value)
+                          else IF_SET_LONG("antialias", php_style->style->antialias, value)
+                            else IF_SET_DOUBLE("minvalue", php_style->style->minvalue, value)
+                              else IF_SET_DOUBLE("maxvalue", php_style->style->maxvalue, value)
+                                else IF_SET_DOUBLE("minscaledenom", php_style->style->minscaledenom, value)
+                                  else IF_SET_DOUBLE("maxscaledenom", php_style->style->maxscaledenom, value)
+                                    else IF_SET_STRING("rangeitem", php_style->style->rangeitem, value)
+                                      else IF_SET_LONG("rangeitemindex", php_style->style->rangeitemindex, value)
+                                        else IF_SET_DOUBLE("gap", php_style->style->gap, value)
+                                          else IF_SET_DOUBLE("initialgap", php_style->style->initialgap, value)
+                                            else IF_SET_LONG("position", php_style->style->position, value)
+                                              else IF_SET_LONG("linecap", php_style->style->linecap, value)
+                                                else IF_SET_LONG("linejoin", php_style->style->linejoin, value)
+                                                  else IF_SET_LONG("linejoinmaxsize", php_style->style->linejoinmaxsize, value)
+                                                    else IF_SET_DOUBLE("angle", php_style->style->angle, value)
+                                                      else IF_SET_LONG("autoangle", php_style->style->autoangle, value)
+                                                        else if (STRING_EQUAL("opacity", property)) {
+                                                          int alpha;
+                                                          convert_to_long(value);
+                                                          php_style->style->opacity = Z_LVAL_P(value);
+
+                                                          /* apply opacity as the alpha channel color(s) */
+                                                          if(php_style->style->opacity < 100)
+                                                            alpha = MS_NINT(php_style->style->opacity*2.55);
+                                                          else
+                                                            alpha = 255;
+
+                                                          php_style->style->color.alpha = alpha;
+                                                          php_style->style->outlinecolor.alpha = alpha;
+                                                          php_style->style->backgroundcolor.alpha = alpha;
+                                                          php_style->style->mincolor.alpha = alpha;
+                                                          php_style->style->maxcolor.alpha = alpha;
+                                                        } else if (STRING_EQUAL("symbolname", property)) {
+                                                          convert_to_string(value);
+                                                          if (php_style->style->symbolname) free(php_style->style->symbolname);
+                                                          if (Z_STRVAL_P(value))
+                                                            php_style->style->symbolname = strdup(Z_STRVAL_P(value));
+
+                                                          /* The parent can be a classObj or a labelCacheMemberObj */
+                                                          if (Z_OBJCE_P(php_style->parent.val) == mapscript_ce_class) {
+                                                            php_class = (php_class_object *) zend_object_store_get_object(php_style->parent.val TSRMLS_CC);
+                                                            /* Can a class have no layer object ? */
+                                                            php_layer = (php_layer_object *) zend_object_store_get_object(php_class->parent.val TSRMLS_CC);
+                                                            if (!php_layer->parent.val) {
+                                                              mapscript_throw_exception("No map object associated with this style object." TSRMLS_CC);
+                                                              return;
+                                                            }
+                                                            php_map = (php_map_object *) zend_object_store_get_object(php_layer->parent.val TSRMLS_CC);
+                                                          } else if (Z_OBJCE_P(php_style->parent.val) == mapscript_ce_labelcachemember) {
+                                                            /* The parent is always a map */
+                                                            php_labelcachemember = (php_labelcachemember_object *) zend_object_store_get_object(php_style->parent.val TSRMLS_CC);
+                                                            if (!php_labelcachemember->parent.val) {
+                                                              mapscript_throw_exception("No map object associated with this style object." TSRMLS_CC);
+                                                              return;
+                                                            }
+                                                            php_map = (php_map_object *) zend_object_store_get_object(php_labelcachemember->parent.val TSRMLS_CC);
+                                                          }
+
+                                                          if (styleObj_setSymbolByName(php_style->style,
+                                                                                       php_map->map,
+                                                                                       php_style->style->symbolname) == -1) {
+                                                            mapscript_throw_exception("Symbol not found." TSRMLS_CC);
+                                                            return;
+                                                          }
+                                                        } else if ( (STRING_EQUAL("color", property)) ||
+                                                                    (STRING_EQUAL("outlinecolor", property)) ||
+                                                                    (STRING_EQUAL("backgroundcolor", property)) ||
+                                                                    (STRING_EQUAL("maxcolor", property)) ||
+                                                                    (STRING_EQUAL("mincolor", property))) {
+                                                          mapscript_throw_exception("Property '%s' is an object and can only be modified through its accessors." TSRMLS_CC, property);
+                                                        } else if ( (STRING_EQUAL("patternlength", property)))    {
+                                                          mapscript_throw_exception("Property '%s' is read-only and cannot be set." TSRMLS_CC, property);
+                                                        } else {
+                                                          mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+                                                        }
+
 }
 
 /* {{{ proto int style.updateFromString(string snippet)
    Update a style from a string snippet.  Returns MS_SUCCESS/MS_FAILURE */
 PHP_METHOD(styleObj, updateFromString)
 {
-    zval *zobj = getThis();
-    char *snippet;
-    long snippet_len;
-    int status = MS_FAILURE;
-    zval *retval;
-    zval property_name, value;
-    php_style_object *php_style;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &snippet, &snippet_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  char *snippet;
+  long snippet_len;
+  int status = MS_FAILURE;
+  zval *retval;
+  zval property_name, value;
+  php_style_object *php_style;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &snippet, &snippet_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_style = (php_style_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-
-    if ((status = styleObj_updateFromString(php_style->style, snippet)) != MS_SUCCESS)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
-    
-    /* verify the symbol if needed */
-    if (php_style->style->symbolname) 
-    {
-        INIT_ZVAL(property_name);
-        INIT_ZVAL(value);
-        ZVAL_STRING(&property_name, "symbolname", 1);
-        ZVAL_STRING(&value, php_style->style->symbolname, 1);
-        MAPSCRIPT_CALL_METHOD_2(zobj, "__set", retval, &property_name, &value);
-    }
-
-    RETURN_LONG(status);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_style = (php_style_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  if ((status = styleObj_updateFromString(php_style->style, snippet)) != MS_SUCCESS) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
+
+  /* verify the symbol if needed */
+  if (php_style->style->symbolname) {
+    INIT_ZVAL(property_name);
+    INIT_ZVAL(value);
+    ZVAL_STRING(&property_name, "symbolname", 1);
+    ZVAL_STRING(&value, php_style->style->symbolname, 1);
+    MAPSCRIPT_CALL_METHOD_2(zobj, "__set", retval, &property_name, &value);
+  }
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -356,81 +342,76 @@ PHP_METHOD(styleObj, updateFromString)
    Set the attribute binding for a specfiled style property. Returns MS_SUCCESS on success. */
 PHP_METHOD(styleObj, setBinding)
 {
-    zval *zobj = getThis();
-    char *value;
-    long value_len;
-    long bindingId;
-    php_style_object *php_style;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ls",
-                              &bindingId, &value, &value_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  char *value;
+  long value_len;
+  long bindingId;
+  php_style_object *php_style;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ls",
+                            &bindingId, &value, &value_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_style = (php_style_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_style = (php_style_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    if (bindingId < 0 || bindingId > MS_STYLE_BINDING_LENGTH)
-     {
-        mapscript_throw_exception("Invalid binding id." TSRMLS_CC);
-        return;
-     }
+  if (bindingId < 0 || bindingId > MS_STYLE_BINDING_LENGTH) {
+    mapscript_throw_exception("Invalid binding id." TSRMLS_CC);
+    return;
+  }
 
-    if (!value || strlen(value) <= 0)
-    {
-        mapscript_throw_exception("Invalid binding value." TSRMLS_CC);
-        return;
-    }
+  if (!value || strlen(value) <= 0) {
+    mapscript_throw_exception("Invalid binding value." TSRMLS_CC);
+    return;
+  }
 
-    if(php_style->style->bindings[bindingId].item) 
-    {
-        msFree(php_style->style->bindings[bindingId].item);
-        php_style->style->bindings[bindingId].index = -1; 
-        php_style->style->numbindings--;
-    }
+  if(php_style->style->bindings[bindingId].item) {
+    msFree(php_style->style->bindings[bindingId].item);
+    php_style->style->bindings[bindingId].index = -1;
+    php_style->style->numbindings--;
+  }
 
-    php_style->style->bindings[bindingId].item = strdup(value); 
-    php_style->style->numbindings++;
+  php_style->style->bindings[bindingId].item = strdup(value);
+  php_style->style->numbindings++;
 
-    RETURN_LONG(MS_SUCCESS);
+  RETURN_LONG(MS_SUCCESS);
 }
 /* }}} */
 
 /* {{{ proto int style.getbinding(const bindingid)
-   Get the value of a attribute binding for a specfiled style property. 
+   Get the value of a attribute binding for a specfiled style property.
    Returns the string value if exist, else null. */
 PHP_METHOD(styleObj, getBinding)
 {
-    zval *zobj = getThis();
-    long bindingId;
-    char *value = NULL;
-    php_style_object *php_style;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
-                              &bindingId) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  long bindingId;
+  char *value = NULL;
+  php_style_object *php_style;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
+                            &bindingId) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_style = (php_style_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    if (bindingId < 0 || bindingId > MS_STYLE_BINDING_LENGTH)
-    {
-        mapscript_throw_exception("Invalid binding id." TSRMLS_CC);
-        return;
-    }
+  php_style = (php_style_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    if( (value = php_style->style->bindings[bindingId].item) != NULL)
-    {
-       RETURN_STRING(value, 1);                
-    }
+  if (bindingId < 0 || bindingId > MS_STYLE_BINDING_LENGTH) {
+    mapscript_throw_exception("Invalid binding id." TSRMLS_CC);
+    return;
+  }
+
+  if( (value = php_style->style->bindings[bindingId].item) != NULL) {
+    RETURN_STRING(value, 1);
+  }
+
+  RETURN_NULL();
 
-    RETURN_NULL();
-    
 }
 /* }}} */
 
@@ -438,37 +419,35 @@ PHP_METHOD(styleObj, getBinding)
    Remove attribute binding for a specfiled style property. Returns MS_SUCCESS on success. */
 PHP_METHOD(styleObj, removeBinding)
 {
-    zval *zobj = getThis();
-    long bindingId;
-    php_style_object *php_style;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
-                              &bindingId) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  long bindingId;
+  php_style_object *php_style;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
+                            &bindingId) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_style = (php_style_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    if (bindingId < 0 || bindingId > MS_STYLE_BINDING_LENGTH)
-    {
-        mapscript_throw_exception("Invalid binding id." TSRMLS_CC);
-        return;
-    }
+  php_style = (php_style_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
+  if (bindingId < 0 || bindingId > MS_STYLE_BINDING_LENGTH) {
+    mapscript_throw_exception("Invalid binding id." TSRMLS_CC);
+    return;
+  }
 
-    if(php_style->style->bindings[bindingId].item) 
-    {
-        msFree(php_style->style->bindings[bindingId].item);
-        php_style->style->bindings[bindingId].item =  NULL;
-        php_style->style->bindings[bindingId].index = -1; 
-        php_style->style->numbindings--;
-    }
 
-    RETURN_LONG(MS_SUCCESS);
-    
+  if(php_style->style->bindings[bindingId].item) {
+    msFree(php_style->style->bindings[bindingId].item);
+    php_style->style->bindings[bindingId].item =  NULL;
+    php_style->style->bindings[bindingId].index = -1;
+    php_style->style->numbindings--;
+  }
+
+  RETURN_LONG(MS_SUCCESS);
+
 }
 /* }}} */
 
@@ -476,21 +455,21 @@ PHP_METHOD(styleObj, removeBinding)
    Free the object */
 PHP_METHOD(styleObj, free)
 {
-    zval *zobj = getThis();
-    php_style_object *php_style;
+  zval *zobj = getThis();
+  php_style_object *php_style;
 
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_style = (php_style_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_style = (php_style_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    MAPSCRIPT_DELREF(php_style->color);
-    MAPSCRIPT_DELREF(php_style->outlinecolor);
-    MAPSCRIPT_DELREF(php_style->backgroundcolor);
+  MAPSCRIPT_DELREF(php_style->color);
+  MAPSCRIPT_DELREF(php_style->outlinecolor);
+  MAPSCRIPT_DELREF(php_style->backgroundcolor);
 }
 /* }}} */
 
@@ -498,23 +477,23 @@ PHP_METHOD(styleObj, free)
    return the geometry transform expression */
 PHP_METHOD(styleObj, getGeomTransform)
 {
-    zval *zobj = getThis();
-    php_style_object *php_style;
+  zval *zobj = getThis();
+  php_style_object *php_style;
 
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_style = (php_style_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_style = (php_style_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    if (php_style->style->_geomtransform.type == MS_GEOMTRANSFORM_NONE ||
-        !php_style->style->_geomtransform.string)
-        RETURN_STRING("", 1);
+  if (php_style->style->_geomtransform.type == MS_GEOMTRANSFORM_NONE ||
+      !php_style->style->_geomtransform.string)
+    RETURN_STRING("", 1);
 
-    RETURN_STRING(php_style->style->_geomtransform.string, 1);
+  RETURN_STRING(php_style->style->_geomtransform.string, 1);
 }
 /* }}} */
 
@@ -522,70 +501,68 @@ PHP_METHOD(styleObj, getGeomTransform)
    set the geometry transform expression */
 PHP_METHOD(styleObj, setGeomTransform)
 {
-    zval *zobj = getThis();
-    char *transform;
-    long transform_len;
-    php_style_object *php_style;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &transform, &transform_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  char *transform;
+  long transform_len;
+  php_style_object *php_style;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &transform, &transform_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_style = (php_style_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_style = (php_style_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    styleObj_setGeomTransform(php_style->style, transform);
+  styleObj_setGeomTransform(php_style->style, transform);
 }
 /* }}} */
 
 /* {{{ proto int style.setpattern(array points)
-   Set the pattern of the style ) */ 
+   Set the pattern of the style ) */
 PHP_METHOD(styleObj, setPattern)
 {
-    zval *zpattern, **ppzval;
-    HashTable *pattern_hash = NULL;
-    zval *zobj = getThis();
-    int index = 0, numelements = 0;
-    php_style_object *php_style;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a",
-                              &zpattern) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zpattern, **ppzval;
+  HashTable *pattern_hash = NULL;
+  zval *zobj = getThis();
+  int index = 0, numelements = 0;
+  php_style_object *php_style;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a",
+                            &zpattern) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_style = (php_style_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    pattern_hash = Z_ARRVAL_P(zpattern);
-
-    numelements = zend_hash_num_elements(pattern_hash);
-    if (numelements == 0)
-    {
-        mapscript_report_php_error(E_WARNING, 
-                                   "style->setpoints : invalid array of %d element(s) as parameter." TSRMLS_CC, numelements);
-        RETURN_LONG(MS_FAILURE);
-    }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    for(zend_hash_internal_pointer_reset(pattern_hash); 
-        zend_hash_has_more_elements(pattern_hash) == SUCCESS; 
-        zend_hash_move_forward(pattern_hash))
-    { 
-        
-        zend_hash_get_current_data(pattern_hash, (void **)&ppzval);
-        if (Z_TYPE_PP(ppzval) != IS_LONG)
-            convert_to_long(*ppzval);
-	     
-        php_style->style->pattern[index] = Z_LVAL_PP(ppzval);
-        index++;
-    }
+  php_style = (php_style_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  pattern_hash = Z_ARRVAL_P(zpattern);
+
+  numelements = zend_hash_num_elements(pattern_hash);
+  if (numelements == 0) {
+    mapscript_report_php_error(E_WARNING,
+                               "style->setpoints : invalid array of %d element(s) as parameter." TSRMLS_CC, numelements);
+    RETURN_LONG(MS_FAILURE);
+  }
+
+  for(zend_hash_internal_pointer_reset(pattern_hash);
+      zend_hash_has_more_elements(pattern_hash) == SUCCESS;
+      zend_hash_move_forward(pattern_hash)) {
 
-    php_style->style->patternlength = numelements;
+    zend_hash_get_current_data(pattern_hash, (void **)&ppzval);
+    if (Z_TYPE_PP(ppzval) != IS_LONG)
+      convert_to_long(*ppzval);
 
-    RETURN_LONG(MS_SUCCESS);
+    php_style->style->pattern[index] = Z_LVAL_PP(ppzval);
+    index++;
+  }
+
+  php_style->style->patternlength = numelements;
+
+  RETURN_LONG(MS_SUCCESS);
 }
 /* }}} */
 
@@ -593,132 +570,131 @@ PHP_METHOD(styleObj, setPattern)
    Returns an array containing the pattern.*/
 PHP_METHOD(styleObj, getPatternArray)
 {
-    zval *zobj = getThis();
-    php_style_object *php_style;
-    int index;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  php_style_object *php_style;
+  int index;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_style = (php_style_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    
-    array_init(return_value);
-    
-    if (php_style->style->patternlength > 0)
-    {
-        for (index=0; index < php_style->style->patternlength; index++)
-        {
-            add_next_index_long(return_value, php_style->style->pattern[index]);
-        }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_style = (php_style_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  array_init(return_value);
+
+  if (php_style->style->patternlength > 0) {
+    for (index=0; index < php_style->style->patternlength; index++) {
+      add_next_index_long(return_value, php_style->style->pattern[index]);
     }
+  }
 }
 /* }}} */
 
 zend_function_entry style_functions[] = {
-    PHP_ME(styleObj, __construct, style___construct_args, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
-    PHP_ME(styleObj, __get, style___get_args, ZEND_ACC_PUBLIC)
-    PHP_ME(styleObj, __set, style___set_args, ZEND_ACC_PUBLIC)
-    PHP_MALIAS(styleObj, set, __set, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(styleObj, updateFromString, style_updateFromString_args, ZEND_ACC_PUBLIC)
-    PHP_ME(styleObj, setBinding, style_setBinding_args, ZEND_ACC_PUBLIC)
-    PHP_ME(styleObj, getBinding, style_getBinding_args, ZEND_ACC_PUBLIC)
-    PHP_ME(styleObj, removeBinding, style_removeBinding_args, ZEND_ACC_PUBLIC)
-    PHP_ME(styleObj, getGeomTransform, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(styleObj, setGeomTransform, style_setGeomTransform_args, ZEND_ACC_PUBLIC)
-    PHP_ME(styleObj, setPattern, style_setPattern_args, ZEND_ACC_PUBLIC) 
-    PHP_ME(styleObj, getPatternArray, NULL, ZEND_ACC_PUBLIC) 
-    PHP_ME(styleObj, free, NULL, ZEND_ACC_PUBLIC)
-    {NULL, NULL, NULL}
+  PHP_ME(styleObj, __construct, style___construct_args, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
+  PHP_ME(styleObj, __get, style___get_args, ZEND_ACC_PUBLIC)
+  PHP_ME(styleObj, __set, style___set_args, ZEND_ACC_PUBLIC)
+  PHP_MALIAS(styleObj, set, __set, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(styleObj, updateFromString, style_updateFromString_args, ZEND_ACC_PUBLIC)
+  PHP_ME(styleObj, setBinding, style_setBinding_args, ZEND_ACC_PUBLIC)
+  PHP_ME(styleObj, getBinding, style_getBinding_args, ZEND_ACC_PUBLIC)
+  PHP_ME(styleObj, removeBinding, style_removeBinding_args, ZEND_ACC_PUBLIC)
+  PHP_ME(styleObj, getGeomTransform, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(styleObj, setGeomTransform, style_setGeomTransform_args, ZEND_ACC_PUBLIC)
+  PHP_ME(styleObj, setPattern, style_setPattern_args, ZEND_ACC_PUBLIC)
+  PHP_ME(styleObj, getPatternArray, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(styleObj, free, NULL, ZEND_ACC_PUBLIC) {
+    NULL, NULL, NULL
+  }
 };
 
 
 void mapscript_create_style(styleObj *style, parent_object parent, zval *return_value TSRMLS_DC)
 {
-    php_style_object * php_style;
-    object_init_ex(return_value, mapscript_ce_style); 
-    php_style = (php_style_object *)zend_object_store_get_object(return_value TSRMLS_CC);
-    php_style->style = style;
-
-    php_style->parent = parent;
-    
-    MAPSCRIPT_ADDREF(parent.val);
+  php_style_object * php_style;
+  object_init_ex(return_value, mapscript_ce_style);
+  php_style = (php_style_object *)zend_object_store_get_object(return_value TSRMLS_CC);
+  php_style->style = style;
+
+  php_style->parent = parent;
+
+  MAPSCRIPT_ADDREF(parent.val);
 }
 
 static void mapscript_style_object_destroy(void *object TSRMLS_DC)
 {
-    php_style_object *php_style = (php_style_object *)object;
+  php_style_object *php_style = (php_style_object *)object;
 
-    MAPSCRIPT_FREE_OBJECT(php_style);
+  MAPSCRIPT_FREE_OBJECT(php_style);
 
-    MAPSCRIPT_FREE_PARENT(php_style->parent);
-    MAPSCRIPT_DELREF(php_style->color);
-    MAPSCRIPT_DELREF(php_style->outlinecolor);
-    MAPSCRIPT_DELREF(php_style->backgroundcolor);
+  MAPSCRIPT_FREE_PARENT(php_style->parent);
+  MAPSCRIPT_DELREF(php_style->color);
+  MAPSCRIPT_DELREF(php_style->outlinecolor);
+  MAPSCRIPT_DELREF(php_style->backgroundcolor);
 
-    /* We don't need to free the styleObj, the mapObj will do it */ 
-    efree(object);
+  /* We don't need to free the styleObj, the mapObj will do it */
+  efree(object);
 }
 
 static zend_object_value mapscript_style_object_new_ex(zend_class_entry *ce, php_style_object **ptr TSRMLS_DC)
 {
-    zend_object_value retval;
-    php_style_object *php_style;
+  zend_object_value retval;
+  php_style_object *php_style;
 
-    MAPSCRIPT_ALLOC_OBJECT(php_style, php_style_object);
+  MAPSCRIPT_ALLOC_OBJECT(php_style, php_style_object);
 
-    retval = mapscript_object_new_ex(&php_style->std, ce,
-                                     &mapscript_style_object_destroy,
-                                     &mapscript_style_object_handlers TSRMLS_CC);
+  retval = mapscript_object_new_ex(&php_style->std, ce,
+                                   &mapscript_style_object_destroy,
+                                   &mapscript_style_object_handlers TSRMLS_CC);
 
-    if (ptr)
-        *ptr = php_style;
+  if (ptr)
+    *ptr = php_style;
 
-    MAPSCRIPT_INIT_PARENT(php_style->parent);
-    php_style->color = NULL;
-    php_style->outlinecolor = NULL;
-    php_style->backgroundcolor = NULL;
+  MAPSCRIPT_INIT_PARENT(php_style->parent);
+  php_style->color = NULL;
+  php_style->outlinecolor = NULL;
+  php_style->backgroundcolor = NULL;
 
-    return retval;
+  return retval;
 }
 
 static zend_object_value mapscript_style_object_new(zend_class_entry *ce TSRMLS_DC)
 {
-    return mapscript_style_object_new_ex(ce, NULL TSRMLS_CC);
+  return mapscript_style_object_new_ex(ce, NULL TSRMLS_CC);
 }
 
 static zend_object_value mapscript_style_object_clone(zval *zobj TSRMLS_DC)
 {
-    php_style_object *php_style_old, *php_style_new;
-    zend_object_value new_ov;
+  php_style_object *php_style_old, *php_style_new;
+  zend_object_value new_ov;
 
-    php_style_old = (php_style_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_style_old = (php_style_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    new_ov = mapscript_style_object_new_ex(mapscript_ce_style, &php_style_new TSRMLS_CC); 
-    zend_objects_clone_members(&php_style_new->std, new_ov, &php_style_old->std, Z_OBJ_HANDLE_P(zobj) TSRMLS_CC);
+  new_ov = mapscript_style_object_new_ex(mapscript_ce_style, &php_style_new TSRMLS_CC);
+  zend_objects_clone_members(&php_style_new->std, new_ov, &php_style_old->std, Z_OBJ_HANDLE_P(zobj) TSRMLS_CC);
 
-    php_style_new->style = styleObj_clone(php_style_old->style);
+  php_style_new->style = styleObj_clone(php_style_old->style);
 
-    return new_ov;
+  return new_ov;
 }
 
 PHP_MINIT_FUNCTION(style)
 {
-    zend_class_entry ce;
+  zend_class_entry ce;
+
+  memcpy(&mapscript_style_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
+  mapscript_style_object_handlers.clone_obj = mapscript_style_object_clone;
 
-    memcpy(&mapscript_style_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
-    mapscript_style_object_handlers.clone_obj = mapscript_style_object_clone;
+  MAPSCRIPT_REGISTER_CLASS("styleObj",
+                           style_functions,
+                           mapscript_ce_style,
+                           mapscript_style_object_new);
 
-    MAPSCRIPT_REGISTER_CLASS("styleObj", 
-                             style_functions,
-                             mapscript_ce_style,
-                             mapscript_style_object_new);
+  mapscript_ce_style->ce_flags |= ZEND_ACC_FINAL_CLASS;
 
-    mapscript_ce_style->ce_flags |= ZEND_ACC_FINAL_CLASS; 
-    
-    return SUCCESS;
+  return SUCCESS;
 }
 
diff --git a/mapscript/php/symbol.c b/mapscript/php/symbol.c
index 72da0f6..8a7edb2 100644
--- a/mapscript/php/symbol.c
+++ b/mapscript/php/symbol.c
@@ -2,7 +2,7 @@
  * $Id: php_mapscript.c 9765 2010-01-28 15:32:10Z aboudreault $
  *
  * Project:  MapServer
- * Purpose:  PHP/MapScript extension for MapServer.  External interface 
+ * Purpose:  PHP/MapScript extension for MapServer.  External interface
  *           functions
  * Author:   Daniel Morissette, DM Solutions Group (dmorissette at dmsolutions.ca)
  *           Alan Boudreault, Mapgears
@@ -16,16 +16,16 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
+ *
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  * DEALINGS IN THE SOFTWARE.
  **********************************************************************/
 
@@ -34,328 +34,399 @@
 zend_class_entry *mapscript_ce_symbol;
 
 ZEND_BEGIN_ARG_INFO_EX(symbol___construct_args, 0, 0, 2)
-  ZEND_ARG_OBJ_INFO(0, map, mapObj, 0)
-  ZEND_ARG_INFO(0, symbolName)
+ZEND_ARG_OBJ_INFO(0, map, mapObj, 0)
+ZEND_ARG_INFO(0, symbolName)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(symbol___get_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, property)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(symbol___set_args, 0, 0, 2)
-  ZEND_ARG_INFO(0, property)
-  ZEND_ARG_INFO(0, value)
+ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, value)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(symbol_setPoints_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, points)
+ZEND_ARG_INFO(0, points)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(symbol_setImagePath_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, filename)
+ZEND_ARG_INFO(0, filename)
+ZEND_END_ARG_INFO()
+
+ZEND_BEGIN_ARG_INFO_EX(symbol_setImage_args, 0, 0, 1)
+ZEND_ARG_OBJ_INFO(0, image, imageObj, 0)
+ZEND_END_ARG_INFO()
+
+ZEND_BEGIN_ARG_INFO_EX(symbol_getImage_args, 0, 0, 1)
+ZEND_ARG_OBJ_INFO(0, outputformat, outputFormatObj, 0)
 ZEND_END_ARG_INFO()
 
 /* {{{ proto void __construct(mapObj map, string symbolname)
    Create a new symbolObj instance. */
 PHP_METHOD(symbolObj, __construct)
 {
-    zval *zmap;
-    char *symbolName;
-    long symbolName_len;
-    int symbolId = -1;
-    php_symbol_object *php_symbol;
-    php_map_object *php_map;
-    parent_object parent;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Os",
-                              &zmap, mapscript_ce_map, 
-                              &symbolName, &symbolName_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zmap;
+  char *symbolName;
+  long symbolName_len;
+  int symbolId = -1;
+  php_symbol_object *php_symbol;
+  php_map_object *php_map;
+  parent_object parent;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Os",
+                            &zmap, mapscript_ce_map,
+                            &symbolName, &symbolName_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_symbol = (php_symbol_object *)zend_object_store_get_object(getThis() TSRMLS_CC);
-    php_map = (php_map_object *)zend_object_store_get_object(zmap TSRMLS_CC);
-    
-    symbolId = msAddNewSymbol(php_map->map, symbolName);
-
-    if (symbolId == -1)
-    {
-        mapscript_throw_mapserver_exception("Unable to construct symbolObj" TSRMLS_CC);
-        return;
-    }
-    
-    php_symbol->symbol = php_map->map->symbolset.symbol[symbolId];
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_symbol = (php_symbol_object *)zend_object_store_get_object(getThis() TSRMLS_CC);
+  php_map = (php_map_object *)zend_object_store_get_object(zmap TSRMLS_CC);
+
+  symbolId = msAddNewSymbol(php_map->map, symbolName);
+
+  if (symbolId == -1) {
+    mapscript_throw_mapserver_exception("Unable to construct symbolObj" TSRMLS_CC);
+    return;
+  }
 
-    MAPSCRIPT_MAKE_PARENT(zmap, NULL);
-    php_symbol->parent = parent;
-    MAPSCRIPT_ADDREF(zmap);    
+  php_symbol->symbol = php_map->map->symbolset.symbol[symbolId];
+
+  MAPSCRIPT_MAKE_PARENT(zmap, NULL);
+  php_symbol->parent = parent;
+  MAPSCRIPT_ADDREF(zmap);
 }
 /* }}} */
 
 PHP_METHOD(symbolObj, __get)
 {
-    char *property;
-    long property_len;
-    zval *zobj = getThis();
-    php_symbol_object *php_symbol;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &property, &property_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *zobj = getThis();
+  php_symbol_object *php_symbol;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &property, &property_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_symbol = (php_symbol_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-
-    IF_GET_STRING("name", php_symbol->symbol->name)
-    else IF_GET_LONG("type", php_symbol->symbol->type) 
-    else IF_GET_LONG("inmapfile", php_symbol->symbol->inmapfile) 
-    else IF_GET_DOUBLE("sizex", php_symbol->symbol->sizex) 
-    else IF_GET_DOUBLE("sizey", php_symbol->symbol->sizey) 
-    else IF_GET_LONG("numpoints", php_symbol->symbol->numpoints) 
-    else IF_GET_LONG("filled", php_symbol->symbol->filled) 
-    else IF_GET_STRING("imagepath", php_symbol->symbol->imagepath)
-    else IF_GET_LONG("transparent", php_symbol->symbol->transparent) 
-    else IF_GET_LONG("transparentcolor", php_symbol->symbol->transparentcolor) 
-    else IF_GET_STRING("character", php_symbol->symbol->character)
-    else IF_GET_LONG("antialias", php_symbol->symbol->antialias) 
-    else IF_GET_STRING("font", php_symbol->symbol->font)
-    else 
-    {
-        mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_symbol = (php_symbol_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  IF_GET_STRING("name", php_symbol->symbol->name)
+  else IF_GET_LONG("type", php_symbol->symbol->type)
+    else IF_GET_LONG("inmapfile", php_symbol->symbol->inmapfile)
+      else IF_GET_DOUBLE("sizex", php_symbol->symbol->sizex)
+        else IF_GET_DOUBLE("sizey", php_symbol->symbol->sizey)
+          else IF_GET_LONG("numpoints", php_symbol->symbol->numpoints)
+            else IF_GET_LONG("filled", php_symbol->symbol->filled)
+              else IF_GET_STRING("imagepath", php_symbol->symbol->imagepath)
+                else IF_GET_LONG("transparent", php_symbol->symbol->transparent)
+                  else IF_GET_LONG("transparentcolor", php_symbol->symbol->transparentcolor)
+                    else IF_GET_STRING("character", php_symbol->symbol->character)
+                      else IF_GET_STRING("svg_text", php_symbol->symbol->svg_text)
+                        else IF_GET_LONG("antialias", php_symbol->symbol->antialias)
+                          else IF_GET_DOUBLE("anchorpoint_y", php_symbol->symbol->anchorpoint_y)
+                            else IF_GET_DOUBLE("anchorpoint_x", php_symbol->symbol->anchorpoint_x)
+                              else IF_GET_DOUBLE("maxx", php_symbol->symbol->maxx)
+                                else IF_GET_DOUBLE("minx", php_symbol->symbol->minx)
+                                  else IF_GET_DOUBLE("miny", php_symbol->symbol->miny)
+                                    else IF_GET_DOUBLE("maxy", php_symbol->symbol->maxy)
+                                      else IF_GET_STRING("font", php_symbol->symbol->font)
+                                        else {
+                                          mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+                                        }
 }
 
 PHP_METHOD(symbolObj, __set)
 {
-    char *property;
-    long property_len;
-    zval *value;
-    zval *zobj = getThis();
-    php_symbol_object *php_symbol;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
-                              &property, &property_len, &value) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *value;
+  zval *zobj = getThis();
+  php_symbol_object *php_symbol;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
+                            &property, &property_len, &value) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_symbol = (php_symbol_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-
-    IF_SET_STRING("name", php_symbol->symbol->name, value)
-    else IF_SET_LONG("type", php_symbol->symbol->type, value) 
-    else IF_SET_LONG("inmapfile", php_symbol->symbol->inmapfile, value) 
-    else IF_SET_DOUBLE("sizex", php_symbol->symbol->sizex, value) 
-    else IF_SET_DOUBLE("sizey", php_symbol->symbol->sizey, value) 
-    else IF_SET_LONG("filled", php_symbol->symbol->filled, value) 
-    else IF_SET_LONG("transparent", php_symbol->symbol->transparent, value) 
-    else IF_SET_LONG("transparentcolor", php_symbol->symbol->transparentcolor, value) 
-    else IF_SET_STRING("character", php_symbol->symbol->character, value)
-    else IF_SET_LONG("antialias", php_symbol->symbol->antialias, value) 
-    else IF_SET_STRING("font", php_symbol->symbol->font, value)
-    else if ( (STRING_EQUAL("numpoints", property)) ||
-         (STRING_EQUAL("imagepath", property)))
-    {
-        mapscript_throw_exception("Property '%s' is read-only and cannot be set." TSRMLS_CC, property);
-    }
-    else 
-    {
-        mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_symbol = (php_symbol_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  IF_SET_STRING("name", php_symbol->symbol->name, value)
+  else IF_SET_LONG("type", php_symbol->symbol->type, value)
+    else IF_SET_LONG("inmapfile", php_symbol->symbol->inmapfile, value)
+      else IF_SET_DOUBLE("sizex", php_symbol->symbol->sizex, value)
+        else IF_SET_DOUBLE("sizey", php_symbol->symbol->sizey, value)
+          else IF_SET_LONG("filled", php_symbol->symbol->filled, value)
+            else IF_SET_LONG("transparent", php_symbol->symbol->transparent, value)
+              else IF_SET_LONG("transparentcolor", php_symbol->symbol->transparentcolor, value)
+                else IF_SET_STRING("character", php_symbol->symbol->character, value)
+                  else IF_SET_STRING("svg_text", php_symbol->symbol->svg_text, value)
+                    else IF_SET_LONG("antialias", php_symbol->symbol->antialias, value)
+                      else IF_SET_STRING("font", php_symbol->symbol->font, value)
+                        else IF_SET_DOUBLE("anchorpoint_y", php_symbol->symbol->anchorpoint_y, value)
+                          else IF_SET_DOUBLE("anchorpoint_x", php_symbol->symbol->anchorpoint_x, value)
+                            else IF_SET_DOUBLE("maxx", php_symbol->symbol->maxx, value)
+                              else IF_SET_DOUBLE("maxy", php_symbol->symbol->maxy, value)
+                                else IF_SET_DOUBLE("minx", php_symbol->symbol->minx, value)
+                                  else IF_SET_DOUBLE("miny", php_symbol->symbol->miny, value)
+                                    else if ( (STRING_EQUAL("numpoints", property)) ||
+                                              (STRING_EQUAL("imagepath", property))) {
+                                      mapscript_throw_exception("Property '%s' is read-only and cannot be set." TSRMLS_CC, property);
+                                    } else {
+                                      mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+                                    }
 }
 
 /* {{{ proto int symbol.setpoints(array points)
-   Set the points of the symbol ) */ 
+   Set the points of the symbol ) */
 PHP_METHOD(symbolObj, setPoints)
 {
-    zval *zpoints, **ppzval;
-    HashTable *points_hash = NULL;
-    zval *zobj = getThis();
-    int index = 0, flag = 0, numelements = 0;
-    php_symbol_object *php_symbol;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a",
-                              &zpoints) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zpoints, **ppzval;
+  HashTable *points_hash = NULL;
+  zval *zobj = getThis();
+  int index = 0, flag = 0, numelements = 0;
+  php_symbol_object *php_symbol;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a",
+                            &zpoints) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_symbol = (php_symbol_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-    points_hash = Z_ARRVAL_P(zpoints);
-
-    numelements = zend_hash_num_elements(points_hash);
-    if ((numelements == 0) || (numelements % 2 != 0))
-    {
-        mapscript_report_php_error(E_WARNING, 
-                                   "symbol->setpoints : invalid array of %d element(s) as parameter." TSRMLS_CC, numelements);
-        RETURN_LONG(MS_FAILURE);
-        
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_symbol = (php_symbol_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  points_hash = Z_ARRVAL_P(zpoints);
+
+  numelements = zend_hash_num_elements(points_hash);
+  if ((numelements == 0) || (numelements % 2 != 0)) {
+    mapscript_report_php_error(E_WARNING,
+                               "symbol->setpoints : invalid array of %d element(s) as parameter." TSRMLS_CC, numelements);
+    RETURN_LONG(MS_FAILURE);
+
+  }
+
+  for(zend_hash_internal_pointer_reset(points_hash);
+      zend_hash_has_more_elements(points_hash) == SUCCESS;
+      zend_hash_move_forward(points_hash)) {
+
+    zend_hash_get_current_data(points_hash, (void **)&ppzval);
+    if (Z_TYPE_PP(ppzval) != IS_DOUBLE)
+      convert_to_double(*ppzval);
+
+    if (!flag) {
+      php_symbol->symbol->points[index].x = Z_DVAL_PP(ppzval);
+      php_symbol->symbol->sizex = MS_MAX(php_symbol->symbol->sizex, php_symbol->symbol->points[index].x);
+    } else {
+      php_symbol->symbol->points[index].y = Z_DVAL_PP(ppzval);
+      php_symbol->symbol->sizey = MS_MAX(php_symbol->symbol->sizey, php_symbol->symbol->points[index].y);
+      index++;
     }
+    flag = !flag;
+  }
 
-    for(zend_hash_internal_pointer_reset(points_hash); 
-        zend_hash_has_more_elements(points_hash) == SUCCESS; 
-        zend_hash_move_forward(points_hash))
-    { 
-        
-        zend_hash_get_current_data(points_hash, (void **)&ppzval);
-        if (Z_TYPE_PP(ppzval) != IS_DOUBLE)
-            convert_to_double(*ppzval);
-	     
-        if (!flag)
-        {
-            php_symbol->symbol->points[index].x = Z_DVAL_PP(ppzval);
-            php_symbol->symbol->sizex = MS_MAX(php_symbol->symbol->sizex, php_symbol->symbol->points[index].x);
-        }
-        else
-        {
-            php_symbol->symbol->points[index].y = Z_DVAL_PP(ppzval);
-            php_symbol->symbol->sizey = MS_MAX(php_symbol->symbol->sizey, php_symbol->symbol->points[index].y);
-            index++;
-        }    
-        flag = !flag;
-    }
+  php_symbol->symbol->numpoints = (numelements/2);
 
-    php_symbol->symbol->numpoints = (numelements/2);
-
-    RETURN_LONG(MS_SUCCESS);
+  RETURN_LONG(MS_SUCCESS);
 }
 /* }}} */
 
 /* {{{ proto int symbol.getPointsArray()
-   Returns an array containing the points of the symbol. 
+   Returns an array containing the points of the symbol.
    Refer to setpoints to see how the array should be interpreted. */
 PHP_METHOD(symbolObj, getPointsArray)
 {
-    zval *zobj = getThis();
-    php_symbol_object *php_symbol;
-    int index;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  php_symbol_object *php_symbol;
+  int index;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_symbol = (php_symbol_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_symbol = (php_symbol_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    array_init(return_value);
+  array_init(return_value);
 
-    if (php_symbol->symbol->numpoints > 0)
-    {
-        for (index=0; index < php_symbol->symbol->numpoints; index++)
-        {
-            add_next_index_double(return_value, php_symbol->symbol->points[index].x);
-            add_next_index_double(return_value, php_symbol->symbol->points[index].y);
-        }
+  if (php_symbol->symbol->numpoints > 0) {
+    for (index=0; index < php_symbol->symbol->numpoints; index++) {
+      add_next_index_double(return_value, php_symbol->symbol->points[index].x);
+      add_next_index_double(return_value, php_symbol->symbol->points[index].y);
     }
+  }
 }
 /* }}} */
 
 
 
 /* {{{ proto int symbol.setimagepath(char *imagefile)
-   loads a new symbol image  ) */ 
+   loads a new symbol image  ) */
 PHP_METHOD(symbolObj, setImagePath)
 {
-    zval *zobj = getThis();
-    php_symbol_object *php_symbol;
-    char *filename;
-    long filename_len;
-    int status = MS_FAILURE;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &filename, &filename_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  php_symbol_object *php_symbol;
+  char *filename;
+  long filename_len;
+  int status = MS_FAILURE;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &filename, &filename_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    php_symbol = (php_symbol_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+  php_symbol = (php_symbol_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    status = msLoadImageSymbol(php_symbol->symbol, filename);
-    
-    if (status != MS_SUCCESS)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
+  status = msLoadImageSymbol(php_symbol->symbol, filename);
 
-    RETURN_LONG(status);
+  if (status != MS_SUCCESS) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
+/* {{{ proto int setImage(imageObj image)
+   Set image pixmap symbol */
+PHP_METHOD(symbolObj, setImage)
+{
+  zval *zimage;
+  php_symbol_object *php_symbol;
+  php_image_object *php_image;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
+                            &zimage, mapscript_ce_image) == FAILURE) {
+    PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_symbol = (php_symbol_object *)zend_object_store_get_object(getThis() TSRMLS_CC);
+  php_image = (php_image_object *)zend_object_store_get_object(zimage TSRMLS_CC);
+
+  RETURN_LONG(symbolObj_setImage(php_symbol->symbol, php_image->image));
+}
+/* }}} */
+
+/* {{{ proto imageObj getImage(outputFormatObj outputformat)
+   Get the symbol image */
+PHP_METHOD(symbolObj, getImage)
+{
+  zval *zoutputformat;
+  imageObj *image = NULL;
+  php_map_object *php_map;
+  php_symbol_object *php_symbol;
+  php_outputformat_object *php_outputformat;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O",
+                            &zoutputformat, mapscript_ce_outputformat) == FAILURE) {
+    PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_symbol = (php_symbol_object *)zend_object_store_get_object(getThis() TSRMLS_CC);
+  php_map = (php_map_object *) zend_object_store_get_object(php_symbol->parent.val TSRMLS_CC);
+  php_outputformat = (php_outputformat_object *)zend_object_store_get_object(zoutputformat TSRMLS_CC);
+
+  image = symbolObj_getImage(php_symbol->symbol, php_outputformat->outputformat);
+  if (image == NULL) {
+    mapscript_throw_exception("Unable to get the symbol image" TSRMLS_CC);
+    return;
+  }
+
+  /* the outputformat HAS to be added to the map, since the renderer is now used
+     by the current symbol */
+  if (msGetOutputFormatIndex(php_map->map, php_outputformat->outputformat->name) == -1)
+    msAppendOutputFormat(php_map->map, php_outputformat->outputformat);
+
+  mapscript_create_image(image, return_value TSRMLS_CC);
+  } /* }}} */
+
 zend_function_entry symbol_functions[] = {
-    PHP_ME(symbolObj, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
-    PHP_ME(symbolObj, __get, symbol___get_args, ZEND_ACC_PUBLIC)
-    PHP_ME(symbolObj, __set, symbol___set_args, ZEND_ACC_PUBLIC)
-    PHP_MALIAS(symbolObj, set, __set, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(symbolObj, setPoints, symbol_setPoints_args, ZEND_ACC_PUBLIC)
-    PHP_ME(symbolObj, getPointsArray, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(symbolObj, setImagePath, symbol_setImagePath_args, ZEND_ACC_PUBLIC)
-    {NULL, NULL, NULL}
+  PHP_ME(symbolObj, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
+  PHP_ME(symbolObj, __get, symbol___get_args, ZEND_ACC_PUBLIC)
+  PHP_ME(symbolObj, __set, symbol___set_args, ZEND_ACC_PUBLIC)
+  PHP_MALIAS(symbolObj, set, __set, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(symbolObj, setPoints, symbol_setPoints_args, ZEND_ACC_PUBLIC)
+  PHP_ME(symbolObj, getPointsArray, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(symbolObj, setImage, symbol_setImage_args, ZEND_ACC_PUBLIC)
+  PHP_ME(symbolObj, getImage, symbol_getImage_args, ZEND_ACC_PUBLIC)
+  PHP_ME(symbolObj, setImagePath, symbol_setImagePath_args, ZEND_ACC_PUBLIC) {
+    NULL, NULL, NULL
+  }
 };
 
 void mapscript_create_symbol(symbolObj *symbol, parent_object parent, zval *return_value TSRMLS_DC)
 {
-    php_symbol_object * php_symbol;
-    object_init_ex(return_value, mapscript_ce_symbol); 
-    php_symbol = (php_symbol_object *)zend_object_store_get_object(return_value TSRMLS_CC);
-    php_symbol->symbol = symbol;
+  php_symbol_object * php_symbol;
+  object_init_ex(return_value, mapscript_ce_symbol);
+  php_symbol = (php_symbol_object *)zend_object_store_get_object(return_value TSRMLS_CC);
+  php_symbol->symbol = symbol;
 
-    php_symbol->parent = parent;
+  php_symbol->parent = parent;
 
-    MAPSCRIPT_ADDREF(parent.val);
+  MAPSCRIPT_ADDREF(parent.val);
 }
 
 static void mapscript_symbol_object_destroy(void *object TSRMLS_DC)
 {
-    php_symbol_object *php_symbol = (php_symbol_object *)object;
+  php_symbol_object *php_symbol = (php_symbol_object *)object;
 
-    MAPSCRIPT_FREE_OBJECT(php_symbol);
+  MAPSCRIPT_FREE_OBJECT(php_symbol);
 
-    MAPSCRIPT_FREE_PARENT(php_symbol->parent);
+  MAPSCRIPT_FREE_PARENT(php_symbol->parent);
 
-    /* We don't need to free the symbolObj */ 
-    
-    efree(object);
+  /* We don't need to free the symbolObj */
+
+  efree(object);
 }
 
 static zend_object_value mapscript_symbol_object_new(zend_class_entry *ce TSRMLS_DC)
 {
-    zend_object_value retval;
-    php_symbol_object *php_symbol;
+  zend_object_value retval;
+  php_symbol_object *php_symbol;
 
-    MAPSCRIPT_ALLOC_OBJECT(php_symbol, php_symbol_object);
+  MAPSCRIPT_ALLOC_OBJECT(php_symbol, php_symbol_object);
 
-    retval = mapscript_object_new(&php_symbol->std, ce,
-                                  &mapscript_symbol_object_destroy TSRMLS_CC);
+  retval = mapscript_object_new(&php_symbol->std, ce,
+                                &mapscript_symbol_object_destroy TSRMLS_CC);
 
-    MAPSCRIPT_INIT_PARENT(php_symbol->parent);
+  MAPSCRIPT_INIT_PARENT(php_symbol->parent);
 
-    return retval;
+  return retval;
 }
 
 PHP_MINIT_FUNCTION(symbol)
 {
-    zend_class_entry ce;
+  zend_class_entry ce;
+
+  MAPSCRIPT_REGISTER_CLASS("symbolObj",
+                           symbol_functions,
+                           mapscript_ce_symbol,
+                           mapscript_symbol_object_new);
 
-    MAPSCRIPT_REGISTER_CLASS("symbolObj", 
-                             symbol_functions,
-                             mapscript_ce_symbol,
-                             mapscript_symbol_object_new);
+  mapscript_ce_symbol->ce_flags |= ZEND_ACC_FINAL_CLASS;
 
-    mapscript_ce_symbol->ce_flags |= ZEND_ACC_FINAL_CLASS; 
-    
-    return SUCCESS;
+  return SUCCESS;
 }
diff --git a/mapscript/php/web.c b/mapscript/php/web.c
index 62d377d..82a96e2 100644
--- a/mapscript/php/web.c
+++ b/mapscript/php/web.c
@@ -2,7 +2,7 @@
  * $Id: php_mapscript.c 9765 2010-01-28 15:32:10Z aboudreault $
  *
  * Project:  MapServer
- * Purpose:  PHP/MapScript extension for MapServer.  External interface 
+ * Purpose:  PHP/MapScript extension for MapServer.  External interface
  *           functions
  * Author:   Daniel Morissette, DM Solutions Group (dmorissette at dmsolutions.ca)
  *           Alan Boudreault, Mapgears
@@ -16,16 +16,16 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
+ *
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  * DEALINGS IN THE SOFTWARE.
  **********************************************************************/
 
@@ -34,144 +34,139 @@
 zend_class_entry *mapscript_ce_web;
 
 ZEND_BEGIN_ARG_INFO_EX(web___get_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, property)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(web___set_args, 0, 0, 2)
-  ZEND_ARG_INFO(0, property)
-  ZEND_ARG_INFO(0, value)
+ZEND_ARG_INFO(0, property)
+ZEND_ARG_INFO(0, value)
 ZEND_END_ARG_INFO()
 
 ZEND_BEGIN_ARG_INFO_EX(web_updateFromString_args, 0, 0, 1)
-  ZEND_ARG_INFO(0, snippet)
+ZEND_ARG_INFO(0, snippet)
 ZEND_END_ARG_INFO()
 
 /* {{{ proto web __construct()
    webObj CANNOT be instanciated, this will throw an exception on use */
 PHP_METHOD(webObj, __construct)
 {
-    mapscript_throw_exception("webObj cannot be constructed" TSRMLS_CC);
+  mapscript_throw_exception("webObj cannot be constructed" TSRMLS_CC);
 }
 /* }}} */
 
 PHP_METHOD(webObj, __get)
 {
-    char *property;
-    long property_len;
-    zval *zobj = getThis();
-    php_web_object *php_web;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &property, &property_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *zobj = getThis();
+  php_web_object *php_web;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &property, &property_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_web = (php_web_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_web = (php_web_object *) zend_object_store_get_object(zobj TSRMLS_CC);
 
-    IF_GET_STRING("log", php_web->web->log)
-    else IF_GET_STRING("imagepath", php_web->web->imagepath)
+  IF_GET_STRING("log", php_web->web->log)
+  else IF_GET_STRING("imagepath", php_web->web->imagepath)
     else IF_GET_STRING("template", php_web->web->template)
-    else IF_GET_STRING("imageurl", php_web->web->imageurl)
-    else IF_GET_STRING("temppath", php_web->web->temppath)
-    else IF_GET_STRING("header", php_web->web->header)
-    else IF_GET_STRING("footer", php_web->web->footer)
-    else IF_GET_STRING("empty", php_web->web->empty)
-    else IF_GET_STRING("error", php_web->web->error)
-    else IF_GET_STRING("mintemplate", php_web->web->mintemplate)
-    else IF_GET_STRING("maxtemplate", php_web->web->maxtemplate)
-    else IF_GET_DOUBLE("minscaledenom", php_web->web->minscaledenom) 
-    else IF_GET_DOUBLE("maxscaledenom", php_web->web->maxscaledenom) 
-    else IF_GET_STRING("queryformat", php_web->web->queryformat)
-    else IF_GET_STRING("legendformat", php_web->web->legendformat)
-    else IF_GET_STRING("browseformat", php_web->web->browseformat)
-    else IF_GET_OBJECT("extent", mapscript_ce_rect, php_web->extent, &php_web->web->extent)
-    else IF_GET_OBJECT("metadata", mapscript_ce_web, php_web->metadata, &php_web->web->metadata)
-    else 
-    {
-        mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }
+      else IF_GET_STRING("imageurl", php_web->web->imageurl)
+        else IF_GET_STRING("temppath", php_web->web->temppath)
+          else IF_GET_STRING("header", php_web->web->header)
+            else IF_GET_STRING("footer", php_web->web->footer)
+              else IF_GET_STRING("empty", php_web->web->empty)
+                else IF_GET_STRING("error", php_web->web->error)
+                  else IF_GET_STRING("mintemplate", php_web->web->mintemplate)
+                    else IF_GET_STRING("maxtemplate", php_web->web->maxtemplate)
+                      else IF_GET_DOUBLE("minscaledenom", php_web->web->minscaledenom)
+                        else IF_GET_DOUBLE("maxscaledenom", php_web->web->maxscaledenom)
+                          else IF_GET_STRING("queryformat", php_web->web->queryformat)
+                            else IF_GET_STRING("legendformat", php_web->web->legendformat)
+                              else IF_GET_STRING("browseformat", php_web->web->browseformat)
+                                else IF_GET_OBJECT("extent", mapscript_ce_rect, php_web->extent, &php_web->web->extent)
+                                  else IF_GET_OBJECT("metadata", mapscript_ce_hashtable, php_web->metadata, &php_web->web->metadata)
+                                    else IF_GET_OBJECT("validation", mapscript_ce_hashtable, php_web->validation, &php_web->web->validation)
+                                      else {
+                                        mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+                                      }
 }
 
 PHP_METHOD(webObj, __set)
 {
-    char *property;
-    long property_len;
-    zval *value;
-    zval *zobj = getThis();
-    php_web_object *php_web;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
-                              &property, &property_len, &value) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *property;
+  long property_len;
+  zval *value;
+  zval *zobj = getThis();
+  php_web_object *php_web;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz",
+                            &property, &property_len, &value) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_web = (php_web_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    IF_SET_STRING("log", php_web->web->log, value)
-    else IF_SET_STRING("imagepath", php_web->web->imagepath, value)
+  php_web = (php_web_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  IF_SET_STRING("log", php_web->web->log, value)
+  else IF_SET_STRING("imagepath", php_web->web->imagepath, value)
     else IF_SET_STRING("template", php_web->web->template, value)
-    else IF_SET_STRING("imageurl", php_web->web->imageurl, value)
-    else IF_SET_STRING("temppath", php_web->web->temppath, value)
-    else IF_SET_STRING("header", php_web->web->header, value)
-    else IF_SET_STRING("footer", php_web->web->footer, value)
-    else IF_SET_STRING("mintemplate", php_web->web->mintemplate, value)
-    else IF_SET_STRING("maxtemplate", php_web->web->maxtemplate, value)
-    else IF_SET_DOUBLE("minscaledenom", php_web->web->minscaledenom, value) 
-    else IF_SET_DOUBLE("maxscaledenom", php_web->web->maxscaledenom, value) 
-    else IF_SET_STRING("queryformat", php_web->web->queryformat, value)
-    else IF_SET_STRING("legendformat", php_web->web->legendformat, value)
-    else IF_SET_STRING("browseformat", php_web->web->browseformat, value)
-    else if ( (STRING_EQUAL("empty", property)) ||
-              (STRING_EQUAL("error", property)) ||
-              (STRING_EQUAL("extent", property)))
-    {
-        mapscript_throw_exception("Property '%s' is read-only and cannot be set." TSRMLS_CC, property);
-    }
-    else if (STRING_EQUAL("metadata", property))
-    {
-        mapscript_throw_exception("Property '%s' is an object and can only be modified through its accessors." TSRMLS_CC, property);
-    }
-    else 
-    {
-        mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
-    }
+      else IF_SET_STRING("imageurl", php_web->web->imageurl, value)
+        else IF_SET_STRING("temppath", php_web->web->temppath, value)
+          else IF_SET_STRING("header", php_web->web->header, value)
+            else IF_SET_STRING("footer", php_web->web->footer, value)
+              else IF_SET_STRING("mintemplate", php_web->web->mintemplate, value)
+                else IF_SET_STRING("maxtemplate", php_web->web->maxtemplate, value)
+                  else IF_SET_DOUBLE("minscaledenom", php_web->web->minscaledenom, value)
+                    else IF_SET_DOUBLE("maxscaledenom", php_web->web->maxscaledenom, value)
+                      else IF_SET_STRING("queryformat", php_web->web->queryformat, value)
+                        else IF_SET_STRING("legendformat", php_web->web->legendformat, value)
+                          else IF_SET_STRING("browseformat", php_web->web->browseformat, value)
+                            else if ( (STRING_EQUAL("empty", property)) ||
+                                      (STRING_EQUAL("error", property)) ||
+                                      (STRING_EQUAL("extent", property))) {
+                              mapscript_throw_exception("Property '%s' is read-only and cannot be set." TSRMLS_CC, property);
+                            } else if ( (STRING_EQUAL("metadata", property)) ||
+                                        (STRING_EQUAL("validation", property)) ) {
+                              mapscript_throw_exception("Property '%s' is an object and can only be modified through its accessors." TSRMLS_CC, property);
+                            } else {
+                              mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property);
+                            }
 }
 
 /* {{{ proto int web.updateFromString(string snippet)
    Update a web from a string snippet.  Returns MS_SUCCESS/MS_FAILURE */
 PHP_METHOD(webObj, updateFromString)
 {
-    char *snippet;
-    long snippet_len;
-    zval *zobj = getThis();
-    php_web_object *php_web;
-    int status = MS_FAILURE;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
-                              &snippet, &snippet_len) == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  char *snippet;
+  long snippet_len;
+  zval *zobj = getThis();
+  php_web_object *php_web;
+  int status = MS_FAILURE;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
+                            &snippet, &snippet_len) == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_web = (php_web_object *) zend_object_store_get_object(zobj TSRMLS_CC);
-
-    status =  webObj_updateFromString(php_web->web, snippet);
-    
-    if (status != MS_SUCCESS)
-    {
-        mapscript_throw_mapserver_exception("" TSRMLS_CC);
-        return;
-    }
-
-    RETURN_LONG(status);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
+
+  php_web = (php_web_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  status =  webObj_updateFromString(php_web->web, snippet);
+
+  if (status != MS_SUCCESS) {
+    mapscript_throw_mapserver_exception("" TSRMLS_CC);
+    return;
+  }
+
+  RETURN_LONG(status);
 }
 /* }}} */
 
@@ -179,86 +174,90 @@ PHP_METHOD(webObj, updateFromString)
    Free the object. */
 PHP_METHOD(webObj, free)
 {
-    zval *zobj = getThis();
-    php_web_object *php_web;
-
-    PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
-    if (zend_parse_parameters_none() == FAILURE) {
-        PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-        return;
-    }
+  zval *zobj = getThis();
+  php_web_object *php_web;
+
+  PHP_MAPSCRIPT_ERROR_HANDLING(TRUE);
+  if (zend_parse_parameters_none() == FAILURE) {
     PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
-    
-    php_web = (php_web_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+    return;
+  }
+  PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE);
 
-    MAPSCRIPT_DELREF(php_web->extent);
-    MAPSCRIPT_DELREF(php_web->metadata);
+  php_web = (php_web_object *) zend_object_store_get_object(zobj TSRMLS_CC);
+
+  MAPSCRIPT_DELREF(php_web->extent);
+  MAPSCRIPT_DELREF(php_web->metadata);
+  MAPSCRIPT_DELREF(php_web->validation);
 }
 /* }}} */
 
 zend_function_entry web_functions[] = {
-    PHP_ME(webObj, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
-    PHP_ME(webObj, __get, web___get_args, ZEND_ACC_PUBLIC)
-    PHP_ME(webObj, __set, web___set_args, ZEND_ACC_PUBLIC)
-    PHP_MALIAS(webObj, set, __set, NULL, ZEND_ACC_PUBLIC)
-    PHP_ME(webObj, updateFromString, web_updateFromString_args, ZEND_ACC_PUBLIC)
-    PHP_ME(webObj, free, NULL, ZEND_ACC_PUBLIC)
-    {NULL, NULL, NULL}
+  PHP_ME(webObj, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
+  PHP_ME(webObj, __get, web___get_args, ZEND_ACC_PUBLIC)
+  PHP_ME(webObj, __set, web___set_args, ZEND_ACC_PUBLIC)
+  PHP_MALIAS(webObj, set, __set, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(webObj, updateFromString, web_updateFromString_args, ZEND_ACC_PUBLIC)
+  PHP_ME(webObj, free, NULL, ZEND_ACC_PUBLIC) {
+    NULL, NULL, NULL
+  }
 };
 
 void mapscript_create_web(webObj *web, parent_object parent, zval *return_value TSRMLS_DC)
 {
-    php_web_object * php_web;
-    object_init_ex(return_value, mapscript_ce_web); 
-    php_web = (php_web_object *)zend_object_store_get_object(return_value TSRMLS_CC);
-    php_web->web = web;
+  php_web_object * php_web;
+  object_init_ex(return_value, mapscript_ce_web);
+  php_web = (php_web_object *)zend_object_store_get_object(return_value TSRMLS_CC);
+  php_web->web = web;
 
-    php_web->parent = parent;
-    MAPSCRIPT_ADDREF(parent.val);
+  php_web->parent = parent;
+  MAPSCRIPT_ADDREF(parent.val);
 }
 
 static void mapscript_web_object_destroy(void *object TSRMLS_DC)
 {
-    php_web_object *php_web = (php_web_object *)object;
+  php_web_object *php_web = (php_web_object *)object;
+
+  MAPSCRIPT_FREE_OBJECT(php_web);
 
-    MAPSCRIPT_FREE_OBJECT(php_web);
+  MAPSCRIPT_FREE_PARENT(php_web->parent);
+  MAPSCRIPT_DELREF(php_web->extent);
+  MAPSCRIPT_DELREF(php_web->metadata);
+  MAPSCRIPT_DELREF(php_web->validation);
 
-    MAPSCRIPT_FREE_PARENT(php_web->parent);
-    MAPSCRIPT_DELREF(php_web->extent);
-    MAPSCRIPT_DELREF(php_web->metadata);
+  /* We don't need to free the webObj */
 
-    /* We don't need to free the webObj */ 
-    
-    efree(object);
+  efree(object);
 }
 
 static zend_object_value mapscript_web_object_new(zend_class_entry *ce TSRMLS_DC)
 {
-    zend_object_value retval;
-    php_web_object *php_web;
+  zend_object_value retval;
+  php_web_object *php_web;
 
-    MAPSCRIPT_ALLOC_OBJECT(php_web, php_web_object);
+  MAPSCRIPT_ALLOC_OBJECT(php_web, php_web_object);
 
-    retval = mapscript_object_new(&php_web->std, ce,
-                                  &mapscript_web_object_destroy TSRMLS_CC);
+  retval = mapscript_object_new(&php_web->std, ce,
+                                &mapscript_web_object_destroy TSRMLS_CC);
 
-    MAPSCRIPT_INIT_PARENT(php_web->parent);
-    php_web->extent = NULL;
-    php_web->metadata = NULL;
+  MAPSCRIPT_INIT_PARENT(php_web->parent);
+  php_web->extent = NULL;
+  php_web->metadata = NULL;
+  php_web->validation = NULL;
 
-    return retval;
+  return retval;
 }
 
 PHP_MINIT_FUNCTION(web)
 {
-    zend_class_entry ce;
+  zend_class_entry ce;
+
+  MAPSCRIPT_REGISTER_CLASS("webObj",
+                           web_functions,
+                           mapscript_ce_web,
+                           mapscript_web_object_new);
 
-    MAPSCRIPT_REGISTER_CLASS("webObj", 
-                             web_functions,
-                             mapscript_ce_web,
-                             mapscript_web_object_new);
+  mapscript_ce_web->ce_flags |= ZEND_ACC_FINAL_CLASS;
 
-    mapscript_ce_web->ce_flags |= ZEND_ACC_FINAL_CLASS; 
-    
-    return SUCCESS;
+  return SUCCESS;
 }
diff --git a/mapscript/python/Makefile.in b/mapscript/python/Makefile.in
new file mode 100644
index 0000000..a6007ab
--- /dev/null
+++ b/mapscript/python/Makefile.in
@@ -0,0 +1,63 @@
+# Run ./configure in the main MapServer directory to turn this Makefile.in
+# into a proper Makefile
+
+prefix		=	@prefix@
+exec_prefix	=	@exec_prefix@
+libdir	=	@libdir@
+bindir	=	@bindir@
+top_builddir = @top_builddir@
+SHELL = @SHELL@
+CXX=	@CXX@
+CC=     @CC@
+LD=     @CXX@
+LIBTOOL=@LIBTOOL@
+INSTALL=@INSTALL@
+PYTHON=@PYTHON@
+SWIG=@SWIG@
+
+LTCC=$(LIBTOOL) --mode=compile --tag=CC
+LTCXX=$(LIBTOOL) --mode=compile --tag=CXX
+LTLD=$(LIBTOOL) --mode=link --tag=CXX
+LTINSTALL=$(LIBTOOL) --mode=install
+
+XTRALIBS= @XTRALIBS@
+
+
+PYLIBDIR=`$(PYTHON) -c "from distutils.sysconfig import get_python_lib; print get_python_lib(1)"`
+PYINCDIR=`$(PYTHON) -c "from distutils.sysconfig import get_python_inc; print get_python_inc(1)"`
+
+RUNPATH= -rpath $(PYLIBDIR)
+DEFINES=@ALL_ENABLED@
+CFLAGS = $(DEFINES) @CFLAGS@ -I$(PYINCDIR) @MS_INC@ @ALL_INC@
+
+LT_LDFLAGS= $(RUNPATH) -module
+OBJ_SUFFIX=lo
+LINK=$(LTLD) $(LD) $(LT_LDFLAGS)
+MS_LIB =   $(top_builddir)/libmapserver.la
+
+
+.SUFFIXES:
+.SUFFIXES: .cpp .c .$(OBJ_SUFFIX)
+
+all: _mapscript.la
+
+_mapscript.la: mapscript_wrap.lo pygdioctx/pygdioctx.lo $(MS_LIB)
+	$(LINK) -o $@ mapscript_wrap.lo pygdioctx/pygdioctx.lo $(MS_LIB)
+
+%.lo: %.c
+	$(LTCC) $(CC) $(CFLAGS) -c -o $@ $<
+
+mapscript_wrap.c: ../mapscript.i
+	@test -n "$(SWIG)" || (echo "swig binary not found, cannot procede. install swig and rerun ./configure"; exit 1;)
+	$(SWIG) -python -shadow -modern -templatereduce -fastdispatch -fvirtual -fastproxy -modernargs -castmode -dirvtable -fastinit -fastquery -noproxydel -nobuildnone $(DEFINES) -o mapscript_wrap.c ../mapscript.i
+
+install-dirs:
+	$(INSTALL) -d $(DESTDIR)$(PYLIBDIR)
+
+install: install-dirs _mapscript.la
+	$(LTINSTALL) $(INSTALL) _mapscript.la $(DESTDIR)$(PYLIBDIR)
+	$(INSTALL) -c mapscript.py $(DESTDIR)$(PYLIBDIR)
+
+clean:
+	-rm -rf .libs *.lo *.la *.so *.o pygdioctx/.libs pygdioctx/*.o pygdioctx/*.lo mapscript_wrap.c mapscript.py
+
diff --git a/mapscript/python/mapscript.py b/mapscript/python/mapscript.py
index 90573eb..6b43c81 100644
--- a/mapscript/python/mapscript.py
+++ b/mapscript/python/mapscript.py
@@ -98,7 +98,6 @@ MS_VERSION_MAJOR = _mapscript.MS_VERSION_MAJOR
 MS_VERSION_MINOR = _mapscript.MS_VERSION_MINOR
 MS_VERSION_REV = _mapscript.MS_VERSION_REV
 MS_VERSION_NUM = _mapscript.MS_VERSION_NUM
-__FUNCTION__ = _mapscript.__FUNCTION__
 MS_TRUE = _mapscript.MS_TRUE
 MS_FALSE = _mapscript.MS_FALSE
 MS_UNKNOWN = _mapscript.MS_UNKNOWN
@@ -113,8 +112,11 @@ MS_GD_ALPHA = _mapscript.MS_GD_ALPHA
 MS_LAYER_ALLOCSIZE = _mapscript.MS_LAYER_ALLOCSIZE
 MS_CLASS_ALLOCSIZE = _mapscript.MS_CLASS_ALLOCSIZE
 MS_STYLE_ALLOCSIZE = _mapscript.MS_STYLE_ALLOCSIZE
+MS_LABEL_ALLOCSIZE = _mapscript.MS_LABEL_ALLOCSIZE
 MS_MAX_LABEL_PRIORITY = _mapscript.MS_MAX_LABEL_PRIORITY
+MS_MAX_LABEL_FONTS = _mapscript.MS_MAX_LABEL_FONTS
 MS_DEFAULT_LABEL_PRIORITY = _mapscript.MS_DEFAULT_LABEL_PRIORITY
+MS_LABEL_FORCE_GROUP = _mapscript.MS_LABEL_FORCE_GROUP
 MS_RENDER_WITH_SWF = _mapscript.MS_RENDER_WITH_SWF
 MS_RENDER_WITH_RAWDATA = _mapscript.MS_RENDER_WITH_RAWDATA
 MS_RENDER_WITH_IMAGEMAP = _mapscript.MS_RENDER_WITH_IMAGEMAP
@@ -192,6 +194,7 @@ MS_MYSQL = _mapscript.MS_MYSQL
 MS_RASTER = _mapscript.MS_RASTER
 MS_PLUGIN = _mapscript.MS_PLUGIN
 MS_UNION = _mapscript.MS_UNION
+MS_UVRASTER = _mapscript.MS_UVRASTER
 MS_DB_XBASE = _mapscript.MS_DB_XBASE
 MS_DB_CSV = _mapscript.MS_DB_CSV
 MS_DB_MYSQL = _mapscript.MS_DB_MYSQL
@@ -256,6 +259,10 @@ MS_STYLE_BINDING_OUTLINECOLOR = _mapscript.MS_STYLE_BINDING_OUTLINECOLOR
 MS_STYLE_BINDING_SYMBOL = _mapscript.MS_STYLE_BINDING_SYMBOL
 MS_STYLE_BINDING_OUTLINEWIDTH = _mapscript.MS_STYLE_BINDING_OUTLINEWIDTH
 MS_STYLE_BINDING_OPACITY = _mapscript.MS_STYLE_BINDING_OPACITY
+MS_STYLE_BINDING_OFFSET_X = _mapscript.MS_STYLE_BINDING_OFFSET_X
+MS_STYLE_BINDING_OFFSET_Y = _mapscript.MS_STYLE_BINDING_OFFSET_Y
+MS_STYLE_BINDING_POLAROFFSET_PIXEL = _mapscript.MS_STYLE_BINDING_POLAROFFSET_PIXEL
+MS_STYLE_BINDING_POLAROFFSET_ANGLE = _mapscript.MS_STYLE_BINDING_POLAROFFSET_ANGLE
 MS_LABEL_BINDING_LENGTH = _mapscript.MS_LABEL_BINDING_LENGTH
 MS_LABEL_BINDING_SIZE = _mapscript.MS_LABEL_BINDING_SIZE
 MS_LABEL_BINDING_ANGLE = _mapscript.MS_LABEL_BINDING_ANGLE
@@ -321,6 +328,7 @@ MS_TOKEN_FUNCTION_AREA = _mapscript.MS_TOKEN_FUNCTION_AREA
 MS_TOKEN_FUNCTION_ROUND = _mapscript.MS_TOKEN_FUNCTION_ROUND
 MS_TOKEN_FUNCTION_FROMTEXT = _mapscript.MS_TOKEN_FUNCTION_FROMTEXT
 MS_TOKEN_FUNCTION_BUFFER = _mapscript.MS_TOKEN_FUNCTION_BUFFER
+MS_TOKEN_FUNCTION_DIFFERENCE = _mapscript.MS_TOKEN_FUNCTION_DIFFERENCE
 MS_TOKEN_BINDING_DOUBLE = _mapscript.MS_TOKEN_BINDING_DOUBLE
 MS_TOKEN_BINDING_INTEGER = _mapscript.MS_TOKEN_BINDING_INTEGER
 MS_TOKEN_BINDING_STRING = _mapscript.MS_TOKEN_BINDING_STRING
@@ -585,6 +593,9 @@ class styleObj(_object):
     __swig_setmethods__["gap"] = _mapscript.styleObj_gap_set
     __swig_getmethods__["gap"] = _mapscript.styleObj_gap_get
     if _newclass:gap = _swig_property(_mapscript.styleObj_gap_get, _mapscript.styleObj_gap_set)
+    __swig_setmethods__["initialgap"] = _mapscript.styleObj_initialgap_set
+    __swig_getmethods__["initialgap"] = _mapscript.styleObj_initialgap_get
+    if _newclass:initialgap = _swig_property(_mapscript.styleObj_initialgap_get, _mapscript.styleObj_initialgap_set)
     __swig_setmethods__["position"] = _mapscript.styleObj_position_set
     __swig_getmethods__["position"] = _mapscript.styleObj_position_get
     if _newclass:position = _swig_property(_mapscript.styleObj_position_get, _mapscript.styleObj_position_set)
@@ -615,6 +626,12 @@ class styleObj(_object):
     __swig_setmethods__["offsety"] = _mapscript.styleObj_offsety_set
     __swig_getmethods__["offsety"] = _mapscript.styleObj_offsety_get
     if _newclass:offsety = _swig_property(_mapscript.styleObj_offsety_get, _mapscript.styleObj_offsety_set)
+    __swig_setmethods__["polaroffsetpixel"] = _mapscript.styleObj_polaroffsetpixel_set
+    __swig_getmethods__["polaroffsetpixel"] = _mapscript.styleObj_polaroffsetpixel_get
+    if _newclass:polaroffsetpixel = _swig_property(_mapscript.styleObj_polaroffsetpixel_get, _mapscript.styleObj_polaroffsetpixel_set)
+    __swig_setmethods__["polaroffsetangle"] = _mapscript.styleObj_polaroffsetangle_set
+    __swig_getmethods__["polaroffsetangle"] = _mapscript.styleObj_polaroffsetangle_get
+    if _newclass:polaroffsetangle = _swig_property(_mapscript.styleObj_polaroffsetangle_get, _mapscript.styleObj_polaroffsetangle_set)
     __swig_setmethods__["angle"] = _mapscript.styleObj_angle_set
     __swig_getmethods__["angle"] = _mapscript.styleObj_angle_get
     if _newclass:angle = _swig_property(_mapscript.styleObj_angle_get, _mapscript.styleObj_angle_set)
@@ -644,12 +661,37 @@ class styleObj(_object):
 styleObj_swigregister = _mapscript.styleObj_swigregister
 styleObj_swigregister(styleObj)
 
+class labelLeaderObj(_object):
+    __swig_setmethods__ = {}
+    __setattr__ = lambda self, name, value: _swig_setattr(self, labelLeaderObj, name, value)
+    __swig_getmethods__ = {}
+    __getattr__ = lambda self, name: _swig_getattr(self, labelLeaderObj, name)
+    __repr__ = _swig_repr
+    __swig_setmethods__["maxdistance"] = _mapscript.labelLeaderObj_maxdistance_set
+    __swig_getmethods__["maxdistance"] = _mapscript.labelLeaderObj_maxdistance_get
+    if _newclass:maxdistance = _swig_property(_mapscript.labelLeaderObj_maxdistance_get, _mapscript.labelLeaderObj_maxdistance_set)
+    __swig_setmethods__["gridstep"] = _mapscript.labelLeaderObj_gridstep_set
+    __swig_getmethods__["gridstep"] = _mapscript.labelLeaderObj_gridstep_get
+    if _newclass:gridstep = _swig_property(_mapscript.labelLeaderObj_gridstep_get, _mapscript.labelLeaderObj_gridstep_set)
+    __swig_getmethods__["numstyles"] = _mapscript.labelLeaderObj_numstyles_get
+    if _newclass:numstyles = _swig_property(_mapscript.labelLeaderObj_numstyles_get)
+    def __init__(self): 
+        this = _mapscript.new_labelLeaderObj()
+        try: self.this.append(this)
+        except: self.this = this
+    __swig_destroy__ = _mapscript.delete_labelLeaderObj
+    __del__ = lambda self : None;
+labelLeaderObj_swigregister = _mapscript.labelLeaderObj_swigregister
+labelLeaderObj_swigregister(labelLeaderObj)
+
 class labelObj(_object):
     __swig_setmethods__ = {}
     __setattr__ = lambda self, name, value: _swig_setattr(self, labelObj, name, value)
     __swig_getmethods__ = {}
     __getattr__ = lambda self, name: _swig_getattr(self, labelObj, name)
     __repr__ = _swig_repr
+    __swig_getmethods__["refcount"] = _mapscript.labelObj_refcount_get
+    if _newclass:refcount = _swig_property(_mapscript.labelObj_refcount_get)
     __swig_setmethods__["font"] = _mapscript.labelObj_font_set
     __swig_getmethods__["font"] = _mapscript.labelObj_font_get
     if _newclass:font = _swig_property(_mapscript.labelObj_font_get, _mapscript.labelObj_font_set)
@@ -752,24 +794,43 @@ class labelObj(_object):
     __swig_setmethods__["priority"] = _mapscript.labelObj_priority_set
     __swig_getmethods__["priority"] = _mapscript.labelObj_priority_get
     if _newclass:priority = _swig_property(_mapscript.labelObj_priority_get, _mapscript.labelObj_priority_set)
+    __swig_setmethods__["status"] = _mapscript.labelObj_status_set
+    __swig_getmethods__["status"] = _mapscript.labelObj_status_get
+    if _newclass:status = _swig_property(_mapscript.labelObj_status_get, _mapscript.labelObj_status_set)
     __swig_setmethods__["numstyles"] = _mapscript.labelObj_numstyles_set
     __swig_getmethods__["numstyles"] = _mapscript.labelObj_numstyles_get
     if _newclass:numstyles = _swig_property(_mapscript.labelObj_numstyles_get, _mapscript.labelObj_numstyles_set)
+    __swig_setmethods__["annotext"] = _mapscript.labelObj_annotext_set
+    __swig_getmethods__["annotext"] = _mapscript.labelObj_annotext_get
+    if _newclass:annotext = _swig_property(_mapscript.labelObj_annotext_get, _mapscript.labelObj_annotext_set)
+    __swig_setmethods__["annopoint"] = _mapscript.labelObj_annopoint_set
+    __swig_getmethods__["annopoint"] = _mapscript.labelObj_annopoint_get
+    if _newclass:annopoint = _swig_property(_mapscript.labelObj_annopoint_get, _mapscript.labelObj_annopoint_set)
+    __swig_setmethods__["annopoly"] = _mapscript.labelObj_annopoly_set
+    __swig_getmethods__["annopoly"] = _mapscript.labelObj_annopoly_get
+    if _newclass:annopoly = _swig_property(_mapscript.labelObj_annopoly_get, _mapscript.labelObj_annopoly_set)
+    __swig_setmethods__["leader"] = _mapscript.labelObj_leader_set
+    __swig_getmethods__["leader"] = _mapscript.labelObj_leader_get
+    if _newclass:leader = _swig_property(_mapscript.labelObj_leader_get, _mapscript.labelObj_leader_set)
+    def __init__(self): 
+        this = _mapscript.new_labelObj()
+        try: self.this.append(this)
+        except: self.this = this
+    __swig_destroy__ = _mapscript.delete_labelObj
+    __del__ = lambda self : None;
     def updateFromString(self, *args): return _mapscript.labelObj_updateFromString(self, *args)
     def removeBinding(self, *args): return _mapscript.labelObj_removeBinding(self, *args)
     def getBinding(self, *args): return _mapscript.labelObj_getBinding(self, *args)
     def setBinding(self, *args): return _mapscript.labelObj_setBinding(self, *args)
+    def setExpression(self, *args): return _mapscript.labelObj_setExpression(self, *args)
+    def getExpressionString(self): return _mapscript.labelObj_getExpressionString(self)
+    def setText(self, *args): return _mapscript.labelObj_setText(self, *args)
+    def getTextString(self): return _mapscript.labelObj_getTextString(self)
     def getStyle(self, *args): return _mapscript.labelObj_getStyle(self, *args)
     def insertStyle(self, *args): return _mapscript.labelObj_insertStyle(self, *args)
     def removeStyle(self, *args): return _mapscript.labelObj_removeStyle(self, *args)
     def moveStyleUp(self, *args): return _mapscript.labelObj_moveStyleUp(self, *args)
     def moveStyleDown(self, *args): return _mapscript.labelObj_moveStyleDown(self, *args)
-    def __init__(self): 
-        this = _mapscript.new_labelObj()
-        try: self.this.append(this)
-        except: self.this = this
-    __swig_destroy__ = _mapscript.delete_labelObj
-    __del__ = lambda self : None;
 labelObj_swigregister = _mapscript.labelObj_swigregister
 labelObj_swigregister(labelObj)
 
@@ -782,11 +843,11 @@ class classObj(_object):
     __swig_setmethods__["status"] = _mapscript.classObj_status_set
     __swig_getmethods__["status"] = _mapscript.classObj_status_get
     if _newclass:status = _swig_property(_mapscript.classObj_status_get, _mapscript.classObj_status_set)
-    __swig_setmethods__["numstyles"] = _mapscript.classObj_numstyles_set
     __swig_getmethods__["numstyles"] = _mapscript.classObj_numstyles_get
-    if _newclass:numstyles = _swig_property(_mapscript.classObj_numstyles_get, _mapscript.classObj_numstyles_set)
-    __swig_getmethods__["label"] = _mapscript.classObj_label_get
-    if _newclass:label = _swig_property(_mapscript.classObj_label_get)
+    if _newclass:numstyles = _swig_property(_mapscript.classObj_numstyles_get)
+    __swig_setmethods__["numlabels"] = _mapscript.classObj_numlabels_set
+    __swig_getmethods__["numlabels"] = _mapscript.classObj_numlabels_get
+    if _newclass:numlabels = _swig_property(_mapscript.classObj_numlabels_get, _mapscript.classObj_numlabels_set)
     __swig_setmethods__["name"] = _mapscript.classObj_name_set
     __swig_getmethods__["name"] = _mapscript.classObj_name_get
     if _newclass:name = _swig_property(_mapscript.classObj_name_get, _mapscript.classObj_name_set)
@@ -825,6 +886,9 @@ class classObj(_object):
     __swig_setmethods__["group"] = _mapscript.classObj_group_set
     __swig_getmethods__["group"] = _mapscript.classObj_group_get
     if _newclass:group = _swig_property(_mapscript.classObj_group_get, _mapscript.classObj_group_set)
+    __swig_setmethods__["leader"] = _mapscript.classObj_leader_set
+    __swig_getmethods__["leader"] = _mapscript.classObj_leader_get
+    if _newclass:leader = _swig_property(_mapscript.classObj_leader_get, _mapscript.classObj_leader_set)
     def __init__(self, layer = None): 
         this = _mapscript.new_classObj(layer)
         try: self.this.append(this)
@@ -856,6 +920,9 @@ class classObj(_object):
     def getNextMetaDataKey(self, *args): return _mapscript.classObj_getNextMetaDataKey(self, *args)
     def drawLegendIcon(self, *args): return _mapscript.classObj_drawLegendIcon(self, *args)
     def createLegendIcon(self, *args): return _mapscript.classObj_createLegendIcon(self, *args)
+    def getLabel(self, *args): return _mapscript.classObj_getLabel(self, *args)
+    def addLabel(self, *args): return _mapscript.classObj_addLabel(self, *args)
+    def removeLabel(self, *args): return _mapscript.classObj_removeLabel(self, *args)
     def getStyle(self, *args): return _mapscript.classObj_getStyle(self, *args)
     def insertStyle(self, *args): return _mapscript.classObj_insertStyle(self, *args)
     def removeStyle(self, *args): return _mapscript.classObj_removeStyle(self, *args)
@@ -870,24 +937,20 @@ class labelCacheMemberObj(_object):
     __swig_getmethods__ = {}
     __getattr__ = lambda self, name: _swig_getattr(self, labelCacheMemberObj, name)
     __repr__ = _swig_repr
-    __swig_getmethods__["text"] = _mapscript.labelCacheMemberObj_text_get
-    if _newclass:text = _swig_property(_mapscript.labelCacheMemberObj_text_get)
     __swig_getmethods__["featuresize"] = _mapscript.labelCacheMemberObj_featuresize_get
     if _newclass:featuresize = _swig_property(_mapscript.labelCacheMemberObj_featuresize_get)
     __swig_getmethods__["styles"] = _mapscript.labelCacheMemberObj_styles_get
     if _newclass:styles = _swig_property(_mapscript.labelCacheMemberObj_styles_get)
     __swig_getmethods__["numstyles"] = _mapscript.labelCacheMemberObj_numstyles_get
     if _newclass:numstyles = _swig_property(_mapscript.labelCacheMemberObj_numstyles_get)
-    __swig_getmethods__["label"] = _mapscript.labelCacheMemberObj_label_get
-    if _newclass:label = _swig_property(_mapscript.labelCacheMemberObj_label_get)
+    __swig_getmethods__["labels"] = _mapscript.labelCacheMemberObj_labels_get
+    if _newclass:labels = _swig_property(_mapscript.labelCacheMemberObj_labels_get)
+    __swig_getmethods__["numlabels"] = _mapscript.labelCacheMemberObj_numlabels_get
+    if _newclass:numlabels = _swig_property(_mapscript.labelCacheMemberObj_numlabels_get)
     __swig_getmethods__["layerindex"] = _mapscript.labelCacheMemberObj_layerindex_get
     if _newclass:layerindex = _swig_property(_mapscript.labelCacheMemberObj_layerindex_get)
     __swig_getmethods__["classindex"] = _mapscript.labelCacheMemberObj_classindex_get
     if _newclass:classindex = _swig_property(_mapscript.labelCacheMemberObj_classindex_get)
-    __swig_getmethods__["tileindex"] = _mapscript.labelCacheMemberObj_tileindex_get
-    if _newclass:tileindex = _swig_property(_mapscript.labelCacheMemberObj_tileindex_get)
-    __swig_getmethods__["shapeindex"] = _mapscript.labelCacheMemberObj_shapeindex_get
-    if _newclass:shapeindex = _swig_property(_mapscript.labelCacheMemberObj_shapeindex_get)
     __swig_getmethods__["shapetype"] = _mapscript.labelCacheMemberObj_shapetype_get
     if _newclass:shapetype = _swig_property(_mapscript.labelCacheMemberObj_shapetype_get)
     __swig_getmethods__["point"] = _mapscript.labelCacheMemberObj_point_get
@@ -898,6 +961,10 @@ class labelCacheMemberObj(_object):
     if _newclass:status = _swig_property(_mapscript.labelCacheMemberObj_status_get)
     __swig_getmethods__["markerid"] = _mapscript.labelCacheMemberObj_markerid_get
     if _newclass:markerid = _swig_property(_mapscript.labelCacheMemberObj_markerid_get)
+    __swig_getmethods__["leaderline"] = _mapscript.labelCacheMemberObj_leaderline_get
+    if _newclass:leaderline = _swig_property(_mapscript.labelCacheMemberObj_leaderline_get)
+    __swig_getmethods__["leaderbbox"] = _mapscript.labelCacheMemberObj_leaderbbox_get
+    if _newclass:leaderbbox = _swig_property(_mapscript.labelCacheMemberObj_leaderbbox_get)
     def __init__(self): 
         this = _mapscript.new_labelCacheMemberObj()
         try: self.this.append(this)
@@ -963,6 +1030,8 @@ class labelCacheObj(_object):
     if _newclass:slots = _swig_property(_mapscript.labelCacheObj_slots_get)
     __swig_getmethods__["numlabels"] = _mapscript.labelCacheObj_numlabels_get
     if _newclass:numlabels = _swig_property(_mapscript.labelCacheObj_numlabels_get)
+    __swig_getmethods__["gutter"] = _mapscript.labelCacheObj_gutter_get
+    if _newclass:gutter = _swig_property(_mapscript.labelCacheObj_gutter_get)
     def freeCache(self): return _mapscript.labelCacheObj_freeCache(self)
     def __init__(self): 
         this = _mapscript.new_labelCacheObj()
@@ -1218,6 +1287,40 @@ class legendObj(_object):
 legendObj_swigregister = _mapscript.legendObj_swigregister
 legendObj_swigregister(legendObj)
 
+class imageObj(_object):
+    __swig_setmethods__ = {}
+    __setattr__ = lambda self, name, value: _swig_setattr(self, imageObj, name, value)
+    __swig_getmethods__ = {}
+    __getattr__ = lambda self, name: _swig_getattr(self, imageObj, name)
+    __repr__ = _swig_repr
+    __swig_getmethods__["width"] = _mapscript.imageObj_width_get
+    if _newclass:width = _swig_property(_mapscript.imageObj_width_get)
+    __swig_getmethods__["height"] = _mapscript.imageObj_height_get
+    if _newclass:height = _swig_property(_mapscript.imageObj_height_get)
+    __swig_getmethods__["resolution"] = _mapscript.imageObj_resolution_get
+    if _newclass:resolution = _swig_property(_mapscript.imageObj_resolution_get)
+    __swig_getmethods__["resolutionfactor"] = _mapscript.imageObj_resolutionfactor_get
+    if _newclass:resolutionfactor = _swig_property(_mapscript.imageObj_resolutionfactor_get)
+    __swig_getmethods__["imagepath"] = _mapscript.imageObj_imagepath_get
+    if _newclass:imagepath = _swig_property(_mapscript.imageObj_imagepath_get)
+    __swig_getmethods__["imageurl"] = _mapscript.imageObj_imageurl_get
+    if _newclass:imageurl = _swig_property(_mapscript.imageObj_imageurl_get)
+    __swig_getmethods__["format"] = _mapscript.imageObj_format_get
+    if _newclass:format = _swig_property(_mapscript.imageObj_format_get)
+    __swig_destroy__ = _mapscript.delete_imageObj
+    __del__ = lambda self : None;
+    def save(self, *args): return _mapscript.imageObj_save(self, *args)
+    def getBytes(self): return _mapscript.imageObj_getBytes(self)
+    def getSize(self): return _mapscript.imageObj_getSize(self)
+    def __init__(self, *args): 
+        this = _mapscript.new_imageObj(*args)
+        try: self.this.append(this)
+        except: self.this = this
+    def write(self, *args): return _mapscript.imageObj_write(self, *args)
+    def saveToString(self): return _mapscript.imageObj_saveToString(self)
+imageObj_swigregister = _mapscript.imageObj_swigregister
+imageObj_swigregister(imageObj)
+
 class layerObj(_object):
     __swig_setmethods__ = {}
     __setattr__ = lambda self, name, value: _swig_setattr(self, layerObj, name, value)
@@ -1379,6 +1482,9 @@ class layerObj(_object):
     __swig_setmethods__["classgroup"] = _mapscript.layerObj_classgroup_set
     __swig_getmethods__["classgroup"] = _mapscript.layerObj_classgroup_get
     if _newclass:classgroup = _swig_property(_mapscript.layerObj_classgroup_get, _mapscript.layerObj_classgroup_set)
+    __swig_setmethods__["mask"] = _mapscript.layerObj_mask_set
+    __swig_getmethods__["mask"] = _mapscript.layerObj_mask_get
+    if _newclass:mask = _swig_property(_mapscript.layerObj_mask_get, _mapscript.layerObj_mask_set)
     def __init__(self, map = None): 
         this = _mapscript.new_layerObj(map)
         try: self.this.append(this)
@@ -1424,6 +1530,7 @@ class layerObj(_object):
     	return clazz
 
     def getItem(self, *args): return _mapscript.layerObj_getItem(self, *args)
+    def setItems(self, *args): return _mapscript.layerObj_setItems(self, *args)
     def draw(self, *args): return _mapscript.layerObj_draw(self, *args)
     def drawQuery(self, *args): return _mapscript.layerObj_drawQuery(self, *args)
     def queryByFilter(self, *args): return _mapscript.layerObj_queryByFilter(self, *args)
@@ -1683,40 +1790,6 @@ class mapObj(_object):
 mapObj_swigregister = _mapscript.mapObj_swigregister
 mapObj_swigregister(mapObj)
 
-class imageObj(_object):
-    __swig_setmethods__ = {}
-    __setattr__ = lambda self, name, value: _swig_setattr(self, imageObj, name, value)
-    __swig_getmethods__ = {}
-    __getattr__ = lambda self, name: _swig_getattr(self, imageObj, name)
-    __repr__ = _swig_repr
-    __swig_getmethods__["width"] = _mapscript.imageObj_width_get
-    if _newclass:width = _swig_property(_mapscript.imageObj_width_get)
-    __swig_getmethods__["height"] = _mapscript.imageObj_height_get
-    if _newclass:height = _swig_property(_mapscript.imageObj_height_get)
-    __swig_getmethods__["resolution"] = _mapscript.imageObj_resolution_get
-    if _newclass:resolution = _swig_property(_mapscript.imageObj_resolution_get)
-    __swig_getmethods__["resolutionfactor"] = _mapscript.imageObj_resolutionfactor_get
-    if _newclass:resolutionfactor = _swig_property(_mapscript.imageObj_resolutionfactor_get)
-    __swig_getmethods__["imagepath"] = _mapscript.imageObj_imagepath_get
-    if _newclass:imagepath = _swig_property(_mapscript.imageObj_imagepath_get)
-    __swig_getmethods__["imageurl"] = _mapscript.imageObj_imageurl_get
-    if _newclass:imageurl = _swig_property(_mapscript.imageObj_imageurl_get)
-    __swig_getmethods__["format"] = _mapscript.imageObj_format_get
-    if _newclass:format = _swig_property(_mapscript.imageObj_format_get)
-    __swig_destroy__ = _mapscript.delete_imageObj
-    __del__ = lambda self : None;
-    def save(self, *args): return _mapscript.imageObj_save(self, *args)
-    def getBytes(self): return _mapscript.imageObj_getBytes(self)
-    def getSize(self): return _mapscript.imageObj_getSize(self)
-    def __init__(self, *args): 
-        this = _mapscript.new_imageObj(*args)
-        try: self.this.append(this)
-        except: self.this = this
-    def write(self, *args): return _mapscript.imageObj_write(self, *args)
-    def saveToString(self): return _mapscript.imageObj_saveToString(self)
-imageObj_swigregister = _mapscript.imageObj_swigregister
-imageObj_swigregister(imageObj)
-
 
 def msSaveImage(*args):
   return _mapscript.msSaveImage(*args)
@@ -1730,8 +1803,8 @@ def msSetup():
   return _mapscript.msSetup()
 msSetup = _mapscript.msSetup
 
-def msCleanup():
-  return _mapscript.msCleanup()
+def msCleanup(*args):
+  return _mapscript.msCleanup(*args)
 msCleanup = _mapscript.msCleanup
 
 def msLoadMapFromString(*args):
@@ -1752,6 +1825,9 @@ class strokeStyleObj(_object):
     __swig_setmethods__["pattern"] = _mapscript.strokeStyleObj_pattern_set
     __swig_getmethods__["pattern"] = _mapscript.strokeStyleObj_pattern_get
     if _newclass:pattern = _swig_property(_mapscript.strokeStyleObj_pattern_get, _mapscript.strokeStyleObj_pattern_set)
+    __swig_setmethods__["patternoffset"] = _mapscript.strokeStyleObj_patternoffset_set
+    __swig_getmethods__["patternoffset"] = _mapscript.strokeStyleObj_patternoffset_get
+    if _newclass:patternoffset = _swig_property(_mapscript.strokeStyleObj_patternoffset_get, _mapscript.strokeStyleObj_patternoffset_set)
     __swig_setmethods__["color"] = _mapscript.strokeStyleObj_color_set
     __swig_getmethods__["color"] = _mapscript.strokeStyleObj_color_get
     if _newclass:color = _swig_property(_mapscript.strokeStyleObj_color_get, _mapscript.strokeStyleObj_color_set)
@@ -1866,9 +1942,12 @@ class labelStyleObj(_object):
     __swig_getmethods__ = {}
     __getattr__ = lambda self, name: _swig_getattr(self, labelStyleObj, name)
     __repr__ = _swig_repr
-    __swig_setmethods__["font"] = _mapscript.labelStyleObj_font_set
-    __swig_getmethods__["font"] = _mapscript.labelStyleObj_font_get
-    if _newclass:font = _swig_property(_mapscript.labelStyleObj_font_get, _mapscript.labelStyleObj_font_set)
+    __swig_setmethods__["fonts"] = _mapscript.labelStyleObj_fonts_set
+    __swig_getmethods__["fonts"] = _mapscript.labelStyleObj_fonts_get
+    if _newclass:fonts = _swig_property(_mapscript.labelStyleObj_fonts_get, _mapscript.labelStyleObj_fonts_set)
+    __swig_setmethods__["numfonts"] = _mapscript.labelStyleObj_numfonts_set
+    __swig_getmethods__["numfonts"] = _mapscript.labelStyleObj_numfonts_get
+    if _newclass:numfonts = _swig_property(_mapscript.labelStyleObj_numfonts_get, _mapscript.labelStyleObj_numfonts_set)
     __swig_setmethods__["size"] = _mapscript.labelStyleObj_size_set
     __swig_getmethods__["size"] = _mapscript.labelStyleObj_size_get
     if _newclass:size = _swig_property(_mapscript.labelStyleObj_size_get, _mapscript.labelStyleObj_size_set)
@@ -1884,6 +1963,9 @@ class labelStyleObj(_object):
     __swig_setmethods__["outlinecolor"] = _mapscript.labelStyleObj_outlinecolor_set
     __swig_getmethods__["outlinecolor"] = _mapscript.labelStyleObj_outlinecolor_get
     if _newclass:outlinecolor = _swig_property(_mapscript.labelStyleObj_outlinecolor_get, _mapscript.labelStyleObj_outlinecolor_set)
+    __swig_setmethods__["antialias"] = _mapscript.labelStyleObj_antialias_set
+    __swig_getmethods__["antialias"] = _mapscript.labelStyleObj_antialias_get
+    if _newclass:antialias = _swig_property(_mapscript.labelStyleObj_antialias_get, _mapscript.labelStyleObj_antialias_set)
     def __init__(self): 
         this = _mapscript.new_labelStyleObj()
         try: self.this.append(this)
@@ -2190,6 +2272,9 @@ class shapefileObj(_object):
 shapefileObj_swigregister = _mapscript.shapefileObj_swigregister
 shapefileObj_swigregister(shapefileObj)
 
+wkp_none = _mapscript.wkp_none
+wkp_lonlat = _mapscript.wkp_lonlat
+wkp_gmerc = _mapscript.wkp_gmerc
 class projectionObj(_object):
     __swig_setmethods__ = {}
     __setattr__ = lambda self, name, value: _swig_setattr(self, projectionObj, name, value)
@@ -2200,6 +2285,9 @@ class projectionObj(_object):
     if _newclass:numargs = _swig_property(_mapscript.projectionObj_numargs_get)
     __swig_getmethods__["automatic"] = _mapscript.projectionObj_automatic_get
     if _newclass:automatic = _swig_property(_mapscript.projectionObj_automatic_get)
+    __swig_setmethods__["wellknownprojection"] = _mapscript.projectionObj_wellknownprojection_set
+    __swig_getmethods__["wellknownprojection"] = _mapscript.projectionObj_wellknownprojection_get
+    if _newclass:wellknownprojection = _swig_property(_mapscript.projectionObj_wellknownprojection_get, _mapscript.projectionObj_wellknownprojection_set)
     def __init__(self, *args): 
         this = _mapscript.new_projectionObj(*args)
         try: self.this.append(this)
@@ -2228,9 +2316,6 @@ class colorObj(_object):
     __swig_getmethods__ = {}
     __getattr__ = lambda self, name: _swig_getattr(self, colorObj, name)
     __repr__ = _swig_repr
-    __swig_setmethods__["pen"] = _mapscript.colorObj_pen_set
-    __swig_getmethods__["pen"] = _mapscript.colorObj_pen_get
-    if _newclass:pen = _swig_property(_mapscript.colorObj_pen_get, _mapscript.colorObj_pen_set)
     __swig_setmethods__["red"] = _mapscript.colorObj_red_set
     __swig_getmethods__["red"] = _mapscript.colorObj_red_get
     if _newclass:red = _swig_property(_mapscript.colorObj_red_get, _mapscript.colorObj_red_set)
@@ -2295,6 +2380,12 @@ class symbolObj(_object):
     __swig_setmethods__["filled"] = _mapscript.symbolObj_filled_set
     __swig_getmethods__["filled"] = _mapscript.symbolObj_filled_get
     if _newclass:filled = _swig_property(_mapscript.symbolObj_filled_get, _mapscript.symbolObj_filled_set)
+    __swig_setmethods__["anchorpoint_x"] = _mapscript.symbolObj_anchorpoint_x_set
+    __swig_getmethods__["anchorpoint_x"] = _mapscript.symbolObj_anchorpoint_x_get
+    if _newclass:anchorpoint_x = _swig_property(_mapscript.symbolObj_anchorpoint_x_get, _mapscript.symbolObj_anchorpoint_x_set)
+    __swig_setmethods__["anchorpoint_y"] = _mapscript.symbolObj_anchorpoint_y_set
+    __swig_getmethods__["anchorpoint_y"] = _mapscript.symbolObj_anchorpoint_y_get
+    if _newclass:anchorpoint_y = _swig_property(_mapscript.symbolObj_anchorpoint_y_get, _mapscript.symbolObj_anchorpoint_y_set)
     __swig_getmethods__["imagepath"] = _mapscript.symbolObj_imagepath_get
     if _newclass:imagepath = _swig_property(_mapscript.symbolObj_imagepath_get)
     __swig_setmethods__["transparent"] = _mapscript.symbolObj_transparent_set
@@ -2485,6 +2576,7 @@ class OWSRequest(_object):
     def loadParams(self): return _mapscript.OWSRequest_loadParams(self)
     def loadParamsFromURL(self, *args): return _mapscript.OWSRequest_loadParamsFromURL(self, *args)
     def setParameter(self, *args): return _mapscript.OWSRequest_setParameter(self, *args)
+    def addParameter(self, *args): return _mapscript.OWSRequest_addParameter(self, *args)
     def getName(self, *args): return _mapscript.OWSRequest_getName(self, *args)
     def getValue(self, *args): return _mapscript.OWSRequest_getValue(self, *args)
     def getValueByName(self, *args): return _mapscript.OWSRequest_getValueByName(self, *args)
diff --git a/mapscript/python/mapscript_wrap.c b/mapscript/python/mapscript_wrap.c
index 28fe3a2..0bf2227 100644
--- a/mapscript/python/mapscript_wrap.c
+++ b/mapscript/python/mapscript_wrap.c
@@ -2666,12 +2666,12 @@ SWIG_Python_MustGetPtr(PyObject *obj, swig_type_info *ty, int argnum, int flags)
 #define SWIGTYPE_p_FILE swig_types[2]
 #define SWIGTYPE_p_cgiRequestObj swig_types[3]
 #define SWIGTYPE_p_char swig_types[4]
-#define SWIGTYPE_p_class_obj swig_types[5]
+#define SWIGTYPE_p_classObj swig_types[5]
 #define SWIGTYPE_p_clusterObj swig_types[6]
 #define SWIGTYPE_p_colorObj swig_types[7]
 #define SWIGTYPE_p_debugLevel swig_types[8]
 #define SWIGTYPE_p_double swig_types[9]
-#define SWIGTYPE_p_error_obj swig_types[10]
+#define SWIGTYPE_p_errorObj swig_types[10]
 #define SWIGTYPE_p_fontSetObj swig_types[11]
 #define SWIGTYPE_p_hashTableObj swig_types[12]
 #define SWIGTYPE_p_imageObj swig_types[13]
@@ -2681,38 +2681,39 @@ SWIG_Python_MustGetPtr(PyObject *obj, swig_type_info *ty, int argnum, int flags)
 #define SWIGTYPE_p_labelCacheMemberObj swig_types[17]
 #define SWIGTYPE_p_labelCacheObj swig_types[18]
 #define SWIGTYPE_p_labelCacheSlotObj swig_types[19]
-#define SWIGTYPE_p_labelObj swig_types[20]
-#define SWIGTYPE_p_labelStyleObj swig_types[21]
-#define SWIGTYPE_p_layer_obj swig_types[22]
-#define SWIGTYPE_p_legendObj swig_types[23]
-#define SWIGTYPE_p_lineObj swig_types[24]
-#define SWIGTYPE_p_map_obj swig_types[25]
-#define SWIGTYPE_p_markerCacheMemberObj swig_types[26]
-#define SWIGTYPE_p_outputFormatObj swig_types[27]
-#define SWIGTYPE_p_p_char swig_types[28]
-#define SWIGTYPE_p_p_outputFormatObj swig_types[29]
-#define SWIGTYPE_p_pointObj swig_types[30]
-#define SWIGTYPE_p_projectionObj swig_types[31]
-#define SWIGTYPE_p_queryMapObj swig_types[32]
-#define SWIGTYPE_p_rectObj swig_types[33]
-#define SWIGTYPE_p_referenceMapObj swig_types[34]
-#define SWIGTYPE_p_rendererVTableObj swig_types[35]
-#define SWIGTYPE_p_resultCacheObj swig_types[36]
-#define SWIGTYPE_p_resultObj swig_types[37]
-#define SWIGTYPE_p_scalebarObj swig_types[38]
-#define SWIGTYPE_p_shapeObj swig_types[39]
-#define SWIGTYPE_p_shapefileObj swig_types[40]
-#define SWIGTYPE_p_strokeStyleObj swig_types[41]
-#define SWIGTYPE_p_styleObj swig_types[42]
-#define SWIGTYPE_p_symbolObj swig_types[43]
-#define SWIGTYPE_p_symbolSetObj swig_types[44]
-#define SWIGTYPE_p_symbolStyleObj swig_types[45]
-#define SWIGTYPE_p_tileCacheObj swig_types[46]
-#define SWIGTYPE_p_uint32_t swig_types[47]
-#define SWIGTYPE_p_void swig_types[48]
-#define SWIGTYPE_p_webObj swig_types[49]
-static swig_type_info *swig_types[51];
-static swig_module_info swig_module = {swig_types, 50, 0, 0, 0, 0};
+#define SWIGTYPE_p_labelLeaderObj swig_types[20]
+#define SWIGTYPE_p_labelObj swig_types[21]
+#define SWIGTYPE_p_labelStyleObj swig_types[22]
+#define SWIGTYPE_p_layerObj swig_types[23]
+#define SWIGTYPE_p_legendObj swig_types[24]
+#define SWIGTYPE_p_lineObj swig_types[25]
+#define SWIGTYPE_p_mapObj swig_types[26]
+#define SWIGTYPE_p_markerCacheMemberObj swig_types[27]
+#define SWIGTYPE_p_outputFormatObj swig_types[28]
+#define SWIGTYPE_p_p_char swig_types[29]
+#define SWIGTYPE_p_p_outputFormatObj swig_types[30]
+#define SWIGTYPE_p_pointObj swig_types[31]
+#define SWIGTYPE_p_projectionObj swig_types[32]
+#define SWIGTYPE_p_queryMapObj swig_types[33]
+#define SWIGTYPE_p_rectObj swig_types[34]
+#define SWIGTYPE_p_referenceMapObj swig_types[35]
+#define SWIGTYPE_p_rendererVTableObj swig_types[36]
+#define SWIGTYPE_p_resultCacheObj swig_types[37]
+#define SWIGTYPE_p_resultObj swig_types[38]
+#define SWIGTYPE_p_scalebarObj swig_types[39]
+#define SWIGTYPE_p_shapeObj swig_types[40]
+#define SWIGTYPE_p_shapefileObj swig_types[41]
+#define SWIGTYPE_p_strokeStyleObj swig_types[42]
+#define SWIGTYPE_p_styleObj swig_types[43]
+#define SWIGTYPE_p_symbolObj swig_types[44]
+#define SWIGTYPE_p_symbolSetObj swig_types[45]
+#define SWIGTYPE_p_symbolStyleObj swig_types[46]
+#define SWIGTYPE_p_tileCacheObj swig_types[47]
+#define SWIGTYPE_p_uint32_t swig_types[48]
+#define SWIGTYPE_p_void swig_types[49]
+#define SWIGTYPE_p_webObj swig_types[50]
+static swig_type_info *swig_types[52];
+static swig_module_info swig_module = {swig_types, 51, 0, 0, 0, 0};
 #define SWIG_TypeQuery(name) SWIG_TypeQueryModule(&swig_module, &swig_module, name)
 #define SWIG_MangledTypeQuery(name) SWIG_MangledTypeQueryModule(&swig_module, &swig_module, name)
 
@@ -3332,7 +3333,7 @@ SWIGINTERN int styleObj_setSymbolByName(styleObj *self,mapObj *map,char *symboln
         return self->symbol;
     }
 SWIGINTERN int styleObj_removeBinding(styleObj *self,int binding){
-    if(binding < 0 || binding >= 8) return MS_FAILURE;
+    if(binding < 0 || binding >= 12) return MS_FAILURE;
 
     if(self->bindings[binding].item) {
       free(self->bindings[binding].item);
@@ -3345,7 +3346,7 @@ SWIGINTERN int styleObj_removeBinding(styleObj *self,int binding){
   }
 SWIGINTERN int styleObj_setBinding(styleObj *self,int binding,char *item){
     if(!item) return MS_FAILURE;
-    if(binding < 0 || binding >= 8) return MS_FAILURE;
+    if(binding < 0 || binding >= 12) return MS_FAILURE;
 
     if(self->bindings[binding].item) {
       free(self->bindings[binding].item);
@@ -3360,7 +3361,7 @@ SWIGINTERN int styleObj_setBinding(styleObj *self,int binding,char *item){
     return MS_SUCCESS;
   }
 SWIGINTERN char *styleObj_getBinding(styleObj *self,int binding){
-    if(binding < 0 || binding >= 8) return NULL;
+    if(binding < 0 || binding >= 12) return NULL;
 
     return self->bindings[binding].item;
   }
@@ -3420,6 +3421,20 @@ SWIG_From_char  (char c)
   return SWIG_FromCharPtrAndSize(&c,1);
 }
 
+SWIGINTERN labelObj *new_labelObj(){
+      labelObj *label;
+        
+      label = (labelObj *)calloc(1, sizeof(labelObj));
+      if (!label)
+        return(NULL);
+    
+      initLabel(label);
+      
+      return(label);    	
+    }
+SWIGINTERN void delete_labelObj(labelObj *self){
+      freeLabel(self);
+    }
 SWIGINTERN int labelObj_updateFromString(labelObj *self,char *snippet){
     return msUpdateLabelFromString(self, snippet);
   }
@@ -3456,6 +3471,26 @@ SWIGINTERN int labelObj_setBinding(labelObj *self,int binding,char *item){
 
     return MS_SUCCESS;
   }
+SWIGINTERN int labelObj_setExpression(labelObj *self,char *expression){
+    if (!expression || strlen(expression) == 0) {
+       freeExpression(&self->expression);
+       return MS_SUCCESS;
+    }
+    else return msLoadExpressionString(&self->expression, expression);
+  }
+SWIGINTERN char *labelObj_getExpressionString(labelObj *self){
+    return msGetExpressionString(&(self->expression));
+  }
+SWIGINTERN int labelObj_setText(labelObj *self,char *text){
+    if (!text || strlen(text) == 0) {
+      freeExpression(&self->text);
+      return MS_SUCCESS;
+    }	
+    else return msLoadExpressionString(&self->text, text);
+  }
+SWIGINTERN char *labelObj_getTextString(labelObj *self){
+    return msGetExpressionString(&(self->text));
+  }
 SWIGINTERN styleObj *labelObj_getStyle(labelObj *self,int i){
       if (i >= 0 && i < self->numstyles) {
           MS_REFCNT_INCR(self->styles[i]);
@@ -3601,30 +3636,46 @@ SWIGINTERN int classObj_drawLegendIcon(classObj *self,mapObj *map,layerObj *laye
 SWIGINTERN imageObj *classObj_createLegendIcon(classObj *self,mapObj *map,layerObj *layer,int width,int height){
     return msCreateLegendIcon(map, layer, self, width, height);
   }
+SWIGINTERN labelObj *classObj_getLabel(classObj *self,int i){
+    if (i >= 0 && i < self->numlabels) {
+      MS_REFCNT_INCR(self->labels[i]);
+      return self->labels[i];
+    } else {
+      msSetError(31, "Invalid index: %d.", "getLabel()", i);
+      return NULL;
+    }
+  }
+SWIGINTERN int classObj_addLabel(classObj *self,labelObj *label){
+    return msAddLabelToClass(self, label);
+  }
+SWIGINTERN labelObj *classObj_removeLabel(classObj *self,int index){
+    labelObj* label = (labelObj *) msRemoveLabelFromClass(self, index);
+    if (label) MS_REFCNT_INCR(label);
+    return label;
+  }
 SWIGINTERN styleObj *classObj_getStyle(classObj *self,int i){
-        if (i >= 0 && i < self->numstyles) {
-	    MS_REFCNT_INCR(self->styles[i]);
-            return self->styles[i];
-	} else {
-            msSetError(31, "Invalid index: %d", "getStyle()", i);
-            return NULL;
-        }
+    if (i >= 0 && i < self->numstyles) {
+      MS_REFCNT_INCR(self->styles[i]);
+      return self->styles[i];
+    } else {
+      msSetError(31, "Invalid index: %d", "getStyle()", i);
+      return NULL;
     }
+  }
 SWIGINTERN int classObj_insertStyle(classObj *self,styleObj *style,int index){
-        return msInsertStyle(self, style, index);
-    }
+    return msInsertStyle(self, style, index);
+  }
 SWIGINTERN styleObj *classObj_removeStyle(classObj *self,int index){
-	styleObj* style = (styleObj *) msRemoveStyle(self, index);
-	if (style)
-		MS_REFCNT_INCR(style);
-        return style;
-    }
+    styleObj* style = (styleObj *) msRemoveStyle(self, index);
+    if (style) MS_REFCNT_INCR(style);
+    return style;
+  }
 SWIGINTERN int classObj_moveStyleUp(classObj *self,int index){
-        return msMoveStyleUp(self, index);
-    }
+    return msMoveStyleUp(self, index);
+  }
 SWIGINTERN int classObj_moveStyleDown(classObj *self,int index){
-       return msMoveStyleDown(self, index);
-    }
+    return msMoveStyleDown(self, index);
+  }
 SWIGINTERN void labelCacheObj_freeCache(labelCacheObj *self){
         msFreeLabelCache(self);    
     }
@@ -3711,6 +3762,260 @@ SWIGINTERN int scalebarObj_updateFromString(scalebarObj *self,char *snippet){
 SWIGINTERN int legendObj_updateFromString(legendObj *self,char *snippet){
     return msUpdateLegendFromString(self, snippet, 0);
   }
+SWIGINTERN void delete_imageObj(imageObj *self){
+        msFreeImage(self);    
+    }
+SWIGINTERN void imageObj_save(imageObj *self,char *filename,mapObj *map){
+        msSaveImage(map, self, filename );
+    }
+SWIGINTERN gdBuffer imageObj_getBytes(imageObj *self){
+        gdBuffer buffer;
+        
+        buffer.owns_data = 1;
+        
+        buffer.data = msSaveImageBuffer(self, &buffer.size, self->format);
+            
+        if( buffer.data == NULL || buffer.size == 0 )
+        {
+            buffer.data = NULL;
+            msSetError(12, "Failed to get image buffer", "getBytes");
+            return buffer;
+        }
+
+        return buffer;
+    }
+SWIGINTERN int imageObj_getSize(imageObj *self){
+        gdBuffer buffer;
+	int size=0;
+        
+        buffer.data = msSaveImageBuffer(self, &buffer.size, self->format);
+	size = buffer.size;
+            
+        if( buffer.data == NULL || buffer.size == 0 ) {
+            buffer.data = NULL;
+            msSetError(12, "Failed to get image buffer size", "getSize");
+        }
+	free(buffer.data);
+        return size;
+    }
+SWIGINTERN imageObj *new_imageObj(PyObject *arg1,PyObject *arg2,PyObject *input_format,PyObject *input_resolution,PyObject *input_defresolution){
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+         msSetError(15, "imageObj() is severely broken and should not be used","imageObj()");
+         return NULL;
+
+    }
+SWIGINTERN int imageObj_write(imageObj *self,PyObject *file){
+        unsigned char *imgbuffer=NULL;
+        int imgsize;
+        PyObject *noerr;
+        int retval=MS_FAILURE;
+        rendererVTableObj *renderer = NULL;
+
+        /* Return immediately if image driver is not GD */
+        if ( !MS_RENDERER_PLUGIN(self->format) )
+        {
+            msSetError(15, "Writing of %s format not implemented",
+                       "imageObj::write", self->format->driver);
+            return MS_FAILURE;
+        }
+
+        if (file == Py_None) /* write to stdout */
+            retval = msSaveImage(NULL, self, NULL);
+
+        else if (PyFile_Check(file)) /* a Python (C) file */
+        {
+            renderer = self->format->vtable;
+            /* FIXME? as an improvement, pass a map argument instead of the NULL (see #4216) */
+            retval = renderer->saveImage(self, NULL, PyFile_AsFile(file), self->format);
+        }
+        else /* presume a Python file-like object */
+        {
+            imgbuffer = msSaveImageBuffer(self, &imgsize,
+                                          self->format);
+            if (imgsize == 0)
+            {
+                msSetError(15, "failed to get image buffer", "write()");
+                return MS_FAILURE;
+            }
+                
+            noerr = PyObject_CallMethod(file, "write", "s#", imgbuffer,
+                                        imgsize);
+            free(imgbuffer);
+            if (noerr == NULL)
+                return MS_FAILURE;
+            else
+                Py_DECREF(noerr);
+            retval = MS_SUCCESS;
+        }
+
+        return retval;
+    }
+SWIGINTERN PyObject *imageObj_saveToString(imageObj *self){
+        int size=0;
+        unsigned char *imgbytes;
+        PyObject *imgstring; 
+
+        imgbytes = msSaveImageBuffer(self, &size, self->format);
+        if (size == 0)
+        {
+            msSetError(15, "failed to get image buffer", "saveToString()");
+            return NULL;
+        }
+        imgstring = PyString_FromStringAndSize((const char*) imgbytes, size); 
+        free(imgbytes);
+        return imgstring;
+    }
 SWIGINTERN layerObj *new_layerObj(mapObj *map){
         layerObj *layer;
         int result;
@@ -3883,6 +4188,9 @@ SWIGINTERN char *layerObj_getItem(layerObj *self,int i){
         else
             return NULL;
     }
+SWIGINTERN int layerObj_setItems(layerObj *self,char **items,int numitems){
+        return msLayerSetItems(self, items, numitems);
+    }
 SWIGINTERN int layerObj_draw(layerObj *self,mapObj *map,imageObj *image){
         return msDrawLayer(map, self, image);    
     }
@@ -3900,7 +4208,10 @@ SWIGINTERN int layerObj_queryByFilter(layerObj *self,mapObj *map,char *string){
         map->query.filter = (expressionObj *) malloc(sizeof(expressionObj));
         map->query.filter->string = strdup(string);
 	map->query.filter->type = 2000; /* MS_EXPRESSION: lot's of conflicts in mapfile.h */
-
+        map->query.filter->compiled = 0;
+        map->query.filter->flags = 0;
+        map->query.filter->tokens = map->query.filter->curtoken = NULL;
+        
         map->query.layer = self->index;
      	map->query.rect = map->extent;
 
@@ -3927,6 +4238,7 @@ SWIGINTERN int layerObj_queryByAttributes(layerObj *self,mapObj *map,char *qitem
         self->status = 1;
         retval = msQueryByAttributes(map);
         self->status = status;
+
         return retval;
     }
 SWIGINTERN int layerObj_queryByPoint(layerObj *self,mapObj *map,pointObj *point,int mode,double buffer){
@@ -3945,6 +4257,7 @@ SWIGINTERN int layerObj_queryByPoint(layerObj *self,mapObj *map,pointObj *point,
         self->status = 1;
         retval = msQueryByPoint(map);
         self->status = status;
+
         return retval;
     }
 SWIGINTERN int layerObj_queryByRect(layerObj *self,mapObj *map,rectObj rect){
@@ -3962,6 +4275,7 @@ SWIGINTERN int layerObj_queryByRect(layerObj *self,mapObj *map,rectObj rect){
         self->status = 1;
         retval = msQueryByRect(map);
         self->status = status;
+
         return retval;
     }
 SWIGINTERN int layerObj_queryByFeatures(layerObj *self,mapObj *map,int slayer){
@@ -4111,10 +4425,10 @@ SWIGINTERN char *layerObj_executeWFSGetFeature(layerObj *self,layerObj *layer){
         return (char *) msWFSExecuteGetFeature(layer);
     }
 SWIGINTERN int layerObj_applySLD(layerObj *self,char *sld,char *stylelayer){
-        return msSLDApplySLD(self->map, sld, self->index, stylelayer);
+      return msSLDApplySLD(self->map, sld, self->index, stylelayer, NULL);
     }
 SWIGINTERN int layerObj_applySLDURL(layerObj *self,char *sld,char *stylelayer){
-        return msSLDApplySLDURL(self->map, sld, self->index, stylelayer);
+      return msSLDApplySLDURL(self->map, sld, self->index, stylelayer, NULL);
     }
 SWIGINTERN char *layerObj_generateSLD(layerObj *self){
         return (char *) msSLDGenerateSLD(self->map, self->index, NULL);
@@ -4318,7 +4632,10 @@ SWIGINTERN int mapObj_queryByFilter(mapObj *self,char *string){
     self->query.filter = (expressionObj *) malloc(sizeof(expressionObj));
     self->query.filter->string = strdup(string);
     self->query.filter->type = 2000; /* MS_EXPRESSION: lot's of conflicts in mapfile.h */
-
+    self->query.filter->compiled = 0;
+    self->query.filter->flags = 0;
+    self->query.filter->tokens = self->query.filter->curtoken = NULL;
+    
     self->query.rect = self->extent;
 
     return msQueryByFilter(self);
@@ -4467,10 +4784,10 @@ SWIGINTERN void mapObj_applyConfigOptions(mapObj *self){
     msApplyMapConfigOptions( self );
   }
 SWIGINTERN int mapObj_applySLD(mapObj *self,char *sld){
-        return msSLDApplySLD(self, sld, -1, NULL);
+      return msSLDApplySLD(self, sld, -1, NULL, NULL);
     }
 SWIGINTERN int mapObj_applySLDURL(mapObj *self,char *sld){
-        return msSLDApplySLDURL(self, sld, -1, NULL);
+      return msSLDApplySLDURL(self, sld, -1, NULL, NULL);
     }
 SWIGINTERN char *mapObj_generateSLD(mapObj *self){
         return (char *) msSLDGenerateSLD(self, -1, NULL);
@@ -5050,254 +5367,6 @@ SWIGINTERN PyObject *mapObj_getSize(mapObj *self){
         PyTuple_SetItem(output,1,PyInt_FromLong((long)self->height));
         return output;
     }
-SWIGINTERN void delete_imageObj(imageObj *self){
-        msFreeImage(self);    
-    }
-SWIGINTERN void imageObj_save(imageObj *self,char *filename,mapObj *map){
-        msSaveImage(map, self, filename );
-    }
-SWIGINTERN gdBuffer imageObj_getBytes(imageObj *self){
-        gdBuffer buffer;
-        
-        buffer.owns_data = 1;
-        
-        buffer.data = msSaveImageBuffer(self, &buffer.size, self->format);
-            
-        if( buffer.data == NULL || buffer.size == 0 )
-        {
-            buffer.data = NULL;
-            msSetError(12, "Failed to get image buffer", "getBytes");
-            return buffer;
-        }
-
-        return buffer;
-    }
-SWIGINTERN int imageObj_getSize(imageObj *self){
-        gdBuffer buffer;
-	int size=0;
-        
-        buffer.data = msSaveImageBuffer(self, &buffer.size, self->format);
-	size = buffer.size;
-            
-        if( buffer.data == NULL || buffer.size == 0 ) {
-            buffer.data = NULL;
-            msSetError(12, "Failed to get image buffer size", "getSize");
-        }
-	free(buffer.data);
-        return size;
-    }
-SWIGINTERN imageObj *new_imageObj(PyObject *arg1,PyObject *arg2,PyObject *input_format,PyObject *input_resolution,PyObject *input_defresolution){
-        imageObj *image=NULL;
-        outputFormatObj *format=NULL;
-        int width;
-        int height;
-        double resolution, defresolution;
-        PyObject *pybytes;
-        rendererVTableObj *renderer = NULL;
-        rasterBufferObj *rb = NULL;
-      
-        unsigned char PNGsig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
-        unsigned char JPEGsig[3] = {255, 216, 255};
-
-        resolution = defresolution = MS_DEFAULT_RESOLUTION;
-
-        if ((PyInt_Check(arg1) && PyInt_Check(arg2)) || PyString_Check(arg1))
-        {
-            if (input_format == Py_None) {
-                format = msCreateDefaultOutputFormat(NULL, "GD/GIF", "gdgif");
-                if (format == NULL)
-                    format = msCreateDefaultOutputFormat(NULL, "GD/PNG", "gdpng");
-
-                if (format)
-                  msInitializeRendererVTable(format);
-            }
-            else if (PyString_Check(input_format)) {
-                format = msCreateDefaultOutputFormat(NULL, 
-                                                     PyString_AsString(input_format),
-                                                     NULL);
-            }
-            else {
-                if ((SWIG_ConvertPtr(input_format, (void **) &format,
-                                     SWIGTYPE_p_outputFormatObj,
-                                     SWIG_POINTER_EXCEPTION | 0 )) == -1) 
-                {
-                    msSetError(15, "Can't convert format pointer",
-                               "imageObj()");
-                    return NULL;
-                }
-            }
-        
-            if (format == NULL) {
-                msSetError(15, "Could not create output format",
-                           "imageObj()");
-                return NULL;
-            }
-        }
-
-        if (PyFloat_Check(input_resolution))
-            resolution = PyFloat_AsDouble(input_resolution);
-        if (PyFloat_Check(input_defresolution))
-            defresolution = PyFloat_AsDouble(input_defresolution);
-
-        if (PyInt_Check(arg1) && PyInt_Check(arg2)) 
-        {
-            /* Create from width, height, format/driver */
-            width = (int) PyInt_AsLong(arg1);
-            height = (int) PyInt_AsLong(arg2);
-
-            image = msImageCreate(width, height, format, NULL, NULL, resolution, defresolution, NULL);
-            return image;
-        }
-        
-        /* Is arg1 a filename? */
-        else if (PyString_Check(arg1)) 
-        {
-            renderer = format->vtable;
-            rb = (rasterBufferObj*)calloc(1,sizeof(rasterBufferObj));
-
-            if (!rb) {
-                msSetError(2, NULL, "imageObj()");
-                return NULL;
-            }
-
-            if ( (renderer->loadImageFromFile(PyString_AsString(arg1), rb)) == MS_FAILURE)
-                return NULL;
-
-            image = msImageCreate(rb->width, rb->height, format, NULL, NULL, 
-                                  resolution, defresolution, NULL);
-            renderer->mergeRasterBuffer(image, rb, 1.0, 0, 0, 0, 0, rb->width, rb->height);
-
-            msFreeRasterBuffer(rb);
-            free(rb);
-
-            return image;
-        }
-        
-        /* Is a file-like object */
-        else if (arg1 != Py_None)
-        {
-
-            if (PyObject_HasAttrString(arg1, "seek"))
-            {
-                /* Detect image format */
-                pybytes = PyObject_CallMethod(arg1, "read", "i", 8);
-                PyObject_CallMethod(arg1, "seek", "i", 0);
-            
-                if (memcmp(PyString_AsString(pybytes),"GIF8",4)==0) 
-                {
-#ifdef USE_GD_GIF
-                    image = createImageObjFromPyFile(arg1, "GD/GIF");
-#else
-                    msSetError(12, "Unable to load GIF image.",
-                               "imageObj()");
-#endif
-                }
-                else if (memcmp(PyString_AsString(pybytes),PNGsig,8)==0) 
-                {
-#ifdef USE_GD_PNG
-                    image = createImageObjFromPyFile(arg1, "GD/PNG");
-#else
-                    msSetError(12, "Unable to load PNG image.",
-                               "imageObj()");
-#endif
-                }
-                else if (memcmp(PyString_AsString(pybytes),JPEGsig,3)==0) 
-                {
-#ifdef USE_GD_JPEG
-                    image = createImageObjFromPyFile(arg1, "GD/JPEG");
-#else
-                    msSetError(12, "Unable to load JPEG image.", 
-                               "imageObj()");
-#endif
-                }
-                else
-                {
-                    msSetError(12, "Failed to detect image format.  Likely cause is invalid image or improper filemode.  On windows, Python files should be opened in 'rb' mode.", "imageObj()");
-                }
-
-                return image;
-            
-            }
-            else /* such as a url handle */
-            {
-                /* If there is no seek method, we absolutely must
-                   have a driver name */
-                if (!PyString_Check(arg2))
-                {
-                    msSetError(12, "A driver name absolutely must accompany file objects which do not have a seek() method", "imageObj()");
-                    return NULL;
-                }    
-                return (imageObj *) createImageObjFromPyFile(arg1, 
-                        PyString_AsString(arg2));
-            }
-        }
-        else 
-        {
-            msSetError(15, "Failed to create image", 
-                       "imageObj()");
-            return NULL;
-        }
-    }
-SWIGINTERN int imageObj_write(imageObj *self,PyObject *file){
-        unsigned char *imgbuffer=NULL;
-        int imgsize;
-        PyObject *noerr;
-        int retval=MS_FAILURE;
-        rendererVTableObj *renderer = NULL;
-
-        /* Return immediately if image driver is not GD */
-        if ( !MS_RENDERER_PLUGIN(self->format) )
-        {
-            msSetError(15, "Writing of %s format not implemented",
-                       "imageObj::write", self->format->driver);
-            return MS_FAILURE;
-        }
-
-        if (file == Py_None) /* write to stdout */
-            retval = msSaveImage(NULL, self, NULL);
-
-        else if (PyFile_Check(file)) /* a Python (C) file */
-        {
-            renderer = self->format->vtable;
-            retval = renderer->saveImage(self, PyFile_AsFile(file), self->format);
-        }
-        else /* presume a Python file-like object */
-        {
-            imgbuffer = msSaveImageBuffer(self, &imgsize,
-                                          self->format);
-            if (imgsize == 0)
-            {
-                msSetError(15, "failed to get image buffer", "write()");
-                return MS_FAILURE;
-            }
-                
-            noerr = PyObject_CallMethod(file, "write", "s#", imgbuffer,
-                                        imgsize);
-            free(imgbuffer);
-            if (noerr == NULL)
-                return MS_FAILURE;
-            else
-                Py_DECREF(noerr);
-            retval = MS_SUCCESS;
-        }
-
-        return retval;
-    }
-SWIGINTERN PyObject *imageObj_saveToString(imageObj *self){
-        int size=0;
-        unsigned char *imgbytes;
-        PyObject *imgstring; 
-
-        imgbytes = msSaveImageBuffer(self, &size, self->format);
-        if (size == 0)
-        {
-            msSetError(15, "failed to get image buffer", "saveToString()");
-            return NULL;
-        }
-        imgstring = PyString_FromStringAndSize((const char*) imgbytes, size); 
-        free(imgbytes);
-        return imgstring;
-    }
 SWIGINTERN rectObj *new_rectObj(double minx,double miny,double maxx,double maxy,int imageunits){	
         rectObj *rect;
     
@@ -5350,7 +5419,7 @@ SWIGINTERN int rectObj_draw(rectObj *self,mapObj *map,layerObj *layer,imageObj *
         shape.classindex = classindex;
         shape.text = strdup(text);
 
-        msDrawShape(map, layer, &shape, image, -1, 0);
+        msDrawShape(map, layer, &shape, image, -1, MS_DRAWMODE_FEATURES|MS_DRAWMODE_LABELS);
 
         msFreeShape(&shape);
     
@@ -5589,7 +5658,7 @@ SWIGINTERN int shapeObj_add(shapeObj *self,lineObj *line){
         return msAddLine(self, line);
     }
 SWIGINTERN int shapeObj_draw(shapeObj *self,mapObj *map,layerObj *layer,imageObj *image){
-        return msDrawShape(map, layer, self, image, -1, 0);
+        return msDrawShape(map, layer, self, image, -1, MS_DRAWMODE_FEATURES|MS_DRAWMODE_LABELS);
     }
 SWIGINTERN void shapeObj_setBounds(shapeObj *self){    
         msComputeBounds(self);
@@ -5975,7 +6044,7 @@ SWIGINTERN lineObj *symbolObj_getPoints(symbolObj *self){
         return line;
     }
 SWIGINTERN imageObj *symbolObj_getImage(symbolObj *self,outputFormatObj *input_format){
-        imageObj *image;
+        imageObj *image = NULL;
         outputFormatObj *format = NULL;
         rendererVTableObj *renderer = NULL;
 
@@ -6034,7 +6103,6 @@ SWIGINTERN int symbolObj_setImage(symbolObj *self,imageObj *image){
             msSetError(2, NULL, "setImage()");
             return MS_FAILURE;
         }
-        renderer->initializeRasterBuffer(self->pixmap_buffer, image->width, image->height, image->format->imagemode);
         self->type = MS_SYMBOL_PIXMAP;
         renderer->getRasterBufferCopy(image, self->pixmap_buffer);
 
@@ -6154,6 +6222,14 @@ SWIGINTERN void cgiRequestObj_setParameter(cgiRequestObj *self,char *name,char *
             self->NumParams++;
         }
     }
+SWIGINTERN void cgiRequestObj_addParameter(cgiRequestObj *self,char *name,char *value){
+        if (self->NumParams == 100) {
+            msSetError(31, "Maximum number of items, %d, has been reached", "addParameter()", 100);
+        }
+        self->ParamNames[self->NumParams] = strdup(name);
+        self->ParamValues[self->NumParams] = strdup(value);
+        self->NumParams++;
+    }
 SWIGINTERN char *cgiRequestObj_getName(cgiRequestObj *self,int index){
         if (index < 0 || index >= self->NumParams) {
             msSetError(31, "Invalid index, valid range is [0, %d]", "getName()", self->NumParams-1);
@@ -8745,7 +8821,7 @@ SWIGINTERN PyObject *_wrap_webObj_map_get(PyObject *SWIGUNUSEDPARM(self), PyObje
   void *argp1 = 0 ;
   int res1 = 0 ;
   PyObject * obj0 = 0 ;
-  struct map_obj *result = 0 ;
+  struct mapObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:webObj_map_get",&obj0)) SWIG_fail;
   res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_webObj, 0 |  0 );
@@ -8753,8 +8829,8 @@ SWIGINTERN PyObject *_wrap_webObj_map_get(PyObject *SWIGUNUSEDPARM(self), PyObje
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "webObj_map_get" "', argument " "1"" of type '" "webObj *""'"); 
   }
   arg1 = (webObj *)(argp1);
-  result = (struct map_obj *) ((arg1)->map);
-  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_map_obj, 0 |  0 );
+  result = (struct mapObj *) ((arg1)->map);
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_mapObj, 0 |  0 );
   return resultobj;
 fail:
   return NULL;
@@ -10637,6 +10713,58 @@ fail:
 }
 
 
+SWIGINTERN PyObject *_wrap_styleObj_initialgap_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  styleObj *arg1 = (styleObj *) 0 ;
+  double arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  double val2 ;
+  int ecode2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:styleObj_initialgap_set",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_styleObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "styleObj_initialgap_set" "', argument " "1"" of type '" "styleObj *""'"); 
+  }
+  arg1 = (styleObj *)(argp1);
+  ecode2 = SWIG_AsVal_double(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "styleObj_initialgap_set" "', argument " "2"" of type '" "double""'");
+  } 
+  arg2 = (double)(val2);
+  if (arg1) (arg1)->initialgap = arg2;
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_styleObj_initialgap_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  styleObj *arg1 = (styleObj *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  double result;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:styleObj_initialgap_get",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_styleObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "styleObj_initialgap_get" "', argument " "1"" of type '" "styleObj *""'"); 
+  }
+  arg1 = (styleObj *)(argp1);
+  result = (double) ((arg1)->initialgap);
+  resultobj = SWIG_From_double((double)(result));
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
 SWIGINTERN PyObject *_wrap_styleObj_position_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   styleObj *arg1 = (styleObj *) 0 ;
@@ -11157,6 +11285,110 @@ fail:
 }
 
 
+SWIGINTERN PyObject *_wrap_styleObj_polaroffsetpixel_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  styleObj *arg1 = (styleObj *) 0 ;
+  double arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  double val2 ;
+  int ecode2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:styleObj_polaroffsetpixel_set",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_styleObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "styleObj_polaroffsetpixel_set" "', argument " "1"" of type '" "styleObj *""'"); 
+  }
+  arg1 = (styleObj *)(argp1);
+  ecode2 = SWIG_AsVal_double(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "styleObj_polaroffsetpixel_set" "', argument " "2"" of type '" "double""'");
+  } 
+  arg2 = (double)(val2);
+  if (arg1) (arg1)->polaroffsetpixel = arg2;
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_styleObj_polaroffsetpixel_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  styleObj *arg1 = (styleObj *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  double result;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:styleObj_polaroffsetpixel_get",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_styleObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "styleObj_polaroffsetpixel_get" "', argument " "1"" of type '" "styleObj *""'"); 
+  }
+  arg1 = (styleObj *)(argp1);
+  result = (double) ((arg1)->polaroffsetpixel);
+  resultobj = SWIG_From_double((double)(result));
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_styleObj_polaroffsetangle_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  styleObj *arg1 = (styleObj *) 0 ;
+  double arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  double val2 ;
+  int ecode2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:styleObj_polaroffsetangle_set",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_styleObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "styleObj_polaroffsetangle_set" "', argument " "1"" of type '" "styleObj *""'"); 
+  }
+  arg1 = (styleObj *)(argp1);
+  ecode2 = SWIG_AsVal_double(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "styleObj_polaroffsetangle_set" "', argument " "2"" of type '" "double""'");
+  } 
+  arg2 = (double)(val2);
+  if (arg1) (arg1)->polaroffsetangle = arg2;
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_styleObj_polaroffsetangle_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  styleObj *arg1 = (styleObj *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  double result;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:styleObj_polaroffsetangle_get",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_styleObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "styleObj_polaroffsetangle_get" "', argument " "1"" of type '" "styleObj *""'"); 
+  }
+  arg1 = (styleObj *)(argp1);
+  result = (double) ((arg1)->polaroffsetangle);
+  resultobj = SWIG_From_double((double)(result));
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
 SWIGINTERN PyObject *_wrap_styleObj_angle_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   styleObj *arg1 = (styleObj *) 0 ;
@@ -11375,7 +11607,7 @@ SWIGINTERN PyObject *_wrap_new_styleObj(PyObject *SWIGUNUSEDPARM(self), PyObject
   
   if (!PyArg_ParseTuple(args,(char *)"|O:new_styleObj",&obj0)) SWIG_fail;
   if (obj0) {
-    res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "new_styleObj" "', argument " "1"" of type '" "classObj *""'"); 
     }
@@ -11574,7 +11806,7 @@ SWIGINTERN PyObject *_wrap_styleObj_setSymbolByName(PyObject *SWIGUNUSEDPARM(sel
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "styleObj_setSymbolByName" "', argument " "1"" of type '" "styleObj *""'"); 
   }
   arg1 = (styleObj *)(argp1);
-  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_map_obj, 0 |  0 );
+  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res2)) {
     SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "styleObj_setSymbolByName" "', argument " "2"" of type '" "mapObj *""'"); 
   }
@@ -11882,6 +12114,245 @@ SWIGINTERN PyObject *styleObj_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObj
   return SWIG_Py_Void();
 }
 
+SWIGINTERN PyObject *_wrap_labelLeaderObj_maxdistance_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  labelLeaderObj *arg1 = (labelLeaderObj *) 0 ;
+  int arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val2 ;
+  int ecode2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:labelLeaderObj_maxdistance_set",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_labelLeaderObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelLeaderObj_maxdistance_set" "', argument " "1"" of type '" "labelLeaderObj *""'"); 
+  }
+  arg1 = (labelLeaderObj *)(argp1);
+  ecode2 = SWIG_AsVal_int(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "labelLeaderObj_maxdistance_set" "', argument " "2"" of type '" "int""'");
+  } 
+  arg2 = (int)(val2);
+  if (arg1) (arg1)->maxdistance = arg2;
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_labelLeaderObj_maxdistance_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  labelLeaderObj *arg1 = (labelLeaderObj *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  int result;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:labelLeaderObj_maxdistance_get",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_labelLeaderObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelLeaderObj_maxdistance_get" "', argument " "1"" of type '" "labelLeaderObj *""'"); 
+  }
+  arg1 = (labelLeaderObj *)(argp1);
+  result = (int) ((arg1)->maxdistance);
+  resultobj = SWIG_From_int((int)(result));
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_labelLeaderObj_gridstep_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  labelLeaderObj *arg1 = (labelLeaderObj *) 0 ;
+  int arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val2 ;
+  int ecode2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:labelLeaderObj_gridstep_set",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_labelLeaderObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelLeaderObj_gridstep_set" "', argument " "1"" of type '" "labelLeaderObj *""'"); 
+  }
+  arg1 = (labelLeaderObj *)(argp1);
+  ecode2 = SWIG_AsVal_int(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "labelLeaderObj_gridstep_set" "', argument " "2"" of type '" "int""'");
+  } 
+  arg2 = (int)(val2);
+  if (arg1) (arg1)->gridstep = arg2;
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_labelLeaderObj_gridstep_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  labelLeaderObj *arg1 = (labelLeaderObj *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  int result;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:labelLeaderObj_gridstep_get",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_labelLeaderObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelLeaderObj_gridstep_get" "', argument " "1"" of type '" "labelLeaderObj *""'"); 
+  }
+  arg1 = (labelLeaderObj *)(argp1);
+  result = (int) ((arg1)->gridstep);
+  resultobj = SWIG_From_int((int)(result));
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_labelLeaderObj_numstyles_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  labelLeaderObj *arg1 = (labelLeaderObj *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  int result;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:labelLeaderObj_numstyles_get",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_labelLeaderObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelLeaderObj_numstyles_get" "', argument " "1"" of type '" "labelLeaderObj *""'"); 
+  }
+  arg1 = (labelLeaderObj *)(argp1);
+  result = (int) ((arg1)->numstyles);
+  resultobj = SWIG_From_int((int)(result));
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_new_labelLeaderObj(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  labelLeaderObj *result = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)":new_labelLeaderObj")) SWIG_fail;
+  {
+    result = (labelLeaderObj *)calloc(1, sizeof(labelLeaderObj)); {
+      errorObj *ms_error = msGetErrorObj();
+      
+      switch(ms_error->code) {
+      case MS_NOERR:
+        break;
+      case MS_NOTFOUND:
+        msResetErrorList();
+        break;
+      case -1:
+        break;
+      case MS_IOERR:
+        if (strcmp(ms_error->routine, "msSearchDiskTree()") != 0) {
+          _raise_ms_exception();
+          msResetErrorList();
+          return NULL;
+        }
+      default:
+        _raise_ms_exception();
+        msResetErrorList();
+        return NULL;
+      }
+      
+    }
+  }
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_labelLeaderObj, SWIG_POINTER_NEW |  0 );
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_delete_labelLeaderObj(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  labelLeaderObj *arg1 = (labelLeaderObj *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:delete_labelLeaderObj",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_labelLeaderObj, SWIG_POINTER_DISOWN |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_labelLeaderObj" "', argument " "1"" of type '" "labelLeaderObj *""'"); 
+  }
+  arg1 = (labelLeaderObj *)(argp1);
+  {
+    free((char *) arg1); {
+      errorObj *ms_error = msGetErrorObj();
+      
+      switch(ms_error->code) {
+      case MS_NOERR:
+        break;
+      case MS_NOTFOUND:
+        msResetErrorList();
+        break;
+      case -1:
+        break;
+      case MS_IOERR:
+        if (strcmp(ms_error->routine, "msSearchDiskTree()") != 0) {
+          _raise_ms_exception();
+          msResetErrorList();
+          return NULL;
+        }
+      default:
+        _raise_ms_exception();
+        msResetErrorList();
+        return NULL;
+      }
+      
+    }
+  }
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *labelLeaderObj_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *obj;
+  if (!PyArg_ParseTuple(args,(char*)"O:swigregister", &obj)) return NULL;
+  SWIG_TypeNewClientData(SWIGTYPE_p_labelLeaderObj, SWIG_NewClientData(obj));
+  return SWIG_Py_Void();
+}
+
+SWIGINTERN PyObject *_wrap_labelObj_refcount_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  labelObj *arg1 = (labelObj *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  int result;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:labelObj_refcount_get",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_labelObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelObj_refcount_get" "', argument " "1"" of type '" "labelObj *""'"); 
+  }
+  arg1 = (labelObj *)(argp1);
+  result = (int) ((arg1)->refcount);
+  resultobj = SWIG_From_int((int)(result));
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
 SWIGINTERN PyObject *_wrap_labelObj_font_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   labelObj *arg1 = (labelObj *) 0 ;
@@ -13650,6 +14121,58 @@ fail:
 }
 
 
+SWIGINTERN PyObject *_wrap_labelObj_status_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  labelObj *arg1 = (labelObj *) 0 ;
+  int arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val2 ;
+  int ecode2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:labelObj_status_set",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_labelObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelObj_status_set" "', argument " "1"" of type '" "labelObj *""'"); 
+  }
+  arg1 = (labelObj *)(argp1);
+  ecode2 = SWIG_AsVal_int(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "labelObj_status_set" "', argument " "2"" of type '" "int""'");
+  } 
+  arg2 = (int)(val2);
+  if (arg1) (arg1)->status = arg2;
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_labelObj_status_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  labelObj *arg1 = (labelObj *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  int result;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:labelObj_status_get",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_labelObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelObj_status_get" "', argument " "1"" of type '" "labelObj *""'"); 
+  }
+  arg1 = (labelObj *)(argp1);
+  result = (int) ((arg1)->status);
+  resultobj = SWIG_From_int((int)(result));
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
 SWIGINTERN PyObject *_wrap_labelObj_numstyles_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   labelObj *arg1 = (labelObj *) 0 ;
@@ -13702,23 +14225,315 @@ fail:
 }
 
 
-SWIGINTERN PyObject *_wrap_labelObj_updateFromString(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_labelObj_annotext_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   labelObj *arg1 = (labelObj *) 0 ;
   char *arg2 = (char *) 0 ;
   void *argp1 = 0 ;
   int res1 = 0 ;
   PyObject * obj0 = 0 ;
-  int result;
   
-  if (!PyArg_ParseTuple(args,(char *)"Oz:labelObj_updateFromString",&obj0,&arg2)) SWIG_fail;
+  if (!PyArg_ParseTuple(args,(char *)"Oz:labelObj_annotext_set",&obj0,&arg2)) SWIG_fail;
   res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_labelObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelObj_updateFromString" "', argument " "1"" of type '" "labelObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelObj_annotext_set" "', argument " "1"" of type '" "labelObj *""'"); 
   }
   arg1 = (labelObj *)(argp1);
   {
-    result = (int)labelObj_updateFromString(arg1,arg2); {
+    if (arg1->annotext) free((char*)arg1->annotext);
+    if (arg2) {
+      arg1->annotext = (char *) malloc(strlen(arg2)+1);
+      strcpy((char*)arg1->annotext,arg2);
+    } else {
+      arg1->annotext = 0;
+    }
+  }
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_labelObj_annotext_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  labelObj *arg1 = (labelObj *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  char *result = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:labelObj_annotext_get",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_labelObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelObj_annotext_get" "', argument " "1"" of type '" "labelObj *""'"); 
+  }
+  arg1 = (labelObj *)(argp1);
+  result = (char *) ((arg1)->annotext);
+  resultobj = SWIG_FromCharPtr((const char *)result);
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_labelObj_annopoint_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  labelObj *arg1 = (labelObj *) 0 ;
+  pointObj *arg2 = (pointObj *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  void *argp2 = 0 ;
+  int res2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:labelObj_annopoint_set",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_labelObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelObj_annopoint_set" "', argument " "1"" of type '" "labelObj *""'"); 
+  }
+  arg1 = (labelObj *)(argp1);
+  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_pointObj, 0 |  0 );
+  if (!SWIG_IsOK(res2)) {
+    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "labelObj_annopoint_set" "', argument " "2"" of type '" "pointObj *""'"); 
+  }
+  arg2 = (pointObj *)(argp2);
+  if (arg1) (arg1)->annopoint = *arg2;
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_labelObj_annopoint_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  labelObj *arg1 = (labelObj *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  pointObj *result = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:labelObj_annopoint_get",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_labelObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelObj_annopoint_get" "', argument " "1"" of type '" "labelObj *""'"); 
+  }
+  arg1 = (labelObj *)(argp1);
+  result = (pointObj *)& ((arg1)->annopoint);
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_pointObj, 0 |  0 );
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_labelObj_annopoly_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  labelObj *arg1 = (labelObj *) 0 ;
+  shapeObj *arg2 = (shapeObj *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  void *argp2 = 0 ;
+  int res2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:labelObj_annopoly_set",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_labelObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelObj_annopoly_set" "', argument " "1"" of type '" "labelObj *""'"); 
+  }
+  arg1 = (labelObj *)(argp1);
+  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_shapeObj, SWIG_POINTER_DISOWN |  0 );
+  if (!SWIG_IsOK(res2)) {
+    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "labelObj_annopoly_set" "', argument " "2"" of type '" "shapeObj *""'"); 
+  }
+  arg2 = (shapeObj *)(argp2);
+  if (arg1) (arg1)->annopoly = arg2;
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_labelObj_annopoly_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  labelObj *arg1 = (labelObj *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  shapeObj *result = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:labelObj_annopoly_get",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_labelObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelObj_annopoly_get" "', argument " "1"" of type '" "labelObj *""'"); 
+  }
+  arg1 = (labelObj *)(argp1);
+  result = (shapeObj *) ((arg1)->annopoly);
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_shapeObj, 0 |  0 );
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_labelObj_leader_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  labelObj *arg1 = (labelObj *) 0 ;
+  labelLeaderObj *arg2 = (labelLeaderObj *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  void *argp2 = 0 ;
+  int res2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:labelObj_leader_set",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_labelObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelObj_leader_set" "', argument " "1"" of type '" "labelObj *""'"); 
+  }
+  arg1 = (labelObj *)(argp1);
+  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_labelLeaderObj, 0 |  0 );
+  if (!SWIG_IsOK(res2)) {
+    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "labelObj_leader_set" "', argument " "2"" of type '" "labelLeaderObj *""'"); 
+  }
+  arg2 = (labelLeaderObj *)(argp2);
+  if (arg1) (arg1)->leader = *arg2;
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_labelObj_leader_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  labelObj *arg1 = (labelObj *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  labelLeaderObj *result = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:labelObj_leader_get",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_labelObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelObj_leader_get" "', argument " "1"" of type '" "labelObj *""'"); 
+  }
+  arg1 = (labelObj *)(argp1);
+  result = (labelLeaderObj *)& ((arg1)->leader);
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_labelLeaderObj, 0 |  0 );
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_new_labelObj(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  labelObj *result = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)":new_labelObj")) SWIG_fail;
+  {
+    result = (labelObj *)new_labelObj(); {
+      errorObj *ms_error = msGetErrorObj();
+      
+      switch(ms_error->code) {
+      case MS_NOERR:
+        break;
+      case MS_NOTFOUND:
+        msResetErrorList();
+        break;
+      case -1:
+        break;
+      case MS_IOERR:
+        if (strcmp(ms_error->routine, "msSearchDiskTree()") != 0) {
+          _raise_ms_exception();
+          msResetErrorList();
+          return NULL;
+        }
+      default:
+        _raise_ms_exception();
+        msResetErrorList();
+        return NULL;
+      }
+      
+    }
+  }
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_labelObj, SWIG_POINTER_NEW |  0 );
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_delete_labelObj(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  labelObj *arg1 = (labelObj *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:delete_labelObj",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_labelObj, SWIG_POINTER_DISOWN |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_labelObj" "', argument " "1"" of type '" "labelObj *""'"); 
+  }
+  arg1 = (labelObj *)(argp1);
+  {
+    delete_labelObj(arg1); {
+      errorObj *ms_error = msGetErrorObj();
+      
+      switch(ms_error->code) {
+      case MS_NOERR:
+        break;
+      case MS_NOTFOUND:
+        msResetErrorList();
+        break;
+      case -1:
+        break;
+      case MS_IOERR:
+        if (strcmp(ms_error->routine, "msSearchDiskTree()") != 0) {
+          _raise_ms_exception();
+          msResetErrorList();
+          return NULL;
+        }
+      default:
+        _raise_ms_exception();
+        msResetErrorList();
+        return NULL;
+      }
+      
+    }
+  }
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_labelObj_updateFromString(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  labelObj *arg1 = (labelObj *) 0 ;
+  char *arg2 = (char *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  int result;
+  
+  if (!PyArg_ParseTuple(args,(char *)"Oz:labelObj_updateFromString",&obj0,&arg2)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_labelObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelObj_updateFromString" "', argument " "1"" of type '" "labelObj *""'"); 
+  }
+  arg1 = (labelObj *)(argp1);
+  {
+    result = (int)labelObj_updateFromString(arg1,arg2); {
       errorObj *ms_error = msGetErrorObj();
       
       switch(ms_error->code) {
@@ -13919,31 +14734,23 @@ fail:
 }
 
 
-SWIGINTERN PyObject *_wrap_labelObj_getStyle(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_labelObj_setExpression(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   labelObj *arg1 = (labelObj *) 0 ;
-  int arg2 ;
+  char *arg2 = (char *) 0 ;
   void *argp1 = 0 ;
   int res1 = 0 ;
-  int val2 ;
-  int ecode2 = 0 ;
   PyObject * obj0 = 0 ;
-  PyObject * obj1 = 0 ;
-  styleObj *result = 0 ;
+  int result;
   
-  if (!PyArg_ParseTuple(args,(char *)"OO:labelObj_getStyle",&obj0,&obj1)) SWIG_fail;
+  if (!PyArg_ParseTuple(args,(char *)"Oz:labelObj_setExpression",&obj0,&arg2)) SWIG_fail;
   res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_labelObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelObj_getStyle" "', argument " "1"" of type '" "labelObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelObj_setExpression" "', argument " "1"" of type '" "labelObj *""'"); 
   }
   arg1 = (labelObj *)(argp1);
-  ecode2 = SWIG_AsVal_int(obj1, &val2);
-  if (!SWIG_IsOK(ecode2)) {
-    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "labelObj_getStyle" "', argument " "2"" of type '" "int""'");
-  } 
-  arg2 = (int)(val2);
   {
-    result = (styleObj *)labelObj_getStyle(arg1,arg2); {
+    result = (int)labelObj_setExpression(arg1,arg2); {
       errorObj *ms_error = msGetErrorObj();
       
       switch(ms_error->code) {
@@ -13968,49 +14775,78 @@ SWIGINTERN PyObject *_wrap_labelObj_getStyle(PyObject *SWIGUNUSEDPARM(self), PyO
       
     }
   }
-  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_styleObj, SWIG_POINTER_OWN |  0 );
+  resultobj = SWIG_From_int((int)(result));
   return resultobj;
 fail:
   return NULL;
 }
 
 
-SWIGINTERN PyObject *_wrap_labelObj_insertStyle(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_labelObj_getExpressionString(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   labelObj *arg1 = (labelObj *) 0 ;
-  styleObj *arg2 = (styleObj *) 0 ;
-  int arg3 = (int) -1 ;
   void *argp1 = 0 ;
   int res1 = 0 ;
-  void *argp2 = 0 ;
-  int res2 = 0 ;
-  int val3 ;
-  int ecode3 = 0 ;
   PyObject * obj0 = 0 ;
-  PyObject * obj1 = 0 ;
-  PyObject * obj2 = 0 ;
-  int result;
+  char *result = 0 ;
   
-  if (!PyArg_ParseTuple(args,(char *)"OO|O:labelObj_insertStyle",&obj0,&obj1,&obj2)) SWIG_fail;
+  if (!PyArg_ParseTuple(args,(char *)"O:labelObj_getExpressionString",&obj0)) SWIG_fail;
   res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_labelObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelObj_insertStyle" "', argument " "1"" of type '" "labelObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelObj_getExpressionString" "', argument " "1"" of type '" "labelObj *""'"); 
   }
   arg1 = (labelObj *)(argp1);
-  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_styleObj, 0 |  0 );
-  if (!SWIG_IsOK(res2)) {
-    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "labelObj_insertStyle" "', argument " "2"" of type '" "styleObj *""'"); 
+  {
+    result = (char *)labelObj_getExpressionString(arg1); {
+      errorObj *ms_error = msGetErrorObj();
+      
+      switch(ms_error->code) {
+      case MS_NOERR:
+        break;
+      case MS_NOTFOUND:
+        msResetErrorList();
+        break;
+      case -1:
+        break;
+      case MS_IOERR:
+        if (strcmp(ms_error->routine, "msSearchDiskTree()") != 0) {
+          _raise_ms_exception();
+          msResetErrorList();
+          return NULL;
+        }
+      default:
+        _raise_ms_exception();
+        msResetErrorList();
+        return NULL;
+      }
+      
+    }
   }
-  arg2 = (styleObj *)(argp2);
-  if (obj2) {
-    ecode3 = SWIG_AsVal_int(obj2, &val3);
-    if (!SWIG_IsOK(ecode3)) {
-      SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "labelObj_insertStyle" "', argument " "3"" of type '" "int""'");
-    } 
-    arg3 = (int)(val3);
+  resultobj = SWIG_FromCharPtr((const char *)result);
+  free((char*)result);
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_labelObj_setText(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  labelObj *arg1 = (labelObj *) 0 ;
+  char *arg2 = (char *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  int result;
+  
+  if (!PyArg_ParseTuple(args,(char *)"Oz:labelObj_setText",&obj0,&arg2)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_labelObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelObj_setText" "', argument " "1"" of type '" "labelObj *""'"); 
   }
+  arg1 = (labelObj *)(argp1);
   {
-    result = (int)labelObj_insertStyle(arg1,arg2,arg3); {
+    result = (int)labelObj_setText(arg1,arg2); {
       errorObj *ms_error = msGetErrorObj();
       
       switch(ms_error->code) {
@@ -14042,7 +14878,55 @@ fail:
 }
 
 
-SWIGINTERN PyObject *_wrap_labelObj_removeStyle(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_labelObj_getTextString(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  labelObj *arg1 = (labelObj *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  char *result = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:labelObj_getTextString",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_labelObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelObj_getTextString" "', argument " "1"" of type '" "labelObj *""'"); 
+  }
+  arg1 = (labelObj *)(argp1);
+  {
+    result = (char *)labelObj_getTextString(arg1); {
+      errorObj *ms_error = msGetErrorObj();
+      
+      switch(ms_error->code) {
+      case MS_NOERR:
+        break;
+      case MS_NOTFOUND:
+        msResetErrorList();
+        break;
+      case -1:
+        break;
+      case MS_IOERR:
+        if (strcmp(ms_error->routine, "msSearchDiskTree()") != 0) {
+          _raise_ms_exception();
+          msResetErrorList();
+          return NULL;
+        }
+      default:
+        _raise_ms_exception();
+        msResetErrorList();
+        return NULL;
+      }
+      
+    }
+  }
+  resultobj = SWIG_FromCharPtr((const char *)result);
+  free((char*)result);
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_labelObj_getStyle(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   labelObj *arg1 = (labelObj *) 0 ;
   int arg2 ;
@@ -14054,19 +14938,19 @@ SWIGINTERN PyObject *_wrap_labelObj_removeStyle(PyObject *SWIGUNUSEDPARM(self),
   PyObject * obj1 = 0 ;
   styleObj *result = 0 ;
   
-  if (!PyArg_ParseTuple(args,(char *)"OO:labelObj_removeStyle",&obj0,&obj1)) SWIG_fail;
+  if (!PyArg_ParseTuple(args,(char *)"OO:labelObj_getStyle",&obj0,&obj1)) SWIG_fail;
   res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_labelObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelObj_removeStyle" "', argument " "1"" of type '" "labelObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelObj_getStyle" "', argument " "1"" of type '" "labelObj *""'"); 
   }
   arg1 = (labelObj *)(argp1);
   ecode2 = SWIG_AsVal_int(obj1, &val2);
   if (!SWIG_IsOK(ecode2)) {
-    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "labelObj_removeStyle" "', argument " "2"" of type '" "int""'");
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "labelObj_getStyle" "', argument " "2"" of type '" "int""'");
   } 
   arg2 = (int)(val2);
   {
-    result = (styleObj *)labelObj_removeStyle(arg1,arg2); {
+    result = (styleObj *)labelObj_getStyle(arg1,arg2); {
       errorObj *ms_error = msGetErrorObj();
       
       switch(ms_error->code) {
@@ -14098,31 +14982,42 @@ fail:
 }
 
 
-SWIGINTERN PyObject *_wrap_labelObj_moveStyleUp(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_labelObj_insertStyle(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   labelObj *arg1 = (labelObj *) 0 ;
-  int arg2 ;
+  styleObj *arg2 = (styleObj *) 0 ;
+  int arg3 = (int) -1 ;
   void *argp1 = 0 ;
   int res1 = 0 ;
-  int val2 ;
-  int ecode2 = 0 ;
+  void *argp2 = 0 ;
+  int res2 = 0 ;
+  int val3 ;
+  int ecode3 = 0 ;
   PyObject * obj0 = 0 ;
   PyObject * obj1 = 0 ;
+  PyObject * obj2 = 0 ;
   int result;
   
-  if (!PyArg_ParseTuple(args,(char *)"OO:labelObj_moveStyleUp",&obj0,&obj1)) SWIG_fail;
+  if (!PyArg_ParseTuple(args,(char *)"OO|O:labelObj_insertStyle",&obj0,&obj1,&obj2)) SWIG_fail;
   res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_labelObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelObj_moveStyleUp" "', argument " "1"" of type '" "labelObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelObj_insertStyle" "', argument " "1"" of type '" "labelObj *""'"); 
   }
   arg1 = (labelObj *)(argp1);
-  ecode2 = SWIG_AsVal_int(obj1, &val2);
-  if (!SWIG_IsOK(ecode2)) {
-    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "labelObj_moveStyleUp" "', argument " "2"" of type '" "int""'");
-  } 
-  arg2 = (int)(val2);
+  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_styleObj, 0 |  0 );
+  if (!SWIG_IsOK(res2)) {
+    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "labelObj_insertStyle" "', argument " "2"" of type '" "styleObj *""'"); 
+  }
+  arg2 = (styleObj *)(argp2);
+  if (obj2) {
+    ecode3 = SWIG_AsVal_int(obj2, &val3);
+    if (!SWIG_IsOK(ecode3)) {
+      SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "labelObj_insertStyle" "', argument " "3"" of type '" "int""'");
+    } 
+    arg3 = (int)(val3);
+  }
   {
-    result = (int)labelObj_moveStyleUp(arg1,arg2); {
+    result = (int)labelObj_insertStyle(arg1,arg2,arg3); {
       errorObj *ms_error = msGetErrorObj();
       
       switch(ms_error->code) {
@@ -14154,7 +15049,7 @@ fail:
 }
 
 
-SWIGINTERN PyObject *_wrap_labelObj_moveStyleDown(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_labelObj_removeStyle(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   labelObj *arg1 = (labelObj *) 0 ;
   int arg2 ;
@@ -14164,21 +15059,21 @@ SWIGINTERN PyObject *_wrap_labelObj_moveStyleDown(PyObject *SWIGUNUSEDPARM(self)
   int ecode2 = 0 ;
   PyObject * obj0 = 0 ;
   PyObject * obj1 = 0 ;
-  int result;
+  styleObj *result = 0 ;
   
-  if (!PyArg_ParseTuple(args,(char *)"OO:labelObj_moveStyleDown",&obj0,&obj1)) SWIG_fail;
+  if (!PyArg_ParseTuple(args,(char *)"OO:labelObj_removeStyle",&obj0,&obj1)) SWIG_fail;
   res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_labelObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelObj_moveStyleDown" "', argument " "1"" of type '" "labelObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelObj_removeStyle" "', argument " "1"" of type '" "labelObj *""'"); 
   }
   arg1 = (labelObj *)(argp1);
   ecode2 = SWIG_AsVal_int(obj1, &val2);
   if (!SWIG_IsOK(ecode2)) {
-    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "labelObj_moveStyleDown" "', argument " "2"" of type '" "int""'");
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "labelObj_removeStyle" "', argument " "2"" of type '" "int""'");
   } 
   arg2 = (int)(val2);
   {
-    result = (int)labelObj_moveStyleDown(arg1,arg2); {
+    result = (styleObj *)labelObj_removeStyle(arg1,arg2); {
       errorObj *ms_error = msGetErrorObj();
       
       switch(ms_error->code) {
@@ -14203,20 +15098,38 @@ SWIGINTERN PyObject *_wrap_labelObj_moveStyleDown(PyObject *SWIGUNUSEDPARM(self)
       
     }
   }
-  resultobj = SWIG_From_int((int)(result));
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_styleObj, SWIG_POINTER_OWN |  0 );
   return resultobj;
 fail:
   return NULL;
 }
 
 
-SWIGINTERN PyObject *_wrap_new_labelObj(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_labelObj_moveStyleUp(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
-  labelObj *result = 0 ;
+  labelObj *arg1 = (labelObj *) 0 ;
+  int arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val2 ;
+  int ecode2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  int result;
   
-  if (!PyArg_ParseTuple(args,(char *)":new_labelObj")) SWIG_fail;
+  if (!PyArg_ParseTuple(args,(char *)"OO:labelObj_moveStyleUp",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_labelObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelObj_moveStyleUp" "', argument " "1"" of type '" "labelObj *""'"); 
+  }
+  arg1 = (labelObj *)(argp1);
+  ecode2 = SWIG_AsVal_int(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "labelObj_moveStyleUp" "', argument " "2"" of type '" "int""'");
+  } 
+  arg2 = (int)(val2);
   {
-    result = (labelObj *)calloc(1, sizeof(labelObj)); {
+    result = (int)labelObj_moveStyleUp(arg1,arg2); {
       errorObj *ms_error = msGetErrorObj();
       
       switch(ms_error->code) {
@@ -14241,28 +15154,38 @@ SWIGINTERN PyObject *_wrap_new_labelObj(PyObject *SWIGUNUSEDPARM(self), PyObject
       
     }
   }
-  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_labelObj, SWIG_POINTER_NEW |  0 );
+  resultobj = SWIG_From_int((int)(result));
   return resultobj;
 fail:
   return NULL;
 }
 
 
-SWIGINTERN PyObject *_wrap_delete_labelObj(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_labelObj_moveStyleDown(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   labelObj *arg1 = (labelObj *) 0 ;
+  int arg2 ;
   void *argp1 = 0 ;
   int res1 = 0 ;
+  int val2 ;
+  int ecode2 = 0 ;
   PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  int result;
   
-  if (!PyArg_ParseTuple(args,(char *)"O:delete_labelObj",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_labelObj, SWIG_POINTER_DISOWN |  0 );
+  if (!PyArg_ParseTuple(args,(char *)"OO:labelObj_moveStyleDown",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_labelObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_labelObj" "', argument " "1"" of type '" "labelObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelObj_moveStyleDown" "', argument " "1"" of type '" "labelObj *""'"); 
   }
   arg1 = (labelObj *)(argp1);
+  ecode2 = SWIG_AsVal_int(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "labelObj_moveStyleDown" "', argument " "2"" of type '" "int""'");
+  } 
+  arg2 = (int)(val2);
   {
-    free((char *) arg1); {
+    result = (int)labelObj_moveStyleDown(arg1,arg2); {
       errorObj *ms_error = msGetErrorObj();
       
       switch(ms_error->code) {
@@ -14287,7 +15210,7 @@ SWIGINTERN PyObject *_wrap_delete_labelObj(PyObject *SWIGUNUSEDPARM(self), PyObj
       
     }
   }
-  resultobj = SWIG_Py_Void();
+  resultobj = SWIG_From_int((int)(result));
   return resultobj;
 fail:
   return NULL;
@@ -14313,7 +15236,7 @@ SWIGINTERN PyObject *_wrap_classObj_status_set(PyObject *SWIGUNUSEDPARM(self), P
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:classObj_status_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_status_set" "', argument " "1"" of type '" "classObj *""'"); 
   }
@@ -14340,7 +15263,7 @@ SWIGINTERN PyObject *_wrap_classObj_status_get(PyObject *SWIGUNUSEDPARM(self), P
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:classObj_status_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_status_get" "', argument " "1"" of type '" "classObj *""'"); 
   }
@@ -14353,74 +15276,74 @@ fail:
 }
 
 
-SWIGINTERN PyObject *_wrap_classObj_numstyles_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_classObj_numstyles_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   classObj *arg1 = (classObj *) 0 ;
-  int arg2 ;
   void *argp1 = 0 ;
   int res1 = 0 ;
-  int val2 ;
-  int ecode2 = 0 ;
   PyObject * obj0 = 0 ;
-  PyObject * obj1 = 0 ;
+  int result;
   
-  if (!PyArg_ParseTuple(args,(char *)"OO:classObj_numstyles_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+  if (!PyArg_ParseTuple(args,(char *)"O:classObj_numstyles_get",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_numstyles_set" "', argument " "1"" of type '" "classObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_numstyles_get" "', argument " "1"" of type '" "classObj *""'"); 
   }
   arg1 = (classObj *)(argp1);
-  ecode2 = SWIG_AsVal_int(obj1, &val2);
-  if (!SWIG_IsOK(ecode2)) {
-    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "classObj_numstyles_set" "', argument " "2"" of type '" "int""'");
-  } 
-  arg2 = (int)(val2);
-  if (arg1) (arg1)->numstyles = arg2;
-  resultobj = SWIG_Py_Void();
+  result = (int) ((arg1)->numstyles);
+  resultobj = SWIG_From_int((int)(result));
   return resultobj;
 fail:
   return NULL;
 }
 
 
-SWIGINTERN PyObject *_wrap_classObj_numstyles_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_classObj_numlabels_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   classObj *arg1 = (classObj *) 0 ;
+  int arg2 ;
   void *argp1 = 0 ;
   int res1 = 0 ;
+  int val2 ;
+  int ecode2 = 0 ;
   PyObject * obj0 = 0 ;
-  int result;
+  PyObject * obj1 = 0 ;
   
-  if (!PyArg_ParseTuple(args,(char *)"O:classObj_numstyles_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+  if (!PyArg_ParseTuple(args,(char *)"OO:classObj_numlabels_set",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_numstyles_get" "', argument " "1"" of type '" "classObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_numlabels_set" "', argument " "1"" of type '" "classObj *""'"); 
   }
   arg1 = (classObj *)(argp1);
-  result = (int) ((arg1)->numstyles);
-  resultobj = SWIG_From_int((int)(result));
+  ecode2 = SWIG_AsVal_int(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "classObj_numlabels_set" "', argument " "2"" of type '" "int""'");
+  } 
+  arg2 = (int)(val2);
+  if (arg1) (arg1)->numlabels = arg2;
+  resultobj = SWIG_Py_Void();
   return resultobj;
 fail:
   return NULL;
 }
 
 
-SWIGINTERN PyObject *_wrap_classObj_label_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_classObj_numlabels_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   classObj *arg1 = (classObj *) 0 ;
   void *argp1 = 0 ;
   int res1 = 0 ;
   PyObject * obj0 = 0 ;
-  labelObj *result = 0 ;
+  int result;
   
-  if (!PyArg_ParseTuple(args,(char *)"O:classObj_label_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+  if (!PyArg_ParseTuple(args,(char *)"O:classObj_numlabels_get",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_label_get" "', argument " "1"" of type '" "classObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_numlabels_get" "', argument " "1"" of type '" "classObj *""'"); 
   }
   arg1 = (classObj *)(argp1);
-  result = (labelObj *)& ((arg1)->label);
-  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_labelObj, 0 |  0 );
+  result = (int) ((arg1)->numlabels);
+  resultobj = SWIG_From_int((int)(result));
   return resultobj;
 fail:
   return NULL;
@@ -14436,7 +15359,7 @@ SWIGINTERN PyObject *_wrap_classObj_name_set(PyObject *SWIGUNUSEDPARM(self), PyO
   PyObject * obj0 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:classObj_name_set",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_name_set" "', argument " "1"" of type '" "classObj *""'"); 
   }
@@ -14466,7 +15389,7 @@ SWIGINTERN PyObject *_wrap_classObj_name_get(PyObject *SWIGUNUSEDPARM(self), PyO
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:classObj_name_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_name_get" "', argument " "1"" of type '" "classObj *""'"); 
   }
@@ -14488,7 +15411,7 @@ SWIGINTERN PyObject *_wrap_classObj_title_set(PyObject *SWIGUNUSEDPARM(self), Py
   PyObject * obj0 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:classObj_title_set",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_title_set" "', argument " "1"" of type '" "classObj *""'"); 
   }
@@ -14518,7 +15441,7 @@ SWIGINTERN PyObject *_wrap_classObj_title_get(PyObject *SWIGUNUSEDPARM(self), Py
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:classObj_title_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_title_get" "', argument " "1"" of type '" "classObj *""'"); 
   }
@@ -14540,7 +15463,7 @@ SWIGINTERN PyObject *_wrap_classObj_template_set(PyObject *SWIGUNUSEDPARM(self),
   PyObject * obj0 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:classObj_template_set",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_template_set" "', argument " "1"" of type '" "classObj *""'"); 
   }
@@ -14570,7 +15493,7 @@ SWIGINTERN PyObject *_wrap_classObj_template_get(PyObject *SWIGUNUSEDPARM(self),
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:classObj_template_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_template_get" "', argument " "1"" of type '" "classObj *""'"); 
   }
@@ -14595,7 +15518,7 @@ SWIGINTERN PyObject *_wrap_classObj_type_set(PyObject *SWIGUNUSEDPARM(self), PyO
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:classObj_type_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_type_set" "', argument " "1"" of type '" "classObj *""'"); 
   }
@@ -14622,7 +15545,7 @@ SWIGINTERN PyObject *_wrap_classObj_type_get(PyObject *SWIGUNUSEDPARM(self), PyO
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:classObj_type_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_type_get" "', argument " "1"" of type '" "classObj *""'"); 
   }
@@ -14644,7 +15567,7 @@ SWIGINTERN PyObject *_wrap_classObj_metadata_get(PyObject *SWIGUNUSEDPARM(self),
   hashTableObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:classObj_metadata_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_metadata_get" "', argument " "1"" of type '" "classObj *""'"); 
   }
@@ -14666,7 +15589,7 @@ SWIGINTERN PyObject *_wrap_classObj_validation_get(PyObject *SWIGUNUSEDPARM(self
   hashTableObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:classObj_validation_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_validation_get" "', argument " "1"" of type '" "classObj *""'"); 
   }
@@ -14691,7 +15614,7 @@ SWIGINTERN PyObject *_wrap_classObj_minscaledenom_set(PyObject *SWIGUNUSEDPARM(s
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:classObj_minscaledenom_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_minscaledenom_set" "', argument " "1"" of type '" "classObj *""'"); 
   }
@@ -14718,7 +15641,7 @@ SWIGINTERN PyObject *_wrap_classObj_minscaledenom_get(PyObject *SWIGUNUSEDPARM(s
   double result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:classObj_minscaledenom_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_minscaledenom_get" "', argument " "1"" of type '" "classObj *""'"); 
   }
@@ -14743,7 +15666,7 @@ SWIGINTERN PyObject *_wrap_classObj_maxscaledenom_set(PyObject *SWIGUNUSEDPARM(s
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:classObj_maxscaledenom_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_maxscaledenom_set" "', argument " "1"" of type '" "classObj *""'"); 
   }
@@ -14770,7 +15693,7 @@ SWIGINTERN PyObject *_wrap_classObj_maxscaledenom_get(PyObject *SWIGUNUSEDPARM(s
   double result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:classObj_maxscaledenom_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_maxscaledenom_get" "', argument " "1"" of type '" "classObj *""'"); 
   }
@@ -14795,7 +15718,7 @@ SWIGINTERN PyObject *_wrap_classObj_minfeaturesize_set(PyObject *SWIGUNUSEDPARM(
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:classObj_minfeaturesize_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_minfeaturesize_set" "', argument " "1"" of type '" "classObj *""'"); 
   }
@@ -14822,7 +15745,7 @@ SWIGINTERN PyObject *_wrap_classObj_minfeaturesize_get(PyObject *SWIGUNUSEDPARM(
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:classObj_minfeaturesize_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_minfeaturesize_get" "', argument " "1"" of type '" "classObj *""'"); 
   }
@@ -14844,7 +15767,7 @@ SWIGINTERN PyObject *_wrap_classObj_refcount_get(PyObject *SWIGUNUSEDPARM(self),
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:classObj_refcount_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_refcount_get" "', argument " "1"" of type '" "classObj *""'"); 
   }
@@ -14863,16 +15786,16 @@ SWIGINTERN PyObject *_wrap_classObj_layer_get(PyObject *SWIGUNUSEDPARM(self), Py
   void *argp1 = 0 ;
   int res1 = 0 ;
   PyObject * obj0 = 0 ;
-  struct layer_obj *result = 0 ;
+  struct layerObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:classObj_layer_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_layer_get" "', argument " "1"" of type '" "classObj *""'"); 
   }
   arg1 = (classObj *)(argp1);
-  result = (struct layer_obj *) ((arg1)->layer);
-  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_layer_obj, 0 |  0 );
+  result = (struct layerObj *) ((arg1)->layer);
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_layerObj, 0 |  0 );
   return resultobj;
 fail:
   return NULL;
@@ -14891,7 +15814,7 @@ SWIGINTERN PyObject *_wrap_classObj_debug_set(PyObject *SWIGUNUSEDPARM(self), Py
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:classObj_debug_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_debug_set" "', argument " "1"" of type '" "classObj *""'"); 
   }
@@ -14918,7 +15841,7 @@ SWIGINTERN PyObject *_wrap_classObj_debug_get(PyObject *SWIGUNUSEDPARM(self), Py
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:classObj_debug_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_debug_get" "', argument " "1"" of type '" "classObj *""'"); 
   }
@@ -14940,7 +15863,7 @@ SWIGINTERN PyObject *_wrap_classObj_keyimage_set(PyObject *SWIGUNUSEDPARM(self),
   PyObject * obj0 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:classObj_keyimage_set",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_keyimage_set" "', argument " "1"" of type '" "classObj *""'"); 
   }
@@ -14970,7 +15893,7 @@ SWIGINTERN PyObject *_wrap_classObj_keyimage_get(PyObject *SWIGUNUSEDPARM(self),
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:classObj_keyimage_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_keyimage_get" "', argument " "1"" of type '" "classObj *""'"); 
   }
@@ -14992,7 +15915,7 @@ SWIGINTERN PyObject *_wrap_classObj_group_set(PyObject *SWIGUNUSEDPARM(self), Py
   PyObject * obj0 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:classObj_group_set",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_group_set" "', argument " "1"" of type '" "classObj *""'"); 
   }
@@ -15022,7 +15945,7 @@ SWIGINTERN PyObject *_wrap_classObj_group_get(PyObject *SWIGUNUSEDPARM(self), Py
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:classObj_group_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_group_get" "', argument " "1"" of type '" "classObj *""'"); 
   }
@@ -15035,6 +15958,58 @@ fail:
 }
 
 
+SWIGINTERN PyObject *_wrap_classObj_leader_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  classObj *arg1 = (classObj *) 0 ;
+  labelLeaderObj *arg2 = (labelLeaderObj *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  void *argp2 = 0 ;
+  int res2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:classObj_leader_set",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_leader_set" "', argument " "1"" of type '" "classObj *""'"); 
+  }
+  arg1 = (classObj *)(argp1);
+  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_labelLeaderObj, 0 |  0 );
+  if (!SWIG_IsOK(res2)) {
+    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "classObj_leader_set" "', argument " "2"" of type '" "labelLeaderObj *""'"); 
+  }
+  arg2 = (labelLeaderObj *)(argp2);
+  if (arg1) (arg1)->leader = *arg2;
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_classObj_leader_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  classObj *arg1 = (classObj *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  labelLeaderObj *result = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:classObj_leader_get",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_leader_get" "', argument " "1"" of type '" "classObj *""'"); 
+  }
+  arg1 = (classObj *)(argp1);
+  result = (labelLeaderObj *)& ((arg1)->leader);
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_labelLeaderObj, 0 |  0 );
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
 SWIGINTERN PyObject *_wrap_new_classObj(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   layerObj *arg1 = (layerObj *) NULL ;
@@ -15045,7 +16020,7 @@ SWIGINTERN PyObject *_wrap_new_classObj(PyObject *SWIGUNUSEDPARM(self), PyObject
   
   if (!PyArg_ParseTuple(args,(char *)"|O:new_classObj",&obj0)) SWIG_fail;
   if (obj0) {
-    res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "new_classObj" "', argument " "1"" of type '" "layerObj *""'"); 
     }
@@ -15077,7 +16052,7 @@ SWIGINTERN PyObject *_wrap_new_classObj(PyObject *SWIGUNUSEDPARM(self), PyObject
       
     }
   }
-  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_class_obj, SWIG_POINTER_NEW |  0 );
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_classObj, SWIG_POINTER_NEW |  0 );
   return resultobj;
 fail:
   return NULL;
@@ -15092,7 +16067,7 @@ SWIGINTERN PyObject *_wrap_delete_classObj(PyObject *SWIGUNUSEDPARM(self), PyObj
   PyObject * obj0 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:delete_classObj",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_class_obj, SWIG_POINTER_DISOWN |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, SWIG_POINTER_DISOWN |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_classObj" "', argument " "1"" of type '" "classObj *""'"); 
   }
@@ -15140,7 +16115,7 @@ SWIGINTERN PyObject *_wrap_classObj_updateFromString(PyObject *SWIGUNUSEDPARM(se
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:classObj_updateFromString",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_updateFromString" "', argument " "1"" of type '" "classObj *""'"); 
   }
@@ -15187,7 +16162,7 @@ SWIGINTERN PyObject *_wrap_classObj_clone(PyObject *SWIGUNUSEDPARM(self), PyObje
   classObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:classObj_clone",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_clone" "', argument " "1"" of type '" "classObj *""'"); 
   }
@@ -15218,7 +16193,7 @@ SWIGINTERN PyObject *_wrap_classObj_clone(PyObject *SWIGUNUSEDPARM(self), PyObje
       
     }
   }
-  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_class_obj, SWIG_POINTER_OWN |  0 );
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_classObj, SWIG_POINTER_OWN |  0 );
   return resultobj;
 fail:
   return NULL;
@@ -15235,7 +16210,7 @@ SWIGINTERN PyObject *_wrap_classObj_setExpression(PyObject *SWIGUNUSEDPARM(self)
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:classObj_setExpression",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_setExpression" "', argument " "1"" of type '" "classObj *""'"); 
   }
@@ -15282,7 +16257,7 @@ SWIGINTERN PyObject *_wrap_classObj_getExpressionString(PyObject *SWIGUNUSEDPARM
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:classObj_getExpressionString",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_getExpressionString" "', argument " "1"" of type '" "classObj *""'"); 
   }
@@ -15331,7 +16306,7 @@ SWIGINTERN PyObject *_wrap_classObj_setText(PyObject *SWIGUNUSEDPARM(self), PyOb
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:classObj_setText",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_setText" "', argument " "1"" of type '" "classObj *""'"); 
   }
@@ -15378,7 +16353,7 @@ SWIGINTERN PyObject *_wrap_classObj_getTextString(PyObject *SWIGUNUSEDPARM(self)
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:classObj_getTextString",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_getTextString" "', argument " "1"" of type '" "classObj *""'"); 
   }
@@ -15427,7 +16402,7 @@ SWIGINTERN PyObject *_wrap_classObj_getMetaData(PyObject *SWIGUNUSEDPARM(self),
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:classObj_getMetaData",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_getMetaData" "', argument " "1"" of type '" "classObj *""'"); 
   }
@@ -15476,7 +16451,7 @@ SWIGINTERN PyObject *_wrap_classObj_setMetaData(PyObject *SWIGUNUSEDPARM(self),
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"Ozz:classObj_setMetaData",&obj0,&arg2,&arg3)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_setMetaData" "', argument " "1"" of type '" "classObj *""'"); 
   }
@@ -15523,7 +16498,7 @@ SWIGINTERN PyObject *_wrap_classObj_getFirstMetaDataKey(PyObject *SWIGUNUSEDPARM
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:classObj_getFirstMetaDataKey",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_getFirstMetaDataKey" "', argument " "1"" of type '" "classObj *""'"); 
   }
@@ -15571,7 +16546,7 @@ SWIGINTERN PyObject *_wrap_classObj_getNextMetaDataKey(PyObject *SWIGUNUSEDPARM(
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:classObj_getNextMetaDataKey",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_getNextMetaDataKey" "', argument " "1"" of type '" "classObj *""'"); 
   }
@@ -15646,17 +16621,17 @@ SWIGINTERN PyObject *_wrap_classObj_drawLegendIcon(PyObject *SWIGUNUSEDPARM(self
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"OOOOOOOO:classObj_drawLegendIcon",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_drawLegendIcon" "', argument " "1"" of type '" "classObj *""'"); 
   }
   arg1 = (classObj *)(argp1);
-  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_map_obj, 0 |  0 );
+  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res2)) {
     SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "classObj_drawLegendIcon" "', argument " "2"" of type '" "mapObj *""'"); 
   }
   arg2 = (mapObj *)(argp2);
-  res3 = SWIG_ConvertPtr(obj2, &argp3,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res3 = SWIG_ConvertPtr(obj2, &argp3,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res3)) {
     SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "classObj_drawLegendIcon" "', argument " "3"" of type '" "layerObj *""'"); 
   }
@@ -15744,17 +16719,17 @@ SWIGINTERN PyObject *_wrap_classObj_createLegendIcon(PyObject *SWIGUNUSEDPARM(se
   imageObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OOOOO:classObj_createLegendIcon",&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_createLegendIcon" "', argument " "1"" of type '" "classObj *""'"); 
   }
   arg1 = (classObj *)(argp1);
-  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_map_obj, 0 |  0 );
+  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res2)) {
     SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "classObj_createLegendIcon" "', argument " "2"" of type '" "mapObj *""'"); 
   }
   arg2 = (mapObj *)(argp2);
-  res3 = SWIG_ConvertPtr(obj2, &argp3,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res3 = SWIG_ConvertPtr(obj2, &argp3,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res3)) {
     SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "classObj_createLegendIcon" "', argument " "3"" of type '" "layerObj *""'"); 
   }
@@ -15802,6 +16777,174 @@ fail:
 }
 
 
+SWIGINTERN PyObject *_wrap_classObj_getLabel(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  classObj *arg1 = (classObj *) 0 ;
+  int arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val2 ;
+  int ecode2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  labelObj *result = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:classObj_getLabel",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_getLabel" "', argument " "1"" of type '" "classObj *""'"); 
+  }
+  arg1 = (classObj *)(argp1);
+  ecode2 = SWIG_AsVal_int(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "classObj_getLabel" "', argument " "2"" of type '" "int""'");
+  } 
+  arg2 = (int)(val2);
+  {
+    result = (labelObj *)classObj_getLabel(arg1,arg2); {
+      errorObj *ms_error = msGetErrorObj();
+      
+      switch(ms_error->code) {
+      case MS_NOERR:
+        break;
+      case MS_NOTFOUND:
+        msResetErrorList();
+        break;
+      case -1:
+        break;
+      case MS_IOERR:
+        if (strcmp(ms_error->routine, "msSearchDiskTree()") != 0) {
+          _raise_ms_exception();
+          msResetErrorList();
+          return NULL;
+        }
+      default:
+        _raise_ms_exception();
+        msResetErrorList();
+        return NULL;
+      }
+      
+    }
+  }
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_labelObj, SWIG_POINTER_OWN |  0 );
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_classObj_addLabel(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  classObj *arg1 = (classObj *) 0 ;
+  labelObj *arg2 = (labelObj *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  void *argp2 = 0 ;
+  int res2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  int result;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:classObj_addLabel",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_addLabel" "', argument " "1"" of type '" "classObj *""'"); 
+  }
+  arg1 = (classObj *)(argp1);
+  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_labelObj, 0 |  0 );
+  if (!SWIG_IsOK(res2)) {
+    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "classObj_addLabel" "', argument " "2"" of type '" "labelObj *""'"); 
+  }
+  arg2 = (labelObj *)(argp2);
+  {
+    result = (int)classObj_addLabel(arg1,arg2); {
+      errorObj *ms_error = msGetErrorObj();
+      
+      switch(ms_error->code) {
+      case MS_NOERR:
+        break;
+      case MS_NOTFOUND:
+        msResetErrorList();
+        break;
+      case -1:
+        break;
+      case MS_IOERR:
+        if (strcmp(ms_error->routine, "msSearchDiskTree()") != 0) {
+          _raise_ms_exception();
+          msResetErrorList();
+          return NULL;
+        }
+      default:
+        _raise_ms_exception();
+        msResetErrorList();
+        return NULL;
+      }
+      
+    }
+  }
+  resultobj = SWIG_From_int((int)(result));
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_classObj_removeLabel(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  classObj *arg1 = (classObj *) 0 ;
+  int arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val2 ;
+  int ecode2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  labelObj *result = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:classObj_removeLabel",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_removeLabel" "', argument " "1"" of type '" "classObj *""'"); 
+  }
+  arg1 = (classObj *)(argp1);
+  ecode2 = SWIG_AsVal_int(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "classObj_removeLabel" "', argument " "2"" of type '" "int""'");
+  } 
+  arg2 = (int)(val2);
+  {
+    result = (labelObj *)classObj_removeLabel(arg1,arg2); {
+      errorObj *ms_error = msGetErrorObj();
+      
+      switch(ms_error->code) {
+      case MS_NOERR:
+        break;
+      case MS_NOTFOUND:
+        msResetErrorList();
+        break;
+      case -1:
+        break;
+      case MS_IOERR:
+        if (strcmp(ms_error->routine, "msSearchDiskTree()") != 0) {
+          _raise_ms_exception();
+          msResetErrorList();
+          return NULL;
+        }
+      default:
+        _raise_ms_exception();
+        msResetErrorList();
+        return NULL;
+      }
+      
+    }
+  }
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_labelObj, SWIG_POINTER_OWN |  0 );
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
 SWIGINTERN PyObject *_wrap_classObj_getStyle(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   classObj *arg1 = (classObj *) 0 ;
@@ -15815,7 +16958,7 @@ SWIGINTERN PyObject *_wrap_classObj_getStyle(PyObject *SWIGUNUSEDPARM(self), PyO
   styleObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:classObj_getStyle",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_getStyle" "', argument " "1"" of type '" "classObj *""'"); 
   }
@@ -15875,7 +17018,7 @@ SWIGINTERN PyObject *_wrap_classObj_insertStyle(PyObject *SWIGUNUSEDPARM(self),
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"OO|O:classObj_insertStyle",&obj0,&obj1,&obj2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_insertStyle" "', argument " "1"" of type '" "classObj *""'"); 
   }
@@ -15938,7 +17081,7 @@ SWIGINTERN PyObject *_wrap_classObj_removeStyle(PyObject *SWIGUNUSEDPARM(self),
   styleObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:classObj_removeStyle",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_removeStyle" "', argument " "1"" of type '" "classObj *""'"); 
   }
@@ -15994,7 +17137,7 @@ SWIGINTERN PyObject *_wrap_classObj_moveStyleUp(PyObject *SWIGUNUSEDPARM(self),
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:classObj_moveStyleUp",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_moveStyleUp" "', argument " "1"" of type '" "classObj *""'"); 
   }
@@ -16050,7 +17193,7 @@ SWIGINTERN PyObject *_wrap_classObj_moveStyleDown(PyObject *SWIGUNUSEDPARM(self)
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:classObj_moveStyleDown",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_class_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_classObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "classObj_moveStyleDown" "', argument " "1"" of type '" "classObj *""'"); 
   }
@@ -16096,32 +17239,10 @@ fail:
 SWIGINTERN PyObject *classObj_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *obj;
   if (!PyArg_ParseTuple(args,(char*)"O:swigregister", &obj)) return NULL;
-  SWIG_TypeNewClientData(SWIGTYPE_p_class_obj, SWIG_NewClientData(obj));
+  SWIG_TypeNewClientData(SWIGTYPE_p_classObj, SWIG_NewClientData(obj));
   return SWIG_Py_Void();
 }
 
-SWIGINTERN PyObject *_wrap_labelCacheMemberObj_text_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
-  PyObject *resultobj = 0;
-  labelCacheMemberObj *arg1 = (labelCacheMemberObj *) 0 ;
-  void *argp1 = 0 ;
-  int res1 = 0 ;
-  PyObject * obj0 = 0 ;
-  char *result = 0 ;
-  
-  if (!PyArg_ParseTuple(args,(char *)"O:labelCacheMemberObj_text_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_labelCacheMemberObj, 0 |  0 );
-  if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelCacheMemberObj_text_get" "', argument " "1"" of type '" "labelCacheMemberObj *""'"); 
-  }
-  arg1 = (labelCacheMemberObj *)(argp1);
-  result = (char *) ((arg1)->text);
-  resultobj = SWIG_FromCharPtr((const char *)result);
-  return resultobj;
-fail:
-  return NULL;
-}
-
-
 SWIGINTERN PyObject *_wrap_labelCacheMemberObj_featuresize_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   labelCacheMemberObj *arg1 = (labelCacheMemberObj *) 0 ;
@@ -16188,7 +17309,7 @@ fail:
 }
 
 
-SWIGINTERN PyObject *_wrap_labelCacheMemberObj_label_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_labelCacheMemberObj_labels_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   labelCacheMemberObj *arg1 = (labelCacheMemberObj *) 0 ;
   void *argp1 = 0 ;
@@ -16196,13 +17317,13 @@ SWIGINTERN PyObject *_wrap_labelCacheMemberObj_label_get(PyObject *SWIGUNUSEDPAR
   PyObject * obj0 = 0 ;
   labelObj *result = 0 ;
   
-  if (!PyArg_ParseTuple(args,(char *)"O:labelCacheMemberObj_label_get",&obj0)) SWIG_fail;
+  if (!PyArg_ParseTuple(args,(char *)"O:labelCacheMemberObj_labels_get",&obj0)) SWIG_fail;
   res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_labelCacheMemberObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelCacheMemberObj_label_get" "', argument " "1"" of type '" "labelCacheMemberObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelCacheMemberObj_labels_get" "', argument " "1"" of type '" "labelCacheMemberObj *""'"); 
   }
   arg1 = (labelCacheMemberObj *)(argp1);
-  result = (labelObj *)& ((arg1)->label);
+  result = (labelObj *) ((arg1)->labels);
   resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_labelObj, 0 |  0 );
   return resultobj;
 fail:
@@ -16210,29 +17331,7 @@ fail:
 }
 
 
-SWIGINTERN PyObject *_wrap_labelCacheMemberObj_layerindex_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
-  PyObject *resultobj = 0;
-  labelCacheMemberObj *arg1 = (labelCacheMemberObj *) 0 ;
-  void *argp1 = 0 ;
-  int res1 = 0 ;
-  PyObject * obj0 = 0 ;
-  int result;
-  
-  if (!PyArg_ParseTuple(args,(char *)"O:labelCacheMemberObj_layerindex_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_labelCacheMemberObj, 0 |  0 );
-  if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelCacheMemberObj_layerindex_get" "', argument " "1"" of type '" "labelCacheMemberObj *""'"); 
-  }
-  arg1 = (labelCacheMemberObj *)(argp1);
-  result = (int) ((arg1)->layerindex);
-  resultobj = SWIG_From_int((int)(result));
-  return resultobj;
-fail:
-  return NULL;
-}
-
-
-SWIGINTERN PyObject *_wrap_labelCacheMemberObj_classindex_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_labelCacheMemberObj_numlabels_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   labelCacheMemberObj *arg1 = (labelCacheMemberObj *) 0 ;
   void *argp1 = 0 ;
@@ -16240,13 +17339,13 @@ SWIGINTERN PyObject *_wrap_labelCacheMemberObj_classindex_get(PyObject *SWIGUNUS
   PyObject * obj0 = 0 ;
   int result;
   
-  if (!PyArg_ParseTuple(args,(char *)"O:labelCacheMemberObj_classindex_get",&obj0)) SWIG_fail;
+  if (!PyArg_ParseTuple(args,(char *)"O:labelCacheMemberObj_numlabels_get",&obj0)) SWIG_fail;
   res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_labelCacheMemberObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelCacheMemberObj_classindex_get" "', argument " "1"" of type '" "labelCacheMemberObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelCacheMemberObj_numlabels_get" "', argument " "1"" of type '" "labelCacheMemberObj *""'"); 
   }
   arg1 = (labelCacheMemberObj *)(argp1);
-  result = (int) ((arg1)->classindex);
+  result = (int) ((arg1)->numlabels);
   resultobj = SWIG_From_int((int)(result));
   return resultobj;
 fail:
@@ -16254,7 +17353,7 @@ fail:
 }
 
 
-SWIGINTERN PyObject *_wrap_labelCacheMemberObj_tileindex_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_labelCacheMemberObj_layerindex_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   labelCacheMemberObj *arg1 = (labelCacheMemberObj *) 0 ;
   void *argp1 = 0 ;
@@ -16262,13 +17361,13 @@ SWIGINTERN PyObject *_wrap_labelCacheMemberObj_tileindex_get(PyObject *SWIGUNUSE
   PyObject * obj0 = 0 ;
   int result;
   
-  if (!PyArg_ParseTuple(args,(char *)"O:labelCacheMemberObj_tileindex_get",&obj0)) SWIG_fail;
+  if (!PyArg_ParseTuple(args,(char *)"O:labelCacheMemberObj_layerindex_get",&obj0)) SWIG_fail;
   res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_labelCacheMemberObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelCacheMemberObj_tileindex_get" "', argument " "1"" of type '" "labelCacheMemberObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelCacheMemberObj_layerindex_get" "', argument " "1"" of type '" "labelCacheMemberObj *""'"); 
   }
   arg1 = (labelCacheMemberObj *)(argp1);
-  result = (int) ((arg1)->tileindex);
+  result = (int) ((arg1)->layerindex);
   resultobj = SWIG_From_int((int)(result));
   return resultobj;
 fail:
@@ -16276,7 +17375,7 @@ fail:
 }
 
 
-SWIGINTERN PyObject *_wrap_labelCacheMemberObj_shapeindex_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_labelCacheMemberObj_classindex_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   labelCacheMemberObj *arg1 = (labelCacheMemberObj *) 0 ;
   void *argp1 = 0 ;
@@ -16284,13 +17383,13 @@ SWIGINTERN PyObject *_wrap_labelCacheMemberObj_shapeindex_get(PyObject *SWIGUNUS
   PyObject * obj0 = 0 ;
   int result;
   
-  if (!PyArg_ParseTuple(args,(char *)"O:labelCacheMemberObj_shapeindex_get",&obj0)) SWIG_fail;
+  if (!PyArg_ParseTuple(args,(char *)"O:labelCacheMemberObj_classindex_get",&obj0)) SWIG_fail;
   res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_labelCacheMemberObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelCacheMemberObj_shapeindex_get" "', argument " "1"" of type '" "labelCacheMemberObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelCacheMemberObj_classindex_get" "', argument " "1"" of type '" "labelCacheMemberObj *""'"); 
   }
   arg1 = (labelCacheMemberObj *)(argp1);
-  result = (int) ((arg1)->shapeindex);
+  result = (int) ((arg1)->classindex);
   resultobj = SWIG_From_int((int)(result));
   return resultobj;
 fail:
@@ -16408,6 +17507,50 @@ fail:
 }
 
 
+SWIGINTERN PyObject *_wrap_labelCacheMemberObj_leaderline_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  labelCacheMemberObj *arg1 = (labelCacheMemberObj *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  lineObj *result = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:labelCacheMemberObj_leaderline_get",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_labelCacheMemberObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelCacheMemberObj_leaderline_get" "', argument " "1"" of type '" "labelCacheMemberObj *""'"); 
+  }
+  arg1 = (labelCacheMemberObj *)(argp1);
+  result = (lineObj *) ((arg1)->leaderline);
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_lineObj, 0 |  0 );
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_labelCacheMemberObj_leaderbbox_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  labelCacheMemberObj *arg1 = (labelCacheMemberObj *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  rectObj *result = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:labelCacheMemberObj_leaderbbox_get",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_labelCacheMemberObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelCacheMemberObj_leaderbbox_get" "', argument " "1"" of type '" "labelCacheMemberObj *""'"); 
+  }
+  arg1 = (labelCacheMemberObj *)(argp1);
+  result = (rectObj *) ((arg1)->leaderbbox);
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_rectObj, 0 |  0 );
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
 SWIGINTERN PyObject *_wrap_new_labelCacheMemberObj(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   labelCacheMemberObj *result = 0 ;
@@ -16901,6 +18044,28 @@ fail:
 }
 
 
+SWIGINTERN PyObject *_wrap_labelCacheObj_gutter_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  labelCacheObj *arg1 = (labelCacheObj *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  int result;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:labelCacheObj_gutter_get",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_labelCacheObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelCacheObj_gutter_get" "', argument " "1"" of type '" "labelCacheObj *""'"); 
+  }
+  arg1 = (labelCacheObj *)(argp1);
+  result = (int) ((arg1)->gutter);
+  resultobj = SWIG_From_int((int)(result));
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
 SWIGINTERN PyObject *_wrap_labelCacheObj_freeCache(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   labelCacheObj *arg1 = (labelCacheObj *) 0 ;
@@ -18675,7 +19840,7 @@ SWIGINTERN PyObject *_wrap_referenceMapObj_map_get(PyObject *SWIGUNUSEDPARM(self
   void *argp1 = 0 ;
   int res1 = 0 ;
   PyObject * obj0 = 0 ;
-  struct map_obj *result = 0 ;
+  struct mapObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:referenceMapObj_map_get",&obj0)) SWIG_fail;
   res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_referenceMapObj, 0 |  0 );
@@ -18683,8 +19848,8 @@ SWIGINTERN PyObject *_wrap_referenceMapObj_map_get(PyObject *SWIGUNUSEDPARM(self
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "referenceMapObj_map_get" "', argument " "1"" of type '" "referenceMapObj *""'"); 
   }
   arg1 = (referenceMapObj *)(argp1);
-  result = (struct map_obj *) ((arg1)->map);
-  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_map_obj, 0 |  0 );
+  result = (struct mapObj *) ((arg1)->map);
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_mapObj, 0 |  0 );
   return resultobj;
 fail:
   return NULL;
@@ -20349,7 +21514,7 @@ SWIGINTERN PyObject *_wrap_legendObj_map_get(PyObject *SWIGUNUSEDPARM(self), PyO
   void *argp1 = 0 ;
   int res1 = 0 ;
   PyObject * obj0 = 0 ;
-  struct map_obj *result = 0 ;
+  struct mapObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:legendObj_map_get",&obj0)) SWIG_fail;
   res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_legendObj, 0 |  0 );
@@ -20357,8 +21522,8 @@ SWIGINTERN PyObject *_wrap_legendObj_map_get(PyObject *SWIGUNUSEDPARM(self), PyO
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "legendObj_map_get" "', argument " "1"" of type '" "legendObj *""'"); 
   }
   arg1 = (legendObj *)(argp1);
-  result = (struct map_obj *) ((arg1)->map);
-  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_map_obj, 0 |  0 );
+  result = (struct mapObj *) ((arg1)->map);
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_mapObj, 0 |  0 );
   return resultobj;
 fail:
   return NULL;
@@ -20504,189 +21669,197 @@ SWIGINTERN PyObject *legendObj_swigregister(PyObject *SWIGUNUSEDPARM(self), PyOb
   return SWIG_Py_Void();
 }
 
-SWIGINTERN PyObject *_wrap_layerObj_classitem_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_imageObj_width_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
-  layerObj *arg1 = (layerObj *) 0 ;
-  char *arg2 = (char *) 0 ;
+  imageObj *arg1 = (imageObj *) 0 ;
   void *argp1 = 0 ;
   int res1 = 0 ;
   PyObject * obj0 = 0 ;
+  int result;
   
-  if (!PyArg_ParseTuple(args,(char *)"Oz:layerObj_classitem_set",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  if (!PyArg_ParseTuple(args,(char *)"O:imageObj_width_get",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_imageObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_classitem_set" "', argument " "1"" of type '" "layerObj *""'"); 
-  }
-  arg1 = (layerObj *)(argp1);
-  {
-    if (arg1->classitem) free((char*)arg1->classitem);
-    if (arg2) {
-      arg1->classitem = (char *) malloc(strlen(arg2)+1);
-      strcpy((char*)arg1->classitem,arg2);
-    } else {
-      arg1->classitem = 0;
-    }
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "imageObj_width_get" "', argument " "1"" of type '" "imageObj *""'"); 
   }
-  resultobj = SWIG_Py_Void();
+  arg1 = (imageObj *)(argp1);
+  result = (int) ((arg1)->width);
+  resultobj = SWIG_From_int((int)(result));
   return resultobj;
 fail:
   return NULL;
 }
 
 
-SWIGINTERN PyObject *_wrap_layerObj_classitem_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_imageObj_height_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
-  layerObj *arg1 = (layerObj *) 0 ;
+  imageObj *arg1 = (imageObj *) 0 ;
   void *argp1 = 0 ;
   int res1 = 0 ;
   PyObject * obj0 = 0 ;
-  char *result = 0 ;
+  int result;
   
-  if (!PyArg_ParseTuple(args,(char *)"O:layerObj_classitem_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  if (!PyArg_ParseTuple(args,(char *)"O:imageObj_height_get",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_imageObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_classitem_get" "', argument " "1"" of type '" "layerObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "imageObj_height_get" "', argument " "1"" of type '" "imageObj *""'"); 
   }
-  arg1 = (layerObj *)(argp1);
-  result = (char *) ((arg1)->classitem);
-  resultobj = SWIG_FromCharPtr((const char *)result);
+  arg1 = (imageObj *)(argp1);
+  result = (int) ((arg1)->height);
+  resultobj = SWIG_From_int((int)(result));
   return resultobj;
 fail:
   return NULL;
 }
 
 
-SWIGINTERN PyObject *_wrap_layerObj_refcount_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_imageObj_resolution_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
-  layerObj *arg1 = (layerObj *) 0 ;
+  imageObj *arg1 = (imageObj *) 0 ;
   void *argp1 = 0 ;
   int res1 = 0 ;
   PyObject * obj0 = 0 ;
-  int result;
+  double result;
   
-  if (!PyArg_ParseTuple(args,(char *)"O:layerObj_refcount_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  if (!PyArg_ParseTuple(args,(char *)"O:imageObj_resolution_get",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_imageObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_refcount_get" "', argument " "1"" of type '" "layerObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "imageObj_resolution_get" "', argument " "1"" of type '" "imageObj *""'"); 
   }
-  arg1 = (layerObj *)(argp1);
-  result = (int) ((arg1)->refcount);
-  resultobj = SWIG_From_int((int)(result));
+  arg1 = (imageObj *)(argp1);
+  result = (double) ((arg1)->resolution);
+  resultobj = SWIG_From_double((double)(result));
   return resultobj;
 fail:
   return NULL;
 }
 
 
-SWIGINTERN PyObject *_wrap_layerObj_numclasses_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_imageObj_resolutionfactor_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
-  layerObj *arg1 = (layerObj *) 0 ;
+  imageObj *arg1 = (imageObj *) 0 ;
   void *argp1 = 0 ;
   int res1 = 0 ;
   PyObject * obj0 = 0 ;
-  int result;
+  double result;
   
-  if (!PyArg_ParseTuple(args,(char *)"O:layerObj_numclasses_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  if (!PyArg_ParseTuple(args,(char *)"O:imageObj_resolutionfactor_get",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_imageObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_numclasses_get" "', argument " "1"" of type '" "layerObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "imageObj_resolutionfactor_get" "', argument " "1"" of type '" "imageObj *""'"); 
   }
-  arg1 = (layerObj *)(argp1);
-  result = (int) ((arg1)->numclasses);
-  resultobj = SWIG_From_int((int)(result));
+  arg1 = (imageObj *)(argp1);
+  result = (double) ((arg1)->resolutionfactor);
+  resultobj = SWIG_From_double((double)(result));
   return resultobj;
 fail:
   return NULL;
 }
 
 
-SWIGINTERN PyObject *_wrap_layerObj_maxclasses_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_imageObj_imagepath_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
-  layerObj *arg1 = (layerObj *) 0 ;
+  imageObj *arg1 = (imageObj *) 0 ;
   void *argp1 = 0 ;
   int res1 = 0 ;
   PyObject * obj0 = 0 ;
-  int result;
+  char *result = 0 ;
   
-  if (!PyArg_ParseTuple(args,(char *)"O:layerObj_maxclasses_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  if (!PyArg_ParseTuple(args,(char *)"O:imageObj_imagepath_get",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_imageObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_maxclasses_get" "', argument " "1"" of type '" "layerObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "imageObj_imagepath_get" "', argument " "1"" of type '" "imageObj *""'"); 
   }
-  arg1 = (layerObj *)(argp1);
-  result = (int) ((arg1)->maxclasses);
-  resultobj = SWIG_From_int((int)(result));
+  arg1 = (imageObj *)(argp1);
+  result = (char *) ((arg1)->imagepath);
+  resultobj = SWIG_FromCharPtr((const char *)result);
   return resultobj;
 fail:
   return NULL;
 }
 
 
-SWIGINTERN PyObject *_wrap_layerObj_index_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_imageObj_imageurl_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
-  layerObj *arg1 = (layerObj *) 0 ;
+  imageObj *arg1 = (imageObj *) 0 ;
   void *argp1 = 0 ;
   int res1 = 0 ;
   PyObject * obj0 = 0 ;
-  int result;
+  char *result = 0 ;
   
-  if (!PyArg_ParseTuple(args,(char *)"O:layerObj_index_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  if (!PyArg_ParseTuple(args,(char *)"O:imageObj_imageurl_get",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_imageObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_index_get" "', argument " "1"" of type '" "layerObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "imageObj_imageurl_get" "', argument " "1"" of type '" "imageObj *""'"); 
   }
-  arg1 = (layerObj *)(argp1);
-  result = (int) ((arg1)->index);
-  resultobj = SWIG_From_int((int)(result));
+  arg1 = (imageObj *)(argp1);
+  result = (char *) ((arg1)->imageurl);
+  resultobj = SWIG_FromCharPtr((const char *)result);
   return resultobj;
 fail:
   return NULL;
 }
 
 
-SWIGINTERN PyObject *_wrap_layerObj_map_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_imageObj_format_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
-  layerObj *arg1 = (layerObj *) 0 ;
+  imageObj *arg1 = (imageObj *) 0 ;
   void *argp1 = 0 ;
   int res1 = 0 ;
   PyObject * obj0 = 0 ;
-  struct map_obj *result = 0 ;
+  outputFormatObj *result = 0 ;
   
-  if (!PyArg_ParseTuple(args,(char *)"O:layerObj_map_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  if (!PyArg_ParseTuple(args,(char *)"O:imageObj_format_get",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_imageObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_map_get" "', argument " "1"" of type '" "layerObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "imageObj_format_get" "', argument " "1"" of type '" "imageObj *""'"); 
   }
-  arg1 = (layerObj *)(argp1);
-  result = (struct map_obj *) ((arg1)->map);
-  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_map_obj, 0 |  0 );
+  arg1 = (imageObj *)(argp1);
+  result = (outputFormatObj *) ((arg1)->format);
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_outputFormatObj, 0 |  0 );
   return resultobj;
 fail:
   return NULL;
 }
 
 
-SWIGINTERN PyObject *_wrap_layerObj_header_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_delete_imageObj(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
-  layerObj *arg1 = (layerObj *) 0 ;
-  char *arg2 = (char *) 0 ;
+  imageObj *arg1 = (imageObj *) 0 ;
   void *argp1 = 0 ;
   int res1 = 0 ;
   PyObject * obj0 = 0 ;
   
-  if (!PyArg_ParseTuple(args,(char *)"Oz:layerObj_header_set",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  if (!PyArg_ParseTuple(args,(char *)"O:delete_imageObj",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_imageObj, SWIG_POINTER_DISOWN |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_header_set" "', argument " "1"" of type '" "layerObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_imageObj" "', argument " "1"" of type '" "imageObj *""'"); 
   }
-  arg1 = (layerObj *)(argp1);
+  arg1 = (imageObj *)(argp1);
   {
-    if (arg1->header) free((char*)arg1->header);
-    if (arg2) {
-      arg1->header = (char *) malloc(strlen(arg2)+1);
-      strcpy((char*)arg1->header,arg2);
-    } else {
-      arg1->header = 0;
+    delete_imageObj(arg1); {
+      errorObj *ms_error = msGetErrorObj();
+      
+      switch(ms_error->code) {
+      case MS_NOERR:
+        break;
+      case MS_NOTFOUND:
+        msResetErrorList();
+        break;
+      case -1:
+        break;
+      case MS_IOERR:
+        if (strcmp(ms_error->routine, "msSearchDiskTree()") != 0) {
+          _raise_ms_exception();
+          msResetErrorList();
+          return NULL;
+        }
+      default:
+        _raise_ms_exception();
+        msResetErrorList();
+        return NULL;
+      }
+      
     }
   }
   resultobj = SWIG_Py_Void();
@@ -20696,133 +21869,332 @@ fail:
 }
 
 
-SWIGINTERN PyObject *_wrap_layerObj_header_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_imageObj_save(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
-  layerObj *arg1 = (layerObj *) 0 ;
+  imageObj *arg1 = (imageObj *) 0 ;
+  char *arg2 = (char *) 0 ;
+  mapObj *arg3 = (mapObj *) NULL ;
   void *argp1 = 0 ;
   int res1 = 0 ;
+  void *argp3 = 0 ;
+  int res3 = 0 ;
   PyObject * obj0 = 0 ;
-  char *result = 0 ;
+  PyObject * obj2 = 0 ;
   
-  if (!PyArg_ParseTuple(args,(char *)"O:layerObj_header_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  if (!PyArg_ParseTuple(args,(char *)"Oz|O:imageObj_save",&obj0,&arg2,&obj2)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_imageObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_header_get" "', argument " "1"" of type '" "layerObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "imageObj_save" "', argument " "1"" of type '" "imageObj *""'"); 
   }
-  arg1 = (layerObj *)(argp1);
-  result = (char *) ((arg1)->header);
-  resultobj = SWIG_FromCharPtr((const char *)result);
+  arg1 = (imageObj *)(argp1);
+  if (obj2) {
+    res3 = SWIG_ConvertPtr(obj2, &argp3,SWIGTYPE_p_mapObj, 0 |  0 );
+    if (!SWIG_IsOK(res3)) {
+      SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "imageObj_save" "', argument " "3"" of type '" "mapObj *""'"); 
+    }
+    arg3 = (mapObj *)(argp3);
+  }
+  {
+    imageObj_save(arg1,arg2,arg3); {
+      errorObj *ms_error = msGetErrorObj();
+      
+      switch(ms_error->code) {
+      case MS_NOERR:
+        break;
+      case MS_NOTFOUND:
+        msResetErrorList();
+        break;
+      case -1:
+        break;
+      case MS_IOERR:
+        if (strcmp(ms_error->routine, "msSearchDiskTree()") != 0) {
+          _raise_ms_exception();
+          msResetErrorList();
+          return NULL;
+        }
+      default:
+        _raise_ms_exception();
+        msResetErrorList();
+        return NULL;
+      }
+      
+    }
+  }
+  resultobj = SWIG_Py_Void();
   return resultobj;
 fail:
   return NULL;
 }
 
 
-SWIGINTERN PyObject *_wrap_layerObj_footer_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_imageObj_getBytes(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
-  layerObj *arg1 = (layerObj *) 0 ;
-  char *arg2 = (char *) 0 ;
+  imageObj *arg1 = (imageObj *) 0 ;
   void *argp1 = 0 ;
   int res1 = 0 ;
   PyObject * obj0 = 0 ;
+  gdBuffer result;
   
-  if (!PyArg_ParseTuple(args,(char *)"Oz:layerObj_footer_set",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  if (!PyArg_ParseTuple(args,(char *)"O:imageObj_getBytes",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_imageObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_footer_set" "', argument " "1"" of type '" "layerObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "imageObj_getBytes" "', argument " "1"" of type '" "imageObj *""'"); 
   }
-  arg1 = (layerObj *)(argp1);
+  arg1 = (imageObj *)(argp1);
   {
-    if (arg1->footer) free((char*)arg1->footer);
-    if (arg2) {
-      arg1->footer = (char *) malloc(strlen(arg2)+1);
-      strcpy((char*)arg1->footer,arg2);
-    } else {
-      arg1->footer = 0;
+    result = imageObj_getBytes(arg1); {
+      errorObj *ms_error = msGetErrorObj();
+      
+      switch(ms_error->code) {
+      case MS_NOERR:
+        break;
+      case MS_NOTFOUND:
+        msResetErrorList();
+        break;
+      case -1:
+        break;
+      case MS_IOERR:
+        if (strcmp(ms_error->routine, "msSearchDiskTree()") != 0) {
+          _raise_ms_exception();
+          msResetErrorList();
+          return NULL;
+        }
+      default:
+        _raise_ms_exception();
+        msResetErrorList();
+        return NULL;
+      }
+      
     }
   }
-  resultobj = SWIG_Py_Void();
+  {
+    resultobj = PyString_FromStringAndSize((const char*)(&result)->data, (&result)->size); 
+    if( (&result)->owns_data )
+    msFree((&result)->data);
+  }
   return resultobj;
 fail:
   return NULL;
 }
 
 
-SWIGINTERN PyObject *_wrap_layerObj_footer_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_imageObj_getSize(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
-  layerObj *arg1 = (layerObj *) 0 ;
+  imageObj *arg1 = (imageObj *) 0 ;
   void *argp1 = 0 ;
   int res1 = 0 ;
   PyObject * obj0 = 0 ;
-  char *result = 0 ;
+  int result;
   
-  if (!PyArg_ParseTuple(args,(char *)"O:layerObj_footer_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  if (!PyArg_ParseTuple(args,(char *)"O:imageObj_getSize",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_imageObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_footer_get" "', argument " "1"" of type '" "layerObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "imageObj_getSize" "', argument " "1"" of type '" "imageObj *""'"); 
   }
-  arg1 = (layerObj *)(argp1);
-  result = (char *) ((arg1)->footer);
-  resultobj = SWIG_FromCharPtr((const char *)result);
+  arg1 = (imageObj *)(argp1);
+  {
+    result = (int)imageObj_getSize(arg1); {
+      errorObj *ms_error = msGetErrorObj();
+      
+      switch(ms_error->code) {
+      case MS_NOERR:
+        break;
+      case MS_NOTFOUND:
+        msResetErrorList();
+        break;
+      case -1:
+        break;
+      case MS_IOERR:
+        if (strcmp(ms_error->routine, "msSearchDiskTree()") != 0) {
+          _raise_ms_exception();
+          msResetErrorList();
+          return NULL;
+        }
+      default:
+        _raise_ms_exception();
+        msResetErrorList();
+        return NULL;
+      }
+      
+    }
+  }
+  resultobj = SWIG_From_int((int)(result));
   return resultobj;
 fail:
   return NULL;
 }
 
 
-SWIGINTERN PyObject *_wrap_layerObj_template_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_new_imageObj(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
-  layerObj *arg1 = (layerObj *) 0 ;
-  char *arg2 = (char *) 0 ;
+  PyObject *arg1 = (PyObject *) Py_None ;
+  PyObject *arg2 = (PyObject *) Py_None ;
+  PyObject *arg3 = (PyObject *) Py_None ;
+  PyObject *arg4 = (PyObject *) Py_None ;
+  PyObject *arg5 = (PyObject *) Py_None ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  PyObject * obj2 = 0 ;
+  PyObject * obj3 = 0 ;
+  PyObject * obj4 = 0 ;
+  imageObj *result = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"|OOOOO:new_imageObj",&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail;
+  if (obj0) {
+    arg1 = obj0;
+  }
+  if (obj1) {
+    arg2 = obj1;
+  }
+  if (obj2) {
+    arg3 = obj2;
+  }
+  if (obj3) {
+    arg4 = obj3;
+  }
+  if (obj4) {
+    arg5 = obj4;
+  }
+  {
+    result = (imageObj *)new_imageObj(arg1,arg2,arg3,arg4,arg5); {
+      errorObj *ms_error = msGetErrorObj();
+      
+      switch(ms_error->code) {
+      case MS_NOERR:
+        break;
+      case MS_NOTFOUND:
+        msResetErrorList();
+        break;
+      case -1:
+        break;
+      case MS_IOERR:
+        if (strcmp(ms_error->routine, "msSearchDiskTree()") != 0) {
+          _raise_ms_exception();
+          msResetErrorList();
+          return NULL;
+        }
+      default:
+        _raise_ms_exception();
+        msResetErrorList();
+        return NULL;
+      }
+      
+    }
+  }
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_imageObj, SWIG_POINTER_NEW |  0 );
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_imageObj_write(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  imageObj *arg1 = (imageObj *) 0 ;
+  PyObject *arg2 = (PyObject *) Py_None ;
   void *argp1 = 0 ;
   int res1 = 0 ;
   PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  int result;
   
-  if (!PyArg_ParseTuple(args,(char *)"Oz:layerObj_template_set",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  if (!PyArg_ParseTuple(args,(char *)"O|O:imageObj_write",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_imageObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_template_set" "', argument " "1"" of type '" "layerObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "imageObj_write" "', argument " "1"" of type '" "imageObj *""'"); 
+  }
+  arg1 = (imageObj *)(argp1);
+  if (obj1) {
+    arg2 = obj1;
   }
-  arg1 = (layerObj *)(argp1);
   {
-    if (arg1->template) free((char*)arg1->template);
-    if (arg2) {
-      arg1->template = (char *) malloc(strlen(arg2)+1);
-      strcpy((char*)arg1->template,arg2);
-    } else {
-      arg1->template = 0;
+    result = (int)imageObj_write(arg1,arg2); {
+      errorObj *ms_error = msGetErrorObj();
+      
+      switch(ms_error->code) {
+      case MS_NOERR:
+        break;
+      case MS_NOTFOUND:
+        msResetErrorList();
+        break;
+      case -1:
+        break;
+      case MS_IOERR:
+        if (strcmp(ms_error->routine, "msSearchDiskTree()") != 0) {
+          _raise_ms_exception();
+          msResetErrorList();
+          return NULL;
+        }
+      default:
+        _raise_ms_exception();
+        msResetErrorList();
+        return NULL;
+      }
+      
     }
   }
-  resultobj = SWIG_Py_Void();
+  resultobj = SWIG_From_int((int)(result));
   return resultobj;
 fail:
   return NULL;
 }
 
 
-SWIGINTERN PyObject *_wrap_layerObj_template_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_imageObj_saveToString(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
-  layerObj *arg1 = (layerObj *) 0 ;
+  imageObj *arg1 = (imageObj *) 0 ;
   void *argp1 = 0 ;
   int res1 = 0 ;
   PyObject * obj0 = 0 ;
-  char *result = 0 ;
+  PyObject *result = 0 ;
   
-  if (!PyArg_ParseTuple(args,(char *)"O:layerObj_template_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  if (!PyArg_ParseTuple(args,(char *)"O:imageObj_saveToString",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_imageObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_template_get" "', argument " "1"" of type '" "layerObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "imageObj_saveToString" "', argument " "1"" of type '" "imageObj *""'"); 
   }
-  arg1 = (layerObj *)(argp1);
-  result = (char *) ((arg1)->template);
-  resultobj = SWIG_FromCharPtr((const char *)result);
+  arg1 = (imageObj *)(argp1);
+  {
+    result = (PyObject *)imageObj_saveToString(arg1); {
+      errorObj *ms_error = msGetErrorObj();
+      
+      switch(ms_error->code) {
+      case MS_NOERR:
+        break;
+      case MS_NOTFOUND:
+        msResetErrorList();
+        break;
+      case -1:
+        break;
+      case MS_IOERR:
+        if (strcmp(ms_error->routine, "msSearchDiskTree()") != 0) {
+          _raise_ms_exception();
+          msResetErrorList();
+          return NULL;
+        }
+      default:
+        _raise_ms_exception();
+        msResetErrorList();
+        return NULL;
+      }
+      
+    }
+  }
+  resultobj = result;
   return resultobj;
 fail:
   return NULL;
 }
 
 
-SWIGINTERN PyObject *_wrap_layerObj_name_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *imageObj_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *obj;
+  if (!PyArg_ParseTuple(args,(char*)"O:swigregister", &obj)) return NULL;
+  SWIG_TypeNewClientData(SWIGTYPE_p_imageObj, SWIG_NewClientData(obj));
+  return SWIG_Py_Void();
+}
+
+SWIGINTERN PyObject *_wrap_layerObj_classitem_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   layerObj *arg1 = (layerObj *) 0 ;
   char *arg2 = (char *) 0 ;
@@ -20830,19 +22202,19 @@ SWIGINTERN PyObject *_wrap_layerObj_name_set(PyObject *SWIGUNUSEDPARM(self), PyO
   int res1 = 0 ;
   PyObject * obj0 = 0 ;
   
-  if (!PyArg_ParseTuple(args,(char *)"Oz:layerObj_name_set",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  if (!PyArg_ParseTuple(args,(char *)"Oz:layerObj_classitem_set",&obj0,&arg2)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_name_set" "', argument " "1"" of type '" "layerObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_classitem_set" "', argument " "1"" of type '" "layerObj *""'"); 
   }
   arg1 = (layerObj *)(argp1);
   {
-    if (arg1->name) free((char*)arg1->name);
+    if (arg1->classitem) free((char*)arg1->classitem);
     if (arg2) {
-      arg1->name = (char *) malloc(strlen(arg2)+1);
-      strcpy((char*)arg1->name,arg2);
+      arg1->classitem = (char *) malloc(strlen(arg2)+1);
+      strcpy((char*)arg1->classitem,arg2);
     } else {
-      arg1->name = 0;
+      arg1->classitem = 0;
     }
   }
   resultobj = SWIG_Py_Void();
@@ -20852,7 +22224,7 @@ fail:
 }
 
 
-SWIGINTERN PyObject *_wrap_layerObj_name_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_layerObj_classitem_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   layerObj *arg1 = (layerObj *) 0 ;
   void *argp1 = 0 ;
@@ -20860,13 +22232,13 @@ SWIGINTERN PyObject *_wrap_layerObj_name_get(PyObject *SWIGUNUSEDPARM(self), PyO
   PyObject * obj0 = 0 ;
   char *result = 0 ;
   
-  if (!PyArg_ParseTuple(args,(char *)"O:layerObj_name_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  if (!PyArg_ParseTuple(args,(char *)"O:layerObj_classitem_get",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_name_get" "', argument " "1"" of type '" "layerObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_classitem_get" "', argument " "1"" of type '" "layerObj *""'"); 
   }
   arg1 = (layerObj *)(argp1);
-  result = (char *) ((arg1)->name);
+  result = (char *) ((arg1)->classitem);
   resultobj = SWIG_FromCharPtr((const char *)result);
   return resultobj;
 fail:
@@ -20874,16 +22246,334 @@ fail:
 }
 
 
-SWIGINTERN PyObject *_wrap_layerObj_group_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_layerObj_refcount_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   layerObj *arg1 = (layerObj *) 0 ;
-  char *arg2 = (char *) 0 ;
   void *argp1 = 0 ;
   int res1 = 0 ;
   PyObject * obj0 = 0 ;
+  int result;
   
-  if (!PyArg_ParseTuple(args,(char *)"Oz:layerObj_group_set",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  if (!PyArg_ParseTuple(args,(char *)"O:layerObj_refcount_get",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_refcount_get" "', argument " "1"" of type '" "layerObj *""'"); 
+  }
+  arg1 = (layerObj *)(argp1);
+  result = (int) ((arg1)->refcount);
+  resultobj = SWIG_From_int((int)(result));
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_layerObj_numclasses_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  layerObj *arg1 = (layerObj *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  int result;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:layerObj_numclasses_get",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_numclasses_get" "', argument " "1"" of type '" "layerObj *""'"); 
+  }
+  arg1 = (layerObj *)(argp1);
+  result = (int) ((arg1)->numclasses);
+  resultobj = SWIG_From_int((int)(result));
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_layerObj_maxclasses_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  layerObj *arg1 = (layerObj *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  int result;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:layerObj_maxclasses_get",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_maxclasses_get" "', argument " "1"" of type '" "layerObj *""'"); 
+  }
+  arg1 = (layerObj *)(argp1);
+  result = (int) ((arg1)->maxclasses);
+  resultobj = SWIG_From_int((int)(result));
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_layerObj_index_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  layerObj *arg1 = (layerObj *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  int result;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:layerObj_index_get",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_index_get" "', argument " "1"" of type '" "layerObj *""'"); 
+  }
+  arg1 = (layerObj *)(argp1);
+  result = (int) ((arg1)->index);
+  resultobj = SWIG_From_int((int)(result));
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_layerObj_map_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  layerObj *arg1 = (layerObj *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  struct mapObj *result = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:layerObj_map_get",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_map_get" "', argument " "1"" of type '" "layerObj *""'"); 
+  }
+  arg1 = (layerObj *)(argp1);
+  result = (struct mapObj *) ((arg1)->map);
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_mapObj, 0 |  0 );
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_layerObj_header_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  layerObj *arg1 = (layerObj *) 0 ;
+  char *arg2 = (char *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"Oz:layerObj_header_set",&obj0,&arg2)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_header_set" "', argument " "1"" of type '" "layerObj *""'"); 
+  }
+  arg1 = (layerObj *)(argp1);
+  {
+    if (arg1->header) free((char*)arg1->header);
+    if (arg2) {
+      arg1->header = (char *) malloc(strlen(arg2)+1);
+      strcpy((char*)arg1->header,arg2);
+    } else {
+      arg1->header = 0;
+    }
+  }
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_layerObj_header_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  layerObj *arg1 = (layerObj *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  char *result = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:layerObj_header_get",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_header_get" "', argument " "1"" of type '" "layerObj *""'"); 
+  }
+  arg1 = (layerObj *)(argp1);
+  result = (char *) ((arg1)->header);
+  resultobj = SWIG_FromCharPtr((const char *)result);
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_layerObj_footer_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  layerObj *arg1 = (layerObj *) 0 ;
+  char *arg2 = (char *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"Oz:layerObj_footer_set",&obj0,&arg2)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_footer_set" "', argument " "1"" of type '" "layerObj *""'"); 
+  }
+  arg1 = (layerObj *)(argp1);
+  {
+    if (arg1->footer) free((char*)arg1->footer);
+    if (arg2) {
+      arg1->footer = (char *) malloc(strlen(arg2)+1);
+      strcpy((char*)arg1->footer,arg2);
+    } else {
+      arg1->footer = 0;
+    }
+  }
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_layerObj_footer_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  layerObj *arg1 = (layerObj *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  char *result = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:layerObj_footer_get",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_footer_get" "', argument " "1"" of type '" "layerObj *""'"); 
+  }
+  arg1 = (layerObj *)(argp1);
+  result = (char *) ((arg1)->footer);
+  resultobj = SWIG_FromCharPtr((const char *)result);
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_layerObj_template_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  layerObj *arg1 = (layerObj *) 0 ;
+  char *arg2 = (char *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"Oz:layerObj_template_set",&obj0,&arg2)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_template_set" "', argument " "1"" of type '" "layerObj *""'"); 
+  }
+  arg1 = (layerObj *)(argp1);
+  {
+    if (arg1->template) free((char*)arg1->template);
+    if (arg2) {
+      arg1->template = (char *) malloc(strlen(arg2)+1);
+      strcpy((char*)arg1->template,arg2);
+    } else {
+      arg1->template = 0;
+    }
+  }
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_layerObj_template_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  layerObj *arg1 = (layerObj *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  char *result = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:layerObj_template_get",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_template_get" "', argument " "1"" of type '" "layerObj *""'"); 
+  }
+  arg1 = (layerObj *)(argp1);
+  result = (char *) ((arg1)->template);
+  resultobj = SWIG_FromCharPtr((const char *)result);
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_layerObj_name_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  layerObj *arg1 = (layerObj *) 0 ;
+  char *arg2 = (char *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"Oz:layerObj_name_set",&obj0,&arg2)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_name_set" "', argument " "1"" of type '" "layerObj *""'"); 
+  }
+  arg1 = (layerObj *)(argp1);
+  {
+    if (arg1->name) free((char*)arg1->name);
+    if (arg2) {
+      arg1->name = (char *) malloc(strlen(arg2)+1);
+      strcpy((char*)arg1->name,arg2);
+    } else {
+      arg1->name = 0;
+    }
+  }
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_layerObj_name_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  layerObj *arg1 = (layerObj *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  char *result = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:layerObj_name_get",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_name_get" "', argument " "1"" of type '" "layerObj *""'"); 
+  }
+  arg1 = (layerObj *)(argp1);
+  result = (char *) ((arg1)->name);
+  resultobj = SWIG_FromCharPtr((const char *)result);
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_layerObj_group_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  layerObj *arg1 = (layerObj *) 0 ;
+  char *arg2 = (char *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"Oz:layerObj_group_set",&obj0,&arg2)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_group_set" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -20913,7 +22603,7 @@ SWIGINTERN PyObject *_wrap_layerObj_group_get(PyObject *SWIGUNUSEDPARM(self), Py
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_group_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_group_get" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -20938,7 +22628,7 @@ SWIGINTERN PyObject *_wrap_layerObj_status_set(PyObject *SWIGUNUSEDPARM(self), P
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:layerObj_status_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_status_set" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -20965,7 +22655,7 @@ SWIGINTERN PyObject *_wrap_layerObj_status_get(PyObject *SWIGUNUSEDPARM(self), P
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_status_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_status_get" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -20987,7 +22677,7 @@ SWIGINTERN PyObject *_wrap_layerObj_data_set(PyObject *SWIGUNUSEDPARM(self), PyO
   PyObject * obj0 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:layerObj_data_set",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_data_set" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -21017,7 +22707,7 @@ SWIGINTERN PyObject *_wrap_layerObj_data_get(PyObject *SWIGUNUSEDPARM(self), PyO
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_data_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_data_get" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -21042,7 +22732,7 @@ SWIGINTERN PyObject *_wrap_layerObj_type_set(PyObject *SWIGUNUSEDPARM(self), PyO
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:layerObj_type_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_type_set" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -21069,7 +22759,7 @@ SWIGINTERN PyObject *_wrap_layerObj_type_get(PyObject *SWIGUNUSEDPARM(self), PyO
   enum MS_LAYER_TYPE result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_type_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_type_get" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -21094,7 +22784,7 @@ SWIGINTERN PyObject *_wrap_layerObj_tolerance_set(PyObject *SWIGUNUSEDPARM(self)
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:layerObj_tolerance_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_tolerance_set" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -21121,7 +22811,7 @@ SWIGINTERN PyObject *_wrap_layerObj_tolerance_get(PyObject *SWIGUNUSEDPARM(self)
   double result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_tolerance_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_tolerance_get" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -21146,7 +22836,7 @@ SWIGINTERN PyObject *_wrap_layerObj_toleranceunits_set(PyObject *SWIGUNUSEDPARM(
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:layerObj_toleranceunits_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_toleranceunits_set" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -21173,7 +22863,7 @@ SWIGINTERN PyObject *_wrap_layerObj_toleranceunits_get(PyObject *SWIGUNUSEDPARM(
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_toleranceunits_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_toleranceunits_get" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -21198,7 +22888,7 @@ SWIGINTERN PyObject *_wrap_layerObj_symbolscaledenom_set(PyObject *SWIGUNUSEDPAR
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:layerObj_symbolscaledenom_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_symbolscaledenom_set" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -21225,7 +22915,7 @@ SWIGINTERN PyObject *_wrap_layerObj_symbolscaledenom_get(PyObject *SWIGUNUSEDPAR
   double result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_symbolscaledenom_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_symbolscaledenom_get" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -21250,7 +22940,7 @@ SWIGINTERN PyObject *_wrap_layerObj_minscaledenom_set(PyObject *SWIGUNUSEDPARM(s
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:layerObj_minscaledenom_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_minscaledenom_set" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -21277,7 +22967,7 @@ SWIGINTERN PyObject *_wrap_layerObj_minscaledenom_get(PyObject *SWIGUNUSEDPARM(s
   double result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_minscaledenom_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_minscaledenom_get" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -21302,7 +22992,7 @@ SWIGINTERN PyObject *_wrap_layerObj_maxscaledenom_set(PyObject *SWIGUNUSEDPARM(s
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:layerObj_maxscaledenom_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_maxscaledenom_set" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -21329,7 +23019,7 @@ SWIGINTERN PyObject *_wrap_layerObj_maxscaledenom_get(PyObject *SWIGUNUSEDPARM(s
   double result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_maxscaledenom_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_maxscaledenom_get" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -21354,7 +23044,7 @@ SWIGINTERN PyObject *_wrap_layerObj_minfeaturesize_set(PyObject *SWIGUNUSEDPARM(
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:layerObj_minfeaturesize_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_minfeaturesize_set" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -21381,7 +23071,7 @@ SWIGINTERN PyObject *_wrap_layerObj_minfeaturesize_get(PyObject *SWIGUNUSEDPARM(
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_minfeaturesize_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_minfeaturesize_get" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -21406,7 +23096,7 @@ SWIGINTERN PyObject *_wrap_layerObj_labelminscaledenom_set(PyObject *SWIGUNUSEDP
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:layerObj_labelminscaledenom_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_labelminscaledenom_set" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -21433,7 +23123,7 @@ SWIGINTERN PyObject *_wrap_layerObj_labelminscaledenom_get(PyObject *SWIGUNUSEDP
   double result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_labelminscaledenom_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_labelminscaledenom_get" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -21458,7 +23148,7 @@ SWIGINTERN PyObject *_wrap_layerObj_labelmaxscaledenom_set(PyObject *SWIGUNUSEDP
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:layerObj_labelmaxscaledenom_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_labelmaxscaledenom_set" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -21485,7 +23175,7 @@ SWIGINTERN PyObject *_wrap_layerObj_labelmaxscaledenom_get(PyObject *SWIGUNUSEDP
   double result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_labelmaxscaledenom_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_labelmaxscaledenom_get" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -21510,7 +23200,7 @@ SWIGINTERN PyObject *_wrap_layerObj_mingeowidth_set(PyObject *SWIGUNUSEDPARM(sel
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:layerObj_mingeowidth_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_mingeowidth_set" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -21537,7 +23227,7 @@ SWIGINTERN PyObject *_wrap_layerObj_mingeowidth_get(PyObject *SWIGUNUSEDPARM(sel
   double result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_mingeowidth_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_mingeowidth_get" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -21562,7 +23252,7 @@ SWIGINTERN PyObject *_wrap_layerObj_maxgeowidth_set(PyObject *SWIGUNUSEDPARM(sel
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:layerObj_maxgeowidth_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_maxgeowidth_set" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -21589,7 +23279,7 @@ SWIGINTERN PyObject *_wrap_layerObj_maxgeowidth_get(PyObject *SWIGUNUSEDPARM(sel
   double result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_maxgeowidth_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_maxgeowidth_get" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -21614,7 +23304,7 @@ SWIGINTERN PyObject *_wrap_layerObj_sizeunits_set(PyObject *SWIGUNUSEDPARM(self)
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:layerObj_sizeunits_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_sizeunits_set" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -21641,7 +23331,7 @@ SWIGINTERN PyObject *_wrap_layerObj_sizeunits_get(PyObject *SWIGUNUSEDPARM(self)
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_sizeunits_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_sizeunits_get" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -21666,7 +23356,7 @@ SWIGINTERN PyObject *_wrap_layerObj_maxfeatures_set(PyObject *SWIGUNUSEDPARM(sel
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:layerObj_maxfeatures_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_maxfeatures_set" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -21693,7 +23383,7 @@ SWIGINTERN PyObject *_wrap_layerObj_maxfeatures_get(PyObject *SWIGUNUSEDPARM(sel
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_maxfeatures_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_maxfeatures_get" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -21718,7 +23408,7 @@ SWIGINTERN PyObject *_wrap_layerObj_startindex_set(PyObject *SWIGUNUSEDPARM(self
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:layerObj_startindex_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_startindex_set" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -21745,7 +23435,7 @@ SWIGINTERN PyObject *_wrap_layerObj_startindex_get(PyObject *SWIGUNUSEDPARM(self
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_startindex_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_startindex_get" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -21770,7 +23460,7 @@ SWIGINTERN PyObject *_wrap_layerObj_offsite_set(PyObject *SWIGUNUSEDPARM(self),
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:layerObj_offsite_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_offsite_set" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -21797,7 +23487,7 @@ SWIGINTERN PyObject *_wrap_layerObj_offsite_get(PyObject *SWIGUNUSEDPARM(self),
   colorObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_offsite_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_offsite_get" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -21822,7 +23512,7 @@ SWIGINTERN PyObject *_wrap_layerObj_transform_set(PyObject *SWIGUNUSEDPARM(self)
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:layerObj_transform_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_transform_set" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -21849,7 +23539,7 @@ SWIGINTERN PyObject *_wrap_layerObj_transform_get(PyObject *SWIGUNUSEDPARM(self)
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_transform_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_transform_get" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -21874,7 +23564,7 @@ SWIGINTERN PyObject *_wrap_layerObj_labelcache_set(PyObject *SWIGUNUSEDPARM(self
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:layerObj_labelcache_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_labelcache_set" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -21901,7 +23591,7 @@ SWIGINTERN PyObject *_wrap_layerObj_labelcache_get(PyObject *SWIGUNUSEDPARM(self
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_labelcache_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_labelcache_get" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -21926,7 +23616,7 @@ SWIGINTERN PyObject *_wrap_layerObj_postlabelcache_set(PyObject *SWIGUNUSEDPARM(
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:layerObj_postlabelcache_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_postlabelcache_set" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -21953,7 +23643,7 @@ SWIGINTERN PyObject *_wrap_layerObj_postlabelcache_get(PyObject *SWIGUNUSEDPARM(
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_postlabelcache_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_postlabelcache_get" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -21975,7 +23665,7 @@ SWIGINTERN PyObject *_wrap_layerObj_labelitem_set(PyObject *SWIGUNUSEDPARM(self)
   PyObject * obj0 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:layerObj_labelitem_set",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_labelitem_set" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -22005,7 +23695,7 @@ SWIGINTERN PyObject *_wrap_layerObj_labelitem_get(PyObject *SWIGUNUSEDPARM(self)
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_labelitem_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_labelitem_get" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -22027,7 +23717,7 @@ SWIGINTERN PyObject *_wrap_layerObj_tileitem_set(PyObject *SWIGUNUSEDPARM(self),
   PyObject * obj0 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:layerObj_tileitem_set",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_tileitem_set" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -22057,7 +23747,7 @@ SWIGINTERN PyObject *_wrap_layerObj_tileitem_get(PyObject *SWIGUNUSEDPARM(self),
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_tileitem_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_tileitem_get" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -22079,7 +23769,7 @@ SWIGINTERN PyObject *_wrap_layerObj_tileindex_set(PyObject *SWIGUNUSEDPARM(self)
   PyObject * obj0 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:layerObj_tileindex_set",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_tileindex_set" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -22109,7 +23799,7 @@ SWIGINTERN PyObject *_wrap_layerObj_tileindex_get(PyObject *SWIGUNUSEDPARM(self)
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_tileindex_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_tileindex_get" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -22134,7 +23824,7 @@ SWIGINTERN PyObject *_wrap_layerObj_units_set(PyObject *SWIGUNUSEDPARM(self), Py
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:layerObj_units_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_units_set" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -22161,7 +23851,7 @@ SWIGINTERN PyObject *_wrap_layerObj_units_get(PyObject *SWIGUNUSEDPARM(self), Py
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_units_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_units_get" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -22183,7 +23873,7 @@ SWIGINTERN PyObject *_wrap_layerObj_connection_set(PyObject *SWIGUNUSEDPARM(self
   PyObject * obj0 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:layerObj_connection_set",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_connection_set" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -22213,7 +23903,7 @@ SWIGINTERN PyObject *_wrap_layerObj_connection_get(PyObject *SWIGUNUSEDPARM(self
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_connection_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_connection_get" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -22235,7 +23925,7 @@ SWIGINTERN PyObject *_wrap_layerObj_plugin_library_set(PyObject *SWIGUNUSEDPARM(
   PyObject * obj0 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:layerObj_plugin_library_set",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_plugin_library_set" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -22265,7 +23955,7 @@ SWIGINTERN PyObject *_wrap_layerObj_plugin_library_get(PyObject *SWIGUNUSEDPARM(
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_plugin_library_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_plugin_library_get" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -22287,7 +23977,7 @@ SWIGINTERN PyObject *_wrap_layerObj_plugin_library_original_set(PyObject *SWIGUN
   PyObject * obj0 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:layerObj_plugin_library_original_set",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_plugin_library_original_set" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -22317,7 +24007,7 @@ SWIGINTERN PyObject *_wrap_layerObj_plugin_library_original_get(PyObject *SWIGUN
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_plugin_library_original_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_plugin_library_original_get" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -22342,7 +24032,7 @@ SWIGINTERN PyObject *_wrap_layerObj_connectiontype_set(PyObject *SWIGUNUSEDPARM(
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:layerObj_connectiontype_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_connectiontype_set" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -22369,7 +24059,7 @@ SWIGINTERN PyObject *_wrap_layerObj_connectiontype_get(PyObject *SWIGUNUSEDPARM(
   enum MS_CONNECTION_TYPE result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_connectiontype_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_connectiontype_get" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -22391,7 +24081,7 @@ SWIGINTERN PyObject *_wrap_layerObj_numitems_get(PyObject *SWIGUNUSEDPARM(self),
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_numitems_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_numitems_get" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -22413,7 +24103,7 @@ SWIGINTERN PyObject *_wrap_layerObj_bandsitem_set(PyObject *SWIGUNUSEDPARM(self)
   PyObject * obj0 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:layerObj_bandsitem_set",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_bandsitem_set" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -22443,7 +24133,7 @@ SWIGINTERN PyObject *_wrap_layerObj_bandsitem_get(PyObject *SWIGUNUSEDPARM(self)
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_bandsitem_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_bandsitem_get" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -22465,7 +24155,7 @@ SWIGINTERN PyObject *_wrap_layerObj_filteritem_set(PyObject *SWIGUNUSEDPARM(self
   PyObject * obj0 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:layerObj_filteritem_set",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_filteritem_set" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -22495,7 +24185,7 @@ SWIGINTERN PyObject *_wrap_layerObj_filteritem_get(PyObject *SWIGUNUSEDPARM(self
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_filteritem_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_filteritem_get" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -22517,7 +24207,7 @@ SWIGINTERN PyObject *_wrap_layerObj_styleitem_set(PyObject *SWIGUNUSEDPARM(self)
   PyObject * obj0 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:layerObj_styleitem_set",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_styleitem_set" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -22547,7 +24237,7 @@ SWIGINTERN PyObject *_wrap_layerObj_styleitem_get(PyObject *SWIGUNUSEDPARM(self)
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_styleitem_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_styleitem_get" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -22569,7 +24259,7 @@ SWIGINTERN PyObject *_wrap_layerObj_requires_set(PyObject *SWIGUNUSEDPARM(self),
   PyObject * obj0 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:layerObj_requires_set",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_requires_set" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -22599,7 +24289,7 @@ SWIGINTERN PyObject *_wrap_layerObj_requires_get(PyObject *SWIGUNUSEDPARM(self),
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_requires_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_requires_get" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -22621,7 +24311,7 @@ SWIGINTERN PyObject *_wrap_layerObj_labelrequires_set(PyObject *SWIGUNUSEDPARM(s
   PyObject * obj0 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:layerObj_labelrequires_set",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_labelrequires_set" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -22651,7 +24341,7 @@ SWIGINTERN PyObject *_wrap_layerObj_labelrequires_get(PyObject *SWIGUNUSEDPARM(s
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_labelrequires_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_labelrequires_get" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -22673,7 +24363,7 @@ SWIGINTERN PyObject *_wrap_layerObj_metadata_get(PyObject *SWIGUNUSEDPARM(self),
   hashTableObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_metadata_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_metadata_get" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -22695,7 +24385,7 @@ SWIGINTERN PyObject *_wrap_layerObj_validation_get(PyObject *SWIGUNUSEDPARM(self
   hashTableObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_validation_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_validation_get" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -22717,7 +24407,7 @@ SWIGINTERN PyObject *_wrap_layerObj_bindvals_get(PyObject *SWIGUNUSEDPARM(self),
   hashTableObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_bindvals_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_bindvals_get" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -22739,7 +24429,7 @@ SWIGINTERN PyObject *_wrap_layerObj_cluster_get(PyObject *SWIGUNUSEDPARM(self),
   clusterObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_cluster_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_cluster_get" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -22764,7 +24454,7 @@ SWIGINTERN PyObject *_wrap_layerObj_opacity_set(PyObject *SWIGUNUSEDPARM(self),
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:layerObj_opacity_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_opacity_set" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -22791,7 +24481,7 @@ SWIGINTERN PyObject *_wrap_layerObj_opacity_get(PyObject *SWIGUNUSEDPARM(self),
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_opacity_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_opacity_get" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -22816,7 +24506,7 @@ SWIGINTERN PyObject *_wrap_layerObj_dump_set(PyObject *SWIGUNUSEDPARM(self), PyO
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:layerObj_dump_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_dump_set" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -22843,7 +24533,7 @@ SWIGINTERN PyObject *_wrap_layerObj_dump_get(PyObject *SWIGUNUSEDPARM(self), PyO
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_dump_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_dump_get" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -22868,7 +24558,7 @@ SWIGINTERN PyObject *_wrap_layerObj_debug_set(PyObject *SWIGUNUSEDPARM(self), Py
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:layerObj_debug_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_debug_set" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -22895,7 +24585,7 @@ SWIGINTERN PyObject *_wrap_layerObj_debug_get(PyObject *SWIGUNUSEDPARM(self), Py
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_debug_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_debug_get" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -22917,7 +24607,7 @@ SWIGINTERN PyObject *_wrap_layerObj_extent_get(PyObject *SWIGUNUSEDPARM(self), P
   rectObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_extent_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_extent_get" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -22939,7 +24629,7 @@ SWIGINTERN PyObject *_wrap_layerObj_numprocessing_get(PyObject *SWIGUNUSEDPARM(s
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_numprocessing_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_numprocessing_get" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -22961,7 +24651,7 @@ SWIGINTERN PyObject *_wrap_layerObj_numjoins_get(PyObject *SWIGUNUSEDPARM(self),
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_numjoins_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_numjoins_get" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -22983,7 +24673,7 @@ SWIGINTERN PyObject *_wrap_layerObj_classgroup_set(PyObject *SWIGUNUSEDPARM(self
   PyObject * obj0 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:layerObj_classgroup_set",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_classgroup_set" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -23013,7 +24703,7 @@ SWIGINTERN PyObject *_wrap_layerObj_classgroup_get(PyObject *SWIGUNUSEDPARM(self
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_classgroup_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_classgroup_get" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -23026,6 +24716,58 @@ fail:
 }
 
 
+SWIGINTERN PyObject *_wrap_layerObj_mask_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  layerObj *arg1 = (layerObj *) 0 ;
+  char *arg2 = (char *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"Oz:layerObj_mask_set",&obj0,&arg2)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_mask_set" "', argument " "1"" of type '" "layerObj *""'"); 
+  }
+  arg1 = (layerObj *)(argp1);
+  {
+    if (arg1->mask) free((char*)arg1->mask);
+    if (arg2) {
+      arg1->mask = (char *) malloc(strlen(arg2)+1);
+      strcpy((char*)arg1->mask,arg2);
+    } else {
+      arg1->mask = 0;
+    }
+  }
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_layerObj_mask_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  layerObj *arg1 = (layerObj *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  char *result = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:layerObj_mask_get",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_mask_get" "', argument " "1"" of type '" "layerObj *""'"); 
+  }
+  arg1 = (layerObj *)(argp1);
+  result = (char *) ((arg1)->mask);
+  resultobj = SWIG_FromCharPtr((const char *)result);
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
 SWIGINTERN PyObject *_wrap_new_layerObj(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   mapObj *arg1 = (mapObj *) NULL ;
@@ -23036,7 +24778,7 @@ SWIGINTERN PyObject *_wrap_new_layerObj(PyObject *SWIGUNUSEDPARM(self), PyObject
   
   if (!PyArg_ParseTuple(args,(char *)"|O:new_layerObj",&obj0)) SWIG_fail;
   if (obj0) {
-    res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+    res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
     if (!SWIG_IsOK(res1)) {
       SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "new_layerObj" "', argument " "1"" of type '" "mapObj *""'"); 
     }
@@ -23068,7 +24810,7 @@ SWIGINTERN PyObject *_wrap_new_layerObj(PyObject *SWIGUNUSEDPARM(self), PyObject
       
     }
   }
-  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_layer_obj, SWIG_POINTER_NEW |  0 );
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_layerObj, SWIG_POINTER_NEW |  0 );
   return resultobj;
 fail:
   return NULL;
@@ -23083,7 +24825,7 @@ SWIGINTERN PyObject *_wrap_delete_layerObj(PyObject *SWIGUNUSEDPARM(self), PyObj
   PyObject * obj0 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:delete_layerObj",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, SWIG_POINTER_DISOWN |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, SWIG_POINTER_DISOWN |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_layerObj" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -23130,7 +24872,7 @@ SWIGINTERN PyObject *_wrap_layerObj_clone(PyObject *SWIGUNUSEDPARM(self), PyObje
   layerObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_clone",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_clone" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -23161,7 +24903,7 @@ SWIGINTERN PyObject *_wrap_layerObj_clone(PyObject *SWIGUNUSEDPARM(self), PyObje
       
     }
   }
-  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_layer_obj, SWIG_POINTER_OWN |  0 );
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_layerObj, SWIG_POINTER_OWN |  0 );
   return resultobj;
 fail:
   return NULL;
@@ -23178,7 +24920,7 @@ SWIGINTERN PyObject *_wrap_layerObj_updateFromString(PyObject *SWIGUNUSEDPARM(se
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:layerObj_updateFromString",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_updateFromString" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -23233,12 +24975,12 @@ SWIGINTERN PyObject *_wrap_layerObj_insertClass(PyObject *SWIGUNUSEDPARM(self),
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"OO|O:layerObj_insertClass",&obj0,&obj1,&obj2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_insertClass" "', argument " "1"" of type '" "layerObj *""'"); 
   }
   arg1 = (layerObj *)(argp1);
-  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_class_obj, 0 |  0 );
+  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_classObj, 0 |  0 );
   if (!SWIG_IsOK(res2)) {
     SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "layerObj_insertClass" "', argument " "2"" of type '" "classObj *""'"); 
   }
@@ -23296,7 +25038,7 @@ SWIGINTERN PyObject *_wrap_layerObj_removeClass(PyObject *SWIGUNUSEDPARM(self),
   classObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:layerObj_removeClass",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_removeClass" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -23332,7 +25074,7 @@ SWIGINTERN PyObject *_wrap_layerObj_removeClass(PyObject *SWIGUNUSEDPARM(self),
       
     }
   }
-  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_class_obj, SWIG_POINTER_OWN |  0 );
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_classObj, SWIG_POINTER_OWN |  0 );
   return resultobj;
 fail:
   return NULL;
@@ -23348,7 +25090,7 @@ SWIGINTERN PyObject *_wrap_layerObj_open(PyObject *SWIGUNUSEDPARM(self), PyObjec
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_open",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_open" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -23399,7 +25141,7 @@ SWIGINTERN PyObject *_wrap_layerObj_whichShapes(PyObject *SWIGUNUSEDPARM(self),
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:layerObj_whichShapes",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_whichShapes" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -23457,7 +25199,7 @@ SWIGINTERN PyObject *_wrap_layerObj_nextShape(PyObject *SWIGUNUSEDPARM(self), Py
   shapeObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_nextShape",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_nextShape" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -23503,7 +25245,7 @@ SWIGINTERN PyObject *_wrap_layerObj_close(PyObject *SWIGUNUSEDPARM(self), PyObje
   PyObject * obj0 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_close",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_close" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -23554,7 +25296,7 @@ SWIGINTERN PyObject *_wrap_layerObj_getShape(PyObject *SWIGUNUSEDPARM(self), PyO
   shapeObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:layerObj_getShape",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_getShape" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -23606,7 +25348,7 @@ SWIGINTERN PyObject *_wrap_layerObj_getNumResults(PyObject *SWIGUNUSEDPARM(self)
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_getNumResults",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_getNumResults" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -23653,7 +25395,7 @@ SWIGINTERN PyObject *_wrap_layerObj_getResultsBounds(PyObject *SWIGUNUSEDPARM(se
   rectObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_getResultsBounds",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_getResultsBounds" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -23704,7 +25446,7 @@ SWIGINTERN PyObject *_wrap_layerObj_getResult(PyObject *SWIGUNUSEDPARM(self), Py
   resultObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:layerObj_getResult",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_getResult" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -23760,7 +25502,7 @@ SWIGINTERN PyObject *_wrap_layerObj_getClass(PyObject *SWIGUNUSEDPARM(self), PyO
   classObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:layerObj_getClass",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_getClass" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -23796,7 +25538,7 @@ SWIGINTERN PyObject *_wrap_layerObj_getClass(PyObject *SWIGUNUSEDPARM(self), PyO
       
     }
   }
-  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_class_obj, SWIG_POINTER_OWN |  0 );
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_classObj, SWIG_POINTER_OWN |  0 );
   return resultobj;
 fail:
   return NULL;
@@ -23816,7 +25558,7 @@ SWIGINTERN PyObject *_wrap_layerObj_getItem(PyObject *SWIGUNUSEDPARM(self), PyOb
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:layerObj_getItem",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_getItem" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -23859,40 +25601,40 @@ fail:
 }
 
 
-SWIGINTERN PyObject *_wrap_layerObj_draw(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_layerObj_setItems(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   layerObj *arg1 = (layerObj *) 0 ;
-  mapObj *arg2 = (mapObj *) 0 ;
-  imageObj *arg3 = (imageObj *) 0 ;
+  char **arg2 = (char **) 0 ;
+  int arg3 ;
   void *argp1 = 0 ;
   int res1 = 0 ;
   void *argp2 = 0 ;
   int res2 = 0 ;
-  void *argp3 = 0 ;
-  int res3 = 0 ;
+  int val3 ;
+  int ecode3 = 0 ;
   PyObject * obj0 = 0 ;
   PyObject * obj1 = 0 ;
   PyObject * obj2 = 0 ;
   int result;
   
-  if (!PyArg_ParseTuple(args,(char *)"OOO:layerObj_draw",&obj0,&obj1,&obj2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  if (!PyArg_ParseTuple(args,(char *)"OOO:layerObj_setItems",&obj0,&obj1,&obj2)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_draw" "', argument " "1"" of type '" "layerObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_setItems" "', argument " "1"" of type '" "layerObj *""'"); 
   }
   arg1 = (layerObj *)(argp1);
-  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_map_obj, 0 |  0 );
+  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_p_char, 0 |  0 );
   if (!SWIG_IsOK(res2)) {
-    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "layerObj_draw" "', argument " "2"" of type '" "mapObj *""'"); 
-  }
-  arg2 = (mapObj *)(argp2);
-  res3 = SWIG_ConvertPtr(obj2, &argp3,SWIGTYPE_p_imageObj, 0 |  0 );
-  if (!SWIG_IsOK(res3)) {
-    SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "layerObj_draw" "', argument " "3"" of type '" "imageObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "layerObj_setItems" "', argument " "2"" of type '" "char **""'"); 
   }
-  arg3 = (imageObj *)(argp3);
+  arg2 = (char **)(argp2);
+  ecode3 = SWIG_AsVal_int(obj2, &val3);
+  if (!SWIG_IsOK(ecode3)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "layerObj_setItems" "', argument " "3"" of type '" "int""'");
+  } 
+  arg3 = (int)(val3);
   {
-    result = (int)layerObj_draw(arg1,arg2,arg3); {
+    result = (int)layerObj_setItems(arg1,arg2,arg3); {
       errorObj *ms_error = msGetErrorObj();
       
       switch(ms_error->code) {
@@ -23924,7 +25666,7 @@ fail:
 }
 
 
-SWIGINTERN PyObject *_wrap_layerObj_drawQuery(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_layerObj_draw(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   layerObj *arg1 = (layerObj *) 0 ;
   mapObj *arg2 = (mapObj *) 0 ;
@@ -23940,148 +25682,24 @@ SWIGINTERN PyObject *_wrap_layerObj_drawQuery(PyObject *SWIGUNUSEDPARM(self), Py
   PyObject * obj2 = 0 ;
   int result;
   
-  if (!PyArg_ParseTuple(args,(char *)"OOO:layerObj_drawQuery",&obj0,&obj1,&obj2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  if (!PyArg_ParseTuple(args,(char *)"OOO:layerObj_draw",&obj0,&obj1,&obj2)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_drawQuery" "', argument " "1"" of type '" "layerObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_draw" "', argument " "1"" of type '" "layerObj *""'"); 
   }
   arg1 = (layerObj *)(argp1);
-  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_map_obj, 0 |  0 );
+  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res2)) {
-    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "layerObj_drawQuery" "', argument " "2"" of type '" "mapObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "layerObj_draw" "', argument " "2"" of type '" "mapObj *""'"); 
   }
   arg2 = (mapObj *)(argp2);
   res3 = SWIG_ConvertPtr(obj2, &argp3,SWIGTYPE_p_imageObj, 0 |  0 );
   if (!SWIG_IsOK(res3)) {
-    SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "layerObj_drawQuery" "', argument " "3"" of type '" "imageObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "layerObj_draw" "', argument " "3"" of type '" "imageObj *""'"); 
   }
   arg3 = (imageObj *)(argp3);
   {
-    result = (int)layerObj_drawQuery(arg1,arg2,arg3); {
-      errorObj *ms_error = msGetErrorObj();
-      
-      switch(ms_error->code) {
-      case MS_NOERR:
-        break;
-      case MS_NOTFOUND:
-        msResetErrorList();
-        break;
-      case -1:
-        break;
-      case MS_IOERR:
-        if (strcmp(ms_error->routine, "msSearchDiskTree()") != 0) {
-          _raise_ms_exception();
-          msResetErrorList();
-          return NULL;
-        }
-      default:
-        _raise_ms_exception();
-        msResetErrorList();
-        return NULL;
-      }
-      
-    }
-  }
-  resultobj = SWIG_From_int((int)(result));
-  return resultobj;
-fail:
-  return NULL;
-}
-
-
-SWIGINTERN PyObject *_wrap_layerObj_queryByFilter(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
-  PyObject *resultobj = 0;
-  layerObj *arg1 = (layerObj *) 0 ;
-  mapObj *arg2 = (mapObj *) 0 ;
-  char *arg3 = (char *) 0 ;
-  void *argp1 = 0 ;
-  int res1 = 0 ;
-  void *argp2 = 0 ;
-  int res2 = 0 ;
-  PyObject * obj0 = 0 ;
-  PyObject * obj1 = 0 ;
-  int result;
-  
-  if (!PyArg_ParseTuple(args,(char *)"OOz:layerObj_queryByFilter",&obj0,&obj1,&arg3)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
-  if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_queryByFilter" "', argument " "1"" of type '" "layerObj *""'"); 
-  }
-  arg1 = (layerObj *)(argp1);
-  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_map_obj, 0 |  0 );
-  if (!SWIG_IsOK(res2)) {
-    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "layerObj_queryByFilter" "', argument " "2"" of type '" "mapObj *""'"); 
-  }
-  arg2 = (mapObj *)(argp2);
-  {
-    result = (int)layerObj_queryByFilter(arg1,arg2,arg3); {
-      errorObj *ms_error = msGetErrorObj();
-      
-      switch(ms_error->code) {
-      case MS_NOERR:
-        break;
-      case MS_NOTFOUND:
-        msResetErrorList();
-        break;
-      case -1:
-        break;
-      case MS_IOERR:
-        if (strcmp(ms_error->routine, "msSearchDiskTree()") != 0) {
-          _raise_ms_exception();
-          msResetErrorList();
-          return NULL;
-        }
-      default:
-        _raise_ms_exception();
-        msResetErrorList();
-        return NULL;
-      }
-      
-    }
-  }
-  resultobj = SWIG_From_int((int)(result));
-  return resultobj;
-fail:
-  return NULL;
-}
-
-
-SWIGINTERN PyObject *_wrap_layerObj_queryByAttributes(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
-  PyObject *resultobj = 0;
-  layerObj *arg1 = (layerObj *) 0 ;
-  mapObj *arg2 = (mapObj *) 0 ;
-  char *arg3 = (char *) 0 ;
-  char *arg4 = (char *) 0 ;
-  int arg5 ;
-  void *argp1 = 0 ;
-  int res1 = 0 ;
-  void *argp2 = 0 ;
-  int res2 = 0 ;
-  int val5 ;
-  int ecode5 = 0 ;
-  PyObject * obj0 = 0 ;
-  PyObject * obj1 = 0 ;
-  PyObject * obj4 = 0 ;
-  int result;
-  
-  if (!PyArg_ParseTuple(args,(char *)"OOzzO:layerObj_queryByAttributes",&obj0,&obj1,&arg3,&arg4,&obj4)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
-  if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_queryByAttributes" "', argument " "1"" of type '" "layerObj *""'"); 
-  }
-  arg1 = (layerObj *)(argp1);
-  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_map_obj, 0 |  0 );
-  if (!SWIG_IsOK(res2)) {
-    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "layerObj_queryByAttributes" "', argument " "2"" of type '" "mapObj *""'"); 
-  }
-  arg2 = (mapObj *)(argp2);
-  ecode5 = SWIG_AsVal_int(obj4, &val5);
-  if (!SWIG_IsOK(ecode5)) {
-    SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "layerObj_queryByAttributes" "', argument " "5"" of type '" "int""'");
-  } 
-  arg5 = (int)(val5);
-  {
-    result = (int)layerObj_queryByAttributes(arg1,arg2,arg3,arg4,arg5); {
+    result = (int)layerObj_draw(arg1,arg2,arg3); {
       errorObj *ms_error = msGetErrorObj();
       
       switch(ms_error->code) {
@@ -24113,58 +25731,40 @@ fail:
 }
 
 
-SWIGINTERN PyObject *_wrap_layerObj_queryByPoint(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_layerObj_drawQuery(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   layerObj *arg1 = (layerObj *) 0 ;
   mapObj *arg2 = (mapObj *) 0 ;
-  pointObj *arg3 = (pointObj *) 0 ;
-  int arg4 ;
-  double arg5 ;
+  imageObj *arg3 = (imageObj *) 0 ;
   void *argp1 = 0 ;
   int res1 = 0 ;
   void *argp2 = 0 ;
   int res2 = 0 ;
   void *argp3 = 0 ;
   int res3 = 0 ;
-  int val4 ;
-  int ecode4 = 0 ;
-  double val5 ;
-  int ecode5 = 0 ;
   PyObject * obj0 = 0 ;
   PyObject * obj1 = 0 ;
   PyObject * obj2 = 0 ;
-  PyObject * obj3 = 0 ;
-  PyObject * obj4 = 0 ;
   int result;
   
-  if (!PyArg_ParseTuple(args,(char *)"OOOOO:layerObj_queryByPoint",&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  if (!PyArg_ParseTuple(args,(char *)"OOO:layerObj_drawQuery",&obj0,&obj1,&obj2)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_queryByPoint" "', argument " "1"" of type '" "layerObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_drawQuery" "', argument " "1"" of type '" "layerObj *""'"); 
   }
   arg1 = (layerObj *)(argp1);
-  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_map_obj, 0 |  0 );
+  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res2)) {
-    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "layerObj_queryByPoint" "', argument " "2"" of type '" "mapObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "layerObj_drawQuery" "', argument " "2"" of type '" "mapObj *""'"); 
   }
   arg2 = (mapObj *)(argp2);
-  res3 = SWIG_ConvertPtr(obj2, &argp3,SWIGTYPE_p_pointObj, 0 |  0 );
+  res3 = SWIG_ConvertPtr(obj2, &argp3,SWIGTYPE_p_imageObj, 0 |  0 );
   if (!SWIG_IsOK(res3)) {
-    SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "layerObj_queryByPoint" "', argument " "3"" of type '" "pointObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "layerObj_drawQuery" "', argument " "3"" of type '" "imageObj *""'"); 
   }
-  arg3 = (pointObj *)(argp3);
-  ecode4 = SWIG_AsVal_int(obj3, &val4);
-  if (!SWIG_IsOK(ecode4)) {
-    SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "layerObj_queryByPoint" "', argument " "4"" of type '" "int""'");
-  } 
-  arg4 = (int)(val4);
-  ecode5 = SWIG_AsVal_double(obj4, &val5);
-  if (!SWIG_IsOK(ecode5)) {
-    SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "layerObj_queryByPoint" "', argument " "5"" of type '" "double""'");
-  } 
-  arg5 = (double)(val5);
+  arg3 = (imageObj *)(argp3);
   {
-    result = (int)layerObj_queryByPoint(arg1,arg2,arg3,arg4,arg5); {
+    result = (int)layerObj_drawQuery(arg1,arg2,arg3); {
       errorObj *ms_error = msGetErrorObj();
       
       switch(ms_error->code) {
@@ -24196,46 +25796,32 @@ fail:
 }
 
 
-SWIGINTERN PyObject *_wrap_layerObj_queryByRect(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_layerObj_queryByFilter(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   layerObj *arg1 = (layerObj *) 0 ;
   mapObj *arg2 = (mapObj *) 0 ;
-  rectObj arg3 ;
+  char *arg3 = (char *) 0 ;
   void *argp1 = 0 ;
   int res1 = 0 ;
   void *argp2 = 0 ;
   int res2 = 0 ;
-  void *argp3 ;
-  int res3 = 0 ;
   PyObject * obj0 = 0 ;
   PyObject * obj1 = 0 ;
-  PyObject * obj2 = 0 ;
   int result;
   
-  if (!PyArg_ParseTuple(args,(char *)"OOO:layerObj_queryByRect",&obj0,&obj1,&obj2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  if (!PyArg_ParseTuple(args,(char *)"OOz:layerObj_queryByFilter",&obj0,&obj1,&arg3)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_queryByRect" "', argument " "1"" of type '" "layerObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_queryByFilter" "', argument " "1"" of type '" "layerObj *""'"); 
   }
   arg1 = (layerObj *)(argp1);
-  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_map_obj, 0 |  0 );
+  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res2)) {
-    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "layerObj_queryByRect" "', argument " "2"" of type '" "mapObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "layerObj_queryByFilter" "', argument " "2"" of type '" "mapObj *""'"); 
   }
   arg2 = (mapObj *)(argp2);
   {
-    res3 = SWIG_ConvertPtr(obj2, &argp3, SWIGTYPE_p_rectObj,  0 );
-    if (!SWIG_IsOK(res3)) {
-      SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "layerObj_queryByRect" "', argument " "3"" of type '" "rectObj""'"); 
-    }  
-    if (!argp3) {
-      SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "layerObj_queryByRect" "', argument " "3"" of type '" "rectObj""'");
-    } else {
-      arg3 = *((rectObj *)(argp3));
-    }
-  }
-  {
-    result = (int)layerObj_queryByRect(arg1,arg2,arg3); {
+    result = (int)layerObj_queryByFilter(arg1,arg2,arg3); {
       errorObj *ms_error = msGetErrorObj();
       
       switch(ms_error->code) {
@@ -24267,40 +25853,42 @@ fail:
 }
 
 
-SWIGINTERN PyObject *_wrap_layerObj_queryByFeatures(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_layerObj_queryByAttributes(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   layerObj *arg1 = (layerObj *) 0 ;
   mapObj *arg2 = (mapObj *) 0 ;
-  int arg3 ;
+  char *arg3 = (char *) 0 ;
+  char *arg4 = (char *) 0 ;
+  int arg5 ;
   void *argp1 = 0 ;
   int res1 = 0 ;
   void *argp2 = 0 ;
   int res2 = 0 ;
-  int val3 ;
-  int ecode3 = 0 ;
+  int val5 ;
+  int ecode5 = 0 ;
   PyObject * obj0 = 0 ;
   PyObject * obj1 = 0 ;
-  PyObject * obj2 = 0 ;
+  PyObject * obj4 = 0 ;
   int result;
   
-  if (!PyArg_ParseTuple(args,(char *)"OOO:layerObj_queryByFeatures",&obj0,&obj1,&obj2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  if (!PyArg_ParseTuple(args,(char *)"OOzzO:layerObj_queryByAttributes",&obj0,&obj1,&arg3,&arg4,&obj4)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_queryByFeatures" "', argument " "1"" of type '" "layerObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_queryByAttributes" "', argument " "1"" of type '" "layerObj *""'"); 
   }
   arg1 = (layerObj *)(argp1);
-  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_map_obj, 0 |  0 );
+  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res2)) {
-    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "layerObj_queryByFeatures" "', argument " "2"" of type '" "mapObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "layerObj_queryByAttributes" "', argument " "2"" of type '" "mapObj *""'"); 
   }
   arg2 = (mapObj *)(argp2);
-  ecode3 = SWIG_AsVal_int(obj2, &val3);
-  if (!SWIG_IsOK(ecode3)) {
-    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "layerObj_queryByFeatures" "', argument " "3"" of type '" "int""'");
+  ecode5 = SWIG_AsVal_int(obj4, &val5);
+  if (!SWIG_IsOK(ecode5)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "layerObj_queryByAttributes" "', argument " "5"" of type '" "int""'");
   } 
-  arg3 = (int)(val3);
+  arg5 = (int)(val5);
   {
-    result = (int)layerObj_queryByFeatures(arg1,arg2,arg3); {
+    result = (int)layerObj_queryByAttributes(arg1,arg2,arg3,arg4,arg5); {
       errorObj *ms_error = msGetErrorObj();
       
       switch(ms_error->code) {
@@ -24332,40 +25920,58 @@ fail:
 }
 
 
-SWIGINTERN PyObject *_wrap_layerObj_queryByShape(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_layerObj_queryByPoint(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   layerObj *arg1 = (layerObj *) 0 ;
   mapObj *arg2 = (mapObj *) 0 ;
-  shapeObj *arg3 = (shapeObj *) 0 ;
+  pointObj *arg3 = (pointObj *) 0 ;
+  int arg4 ;
+  double arg5 ;
   void *argp1 = 0 ;
   int res1 = 0 ;
   void *argp2 = 0 ;
   int res2 = 0 ;
   void *argp3 = 0 ;
   int res3 = 0 ;
+  int val4 ;
+  int ecode4 = 0 ;
+  double val5 ;
+  int ecode5 = 0 ;
   PyObject * obj0 = 0 ;
   PyObject * obj1 = 0 ;
   PyObject * obj2 = 0 ;
+  PyObject * obj3 = 0 ;
+  PyObject * obj4 = 0 ;
   int result;
   
-  if (!PyArg_ParseTuple(args,(char *)"OOO:layerObj_queryByShape",&obj0,&obj1,&obj2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  if (!PyArg_ParseTuple(args,(char *)"OOOOO:layerObj_queryByPoint",&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_queryByShape" "', argument " "1"" of type '" "layerObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_queryByPoint" "', argument " "1"" of type '" "layerObj *""'"); 
   }
   arg1 = (layerObj *)(argp1);
-  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_map_obj, 0 |  0 );
+  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res2)) {
-    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "layerObj_queryByShape" "', argument " "2"" of type '" "mapObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "layerObj_queryByPoint" "', argument " "2"" of type '" "mapObj *""'"); 
   }
   arg2 = (mapObj *)(argp2);
-  res3 = SWIG_ConvertPtr(obj2, &argp3,SWIGTYPE_p_shapeObj, 0 |  0 );
+  res3 = SWIG_ConvertPtr(obj2, &argp3,SWIGTYPE_p_pointObj, 0 |  0 );
   if (!SWIG_IsOK(res3)) {
-    SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "layerObj_queryByShape" "', argument " "3"" of type '" "shapeObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "layerObj_queryByPoint" "', argument " "3"" of type '" "pointObj *""'"); 
   }
-  arg3 = (shapeObj *)(argp3);
+  arg3 = (pointObj *)(argp3);
+  ecode4 = SWIG_AsVal_int(obj3, &val4);
+  if (!SWIG_IsOK(ecode4)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "layerObj_queryByPoint" "', argument " "4"" of type '" "int""'");
+  } 
+  arg4 = (int)(val4);
+  ecode5 = SWIG_AsVal_double(obj4, &val5);
+  if (!SWIG_IsOK(ecode5)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "layerObj_queryByPoint" "', argument " "5"" of type '" "double""'");
+  } 
+  arg5 = (double)(val5);
   {
-    result = (int)layerObj_queryByShape(arg1,arg2,arg3); {
+    result = (int)layerObj_queryByPoint(arg1,arg2,arg3,arg4,arg5); {
       errorObj *ms_error = msGetErrorObj();
       
       switch(ms_error->code) {
@@ -24397,60 +26003,46 @@ fail:
 }
 
 
-SWIGINTERN PyObject *_wrap_layerObj_queryByIndex(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_layerObj_queryByRect(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   layerObj *arg1 = (layerObj *) 0 ;
   mapObj *arg2 = (mapObj *) 0 ;
-  int arg3 ;
-  int arg4 ;
-  int arg5 = (int) 0 ;
+  rectObj arg3 ;
   void *argp1 = 0 ;
   int res1 = 0 ;
   void *argp2 = 0 ;
   int res2 = 0 ;
-  int val3 ;
-  int ecode3 = 0 ;
-  int val4 ;
-  int ecode4 = 0 ;
-  int val5 ;
-  int ecode5 = 0 ;
+  void *argp3 ;
+  int res3 = 0 ;
   PyObject * obj0 = 0 ;
   PyObject * obj1 = 0 ;
   PyObject * obj2 = 0 ;
-  PyObject * obj3 = 0 ;
-  PyObject * obj4 = 0 ;
   int result;
   
-  if (!PyArg_ParseTuple(args,(char *)"OOOO|O:layerObj_queryByIndex",&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  if (!PyArg_ParseTuple(args,(char *)"OOO:layerObj_queryByRect",&obj0,&obj1,&obj2)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_queryByIndex" "', argument " "1"" of type '" "layerObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_queryByRect" "', argument " "1"" of type '" "layerObj *""'"); 
   }
   arg1 = (layerObj *)(argp1);
-  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_map_obj, 0 |  0 );
+  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res2)) {
-    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "layerObj_queryByIndex" "', argument " "2"" of type '" "mapObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "layerObj_queryByRect" "', argument " "2"" of type '" "mapObj *""'"); 
   }
   arg2 = (mapObj *)(argp2);
-  ecode3 = SWIG_AsVal_int(obj2, &val3);
-  if (!SWIG_IsOK(ecode3)) {
-    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "layerObj_queryByIndex" "', argument " "3"" of type '" "int""'");
-  } 
-  arg3 = (int)(val3);
-  ecode4 = SWIG_AsVal_int(obj3, &val4);
-  if (!SWIG_IsOK(ecode4)) {
-    SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "layerObj_queryByIndex" "', argument " "4"" of type '" "int""'");
-  } 
-  arg4 = (int)(val4);
-  if (obj4) {
-    ecode5 = SWIG_AsVal_int(obj4, &val5);
-    if (!SWIG_IsOK(ecode5)) {
-      SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "layerObj_queryByIndex" "', argument " "5"" of type '" "int""'");
-    } 
-    arg5 = (int)(val5);
+  {
+    res3 = SWIG_ConvertPtr(obj2, &argp3, SWIGTYPE_p_rectObj,  0 );
+    if (!SWIG_IsOK(res3)) {
+      SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "layerObj_queryByRect" "', argument " "3"" of type '" "rectObj""'"); 
+    }  
+    if (!argp3) {
+      SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "layerObj_queryByRect" "', argument " "3"" of type '" "rectObj""'");
+    } else {
+      arg3 = *((rectObj *)(argp3));
+    }
   }
   {
-    result = (int)layerObj_queryByIndex(arg1,arg2,arg3,arg4,arg5); {
+    result = (int)layerObj_queryByRect(arg1,arg2,arg3); {
       errorObj *ms_error = msGetErrorObj();
       
       switch(ms_error->code) {
@@ -24482,22 +26074,40 @@ fail:
 }
 
 
-SWIGINTERN PyObject *_wrap_layerObj_getResults(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_layerObj_queryByFeatures(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   layerObj *arg1 = (layerObj *) 0 ;
+  mapObj *arg2 = (mapObj *) 0 ;
+  int arg3 ;
   void *argp1 = 0 ;
   int res1 = 0 ;
+  void *argp2 = 0 ;
+  int res2 = 0 ;
+  int val3 ;
+  int ecode3 = 0 ;
   PyObject * obj0 = 0 ;
-  resultCacheObj *result = 0 ;
+  PyObject * obj1 = 0 ;
+  PyObject * obj2 = 0 ;
+  int result;
   
-  if (!PyArg_ParseTuple(args,(char *)"O:layerObj_getResults",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  if (!PyArg_ParseTuple(args,(char *)"OOO:layerObj_queryByFeatures",&obj0,&obj1,&obj2)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_getResults" "', argument " "1"" of type '" "layerObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_queryByFeatures" "', argument " "1"" of type '" "layerObj *""'"); 
   }
   arg1 = (layerObj *)(argp1);
+  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_mapObj, 0 |  0 );
+  if (!SWIG_IsOK(res2)) {
+    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "layerObj_queryByFeatures" "', argument " "2"" of type '" "mapObj *""'"); 
+  }
+  arg2 = (mapObj *)(argp2);
+  ecode3 = SWIG_AsVal_int(obj2, &val3);
+  if (!SWIG_IsOK(ecode3)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "layerObj_queryByFeatures" "', argument " "3"" of type '" "int""'");
+  } 
+  arg3 = (int)(val3);
   {
-    result = (resultCacheObj *)layerObj_getResults(arg1); {
+    result = (int)layerObj_queryByFeatures(arg1,arg2,arg3); {
       errorObj *ms_error = msGetErrorObj();
       
       switch(ms_error->code) {
@@ -24522,30 +26132,47 @@ SWIGINTERN PyObject *_wrap_layerObj_getResults(PyObject *SWIGUNUSEDPARM(self), P
       
     }
   }
-  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_resultCacheObj, 0 |  0 );
+  resultobj = SWIG_From_int((int)(result));
   return resultobj;
 fail:
   return NULL;
 }
 
 
-SWIGINTERN PyObject *_wrap_layerObj_setFilter(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_layerObj_queryByShape(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   layerObj *arg1 = (layerObj *) 0 ;
-  char *arg2 = (char *) 0 ;
+  mapObj *arg2 = (mapObj *) 0 ;
+  shapeObj *arg3 = (shapeObj *) 0 ;
   void *argp1 = 0 ;
   int res1 = 0 ;
+  void *argp2 = 0 ;
+  int res2 = 0 ;
+  void *argp3 = 0 ;
+  int res3 = 0 ;
   PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  PyObject * obj2 = 0 ;
   int result;
   
-  if (!PyArg_ParseTuple(args,(char *)"Oz:layerObj_setFilter",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  if (!PyArg_ParseTuple(args,(char *)"OOO:layerObj_queryByShape",&obj0,&obj1,&obj2)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_setFilter" "', argument " "1"" of type '" "layerObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_queryByShape" "', argument " "1"" of type '" "layerObj *""'"); 
   }
   arg1 = (layerObj *)(argp1);
+  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_mapObj, 0 |  0 );
+  if (!SWIG_IsOK(res2)) {
+    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "layerObj_queryByShape" "', argument " "2"" of type '" "mapObj *""'"); 
+  }
+  arg2 = (mapObj *)(argp2);
+  res3 = SWIG_ConvertPtr(obj2, &argp3,SWIGTYPE_p_shapeObj, 0 |  0 );
+  if (!SWIG_IsOK(res3)) {
+    SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "layerObj_queryByShape" "', argument " "3"" of type '" "shapeObj *""'"); 
+  }
+  arg3 = (shapeObj *)(argp3);
   {
-    result = (int)layerObj_setFilter(arg1,arg2); {
+    result = (int)layerObj_queryByShape(arg1,arg2,arg3); {
       errorObj *ms_error = msGetErrorObj();
       
       switch(ms_error->code) {
@@ -24577,22 +26204,60 @@ fail:
 }
 
 
-SWIGINTERN PyObject *_wrap_layerObj_getFilterString(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_layerObj_queryByIndex(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   layerObj *arg1 = (layerObj *) 0 ;
+  mapObj *arg2 = (mapObj *) 0 ;
+  int arg3 ;
+  int arg4 ;
+  int arg5 = (int) 0 ;
   void *argp1 = 0 ;
   int res1 = 0 ;
+  void *argp2 = 0 ;
+  int res2 = 0 ;
+  int val3 ;
+  int ecode3 = 0 ;
+  int val4 ;
+  int ecode4 = 0 ;
+  int val5 ;
+  int ecode5 = 0 ;
   PyObject * obj0 = 0 ;
-  char *result = 0 ;
+  PyObject * obj1 = 0 ;
+  PyObject * obj2 = 0 ;
+  PyObject * obj3 = 0 ;
+  PyObject * obj4 = 0 ;
+  int result;
   
-  if (!PyArg_ParseTuple(args,(char *)"O:layerObj_getFilterString",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  if (!PyArg_ParseTuple(args,(char *)"OOOO|O:layerObj_queryByIndex",&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_getFilterString" "', argument " "1"" of type '" "layerObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_queryByIndex" "', argument " "1"" of type '" "layerObj *""'"); 
   }
   arg1 = (layerObj *)(argp1);
+  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_mapObj, 0 |  0 );
+  if (!SWIG_IsOK(res2)) {
+    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "layerObj_queryByIndex" "', argument " "2"" of type '" "mapObj *""'"); 
+  }
+  arg2 = (mapObj *)(argp2);
+  ecode3 = SWIG_AsVal_int(obj2, &val3);
+  if (!SWIG_IsOK(ecode3)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "layerObj_queryByIndex" "', argument " "3"" of type '" "int""'");
+  } 
+  arg3 = (int)(val3);
+  ecode4 = SWIG_AsVal_int(obj3, &val4);
+  if (!SWIG_IsOK(ecode4)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "layerObj_queryByIndex" "', argument " "4"" of type '" "int""'");
+  } 
+  arg4 = (int)(val4);
+  if (obj4) {
+    ecode5 = SWIG_AsVal_int(obj4, &val5);
+    if (!SWIG_IsOK(ecode5)) {
+      SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "layerObj_queryByIndex" "', argument " "5"" of type '" "int""'");
+    } 
+    arg5 = (int)(val5);
+  }
   {
-    result = (char *)layerObj_getFilterString(arg1); {
+    result = (int)layerObj_queryByIndex(arg1,arg2,arg3,arg4,arg5); {
       errorObj *ms_error = msGetErrorObj();
       
       switch(ms_error->code) {
@@ -24617,31 +26282,29 @@ SWIGINTERN PyObject *_wrap_layerObj_getFilterString(PyObject *SWIGUNUSEDPARM(sel
       
     }
   }
-  resultobj = SWIG_FromCharPtr((const char *)result);
-  free((char*)result);
+  resultobj = SWIG_From_int((int)(result));
   return resultobj;
 fail:
   return NULL;
 }
 
 
-SWIGINTERN PyObject *_wrap_layerObj_setWKTProjection(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_layerObj_getResults(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   layerObj *arg1 = (layerObj *) 0 ;
-  char *arg2 = (char *) 0 ;
   void *argp1 = 0 ;
   int res1 = 0 ;
   PyObject * obj0 = 0 ;
-  int result;
+  resultCacheObj *result = 0 ;
   
-  if (!PyArg_ParseTuple(args,(char *)"Oz:layerObj_setWKTProjection",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  if (!PyArg_ParseTuple(args,(char *)"O:layerObj_getResults",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_setWKTProjection" "', argument " "1"" of type '" "layerObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_getResults" "', argument " "1"" of type '" "layerObj *""'"); 
   }
   arg1 = (layerObj *)(argp1);
   {
-    result = (int)layerObj_setWKTProjection(arg1,arg2); {
+    result = (resultCacheObj *)layerObj_getResults(arg1); {
       errorObj *ms_error = msGetErrorObj();
       
       switch(ms_error->code) {
@@ -24666,29 +26329,30 @@ SWIGINTERN PyObject *_wrap_layerObj_setWKTProjection(PyObject *SWIGUNUSEDPARM(se
       
     }
   }
-  resultobj = SWIG_From_int((int)(result));
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_resultCacheObj, 0 |  0 );
   return resultobj;
 fail:
   return NULL;
 }
 
 
-SWIGINTERN PyObject *_wrap_layerObj_getProjection(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_layerObj_setFilter(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   layerObj *arg1 = (layerObj *) 0 ;
+  char *arg2 = (char *) 0 ;
   void *argp1 = 0 ;
   int res1 = 0 ;
   PyObject * obj0 = 0 ;
-  char *result = 0 ;
+  int result;
   
-  if (!PyArg_ParseTuple(args,(char *)"O:layerObj_getProjection",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  if (!PyArg_ParseTuple(args,(char *)"Oz:layerObj_setFilter",&obj0,&arg2)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_getProjection" "', argument " "1"" of type '" "layerObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_setFilter" "', argument " "1"" of type '" "layerObj *""'"); 
   }
   arg1 = (layerObj *)(argp1);
   {
-    result = (char *)layerObj_getProjection(arg1); {
+    result = (int)layerObj_setFilter(arg1,arg2); {
       errorObj *ms_error = msGetErrorObj();
       
       switch(ms_error->code) {
@@ -24713,31 +26377,29 @@ SWIGINTERN PyObject *_wrap_layerObj_getProjection(PyObject *SWIGUNUSEDPARM(self)
       
     }
   }
-  resultobj = SWIG_FromCharPtr((const char *)result);
-  free((char*)result);
+  resultobj = SWIG_From_int((int)(result));
   return resultobj;
 fail:
   return NULL;
 }
 
 
-SWIGINTERN PyObject *_wrap_layerObj_setProjection(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_layerObj_getFilterString(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   layerObj *arg1 = (layerObj *) 0 ;
-  char *arg2 = (char *) 0 ;
   void *argp1 = 0 ;
   int res1 = 0 ;
   PyObject * obj0 = 0 ;
-  int result;
+  char *result = 0 ;
   
-  if (!PyArg_ParseTuple(args,(char *)"Oz:layerObj_setProjection",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  if (!PyArg_ParseTuple(args,(char *)"O:layerObj_getFilterString",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_setProjection" "', argument " "1"" of type '" "layerObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_getFilterString" "', argument " "1"" of type '" "layerObj *""'"); 
   }
   arg1 = (layerObj *)(argp1);
   {
-    result = (int)layerObj_setProjection(arg1,arg2); {
+    result = (char *)layerObj_getFilterString(arg1); {
       errorObj *ms_error = msGetErrorObj();
       
       switch(ms_error->code) {
@@ -24762,38 +26424,31 @@ SWIGINTERN PyObject *_wrap_layerObj_setProjection(PyObject *SWIGUNUSEDPARM(self)
       
     }
   }
-  resultobj = SWIG_From_int((int)(result));
+  resultobj = SWIG_FromCharPtr((const char *)result);
+  free((char*)result);
   return resultobj;
 fail:
   return NULL;
 }
 
 
-SWIGINTERN PyObject *_wrap_layerObj_addFeature(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_layerObj_setWKTProjection(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   layerObj *arg1 = (layerObj *) 0 ;
-  shapeObj *arg2 = (shapeObj *) 0 ;
+  char *arg2 = (char *) 0 ;
   void *argp1 = 0 ;
   int res1 = 0 ;
-  void *argp2 = 0 ;
-  int res2 = 0 ;
   PyObject * obj0 = 0 ;
-  PyObject * obj1 = 0 ;
   int result;
   
-  if (!PyArg_ParseTuple(args,(char *)"OO:layerObj_addFeature",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  if (!PyArg_ParseTuple(args,(char *)"Oz:layerObj_setWKTProjection",&obj0,&arg2)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_addFeature" "', argument " "1"" of type '" "layerObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_setWKTProjection" "', argument " "1"" of type '" "layerObj *""'"); 
   }
   arg1 = (layerObj *)(argp1);
-  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_shapeObj, 0 |  0 );
-  if (!SWIG_IsOK(res2)) {
-    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "layerObj_addFeature" "', argument " "2"" of type '" "shapeObj *""'"); 
-  }
-  arg2 = (shapeObj *)(argp2);
   {
-    result = (int)layerObj_addFeature(arg1,arg2); {
+    result = (int)layerObj_setWKTProjection(arg1,arg2); {
       errorObj *ms_error = msGetErrorObj();
       
       switch(ms_error->code) {
@@ -24825,22 +26480,174 @@ fail:
 }
 
 
-SWIGINTERN PyObject *_wrap_layerObj_getNumFeatures(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_layerObj_getProjection(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   layerObj *arg1 = (layerObj *) 0 ;
   void *argp1 = 0 ;
   int res1 = 0 ;
   PyObject * obj0 = 0 ;
-  int result;
+  char *result = 0 ;
   
-  if (!PyArg_ParseTuple(args,(char *)"O:layerObj_getNumFeatures",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  if (!PyArg_ParseTuple(args,(char *)"O:layerObj_getProjection",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_getNumFeatures" "', argument " "1"" of type '" "layerObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_getProjection" "', argument " "1"" of type '" "layerObj *""'"); 
   }
   arg1 = (layerObj *)(argp1);
   {
-    result = (int)layerObj_getNumFeatures(arg1); {
+    result = (char *)layerObj_getProjection(arg1); {
+      errorObj *ms_error = msGetErrorObj();
+      
+      switch(ms_error->code) {
+      case MS_NOERR:
+        break;
+      case MS_NOTFOUND:
+        msResetErrorList();
+        break;
+      case -1:
+        break;
+      case MS_IOERR:
+        if (strcmp(ms_error->routine, "msSearchDiskTree()") != 0) {
+          _raise_ms_exception();
+          msResetErrorList();
+          return NULL;
+        }
+      default:
+        _raise_ms_exception();
+        msResetErrorList();
+        return NULL;
+      }
+      
+    }
+  }
+  resultobj = SWIG_FromCharPtr((const char *)result);
+  free((char*)result);
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_layerObj_setProjection(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  layerObj *arg1 = (layerObj *) 0 ;
+  char *arg2 = (char *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  int result;
+  
+  if (!PyArg_ParseTuple(args,(char *)"Oz:layerObj_setProjection",&obj0,&arg2)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_setProjection" "', argument " "1"" of type '" "layerObj *""'"); 
+  }
+  arg1 = (layerObj *)(argp1);
+  {
+    result = (int)layerObj_setProjection(arg1,arg2); {
+      errorObj *ms_error = msGetErrorObj();
+      
+      switch(ms_error->code) {
+      case MS_NOERR:
+        break;
+      case MS_NOTFOUND:
+        msResetErrorList();
+        break;
+      case -1:
+        break;
+      case MS_IOERR:
+        if (strcmp(ms_error->routine, "msSearchDiskTree()") != 0) {
+          _raise_ms_exception();
+          msResetErrorList();
+          return NULL;
+        }
+      default:
+        _raise_ms_exception();
+        msResetErrorList();
+        return NULL;
+      }
+      
+    }
+  }
+  resultobj = SWIG_From_int((int)(result));
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_layerObj_addFeature(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  layerObj *arg1 = (layerObj *) 0 ;
+  shapeObj *arg2 = (shapeObj *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  void *argp2 = 0 ;
+  int res2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  int result;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:layerObj_addFeature",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_addFeature" "', argument " "1"" of type '" "layerObj *""'"); 
+  }
+  arg1 = (layerObj *)(argp1);
+  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_shapeObj, 0 |  0 );
+  if (!SWIG_IsOK(res2)) {
+    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "layerObj_addFeature" "', argument " "2"" of type '" "shapeObj *""'"); 
+  }
+  arg2 = (shapeObj *)(argp2);
+  {
+    result = (int)layerObj_addFeature(arg1,arg2); {
+      errorObj *ms_error = msGetErrorObj();
+      
+      switch(ms_error->code) {
+      case MS_NOERR:
+        break;
+      case MS_NOTFOUND:
+        msResetErrorList();
+        break;
+      case -1:
+        break;
+      case MS_IOERR:
+        if (strcmp(ms_error->routine, "msSearchDiskTree()") != 0) {
+          _raise_ms_exception();
+          msResetErrorList();
+          return NULL;
+        }
+      default:
+        _raise_ms_exception();
+        msResetErrorList();
+        return NULL;
+      }
+      
+    }
+  }
+  resultobj = SWIG_From_int((int)(result));
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_layerObj_getNumFeatures(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  layerObj *arg1 = (layerObj *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  int result;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:layerObj_getNumFeatures",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_getNumFeatures" "', argument " "1"" of type '" "layerObj *""'"); 
+  }
+  arg1 = (layerObj *)(argp1);
+  {
+    result = (int)layerObj_getNumFeatures(arg1); {
       errorObj *ms_error = msGetErrorObj();
       
       switch(ms_error->code) {
@@ -24881,7 +26688,7 @@ SWIGINTERN PyObject *_wrap_layerObj_getExtent(PyObject *SWIGUNUSEDPARM(self), Py
   rectObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_getExtent",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_getExtent" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -24944,7 +26751,7 @@ SWIGINTERN PyObject *_wrap_layerObj_setExtent(PyObject *SWIGUNUSEDPARM(self), Py
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"O|OOOO:layerObj_setExtent",&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_setExtent" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -25020,7 +26827,7 @@ SWIGINTERN PyObject *_wrap_layerObj_getMetaData(PyObject *SWIGUNUSEDPARM(self),
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:layerObj_getMetaData",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_getMetaData" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -25069,7 +26876,7 @@ SWIGINTERN PyObject *_wrap_layerObj_setMetaData(PyObject *SWIGUNUSEDPARM(self),
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"Ozz:layerObj_setMetaData",&obj0,&arg2,&arg3)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_setMetaData" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -25117,7 +26924,7 @@ SWIGINTERN PyObject *_wrap_layerObj_removeMetaData(PyObject *SWIGUNUSEDPARM(self
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:layerObj_removeMetaData",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_removeMetaData" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -25164,7 +26971,7 @@ SWIGINTERN PyObject *_wrap_layerObj_getFirstMetaDataKey(PyObject *SWIGUNUSEDPARM
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_getFirstMetaDataKey",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_getFirstMetaDataKey" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -25212,7 +27019,7 @@ SWIGINTERN PyObject *_wrap_layerObj_getNextMetaDataKey(PyObject *SWIGUNUSEDPARM(
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:layerObj_getNextMetaDataKey",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_getNextMetaDataKey" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -25276,12 +27083,12 @@ SWIGINTERN PyObject *_wrap_layerObj_getWMSFeatureInfoURL(PyObject *SWIGUNUSEDPAR
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OOOOOz:layerObj_getWMSFeatureInfoURL",&obj0,&obj1,&obj2,&obj3,&obj4,&arg6)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_getWMSFeatureInfoURL" "', argument " "1"" of type '" "layerObj *""'"); 
   }
   arg1 = (layerObj *)(argp1);
-  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_map_obj, 0 |  0 );
+  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res2)) {
     SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "layerObj_getWMSFeatureInfoURL" "', argument " "2"" of type '" "mapObj *""'"); 
   }
@@ -25348,12 +27155,12 @@ SWIGINTERN PyObject *_wrap_layerObj_executeWFSGetFeature(PyObject *SWIGUNUSEDPAR
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:layerObj_executeWFSGetFeature",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_executeWFSGetFeature" "', argument " "1"" of type '" "layerObj *""'"); 
   }
   arg1 = (layerObj *)(argp1);
-  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res2)) {
     SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "layerObj_executeWFSGetFeature" "', argument " "2"" of type '" "layerObj *""'"); 
   }
@@ -25403,7 +27210,7 @@ SWIGINTERN PyObject *_wrap_layerObj_applySLD(PyObject *SWIGUNUSEDPARM(self), PyO
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"Ozz:layerObj_applySLD",&obj0,&arg2,&arg3)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_applySLD" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -25452,7 +27259,7 @@ SWIGINTERN PyObject *_wrap_layerObj_applySLDURL(PyObject *SWIGUNUSEDPARM(self),
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"Ozz:layerObj_applySLDURL",&obj0,&arg2,&arg3)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_applySLDURL" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -25499,7 +27306,7 @@ SWIGINTERN PyObject *_wrap_layerObj_generateSLD(PyObject *SWIGUNUSEDPARM(self),
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_generateSLD",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_generateSLD" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -25547,7 +27354,7 @@ SWIGINTERN PyObject *_wrap_layerObj_isVisible(PyObject *SWIGUNUSEDPARM(self), Py
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_isVisible",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_isVisible" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -25598,7 +27405,7 @@ SWIGINTERN PyObject *_wrap_layerObj_moveClassUp(PyObject *SWIGUNUSEDPARM(self),
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:layerObj_moveClassUp",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_moveClassUp" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -25654,7 +27461,7 @@ SWIGINTERN PyObject *_wrap_layerObj_moveClassDown(PyObject *SWIGUNUSEDPARM(self)
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:layerObj_moveClassDown",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_moveClassDown" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -25715,7 +27522,7 @@ SWIGINTERN PyObject *_wrap_layerObj_setProcessingKey(PyObject *SWIGUNUSEDPARM(se
   PyObject * obj2 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OOO:layerObj_setProcessingKey",&obj0,&obj1,&obj2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_setProcessingKey" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -25780,7 +27587,7 @@ SWIGINTERN PyObject *_wrap_layerObj_setProcessing(PyObject *SWIGUNUSEDPARM(self)
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:layerObj_setProcessing",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_setProcessing" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -25838,7 +27645,7 @@ SWIGINTERN PyObject *_wrap_layerObj_addProcessing(PyObject *SWIGUNUSEDPARM(self)
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:layerObj_addProcessing",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_addProcessing" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -25896,7 +27703,7 @@ SWIGINTERN PyObject *_wrap_layerObj_getProcessing(PyObject *SWIGUNUSEDPARM(self)
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:layerObj_getProcessing",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_getProcessing" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -25953,7 +27760,7 @@ SWIGINTERN PyObject *_wrap_layerObj_getProcessingKey(PyObject *SWIGUNUSEDPARM(se
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:layerObj_getProcessingKey",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_getProcessingKey" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -26007,7 +27814,7 @@ SWIGINTERN PyObject *_wrap_layerObj_clearProcessing(PyObject *SWIGUNUSEDPARM(sel
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:layerObj_clearProcessing",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_clearProcessing" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -26063,7 +27870,7 @@ SWIGINTERN PyObject *_wrap_layerObj_setConnectionType(PyObject *SWIGUNUSEDPARM(s
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"OOO:layerObj_setConnectionType",&obj0,&obj1,&obj2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_setConnectionType" "', argument " "1"" of type '" "layerObj *""'"); 
   }
@@ -26138,12 +27945,12 @@ SWIGINTERN PyObject *_wrap_layerObj_getClassIndex(PyObject *SWIGUNUSEDPARM(self)
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"OOO|OO:layerObj_getClassIndex",&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "layerObj_getClassIndex" "', argument " "1"" of type '" "layerObj *""'"); 
   }
   arg1 = (layerObj *)(argp1);
-  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_map_obj, 0 |  0 );
+  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res2)) {
     SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "layerObj_getClassIndex" "', argument " "2"" of type '" "mapObj *""'"); 
   }
@@ -26203,7 +28010,7 @@ fail:
 SWIGINTERN PyObject *layerObj_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *obj;
   if (!PyArg_ParseTuple(args,(char*)"O:swigregister", &obj)) return NULL;
-  SWIG_TypeNewClientData(SWIGTYPE_p_layer_obj, SWIG_NewClientData(obj));
+  SWIG_TypeNewClientData(SWIGTYPE_p_layerObj, SWIG_NewClientData(obj));
   return SWIG_Py_Void();
 }
 
@@ -26216,7 +28023,7 @@ SWIGINTERN PyObject *_wrap_mapObj_name_set(PyObject *SWIGUNUSEDPARM(self), PyObj
   PyObject * obj0 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:mapObj_name_set",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_name_set" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -26246,7 +28053,7 @@ SWIGINTERN PyObject *_wrap_mapObj_name_get(PyObject *SWIGUNUSEDPARM(self), PyObj
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_name_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_name_get" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -26271,7 +28078,7 @@ SWIGINTERN PyObject *_wrap_mapObj_status_set(PyObject *SWIGUNUSEDPARM(self), PyO
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:mapObj_status_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_status_set" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -26298,7 +28105,7 @@ SWIGINTERN PyObject *_wrap_mapObj_status_get(PyObject *SWIGUNUSEDPARM(self), PyO
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_status_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_status_get" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -26323,7 +28130,7 @@ SWIGINTERN PyObject *_wrap_mapObj_height_set(PyObject *SWIGUNUSEDPARM(self), PyO
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:mapObj_height_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_height_set" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -26350,7 +28157,7 @@ SWIGINTERN PyObject *_wrap_mapObj_height_get(PyObject *SWIGUNUSEDPARM(self), PyO
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_height_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_height_get" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -26375,7 +28182,7 @@ SWIGINTERN PyObject *_wrap_mapObj_width_set(PyObject *SWIGUNUSEDPARM(self), PyOb
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:mapObj_width_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_width_set" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -26402,7 +28209,7 @@ SWIGINTERN PyObject *_wrap_mapObj_width_get(PyObject *SWIGUNUSEDPARM(self), PyOb
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_width_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_width_get" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -26427,7 +28234,7 @@ SWIGINTERN PyObject *_wrap_mapObj_maxsize_set(PyObject *SWIGUNUSEDPARM(self), Py
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:mapObj_maxsize_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_maxsize_set" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -26454,7 +28261,7 @@ SWIGINTERN PyObject *_wrap_mapObj_maxsize_get(PyObject *SWIGUNUSEDPARM(self), Py
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_maxsize_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_maxsize_get" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -26476,7 +28283,7 @@ SWIGINTERN PyObject *_wrap_mapObj_refcount_get(PyObject *SWIGUNUSEDPARM(self), P
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_refcount_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_refcount_get" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -26498,7 +28305,7 @@ SWIGINTERN PyObject *_wrap_mapObj_numlayers_get(PyObject *SWIGUNUSEDPARM(self),
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_numlayers_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_numlayers_get" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -26520,7 +28327,7 @@ SWIGINTERN PyObject *_wrap_mapObj_maxlayers_get(PyObject *SWIGUNUSEDPARM(self),
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_maxlayers_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_maxlayers_get" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -26542,7 +28349,7 @@ SWIGINTERN PyObject *_wrap_mapObj_symbolset_get(PyObject *SWIGUNUSEDPARM(self),
   symbolSetObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_symbolset_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_symbolset_get" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -26564,7 +28371,7 @@ SWIGINTERN PyObject *_wrap_mapObj_fontset_get(PyObject *SWIGUNUSEDPARM(self), Py
   fontSetObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_fontset_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_fontset_get" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -26586,7 +28393,7 @@ SWIGINTERN PyObject *_wrap_mapObj_labelcache_get(PyObject *SWIGUNUSEDPARM(self),
   labelCacheObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_labelcache_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_labelcache_get" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -26611,7 +28418,7 @@ SWIGINTERN PyObject *_wrap_mapObj_transparent_set(PyObject *SWIGUNUSEDPARM(self)
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:mapObj_transparent_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_transparent_set" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -26638,7 +28445,7 @@ SWIGINTERN PyObject *_wrap_mapObj_transparent_get(PyObject *SWIGUNUSEDPARM(self)
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_transparent_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_transparent_get" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -26663,7 +28470,7 @@ SWIGINTERN PyObject *_wrap_mapObj_interlace_set(PyObject *SWIGUNUSEDPARM(self),
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:mapObj_interlace_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_interlace_set" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -26690,7 +28497,7 @@ SWIGINTERN PyObject *_wrap_mapObj_interlace_get(PyObject *SWIGUNUSEDPARM(self),
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_interlace_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_interlace_get" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -26715,7 +28522,7 @@ SWIGINTERN PyObject *_wrap_mapObj_imagequality_set(PyObject *SWIGUNUSEDPARM(self
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:mapObj_imagequality_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_imagequality_set" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -26742,7 +28549,7 @@ SWIGINTERN PyObject *_wrap_mapObj_imagequality_get(PyObject *SWIGUNUSEDPARM(self
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_imagequality_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_imagequality_get" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -26767,7 +28574,7 @@ SWIGINTERN PyObject *_wrap_mapObj_extent_set(PyObject *SWIGUNUSEDPARM(self), PyO
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:mapObj_extent_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_extent_set" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -26794,7 +28601,7 @@ SWIGINTERN PyObject *_wrap_mapObj_extent_get(PyObject *SWIGUNUSEDPARM(self), PyO
   rectObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_extent_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_extent_get" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -26819,7 +28626,7 @@ SWIGINTERN PyObject *_wrap_mapObj_cellsize_set(PyObject *SWIGUNUSEDPARM(self), P
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:mapObj_cellsize_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_cellsize_set" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -26846,7 +28653,7 @@ SWIGINTERN PyObject *_wrap_mapObj_cellsize_get(PyObject *SWIGUNUSEDPARM(self), P
   double result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_cellsize_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_cellsize_get" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -26871,7 +28678,7 @@ SWIGINTERN PyObject *_wrap_mapObj_units_set(PyObject *SWIGUNUSEDPARM(self), PyOb
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:mapObj_units_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_units_set" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -26898,7 +28705,7 @@ SWIGINTERN PyObject *_wrap_mapObj_units_get(PyObject *SWIGUNUSEDPARM(self), PyOb
   enum MS_UNITS result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_units_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_units_get" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -26923,7 +28730,7 @@ SWIGINTERN PyObject *_wrap_mapObj_scaledenom_set(PyObject *SWIGUNUSEDPARM(self),
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:mapObj_scaledenom_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_scaledenom_set" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -26950,7 +28757,7 @@ SWIGINTERN PyObject *_wrap_mapObj_scaledenom_get(PyObject *SWIGUNUSEDPARM(self),
   double result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_scaledenom_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_scaledenom_get" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -26975,7 +28782,7 @@ SWIGINTERN PyObject *_wrap_mapObj_resolution_set(PyObject *SWIGUNUSEDPARM(self),
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:mapObj_resolution_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_resolution_set" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -27002,7 +28809,7 @@ SWIGINTERN PyObject *_wrap_mapObj_resolution_get(PyObject *SWIGUNUSEDPARM(self),
   double result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_resolution_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_resolution_get" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -27027,7 +28834,7 @@ SWIGINTERN PyObject *_wrap_mapObj_defresolution_set(PyObject *SWIGUNUSEDPARM(sel
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:mapObj_defresolution_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_defresolution_set" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -27054,7 +28861,7 @@ SWIGINTERN PyObject *_wrap_mapObj_defresolution_get(PyObject *SWIGUNUSEDPARM(sel
   double result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_defresolution_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_defresolution_get" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -27076,7 +28883,7 @@ SWIGINTERN PyObject *_wrap_mapObj_shapepath_set(PyObject *SWIGUNUSEDPARM(self),
   PyObject * obj0 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:mapObj_shapepath_set",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_shapepath_set" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -27106,7 +28913,7 @@ SWIGINTERN PyObject *_wrap_mapObj_shapepath_get(PyObject *SWIGUNUSEDPARM(self),
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_shapepath_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_shapepath_get" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -27128,7 +28935,7 @@ SWIGINTERN PyObject *_wrap_mapObj_mappath_set(PyObject *SWIGUNUSEDPARM(self), Py
   PyObject * obj0 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:mapObj_mappath_set",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_mappath_set" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -27158,7 +28965,7 @@ SWIGINTERN PyObject *_wrap_mapObj_mappath_get(PyObject *SWIGUNUSEDPARM(self), Py
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_mappath_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_mappath_get" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -27183,7 +28990,7 @@ SWIGINTERN PyObject *_wrap_mapObj_imagecolor_set(PyObject *SWIGUNUSEDPARM(self),
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:mapObj_imagecolor_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_imagecolor_set" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -27210,7 +29017,7 @@ SWIGINTERN PyObject *_wrap_mapObj_imagecolor_get(PyObject *SWIGUNUSEDPARM(self),
   colorObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_imagecolor_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_imagecolor_get" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -27232,7 +29039,7 @@ SWIGINTERN PyObject *_wrap_mapObj_numoutputformats_get(PyObject *SWIGUNUSEDPARM(
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_numoutputformats_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_numoutputformats_get" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -27254,7 +29061,7 @@ SWIGINTERN PyObject *_wrap_mapObj_outputformatlist_get(PyObject *SWIGUNUSEDPARM(
   outputFormatObj **result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_outputformatlist_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_outputformatlist_get" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -27276,7 +29083,7 @@ SWIGINTERN PyObject *_wrap_mapObj_outputformat_get(PyObject *SWIGUNUSEDPARM(self
   outputFormatObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_outputformat_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_outputformat_get" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -27298,7 +29105,7 @@ SWIGINTERN PyObject *_wrap_mapObj_imagetype_get(PyObject *SWIGUNUSEDPARM(self),
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_imagetype_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_imagetype_get" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -27320,7 +29127,7 @@ SWIGINTERN PyObject *_wrap_mapObj_reference_get(PyObject *SWIGUNUSEDPARM(self),
   referenceMapObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_reference_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_reference_get" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -27342,7 +29149,7 @@ SWIGINTERN PyObject *_wrap_mapObj_scalebar_get(PyObject *SWIGUNUSEDPARM(self), P
   scalebarObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_scalebar_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_scalebar_get" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -27364,7 +29171,7 @@ SWIGINTERN PyObject *_wrap_mapObj_legend_get(PyObject *SWIGUNUSEDPARM(self), PyO
   legendObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_legend_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_legend_get" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -27386,7 +29193,7 @@ SWIGINTERN PyObject *_wrap_mapObj_querymap_get(PyObject *SWIGUNUSEDPARM(self), P
   queryMapObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_querymap_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_querymap_get" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -27408,7 +29215,7 @@ SWIGINTERN PyObject *_wrap_mapObj_web_get(PyObject *SWIGUNUSEDPARM(self), PyObje
   webObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_web_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_web_get" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -27433,7 +29240,7 @@ SWIGINTERN PyObject *_wrap_mapObj_layerorder_set(PyObject *SWIGUNUSEDPARM(self),
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:mapObj_layerorder_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_layerorder_set" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -27460,7 +29267,7 @@ SWIGINTERN PyObject *_wrap_mapObj_layerorder_get(PyObject *SWIGUNUSEDPARM(self),
   int *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_layerorder_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_layerorder_get" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -27485,7 +29292,7 @@ SWIGINTERN PyObject *_wrap_mapObj_debug_set(PyObject *SWIGUNUSEDPARM(self), PyOb
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:mapObj_debug_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_debug_set" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -27512,7 +29319,7 @@ SWIGINTERN PyObject *_wrap_mapObj_debug_get(PyObject *SWIGUNUSEDPARM(self), PyOb
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_debug_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_debug_get" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -27534,7 +29341,7 @@ SWIGINTERN PyObject *_wrap_mapObj_datapattern_set(PyObject *SWIGUNUSEDPARM(self)
   PyObject * obj0 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:mapObj_datapattern_set",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_datapattern_set" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -27564,7 +29371,7 @@ SWIGINTERN PyObject *_wrap_mapObj_datapattern_get(PyObject *SWIGUNUSEDPARM(self)
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_datapattern_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_datapattern_get" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -27586,7 +29393,7 @@ SWIGINTERN PyObject *_wrap_mapObj_templatepattern_set(PyObject *SWIGUNUSEDPARM(s
   PyObject * obj0 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:mapObj_templatepattern_set",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_templatepattern_set" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -27616,7 +29423,7 @@ SWIGINTERN PyObject *_wrap_mapObj_templatepattern_get(PyObject *SWIGUNUSEDPARM(s
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_templatepattern_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_templatepattern_get" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -27638,7 +29445,7 @@ SWIGINTERN PyObject *_wrap_mapObj_configoptions_get(PyObject *SWIGUNUSEDPARM(sel
   hashTableObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_configoptions_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_configoptions_get" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -27683,7 +29490,7 @@ SWIGINTERN PyObject *_wrap_new_mapObj(PyObject *SWIGUNUSEDPARM(self), PyObject *
       
     }
   }
-  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_map_obj, SWIG_POINTER_NEW |  0 );
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_mapObj, SWIG_POINTER_NEW |  0 );
   return resultobj;
 fail:
   return NULL;
@@ -27698,7 +29505,7 @@ SWIGINTERN PyObject *_wrap_delete_mapObj(PyObject *SWIGUNUSEDPARM(self), PyObjec
   PyObject * obj0 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:delete_mapObj",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, SWIG_POINTER_DISOWN |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, SWIG_POINTER_DISOWN |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_mapObj" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -27745,7 +29552,7 @@ SWIGINTERN PyObject *_wrap_mapObj_clone(PyObject *SWIGUNUSEDPARM(self), PyObject
   mapObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_clone",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_clone" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -27776,7 +29583,7 @@ SWIGINTERN PyObject *_wrap_mapObj_clone(PyObject *SWIGUNUSEDPARM(self), PyObject
       
     }
   }
-  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_map_obj, SWIG_POINTER_OWN |  0 );
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_mapObj, SWIG_POINTER_OWN |  0 );
   return resultobj;
 fail:
   return NULL;
@@ -27800,12 +29607,12 @@ SWIGINTERN PyObject *_wrap_mapObj_insertLayer(PyObject *SWIGUNUSEDPARM(self), Py
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"OO|O:mapObj_insertLayer",&obj0,&obj1,&obj2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_insertLayer" "', argument " "1"" of type '" "mapObj *""'"); 
   }
   arg1 = (mapObj *)(argp1);
-  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res2)) {
     SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "mapObj_insertLayer" "', argument " "2"" of type '" "layerObj *""'"); 
   }
@@ -27863,7 +29670,7 @@ SWIGINTERN PyObject *_wrap_mapObj_removeLayer(PyObject *SWIGUNUSEDPARM(self), Py
   layerObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:mapObj_removeLayer",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_removeLayer" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -27899,7 +29706,7 @@ SWIGINTERN PyObject *_wrap_mapObj_removeLayer(PyObject *SWIGUNUSEDPARM(self), Py
       
     }
   }
-  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_layer_obj, SWIG_POINTER_OWN |  0 );
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_layerObj, SWIG_POINTER_OWN |  0 );
   return resultobj;
 fail:
   return NULL;
@@ -27931,7 +29738,7 @@ SWIGINTERN PyObject *_wrap_mapObj_setExtent(PyObject *SWIGUNUSEDPARM(self), PyOb
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"OOOOO:mapObj_setExtent",&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_setExtent" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -28006,7 +29813,7 @@ SWIGINTERN PyObject *_wrap_mapObj_offsetExtent(PyObject *SWIGUNUSEDPARM(self), P
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"OOO:mapObj_offsetExtent",&obj0,&obj1,&obj2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_offsetExtent" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -28075,7 +29882,7 @@ SWIGINTERN PyObject *_wrap_mapObj_scaleExtent(PyObject *SWIGUNUSEDPARM(self), Py
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"OOOO:mapObj_scaleExtent",&obj0,&obj1,&obj2,&obj3)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_scaleExtent" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -28141,7 +29948,7 @@ SWIGINTERN PyObject *_wrap_mapObj_setCenter(PyObject *SWIGUNUSEDPARM(self), PyOb
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:mapObj_setCenter",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_setCenter" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -28201,7 +30008,7 @@ SWIGINTERN PyObject *_wrap_mapObj_setSize(PyObject *SWIGUNUSEDPARM(self), PyObje
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"OOO:mapObj_setSize",&obj0,&obj1,&obj2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_setSize" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -28262,7 +30069,7 @@ SWIGINTERN PyObject *_wrap_mapObj_setRotation(PyObject *SWIGUNUSEDPARM(self), Py
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:mapObj_setRotation",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_setRotation" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -28318,7 +30125,7 @@ SWIGINTERN PyObject *_wrap_mapObj_getLayer(PyObject *SWIGUNUSEDPARM(self), PyObj
   layerObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:mapObj_getLayer",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_getLayer" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -28354,7 +30161,7 @@ SWIGINTERN PyObject *_wrap_mapObj_getLayer(PyObject *SWIGUNUSEDPARM(self), PyObj
       
     }
   }
-  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_layer_obj, SWIG_POINTER_OWN |  0 );
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_layerObj, SWIG_POINTER_OWN |  0 );
   return resultobj;
 fail:
   return NULL;
@@ -28371,7 +30178,7 @@ SWIGINTERN PyObject *_wrap_mapObj_getLayerByName(PyObject *SWIGUNUSEDPARM(self),
   layerObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:mapObj_getLayerByName",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_getLayerByName" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -28402,7 +30209,7 @@ SWIGINTERN PyObject *_wrap_mapObj_getLayerByName(PyObject *SWIGUNUSEDPARM(self),
       
     }
   }
-  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_layer_obj, SWIG_POINTER_OWN |  0 );
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_layerObj, SWIG_POINTER_OWN |  0 );
   return resultobj;
 fail:
   return NULL;
@@ -28419,7 +30226,7 @@ SWIGINTERN PyObject *_wrap_mapObj_getSymbolByName(PyObject *SWIGUNUSEDPARM(self)
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:mapObj_getSymbolByName",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_getSymbolByName" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -28465,7 +30272,7 @@ SWIGINTERN PyObject *_wrap_mapObj_prepareQuery(PyObject *SWIGUNUSEDPARM(self), P
   PyObject * obj0 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_prepareQuery",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_prepareQuery" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -28512,7 +30319,7 @@ SWIGINTERN PyObject *_wrap_mapObj_prepareImage(PyObject *SWIGUNUSEDPARM(self), P
   imageObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_prepareImage",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_prepareImage" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -28559,7 +30366,7 @@ SWIGINTERN PyObject *_wrap_mapObj_setImageType(PyObject *SWIGUNUSEDPARM(self), P
   PyObject * obj0 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:mapObj_setImageType",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_setImageType" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -28606,7 +30413,7 @@ SWIGINTERN PyObject *_wrap_mapObj_selectOutputFormat(PyObject *SWIGUNUSEDPARM(se
   PyObject * obj0 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:mapObj_selectOutputFormat",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_selectOutputFormat" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -28656,7 +30463,7 @@ SWIGINTERN PyObject *_wrap_mapObj_setOutputFormat(PyObject *SWIGUNUSEDPARM(self)
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:mapObj_setOutputFormat",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_setOutputFormat" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -28708,7 +30515,7 @@ SWIGINTERN PyObject *_wrap_mapObj_draw(PyObject *SWIGUNUSEDPARM(self), PyObject
   imageObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_draw",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_draw" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -28755,7 +30562,7 @@ SWIGINTERN PyObject *_wrap_mapObj_drawQuery(PyObject *SWIGUNUSEDPARM(self), PyOb
   imageObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_drawQuery",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_drawQuery" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -28802,7 +30609,7 @@ SWIGINTERN PyObject *_wrap_mapObj_drawLegend(PyObject *SWIGUNUSEDPARM(self), PyO
   imageObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_drawLegend",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_drawLegend" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -28849,7 +30656,7 @@ SWIGINTERN PyObject *_wrap_mapObj_drawScalebar(PyObject *SWIGUNUSEDPARM(self), P
   imageObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_drawScalebar",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_drawScalebar" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -28896,7 +30703,7 @@ SWIGINTERN PyObject *_wrap_mapObj_drawReferenceMap(PyObject *SWIGUNUSEDPARM(self
   imageObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_drawReferenceMap",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_drawReferenceMap" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -28947,7 +30754,7 @@ SWIGINTERN PyObject *_wrap_mapObj_embedScalebar(PyObject *SWIGUNUSEDPARM(self),
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:mapObj_embedScalebar",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_embedScalebar" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -29003,7 +30810,7 @@ SWIGINTERN PyObject *_wrap_mapObj_embedLegend(PyObject *SWIGUNUSEDPARM(self), Py
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:mapObj_embedLegend",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_embedLegend" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -29059,7 +30866,7 @@ SWIGINTERN PyObject *_wrap_mapObj_drawLabelCache(PyObject *SWIGUNUSEDPARM(self),
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:mapObj_drawLabelCache",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_drawLabelCache" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -29115,7 +30922,7 @@ SWIGINTERN PyObject *_wrap_mapObj_getLabel(PyObject *SWIGUNUSEDPARM(self), PyObj
   labelCacheMemberObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:mapObj_getLabel",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_getLabel" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -29167,7 +30974,7 @@ SWIGINTERN PyObject *_wrap_mapObj_nextLabel(PyObject *SWIGUNUSEDPARM(self), PyOb
   labelCacheMemberObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_nextLabel",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_nextLabel" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -29215,7 +31022,7 @@ SWIGINTERN PyObject *_wrap_mapObj_queryByFilter(PyObject *SWIGUNUSEDPARM(self),
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:mapObj_queryByFilter",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_queryByFilter" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -29274,7 +31081,7 @@ SWIGINTERN PyObject *_wrap_mapObj_queryByPoint(PyObject *SWIGUNUSEDPARM(self), P
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"OOOO:mapObj_queryByPoint",&obj0,&obj1,&obj2,&obj3)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_queryByPoint" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -29340,7 +31147,7 @@ SWIGINTERN PyObject *_wrap_mapObj_queryByRect(PyObject *SWIGUNUSEDPARM(self), Py
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:mapObj_queryByRect",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_queryByRect" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -29402,7 +31209,7 @@ SWIGINTERN PyObject *_wrap_mapObj_queryByFeatures(PyObject *SWIGUNUSEDPARM(self)
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:mapObj_queryByFeatures",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_queryByFeatures" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -29458,7 +31265,7 @@ SWIGINTERN PyObject *_wrap_mapObj_queryByShape(PyObject *SWIGUNUSEDPARM(self), P
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:mapObj_queryByShape",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_queryByShape" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -29511,7 +31318,7 @@ SWIGINTERN PyObject *_wrap_mapObj_setWKTProjection(PyObject *SWIGUNUSEDPARM(self
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:mapObj_setWKTProjection",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_setWKTProjection" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -29558,7 +31365,7 @@ SWIGINTERN PyObject *_wrap_mapObj_getProjection(PyObject *SWIGUNUSEDPARM(self),
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_getProjection",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_getProjection" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -29607,7 +31414,7 @@ SWIGINTERN PyObject *_wrap_mapObj_setProjection(PyObject *SWIGUNUSEDPARM(self),
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:mapObj_setProjection",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_setProjection" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -29655,7 +31462,7 @@ SWIGINTERN PyObject *_wrap_mapObj_save(PyObject *SWIGUNUSEDPARM(self), PyObject
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:mapObj_save",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_save" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -29707,7 +31514,7 @@ SWIGINTERN PyObject *_wrap_mapObj_saveQuery(PyObject *SWIGUNUSEDPARM(self), PyOb
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz|O:mapObj_saveQuery",&obj0,&arg2,&obj2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_saveQuery" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -29762,7 +31569,7 @@ SWIGINTERN PyObject *_wrap_mapObj_loadQuery(PyObject *SWIGUNUSEDPARM(self), PyOb
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:mapObj_loadQuery",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_loadQuery" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -29812,7 +31619,7 @@ SWIGINTERN PyObject *_wrap_mapObj_freeQuery(PyObject *SWIGUNUSEDPARM(self), PyOb
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O|O:mapObj_freeQuery",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_freeQuery" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -29872,7 +31679,7 @@ SWIGINTERN PyObject *_wrap_mapObj_saveQueryAsGML(PyObject *SWIGUNUSEDPARM(self),
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz|O:mapObj_saveQueryAsGML",&obj0,&arg2,&obj2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_saveQueryAsGML" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -29929,7 +31736,7 @@ SWIGINTERN PyObject *_wrap_mapObj_getMetaData(PyObject *SWIGUNUSEDPARM(self), Py
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:mapObj_getMetaData",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_getMetaData" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -29978,7 +31785,7 @@ SWIGINTERN PyObject *_wrap_mapObj_setMetaData(PyObject *SWIGUNUSEDPARM(self), Py
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"Ozz:mapObj_setMetaData",&obj0,&arg2,&arg3)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_setMetaData" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -30026,7 +31833,7 @@ SWIGINTERN PyObject *_wrap_mapObj_removeMetaData(PyObject *SWIGUNUSEDPARM(self),
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:mapObj_removeMetaData",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_removeMetaData" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -30073,7 +31880,7 @@ SWIGINTERN PyObject *_wrap_mapObj_getFirstMetaDataKey(PyObject *SWIGUNUSEDPARM(s
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_getFirstMetaDataKey",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_getFirstMetaDataKey" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -30121,7 +31928,7 @@ SWIGINTERN PyObject *_wrap_mapObj_getNextMetaDataKey(PyObject *SWIGUNUSEDPARM(se
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:mapObj_getNextMetaDataKey",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_getNextMetaDataKey" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -30169,7 +31976,7 @@ SWIGINTERN PyObject *_wrap_mapObj_setSymbolSet(PyObject *SWIGUNUSEDPARM(self), P
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:mapObj_setSymbolSet",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_setSymbolSet" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -30216,7 +32023,7 @@ SWIGINTERN PyObject *_wrap_mapObj_getNumSymbols(PyObject *SWIGUNUSEDPARM(self),
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_getNumSymbols",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_getNumSymbols" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -30264,7 +32071,7 @@ SWIGINTERN PyObject *_wrap_mapObj_setFontSet(PyObject *SWIGUNUSEDPARM(self), PyO
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:mapObj_setFontSet",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_setFontSet" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -30312,7 +32119,7 @@ SWIGINTERN PyObject *_wrap_mapObj_saveMapContext(PyObject *SWIGUNUSEDPARM(self),
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:mapObj_saveMapContext",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_saveMapContext" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -30364,7 +32171,7 @@ SWIGINTERN PyObject *_wrap_mapObj_loadMapContext(PyObject *SWIGUNUSEDPARM(self),
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz|O:mapObj_loadMapContext",&obj0,&arg2,&obj2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_loadMapContext" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -30422,7 +32229,7 @@ SWIGINTERN PyObject *_wrap_mapObj_moveLayerUp(PyObject *SWIGUNUSEDPARM(self), Py
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:mapObj_moveLayerUp",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_moveLayerUp" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -30478,7 +32285,7 @@ SWIGINTERN PyObject *_wrap_mapObj_moveLayerDown(PyObject *SWIGUNUSEDPARM(self),
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:mapObj_moveLayerDown",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_moveLayerDown" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -30530,7 +32337,7 @@ SWIGINTERN PyObject *_wrap_mapObj_getLayersDrawingOrder(PyObject *SWIGUNUSEDPARM
   intarray *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_getLayersDrawingOrder",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_getLayersDrawingOrder" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -30581,7 +32388,7 @@ SWIGINTERN PyObject *_wrap_mapObj_setLayersDrawingOrder(PyObject *SWIGUNUSEDPARM
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:mapObj_setLayersDrawingOrder",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_setLayersDrawingOrder" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -30634,7 +32441,7 @@ SWIGINTERN PyObject *_wrap_mapObj_setConfigOption(PyObject *SWIGUNUSEDPARM(self)
   PyObject * obj0 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"Ozz:mapObj_setConfigOption",&obj0,&arg2,&arg3)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_setConfigOption" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -30682,7 +32489,7 @@ SWIGINTERN PyObject *_wrap_mapObj_getConfigOption(PyObject *SWIGUNUSEDPARM(self)
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:mapObj_getConfigOption",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_getConfigOption" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -30728,7 +32535,7 @@ SWIGINTERN PyObject *_wrap_mapObj_applyConfigOptions(PyObject *SWIGUNUSEDPARM(se
   PyObject * obj0 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_applyConfigOptions",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_applyConfigOptions" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -30776,7 +32583,7 @@ SWIGINTERN PyObject *_wrap_mapObj_applySLD(PyObject *SWIGUNUSEDPARM(self), PyObj
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:mapObj_applySLD",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_applySLD" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -30824,7 +32631,7 @@ SWIGINTERN PyObject *_wrap_mapObj_applySLDURL(PyObject *SWIGUNUSEDPARM(self), Py
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:mapObj_applySLDURL",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_applySLDURL" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -30871,7 +32678,7 @@ SWIGINTERN PyObject *_wrap_mapObj_generateSLD(PyObject *SWIGUNUSEDPARM(self), Py
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_generateSLD",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_generateSLD" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -30935,7 +32742,7 @@ SWIGINTERN PyObject *_wrap_mapObj_processTemplate(PyObject *SWIGUNUSEDPARM(self)
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OOOOO:mapObj_processTemplate",&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_processTemplate" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -31015,7 +32822,7 @@ SWIGINTERN PyObject *_wrap_mapObj_processLegendTemplate(PyObject *SWIGUNUSEDPARM
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OOOO:mapObj_processLegendTemplate",&obj0,&obj1,&obj2,&obj3)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_processLegendTemplate" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -31090,7 +32897,7 @@ SWIGINTERN PyObject *_wrap_mapObj_processQueryTemplate(PyObject *SWIGUNUSEDPARM(
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OOOO:mapObj_processQueryTemplate",&obj0,&obj1,&obj2,&obj3)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_processQueryTemplate" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -31154,7 +32961,7 @@ SWIGINTERN PyObject *_wrap_mapObj_getOutputFormatByName(PyObject *SWIGUNUSEDPARM
   outputFormatObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:mapObj_getOutputFormatByName",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_getOutputFormatByName" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -31205,7 +33012,7 @@ SWIGINTERN PyObject *_wrap_mapObj_appendOutputFormat(PyObject *SWIGUNUSEDPARM(se
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:mapObj_appendOutputFormat",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_appendOutputFormat" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -31258,7 +33065,7 @@ SWIGINTERN PyObject *_wrap_mapObj_removeOutputFormat(PyObject *SWIGUNUSEDPARM(se
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"Oz:mapObj_removeOutputFormat",&obj0,&arg2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_removeOutputFormat" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -31310,7 +33117,7 @@ SWIGINTERN PyObject *_wrap_mapObj_loadOWSParameters(PyObject *SWIGUNUSEDPARM(sel
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"OO|z:mapObj_loadOWSParameters",&obj0,&obj1,&arg3)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_loadOWSParameters" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -31366,7 +33173,7 @@ SWIGINTERN PyObject *_wrap_mapObj_OWSDispatch(PyObject *SWIGUNUSEDPARM(self), Py
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:mapObj_OWSDispatch",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_OWSDispatch" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -31442,7 +33249,7 @@ SWIGINTERN PyObject *_wrap_mapObj_zoomPoint(PyObject *SWIGUNUSEDPARM(self), PyOb
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"OOOOOOO:mapObj_zoomPoint",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_zoomPoint" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -31539,7 +33346,7 @@ SWIGINTERN PyObject *_wrap_mapObj_zoomRectangle(PyObject *SWIGUNUSEDPARM(self),
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"OOOOOO:mapObj_zoomRectangle",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_zoomRectangle" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -31635,7 +33442,7 @@ SWIGINTERN PyObject *_wrap_mapObj_zoomScale(PyObject *SWIGUNUSEDPARM(self), PyOb
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"OOOOOOO:mapObj_zoomScale",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_zoomScale" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -31712,7 +33519,7 @@ SWIGINTERN PyObject *_wrap_mapObj_getLayerOrder(PyObject *SWIGUNUSEDPARM(self),
   PyObject *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_getLayerOrder",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_getLayerOrder" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -31761,7 +33568,7 @@ SWIGINTERN PyObject *_wrap_mapObj_setLayerOrder(PyObject *SWIGUNUSEDPARM(self),
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:mapObj_setLayerOrder",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_setLayerOrder" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -31809,7 +33616,7 @@ SWIGINTERN PyObject *_wrap_mapObj_getSize(PyObject *SWIGUNUSEDPARM(self), PyObje
   PyObject *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:mapObj_getSize",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "mapObj_getSize" "', argument " "1"" of type '" "mapObj *""'"); 
   }
@@ -31850,561 +33657,36 @@ fail:
 SWIGINTERN PyObject *mapObj_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *obj;
   if (!PyArg_ParseTuple(args,(char*)"O:swigregister", &obj)) return NULL;
-  SWIG_TypeNewClientData(SWIGTYPE_p_map_obj, SWIG_NewClientData(obj));
+  SWIG_TypeNewClientData(SWIGTYPE_p_mapObj, SWIG_NewClientData(obj));
   return SWIG_Py_Void();
 }
 
-SWIGINTERN PyObject *_wrap_imageObj_width_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
-  PyObject *resultobj = 0;
-  imageObj *arg1 = (imageObj *) 0 ;
-  void *argp1 = 0 ;
-  int res1 = 0 ;
-  PyObject * obj0 = 0 ;
-  int result;
-  
-  if (!PyArg_ParseTuple(args,(char *)"O:imageObj_width_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_imageObj, 0 |  0 );
-  if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "imageObj_width_get" "', argument " "1"" of type '" "imageObj *""'"); 
-  }
-  arg1 = (imageObj *)(argp1);
-  result = (int) ((arg1)->width);
-  resultobj = SWIG_From_int((int)(result));
-  return resultobj;
-fail:
-  return NULL;
-}
-
-
-SWIGINTERN PyObject *_wrap_imageObj_height_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_msSaveImage(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
-  imageObj *arg1 = (imageObj *) 0 ;
+  mapObj *arg1 = (mapObj *) 0 ;
+  imageObj *arg2 = (imageObj *) 0 ;
+  char *arg3 = (char *) 0 ;
   void *argp1 = 0 ;
   int res1 = 0 ;
+  void *argp2 = 0 ;
+  int res2 = 0 ;
   PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
   int result;
   
-  if (!PyArg_ParseTuple(args,(char *)"O:imageObj_height_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_imageObj, 0 |  0 );
-  if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "imageObj_height_get" "', argument " "1"" of type '" "imageObj *""'"); 
-  }
-  arg1 = (imageObj *)(argp1);
-  result = (int) ((arg1)->height);
-  resultobj = SWIG_From_int((int)(result));
-  return resultobj;
-fail:
-  return NULL;
-}
-
-
-SWIGINTERN PyObject *_wrap_imageObj_resolution_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
-  PyObject *resultobj = 0;
-  imageObj *arg1 = (imageObj *) 0 ;
-  void *argp1 = 0 ;
-  int res1 = 0 ;
-  PyObject * obj0 = 0 ;
-  double result;
-  
-  if (!PyArg_ParseTuple(args,(char *)"O:imageObj_resolution_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_imageObj, 0 |  0 );
-  if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "imageObj_resolution_get" "', argument " "1"" of type '" "imageObj *""'"); 
-  }
-  arg1 = (imageObj *)(argp1);
-  result = (double) ((arg1)->resolution);
-  resultobj = SWIG_From_double((double)(result));
-  return resultobj;
-fail:
-  return NULL;
-}
-
-
-SWIGINTERN PyObject *_wrap_imageObj_resolutionfactor_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
-  PyObject *resultobj = 0;
-  imageObj *arg1 = (imageObj *) 0 ;
-  void *argp1 = 0 ;
-  int res1 = 0 ;
-  PyObject * obj0 = 0 ;
-  double result;
-  
-  if (!PyArg_ParseTuple(args,(char *)"O:imageObj_resolutionfactor_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_imageObj, 0 |  0 );
-  if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "imageObj_resolutionfactor_get" "', argument " "1"" of type '" "imageObj *""'"); 
-  }
-  arg1 = (imageObj *)(argp1);
-  result = (double) ((arg1)->resolutionfactor);
-  resultobj = SWIG_From_double((double)(result));
-  return resultobj;
-fail:
-  return NULL;
-}
-
-
-SWIGINTERN PyObject *_wrap_imageObj_imagepath_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
-  PyObject *resultobj = 0;
-  imageObj *arg1 = (imageObj *) 0 ;
-  void *argp1 = 0 ;
-  int res1 = 0 ;
-  PyObject * obj0 = 0 ;
-  char *result = 0 ;
-  
-  if (!PyArg_ParseTuple(args,(char *)"O:imageObj_imagepath_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_imageObj, 0 |  0 );
-  if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "imageObj_imagepath_get" "', argument " "1"" of type '" "imageObj *""'"); 
-  }
-  arg1 = (imageObj *)(argp1);
-  result = (char *) ((arg1)->imagepath);
-  resultobj = SWIG_FromCharPtr((const char *)result);
-  return resultobj;
-fail:
-  return NULL;
-}
-
-
-SWIGINTERN PyObject *_wrap_imageObj_imageurl_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
-  PyObject *resultobj = 0;
-  imageObj *arg1 = (imageObj *) 0 ;
-  void *argp1 = 0 ;
-  int res1 = 0 ;
-  PyObject * obj0 = 0 ;
-  char *result = 0 ;
-  
-  if (!PyArg_ParseTuple(args,(char *)"O:imageObj_imageurl_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_imageObj, 0 |  0 );
-  if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "imageObj_imageurl_get" "', argument " "1"" of type '" "imageObj *""'"); 
-  }
-  arg1 = (imageObj *)(argp1);
-  result = (char *) ((arg1)->imageurl);
-  resultobj = SWIG_FromCharPtr((const char *)result);
-  return resultobj;
-fail:
-  return NULL;
-}
-
-
-SWIGINTERN PyObject *_wrap_imageObj_format_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
-  PyObject *resultobj = 0;
-  imageObj *arg1 = (imageObj *) 0 ;
-  void *argp1 = 0 ;
-  int res1 = 0 ;
-  PyObject * obj0 = 0 ;
-  outputFormatObj *result = 0 ;
-  
-  if (!PyArg_ParseTuple(args,(char *)"O:imageObj_format_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_imageObj, 0 |  0 );
+  if (!PyArg_ParseTuple(args,(char *)"OOz:msSaveImage",&obj0,&obj1,&arg3)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "imageObj_format_get" "', argument " "1"" of type '" "imageObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "msSaveImage" "', argument " "1"" of type '" "mapObj *""'"); 
   }
-  arg1 = (imageObj *)(argp1);
-  result = (outputFormatObj *) ((arg1)->format);
-  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_outputFormatObj, 0 |  0 );
-  return resultobj;
-fail:
-  return NULL;
-}
-
-
-SWIGINTERN PyObject *_wrap_delete_imageObj(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
-  PyObject *resultobj = 0;
-  imageObj *arg1 = (imageObj *) 0 ;
-  void *argp1 = 0 ;
-  int res1 = 0 ;
-  PyObject * obj0 = 0 ;
-  
-  if (!PyArg_ParseTuple(args,(char *)"O:delete_imageObj",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_imageObj, SWIG_POINTER_DISOWN |  0 );
-  if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_imageObj" "', argument " "1"" of type '" "imageObj *""'"); 
+  arg1 = (mapObj *)(argp1);
+  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_imageObj, 0 |  0 );
+  if (!SWIG_IsOK(res2)) {
+    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "msSaveImage" "', argument " "2"" of type '" "imageObj *""'"); 
   }
-  arg1 = (imageObj *)(argp1);
+  arg2 = (imageObj *)(argp2);
   {
-    delete_imageObj(arg1); {
-      errorObj *ms_error = msGetErrorObj();
-      
-      switch(ms_error->code) {
-      case MS_NOERR:
-        break;
-      case MS_NOTFOUND:
-        msResetErrorList();
-        break;
-      case -1:
-        break;
-      case MS_IOERR:
-        if (strcmp(ms_error->routine, "msSearchDiskTree()") != 0) {
-          _raise_ms_exception();
-          msResetErrorList();
-          return NULL;
-        }
-      default:
-        _raise_ms_exception();
-        msResetErrorList();
-        return NULL;
-      }
-      
-    }
-  }
-  resultobj = SWIG_Py_Void();
-  return resultobj;
-fail:
-  return NULL;
-}
-
-
-SWIGINTERN PyObject *_wrap_imageObj_save(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
-  PyObject *resultobj = 0;
-  imageObj *arg1 = (imageObj *) 0 ;
-  char *arg2 = (char *) 0 ;
-  mapObj *arg3 = (mapObj *) NULL ;
-  void *argp1 = 0 ;
-  int res1 = 0 ;
-  void *argp3 = 0 ;
-  int res3 = 0 ;
-  PyObject * obj0 = 0 ;
-  PyObject * obj2 = 0 ;
-  
-  if (!PyArg_ParseTuple(args,(char *)"Oz|O:imageObj_save",&obj0,&arg2,&obj2)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_imageObj, 0 |  0 );
-  if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "imageObj_save" "', argument " "1"" of type '" "imageObj *""'"); 
-  }
-  arg1 = (imageObj *)(argp1);
-  if (obj2) {
-    res3 = SWIG_ConvertPtr(obj2, &argp3,SWIGTYPE_p_map_obj, 0 |  0 );
-    if (!SWIG_IsOK(res3)) {
-      SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "imageObj_save" "', argument " "3"" of type '" "mapObj *""'"); 
-    }
-    arg3 = (mapObj *)(argp3);
-  }
-  {
-    imageObj_save(arg1,arg2,arg3); {
-      errorObj *ms_error = msGetErrorObj();
-      
-      switch(ms_error->code) {
-      case MS_NOERR:
-        break;
-      case MS_NOTFOUND:
-        msResetErrorList();
-        break;
-      case -1:
-        break;
-      case MS_IOERR:
-        if (strcmp(ms_error->routine, "msSearchDiskTree()") != 0) {
-          _raise_ms_exception();
-          msResetErrorList();
-          return NULL;
-        }
-      default:
-        _raise_ms_exception();
-        msResetErrorList();
-        return NULL;
-      }
-      
-    }
-  }
-  resultobj = SWIG_Py_Void();
-  return resultobj;
-fail:
-  return NULL;
-}
-
-
-SWIGINTERN PyObject *_wrap_imageObj_getBytes(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
-  PyObject *resultobj = 0;
-  imageObj *arg1 = (imageObj *) 0 ;
-  void *argp1 = 0 ;
-  int res1 = 0 ;
-  PyObject * obj0 = 0 ;
-  gdBuffer result;
-  
-  if (!PyArg_ParseTuple(args,(char *)"O:imageObj_getBytes",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_imageObj, 0 |  0 );
-  if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "imageObj_getBytes" "', argument " "1"" of type '" "imageObj *""'"); 
-  }
-  arg1 = (imageObj *)(argp1);
-  {
-    result = imageObj_getBytes(arg1); {
-      errorObj *ms_error = msGetErrorObj();
-      
-      switch(ms_error->code) {
-      case MS_NOERR:
-        break;
-      case MS_NOTFOUND:
-        msResetErrorList();
-        break;
-      case -1:
-        break;
-      case MS_IOERR:
-        if (strcmp(ms_error->routine, "msSearchDiskTree()") != 0) {
-          _raise_ms_exception();
-          msResetErrorList();
-          return NULL;
-        }
-      default:
-        _raise_ms_exception();
-        msResetErrorList();
-        return NULL;
-      }
-      
-    }
-  }
-  {
-    resultobj = PyString_FromStringAndSize((const char*)(&result)->data, (&result)->size); 
-    if( (&result)->owns_data )
-    gdFree((&result)->data);
-  }
-  return resultobj;
-fail:
-  return NULL;
-}
-
-
-SWIGINTERN PyObject *_wrap_imageObj_getSize(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
-  PyObject *resultobj = 0;
-  imageObj *arg1 = (imageObj *) 0 ;
-  void *argp1 = 0 ;
-  int res1 = 0 ;
-  PyObject * obj0 = 0 ;
-  int result;
-  
-  if (!PyArg_ParseTuple(args,(char *)"O:imageObj_getSize",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_imageObj, 0 |  0 );
-  if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "imageObj_getSize" "', argument " "1"" of type '" "imageObj *""'"); 
-  }
-  arg1 = (imageObj *)(argp1);
-  {
-    result = (int)imageObj_getSize(arg1); {
-      errorObj *ms_error = msGetErrorObj();
-      
-      switch(ms_error->code) {
-      case MS_NOERR:
-        break;
-      case MS_NOTFOUND:
-        msResetErrorList();
-        break;
-      case -1:
-        break;
-      case MS_IOERR:
-        if (strcmp(ms_error->routine, "msSearchDiskTree()") != 0) {
-          _raise_ms_exception();
-          msResetErrorList();
-          return NULL;
-        }
-      default:
-        _raise_ms_exception();
-        msResetErrorList();
-        return NULL;
-      }
-      
-    }
-  }
-  resultobj = SWIG_From_int((int)(result));
-  return resultobj;
-fail:
-  return NULL;
-}
-
-
-SWIGINTERN PyObject *_wrap_new_imageObj(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
-  PyObject *resultobj = 0;
-  PyObject *arg1 = (PyObject *) Py_None ;
-  PyObject *arg2 = (PyObject *) Py_None ;
-  PyObject *arg3 = (PyObject *) Py_None ;
-  PyObject *arg4 = (PyObject *) Py_None ;
-  PyObject *arg5 = (PyObject *) Py_None ;
-  PyObject * obj0 = 0 ;
-  PyObject * obj1 = 0 ;
-  PyObject * obj2 = 0 ;
-  PyObject * obj3 = 0 ;
-  PyObject * obj4 = 0 ;
-  imageObj *result = 0 ;
-  
-  if (!PyArg_ParseTuple(args,(char *)"|OOOOO:new_imageObj",&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail;
-  if (obj0) {
-    arg1 = obj0;
-  }
-  if (obj1) {
-    arg2 = obj1;
-  }
-  if (obj2) {
-    arg3 = obj2;
-  }
-  if (obj3) {
-    arg4 = obj3;
-  }
-  if (obj4) {
-    arg5 = obj4;
-  }
-  {
-    result = (imageObj *)new_imageObj(arg1,arg2,arg3,arg4,arg5); {
-      errorObj *ms_error = msGetErrorObj();
-      
-      switch(ms_error->code) {
-      case MS_NOERR:
-        break;
-      case MS_NOTFOUND:
-        msResetErrorList();
-        break;
-      case -1:
-        break;
-      case MS_IOERR:
-        if (strcmp(ms_error->routine, "msSearchDiskTree()") != 0) {
-          _raise_ms_exception();
-          msResetErrorList();
-          return NULL;
-        }
-      default:
-        _raise_ms_exception();
-        msResetErrorList();
-        return NULL;
-      }
-      
-    }
-  }
-  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_imageObj, SWIG_POINTER_NEW |  0 );
-  return resultobj;
-fail:
-  return NULL;
-}
-
-
-SWIGINTERN PyObject *_wrap_imageObj_write(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
-  PyObject *resultobj = 0;
-  imageObj *arg1 = (imageObj *) 0 ;
-  PyObject *arg2 = (PyObject *) Py_None ;
-  void *argp1 = 0 ;
-  int res1 = 0 ;
-  PyObject * obj0 = 0 ;
-  PyObject * obj1 = 0 ;
-  int result;
-  
-  if (!PyArg_ParseTuple(args,(char *)"O|O:imageObj_write",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_imageObj, 0 |  0 );
-  if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "imageObj_write" "', argument " "1"" of type '" "imageObj *""'"); 
-  }
-  arg1 = (imageObj *)(argp1);
-  if (obj1) {
-    arg2 = obj1;
-  }
-  {
-    result = (int)imageObj_write(arg1,arg2); {
-      errorObj *ms_error = msGetErrorObj();
-      
-      switch(ms_error->code) {
-      case MS_NOERR:
-        break;
-      case MS_NOTFOUND:
-        msResetErrorList();
-        break;
-      case -1:
-        break;
-      case MS_IOERR:
-        if (strcmp(ms_error->routine, "msSearchDiskTree()") != 0) {
-          _raise_ms_exception();
-          msResetErrorList();
-          return NULL;
-        }
-      default:
-        _raise_ms_exception();
-        msResetErrorList();
-        return NULL;
-      }
-      
-    }
-  }
-  resultobj = SWIG_From_int((int)(result));
-  return resultobj;
-fail:
-  return NULL;
-}
-
-
-SWIGINTERN PyObject *_wrap_imageObj_saveToString(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
-  PyObject *resultobj = 0;
-  imageObj *arg1 = (imageObj *) 0 ;
-  void *argp1 = 0 ;
-  int res1 = 0 ;
-  PyObject * obj0 = 0 ;
-  PyObject *result = 0 ;
-  
-  if (!PyArg_ParseTuple(args,(char *)"O:imageObj_saveToString",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_imageObj, 0 |  0 );
-  if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "imageObj_saveToString" "', argument " "1"" of type '" "imageObj *""'"); 
-  }
-  arg1 = (imageObj *)(argp1);
-  {
-    result = (PyObject *)imageObj_saveToString(arg1); {
-      errorObj *ms_error = msGetErrorObj();
-      
-      switch(ms_error->code) {
-      case MS_NOERR:
-        break;
-      case MS_NOTFOUND:
-        msResetErrorList();
-        break;
-      case -1:
-        break;
-      case MS_IOERR:
-        if (strcmp(ms_error->routine, "msSearchDiskTree()") != 0) {
-          _raise_ms_exception();
-          msResetErrorList();
-          return NULL;
-        }
-      default:
-        _raise_ms_exception();
-        msResetErrorList();
-        return NULL;
-      }
-      
-    }
-  }
-  resultobj = result;
-  return resultobj;
-fail:
-  return NULL;
-}
-
-
-SWIGINTERN PyObject *imageObj_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
-  PyObject *obj;
-  if (!PyArg_ParseTuple(args,(char*)"O:swigregister", &obj)) return NULL;
-  SWIG_TypeNewClientData(SWIGTYPE_p_imageObj, SWIG_NewClientData(obj));
-  return SWIG_Py_Void();
-}
-
-SWIGINTERN PyObject *_wrap_msSaveImage(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
-  PyObject *resultobj = 0;
-  mapObj *arg1 = (mapObj *) 0 ;
-  imageObj *arg2 = (imageObj *) 0 ;
-  char *arg3 = (char *) 0 ;
-  void *argp1 = 0 ;
-  int res1 = 0 ;
-  void *argp2 = 0 ;
-  int res2 = 0 ;
-  PyObject * obj0 = 0 ;
-  PyObject * obj1 = 0 ;
-  int result;
-  
-  if (!PyArg_ParseTuple(args,(char *)"OOz:msSaveImage",&obj0,&obj1,&arg3)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_map_obj, 0 |  0 );
-  if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "msSaveImage" "', argument " "1"" of type '" "mapObj *""'"); 
-  }
-  arg1 = (mapObj *)(argp1);
-  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_imageObj, 0 |  0 );
-  if (!SWIG_IsOK(res2)) {
-    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "msSaveImage" "', argument " "2"" of type '" "imageObj *""'"); 
-  }
-  arg2 = (imageObj *)(argp2);
-  {
-    result = (int)msSaveImage(arg1,arg2,arg3); {
+    result = (int)msSaveImage(arg1,arg2,arg3); {
       errorObj *ms_error = msGetErrorObj();
       
       switch(ms_error->code) {
@@ -32522,10 +33804,19 @@ fail:
 
 SWIGINTERN PyObject *_wrap_msCleanup(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
+  int arg1 ;
+  int val1 ;
+  int ecode1 = 0 ;
+  PyObject * obj0 = 0 ;
   
-  if (!PyArg_ParseTuple(args,(char *)":msCleanup")) SWIG_fail;
+  if (!PyArg_ParseTuple(args,(char *)"O:msCleanup",&obj0)) SWIG_fail;
+  ecode1 = SWIG_AsVal_int(obj0, &val1);
+  if (!SWIG_IsOK(ecode1)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "msCleanup" "', argument " "1"" of type '" "int""'");
+  } 
+  arg1 = (int)(val1);
   {
-    msCleanup(); {
+    msCleanup(arg1); {
       errorObj *ms_error = msGetErrorObj();
       
       switch(ms_error->code) {
@@ -32590,7 +33881,7 @@ SWIGINTERN PyObject *_wrap_msLoadMapFromString(PyObject *SWIGUNUSEDPARM(self), P
       
     }
   }
-  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_map_obj, 0 |  0 );
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_mapObj, 0 |  0 );
   return resultobj;
 fail:
   return NULL;
@@ -32760,6 +34051,58 @@ fail:
 }
 
 
+SWIGINTERN PyObject *_wrap_strokeStyleObj_patternoffset_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  strokeStyleObj *arg1 = (strokeStyleObj *) 0 ;
+  double arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  double val2 ;
+  int ecode2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:strokeStyleObj_patternoffset_set",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_strokeStyleObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "strokeStyleObj_patternoffset_set" "', argument " "1"" of type '" "strokeStyleObj *""'"); 
+  }
+  arg1 = (strokeStyleObj *)(argp1);
+  ecode2 = SWIG_AsVal_double(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "strokeStyleObj_patternoffset_set" "', argument " "2"" of type '" "double""'");
+  } 
+  arg2 = (double)(val2);
+  if (arg1) (arg1)->patternoffset = arg2;
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_strokeStyleObj_patternoffset_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  strokeStyleObj *arg1 = (strokeStyleObj *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  double result;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:strokeStyleObj_patternoffset_get",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_strokeStyleObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "strokeStyleObj_patternoffset_get" "', argument " "1"" of type '" "strokeStyleObj *""'"); 
+  }
+  arg1 = (strokeStyleObj *)(argp1);
+  result = (double) ((arg1)->patternoffset);
+  resultobj = SWIG_From_double((double)(result));
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
 SWIGINTERN PyObject *_wrap_strokeStyleObj_color_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   strokeStyleObj *arg1 = (strokeStyleObj *) 0 ;
@@ -34229,27 +35572,34 @@ SWIGINTERN PyObject *tileCacheObj_swigregister(PyObject *SWIGUNUSEDPARM(self), P
   return SWIG_Py_Void();
 }
 
-SWIGINTERN PyObject *_wrap_labelStyleObj_font_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_labelStyleObj_fonts_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   labelStyleObj *arg1 = (labelStyleObj *) 0 ;
-  char *arg2 = (char *) 0 ;
+  char **arg2 ;
   void *argp1 = 0 ;
   int res1 = 0 ;
+  void *argp2 = 0 ;
+  int res2 = 0 ;
   PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
   
-  if (!PyArg_ParseTuple(args,(char *)"Oz:labelStyleObj_font_set",&obj0,&arg2)) SWIG_fail;
+  if (!PyArg_ParseTuple(args,(char *)"OO:labelStyleObj_fonts_set",&obj0,&obj1)) SWIG_fail;
   res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_labelStyleObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelStyleObj_font_set" "', argument " "1"" of type '" "labelStyleObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelStyleObj_fonts_set" "', argument " "1"" of type '" "labelStyleObj *""'"); 
   }
   arg1 = (labelStyleObj *)(argp1);
+  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_p_char, 0 |  0 );
+  if (!SWIG_IsOK(res2)) {
+    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "labelStyleObj_fonts_set" "', argument " "2"" of type '" "char *[5]""'"); 
+  } 
+  arg2 = (char **)(argp2);
   {
-    if (arg1->font) free((char*)arg1->font);
     if (arg2) {
-      arg1->font = (char *) malloc(strlen(arg2)+1);
-      strcpy((char*)arg1->font,arg2);
+      size_t ii = 0;
+      for (; ii < (size_t)5; ++ii) arg1->fonts[ii] = arg2[ii];
     } else {
-      arg1->font = 0;
+      SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in variable '""fonts""' of type '""char *[5]""'");
     }
   }
   resultobj = SWIG_Py_Void();
@@ -34259,22 +35609,74 @@ fail:
 }
 
 
-SWIGINTERN PyObject *_wrap_labelStyleObj_font_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_labelStyleObj_fonts_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   labelStyleObj *arg1 = (labelStyleObj *) 0 ;
   void *argp1 = 0 ;
   int res1 = 0 ;
   PyObject * obj0 = 0 ;
-  char *result = 0 ;
+  char **result = 0 ;
   
-  if (!PyArg_ParseTuple(args,(char *)"O:labelStyleObj_font_get",&obj0)) SWIG_fail;
+  if (!PyArg_ParseTuple(args,(char *)"O:labelStyleObj_fonts_get",&obj0)) SWIG_fail;
   res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_labelStyleObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelStyleObj_font_get" "', argument " "1"" of type '" "labelStyleObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelStyleObj_fonts_get" "', argument " "1"" of type '" "labelStyleObj *""'"); 
   }
   arg1 = (labelStyleObj *)(argp1);
-  result = (char *) ((arg1)->font);
-  resultobj = SWIG_FromCharPtr((const char *)result);
+  result = (char **)(char **) ((arg1)->fonts);
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_p_char, 0 |  0 );
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_labelStyleObj_numfonts_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  labelStyleObj *arg1 = (labelStyleObj *) 0 ;
+  int arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val2 ;
+  int ecode2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:labelStyleObj_numfonts_set",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_labelStyleObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelStyleObj_numfonts_set" "', argument " "1"" of type '" "labelStyleObj *""'"); 
+  }
+  arg1 = (labelStyleObj *)(argp1);
+  ecode2 = SWIG_AsVal_int(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "labelStyleObj_numfonts_set" "', argument " "2"" of type '" "int""'");
+  } 
+  arg2 = (int)(val2);
+  if (arg1) (arg1)->numfonts = arg2;
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_labelStyleObj_numfonts_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  labelStyleObj *arg1 = (labelStyleObj *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  int result;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:labelStyleObj_numfonts_get",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_labelStyleObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelStyleObj_numfonts_get" "', argument " "1"" of type '" "labelStyleObj *""'"); 
+  }
+  arg1 = (labelStyleObj *)(argp1);
+  result = (int) ((arg1)->numfonts);
+  resultobj = SWIG_From_int((int)(result));
   return resultobj;
 fail:
   return NULL;
@@ -34541,6 +35943,58 @@ fail:
 }
 
 
+SWIGINTERN PyObject *_wrap_labelStyleObj_antialias_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  labelStyleObj *arg1 = (labelStyleObj *) 0 ;
+  int arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val2 ;
+  int ecode2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:labelStyleObj_antialias_set",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_labelStyleObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelStyleObj_antialias_set" "', argument " "1"" of type '" "labelStyleObj *""'"); 
+  }
+  arg1 = (labelStyleObj *)(argp1);
+  ecode2 = SWIG_AsVal_int(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "labelStyleObj_antialias_set" "', argument " "2"" of type '" "int""'");
+  } 
+  arg2 = (int)(val2);
+  if (arg1) (arg1)->antialias = arg2;
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_labelStyleObj_antialias_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  labelStyleObj *arg1 = (labelStyleObj *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  int result;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:labelStyleObj_antialias_get",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_labelStyleObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "labelStyleObj_antialias_get" "', argument " "1"" of type '" "labelStyleObj *""'"); 
+  }
+  arg1 = (labelStyleObj *)(argp1);
+  result = (int) ((arg1)->antialias);
+  resultobj = SWIG_From_int((int)(result));
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
 SWIGINTERN PyObject *_wrap_new_labelStyleObj(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   labelStyleObj *result = 0 ;
@@ -35140,12 +36594,12 @@ SWIGINTERN PyObject *_wrap_rectObj_draw(PyObject *SWIGUNUSEDPARM(self), PyObject
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "rectObj_draw" "', argument " "1"" of type '" "rectObj *""'"); 
   }
   arg1 = (rectObj *)(argp1);
-  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_map_obj, 0 |  0 );
+  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res2)) {
     SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "rectObj_draw" "', argument " "2"" of type '" "mapObj *""'"); 
   }
   arg2 = (mapObj *)(argp2);
-  res3 = SWIG_ConvertPtr(obj2, &argp3,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res3 = SWIG_ConvertPtr(obj2, &argp3,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res3)) {
     SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "rectObj_draw" "', argument " "3"" of type '" "layerObj *""'"); 
   }
@@ -35670,12 +37124,12 @@ SWIGINTERN PyObject *_wrap_pointObj_draw(PyObject *SWIGUNUSEDPARM(self), PyObjec
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "pointObj_draw" "', argument " "1"" of type '" "pointObj *""'"); 
   }
   arg1 = (pointObj *)(argp1);
-  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_map_obj, 0 |  0 );
+  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res2)) {
     SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "pointObj_draw" "', argument " "2"" of type '" "mapObj *""'"); 
   }
   arg2 = (mapObj *)(argp2);
-  res3 = SWIG_ConvertPtr(obj2, &argp3,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res3 = SWIG_ConvertPtr(obj2, &argp3,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res3)) {
     SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "pointObj_draw" "', argument " "3"" of type '" "layerObj *""'"); 
   }
@@ -37398,12 +38852,12 @@ SWIGINTERN PyObject *_wrap_shapeObj_draw(PyObject *SWIGUNUSEDPARM(self), PyObjec
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "shapeObj_draw" "', argument " "1"" of type '" "shapeObj *""'"); 
   }
   arg1 = (shapeObj *)(argp1);
-  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_map_obj, 0 |  0 );
+  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res2)) {
     SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "shapeObj_draw" "', argument " "2"" of type '" "mapObj *""'"); 
   }
   arg2 = (mapObj *)(argp2);
-  res3 = SWIG_ConvertPtr(obj2, &argp3,SWIGTYPE_p_layer_obj, 0 |  0 );
+  res3 = SWIG_ConvertPtr(obj2, &argp3,SWIGTYPE_p_layerObj, 0 |  0 );
   if (!SWIG_IsOK(res3)) {
     SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "shapeObj_draw" "', argument " "3"" of type '" "layerObj *""'"); 
   }
@@ -40335,7 +41789,7 @@ SWIGINTERN PyObject *_wrap_shapefileObj_getTransformed(PyObject *SWIGUNUSEDPARM(
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "shapefileObj_getTransformed" "', argument " "1"" of type '" "shapefileObj *""'"); 
   }
   arg1 = (shapefileObj *)(argp1);
-  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_map_obj, 0 |  0 );
+  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_mapObj, 0 |  0 );
   if (!SWIG_IsOK(res2)) {
     SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "shapefileObj_getTransformed" "', argument " "2"" of type '" "mapObj *""'"); 
   }
@@ -40657,84 +42111,29 @@ fail:
 }
 
 
-SWIGINTERN PyObject *_wrap_new_projectionObj(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
-  PyObject *resultobj = 0;
-  char *arg1 = (char *) 0 ;
-  projectionObj *result = 0 ;
-  
-  if (!PyArg_ParseTuple(args,(char *)"z:new_projectionObj",&arg1)) SWIG_fail;
-  {
-    result = (projectionObj *)new_projectionObj(arg1); {
-      errorObj *ms_error = msGetErrorObj();
-      
-      switch(ms_error->code) {
-      case MS_NOERR:
-        break;
-      case MS_NOTFOUND:
-        msResetErrorList();
-        break;
-      case -1:
-        break;
-      case MS_IOERR:
-        if (strcmp(ms_error->routine, "msSearchDiskTree()") != 0) {
-          _raise_ms_exception();
-          msResetErrorList();
-          return NULL;
-        }
-      default:
-        _raise_ms_exception();
-        msResetErrorList();
-        return NULL;
-      }
-      
-    }
-  }
-  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_projectionObj, SWIG_POINTER_NEW |  0 );
-  return resultobj;
-fail:
-  return NULL;
-}
-
-
-SWIGINTERN PyObject *_wrap_delete_projectionObj(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_projectionObj_wellknownprojection_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   projectionObj *arg1 = (projectionObj *) 0 ;
+  int arg2 ;
   void *argp1 = 0 ;
   int res1 = 0 ;
+  int val2 ;
+  int ecode2 = 0 ;
   PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
   
-  if (!PyArg_ParseTuple(args,(char *)"O:delete_projectionObj",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_projectionObj, SWIG_POINTER_DISOWN |  0 );
+  if (!PyArg_ParseTuple(args,(char *)"OO:projectionObj_wellknownprojection_set",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_projectionObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_projectionObj" "', argument " "1"" of type '" "projectionObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "projectionObj_wellknownprojection_set" "', argument " "1"" of type '" "projectionObj *""'"); 
   }
   arg1 = (projectionObj *)(argp1);
-  {
-    delete_projectionObj(arg1); {
-      errorObj *ms_error = msGetErrorObj();
-      
-      switch(ms_error->code) {
-      case MS_NOERR:
-        break;
-      case MS_NOTFOUND:
-        msResetErrorList();
-        break;
-      case -1:
-        break;
-      case MS_IOERR:
-        if (strcmp(ms_error->routine, "msSearchDiskTree()") != 0) {
-          _raise_ms_exception();
-          msResetErrorList();
-          return NULL;
-        }
-      default:
-        _raise_ms_exception();
-        msResetErrorList();
-        return NULL;
-      }
-      
-    }
-  }
+  ecode2 = SWIG_AsVal_int(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "projectionObj_wellknownprojection_set" "', argument " "2"" of type '" "int""'");
+  } 
+  arg2 = (int)(val2);
+  if (arg1) (arg1)->wellknownprojection = arg2;
   resultobj = SWIG_Py_Void();
   return resultobj;
 fail:
@@ -40742,23 +42141,36 @@ fail:
 }
 
 
-SWIGINTERN PyObject *_wrap_projectionObj_setWKTProjection(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_projectionObj_wellknownprojection_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   projectionObj *arg1 = (projectionObj *) 0 ;
-  char *arg2 = (char *) 0 ;
   void *argp1 = 0 ;
   int res1 = 0 ;
   PyObject * obj0 = 0 ;
   int result;
   
-  if (!PyArg_ParseTuple(args,(char *)"Oz:projectionObj_setWKTProjection",&obj0,&arg2)) SWIG_fail;
+  if (!PyArg_ParseTuple(args,(char *)"O:projectionObj_wellknownprojection_get",&obj0)) SWIG_fail;
   res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_projectionObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "projectionObj_setWKTProjection" "', argument " "1"" of type '" "projectionObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "projectionObj_wellknownprojection_get" "', argument " "1"" of type '" "projectionObj *""'"); 
   }
   arg1 = (projectionObj *)(argp1);
+  result = (int) ((arg1)->wellknownprojection);
+  resultobj = SWIG_From_int((int)(result));
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_new_projectionObj(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  char *arg1 = (char *) 0 ;
+  projectionObj *result = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"z:new_projectionObj",&arg1)) SWIG_fail;
   {
-    result = (int)projectionObj_setWKTProjection(arg1,arg2); {
+    result = (projectionObj *)new_projectionObj(arg1); {
       errorObj *ms_error = msGetErrorObj();
       
       switch(ms_error->code) {
@@ -40783,29 +42195,28 @@ SWIGINTERN PyObject *_wrap_projectionObj_setWKTProjection(PyObject *SWIGUNUSEDPA
       
     }
   }
-  resultobj = SWIG_From_int((int)(result));
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_projectionObj, SWIG_POINTER_NEW |  0 );
   return resultobj;
 fail:
   return NULL;
 }
 
 
-SWIGINTERN PyObject *_wrap_projectionObj_getUnits(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_delete_projectionObj(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   projectionObj *arg1 = (projectionObj *) 0 ;
   void *argp1 = 0 ;
   int res1 = 0 ;
   PyObject * obj0 = 0 ;
-  int result;
   
-  if (!PyArg_ParseTuple(args,(char *)"O:projectionObj_getUnits",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_projectionObj, 0 |  0 );
+  if (!PyArg_ParseTuple(args,(char *)"O:delete_projectionObj",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_projectionObj, SWIG_POINTER_DISOWN |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "projectionObj_getUnits" "', argument " "1"" of type '" "projectionObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_projectionObj" "', argument " "1"" of type '" "projectionObj *""'"); 
   }
   arg1 = (projectionObj *)(argp1);
   {
-    result = (int)projectionObj_getUnits(arg1); {
+    delete_projectionObj(arg1); {
       errorObj *ms_error = msGetErrorObj();
       
       switch(ms_error->code) {
@@ -40830,65 +42241,101 @@ SWIGINTERN PyObject *_wrap_projectionObj_getUnits(PyObject *SWIGUNUSEDPARM(self)
       
     }
   }
-  resultobj = SWIG_From_int((int)(result));
+  resultobj = SWIG_Py_Void();
   return resultobj;
 fail:
   return NULL;
 }
 
 
-SWIGINTERN PyObject *projectionObj_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
-  PyObject *obj;
-  if (!PyArg_ParseTuple(args,(char*)"O:swigregister", &obj)) return NULL;
-  SWIG_TypeNewClientData(SWIGTYPE_p_projectionObj, SWIG_NewClientData(obj));
-  return SWIG_Py_Void();
-}
-
-SWIGINTERN PyObject *_wrap_colorObj_pen_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_projectionObj_setWKTProjection(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
-  colorObj *arg1 = (colorObj *) 0 ;
-  int arg2 ;
+  projectionObj *arg1 = (projectionObj *) 0 ;
+  char *arg2 = (char *) 0 ;
   void *argp1 = 0 ;
   int res1 = 0 ;
-  int val2 ;
-  int ecode2 = 0 ;
   PyObject * obj0 = 0 ;
-  PyObject * obj1 = 0 ;
+  int result;
   
-  if (!PyArg_ParseTuple(args,(char *)"OO:colorObj_pen_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_colorObj, 0 |  0 );
+  if (!PyArg_ParseTuple(args,(char *)"Oz:projectionObj_setWKTProjection",&obj0,&arg2)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_projectionObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "colorObj_pen_set" "', argument " "1"" of type '" "colorObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "projectionObj_setWKTProjection" "', argument " "1"" of type '" "projectionObj *""'"); 
   }
-  arg1 = (colorObj *)(argp1);
-  ecode2 = SWIG_AsVal_int(obj1, &val2);
-  if (!SWIG_IsOK(ecode2)) {
-    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "colorObj_pen_set" "', argument " "2"" of type '" "int""'");
-  } 
-  arg2 = (int)(val2);
-  if (arg1) (arg1)->pen = arg2;
-  resultobj = SWIG_Py_Void();
+  arg1 = (projectionObj *)(argp1);
+  {
+    result = (int)projectionObj_setWKTProjection(arg1,arg2); {
+      errorObj *ms_error = msGetErrorObj();
+      
+      switch(ms_error->code) {
+      case MS_NOERR:
+        break;
+      case MS_NOTFOUND:
+        msResetErrorList();
+        break;
+      case -1:
+        break;
+      case MS_IOERR:
+        if (strcmp(ms_error->routine, "msSearchDiskTree()") != 0) {
+          _raise_ms_exception();
+          msResetErrorList();
+          return NULL;
+        }
+      default:
+        _raise_ms_exception();
+        msResetErrorList();
+        return NULL;
+      }
+      
+    }
+  }
+  resultobj = SWIG_From_int((int)(result));
   return resultobj;
 fail:
   return NULL;
 }
 
 
-SWIGINTERN PyObject *_wrap_colorObj_pen_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+SWIGINTERN PyObject *_wrap_projectionObj_getUnits(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
-  colorObj *arg1 = (colorObj *) 0 ;
+  projectionObj *arg1 = (projectionObj *) 0 ;
   void *argp1 = 0 ;
   int res1 = 0 ;
   PyObject * obj0 = 0 ;
   int result;
   
-  if (!PyArg_ParseTuple(args,(char *)"O:colorObj_pen_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_colorObj, 0 |  0 );
+  if (!PyArg_ParseTuple(args,(char *)"O:projectionObj_getUnits",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_projectionObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
-    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "colorObj_pen_get" "', argument " "1"" of type '" "colorObj *""'"); 
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "projectionObj_getUnits" "', argument " "1"" of type '" "projectionObj *""'"); 
+  }
+  arg1 = (projectionObj *)(argp1);
+  {
+    result = (int)projectionObj_getUnits(arg1); {
+      errorObj *ms_error = msGetErrorObj();
+      
+      switch(ms_error->code) {
+      case MS_NOERR:
+        break;
+      case MS_NOTFOUND:
+        msResetErrorList();
+        break;
+      case -1:
+        break;
+      case MS_IOERR:
+        if (strcmp(ms_error->routine, "msSearchDiskTree()") != 0) {
+          _raise_ms_exception();
+          msResetErrorList();
+          return NULL;
+        }
+      default:
+        _raise_ms_exception();
+        msResetErrorList();
+        return NULL;
+      }
+      
+    }
   }
-  arg1 = (colorObj *)(argp1);
-  result = (int) ((arg1)->pen);
   resultobj = SWIG_From_int((int)(result));
   return resultobj;
 fail:
@@ -40896,6 +42343,13 @@ fail:
 }
 
 
+SWIGINTERN PyObject *projectionObj_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *obj;
+  if (!PyArg_ParseTuple(args,(char*)"O:swigregister", &obj)) return NULL;
+  SWIG_TypeNewClientData(SWIGTYPE_p_projectionObj, SWIG_NewClientData(obj));
+  return SWIG_Py_Void();
+}
+
 SWIGINTERN PyObject *_wrap_colorObj_red_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   colorObj *arg1 = (colorObj *) 0 ;
@@ -41973,6 +43427,110 @@ fail:
 }
 
 
+SWIGINTERN PyObject *_wrap_symbolObj_anchorpoint_x_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  symbolObj *arg1 = (symbolObj *) 0 ;
+  double arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  double val2 ;
+  int ecode2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:symbolObj_anchorpoint_x_set",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_symbolObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "symbolObj_anchorpoint_x_set" "', argument " "1"" of type '" "symbolObj *""'"); 
+  }
+  arg1 = (symbolObj *)(argp1);
+  ecode2 = SWIG_AsVal_double(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "symbolObj_anchorpoint_x_set" "', argument " "2"" of type '" "double""'");
+  } 
+  arg2 = (double)(val2);
+  if (arg1) (arg1)->anchorpoint_x = arg2;
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_symbolObj_anchorpoint_x_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  symbolObj *arg1 = (symbolObj *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  double result;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:symbolObj_anchorpoint_x_get",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_symbolObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "symbolObj_anchorpoint_x_get" "', argument " "1"" of type '" "symbolObj *""'"); 
+  }
+  arg1 = (symbolObj *)(argp1);
+  result = (double) ((arg1)->anchorpoint_x);
+  resultobj = SWIG_From_double((double)(result));
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_symbolObj_anchorpoint_y_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  symbolObj *arg1 = (symbolObj *) 0 ;
+  double arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  double val2 ;
+  int ecode2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:symbolObj_anchorpoint_y_set",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_symbolObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "symbolObj_anchorpoint_y_set" "', argument " "1"" of type '" "symbolObj *""'"); 
+  }
+  arg1 = (symbolObj *)(argp1);
+  ecode2 = SWIG_AsVal_double(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "symbolObj_anchorpoint_y_set" "', argument " "2"" of type '" "double""'");
+  } 
+  arg2 = (double)(val2);
+  if (arg1) (arg1)->anchorpoint_y = arg2;
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_symbolObj_anchorpoint_y_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  symbolObj *arg1 = (symbolObj *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  double result;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:symbolObj_anchorpoint_y_get",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_symbolObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "symbolObj_anchorpoint_y_get" "', argument " "1"" of type '" "symbolObj *""'"); 
+  }
+  arg1 = (symbolObj *)(argp1);
+  result = (double) ((arg1)->anchorpoint_y);
+  resultobj = SWIG_From_double((double)(result));
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
 SWIGINTERN PyObject *_wrap_symbolObj_imagepath_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   symbolObj *arg1 = (symbolObj *) 0 ;
@@ -42699,7 +44257,7 @@ SWIGINTERN PyObject *_wrap_errorObj_code_set(PyObject *SWIGUNUSEDPARM(self), PyO
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:errorObj_code_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_error_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_errorObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "errorObj_code_set" "', argument " "1"" of type '" "errorObj *""'"); 
   }
@@ -42726,7 +44284,7 @@ SWIGINTERN PyObject *_wrap_errorObj_code_get(PyObject *SWIGUNUSEDPARM(self), PyO
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:errorObj_code_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_error_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_errorObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "errorObj_code_get" "', argument " "1"" of type '" "errorObj *""'"); 
   }
@@ -42751,7 +44309,7 @@ SWIGINTERN PyObject *_wrap_errorObj_routine_set(PyObject *SWIGUNUSEDPARM(self),
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:errorObj_routine_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_error_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_errorObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "errorObj_routine_set" "', argument " "1"" of type '" "errorObj *""'"); 
   }
@@ -42779,7 +44337,7 @@ SWIGINTERN PyObject *_wrap_errorObj_routine_get(PyObject *SWIGUNUSEDPARM(self),
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:errorObj_routine_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_error_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_errorObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "errorObj_routine_get" "', argument " "1"" of type '" "errorObj *""'"); 
   }
@@ -42810,7 +44368,7 @@ SWIGINTERN PyObject *_wrap_errorObj_message_set(PyObject *SWIGUNUSEDPARM(self),
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:errorObj_message_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_error_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_errorObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "errorObj_message_set" "', argument " "1"" of type '" "errorObj *""'"); 
   }
@@ -42838,7 +44396,7 @@ SWIGINTERN PyObject *_wrap_errorObj_message_get(PyObject *SWIGUNUSEDPARM(self),
   char *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:errorObj_message_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_error_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_errorObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "errorObj_message_get" "', argument " "1"" of type '" "errorObj *""'"); 
   }
@@ -42869,7 +44427,7 @@ SWIGINTERN PyObject *_wrap_errorObj_isreported_set(PyObject *SWIGUNUSEDPARM(self
   PyObject * obj1 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"OO:errorObj_isreported_set",&obj0,&obj1)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_error_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_errorObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "errorObj_isreported_set" "', argument " "1"" of type '" "errorObj *""'"); 
   }
@@ -42896,7 +44454,7 @@ SWIGINTERN PyObject *_wrap_errorObj_isreported_get(PyObject *SWIGUNUSEDPARM(self
   int result;
   
   if (!PyArg_ParseTuple(args,(char *)"O:errorObj_isreported_get",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_error_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_errorObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "errorObj_isreported_get" "', argument " "1"" of type '" "errorObj *""'"); 
   }
@@ -42940,7 +44498,7 @@ SWIGINTERN PyObject *_wrap_new_errorObj(PyObject *SWIGUNUSEDPARM(self), PyObject
       
     }
   }
-  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_error_obj, SWIG_POINTER_NEW |  0 );
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_errorObj, SWIG_POINTER_NEW |  0 );
   return resultobj;
 fail:
   return NULL;
@@ -42955,7 +44513,7 @@ SWIGINTERN PyObject *_wrap_delete_errorObj(PyObject *SWIGUNUSEDPARM(self), PyObj
   PyObject * obj0 = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:delete_errorObj",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_error_obj, SWIG_POINTER_DISOWN |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_errorObj, SWIG_POINTER_DISOWN |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_errorObj" "', argument " "1"" of type '" "errorObj *""'"); 
   }
@@ -43002,7 +44560,7 @@ SWIGINTERN PyObject *_wrap_errorObj_next(PyObject *SWIGUNUSEDPARM(self), PyObjec
   errorObj *result = 0 ;
   
   if (!PyArg_ParseTuple(args,(char *)"O:errorObj_next",&obj0)) SWIG_fail;
-  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_error_obj, 0 |  0 );
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_errorObj, 0 |  0 );
   if (!SWIG_IsOK(res1)) {
     SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "errorObj_next" "', argument " "1"" of type '" "errorObj *""'"); 
   }
@@ -43033,7 +44591,7 @@ SWIGINTERN PyObject *_wrap_errorObj_next(PyObject *SWIGUNUSEDPARM(self), PyObjec
       
     }
   }
-  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_error_obj, 0 |  0 );
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_errorObj, 0 |  0 );
   return resultobj;
 fail:
   return NULL;
@@ -43043,7 +44601,7 @@ fail:
 SWIGINTERN PyObject *errorObj_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *obj;
   if (!PyArg_ParseTuple(args,(char*)"O:swigregister", &obj)) return NULL;
-  SWIG_TypeNewClientData(SWIGTYPE_p_error_obj, SWIG_NewClientData(obj));
+  SWIG_TypeNewClientData(SWIGTYPE_p_errorObj, SWIG_NewClientData(obj));
   return SWIG_Py_Void();
 }
 
@@ -43078,7 +44636,7 @@ SWIGINTERN PyObject *_wrap_msGetErrorObj(PyObject *SWIGUNUSEDPARM(self), PyObjec
       
     }
   }
-  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_error_obj, 0 |  0 );
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_errorObj, 0 |  0 );
   return resultobj;
 fail:
   return NULL;
@@ -44058,6 +45616,54 @@ fail:
 }
 
 
+SWIGINTERN PyObject *_wrap_OWSRequest_addParameter(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  cgiRequestObj *arg1 = (cgiRequestObj *) 0 ;
+  char *arg2 = (char *) 0 ;
+  char *arg3 = (char *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"Ozz:OWSRequest_addParameter",&obj0,&arg2,&arg3)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_cgiRequestObj, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "OWSRequest_addParameter" "', argument " "1"" of type '" "cgiRequestObj *""'"); 
+  }
+  arg1 = (cgiRequestObj *)(argp1);
+  {
+    cgiRequestObj_addParameter(arg1,arg2,arg3); {
+      errorObj *ms_error = msGetErrorObj();
+      
+      switch(ms_error->code) {
+      case MS_NOERR:
+        break;
+      case MS_NOTFOUND:
+        msResetErrorList();
+        break;
+      case -1:
+        break;
+      case MS_IOERR:
+        if (strcmp(ms_error->routine, "msSearchDiskTree()") != 0) {
+          _raise_ms_exception();
+          msResetErrorList();
+          return NULL;
+        }
+      default:
+        _raise_ms_exception();
+        msResetErrorList();
+        return NULL;
+      }
+      
+    }
+  }
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
 SWIGINTERN PyObject *_wrap_OWSRequest_getName(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
   PyObject *resultobj = 0;
   cgiRequestObj *arg1 = (cgiRequestObj *) 0 ;
@@ -44532,7 +46138,7 @@ SWIGINTERN PyObject *_wrap_msIO_getStdoutBufferBytes(PyObject *SWIGUNUSEDPARM(se
   {
     resultobj = PyString_FromStringAndSize((const char*)(&result)->data, (&result)->size); 
     if( (&result)->owns_data )
-    gdFree((&result)->data);
+    msFree((&result)->data);
   }
   return resultobj;
 fail:
@@ -44696,6 +46302,8 @@ static PyMethodDef SwigMethods[] = {
 	 { (char *)"styleObj_pattern_get", _wrap_styleObj_pattern_get, METH_VARARGS, NULL},
 	 { (char *)"styleObj_gap_set", _wrap_styleObj_gap_set, METH_VARARGS, NULL},
 	 { (char *)"styleObj_gap_get", _wrap_styleObj_gap_get, METH_VARARGS, NULL},
+	 { (char *)"styleObj_initialgap_set", _wrap_styleObj_initialgap_set, METH_VARARGS, NULL},
+	 { (char *)"styleObj_initialgap_get", _wrap_styleObj_initialgap_get, METH_VARARGS, NULL},
 	 { (char *)"styleObj_position_set", _wrap_styleObj_position_set, METH_VARARGS, NULL},
 	 { (char *)"styleObj_position_get", _wrap_styleObj_position_get, METH_VARARGS, NULL},
 	 { (char *)"styleObj_linecap_set", _wrap_styleObj_linecap_set, METH_VARARGS, NULL},
@@ -44716,6 +46324,10 @@ static PyMethodDef SwigMethods[] = {
 	 { (char *)"styleObj_offsetx_get", _wrap_styleObj_offsetx_get, METH_VARARGS, NULL},
 	 { (char *)"styleObj_offsety_set", _wrap_styleObj_offsety_set, METH_VARARGS, NULL},
 	 { (char *)"styleObj_offsety_get", _wrap_styleObj_offsety_get, METH_VARARGS, NULL},
+	 { (char *)"styleObj_polaroffsetpixel_set", _wrap_styleObj_polaroffsetpixel_set, METH_VARARGS, NULL},
+	 { (char *)"styleObj_polaroffsetpixel_get", _wrap_styleObj_polaroffsetpixel_get, METH_VARARGS, NULL},
+	 { (char *)"styleObj_polaroffsetangle_set", _wrap_styleObj_polaroffsetangle_set, METH_VARARGS, NULL},
+	 { (char *)"styleObj_polaroffsetangle_get", _wrap_styleObj_polaroffsetangle_get, METH_VARARGS, NULL},
 	 { (char *)"styleObj_angle_set", _wrap_styleObj_angle_set, METH_VARARGS, NULL},
 	 { (char *)"styleObj_angle_get", _wrap_styleObj_angle_get, METH_VARARGS, NULL},
 	 { (char *)"styleObj_antialias_set", _wrap_styleObj_antialias_set, METH_VARARGS, NULL},
@@ -44735,6 +46347,15 @@ static PyMethodDef SwigMethods[] = {
 	 { (char *)"styleObj_getGeomTransform", _wrap_styleObj_getGeomTransform, METH_VARARGS, NULL},
 	 { (char *)"styleObj_setGeomTransform", _wrap_styleObj_setGeomTransform, METH_VARARGS, NULL},
 	 { (char *)"styleObj_swigregister", styleObj_swigregister, METH_VARARGS, NULL},
+	 { (char *)"labelLeaderObj_maxdistance_set", _wrap_labelLeaderObj_maxdistance_set, METH_VARARGS, NULL},
+	 { (char *)"labelLeaderObj_maxdistance_get", _wrap_labelLeaderObj_maxdistance_get, METH_VARARGS, NULL},
+	 { (char *)"labelLeaderObj_gridstep_set", _wrap_labelLeaderObj_gridstep_set, METH_VARARGS, NULL},
+	 { (char *)"labelLeaderObj_gridstep_get", _wrap_labelLeaderObj_gridstep_get, METH_VARARGS, NULL},
+	 { (char *)"labelLeaderObj_numstyles_get", _wrap_labelLeaderObj_numstyles_get, METH_VARARGS, NULL},
+	 { (char *)"new_labelLeaderObj", _wrap_new_labelLeaderObj, METH_VARARGS, NULL},
+	 { (char *)"delete_labelLeaderObj", _wrap_delete_labelLeaderObj, METH_VARARGS, NULL},
+	 { (char *)"labelLeaderObj_swigregister", labelLeaderObj_swigregister, METH_VARARGS, NULL},
+	 { (char *)"labelObj_refcount_get", _wrap_labelObj_refcount_get, METH_VARARGS, NULL},
 	 { (char *)"labelObj_font_set", _wrap_labelObj_font_set, METH_VARARGS, NULL},
 	 { (char *)"labelObj_font_get", _wrap_labelObj_font_get, METH_VARARGS, NULL},
 	 { (char *)"labelObj_type_set", _wrap_labelObj_type_set, METH_VARARGS, NULL},
@@ -44803,25 +46424,39 @@ static PyMethodDef SwigMethods[] = {
 	 { (char *)"labelObj_encoding_get", _wrap_labelObj_encoding_get, METH_VARARGS, NULL},
 	 { (char *)"labelObj_priority_set", _wrap_labelObj_priority_set, METH_VARARGS, NULL},
 	 { (char *)"labelObj_priority_get", _wrap_labelObj_priority_get, METH_VARARGS, NULL},
+	 { (char *)"labelObj_status_set", _wrap_labelObj_status_set, METH_VARARGS, NULL},
+	 { (char *)"labelObj_status_get", _wrap_labelObj_status_get, METH_VARARGS, NULL},
 	 { (char *)"labelObj_numstyles_set", _wrap_labelObj_numstyles_set, METH_VARARGS, NULL},
 	 { (char *)"labelObj_numstyles_get", _wrap_labelObj_numstyles_get, METH_VARARGS, NULL},
+	 { (char *)"labelObj_annotext_set", _wrap_labelObj_annotext_set, METH_VARARGS, NULL},
+	 { (char *)"labelObj_annotext_get", _wrap_labelObj_annotext_get, METH_VARARGS, NULL},
+	 { (char *)"labelObj_annopoint_set", _wrap_labelObj_annopoint_set, METH_VARARGS, NULL},
+	 { (char *)"labelObj_annopoint_get", _wrap_labelObj_annopoint_get, METH_VARARGS, NULL},
+	 { (char *)"labelObj_annopoly_set", _wrap_labelObj_annopoly_set, METH_VARARGS, NULL},
+	 { (char *)"labelObj_annopoly_get", _wrap_labelObj_annopoly_get, METH_VARARGS, NULL},
+	 { (char *)"labelObj_leader_set", _wrap_labelObj_leader_set, METH_VARARGS, NULL},
+	 { (char *)"labelObj_leader_get", _wrap_labelObj_leader_get, METH_VARARGS, NULL},
+	 { (char *)"new_labelObj", _wrap_new_labelObj, METH_VARARGS, NULL},
+	 { (char *)"delete_labelObj", _wrap_delete_labelObj, METH_VARARGS, NULL},
 	 { (char *)"labelObj_updateFromString", _wrap_labelObj_updateFromString, METH_VARARGS, NULL},
 	 { (char *)"labelObj_removeBinding", _wrap_labelObj_removeBinding, METH_VARARGS, NULL},
 	 { (char *)"labelObj_getBinding", _wrap_labelObj_getBinding, METH_VARARGS, NULL},
 	 { (char *)"labelObj_setBinding", _wrap_labelObj_setBinding, METH_VARARGS, NULL},
+	 { (char *)"labelObj_setExpression", _wrap_labelObj_setExpression, METH_VARARGS, NULL},
+	 { (char *)"labelObj_getExpressionString", _wrap_labelObj_getExpressionString, METH_VARARGS, NULL},
+	 { (char *)"labelObj_setText", _wrap_labelObj_setText, METH_VARARGS, NULL},
+	 { (char *)"labelObj_getTextString", _wrap_labelObj_getTextString, METH_VARARGS, NULL},
 	 { (char *)"labelObj_getStyle", _wrap_labelObj_getStyle, METH_VARARGS, NULL},
 	 { (char *)"labelObj_insertStyle", _wrap_labelObj_insertStyle, METH_VARARGS, NULL},
 	 { (char *)"labelObj_removeStyle", _wrap_labelObj_removeStyle, METH_VARARGS, NULL},
 	 { (char *)"labelObj_moveStyleUp", _wrap_labelObj_moveStyleUp, METH_VARARGS, NULL},
 	 { (char *)"labelObj_moveStyleDown", _wrap_labelObj_moveStyleDown, METH_VARARGS, NULL},
-	 { (char *)"new_labelObj", _wrap_new_labelObj, METH_VARARGS, NULL},
-	 { (char *)"delete_labelObj", _wrap_delete_labelObj, METH_VARARGS, NULL},
 	 { (char *)"labelObj_swigregister", labelObj_swigregister, METH_VARARGS, NULL},
 	 { (char *)"classObj_status_set", _wrap_classObj_status_set, METH_VARARGS, NULL},
 	 { (char *)"classObj_status_get", _wrap_classObj_status_get, METH_VARARGS, NULL},
-	 { (char *)"classObj_numstyles_set", _wrap_classObj_numstyles_set, METH_VARARGS, NULL},
 	 { (char *)"classObj_numstyles_get", _wrap_classObj_numstyles_get, METH_VARARGS, NULL},
-	 { (char *)"classObj_label_get", _wrap_classObj_label_get, METH_VARARGS, NULL},
+	 { (char *)"classObj_numlabels_set", _wrap_classObj_numlabels_set, METH_VARARGS, NULL},
+	 { (char *)"classObj_numlabels_get", _wrap_classObj_numlabels_get, METH_VARARGS, NULL},
 	 { (char *)"classObj_name_set", _wrap_classObj_name_set, METH_VARARGS, NULL},
 	 { (char *)"classObj_name_get", _wrap_classObj_name_get, METH_VARARGS, NULL},
 	 { (char *)"classObj_title_set", _wrap_classObj_title_set, METH_VARARGS, NULL},
@@ -44846,6 +46481,8 @@ static PyMethodDef SwigMethods[] = {
 	 { (char *)"classObj_keyimage_get", _wrap_classObj_keyimage_get, METH_VARARGS, NULL},
 	 { (char *)"classObj_group_set", _wrap_classObj_group_set, METH_VARARGS, NULL},
 	 { (char *)"classObj_group_get", _wrap_classObj_group_get, METH_VARARGS, NULL},
+	 { (char *)"classObj_leader_set", _wrap_classObj_leader_set, METH_VARARGS, NULL},
+	 { (char *)"classObj_leader_get", _wrap_classObj_leader_get, METH_VARARGS, NULL},
 	 { (char *)"new_classObj", _wrap_new_classObj, METH_VARARGS, NULL},
 	 { (char *)"delete_classObj", _wrap_delete_classObj, METH_VARARGS, NULL},
 	 { (char *)"classObj_updateFromString", _wrap_classObj_updateFromString, METH_VARARGS, NULL},
@@ -44860,26 +46497,29 @@ static PyMethodDef SwigMethods[] = {
 	 { (char *)"classObj_getNextMetaDataKey", _wrap_classObj_getNextMetaDataKey, METH_VARARGS, NULL},
 	 { (char *)"classObj_drawLegendIcon", _wrap_classObj_drawLegendIcon, METH_VARARGS, NULL},
 	 { (char *)"classObj_createLegendIcon", _wrap_classObj_createLegendIcon, METH_VARARGS, NULL},
+	 { (char *)"classObj_getLabel", _wrap_classObj_getLabel, METH_VARARGS, NULL},
+	 { (char *)"classObj_addLabel", _wrap_classObj_addLabel, METH_VARARGS, NULL},
+	 { (char *)"classObj_removeLabel", _wrap_classObj_removeLabel, METH_VARARGS, NULL},
 	 { (char *)"classObj_getStyle", _wrap_classObj_getStyle, METH_VARARGS, NULL},
 	 { (char *)"classObj_insertStyle", _wrap_classObj_insertStyle, METH_VARARGS, NULL},
 	 { (char *)"classObj_removeStyle", _wrap_classObj_removeStyle, METH_VARARGS, NULL},
 	 { (char *)"classObj_moveStyleUp", _wrap_classObj_moveStyleUp, METH_VARARGS, NULL},
 	 { (char *)"classObj_moveStyleDown", _wrap_classObj_moveStyleDown, METH_VARARGS, NULL},
 	 { (char *)"classObj_swigregister", classObj_swigregister, METH_VARARGS, NULL},
-	 { (char *)"labelCacheMemberObj_text_get", _wrap_labelCacheMemberObj_text_get, METH_VARARGS, NULL},
 	 { (char *)"labelCacheMemberObj_featuresize_get", _wrap_labelCacheMemberObj_featuresize_get, METH_VARARGS, NULL},
 	 { (char *)"labelCacheMemberObj_styles_get", _wrap_labelCacheMemberObj_styles_get, METH_VARARGS, NULL},
 	 { (char *)"labelCacheMemberObj_numstyles_get", _wrap_labelCacheMemberObj_numstyles_get, METH_VARARGS, NULL},
-	 { (char *)"labelCacheMemberObj_label_get", _wrap_labelCacheMemberObj_label_get, METH_VARARGS, NULL},
+	 { (char *)"labelCacheMemberObj_labels_get", _wrap_labelCacheMemberObj_labels_get, METH_VARARGS, NULL},
+	 { (char *)"labelCacheMemberObj_numlabels_get", _wrap_labelCacheMemberObj_numlabels_get, METH_VARARGS, NULL},
 	 { (char *)"labelCacheMemberObj_layerindex_get", _wrap_labelCacheMemberObj_layerindex_get, METH_VARARGS, NULL},
 	 { (char *)"labelCacheMemberObj_classindex_get", _wrap_labelCacheMemberObj_classindex_get, METH_VARARGS, NULL},
-	 { (char *)"labelCacheMemberObj_tileindex_get", _wrap_labelCacheMemberObj_tileindex_get, METH_VARARGS, NULL},
-	 { (char *)"labelCacheMemberObj_shapeindex_get", _wrap_labelCacheMemberObj_shapeindex_get, METH_VARARGS, NULL},
 	 { (char *)"labelCacheMemberObj_shapetype_get", _wrap_labelCacheMemberObj_shapetype_get, METH_VARARGS, NULL},
 	 { (char *)"labelCacheMemberObj_point_get", _wrap_labelCacheMemberObj_point_get, METH_VARARGS, NULL},
 	 { (char *)"labelCacheMemberObj_poly_get", _wrap_labelCacheMemberObj_poly_get, METH_VARARGS, NULL},
 	 { (char *)"labelCacheMemberObj_status_get", _wrap_labelCacheMemberObj_status_get, METH_VARARGS, NULL},
 	 { (char *)"labelCacheMemberObj_markerid_get", _wrap_labelCacheMemberObj_markerid_get, METH_VARARGS, NULL},
+	 { (char *)"labelCacheMemberObj_leaderline_get", _wrap_labelCacheMemberObj_leaderline_get, METH_VARARGS, NULL},
+	 { (char *)"labelCacheMemberObj_leaderbbox_get", _wrap_labelCacheMemberObj_leaderbbox_get, METH_VARARGS, NULL},
 	 { (char *)"new_labelCacheMemberObj", _wrap_new_labelCacheMemberObj, METH_VARARGS, NULL},
 	 { (char *)"delete_labelCacheMemberObj", _wrap_delete_labelCacheMemberObj, METH_VARARGS, NULL},
 	 { (char *)"labelCacheMemberObj_swigregister", labelCacheMemberObj_swigregister, METH_VARARGS, NULL},
@@ -44899,6 +46539,7 @@ static PyMethodDef SwigMethods[] = {
 	 { (char *)"labelCacheSlotObj_swigregister", labelCacheSlotObj_swigregister, METH_VARARGS, NULL},
 	 { (char *)"labelCacheObj_slots_get", _wrap_labelCacheObj_slots_get, METH_VARARGS, NULL},
 	 { (char *)"labelCacheObj_numlabels_get", _wrap_labelCacheObj_numlabels_get, METH_VARARGS, NULL},
+	 { (char *)"labelCacheObj_gutter_get", _wrap_labelCacheObj_gutter_get, METH_VARARGS, NULL},
 	 { (char *)"labelCacheObj_freeCache", _wrap_labelCacheObj_freeCache, METH_VARARGS, NULL},
 	 { (char *)"new_labelCacheObj", _wrap_new_labelCacheObj, METH_VARARGS, NULL},
 	 { (char *)"delete_labelCacheObj", _wrap_delete_labelCacheObj, METH_VARARGS, NULL},
@@ -45024,6 +46665,21 @@ static PyMethodDef SwigMethods[] = {
 	 { (char *)"new_legendObj", _wrap_new_legendObj, METH_VARARGS, NULL},
 	 { (char *)"delete_legendObj", _wrap_delete_legendObj, METH_VARARGS, NULL},
 	 { (char *)"legendObj_swigregister", legendObj_swigregister, METH_VARARGS, NULL},
+	 { (char *)"imageObj_width_get", _wrap_imageObj_width_get, METH_VARARGS, NULL},
+	 { (char *)"imageObj_height_get", _wrap_imageObj_height_get, METH_VARARGS, NULL},
+	 { (char *)"imageObj_resolution_get", _wrap_imageObj_resolution_get, METH_VARARGS, NULL},
+	 { (char *)"imageObj_resolutionfactor_get", _wrap_imageObj_resolutionfactor_get, METH_VARARGS, NULL},
+	 { (char *)"imageObj_imagepath_get", _wrap_imageObj_imagepath_get, METH_VARARGS, NULL},
+	 { (char *)"imageObj_imageurl_get", _wrap_imageObj_imageurl_get, METH_VARARGS, NULL},
+	 { (char *)"imageObj_format_get", _wrap_imageObj_format_get, METH_VARARGS, NULL},
+	 { (char *)"delete_imageObj", _wrap_delete_imageObj, METH_VARARGS, NULL},
+	 { (char *)"imageObj_save", _wrap_imageObj_save, METH_VARARGS, NULL},
+	 { (char *)"imageObj_getBytes", _wrap_imageObj_getBytes, METH_VARARGS, NULL},
+	 { (char *)"imageObj_getSize", _wrap_imageObj_getSize, METH_VARARGS, NULL},
+	 { (char *)"new_imageObj", _wrap_new_imageObj, METH_VARARGS, NULL},
+	 { (char *)"imageObj_write", _wrap_imageObj_write, METH_VARARGS, NULL},
+	 { (char *)"imageObj_saveToString", _wrap_imageObj_saveToString, METH_VARARGS, NULL},
+	 { (char *)"imageObj_swigregister", imageObj_swigregister, METH_VARARGS, NULL},
 	 { (char *)"layerObj_classitem_set", _wrap_layerObj_classitem_set, METH_VARARGS, NULL},
 	 { (char *)"layerObj_classitem_get", _wrap_layerObj_classitem_get, METH_VARARGS, NULL},
 	 { (char *)"layerObj_refcount_get", _wrap_layerObj_refcount_get, METH_VARARGS, NULL},
@@ -45123,6 +46779,8 @@ static PyMethodDef SwigMethods[] = {
 	 { (char *)"layerObj_numjoins_get", _wrap_layerObj_numjoins_get, METH_VARARGS, NULL},
 	 { (char *)"layerObj_classgroup_set", _wrap_layerObj_classgroup_set, METH_VARARGS, NULL},
 	 { (char *)"layerObj_classgroup_get", _wrap_layerObj_classgroup_get, METH_VARARGS, NULL},
+	 { (char *)"layerObj_mask_set", _wrap_layerObj_mask_set, METH_VARARGS, NULL},
+	 { (char *)"layerObj_mask_get", _wrap_layerObj_mask_get, METH_VARARGS, NULL},
 	 { (char *)"new_layerObj", _wrap_new_layerObj, METH_VARARGS, NULL},
 	 { (char *)"delete_layerObj", _wrap_delete_layerObj, METH_VARARGS, NULL},
 	 { (char *)"layerObj_clone", _wrap_layerObj_clone, METH_VARARGS, NULL},
@@ -45139,6 +46797,7 @@ static PyMethodDef SwigMethods[] = {
 	 { (char *)"layerObj_getResult", _wrap_layerObj_getResult, METH_VARARGS, NULL},
 	 { (char *)"layerObj_getClass", _wrap_layerObj_getClass, METH_VARARGS, NULL},
 	 { (char *)"layerObj_getItem", _wrap_layerObj_getItem, METH_VARARGS, NULL},
+	 { (char *)"layerObj_setItems", _wrap_layerObj_setItems, METH_VARARGS, NULL},
 	 { (char *)"layerObj_draw", _wrap_layerObj_draw, METH_VARARGS, NULL},
 	 { (char *)"layerObj_drawQuery", _wrap_layerObj_drawQuery, METH_VARARGS, NULL},
 	 { (char *)"layerObj_queryByFilter", _wrap_layerObj_queryByFilter, METH_VARARGS, NULL},
@@ -45315,21 +46974,6 @@ static PyMethodDef SwigMethods[] = {
 	 { (char *)"mapObj_setLayerOrder", _wrap_mapObj_setLayerOrder, METH_VARARGS, NULL},
 	 { (char *)"mapObj_getSize", _wrap_mapObj_getSize, METH_VARARGS, NULL},
 	 { (char *)"mapObj_swigregister", mapObj_swigregister, METH_VARARGS, NULL},
-	 { (char *)"imageObj_width_get", _wrap_imageObj_width_get, METH_VARARGS, NULL},
-	 { (char *)"imageObj_height_get", _wrap_imageObj_height_get, METH_VARARGS, NULL},
-	 { (char *)"imageObj_resolution_get", _wrap_imageObj_resolution_get, METH_VARARGS, NULL},
-	 { (char *)"imageObj_resolutionfactor_get", _wrap_imageObj_resolutionfactor_get, METH_VARARGS, NULL},
-	 { (char *)"imageObj_imagepath_get", _wrap_imageObj_imagepath_get, METH_VARARGS, NULL},
-	 { (char *)"imageObj_imageurl_get", _wrap_imageObj_imageurl_get, METH_VARARGS, NULL},
-	 { (char *)"imageObj_format_get", _wrap_imageObj_format_get, METH_VARARGS, NULL},
-	 { (char *)"delete_imageObj", _wrap_delete_imageObj, METH_VARARGS, NULL},
-	 { (char *)"imageObj_save", _wrap_imageObj_save, METH_VARARGS, NULL},
-	 { (char *)"imageObj_getBytes", _wrap_imageObj_getBytes, METH_VARARGS, NULL},
-	 { (char *)"imageObj_getSize", _wrap_imageObj_getSize, METH_VARARGS, NULL},
-	 { (char *)"new_imageObj", _wrap_new_imageObj, METH_VARARGS, NULL},
-	 { (char *)"imageObj_write", _wrap_imageObj_write, METH_VARARGS, NULL},
-	 { (char *)"imageObj_saveToString", _wrap_imageObj_saveToString, METH_VARARGS, NULL},
-	 { (char *)"imageObj_swigregister", imageObj_swigregister, METH_VARARGS, NULL},
 	 { (char *)"msSaveImage", _wrap_msSaveImage, METH_VARARGS, NULL},
 	 { (char *)"msFreeImage", _wrap_msFreeImage, METH_VARARGS, NULL},
 	 { (char *)"msSetup", _wrap_msSetup, METH_VARARGS, NULL},
@@ -45341,6 +46985,8 @@ static PyMethodDef SwigMethods[] = {
 	 { (char *)"strokeStyleObj_patternlength_get", _wrap_strokeStyleObj_patternlength_get, METH_VARARGS, NULL},
 	 { (char *)"strokeStyleObj_pattern_set", _wrap_strokeStyleObj_pattern_set, METH_VARARGS, NULL},
 	 { (char *)"strokeStyleObj_pattern_get", _wrap_strokeStyleObj_pattern_get, METH_VARARGS, NULL},
+	 { (char *)"strokeStyleObj_patternoffset_set", _wrap_strokeStyleObj_patternoffset_set, METH_VARARGS, NULL},
+	 { (char *)"strokeStyleObj_patternoffset_get", _wrap_strokeStyleObj_patternoffset_get, METH_VARARGS, NULL},
 	 { (char *)"strokeStyleObj_color_set", _wrap_strokeStyleObj_color_set, METH_VARARGS, NULL},
 	 { (char *)"strokeStyleObj_color_get", _wrap_strokeStyleObj_color_get, METH_VARARGS, NULL},
 	 { (char *)"strokeStyleObj_linecap_set", _wrap_strokeStyleObj_linecap_set, METH_VARARGS, NULL},
@@ -45396,8 +47042,10 @@ static PyMethodDef SwigMethods[] = {
 	 { (char *)"new_tileCacheObj", _wrap_new_tileCacheObj, METH_VARARGS, NULL},
 	 { (char *)"delete_tileCacheObj", _wrap_delete_tileCacheObj, METH_VARARGS, NULL},
 	 { (char *)"tileCacheObj_swigregister", tileCacheObj_swigregister, METH_VARARGS, NULL},
-	 { (char *)"labelStyleObj_font_set", _wrap_labelStyleObj_font_set, METH_VARARGS, NULL},
-	 { (char *)"labelStyleObj_font_get", _wrap_labelStyleObj_font_get, METH_VARARGS, NULL},
+	 { (char *)"labelStyleObj_fonts_set", _wrap_labelStyleObj_fonts_set, METH_VARARGS, NULL},
+	 { (char *)"labelStyleObj_fonts_get", _wrap_labelStyleObj_fonts_get, METH_VARARGS, NULL},
+	 { (char *)"labelStyleObj_numfonts_set", _wrap_labelStyleObj_numfonts_set, METH_VARARGS, NULL},
+	 { (char *)"labelStyleObj_numfonts_get", _wrap_labelStyleObj_numfonts_get, METH_VARARGS, NULL},
 	 { (char *)"labelStyleObj_size_set", _wrap_labelStyleObj_size_set, METH_VARARGS, NULL},
 	 { (char *)"labelStyleObj_size_get", _wrap_labelStyleObj_size_get, METH_VARARGS, NULL},
 	 { (char *)"labelStyleObj_rotation_set", _wrap_labelStyleObj_rotation_set, METH_VARARGS, NULL},
@@ -45408,6 +47056,8 @@ static PyMethodDef SwigMethods[] = {
 	 { (char *)"labelStyleObj_outlinewidth_get", _wrap_labelStyleObj_outlinewidth_get, METH_VARARGS, NULL},
 	 { (char *)"labelStyleObj_outlinecolor_set", _wrap_labelStyleObj_outlinecolor_set, METH_VARARGS, NULL},
 	 { (char *)"labelStyleObj_outlinecolor_get", _wrap_labelStyleObj_outlinecolor_get, METH_VARARGS, NULL},
+	 { (char *)"labelStyleObj_antialias_set", _wrap_labelStyleObj_antialias_set, METH_VARARGS, NULL},
+	 { (char *)"labelStyleObj_antialias_get", _wrap_labelStyleObj_antialias_get, METH_VARARGS, NULL},
 	 { (char *)"new_labelStyleObj", _wrap_new_labelStyleObj, METH_VARARGS, NULL},
 	 { (char *)"delete_labelStyleObj", _wrap_delete_labelStyleObj, METH_VARARGS, NULL},
 	 { (char *)"labelStyleObj_swigregister", labelStyleObj_swigregister, METH_VARARGS, NULL},
@@ -45554,13 +47204,13 @@ static PyMethodDef SwigMethods[] = {
 	 { (char *)"shapefileObj_swigregister", shapefileObj_swigregister, METH_VARARGS, NULL},
 	 { (char *)"projectionObj_numargs_get", _wrap_projectionObj_numargs_get, METH_VARARGS, NULL},
 	 { (char *)"projectionObj_automatic_get", _wrap_projectionObj_automatic_get, METH_VARARGS, NULL},
+	 { (char *)"projectionObj_wellknownprojection_set", _wrap_projectionObj_wellknownprojection_set, METH_VARARGS, NULL},
+	 { (char *)"projectionObj_wellknownprojection_get", _wrap_projectionObj_wellknownprojection_get, METH_VARARGS, NULL},
 	 { (char *)"new_projectionObj", _wrap_new_projectionObj, METH_VARARGS, NULL},
 	 { (char *)"delete_projectionObj", _wrap_delete_projectionObj, METH_VARARGS, NULL},
 	 { (char *)"projectionObj_setWKTProjection", _wrap_projectionObj_setWKTProjection, METH_VARARGS, NULL},
 	 { (char *)"projectionObj_getUnits", _wrap_projectionObj_getUnits, METH_VARARGS, NULL},
 	 { (char *)"projectionObj_swigregister", projectionObj_swigregister, METH_VARARGS, NULL},
-	 { (char *)"colorObj_pen_set", _wrap_colorObj_pen_set, METH_VARARGS, NULL},
-	 { (char *)"colorObj_pen_get", _wrap_colorObj_pen_get, METH_VARARGS, NULL},
 	 { (char *)"colorObj_red_set", _wrap_colorObj_red_set, METH_VARARGS, NULL},
 	 { (char *)"colorObj_red_get", _wrap_colorObj_red_get, METH_VARARGS, NULL},
 	 { (char *)"colorObj_green_set", _wrap_colorObj_green_set, METH_VARARGS, NULL},
@@ -45597,6 +47247,10 @@ static PyMethodDef SwigMethods[] = {
 	 { (char *)"symbolObj_numpoints_get", _wrap_symbolObj_numpoints_get, METH_VARARGS, NULL},
 	 { (char *)"symbolObj_filled_set", _wrap_symbolObj_filled_set, METH_VARARGS, NULL},
 	 { (char *)"symbolObj_filled_get", _wrap_symbolObj_filled_get, METH_VARARGS, NULL},
+	 { (char *)"symbolObj_anchorpoint_x_set", _wrap_symbolObj_anchorpoint_x_set, METH_VARARGS, NULL},
+	 { (char *)"symbolObj_anchorpoint_x_get", _wrap_symbolObj_anchorpoint_x_get, METH_VARARGS, NULL},
+	 { (char *)"symbolObj_anchorpoint_y_set", _wrap_symbolObj_anchorpoint_y_set, METH_VARARGS, NULL},
+	 { (char *)"symbolObj_anchorpoint_y_get", _wrap_symbolObj_anchorpoint_y_get, METH_VARARGS, NULL},
 	 { (char *)"symbolObj_imagepath_get", _wrap_symbolObj_imagepath_get, METH_VARARGS, NULL},
 	 { (char *)"symbolObj_transparent_set", _wrap_symbolObj_transparent_set, METH_VARARGS, NULL},
 	 { (char *)"symbolObj_transparent_get", _wrap_symbolObj_transparent_get, METH_VARARGS, NULL},
@@ -45658,6 +47312,7 @@ static PyMethodDef SwigMethods[] = {
 	 { (char *)"OWSRequest_loadParams", _wrap_OWSRequest_loadParams, METH_VARARGS, NULL},
 	 { (char *)"OWSRequest_loadParamsFromURL", _wrap_OWSRequest_loadParamsFromURL, METH_VARARGS, NULL},
 	 { (char *)"OWSRequest_setParameter", _wrap_OWSRequest_setParameter, METH_VARARGS, NULL},
+	 { (char *)"OWSRequest_addParameter", _wrap_OWSRequest_addParameter, METH_VARARGS, NULL},
 	 { (char *)"OWSRequest_getName", _wrap_OWSRequest_getName, METH_VARARGS, NULL},
 	 { (char *)"OWSRequest_getValue", _wrap_OWSRequest_getValue, METH_VARARGS, NULL},
 	 { (char *)"OWSRequest_getValueByName", _wrap_OWSRequest_getValueByName, METH_VARARGS, NULL},
@@ -45684,12 +47339,12 @@ static swig_type_info _swigt__p_DBFInfo = {"_p_DBFInfo", "DBFInfo *", 0, 0, (voi
 static swig_type_info _swigt__p_FILE = {"_p_FILE", "FILE *", 0, 0, (void*)0, 0};
 static swig_type_info _swigt__p_cgiRequestObj = {"_p_cgiRequestObj", "cgiRequestObj *", 0, 0, (void*)0, 0};
 static swig_type_info _swigt__p_char = {"_p_char", "char *", 0, 0, (void*)0, 0};
-static swig_type_info _swigt__p_class_obj = {"_p_class_obj", "classObj *|struct class_obj *", 0, 0, (void*)0, 0};
+static swig_type_info _swigt__p_classObj = {"_p_classObj", "struct classObj *|classObj *", 0, 0, (void*)0, 0};
 static swig_type_info _swigt__p_clusterObj = {"_p_clusterObj", "clusterObj *", 0, 0, (void*)0, 0};
 static swig_type_info _swigt__p_colorObj = {"_p_colorObj", "colorObj *", 0, 0, (void*)0, 0};
 static swig_type_info _swigt__p_debugLevel = {"_p_debugLevel", "enum debugLevel *|debugLevel *", 0, 0, (void*)0, 0};
 static swig_type_info _swigt__p_double = {"_p_double", "double *", 0, 0, (void*)0, 0};
-static swig_type_info _swigt__p_error_obj = {"_p_error_obj", "struct error_obj *|errorObj *", 0, 0, (void*)0, 0};
+static swig_type_info _swigt__p_errorObj = {"_p_errorObj", "struct errorObj *|errorObj *", 0, 0, (void*)0, 0};
 static swig_type_info _swigt__p_fontSetObj = {"_p_fontSetObj", "fontSetObj *", 0, 0, (void*)0, 0};
 static swig_type_info _swigt__p_hashTableObj = {"_p_hashTableObj", "hashTableObj *", 0, 0, (void*)0, 0};
 static swig_type_info _swigt__p_imageObj = {"_p_imageObj", "imageObj *", 0, 0, (void*)0, 0};
@@ -45699,12 +47354,13 @@ static swig_type_info _swigt__p_intarray = {"_p_intarray", "struct intarray *|in
 static swig_type_info _swigt__p_labelCacheMemberObj = {"_p_labelCacheMemberObj", "labelCacheMemberObj *", 0, 0, (void*)0, 0};
 static swig_type_info _swigt__p_labelCacheObj = {"_p_labelCacheObj", "labelCacheObj *", 0, 0, (void*)0, 0};
 static swig_type_info _swigt__p_labelCacheSlotObj = {"_p_labelCacheSlotObj", "labelCacheSlotObj *", 0, 0, (void*)0, 0};
+static swig_type_info _swigt__p_labelLeaderObj = {"_p_labelLeaderObj", "labelLeaderObj *", 0, 0, (void*)0, 0};
 static swig_type_info _swigt__p_labelObj = {"_p_labelObj", "labelObj *", 0, 0, (void*)0, 0};
 static swig_type_info _swigt__p_labelStyleObj = {"_p_labelStyleObj", "labelStyleObj *", 0, 0, (void*)0, 0};
-static swig_type_info _swigt__p_layer_obj = {"_p_layer_obj", "struct layer_obj *|layerObj *", 0, 0, (void*)0, 0};
+static swig_type_info _swigt__p_layerObj = {"_p_layerObj", "struct layerObj *|layerObj *", 0, 0, (void*)0, 0};
 static swig_type_info _swigt__p_legendObj = {"_p_legendObj", "legendObj *", 0, 0, (void*)0, 0};
 static swig_type_info _swigt__p_lineObj = {"_p_lineObj", "lineObj *|multipointObj *", 0, 0, (void*)0, 0};
-static swig_type_info _swigt__p_map_obj = {"_p_map_obj", "mapObj *|struct map_obj *", 0, 0, (void*)0, 0};
+static swig_type_info _swigt__p_mapObj = {"_p_mapObj", "struct mapObj *|mapObj *", 0, 0, (void*)0, 0};
 static swig_type_info _swigt__p_markerCacheMemberObj = {"_p_markerCacheMemberObj", "markerCacheMemberObj *", 0, 0, (void*)0, 0};
 static swig_type_info _swigt__p_outputFormatObj = {"_p_outputFormatObj", "outputFormatObj *", 0, 0, (void*)0, 0};
 static swig_type_info _swigt__p_p_char = {"_p_p_char", "char **", 0, 0, (void*)0, 0};
@@ -45736,12 +47392,12 @@ static swig_type_info *swig_type_initial[] = {
   &_swigt__p_FILE,
   &_swigt__p_cgiRequestObj,
   &_swigt__p_char,
-  &_swigt__p_class_obj,
+  &_swigt__p_classObj,
   &_swigt__p_clusterObj,
   &_swigt__p_colorObj,
   &_swigt__p_debugLevel,
   &_swigt__p_double,
-  &_swigt__p_error_obj,
+  &_swigt__p_errorObj,
   &_swigt__p_fontSetObj,
   &_swigt__p_hashTableObj,
   &_swigt__p_imageObj,
@@ -45751,12 +47407,13 @@ static swig_type_info *swig_type_initial[] = {
   &_swigt__p_labelCacheMemberObj,
   &_swigt__p_labelCacheObj,
   &_swigt__p_labelCacheSlotObj,
+  &_swigt__p_labelLeaderObj,
   &_swigt__p_labelObj,
   &_swigt__p_labelStyleObj,
-  &_swigt__p_layer_obj,
+  &_swigt__p_layerObj,
   &_swigt__p_legendObj,
   &_swigt__p_lineObj,
-  &_swigt__p_map_obj,
+  &_swigt__p_mapObj,
   &_swigt__p_markerCacheMemberObj,
   &_swigt__p_outputFormatObj,
   &_swigt__p_p_char,
@@ -45788,12 +47445,12 @@ static swig_cast_info _swigc__p_DBFInfo[] = {  {&_swigt__p_DBFInfo, 0, 0, 0},{0,
 static swig_cast_info _swigc__p_FILE[] = {  {&_swigt__p_FILE, 0, 0, 0},{0, 0, 0, 0}};
 static swig_cast_info _swigc__p_cgiRequestObj[] = {  {&_swigt__p_cgiRequestObj, 0, 0, 0},{0, 0, 0, 0}};
 static swig_cast_info _swigc__p_char[] = {  {&_swigt__p_char, 0, 0, 0},{0, 0, 0, 0}};
-static swig_cast_info _swigc__p_class_obj[] = {  {&_swigt__p_class_obj, 0, 0, 0},{0, 0, 0, 0}};
+static swig_cast_info _swigc__p_classObj[] = {  {&_swigt__p_classObj, 0, 0, 0},{0, 0, 0, 0}};
 static swig_cast_info _swigc__p_clusterObj[] = {  {&_swigt__p_clusterObj, 0, 0, 0},{0, 0, 0, 0}};
 static swig_cast_info _swigc__p_colorObj[] = {  {&_swigt__p_colorObj, 0, 0, 0},{0, 0, 0, 0}};
 static swig_cast_info _swigc__p_debugLevel[] = {  {&_swigt__p_debugLevel, 0, 0, 0},{0, 0, 0, 0}};
 static swig_cast_info _swigc__p_double[] = {  {&_swigt__p_double, 0, 0, 0},{0, 0, 0, 0}};
-static swig_cast_info _swigc__p_error_obj[] = {  {&_swigt__p_error_obj, 0, 0, 0},{0, 0, 0, 0}};
+static swig_cast_info _swigc__p_errorObj[] = {  {&_swigt__p_errorObj, 0, 0, 0},{0, 0, 0, 0}};
 static swig_cast_info _swigc__p_fontSetObj[] = {  {&_swigt__p_fontSetObj, 0, 0, 0},{0, 0, 0, 0}};
 static swig_cast_info _swigc__p_hashTableObj[] = {  {&_swigt__p_hashTableObj, 0, 0, 0},{0, 0, 0, 0}};
 static swig_cast_info _swigc__p_imageObj[] = {  {&_swigt__p_imageObj, 0, 0, 0},{0, 0, 0, 0}};
@@ -45803,12 +47460,13 @@ static swig_cast_info _swigc__p_intarray[] = {  {&_swigt__p_intarray, 0, 0, 0},{
 static swig_cast_info _swigc__p_labelCacheMemberObj[] = {  {&_swigt__p_labelCacheMemberObj, 0, 0, 0},{0, 0, 0, 0}};
 static swig_cast_info _swigc__p_labelCacheObj[] = {  {&_swigt__p_labelCacheObj, 0, 0, 0},{0, 0, 0, 0}};
 static swig_cast_info _swigc__p_labelCacheSlotObj[] = {  {&_swigt__p_labelCacheSlotObj, 0, 0, 0},{0, 0, 0, 0}};
+static swig_cast_info _swigc__p_labelLeaderObj[] = {  {&_swigt__p_labelLeaderObj, 0, 0, 0},{0, 0, 0, 0}};
 static swig_cast_info _swigc__p_labelObj[] = {  {&_swigt__p_labelObj, 0, 0, 0},{0, 0, 0, 0}};
 static swig_cast_info _swigc__p_labelStyleObj[] = {  {&_swigt__p_labelStyleObj, 0, 0, 0},{0, 0, 0, 0}};
-static swig_cast_info _swigc__p_layer_obj[] = {  {&_swigt__p_layer_obj, 0, 0, 0},{0, 0, 0, 0}};
+static swig_cast_info _swigc__p_layerObj[] = {  {&_swigt__p_layerObj, 0, 0, 0},{0, 0, 0, 0}};
 static swig_cast_info _swigc__p_legendObj[] = {  {&_swigt__p_legendObj, 0, 0, 0},{0, 0, 0, 0}};
 static swig_cast_info _swigc__p_lineObj[] = {  {&_swigt__p_lineObj, 0, 0, 0},{0, 0, 0, 0}};
-static swig_cast_info _swigc__p_map_obj[] = {  {&_swigt__p_map_obj, 0, 0, 0},{0, 0, 0, 0}};
+static swig_cast_info _swigc__p_mapObj[] = {  {&_swigt__p_mapObj, 0, 0, 0},{0, 0, 0, 0}};
 static swig_cast_info _swigc__p_markerCacheMemberObj[] = {  {&_swigt__p_markerCacheMemberObj, 0, 0, 0},{0, 0, 0, 0}};
 static swig_cast_info _swigc__p_outputFormatObj[] = {  {&_swigt__p_outputFormatObj, 0, 0, 0},{0, 0, 0, 0}};
 static swig_cast_info _swigc__p_p_char[] = {  {&_swigt__p_p_char, 0, 0, 0},{0, 0, 0, 0}};
@@ -45840,12 +47498,12 @@ static swig_cast_info *swig_cast_initial[] = {
   _swigc__p_FILE,
   _swigc__p_cgiRequestObj,
   _swigc__p_char,
-  _swigc__p_class_obj,
+  _swigc__p_classObj,
   _swigc__p_clusterObj,
   _swigc__p_colorObj,
   _swigc__p_debugLevel,
   _swigc__p_double,
-  _swigc__p_error_obj,
+  _swigc__p_errorObj,
   _swigc__p_fontSetObj,
   _swigc__p_hashTableObj,
   _swigc__p_imageObj,
@@ -45855,12 +47513,13 @@ static swig_cast_info *swig_cast_initial[] = {
   _swigc__p_labelCacheMemberObj,
   _swigc__p_labelCacheObj,
   _swigc__p_labelCacheSlotObj,
+  _swigc__p_labelLeaderObj,
   _swigc__p_labelObj,
   _swigc__p_labelStyleObj,
-  _swigc__p_layer_obj,
+  _swigc__p_layerObj,
   _swigc__p_legendObj,
   _swigc__p_lineObj,
-  _swigc__p_map_obj,
+  _swigc__p_mapObj,
   _swigc__p_markerCacheMemberObj,
   _swigc__p_outputFormatObj,
   _swigc__p_p_char,
@@ -46500,12 +48159,11 @@ SWIG_init(void) {
   PyDict_SetItemString(d, "MapServerChildError", MSExc_MapServerChildError);
   
   
-  SWIG_Python_SetConstant(d, "MS_VERSION",SWIG_FromCharPtr("6.0.3"));
+  SWIG_Python_SetConstant(d, "MS_VERSION",SWIG_FromCharPtr("6.2.0"));
   SWIG_Python_SetConstant(d, "MS_VERSION_MAJOR",SWIG_From_int((int)(6)));
-  SWIG_Python_SetConstant(d, "MS_VERSION_MINOR",SWIG_From_int((int)(0)));
-  SWIG_Python_SetConstant(d, "MS_VERSION_REV",SWIG_From_int((int)(3)));
-  SWIG_Python_SetConstant(d, "MS_VERSION_NUM",SWIG_From_int((int)((6*10000+0*100+3))));
-  SWIG_Python_SetConstant(d, "__FUNCTION__",SWIG_FromCharPtr("MapServer"));
+  SWIG_Python_SetConstant(d, "MS_VERSION_MINOR",SWIG_From_int((int)(2)));
+  SWIG_Python_SetConstant(d, "MS_VERSION_REV",SWIG_From_int((int)(0)));
+  SWIG_Python_SetConstant(d, "MS_VERSION_NUM",SWIG_From_int((int)((6*10000+2*100+0))));
   SWIG_Python_SetConstant(d, "MS_TRUE",SWIG_From_int((int)(1)));
   SWIG_Python_SetConstant(d, "MS_FALSE",SWIG_From_int((int)(0)));
   SWIG_Python_SetConstant(d, "MS_UNKNOWN",SWIG_From_int((int)(-1)));
@@ -46520,8 +48178,11 @@ SWIG_init(void) {
   SWIG_Python_SetConstant(d, "MS_LAYER_ALLOCSIZE",SWIG_From_int((int)(64)));
   SWIG_Python_SetConstant(d, "MS_CLASS_ALLOCSIZE",SWIG_From_int((int)(8)));
   SWIG_Python_SetConstant(d, "MS_STYLE_ALLOCSIZE",SWIG_From_int((int)(4)));
+  SWIG_Python_SetConstant(d, "MS_LABEL_ALLOCSIZE",SWIG_From_int((int)(2)));
   SWIG_Python_SetConstant(d, "MS_MAX_LABEL_PRIORITY",SWIG_From_int((int)(10)));
+  SWIG_Python_SetConstant(d, "MS_MAX_LABEL_FONTS",SWIG_From_int((int)(5)));
   SWIG_Python_SetConstant(d, "MS_DEFAULT_LABEL_PRIORITY",SWIG_From_int((int)(1)));
+  SWIG_Python_SetConstant(d, "MS_LABEL_FORCE_GROUP",SWIG_From_int((int)(2)));
   SWIG_Python_SetConstant(d, "MS_RENDER_WITH_SWF",SWIG_From_int((int)(2)));
   SWIG_Python_SetConstant(d, "MS_RENDER_WITH_RAWDATA",SWIG_From_int((int)(3)));
   SWIG_Python_SetConstant(d, "MS_RENDER_WITH_IMAGEMAP",SWIG_From_int((int)(5)));
@@ -46599,6 +48260,7 @@ SWIG_init(void) {
   SWIG_Python_SetConstant(d, "MS_RASTER",SWIG_From_int((int)(MS_RASTER)));
   SWIG_Python_SetConstant(d, "MS_PLUGIN",SWIG_From_int((int)(MS_PLUGIN)));
   SWIG_Python_SetConstant(d, "MS_UNION",SWIG_From_int((int)(MS_UNION)));
+  SWIG_Python_SetConstant(d, "MS_UVRASTER",SWIG_From_int((int)(MS_UVRASTER)));
   SWIG_Python_SetConstant(d, "MS_DB_XBASE",SWIG_From_int((int)(MS_DB_XBASE)));
   SWIG_Python_SetConstant(d, "MS_DB_CSV",SWIG_From_int((int)(MS_DB_CSV)));
   SWIG_Python_SetConstant(d, "MS_DB_MYSQL",SWIG_From_int((int)(MS_DB_MYSQL)));
@@ -46654,7 +48316,7 @@ SWIG_init(void) {
   SWIG_Python_SetConstant(d, "MS_TRANSFORM_SNAPTOGRID",SWIG_From_int((int)(MS_TRANSFORM_SNAPTOGRID)));
   SWIG_Python_SetConstant(d, "MS_TRANSFORM_FULLRESOLUTION",SWIG_From_int((int)(MS_TRANSFORM_FULLRESOLUTION)));
   SWIG_Python_SetConstant(d, "MS_TRANSFORM_SIMPLIFY",SWIG_From_int((int)(MS_TRANSFORM_SIMPLIFY)));
-  SWIG_Python_SetConstant(d, "MS_STYLE_BINDING_LENGTH",SWIG_From_int((int)(8)));
+  SWIG_Python_SetConstant(d, "MS_STYLE_BINDING_LENGTH",SWIG_From_int((int)(12)));
   SWIG_Python_SetConstant(d, "MS_STYLE_BINDING_SIZE",SWIG_From_int((int)(MS_STYLE_BINDING_SIZE)));
   SWIG_Python_SetConstant(d, "MS_STYLE_BINDING_WIDTH",SWIG_From_int((int)(MS_STYLE_BINDING_WIDTH)));
   SWIG_Python_SetConstant(d, "MS_STYLE_BINDING_ANGLE",SWIG_From_int((int)(MS_STYLE_BINDING_ANGLE)));
@@ -46663,6 +48325,10 @@ SWIG_init(void) {
   SWIG_Python_SetConstant(d, "MS_STYLE_BINDING_SYMBOL",SWIG_From_int((int)(MS_STYLE_BINDING_SYMBOL)));
   SWIG_Python_SetConstant(d, "MS_STYLE_BINDING_OUTLINEWIDTH",SWIG_From_int((int)(MS_STYLE_BINDING_OUTLINEWIDTH)));
   SWIG_Python_SetConstant(d, "MS_STYLE_BINDING_OPACITY",SWIG_From_int((int)(MS_STYLE_BINDING_OPACITY)));
+  SWIG_Python_SetConstant(d, "MS_STYLE_BINDING_OFFSET_X",SWIG_From_int((int)(MS_STYLE_BINDING_OFFSET_X)));
+  SWIG_Python_SetConstant(d, "MS_STYLE_BINDING_OFFSET_Y",SWIG_From_int((int)(MS_STYLE_BINDING_OFFSET_Y)));
+  SWIG_Python_SetConstant(d, "MS_STYLE_BINDING_POLAROFFSET_PIXEL",SWIG_From_int((int)(MS_STYLE_BINDING_POLAROFFSET_PIXEL)));
+  SWIG_Python_SetConstant(d, "MS_STYLE_BINDING_POLAROFFSET_ANGLE",SWIG_From_int((int)(MS_STYLE_BINDING_POLAROFFSET_ANGLE)));
   SWIG_Python_SetConstant(d, "MS_LABEL_BINDING_LENGTH",SWIG_From_int((int)(9)));
   SWIG_Python_SetConstant(d, "MS_LABEL_BINDING_SIZE",SWIG_From_int((int)(MS_LABEL_BINDING_SIZE)));
   SWIG_Python_SetConstant(d, "MS_LABEL_BINDING_ANGLE",SWIG_From_int((int)(MS_LABEL_BINDING_ANGLE)));
@@ -46707,6 +48373,7 @@ SWIG_init(void) {
   SWIG_Python_SetConstant(d, "MS_TOKEN_FUNCTION_ROUND",SWIG_From_int((int)(MS_TOKEN_FUNCTION_ROUND)));
   SWIG_Python_SetConstant(d, "MS_TOKEN_FUNCTION_FROMTEXT",SWIG_From_int((int)(MS_TOKEN_FUNCTION_FROMTEXT)));
   SWIG_Python_SetConstant(d, "MS_TOKEN_FUNCTION_BUFFER",SWIG_From_int((int)(MS_TOKEN_FUNCTION_BUFFER)));
+  SWIG_Python_SetConstant(d, "MS_TOKEN_FUNCTION_DIFFERENCE",SWIG_From_int((int)(MS_TOKEN_FUNCTION_DIFFERENCE)));
   SWIG_Python_SetConstant(d, "MS_TOKEN_BINDING_DOUBLE",SWIG_From_int((int)(MS_TOKEN_BINDING_DOUBLE)));
   SWIG_Python_SetConstant(d, "MS_TOKEN_BINDING_INTEGER",SWIG_From_int((int)(MS_TOKEN_BINDING_INTEGER)));
   SWIG_Python_SetConstant(d, "MS_TOKEN_BINDING_STRING",SWIG_From_int((int)(MS_TOKEN_BINDING_STRING)));
@@ -46733,6 +48400,9 @@ SWIG_init(void) {
   SWIG_Python_SetConstant(d, "FTInteger",SWIG_From_int((int)(FTInteger)));
   SWIG_Python_SetConstant(d, "FTDouble",SWIG_From_int((int)(FTDouble)));
   SWIG_Python_SetConstant(d, "FTInvalid",SWIG_From_int((int)(FTInvalid)));
+  SWIG_Python_SetConstant(d, "wkp_none",SWIG_From_int((int)(0)));
+  SWIG_Python_SetConstant(d, "wkp_lonlat",SWIG_From_int((int)(1)));
+  SWIG_Python_SetConstant(d, "wkp_gmerc",SWIG_From_int((int)(2)));
   SWIG_Python_SetConstant(d, "MS_SYMBOL_SIMPLE",SWIG_From_int((int)(MS_SYMBOL_SIMPLE)));
   SWIG_Python_SetConstant(d, "MS_SYMBOL_VECTOR",SWIG_From_int((int)(MS_SYMBOL_VECTOR)));
   SWIG_Python_SetConstant(d, "MS_SYMBOL_ELLIPSE",SWIG_From_int((int)(MS_SYMBOL_ELLIPSE)));
diff --git a/mapscript/python/pyextend.i b/mapscript/python/pyextend.i
index aa31568..2262ae7 100644
--- a/mapscript/python/pyextend.i
+++ b/mapscript/python/pyextend.i
@@ -168,6 +168,7 @@ def fromstring(data, mappath=None):
     imageObj(PyObject *arg1=Py_None, PyObject *arg2=Py_None, 
              PyObject *input_format=Py_None, PyObject *input_resolution=Py_None, PyObject *input_defresolution=Py_None)
     {
+#ifdef FORCE_BROKEN_GD_CODE
         imageObj *image=NULL;
         outputFormatObj *format=NULL;
         int width;
@@ -318,6 +319,10 @@ def fromstring(data, mappath=None):
                        "imageObj()");
             return NULL;
         }
+#else
+         msSetError(MS_IMGERR, "imageObj() is severely broken and should not be used","imageObj()");
+         return NULL;
+#endif
     }
   
     /* ======================================================================
@@ -349,7 +354,8 @@ def fromstring(data, mappath=None):
         else if (PyFile_Check(file)) /* a Python (C) file */
         {
             renderer = self->format->vtable;
-            retval = renderer->saveImage(self, PyFile_AsFile(file), self->format);
+            /* FIXME? as an improvement, pass a map argument instead of the NULL (see #4216) */
+            retval = renderer->saveImage(self, NULL, PyFile_AsFile(file), self->format);
         }
         else /* presume a Python file-like object */
         {
diff --git a/mapscript/python/pygdioctx/pygdioctx.c b/mapscript/python/pygdioctx/pygdioctx.c
index 6b6e9ed..b1eb27d 100644
--- a/mapscript/python/pygdioctx/pygdioctx.c
+++ b/mapscript/python/pygdioctx/pygdioctx.c
@@ -7,11 +7,11 @@
  *
  ******************************************************************************
  * The PyFileIfaceObj_IOCtx API is
- * 
+ *
  * Copyright 1995 Richard Jones, Bureau of Meteorology Australia.
  * richard at bofh.asn.au
  *
- * Current maintainer is 
+ * Current maintainer is
  * Chris Gonnerman <chris.gonnerman at newcenturycomputers.net>
  * Please direct all questions and problems to me.
  *
@@ -32,7 +32,7 @@
  * distribution.  Neither the name of the Bureau of Meteorology
  * Australia nor the names of its contributors may be used to endorse
  * or promote products derived from this software without specific
- * prior written permission. 
+ * prior written permission.
  *
  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
@@ -47,87 +47,88 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  * ***************************************************************************/
 
+#ifdef USE_GD
+
 #include "pygdioctx.h"
 
 int PyFileIfaceObj_IOCtx_GetC(gdIOCtx *ctx)
 {
-    struct PyFileIfaceObj_gdIOCtx *pctx = (struct PyFileIfaceObj_gdIOCtx *)ctx;
-    if (pctx->strObj) {
-        Py_DECREF(pctx->strObj);
-        pctx->strObj = NULL;
-    }
-    pctx->strObj = PyObject_CallMethod(pctx->fileIfaceObj, "read", "i", 1);
-    if (!pctx->strObj || !PyString_Check(pctx->strObj)) {
-        return EOF;
-    }
-    if (PyString_GET_SIZE(pctx->strObj) == 1) {
-        return (int)(unsigned char)PyString_AS_STRING(pctx->strObj)[0];
-    }
+  struct PyFileIfaceObj_gdIOCtx *pctx = (struct PyFileIfaceObj_gdIOCtx *)ctx;
+  if (pctx->strObj) {
+    Py_DECREF(pctx->strObj);
+    pctx->strObj = NULL;
+  }
+  pctx->strObj = PyObject_CallMethod(pctx->fileIfaceObj, "read", "i", 1);
+  if (!pctx->strObj || !PyString_Check(pctx->strObj)) {
     return EOF;
+  }
+  if (PyString_GET_SIZE(pctx->strObj) == 1) {
+    return (int)(unsigned char)PyString_AS_STRING(pctx->strObj)[0];
+  }
+  return EOF;
 }
 
 int PyFileIfaceObj_IOCtx_GetBuf(gdIOCtx *ctx, void *data, int size)
 {
-    int err;
-    char *value;
-    struct PyFileIfaceObj_gdIOCtx *pctx = (struct PyFileIfaceObj_gdIOCtx *)ctx;
-    if (pctx->strObj) {
-        Py_DECREF(pctx->strObj);
-        pctx->strObj = NULL;
-    }
-    pctx->strObj = PyObject_CallMethod(pctx->fileIfaceObj, "read", "i", size);
-    if (!pctx->strObj) {
-        return 0;
-    }
-    err = PyString_AsStringAndSize(pctx->strObj, &value, &size);
-    if (err < 0) {
-        /* this throws away the python exception since the gd library
-         * won't pass it up properly.  gdmodule should create its own
-         * since the "file" couldn't be read properly.  */
-        PyErr_Clear();
-        return 0;
-    }
-    memcpy(data, value, size);
-    return size;
+  int err;
+  char *value;
+  struct PyFileIfaceObj_gdIOCtx *pctx = (struct PyFileIfaceObj_gdIOCtx *)ctx;
+  if (pctx->strObj) {
+    Py_DECREF(pctx->strObj);
+    pctx->strObj = NULL;
+  }
+  pctx->strObj = PyObject_CallMethod(pctx->fileIfaceObj, "read", "i", size);
+  if (!pctx->strObj) {
+    return 0;
+  }
+  err = PyString_AsStringAndSize(pctx->strObj, &value, &size);
+  if (err < 0) {
+    /* this throws away the python exception since the gd library
+     * won't pass it up properly.  gdmodule should create its own
+     * since the "file" couldn't be read properly.  */
+    PyErr_Clear();
+    return 0;
+  }
+  memcpy(data, value, size);
+  return size;
 }
 
 void PyFileIfaceObj_IOCtx_Free(gdIOCtx *ctx)
 {
-    struct PyFileIfaceObj_gdIOCtx *pctx = (struct PyFileIfaceObj_gdIOCtx *)ctx;
-    if (pctx->strObj) {
-        Py_DECREF(pctx->strObj);
-        pctx->strObj = NULL;
-    }
-    if (pctx->fileIfaceObj) {
-        Py_DECREF(pctx->fileIfaceObj);
-        pctx->fileIfaceObj = NULL;
-    }
-    /* NOTE: we leave deallocation of the ctx structure itself to outside
-     * code for memory allocation symmetry.  This function is safe to
-     * call multiple times (gd should call it + we call it to be safe). */
+  struct PyFileIfaceObj_gdIOCtx *pctx = (struct PyFileIfaceObj_gdIOCtx *)ctx;
+  if (pctx->strObj) {
+    Py_DECREF(pctx->strObj);
+    pctx->strObj = NULL;
+  }
+  if (pctx->fileIfaceObj) {
+    Py_DECREF(pctx->fileIfaceObj);
+    pctx->fileIfaceObj = NULL;
+  }
+  /* NOTE: we leave deallocation of the ctx structure itself to outside
+   * code for memory allocation symmetry.  This function is safe to
+   * call multiple times (gd should call it + we call it to be safe). */
 }
 
-struct PyFileIfaceObj_gdIOCtx * alloc_PyFileIfaceObj_IOCtx(PyObject *fileIfaceObj)
-{
-    struct PyFileIfaceObj_gdIOCtx *pctx;
-    pctx = calloc(1, sizeof(struct PyFileIfaceObj_gdIOCtx));
-    if (!pctx)
-        return NULL;
-    pctx->ctx.getC = PyFileIfaceObj_IOCtx_GetC; 
-    pctx->ctx.getBuf = PyFileIfaceObj_IOCtx_GetBuf;
-    pctx->ctx.gd_free = PyFileIfaceObj_IOCtx_Free;
-    Py_INCREF(fileIfaceObj);
-    pctx->fileIfaceObj = fileIfaceObj;
-    return pctx;
+struct PyFileIfaceObj_gdIOCtx * alloc_PyFileIfaceObj_IOCtx(PyObject *fileIfaceObj) {
+  struct PyFileIfaceObj_gdIOCtx *pctx;
+  pctx = calloc(1, sizeof(struct PyFileIfaceObj_gdIOCtx));
+  if (!pctx)
+    return NULL;
+  pctx->ctx.getC = PyFileIfaceObj_IOCtx_GetC;
+  pctx->ctx.getBuf = PyFileIfaceObj_IOCtx_GetBuf;
+  pctx->ctx.gd_free = PyFileIfaceObj_IOCtx_Free;
+  Py_INCREF(fileIfaceObj);
+  pctx->fileIfaceObj = fileIfaceObj;
+  return pctx;
 }
 
 void free_PyFileIfaceObj_IOCtx(struct PyFileIfaceObj_gdIOCtx *pctx)
 {
-    if (!pctx)
-        return;
-    assert(pctx->ctx.gd_free != NULL);
-    pctx->ctx.gd_free((gdIOCtxPtr)pctx);
-    free(pctx);
+  if (!pctx)
+    return;
+  assert(pctx->ctx.gd_free != NULL);
+  pctx->ctx.gd_free((gdIOCtxPtr)pctx);
+  free(pctx);
 }
 
 /* ===========================================================================
@@ -137,27 +138,24 @@ void free_PyFileIfaceObj_IOCtx(struct PyFileIfaceObj_gdIOCtx *pctx)
 
 imageObj *createImageObjFromPyFile(PyObject *file, const char *driver)
 {
-    imageObj *image=NULL;
-    struct PyFileIfaceObj_gdIOCtx *pctx;
+  imageObj *image=NULL;
+  struct PyFileIfaceObj_gdIOCtx *pctx;
 
-    if (file == Py_None) 
-    {
-        msSetError(MS_IMGERR, "NULL file object",
-                   "createImageObjFromPyFile()");
-        return NULL;
-    }
-    else if (!driver) 
-    {
-        msSetError(MS_IMGERR, "NULL or invalid driver string",
-                   "createImageObjFromPyFile()");
-        return NULL;
-    }
-    else
-    {
-        pctx = alloc_PyFileIfaceObj_IOCtx(file);
-        //image = msImageLoadGDCtx((gdIOCtx *) pctx, driver);
-        free_PyFileIfaceObj_IOCtx(pctx);
-        return image;
-    }
+  if (file == Py_None) {
+    msSetError(MS_IMGERR, "NULL file object",
+               "createImageObjFromPyFile()");
+    return NULL;
+  } else if (!driver) {
+    msSetError(MS_IMGERR, "NULL or invalid driver string",
+               "createImageObjFromPyFile()");
+    return NULL;
+  } else {
+    pctx = alloc_PyFileIfaceObj_IOCtx(file);
+    //image = msImageLoadGDCtx((gdIOCtx *) pctx, driver);
+    free_PyFileIfaceObj_IOCtx(pctx);
+    return image;
+  }
 }
 
+#endif
+
diff --git a/mapscript/python/pygdioctx/pygdioctx.h b/mapscript/python/pygdioctx/pygdioctx.h
index 13da345..1370ee3 100644
--- a/mapscript/python/pygdioctx/pygdioctx.h
+++ b/mapscript/python/pygdioctx/pygdioctx.h
@@ -7,11 +7,11 @@
  *
  ******************************************************************************
  * The PyFileIfaceObj_IOCtx API is
- * 
+ *
  * Copyright 1995 Richard Jones, Bureau of Meteorology Australia.
  * richard at bofh.asn.au
  *
- * Current maintainer is 
+ * Current maintainer is
  * Chris Gonnerman <chris.gonnerman at newcenturycomputers.net>
  * Please direct all questions and problems to me.
  *
@@ -32,7 +32,7 @@
  * distribution.  Neither the name of the Bureau of Meteorology
  * Australia nor the names of its contributors may be used to endorse
  * or promote products derived from this software without specific
- * prior written permission. 
+ * prior written permission.
  *
  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
@@ -47,6 +47,8 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  * ***************************************************************************/
 
+#ifdef USE_GD
+
 #include <Python.h>
 #include <gd.h>
 #include <gdfonts.h>
@@ -65,12 +67,14 @@
 */
 
 struct PyFileIfaceObj_gdIOCtx {
-    gdIOCtx ctx;
-    PyObject *fileIfaceObj;
-    PyObject *strObj;
+  gdIOCtx ctx;
+  PyObject *fileIfaceObj;
+  PyObject *strObj;
 };
 
 struct PyFileIfaceObj_gdIOCtx * alloc_PyFileIfaceObj_IOCtx(PyObject *fileIfaceObj);
 void free_PyFileIfaceObj_IOCtx(struct PyFileIfaceObj_gdIOCtx *pctx);
 imageObj *createImageObjFromPyFile(PyObject *file, const char *driver);
 
+#endif
+
diff --git a/mapscript/python/pymodule.i b/mapscript/python/pymodule.i
index 9ba4e68..ab96d9a 100644
--- a/mapscript/python/pymodule.i
+++ b/mapscript/python/pymodule.i
@@ -34,7 +34,7 @@
 %typemap(out) gdBuffer {
     $result = PyString_FromStringAndSize((const char*)$1.data, $1.size); 
     if( $1.owns_data )
-       gdFree($1.data);
+       msFree($1.data);
 }
 
 /**************************************************************************
diff --git a/mapscript/python/setup.py b/mapscript/python/setup.py
index 4ac33b5..4bc5a92 100644
--- a/mapscript/python/setup.py
+++ b/mapscript/python/setup.py
@@ -50,7 +50,7 @@ def unique(list):
 # ---------------------------------------------------------------------------
 
 include_dirs = ['../..']
-library_dirs = ['../../']
+library_dirs = ['../../.libs']
 libraries = ['mapserver']
 
 extra_link_args = []
@@ -273,4 +273,4 @@ else:
            py_modules = py_modules,
            url=url,
            cmdclass={'build_ext':ms_ext},
-           ext_modules = ext_modules )    
\ No newline at end of file
+           ext_modules = ext_modules )    
diff --git a/mapscript/python/tests/cases/imagetest.py b/mapscript/python/tests/cases/imagetest.py
index 12154b4..ef62368 100644
--- a/mapscript/python/tests/cases/imagetest.py
+++ b/mapscript/python/tests/cases/imagetest.py
@@ -128,7 +128,7 @@ class ImageObjTestCase(unittest.TestCase):
     
     def testConstructorUrlStream(self):
         """imageObj with a URL stream works"""
-        url = urllib.urlopen('http://mapserver.gis.umn.edu/logo.jpg')
+        url = urllib.urlopen('http://mapserver.org/_static/banner.png')
         imgobj = mapscript.imageObj(url, 'GD/JPEG')
         assert imgobj.thisown == 1
         assert imgobj.height == 68
diff --git a/mapscript/python/tests/cases/threadtest.py b/mapscript/python/tests/cases/threadtest.py
index 1a0538e..974b789 100644
--- a/mapscript/python/tests/cases/threadtest.py
+++ b/mapscript/python/tests/cases/threadtest.py
@@ -159,7 +159,7 @@ def draw_map_wms(name, save=0):
     lo.setProjection('+init=epsg:4326')
     lo.connectiontype = mapscript.MS_WMS
 #    lo.connection = 'http://wms.jpl.nasa.gov/wms.cgi?'
-    lo.connection = 'http://labs.metacarta.com/wms/vmap0?'
+    lo.connection = 'http://vmap0.tiles.osgeo.org/wms/vmap0?'
     lo.metadata.set('wms_service', 'WMS')
     lo.metadata.set('wms_server_version', '1.1.1')
     lo.metadata.set('wms_name', 'basic')
diff --git a/mapscript/ruby/extconf.rb b/mapscript/ruby/extconf.rb
index d5693af..b81d48e 100755
--- a/mapscript/ruby/extconf.rb
+++ b/mapscript/ruby/extconf.rb
@@ -13,7 +13,8 @@ mapscriptvars.close
 $CFLAGS = ""
 $CPPFLAGS = make_inc + " -idirafter $(rubylibdir)/$(arch) " + make_define
 $LDFLAGS += " -fPIC"
-$LOCAL_LIBS += " -L../.. " + make_libs + " " + make_static_libs
+#$LOCAL_LIBS += " -L../../.libs/ " + " -lmapserver " + make_static_libs
+$LOCAL_LIBS += " -L../../.libs/ " + " -lmapserver "
 
 # if the source file 'mapscript_wrap.c' is missing nothing works
 # this is a workaround !!
diff --git a/mapscript/ruby/rbmodule.i b/mapscript/ruby/rbmodule.i
index 88b8ca7..55732d2 100644
--- a/mapscript/ruby/rbmodule.i
+++ b/mapscript/ruby/rbmodule.i
@@ -20,7 +20,7 @@
 /* To support imageObj::getBytes */
 %typemap(out) gdBuffer {
     $result = rb_str_new($1.data, $1.size);
-    gdFree($1.data);
+    msFree($1.data);
 }
 
 /**************************************************************************
diff --git a/mapscript/swiginc/class.i b/mapscript/swiginc/class.i
index 4eea095..15d5cc1 100644
--- a/mapscript/swiginc/class.i
+++ b/mapscript/swiginc/class.i
@@ -180,41 +180,68 @@
     return msCreateLegendIcon(map, layer, self, width, height);
   } 
 
-    /* See Bugzilla issue 548 for more details about the *Style methods */
-    %newobject getStyle;
-    styleObj *getStyle(int i) {
-        if (i >= 0 && i < self->numstyles) {
-	    MS_REFCNT_INCR(self->styles[i]);
-            return self->styles[i];
-	} else {
-            msSetError(MS_CHILDERR, "Invalid index: %d", "getStyle()", i);
-            return NULL;
-        }
+  %newobject getLabel;
+  labelObj *getLabel(int i) {
+    if (i >= 0 && i < self->numlabels) {
+      MS_REFCNT_INCR(self->labels[i]);
+      return self->labels[i];
+    } else {
+      msSetError(MS_CHILDERR, "Invalid index: %d.", "getLabel()", i);
+      return NULL;
     }
+  }
 
 #ifdef SWIGCSHARP
-%apply SWIGTYPE *SETREFERENCE {styleObj *style};
+%apply SWIGTYPE *SETREFERENCE {labelObj *label};
+#endif
+  int addLabel(labelObj *label) {
+    return msAddLabelToClass(self, label);
+  }
+#ifdef SWIGCSHARP 
+%clear labelObj *label;
 #endif
-    int insertStyle(styleObj *style, int index=-1) {
-        return msInsertStyle(self, style, index);
+
+  %newobject removeLabel;
+  labelObj *removeLabel(int index) {
+    labelObj* label = (labelObj *) msRemoveLabelFromClass(self, index);
+    if (label) MS_REFCNT_INCR(label);
+    return label;
+  }
+  
+  /* See Bugzilla issue 548 for more details about the *Style methods */
+  %newobject getStyle;
+  styleObj *getStyle(int i) {
+    if (i >= 0 && i < self->numstyles) {
+      MS_REFCNT_INCR(self->styles[i]);
+      return self->styles[i];
+    } else {
+      msSetError(MS_CHILDERR, "Invalid index: %d", "getStyle()", i);
+      return NULL;
     }
+  }
+
+#ifdef SWIGCSHARP
+%apply SWIGTYPE *SETREFERENCE {styleObj *style};
+#endif
+  int insertStyle(styleObj *style, int index=-1) {
+    return msInsertStyle(self, style, index);
+  }
 #ifdef SWIGCSHARP 
 %clear styleObj *style;
 #endif
 
-    %newobject removeStyle;
-    styleObj *removeStyle(int index) {
-	styleObj* style = (styleObj *) msRemoveStyle(self, index);
-	if (style)
-		MS_REFCNT_INCR(style);
-        return style;
-    }
+  %newobject removeStyle;
+  styleObj *removeStyle(int index) {
+    styleObj* style = (styleObj *) msRemoveStyle(self, index);
+    if (style) MS_REFCNT_INCR(style);
+    return style;
+  }
 
-    int moveStyleUp(int index) {
-        return msMoveStyleUp(self, index);
-    }
+  int moveStyleUp(int index) {
+    return msMoveStyleUp(self, index);
+  }
 
-    int moveStyleDown(int index) {
-       return msMoveStyleDown(self, index);
-    }
+  int moveStyleDown(int index) {
+    return msMoveStyleDown(self, index);
+  }
 }
diff --git a/mapscript/swiginc/image.i b/mapscript/swiginc/image.i
index d94120a..63143df 100644
--- a/mapscript/swiginc/image.i
+++ b/mapscript/swiginc/image.i
@@ -69,7 +69,7 @@
                 msSetError(MS_MEMERR, NULL, "imageObj()");
                 return NULL;
             }
-            if ( (renderer->loadImageFromFile(file, rb)) == MS_FAILURE)
+            if ( (renderer->loadImageFromFile((char *)file, rb)) == MS_FAILURE)
                 return NULL;
 
             image = msImageCreate(rb->width, rb->height, format, NULL, NULL, 
@@ -116,7 +116,8 @@
             if (file)
             {
                 renderer = self->format->vtable;
-                retval = renderer->saveImage(self, file, self->format);
+                /* FIXME? as an improvement, pass a map argument instead of the NULL (see #4216) */
+                retval = renderer->saveImage(self, NULL, file, self->format);
             }
             else
             {
@@ -142,6 +143,7 @@
     Tcl_Obj *saveToString() 
     {
 
+#ifdef FORCE_BROKEN_GD_CODE
         unsigned char *imgbytes;
         int size;
         Tcl_Obj *imgstring;
@@ -206,9 +208,14 @@
         /* Tcl implementation to create string */
         imgstring = Tcl_NewByteArrayObj(imgbytes, size);    
     
-        gdFree(imgbytes);
+        msFree(imgbytes);
 
         return imgstring;
+#else /* force_gd_broken_code */
+        msSetError(MS_MISCERR, "saveToString() is long deprecated and severley broken", "saveToString()", self->format->driver );
+        return(MS_FAILURE);
+#endif
+
     }
 #endif
 
@@ -216,7 +223,7 @@
     -------------------------------------------------------------------------
     getBytes returns a gdBuffer structure (defined in mapscript.i) which must
     be typemapped to an object appropriate to the target language.  This
-    typemap must also gdFree the data member of the gdBuffer.  See the type-
+    typemap must also msFree the data member of the gdBuffer.  See the type-
     maps in java/javamodule.i and python/pymodule.i for examples.
 
     contributed by Jerry Pisk, jerry.pisk at gmail.com
diff --git a/mapscript/swiginc/label.i b/mapscript/swiginc/label.i
index 7d2ea75..3e2706b 100644
--- a/mapscript/swiginc/label.i
+++ b/mapscript/swiginc/label.i
@@ -30,6 +30,26 @@
 
 %extend labelObj
 {
+
+  labelObj() 
+    {
+      labelObj *label;
+        
+      label = (labelObj *)calloc(1, sizeof(labelObj));
+      if (!label)
+        return(NULL);
+    
+      initLabel(label);
+      
+      return(label);    	
+    }
+
+  ~labelObj() 
+    {
+      freeLabel(self);
+    }
+
+    
   int updateFromString(char *snippet)
   {
     return msUpdateLabelFromString(self, snippet);
@@ -73,6 +93,33 @@
 
     return MS_SUCCESS;
   }
+  
+  int setExpression(char *expression) 
+  {
+    if (!expression || strlen(expression) == 0) {
+       freeExpression(&self->expression);
+       return MS_SUCCESS;
+    }
+    else return msLoadExpressionString(&self->expression, expression);
+  }
+
+  %newobject getExpressionString;
+  char *getExpressionString() {
+    return msGetExpressionString(&(self->expression));
+  }
+
+  int setText(char *text) {
+    if (!text || strlen(text) == 0) {
+      freeExpression(&self->text);
+      return MS_SUCCESS;
+    }	
+    else return msLoadExpressionString(&self->text, text);
+  }
+
+  %newobject getTextString;
+  char *getTextString() {
+    return msGetExpressionString(&(self->text));
+  }
 
   %newobject getStyle;
   styleObj *getStyle(int i) {
diff --git a/mapscript/swiginc/layer.i b/mapscript/swiginc/layer.i
index 6f987dc..da7d81e 100644
--- a/mapscript/swiginc/layer.i
+++ b/mapscript/swiginc/layer.i
@@ -255,6 +255,10 @@
             return NULL;
     }
 
+    int setItems(char **items, int numitems) {
+        return msLayerSetItems(self, items, numitems);
+    }
+
     int draw(mapObj *map, imageObj *image) 
     {
         return msDrawLayer(map, self, image);    
@@ -280,7 +284,10 @@
         map->query.filter = (expressionObj *) malloc(sizeof(expressionObj));
         map->query.filter->string = strdup(string);
 	map->query.filter->type = 2000; /* MS_EXPRESSION: lot's of conflicts in mapfile.h */
-
+        map->query.filter->compiled = MS_FALSE;
+        map->query.filter->flags = 0;
+        map->query.filter->tokens = map->query.filter->curtoken = NULL;
+        
         map->query.layer = self->index;
      	map->query.rect = map->extent;
 
@@ -309,6 +316,7 @@
         self->status = MS_ON;
         retval = msQueryByAttributes(map);
         self->status = status;
+
         return retval;
     }
 
@@ -329,6 +337,7 @@
         self->status = MS_ON;
         retval = msQueryByPoint(map);
         self->status = status;
+
         return retval;
     }
 
@@ -348,6 +357,7 @@
         self->status = MS_ON;
         retval = msQueryByRect(map);
         self->status = status;
+
         return retval;
     }
 
@@ -555,12 +565,12 @@
 
     int applySLD(char *sld, char *stylelayer) 
     {
-        return msSLDApplySLD(self->map, sld, self->index, stylelayer);
+      return msSLDApplySLD(self->map, sld, self->index, stylelayer, NULL);
     }
 
     int applySLDURL(char *sld, char *stylelayer) 
     {
-        return msSLDApplySLDURL(self->map, sld, self->index, stylelayer);
+      return msSLDApplySLDURL(self->map, sld, self->index, stylelayer, NULL);
     }
 
     %newobject generateSLD; 
diff --git a/mapscript/swiginc/map.i b/mapscript/swiginc/map.i
index 8eb021a..f2e965e 100644
--- a/mapscript/swiginc/map.i
+++ b/mapscript/swiginc/map.i
@@ -248,7 +248,10 @@
     self->query.filter = (expressionObj *) malloc(sizeof(expressionObj));
     self->query.filter->string = strdup(string);
     self->query.filter->type = 2000; /* MS_EXPRESSION: lot's of conflicts in mapfile.h */
-
+    self->query.filter->compiled = MS_FALSE;
+    self->query.filter->flags = 0;
+    self->query.filter->tokens = self->query.filter->curtoken = NULL;
+    
     self->query.rect = self->extent;
 
     return msQueryByFilter(self);
@@ -436,11 +439,11 @@
   /* SLD */
   
     int applySLD(char *sld) {
-        return msSLDApplySLD(self, sld, -1, NULL);
+      return msSLDApplySLD(self, sld, -1, NULL, NULL);
     }
 
     int applySLDURL(char *sld) {
-        return msSLDApplySLDURL(self, sld, -1, NULL);
+      return msSLDApplySLDURL(self, sld, -1, NULL, NULL);
     }
     
     %newobject generateSLD;
diff --git a/mapscript/swiginc/owsrequest.i b/mapscript/swiginc/owsrequest.i
index 5f44a2f..02daffc 100644
--- a/mapscript/swiginc/owsrequest.i
+++ b/mapscript/swiginc/owsrequest.i
@@ -104,6 +104,16 @@ static char *msGetEnvURL( const char *key, void *thread_context )
             self->NumParams++;
         }
     }
+    
+    void addParameter(char *name, char *value)
+    {
+        if (self->NumParams == MS_DEFAULT_CGI_PARAMS) {
+            msSetError(MS_CHILDERR, "Maximum number of items, %d, has been reached", "addParameter()", MS_DEFAULT_CGI_PARAMS);
+        }
+        self->ParamNames[self->NumParams] = strdup(name);
+        self->ParamValues[self->NumParams] = strdup(value);
+        self->NumParams++;
+    }
 
     char *getName(int index) 
     {
diff --git a/mapscript/swiginc/rect.i b/mapscript/swiginc/rect.i
index dd8bfac..a4dcafb 100644
--- a/mapscript/swiginc/rect.i
+++ b/mapscript/swiginc/rect.i
@@ -92,7 +92,7 @@
         shape.classindex = classindex;
         shape.text = strdup(text);
 
-        msDrawShape(map, layer, &shape, image, -1, MS_FALSE);
+        msDrawShape(map, layer, &shape, image, -1, MS_DRAWMODE_FEATURES|MS_DRAWMODE_LABELS);
 
         msFreeShape(&shape);
     
diff --git a/mapscript/swiginc/shape.i b/mapscript/swiginc/shape.i
index c9f9926..3c69754 100644
--- a/mapscript/swiginc/shape.i
+++ b/mapscript/swiginc/shape.i
@@ -82,7 +82,7 @@
     }
 
     int draw(mapObj *map, layerObj *layer, imageObj *image) {
-        return msDrawShape(map, layer, self, image, -1, MS_FALSE);
+        return msDrawShape(map, layer, self, image, -1, MS_DRAWMODE_FEATURES|MS_DRAWMODE_LABELS);
     }
 
     void setBounds() 
diff --git a/mapscript/swiginc/symbol.i b/mapscript/swiginc/symbol.i
index 5d8b413..de48621 100644
--- a/mapscript/swiginc/symbol.i
+++ b/mapscript/swiginc/symbol.i
@@ -97,7 +97,7 @@
     %newobject getImage;
     imageObj *getImage(outputFormatObj *input_format)
     {
-        imageObj *image;
+        imageObj *image = NULL;
         outputFormatObj *format = NULL;
         rendererVTableObj *renderer = NULL;
 
@@ -158,7 +158,6 @@
             msSetError(MS_MEMERR, NULL, "setImage()");
             return MS_FAILURE;
         }
-        renderer->initializeRasterBuffer(self->pixmap_buffer, image->width, image->height, image->format->imagemode);
         self->type = MS_SYMBOL_PIXMAP;
         renderer->getRasterBufferCopy(image, self->pixmap_buffer);
 
diff --git a/mapsde.c b/mapsde.c
index 1ec2a52..49fa0f9 100644
--- a/mapsde.c
+++ b/mapsde.c
@@ -1,6 +1,6 @@
 /******************************************************************************
  * $Id$
- *    
+ *
  * Project:  MapServer
  * Purpose:  Implements SDE CONNECTIONTYPE.
  * Author:   Steve Lime and Howard Butler
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -35,10 +35,12 @@
 #include "maptime.h"
 #include "mapthread.h"
 
+
+
 #ifdef USE_SDE
 #include <sdetype.h> /* ESRI SDE Client Includes */
 #include <sdeerno.h>
- 
+
 #define MS_SDE_MAXBLOBSIZE 1024*50 /* 50 kbytes */
 #define MS_SDE_NULLSTRING "<null>"
 #define MS_SDE_SHAPESTRING "<shape>"
@@ -49,9 +51,9 @@
 typedef struct {
   SE_CONNECTION connection;
   SE_STREAM stream;
-} msSDEConnPoolInfo; 
+} msSDEConnPoolInfo;
 
-typedef struct { 
+typedef struct {
   msSDEConnPoolInfo *connPoolInfo;
   SE_CONNECTION connection;
   SE_LAYERINFO layerinfo;
@@ -80,7 +82,7 @@ typedef struct {
 /*
  * Layer ID caching section.
  */
- 
+
 static int lcacheCount = 0;
 static int lcacheMax = 0;
 static layerId *lcache = NULL;
@@ -92,16 +94,21 @@ static layerId *lcache = NULL;
 /* -------------------------------------------------------------------- */
 /*     Returns MS_TRUE if layer is already opened, MS_FALSE otherwise   */
 /* -------------------------------------------------------------------- */
-int msSDELayerIsOpen(layerObj *layer) {
+int msSDELayerIsOpen(layerObj *layer)
+{
 #ifdef USE_SDE
-  if(layer->layerinfo) 
-    return(MS_TRUE); 
+
+  if(layer->layerinfo)
+    return(MS_TRUE);
+
   return MS_FALSE;
+
 #else
-  msSetError(MS_MISCERR, "SDE support is not available.",  "msSDELayerIsOpen()");
+  msSetError(MS_MISCERR, "SDE support is not available.",
+             "msSDELayerIsOpen()");
   return(MS_FALSE);
 #endif
-} 
+}
 
 #ifdef USE_SDE
 
@@ -122,21 +129,21 @@ int msSDELayerIsOpen(layerObj *layer) {
 static void msSDECloseConnection( void *conn_handle )
 {
 
-    long status;
-    msSDEConnPoolInfo *poolinfo = conn_handle;
-    
-    if (poolinfo) {
-        if (poolinfo->stream) {
-            SE_stream_free(poolinfo->stream);
-        }
-        if (poolinfo->connection) {
-            status = SE_connection_free_all_locks (poolinfo->connection);
-            if (status == SE_SUCCESS) {
-                SE_connection_free(poolinfo->connection);
-            }
-        }
-        msFree(poolinfo);
-    } 
+  long status;
+  msSDEConnPoolInfo *poolinfo = conn_handle;
+
+  if (poolinfo) {
+    if (poolinfo->stream) {
+      SE_stream_free(poolinfo->stream);
+    }
+    if (poolinfo->connection) {
+      status = SE_connection_free_all_locks (poolinfo->connection);
+      if (status == SE_SUCCESS) {
+        SE_connection_free(poolinfo->connection);
+      }
+    }
+    msFree(poolinfo);
+  }
 
 }
 
@@ -145,18 +152,18 @@ static void msSDECloseConnection( void *conn_handle )
 /* -------------------------------------------------------------------- */
 /*     Reports more detailed error information from SDE                 */
 /* -------------------------------------------------------------------- */
-static void sde_error(long error_code, char *routine, char *sde_routine) 
+static void sde_error(long error_code, char *routine, char *sde_routine)
 {
   char error_string[SE_MAX_MESSAGE_LENGTH];
 
   error_string[0] = '\0';
   SE_error_get_string(error_code, error_string);
 
-  msSetError( MS_SDEERR, 
-              "%s: %s. (%ld)", 
-              routine, 
-              sde_routine, 
-              error_string, 
+  msSetError( MS_SDEERR,
+              "%s: %s. (%ld)",
+              routine,
+              sde_routine,
+              error_string,
               error_code);
 
   return;
@@ -166,135 +173,133 @@ static void sde_error(long error_code, char *routine, char *sde_routine)
 /* -------------------------------------------------------------------- */
 /* msSDELayerGetRowIDColumn                                             */
 /* -------------------------------------------------------------------- */
-/*     A helper function to return unique row ID column for             */ 
+/*     A helper function to return unique row ID column for             */
 /*     an opened SDE layer.  The caller owns the string.                */
 /* -------------------------------------------------------------------- */
 char *msSDELayerGetRowIDColumn(layerObj *layer)
 {
 #ifdef USE_SDE
-    long status, column_type; 
-    char* column_name;
-    char* full_column_name;
-    char* proc_key;
-
-    SE_REGINFO registration;
-    
-    msSDELayerInfo *sde=NULL;
-    sde = layer->layerinfo;
-
-    if(!msSDELayerIsOpen(layer)) {
-        msSetError( MS_SDEERR, 
-                    "SDE layer has not been opened.", 
-                    "msSDELayerGetRowIDColumn()");
-        return NULL;
-    }
+  long status, column_type;
+  char* column_name;
+  char* full_column_name;
+  char* proc_key;
 
-    column_name = (char*) msSmallMalloc(SE_QUALIFIED_COLUMN_LEN+1);
-    column_name[0]='\0';
+  SE_REGINFO registration;
 
-    proc_key = msLayerGetProcessingKey(layer,"OBJECTID");
-    if (proc_key)
-       strcpy(column_name,proc_key);
+  msSDELayerInfo *sde=NULL;
+  sde = layer->layerinfo;
 
-    if (proc_key) {
-       if (layer->debug)
-          msDebug("msSDELayerGetRowIDColumn(): Column was manually set to %s\n", column_name);
-       return column_name;
-    }
-    full_column_name = (char*) msSmallMalloc(SE_QUALIFIED_COLUMN_LEN+1);
-    full_column_name[0]='\0';
-    
-    /*
-    ** if the state_id is the SE_DEFAULT_STATE_ID, we are 
-    ** assuming no versioned queries are happening at all 
-    ** and we are using the hardcoded row_id column.
-    */
-    if (sde->state_id == SE_DEFAULT_STATE_ID) {
-        if(layer->debug) {
-            msDebug("msSDELayerGetRowIDColumn(): State ID was "
-                    "SE_DEFAULT_STATE_ID, reverting to %s.\n", 
-                    MS_SDE_ROW_ID_COLUMN);
-        }
-        strcpy(column_name,MS_SDE_ROW_ID_COLUMN);
-    } 
-    
-    /*
-    ** if the state_id was not set to SE_DEFAULT_STATE_ID,
-    ** check if the table is registered, and if so, use the 
-    ** registration info to tell us what the row_id column is.
-    */
-    status = SE_reginfo_create (&registration);
-    if(status != SE_SUCCESS) {
-        sde_error(  status, 
-                    "msSDELayerGetRowIDColumn()", 
-                    "SE_reginfo_create()");
-        return(NULL);
-    }
-    
-    status = SE_registration_get_info ( sde->connPoolInfo->connection, 
-                                        sde->table, 
-                                        registration);
-    if(status != SE_SUCCESS) {
-        sde_error(  status, 
-                    "msSDELayerGetRowIDColumn()", 
-                    "SE_registration_get_info()");
-        SE_reginfo_free(registration);
-        return(NULL);
-    }
-    
-    status= SE_reginfo_get_rowid_column ( registration, 
-                                          column_name, 
-                                          &column_type);
-    
-    if(status != SE_SUCCESS) {
-        sde_error(status, 
-                "msSDELayerGetRowIDColumn()", 
-                "SE_reginfo_get_rowid_column()");
-        SE_reginfo_free(registration);
-        return(NULL);
-    }
-    /* Free up the reginfo now that we're done with it */
+  if(!msSDELayerIsOpen(layer)) {
+    msSetError( MS_SDEERR,
+                "SDE layer has not been opened.",
+                "msSDELayerGetRowIDColumn()");
+    return NULL;
+  }
+
+  column_name = (char*) msSmallMalloc(SE_QUALIFIED_COLUMN_LEN+1);
+  column_name[0]='\0';
+
+  proc_key = msLayerGetProcessingKey(layer,"OBJECTID");
+  if (proc_key)
+    strcpy(column_name,proc_key);
+
+  if (proc_key) {
+    if (layer->debug)
+      msDebug("msSDELayerGetRowIDColumn(): Column was manually set to %s\n", column_name);
+    return column_name;
+  }
+  full_column_name = (char*) msSmallMalloc(SE_QUALIFIED_COLUMN_LEN+1);
+  full_column_name[0]='\0';
+
+  /*
+  ** if the state_id is the SE_DEFAULT_STATE_ID, we are
+  ** assuming no versioned queries are happening at all
+  ** and we are using the hardcoded row_id column.
+  */
+  if (sde->state_id == SE_DEFAULT_STATE_ID) {
+    if(layer->debug) {
+      msDebug("msSDELayerGetRowIDColumn(): State ID was "
+              "SE_DEFAULT_STATE_ID, reverting to %s.\n",
+              MS_SDE_ROW_ID_COLUMN);
+    }
+    strcpy(column_name,MS_SDE_ROW_ID_COLUMN);
+  }
+
+  /*
+  ** if the state_id was not set to SE_DEFAULT_STATE_ID,
+  ** check if the table is registered, and if so, use the
+  ** registration info to tell us what the row_id column is.
+  */
+  status = SE_reginfo_create (&registration);
+  if(status != SE_SUCCESS) {
+    sde_error(  status,
+                "msSDELayerGetRowIDColumn()",
+                "SE_reginfo_create()");
+    return(NULL);
+  }
+
+  status = SE_registration_get_info ( sde->connPoolInfo->connection,
+                                      sde->table,
+                                      registration);
+  if(status != SE_SUCCESS) {
+    sde_error(  status,
+                "msSDELayerGetRowIDColumn()",
+                "SE_registration_get_info()");
     SE_reginfo_free(registration);
+    return(NULL);
+  }
 
-    /* if the table wasn't registered, return the hard-coded row_id column. */
-    if (column_type == SE_REGISTRATION_ROW_ID_COLUMN_TYPE_NONE){
-        if(layer->debug) {
-            msDebug("msSDELayerGetRowIDColumn(): Table was not registered, "
-                    "returning %s.\n", 
-                    MS_SDE_ROW_ID_COLUMN);
-        }
-        strcpy(column_name, MS_SDE_ROW_ID_COLUMN);
+  status= SE_reginfo_get_rowid_column ( registration,
+                                        column_name,
+                                        &column_type);
+
+  if(status != SE_SUCCESS) {
+    sde_error(status,
+              "msSDELayerGetRowIDColumn()",
+              "SE_reginfo_get_rowid_column()");
+    SE_reginfo_free(registration);
+    return(NULL);
+  }
+  /* Free up the reginfo now that we're done with it */
+  SE_reginfo_free(registration);
+
+  /* if the table wasn't registered, return the hard-coded row_id column. */
+  if (column_type == SE_REGISTRATION_ROW_ID_COLUMN_TYPE_NONE) {
+    if(layer->debug) {
+      msDebug("msSDELayerGetRowIDColumn(): Table was not registered, "
+              "returning %s.\n",
+              MS_SDE_ROW_ID_COLUMN);
     }
+    strcpy(column_name, MS_SDE_ROW_ID_COLUMN);
+  }
 
 
-    proc_key = msLayerGetProcessingKey(layer,"ATTRIBUTE_QUALIFIED");
-    if (sde->join_table ||
-        (proc_key && strcasecmp( proc_key, "TRUE") == 0)) {
-        strcat(full_column_name, sde->table);
-        strcat(full_column_name, ".");
-        strcat(full_column_name, column_name);
-        msFree(column_name);
+  proc_key = msLayerGetProcessingKey(layer,"ATTRIBUTE_QUALIFIED");
+  if (sde->join_table ||
+      (proc_key && strcasecmp( proc_key, "TRUE") == 0)) {
+    strcat(full_column_name, sde->table);
+    strcat(full_column_name, ".");
+    strcat(full_column_name, column_name);
+    msFree(column_name);
 
-    }
-    else {
-        strcpy(full_column_name, column_name);
-        msFree(column_name);
-        }
-        
+  } else {
+    strcpy(full_column_name, column_name);
+    msFree(column_name);
+  }
 
-    if (full_column_name) {
-        return (full_column_name); 
-    }
-    else {
-        msFree(full_column_name);
-        return(msStrdup(MS_SDE_ROW_ID_COLUMN));
-    }
+
+  if (full_column_name) {
+    return (full_column_name);
+  } else {
+    msFree(full_column_name);
+    return(msStrdup(MS_SDE_ROW_ID_COLUMN));
+  }
 
 #else
-    msSetError( MS_MISCERR, 
-                "SDE support is not available.", 
-                "msSDELayerGetRowIDColumn()");
-    return(NULL);
+  msSetError( MS_MISCERR,
+              "SDE support is not available.",
+              "msSDELayerGetRowIDColumn()");
+  return(NULL);
 #endif
 }
 
@@ -308,50 +313,47 @@ long msSDELCacheAdd( layerObj *layer,
                      SE_LAYERINFO layerinfo,
                      char *tableName,
                      char *columnName,
-                     char *connectionString) 
+                     char *connectionString)
 {
-  
-    layerId *lid = NULL;
-    long status = 0;
-  
-    msAcquireLock( TLOCK_SDE );
-  
-    if (layer->debug){
-        msDebug( "%s: Caching id for %s, %s, %s\n", "msSDELCacheAdd()", 
-                 tableName, columnName, connectionString);
-    }
 
-    /* Ensure the cache is large enough to hold the new item. */
-    if(lcacheCount == lcacheMax)
-    {
-        lcacheMax += 10;
-        lcache = (layerId *)realloc(lcache, sizeof(layerId) * lcacheMax);
-        if(lcache == NULL)
-        {
-            msReleaseLock( TLOCK_SDE );
-            msSetError(MS_MEMERR, NULL, "msSDELCacheAdd()");
-            return (MS_FAILURE);
-        }
-    }
+  layerId *lid = NULL;
+  long status = 0;
 
-    /* Population the new lcache object. */
-    lid = lcache + lcacheCount;
-    lcacheCount++;
+  msAcquireLock( TLOCK_SDE );
 
-    status = SE_layerinfo_get_id(layerinfo, &lid->layerId);
-    if(status != SE_SUCCESS)
-    {
-        msReleaseLock( TLOCK_SDE );
-        sde_error(status, "msSDELCacheAdd()", "SE_layerinfo_get_id()");
-        return(MS_FAILURE);
+  if (layer->debug) {
+    msDebug( "%s: Caching id for %s, %s, %s\n", "msSDELCacheAdd()",
+             tableName, columnName, connectionString);
+  }
+
+  /* Ensure the cache is large enough to hold the new item. */
+  if(lcacheCount == lcacheMax) {
+    lcacheMax += 10;
+    lcache = (layerId *)realloc(lcache, sizeof(layerId) * lcacheMax);
+    if(lcache == NULL) {
+      msReleaseLock( TLOCK_SDE );
+      msSetError(MS_MEMERR, NULL, "msSDELCacheAdd()");
+      return (MS_FAILURE);
     }
-    
-    lid->table = msStrdup(tableName);
-    lid->column = msStrdup(columnName);
-    lid->connection = msStrdup(connectionString);
-  
+  }
+
+  /* Population the new lcache object. */
+  lid = lcache + lcacheCount;
+  lcacheCount++;
+
+  status = SE_layerinfo_get_id(layerinfo, &lid->layerId);
+  if(status != SE_SUCCESS) {
     msReleaseLock( TLOCK_SDE );
-    return (MS_SUCCESS);
+    sde_error(status, "msSDELCacheAdd()", "SE_layerinfo_get_id()");
+    return(MS_FAILURE);
+  }
+
+  lid->table = msStrdup(tableName);
+  lid->column = msStrdup(columnName);
+  lid->connection = msStrdup(connectionString);
+
+  msReleaseLock( TLOCK_SDE );
+  return (MS_SUCCESS);
 }
 
 /* -------------------------------------------------------------------- */
@@ -361,85 +363,80 @@ long msSDELCacheAdd( layerObj *layer,
 /*     exists in the cache.                                             */
 /* -------------------------------------------------------------------- */
 long msSDEGetLayerInfo(layerObj *layer,
-                       SE_CONNECTION conn, 
-                       char *tableName, 
-                       char *columnName, 
+                       SE_CONNECTION conn,
+                       char *tableName,
+                       char *columnName,
                        char *connectionString,
                        SE_LAYERINFO layerinfo)
 {
-    int i;
-    long status;
-    layerId *lid = NULL;
-  
-    /* If table or column are null, nothing can be done. */
-    if(tableName == NULL)
-    {
-        msSetError( MS_MISCERR,
-                    "Missing table name.\n",
-                    "msSDEGetLayerInfo()");
-        return (MS_FAILURE);
-    }
-    if(columnName == NULL)
-    {
-        msSetError( MS_MISCERR,
-                    "Missing column name.\n",
-                    "msSDEGetLayerInfo()");
-        return (MS_FAILURE);
-    }
-    if(connectionString == NULL)
-    {
-        msSetError( MS_MISCERR,
-                    "Missing connection string.\n",
-                    "msSDEGetLayerInfo()");
-        return (MS_FAILURE);
-    }  
-
-    if (layer->debug){
-        msDebug("%s: Looking for layer by %s, %s, %s\n", 
-                "msSDEGetLayerInfo()",
-                tableName, 
-                columnName, 
-                connectionString);
-    }
+  int i;
+  long status;
+  layerId *lid = NULL;
+
+  /* If table or column are null, nothing can be done. */
+  if(tableName == NULL) {
+    msSetError( MS_MISCERR,
+                "Missing table name.\n",
+                "msSDEGetLayerInfo()");
+    return (MS_FAILURE);
+  }
+  if(columnName == NULL) {
+    msSetError( MS_MISCERR,
+                "Missing column name.\n",
+                "msSDEGetLayerInfo()");
+    return (MS_FAILURE);
+  }
+  if(connectionString == NULL) {
+    msSetError( MS_MISCERR,
+                "Missing connection string.\n",
+                "msSDEGetLayerInfo()");
+    return (MS_FAILURE);
+  }
 
-    /* Search the lcache for the layer id. */
-    for(i = 0; i < lcacheCount; i++)
-    {
-        lid = lcache + i;
-        if(strcasecmp(lid->table, tableName) == 0 &&
-            strcasecmp(lid->column, columnName) == 0 &&
-            strcasecmp(lid->connection, connectionString) == 0)
-        {
-            status = SE_layer_get_info_by_id(conn, lid->layerId, layerinfo);
-            if(status != SE_SUCCESS) {
-                sde_error(status, "msSDEGetLayerInfo()", "SE_layer_get_info()");
-                return(MS_FAILURE);
-            } 
-            if (layer->debug){
-                msDebug( "%s: Matched layer to id %i.\n", 
-                       "msSDEGetLayerId()", lid->layerId);
-            }
-            return (MS_SUCCESS);
-            
-        }
-    }
-    if (layer->debug){
-        msDebug("%s: No cached layerid found.\n", "msSDEGetLayerInfo()");
-    }
+  if (layer->debug) {
+    msDebug("%s: Looking for layer by %s, %s, %s\n",
+            "msSDEGetLayerInfo()",
+            tableName,
+            columnName,
+            connectionString);
+  }
 
-    /* No matches found, create one. */
-    status = SE_layer_get_info( conn, tableName, columnName, layerinfo );
-    if(status != SE_SUCCESS) {
+  /* Search the lcache for the layer id. */
+  for(i = 0; i < lcacheCount; i++) {
+    lid = lcache + i;
+    if(strcasecmp(lid->table, tableName) == 0 &&
+        strcasecmp(lid->column, columnName) == 0 &&
+        strcasecmp(lid->connection, connectionString) == 0) {
+      status = SE_layer_get_info_by_id(conn, lid->layerId, layerinfo);
+      if(status != SE_SUCCESS) {
         sde_error(status, "msSDEGetLayerInfo()", "SE_layer_get_info()");
         return(MS_FAILURE);
+      }
+      if (layer->debug) {
+        msDebug( "%s: Matched layer to id %i.\n",
+                 "msSDEGetLayerId()", lid->layerId);
+      }
+      return (MS_SUCCESS);
+
     }
+  }
+  if (layer->debug) {
+    msDebug("%s: No cached layerid found.\n", "msSDEGetLayerInfo()");
+  }
+
+  /* No matches found, create one. */
+  status = SE_layer_get_info( conn, tableName, columnName, layerinfo );
+  if(status != SE_SUCCESS) {
+    sde_error(status, "msSDEGetLayerInfo()", "SE_layer_get_info()");
+    return(MS_FAILURE);
+  }
 
-    status = msSDELCacheAdd(layer, 
-                            layerinfo, 
-                            tableName, 
-                            columnName, 
-                            connectionString);
-    return(MS_SUCCESS);
+  status = msSDELCacheAdd(layer,
+                          layerinfo,
+                          tableName,
+                          columnName,
+                          connectionString);
+  return(MS_SUCCESS);
 
 }
 
@@ -448,130 +445,130 @@ long msSDEGetLayerInfo(layerObj *layer,
 /* -------------------------------------------------------------------- */
 /*     Copies a SDE shape into a MapServer shapeObj                     */
 /* -------------------------------------------------------------------- */
-static int sdeShapeCopy(SE_SHAPE inshp, shapeObj *outshp) {
-
-    SE_POINT *points=NULL;
-    SE_ENVELOPE envelope;
-    long type, status;
-    long *part_offsets = NULL;
-    long *subpart_offsets = NULL;
-    long num_parts = -1;
-    long num_subparts = -1;
-    long num_points = -1;
-  
-    lineObj line={0,NULL};
-
-    int i,j,k;
-
-    status = SE_shape_get_type(inshp, &type);
-    if(status != SE_SUCCESS) {
-        sde_error(status, 
-                  "sdeCopyShape()", 
-                  "SE_shape_get_type()");
-        return(MS_FAILURE);
-    }
-  
-    switch(type) {
-        case(SG_NIL_SHAPE):
-            return(MS_SUCCESS); /* skip null shapes */
-            break;
-        case(SG_POINT_SHAPE):
-        case(SG_MULTI_POINT_SHAPE):
-            outshp->type = MS_SHAPE_POINT;
-            break;
-        case(SG_LINE_SHAPE):
-        case(SG_SIMPLE_LINE_SHAPE): 
-        case(SG_MULTI_LINE_SHAPE):
-        case(SG_MULTI_SIMPLE_LINE_SHAPE):
-            outshp->type = MS_SHAPE_LINE;
-            break;
-        case(SG_AREA_SHAPE):
-        case(SG_MULTI_AREA_SHAPE):
-            outshp->type = MS_SHAPE_POLYGON;
-            break;  
-        default:
-            msSetError( MS_SDEERR, 
-                        "Unsupported SDE shape type (%ld).", 
-                        "sdeCopyShape()", 
-                        type);
-            return(MS_FAILURE);
-    }
+static int sdeShapeCopy(SE_SHAPE inshp, shapeObj *outshp)
+{
 
+  SE_POINT *points=NULL;
+  SE_ENVELOPE envelope;
+  long type, status;
+  long *part_offsets = NULL;
+  long *subpart_offsets = NULL;
+  long num_parts = -1;
+  long num_subparts = -1;
+  long num_points = -1;
 
-    status = SE_shape_get_num_parts (inshp, &num_parts, &num_subparts);
-    if(status != SE_SUCCESS) {
-        sde_error(status, "sdeShapeCopy()", "SE_shape_get_num_parts()");
-        return(MS_FAILURE);
-    }
-    status = SE_shape_get_num_points (inshp, 0, 0, &num_points); 
-    if(status != SE_SUCCESS) {
-        sde_error(status, "sdeShapeCopy()", "SE_shape_get_num_points()");
-        return(MS_FAILURE);
-    }
-     
-    part_offsets = (long *) msSmallMalloc( (num_parts + 1) * sizeof(long));
-    subpart_offsets = (long *) msSmallMalloc( (num_subparts + 1)	* sizeof(long));
-    part_offsets[num_parts] = num_subparts;
-    subpart_offsets[num_subparts]	= num_points;
-
-    points = (SE_POINT *) msSmallMalloc (num_points*sizeof(SE_POINT));
-    if(!points) {
-        msSetError( MS_MEMERR, 
-                    "Unable to allocate points array.", 
-                    "sdeCopyShape()");
-        return(MS_FAILURE);
-    }
+  lineObj line= {0,NULL};
 
-    status = SE_shape_get_all_points(   inshp, 
-                                        SE_DEFAULT_ROTATION, 
-                                        part_offsets, 
-                                        subpart_offsets, 
-                                        points, 
-                                        NULL, 
-                                        NULL);
-    if(status != SE_SUCCESS) {
-        sde_error(status, "sdeCopyShape()", "SE_shape_get_all_points()");
-        return(MS_FAILURE);
-    }
+  int i,j,k;
 
-    k = 0; /* overall point counter */
-    for(i=0; i<num_subparts; i++) 
-    {
-
-        if( i == num_subparts-1)
-            line.numpoints = num_points - subpart_offsets[i];
-        else
-            line.numpoints = subpart_offsets[i+1] - subpart_offsets[i];
-    
-        line.point = (pointObj *)malloc(sizeof(pointObj)*line.numpoints);
-        MS_CHECK_ALLOC(line.point, sizeof(pointObj)*line.numpoints, MS_FAILURE);
-         
-        for(j=0; j < line.numpoints; j++) {
-            line.point[j].x = points[k].x; 
-            line.point[j].y = points[k].y;     
-            k++;
-        }
-    
-        msAddLine(outshp, &line);
-        msFree(line.point);
-    }
+  status = SE_shape_get_type(inshp, &type);
+  if(status != SE_SUCCESS) {
+    sde_error(status,
+              "sdeCopyShape()",
+              "SE_shape_get_type()");
+    return(MS_FAILURE);
+  }
 
-    msFree(part_offsets);
-    msFree(subpart_offsets);
-    msFree(points);
+  switch(type) {
+    case(SG_NIL_SHAPE):
+      return(MS_SUCCESS); /* skip null shapes */
+      break;
+    case(SG_POINT_SHAPE):
+    case(SG_MULTI_POINT_SHAPE):
+      outshp->type = MS_SHAPE_POINT;
+      break;
+    case(SG_LINE_SHAPE):
+    case(SG_SIMPLE_LINE_SHAPE):
+    case(SG_MULTI_LINE_SHAPE):
+    case(SG_MULTI_SIMPLE_LINE_SHAPE):
+      outshp->type = MS_SHAPE_LINE;
+      break;
+    case(SG_AREA_SHAPE):
+    case(SG_MULTI_AREA_SHAPE):
+      outshp->type = MS_SHAPE_POLYGON;
+      break;
+    default:
+      msSetError( MS_SDEERR,
+                  "Unsupported SDE shape type (%ld).",
+                  "sdeCopyShape()",
+                  type);
+      return(MS_FAILURE);
+  }
 
-    /* finally copy the bounding box for the entire shape */
-    status = SE_shape_get_extent(inshp, 0, &envelope);
-    if(status != SE_SUCCESS) {
-        sde_error(status, "sdeCopyShape()", "SE_shape_get_extent()");
-        return(MS_FAILURE);
+
+  status = SE_shape_get_num_parts (inshp, &num_parts, &num_subparts);
+  if(status != SE_SUCCESS) {
+    sde_error(status, "sdeShapeCopy()", "SE_shape_get_num_parts()");
+    return(MS_FAILURE);
+  }
+  status = SE_shape_get_num_points (inshp, 0, 0, &num_points);
+  if(status != SE_SUCCESS) {
+    sde_error(status, "sdeShapeCopy()", "SE_shape_get_num_points()");
+    return(MS_FAILURE);
+  }
+
+  part_offsets = (long *) msSmallMalloc( (num_parts + 1) * sizeof(long));
+  subpart_offsets = (long *) msSmallMalloc( (num_subparts + 1)  * sizeof(long));
+  part_offsets[num_parts] = num_subparts;
+  subpart_offsets[num_subparts] = num_points;
+
+  points = (SE_POINT *) msSmallMalloc (num_points*sizeof(SE_POINT));
+  if(!points) {
+    msSetError( MS_MEMERR,
+                "Unable to allocate points array.",
+                "sdeCopyShape()");
+    return(MS_FAILURE);
+  }
+
+  status = SE_shape_get_all_points(   inshp,
+                                      SE_DEFAULT_ROTATION,
+                                      part_offsets,
+                                      subpart_offsets,
+                                      points,
+                                      NULL,
+                                      NULL);
+  if(status != SE_SUCCESS) {
+    sde_error(status, "sdeCopyShape()", "SE_shape_get_all_points()");
+    return(MS_FAILURE);
+  }
+
+  k = 0; /* overall point counter */
+  for(i=0; i<num_subparts; i++) {
+
+    if( i == num_subparts-1)
+      line.numpoints = num_points - subpart_offsets[i];
+    else
+      line.numpoints = subpart_offsets[i+1] - subpart_offsets[i];
+
+    line.point = (pointObj *)malloc(sizeof(pointObj)*line.numpoints);
+    MS_CHECK_ALLOC(line.point, sizeof(pointObj)*line.numpoints, MS_FAILURE);
+
+    for(j=0; j < line.numpoints; j++) {
+      line.point[j].x = points[k].x;
+      line.point[j].y = points[k].y;
+      k++;
     }
-    outshp->bounds.minx = envelope.minx;
-    outshp->bounds.miny = envelope.miny;
-    outshp->bounds.maxx = envelope.maxx;
-    outshp->bounds.maxy = envelope.maxy;
 
-    return(MS_SUCCESS);
+    msAddLine(outshp, &line);
+    msFree(line.point);
+  }
+
+  msFree(part_offsets);
+  msFree(subpart_offsets);
+  msFree(points);
+
+  /* finally copy the bounding box for the entire shape */
+  status = SE_shape_get_extent(inshp, 0, &envelope);
+  if(status != SE_SUCCESS) {
+    sde_error(status, "sdeCopyShape()", "SE_shape_get_extent()");
+    return(MS_FAILURE);
+  }
+  outshp->bounds.minx = envelope.minx;
+  outshp->bounds.miny = envelope.miny;
+  outshp->bounds.maxx = envelope.maxx;
+  outshp->bounds.maxy = envelope.maxy;
+
+  return(MS_SUCCESS);
 }
 
 /* -------------------------------------------------------------------- */
@@ -580,461 +577,472 @@ static int sdeShapeCopy(SE_SHAPE inshp, shapeObj *outshp) {
 /*     Retrieves the current row as setup via the SDE stream query      */
 /*     or row fetch routines.                                           */
 /* -------------------------------------------------------------------- */
-static int sdeGetRecord(layerObj *layer, shapeObj *shape) {
-    int i;
-    long status;
-    
-    double doubleval;
-    long longval;
-    struct tm dateval;
-    
-    short shortval; /* new gdv */
-    float floatval;
-    
-    SE_COLUMN_DEF *itemdefs;
-    SE_SHAPE shapeval=0;
-    msSDELayerInfo *sde;
-
-    SE_BLOB_INFO blobval;
+static int sdeGetRecord(layerObj *layer, shapeObj *shape)
+{
+  int i;
+  long status;
+
+  double doubleval;
+  long longval;
+  struct tm dateval;
+
+  short shortval; /* new gdv */
+  float floatval;
+
+  SE_COLUMN_DEF *itemdefs;
+  SE_SHAPE shapeval=0;
+  msSDELayerInfo *sde;
+
+  SE_BLOB_INFO blobval;
 
 #ifdef SE_CLOB_TYPE
-    SE_CLOB_INFO clobval;
+  SE_CLOB_INFO clobval;
 #endif
 
 #ifdef SE_NCLOB_TYPE
-    SE_NCLOB_INFO nclobval;
+  SE_NCLOB_INFO nclobval;
+  SE_WCHAR* nclobstring; /* null terminated */
 #endif
 
 #ifdef SE_NSTRING_TYPE
-    SE_WCHAR* wide=NULL;
+  SE_WCHAR* wide=NULL;
 #endif
 
 
-    if(!msSDELayerIsOpen(layer)) {
-        msSetError( MS_SDEERR, 
-                    "SDE layer has not been opened.", 
-                    "sdeGetRecord()");
-        return MS_FAILURE;
-    }
+  if(!msSDELayerIsOpen(layer)) {
+    msSetError( MS_SDEERR,
+                "SDE layer has not been opened.",
+                "sdeGetRecord()");
+    return MS_FAILURE;
+  }
 
-    sde = layer->layerinfo;
+  sde = layer->layerinfo;
 
-    if(layer->numitems > 0) {
-        shape->numvalues = layer->numitems;
-        shape->values = (char **) malloc (sizeof(char *)*layer->numitems);
-        MS_CHECK_ALLOC(shape->values, sizeof(char *)*layer->numitems, MS_FAILURE);
-    }
+  if(layer->numitems > 0) {
+    shape->numvalues = layer->numitems;
+    shape->values = (char **) malloc (sizeof(char *)*layer->numitems);
+    MS_CHECK_ALLOC(shape->values, sizeof(char *)*layer->numitems, MS_FAILURE);
+  }
 
-    status = SE_shape_create(NULL, &shapeval);
-    if(status != SE_SUCCESS) {
-        sde_error(status, "sdeGetRecord()", "SE_shape_create()");
+  status = SE_shape_create(NULL, &shapeval);
+  if(status != SE_SUCCESS) {
+    sde_error(status, "sdeGetRecord()", "SE_shape_create()");
+    return(MS_FAILURE);
+  }
+
+  itemdefs = layer->iteminfo;
+  for(i=0; i<layer->numitems; i++) {
+
+    /* do something special */
+    if(strcmp(layer->items[i],sde->row_id_column) == 0) {
+      status = SE_stream_get_integer(sde->connPoolInfo->stream, (short)(i+1), &shape->index);
+      if(status != SE_SUCCESS) {
+        sde_error(status, "sdeGetRecord()", "SE_stream_get_integer()");
         return(MS_FAILURE);
-    }
+      }
 
-    itemdefs = layer->iteminfo;
-    for(i=0; i<layer->numitems; i++) {
-
-        /* do something special */
-        if(strcmp(layer->items[i],sde->row_id_column) == 0) {
-            status = SE_stream_get_integer(sde->connPoolInfo->stream, (short)(i+1), &shape->index);
-            if(status != SE_SUCCESS) {
-                sde_error(status, "sdeGetRecord()", "SE_stream_get_integer()");
-                return(MS_FAILURE);
-            }
-    
-            shape->values[i] = (char *)msSmallMalloc(64); /* should be enough */
-            sprintf(shape->values[i], "%ld", shape->index);
-            continue;
-        }    
+      shape->values[i] = (char *)msSmallMalloc(64); /* should be enough */
+      sprintf(shape->values[i], "%ld", shape->index);
+      continue;
+    }
 
     switch(itemdefs[i].sde_type) {
-        case SE_SMALLINT_TYPE:
-            /* changed by gdv */
-            status = SE_stream_get_smallint(sde->connPoolInfo->stream, 
-                                            (short)(i+1), 
-                                            &shortval); 
-            if(status == SE_SUCCESS)
-                shape->values[i] = msLongToString(shortval);
-            else if(status == SE_NULL_VALUE)
-                shape->values[i] = msStrdup(MS_SDE_NULLSTRING);
-            else {
-                sde_error(  status, 
-                            "sdeGetRecord()", 
-                            "SE_stream_get_smallint()");
-                return(MS_FAILURE);
-            }
-            break;
-        case SE_INTEGER_TYPE:
-            status = SE_stream_get_integer( sde->connPoolInfo->stream, 
-                                            (short)(i+1), 
-                                            &longval);
-            if(status == SE_SUCCESS)
-                shape->values[i] = msLongToString(longval);
-            else if(status == SE_NULL_VALUE)
-                shape->values[i] = msStrdup(MS_SDE_NULLSTRING);
-            else {
-                sde_error(  status, 
-                            "sdeGetRecord()", 
-                            "SE_stream_get_integer()");
-                return(MS_FAILURE);
-            }      
-            break;
-        case SE_FLOAT_TYPE:
-            status = SE_stream_get_float(   sde->connPoolInfo->stream, 
-                                            (short)(i+1), 
-                                            &floatval); 
-            if(status == SE_SUCCESS)
-                shape->values[i] = msDoubleToString(floatval, MS_FALSE);
-            else if(status == SE_NULL_VALUE)
-                shape->values[i] = msStrdup(MS_SDE_NULLSTRING);
-            else {     
-                sde_error(  status, 
-                            "sdeGetRecord()", 
-                            "SE_stream_get_float()");
-                return(MS_FAILURE);
-            }
-            break;
-        case SE_DOUBLE_TYPE:
-            status = SE_stream_get_double(  sde->connPoolInfo->stream, 
-                                            (short) (i+1), 
-                                            &doubleval);
-            if(status == SE_SUCCESS)
-                shape->values[i] = msDoubleToString(doubleval, MS_FALSE);
-            else if(status == SE_NULL_VALUE)
-                shape->values[i] = msStrdup(MS_SDE_NULLSTRING);
-            else {     
-                sde_error(  status, 
-                            "sdeGetRecord()", 
-                            "SE_stream_get_double()");
-                return(MS_FAILURE);
-            }
-            break;
-        case SE_STRING_TYPE:
-            shape->values[i] = (char *)msSmallMalloc(itemdefs[i].size+1);
-            status = SE_stream_get_string(  sde->connPoolInfo->stream, 
-                                            (short) (i+1), 
-                                            shape->values[i]);
-            if(status == SE_NULL_VALUE)
-                shape->values[i][0] = '\0'; /* empty string */
-            else if(status != SE_SUCCESS) {
-                sde_error(  status, 
-                            "sdeGetRecord()", 
-                            "SE_stream_get_string()");
-                return(MS_FAILURE);
-            }
-            break;
+      case SE_SMALLINT_TYPE:
+        /* changed by gdv */
+        status = SE_stream_get_smallint(sde->connPoolInfo->stream,
+                                        (short)(i+1),
+                                        &shortval);
+        if(status == SE_SUCCESS)
+          shape->values[i] = msLongToString(shortval);
+        else if(status == SE_NULL_VALUE)
+          shape->values[i] = msStrdup(MS_SDE_NULLSTRING);
+        else {
+          sde_error(  status,
+                      "sdeGetRecord()",
+                      "SE_stream_get_smallint()");
+          return(MS_FAILURE);
+        }
+        break;
+      case SE_INTEGER_TYPE:
+        status = SE_stream_get_integer( sde->connPoolInfo->stream,
+                                        (short)(i+1),
+                                        &longval);
+        if(status == SE_SUCCESS)
+          shape->values[i] = msLongToString(longval);
+        else if(status == SE_NULL_VALUE)
+          shape->values[i] = msStrdup(MS_SDE_NULLSTRING);
+        else {
+          sde_error(  status,
+                      "sdeGetRecord()",
+                      "SE_stream_get_integer()");
+          return(MS_FAILURE);
+        }
+        break;
+      case SE_FLOAT_TYPE:
+        status = SE_stream_get_float(   sde->connPoolInfo->stream,
+                                        (short)(i+1),
+                                        &floatval);
+        if(status == SE_SUCCESS)
+          shape->values[i] = msDoubleToString(floatval, MS_FALSE);
+        else if(status == SE_NULL_VALUE)
+          shape->values[i] = msStrdup(MS_SDE_NULLSTRING);
+        else {
+          sde_error(  status,
+                      "sdeGetRecord()",
+                      "SE_stream_get_float()");
+          return(MS_FAILURE);
+        }
+        break;
+      case SE_DOUBLE_TYPE:
+        status = SE_stream_get_double(  sde->connPoolInfo->stream,
+                                        (short) (i+1),
+                                        &doubleval);
+        if(status == SE_SUCCESS)
+          shape->values[i] = msDoubleToString(doubleval, MS_FALSE);
+        else if(status == SE_NULL_VALUE)
+          shape->values[i] = msStrdup(MS_SDE_NULLSTRING);
+        else {
+          sde_error(  status,
+                      "sdeGetRecord()",
+                      "SE_stream_get_double()");
+          return(MS_FAILURE);
+        }
+        break;
+      case SE_STRING_TYPE:
+        shape->values[i] = (char *)msSmallMalloc(itemdefs[i].size+1);
+        status = SE_stream_get_string(  sde->connPoolInfo->stream,
+                                        (short) (i+1),
+                                        shape->values[i]);
+        if(status == SE_NULL_VALUE)
+          shape->values[i][0] = '\0'; /* empty string */
+        else if(status != SE_SUCCESS) {
+          sde_error(  status,
+                      "sdeGetRecord()",
+                      "SE_stream_get_string()");
+          return(MS_FAILURE);
+        }
+        break;
 #ifdef SE_NSTRING_TYPE
-            case SE_NSTRING_TYPE:
-                wide = (SE_WCHAR *)msSmallMalloc(itemdefs[i].size*2*sizeof(SE_WCHAR)+1);
-                memset(wide, 0, itemdefs[i].size*2*sizeof(SE_WCHAR)+1);
-                status = SE_stream_get_nstring( sde->connPoolInfo->stream, 
-                                                (short) (i+1), 
-                                                wide);
-                if(status == SE_NULL_VALUE) {
-                    shape->values[i] = (char *)msSmallMalloc(itemdefs[i].size*sizeof(char)+1);
-                    shape->values[i][0] = '\0'; /* empty string */
-                    msFree(wide);
-                }
-                else if(status != SE_SUCCESS) {
-                    sde_error(  status, 
-                                "sdeGetRecord()", 
-                                "SE_stream_get_string()");
-                    return(MS_FAILURE);
-                } else {
-                    if (sde->bBigEndian)
-                        shape->values[i] = msConvertWideStringToUTF8((const wchar_t*) wide, "UTF-16BE");
-                    else
-                        shape->values[i] = msConvertWideStringToUTF8((const wchar_t*) wide, "UTF-16LE");
-                    msFree(wide);
-                    if (!shape->values[i]) {  /* There was an error */
-                        msSetError( MS_SDEERR,
-                                 "msConvertWideStringToUTF8()==NULL.",
-                                 "sdeGetRecord()");
-                        shape->values[i] = (char *)msSmallMalloc(itemdefs[i].size*sizeof(char)+1);
-                        shape->values[i][0] = '\0'; /* empty string */
-                    }                    
-                }
-                break;
+      case SE_NSTRING_TYPE:
+        wide = (SE_WCHAR *)msSmallMalloc(itemdefs[i].size*2*sizeof(SE_WCHAR)+1);
+        memset(wide, 0, itemdefs[i].size*2*sizeof(SE_WCHAR)+1);
+        status = SE_stream_get_nstring( sde->connPoolInfo->stream,
+                                        (short) (i+1),
+                                        wide);
+        if(status == SE_NULL_VALUE) {
+          shape->values[i] = (char *)msSmallMalloc(itemdefs[i].size*sizeof(char)+1);
+          shape->values[i][0] = '\0'; /* empty string */
+          msFree(wide);
+        } else if(status != SE_SUCCESS) {
+          sde_error(  status,
+                      "sdeGetRecord()",
+                      "SE_stream_get_string()");
+          return(MS_FAILURE);
+        } else {
+          if (sde->bBigEndian)
+            shape->values[i] = msConvertWideStringToUTF8((const wchar_t*) wide, "UTF-16BE");
+          else
+            shape->values[i] = msConvertWideStringToUTF8((const wchar_t*) wide, "UTF-16LE");
+          msFree(wide);
+          if (!shape->values[i]) {  /* There was an error */
+            msSetError( MS_SDEERR,
+                        "msConvertWideStringToUTF8()==NULL.",
+                        "sdeGetRecord()");
+            shape->values[i] = (char *)msSmallMalloc(itemdefs[i].size*sizeof(char)+1);
+            shape->values[i][0] = '\0'; /* empty string */
+          }
+        }
+        break;
 #endif
 
 #ifdef SE_UUID_TYPE
 
-        case SE_UUID_TYPE:
-            shape->values[i] = (char *)msSmallMalloc(itemdefs[i].size+1);
-            status = SE_stream_get_uuid  (  sde->connPoolInfo->stream, 
-                                            (short) (i+1), 
-                                            shape->values[i]);
-            if(status == SE_NULL_VALUE)
-                shape->values[i][0] = '\0'; /* empty string */
-            else if(status != SE_SUCCESS) {
-                sde_error(  status, 
-                            "sdeGetRecord()", 
-                            "SE_stream_get_uuid()");
-                return(MS_FAILURE);
-            }
-            break;
-            
+      case SE_UUID_TYPE:
+        shape->values[i] = (char *)msSmallMalloc(itemdefs[i].size+1);
+        status = SE_stream_get_uuid  (  sde->connPoolInfo->stream,
+                                        (short) (i+1),
+                                        shape->values[i]);
+        if(status == SE_NULL_VALUE)
+          shape->values[i][0] = '\0'; /* empty string */
+        else if(status != SE_SUCCESS) {
+          sde_error(  status,
+                      "sdeGetRecord()",
+                      "SE_stream_get_uuid()");
+          return(MS_FAILURE);
+        }
+        break;
+
 #endif
 
 #ifdef SE_CLOB_TYPE
 
-        case SE_CLOB_TYPE:
-            status = SE_stream_get_clob(sde->connPoolInfo->stream, (short) (i+1), &clobval);
-            if(status == SE_SUCCESS) {
-                shape->values[i] = (char *)msSmallMalloc(sizeof(char)*clobval.clob_length);
-                shape->values[i] = memcpy(  shape->values[i],
-                                            clobval.clob_buffer, 
-                                            clobval.clob_length);
-                SE_clob_free(&clobval);
-            }
-            else if (status == SE_NULL_VALUE) {
-                shape->values[i] = msStrdup(MS_SDE_NULLSTRING);
-            }
-            else {
-                sde_error(  status,  
-                            "sdeGetRecord()", 
-                            "SE_stream_get_clob()");
-                return(MS_FAILURE);
-            }
-            break;    
+      case SE_CLOB_TYPE:
+        memset(&clobval, 0, sizeof(clobval)); /* to prevent from the crash in SE_stream_get_clob */
+        status = SE_stream_get_clob(sde->connPoolInfo->stream, (short) (i+1), &clobval);
+        if(status == SE_SUCCESS) {
+          shape->values[i] = (char *)msSmallMalloc(sizeof(char)*clobval.clob_length);
+          shape->values[i] = memcpy(  shape->values[i],
+                                      clobval.clob_buffer,
+                                      clobval.clob_length);
+          SE_clob_free(&clobval);
+        } else if (status == SE_NULL_VALUE) {
+          shape->values[i] = msStrdup(MS_SDE_NULLSTRING);
+        } else {
+          sde_error(  status,
+                      "sdeGetRecord()",
+                      "SE_stream_get_clob()");
+          return(MS_FAILURE);
+        }
+        break;
 #endif
 
 #ifdef SE_CLOB_TYPE
 
-        case SE_NCLOB_TYPE:
-            status = SE_stream_get_nclob(sde->connPoolInfo->stream, (short) (i+1), &nclobval);
-            if(status == SE_SUCCESS) {
-                shape->values[i] = (char *)msSmallMalloc(sizeof(char)*nclobval.nclob_length);
-                shape->values[i] = memcpy(  shape->values[i],
-                                            nclobval.nclob_buffer, 
-                                            nclobval.nclob_length);
-                SE_nclob_free(&nclobval);
-            }
-            else if (status == SE_NULL_VALUE) {
-                shape->values[i] = msStrdup(MS_SDE_NULLSTRING);
-            }
-            else {
-                sde_error(  status,  
-                            "sdeGetRecord()", 
-                            "SE_stream_get_nclob()");
-                return(MS_FAILURE);
-            }
-            break;    
+      case SE_NCLOB_TYPE:
+        memset(&nclobval, 0, sizeof(nclobval)); /* to prevent from the crash in SE_stream_get_nclob */
+        status = SE_stream_get_nclob(sde->connPoolInfo->stream, (short) (i+1), &nclobval);
+        if(status == SE_SUCCESS) {
+          /* the returned string is not null-terminated */
+          nclobstring = (SE_WCHAR*)malloc(sizeof(char)*(nclobval.nclob_length+2));
+          memcpy(nclobstring, nclobval.nclob_buffer, nclobval.nclob_length);
+          nclobstring[nclobval.nclob_length / 2] = '\0';
+
+          if (sde->bBigEndian)
+            shape->values[i] = msConvertWideStringToUTF8((const wchar_t*) nclobstring, "UTF-16BE");
+          else
+            shape->values[i] = msConvertWideStringToUTF8((const wchar_t*) nclobstring, "UTF-16LE");
+      
+          if (!shape->values[i]) {  /* There was an error */
+            msSetError( MS_SDEERR,
+                        "msConvertWideStringToUTF8()==NULL.",
+                        "sdeGetRecord()");
+            shape->values[i] = (char *)malloc(itemdefs[i].size*sizeof(char)+1);
+            shape->values[i][0] = '\0'; /* empty string */
+          }                
+
+          SE_nclob_free(&nclobval);
+          msFree(nclobstring);
+        } else if (status == SE_NULL_VALUE) {
+          shape->values[i] = msStrdup(MS_SDE_NULLSTRING);
+        } else {
+          sde_error(  status,
+                      "sdeGetRecord()",
+                      "SE_stream_get_nclob()");
+          return(MS_FAILURE);
+        }
+        break;
 #endif
 
-        case SE_BLOB_TYPE:
-            status = SE_stream_get_blob(sde->connPoolInfo->stream, (short) (i+1), &blobval);
-            if(status == SE_SUCCESS) {
-                shape->values[i] = (char *)msSmallMalloc(sizeof(char)*blobval.blob_length);
-                shape->values[i] = memcpy(  shape->values[i],
-                                            blobval.blob_buffer, 
-                                            blobval.blob_length);
-                SE_blob_free(&blobval);
-            }
-            else if (status == SE_NULL_VALUE) {
-                shape->values[i] = msStrdup(MS_SDE_NULLSTRING);
-            }
-            else {
-                sde_error(  status,  
-                            "sdeGetRecord()", 
-                            "SE_stream_get_blob()");
-                return(MS_FAILURE);
-            }
-            break;
-            
-        case SE_DATE_TYPE:
-            status = SE_stream_get_date(sde->connPoolInfo->stream, (short)(i+1), &dateval);
-            if(status == SE_SUCCESS) {
-                shape->values[i] = (char *)msSmallMalloc(sizeof(char)*MS_SDE_TIMEFMTSIZE);
-                strftime(   shape->values[i], 
-                            MS_SDE_TIMEFMTSIZE, 
-                            MS_SDE_TIMEFMT, 
-                            &dateval);
-            } 
-            else if(status == SE_NULL_VALUE)
-                shape->values[i] = msStrdup(MS_SDE_NULLSTRING);
-            else {     
-                sde_error(  status, 
-                            "sdeGetRecord()", 
-                            "SE_stream_get_date()");
-                return(MS_FAILURE);
-            }
-            break;
-        case SE_SHAPE_TYPE:
-            status = SE_stream_get_shape(sde->connPoolInfo->stream, (short)(i+1), shapeval);
-            if(status == SE_SUCCESS)
-                shape->values[i] = msStrdup(MS_SDE_SHAPESTRING);
-            else if(status == SE_NULL_VALUE)
-                shape->values[i] = msStrdup(MS_SDE_NULLSTRING);
-            else {
-                sde_error(  status, 
-                            "sdeGetRecord()", 
-                            "SE_stream_get_shape()");
-                return(MS_FAILURE);
-            }
-            break;
-        default: 
-          msSetError(   MS_SDEERR, 
-                        "Unknown SDE column type.", 
-                        "sdeGetRecord()");
+      case SE_BLOB_TYPE:
+        status = SE_stream_get_blob(sde->connPoolInfo->stream, (short) (i+1), &blobval);
+        if(status == SE_SUCCESS) {
+          shape->values[i] = (char *)msSmallMalloc(sizeof(char)*blobval.blob_length);
+          shape->values[i] = memcpy(  shape->values[i],
+                                      blobval.blob_buffer,
+                                      blobval.blob_length);
+          SE_blob_free(&blobval);
+        } else if (status == SE_NULL_VALUE) {
+          shape->values[i] = msStrdup(MS_SDE_NULLSTRING);
+        } else {
+          sde_error(  status,
+                      "sdeGetRecord()",
+                      "SE_stream_get_blob()");
           return(MS_FAILURE);
-          break;
-        } /* switch(itemdefs[i].sde_type) */
-    } /*     for(i=0; i<layer->numitems; i++) { */
+        }
+        break;
+
+      case SE_DATE_TYPE:
+        status = SE_stream_get_date(sde->connPoolInfo->stream, (short)(i+1), &dateval);
+        if(status == SE_SUCCESS) {
+          shape->values[i] = (char *)msSmallMalloc(sizeof(char)*MS_SDE_TIMEFMTSIZE);
+          strftime(   shape->values[i],
+                      MS_SDE_TIMEFMTSIZE,
+                      MS_SDE_TIMEFMT,
+                      &dateval);
+        } else if(status == SE_NULL_VALUE)
+          shape->values[i] = msStrdup(MS_SDE_NULLSTRING);
+        else {
+          sde_error(  status,
+                      "sdeGetRecord()",
+                      "SE_stream_get_date()");
+          return(MS_FAILURE);
+        }
+        break;
+      case SE_SHAPE_TYPE:
+        status = SE_stream_get_shape(sde->connPoolInfo->stream, (short)(i+1), shapeval);
+        if(status == SE_SUCCESS)
+          shape->values[i] = msStrdup(MS_SDE_SHAPESTRING);
+        else if(status == SE_NULL_VALUE)
+          shape->values[i] = msStrdup(MS_SDE_NULLSTRING);
+        else {
+          sde_error(  status,
+                      "sdeGetRecord()",
+                      "SE_stream_get_shape()");
+          return(MS_FAILURE);
+        }
+        break;
+      default:
+        msSetError(   MS_SDEERR,
+                      "Unknown SDE column type.",
+                      "sdeGetRecord()");
+        return(MS_FAILURE);
+        break;
+    } /* switch(itemdefs[i].sde_type) */
+  } /*     for(i=0; i<layer->numitems; i++) { */
+
+  if(SE_shape_is_nil(shapeval)) return(MS_SUCCESS);
 
-    if(SE_shape_is_nil(shapeval)) return(MS_SUCCESS);
-  
-    /* copy sde shape to a mapserver shape */
-    status = sdeShapeCopy(shapeval, shape);
-    if(status != MS_SUCCESS) return(MS_FAILURE);
+  /* copy sde shape to a mapserver shape */
+  status = sdeShapeCopy(shapeval, shape);
+  if(status != MS_SUCCESS) return(MS_FAILURE);
 
-    /* clean up */
-    SE_shape_free(shapeval);
+  /* clean up */
+  SE_shape_free(shapeval);
 
-  
-    return(MS_SUCCESS);
+
+  return(MS_SUCCESS);
 }
 
-static SE_QUERYINFO getSDEQueryInfo(layerObj *layer) 
+static SE_QUERYINFO getSDEQueryInfo(layerObj *layer)
 {
-    SE_QUERYINFO query_info;
-    long status;
-    
-    msSDELayerInfo *sde=NULL;
-    
-    if(!msSDELayerIsOpen(layer)) {
-        msSetError( MS_SDEERR, 
-                    "SDE layer has not been opened.", 
-                    "getSDEQueryInfo()");
-        return(NULL);
-    }
-    
-    sde = layer->layerinfo;
-
-    /* 
-    ** See http://forums.esri.com/Thread.asp?c=2&f=59&t=108929&mc=4#msgid310273 
-    ** SE_queryinfo is a new SDE struct in ArcSDE 8.x that is a bit easier  
-    ** (and faster) to use.  HCB 
-    */
-    status = SE_queryinfo_create (&query_info);
-    if(status != SE_SUCCESS) {
-        sde_error(  status, 
-                    "getSDEQueryInfo()", 
-                    "SE_queryinfo_create()");
-        return(NULL);
-    }
+  SE_QUERYINFO query_info;
+  long status;
 
-    /* set the tables -- just one at this point */
-    status = SE_queryinfo_set_tables (  query_info, 
-                                        1, 
-                                        (const CHAR **) &(sde->table),
-                                        NULL);
-    if(status != SE_SUCCESS) {
-        sde_error(  status, 
-                    "getSDEQueryInfo()", 
-                    "SE_queryinfo_create()");
-        return(NULL);
-    }
+  msSDELayerInfo *sde=NULL;
 
-    /* set the "where" clause */
-    if(!(layer->filter.string))
-        /* set to empty string */
-        status = SE_queryinfo_set_where_clause (query_info, 
-                                                (const CHAR * ) "");
-    else
-        /* set to the layer's filter.string */
-        status = SE_queryinfo_set_where_clause (query_info, 
-                                                (const CHAR * ) (layer->filter.string));
-    if(status != SE_SUCCESS) {
-        sde_error(  status, 
-                    "getSDEQueryInfo()", 
-                    "SE_queryinfo_set_where_clause()");
-        return(NULL);
-    }
+  if(!msSDELayerIsOpen(layer)) {
+    msSetError( MS_SDEERR,
+                "SDE layer has not been opened.",
+                "getSDEQueryInfo()");
+    return(NULL);
+  }
 
-    status = SE_queryinfo_set_columns(  query_info, 
-                                        layer->numitems, 
-                                        (const char **)layer->items);
-    if(status != SE_SUCCESS) {
-        sde_error(  status, 
-                    "getSDEQueryInfo()", 
-                    "SE_queryinfo_set_columns()");
-        return(NULL);
-    }
-  
-    /* Join the spatial and feature tables.  If we specify the type of join */
-    /* we'll query faster than querying all tables individually (old method) */
-    status = SE_queryinfo_set_query_type (query_info,SE_QUERYTYPE_JSF);
-    if(status != SE_SUCCESS) {
-        sde_error(  status, 
-                    "getSDEQueryInfo()", 
-                    "SE_queryinfo_set_query_type()");
-        return(NULL);
-    }
-    
-    return query_info;
+  sde = layer->layerinfo;
+
+  /*
+  ** See http://forums.esri.com/Thread.asp?c=2&f=59&t=108929&mc=4#msgid310273
+  ** SE_queryinfo is a new SDE struct in ArcSDE 8.x that is a bit easier
+  ** (and faster) to use.  HCB
+  */
+  status = SE_queryinfo_create (&query_info);
+  if(status != SE_SUCCESS) {
+    sde_error(  status,
+                "getSDEQueryInfo()",
+                "SE_queryinfo_create()");
+    return(NULL);
+  }
+
+  /* set the tables -- just one at this point */
+  status = SE_queryinfo_set_tables (  query_info,
+                                      1,
+                                      (const CHAR **) &(sde->table),
+                                      NULL);
+  if(status != SE_SUCCESS) {
+    sde_error(  status,
+                "getSDEQueryInfo()",
+                "SE_queryinfo_create()");
+    return(NULL);
+  }
+
+  /* set the "where" clause */
+  if(!(layer->filter.string))
+    /* set to empty string */
+    status = SE_queryinfo_set_where_clause (query_info,
+                                            (const CHAR * ) "");
+  else
+    /* set to the layer's filter.string */
+    status = SE_queryinfo_set_where_clause (query_info,
+                                            (const CHAR * ) (layer->filter.string));
+  if(status != SE_SUCCESS) {
+    sde_error(  status,
+                "getSDEQueryInfo()",
+                "SE_queryinfo_set_where_clause()");
+    return(NULL);
+  }
+
+  status = SE_queryinfo_set_columns(  query_info,
+                                      layer->numitems,
+                                      (const char **)layer->items);
+  if(status != SE_SUCCESS) {
+    sde_error(  status,
+                "getSDEQueryInfo()",
+                "SE_queryinfo_set_columns()");
+    return(NULL);
+  }
+
+  /* Join the spatial and feature tables.  If we specify the type of join */
+  /* we'll query faster than querying all tables individually (old method) */
+  status = SE_queryinfo_set_query_type (query_info,SE_QUERYTYPE_JSF);
+  if(status != SE_SUCCESS) {
+    sde_error(  status,
+                "getSDEQueryInfo()",
+                "SE_queryinfo_set_query_type()");
+    return(NULL);
+  }
+
+  return query_info;
 }
 
-static SE_SQL_CONSTRUCT* getSDESQLConstructInfo(layerObj *layer, long* id) 
+static SE_SQL_CONSTRUCT* getSDESQLConstructInfo(layerObj *layer, long* id)
 {
-    SE_SQL_CONSTRUCT* sql;
-
-    char *full_filter=NULL;
-    char *pszId=NULL;
-    long status;
-    
-    msSDELayerInfo *sde=NULL;
-    full_filter = (char*) msSmallMalloc((1000+1)*sizeof (char));
-    full_filter[0] = '\0';
-    if(!msSDELayerIsOpen(layer)) {
-        msSetError( MS_SDEERR, 
-                    "SDE layer has not been opened.", 
-                    "getSDESQLConstructInfo()");
-        return(NULL);
-    }
-    
-    sde = layer->layerinfo;
-    
-    if (!sde->join_table) {
-        msSetError( MS_SDEERR, 
-                    "Join table is null, we should be using QueryInfo.", 
-                    "getSDESQLConstructInfo()");
-        return(NULL);
-    }
-    
-    status = SE_sql_construct_alloc( 2, &sql);
-    if(status != SE_SUCCESS) {
-        sde_error(  status, 
-                    "getSDESQLConstructInfo()", 
-                    "SE_sql_construct_alloc()");
-        return(NULL);       
-    }
+  SE_SQL_CONSTRUCT* sql;
 
-    strcpy(sql->tables[0], sde->table); /* main table */
-    strcpy(sql->tables[1], sde->join_table); /* join table */
-      
-    /* If we were given an ID *and* we have a join, we need to 
-       set our FILTER statement to reflect this. */
-    if ((sde->join_table) && (id != NULL)) {
-        pszId = msLongToString(*id);
-        strcat(full_filter, layer->filter.string);
-        strcat(full_filter, " AND ");
-        strcat(full_filter, sde->row_id_column);
-        strcat(full_filter, "=");
-        strcat(full_filter, pszId);
-        msFree(pszId);
-        sql->where = msStrdup(full_filter);
-     
-
-    } else {
-        sql->where = layer->filter.string;
-    }
-    
-    msFree(full_filter);   
-    
-    if (layer->debug) msDebug("WHERE statement: %s\n", sql->where);
-    return sql;
-} 
+  char *full_filter=NULL;
+  char *pszId=NULL;
+  long status;
+
+  msSDELayerInfo *sde=NULL;
+  full_filter = (char*) msSmallMalloc((1000+1)*sizeof (char));
+  full_filter[0] = '\0';
+  if(!msSDELayerIsOpen(layer)) {
+    msSetError( MS_SDEERR,
+                "SDE layer has not been opened.",
+                "getSDESQLConstructInfo()");
+    return(NULL);
+  }
+
+  sde = layer->layerinfo;
+
+  if (!sde->join_table) {
+    msSetError( MS_SDEERR,
+                "Join table is null, we should be using QueryInfo.",
+                "getSDESQLConstructInfo()");
+    return(NULL);
+  }
+
+  status = SE_sql_construct_alloc( 2, &sql);
+  if(status != SE_SUCCESS) {
+    sde_error(  status,
+                "getSDESQLConstructInfo()",
+                "SE_sql_construct_alloc()");
+    return(NULL);
+  }
+
+  strcpy(sql->tables[0], sde->table); /* main table */
+  strcpy(sql->tables[1], sde->join_table); /* join table */
+
+  /* If we were given an ID *and* we have a join, we need to
+     set our FILTER statement to reflect this. */
+  if ((sde->join_table) && (id != NULL)) {
+    pszId = msLongToString(*id);
+    strcat(full_filter, layer->filter.string);
+    strcat(full_filter, " AND ");
+    strcat(full_filter, sde->row_id_column);
+    strcat(full_filter, "=");
+    strcat(full_filter, pszId);
+    msFree(pszId);
+    sql->where = msStrdup(full_filter);
+
+
+  } else {
+    sql->where = layer->filter.string;
+  }
+
+  msFree(full_filter);
+
+  if (layer->debug) msDebug("WHERE statement: %s\n", sql->where);
+  return sql;
+}
 #endif
 
 /************************************************************************/
@@ -1054,327 +1062,326 @@ static SE_SQL_CONSTRUCT* getSDESQLConstructInfo(layerObj *layer, long* id)
 /*     even for layers with the same version name.  These are *not*     */
 /*     shared across layers.                                            */
 /* -------------------------------------------------------------------- */
-int msSDELayerOpen(layerObj *layer) {
+int msSDELayerOpen(layerObj *layer)
+{
 #ifdef USE_SDE
-    long status=-1;
-    int endian_test=1;
-    char **params=NULL;
-    char **data_params=NULL;
-    char *join_table=NULL;
-    
-    int numparams=0;
-    SE_ERROR hSDEError;
-    SE_STATEINFO state;
-    SE_VERSIONINFO version;
-    
-    SE_ENVELOPE envelope;
-
-    msSDELayerInfo *sde = NULL;
-    msSDEConnPoolInfo *poolinfo;
-
-    /* allocate space for SDE structures */
-    sde = (msSDELayerInfo *) malloc(sizeof(msSDELayerInfo));
-    MS_CHECK_ALLOC(sde, sizeof(msSDELayerInfo), MS_FAILURE);
- 
-    sde->state_id = SE_BASE_STATE_ID;
-  
-    /* initialize the table and spatial column names */
-    sde->table = NULL;
-    sde->column = NULL;
-    sde->row_id_column = NULL;
-    sde->join_table = NULL;
-    sde->basedefs = NULL;
-    sde->joindefs = NULL;
-    sde->extent = (rectObj *) msSmallMalloc(sizeof(rectObj));
+  long status=-1;
+  int endian_test=1;
+  char **params=NULL;
+  char **data_params=NULL;
+  char *join_table=NULL;
 
-    sde->nBaseColumns = (short *) msSmallMalloc(1*sizeof(short));
-    *(sde->nBaseColumns) = 0;
-    sde->nJoinColumns = (short *) msSmallMalloc(1*sizeof(short));
-    *(sde->nJoinColumns) = 0;
-
-    if(!sde->extent) {
-        msSetError( MS_MEMERR, 
-                    "Error allocating extent for SDE layer", 
-                    "msSDELayerOpen()");
-        return(MS_FAILURE);
-    }
-  
-    /* request a connection and stream from the pool */
-    poolinfo = (msSDEConnPoolInfo *)msConnPoolRequest( layer ); 
+  int numparams=0;
+  SE_ERROR hSDEError;
+  SE_STATEINFO state;
+  SE_VERSIONINFO version;
 
-#ifdef SE_connection_test_server
-    /* check the connection */
-    if (poolinfo && (SE_connection_test_server(poolinfo->connection, 30) != SE_SUCCESS)) {
-        msSDECloseConnection(poolinfo->connection);
-    }
-#endif
-  
-    /* If we weren't returned a connection and stream, initialize new ones */
-    if (!poolinfo) {
-        char *conn_decrypted;
+  SE_ENVELOPE envelope;
 
-        if (layer->debug) 
-            msDebug("msSDELayerOpen(): "
-                    "Layer %s opened from scratch.\n", layer->name);
+  msSDELayerInfo *sde = NULL;
+  msSDEConnPoolInfo *poolinfo;
+
+  /* allocate space for SDE structures */
+  sde = (msSDELayerInfo *) malloc(sizeof(msSDELayerInfo));
+  MS_CHECK_ALLOC(sde, sizeof(msSDELayerInfo), MS_FAILURE);
+
+  sde->state_id = SE_BASE_STATE_ID;
+
+  /* initialize the table and spatial column names */
+  sde->table = NULL;
+  sde->column = NULL;
+  sde->row_id_column = NULL;
+  sde->join_table = NULL;
+  sde->basedefs = NULL;
+  sde->joindefs = NULL;
+  sde->extent = (rectObj *) msSmallMalloc(sizeof(rectObj));
+
+  sde->nBaseColumns = (short *) msSmallMalloc(1*sizeof(short));
+  *(sde->nBaseColumns) = 0;
+  sde->nJoinColumns = (short *) msSmallMalloc(1*sizeof(short));
+  *(sde->nJoinColumns) = 0;
+
+  if(!sde->extent) {
+    msSetError( MS_MEMERR,
+                "Error allocating extent for SDE layer",
+                "msSDELayerOpen()");
+    return(MS_FAILURE);
+  }
 
+  /* request a connection and stream from the pool */
+  poolinfo = (msSDEConnPoolInfo *)msConnPoolRequest( layer );
 
-        poolinfo = (msSDEConnPoolInfo *)malloc(sizeof *poolinfo);
-        MS_CHECK_ALLOC(poolinfo, sizeof *poolinfo, MS_FAILURE);
+#ifdef SE_connection_test_server
+  /* check the connection */
+  if (poolinfo && (SE_connection_test_server(poolinfo->connection, 30) != SE_SUCCESS)) {
+    msSDECloseConnection(poolinfo->connection);
+  }
+#endif
 
-        /* Decrypt any encrypted token in the connection string */
-        conn_decrypted = msDecryptStringTokens(layer->map, layer->connection);
+  /* If we weren't returned a connection and stream, initialize new ones */
+  if (!poolinfo) {
+    char *conn_decrypted;
 
-        /* An error should already have been produced */
-        if (conn_decrypted == NULL) {
-            return(MS_FAILURE);  
-        }
-        /* Split the connection parameters and make sure we have enough of them */
-        params = msStringSplit(conn_decrypted, ',', &numparams);
-        if(!params) {
-            msSetError( MS_MEMERR, 
-                        "Error splitting SDE connection information.", 
-                        "msSDELayerOpen()");
-            msFree(conn_decrypted);
-            return(MS_FAILURE);
-        }
-        msFree(conn_decrypted);
-        conn_decrypted = NULL;
-
-        if(numparams < 5) {
-            msSetError( MS_SDEERR, 
-                        "Not enough SDE connection parameters specified.", 
-                        "msSDELayerOpen()");
-            return(MS_FAILURE);
-        }
-  
-        /* Create the connection handle and put into poolinfo->connection */
-        status = SE_connection_create(params[0], 
-                                      params[1], 
-                                      params[2], 
-                                      params[3], 
-                                      params[4], 
-                                      &(hSDEError), 
-                                      &(poolinfo->connection));
-
-        if(status != SE_SUCCESS) {
-            sde_error(  status, 
-                        "msSDELayerOpen()", 
-                        "SE_connection_create()");
-            return(MS_FAILURE);
-        }
+    if (layer->debug)
+      msDebug("msSDELayerOpen(): "
+              "Layer %s opened from scratch.\n", layer->name);
 
-        /* ------------------------------------------------------------------------- */
-        /* Set the concurrency type for the connection.  SE_UNPROTECTED_POLICY is    */
-        /* suitable when only one thread accesses the specified connection.          */
-        /* ------------------------------------------------------------------------- */
-        status = SE_connection_set_concurrency( poolinfo->connection, 
-                                                SE_UNPROTECTED_POLICY);
-
-  
-        if(status != SE_SUCCESS) {
-            sde_error(  status, 
-                        "msSDELayerOpen()", 
-                        "SE_connection_set_concurrency()");
-            return(MS_FAILURE);
-        }
-    
-
-        status = SE_stream_create(poolinfo->connection, &(poolinfo->stream));
-        if(status != SE_SUCCESS) {
-            sde_error(  status, 
-                        "msSDELayerOpen()", 
-                        "SE_stream_create()");
-            return(MS_FAILURE);
-        }
 
-        /* Register the connection with the connection pooling API.  Give  */
-        /* msSDECloseConnection as the function to call when we run out of layer  */
-        /* instances using it */
-        msConnPoolRegister(layer, poolinfo, msSDECloseConnection);
-        msFreeCharArray(params, numparams); /* done with parameter list */
-    } /* !poolinfo */
-
-    /* Split the DATA member into its parameters using the comma */
-    /* Periods (.) are used to denote table names and schemas in SDE,  */
-    /* as are underscores (_). */
-    data_params = msStringSplit(layer->data, ',', &numparams);
-    if(!data_params) {
-        msSetError( MS_MEMERR, 
-                    "Error splitting SDE layer information.", 
-                    "msSDELayerOpen()");
-        return(MS_FAILURE);
-    }
+    poolinfo = (msSDEConnPoolInfo *)malloc(sizeof *poolinfo);
+    MS_CHECK_ALLOC(poolinfo, sizeof *poolinfo, MS_FAILURE);
 
-    if(numparams < 2) {
-        msSetError( MS_SDEERR, 
-                    "Not enough SDE layer parameters specified.", 
-                    "msSDELayerOpen()");
-        return(MS_FAILURE);
+    /* Decrypt any encrypted token in the connection string */
+    conn_decrypted = msDecryptStringTokens(layer->map, layer->connection);
+
+    /* An error should already have been produced */
+    if (conn_decrypted == NULL) {
+      return(MS_FAILURE);
+    }
+    /* Split the connection parameters and make sure we have enough of them */
+    params = msStringSplit(conn_decrypted, ',', &numparams);
+    if(!params) {
+      msSetError( MS_MEMERR,
+                  "Error splitting SDE connection information.",
+                  "msSDELayerOpen()");
+      msFree(conn_decrypted);
+      return(MS_FAILURE);
     }
+    msFree(conn_decrypted);
+    conn_decrypted = NULL;
 
-    sde->table = msStrdup(data_params[0]); 
-    sde->column = msStrdup(data_params[1]);
-    
-    join_table = msLayerGetProcessingKey(layer,"JOINTABLE");
-    if (join_table) {
-        sde->join_table = msStrdup(join_table);
-        /* msFree(join_table); */
+    if(numparams < 5) {
+      msSetError( MS_SDEERR,
+                  "Not enough SDE connection parameters specified.",
+                  "msSDELayerOpen()");
+      return(MS_FAILURE);
     }
-    if (numparams < 3){ 
-        /* User didn't specify a version, we won't use one */
-        if (layer->debug) {
-            msDebug("msSDELayerOpen(): Layer %s did not have a " 
-                    "specified version.\n", 
-                    layer->name);
-        } 
-        sde->state_id = SE_DEFAULT_STATE_ID;
-    } 
-    else {
-        /* A version was specified... obtain the state_id */
-        /* for it. */
-        if (layer->debug) {
-            msDebug("msSDELayerOpen(): Layer %s specified version %s.\n", 
-                    layer->name, 
-                    data_params[2]);
-        }
-        status = SE_versioninfo_create (&(version));
-        if(status != SE_SUCCESS) {
-            sde_error(  status, 
-                        "msSDELayerOpen()", 
-                        "SE_versioninfo_create()");
-            return(MS_FAILURE);
-        }
-        status = SE_version_get_info(poolinfo->connection, data_params[2], version);
-    
-        if(status != SE_SUCCESS) {
-       
-            if (status == SE_INVALID_RELEASE) {
-                /* The user has incongruent versions of SDE, ie 8.2 client and  */
-                /* 8.3 server set the state_id to SE_DEFAULT_STATE_ID, which means    */
-                /* no version queries are done */
-                sde->state_id = SE_DEFAULT_STATE_ID;
-            }
-            else {
-                sde_error(  status, 
-                            "msSDELayerOpen()", 
-                            "SE_version_get_info()");
-                SE_versioninfo_free(version);
-                return(MS_FAILURE);
-            }
-        } /* couldn't get version info */
-  
-    } /* version was specified */
-
-    /* Get the STATEID from the given version and set the stream to  */
-    /* that if we didn't already set it to SE_DEFAULT_STATE_ID.   */
-    if (sde->state_id != SE_DEFAULT_STATE_ID){
-        status = SE_versioninfo_get_state_id(version, &sde->state_id);
-        if(status != SE_SUCCESS) {
-            sde_error(  status, 
-                        "msSDELayerOpen()", 
-                        "SE_versioninfo_get_state_id()");
-            SE_versioninfo_free(version);
-            return(MS_FAILURE);
-        }
-        
-        SE_versioninfo_free(version);
-        status = SE_stateinfo_create (&state);
-        if(status != SE_SUCCESS) {
-            sde_error(  status, 
-                        "msSDELayerOpen()", 
-                        "SE_stateinfo_create()");
-            return(MS_FAILURE);
-        }    
-        status = SE_state_get_info( poolinfo->connection, 
-                                    sde->state_id, 
-                                    state);
-        if(status != SE_SUCCESS) {
-            sde_error(status, "msSDELayerOpen()", "SE_state_get_info()");
-            SE_stateinfo_free (state); 
-            return(MS_FAILURE);
-        }  
-        if (SE_stateinfo_is_open (state)) {
-            /* If the state is open for edits, we shouldn't be querying from it */
-            sde_error(  status, 
-                        "msSDELayerOpen()", 
-                        "SE_stateinfo_is_open() -- State for version is open");
-            SE_stateinfo_free (state); 
-            return(MS_FAILURE);
-        }
-        SE_stateinfo_free (state); 
-    } /* if (!(sde->state_id == SE_DEFAULT_STATE_ID)) */
- 
-
-    /* done with the DATA stuff now */
-    msFreeCharArray(data_params, numparams);  
-  
-    status = SE_layerinfo_create(NULL, &(sde->layerinfo));
+
+    /* Create the connection handle and put into poolinfo->connection */
+    status = SE_connection_create(params[0],
+                                  params[1],
+                                  params[2],
+                                  params[3],
+                                  params[4],
+                                  &(hSDEError),
+                                  &(poolinfo->connection));
+
     if(status != SE_SUCCESS) {
-        sde_error(status, "msSDELayerOpen()", "SE_layerinfo_create()");
-        return(MS_FAILURE);
+      sde_error(  status,
+                  "msSDELayerOpen()",
+                  "SE_connection_create()");
+      return(MS_FAILURE);
     }
 
+    /* ------------------------------------------------------------------------- */
+    /* Set the concurrency type for the connection.  SE_UNPROTECTED_POLICY is    */
+    /* suitable when only one thread accesses the specified connection.          */
+    /* ------------------------------------------------------------------------- */
+    status = SE_connection_set_concurrency( poolinfo->connection,
+                                            SE_UNPROTECTED_POLICY);
 
-    status = msSDEGetLayerInfo( layer,
-                                poolinfo->connection,
-                                sde->table,
-                                sde->column,
-                                layer->connection,
-                                sde->layerinfo);
 
-    if(status != MS_SUCCESS) {
-        sde_error(status, "msSDELayerOpen()", "msSDEGetLayerInfo()");
-        return(MS_FAILURE);
+    if(status != SE_SUCCESS) {
+      sde_error(  status,
+                  "msSDELayerOpen()",
+                  "SE_connection_set_concurrency()");
+      return(MS_FAILURE);
     }
 
-    status = SE_coordref_create(&(sde->coordref));
+
+    status = SE_stream_create(poolinfo->connection, &(poolinfo->stream));
     if(status != SE_SUCCESS) {
-        sde_error(status, "msSDELayerOpen()", "SE_coordref_create()");
-        return(MS_FAILURE);
-    }
+      sde_error(  status,
+                  "msSDELayerOpen()",
+                  "SE_stream_create()");
+      return(MS_FAILURE);
+    }
+
+    /* Register the connection with the connection pooling API.  Give  */
+    /* msSDECloseConnection as the function to call when we run out of layer  */
+    /* instances using it */
+    msConnPoolRegister(layer, poolinfo, msSDECloseConnection);
+    msFreeCharArray(params, numparams); /* done with parameter list */
+  } /* !poolinfo */
+
+  /* Split the DATA member into its parameters using the comma */
+  /* Periods (.) are used to denote table names and schemas in SDE,  */
+  /* as are underscores (_). */
+  data_params = msStringSplit(layer->data, ',', &numparams);
+  if(!data_params) {
+    msSetError( MS_MEMERR,
+                "Error splitting SDE layer information.",
+                "msSDELayerOpen()");
+    return(MS_FAILURE);
+  }
+
+  if(numparams < 2) {
+    msSetError( MS_SDEERR,
+                "Not enough SDE layer parameters specified.",
+                "msSDELayerOpen()");
+    return(MS_FAILURE);
+  }
+
+  sde->table = msStrdup(data_params[0]);
+  sde->column = msStrdup(data_params[1]);
 
-    status = SE_layerinfo_get_coordref(sde->layerinfo, sde->coordref);
+  join_table = msLayerGetProcessingKey(layer,"JOINTABLE");
+  if (join_table) {
+    sde->join_table = msStrdup(join_table);
+    /* msFree(join_table); */
+  }
+  if (numparams < 3) {
+    /* User didn't specify a version, we won't use one */
+    if (layer->debug) {
+      msDebug("msSDELayerOpen(): Layer %s did not have a "
+              "specified version.\n",
+              layer->name);
+    }
+    sde->state_id = SE_DEFAULT_STATE_ID;
+  } else {
+    /* A version was specified... obtain the state_id */
+    /* for it. */
+    if (layer->debug) {
+      msDebug("msSDELayerOpen(): Layer %s specified version %s.\n",
+              layer->name,
+              data_params[2]);
+    }
+    status = SE_versioninfo_create (&(version));
     if(status != SE_SUCCESS) {
-        sde_error(status, "msSDELayerOpen()", "SE_layerinfo_get_coordref()");
-        return(MS_FAILURE);
+      sde_error(  status,
+                  "msSDELayerOpen()",
+                  "SE_versioninfo_create()");
+      return(MS_FAILURE);
     }
+    status = SE_version_get_info(poolinfo->connection, data_params[2], version);
 
-    /* Get the layer extent and hang it on the layerinfo */
-    status = SE_layerinfo_get_envelope(sde->layerinfo, &envelope);
     if(status != SE_SUCCESS) {
-        sde_error(status, 
-                "msSDELayerOpen()", 
-                "SE_layerinfo_get_envelope()");
+
+      if (status == SE_INVALID_RELEASE) {
+        /* The user has incongruent versions of SDE, ie 8.2 client and  */
+        /* 8.3 server set the state_id to SE_DEFAULT_STATE_ID, which means    */
+        /* no version queries are done */
+        sde->state_id = SE_DEFAULT_STATE_ID;
+      } else {
+        sde_error(  status,
+                    "msSDELayerOpen()",
+                    "SE_version_get_info()");
+        SE_versioninfo_free(version);
         return(MS_FAILURE);
+      }
+    } /* couldn't get version info */
+
+  } /* version was specified */
+
+  /* Get the STATEID from the given version and set the stream to  */
+  /* that if we didn't already set it to SE_DEFAULT_STATE_ID.   */
+  if (sde->state_id != SE_DEFAULT_STATE_ID) {
+    status = SE_versioninfo_get_state_id(version, &sde->state_id);
+    if(status != SE_SUCCESS) {
+      sde_error(  status,
+                  "msSDELayerOpen()",
+                  "SE_versioninfo_get_state_id()");
+      SE_versioninfo_free(version);
+      return(MS_FAILURE);
     }
-  
-    sde->extent->minx = envelope.minx;
-    sde->extent->miny = envelope.miny;
-    sde->extent->maxx = envelope.maxx;
-    sde->extent->maxy = envelope.maxy;
-
-    /* reset the stream */
-    status = SE_stream_close(poolinfo->stream, 1);
+
+    SE_versioninfo_free(version);
+    status = SE_stateinfo_create (&state);
     if(status != SE_SUCCESS) {
-        sde_error(status, "msSDELayerOpen()", "SE_stream_close()");
-        return(MS_FAILURE);
-    }  
+      sde_error(  status,
+                  "msSDELayerOpen()",
+                  "SE_stateinfo_create()");
+      return(MS_FAILURE);
+    }
+    status = SE_state_get_info( poolinfo->connection,
+                                sde->state_id,
+                                state);
+    if(status != SE_SUCCESS) {
+      sde_error(status, "msSDELayerOpen()", "SE_state_get_info()");
+      SE_stateinfo_free (state);
+      return(MS_FAILURE);
+    }
+    if (SE_stateinfo_is_open (state)) {
+      /* If the state is open for edits, we shouldn't be querying from it */
+      sde_error(  status,
+                  "msSDELayerOpen()",
+                  "SE_stateinfo_is_open() -- State for version is open");
+      SE_stateinfo_free (state);
+      return(MS_FAILURE);
+    }
+    SE_stateinfo_free (state);
+  } /* if (!(sde->state_id == SE_DEFAULT_STATE_ID)) */
 
-    /* Determine if we are big or little- endian for */
-    /* working with the encoding */
-    if( *((unsigned char *) &endian_test) == 1 )
-        sde->bBigEndian = MS_FALSE;
-    else
-        sde->bBigEndian = MS_TRUE;
 
-    /* point to the SDE layer information  */
-    /* (note this might actually be in another layer) */
-    layer->layerinfo = sde; 
-    sde->connPoolInfo = poolinfo;   
-    return(MS_SUCCESS);
-#else
-    msSetError(MS_MISCERR, "SDE support is not available.", "msSDELayerOpen()");
+  /* done with the DATA stuff now */
+  msFreeCharArray(data_params, numparams);
+
+  status = SE_layerinfo_create(NULL, &(sde->layerinfo));
+  if(status != SE_SUCCESS) {
+    sde_error(status, "msSDELayerOpen()", "SE_layerinfo_create()");
+    return(MS_FAILURE);
+  }
+
+
+  status = msSDEGetLayerInfo( layer,
+                              poolinfo->connection,
+                              sde->table,
+                              sde->column,
+                              layer->connection,
+                              sde->layerinfo);
+
+  if(status != MS_SUCCESS) {
+    sde_error(status, "msSDELayerOpen()", "msSDEGetLayerInfo()");
     return(MS_FAILURE);
+  }
+
+  status = SE_coordref_create(&(sde->coordref));
+  if(status != SE_SUCCESS) {
+    sde_error(status, "msSDELayerOpen()", "SE_coordref_create()");
+    return(MS_FAILURE);
+  }
+
+  status = SE_layerinfo_get_coordref(sde->layerinfo, sde->coordref);
+  if(status != SE_SUCCESS) {
+    sde_error(status, "msSDELayerOpen()", "SE_layerinfo_get_coordref()");
+    return(MS_FAILURE);
+  }
+
+  /* Get the layer extent and hang it on the layerinfo */
+  status = SE_layerinfo_get_envelope(sde->layerinfo, &envelope);
+  if(status != SE_SUCCESS) {
+    sde_error(status,
+              "msSDELayerOpen()",
+              "SE_layerinfo_get_envelope()");
+    return(MS_FAILURE);
+  }
+
+  sde->extent->minx = envelope.minx;
+  sde->extent->miny = envelope.miny;
+  sde->extent->maxx = envelope.maxx;
+  sde->extent->maxy = envelope.maxy;
+
+  /* reset the stream */
+  status = SE_stream_close(poolinfo->stream, 1);
+  if(status != SE_SUCCESS) {
+    sde_error(status, "msSDELayerOpen()", "SE_stream_close()");
+    return(MS_FAILURE);
+  }
+
+  /* Determine if we are big or little- endian for */
+  /* working with the encoding */
+  if( *((unsigned char *) &endian_test) == 1 )
+    sde->bBigEndian = MS_FALSE;
+  else
+    sde->bBigEndian = MS_TRUE;
+
+  /* point to the SDE layer information  */
+  /* (note this might actually be in another layer) */
+  layer->layerinfo = sde;
+  sde->connPoolInfo = poolinfo;
+  return(MS_SUCCESS);
+#else
+  msSetError(MS_MISCERR, "SDE support is not available.", "msSDELayerOpen()");
+  return(MS_FAILURE);
 #endif
 }
 
@@ -1387,35 +1394,41 @@ int msSDELayerOpen(layerObj *layer) {
 /*     Closes the MapServer layer.  This doesn't necessarily close the  */
 /*     connection to the layer.                                         */
 /* -------------------------------------------------------------------- */
-int  msSDELayerClose(layerObj *layer) {
+int  msSDELayerClose(layerObj *layer)
+{
 #ifdef USE_SDE
-    msSDELayerInfo *sde=NULL;
-    sde = layer->layerinfo;
-    
-    /* Silently return if layer not opened. */
-    if (!msSDELayerIsOpen(layer)) return MS_SUCCESS;  
-    
-    if(layer->debug) 
-       msDebug("msSDELayerClose(): Closing layer %s.\n", layer->name);
-    
-    if (sde->layerinfo) SE_layerinfo_free(sde->layerinfo);
-    if (sde->coordref) SE_coordref_free(sde->coordref);
-    if (sde->table) msFree(sde->table);
-    if (sde->column) msFree(sde->column);
-    if (sde->row_id_column) msFree(sde->row_id_column);
-    if (sde->join_table) msFree(sde->join_table);
-    if (sde->extent) msFree(sde->extent);
-    if (sde->nBaseColumns) msFree(sde->nBaseColumns);
-    if (sde->nJoinColumns) msFree(sde->nJoinColumns);
-
-    msConnPoolRelease( layer, sde->connPoolInfo );  
-    if (layer->layerinfo) msFree(layer->layerinfo);
-    layer->layerinfo = NULL;
-    return MS_SUCCESS;
- 
+
+
+  msSDELayerInfo *sde=NULL;
+
+  sde = layer->layerinfo;
+
+  /* Silently return if layer not opened. */
+  if (!msSDELayerIsOpen(layer)) return MS_SUCCESS;
+
+  if(layer->debug)
+    msDebug("msSDELayerClose(): Closing layer %s.\n", layer->name);
+
+  if (sde->layerinfo) SE_layerinfo_free(sde->layerinfo);
+  if (sde->coordref) SE_coordref_free(sde->coordref);
+  if (sde->table) msFree(sde->table);
+  if (sde->column) msFree(sde->column);
+  if (sde->row_id_column) msFree(sde->row_id_column);
+  if (sde->join_table) msFree(sde->join_table);
+  if (sde->extent) msFree(sde->extent);
+  if (sde->nBaseColumns) msFree(sde->nBaseColumns);
+  if (sde->nJoinColumns) msFree(sde->nJoinColumns);
+
+  msConnPoolRelease( layer, sde->connPoolInfo );
+  if (layer->layerinfo) msFree(layer->layerinfo);
+  layer->layerinfo = NULL;
+  return MS_SUCCESS;
+
 #else
-    msSetError( MS_MISCERR, "SDE support is not available.", "msSDELayerClose()");
-    return(MS_FALSE);
+  msSetError( MS_MISCERR,
+              "SDE support is not available.",
+              "msSDELayerClose()");
+  return(MS_FALSE);
 #endif
 }
 
@@ -1425,20 +1438,20 @@ int  msSDELayerClose(layerObj *layer) {
 /* -------------------------------------------------------------------- */
 /* Virtual table function                                               */
 /* -------------------------------------------------------------------- */
-int msSDELayerCloseConnection(layerObj *layer) 
+int msSDELayerCloseConnection(layerObj *layer)
 {
-	
+
 
 #ifdef USE_SDE
 
 
   msSDELayerInfo *sde=NULL;
 
-    if(!msSDELayerIsOpen(layer)) {
-        return MS_SUCCESS;  /* already closed */
-    }
+  if(!msSDELayerIsOpen(layer)) {
+    return MS_SUCCESS;  /* already closed */
+  }
 
-    sde = layer->layerinfo;
+  sde = layer->layerinfo;
 
   if(layer->debug)
     msDebug("msSDELayerCloseConnection(): Closing connection for layer %s.\n", layer->name);
@@ -1453,7 +1466,7 @@ int msSDELayerCloseConnection(layerObj *layer)
   return MS_FAILURE;
 #endif
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 
@@ -1463,179 +1476,180 @@ int msSDELayerCloseConnection(layerObj *layer)
 /*     starts a stream query using spatial filter.  Also limits the     */
 /*     query by the layer's FILTER item as well.                        */
 /* -------------------------------------------------------------------- */
-int msSDELayerWhichShapes(layerObj *layer, rectObj rect, int isQuery) {
+int msSDELayerWhichShapes(layerObj *layer, rectObj rect, int isQuery)
+{
 #ifdef USE_SDE
-    long status;
-    SE_ENVELOPE envelope;
-    SE_SHAPE shape=0;
-    SE_FILTER constraint;
-    SE_QUERYINFO query_info = NULL;
-    SE_SQL_CONSTRUCT* sql = NULL;
-    char* proc_value=NULL;
-    int query_order=SE_SPATIAL_FIRST;
-
-    msSDELayerInfo *sde=NULL;
-    
-    if(!msSDELayerIsOpen(layer)) {
-        msSetError( MS_SDEERR, 
-                    "SDE layer has not been opened.", 
-                    "msSDELayerWhichShapes()");
-        return(MS_FAILURE);
-    }
+  long status;
+  SE_ENVELOPE envelope;
+  SE_SHAPE shape=0;
+  SE_FILTER constraint;
+  SE_QUERYINFO query_info = NULL;
+  SE_SQL_CONSTRUCT* sql = NULL;
+  char* proc_value=NULL;
+  int query_order=SE_SPATIAL_FIRST;
 
-    sde = layer->layerinfo;
-
-    /* use the cached layer's extent. */
-    /* there is NO overlap, return MS_DONE */
-    /* (FIX: use this in ALL which shapes functions) */
-    if(sde->extent->minx > rect.maxx) return(MS_DONE); 
-    if(sde->extent->maxx < rect.minx) return(MS_DONE);
-    if(sde->extent->miny > rect.maxy) return(MS_DONE);
-    if(sde->extent->maxy < rect.miny) return(MS_DONE);
-
-    /* set spatial constraint search shape */
-    /* crop against SDE layer extent *argh* */
-    envelope.minx = MS_MAX(rect.minx, sde->extent->minx); 
-    envelope.miny = MS_MAX(rect.miny, sde->extent->miny);
-    envelope.maxx = MS_MIN(rect.maxx, sde->extent->maxx);
-    envelope.maxy = MS_MIN(rect.maxy, sde->extent->maxy);
-  
-    if( envelope.minx == envelope.maxx && envelope.miny == envelope.maxy){
-        /* fudge a rectangle so we have a valid one for generate_rectangle */
-        /* FIXME: use the real shape for the query and set the filter_type 
-           to be an appropriate type */
-        envelope.minx = envelope.minx - 0.001;
-        envelope.maxx = envelope.maxx + 0.001;
-        envelope.miny = envelope.miny - 0.001;
-        envelope.maxy = envelope.maxy + 0.001;
-    }
+  msSDELayerInfo *sde=NULL;
 
-    status = SE_shape_create(sde->coordref, &shape);
-    if(status != SE_SUCCESS) {
-        sde_error(  status, 
-                    "msSDELayerWhichShapes()", 
-                    "SE_shape_create()");
-        return(MS_FAILURE);
-    }
-    
-    status = SE_shape_generate_rectangle(&envelope, shape);
-    if(status != SE_SUCCESS) {
-        sde_error(  status, 
-                "msSDELayerWhichShapes()", 
+  if(!msSDELayerIsOpen(layer)) {
+    msSetError( MS_SDEERR,
+                "SDE layer has not been opened.",
+                "msSDELayerWhichShapes()");
+    return(MS_FAILURE);
+  }
+
+  sde = layer->layerinfo;
+
+  /* use the cached layer's extent. */
+  /* there is NO overlap, return MS_DONE */
+  /* (FIX: use this in ALL which shapes functions) */
+  if(sde->extent->minx > rect.maxx) return(MS_DONE);
+  if(sde->extent->maxx < rect.minx) return(MS_DONE);
+  if(sde->extent->miny > rect.maxy) return(MS_DONE);
+  if(sde->extent->maxy < rect.miny) return(MS_DONE);
+
+  /* set spatial constraint search shape */
+  /* crop against SDE layer extent *argh* */
+  envelope.minx = MS_MAX(rect.minx, sde->extent->minx);
+  envelope.miny = MS_MAX(rect.miny, sde->extent->miny);
+  envelope.maxx = MS_MIN(rect.maxx, sde->extent->maxx);
+  envelope.maxy = MS_MIN(rect.maxy, sde->extent->maxy);
+
+  if( envelope.minx == envelope.maxx && envelope.miny == envelope.maxy) {
+    /* fudge a rectangle so we have a valid one for generate_rectangle */
+    /* FIXME: use the real shape for the query and set the filter_type
+       to be an appropriate type */
+    envelope.minx = envelope.minx - 0.001;
+    envelope.maxx = envelope.maxx + 0.001;
+    envelope.miny = envelope.miny - 0.001;
+    envelope.maxy = envelope.maxy + 0.001;
+  }
+
+  status = SE_shape_create(sde->coordref, &shape);
+  if(status != SE_SUCCESS) {
+    sde_error(  status,
+                "msSDELayerWhichShapes()",
+                "SE_shape_create()");
+    return(MS_FAILURE);
+  }
+
+  status = SE_shape_generate_rectangle(&envelope, shape);
+  if(status != SE_SUCCESS) {
+    sde_error(  status,
+                "msSDELayerWhichShapes()",
                 "SE_shape_generate_rectangle()");
-        return(MS_FAILURE);
-    }
-    constraint.filter.shape = shape;
-
-    /* set spatial constraint column and table */
-    strcpy(constraint.table, sde->table);
-    strcpy(constraint.column, sde->column);
-
-    /* set a couple of other spatial constraint properties */
-    constraint.method = SM_ENVP;
-    constraint.filter_type = SE_SHAPE_FILTER;
-    constraint.truth = TRUE;
-  
-    if (!sde->join_table) {
-        query_info = getSDEQueryInfo(layer);
-        if (!query_info) {
-            sde_error(  status, 
-                        "msSDELayerWhichShapes()", 
-                        "getSDEQueryInfo()");
-            return(MS_FAILURE);
-        }
-    } else {
-        if (!layer->filter.string) {
-            sde_error(  -51, 
-                        "msSDELayerWhichShapes()", 
-                        "A join table is specified, but no FILTER is"
-                        " defined that joins the two tables together");
-            return(MS_FAILURE);
-        }
-        sql = getSDESQLConstructInfo(layer, NULL);
-    }    
-        
-    /* reset the stream */
-    status = SE_stream_close(sde->connPoolInfo->stream, 1);
+    return(MS_FAILURE);
+  }
+  constraint.filter.shape = shape;
+
+  /* set spatial constraint column and table */
+  strcpy(constraint.table, sde->table);
+  strcpy(constraint.column, sde->column);
+
+  /* set a couple of other spatial constraint properties */
+  constraint.method = SM_ENVP;
+  constraint.filter_type = SE_SHAPE_FILTER;
+  constraint.truth = TRUE;
+
+  if (!sde->join_table) {
+    query_info = getSDEQueryInfo(layer);
+    if (!query_info) {
+      sde_error(  status,
+                  "msSDELayerWhichShapes()",
+                  "getSDEQueryInfo()");
+      return(MS_FAILURE);
+    }
+  } else {
+    if (!layer->filter.string) {
+      sde_error(  -51,
+                  "msSDELayerWhichShapes()",
+                  "A join table is specified, but no FILTER is"
+                  " defined that joins the two tables together");
+      return(MS_FAILURE);
+    }
+    sql = getSDESQLConstructInfo(layer, NULL);
+  }
+
+  /* reset the stream */
+  status = SE_stream_close(sde->connPoolInfo->stream, 1);
+  if(status != SE_SUCCESS) {
+    sde_error(  status,
+                "msSDELayerWhichShapes()",
+                "SE_stream_close()");
+    return(MS_FAILURE);
+  }
+  /* Set the stream state back to the state_id of our user-specified version */
+  /* This must be done every time after the stream is reset before the  */
+  /* query happens. */
+
+  if (sde->state_id != SE_DEFAULT_STATE_ID) {
+
+    status =  SE_stream_set_state(sde->connPoolInfo->stream,
+                                  sde->state_id,
+                                  sde->state_id,
+                                  SE_STATE_DIFF_NOCHECK);
     if(status != SE_SUCCESS) {
-        sde_error(  status, 
-                    "msSDELayerWhichShapes()", 
-                    "SE_stream_close()");
-        return(MS_FAILURE);
+      sde_error(  status,
+                  "msSDELayerOpen()",
+                  "SE_stream_set_state()");
+      return(MS_FAILURE);
     }
-    /* Set the stream state back to the state_id of our user-specified version */
-    /* This must be done every time after the stream is reset before the  */
-    /* query happens. */
-
-    if (sde->state_id != SE_DEFAULT_STATE_ID){
-
-        status =  SE_stream_set_state(sde->connPoolInfo->stream, 
-                                      sde->state_id, 
-                                      sde->state_id, 
-                                      SE_STATE_DIFF_NOCHECK); 
-        if(status != SE_SUCCESS) {
-            sde_error(  status, 
-                        "msSDELayerOpen()", 
-                        "SE_stream_set_state()");
-            return(MS_FAILURE);
-        }  
-    } 
-
-    if (!sql) {
-        status = SE_stream_query_with_info(sde->connPoolInfo->stream, query_info);
-        if(status != SE_SUCCESS) {
-            sde_error(status, 
-                      "msSDELayerWhichShapes()", 
-                      "SE_stream_query_with_info()");
-            return(MS_FAILURE);
-        }
-    } else {
-        status = SE_stream_query(sde->connPoolInfo->stream, layer->numitems, (const CHAR**) layer->items, sql);
-        if(status != SE_SUCCESS) {
-            sde_error(status, 
-                      "msSDELayerWhichShapes()", 
-                      "SE_stream_query()");
-            return(MS_FAILURE);
-        }
-        /* Free up the sql now that we've queried */
-        SE_sql_construct_free(sql);
-    }  
-    proc_value = msLayerGetProcessingKey(layer,"QUERYORDER");
-    if(proc_value && strcasecmp(proc_value, "ATTRIBUTE") == 0)
-        query_order = SE_ATTRIBUTE_FIRST;
-
-    status = SE_stream_set_spatial_constraints( sde->connPoolInfo->stream, 
-                                                query_order, 
-                                                FALSE, 
-                                                1, 
-                                                &constraint);
+  }
 
+  if (!sql) {
+    status = SE_stream_query_with_info(sde->connPoolInfo->stream, query_info);
     if(status != SE_SUCCESS) {
-        sde_error(  status, 
-                    "msSDELayerWhichShapes()", 
-                    "SE_stream_set_spatial_constraints()");
-        return(MS_FAILURE);
+      sde_error(status,
+                "msSDELayerWhichShapes()",
+                "SE_stream_query_with_info()");
+      return(MS_FAILURE);
     }
-  
-    /* *should* be ready to step through shapes now */
-    status = SE_stream_execute(sde->connPoolInfo->stream); 
+  } else {
+    status = SE_stream_query(sde->connPoolInfo->stream, layer->numitems, (const CHAR**) layer->items, sql);
     if(status != SE_SUCCESS) {
-        sde_error(  status, 
-                    "msSDELayerWhichShapes()", 
-                    "SE_stream_execute()");
-        return(MS_FAILURE);
+      sde_error(status,
+                "msSDELayerWhichShapes()",
+                "SE_stream_query()");
+      return(MS_FAILURE);
     }
+    /* Free up the sql now that we've queried */
+    SE_sql_construct_free(sql);
+  }
+  proc_value = msLayerGetProcessingKey(layer,"QUERYORDER");
+  if(proc_value && strcasecmp(proc_value, "ATTRIBUTE") == 0)
+    query_order = SE_ATTRIBUTE_FIRST;
+
+  status = SE_stream_set_spatial_constraints( sde->connPoolInfo->stream,
+           query_order,
+           FALSE,
+           1,
+           &constraint);
+
+  if(status != SE_SUCCESS) {
+    sde_error(  status,
+                "msSDELayerWhichShapes()",
+                "SE_stream_set_spatial_constraints()");
+    return(MS_FAILURE);
+  }
 
-    /* clean-up */
-    SE_shape_free(shape);
-    SE_queryinfo_free (query_info);
-  
-    return(MS_SUCCESS);
+  /* *should* be ready to step through shapes now */
+  status = SE_stream_execute(sde->connPoolInfo->stream);
+  if(status != SE_SUCCESS) {
+    sde_error(  status,
+                "msSDELayerWhichShapes()",
+                "SE_stream_execute()");
+    return(MS_FAILURE);
+  }
+
+  /* clean-up */
+  SE_shape_free(shape);
+  SE_queryinfo_free (query_info);
+
+  return(MS_SUCCESS);
 #else
-    msSetError(MS_MISCERR, 
-             "SDE support is not available.", 
+  msSetError(MS_MISCERR,
+             "SDE support is not available.",
              "msSDELayerWhichShapes()");
-    return(MS_FAILURE);
+  return(MS_FAILURE);
 #endif
 }
 
@@ -1644,48 +1658,49 @@ int msSDELayerWhichShapes(layerObj *layer, rectObj rect, int isQuery) {
 /* -------------------------------------------------------------------- */
 /*     Recursively gets the shapes for the SDE layer                    */
 /* -------------------------------------------------------------------- */
-int msSDELayerNextShape(layerObj *layer, shapeObj *shape) {
+int msSDELayerNextShape(layerObj *layer, shapeObj *shape)
+{
 #ifdef USE_SDE
-    long status;
-    
-    msSDELayerInfo *sde=NULL;
-
-    if(!msSDELayerIsOpen(layer)) {
-        msSetError( MS_SDEERR, 
-                    "SDE layer has not been opened.", 
-                    "msSDELayerNextShape()");
-        return(MS_FAILURE);
-    }
+  long status;
 
-    sde = layer->layerinfo;
-    
-    /* fetch the next record from the stream */
-    status = SE_stream_fetch(sde->connPoolInfo->stream);
+  msSDELayerInfo *sde=NULL;
 
-    if(status == SE_FINISHED)
-        return(MS_DONE);
-    else if(status != MS_SUCCESS) {
-        sde_error(  status, 
-                    "msSDELayerNextShape()", 
-                    "SE_stream_fetch()");
-        return(MS_FAILURE);
-    }
+  if(!msSDELayerIsOpen(layer)) {
+    msSetError( MS_SDEERR,
+                "SDE layer has not been opened.",
+                "msSDELayerNextShape()");
+    return(MS_FAILURE);
+  }
 
-    /* get the shape and values (first column is the shape id,  */
-    /* second is the shape itself) */
-    status = sdeGetRecord(layer, shape);
-    if(status != MS_SUCCESS)
-        return(MS_FAILURE); /* something went wrong fetching the record/shape */
+  sde = layer->layerinfo;
 
-    if(shape->numlines == 0) /* null shape, skip it */
-        return(msSDELayerNextShape(layer, shape));
+  /* fetch the next record from the stream */
+  status = SE_stream_fetch(sde->connPoolInfo->stream);
 
-    return(MS_SUCCESS);
-#else
-    msSetError( MS_MISCERR, 
-                "SDE support is not available.", 
-                "msSDELayerNextShape()");
+  if(status == SE_FINISHED)
+    return(MS_DONE);
+  else if(status != MS_SUCCESS) {
+    sde_error(  status,
+                "msSDELayerNextShape()",
+                "SE_stream_fetch()");
     return(MS_FAILURE);
+  }
+
+  /* get the shape and values (first column is the shape id,  */
+  /* second is the shape itself) */
+  status = sdeGetRecord(layer, shape);
+  if(status != MS_SUCCESS)
+    return(MS_FAILURE); /* something went wrong fetching the record/shape */
+
+  if(shape->numlines == 0) /* null shape, skip it */
+    return(msSDELayerNextShape(layer, shape));
+
+  return(MS_SUCCESS);
+#else
+  msSetError( MS_MISCERR,
+              "SDE support is not available.",
+              "msSDELayerNextShape()");
+  return(MS_FAILURE);
 #endif
 }
 
@@ -1694,32 +1709,33 @@ int msSDELayerNextShape(layerObj *layer, shapeObj *shape) {
 /* -------------------------------------------------------------------- */
 /*     Returns the extent of the SDE layer                              */
 /* -------------------------------------------------------------------- */
-int msSDELayerGetExtent(layerObj *layer, rectObj *extent) {
+int msSDELayerGetExtent(layerObj *layer, rectObj *extent)
+{
 #ifdef USE_SDE
 
-    msSDELayerInfo *sde = NULL;
+  msSDELayerInfo *sde = NULL;
 
-    if(!msSDELayerIsOpen(layer)) {
-        msSetError( MS_SDEERR, 
-                    "SDE layer has not been opened.", 
-                    "msSDELayerGetExtent()");
-        return(MS_FAILURE);
-    }
+  if(!msSDELayerIsOpen(layer)) {
+    msSetError( MS_SDEERR,
+                "SDE layer has not been opened.",
+                "msSDELayerGetExtent()");
+    return(MS_FAILURE);
+  }
+
+  sde = layer->layerinfo;
 
-    sde = layer->layerinfo;
-    
-    /* copy our cached extent members into the caller's extent */
-    extent->minx = sde->extent->minx;
-    extent->miny = sde->extent->miny;
-    extent->maxx = sde->extent->maxx;
-    extent->maxy = sde->extent->maxy;
+  /* copy our cached extent members into the caller's extent */
+  extent->minx = sde->extent->minx;
+  extent->miny = sde->extent->miny;
+  extent->maxx = sde->extent->maxx;
+  extent->maxy = sde->extent->maxy;
 
-    return(MS_SUCCESS);
+  return(MS_SUCCESS);
 #else
-    msSetError( MS_MISCERR, 
-                "SDE support is not available.", 
-                "msSDELayerGetExtent()");
-    return(MS_FAILURE);
+  msSetError( MS_MISCERR,
+              "SDE support is not available.",
+              "msSDELayerGetExtent()");
+  return(MS_FAILURE);
 #endif
 }
 
@@ -1729,102 +1745,103 @@ int msSDELayerGetExtent(layerObj *layer, rectObj *extent) {
 /*     Queries SDE for a shape (and its attributes, if requested)       */
 /*     given the ID (which is the MS_SDE_ROW_ID_COLUMN column           */
 /* -------------------------------------------------------------------- */
-int msSDELayerGetShape(layerObj *layer, shapeObj *shape, resultObj *record) {
+int msSDELayerGetShape(layerObj *layer, shapeObj *shape, resultObj *record)
+{
 #ifdef USE_SDE
-    long status;
+  long status;
+
+  SE_SQL_CONSTRUCT* sql;
 
-    SE_SQL_CONSTRUCT* sql;
+  msSDELayerInfo *sde=NULL;
 
-    msSDELayerInfo *sde=NULL;
-  
-    long shapeindex = record->shapeindex;
+  long shapeindex = record->shapeindex;
 
-    if(!msSDELayerIsOpen(layer)) {
-        msSetError( MS_SDEERR, 
-                    "SDE layer has not been opened.", 
-                    "msSDELayerGetShape()");
-        return(MS_FAILURE);
-    }
+  if(!msSDELayerIsOpen(layer)) {
+    msSetError( MS_SDEERR,
+                "SDE layer has not been opened.",
+                "msSDELayerGetShape()");
+    return(MS_FAILURE);
+  }
 
-    sde = layer->layerinfo;
+  sde = layer->layerinfo;
 
-    /* must be at least one thing to retrieve (i.e. spatial column) */
-    if(layer->numitems < 1) { 
-        msSetError( MS_MISCERR, 
-                    "No items requested, SDE requires at least one item.", 
-                    "msSDELayerGetShape()");
-        return(MS_FAILURE);
-    }
+  /* must be at least one thing to retrieve (i.e. spatial column) */
+  if(layer->numitems < 1) {
+    msSetError( MS_MISCERR,
+                "No items requested, SDE requires at least one item.",
+                "msSDELayerGetShape()");
+    return(MS_FAILURE);
+  }
+
+  /* reset the stream */
+  status = SE_stream_close(sde->connPoolInfo->stream, 1);
+  if(status != SE_SUCCESS) {
+    sde_error(  status,
+                "msSDELayerGetShape()",
+                "SE_stream_close()");
+    return(MS_FAILURE);
+  }
+
+  if (!sde->join_table) {
+
+    status = SE_stream_fetch_row(   sde->connPoolInfo->stream,
+                                    sde->table,
+                                    shapeindex,
+                                    (short)(layer->numitems),
+                                    (const char **)layer->items);
 
-    /* reset the stream */
-    status = SE_stream_close(sde->connPoolInfo->stream, 1);
     if(status != SE_SUCCESS) {
-        sde_error(  status, 
-                    "msSDELayerGetShape()", 
-                    "SE_stream_close()");
-        return(MS_FAILURE);
+      sde_error(  status,
+                  "msSDELayerGetShape()",
+                  "SE_stream_fetch_row()");
+      return(MS_FAILURE);
     }
+  } else {
+    sql = getSDESQLConstructInfo(layer, &shapeindex);
 
-    if (!sde->join_table) {
+    status = SE_stream_query(sde->connPoolInfo->stream, layer->numitems, (const CHAR**) layer->items, sql);
+    ;
+    if(status != SE_SUCCESS) {
+      sde_error(status,
+                "msSDELayerWhichShapes()",
+                "SE_stream_query()");
+      return(MS_FAILURE);
+    }
 
-        status = SE_stream_fetch_row(   sde->connPoolInfo->stream, 
-                                        sde->table, 
-                                        shapeindex, 
-                                        (short)(layer->numitems), 
-                                        (const char **)layer->items);
+    /* Free up the sql now that we've queried */
+    SE_sql_construct_free(sql);
 
-        if(status != SE_SUCCESS) {
-            sde_error(  status, 
-                        "msSDELayerGetShape()", 
-                        "SE_stream_fetch_row()");
-            return(MS_FAILURE);
-        }
-    } else {
-        sql = getSDESQLConstructInfo(layer, &shapeindex);
-
-        status = SE_stream_query(sde->connPoolInfo->stream, layer->numitems, (const CHAR**) layer->items, sql);
-;
-        if(status != SE_SUCCESS) {
-            sde_error(status, 
-                      "msSDELayerWhichShapes()", 
-                      "SE_stream_query()");
-            return(MS_FAILURE);
-        }
-        
-        /* Free up the sql now that we've queried */
-        SE_sql_construct_free(sql);
-  
-        /* *should* be ready to step through shapes now */
-        status = SE_stream_execute(sde->connPoolInfo->stream);  
-
-        if(status != SE_SUCCESS) {
-            sde_error(status, 
-                      "SE_stream_execute()", 
-                      "SE_stream_execute()");
-            return(MS_FAILURE);
-        } 
-           
-        /* fetch the next record from the stream */
-        status = SE_stream_fetch(sde->connPoolInfo->stream);
+    /* *should* be ready to step through shapes now */
+    status = SE_stream_execute(sde->connPoolInfo->stream);
 
+    if(status != SE_SUCCESS) {
+      sde_error(status,
+                "SE_stream_execute()",
+                "SE_stream_execute()");
+      return(MS_FAILURE);
     }
-    status = sdeGetRecord(layer, shape);
-    if(status != MS_SUCCESS)
-        return(MS_FAILURE); /* something went wrong fetching the record/shape */
 
-    return(MS_SUCCESS);
+    /* fetch the next record from the stream */
+    status = SE_stream_fetch(sde->connPoolInfo->stream);
+
+  }
+  status = sdeGetRecord(layer, shape);
+  if(status != MS_SUCCESS)
+    return(MS_FAILURE); /* something went wrong fetching the record/shape */
+
+  return(MS_SUCCESS);
 #else
-    msSetError( MS_MISCERR,  
-                "SDE support is not available.", 
-                "msSDELayerGetShape()");
-    return(MS_FAILURE);
+  msSetError( MS_MISCERR,
+              "SDE support is not available.",
+              "msSDELayerGetShape()");
+  return(MS_FAILURE);
 #endif
 }
 
 /* -------------------------------------------------------------------- */
 /* msSDELayerGetSpatialColumn                                           */
 /* -------------------------------------------------------------------- */
-/*     A helper function to return the spatial column for               */ 
+/*     A helper function to return the spatial column for               */
 /*     an opened SDE layer                                              */
 /*                                                                      */
 /*     The caller owns the string after it is returned.                 */
@@ -1832,24 +1849,24 @@ int msSDELayerGetShape(layerObj *layer, shapeObj *shape, resultObj *record) {
 char *msSDELayerGetSpatialColumn(layerObj *layer)
 {
 #ifdef USE_SDE
-  
-    msSDELayerInfo *sde=NULL;
-  
-    if(!msSDELayerIsOpen(layer)) {
-        msSetError( MS_SDEERR, 
-                    "SDE layer has not been opened.", 
-                    "msSDELayerGetSpatialColumn()");
-        return NULL;
-    }
 
-    sde = layer->layerinfo;
-  
-    return(msStrdup(sde->column));
-#else
-    msSetError( MS_MISCERR, 
-                "SDE support is not available.", 
+  msSDELayerInfo *sde=NULL;
+
+  if(!msSDELayerIsOpen(layer)) {
+    msSetError( MS_SDEERR,
+                "SDE layer has not been opened.",
                 "msSDELayerGetSpatialColumn()");
-    return(NULL);
+    return NULL;
+  }
+
+  sde = layer->layerinfo;
+
+  return(msStrdup(sde->column));
+#else
+  msSetError( MS_MISCERR,
+              "SDE support is not available.",
+              "msSDELayerGetSpatialColumn()");
+  return(NULL);
 #endif
 }
 /* -------------------------------------------------------------------- */
@@ -1865,181 +1882,180 @@ msSDELayerInitItemInfo(layerObj *layer)
 {
 #ifdef USE_SDE
 
-    int i,j;
-/*    short nBaseColumns, nJoinColumns; */
-    long status;
-short nbasecol, njoincol;
-    SE_COLUMN_DEF *all_itemdefs = NULL;
-
-    msSDELayerInfo *sde = NULL;
-/*    nBaseColumns = 0; */
-/*    nJoinColumns = 0; */
- 
-    char *proc_key = NULL;
-
-    if (!msSDELayerIsOpen(layer)) {
-        msSetError( MS_SDEERR,
-                    "SDE layer has not been opened.",
-                    "msSDELayerInitItemInfo()");
-        return(MS_FAILURE);
-    }
-    
-    sde = layer->layerinfo;
-    
-    /*
-    ** This insanity is because we keep around the number of 
-    ** columns we have along with the layer info.  If the total 
-    ** number of columns that we have doesn't match when we're 
-    ** called the second time around, we have to throw an error or
-    ** msWhichShape will add an item onto our layer->items list, which 
-    ** in turn doesn't match the layer->iteminfo list of SDE column definitions.
-    */
-
-    nbasecol =*(sde->nBaseColumns);
-    njoincol =*(sde->nJoinColumns);
-
-    /* Hop right out again if we've already gotten the layer->iteminfo */
-    if (layer->iteminfo && layer->items) {
-        if (layer->debug)
-            msDebug("Column information has already been gotten..." 
-                    " returning from msSDELayerInitItemInfo\n");
-        if (layer->numitems != ( nbasecol+ njoincol)) {
-           /* if someone has modified the size of the items list, 
-           ** it is because it didn't find a column name (and we have 
-           ** already given them all because we have iteminfo and items
-           ** If this is the case, we can't continue. */
+  int i,j;
+  /*    short nBaseColumns, nJoinColumns; */
+  long status;
+  short nbasecol, njoincol;
+  SE_COLUMN_DEF *all_itemdefs = NULL;
 
-            msSetError( MS_SDEERR,
-                        "A specified CLASSITEM, FILTERITEM, or expression key cannot be found",
-                        "msSDELayerInitItemInfo()");
-            return(MS_FAILURE);
-        }
-        return (MS_SUCCESS);  
-    }
+  msSDELayerInfo *sde = NULL;
+  /*    nBaseColumns = 0; */
+  /*    nJoinColumns = 0; */
+
+  char *proc_key = NULL;
+
+  if (!msSDELayerIsOpen(layer)) {
+    msSetError( MS_SDEERR,
+                "SDE layer has not been opened.",
+                "msSDELayerInitItemInfo()");
+    return(MS_FAILURE);
+  }
+
+  sde = layer->layerinfo;
+
+  /*
+  ** This insanity is because we keep around the number of
+  ** columns we have along with the layer info.  If the total
+  ** number of columns that we have doesn't match when we're
+  ** called the second time around, we have to throw an error or
+  ** msWhichShape will add an item onto our layer->items list, which
+  ** in turn doesn't match the layer->iteminfo list of SDE column definitions.
+  */
+
+  nbasecol =*(sde->nBaseColumns);
+  njoincol =*(sde->nJoinColumns);
+
+  /* Hop right out again if we've already gotten the layer->iteminfo */
+  if (layer->iteminfo && layer->items) {
     if (layer->debug)
-        msDebug("Getting all column information in msSDELayerInitItemInfo\n");
-
-    if (!(sde->row_id_column)) {
-        
-        sde->row_id_column = msSDELayerGetRowIDColumn(layer);   
-    } else {
-        /* Don't think this should happen.  If it does, it'd be good to know why. */
-        if (layer->debug)
-            msDebug ("RowID column has already been gotten... msSDELayerInitItemInfo\n");
+      msDebug("Column information has already been gotten..."
+              " returning from msSDELayerInitItemInfo\n");
+    if (layer->numitems != ( nbasecol+ njoincol)) {
+      /* if someone has modified the size of the items list,
+      ** it is because it didn't find a column name (and we have
+      ** already given them all because we have iteminfo and items
+      ** If this is the case, we can't continue. */
+
+      msSetError( MS_SDEERR,
+                  "A specified CLASSITEM, FILTERITEM, or expression key cannot be found",
+                  "msSDELayerInitItemInfo()");
+      return(MS_FAILURE);
     }
+    return (MS_SUCCESS);
+  }
+  if (layer->debug)
+    msDebug("Getting all column information in msSDELayerInitItemInfo\n");
+
+  if (!(sde->row_id_column)) {
+
+    sde->row_id_column = msSDELayerGetRowIDColumn(layer);
+  } else {
+    /* Don't think this should happen.  If it does, it'd be good to know why. */
+    if (layer->debug)
+      msDebug ("RowID column has already been gotten... msSDELayerInitItemInfo\n");
+  }
+
+  status = SE_table_describe( sde->connPoolInfo->connection,
+                              sde->table,
+                              (short*)&(nbasecol),
+                              &(sde->basedefs));
+  if(status != SE_SUCCESS) {
+    sde_error(  status,
+                "msSDELayerInitItemInfo()",
+                "SE_table_describe() (base table)");
+    return(MS_FAILURE);
+  }
+
+  if (sde->join_table) {
+    status = SE_table_describe( sde->connPoolInfo->connection,
+                                sde->join_table,
+                                (short*)&(njoincol),
+                                &(sde->joindefs));
 
-    status = SE_table_describe( sde->connPoolInfo->connection, 
-                                sde->table, 
-                                (short*)&(nbasecol),  
-                                &(sde->basedefs));
     if(status != SE_SUCCESS) {
-        sde_error(  status, 
-                    "msSDELayerInitItemInfo()", 
-                    "SE_table_describe() (base table)");
-        return(MS_FAILURE);
-    }
-        
-    if (sde->join_table) {
-        status = SE_table_describe( sde->connPoolInfo->connection, 
-                                    sde->join_table, 
-                                    (short*)&(njoincol),  
-                                    &(sde->joindefs));
-
-        if(status != SE_SUCCESS) {
-            sde_error(  status, 
-                        "msSDELayerInitItemInfo()", 
-                        "SE_table_describe() (join table).  Did you specify the name of the join table properly?");
-            return(MS_FAILURE);
-        }     
+      sde_error(  status,
+                  "msSDELayerInitItemInfo()",
+                  "SE_table_describe() (join table).  Did you specify the name of the join table properly?");
+      return(MS_FAILURE);
     }
+  }
 
-    layer->numitems = nbasecol + njoincol;
+  layer->numitems = nbasecol + njoincol;
 
-    /* combine the itemdefs of both tables into one */
-    all_itemdefs = (SE_COLUMN_DEF *) calloc( layer->numitems, sizeof(SE_COLUMN_DEF));
-    MS_CHECK_ALLOC(all_itemdefs, sizeof(SE_COLUMN_DEF), MS_FAILURE);
+  /* combine the itemdefs of both tables into one */
+  all_itemdefs = (SE_COLUMN_DEF *) calloc( layer->numitems, sizeof(SE_COLUMN_DEF));
+  MS_CHECK_ALLOC(all_itemdefs, sizeof(SE_COLUMN_DEF), MS_FAILURE);
 
-    for(i=0;i<nbasecol;i++) all_itemdefs[i] = sde->basedefs[i];
+  for(i=0; i<nbasecol; i++) all_itemdefs[i] = sde->basedefs[i];
 
-    if (njoincol > 0) {
-        for(i=0;i<njoincol;i++) {
-           all_itemdefs[i+nbasecol]=sde->joindefs[i];    
-        }
+  if (njoincol > 0) {
+    for(i=0; i<njoincol; i++) {
+      all_itemdefs[i+nbasecol]=sde->joindefs[i];
     }
+  }
 
-    if (!layer->iteminfo){
-        layer->iteminfo = (SE_COLUMN_DEF *) calloc( layer->numitems, sizeof(SE_COLUMN_DEF));
-        if(!layer->iteminfo) {
-            msSetError( MS_MEMERR, 
-                        "Error allocating SDE item  information.", 
-                        "msSDELayerInitItemInfo()");
-            free(all_itemdefs);
-            return(MS_FAILURE);
-        }
-    } else {
-        /* Don't think this should happen.  If it does, it'd be good to know why. */
+  if (!layer->iteminfo) {
+    layer->iteminfo = (SE_COLUMN_DEF *) calloc( layer->numitems, sizeof(SE_COLUMN_DEF));
+    if(!layer->iteminfo) {
+      msSetError( MS_MEMERR,
+                  "Error allocating SDE item  information.",
+                  "msSDELayerInitItemInfo()");
+      free(all_itemdefs);
+      return(MS_FAILURE);
+    }
+  } else {
+    /* Don't think this should happen.  If it does, it'd be good to know why. */
     if (layer->debug)
-        msDebug ("layer->iteminfo has already been initialized... msSDELayerInitItemInfo\n");
-    }
-    
-    if (!(layer->items)) {
-        /* gather up all of the column names and put them onto layer->items */
-        layer->items = (char **)malloc(layer->numitems*sizeof(char *)+10);
-        MS_CHECK_ALLOC(layer->items, layer->numitems*sizeof(char *)+10, MS_FAILURE);
-    } else {
-       msDebug("layer->items has already been initialized!!!");
-    }
+      msDebug ("layer->iteminfo has already been initialized... msSDELayerInitItemInfo\n");
+  }
 
-    proc_key = msLayerGetProcessingKey(layer,"ATTRIBUTE_QUALIFIED");
-    if (!sde->join_table && 
-        (proc_key == NULL ||  strcasecmp( proc_key, "TRUE") != 0)) {
-        for(i=0; i<layer->numitems; i++) layer->items[i] = msStrdup(all_itemdefs[i].column_name);
-        for(i=0; i<layer->numitems; i++) { /* requested columns */
-            for(j=0; j<layer->numitems; j++) { /* all columns */
-                if(strcasecmp(layer->items[i], all_itemdefs[j].column_name) == 0) {
-                    /* found it */
-                    ((SE_COLUMN_DEF *)(layer->iteminfo))[i] = all_itemdefs[j];
-                    break;
-                }
-            }
+  if (!(layer->items)) {
+    /* gather up all of the column names and put them onto layer->items */
+    layer->items = (char **)malloc(layer->numitems*sizeof(char *)+10);
+    MS_CHECK_ALLOC(layer->items, layer->numitems*sizeof(char *)+10, MS_FAILURE);
+  } else {
+    msDebug("layer->items has already been initialized!!!");
+  }
+
+  proc_key = msLayerGetProcessingKey(layer,"ATTRIBUTE_QUALIFIED");
+  if (!sde->join_table &&
+      (proc_key == NULL ||  strcasecmp( proc_key, "TRUE") != 0)) {
+    for(i=0; i<layer->numitems; i++) layer->items[i] = msStrdup(all_itemdefs[i].column_name);
+    for(i=0; i<layer->numitems; i++) { /* requested columns */
+      for(j=0; j<layer->numitems; j++) { /* all columns */
+        if(strcasecmp(layer->items[i], all_itemdefs[j].column_name) == 0) {
+          /* found it */
+          ((SE_COLUMN_DEF *)(layer->iteminfo))[i] = all_itemdefs[j];
+          break;
         }
+      }
     }
-    else {
-        for(i=0;i<nbasecol;i++) {
-            layer->items[i] = (char*) msSmallMalloc((SE_QUALIFIED_COLUMN_LEN+1)*sizeof (char));
-            layer->items[i][0] = '\0';
-            strcat(layer->items[i], sde->table);
-            strcat(layer->items[i], ".");
-            strcat(layer->items[i], all_itemdefs[i].column_name);
-            ((SE_COLUMN_DEF *)(layer->iteminfo))[i] = all_itemdefs[i];
+  } else {
+    for(i=0; i<nbasecol; i++) {
+      layer->items[i] = (char*) msSmallMalloc((SE_QUALIFIED_COLUMN_LEN+1)*sizeof (char));
+      layer->items[i][0] = '\0';
+      strcat(layer->items[i], sde->table);
+      strcat(layer->items[i], ".");
+      strcat(layer->items[i], all_itemdefs[i].column_name);
+      ((SE_COLUMN_DEF *)(layer->iteminfo))[i] = all_itemdefs[i];
 
-        }
-        for(i=nbasecol;i<layer->numitems;i++) {
-            layer->items[i] = (char*) msSmallMalloc((SE_QUALIFIED_COLUMN_LEN+1)*sizeof (char));
-            layer->items[i][0] = '\0';
-
-            strcat(layer->items[i], sde->join_table);
-            strcat(layer->items[i], ".");
-            strcat(layer->items[i], all_itemdefs[i].column_name);
-            ((SE_COLUMN_DEF *)(layer->iteminfo))[i] = all_itemdefs[i];
-  
-        }    
     }
-    /* Tell the user which columns we've gotten */
-    if (layer->debug)
-        for(i=0; i<layer->numitems; i++) 
-            msDebug("msSDELayerInitItemInfo(): getting info for %s\n", layer->items[i]);
-   
-    *(sde->nJoinColumns) = njoincol;
-    *(sde->nBaseColumns) = nbasecol; 
-    msFree(all_itemdefs);
-    return MS_SUCCESS;
+    for(i=nbasecol; i<layer->numitems; i++) {
+      layer->items[i] = (char*) msSmallMalloc((SE_QUALIFIED_COLUMN_LEN+1)*sizeof (char));
+      layer->items[i][0] = '\0';
+
+      strcat(layer->items[i], sde->join_table);
+      strcat(layer->items[i], ".");
+      strcat(layer->items[i], all_itemdefs[i].column_name);
+      ((SE_COLUMN_DEF *)(layer->iteminfo))[i] = all_itemdefs[i];
+
+    }
+  }
+  /* Tell the user which columns we've gotten */
+  if (layer->debug)
+    for(i=0; i<layer->numitems; i++)
+      msDebug("msSDELayerInitItemInfo(): getting info for %s\n", layer->items[i]);
+
+  *(sde->nJoinColumns) = njoincol;
+  *(sde->nBaseColumns) = nbasecol;
+  msFree(all_itemdefs);
+  return MS_SUCCESS;
 
 #else
-    msSetError( MS_MISCERR, 
-                "SDE support is not available.", 
-                "msSDELayerInitItemInfo()");
-    return(MS_FAILURE);
+  msSetError( MS_MISCERR,
+              "SDE support is not available.",
+              "msSDELayerInitItemInfo()");
+  return(MS_FAILURE);
 #endif
 }
 
@@ -2050,17 +2066,18 @@ short nbasecol, njoincol;
 /* -------------------------------------------------------------------- */
 /*     Inits the stuff we'll be querying from SDE                       */
 /* -------------------------------------------------------------------- */
-int msSDELayerCreateItems(layerObj *layer, int nt){    
-    int status;    
-    /* status = msSDELayerCreateItems(layer, 0);    */
-    status = msSDELayerInitItemInfo(layer);
-    if (status != MS_SUCCESS) {        
-        msSetError( MS_MISCERR,                    
-                    "Unable to create SDE column info",
-                    "msSDELayerCreateItemsInfo()");       
-        return(MS_FAILURE);    
-    }    
-    return (MS_SUCCESS);
+int msSDELayerCreateItems(layerObj *layer, int nt)
+{
+  int status;
+  /* status = msSDELayerCreateItems(layer, 0);    */
+  status = msSDELayerInitItemInfo(layer);
+  if (status != MS_SUCCESS) {
+    msSetError( MS_MISCERR,
+                "Unable to create SDE column info",
+                "msSDELayerCreateItemsInfo()");
+    return(MS_FAILURE);
+  }
+  return (MS_SUCCESS);
 }
 
 /* -------------------------------------------------------------------- */
@@ -2068,17 +2085,24 @@ int msSDELayerCreateItems(layerObj *layer, int nt){
 /* -------------------------------------------------------------------- */
 /*     Queries the SDE table's column names into layer->iteminfo        */
 /* -------------------------------------------------------------------- */
-int msSDELayerGetItems(layerObj *layer) {
+int msSDELayerGetItems(layerObj *layer)
+{
 #ifdef USE_SDE
   int status;
   status = msSDELayerInitItemInfo(layer);
+
   if (status != MS_SUCCESS) {
-    msSetError( MS_MISCERR, "Unable to create SDE column info", "msSDELayerGetItems()");
-    return(MS_FAILURE);     
-  }    
+    msSetError( MS_MISCERR,
+                "Unable to create SDE column info",
+                "msSDELayerGetItems()");
+    return(MS_FAILURE);
+  }
   return (MS_SUCCESS);
+
 #else
-  msSetError( MS_MISCERR, "SDE support is not available.", "msSDELayerGetItems()");
+  msSetError( MS_MISCERR,
+              "SDE support is not available.",
+              "msSDELayerGetItems()");
   return(MS_FAILURE);
 #endif
 }
@@ -2086,29 +2110,43 @@ int msSDELayerGetItems(layerObj *layer) {
 /* -------------------------------------------------------------------- */
 /* msSDELayerFreeItemInfo                                               */
 /* -------------------------------------------------------------------- */
-void msSDELayerFreeItemInfo(layerObj *layer) {
+void msSDELayerFreeItemInfo(layerObj *layer)
+{
 #ifdef USE_SDE
   msSDELayerInfo *sde = NULL;
-
+  int i;
+  if (!msSDELayerIsOpen(layer)) {
+    msSetError( MS_SDEERR,
+                "SDE layer has not been opened.",
+                "msSDELayerFreeItemInfo()");
+  }
   sde = layer->layerinfo;
-  if(sde) {
-    if (sde->basedefs) {
-      SE_table_free_descriptions(sde->basedefs);  
-      sde->basedefs = NULL;
-    }
-    if (sde->joindefs) {
-      SE_table_free_descriptions(sde->joindefs);
-      sde->joindefs = NULL;
-    }
+  if (sde->basedefs) {
+    SE_table_free_descriptions(sde->basedefs);
+    sde->basedefs = NULL;
+  }
+  if (sde->joindefs) {
+    SE_table_free_descriptions(sde->joindefs);
+    sde->joindefs = NULL;
   }
-
   if (layer->iteminfo) {
     msFree(layer->iteminfo);
     layer->iteminfo = NULL;
   }
+
+  if (layer->items) {
+    for (i=0; i< layer->numitems; i++) {
+      msFree(layer->items[i]);
+    }
+    msFree(layer->items);
+    layer->items = NULL;
+    layer->numitems = 0;
+  }
+
 #else
-  msSetError( MS_MISCERR, "SDE support is not available.", "msSDELayerFreeItemInfo()");
-  return;
+  msSetError( MS_MISCERR,
+              "SDE support is not available.",
+              "msSDELayerFreeItemInfo()");
 #endif
 }
 
@@ -2117,7 +2155,7 @@ MS_DLL_EXPORT  int
 PluginInitializeVirtualTable(layerVTableObj* vtable, layerObj *layer)
 {
   assert(layer != NULL);
-  assert(vtable != NULL);    
+  assert(vtable != NULL);
 
   vtable->LayerInitItemInfo = msSDELayerInitItemInfo;
   vtable->LayerFreeItemInfo = msSDELayerFreeItemInfo;
@@ -2147,27 +2185,27 @@ PluginInitializeVirtualTable(layerVTableObj* vtable, layerObj *layer)
 int
 msSDELayerInitializeVirtualTable(layerObj *layer)
 {
-    assert(layer != NULL);
-    assert(layer->vtable != NULL);
-
-    layer->vtable->LayerInitItemInfo = msSDELayerInitItemInfo;
-    layer->vtable->LayerFreeItemInfo = msSDELayerFreeItemInfo;
-    layer->vtable->LayerOpen = msSDELayerOpen;
-    layer->vtable->LayerIsOpen = msSDELayerIsOpen;
-    layer->vtable->LayerWhichShapes = msSDELayerWhichShapes;
-    layer->vtable->LayerNextShape = msSDELayerNextShape;
-    layer->vtable->LayerGetShape = msSDELayerGetShape;
-    layer->vtable->LayerClose = msSDELayerClose;
-    layer->vtable->LayerGetItems = msSDELayerGetItems;
-    layer->vtable->LayerGetExtent = msSDELayerGetExtent;
-    /* layer->vtable->LayerGetAutoStyle, use default */
-    /* layer->vtable->LayerApplyFilterToLayer, use default */
-    layer->vtable->LayerCloseConnection = msSDELayerCloseConnection; /* SDE uses pooled connections, close from msCloseConnections */
-    layer->vtable->LayerSetTimeFilter = msLayerMakePlainTimeFilter;
-    layer->vtable->LayerCreateItems = msSDELayerCreateItems;
-    /* layer->vtable->LayerGetNumFeatures, use default */
-
-    return MS_SUCCESS;
+  assert(layer != NULL);
+  assert(layer->vtable != NULL);
+
+  layer->vtable->LayerInitItemInfo = msSDELayerInitItemInfo;
+  layer->vtable->LayerFreeItemInfo = msSDELayerFreeItemInfo;
+  layer->vtable->LayerOpen = msSDELayerOpen;
+  layer->vtable->LayerIsOpen = msSDELayerIsOpen;
+  layer->vtable->LayerWhichShapes = msSDELayerWhichShapes;
+  layer->vtable->LayerNextShape = msSDELayerNextShape;
+  layer->vtable->LayerGetShape = msSDELayerGetShape;
+  layer->vtable->LayerClose = msSDELayerClose;
+  layer->vtable->LayerGetItems = msSDELayerGetItems;
+  layer->vtable->LayerGetExtent = msSDELayerGetExtent;
+  /* layer->vtable->LayerGetAutoStyle, use default */
+  /* layer->vtable->LayerApplyFilterToLayer, use default */
+  layer->vtable->LayerCloseConnection = msSDELayerCloseConnection; /* SDE uses pooled connections, close from msCloseConnections */
+  layer->vtable->LayerSetTimeFilter = msLayerMakePlainTimeFilter;
+  layer->vtable->LayerCreateItems = msSDELayerCreateItems;
+  /* layer->vtable->LayerGetNumFeatures, use default */
+
+  return MS_SUCCESS;
 }
 
 
diff --git a/mapsearch.c b/mapsearch.c
index b4abd19..a8e268c 100644
--- a/mapsearch.c
+++ b/mapsearch.c
@@ -8,7 +8,7 @@
  * Notes: For information on point in polygon function please see:
  *
  *   http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
- * 
+ *
  * The appropriate copyright notice accompanies the funtion definition.
  *
  ******************************************************************************
@@ -21,7 +21,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -35,7 +35,7 @@
 
 #include "mapserver.h"
 
-MS_CVSID("$Id$")
+
 
 #define LASTVERT(v,n)  ((v) == 0 ? n-2 : v-1)
 #define NEXTVERT(v,n)  ((v) == n-2 ? 0 : v+1)
@@ -55,24 +55,24 @@ int msRectOverlap(rectObj *a, rectObj *b)
 /*
 ** Computes the intersection of two rectangles, updating the first
 ** to be only the intersection of the two.  Returns MS_FALSE if
-** the intersection is empty. 
+** the intersection is empty.
 */
 int msRectIntersect( rectObj *a, const rectObj *b )
 {
-    if( a->maxx > b->maxx )
-        a->maxx = b->maxx;
-    if( a->minx < b->minx )
-        a->minx = b->minx;
-    if( a->maxy > b->maxy )
-        a->maxy = b->maxy;
-    if( a->miny < b->miny )
-        a->miny = b->miny;
-
-    if( a->maxx < a->minx || b->maxx < b->minx )
-        return MS_FALSE;
-    else 
-        return MS_TRUE;
-}        
+  if( a->maxx > b->maxx )
+    a->maxx = b->maxx;
+  if( a->minx < b->minx )
+    a->minx = b->minx;
+  if( a->maxy > b->maxy )
+    a->maxy = b->maxy;
+  if( a->miny < b->miny )
+    a->miny = b->miny;
+
+  if( a->maxx < a->minx || b->maxx < b->minx )
+    return MS_FALSE;
+  else
+    return MS_TRUE;
+}
 
 /*
 ** Returns MS_TRUE if rectangle a is contained in rectangle b
@@ -82,7 +82,7 @@ int msRectContained(rectObj *a, rectObj *b)
   if(a->minx >= b->minx && a->maxx <= b->maxx)
     if(a->miny >= b->miny && a->maxy <= b->maxy)
       return(MS_TRUE);
-  return(MS_FALSE);  
+  return(MS_FALSE);
 }
 
 /*
@@ -125,37 +125,36 @@ int msPolygonDirection(lineObj *c)
   lv = LASTVERT(v,c->numpoints);
   nv = NEXTVERT(v,c->numpoints);
 
-  area = c->point[lv].x*c->point[v].y - c->point[lv].y*c->point[v].x + c->point[lv].y*c->point[nv].x - c->point[lv].x*c->point[nv].y + c->point[v].x*c->point[nv].y - c->point[nv].x*c->point[v].y;   
+  area = c->point[lv].x*c->point[v].y - c->point[lv].y*c->point[v].x + c->point[lv].y*c->point[nv].x - c->point[lv].x*c->point[nv].y + c->point[v].x*c->point[nv].y - c->point[nv].x*c->point[v].y;
   if(area > 0)
-    return(1); /* counter clockwise orientation */ 
-  else 
-    if(area < 0) /* clockwise orientation */
-      return(-1);
-    else
-      return(0); /* shouldn't happen unless the polygon is self intersecting */
+    return(1); /* counter clockwise orientation */
+  else if(area < 0) /* clockwise orientation */
+    return(-1);
+  else
+    return(0); /* shouldn't happen unless the polygon is self intersecting */
 }
 
-/*                                                                                                                         
-** Copyright (c) 1970-2003, Wm. Randolph Franklin                                                                          
-**                                                                                                                         
-** Permission is hereby granted, free of charge, to any person obtaining a copy of this software and                       
-** associated documentation files (the "Software"), to deal in the Software without restriction, including                 
-** without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell                 
-** copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the                
-** following conditions:                                                                                                   
-**                                                                                                                         
-** 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the               
-**    following disclaimers.                                                                                               
-** 2. Redistributions in binary form must reproduce the above copyright notice in the documentation and/or                 
-**    other materials provided with the distribution.                                                                      
-** 3. The name of W. Randolph Franklin may not be used to endorse or promote products derived from this                    
-**    Software without specific prior written permission.                                                                  
-**                                                                                                                         
-** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT                   
-** LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN                  
-** NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,                    
-** WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE                     
-** SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                                                                  
+/*
+** Copyright (c) 1970-2003, Wm. Randolph Franklin
+**
+** Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
+** associated documentation files (the "Software"), to deal in the Software without restriction, including
+** without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+** copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
+** following conditions:
+**
+** 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the
+**    following disclaimers.
+** 2. Redistributions in binary form must reproduce the above copyright notice in the documentation and/or
+**    other materials provided with the distribution.
+** 3. The name of W. Randolph Franklin may not be used to endorse or promote products derived from this
+**    Software without specific prior written permission.
+**
+** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
+** LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+** NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+** WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+** SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
 int msPointInPolygon(pointObj *p, lineObj *c)
 {
@@ -174,25 +173,26 @@ int msPointInPolygon(pointObj *p, lineObj *c)
 ** cases. In due time... -SDL-
 */
 
-int msIntersectSegments(pointObj *a, pointObj *b, pointObj *c, pointObj *d) { /* from comp.graphics.alogorithms FAQ */
+int msIntersectSegments(pointObj *a, pointObj *b, pointObj *c, pointObj *d)   /* from comp.graphics.alogorithms FAQ */
+{
 
   double r, s;
   double denominator, numerator;
 
-  numerator = ((a->y-c->y)*(d->x-c->x) - (a->x-c->x)*(d->y-c->y));  
-  denominator = ((b->x-a->x)*(d->y-c->y) - (b->y-a->y)*(d->x-c->x));  
+  numerator = ((a->y-c->y)*(d->x-c->x) - (a->x-c->x)*(d->y-c->y));
+  denominator = ((b->x-a->x)*(d->y-c->y) - (b->y-a->y)*(d->x-c->x));
 
   if((denominator == 0) && (numerator == 0)) { /* lines are coincident, intersection is a line segement if it exists */
     if(a->y == c->y) { /* coincident horizontally, check x's */
       if(((a->x >= MS_MIN(c->x,d->x)) && (a->x <= MS_MAX(c->x,d->x))) || ((b->x >= MS_MIN(c->x,d->x)) && (b->x <= MS_MAX(c->x,d->x))))
-  return(MS_TRUE);
+        return(MS_TRUE);
       else
-  return(MS_FALSE);
+        return(MS_FALSE);
     } else { /* test for y's will work fine for remaining cases */
       if(((a->y >= MS_MIN(c->y,d->y)) && (a->y <= MS_MAX(c->y,d->y))) || ((b->y >= MS_MIN(c->y,d->y)) && (b->y <= MS_MAX(c->y,d->y))))
-  return(MS_TRUE);
+        return(MS_TRUE);
       else
-  return(MS_FALSE);
+        return(MS_FALSE);
     }
   }
 
@@ -218,7 +218,8 @@ int msIntersectSegments(pointObj *a, pointObj *b, pointObj *c, pointObj *d) { /*
 ** point falls in. If odd the point is in the polygon, if 0 or even
 ** then the point is in a hole or completely outside.
 */
-int msIntersectPointPolygon(pointObj *point, shapeObj *poly) {
+int msIntersectPointPolygon(pointObj *point, shapeObj *poly)
+{
   int i;
   int status=MS_FALSE;
 
@@ -227,10 +228,11 @@ int msIntersectPointPolygon(pointObj *point, shapeObj *poly) {
       status = !status;
   }
 
-  return(status);  
+  return(status);
 }
 
-int msIntersectMultipointPolygon(shapeObj *multipoint, shapeObj *poly) {
+int msIntersectMultipointPolygon(shapeObj *multipoint, shapeObj *poly)
+{
   int i,j;
 
   /* The change to loop through all the lines has been made for ticket
@@ -239,15 +241,16 @@ int msIntersectMultipointPolygon(shapeObj *multipoint, shapeObj *poly) {
   for(i=0; i<multipoint->numlines; i++ ) {
     lineObj points = multipoint->line[i];
     for(j=0; j<points.numpoints; j++) {
-          if(msIntersectPointPolygon(&(points.point[j]), poly) == MS_TRUE)
+      if(msIntersectPointPolygon(&(points.point[j]), poly) == MS_TRUE)
         return(MS_TRUE);
     }
   }
-    
+
   return(MS_FALSE);
 }
 
-int msIntersectPolylines(shapeObj *line1, shapeObj *line2) {
+int msIntersectPolylines(shapeObj *line1, shapeObj *line2)
+{
   int c1,v1,c2,v2;
 
   for(c1=0; c1<line1->numlines; c1++)
@@ -255,13 +258,14 @@ int msIntersectPolylines(shapeObj *line1, shapeObj *line2) {
       for(c2=0; c2<line2->numlines; c2++)
         for(v2=1; v2<line2->line[c2].numpoints; v2++)
           if(msIntersectSegments(&(line1->line[c1].point[v1-1]), &(line1->line[c1].point[v1]),
-              &(line2->line[c2].point[v2-1]), &(line2->line[c2].point[v2])) ==  MS_TRUE)
+                                 &(line2->line[c2].point[v2-1]), &(line2->line[c2].point[v2])) ==  MS_TRUE)
             return(MS_TRUE);
 
   return(MS_FALSE);
 }
 
-int msIntersectPolylinePolygon(shapeObj *line, shapeObj *poly) {
+int msIntersectPolylinePolygon(shapeObj *line, shapeObj *poly)
+{
   int i;
 
   /* STEP 1: polygon might competely contain the polyline or one of it's parts (only need to check one point from each part) */
@@ -277,7 +281,8 @@ int msIntersectPolylinePolygon(shapeObj *line, shapeObj *poly) {
   return(MS_FALSE);
 }
 
-int msIntersectPolygons(shapeObj *p1, shapeObj *p2) {
+int msIntersectPolygons(shapeObj *p1, shapeObj *p2)
+{
   int i;
 
   /* STEP 1: polygon 1 completely contains 2 (only need to check one point from each part) */
@@ -324,7 +329,7 @@ double msDistancePointToPoint(pointObj *a, pointObj *b)
 double msSquareDistancePointToPoint(pointObj *a, pointObj *b)
 {
   double dx, dy;
-  
+
   dx = a->x - b->x;
   dy = a->y - b->y;
 
@@ -333,7 +338,7 @@ double msSquareDistancePointToPoint(pointObj *a, pointObj *b)
 
 double msDistancePointToSegment(pointObj *p, pointObj *a, pointObj *b)
 {
-	return (sqrt(msSquareDistancePointToSegment(p, a, b)));
+  return (sqrt(msSquareDistancePointToSegment(p, a, b)));
 }
 
 double msSquareDistancePointToSegment(pointObj *p, pointObj *a, pointObj *b)
@@ -375,11 +380,11 @@ double msSquareDistancePointToSegment(pointObj *p, pointObj *a, pointObj *b)
 /* liable for any real or imagined damage resulting from its use. */
 /* Users of this code must verify correctness for their application. */
 
-double msDistanceSegmentToSegment(pointObj *pa, pointObj *pb, pointObj *pc, pointObj *pd) 
+double msDistanceSegmentToSegment(pointObj *pa, pointObj *pb, pointObj *pc, pointObj *pd)
 {
   vectorObj dP;
   vectorObj u, v, w;
-  double a, b, c, d, e; 
+  double a, b, c, d, e;
   double D;
   double sc, sN, sD; /* N=numerator, D=demoninator */
   double tc, tN, tD;
@@ -395,9 +400,9 @@ double msDistanceSegmentToSegment(pointObj *pa, pointObj *pb, pointObj *pc, poin
   u.x = pb->x - pa->x; /* u = pb - pa */
   u.y = pb->y - pa->y;
   v.x = pd->x - pc->x; /* v = pd - pc  */
-  v.y = pd->y - pc->y; 
+  v.y = pd->y - pc->y;
   w.x = pa->x - pc->x; /* w = pa - pc */
-  w.y = pa->y - pc->y; 
+  w.y = pa->y - pc->y;
 
   a = dot(u,u);
   b = dot(u,v);
@@ -408,7 +413,7 @@ double msDistanceSegmentToSegment(pointObj *pa, pointObj *pb, pointObj *pc, poin
   D = a*c - b*b;
   sc = sN = sD = D;
   tc = tN = tD = D;
-  
+
   /* compute the line parameters of the two closest points */
   if(D < SMALL_NUMBER) { /* lines are parallel or almost parallel */
     sN = 0.0;
@@ -479,36 +484,36 @@ double msSquareDistancePointToShape(pointObj *point, shapeObj *shape)
   double dist, minDist=-1;
 
   switch(shape->type) {
-  case(MS_SHAPE_POINT):
-    for(j=0;j<shape->numlines;j++) {
-      for(i=0; i<shape->line[j].numpoints; i++) {
-        dist = msSquareDistancePointToPoint(point, &(shape->line[j].point[i]));
-        if((dist < minDist) || (minDist < 0)) minDist = dist;
-      }
-    }
-    break;
-  case(MS_SHAPE_LINE):
-    for(j=0;j<shape->numlines;j++) {
-      for(i=1; i<shape->line[j].numpoints; i++) {
-        dist = msSquareDistancePointToSegment(point, &(shape->line[j].point[i-1]), &(shape->line[j].point[i]));
-        if((dist < minDist) || (minDist < 0)) minDist = dist;
+    case(MS_SHAPE_POINT):
+      for(j=0; j<shape->numlines; j++) {
+        for(i=0; i<shape->line[j].numpoints; i++) {
+          dist = msSquareDistancePointToPoint(point, &(shape->line[j].point[i]));
+          if((dist < minDist) || (minDist < 0)) minDist = dist;
+        }
       }
-    }
-    break;
-  case(MS_SHAPE_POLYGON):
-    if(msIntersectPointPolygon(point, shape))
-      minDist = 0; /* point is IN the shape */
-    else { /* treat shape just like a line */
-      for(j=0;j<shape->numlines;j++) {
+      break;
+    case(MS_SHAPE_LINE):
+      for(j=0; j<shape->numlines; j++) {
         for(i=1; i<shape->line[j].numpoints; i++) {
           dist = msSquareDistancePointToSegment(point, &(shape->line[j].point[i-1]), &(shape->line[j].point[i]));
           if((dist < minDist) || (minDist < 0)) minDist = dist;
         }
       }
-    }
-    break;
-  default:
-    break;
+      break;
+    case(MS_SHAPE_POLYGON):
+      if(msIntersectPointPolygon(point, shape))
+        minDist = 0; /* point is IN the shape */
+      else { /* treat shape just like a line */
+        for(j=0; j<shape->numlines; j++) {
+          for(i=1; i<shape->line[j].numpoints; i++) {
+            dist = msSquareDistancePointToSegment(point, &(shape->line[j].point[i-1]), &(shape->line[j].point[i]));
+            if((dist < minDist) || (minDist < 0)) minDist = dist;
+          }
+        }
+      }
+      break;
+    default:
+      break;
   }
 
   return(minDist);
@@ -520,143 +525,143 @@ double msDistanceShapeToShape(shapeObj *shape1, shapeObj *shape2)
   double dist, minDist=-1;
 
   switch(shape1->type) {
-  case(MS_SHAPE_POINT): /* shape1 */
-    for(i=0;i<shape1->numlines;i++) {
-      for(j=0; j<shape1->line[i].numpoints; j++) {
-        dist = msSquareDistancePointToShape(&(shape1->line[i].point[j]), shape2);
-        if((dist < minDist) || (minDist < 0)) 
-    minDist = dist;
-      }
-    }
-    minDist = sqrt(minDist);
-    break;
-  case(MS_SHAPE_LINE): /* shape1 */
-    switch(shape2->type) {
-    case(MS_SHAPE_POINT):
-      for(i=0;i<shape2->numlines;i++) {
-        for(j=0; j<shape2->line[i].numpoints; j++) {
-          dist = msSquareDistancePointToShape(&(shape2->line[i].point[j]), shape1);
-          if((dist < minDist) || (minDist < 0)) 
-      minDist = dist;
-        }
-      }
-      minDist = sqrt(minDist);
-      break;
-    case(MS_SHAPE_LINE):
-      for(i=0;i<shape1->numlines;i++) {
-        for(j=1; j<shape1->line[i].numpoints; j++) {
-          for(k=0;k<shape2->numlines;k++) {
-            for(l=1; l<shape2->line[k].numpoints; l++) {
-              /* check intersection (i.e. dist=0) */
-        if(msIntersectSegments(&(shape1->line[i].point[j-1]), &(shape1->line[i].point[j]), &(shape2->line[k].point[l-1]), &(shape2->line[k].point[l])) == MS_TRUE) 
-                return(0);
-
-        /* no intersection, compute distance */
-        dist = msDistanceSegmentToSegment(&(shape1->line[i].point[j-1]), &(shape1->line[i].point[j]), &(shape2->line[k].point[l-1]), &(shape2->line[k].point[l]));
-        if((dist < minDist) || (minDist < 0)) 
-    minDist = dist;
-      }
-    }
-  }
-      }
-      break;    
-    case(MS_SHAPE_POLYGON):
-      /* shape2 (the polygon) could contain shape1 or one of it's parts       */
+    case(MS_SHAPE_POINT): /* shape1 */
       for(i=0; i<shape1->numlines; i++) {
-        if(msIntersectPointPolygon(&(shape1->line[0].point[0]), shape2) == MS_TRUE) /* this considers holes and multiple parts */
-          return(0);
-      }
-      
-      /* check segment intersection and, if necessary, distance between segments */
-      for(i=0;i<shape1->numlines;i++) {
-        for(j=1; j<shape1->line[i].numpoints; j++) {
-          for(k=0;k<shape2->numlines;k++) {
-            for(l=1; l<shape2->line[k].numpoints; l++) {
-        /* check intersection (i.e. dist=0) */
-        if(msIntersectSegments(&(shape1->line[i].point[j-1]), &(shape1->line[i].point[j]), &(shape2->line[k].point[l-1]), &(shape2->line[k].point[l])) == MS_TRUE) 
-                return(0);
-
-        /* no intersection, compute distance */
-        dist = msDistanceSegmentToSegment(&(shape1->line[i].point[j-1]), &(shape1->line[i].point[j]), &(shape2->line[k].point[l-1]), &(shape2->line[k].point[l]));
-        if((dist < minDist) || (minDist < 0)) 
-    minDist = dist;
-      }
-    }
-  }
-      }
-      break;
-    }
-    break;
-  case(MS_SHAPE_POLYGON): /* shape1 */
-    switch(shape2->type) {
-    case(MS_SHAPE_POINT):
-      for(i=0;i<shape2->numlines;i++) {
-        for(j=0; j<shape2->line[i].numpoints; j++) {
-          dist = msSquareDistancePointToShape(&(shape2->line[i].point[j]), shape1);
-          if((dist < minDist) || (minDist < 0)) 
-      minDist = dist;
+        for(j=0; j<shape1->line[i].numpoints; j++) {
+          dist = msSquareDistancePointToShape(&(shape1->line[i].point[j]), shape2);
+          if((dist < minDist) || (minDist < 0))
+            minDist = dist;
         }
       }
       minDist = sqrt(minDist);
       break;
-    case(MS_SHAPE_LINE):
-      /* shape1 (the polygon) could contain shape2 or one of it's parts       */
-      for(i=0; i<shape2->numlines; i++) {
-        if(msIntersectPointPolygon(&(shape2->line[i].point[0]), shape1) == MS_TRUE) /* this considers holes and multiple parts */
-          return(0);
+    case(MS_SHAPE_LINE): /* shape1 */
+      switch(shape2->type) {
+        case(MS_SHAPE_POINT):
+          for(i=0; i<shape2->numlines; i++) {
+            for(j=0; j<shape2->line[i].numpoints; j++) {
+              dist = msSquareDistancePointToShape(&(shape2->line[i].point[j]), shape1);
+              if((dist < minDist) || (minDist < 0))
+                minDist = dist;
+            }
+          }
+          minDist = sqrt(minDist);
+          break;
+        case(MS_SHAPE_LINE):
+          for(i=0; i<shape1->numlines; i++) {
+            for(j=1; j<shape1->line[i].numpoints; j++) {
+              for(k=0; k<shape2->numlines; k++) {
+                for(l=1; l<shape2->line[k].numpoints; l++) {
+                  /* check intersection (i.e. dist=0) */
+                  if(msIntersectSegments(&(shape1->line[i].point[j-1]), &(shape1->line[i].point[j]), &(shape2->line[k].point[l-1]), &(shape2->line[k].point[l])) == MS_TRUE)
+                    return(0);
+
+                  /* no intersection, compute distance */
+                  dist = msDistanceSegmentToSegment(&(shape1->line[i].point[j-1]), &(shape1->line[i].point[j]), &(shape2->line[k].point[l-1]), &(shape2->line[k].point[l]));
+                  if((dist < minDist) || (minDist < 0))
+                    minDist = dist;
+                }
+              }
+            }
+          }
+          break;
+        case(MS_SHAPE_POLYGON):
+          /* shape2 (the polygon) could contain shape1 or one of it's parts       */
+          for(i=0; i<shape1->numlines; i++) {
+            if(msIntersectPointPolygon(&(shape1->line[0].point[0]), shape2) == MS_TRUE) /* this considers holes and multiple parts */
+              return(0);
+          }
+
+          /* check segment intersection and, if necessary, distance between segments */
+          for(i=0; i<shape1->numlines; i++) {
+            for(j=1; j<shape1->line[i].numpoints; j++) {
+              for(k=0; k<shape2->numlines; k++) {
+                for(l=1; l<shape2->line[k].numpoints; l++) {
+                  /* check intersection (i.e. dist=0) */
+                  if(msIntersectSegments(&(shape1->line[i].point[j-1]), &(shape1->line[i].point[j]), &(shape2->line[k].point[l-1]), &(shape2->line[k].point[l])) == MS_TRUE)
+                    return(0);
+
+                  /* no intersection, compute distance */
+                  dist = msDistanceSegmentToSegment(&(shape1->line[i].point[j-1]), &(shape1->line[i].point[j]), &(shape2->line[k].point[l-1]), &(shape2->line[k].point[l]));
+                  if((dist < minDist) || (minDist < 0))
+                    minDist = dist;
+                }
+              }
+            }
+          }
+          break;
       }
-      
-      /* check segment intersection and, if necessary, distance between segments */
-      for(i=0;i<shape1->numlines;i++) {      
-        for(j=1; j<shape1->line[i].numpoints; j++) {
-          for(k=0;k<shape2->numlines;k++) {
-            for(l=1; l<shape2->line[k].numpoints; l++) {
-        /* check intersection (i.e. dist=0) */
-        if(msIntersectSegments(&(shape1->line[i].point[j-1]), &(shape1->line[i].point[j]), &(shape2->line[k].point[l-1]), &(shape2->line[k].point[l])) == MS_TRUE) 
-                return(0);
-
-        /* no intersection, compute distance */
-        dist = msDistanceSegmentToSegment(&(shape1->line[i].point[j-1]), &(shape1->line[i].point[j]), &(shape2->line[k].point[l-1]), &(shape2->line[k].point[l]));
-        if((dist < minDist) || (minDist < 0)) 
-    minDist = dist;
-      }
-    }
-  }
-      }
-      break; 
-    case(MS_SHAPE_POLYGON): 
-      /* shape1 completely contains shape2 (only need to check one point from each part) */
-      for(i=0; i<shape2->numlines; i++) {
-        if(msIntersectPointPolygon(&(shape2->line[i].point[0]), shape1) == MS_TRUE) /* this considers holes and multiple parts */
-          return(0);
-      }
-
-      /* shape2 completely contains shape1 (only need to check one point from each part) */
-      for(i=0; i<shape1->numlines; i++) {
-        if(msIntersectPointPolygon(&(shape1->line[i].point[0]), shape2) == MS_TRUE) /* this considers holes and multiple parts */
-          return(0);
-      }
-
-      /* check segment intersection and, if necessary, distance between segments */
-      for(i=0;i<shape1->numlines;i++) {        
-        for(j=1; j<shape1->line[i].numpoints; j++) {
-          for(k=0;k<shape2->numlines;k++) {
-            for(l=1; l<shape2->line[k].numpoints; l++) {
-        /* check intersection (i.e. dist=0) */
-        if(msIntersectSegments(&(shape1->line[i].point[j-1]), &(shape1->line[i].point[j]), &(shape2->line[k].point[l-1]), &(shape2->line[k].point[l])) == MS_TRUE) 
-                return(0);        
-
-        /* no intersection, compute distance */
-        dist = msDistanceSegmentToSegment(&(shape1->line[i].point[j-1]), &(shape1->line[i].point[j]), &(shape2->line[k].point[l-1]), &(shape2->line[k].point[l]));
-        if((dist < minDist) || (minDist < 0)) 
-    minDist = dist;
-      }
-    }
-  }
+      break;
+    case(MS_SHAPE_POLYGON): /* shape1 */
+      switch(shape2->type) {
+        case(MS_SHAPE_POINT):
+          for(i=0; i<shape2->numlines; i++) {
+            for(j=0; j<shape2->line[i].numpoints; j++) {
+              dist = msSquareDistancePointToShape(&(shape2->line[i].point[j]), shape1);
+              if((dist < minDist) || (minDist < 0))
+                minDist = dist;
+            }
+          }
+          minDist = sqrt(minDist);
+          break;
+        case(MS_SHAPE_LINE):
+          /* shape1 (the polygon) could contain shape2 or one of it's parts       */
+          for(i=0; i<shape2->numlines; i++) {
+            if(msIntersectPointPolygon(&(shape2->line[i].point[0]), shape1) == MS_TRUE) /* this considers holes and multiple parts */
+              return(0);
+          }
+
+          /* check segment intersection and, if necessary, distance between segments */
+          for(i=0; i<shape1->numlines; i++) {
+            for(j=1; j<shape1->line[i].numpoints; j++) {
+              for(k=0; k<shape2->numlines; k++) {
+                for(l=1; l<shape2->line[k].numpoints; l++) {
+                  /* check intersection (i.e. dist=0) */
+                  if(msIntersectSegments(&(shape1->line[i].point[j-1]), &(shape1->line[i].point[j]), &(shape2->line[k].point[l-1]), &(shape2->line[k].point[l])) == MS_TRUE)
+                    return(0);
+
+                  /* no intersection, compute distance */
+                  dist = msDistanceSegmentToSegment(&(shape1->line[i].point[j-1]), &(shape1->line[i].point[j]), &(shape2->line[k].point[l-1]), &(shape2->line[k].point[l]));
+                  if((dist < minDist) || (minDist < 0))
+                    minDist = dist;
+                }
+              }
+            }
+          }
+          break;
+        case(MS_SHAPE_POLYGON):
+          /* shape1 completely contains shape2 (only need to check one point from each part) */
+          for(i=0; i<shape2->numlines; i++) {
+            if(msIntersectPointPolygon(&(shape2->line[i].point[0]), shape1) == MS_TRUE) /* this considers holes and multiple parts */
+              return(0);
+          }
+
+          /* shape2 completely contains shape1 (only need to check one point from each part) */
+          for(i=0; i<shape1->numlines; i++) {
+            if(msIntersectPointPolygon(&(shape1->line[i].point[0]), shape2) == MS_TRUE) /* this considers holes and multiple parts */
+              return(0);
+          }
+
+          /* check segment intersection and, if necessary, distance between segments */
+          for(i=0; i<shape1->numlines; i++) {
+            for(j=1; j<shape1->line[i].numpoints; j++) {
+              for(k=0; k<shape2->numlines; k++) {
+                for(l=1; l<shape2->line[k].numpoints; l++) {
+                  /* check intersection (i.e. dist=0) */
+                  if(msIntersectSegments(&(shape1->line[i].point[j-1]), &(shape1->line[i].point[j]), &(shape2->line[k].point[l-1]), &(shape2->line[k].point[l])) == MS_TRUE)
+                    return(0);
+
+                  /* no intersection, compute distance */
+                  dist = msDistanceSegmentToSegment(&(shape1->line[i].point[j-1]), &(shape1->line[i].point[j]), &(shape2->line[k].point[l-1]), &(shape2->line[k].point[l]));
+                  if((dist < minDist) || (minDist < 0))
+                    minDist = dist;
+                }
+              }
+            }
+          }
+          break;
       }
       break;
-    }
-    break;
   }
 
   return(minDist);
diff --git a/mapserv.c b/mapserv.c
index 34e42bb..78a7969 100644
--- a/mapserv.c
+++ b/mapserv.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -33,1083 +33,124 @@
 #endif
 
 #include "mapserv.h"
+#include "mapio.h"
 #include "maptime.h"
 
 #ifndef WIN32
 #include <signal.h>
 #endif
 
-MS_CVSID("$Id$")
 
-mapservObj* mapserv;
 
-int writeLog(int show_error)
+/************************************************************************/
+/*                      FastCGI cleanup functions.                      */
+/************************************************************************/
+#ifndef WIN32
+void msCleanupOnSignal( int nInData )
 {
-  FILE *stream;
-  int i;
-  time_t t;
-  char szPath[MS_MAXPATHLEN];
-
-  if(!mapserv) return(0);
-  if(!mapserv->map) return(0);
-  if(!mapserv->map->web.log) return(0);
-  
-  if((stream = fopen(msBuildPath(szPath, mapserv->map->mappath, 
-                                   mapserv->map->web.log),"a")) == NULL) {
-    msSetError(MS_IOERR, mapserv->map->web.log, "writeLog()");
-    return(-1);
-  }
-
-  t = time(NULL);
-  fprintf(stream,"%s,",msStringChop(ctime(&t)));
-  fprintf(stream,"%d,",(int)getpid());
-  
-  if(getenv("REMOTE_ADDR") != NULL)
-    fprintf(stream,"%s,",getenv("REMOTE_ADDR"));
-  else
-    fprintf(stream,"NULL,");
- 
-  fprintf(stream,"%s,",mapserv->map->name);
-  fprintf(stream,"%d,",mapserv->Mode);
-
-  fprintf(stream,"%f %f %f %f,", mapserv->map->extent.minx, mapserv->map->extent.miny, mapserv->map->extent.maxx, mapserv->map->extent.maxy);
-
-  fprintf(stream,"%f %f,", mapserv->mappnt.x, mapserv->mappnt.y);
-
-  for(i=0;i<mapserv->NumLayers;i++)
-    fprintf(stream, "%s ", mapserv->Layers[i]);
-  fprintf(stream,",");
-
-  if(show_error == MS_TRUE)
-    msWriteError(stream);
-  else
-    fprintf(stream, "normal execution");
-
-  fprintf(stream,"\n");
-
-  fclose(stream);
-  return(0);
+  /* For some reason, the fastcgi message code does not seem to work */
+  /* from within the signal handler on Unix.  So we force output through */
+  /* normal stdio functions. */
+  msIO_installHandlers( NULL, NULL, NULL );
+  msIO_fprintf( stderr, "In msCleanupOnSignal.\n" );
+  msCleanup(1);
+  exit(0);
 }
+#endif
 
-void writeError(void)
+#ifdef WIN32
+void msCleanupOnExit( void )
 {
-  errorObj *ms_error = msGetErrorObj();
-
-  writeLog(MS_TRUE);
-
-  if(!mapserv || !mapserv->map) {
-    msIO_printf("Content-type: text/html%c%c",10,10);
-    msIO_printf("<HTML>\n");
-    msIO_printf("<HEAD><TITLE>MapServer Message</TITLE></HEAD>\n");
-    msIO_printf("<!-- %s -->\n", msGetVersion());
-    msIO_printf("<BODY BGCOLOR=\"#FFFFFF\">\n");
-    msWriteErrorXML(stdout);
-    msIO_printf("</BODY></HTML>");
-    if(mapserv) 
-      msFreeMapServObj(mapserv);
-    msCleanup();
-    exit(0);
-  }
-
-  if((ms_error->code == MS_NOTFOUND) && (mapserv->map->web.empty)) {
-    /* msRedirect(mapserv->map->web.empty); */
-    if(msReturnURL(mapserv, mapserv->map->web.empty, BROWSE) != MS_SUCCESS) {
-      msIO_printf("Content-type: text/html%c%c",10,10);
-      msIO_printf("<HTML>\n");
-      msIO_printf("<HEAD><TITLE>MapServer Message</TITLE></HEAD>\n");
-      msIO_printf("<!-- %s -->\n", msGetVersion());
-      msIO_printf("<BODY BGCOLOR=\"#FFFFFF\">\n");
-      msWriteErrorXML(stdout);
-      msIO_printf("</BODY></HTML>");
-    }
-  } else {
-    if(mapserv->map->web.error) {      
-      /* msRedirect(mapserv->map->web.error); */
-      if(msReturnURL(mapserv, mapserv->map->web.error, BROWSE) != MS_SUCCESS) {
-        msIO_printf("Content-type: text/html%c%c",10,10);
-        msIO_printf("<HTML>\n");
-        msIO_printf("<HEAD><TITLE>MapServer Message</TITLE></HEAD>\n");
-        msIO_printf("<!-- %s -->\n", msGetVersion());
-        msIO_printf("<BODY BGCOLOR=\"#FFFFFF\">\n");
-        msWriteErrorXML(stdout);
-        msIO_printf("</BODY></HTML>");
-      }
-    } else {
-      msIO_printf("Content-type: text/html%c%c",10,10);
-      msIO_printf("<HTML>\n");
-      msIO_printf("<HEAD><TITLE>MapServer Message</TITLE></HEAD>\n");
-      msIO_printf("<!-- %s -->\n", msGetVersion());
-      msIO_printf("<BODY BGCOLOR=\"#FFFFFF\">\n");
-      msWriteErrorXML(stdout);
-      msIO_printf("</BODY></HTML>");
-    }
-  }
-
-  /* Clean-up (the following are not stored as part of the mapserv) */
-  if(QueryItem) free(QueryItem);
-  if(QueryString) free(QueryString);
-  if(QueryLayer) free(QueryLayer);
-  if(SelectLayer) free(SelectLayer);
-  if(QueryFile) free(QueryFile);
+  /* note that stderr and stdout seem to be non-functional in the */
+  /* fastcgi/win32 case.  If you really want to check functioning do */
+  /* some sort of hack logging like below ... otherwise just trust it! */
 
-  msFreeMapServObj(mapserv);
-  msCleanup();
+#ifdef notdef
+  FILE *fp_out = fopen( "D:\\temp\\mapserv.log", "w" );
 
-  exit(0); /* bail */
+  fprintf( fp_out, "In msCleanupOnExit\n" );
+  fclose( fp_out );
+#endif
+  msCleanup(1);
 }
+#endif
 
-/*
-** Converts a string (e.g. form parameter) to a double, first checking the format against
-** a regular expression. Dumps an error immediately if the format test fails.
-*/
-static double getNumeric(char *s)
-{
-  char *err;
-  double rv; 
-
-  rv = strtod(s, &err);
-  if (*err) {
-    msSetError(MS_TYPEERR, NULL, "getNumeric()");
-    writeError();
-  }
-  return rv;
-}
+#ifdef USE_FASTCGI
 
+/************************************************************************/
+/*                           msIO_fcgiRead()                            */
+/*                                                                      */
+/*      This is the default implementation via stdio.                   */
+/************************************************************************/
 
+static int msIO_fcgiRead( void *cbData, void *data, int byteCount )
 
-/*
-** Extract Map File name from params and load it.  
-** Returns map object or NULL on error.
-*/
-mapObj *loadMap(void)
 {
-  int i;
-  mapObj *map = NULL;
-
-  for(i=0;i<mapserv->request->NumParams;i++) /* find the mapfile parameter first */
-    if(strcasecmp(mapserv->request->ParamNames[i], "map") == 0) break;
-  
-  if(i == mapserv->request->NumParams) {
-    if(getenv("MS_MAPFILE")) /* has a default file has not been set */
-      map = msLoadMap(getenv("MS_MAPFILE"), NULL);
-    else {
-      msSetError(MS_WEBERR, "CGI variable \"map\" is not set.", "loadMap()"); /* no default, outta here */
-      writeError();
-    }
-  } else {
-    if(getenv(mapserv->request->ParamValues[i])) /* an environment variable references the actual file to use */
-      map = msLoadMap(getenv(mapserv->request->ParamValues[i]), NULL);
-    else {
-      /* by here we know the request isn't for something in an environment variable */
-      if(getenv("MS_MAP_NO_PATH")) {
-        msSetError(MS_WEBERR, "Mapfile not found in environment variables and this server is not configured for full paths.", "loadMap()");
-	writeError();
-      }
-
-      if(getenv("MS_MAP_PATTERN") && msEvalRegex(getenv("MS_MAP_PATTERN"), mapserv->request->ParamValues[i]) != MS_TRUE) {
-        msSetError(MS_WEBERR, "Parameter 'map' value fails to validate.", "loadMap()");
-        writeError();
-      }
-
-      /* ok to try to load now */
-      map = msLoadMap(mapserv->request->ParamValues[i], NULL);
-    }
-  }
-
-  if(!map) writeError();
-
-  /* check for any %variable% substitutions here, also do any map_ changes, we do this here so WMS/WFS  */
-  /* services can take advantage of these "vendor specific" extensions */
-  for(i=0;i<mapserv->request->NumParams;i++) {
-    /*
-    ** a few CGI variables should be skipped altogether
-    **
-    ** qstring: there is separate per layer validation for attribute queries and the substitution checks
-    **          below conflict with that so we avoid it here
-    */
-    if(strncasecmp(mapserv->request->ParamNames[i],"qstring",7) == 0) continue;
-
-    if(strncasecmp(mapserv->request->ParamNames[i],"map_",4) == 0 || strncasecmp(mapserv->request->ParamNames[i],"map.",4) == 0) { /* check to see if there are any additions to the mapfile */
-      if(msUpdateMapFromURL(map, mapserv->request->ParamNames[i], mapserv->request->ParamValues[i]) != MS_SUCCESS) writeError();
-      continue;
-    }
-  }
-
-  msApplySubstitutions(map, mapserv->request->ParamNames, mapserv->request->ParamValues, mapserv->request->NumParams);
-  msApplyDefaultSubstitutions(map);
-
-  /* check to see if a ogc map context is passed as argument. if there */
-  /* is one load it */
-
-  for(i=0;i<mapserv->request->NumParams;i++) {
-    if(strcasecmp(mapserv->request->ParamNames[i],"context") == 0) {
-      if(mapserv->request->ParamValues[i] && strlen(mapserv->request->ParamValues[i]) > 0) {
-        if(strncasecmp(mapserv->request->ParamValues[i],"http",4) == 0) {
-          if(msGetConfigOption(map, "CGI_CONTEXT_URL"))
-            msLoadMapContextURL(map, mapserv->request->ParamValues[i], MS_FALSE);
-        } else
-            msLoadMapContext(map, mapserv->request->ParamValues[i], MS_FALSE); 
-      }
-    }
-  } 
-
-  return map;
+  return FCGI_fread( data, 1, byteCount, (FCGI_FILE *) cbData );
 }
 
+/************************************************************************/
+/*                           msIO_fcgiWrite()                           */
+/*                                                                      */
+/*      This is the default implementation via stdio.                   */
+/************************************************************************/
 
-/*
-** Set operation mode. First look in MS_MODE env. var. as a
-** default value that can be overridden by the mode=... CGI param.
-** Returns silently, leaving mapserv->Mode unchanged if mode param not set.
-*/
-static int setMode(void)
-{
-    const char *mode = NULL;
-    int i, j;
-
-
-    mode = getenv("MS_MODE");
-    for( i=0; i<mapserv->request->NumParams; i++ ) 
-    {
-        if(strcasecmp(mapserv->request->ParamNames[i], "mode") == 0)
-        {
-            mode = mapserv->request->ParamValues[i];
-            break;
-        }
-    }
-
-    if (mode) {
-      for(j=0; j<numModes; j++) {
-        if(strcasecmp(mode, modeStrings[j]) == 0) {
-          mapserv->Mode = j;
-          break;
-        }
-      }
-
-      if(j == numModes) {
-        msSetError(MS_WEBERR, "Invalid mode.", "setMode()");
-        return MS_FAILURE;
-      }
-    }
-
-    return MS_SUCCESS;
-}
+static int msIO_fcgiWrite( void *cbData, void *data, int byteCount )
 
-/*
-** Process CGI parameters.
-*/
-void loadForm(void)
 {
-  int i,n;
-  char **tokens=NULL;
-  int rosa_type=0;
-
-  for(i=0;i<mapserv->request->NumParams;i++) { /* now process the rest of the form variables */
-    if(strlen(mapserv->request->ParamValues[i]) == 0)
-      continue;
-    
-    
-    if(strcasecmp(mapserv->request->ParamNames[i],"icon") == 0) {      
-      mapserv->icon = msStrdup(mapserv->request->ParamValues[i]);
-      continue;
-    }
-
-    if(strcasecmp(mapserv->request->ParamNames[i],"queryfile") == 0) {      
-      QueryFile = msStrdup(mapserv->request->ParamValues[i]);
-      continue;
-    }
-    
-    if(strcasecmp(mapserv->request->ParamNames[i],"savequery") == 0) {
-      mapserv->savequery = MS_TRUE;
-      continue;
-    }
-    
-    /* Insecure as implemented, need to save someplace non accessible by everyone in the universe
-        if(strcasecmp(mapserv->request->ParamNames[i],"savemap") == 0) {      
-         mapserv->savemap = MS_TRUE;
-         continue;
-        }
-    */
-
-    if(strcasecmp(mapserv->request->ParamNames[i],"zoom") == 0) {
-      mapserv->Zoom = getNumeric(mapserv->request->ParamValues[i]);      
-      if((mapserv->Zoom > MAXZOOM) || (mapserv->Zoom < MINZOOM)) {
-        msSetError(MS_WEBERR, "Zoom value out of range.", "loadForm()");
-        writeError();
-      }
-      continue;
-    }
-
-    if(strcasecmp(mapserv->request->ParamNames[i],"zoomdir") == 0) {
-      mapserv->ZoomDirection = (int)getNumeric(mapserv->request->ParamValues[i]);
-      if((mapserv->ZoomDirection != -1) && (mapserv->ZoomDirection != 1) && (mapserv->ZoomDirection != 0)) {
-        msSetError(MS_WEBERR, "Zoom direction must be 1, 0 or -1.", "loadForm()");
-        writeError();
-      }
-      continue;
-    }
-
-    if(strcasecmp(mapserv->request->ParamNames[i],"zoomsize") == 0) { /* absolute zoom magnitude */
-      ZoomSize = (int) getNumeric(mapserv->request->ParamValues[i]);      
-      if((ZoomSize > MAXZOOM) || (ZoomSize < 1)) {
-        msSetError(MS_WEBERR, "Invalid zoom size.", "loadForm()");
-        writeError();
-      }    
-      continue;
-    }
-    
-    if(strcasecmp(mapserv->request->ParamNames[i],"imgext") == 0) { /* extent of an existing image in a web application */
-      tokens = msStringSplit(mapserv->request->ParamValues[i], ' ', &n);
-
-      if(!tokens) {
-        msSetError(MS_MEMERR, NULL, "loadForm()");
-        writeError();
-      }
-
-      if(n != 4) {
-        msSetError(MS_WEBERR, "Not enough arguments for imgext.", "loadForm()");
-        writeError();
-      }
-
-      mapserv->ImgExt.minx = getNumeric(tokens[0]);
-      mapserv->ImgExt.miny = getNumeric(tokens[1]);
-      mapserv->ImgExt.maxx = getNumeric(tokens[2]);
-      mapserv->ImgExt.maxy = getNumeric(tokens[3]);
-
-      msFreeCharArray(tokens, 4);
-      continue;
-    }
-
-    if(strcasecmp(mapserv->request->ParamNames[i],"searchmap") == 0) {      
-      SearchMap = MS_TRUE;
-      continue;
-    }
-
-    if(strcasecmp(mapserv->request->ParamNames[i],"id") == 0) {
-      if(msEvalRegex(IDPATTERN, mapserv->request->ParamValues[i]) == MS_FALSE) { 
-	msSetError(MS_WEBERR, "Parameter 'id' value fails to validate.", "loadForm()"); 
-	writeError(); 
-      }
-      strlcpy(mapserv->Id, mapserv->request->ParamValues[i], IDSIZE);
-      continue;
-    }
-
-    if(strcasecmp(mapserv->request->ParamNames[i],"mapext") == 0) { /* extent of the new map or query */
-
-      if(strncasecmp(mapserv->request->ParamValues[i],"shape",5) == 0)
-        mapserv->UseShapes = MS_TRUE;
-      else {
-        tokens = msStringSplit(mapserv->request->ParamValues[i], ' ', &n);
-    
-        if(!tokens) {
-          msSetError(MS_MEMERR, NULL, "loadForm()");
-          writeError();
-        }
-    
-        if(n != 4) {
-          msSetError(MS_WEBERR, "Not enough arguments for mapext.", "loadForm()");
-          writeError();
-        }
-    
-        mapserv->map->extent.minx = getNumeric(tokens[0]);
-        mapserv->map->extent.miny = getNumeric(tokens[1]);
-        mapserv->map->extent.maxx = getNumeric(tokens[2]);
-        mapserv->map->extent.maxy = getNumeric(tokens[3]);    
-    
-        msFreeCharArray(tokens, 4);
-    
-#ifdef USE_PROJ
-        /* 
-         * If there is a projection in the map file, and it is not lon/lat, and the 
-         * extents "look like" they *are* lon/lat, based on their size,
-         * then convert the extents to the map file projection.
-         *
-         * DANGER: If the extents are legitimately in the mapfile projection
-         *         and coincidentally fall in the lon/lat range, bad things
-         *         will ensue.
-         */
-        if(mapserv->map->projection.proj && !pj_is_latlong(mapserv->map->projection.proj)
-           && (mapserv->map->extent.minx >= -180.0 && mapserv->map->extent.minx <= 180.0) 
-           && (mapserv->map->extent.miny >= -90.0 && mapserv->map->extent.miny <= 90.0)
-           && (mapserv->map->extent.maxx >= -180.0 && mapserv->map->extent.maxx <= 180.0) 
-           && (mapserv->map->extent.maxy >= -90.0 && mapserv->map->extent.maxy <= 90.0)) {
-          msProjectRect(&(mapserv->map->latlon), &(mapserv->map->projection), &(mapserv->map->extent)); /* extent is a in lat/lon */
-        }
-#endif
-
-        if((mapserv->map->extent.minx != mapserv->map->extent.maxx) && (mapserv->map->extent.miny != mapserv->map->extent.maxy)) { /* extent seems ok */
-          mapserv->CoordSource = FROMUSERBOX;
-          QueryCoordSource = FROMUSERBOX;
-        }
-      }
-
-      continue;
-    }
-
-    if(strcasecmp(mapserv->request->ParamNames[i],"minx") == 0) { /* extent of the new map, in pieces */
-      mapserv->map->extent.minx = getNumeric(mapserv->request->ParamValues[i]);      
-      continue;
-    }
-    if(strcasecmp(mapserv->request->ParamNames[i],"maxx") == 0) {      
-      mapserv->map->extent.maxx = getNumeric(mapserv->request->ParamValues[i]);
-      continue;
-    }
-    if(strcasecmp(mapserv->request->ParamNames[i],"miny") == 0) {
-      mapserv->map->extent.miny = getNumeric(mapserv->request->ParamValues[i]);
-      continue;
-    }
-    if(strcasecmp(mapserv->request->ParamNames[i],"maxy") == 0) {
-      mapserv->map->extent.maxy = getNumeric(mapserv->request->ParamValues[i]);
-      mapserv->CoordSource = FROMUSERBOX;
-      QueryCoordSource = FROMUSERBOX;
-      continue;
-    } 
-
-    if(strcasecmp(mapserv->request->ParamNames[i],"mapxy") == 0) { /* user map coordinate */
-      
-      if(strncasecmp(mapserv->request->ParamValues[i],"shape",5) == 0) {
-        mapserv->UseShapes = MS_TRUE;    
-      } else {
-        tokens = msStringSplit(mapserv->request->ParamValues[i], ' ', &n);
-
-        if(!tokens) {
-          msSetError(MS_MEMERR, NULL, "loadForm()");
-          writeError();
-        }
-    
-        if(n != 2) {
-          msSetError(MS_WEBERR, "Not enough arguments for mapxy.", "loadForm()");
-          writeError();
-        }
-    
-        mapserv->mappnt.x = getNumeric(tokens[0]);
-        mapserv->mappnt.y = getNumeric(tokens[1]);
-    
-        msFreeCharArray(tokens, 2);
-
-#ifdef USE_PROJ
-        if(mapserv->map->projection.proj && !pj_is_latlong(mapserv->map->projection.proj)
-           && (mapserv->mappnt.x >= -180.0 && mapserv->mappnt.x <= 180.0) 
-           && (mapserv->mappnt.y >= -90.0 && mapserv->mappnt.y <= 90.0)) {
-          msProjectPoint(&(mapserv->map->latlon), &(mapserv->map->projection), &mapserv->mappnt); /* point is a in lat/lon */
-        }
-#endif
-
-        if(mapserv->CoordSource == NONE) { /* don't override previous settings (i.e. buffer or scale ) */
-          mapserv->CoordSource = FROMUSERPNT;
-          QueryCoordSource = FROMUSERPNT;
-        }
-      }
-      continue;
-    }
-
-    /*
-    ** Query shape consisting of map or image coordinates. It's almost identical processing so we'll do either in this block...
-    */
-    if(strcasecmp(mapserv->request->ParamNames[i], "mapshape") == 0 || strcasecmp(mapserv->request->ParamNames[i], "imgshape") == 0) {
-      if(strcasecmp(mapserv->request->ParamNames[i],"mapshape") == 0)
-        QueryCoordSource = FROMUSERSHAPE;
-      else
-        QueryCoordSource = FROMIMGSHAPE;
-
-      if(strchr(mapserv->request->ParamValues[i], '(') != NULL) { /* try WKT */
-        if((mapserv->map->query.shape = msShapeFromWKT(mapserv->request->ParamValues[i])) == NULL) {
-          msSetError(MS_WEBERR, "WKT parse failed for mapshape/imgshape.", "loadForm()");
-          writeError();
-        }
-      } else {
-        lineObj line={0,NULL};
-        char **tmp=NULL;
-        int n, j;
-      
-        tmp = msStringSplit(mapserv->request->ParamValues[i], ' ', &n);
-
-        if(n%2 != 0 || n<8) { /* n must be even and be at least 8 */
-          msSetError(MS_WEBERR, "Malformed polygon geometry for mapshape/imgshape.", "loadForm()");
-          writeError();
-        }
-
-        line.numpoints = n/2;
-        if((line.point = (pointObj *)malloc(sizeof(pointObj)*line.numpoints)) == NULL) {
-          msSetError(MS_MEMERR, NULL, "loadForm()");
-          writeError();
-        }
-
-        if((mapserv->map->query.shape = (shapeObj *) malloc(sizeof(shapeObj))) == NULL) {
-          msSetError(MS_MEMERR, NULL, "loadForm()");
-          writeError();
-	}
-        msInitShape(mapserv->map->query.shape);
-        mapserv->map->query.shape->type = MS_SHAPE_POLYGON;
-
-        for(j=0; j<line.numpoints; j++) {
-          line.point[j].x = atof(tmp[2*j]);
-          line.point[j].y = atof(tmp[2*j+1]);
-
-#ifdef USE_PROJ
-          if(QueryCoordSource == FROMUSERSHAPE && mapserv->map->projection.proj && !pj_is_latlong(mapserv->map->projection.proj)
-             && (line.point[j].x >= -180.0 && line.point[j].x <= 180.0) 
-             && (line.point[j].y >= -90.0 && line.point[j].y <= 90.0)) {
-            msProjectPoint(&(mapserv->map->latlon), &(mapserv->map->projection), &line.point[j]); /* point is a in lat/lon */
-          }
-#endif
-        }
-
-        if(msAddLine(mapserv->map->query.shape, &line) == -1) writeError();
-
-        msFree(line.point);
-        msFreeCharArray(tmp, n);
-      }
-
-      continue;
-    }
-
-    if(strcasecmp(mapserv->request->ParamNames[i],"img.x") == 0) { /* mouse click, in pieces */
-      mapserv->ImgPnt.x = getNumeric(mapserv->request->ParamValues[i]);
-      if((mapserv->ImgPnt.x > (2*mapserv->map->maxsize)) || (mapserv->ImgPnt.x < (-2*mapserv->map->maxsize))) {
-        msSetError(MS_WEBERR, "Coordinate out of range.", "loadForm()");
-        writeError();
-      }
-      mapserv->CoordSource = FROMIMGPNT;
-      QueryCoordSource = FROMIMGPNT;
-      continue;
-    }
-    if(strcasecmp(mapserv->request->ParamNames[i],"img.y") == 0) {
-      mapserv->ImgPnt.y = getNumeric(mapserv->request->ParamValues[i]);      
-      if((mapserv->ImgPnt.y > (2*mapserv->map->maxsize)) || (mapserv->ImgPnt.y < (-2*mapserv->map->maxsize))) {
-        msSetError(MS_WEBERR, "Coordinate out of range.", "loadForm()");
-        writeError();
-      }
-      mapserv->CoordSource = FROMIMGPNT;
-      QueryCoordSource = FROMIMGPNT;
-      continue;
-    }
-
-    if(strcasecmp(mapserv->request->ParamNames[i],"imgxy") == 0) { /* mouse click, single variable */
-      if(mapserv->CoordSource == FROMIMGPNT)
-        continue;
-
-      tokens = msStringSplit(mapserv->request->ParamValues[i], ' ', &n);
-
-      if(!tokens) {
-        msSetError(MS_MEMERR, NULL, "loadForm()");
-        writeError();
-      }
-
-      if(n != 2) {
-        msSetError(MS_WEBERR, "Not enough arguments for imgxy.", "loadForm()");
-        writeError();
-      }
-
-      mapserv->ImgPnt.x = getNumeric(tokens[0]);
-      mapserv->ImgPnt.y = getNumeric(tokens[1]);
-
-      msFreeCharArray(tokens, 2);
-
-      if((mapserv->ImgPnt.x > (2*mapserv->map->maxsize)) || (mapserv->ImgPnt.x < (-2*mapserv->map->maxsize)) || (mapserv->ImgPnt.y > (2*mapserv->map->maxsize)) || (mapserv->ImgPnt.y < (-2*mapserv->map->maxsize))) {
-        msSetError(MS_WEBERR, "Reference map coordinate out of range.", "loadForm()");
-        writeError();
-      }
-
-      if(mapserv->CoordSource == NONE) { /* override nothing since this parameter is usually used to hold a default value */
-        mapserv->CoordSource = FROMIMGPNT;
-        QueryCoordSource = FROMIMGPNT;
-      }
-      continue;
-    }
-
-    if(strcasecmp(mapserv->request->ParamNames[i],"imgbox") == 0) { /* selection box (eg. mouse drag) */
-      tokens = msStringSplit(mapserv->request->ParamValues[i], ' ', &n);
-      
-      if(!tokens) {
-        msSetError(MS_MEMERR, NULL, "loadForm()");
-        writeError();
-      }
-      
-      if(n != 4) {
-        msSetError(MS_WEBERR, "Not enough arguments for imgbox.", "loadForm()");
-        writeError();
-      }
-      
-      mapserv->ImgBox.minx = getNumeric(tokens[0]);
-      mapserv->ImgBox.miny = getNumeric(tokens[1]);
-      mapserv->ImgBox.maxx = getNumeric(tokens[2]);
-      mapserv->ImgBox.maxy = getNumeric(tokens[3]);
-      
-      msFreeCharArray(tokens, 4);
-
-      if((mapserv->ImgBox.minx != mapserv->ImgBox.maxx) && (mapserv->ImgBox.miny != mapserv->ImgBox.maxy)) { /* must not degenerate into a point */
-        mapserv->CoordSource = FROMIMGBOX;
-        QueryCoordSource = FROMIMGBOX;
-      }
-      continue;
-    }
-
-    if(strcasecmp(mapserv->request->ParamNames[i],"ref.x") == 0) { /* mouse click in reference image, in pieces */
-      mapserv->RefPnt.x = getNumeric(mapserv->request->ParamValues[i]);      
-      if((mapserv->RefPnt.x > (2*mapserv->map->maxsize)) || (mapserv->RefPnt.x < (-2*mapserv->map->maxsize))) {
-        msSetError(MS_WEBERR, "Coordinate out of range.", "loadForm()");
-        writeError();
-      }
-      mapserv->CoordSource = FROMREFPNT;
-      continue;
-    }
-    if(strcasecmp(mapserv->request->ParamNames[i],"ref.y") == 0) {
-      mapserv->RefPnt.y = getNumeric(mapserv->request->ParamValues[i]); 
-      if((mapserv->RefPnt.y > (2*mapserv->map->maxsize)) || (mapserv->RefPnt.y < (-2*mapserv->map->maxsize))) {
-        msSetError(MS_WEBERR, "Coordinate out of range.", "loadForm()");
-        writeError();
-      }
-      mapserv->CoordSource = FROMREFPNT;
-      continue;
-    }
-
-    if(strcasecmp(mapserv->request->ParamNames[i],"refxy") == 0) { /* mouse click in reference image, single variable */
-      tokens = msStringSplit(mapserv->request->ParamValues[i], ' ', &n);
-
-      if(!tokens) {
-        msSetError(MS_MEMERR, NULL, "loadForm()");
-        writeError();
-      }
-
-      if(n != 2) {
-        msSetError(MS_WEBERR, "Not enough arguments for imgxy.", "loadForm()");
-        writeError();
-      }
-
-      mapserv->RefPnt.x = getNumeric(tokens[0]);
-      mapserv->RefPnt.y = getNumeric(tokens[1]);
-
-      msFreeCharArray(tokens, 2);
-      
-      if((mapserv->RefPnt.x > (2*mapserv->map->maxsize)) || (mapserv->RefPnt.x < (-2*mapserv->map->maxsize)) || (mapserv->RefPnt.y > (2*mapserv->map->maxsize)) || (mapserv->RefPnt.y < (-2*mapserv->map->maxsize))) {
-        msSetError(MS_WEBERR, "Reference map coordinate out of range.", "loadForm()");
-        writeError();
-      }
-      
-      mapserv->CoordSource = FROMREFPNT;
-      continue;
-    }
-
-    if(strcasecmp(mapserv->request->ParamNames[i],"buffer") == 0) { /* radius (map units), actually 1/2 square side */
-      mapserv->Buffer = getNumeric(mapserv->request->ParamValues[i]);      
-      mapserv->CoordSource = FROMBUF;
-      QueryCoordSource = FROMUSERPNT;
-      continue;
-    }
-
-    if(strcasecmp(mapserv->request->ParamNames[i],"scale") == 0 || strcasecmp(mapserv->request->ParamNames[i],"scaledenom") == 0) { /* scale for new map */
-      mapserv->ScaleDenom = getNumeric(mapserv->request->ParamValues[i]);      
-      if(mapserv->ScaleDenom <= 0) {
-        msSetError(MS_WEBERR, "Scale out of range.", "loadForm()");
-        writeError();
-      }
-      mapserv->CoordSource = FROMSCALE;
-      QueryCoordSource = FROMUSERPNT;
-      continue;
-    }
-    
-    if(strcasecmp(mapserv->request->ParamNames[i],"imgsize") == 0) { /* size of existing image (pixels) */
-      tokens = msStringSplit(mapserv->request->ParamValues[i], ' ', &n);
-
-      if(!tokens) {
-        msSetError(MS_MEMERR, NULL, "loadForm()");
-        writeError();
-      }
-
-      if(n != 2) {
-        msSetError(MS_WEBERR, "Not enough arguments for imgsize.", "loadForm()");
-        writeError();
-      }
-
-      mapserv->ImgCols = (int)getNumeric(tokens[0]);
-      mapserv->ImgRows = (int)getNumeric(tokens[1]);
-
-      msFreeCharArray(tokens, 2);
-      
-      if(mapserv->ImgCols > mapserv->map->maxsize || mapserv->ImgRows > mapserv->map->maxsize || mapserv->ImgCols <= 0 || mapserv->ImgRows <= 0) {
-        msSetError(MS_WEBERR, "Image size out of range.", "loadForm()");
-        writeError();
-      }
- 
-      continue;
-    }
-
-    if(strcasecmp(mapserv->request->ParamNames[i],"mapsize") == 0) { /* size of new map (pixels) */
-      tokens = msStringSplit(mapserv->request->ParamValues[i], ' ', &n);
-
-      if(!tokens) {
-        msSetError(MS_MEMERR, NULL, "loadForm()");
-        writeError();
-      }
-
-      if(n != 2) {
-        msSetError(MS_WEBERR, "Not enough arguments for mapsize.", "loadForm()");
-        writeError();
-      }
-
-      mapserv->map->width = (int)getNumeric(tokens[0]);
-      mapserv->map->height = (int)getNumeric(tokens[1]);
-
-      msFreeCharArray(tokens, 2);
-      
-      if(mapserv->map->width > mapserv->map->maxsize || mapserv->map->height > mapserv->map->maxsize || mapserv->map->width <= 0 || mapserv->map->height <= 0) {
-        msSetError(MS_WEBERR, "Image size out of range.", "loadForm()");
-        writeError();
-      }
-      continue;
-    }
-
-    if(strncasecmp(mapserv->request->ParamNames[i],"layers", 6) == 0) { /* turn a set of layers, delimited by spaces, on */
-
-      /* If layers=all then turn on all layers */
-      if (strcasecmp(mapserv->request->ParamValues[i], "all") == 0 && mapserv->map != NULL) {
-        int l;
-
-        /* Reset NumLayers=0. If individual layers were already selected then free the previous values.  */
-        for(l=0; l<mapserv->NumLayers; l++)
-          msFree(mapserv->Layers[l]);
-        mapserv->NumLayers=0;
-
-        for(mapserv->NumLayers=0; mapserv->NumLayers < mapserv->map->numlayers; mapserv->NumLayers++) {
-          if(msGrowMapservLayers(mapserv) == MS_FAILURE)
-            writeError();
-
-          if(GET_LAYER(mapserv->map, mapserv->NumLayers)->name) {
-            mapserv->Layers[mapserv->NumLayers] = msStrdup(GET_LAYER(mapserv->map, mapserv->NumLayers)->name);
-          } else {
-            mapserv->Layers[mapserv->NumLayers] = msStrdup("");
-          }
-        }
-      } else {
-        int num_layers=0, l;
-        char **layers=NULL;
-
-        layers = msStringSplit(mapserv->request->ParamValues[i], ' ', &(num_layers));
-        for(l=0; l<num_layers; l++) {
-          if(msGrowMapservLayers(mapserv) == MS_FAILURE)
-            writeError();
-          mapserv->Layers[mapserv->NumLayers++] = msStrdup(layers[l]);
-        }
-
-        msFreeCharArray(layers, num_layers);
-        num_layers = 0;
-      }
-
-      continue;
-    }
-
-    if(strncasecmp(mapserv->request->ParamNames[i],"layer", 5) == 0) { /* turn a single layer/group on */
-      if(msGrowMapservLayers(mapserv) == MS_FAILURE)
-        writeError();
-      mapserv->Layers[mapserv->NumLayers] = msStrdup(mapserv->request->ParamValues[i]);
-      mapserv->NumLayers++;
-      continue;
-    }
-
-    if(strcasecmp(mapserv->request->ParamNames[i],"qlayer") == 0) { /* layer to query (i.e search) */
-      QueryLayer = msStrdup(mapserv->request->ParamValues[i]);
-      continue;
-    }
-
-    if(strcasecmp(mapserv->request->ParamNames[i],"qitem") == 0) { /* attribute to query on (optional) */
-      QueryItem = msStrdup(mapserv->request->ParamValues[i]);
-      continue;
-    }
-
-    if(strcasecmp(mapserv->request->ParamNames[i],"qstring") == 0) { /* attribute query string */
-      QueryString = msStrdup(mapserv->request->ParamValues[i]);
-      continue;
-    }
-
-    if(strcasecmp(mapserv->request->ParamNames[i],"qformat") == 0) { /* format to apply to query results (shortcut instead of having to use "map.web=QUERYFORMAT+foo") */
-      if(mapserv->map->web.queryformat) free(mapserv->map->web.queryformat); /* avoid leak */
-      mapserv->map->web.queryformat = msStrdup(mapserv->request->ParamValues[i]);
-      continue;
-    }
-
-    if(strcasecmp(mapserv->request->ParamNames[i],"slayer") == 0) { /* layer to select (for feature based search) */
-      SelectLayer = msStrdup(mapserv->request->ParamValues[i]);
-      continue;
-    }
-
-    if(strcasecmp(mapserv->request->ParamNames[i],"shapeindex") == 0) { /* used for index queries */
-      ShapeIndex = (int)getNumeric(mapserv->request->ParamValues[i]);
-      continue;
-    }
-    if(strcasecmp(mapserv->request->ParamNames[i],"tileindex") == 0) {
-      TileIndex = (int)getNumeric(mapserv->request->ParamValues[i]);
-      continue;
-    }
-
-    /* -------------------------------------------------------------------- 
-     *   The following code is used to support mode=tile                    
-     * -------------------------------------------------------------------- */ 
-
-    if(strcasecmp(mapserv->request->ParamNames[i], "tilemode") == 0) { 
-      /* currently, only valid tilemode is "spheremerc" */
-      if( strcasecmp(mapserv->request->ParamValues[i], "gmap") == 0) {
-        mapserv->TileMode = TILE_GMAP;
-      } else if ( strcasecmp(mapserv->request->ParamValues[i], "ve") == 0 ) {
-        mapserv->TileMode = TILE_VE;
-      } else {
-        msSetError(MS_WEBERR, "Invalid tilemode. Use one of: gmap, ve", "loadForm()");
-        writeError();
-      }
-      continue;
-    }
-
-    if(strcasecmp(mapserv->request->ParamNames[i],"tile") == 0) { 
-
-      if( strlen(mapserv->request->ParamValues[i]) < 1 ) {
-        msSetError(MS_WEBERR, "Empty tile parameter.", "loadForm()");
-        writeError();
-      }
-      mapserv->CoordSource = FROMTILE;
-      mapserv->TileCoords = msStrdup(mapserv->request->ParamValues[i]);
-      
-      continue;
-    }
-
-    /* -------------------------------------------------------------------- */
-    /*      The following code is used to support the rosa applet (for      */
-    /*      more information on Rosa, please consult :                      */
-    /*      http://www.maptools.org/rosa/) .                                */
-    /*      This code was provided by Tim.Mackey at agso.gov.au.               */
-    /*                                                                      */
-    /*      For Application using it can be seen at :                       */    
-    /*        http://www.agso.gov.au/map/pilbara/                           */
-    /*                                                                      */
-    /* -------------------------------------------------------------------- */
-
-    if(strcasecmp(mapserv->request->ParamNames[i],"INPUT_TYPE") == 0)
-    { /* Rosa input type */
-        if(strcasecmp(mapserv->request->ParamValues[i],"auto_rect") == 0) 
-        {
-            rosa_type=1; /* rectangle */
-            continue;
-        }
-            
-        if(strcasecmp(mapserv->request->ParamValues[i],"auto_point") == 0) 
-        {
-            rosa_type=2; /* point */
-            continue;
-        }
-    }
-    if(strcasecmp(mapserv->request->ParamNames[i],"INPUT_COORD") == 0) 
-    { /* Rosa coordinates */
- 
-       switch(rosa_type)
-       {
-         case 1:
-             sscanf(mapserv->request->ParamValues[i],"%lf,%lf;%lf,%lf",
-                    &mapserv->ImgBox.minx,&mapserv->ImgBox.miny,&mapserv->ImgBox.maxx,
-                    &mapserv->ImgBox.maxy);
-             if((mapserv->ImgBox.minx != mapserv->ImgBox.maxx) && 
-                (mapserv->ImgBox.miny != mapserv->ImgBox.maxy)) 
-             {
-                 mapserv->CoordSource = FROMIMGBOX;
-                 QueryCoordSource = FROMIMGBOX;
-             }
-             else 
-             {
-                 mapserv->CoordSource = FROMIMGPNT;
-                 QueryCoordSource = FROMIMGPNT;
-                 mapserv->ImgPnt.x=mapserv->ImgBox.minx;
-                 mapserv->ImgPnt.y=mapserv->ImgBox.miny;
-       }
-           break;
-         case 2:
-           sscanf(mapserv->request->ParamValues[i],"%lf,%lf",&mapserv->ImgPnt.x,
-                   &mapserv->ImgPnt.y);
-           mapserv->CoordSource = FROMIMGPNT;
-           QueryCoordSource = FROMIMGPNT;
-           break;
-         }
-       continue;
-    }    
-    /* -------------------------------------------------------------------- */
-    /*      end of code for Rosa support.                                   */
-    /* -------------------------------------------------------------------- */
-
-  } /* next parameter */
-
-  if(mapserv->Mode == ZOOMIN) {
-    mapserv->ZoomDirection = 1;
-    mapserv->Mode = BROWSE;
-  }     
-  if(mapserv->Mode == ZOOMOUT) {
-    mapserv->ZoomDirection = -1;
-    mapserv->Mode = BROWSE;
-  }
-
-  if(ZoomSize != 0) { /* use direction and magnitude to calculate zoom */
-    if(mapserv->ZoomDirection == 0) {
-      mapserv->fZoom = 1;
-    } else {
-      mapserv->fZoom = ZoomSize*mapserv->ZoomDirection;
-      if(mapserv->fZoom < 0)
-        mapserv->fZoom = 1.0/MS_ABS(mapserv->fZoom);
-    }
-  } else { /* use single value for zoom */
-    if((mapserv->Zoom >= -1) && (mapserv->Zoom <= 1)) {
-      mapserv->fZoom = 1; /* pan */
-    } else {
-      if(mapserv->Zoom < 0)
-        mapserv->fZoom = 1.0/MS_ABS(mapserv->Zoom);
-      else
-        mapserv->fZoom = mapserv->Zoom;
-    }
-  }
-
-  if(mapserv->ImgRows == -1) mapserv->ImgRows = mapserv->map->height;
-  if(mapserv->ImgCols == -1) mapserv->ImgCols = mapserv->map->width;  
-  if(mapserv->map->height == -1) mapserv->map->height = mapserv->ImgRows;
-  if(mapserv->map->width == -1) mapserv->map->width = mapserv->ImgCols;  
-}
-
-void setExtentFromShapes(void) {
-  int found=0;
-  double dx, dy, cellsize;
-
-  rectObj tmpext={-1.0,-1.0,-1.0,-1.0};
-  pointObj tmppnt={-1.0,-1.0};
-
-  found = msGetQueryResultBounds(mapserv->map, &(tmpext));
-
-  dx = tmpext.maxx - tmpext.minx;
-  dy = tmpext.maxy - tmpext.miny;
- 
-  tmppnt.x = (tmpext.maxx + tmpext.minx)/2;
-  tmppnt.y = (tmpext.maxy + tmpext.miny)/2;
-  tmpext.minx -= dx*EXTENT_PADDING/2.0;
-  tmpext.maxx += dx*EXTENT_PADDING/2.0;
-  tmpext.miny -= dy*EXTENT_PADDING/2.0;
-  tmpext.maxy += dy*EXTENT_PADDING/2.0;
-
-  if(mapserv->ScaleDenom != 0) { /* apply the scale around the center point (tmppnt) */
-    cellsize = (mapserv->ScaleDenom/mapserv->map->resolution)/msInchesPerUnit(mapserv->map->units,0); /* user supplied a point and a scale */
-    tmpext.minx = tmppnt.x - cellsize*mapserv->map->width/2.0;
-    tmpext.miny = tmppnt.y - cellsize*mapserv->map->height/2.0;
-    tmpext.maxx = tmppnt.x + cellsize*mapserv->map->width/2.0;
-    tmpext.maxy = tmppnt.y + cellsize*mapserv->map->height/2.0;
-  } else if(mapserv->Buffer != 0) { /* apply the buffer around the center point (tmppnt) */
-    tmpext.minx = tmppnt.x - mapserv->Buffer;
-    tmpext.miny = tmppnt.y - mapserv->Buffer;
-    tmpext.maxx = tmppnt.x + mapserv->Buffer;
-    tmpext.maxy = tmppnt.y + mapserv->Buffer;
-  }
-
-  /* in case we don't get  usable extent at this point (i.e. single point result) */
-  if(!MS_VALID_EXTENT(tmpext)) {
-    if(mapserv->map->web.minscaledenom > 0) { /* try web object minscale first */
-      cellsize = (mapserv->map->web.minscaledenom/mapserv->map->resolution)/msInchesPerUnit(mapserv->map->units,0); /* user supplied a point and a scale */
-      tmpext.minx = tmppnt.x - cellsize*mapserv->map->width/2.0;
-      tmpext.miny = tmppnt.y - cellsize*mapserv->map->height/2.0;
-      tmpext.maxx = tmppnt.x + cellsize*mapserv->map->width/2.0;
-      tmpext.maxy = tmppnt.y + cellsize*mapserv->map->height/2.0;
-    } else {
-      msSetError(MS_WEBERR, "No way to generate a valid map extent from selected shapes.", "mapserv()");
-      writeError();
-    }
-  }
-
-  mapserv->mappnt = tmppnt;
-  mapserv->map->extent = mapserv->RawExt = tmpext; /* save unadjusted extent */
-
-  return;
+  return FCGI_fwrite( data, 1, byteCount, (FCGI_FILE *) cbData );
 }
 
+/************************************************************************/
+/*                    msIO_installFastCGIRedirect()                     */
+/************************************************************************/
+static int msIO_installFastCGIRedirect()
 
-/* FIX: NEED ERROR CHECKING HERE FOR IMGPNT or MAPPNT */
-void setCoordinate(void)
 {
-  double cellx,celly;
-
-  cellx = MS_CELLSIZE(mapserv->ImgExt.minx, mapserv->ImgExt.maxx, mapserv->ImgCols);
-  celly = MS_CELLSIZE(mapserv->ImgExt.miny, mapserv->ImgExt.maxy, mapserv->ImgRows);
+  msIOContext stdin_ctx, stdout_ctx, stderr_ctx;
 
-  mapserv->mappnt.x = MS_IMAGE2MAP_X(mapserv->ImgPnt.x, mapserv->ImgExt.minx, cellx);
-  mapserv->mappnt.y = MS_IMAGE2MAP_Y(mapserv->ImgPnt.y, mapserv->ImgExt.maxy, celly);
+  stdin_ctx.label = "fcgi";
+  stdin_ctx.write_channel = MS_FALSE;
+  stdin_ctx.readWriteFunc = msIO_fcgiRead;
+  stdin_ctx.cbData = (void *) FCGI_stdin;
 
-  return;
-}
+  stdout_ctx.label = "fcgi";
+  stdout_ctx.write_channel = MS_TRUE;
+  stdout_ctx.readWriteFunc = msIO_fcgiWrite;
+  stdout_ctx.cbData = (void *) FCGI_stdout;
 
-void returnCoordinate(pointObj pnt)
-{
-  msSetError(MS_NOERR, 
-             "Your \"<i>click</i>\" corresponds to (approximately): (%g, %g).",
-             NULL, mapserv->mappnt.x, mapserv->mappnt.y);
+  stderr_ctx.label = "fcgi";
+  stderr_ctx.write_channel = MS_TRUE;
+  stderr_ctx.readWriteFunc = msIO_fcgiWrite;
+  stderr_ctx.cbData = (void *) FCGI_stderr;
 
-#ifdef USE_PROJ
-  if(mapserv->map->projection.proj != NULL && !pj_is_latlong(mapserv->map->projection.proj) ) {
-    pointObj p=mapserv->mappnt;
-    msProjectPoint(&(mapserv->map->projection), &(mapserv->map->latlon), &p);
-    msSetError( MS_NOERR, "%s Computed lat/lon value is (%g, %g).\n", NULL, p.x, p.y);
-  }
-#endif
+  msIO_installHandlers( &stdin_ctx, &stdout_ctx, &stderr_ctx );
 
-  writeError();
+  return MS_TRUE;
 }
 
-
-/************************************************************************/
-/*                      FastCGI cleanup functions.                      */
-/************************************************************************/
-#ifndef WIN32
-void msCleanupOnSignal( int nInData )
-{
-  /* For some reason, the fastcgi message code does not seem to work */
-  /* from within the signal handler on Unix.  So we force output through */
-  /* normal stdio functions. */
-  msIO_installHandlers( NULL, NULL, NULL );
-  msIO_fprintf( stderr, "In msCleanupOnSignal.\n" );
-  msCleanup();
-  exit( 0 );
-}
 #endif
-
-#ifdef WIN32
-void msCleanupOnExit( void )
-{
-  /* note that stderr and stdout seem to be non-functional in the */
-  /* fastcgi/win32 case.  If you really want to check functioning do */
-  /* some sort of hack logging like below ... otherwise just trust it! */
-       
-#ifdef notdef
-  FILE *fp_out = fopen( "D:\\temp\\mapserv.log", "w" );
-    
-  fprintf( fp_out, "In msCleanupOnExit\n" );
-  fclose( fp_out );
-#endif    
-  msCleanup();
-}
-#endif
-
 /************************************************************************/
 /*                                main()                                */
 /************************************************************************/
-int main(int argc, char *argv[]) {
-  int i,j, iArg;
-  char buffer[1024];
-  imageObj *img=NULL;
-  int status;
+int main(int argc, char *argv[])
+{
+  int iArg;
   int sendheaders = MS_TRUE;
   struct mstimeval execstarttime, execendtime;
   struct mstimeval requeststarttime, requestendtime;
-  char *service = NULL;
-
+  mapservObj* mapserv = NULL;
   msSetup();
 
   /* Use MS_ERRORFILE and MS_DEBUGLEVEL env vars if set */
   if( msDebugInitFromEnv() != MS_SUCCESS ) {
-    writeError();
-    msCleanup();
+    msCGIWriteError(mapserv);
+    msCleanup(0);
     exit(0);
   }
 
-  if(msGetGlobalDebugLevel() >= MS_DEBUGLEVEL_TUNING) 
-      msGettimeofday(&execstarttime, NULL);
+  if(msGetGlobalDebugLevel() >= MS_DEBUGLEVEL_TUNING)
+    msGettimeofday(&execstarttime, NULL);
 
   /* -------------------------------------------------------------------- */
   /*      Process arguments.  In normal use as a cgi-bin there are no     */
@@ -1145,15 +186,15 @@ int main(int argc, char *argv[]) {
           printf("%s\n", tokens[i]);
         msFreeCharArray(tokens, numtokens);
       } else {
-        writeError();
+        msCGIWriteError(mapserv);
       }
-            
+
       exit(0);
     } else if( strncmp(argv[iArg], "MS_ERRORFILE=", 13) == 0 ) {
-        msSetErrorFile( argv[iArg] + 13, NULL );
+      msSetErrorFile( argv[iArg] + 13, NULL );
     } else if( strncmp(argv[iArg], "MS_DEBUGLEVEL=", 14) == 0) {
       msSetGlobalDebugLevel( atoi(argv[iArg] + 14) );
-    } 
+    }
 #endif /* MS_ENABLE_CGI_CL_DEBUG_ARGS */
     else {
       /* we don't produce a usage message as some web servers pass junk arguments */
@@ -1173,7 +214,7 @@ int main(int argc, char *argv[]) {
 
 #ifdef WIN32
   atexit( msCleanupOnExit );
-#endif    
+#endif
 
   /* In FastCGI case we loop accepting multiple requests.  In normal CGI */
   /* use we only accept and process one request.  */
@@ -1188,20 +229,17 @@ int main(int argc, char *argv[]) {
 
     mapserv->request->NumParams = loadParams(mapserv->request, NULL, NULL, 0, NULL);
     if( mapserv->request->NumParams == -1 ) {
-#ifdef USE_FASTCGI
-      /* FCGI_ --- return to top of loop */
-      msResetErrorList();
-      continue;
-#else
-      /* normal case, processing is complete */
-      msCleanup();
-      exit( 0 );
-#endif
+      msCGIWriteError(mapserv);
+      goto end_request;
     }
 
-    mapserv->map = loadMap();
+    mapserv->map = msCGILoadMap(mapserv);
+    if(!mapserv->map) {
+      msCGIWriteError(mapserv);
+      goto end_request;
+    }
 
-    if( mapserv->map->debug >= MS_DEBUGLEVEL_TUNING) 
+    if( mapserv->map->debug >= MS_DEBUGLEVEL_TUNING)
       msGettimeofday(&requeststarttime, NULL);
 
 #ifdef USE_FASTCGI
@@ -1213,628 +251,46 @@ int main(int argc, char *argv[]) {
     }
 #endif
 
-    /*
-     * RFC-42 HTTP Cookie Forwarding
-     * Here we set the http_cookie_data metadata to handle the 
-     * HTTP Cookie Forwarding. The content of this metadata is the cookie 
-     * content. In the future, this metadata will probably be replaced
-     * by an object that is part of the mapObject that would contain 
-     * information on the application status (such as cookie).
-     */
-    if( mapserv->request->httpcookiedata != NULL )
-    {
-        msInsertHashTable( &(mapserv->map->web.metadata), "http_cookie_data",
-                           mapserv->request->httpcookiedata );
-    }
-
-    /*
-    ** Determine 'mode': Check for MS_MODE env. var. and mode=... CGI param
-    */
-    mapserv->Mode = -1; /* Not set */
-    if( setMode() != MS_SUCCESS)
-        writeError();
-
-    /*
-    ** Start by calling the WMS/WFS/WCS Dispatchers.  If they fail then we'll 
-    ** process this as a regular MapServer request.
-    */
-    if((mapserv->Mode == -1 || mapserv->Mode == OWS || mapserv->Mode == WFS) &&
-       (status = msOWSDispatch(mapserv->map, mapserv->request, 
-                               mapserv->Mode)) != MS_DONE  )  {
-      /*
-      ** OWSDispatch returned either MS_SUCCESS or MS_FAILURE
-      **
-      ** Normally if the OWS service fails it will issue an exception,
-      ** and clear the error stack but still return MS_FAILURE.  But in
-      ** a few situations it can't issue the exception and will instead 
-      ** just an error and let us report it. 
-      */
-      if( status == MS_FAILURE ) {
-        errorObj *ms_error = msGetErrorObj();
-        
-        if( (ms_error->code != MS_NOERR) && (ms_error->isreported == MS_FALSE) )
-          writeError();
-      }
-       
-      /* 
-      ** This was a WMS/WFS request... cleanup and exit 
-      ** At this point any error has already been handled
-      ** as an XML exception by the OGC service.
-      */
-      if(mapserv->map->debug >= MS_DEBUGLEVEL_TUNING) {
-        msGettimeofday(&requestendtime, NULL);
-        msDebug("mapserv request processing time (msLoadMap not incl.): %.3fs\n", 
-                (requestendtime.tv_sec+requestendtime.tv_usec/1.0e6)-
-                (requeststarttime.tv_sec+requeststarttime.tv_usec/1.0e6) );
-      }
-      
-      if (status == MS_SUCCESS &&
-          strcasecmp(mapserv->map->imagetype, "application/openlayers")==0)
-      {
-        for( i=0; i<mapserv->request->NumParams; i++)
-        {
-          if(strcasecmp(mapserv->request->ParamNames[i], "SERVICE") == 0) {
-            service = mapserv->request->ParamValues[i];
-            break;
-          }
-        }
-        if (service && strcasecmp(service,"WMS")==0)
-        {
-          msIO_printf("Content-type: text/html%c%c",10,10);
-          
-          if (msReturnOpenLayersPage(mapserv) != MS_SUCCESS)
-            writeError();
-        }
-      }
-
-      msFreeMapServObj(mapserv);      
-#ifdef USE_FASTCGI
-      /* FCGI_ --- return to top of loop */
-      continue;
-#else
-      /* normal case, processing is complete */
-      if(msGetGlobalDebugLevel() >= MS_DEBUGLEVEL_TUNING) {
-        msGettimeofday(&execendtime, NULL);
-        msDebug("mapserv total execution time: %.3fs\n", 
-                (execendtime.tv_sec+execendtime.tv_usec/1.0e6)-
-                (execstarttime.tv_sec+execstarttime.tv_usec/1.0e6) );
-      }
-      msCleanup();
-      exit( 0 );
-#endif
-    } /* done OGC/OWS case */
-
-    /*
-    ** Do "traditional" mode processing.
-    */
-    if (mapserv->Mode == -1)
-        mapserv->Mode = BROWSE;
 
-    loadForm();
- 
-    if(mapserv->savemap) {
-      snprintf(buffer, sizeof(buffer), "%s%s%s.map", mapserv->map->web.imagepath, mapserv->map->name, mapserv->Id);
-      if(msSaveMap(mapserv->map, buffer) == -1) writeError();
-    }
 
-    if((mapserv->CoordSource == FROMIMGPNT) || (mapserv->CoordSource == FROMIMGBOX)) /* make sure extent of existing image matches shape of image */
-      mapserv->map->cellsize = msAdjustExtent(&mapserv->ImgExt, mapserv->ImgCols, mapserv->ImgRows);
 
-    /*
-    ** For each layer let's set layer status
-    */
-    for(i=0;i<mapserv->map->numlayers;i++) {
-      if((GET_LAYER(mapserv->map, i)->status != MS_DEFAULT)) {
-        if(isOn(mapserv,  GET_LAYER(mapserv->map, i)->name, GET_LAYER(mapserv->map, i)->group) == MS_TRUE) /* Set layer status */
-          GET_LAYER(mapserv->map, i)->status = MS_ON;
-        else
-          GET_LAYER(mapserv->map, i)->status = MS_OFF;
-      }
-    }
-
-    if(mapserv->CoordSource == FROMREFPNT) /* force browse mode if the reference coords are set */
-      mapserv->Mode = BROWSE;
-
-    /*
-    ** Tile mode:
-    ** Set the projection up and test the parameters for legality.
-    */
-    if(mapserv->Mode == TILE) {
-      if( msTileSetup(mapserv) != MS_SUCCESS ) {
-        writeError();
-      }
+    if(msCGIDispatchRequest(mapserv) != MS_SUCCESS) {
+      msCGIWriteError(mapserv);
+      goto end_request;
     }
 
-    if(mapserv->Mode == BROWSE) {
-
-      char *template =  NULL;
-      for(i=0;i<mapserv->request->NumParams;i++) /* find the template param value */
-          if (strcasecmp(mapserv->request->ParamNames[i], "template") == 0)
-              template = mapserv->request->ParamValues[i];
-
-      if ( (!mapserv->map->web.template) && (template==NULL || (strcasecmp(template, "openlayers")!=0)) ) {
-        msSetError(MS_WEBERR, "Traditional BROWSE mode requires a TEMPLATE in the WEB section, but none was provided.", "mapserv()");
-        writeError();
-      }
-
-      if(QueryFile) {
-        status = msLoadQuery(mapserv->map, QueryFile);
-        if(status != MS_SUCCESS) writeError();
-      }
-      
-      setExtent(mapserv);
-      checkWebScale(mapserv);
-       
-      /* -------------------------------------------------------------------- */
-      /*      generate map, legend, scalebar and refernce images.             */
-      /* -------------------------------------------------------------------- */
-      if(msGenerateImages(mapserv, MS_FALSE, MS_TRUE) != MS_SUCCESS)
-        writeError();
-
-      if ( (template != NULL) && (strcasecmp(template, "openlayers")==0) ) {
-        msIO_printf("Content-type: text/html%c%c",10,10);
-        if (msReturnOpenLayersPage(mapserv) != MS_SUCCESS)
-          writeError();
-      }
-      else if(QueryFile) {
-        if(msReturnTemplateQuery(mapserv, mapserv->map->web.queryformat, NULL) != MS_SUCCESS)
-          writeError();
-      } else {
-        if(TEMPLATE_TYPE(mapserv->map->web.template) == MS_FILE) { /* if thers's an html template, then use it */
-          if(mapserv->sendheaders) msIO_printf("Content-type: %s%c%c",  mapserv->map->web.browseformat, 10, 10); /* write MIME header */
-          /* msIO_printf("<!-- %s -->\n", msGetVersion()); */
-          fflush(stdout);
-          if(msReturnPage(mapserv, mapserv->map->web.template, BROWSE, NULL) != MS_SUCCESS)
-            writeError();
-        } else {    
-          if(msReturnURL(mapserv, mapserv->map->web.template, BROWSE) != MS_SUCCESS)
-            writeError();
-        }
-      }
-
-    } else if(mapserv->Mode == MAP || mapserv->Mode == SCALEBAR || mapserv->Mode == REFERENCE || mapserv->Mode == TILE) { /* "image" only modes */
-
-      setExtent(mapserv);
-      checkWebScale(mapserv);
-      
-      switch(mapserv->Mode) {
-      case MAP:
-        if(QueryFile) {
-          status = msLoadQuery(mapserv->map, QueryFile);
-          if(status != MS_SUCCESS) writeError();
-          img = msDrawMap(mapserv->map, MS_TRUE);
-        } else
-          img = msDrawMap(mapserv->map, MS_FALSE);
-        break;
-      case REFERENCE:
-        mapserv->map->cellsize = msAdjustExtent(&(mapserv->map->extent), mapserv->map->width, mapserv->map->height);
-        img = msDrawReferenceMap(mapserv->map);
-        break;      
-      case SCALEBAR:
-        img = msDrawScalebar(mapserv->map);
-        break;
-      case TILE:
-        msTileSetExtent(mapserv);
-        img = msTileDraw(mapserv);
-        break;
-      }
-      
-      if(!img) writeError();
-      
-      /*
-      ** Set the Cache control headers if the option is set. 
-      */
-      if( msLookupHashTable(&(mapserv->map->web.metadata), "http_max_age") ) {
-        msIO_printf("Cache-Control: max-age=%s%c", msLookupHashTable(&(mapserv->map->web.metadata), "http_max_age"), 10);
-      }
-
-      if(mapserv->sendheaders)  {
-        const char *attachment = msGetOutputFormatOption(mapserv->map->outputformat, "ATTACHMENT", NULL ); 
-        if(attachment) msIO_printf("Content-disposition: attachment; filename=%s\n", attachment);
-        msIO_printf("Content-type: %s%c%c", MS_IMAGE_MIME_TYPE(mapserv->map->outputformat), 10,10);
-      }
-            
-      if( mapserv->Mode == MAP || mapserv->Mode == TILE )
-        status = msSaveImage(mapserv->map, img, NULL);
-      else
-        status = msSaveImage(NULL,img, NULL);
-          
-      if(status != MS_SUCCESS) writeError();
-      
-      msFreeImage(img);
-    } else if(mapserv->Mode == LEGEND) {
-      if(mapserv->map->legend.template) {
-        char *legendTemplate;
-
-        legendTemplate = generateLegendTemplate(mapserv);
-        if(legendTemplate) {
-          if(mapserv->sendheaders) msIO_printf("Content-type: %s%c%c", mapserv->map->web.legendformat, 10, 10);
-          msIO_fwrite(legendTemplate, strlen(legendTemplate), 1, stdout);
-
-          free(legendTemplate);
-        } else /* error already generated by (generateLegendTemplate()) */
-          writeError();
-      } else {
-        img = msDrawLegend(mapserv->map, MS_FALSE);
-        if(!img) writeError();
-
-        if(mapserv->sendheaders) msIO_printf("Content-type: %s%c%c", MS_IMAGE_MIME_TYPE(mapserv->map->outputformat), 10,10);
-        status = msSaveImage(NULL, img, NULL);
-        if(status != MS_SUCCESS) writeError();
-
-        msFreeImage(img);
-      }
-    } else if(mapserv->Mode == LEGENDICON) {
-			char **tokens;
-      int numtokens=0;
-      int layerindex=-1, classindex=0;
-      outputFormatObj *format = NULL;
-
-      /* TODO: do we want to set scale here? */
-
-      /* do we have enough information */
-      if(!mapserv->icon) {
-        msSetError(MS_WEBERR, "Mode=LEGENDICON requires an icon parameter.", "mapserv()");
-        writeError();
-      }
-
-      /* process the icon definition */
-      tokens = msStringSplit(mapserv->icon, ',', &numtokens);
-
-      if(numtokens != 1 && numtokens != 2) {
-        msSetError(MS_WEBERR, "%d Malformed icon parameter, should be 'layer,class' or just 'layer' if the layer has only 1 class defined.", "mapserv()", numtokens);
-        writeError();
-      }
-
-      if((layerindex = msGetLayerIndex(mapserv->map, tokens[0])) == -1) {
-        msSetError(MS_WEBERR, "Icon layer=%s not found in mapfile.", "mapserv()", tokens[0]);
-        writeError();
-      }
-
-      if(numtokens == 2) { /* check the class index */
-        classindex = atoi(tokens[1]);
-        if(classindex >= GET_LAYER(mapserv->map, layerindex)->numclasses) {
-          msSetError(MS_WEBERR, "Icon class=%d not found in layer=%s.", "mapserv()", classindex, GET_LAYER(mapserv->map, layerindex)->name);
-          writeError();
-        }
-      }
-
-      /* ensure we have an image format representing the options for the legend. */
-      msApplyOutputFormat(&format, mapserv->map->outputformat, mapserv->map->legend.transparent, mapserv->map->legend.interlace, MS_NOOVERRIDE);
-
-      /* initialize the legend image */
-      if( ! MS_RENDERER_PLUGIN(format) ) {
-    	  msSetError(MS_RENDERERERR, "unsupported renderer for legend icon", "mapserv main()");
-    	  writeError();
-      }
-      img = msImageCreate(mapserv->map->legend.keysizex, mapserv->map->legend.keysizey, format,
-    		  mapserv->map->web.imagepath, mapserv->map->web.imageurl, mapserv->map->resolution, mapserv->map->defresolution,
-    		  &(mapserv->map->legend.imagecolor));
-
-      /* drop this reference to output format */
-      msApplyOutputFormat(&format, NULL, MS_NOOVERRIDE, MS_NOOVERRIDE, MS_NOOVERRIDE);
-
-      if(msDrawLegendIcon(mapserv->map, GET_LAYER(mapserv->map, layerindex), GET_LAYER(mapserv->map, layerindex)->class[classindex], mapserv->map->legend.keysizex,  mapserv->map->legend.keysizey, img, 0, 0) != MS_SUCCESS)
-        writeError();
-
-      if(mapserv->sendheaders) msIO_printf("Content-type: %s%c%c", MS_IMAGE_MIME_TYPE(mapserv->map->outputformat), 10,10);
-      status = msSaveImage(NULL, img, NULL);
-      if(status != MS_SUCCESS) writeError();
-
-      msFreeCharArray(tokens, numtokens);
-      msFreeImage(img);
-
-    } else if(mapserv->Mode >= QUERY) { /* query modes */
-      if(QueryFile) { /* already got a completed query */
-        status = msLoadQuery(mapserv->map, QueryFile);
-        if(status != MS_SUCCESS) writeError();
-      } else {
-
-        if((QueryLayerIndex = msGetLayerIndex(mapserv->map, QueryLayer)) != -1) /* force the query layer on */
-          GET_LAYER(mapserv->map, QueryLayerIndex)->status = MS_ON;
-
-        switch(mapserv->Mode) {
-        case ITEMFEATUREQUERY:
-        case ITEMFEATURENQUERY:
-          if((SelectLayerIndex = msGetLayerIndex(mapserv->map, SelectLayer)) == -1) { /* force the selection layer on */
-            msSetError(MS_WEBERR, "Selection layer not set or references an invalid layer.", "mapserv()"); 
-            writeError();
-          }
-          GET_LAYER(mapserv->map, SelectLayerIndex)->status = MS_ON;
-
-          /* validate the qstring parameter */
-          if(msValidateParameter(QueryString, msLookupHashTable(&(GET_LAYER(mapserv->map, SelectLayerIndex)->validation), "qstring"), 
-                                              msLookupHashTable(&(mapserv->map->web.validation), "qstring"), 
-                                              msLookupHashTable(&(GET_LAYER(mapserv->map, SelectLayerIndex)->metadata), "qstring_validation_pattern"), NULL) != MS_SUCCESS) {
-	    msSetError(MS_WEBERR, "Parameter 'qstring' value fails to validate.", "mapserv()");
-	    writeError();
-          }
-
-          if(QueryCoordSource != NONE && !mapserv->UseShapes)
-            setExtent(mapserv); /* set user area of interest */
-
-	  mapserv->map->query.type = MS_QUERY_BY_ATTRIBUTE;
-          if(QueryItem) mapserv->map->query.item = msStrdup(QueryItem);
-          if(QueryString) mapserv->map->query.str = msStrdup(QueryString);
-
-          mapserv->map->query.rect = mapserv->map->extent;
-
-          mapserv->map->query.mode = MS_QUERY_MULTIPLE;
-          if(mapserv->Mode == ITEMFEATUREQUERY)
-            mapserv->map->query.mode = MS_QUERY_SINGLE;
-
-          mapserv->map->query.layer = QueryLayerIndex;
-	  mapserv->map->query.slayer = SelectLayerIndex; /* this will trigger the feature query eventually */
-          break;
-        case FEATUREQUERY:
-        case FEATURENQUERY:
-          if((SelectLayerIndex = msGetLayerIndex(mapserv->map, SelectLayer)) == -1) { /* force the selection layer on */
-            msSetError(MS_WEBERR, "Selection layer not set or references an invalid layer.", "mapserv()"); 
-            writeError();
-          }
-          GET_LAYER(mapserv->map, SelectLayerIndex)->status = MS_ON;
-      
-          if(mapserv->Mode == FEATUREQUERY) {
-            switch(QueryCoordSource) {
-            case FROMIMGPNT:
-              mapserv->map->extent = mapserv->ImgExt; /* use the existing map extent */    
-              setCoordinate();
-              break;
-            case FROMUSERPNT:
-              break;
-            default:
-              msSetError(MS_WEBERR, "No way to perform the initial search, not enough information.", "mapserv()");
-              writeError();
-              break;
-            }      
-
-            mapserv->map->query.type = MS_QUERY_BY_POINT;
-            mapserv->map->query.mode = MS_QUERY_SINGLE;
-
-            mapserv->map->query.point = mapserv->mappnt;
-	    mapserv->map->query.buffer = mapserv->Buffer;
-
-            mapserv->map->query.layer = QueryLayerIndex;
-	    mapserv->map->query.slayer = SelectLayerIndex; /* this will trigger the feature query eventually */
-          } else { /* FEATURENQUERY */
-            switch(QueryCoordSource) {
-            case FROMIMGPNT:
-              mapserv->map->extent = mapserv->ImgExt; /* use the existing map extent */    
-              setCoordinate();
-              mapserv->map->query.type = MS_QUERY_BY_POINT;
-              break;     
-            case FROMIMGBOX:
-              /* TODO: this option was present but with no code to leverage the image box... */
-              break;
-            case FROMUSERPNT:
-              mapserv->map->query.type = MS_QUERY_BY_POINT;
-            default:
-              setExtent(mapserv);
-              mapserv->map->query.type = MS_QUERY_BY_RECT;
-              break;
-            }
-          }
-
-          mapserv->map->query.mode = MS_QUERY_MULTIPLE;
-
-          mapserv->map->query.rect = mapserv->map->extent;
-          mapserv->map->query.point = mapserv->mappnt;
-          mapserv->map->query.buffer = mapserv->Buffer;
-
-          mapserv->map->query.layer = QueryLayerIndex;
-	  mapserv->map->query.slayer = SelectLayerIndex;
-          break;
-        case ITEMQUERY:
-        case ITEMNQUERY:
-          if(QueryLayerIndex < 0 || QueryLayerIndex >= mapserv->map->numlayers) {
-            msSetError(MS_WEBERR, "Query layer not set or references an invalid layer.", "mapserv()"); 
-            writeError();
-          }
-
-	  /* validate the qstring parameter */
-          if(msValidateParameter(QueryString, msLookupHashTable(&(GET_LAYER(mapserv->map, QueryLayerIndex)->validation), "qstring"),
-				 msLookupHashTable(&(mapserv->map->web.validation), "qstring"),
-				 msLookupHashTable(&(GET_LAYER(mapserv->map, QueryLayerIndex)->metadata), "qstring_validation_pattern"), NULL) != MS_SUCCESS) {
-            msSetError(MS_WEBERR, "Parameter 'qstring' value fails to validate.", "mapserv()");
-            writeError();
-          }
-
-          if(QueryCoordSource != NONE && !mapserv->UseShapes)
-            setExtent(mapserv); /* set user area of interest */
 
-	  mapserv->map->query.type = MS_QUERY_BY_ATTRIBUTE;
-	  mapserv->map->query.layer = QueryLayerIndex;
-          if(QueryItem) mapserv->map->query.item = msStrdup(QueryItem);
-          if(QueryString) mapserv->map->query.str = msStrdup(QueryString);
-
-	  mapserv->map->query.rect = mapserv->map->extent;
-
-	  mapserv->map->query.mode = MS_QUERY_MULTIPLE;
-          if(mapserv->Mode == ITEMQUERY) mapserv->map->query.mode = MS_QUERY_SINGLE;
-          break;
-        case NQUERY:
-          mapserv->map->query.mode = MS_QUERY_MULTIPLE; /* all of these cases return multiple results */
-          mapserv->map->query.layer = QueryLayerIndex;
-
-          switch(QueryCoordSource) {
-          case FROMIMGPNT:      
-            setCoordinate();
-            
-            if(SearchMap) { /* compute new extent, pan etc then search that extent */
-              setExtent(mapserv);
-              mapserv->map->cellsize = msAdjustExtent(&(mapserv->map->extent), mapserv->map->width, mapserv->map->height);
-              if((status = msCalculateScale(mapserv->map->extent, mapserv->map->units, mapserv->map->width, mapserv->map->height, mapserv->map->resolution, &mapserv->map->scaledenom)) != MS_SUCCESS) writeError();
-              mapserv->map->query.rect = mapserv->map->extent;
-	      mapserv->map->query.type = MS_QUERY_BY_RECT; 
-            } else {
-              mapserv->map->extent = mapserv->ImgExt; /* use the existing image parameters */
-              mapserv->map->width = mapserv->ImgCols;
-              mapserv->map->height = mapserv->ImgRows;
-              if((status = msCalculateScale(mapserv->map->extent, mapserv->map->units, mapserv->map->width, mapserv->map->height, mapserv->map->resolution, &mapserv->map->scaledenom)) != MS_SUCCESS) writeError();     
-              mapserv->map->query.point = mapserv->mappnt;
-              mapserv->map->query.type = MS_QUERY_BY_POINT;
-            }
-
-            break;      
-          case FROMIMGBOX:      
-            if(SearchMap) { /* compute new extent, pan etc then search that extent */
-              setExtent(mapserv);
-              if((status = msCalculateScale(mapserv->map->extent, mapserv->map->units, mapserv->map->width, mapserv->map->height, mapserv->map->resolution, &mapserv->map->scaledenom)) != MS_SUCCESS) writeError();
-              mapserv->map->cellsize = msAdjustExtent(&(mapserv->map->extent), mapserv->map->width, mapserv->map->height);
-              mapserv->map->query.rect = mapserv->map->extent;
-              mapserv->map->query.type = MS_QUERY_BY_RECT;
-            } else {
-              double cellx, celly;
-        
-              mapserv->map->extent = mapserv->ImgExt; /* use the existing image parameters */
-              mapserv->map->width = mapserv->ImgCols;
-              mapserv->map->height = mapserv->ImgRows;
-              if((status = msCalculateScale(mapserv->map->extent, mapserv->map->units, mapserv->map->width, mapserv->map->height, mapserv->map->resolution, &mapserv->map->scaledenom)) != MS_SUCCESS) writeError();    
-              cellx = MS_CELLSIZE(mapserv->ImgExt.minx, mapserv->ImgExt.maxx, mapserv->ImgCols); /* calculate the new search extent */
-              celly = MS_CELLSIZE(mapserv->ImgExt.miny, mapserv->ImgExt.maxy, mapserv->ImgRows);
-              mapserv->RawExt.minx = MS_IMAGE2MAP_X(mapserv->ImgBox.minx, mapserv->ImgExt.minx, cellx);          
-              mapserv->RawExt.maxx = MS_IMAGE2MAP_X(mapserv->ImgBox.maxx, mapserv->ImgExt.minx, cellx);
-              mapserv->RawExt.maxy = MS_IMAGE2MAP_Y(mapserv->ImgBox.miny, mapserv->ImgExt.maxy, celly); /* y's are flip flopped because img/map coordinate systems are */
-              mapserv->RawExt.miny = MS_IMAGE2MAP_Y(mapserv->ImgBox.maxy, mapserv->ImgExt.maxy, celly);
-
-              mapserv->map->query.rect = mapserv->RawExt;
-              mapserv->map->query.type = MS_QUERY_BY_RECT;
-            }
-            break;
-          case FROMIMGSHAPE:
-            mapserv->map->extent = mapserv->ImgExt; /* use the existing image parameters */
-            mapserv->map->width = mapserv->ImgCols;
-            mapserv->map->height = mapserv->ImgRows;
-            mapserv->map->cellsize = msAdjustExtent(&(mapserv->map->extent), mapserv->map->width, mapserv->map->height);
-            if((status = msCalculateScale(mapserv->map->extent, mapserv->map->units, mapserv->map->width, mapserv->map->height, mapserv->map->resolution, &mapserv->map->scaledenom)) != MS_SUCCESS) writeError();
-      
-            /* convert from image to map coordinates here (see setCoordinate) */
-            for(i=0; i<mapserv->map->query.shape->numlines; i++) {
-              for(j=0; j<mapserv->map->query.shape->line[i].numpoints; j++) {
-                mapserv->map->query.shape->line[i].point[j].x = MS_IMAGE2MAP_X(mapserv->map->query.shape->line[i].point[j].x, mapserv->map->extent.minx, mapserv->map->cellsize);
-                mapserv->map->query.shape->line[i].point[j].y = MS_IMAGE2MAP_Y(mapserv->map->query.shape->line[i].point[j].y, mapserv->map->extent.maxy, mapserv->map->cellsize);             
-              }
-            }
-
-            mapserv->map->query.type = MS_QUERY_BY_SHAPE;
-            break;      
-          case FROMUSERPNT:
-            if(mapserv->Buffer == 0) { /* do a *pure* point query */
-	      mapserv->map->query.point = mapserv->mappnt;
-              mapserv->map->query.type = MS_QUERY_BY_POINT;
-              setExtent(mapserv);
-            } else {
-              setExtent(mapserv);
-              if(SearchMap) { /* the extent should be tied to a map, so we need to "adjust" it */
-                if((status = msCalculateScale(mapserv->map->extent, mapserv->map->units, mapserv->map->width, mapserv->map->height, mapserv->map->resolution, &mapserv->map->scaledenom)) != MS_SUCCESS) writeError();
-                mapserv->map->cellsize = msAdjustExtent(&(mapserv->map->extent), mapserv->map->width, mapserv->map->height); 
-              }
-              mapserv->map->query.rect = mapserv->map->extent;
-              mapserv->map->query.type = MS_QUERY_BY_RECT;
-            }
-            break;
-          case FROMUSERSHAPE:
-            setExtent(mapserv);
-            mapserv->map->query.type = MS_QUERY_BY_SHAPE;
-            break;
-          default: /* from an extent of some sort */
-            setExtent(mapserv);
-            if(SearchMap) { /* the extent should be tied to a map, so we need to "adjust" it */
-              if((status = msCalculateScale(mapserv->map->extent, mapserv->map->units, mapserv->map->width, mapserv->map->height, mapserv->map->resolution, &mapserv->map->scaledenom)) != MS_SUCCESS) writeError();
-              mapserv->map->cellsize = msAdjustExtent(&(mapserv->map->extent), mapserv->map->width, mapserv->map->height);
-            }
-
-	    mapserv->map->query.rect = mapserv->map->extent;
-	    mapserv->map->query.type = MS_QUERY_BY_RECT;
-            break;
-	  }
-          break;
-        case QUERY:
-          switch(QueryCoordSource) {
-          case FROMIMGPNT:
-            setCoordinate();
-            mapserv->map->extent = mapserv->ImgExt; /* use the existing image parameters */
-            mapserv->map->width = mapserv->ImgCols;
-            mapserv->map->height = mapserv->ImgRows;
-            if((status = msCalculateScale(mapserv->map->extent, mapserv->map->units, mapserv->map->width, mapserv->map->height, mapserv->map->resolution, &mapserv->map->scaledenom)) != MS_SUCCESS) writeError();
-            break;
-          case FROMUSERPNT: /* only a buffer makes sense, DOES IT? */    
-            setExtent(mapserv);    
-            break;
-          default:
-            msSetError(MS_WEBERR, "Query mode needs a point, imgxy and mapxy are not set.", "mapserv()");
-            writeError();
-            break;
-          }
-
-          mapserv->map->query.type = MS_QUERY_BY_POINT;
-          mapserv->map->query.mode = MS_QUERY_SINGLE;
-          mapserv->map->query.layer = QueryLayerIndex;
-          mapserv->map->query.point = mapserv->mappnt;
-          mapserv->map->query.buffer = mapserv->Buffer;          
-          break;
-        case INDEXQUERY:
-          mapserv->map->query.type = MS_QUERY_BY_INDEX;
-          mapserv->map->query.mode = MS_QUERY_SINGLE;
-          mapserv->map->query.layer = QueryLayerIndex;
-          mapserv->map->query.shapeindex = ShapeIndex;
-          mapserv->map->query.tileindex = TileIndex;
-          break;
-        } /* end mode switch */
-
-        /* finally execute the query */
-        if((status = msExecuteQuery(mapserv->map)) != MS_SUCCESS) writeError();
-      }
-      
-      if(mapserv->map->querymap.width != -1) mapserv->map->width = mapserv->map->querymap.width; /* make sure we use the right size */
-      if(mapserv->map->querymap.height != -1) mapserv->map->height = mapserv->map->querymap.height;
-
-      if(mapserv->UseShapes)
-        setExtentFromShapes();
-
-      if(msReturnTemplateQuery(mapserv, mapserv->map->web.queryformat, NULL) != MS_SUCCESS) writeError();
-          
-      if(mapserv->savequery) {
-        snprintf(buffer, sizeof(buffer), "%s%s%s%s", mapserv->map->web.imagepath, mapserv->map->name, mapserv->Id, MS_QUERY_EXTENSION);
-        if((status = msSaveQuery(mapserv->map, buffer, MS_FALSE)) != MS_SUCCESS) return status;
+end_request:
+    if(mapserv) {
+      if(mapserv->map && mapserv->map->debug >= MS_DEBUGLEVEL_TUNING) {
+        msGettimeofday(&requestendtime, NULL);
+        msDebug("mapserv request processing time (msLoadMap not incl.): %.3fs\n",
+                (requestendtime.tv_sec+requestendtime.tv_usec/1.0e6)-
+                (requeststarttime.tv_sec+requeststarttime.tv_usec/1.0e6) );
       }
-      
-    } else if(mapserv->Mode == COORDINATE) {
-      setCoordinate(); /* mouse click => map coord */
-      returnCoordinate(mapserv->mappnt);
-    }
-
-    writeLog(MS_FALSE);
-   
-    /* Clean-up (the following are not stored as part of the mapserv) */
-    if(QueryItem) free(QueryItem);
-    if(QueryString) free(QueryString);
-    if(QueryLayer) free(QueryLayer);
-    if(SelectLayer) free(SelectLayer);
-    if(QueryFile) free(QueryFile);
-
-    if(mapserv->map->debug >= MS_DEBUGLEVEL_TUNING) {
-      msGettimeofday(&requestendtime, NULL);
-      msDebug("mapserv request processing time (loadmap not incl.): %.3fs\n", 
-              (requestendtime.tv_sec+requestendtime.tv_usec/1.0e6)-
-              (requeststarttime.tv_sec+requeststarttime.tv_usec/1.0e6) );
+      msCGIWriteLog(mapserv,MS_FALSE);
+      msFreeMapServObj(mapserv);
     }
-
-    msFreeMapServObj(mapserv);
-
 #ifdef USE_FASTCGI
+    /* FCGI_ --- return to top of loop */
     msResetErrorList();
-  }
+    continue;
+  } /* end fastcgi loop */
 #endif
 
+  /* normal case, processing is complete */
   if(msGetGlobalDebugLevel() >= MS_DEBUGLEVEL_TUNING) {
     msGettimeofday(&execendtime, NULL);
-    msDebug("mapserv total execution time: %.3fs\n", 
+    msDebug("mapserv total execution time: %.3fs\n",
             (execendtime.tv_sec+execendtime.tv_usec/1.0e6)-
             (execstarttime.tv_sec+execstarttime.tv_usec/1.0e6) );
   }
+  msCleanup(0);
 
-  msCleanup();
+#ifdef _WIN32
+  /* flush pending writes to stdout */
+  fflush(stdout);
+#endif
 
-  exit(0); /* end MapServer */
-} 
+  exit( 0 );
+}
diff --git a/mapserv.h b/mapserv.h
index a674c54..845a544 100644
--- a/mapserv.h
+++ b/mapserv.h
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -47,37 +47,26 @@
 #define NUMEXP "[-]?(([0-9]+)|([0-9]*[.][0-9]+)([eE][-+]?[0-9]+)?)"
 #define EXTENT_PADDING .05
 
-extern int enter_string;
-
 /*
 ** Macros
 */
 #define TEMPLATE_TYPE(s)  (((strncmp("http://", s, 7) == 0) || (strncmp("https://", s, 8) == 0) || (strncmp("ftp://", s, 6)) == 0)  ? MS_URL : MS_FILE)
 
-/*
-** Enumerated types, keep the query modes in sequence and at the end of the enumeration (mode enumeration is in maptemplate.h).
-*/
-int numModes = 21;
-static char *modeStrings[21] = {"BROWSE","ZOOMIN","ZOOMOUT","MAP","LEGEND","LEGENDICON","REFERENCE","SCALEBAR","COORDINATE",
-                                "QUERY","NQUERY","ITEMQUERY","ITEMNQUERY",
-				"FEATUREQUERY","FEATURENQUERY","ITEMFEATUREQUERY","ITEMFEATURENQUERY",
-				"INDEXQUERY","TILE","OWS", "WFS"};
-
-/*
-** Global variables
-*/
-int SearchMap=MS_FALSE; /* apply pan/zoom BEFORE doing the query (e.g. query the output image rather than the input image) */
-
-char *QueryFile=NULL;
-char *QueryLayer=NULL, *SelectLayer=NULL;
-int QueryLayerIndex=-1, SelectLayerIndex=-1;
+MS_DLL_EXPORT int msCGIWriteLog(mapservObj *mapserv, int show_error);
+MS_DLL_EXPORT void msCGIWriteError(mapservObj *mapserv);
+MS_DLL_EXPORT mapObj *msCGILoadMap(mapservObj *mapserv);
+int msCGISetMode(mapservObj *mapserv);
+int msCGILoadForm(mapservObj *mapserv);
+int msCGIDispatchBrowseRequest(mapservObj *mapserv);
+int msCGIDispatchCoordinateRequest(mapservObj *mapserv);
+int msCGIDispatchQueryRequest(mapservObj *mapserv);
+int msCGIDispatchImageRequest(mapservObj *mapserv);
+int msCGIDispatchLegendRequest(mapservObj *mapserv);
+int msCGIDispatchLegendIconRequest(mapservObj *mapserv);
+MS_DLL_EXPORT int msCGIDispatchRequest(mapservObj *mapserv);
 
-char *QueryItem=NULL, *QueryString=NULL;
 
-int ShapeIndex=-1, TileIndex=-1;
 
-int QueryCoordSource=NONE;
 
-int ZoomSize=0; /* zoom absolute magnitude (i.e. > 0) */
 
 #endif /* MAPSERV_H */
diff --git a/mapserver.h b/mapserver.h
index b76671e..a950dc3 100644
--- a/mapserver.h
+++ b/mapserver.h
@@ -14,7 +14,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -30,18 +30,18 @@
 #define MAP_H
 
 /*
-** MapServer version - to be updated for every release 
+** MapServer version - to be updated for every release
 */
-#define MS_VERSION "6.0.3"
+#define MS_VERSION "6.2.0"
 
 #define MS_VERSION_MAJOR    6
-#define MS_VERSION_MINOR    0
-#define MS_VERSION_REV      3
+#define MS_VERSION_MINOR    2
+#define MS_VERSION_REV      0
 
 #define MS_VERSION_NUM (MS_VERSION_MAJOR*10000+MS_VERSION_MINOR*100+MS_VERSION_REV)
 
 
-/* 
+/*
 ** Main includes. If a particular header was needed by several .c files then
 ** I just put it here. What the hell, it works and it's all right here. -SDL-
 */
@@ -65,19 +65,9 @@
 #include <unistd.h>
 #endif
 
-#ifndef DISABLE_CVSID
-#if defined(__GNUC__) && __GNUC__ >= 4
-#  define MS_CVSID(string)     static char ms_cvsid[] __attribute__((used)) = string;
-#else
-#  define MS_CVSID(string)     static char ms_cvsid[] = string; \
-static char *cvsid_aw() { return( cvsid_aw() ? ((char *) NULL) : ms_cvsid ); }
-#endif
-#else
-#  define MS_CVSID(string)
-#endif
-
 #if defined(_WIN32) && !defined(__CYGWIN__)
 #  define MS_DLL_EXPORT     __declspec(dllexport)
+#define USE_MSFREE
 #else
 #define  MS_DLL_EXPORT
 #endif
@@ -90,7 +80,7 @@ static char *cvsid_aw() { return( cvsid_aw() ? ((char *) NULL) : ms_cvsid ); }
 
 #ifdef _WIN32
 #ifndef SIZE_MAX
-#ifdef _WIN64 
+#ifdef _WIN64
 #define SIZE_MAX _UI64_MAX
 #else
 #define SIZE_MAX UINT_MAX
@@ -112,14 +102,13 @@ typedef uint32_t        ms_uint32;
 #if defined(_WIN32) && !defined(__CYGWIN__)
 /* Need to use _vsnprintf() with VS2003 */
 #define vsnprintf _vsnprintf
-#endif 
+#endif
 
 /*forward declaration of rendering object*/
 typedef struct rendererVTableObj rendererVTableObj;
 typedef struct tileCacheObj tileCacheObj;
 
 
-
 /* ms_bitarray is used by the bit mask in mapbit.c */
 typedef ms_uint32 *     ms_bitarray;
 
@@ -134,8 +123,9 @@ typedef ms_uint32 *     ms_bitarray;
 #include "mapproject.h"
 #include "cgiutil.h"
 
-
+#ifdef USE_GD
 #include <gd.h>
+#endif
 
 #if defined USE_PDF
 #include <pdflib.h>
@@ -182,11 +172,13 @@ typedef ms_uint32 *     ms_bitarray;
 extern "C" {
 #endif
 
-/* Memory allocation check utility */
-
+// hide from swig or ruby will choke on the __FUNCTION__ name
+#ifndef SWIG
+  /* Memory allocation check utility */
 #ifndef __FUNCTION__
 #   define __FUNCTION__ "MapServer"
 #endif
+#endif
 
 #define MS_CHECK_ALLOC(var, size, retval)     \
     if (!var) {   \
@@ -202,7 +194,7 @@ extern "C" {
         return;                                                         \
     }
 
-/* General defines, wrapable */
+  /* General defines, wrapable */
 
 #define MS_TRUE 1 /* logical control variables */
 #define MS_FALSE 0
@@ -215,21 +207,24 @@ extern "C" {
 #define MS_YES 1
 #define MS_NO 0
 
-/* For layer transparency, allows alpha transparent pixmaps to be used
-   with RGB map images */
+  /* For layer transparency, allows alpha transparent pixmaps to be used
+     with RGB map images */
 #define MS_GD_ALPHA 1000
 
-/* Number of layer, class and style ptrs to alloc at once in the 
-   corresponding msGrow...() functions. Replaces former MS_MAXLAYERS, 
-   MS_MAXCLASSES and MS_MAXSTYLES with dynamic allocation (see RFC-17). */
+  /* Number of layer, class and style ptrs to alloc at once in the
+     corresponding msGrow...() functions. Replaces former MS_MAXLAYERS,
+     MS_MAXCLASSES and MS_MAXSTYLES with dynamic allocation (see RFC-17). */
 #define MS_LAYER_ALLOCSIZE 64
 #define MS_CLASS_ALLOCSIZE 8
 #define MS_STYLE_ALLOCSIZE 4
+#define MS_LABEL_ALLOCSIZE 2 /* not too common */
 
 #define MS_MAX_LABEL_PRIORITY     10
+#define MS_MAX_LABEL_FONTS     5
 #define MS_DEFAULT_LABEL_PRIORITY 1
+#define MS_LABEL_FORCE_GROUP 2 /* other values are MS_ON/MS_OFF */
 
-/* General defines, not wrapable */
+  /* General defines, not wrapable */
 #ifndef SWIG
 #ifdef USE_XMLMAPFILE
 #define MS_DEFAULT_MAPFILE_PATTERN "\\.(map|xml)$"
@@ -302,7 +297,7 @@ extern "C" {
 #define MS_ISTRING 2006
 #define MS_BINDING 2007
 
-/* string split flags */
+  /* string split flags */
 #define MS_HONOURSTRINGS      0x0001
 #define MS_ALLOWEMPTYTOKENS   0x0002
 #define MS_PRESERVEQUOTES     0x0004
@@ -310,10 +305,10 @@ extern "C" {
 #define MS_STRIPLEADSPACES    0x0010
 #define MS_STRIPENDSPACES     0x0020
 
-/* boolean options for the expression object. */
+  /* boolean options for the expression object. */
 #define MS_EXP_INSENSITIVE 1
 
-/* General macro definitions */
+  /* General macro definitions */
 #define MS_MIN(a,b) (((a)<(b))?(a):(b))
 #define MS_MAX(a,b) (((a)>(b))?(a):(b))
 #define MS_ABS(a) (((a)<0) ? -(a) : (a))
@@ -327,33 +322,34 @@ extern "C" {
 #define msIsNan(x) isnan(x)
 #endif
 
-/* see http://mega-nerd.com/FPcast/ for some discussion of fast
-   conversion to nearest int.  We avoid lrint() for now because it
-   would be hard to include math.h "properly". */
+  /* see http://mega-nerd.com/FPcast/ for some discussion of fast
+     conversion to nearest int.  We avoid lrint() for now because it
+     would be hard to include math.h "properly". */
 
 #if defined(WE_HAVE_THE_C99_LRINT) && !defined(USE_GENERIC_MS_NINT)
 #   define MS_NINT(x) lrint(x)
-/*#   define MS_NINT(x) lround(x) */
+  /*#   define MS_NINT(x) lround(x) */
 #elif defined(_MSC_VER) && defined(_WIN32) && !defined(USE_GENERIC_MS_NINT)
-    static __inline long int MS_NINT (double flt) 
-    {	int intgr;
-  
-    _asm
-        {	fld flt
-                    fistp intgr
-                    } ;
-			
+  static __inline long int MS_NINT (double flt)
+  {
+    int intgr;
+
+    _asm {
+      fld flt
+      fistp intgr
+    } ;
+
     return intgr ;
-    } 
+  }
 #elif defined(i386) && defined(__GNUC_PREREQ) && !defined(USE_GENERIC_MS_NINT)
-    static __inline long int MS_NINT( double __x ) 
-    {
-        long int __lrintres;                                                        
-        __asm__ __volatile__                                                        
-          ("fistpl %0"                                                              
-           : "=m" (__lrintres) : "t" (__x) : "st");                                 
-        return __lrintres;
-    }
+  static __inline long int MS_NINT( double __x )
+  {
+    long int __lrintres;
+    __asm__ __volatile__
+    ("fistpl %0"
+     : "=m" (__lrintres) : "t" (__x) : "st");
+    return __lrintres;
+  }
 #else
 #  define MS_NINT(x)      MS_NINT_GENERIC(x)
 #endif
@@ -362,10 +358,16 @@ extern "C" {
 #define MS_PEN_TRANSPARENT -1
 #define MS_PEN_UNSET     -4
 
-/* #define MS_VALID_EXTENT(minx, miny, maxx, maxy)  (((minx<maxx) && (miny<maxy))?MS_TRUE:MS_FALSE) */
+  /* #define MS_VALID_EXTENT(minx, miny, maxx, maxy)  (((minx<maxx) && (miny<maxy))?MS_TRUE:MS_FALSE) */
 #define MS_VALID_EXTENT(rect)  (((rect.minx < rect.maxx && rect.miny < rect.maxy))?MS_TRUE:MS_FALSE)
 
+#ifdef USE_GD
 #define MS_INIT_COLOR(color,r,g,b,a) { (color).red = r; (color).green = g; (color).blue = b; (color).pen = MS_PEN_UNSET; (color).alpha=a; }
+#define RESOLVE_PEN_GD(img,color) { if( (color).pen == MS_PEN_UNSET ) msImageSetPenGD( img, &(color) ); }
+  MS_DLL_EXPORT int msImageSetPenGD(gdImagePtr img, colorObj *color);
+#else
+#define MS_INIT_COLOR(color,r,g,b,a) { (color).red = r; (color).green = g; (color).blue = b; (color).alpha=a; }
+#endif
 #define MS_VALID_COLOR(color) (((color).red==-1 || (color).green==-1 || (color).blue==-1)?MS_FALSE:MS_TRUE)
 #define MS_COMPARE_COLOR(color1, color2) (((color2).red==(color1).red && (color2).green==(color1).green && (color2).blue==(color1).blue)?MS_TRUE:MS_FALSE)
 #define MS_TRANSPARENT_COLOR(color) (((color).alpha==0 || (color).red==-255 || (color).green==-255 || (color).blue==-255)?MS_TRUE:MS_FALSE)
@@ -374,8 +376,9 @@ extern "C" {
 
 #define MS_IMAGE_MIME_TYPE(format) (format->mimetype ? format->mimetype : "unknown")
 #define MS_IMAGE_EXTENSION(format)  (format->extension ? format->extension : "unknown")
-
+#ifdef USE_GD
 #define MS_DRIVER_GD(format)  (strncasecmp((format)->driver,"gd/",3)==0)
+#endif
 #define MS_DRIVER_SWF(format) (strncasecmp((format)->driver,"swf",3)==0)
 #define MS_DRIVER_GDAL(format)  (strncasecmp((format)->driver,"gdal/",5)==0)
 #define MS_DRIVER_IMAGEMAP(format)  (strncasecmp((format)->driver,"imagemap",8)==0)
@@ -392,7 +395,7 @@ extern "C" {
 #define MS_RENDER_WITH_TEMPLATE 8 /* query results only */
 #define MS_RENDER_WITH_OGR 16
 
-#define MS_RENDER_WITH_PLUGIN 100 
+#define MS_RENDER_WITH_PLUGIN 100
 #define MS_RENDER_WITH_CAIRO_RASTER   101
 #define MS_RENDER_WITH_CAIRO_PDF 102
 #define MS_RENDER_WITH_CAIRO_SVG 103
@@ -419,17 +422,17 @@ extern "C" {
 #define MS_IMAGE2MAP_X(x,minx,cx) (minx + cx*x)
 #define MS_IMAGE2MAP_Y(y,maxy,cy) (maxy - cy*y)
 
-/* these versions of MS_MAP2IMAGE takes 1/cellsize and is much faster */
+  /* these versions of MS_MAP2IMAGE takes 1/cellsize and is much faster */
 #define MS_MAP2IMAGE_X_IC(x,minx,icx) (MS_NINT((x - minx)*icx))
 #define MS_MAP2IMAGE_Y_IC(y,maxy,icy) (MS_NINT((maxy - y)*icy))
 
 #define MS_MAP2IMAGE_X_IC_DBL(x,minx,icx) ((x - minx)*icx)
 #define MS_MAP2IMAGE_Y_IC_DBL(y,maxy,icy) ((maxy - y)*icy)
-    
+
 #define MS_MAP2IMAGE_X_IC_SNAP(x,minx,icx,res) ((MS_NINT((x - minx)*icx*res))/(res))
 #define MS_MAP2IMAGE_Y_IC_SNAP(y,maxy,icy,res) ((MS_NINT((maxy - y)*icy*res))/(res))
 
-/* For CARTO symbols */
+  /* For CARTO symbols */
 #define MS_PI    3.14159265358979323846
 #define MS_PI2   1.57079632679489661923  /* (MS_PI / 2) */
 #define MS_3PI2  4.71238898038468985769  /* (3 * MS_PI2) */
@@ -438,17 +441,34 @@ extern "C" {
 #define MS_ENCRYPTION_KEY_SIZE  16   /* Key size: 128 bits = 16 bytes */
 
 #define GET_LAYER(map, pos) map->layers[pos]
+#define GET_CLASS(map, lid, cid) map->layers[lid]->class[cid]
 
-#if defined(USE_THREAD) && (__GNUC__*10000 + __GNUC_MINOR__*100 + __GNUC_PATCHLEVEL__) >= 40102
-  // __sync* appeared in GCC 4.1.2
+#if defined(HAVE_SYNC_FETCH_AND_ADD)
 #define MS_REFCNT_INCR(obj) __sync_fetch_and_add(&obj->refcount, +1)
 #define MS_REFCNT_DECR(obj) __sync_sub_and_fetch(&obj->refcount, +1)
 #define MS_REFCNT_INIT(obj) obj->refcount=1, __sync_synchronize()
+#elif defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64))
+#pragma intrinsic (_InterlockedExchangeAdd)
+#if defined(_MSC_VER) && (_MSC_VER <= 1200)
+#define MS_REFCNT_INCR(obj) ( _InterlockedExchangeAdd((long*)(&obj->refcount), (long)(+1)) +1 )
+#define MS_REFCNT_DECR(obj) ( _InterlockedExchangeAdd((long*)(&obj->refcount), (long)(-1)) -1 )
+#define MS_REFCNT_INIT(obj) obj->refcount=1
 #else
+#define MS_REFCNT_INCR(obj) ( _InterlockedExchangeAdd((volatile long*)(&obj->refcount), (long)(+1)) +1 )
+#define MS_REFCNT_DECR(obj) ( _InterlockedExchangeAdd((volatile long*)(&obj->refcount), (long)(-1)) -1 )
+#define MS_REFCNT_INIT(obj) obj->refcount=1
+#endif
+#elif defined(__MINGW32__) && defined(__i386__)
+#define MS_REFCNT_INCR(obj) ( InterlockedExchangeAdd((long*)(&obj->refcount), (long)(+1)) +1 )
+#define MS_REFCNT_DECR(obj) ( InterlockedExchangeAdd((long*)(&obj->refcount), (long)(-1)) -1 )
+#define MS_REFCNT_INIT(obj) obj->refcount=1
+#else
+  // unsafe fallback
 #define MS_REFCNT_INCR(obj) obj->refcount++
 #define MS_REFCNT_DECR(obj) (--(obj->refcount))
 #define MS_REFCNT_INIT(obj) obj->refcount=1
-#endif
+#endif // close if defined(_MSC..
+
 #define MS_REFCNT_DECR_IS_NOT_ZERO(obj) (MS_REFCNT_DECR(obj))>0
 #define MS_REFCNT_DECR_IS_ZERO(obj) (MS_REFCNT_DECR(obj))<=0
 
@@ -456,55 +476,54 @@ extern "C" {
 
 #endif
 
-/* General enumerated types - needed by scripts */
-enum MS_FILE_TYPE {MS_FILE_MAP, MS_FILE_SYMBOL};
-enum MS_UNITS {MS_INCHES, MS_FEET, MS_MILES, MS_METERS, MS_KILOMETERS, MS_DD, MS_PIXELS, MS_PERCENTAGES, MS_NAUTICALMILES};
-enum MS_SHAPE_TYPE {MS_SHAPE_POINT, MS_SHAPE_LINE, MS_SHAPE_POLYGON, MS_SHAPE_NULL};
-enum MS_LAYER_TYPE {MS_LAYER_POINT, MS_LAYER_LINE, MS_LAYER_POLYGON, MS_LAYER_RASTER, MS_LAYER_ANNOTATION, MS_LAYER_QUERY, MS_LAYER_CIRCLE, MS_LAYER_TILEINDEX, MS_LAYER_CHART};
-enum MS_FONT_TYPE {MS_TRUETYPE, MS_BITMAP};
+  /* General enumerated types - needed by scripts */
+  enum MS_FILE_TYPE {MS_FILE_MAP, MS_FILE_SYMBOL};
+  enum MS_UNITS {MS_INCHES, MS_FEET, MS_MILES, MS_METERS, MS_KILOMETERS, MS_DD, MS_PIXELS, MS_PERCENTAGES, MS_NAUTICALMILES};
+  enum MS_SHAPE_TYPE {MS_SHAPE_POINT, MS_SHAPE_LINE, MS_SHAPE_POLYGON, MS_SHAPE_NULL};
+  enum MS_LAYER_TYPE {MS_LAYER_POINT, MS_LAYER_LINE, MS_LAYER_POLYGON, MS_LAYER_RASTER, MS_LAYER_ANNOTATION, MS_LAYER_QUERY, MS_LAYER_CIRCLE, MS_LAYER_TILEINDEX, MS_LAYER_CHART};
+  enum MS_FONT_TYPE {MS_TRUETYPE, MS_BITMAP};
 
 #define MS_POSITIONS_LENGTH 14
-enum MS_POSITIONS_ENUM {MS_UL=101, MS_LR, MS_UR, MS_LL, MS_CR, MS_CL, MS_UC, MS_LC, MS_CC, MS_AUTO, MS_XY, MS_FOLLOW, MS_NONE, MS_AUTO2}; /* Added MS_FOLLOW for bug #1620 implementation. */
+  enum MS_POSITIONS_ENUM {MS_UL=101, MS_LR, MS_UR, MS_LL, MS_CR, MS_CL, MS_UC, MS_LC, MS_CC, MS_AUTO, MS_XY, MS_FOLLOW, MS_NONE, MS_AUTO2}; /* Added MS_FOLLOW for bug #1620 implementation. */
 
-enum MS_BITMAP_FONT_SIZES {MS_TINY , MS_SMALL, MS_MEDIUM, MS_LARGE, MS_GIANT};
-enum MS_QUERYMAP_STYLES {MS_NORMAL, MS_HILITE, MS_SELECTED};
-enum MS_CONNECTION_TYPE {MS_INLINE, MS_SHAPEFILE, MS_TILED_SHAPEFILE, MS_SDE, MS_OGR, MS_UNUSED_1, MS_POSTGIS, MS_WMS, MS_ORACLESPATIAL, MS_WFS, MS_GRATICULE, MS_MYSQL, MS_RASTER, MS_PLUGIN, MS_UNION };
-enum MS_JOIN_CONNECTION_TYPE {MS_DB_XBASE, MS_DB_CSV, MS_DB_MYSQL, MS_DB_ORACLE, MS_DB_POSTGRES};
-enum MS_JOIN_TYPE {MS_JOIN_ONE_TO_ONE, MS_JOIN_ONE_TO_MANY};
+  enum MS_BITMAP_FONT_SIZES {MS_TINY , MS_SMALL, MS_MEDIUM, MS_LARGE, MS_GIANT};
+  enum MS_QUERYMAP_STYLES {MS_NORMAL, MS_HILITE, MS_SELECTED};
+  enum MS_CONNECTION_TYPE {MS_INLINE, MS_SHAPEFILE, MS_TILED_SHAPEFILE, MS_SDE, MS_OGR, MS_UNUSED_1, MS_POSTGIS, MS_WMS, MS_ORACLESPATIAL, MS_WFS, MS_GRATICULE, MS_MYSQL, MS_RASTER, MS_PLUGIN, MS_UNION, MS_UVRASTER };
+  enum MS_JOIN_CONNECTION_TYPE {MS_DB_XBASE, MS_DB_CSV, MS_DB_MYSQL, MS_DB_ORACLE, MS_DB_POSTGRES};
+  enum MS_JOIN_TYPE {MS_JOIN_ONE_TO_ONE, MS_JOIN_ONE_TO_MANY};
 
 #define MS_SINGLE 0 /* modes for searching (spatial/database) */
 #define MS_MULTIPLE 1
 
-enum MS_QUERY_MODE {MS_QUERY_SINGLE, MS_QUERY_MULTIPLE};
-enum MS_QUERY_TYPE {MS_QUERY_IS_NULL, MS_QUERY_BY_POINT, MS_QUERY_BY_RECT, MS_QUERY_BY_SHAPE, MS_QUERY_BY_ATTRIBUTE, MS_QUERY_BY_INDEX, MS_QUERY_BY_FILTER};
+  enum MS_QUERY_MODE {MS_QUERY_SINGLE, MS_QUERY_MULTIPLE};
+  enum MS_QUERY_TYPE {MS_QUERY_IS_NULL, MS_QUERY_BY_POINT, MS_QUERY_BY_RECT, MS_QUERY_BY_SHAPE, MS_QUERY_BY_ATTRIBUTE, MS_QUERY_BY_INDEX, MS_QUERY_BY_FILTER};
 
-enum MS_ALIGN_VALUE {MS_ALIGN_LEFT, MS_ALIGN_CENTER, MS_ALIGN_RIGHT}; 
+  enum MS_ALIGN_VALUE {MS_ALIGN_LEFT, MS_ALIGN_CENTER, MS_ALIGN_RIGHT};
 
-enum MS_CAPS_JOINS_AND_CORNERS {MS_CJC_NONE, MS_CJC_BEVEL, MS_CJC_BUTT, MS_CJC_MITER, MS_CJC_ROUND, MS_CJC_SQUARE, MS_CJC_TRIANGLE}; 
+  enum MS_CAPS_JOINS_AND_CORNERS {MS_CJC_NONE, MS_CJC_BEVEL, MS_CJC_BUTT, MS_CJC_MITER, MS_CJC_ROUND, MS_CJC_SQUARE, MS_CJC_TRIANGLE};
 
 #define MS_CJC_DEFAULT_CAPS MS_CJC_ROUND
 #define MS_CJC_DEFAULT_JOINS MS_CJC_NONE
 #define MS_CJC_DEFAULT_JOIN_MAXSIZE 3
 
-enum MS_RETURN_VALUE {MS_SUCCESS, MS_FAILURE, MS_DONE};
-enum MS_IMAGEMODE { MS_IMAGEMODE_PC256, MS_IMAGEMODE_RGB, MS_IMAGEMODE_RGBA, MS_IMAGEMODE_INT16, MS_IMAGEMODE_FLOAT32, MS_IMAGEMODE_BYTE, MS_IMAGEMODE_FEATURE, MS_IMAGEMODE_NULL };
+  enum MS_RETURN_VALUE {MS_SUCCESS, MS_FAILURE, MS_DONE};
+  enum MS_IMAGEMODE { MS_IMAGEMODE_PC256, MS_IMAGEMODE_RGB, MS_IMAGEMODE_RGBA, MS_IMAGEMODE_INT16, MS_IMAGEMODE_FLOAT32, MS_IMAGEMODE_BYTE, MS_IMAGEMODE_FEATURE, MS_IMAGEMODE_NULL };
 
-enum MS_GEOS_OPERATOR {MS_GEOS_EQUALS, MS_GEOS_DISJOINT, MS_GEOS_TOUCHES, MS_GEOS_OVERLAPS, MS_GEOS_CROSSES, MS_GEOS_INTERSECTS, MS_GEOS_WITHIN, MS_GEOS_CONTAINS, MS_GEOS_BEYOND, MS_GEOS_DWITHIN};
-#define MS_FILE_DEFAULT MS_FILE_MAP   
+  enum MS_GEOS_OPERATOR {MS_GEOS_EQUALS, MS_GEOS_DISJOINT, MS_GEOS_TOUCHES, MS_GEOS_OVERLAPS, MS_GEOS_CROSSES, MS_GEOS_INTERSECTS, MS_GEOS_WITHIN, MS_GEOS_CONTAINS, MS_GEOS_BEYOND, MS_GEOS_DWITHIN};
+#define MS_FILE_DEFAULT MS_FILE_MAP
 
-/* coordinate to pixel simplification modes, used in msTransformShape */
-enum MS_TRANSFORM_MODE {
-   MS_TRANSFORM_NONE, /* no geographic to pixel transformation */
-   MS_TRANSFORM_ROUND, /* round to integer, might create degenerate geometries (used for GD)*/
-   MS_TRANSFORM_SNAPTOGRID, /* snap to a grid, should be user configurable in the future*/
-   MS_TRANSFORM_FULLRESOLUTION, /* keep full resolution */
-   MS_TRANSFORM_SIMPLIFY /* keep full resolution */
-};
+  /* coordinate to pixel simplification modes, used in msTransformShape */
+  enum MS_TRANSFORM_MODE {
+    MS_TRANSFORM_NONE, /* no geographic to pixel transformation */
+    MS_TRANSFORM_ROUND, /* round to integer, might create degenerate geometries (used for GD)*/
+    MS_TRANSFORM_SNAPTOGRID, /* snap to a grid, should be user configurable in the future*/
+    MS_TRANSFORM_FULLRESOLUTION, /* keep full resolution */
+    MS_TRANSFORM_SIMPLIFY /* keep full resolution */
+  };
 
 #ifndef SWIG
-/* Filter object */    
-typedef enum 
-{
+  /* Filter object */
+  typedef enum {
     FILTER_NODE_TYPE_UNDEFINED = -1,
     FILTER_NODE_TYPE_LOGICAL = 0,
     FILTER_NODE_TYPE_SPATIAL = 1,
@@ -517,65 +536,64 @@ typedef enum
     FILTER_NODE_TYPE_GEOMETRY_LINE = 8,
     FILTER_NODE_TYPE_GEOMETRY_POLYGON = 9,
     FILTER_NODE_TYPE_FEATUREID = 10
-} FilterNodeType;
+  } FilterNodeType;
 
 
-/************************************************************************/
-/*                          FilterEncodingNode                          */
-/************************************************************************/
+  /************************************************************************/
+  /*                          FilterEncodingNode                          */
+  /************************************************************************/
 
-typedef struct _FilterNode
-{
+  typedef struct _FilterNode {
     FilterNodeType      eType;
     char                *pszValue;
     void                *pOther;
     char                *pszSRS;
     struct _FilterNode  *psLeftNode;
     struct _FilterNode  *psRightNode;
-} FilterEncodingNode;
+  } FilterEncodingNode;
 #endif /*SWIG*/
 
-/* Define supported bindings here (only covers existing bindings at first). Not accessible directly using MapScript. */
-#define MS_STYLE_BINDING_LENGTH 8
-enum MS_STYLE_BINDING_ENUM { MS_STYLE_BINDING_SIZE, MS_STYLE_BINDING_WIDTH, MS_STYLE_BINDING_ANGLE, MS_STYLE_BINDING_COLOR, MS_STYLE_BINDING_OUTLINECOLOR, MS_STYLE_BINDING_SYMBOL, MS_STYLE_BINDING_OUTLINEWIDTH, MS_STYLE_BINDING_OPACITY };
+  /* Define supported bindings here (only covers existing bindings at first). Not accessible directly using MapScript. */
+#define MS_STYLE_BINDING_LENGTH 12
+  enum MS_STYLE_BINDING_ENUM { MS_STYLE_BINDING_SIZE, MS_STYLE_BINDING_WIDTH, MS_STYLE_BINDING_ANGLE, MS_STYLE_BINDING_COLOR, MS_STYLE_BINDING_OUTLINECOLOR, MS_STYLE_BINDING_SYMBOL, MS_STYLE_BINDING_OUTLINEWIDTH, MS_STYLE_BINDING_OPACITY, MS_STYLE_BINDING_OFFSET_X, MS_STYLE_BINDING_OFFSET_Y, MS_STYLE_BINDING_POLAROFFSET_PIXEL, MS_STYLE_BINDING_POLAROFFSET_ANGLE };
 #define MS_LABEL_BINDING_LENGTH 9
-enum MS_LABEL_BINDING_ENUM { MS_LABEL_BINDING_SIZE, MS_LABEL_BINDING_ANGLE, MS_LABEL_BINDING_COLOR, MS_LABEL_BINDING_OUTLINECOLOR, MS_LABEL_BINDING_FONT, MS_LABEL_BINDING_PRIORITY, MS_LABEL_BINDING_POSITION, MS_LABEL_BINDING_SHADOWSIZEX, MS_LABEL_BINDING_SHADOWSIZEY };
+  enum MS_LABEL_BINDING_ENUM { MS_LABEL_BINDING_SIZE, MS_LABEL_BINDING_ANGLE, MS_LABEL_BINDING_COLOR, MS_LABEL_BINDING_OUTLINECOLOR, MS_LABEL_BINDING_FONT, MS_LABEL_BINDING_PRIORITY, MS_LABEL_BINDING_POSITION, MS_LABEL_BINDING_SHADOWSIZEX, MS_LABEL_BINDING_SHADOWSIZEY };
 
-/************************************************************************/
-/*                         attributeBindingObj                          */
-/************************************************************************/
+  /************************************************************************/
+  /*                         attributeBindingObj                          */
+  /************************************************************************/
 #ifndef SWIG
-typedef struct {
-  char *item;
-  int index;
-} attributeBindingObj;
+  typedef struct {
+    char *item;
+    int index;
+  } attributeBindingObj;
 #endif /*SWIG*/
 
-/************************************************************************/
-/*                             labelPathObj                             */
-/*                                                                      */
-/*      Label path object - used to hold path and bounds of curved      */
-/*      labels - Bug #1620 implementation.                              */
-/************************************************************************/
+  /************************************************************************/
+  /*                             labelPathObj                             */
+  /*                                                                      */
+  /*      Label path object - used to hold path and bounds of curved      */
+  /*      labels - Bug #1620 implementation.                              */
+  /************************************************************************/
 #ifndef SWIG
-typedef struct {
-  multipointObj path;
-  shapeObj bounds;
-  double *angles;
-} labelPathObj;
+  typedef struct {
+    multipointObj path;
+    shapeObj bounds;
+    double *angles;
+  } labelPathObj;
 #endif /*SWIG*/
 
-/************************************************************************/
-/*                              fontSetObj                              */
-/*                                                                      */
-/*      used to hold aliases for TRUETYPE fonts                         */
-/************************************************************************/
+  /************************************************************************/
+  /*                              fontSetObj                              */
+  /*                                                                      */
+  /*      used to hold aliases for TRUETYPE fonts                         */
+  /************************************************************************/
 
-typedef struct {
+  typedef struct {
 #ifdef SWIG
     %immutable;
 #endif
-    char *filename; 
+    char *filename;
     int numfonts;
     hashTableObj fonts;
 #ifdef SWIG
@@ -583,157 +601,157 @@ typedef struct {
 #endif
 
 #ifndef SWIG
-    struct map_obj *map;
+    struct mapObj *map;
 #endif
-} fontSetObj;
+  } fontSetObj;
 
-/************************************************************************/
-/*                         featureListNodeObj                           */
-/*                                                                      */
-/*      for inline features, shape caches and queries                   */
-/************************************************************************/
+  /************************************************************************/
+  /*                         featureListNodeObj                           */
+  /*                                                                      */
+  /*      for inline features, shape caches and queries                   */
+  /************************************************************************/
 #ifndef SWIG
-typedef struct listNode {
+  typedef struct listNode {
     shapeObj shape;
     struct listNode *next;
     struct listNode *tailifhead; /* this is the tail node in the list, if this is the head element, otherwise NULL */
-} featureListNodeObj;
+  } featureListNodeObj;
 
-typedef featureListNodeObj * featureListNodeObjPtr;
+  typedef featureListNodeObj * featureListNodeObjPtr;
 #endif
 
-/************************************************************************/
-/*                              paletteObj                              */
-/*                                                                      */
-/*      used to hold colors while a map file is read                    */
-/************************************************************************/
+  /************************************************************************/
+  /*                              paletteObj                              */
+  /*                                                                      */
+  /*      used to hold colors while a map file is read                    */
+  /************************************************************************/
 #ifndef SWIG
-typedef struct {
+  typedef struct {
     colorObj colors[MS_MAXCOLORS-1];
     int      colorvalue[MS_MAXCOLORS-1];
     int numcolors;
-} paletteObj;
-#endif
-
-/************************************************************************/
-/*                     expressionObj & tokenObj                         */
-/************************************************************************/
-
-enum MS_TOKEN_LOGICAL_ENUM { MS_TOKEN_LOGICAL_AND=100, MS_TOKEN_LOGICAL_OR, MS_TOKEN_LOGICAL_NOT };
-enum MS_TOKEN_LITERAL_ENUM { MS_TOKEN_LITERAL_NUMBER=110, MS_TOKEN_LITERAL_STRING, MS_TOKEN_LITERAL_TIME, MS_TOKEN_LITERAL_SHAPE };
-enum MS_TOKEN_COMPARISON_ENUM { 
-  MS_TOKEN_COMPARISON_EQ=120, MS_TOKEN_COMPARISON_NE, MS_TOKEN_COMPARISON_GT, MS_TOKEN_COMPARISON_LT, MS_TOKEN_COMPARISON_LE, MS_TOKEN_COMPARISON_GE, MS_TOKEN_COMPARISON_IEQ,
-  MS_TOKEN_COMPARISON_RE, MS_TOKEN_COMPARISON_IRE,
-  MS_TOKEN_COMPARISON_IN, MS_TOKEN_COMPARISON_LIKE,
-  MS_TOKEN_COMPARISON_INTERSECTS, MS_TOKEN_COMPARISON_DISJOINT, MS_TOKEN_COMPARISON_TOUCHES, MS_TOKEN_COMPARISON_OVERLAPS, MS_TOKEN_COMPARISON_CROSSES, MS_TOKEN_COMPARISON_WITHIN, MS_TOKEN_COMPARISON_CONTAINS, 
-  MS_TOKEN_COMPARISON_BEYOND, MS_TOKEN_COMPARISON_DWITHIN
-};
-enum MS_TOKEN_FUNCTION_ENUM { 
-  MS_TOKEN_FUNCTION_LENGTH=140, MS_TOKEN_FUNCTION_TOSTRING, MS_TOKEN_FUNCTION_COMMIFY, MS_TOKEN_FUNCTION_AREA, MS_TOKEN_FUNCTION_ROUND, MS_TOKEN_FUNCTION_FROMTEXT, 
-  MS_TOKEN_FUNCTION_BUFFER
-};
-enum MS_TOKEN_BINDING_ENUM { MS_TOKEN_BINDING_DOUBLE=150, MS_TOKEN_BINDING_INTEGER, MS_TOKEN_BINDING_STRING, MS_TOKEN_BINDING_TIME, MS_TOKEN_BINDING_SHAPE };
-enum MS_PARSE_TYPE_ENUM { MS_PARSE_TYPE_BOOLEAN, MS_PARSE_TYPE_STRING, MS_PARSE_TYPE_SHAPE };
+  } paletteObj;
+#endif
+
+  /************************************************************************/
+  /*                     expressionObj & tokenObj                         */
+  /************************************************************************/
+
+  enum MS_TOKEN_LOGICAL_ENUM { MS_TOKEN_LOGICAL_AND=300, MS_TOKEN_LOGICAL_OR, MS_TOKEN_LOGICAL_NOT };
+  enum MS_TOKEN_LITERAL_ENUM { MS_TOKEN_LITERAL_NUMBER=310, MS_TOKEN_LITERAL_STRING, MS_TOKEN_LITERAL_TIME, MS_TOKEN_LITERAL_SHAPE };
+  enum MS_TOKEN_COMPARISON_ENUM {
+    MS_TOKEN_COMPARISON_EQ=320, MS_TOKEN_COMPARISON_NE, MS_TOKEN_COMPARISON_GT, MS_TOKEN_COMPARISON_LT, MS_TOKEN_COMPARISON_LE, MS_TOKEN_COMPARISON_GE, MS_TOKEN_COMPARISON_IEQ,
+    MS_TOKEN_COMPARISON_RE, MS_TOKEN_COMPARISON_IRE,
+    MS_TOKEN_COMPARISON_IN, MS_TOKEN_COMPARISON_LIKE,
+    MS_TOKEN_COMPARISON_INTERSECTS, MS_TOKEN_COMPARISON_DISJOINT, MS_TOKEN_COMPARISON_TOUCHES, MS_TOKEN_COMPARISON_OVERLAPS, MS_TOKEN_COMPARISON_CROSSES, MS_TOKEN_COMPARISON_WITHIN, MS_TOKEN_COMPARISON_CONTAINS,
+    MS_TOKEN_COMPARISON_BEYOND, MS_TOKEN_COMPARISON_DWITHIN
+  };
+  enum MS_TOKEN_FUNCTION_ENUM {
+    MS_TOKEN_FUNCTION_LENGTH=340, MS_TOKEN_FUNCTION_TOSTRING, MS_TOKEN_FUNCTION_COMMIFY, MS_TOKEN_FUNCTION_AREA, MS_TOKEN_FUNCTION_ROUND, MS_TOKEN_FUNCTION_FROMTEXT,
+    MS_TOKEN_FUNCTION_BUFFER, MS_TOKEN_FUNCTION_DIFFERENCE
+  };
+  enum MS_TOKEN_BINDING_ENUM { MS_TOKEN_BINDING_DOUBLE=350, MS_TOKEN_BINDING_INTEGER, MS_TOKEN_BINDING_STRING, MS_TOKEN_BINDING_TIME, MS_TOKEN_BINDING_SHAPE };
+  enum MS_PARSE_TYPE_ENUM { MS_PARSE_TYPE_BOOLEAN, MS_PARSE_TYPE_STRING, MS_PARSE_TYPE_SHAPE };
 
 #ifndef SWIG
-typedef union {
-  int intval;
-  char *strval;
-  shapeObj *shpval;
-} parseResultObj;
-
-typedef union {
-  double dblval;
-  int intval;
-  char *strval;
-  struct tm tmval;
-  shapeObj *shpval;
-  attributeBindingObj bindval;
-} tokenValueObj;
-
-typedef struct tokenListNode {
-  int token;
-  tokenValueObj tokenval;
-  struct tokenListNode *next;
-  struct tokenListNode *tailifhead; /* this is the tail node in the list if this is the head element, otherwise NULL */
-} tokenListNodeObj;
-
-typedef tokenListNodeObj * tokenListNodeObjPtr;
-
-typedef struct {
-  char *string;
-  int type;
-  /* container for expression options such as case-insensitiveness */
-  /* This is a boolean container. */
-  int flags;
-    
-  /* logical expression options */
-  tokenListNodeObjPtr tokens;
-  tokenListNodeObjPtr curtoken;
-
-  /* regular expression options */
-  ms_regex_t regex; /* compiled regular expression to be matched */
-  int compiled;
-} expressionObj;
-
-typedef struct {
-  colorObj *pixel; /* for raster layers */
-  shapeObj *shape; /* for vector layers */ 
-  expressionObj *expr; /* expression to be evaluated (contains tokens) */
-  int type; /* type of parse: boolean, string/text or shape/geometry */
-  parseResultObj result; /* parse result */
-} parseObj;
-#endif
-
-/* MS RFC 69*/
-typedef struct {
-  double maxdistance; /* max distance between clusters */
-  double buffer;      /* the buffer size around the selection area */
-  char* region;       /* type of the cluster region (rectangle or ellipse) */ 
+  typedef union {
+    int intval;
+    char *strval;
+    shapeObj *shpval;
+  } parseResultObj;
+
+  typedef union {
+    double dblval;
+    int intval;
+    char *strval;
+    struct tm tmval;
+    shapeObj *shpval;
+    attributeBindingObj bindval;
+  } tokenValueObj;
+
+  typedef struct tokenListNode {
+    int token;
+    tokenValueObj tokenval;
+    struct tokenListNode *next;
+    struct tokenListNode *tailifhead; /* this is the tail node in the list if this is the head element, otherwise NULL */
+  } tokenListNodeObj;
+
+  typedef tokenListNodeObj * tokenListNodeObjPtr;
+
+  typedef struct {
+    char *string;
+    int type;
+    /* container for expression options such as case-insensitiveness */
+    /* This is a boolean container. */
+    int flags;
+
+    /* logical expression options */
+    tokenListNodeObjPtr tokens;
+    tokenListNodeObjPtr curtoken;
+
+    /* regular expression options */
+    ms_regex_t regex; /* compiled regular expression to be matched */
+    int compiled;
+  } expressionObj;
+
+  typedef struct {
+    colorObj *pixel; /* for raster layers */
+    shapeObj *shape; /* for vector layers */
+    expressionObj *expr; /* expression to be evaluated (contains tokens) */
+    int type; /* type of parse: boolean, string/text or shape/geometry */
+    parseResultObj result; /* parse result */
+  } parseObj;
+#endif
+
+  /* MS RFC 69*/
+  typedef struct {
+    double maxdistance; /* max distance between clusters */
+    double buffer;      /* the buffer size around the selection area */
+    char* region;       /* type of the cluster region (rectangle or ellipse) */
 #ifndef SWIG
-  expressionObj group; /* expression to identify the groups */
-  expressionObj filter; /* expression for filtering the shapes */
+    expressionObj group; /* expression to identify the groups */
+    expressionObj filter; /* expression for filtering the shapes */
 #endif
-} clusterObj;
+  } clusterObj;
 
-/************************************************************************/
-/*                               joinObj                                */
-/*                                                                      */
-/*      simple way to access other XBase files, one-to-one or           */
-/*      one-to-many supported                                           */
-/************************************************************************/
+  /************************************************************************/
+  /*                               joinObj                                */
+  /*                                                                      */
+  /*      simple way to access other XBase files, one-to-one or           */
+  /*      one-to-many supported                                           */
+  /************************************************************************/
 
 #ifndef SWIG
-typedef struct {
+  typedef struct {
     char *name;
     char **items, **values; /* items/values (process 1 record at a time) */
     int numitems;
-    
+
     char *table;
     char *from, *to; /* item names */
-    
+
     void *joininfo; /* vendor specific (i.e. XBase, MySQL, etc.) stuff to allow for persistant access */
-    
+
     char *header, *footer;
 #ifndef __cplusplus
     char *template;
 #else
     char *_template;
 #endif
-    
+
     enum MS_JOIN_TYPE type;
     char *connection;
     enum MS_JOIN_CONNECTION_TYPE connectiontype;
-} joinObj;
+  } joinObj;
 #endif
 
-/************************************************************************/
-/*                           outputFormatObj                            */
-/*                                                                      */
-/*      see mapoutput.c for most related code.                          */
-/************************************************************************/
+  /************************************************************************/
+  /*                           outputFormatObj                            */
+  /*                                                                      */
+  /*      see mapoutput.c for most related code.                          */
+  /************************************************************************/
 
-typedef struct {
+  typedef struct {
     char *name;
     char *mimetype;
     char *driver;
@@ -750,371 +768,428 @@ typedef struct {
     rendererVTableObj *vtable;
     void *device; /* for supporting direct rendering onto a device context */
 #endif
-} outputFormatObj;
+  } outputFormatObj;
 
-/* The following is used for "don't care" values in transparent, interlace and
-   imagequality values. */
-#define MS_NOOVERRIDE  -1111 
+  /* The following is used for "don't care" values in transparent, interlace and
+     imagequality values. */
+#define MS_NOOVERRIDE  -1111
 
-/************************************************************************/
-/*                             queryObj                                 */
-/*                                                                      */
-/*      encapsulates the information necessary to perform a query       */
-/************************************************************************/
+  /************************************************************************/
+  /*                             queryObj                                 */
+  /*                                                                      */
+  /*      encapsulates the information necessary to perform a query       */
+  /************************************************************************/
 #ifndef SWIG
-typedef struct {
-  int type; /* MS_QUERY_TYPE */
-  int mode; /* MS_QUERY_MODE */
+  typedef struct {
+    int type; /* MS_QUERY_TYPE */
+    int mode; /* MS_QUERY_MODE */
 
-  int layer;
+    int layer;
 
-  pointObj point; /* by point */
-  double buffer;
-  int maxresults;
+    pointObj point; /* by point */
+    double buffer;
+    int maxresults;
 
-  rectObj rect; /* by rect */
-  shapeObj *shape; /* by shape & operator (OGC filter) */
+    rectObj rect; /* by rect */
+    shapeObj *shape; /* by shape & operator (OGC filter) */
 
-  long shapeindex; /* by index */
-  long tileindex; 
-  int clear_resultcache;
+    long shapeindex; /* by index */
+    long tileindex;
+    int clear_resultcache;
 
-  char *item; /* by attribute */
-  char *str;
+    int  maxfeatures; /* global maxfeatures */    
+    int  startindex;
+    
+    char *item; /* by attribute */
+    char *str;
 
-  expressionObj *filter; /* by filter */
+    expressionObj *filter; /* by filter */
 
-  int slayer; /* selection layer, used for msQueryByFeatures() (note this is not a query mode per se) */
-} queryObj;
+    int slayer; /* selection layer, used for msQueryByFeatures() (note this is not a query mode per se) */
+  } queryObj;
 #endif
 
-/************************************************************************/
-/*                             queryMapObj                              */
-/*                                                                      */
-/*      used to visualize query results                                 */
-/************************************************************************/
-typedef struct {
+  /************************************************************************/
+  /*                             queryMapObj                              */
+  /*                                                                      */
+  /*      used to visualize query results                                 */
+  /************************************************************************/
+  typedef struct {
     int height, width;
     int status;
     int style; /* HILITE, SELECTED or NORMAL */
     colorObj color;
-} queryMapObj;
+  } queryMapObj;
 
-/************************************************************************/
-/*                                webObj                                */
-/*                                                                      */
-/*      holds parameters for a mapserver/mapscript interface            */
-/************************************************************************/
+  /************************************************************************/
+  /*                                webObj                                */
+  /*                                                                      */
+  /*      holds parameters for a mapserver/mapscript interface            */
+  /************************************************************************/
 
-typedef struct {
-  char *log;
-  char *imagepath, *imageurl, *temppath;
+  typedef struct {
+    char *log;
+    char *imagepath, *imageurl, *temppath;
 
 #ifdef SWIG
-%immutable;
+    %immutable;
 #endif /* SWIG */
-  struct map_obj *map;
+    struct mapObj *map;
 #ifdef SWIG
-%mutable;
+    %mutable;
 #endif /* SWIG */
 
 #ifndef __cplusplus
-  char *template;
+    char *template;
 #else
-  char *_template;
+    char *_template;
 #endif
 
-  char *header, *footer;
-  char *empty, *error; /* error handling */
-  rectObj extent; /* clipping extent */
-  double minscaledenom, maxscaledenom;
-  char *mintemplate, *maxtemplate;
+    char *header, *footer;
+    char *empty, *error; /* error handling */
+    rectObj extent; /* clipping extent */
+    double minscaledenom, maxscaledenom;
+    char *mintemplate, *maxtemplate;
 
-  char *queryformat; /* what format is the query to be returned, given as a MIME type */
-  char *legendformat;
-  char *browseformat;
+    char *queryformat; /* what format is the query to be returned, given as a MIME type */
+    char *legendformat;
+    char *browseformat;
 
 #ifdef SWIG
-%immutable;
+    %immutable;
 #endif /* SWIG */
-  hashTableObj metadata;
-  hashTableObj validation;
+    hashTableObj metadata;
+    hashTableObj validation;
 #ifdef SWIG
-%mutable;
+    %mutable;
 #endif /* SWIG */
 
-} webObj;
+  } webObj;
 
-/************************************************************************/
-/*                               styleObj                               */
-/*                                                                      */
-/*      holds parameters for symbolization, multiple styles may be      */
-/*      applied within a classObj                                       */
-/************************************************************************/
+  /************************************************************************/
+  /*                               styleObj                               */
+  /*                                                                      */
+  /*      holds parameters for symbolization, multiple styles may be      */
+  /*      applied within a classObj                                       */
+  /************************************************************************/
 
-typedef struct {
+  typedef struct {
 #ifdef SWIG
-%immutable;
+    %immutable;
 #endif /* SWIG */
-  int refcount;
+    int refcount;
 #ifdef SWIG
-%mutable;
+    %mutable;
 #endif /* SWIG */
 
 #ifndef SWIG
-  /* private vars for rfc 48 & 64 */
-  expressionObj _geomtransform;
+    /* private vars for rfc 48 & 64 */
+    expressionObj _geomtransform;
 #endif
-  
-  /*should an angle be automatically computed*/
-  int autoangle;
-
-  colorObj color;
-  colorObj backgroundcolor;
-  colorObj outlinecolor;
-
-  int opacity;
-
-  /* Stuff to handle Color Range Styles */
-  colorObj mincolor;
-  colorObj maxcolor;
-  double minvalue;
-  double maxvalue;
-  char *rangeitem;
-  int rangeitemindex;
-  
-  int symbol;
-  char *symbolname;
 
-  double size;
-  double minsize, maxsize;
+    /*should an angle be automatically computed*/
+    int autoangle;
 
-  int patternlength;  /*moved from symbolObj in version 6.0*/                     
-  double pattern[MS_MAXPATTERNLENGTH]; /*moved from symbolObj in version 6.0*/ 
-  
-  double gap; /*moved from symbolObj in version 6.0*/
-  int position; /*moved from symbolObj in version 6.0*/
-  
-  int linecap, linejoin; /*moved from symbolObj in version 6.0*/
-  double linejoinmaxsize; /*moved from symbolObj in version 6.0*/
-  
-  double width;
-  double outlinewidth;
-  double minwidth, maxwidth;
+    colorObj color;
+    colorObj backgroundcolor;
+    colorObj outlinecolor;
+
+    int opacity;
+
+    /* Stuff to handle Color Range Styles */
+    colorObj mincolor;
+    colorObj maxcolor;
+    double minvalue;
+    double maxvalue;
+    char *rangeitem;
+    int rangeitemindex;
+
+    int symbol;
+    char *symbolname;
+
+    double size;
+    double minsize, maxsize;
 
-  double offsetx, offsety; /* for shadows, hollow symbols, etc... */
+    int patternlength;  /*moved from symbolObj in version 6.0*/
+    double pattern[MS_MAXPATTERNLENGTH]; /*moved from symbolObj in version 6.0*/
 
-  double angle;
+    double gap; /*moved from symbolObj in version 6.0*/
+    double initialgap;
+    int position; /*moved from symbolObj in version 6.0*/
 
-  int antialias;
+    int linecap, linejoin; /*moved from symbolObj in version 6.0*/
+    double linejoinmaxsize; /*moved from symbolObj in version 6.0*/
 
-  double minscaledenom, maxscaledenom;
+    double width;
+    double outlinewidth;
+    double minwidth, maxwidth;
+
+    double offsetx, offsety; /* for shadows, hollow symbols, etc... */
+    double polaroffsetpixel, polaroffsetangle;
+
+    double angle;
+
+    int antialias;
+
+    double minscaledenom, maxscaledenom;
 
 #ifndef SWIG
-  attributeBindingObj bindings[MS_STYLE_BINDING_LENGTH];
-  int numbindings;
+    attributeBindingObj bindings[MS_STYLE_BINDING_LENGTH];
+    int numbindings;
 #endif
-} styleObj;
+  } styleObj;
 
-/************************************************************************/
-/*                               labelObj                               */
-/*                                                                      */
-/*      parameters needed to annotate a layer, legend or scalebar       */
-/************************************************************************/
 
-typedef struct {
-  char *font;
-  enum MS_FONT_TYPE type;
-    
-  colorObj color;
-  colorObj outlinecolor;
-  int outlinewidth;
-  
-  colorObj shadowcolor;
-  int shadowsizex, shadowsizey;
 
-  double size;
-  double minsize, maxsize;
+  /********************************************************************/
+  /*                          labelLeaderObj                          */
+  /*                                                                  */
+  /*  parameters defining how a label or a group of labels may be     */
+  /*  offsetted from its original position                            */
+  /********************************************************************/
 
-  int position;
-  int offsetx, offsety;
+  typedef struct {
+    int maxdistance;
+    int gridstep;
+#ifndef SWIG
+    styleObj **styles;
+    int maxstyles;
+#endif
 
-  double angle;
-  int anglemode;
+#ifdef SWIG
+    %immutable;
+#endif
+    int numstyles;
+#ifdef SWIG
+    %mutable;
+#endif
 
-  int buffer; /* space to reserve around a label */
+  } labelLeaderObj;
 
-  int antialias;
-  int align;
 
-  char wrap;
-  int maxlength;
-  int minlength;
-  double space_size_10; /*cached size of a single space character -
-                       used for label text alignment of rfc40 */
+  /************************************************************************/
+  /*                               labelObj                               */
+  /*                                                                      */
+  /*      parameters needed to annotate a layer, legend or scalebar       */
+  /************************************************************************/
 
-  int minfeaturesize; /* minimum feature size (in pixels) to label */
-  int autominfeaturesize; /* true or false */
+  typedef struct {
+#ifdef SWIG
+    %immutable;
+#endif /* SWIG */
+    int refcount;
+#ifdef SWIG
+    %mutable;
+#endif /* SWIG */
 
-  double minscaledenom, maxscaledenom;
-  
-  int mindistance;
-  int repeatdistance;
-  double maxoverlapangle;
-  int partials; /* can labels run of an image */
+    char *font;
+    enum MS_FONT_TYPE type;
+
+    colorObj color;
+    colorObj outlinecolor;
+    int outlinewidth;
+
+    colorObj shadowcolor;
+    int shadowsizex, shadowsizey;
+
+    double size;
+    double minsize, maxsize;
+
+    int position;
+    int offsetx, offsety;
+
+    double angle;
+    int anglemode;
+
+    int buffer; /* space to reserve around a label */
+
+    int antialias;
+    int align;
+
+    char wrap;
+    int maxlength;
+    int minlength;
+    double space_size_10; /*cached size of a single space character used for label text alignment of rfc40 */
 
-  int force; /* labels *must* be drawn */
+    int minfeaturesize; /* minimum feature size (in pixels) to label */
+    int autominfeaturesize; /* true or false */
 
-  char *encoding;
+    double minscaledenom, maxscaledenom;
 
-  int priority;  /* Priority level 1 to MS_MAX_LABEL_PRIORITY, default=1 */
+    int mindistance;
+    int repeatdistance;
+    double maxoverlapangle;
+    int partials; /* can labels run of an image */
 
+    int force; /* labels *must* be drawn */
+
+    char *encoding;
+
+    int priority;  /* Priority level 1 to MS_MAX_LABEL_PRIORITY, default=1 */
+
+    int status;
 #ifndef SWIG
-  styleObj **styles;
-  int maxstyles;
+    expressionObj expression;
+    expressionObj text;
 #endif
-  int numstyles;
 
 #ifndef SWIG
-  attributeBindingObj bindings[MS_LABEL_BINDING_LENGTH];
-  int numbindings;
+    styleObj **styles;
+    int maxstyles;
 #endif
+    int numstyles;
+
+#ifndef SWIG
+    attributeBindingObj bindings[MS_LABEL_BINDING_LENGTH];
+    int numbindings;
+#endif
+
+    /* book keeping variable- used on a feature-by-feature basis (similar to bindings) */
+    char *annotext;
+    pointObj annopoint;
+    shapeObj *annopoly;
 
-} labelObj;
+    labelLeaderObj leader;
+  } labelObj;
 
-/************************************************************************/
-/*                               classObj                               */
-/*                                                                      */
-/*      basic symbolization and classification information              */
-/************************************************************************/
+  /************************************************************************/
+  /*                               classObj                               */
+  /*                                                                      */
+  /*      basic symbolization and classification information              */
+  /************************************************************************/
 
-typedef struct class_obj{
+  typedef struct classObj {
 #ifndef SWIG
-  expressionObj expression; /* the expression to be matched */
+    expressionObj expression; /* the expression to be matched */
 #endif
 
-  int status;
+    int status;
 
 #ifndef SWIG
-  styleObj **styles;
-  int maxstyles;
+    styleObj **styles;
+    int maxstyles;
 #endif
-  int numstyles;
 
 #ifdef SWIG
-%immutable;
-#endif /* SWIG */
-  labelObj label;
+    %immutable;
+#endif
+    int numstyles;
 #ifdef SWIG
-%mutable;
-#endif /* SWIG */
+    %mutable;
+#endif
+
+#ifndef SWIG
+    labelObj **labels;
+    int maxlabels;
+#endif
+    int numlabels; /* should be immutable */
 
-  char *name; /* should be unique within a layer */
-  char *title; /* used for legend labeling */
+    char *name; /* should be unique within a layer */
+    char *title; /* used for legend labeling */
 
 #ifndef SWIG
-  expressionObj text;
+    expressionObj text;
 #endif /* not SWIG */
 
 #ifndef __cplusplus
-  char *template;
+    char *template;
 #else /* __cplusplus */
-  char *_template;
+    char *_template;
 #endif /* __cplusplus */
 
-  int type;
+    int type;
 
 #ifdef SWIG
-%immutable;
+    %immutable;
 #endif /* SWIG */
-  hashTableObj metadata;
-  hashTableObj validation;
+    hashTableObj metadata;
+    hashTableObj validation;
 #ifdef SWIG
-%mutable;
+    %mutable;
 #endif /* SWIG */
 
-  double minscaledenom, maxscaledenom;
-  int minfeaturesize; /* minimum feature size (in pixels) to shape */
+    double minscaledenom, maxscaledenom;
+    int minfeaturesize; /* minimum feature size (in pixels) to shape */
 #ifdef SWIG
-%immutable;
+    %immutable;
 #endif /* SWIG */
-  int refcount;
-  struct layer_obj *layer;
+    int refcount;
+    struct layerObj *layer;
 #ifdef SWIG
-%mutable;
+    %mutable;
 #endif /* SWIG */
-  int debug;
+    int debug;
 
-  char *keyimage;
-  
-   char *group;
-} classObj;
-
-/************************************************************************/
-/*                         labelCacheMemberObj                          */
-/*                                                                      */
-/*      structures to implement label caching and collision             */
-/*      avoidance etc                                                   */
-/*                                                                      */
-/*        Note: These are scriptable, but are read only.                */
-/************************************************************************/
+    char *keyimage;
+
+    char *group;
+    labelLeaderObj leader;
+  } classObj;
+
+  /************************************************************************/
+  /*                         labelCacheMemberObj                          */
+  /*                                                                      */
+  /*      structures to implement label caching and collision             */
+  /*      avoidance etc                                                   */
+  /*                                                                      */
+  /*        Note: These are scriptable, but are read only.                */
+  /************************************************************************/
 
 #ifdef SWIG
-%immutable;
+  %immutable;
 #endif /* SWIG */
-typedef struct {
-  char *text;
-  double featuresize;
+  typedef struct {
+    double featuresize;
 
-  styleObj *styles; /* copied from the classObj, only present if there is a marker to be drawn */
-  int numstyles;
+    styleObj *styles; /* copied from the classObj, only present if there is a marker to be drawn */
+    int numstyles;
 
-  labelObj label; /* copied from the classObj */
+    labelObj *labels; /* copied from the classObj (1 or more depending on situation) */
+    int numlabels;
 
-  int layerindex; /* indexes */
-  int classindex;
-  int tileindex;
-  int shapeindex;
+    int layerindex; /* indexes */
+    int classindex;
 
-  int shapetype; /* source geometry type */
+    int shapetype; /* source geometry type, can be removed once annotation layers are dropped */
 
-  pointObj point; /* label point */
-  shapeObj *poly; /* label bounding box */
+    pointObj point; /* label point */
+    shapeObj *poly; /* label bounding box, accumulation of individual label's bounding boxes */
 
-  int status; /* has this label been drawn or not */
+    int status; /* has this label been drawn or not */
 
 #ifndef SWIG
-  labelPathObj *labelpath;  /* Path & bounds of curved labels.  Bug #1620 implementation */
+    labelPathObj *labelpath;  /* Path & bounds of curved labels.  Bug #1620 implementation */
 #endif /* SWIG */
 
-  int markerid; /* corresponding marker (POINT layers only) */
-  
-} labelCacheMemberObj;
-
-/************************************************************************/
-/*                         markerCacheMemberObj                         */
-/************************************************************************/
-typedef struct {
-  int id; /* corresponding label */
-  shapeObj *poly; /* marker bounding box (POINT layers only) */
-} markerCacheMemberObj;
-
-/************************************************************************/
-/*                          labelCacheSlotObj                           */
-/************************************************************************/
-typedef struct {
-  labelCacheMemberObj *labels;
-  int numlabels;
-  int cachesize;
-  markerCacheMemberObj *markers;
-  int nummarkers;
-  int markercachesize;
-} labelCacheSlotObj;
-
-/************************************************************************/
-/*                            labelCacheObj                             */
-/************************************************************************/
-typedef struct {
+    int markerid; /* corresponding marker (POINT layers only) */
+    lineObj *leaderline;
+    rectObj *leaderbbox;
+  } labelCacheMemberObj;
+
+  /************************************************************************/
+  /*                         markerCacheMemberObj                         */
+  /************************************************************************/
+  typedef struct {
+    int id; /* corresponding label */
+    shapeObj *poly; /* marker bounding box (POINT layers only) */
+  } markerCacheMemberObj;
+
+  /************************************************************************/
+  /*                          labelCacheSlotObj                           */
+  /************************************************************************/
+  typedef struct {
+    labelCacheMemberObj *labels;
+    int numlabels;
+    int cachesize;
+    markerCacheMemberObj *markers;
+    int nummarkers;
+    int markercachesize;
+  } labelCacheSlotObj;
+
+  /************************************************************************/
+  /*                            labelCacheObj                             */
+  /************************************************************************/
+  typedef struct {
     /* One labelCacheSlotObj for each priority level */
     labelCacheSlotObj slots[MS_MAX_LABEL_PRIORITY];
     /* numlabels is deprecated, maintained only for backwards compatibility
@@ -1122,932 +1197,938 @@ typedef struct {
      * The slots[].numlabels are the real values to rely on.
      */
     int numlabels;
-} labelCacheObj;
-
-/************************************************************************/
-/*                         resultObj                                    */
-/************************************************************************/
-typedef struct {
-  long shapeindex;
-  int tileindex;
-  int resultindex;
-  int classindex;
-} resultObj;
+    int gutter; /* space in pixels around the image where labels cannot be placed */
+  } labelCacheObj;
+
+  /************************************************************************/
+  /*                         resultObj                                    */
+  /************************************************************************/
+  typedef struct {
+    long shapeindex;
+    int tileindex;
+    int resultindex;
+    int classindex;
+  } resultObj;
 #ifdef SWIG
-%mutable;
+  %mutable;
 #endif /* SWIG */
 
 
-/************************************************************************/
-/*                            resultCacheObj                            */
-/************************************************************************/
-typedef struct {
+  /************************************************************************/
+  /*                            resultCacheObj                            */
+  /************************************************************************/
+  typedef struct {
 
 #ifndef SWIG
-  resultObj *results;
-  int cachesize;
+    resultObj *results;
+    int cachesize;
 #endif /* not SWIG */
 
 #ifdef SWIG
-%immutable;
+    %immutable;
 #endif /* SWIG */
-  int numresults;
-  rectObj bounds;
+    int numresults;
+    rectObj bounds;
 #ifdef SWIG
-%mutable;
+    %mutable;
 #endif /* SWIG */
-  
-  /* TODO: remove for 6.0, confirm with Assefa */
-  /*used to force the result retreiving to use getshape instead of resultgetshape*/
-  int usegetshape;
 
-} resultCacheObj;
+    /* TODO: remove for 6.0, confirm with Assefa */
+    /*used to force the result retreiving to use getshape instead of resultgetshape*/
+    int usegetshape;
 
+  } resultCacheObj;
 
-/************************************************************************/
-/*                             symbolSetObj                             */
-/************************************************************************/
-typedef struct {
-  char *filename;
-  int imagecachesize;
+
+  /************************************************************************/
+  /*                             symbolSetObj                             */
+  /************************************************************************/
+  typedef struct {
+    char *filename;
+    int imagecachesize;
 #ifdef SWIG
-  %immutable;
+    %immutable;
 #endif /* SWIG */
-  int numsymbols;
-  int maxsymbols;
+    int numsymbols;
+    int maxsymbols;
 #ifdef SWIG
-%mutable;
+    %mutable;
 #endif /* SWIG */
 #ifndef SWIG
-  int refcount;
-  symbolObj** symbol;
-  struct map_obj *map;
-  fontSetObj *fontset; /* a pointer to the main mapObj version */
-  struct imageCacheObj *imagecache;
+    int refcount;
+    symbolObj** symbol;
+    struct mapObj *map;
+    fontSetObj *fontset; /* a pointer to the main mapObj version */
+    struct imageCacheObj *imagecache;
 #endif /* not SWIG */
-} symbolSetObj;
-
-/************************************************************************/
-/*                           referenceMapObj                            */
-/************************************************************************/
-typedef struct {
-  rectObj extent;
-  int height, width;
-  colorObj color;
-  colorObj outlinecolor;
-  char *image;
-  int status;
-  int marker;
-  char *markername;
-  int markersize;
-  int minboxsize;
-  int maxboxsize;
+  } symbolSetObj;
+
+  /************************************************************************/
+  /*                           referenceMapObj                            */
+  /************************************************************************/
+  typedef struct {
+    rectObj extent;
+    int height, width;
+    colorObj color;
+    colorObj outlinecolor;
+    char *image;
+    int status;
+    int marker;
+    char *markername;
+    int markersize;
+    int minboxsize;
+    int maxboxsize;
 #ifdef SWIG
-%immutable;
+    %immutable;
 #endif /* SWIG */
-  struct map_obj *map;
+    struct mapObj *map;
 #ifdef SWIG
-%mutable;
+    %mutable;
 #endif /* SWIG */
-} referenceMapObj;
-
-/************************************************************************/
-/*                             scalebarObj                              */
-/************************************************************************/
-typedef struct {
-  colorObj imagecolor;
-  int height, width;
-  int style;
-  int intervals;
-  labelObj label;
-  colorObj color;
-  colorObj backgroundcolor;
-  colorObj outlinecolor;
-  int units;
-  int status; /* ON, OFF or EMBED */
-  int position; /* for embeded scalebars */
+  } referenceMapObj;
+
+  /************************************************************************/
+  /*                             scalebarObj                              */
+  /************************************************************************/
+  typedef struct {
+    colorObj imagecolor;
+    int height, width;
+    int style;
+    int intervals;
+    labelObj label;
+    colorObj color;
+    colorObj backgroundcolor;
+    colorObj outlinecolor;
+    int units;
+    int status; /* ON, OFF or EMBED */
+    int position; /* for embeded scalebars */
 #ifndef SWIG
-  int transparent;
-  int interlace;
+    int transparent;
+    int interlace;
 #endif /* not SWIG */
-  int postlabelcache;
-  int align;
-} scalebarObj;
+    int postlabelcache;
+    int align;
+  } scalebarObj;
 
-/************************************************************************/
-/*                              legendObj                               */
-/************************************************************************/
+  /************************************************************************/
+  /*                              legendObj                               */
+  /************************************************************************/
 
-typedef struct {
-  colorObj imagecolor;
+  typedef struct {
+    colorObj imagecolor;
 #ifdef SWIG
-        %immutable;
+    %immutable;
 #endif
-  labelObj label;
+    labelObj label;
 #ifdef SWIG
-        %mutable;
-#endif
-  int keysizex, keysizey;
-  int keyspacingx, keyspacingy;
-  colorObj outlinecolor; /* Color of outline of box, -1 for no outline */
-  int status; /* ON, OFF or EMBED */
-  int height, width;
-  int position; /* for embeded legends */
+    %mutable;
+#endif
+    int keysizex, keysizey;
+    int keyspacingx, keyspacingy;
+    colorObj outlinecolor; /* Color of outline of box, -1 for no outline */
+    int status; /* ON, OFF or EMBED */
+    int height, width;
+    int position; /* for embeded legends */
 #ifndef SWIG
-  int transparent;
-  int interlace;
+    int transparent;
+    int interlace;
 #endif /* not SWIG */
-  int postlabelcache;
+    int postlabelcache;
 #ifndef __cplusplus
-   char *template;
+    char *template;
 #else /* __cplusplus */
-   char *_template;
+    char *_template;
 #endif /* __cplusplus */
 #ifdef SWIG
-%immutable;
+    %immutable;
 #endif /* SWIG */
-  struct map_obj *map;
+    struct mapObj *map;
 #ifdef SWIG
-%mutable;
+    %mutable;
 #endif /* SWIG */
-} legendObj;
+  } legendObj;
 
-/************************************************************************/
-/*                             graticuleObj                             */
-/************************************************************************/
+  /************************************************************************/
+  /*                             graticuleObj                             */
+  /************************************************************************/
 #ifndef SWIG
-typedef struct
-{
-  double    dwhichlatitude;
-  double    dwhichlongitude;
-  double    dstartlatitude;
-  double    dstartlongitude;
-  double    dendlatitude;
-  double    dendlongitude;
-  double    dincrementlatitude;
-  double    dincrementlongitude;
-  double    minarcs;
-  double    maxarcs;
-  double    minincrement;
-  double    maxincrement;
-  double    minsubdivides;
-  double    maxsubdivides;
-  int     bvertical;
-  int     blabelaxes;
-  int     ilabelstate;
-  int     ilabeltype;
-  rectObj   extent;
-  lineObj   *pboundinglines;
-  pointObj  *pboundingpoints;
-  char    *labelformat;
-} graticuleObj;
-
-typedef struct
-{
-  int nTop;
-  pointObj *pasTop;
-  char  **papszTopLabels;
-  int nBottom;
-  pointObj *pasBottom;
-  char  **papszBottomLabels;
-  int nLeft;
-  pointObj *pasLeft;
-  char  **papszLeftLabels;
-  int nRight;
-  pointObj *pasRight;
-  char  **papszRightLabels;
-  
-}graticuleIntersectionObj;
-
-struct layerVTable;
-typedef struct layerVTable layerVTableObj;
+  typedef struct {
+    double    dwhichlatitude;
+    double    dwhichlongitude;
+    double    dstartlatitude;
+    double    dstartlongitude;
+    double    dendlatitude;
+    double    dendlongitude;
+    double    dincrementlatitude;
+    double    dincrementlongitude;
+    double    minarcs;
+    double    maxarcs;
+    double    minincrement;
+    double    maxincrement;
+    double    minsubdivides;
+    double    maxsubdivides;
+    int     bvertical;
+    int     blabelaxes;
+    int     ilabelstate;
+    int     ilabeltype;
+    rectObj   extent;
+    lineObj   *pboundinglines;
+    pointObj  *pboundingpoints;
+    char    *labelformat;
+  } graticuleObj;
+
+  typedef struct {
+    int nTop;
+    pointObj *pasTop;
+    char  **papszTopLabels;
+    int nBottom;
+    pointObj *pasBottom;
+    char  **papszBottomLabels;
+    int nLeft;
+    pointObj *pasLeft;
+    char  **papszLeftLabels;
+    int nRight;
+    pointObj *pasRight;
+    char  **papszRightLabels;
+
+  } graticuleIntersectionObj;
+
+  struct layerVTable;
+  typedef struct layerVTable layerVTableObj;
 
 #endif /*SWIG*/
 
-/************************************************************************/
-/*                               layerObj                               */
-/*                                                                      */
-/*      base unit of a map.                                             */
-/************************************************************************/
+  /************************************************************************/
+  /*                               imageObj                               */
+  /*                                                                      */
+  /*      A wrapper for GD and other images.                              */
+  /************************************************************************/
+  typedef struct {
+#ifdef SWIG
+    %immutable;
+#endif
+    int width, height;
+    double resolution;
+    double resolutionfactor;
 
-typedef struct layer_obj {
+    char *imagepath, *imageurl;
 
-  char *classitem; /* .DBF item to be used for symbol lookup */
+    outputFormatObj *format;
+#ifndef SWIG
+    tileCacheObj *tilecache;
+    int ntiles;
+#endif
+#ifdef SWIG
+    %mutable;
+#endif
+#ifndef SWIG
+    int size;
+#endif
+
+#ifndef SWIG
+    union {
+      void *plugin;
+
+      char *imagemap;
+      short *raw_16bit;
+      float *raw_float;
+      unsigned char *raw_byte;
+    } img;
+    ms_bitarray  img_mask;
+    pointObj refpt;
+#endif
+  } imageObj;
+
+  /************************************************************************/
+  /*                               layerObj                               */
+  /*                                                                      */
+  /*      base unit of a map.                                             */
+  /************************************************************************/
+
+  typedef struct layerObj {
+
+    char *classitem; /* .DBF item to be used for symbol lookup */
 
 #ifndef SWIG
-  int classitemindex;
-  resultCacheObj *resultcache; /* holds the results of a query against this layer */
-  int annotate; /* boolean flag for annotation */
-  double scalefactor; /* computed, not set */
+    int classitemindex;
+    resultCacheObj *resultcache; /* holds the results of a query against this layer */
+    int annotate; /* boolean flag for annotation */
+    double scalefactor; /* computed, not set */
 #ifndef __cplusplus
-  classObj **class; /* always at least 1 class */
+    classObj **class; /* always at least 1 class */
 #else /* __cplusplus */
-  classObj **_class;
+    classObj **_class;
 #endif /* __cplusplus */
 #endif /* not SWIG */
 
 #ifdef SWIG
-%immutable;
+    %immutable;
 #endif /* SWIG */
-  /* reference counting, RFC24 */
-  int refcount;
-  int numclasses;
-  int maxclasses;
-  int index;
-  struct map_obj *map;
+    /* reference counting, RFC24 */
+    int refcount;
+    int numclasses;
+    int maxclasses;
+    int index;
+    struct mapObj *map;
 #ifdef SWIG
-%mutable;
+    %mutable;
 #endif /* SWIG */
 
-  char *header, *footer; /* only used with multi result queries */
+    char *header, *footer; /* only used with multi result queries */
 
 #ifndef __cplusplus
-  char *template; /* global template, used across all classes */
+    char *template; /* global template, used across all classes */
 #else /* __cplusplus */
-  char *_template;
+    char *_template;
 #endif /* __cplusplus */
 
-  char *name; /* should be unique */
-  char *group; /* shouldn't be unique it's supposed to be a group right? */
+    char *name; /* should be unique */
+    char *group; /* shouldn't be unique it's supposed to be a group right? */
 
-  int status; /* on or off */
-  char *data; /* filename, can be relative or full path */
+    int status; /* on or off */
+    char *data; /* filename, can be relative or full path */
 
-  enum MS_LAYER_TYPE type;
+    enum MS_LAYER_TYPE type;
 
-  double tolerance; /* search buffer for point and line queries (in toleranceunits) */
-  int toleranceunits;
+    double tolerance; /* search buffer for point and line queries (in toleranceunits) */
+    int toleranceunits;
 
-  double symbolscaledenom; /* scale at which symbols are default size */
-  double minscaledenom, maxscaledenom;
-  int minfeaturesize; /* minimum feature size (in pixels) to shape */
-  double labelminscaledenom, labelmaxscaledenom;
-  double mingeowidth, maxgeowidth; /* map width (in map units) at which the layer should be drawn */
+    double symbolscaledenom; /* scale at which symbols are default size */
+    double minscaledenom, maxscaledenom;
+    int minfeaturesize; /* minimum feature size (in pixels) to shape */
+    double labelminscaledenom, labelmaxscaledenom;
+    double mingeowidth, maxgeowidth; /* map width (in map units) at which the layer should be drawn */
 
-  int sizeunits; /* applies to all classes */
+    int sizeunits; /* applies to all classes */
 
-  int maxfeatures;      
-  int startindex;
+    int maxfeatures;
+    int startindex;
 
-  colorObj offsite; /* transparent pixel value for raster images */
+    colorObj offsite; /* transparent pixel value for raster images */
 
-  int transform; /* does this layer have to be transformed to file coordinates */
+    int transform; /* does this layer have to be transformed to file coordinates */
 
-  int labelcache, postlabelcache; /* on or off */
+    int labelcache, postlabelcache; /* on or off */
 
-  char *labelitem;
+    char *labelitem;
 #ifndef SWIG
-  int labelitemindex;
+    int labelitemindex;
 #endif /* not SWIG */
 
-  char *tileitem;
-  char *tileindex; /* layer index file for tiling support */
+    char *tileitem;
+    char *tileindex; /* layer index file for tiling support */
 
 #ifndef SWIG
-  int tileitemindex;
-  projectionObj projection; /* projection information for the layer */
-  int project; /* boolean variable, do we need to project this layer or not */
+    int tileitemindex;
+    projectionObj projection; /* projection information for the layer */
+    int project; /* boolean variable, do we need to project this layer or not */
 #endif /* not SWIG */
 
-  int units; /* units of the projection */
+    int units; /* units of the projection */
 
 #ifndef SWIG
-  featureListNodeObjPtr features; /* linked list so we don't need a counter */
-  featureListNodeObjPtr currentfeature; /* pointer to the current feature */
+    featureListNodeObjPtr features; /* linked list so we don't need a counter */
+    featureListNodeObjPtr currentfeature; /* pointer to the current feature */
 #endif /* SWIG */
 
-  char *connection;
-  char *plugin_library;
-  char *plugin_library_original; /* this is needed for mapfile writing */
-  enum MS_CONNECTION_TYPE connectiontype;
+    char *connection;
+    char *plugin_library;
+    char *plugin_library_original; /* this is needed for mapfile writing */
+    enum MS_CONNECTION_TYPE connectiontype;
 
 #ifndef SWIG
-  layerVTableObj *vtable;
+    layerVTableObj *vtable;
 
-  /* SDL has converted OracleSpatial, SDE, Graticules */
-  void *layerinfo; /* all connection types should use this generic pointer to a vendor specific structure */
-  void *wfslayerinfo; /* For WFS layers, will contain a msWFSLayerInfo struct */
+    /* SDL has converted OracleSpatial, SDE, Graticules */
+    void *layerinfo; /* all connection types should use this generic pointer to a vendor specific structure */
+    void *wfslayerinfo; /* For WFS layers, will contain a msWFSLayerInfo struct */
 #endif /* not SWIG */
 
-  /* attribute/classification handling components */
+    /* attribute/classification handling components */
 #ifdef SWIG
-%immutable;
+    %immutable;
 #endif /* SWIG */
-  int numitems;
+    int numitems;
 #ifdef SWIG
-%mutable;
+    %mutable;
 #endif /* SWIG */
 
 #ifndef SWIG
-  char **items;
-  void *iteminfo; /* connection specific information necessary to retrieve values */
-  expressionObj filter; /* connection specific attribute filter */
-  int bandsitemindex;
-  int filteritemindex;
-  int styleitemindex;
+    char **items;
+    void *iteminfo; /* connection specific information necessary to retrieve values */
+    expressionObj filter; /* connection specific attribute filter */
+    int bandsitemindex;
+    int filteritemindex;
+    int styleitemindex;
 #endif /* not SWIG */
 
-  char *bandsitem; /* which item in a tile contains bands to use (tiled raster data only) */
-  char *filteritem;
-  char *styleitem; /* item to be used for style lookup - can also be 'AUTO' */
+    char *bandsitem; /* which item in a tile contains bands to use (tiled raster data only) */
+    char *filteritem;
+    char *styleitem; /* item to be used for style lookup - can also be 'AUTO' */
 
-  char *requires; /* context expressions, simple enough to not use expressionObj */
-  char *labelrequires;
+    char *requires; /* context expressions, simple enough to not use expressionObj */
+    char *labelrequires;
 
 #ifdef SWIG
-%immutable;
+    %immutable;
 #endif /* SWIG */
-  hashTableObj metadata;
-  hashTableObj validation;
-  hashTableObj bindvals;
-  clusterObj cluster;
+    hashTableObj metadata;
+    hashTableObj validation;
+    hashTableObj bindvals;
+    clusterObj cluster;
 #ifdef SWIG
-%mutable;
+    %mutable;
 #endif /* SWIG */
 
-  int opacity; /* opacity (was transparency) value 0-100 */
-  
-  int dump;
-  int debug;
+    int opacity; /* opacity (was transparency) value 0-100 */
+
+    int dump;
+    int debug;
 #ifndef SWIG
-  char **processing;
-  joinObj *joins;
+    char **processing;
+    joinObj *joins;
 #endif /* not SWIG */
 #ifdef SWIG
-%immutable;
+    %immutable;
 #endif /* SWIG */
-  
-  rectObj extent;
 
-  int numprocessing;
-  int numjoins;
+    rectObj extent;
+
+    int numprocessing;
+    int numjoins;
 #ifdef SWIG
-%mutable;
+    %mutable;
 #endif /* SWIG */
 
-  char *classgroup;
-} layerObj;
+    char *classgroup;
 
-/************************************************************************/
-/*                                mapObj                                */
-/*                                                                      */
-/*      encompasses everything used in an Internet mapping              */
-/*      application.                                                    */
-/************************************************************************/
+#ifndef SWIG
+    imageObj *maskimage;
+#endif
+    char *mask;
+
+  } layerObj;
+
+  /************************************************************************/
+  /*                                mapObj                                */
+  /*                                                                      */
+  /*      encompasses everything used in an Internet mapping              */
+  /*      application.                                                    */
+  /************************************************************************/
 
-/* MAP OBJECT -  */
-typedef struct map_obj{ /* structure for a map */
-  char *name; /* small identifier for naming etc. */
-  int status; /* is map creation on or off */
-  int height, width;
-  int maxsize;
+  /* MAP OBJECT -  */
+  typedef struct mapObj { /* structure for a map */
+    char *name; /* small identifier for naming etc. */
+    int status; /* is map creation on or off */
+    int height, width;
+    int maxsize;
 
 #ifndef SWIG
-  layerObj **layers;
+    layerObj **layers;
 #endif /* SWIG */
 
 #ifdef SWIG
-%immutable;
+    %immutable;
 #endif /* SWIG */
-  /* reference counting, RFC24 */
-  int refcount;
-  int numlayers; /* number of layers in mapfile */
-  int maxlayers; /* allocated size of layers[] array */
+    /* reference counting, RFC24 */
+    int refcount;
+    int numlayers; /* number of layers in mapfile */
+    int maxlayers; /* allocated size of layers[] array */
 
-  symbolSetObj symbolset;
-  fontSetObj fontset;
+    symbolSetObj symbolset;
+    fontSetObj fontset;
 
-  labelCacheObj labelcache; /* we need this here so multiple feature processors can access it */
+    labelCacheObj labelcache; /* we need this here so multiple feature processors can access it */
 #ifdef SWIG
-%mutable;
+    %mutable;
 #endif /* SWIG */
 
-  int transparent; /* TODO - Deprecated */
-  int interlace; /* TODO - Deprecated */
-  int imagequality; /* TODO - Deprecated */
+    int transparent; /* TODO - Deprecated */
+    int interlace; /* TODO - Deprecated */
+    int imagequality; /* TODO - Deprecated */
 
-  rectObj extent; /* map extent array */
-  double cellsize; /* in map units */
+    rectObj extent; /* map extent array */
+    double cellsize; /* in map units */
 
 
 #ifndef SWIG
-  geotransformObj gt; /* rotation / geotransform */
-  rectObj saved_extent;
+    geotransformObj gt; /* rotation / geotransform */
+    rectObj saved_extent;
 #endif /*SWIG*/
 
-  enum MS_UNITS units; /* units of the projection */
-  double scaledenom; /* scale of the output image */
-  double resolution;
-  double defresolution; /* default resolution: used for calculate the scalefactor */
+    enum MS_UNITS units; /* units of the projection */
+    double scaledenom; /* scale of the output image */
+    double resolution;
+    double defresolution; /* default resolution: used for calculate the scalefactor */
 
-  char *shapepath; /* where are the shape files located */
-  char *mappath; /* path of the mapfile, all path are relative to this path */
+    char *shapepath; /* where are the shape files located */
+    char *mappath; /* path of the mapfile, all path are relative to this path */
 
 #ifndef SWIG
-  paletteObj palette; /* holds a map palette */
+    paletteObj palette; /* holds a map palette */
 #endif /*SWIG*/
-  colorObj imagecolor; /* holds the initial image color value */
+    colorObj imagecolor; /* holds the initial image color value */
 
 #ifdef SWIG
-%immutable;
+    %immutable;
 #endif /* SWIG */
-  int numoutputformats;
-  outputFormatObj **outputformatlist;
-  outputFormatObj *outputformat;
+    int numoutputformats;
+    outputFormatObj **outputformatlist;
+    outputFormatObj *outputformat;
 
-  char *imagetype; /* name of current outputformat */
+    char *imagetype; /* name of current outputformat */
 #ifdef SWIG
-  %mutable;
+    %mutable;
 #endif /* SWIG */
 
 #ifndef SWIG
-  projectionObj projection; /* projection information for output map */
-  projectionObj latlon; /* geographic projection definition */
+    projectionObj projection; /* projection information for output map */
+    projectionObj latlon; /* geographic projection definition */
 #endif /* not SWIG */
 
 #ifdef SWIG
-%immutable;
-#endif /* SWIG */  
-  referenceMapObj reference;
-  scalebarObj scalebar;
-  legendObj legend;
+    %immutable;
+#endif /* SWIG */
+    referenceMapObj reference;
+    scalebarObj scalebar;
+    legendObj legend;
 
-  queryMapObj querymap;
+    queryMapObj querymap;
 
-  webObj web;
+    webObj web;
 #ifdef SWIG
-%mutable;
+    %mutable;
 #endif /* SWIG */
 
-  int *layerorder;
+    int *layerorder;
 
-  int debug;
+    int debug;
 
-  char *datapattern, *templatepattern; /* depricated, use VALIDATION ... END block instead */
+    char *datapattern, *templatepattern; /* depricated, use VALIDATION ... END block instead */
 
 #ifdef SWIG
-%immutable;
+    %immutable;
 #endif /* SWIG */
-  hashTableObj configoptions;
+    hashTableObj configoptions;
 #ifdef SWIG
-%mutable;
+    %mutable;
 #endif /* SWIG */
 
 #ifndef SWIG
-  /* Private encryption key information - see mapcrypto.c */
-  int encryption_key_loaded;        /* MS_TRUE once key has been loaded */
-  unsigned char encryption_key[MS_ENCRYPTION_KEY_SIZE]; /* 128bits encryption key */
+    /* Private encryption key information - see mapcrypto.c */
+    int encryption_key_loaded;        /* MS_TRUE once key has been loaded */
+    unsigned char encryption_key[MS_ENCRYPTION_KEY_SIZE]; /* 128bits encryption key */
 
-  queryObj query;
-#endif
-} mapObj;
-
-/************************************************************************/
-/*                               imageObj                               */
-/*                                                                      */
-/*      A wrapper for GD and other images.                              */
-/************************************************************************/
-typedef struct {
-#ifdef SWIG
-%immutable;
-#endif
-  int width, height;
-  double resolution;
-  double resolutionfactor;
-
-  char *imagepath, *imageurl;
-
-  outputFormatObj *format;
-#ifndef SWIG
-  tileCacheObj *tilecache;
-  int ntiles;
-#endif
-#ifdef SWIG
-%mutable;
+    queryObj query;
 #endif
+  } mapObj;
+
+  /************************************************************************/
+  /*                             layerVTable                              */
+  /*                                                                      */
+  /*      contains function pointers to the layer operations.  If you     */
+  /*      add new functions to here, remember to update                   */
+  /*      populateVirtualTable in maplayer.c                              */
+  /************************************************************************/
 #ifndef SWIG
-  int size;
-#endif
-
-#ifndef SWIG
-  union {
-    void *plugin;
-
-    char *imagemap;
-    short *raw_16bit;
-    float *raw_float;
-    unsigned char *raw_byte;
-  } img;
-  ms_bitarray  img_mask;
-#endif
-} imageObj;
-
-
-/************************************************************************/
-/*                             layerVTable                              */
-/*                                                                      */
-/*      contains function pointers to the layer operations.  If you     */
-/*      add new functions to here, remember to update                   */
-/*      populateVirtualTable in maplayer.c                              */
-/************************************************************************/
-#ifndef SWIG
-struct layerVTable {
-  int (*LayerSupportsCommonFilters)(layerObj *layer);
-  int (*LayerInitItemInfo)(layerObj *layer);
-  void (*LayerFreeItemInfo)(layerObj *layer);
-  int (*LayerOpen)(layerObj *layer);
-  int (*LayerIsOpen)(layerObj *layer);
-  int (*LayerWhichShapes)(layerObj *layer, rectObj rect, int isQuery);
-  int (*LayerNextShape)(layerObj *layer, shapeObj *shape);
-  int (*LayerGetShape)(layerObj *layer, shapeObj *shape, resultObj *record);
-  int (*LayerClose)(layerObj *layer);
-  int (*LayerGetItems)(layerObj *layer);
-  int (*LayerGetExtent)(layerObj *layer, rectObj *extent);
-  int (*LayerGetAutoStyle)(mapObj *map, layerObj *layer, classObj *c, shapeObj *shape);
-  int (*LayerCloseConnection)(layerObj *layer);
-  int (*LayerSetTimeFilter)(layerObj *layer, const char *timestring, const char *timefield);
-  int (*LayerApplyFilterToLayer)(FilterEncodingNode *psNode, mapObj *map, int iLayerIndex);
-  int (*LayerCreateItems)(layerObj *layer, int nt);
-  int (*LayerGetNumFeatures)(layerObj *layer);
-  int (*LayerGetAutoProjection)(layerObj *layer, projectionObj *projection);
-  char* (*LayerEscapeSQLParam)(layerObj *layer, const char* pszString);
-  char* (*LayerEscapePropertyName)(layerObj *layer, const char* pszString);
-};
+  struct layerVTable {
+    int (*LayerSupportsCommonFilters)(layerObj *layer);
+    int (*LayerInitItemInfo)(layerObj *layer);
+    void (*LayerFreeItemInfo)(layerObj *layer);
+    int (*LayerOpen)(layerObj *layer);
+    int (*LayerIsOpen)(layerObj *layer);
+    int (*LayerWhichShapes)(layerObj *layer, rectObj rect, int isQuery);
+    int (*LayerNextShape)(layerObj *layer, shapeObj *shape);
+    int (*LayerGetShape)(layerObj *layer, shapeObj *shape, resultObj *record);
+    int (*LayerClose)(layerObj *layer);
+    int (*LayerGetItems)(layerObj *layer);
+    int (*LayerGetExtent)(layerObj *layer, rectObj *extent);
+    int (*LayerGetAutoStyle)(mapObj *map, layerObj *layer, classObj *c, shapeObj *shape);
+    int (*LayerCloseConnection)(layerObj *layer);
+    int (*LayerSetTimeFilter)(layerObj *layer, const char *timestring, const char *timefield);
+    int (*LayerApplyFilterToLayer)(FilterEncodingNode *psNode, mapObj *map, int iLayerIndex);
+    int (*LayerCreateItems)(layerObj *layer, int nt);
+    int (*LayerGetNumFeatures)(layerObj *layer);
+    int (*LayerGetAutoProjection)(layerObj *layer, projectionObj *projection);
+    char* (*LayerEscapeSQLParam)(layerObj *layer, const char* pszString);
+    char* (*LayerEscapePropertyName)(layerObj *layer, const char* pszString);
+    void (*LayerEnablePaging)(layerObj *layer, int value);
+    int (*LayerGetPaging)(layerObj *layer);
+  };
 #endif /*SWIG*/
 
-/* Function prototypes, wrapable */
-MS_DLL_EXPORT int msSaveImage(mapObj *map, imageObj *img, char *filename);
-MS_DLL_EXPORT void msFreeImage(imageObj *img);
-MS_DLL_EXPORT int msSetup(void);
-MS_DLL_EXPORT void msCleanup(void);
-MS_DLL_EXPORT mapObj *msLoadMapFromString(char *buffer, char *new_mappath);
+  /* Function prototypes, wrapable */
+  MS_DLL_EXPORT int msSaveImage(mapObj *map, imageObj *img, char *filename);
+  MS_DLL_EXPORT void msFreeImage(imageObj *img);
+  MS_DLL_EXPORT int msSetup(void);
+  MS_DLL_EXPORT void msCleanup(int signal);
+  MS_DLL_EXPORT mapObj *msLoadMapFromString(char *buffer, char *new_mappath);
 
-/* Function prototypes, not wrapable */
+  /* Function prototypes, not wrapable */
 
 #ifndef SWIG
 
-/*
-** helper functions not part of the general API but needed in
-** a few other places (like mapscript)... found in mapfile.c
-*/
-int getString(char **s);
-int getDouble(double *d);
-int getInteger(int *i);
-int getSymbol(int n, ...);
-int getCharacter(char *c);
-
-int msBuildPluginLibraryPath(char **dest, const char *lib_str, mapObj *map);
-
-MS_DLL_EXPORT int  hex2int(char *hex);
-
-MS_DLL_EXPORT void initJoin(joinObj *join);
-MS_DLL_EXPORT void initSymbol(symbolObj *s);
-MS_DLL_EXPORT int initMap(mapObj *map);
-MS_DLL_EXPORT layerObj *msGrowMapLayers( mapObj *map );
-MS_DLL_EXPORT int initLayer(layerObj *layer, mapObj *map);
-MS_DLL_EXPORT int freeLayer( layerObj * );
-MS_DLL_EXPORT classObj *msGrowLayerClasses( layerObj *layer );
-MS_DLL_EXPORT int initClass(classObj *_class);
-MS_DLL_EXPORT int freeClass( classObj * );
-MS_DLL_EXPORT styleObj *msGrowClassStyles( classObj *_class );
-MS_DLL_EXPORT styleObj *msGrowLabelStyles( labelObj *label );
-MS_DLL_EXPORT int msMaybeAllocateClassStyle(classObj* c, int idx);
-MS_DLL_EXPORT void initLabel(labelObj *label);
-MS_DLL_EXPORT void resetClassStyle(classObj *_class);
-MS_DLL_EXPORT int initStyle(styleObj *style);
-MS_DLL_EXPORT int freeStyle(styleObj *style);
-MS_DLL_EXPORT void initReferenceMap(referenceMapObj *ref);
-MS_DLL_EXPORT void initScalebar(scalebarObj *scalebar);
-MS_DLL_EXPORT void initGrid( graticuleObj *pGraticule );
-MS_DLL_EXPORT void initWeb(webObj *web);
-MS_DLL_EXPORT void freeWeb(webObj *web);
-MS_DLL_EXPORT void initResultCache(resultCacheObj *resultcache);
-
-MS_DLL_EXPORT featureListNodeObjPtr insertFeatureList(featureListNodeObjPtr *list, shapeObj *shape);
-MS_DLL_EXPORT void freeFeatureList(featureListNodeObjPtr list);
-
-/* To be used *only* within the mapfile loading phase */
-MS_DLL_EXPORT int loadExpressionString(expressionObj *exp, char *value);
-/* Use this next, thread safe wrapper, function everywhere else */
-MS_DLL_EXPORT int msLoadExpressionString(expressionObj *exp, char *value);
-MS_DLL_EXPORT char *msGetExpressionString(expressionObj *exp);
-MS_DLL_EXPORT void initExpression(expressionObj *exp);
-MS_DLL_EXPORT void freeExpressionTokens(expressionObj *exp);
-MS_DLL_EXPORT void freeExpression(expressionObj *exp);
-
-MS_DLL_EXPORT void msApplySubstitutions(mapObj *map, char **names, char **values, int npairs);
-MS_DLL_EXPORT void msApplyDefaultSubstitutions(mapObj *map);
-
-MS_DLL_EXPORT int getClassIndex(layerObj *layer, char *str);
-
-/* For maplabel */
-int intersectLabelPolygons(shapeObj *p1, shapeObj *p2);
-pointObj get_metrics_line(pointObj *p, int position, rectObj rect, int ox, int oy, double angle, int buffer, lineObj *poly);
-pointObj get_metrics(pointObj *p, int position, rectObj rect, int ox, int oy, double angle, int buffer, shapeObj *poly);
-double dist(pointObj a, pointObj b);
-   
-/*
-** Main API Functions
-*/
-
-/* mapobject.c */
-
-MS_DLL_EXPORT void msFreeMap(mapObj *map);
-MS_DLL_EXPORT mapObj *msNewMapObj(void);
-MS_DLL_EXPORT const char *msGetConfigOption( mapObj *map, const char *key);
-MS_DLL_EXPORT int msSetConfigOption( mapObj *map, const char *key, const char *value);
-MS_DLL_EXPORT int msTestConfigOption( mapObj *map, const char *key, 
-                                      int default_result );
-MS_DLL_EXPORT void msApplyMapConfigOptions( mapObj *map );
-MS_DLL_EXPORT int msMapComputeGeotransform( mapObj *map );
-
-MS_DLL_EXPORT void msMapPixelToGeoref( mapObj *map, double *x, double *y );
-MS_DLL_EXPORT void msMapGeorefToPixel( mapObj *map, double *x, double *y );
-
-MS_DLL_EXPORT int msMapSetExtent(mapObj *map, double minx, double miny, 
-                                 double maxx, double maxy);
-MS_DLL_EXPORT int msMapOffsetExtent( mapObj *map, double x, double y);
-MS_DLL_EXPORT int msMapScaleExtent( mapObj *map, double zoomfactor, 
-					 double minscaledenom, double maxscaledenom);
-MS_DLL_EXPORT int msMapSetCenter( mapObj *map, pointObj *center);
-MS_DLL_EXPORT int msMapSetRotation( mapObj *map, double rotation_angle );
-MS_DLL_EXPORT int msMapSetSize( mapObj *map, int width, int height );
-MS_DLL_EXPORT int msMapSetSize( mapObj *map, int width, int height );
-MS_DLL_EXPORT int msMapSetFakedExtent( mapObj *map );
-MS_DLL_EXPORT int msMapRestoreRealExtent( mapObj *map );
-MS_DLL_EXPORT int msMapLoadOWSParameters( mapObj *map, cgiRequestObj *request,
-                                          const char *wmtver_string );
-MS_DLL_EXPORT int msMapIgnoreMissingData( mapObj *map );
-
-/* mapfile.c */
-
-MS_DLL_EXPORT int msValidateParameter(char *value, char *pattern1, char *pattern2, char *pattern3, char *pattern4);
-MS_DLL_EXPORT int msGetLayerIndex(mapObj *map, char *name);
-MS_DLL_EXPORT int msGetSymbolIndex(symbolSetObj *set, char *name, int try_addimage_if_notfound);
-MS_DLL_EXPORT mapObj  *msLoadMap(char *filename, char *new_mappath);
-MS_DLL_EXPORT int msTransformXmlMapfile(const char *stylesheet, const char *xmlMapfile, FILE *tmpfile);
-MS_DLL_EXPORT int msSaveMap(mapObj *map, char *filename);
-MS_DLL_EXPORT void msFreeCharArray(char **array, int num_items);
-MS_DLL_EXPORT int msUpdateScalebarFromString(scalebarObj *scalebar, char *string, int url_string);
-MS_DLL_EXPORT int msUpdateQueryMapFromString(queryMapObj *querymap, char *string, int url_string);
-MS_DLL_EXPORT int msUpdateLabelFromString(labelObj *label, char *string);
-MS_DLL_EXPORT int msUpdateClusterFromString(clusterObj *cluster, char *string);
-MS_DLL_EXPORT int msUpdateReferenceMapFromString(referenceMapObj *ref, char *string, int url_string);
-MS_DLL_EXPORT int msUpdateLegendFromString(legendObj *legend, char *string, int url_string);
-MS_DLL_EXPORT int msUpdateWebFromString(webObj *web, char *string, int url_string);
-MS_DLL_EXPORT int msUpdateStyleFromString(styleObj *style, char *string, int url_string);
-MS_DLL_EXPORT int msUpdateClassFromString(classObj *_class, char *string, int url_string);
-MS_DLL_EXPORT int msUpdateLayerFromString(layerObj *layer, char *string, int url_string);
-MS_DLL_EXPORT int msUpdateMapFromURL(mapObj *map, char *variable, char *string);
-MS_DLL_EXPORT int msEvalRegex(char *e, char *s);
-MS_DLL_EXPORT void msFree(void *p);
-MS_DLL_EXPORT char **msTokenizeMap(char *filename, int *numtokens);
-MS_DLL_EXPORT int msInitLabelCache(labelCacheObj *cache);
-MS_DLL_EXPORT int msFreeLabelCache(labelCacheObj *cache);
-MS_DLL_EXPORT int msCheckConnection(layerObj * layer); /* connection pooling functions (mapfile.c) */
-MS_DLL_EXPORT void msCloseConnections(mapObj *map); 
-
-MS_DLL_EXPORT void msOGRInitialize(void);
-MS_DLL_EXPORT void msOGRCleanup(void);
-MS_DLL_EXPORT void msGDALCleanup(void);
-MS_DLL_EXPORT void msGDALInitialize(void);
-   
-
-MS_DLL_EXPORT imageObj *msDrawScalebar(mapObj *map); /* in mapscale.c */
-MS_DLL_EXPORT int msCalculateScale(rectObj extent, int units, int width, int height, double resolution, double *scaledenom);
-MS_DLL_EXPORT double GetDeltaExtentsUsingScale(double scale, int units, double centerLat, int width, double resolution);
-MS_DLL_EXPORT double Pix2Georef(int nPixPos, int nPixMin, int nPixMax, double dfGeoMin, double dfGeoMax, int bULisYOrig);
-MS_DLL_EXPORT double Pix2LayerGeoref(mapObj *map, layerObj *layer, int value);
-MS_DLL_EXPORT double msInchesPerUnit(int units, double center_lat);
-MS_DLL_EXPORT int msEmbedScalebar(mapObj *map, imageObj *img);
-
-MS_DLL_EXPORT int msPointInRect(pointObj *p, rectObj *rect); /* in mapsearch.c */
-MS_DLL_EXPORT int msRectOverlap(rectObj *a, rectObj *b);
-MS_DLL_EXPORT int msRectContained(rectObj *a, rectObj *b);
-MS_DLL_EXPORT int msRectIntersect(rectObj *a, const rectObj *b);
-
-MS_DLL_EXPORT void msRectToFormattedString(rectObj *rect, char *format,
-                                           char *buffer, int buffer_length);
-MS_DLL_EXPORT void msPointToFormattedString(pointObj *point, const char*format,
-                                           char *buffer, int buffer_length);
-MS_DLL_EXPORT int msIsDegenerateShape(shapeObj *shape);
-
-MS_DLL_EXPORT void msMergeRect(rectObj *a, rectObj *b);
-MS_DLL_EXPORT double msDistancePointToPoint(pointObj *a, pointObj *b);
-MS_DLL_EXPORT double msSquareDistancePointToPoint(pointObj *a, pointObj *b);
-MS_DLL_EXPORT double msDistancePointToSegment(pointObj *p, pointObj *a, pointObj *b);
-MS_DLL_EXPORT double msSquareDistancePointToSegment(pointObj *p, pointObj *a, pointObj *b);
-MS_DLL_EXPORT double msDistancePointToShape(pointObj *p, shapeObj *shape);
-MS_DLL_EXPORT double msSquareDistancePointToShape(pointObj *p, shapeObj *shape);
-MS_DLL_EXPORT double msDistanceSegmentToSegment(pointObj *pa, pointObj *pb, pointObj *pc, pointObj *pd);
-MS_DLL_EXPORT double msDistanceShapeToShape(shapeObj *shape1, shapeObj *shape2);
-MS_DLL_EXPORT int msIntersectSegments(pointObj *a, pointObj *b, pointObj *c, pointObj *d);
-MS_DLL_EXPORT int msPointInPolygon(pointObj *p, lineObj *c);
-MS_DLL_EXPORT int msIntersectMultipointPolygon(shapeObj *multipoint, shapeObj *polygon);
-MS_DLL_EXPORT int msIntersectPointPolygon(pointObj *p, shapeObj *polygon);
-MS_DLL_EXPORT int msIntersectPolylinePolygon(shapeObj *line, shapeObj *poly);
-MS_DLL_EXPORT int msIntersectPolygons(shapeObj *p1, shapeObj *p2);
-MS_DLL_EXPORT int msIntersectPolylines(shapeObj *line1, shapeObj *line2);
-
-MS_DLL_EXPORT int msInitQuery(queryObj *query); /* in mapquery.c */
-MS_DLL_EXPORT void msFreeQuery(queryObj *query);
-MS_DLL_EXPORT int msSaveQuery(mapObj *map, char *filename, int results);
-MS_DLL_EXPORT int msLoadQuery(mapObj *map, char *filename);
-MS_DLL_EXPORT int msExecuteQuery(mapObj *map);
-
-MS_DLL_EXPORT int msQueryByIndex(mapObj *map); /* various query methods, all rely on the queryObj hung off the mapObj */
-MS_DLL_EXPORT int msQueryByAttributes(mapObj *map);
-MS_DLL_EXPORT int msQueryByPoint(mapObj *map);
-MS_DLL_EXPORT int msQueryByRect(mapObj *map);
-MS_DLL_EXPORT int msQueryByFeatures(mapObj *map);
-MS_DLL_EXPORT int msQueryByShape(mapObj *map);
-MS_DLL_EXPORT int msQueryByFilter(mapObj *map);
-
-MS_DLL_EXPORT int msGetQueryResultBounds(mapObj *map, rectObj *bounds);
-MS_DLL_EXPORT int msIsLayerQueryable(layerObj *lp);
-MS_DLL_EXPORT void msQueryFree(mapObj *map, int qlayer); /* todo: rename */
-MS_DLL_EXPORT int msRasterQueryByShape(mapObj *map, layerObj *layer, shapeObj *selectshape);
-MS_DLL_EXPORT int msRasterQueryByRect(mapObj *map, layerObj *layer, rectObj queryRect);
-MS_DLL_EXPORT int msRasterQueryByPoint(mapObj *map, layerObj *layer, int mode, pointObj p, double buffer, int maxresults );
-
-/* in mapstring.c */
-MS_DLL_EXPORT void msStringTrim(char *str); 
-MS_DLL_EXPORT void msStringTrimBlanks(char *string); 
-MS_DLL_EXPORT char *msStringTrimLeft(char *string);
-MS_DLL_EXPORT char *msStringChop(char *string);
-MS_DLL_EXPORT void msStringTrimEOL(char *string);
-MS_DLL_EXPORT char *msReplaceSubstring(char *str, const char *old, const char *sznew);
-MS_DLL_EXPORT void msReplaceChar(char *str, char old, char sznew);
-MS_DLL_EXPORT char *msCaseReplaceSubstring(char *str, const char *old, const char *sznew);
-MS_DLL_EXPORT char *msStripPath(char *fn);
-MS_DLL_EXPORT char *msGetPath(char *fn);
-MS_DLL_EXPORT char *msBuildPath(char *pszReturnPath, const char *abs_path, const char *path);
-MS_DLL_EXPORT char *msBuildPath3(char *pszReturnPath, const char *abs_path, const char *path1, const char *path2);
-MS_DLL_EXPORT char *msTryBuildPath(char *szReturnPath, const char *abs_path, const char *path);
-MS_DLL_EXPORT char *msTryBuildPath3(char *szReturnPath, const char *abs_path, const char *path1, const char *path2);
-MS_DLL_EXPORT char **msStringSplit(const char *string, char cd, int *num_tokens);
-MS_DLL_EXPORT char ** msStringSplitComplex( const char * pszString, const char * pszDelimiters, int *num_tokens, int nFlags);
-MS_DLL_EXPORT int msStringArrayContains(char **array, const char *element, int numElements);
-MS_DLL_EXPORT char **msStringTokenize( const char *pszLine, const char *pszDelim, int *num_tokens, int preserve_quote);
-MS_DLL_EXPORT int msCountChars(char *str, char ch);
-MS_DLL_EXPORT char *msLongToString(long value);
-MS_DLL_EXPORT char *msDoubleToString(double value, int force_f);
-MS_DLL_EXPORT char *msIntToString(int value);
-MS_DLL_EXPORT void msStringToUpper(char *string);
-MS_DLL_EXPORT void msStringToLower(char *string);
-MS_DLL_EXPORT int msEncodeChar(const char);
-MS_DLL_EXPORT char *msEncodeUrlExcept(const char*, const char);
-MS_DLL_EXPORT char *msEncodeUrl(const char*);
-MS_DLL_EXPORT char *msEncodeHTMLEntities(const char *string);
-MS_DLL_EXPORT void msDecodeHTMLEntities(const char *string);
-MS_DLL_EXPORT int msIsXMLTagValid(const char *string);
-MS_DLL_EXPORT char *msStringConcatenate(char *pszDest, const char *pszSrc);
-MS_DLL_EXPORT char *msJoinStrings(char **array, int arrayLength, const char *delimeter);
-MS_DLL_EXPORT char *msHashString(const char *pszStr);
-MS_DLL_EXPORT char *msCommifyString(char *str);
-MS_DLL_EXPORT int msHexToInt(char *hex);
-MS_DLL_EXPORT char *msGetEncodedString(const char *string, const char *encoding);
-MS_DLL_EXPORT char *msConvertWideStringToUTF8 (const wchar_t* string, const char* encoding);
-MS_DLL_EXPORT int msGetNextGlyph(const char **in_ptr, char *out_string);
-MS_DLL_EXPORT int msGetNumGlyphs(const char *in_ptr);
-MS_DLL_EXPORT int msGetUnicodeEntity(const char *inptr, int *unicode);
-MS_DLL_EXPORT int msStringIsInteger(const char *string);
-MS_DLL_EXPORT int msUTF8ToUniChar(const char *str, int *chPtr); /* maptclutf.c */
-MS_DLL_EXPORT char* msGetFirstLine(char* text);
-MS_DLL_EXPORT char* msStringEscape( const char * pszString );
-MS_DLL_EXPORT int msStringInArray( const char * pszString, char **array, int numelements);
+  /*
+  ** helper functions not part of the general API but needed in
+  ** a few other places (like mapscript)... found in mapfile.c
+  */
+  int getString(char **s);
+  int getDouble(double *d);
+  int getInteger(int *i);
+  int getSymbol(int n, ...);
+  int getCharacter(char *c);
+
+  int msBuildPluginLibraryPath(char **dest, const char *lib_str, mapObj *map);
+
+  MS_DLL_EXPORT int  hex2int(char *hex);
+
+  MS_DLL_EXPORT void initJoin(joinObj *join);
+  MS_DLL_EXPORT void initSymbol(symbolObj *s);
+  MS_DLL_EXPORT int initMap(mapObj *map);
+  MS_DLL_EXPORT layerObj *msGrowMapLayers( mapObj *map );
+  MS_DLL_EXPORT int initLayer(layerObj *layer, mapObj *map);
+  MS_DLL_EXPORT int freeLayer( layerObj * );
+  MS_DLL_EXPORT classObj *msGrowLayerClasses( layerObj *layer );
+  MS_DLL_EXPORT int initClass(classObj *_class);
+  MS_DLL_EXPORT int freeClass( classObj * );
+  MS_DLL_EXPORT styleObj *msGrowClassStyles( classObj *_class );
+  MS_DLL_EXPORT labelObj *msGrowClassLabels( classObj *_class );
+  MS_DLL_EXPORT styleObj *msGrowLabelStyles( labelObj *label );
+  MS_DLL_EXPORT styleObj *msGrowLeaderStyles( labelLeaderObj *leader );
+  MS_DLL_EXPORT int msMaybeAllocateClassStyle(classObj* c, int idx);
+  MS_DLL_EXPORT void initLabel(labelObj *label);
+  MS_DLL_EXPORT int  freeLabel(labelObj *label);
+  MS_DLL_EXPORT void resetClassStyle(classObj *_class);
+  MS_DLL_EXPORT int initStyle(styleObj *style);
+  MS_DLL_EXPORT int freeStyle(styleObj *style);
+  MS_DLL_EXPORT void initReferenceMap(referenceMapObj *ref);
+  MS_DLL_EXPORT void initScalebar(scalebarObj *scalebar);
+  MS_DLL_EXPORT void initGrid( graticuleObj *pGraticule );
+  MS_DLL_EXPORT void initWeb(webObj *web);
+  MS_DLL_EXPORT void freeWeb(webObj *web);
+  MS_DLL_EXPORT void initResultCache(resultCacheObj *resultcache);
+
+  MS_DLL_EXPORT featureListNodeObjPtr insertFeatureList(featureListNodeObjPtr *list, shapeObj *shape);
+  MS_DLL_EXPORT void freeFeatureList(featureListNodeObjPtr list);
+
+  /* To be used *only* within the mapfile loading phase */
+  MS_DLL_EXPORT int loadExpressionString(expressionObj *exp, char *value);
+  /* Use this next, thread safe wrapper, function everywhere else */
+  MS_DLL_EXPORT int msLoadExpressionString(expressionObj *exp, char *value);
+  MS_DLL_EXPORT char *msGetExpressionString(expressionObj *exp);
+  MS_DLL_EXPORT void initExpression(expressionObj *exp);
+  MS_DLL_EXPORT void freeExpressionTokens(expressionObj *exp);
+  MS_DLL_EXPORT void freeExpression(expressionObj *exp);
+
+  MS_DLL_EXPORT void msApplySubstitutions(mapObj *map, char **names, char **values, int npairs);
+  MS_DLL_EXPORT void msApplyDefaultSubstitutions(mapObj *map);
+
+  MS_DLL_EXPORT int getClassIndex(layerObj *layer, char *str);
+
+  /* For maplabel */
+  int intersectLabelPolygons(shapeObj *p1, shapeObj *p2);
+  pointObj get_metrics_line(pointObj *p, int position, rectObj rect, int ox, int oy, double angle, int buffer, lineObj *poly);
+  pointObj get_metrics(pointObj *p, int position, rectObj rect, int ox, int oy, double angle, int buffer, shapeObj *poly);
+  double dist(pointObj a, pointObj b);
+
+  /*
+  ** Main API Functions
+  */
+
+  /* mapobject.c */
+
+  MS_DLL_EXPORT void msFreeMap(mapObj *map);
+  MS_DLL_EXPORT mapObj *msNewMapObj(void);
+  MS_DLL_EXPORT const char *msGetConfigOption( mapObj *map, const char *key);
+  MS_DLL_EXPORT int msSetConfigOption( mapObj *map, const char *key, const char *value);
+  MS_DLL_EXPORT int msTestConfigOption( mapObj *map, const char *key,
+                                        int default_result );
+  MS_DLL_EXPORT void msApplyMapConfigOptions( mapObj *map );
+  MS_DLL_EXPORT int msMapComputeGeotransform( mapObj *map );
+
+  MS_DLL_EXPORT void msMapPixelToGeoref( mapObj *map, double *x, double *y );
+  MS_DLL_EXPORT void msMapGeorefToPixel( mapObj *map, double *x, double *y );
+
+  MS_DLL_EXPORT int msMapSetExtent(mapObj *map, double minx, double miny,
+                                   double maxx, double maxy);
+  MS_DLL_EXPORT int msMapOffsetExtent( mapObj *map, double x, double y);
+  MS_DLL_EXPORT int msMapScaleExtent( mapObj *map, double zoomfactor,
+                                      double minscaledenom, double maxscaledenom);
+  MS_DLL_EXPORT int msMapSetCenter( mapObj *map, pointObj *center);
+  MS_DLL_EXPORT int msMapSetRotation( mapObj *map, double rotation_angle );
+  MS_DLL_EXPORT int msMapSetSize( mapObj *map, int width, int height );
+  MS_DLL_EXPORT int msMapSetSize( mapObj *map, int width, int height );
+  MS_DLL_EXPORT int msMapSetFakedExtent( mapObj *map );
+  MS_DLL_EXPORT int msMapRestoreRealExtent( mapObj *map );
+  MS_DLL_EXPORT int msMapLoadOWSParameters( mapObj *map, cgiRequestObj *request,
+      const char *wmtver_string );
+  MS_DLL_EXPORT int msMapIgnoreMissingData( mapObj *map );
+
+  /* mapfile.c */
+
+  MS_DLL_EXPORT int msValidateParameter(char *value, char *pattern1, char *pattern2, char *pattern3, char *pattern4);
+  MS_DLL_EXPORT int msGetLayerIndex(mapObj *map, char *name);
+  MS_DLL_EXPORT int msGetSymbolIndex(symbolSetObj *set, char *name, int try_addimage_if_notfound);
+  MS_DLL_EXPORT mapObj  *msLoadMap(char *filename, char *new_mappath);
+  MS_DLL_EXPORT int msTransformXmlMapfile(const char *stylesheet, const char *xmlMapfile, FILE *tmpfile);
+  MS_DLL_EXPORT int msSaveMap(mapObj *map, char *filename);
+  MS_DLL_EXPORT void msFreeCharArray(char **array, int num_items);
+  MS_DLL_EXPORT int msUpdateScalebarFromString(scalebarObj *scalebar, char *string, int url_string);
+  MS_DLL_EXPORT int msUpdateQueryMapFromString(queryMapObj *querymap, char *string, int url_string);
+  MS_DLL_EXPORT int msUpdateLabelFromString(labelObj *label, char *string);
+  MS_DLL_EXPORT int msUpdateClusterFromString(clusterObj *cluster, char *string);
+  MS_DLL_EXPORT int msUpdateReferenceMapFromString(referenceMapObj *ref, char *string, int url_string);
+  MS_DLL_EXPORT int msUpdateLegendFromString(legendObj *legend, char *string, int url_string);
+  MS_DLL_EXPORT int msUpdateWebFromString(webObj *web, char *string, int url_string);
+  MS_DLL_EXPORT int msUpdateStyleFromString(styleObj *style, char *string, int url_string);
+  MS_DLL_EXPORT int msUpdateClassFromString(classObj *_class, char *string, int url_string);
+  MS_DLL_EXPORT int msUpdateLayerFromString(layerObj *layer, char *string, int url_string);
+  MS_DLL_EXPORT int msUpdateMapFromURL(mapObj *map, char *variable, char *string);
+  MS_DLL_EXPORT int msEvalRegex(char *e, char *s);
+#ifdef USE_MSFREE
+  MS_DLL_EXPORT void msFree(void *p);
+#else
+#define msFree free
+#endif
+  MS_DLL_EXPORT char **msTokenizeMap(char *filename, int *numtokens);
+  MS_DLL_EXPORT int msInitLabelCache(labelCacheObj *cache);
+  MS_DLL_EXPORT int msFreeLabelCache(labelCacheObj *cache);
+  MS_DLL_EXPORT int msCheckConnection(layerObj * layer); /* connection pooling functions (mapfile.c) */
+  MS_DLL_EXPORT void msCloseConnections(mapObj *map);
+
+  MS_DLL_EXPORT void msOGRInitialize(void);
+  MS_DLL_EXPORT void msOGRCleanup(void);
+  MS_DLL_EXPORT void msGDALCleanup(void);
+  MS_DLL_EXPORT void msGDALInitialize(void);
+
+  MS_DLL_EXPORT imageObj *msDrawScalebar(mapObj *map); /* in mapscale.c */
+  MS_DLL_EXPORT int msCalculateScale(rectObj extent, int units, int width, int height, double resolution, double *scaledenom);
+  MS_DLL_EXPORT double GetDeltaExtentsUsingScale(double scale, int units, double centerLat, int width, double resolution);
+  MS_DLL_EXPORT double Pix2Georef(int nPixPos, int nPixMin, int nPixMax, double dfGeoMin, double dfGeoMax, int bULisYOrig);
+  MS_DLL_EXPORT double Pix2LayerGeoref(mapObj *map, layerObj *layer, int value);
+  MS_DLL_EXPORT double msInchesPerUnit(int units, double center_lat);
+  MS_DLL_EXPORT int msEmbedScalebar(mapObj *map, imageObj *img);
+
+  MS_DLL_EXPORT int msPointInRect(pointObj *p, rectObj *rect); /* in mapsearch.c */
+  MS_DLL_EXPORT int msRectOverlap(rectObj *a, rectObj *b);
+  MS_DLL_EXPORT int msRectContained(rectObj *a, rectObj *b);
+  MS_DLL_EXPORT int msRectIntersect(rectObj *a, const rectObj *b);
+
+  MS_DLL_EXPORT void msRectToFormattedString(rectObj *rect, char *format,
+      char *buffer, int buffer_length);
+  MS_DLL_EXPORT void msPointToFormattedString(pointObj *point, const char*format,
+      char *buffer, int buffer_length);
+  MS_DLL_EXPORT int msIsDegenerateShape(shapeObj *shape);
+
+  MS_DLL_EXPORT void msMergeRect(rectObj *a, rectObj *b);
+  MS_DLL_EXPORT double msDistancePointToPoint(pointObj *a, pointObj *b);
+  MS_DLL_EXPORT double msSquareDistancePointToPoint(pointObj *a, pointObj *b);
+  MS_DLL_EXPORT double msDistancePointToSegment(pointObj *p, pointObj *a, pointObj *b);
+  MS_DLL_EXPORT double msSquareDistancePointToSegment(pointObj *p, pointObj *a, pointObj *b);
+  MS_DLL_EXPORT double msDistancePointToShape(pointObj *p, shapeObj *shape);
+  MS_DLL_EXPORT double msSquareDistancePointToShape(pointObj *p, shapeObj *shape);
+  MS_DLL_EXPORT double msDistanceSegmentToSegment(pointObj *pa, pointObj *pb, pointObj *pc, pointObj *pd);
+  MS_DLL_EXPORT double msDistanceShapeToShape(shapeObj *shape1, shapeObj *shape2);
+  MS_DLL_EXPORT int msIntersectSegments(pointObj *a, pointObj *b, pointObj *c, pointObj *d);
+  MS_DLL_EXPORT int msPointInPolygon(pointObj *p, lineObj *c);
+  MS_DLL_EXPORT int msIntersectMultipointPolygon(shapeObj *multipoint, shapeObj *polygon);
+  MS_DLL_EXPORT int msIntersectPointPolygon(pointObj *p, shapeObj *polygon);
+  MS_DLL_EXPORT int msIntersectPolylinePolygon(shapeObj *line, shapeObj *poly);
+  MS_DLL_EXPORT int msIntersectPolygons(shapeObj *p1, shapeObj *p2);
+  MS_DLL_EXPORT int msIntersectPolylines(shapeObj *line1, shapeObj *line2);
+
+  MS_DLL_EXPORT int msInitQuery(queryObj *query); /* in mapquery.c */
+  MS_DLL_EXPORT void msFreeQuery(queryObj *query);
+  MS_DLL_EXPORT int msSaveQuery(mapObj *map, char *filename, int results);
+  MS_DLL_EXPORT int msLoadQuery(mapObj *map, char *filename);
+  MS_DLL_EXPORT int msExecuteQuery(mapObj *map);
+
+  MS_DLL_EXPORT int msQueryByIndex(mapObj *map); /* various query methods, all rely on the queryObj hung off the mapObj */
+  MS_DLL_EXPORT int msQueryByAttributes(mapObj *map);
+  MS_DLL_EXPORT int msQueryByPoint(mapObj *map);
+  MS_DLL_EXPORT int msQueryByRect(mapObj *map);
+  MS_DLL_EXPORT int msQueryByFeatures(mapObj *map);
+  MS_DLL_EXPORT int msQueryByShape(mapObj *map);
+  MS_DLL_EXPORT int msQueryByFilter(mapObj *map);
+
+  MS_DLL_EXPORT int msGetQueryResultBounds(mapObj *map, rectObj *bounds);
+  MS_DLL_EXPORT int msIsLayerQueryable(layerObj *lp);
+  MS_DLL_EXPORT void msQueryFree(mapObj *map, int qlayer); /* todo: rename */
+  MS_DLL_EXPORT int msRasterQueryByShape(mapObj *map, layerObj *layer, shapeObj *selectshape);
+  MS_DLL_EXPORT int msRasterQueryByRect(mapObj *map, layerObj *layer, rectObj queryRect);
+  MS_DLL_EXPORT int msRasterQueryByPoint(mapObj *map, layerObj *layer, int mode, pointObj p, double buffer, int maxresults );
+
+  /* in mapstring.c */
+  MS_DLL_EXPORT void msStringTrim(char *str);
+  MS_DLL_EXPORT void msStringTrimBlanks(char *string);
+  MS_DLL_EXPORT char *msStringTrimLeft(char *string);
+  MS_DLL_EXPORT char *msStringChop(char *string);
+  MS_DLL_EXPORT void msStringTrimEOL(char *string);
+  MS_DLL_EXPORT char *msReplaceSubstring(char *str, const char *old, const char *sznew);
+  MS_DLL_EXPORT void msReplaceChar(char *str, char old, char sznew);
+  MS_DLL_EXPORT char *msCaseReplaceSubstring(char *str, const char *old, const char *sznew);
+  MS_DLL_EXPORT char *msStripPath(char *fn);
+  MS_DLL_EXPORT char *msGetPath(char *fn);
+  MS_DLL_EXPORT char *msBuildPath(char *pszReturnPath, const char *abs_path, const char *path);
+  MS_DLL_EXPORT char *msBuildPath3(char *pszReturnPath, const char *abs_path, const char *path1, const char *path2);
+  MS_DLL_EXPORT char *msTryBuildPath(char *szReturnPath, const char *abs_path, const char *path);
+  MS_DLL_EXPORT char *msTryBuildPath3(char *szReturnPath, const char *abs_path, const char *path1, const char *path2);
+  MS_DLL_EXPORT char **msStringSplit(const char *string, char cd, int *num_tokens);
+  MS_DLL_EXPORT char ** msStringSplitComplex( const char * pszString, const char * pszDelimiters, int *num_tokens, int nFlags);
+  MS_DLL_EXPORT int msStringArrayContains(char **array, const char *element, int numElements);
+  MS_DLL_EXPORT char **msStringTokenize( const char *pszLine, const char *pszDelim, int *num_tokens, int preserve_quote);
+  MS_DLL_EXPORT int msCountChars(char *str, char ch);
+  MS_DLL_EXPORT char *msLongToString(long value);
+  MS_DLL_EXPORT char *msDoubleToString(double value, int force_f);
+  MS_DLL_EXPORT char *msIntToString(int value);
+  MS_DLL_EXPORT void msStringToUpper(char *string);
+  MS_DLL_EXPORT void msStringToLower(char *string);
+  MS_DLL_EXPORT int msEncodeChar(const char);
+  MS_DLL_EXPORT char *msEncodeUrlExcept(const char*, const char);
+  MS_DLL_EXPORT char *msEncodeUrl(const char*);
+  MS_DLL_EXPORT char *msEncodeHTMLEntities(const char *string);
+  MS_DLL_EXPORT void msDecodeHTMLEntities(const char *string);
+  MS_DLL_EXPORT int msIsXMLTagValid(const char *string);
+  MS_DLL_EXPORT char *msStringConcatenate(char *pszDest, const char *pszSrc);
+  MS_DLL_EXPORT char *msJoinStrings(char **array, int arrayLength, const char *delimeter);
+  MS_DLL_EXPORT char *msHashString(const char *pszStr);
+  MS_DLL_EXPORT char *msCommifyString(char *str);
+  MS_DLL_EXPORT int msHexToInt(char *hex);
+  MS_DLL_EXPORT char *msGetEncodedString(const char *string, const char *encoding);
+  MS_DLL_EXPORT char *msConvertWideStringToUTF8 (const wchar_t* string, const char* encoding);
+  MS_DLL_EXPORT int msGetNextGlyph(const char **in_ptr, char *out_string);
+  MS_DLL_EXPORT int msGetNumGlyphs(const char *in_ptr);
+  MS_DLL_EXPORT int msGetUnicodeEntity(const char *inptr, int *unicode);
+  MS_DLL_EXPORT int msStringIsInteger(const char *string);
+  MS_DLL_EXPORT int msUTF8ToUniChar(const char *str, int *chPtr); /* maptclutf.c */
+  MS_DLL_EXPORT char* msStringEscape( const char * pszString );
+  MS_DLL_EXPORT int msStringInArray( const char * pszString, char **array, int numelements);
 
 #ifdef NEED_STRDUP
-MS_DLL_EXPORT char *strdup(char *s);
+  MS_DLL_EXPORT char *strdup(char *s);
 #endif /* NEED_STRDUP */
 
 #ifdef NEED_STRRSTR
-MS_DLL_EXPORT char *strrstr(char *string, char *find);
+  MS_DLL_EXPORT char *strrstr(char *string, char *find);
 #endif /* NEED_STRRSTR */
 
 #ifdef NEED_STRCASESTR
-MS_DLL_EXPORT char *strcasestr(const char *s, const char *find);
+  MS_DLL_EXPORT char *strcasestr(const char *s, const char *find);
 #endif /* NEED_STRCASESTR */
 
 #ifdef NEED_STRNCASECMP
-MS_DLL_EXPORT int strncasecmp(const char *s1, const char *s2, int len);
+  MS_DLL_EXPORT int strncasecmp(const char *s1, const char *s2, int len);
 #endif /* NEED_STRNCASECMP */
 
 #ifdef NEED_STRCASECMP
-MS_DLL_EXPORT int strcasecmp(const char *s1, const char *s2);
+  MS_DLL_EXPORT int strcasecmp(const char *s1, const char *s2);
 #endif /* NEED_STRCASECMP */
 
 #ifdef NEED_STRLCAT
-MS_DLL_EXPORT size_t strlcat(char *dst, const char *src, size_t siz);
+  MS_DLL_EXPORT size_t strlcat(char *dst, const char *src, size_t siz);
 #endif /* NEED_STRLCAT */
 
 #ifdef NEED_STRLCPY
-MS_DLL_EXPORT size_t strlcpy(char *dst, const char *src, size_t siz);
+  MS_DLL_EXPORT size_t strlcpy(char *dst, const char *src, size_t siz);
 #endif /* NEED_STRLCAT */
 
-MS_DLL_EXPORT char *msStrdup( const char * pszString );
-
-/* in mapsymbol.c */
-/* Use this function *only* with mapfile loading phase */
-MS_DLL_EXPORT int loadSymbolSet(symbolSetObj *symbolset, mapObj *map);
-/* Use this threadsafe wrapper everywhere else */
-MS_DLL_EXPORT int msLoadSymbolSet(symbolSetObj *symbolset, mapObj *map);
-MS_DLL_EXPORT int msCopySymbol(symbolObj *dst, symbolObj *src, mapObj *map);
-MS_DLL_EXPORT int msCopySymbolSet(symbolSetObj *dst, symbolSetObj *src, mapObj *map);
-MS_DLL_EXPORT void msInitSymbolSet(symbolSetObj *symbolset);
-MS_DLL_EXPORT symbolObj *msGrowSymbolSet( symbolSetObj *symbolset );
-MS_DLL_EXPORT int msAddImageSymbol(symbolSetObj *symbolset, char *filename);
-MS_DLL_EXPORT int msFreeSymbolSet(symbolSetObj *symbolset);
-MS_DLL_EXPORT int msFreeSymbol(symbolObj *symbol);
-MS_DLL_EXPORT int msAddNewSymbol(mapObj *map, char *name);
-MS_DLL_EXPORT int msAppendSymbol(symbolSetObj *symbolset, symbolObj *symbol);
-MS_DLL_EXPORT symbolObj *msRemoveSymbol(symbolSetObj *symbolset, int index);
-MS_DLL_EXPORT int msSaveSymbolSet(symbolSetObj *symbolset, const char *filename);
-MS_DLL_EXPORT int msLoadImageSymbol(symbolObj *symbol, const char *filename);
-MS_DLL_EXPORT int msPreloadImageSymbol(rendererVTableObj *renderer, symbolObj *symbol);
-MS_DLL_EXPORT symbolObj *msRotateSymbol(symbolObj *symbol, double angle);
-
-MS_DLL_EXPORT imageObj *msSymbolGetImageGD(symbolObj *symbol, outputFormatObj *format);
-MS_DLL_EXPORT int msSymbolSetImageGD(symbolObj *symbol, imageObj *image);
-
-MS_DLL_EXPORT int msGetMarkerSize(symbolSetObj *symbolset, styleObj *style, int *width, int *height, double scalefactor);
-//MS_DLL_EXPORT int msGetCharacterSize(char *character, int size, char *font, rectObj *rect);
-MS_DLL_EXPORT double msSymbolGetDefaultSize(symbolObj *s);
-MS_DLL_EXPORT void freeImageCache(struct imageCacheObj *ic);
-
-MS_DLL_EXPORT imageObj *msDrawLegend(mapObj *map, int scale_independent); /* in maplegend.c */
-MS_DLL_EXPORT int msLegendCalcSize(mapObj *map, int scale_independent, int *size_x, int *size_y, 
-                                   int *alayers, int numl_ayer);
-MS_DLL_EXPORT int msEmbedLegend(mapObj *map, imageObj *img);
-MS_DLL_EXPORT int msDrawLegendIcon(mapObj* map, layerObj* lp, classObj* myClass, int width, int height, imageObj *img, int dstX, int dstY);
-MS_DLL_EXPORT imageObj *msCreateLegendIcon(mapObj* map, layerObj* lp, classObj* myClass, int width, int height);
-   
-MS_DLL_EXPORT int msLoadFontSet(fontSetObj *fontSet, mapObj *map); /* in maplabel.c */
-MS_DLL_EXPORT int msInitFontSet(fontSetObj *fontset);
-MS_DLL_EXPORT int msFreeFontSet(fontSetObj *fontset);
-MS_DLL_EXPORT char *msFontsetLookupFont(fontSetObj *fontset, char *fontKey);
-
-MS_DLL_EXPORT char *msTransformLabelText(mapObj *map, imageObj* image, labelObj *label, char *text);
-MS_DLL_EXPORT int msGetTruetypeTextBBox(rendererVTableObj *renderer, char *font, double size, char *string, rectObj *rect, double **advances);
-
-MS_DLL_EXPORT int msGetLabelSize(mapObj *map, labelObj *label, char *string, double size, rectObj *rect, double **advances);
-MS_DLL_EXPORT int msAddLabel(mapObj *map, int layerindex, int classindex, shapeObj *shape, pointObj *point, labelPathObj *labelpath, char *string, double featuresize, labelObj *label);
-MS_DLL_EXPORT void msTestLabelCacheCollisions(labelCacheObj *labelcache, labelObj *labelPtr, int mapwidth, int mapheight, int buffer, labelCacheMemberObj *cachePtr, int current_priority, int current_label, int mindistance, double label_size);
-MS_DLL_EXPORT labelCacheMemberObj *msGetLabelCacheMember(labelCacheObj *labelcache, int i);
-
-MS_DLL_EXPORT gdFontPtr msGetBitmapFont(int size);
-MS_DLL_EXPORT int msImageTruetypePolyline(symbolSetObj *symbolset, imageObj *img, shapeObj *p, styleObj *style, double scalefactor);
-MS_DLL_EXPORT int msImageTruetypeArrow(symbolSetObj *symbolset, gdImagePtr img, shapeObj *p, styleObj *style, double scalefactor);
-
-MS_DLL_EXPORT void msFreeShape(shapeObj *shape); /* in mapprimitive.c */
-MS_DLL_EXPORT void msFreeLabelPathObj(labelPathObj *path);
-MS_DLL_EXPORT shapeObj *msShapeFromWKT(const char *string);
-MS_DLL_EXPORT char *msShapeToWKT(shapeObj *shape);
-MS_DLL_EXPORT void msInitShape(shapeObj *shape);
-MS_DLL_EXPORT void msShapeDeleteLine( shapeObj *shape, int line );
-MS_DLL_EXPORT int msCopyShape(shapeObj *from, shapeObj *to);
-MS_DLL_EXPORT int msIsOuterRing(shapeObj *shape, int r);
-MS_DLL_EXPORT int *msGetOuterList(shapeObj *shape);
-MS_DLL_EXPORT int *msGetInnerList(shapeObj *shape, int r, int *outerlist);
-MS_DLL_EXPORT void msComputeBounds(shapeObj *shape);
-MS_DLL_EXPORT void msRectToPolygon(rectObj rect, shapeObj *poly);
-MS_DLL_EXPORT void msClipPolylineRect(shapeObj *shape, rectObj rect);
-MS_DLL_EXPORT void msClipPolygonRect(shapeObj *shape, rectObj rect);
-MS_DLL_EXPORT void msTransformShape(shapeObj *shape, rectObj extent, double cellsize, imageObj *image);
-
-
-MS_DLL_EXPORT void msTransformPoint(pointObj *point, rectObj *extent, double cellsize, imageObj *image);
-
-MS_DLL_EXPORT void msOffsetPointRelativeTo(pointObj *point, layerObj *layer);
-MS_DLL_EXPORT void msOffsetShapeRelativeTo(shapeObj *shape, layerObj *layer);
-MS_DLL_EXPORT void msTransformShapeSimplify(shapeObj *shape, rectObj extent, double cellsize);
-MS_DLL_EXPORT void msTransformShapeToPixelSnapToGrid(shapeObj *shape, rectObj extent, double cellsize, double grid_resolution);
-MS_DLL_EXPORT void msTransformShapeToPixelRound(shapeObj *shape, rectObj extent, double cellsize);
-MS_DLL_EXPORT void msTransformShapeToPixelDoublePrecision(shapeObj *shape, rectObj extent, double cellsize);
-
-MS_DLL_EXPORT void msTransformPixelToShape(shapeObj *shape, rectObj extent, double cellsize);
-MS_DLL_EXPORT void msImageCartographicPolyline(gdImagePtr im, shapeObj *p, styleObj *style, symbolObj *symbol, int c, double size, double scalefactor);
-MS_DLL_EXPORT void msPolylineComputeLineSegments(shapeObj *shape, double ***segment_lengths, double **line_lengths, int *max_line_index, double *max_line_length, int *segment_index, double *total_length);
-MS_DLL_EXPORT pointObj** msPolylineLabelPoint(shapeObj *p, int min_length, int repeat_distance, double ***angles, double ***lengths, int *numpoints, int center_on_longest_segment);
-MS_DLL_EXPORT pointObj** msPolylineLabelPointExtended(shapeObj *p, int min_length, int repeat_distance, double ***angles, double ***lengths, int *numpoints, int *regularLines, int numlines, int center_on_longest_segment);
-MS_DLL_EXPORT void msPolylineLabelPointLineString(shapeObj *p, int min_length, int repeat_distance, double ***angles, double ***lengths, double** segment_lengths, 
-                                                  int line_index, double line_length, double total_length, int segment_index, 
-                                                  int* labelpoints_index, int* labelpoints_size, pointObj ***labelpoints, int center_on_longest_segment);
-MS_DLL_EXPORT labelPathObj** msPolylineLabelPath(mapObj *map, imageObj *img, shapeObj *p, int min_length, fontSetObj *fontset, char *string, labelObj *label, double scalefactor, int *numpaths, int** regular_lines, int* num_regular_Lines);
-MS_DLL_EXPORT void msPolylineLabelPathLineString(mapObj *map, imageObj *img, shapeObj *p, int min_length, fontSetObj *fontset, char *string, labelObj *label, double scalefactor,
-                                                 int line_index, double** segment_lengths, double line_length, double total_length, 
-                                                 int* labelpaths_index, int* labelpaths_size, labelPathObj ***labelpaths, int** regular_lines, int *regular_lines_index, int* regular_lines_size);
-MS_DLL_EXPORT int msPolygonLabelPoint(shapeObj *p, pointObj *lp, double min_dimension);
-MS_DLL_EXPORT int msAddLine(shapeObj *p, lineObj *new_line);
-MS_DLL_EXPORT int msAddLineDirectly(shapeObj *p, lineObj *new_line);
-MS_DLL_EXPORT int msAddPointToLine(lineObj *line, pointObj *point );
-MS_DLL_EXPORT double msGetPolygonArea(shapeObj *p);
-MS_DLL_EXPORT int msGetPolygonCentroid(shapeObj *p, pointObj *lp, double *miny, double *maxy);
-
-MS_DLL_EXPORT int msDrawRasterLayer(mapObj *map, layerObj *layer, imageObj *image); /* in mapraster.c */
-MS_DLL_EXPORT imageObj *msDrawReferenceMap(mapObj *map);
-
-/* mapbits.c - bit array handling functions and macros */
+  MS_DLL_EXPORT char *msStrdup( const char * pszString );
+
+  /* in mapsymbol.c */
+  /* Use this function *only* with mapfile loading phase */
+  MS_DLL_EXPORT int loadSymbolSet(symbolSetObj *symbolset, mapObj *map);
+  /* Use this threadsafe wrapper everywhere else */
+  MS_DLL_EXPORT int msLoadSymbolSet(symbolSetObj *symbolset, mapObj *map);
+  MS_DLL_EXPORT int msCopySymbol(symbolObj *dst, symbolObj *src, mapObj *map);
+  MS_DLL_EXPORT int msCopySymbolSet(symbolSetObj *dst, symbolSetObj *src, mapObj *map);
+  MS_DLL_EXPORT void msInitSymbolSet(symbolSetObj *symbolset);
+  MS_DLL_EXPORT symbolObj *msGrowSymbolSet( symbolSetObj *symbolset );
+  MS_DLL_EXPORT int msAddImageSymbol(symbolSetObj *symbolset, char *filename);
+  MS_DLL_EXPORT int msFreeSymbolSet(symbolSetObj *symbolset);
+  MS_DLL_EXPORT int msFreeSymbol(symbolObj *symbol);
+  MS_DLL_EXPORT int msAddNewSymbol(mapObj *map, char *name);
+  MS_DLL_EXPORT int msAppendSymbol(symbolSetObj *symbolset, symbolObj *symbol);
+  MS_DLL_EXPORT symbolObj *msRemoveSymbol(symbolSetObj *symbolset, int index);
+  MS_DLL_EXPORT int msSaveSymbolSet(symbolSetObj *symbolset, const char *filename);
+  MS_DLL_EXPORT int msLoadImageSymbol(symbolObj *symbol, const char *filename);
+  MS_DLL_EXPORT int msPreloadImageSymbol(rendererVTableObj *renderer, symbolObj *symbol);
+  MS_DLL_EXPORT int msPreloadSVGSymbol(symbolObj *symbol);
+  MS_DLL_EXPORT symbolObj *msRotateSymbol(symbolObj *symbol, double angle);
+
+  MS_DLL_EXPORT int msGetMarkerSize(symbolSetObj *symbolset, styleObj *style, double *width, double *height, double scalefactor);
+  /* MS_DLL_EXPORT int msGetCharacterSize(char *character, int size, char *font, rectObj *rect); */
+  MS_DLL_EXPORT double msSymbolGetDefaultSize(symbolObj *s);
+  MS_DLL_EXPORT void freeImageCache(struct imageCacheObj *ic);
+
+  MS_DLL_EXPORT imageObj *msDrawLegend(mapObj *map, int scale_independent); /* in maplegend.c */
+  MS_DLL_EXPORT int msLegendCalcSize(mapObj *map, int scale_independent, int *size_x, int *size_y,
+                                     int *alayers, int numl_ayer);
+  MS_DLL_EXPORT int msEmbedLegend(mapObj *map, imageObj *img);
+  MS_DLL_EXPORT int msDrawLegendIcon(mapObj* map, layerObj* lp, classObj* myClass, int width, int height, imageObj *img, int dstX, int dstY);
+  MS_DLL_EXPORT imageObj *msCreateLegendIcon(mapObj* map, layerObj* lp, classObj* myClass, int width, int height);
+
+  MS_DLL_EXPORT int msLoadFontSet(fontSetObj *fontSet, mapObj *map); /* in maplabel.c */
+  MS_DLL_EXPORT int msInitFontSet(fontSetObj *fontset);
+  MS_DLL_EXPORT int msFreeFontSet(fontSetObj *fontset);
+  MS_DLL_EXPORT char *msFontsetLookupFont(fontSetObj *fontset, char *fontKey);
+  MS_DLL_EXPORT int msFontsetLookupFonts(char* fontstring, int *numfonts, fontSetObj *fontset, char **lookedUpFonts);
+
+  MS_DLL_EXPORT char *msTransformLabelText(mapObj *map, labelObj *label, char *text);
+  MS_DLL_EXPORT int msGetTruetypeTextBBox(rendererVTableObj *renderer, char* fontstring, fontSetObj *fontset, double size, char *string, rectObj *rect, double **advances, int bAdjustBaseline);
+
+  MS_DLL_EXPORT int msGetLabelSize(mapObj *map, labelObj *label, char *string, double size, rectObj *rect, double **advances);
+
+  MS_DLL_EXPORT int msAddLabel(mapObj *map, labelObj *label, int layerindex, int classindex, shapeObj *shape, pointObj *point, labelPathObj *labelpath, double featuresize);
+  MS_DLL_EXPORT int msAddLabelGroup(mapObj *map, int layerindex, int classindex, shapeObj *shape, pointObj *point, double featuresize);
+  MS_DLL_EXPORT int msTestLabelCacheCollisions(mapObj *map, labelCacheMemberObj *cachePtr, shapeObj *poly, int mindistance, int current_priority, int current_label);
+  MS_DLL_EXPORT labelCacheMemberObj *msGetLabelCacheMember(labelCacheObj *labelcache, int i);
+
+  MS_DLL_EXPORT void msFreeShape(shapeObj *shape); /* in mapprimitive.c */
+  MS_DLL_EXPORT void msFreeLabelPathObj(labelPathObj *path);
+  MS_DLL_EXPORT shapeObj *msShapeFromWKT(const char *string);
+  MS_DLL_EXPORT char *msShapeToWKT(shapeObj *shape);
+  MS_DLL_EXPORT void msInitShape(shapeObj *shape);
+  MS_DLL_EXPORT void msShapeDeleteLine( shapeObj *shape, int line );
+  MS_DLL_EXPORT int msCopyShape(shapeObj *from, shapeObj *to);
+  MS_DLL_EXPORT int msIsOuterRing(shapeObj *shape, int r);
+  MS_DLL_EXPORT int *msGetOuterList(shapeObj *shape);
+  MS_DLL_EXPORT int *msGetInnerList(shapeObj *shape, int r, int *outerlist);
+  MS_DLL_EXPORT void msComputeBounds(shapeObj *shape);
+  MS_DLL_EXPORT void msRectToPolygon(rectObj rect, shapeObj *poly);
+  MS_DLL_EXPORT void msClipPolylineRect(shapeObj *shape, rectObj rect);
+  MS_DLL_EXPORT void msClipPolygonRect(shapeObj *shape, rectObj rect);
+  MS_DLL_EXPORT void msTransformShape(shapeObj *shape, rectObj extent, double cellsize, imageObj *image);
+  MS_DLL_EXPORT void msTransformPoint(pointObj *point, rectObj *extent, double cellsize, imageObj *image);
+
+  MS_DLL_EXPORT void msOffsetPointRelativeTo(pointObj *point, layerObj *layer);
+  MS_DLL_EXPORT void msOffsetShapeRelativeTo(shapeObj *shape, layerObj *layer);
+  MS_DLL_EXPORT void msTransformShapeSimplify(shapeObj *shape, rectObj extent, double cellsize);
+  MS_DLL_EXPORT void msTransformShapeToPixelSnapToGrid(shapeObj *shape, rectObj extent, double cellsize, double grid_resolution);
+  MS_DLL_EXPORT void msTransformShapeToPixelRound(shapeObj *shape, rectObj extent, double cellsize);
+  MS_DLL_EXPORT void msTransformShapeToPixelDoublePrecision(shapeObj *shape, rectObj extent, double cellsize);
+
+  MS_DLL_EXPORT void msTransformPixelToShape(shapeObj *shape, rectObj extent, double cellsize);
+  MS_DLL_EXPORT void msPolylineComputeLineSegments(shapeObj *shape, double ***segment_lengths, double **line_lengths, int *max_line_index, double *max_line_length, int *segment_index, double *total_length);
+  MS_DLL_EXPORT pointObj** msPolylineLabelPoint(shapeObj *p, int min_length, int repeat_distance, double ***angles, double ***lengths, int *numpoints, int center_on_longest_segment);
+  MS_DLL_EXPORT pointObj** msPolylineLabelPointExtended(shapeObj *p, int min_length, int repeat_distance, double ***angles, double ***lengths, int *numpoints, int *regularLines, int numlines, int center_on_longest_segment);
+  MS_DLL_EXPORT void msPolylineLabelPointLineString(shapeObj *p, int min_length, int repeat_distance, double ***angles, double ***lengths, double** segment_lengths,
+      int line_index, double line_length, double total_length, int segment_index,
+      int* labelpoints_index, int* labelpoints_size, pointObj ***labelpoints, int center_on_longest_segment);
+  MS_DLL_EXPORT labelPathObj** msPolylineLabelPath(mapObj *map, imageObj *img, shapeObj *p, int min_length, fontSetObj *fontset, char *string, labelObj *label, double scalefactor, int *numpaths, int** regular_lines, int* num_regular_Lines);
+  MS_DLL_EXPORT void msPolylineLabelPathLineString(mapObj *map, imageObj *img, shapeObj *p, int min_length, fontSetObj *fontset, char *string, labelObj *label, double scalefactor,
+      int line_index, double** segment_lengths, double line_length, double total_length,
+      int* labelpaths_index, int* labelpaths_size, labelPathObj ***labelpaths, int** regular_lines, int *regular_lines_index, int* regular_lines_size);
+  MS_DLL_EXPORT int msPolygonLabelPoint(shapeObj *p, pointObj *lp, double min_dimension);
+  MS_DLL_EXPORT int msAddLine(shapeObj *p, lineObj *new_line);
+  MS_DLL_EXPORT int msAddLineDirectly(shapeObj *p, lineObj *new_line);
+  MS_DLL_EXPORT int msAddPointToLine(lineObj *line, pointObj *point );
+  MS_DLL_EXPORT double msGetPolygonArea(shapeObj *p);
+  MS_DLL_EXPORT int msGetPolygonCentroid(shapeObj *p, pointObj *lp, double *miny, double *maxy);
+
+  MS_DLL_EXPORT int msDrawRasterLayer(mapObj *map, layerObj *layer, imageObj *image); /* in mapraster.c */
+  MS_DLL_EXPORT imageObj *msDrawReferenceMap(mapObj *map);
+
+  /* mapbits.c - bit array handling functions and macros */
 
 #define MS_ARRAY_BIT 32
 
@@ -2055,497 +2136,520 @@ MS_DLL_EXPORT imageObj *msDrawReferenceMap(mapObj *map);
 #define MS_SET_BIT(array,i) {array[i>>5] |= (1 <<(i & 0x3f));}
 #define MS_CLR_BIT(array,i) {array[i>>5] &= (~(1 <<(i & 0x3f)));}
 
-MS_DLL_EXPORT size_t msGetBitArraySize(int numbits); /* in mapbits.c */
-MS_DLL_EXPORT ms_bitarray msAllocBitArray(int numbits);
-MS_DLL_EXPORT int msGetBit(ms_bitarray array, int index);
-MS_DLL_EXPORT void msSetBit(ms_bitarray array, int index, int value);
-MS_DLL_EXPORT void msSetAllBits(ms_bitarray array, int index, int value);
-MS_DLL_EXPORT void msFlipBit(ms_bitarray array, int index);
-MS_DLL_EXPORT int msGetNextBit(ms_bitarray array, int index, int size);
-
-/* maplayer.c - layerObj  api */
-
-MS_DLL_EXPORT int msLayerInitItemInfo(layerObj *layer);
-MS_DLL_EXPORT void msLayerFreeItemInfo(layerObj *layer); 
-
-MS_DLL_EXPORT int msLayerOpen(layerObj *layer); /* in maplayer.c */
-MS_DLL_EXPORT int msClusterLayerOpen(layerObj *layer); /* in mapcluster.c */
-MS_DLL_EXPORT int msLayerIsOpen(layerObj *layer);
-MS_DLL_EXPORT void msLayerClose(layerObj *layer);
-MS_DLL_EXPORT int msLayerWhichShapes(layerObj *layer, rectObj rect, int isQuery);
-MS_DLL_EXPORT int msLayerGetItemIndex(layerObj *layer, char *item);
-MS_DLL_EXPORT int msLayerWhichItems(layerObj *layer, int get_all, char *metadata); 
-MS_DLL_EXPORT int msLayerNextShape(layerObj *layer, shapeObj *shape);
-MS_DLL_EXPORT int msLayerGetItems(layerObj *layer);
-MS_DLL_EXPORT int msLayerSetItems(layerObj *layer, char **items, int numitems);
-MS_DLL_EXPORT int msLayerGetShape(layerObj *layer, shapeObj *shape, resultObj *record);
-MS_DLL_EXPORT int msLayerGetExtent(layerObj *layer, rectObj *extent);
-MS_DLL_EXPORT int msLayerSetExtent( layerObj *layer, double minx, double miny, double maxx, double maxy);
-MS_DLL_EXPORT int msLayerGetAutoStyle(mapObj *map, layerObj *layer, classObj *c, shapeObj* shape);
-MS_DLL_EXPORT int msLayerGetFeatureStyle(mapObj *map, layerObj *layer, classObj *c, shapeObj* shape);
-MS_DLL_EXPORT void msLayerAddProcessing( layerObj *layer, const char *directive );
-MS_DLL_EXPORT void msLayerSetProcessingKey( layerObj *layer, const char *key, 
-                                            const char *value);
-MS_DLL_EXPORT char *msLayerGetProcessing( layerObj *layer, int proc_index);
-MS_DLL_EXPORT char *msLayerGetProcessingKey( layerObj *layer, const char *);
-MS_DLL_EXPORT int msLayerClearProcessing( layerObj *layer );
-MS_DLL_EXPORT char* msLayerGetFilterString( layerObj *layer );
-
-MS_DLL_EXPORT int msLayerSupportsCommonFilters(layerObj *layer);
-MS_DLL_EXPORT int msTokenizeExpression(expressionObj *expression, char **list, int *listsize);
-
-MS_DLL_EXPORT int msLayerSetTimeFilter(layerObj *lp, const char *timestring, 
-                                       const char *timefield);
-/* Helper functions for layers */ 
-MS_DLL_EXPORT int msLayerMakeBackticsTimeFilter(layerObj *lp, const char *timestring, 
-                                                 const char *timefield);
-
-MS_DLL_EXPORT int msLayerMakePlainTimeFilter(layerObj *lp, const char *timestring, 
-                                             const char *timefield);
-
-MS_DLL_EXPORT int msLayerApplyCondSQLFilterToLayer(FilterEncodingNode *psNode, mapObj *map, 
-                                                   int iLayerIndex);
-
-MS_DLL_EXPORT int msLayerApplyPlainFilterToLayer(FilterEncodingNode *psNode, mapObj *map, 
-                                                 int iLayerIndex);
-
-
-/* maplayer.c */
-MS_DLL_EXPORT int msLayerGetNumFeatures(layerObj *layer);
-
-MS_DLL_EXPORT int msLayerSupportsPaging(layerObj *layer);
-
-MS_DLL_EXPORT int msLayerGetMaxFeaturesToDraw(layerObj *layer, outputFormatObj *format);
-
-MS_DLL_EXPORT char *msLayerEscapeSQLParam(layerObj *layer, const char* pszString);
-MS_DLL_EXPORT char *msLayerEscapePropertyName(layerObj *layer, const char* pszString);
-
-/* These are special because SWF is using these */
-int msOGRLayerNextShape(layerObj *layer, shapeObj *shape);
-int msOGRLayerGetItems(layerObj *layer);
-void msOGRLayerFreeItemInfo(layerObj *layer);
-int msOGRLayerGetShape(layerObj *layer, shapeObj *shape, resultObj *record);
-int msOGRLayerGetExtent(layerObj *layer, rectObj *extent);
+  MS_DLL_EXPORT size_t msGetBitArraySize(int numbits); /* in mapbits.c */
+  MS_DLL_EXPORT ms_bitarray msAllocBitArray(int numbits);
+  MS_DLL_EXPORT int msGetBit(ms_bitarray array, int index);
+  MS_DLL_EXPORT void msSetBit(ms_bitarray array, int index, int value);
+  MS_DLL_EXPORT void msSetAllBits(ms_bitarray array, int index, int value);
+  MS_DLL_EXPORT void msFlipBit(ms_bitarray array, int index);
+  MS_DLL_EXPORT int msGetNextBit(ms_bitarray array, int index, int size);
+
+  /* maplayer.c - layerObj  api */
+
+  MS_DLL_EXPORT int msLayerInitItemInfo(layerObj *layer);
+  MS_DLL_EXPORT void msLayerFreeItemInfo(layerObj *layer);
+
+  MS_DLL_EXPORT int msLayerOpen(layerObj *layer); /* in maplayer.c */
+  MS_DLL_EXPORT int msClusterLayerOpen(layerObj *layer); /* in mapcluster.c */
+  MS_DLL_EXPORT int msLayerIsOpen(layerObj *layer);
+  MS_DLL_EXPORT void msLayerClose(layerObj *layer);
+  MS_DLL_EXPORT int msLayerWhichShapes(layerObj *layer, rectObj rect, int isQuery);
+  MS_DLL_EXPORT int msLayerGetItemIndex(layerObj *layer, char *item);
+  MS_DLL_EXPORT int msLayerWhichItems(layerObj *layer, int get_all, char *metadata);
+  MS_DLL_EXPORT int msLayerNextShape(layerObj *layer, shapeObj *shape);
+  MS_DLL_EXPORT int msLayerGetItems(layerObj *layer);
+  MS_DLL_EXPORT int msLayerSetItems(layerObj *layer, char **items, int numitems);
+  MS_DLL_EXPORT int msLayerGetShape(layerObj *layer, shapeObj *shape, resultObj *record);
+  MS_DLL_EXPORT int msLayerGetExtent(layerObj *layer, rectObj *extent);
+  MS_DLL_EXPORT int msLayerSetExtent( layerObj *layer, double minx, double miny, double maxx, double maxy);
+  MS_DLL_EXPORT int msLayerGetAutoStyle(mapObj *map, layerObj *layer, classObj *c, shapeObj* shape);
+  MS_DLL_EXPORT int msLayerGetFeatureStyle(mapObj *map, layerObj *layer, classObj *c, shapeObj* shape);
+  MS_DLL_EXPORT void msLayerAddProcessing( layerObj *layer, const char *directive );
+  MS_DLL_EXPORT void msLayerSetProcessingKey( layerObj *layer, const char *key,
+      const char *value);
+  MS_DLL_EXPORT char *msLayerGetProcessing( layerObj *layer, int proc_index);
+  MS_DLL_EXPORT char *msLayerGetProcessingKey( layerObj *layer, const char *);
+  MS_DLL_EXPORT int msLayerClearProcessing( layerObj *layer );
+  MS_DLL_EXPORT char* msLayerGetFilterString( layerObj *layer );
+
+  MS_DLL_EXPORT int msLayerSupportsCommonFilters(layerObj *layer);
+  MS_DLL_EXPORT int msTokenizeExpression(expressionObj *expression, char **list, int *listsize);
+
+  MS_DLL_EXPORT int msLayerSetTimeFilter(layerObj *lp, const char *timestring,
+                                         const char *timefield);
+  /* Helper functions for layers */
+  MS_DLL_EXPORT int msLayerMakeBackticsTimeFilter(layerObj *lp, const char *timestring,
+      const char *timefield);
+
+  MS_DLL_EXPORT int msLayerMakePlainTimeFilter(layerObj *lp, const char *timestring,
+      const char *timefield);
+
+  MS_DLL_EXPORT int msLayerApplyCondSQLFilterToLayer(FilterEncodingNode *psNode, mapObj *map,
+      int iLayerIndex);
+
+  MS_DLL_EXPORT int msLayerApplyPlainFilterToLayer(FilterEncodingNode *psNode, mapObj *map,
+      int iLayerIndex);
+
+
+  /* maplayer.c */
+  MS_DLL_EXPORT int msLayerGetNumFeatures(layerObj *layer);
+
+  MS_DLL_EXPORT int msLayerSupportsPaging(layerObj *layer);
+
+  MS_DLL_EXPORT void msLayerEnablePaging(layerObj *layer, int value);
+  MS_DLL_EXPORT int msLayerGetPaging(layerObj *layer);
+
+  MS_DLL_EXPORT int msLayerGetMaxFeaturesToDraw(layerObj *layer, outputFormatObj *format);
+
+  MS_DLL_EXPORT char *msLayerEscapeSQLParam(layerObj *layer, const char* pszString);
+  MS_DLL_EXPORT char *msLayerEscapePropertyName(layerObj *layer, const char* pszString);
+
+  /* These are special because SWF is using these */
+  int msOGRLayerNextShape(layerObj *layer, shapeObj *shape);
+  int msOGRLayerGetItems(layerObj *layer);
+  void msOGRLayerFreeItemInfo(layerObj *layer);
+  int msOGRLayerGetShape(layerObj *layer, shapeObj *shape, resultObj *record);
+  int msOGRLayerGetExtent(layerObj *layer, rectObj *extent);
 
 #ifdef USE_OGR
-MS_DLL_EXPORT int msOGRGeometryToShape(OGRGeometryH hGeometry, shapeObj *shape,
-                         OGRwkbGeometryType type);
+  MS_DLL_EXPORT int msOGRGeometryToShape(OGRGeometryH hGeometry, shapeObj *shape,
+                                         OGRwkbGeometryType type);
 #endif /* USE_OGR */
 
-MS_DLL_EXPORT int drawSDE(mapObj *map, layerObj *layer, gdImagePtr img);
-
-MS_DLL_EXPORT int msInitializeVirtualTable(layerObj *layer);
-MS_DLL_EXPORT int msConnectLayer(layerObj *layer, const int connectiontype, 
-                                 const char *library_str);
-
-MS_DLL_EXPORT int msINLINELayerInitializeVirtualTable(layerObj *layer);
-MS_DLL_EXPORT int msSHPLayerInitializeVirtualTable(layerObj *layer);
-MS_DLL_EXPORT int msTiledSHPLayerInitializeVirtualTable(layerObj *layer);
-MS_DLL_EXPORT int msSDELayerInitializeVirtualTable(layerObj *layer);
-MS_DLL_EXPORT int msOGRLayerInitializeVirtualTable(layerObj *layer);
-MS_DLL_EXPORT int msPostGISLayerInitializeVirtualTable(layerObj *layer);
-MS_DLL_EXPORT int msOracleSpatialLayerInitializeVirtualTable(layerObj *layer);
-MS_DLL_EXPORT int msWFSLayerInitializeVirtualTable(layerObj *layer);
-MS_DLL_EXPORT int msGraticuleLayerInitializeVirtualTable(layerObj *layer);
-MS_DLL_EXPORT int msRASTERLayerInitializeVirtualTable(layerObj *layer);
-MS_DLL_EXPORT int msPluginLayerInitializeVirtualTable(layerObj *layer);
-MS_DLL_EXPORT int msUnionLayerInitializeVirtualTable(layerObj *layer);
-MS_DLL_EXPORT void msPluginFreeVirtualTableFactory();
-
-/* ==================================================================== */
-/*      Prototypes for functions in mapdraw.c                           */
-/* ==================================================================== */
-MS_DLL_EXPORT void msClearLayerPenValues(layerObj *layer);
-MS_DLL_EXPORT void msClearScalebarPenValues(scalebarObj *scalebar);
-MS_DLL_EXPORT void msClearLegendPenValues(legendObj *legend);
-MS_DLL_EXPORT void msClearReferenceMapPenValues(referenceMapObj *referencemap);
-MS_DLL_EXPORT void msClearQueryMapPenValues(queryMapObj *querymap);
-MS_DLL_EXPORT void msClearPenValues(mapObj *map);
-
-MS_DLL_EXPORT imageObj *msPrepareImage(mapObj *map, int allow_nonsquare);
-MS_DLL_EXPORT imageObj *msDrawMap(mapObj *map, int querymap);
-MS_DLL_EXPORT int msLayerIsVisible(mapObj *map, layerObj *layer);
-MS_DLL_EXPORT int msDrawLayer(mapObj *map, layerObj *layer, imageObj *image);
-MS_DLL_EXPORT int msDrawVectorLayer(mapObj *map, layerObj *layer, imageObj *image);
-MS_DLL_EXPORT int msDrawQueryLayer(mapObj *map, layerObj *layer, imageObj *image);
-MS_DLL_EXPORT int msDrawWMSLayer(mapObj *map, layerObj *layer, imageObj *image);
-MS_DLL_EXPORT int msDrawWFSLayer(mapObj *map, layerObj *layer, imageObj *image);
-MS_DLL_EXPORT int msDrawShape(mapObj *map, layerObj *layer, shapeObj *shape, imageObj *image, int style, int querymapMode);
-MS_DLL_EXPORT int msDrawPoint(mapObj *map, layerObj *layer, pointObj *point, imageObj *image, int classindex, char *labeltext);
+  MS_DLL_EXPORT int msInitializeVirtualTable(layerObj *layer);
+  MS_DLL_EXPORT int msConnectLayer(layerObj *layer, const int connectiontype,
+                                   const char *library_str);
+
+  MS_DLL_EXPORT int msINLINELayerInitializeVirtualTable(layerObj *layer);
+  MS_DLL_EXPORT int msSHPLayerInitializeVirtualTable(layerObj *layer);
+  MS_DLL_EXPORT int msTiledSHPLayerInitializeVirtualTable(layerObj *layer);
+  MS_DLL_EXPORT int msSDELayerInitializeVirtualTable(layerObj *layer);
+  MS_DLL_EXPORT int msOGRLayerInitializeVirtualTable(layerObj *layer);
+  MS_DLL_EXPORT int msPostGISLayerInitializeVirtualTable(layerObj *layer);
+  MS_DLL_EXPORT int msOracleSpatialLayerInitializeVirtualTable(layerObj *layer);
+  MS_DLL_EXPORT int msWFSLayerInitializeVirtualTable(layerObj *layer);
+  MS_DLL_EXPORT int msGraticuleLayerInitializeVirtualTable(layerObj *layer);
+  MS_DLL_EXPORT int msRASTERLayerInitializeVirtualTable(layerObj *layer);
+  MS_DLL_EXPORT int msUVRASTERLayerInitializeVirtualTable(layerObj *layer);
+  MS_DLL_EXPORT int msPluginLayerInitializeVirtualTable(layerObj *layer);
+  MS_DLL_EXPORT int msUnionLayerInitializeVirtualTable(layerObj *layer);
+  MS_DLL_EXPORT void msPluginFreeVirtualTableFactory(void);
+
+  /* ==================================================================== */
+  /*      Prototypes for functions in mapdraw.c                           */
+  /* ==================================================================== */
+  MS_DLL_EXPORT void msClearLayerPenValues(layerObj *layer);
+  MS_DLL_EXPORT void msClearScalebarPenValues(scalebarObj *scalebar);
+  MS_DLL_EXPORT void msClearLegendPenValues(legendObj *legend);
+  MS_DLL_EXPORT void msClearReferenceMapPenValues(referenceMapObj *referencemap);
+  MS_DLL_EXPORT void msClearQueryMapPenValues(queryMapObj *querymap);
+  MS_DLL_EXPORT void msClearPenValues(mapObj *map);
+
+  MS_DLL_EXPORT imageObj *msPrepareImage(mapObj *map, int allow_nonsquare);
+  MS_DLL_EXPORT imageObj *msDrawMap(mapObj *map, int querymap);
+  MS_DLL_EXPORT int msLayerIsVisible(mapObj *map, layerObj *layer);
+  MS_DLL_EXPORT int msDrawLayer(mapObj *map, layerObj *layer, imageObj *image);
+  MS_DLL_EXPORT int msDrawVectorLayer(mapObj *map, layerObj *layer, imageObj *image);
+  MS_DLL_EXPORT int msDrawQueryLayer(mapObj *map, layerObj *layer, imageObj *image);
+  MS_DLL_EXPORT int msDrawWMSLayer(mapObj *map, layerObj *layer, imageObj *image);
+  MS_DLL_EXPORT int msDrawWFSLayer(mapObj *map, layerObj *layer, imageObj *image);
+  
+#define MS_DRAWMODE_FEATURES    0x00001
+#define MS_DRAW_FEATURES(mode) (MS_DRAWMODE_FEATURES&(mode))
+#define MS_DRAWMODE_LABELS      0x00002
+#define MS_DRAW_LABELS(mode) (MS_DRAWMODE_LABELS&(mode))
+#define MS_DRAWMODE_SINGLESTYLE 0x00004
+#define MS_DRAW_SINGLESTYLE(mode) (MS_DRAWMODE_SINGLESTYLE&(mode))
+#define MS_DRAWMODE_QUERY       0x00008
+#define MS_DRAW_QUERY(mode) (MS_DRAWMODE_QUERY&(mode))
+#define MS_DRAWMODE_UNCLIPPEDLABELS       0x00010
+#define MS_DRAW_UNCLIPPED_LABELS(mode) (MS_DRAWMODE_UNCLIPPEDLABELS&(mode))
+#define MS_DRAWMODE_UNCLIPPEDLINES       0x00020
+#define MS_DRAW_UNCLIPPED_LINES(mode) (MS_DRAWMODE_UNCLIPPEDLINES&(mode))
+
+  MS_DLL_EXPORT int msDrawShape(mapObj *map, layerObj *layer, shapeObj *shape, imageObj *image, int style, int mode);
+  MS_DLL_EXPORT int msDrawPoint(mapObj *map, layerObj *layer, pointObj *point, imageObj *image, int classindex, char *labeltext);
 
   /*Range Support*/
-MS_DLL_EXPORT int msShapeToRange(styleObj *style, shapeObj *shape);
-MS_DLL_EXPORT int msValueToRange(styleObj *style, double fieldVal);
-
-MS_DLL_EXPORT int msDrawMarkerSymbol(symbolSetObj *symbolset,imageObj *image, pointObj *p, styleObj *style, double scalefactor);
-MS_DLL_EXPORT int msDrawLineSymbol(symbolSetObj *symbolset, imageObj *image, shapeObj *p, styleObj *style, double scalefactor);
-MS_DLL_EXPORT int msDrawShadeSymbol(symbolSetObj *symbolset, imageObj *image, shapeObj *p, styleObj *style, double scalefactor);
-MS_DLL_EXPORT int msCircleDrawLineSymbol(symbolSetObj *symbolset, imageObj *image, pointObj *p, double r, styleObj *style, double scalefactor);
-MS_DLL_EXPORT int msCircleDrawShadeSymbol(symbolSetObj *symbolset, imageObj *image, pointObj *p, double r, styleObj *style, double scalefactor);
-MS_DLL_EXPORT int msDrawPieSlice(symbolSetObj *symbolset, imageObj *image, pointObj *p, styleObj *style, double radius, double start, double end);
-
-
-
-MS_DLL_EXPORT int msDrawLabel(mapObj *map, imageObj *image, pointObj labelPnt, char *string, labelObj *label, double scalefactor);
-MS_DLL_EXPORT int msDrawText(imageObj *image, pointObj labelPnt, char *string, labelObj *label, fontSetObj *fontset, double scalefactor);
-MS_DLL_EXPORT int msDrawTextLine(imageObj *image, char *string, labelObj *label, labelPathObj *labelpath, fontSetObj *fontset, double scalefactor);
-MS_DLL_EXPORT int msDrawLabelCache(imageObj *image, mapObj *map);
-
-MS_DLL_EXPORT void msImageStartLayer(mapObj *map, layerObj *layer, imageObj *image);
-MS_DLL_EXPORT void msImageEndLayer(mapObj *map, layerObj *layer, imageObj *image);
-
-MS_DLL_EXPORT void msDrawStartShape(mapObj *map, layerObj *layer, imageObj *image, shapeObj *shape);
-MS_DLL_EXPORT void msDrawEndShape(mapObj *map, layerObj *layer, imageObj *image, shapeObj *shape);
-/* ==================================================================== */
-/*      End of Prototypes for functions in mapdraw.c                    */
-/* ==================================================================== */
-
-/* ==================================================================== */
-/*      Prototypes for functions in mapgeomutil.cpp                       */
-/* ==================================================================== */
-MS_DLL_EXPORT shapeObj *msRasterizeArc(double x0, double y0, double radius, double startAngle, double endAngle, int isSlice);
-MS_DLL_EXPORT int msHatchPolygon(imageObj *img, shapeObj *poly, double spacing, double width, double angle, colorObj *color);
-
-
-
-/* ==================================================================== */
-/*      Prototypes for functions in mapimagemap.c                       */
-/* ==================================================================== */
-MS_DLL_EXPORT imageObj *msImageCreateIM(int width, int height, outputFormatObj *format, char *imagepath, char *imageurl, double resolution, double defresolution);
-MS_DLL_EXPORT imageObj *msImageLoadIM( const char *filename );
-MS_DLL_EXPORT imageObj *msImageLoadGD( const char *filename );
-MS_DLL_EXPORT imageObj *msImageLoadGDCtx( gdIOCtx *ctx, const char *driver );
-MS_DLL_EXPORT void msImageInitIM( imageObj *image );
-MS_DLL_EXPORT void msImageStartLayerIM(mapObj *map, layerObj *layer, imageObj *image);
-MS_DLL_EXPORT int msSaveImageIM(imageObj* img, char *filename, outputFormatObj *format);
-MS_DLL_EXPORT int msSaveImageIM_LL(imageObj* img, char *filename, int type, int transparent, int interlace, int quality);
-MS_DLL_EXPORT void msFreeImagexsIM(imageObj* img);
-MS_DLL_EXPORT void msFreeImageIM(imageObj* img);
-MS_DLL_EXPORT void msCircleDrawLineSymbolIM(symbolSetObj *symbolset, imageObj* img, pointObj *p, double r, styleObj *style, double scalefactor);
-MS_DLL_EXPORT void msCircleDrawShadeSymbolIM(symbolSetObj *symbolset, imageObj* img, pointObj *p, double r, styleObj *style, double scalefactor);
-MS_DLL_EXPORT void msDrawMarkerSymbolIM(symbolSetObj *symbolset, imageObj* img, pointObj *p, styleObj *style, double scalefactor);
-MS_DLL_EXPORT void msDrawLineSymbolIM(symbolSetObj *symbolset, imageObj* img, shapeObj *p, styleObj *style, double scalefactor);
-MS_DLL_EXPORT void msDrawShadeSymbolIM(symbolSetObj *symbolset, imageObj* img, shapeObj *p, styleObj *style, double scalefactor);
-MS_DLL_EXPORT int msDrawTextIM(imageObj* img, pointObj labelPnt, char *string, labelObj *label, fontSetObj *fontset, double scalefactor);
-MS_DLL_EXPORT int msDrawLabelCacheIM(imageObj* img, mapObj *map);
-/* ==================================================================== */
-/*      End of Prototypes for functions in mapimagemap.c                */
-/* ==================================================================== */
+  MS_DLL_EXPORT int msShapeToRange(styleObj *style, shapeObj *shape);
+  MS_DLL_EXPORT int msValueToRange(styleObj *style, double fieldVal);
 
-#define RESOLVE_PEN_GD(img,color) { if( (color).pen == MS_PEN_UNSET ) msImageSetPenGD( img, &(color) ); }
-MS_DLL_EXPORT int msImageSetPenGD(gdImagePtr img, colorObj *color);
-
-/* various JOIN functions (in mapjoin.c) */
-MS_DLL_EXPORT int msJoinConnect(layerObj *layer, joinObj *join);
-MS_DLL_EXPORT int msJoinPrepare(joinObj *join, shapeObj *shape);
-MS_DLL_EXPORT int msJoinNext(joinObj *join);
-MS_DLL_EXPORT int msJoinClose(joinObj *join);
-
-/*in mapraster.c */
-MS_DLL_EXPORT int msDrawRasterLayerLow(mapObj *map, layerObj *layer, imageObj *image, rasterBufferObj *rb );
-MS_DLL_EXPORT int msAddColorGD(mapObj *map, gdImagePtr img, int cmt, int r, int g, int b);
-MS_DLL_EXPORT int msGetClass(layerObj *layer, colorObj *color);
-MS_DLL_EXPORT int msGetClass_FloatRGB(layerObj *layer, float fValue,
-                                      int red, int green, int blue );
-
-/* in mapdrawgdal.c */
-MS_DLL_EXPORT int msDrawRasterLayerGDAL(mapObj *map, layerObj *layer, imageObj *image, rasterBufferObj *rb, void *hDSVoid );
-MS_DLL_EXPORT int msGetGDALGeoTransform(void *hDS, mapObj *map, layerObj *layer, double *padfGeoTransform );
-MS_DLL_EXPORT int *msGetGDALBandList( layerObj *layer, void *hDS, int max_bands, int *band_count );
-MS_DLL_EXPORT double msGetGDALNoDataValue( layerObj *layer, void *hBand, int *pbGotNoData );
-
-/* in mapchart.c */
-MS_DLL_EXPORT int msDrawChartLayer(mapObj *map, layerObj *layer, imageObj *image);
-
-/* ==================================================================== */
-/*      End of prototypes for functions in mapgd.c                      */
-/* ==================================================================== */
-
-/* ==================================================================== */
-/*      Prototypes for functions in maputil.c                           */
-/* ==================================================================== */
-
-MS_DLL_EXPORT void *msSmallMalloc( size_t nSize );
-MS_DLL_EXPORT void * msSmallRealloc( void * pData, size_t nNewSize );
-MS_DLL_EXPORT void *msSmallCalloc( size_t nCount, size_t nSize );
-MS_DLL_EXPORT int msIntegerInArray(const int value, int *array, int numelements);
-
-MS_DLL_EXPORT int msExtentsOverlap(mapObj *map, layerObj *layer);
-MS_DLL_EXPORT char *msBuildOnlineResource(mapObj *map, cgiRequestObj *req);
-
-/* For mapswf */
-MS_DLL_EXPORT int getRgbColor(mapObj *map,int i,int *r,int *g,int *b); /* maputil.c */
-
-MS_DLL_EXPORT int msBindLayerToShape(layerObj *layer, shapeObj *shape, int querymapMode);
-MS_DLL_EXPORT int msValidateContexts(mapObj *map);
-MS_DLL_EXPORT int msEvalContext(mapObj *map, layerObj *layer, char *context);
-MS_DLL_EXPORT int msEvalExpression(layerObj *layer, shapeObj *shape, expressionObj *expression, int itemindex);
-MS_DLL_EXPORT int msShapeGetClass(layerObj *layer, mapObj *map, shapeObj *shape, int *classgroup, int numclasses);
-MS_DLL_EXPORT char *msShapeGetAnnotation(layerObj *layer, shapeObj *shape);
-MS_DLL_EXPORT int msShapeCheckSize(shapeObj *shape, double minfeaturesize);
-MS_DLL_EXPORT int msAdjustImage(rectObj rect, int *width, int *height);
-MS_DLL_EXPORT double msAdjustExtent(rectObj *rect, int width, int height);
-MS_DLL_EXPORT int msConstrainExtent(rectObj *bounds, rectObj *rect, double overlay);
-MS_DLL_EXPORT int *msGetLayersIndexByGroup(mapObj *map, char *groupname, int *nCount);
-MS_DLL_EXPORT unsigned char *msSaveImageBuffer(imageObj* image, int *size_ptr, outputFormatObj *format);
-MS_DLL_EXPORT shapeObj* msOffsetPolyline(shapeObj* shape, double offsetx, double offsety);
-/* Functions to chnage the drawing order of the layers. */
-/* Defined in mapobject.c */
-MS_DLL_EXPORT int msMoveLayerUp(mapObj *map, int nLayerIndex);
-MS_DLL_EXPORT int msMoveLayerDown(mapObj *map, int nLayerIndex);
-MS_DLL_EXPORT int msSetLayersdrawingOrder(mapObj *self, int *panIndexes);
-MS_DLL_EXPORT int msInsertLayer(mapObj *map, layerObj *layer, int nIndex);
-MS_DLL_EXPORT layerObj *msRemoveLayer(mapObj *map, int nIndex);
-
-/* Defined in layerobject.c */
-MS_DLL_EXPORT int msInsertClass(layerObj *layer,classObj *classobj,int nIndex);
-MS_DLL_EXPORT classObj *msRemoveClass(layerObj *layer, int nIndex);
-MS_DLL_EXPORT int msMoveClassUp(layerObj *layer, int nClassIndex);
-MS_DLL_EXPORT int msMoveClassDown(layerObj *layer, int nClassIndex);
-
-/* classobject.c */
-MS_DLL_EXPORT int msMoveStyleUp(classObj *classo, int nStyleIndex);
-MS_DLL_EXPORT int msMoveStyleDown(classObj *classo, int nStyleIndex);
-MS_DLL_EXPORT int msDeleteStyle(classObj *classo, int iStyleIndex);
-MS_DLL_EXPORT int msInsertStyle(classObj *classo, styleObj *style,
-                                int nStyleIndex);
-MS_DLL_EXPORT styleObj *msRemoveStyle(classObj *classo, int index);
-
-/* maplabel.c */
-MS_DLL_EXPORT int msInsertLabelStyle(labelObj *label, styleObj *style,
-                                     int nStyleIndex);
-MS_DLL_EXPORT int msMoveLabelStyleUp(labelObj *label, int nStyleIndex);
-MS_DLL_EXPORT int msMoveLabelStyleDown(labelObj *label, int nStyleIndex);
-MS_DLL_EXPORT int msDeleteLabelStyle(labelObj *label, int nStyleIndex);
-MS_DLL_EXPORT styleObj *msRemoveLabelStyle(labelObj *label, int nStyleIndex);
-
-/* Measured shape utility functions. */
-MS_DLL_EXPORT pointObj *msGetPointUsingMeasure(shapeObj *shape, double m);
-MS_DLL_EXPORT pointObj *msGetMeasureUsingPoint(shapeObj *shape, pointObj *point);
-
-MS_DLL_EXPORT char **msGetAllGroupNames(mapObj* map, int *numTok);
-MS_DLL_EXPORT char *msTmpFile(mapObj *map, const char *mappath, const char *tmppath, const char *ext);
-MS_DLL_EXPORT char *msTmpPath(mapObj *map, const char *mappath, const char *tmppath);
-MS_DLL_EXPORT char *msTmpFilename(const char *ext);
-MS_DLL_EXPORT void msForceTmpFileBase( const char *new_base );
-
-
-MS_DLL_EXPORT imageObj *msImageCreate(int width, int height, outputFormatObj *format, char *imagepath, char *imageurl, double resolution, double defresolution, colorObj *bg);
-
-MS_DLL_EXPORT void msAlphaBlend( 
+  MS_DLL_EXPORT int msDrawMarkerSymbol(symbolSetObj *symbolset,imageObj *image, pointObj *p, styleObj *style, double scalefactor);
+  MS_DLL_EXPORT int msDrawLineSymbol(symbolSetObj *symbolset, imageObj *image, shapeObj *p, styleObj *style, double scalefactor);
+  MS_DLL_EXPORT int msDrawShadeSymbol(symbolSetObj *symbolset, imageObj *image, shapeObj *p, styleObj *style, double scalefactor);
+  MS_DLL_EXPORT int msCircleDrawLineSymbol(symbolSetObj *symbolset, imageObj *image, pointObj *p, double r, styleObj *style, double scalefactor);
+  MS_DLL_EXPORT int msCircleDrawShadeSymbol(symbolSetObj *symbolset, imageObj *image, pointObj *p, double r, styleObj *style, double scalefactor);
+  MS_DLL_EXPORT int msDrawPieSlice(symbolSetObj *symbolset, imageObj *image, pointObj *p, styleObj *style, double radius, double start, double end);
+
+
+
+  MS_DLL_EXPORT int msDrawLabel(mapObj *map, imageObj *image, pointObj labelPnt, char *string, labelObj *label, double scalefactor);
+  MS_DLL_EXPORT int msDrawText(imageObj *image, pointObj labelPnt, char *string, labelObj *label, fontSetObj *fontset, double scalefactor);
+  MS_DLL_EXPORT int msDrawTextLine(imageObj *image, char *string, labelObj *label, labelPathObj *labelpath, fontSetObj *fontset, double scalefactor);
+  MS_DLL_EXPORT int msDrawLabelCache(imageObj *image, mapObj *map);
+
+  MS_DLL_EXPORT void msImageStartLayer(mapObj *map, layerObj *layer, imageObj *image);
+  MS_DLL_EXPORT void msImageEndLayer(mapObj *map, layerObj *layer, imageObj *image);
+
+  MS_DLL_EXPORT void msDrawStartShape(mapObj *map, layerObj *layer, imageObj *image, shapeObj *shape);
+  MS_DLL_EXPORT void msDrawEndShape(mapObj *map, layerObj *layer, imageObj *image, shapeObj *shape);
+  /* ==================================================================== */
+  /*      End of Prototypes for functions in mapdraw.c                    */
+  /* ==================================================================== */
+
+  /* ==================================================================== */
+  /*      Prototypes for functions in mapgeomutil.cpp                       */
+  /* ==================================================================== */
+  MS_DLL_EXPORT shapeObj *msRasterizeArc(double x0, double y0, double radius, double startAngle, double endAngle, int isSlice);
+  MS_DLL_EXPORT int msHatchPolygon(imageObj *img, shapeObj *poly, double spacing, double width, double *pattern, int patternlength, double angle, colorObj *color);
+
+
+
+  /* ==================================================================== */
+  /*      Prototypes for functions in mapimagemap.c                       */
+  /* ==================================================================== */
+  MS_DLL_EXPORT imageObj *msImageCreateIM(int width, int height, outputFormatObj *format, char *imagepath, char *imageurl, double resolution, double defresolution);
+#ifdef USE_GD
+  MS_DLL_EXPORT imageObj *msImageLoadGD( const char *filename );
+  MS_DLL_EXPORT imageObj *msImageLoadGDCtx( gdIOCtx *ctx, const char *driver );
+  MS_DLL_EXPORT int msGDSetup();
+  MS_DLL_EXPORT void msGDCleanup(int signal);
+#else
+//#define gdIOCtx void*
+#endif
+  MS_DLL_EXPORT void msImageStartLayerIM(mapObj *map, layerObj *layer, imageObj *image);
+  MS_DLL_EXPORT int msSaveImageIM(imageObj* img, char *filename, outputFormatObj *format);
+  MS_DLL_EXPORT void msFreeImageIM(imageObj* img);
+  MS_DLL_EXPORT void msDrawMarkerSymbolIM(symbolSetObj *symbolset, imageObj* img, pointObj *p, styleObj *style, double scalefactor);
+  MS_DLL_EXPORT void msDrawLineSymbolIM(symbolSetObj *symbolset, imageObj* img, shapeObj *p, styleObj *style, double scalefactor);
+  MS_DLL_EXPORT void msDrawShadeSymbolIM(symbolSetObj *symbolset, imageObj* img, shapeObj *p, styleObj *style, double scalefactor);
+  MS_DLL_EXPORT int msDrawTextIM(imageObj* img, pointObj labelPnt, char *string, labelObj *label, fontSetObj *fontset, double scalefactor);
+  /* ==================================================================== */
+  /*      End of Prototypes for functions in mapimagemap.c                */
+  /* ==================================================================== */
+
+
+  /* various JOIN functions (in mapjoin.c) */
+  MS_DLL_EXPORT int msJoinConnect(layerObj *layer, joinObj *join);
+  MS_DLL_EXPORT int msJoinPrepare(joinObj *join, shapeObj *shape);
+  MS_DLL_EXPORT int msJoinNext(joinObj *join);
+  MS_DLL_EXPORT int msJoinClose(joinObj *join);
+
+  /*in mapraster.c */
+  MS_DLL_EXPORT int msDrawRasterLayerLow(mapObj *map, layerObj *layer, imageObj *image, rasterBufferObj *rb );
+#ifdef USE_GD
+  MS_DLL_EXPORT int msAddColorGD(mapObj *map, gdImagePtr img, int cmt, int r, int g, int b);
+#endif
+  MS_DLL_EXPORT int msGetClass(layerObj *layer, colorObj *color, int colormap_index);
+  MS_DLL_EXPORT int msGetClass_FloatRGB(layerObj *layer, float fValue,
+                                        int red, int green, int blue );
+
+  /* in mapdrawgdal.c */
+  MS_DLL_EXPORT int msDrawRasterLayerGDAL(mapObj *map, layerObj *layer, imageObj *image, rasterBufferObj *rb, void *hDSVoid );
+  MS_DLL_EXPORT int msGetGDALGeoTransform(void *hDS, mapObj *map, layerObj *layer, double *padfGeoTransform );
+  MS_DLL_EXPORT int *msGetGDALBandList( layerObj *layer, void *hDS, int max_bands, int *band_count );
+  MS_DLL_EXPORT double msGetGDALNoDataValue( layerObj *layer, void *hBand, int *pbGotNoData );
+
+  /* in mapchart.c */
+  MS_DLL_EXPORT int msDrawChartLayer(mapObj *map, layerObj *layer, imageObj *image);
+
+  /* ==================================================================== */
+  /*      End of prototypes for functions in mapgd.c                      */
+  /* ==================================================================== */
+
+  /* ==================================================================== */
+  /*      Prototypes for functions in maputil.c                           */
+  /* ==================================================================== */
+
+  MS_DLL_EXPORT int msScaleInBounds(double scale, double minscale, double maxscale);
+  MS_DLL_EXPORT void *msSmallMalloc( size_t nSize );
+  MS_DLL_EXPORT void * msSmallRealloc( void * pData, size_t nNewSize );
+  MS_DLL_EXPORT void *msSmallCalloc( size_t nCount, size_t nSize );
+  MS_DLL_EXPORT int msIntegerInArray(const int value, int *array, int numelements);
+
+  MS_DLL_EXPORT int msExtentsOverlap(mapObj *map, layerObj *layer);
+  MS_DLL_EXPORT char *msBuildOnlineResource(mapObj *map, cgiRequestObj *req);
+
+  /* For mapswf */
+  MS_DLL_EXPORT int getRgbColor(mapObj *map,int i,int *r,int *g,int *b); /* maputil.c */
+
+  MS_DLL_EXPORT int msBindLayerToShape(layerObj *layer, shapeObj *shape, int querymapMode);
+  MS_DLL_EXPORT int msValidateContexts(mapObj *map);
+  MS_DLL_EXPORT int msEvalContext(mapObj *map, layerObj *layer, char *context);
+  MS_DLL_EXPORT int msEvalExpression(layerObj *layer, shapeObj *shape, expressionObj *expression, int itemindex);
+  MS_DLL_EXPORT int msShapeGetClass(layerObj *layer, mapObj *map, shapeObj *shape, int *classgroup, int numclasses);
+  MS_DLL_EXPORT int msShapeGetAnnotation(layerObj *layer, shapeObj *shape);
+  MS_DLL_EXPORT int msShapeCheckSize(shapeObj *shape, double minfeaturesize);
+  MS_DLL_EXPORT int msAdjustImage(rectObj rect, int *width, int *height);
+  MS_DLL_EXPORT double msAdjustExtent(rectObj *rect, int width, int height);
+  MS_DLL_EXPORT int msConstrainExtent(rectObj *bounds, rectObj *rect, double overlay);
+  MS_DLL_EXPORT int *msGetLayersIndexByGroup(mapObj *map, char *groupname, int *nCount);
+  MS_DLL_EXPORT unsigned char *msSaveImageBuffer(imageObj* image, int *size_ptr, outputFormatObj *format);
+  MS_DLL_EXPORT shapeObj* msOffsetPolyline(shapeObj* shape, double offsetx, double offsety);
+  MS_DLL_EXPORT int msMapSetLayerProjections(mapObj* map);
+
+  /* Functions to chnage the drawing order of the layers. */
+  /* Defined in mapobject.c */
+  MS_DLL_EXPORT int msMoveLayerUp(mapObj *map, int nLayerIndex);
+  MS_DLL_EXPORT int msMoveLayerDown(mapObj *map, int nLayerIndex);
+  MS_DLL_EXPORT int msSetLayersdrawingOrder(mapObj *self, int *panIndexes);
+  MS_DLL_EXPORT int msInsertLayer(mapObj *map, layerObj *layer, int nIndex);
+  MS_DLL_EXPORT layerObj *msRemoveLayer(mapObj *map, int nIndex);
+
+  /* Defined in layerobject.c */
+  MS_DLL_EXPORT int msInsertClass(layerObj *layer,classObj *classobj,int nIndex);
+  MS_DLL_EXPORT classObj *msRemoveClass(layerObj *layer, int nIndex);
+  MS_DLL_EXPORT int msMoveClassUp(layerObj *layer, int nClassIndex);
+  MS_DLL_EXPORT int msMoveClassDown(layerObj *layer, int nClassIndex);
+
+  /* classobject.c */
+  MS_DLL_EXPORT int msAddLabelToClass(classObj *classo, labelObj *label);
+  MS_DLL_EXPORT labelObj *msRemoveLabelFromClass(classObj *classo, int nLabelIndex);
+  MS_DLL_EXPORT int msMoveStyleUp(classObj *classo, int nStyleIndex);
+  MS_DLL_EXPORT int msMoveStyleDown(classObj *classo, int nStyleIndex);
+  MS_DLL_EXPORT int msDeleteStyle(classObj *classo, int nStyleIndex);
+  MS_DLL_EXPORT int msInsertStyle(classObj *classo, styleObj *style, int nStyleIndex);
+  MS_DLL_EXPORT styleObj *msRemoveStyle(classObj *classo, int index);
+
+  /* maplabel.c */
+  MS_DLL_EXPORT int msInsertLabelStyle(labelObj *label, styleObj *style,
+                                       int nStyleIndex);
+  MS_DLL_EXPORT int msMoveLabelStyleUp(labelObj *label, int nStyleIndex);
+  MS_DLL_EXPORT int msMoveLabelStyleDown(labelObj *label, int nStyleIndex);
+  MS_DLL_EXPORT int msDeleteLabelStyle(labelObj *label, int nStyleIndex);
+  MS_DLL_EXPORT styleObj *msRemoveLabelStyle(labelObj *label, int nStyleIndex);
+
+  /* Measured shape utility functions. */
+  MS_DLL_EXPORT pointObj *msGetPointUsingMeasure(shapeObj *shape, double m);
+  MS_DLL_EXPORT pointObj *msGetMeasureUsingPoint(shapeObj *shape, pointObj *point);
+
+  MS_DLL_EXPORT char **msGetAllGroupNames(mapObj* map, int *numTok);
+  MS_DLL_EXPORT char *msTmpFile(mapObj *map, const char *mappath, const char *tmppath, const char *ext);
+  MS_DLL_EXPORT char *msTmpPath(mapObj *map, const char *mappath, const char *tmppath);
+  MS_DLL_EXPORT char *msTmpFilename(const char *ext);
+  MS_DLL_EXPORT void msForceTmpFileBase( const char *new_base );
+
+
+  MS_DLL_EXPORT imageObj *msImageCreate(int width, int height, outputFormatObj *format, char *imagepath, char *imageurl, double resolution, double defresolution, colorObj *bg);
+
+  MS_DLL_EXPORT void msAlphaBlend(
     unsigned char red_src, unsigned char green_src,
-    unsigned char blue_src, unsigned char alpha_src, 
+    unsigned char blue_src, unsigned char alpha_src,
     unsigned char *red_dst, unsigned char *green_dst,
     unsigned char *blue_dst, unsigned char *alpha_dst );
-MS_DLL_EXPORT void msAlphaBlendPM( 
+  MS_DLL_EXPORT void msAlphaBlendPM(
     unsigned char red_src, unsigned char green_src,
-    unsigned char blue_src, unsigned char alpha_src, 
+    unsigned char blue_src, unsigned char alpha_src,
     unsigned char *red_dst, unsigned char *green_dst,
     unsigned char *blue_dst, unsigned char *alpha_dst );
 
-MS_DLL_EXPORT int msCheckParentPointer(void* p, char* objname);
-
-MS_DLL_EXPORT int *msAllocateValidClassGroups(layerObj *lp, int *nclasses);
-
-MS_DLL_EXPORT void msFreeRasterBuffer(rasterBufferObj *b);
-/* ==================================================================== */
-/*      End of prototypes for functions in maputil.c                    */
-/* ==================================================================== */
-
-
-/* ==================================================================== */
-/*      prototypes for functions in mapoutput.c                         */
-/* ==================================================================== */
-
-MS_DLL_EXPORT void msApplyDefaultOutputFormats( mapObj * );
-MS_DLL_EXPORT void msFreeOutputFormat( outputFormatObj * );
-MS_DLL_EXPORT int msGetOutputFormatIndex(mapObj *map, const char *imagetype);
-MS_DLL_EXPORT int msRemoveOutputFormat(mapObj *map, const char *imagetype);
-MS_DLL_EXPORT int msAppendOutputFormat(mapObj *map, outputFormatObj *format);
-MS_DLL_EXPORT outputFormatObj *msSelectOutputFormat( mapObj *map, const char *imagetype );
-MS_DLL_EXPORT void msApplyOutputFormat( outputFormatObj **target, outputFormatObj *format, int transparent, int interlaced, int imagequality );
-MS_DLL_EXPORT const char *msGetOutputFormatOption( outputFormatObj *format, const char *optionkey, const char *defaultresult );
-MS_DLL_EXPORT outputFormatObj *msCreateDefaultOutputFormat( mapObj *map, const char *driver, const char *name );
-MS_DLL_EXPORT int msPostMapParseOutputFormatSetup( mapObj *map );
-MS_DLL_EXPORT void msSetOutputFormatOption( outputFormatObj *format, const char *key, const char *value );
-MS_DLL_EXPORT void msGetOutputFormatMimeList( mapObj *map, char **mime_list, int max_mime );
-MS_DLL_EXPORT void msGetOutputFormatMimeListImg( mapObj *map, char **mime_list, int max_mime );
-MS_DLL_EXPORT void msGetOutputFormatMimeListWMS( mapObj *map, char **mime_list, int max_mime );
-MS_DLL_EXPORT outputFormatObj *msCloneOutputFormat( outputFormatObj *format );
-MS_DLL_EXPORT int msOutputFormatValidate( outputFormatObj *format, 
-                                          int issue_error );
-
-#ifndef gdImageTrueColor
-#  define gdImageTrueColor(x) (0)
-#endif /* not gdImageTrueColor */
-
-/* ==================================================================== */
-/*      End of prototypes for functions in mapoutput.c                  */
-/* ==================================================================== */
-
-/* ==================================================================== */
-/*      prototypes for functions in mapgdal.c                           */
-/* ==================================================================== */
-MS_DLL_EXPORT int msSaveImageGDAL( mapObj *map, imageObj *image, char *filename );
-MS_DLL_EXPORT int msInitDefaultGDALOutputFormat( outputFormatObj *format );
-
-/* ==================================================================== */
-/*      prototypes for functions in mapogroutput.c                      */
-/* ==================================================================== */
-MS_DLL_EXPORT int msInitDefaultOGROutputFormat( outputFormatObj *format );
-MS_DLL_EXPORT int msOGRWriteFromQuery( mapObj *map, outputFormatObj *format,
-                                       int sendheaders );
-
-/* ==================================================================== */
-/*      Public prototype for mapogr.cpp functions.                      */
-/* ==================================================================== */
-int MS_DLL_EXPORT msOGRLayerWhichShapes(layerObj *layer, rectObj rect, int isQuery);
-int MS_DLL_EXPORT msOGRLayerOpen(layerObj *layer, const char *pszOverrideConnection); /* in mapogr.cpp */
-int MS_DLL_EXPORT msOGRLayerClose(layerObj *layer);
-
-char MS_DLL_EXPORT *msOGRShapeToWKT(shapeObj *shape);
-shapeObj MS_DLL_EXPORT *msOGRShapeFromWKT(const char *string);
-int msOGRUpdateStyleFromString(mapObj *map, layerObj *layer, classObj *c,
-                                  const char *stylestring);
-
-/* ==================================================================== */
-/*      prototypes for functions in mapcopy                             */
-/* ==================================================================== */
-MS_DLL_EXPORT int msCopyMap(mapObj *dst, mapObj *src);
-MS_DLL_EXPORT int msCopyLayer(layerObj *dst, layerObj *src);
-MS_DLL_EXPORT int msCopyPoint(pointObj *dst, pointObj *src);
-MS_DLL_EXPORT int msCopyFontSet(fontSetObj *dst, fontSetObj *src, mapObj *map);
-MS_DLL_EXPORT void copyProperty(void *dst, void *src, int size);
-MS_DLL_EXPORT char *copyStringProperty(char **dst, char *src);
-MS_DLL_EXPORT int msCopyClass(classObj *dst, classObj *src, layerObj *layer);
-MS_DLL_EXPORT int msCopyStyle(styleObj *dst, styleObj *src);
-MS_DLL_EXPORT int msCopyLabel(labelObj *dst, labelObj *src);
-int msCopyExpression(expressionObj *dst, expressionObj *src);
-
-/* ==================================================================== */
-/*      end prototypes for functions in mapcopy                         */
-/* ==================================================================== */
-
-/* ==================================================================== */
-/*      mappool.c: connection pooling API.                              */
-/* ==================================================================== */
-MS_DLL_EXPORT void *msConnPoolRequest( layerObj *layer );
-MS_DLL_EXPORT void msConnPoolRelease( layerObj *layer, void * );
-MS_DLL_EXPORT void msConnPoolRegister( layerObj *layer,
-                                        void *conn_handle,
-                                        void (*close)( void * ) );
-MS_DLL_EXPORT void msConnPoolCloseUnreferenced( void );
-MS_DLL_EXPORT void msConnPoolFinalCleanup( void );
-
-/* ==================================================================== */
-/*      prototypes for functions in mapcpl.c                            */
-/* ==================================================================== */
-MS_DLL_EXPORT const char *msGetBasename( const char *pszFullFilename );
-MS_DLL_EXPORT void *msGetSymbol(const char *pszLibrary, 
-                                const char *pszEntryPoint);
-
-/* ==================================================================== */
-/*      include definitions from mapows.h                               */
-/* ==================================================================== */
+  MS_DLL_EXPORT int msCheckParentPointer(void* p, char* objname);
+
+  MS_DLL_EXPORT int *msAllocateValidClassGroups(layerObj *lp, int *nclasses);
+
+  MS_DLL_EXPORT void msFreeRasterBuffer(rasterBufferObj *b);
+  /* ==================================================================== */
+  /*      End of prototypes for functions in maputil.c                    */
+  /* ==================================================================== */
+
+
+  /* ==================================================================== */
+  /*      prototypes for functions in mapoutput.c                         */
+  /* ==================================================================== */
+
+  MS_DLL_EXPORT void msApplyDefaultOutputFormats( mapObj * );
+  MS_DLL_EXPORT void msFreeOutputFormat( outputFormatObj * );
+  MS_DLL_EXPORT int msGetOutputFormatIndex(mapObj *map, const char *imagetype);
+  MS_DLL_EXPORT int msRemoveOutputFormat(mapObj *map, const char *imagetype);
+  MS_DLL_EXPORT int msAppendOutputFormat(mapObj *map, outputFormatObj *format);
+  MS_DLL_EXPORT outputFormatObj *msSelectOutputFormat( mapObj *map, const char *imagetype );
+  MS_DLL_EXPORT void msApplyOutputFormat( outputFormatObj **target, outputFormatObj *format, int transparent, int interlaced, int imagequality );
+  MS_DLL_EXPORT const char *msGetOutputFormatOption( outputFormatObj *format, const char *optionkey, const char *defaultresult );
+  MS_DLL_EXPORT outputFormatObj *msCreateDefaultOutputFormat( mapObj *map, const char *driver, const char *name );
+  MS_DLL_EXPORT int msPostMapParseOutputFormatSetup( mapObj *map );
+  MS_DLL_EXPORT void msSetOutputFormatOption( outputFormatObj *format, const char *key, const char *value );
+  MS_DLL_EXPORT void msGetOutputFormatMimeList( mapObj *map, char **mime_list, int max_mime );
+  MS_DLL_EXPORT void msGetOutputFormatMimeListImg( mapObj *map, char **mime_list, int max_mime );
+  MS_DLL_EXPORT void msGetOutputFormatMimeListWMS( mapObj *map, char **mime_list, int max_mime );
+  MS_DLL_EXPORT outputFormatObj *msCloneOutputFormat( outputFormatObj *format );
+  MS_DLL_EXPORT int msOutputFormatValidate( outputFormatObj *format,
+      int issue_error );
+
+  /* ==================================================================== */
+  /*      End of prototypes for functions in mapoutput.c                  */
+  /* ==================================================================== */
+
+  /* ==================================================================== */
+  /*      prototypes for functions in mapgdal.c                           */
+  /* ==================================================================== */
+  MS_DLL_EXPORT int msSaveImageGDAL( mapObj *map, imageObj *image, char *filename );
+  MS_DLL_EXPORT int msInitDefaultGDALOutputFormat( outputFormatObj *format );
+
+  /* ==================================================================== */
+  /*      prototypes for functions in mapogroutput.c                      */
+  /* ==================================================================== */
+  MS_DLL_EXPORT int msInitDefaultOGROutputFormat( outputFormatObj *format );
+  MS_DLL_EXPORT int msOGRWriteFromQuery( mapObj *map, outputFormatObj *format,
+                                         int sendheaders );
+
+  /* ==================================================================== */
+  /*      Public prototype for mapogr.cpp functions.                      */
+  /* ==================================================================== */
+  int MS_DLL_EXPORT msOGRLayerWhichShapes(layerObj *layer, rectObj rect, int isQuery);
+  int MS_DLL_EXPORT msOGRLayerOpen(layerObj *layer, const char *pszOverrideConnection); /* in mapogr.cpp */
+  int MS_DLL_EXPORT msOGRLayerClose(layerObj *layer);
+
+  char MS_DLL_EXPORT *msOGRShapeToWKT(shapeObj *shape);
+  shapeObj MS_DLL_EXPORT *msOGRShapeFromWKT(const char *string);
+  int msOGRUpdateStyleFromString(mapObj *map, layerObj *layer, classObj *c,
+                                 const char *stylestring);
+
+  /* ==================================================================== */
+  /*      prototypes for functions in mapcopy                             */
+  /* ==================================================================== */
+  MS_DLL_EXPORT int msCopyMap(mapObj *dst, mapObj *src);
+  MS_DLL_EXPORT int msCopyLayer(layerObj *dst, layerObj *src);
+  MS_DLL_EXPORT int msCopyPoint(pointObj *dst, pointObj *src);
+  MS_DLL_EXPORT int msCopyFontSet(fontSetObj *dst, fontSetObj *src, mapObj *map);
+  MS_DLL_EXPORT void copyProperty(void *dst, void *src, int size);
+  MS_DLL_EXPORT char *copyStringProperty(char **dst, char *src);
+  MS_DLL_EXPORT int msCopyClass(classObj *dst, classObj *src, layerObj *layer);
+  MS_DLL_EXPORT int msCopyStyle(styleObj *dst, styleObj *src);
+  MS_DLL_EXPORT int msCopyLabel(labelObj *dst, labelObj *src);
+  MS_DLL_EXPORT int msCopyLine(lineObj *dst, lineObj *src);
+  MS_DLL_EXPORT int msCopyProjection(projectionObj *dst, projectionObj *src);
+  int msCopyExpression(expressionObj *dst, expressionObj *src);
+  int msCopyProjection(projectionObj *dst, projectionObj *src);
+
+  /* ==================================================================== */
+  /*      end prototypes for functions in mapcopy                         */
+  /* ==================================================================== */
+
+  /* ==================================================================== */
+  /*      mappool.c: connection pooling API.                              */
+  /* ==================================================================== */
+  MS_DLL_EXPORT void *msConnPoolRequest( layerObj *layer );
+  MS_DLL_EXPORT void msConnPoolRelease( layerObj *layer, void * );
+  MS_DLL_EXPORT void msConnPoolRegister( layerObj *layer,
+                                         void *conn_handle,
+                                         void (*close)( void * ) );
+  MS_DLL_EXPORT void msConnPoolCloseUnreferenced( void );
+  MS_DLL_EXPORT void msConnPoolFinalCleanup( void );
+
+  /* ==================================================================== */
+  /*      prototypes for functions in mapcpl.c                            */
+  /* ==================================================================== */
+  MS_DLL_EXPORT const char *msGetBasename( const char *pszFullFilename );
+  MS_DLL_EXPORT void *msGetSymbol(const char *pszLibrary,
+                                  const char *pszEntryPoint);
+
+  /* ==================================================================== */
+  /*      include definitions from mapows.h                               */
+  /* ==================================================================== */
 #include "mapows.h"
 
-/* ==================================================================== */
-/*      prototypes for functions in mapgeos.c                         */
-/* ==================================================================== */
-MS_DLL_EXPORT void msGEOSSetup(void);
-MS_DLL_EXPORT void msGEOSCleanup(void);
-MS_DLL_EXPORT void msGEOSFreeGeometry(shapeObj *shape);
-
-MS_DLL_EXPORT shapeObj *msGEOSShapeFromWKT(const char *string);
-MS_DLL_EXPORT char *msGEOSShapeToWKT(shapeObj *shape);
-MS_DLL_EXPORT void msGEOSFreeWKT(char* pszGEOSWKT);
-
-MS_DLL_EXPORT shapeObj *msGEOSBuffer(shapeObj *shape, double width);
-MS_DLL_EXPORT shapeObj *msGEOSSimplify(shapeObj *shape, double tolerance);
-MS_DLL_EXPORT shapeObj *msGEOSTopologyPreservingSimplify(shapeObj *shape, double tolerance);
-MS_DLL_EXPORT shapeObj *msGEOSConvexHull(shapeObj *shape);
-MS_DLL_EXPORT shapeObj *msGEOSBoundary(shapeObj *shape);
-MS_DLL_EXPORT pointObj *msGEOSGetCentroid(shapeObj *shape);
-MS_DLL_EXPORT shapeObj *msGEOSUnion(shapeObj *shape1, shapeObj *shape2);
-MS_DLL_EXPORT shapeObj *msGEOSIntersection(shapeObj *shape1, shapeObj *shape2);
-MS_DLL_EXPORT shapeObj *msGEOSDifference(shapeObj *shape1, shapeObj *shape2);
-MS_DLL_EXPORT shapeObj *msGEOSSymDifference(shapeObj *shape1, shapeObj *shape2);
-
-MS_DLL_EXPORT int msGEOSContains(shapeObj *shape1, shapeObj *shape2);
-MS_DLL_EXPORT int msGEOSOverlaps(shapeObj *shape1, shapeObj *shape2);
-MS_DLL_EXPORT int msGEOSWithin(shapeObj *shape1, shapeObj *shape2);
-MS_DLL_EXPORT int msGEOSCrosses(shapeObj *shape1, shapeObj *shape2);
-MS_DLL_EXPORT int msGEOSIntersects(shapeObj *shape1, shapeObj *shape2);
-MS_DLL_EXPORT int msGEOSTouches(shapeObj *shape1, shapeObj *shape2);
-MS_DLL_EXPORT int msGEOSEquals(shapeObj *shape1, shapeObj *shape2);
-MS_DLL_EXPORT int msGEOSDisjoint(shapeObj *shape1, shapeObj *shape2);
-
-MS_DLL_EXPORT double msGEOSArea(shapeObj *shape);
-MS_DLL_EXPORT double msGEOSLength(shapeObj *shape);
-MS_DLL_EXPORT double msGEOSDistance(shapeObj *shape1, shapeObj *shape2);
-
-/* ==================================================================== */
-/*      prototypes for functions in mapcrypto.c                         */
-/* ==================================================================== */
-MS_DLL_EXPORT int msGenerateEncryptionKey(unsigned char *k);
-MS_DLL_EXPORT int msReadEncryptionKeyFromFile(const char *keyfile, unsigned char *k);
-MS_DLL_EXPORT void msEncryptStringWithKey(const unsigned char *key, const char *in, char *out);
-MS_DLL_EXPORT void msDecryptStringWithKey(const unsigned char *key, const char *in, char *out);
-MS_DLL_EXPORT char *msDecryptStringTokens(mapObj *map, const char *in);
-MS_DLL_EXPORT void msHexEncode(const unsigned char *in, char *out, int numbytes);
-MS_DLL_EXPORT int msHexDecode(const char *in, unsigned char *out, int numchars);
-
-
-
-/* ==================================================================== */
-/*      prototypes for functions in mapgeomtransform.c                  */
-/* ==================================================================== */
-enum MS_GEOMTRANSFORM_TYPE {
-  MS_GEOMTRANSFORM_NONE,
-  MS_GEOMTRANSFORM_EXPRESSION,
-  MS_GEOMTRANSFORM_START,
-  MS_GEOMTRANSFORM_END,
-  MS_GEOMTRANSFORM_VERTICES,
-  MS_GEOMTRANSFORM_BBOX,
-  MS_GEOMTRANSFORM_CENTROID,
-  MS_GEOMTRANSFORM_BUFFER,
-  MS_GEOMTRANSFORM_CONVEXHULL,
-  MS_GEOMTRANSFORM_LABELPOINT,
-  MS_GEOMTRANSFORM_LABELPOLY
-};
-
-MS_DLL_EXPORT int msDrawTransformedShape(mapObj *map, symbolSetObj *symbolset, imageObj *image, shapeObj *shape, styleObj *style, double scalefactor);
-MS_DLL_EXPORT void msStyleSetGeomTransform(styleObj *style, char *transform);
-MS_DLL_EXPORT char *msStyleGetGeomTransform(styleObj *style);
-/* ==================================================================== */
-/*      end of prototypes for functions in mapgeomtransform.c                 */
-/* ==================================================================== */
-
-
-/* ==================================================================== */
-/*      prototypes for functions in mapgraticule.c                      */
-/* ==================================================================== */
-MS_DLL_EXPORT graticuleIntersectionObj *msGraticuleLayerGetIntersectionPoints(mapObj *map, layerObj *layer);
-MS_DLL_EXPORT void msGraticuleLayerFreeIntersectionPoints( graticuleIntersectionObj *psValue);
-
-/* ==================================================================== */
-/*      end of prototypes for functions in mapgraticule.c               */
-/* ==================================================================== */
+  /* ==================================================================== */
+  /*      prototypes for functions in mapgeos.c                         */
+  /* ==================================================================== */
+  MS_DLL_EXPORT void msGEOSSetup(void);
+  MS_DLL_EXPORT void msGEOSCleanup(void);
+  MS_DLL_EXPORT void msGEOSFreeGeometry(shapeObj *shape);
+
+  MS_DLL_EXPORT shapeObj *msGEOSShapeFromWKT(const char *string);
+  MS_DLL_EXPORT char *msGEOSShapeToWKT(shapeObj *shape);
+  MS_DLL_EXPORT void msGEOSFreeWKT(char* pszGEOSWKT);
+
+  MS_DLL_EXPORT shapeObj *msGEOSBuffer(shapeObj *shape, double width);
+  MS_DLL_EXPORT shapeObj *msGEOSSimplify(shapeObj *shape, double tolerance);
+  MS_DLL_EXPORT shapeObj *msGEOSTopologyPreservingSimplify(shapeObj *shape, double tolerance);
+  MS_DLL_EXPORT shapeObj *msGEOSConvexHull(shapeObj *shape);
+  MS_DLL_EXPORT shapeObj *msGEOSBoundary(shapeObj *shape);
+  MS_DLL_EXPORT pointObj *msGEOSGetCentroid(shapeObj *shape);
+  MS_DLL_EXPORT shapeObj *msGEOSUnion(shapeObj *shape1, shapeObj *shape2);
+  MS_DLL_EXPORT shapeObj *msGEOSIntersection(shapeObj *shape1, shapeObj *shape2);
+  MS_DLL_EXPORT shapeObj *msGEOSDifference(shapeObj *shape1, shapeObj *shape2);
+  MS_DLL_EXPORT shapeObj *msGEOSSymDifference(shapeObj *shape1, shapeObj *shape2);
+
+  MS_DLL_EXPORT int msGEOSContains(shapeObj *shape1, shapeObj *shape2);
+  MS_DLL_EXPORT int msGEOSOverlaps(shapeObj *shape1, shapeObj *shape2);
+  MS_DLL_EXPORT int msGEOSWithin(shapeObj *shape1, shapeObj *shape2);
+  MS_DLL_EXPORT int msGEOSCrosses(shapeObj *shape1, shapeObj *shape2);
+  MS_DLL_EXPORT int msGEOSIntersects(shapeObj *shape1, shapeObj *shape2);
+  MS_DLL_EXPORT int msGEOSTouches(shapeObj *shape1, shapeObj *shape2);
+  MS_DLL_EXPORT int msGEOSEquals(shapeObj *shape1, shapeObj *shape2);
+  MS_DLL_EXPORT int msGEOSDisjoint(shapeObj *shape1, shapeObj *shape2);
+
+  MS_DLL_EXPORT double msGEOSArea(shapeObj *shape);
+  MS_DLL_EXPORT double msGEOSLength(shapeObj *shape);
+  MS_DLL_EXPORT double msGEOSDistance(shapeObj *shape1, shapeObj *shape2);
+
+  /* ==================================================================== */
+  /*      prototypes for functions in mapcrypto.c                         */
+  /* ==================================================================== */
+  MS_DLL_EXPORT int msGenerateEncryptionKey(unsigned char *k);
+  MS_DLL_EXPORT int msReadEncryptionKeyFromFile(const char *keyfile, unsigned char *k);
+  MS_DLL_EXPORT void msEncryptStringWithKey(const unsigned char *key, const char *in, char *out);
+  MS_DLL_EXPORT void msDecryptStringWithKey(const unsigned char *key, const char *in, char *out);
+  MS_DLL_EXPORT char *msDecryptStringTokens(mapObj *map, const char *in);
+  MS_DLL_EXPORT void msHexEncode(const unsigned char *in, char *out, int numbytes);
+  MS_DLL_EXPORT int msHexDecode(const char *in, unsigned char *out, int numchars);
+
+  /* ==================================================================== */
+  /*      prototypes for functions in mapxmp.c                            */
+  /* ==================================================================== */
+  MS_DLL_EXPORT int msXmpPresent(mapObj *map);
+  MS_DLL_EXPORT int msXmpWrite(mapObj *map, const char *filename);
+
+  /* ==================================================================== */
+  /*      prototypes for functions in mapgeomtransform.c                  */
+  /* ==================================================================== */
+  enum MS_GEOMTRANSFORM_TYPE {
+    MS_GEOMTRANSFORM_NONE,
+    MS_GEOMTRANSFORM_EXPRESSION,
+    MS_GEOMTRANSFORM_START,
+    MS_GEOMTRANSFORM_END,
+    MS_GEOMTRANSFORM_VERTICES,
+    MS_GEOMTRANSFORM_BBOX,
+    MS_GEOMTRANSFORM_CENTROID,
+    MS_GEOMTRANSFORM_BUFFER,
+    MS_GEOMTRANSFORM_CONVEXHULL,
+    MS_GEOMTRANSFORM_LABELPOINT,
+    MS_GEOMTRANSFORM_LABELPOLY
+  };
+
+  MS_DLL_EXPORT int msDrawTransformedShape(mapObj *map, symbolSetObj *symbolset, imageObj *image, shapeObj *shape, styleObj *style, double scalefactor);
+  MS_DLL_EXPORT void msStyleSetGeomTransform(styleObj *style, char *transform);
+  MS_DLL_EXPORT char *msStyleGetGeomTransform(styleObj *style);
+  /* ==================================================================== */
+  /*      end of prototypes for functions in mapgeomtransform.c                 */
+  /* ==================================================================== */
+
+
+  /* ==================================================================== */
+  /*      prototypes for functions in mapgraticule.c                      */
+  /* ==================================================================== */
+  MS_DLL_EXPORT graticuleIntersectionObj *msGraticuleLayerGetIntersectionPoints(mapObj *map, layerObj *layer);
+  MS_DLL_EXPORT void msGraticuleLayerFreeIntersectionPoints( graticuleIntersectionObj *psValue);
+
+  /* ==================================================================== */
+  /*      end of prototypes for functions in mapgraticule.c               */
+  /* ==================================================================== */
 
 #endif
 
 
 
-/*
- * strokeStyleObj
- */
-typedef struct {
+  /*
+   * strokeStyleObj
+   */
+  typedef struct {
     double width; /* line width in pixels */
-    
+
     /* line pattern, e.g. dots, dashes, etc.. */
     int patternlength;
     double pattern[MS_MAXPATTERNLENGTH];
-    
+    double patternoffset;
+
     /* must be a valid color if not NULL */
     /* color.alpha must be used if supported by the renderer */
     colorObj *color;
@@ -2553,20 +2657,20 @@ typedef struct {
     int linecap; /* MS_CJC_TRIANGLE, MS_CJC_SQUARE, MS_CJC_ROUND, MS_CJC_BUTT */
     int linejoin; /* MS_CJC_BEVEL MS_CJC_ROUND MS_CJC_MITER */
     double linejoinmaxsize;
-} strokeStyleObj;
+  } strokeStyleObj;
 
 #define INIT_STROKE_STYLE(s) { (s).width=0; (s).patternlength=0; (s).color=NULL; (s).linecap=MS_CJC_ROUND; (s).linejoin=MS_CJC_ROUND; (s).linejoinmaxsize=0;}
 
 
-/*
- * symbolStyleObj
- */
-typedef struct {
+  /*
+   * symbolStyleObj
+   */
+  typedef struct {
     /* must be valid colors if not NULL */
     /* color.alpha must be used if supported by the renderer */
     colorObj *color;
     colorObj *backgroundcolor;
-    
+
     double outlinewidth;
     colorObj *outlinecolor;
 
@@ -2576,7 +2680,7 @@ typedef struct {
     /* rotation to apply on the symbol (and the tile?)
      * in radians */
     double rotation;
-   
+
     /* the gap to space symbols appart when used as a polygon tile
      */
     double gap;
@@ -2584,11 +2688,11 @@ typedef struct {
     /* style object, necessary for vector type renderers to be able
      * to render symbols through other renders such as cairo/agg */
     styleObj *style;
-} symbolStyleObj;
+  } symbolStyleObj;
 
 #define INIT_SYMBOL_STYLE(s) {(s).color=NULL; (s).backgroundcolor=NULL; (s).outlinewidth=0; (s).outlinecolor=NULL; (s).scale=1.0; (s).rotation=0; (s).style=NULL;}
 
-struct tileCacheObj {
+  struct tileCacheObj {
     symbolObj *symbol;
     int width;
     int height;
@@ -2596,152 +2700,169 @@ struct tileCacheObj {
     double outlinewidth, rotation,scale;
     imageObj *image;
     tileCacheObj *next;
-};
+  };
 
 
-/*
- * labelStyleObj
- */
-typedef struct {
-    /* full path to truetype font file */
-    char *font;
+  /*
+   * labelStyleObj
+   */
+  typedef struct {
+    /* full paths to truetype font file */
+    char* fonts[MS_MAX_LABEL_FONTS];
+    int numfonts;
     double size;
     double rotation;
     colorObj *color;
     double outlinewidth;
     colorObj *outlinecolor;
-} labelStyleObj;
+    int antialias; /*only for GD*/
+  } labelStyleObj;
 
-#define INIT_LABEL_STYLE(s) {(s).font=NULL; (s).size=0; (s).rotation=0; (s).color=NULL; (s).outlinewidth=0; (s).outlinecolor=NULL;}
+#define INIT_LABEL_STYLE(s) {memset(&(s),'\0',sizeof(labelStyleObj));}
 
 #ifndef SWIG
-MS_DLL_EXPORT int msInitializeDummyRenderer(rendererVTableObj *vtable);
-MS_DLL_EXPORT int msInitializeRendererVTable(outputFormatObj *outputformat);
-MS_DLL_EXPORT int msPopulateRendererVTableCairoRaster( rendererVTableObj *renderer );
-MS_DLL_EXPORT int msPopulateRendererVTableCairoSVG( rendererVTableObj *renderer );
-MS_DLL_EXPORT int msPopulateRendererVTableCairoPDF( rendererVTableObj *renderer );
-MS_DLL_EXPORT int msPopulateRendererVTableOGL( rendererVTableObj *renderer );
-MS_DLL_EXPORT int msPopulateRendererVTableAGG( rendererVTableObj *renderer );
-MS_DLL_EXPORT int msPopulateRendererVTableGD( rendererVTableObj *renderer );
-MS_DLL_EXPORT int msPopulateRendererVTableKML( rendererVTableObj *renderer );
-MS_DLL_EXPORT int msPopulateRendererVTableOGR( rendererVTableObj *renderer );
-
-//allocate 50k for starters
+  MS_DLL_EXPORT int msInitializeDummyRenderer(rendererVTableObj *vtable);
+  MS_DLL_EXPORT int msInitializeRendererVTable(outputFormatObj *outputformat);
+  MS_DLL_EXPORT int msPopulateRendererVTableCairoRaster( rendererVTableObj *renderer );
+  MS_DLL_EXPORT int msPopulateRendererVTableCairoSVG( rendererVTableObj *renderer );
+  MS_DLL_EXPORT int msPopulateRendererVTableCairoPDF( rendererVTableObj *renderer );
+  MS_DLL_EXPORT int msPopulateRendererVTableOGL( rendererVTableObj *renderer );
+  MS_DLL_EXPORT int msPopulateRendererVTableAGG( rendererVTableObj *renderer );
+  MS_DLL_EXPORT int msPopulateRendererVTableGD( rendererVTableObj *renderer );
+  MS_DLL_EXPORT int msPopulateRendererVTableKML( rendererVTableObj *renderer );
+  MS_DLL_EXPORT int msPopulateRendererVTableOGR( rendererVTableObj *renderer );
+#ifdef USE_CAIRO
+  MS_DLL_EXPORT void msCairoCleanup(void);
+#endif
+
+  /* allocate 50k for starters */
 #define MS_DEFAULT_BUFFER_ALLOC 50000
 
-typedef struct _autobuffer {
+  typedef struct _autobuffer {
     unsigned char *data;
     size_t size;
     size_t available;
     size_t _next_allocation_size;
-} bufferObj;
-
-
-/* in mapimageio.c */
-int msQuantizeRasterBuffer(rasterBufferObj *rb, unsigned int *reqcolors, rgbaPixel *palette,
-      rgbaPixel *forced_palette, int num_forced_palette_entries,
-      unsigned int *palette_scaling_maxval);
-int msClassifyRasterBuffer(rasterBufferObj *rb, rasterBufferObj *qrb);
-int msSaveRasterBuffer(mapObj *map, rasterBufferObj *data, FILE *stream, outputFormatObj *format);
-int msSaveRasterBufferToBuffer(rasterBufferObj *data, bufferObj *buffer, outputFormatObj *format);
-int msLoadMSRasterBufferFromFile(char *path, rasterBufferObj *rb);
-int msLoadGDRasterBufferFromFile(char *path, rasterBufferObj *rb);
-int saveGdImage(gdImagePtr ip, FILE *fp, outputFormatObj *format);
-int saveGdImageBuffer(gdImagePtr ip, bufferObj *buffer, outputFormatObj *format);
-
-void msBufferInit(bufferObj *buffer);
-void msBufferResize(bufferObj *buffer, size_t target_size);
-MS_DLL_EXPORT void msBufferFree(bufferObj *buffer);
-MS_DLL_EXPORT void msBufferAppend(bufferObj *buffer, void *data, size_t length);
-
-typedef struct {
+  } bufferObj;
+
+
+  /* in mapimageio.c */
+  int msQuantizeRasterBuffer(rasterBufferObj *rb, unsigned int *reqcolors, rgbaPixel *palette,
+                             rgbaPixel *forced_palette, int num_forced_palette_entries,
+                             unsigned int *palette_scaling_maxval);
+  int msClassifyRasterBuffer(rasterBufferObj *rb, rasterBufferObj *qrb);
+  int msSaveRasterBuffer(mapObj *map, rasterBufferObj *data, FILE *stream, outputFormatObj *format);
+  int msSaveRasterBufferToBuffer(rasterBufferObj *data, bufferObj *buffer, outputFormatObj *format);
+  int msLoadMSRasterBufferFromFile(char *path, rasterBufferObj *rb);
+#ifdef USE_GD
+  int msLoadGDRasterBufferFromFile(char *path, rasterBufferObj *rb);
+  int saveGdImage(gdImagePtr ip, FILE *fp, outputFormatObj *format);
+  int saveGdImageBuffer(gdImagePtr ip, bufferObj *buffer, outputFormatObj *format);
+#endif
+
+  void msBufferInit(bufferObj *buffer);
+  void msBufferResize(bufferObj *buffer, size_t target_size);
+  MS_DLL_EXPORT void msBufferFree(bufferObj *buffer);
+  MS_DLL_EXPORT void msBufferAppend(bufferObj *buffer, void *data, size_t length);
+
+  typedef struct {
     int charWidth, charHeight;
-} fontMetrics;
+  } fontMetrics;
+
+  struct rendererVTableObj {
+    int supports_transparent_layers;
+    int supports_pixel_buffer;
+    int supports_clipping;
+    int supports_bitmap_fonts;
+    int supports_svg;
+    int use_imagecache;
+    enum MS_TRANSFORM_MODE default_transform_mode;
+    enum MS_TRANSFORM_MODE transform_mode;
+    double default_approximation_scale;
+    double approximation_scale;
+
+    void *renderer_data;
+
+    fontMetrics* bitmapFontMetrics[5];
+
+    int (*renderLine)(imageObj *img, shapeObj *p, strokeStyleObj *style);
+    int (*renderPolygon)(imageObj *img, shapeObj *p, colorObj *color);
+    int (*renderPolygonTiled)(imageObj *img, shapeObj *p, imageObj *tile);
+    int (*renderLineTiled)(imageObj *img, shapeObj *p, imageObj *tile);
 
-struct rendererVTableObj {
-	int supports_transparent_layers;
-	int supports_pixel_buffer;
-	int supports_clipping;
-	int supports_bitmap_fonts;
-	int use_imagecache;
-	enum MS_TRANSFORM_MODE default_transform_mode;
-	enum MS_TRANSFORM_MODE transform_mode;
-	double default_approximation_scale;
-	double approximation_scale;
-	
-	void *renderer_data;
+    int (*renderBitmapGlyphs)(imageObj *img, double x, double y,
+                              labelStyleObj *style, char *text);
 
-	fontMetrics* bitmapFontMetrics[5];
+    int (*renderGlyphs)(imageObj *img, double x, double y,
+                        labelStyleObj *style, char *text);
 
-	int (*renderLine)(imageObj *img, shapeObj *p, strokeStyleObj *style);
-	int (*renderPolygon)(imageObj *img, shapeObj *p, colorObj *color);
-	int (*renderPolygonTiled)(imageObj *img, shapeObj *p, imageObj *tile);
-	int (*renderPolygonHatched)(imageObj *img, shapeObj *poly, double spacing, double width, double angle, colorObj *color);
-	int (*renderLineTiled)(imageObj *img, shapeObj *p, imageObj *tile);
+    int (*renderGlyphsLine)(imageObj *img, labelPathObj *labelpath,
+                            labelStyleObj *style, char *text);
 
-	int (*renderBitmapGlyphs)(imageObj *img, double x, double y,
-			labelStyleObj *style, char *text);
+    int (*renderVectorSymbol)(imageObj *img, double x, double y,
+                              symbolObj *symbol, symbolStyleObj *style);
 
-	int (*renderGlyphs)(imageObj *img, double x, double y,
-			labelStyleObj *style, char *text);
+    void* (*createVectorSymbolTile)(int width, int height,
+                                    symbolObj *symbol, symbolStyleObj *style);
 
-	int (*renderVectorSymbol)(imageObj *img, double x, double y,
-			symbolObj *symbol, symbolStyleObj *style);
+    int (*renderPixmapSymbol)(imageObj *img, double x, double y,
+                              symbolObj *symbol, symbolStyleObj *style);
 
-	void* (*createVectorSymbolTile)(int width, int height,
-			symbolObj *symbol, symbolStyleObj *style);
+    void* (*createPixmapSymbolTile)(int width, int height,
+                                    symbolObj *symbol, symbolStyleObj *style);
 
-	int (*renderPixmapSymbol)(imageObj *img, double x, double y,
-			symbolObj *symbol, symbolStyleObj *style);
+    int (*renderEllipseSymbol)(imageObj *image, double x, double y,
+                               symbolObj *symbol, symbolStyleObj *style);
 
-	void* (*createPixmapSymbolTile)(int width, int height,
-			symbolObj *symbol, symbolStyleObj *style);
+    void* (*createEllipseSymbolTile)(int width, int height,
+                                     symbolObj *symbol, symbolStyleObj *style);
 
-	int (*renderEllipseSymbol)(imageObj *image, double x, double y, 
-			symbolObj *symbol, symbolStyleObj *style);
+    int (*renderTruetypeSymbol)(imageObj *img, double x, double y,
+                                symbolObj *symbol, symbolStyleObj *style);
 
-	void* (*createEllipseSymbolTile)(int width, int height,
-			symbolObj *symbol, symbolStyleObj *style);
+    void* (*createTruetypeSymbolTile)(int width, int height,
+                                      symbolObj *symbol, symbolStyleObj *style);
 
-	int (*renderTruetypeSymbol)(imageObj *img, double x, double y,
-			symbolObj *symbol, symbolStyleObj *style);
+    int (*renderSVGSymbol)(imageObj *img, double x, double y,
+                           symbolObj *symbol, symbolStyleObj *style);
 
-	void* (*createTruetypeSymbolTile)(int width, int height,
-			symbolObj *symbol, symbolStyleObj *style);
+    void* (*createSVGSymbolTile)(int width, int height,
+                                 symbolObj *symbol, symbolStyleObj *style);
 
-	int (*renderTile)(imageObj *img, imageObj *tile, double x, double y);
+    int (*renderTile)(imageObj *img, imageObj *tile, double x, double y);
 
-	int (*loadImageFromFile)(char *path, rasterBufferObj *rb);
+    int (*loadImageFromFile)(char *path, rasterBufferObj *rb);
 
 
-	int (*getRasterBufferHandle)(imageObj *img, rasterBufferObj *rb);
-	int (*getRasterBufferCopy)(imageObj *img, rasterBufferObj *rb);
-	int (*initializeRasterBuffer)(rasterBufferObj *rb, int width, int height, int mode);
+    int (*getRasterBufferHandle)(imageObj *img, rasterBufferObj *rb);
+    int (*getRasterBufferCopy)(imageObj *img, rasterBufferObj *rb);
+    int (*initializeRasterBuffer)(rasterBufferObj *rb, int width, int height, int mode);
 
-	int (*mergeRasterBuffer)(imageObj *dest, rasterBufferObj *overlay, double opacity, int srcX, int srcY, int dstX, int dstY, int width, int height);
+    int (*mergeRasterBuffer)(imageObj *dest, rasterBufferObj *overlay, double opacity, int srcX, int srcY, int dstX, int dstY, int width, int height);
 
 
-	/* image i/o */
-	imageObj* (*createImage)(int width, int height, outputFormatObj *format, colorObj* bg);
-	int (*saveImage)(imageObj *img, FILE *fp, outputFormatObj *format);
-	unsigned char* (*saveImageBuffer)(imageObj *img, int *size_ptr, outputFormatObj *format);
-	/*...*/
+    /* image i/o */
+    imageObj* (*createImage)(int width, int height, outputFormatObj *format, colorObj* bg);
+    int (*saveImage)(imageObj *img, mapObj *map, FILE *fp, outputFormatObj *format);
+    unsigned char* (*saveImageBuffer)(imageObj *img, int *size_ptr, outputFormatObj *format);
+    /*...*/
 
-	/* helper functions */
-	int (*getTruetypeTextBBox)(rendererVTableObj *renderer, char *font, double size, char *string, rectObj *rect, double **advances);
+    /* helper functions */
+    int (*getTruetypeTextBBox)(rendererVTableObj *renderer, char **fonts, int numfonts, double size, char *string, rectObj *rect, double **advances, int bAdjustBaseline);
 
-	int (*startLayer)(imageObj *img, mapObj *map, layerObj *layer);
-	int (*endLayer)(imageObj *img, mapObj *map, layerObj *layer);
+    int (*startLayer)(imageObj *img, mapObj *map, layerObj *layer);
+    int (*endLayer)(imageObj *img, mapObj *map, layerObj *layer);
 
-	int (*startShape)(imageObj *img, shapeObj *shape);
-	int (*endShape)(imageObj *img, shapeObj *shape);
-	int (*setClip)(imageObj *img, rectObj clipRect);
-	int (*resetClip)(imageObj *img);
+    int (*startShape)(imageObj *img, shapeObj *shape);
+    int (*endShape)(imageObj *img, shapeObj *shape);
+    int (*setClip)(imageObj *img, rectObj clipRect);
+    int (*resetClip)(imageObj *img);
 
-	int (*freeImage)(imageObj *image);
-	int (*freeSymbol)(symbolObj *symbol);
-	int (*cleanup)(void *renderer_data);
-} ;
+    int (*freeImage)(imageObj *image);
+    int (*freeSymbol)(symbolObj *symbol);
+    int (*cleanup)(void *renderer_data);
+  } ;
+  MS_DLL_EXPORT int msRenderRasterizedSVGSymbol(imageObj* img, double x, double y, symbolObj* symbol, symbolStyleObj* style);
 
 #endif /* SWIG */
 
diff --git a/mapservutil.c b/mapservutil.c
new file mode 100644
index 0000000..2278622
--- /dev/null
+++ b/mapservutil.c
@@ -0,0 +1,1808 @@
+/******************************************************************************
+ * $id$
+ *
+ * Project:  MapServer
+ * Purpose:  MapServer CGI utility functions.
+ * Author:   Steve Lime and the MapServer team.
+ *
+ ******************************************************************************
+ * Copyright (c) 1996-2005 Regents of the University of Minnesota.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies of this Software or works derived from this Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ ****************************************************************************/
+
+
+#include "mapserver.h"
+#include "mapserv.h"
+#include "maptime.h"
+
+/*
+** Enumerated types, keep the query modes in sequence and at the end of the enumeration (mode enumeration is in maptemplate.h).
+*/
+static int numModes = 21;
+static char *modeStrings[21] = {"BROWSE","ZOOMIN","ZOOMOUT","MAP","LEGEND","LEGENDICON","REFERENCE","SCALEBAR","COORDINATE",
+                                "QUERY","NQUERY","ITEMQUERY","ITEMNQUERY",
+                                "FEATUREQUERY","FEATURENQUERY","ITEMFEATUREQUERY","ITEMFEATURENQUERY",
+                                "INDEXQUERY","TILE","OWS", "WFS"
+                               };
+
+
+
+int msCGIWriteLog(mapservObj *mapserv, int show_error)
+{
+  FILE *stream;
+  int i;
+  time_t t;
+  char szPath[MS_MAXPATHLEN];
+
+  if(!mapserv) return(MS_SUCCESS);
+  if(!mapserv->map) return(MS_SUCCESS);
+  if(!mapserv->map->web.log) return(MS_SUCCESS);
+
+  if((stream = fopen(msBuildPath(szPath, mapserv->map->mappath,
+                                 mapserv->map->web.log),"a")) == NULL) {
+    msSetError(MS_IOERR, mapserv->map->web.log, "msCGIWriteLog()");
+    return(MS_FAILURE);
+  }
+
+  t = time(NULL);
+  fprintf(stream,"%s,",msStringChop(ctime(&t)));
+  fprintf(stream,"%d,",(int)getpid());
+
+  if(getenv("REMOTE_ADDR") != NULL)
+    fprintf(stream,"%s,",getenv("REMOTE_ADDR"));
+  else
+    fprintf(stream,"NULL,");
+
+  fprintf(stream,"%s,",mapserv->map->name);
+  fprintf(stream,"%d,",mapserv->Mode);
+
+  fprintf(stream,"%f %f %f %f,", mapserv->map->extent.minx, mapserv->map->extent.miny, mapserv->map->extent.maxx, mapserv->map->extent.maxy);
+
+  fprintf(stream,"%f %f,", mapserv->mappnt.x, mapserv->mappnt.y);
+
+  for(i=0; i<mapserv->NumLayers; i++)
+    fprintf(stream, "%s ", mapserv->Layers[i]);
+  fprintf(stream,",");
+
+  if(show_error == MS_TRUE)
+    msWriteError(stream);
+  else
+    fprintf(stream, "normal execution");
+
+  fprintf(stream,"\n");
+
+  fclose(stream);
+  return(MS_SUCCESS);
+}
+
+void msCGIWriteError(mapservObj *mapserv)
+{
+  errorObj *ms_error = msGetErrorObj();
+
+  if(!ms_error || ms_error->code == MS_NOERR || ms_error->isreported) {
+    /* either we have no error, or it was already reported by other means */
+    return;
+  }
+
+  msCGIWriteLog(mapserv,MS_TRUE);
+
+  if(!mapserv || !mapserv->map) {
+    msIO_setHeader("Content-Type","text/html");
+    msIO_sendHeaders();
+    msIO_printf("<HTML>\n");
+    msIO_printf("<HEAD><TITLE>MapServer Message</TITLE></HEAD>\n");
+    msIO_printf("<!-- %s -->\n", msGetVersion());
+    msIO_printf("<BODY BGCOLOR=\"#FFFFFF\">\n");
+    msWriteErrorXML(stdout);
+    msIO_printf("</BODY></HTML>");
+    return;
+  }
+
+  if((ms_error->code == MS_NOTFOUND) && (mapserv->map->web.empty)) {
+    /* msRedirect(mapserv->map->web.empty); */
+    if(msReturnURL(mapserv, mapserv->map->web.empty, BROWSE) != MS_SUCCESS) {
+      msIO_setHeader("Content-Type","text/html");
+      msIO_sendHeaders();
+      msIO_printf("<HTML>\n");
+      msIO_printf("<HEAD><TITLE>MapServer Message</TITLE></HEAD>\n");
+      msIO_printf("<!-- %s -->\n", msGetVersion());
+      msIO_printf("<BODY BGCOLOR=\"#FFFFFF\">\n");
+      msWriteErrorXML(stdout);
+      msIO_printf("</BODY></HTML>");
+    }
+  } else {
+    if(mapserv->map->web.error) {
+      /* msRedirect(mapserv->map->web.error); */
+      if(msReturnURL(mapserv, mapserv->map->web.error, BROWSE) != MS_SUCCESS) {
+        msIO_setHeader("Content-Type","text/html");
+        msIO_sendHeaders();
+        msIO_printf("<HTML>\n");
+        msIO_printf("<HEAD><TITLE>MapServer Message</TITLE></HEAD>\n");
+        msIO_printf("<!-- %s -->\n", msGetVersion());
+        msIO_printf("<BODY BGCOLOR=\"#FFFFFF\">\n");
+        msWriteErrorXML(stdout);
+        msIO_printf("</BODY></HTML>");
+      }
+    } else {
+      msIO_setHeader("Content-Type","text/html");
+      msIO_sendHeaders();
+      msIO_printf("<HTML>\n");
+      msIO_printf("<HEAD><TITLE>MapServer Message</TITLE></HEAD>\n");
+      msIO_printf("<!-- %s -->\n", msGetVersion());
+      msIO_printf("<BODY BGCOLOR=\"#FFFFFF\">\n");
+      msWriteErrorXML(stdout);
+      msIO_printf("</BODY></HTML>");
+    }
+  }
+}
+
+/*
+** Converts a string (e.g. form parameter) to a double, first checking the format against
+** a regular expression. returns an error if the format test fails.
+*/
+
+#define GET_NUMERIC(string,dbl) do { \
+  dbl = strtod((string), &strtoderr);\
+  if (*strtoderr) {\
+    msSetError(MS_TYPEERR, NULL, "GET_NUMERIC()");\
+    return MS_FAILURE;\
+  }\
+} while (0)
+
+static void setClassGroup(layerObj *layer, char *classgroup)
+{
+  int i;
+
+  if(!layer || !classgroup) return;
+
+  for(i=0; i<layer->numclasses; i++) {
+    if(layer->class[i]->group && strcmp(layer->class[i]->group, classgroup) == 0) {
+      msFree(layer->classgroup);
+      layer->classgroup = msStrdup(classgroup);
+      return; /* bail */
+    }
+  }
+}
+
+/*
+** Extract Map File name from params and load it.
+** Returns map object or NULL on error.
+*/
+mapObj *msCGILoadMap(mapservObj *mapserv)
+{
+  int i, j;
+  mapObj *map = NULL;
+
+  for(i=0; i<mapserv->request->NumParams; i++) /* find the mapfile parameter first */
+    if(strcasecmp(mapserv->request->ParamNames[i], "map") == 0) break;
+
+  if(i == mapserv->request->NumParams) {
+    char *ms_mapfile = getenv("MS_MAPFILE");
+    if(ms_mapfile) {
+      map = msLoadMap(ms_mapfile,NULL);
+    } else {
+      msSetError(MS_WEBERR, "CGI variable \"map\" is not set.", "msCGILoadMap()"); /* no default, outta here */
+      return NULL;
+    }
+  } else {
+    if(getenv(mapserv->request->ParamValues[i])) /* an environment variable references the actual file to use */
+      map = msLoadMap(getenv(mapserv->request->ParamValues[i]), NULL);
+    else {
+      /* by here we know the request isn't for something in an environment variable */
+      if(getenv("MS_MAP_NO_PATH")) {
+        msSetError(MS_WEBERR, "Mapfile not found in environment variables and this server is not configured for full paths.", "msCGILoadMap()");
+        return NULL;
+      }
+
+      if(getenv("MS_MAP_PATTERN") && msEvalRegex(getenv("MS_MAP_PATTERN"), mapserv->request->ParamValues[i]) != MS_TRUE) {
+        msSetError(MS_WEBERR, "Parameter 'map' value fails to validate.", "msCGILoadMap()");
+        return NULL;
+      }
+
+      /* ok to try to load now */
+      map = msLoadMap(mapserv->request->ParamValues[i], NULL);
+    }
+  }
+  
+
+  if(!map) return NULL;
+
+  if(!msLookupHashTable(&(map->web.validation), "immutable")) {
+    /* check for any %variable% substitutions here, also do any map_ changes, we do this here so WMS/WFS  */
+    /* services can take advantage of these "vendor specific" extensions */
+    for(i=0; i<mapserv->request->NumParams; i++) {
+      /*
+       ** a few CGI variables should be skipped altogether
+       **
+       ** qstring: there is separate per layer validation for attribute queries and the substitution checks
+       **          below conflict with that so we avoid it here
+       */
+      if(strncasecmp(mapserv->request->ParamNames[i],"qstring",7) == 0) continue;
+
+      /* check to see if there are any additions to the mapfile */
+      if(strncasecmp(mapserv->request->ParamNames[i],"map_",4) == 0 || strncasecmp(mapserv->request->ParamNames[i],"map.",4) == 0) {
+        if(msUpdateMapFromURL(map, mapserv->request->ParamNames[i], mapserv->request->ParamValues[i]) != MS_SUCCESS) {
+          msFreeMap(map);
+          return NULL;
+        }
+        continue;
+      }
+
+      if(strncasecmp(mapserv->request->ParamNames[i],"classgroup",10) == 0) { /* #4207 */
+        for(j=0; j<map->numlayers; j++) {
+          setClassGroup(GET_LAYER(map, j), mapserv->request->ParamValues[i]);
+        }
+        continue;
+      }
+    }
+
+    msApplySubstitutions(map, mapserv->request->ParamNames, mapserv->request->ParamValues, mapserv->request->NumParams);
+    msApplyDefaultSubstitutions(map);
+
+    /* check to see if a ogc map context is passed as argument. if there */
+    /* is one load it */
+
+    for(i=0; i<mapserv->request->NumParams; i++) {
+      if(strcasecmp(mapserv->request->ParamNames[i],"context") == 0) {
+        if(mapserv->request->ParamValues[i] && strlen(mapserv->request->ParamValues[i]) > 0) {
+          if(strncasecmp(mapserv->request->ParamValues[i],"http",4) == 0) {
+            if(msGetConfigOption(map, "CGI_CONTEXT_URL"))
+              msLoadMapContextURL(map, mapserv->request->ParamValues[i], MS_FALSE);
+          } else
+            msLoadMapContext(map, mapserv->request->ParamValues[i], MS_FALSE);
+        }
+      }
+    }
+  }
+
+  /*
+   * RFC-42 HTTP Cookie Forwarding
+   * Here we set the http_cookie_data metadata to handle the
+   * HTTP Cookie Forwarding. The content of this metadata is the cookie
+   * content. In the future, this metadata will probably be replaced
+   * by an object that is part of the mapObject that would contain
+   * information on the application status (such as cookie).
+   */
+  if( mapserv->request->httpcookiedata != NULL ) {
+    msInsertHashTable( &(map->web.metadata), "http_cookie_data",
+                       mapserv->request->httpcookiedata );
+  }
+
+  return map;
+}
+
+
+/*
+** Set operation mode. First look in MS_MODE env. var. as a
+** default value that can be overridden by the mode=... CGI param.
+** Returns silently, leaving mapserv->Mode unchanged if mode param not set.
+*/
+int msCGISetMode(mapservObj *mapserv)
+{
+  const char *mode = NULL;
+  int i, j;
+
+
+  mode = getenv("MS_MODE");
+  for( i=0; i<mapserv->request->NumParams; i++ ) {
+    if(strcasecmp(mapserv->request->ParamNames[i], "mode") == 0) {
+      mode = mapserv->request->ParamValues[i];
+      break;
+    }
+  }
+
+  if (mode) {
+    for(j=0; j<numModes; j++) {
+      if(strcasecmp(mode, modeStrings[j]) == 0) {
+        mapserv->Mode = j;
+        break;
+      }
+    }
+
+    if(j == numModes) {
+      msSetError(MS_WEBERR, "Invalid mode.", "msCGISetMode()");
+      return MS_FAILURE;
+    }
+  }
+
+  return MS_SUCCESS;
+}
+
+
+
+
+/*
+** Process CGI parameters.
+*/
+int msCGILoadForm(mapservObj *mapserv)
+{
+  int i,n;
+  char **tokens=NULL;
+  int rosa_type=0;
+  double tmpval;
+  char *strtoderr;
+
+  for(i=0; i<mapserv->request->NumParams; i++) { /* now process the rest of the form variables */
+    if(strlen(mapserv->request->ParamValues[i]) == 0)
+      continue;
+
+
+    if(strcasecmp(mapserv->request->ParamNames[i],"icon") == 0) {
+      mapserv->icon = msStrdup(mapserv->request->ParamValues[i]);
+      continue;
+    }
+
+    if(strcasecmp(mapserv->request->ParamNames[i],"queryfile") == 0) {
+      mapserv->QueryFile = msStrdup(mapserv->request->ParamValues[i]);
+      continue;
+    }
+
+    if(strcasecmp(mapserv->request->ParamNames[i],"savequery") == 0) {
+      mapserv->savequery = MS_TRUE;
+      continue;
+    }
+
+    /* Insecure as implemented, need to save someplace non accessible by everyone in the universe
+        if(strcasecmp(mapserv->request->ParamNames[i],"savemap") == 0) {
+         mapserv->savemap = MS_TRUE;
+         continue;
+        }
+    */
+
+    if(strcasecmp(mapserv->request->ParamNames[i],"zoom") == 0) {
+      GET_NUMERIC(mapserv->request->ParamValues[i],mapserv->Zoom);
+      if((mapserv->Zoom > MAXZOOM) || (mapserv->Zoom < MINZOOM)) {
+        msSetError(MS_WEBERR, "Zoom value out of range.", "msCGILoadForm()");
+        return MS_FAILURE;
+      }
+      continue;
+    }
+
+    if(strcasecmp(mapserv->request->ParamNames[i],"zoomdir") == 0) {
+      GET_NUMERIC(mapserv->request->ParamValues[i],tmpval);
+      mapserv->ZoomDirection = (int)tmpval;
+      if((mapserv->ZoomDirection != -1) && (mapserv->ZoomDirection != 1) && (mapserv->ZoomDirection != 0)) {
+        msSetError(MS_WEBERR, "Zoom direction must be 1, 0 or -1.", "msCGILoadForm()");
+        return MS_FAILURE;
+      }
+      continue;
+    }
+
+    if(strcasecmp(mapserv->request->ParamNames[i],"zoomsize") == 0) { /* absolute zoom magnitude */
+      GET_NUMERIC(mapserv->request->ParamValues[i],tmpval);
+      mapserv->ZoomSize = (int)tmpval;
+      if((mapserv->ZoomSize > MAXZOOM) || (mapserv->ZoomSize < 1)) {
+        msSetError(MS_WEBERR, "Invalid zoom size.", "msCGILoadForm()");
+        return MS_FAILURE;
+      }
+      continue;
+    }
+
+    if(strcasecmp(mapserv->request->ParamNames[i],"imgext") == 0) { /* extent of an existing image in a web application */
+      tokens = msStringSplit(mapserv->request->ParamValues[i], ' ', &n);
+
+      if(!tokens) {
+        msSetError(MS_MEMERR, NULL, "msCGILoadForm()");
+        return MS_FAILURE;
+      }
+
+      if(n != 4) {
+        msSetError(MS_WEBERR, "Not enough arguments for imgext.", "msCGILoadForm()");
+        return MS_FAILURE;
+      }
+
+      GET_NUMERIC(tokens[0],mapserv->ImgExt.minx);
+      GET_NUMERIC(tokens[1],mapserv->ImgExt.miny);
+      GET_NUMERIC(tokens[2],mapserv->ImgExt.maxx);
+      GET_NUMERIC(tokens[3],mapserv->ImgExt.maxy);
+
+      msFreeCharArray(tokens, 4);
+      continue;
+    }
+
+    if(strcasecmp(mapserv->request->ParamNames[i],"searchmap") == 0) {
+      mapserv->SearchMap = MS_TRUE;
+      continue;
+    }
+
+    if(strcasecmp(mapserv->request->ParamNames[i],"id") == 0) {
+      if(msEvalRegex(IDPATTERN, mapserv->request->ParamValues[i]) == MS_FALSE) {
+        msSetError(MS_WEBERR, "Parameter 'id' value fails to validate.", "msCGILoadForm()");
+        return MS_FAILURE;
+      }
+      strlcpy(mapserv->Id, mapserv->request->ParamValues[i], IDSIZE);
+      continue;
+    }
+
+    if(strcasecmp(mapserv->request->ParamNames[i],"mapext") == 0) { /* extent of the new map or query */
+
+      if(strncasecmp(mapserv->request->ParamValues[i],"shape",5) == 0)
+        mapserv->UseShapes = MS_TRUE;
+      else {
+        tokens = msStringSplit(mapserv->request->ParamValues[i], ' ', &n);
+
+        if(!tokens) {
+          msSetError(MS_MEMERR, NULL, "msCGILoadForm()");
+          return MS_FAILURE;
+        }
+
+        if(n != 4) {
+          msSetError(MS_WEBERR, "Not enough arguments for mapext.", "msCGILoadForm()");
+          return MS_FAILURE;
+        }
+
+        GET_NUMERIC(tokens[0],mapserv->map->extent.minx);
+        GET_NUMERIC(tokens[1],mapserv->map->extent.miny);
+        GET_NUMERIC(tokens[2],mapserv->map->extent.maxx);
+        GET_NUMERIC(tokens[3],mapserv->map->extent.maxy);
+
+        msFreeCharArray(tokens, 4);
+
+#ifdef USE_PROJ
+        /*
+         * If there is a projection in the map file, and it is not lon/lat, and the
+         * extents "look like" they *are* lon/lat, based on their size,
+         * then convert the extents to the map file projection.
+         *
+         * DANGER: If the extents are legitimately in the mapfile projection
+         *         and coincidentally fall in the lon/lat range, bad things
+         *         will ensue.
+         */
+        if(mapserv->map->projection.proj && !pj_is_latlong(mapserv->map->projection.proj)
+            && (mapserv->map->extent.minx >= -180.0 && mapserv->map->extent.minx <= 180.0)
+            && (mapserv->map->extent.miny >= -90.0 && mapserv->map->extent.miny <= 90.0)
+            && (mapserv->map->extent.maxx >= -180.0 && mapserv->map->extent.maxx <= 180.0)
+            && (mapserv->map->extent.maxy >= -90.0 && mapserv->map->extent.maxy <= 90.0)) {
+          msProjectRect(&(mapserv->map->latlon), &(mapserv->map->projection), &(mapserv->map->extent)); /* extent is a in lat/lon */
+        }
+#endif
+
+        if((mapserv->map->extent.minx != mapserv->map->extent.maxx) && (mapserv->map->extent.miny != mapserv->map->extent.maxy)) { /* extent seems ok */
+          mapserv->CoordSource = FROMUSERBOX;
+          mapserv->QueryCoordSource = FROMUSERBOX;
+        }
+      }
+
+      continue;
+    }
+
+    if(strcasecmp(mapserv->request->ParamNames[i],"minx") == 0) { /* extent of the new map, in pieces */
+      GET_NUMERIC(mapserv->request->ParamValues[i],mapserv->map->extent.minx);
+      continue;
+    }
+    if(strcasecmp(mapserv->request->ParamNames[i],"maxx") == 0) {
+      GET_NUMERIC(mapserv->request->ParamValues[i],mapserv->map->extent.maxx);
+      continue;
+    }
+    if(strcasecmp(mapserv->request->ParamNames[i],"miny") == 0) {
+      GET_NUMERIC(mapserv->request->ParamValues[i],mapserv->map->extent.miny);
+      continue;
+    }
+    if(strcasecmp(mapserv->request->ParamNames[i],"maxy") == 0) {
+      GET_NUMERIC(mapserv->request->ParamValues[i],mapserv->map->extent.maxy);
+      mapserv->CoordSource = FROMUSERBOX;
+      mapserv->QueryCoordSource = FROMUSERBOX;
+      continue;
+    }
+
+    if(strcasecmp(mapserv->request->ParamNames[i],"mapxy") == 0) { /* user map coordinate */
+
+      if(strncasecmp(mapserv->request->ParamValues[i],"shape",5) == 0) {
+        mapserv->UseShapes = MS_TRUE;
+      } else {
+        tokens = msStringSplit(mapserv->request->ParamValues[i], ' ', &n);
+
+        if(!tokens) {
+          msSetError(MS_MEMERR, NULL, "msCGILoadForm()");
+          return MS_FAILURE;
+        }
+
+        if(n != 2) {
+          msSetError(MS_WEBERR, "Not enough arguments for mapxy.", "msCGILoadForm()");
+          return MS_FAILURE;
+        }
+
+        GET_NUMERIC(tokens[0],mapserv->mappnt.x );
+        GET_NUMERIC(tokens[1],mapserv->mappnt.y );
+
+        msFreeCharArray(tokens, 2);
+
+#ifdef USE_PROJ
+        if(mapserv->map->projection.proj && !pj_is_latlong(mapserv->map->projection.proj)
+            && (mapserv->mappnt.x >= -180.0 && mapserv->mappnt.x <= 180.0)
+            && (mapserv->mappnt.y >= -90.0 && mapserv->mappnt.y <= 90.0)) {
+          msProjectPoint(&(mapserv->map->latlon), &(mapserv->map->projection), &mapserv->mappnt); /* point is a in lat/lon */
+        }
+#endif
+
+        if(mapserv->CoordSource == NONE) { /* don't override previous settings (i.e. buffer or scale ) */
+          mapserv->CoordSource = FROMUSERPNT;
+          mapserv->QueryCoordSource = FROMUSERPNT;
+        }
+      }
+      continue;
+    }
+
+    /*
+    ** Query shape consisting of map or image coordinates. It's almost identical processing so we'll do either in this block...
+    */
+    if(strcasecmp(mapserv->request->ParamNames[i], "mapshape") == 0 || strcasecmp(mapserv->request->ParamNames[i], "imgshape") == 0) {
+      if(strcasecmp(mapserv->request->ParamNames[i],"mapshape") == 0)
+        mapserv->QueryCoordSource = FROMUSERSHAPE;
+      else
+        mapserv->QueryCoordSource = FROMIMGSHAPE;
+
+      if(strchr(mapserv->request->ParamValues[i], '(') != NULL) { /* try WKT */
+        if((mapserv->map->query.shape = msShapeFromWKT(mapserv->request->ParamValues[i])) == NULL) {
+          msSetError(MS_WEBERR, "WKT parse failed for mapshape/imgshape.", "msCGILoadForm()");
+          return MS_FAILURE;
+        }
+      } else {
+        lineObj line= {0,NULL};
+        char **tmp=NULL;
+        int n, j;
+
+        tmp = msStringSplit(mapserv->request->ParamValues[i], ' ', &n);
+
+        if(n%2 != 0 || n<8) { /* n must be even and be at least 8 */
+          msSetError(MS_WEBERR, "Malformed polygon geometry for mapshape/imgshape.", "msCGILoadForm()");
+          return MS_FAILURE;
+        }
+
+        line.numpoints = n/2;
+        if((line.point = (pointObj *)malloc(sizeof(pointObj)*line.numpoints)) == NULL) {
+          msSetError(MS_MEMERR, NULL, "msCGILoadForm()");
+          return MS_FAILURE;
+        }
+
+        if((mapserv->map->query.shape = (shapeObj *) malloc(sizeof(shapeObj))) == NULL) {
+          msSetError(MS_MEMERR, NULL, "msCGILoadForm()");
+          return MS_FAILURE;
+        }
+        msInitShape(mapserv->map->query.shape);
+        mapserv->map->query.shape->type = MS_SHAPE_POLYGON;
+
+        for(j=0; j<line.numpoints; j++) {
+          line.point[j].x = atof(tmp[2*j]);
+          line.point[j].y = atof(tmp[2*j+1]);
+
+#ifdef USE_PROJ
+          if(mapserv->QueryCoordSource == FROMUSERSHAPE && mapserv->map->projection.proj && !pj_is_latlong(mapserv->map->projection.proj)
+              && (line.point[j].x >= -180.0 && line.point[j].x <= 180.0)
+              && (line.point[j].y >= -90.0 && line.point[j].y <= 90.0)) {
+            msProjectPoint(&(mapserv->map->latlon), &(mapserv->map->projection), &line.point[j]); /* point is a in lat/lon */
+          }
+#endif
+        }
+
+        if(msAddLine(mapserv->map->query.shape, &line) == -1) {
+          msFree(line.point);
+          msFreeCharArray(tmp, n);
+          return MS_FAILURE;
+        }
+
+        msFree(line.point);
+        msFreeCharArray(tmp, n);
+      }
+
+      continue;
+    }
+
+    if(strcasecmp(mapserv->request->ParamNames[i],"img.x") == 0) { /* mouse click, in pieces */
+      GET_NUMERIC(mapserv->request->ParamValues[i],mapserv->ImgPnt.x);
+      if((mapserv->ImgPnt.x > (2*mapserv->map->maxsize)) || (mapserv->ImgPnt.x < (-2*mapserv->map->maxsize))) {
+        msSetError(MS_WEBERR, "Coordinate out of range.", "msCGILoadForm()");
+        return MS_FAILURE;
+      }
+      mapserv->CoordSource = FROMIMGPNT;
+      mapserv->QueryCoordSource = FROMIMGPNT;
+      continue;
+    }
+    if(strcasecmp(mapserv->request->ParamNames[i],"img.y") == 0) {
+      GET_NUMERIC(mapserv->request->ParamValues[i],mapserv->ImgPnt.y);
+      if((mapserv->ImgPnt.y > (2*mapserv->map->maxsize)) || (mapserv->ImgPnt.y < (-2*mapserv->map->maxsize))) {
+        msSetError(MS_WEBERR, "Coordinate out of range.", "msCGILoadForm()");
+        return MS_FAILURE;
+      }
+      mapserv->CoordSource = FROMIMGPNT;
+      mapserv->QueryCoordSource = FROMIMGPNT;
+      continue;
+    }
+
+    if(strcasecmp(mapserv->request->ParamNames[i],"imgxy") == 0) { /* mouse click, single variable */
+      if(mapserv->CoordSource == FROMIMGPNT)
+        continue;
+
+      tokens = msStringSplit(mapserv->request->ParamValues[i], ' ', &n);
+
+      if(!tokens) {
+        msSetError(MS_MEMERR, NULL, "msCGILoadForm()");
+        return MS_FAILURE;
+      }
+
+      if(n != 2) {
+        msSetError(MS_WEBERR, "Not enough arguments for imgxy.", "msCGILoadForm()");
+        return MS_FAILURE;
+      }
+
+      GET_NUMERIC(tokens[0],mapserv->ImgPnt.x );
+      GET_NUMERIC(tokens[1],mapserv->ImgPnt.y );
+
+      msFreeCharArray(tokens, 2);
+
+      if((mapserv->ImgPnt.x > (2*mapserv->map->maxsize)) || (mapserv->ImgPnt.x < (-2*mapserv->map->maxsize)) || (mapserv->ImgPnt.y > (2*mapserv->map->maxsize)) || (mapserv->ImgPnt.y < (-2*mapserv->map->maxsize))) {
+        msSetError(MS_WEBERR, "Reference map coordinate out of range.", "msCGILoadForm()");
+        return MS_FAILURE;
+      }
+
+      if(mapserv->CoordSource == NONE) { /* override nothing since this parameter is usually used to hold a default value */
+        mapserv->CoordSource = FROMIMGPNT;
+        mapserv->QueryCoordSource = FROMIMGPNT;
+      }
+      continue;
+    }
+
+    if(strcasecmp(mapserv->request->ParamNames[i],"imgbox") == 0) { /* selection box (eg. mouse drag) */
+      tokens = msStringSplit(mapserv->request->ParamValues[i], ' ', &n);
+
+      if(!tokens) {
+        msSetError(MS_MEMERR, NULL, "msCGILoadForm()");
+        return MS_FAILURE;
+      }
+
+      if(n != 4) {
+        msSetError(MS_WEBERR, "Not enough arguments for imgbox.", "msCGILoadForm()");
+        return MS_FAILURE;
+      }
+
+      GET_NUMERIC(tokens[0],mapserv->ImgBox.minx);
+      GET_NUMERIC(tokens[1],mapserv->ImgBox.miny);
+      GET_NUMERIC(tokens[2],mapserv->ImgBox.maxx);
+      GET_NUMERIC(tokens[3],mapserv->ImgBox.maxy);
+
+      msFreeCharArray(tokens, 4);
+
+      if((mapserv->ImgBox.minx != mapserv->ImgBox.maxx) && (mapserv->ImgBox.miny != mapserv->ImgBox.maxy)) { /* must not degenerate into a point */
+        mapserv->CoordSource = FROMIMGBOX;
+        mapserv->QueryCoordSource = FROMIMGBOX;
+      }
+      continue;
+    }
+
+    if(strcasecmp(mapserv->request->ParamNames[i],"ref.x") == 0) { /* mouse click in reference image, in pieces */
+      GET_NUMERIC(mapserv->request->ParamValues[i],mapserv->RefPnt.x);
+      if((mapserv->RefPnt.x > (2*mapserv->map->maxsize)) || (mapserv->RefPnt.x < (-2*mapserv->map->maxsize))) {
+        msSetError(MS_WEBERR, "Coordinate out of range.", "msCGILoadForm()");
+        return MS_FAILURE;
+      }
+      mapserv->CoordSource = FROMREFPNT;
+      continue;
+    }
+    if(strcasecmp(mapserv->request->ParamNames[i],"ref.y") == 0) {
+      GET_NUMERIC(mapserv->request->ParamValues[i],mapserv->RefPnt.y);
+      if((mapserv->RefPnt.y > (2*mapserv->map->maxsize)) || (mapserv->RefPnt.y < (-2*mapserv->map->maxsize))) {
+        msSetError(MS_WEBERR, "Coordinate out of range.", "msCGILoadForm()");
+        return MS_FAILURE;
+      }
+      mapserv->CoordSource = FROMREFPNT;
+      continue;
+    }
+
+    if(strcasecmp(mapserv->request->ParamNames[i],"refxy") == 0) { /* mouse click in reference image, single variable */
+      tokens = msStringSplit(mapserv->request->ParamValues[i], ' ', &n);
+
+      if(!tokens) {
+        msSetError(MS_MEMERR, NULL, "msCGILoadForm()");
+        return MS_FAILURE;
+      }
+
+      if(n != 2) {
+        msSetError(MS_WEBERR, "Not enough arguments for imgxy.", "msCGILoadForm()");
+        return MS_FAILURE;
+      }
+
+      GET_NUMERIC(tokens[0],mapserv->RefPnt.x);
+      GET_NUMERIC(tokens[1],mapserv->RefPnt.y);
+
+      msFreeCharArray(tokens, 2);
+
+      if((mapserv->RefPnt.x > (2*mapserv->map->maxsize)) || (mapserv->RefPnt.x < (-2*mapserv->map->maxsize)) || (mapserv->RefPnt.y > (2*mapserv->map->maxsize)) || (mapserv->RefPnt.y < (-2*mapserv->map->maxsize))) {
+        msSetError(MS_WEBERR, "Reference map coordinate out of range.", "msCGILoadForm()");
+        return MS_FAILURE;
+      }
+
+      mapserv->CoordSource = FROMREFPNT;
+      continue;
+    }
+
+    if(strcasecmp(mapserv->request->ParamNames[i],"buffer") == 0) { /* radius (map units), actually 1/2 square side */
+      GET_NUMERIC(mapserv->request->ParamValues[i],mapserv->Buffer);
+      mapserv->CoordSource = FROMBUF;
+      mapserv->QueryCoordSource = FROMUSERPNT;
+      continue;
+    }
+
+    if(strcasecmp(mapserv->request->ParamNames[i],"scale") == 0 || strcasecmp(mapserv->request->ParamNames[i],"scaledenom") == 0) { /* scale for new map */
+      GET_NUMERIC(mapserv->request->ParamValues[i],mapserv->ScaleDenom);
+      if(mapserv->ScaleDenom <= 0) {
+        msSetError(MS_WEBERR, "Scale out of range.", "msCGILoadForm()");
+        return MS_FAILURE;
+      }
+      mapserv->CoordSource = FROMSCALE;
+      mapserv->QueryCoordSource = FROMUSERPNT;
+      continue;
+    }
+
+    if(strcasecmp(mapserv->request->ParamNames[i],"imgsize") == 0) { /* size of existing image (pixels) */
+      tokens = msStringSplit(mapserv->request->ParamValues[i], ' ', &n);
+
+      if(!tokens) {
+        msSetError(MS_MEMERR, NULL, "msCGILoadForm()");
+        return MS_FAILURE;
+      }
+
+      if(n != 2) {
+        msSetError(MS_WEBERR, "Not enough arguments for imgsize.", "msCGILoadForm()");
+        return MS_FAILURE;
+      }
+
+      GET_NUMERIC(tokens[0],tmpval);
+      mapserv->ImgCols = (int)tmpval;
+      GET_NUMERIC(tokens[1],tmpval);
+      mapserv->ImgRows = (int)tmpval;
+
+      msFreeCharArray(tokens, 2);
+
+      if(mapserv->ImgCols > mapserv->map->maxsize || mapserv->ImgRows > mapserv->map->maxsize || mapserv->ImgCols <= 0 || mapserv->ImgRows <= 0) {
+        msSetError(MS_WEBERR, "Image size out of range.", "msCGILoadForm()");
+        return MS_FAILURE;
+      }
+
+      continue;
+    }
+
+    if(strcasecmp(mapserv->request->ParamNames[i],"mapsize") == 0) { /* size of new map (pixels) */
+      tokens = msStringSplit(mapserv->request->ParamValues[i], ' ', &n);
+
+      if(!tokens) {
+        msSetError(MS_MEMERR, NULL, "msCGILoadForm()");
+        return MS_FAILURE;
+      }
+
+      if(n != 2) {
+        msSetError(MS_WEBERR, "Not enough arguments for mapsize.", "msCGILoadForm()");
+        return MS_FAILURE;
+      }
+
+      GET_NUMERIC(tokens[0],tmpval);
+      mapserv->map->width = (int)tmpval;
+      GET_NUMERIC(tokens[1],tmpval);
+      mapserv->map->height = (int)tmpval;
+
+      msFreeCharArray(tokens, 2);
+
+      if(mapserv->map->width > mapserv->map->maxsize || mapserv->map->height > mapserv->map->maxsize || mapserv->map->width <= 0 || mapserv->map->height <= 0) {
+        msSetError(MS_WEBERR, "Image size out of range.", "msCGILoadForm()");
+        return MS_FAILURE;
+      }
+      continue;
+    }
+
+    if(strncasecmp(mapserv->request->ParamNames[i],"layers", 6) == 0) { /* turn a set of layers, delimited by spaces, on */
+
+      /* If layers=all then turn on all layers */
+      if (strcasecmp(mapserv->request->ParamValues[i], "all") == 0 && mapserv->map != NULL) {
+        int l;
+
+        /* Reset NumLayers=0. If individual layers were already selected then free the previous values.  */
+        for(l=0; l<mapserv->NumLayers; l++)
+          msFree(mapserv->Layers[l]);
+        mapserv->NumLayers=0;
+
+        for(mapserv->NumLayers=0; mapserv->NumLayers < mapserv->map->numlayers; mapserv->NumLayers++) {
+          if(msGrowMapservLayers(mapserv) == MS_FAILURE)
+            return MS_FAILURE;
+
+          if(GET_LAYER(mapserv->map, mapserv->NumLayers)->name) {
+            mapserv->Layers[mapserv->NumLayers] = msStrdup(GET_LAYER(mapserv->map, mapserv->NumLayers)->name);
+          } else {
+            mapserv->Layers[mapserv->NumLayers] = msStrdup("");
+          }
+        }
+      } else {
+        int num_layers=0, l;
+        char **layers=NULL;
+
+        layers = msStringSplit(mapserv->request->ParamValues[i], ' ', &(num_layers));
+        for(l=0; l<num_layers; l++) {
+          if(msGrowMapservLayers(mapserv) == MS_FAILURE)
+            return MS_FAILURE;
+          mapserv->Layers[mapserv->NumLayers++] = msStrdup(layers[l]);
+        }
+
+        msFreeCharArray(layers, num_layers);
+        num_layers = 0;
+      }
+
+      continue;
+    }
+
+    if(strncasecmp(mapserv->request->ParamNames[i],"layer", 5) == 0) { /* turn a single layer/group on */
+      if(msGrowMapservLayers(mapserv) == MS_FAILURE)
+        return MS_FAILURE;
+      mapserv->Layers[mapserv->NumLayers] = msStrdup(mapserv->request->ParamValues[i]);
+      mapserv->NumLayers++;
+      continue;
+    }
+
+    if(strcasecmp(mapserv->request->ParamNames[i],"qlayer") == 0) { /* layer to query (i.e search) */
+      mapserv->QueryLayer = msStrdup(mapserv->request->ParamValues[i]);
+      continue;
+    }
+
+    if(strcasecmp(mapserv->request->ParamNames[i],"qitem") == 0) { /* attribute to query on (optional) */
+      mapserv->QueryItem = msStrdup(mapserv->request->ParamValues[i]);
+      continue;
+    }
+
+    if(strcasecmp(mapserv->request->ParamNames[i],"qstring") == 0) { /* attribute query string */
+      mapserv->QueryString = msStrdup(mapserv->request->ParamValues[i]);
+      continue;
+    }
+
+    if(strcasecmp(mapserv->request->ParamNames[i],"qformat") == 0) { /* format to apply to query results (shortcut instead of having to use "map.web=QUERYFORMAT+foo") */
+      if(mapserv->map->web.queryformat) free(mapserv->map->web.queryformat); /* avoid leak */
+      mapserv->map->web.queryformat = msStrdup(mapserv->request->ParamValues[i]);
+      continue;
+    }
+
+    if(strcasecmp(mapserv->request->ParamNames[i],"slayer") == 0) { /* layer to select (for feature based search) */
+      mapserv->SelectLayer = msStrdup(mapserv->request->ParamValues[i]);
+      continue;
+    }
+
+    if(strcasecmp(mapserv->request->ParamNames[i],"shapeindex") == 0) { /* used for index queries */
+      GET_NUMERIC(mapserv->request->ParamValues[i],tmpval);
+      mapserv->ShapeIndex = (int)tmpval;
+      continue;
+    }
+    if(strcasecmp(mapserv->request->ParamNames[i],"tileindex") == 0) {
+      GET_NUMERIC(mapserv->request->ParamValues[i],tmpval);
+      mapserv->TileIndex = (int)tmpval;
+      continue;
+    }
+
+    /* --------------------------------------------------------------------
+     *   The following code is used to support mode=tile
+     * -------------------------------------------------------------------- */
+
+    if(strcasecmp(mapserv->request->ParamNames[i], "tilemode") == 0) {
+      /* currently, only valid tilemode is "spheremerc" */
+      if( strcasecmp(mapserv->request->ParamValues[i], "gmap") == 0) {
+        mapserv->TileMode = TILE_GMAP;
+      } else if ( strcasecmp(mapserv->request->ParamValues[i], "ve") == 0 ) {
+        mapserv->TileMode = TILE_VE;
+      } else {
+        msSetError(MS_WEBERR, "Invalid tilemode. Use one of: gmap, ve", "msCGILoadForm()");
+        return MS_FAILURE;
+      }
+      continue;
+    }
+
+    if(strcasecmp(mapserv->request->ParamNames[i],"tile") == 0) {
+
+      if( strlen(mapserv->request->ParamValues[i]) < 1 ) {
+        msSetError(MS_WEBERR, "Empty tile parameter.", "msCGILoadForm()");
+        return MS_FAILURE;
+      }
+      mapserv->CoordSource = FROMTILE;
+      mapserv->TileCoords = msStrdup(mapserv->request->ParamValues[i]);
+
+      continue;
+    }
+
+    /* -------------------------------------------------------------------- */
+    /*      The following code is used to support the rosa applet (for      */
+    /*      more information on Rosa, please consult :                      */
+    /*      http://www.maptools.org/rosa/) .                                */
+    /*      This code was provided by Tim.Mackey at agso.gov.au.               */
+    /*                                                                      */
+    /*      For Application using it can be seen at :                       */
+    /*        http://www.agso.gov.au/map/pilbara/                           */
+    /*                                                                      */
+    /* -------------------------------------------------------------------- */
+
+    if(strcasecmp(mapserv->request->ParamNames[i],"INPUT_TYPE") == 0) {
+      /* Rosa input type */
+      if(strcasecmp(mapserv->request->ParamValues[i],"auto_rect") == 0) {
+        rosa_type=1; /* rectangle */
+        continue;
+      }
+
+      if(strcasecmp(mapserv->request->ParamValues[i],"auto_point") == 0) {
+        rosa_type=2; /* point */
+        continue;
+      }
+    }
+    if(strcasecmp(mapserv->request->ParamNames[i],"INPUT_COORD") == 0) {
+      /* Rosa coordinates */
+
+      switch(rosa_type) {
+        case 1:
+          sscanf(mapserv->request->ParamValues[i],"%lf,%lf;%lf,%lf",
+                 &mapserv->ImgBox.minx,&mapserv->ImgBox.miny,&mapserv->ImgBox.maxx,
+                 &mapserv->ImgBox.maxy);
+          if((mapserv->ImgBox.minx != mapserv->ImgBox.maxx) &&
+              (mapserv->ImgBox.miny != mapserv->ImgBox.maxy)) {
+            mapserv->CoordSource = FROMIMGBOX;
+            mapserv->QueryCoordSource = FROMIMGBOX;
+          } else {
+            mapserv->CoordSource = FROMIMGPNT;
+            mapserv->QueryCoordSource = FROMIMGPNT;
+            mapserv->ImgPnt.x=mapserv->ImgBox.minx;
+            mapserv->ImgPnt.y=mapserv->ImgBox.miny;
+          }
+          break;
+        case 2:
+          sscanf(mapserv->request->ParamValues[i],"%lf,%lf",&mapserv->ImgPnt.x,
+                 &mapserv->ImgPnt.y);
+          mapserv->CoordSource = FROMIMGPNT;
+          mapserv->QueryCoordSource = FROMIMGPNT;
+          break;
+      }
+      continue;
+    }
+    /* -------------------------------------------------------------------- */
+    /*      end of code for Rosa support.                                   */
+    /* -------------------------------------------------------------------- */
+
+  } /* next parameter */
+
+  if(mapserv->Mode == ZOOMIN) {
+    mapserv->ZoomDirection = 1;
+    mapserv->Mode = BROWSE;
+  }
+  if(mapserv->Mode == ZOOMOUT) {
+    mapserv->ZoomDirection = -1;
+    mapserv->Mode = BROWSE;
+  }
+
+  if(mapserv->ZoomSize != 0) { /* use direction and magnitude to calculate zoom */
+    if(mapserv->ZoomDirection == 0) {
+      mapserv->fZoom = 1;
+    } else {
+      mapserv->fZoom = mapserv->ZoomSize*mapserv->ZoomDirection;
+      if(mapserv->fZoom < 0)
+        mapserv->fZoom = 1.0/MS_ABS(mapserv->fZoom);
+    }
+  } else { /* use single value for zoom */
+    if((mapserv->Zoom >= -1) && (mapserv->Zoom <= 1)) {
+      mapserv->fZoom = 1; /* pan */
+    } else {
+      if(mapserv->Zoom < 0)
+        mapserv->fZoom = 1.0/MS_ABS(mapserv->Zoom);
+      else
+        mapserv->fZoom = mapserv->Zoom;
+    }
+  }
+
+  if(mapserv->ImgRows == -1) mapserv->ImgRows = mapserv->map->height;
+  if(mapserv->ImgCols == -1) mapserv->ImgCols = mapserv->map->width;
+  if(mapserv->map->height == -1) mapserv->map->height = mapserv->ImgRows;
+  if(mapserv->map->width == -1) mapserv->map->width = mapserv->ImgCols;
+  return MS_SUCCESS;
+}
+
+int setExtentFromShapes(mapservObj *mapserv)
+{
+  double dx, dy, cellsize;
+
+  rectObj tmpext= {-1.0,-1.0,-1.0,-1.0};
+  pointObj tmppnt= {-1.0,-1.0};
+
+  msGetQueryResultBounds(mapserv->map, &(tmpext));
+
+  dx = tmpext.maxx - tmpext.minx;
+  dy = tmpext.maxy - tmpext.miny;
+
+  tmppnt.x = (tmpext.maxx + tmpext.minx)/2;
+  tmppnt.y = (tmpext.maxy + tmpext.miny)/2;
+  tmpext.minx -= dx*EXTENT_PADDING/2.0;
+  tmpext.maxx += dx*EXTENT_PADDING/2.0;
+  tmpext.miny -= dy*EXTENT_PADDING/2.0;
+  tmpext.maxy += dy*EXTENT_PADDING/2.0;
+
+  if(mapserv->ScaleDenom != 0) { /* apply the scale around the center point (tmppnt) */
+    cellsize = (mapserv->ScaleDenom/mapserv->map->resolution)/msInchesPerUnit(mapserv->map->units,0); /* user supplied a point and a scale */
+    tmpext.minx = tmppnt.x - cellsize*mapserv->map->width/2.0;
+    tmpext.miny = tmppnt.y - cellsize*mapserv->map->height/2.0;
+    tmpext.maxx = tmppnt.x + cellsize*mapserv->map->width/2.0;
+    tmpext.maxy = tmppnt.y + cellsize*mapserv->map->height/2.0;
+  } else if(mapserv->Buffer != 0) { /* apply the buffer around the center point (tmppnt) */
+    tmpext.minx = tmppnt.x - mapserv->Buffer;
+    tmpext.miny = tmppnt.y - mapserv->Buffer;
+    tmpext.maxx = tmppnt.x + mapserv->Buffer;
+    tmpext.maxy = tmppnt.y + mapserv->Buffer;
+  }
+
+  /* in case we don't get  usable extent at this point (i.e. single point result) */
+  if(!MS_VALID_EXTENT(tmpext)) {
+    if(mapserv->map->web.minscaledenom > 0) { /* try web object minscale first */
+      cellsize = (mapserv->map->web.minscaledenom/mapserv->map->resolution)/msInchesPerUnit(mapserv->map->units,0); /* user supplied a point and a scale */
+      tmpext.minx = tmppnt.x - cellsize*mapserv->map->width/2.0;
+      tmpext.miny = tmppnt.y - cellsize*mapserv->map->height/2.0;
+      tmpext.maxx = tmppnt.x + cellsize*mapserv->map->width/2.0;
+      tmpext.maxy = tmppnt.y + cellsize*mapserv->map->height/2.0;
+    } else {
+      msSetError(MS_WEBERR, "No way to generate a valid map extent from selected shapes.", "mapserv()");
+      return MS_FAILURE;
+    }
+  }
+
+  mapserv->mappnt = tmppnt;
+  mapserv->map->extent = mapserv->RawExt = tmpext; /* save unadjusted extent */
+
+  return MS_SUCCESS;
+}
+
+
+/* FIX: NEED ERROR CHECKING HERE FOR IMGPNT or MAPPNT */
+void setCoordinate(mapservObj *mapserv)
+{
+  double cellx,celly;
+
+  cellx = MS_CELLSIZE(mapserv->ImgExt.minx, mapserv->ImgExt.maxx, mapserv->ImgCols);
+  celly = MS_CELLSIZE(mapserv->ImgExt.miny, mapserv->ImgExt.maxy, mapserv->ImgRows);
+
+  mapserv->mappnt.x = MS_IMAGE2MAP_X(mapserv->ImgPnt.x, mapserv->ImgExt.minx, cellx);
+  mapserv->mappnt.y = MS_IMAGE2MAP_Y(mapserv->ImgPnt.y, mapserv->ImgExt.maxy, celly);
+
+  return;
+}
+
+
+int msCGIDispatchBrowseRequest(mapservObj *mapserv)
+{
+  char *template =  NULL;
+  int i,status;
+  for(i=0; i<mapserv->request->NumParams; i++) /* find the template param value */
+    if (strcasecmp(mapserv->request->ParamNames[i], "template") == 0)
+      template = mapserv->request->ParamValues[i];
+
+  if ( (!mapserv->map->web.template) && (template==NULL || (strcasecmp(template, "openlayers")!=0)) ) {
+    msSetError(MS_WEBERR, "Traditional BROWSE mode requires a TEMPLATE in the WEB section, but none was provided.", "mapserv()");
+    return MS_FAILURE;
+  }
+
+  if(mapserv->QueryFile) {
+    status = msLoadQuery(mapserv->map, mapserv->QueryFile);
+    if(status != MS_SUCCESS) return MS_FAILURE;
+  }
+
+  status = setExtent(mapserv);
+  if(status != MS_SUCCESS) return MS_FAILURE;
+  status = checkWebScale(mapserv);
+  if(status != MS_SUCCESS) return MS_FAILURE;
+
+  /* -------------------------------------------------------------------- */
+  /*      generate map, legend, scalebar and refernce images.             */
+  /* -------------------------------------------------------------------- */
+  if(msGenerateImages(mapserv, MS_FALSE, MS_TRUE) != MS_SUCCESS)
+    return MS_FAILURE;
+
+  if ( (template != NULL) && (strcasecmp(template, "openlayers")==0) ) {
+    msIO_setHeader("Content-Type","text/html");
+    msIO_sendHeaders();
+    if (msReturnOpenLayersPage(mapserv) != MS_SUCCESS)
+      return MS_FAILURE;
+  } else if(mapserv->QueryFile) {
+    if(msReturnTemplateQuery(mapserv, mapserv->map->web.queryformat, NULL) != MS_SUCCESS)
+      return MS_FAILURE;
+  } else {
+    if(TEMPLATE_TYPE(mapserv->map->web.template) == MS_FILE) { /* if thers's an html template, then use it */
+      if(mapserv->sendheaders) {
+        msIO_setHeader("Content-Type",mapserv->map->web.browseformat); /* write MIME header */
+        msIO_sendHeaders();
+      }
+      if(msReturnPage(mapserv, mapserv->map->web.template, BROWSE, NULL) != MS_SUCCESS)
+        return MS_FAILURE;
+    } else {
+      if(msReturnURL(mapserv, mapserv->map->web.template, BROWSE) != MS_SUCCESS)
+        return MS_FAILURE;
+    }
+  }
+  return MS_SUCCESS;
+}
+
+
+int msCGIDispatchCoordinateRequest(mapservObj *mapserv)
+{
+  setCoordinate(mapserv); /* mouse click => map coord */
+  msIO_printf("Your \"<i>click</i>\" corresponds to (approximately): (%g, %g).",
+              mapserv->mappnt.x, mapserv->mappnt.y);
+
+#ifdef USE_PROJ
+  if(mapserv->map->projection.proj != NULL && !pj_is_latlong(mapserv->map->projection.proj) ) {
+    pointObj p=mapserv->mappnt;
+    msProjectPoint(&(mapserv->map->projection), &(mapserv->map->latlon), &p);
+    msIO_printf("Computed lat/lon value is (%g, %g).\n",p.x, p.y);
+  }
+#endif
+  return MS_SUCCESS;
+}
+
+int msCGIDispatchQueryRequest(mapservObj *mapserv)
+{
+  int status,i,j;
+  char buffer[1024];
+  if(mapserv->QueryFile) { /* already got a completed query */
+    status = msLoadQuery(mapserv->map, mapserv->QueryFile);
+    if(status != MS_SUCCESS) return MS_FAILURE;
+  } else {
+
+    if((mapserv->QueryLayerIndex = msGetLayerIndex(mapserv->map, mapserv->QueryLayer)) != -1) /* force the query layer on */
+      GET_LAYER(mapserv->map, mapserv->QueryLayerIndex)->status = MS_ON;
+
+    switch(mapserv->Mode) {
+      case ITEMFEATUREQUERY:
+      case ITEMFEATURENQUERY:
+        if((mapserv->SelectLayerIndex = msGetLayerIndex(mapserv->map, mapserv->SelectLayer)) == -1) { /* force the selection layer on */
+          msSetError(MS_WEBERR, "Selection layer not set or references an invalid layer.", "mapserv()");
+          return MS_FAILURE;
+        }
+        GET_LAYER(mapserv->map, mapserv->SelectLayerIndex)->status = MS_ON;
+
+        /* validate the qstring parameter */
+        if(msValidateParameter(mapserv->QueryString, msLookupHashTable(&(GET_LAYER(mapserv->map, mapserv->SelectLayerIndex)->validation), "qstring"),
+                               msLookupHashTable(&(mapserv->map->web.validation), "qstring"),
+                               msLookupHashTable(&(GET_LAYER(mapserv->map, mapserv->SelectLayerIndex)->metadata), "qstring_validation_pattern"), NULL) != MS_SUCCESS) {
+          msSetError(MS_WEBERR, "Parameter 'qstring' value fails to validate.", "mapserv()");
+          return MS_FAILURE;
+        }
+
+        if(mapserv->QueryCoordSource != NONE && !mapserv->UseShapes)
+          if(MS_SUCCESS != setExtent(mapserv)) /* set user area of interest */
+            return MS_FAILURE;
+
+        mapserv->map->query.type = MS_QUERY_BY_ATTRIBUTE;
+        if(mapserv->QueryItem) mapserv->map->query.item = msStrdup(mapserv->QueryItem);
+        if(mapserv->QueryString) mapserv->map->query.str = msStrdup(mapserv->QueryString);
+
+        mapserv->map->query.rect = mapserv->map->extent;
+
+        mapserv->map->query.mode = MS_QUERY_MULTIPLE;
+        if(mapserv->Mode == ITEMFEATUREQUERY)
+          mapserv->map->query.mode = MS_QUERY_SINGLE;
+
+        mapserv->map->query.layer = mapserv->QueryLayerIndex;
+        mapserv->map->query.slayer = mapserv->SelectLayerIndex; /* this will trigger the feature query eventually */
+        break;
+      case FEATUREQUERY:
+      case FEATURENQUERY:
+        if((mapserv->SelectLayerIndex = msGetLayerIndex(mapserv->map, mapserv->SelectLayer)) == -1) { /* force the selection layer on */
+          msSetError(MS_WEBERR, "Selection layer not set or references an invalid layer.", "mapserv()");
+          return MS_FAILURE;
+        }
+        GET_LAYER(mapserv->map, mapserv->SelectLayerIndex)->status = MS_ON;
+
+        if(mapserv->Mode == FEATUREQUERY) {
+          switch(mapserv->QueryCoordSource) {
+            case FROMIMGPNT:
+              mapserv->map->extent = mapserv->ImgExt; /* use the existing map extent */
+              setCoordinate(mapserv);
+              break;
+            case FROMUSERPNT:
+              break;
+            default:
+              msSetError(MS_WEBERR, "No way to perform the initial search, not enough information.", "mapserv()");
+              return MS_FAILURE;
+              break;
+          }
+
+          mapserv->map->query.type = MS_QUERY_BY_POINT;
+          mapserv->map->query.mode = MS_QUERY_SINGLE;
+
+          mapserv->map->query.point = mapserv->mappnt;
+          mapserv->map->query.buffer = mapserv->Buffer;
+
+          mapserv->map->query.layer = mapserv->QueryLayerIndex;
+          mapserv->map->query.slayer = mapserv->SelectLayerIndex; /* this will trigger the feature query eventually */
+        } else { /* FEATURENQUERY */
+          switch(mapserv->QueryCoordSource) {
+            case FROMIMGPNT:
+              mapserv->map->extent = mapserv->ImgExt; /* use the existing map extent */
+              setCoordinate(mapserv);
+              mapserv->map->query.type = MS_QUERY_BY_POINT;
+              break;
+            case FROMIMGBOX:
+              /* TODO: this option was present but with no code to leverage the image box... */
+              break;
+            case FROMUSERPNT:
+              mapserv->map->query.type = MS_QUERY_BY_POINT;
+            default:
+              if(MS_SUCCESS != setExtent(mapserv)) {
+                return MS_FAILURE;
+              }
+              mapserv->map->query.type = MS_QUERY_BY_RECT;
+              break;
+          }
+        }
+
+        mapserv->map->query.mode = MS_QUERY_MULTIPLE;
+
+        mapserv->map->query.rect = mapserv->map->extent;
+        mapserv->map->query.point = mapserv->mappnt;
+        mapserv->map->query.buffer = mapserv->Buffer;
+
+        mapserv->map->query.layer = mapserv->QueryLayerIndex;
+        mapserv->map->query.slayer = mapserv->SelectLayerIndex;
+        break;
+      case ITEMQUERY:
+      case ITEMNQUERY:
+        if(mapserv->QueryLayerIndex < 0 || mapserv->QueryLayerIndex >= mapserv->map->numlayers) {
+          msSetError(MS_WEBERR, "Query layer not set or references an invalid layer.", "mapserv()");
+          return MS_FAILURE;
+        }
+
+        /* validate the qstring parameter */
+        if(msValidateParameter(mapserv->QueryString, msLookupHashTable(&(GET_LAYER(mapserv->map, mapserv->QueryLayerIndex)->validation), "qstring"),
+                               msLookupHashTable(&(mapserv->map->web.validation), "qstring"),
+                               msLookupHashTable(&(GET_LAYER(mapserv->map, mapserv->QueryLayerIndex)->metadata), "qstring_validation_pattern"), NULL) != MS_SUCCESS) {
+          msSetError(MS_WEBERR, "Parameter 'qstring' value fails to validate.", "mapserv()");
+          return MS_FAILURE;
+        }
+
+        if(mapserv->QueryCoordSource != NONE && !mapserv->UseShapes)
+          if(MS_SUCCESS != setExtent(mapserv)) /* set user area of interest */
+            return MS_FAILURE;
+
+        mapserv->map->query.type = MS_QUERY_BY_ATTRIBUTE;
+        mapserv->map->query.layer = mapserv->QueryLayerIndex;
+        if(mapserv->QueryItem) mapserv->map->query.item = msStrdup(mapserv->QueryItem);
+        if(mapserv->QueryString) mapserv->map->query.str = msStrdup(mapserv->QueryString);
+
+        mapserv->map->query.rect = mapserv->map->extent;
+
+        mapserv->map->query.mode = MS_QUERY_MULTIPLE;
+        if(mapserv->Mode == ITEMQUERY) mapserv->map->query.mode = MS_QUERY_SINGLE;
+        break;
+      case NQUERY:
+        mapserv->map->query.mode = MS_QUERY_MULTIPLE; /* all of these cases return multiple results */
+        mapserv->map->query.layer = mapserv->QueryLayerIndex;
+
+        switch(mapserv->QueryCoordSource) {
+          case FROMIMGPNT:
+            setCoordinate(mapserv);
+
+            if(mapserv->SearchMap) { /* compute new extent, pan etc then search that extent */
+              if(MS_SUCCESS != setExtent(mapserv)) /* set user area of interest */
+                return MS_FAILURE;
+              mapserv->map->cellsize = msAdjustExtent(&(mapserv->map->extent), mapserv->map->width, mapserv->map->height);
+              if((status = msCalculateScale(mapserv->map->extent, mapserv->map->units, mapserv->map->width, mapserv->map->height, mapserv->map->resolution, &mapserv->map->scaledenom)) != MS_SUCCESS) return MS_FAILURE;
+              mapserv->map->query.rect = mapserv->map->extent;
+              mapserv->map->query.type = MS_QUERY_BY_RECT;
+            } else {
+              mapserv->map->extent = mapserv->ImgExt; /* use the existing image parameters */
+              mapserv->map->width = mapserv->ImgCols;
+              mapserv->map->height = mapserv->ImgRows;
+              if((status = msCalculateScale(mapserv->map->extent, mapserv->map->units, mapserv->map->width, mapserv->map->height, mapserv->map->resolution, &mapserv->map->scaledenom)) != MS_SUCCESS) return MS_FAILURE;
+              mapserv->map->query.point = mapserv->mappnt;
+              mapserv->map->query.type = MS_QUERY_BY_POINT;
+            }
+
+            break;
+          case FROMIMGBOX:
+            if(mapserv->SearchMap) { /* compute new extent, pan etc then search that extent */
+              setExtent(mapserv);
+              if((status = msCalculateScale(mapserv->map->extent, mapserv->map->units, mapserv->map->width, mapserv->map->height, mapserv->map->resolution, &mapserv->map->scaledenom)) != MS_SUCCESS) return MS_FAILURE;
+              mapserv->map->cellsize = msAdjustExtent(&(mapserv->map->extent), mapserv->map->width, mapserv->map->height);
+              mapserv->map->query.rect = mapserv->map->extent;
+              mapserv->map->query.type = MS_QUERY_BY_RECT;
+            } else {
+              double cellx, celly;
+
+              mapserv->map->extent = mapserv->ImgExt; /* use the existing image parameters */
+              mapserv->map->width = mapserv->ImgCols;
+              mapserv->map->height = mapserv->ImgRows;
+              if((status = msCalculateScale(mapserv->map->extent, mapserv->map->units, mapserv->map->width, mapserv->map->height, mapserv->map->resolution, &mapserv->map->scaledenom)) != MS_SUCCESS) return MS_FAILURE;
+              cellx = MS_CELLSIZE(mapserv->ImgExt.minx, mapserv->ImgExt.maxx, mapserv->ImgCols); /* calculate the new search extent */
+              celly = MS_CELLSIZE(mapserv->ImgExt.miny, mapserv->ImgExt.maxy, mapserv->ImgRows);
+              mapserv->RawExt.minx = MS_IMAGE2MAP_X(mapserv->ImgBox.minx, mapserv->ImgExt.minx, cellx);
+              mapserv->RawExt.maxx = MS_IMAGE2MAP_X(mapserv->ImgBox.maxx, mapserv->ImgExt.minx, cellx);
+              mapserv->RawExt.maxy = MS_IMAGE2MAP_Y(mapserv->ImgBox.miny, mapserv->ImgExt.maxy, celly); /* y's are flip flopped because img/map coordinate systems are */
+              mapserv->RawExt.miny = MS_IMAGE2MAP_Y(mapserv->ImgBox.maxy, mapserv->ImgExt.maxy, celly);
+
+              mapserv->map->query.rect = mapserv->RawExt;
+              mapserv->map->query.type = MS_QUERY_BY_RECT;
+            }
+            break;
+          case FROMIMGSHAPE:
+            mapserv->map->extent = mapserv->ImgExt; /* use the existing image parameters */
+            mapserv->map->width = mapserv->ImgCols;
+            mapserv->map->height = mapserv->ImgRows;
+            mapserv->map->cellsize = msAdjustExtent(&(mapserv->map->extent), mapserv->map->width, mapserv->map->height);
+            if((status = msCalculateScale(mapserv->map->extent, mapserv->map->units, mapserv->map->width, mapserv->map->height, mapserv->map->resolution, &mapserv->map->scaledenom)) != MS_SUCCESS) return MS_FAILURE;
+
+            /* convert from image to map coordinates here (see setCoordinate) */
+            for(i=0; i<mapserv->map->query.shape->numlines; i++) {
+              for(j=0; j<mapserv->map->query.shape->line[i].numpoints; j++) {
+                mapserv->map->query.shape->line[i].point[j].x = MS_IMAGE2MAP_X(mapserv->map->query.shape->line[i].point[j].x, mapserv->map->extent.minx, mapserv->map->cellsize);
+                mapserv->map->query.shape->line[i].point[j].y = MS_IMAGE2MAP_Y(mapserv->map->query.shape->line[i].point[j].y, mapserv->map->extent.maxy, mapserv->map->cellsize);
+              }
+            }
+
+            mapserv->map->query.type = MS_QUERY_BY_SHAPE;
+            break;
+          case FROMUSERPNT:
+            if(mapserv->Buffer == 0) { /* do a *pure* point query */
+              mapserv->map->query.point = mapserv->mappnt;
+              mapserv->map->query.type = MS_QUERY_BY_POINT;
+              setExtent(mapserv);
+            } else {
+              setExtent(mapserv);
+              if(mapserv->SearchMap) { /* the extent should be tied to a map, so we need to "adjust" it */
+                if((status = msCalculateScale(mapserv->map->extent, mapserv->map->units, mapserv->map->width, mapserv->map->height, mapserv->map->resolution, &mapserv->map->scaledenom)) != MS_SUCCESS) return MS_FAILURE;
+                mapserv->map->cellsize = msAdjustExtent(&(mapserv->map->extent), mapserv->map->width, mapserv->map->height);
+              }
+              mapserv->map->query.rect = mapserv->map->extent;
+              mapserv->map->query.type = MS_QUERY_BY_RECT;
+            }
+            break;
+          case FROMUSERSHAPE:
+            setExtent(mapserv);
+            mapserv->map->query.type = MS_QUERY_BY_SHAPE;
+            break;
+          default: /* from an extent of some sort */
+            setExtent(mapserv);
+            if(mapserv->SearchMap) { /* the extent should be tied to a map, so we need to "adjust" it */
+              if((status = msCalculateScale(mapserv->map->extent, mapserv->map->units, mapserv->map->width, mapserv->map->height, mapserv->map->resolution, &mapserv->map->scaledenom)) != MS_SUCCESS) return MS_FAILURE;
+              mapserv->map->cellsize = msAdjustExtent(&(mapserv->map->extent), mapserv->map->width, mapserv->map->height);
+            }
+
+            mapserv->map->query.rect = mapserv->map->extent;
+            mapserv->map->query.type = MS_QUERY_BY_RECT;
+            break;
+        }
+        break;
+      case QUERY:
+        switch(mapserv->QueryCoordSource) {
+          case FROMIMGPNT:
+            setCoordinate(mapserv);
+            mapserv->map->extent = mapserv->ImgExt; /* use the existing image parameters */
+            mapserv->map->width = mapserv->ImgCols;
+            mapserv->map->height = mapserv->ImgRows;
+            if((status = msCalculateScale(mapserv->map->extent, mapserv->map->units, mapserv->map->width, mapserv->map->height, mapserv->map->resolution, &mapserv->map->scaledenom)) != MS_SUCCESS) return MS_FAILURE;
+            break;
+          case FROMUSERPNT: /* only a buffer makes sense, DOES IT? */
+            if(setExtent(mapserv) != MS_SUCCESS) return MS_FAILURE;
+            break;
+          default:
+            msSetError(MS_WEBERR, "Query mode needs a point, imgxy and mapxy are not set.", "mapserv()");
+            return MS_FAILURE;
+            break;
+        }
+
+        mapserv->map->query.type = MS_QUERY_BY_POINT;
+        mapserv->map->query.mode = MS_QUERY_SINGLE;
+        mapserv->map->query.layer = mapserv->QueryLayerIndex;
+        mapserv->map->query.point = mapserv->mappnt;
+        mapserv->map->query.buffer = mapserv->Buffer;
+        break;
+      case INDEXQUERY:
+        mapserv->map->query.type = MS_QUERY_BY_INDEX;
+        mapserv->map->query.mode = MS_QUERY_SINGLE;
+        mapserv->map->query.layer = mapserv->QueryLayerIndex;
+        mapserv->map->query.shapeindex = mapserv->ShapeIndex;
+        mapserv->map->query.tileindex = mapserv->TileIndex;
+        break;
+    } /* end mode switch */
+
+    /* finally execute the query */
+    if((status = msExecuteQuery(mapserv->map)) != MS_SUCCESS) return MS_FAILURE;
+  }
+
+  if(mapserv->map->querymap.width != -1) mapserv->map->width = mapserv->map->querymap.width; /* make sure we use the right size */
+  if(mapserv->map->querymap.height != -1) mapserv->map->height = mapserv->map->querymap.height;
+
+  if(mapserv->UseShapes)
+    if(MS_SUCCESS != setExtentFromShapes(mapserv))
+      return MS_FAILURE;
+
+  if(msReturnTemplateQuery(mapserv, mapserv->map->web.queryformat, NULL) != MS_SUCCESS) return MS_FAILURE;
+
+  if(mapserv->savequery) {
+    snprintf(buffer, sizeof(buffer), "%s%s%s%s", mapserv->map->web.imagepath, mapserv->map->name, mapserv->Id, MS_QUERY_EXTENSION);
+    if((status = msSaveQuery(mapserv->map, buffer, MS_FALSE)) != MS_SUCCESS) return status;
+  }
+  return MS_SUCCESS;
+}
+
+int msCGIDispatchImageRequest(mapservObj *mapserv)
+{
+  int status;
+  imageObj *img = NULL;
+  switch(mapserv->Mode) {
+    case MAP:
+      if(mapserv->QueryFile) {
+        status = msLoadQuery(mapserv->map, mapserv->QueryFile);
+        if(status != MS_SUCCESS) return MS_FAILURE;
+        img = msDrawMap(mapserv->map, MS_TRUE);
+      } else
+        img = msDrawMap(mapserv->map, MS_FALSE);
+      break;
+    case REFERENCE:
+      mapserv->map->cellsize = msAdjustExtent(&(mapserv->map->extent), mapserv->map->width, mapserv->map->height);
+      img = msDrawReferenceMap(mapserv->map);
+      break;
+    case SCALEBAR:
+      img = msDrawScalebar(mapserv->map);
+      break;
+    case TILE:
+      msTileSetExtent(mapserv);
+      img = msTileDraw(mapserv);
+      break;
+    case LEGEND:
+      img = msDrawLegend(mapserv->map, MS_FALSE);
+      break;
+  }
+
+  if(!img) return MS_FAILURE;
+
+  /*
+   ** Set the Cache control headers if the option is set.
+   */
+  if( mapserv->sendheaders && msLookupHashTable(&(mapserv->map->web.metadata), "http_max_age") ) {
+    msIO_setHeader("Cache-Control","max-age=%s", msLookupHashTable(&(mapserv->map->web.metadata), "http_max_age"));
+  }
+
+  if(mapserv->sendheaders)  {
+    const char *attachment = msGetOutputFormatOption(mapserv->map->outputformat, "ATTACHMENT", NULL );
+    if(attachment)
+      msIO_setHeader("Content-disposition","attachment; filename=%s", attachment);
+    msIO_setHeader("Content-Type",MS_IMAGE_MIME_TYPE(mapserv->map->outputformat));
+    msIO_sendHeaders();
+  }
+
+  if( mapserv->Mode == MAP || mapserv->Mode == TILE )
+    status = msSaveImage(mapserv->map, img, NULL);
+  else
+    status = msSaveImage(NULL,img, NULL);
+
+  if(status != MS_SUCCESS) return MS_FAILURE;
+
+  msFreeImage(img);
+  return MS_SUCCESS;
+}
+
+
+int msCGIDispatchLegendRequest(mapservObj *mapserv)
+{
+  if(mapserv->map->legend.template) {
+    char *legendTemplate;
+    legendTemplate = generateLegendTemplate(mapserv);
+    if(legendTemplate) {
+      if(mapserv->sendheaders) {
+        msIO_setHeader("Content-Type",mapserv->map->web.legendformat);
+        msIO_sendHeaders();
+      }
+      msIO_fwrite(legendTemplate, strlen(legendTemplate), 1, stdout);
+
+      free(legendTemplate);
+      return MS_SUCCESS;
+    } else {/* error already generated by (generateLegendTemplate()) */
+      return MS_FAILURE;
+    }
+  } else {
+    return msCGIDispatchImageRequest(mapserv);
+  }
+}
+
+int msCGIDispatchLegendIconRequest(mapservObj *mapserv)
+{
+  char **tokens;
+  int numtokens=0;
+  int layerindex=-1, classindex=0;
+  outputFormatObj *format = NULL;
+  imageObj *img;
+
+  /* TODO: do we want to set scale here? */
+
+  /* do we have enough information */
+  if(!mapserv->icon) {
+    msSetError(MS_WEBERR, "Mode=LEGENDICON requires an icon parameter.", "mapserv()");
+    return MS_FAILURE;
+  }
+
+  /* process the icon definition */
+  tokens = msStringSplit(mapserv->icon, ',', &numtokens);
+
+  if(numtokens != 1 && numtokens != 2) {
+    msSetError(MS_WEBERR, "%d Malformed icon parameter, should be 'layer,class' or just 'layer' if the layer has only 1 class defined.", "mapserv()", numtokens);
+    return MS_FAILURE;
+  }
+
+  if((layerindex = msGetLayerIndex(mapserv->map, tokens[0])) == -1) {
+    msSetError(MS_WEBERR, "Icon layer=%s not found in mapfile.", "mapserv()", tokens[0]);
+    return MS_FAILURE;
+  }
+
+  if(numtokens == 2) { /* check the class index */
+    classindex = atoi(tokens[1]);
+    if(classindex >= GET_LAYER(mapserv->map, layerindex)->numclasses) {
+      msSetError(MS_WEBERR, "Icon class=%d not found in layer=%s.", "mapserv()", classindex, GET_LAYER(mapserv->map, layerindex)->name);
+      return MS_FAILURE;
+    }
+  }
+
+  /* ensure we have an image format representing the options for the legend. */
+  msApplyOutputFormat(&format, mapserv->map->outputformat, mapserv->map->legend.transparent, mapserv->map->legend.interlace, MS_NOOVERRIDE);
+
+  /* initialize the legend image */
+  if( ! MS_RENDERER_PLUGIN(format) ) {
+    msSetError(MS_RENDERERERR, "unsupported renderer for legend icon", "mapserv main()");
+    return MS_FAILURE;
+  }
+  img = msImageCreate(mapserv->map->legend.keysizex, mapserv->map->legend.keysizey, format,
+                      mapserv->map->web.imagepath, mapserv->map->web.imageurl, mapserv->map->resolution, mapserv->map->defresolution,
+                      &(mapserv->map->legend.imagecolor));
+
+  /* drop this reference to output format */
+  msApplyOutputFormat(&format, NULL, MS_NOOVERRIDE, MS_NOOVERRIDE, MS_NOOVERRIDE);
+
+  if(msDrawLegendIcon(mapserv->map, GET_LAYER(mapserv->map, layerindex), GET_LAYER(mapserv->map, layerindex)->class[classindex], mapserv->map->legend.keysizex,  mapserv->map->legend.keysizey, img, 0, 0) != MS_SUCCESS)
+    return MS_FAILURE;
+
+  if(mapserv->sendheaders) {
+    msIO_setHeader("Content-Type",MS_IMAGE_MIME_TYPE(mapserv->map->outputformat));
+    msIO_sendHeaders();
+  }
+  /*
+   ** Set the Cache control headers if the option is set.
+   */
+  if( mapserv->sendheaders && msLookupHashTable(&(mapserv->map->web.metadata), "http_max_age") ) {
+    msIO_printf("Cache-Control: max-age=%s%c", msLookupHashTable(&(mapserv->map->web.metadata), "http_max_age"), 10);
+  }
+  if( msSaveImage(NULL, img, NULL) != MS_SUCCESS)
+    return MS_FAILURE;
+
+  msFreeCharArray(tokens, numtokens);
+  msFreeImage(img);
+  return MS_SUCCESS;
+}
+
+int msCGIDispatchRequest(mapservObj *mapserv)
+{
+  int i;
+  int status;
+
+  /*
+   ** Determine 'mode': Check for MS_MODE env. var. and mode=... CGI param
+   */
+  mapserv->Mode = -1; /* Not set */
+  if( msCGISetMode(mapserv) != MS_SUCCESS) {
+    return MS_FAILURE;
+  }
+
+  /*
+   ** Start by calling the WMS/WFS/WCS Dispatchers.  If they fail then we'll
+   ** process this as a regular MapServer request.
+   */
+  if((mapserv->Mode == -1 || mapserv->Mode == OWS || mapserv->Mode == WFS) &&
+      (status = msOWSDispatch(mapserv->map, mapserv->request,
+                              mapserv->Mode)) != MS_DONE  )  {
+    /*
+     ** OWSDispatch returned either MS_SUCCESS or MS_FAILURE
+     */
+    if( status == MS_FAILURE ) {
+      return MS_FAILURE;
+    }
+
+    if (status == MS_SUCCESS &&
+        strcasecmp(mapserv->map->imagetype, "application/openlayers")==0) {
+      char *service = NULL;
+      for( i=0; i<mapserv->request->NumParams; i++) {
+        if(strcasecmp(mapserv->request->ParamNames[i], "SERVICE") == 0) {
+          service = mapserv->request->ParamValues[i];
+          break;
+        }
+      }
+      if (service && strcasecmp(service,"WMS")==0) {
+        if(mapserv->sendheaders) {
+          msIO_setHeader("Content-Type","text/html");
+          msIO_sendHeaders();
+        }
+
+        if (msReturnOpenLayersPage(mapserv) != MS_SUCCESS)
+          return MS_FAILURE;
+      }
+    }
+    return MS_SUCCESS;
+  } /* done OGC/OWS case */
+
+
+  /*
+  ** Do "traditional" mode processing.
+  */
+  if (mapserv->Mode == -1)
+    mapserv->Mode = BROWSE;
+
+  if(MS_SUCCESS != msCGILoadForm(mapserv)) {
+    return MS_FAILURE;
+  }
+
+  /* Insecure as implemented, need to save someplace non accessible by everyone in the universe
+      if(mapserv->savemap) {
+        snprintf(buffer, sizeof(buffer), "%s%s%s.map", mapserv->map->web.imagepath, mapserv->map->name, mapserv->Id);
+        if(msSaveMap(mapserv->map, buffer) == -1) return MS_FAILURE;
+      }
+  */
+
+  if((mapserv->CoordSource == FROMIMGPNT) || (mapserv->CoordSource == FROMIMGBOX)) /* make sure extent of existing image matches shape of image */
+    mapserv->map->cellsize = msAdjustExtent(&mapserv->ImgExt, mapserv->ImgCols, mapserv->ImgRows);
+
+  /*
+  ** For each layer let's set layer status
+  */
+  for(i=0; i<mapserv->map->numlayers; i++) {
+    if((GET_LAYER(mapserv->map, i)->status != MS_DEFAULT)) {
+      if(isOn(mapserv,  GET_LAYER(mapserv->map, i)->name, GET_LAYER(mapserv->map, i)->group) == MS_TRUE) /* Set layer status */
+        GET_LAYER(mapserv->map, i)->status = MS_ON;
+      else
+        GET_LAYER(mapserv->map, i)->status = MS_OFF;
+    }
+  }
+
+  if(mapserv->CoordSource == FROMREFPNT) /* force browse mode if the reference coords are set */
+    mapserv->Mode = BROWSE;
+
+  if(mapserv->Mode == TILE) {
+    /*
+     ** Tile mode:
+     ** Set the projection up and test the parameters for legality.
+     */
+    if( msTileSetup(mapserv) != MS_SUCCESS ) {
+      return MS_FAILURE;
+    }
+  }
+  if(mapserv->Mode == BROWSE) {
+    return msCGIDispatchBrowseRequest(mapserv);
+  } else if(mapserv->Mode == MAP || mapserv->Mode == SCALEBAR || mapserv->Mode == REFERENCE || mapserv->Mode == TILE) { /* "image" only modes */
+    /* tile, map, scalebar and reference all need the extent to be set up correctly */
+    if(setExtent(mapserv) != MS_SUCCESS) return MS_FAILURE;
+    if(checkWebScale(mapserv) != MS_SUCCESS) return MS_FAILURE;
+    return msCGIDispatchImageRequest(mapserv);
+  } else if(mapserv->Mode == LEGEND) {
+    return msCGIDispatchLegendRequest(mapserv);
+  } else if(mapserv->Mode == LEGENDICON) {
+    return msCGIDispatchLegendIconRequest(mapserv);
+  } else if(mapserv->Mode >= QUERY) {
+    return msCGIDispatchQueryRequest(mapserv);
+  } else if(mapserv->Mode == COORDINATE) {
+    return msCGIDispatchCoordinateRequest(mapserv);
+  } else {
+    msSetError(MS_WEBERR, "Bug: unsupported mode", "msDispatchRequest");
+    return MS_FAILURE;
+  }
+}
+
+int msCGIHandler(const char *query_string, void **out_buffer, size_t *buffer_length)
+{
+  int x,m=0;
+  struct mstimeval execstarttime, execendtime;
+  struct mstimeval requeststarttime, requestendtime;
+  mapservObj* mapserv = NULL;
+  char *queryString = NULL;
+  int maxParams = MS_DEFAULT_CGI_PARAMS;
+  msIOContext *ctx;
+  msIOBuffer  *buf;
+
+  msIO_installStdoutToBuffer();
+  /* Use MS_ERRORFILE and MS_DEBUGLEVEL env vars if set */
+  if( msDebugInitFromEnv() != MS_SUCCESS ) {
+    msCGIWriteError(mapserv);
+    goto end_request;
+  }
+
+  if(msGetGlobalDebugLevel() >= MS_DEBUGLEVEL_TUNING)
+    msGettimeofday(&execstarttime, NULL);
+
+  mapserv = msAllocMapServObj();
+  mapserv->request->type = MS_GET_REQUEST;
+
+  if(!query_string || !*query_string) {
+    msIO_setHeader("Content-Type","text/html");
+    msIO_sendHeaders();
+    msIO_printf("No query information to decode. QUERY_STRING not set.\n");
+    goto end_request;
+  }
+
+  /* don't modify the string */
+  queryString = msStrdup(query_string);
+  for(x=0; queryString[0] != '\0'; x++) {
+    if(m >= maxParams) {
+      maxParams *= 2;
+      mapserv->request->ParamNames = (char **) realloc(mapserv->request->ParamNames,sizeof(char *) * maxParams);
+      if (mapserv->request->ParamNames == NULL) {
+        msIO_printf("Out of memory trying to allocate name/value pairs.\n");
+        goto end_request;
+      }
+      mapserv->request->ParamValues = (char **) realloc(mapserv->request->ParamValues,sizeof(char *) * maxParams);
+      if (mapserv->request->ParamValues ==  NULL) {
+        msIO_printf("Out of memory trying to allocate name/value pairs.\n");
+        goto end_request;
+      }
+    }
+    mapserv->request->ParamValues[m] = makeword(queryString,'&');
+    plustospace(mapserv->request->ParamValues[m]);
+    unescape_url(mapserv->request->ParamValues[m]);
+    mapserv->request->ParamNames[m] = makeword(mapserv->request->ParamValues[m],'=');
+    m++;
+  }
+  mapserv->request->NumParams = m;
+
+  if( mapserv->request->NumParams == 0 ) {
+    msCGIWriteError(mapserv);
+    goto end_request;
+  }
+
+  mapserv->map = msCGILoadMap(mapserv);
+  if(!mapserv->map) {
+    msCGIWriteError(mapserv);
+    goto end_request;
+  }
+
+  if( mapserv->map->debug >= MS_DEBUGLEVEL_TUNING)
+    msGettimeofday(&requeststarttime, NULL);
+
+
+  if(msCGIDispatchRequest(mapserv) != MS_SUCCESS) {
+    msCGIWriteError(mapserv);
+    goto end_request;
+  }
+
+
+end_request:
+  if(mapserv) {
+    if(mapserv->map && mapserv->map->debug >= MS_DEBUGLEVEL_TUNING) {
+      msGettimeofday(&requestendtime, NULL);
+      msDebug("mapserv request processing time (msLoadMap not incl.): %.3fs\n",
+              (requestendtime.tv_sec+requestendtime.tv_usec/1.0e6)-
+              (requeststarttime.tv_sec+requeststarttime.tv_usec/1.0e6) );
+    }
+    msCGIWriteLog(mapserv,MS_FALSE);
+    msFreeMapServObj(mapserv);
+  }
+
+  /* normal case, processing is complete */
+  if(msGetGlobalDebugLevel() >= MS_DEBUGLEVEL_TUNING) {
+    msGettimeofday(&execendtime, NULL);
+    msDebug("mapserv total execution time: %.3fs\n",
+            (execendtime.tv_sec+execendtime.tv_usec/1.0e6)-
+            (execstarttime.tv_sec+execstarttime.tv_usec/1.0e6) );
+  }
+  ctx = msIO_getHandler( (FILE *) "stdout" );
+  buf = (msIOBuffer *) ctx->cbData;
+  *out_buffer = buf->data;
+  *buffer_length = buf->data_offset;
+
+  free(queryString);
+
+  return 0;
+}
diff --git a/mapshape.c b/mapshape.c
index ce98774..ea0f684 100644
--- a/mapshape.c
+++ b/mapshape.c
@@ -8,8 +8,8 @@
  * Note:
  * This code is entirely based on the previous work of Frank Warmerdam. It is
  * essentially shapelib 1.1.5. However, there were enough changes that it was
- * incorporated into the MapServer source to avoid confusion. Relicensed with 
- * permission of Frank Warmerdam (shapelib author). See the README 
+ * incorporated into the MapServer source to avoid confusion. Relicensed with
+ * permission of Frank Warmerdam (shapelib author). See the README
  * for licence details.
  *
  ******************************************************************************
@@ -22,7 +22,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -38,7 +38,7 @@
 #include <assert.h>
 #include "mapserver.h"
 
-MS_CVSID("$Id$")
+
 
 /* Only use this macro on 32-bit integers! */
 #define SWAP_FOUR_BYTES(data) \
@@ -58,8 +58,8 @@ static int      bBigEndian;
 static void SwapWord( int length, void * wordP )
 {
   int i;
-  uchar	temp;
-  
+  uchar temp;
+
   for( i=0; i < length/2; i++ ) {
     temp = ((uchar *) wordP)[i];
     ((uchar *)wordP)[i] = ((uchar *) wordP)[length-i-1];
@@ -73,7 +73,7 @@ static void SwapWord( int length, void * wordP )
 /*      A realloc cover function that will access a NULL pointer as     */
 /*      a valid input.                                                  */
 /************************************************************************/
-static void * SfRealloc( void * pMem, int nNewSize )     
+static void * SfRealloc( void * pMem, int nNewSize )
 {
   if( pMem == NULL )
     return( (void *) malloc(nNewSize) );
@@ -84,55 +84,55 @@ static void * SfRealloc( void * pMem, int nNewSize )
 /************************************************************************/
 /*                          writeHeader()                               */
 /*                                                                      */
-/*      Write out a header for the .shp and .shx files as well as the	*/
-/*	contents of the index (.shx) file.				*/
+/*      Write out a header for the .shp and .shx files as well as the */
+/*  contents of the index (.shx) file.        */
 /************************************************************************/
 static void writeHeader( SHPHandle psSHP )
 {
   uchar abyHeader[100];
-  int	i;
+  int i;
   ms_int32 i32;
   double dValue;
   ms_int32 *panSHX;
-  
+
   /* -------------------------------------------------------------------- */
   /*      Prepare header block for .shp file.                             */
   /* -------------------------------------------------------------------- */
   for( i = 0; i < 100; i++ )
     abyHeader[i] = 0;
-  
-  abyHeader[2] = 0x27;				/* magic cookie */
+
+  abyHeader[2] = 0x27;        /* magic cookie */
   abyHeader[3] = 0x0a;
-  
-  i32 = psSHP->nFileSize/2;				/* file size */
+
+  i32 = psSHP->nFileSize/2;       /* file size */
   ByteCopy( &i32, abyHeader+24, 4 );
   if( !bBigEndian ) SwapWord( 4, abyHeader+24 );
-    
-  i32 = 1000;						/* version */
+
+  i32 = 1000;           /* version */
   ByteCopy( &i32, abyHeader+28, 4 );
   if( bBigEndian ) SwapWord( 4, abyHeader+28 );
-    
-  i32 = psSHP->nShapeType;				/* shape type */
+
+  i32 = psSHP->nShapeType;        /* shape type */
   ByteCopy( &i32, abyHeader+32, 4 );
   if( bBigEndian ) SwapWord( 4, abyHeader+32 );
-    
-  dValue = psSHP->adBoundsMin[0];			/* set bounds */
+
+  dValue = psSHP->adBoundsMin[0];     /* set bounds */
   ByteCopy( &dValue, abyHeader+36, 8 );
   if( bBigEndian ) SwapWord( 8, abyHeader+36 );
-  
+
   dValue = psSHP->adBoundsMin[1];
   ByteCopy( &dValue, abyHeader+44, 8 );
   if( bBigEndian ) SwapWord( 8, abyHeader+44 );
-  
+
   dValue = psSHP->adBoundsMax[0];
   ByteCopy( &dValue, abyHeader+52, 8 );
   if( bBigEndian ) SwapWord( 8, abyHeader+52 );
-  
+
   dValue = psSHP->adBoundsMax[1];
   ByteCopy( &dValue, abyHeader+60, 8 );
   if( bBigEndian ) SwapWord( 8, abyHeader+60 );
 
-  dValue = psSHP->adBoundsMin[2];			/* z */
+  dValue = psSHP->adBoundsMin[2];     /* z */
   ByteCopy( &dValue, abyHeader+68, 8 );
   if( bBigEndian ) SwapWord( 8, abyHeader+68 );
 
@@ -140,8 +140,8 @@ static void writeHeader( SHPHandle psSHP )
   ByteCopy( &dValue, abyHeader+76, 8 );
   if( bBigEndian ) SwapWord( 8, abyHeader+76 );
 
-  
-  dValue = psSHP->adBoundsMin[3];			/* m */
+
+  dValue = psSHP->adBoundsMin[3];     /* m */
   ByteCopy( &dValue, abyHeader+84, 8 );
   if( bBigEndian ) SwapWord( 8, abyHeader+84 );
 
@@ -154,22 +154,22 @@ static void writeHeader( SHPHandle psSHP )
   /* -------------------------------------------------------------------- */
   fseek( psSHP->fpSHP, 0, 0 );
   fwrite( abyHeader, 100, 1, psSHP->fpSHP );
-  
+
   /* -------------------------------------------------------------------- */
   /*      Prepare, and write .shx file header.                            */
   /* -------------------------------------------------------------------- */
   i32 = (psSHP->nRecords * 2 * sizeof(ms_int32) + 100)/2;   /* file size */
   ByteCopy( &i32, abyHeader+24, 4 );
   if( !bBigEndian ) SwapWord( 4, abyHeader+24 );
-  
+
   fseek( psSHP->fpSHX, 0, 0 );
   fwrite( abyHeader, 100, 1, psSHP->fpSHX );
-  
+
   /* -------------------------------------------------------------------- */
   /*      Write out the .shx contents.                                    */
   /* -------------------------------------------------------------------- */
   panSHX = (ms_int32 *) msSmallMalloc(sizeof(ms_int32) * 2 * psSHP->nRecords);
-  
+
   for( i = 0; i < psSHP->nRecords; i++ ) {
     panSHX[i*2  ] = psSHP->panRecOffset[i]/2;
     panSHX[i*2+1] = psSHP->panRecSize[i]/2;
@@ -178,9 +178,9 @@ static void writeHeader( SHPHandle psSHP )
       *(panSHX+i*2+1) = SWAP_FOUR_BYTES(*(panSHX+i*2+1));
     }
   }
-  
+
   fwrite( panSHX, sizeof(ms_int32) * 2, psSHP->nRecords, psSHP->fpSHX );
-  
+
   free( panSHX );
 }
 
@@ -189,14 +189,14 @@ static void writeHeader( SHPHandle psSHP )
 /*                                                                      */
 /*      Open the .shp and .shx files based on the basename of the       */
 /*      files or either file name.                                      */
-/************************************************************************/   
+/************************************************************************/
 SHPHandle msSHPOpen( const char * pszLayer, const char * pszAccess )
 {
   char *pszFullname, *pszBasename;
-  SHPHandle	psSHP;
-  
-  uchar	*pabyBuf;
-  int	i;
+  SHPHandle psSHP;
+
+  uchar *pabyBuf;
+  int i;
   double dValue;
 
   /* -------------------------------------------------------------------- */
@@ -208,21 +208,21 @@ SHPHandle msSHPOpen( const char * pszLayer, const char * pszAccess )
     pszAccess = "r+b";
   else
     pszAccess = "rb";
-  
+
   /* -------------------------------------------------------------------- */
-  /*	Establish the byte order on this machine.			    */
+  /*  Establish the byte order on this machine.         */
   /* -------------------------------------------------------------------- */
   i = 1;
   if( *((uchar *) &i) == 1 )
     bBigEndian = MS_FALSE;
   else
     bBigEndian = MS_TRUE;
-  
+
   /* -------------------------------------------------------------------- */
-  /*	Initialize the info structure.					    */
+  /*  Initialize the info structure.              */
   /* -------------------------------------------------------------------- */
   psSHP = (SHPHandle) msSmallMalloc(sizeof(SHPInfo));
-  
+
   psSHP->bUpdated = MS_FALSE;
 
   psSHP->pabyRec = NULL;
@@ -230,21 +230,21 @@ SHPHandle msSHPOpen( const char * pszLayer, const char * pszAccess )
   psSHP->nBufSize = psSHP->nPartMax = 0;
 
   /* -------------------------------------------------------------------- */
-  /*	Compute the base (layer) name.  If there is any extension	    */
-  /*	on the passed in filename we will strip it off.			    */
+  /*  Compute the base (layer) name.  If there is any extension     */
+  /*  on the passed in filename we will strip it off.         */
   /* -------------------------------------------------------------------- */
   pszBasename = (char *) msSmallMalloc(strlen(pszLayer)+5);
   strcpy( pszBasename, pszLayer );
-  for( i = strlen(pszBasename)-1; 
+  for( i = strlen(pszBasename)-1;
        i > 0 && pszBasename[i] != '.' && pszBasename[i] != '/' && pszBasename[i] != '\\';
        i-- ) {}
-  
+
   if( pszBasename[i] == '.' )
     pszBasename[i] = '\0';
-  
+
   /* -------------------------------------------------------------------- */
-  /*	Open the .shp and .shx files.  Note that files pulled from	    */
-  /*	a PC to Unix with upper case filenames won't work!		    */
+  /*  Open the .shp and .shx files.  Note that files pulled from      */
+  /*  a PC to Unix with upper case filenames won't work!        */
   /* -------------------------------------------------------------------- */
   pszFullname = (char *) msSmallMalloc(strlen(pszBasename) + 5);
   sprintf( pszFullname, "%s.shp", pszBasename );
@@ -264,40 +264,39 @@ SHPHandle msSHPOpen( const char * pszLayer, const char * pszAccess )
     msFree(psSHP);
     return( NULL );
   }
-  
+
   free( pszFullname );
-  free( pszBasename ); 
+  free( pszBasename );
 
   /* -------------------------------------------------------------------- */
-  /*   Read the file size from the SHP file.				    */
+  /*   Read the file size from the SHP file.            */
   /* -------------------------------------------------------------------- */
   pabyBuf = (uchar *) msSmallMalloc(100);
   fread( pabyBuf, 100, 1, psSHP->fpSHP );
-  
+
   psSHP->nFileSize = (pabyBuf[24] * 256 * 256 * 256
-		      + pabyBuf[25] * 256 * 256
-		      + pabyBuf[26] * 256
-		      + pabyBuf[27]) * 2;
-  
+                      + pabyBuf[25] * 256 * 256
+                      + pabyBuf[26] * 256
+                      + pabyBuf[27]) * 2;
+
   /* -------------------------------------------------------------------- */
   /*  Read SHX file Header info                                           */
   /* -------------------------------------------------------------------- */
   fread( pabyBuf, 100, 1, psSHP->fpSHX );
-  
+
   if( pabyBuf[0] != 0 || pabyBuf[1] != 0 || pabyBuf[2] != 0x27  || (pabyBuf[3] != 0x0a && pabyBuf[3] != 0x0d) ) {
     fclose( psSHP->fpSHP );
     fclose( psSHP->fpSHX );
     free( psSHP );
-      
+
     return( NULL );
   }
 
   psSHP->nRecords = pabyBuf[27] + pabyBuf[26] * 256 + pabyBuf[25] * 256 * 256 + pabyBuf[24] * 256 * 256 * 256;
   if (psSHP->nRecords != 0)
-      psSHP->nRecords = (psSHP->nRecords*2 - 100) / 8;
+    psSHP->nRecords = (psSHP->nRecords*2 - 100) / 8;
 
-  if( psSHP->nRecords < 0 || psSHP->nRecords > 256000000 )
-  {
+  if( psSHP->nRecords < 0 || psSHP->nRecords > 256000000 ) {
     msSetError(MS_SHPERR, "Corrupted .shp file : nRecords = %d.", "msSHPOpen()",
                psSHP->nRecords);
     fclose( psSHP->fpSHP );
@@ -307,24 +306,24 @@ SHPHandle msSHPOpen( const char * pszLayer, const char * pszAccess )
   }
 
   psSHP->nShapeType = pabyBuf[32];
-  
+
   if( bBigEndian ) SwapWord( 8, pabyBuf+36 );
   memcpy( &dValue, pabyBuf+36, 8 );
   psSHP->adBoundsMin[0] = dValue;
-  
+
   if( bBigEndian ) SwapWord( 8, pabyBuf+44 );
   memcpy( &dValue, pabyBuf+44, 8 );
   psSHP->adBoundsMin[1] = dValue;
-  
+
   if( bBigEndian ) SwapWord( 8, pabyBuf+52 );
   memcpy( &dValue, pabyBuf+52, 8 );
   psSHP->adBoundsMax[0] = dValue;
-  
+
   if( bBigEndian ) SwapWord( 8, pabyBuf+60 );
   memcpy( &dValue, pabyBuf+60, 8 );
   psSHP->adBoundsMax[1] = dValue;
-  
-  if( bBigEndian ) SwapWord( 8, pabyBuf+68 );		/* z */
+
+  if( bBigEndian ) SwapWord( 8, pabyBuf+68 );   /* z */
   memcpy( &dValue, pabyBuf+68, 8 );
   psSHP->adBoundsMin[2] = dValue;
 
@@ -332,7 +331,7 @@ SHPHandle msSHPOpen( const char * pszLayer, const char * pszAccess )
   memcpy( &dValue, pabyBuf+76, 8 );
   psSHP->adBoundsMax[2] = dValue;
 
-  if( bBigEndian ) SwapWord( 8, pabyBuf+84 );		/* m */
+  if( bBigEndian ) SwapWord( 8, pabyBuf+84 );   /* m */
   memcpy( &dValue, pabyBuf+84, 8 );
   psSHP->adBoundsMin[3] = dValue;
 
@@ -340,13 +339,13 @@ SHPHandle msSHPOpen( const char * pszLayer, const char * pszAccess )
   memcpy( &dValue, pabyBuf+92, 8 );
   psSHP->adBoundsMax[3] = dValue;
   free( pabyBuf );
-  
+
   /* -------------------------------------------------------------------- */
-  /*	Read the .shx file to get the offsets to each record in 	    */
-  /*	the .shp file.							    */
+  /*  Read the .shx file to get the offsets to each record in       */
+  /*  the .shp file.                  */
   /* -------------------------------------------------------------------- */
   psSHP->nMaxRecords = psSHP->nRecords;
-  
+
   /* Our in-memory cache of offset information */
   psSHP->panRecOffset = (int *) malloc(sizeof(int) * psSHP->nMaxRecords );
   /* Our in-memory cache of size information */
@@ -354,13 +353,12 @@ SHPHandle msSHPOpen( const char * pszLayer, const char * pszAccess )
   /* The completeness information for our in-memory cache */
   psSHP->panRecLoaded = msAllocBitArray( 1 + (psSHP->nMaxRecords / SHX_BUFFER_PAGE) ) ;
   /* Is our in-memory cache completely populated? */
-  psSHP->panRecAllLoaded = 0; 
-  
-  /* malloc failed? clean up and shut down */  
+  psSHP->panRecAllLoaded = 0;
+
+  /* malloc failed? clean up and shut down */
   if (psSHP->panRecOffset == NULL ||
       psSHP->panRecSize == NULL ||
-      psSHP->panRecLoaded == NULL)
-  {
+      psSHP->panRecLoaded == NULL) {
     free(psSHP->panRecOffset);
     free(psSHP->panRecSize);
     free(psSHP->panRecLoaded);
@@ -371,37 +369,37 @@ SHPHandle msSHPOpen( const char * pszLayer, const char * pszAccess )
     return( NULL );
   }
 
-  
+
   return( psSHP );
 }
 
 /************************************************************************/
 /*                              msSHPClose()                            */
-/*								       	*/
-/*	Close the .shp and .shx files.					*/
+/*                        */
+/*  Close the .shp and .shx files.          */
 /************************************************************************/
 void msSHPClose(SHPHandle psSHP )
 {
   /* -------------------------------------------------------------------- */
-  /*	Update the header if we have modified anything.		    	  */
+  /*  Update the header if we have modified anything.           */
   /* -------------------------------------------------------------------- */
   if( psSHP->bUpdated )
     writeHeader( psSHP );
-  
+
   /* -------------------------------------------------------------------- */
   /*      Free all resources, and close files.                            */
   /* -------------------------------------------------------------------- */
   free( psSHP->panRecOffset );
   free( psSHP->panRecSize );
   free( psSHP->panRecLoaded );
-  
-  
+
+
   if(psSHP->pabyRec) free(psSHP->pabyRec);
   if(psSHP->panParts) free(psSHP->panParts);
 
   fclose( psSHP->fpSHX );
   fclose( psSHP->fpSHP );
-  
+
   free( psSHP );
 }
 
@@ -414,7 +412,7 @@ void msSHPGetInfo(SHPHandle psSHP, int * pnEntities, int * pnShapeType )
 {
   if( pnEntities )
     *pnEntities = psSHP->nRecords;
-  
+
   if( pnShapeType )
     *pnShapeType = psSHP->nShapeType;
 }
@@ -428,29 +426,28 @@ void msSHPGetInfo(SHPHandle psSHP, int * pnEntities, int * pnShapeType )
 SHPHandle msSHPCreate( const char * pszLayer, int nShapeType )
 {
   char *pszBasename, *pszFullname;
-  int	i;
+  int i;
   FILE *fpSHP, *fpSHX;
   uchar abyHeader[100];
   ms_int32 i32;
   double dValue;
 
 #ifndef USE_POINT_Z_M
-  if( nShapeType == SHP_POLYGONZ 
+  if( nShapeType == SHP_POLYGONZ
       || nShapeType == SHP_POLYGONM
       || nShapeType == SHP_ARCZ
       || nShapeType == SHP_ARCM
       || nShapeType == SHP_POINTZ
       || nShapeType == SHP_POINTM
       || nShapeType == SHP_MULTIPOINTZ
-      || nShapeType == SHP_MULTIPOINTM )
-  {
-      msSetError( MS_SHPERR, 
-                  "Attempt to create M/Z shapefile but without having enabled Z/M support.", 
-                  "msSHPCreate()" );
-      return NULL;
+      || nShapeType == SHP_MULTIPOINTM ) {
+    msSetError( MS_SHPERR,
+                "Attempt to create M/Z shapefile but without having enabled Z/M support.",
+                "msSHPCreate()" );
+    return NULL;
   }
 #endif
-      
+
   /* -------------------------------------------------------------------- */
   /*      Establish the byte order on this system.                        */
   /* -------------------------------------------------------------------- */
@@ -459,20 +456,20 @@ SHPHandle msSHPCreate( const char * pszLayer, int nShapeType )
     bBigEndian = MS_FALSE;
   else
     bBigEndian = MS_TRUE;
-  
+
   /* -------------------------------------------------------------------- */
-  /*	Compute the base (layer) name.  If there is any extension  	    */
-  /*	on the passed in filename we will strip it off.			    */
+  /*  Compute the base (layer) name.  If there is any extension       */
+  /*  on the passed in filename we will strip it off.         */
   /* -------------------------------------------------------------------- */
   pszBasename = (char *) msSmallMalloc(strlen(pszLayer)+5);
   strcpy( pszBasename, pszLayer );
-  for( i = strlen(pszBasename)-1; 
+  for( i = strlen(pszBasename)-1;
        i > 0 && pszBasename[i] != '.' && pszBasename[i] != '/' && pszBasename[i] != '\\';
        i-- ) {}
-  
+
   if( pszBasename[i] == '.' )
     pszBasename[i] = '\0';
-  
+
   /* -------------------------------------------------------------------- */
   /*      Open the two files so we can write their headers.               */
   /* -------------------------------------------------------------------- */
@@ -481,55 +478,55 @@ SHPHandle msSHPCreate( const char * pszLayer, int nShapeType )
   fpSHP = fopen(pszFullname, "wb" );
   if( fpSHP == NULL )
     return( NULL );
-  
+
   sprintf( pszFullname, "%s.shx", pszBasename );
   fpSHX = fopen(pszFullname, "wb" );
   if( fpSHX == NULL )
     return( NULL );
 
   free( pszFullname );
-  
+
   /* -------------------------------------------------------------------- */
   /*      Prepare header block for .shp file.                             */
   /* -------------------------------------------------------------------- */
   for( i = 0; i < 100; i++ )
     abyHeader[i] = 0;
-  
-  abyHeader[2] = 0x27;				/* magic cookie */
+
+  abyHeader[2] = 0x27;        /* magic cookie */
   abyHeader[3] = 0x0a;
-  
-  i32 = 50;						/* file size */
+
+  i32 = 50;           /* file size */
   ByteCopy( &i32, abyHeader+24, 4 );
   if( !bBigEndian ) SwapWord( 4, abyHeader+24 );
 
-  i32 = 1000;						/* version */
+  i32 = 1000;           /* version */
   ByteCopy( &i32, abyHeader+28, 4 );
   if( bBigEndian ) SwapWord( 4, abyHeader+28 );
-  
-  i32 = nShapeType;					/* shape type */
+
+  i32 = nShapeType;         /* shape type */
   ByteCopy( &i32, abyHeader+32, 4 );
   if( bBigEndian ) SwapWord( 4, abyHeader+32 );
 
-  dValue = 0.0;					/* set bounds */
+  dValue = 0.0;         /* set bounds */
   ByteCopy( &dValue, abyHeader+36, 8 );
   ByteCopy( &dValue, abyHeader+44, 8 );
   ByteCopy( &dValue, abyHeader+52, 8 );
   ByteCopy( &dValue, abyHeader+60, 8 );
-  
+
   /* -------------------------------------------------------------------- */
   /*      Write .shp file header.                                         */
   /* -------------------------------------------------------------------- */
   fwrite( abyHeader, 100, 1, fpSHP );
-  
+
   /* -------------------------------------------------------------------- */
   /*      Prepare, and write .shx file header.                            */
   /* -------------------------------------------------------------------- */
-  i32 = 50;						/* file size */
+  i32 = 50;           /* file size */
   ByteCopy( &i32, abyHeader+24, 4 );
   if( !bBigEndian ) SwapWord( 4, abyHeader+24 );
-  
+
   fwrite( abyHeader, 100, 1, fpSHX );
-  
+
   /* -------------------------------------------------------------------- */
   /*      Close the files, and then open them as regular existing files.  */
   /* -------------------------------------------------------------------- */
@@ -548,14 +545,14 @@ SHPHandle msSHPCreate( const char * pszLayer, int nShapeType )
 static void writeBounds( uchar * pabyRec, shapeObj *shape, int nVCount )
 {
   double dXMin, dXMax, dYMin, dYMax;
-  int	i, j;
-  
+  int i, j;
+
   if( nVCount == 0 ) {
     dXMin = dYMin = dXMax = dYMax = 0.0;
   } else {
     dXMin = dXMax = shape->line[0].point[0].x;
     dYMin = dYMax = shape->line[0].point[0].y;
-    
+
     for( i=0; i<shape->numlines; i++ ) {
       for( j=0; j<shape->line[i].numpoints; j++ ) {
         dXMin = MS_MIN(dXMin, shape->line[i].point[j].x);
@@ -565,14 +562,14 @@ static void writeBounds( uchar * pabyRec, shapeObj *shape, int nVCount )
       }
     }
   }
-  
-  if( bBigEndian ) { 
+
+  if( bBigEndian ) {
     SwapWord( 8, &dXMin );
     SwapWord( 8, &dYMin );
     SwapWord( 8, &dXMax );
     SwapWord( 8, &dYMax );
   }
-  
+
   ByteCopy( &dXMin, pabyRec +  0, 8 );
   ByteCopy( &dYMin, pabyRec +  8, 8 );
   ByteCopy( &dXMax, pabyRec + 16, 8 );
@@ -582,9 +579,9 @@ static void writeBounds( uchar * pabyRec, shapeObj *shape, int nVCount )
 int msSHPWritePoint(SHPHandle psSHP, pointObj *point )
 {
   int nRecordOffset, nRecordSize=0;
-  uchar	*pabyRec;
-  ms_int32	i32, nPoints, nParts;
-  
+  uchar *pabyRec;
+  ms_int32  i32, nPoints, nParts;
+
   if( psSHP->nShapeType != SHP_POINT) return(-1);
 
   psSHP->bUpdated = MS_TRUE;
@@ -598,7 +595,7 @@ int msSHPWritePoint(SHPHandle psSHP, pointObj *point )
   psSHP->nRecords++;
   if( psSHP->nRecords > psSHP->nMaxRecords ) {
     psSHP->nMaxRecords = (int) (psSHP->nMaxRecords * 1.3 + 100);
-    
+
     psSHP->panRecOffset = (int *) SfRealloc(psSHP->panRecOffset,sizeof(int) * psSHP->nMaxRecords );
     psSHP->panRecSize = (int *) SfRealloc(psSHP->panRecSize,sizeof(int) * psSHP->nMaxRecords );
   }
@@ -608,55 +605,55 @@ int msSHPWritePoint(SHPHandle psSHP, pointObj *point )
   /* -------------------------------------------------------------------- */
   nPoints = 1;
   nParts = 1;
-  
+
   /* -------------------------------------------------------------------- */
   /*      Initialize record.                                              */
   /* -------------------------------------------------------------------- */
   psSHP->panRecOffset[psSHP->nRecords-1] = nRecordOffset = psSHP->nFileSize;
-  
+
   pabyRec = (uchar *) msSmallMalloc(nPoints * 2 * sizeof(double) + nParts * 4 + 128);
-  
+
   /* -------------------------------------------------------------------- */
   /*      Write vertices for a point.                                     */
   /* -------------------------------------------------------------------- */
   ByteCopy( &(point->x), pabyRec + 12, 8 );
   ByteCopy( &(point->y), pabyRec + 20, 8 );
-  
-    
+
+
   if( bBigEndian ) {
     SwapWord( 8, pabyRec + 12 );
     SwapWord( 8, pabyRec + 20 );
   }
-    
+
   nRecordSize = 20;
 
   /* -------------------------------------------------------------------- */
   /*      Set the shape type, record number, and record size.             */
   /* -------------------------------------------------------------------- */
-  i32 = psSHP->nRecords-1+1;					/* record # */
+  i32 = psSHP->nRecords-1+1;          /* record # */
   if( !bBigEndian ) i32 = SWAP_FOUR_BYTES(i32);
   ByteCopy( &i32, pabyRec, 4 );
-  
-  i32 = nRecordSize/2;				/* record size */
+
+  i32 = nRecordSize/2;        /* record size */
   if( !bBigEndian ) i32 = SWAP_FOUR_BYTES(i32);
   ByteCopy( &i32, pabyRec + 4, 4 );
-  
-  i32 = psSHP->nShapeType;				/* shape type */
+
+  i32 = psSHP->nShapeType;        /* shape type */
   if( bBigEndian ) i32 = SWAP_FOUR_BYTES(i32);
   ByteCopy( &i32, pabyRec + 8, 4 );
-  
+
   /* -------------------------------------------------------------------- */
   /*      Write out record.                                               */
   /* -------------------------------------------------------------------- */
   fseek( psSHP->fpSHP, nRecordOffset, 0 );
   fwrite( pabyRec, nRecordSize+8, 1, psSHP->fpSHP );
   free( pabyRec );
-  
+
   psSHP->panRecSize[psSHP->nRecords-1] = nRecordSize;
   psSHP->nFileSize += nRecordSize + 8;
-  
+
   /* -------------------------------------------------------------------- */
-  /*	Expand file wide bounds based on this shape.			  */
+  /*  Expand file wide bounds based on this shape.        */
   /* -------------------------------------------------------------------- */
   if( psSHP->nRecords == 1 ) {
     psSHP->adBoundsMin[0] = psSHP->adBoundsMax[0] = point->x;
@@ -667,75 +664,75 @@ int msSHPWritePoint(SHPHandle psSHP, pointObj *point )
     psSHP->adBoundsMax[0] = MS_MAX(psSHP->adBoundsMax[0], point->x);
     psSHP->adBoundsMax[1] = MS_MAX(psSHP->adBoundsMax[1], point->y);
   }
-  
+
   return( psSHP->nRecords - 1 );
 }
 
 int msSHPWriteShape(SHPHandle psSHP, shapeObj *shape )
 {
   int nRecordOffset, i, j, k, nRecordSize=0;
-  uchar	*pabyRec;
+  uchar *pabyRec;
   int nShapeType;
 
-  ms_int32	i32, nPoints, nParts;
+  ms_int32  i32, nPoints, nParts;
 #ifdef USE_POINT_Z_M
   double dfMMin, dfMMax = 0;
 #endif
   psSHP->bUpdated = MS_TRUE;
-  
+
   /* Fill the SHX buffer if it is not already full. */
   if( ! psSHP->panRecAllLoaded ) msSHXLoadAll( psSHP );
-  
+
   /* -------------------------------------------------------------------- */
   /*      Add the new entity to the in memory index.                      */
   /* -------------------------------------------------------------------- */
   psSHP->nRecords++;
   if( psSHP->nRecords > psSHP->nMaxRecords ) {
     psSHP->nMaxRecords = (int) (psSHP->nMaxRecords * 1.3 + 100);
-    
+
     psSHP->panRecOffset = (int *) SfRealloc(psSHP->panRecOffset,sizeof(int) * psSHP->nMaxRecords );
     psSHP->panRecSize = (int *) SfRealloc(psSHP->panRecSize,sizeof(int) * psSHP->nMaxRecords );
   }
-  
+
   /* -------------------------------------------------------------------- */
   /*      Compute a few things.                                           */
   /* -------------------------------------------------------------------- */
   nPoints = 0;
   for(i=0; i<shape->numlines; i++)
     nPoints += shape->line[i].numpoints;
-  
+
   nParts = shape->numlines;
-  
+
   /* -------------------------------------------------------------------- */
   /*      Initialize record.                                              */
   /* -------------------------------------------------------------------- */
   psSHP->panRecOffset[psSHP->nRecords-1] = nRecordOffset = psSHP->nFileSize;
-  
+
   pabyRec = (uchar *) msSmallMalloc(nPoints * 4 * sizeof(double) + nParts * 8 + 128);
   nShapeType = psSHP->nShapeType;
-  
+
   if (shape->type == MS_SHAPE_NULL) {
-      nShapeType = 0;
-      nRecordSize = 12;
+    nShapeType = 0;
+    nRecordSize = 12;
   }
   /* -------------------------------------------------------------------- */
-  /*  Write vertices for a Polygon or Arc.				    */
+  /*  Write vertices for a Polygon or Arc.            */
   /* -------------------------------------------------------------------- */
   else if(psSHP->nShapeType == SHP_POLYGON || psSHP->nShapeType == SHP_ARC ||
-     psSHP->nShapeType == SHP_POLYGONM || psSHP->nShapeType == SHP_ARCM ||
-     psSHP->nShapeType == SHP_ARCZ ||  psSHP->nShapeType == SHP_POLYGONZ) {
+          psSHP->nShapeType == SHP_POLYGONM || psSHP->nShapeType == SHP_ARCM ||
+          psSHP->nShapeType == SHP_ARCZ ||  psSHP->nShapeType == SHP_POLYGONZ) {
     ms_int32 t_nParts, t_nPoints, partSize;
-    
+
     t_nParts = nParts;
     t_nPoints = nPoints;
-    
+
     writeBounds( pabyRec + 12, shape, t_nPoints );
-    
-    if( bBigEndian ) { 
+
+    if( bBigEndian ) {
       nPoints = SWAP_FOUR_BYTES(nPoints);
       nParts = SWAP_FOUR_BYTES(nParts);
     }
-    
+
     ByteCopy( &nPoints, pabyRec + 40 + 8, 4 );
     ByteCopy( &nParts, pabyRec + 36 + 8, 4 );
 
@@ -749,13 +746,13 @@ int msSHPWriteShape(SHPHandle psSHP, shapeObj *shape )
       if( bBigEndian ) SwapWord( 4, pabyRec + 44 + 8 + 4*i);
 
     }
-    
+
     k = 0; /* overall point counter */
     for( i = 0; i < shape->numlines; i++ ) {
       for( j = 0; j < shape->line[i].numpoints; j++ ) {
         ByteCopy( &(shape->line[i].point[j].x), pabyRec + 44 + 4*t_nParts + 8 + k * 16, 8 );
         ByteCopy( &(shape->line[i].point[j].y), pabyRec + 44 + 4*t_nParts + 8 + k * 16 + 8, 8 );
-	
+
         if( bBigEndian ) {
           SwapWord( 8, pabyRec + 44+4*t_nParts+8+k*16 );
           SwapWord( 8, pabyRec + 44+4*t_nParts+8+k*16+8 );
@@ -783,7 +780,7 @@ int msSHPWriteShape(SHPHandle psSHP, shapeObj *shape )
       ByteCopy( &(dfMMax), pabyRec + nRecordSize, 8 );
       if( bBigEndian ) SwapWord( 8, pabyRec + nRecordSize );
       nRecordSize += 8;
-            
+
       for( i = 0; i < shape->numlines; i++ ) {
         for( j = 0; j < shape->line[i].numpoints; j++ ) {
           ByteCopy( &(shape->line[i].point[j].m), pabyRec + nRecordSize, 8 );
@@ -800,7 +797,7 @@ int msSHPWriteShape(SHPHandle psSHP, shapeObj *shape )
         || psSHP->nShapeType == SHP_POLYGONM || psSHP->nShapeType == SHP_ARCM) {
       dfMMin = shape->line[0].point[0].z;
       dfMMax = shape->line[shape->numlines-1].point[shape->line[shape->numlines-1].numpoints-1].z;
-            
+
       nRecordSize = 44 + 4*t_nParts + 8 + (t_nPoints* 16);
 
       ByteCopy( &(dfMMin), pabyRec + nRecordSize, 8 );
@@ -810,7 +807,7 @@ int msSHPWriteShape(SHPHandle psSHP, shapeObj *shape )
       ByteCopy( &(dfMMax), pabyRec + nRecordSize, 8 );
       if( bBigEndian ) SwapWord( 8, pabyRec + nRecordSize );
       nRecordSize += 8;
-            
+
       for( i = 0; i < shape->numlines; i++ ) {
         for( j = 0; j < shape->line[i].numpoints; j++ ) {
           ByteCopy( &(shape->line[i].point[j].z), pabyRec + nRecordSize, 8 );
@@ -821,27 +818,27 @@ int msSHPWriteShape(SHPHandle psSHP, shapeObj *shape )
     }
 #endif /* def USE_POINT_Z_M */
   }
-  
+
   /* -------------------------------------------------------------------- */
-  /*  Write vertices for a MultiPoint.				                            */
+  /*  Write vertices for a MultiPoint.                                    */
   /* -------------------------------------------------------------------- */
   else if( psSHP->nShapeType == SHP_MULTIPOINT ||
            psSHP->nShapeType == SHP_MULTIPOINTM ||
            psSHP->nShapeType == SHP_MULTIPOINTZ) {
     ms_int32 t_nPoints;
-    
+
     t_nPoints = nPoints;
-    
+
     writeBounds( pabyRec + 12, shape, nPoints );
-    
+
     if( bBigEndian ) nPoints = SWAP_FOUR_BYTES(nPoints);
     ByteCopy( &nPoints, pabyRec + 44, 4 );
-    
+
     for( i = 0; i < shape->line[0].numpoints; i++ ) {
       ByteCopy( &(shape->line[0].point[i].x), pabyRec + 48 + i*16, 8 );
       ByteCopy( &(shape->line[0].point[i].y), pabyRec + 48 + i*16 + 8, 8 );
-      
-      if( bBigEndian ) { 
+
+      if( bBigEndian ) {
         SwapWord( 8, pabyRec + 48 + i*16 );
         SwapWord( 8, pabyRec + 48 + i*16 + 8 );
       }
@@ -861,7 +858,7 @@ int msSHPWriteShape(SHPHandle psSHP, shapeObj *shape )
       ByteCopy( &(dfMMax), pabyRec + nRecordSize, 8 );
       if( bBigEndian ) SwapWord( 8, pabyRec + nRecordSize );
       nRecordSize += 8;
-        
+
       for( i = 0; i < shape->line[0].numpoints; i++ ) {
         ByteCopy( &(shape->line[0].point[i].m), pabyRec + nRecordSize, 8 );
         if( bBigEndian ) SwapWord( 8, pabyRec + nRecordSize );
@@ -880,7 +877,7 @@ int msSHPWriteShape(SHPHandle psSHP, shapeObj *shape )
       ByteCopy( &(dfMMax), pabyRec + nRecordSize, 8 );
       if( bBigEndian ) SwapWord( 8, pabyRec + nRecordSize );
       nRecordSize += 8;
-        
+
       for( i = 0; i < shape->line[0].numpoints; i++ ) {
         ByteCopy( &(shape->line[0].point[i].z), pabyRec + nRecordSize, 8 );
         if( bBigEndian ) SwapWord( 8, pabyRec + nRecordSize );
@@ -889,7 +886,7 @@ int msSHPWriteShape(SHPHandle psSHP, shapeObj *shape )
     }
 #endif /* USE_POINT_Z_M */
   }
-  
+
   /* -------------------------------------------------------------------- */
   /*      Write vertices for a point.                                     */
   /* -------------------------------------------------------------------- */
@@ -897,12 +894,12 @@ int msSHPWriteShape(SHPHandle psSHP, shapeObj *shape )
            psSHP->nShapeType == SHP_POINTZ) {
     ByteCopy( &(shape->line[0].point[0].x), pabyRec + 12, 8 );
     ByteCopy( &(shape->line[0].point[0].y), pabyRec + 20, 8 );
-    
+
     if( bBigEndian ) {
       SwapWord( 8, pabyRec + 12 );
       SwapWord( 8, pabyRec + 20 );
     }
-    
+
     nRecordSize = 20;
 
 #ifdef USE_POINT_Z_M
@@ -919,34 +916,34 @@ int msSHPWriteShape(SHPHandle psSHP, shapeObj *shape )
     }
 #endif /* USE_POINT_Z_M */
   }
-  
+
   /* -------------------------------------------------------------------- */
   /*      Set the shape type, record number, and record size.             */
   /* -------------------------------------------------------------------- */
-  i32 = psSHP->nRecords-1+1;					/* record # */
+  i32 = psSHP->nRecords-1+1;          /* record # */
   if( !bBigEndian ) i32 = SWAP_FOUR_BYTES(i32);
   ByteCopy( &i32, pabyRec, 4 );
-  
-  i32 = nRecordSize/2;				/* record size */
+
+  i32 = nRecordSize/2;        /* record size */
   if( !bBigEndian ) i32 = SWAP_FOUR_BYTES(i32);
   ByteCopy( &i32, pabyRec + 4, 4 );
-  
+
   i32 = nShapeType;     /* shape type */
   if( bBigEndian ) i32 = SWAP_FOUR_BYTES(i32);
   ByteCopy( &i32, pabyRec + 8, 4 );
-  
+
   /* -------------------------------------------------------------------- */
   /*      Write out record.                                               */
   /* -------------------------------------------------------------------- */
   fseek( psSHP->fpSHP, nRecordOffset, 0 );
   fwrite( pabyRec, nRecordSize+8, 1, psSHP->fpSHP );
   free( pabyRec );
-  
+
   psSHP->panRecSize[psSHP->nRecords-1] = nRecordSize;
   psSHP->nFileSize += nRecordSize + 8;
-  
+
   /* -------------------------------------------------------------------- */
-  /*	Expand file wide bounds based on this shape.			  */
+  /*  Expand file wide bounds based on this shape.        */
   /* -------------------------------------------------------------------- */
   if( psSHP->nRecords == 1 ) {
     psSHP->adBoundsMin[0] = psSHP->adBoundsMax[0] = shape->line[0].point[0].x;
@@ -956,7 +953,7 @@ int msSHPWriteShape(SHPHandle psSHP, shapeObj *shape )
     psSHP->adBoundsMin[3] = psSHP->adBoundsMax[3] = shape->line[0].point[0].m;
 #endif
   }
-  
+
   for( i=0; i<shape->numlines; i++ ) {
     for( j=0; j<shape->line[i].numpoints; j++ ) {
       psSHP->adBoundsMin[0] = MS_MIN(psSHP->adBoundsMin[0], shape->line[i].point[j].x);
@@ -973,7 +970,7 @@ int msSHPWriteShape(SHPHandle psSHP, shapeObj *shape )
 #endif
     }
   }
-  
+
   return( psSHP->nRecords - 1 );
 }
 
@@ -989,19 +986,17 @@ static int msSHPReadAllocateBuffer( SHPHandle psSHP, int hEntity, const char* ps
   /* -------------------------------------------------------------------- */
   if( nEntitySize > psSHP->nBufSize ) {
     psSHP->pabyRec = (uchar *) SfRealloc(psSHP->pabyRec,nEntitySize);
-    if (psSHP->pabyRec == NULL)
-    {
-        /* Reallocate previous successfull size for following features */
-        psSHP->pabyRec = msSmallMalloc(psSHP->nBufSize);
+    if (psSHP->pabyRec == NULL) {
+      /* Reallocate previous successfull size for following features */
+      psSHP->pabyRec = msSmallMalloc(psSHP->nBufSize);
 
-        msSetError(MS_MEMERR, "Out of memory. Cannot allocate %d bytes. Probably broken shapefile at feature %d",
-                   pszCallingFunction, nEntitySize, hEntity);
-        return(MS_FAILURE);
+      msSetError(MS_MEMERR, "Out of memory. Cannot allocate %d bytes. Probably broken shapefile at feature %d",
+                 pszCallingFunction, nEntitySize, hEntity);
+      return(MS_FAILURE);
     }
     psSHP->nBufSize = nEntitySize;
   }
-  if (psSHP->pabyRec == NULL)
-  {
+  if (psSHP->pabyRec == NULL) {
     msSetError(MS_MEMERR, "Out of memory", pszCallingFunction);
     return(MS_FAILURE);
   }
@@ -1036,15 +1031,13 @@ int msSHPReadPoint( SHPHandle psSHP, int hEntity, pointObj *point )
   if( msSHXReadSize( psSHP, hEntity) == 4 ) {
     msSetError(MS_SHPERR, "NULL feature encountered.", "msSHPReadPoint()");
     return(MS_FAILURE);
-  }
-  else if ( nEntitySize < 28 ) {
+  } else if ( nEntitySize < 28 ) {
     msSetError(MS_SHPERR, "Corrupted feature encountered.  hEntity=%d, nEntitySize=%d", "msSHPReadPoint()",
                hEntity, nEntitySize);
     return(MS_FAILURE);
   }
 
-  if (msSHPReadAllocateBuffer(psSHP, hEntity, "msSHPReadPoint()") == MS_FAILURE)
-  {
+  if (msSHPReadAllocateBuffer(psSHP, hEntity, "msSHPReadPoint()") == MS_FAILURE) {
     return MS_FAILURE;
   }
 
@@ -1053,10 +1046,10 @@ int msSHPReadPoint( SHPHandle psSHP, int hEntity, pointObj *point )
   /* -------------------------------------------------------------------- */
   fseek( psSHP->fpSHP, msSHXReadOffset( psSHP, hEntity), 0 );
   fread( psSHP->pabyRec, nEntitySize, 1, psSHP->fpSHP );
-      
+
   memcpy( &(point->x), psSHP->pabyRec + 12, 8 );
   memcpy( &(point->y), psSHP->pabyRec + 20, 8 );
-      
+
   if( bBigEndian ) {
     SwapWord( 8, &(point->x));
     SwapWord( 8, &(point->y));
@@ -1066,11 +1059,11 @@ int msSHPReadPoint( SHPHandle psSHP, int hEntity, pointObj *point )
 }
 
 /*
-** msSHXLoadPage() 
+** msSHXLoadPage()
 **
 ** The SHX tells us what the byte offsets of the shapes in the SHP file are.
-** We read the SHX file in ~8K pages and store those pages in memory for 
-** successive accesses during the reading cycle (first bounds are read, 
+** We read the SHX file in ~8K pages and store those pages in memory for
+** successive accesses during the reading cycle (first bounds are read,
 ** then entire shapes). Each time we read a page, we mark it as read.
 */
 int msSHXLoadPage( SHPHandle psSHP, int shxBufferPage )
@@ -1091,21 +1084,21 @@ int msSHXLoadPage( SHPHandle psSHP, int shxBufferPage )
   /* Copy the buffer contents out into the working arrays. */
   for( i = 0; i < SHX_BUFFER_PAGE; i++ ) {
     int tmpOffset, tmpSize;
-    
+
     /* Don't write information past the end of the arrays, please. */
     if(psSHP->nRecords <= (shxBufferPage * SHX_BUFFER_PAGE + i) )
       break;
-    
+
     memcpy( &tmpOffset, (buffer + (8*i)), 4);
     memcpy( &tmpSize, (buffer + (8*i) + 4), 4);
-  
+
     /* SHX uses big endian numbers for the offsets, so we have to flip them */
     /* if we are a little endian machine. */
     if( !bBigEndian ) {
       tmpOffset = SWAP_FOUR_BYTES(tmpOffset);
       tmpSize = SWAP_FOUR_BYTES(tmpSize);
     }
-    
+
     /* SHX stores the offsets in 2 byte units, so we double them to get */
     /* an offset in bytes. */
     tmpOffset = tmpOffset * 2;
@@ -1115,22 +1108,23 @@ int msSHXLoadPage( SHPHandle psSHP, int shxBufferPage )
     psSHP->panRecOffset[shxBufferPage * SHX_BUFFER_PAGE + i] = tmpOffset;
     psSHP->panRecSize[shxBufferPage * SHX_BUFFER_PAGE + i] = tmpSize;
   }
-    
+
   msSetBit(psSHP->panRecLoaded, shxBufferPage, 1);
-  
+
   return(MS_SUCCESS);
 }
 
-int msSHXLoadAll( SHPHandle psSHP ) {
+int msSHXLoadAll( SHPHandle psSHP )
+{
 
   int i;
-  uchar	*pabyBuf;
+  uchar *pabyBuf;
 
   pabyBuf = (uchar *) msSmallMalloc(8 * psSHP->nRecords );
   fread( pabyBuf, 8, psSHP->nRecords, psSHP->fpSHX );
   for( i = 0; i < psSHP->nRecords; i++ ) {
     ms_int32 nOffset, nLength;
-    
+
     memcpy( &nOffset, pabyBuf + i * 8, 4 );
     memcpy( &nLength, pabyBuf + i * 8 + 4, 4 );
 
@@ -1138,18 +1132,19 @@ int msSHXLoadAll( SHPHandle psSHP ) {
       nOffset = SWAP_FOUR_BYTES( nOffset );
       nLength = SWAP_FOUR_BYTES( nLength );
     }
-    
-    psSHP->panRecOffset[i] = nOffset*2; 
-    psSHP->panRecSize[i] = nLength*2; 
+
+    psSHP->panRecOffset[i] = nOffset*2;
+    psSHP->panRecSize[i] = nLength*2;
   }
   free(pabyBuf);
   psSHP->panRecAllLoaded = 1;
-  
+
   return(MS_SUCCESS);
 
 }
 
-int msSHXReadOffset( SHPHandle psSHP, int hEntity ) {
+int msSHXReadOffset( SHPHandle psSHP, int hEntity )
+{
 
   int shxBufferPage = hEntity / SHX_BUFFER_PAGE;
 
@@ -1165,7 +1160,8 @@ int msSHXReadOffset( SHPHandle psSHP, int hEntity ) {
 
 }
 
-int msSHXReadSize( SHPHandle psSHP, int hEntity ) {
+int msSHXReadSize( SHPHandle psSHP, int hEntity )
+{
 
   int shxBufferPage = hEntity / SHX_BUFFER_PAGE;
 
@@ -1200,14 +1196,13 @@ void msSHPReadShape( SHPHandle psSHP, int hEntity, shapeObj *shape )
   if( hEntity < 0 || hEntity >= psSHP->nRecords )
     return;
 
-  if( msSHXReadSize(psSHP, hEntity) == 4 ) {      
+  if( msSHXReadSize(psSHP, hEntity) == 4 ) {
     shape->type = MS_SHAPE_NULL;
     return;
   }
 
   nEntitySize = msSHXReadSize(psSHP, hEntity) + 8;
-  if (msSHPReadAllocateBuffer(psSHP, hEntity, "msSHPReadShape()") == MS_FAILURE)
-  {
+  if (msSHPReadAllocateBuffer(psSHP, hEntity, "msSHPReadShape()") == MS_FAILURE) {
     shape->type = MS_SHAPE_NULL;
     return;
   }
@@ -1219,16 +1214,14 @@ void msSHPReadShape( SHPHandle psSHP, int hEntity, shapeObj *shape )
   fread( psSHP->pabyRec, nEntitySize, 1, psSHP->fpSHP );
 
   /* -------------------------------------------------------------------- */
-  /*  Extract vertices for a Polygon or Arc.				    */
+  /*  Extract vertices for a Polygon or Arc.            */
   /* -------------------------------------------------------------------- */
-  if( psSHP->nShapeType == SHP_POLYGON || psSHP->nShapeType == SHP_ARC || 
+  if( psSHP->nShapeType == SHP_POLYGON || psSHP->nShapeType == SHP_ARC ||
       psSHP->nShapeType == SHP_POLYGONM || psSHP->nShapeType == SHP_ARCM ||
-      psSHP->nShapeType == SHP_POLYGONZ || psSHP->nShapeType == SHP_ARCZ)
-  {
-    ms_int32  nPoints, nParts;      
-    
-    if (nEntitySize < 40 + 8 + 4)
-    {
+      psSHP->nShapeType == SHP_POLYGONZ || psSHP->nShapeType == SHP_ARCZ) {
+    ms_int32  nPoints, nParts;
+
+    if (nEntitySize < 40 + 8 + 4) {
       shape->type = MS_SHAPE_NULL;
       msSetError(MS_SHPERR, "Corrupted feature encountered.  hEntity = %d, nEntitySize=%d", "msSHPReadShape()",
                  hEntity, nEntitySize);
@@ -1250,29 +1243,27 @@ void msSHPReadShape( SHPHandle psSHP, int hEntity, shapeObj *shape )
 
     memcpy( &nPoints, psSHP->pabyRec + 40 + 8, 4 );
     memcpy( &nParts, psSHP->pabyRec + 36 + 8, 4 );
-      
+
     if( bBigEndian ) {
       nPoints = SWAP_FOUR_BYTES(nPoints);
-      nParts = SWAP_FOUR_BYTES(nParts);    
+      nParts = SWAP_FOUR_BYTES(nParts);
     }
 
-    if (nPoints < 0 || nParts < 0 || 
-        nPoints > 50 * 1000 * 1000 || nParts > 10 * 1000 * 1000) 
-    {
+    if (nPoints < 0 || nParts < 0 ||
+        nPoints > 50 * 1000 * 1000 || nParts > 10 * 1000 * 1000) {
       shape->type = MS_SHAPE_NULL;
       msSetError(MS_SHPERR, "Corrupted feature encountered.  hEntity = %d, nPoints =%d, nParts = %d", "msSHPReadShape()",
                  hEntity, nPoints, nParts);
       return;
     }
-    
+
     /* -------------------------------------------------------------------- */
     /*      Copy out the part array from the record.                        */
     /* -------------------------------------------------------------------- */
     if( psSHP->nPartMax < nParts ) {
       psSHP->panParts = (int *) SfRealloc(psSHP->panParts, nParts * sizeof(int) );
-      if (psSHP->panParts == NULL)
-      {
-        /* Reallocate previous successfull size for following features */ 
+      if (psSHP->panParts == NULL) {
+        /* Reallocate previous successfull size for following features */
         psSHP->panParts = (int *) msSmallMalloc(psSHP->nPartMax * sizeof(int) );
 
         shape->type = MS_SHAPE_NULL;
@@ -1282,31 +1273,29 @@ void msSHPReadShape( SHPHandle psSHP, int hEntity, shapeObj *shape )
       }
       psSHP->nPartMax = nParts;
     }
-    if (psSHP->panParts == NULL)
-    {
-       shape->type = MS_SHAPE_NULL;
-       msSetError(MS_MEMERR, "Out of memory", "msSHPReadShape()");
-       return;
+    if (psSHP->panParts == NULL) {
+      shape->type = MS_SHAPE_NULL;
+      msSetError(MS_MEMERR, "Out of memory", "msSHPReadShape()");
+      return;
     }
-    
+
     /* With the previous checks on nPoints and nParts, */
     /* we should not overflow here and after */
     /* since 50 M * (16 + 8 + 8) = 1 600 MB */
-    if (44 + 8 + 4 * nParts + 16 * nPoints > nEntitySize)
-    {
+    if (44 + 8 + 4 * nParts + 16 * nPoints > nEntitySize) {
       shape->type = MS_SHAPE_NULL;
       msSetError(MS_SHPERR, "Corrupted .shp file : shape %d, nPoints=%d, nParts=%d.",
                  "msSHPReadShape()", hEntity, nPoints, nParts);
       return;
     }
-      
+
     memcpy( psSHP->panParts, psSHP->pabyRec + 44 + 8, 4 * nParts );
     if( bBigEndian ) {
       for( i = 0; i < nParts; i++ ) {
         *(psSHP->panParts+i) = SWAP_FOUR_BYTES(*(psSHP->panParts+i));
       }
     }
-      
+
     /* -------------------------------------------------------------------- */
     /*      Fill the shape structure.                                       */
     /* -------------------------------------------------------------------- */
@@ -1314,15 +1303,14 @@ void msSHPReadShape( SHPHandle psSHP, int hEntity, shapeObj *shape )
     MS_CHECK_ALLOC_NO_RET(shape->line, sizeof(lineObj)*nParts);
 
     shape->numlines = nParts;
-      
+
     k = 0; /* overall point counter */
-    for( i = 0; i < nParts; i++) { 	  
+    for( i = 0; i < nParts; i++) {
       if( i == nParts-1)
         shape->line[i].numpoints = nPoints - psSHP->panParts[i];
       else
         shape->line[i].numpoints = psSHP->panParts[i+1] - psSHP->panParts[i];
-      if (shape->line[i].numpoints <= 0)
-      {
+      if (shape->line[i].numpoints <= 0) {
         msSetError(MS_SHPERR, "Corrupted .shp file : shape %d, shape->line[%d].numpoints=%d", "msSHPReadShape()",
                    hEntity, i, shape->line[i].numpoints);
         while(--i >= 0)
@@ -1333,7 +1321,7 @@ void msSHPReadShape( SHPHandle psSHP, int hEntity, shapeObj *shape )
         shape->type = MS_SHAPE_NULL;
         return;
       }
-	
+
       if( (shape->line[i].point = (pointObj *)malloc(sizeof(pointObj)*shape->line[i].numpoints)) == NULL ) {
         while(--i >= 0)
           free(shape->line[i].point);
@@ -1348,7 +1336,7 @@ void msSHPReadShape( SHPHandle psSHP, int hEntity, shapeObj *shape )
       for( j = 0; j < shape->line[i].numpoints; j++ ) {
         memcpy(&(shape->line[i].point[j].x), psSHP->pabyRec + 44 + 4*nParts + 8 + k * 16, 8 );
         memcpy(&(shape->line[i].point[j].y), psSHP->pabyRec + 44 + 4*nParts + 8 + k * 16 + 8, 8 );
-	  
+
         if( bBigEndian ) {
           SwapWord( 8, &(shape->line[i].point[j].x) );
           SwapWord( 8, &(shape->line[i].point[j].y) );
@@ -1364,7 +1352,7 @@ void msSHPReadShape( SHPHandle psSHP, int hEntity, shapeObj *shape )
           if( nEntitySize >= nOffset + 16 + 8*nPoints ) {
             memcpy(&(shape->line[i].point[j].z), psSHP->pabyRec + nOffset + 16 + k*8, 8 );
             if( bBigEndian ) SwapWord( 8, &(shape->line[i].point[j].z) );
-          }   
+          }
         }
 
         /* -------------------------------------------------------------------- */
@@ -1376,16 +1364,16 @@ void msSHPReadShape( SHPHandle psSHP, int hEntity, shapeObj *shape )
           if( nEntitySize >= nOffset + 16 + 8*nPoints ) {
             memcpy(&(shape->line[i].point[j].m), psSHP->pabyRec + nOffset + 16 + k*8, 8 );
             if( bBigEndian ) SwapWord( 8, &(shape->line[i].point[j].m) );
-          }   
+          }
         }
 #endif /* USE_POINT_Z_M */
-	      k++;
-	    }
+        k++;
+      }
     }
 
-    if(psSHP->nShapeType == SHP_POLYGON 
-       || psSHP->nShapeType == SHP_POLYGONZ
-       || psSHP->nShapeType == SHP_POLYGONM)
+    if(psSHP->nShapeType == SHP_POLYGON
+        || psSHP->nShapeType == SHP_POLYGONZ
+        || psSHP->nShapeType == SHP_POLYGONM)
       shape->type = MS_SHAPE_POLYGON;
     else
       shape->type = MS_SHAPE_LINE;
@@ -1393,14 +1381,13 @@ void msSHPReadShape( SHPHandle psSHP, int hEntity, shapeObj *shape )
   }
 
   /* -------------------------------------------------------------------- */
-  /*  Extract a MultiPoint.                     			                    */
+  /*  Extract a MultiPoint.                                               */
   /* -------------------------------------------------------------------- */
   else if( psSHP->nShapeType == SHP_MULTIPOINT || psSHP->nShapeType == SHP_MULTIPOINTM ||
            psSHP->nShapeType == SHP_MULTIPOINTZ) {
     ms_int32 nPoints;
 
-    if (nEntitySize < 44 + 4)
-    {
+    if (nEntitySize < 44 + 4) {
       shape->type = MS_SHAPE_NULL;
       msSetError(MS_SHPERR, "Corrupted feature encountered.  recSize of feature %d=%d", "msSHPReadShape()",
                  hEntity, msSHXReadSize(psSHP, hEntity));
@@ -1422,7 +1409,7 @@ void msSHPReadShape( SHPHandle psSHP, int hEntity, shapeObj *shape )
 
     memcpy( &nPoints, psSHP->pabyRec + 44, 4 );
     if( bBigEndian ) nPoints = SWAP_FOUR_BYTES(nPoints);
-    
+
     /* -------------------------------------------------------------------- */
     /*      Fill the shape structure.                                       */
     /* -------------------------------------------------------------------- */
@@ -1432,8 +1419,7 @@ void msSHPReadShape( SHPHandle psSHP, int hEntity, shapeObj *shape )
       return;
     }
 
-    if (nPoints < 0 || nPoints > 50 * 1000 * 1000)
-    {
+    if (nPoints < 0 || nPoints > 50 * 1000 * 1000) {
       free(shape->line);
       shape->type = MS_SHAPE_NULL;
       msSetError(MS_SHPERR, "Corrupted .shp file : shape %d, nPoints=%d.",
@@ -1443,34 +1429,32 @@ void msSHPReadShape( SHPHandle psSHP, int hEntity, shapeObj *shape )
 
     nRequiredSize = 48 + nPoints * 16;
     if (psSHP->nShapeType == SHP_MULTIPOINTZ || psSHP->nShapeType == SHP_MULTIPOINTM)
-        nRequiredSize += 16 + nPoints * 8;
-    if (nRequiredSize > nEntitySize)
-    {
+      nRequiredSize += 16 + nPoints * 8;
+    if (nRequiredSize > nEntitySize) {
       free(shape->line);
       shape->type = MS_SHAPE_NULL;
       msSetError(MS_SHPERR, "Corrupted .shp file : shape %d : nPoints = %d, nEntitySize = %d",
-                 "msSHPReadShape()", hEntity, nPoints, nEntitySize); 
+                 "msSHPReadShape()", hEntity, nPoints, nEntitySize);
       return;
     }
 
     shape->numlines = 1;
     shape->line[0].numpoints = nPoints;
     shape->line[0].point = (pointObj *) malloc( nPoints * sizeof(pointObj) );
-    if (shape->line[0].point == NULL)
-    {
+    if (shape->line[0].point == NULL) {
       free(shape->line);
       shape->numlines = 0;
       shape->type = MS_SHAPE_NULL;
       msSetError(MS_MEMERR, "Out of memory", "msSHPReadShape()");
       return;
     }
-      
+
     for( i = 0; i < nPoints; i++ ) {
       memcpy(&(shape->line[0].point[i].x), psSHP->pabyRec + 48 + 16 * i, 8 );
       memcpy(&(shape->line[0].point[i].y), psSHP->pabyRec + 48 + 16 * i + 8, 8 );
-	
+
       if( bBigEndian ) {
-	      SwapWord( 8, &(shape->line[0].point[i].x) );
+        SwapWord( 8, &(shape->line[0].point[i].x) );
         SwapWord( 8, &(shape->line[0].point[i].y) );
       }
 
@@ -1501,13 +1485,12 @@ void msSHPReadShape( SHPHandle psSHP, int hEntity, shapeObj *shape )
   }
 
   /* -------------------------------------------------------------------- */
-  /*  Extract a Point.   			                    */
+  /*  Extract a Point.                            */
   /* -------------------------------------------------------------------- */
   else if(psSHP->nShapeType == SHP_POINT ||  psSHP->nShapeType == SHP_POINTM ||
-          psSHP->nShapeType == SHP_POINTZ) {    
+          psSHP->nShapeType == SHP_POINTZ) {
 
-    if (nEntitySize < 20 + 8)
-    {
+    if (nEntitySize < 20 + 8) {
       shape->type = MS_SHAPE_NULL;
       msSetError(MS_SHPERR, "Corrupted feature encountered.  recSize of feature %d=%d", "msSHPReadShape()",
                  hEntity, msSHXReadSize(psSHP, hEntity));
@@ -1523,10 +1506,10 @@ void msSHPReadShape( SHPHandle psSHP, int hEntity, shapeObj *shape )
     shape->numlines = 1;
     shape->line[0].numpoints = 1;
     shape->line[0].point = (pointObj *) msSmallMalloc(sizeof(pointObj));
-      
+
     memcpy( &(shape->line[0].point[0].x), psSHP->pabyRec + 12, 8 );
     memcpy( &(shape->line[0].point[0].y), psSHP->pabyRec + 20, 8 );
-      
+
     if( bBigEndian ) {
       SwapWord( 8, &(shape->line[0].point[0].x));
       SwapWord( 8, &(shape->line[0].point[0].y));
@@ -1540,7 +1523,7 @@ void msSHPReadShape( SHPHandle psSHP, int hEntity, shapeObj *shape )
     if (psSHP->nShapeType == SHP_POINTZ) {
       nOffset = 20 + 8;
       if( nEntitySize >= nOffset + 8 ) {
-        memcpy(&(shape->line[0].point[0].z), psSHP->pabyRec + nOffset, 8 );        
+        memcpy(&(shape->line[0].point[0].z), psSHP->pabyRec + nOffset, 8 );
         if( bBigEndian ) SwapWord( 8, &(shape->line[0].point[0].z));
       }
     }
@@ -1581,20 +1564,20 @@ int msSHPReadBounds( SHPHandle psSHP, int hEntity, rectObj *padBounds)
   }
 
   /* -------------------------------------------------------------------- */
-  /*	If the entity is -1 we fetch the bounds for the whole file.	  */
+  /*  If the entity is -1 we fetch the bounds for the whole file.   */
   /* -------------------------------------------------------------------- */
   if( hEntity == -1 ) {
     padBounds->minx = psSHP->adBoundsMin[0];
     padBounds->miny = psSHP->adBoundsMin[1];
     padBounds->maxx = psSHP->adBoundsMax[0];
     padBounds->maxy = psSHP->adBoundsMax[1];
-  } else {    
-    
+  } else {
+
     if( msSHXReadSize(psSHP, hEntity) == 4 ) { /* NULL shape */
       padBounds->minx = padBounds->miny = padBounds->maxx = padBounds->maxy = 0.0;
       return MS_FAILURE;
-    } 
-    
+    }
+
     if( psSHP->nShapeType != SHP_POINT && psSHP->nShapeType != SHP_POINTZ && psSHP->nShapeType != SHP_POINTM) {
       fseek( psSHP->fpSHP, msSHXReadOffset(psSHP, hEntity) + 12, 0 );
       fread( padBounds, sizeof(double)*4, 1, psSHP->fpSHP );
@@ -1608,22 +1591,22 @@ int msSHPReadBounds( SHPHandle psSHP, int hEntity, rectObj *padBounds)
 
       if(msIsNan(padBounds->minx)) { /* empty shape */
         padBounds->minx = padBounds->miny = padBounds->maxx = padBounds->maxy = 0.0;
-	return MS_FAILURE;
+        return MS_FAILURE;
       }
     } else {
       /* -------------------------------------------------------------------- */
       /*      For points we fetch the point, and duplicate it as the          */
       /*      minimum and maximum bound.                                      */
       /* -------------------------------------------------------------------- */
-      
+
       fseek( psSHP->fpSHP, msSHXReadOffset(psSHP, hEntity) + 12, 0 );
       fread( padBounds, sizeof(double)*2, 1, psSHP->fpSHP );
-      
+
       if( bBigEndian ) {
         SwapWord( 8, &(padBounds->minx) );
         SwapWord( 8, &(padBounds->miny) );
       }
-      
+
       padBounds->maxx = padBounds->minx;
       padBounds->maxy = padBounds->miny;
     }
@@ -1650,7 +1633,7 @@ int msShapefileOpen(shapefileObj *shpfile, char *mode, char *filename, int log_f
   shpfile->isopen = MS_FALSE;
 
   /* open the shapefile file (appending ok) and get basic info */
-  if(!mode) 	
+  if(!mode)
     shpfile->hSHP = msSHPOpen( filename, "rb");
   else
     shpfile->hSHP = msSHPOpen( filename, mode);
@@ -1662,31 +1645,31 @@ int msShapefileOpen(shapefileObj *shpfile, char *mode, char *filename, int log_f
   }
 
   strlcpy(shpfile->source, filename, sizeof(shpfile->source));
-  
+
   /* load some information about this shapefile */
   msSHPGetInfo( shpfile->hSHP, &shpfile->numshapes, &shpfile->type);
   msSHPReadBounds( shpfile->hSHP, -1, &(shpfile->bounds));
-  
+
   bufferSize = strlen(filename)+5;
   dbfFilename = (char *)msSmallMalloc(bufferSize);
   dbfFilename[0] = '\0';
   strcpy(dbfFilename, filename);
-  
+
   /* clean off any extention the filename might have */
-  for (i = strlen(dbfFilename) - 1; 
+  for (i = strlen(dbfFilename) - 1;
        i > 0 && dbfFilename[i] != '.' && dbfFilename[i] != '/' && dbfFilename[i] != '\\';
        i-- ) {}
 
   if( dbfFilename[i] == '.' )
     dbfFilename[i] = '\0';
-  
+
   strlcat(dbfFilename, ".dbf", bufferSize);
 
   shpfile->hDBF = msDBFOpen(dbfFilename, "rb");
 
   if(!shpfile->hDBF) {
     if( log_failures )
-      msSetError(MS_IOERR, "(%s)", "msShapefileOpen()", dbfFilename);    
+      msSetError(MS_IOERR, "(%s)", "msShapefileOpen()", dbfFilename);
     free(dbfFilename);
     return(-1);
   }
@@ -1700,11 +1683,11 @@ int msShapefileOpen(shapefileObj *shpfile, char *mode, char *filename, int log_f
 int msShapefileCreate(shapefileObj *shpfile, char *filename, int type)
 {
   if(type != SHP_POINT && type != SHP_MULTIPOINT && type != SHP_ARC &&
-     type != SHP_POLYGON && 
-     type != SHP_POINTM && type != SHP_MULTIPOINTM &&
-     type != SHP_ARCM && type != SHP_POLYGONM && 
-     type != SHP_POINTZ && type != SHP_MULTIPOINTZ &&
-     type != SHP_ARCZ && type != SHP_POLYGONZ) {
+      type != SHP_POLYGON &&
+      type != SHP_POINTM && type != SHP_MULTIPOINTM &&
+      type != SHP_ARCM && type != SHP_POLYGONM &&
+      type != SHP_POINTZ && type != SHP_MULTIPOINTZ &&
+      type != SHP_ARCZ && type != SHP_POLYGONZ) {
     msSetError(MS_SHPERR, "Invalid shape type.", "msNewSHPFile()");
     return(-1);
   }
@@ -1712,7 +1695,7 @@ int msShapefileCreate(shapefileObj *shpfile, char *filename, int type)
   /* create the spatial portion */
   shpfile->hSHP = msSHPCreate(filename, type);
   if(!shpfile->hSHP) {
-    msSetError(MS_IOERR, "(%s)", "msNewSHPFile()",filename);    
+    msSetError(MS_IOERR, "(%s)", "msNewSHPFile()",filename);
     return(-1);
   }
 
@@ -1747,7 +1730,7 @@ int msShapefileWhichShapes(shapefileObj *shpfile, rectObj rect, int debug)
   char *filename;
   char *sourcename = 0; /* shape file source string from map file */
   char *s = 0; /* pointer to start of '.shp' in source string */
-  
+
   if(shpfile->status) {
     free(shpfile->status);
     shpfile->status = NULL;
@@ -1756,7 +1739,7 @@ int msShapefileWhichShapes(shapefileObj *shpfile, rectObj rect, int debug)
   shpfile->statusbounds = rect; /* save the search extent */
 
   /* rect and shapefile DON'T overlap... */
-  if(msRectOverlap(&shpfile->bounds, &rect) != MS_TRUE) 
+  if(msRectOverlap(&shpfile->bounds, &rect) != MS_TRUE)
     return(MS_DONE);
 
   if(msRectContained(&shpfile->bounds, &rect) == MS_TRUE) {
@@ -1766,8 +1749,7 @@ int msShapefileWhichShapes(shapefileObj *shpfile, rectObj rect, int debug)
       return(MS_FAILURE);
     }
     msSetAllBits(shpfile->status, shpfile->numshapes, 1);
-  } 
-  else {
+  } else {
 
     /* deal with case where sourcename is of the form 'file.shp' */
     sourcename = msStrdup(shpfile->source);
@@ -1777,30 +1759,29 @@ int msShapefileWhichShapes(shapefileObj *shpfile, rectObj rect, int debug)
 
     filename = (char *)malloc(strlen(sourcename)+strlen(MS_INDEX_EXTENSION)+1);
     MS_CHECK_ALLOC(filename, strlen(sourcename)+strlen(MS_INDEX_EXTENSION)+1, MS_FAILURE);
-  
+
     sprintf(filename, "%s%s", sourcename, MS_INDEX_EXTENSION);
-    
+
     shpfile->status = msSearchDiskTree(filename, rect, debug);
     free(filename);
     free(sourcename);
 
     if(shpfile->status) { /* index  */
       msFilterTreeSearch(shpfile, shpfile->status, rect);
-    }
-    else { /* no index  */
+    } else { /* no index  */
       shpfile->status = msAllocBitArray(shpfile->numshapes);
       if(!shpfile->status) {
-        msSetError(MS_MEMERR, NULL, "msShapefileWhichShapes()");       
+        msSetError(MS_MEMERR, NULL, "msShapefileWhichShapes()");
         return(MS_FAILURE);
       }
-      
-      for(i=0;i<shpfile->numshapes;i++) {
+
+      for(i=0; i<shpfile->numshapes; i++) {
         if(msSHPReadBounds(shpfile->hSHP, i, &shaperect) == MS_SUCCESS)
           if(msRectOverlap(&shaperect, &rect) == MS_TRUE) msSetBit(shpfile->status, i, 1);
       }
     }
   }
- 
+
   shpfile->lastshape = -1;
 
   return(MS_SUCCESS); /* success */
@@ -1811,7 +1792,7 @@ void msTileIndexAbsoluteDir(char *tiFileAbsDir, layerObj *layer)
 {
   char tiFileAbsPath[MS_MAXPATHLEN];
   char *tiFileAbsDirTmp=NULL;
- 
+
   msBuildPath(tiFileAbsPath, layer->map->mappath, layer->tileindex); /* absolute path to tileindex file */
   tiFileAbsDirTmp = msGetPath(tiFileAbsPath); /* tileindex file's directory */
   strlcpy(tiFileAbsDir, tiFileAbsDirTmp, MS_MAXPATHLEN);
@@ -1823,45 +1804,43 @@ void msTileIndexAbsoluteDir(char *tiFileAbsDir, layerObj *layer)
 **   map dir + shape path + filename?
 **   tile dir + shape path + filename?
 **   map dir + filename?
-** 
+**
 ** Returns
 ** MS_SUCCESS - found a file
 ** MS_FAILURE - no file, and map is configured to fail on missing
 ** MS_DONE - no file, and map is configured to continue on missing
 */
-int msTiledSHPTryOpen(shapefileObj *shpfile, layerObj *layer, char *tiFileAbsDir, char *filename) {
-    char szPath[MS_MAXPATHLEN];
-    int ignore_missing = msMapIgnoreMissingData(layer->map);
-    int log_failures = MS_TRUE;
-    
-    if( ignore_missing == MS_MISSING_DATA_IGNORE ) 
-      log_failures = MS_FALSE;
-    
-    if(msShapefileOpen(shpfile, "rb", msBuildPath3(szPath, layer->map->mappath, layer->map->shapepath, filename), log_failures) == -1) { 
-      if(msShapefileOpen(shpfile, "rb", msBuildPath3(szPath, tiFileAbsDir, layer->map->shapepath, filename), log_failures) == -1) { 
-        if(msShapefileOpen(shpfile, "rb", msBuildPath(szPath, layer->map->mappath, filename), log_failures) == -1) { 
-          if(ignore_missing == MS_MISSING_DATA_FAIL) {
-            msSetError(MS_IOERR, "Unable to open shapefile '%s' for layer '%s' ... fatal error.", "msTiledSHPTryOpen()", filename, layer->name);
-            return(MS_FAILURE); 
-          }
-          else if( ignore_missing == MS_MISSING_DATA_LOG ) {
-            if( layer->debug || layer->map->debug ) {
-              msDebug( "Unable to open shapefile '%s' for layer '%s' ... ignoring this missing data.\n", szPath, layer->name );
-            }
-            return(MS_DONE);
-          }
-          else if( ignore_missing == MS_MISSING_DATA_IGNORE ) {
-            return(MS_DONE);
-          }
-          else {
-            /* never get here */
-            msSetError(MS_IOERR, "msIgnoreMissingData returned unexpected value.", "msTiledSHPTryOpen()");
-            return(MS_FAILURE);
+int msTiledSHPTryOpen(shapefileObj *shpfile, layerObj *layer, char *tiFileAbsDir, char *filename)
+{
+  char szPath[MS_MAXPATHLEN];
+  int ignore_missing = msMapIgnoreMissingData(layer->map);
+  int log_failures = MS_TRUE;
+
+  if( ignore_missing == MS_MISSING_DATA_IGNORE )
+    log_failures = MS_FALSE;
+
+  if(msShapefileOpen(shpfile, "rb", msBuildPath3(szPath, layer->map->mappath, layer->map->shapepath, filename), log_failures) == -1) {
+    if(msShapefileOpen(shpfile, "rb", msBuildPath3(szPath, tiFileAbsDir, layer->map->shapepath, filename), log_failures) == -1) {
+      if(msShapefileOpen(shpfile, "rb", msBuildPath(szPath, layer->map->mappath, filename), log_failures) == -1) {
+        if(ignore_missing == MS_MISSING_DATA_FAIL) {
+          msSetError(MS_IOERR, "Unable to open shapefile '%s' for layer '%s' ... fatal error.", "msTiledSHPTryOpen()", filename, layer->name);
+          return(MS_FAILURE);
+        } else if( ignore_missing == MS_MISSING_DATA_LOG ) {
+          if( layer->debug || layer->map->debug ) {
+            msDebug( "Unable to open shapefile '%s' for layer '%s' ... ignoring this missing data.\n", szPath, layer->name );
           }
+          return(MS_DONE);
+        } else if( ignore_missing == MS_MISSING_DATA_IGNORE ) {
+          return(MS_DONE);
+        } else {
+          /* never get here */
+          msSetError(MS_IOERR, "msIgnoreMissingData returned unexpected value.", "msTiledSHPTryOpen()");
+          return(MS_FAILURE);
         }
-      } 
-    }      
-    return(MS_SUCCESS);
+      }
+    }
+  }
+  return(MS_SUCCESS);
 }
 
 int msTiledSHPOpenFile(layerObj *layer)
@@ -1871,23 +1850,23 @@ int msTiledSHPOpenFile(layerObj *layer)
   char tiFileAbsDir[MS_MAXPATHLEN];
 
   msTiledSHPLayerInfo *tSHP=NULL;
-  
+
   if ( msCheckParentPointer(layer->map,"map")==MS_FAILURE )
-	return MS_FAILURE;  
+    return MS_FAILURE;
 
-  /* allocate space for a shapefileObj using layer->layerinfo	 */
+  /* allocate space for a shapefileObj using layer->layerinfo  */
   tSHP = (msTiledSHPLayerInfo *) malloc(sizeof(msTiledSHPLayerInfo));
   MS_CHECK_ALLOC(tSHP, sizeof(msTiledSHPLayerInfo), MS_FAILURE);
 
   tSHP->shpfile = (shapefileObj *) malloc(sizeof(shapefileObj));
-  if (tSHP->shpfile == NULL)
-  {
-      msSetError(MS_MEMERR, "%s: %d: Out of memory allocating %u bytes.\n", "msTiledSHPOpenFile()",
-                 __FILE__, __LINE__, sizeof(shapefileObj));
-      free(tSHP);
-      return MS_FAILURE;
+  if (tSHP->shpfile == NULL) {
+    msSetError(MS_MEMERR, "%s: %d: Out of memory allocating %u bytes.\n", "msTiledSHPOpenFile()",
+               __FILE__, __LINE__, sizeof(shapefileObj));
+    free(tSHP);
+    return MS_FAILURE;
   }
-
+  
+  tSHP->shpfile->isopen = MS_FALSE; /* in case of error: do not try to close the shpfile */
   tSHP->tileshpfile = NULL; /* may need this if not using a tile layer, look for malloc later */
   layer->layerinfo = tSHP;
 
@@ -1899,59 +1878,59 @@ int msTiledSHPOpenFile(layerObj *layer)
     tlp = (GET_LAYER(layer->map, tSHP->tilelayerindex));
 
     if(tlp->connectiontype != MS_SHAPEFILE) {
-	  msSetError(MS_SDEERR, "Tileindex layer must be a shapefile.", "msTiledSHPOpenFile()");
+      msSetError(MS_SDEERR, "Tileindex layer must be a shapefile.", "msTiledSHPOpenFile()");
       return(MS_FAILURE);
     }
 
     status = msLayerOpen(tlp);
     if(status != MS_SUCCESS) return(MS_FAILURE);
 
-     /* build item list */
-     status = msLayerWhichItems(tlp, MS_FALSE, NULL);
-     if(status != MS_SUCCESS) return(MS_FAILURE);
+    /* build item list */
+    status = msLayerWhichItems(tlp, MS_FALSE, NULL);
+    if(status != MS_SUCCESS) return(MS_FAILURE);
 
-     tSHP->tileshpfile = (shapefileObj *) tlp->layerinfo; /* shapefiles use layerinfo to point to a shapefileObj */
+    tSHP->tileshpfile = (shapefileObj *) tlp->layerinfo; /* shapefiles use layerinfo to point to a shapefileObj */
 
   } else { /* or reference a shapefile directly */
 
     /* we need tSHP->tileshpfile if we're not working with a layer */
     tSHP->tileshpfile = (shapefileObj *) malloc(sizeof(shapefileObj));
-    if (tSHP->tileshpfile == NULL)
-    {
-        msSetError(MS_MEMERR, "%s: %d: Out of memory allocating %u bytes.\n", "msTiledSHPOpenFile()",
-                   __FILE__, __LINE__, sizeof(shapefileObj));
-        free(tSHP->shpfile);
-        free(tSHP);
-        return MS_FAILURE;
+    if (tSHP->tileshpfile == NULL) {
+      msSetError(MS_MEMERR, "%s: %d: Out of memory allocating %u bytes.\n", "msTiledSHPOpenFile()",
+                 __FILE__, __LINE__, sizeof(shapefileObj));
+      free(tSHP->shpfile);
+      free(tSHP);
+      layer->layerinfo = NULL;
+      return MS_FAILURE;
     }
 
 
-    if(msShapefileOpen(tSHP->tileshpfile, "rb", msBuildPath3(szPath, layer->map->mappath, layer->map->shapepath, layer->tileindex), MS_TRUE) == -1) 
+    if(msShapefileOpen(tSHP->tileshpfile, "rb", msBuildPath3(szPath, layer->map->mappath, layer->map->shapepath, layer->tileindex), MS_TRUE) == -1)
       if(msShapefileOpen(tSHP->tileshpfile, "rb", msBuildPath(szPath, layer->map->mappath, layer->tileindex), MS_TRUE) == -1)
         return(MS_FAILURE);
   }
 
   if((layer->tileitemindex = msDBFGetItemIndex(tSHP->tileshpfile->hDBF, layer->tileitem)) == -1) return(MS_FAILURE);
- 
+
   msTileIndexAbsoluteDir(tiFileAbsDir, layer);
 
   /* position the source at the FIRST tile to use as a template, this is so the functions that fill the iteminfo array have something to work from */
   for(i=0; i<tSHP->tileshpfile->numshapes; i++) {
     int try_open;
-    
+
     if(!layer->data) /* assume whole filename is in attribute field */
       filename = (char*) msDBFReadStringAttribute(tSHP->tileshpfile->hDBF, i, layer->tileitemindex);
-    else {  
+    else {
       snprintf(tilename, sizeof(tilename), "%s/%s", msDBFReadStringAttribute(tSHP->tileshpfile->hDBF, i, layer->tileitemindex) , layer->data);
       filename = tilename;
     }
-      
+
     if(strlen(filename) == 0) continue; /* check again */
-    
+
     try_open = msTiledSHPTryOpen(tSHP->shpfile, layer, tiFileAbsDir, filename);
     if( try_open == MS_DONE )
       continue;
-    else if (try_open == MS_FAILURE ) 
+    else if (try_open == MS_FAILURE )
       return(MS_FAILURE);
 
     return(MS_SUCCESS); /* found a template, ok to proceed */
@@ -1969,9 +1948,9 @@ int msTiledSHPWhichShapes(layerObj *layer, rectObj rect, int isQuery)
   char tiFileAbsDir[MS_MAXPATHLEN];
 
   msTiledSHPLayerInfo *tSHP=NULL;
-  
+
   if ( msCheckParentPointer(layer->map,"map")==MS_FAILURE )
-	return MS_FAILURE;
+    return MS_FAILURE;
 
   tSHP = layer->layerinfo;
   if(!tSHP) {
@@ -1994,34 +1973,33 @@ int msTiledSHPWhichShapes(layerObj *layer, rectObj rect, int isQuery)
     msInitShape(&tshape);
     while((status = msLayerNextShape(tlp, &tshape)) == MS_SUCCESS) {
       int try_open;
-      
+
       /* TODO: seems stupid to read the tileitem seperately from the shape, need to fix msTiledSHPOpenFile */
       if(!layer->data) /* assume whole filename is in attribute field */
-	    filename = (char *) msDBFReadStringAttribute(tSHP->tileshpfile->hDBF, tshape.index, layer->tileitemindex);
+        filename = (char *) msDBFReadStringAttribute(tSHP->tileshpfile->hDBF, tshape.index, layer->tileitemindex);
       else {
-            snprintf(tilename, sizeof(tilename), "%s/%s", msDBFReadStringAttribute(tSHP->tileshpfile->hDBF, tshape.index, layer->tileitemindex) , layer->data);
-	    filename = tilename;
+        snprintf(tilename, sizeof(tilename), "%s/%s", msDBFReadStringAttribute(tSHP->tileshpfile->hDBF, tshape.index, layer->tileitemindex) , layer->data);
+        filename = tilename;
       }
 
       if(strlen(filename) == 0) continue; /* check again */
 
       try_open = msTiledSHPTryOpen(tSHP->shpfile, layer, tiFileAbsDir, filename);
-      if( try_open == MS_DONE ) 
+      if( try_open == MS_DONE )
         continue;
-      else if (try_open == MS_FAILURE ) 
+      else if (try_open == MS_FAILURE )
         return(MS_FAILURE);
 
       status = msShapefileWhichShapes(tSHP->shpfile, rect, layer->debug);
       if(status == MS_DONE) {
-          /* Close and continue to next tile */
-          msShapefileClose(tSHP->shpfile);
-          continue;
-      }
-      else if(status != MS_SUCCESS) {
-          msShapefileClose(tSHP->shpfile);
-          return(MS_FAILURE);
+        /* Close and continue to next tile */
+        msShapefileClose(tSHP->shpfile);
+        continue;
+      } else if(status != MS_SUCCESS) {
+        msShapefileClose(tSHP->shpfile);
+        return(MS_FAILURE);
       }
-       
+
       /* the layer functions keeps track of this */
       /* tSHP->tileshpfile->lastshape = tshape.index; */
       break;
@@ -2030,7 +2008,7 @@ int msTiledSHPWhichShapes(layerObj *layer, rectObj rect, int isQuery)
 
   } else { /* or reference a shapefile directly */
     int try_open;
-    
+
     status = msShapefileWhichShapes(tSHP->tileshpfile, rect, layer->debug);
     if(status != MS_SUCCESS) return(status); /* could be MS_DONE or MS_FAILURE */
 
@@ -2040,10 +2018,10 @@ int msTiledSHPWhichShapes(layerObj *layer, rectObj rect, int isQuery)
     for(i=0; i<tSHP->tileshpfile->numshapes; i++) {
       if(msGetBit(tSHP->tileshpfile->status,i)) {
         if(!layer->data) /* assume whole filename is in attribute field */
-	      filename = (char *) msDBFReadStringAttribute(tSHP->tileshpfile->hDBF, i, layer->tileitemindex);
-        else {  
-              snprintf(tilename, sizeof(tilename), "%s/%s", msDBFReadStringAttribute(tSHP->tileshpfile->hDBF, i, layer->tileitemindex) , layer->data);
-	      filename = tilename;
+          filename = (char *) msDBFReadStringAttribute(tSHP->tileshpfile->hDBF, i, layer->tileitemindex);
+        else {
+          snprintf(tilename, sizeof(tilename), "%s/%s", msDBFReadStringAttribute(tSHP->tileshpfile->hDBF, i, layer->tileitemindex) , layer->data);
+          filename = tilename;
         }
 
         if(strlen(filename) == 0) continue; /* check again */
@@ -2051,18 +2029,17 @@ int msTiledSHPWhichShapes(layerObj *layer, rectObj rect, int isQuery)
         try_open = msTiledSHPTryOpen(tSHP->shpfile, layer, tiFileAbsDir, filename);
         if( try_open == MS_DONE )
           continue;
-        else if (try_open == MS_FAILURE ) 
+        else if (try_open == MS_FAILURE )
           return(MS_FAILURE);
 
         status = msShapefileWhichShapes(tSHP->shpfile, rect, layer->debug);
         if(status == MS_DONE) {
-            /* Close and continue to next tile */
-            msShapefileClose(tSHP->shpfile);
-            continue;
-        }
-        else if(status != MS_SUCCESS) {
-            msShapefileClose(tSHP->shpfile);
-            return(MS_FAILURE);
+          /* Close and continue to next tile */
+          msShapefileClose(tSHP->shpfile);
+          continue;
+        } else if(status != MS_SUCCESS) {
+          msShapefileClose(tSHP->shpfile);
+          return(MS_FAILURE);
         }
 
         tSHP->tileshpfile->lastshape = i;
@@ -2079,17 +2056,17 @@ int msTiledSHPWhichShapes(layerObj *layer, rectObj rect, int isQuery)
   return(MS_FAILURE); /* should *never* get here */
 }
 
-int msTiledSHPNextShape(layerObj *layer, shapeObj *shape) 
+int msTiledSHPNextShape(layerObj *layer, shapeObj *shape)
 {
   int i, status, filter_passed = MS_FALSE;
   char *filename, tilename[MS_MAXPATHLEN];
   char tiFileAbsDir[MS_MAXPATHLEN];
 
   msTiledSHPLayerInfo *tSHP=NULL;
-  
+
   if ( msCheckParentPointer(layer->map,"map")==MS_FAILURE )
     return MS_FAILURE;
-  
+
   tSHP = layer->layerinfo;
   if(!tSHP) {
     msSetError(MS_SHPERR, "Tiled shapefile layer has not been opened.", "msTiledSHPNextShape()");
@@ -2101,27 +2078,27 @@ int msTiledSHPNextShape(layerObj *layer, shapeObj *shape)
   do {
     i = tSHP->shpfile->lastshape + 1;
     while(i<tSHP->shpfile->numshapes && !msGetBit(tSHP->shpfile->status,i)) i++; /* next "in" shape */
-    
+
     if(i == tSHP->shpfile->numshapes) { /* done with this tile, need a new one */
       msShapefileClose(tSHP->shpfile); /* clean up */
-       
+
       /* position the source to the NEXT shapefile based on the tileindex */
       if(tSHP->tilelayerindex != -1) { /* does the tileindex reference another layer */
         layerObj *tlp;
         shapeObj tshape;
         int try_open;
-        
+
         tlp = (GET_LAYER(layer->map, tSHP->tilelayerindex));
 
         msInitShape(&tshape);
         while((status = msLayerNextShape(tlp, &tshape)) == MS_SUCCESS) {
- 
+
           /* TODO: seems stupid to read the tileitem seperately from the shape, need to fix msTiledSHPOpenFile */
           if(!layer->data) /* assume whole filename is in attribute field */
             filename = (char *) msDBFReadStringAttribute(tSHP->tileshpfile->hDBF, tshape.index, layer->tileitemindex);
           else {
             snprintf(tilename, sizeof(tilename),"%s/%s", msDBFReadStringAttribute(tSHP->tileshpfile->hDBF, tshape.index, layer->tileitemindex) , layer->data);
-	    filename = tilename;
+            filename = tilename;
           }
 
           if(strlen(filename) == 0) continue; /* check again */
@@ -2129,7 +2106,7 @@ int msTiledSHPNextShape(layerObj *layer, shapeObj *shape)
           try_open = msTiledSHPTryOpen(tSHP->shpfile, layer, tiFileAbsDir, filename);
           if( try_open == MS_DONE )
             continue;
-          else if (try_open == MS_FAILURE ) 
+          else if (try_open == MS_FAILURE )
             return(MS_FAILURE);
 
           status = msShapefileWhichShapes(tSHP->shpfile, tSHP->tileshpfile->statusbounds, layer->debug);
@@ -2146,10 +2123,10 @@ int msTiledSHPNextShape(layerObj *layer, shapeObj *shape)
           /* tSHP->tileshpfile->lastshape = tshape.index; */
           break;
         }
-        
+
         if(status == MS_DONE) return(MS_DONE); /* no more tiles */
         else {
-          msFreeShape(&tshape); 
+          msFreeShape(&tshape);
           continue; /* we've got shapes */
         }
 
@@ -2158,20 +2135,20 @@ int msTiledSHPNextShape(layerObj *layer, shapeObj *shape)
         for(i=(tSHP->tileshpfile->lastshape + 1); i<tSHP->tileshpfile->numshapes; i++) {
           if(msGetBit(tSHP->tileshpfile->status,i)) {
             int try_open;
-            
+
             if(!layer->data) /* assume whole filename is in attribute field */
               filename = (char*)msDBFReadStringAttribute(tSHP->tileshpfile->hDBF, i, layer->tileitemindex);
-            else {  
+            else {
               snprintf(tilename, sizeof(tilename),"%s/%s", msDBFReadStringAttribute(tSHP->tileshpfile->hDBF, i, layer->tileitemindex) , layer->data);
               filename = tilename;
-	          }
+            }
 
             if(strlen(filename) == 0) continue; /* check again */
 
             try_open = msTiledSHPTryOpen(tSHP->shpfile, layer, tiFileAbsDir, filename);
             if( try_open == MS_DONE )
               continue;
-            else if (try_open == MS_FAILURE ) 
+            else if (try_open == MS_FAILURE )
               return(MS_FAILURE);
 
             status = msShapefileWhichShapes(tSHP->shpfile, tSHP->tileshpfile->statusbounds, layer->debug);
@@ -2183,33 +2160,34 @@ int msTiledSHPNextShape(layerObj *layer, shapeObj *shape)
               msShapefileClose(tSHP->shpfile);
               return(MS_FAILURE);
             }
-	  
+
             tSHP->tileshpfile->lastshape = i;
             break;
-	  }
+          }
         } /* end for loop */
-      
+
         if(i == tSHP->tileshpfile->numshapes) return(MS_DONE); /* no more tiles */
         else continue; /* we've got shapes */
       }
     }
-    
+
     tSHP->shpfile->lastshape = i;
- 
+
     msSHPReadShape(tSHP->shpfile->hSHP, i, shape);
     if(shape->type == MS_SHAPE_NULL) {
       msFreeShape(shape);
       continue; /* skip NULL shapes */
     }
     shape->tileindex = tSHP->tileshpfile->lastshape;
-    shape->values = msDBFGetValueList(tSHP->shpfile->hDBF, i, layer->iteminfo, layer->numitems);
     shape->numvalues = layer->numitems;
+    shape->values = msDBFGetValueList(tSHP->shpfile->hDBF, i, layer->iteminfo, layer->numitems);
+    if(!shape->values) shape->numvalues = 0;
 
     filter_passed = MS_TRUE;  /* By default accept ANY shape */
     if(layer->numitems > 0 && layer->iteminfo) {
       filter_passed = msEvalExpression(layer, shape, &(layer->filter), layer->filteritemindex);
     }
-    
+
     if(!filter_passed) msFreeShape(shape); /* free's values as well */
 
   } while(!filter_passed);  /* Loop until both spatial and attribute filters match  */
@@ -2217,7 +2195,7 @@ int msTiledSHPNextShape(layerObj *layer, shapeObj *shape)
   return(MS_SUCCESS);
 }
 
-int msTiledSHPGetShape(layerObj *layer, shapeObj *shape, resultObj *record) 
+int msTiledSHPGetShape(layerObj *layer, shapeObj *shape, resultObj *record)
 {
   char *filename, tilename[MS_MAXPATHLEN], szPath[MS_MAXPATHLEN];
 
@@ -2226,7 +2204,7 @@ int msTiledSHPGetShape(layerObj *layer, shapeObj *shape, resultObj *record)
 
   long shapeindex = record->shapeindex;
   int tileindex = record->tileindex;
-  
+
   if ( msCheckParentPointer(layer->map,"map")==MS_FAILURE )
     return MS_FAILURE;
 
@@ -2243,20 +2221,20 @@ int msTiledSHPGetShape(layerObj *layer, shapeObj *shape, resultObj *record)
 
     if(!layer->data) /* assume whole filename is in attribute field */
       filename = (char*) msDBFReadStringAttribute(tSHP->tileshpfile->hDBF, tileindex, layer->tileitemindex);
-    else {  
+    else {
       snprintf(tilename, sizeof(tilename), "%s/%s", msDBFReadStringAttribute(tSHP->tileshpfile->hDBF, tileindex, layer->tileitemindex) , layer->data);
       filename = tilename;
     }
-      
+
     /* open the shapefile, since a specific tile was request an error should be generated if that tile does not exist */
     if(strlen(filename) == 0) return(MS_FAILURE);
-    if(msShapefileOpen(tSHP->shpfile, "rb", msBuildPath3(szPath, tiFileAbsDir, layer->map->shapepath, filename), MS_TRUE) == -1) { 
-      if(msShapefileOpen(tSHP->shpfile, "rb", msBuildPath3(szPath, layer->map->mappath, layer->map->shapepath, filename), MS_TRUE) == -1) { 
-        if(msShapefileOpen(tSHP->shpfile, "rb", msBuildPath(szPath, layer->map->mappath, filename), MS_TRUE) == -1) { 
-          return(MS_FAILURE); 
+    if(msShapefileOpen(tSHP->shpfile, "rb", msBuildPath3(szPath, tiFileAbsDir, layer->map->shapepath, filename), MS_TRUE) == -1) {
+      if(msShapefileOpen(tSHP->shpfile, "rb", msBuildPath3(szPath, layer->map->mappath, layer->map->shapepath, filename), MS_TRUE) == -1) {
+        if(msShapefileOpen(tSHP->shpfile, "rb", msBuildPath(szPath, layer->map->mappath, filename), MS_TRUE) == -1) {
+          return(MS_FAILURE);
         }
-      } 
-    }    
+      }
+    }
 
   }
 
@@ -2276,26 +2254,26 @@ int msTiledSHPGetShape(layerObj *layer, shapeObj *shape, resultObj *record)
   return(MS_SUCCESS);
 }
 
-void msTiledSHPClose(layerObj *layer) 
-{  
+void msTiledSHPClose(layerObj *layer)
+{
   msTiledSHPLayerInfo *tSHP=NULL;
 
   tSHP = layer->layerinfo;
   if(tSHP) {
     msShapefileClose(tSHP->shpfile);
     free(tSHP->shpfile);
-  
+
     if(tSHP->tilelayerindex != -1) {
       layerObj *tlp;
-	  if ( msCheckParentPointer(layer->map,"map")==MS_FAILURE )
-	    return;
+      if ( msCheckParentPointer(layer->map,"map")==MS_FAILURE )
+        return;
       tlp = (GET_LAYER(layer->map, tSHP->tilelayerindex));
       msLayerClose(tlp);
-    } else { 
+    } else {
       msShapefileClose(tSHP->tileshpfile);
       free(tSHP->tileshpfile);
     }
-			
+
     free(tSHP);
   }
   layer->layerinfo = NULL;
@@ -2304,7 +2282,7 @@ void msTiledSHPClose(layerObj *layer)
 /*                              msTiledSHPClose()                       */
 /* Overloaded version of msTiledSHPClose for virtual table architecture */
 /************************************************************************/
-int msTiledSHPCloseVT(layerObj *layer) 
+int msTiledSHPCloseVT(layerObj *layer)
 {
   msTiledSHPClose(layer);
   return MS_SUCCESS;
@@ -2337,61 +2315,59 @@ int msTiledSHPLayerInitItemInfo(layerObj *layer)
 
 static void msSHPPassThroughFieldDefinitions( layerObj *layer, DBFHandle hDBF )
 {
-    int numitems, i;
-  
-    numitems = msDBFGetFieldCount( hDBF );
-
-    for(i=0;i<numitems;i++)
-    {
-        char item[16];
-        int  nWidth=0, nPrecision=0;
-        char md_item_name[64];
-        char gml_width[32], gml_precision[32];
-        DBFFieldType eType;
-        const char *gml_type = NULL;
-
-        eType = msDBFGetFieldInfo( hDBF, i, item, &nWidth, &nPrecision );
-        
-        gml_width[0] = '\0';
-        gml_precision[0] = '\0';
-
-        switch( eType )
-        {
-          case FTInteger:
-            gml_type = "Integer";
-            sprintf( gml_width, "%d", nWidth ); 
-            break;
+  int numitems, i;
 
-          case FTDouble:
-            gml_type = "Real";
-            sprintf( gml_width, "%d", nWidth ); 
-            sprintf( gml_precision, "%d", nPrecision ); 
-            break;
+  numitems = msDBFGetFieldCount( hDBF );
 
-          case FTString:
-          default:
-            gml_type = "Character";
-            sprintf( gml_width, "%d", nWidth ); 
-            break;
-        }
+  for(i=0; i<numitems; i++) {
+    char item[16];
+    int  nWidth=0, nPrecision=0;
+    char md_item_name[64];
+    char gml_width[32], gml_precision[32];
+    DBFFieldType eType;
+    const char *gml_type = NULL;
+
+    eType = msDBFGetFieldInfo( hDBF, i, item, &nWidth, &nPrecision );
+
+    gml_width[0] = '\0';
+    gml_precision[0] = '\0';
+
+    switch( eType ) {
+      case FTInteger:
+        gml_type = "Integer";
+        sprintf( gml_width, "%d", nWidth );
+        break;
+
+      case FTDouble:
+        gml_type = "Real";
+        sprintf( gml_width, "%d", nWidth );
+        sprintf( gml_precision, "%d", nPrecision );
+        break;
 
-        snprintf( md_item_name, sizeof(md_item_name), "gml_%s_type", item );
-        if( msOWSLookupMetadata(&(layer->metadata), "G", "type") == NULL )
-            msInsertHashTable(&(layer->metadata), md_item_name, gml_type );
-        
-        snprintf( md_item_name, sizeof(md_item_name), "gml_%s_width", item );
-        if( strlen(gml_width) > 0 
-            && msOWSLookupMetadata(&(layer->metadata), "G", "width") == NULL )
-            msInsertHashTable(&(layer->metadata), md_item_name, gml_width );
-
-        snprintf( md_item_name, sizeof(md_item_name), "gml_%s_precision",item );
-        if( strlen(gml_precision) > 0 
-            && msOWSLookupMetadata(&(layer->metadata), "G", "precision")==NULL )
-            msInsertHashTable(&(layer->metadata), md_item_name, gml_precision );
+      case FTString:
+      default:
+        gml_type = "Character";
+        sprintf( gml_width, "%d", nWidth );
+        break;
     }
+
+    snprintf( md_item_name, sizeof(md_item_name), "gml_%s_type", item );
+    if( msOWSLookupMetadata(&(layer->metadata), "G", "type") == NULL )
+      msInsertHashTable(&(layer->metadata), md_item_name, gml_type );
+
+    snprintf( md_item_name, sizeof(md_item_name), "gml_%s_width", item );
+    if( strlen(gml_width) > 0
+        && msOWSLookupMetadata(&(layer->metadata), "G", "width") == NULL )
+      msInsertHashTable(&(layer->metadata), md_item_name, gml_width );
+
+    snprintf( md_item_name, sizeof(md_item_name), "gml_%s_precision",item );
+    if( strlen(gml_precision) > 0
+        && msOWSLookupMetadata(&(layer->metadata), "G", "precision")==NULL )
+      msInsertHashTable(&(layer->metadata), md_item_name, gml_precision );
+  }
 }
 
-int msTiledSHPLayerGetItems(layerObj *layer) 
+int msTiledSHPLayerGetItems(layerObj *layer)
 {
   msTiledSHPLayerInfo *tSHP=NULL;
   const char *value;
@@ -2403,20 +2379,20 @@ int msTiledSHPLayerGetItems(layerObj *layer)
   }
 
   layer->numitems = msDBFGetFieldCount(tSHP->shpfile->hDBF);
-  layer->items = msDBFGetItems(tSHP->shpfile->hDBF);    
+  layer->items = msDBFGetItems(tSHP->shpfile->hDBF);
   if(!layer->items) return MS_FAILURE;
 
-/* -------------------------------------------------------------------- */
-/*      consider populating the field definitions in metadata.          */
-/* -------------------------------------------------------------------- */
+  /* -------------------------------------------------------------------- */
+  /*      consider populating the field definitions in metadata.          */
+  /* -------------------------------------------------------------------- */
   if((value = msOWSLookupMetadata(&(layer->metadata), "G", "types")) != NULL
-     && strcasecmp(value,"auto") == 0 )
-      msSHPPassThroughFieldDefinitions( layer, tSHP->shpfile->hDBF );
+      && strcasecmp(value,"auto") == 0 )
+    msSHPPassThroughFieldDefinitions( layer, tSHP->shpfile->hDBF );
 
   return msTiledSHPLayerInitItemInfo(layer);
 }
 
-int msTiledSHPLayerGetExtent(layerObj *layer, rectObj *extent) 
+int msTiledSHPLayerGetExtent(layerObj *layer, rectObj *extent)
 {
   msTiledSHPLayerInfo *tSHP=NULL;
 
@@ -2455,7 +2431,8 @@ int msTiledSHPLayerInitializeVirtualTable(layerObj *layer)
   layer->vtable->LayerIsOpen = msTiledSHPLayerIsOpen;
   layer->vtable->LayerWhichShapes = msTiledSHPWhichShapes;
   layer->vtable->LayerNextShape = msTiledSHPNextShape;
-  // layer->vtable->LayerResultsGetShape = msTiledSHPGetShape; /* no special version, use ...GetShape() */
+  /* no special version, use ...GetShape() */
+  /* layer->vtable->LayerResultsGetShape = msTiledSHPGetShape; */
   layer->vtable->LayerGetShape = msTiledSHPGetShape;
   layer->vtable->LayerClose = msTiledSHPCloseVT;
   layer->vtable->LayerGetItems = msTiledSHPLayerGetItems;
@@ -2473,15 +2450,15 @@ int msTiledSHPLayerInitializeVirtualTable(layerObj *layer)
 
 /* SHAPEFILE Layer virtual table functions */
 
-void msSHPLayerFreeItemInfo(layerObj *layer) 
-{ 
+void msSHPLayerFreeItemInfo(layerObj *layer)
+{
   if(layer->iteminfo) {
     free(layer->iteminfo);
     layer->iteminfo = NULL;
   }
 }
 
-int msSHPLayerInitItemInfo(layerObj *layer) 
+int msSHPLayerInitItemInfo(layerObj *layer)
 {
   shapefileObj *shpfile = shpfile = layer->layerinfo;
   if( ! shpfile) {
@@ -2505,14 +2482,14 @@ int msSHPLayerOpen(layerObj *layer)
   shapefileObj *shpfile;
 
   if(layer->layerinfo) return MS_SUCCESS; /* layer already open */
-    
+
   /* allocate space for a shapefileObj using layer->layerinfo  */
   shpfile = (shapefileObj *) malloc(sizeof(shapefileObj));
   MS_CHECK_ALLOC(shpfile, sizeof(shapefileObj), MS_FAILURE);
 
-    if ( msCheckParentPointer(layer->map,"map")==MS_FAILURE )
-		return MS_FAILURE;
-    
+  if ( msCheckParentPointer(layer->map,"map")==MS_FAILURE )
+    return MS_FAILURE;
+
 
   layer->layerinfo = shpfile;
 
@@ -2523,7 +2500,7 @@ int msSHPLayerOpen(layerObj *layer)
       return MS_FAILURE;
     }
   }
-    
+
   return MS_SUCCESS;
 }
 
@@ -2537,7 +2514,6 @@ int msSHPLayerIsOpen(layerObj *layer)
 
 int msSHPLayerWhichShapes(layerObj *layer, rectObj rect, int isQuery)
 {
-  int i, n1=0, n2=0;
   int status;
   shapefileObj *shpfile;
 
@@ -2553,23 +2529,10 @@ int msSHPLayerWhichShapes(layerObj *layer, rectObj rect, int isQuery)
     return status;
   }
 
-  /* now apply the maxshapes criteria (NOTE: this ignores the filter so you could get less than maxfeatures) */
-  if(layer->maxfeatures > 0) {
-
-    for( i = (shpfile->numshapes - 1); i >= 0; i-- ) {
-      n2 = msGetBit(shpfile->status, i);
-      n1 += n2;
-      if( n2 && n1 > layer->maxfeatures ) {
-        msSetBit(shpfile->status, i, 0);
-      }
-    }
-
-  }
-    
   return MS_SUCCESS;
 }
 
-int msSHPLayerNextShape(layerObj *layer, shapeObj *shape) 
+int msSHPLayerNextShape(layerObj *layer, shapeObj *shape)
 {
   int i, filter_passed=MS_FALSE;
   shapefileObj *shpfile;
@@ -2579,8 +2542,8 @@ int msSHPLayerNextShape(layerObj *layer, shapeObj *shape)
   if(!shpfile) {
     msSetError(MS_SHPERR, "Shapefile layer has not been opened.", "msSHPLayerNextShape()");
     return MS_FAILURE;
-  }    
-  
+  }
+
   do {
     i = msGetNextBit(shpfile->status, shpfile->lastshape + 1, shpfile->numshapes);
     shpfile->lastshape = i;
@@ -2591,8 +2554,11 @@ int msSHPLayerNextShape(layerObj *layer, shapeObj *shape)
       msFreeShape(shape);
       continue; /* skip NULL shapes */
     }
-    shape->values = msDBFGetValueList(shpfile->hDBF, i, layer->iteminfo, layer->numitems);
     shape->numvalues = layer->numitems;
+    shape->values = msDBFGetValueList(shpfile->hDBF, i, layer->iteminfo, layer->numitems);
+    if(!shape->values) {
+      shape->numvalues = 0;
+    }
 
     filter_passed = MS_TRUE;  /* By default accept ANY shape */
     if(layer->numitems > 0 && layer->iteminfo) {
@@ -2632,23 +2598,25 @@ int msSHPLayerGetShape(layerObj *layer, shapeObj *shape, resultObj *record)
     if(!shape->values) return MS_FAILURE;
   }
 
+  shpfile->lastshape = shapeindex;
+
   return MS_SUCCESS;
 }
 
-int msSHPLayerClose(layerObj *layer) 
+int msSHPLayerClose(layerObj *layer)
 {
   shapefileObj *shpfile;
   shpfile = layer->layerinfo;
-  if(!shpfile) return MS_SUCCESS; /* nothing to do */ 
+  if(!shpfile) return MS_SUCCESS; /* nothing to do */
 
   msShapefileClose(shpfile);
   free(layer->layerinfo);
   layer->layerinfo = NULL;
 
-  return MS_SUCCESS; 
+  return MS_SUCCESS;
 }
 
-int msSHPLayerGetItems(layerObj *layer) 
+int msSHPLayerGetItems(layerObj *layer)
 {
   shapefileObj *shpfile;
   const char *value;
@@ -2665,17 +2633,17 @@ int msSHPLayerGetItems(layerObj *layer)
   if(layer->numitems == 0) return MS_SUCCESS; /* No items is a valid case (#3147) */
   if(!layer->items) return MS_FAILURE;
 
-/* -------------------------------------------------------------------- */
-/*      consider populating the field definitions in metadata.          */
-/* -------------------------------------------------------------------- */
+  /* -------------------------------------------------------------------- */
+  /*      consider populating the field definitions in metadata.          */
+  /* -------------------------------------------------------------------- */
   if((value = msOWSLookupMetadata(&(layer->metadata), "G", "types")) != NULL
-     && strcasecmp(value,"auto") == 0 )
-      msSHPPassThroughFieldDefinitions( layer, shpfile->hDBF );
+      && strcasecmp(value,"auto") == 0 )
+    msSHPPassThroughFieldDefinitions( layer, shpfile->hDBF );
 
   return msLayerInitItemInfo(layer);
 }
 
-int msSHPLayerGetExtent(layerObj *layer, rectObj *extent) 
+int msSHPLayerGetExtent(layerObj *layer, rectObj *extent)
 {
   *extent = ((shapefileObj*)layer->layerinfo)->bounds;
   return MS_SUCCESS;
diff --git a/mapshape.h b/mapshape.h
index 94168d7..6d9f004 100644
--- a/mapshape.h
+++ b/mapshape.h
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -42,7 +42,7 @@ extern "C" {
 #ifndef SWIG
 #define MS_PATH_LENGTH 1024
 
-/* Shapefile types */
+  /* Shapefile types */
 #define SHP_POINT 1
 #define SHP_ARC 3
 #define SHP_POLYGON 5
@@ -75,162 +75,161 @@ extern "C" {
 #define MS_SHP_MULTIPOINTM 28
 
 #ifndef SWIG
-typedef unsigned char uchar;
+  typedef unsigned char uchar;
 
-typedef	struct {
-    FILE	*fpSHP;
-    FILE	*fpSHX;
+  typedef struct {
+    FILE  *fpSHP;
+    FILE  *fpSHX;
 
-    int		nShapeType;				/* SHPT_* */
-    int		nFileSize;				/* SHP file */
+    int   nShapeType;       /* SHPT_* */
+    int   nFileSize;        /* SHP file */
 
-    int		nRecords;
-    int		nMaxRecords;
+    int   nRecords;
+    int   nMaxRecords;
 
-    int		*panRecOffset;
-    int		*panRecSize;
+    int   *panRecOffset;
+    int   *panRecSize;
     ms_bitarray panRecLoaded;
     int   panRecAllLoaded;
 
-    double	adBoundsMin[4];
-    double	adBoundsMax[4];
+    double  adBoundsMin[4];
+    double  adBoundsMax[4];
 
-    int		bUpdated;
+    int   bUpdated;
 
-    int		nBufSize; /* these used static vars in shape readers, moved to be thread-safe */
+    int   nBufSize; /* these used static vars in shape readers, moved to be thread-safe */
     uchar   *pabyRec;
-    int		nPartMax;
-    int		*panParts;
+    int   nPartMax;
+    int   *panParts;
 
-} SHPInfo;
-typedef SHPInfo * SHPHandle;
+  } SHPInfo;
+  typedef SHPInfo * SHPHandle;
 #endif
 
 
 
-typedef	struct
-{
+  typedef struct {
 #ifdef SWIG
-%immutable;
+    %immutable;
 #endif
-    FILE	*fp;
+    FILE  *fp;
 
-    int		nRecords;
+    int   nRecords;
 
     unsigned int nRecordLength;
-    int		nHeaderLength;
-    int		nFields;
-    int		*panFieldOffset;
-    int		*panFieldSize;
-    int		*panFieldDecimals;
-    char	*pachFieldType;
-
-    char	*pszHeader;
-
-    int		nCurrentRecord;
-    int		bCurrentRecordModified;
-    char	*pszCurrentRecord;
-    
-    int		bNoHeader;
-    int		bUpdated;
-
-    char 	*pszStringField;
-    int		nStringFieldLen;    
+    int   nHeaderLength;
+    int   nFields;
+    int   *panFieldOffset;
+    int   *panFieldSize;
+    int   *panFieldDecimals;
+    char  *pachFieldType;
+
+    char  *pszHeader;
+
+    int   nCurrentRecord;
+    int   bCurrentRecordModified;
+    char  *pszCurrentRecord;
+
+    int   bNoHeader;
+    int   bUpdated;
+
+    char  *pszStringField;
+    int   nStringFieldLen;
 #ifdef SWIG
-%mutable;
+    %mutable;
 #endif
-} DBFInfo;
-typedef DBFInfo * DBFHandle;
+  } DBFInfo;
+  typedef DBFInfo * DBFHandle;
 
-typedef enum {FTString, FTInteger, FTDouble, FTInvalid} DBFFieldType;
+  typedef enum {FTString, FTInteger, FTDouble, FTInvalid} DBFFieldType;
 
-/* Shapefile object, no write access via scripts */
-typedef struct {
+  /* Shapefile object, no write access via scripts */
+  typedef struct {
 #ifdef SWIG
-%immutable;
+    %immutable;
 #endif
-  char source[MS_PATH_LENGTH]; /* full path to this file data */
+    char source[MS_PATH_LENGTH]; /* full path to this file data */
 
 #ifndef SWIG
-  SHPHandle hSHP; /* SHP/SHX file pointer */
+    SHPHandle hSHP; /* SHP/SHX file pointer */
 #endif
 
-  int type; /* shapefile type */
-  int numshapes; /* number of shapes */
-  rectObj bounds; /* shape extent */
+    int type; /* shapefile type */
+    int numshapes; /* number of shapes */
+    rectObj bounds; /* shape extent */
 
 #ifndef SWIG
-  DBFHandle hDBF; /* DBF file pointer */
+    DBFHandle hDBF; /* DBF file pointer */
 #endif
 
-  int lastshape;
+    int lastshape;
 
-  ms_bitarray status;
-  rectObj statusbounds; /* holds extent associated with the status vector */
+    ms_bitarray status;
+    rectObj statusbounds; /* holds extent associated with the status vector */
 
-  int isopen;
+    int isopen;
 #ifdef SWIG
-%mutable;
+    %mutable;
 #endif
-} shapefileObj;
+  } shapefileObj;
 
 #ifndef SWIG
-/* layerInfo structure for tiled shapefiles */
-typedef struct { 
-  shapefileObj *shpfile;
-  shapefileObj *tileshpfile;
-  int tilelayerindex;
-} msTiledSHPLayerInfo;
-
-/* shapefileObj function prototypes  */
-MS_DLL_EXPORT int msShapefileOpen(shapefileObj *shpfile, char *mode, char *filename, int log_failures);
-MS_DLL_EXPORT int msShapefileCreate(shapefileObj *shpfile, char *filename, int type);
-MS_DLL_EXPORT void msShapefileClose(shapefileObj *shpfile);
-MS_DLL_EXPORT int msShapefileWhichShapes(shapefileObj *shpfile, rectObj rect, int debug);
-
-/* SHP/SHX function prototypes */
-MS_DLL_EXPORT SHPHandle msSHPOpen( const char * pszShapeFile, const char * pszAccess );
-MS_DLL_EXPORT SHPHandle msSHPCreate( const char * pszShapeFile, int nShapeType );
-MS_DLL_EXPORT void msSHPClose( SHPHandle hSHP );
-MS_DLL_EXPORT void msSHPGetInfo( SHPHandle hSHP, int * pnEntities, int * pnShapeType );
-MS_DLL_EXPORT int msSHPReadBounds( SHPHandle psSHP, int hEntity, rectObj *padBounds );
-MS_DLL_EXPORT void msSHPReadShape( SHPHandle psSHP, int hEntity, shapeObj *shape );
-MS_DLL_EXPORT int msSHPReadPoint(SHPHandle psSHP, int hEntity, pointObj *point );
-MS_DLL_EXPORT int msSHPWriteShape( SHPHandle psSHP, shapeObj *shape );
-MS_DLL_EXPORT int msSHPWritePoint(SHPHandle psSHP, pointObj *point );
-/* SHX reading */
-MS_DLL_EXPORT int msSHXLoadAll( SHPHandle psSHP );
-MS_DLL_EXPORT int msSHXLoadPage( SHPHandle psSHP, int shxBufferPage );
-MS_DLL_EXPORT int msSHXReadOffset( SHPHandle psSHP, int hEntity );
-MS_DLL_EXPORT int msSHXReadSize( SHPHandle psSHP, int hEntity );
-
-
-/* tiledShapefileObj function prototypes are in mapserver.h */
-
-/* XBase function prototypes */
-MS_DLL_EXPORT DBFHandle msDBFOpen( const char * pszDBFFile, const char * pszAccess );
-MS_DLL_EXPORT void msDBFClose( DBFHandle hDBF );
-MS_DLL_EXPORT DBFHandle msDBFCreate( const char * pszDBFFile );
-
-MS_DLL_EXPORT int msDBFGetFieldCount( DBFHandle psDBF );
-MS_DLL_EXPORT int msDBFGetRecordCount( DBFHandle psDBF );
-MS_DLL_EXPORT int msDBFAddField( DBFHandle hDBF, const char * pszFieldName, DBFFieldType eType, int nWidth, int nDecimals );
-
-MS_DLL_EXPORT DBFFieldType msDBFGetFieldInfo( DBFHandle psDBF, int iField, char * pszFieldName, int * pnWidth, int * pnDecimals );
-
-MS_DLL_EXPORT int msDBFReadIntegerAttribute( DBFHandle hDBF, int iShape, int iField );
-MS_DLL_EXPORT double msDBFReadDoubleAttribute( DBFHandle hDBF, int iShape, int iField );
-MS_DLL_EXPORT const char *msDBFReadStringAttribute( DBFHandle hDBF, int iShape, int iField );
-
-MS_DLL_EXPORT int msDBFWriteIntegerAttribute( DBFHandle hDBF, int iShape, int iField, int nFieldValue );
-MS_DLL_EXPORT int msDBFWriteDoubleAttribute( DBFHandle hDBF, int iShape, int iField, double dFieldValue );
-MS_DLL_EXPORT int msDBFWriteStringAttribute( DBFHandle hDBF, int iShape, int iField, const char * pszFieldValue );
-
-MS_DLL_EXPORT char **msDBFGetItems(DBFHandle dbffile);
-MS_DLL_EXPORT char **msDBFGetValues(DBFHandle dbffile, int record);
-MS_DLL_EXPORT char **msDBFGetValueList(DBFHandle dbffile, int record, int *itemindexes, int numitems);
-MS_DLL_EXPORT int *msDBFGetItemIndexes(DBFHandle dbffile, char **items, int numitems);
-MS_DLL_EXPORT int msDBFGetItemIndex(DBFHandle dbffile, char *name);
+  /* layerInfo structure for tiled shapefiles */
+  typedef struct {
+    shapefileObj *shpfile;
+    shapefileObj *tileshpfile;
+    int tilelayerindex;
+  } msTiledSHPLayerInfo;
+
+  /* shapefileObj function prototypes  */
+  MS_DLL_EXPORT int msShapefileOpen(shapefileObj *shpfile, char *mode, char *filename, int log_failures);
+  MS_DLL_EXPORT int msShapefileCreate(shapefileObj *shpfile, char *filename, int type);
+  MS_DLL_EXPORT void msShapefileClose(shapefileObj *shpfile);
+  MS_DLL_EXPORT int msShapefileWhichShapes(shapefileObj *shpfile, rectObj rect, int debug);
+
+  /* SHP/SHX function prototypes */
+  MS_DLL_EXPORT SHPHandle msSHPOpen( const char * pszShapeFile, const char * pszAccess );
+  MS_DLL_EXPORT SHPHandle msSHPCreate( const char * pszShapeFile, int nShapeType );
+  MS_DLL_EXPORT void msSHPClose( SHPHandle hSHP );
+  MS_DLL_EXPORT void msSHPGetInfo( SHPHandle hSHP, int * pnEntities, int * pnShapeType );
+  MS_DLL_EXPORT int msSHPReadBounds( SHPHandle psSHP, int hEntity, rectObj *padBounds );
+  MS_DLL_EXPORT void msSHPReadShape( SHPHandle psSHP, int hEntity, shapeObj *shape );
+  MS_DLL_EXPORT int msSHPReadPoint(SHPHandle psSHP, int hEntity, pointObj *point );
+  MS_DLL_EXPORT int msSHPWriteShape( SHPHandle psSHP, shapeObj *shape );
+  MS_DLL_EXPORT int msSHPWritePoint(SHPHandle psSHP, pointObj *point );
+  /* SHX reading */
+  MS_DLL_EXPORT int msSHXLoadAll( SHPHandle psSHP );
+  MS_DLL_EXPORT int msSHXLoadPage( SHPHandle psSHP, int shxBufferPage );
+  MS_DLL_EXPORT int msSHXReadOffset( SHPHandle psSHP, int hEntity );
+  MS_DLL_EXPORT int msSHXReadSize( SHPHandle psSHP, int hEntity );
+
+
+  /* tiledShapefileObj function prototypes are in mapserver.h */
+
+  /* XBase function prototypes */
+  MS_DLL_EXPORT DBFHandle msDBFOpen( const char * pszDBFFile, const char * pszAccess );
+  MS_DLL_EXPORT void msDBFClose( DBFHandle hDBF );
+  MS_DLL_EXPORT DBFHandle msDBFCreate( const char * pszDBFFile );
+
+  MS_DLL_EXPORT int msDBFGetFieldCount( DBFHandle psDBF );
+  MS_DLL_EXPORT int msDBFGetRecordCount( DBFHandle psDBF );
+  MS_DLL_EXPORT int msDBFAddField( DBFHandle hDBF, const char * pszFieldName, DBFFieldType eType, int nWidth, int nDecimals );
+
+  MS_DLL_EXPORT DBFFieldType msDBFGetFieldInfo( DBFHandle psDBF, int iField, char * pszFieldName, int * pnWidth, int * pnDecimals );
+
+  MS_DLL_EXPORT int msDBFReadIntegerAttribute( DBFHandle hDBF, int iShape, int iField );
+  MS_DLL_EXPORT double msDBFReadDoubleAttribute( DBFHandle hDBF, int iShape, int iField );
+  MS_DLL_EXPORT const char *msDBFReadStringAttribute( DBFHandle hDBF, int iShape, int iField );
+
+  MS_DLL_EXPORT int msDBFWriteIntegerAttribute( DBFHandle hDBF, int iShape, int iField, int nFieldValue );
+  MS_DLL_EXPORT int msDBFWriteDoubleAttribute( DBFHandle hDBF, int iShape, int iField, double dFieldValue );
+  MS_DLL_EXPORT int msDBFWriteStringAttribute( DBFHandle hDBF, int iShape, int iField, const char * pszFieldValue );
+
+  MS_DLL_EXPORT char **msDBFGetItems(DBFHandle dbffile);
+  MS_DLL_EXPORT char **msDBFGetValues(DBFHandle dbffile, int record);
+  MS_DLL_EXPORT char **msDBFGetValueList(DBFHandle dbffile, int record, int *itemindexes, int numitems);
+  MS_DLL_EXPORT int *msDBFGetItemIndexes(DBFHandle dbffile, char **items, int numitems);
+  MS_DLL_EXPORT int msDBFGetItemIndex(DBFHandle dbffile, char *name);
 
 #endif
 
diff --git a/mapstring.c b/mapstring.c
index 232d9e3..0ea53aa 100644
--- a/mapstring.c
+++ b/mapstring.c
@@ -6,7 +6,7 @@
  * Author:   Steve Lime and the MapServer team.
  *
  * Notes: A couple of string handling functions (strrstr, strlcat) were taken from
- * other sources. Copyright notices accompany those functions below. 
+ * other sources. Copyright notices accompany those functions below.
  *
  ******************************************************************************
  * Copyright (c) 1996-2005 Regents of the University of Minnesota.
@@ -19,7 +19,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -33,7 +33,7 @@
 
 #include "mapserver.h"
 
-MS_CVSID("$Id$")
+
 
 #include <ctype.h>
 #include <string.h>
@@ -60,7 +60,7 @@ MS_CVSID("$Id$")
 #include "mapentities.h"
 
 #ifdef NEED_STRRSTR
-/* 
+/*
 ** Copyright (c) 2000-2004  University of Illinois Board of Trustees
 ** Copyright (c) 2000-2005  Mark D. Roth
 ** All rights reserved.
@@ -75,14 +75,14 @@ MS_CVSID("$Id$")
 ** distribute, sublicense, and/or sell copies of the Software, and to
 ** permit persons to whom the Software is furnished to do so, subject to
 ** the following conditions:
-** 
+**
 ** * Redistributions of source code must retain the above copyright
 **   notice, this list of conditions and the following disclaimers.
 **
 ** * Redistributions in binary form must reproduce the above copyright
 **   notice, this list of conditions and the following disclaimers in the
 **   documentation and/or other materials provided with the distribution.
-** 
+**
 ** * Neither the names of Campus Information Technologies and Educational
 **   Services, University of Illinois at Urbana-Champaign, nor the names
 **   of its contributors may be used to endorse or promote products derived
@@ -202,34 +202,34 @@ size_t strlcat(char *dst, const char *src, size_t siz)
 size_t
 strlcpy(char *dst, const char *src, size_t siz)
 {
-        register char *d = dst;
-        register const char *s = src;
-        register size_t n = siz;
-
-        /* Copy as many bytes as will fit */
-        if (n != 0 && --n != 0) {
-                do {
-                        if ((*d++ = *s++) == 0)
-                                break;
-                } while (--n != 0);
-        }
+  register char *d = dst;
+  register const char *s = src;
+  register size_t n = siz;
 
-        /* Not enough room in dst, add NUL and traverse rest of src */
-        if (n == 0) {
-                if (siz != 0)
-                        *d = '\0';              /* NUL-terminate dst */
-                while (*s++)
-                        ;
-        }
+  /* Copy as many bytes as will fit */
+  if (n != 0 && --n != 0) {
+    do {
+      if ((*d++ = *s++) == 0)
+        break;
+    } while (--n != 0);
+  }
+
+  /* Not enough room in dst, add NUL and traverse rest of src */
+  if (n == 0) {
+    if (siz != 0)
+      *d = '\0';              /* NUL-terminate dst */
+    while (*s++)
+      ;
+  }
 
-        return(s - src - 1);    /* count does not include NUL */
+  return(s - src - 1);    /* count does not include NUL */
 }
 #endif
 
 #ifdef NEED_STRCASESTR
 /*-
  * Copyright (c) 1990, 1993
- *	The Regents of the University of California.  All rights reserved.
+ *  The Regents of the University of California.  All rights reserved.
  *
  * This code is derived from software contributed to Berkeley by
  * Chris Torek.
@@ -260,28 +260,28 @@ strlcpy(char *dst, const char *src, size_t siz)
  */
 char *strcasestr(const char *s, const char *find)
 {
-	char c, sc;
-	size_t len;
-
-	if ((c = *find++) != 0) {
-		c = tolower((unsigned char)c);
-		len = strlen(find);
-		do {
-			do {
-				if ((sc = *s++) == 0)
-					return (NULL);
-			} while ((char)tolower((unsigned char)sc) != c);
-		} while (strncasecmp(s, find, len) != 0);
-		s--;
-	}
-	return ((char *)s);
+  char c, sc;
+  size_t len;
+
+  if ((c = *find++) != 0) {
+    c = tolower((unsigned char)c);
+    len = strlen(find);
+    do {
+      do {
+        if ((sc = *s++) == 0)
+          return (NULL);
+      } while ((char)tolower((unsigned char)sc) != c);
+    } while (strncasecmp(s, find, len) != 0);
+    s--;
+  }
+  return ((char *)s);
 }
 #endif
 
 #ifdef NEED_STRDUP
-char	*strdup(char *s)
+char  *strdup(char *s)
 {
-  char	*s1;
+  char  *s1;
 
   if(!s)
     return(NULL);
@@ -302,27 +302,31 @@ int strncasecmp(const char *s1, const char *s2, int len)
 
   cp1 = s1;
   cp2 = s2;
-  if ((!*cp1) || (!*cp2 )) {
-    return (0);
-  }
-  while(*cp1 && *cp2 && len) 
-  {
-      if((cmp = (toupper(*cp1) - toupper(*cp2))) != 0)
-        return(cmp);
-      cp1++;
-      cp2++;
-      len--;
+
+  if(len == 0)
+    return(0);
+
+  if (!*cp1)
+    return -1;
+  else if (!*cp2)
+    return 1;
+
+  while(*cp1 && *cp2 && len) {
+    if((cmp = (toupper(*cp1) - toupper(*cp2))) != 0)
+      return(cmp);
+    cp1++;
+    cp2++;
+    len--;
   }
-  
+
   if(len == 0) {
     return(0);
   }
-  if(*cp1 || *cp2)
-  {
-      if (*cp1)
-        return(1);
-      else
-        return (-1);
+  if(*cp1 || *cp2) {
+    if (*cp1)
+      return(1);
+    else
+      return (-1);
   }
   return(0);
 }
@@ -339,26 +343,25 @@ int strcasecmp(const char *s1, const char *s2)
   if ((!cp1) || (!cp2 )) {
     return (0);
   }
-  while(*cp1 && *cp2) 
-  {
-     if((cmp = (toupper(*cp1) - toupper(*cp2))) != 0)
-        return(cmp);
+  while(*cp1 && *cp2) {
+    if((cmp = (toupper(*cp1) - toupper(*cp2))) != 0)
+      return(cmp);
     cp1++;
     cp2++;
   }
-  if(*cp1 || *cp2)
-  {
-      if (*cp1)
-        return(1);
-      else
-        return (-1);
+  if(*cp1 || *cp2) {
+    if (*cp1)
+      return(1);
+    else
+      return (-1);
   }
 
   return(0);
 }
 #endif
 
-char *msLongToString(long value) {
+char *msLongToString(long value)
+{
   size_t bufferSize = 256;
   char *buffer = (char*)msSmallMalloc(bufferSize);
 
@@ -366,7 +369,8 @@ char *msLongToString(long value) {
   return(buffer);
 }
 
-char *msDoubleToString(double value, int force_f) {
+char *msDoubleToString(double value, int force_f)
+{
   size_t bufferSize = 256;
   char *buffer = (char*)msSmallMalloc(bufferSize);
 
@@ -377,7 +381,8 @@ char *msDoubleToString(double value, int force_f) {
   return(buffer);
 }
 
-char *msIntToString(int value) {
+char *msIntToString(int value)
+{
   size_t bufferSize = 256;
   char *buffer = (char*)msSmallMalloc(bufferSize);
 
@@ -385,7 +390,8 @@ char *msIntToString(int value) {
   return(buffer);
 }
 
-void msStringToUpper(char *string) {
+void msStringToUpper(char *string)
+{
   int i;
 
   if (string != NULL) {
@@ -396,7 +402,8 @@ void msStringToUpper(char *string) {
   }
 }
 
-void msStringToLower(char *string) {
+void msStringToLower(char *string)
+{
   int i;
 
   if (string != NULL) {
@@ -407,7 +414,8 @@ void msStringToLower(char *string) {
   }
 }
 
-char *msStringChop(char *string) {  
+char *msStringChop(char *string)
+{
   int n;
 
   n = strlen(string);
@@ -422,28 +430,28 @@ char *msStringChop(char *string) {
 */
 void msStringTrim(char *str)
 {
-    int i;
+  int i;
 
-    /* Send nulls home without supper. */
-    if( ! str ) return;
+  /* Send nulls home without supper. */
+  if( ! str ) return;
 
-    /* Move non-white string to the front. */
-    i = strspn(str, " ");
-    if(i) {
-        memmove(str, str + i, strlen(str) - i + 1);
-    }
-    /* Nothing left? Exit. */
-    if(strlen(str) == 0) {
-        return;
-    }
-    /* Null-terminate end of non-white string. */
-    for(i=strlen(str)-1; i>=0; i--) { /* step backwards from end */
-        if(str[i] != ' ') { 
-	        str[i+1] = '\0'; 
-	        return; 
-        }
-    }
+  /* Move non-white string to the front. */
+  i = strspn(str, " ");
+  if(i) {
+    memmove(str, str + i, strlen(str) - i + 1);
+  }
+  /* Nothing left? Exit. */
+  if(strlen(str) == 0) {
     return;
+  }
+  /* Null-terminate end of non-white string. */
+  for(i=strlen(str)-1; i>=0; i--) { /* step backwards from end */
+    if(str[i] != ' ') {
+      str[i+1] = '\0';
+      return;
+    }
+  }
+  return;
 }
 
 /*
@@ -451,51 +459,47 @@ void msStringTrim(char *str)
 */
 char *msStringTrimLeft(char *string)
 {
-    char *read, *write;
-    int i, length;
+  char *read, *write;
+  int i, length;
 
-    if (string && strlen(string) > 0)
-    {
-        length = strlen(string);
-        read = string;
-        write = string;
-
-        for (i=0; i<length; i++)
-        {
-            if (isspace(string[i]))
-              read++;
-            else
-              break;
-        }
+  if (string && strlen(string) > 0) {
+    length = strlen(string);
+    read = string;
+    write = string;
 
-        if (read > write)
-        {
-            while (*read)
-            {
-                *write = *read;
-                read++;
-                write++;
-            }
-            *write = '\0';
-        }
+    for (i=0; i<length; i++) {
+      if (isspace(string[i]))
+        read++;
+      else
+        break;
+    }
+
+    if (read > write) {
+      while (*read) {
+        *write = *read;
+        read++;
+        write++;
+      }
+      *write = '\0';
     }
-    return string;
+  }
+  return string;
 }
-    
+
 /* ------------------------------------------------------------------------------- */
 /*       Trims trailing blanks from a string                                        */
 /* ------------------------------------------------------------------------------- */
 void msStringTrimBlanks(char *string)
 {
-   int i,n;
+  int i,n;
 
-   n = strlen(string);
-   for(i=n-1;i>=0;i--) { /* step backwards through the string */
-      if(string[i] != ' ') { 
-	string[i+1] = '\0'; 
-	return; 
-      }
-   }
+  n = strlen(string);
+  for(i=n-1; i>=0; i--) { /* step backwards through the string */
+    if(string[i] != ' ') {
+      string[i+1] = '\0';
+      return;
+    }
+  }
 }
 
 /* ------------------------------------------------------------------------------- */
@@ -520,60 +524,60 @@ void msStringTrimEOL(char *string)
 /* ------------------------------------------------------------------------------- */
 char *msReplaceSubstring(char *str, const char *old, const char *new)
 {
-      size_t str_len, old_len, new_len, tmp_offset;
-      char *tmp_ptr;
+  size_t str_len, old_len, new_len, tmp_offset;
+  char *tmp_ptr;
 
-      if(new == NULL)
-          new = "";
+  if(new == NULL)
+    new = "";
 
-      /*
-      ** If old is not found then leave str alone
-      */
-      if( (tmp_ptr = strstr(str, old)) == NULL)
-	return(str);
+  /*
+  ** If old is not found then leave str alone
+  */
+  if( (tmp_ptr = strstr(str, old)) == NULL)
+    return(str);
 
-      /*
-      ** Grab some info about incoming strings
-      */
-      str_len = strlen(str);
-      old_len = strlen(old);
-      new_len = strlen(new);
+  /*
+  ** Grab some info about incoming strings
+  */
+  str_len = strlen(str);
+  old_len = strlen(old);
+  new_len = strlen(new);
 
-      /*
-      ** Now loop until old is NOT found in new
-      */
-      while( tmp_ptr != NULL ) {
-
-	/*
-	** re-allocate memory for buf assuming 1 replacement of old with new
-        ** don't bother reallocating if old is larger than new)
-	*/
-        if (old_len < new_len) {
-          tmp_offset = tmp_ptr - str;
-          str_len = str_len - old_len + new_len;
-          str = (char *)msSmallRealloc(str, (str_len + 1)); /* make new space for a copy */
-          tmp_ptr = str + tmp_offset;
-        }
+  /*
+  ** Now loop until old is NOT found in new
+  */
+  while( tmp_ptr != NULL ) {
 
-        /*
-        ** Move the trailing part of str to make some room unless old_len == new_len
-        */
-        if (old_len != new_len) {
-            memmove(tmp_ptr+new_len, tmp_ptr+old_len, strlen(tmp_ptr)-old_len+1);
-        }
+    /*
+    ** re-allocate memory for buf assuming 1 replacement of old with new
+          ** don't bother reallocating if old is larger than new)
+    */
+    if (old_len < new_len) {
+      tmp_offset = tmp_ptr - str;
+      str_len = str_len - old_len + new_len;
+      str = (char *)msSmallRealloc(str, (str_len + 1)); /* make new space for a copy */
+      tmp_ptr = str + tmp_offset;
+    }
+
+    /*
+    ** Move the trailing part of str to make some room unless old_len == new_len
+    */
+    if (old_len != new_len) {
+      memmove(tmp_ptr+new_len, tmp_ptr+old_len, strlen(tmp_ptr)-old_len+1);
+    }
 
-        /*
-        ** Now copy new over old
-        */
-        memcpy(tmp_ptr, new, new_len);
+    /*
+    ** Now copy new over old
+    */
+    memcpy(tmp_ptr, new, new_len);
 
-        /*
-        ** And look for more matches in the rest of the string
-        */
-        tmp_ptr = strstr(tmp_ptr + new_len, old);
-      }
+    /*
+    ** And look for more matches in the rest of the string
+    */
+    tmp_ptr = strstr(tmp_ptr + new_len, old);
+  }
 
-      return(str);
+  return(str);
 }
 
 /*
@@ -581,21 +585,22 @@ char *msReplaceSubstring(char *str, const char *old, const char *new)
  * when we won't have to do reallocs etc
  * used to replace the wrap characetr by a newline for labels
  */
-void msReplaceChar(char *str, char old, char new) {
-    while(*(str++))
-        if(*str==old)
-            *str=new;
+void msReplaceChar(char *str, char old, char new)
+{
+  while(*(str++))
+    if(*str==old)
+      *str=new;
 }
 
 /*
 ** how many times does ch occur in str
 */
-int msCountChars(char *str, char ch) 
+int msCountChars(char *str, char ch)
 {
   int i, l, n=0;
 
   l = strlen(str);
-  for(i=0;i<l;i++)
+  for(i=0; i<l; i++)
     if(str[i] == ch) n++;
 
   return(n);
@@ -606,12 +611,23 @@ int msCountChars(char *str, char ch)
 /* ------------------------------------------------------------------------------- */
 char *msStripPath(char *fn)
 {
-  char *str;
+  char *pSlash;
+  char *pBackslash;
 
-  if((str = strrchr(fn,'/')) != NULL) { /* return pointer to last "slash" */
-    str++; /* skip past the "slash" */
-    return(str);
-  } else
+  /* try to locate both, the last slash or backslash */
+  pSlash = strrchr(fn,'/');
+  pBackslash = strrchr(fn,'\\');
+
+  if( pSlash != NULL && pBackslash != NULL ) {
+    if( pSlash < pBackslash )
+      return ++pBackslash;
+    else
+      return ++pSlash;
+  } else if ( pSlash != NULL )
+    return ++pSlash; /* skip past the "slash" */
+  else if ( pBackslash != NULL )
+    return ++pBackslash; /* skip past the "backslash" */
+  else
     return(fn);
 }
 
@@ -622,26 +638,25 @@ char *msGetPath(char *fn)
 {
   char *str;
   int i, length;
-  
+
   length = strlen(fn);
   if((str = msStrdup(fn)) == NULL)
     return(NULL);
-  
+
   for(i=length-1; i>=0; i--) { /* step backwards through the string */
-    if((str[i] == '/') || (str[i] == '\\')) { 
-      str[i+1] = '\0'; 
+    if((str[i] == '/') || (str[i] == '\\')) {
+      str[i+1] = '\0';
       break;
     }
   }
 
-  if(strcmp(str, fn) == 0)
-  {
+  if(strcmp(str, fn) == 0) {
     msFree(str);
-#if defined(_WIN32) && !defined(__CYGWIN__)  
+#if defined(_WIN32) && !defined(__CYGWIN__)
     str = msStrdup(".\\");
 #else
     str= msStrdup("./");
-#endif  
+#endif
   }
 
   return(str);
@@ -658,39 +673,33 @@ char *msBuildPath(char *pszReturnPath, const char *abs_path, const char *path)
   int   pathlen = 0;
 
 
-  if(path == NULL)
-  {
-      msSetError(MS_IOERR, NULL, "msBuildPath");
-      return NULL;
+  if(path == NULL) {
+    msSetError(MS_IOERR, NULL, "msBuildPath");
+    return NULL;
   }
 
   pathlen = strlen(path);
   if (abs_path)
     abslen = strlen(abs_path);
 
-  if((pathlen + abslen + 2) > MS_MAXPATHLEN)
-  {
-      msSetError(MS_IOERR, "(%s%s): path is too long", "msBuildPath()",
-                 abs_path, path);
-      return NULL;
+  if((pathlen + abslen + 2) > MS_MAXPATHLEN) {
+    msSetError(MS_IOERR, "(%s%s): path is too long", "msBuildPath()",
+               abs_path, path);
+    return NULL;
   }
 
   /* Check if path is absolute */
-  if((abs_path == NULL) || (abslen == 0) || 
-       (path[0] == '\\') || (path[0] == '/') || 
-         (pathlen > 1 && (path[1] == ':')))
-  {
-      strlcpy(pszReturnPath, path, MS_MAXPATHLEN);
-      return(pszReturnPath);
+  if((abs_path == NULL) || (abslen == 0) ||
+      (path[0] == '\\') || (path[0] == '/') ||
+      (pathlen > 1 && (path[1] == ':'))) {
+    strlcpy(pszReturnPath, path, MS_MAXPATHLEN);
+    return(pszReturnPath);
   }
 
   /* else return abs_path/path */
-  if((abs_path[abslen-1] == '/') || (abs_path[abslen-1] == '\\'))
-  {
+  if((abs_path[abslen-1] == '/') || (abs_path[abslen-1] == '\\')) {
     snprintf(pszReturnPath, MS_MAXPATHLEN, "%s%s", abs_path, path);
-  }
-  else
-  {
+  } else {
     snprintf(pszReturnPath, MS_MAXPATHLEN, "%s/%s", abs_path, path);
   }
 
@@ -707,7 +716,7 @@ char *msBuildPath3(char *pszReturnPath, const char *abs_path, const char *path1,
 {
   char szPath[MS_MAXPATHLEN];
 
-  return msBuildPath(pszReturnPath, abs_path, 
+  return msBuildPath(pszReturnPath, abs_path,
                      msBuildPath(szPath, path1, path2));
 }
 
@@ -721,21 +730,19 @@ char *msBuildPath3(char *pszReturnPath, const char *abs_path, const char *path1,
 char *msTryBuildPath(char *szReturnPath, const char *abs_path, const char *path)
 
 {
-    FILE	*fp;
+  FILE  *fp;
 
-    if( msBuildPath( szReturnPath, abs_path, path ) == NULL )
-        return NULL;
+  if( msBuildPath( szReturnPath, abs_path, path ) == NULL )
+    return NULL;
 
-    fp = fopen( szReturnPath, "r" );
-    if( fp == NULL )
-    {
-        strlcpy( szReturnPath, path, MS_MAXPATHLEN);
-        return NULL;
-    }
-    else
-        fclose( fp );
+  fp = fopen( szReturnPath, "r" );
+  if( fp == NULL ) {
+    strlcpy( szReturnPath, path, MS_MAXPATHLEN);
+    return NULL;
+  } else
+    fclose( fp );
 
-    return szReturnPath;
+  return szReturnPath;
 }
 
 /*
@@ -748,27 +755,25 @@ char *msTryBuildPath(char *szReturnPath, const char *abs_path, const char *path)
 char *msTryBuildPath3(char *szReturnPath, const char *abs_path, const char *path1, const char *path2)
 
 {
-    FILE	*fp;
+  FILE  *fp;
 
-    if( msBuildPath3( szReturnPath, abs_path, path1, path2 ) == NULL )
-        return NULL;
+  if( msBuildPath3( szReturnPath, abs_path, path1, path2 ) == NULL )
+    return NULL;
 
-    fp = fopen( szReturnPath, "r" );
-    if( fp == NULL )
-    {
-      strlcpy( szReturnPath, path2, MS_MAXPATHLEN);
-      return NULL;
-    }
-    else
-        fclose( fp );
+  fp = fopen( szReturnPath, "r" );
+  if( fp == NULL ) {
+    strlcpy( szReturnPath, path2, MS_MAXPATHLEN);
+    return NULL;
+  } else
+    fclose( fp );
 
-    return szReturnPath;
+  return szReturnPath;
 }
 
 /*
 ** Splits a string into multiple strings based on ch. Consecutive ch's are ignored.
 */
-char **msStringSplit(const char *string, char ch, int *num_tokens) 
+char **msStringSplit(const char *string, char ch, int *num_tokens)
 {
   int i,j,k;
   int length,n;
@@ -785,7 +790,7 @@ char **msStringSplit(const char *string, char ch, int *num_tokens)
 
   token = (char **) msSmallMalloc(sizeof(char *)*n);
   if(!token) return(NULL);
-  
+
   k = 0;
   token[k] = (char *)msSmallMalloc(sizeof(char)*(length+1));
   if(!token[k]) return(NULL);
@@ -794,23 +799,23 @@ char **msStringSplit(const char *string, char ch, int *num_tokens)
   last_ch='\0';
   for(i=0; i<length; i++) {
     if(string[i] == ch) {
-      
+
       if(last_ch == ch)
-	continue;
-      
-      token[k][j] = '\0'; /* terminate current token */      
-      
+        continue;
+
+      token[k][j] = '\0'; /* terminate current token */
+
       k++;
       token[k] = (char *)msSmallMalloc(sizeof(char)*(length+1));
       if(!token[k]) return(NULL);
-      
-      j = 0;      
-    } else {      
+
+      j = 0;
+    } else {
       token[k][j] = string[i];
       j++;
     }
-    
-    last_ch = string[i]; 
+
+    last_ch = string[i];
   }
 
   token[k][j] = '\0'; /* terminate last token */
@@ -824,18 +829,18 @@ char **msStringSplit(const char *string, char ch, int *num_tokens)
  This function is a copy of CSLTokenizeString2() function of the CPL component.
  See the port/cpl_string.cpp file in gdal source for the complete documentation.
  Available Flags:
- * - MS_ALLOWEMPTYTOKENS: allow the return of empty tokens when two 
- * delimiters in a row occur with no other text between them.  If not set, 
+ * - MS_ALLOWEMPTYTOKENS: allow the return of empty tokens when two
+ * delimiters in a row occur with no other text between them.  If not set,
  * empty tokens will be discarded;
  * - MS_STRIPLEADSPACES: strip leading space characters from the token (as
  * reported by isspace());
  * - MS_STRIPENDSPACES: strip ending space characters from the token (as
  * reported by isspace());
- * - MS_HONOURSTRINGS: double quotes can be used to hold values that should 
- * not be broken into multiple tokens; 
+ * - MS_HONOURSTRINGS: double quotes can be used to hold values that should
+ * not be broken into multiple tokens;
  * - MS_PRESERVEQUOTES: string quotes are carried into the tokens when this
  * is set, otherwise they are removed;
- * - MS_PRESERVEESCAPES: if set backslash escapes (for backslash itself, 
+ * - MS_PRESERVEESCAPES: if set backslash escapes (for backslash itself,
  * and for literal double quotes) will be preserved in the tokens, otherwise
  * the backslashes will be removed in processing.
  */
@@ -845,268 +850,234 @@ char ** msStringSplitComplex( const char * pszString,
                               int nFlags )
 
 {
-    char        **papszRetList = NULL;
-    int         nRetMax = 0, nRetLen = 0;
-    char        *pszToken;
-    int         nTokenMax, nTokenLen;
-    int         bHonourStrings = (nFlags & MS_HONOURSTRINGS);
-    int         bAllowEmptyTokens = (nFlags & MS_ALLOWEMPTYTOKENS);
-    int         bStripLeadSpaces = (nFlags & MS_STRIPLEADSPACES);
-    int         bStripEndSpaces = (nFlags & MS_STRIPENDSPACES);
-
-    pszToken = (char *) msSmallMalloc(sizeof(char*)*10);;
-    nTokenMax = 10;
-    
-    while( pszString != NULL && *pszString != '\0' )
-    {
-        int     bInString = MS_FALSE;
-        int     bStartString = MS_TRUE;
-
-        nTokenLen = 0;
-        
-        /* Try to find the next delimeter, marking end of token */
-        for( ; *pszString != '\0'; pszString++ )
-        {
-
-            /* End if this is a delimeter skip it and break. */
-            if( !bInString && strchr(pszDelimiters, *pszString) != NULL )
-            {
-                pszString++;
-                break;
-            }
-            
-            /* If this is a quote, and we are honouring constant
-               strings, then process the constant strings, with out delim
-               but don't copy over the quotes */
-            if( bHonourStrings && *pszString == '"' )
-            {
-                if( nFlags & MS_PRESERVEQUOTES )
-                {
-                    pszToken[nTokenLen] = *pszString;
-                    nTokenLen++;
-                }
-
-                if( bInString )
-                {
-                    bInString = MS_FALSE;
-                    continue;
-                }
-                else
-                {
-                    bInString = MS_TRUE;
-                    continue;
-                }
-            }
-
-            /*
-             * Within string constants we allow for escaped quotes, but in
-             * processing them we will unescape the quotes and \\ sequence
-             * reduces to \
-             */
-            if( bInString && pszString[0] == '\\' )
-            {
-                if ( pszString[1] == '"' || pszString[1] == '\\' )
-                {
-                    if( nFlags & MS_PRESERVEESCAPES )
-                    {
-                        pszToken[nTokenLen] = *pszString;
-                        nTokenLen++;
-                    }
-
-                    pszString++;
-                }
-            }
-
-            /*
-             * Strip spaces at the token start if requested.
-             */
-            if ( !bInString && bStripLeadSpaces
-                 && bStartString && isspace((unsigned char)*pszString) )
-                continue;
-
-            bStartString = MS_FALSE;
-
-            /*
-             * Extend token buffer if we are running close to its end.
-             */
-            if( nTokenLen >= nTokenMax-3 )
-            {
-                nTokenMax = nTokenMax * 2 + 10;
-                pszToken = (char *) msSmallRealloc(pszToken, sizeof(char*)*nTokenMax);
-            }
+  char        **papszRetList = NULL;
+  int         nRetMax = 0, nRetLen = 0;
+  char        *pszToken;
+  int         nTokenMax, nTokenLen;
+  int         bHonourStrings = (nFlags & MS_HONOURSTRINGS);
+  int         bAllowEmptyTokens = (nFlags & MS_ALLOWEMPTYTOKENS);
+  int         bStripLeadSpaces = (nFlags & MS_STRIPLEADSPACES);
+  int         bStripEndSpaces = (nFlags & MS_STRIPENDSPACES);
+
+  pszToken = (char *) msSmallMalloc(sizeof(char*)*10);;
+  nTokenMax = 10;
+
+  while( pszString != NULL && *pszString != '\0' ) {
+    int     bInString = MS_FALSE;
+    int     bStartString = MS_TRUE;
+
+    nTokenLen = 0;
+
+    /* Try to find the next delimeter, marking end of token */
+    for( ; *pszString != '\0'; pszString++ ) {
+
+      /* End if this is a delimeter skip it and break. */
+      if( !bInString && strchr(pszDelimiters, *pszString) != NULL ) {
+        pszString++;
+        break;
+      }
 
-            pszToken[nTokenLen] = *pszString;
-            nTokenLen++;
+      /* If this is a quote, and we are honouring constant
+         strings, then process the constant strings, with out delim
+         but don't copy over the quotes */
+      if( bHonourStrings && *pszString == '"' ) {
+        if( nFlags & MS_PRESERVEQUOTES ) {
+          pszToken[nTokenLen] = *pszString;
+          nTokenLen++;
         }
 
-        /*
-         * Strip spaces at the token end if requested.
-         */
-        if ( !bInString && bStripEndSpaces )
-        {
-            while ( nTokenLen && isspace((unsigned char)pszToken[nTokenLen - 1]) )
-                nTokenLen--;
+        if( bInString ) {
+          bInString = MS_FALSE;
+          continue;
+        } else {
+          bInString = MS_TRUE;
+          continue;
         }
+      }
+
+      /*
+       * Within string constants we allow for escaped quotes, but in
+       * processing them we will unescape the quotes and \\ sequence
+       * reduces to \
+       */
+      if( bInString && pszString[0] == '\\' ) {
+        if ( pszString[1] == '"' || pszString[1] == '\\' ) {
+          if( nFlags & MS_PRESERVEESCAPES ) {
+            pszToken[nTokenLen] = *pszString;
+            nTokenLen++;
+          }
 
-        pszToken[nTokenLen] = '\0';
-
-        /*
-         * Add the token.
-         */
-        if( pszToken[0] != '\0' || bAllowEmptyTokens )
-        {
-            if( nRetLen >= nRetMax - 1 )
-            {
-                nRetMax = nRetMax * 2 + 10;
-                papszRetList = (char **) msSmallRealloc(papszRetList, sizeof(char*)*nRetMax);
-            }
-
-            papszRetList[nRetLen++] = msStrdup( pszToken );
-            papszRetList[nRetLen] = NULL;
+          pszString++;
         }
+      }
+
+      /*
+       * Strip spaces at the token start if requested.
+       */
+      if ( !bInString && bStripLeadSpaces
+           && bStartString && isspace((unsigned char)*pszString) )
+        continue;
+
+      bStartString = MS_FALSE;
+
+      /*
+       * Extend token buffer if we are running close to its end.
+       */
+      if( nTokenLen >= nTokenMax-3 ) {
+        nTokenMax = nTokenMax * 2 + 10;
+        pszToken = (char *) msSmallRealloc(pszToken, sizeof(char*)*nTokenMax);
+      }
+
+      pszToken[nTokenLen] = *pszString;
+      nTokenLen++;
     }
 
     /*
-     * If the last token was empty, then we need to capture
-     * it now, as the loop would skip it.
+     * Strip spaces at the token end if requested.
      */
-    if( *pszString == '\0' && bAllowEmptyTokens && nRetLen > 0 
-        && strchr(pszDelimiters,*(pszString-1)) != NULL )
-    {
-        if( nRetLen >= nRetMax - 1 )
-        {
-            nRetMax = nRetMax * 2 + 10;
-            papszRetList = (char **) msSmallRealloc(papszRetList, sizeof(char*)*nRetMax);
-        }
+    if ( !bInString && bStripEndSpaces ) {
+      while ( nTokenLen && isspace((unsigned char)pszToken[nTokenLen - 1]) )
+        nTokenLen--;
+    }
+
+    pszToken[nTokenLen] = '\0';
 
-        papszRetList[nRetLen++] = msStrdup("");
-        papszRetList[nRetLen] = NULL;
+    /*
+     * Add the token.
+     */
+    if( pszToken[0] != '\0' || bAllowEmptyTokens ) {
+      if( nRetLen >= nRetMax - 1 ) {
+        nRetMax = nRetMax * 2 + 10;
+        papszRetList = (char **) msSmallRealloc(papszRetList, sizeof(char*)*nRetMax);
+      }
+
+      papszRetList[nRetLen++] = msStrdup( pszToken );
+      papszRetList[nRetLen] = NULL;
     }
+  }
+
+  /*
+   * If the last token was empty, then we need to capture
+   * it now, as the loop would skip it.
+   */
+  if( *pszString == '\0' && bAllowEmptyTokens && nRetLen > 0
+      && strchr(pszDelimiters,*(pszString-1)) != NULL ) {
+    if( nRetLen >= nRetMax - 1 ) {
+      nRetMax = nRetMax * 2 + 10;
+      papszRetList = (char **) msSmallRealloc(papszRetList, sizeof(char*)*nRetMax);
+    }
+
+    papszRetList[nRetLen++] = msStrdup("");
+    papszRetList[nRetLen] = NULL;
+  }
 
-    if( papszRetList == NULL )
-        papszRetList = (char **) msSmallMalloc(sizeof(char *)*1);
+  if( papszRetList == NULL )
+    papszRetList = (char **) msSmallMalloc(sizeof(char *)*1);
 
-    *num_tokens = nRetLen;
-    free(pszToken);
+  *num_tokens = nRetLen;
+  free(pszToken);
 
-    return papszRetList;
+  return papszRetList;
 }
 
-/* This method is similar to msStringSplit but support quoted strings. 
+/* This method is similar to msStringSplit but support quoted strings.
    It also support multi-characters delimiter and allows to preserve quotes */
-char **msStringTokenize( const char *pszLine, const char *pszDelim, 
+char **msStringTokenize( const char *pszLine, const char *pszDelim,
                          int *num_tokens, int preserve_quote )
 {
-    char **papszResult = NULL;
-    int n = 1, iChar, nLength = strlen(pszLine), iTokenChar = 0, bInQuotes = MS_FALSE;
-    char *pszToken = (char *) msSmallMalloc(sizeof(char*)*(nLength+1));
-    int nDelimLen = strlen(pszDelim);
-
-    /* Compute the number of tokens */
-    for( iChar = 0; pszLine[iChar] != '\0'; iChar++ )
-    {
-        if( bInQuotes && pszLine[iChar] == '"' && pszLine[iChar+1] == '"' )
-        {
-            iChar++;
-        }
-        else if( pszLine[iChar] == '"' )
-        {
-            bInQuotes = !bInQuotes;
-        }
-        else if ( !bInQuotes && strncmp(pszLine+iChar,pszDelim,nDelimLen) == 0 )
-        {
-            iChar += nDelimLen - 1;
-            n++;
-        }
+  char **papszResult = NULL;
+  int n = 1, iChar, nLength = strlen(pszLine), iTokenChar = 0, bInQuotes = MS_FALSE;
+  char *pszToken = (char *) msSmallMalloc(sizeof(char*)*(nLength+1));
+  int nDelimLen = strlen(pszDelim);
+
+  /* Compute the number of tokens */
+  for( iChar = 0; pszLine[iChar] != '\0'; iChar++ ) {
+    if( bInQuotes && pszLine[iChar] == '"' && pszLine[iChar+1] == '"' ) {
+      iChar++;
+    } else if( pszLine[iChar] == '"' ) {
+      bInQuotes = !bInQuotes;
+    } else if ( !bInQuotes && strncmp(pszLine+iChar,pszDelim,nDelimLen) == 0 ) {
+      iChar += nDelimLen - 1;
+      n++;
     }
+  }
 
-    papszResult = (char **) msSmallMalloc(sizeof(char *)*n);
-    n = iTokenChar = bInQuotes = 0;
-    for( iChar = 0; pszLine[iChar] != '\0'; iChar++ )
-    {
-        if( bInQuotes && pszLine[iChar] == '"' && pszLine[iChar+1] == '"' )
-        {
-           if (preserve_quote == MS_TRUE)
-              pszToken[iTokenChar++] = '"';
-           pszToken[iTokenChar++] = '"';
-           iChar++;
-        }
-        else if( pszLine[iChar] == '"' )
-        {
-           if (preserve_quote == MS_TRUE)
-              pszToken[iTokenChar++] = '"';
-            bInQuotes = !bInQuotes;
-        }
-        else if( !bInQuotes && strncmp(pszLine+iChar,pszDelim,nDelimLen) == 0 )
-        {
-            pszToken[iTokenChar++] = '\0';
-            papszResult[n] = pszToken;
-            pszToken = (char *) msSmallMalloc(sizeof(char*)*(nLength+1));
-            iChar += nDelimLen - 1;
-            iTokenChar = 0;
-            n++;
-        }
-        else
-        {
-            pszToken[iTokenChar++] = pszLine[iChar];
-        }
+  papszResult = (char **) msSmallMalloc(sizeof(char *)*n);
+  n = iTokenChar = bInQuotes = 0;
+  for( iChar = 0; pszLine[iChar] != '\0'; iChar++ ) {
+    if( bInQuotes && pszLine[iChar] == '"' && pszLine[iChar+1] == '"' ) {
+      if (preserve_quote == MS_TRUE)
+        pszToken[iTokenChar++] = '"';
+      pszToken[iTokenChar++] = '"';
+      iChar++;
+    } else if( pszLine[iChar] == '"' ) {
+      if (preserve_quote == MS_TRUE)
+        pszToken[iTokenChar++] = '"';
+      bInQuotes = !bInQuotes;
+    } else if( !bInQuotes && strncmp(pszLine+iChar,pszDelim,nDelimLen) == 0 ) {
+      pszToken[iTokenChar++] = '\0';
+      papszResult[n] = pszToken;
+      pszToken = (char *) msSmallMalloc(sizeof(char*)*(nLength+1));
+      iChar += nDelimLen - 1;
+      iTokenChar = 0;
+      n++;
+    } else {
+      pszToken[iTokenChar++] = pszLine[iChar];
     }
+  }
+
+  pszToken[iTokenChar++] = '\0';
+  papszResult[n] = pszToken;
 
-    pszToken[iTokenChar++] = '\0';
-    papszResult[n] = pszToken;
-    
-    *num_tokens = n+1;
+  *num_tokens = n+1;
 
-    return papszResult;
+  return papszResult;
 }
 
 /**********************************************************************
  *                       msEncodeChar()
  *
  * Return 1 if the character argument should be encoded for safety
- * in URL use and 0 otherwise. Specific character map taken from 
+ * in URL use and 0 otherwise. Specific character map taken from
  * http://www.ietf.org/rfc/rfc2396.txt
  *
  **********************************************************************/
 
 int msEncodeChar(const char c)
 {
-  if ( 
-       (c >= 0x61 && c <= 0x7A ) ||   /* Letters a-z */
-       (c >= 0x41 && c <= 0x5A ) ||   /* Letters A-Z */
-       (c >= 0x30 && c <= 0x39 ) ||   /* Numbers 0-9 */
-       (c >= 0x27 && c <= 0x2A ) ||   /* * ' ( )     */
-       (c >= 0x2D && c <= 0x2E ) ||   /* - .         */
-       (c == 0x5F ) ||                /* _           */
-       (c == 0x21 ) ||                /* !           */
-       (c == 0x7E ) )                 /* ~           */
-  {
+  if (
+    (c >= 0x61 && c <= 0x7A ) ||   /* Letters a-z */
+    (c >= 0x41 && c <= 0x5A ) ||   /* Letters A-Z */
+    (c >= 0x30 && c <= 0x39 ) ||   /* Numbers 0-9 */
+    (c >= 0x27 && c <= 0x2A ) ||   /* * ' ( )     */
+    (c >= 0x2D && c <= 0x2E ) ||   /* - .         */
+    (c == 0x5F ) ||                /* _           */
+    (c == 0x21 ) ||                /* !           */
+    (c == 0x7E ) ) {               /* ~           */
     return(0);
-  }
-  else 
-  {
+  } else {
     return(1);
   }
 }
 
 char *msEncodeUrl(const char *data)
 {
-       /*
-        * Delegate to msEncodeUrlExcept, with a null second argument
-        * to render the except handling moot.
-        */ 
-	return(msEncodeUrlExcept(data, '\0'));
+  /*
+   * Delegate to msEncodeUrlExcept, with a null second argument
+   * to render the except handling moot.
+   */
+  return(msEncodeUrlExcept(data, '\0'));
 }
 
 /**********************************************************************
  *                       msEncodeCharExcept()
  *
- * URL encoding, applies RFP2396 encoding to all characters 
+ * URL encoding, applies RFP2396 encoding to all characters
  * except the one exception character. An exception character
  * of '\0' implies no exception handling.
  *
  **********************************************************************/
- 
+
 char *msEncodeUrlExcept(const char *data, const char except)
 {
   char *hex = "0123456789ABCDEF";
@@ -1118,31 +1089,24 @@ char *msEncodeUrlExcept(const char *data, const char except)
   for (inc=0, i=data; *i!='\0'; i++)
     if (msEncodeChar(*i))
       inc += 2;
-  
+
   code = (char*)msSmallMalloc(strlen(data)+inc+1);
-  
-  for (j=code, i=data; *i!='\0'; i++, j++)
-    {
-      if (*i == ' ')
-	*j = '+';
-      else
-      if ( except != '\0' && *i == except )
-        {
-	  *j = except;
-        }
-      else 
-      if (msEncodeChar(*i))
-	{
-	  ch = *i;
-	  *j++ = '%'; 
-	  *j++ = hex[ch/16]; 
-	  *j   = hex[ch%16];
-	}
-      else
-	*j = *i;
-    }
+
+  for (j=code, i=data; *i!='\0'; i++, j++) {
+    if (*i == ' ')
+      *j = '+';
+    else if ( except != '\0' && *i == except ) {
+      *j = except;
+    } else if (msEncodeChar(*i)) {
+      ch = *i;
+      *j++ = '%';
+      *j++ = hex[ch/16];
+      *j   = hex[ch%16];
+    } else
+      *j = *i;
+  }
   *j = '\0';
-  
+
   return code;
 }
 
@@ -1154,63 +1118,60 @@ char *msEncodeUrlExcept(const char *data, const char except)
 ** The replacements performed are:
 **  '&' -> "&", '"' -> """, '<' -> "<" and '>' -> ">"
 **/
-char *msEncodeHTMLEntities(const char *string) 
+char *msEncodeHTMLEntities(const char *string)
 {
-    int buflen, i;
-    char *newstring;
-    const char *c;
+  int buflen, i;
+  char *newstring;
+  const char *c;
 
-    if(string == NULL)
-        return NULL;
-
-    /* Start with 100 extra chars for replacements...  */
-    /* should be good enough for most cases */
-    buflen = strlen(string) + 100;
-    newstring = (char*)malloc(buflen+1);
-    MS_CHECK_ALLOC(newstring, buflen+1, NULL);
+  if(string == NULL)
+    return NULL;
 
-    for(i=0, c=string; *c != '\0'; c++)
-    {
-        /* Need to realloc buffer? */
-        if (i+6 > buflen)
-        {
-            /* If we had to realloc then this string must contain several */
-            /* entities... so let's go with twice the previous buffer size */
-            buflen *= 2;
-            newstring = (char*)realloc(newstring, buflen+1);
-            MS_CHECK_ALLOC(newstring, buflen+1, NULL);
-        }
+  /* Start with 100 extra chars for replacements...  */
+  /* should be good enough for most cases */
+  buflen = strlen(string) + 100;
+  newstring = (char*)malloc(buflen+1);
+  MS_CHECK_ALLOC(newstring, buflen+1, NULL);
+
+  for(i=0, c=string; *c != '\0'; c++) {
+    /* Need to realloc buffer? */
+    if (i+6 > buflen) {
+      /* If we had to realloc then this string must contain several */
+      /* entities... so let's go with twice the previous buffer size */
+      buflen *= 2;
+      newstring = (char*)realloc(newstring, buflen+1);
+      MS_CHECK_ALLOC(newstring, buflen+1, NULL);
+    }
 
-        switch(*c)
-        {
-          case '&':
-            strcpy(newstring+i, "&");
-            i += 5;
-            break;
-          case '<':
-            strcpy(newstring+i, "<");
-            i += 4;
-            break;
-          case '>':
-            strcpy(newstring+i, ">");
-            i += 4;
-            break;
-          case '"':
-            strcpy(newstring+i, """);
-            i += 6;
-            break;
-          case '\'':
-            strcpy(newstring+i, "'"); /* changed from ' and i += 6 (bug 1040) */
-            i += 5;
-            break;
-          default:
-            newstring[i++] = *c;
-        }
+    switch(*c) {
+      case '&':
+        strcpy(newstring+i, "&");
+        i += 5;
+        break;
+      case '<':
+        strcpy(newstring+i, "<");
+        i += 4;
+        break;
+      case '>':
+        strcpy(newstring+i, ">");
+        i += 4;
+        break;
+      case '"':
+        strcpy(newstring+i, """);
+        i += 6;
+        break;
+      case '\'':
+        strcpy(newstring+i, "'"); /* changed from ' and i += 6 (bug 1040) */
+        i += 5;
+        break;
+      default:
+        newstring[i++] = *c;
     }
+  }
 
-    newstring[i++] = '\0';
+  newstring[i++] = '\0';
 
-    return newstring;
+  return newstring;
 }
 
 
@@ -1221,75 +1182,65 @@ char *msEncodeHTMLEntities(const char *string)
 ** The replacements performed are:
 **  "&" -> '&', """ -> '"', "<" -> '<' and ">" -> '>'
 **/
-void msDecodeHTMLEntities(const char *string) 
+void msDecodeHTMLEntities(const char *string)
 {
-    char *pszAmp=NULL, *pszSemiColon=NULL, *pszReplace=NULL, *pszEnd=NULL;
-    char *pszBuffer=NULL;
-    size_t bufferSize = 0;
-
-    if(string == NULL)
-        return;
-    else
-        pszBuffer = (char*)string;
-
-    bufferSize = strlen(pszBuffer);
-    pszReplace = (char*) msSmallMalloc(bufferSize);
-    pszEnd = (char*) msSmallMalloc(bufferSize);
-
-    while((pszAmp = strchr(pszBuffer, '&')) != NULL)
-    {
-        /* Get the &...; */
-        strlcpy(pszReplace, pszAmp, bufferSize);
-        pszSemiColon = strchr(pszReplace, ';');
-        if(pszSemiColon == NULL)
-            break;
-        else
-            pszSemiColon++;
+  char *pszAmp=NULL, *pszSemiColon=NULL, *pszReplace=NULL, *pszEnd=NULL;
+  char *pszBuffer=NULL;
+  size_t bufferSize = 0;
 
-        /* Get everything after the &...; */
-        strlcpy(pszEnd, pszSemiColon, bufferSize);
+  if(string == NULL)
+    return;
+  else
+    pszBuffer = (char*)string;
 
-        pszReplace[pszSemiColon-pszReplace] = '\0';
+  bufferSize = strlen(pszBuffer);
+  pszReplace = (char*) msSmallMalloc(bufferSize);
+  pszEnd = (char*) msSmallMalloc(bufferSize);
 
-        /* Replace the &...; */
-        if(strcasecmp(pszReplace, "&") == 0)
-        {
-            pszBuffer[pszAmp - pszBuffer] = '&';
-            pszBuffer[pszAmp - pszBuffer + 1] = '\0';
-            strcat(pszBuffer, pszEnd);
-        }
-        else if(strcasecmp(pszReplace, "<") == 0)
-        {
-            pszBuffer[pszAmp - pszBuffer] = '<';
-            pszBuffer[pszAmp - pszBuffer + 1] = '\0';
-            strcat(pszBuffer, pszEnd);
-        }
-        else if(strcasecmp(pszReplace, ">") == 0)
-        {
-            pszBuffer[pszAmp - pszBuffer] = '>';
-            pszBuffer[pszAmp - pszBuffer + 1] = '\0';
-            strcat(pszBuffer, pszEnd);
-        }
-        else if(strcasecmp(pszReplace, """) == 0)
-        {
-            pszBuffer[pszAmp - pszBuffer] = '"';
-            pszBuffer[pszAmp - pszBuffer + 1] = '\0';
-            strcat(pszBuffer, pszEnd);
-        }
-        else if(strcasecmp(pszReplace, "'") == 0)
-        {
-            pszBuffer[pszAmp - pszBuffer] = '\'';
-            pszBuffer[pszAmp - pszBuffer + 1] = '\0';
-            strcat(pszBuffer, pszEnd);
-        }
-
-        pszBuffer = pszAmp + 1;
+  while((pszAmp = strchr(pszBuffer, '&')) != NULL) {
+    /* Get the &...; */
+    strlcpy(pszReplace, pszAmp, bufferSize);
+    pszSemiColon = strchr(pszReplace, ';');
+    if(pszSemiColon == NULL)
+      break;
+    else
+      pszSemiColon++;
+
+    /* Get everything after the &...; */
+    strlcpy(pszEnd, pszSemiColon, bufferSize);
+
+    pszReplace[pszSemiColon-pszReplace] = '\0';
+
+    /* Replace the &...; */
+    if(strcasecmp(pszReplace, "&") == 0) {
+      pszBuffer[pszAmp - pszBuffer] = '&';
+      pszBuffer[pszAmp - pszBuffer + 1] = '\0';
+      strcat(pszBuffer, pszEnd);
+    } else if(strcasecmp(pszReplace, "<") == 0) {
+      pszBuffer[pszAmp - pszBuffer] = '<';
+      pszBuffer[pszAmp - pszBuffer + 1] = '\0';
+      strcat(pszBuffer, pszEnd);
+    } else if(strcasecmp(pszReplace, ">") == 0) {
+      pszBuffer[pszAmp - pszBuffer] = '>';
+      pszBuffer[pszAmp - pszBuffer + 1] = '\0';
+      strcat(pszBuffer, pszEnd);
+    } else if(strcasecmp(pszReplace, """) == 0) {
+      pszBuffer[pszAmp - pszBuffer] = '"';
+      pszBuffer[pszAmp - pszBuffer + 1] = '\0';
+      strcat(pszBuffer, pszEnd);
+    } else if(strcasecmp(pszReplace, "'") == 0) {
+      pszBuffer[pszAmp - pszBuffer] = '\'';
+      pszBuffer[pszAmp - pszBuffer + 1] = '\0';
+      strcat(pszBuffer, pszEnd);
     }
 
-    free(pszReplace);
-    free(pszEnd);
+    pszBuffer = pszAmp + 1;
+  }
 
-    return;
+  free(pszReplace);
+  free(pszEnd);
+
+  return;
 }
 
 /*
@@ -1301,21 +1252,20 @@ void msDecodeHTMLEntities(const char *string)
 */
 int msIsXMLTagValid(const char *string)
 {
-    int i, nLen;
+  int i, nLen;
 
-    nLen = strlen(string);
+  nLen = strlen(string);
 
-    for(i=0; i<nLen; i++)
-    {
-        if( !( string[i] >= 'A' && string[i] <= 'Z' ) && 
-            !( string[i] >= 'a' && string[i] <= 'z' ) && 
-            !( string[i] >= '0' && string[i] <= '9' ) && 
-            string[i] != '-' && string[i] != '.' && 
-            string[i] != ':' && string[i] != '_' )
-            return MS_FALSE;
-    }
+  for(i=0; i<nLen; i++) {
+    if( !( string[i] >= 'A' && string[i] <= 'Z' ) &&
+        !( string[i] >= 'a' && string[i] <= 'z' ) &&
+        !( string[i] >= '0' && string[i] <= '9' ) &&
+        string[i] != '-' && string[i] != '.' &&
+        string[i] != ':' && string[i] != '_' )
+      return MS_FALSE;
+  }
 
-    return MS_TRUE;
+  return MS_TRUE;
 }
 
 
@@ -1324,36 +1274,34 @@ int msIsXMLTagValid(const char *string)
 */
 char *msStringConcatenate(char *pszDest, const char *pszSrc)
 {
-   int nLen;
-   
-   if (pszSrc == NULL)
-      return pszDest;
-
-   /* if destination is null, allocate memory */
-   if (pszDest == NULL) {
-      pszDest = msStrdup(pszSrc);
-   }
-   else { /* if dest is not null, reallocate memory */
-      char *pszTemp;
-
-      nLen = strlen(pszDest) + strlen(pszSrc);
-
-      pszTemp = (char*)realloc(pszDest, nLen + 1);
-      if (pszTemp) {
-         pszDest = pszTemp;
-         strcat(pszDest, pszSrc);
-         pszDest[nLen] = '\0';
-      }
-      else {
-         msSetError(MS_MEMERR, "Error while reallocating memory.", "msStringConcatenate()");
-         return NULL;
-      }        
-   }
-   
-   return pszDest;
+  int nLen;
+
+  if (pszSrc == NULL)
+    return pszDest;
+
+  /* if destination is null, allocate memory */
+  if (pszDest == NULL) {
+    pszDest = msStrdup(pszSrc);
+  } else { /* if dest is not null, reallocate memory */
+    char *pszTemp;
+
+    nLen = strlen(pszDest) + strlen(pszSrc);
+
+    pszTemp = (char*)realloc(pszDest, nLen + 1);
+    if (pszTemp) {
+      pszDest = pszTemp;
+      strcat(pszDest, pszSrc);
+      pszDest[nLen] = '\0';
+    } else {
+      msSetError(MS_MEMERR, "Error while reallocating memory.", "msStringConcatenate()");
+      return NULL;
+    }
+  }
+
+  return pszDest;
 }
 
-char *msJoinStrings(char **array, int arrayLength, const char *delimeter) 
+char *msJoinStrings(char **array, int arrayLength, const char *delimeter)
 {
   char *string;
   int stringLength=0;
@@ -1387,30 +1335,28 @@ char *msJoinStrings(char **array, int arrayLength, const char *delimeter)
 */
 char *msHashString(const char *pszStr)
 {
-    unsigned char sums[HASH_SIZE] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
-    char *pszOutBuf = NULL;
-    size_t bufferSize = 0;
-    int i=0;
+  unsigned char sums[HASH_SIZE] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
+  char *pszOutBuf = NULL;
+  size_t bufferSize = 0;
+  int i=0;
 
-    bufferSize = HASH_SIZE*2+1;
-    pszOutBuf = (char*)msSmallMalloc(bufferSize);
+  bufferSize = HASH_SIZE*2+1;
+  pszOutBuf = (char*)msSmallMalloc(bufferSize);
 
-    for(i=0; pszStr && pszStr[i]; i++)
-    {
-        sums[i%HASH_SIZE] += (unsigned char)(pszStr[i]);
-    }
+  for(i=0; pszStr && pszStr[i]; i++) {
+    sums[i%HASH_SIZE] += (unsigned char)(pszStr[i]);
+  }
 
-    for(i=0; i<HASH_SIZE; i++)
-    {
-      snprintf(pszOutBuf + i*2, bufferSize-(i*2), "%02x", sums[i]);
-    }
+  for(i=0; i<HASH_SIZE; i++) {
+    snprintf(pszOutBuf + i*2, bufferSize-(i*2), "%02x", sums[i]);
+  }
 
-    return pszOutBuf;
+  return pszOutBuf;
 }
 
 char *msCommifyString(char *str)
 {
-	int i, j, old_length, new_length;
+  int i, j, old_length, new_length;
   int num_commas=0, num_decimal_points=0;
   int add_commas;
 
@@ -1437,7 +1383,7 @@ char *msCommifyString(char *str)
   str[new_length] = '\0';
 
   j = 0;
-  for(i=new_length-1;i>=0;i--) { /* step backwards through the string */
+  for(i=new_length-1; i>=0; i--) { /* step backwards through the string */
 
     if(num_decimal_points == 1 &&  add_commas == 0) { /* to the right of the decimal point, no commas */
       str[i] = str[i-num_commas];
@@ -1465,72 +1411,73 @@ char *msCommifyString(char *str)
 /* ------------------------------------------------------------------------------- */
 char *msCaseReplaceSubstring(char *str, const char *old, const char *new)
 {
-      size_t str_len, old_len, new_len, tmp_offset;
-      char *tmp_ptr;
+  size_t str_len, old_len, new_len, tmp_offset;
+  char *tmp_ptr;
 
-      if(new == NULL)
-          new = "";
+  if(new == NULL)
+    new = "";
 
-      /*
-      ** If old is not found then leave str alone
-      */
-      if( (tmp_ptr = (char *) strcasestr(str, old)) == NULL)
-	return(str);
+  /*
+  ** If old is not found then leave str alone
+  */
+  if( (tmp_ptr = (char *) strcasestr(str, old)) == NULL)
+    return(str);
 
-      /*
-      ** Grab some info about incoming strings
-      */
-      str_len = strlen(str);
-      old_len = strlen(old);
-      new_len = strlen(new);
+  /*
+  ** Grab some info about incoming strings
+  */
+  str_len = strlen(str);
+  old_len = strlen(old);
+  new_len = strlen(new);
 
-      /*
-      ** Now loop until old is NOT found in new
-      */
-      while( tmp_ptr != NULL ) {
-
-	/*
-	** re-allocate memory for buf assuming 1 replacement of old with new
-        ** don't bother reallocating if old is larger than new)
-	*/
-        if (old_len < new_len) {
-          tmp_offset = tmp_ptr - str;
-          str_len = str_len - old_len + new_len;
-          str = (char *)msSmallRealloc(str, (str_len + 1)); /* make new space for a copy */
-          tmp_ptr = str + tmp_offset;
-        }
+  /*
+  ** Now loop until old is NOT found in new
+  */
+  while( tmp_ptr != NULL ) {
 
-        /*
-        ** Move the trailing part of str to make some room unless old_len == new_len
-        */
-        if (old_len != new_len) {
-            memmove(tmp_ptr+new_len, tmp_ptr+old_len, strlen(tmp_ptr)-old_len+1);
-        }
+    /*
+    ** re-allocate memory for buf assuming 1 replacement of old with new
+          ** don't bother reallocating if old is larger than new)
+    */
+    if (old_len < new_len) {
+      tmp_offset = tmp_ptr - str;
+      str_len = str_len - old_len + new_len;
+      str = (char *)msSmallRealloc(str, (str_len + 1)); /* make new space for a copy */
+      tmp_ptr = str + tmp_offset;
+    }
 
-        /*
-        ** Now copy new over old
-        */
-        memcpy(tmp_ptr, new, new_len);
+    /*
+    ** Move the trailing part of str to make some room unless old_len == new_len
+    */
+    if (old_len != new_len) {
+      memmove(tmp_ptr+new_len, tmp_ptr+old_len, strlen(tmp_ptr)-old_len+1);
+    }
 
-        /*
-        ** And look for more matches in the rest of the string
-        */
-        tmp_ptr = (char *) strcasestr(tmp_ptr + new_len, old);
-      }
+    /*
+    ** Now copy new over old
+    */
+    memcpy(tmp_ptr, new, new_len);
 
-      return(str);
+    /*
+    ** And look for more matches in the rest of the string
+    */
+    tmp_ptr = (char *) strcasestr(tmp_ptr + new_len, old);
+  }
+
+  return(str);
 }
 
-/* 
+/*
 ** Converts a 2 character hexidecimal string to an integer.
 */
-int msHexToInt(char *hex) {
+int msHexToInt(char *hex)
+{
   int number;
 
   number = (hex[0] >= 'A' ? ((hex[0] & 0xdf) - 'A')+10 : (hex[0] - '0'));
   number *= 16;
   number += (hex[1] >= 'A' ? ((hex[1] & 0xdf) - 'A')+10 : (hex[1] - '0'));
-   
+
   return(number);
 }
 
@@ -1545,7 +1492,7 @@ char *msGetFriBidiEncodedString(const char *string, const char *encoding)
   FriBidiChar logical[MAX_STR_LEN];
   FriBidiCharType base = FRIBIDI_TYPE_ON;
   size_t len;
-  
+
 #ifdef FRIBIDI_NO_CHARSETS
   iconv_t to_ucs4, from_ucs4;
 #else
@@ -1569,7 +1516,7 @@ char *msGetFriBidiEncodedString(const char *string, const char *encoding)
   if (!to_char_set_num || !from_char_set_num)
 #endif
   {
-    msSetError(MS_IDENTERR, "Encoding not supported (%s).", 
+    msSetError(MS_IDENTERR, "Encoding not supported (%s).",
                "msGetFriBidiEncodedString()", encoding);
     return NULL;
   }
@@ -1602,12 +1549,12 @@ char *msGetFriBidiEncodedString(const char *string, const char *encoding)
 
     /* Create a bidi string. */
     log2vis = fribidi_log2vis (logical, len, &base,
-       /* output */
-       visual, ltov, vtol, levels);
+                               /* output */
+                               visual, ltov, vtol, levels);
 
     if (!log2vis) {
-      msSetError(MS_IDENTERR, "Failed to create bidi string.", 
-             "msGetFriBidiEncodedString()");
+      msSetError(MS_IDENTERR, "Failed to create bidi string.",
+                 "msGetFriBidiEncodedString()");
       return NULL;
     }
 
@@ -1622,31 +1569,28 @@ char *msGetFriBidiEncodedString(const char *string, const char *encoding)
       iconv (from_ucs4, &ust, &in_len, &str, (int *) &new_len);
       *str = '\0';
       new_len = str - outstring;
-     }
+    }
 #else
-     new_len =
-       fribidi_unicode_to_charset (from_char_set_num,
-           visual, len, outstring);
+    new_len =
+      fribidi_unicode_to_charset (from_char_set_num,
+                                  visual, len, outstring);
 
     /* scan str and compress out FRIBIDI_CHAR_FILL UTF8 characters */
 
-    for (i=0, j=0; i<new_len; i++, j++)
-    {
-      if (outstring[i] == '\xef' && outstring[i+1] == '\xbb' && outstring[i+2] == '\xbf')
-      {
-         i += 3;
+    for (i=0, j=0; i<new_len; i++, j++) {
+      if (outstring[i] == '\xef' && outstring[i+1] == '\xbb' && outstring[i+2] == '\xbf') {
+        i += 3;
       }
-      if (i != j)
-      {
+      if (i != j) {
         outstring[j] = outstring[i];
       }
     }
     outstring[j] = '\0';
 
 #endif
-    
-     free(visual);
-     return msStrdup(outstring);
+
+    free(visual);
+    return msStrdup(outstring);
   }
 }
 #endif
@@ -1666,15 +1610,15 @@ char *msGetEncodedString(const char *string, const char *encoding)
 #ifdef USE_FRIBIDI
   if(fribidi_parse_charset ((char*)encoding))
     return msGetFriBidiEncodedString(string, encoding);
-#endif 
+#endif
   len = strlen(string);
 
   if (len == 0 || (encoding && strcasecmp(encoding, "UTF-8")==0))
-      return msStrdup(string);    /* Nothing to do: string already in UTF-8 */
+    return msStrdup(string);    /* Nothing to do: string already in UTF-8 */
 
   cd = iconv_open("UTF-8", encoding);
   if(cd == (iconv_t)-1) {
-    msSetError(MS_IDENTERR, "Encoding not supported by libiconv (%s).", 
+    msSetError(MS_IDENTERR, "Encoding not supported by libiconv (%s).",
                "msGetEncodedString()", encoding);
     return NULL;
   }
@@ -1682,7 +1626,7 @@ char *msGetEncodedString(const char *string, const char *encoding)
   bufsize = len * 6 + 1; /* Each UTF-8 char can be up to 6 bytes */
   inp = string;
   out = (char*) malloc(bufsize);
-  if(out == NULL){
+  if(out == NULL) {
     msSetError(MS_MEMERR, NULL, "msGetEncodedString()");
     iconv_close(cd);
     return NULL;
@@ -1693,22 +1637,22 @@ char *msGetEncodedString(const char *string, const char *encoding)
   bufleft = bufsize;
   iconv_status = -1;
 
-  while (len > 0){
+  while (len > 0) {
     iconv_status = iconv(cd, (char**)&inp, &len, &outp, &bufleft);
-    if(iconv_status == -1){
+    if(iconv_status == -1) {
       msFree(out);
       iconv_close(cd);
       return msStrdup(string);
     }
   }
   out[bufsize - bufleft] = '\0';
-  
+
   iconv_close(cd);
 
   return out;
 #else
   if (*string == '\0' || (encoding && strcasecmp(encoding, "UTF-8")==0))
-      return msStrdup(string);    /* Nothing to do: string already in UTF-8 */
+    return msStrdup(string);    /* Nothing to do: string already in UTF-8 */
 
   msSetError(MS_MISCERR, "Not implemeted since Iconv is not enabled.", "msGetEncodedString()");
   return NULL;
@@ -1716,81 +1660,80 @@ char *msGetEncodedString(const char *string, const char *encoding)
 }
 
 
-char* msConvertWideStringToUTF8 (const wchar_t* string, const char* encoding) {
+char* msConvertWideStringToUTF8 (const wchar_t* string, const char* encoding)
+{
 #ifdef USE_ICONV
 
-    char* output = NULL;
-    char* errormessage = NULL;
-    iconv_t cd = NULL;
-    size_t nStr;
-    size_t nInSize;
-    size_t nOutSize;
-    size_t iconv_status = -1;
-    size_t nBufferSize;
-
-    char* pszUTF8 = NULL;
-    const wchar_t* pwszWide = NULL;
-
-    if (string != NULL)
-    {   
-        nStr = wcslen (string);
-        nBufferSize = ((nStr * 6) + 1);
-        output = (char*) msSmallMalloc (nBufferSize);
-
-        if (nStr == 0) {
-            /* return an empty 8 byte string */
-            output[0] = '\0';
-            return output;
-        }
+  char* output = NULL;
+  char* errormessage = NULL;
+  iconv_t cd = NULL;
+  size_t nStr;
+  size_t nInSize;
+  size_t nOutSize;
+  size_t iconv_status = -1;
+  size_t nBufferSize;
 
-        cd = iconv_open("UTF-8", encoding);
-        
-        nOutSize = nBufferSize;
-        if ((iconv_t)-1 != cd)
-        {  
-            nInSize = sizeof (wchar_t)*nStr;
-            pszUTF8 = output;
-            pwszWide = string;
-            iconv_status = iconv(cd, (char **)&pwszWide, &nInSize, &pszUTF8, &nOutSize);
-            if ((size_t)-1 == iconv_status) {
-                switch (errno) {
-                    case E2BIG:
-                    errormessage = "There is not sufficient room in buffer";
-                    break;
-                    case EILSEQ:
-                    errormessage = "An invalid multibyte sequence has been encountered in the input";
-                    break;
-                    case EINVAL:
-                    errormessage = "An incomplete multibyte sequence has been encountered in the input";
-                    break;
-                    default:
-                    errormessage = "Unknown";
-                    break;
-                }
-                msSetError(MS_MISCERR, "Unable to convert string in encoding '%s' to UTF8 %s",
-                                       "msConvertWideStringToUTF8()",
-                           encoding,errormessage);
-                iconv_close(cd);
-                msFree(output);
-                return NULL;
-            }
-            iconv_close(cd);
-        } else {
-            msSetError(MS_MISCERR, "Encoding not supported by libiconv (%s).", 
-                                   "msConvertWideStringToUTF8()", 
-                                   encoding);
-            msFree(output);
-            return NULL;
+  char* pszUTF8 = NULL;
+  const wchar_t* pwszWide = NULL;
+
+  if (string != NULL) {
+    nStr = wcslen (string);
+    nBufferSize = ((nStr * 6) + 1);
+    output = (char*) msSmallMalloc (nBufferSize);
+
+    if (nStr == 0) {
+      /* return an empty 8 byte string */
+      output[0] = '\0';
+      return output;
+    }
+
+    cd = iconv_open("UTF-8", encoding);
+
+    nOutSize = nBufferSize;
+    if ((iconv_t)-1 != cd) {
+      nInSize = sizeof (wchar_t)*nStr;
+      pszUTF8 = output;
+      pwszWide = string;
+      iconv_status = iconv(cd, (char **)&pwszWide, &nInSize, &pszUTF8, &nOutSize);
+      if ((size_t)-1 == iconv_status) {
+        switch (errno) {
+          case E2BIG:
+            errormessage = "There is not sufficient room in buffer";
+            break;
+          case EILSEQ:
+            errormessage = "An invalid multibyte sequence has been encountered in the input";
+            break;
+          case EINVAL:
+            errormessage = "An incomplete multibyte sequence has been encountered in the input";
+            break;
+          default:
+            errormessage = "Unknown";
+            break;
         }
-   
-    } else {
-        /* we were given a NULL wide string, nothing we can do here */
+        msSetError(MS_MISCERR, "Unable to convert string in encoding '%s' to UTF8 %s",
+                   "msConvertWideStringToUTF8()",
+                   encoding,errormessage);
+        iconv_close(cd);
+        msFree(output);
         return NULL;
+      }
+      iconv_close(cd);
+    } else {
+      msSetError(MS_MISCERR, "Encoding not supported by libiconv (%s).",
+                 "msConvertWideStringToUTF8()",
+                 encoding);
+      msFree(output);
+      return NULL;
     }
-    
-    /* NULL-terminate the output string */
-    output[nBufferSize - nOutSize] = '\0';
-    return output;
+
+  } else {
+    /* we were given a NULL wide string, nothing we can do here */
+    return NULL;
+  }
+
+  /* NULL-terminate the output string */
+  output[nBufferSize - nOutSize] = '\0';
+  return output;
 #else
   msSetError(MS_MISCERR, "Not implemented since Iconv is not enabled.", "msConvertWideStringToUTF8()");
   return NULL;
@@ -1801,7 +1744,7 @@ char* msConvertWideStringToUTF8 (const wchar_t* string, const char* encoding) {
 ** Returns the next glyph in string and advances *in_ptr to the next
 ** character.
 **
-** If out_string is not NULL then the character (bytes) is copied to this 
+** If out_string is not NULL then the character (bytes) is copied to this
 ** buffer and null-terminated. out_string must be a pre-allocated buffer of
 ** at least 11 bytes.
 **
@@ -1811,12 +1754,12 @@ char* msConvertWideStringToUTF8 (const wchar_t* string, const char* encoding) {
 *   - as an html entity, for example { , &#x1af; , or é
 *   - as an utf8 encoded character
 *   - if utf8 decoding fails, as a raw character
-* 
-** This function mimics the character decoding function used in gdft.c of 
+*
+** This function mimics the character decoding function used in gdft.c of
 * libGD. It is necessary to have the same behaviour, as input strings must be
 * split into the same glyphs as what gd does.
 **
-** In UTF-8, the number of leading 1 bits in the first byte specifies the 
+** In UTF-8, the number of leading 1 bits in the first byte specifies the
 ** number of bytes in the entire sequence.
 ** Source: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
 **
@@ -1829,114 +1772,105 @@ char* msConvertWideStringToUTF8 (const wchar_t* string, const char* encoding) {
 */
 int msGetNextGlyph(const char **in_ptr, char *out_string)
 {
-    unsigned char in;
-    int numbytes=0,unicode;
-    int i;
-
-    in = (unsigned char)**in_ptr;
-
-    if (in == 0)
-        return -1;  /* Empty string */
-    if((numbytes=msGetUnicodeEntity(*in_ptr,&unicode))>0) {
-        if(out_string) {
-            for(i=0;i<numbytes;i++) {
-                out_string[i]=(*in_ptr)[i];
-            }
-            out_string[numbytes]='\0';
-        }
-        *in_ptr+=numbytes;
-        return numbytes;
-    }
-    if (in < 0xC0)
-    {/*
-     * Handles properly formed UTF-8 characters between
-     * 0x01 and 0x7F.  Also treats \0 and naked trail
-     * bytes 0x80 to 0xBF as valid characters representing
-     * themselves.
-     */
-        /*goto end of loop to return just the char*/
-    }
-    else if (in < 0xE0)
-    {
-        if (((*in_ptr)[1]& 0xC0) == 0x80) {
-            if(out_string) {
-                out_string[0]=in;
-                out_string[1]=(*in_ptr)[1];
-                out_string[2]='\0';
-            }
-            *in_ptr+=2;
-            return 2; /*110xxxxx 10xxxxxx*/
-        }
+  unsigned char in;
+  int numbytes=0,unicode;
+  int i;
+
+  in = (unsigned char)**in_ptr;
+
+  if (in == 0)
+    return -1;  /* Empty string */
+  if((numbytes=msGetUnicodeEntity(*in_ptr,&unicode))>0) {
+    if(out_string) {
+      for(i=0; i<numbytes; i++) {
+        out_string[i]=(*in_ptr)[i];
+      }
+      out_string[numbytes]='\0';
     }
-    else if (in < 0xF0)
-    {
-        if (((*in_ptr)[1]& 0xC0) == 0x80 && ((*in_ptr)[2]& 0xC0) == 0x80) {
-            if(out_string) {
-                out_string[0]=in;
-                *in_ptr+=numbytes;  out_string[1]=(*in_ptr)[1];
-                out_string[2]=(*in_ptr)[2];
-                out_string[3]='\0';
-            }
-            *in_ptr+=3;
-            return 3;   /* 1110xxxx 10xxxxxx 10xxxxxx */
-        }
+    *in_ptr+=numbytes;
+    return numbytes;
+  }
+  if (in < 0xC0) {
+    /*
+    * Handles properly formed UTF-8 characters between
+    * 0x01 and 0x7F.  Also treats \0 and naked trail
+    * bytes 0x80 to 0xBF as valid characters representing
+    * themselves.
+    */
+    /*goto end of loop to return just the char*/
+  } else if (in < 0xE0) {
+    if (((*in_ptr)[1]& 0xC0) == 0x80) {
+      if(out_string) {
+        out_string[0]=in;
+        out_string[1]=(*in_ptr)[1];
+        out_string[2]='\0';
+      }
+      *in_ptr+=2;
+      return 2; /*110xxxxx 10xxxxxx*/
     }
-    else if (in < 0xF8)
-    {
-        if (((*in_ptr)[1]& 0xC0) == 0x80 && ((*in_ptr)[2]& 0xC0) == 0x80 
-                && ((*in_ptr)[3]& 0xC0) == 0x80) {
-            if(out_string) {
-                out_string[0]=in;
-                out_string[1]=(*in_ptr)[1];
-                out_string[2]=(*in_ptr)[2];
-                out_string[3]=(*in_ptr)[3];
-                out_string[4]='\0';
-            }
-            *in_ptr+=4;
-            return 4;   /* 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */
-        }
+  } else if (in < 0xF0) {
+    if (((*in_ptr)[1]& 0xC0) == 0x80 && ((*in_ptr)[2]& 0xC0) == 0x80) {
+      if(out_string) {
+        out_string[0]=in;
+        *in_ptr+=numbytes;
+        out_string[1]=(*in_ptr)[1];
+        out_string[2]=(*in_ptr)[2];
+        out_string[3]='\0';
+      }
+      *in_ptr+=3;
+      return 3;   /* 1110xxxx 10xxxxxx 10xxxxxx */
     }
-    else if (in < 0xFC)
-    {
-        if (((*in_ptr)[1]& 0xC0) == 0x80 && ((*in_ptr)[2]& 0xC0) == 0x80 
-                && ((*in_ptr)[3]& 0xC0) == 0x80 && ((*in_ptr)[4]& 0xC0) == 0x80) {
-            if(out_string) {
-                out_string[0]=in;
-                out_string[1]=(*in_ptr)[1];
-                out_string[2]=(*in_ptr)[2];
-                out_string[3]=(*in_ptr)[3];
-                out_string[4]=(*in_ptr)[4];
-                out_string[5]='\0';
-            }
-            *in_ptr+=5;
-            return 5;   /* 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx */
-        }
+  } else if (in < 0xF8) {
+    if (((*in_ptr)[1]& 0xC0) == 0x80 && ((*in_ptr)[2]& 0xC0) == 0x80
+        && ((*in_ptr)[3]& 0xC0) == 0x80) {
+      if(out_string) {
+        out_string[0]=in;
+        out_string[1]=(*in_ptr)[1];
+        out_string[2]=(*in_ptr)[2];
+        out_string[3]=(*in_ptr)[3];
+        out_string[4]='\0';
+      }
+      *in_ptr+=4;
+      return 4;   /* 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */
     }
-    else if (in < 0xFE)
-    {
-        if (((*in_ptr)[1]& 0xC0) == 0x80 && ((*in_ptr)[2]& 0xC0) == 0x80 
-                && ((*in_ptr)[3]& 0xC0) == 0x80 && ((*in_ptr)[4]& 0xC0) == 0x80
-                && ((*in_ptr)[5]& 0xC0) == 0x80) {
-            if(out_string) {
-                out_string[0]=in;
-                out_string[1]=(*in_ptr)[1];
-                out_string[2]=(*in_ptr)[2];
-                out_string[3]=(*in_ptr)[3];
-                out_string[4]=(*in_ptr)[4];
-                out_string[5]=(*in_ptr)[5];
-                out_string[6]='\0';
-            }
-            *in_ptr+=6;
-            return 6;   /* 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx */
-        }
+  } else if (in < 0xFC) {
+    if (((*in_ptr)[1]& 0xC0) == 0x80 && ((*in_ptr)[2]& 0xC0) == 0x80
+        && ((*in_ptr)[3]& 0xC0) == 0x80 && ((*in_ptr)[4]& 0xC0) == 0x80) {
+      if(out_string) {
+        out_string[0]=in;
+        out_string[1]=(*in_ptr)[1];
+        out_string[2]=(*in_ptr)[2];
+        out_string[3]=(*in_ptr)[3];
+        out_string[4]=(*in_ptr)[4];
+        out_string[5]='\0';
+      }
+      *in_ptr+=5;
+      return 5;   /* 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx */
     }
-    
-    if (out_string) {
+  } else if (in < 0xFE) {
+    if (((*in_ptr)[1]& 0xC0) == 0x80 && ((*in_ptr)[2]& 0xC0) == 0x80
+        && ((*in_ptr)[3]& 0xC0) == 0x80 && ((*in_ptr)[4]& 0xC0) == 0x80
+        && ((*in_ptr)[5]& 0xC0) == 0x80) {
+      if(out_string) {
         out_string[0]=in;
-        out_string[1] = '\0';   /* 0xxxxxxx */
+        out_string[1]=(*in_ptr)[1];
+        out_string[2]=(*in_ptr)[2];
+        out_string[3]=(*in_ptr)[3];
+        out_string[4]=(*in_ptr)[4];
+        out_string[5]=(*in_ptr)[5];
+        out_string[6]='\0';
+      }
+      *in_ptr+=6;
+      return 6;   /* 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx */
     }
-    (*in_ptr)++;
-    return 1;
+  }
+
+  if (out_string) {
+    out_string[0]=in;
+    out_string[1] = '\0';   /* 0xxxxxxx */
+  }
+  (*in_ptr)++;
+  return 1;
 }
 
 /*
@@ -1944,98 +1878,92 @@ int msGetNextGlyph(const char **in_ptr, char *out_string)
 */
 int msGetNumGlyphs(const char *in_ptr)
 {
-    int numchars=0;
+  int numchars=0;
 
-    while( msGetNextGlyph(&in_ptr, NULL) != -1 )
-        numchars++;
+  while( msGetNextGlyph(&in_ptr, NULL) != -1 )
+    numchars++;
 
-    return numchars;
+  return numchars;
 }
 
-static int cmp_entities(const void *e1, const void *e2) {
+static int cmp_entities(const void *e1, const void *e2)
+{
   struct mapentities_s *en1 = (struct mapentities_s *) e1;
   struct mapentities_s *en2 = (struct mapentities_s *) e2;
   return strcmp(en1->name, en2->name);
 }
 /*
  * this function tests if the string pointed by inptr represents
- * an HTML entity, in decimal form ( e.g. Å), in hexadecimal 
+ * an HTML entity, in decimal form ( e.g. Å), in hexadecimal
  * form ( e.g. &#x6C34; ), or from html 4.0 spec ( e.g. é )
- * - returns returns 0 if the string doesn't represent such an entity. 
- * - if the string does start with such entity,it returns the number of 
+ * - returns returns 0 if the string doesn't represent such an entity.
+ * - if the string does start with such entity,it returns the number of
  * bytes occupied by said entity, and stores the unicode value in *unicode
  */
-int msGetUnicodeEntity(const char *inptr, int *unicode) {
-    unsigned char *in = (unsigned char*)inptr;
-    int l,val=0;   
-    if(*in=='&') {
+int msGetUnicodeEntity(const char *inptr, int *unicode)
+{
+  unsigned char *in = (unsigned char*)inptr;
+  int l,val=0;
+  if(*in=='&') {
+    in++;
+    if(*in=='#') {
+      in++;
+      if(*in=='x'||*in=='X') {
         in++;
-        if(*in=='#') {
+        for(l=3; l<8; l++) {
+          char byte;
+          if(*in>='0'&&*in<='9')
+            byte = *in - '0';
+          else if(*in>='a'&&*in<='f')
+            byte = *in - 'a' + 10;
+          else if(*in>='A'&&*in<='F')
+            byte = *in - 'A' + 10;
+          else
+            break;
+          in++;
+          val = (val * 16) + byte;
+        }
+        if(*in==';' && l>3 ) {
+          *unicode=val;
+          return ++l;
+        }
+      } else {
+        for(l=2; l<8; l++) {
+          if(*in>='0'&&*in<='9') {
+            val = val*10+*in-'0';
             in++;
-            if(*in=='x'||*in=='X') {
-                in++;
-                for(l=3;l<8;l++) {
-                    char byte;
-                    if(*in>='0'&&*in<='9')
-                        byte = *in - '0';
-                    else if(*in>='a'&&*in<='f')
-                        byte = *in - 'a' + 10;
-                    else if(*in>='A'&&*in<='F')
-                        byte = *in - 'A' + 10;
-                    else
-                        break;
-                    in++;
-                    val = (val * 16) + byte;
-                }
-                if(*in==';' && l>3 ) {
-                    *unicode=val;
-                    return ++l;
-                }
-            } 
-            else
-            {
-                for(l=2;l<8;l++) {
-                    if(*in>='0'&&*in<='9') {
-                        val = val*10+*in-'0';
-                        in++;
-                    }
-                    else
-                        break;
-                }
-                if(*in==';' && l>2 ) {
-                    *unicode=val;
-                    return ++l;
-                }
-            }
+          } else
+            break;
         }
-        else
-        {
-            char entity_name_buf[MAP_ENTITY_NAME_LENGTH_MAX+1];
-            char *p;
-            struct mapentities_s key, *res;
-            key.name = p = entity_name_buf;
-            for (l = 1; l <=  MAP_ENTITY_NAME_LENGTH_MAX+1; l++)
-            {
-                if (*in == '\0') /*end of string before possible entity: return*/
-                    break;
-                if (*in == ';') /*possible end of entity: do a lookup*/
-                {
-                    *p++ = '\0';
-                    res = bsearch(&key, mapentities, MAP_NR_OF_ENTITIES,
-                            sizeof(mapentities[0]), *cmp_entities);
-                    if (res)
-                    {
-                        *unicode = res->value;
-                        return ++l;
-                    }
-                    break; /*the string was of the form of an entity but didn't correspond to an existing one: return*/
-                }
-                *p++ = *in;
-                in++;
-            }
+        if(*in==';' && l>2 ) {
+          *unicode=val;
+          return ++l;
         }
+      }
+    } else {
+      char entity_name_buf[MAP_ENTITY_NAME_LENGTH_MAX+1];
+      char *p;
+      struct mapentities_s key, *res;
+      key.name = p = entity_name_buf;
+      for (l = 1; l <=  MAP_ENTITY_NAME_LENGTH_MAX+1; l++) {
+        if (*in == '\0') /*end of string before possible entity: return*/
+          break;
+        if (*in == ';') { /*possible end of entity: do a lookup*/
+          *p++ = '\0';
+          res = bsearch(&key, mapentities, MAP_NR_OF_ENTITIES,
+                        sizeof(mapentities[0]), *cmp_entities);
+          if (res) {
+            *unicode = res->value;
+            return ++l;
+          }
+          break; /*the string was of the form of an entity but didn't correspond to an existing one: return*/
+        }
+        *p++ = *in;
+        in++;
+      }
     }
-    return 0;
+  }
+  return 0;
 }
 
 /**
@@ -2048,7 +1976,8 @@ int msGetUnicodeEntity(const char *inptr, int *unicode) {
  * @return MS_SUCCESS or MS_FAILURE
  */
 
-int msStringIsInteger(const char *string) {
+int msStringIsInteger(const char *string)
+{
   int length, i;
 
   length = strlen(string);
@@ -2056,7 +1985,7 @@ int msStringIsInteger(const char *string) {
   if (length == 0)
     return MS_FAILURE;
 
-  for(i=0;i<length;i++) {
+  for(i=0; i<length; i++) {
     if (!isdigit(string[i]))
       return MS_FAILURE;
   }
@@ -2064,45 +1993,6 @@ int msStringIsInteger(const char *string) {
   return MS_SUCCESS;
 }
 
-/**
- * msGetFirstLine()
- *
- * returns the first line of a given string.
- * called by getLabelSize functions for calculating 
- * the baseline offsets of labels
- *
- * this function was implemented to avoid using the 
- * msSplitString function and its multiple mallocs, as
- * only one malloc is used here.
- *
- * this function can be called if the input isn't a
- * multiline string, but this wastes a malloc
- */
-char* msGetFirstLine(char* text) {
-    int firstLineLength=0; /*number of bytes up to first \n character */
-    int glyphLength;
-    char glyph[11];
-    const char *textptr=text;
-    char *firstLine,*firstLineCur;
-    /*loop through glyphs in text*/
-    while((glyphLength=msGetNextGlyph(&textptr,glyph))) {
-        if(glyphLength==1 && *glyph=='\n') { /*we've hit the first \n char*/
-            firstLineCur = firstLine = msSmallMalloc(firstLineLength+1);
-            
-            /*copy the first line into the return array*/
-            while(firstLineLength--) {
-                *firstLineCur++ = *text++;
-            }
-            *firstLineCur='\0';
-            return firstLine;
-        }
-        /*increment byte count if we haven't hit a \n yet*/
-        firstLineLength+=glyphLength;
-    }
-    /*no newline found in text*/
-    return msStrdup(text);
-}
-
 /************************************************************************/
 /*                             msStrdup()                               */
 /************************************************************************/
@@ -2111,21 +2001,20 @@ char* msGetFirstLine(char* text) {
 
 char *msStrdup( const char * pszString )
 {
-    char        *pszReturn;
+  char        *pszReturn;
 
-    if( pszString == NULL )
-        pszString = "";
+  if( pszString == NULL )
+    pszString = "";
 
-    pszReturn = strdup( pszString );
+  pszReturn = strdup( pszString );
 
-    if( pszReturn == NULL )
-    {
-        fprintf(stderr, "msSmallMsStrdup(): Out of memory allocating %ld bytes.\n",
-                (long) strlen(pszString) );
-        exit(1);
-    }
+  if( pszReturn == NULL ) {
+    fprintf(stderr, "msSmallMsStrdup(): Out of memory allocating %ld bytes.\n",
+            (long) strlen(pszString) );
+    exit(1);
+  }
 
-    return( pszReturn );
+  return( pszReturn );
 }
 
 
@@ -2134,27 +2023,35 @@ char *msStrdup( const char * pszString )
 /************************************************************************/
 
 /* Checks if a string contains single or double quotes and escape them.
-   NOTE: the user have to free the returned char */
+   NOTE: the user must free the returned char* if it is different than the
+   one passed in */
 
 char* msStringEscape( const char * pszString )
 {
-    char *string_tmp, *string_ptr;
-    int i;
-    
-    if (pszString ==  NULL || strlen(pszString) == 0)
-        return msStrdup("");
-
-    string_tmp = (char*)msSmallMalloc((strlen(pszString)*2)+1);
-    for (string_ptr=(char*)pszString,i=0; *string_ptr!='\0'; ++string_ptr,++i) {
-        if ( (*string_ptr == '\"') || (*string_ptr == '\'') ) {
-            string_tmp[i] = '\\';
-            ++i;
-        }
-        string_tmp[i] = *string_ptr;
+  char *string_tmp, *string_ptr;
+  int i,ncharstoescape=0;
+
+  if (pszString ==  NULL || strlen(pszString) == 0)
+    return msStrdup("");
+
+  for (i=0; pszString[i]; i++)
+    ncharstoescape += ((pszString[i] == '\"')||(pszString[i] == '\''));
+  
+  if(!ncharstoescape) {
+    return (char*)pszString;
+  }
+
+  string_tmp = (char*)msSmallMalloc(strlen(pszString)+ncharstoescape+1);
+  for (string_ptr=(char*)pszString,i=0; *string_ptr!='\0'; ++string_ptr,++i) {
+    if ( (*string_ptr == '\"') || (*string_ptr == '\'') ) {
+      string_tmp[i] = '\\';
+      ++i;
     }
+    string_tmp[i] = *string_ptr;
+  }
 
-    string_tmp[i] = '\0';
-    return string_tmp;
+  string_tmp[i] = '\0';
+  return string_tmp;
 }
 
 /************************************************************************/
@@ -2164,10 +2061,10 @@ char* msStringEscape( const char * pszString )
 /* Check if a string is in a array */
 int msStringInArray( const char * pszString, char **array, int numelements)
 {
-    int i;
-    for (i=0;i<numelements;++i) {
-        if (strcasecmp(pszString, array[i])==0)
-            return MS_TRUE;
-    }
-    return MS_FALSE;
+  int i;
+  for (i=0; i<numelements; ++i) {
+    if (strcasecmp(pszString, array[i])==0)
+      return MS_TRUE;
+  }
+  return MS_FALSE;
 }
diff --git a/mapsymbol.c b/mapsymbol.c
index 164a0ac..2c1c35a 100644
--- a/mapsymbol.c
+++ b/mapsymbol.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -35,7 +35,7 @@
 #include "mapcopy.h"
 #include "mapthread.h"
 
-MS_CVSID("$Id$")
+
 
 extern int msyylex(void); /* lexer globals */
 extern void msyyrestart(FILE *);
@@ -44,6 +44,8 @@ extern char *msyystring_buffer;
 extern int msyylineno;
 extern FILE *msyyin;
 
+extern int msyystate;
+
 static const unsigned char PNGsig[8] = {137, 80, 78, 71, 13, 10, 26, 10}; /* 89 50 4E 47 0D 0A 1A 0A hex */
 static const unsigned char JPEGsig[3] = {255, 216, 255}; /* FF D8 FF hex */
 
@@ -52,8 +54,8 @@ void freeImageCache(struct imageCacheObj *ic)
 {
   if(ic) {
     freeImageCache(ic->next); /* free any children */
-   	msFreeRasterBuffer(&(ic->img));
-    free(ic);  
+    msFreeRasterBuffer(&(ic->img));
+    free(ic);
   }
   return;
 }
@@ -66,28 +68,35 @@ void freeImageCache(struct imageCacheObj *ic)
 ** is adjusted to the size that becomes the height.
 ** See mapgd.c // size ~ height in pixels
 */
-double msSymbolGetDefaultSize(symbolObj *s) {
+double msSymbolGetDefaultSize(symbolObj *s)
+{
   double size;
-
   if(s == NULL)
-      return 1;
+    return 1;
 
-  switch(s->type) {  
+  switch(s->type) {
     case(MS_SYMBOL_TRUETYPE):
       size = 1;
       break;
     case(MS_SYMBOL_PIXMAP):
       assert(s->pixmap_buffer != NULL);
-      if(s->pixmap_buffer == NULL) return 1; //FIXME
+      if(s->pixmap_buffer == NULL) return 1; /* FIXME */
       size = (double)s->pixmap_buffer->height;
       break;
+    case(MS_SYMBOL_SVG):
+      size = 1;
+#ifdef USE_SVG_CAIRO
+      assert(s->renderer_cache != NULL);
+      size = s->sizey;
+#endif
+      break;
     default: /* vector and ellipses, scalable */
       size = s->sizey;
       break;
   }
 
   if(size <= 0)
-      return 1;
+    return 1;
 
   return size;
 }
@@ -113,159 +122,167 @@ void initSymbol(symbolObj *s)
   s->full_font_path = NULL;
   s->full_pixmap_path = NULL;
   s->character = NULL;
+  s->anchorpoint_x = s->anchorpoint_y = 0.5;
 
   s->svg_text = NULL;
+
 }
 
-int msFreeSymbol(symbolObj *s) {
+int msFreeSymbol(symbolObj *s)
+{
   if(!s) return MS_FAILURE;
   if( MS_REFCNT_DECR_IS_NOT_ZERO(s) ) {
-  	return MS_FAILURE;
+    return MS_FAILURE;
   }
-  
+
   if(s->name) free(s->name);
   if(s->renderer!=NULL) {
-	  s->renderer->freeSymbol(s);
+    s->renderer->freeSymbol(s);
   }
   if(s->pixmap_buffer) {
-      msFreeRasterBuffer(s->pixmap_buffer);
-      free(s->pixmap_buffer);
+    msFreeRasterBuffer(s->pixmap_buffer);
+    free(s->pixmap_buffer);
   }
 
+
   if(s->font) free(s->font);
   msFree(s->full_font_path);
   msFree(s->full_pixmap_path);
   if(s->imagepath) free(s->imagepath);
   if(s->character) free(s->character);
-  
+
+  if (s->svg_text)
+    msFree(s->svg_text);
+
   return MS_SUCCESS;
 }
 
 int loadSymbol(symbolObj *s, char *symbolpath)
 {
   int done=MS_FALSE;
-  FILE *stream;
   char szPath[MS_MAXPATHLEN];
-  int file_len = 0;
-  
+
   initSymbol(s);
 
   for(;;) {
     switch(msyylex()) {
-    case(ANTIALIAS):
-      if((s->antialias = getSymbol(2,MS_TRUE,MS_FALSE)) == -1)
-	return(-1);
-      break;    
-    case(CHARACTER):
-      if(getString(&s->character) == MS_FAILURE) return(-1);
-      break;
-    case(END): /* do some error checking */
-      if((s->type == MS_SYMBOL_SVG) && (s->imagepath == NULL)) {
-	    msSetError(MS_SYMERR, "Symbol of type SVG has no file path specified.", "loadSymbol()");
-		return(-1);
-	  }
-      if((s->type == MS_SYMBOL_PIXMAP) && (s->full_pixmap_path == NULL)) {
-	msSetError(MS_SYMERR, "Symbol of type PIXMAP has no image data.", "loadSymbol()"); 
-	return(-1);
-      }
-      if(((s->type == MS_SYMBOL_ELLIPSE) || (s->type == MS_SYMBOL_VECTOR)) && (s->numpoints == 0)) {
-	msSetError(MS_SYMERR, "Symbol of type VECTOR or ELLIPSE has no point data.", "loadSymbol()"); 
-	return(-1);
-      }
+      case(ANCHORPOINT):
+        if(getDouble(&(s->anchorpoint_x)) == -1) return MS_FAILURE;
+        if(getDouble(&(s->anchorpoint_y)) == -1) return MS_FAILURE;
+        if(s->anchorpoint_x<0 || s->anchorpoint_x>1 || s->anchorpoint_y<0 || s->anchorpoint_y>1) {
+          msSetError(MS_SYMERR, "ANCHORPOINT must be between 0 and 1", "loadSymbol()");
+          return(-1);
+        }
+        break;
+      case(ANTIALIAS):
+        if((s->antialias = getSymbol(2,MS_TRUE,MS_FALSE)) == -1)
+          return(-1);
+        break;
+      case(CHARACTER):
+        if(getString(&s->character) == MS_FAILURE) return(-1);
+        break;
+      case(END): /* do some error checking */
+        if((s->type == MS_SYMBOL_SVG) && (s->imagepath == NULL)) {
+          msSetError(MS_SYMERR, "Symbol of type SVG has no file path specified.", "loadSymbol()");
+          return(-1);
+        }
+        if((s->type == MS_SYMBOL_PIXMAP) && (s->full_pixmap_path == NULL)) {
+          msSetError(MS_SYMERR, "Symbol of type PIXMAP has no image data.", "loadSymbol()");
+          return(-1);
+        }
+        if(((s->type == MS_SYMBOL_ELLIPSE) || (s->type == MS_SYMBOL_VECTOR)) && (s->numpoints == 0)) {
+          msSetError(MS_SYMERR, "Symbol of type VECTOR or ELLIPSE has no point data.", "loadSymbol()");
+          return(-1);
+        }
+        if(s->type == MS_SYMBOL_VECTOR) {
+          double minx = s->points[0].x;
+          double miny = s->points[0].y;
+          /* should only negative points be shifted? (#4116)*/
+          int shiftpositive = ((s->anchorpoint_x!=0.5)||(s->anchorpoint_y!=0.5));
+          int i;
+          for(i=1; i<s->numpoints; i++) {
+            if(s->points[i].x != -99 && s->points[i].y != -99) {
+              if(s->points[i].x<minx) minx = s->points[i].x;
+              if(s->points[i].y<miny) miny = s->points[i].y;
+            }
+          }
+          if(minx<0 || miny<0 || (shiftpositive && (minx!=0 || miny!=0))) {
+            for(i=0; i<s->numpoints; i++) {
+              if(s->points[i].x != -99 && s->points[i].y != -99) {
+                s->points[i].x -= minx;
+                s->points[i].y -= miny;
+              }
+            }
+            s->sizex -= minx;
+            s->sizey -= miny;
+          }
+        }
 
-      return(0);
-      break;
-    case(EOF):
-      msSetError(MS_EOFERR, NULL, "loadSymbol()");      
-      return(-1);
-      break;
-    case(FILLED):      
-      if((s->filled = getSymbol(2,MS_TRUE,MS_FALSE)) == -1)
-	return(-1);
-      break;
-    case(FONT):
-      if(getString(&s->font) == MS_FAILURE) return(-1);
-      break;  
-    case(IMAGE):
-      if(msyylex() != MS_STRING) { /* get image location from next token */
-	msSetError(MS_TYPEERR, "Parsing error near (%s):(line %d)", "loadSymbol()", msyystring_buffer, msyylineno);
-	return(-1);
-      }
-      s->full_pixmap_path = msStrdup(msBuildPath(szPath, symbolpath, msyystring_buffer)); 
-      
-      /* Set imagepath */
-      s->imagepath = msStrdup(msyystring_buffer);
-
-      /* if this is SVG, load the SVG and
-         punt if this is for a SVG symbol */
-      if(s->type == MS_SYMBOL_SVG) {
-        if((stream = fopen(s->full_pixmap_path, "rb")) == NULL)
-        {
-	        msSetError(MS_IOERR, "Parsing error near (%s):(line %d)", "loadSymbol()", 
-                     msyystring_buffer, msyylineno);
-	        return(-1);
-        }      
-        fseek(stream, 0, SEEK_END);
-        file_len = ftell(stream);
-        rewind(stream);
-        s->svg_text = (char*)malloc(sizeof(char) * file_len);
-        if(1 != fread(s->svg_text, file_len, 1, stream)) {
-          msSetError(MS_IOERR, "failed to read %d bytes from svg file %s", "loadSymbol()", file_len, s->full_pixmap_path);
-          free(s->svg_text);
-          return -1;
+        return(0);
+        break;
+      case(EOF):
+        msSetError(MS_EOFERR, NULL, "loadSymbol()");
+        return(-1);
+        break;
+      case(FILLED):
+        if((s->filled = getSymbol(2,MS_TRUE,MS_FALSE)) == -1)
+          return(-1);
+        break;
+      case(FONT):
+        if(getString(&s->font) == MS_FAILURE) return(-1);
+        break;
+      case(IMAGE):
+        if(msyylex() != MS_STRING) { /* get image location from next token */
+          msSetError(MS_TYPEERR, "Parsing error near (%s):(line %d)", "loadSymbol()", msyystring_buffer, msyylineno);
+          return(-1);
         }
-        fclose(stream);
-	    break;
-      }
-      break;
-    case(NAME):
-      if(getString(&s->name) == MS_FAILURE) return(-1);
-      break;
-    case(POINTS):
-      done = MS_FALSE;
-      s->sizex = 0;
-      s->sizey = 0;
-      for(;;) {
-	switch(msyylex()) { 
-	case(END):
-	  done = MS_TRUE;
-	  break;
-	case(MS_NUMBER):
-	  s->points[s->numpoints].x = atof(msyystring_buffer); /* grab the x */
-	  if(getDouble(&(s->points[s->numpoints].y)) == -1) return(-1); /* grab the y */
-	  if(s->points[s->numpoints].x!=-99) {
-	  s->sizex = MS_MAX(s->sizex, s->points[s->numpoints].x);
-	  s->sizey = MS_MAX(s->sizey, s->points[s->numpoints].y);
-	  }
-	  s->numpoints++;
-	  break;
-	default:
-	  msSetError(MS_TYPEERR, "Parsing error near (%s):(line %d)", "loadSymbol()", msyystring_buffer, msyylineno);
-	  return(-1);
-	}
-
-	if(done == MS_TRUE)
-	  break;
-      }
-      break;    
-    case(TRANSPARENT):
-      s->transparent = MS_TRUE;
-      if(getInteger(&(s->transparentcolor)) == -1) return(-1);
-      break;
-    case(TYPE):
-#ifdef USE_GD_FT
-      if((s->type = getSymbol(8,MS_SYMBOL_VECTOR,MS_SYMBOL_ELLIPSE,MS_SYMBOL_PIXMAP,MS_SYMBOL_SIMPLE,MS_TRUETYPE,MS_SYMBOL_HATCH,MS_SYMBOL_SVG)) == -1)
-	return(-1);	
-#else
-      if((s->type = getSymbol(6,MS_SYMBOL_VECTOR,MS_SYMBOL_ELLIPSE,MS_SYMBOL_PIXMAP,MS_SYMBOL_SIMPLE,MS_SYMBOL_HATCH)) == -1)
-	return(-1);
-#endif
-      if(s->type == MS_TRUETYPE) /* TrueType keyword is valid several place in map files and symbol files, this simplifies the lexer */
-	s->type = MS_SYMBOL_TRUETYPE;
-      break;
-    default:
-      msSetError(MS_IDENTERR, "Parsing error near (%s):(line %d)", "loadSymbol()", msyystring_buffer, msyylineno);
-      return(-1);
+        s->full_pixmap_path = msStrdup(msBuildPath(szPath, symbolpath, msyystring_buffer));
+        /* Set imagepath */
+        s->imagepath = msStrdup(msyystring_buffer);
+        break;
+      case(NAME):
+        if(getString(&s->name) == MS_FAILURE) return(-1);
+        break;
+      case(POINTS):
+        done = MS_FALSE;
+        s->sizex = 0;
+        s->sizey = 0;
+        for(;;) {
+          switch(msyylex()) {
+            case(END):
+              done = MS_TRUE;
+              break;
+            case(MS_NUMBER):
+              s->points[s->numpoints].x = atof(msyystring_buffer); /* grab the x */
+              if(getDouble(&(s->points[s->numpoints].y)) == -1) return(-1); /* grab the y */
+              if(s->points[s->numpoints].x!=-99) {
+                s->sizex = MS_MAX(s->sizex, s->points[s->numpoints].x);
+                s->sizey = MS_MAX(s->sizey, s->points[s->numpoints].y);
+              }
+              s->numpoints++;
+              break;
+            default:
+              msSetError(MS_TYPEERR, "Parsing error near (%s):(line %d)", "loadSymbol()", msyystring_buffer, msyylineno);
+              return(-1);
+          }
+
+          if(done == MS_TRUE)
+            break;
+        }
+        break;
+      case(TRANSPARENT):
+        s->transparent = MS_TRUE;
+        if(getInteger(&(s->transparentcolor)) == -1) return(-1);
+        break;
+      case(TYPE):
+        if((s->type = getSymbol(8,MS_SYMBOL_VECTOR,MS_SYMBOL_ELLIPSE,MS_SYMBOL_PIXMAP,MS_SYMBOL_SIMPLE,MS_TRUETYPE,MS_SYMBOL_HATCH,MS_SYMBOL_SVG)) == -1)
+          return(-1);
+        if(s->type == MS_TRUETYPE) /* TrueType keyword is valid several place in map files and symbol files, this simplifies the lexer */
+          s->type = MS_SYMBOL_TRUETYPE;
+        break;
+      default:
+        msSetError(MS_IDENTERR, "Parsing error near (%s):(line %d)", "loadSymbol()", msyystring_buffer, msyylineno);
+        return(-1);
     } /* end switch */
   } /* end for */
 }
@@ -276,54 +293,54 @@ void writeSymbol(symbolObj *s, FILE *stream)
 
   fprintf(stream, "  SYMBOL\n");
   if(s->name != NULL) fprintf(stream, "    NAME \"%s\"\n", s->name);
-  
+
   switch (s->type) {
-  case(MS_SYMBOL_HATCH):
-    fprintf(stream, "    TYPE HATCH\n");
-    break;
-  case(MS_SYMBOL_PIXMAP):
-    fprintf(stream, "    TYPE PIXMAP\n");
-    if(s->imagepath != NULL) fprintf(stream, "    IMAGE \"%s\"\n", s->imagepath);
-    fprintf(stream, "    TRANSPARENT %d\n", s->transparentcolor);
-    break;
-  case(MS_SYMBOL_TRUETYPE):
-    fprintf(stream, "    TYPE TRUETYPE\n");
-    if(s->antialias == MS_TRUE) fprintf(stream, "    ANTIALIAS TRUE\n");
-    if (s->character != NULL) fprintf(stream, "    CHARACTER \"%s\"\n", s->character);
-    if (s->font != NULL) fprintf(stream, "    FONT \"%s\"\n", s->font);
-    break;
-  default:
-    if(s->type == MS_SYMBOL_ELLIPSE)
-      fprintf(stream, "    TYPE ELLIPSE\n");
-    else if(s->type == MS_SYMBOL_VECTOR)
-      fprintf(stream, "    TYPE VECTOR\n");
-    else
-      fprintf(stream, "    TYPE SIMPLE\n");
-    
-    if(s->filled == MS_TRUE) fprintf(stream, "    FILLED TRUE\n");
-    
-    /* POINTS */
-    if(s->numpoints != 0) {
-      fprintf(stream, "    POINTS\n");
-      for(i=0; i<s->numpoints; i++) {
-	fprintf(stream, "      %g %g\n", s->points[i].x, s->points[i].y);
+    case(MS_SYMBOL_HATCH):
+      fprintf(stream, "    TYPE HATCH\n");
+      break;
+    case(MS_SYMBOL_PIXMAP):
+      fprintf(stream, "    TYPE PIXMAP\n");
+      if(s->imagepath != NULL) fprintf(stream, "    IMAGE \"%s\"\n", s->imagepath);
+      fprintf(stream, "    TRANSPARENT %d\n", s->transparentcolor);
+      break;
+    case(MS_SYMBOL_TRUETYPE):
+      fprintf(stream, "    TYPE TRUETYPE\n");
+      if(s->antialias == MS_TRUE) fprintf(stream, "    ANTIALIAS TRUE\n");
+      if (s->character != NULL) fprintf(stream, "    CHARACTER \"%s\"\n", s->character);
+      if (s->font != NULL) fprintf(stream, "    FONT \"%s\"\n", s->font);
+      break;
+    default:
+      if(s->type == MS_SYMBOL_ELLIPSE)
+        fprintf(stream, "    TYPE ELLIPSE\n");
+      else if(s->type == MS_SYMBOL_VECTOR)
+        fprintf(stream, "    TYPE VECTOR\n");
+      else
+        fprintf(stream, "    TYPE SIMPLE\n");
+
+      if(s->filled == MS_TRUE) fprintf(stream, "    FILLED TRUE\n");
+
+      /* POINTS */
+      if(s->numpoints != 0) {
+        fprintf(stream, "    POINTS\n");
+        for(i=0; i<s->numpoints; i++) {
+          fprintf(stream, "      %g %g\n", s->points[i].x, s->points[i].y);
+        }
+        fprintf(stream, "    END\n");
       }
-      fprintf(stream, "    END\n");
-    }
-    break;
+      break;
   }
-      
+
   fprintf(stream, "  END\n\n");
 }
 
 
 /*
-** Little helper function to allow us to build symbol files on-the-fly 
+** Little helper function to allow us to build symbol files on-the-fly
 ** from just a file name.
 **
 ** Returns the symbol index or -1 if it could not be added.
 */
-int msAddImageSymbol(symbolSetObj *symbolset, char *filename) 
+int msAddImageSymbol(symbolSetObj *symbolset, char *filename)
 {
   char szPath[MS_MAXPATHLEN];
   symbolObj *symbol=NULL;
@@ -337,47 +354,42 @@ int msAddImageSymbol(symbolSetObj *symbolset, char *filename)
 
   /* Allocate/init memory for new symbol if needed */
   if (msGrowSymbolSet(symbolset) == NULL)
-      return -1;
+    return -1;
   symbol = symbolset->symbol[symbolset->numsymbols];
 
 #ifdef USE_CURL
-  if (strncasecmp(filename, "http", 4) == 0)
-  {
-      char *tmpfullfilename = NULL;
-      char *tmpfilename = NULL;
-      char *tmppath = NULL;
-      int status = 0;
-      char szPath[MS_MAXPATHLEN];
-     int bCheckLocalCache = MS_TRUE;
- 
-     tmppath = msTmpPath(NULL, NULL, NULL);
-     if (tmppath)
-     {
-          tmpfilename = msEncodeUrl(filename);
-          tmpfullfilename = msBuildPath(szPath, tmppath, tmpfilename);
-          if (tmpfullfilename)
-          {
-              /*use the url for now as a caching mechanism*/
-              if (msHTTPGetFile(filename, tmpfullfilename, &status, -1, bCheckLocalCache, 0) == MS_SUCCESS)
-              {
-                  symbol->imagepath = msStrdup(tmpfullfilename);
-                  symbol->full_pixmap_path = msStrdup(tmpfullfilename);
-              }
-          }
-          msFree(tmpfilename);
-          msFree(tmppath);
-     }
+  if (strncasecmp(filename, "http", 4) == 0) {
+    char *tmpfullfilename = NULL;
+    char *tmpfilename = NULL;
+    char *tmppath = NULL;
+    int status = 0;
+    char szPath[MS_MAXPATHLEN];
+    int bCheckLocalCache = MS_TRUE;
+
+    tmppath = msTmpPath(NULL, NULL, NULL);
+    if (tmppath) {
+      tmpfilename = msEncodeUrl(filename);
+      tmpfullfilename = msBuildPath(szPath, tmppath, tmpfilename);
+      if (tmpfullfilename) {
+        /*use the url for now as a caching mechanism*/
+        if (msHTTPGetFile(filename, tmpfullfilename, &status, -1, bCheckLocalCache, 0) == MS_SUCCESS) {
+          symbol->imagepath = msStrdup(tmpfullfilename);
+          symbol->full_pixmap_path = msStrdup(tmpfullfilename);
+        }
+      }
+      msFree(tmpfilename);
+      msFree(tmppath);
+    }
   }
 #endif
   /*if the http did not work, allow it to be treated as a file*/
-  if (!symbol->full_pixmap_path)
-  {
-      if(symbolset->map) {
-          symbol->full_pixmap_path = msStrdup(msBuildPath(szPath, symbolset->map->mappath, filename));  
-      } else {
-          symbol->full_pixmap_path = msStrdup(msBuildPath(szPath, NULL, filename));  
-      }
-      symbol->imagepath = msStrdup(filename);
+  if (!symbol->full_pixmap_path) {
+    if(symbolset->map) {
+      symbol->full_pixmap_path = msStrdup(msBuildPath(szPath, symbolset->map->mappath, filename));
+    } else {
+      symbol->full_pixmap_path = msStrdup(msBuildPath(szPath, NULL, filename));
+    }
+    symbol->imagepath = msStrdup(filename);
   }
   symbol->name = msStrdup(filename);
   symbol->type = MS_SYMBOL_PIXMAP;
@@ -390,12 +402,12 @@ int msFreeSymbolSet(symbolSetObj *symbolset)
 
   freeImageCache(symbolset->imagecache);
   for(i=0; i<symbolset->numsymbols; i++) {
-	  if (symbolset->symbol[i]!=NULL) {
-		  if ( msFreeSymbol((symbolset->symbol[i])) == MS_SUCCESS ) {
-			  msFree(symbolset->symbol[i]);
-			  symbolset->symbol[i]=NULL;
-		  }
-	  }
+    if (symbolset->symbol[i]!=NULL) {
+      if ( msFreeSymbol((symbolset->symbol[i])) == MS_SUCCESS ) {
+        msFree(symbolset->symbol[i]);
+        symbolset->symbol[i]=NULL;
+      }
+    }
   }
   msFree(symbolset->symbol);
 
@@ -421,7 +433,12 @@ void msInitSymbolSet(symbolSetObj *symbolset)
    * symbol 0 which is the default symbol with all default params.
    */
   if (msGrowSymbolSet(symbolset) == NULL)
-      return; /* alloc failed */
+    return; /* alloc failed */
+  symbolset->symbol[0]->type = MS_SYMBOL_ELLIPSE;
+  symbolset->symbol[0]->filled = MS_TRUE;
+  symbolset->symbol[0]->numpoints = 1;
+  symbolset->symbol[0]->points[0].x = 1;
+  symbolset->symbol[0]->points[0].y = 1;
 
   /* Just increment numsymbols to reserve symbol 0.
    * initSymbol() has already been called
@@ -433,7 +450,7 @@ void msInitSymbolSet(symbolSetObj *symbolset)
 
 /*
 ** Ensure there is at least one free entry in the symbol array of this
-** symbolSetObj. Grow the allocated symbol[] array if necessary and 
+** symbolSetObj. Grow the allocated symbol[] array if necessary and
 ** allocate a new symbol for symbol[numsymbols] if there is not already one
 ** and call initSymbol() on it.
 **
@@ -444,43 +461,43 @@ void msInitSymbolSet(symbolSetObj *symbolset)
 */
 symbolObj *msGrowSymbolSet( symbolSetObj *symbolset )
 {
-    /* Do we need to increase the size of symbol[] by MS_SYMBOL_ALLOCSIZE? */
-    if (symbolset->numsymbols == symbolset->maxsymbols) {
-        int i;
-        if (symbolset->maxsymbols == 0) {
-            /* Initial allocation of array */
-            symbolset->maxsymbols += MS_SYMBOL_ALLOCSIZE;
-            symbolset->numsymbols = 0;
-            symbolset->symbol = (symbolObj**)malloc(symbolset->maxsymbols*sizeof(symbolObj*));
-        } else {
-            /* realloc existing array */
-            symbolset->maxsymbols += MS_SYMBOL_ALLOCSIZE;
-            symbolset->symbol = (symbolObj**)realloc(symbolset->symbol,
-                                                     symbolset->maxsymbols*sizeof(symbolObj*));
-        }
-
-        if (symbolset->symbol == NULL) {
-            msSetError(MS_MEMERR, "Failed to allocate memory for symbol array.", "msGrowSymbolSet()");
-            return NULL;
-        }
+  /* Do we need to increase the size of symbol[] by MS_SYMBOL_ALLOCSIZE? */
+  if (symbolset->numsymbols == symbolset->maxsymbols) {
+    int i;
+    if (symbolset->maxsymbols == 0) {
+      /* Initial allocation of array */
+      symbolset->maxsymbols += MS_SYMBOL_ALLOCSIZE;
+      symbolset->numsymbols = 0;
+      symbolset->symbol = (symbolObj**)malloc(symbolset->maxsymbols*sizeof(symbolObj*));
+    } else {
+      /* realloc existing array */
+      symbolset->maxsymbols += MS_SYMBOL_ALLOCSIZE;
+      symbolset->symbol = (symbolObj**)realloc(symbolset->symbol,
+                          symbolset->maxsymbols*sizeof(symbolObj*));
+    }
 
-        for(i=symbolset->numsymbols; i<symbolset->maxsymbols; i++)
-            symbolset->symbol[i] = NULL;
+    if (symbolset->symbol == NULL) {
+      msSetError(MS_MEMERR, "Failed to allocate memory for symbol array.", "msGrowSymbolSet()");
+      return NULL;
     }
 
+    for(i=symbolset->numsymbols; i<symbolset->maxsymbols; i++)
+      symbolset->symbol[i] = NULL;
+  }
+
+  if (symbolset->symbol[symbolset->numsymbols]==NULL) {
+    symbolset->symbol[symbolset->numsymbols]=(symbolObj*)malloc(sizeof(symbolObj));
     if (symbolset->symbol[symbolset->numsymbols]==NULL) {
-        symbolset->symbol[symbolset->numsymbols]=(symbolObj*)malloc(sizeof(symbolObj));
-        if (symbolset->symbol[symbolset->numsymbols]==NULL) {
-          msSetError(MS_MEMERR, "Failed to allocate memory for a symbolObj", "msGrowSymbolSet()");
-          return NULL;
-        }
+      msSetError(MS_MEMERR, "Failed to allocate memory for a symbolObj", "msGrowSymbolSet()");
+      return NULL;
     }
+  }
 
-    /* Always call initSymbol() even if we didn't allocate a new symbolObj
-     * Since it's possible to dynamically remove/reuse symbols */
-    initSymbol(symbolset->symbol[symbolset->numsymbols]);
+  /* Always call initSymbol() even if we didn't allocate a new symbolObj
+   * Since it's possible to dynamically remove/reuse symbols */
+  initSymbol(symbolset->symbol[symbolset->numsymbols]);
 
-    return symbolset->symbol[symbolset->numsymbols];
+  return symbolset->symbol[symbolset->numsymbols];
 }
 
 
@@ -498,13 +515,13 @@ symbolObj *msGrowSymbolSet( symbolSetObj *symbolset )
 
 int msLoadSymbolSet(symbolSetObj *symbolset, mapObj *map)
 {
-    int retval = MS_FAILURE;
-    
-    msAcquireLock( TLOCK_PARSER );
-    retval = loadSymbolSet( symbolset, map );
-    msReleaseLock( TLOCK_PARSER );
+  int retval = MS_FAILURE;
 
-    return retval;
+  msAcquireLock( TLOCK_PARSER );
+  retval = loadSymbolSet( symbolset, map );
+  msReleaseLock( TLOCK_PARSER );
+
+  return retval;
 }
 
 int loadSymbolSet(symbolSetObj *symbolset, mapObj *map)
@@ -512,7 +529,7 @@ int loadSymbolSet(symbolSetObj *symbolset, mapObj *map)
   int status=1;
   char szPath[MS_MAXPATHLEN], *pszSymbolPath=NULL;
 
-  int foundSymbolSetToken=MS_FALSE; 
+  int foundSymbolSetToken=MS_FALSE;
   int token;
 
   if(!symbolset) {
@@ -534,6 +551,9 @@ int loadSymbolSet(symbolSetObj *symbolset, mapObj *map)
 
   pszSymbolPath = msGetPath(szPath);
 
+  msyystate = MS_TOKENIZE_FILE; /* restore lexer state to INITIAL, and do return comments */
+  msyylex(); /* sets things up, but doesn't process any tokens */
+
   msyylineno = 0; /* reset line counter */
   msyyrestart(msyyin); /* flush the scanner - there's a better way but this works for now */
 
@@ -541,34 +561,33 @@ int loadSymbolSet(symbolSetObj *symbolset, mapObj *map)
   ** Read the symbol file
   */
   for(;;) {
-    token = msyylex(); 
+    token = msyylex();
 
-    if(!foundSymbolSetToken && token != SYMBOLSET) { 
-      msSetError(MS_IDENTERR, "First token must be SYMBOLSET, this doesn't look like a symbol file.", "msLoadSymbolSet()"); 
-      return(-1); 
+    if(!foundSymbolSetToken && token != SYMBOLSET) {
+      msSetError(MS_IDENTERR, "First token must be SYMBOLSET, this doesn't look like a symbol file.", "msLoadSymbolSet()");
+      return(-1);
     }
 
     switch(token) {
-    case(END):
-    case(EOF):      
-      status = 0;
-      break;
-    case(SYMBOL):
-      /* Allocate/init memory for new symbol if needed */
-      if (msGrowSymbolSet(symbolset) == NULL) {
-	status = -1;
-      }
-      else if((loadSymbol((symbolset->symbol[symbolset->numsymbols]), pszSymbolPath) == -1)) 
-	  status = -1;
-      else
+      case(END):
+      case(EOF):
+        status = 0;
+        break;
+      case(SYMBOL):
+        /* Allocate/init memory for new symbol if needed */
+        if (msGrowSymbolSet(symbolset) == NULL) {
+          status = -1;
+        } else if((loadSymbol((symbolset->symbol[symbolset->numsymbols]), pszSymbolPath) == -1))
+          status = -1;
+        else
           symbolset->numsymbols++;
-      break;
-    case(SYMBOLSET):
-      foundSymbolSetToken = MS_TRUE;
-      break;
-    default:
-      msSetError(MS_IDENTERR, "Parsing error near (%s):(line %d)", "loadSymbolSet()", msyystring_buffer, msyylineno);
-      status = -1;
+        break;
+      case(SYMBOLSET):
+        foundSymbolSetToken = MS_TRUE;
+        break;
+      default:
+        msSetError(MS_IDENTERR, "Parsing error near (%s):(line %d)", "loadSymbolSet()", msyystring_buffer, msyylineno);
+        status = -1;
     } /* end switch */
 
     if(status != 1) break;
@@ -585,8 +604,8 @@ int loadSymbolSet(symbolSetObj *symbolset, mapObj *map)
 ** layer collision avoidance. A marker is made up of a number of styles so the calling code must either do the looping
 ** itself or call this function for the bottom style which should be the largest.
 */
-int msGetMarkerSize(symbolSetObj *symbolset, styleObj *style, int *width, int *height, double scalefactor)
-{  
+int msGetMarkerSize(symbolSetObj *symbolset, styleObj *style, double *width, double *height, double scalefactor)
+{
   rectObj rect;
   int size;
   symbolObj *symbol;
@@ -599,60 +618,58 @@ int msGetMarkerSize(symbolSetObj *symbolset, styleObj *style, int *width, int *h
     *height = 1;
     return(MS_SUCCESS);
   }
-  
+
   symbol = symbolset->symbol[style->symbol];
-  if(style->size == -1) {
-      size = MS_NINT( msSymbolGetDefaultSize(symbol) * scalefactor );
+  if (symbol->type == MS_SYMBOL_PIXMAP && !symbol->pixmap_buffer) {
+    if (MS_SUCCESS != msPreloadImageSymbol(MS_MAP_RENDERER(symbolset->map), symbol))
+      return MS_FAILURE;
+  }
+  if(symbol->type == MS_SYMBOL_SVG && !symbol->renderer_cache) {
+#ifdef USE_SVG_CAIRO
+    if(MS_SUCCESS != msPreloadSVGSymbol(symbol))
+      return MS_FAILURE;
+#else
+    msSetError(MS_SYMERR, "SVG symbol support is not enabled.", "msGetMarkerSize()");
+    return MS_FAILURE;
+#endif
   }
-  else
-      size = MS_NINT(style->size*scalefactor);
+  if(style->size == -1) {
+    size = ( msSymbolGetDefaultSize(symbol) * scalefactor );
+  } else
+    size = (style->size*scalefactor);
   size = MS_MAX(size, style->minsize);
   size = MS_MIN(size, style->maxsize);
 
-  switch(symbol->type) {  
-   
-#ifdef USE_GD_FT
-  case(MS_SYMBOL_TRUETYPE):
-	if(!symbol->full_font_path) {
-		char *font = msLookupHashTable(&(symbolset->fontset->fonts),symbol->font);
-		if(!font) {
-			msSetError(MS_MISCERR,"font (%s) not found in fontset","msGetMarkerSize()",symbol->font);
-			return(MS_FAILURE);
-		}
-		symbol->full_font_path =  msStrdup(font);
-	}
-    if(msGetTruetypeTextBBox(MS_MAP_RENDERER(symbolset->map),symbol->full_font_path,size,symbol->character,&rect,NULL) != MS_SUCCESS) 
-      return(MS_FAILURE);
+  switch(symbol->type) {
 
-    *width = (int) MS_MAX(*width, rect.maxx - rect.minx);
-    *height = (int) MS_MAX(*height, rect.maxy - rect.miny);
+    case(MS_SYMBOL_TRUETYPE):
+      if(msGetTruetypeTextBBox(MS_MAP_RENDERER(symbolset->map),symbol->font,symbolset->fontset,size,symbol->character,&rect,NULL,0) != MS_SUCCESS)
+        return(MS_FAILURE);
 
-    break;
-#endif
+      *width = MS_MAX(*width, rect.maxx - rect.minx);
+      *height = MS_MAX(*height, rect.maxy - rect.miny);
 
-  case(MS_SYMBOL_PIXMAP): 
-    if(!symbol->pixmap_buffer) {
-        msSetError(MS_MISCERR,"msGetMarkerSize() called on unloaded pixmap symbol, this is a bug in mapserver itself","msGetMArkerSize()");
-        return MS_FAILURE;
-    }
-    if(size == 1) {        
-      *width = MS_MAX(*width, symbol->pixmap_buffer->width);
-      *height = MS_MAX(*height, symbol->pixmap_buffer->height);
-    } else {
-      *width = MS_MAX(*width, MS_NINT((size/symbol->pixmap_buffer->height) * symbol->pixmap_buffer->width));
-      *height = MS_MAX(*height, size);
-    }
-    break;
-  default: /* vector and ellipses, scalable */
-    if(style->size > 0) {
-      *width = MS_MAX(*width, MS_NINT((size/symbol->sizey) * symbol->sizex));
-      *height = MS_MAX(*height, size);
-    } else { /* use symbol defaults */
-      *width = (int) MS_MAX(*width, symbol->sizex);
-      *height = (int) MS_MAX(*height, symbol->sizey);
-    }
-    break;
-  }  
+      break;
+
+    case(MS_SYMBOL_PIXMAP):
+      if(size == 1) {
+        *width = MS_MAX(*width, symbol->pixmap_buffer->width);
+        *height = MS_MAX(*height, symbol->pixmap_buffer->height);
+      } else {
+        *width = MS_MAX(*width, (((double)size/(double)symbol->pixmap_buffer->height) * symbol->pixmap_buffer->width));
+        *height = MS_MAX(*height, size);
+      }
+      break;
+    default: /* vector and ellipses, scalable */
+      if(style->size > 0) {
+        *width = MS_MAX(*width, ((size/symbol->sizey) * symbol->sizex));
+        *height = MS_MAX(*height, size);
+      } else { /* use symbol defaults */
+        *width = MS_MAX(*width, symbol->sizex);
+        *height = MS_MAX(*height, symbol->sizey);
+      }
+      break;
+  }
 
   return(MS_SUCCESS);
 }
@@ -663,25 +680,25 @@ int msGetMarkerSize(symbolSetObj *symbolset, styleObj *style, int *width, int *h
  */
 int msAddNewSymbol(mapObj *map, char *name)
 {
-    int i = 0;
- 
-    if (!map || !name)
-      return -1;
+  int i = 0;
+
+  if (!map || !name)
+    return -1;
 
-    i = msGetSymbolIndex(&map->symbolset, name, MS_TRUE);
-    if (i >= 0)
-      return i;
+  i = msGetSymbolIndex(&map->symbolset, name, MS_TRUE);
+  if (i >= 0)
+    return i;
 
-    /* Allocate memory for new symbol if needed */
-    if (msGrowSymbolSet(&(map->symbolset)) == NULL)
-        return -1;
+  /* Allocate memory for new symbol if needed */
+  if (msGrowSymbolSet(&(map->symbolset)) == NULL)
+    return -1;
 
-    i = map->symbolset.numsymbols;  
-    map->symbolset.symbol[i]->name = msStrdup(name);
+  i = map->symbolset.numsymbols;
+  map->symbolset.symbol[i]->name = msStrdup(name);
 
-    map->symbolset.numsymbols++;
+  map->symbolset.numsymbols++;
 
-    return i;
+  return i;
 }
 
 /* msAppendSymbol and msRemoveSymbol are part of the work to resolve
@@ -689,98 +706,112 @@ int msAddNewSymbol(mapObj *map, char *name)
  * http://mapserver.gis.umn.edu/bugs/show_bug.cgi?id=579 */
 
 
-int msAppendSymbol(symbolSetObj *symbolset, symbolObj *symbol) {
-    /* Allocate memory for new symbol if needed */
-    if (msGrowSymbolSet(symbolset) == NULL)
-        return -1;
-    symbolset->numsymbols++;
-    symbolset->symbol[symbolset->numsymbols-1]=symbol;
-    MS_REFCNT_INCR(symbol);
-    return symbolset->numsymbols-1;
+int msAppendSymbol(symbolSetObj *symbolset, symbolObj *symbol)
+{
+  /* Allocate memory for new symbol if needed */
+  if (msGrowSymbolSet(symbolset) == NULL)
+    return -1;
+
+  /* we need to free the symbolObj that was already allocated as we are
+   going to replace it with the provided symbolObj*. Not the most efficient
+   technique, but this function should be rarely called, and in any case only
+   by mapscript. Another option could be to use msCopySymbol(), in which case
+   the call to MS_REFCNT_INCR(symbol) should be removed.*/
+  if(symbolset->symbol[symbolset->numsymbols]) {
+    msFreeSymbol(symbolset->symbol[symbolset->numsymbols]);
+    msFree(symbolset->symbol[symbolset->numsymbols]);
+  }
+  symbolset->symbol[symbolset->numsymbols]=symbol;
+  MS_REFCNT_INCR(symbol);
+  return symbolset->numsymbols++;
 }
 
 
-symbolObj *msRemoveSymbol(symbolSetObj *symbolset, int nSymbolIndex) {
-    int i;
-    symbolObj *symbol;
-    if (symbolset->numsymbols == 1) {
-        msSetError(MS_CHILDERR, "Cannot remove a symbolset's sole symbol", "removeSymbol()");
-        return NULL;
-    }
-    else if (nSymbolIndex < 0 || nSymbolIndex >= symbolset->numsymbols) {
-        msSetError(MS_CHILDERR, "Cannot remove symbol, invalid nSymbolIndex %d", "removeSymbol()", nSymbolIndex);
-        return NULL;
-    }
-    else {
-        symbol=symbolset->symbol[nSymbolIndex];
-        for (i=nSymbolIndex+1; i<symbolset->numsymbols; i++) {
-            symbolset->symbol[i-1] = symbolset->symbol[i];
-        }
-		symbolset->symbol[i-1]=NULL;
-        symbolset->numsymbols--;
-        MS_REFCNT_DECR(symbol);
-        return symbol;
+symbolObj *msRemoveSymbol(symbolSetObj *symbolset, int nSymbolIndex)
+{
+  int i;
+  symbolObj *symbol;
+  if (symbolset->numsymbols == 1) {
+    msSetError(MS_CHILDERR, "Cannot remove a symbolset's sole symbol", "removeSymbol()");
+    return NULL;
+  } else if (nSymbolIndex < 0 || nSymbolIndex >= symbolset->numsymbols) {
+    msSetError(MS_CHILDERR, "Cannot remove symbol, invalid nSymbolIndex %d", "removeSymbol()", nSymbolIndex);
+    return NULL;
+  } else {
+    symbol=symbolset->symbol[nSymbolIndex];
+    for (i=nSymbolIndex+1; i<symbolset->numsymbols; i++) {
+      symbolset->symbol[i-1] = symbolset->symbol[i];
     }
+    symbolset->symbol[i-1]=NULL;
+    symbolset->numsymbols--;
+    MS_REFCNT_DECR(symbol);
+    return symbol;
+  }
 }
 
-int msSaveSymbolSetStream(symbolSetObj *symbolset, FILE *stream) {
-  int i; 
-  if (!symbolset || !stream) { 
-    msSetError(MS_SYMERR, "Cannot save symbolset.", "msSaveSymbolSetStream()"); 
-    return MS_FAILURE; 
-  } 
-  /* Don't ever write out the default symbol at index 0 */ 
-  for (i=1; i<symbolset->numsymbols; i++) { 
-    if(!symbolset->symbol[i]->inmapfile) writeSymbol((symbolset->symbol[i]), stream); 
-  } 
+int msSaveSymbolSetStream(symbolSetObj *symbolset, FILE *stream)
+{
+  int i;
+  if (!symbolset || !stream) {
+    msSetError(MS_SYMERR, "Cannot save symbolset.", "msSaveSymbolSetStream()");
+    return MS_FAILURE;
+  }
+  /* Don't ever write out the default symbol at index 0 */
+  for (i=1; i<symbolset->numsymbols; i++) {
+    if(!symbolset->symbol[i]->inmapfile) writeSymbol((symbolset->symbol[i]), stream);
+  }
   return MS_SUCCESS;
 }
 
-int msSaveSymbolSet(symbolSetObj *symbolset, const char *filename) {
-    FILE *stream;
-    int retval;
-    if (!filename || strlen(filename) == 0) {
-        msSetError(MS_SYMERR, "Invalid filename.", "msSaveSymbolSet()");
-        return MS_FAILURE;
-    }
-    stream = fopen(filename, "w");
-    if (stream)
-    {
-	fprintf(stream, "SYMBOLSET\n");
-        retval = msSaveSymbolSetStream(symbolset, stream);
-	fprintf(stream, "END\n");
-        fclose(stream);
-    }
-    else 
-    {
-        msSetError(MS_SYMERR, "Could not write to %s", "msSaveSymbolSet()",
-                   filename);
-        retval = MS_FAILURE;
-    }
-    return retval;
+int msSaveSymbolSet(symbolSetObj *symbolset, const char *filename)
+{
+  FILE *stream;
+  int retval;
+  if (!filename || strlen(filename) == 0) {
+    msSetError(MS_SYMERR, "Invalid filename.", "msSaveSymbolSet()");
+    return MS_FAILURE;
+  }
+  stream = fopen(filename, "w");
+  if (stream) {
+    fprintf(stream, "SYMBOLSET\n");
+    retval = msSaveSymbolSetStream(symbolset, stream);
+    fprintf(stream, "END\n");
+    fclose(stream);
+  } else {
+    msSetError(MS_SYMERR, "Could not write to %s", "msSaveSymbolSet()",
+               filename);
+    retval = MS_FAILURE;
+  }
+  return retval;
 }
 
-int msLoadImageSymbol(symbolObj *symbol, const char *filename) {
-    msFree(symbol->full_pixmap_path);
-    symbol->full_pixmap_path = msStrdup(filename);
-    return MS_SUCCESS;
+int msLoadImageSymbol(symbolObj *symbol, const char *filename)
+{
+  msFree(symbol->full_pixmap_path);
+  symbol->full_pixmap_path = msStrdup(filename);
+  return MS_SUCCESS;
 }
 
-int msPreloadImageSymbol(rendererVTableObj *renderer, symbolObj *symbol) {
-	if(symbol->pixmap_buffer && symbol->renderer == renderer)
-		return MS_SUCCESS;
-	if(symbol->pixmap_buffer) { //other renderer was used, start again
-		msFreeRasterBuffer(symbol->pixmap_buffer);
-	} else {
-		symbol->pixmap_buffer = (rasterBufferObj*)calloc(1,sizeof(rasterBufferObj));
-	}
-	if(MS_SUCCESS != renderer->loadImageFromFile(symbol->full_pixmap_path, symbol->pixmap_buffer))
-		return MS_FAILURE;
-	symbol->renderer = renderer;
-	symbol->sizex = symbol->pixmap_buffer->width;
-	symbol->sizey = symbol->pixmap_buffer->height;
-	return MS_SUCCESS;
-		
+int msPreloadImageSymbol(rendererVTableObj *renderer, symbolObj *symbol)
+{
+  if(symbol->pixmap_buffer && symbol->renderer == renderer)
+    return MS_SUCCESS;
+  if(symbol->pixmap_buffer) { /* other renderer was used, start again */
+    msFreeRasterBuffer(symbol->pixmap_buffer);
+  } else {
+    symbol->pixmap_buffer = (rasterBufferObj*)calloc(1,sizeof(rasterBufferObj));
+  }
+  if(MS_SUCCESS != renderer->loadImageFromFile(symbol->full_pixmap_path, symbol->pixmap_buffer)) {
+    /* Free pixmap_buffer already allocated */
+    free(symbol->pixmap_buffer);
+    symbol->pixmap_buffer = NULL;
+    return MS_FAILURE;
+  }
+  symbol->renderer = renderer;
+  symbol->sizex = symbol->pixmap_buffer->width;
+  symbol->sizey = symbol->pixmap_buffer->height;
+  return MS_SUCCESS;
+
 }
 
 /***********************************************************************
@@ -790,25 +821,28 @@ int msPreloadImageSymbol(rendererVTableObj *renderer, symbolObj *symbol) {
  * gdImageCreate(), gdImageCopy()                                      *
  **********************************************************************/
 
-int msCopySymbol(symbolObj *dst, symbolObj *src, mapObj *map) {
+int msCopySymbol(symbolObj *dst, symbolObj *src, mapObj *map)
+{
   int i;
-  
+
   initSymbol(dst);
-  
+
   MS_COPYSTRING(dst->name, src->name);
   MS_COPYSTELEM(type);
   MS_COPYSTELEM(inmapfile);
-  
+
   /* map is a special case */
   dst->map = map;
-  
+
   MS_COPYSTELEM(sizex);
   MS_COPYSTELEM(sizey);
-  
+  MS_COPYSTELEM(anchorpoint_x);
+  MS_COPYSTELEM(anchorpoint_y);
+
   for (i=0; i < src->numpoints; i++) {
     MS_COPYPOINT(&(dst->points[i]), &(src->points[i]));
   }
-  
+
   MS_COPYSTELEM(numpoints);
   MS_COPYSTELEM(filled);
 
@@ -821,7 +855,7 @@ int msCopySymbol(symbolObj *dst, symbolObj *src, mapObj *map) {
   MS_COPYSTRING(dst->full_pixmap_path,src->full_pixmap_path);
 
   return(MS_SUCCESS);
-} 
+}
 
 /***********************************************************************
  * msCopySymbolSet()                                                   *
@@ -832,16 +866,16 @@ int msCopySymbol(symbolObj *dst, symbolObj *src, mapObj *map) {
 int msCopySymbolSet(symbolSetObj *dst, symbolSetObj *src, mapObj *map)
 {
   int i, return_value;
-  
+
   MS_COPYSTRING(dst->filename, src->filename);
-  
+
   dst->map = map;
   dst->fontset = &(map->fontset);
-  
+
   /* Copy child symbols */
   for (i = 0; i < src->numsymbols; i++) {
     if (msGrowSymbolSet(dst) == NULL)
-        return MS_FAILURE;
+      return MS_FAILURE;
     return_value = msCopySymbol(dst->symbol[i], src->symbol[i], map);
     if (return_value != MS_SUCCESS) {
       msSetError(MS_MEMERR,"Failed to copy symbol.","msCopySymbolSet()");
@@ -851,7 +885,7 @@ int msCopySymbolSet(symbolSetObj *dst, symbolSetObj *src, mapObj *map)
   }
 
   /* MS_COPYSTELEM(imagecachesize); */
-  
+
   /* I have a feeling that the code below is not quite right - Sean */
   /*copyProperty(&(dst->imagecache), &(src->imagecache),
                sizeof(struct imageCacheObj));
@@ -863,7 +897,8 @@ int msCopySymbolSet(symbolSetObj *dst, symbolSetObj *src, mapObj *map)
   return(MS_SUCCESS);
 }
 
-static void get_bbox(pointObj *poiList, int numpoints, double *minx, double *miny, double *maxx, double *maxy) {
+static void get_bbox(pointObj *poiList, int numpoints, double *minx, double *miny, double *maxx, double *maxy)
+{
   int j;
 
   *minx = *maxx = poiList[0].x;
@@ -881,118 +916,63 @@ static void get_bbox(pointObj *poiList, int numpoints, double *minx, double *min
 
 /*
  ** msRotateSymbol - Clockwise rotation of a symbol definition. Contributed
- ** by MapMedia, with clean up by SDL. Currently only type VECTOR and PIXMAP 
+ ** by MapMedia, with clean up by SDL. Currently only type VECTOR and PIXMAP
  ** symbols are handled.
  */
 symbolObj *msRotateVectorSymbol(symbolObj *symbol, double angle)
 {
-    double angle_rad=0.0;
-    double cos_a, sin_a;
-    double minx=0.0, miny=0.0, maxx=0.0, maxy=0.0;
-    symbolObj *newSymbol = NULL;
-   double dp_x, dp_y, xcor, ycor;
-    double TOL=0.00000000001;
-    int i;
+  double angle_rad=0.0;
+  double cos_a, sin_a;
+  double minx=0.0, miny=0.0, maxx=0.0, maxy=0.0;
+  symbolObj *newSymbol = NULL;
+  double dp_x, dp_y, xcor, ycor;
+  double TOL=0.00000000001;
+  int i;
 
-    //assert(symbol->type == MS_SYMBOL_VECTOR);
+  /* assert(symbol->type == MS_SYMBOL_VECTOR); */
 
-    newSymbol = (symbolObj *) malloc(sizeof(symbolObj));
-    msCopySymbol(newSymbol, symbol, NULL); /* TODO: do we really want to do this for all symbol types? */
+  newSymbol = (symbolObj *) malloc(sizeof(symbolObj));
+  msCopySymbol(newSymbol, symbol, NULL); /* TODO: do we really want to do this for all symbol types? */
 
-    angle_rad = (MS_DEG_TO_RAD*angle);
+  angle_rad = (MS_DEG_TO_RAD*angle);
 
- 
-    sin_a = sin(angle_rad);
-    cos_a = cos(angle_rad);
 
-    dp_x = symbol->sizex * .5; /* get the shift vector at 0,0 */
-    dp_y = symbol->sizey * .5;
+  sin_a = sin(angle_rad);
+  cos_a = cos(angle_rad);
 
-    /* center at 0,0 and rotate; then move back */
-    for( i=0;i < symbol->numpoints;i++) {
-        /* don't rotate PENUP commands (TODO: should use a constant here) */
-        if ((symbol->points[i].x == -99.0) || (symbol->points[i].x == -99.0) ) {
-            newSymbol->points[i].x = -99.0;
-            newSymbol->points[i].y = -99.0;
-            continue;
-        }
+  dp_x = symbol->sizex * .5; /* get the shift vector at 0,0 */
+  dp_y = symbol->sizey * .5;
 
-        newSymbol->points[i].x = dp_x + ((symbol->points[i].x-dp_x)*cos_a - (symbol->points[i].y-dp_y)*sin_a);
-        newSymbol->points[i].y = dp_y + ((symbol->points[i].x-dp_x)*sin_a + (symbol->points[i].y-dp_y)*cos_a);
+  /* center at 0,0 and rotate; then move back */
+  for( i=0; i < symbol->numpoints; i++) {
+    /* don't rotate PENUP commands (TODO: should use a constant here) */
+    if ((symbol->points[i].x == -99.0) || (symbol->points[i].x == -99.0) ) {
+      newSymbol->points[i].x = -99.0;
+      newSymbol->points[i].y = -99.0;
+      continue;
     }
 
-    /* get the new bbox of the symbol, because we need it to get the new dimensions of the new symbol */
-    get_bbox(newSymbol->points, newSymbol->numpoints, &minx, &miny, &maxx, &maxy);
-    if ( (fabs(minx)>TOL) || (fabs(miny)>TOL) ) {
-        xcor = minx*-1.0; /* symbols always start at 0,0 so get the shift vector */
-        ycor = miny*-1.0;
-        for( i=0;i < newSymbol->numpoints;i++) {
-            if ((newSymbol->points[i].x == -99.0) || (newSymbol->points[i].x == -99.0))
-                continue;
-            newSymbol->points[i].x = newSymbol->points[i].x + xcor;
-            newSymbol->points[i].y = newSymbol->points[i].y + ycor;
-        }
+    newSymbol->points[i].x = dp_x + ((symbol->points[i].x-dp_x)*cos_a - (symbol->points[i].y-dp_y)*sin_a);
+    newSymbol->points[i].y = dp_y + ((symbol->points[i].x-dp_x)*sin_a + (symbol->points[i].y-dp_y)*cos_a);
+  }
 
-        /* update the bbox to get the final dimension values for the symbol */
-        get_bbox(newSymbol->points, newSymbol->numpoints, &minx, &miny, &maxx, &maxy);
+  /* get the new bbox of the symbol, because we need it to get the new dimensions of the new symbol */
+  get_bbox(newSymbol->points, newSymbol->numpoints, &minx, &miny, &maxx, &maxy);
+  if ( (fabs(minx)>TOL) || (fabs(miny)>TOL) ) {
+    xcor = minx*-1.0; /* symbols always start at 0,0 so get the shift vector */
+    ycor = miny*-1.0;
+    for( i=0; i < newSymbol->numpoints; i++) {
+      if ((newSymbol->points[i].x == -99.0) || (newSymbol->points[i].x == -99.0))
+        continue;
+      newSymbol->points[i].x = newSymbol->points[i].x + xcor;
+      newSymbol->points[i].y = newSymbol->points[i].y + ycor;
     }
 
-    newSymbol->sizex = maxx;
-    newSymbol->sizey = maxy;
-    return newSymbol;
-}
-
-gdImagePtr msRotateGDImage(gdImagePtr img, double angle) {
-    
-    double angle_rad = (MS_DEG_TO_RAD*angle);
-
-    double cos_a, sin_a;
-
-    double x1 = 0.0, y1 = 0.0; /* destination rectangle */
-    double x2 = 0.0, y2 = 0.0;
-    double x3 = 0.0, y3 = 0.0;
-    double x4 = 0.0, y4 = 0.0;
-
-    long minx, miny, maxx, maxy;
-
-    int width=0, height=0;
-    /* int color; */
-
-    gdImagePtr newImage;
-
-    sin_a = sin(angle_rad);
-    cos_a = cos(angle_rad);
-
-    /* compute distination rectangle (x1,y1 is known) */
-    x1 = 0 ; y1 = 0 ;
-    x2 = img->sy * sin_a;
-    y2 = -img->sy * cos_a;
-    x3 = (img->sx * cos_a) + (img->sy * sin_a);
-    y3 = (img->sx * sin_a) - (img->sy * cos_a);
-    x4 = (img->sx * cos_a);
-    y4 = (img->sx * sin_a);
-
-    minx = (long) MS_MIN(x1,MS_MIN(x2,MS_MIN(x3,x4)));
-    miny = (long) MS_MIN(y1,MS_MIN(y2,MS_MIN(y3,y4)));
-    maxx = (long) MS_MAX(x1,MS_MAX(x2,MS_MAX(x3,x4)));
-    maxy = (long) MS_MAX(y1,MS_MAX(y2,MS_MAX(y3,y4)));
-
-    width = (int)ceil(maxx-minx);
-    height = (int)ceil(maxy-miny);
-
-    /* create the new image based on the computed width/height */
-    if (gdImageTrueColor(img)) {
-        newImage = gdImageCreateTrueColor(width, height);
-        gdImageAlphaBlending(newImage, 0);
-        gdImageFilledRectangle(newImage, 0, 0, width, height, gdImageColorAllocateAlpha(newImage, 0, 0, 0, gdAlphaTransparent)); 
-    } else {
-        int tc = gdImageGetTransparent(img);
-        newImage = gdImageCreate(width, height);	
-        if(tc != -1)
-            gdImageColorTransparent(newImage, gdImageColorAllocate(newImage, gdImageRed(img, tc), gdImageGreen(img, tc), gdImageBlue(img, tc)));
-    }
+    /* update the bbox to get the final dimension values for the symbol */
+    get_bbox(newSymbol->points, newSymbol->numpoints, &minx, &miny, &maxx, &maxy);
+  }
 
-    gdImageCopyRotated (newImage, img, width*0.5, height*0.5, 0, 0, gdImageSX(img), gdImageSY(img), angle);
-    return newImage;
+  newSymbol->sizex = maxx;
+  newSymbol->sizey = maxy;
+  return newSymbol;
 }
-
diff --git a/mapsymbol.h b/mapsymbol.h
index 1b722ea..45ed296 100644
--- a/mapsymbol.h
+++ b/mapsymbol.h
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -30,7 +30,10 @@
 #ifndef MAPSYMBOL_H
 #define MAPSYMBOL_H
 
+#ifdef USE_GD
 #include <gd.h>
+#endif
+
 #include <assert.h>
 
 enum MS_SYMBOL_TYPE {MS_SYMBOL_SIMPLE=1000, MS_SYMBOL_VECTOR, MS_SYMBOL_ELLIPSE, MS_SYMBOL_PIXMAP, MS_SYMBOL_TRUETYPE, MS_SYMBOL_HATCH, MS_SYMBOL_SVG};
@@ -43,7 +46,9 @@ enum MS_SYMBOL_TYPE {MS_SYMBOL_SIMPLE=1000, MS_SYMBOL_VECTOR, MS_SYMBOL_ELLIPSE,
 
 /* COLOR OBJECT */
 typedef struct {
+#ifdef USE_GD
   int pen;
+#endif
   int red;
   int green;
   int blue;
@@ -54,38 +59,40 @@ typedef struct {
 enum MS_RASTER_BUFFER_TYPE { MS_BUFFER_NONE=2000, MS_BUFFER_BYTE_RGBA, MS_BUFFER_BYTE_PALETTE, MS_BUFFER_GD };
 
 typedef struct {
-	unsigned char *pixels;
-	unsigned int pixel_step, row_step;
-	unsigned char *a,*r,*g,*b;
+  unsigned char *pixels;
+  unsigned int pixel_step, row_step;
+  unsigned char *a,*r,*g,*b;
 } rgbaArrayObj;
 
 typedef struct {
-    unsigned char b,g,r,a;
+  unsigned char b,g,r,a;
 } rgbaPixel;
 
 typedef struct {
-    unsigned char r,g,b;
+  unsigned char r,g,b;
 } rgbPixel;
 
 
 typedef struct {
-	unsigned char *pixels; /*stores the actual pixel indexes*/
-	rgbaPixel *palette; /*rgba palette entries*/
-	unsigned int num_entries; /*number of palette entries*/
-   unsigned int scaling_maxval;
+  unsigned char *pixels; /*stores the actual pixel indexes*/
+  rgbaPixel *palette; /*rgba palette entries*/
+  unsigned int num_entries; /*number of palette entries*/
+  unsigned int scaling_maxval;
 } paletteArrayObj;
 
 typedef struct {
-	int type;
-	unsigned int width,height;
-	union {
-		rgbaArrayObj rgba;
-		paletteArrayObj palette;
-		gdImagePtr gd_img;
-	} data;
+  int type;
+  unsigned int width,height;
+  union {
+    rgbaArrayObj rgba;
+    paletteArrayObj palette;
+#ifdef USE_GD
+    gdImagePtr gd_img;
+#endif
+  } data;
 } rasterBufferObj;
 
-/* NOTE: RB_SET_PIXEL() will premultiply by alpha, inputs should not be 
+/* NOTE: RB_SET_PIXEL() will premultiply by alpha, inputs should not be
          premultiplied */
 
 #define RB_SET_PIXEL(rb,x,y,red,green,blue,alpha) \
@@ -117,7 +124,7 @@ typedef struct {
         } \
     }
 
-/* NOTE: RB_MIX_PIXEL() will premultiply by alpha, inputs should not be 
+/* NOTE: RB_MIX_PIXEL() will premultiply by alpha, inputs should not be
          premultiplied */
 
 #define RB_MIX_PIXEL(rb,x,y,red,green,blue,alpha) \
@@ -156,7 +163,7 @@ typedef struct {
   /*
   ** Pointer to his map
   */
-  struct map_obj *map;
+  struct mapObj *map;
 #endif /* SWIG */
   /*
   ** MS_SYMBOL_VECTOR and MS_SYMBOL_ELLIPSE options
@@ -177,7 +184,9 @@ typedef struct {
   %mutable;
 #endif /* SWIG */
   int filled;
-  
+
+  double anchorpoint_x, anchorpoint_y;
+
   /*
   ** MS_SYMBOL_PIXMAP options
   */
diff --git a/maptclutf.c b/maptclutf.c
index 09c2498..2185eae 100644
--- a/maptclutf.c
+++ b/maptclutf.c
@@ -4,11 +4,11 @@
  * Project:  MapServer
  * Purpose:  Implementation of msUTF8ToUniChar()
  * Author:   Daniel Morissette, Thomas Bonfort
- * 
+ *
  * Note:
  * The source code of Tcl_UtfToUniChar() was borrowed from tclUtf.c
- * from the Tcl/Tk project. 
- * 
+ * from the Tcl/Tk project.
+ *
  * Website: http://www.tcl.tk/software/tcltk/
  * Source download: http://prdownloads.sourceforge.net/tcl/tcl8.4.15-src.tar.gz
  *
@@ -25,7 +25,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -39,9 +39,9 @@
 
 /*
  * tclUtf.c --
- *                                                               
+ *
  * Routines for manipulating UTF-8 strings.
- * 
+ *
  * Copyright (c) 1997-1998 Sun Microsystems, Inc.
  *
  * This software is copyrighted by the Regents of the University of
@@ -49,7 +49,7 @@
  * Corporation and other parties.  The following terms apply to all files
  * associated with the software unless explicitly disclaimed in
  * individual files.
- * 
+ *
  * The authors hereby grant permission to use, copy, modify, distribute,
  * and license this software and its documentation for any purpose, provided
  * that existing copyright notices are retained in all copies and that this
@@ -59,7 +59,7 @@
  * and need not follow the licensing terms described here, provided that
  * the new terms are clearly indicated on the first page of each file where
  * they apply.
- *  
+ *
  * IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY
  * FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
  * ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY
@@ -72,7 +72,7 @@
  * IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE
  * NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
  * MODIFICATIONS.
- * 
+ *
  * GOVERNMENT USE: If you are acquiring this software on behalf of the
  * U.S. government, the Government shall have only "Restricted Rights"
  * in the software and related documentation as defined in the Federal
@@ -89,14 +89,14 @@
 
 #include "mapserver.h"
 
-MS_CVSID("$Id$")
+
 
 
 /* The source code of Tcl_UtfToUniChar() was borrowed from tclUtf.c
  * from the Tcl/Tk project:
- * Website: 
+ * Website:
  *   http://www.tcl.tk/software/tcltk/
- * Source download: 
+ * Source download:
  *   http://prdownloads.sourceforge.net/tcl/tcl8.4.15-src.tar.gz
  * Original License info follows below.
  */
@@ -147,7 +147,7 @@ MODIFICATIONS.
 
 GOVERNMENT USE: If you are acquiring this software on behalf of the
 U.S. government, the Government shall have only "Restricted Rights"
-in the software and related documentation as defined in the Federal 
+in the software and related documentation as defined in the Federal
 Acquisition Regulations (FARs) in Clause 52.227.19 (c) (2).  If you
 are acquiring the software on behalf of the Department of Defense, the
 software shall be classified as "Commercial Computer Software" and the
@@ -155,7 +155,7 @@ Government shall have only "Restricted Rights" as defined in Clause
 252.227-7013 (c) (1) of DFARs.  Notwithstanding the foregoing, the
 authors grant the U.S. Government and others acting in its behalf
 permission to use and distribute the software in accordance with the
-terms specified in this license. 
+terms specified in this license.
 
 ***********************************************************/
 
@@ -170,28 +170,28 @@ terms specified in this license.
  */
 
 static const unsigned char totalBytes[256] = {
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
-    2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
-    3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
+  1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
+  1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
+  1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
+  1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
+  1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
+  1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
+  2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
+  3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
 #if TCL_UTF_MAX > 3
-    4,4,4,4,4,4,4,4,
+  4,4,4,4,4,4,4,4,
 #else
-    1,1,1,1,1,1,1,1,
+  1,1,1,1,1,1,1,1,
 #endif
 #if TCL_UTF_MAX > 4
-    5,5,5,5,
+  5,5,5,5,
 #else
-    1,1,1,1,
+  1,1,1,1,
 #endif
 #if TCL_UTF_MAX > 5
-    6,6,6,6
+  6,6,6,6
 #else
-    1,1,1,1
+  1,1,1,1
 #endif
 };
 
@@ -220,98 +220,98 @@ static const unsigned char totalBytes[256] = {
  *
  *---------------------------------------------------------------------------
  */
- 
+
 static int
 ms_Tcl_UtfToUniChar(str, chPtr)
-    register const char *str;    /* The UTF-8 string. */
-    register Tcl_UniChar *chPtr; /* Filled with the Tcl_UniChar represented
+register const char *str;    /* The UTF-8 string. */
+register Tcl_UniChar *chPtr; /* Filled with the Tcl_UniChar represented
                                   * by the UTF-8 string. */
 {
-    register int byte;
-    int entitylgth;
+  register int byte;
+  int entitylgth;
+
+  /*check if the string is an html entity (eg { or &#x12a;)*/
+  if((entitylgth=msGetUnicodeEntity(str, chPtr))>0)
+    return entitylgth;
 
-    /*check if the string is an html entity (eg { or &#x12a;)*/
-    if((entitylgth=msGetUnicodeEntity(str, chPtr))>0)
-        return entitylgth;
-    
+  /*
+   * Unroll 1 to 3 byte UTF-8 sequences, use loop to handle longer ones.
+   */
+
+  byte = *((unsigned char *) str);
+  if (byte < 0xC0) {
     /*
-     * Unroll 1 to 3 byte UTF-8 sequences, use loop to handle longer ones.
+     * Handles properly formed UTF-8 characters between 0x01 and 0x7F.
+     * Also treats \0 and naked trail bytes 0x80 to 0xBF as valid
+     * characters representing themselves.
      */
 
-    byte = *((unsigned char *) str);
-    if (byte < 0xC0) {
-        /*
-         * Handles properly formed UTF-8 characters between 0x01 and 0x7F.
-         * Also treats \0 and naked trail bytes 0x80 to 0xBF as valid
-         * characters representing themselves.
-         */
-
-        *chPtr = (Tcl_UniChar) byte;
-        return 1;
-    } else if (byte < 0xE0) {
-        if ((str[1] & 0xC0) == 0x80) {
-            /*
-             * Two-byte-character lead-byte followed by a trail-byte.
-             */
-
-            *chPtr = (Tcl_UniChar) (((byte & 0x1F) << 6) | (str[1] & 0x3F));
-            return 2;
-        }
-        /*
-         * A two-byte-character lead-byte not followed by trail-byte
-         * represents itself.
-         */
-
-        *chPtr = (Tcl_UniChar) byte;
-        return 1;
-    } else if (byte < 0xF0) {
-        if (((str[1] & 0xC0) == 0x80) && ((str[2] & 0xC0) == 0x80)) {
-            /*
-             * Three-byte-character lead byte followed by two trail bytes.
-             */
-
-            *chPtr = (Tcl_UniChar) (((byte & 0x0F) << 12) 
-                                    | ((str[1] & 0x3F) << 6) | (str[2] & 0x3F));
-            return 3;
-        }
-        /*
-         * A three-byte-character lead-byte not followed by two trail-bytes
-         * represents itself.
-         */
+    *chPtr = (Tcl_UniChar) byte;
+    return 1;
+  } else if (byte < 0xE0) {
+    if ((str[1] & 0xC0) == 0x80) {
+      /*
+       * Two-byte-character lead-byte followed by a trail-byte.
+       */
 
-        *chPtr = (Tcl_UniChar) byte;
-        return 1;
+      *chPtr = (Tcl_UniChar) (((byte & 0x1F) << 6) | (str[1] & 0x3F));
+      return 2;
     }
+    /*
+     * A two-byte-character lead-byte not followed by trail-byte
+     * represents itself.
+     */
+
+    *chPtr = (Tcl_UniChar) byte;
+    return 1;
+  } else if (byte < 0xF0) {
+    if (((str[1] & 0xC0) == 0x80) && ((str[2] & 0xC0) == 0x80)) {
+      /*
+       * Three-byte-character lead byte followed by two trail bytes.
+       */
+
+      *chPtr = (Tcl_UniChar) (((byte & 0x0F) << 12)
+                              | ((str[1] & 0x3F) << 6) | (str[2] & 0x3F));
+      return 3;
+    }
+    /*
+     * A three-byte-character lead-byte not followed by two trail-bytes
+     * represents itself.
+     */
+
+    *chPtr = (Tcl_UniChar) byte;
+    return 1;
+  }
 #if TCL_UTF_MAX > 3
-    else {
-        int ch, total, trail;
-
-        total = totalBytes[byte];
-        trail = total - 1;
-        if (trail > 0) {
-            ch = byte & (0x3F >> trail);
-            do {
-                str++;
-                if ((*str & 0xC0) != 0x80) {
-                    *chPtr = byte;
-                    return 1;
-                }
-                ch <<= 6;
-                ch |= (*str & 0x3F);
-                trail--;
-            } while (trail > 0);
-            *chPtr = ch;
-            return total;
+  else {
+    int ch, total, trail;
+
+    total = totalBytes[byte];
+    trail = total - 1;
+    if (trail > 0) {
+      ch = byte & (0x3F >> trail);
+      do {
+        str++;
+        if ((*str & 0xC0) != 0x80) {
+          *chPtr = byte;
+          return 1;
         }
+        ch <<= 6;
+        ch |= (*str & 0x3F);
+        trail--;
+      } while (trail > 0);
+      *chPtr = ch;
+      return total;
     }
+  }
 #endif
 
-    *chPtr = (Tcl_UniChar) byte;
-    return 1;
+  *chPtr = (Tcl_UniChar) byte;
+  return 1;
 }
 
 
-/* msUTF8ToUniChar() 
+/* msUTF8ToUniChar()
  *
  *  Extract the Unicode Char represented by the UTF-8 string.  Bad
  *  UTF-8 sequences are converted to valid Unicode Chars and processing
@@ -323,7 +323,7 @@ ms_Tcl_UtfToUniChar(str, chPtr)
  *  be '\0' terminated, this cannot happen.
  *
  * Results:
- *  *chPtr is filled with the Unicode Char value, and the return value 
+ *  *chPtr is filled with the Unicode Char value, and the return value
  *  is the number of bytes from the UTF-8 string that were consumed.
 **
 **/
@@ -331,5 +331,5 @@ int msUTF8ToUniChar(const char *str, /* The UTF-8 string. */
                     int *chPtr)      /* Filled with the Unicode Char represented
                                       * by the UTF-8 string. */
 {
-    return ms_Tcl_UtfToUniChar(str, chPtr);
+  return ms_Tcl_UtfToUniChar(str, chPtr);
 }
diff --git a/maptemplate.c b/maptemplate.c
index 9ded11c..6b1e12b 100644
--- a/maptemplate.c
+++ b/maptemplate.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -30,6 +30,7 @@
 #include "maptemplate.h"
 #include "maphash.h"
 #include "mapserver.h"
+#include "maptile.h"
 
 #include <sys/types.h>
 #include <sys/stat.h>
@@ -37,41 +38,41 @@
 
 #include <ctype.h>
 
-MS_CVSID("$Id$")
+
 
 static char *olUrl = "http://www.mapserver.org/lib/OpenLayers-ms60.js";
 static char *olTemplate = \
-"<html>\n"
-"<head>\n"
-"  <title>MapServer Simple Viewer</title>\n"
-"    <script type=\"text/javascript\" src=\"[openlayers_js_url]\"></script>\n"
-"    </head>\n"
-"    <body>\n"
-"      <div style=\"width:[mapwidth]; height:[mapheight]\" id=\"map\"></div>\n"
-"      <script defer=\"defer\" type=\"text/javascript\">\n"
-"        var map = new OpenLayers.Map('map',\n"
-"                                     {maxExtent: new OpenLayers.Bounds([minx],[miny],[maxx],[maxy]),\n"
-"                                      maxResolution: [cellsize]});\n"
-"        [openlayers_layer];\n"
-"        map.addLayer(mslayer);\n"
-"        map.zoomToMaxExtent();\n"
-"      </script>\n"
-"</body>\n"
-"</html>";
+                          "<html>\n"
+                          "<head>\n"
+                          "  <title>MapServer Simple Viewer</title>\n"
+                          "    <script type=\"text/javascript\" src=\"[openlayers_js_url]\"></script>\n"
+                          "    </head>\n"
+                          "    <body>\n"
+                          "      <div style=\"width:[mapwidth]; height:[mapheight]\" id=\"map\"></div>\n"
+                          "      <script defer=\"defer\" type=\"text/javascript\">\n"
+                          "        var map = new OpenLayers.Map('map',\n"
+                          "                                     {maxExtent: new OpenLayers.Bounds([minx],[miny],[maxx],[maxy]),\n"
+                          "                                      maxResolution: [cellsize]});\n"
+                          "        [openlayers_layer];\n"
+                          "        map.addLayer(mslayer);\n"
+                          "        map.zoomToMaxExtent();\n"
+                          "      </script>\n"
+                          "</body>\n"
+                          "</html>";
 
 static char *olLayerMapServerTag = \
-"var mslayer = new OpenLayers.Layer.MapServer( \"MapServer Layer\",\n"
-"                                              \"[mapserv_onlineresource]\",\n"
-"                                              {layers: '[layers]'},\n"
-"                                              {singleTile: \"true\", ratio:1} )";
+                                   "var mslayer = new OpenLayers.Layer.MapServer( \"MapServer Layer\",\n"
+                                   "                                              \"[mapserv_onlineresource]\",\n"
+                                   "                                              {layers: '[layers]'},\n"
+                                   "                                              {singleTile: \"true\", ratio:1} )";
 
 static char *olLayerWMSTag = \
-"var mslayer = new OpenLayers.Layer.WMS('MapServer Simple Viewer\',\n"
-"                                   '[mapserv_onlineresource]',\n"
-"                                   {layers: '[LAYERS]',\n"
-"                                   bbox: '[minx],[miny],[maxx],[maxy]',\n"
-"                                   width: [mapwidth], height: [mapheight], version: '[VERSION]'},"
-"                                   {singleTile: \"true\", ratio:1, projection: '[openlayers_projection]'});\n";
+                             "var mslayer = new OpenLayers.Layer.WMS('MapServer Simple Viewer\',\n"
+                             "                                   '[mapserv_onlineresource]',\n"
+                             "                                   {layers: '[LAYERS]',\n"
+                             "                                   bbox: '[minx],[miny],[maxx],[maxy]',\n"
+                             "                                   width: [mapwidth], height: [mapheight], version: '[VERSION]', format:'[openlayers_format]'},"
+                             "                                   {singleTile: \"true\", ratio:1, projection: '[openlayers_projection]'});\n";
 
 static char *processLine(mapservObj *mapserv, char *instr, FILE *stream, int mode);
 
@@ -91,17 +92,15 @@ static int isValidTemplate(FILE *stream, const char *filename)
 
 /*
  * Redirect to (only use in CGI)
- * 
+ *
 */
 int msRedirect(char *url)
 {
-  msIO_printf("Status: 302 Found\n");
-  msIO_printf("Uri: %s\n", url);
-  msIO_printf("Location: %s\n", url);
-  msIO_printf("Content-type: text/html%c%c",10,10);
-
-  /* the following may be an issue for fastcgi/msIO_.  */
-  fflush(stdout);
+  msIO_setHeader("Status","302 Found");
+  msIO_setHeader("Uri",url);
+  msIO_setHeader("Location",url);
+  msIO_setHeader("Content-Type","text/html");
+  msIO_sendHeaders();
   return MS_SUCCESS;
 }
 
@@ -112,62 +111,66 @@ int setExtent(mapservObj *mapserv)
 {
   double cellx,celly,cellsize;
 
-  switch(mapserv->CoordSource) 
-  {
-   case FROMUSERBOX: /* user passed in a map extent */
-     break;
-   case FROMIMGBOX: /* fully interactive web, most likely with java front end */
-     cellx = MS_CELLSIZE(mapserv->ImgExt.minx, mapserv->ImgExt.maxx, mapserv->ImgCols);
-     celly = MS_CELLSIZE(mapserv->ImgExt.miny, mapserv->ImgExt.maxy, mapserv->ImgRows);
-     mapserv->map->extent.minx = MS_IMAGE2MAP_X(mapserv->ImgBox.minx, mapserv->ImgExt.minx, cellx);
-     mapserv->map->extent.maxx = MS_IMAGE2MAP_X(mapserv->ImgBox.maxx, mapserv->ImgExt.minx, cellx);
-     mapserv->map->extent.maxy = MS_IMAGE2MAP_Y(mapserv->ImgBox.miny, mapserv->ImgExt.maxy, celly); /* y's are flip flopped because img/map coordinate systems are */
-     mapserv->map->extent.miny = MS_IMAGE2MAP_Y(mapserv->ImgBox.maxy, mapserv->ImgExt.maxy, celly);
-     break;
-   case FROMIMGPNT:
-     cellx = MS_CELLSIZE(mapserv->ImgExt.minx, mapserv->ImgExt.maxx, mapserv->ImgCols);
-     celly = MS_CELLSIZE(mapserv->ImgExt.miny, mapserv->ImgExt.maxy, mapserv->ImgRows);
-     mapserv->mappnt.x = MS_IMAGE2MAP_X(mapserv->ImgPnt.x, mapserv->ImgExt.minx, cellx);
-     mapserv->mappnt.y = MS_IMAGE2MAP_Y(mapserv->ImgPnt.y, mapserv->ImgExt.maxy, celly);
-
-     mapserv->map->extent.minx = mapserv->mappnt.x - .5*((mapserv->ImgExt.maxx - mapserv->ImgExt.minx)/mapserv->fZoom); /* create an extent around that point */
-     mapserv->map->extent.miny = mapserv->mappnt.y - .5*((mapserv->ImgExt.maxy - mapserv->ImgExt.miny)/mapserv->fZoom);
-     mapserv->map->extent.maxx = mapserv->mappnt.x + .5*((mapserv->ImgExt.maxx - mapserv->ImgExt.minx)/mapserv->fZoom);
-     mapserv->map->extent.maxy = mapserv->mappnt.y + .5*((mapserv->ImgExt.maxy - mapserv->ImgExt.miny)/mapserv->fZoom);
-     break;
-   case FROMREFPNT:
-     cellx = MS_CELLSIZE(mapserv->map->reference.extent.minx, mapserv->map->reference.extent.maxx, mapserv->map->reference.width);
-     celly = MS_CELLSIZE(mapserv->map->reference.extent.miny, mapserv->map->reference.extent.maxy, mapserv->map->reference.height);
-     mapserv->mappnt.x = MS_IMAGE2MAP_X(mapserv->RefPnt.x, mapserv->map->reference.extent.minx, cellx);
-     mapserv->mappnt.y = MS_IMAGE2MAP_Y(mapserv->RefPnt.y, mapserv->map->reference.extent.maxy, celly);  
-
-     mapserv->map->extent.minx = mapserv->mappnt.x - .5*(mapserv->ImgExt.maxx - mapserv->ImgExt.minx); /* create an extent around that point */
-     mapserv->map->extent.miny = mapserv->mappnt.y - .5*(mapserv->ImgExt.maxy - mapserv->ImgExt.miny);
-     mapserv->map->extent.maxx = mapserv->mappnt.x + .5*(mapserv->ImgExt.maxx - mapserv->ImgExt.minx);
-     mapserv->map->extent.maxy = mapserv->mappnt.y + .5*(mapserv->ImgExt.maxy - mapserv->ImgExt.miny);
-     break;
-   case FROMBUF:
-     mapserv->map->extent.minx = mapserv->mappnt.x - mapserv->Buffer; /* create an extent around that point, using the buffer */
-     mapserv->map->extent.miny = mapserv->mappnt.y - mapserv->Buffer;
-     mapserv->map->extent.maxx = mapserv->mappnt.x + mapserv->Buffer;
-     mapserv->map->extent.maxy = mapserv->mappnt.y + mapserv->Buffer;
-     break;
-   case FROMSCALE: 
-     cellsize = (mapserv->ScaleDenom/mapserv->map->resolution)/msInchesPerUnit(mapserv->map->units,0); /* user supplied a point and a scale denominator */
-     mapserv->map->extent.minx = mapserv->mappnt.x - cellsize*(mapserv->map->width-1)/2.0;
-     mapserv->map->extent.miny = mapserv->mappnt.y - cellsize*(mapserv->map->height-1)/2.0;
-     mapserv->map->extent.maxx = mapserv->mappnt.x + cellsize*(mapserv->map->width-1)/2.0;
-     mapserv->map->extent.maxy = mapserv->mappnt.y + cellsize*(mapserv->map->height-1)/2.0;
-     break;
-   default: /* use the default in the mapfile if it exists */
-     if((mapserv->map->extent.minx == mapserv->map->extent.maxx) && (mapserv->map->extent.miny == mapserv->map->extent.maxy)) {
-       msSetError(MS_WEBERR, "No way to generate map extent.", "mapserv()");
-       return MS_FAILURE;
-     }
+  if(mapserv->Mode == TILE) {
+    if(MS_SUCCESS != msTileSetExtent(mapserv)) {
+      return MS_FAILURE;
+    }
+  }
+  switch(mapserv->CoordSource) {
+    case FROMUSERBOX: /* user passed in a map extent */
+      break;
+    case FROMIMGBOX: /* fully interactive web, most likely with java front end */
+      cellx = MS_CELLSIZE(mapserv->ImgExt.minx, mapserv->ImgExt.maxx, mapserv->ImgCols);
+      celly = MS_CELLSIZE(mapserv->ImgExt.miny, mapserv->ImgExt.maxy, mapserv->ImgRows);
+      mapserv->map->extent.minx = MS_IMAGE2MAP_X(mapserv->ImgBox.minx, mapserv->ImgExt.minx, cellx);
+      mapserv->map->extent.maxx = MS_IMAGE2MAP_X(mapserv->ImgBox.maxx, mapserv->ImgExt.minx, cellx);
+      mapserv->map->extent.maxy = MS_IMAGE2MAP_Y(mapserv->ImgBox.miny, mapserv->ImgExt.maxy, celly); /* y's are flip flopped because img/map coordinate systems are */
+      mapserv->map->extent.miny = MS_IMAGE2MAP_Y(mapserv->ImgBox.maxy, mapserv->ImgExt.maxy, celly);
+      break;
+    case FROMIMGPNT:
+      cellx = MS_CELLSIZE(mapserv->ImgExt.minx, mapserv->ImgExt.maxx, mapserv->ImgCols);
+      celly = MS_CELLSIZE(mapserv->ImgExt.miny, mapserv->ImgExt.maxy, mapserv->ImgRows);
+      mapserv->mappnt.x = MS_IMAGE2MAP_X(mapserv->ImgPnt.x, mapserv->ImgExt.minx, cellx);
+      mapserv->mappnt.y = MS_IMAGE2MAP_Y(mapserv->ImgPnt.y, mapserv->ImgExt.maxy, celly);
+
+      mapserv->map->extent.minx = mapserv->mappnt.x - .5*((mapserv->ImgExt.maxx - mapserv->ImgExt.minx)/mapserv->fZoom); /* create an extent around that point */
+      mapserv->map->extent.miny = mapserv->mappnt.y - .5*((mapserv->ImgExt.maxy - mapserv->ImgExt.miny)/mapserv->fZoom);
+      mapserv->map->extent.maxx = mapserv->mappnt.x + .5*((mapserv->ImgExt.maxx - mapserv->ImgExt.minx)/mapserv->fZoom);
+      mapserv->map->extent.maxy = mapserv->mappnt.y + .5*((mapserv->ImgExt.maxy - mapserv->ImgExt.miny)/mapserv->fZoom);
+      break;
+    case FROMREFPNT:
+      cellx = MS_CELLSIZE(mapserv->map->reference.extent.minx, mapserv->map->reference.extent.maxx, mapserv->map->reference.width);
+      celly = MS_CELLSIZE(mapserv->map->reference.extent.miny, mapserv->map->reference.extent.maxy, mapserv->map->reference.height);
+      mapserv->mappnt.x = MS_IMAGE2MAP_X(mapserv->RefPnt.x, mapserv->map->reference.extent.minx, cellx);
+      mapserv->mappnt.y = MS_IMAGE2MAP_Y(mapserv->RefPnt.y, mapserv->map->reference.extent.maxy, celly);
+
+      mapserv->map->extent.minx = mapserv->mappnt.x - .5*(mapserv->ImgExt.maxx - mapserv->ImgExt.minx); /* create an extent around that point */
+      mapserv->map->extent.miny = mapserv->mappnt.y - .5*(mapserv->ImgExt.maxy - mapserv->ImgExt.miny);
+      mapserv->map->extent.maxx = mapserv->mappnt.x + .5*(mapserv->ImgExt.maxx - mapserv->ImgExt.minx);
+      mapserv->map->extent.maxy = mapserv->mappnt.y + .5*(mapserv->ImgExt.maxy - mapserv->ImgExt.miny);
+      break;
+    case FROMBUF:
+      mapserv->map->extent.minx = mapserv->mappnt.x - mapserv->Buffer; /* create an extent around that point, using the buffer */
+      mapserv->map->extent.miny = mapserv->mappnt.y - mapserv->Buffer;
+      mapserv->map->extent.maxx = mapserv->mappnt.x + mapserv->Buffer;
+      mapserv->map->extent.maxy = mapserv->mappnt.y + mapserv->Buffer;
+      break;
+    case FROMSCALE:
+      cellsize = (mapserv->ScaleDenom/mapserv->map->resolution)/msInchesPerUnit(mapserv->map->units,0); /* user supplied a point and a scale denominator */
+      mapserv->map->extent.minx = mapserv->mappnt.x - cellsize*(mapserv->map->width-1)/2.0;
+      mapserv->map->extent.miny = mapserv->mappnt.y - cellsize*(mapserv->map->height-1)/2.0;
+      mapserv->map->extent.maxx = mapserv->mappnt.x + cellsize*(mapserv->map->width-1)/2.0;
+      mapserv->map->extent.maxy = mapserv->mappnt.y + cellsize*(mapserv->map->height-1)/2.0;
+      break;
+    default: /* use the default in the mapfile if it exists */
+      if((mapserv->map->extent.minx == mapserv->map->extent.maxx) && (mapserv->map->extent.miny == mapserv->map->extent.maxy)) {
+        msSetError(MS_WEBERR, "No way to generate map extent.", "mapserv()");
+        return MS_FAILURE;
+      }
   }
 
   mapserv->RawExt = mapserv->map->extent; /* save unaltered extent */
-   
+
   return MS_SUCCESS;
 }
 
@@ -176,7 +179,7 @@ int checkWebExtent(mapservObj *mapserv)
   return MS_SUCCESS;
 }
 
-int checkWebScale(mapservObj *mapserv) 
+int checkWebScale(mapservObj *mapserv)
 {
   int status;
   rectObj work_extent = mapserv->map->extent;
@@ -199,10 +202,10 @@ int checkWebScale(mapservObj *mapserv)
       mapserv->mappnt.x = (mapserv->map->extent.maxx + mapserv->map->extent.minx)/2; /* use center of bad extent */
       mapserv->mappnt.y = (mapserv->map->extent.maxy + mapserv->map->extent.miny)/2;
       setExtent(mapserv);
-      mapserv->map->cellsize = msAdjustExtent(&(mapserv->map->extent), mapserv->map->width, mapserv->map->height);      
+      mapserv->map->cellsize = msAdjustExtent(&(mapserv->map->extent), mapserv->map->width, mapserv->map->height);
       if((status = msCalculateScale(mapserv->map->extent, mapserv->map->units, mapserv->map->width, mapserv->map->height, mapserv->map->resolution, &mapserv->map->scaledenom)) != MS_SUCCESS) return status;
     }
-  } else { 
+  } else {
     if((mapserv->map->scaledenom > mapserv->map->web.maxscaledenom) && (mapserv->map->web.maxscaledenom > 0)) {
       if(mapserv->map->web.maxtemplate) { /* use the template provided */
         if(TEMPLATE_TYPE(mapserv->map->web.maxtemplate) == MS_FILE) {
@@ -223,7 +226,7 @@ int checkWebScale(mapservObj *mapserv)
       }
     }
   }
-   
+
   return MS_SUCCESS;
 }
 
@@ -231,7 +234,7 @@ int msReturnTemplateQuery(mapservObj *mapserv, char *queryFormat, char **papszBu
 {
   imageObj *img = NULL;
   int i, status;
-  
+
   outputFormatObj *outputFormat=NULL;
   mapObj *map = mapserv->map;
 
@@ -246,45 +249,46 @@ int msReturnTemplateQuery(mapservObj *mapserv, char *queryFormat, char **papszBu
   if(i >= 0) outputFormat = map->outputformatlist[i];
 
   if(outputFormat) {
-     if( MS_RENDERER_PLUGIN(outputFormat) ) {
-         msInitializeRendererVTable(outputFormat);
-     }
+    if( MS_RENDERER_PLUGIN(outputFormat) ) {
+      msInitializeRendererVTable(outputFormat);
+    }
 
-     if( MS_RENDERER_OGR(outputFormat) )
-     {
-         if( mapserv != NULL )
-             checkWebScale(mapserv);
-         
-         status = msOGRWriteFromQuery(map, outputFormat, mapserv->sendheaders);
-       
-         return status;
-     }
+    if( MS_RENDERER_OGR(outputFormat) ) {
+      if( mapserv != NULL )
+        checkWebScale(mapserv);
+
+      status = msOGRWriteFromQuery(map, outputFormat, mapserv->sendheaders);
+
+      return status;
+    }
 
-     if( !MS_RENDERER_TEMPLATE(outputFormat) ) { /* got an image format, return the query results that way */
-       outputFormatObj *tempOutputFormat = map->outputformat; /* save format */
+    if( !MS_RENDERER_TEMPLATE(outputFormat) ) { /* got an image format, return the query results that way */
+      outputFormatObj *tempOutputFormat = map->outputformat; /* save format */
 
-       if( mapserv != NULL )
-           checkWebScale(mapserv);
+      if( mapserv != NULL )
+        checkWebScale(mapserv);
 
-       map->outputformat = outputFormat; /* override what was given for IMAGETYPE */
-       img = msDrawMap(map, MS_TRUE);
-       if(!img) return MS_FAILURE;
-       map->outputformat = tempOutputFormat; /* restore format */
+      map->outputformat = outputFormat; /* override what was given for IMAGETYPE */
+      img = msDrawMap(map, MS_TRUE);
+      if(!img) return MS_FAILURE;
+      map->outputformat = tempOutputFormat; /* restore format */
 
-       if(mapserv == NULL || mapserv->sendheaders) 
-           msIO_printf("Content-type: %s%c%c", MS_IMAGE_MIME_TYPE(outputFormat), 10,10);
-       status = msSaveImage(map, img, NULL);
-       msFreeImage(img);
+      if(mapserv == NULL || mapserv->sendheaders) {
+        msIO_setHeader("Content-Type", MS_IMAGE_MIME_TYPE(outputFormat));
+        msIO_sendHeaders();
+      }
+      status = msSaveImage(map, img, NULL);
+      msFreeImage(img);
 
-       return status;
+      return status;
     }
   }
 
-  /* 
+  /*
   ** At this point we know we have a template of some sort, either the new style that references a or the old
   ** style made up of external files slammed together. Either way we may have to compute a query map and other
   ** images. We only create support images IF the querymap has status=MS_ON.
-  */ 
+  */
   if(map->querymap.status && mapserv != NULL ) {
     checkWebScale(mapserv);
     if(msGenerateImages(mapserv, MS_TRUE, MS_TRUE) != MS_SUCCESS)
@@ -298,10 +302,12 @@ int msReturnTemplateQuery(mapservObj *mapserv, char *queryFormat, char **papszBu
       return MS_FAILURE;
     }
 
-    if(mapserv == NULL || mapserv->sendheaders) { 
-      const char *attachment = msGetOutputFormatOption( outputFormat, "ATTACHMENT", NULL ); 
-      if(attachment) msIO_printf("Content-disposition: attachment; filename=%s\n", attachment);
-      msIO_printf("Content-type: %s%c%c", outputFormat->mimetype, 10, 10);
+    if(mapserv == NULL || mapserv->sendheaders) {
+      const char *attachment = msGetOutputFormatOption( outputFormat, "ATTACHMENT", NULL );
+      if(attachment)
+        msIO_setHeader("Content-disposition","attachment; filename=%s", attachment);
+      msIO_setHeader("Content-Type", outputFormat->mimetype);
+      msIO_sendHeaders();
     }
     if((status = msReturnPage(mapserv, (char *) file, BROWSE, papszBuffer)) != MS_SUCCESS)
       return status;
@@ -320,7 +326,7 @@ int isOn(mapservObj *mapserv, char *name, char *group)
 {
   int i;
 
-  for(i=0;i<mapserv->NumLayers;i++) {
+  for(i=0; i<mapserv->NumLayers; i++) {
     if(name && strcmp(mapserv->Layers[i], name) == 0)  return(MS_TRUE);
     if(group && strcmp(mapserv->Layers[i], group) == 0) return(MS_TRUE);
   }
@@ -335,187 +341,181 @@ int isOn(mapservObj *mapserv, char *name, char *group)
 /************************************************************************/
 int sortLayerByOrder(mapObj *map, char* pszOrder)
 {
-    int *panCurrentOrder = NULL;
-    int i = 0;
+  int *panCurrentOrder = NULL;
+  int i = 0;
 
-    if(!map) 
-    {
-        msSetError(MS_WEBERR, "Invalid pointer.", "sortLayerByOrder()");
-        return MS_FAILURE;
-    }
-/* ==================================================================== */
-/*      The flag "ascending" is in fact not useful since the            */
-/*      default ordering is ascending.                                  */
-/* ==================================================================== */
-
-/* -------------------------------------------------------------------- */
-/*      the map->layerorder should be set at this point in the          */
-/*      sortLayerByMetadata.                                            */
-/* -------------------------------------------------------------------- */
-    if(map->layerorder)
-    {
-        panCurrentOrder = (int*)msSmallMalloc(map->numlayers * sizeof(int));
-         for (i=0; i<map->numlayers ;i++)
-           panCurrentOrder[i] = map->layerorder[i];
-         
-         if(strcasecmp(pszOrder, "DESCENDING") == 0)
-         {
-             for (i=0; i<map->numlayers; i++)
-               map->layerorder[i] = panCurrentOrder[map->numlayers-1-i];
-         }
-
-         free(panCurrentOrder);
+  if(!map) {
+    msSetError(MS_WEBERR, "Invalid pointer.", "sortLayerByOrder()");
+    return MS_FAILURE;
+  }
+  /* ==================================================================== */
+  /*      The flag "ascending" is in fact not useful since the            */
+  /*      default ordering is ascending.                                  */
+  /* ==================================================================== */
+
+  /* -------------------------------------------------------------------- */
+  /*      the map->layerorder should be set at this point in the          */
+  /*      sortLayerByMetadata.                                            */
+  /* -------------------------------------------------------------------- */
+  if(map->layerorder) {
+    panCurrentOrder = (int*)msSmallMalloc(map->numlayers * sizeof(int));
+    for (i=0; i<map->numlayers ; i++)
+      panCurrentOrder[i] = map->layerorder[i];
+
+    if(strcasecmp(pszOrder, "DESCENDING") == 0) {
+      for (i=0; i<map->numlayers; i++)
+        map->layerorder[i] = panCurrentOrder[map->numlayers-1-i];
     }
 
-    return MS_SUCCESS;
+    free(panCurrentOrder);
+  }
+
+  return MS_SUCCESS;
 }
-             
-             
+
+
 /*!
  * This function set the map->layerorder
  * index order by the metadata collumn name
 */
 int sortLayerByMetadata(mapObj *map, char* pszMetadata)
 {
-   int nLegendOrder1;
-   int nLegendOrder2;
-   char *pszLegendOrder1;
-   char *pszLegendOrder2;
-   int i, j;
-   int tmp;
-
-   if(!map) {
-     msSetError(MS_WEBERR, "Invalid pointer.", "sortLayerByMetadata()");
-     return MS_FAILURE;
-   }
-   
-   /*
-    * Initiate to default order (Reverse mapfile order)
-    */
-   if(map->layerorder)
-   {
-     int *pnLayerOrder;
-
-     /* Backup the original layer order to be able to reverse it */
-     pnLayerOrder = (int*)msSmallMalloc(map->numlayers * sizeof(int));
-     for (i=0; i<map->numlayers ;i++)
-       pnLayerOrder[i] = map->layerorder[i];
-
-     /* Get a new layerorder array */
-     free(map->layerorder);
-     map->layerorder = (int*)msSmallMalloc(map->numlayers * sizeof(int));
-
-     /* Reverse the layerorder array */
-     for (i=0; i<map->numlayers ;i++)
-       map->layerorder[i] = pnLayerOrder[map->numlayers - i - 1];
-
-     free(pnLayerOrder);
-   }
-   else
-   {
-     map->layerorder = (int*)msSmallMalloc(map->numlayers * sizeof(int));
-
-     for (i=0; i<map->numlayers ;i++)
-       map->layerorder[i] = map->numlayers - i - 1;
-   }
-
-   if(!pszMetadata)
-     return MS_SUCCESS;
-   
-   /* 
-    * Bubble sort algo (not very efficient)
-    * should implement a kind of quick sort
-    * alog instead
+  int nLegendOrder1;
+  int nLegendOrder2;
+  char *pszLegendOrder1;
+  char *pszLegendOrder2;
+  int i, j;
+  int tmp;
+
+  if(!map) {
+    msSetError(MS_WEBERR, "Invalid pointer.", "sortLayerByMetadata()");
+    return MS_FAILURE;
+  }
+
+  /*
+   * Initiate to default order (Reverse mapfile order)
    */
-   for (i=0; i<map->numlayers-1; i++) {
-      for (j=0; j<map->numlayers-1-i; j++) {
-         pszLegendOrder1 = msLookupHashTable(&(GET_LAYER(map, map->layerorder[j+1])->metadata), pszMetadata);
-         pszLegendOrder2 = msLookupHashTable(&(GET_LAYER(map, map->layerorder[j])->metadata), pszMetadata);
-     
-         if(!pszLegendOrder1 || !pszLegendOrder2)
-           continue;
-         
-         nLegendOrder1 = atoi(pszLegendOrder1);
-         nLegendOrder2 = atoi(pszLegendOrder2);      
-         
-         if(nLegendOrder1 < nLegendOrder2) {  /* compare the two neighbors */
-            tmp = map->layerorder[j];         /* swap a[j] and a[j+1]      */
-            map->layerorder[j] = map->layerorder[j+1];
-            map->layerorder[j+1] = tmp;
-         }
+  if(map->layerorder) {
+    int *pnLayerOrder;
+
+    /* Backup the original layer order to be able to reverse it */
+    pnLayerOrder = (int*)msSmallMalloc(map->numlayers * sizeof(int));
+    for (i=0; i<map->numlayers ; i++)
+      pnLayerOrder[i] = map->layerorder[i];
+
+    /* Get a new layerorder array */
+    free(map->layerorder);
+    map->layerorder = (int*)msSmallMalloc(map->numlayers * sizeof(int));
+
+    /* Reverse the layerorder array */
+    for (i=0; i<map->numlayers ; i++)
+      map->layerorder[i] = pnLayerOrder[map->numlayers - i - 1];
+
+    free(pnLayerOrder);
+  } else {
+    map->layerorder = (int*)msSmallMalloc(map->numlayers * sizeof(int));
+
+    for (i=0; i<map->numlayers ; i++)
+      map->layerorder[i] = map->numlayers - i - 1;
+  }
+
+  if(!pszMetadata)
+    return MS_SUCCESS;
+
+  /*
+   * Bubble sort algo (not very efficient)
+   * should implement a kind of quick sort
+   * alog instead
+  */
+  for (i=0; i<map->numlayers-1; i++) {
+    for (j=0; j<map->numlayers-1-i; j++) {
+      pszLegendOrder1 = msLookupHashTable(&(GET_LAYER(map, map->layerorder[j+1])->metadata), pszMetadata);
+      pszLegendOrder2 = msLookupHashTable(&(GET_LAYER(map, map->layerorder[j])->metadata), pszMetadata);
+
+      if(!pszLegendOrder1 || !pszLegendOrder2)
+        continue;
+
+      nLegendOrder1 = atoi(pszLegendOrder1);
+      nLegendOrder2 = atoi(pszLegendOrder2);
+
+      if(nLegendOrder1 < nLegendOrder2) {  /* compare the two neighbors */
+        tmp = map->layerorder[j];         /* swap a[j] and a[j+1]      */
+        map->layerorder[j] = map->layerorder[j+1];
+        map->layerorder[j+1] = tmp;
       }
-   }
-   
-   return MS_SUCCESS;
+    }
+  }
+
+  return MS_SUCCESS;
 }
 
 /*
 ** This function return a pointer
 ** at the begining of the first occurence
 ** of pszTag in pszInstr.
-** 
+**
 ** Tag can be [TAG] or [TAG something]
 */
 char *findTag(char *pszInstr, char *pszTag)
 {
-   char *pszTag1, *pszStart=NULL;
-   char *pszTemp;
-   int done=MS_FALSE;
-   int length;
-
-   if(!pszInstr || !pszTag) {
-     msSetError(MS_WEBERR, "Invalid pointer.", "findTag()");
-     return NULL;
-   }
-
-   length = strlen(pszTag) + 1; /* adding [ character to the beginning */
-   pszTag1 = (char*) msSmallMalloc(length+1);
-
-   strcpy(pszTag1, "[");   
-   strcat(pszTag1, pszTag);
-
-   pszTemp = pszInstr;
-   while(!done) {
-     pszStart = strstr(pszTemp, pszTag1);
-
-     if(pszStart == NULL)
-       done = MS_TRUE; /* tag not found */
-     else if((*(pszStart+length) == ']' || *(pszStart+length) == ' '))
-       done = MS_TRUE; /* valid tag */
-     else
-       pszTemp += length; /* skip ahead and start over */
-   }
-
-   free(pszTag1);
-   
-   return pszStart;
+  char *pszTag1, *pszStart=NULL;
+  char *pszTemp;
+  int done=MS_FALSE;
+  int length;
+
+  if(!pszInstr || !pszTag) {
+    msSetError(MS_WEBERR, "Invalid pointer.", "findTag()");
+    return NULL;
+  }
+
+  length = strlen(pszTag) + 1; /* adding [ character to the beginning */
+  pszTag1 = (char*) msSmallMalloc(length+1);
+
+  strcpy(pszTag1, "[");
+  strcat(pszTag1, pszTag);
+
+  pszTemp = pszInstr;
+  while(!done) {
+    pszStart = strstr(pszTemp, pszTag1);
+
+    if(pszStart == NULL)
+      done = MS_TRUE; /* tag not found */
+    else if((*(pszStart+length) == ']' || *(pszStart+length) == ' '))
+      done = MS_TRUE; /* valid tag */
+    else
+      pszTemp += length; /* skip ahead and start over */
+  }
+
+  free(pszTag1);
+
+  return pszStart;
 }
 
-/* 
-** This function return a pointer 
+/*
+** This function return a pointer
 ** to the end of the tag in pszTag
-** 
+**
 ** The end of a tag is the next
-** non-quoted ']' character. 
+** non-quoted ']' character.
 ** Return NULL if not found.
-*/ 
+*/
 
 char *findTagEnd(const char *pszTag)
 {
-   char *pszEnd = NULL, 
+  char *pszEnd = NULL,
         *pszTmp = (char*)pszTag;
 
-   while (pszTmp != NULL) {
-      if (*pszTmp == '"')
-         pszTmp = strchr(pszTmp+1,'"');
-      if ((pszTmp == NULL) || (*pszTmp == ']')) { 
-         pszEnd = pszTmp;
-         pszTmp = NULL;
-      } else
-         pszTmp++;
-   }
-   
-   return pszEnd;
+  while (pszTmp != NULL) {
+    if (*pszTmp == '"')
+      pszTmp = strchr(pszTmp+1,'"');
+    if ((pszTmp == NULL) || (*pszTmp == ']')) {
+      pszEnd = pszTmp;
+      pszTmp = NULL;
+    } else
+      pszTmp++;
+  }
+
+  return pszEnd;
 }
 
 /*
@@ -524,152 +524,147 @@ char *findTagEnd(const char *pszTag)
 */
 int getTagArgs(char* pszTag, char* pszInstr, hashTableObj **ppoHashTable)
 {
-   char *pszStart, *pszEnd, *pszArgs;
-   int nLength;
-   char **papszArgs, **papszVarVal;
-   int nArgs, nDummy;
-   int i;
-   
-   if(!pszTag || !pszInstr) {
-     msSetError(MS_WEBERR, "Invalid pointer.", "getTagArgs()");
-     return MS_FAILURE;
-   }
-   
-   /* set position to the begining of tag */
-   pszStart = findTag(pszInstr, pszTag);
-
-   if(pszStart) {
-       /* find ending position */
-       pszEnd = findTagEnd(pszStart);
-   
-      if(pszEnd) {
-         /* skip the tag name */
-         pszStart = pszStart + strlen(pszTag) + 1;
-
-         /* get length of all args */
-         nLength = pszEnd - pszStart;
-   
-         if(nLength > 0) { /* is there arguments ? */
-            pszArgs = (char*)msSmallMalloc(nLength + 1);
-            strlcpy(pszArgs, pszStart, nLength+1);
-            
-            if(!(*ppoHashTable))
-              *ppoHashTable = msCreateHashTable();
-            
-            /* put all arguments seperate by space in a hash table */
-            papszArgs = msStringTokenize(pszArgs, " ", &nArgs, MS_TRUE);
-
-            /* msReturnTemplateQuerycheck all argument if they have values */
-            for (i=0; i<nArgs; i++) {
-               if(strlen(papszArgs[i]) == 0) continue;
-
-               if(strchr(papszArgs[i], '='))
-               {
-                  papszVarVal = msStringTokenize(papszArgs[i], "=", &nDummy, MS_FALSE);               
-                  msInsertHashTable(*ppoHashTable, papszVarVal[0], 
-                                    papszVarVal[1]);
-                  free(papszVarVal[0]);
-                  free(papszVarVal[1]);
-                  free(papszVarVal);                  
-               }
-               else /* no value specified. set it to 1 */
-                  msInsertHashTable(*ppoHashTable, papszArgs[i], "1");
-               
-               free(papszArgs[i]);
-            }
-            free(papszArgs);
-            free(pszArgs);
-         }
+  char *pszStart, *pszEnd, *pszArgs;
+  int nLength;
+  char **papszArgs, **papszVarVal;
+  int nArgs, nDummy;
+  int i;
+
+  if(!pszTag || !pszInstr) {
+    msSetError(MS_WEBERR, "Invalid pointer.", "getTagArgs()");
+    return MS_FAILURE;
+  }
+
+  /* set position to the begining of tag */
+  pszStart = findTag(pszInstr, pszTag);
+
+  if(pszStart) {
+    /* find ending position */
+    pszEnd = findTagEnd(pszStart);
+
+    if(pszEnd) {
+      /* skip the tag name */
+      pszStart = pszStart + strlen(pszTag) + 1;
+
+      /* get length of all args */
+      nLength = pszEnd - pszStart;
+
+      if(nLength > 0) { /* is there arguments ? */
+        pszArgs = (char*)msSmallMalloc(nLength + 1);
+        strlcpy(pszArgs, pszStart, nLength+1);
+
+        if(!(*ppoHashTable))
+          *ppoHashTable = msCreateHashTable();
+
+        /* put all arguments seperate by space in a hash table */
+        papszArgs = msStringTokenize(pszArgs, " ", &nArgs, MS_TRUE);
+
+        /* msReturnTemplateQuerycheck all argument if they have values */
+        for (i=0; i<nArgs; i++) {
+          if(strlen(papszArgs[i]) == 0) {
+            free(papszArgs[i]);
+            continue;
+          }
+
+          if(strchr(papszArgs[i], '=')) {
+            papszVarVal = msStringTokenize(papszArgs[i], "=", &nDummy, MS_FALSE);
+            msInsertHashTable(*ppoHashTable, papszVarVal[0],
+                              papszVarVal[1]);
+            free(papszVarVal[0]);
+            free(papszVarVal[1]);
+            free(papszVarVal);
+          } else /* no value specified. set it to 1 */
+            msInsertHashTable(*ppoHashTable, papszArgs[i], "1");
+
+          free(papszArgs[i]);
+        }
+        free(papszArgs);
+        free(pszArgs);
       }
-   }  
+    }
+  }
 
-   return MS_SUCCESS;
-}   
+  return MS_SUCCESS;
+}
 
 /*
 ** Return a substring from instr between [tag] and [/tag]
 ** char * returned must be freed by caller.
-** pszNextInstr will be a pointer at the end of the 
+** pszNextInstr will be a pointer at the end of the
 ** first occurence found.
 */
 int getInlineTag(char *pszTag, char *pszInstr, char **pszResult)
 {
-   char *pszStart, *pszEnd=NULL,  *pszEndTag, *pszPatIn, *pszPatOut=NULL, *pszTmp;
-   int nInst=0;
-   int nLength;
-
-   *pszResult = NULL;
-
-   if(!pszInstr || !pszTag) {
-     msSetError(MS_WEBERR, "Invalid pointer.", "getInlineTag()");
-     return MS_FAILURE;
-   }
-
-   pszEndTag = (char*)msSmallMalloc(strlen(pszTag) + 3);
-   strcpy(pszEndTag, "[/");
-   strcat(pszEndTag, pszTag);
-
-   /* find start tag */
-   pszPatIn  = findTag(pszInstr, pszTag);
-   pszPatOut = strstr(pszInstr, pszEndTag);      
-
-   pszStart = pszPatIn;
-
-   pszTmp = pszInstr;
-
-   if(pszPatIn)
-   {
-      do 
-      {
-         if(pszPatIn && pszPatIn < pszPatOut)
-         {
-            nInst++;
-         
-            pszTmp = pszPatIn;
-         }
-      
-         if(pszPatOut && ((pszPatIn == NULL) || pszPatOut < pszPatIn))
-         {
-            pszEnd = pszPatOut;
-            nInst--;
-         
-            pszTmp = pszPatOut;
-         }
-
-         pszPatIn  = findTag(pszTmp+1, pszTag);
-         pszPatOut = strstr(pszTmp+1, pszEndTag);
-      
-      }while (pszTmp != NULL && nInst > 0);
-   }
-
-   if(pszStart && pszEnd) {
-      /* find end of start tag */
-      pszStart = strchr(pszStart, ']');
-   
-      if(pszStart) {
-         pszStart++;
-
-         nLength = pszEnd - pszStart;
-            
-         if(nLength > 0) {
-            *pszResult = (char*)msSmallMalloc(nLength + 1);
-
-            /* copy string beetween start and end tag */
-            strlcpy(*pszResult, pszStart, nLength+1);
-
-            (*pszResult)[nLength] = '\0';
-         }
+  char *pszStart, *pszEnd=NULL,  *pszEndTag, *pszPatIn, *pszPatOut=NULL, *pszTmp;
+  int nInst=0;
+  int nLength;
+
+  *pszResult = NULL;
+
+  if(!pszInstr || !pszTag) {
+    msSetError(MS_WEBERR, "Invalid pointer.", "getInlineTag()");
+    return MS_FAILURE;
+  }
+
+  pszEndTag = (char*)msSmallMalloc(strlen(pszTag) + 3);
+  strcpy(pszEndTag, "[/");
+  strcat(pszEndTag, pszTag);
+
+  /* find start tag */
+  pszPatIn  = findTag(pszInstr, pszTag);
+  pszPatOut = strstr(pszInstr, pszEndTag);
+
+  pszStart = pszPatIn;
+
+  pszTmp = pszInstr;
+
+  if(pszPatIn) {
+    do {
+      if(pszPatIn && pszPatIn < pszPatOut) {
+        nInst++;
+
+        pszTmp = pszPatIn;
       }
-      else
-      {
-         msSetError(MS_WEBERR, "Malformed [%s] tag.", "getInlineTag()", pszTag);
-         return MS_FAILURE;
+
+      if(pszPatOut && ((pszPatIn == NULL) || pszPatOut < pszPatIn)) {
+        pszEnd = pszPatOut;
+        nInst--;
+
+        pszTmp = pszPatOut;
+      }
+
+      pszPatIn  = findTag(pszTmp+1, pszTag);
+      pszPatOut = strstr(pszTmp+1, pszEndTag);
+
+    } while (pszTmp != NULL && nInst > 0);
+  }
+
+  if(pszStart && pszEnd) {
+    /* find end of start tag */
+    pszStart = strchr(pszStart, ']');
+
+    if(pszStart) {
+      pszStart++;
+
+      nLength = pszEnd - pszStart;
+
+      if(nLength > 0) {
+        *pszResult = (char*)msSmallMalloc(nLength + 1);
+
+        /* copy string beetween start and end tag */
+        strlcpy(*pszResult, pszStart, nLength+1);
+
+        (*pszResult)[nLength] = '\0';
       }
-   }
+    } else {
+      msSetError(MS_WEBERR, "Malformed [%s] tag.", "getInlineTag()", pszTag);
+      return MS_FAILURE;
+    }
+  }
 
-   msFree(pszEndTag);
+  msFree(pszEndTag);
 
-   return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 /*!
@@ -683,139 +678,139 @@ int getInlineTag(char *pszTag, char *pszInstr, char **pszResult)
 */
 int processIfTag(char **pszInstr, hashTableObj *ht, int bLastPass)
 {
-/*   char *pszNextInstr = pszInstr; */
-   char *pszStart, *pszEnd=NULL;
-   char *pszName, *pszValue, *pszOperator, *pszThen=NULL, *pszHTValue;
-   char *pszIfTag;
-   char *pszPatIn=NULL, *pszPatOut=NULL, *pszTmp;
-   int nInst = 0;
-   int bEmpty = 0;
-   int nLength;
-
-   hashTableObj *ifArgs=NULL;
-
-   if(!*pszInstr) {
-     msSetError(MS_WEBERR, "Invalid pointer.", "processIfTag()");
-     return MS_FAILURE;
-   }
-
-   /* find the if start tag */
-   
-   pszStart  = findTag(*pszInstr, "if");
-
-   while (pszStart) {
-     pszPatIn  = findTag(pszStart, "if");
-     pszPatOut = strstr(pszStart, "[/if]");
-     pszTmp = pszPatIn;
-      
-     do {
-       if(pszPatIn && pszPatIn < pszPatOut) {
-         nInst++;         
-         pszTmp = pszPatIn;
-       }
-      
-       if(pszPatOut && ((pszPatIn == NULL) || pszPatOut < pszPatIn)) {
-         pszEnd = pszPatOut;
-         nInst--;         
-         pszTmp = pszPatOut;         
-       }
-
-       pszPatIn  = findTag(pszTmp+1, "if");
-       pszPatOut = strstr(pszTmp+1, "[/if]");
-      
-     } while (pszTmp != NULL && nInst > 0);
-
-     /* get the then string (if expression is true) */
-     if(getInlineTag("if", pszStart, &pszThen) != MS_SUCCESS) {
-       msSetError(MS_WEBERR, "Malformed then if tag.", "processIfTag()");
-       return MS_FAILURE;
-     }
-      
-     /* retrieve if tag args */
-     if(getTagArgs("if", pszStart, &ifArgs) != MS_SUCCESS) {
-       msSetError(MS_WEBERR, "Malformed args if tag.", "processIfTag()");
-       return MS_FAILURE;
-     }
-      
-     pszName = msLookupHashTable(ifArgs, "name");
-     pszValue = msLookupHashTable(ifArgs, "value");
-     pszOperator = msLookupHashTable(ifArgs, "oper"); 
-     if(pszOperator == NULL) /* Default operator if not set is "eq" */
-       pszOperator = "eq";
-
-     bEmpty = 0;
-      
-     if(pszName) {
-       /* build the complete if tag ([if all_args]then string[/if]) */
-       /* to replace if by then string if expression is true */
-       /* or by a white space if not. */
-       nLength = pszEnd - pszStart;
-       pszIfTag = (char*)msSmallMalloc(nLength + 6);
-       strlcpy(pszIfTag, pszStart, nLength+1);
-       pszIfTag[nLength] = '\0';
-       strcat(pszIfTag, "[/if]");
-         
-       pszHTValue = msLookupHashTable(ht, pszName);
-
-       if(strcmp(pszOperator, "neq") == 0) {
-         if(pszValue && pszHTValue && strcasecmp(pszValue, pszHTValue) != 0) {
-           *pszInstr = msReplaceSubstring(*pszInstr, pszIfTag, pszThen);
-         } else if(pszHTValue) {
-           *pszInstr = msReplaceSubstring(*pszInstr, pszIfTag, "");
-           bEmpty = 1;
-         }
-       } else if(strcmp(pszOperator, "eq") == 0) {
-         if(pszValue && pszHTValue && strcasecmp(pszValue, pszHTValue) == 0) {
-           *pszInstr = msReplaceSubstring(*pszInstr, pszIfTag, pszThen);
-         } else if(pszHTValue) {
-           *pszInstr = msReplaceSubstring(*pszInstr, pszIfTag, "");
-           bEmpty = 1;
-         }
-       } else if(strcmp(pszOperator, "isnull") == 0) {
-         if(pszHTValue != NULL) {
-           /* We met a non-null value... condition is false */
-           *pszInstr = msReplaceSubstring(*pszInstr, pszIfTag, "");
-           bEmpty = 1;
-         } else if(bLastPass) {
-           /* On last pass, if value is still null then condition is true */
-           *pszInstr = msReplaceSubstring(*pszInstr, pszIfTag, pszThen);
-         }
-       } else if(strcmp(pszOperator, "isset") == 0) {
-         if(pszHTValue != NULL) {
-           /* Found a non-null value... condition is true */
-           *pszInstr = msReplaceSubstring(*pszInstr, pszIfTag, pszThen);
-         } else if(bLastPass) {
-           /* On last pass, if value still not set then condition is false */
-           *pszInstr = msReplaceSubstring(*pszInstr, pszIfTag, "");
-           bEmpty = 1;
-         }
-       } else {
-         msSetError(MS_WEBERR, "Unsupported operator (%s) in if tag.",  "processIfTag()", pszOperator);
-         return MS_FAILURE;
-       }                    
-
-       if(pszIfTag)
-         free(pszIfTag);
-
-       pszIfTag = NULL;
-     }
-      
-     if(pszThen)
-       free (pszThen);
-
-     pszThen=NULL;
-      
-     msFreeHashTable(ifArgs);
-     ifArgs=NULL;
-      
-     /* find the if start tag */
-     if(bEmpty)
-       pszStart = findTag(pszStart, "if");
-     else
-       pszStart = findTag(pszStart + 1, "if");
-   }
-   
-   return MS_SUCCESS;
+  /*   char *pszNextInstr = pszInstr; */
+  char *pszStart, *pszEnd=NULL;
+  char *pszName, *pszValue, *pszOperator, *pszThen=NULL, *pszHTValue;
+  char *pszIfTag;
+  char *pszPatIn=NULL, *pszPatOut=NULL, *pszTmp;
+  int nInst = 0;
+  int bEmpty = 0;
+  int nLength;
+
+  hashTableObj *ifArgs=NULL;
+
+  if(!*pszInstr) {
+    msSetError(MS_WEBERR, "Invalid pointer.", "processIfTag()");
+    return MS_FAILURE;
+  }
+
+  /* find the if start tag */
+
+  pszStart  = findTag(*pszInstr, "if");
+
+  while (pszStart) {
+    pszPatIn  = findTag(pszStart, "if");
+    pszPatOut = strstr(pszStart, "[/if]");
+    pszTmp = pszPatIn;
+
+    do {
+      if(pszPatIn && pszPatIn < pszPatOut) {
+        nInst++;
+        pszTmp = pszPatIn;
+      }
+
+      if(pszPatOut && ((pszPatIn == NULL) || pszPatOut < pszPatIn)) {
+        pszEnd = pszPatOut;
+        nInst--;
+        pszTmp = pszPatOut;
+      }
+
+      pszPatIn  = findTag(pszTmp+1, "if");
+      pszPatOut = strstr(pszTmp+1, "[/if]");
+
+    } while (pszTmp != NULL && nInst > 0);
+
+    /* get the then string (if expression is true) */
+    if(getInlineTag("if", pszStart, &pszThen) != MS_SUCCESS) {
+      msSetError(MS_WEBERR, "Malformed then if tag.", "processIfTag()");
+      return MS_FAILURE;
+    }
+
+    /* retrieve if tag args */
+    if(getTagArgs("if", pszStart, &ifArgs) != MS_SUCCESS) {
+      msSetError(MS_WEBERR, "Malformed args if tag.", "processIfTag()");
+      return MS_FAILURE;
+    }
+
+    pszName = msLookupHashTable(ifArgs, "name");
+    pszValue = msLookupHashTable(ifArgs, "value");
+    pszOperator = msLookupHashTable(ifArgs, "oper");
+    if(pszOperator == NULL) /* Default operator if not set is "eq" */
+      pszOperator = "eq";
+
+    bEmpty = 0;
+
+    if(pszName) {
+      /* build the complete if tag ([if all_args]then string[/if]) */
+      /* to replace if by then string if expression is true */
+      /* or by a white space if not. */
+      nLength = pszEnd - pszStart;
+      pszIfTag = (char*)msSmallMalloc(nLength + 6);
+      strlcpy(pszIfTag, pszStart, nLength+1);
+      pszIfTag[nLength] = '\0';
+      strcat(pszIfTag, "[/if]");
+
+      pszHTValue = msLookupHashTable(ht, pszName);
+
+      if(strcmp(pszOperator, "neq") == 0) {
+        if(pszValue && pszHTValue && strcasecmp(pszValue, pszHTValue) != 0) {
+          *pszInstr = msReplaceSubstring(*pszInstr, pszIfTag, pszThen);
+        } else if(pszHTValue) {
+          *pszInstr = msReplaceSubstring(*pszInstr, pszIfTag, "");
+          bEmpty = 1;
+        }
+      } else if(strcmp(pszOperator, "eq") == 0) {
+        if(pszValue && pszHTValue && strcasecmp(pszValue, pszHTValue) == 0) {
+          *pszInstr = msReplaceSubstring(*pszInstr, pszIfTag, pszThen);
+        } else if(pszHTValue) {
+          *pszInstr = msReplaceSubstring(*pszInstr, pszIfTag, "");
+          bEmpty = 1;
+        }
+      } else if(strcmp(pszOperator, "isnull") == 0) {
+        if(pszHTValue != NULL) {
+          /* We met a non-null value... condition is false */
+          *pszInstr = msReplaceSubstring(*pszInstr, pszIfTag, "");
+          bEmpty = 1;
+        } else if(bLastPass) {
+          /* On last pass, if value is still null then condition is true */
+          *pszInstr = msReplaceSubstring(*pszInstr, pszIfTag, pszThen);
+        }
+      } else if(strcmp(pszOperator, "isset") == 0) {
+        if(pszHTValue != NULL) {
+          /* Found a non-null value... condition is true */
+          *pszInstr = msReplaceSubstring(*pszInstr, pszIfTag, pszThen);
+        } else if(bLastPass) {
+          /* On last pass, if value still not set then condition is false */
+          *pszInstr = msReplaceSubstring(*pszInstr, pszIfTag, "");
+          bEmpty = 1;
+        }
+      } else {
+        msSetError(MS_WEBERR, "Unsupported operator (%s) in if tag.",  "processIfTag()", pszOperator);
+        return MS_FAILURE;
+      }
+
+      if(pszIfTag)
+        free(pszIfTag);
+
+      pszIfTag = NULL;
+    }
+
+    if(pszThen)
+      free (pszThen);
+
+    pszThen=NULL;
+
+    msFreeHashTable(ifArgs);
+    ifArgs=NULL;
+
+    /* find the if start tag */
+    if(bEmpty)
+      pszStart = findTag(pszStart, "if");
+    else
+      pszStart = findTag(pszStart + 1, "if");
+  }
+
+  return MS_SUCCESS;
 }
 
 /* Helper function to return the text before the supplied string2 in string1. */
@@ -841,14 +836,14 @@ static char *getPostTagText(const char *string1, const char *string2)
   if((tmpstr = strstr(string1, string2)) == NULL) return msStrdup(""); /* return an empty string */
 
   tmpstr += strlen(string2); /* skip string2 */
-  return msStrdup(tmpstr); 
+  return msStrdup(tmpstr);
 }
 
 /*
 ** Function to process a [feature ...] tag. This tag can *only* be found within
 ** a [resultset ...][/resultset] block.
 */
-static int processFeatureTag(mapservObj *mapserv, char **line, layerObj *layer) 
+static int processFeatureTag(mapservObj *mapserv, char **line, layerObj *layer)
 {
   char *preTag, *postTag; /* text before and after the tag */
 
@@ -881,11 +876,13 @@ static int processFeatureTag(mapservObj *mapserv, char **line, layerObj *layer)
 
   if(strstr(*line, "[/feature]") == NULL) { /* we know the closing tag must be here, if not throw an error */
     msSetError(MS_WEBERR, "[feature] tag found without closing [/feature].", "processFeatureTag()");
+    msFreeHashTable(tagArgs);
     return(MS_FAILURE);
   }
 
   if(getInlineTag("feature", *line, &tag) != MS_SUCCESS) {
     msSetError(MS_WEBERR, "Malformed feature tag.", "processFeatureTag()");
+    msFreeHashTable(tagArgs);
     return MS_FAILURE;
   }
 
@@ -893,20 +890,25 @@ static int processFeatureTag(mapservObj *mapserv, char **line, layerObj *layer)
   postTag = getPostTagText(*line, "[/feature]");
 
   /* start rebuilding **line */
-  free(*line); *line = preTag;
+  free(*line);
+  *line = preTag;
 
   /* we know the layer has query results or we wouldn't be in this code */
 
-  // status = msLayerOpen(layer); /* open the layer */
-  // if(status != MS_SUCCESS) return status;
-  
-  // status = msLayerGetItems(layer); /* retrieve all the item names */
-  // if(status != MS_SUCCESS) return status;
+#if 0
+  status = msLayerOpen(layer); /* open the layer */
+  if(status != MS_SUCCESS) return status;
+  status = msLayerGetItems(layer); /* retrieve all the item names */
+  if(status != MS_SUCCESS) return status;
+#endif
 
   if(layer->numjoins > 0) { /* initialize necessary JOINs here */
     for(j=0; j<layer->numjoins; j++) {
       status = msJoinConnect(layer, &(layer->joins[j]));
-      if(status != MS_SUCCESS) return status;
+      if(status != MS_SUCCESS) {
+        msFreeHashTable(tagArgs);
+        return status;
+      }
     }
   }
 
@@ -921,14 +923,16 @@ static int processFeatureTag(mapservObj *mapserv, char **line, layerObj *layer)
 
   for(i=0; i<limit; i++) {
     status = msLayerGetShape(layer, &(mapserv->resultshape), &(layer->resultcache->results[i]));
-    if(status != MS_SUCCESS) return status;
+    if(status != MS_SUCCESS) {
+      msFreeHashTable(tagArgs);
+      return status;
+    }
 
     mapserv->resultshape.classindex = msShapeGetClass(layer, layer->map, &mapserv->resultshape,  NULL, -1);
 
-    if ( mapserv->resultshape.classindex>=0 &&
-         (layer->class[mapserv->resultshape.classindex]->text.string || layer->labelitem) && 
-         layer->class[mapserv->resultshape.classindex]->label.size != -1)
-      mapserv->resultshape.text = msShapeGetAnnotation(layer, & mapserv->resultshape);
+    if(mapserv->resultshape.classindex >=0 && layer->class[mapserv->resultshape.classindex]->numlabels > 0)
+      msShapeGetAnnotation(layer, &mapserv->resultshape); // RFC 77 TODO: check return value
+
 
     /* prepare any necessary JOINs here (one-to-one only) */
     if(layer->numjoins > 0) {
@@ -943,7 +947,7 @@ static int processFeatureTag(mapservObj *mapserv, char **line, layerObj *layer)
     /*
     ** if necessary trim a few characters off the end of the tag
     */
-    if(trimLast && (i == limit-1)) {    
+    if(trimLast && (i == limit-1)) {
       char *ptr;
       if((ptr = strrstr(tag, trimLast)) != NULL)
         *ptr = '\0';
@@ -960,16 +964,17 @@ static int processFeatureTag(mapservObj *mapserv, char **line, layerObj *layer)
     mapserv->LRN++;
   }
 
-  // msLayerClose(layer);
+  /* msLayerClose(layer); */
   mapserv->resultlayer = NULL; /* necessary? */
 
   *line = msStringConcatenate(*line, postTag);
 
   /*
-  ** clean up 
+  ** clean up
   */
   free(postTag);
   free(tag);
+  msFreeHashTable(tagArgs);
 
   return(MS_SUCCESS);
 }
@@ -977,7 +982,7 @@ static int processFeatureTag(mapservObj *mapserv, char **line, layerObj *layer)
 /*
 ** Function to process a [resultset ...] tag.
 */
-static int processResultSetTag(mapservObj *mapserv, char **line, FILE *stream) 
+static int processResultSetTag(mapservObj *mapserv, char **line, FILE *stream)
 {
   char lineBuffer[MS_BUFFER_LENGTH];
   int foundTagEnd;
@@ -1001,7 +1006,7 @@ static int processResultSetTag(mapservObj *mapserv, char **line, FILE *stream)
   tagStart = findTag(*line, "resultset");
   if(!tagStart) return(MS_SUCCESS); /* OK, just return; */
 
-  while (tagStart) {  
+  while (tagStart) {
     /* initialize the tag arguments */
     layerName = NULL;
 
@@ -1015,12 +1020,14 @@ static int processResultSetTag(mapservObj *mapserv, char **line, FILE *stream)
 
     if(!layerName) {
       msSetError(MS_WEBERR, "[resultset] tag missing required 'layer' argument.", "processResultSetTag()");
+      msFreeHashTable(tagArgs);
       return(MS_FAILURE);
     }
 
     layerIndex = msGetLayerIndex(mapserv->map, layerName);
     if(layerIndex>=mapserv->map->numlayers || layerIndex<0) {
       msSetError(MS_MISCERR, "Layer named '%s' does not exist.", "processResultSetTag()", layerName);
+      msFreeHashTable(tagArgs);
       return MS_FAILURE;
     }
     lp = GET_LAYER(mapserv->map, layerIndex);
@@ -1028,6 +1035,7 @@ static int processResultSetTag(mapservObj *mapserv, char **line, FILE *stream)
     if(strstr(*line, "[/resultset]") == NULL) { /* read ahead */
       if(!stream) {
         msSetError(MS_WEBERR, "Invalid file pointer.", "processResultSetTag()");
+        msFreeHashTable(tagArgs);
         return(MS_FAILURE);
       }
 
@@ -1037,17 +1045,19 @@ static int processResultSetTag(mapservObj *mapserv, char **line, FILE *stream)
           *line = msStringConcatenate(*line, lineBuffer);
           if(strstr(*line, "[/resultset]") != NULL)
             foundTagEnd = MS_TRUE;
-        } else 
+        } else
           break; /* ran out of file */
       }
       if(foundTagEnd == MS_FALSE) {
         msSetError(MS_WEBERR, "[resultset] tag found without closing [/resultset].", "processResultSetTag()");
+        msFreeHashTable(tagArgs);
         return(MS_FAILURE);
       }
     }
 
     if(getInlineTag("resultset", *line, &tag) != MS_SUCCESS) {
       msSetError(MS_WEBERR, "Malformed resultset tag.", "processResultSetTag()");
+      msFreeHashTable(tagArgs);
       return MS_FAILURE;
     }
 
@@ -1055,12 +1065,15 @@ static int processResultSetTag(mapservObj *mapserv, char **line, FILE *stream)
     postTag = getPostTagText(*line, "[/resultset]");
 
     /* start rebuilding **line */
-    free(*line); *line = preTag;
+    free(*line);
+    *line = preTag;
 
-    if(lp->resultcache && lp->resultcache->numresults > 0) {    
+    if(lp->resultcache && lp->resultcache->numresults > 0) {
       /* probably will need a while-loop here to handle multiple instances of [feature ...] tags */
-      if(processFeatureTag(mapserv, &tag, lp) != MS_SUCCESS)
-        return(MS_FAILURE); /* TODO: how to handle */ 
+      if(processFeatureTag(mapserv, &tag, lp) != MS_SUCCESS) {
+        msFreeHashTable(tagArgs);
+        return(MS_FAILURE); /* TODO: how to handle */
+      }
       *line = msStringConcatenate(*line, tag);
     } else if(nodata) {
       *line = msStringConcatenate(*line, nodata);
@@ -1069,12 +1082,12 @@ static int processResultSetTag(mapservObj *mapserv, char **line, FILE *stream)
     *line = msStringConcatenate(*line, postTag);
 
     /* clean up */
-    msFreeHashTable(tagArgs); tagArgs=NULL;
     free(postTag);
     free(tag);
 
     tagStart = findTag(*line, "resultset");
   }
+  msFreeHashTable(tagArgs);
 
   return(MS_SUCCESS);
 }
@@ -1108,7 +1121,7 @@ static int processIncludeTag(mapservObj *mapserv, char **line, FILE *stream, int
 
   while( tagStart ) {
     tagOffset = tagStart - *line;
-    
+
     /* check for any tag arguments */
     if(getTagArgs("include", tagStart, &tagArgs) != MS_SUCCESS) return(MS_FAILURE);
     if(tagArgs) {
@@ -1120,8 +1133,8 @@ static int processIncludeTag(mapservObj *mapserv, char **line, FILE *stream, int
     if((includeStream = fopen(msBuildPath(path, mapserv->map->mappath, src), "r")) == NULL) {
       msSetError(MS_IOERR, src, "processIncludeTag()");
       return MS_FAILURE;
-    } 
-    
+    }
+
     if(isValidTemplate(includeStream, src) != MS_TRUE) {
       fclose(includeStream);
       return MS_FAILURE;
@@ -1133,7 +1146,7 @@ static int processIncludeTag(mapservObj *mapserv, char **line, FILE *stream, int
     /* done with included file handle */
     fclose(includeStream);
 
-     /* find the end of the tag */
+    /* find the end of the tag */
     tagEnd = findTagEnd(tagStart);
     tagEnd++;
 
@@ -1149,11 +1162,13 @@ static int processIncludeTag(mapservObj *mapserv, char **line, FILE *stream, int
     *line = msReplaceSubstring(*line, tag, processedContent);
 
     /* clean up */
-    free(tag); tag = NULL;
-    msFreeHashTable(tagArgs); tagArgs=NULL;
+    free(tag);
+    tag = NULL;
+    msFreeHashTable(tagArgs);
+    tagArgs=NULL;
     free(content);
     free(processedContent);
-    
+
     if((*line)[tagOffset] != '\0')
       tagStart = findTag(*line+tagOffset+1, "include");
     else
@@ -1174,7 +1189,7 @@ static int processItemTag(layerObj *layer, char **line, shapeObj *shape)
 
   char *tag, *tagStart, *tagEnd;
   hashTableObj *tagArgs=NULL;
-  int tagOffset, tagLength;
+  int tagLength;
   char *encodedTagValue=NULL, *tagValue=NULL;
 
   char *argValue=NULL;
@@ -1194,7 +1209,7 @@ static int processItemTag(layerObj *layer, char **line, shapeObj *shape)
 
   if(!tagStart) return(MS_SUCCESS); /* OK, just return; */
 
-  while (tagStart) {  
+  while (tagStart) {
     format = "$value"; /* initialize the tag arguments */
     nullFormat = "";
     precision=-1;
@@ -1202,8 +1217,6 @@ static int processItemTag(layerObj *layer, char **line, shapeObj *shape)
     uc = lc = commify = MS_FALSE;
     escape=ESCAPE_HTML;
 
-    tagOffset = tagStart - *line;
-
     /* check for any tag arguments */
     if(getTagArgs("item", tagStart, &tagArgs) != MS_SUCCESS) return(MS_FAILURE);
     if(tagArgs) {
@@ -1243,53 +1256,53 @@ static int processItemTag(layerObj *layer, char **line, shapeObj *shape)
       return(MS_FAILURE);
     }
 
-    for(i=0; i<layer->numitems; i++)			
+    for(i=0; i<layer->numitems; i++)
       if(strcasecmp(name, layer->items[i]) == 0) break;
 
     if(i == layer->numitems) {
       msSetError(MS_WEBERR, "Item name (%s) not found in layer item list.", "processItemTag()", name);
       return(MS_FAILURE);
-    }    
+    }
 
     /*
     ** now we know which item so build the tagValue
     */
     if(shape->values[i] && strlen(shape->values[i]) > 0) {
+      char *itemValue=NULL;
 
+      /* set tag text depending on pattern (if necessary), nullFormat can contain $value (#3637) */
       if(pattern && msEvalRegex(pattern, shape->values[i]) != MS_TRUE)
         tagValue = msStrdup(nullFormat);
-      else {
-        char *itemValue=NULL;
-
-        if(precision != -1) {
-          char numberFormat[16];
-        
-          itemValue = (char *) msSmallMalloc(64); /* plenty big */
-          snprintf(numberFormat, sizeof(numberFormat), "%%.%dlf", precision);
-          snprintf(itemValue, 64, numberFormat, atof(shape->values[i]));
-        } else
-          itemValue = msStrdup(shape->values[i]);
+      else
+        tagValue = msStrdup(format);
 
-        if(commify == MS_TRUE)
-          itemValue = msCommifyString(itemValue);
+      if(precision != -1) {
+        char numberFormat[16];
 
-        /* apply other effects */
-        if(uc == MS_TRUE)
-          for(j=0; j<strlen(itemValue); j++) itemValue[j] = toupper(itemValue[j]);
-        if(lc == MS_TRUE)
-          for(j=0; j<strlen(itemValue); j++) itemValue[j] = tolower(itemValue[j]);
-      
-        tagValue = msStrdup(format);
-        tagValue = msReplaceSubstring(tagValue, "$value", itemValue);
-        msFree(itemValue);
+        itemValue = (char *) msSmallMalloc(64); /* plenty big */
+        snprintf(numberFormat, sizeof(numberFormat), "%%.%dlf", precision);
+        snprintf(itemValue, 64, numberFormat, atof(shape->values[i]));
+      } else
+        itemValue = msStrdup(shape->values[i]);
 
-        if(!tagValue) {
-          msSetError(MS_WEBERR, "Error applying item format.", "processItemTag()");
-          return(MS_FAILURE); /* todo leaking... */
-        }
+      if(commify == MS_TRUE)
+        itemValue = msCommifyString(itemValue);
+
+      /* apply other effects */
+      if(uc == MS_TRUE)
+        for(j=0; j<strlen(itemValue); j++) itemValue[j] = toupper(itemValue[j]);
+      if(lc == MS_TRUE)
+        for(j=0; j<strlen(itemValue); j++) itemValue[j] = tolower(itemValue[j]);
+
+      tagValue = msReplaceSubstring(tagValue, "$value", itemValue);
+      msFree(itemValue);
+
+      if(!tagValue) {
+        msSetError(MS_WEBERR, "Error applying item format.", "processItemTag()");
+        return(MS_FAILURE); /* todo leaking... */
       }
     } else {
-      tagValue = msStrdup(nullFormat);
+      tagValue = msStrdup(nullFormat); /* attribute value is NULL or empty */
     }
 
     /* find the end of the tag */
@@ -1303,26 +1316,30 @@ static int processItemTag(layerObj *layer, char **line, shapeObj *shape)
 
     /* do the replacement */
     switch(escape) {
-    case ESCAPE_HTML:
-      encodedTagValue = msEncodeHTMLEntities(tagValue);
-      *line = msReplaceSubstring(*line, tag, encodedTagValue);
-      break;
-    case ESCAPE_URL:
-      encodedTagValue = msEncodeUrl(tagValue);
-      *line = msReplaceSubstring(*line, tag, encodedTagValue);
-      break;  
-    case ESCAPE_NONE:
-      *line = msReplaceSubstring(*line, tag, tagValue);
-      break;
-    default:
-      break;
+      case ESCAPE_HTML:
+        encodedTagValue = msEncodeHTMLEntities(tagValue);
+        *line = msReplaceSubstring(*line, tag, encodedTagValue);
+        break;
+      case ESCAPE_URL:
+        encodedTagValue = msEncodeUrl(tagValue);
+        *line = msReplaceSubstring(*line, tag, encodedTagValue);
+        break;
+      case ESCAPE_NONE:
+        *line = msReplaceSubstring(*line, tag, tagValue);
+        break;
+      default:
+        break;
     }
 
     /* clean up */
-    free(tag); tag = NULL;
-    msFreeHashTable(tagArgs); tagArgs=NULL;
-    msFree(tagValue); tagValue=NULL;
-    msFree(encodedTagValue); encodedTagValue=NULL;
+    free(tag);
+    tag = NULL;
+    msFreeHashTable(tagArgs);
+    tagArgs=NULL;
+    msFree(tagValue);
+    tagValue=NULL;
+    msFree(encodedTagValue);
+    encodedTagValue=NULL;
 
     tagStart = findTag(*line, "item");
   }
@@ -1380,7 +1397,7 @@ static int processExtentTag(mapservObj *mapserv, char **line, char *name, rectOb
 
     tagOffset = tagStart - *line;
 
-     /* check for any tag arguments */
+    /* check for any tag arguments */
     if(getTagArgs(name, tagStart, &tagArgs) != MS_SUCCESS) return(MS_FAILURE);
     if(tagArgs) {
       argValue = msLookupHashTable(tagArgs, "expand");
@@ -1389,7 +1406,7 @@ static int processExtentTag(mapservObj *mapserv, char **line, char *name, rectOb
           float f;
           sscanf(argValue, "%f%%", &f);
           xExpand = ((f/100.0)*(extent->maxx-extent->minx))/2;
-          yExpand = ((f/100.0)*(extent->maxy-extent->miny))/2;          
+          yExpand = ((f/100.0)*(extent->maxy-extent->miny))/2;
         } else {
           xExpand = atof(argValue);
           yExpand = xExpand;
@@ -1429,13 +1446,13 @@ static int processExtentTag(mapservObj *mapserv, char **line, char *name, rectOb
       tempExtent.maxx = MS_MAP2IMAGE_X(tempExtent.minx, mapserv->map->extent.minx, mapserv->map->cellsize);
       tempExtent.maxy = MS_MAP2IMAGE_Y(tempExtent.miny, mapserv->map->extent.maxy, mapserv->map->cellsize);
     } else if(rectProj && projectionString) {
-       projectionObj projection;
-       msInitProjection(&projection);
+      projectionObj projection;
+      msInitProjection(&projection);
 
-       if(MS_SUCCESS != msLoadProjectionString(&projection, projectionString)) return MS_FAILURE;
+      if(MS_SUCCESS != msLoadProjectionString(&projection, projectionString)) return MS_FAILURE;
 
-       if(msProjectionsDiffer(rectProj, &projection))
-         msProjectRect(rectProj, &projection, &tempExtent);
+      if(msProjectionsDiffer(rectProj, &projection))
+        msProjectRect(rectProj, &projection, &tempExtent);
     }
 
     tagValue = msStrdup(format);
@@ -1454,7 +1471,7 @@ static int processExtentTag(mapservObj *mapserv, char **line, char *name, rectOb
     snprintf(number, sizeof(number), numberFormat, tempExtent.maxy);
     tagValue = msReplaceSubstring(tagValue, "$maxy", number);
 
-     /* find the end of the tag */
+    /* find the end of the tag */
     tagEnd = findTagEnd(tagStart);
     tagEnd++;
 
@@ -1465,27 +1482,31 @@ static int processExtentTag(mapservObj *mapserv, char **line, char *name, rectOb
 
     /* do the replacement */
     switch(escape) {
-    case ESCAPE_HTML:
-      encodedTagValue = msEncodeHTMLEntities(tagValue);
-      *line = msReplaceSubstring(*line, tag, encodedTagValue);
-      break;
-    case ESCAPE_URL:
-      encodedTagValue = msEncodeUrl(tagValue);
-      *line = msReplaceSubstring(*line, tag, encodedTagValue);
-      break;
-    case ESCAPE_NONE:
-      *line = msReplaceSubstring(*line, tag, tagValue);
-      break;
-    default:
-      break;
+      case ESCAPE_HTML:
+        encodedTagValue = msEncodeHTMLEntities(tagValue);
+        *line = msReplaceSubstring(*line, tag, encodedTagValue);
+        break;
+      case ESCAPE_URL:
+        encodedTagValue = msEncodeUrl(tagValue);
+        *line = msReplaceSubstring(*line, tag, encodedTagValue);
+        break;
+      case ESCAPE_NONE:
+        *line = msReplaceSubstring(*line, tag, tagValue);
+        break;
+      default:
+        break;
     }
 
     /* clean up */
-    free(tag); tag = NULL;
-    msFreeHashTable(tagArgs); tagArgs=NULL;
-    msFree(tagValue); tagValue=NULL;
-    msFree(encodedTagValue); encodedTagValue=NULL;
-    
+    free(tag);
+    tag = NULL;
+    msFreeHashTable(tagArgs);
+    tagArgs=NULL;
+    msFree(tagValue);
+    tagValue=NULL;
+    msFree(encodedTagValue);
+    encodedTagValue=NULL;
+
     if((*line)[tagOffset] != '\0')
       tagStart = findTag(*line+tagOffset+1, name);
     else
@@ -1495,370 +1516,328 @@ static int processExtentTag(mapservObj *mapserv, char **line, char *name, rectOb
   return(MS_SUCCESS);
 }
 
-
-static int processShplabelTag(layerObj *layer, char **line, shapeObj *origshape) 
+// RFC 77 TODO: Need to validate these changes with Assefa...
+static int processShplabelTag(layerObj *layer, char **line, shapeObj *origshape)
 {
-    char *tag, *tagStart, *tagEnd;
-    char *tagValue=NULL;
-    hashTableObj *tagArgs=NULL;
-    int tagOffset, tagLength;
-    char *format;
-    char *argValue=NULL;
-    char *projectionString=NULL;
-    shapeObj tShape;
-    int precision=0;
-    int clip_to_map=MS_TRUE;
-    int use_label_settings=MS_FALSE;
-    double cellsize=0;
-    int labelposvalid = MS_FALSE;
-    pointObj labelPos;
-    int i,status;
-    char number[64]; /* holds a single number in the extent */
-    char numberFormat[16];
-    shapeObj *shape = NULL;
-
-    if(!*line) {
+  char *tag, *tagStart, *tagEnd;
+  char *tagValue=NULL;
+  hashTableObj *tagArgs=NULL;
+  int tagOffset, tagLength;
+  char *format;
+  char *argValue=NULL;
+  char *projectionString=NULL;
+  shapeObj tShape;
+  int precision=0;
+  int clip_to_map=MS_TRUE;
+  int use_label_settings=MS_FALSE;
+  double cellsize=0;
+  int labelposvalid = MS_FALSE;
+  pointObj labelPos;
+  int i,status;
+  char number[64]; /* holds a single number in the extent */
+  char numberFormat[16];
+  shapeObj *shape = NULL;
+
+  if(!*line) {
     msSetError(MS_WEBERR, "Invalid line pointer.", "processShplabelTag()");
     return(MS_FAILURE);
-    }
-    if( msCheckParentPointer(layer->map,"map")==MS_FAILURE )
-      return MS_FAILURE;
-  
-    tagStart = findTag(*line, "shplabel");
+  }
+  if(msCheckParentPointer(layer->map,"map") == MS_FAILURE)
+    return MS_FAILURE;
 
-    /* It is OK to have no shplabel tags, just return. */
-    if( !tagStart )
-      return MS_SUCCESS;
+  tagStart = findTag(*line, "shplabel");
 
-    if(!origshape || origshape->numlines <= 0) { /* I suppose we need to make sure the part has vertices (need shape checker?) */
-      msSetError(MS_WEBERR, "Null or empty shape.", "processShplabelTag()");
-      return(MS_FAILURE);
-    }
+  /* It is OK to have no shplabel tags, just return. */
+  if(!tagStart)
+    return MS_SUCCESS;
 
-    
-    while (tagStart) 
-    {
-        if (shape)
-          msFreeShape(shape);
-        shape = (shapeObj *) msSmallMalloc(sizeof(shapeObj));
-        msInitShape(shape);
-        msCopyShape(origshape, shape);
-
-        projectionString = NULL;
-        format = "$x,$y";
-        tagOffset = tagStart - *line;
-
-        if(getTagArgs("shplabel", tagStart, &tagArgs) != MS_SUCCESS) return(MS_FAILURE);
-        if(tagArgs) 
-        {
-            argValue = msLookupHashTable(tagArgs, "format");
-            if(argValue) format = argValue;
-
-            argValue = msLookupHashTable(tagArgs, "precision");
-            if(argValue) precision = atoi(argValue);
-
-            argValue = msLookupHashTable(tagArgs, "proj");
-            if(argValue) projectionString = argValue;
-
-            argValue = msLookupHashTable(tagArgs, "clip_to_map");
-            if(argValue) 
-              if(strcasecmp(argValue,"false") == 0) clip_to_map = MS_FALSE;
-
-            argValue = msLookupHashTable(tagArgs, "use_label_settings");
-            if(argValue) 
-              if(strcasecmp(argValue,"true") == 0) use_label_settings = MS_TRUE;
-        }
+  if(!origshape || origshape->numlines <= 0) { /* I suppose we need to make sure the part has vertices (need shape checker?) */
+    msSetError(MS_WEBERR, "Null or empty shape.", "processShplabelTag()");
+    return(MS_FAILURE);
+  }
 
-        labelPos.x = -1;
-        labelPos.y = -1;
-        msInitShape(&tShape);
+  while(tagStart) {
+    if(shape) msFreeShape(shape);
+    shape = (shapeObj *) msSmallMalloc(sizeof(shapeObj));
+    msInitShape(shape);
+    msCopyShape(origshape, shape);
 
-        tShape.type = MS_SHAPE_LINE;
-        tShape.line = (lineObj *) msSmallMalloc(sizeof(lineObj));
-        tShape.numlines = 1;
-        tShape.line[0].point = NULL; /* initialize the line */
-        tShape.line[0].numpoints = 0;
+    projectionString = NULL;
+    format = "$x,$y";
+    tagOffset = tagStart - *line;
 
-        if (layer->map->cellsize <= 0)
-        cellsize = MS_MAX(MS_CELLSIZE(layer->map->extent.minx, layer->map->extent.maxx, layer->map->width), 
-                          MS_CELLSIZE(layer->map->extent.miny, layer->map->extent.maxy, layer->map->height));
-        else
-          cellsize = layer->map->cellsize ;
+    if(getTagArgs("shplabel", tagStart, &tagArgs) != MS_SUCCESS) return(MS_FAILURE);
+    if(tagArgs) {
+      argValue = msLookupHashTable(tagArgs, "format");
+      if(argValue) format = argValue;
 
-        if (shape->type == MS_SHAPE_POINT)
-        {
-            labelposvalid = MS_FALSE;
-            if (shape->numlines > 0 && shape->line[0].numpoints > 0)
-            {
-                labelposvalid = MS_TRUE;
-                labelPos = shape->line[0].point[0];
-                if(layer->transform == MS_TRUE) 
-                {
-                    if (layer->project && 
-                        msProjectionsDiffer(&(layer->projection), &(layer->map->projection)))
-                      msProjectShape(&layer->projection, &layer->map->projection, shape);
-              
-                    labelPos = shape->line[0].point[0];
-                    labelPos.x = MS_MAP2IMAGE_X(labelPos.x, layer->map->extent.minx, cellsize);
-                    labelPos.y = MS_MAP2IMAGE_Y(labelPos.y, layer->map->extent.maxy, cellsize);
-                }
-            }
-          
+      argValue = msLookupHashTable(tagArgs, "precision");
+      if(argValue) precision = atoi(argValue);
+
+      argValue = msLookupHashTable(tagArgs, "proj");
+      if(argValue) projectionString = argValue;
+
+      argValue = msLookupHashTable(tagArgs, "clip_to_map");
+      if(argValue) {
+        if(strcasecmp(argValue,"false") == 0) clip_to_map = MS_FALSE;
+      }
+
+      argValue = msLookupHashTable(tagArgs, "use_label_settings");
+      if(argValue) {
+        if(strcasecmp(argValue,"true") == 0) use_label_settings = MS_TRUE;
+      }
+    }
+
+    labelPos.x = -1;
+    labelPos.y = -1;
+    msInitShape(&tShape);
+
+    tShape.type = MS_SHAPE_LINE;
+    tShape.line = (lineObj *) msSmallMalloc(sizeof(lineObj));
+    tShape.numlines = 1;
+    tShape.line[0].point = NULL; /* initialize the line */
+    tShape.line[0].numpoints = 0;
+
+    if(layer->map->cellsize <= 0)
+      cellsize = MS_MAX(MS_CELLSIZE(layer->map->extent.minx, layer->map->extent.maxx, layer->map->width), MS_CELLSIZE(layer->map->extent.miny, layer->map->extent.maxy, layer->map->height));
+    else
+      cellsize = layer->map->cellsize ;
+
+    if(shape->type == MS_SHAPE_POINT) {
+      labelposvalid = MS_FALSE;
+      if(shape->numlines > 0 && shape->line[0].numpoints > 0) {
+        labelposvalid = MS_TRUE;
+        labelPos = shape->line[0].point[0];
+        if(layer->transform == MS_TRUE) {
+          if(layer->project && msProjectionsDiffer(&(layer->projection), &(layer->map->projection)))
+            msProjectShape(&layer->projection, &layer->map->projection, shape);
+
+          labelPos = shape->line[0].point[0];
+          labelPos.x = MS_MAP2IMAGE_X(labelPos.x, layer->map->extent.minx, cellsize);
+          labelPos.y = MS_MAP2IMAGE_Y(labelPos.y, layer->map->extent.maxy, cellsize);
+        }
+      }
+    } else if(shape->type == MS_SHAPE_LINE) {
+      pointObj **annopoints = NULL;
+      double **angles = NULL, **lengths = NULL;
+      int numpoints = 1;
+
+      labelposvalid = MS_FALSE;
+      if(layer->transform == MS_TRUE) {
+        if(layer->project && msProjectionsDiffer(&(layer->projection), &(layer->map->projection)))
+          msProjectShape(&layer->projection, &layer->map->projection, shape);
+        if(clip_to_map)
+          msClipPolylineRect(shape, layer->map->extent);
+
+        msTransformShapeToPixelRound(shape, layer->map->extent, cellsize);
+      } else
+        msOffsetShapeRelativeTo(shape, layer);
+
+      if(shape->numlines > 0) {
+        annopoints = msPolylineLabelPoint(shape, -1, 0, &angles, &lengths, &numpoints, MS_FALSE);
+        if(numpoints > 0) {
+          /* convert to geo */
+          labelPos.x = annopoints[0]->x;
+          labelPos.y = annopoints[0]->y;
+
+          labelposvalid = MS_TRUE;
+          for(i=0; i<numpoints; i++) {
+            if(annopoints[i]) msFree(annopoints[i]);
+            if(angles[i]) msFree(angles[i]);
+            if(lengths[i]) msFree(lengths[i]);
+          }
+          msFree(angles);
+          msFree(annopoints);
+          msFree(lengths);
         }
-        else if (shape->type == MS_SHAPE_LINE)
-        {
-            pointObj     **annopoints = NULL;
-            double** angles = NULL, **lengths = NULL;
-            int numpoints = 1;
+      }
+    } else if (shape->type == MS_SHAPE_POLYGON) {
+      labelposvalid = MS_FALSE;
+      if(layer->transform == MS_TRUE) {
+        if(layer->project && msProjectionsDiffer(&(layer->projection), &(layer->map->projection)))
+          msProjectShape(&layer->projection, &layer->map->projection, shape);
+
+        if(clip_to_map)
+          msClipPolygonRect(shape, layer->map->extent);
+
+        msTransformShapeToPixelRound(shape, layer->map->extent, cellsize);
+      } else
+        msOffsetShapeRelativeTo(shape, layer);
 
+      if(shape->numlines > 0) {
+        if(msPolygonLabelPoint(shape, &labelPos, -1) == MS_SUCCESS) {
+          if(labelPos.x == -1 && labelPos.y == -1)
             labelposvalid = MS_FALSE;
-            if(layer->transform == MS_TRUE) {
-                if (layer->project && 
-                    msProjectionsDiffer(&(layer->projection), &(layer->map->projection)))
-                  msProjectShape(&layer->projection, &layer->map->projection, shape);
-                if (clip_to_map)
-                  msClipPolylineRect(shape, layer->map->extent);
-         
-
-                msTransformShapeToPixelRound(shape, layer->map->extent, cellsize);
-            }
-            else
-              msOffsetShapeRelativeTo(shape, layer);
-
-            if (shape->numlines > 0)
-            {
-                annopoints = msPolylineLabelPoint(shape, -1, 0, &angles, &lengths, &numpoints, MS_FALSE);
-                if (numpoints > 0)
-                {
-                    /*convert to geo*/
-                    labelPos.x = annopoints[0]->x;
-                    labelPos.y = annopoints[0]->y;
-                
-                    labelposvalid = MS_TRUE;
-                    for (i=0; i<numpoints; i++)
-                    {
-                        if (annopoints[i])
-                          msFree(annopoints[i]);
-                        if (angles[i])
-                          msFree(angles[i]);
-                        if (lengths[i])
-                          msFree(lengths[i]);
-                    }
-                    msFree(angles);
-                    msFree(annopoints);
-                    msFree(lengths);
-                }      
-            }
-        
+          else
+            labelposvalid = MS_TRUE;
         }
-        else if (shape->type == MS_SHAPE_POLYGON)
-        {
-            labelposvalid = MS_FALSE;
-            if(layer->transform == MS_TRUE) 
-            {
-                if (layer->project && 
-                    msProjectionsDiffer(&(layer->projection), &(layer->map->projection)))
-                  msProjectShape(&layer->projection, &layer->map->projection, shape);
-          
-                if (clip_to_map)
-                  msClipPolygonRect(shape, layer->map->extent);
-
-                msTransformShapeToPixelRound(shape, layer->map->extent, cellsize);
-            }
-            else
-              msOffsetShapeRelativeTo(shape, layer);
-
-            if (shape->numlines > 0)
-            {
-                if (msPolygonLabelPoint(shape, &labelPos, -1) == MS_SUCCESS)
-                {
-                    if (labelPos.x == -1 && labelPos.y == -1)
-                      labelposvalid = MS_FALSE;
-                    else
-                      labelposvalid = MS_TRUE;
-                }
-            }
+      }
+    }
+
+    if(labelposvalid == MS_TRUE) {
+      pointObj p1;
+      pointObj p2;
+      int label_offset_x, label_offset_y;
+      labelObj *label=NULL;
+      rectObj r;
+      shapeObj poly;
+      double tmp;
+
+      msInitShape(&poly);
+      p1.x =labelPos.x;
+      p1.y =labelPos.y;
+
+      p2.x =labelPos.x;
+      p2.y =labelPos.y;
+      if(use_label_settings == MS_TRUE) {
+
+        /* RFC 77: classes (and shapes) can have more than 1 piece of annotation, here we only use the first (index=0) */
+        if(shape->classindex >= 0  && layer->class[shape->classindex]->numlabels > 0) {
+          label = layer->class[shape->classindex]->labels[0];
+          if(msGetLabelSize(layer->map, label, label->annotext, label->size, &r, NULL) == MS_SUCCESS) {
+            label_offset_x = (int)(label->offsetx*layer->scalefactor);
+            label_offset_y = (int)(label->offsety*layer->scalefactor);
+
+            p1 = get_metrics(&labelPos, label->position, r, label_offset_x, label_offset_y, label->angle, 0, &poly);
+
+            /* should we use the point returned from  get_metrics?. From few test done, It seems
+               to return the UL corner of the text. For now use the bounds.minx/miny */
+            p1.x = poly.bounds.minx;
+            p1.y = poly.bounds.miny;
+            p2.x = poly.bounds.maxx;
+            p2.y = poly.bounds.maxy;
+          }
         }
-        if (labelposvalid == MS_TRUE)
-        {
-            pointObj p1;
-            pointObj p2;
-            int label_offset_x, label_offset_y;
-            labelObj *label=NULL;
-            rectObj r;
-            shapeObj poly;
-            double tmp;
-
-            msInitShape(&poly);
-
-            p1.x =labelPos.x;
-            p1.y =labelPos.y; 
-
-            p2.x =labelPos.x;
-            p2.y =labelPos.y;  
-            if (use_label_settings == MS_TRUE)
-            {
-                if (shape->text && shape->classindex >=0)
-                {
-                    label = &layer->class[shape->classindex]->label;
-                    if(msGetLabelSize(layer->map,label,shape->text,label->size,&r,NULL) == MS_SUCCESS)
-                    {
-                        label_offset_x = (int)(label->offsetx*layer->scalefactor);
-                        label_offset_y = (int)(label->offsety*layer->scalefactor);
-
-                        p1 = get_metrics(&labelPos, label->position, r, label_offset_x, label_offset_y, 
-                                              label->angle, 0, &poly);
-                        /*should we use the point returned from  get_metrics?. From few test done, It seems
-                         to return the UL corner of the text. For now use the bounds.minx/miny*/
-
-                        p1.x = poly.bounds.minx;
-                        p1.y = poly.bounds.miny;
-                        p2.x = poly.bounds.maxx;
-                        p2.y = poly.bounds.maxy;
-                        
-                    }
-                }
-            }
-            /* y's are flipped because it is in image coordinate systems */
-            p1.x = MS_IMAGE2MAP_X(p1.x, layer->map->extent.minx, cellsize);
-            tmp = p1.y;
-            p1.y = MS_IMAGE2MAP_Y(p2.y, layer->map->extent.maxy, cellsize);
-            p2.x = MS_IMAGE2MAP_X(p2.x, layer->map->extent.minx, cellsize);
-            p2.y = MS_IMAGE2MAP_Y(tmp, layer->map->extent.maxy, cellsize);
-            if(layer->transform == MS_TRUE) {
-                if (layer->project && 
-                    msProjectionsDiffer(&(layer->projection), &(layer->map->projection)))
-                {
-                    msProjectPoint(&layer->map->projection, &layer->projection, &p1);
-                    msProjectPoint(&layer->map->projection, &layer->projection, &p2);
-                }
-            }
-            msAddPointToLine(&(tShape.line[0]), &p1);
-            msAddPointToLine(&(tShape.line[0]), &p2);
+      }
+
+      /* y's are flipped because it is in image coordinate systems */
+      p1.x = MS_IMAGE2MAP_X(p1.x, layer->map->extent.minx, cellsize);
+      tmp = p1.y;
+      p1.y = MS_IMAGE2MAP_Y(p2.y, layer->map->extent.maxy, cellsize);
+      p2.x = MS_IMAGE2MAP_X(p2.x, layer->map->extent.minx, cellsize);
+      p2.y = MS_IMAGE2MAP_Y(tmp, layer->map->extent.maxy, cellsize);
+      if(layer->transform == MS_TRUE) {
+        if(layer->project && msProjectionsDiffer(&(layer->projection), &(layer->map->projection))) {
+          msProjectPoint(&layer->map->projection, &layer->projection, &p1);
+          msProjectPoint(&layer->map->projection, &layer->projection, &p2);
         }
-        else
-          tShape.numlines = 0;
-
-         if(projectionString && strcasecmp(projectionString,"image") == 0) {
-             precision = 0;
-
-             /* if necessary, project the shape to match the map */
-             if(msProjectionsDiffer(&(layer->projection), &(layer->map->projection)))
-               msProjectShape(&layer->projection, &layer->map->projection, &tShape);
-      
-              msClipPolylineRect(&tShape, layer->map->extent);
-
-              msTransformShapeToPixelRound(&tShape, layer->map->extent, layer->map->cellsize);
-
-         } else if(projectionString) {
-             projectionObj projection;
-             msInitProjection(&projection);
-
-             status = msLoadProjectionString(&projection, projectionString);
-             if(status != MS_SUCCESS) return MS_FAILURE;
-
-             if(msProjectionsDiffer(&(layer->projection), &projection)) 
-               msProjectShape(&layer->projection, &projection, &tShape);
-         }
-         
-          
-
-          /* find the end of the tag */
-          tagEnd = findTagEnd(tagStart);
-          tagEnd++;
-
-          /* build the complete tag so we can do substitution */
-          tagLength = tagEnd - tagStart;
-          tag = (char *) msSmallMalloc(tagLength + 1);
-          strlcpy(tag, tagStart, tagLength+1);
-
-          /* do the replacement */
-          tagValue = msStrdup(format);
-          if(precision > 0)
-            snprintf(numberFormat, sizeof(numberFormat), "%%.%dlf", precision);
-          else
-            snprintf(numberFormat, sizeof(numberFormat), "%%f");
-
-          if (tShape.numlines > 0)
-          {
-              if(strcasestr(tagValue, "$x") != 0)
-              {
-                  snprintf(number, sizeof(number), numberFormat, tShape.line[0].point[0].x);
-                  tagValue = msReplaceSubstring(tagValue, "$x", number);
-              }
-              if(strcasestr(tagValue, "$y") != 0)
-              {
-                  snprintf(number, sizeof(number), numberFormat, tShape.line[0].point[0].y);
-                  tagValue = msReplaceSubstring(tagValue, "$y", number);
-              }
-          
-              if(strcasestr(tagValue, "$minx") != 0)
-              {
-                  snprintf(number, sizeof(number), numberFormat, tShape.line[0].point[0].x);
-                  tagValue = msReplaceSubstring(tagValue, "$minx", number);
-              }
-              if(strcasestr(tagValue, "$miny") != 0)
-              {
-                  snprintf(number, sizeof(number), numberFormat, tShape.line[0].point[0].y);
-                  tagValue = msReplaceSubstring(tagValue, "$miny", number);
-              }
-              if(strcasestr(tagValue, "$maxx") != 0)
-              {
-                  snprintf(number, sizeof(number), numberFormat, tShape.line[0].point[1].x);
-                  tagValue = msReplaceSubstring(tagValue, "$maxx", number);
-              }
-              if(strcasestr(tagValue, "$maxy") != 0)
-              {
-                  snprintf(number, sizeof(number), numberFormat, tShape.line[0].point[1].y);
-                  tagValue = msReplaceSubstring(tagValue, "$maxy", number);
-              }
-          }
-           /* find the end of the tag */
-          tagEnd = findTagEnd(tagStart);
-          tagEnd++;
-
-          /* build the complete tag so we can do substitution */
-          tagLength = tagEnd - tagStart;
-          tag = (char *) msSmallMalloc(tagLength + 1);
-          strlcpy(tag, tagStart, tagLength+1);
-
-          *line = msReplaceSubstring(*line, tag, tagValue);
-
-          /* clean up */
-          msFreeShape(&tShape);
-          free(tag); tag = NULL;
-          msFreeHashTable(tagArgs); tagArgs=NULL;
-          msFree(tagValue); tagValue=NULL;
-             
-
-         if((*line)[tagOffset] != '\0')
-          tagStart = findTag(*line+tagOffset+1, "shplabel");
-         else
-           tagStart = NULL; 
+      }
+      msAddPointToLine(&(tShape.line[0]), &p1);
+      msAddPointToLine(&(tShape.line[0]), &p2);
+    } else
+      tShape.numlines = 0;
+
+    if(projectionString && strcasecmp(projectionString,"image") == 0) {
+      precision = 0;
+
+      /* if necessary, project the shape to match the map */
+      if(msProjectionsDiffer(&(layer->projection), &(layer->map->projection)))
+        msProjectShape(&layer->projection, &layer->map->projection, &tShape);
+
+      msClipPolylineRect(&tShape, layer->map->extent);
+
+      msTransformShapeToPixelRound(&tShape, layer->map->extent, layer->map->cellsize);
+    } else if(projectionString) {
+      projectionObj projection;
+      msInitProjection(&projection);
+
+      status = msLoadProjectionString(&projection, projectionString);
+      if(status != MS_SUCCESS) return MS_FAILURE;
+
+      if(msProjectionsDiffer(&(layer->projection), &projection))
+        msProjectShape(&layer->projection, &projection, &tShape);
     }
-    if (shape)
-      msFreeShape(shape);
 
-    return(MS_SUCCESS);
-}
+    /* find the end of the tag */
+    tagEnd = findTagEnd(tagStart);
+    tagEnd++;
+
+    /* build the complete tag so we can do substitution */
+    tagLength = tagEnd - tagStart;
+    tag = (char *) msSmallMalloc(tagLength + 1);
+    strlcpy(tag, tagStart, tagLength+1);
+
+    /* do the replacement */
+    tagValue = msStrdup(format);
+    if(precision > 0)
+      snprintf(numberFormat, sizeof(numberFormat), "%%.%dlf", precision);
+    else
+      snprintf(numberFormat, sizeof(numberFormat), "%%f");
+
+    if(tShape.numlines > 0) {
+      if(strcasestr(tagValue, "$x") != 0) {
+        snprintf(number, sizeof(number), numberFormat, tShape.line[0].point[0].x);
+        tagValue = msReplaceSubstring(tagValue, "$x", number);
+      }
+      if(strcasestr(tagValue, "$y") != 0) {
+        snprintf(number, sizeof(number), numberFormat, tShape.line[0].point[0].y);
+        tagValue = msReplaceSubstring(tagValue, "$y", number);
+      }
+
+      if(strcasestr(tagValue, "$minx") != 0) {
+        snprintf(number, sizeof(number), numberFormat, tShape.line[0].point[0].x);
+        tagValue = msReplaceSubstring(tagValue, "$minx", number);
+      }
+      if(strcasestr(tagValue, "$miny") != 0) {
+        snprintf(number, sizeof(number), numberFormat, tShape.line[0].point[0].y);
+        tagValue = msReplaceSubstring(tagValue, "$miny", number);
+      }
+      if(strcasestr(tagValue, "$maxx") != 0) {
+        snprintf(number, sizeof(number), numberFormat, tShape.line[0].point[1].x);
+        tagValue = msReplaceSubstring(tagValue, "$maxx", number);
+      }
+      if(strcasestr(tagValue, "$maxy") != 0) {
+        snprintf(number, sizeof(number), numberFormat, tShape.line[0].point[1].y);
+        tagValue = msReplaceSubstring(tagValue, "$maxy", number);
+      }
+    }
 
+    /* find the end of the tag */
+    tagEnd = findTagEnd(tagStart);
+    tagEnd++;
+
+    /* build the complete tag so we can do substitution */
+    tagLength = tagEnd - tagStart;
+    tag = (char *) msSmallMalloc(tagLength + 1);
+    strlcpy(tag, tagStart, tagLength+1);
+
+    *line = msReplaceSubstring(*line, tag, tagValue);
+
+    /* clean up */
+    msFreeShape(&tShape);
+    free(tag);
+    tag = NULL;
+    msFreeHashTable(tagArgs);
+    tagArgs=NULL;
+    msFree(tagValue);
+    tagValue=NULL;
+
+    if((*line)[tagOffset] != '\0')
+      tagStart = findTag(*line+tagOffset+1, "shplabel");
+    else
+      tagStart = NULL;
+  }
+  if(shape)
+    msFreeShape(shape);
+
+  return(MS_SUCCESS);
+}
 
 /*
 ** Function to process a [date ...] tag
 */
-
 static int processDateTag(char **line)
 {
   struct tm *datetime;
   time_t t;
   int result;
-  char *tag, *tagStart, *tagEnd;
+  char *tag=NULL, *tagStart, *tagEnd;
   hashTableObj *tagArgs=NULL;
   int tagOffset, tagLength;
 #define DATE_BUFLEN 1024
-  char datestr[DATE_BUFLEN]; 
+  char datestr[DATE_BUFLEN];
   char *argValue=NULL;
-  char *format, *tz; // tag parameters 
+  char *format, *tz; /* tag parameters */
 
   if(!*line) {
     msSetError(MS_WEBERR, "Invalid line pointer.", "processDateTag()");
@@ -1872,10 +1851,10 @@ static int processDateTag(char **line)
     return MS_SUCCESS;
 
   while (tagStart) {
-    // set tag params to defaults
+    /* set tag params to defaults */
     format = DEFAULT_DATE_FORMAT;
     tz = "";
-    
+
     tagOffset = tagStart - *line;
 
     /* check for any tag arguments */
@@ -1889,17 +1868,15 @@ static int processDateTag(char **line)
     }
 
     t = time(NULL);
-    if( strncasecmp( tz, "gmt", 4 ) == 0 )
-    {
+    if( strncasecmp( tz, "gmt", 4 ) == 0 ) {
       datetime = gmtime(&t);
     } else {
       datetime = localtime(&t);
     }
-    result = strftime(datestr, DATE_BUFLEN, format, datetime); 
-  
-    /* Only do the replacement if the date was successfully written */ 
-    if( result > 0 ) 
-    { 
+    result = strftime(datestr, DATE_BUFLEN, format, datetime);
+
+    /* Only do the replacement if the date was successfully written */
+    if( result > 0 ) {
       /* find the end of the tag */
       tagEnd = findTagEnd(tagStart);
       tagEnd++;
@@ -1914,32 +1891,34 @@ static int processDateTag(char **line)
     }
 
     /* clean up */
-    free(tag); tag = NULL;
-    msFreeHashTable(tagArgs); tagArgs=NULL;
+    msFree(tag);
+    tag = NULL;
+    msFreeHashTable(tagArgs);
+    tagArgs=NULL;
 
     if((*line)[tagOffset] != '\0')
-      tagStart = findTag(*line+tagOffset+1, "shpxy");
+      tagStart = findTag(*line+tagOffset+1, "date");
     else
-      tagStart = NULL;  
+      tagStart = NULL;
   }
-  
+
   return(MS_SUCCESS);
-  
+
 }
 
 /*
-** Function to process a [shpxy ...] tag: line contains the tag, shape holds the coordinates. 
+** Function to process a [shpxy ...] tag: line contains the tag, shape holds the coordinates.
 **
-** TODO's: 
+** TODO's:
 **   - May need to change attribute names.
 **   - Need generalization routines (not here, but in mapprimative.c).
 **   - Try to avoid all the realloc calls.
 */
-static int processShpxyTag(layerObj *layer, char **line, shapeObj *shape) 
+static int processShpxyTag(layerObj *layer, char **line, shapeObj *shape)
 {
   int i,j,p;
   int status;
-  
+
   char *tag, *tagStart, *tagEnd;
   hashTableObj *tagArgs=NULL;
   int tagOffset, tagLength;
@@ -1965,27 +1944,25 @@ static int processShpxyTag(layerObj *layer, char **line, shapeObj *shape)
 
   double scale_x, scale_y;
 
-  double buffer;
-  int bufferUnits;
 
   char *projectionString=NULL;
 
   shapeObj tShape;
-  char *coords=NULL, point[128];  
-  
+  char *coords=NULL, point[128];
+
 
   if(!*line) {
     msSetError(MS_WEBERR, "Invalid line pointer.", "processShpxyTag()");
     return(MS_FAILURE);
   }
   if( msCheckParentPointer(layer->map,"map")==MS_FAILURE )
-  return MS_FAILURE;
-  
+    return MS_FAILURE;
+
   tagStart = findTag(*line, "shpxy");
 
   /* It is OK to have no shpxy tags, just return. */
   if( !tagStart )
-      return MS_SUCCESS;
+    return MS_SUCCESS;
 
   if(!shape || shape->numlines <= 0) { /* I suppose we need to make sure the part has vertices (need shape checker?) */
     msSetError(MS_WEBERR, "Null or empty shape.", "processShpxyTag()");
@@ -1993,22 +1970,23 @@ static int processShpxyTag(layerObj *layer, char **line, shapeObj *shape)
   }
 
   while (tagStart) {
+#ifdef USE_GEOS
+    double buffer = 0;
+    int bufferUnits = -1;
+#endif
     xh = yh = yf = ph = pf = sh = sf = ""; /* initialize the tag arguments */
     xf= ",";
-    irh = irf = orh = orf = "";    
+    irh = irf = orh = orf = "";
     ps = cs = " ";
 
     centroid = MS_FALSE;
     precision = 0;
     scale_x = scale_y = 1.0;
 
-    buffer = 0;
-    bufferUnits = -1;
-
     projectionString = NULL;
 
     tagOffset = tagStart - *line;
- 
+
     /* check for any tag arguments */
     if(getTagArgs("shpxy", tagStart, &tagArgs) != MS_SUCCESS) return(MS_FAILURE);
     if(tagArgs) {
@@ -2047,17 +2025,19 @@ static int processShpxyTag(layerObj *layer, char **line, shapeObj *shape)
       argValue = msLookupHashTable(tagArgs, "sf");
       if(argValue) sf = argValue;
 
+#ifdef USE_GEOS
       argValue = msLookupHashTable(tagArgs, "buffer");
       if(argValue) {
         buffer = atof(argValue);
         if(strstr(argValue, "px")) bufferUnits = MS_PIXELS; /* may support others at some point */
       }
+#endif
 
       argValue = msLookupHashTable(tagArgs, "precision");
       if(argValue) precision = atoi(argValue);
 
       argValue = msLookupHashTable(tagArgs, "scale");
-      if(argValue) { 
+      if(argValue) {
         scale_x = atof(argValue);
         scale_y = scale_x;
       }
@@ -2069,7 +2049,7 @@ static int processShpxyTag(layerObj *layer, char **line, shapeObj *shape)
       if(argValue) scale_y = atof(argValue);
 
       argValue = msLookupHashTable(tagArgs, "centroid");
-      if(argValue) 
+      if(argValue)
         if(strcasecmp(argValue,"true") == 0) centroid = MS_TRUE;
 
 
@@ -2080,10 +2060,10 @@ static int processShpxyTag(layerObj *layer, char **line, shapeObj *shape)
     /* build the per point format strings (version 1 contains the coordinate seperator, version 2 doesn't) */
     pointFormatLength = strlen("xh") + strlen("xf") + strlen("yh") + strlen("yf") + strlen("cs") + 10 + 1;
     pointFormat1 = (char *) msSmallMalloc(pointFormatLength);
-    snprintf(pointFormat1, pointFormatLength, "%s%%.%dlf%s%s%%.%dlf%s%s", xh, precision, xf, yh, precision, yf, cs); 
-    pointFormat2 = (char *) msSmallMalloc(pointFormatLength); 
-    snprintf(pointFormat2, pointFormatLength, "%s%%.%dlf%s%s%%.%dlf%s", xh, precision, xf, yh, precision, yf); 
- 
+    snprintf(pointFormat1, pointFormatLength, "%s%%.%dlf%s%s%%.%dlf%s%s", xh, precision, xf, yh, precision, yf, cs);
+    pointFormat2 = (char *) msSmallMalloc(pointFormatLength);
+    snprintf(pointFormat2, pointFormatLength, "%s%%.%dlf%s%s%%.%dlf%s", xh, precision, xf, yh, precision, yf);
+
     /* make a copy of the original shape or compute a centroid if necessary */
     msInitShape(&tShape);
     if(centroid == MS_TRUE) {
@@ -2098,9 +2078,9 @@ static int processShpxyTag(layerObj *layer, char **line, shapeObj *shape)
       tShape.line[0].point = NULL; /* initialize the line */
       tShape.line[0].numpoints = 0;
 
-      msAddPointToLine(&(tShape.line[0]), &p);      
-    } 
-    
+      msAddPointToLine(&(tShape.line[0]), &p);
+    }
+
 #ifdef USE_GEOS
     else if(buffer != 0 && bufferUnits != MS_PIXELS) {
       shapeObj *bufferShape=NULL;
@@ -2109,8 +2089,8 @@ static int processShpxyTag(layerObj *layer, char **line, shapeObj *shape)
       if(!bufferShape) return(MS_FAILURE); /* buffer failed */
       msCopyShape(bufferShape, &tShape);
       msFreeShape(bufferShape);
-    } 
-#endif 
+    }
+#endif
     else {
       status = msCopyShape(shape, &tShape);
       if(status != 0) return(MS_FAILURE); /* copy failed */
@@ -2123,23 +2103,23 @@ static int processShpxyTag(layerObj *layer, char **line, shapeObj *shape)
       /* if necessary, project the shape to match the map */
       if(msProjectionsDiffer(&(layer->projection), &(layer->map->projection)))
         msProjectShape(&layer->projection, &layer->map->projection, &tShape);
-      
+
       switch(tShape.type) {
-      case(MS_SHAPE_POINT):
-        /* at this point we only convert the first point of the first shape */
-        tShape.line[0].point[0].x = MS_MAP2IMAGE_X(tShape.line[0].point[0].x, layer->map->extent.minx, layer->map->cellsize);
-        tShape.line[0].point[0].y = MS_MAP2IMAGE_Y(tShape.line[0].point[0].y, layer->map->extent.maxy, layer->map->cellsize);
-        break;
-      case(MS_SHAPE_LINE):
-        msClipPolylineRect(&tShape, layer->map->extent);
-        break;
-      case(MS_SHAPE_POLYGON):
-        msClipPolygonRect(&tShape, layer->map->extent);
-        break;
-      default:
-        /* TO DO: need an error message here */
-        return(MS_FAILURE);
-        break;
+        case(MS_SHAPE_POINT):
+          /* at this point we only convert the first point of the first shape */
+          tShape.line[0].point[0].x = MS_MAP2IMAGE_X(tShape.line[0].point[0].x, layer->map->extent.minx, layer->map->cellsize);
+          tShape.line[0].point[0].y = MS_MAP2IMAGE_Y(tShape.line[0].point[0].y, layer->map->extent.maxy, layer->map->cellsize);
+          break;
+        case(MS_SHAPE_LINE):
+          msClipPolylineRect(&tShape, layer->map->extent);
+          break;
+        case(MS_SHAPE_POLYGON):
+          msClipPolygonRect(&tShape, layer->map->extent);
+          break;
+        default:
+          /* TO DO: need an error message here */
+          return(MS_FAILURE);
+          break;
       }
       msTransformShapeToPixelRound(&tShape, layer->map->extent, layer->map->cellsize);
 
@@ -2156,24 +2136,24 @@ static int processShpxyTag(layerObj *layer, char **line, shapeObj *shape)
           msCopyShape(bufferShape, &tShape);
           msFreeShape(bufferShape);
         }
-      } 
+      }
 #endif
 
     } else if(projectionString) {
-       projectionObj projection;
-       msInitProjection(&projection);
+      projectionObj projection;
+      msInitProjection(&projection);
 
-       status = msLoadProjectionString(&projection, projectionString);
-       if(status != MS_SUCCESS) return MS_FAILURE;
+      status = msLoadProjectionString(&projection, projectionString);
+      if(status != MS_SUCCESS) return MS_FAILURE;
 
-       if(msProjectionsDiffer(&(layer->projection), &projection)) 
-         msProjectShape(&layer->projection, &projection, &tShape);
+      if(msProjectionsDiffer(&(layer->projection), &projection))
+        msProjectShape(&layer->projection, &projection, &tShape);
     }
-      
+
     /* TODO: add thinning support here */
-      
-    /* 
-    ** build the coordinate string 
+
+    /*
+    ** build the coordinate string
     */
 
     if(strlen(sh) > 0) coords = msStringConcatenate(coords, sh);
@@ -2183,12 +2163,12 @@ static int processShpxyTag(layerObj *layer, char **line, shapeObj *shape)
       int *outers;
       int firstPart; /* to keep track of inserting part separators before each part after the first */
       outers = msGetOuterList( &tShape );
-      firstPart = 1; 
+      firstPart = 1;
       /* loop over rings looking for outers*/
-      for(i=0; i<tShape.numlines; i++) { 
+      for(i=0; i<tShape.numlines; i++) {
         int *inners;
         if( outers[i] ) {
-          /* this is an outer ring */ 
+          /* this is an outer ring */
           if((!firstPart) && (strlen(ps) > 0)) coords = msStringConcatenate(coords, ps);
           firstPart = 0;
           if(strlen(ph) > 0) coords = msStringConcatenate(coords, ph);
@@ -2224,9 +2204,9 @@ static int processShpxyTag(layerObj *layer, char **line, shapeObj *shape)
 
       for(i=0; i<tShape.numlines; i++) { /* e.g. part */
 
-        /* skip degenerate parts, really should only happen with pixel output */ 
+        /* skip degenerate parts, really should only happen with pixel output */
         if((tShape.type == MS_SHAPE_LINE && tShape.line[i].numpoints < 2) ||
-          (tShape.type == MS_SHAPE_POLYGON && tShape.line[i].numpoints < 3))
+            (tShape.type == MS_SHAPE_POLYGON && tShape.line[i].numpoints < 3))
           continue;
 
         if(strlen(ph) > 0) coords = msStringConcatenate(coords, ph);
@@ -2246,7 +2226,7 @@ static int processShpxyTag(layerObj *layer, char **line, shapeObj *shape)
     if(strlen(sf) > 0) coords = msStringConcatenate(coords, sf);
 
     msFreeShape(&tShape);
-    
+
     /* find the end of the tag */
     tagEnd = findTagEnd(tagStart);
     tagEnd++;
@@ -2260,16 +2240,21 @@ static int processShpxyTag(layerObj *layer, char **line, shapeObj *shape)
     *line = msReplaceSubstring(*line, tag, coords);
 
     /* clean up */
-    free(tag); tag = NULL;
-    msFreeHashTable(tagArgs); tagArgs=NULL;
-    free(pointFormat1); pointFormat1 = NULL;
-    free(pointFormat2); pointFormat2 = NULL;
-    free(coords); coords = NULL;
+    free(tag);
+    tag = NULL;
+    msFreeHashTable(tagArgs);
+    tagArgs=NULL;
+    free(pointFormat1);
+    pointFormat1 = NULL;
+    free(pointFormat2);
+    pointFormat2 = NULL;
+    free(coords);
+    coords = NULL;
 
     if((*line)[tagOffset] != '\0')
       tagStart = findTag(*line+tagOffset+1, "shpxy");
     else
-      tagStart = NULL;  
+      tagStart = NULL;
   }
 
   return(MS_SUCCESS);
@@ -2279,1207 +2264,1167 @@ static int processShpxyTag(layerObj *layer, char **line, shapeObj *shape)
  * this function process all metadata
  * in pszInstr. ht mus contain all corresponding
  * metadata value.
- * 
+ *
  * this function return a modified pszInstr
 */
 int processMetadata(char** pszInstr, hashTableObj *ht)
 {
-/* char *pszNextInstr = pszInstr; */
-   char *pszEnd, *pszStart;
-   char *pszMetadataTag;
-   char *pszHashName;
-   char *pszHashValue;
-   int nLength, nOffset;
-
-   hashTableObj *metadataArgs = NULL;
-
-   if(!*pszInstr) {
-     msSetError(MS_WEBERR, "Invalid pointer.", "processMetadata()");
-     return MS_FAILURE;
-   }
-
-   /* set position to the begining of metadata tag */
-   pszStart = findTag(*pszInstr, "metadata");
-
-   while (pszStart) {
-      /* get metadata args */
-      if(getTagArgs("metadata", pszStart, &metadataArgs) != MS_SUCCESS)
-        return MS_FAILURE;
+  /* char *pszNextInstr = pszInstr; */
+  char *pszEnd, *pszStart;
+  char *pszMetadataTag;
+  char *pszHashName;
+  char *pszHashValue;
+  int nLength, nOffset;
 
-      pszHashName = msLookupHashTable(metadataArgs, "name");
-      pszHashValue = msLookupHashTable(ht, pszHashName);
-      
-      nOffset = pszStart - *pszInstr;
+  hashTableObj *metadataArgs = NULL;
+
+  if(!*pszInstr) {
+    msSetError(MS_WEBERR, "Invalid pointer.", "processMetadata()");
+    return MS_FAILURE;
+  }
 
-      if(pszHashName && pszHashValue) {
-           /* set position to the end of metadata start tag */
-           pszEnd = strchr(pszStart, ']');
-           pszEnd++;
+  /* set position to the begining of metadata tag */
+  pszStart = findTag(*pszInstr, "metadata");
 
-           /* build the complete metadata tag ([metadata all_args]) */
-           /* to replace it by the corresponding value from ht */
-           nLength = pszEnd - pszStart;
-           pszMetadataTag = (char*)msSmallMalloc(nLength + 1);
-           strlcpy(pszMetadataTag, pszStart, nLength+1);
+  while (pszStart) {
+    /* get metadata args */
+    if(getTagArgs("metadata", pszStart, &metadataArgs) != MS_SUCCESS)
+      return MS_FAILURE;
 
-           *pszInstr = msReplaceSubstring(*pszInstr, pszMetadataTag, pszHashValue);
+    pszHashName = msLookupHashTable(metadataArgs, "name");
+    pszHashValue = msLookupHashTable(ht, pszHashName);
 
-           free(pszMetadataTag);
-           pszMetadataTag=NULL;
-      }
+    nOffset = pszStart - *pszInstr;
 
-      msFreeHashTable(metadataArgs);
-      metadataArgs=NULL;
+    if(pszHashName && pszHashValue) {
+      /* set position to the end of metadata start tag */
+      pszEnd = strchr(pszStart, ']');
+      pszEnd++;
 
+      /* build the complete metadata tag ([metadata all_args]) */
+      /* to replace it by the corresponding value from ht */
+      nLength = pszEnd - pszStart;
+      pszMetadataTag = (char*)msSmallMalloc(nLength + 1);
+      strlcpy(pszMetadataTag, pszStart, nLength+1);
 
-      /* set position to the begining of the next metadata tag */
-      if((*pszInstr)[nOffset] != '\0')
-        pszStart = findTag(*pszInstr+nOffset+1, "metadata");
-      else
-        pszStart = NULL;
-   }
+      *pszInstr = msReplaceSubstring(*pszInstr, pszMetadataTag, pszHashValue);
 
-   return MS_SUCCESS;
+      free(pszMetadataTag);
+      pszMetadataTag=NULL;
+    }
+
+    msFreeHashTable(metadataArgs);
+    metadataArgs=NULL;
+
+
+    /* set position to the begining of the next metadata tag */
+    if((*pszInstr)[nOffset] != '\0')
+      pszStart = findTag(*pszInstr+nOffset+1, "metadata");
+    else
+      pszStart = NULL;
+  }
+
+  return MS_SUCCESS;
 }
 
 /*!
  * this function process all icon tag
  * from pszInstr.
- * 
+ *
  * This func return a modified pszInstr.
 */
 int processIcon(mapObj *map, int nIdxLayer, int nIdxClass, char** pszInstr, char* pszPrefix)
 {
-   int nWidth, nHeight, nLen;
-   char szImgFname[1024], *pszFullImgFname=NULL, *pszImgTag;
-   char szPath[MS_MAXPATHLEN];
-   hashTableObj *myHashTable=NULL;
-   FILE *fIcon;
-   
-   if(!map || 
-       nIdxLayer > map->numlayers || 
-       nIdxLayer < 0 ) {
-     msSetError(MS_WEBERR, "Invalid pointer.", "processIcon()");
-     return MS_FAILURE;
-   }
-
-   /* find the begining of tag */
-   pszImgTag = strstr(*pszInstr, "[leg_icon");
-   
-   while (pszImgTag) {
-      int i;
-      char szStyleCode[512] = "";
-      classObj *thisClass=NULL;
-
-      /* It's okay to have no classes... we'll generate an empty icon in this case */
-      if(nIdxClass >= 0 && nIdxClass < GET_LAYER(map, nIdxLayer)->numclasses)
-          thisClass = GET_LAYER(map, nIdxLayer)->class[nIdxClass];
-
-      if(getTagArgs("leg_icon", pszImgTag, &myHashTable) != MS_SUCCESS)
+  int nWidth, nHeight, nLen;
+  char szImgFname[1024], *pszFullImgFname=NULL, *pszImgTag;
+  char szPath[MS_MAXPATHLEN];
+  hashTableObj *myHashTable=NULL;
+  FILE *fIcon;
+
+  if(!map ||
+      nIdxLayer > map->numlayers ||
+      nIdxLayer < 0 ) {
+    msSetError(MS_WEBERR, "Invalid pointer.", "processIcon()");
+    return MS_FAILURE;
+  }
+
+  /* find the begining of tag */
+  pszImgTag = strstr(*pszInstr, "[leg_icon");
+
+  while (pszImgTag) {
+    int i;
+    char szStyleCode[512] = "";
+    classObj *thisClass=NULL;
+
+    /* It's okay to have no classes... we'll generate an empty icon in this case */
+    if(nIdxClass >= 0 && nIdxClass < GET_LAYER(map, nIdxLayer)->numclasses)
+      thisClass = GET_LAYER(map, nIdxLayer)->class[nIdxClass];
+
+    if(getTagArgs("leg_icon", pszImgTag, &myHashTable) != MS_SUCCESS)
+      return MS_FAILURE;
+
+    /* if no specified width or height, set them to map default */
+    if(!msLookupHashTable(myHashTable, "width") || !msLookupHashTable(myHashTable, "height")) {
+      nWidth = map->legend.keysizex;
+      nHeight= map->legend.keysizey;
+    } else {
+      nWidth  = atoi(msLookupHashTable(myHashTable, "width"));
+      nHeight = atoi(msLookupHashTable(myHashTable, "height"));
+    }
+
+    /* Create a unique and predictable filename to cache the legend icons.
+     * Include some key parameters from the first 2 styles
+     */
+    for(i=0; i<2 && thisClass && i<thisClass->numstyles; i++) {
+      styleObj *style;
+      char *pszSymbolNameHash = NULL;
+      style = thisClass->styles[i];
+      if(style->symbolname)
+        pszSymbolNameHash = msHashString(style->symbolname);
+
+      snprintf(szStyleCode+strlen(szStyleCode), 255,
+               "s%d_%x_%x_%x_%d_%s_%g",
+               i, MS_COLOR_GETRGB(style->color), MS_COLOR_GETRGB(style->backgroundcolor), MS_COLOR_GETRGB(style->outlinecolor),
+               style->symbol, pszSymbolNameHash?pszSymbolNameHash:"",
+               style->angle);
+      msFree(pszSymbolNameHash);
+    }
+
+    snprintf(szImgFname, sizeof(szImgFname), "%s_%d_%d_%d_%d_%s.%s%c",
+             pszPrefix, nIdxLayer, nIdxClass, nWidth, nHeight,
+             szStyleCode, MS_IMAGE_EXTENSION(map->outputformat),'\0');
+
+    pszFullImgFname = msStrdup(msBuildPath3(szPath, map->mappath,
+                                            map->web.imagepath, szImgFname));
+
+    /* check if icon already exist in cache */
+    if((fIcon = fopen(pszFullImgFname, "r")) != NULL) {
+      /* File already exists. No need to generate it again */
+      fclose(fIcon);
+    } else {
+      /* Create an image corresponding to the current class */
+      imageObj *img=NULL;
+
+      if(thisClass == NULL) {
+        /* Nonexistent class.  Create an empty image */
+        img = msCreateLegendIcon(map, NULL, NULL, nWidth, nHeight);
+      } else {
+        img = msCreateLegendIcon(map, GET_LAYER(map, nIdxLayer),
+                                 thisClass, nWidth, nHeight);
+      }
+
+      if(!img) {
+        if(myHashTable)
+          msFreeHashTable(myHashTable);
+
+        msSetError(MS_GDERR, "Error while creating GD image.", "processIcon()");
+        return MS_FAILURE;
+      }
+
+      /* save it with a unique file name */
+      if(msSaveImage(map, img, pszFullImgFname) != MS_SUCCESS) {
+        if(myHashTable)
+          msFreeHashTable(myHashTable);
+
+        msFreeImage(img);
+
+        msSetError(MS_IOERR, "Error saving GD image to disk (%s).", "processIcon()", pszFullImgFname);
+        msFree(pszFullImgFname);
         return MS_FAILURE;
+      }
+
+      msFreeImage(img);
+    }
+
+    msFree(pszFullImgFname);
+    pszFullImgFname = NULL;
+
+    nLen = (strchr(pszImgTag, ']') + 1) - pszImgTag;
+
+    if(nLen > 0) {
+      char *pszTag;
+
+      /* rebuid image tag ([leg_class_img all_args]) */
+      /* to replace it by the image url */
+      pszTag = (char*)msSmallMalloc(nLen + 1);
+      strlcpy(pszTag, pszImgTag, nLen+1);
+
+      pszFullImgFname = (char*)msSmallMalloc(strlen(map->web.imageurl) + strlen(szImgFname) + 1);
+      strcpy(pszFullImgFname, map->web.imageurl);
+      strcat(pszFullImgFname, szImgFname);
+
+      *pszInstr = msReplaceSubstring(*pszInstr, pszTag, pszFullImgFname);
+
+      msFree(pszFullImgFname);
+      pszFullImgFname = NULL;
+      msFree(pszTag);
+
+      /* find the begining of tag */
+      pszImgTag = strstr(*pszInstr, "[leg_icon");
+    } else {
+      pszImgTag = NULL;
+    }
+
+    if(myHashTable) {
+      msFreeHashTable(myHashTable);
+      myHashTable = NULL;
+    }
+  }
+
+  return MS_SUCCESS;
+}
+
+/*!
+ * Replace all tags from group template
+ * with correct value.
+ *
+ * this function return a buffer containing
+ * the template with correct values.
+ *
+ * buffer must be freed by caller.
+*/
+int generateGroupTemplate(char* pszGroupTemplate, mapObj *map, char* pszGroupName, hashTableObj *oGroupArgs, char **pszTemp, char* pszPrefix)
+{
+  hashTableObj *myHashTable;
+  char pszStatus[3];
+  char *pszClassImg;
+  char *pszOptFlag = NULL;
+  int i, j;
+  int nOptFlag = 15;
+  int bShowGroup;
+
+  *pszTemp = NULL;
+
+  if(!pszGroupName || !pszGroupTemplate) {
+    msSetError(MS_WEBERR, "Invalid pointer.", "generateGroupTemplate()");
+    return MS_FAILURE;
+  }
+
+  /*
+   * Get the opt_flag is any.
+   */
+  if(oGroupArgs)
+    pszOptFlag = msLookupHashTable(oGroupArgs, "opt_flag");
+
+  if(pszOptFlag)
+    nOptFlag = atoi(pszOptFlag);
+
+  /*
+   * Check all layers, if one in the group
+   * should be visible, print the group.
+   * (Check for opt_flag)
+   */
+  bShowGroup = 0;
+  for (j=0; j<map->numlayers; j++) {
+    if(GET_LAYER(map, map->layerorder[j])->group &&
+        strcmp(GET_LAYER(map, map->layerorder[j])->group, pszGroupName) == 0) {
+      /* dont display layer is off. */
+      if( (nOptFlag & 2) == 0 &&
+          GET_LAYER(map, map->layerorder[j])->status == MS_OFF )
+        bShowGroup = 0;
+      else
+        bShowGroup = 1;
+
+      /* dont display layer is query. */
+      if( (nOptFlag & 4) == 0  &&
+          GET_LAYER(map, map->layerorder[j])->type == MS_LAYER_QUERY )
+        bShowGroup = 0;
+
+      /* dont display layer is annotation. */
+      if( (nOptFlag & 8) == 0 &&
+          GET_LAYER(map, map->layerorder[j])->type == MS_LAYER_ANNOTATION )
+        bShowGroup = 0;
+
+
+      /* dont display layer if out of scale. */
+      if((nOptFlag & 1) == 0) {
+        if(map->scaledenom > 0) {
+          if((GET_LAYER(map, map->layerorder[j])->maxscaledenom > 0) &&
+              (map->scaledenom > GET_LAYER(map, map->layerorder[j])->maxscaledenom))
+            bShowGroup = 0;
+          if((GET_LAYER(map, map->layerorder[j])->minscaledenom > 0) &&
+              (map->scaledenom <= GET_LAYER(map, map->layerorder[j])->minscaledenom))
+            bShowGroup = 0;
+        }
+      }
+
+      /* The group contains one visible layer */
+      /* Draw the group */
+      if( bShowGroup )
+        break;
+    }
+  }
+
+  if( ! bShowGroup )
+    return MS_SUCCESS;
+
+  /*
+   * Work from a copy
+   */
+  *pszTemp = (char*)msSmallMalloc(strlen(pszGroupTemplate) + 1);
+  strcpy(*pszTemp, pszGroupTemplate);
+
+  /*
+   * Change group tags
+   */
+  *pszTemp = msReplaceSubstring(*pszTemp, "[leg_group_name]", pszGroupName);
+
+
+  /*
+   * Create a hash table that contain info
+   * on current layer
+   */
+  myHashTable = msCreateHashTable();
+
+  /*
+   * Check for the first layer
+   * that belong to this group.
+   * Get his status and check for if.
+   */
+  for (j=0; j<map->numlayers; j++) {
+    if(GET_LAYER(map, map->layerorder[j])->group && strcmp(GET_LAYER(map, map->layerorder[j])->group, pszGroupName) == 0) {
+      snprintf(pszStatus, sizeof(pszStatus), "%d", GET_LAYER(map, map->layerorder[j])->status);
+      msInsertHashTable(myHashTable, "layer_status", pszStatus);
+      msInsertHashTable(myHashTable, "layer_visible", msLayerIsVisible(map, GET_LAYER(map, map->layerorder[j]))?"1":"0" );
+      msInsertHashTable(myHashTable, "layer_queryable", msIsLayerQueryable(GET_LAYER(map, map->layerorder[j]))?"1":"0" );
+      msInsertHashTable(myHashTable, "group_name", pszGroupName);
+
+      if(processIfTag(pszTemp, myHashTable, MS_FALSE) != MS_SUCCESS)
+        return MS_FAILURE;
+
+      if(processIfTag(pszTemp, &(GET_LAYER(map, map->layerorder[j])->metadata), MS_FALSE) != MS_SUCCESS)
+        return MS_FAILURE;
+
+      if(processMetadata(pszTemp, &GET_LAYER(map, map->layerorder[j])->metadata) != MS_SUCCESS)
+        return MS_FAILURE;
+
+      break;
+    }
+  }
+
+  msFreeHashTable(myHashTable);
+
+  /*
+   * Process all metadata tags
+   * only web object is accessible
+  */
+  if(processMetadata(pszTemp, &(map->web.metadata)) != MS_SUCCESS)
+    return MS_FAILURE;
+
+  /*
+   * check for if tag
+  */
+  if(processIfTag(pszTemp, &(map->web.metadata), MS_TRUE) != MS_SUCCESS)
+    return MS_FAILURE;
+
+  /*
+   * Check if leg_icon tag exist
+   * if so display the first layer first class icon
+   */
+  pszClassImg = strstr(*pszTemp, "[leg_icon");
+  if(pszClassImg) {
+    /* find first layer of this group */
+    for (i=0; i<map->numlayers; i++)
+      if(GET_LAYER(map, map->layerorder[i])->group && strcmp(GET_LAYER(map, map->layerorder[i])->group, pszGroupName) == 0)
+        processIcon(map, map->layerorder[i], 0, pszTemp, pszPrefix);
+  }
+
+  return MS_SUCCESS;
+}
+
+/*!
+ * Replace all tags from layer template
+ * with correct value.
+ *
+ * this function return a buffer containing
+ * the template with correct values.
+ *
+ * buffer must be freed by caller.
+*/
+int generateLayerTemplate(char *pszLayerTemplate, mapObj *map, int nIdxLayer, hashTableObj *oLayerArgs, char **pszTemp, char* pszPrefix)
+{
+  hashTableObj *myHashTable;
+  char szStatus[10];
+  char szType[10];
+
+  int nOptFlag=0;
+  char *pszOptFlag = NULL;
+  char *pszClassImg;
+
+  char szTmpstr[128]; /* easily big enough for the couple of instances we need */
+
+  *pszTemp = NULL;
+
+  if(!pszLayerTemplate ||
+      !map ||
+      nIdxLayer > map->numlayers ||
+      nIdxLayer < 0 ) {
+    msSetError(MS_WEBERR, "Invalid pointer.", "generateLayerTemplate()");
+    return MS_FAILURE;
+  }
+
+  if(oLayerArgs)
+    pszOptFlag = msLookupHashTable(oLayerArgs, "opt_flag");
+
+  if(pszOptFlag)
+    nOptFlag = atoi(pszOptFlag);
+
+  /* don't display deleted layers */
+  if(GET_LAYER(map, nIdxLayer)->status == MS_DELETE)
+    return MS_SUCCESS;
+
+  /* dont display layer is off. */
+  /* check this if Opt flag is not set */
+  if((nOptFlag & 2) == 0 && GET_LAYER(map, nIdxLayer)->status == MS_OFF)
+    return MS_SUCCESS;
+
+  /* dont display layer is query. */
+  /* check this if Opt flag is not set */
+  if((nOptFlag & 4) == 0  && GET_LAYER(map, nIdxLayer)->type == MS_LAYER_QUERY)
+    return MS_SUCCESS;
+
+  /* dont display layer is annotation. */
+  /* check this if Opt flag is not set       */
+  if((nOptFlag & 8) == 0 && GET_LAYER(map, nIdxLayer)->type == MS_LAYER_ANNOTATION)
+    return MS_SUCCESS;
+
+  /* dont display layer if out of scale. */
+  /* check this if Opt flag is not set             */
+  if((nOptFlag & 1) == 0) {
+    if(map->scaledenom > 0) {
+      if((GET_LAYER(map, nIdxLayer)->maxscaledenom > 0) && (map->scaledenom > GET_LAYER(map, nIdxLayer)->maxscaledenom))
+        return MS_SUCCESS;
+      if((GET_LAYER(map, nIdxLayer)->minscaledenom > 0) && (map->scaledenom <= GET_LAYER(map, nIdxLayer)->minscaledenom))
+        return MS_SUCCESS;
+    }
+  }
+
+  /*
+   * Work from a copy
+   */
+  *pszTemp = msStrdup(pszLayerTemplate);
+
+  /*
+   * Change layer tags
+   */
+  *pszTemp = msReplaceSubstring(*pszTemp, "[leg_layer_name]", GET_LAYER(map, nIdxLayer)->name);
+  *pszTemp = msReplaceSubstring(*pszTemp, "[leg_layer_group]", GET_LAYER(map, nIdxLayer)->group);
+
+  snprintf(szTmpstr, sizeof(szTmpstr), "%d", nIdxLayer);
+  *pszTemp = msReplaceSubstring(*pszTemp, "[leg_layer_index]", szTmpstr);
+
+  snprintf(szTmpstr, sizeof(szTmpstr), "%g", GET_LAYER(map, nIdxLayer)->minscaledenom);
+  *pszTemp = msReplaceSubstring(*pszTemp, "[leg_layer_minscale]", szTmpstr);
+  *pszTemp = msReplaceSubstring(*pszTemp, "[leg_layer_minscaledenom]", szTmpstr);
+  snprintf(szTmpstr, sizeof(szTmpstr), "%g", GET_LAYER(map, nIdxLayer)->maxscaledenom);
+  *pszTemp = msReplaceSubstring(*pszTemp, "[leg_layer_maxscale]", szTmpstr);
+  *pszTemp = msReplaceSubstring(*pszTemp, "[leg_layer_maxscaledenom]", szTmpstr);
+
+  /*
+   * Create a hash table that contain info
+   * on current layer
+   */
+  myHashTable = msCreateHashTable();
+
+  /*
+   * for now, only status and type is required by template
+   */
+  snprintf(szStatus, sizeof(szStatus), "%d", GET_LAYER(map, nIdxLayer)->status);
+  msInsertHashTable(myHashTable, "layer_status", szStatus);
+
+  snprintf(szType, sizeof(szType), "%d", GET_LAYER(map, nIdxLayer)->type);
+  msInsertHashTable(myHashTable, "layer_type", szType);
+
+  msInsertHashTable(myHashTable, "layer_name", (GET_LAYER(map, nIdxLayer)->name)? GET_LAYER(map, nIdxLayer)->name : "");
+  msInsertHashTable(myHashTable, "layer_group", (GET_LAYER(map, nIdxLayer)->group)? GET_LAYER(map, nIdxLayer)->group : "");
+  msInsertHashTable(myHashTable, "layer_visible", msLayerIsVisible(map, GET_LAYER(map, nIdxLayer))?"1":"0" );
+  msInsertHashTable(myHashTable, "layer_queryable", msIsLayerQueryable(GET_LAYER(map, nIdxLayer))?"1":"0" );
+
+  if(processIfTag(pszTemp, myHashTable, MS_FALSE) != MS_SUCCESS)
+    return MS_FAILURE;
+
+  if(processIfTag(pszTemp, &(GET_LAYER(map, nIdxLayer)->metadata), MS_FALSE) != MS_SUCCESS)
+    return MS_FAILURE;
+
+  if(processIfTag(pszTemp, &(map->web.metadata), MS_TRUE) != MS_SUCCESS)
+    return MS_FAILURE;
+
+  msFreeHashTable(myHashTable);
+
+  /*
+   * Check if leg_icon tag exist
+   * if so display the first class icon
+   */
+  pszClassImg = strstr(*pszTemp, "[leg_icon");
+  if(pszClassImg) {
+    processIcon(map, nIdxLayer, 0, pszTemp, pszPrefix);
+  }
+
+  /* process all metadata tags
+   * only current layer and web object
+   * metaddata are accessible
+  */
+  if(processMetadata(pszTemp, &GET_LAYER(map, nIdxLayer)->metadata) != MS_SUCCESS)
+    return MS_FAILURE;
+
+  if(processMetadata(pszTemp, &(map->web.metadata)) != MS_SUCCESS)
+    return MS_FAILURE;
+
+  return MS_SUCCESS;
+}
+
+/*!
+ * Replace all tags from class template
+ * with correct value.
+ *
+ * this function return a buffer containing
+ * the template with correct values.
+ *
+ * buffer must be freed by caller.
+*/
+int generateClassTemplate(char* pszClassTemplate, mapObj *map, int nIdxLayer, int nIdxClass, hashTableObj *oClassArgs, char **pszTemp, char* pszPrefix)
+{
+  hashTableObj *myHashTable;
+  char szStatus[10];
+  char szType[10];
+
+  char *pszClassImg;
+  int nOptFlag=0;
+  char *pszOptFlag = NULL;
+
+  char szTmpstr[128]; /* easily big enough for the couple of instances we need */
+
+  *pszTemp = NULL;
+
+  if(!pszClassTemplate ||
+      !map ||
+      nIdxLayer > map->numlayers ||
+      nIdxLayer < 0 ||
+      nIdxClass > GET_LAYER(map, nIdxLayer)->numclasses ||
+      nIdxClass < 0) {
+
+    msSetError(MS_WEBERR, "Invalid pointer.", "generateClassTemplate()");
+    return MS_FAILURE;
+  }
+
+  if(oClassArgs)
+    pszOptFlag = msLookupHashTable(oClassArgs, "Opt_flag");
+
+  if(pszOptFlag)
+    nOptFlag = atoi(pszOptFlag);
+
+  /* don't display deleted layers */
+  if(GET_LAYER(map, nIdxLayer)->status == MS_DELETE)
+    return MS_SUCCESS;
+
+  /* dont display class if layer is off. */
+  /* check this if Opt flag is not set */
+  if((nOptFlag & 2) == 0 && GET_LAYER(map, nIdxLayer)->status == MS_OFF)
+    return MS_SUCCESS;
+
+  /* dont display class if layer is query. */
+  /* check this if Opt flag is not set       */
+  if((nOptFlag & 4) == 0 && GET_LAYER(map, nIdxLayer)->type == MS_LAYER_QUERY)
+    return MS_SUCCESS;
+
+  /* dont display class if layer is annotation. */
+  /* check this if Opt flag is not set       */
+  if((nOptFlag & 8) == 0 && GET_LAYER(map, nIdxLayer)->type == MS_LAYER_ANNOTATION)
+    return MS_SUCCESS;
+
+  /* dont display layer if out of scale. */
+  /* check this if Opt flag is not set */
+  if((nOptFlag & 1) == 0) {
+    if(map->scaledenom > 0) {
+      if((GET_LAYER(map, nIdxLayer)->maxscaledenom > 0) && (map->scaledenom > GET_LAYER(map, nIdxLayer)->maxscaledenom))
+        return MS_SUCCESS;
+      if((GET_LAYER(map, nIdxLayer)->minscaledenom > 0) && (map->scaledenom <= GET_LAYER(map, nIdxLayer)->minscaledenom))
+        return MS_SUCCESS;
+    }
+  }
+
+  /*
+   * Work from a copy
+   */
+  *pszTemp = (char*)msSmallMalloc(strlen(pszClassTemplate) + 1);
+  strcpy(*pszTemp, pszClassTemplate);
+
+  /*
+   * Change class tags
+   */
+  *pszTemp = msReplaceSubstring(*pszTemp, "[leg_class_name]", GET_LAYER(map, nIdxLayer)->class[nIdxClass]->name);
+  *pszTemp = msReplaceSubstring(*pszTemp, "[leg_class_title]", GET_LAYER(map, nIdxLayer)->class[nIdxClass]->title);
+  *pszTemp = msReplaceSubstring(*pszTemp, "[leg_layer_name]", GET_LAYER(map, nIdxLayer)->name);
+
+  snprintf(szTmpstr, sizeof(szTmpstr), "%d", nIdxClass);
+  *pszTemp = msReplaceSubstring(*pszTemp, "[leg_class_index]", szTmpstr);
+
+  snprintf(szTmpstr, sizeof(szTmpstr), "%g", GET_LAYER(map, nIdxLayer)->class[nIdxClass]->minscaledenom);
+  *pszTemp = msReplaceSubstring(*pszTemp, "[leg_class_minscale]", szTmpstr);
+  *pszTemp = msReplaceSubstring(*pszTemp, "[leg_class_minscaledenom]", szTmpstr);
+  snprintf(szTmpstr, sizeof(szTmpstr), "%g", GET_LAYER(map, nIdxLayer)->class[nIdxClass]->maxscaledenom);
+  *pszTemp = msReplaceSubstring(*pszTemp, "[leg_class_maxscale]", szTmpstr);
+  *pszTemp = msReplaceSubstring(*pszTemp, "[leg_class_maxscaledenom]", szTmpstr);
+
+  /*
+   * Create a hash table that contain info
+   * on current layer
+   */
+  myHashTable = msCreateHashTable();
+
+  /*
+   * for now, only status, type, name and group are  required by template
+   */
+  snprintf(szStatus, sizeof(szStatus), "%d", GET_LAYER(map, nIdxLayer)->status);
+  msInsertHashTable(myHashTable, "layer_status", szStatus);
+
+  snprintf(szType, sizeof(szType), "%d", GET_LAYER(map, nIdxLayer)->type);
+  msInsertHashTable(myHashTable, "layer_type", szType);
+
+  msInsertHashTable(myHashTable, "layer_name",
+                    (GET_LAYER(map, nIdxLayer)->name)? GET_LAYER(map, nIdxLayer)->name : "");
+  msInsertHashTable(myHashTable, "layer_group",
+                    (GET_LAYER(map, nIdxLayer)->group)? GET_LAYER(map, nIdxLayer)->group : "");
+  msInsertHashTable(myHashTable, "layer_visible", msLayerIsVisible(map, GET_LAYER(map, nIdxLayer))?"1":"0" );
+  msInsertHashTable(myHashTable, "layer_queryable", msIsLayerQueryable(GET_LAYER(map, nIdxLayer))?"1":"0" );
+  msInsertHashTable(myHashTable, "class_name",
+                    (GET_LAYER(map, nIdxLayer)->class[nIdxClass]->name)? GET_LAYER(map, nIdxLayer)->class[nIdxClass]->name : "");
+
+  if(processIfTag(pszTemp, myHashTable, MS_FALSE) != MS_SUCCESS)
+    return MS_FAILURE;
+
+  if(processIfTag(pszTemp, &(GET_LAYER(map, nIdxLayer)->metadata), MS_FALSE) != MS_SUCCESS)
+    return MS_FAILURE;
+
+  if(processIfTag(pszTemp, &(map->web.metadata), MS_TRUE) != MS_SUCCESS)
+    return MS_FAILURE;
+
+  msFreeHashTable(myHashTable);
+
+  /*
+   * Check if leg_icon tag exist
+   */
+  pszClassImg = strstr(*pszTemp, "[leg_icon");
+  if(pszClassImg) {
+    processIcon(map, nIdxLayer, nIdxClass, pszTemp, pszPrefix);
+  }
+
+  /* process all metadata tags
+   * only current layer and web object
+   * metaddata are accessible
+  */
+  if(processMetadata(pszTemp, &GET_LAYER(map, nIdxLayer)->metadata) != MS_SUCCESS)
+    return MS_FAILURE;
+
+  if(processMetadata(pszTemp, &(map->web.metadata)) != MS_SUCCESS)
+    return MS_FAILURE;
+
+  return MS_SUCCESS;
+}
+
+char *generateLegendTemplate(mapservObj *mapserv)
+{
+  FILE *stream;
+  char *file = NULL;
+  int length;
+  char *pszResult = NULL;
+  char *legGroupHtml = NULL;
+  char *legLayerHtml = NULL;
+  char *legClassHtml = NULL;
+  char *legLayerHtmlCopy = NULL;
+  char *legClassHtmlCopy = NULL;
+  char *legGroupHtmlCopy = NULL;
+
+  char *legHeaderHtml = NULL;
+  char *legFooterHtml = NULL;
+
+  char *pszPrefix = NULL;
+  char *pszMapFname = NULL;
+
+  struct stat tmpStat;
+
+  char *pszOrderMetadata = NULL;
+  char *pszOrder = NULL;
+
+  int i,j,k;
+  char **papszGroups = NULL;
+  int nGroupNames = 0;
+
+  int nLegendOrder = 0;
+  char *pszOrderValue;
+
+  hashTableObj *groupArgs = NULL;
+  hashTableObj *layerArgs = NULL;
+  hashTableObj *classArgs = NULL;
+
+  ms_regex_t re; /* compiled regular expression to be matched */
+
+  int  *panCurrentDrawingOrder = NULL;
+  char szPath[MS_MAXPATHLEN];
+
+  if(ms_regcomp(&re, MS_TEMPLATE_EXPR, MS_REG_EXTENDED|MS_REG_NOSUB|MS_REG_ICASE) != 0) {
+    msSetError(MS_IOERR, "Error regcomp.", "generateLegendTemplate()");
+    return NULL;
+  }
+
+  if(ms_regexec(&re, mapserv->map->legend.template, 0, NULL, 0) != 0) { /* no match */
+    msSetError(MS_IOERR, "Invalid template file name.", "generateLegendTemplate()");
+    ms_regfree(&re);
+    return NULL;
+  }
+  ms_regfree(&re);
+
+  /* -------------------------------------------------------------------- */
+  /*      Save the current drawing order. The drawing order is reset      */
+  /*      at the end of the function.                                     */
+  /* -------------------------------------------------------------------- */
+  if(mapserv && mapserv->map && mapserv->map->numlayers > 0) {
+    panCurrentDrawingOrder =
+      (int *)msSmallMalloc(sizeof(int)*mapserv->map->numlayers);
+
+    for (i=0; i<mapserv->map->numlayers; i++) {
+      if(mapserv->map->layerorder)
+        panCurrentDrawingOrder[i] = mapserv->map->layerorder[i];
+      else
+        panCurrentDrawingOrder[i] = i;
+    }
+  }
+
+  /*
+   * build prefix filename
+   * for legend icon creation
+  */
+  for(i=0; i<mapserv->request->NumParams; i++) /* find the mapfile parameter first */
+    if(strcasecmp(mapserv->request->ParamNames[i], "map") == 0) break;
+
+  if(i == mapserv->request->NumParams) {
+    if( getenv("MS_MAPFILE"))
+      pszMapFname = msStringConcatenate(pszMapFname, getenv("MS_MAPFILE"));
+  } else {
+    if(getenv(mapserv->request->ParamValues[i])) /* an environment references the actual file to use */
+      pszMapFname = msStringConcatenate(pszMapFname, getenv(mapserv->request->ParamValues[i]));
+    else
+      pszMapFname = msStringConcatenate(pszMapFname, mapserv->request->ParamValues[i]);
+  }
+
+  if(pszMapFname) {
+    if(stat(pszMapFname, &tmpStat) != -1) {
+      int nLen;
+
+      nLen = (mapserv->map->name?strlen(mapserv->map->name):0)  + 50;
+      pszPrefix = (char*)msSmallMalloc((nLen+1) * sizeof(char));
+      snprintf(pszPrefix, nLen, "%s_%ld_%ld",
+               mapserv->map->name,
+               (long) tmpStat.st_size,
+               (long) tmpStat.st_mtime);
+      pszPrefix[nLen] = '\0';
+    }
+
+    free(pszMapFname);
+    pszMapFname = NULL;
+  } else {
+    /* -------------------------------------------------------------------- */
+    /*      map file name may not be avaible when the template functions    */
+    /*      are called from mapscript. Use the time stamp as prefix.        */
+    /* -------------------------------------------------------------------- */
+    char pszTime[20];
+
+    snprintf(pszTime, sizeof(pszTime), "%ld", (long)time(NULL));
+    pszPrefix = msStringConcatenate(pszPrefix, pszTime);
+  }
+
+  /* open template */
+  if((stream = fopen(msBuildPath(szPath, mapserv->map->mappath, mapserv->map->legend.template), "r")) == NULL) {
+    msSetError(MS_IOERR, "Error while opening template file.", "generateLegendTemplate()");
+    return NULL;
+  }
+
+  fseek(stream, 0, SEEK_END);
+  length = ftell(stream);
+  rewind(stream);
+
+  file = (char*)msSmallMalloc(length + 1);
+
+  if(!file) {
+    msSetError(MS_IOERR, "Error while allocating memory for template file.", "generateLegendTemplate()");
+    fclose(stream);
+    return NULL;
+  }
+
+  /*
+   * Read all the template file
+   */
+  fread(file, length, 1, stream);
+  /* Disabled for now due to Windows issue, see ticket #3814
+     if( 1 != fread(file, length, 1, stream)) {
+       msSetError(MS_IOERR, "Error while reading template file.", "generateLegendTemplate()");
+       free(file);
+       fclose(stream);
+       return NULL;
+     }
+  */
+  file[length] = '\0';
+
+  if(msValidateContexts(mapserv->map) != MS_SUCCESS) return NULL; /* make sure there are no recursive REQUIRES or LABELREQUIRES expressions */
+
+  /*
+   * Seperate header/footer, groups, layers and class
+   */
+  getInlineTag("leg_header_html", file, &legHeaderHtml);
+  getInlineTag("leg_footer_html", file, &legFooterHtml);
+  getInlineTag("leg_group_html", file, &legGroupHtml);
+  getInlineTag("leg_layer_html", file, &legLayerHtml);
+  getInlineTag("leg_class_html", file, &legClassHtml);
+
+  /*
+   * Retrieve arguments of all three parts
+   */
+  if(legGroupHtml)
+    if(getTagArgs("leg_group_html", file, &groupArgs) != MS_SUCCESS)
+      return NULL;
+
+  if(legLayerHtml)
+    if(getTagArgs("leg_layer_html", file, &layerArgs) != MS_SUCCESS)
+      return NULL;
+
+  if(legClassHtml)
+    if(getTagArgs("leg_class_html", file, &classArgs) != MS_SUCCESS)
+      return NULL;
+
+
+  mapserv->map->cellsize = msAdjustExtent(&(mapserv->map->extent),
+                                          mapserv->map->width,
+                                          mapserv->map->height);
+  if(msCalculateScale(mapserv->map->extent, mapserv->map->units,
+                      mapserv->map->width, mapserv->map->height,
+                      mapserv->map->resolution, &mapserv->map->scaledenom) != MS_SUCCESS)
+    return(NULL);
+
+  /* start with the header if present */
+  if(legHeaderHtml) pszResult = msStringConcatenate(pszResult, legHeaderHtml);
+
+  /********************************************************************/
+
+  /*
+   * order layers if order_metadata args is set
+   * If not, keep default order
+   */
+  pszOrderMetadata = msLookupHashTable(layerArgs, "order_metadata");
+
+  if(sortLayerByMetadata(mapserv->map, pszOrderMetadata) != MS_SUCCESS)
+    goto error;
+
+  /* -------------------------------------------------------------------- */
+  /*      if the order tag is set to ascending or descending, the         */
+  /*      current order will be changed to correspond to that.            */
+  /* -------------------------------------------------------------------- */
+  pszOrder = msLookupHashTable(layerArgs, "order");
+  if(pszOrder && ((strcasecmp(pszOrder, "ASCENDING") == 0) ||
+                  (strcasecmp(pszOrder, "DESCENDING") == 0))) {
+    if(sortLayerByOrder(mapserv->map, pszOrder) != MS_SUCCESS)
+      goto error;
+  }
+
+  if(legGroupHtml) {
+    /* retrieve group names */
+    papszGroups = msGetAllGroupNames(mapserv->map, &nGroupNames);
+
+    for (i=0; i<nGroupNames; i++) {
+      /* process group tags */
+      if(generateGroupTemplate(legGroupHtml, mapserv->map, papszGroups[i], groupArgs, &legGroupHtmlCopy, pszPrefix) != MS_SUCCESS) {
+        if(pszResult)
+          free(pszResult);
+        pszResult=NULL;
+        goto error;
+      }
+
+      /* concatenate it to final result */
+      pszResult = msStringConcatenate(pszResult, legGroupHtmlCopy);
+
+      /*
+               if(!pszResult)
+               {
+                  if(pszResult)
+                    free(pszResult);
+                  pszResult=NULL;
+                  goto error;
+               }
+      */
+
+      if(legGroupHtmlCopy) {
+        free(legGroupHtmlCopy);
+        legGroupHtmlCopy = NULL;
+      }
+
+      /* for all layers in group */
+      if(legLayerHtml) {
+        for (j=0; j<mapserv->map->numlayers; j++) {
+          /*
+           * if order_metadata is set and the order
+           * value is less than 0, dont display it
+           */
+          pszOrderMetadata = msLookupHashTable(layerArgs, "order_metadata");
+          if(pszOrderMetadata) {
+            pszOrderValue = msLookupHashTable(&(GET_LAYER(mapserv->map, mapserv->map->layerorder[j])->metadata), pszOrderMetadata);
+            if(pszOrderValue) {
+              nLegendOrder = atoi(pszOrderValue);
+              if(nLegendOrder < 0)
+                continue;
+            }
+          }
 
-      /* if no specified width or height, set them to map default */
-      if(!msLookupHashTable(myHashTable, "width") || !msLookupHashTable(myHashTable, "height")) {
-         nWidth = map->legend.keysizex;
-         nHeight= map->legend.keysizey;
-      }
-      else {
-         nWidth  = atoi(msLookupHashTable(myHashTable, "width"));
-         nHeight = atoi(msLookupHashTable(myHashTable, "height"));
-      }
+          if(GET_LAYER(mapserv->map, mapserv->map->layerorder[j])->group && strcmp(GET_LAYER(mapserv->map, mapserv->map->layerorder[j])->group, papszGroups[i]) == 0) {
+            /* process all layer tags */
+            if(generateLayerTemplate(legLayerHtml, mapserv->map, mapserv->map->layerorder[j], layerArgs, &legLayerHtmlCopy, pszPrefix) != MS_SUCCESS) {
+              if(pszResult)
+                free(pszResult);
+              pszResult=NULL;
+              goto error;
+            }
 
-      /* Create a unique and predictable filename to cache the legend icons.
-       * Include some key parameters from the first 2 styles 
-       */
-      for(i=0; i<2 && thisClass && i<thisClass->numstyles; i++) {
-          styleObj *style;
-          char *pszSymbolNameHash = NULL;
-          style = thisClass->styles[i];
-          if(style->symbolname)
-              pszSymbolNameHash = msHashString(style->symbolname);
-
-          snprintf(szStyleCode+strlen(szStyleCode), 255,
-                   "s%d_%x_%x_%x_%d_%s_%g",
-                   i, MS_COLOR_GETRGB(style->color), MS_COLOR_GETRGB(style->backgroundcolor), MS_COLOR_GETRGB(style->outlinecolor),
-                   style->symbol, pszSymbolNameHash?pszSymbolNameHash:"", 
-                   style->angle);
-          msFree(pszSymbolNameHash);
-      }
 
-      snprintf(szImgFname, sizeof(szImgFname), "%s_%d_%d_%d_%d_%s.%s%c", 
-               pszPrefix, nIdxLayer, nIdxClass, nWidth, nHeight, 
-               szStyleCode, MS_IMAGE_EXTENSION(map->outputformat),'\0');
+            /* concatenate to final result */
+            pszResult = msStringConcatenate(pszResult, legLayerHtmlCopy);
 
-      pszFullImgFname = msStrdup(msBuildPath3(szPath, map->mappath, 
-                                            map->web.imagepath, szImgFname));
-      
-      /* check if icon already exist in cache */
-      if((fIcon = fopen(pszFullImgFname, "r")) != NULL)
-      {
-         /* File already exists. No need to generate it again */
-         fclose(fIcon);
-      }
-      else
-      {
-         /* Create an image corresponding to the current class */
-          imageObj *img=NULL;
-
-         if(thisClass == NULL)
-         {
-             /* Nonexistent class.  Create an empty image */
-             img = msCreateLegendIcon(map, NULL, NULL, nWidth, nHeight);
-         }
-         else
-         {
-            img = msCreateLegendIcon(map, GET_LAYER(map, nIdxLayer), 
-                                     thisClass, nWidth, nHeight);
-         }
-
-         if(!img) {
-            if(myHashTable)
-              msFreeHashTable(myHashTable);
-
-            msSetError(MS_GDERR, "Error while creating GD image.", "processIcon()");
-            return MS_FAILURE;
-         }
-         
-         /* save it with a unique file name */
-         if(msSaveImage(map, img, pszFullImgFname) != MS_SUCCESS) {
-            if(myHashTable)
-              msFreeHashTable(myHashTable);
-
-            msFree(pszFullImgFname);
-            msFreeImage(img);
-
-            msSetError(MS_IOERR, "Error saving GD image to disk (%s).", "processIcon()", pszFullImgFname);
-            return MS_FAILURE;
-         }
-         
-         msFreeImage(img);
-      }
+            if(legLayerHtmlCopy) {
+              free(legLayerHtmlCopy);
+              legLayerHtmlCopy = NULL;
+            }
 
-      msFree(pszFullImgFname);
-      pszFullImgFname = NULL;
 
-      nLen = (strchr(pszImgTag, ']') + 1) - pszImgTag;
-   
-      if(nLen > 0) {
-         char *pszTag;
+            /* for all classes in layer */
+            if(legClassHtml) {
+              for (k=0; k<GET_LAYER(mapserv->map, mapserv->map->layerorder[j])->numclasses; k++) {
+                /* process all class tags */
+                if(!GET_LAYER(mapserv->map, mapserv->map->layerorder[j])->class[k]->name)
+                  continue;
+
+                if(generateClassTemplate(legClassHtml, mapserv->map, mapserv->map->layerorder[j], k, classArgs, &legClassHtmlCopy, pszPrefix) != MS_SUCCESS) {
+                  if(pszResult)
+                    free(pszResult);
+                  pszResult=NULL;
+                  goto error;
+                }
 
-         /* rebuid image tag ([leg_class_img all_args]) */
-         /* to replace it by the image url */
-         pszTag = (char*)msSmallMalloc(nLen + 1);
-         strlcpy(pszTag, pszImgTag, nLen+1);
 
-         pszFullImgFname = (char*)msSmallMalloc(strlen(map->web.imageurl) + strlen(szImgFname) + 1);
-         strcpy(pszFullImgFname, map->web.imageurl);
-         strcat(pszFullImgFname, szImgFname);
+                /* concatenate to final result */
+                pszResult = msStringConcatenate(pszResult, legClassHtmlCopy);
 
-         *pszInstr = msReplaceSubstring(*pszInstr, pszTag, pszFullImgFname);
+                if(legClassHtmlCopy) {
+                  free(legClassHtmlCopy);
+                  legClassHtmlCopy = NULL;
+                }
+              }
+            }
+          }
+        }
+      } else if(legClassHtml) { /* no layer template specified but class and group template */
+        for (j=0; j<mapserv->map->numlayers; j++) {
+          /*
+           * if order_metadata is set and the order
+           * value is less than 0, dont display it
+           */
+          pszOrderMetadata = msLookupHashTable(layerArgs, "order_metadata");
+          if(pszOrderMetadata) {
+            pszOrderValue = msLookupHashTable(&(GET_LAYER(mapserv->map, mapserv->map->layerorder[j])->metadata), pszOrderMetadata);
+            if(pszOrderValue) {
+              nLegendOrder = atoi(pszOrderValue);
+              if(nLegendOrder < 0)
+                continue;
+            }
+          }
 
-         msFree(pszFullImgFname);
-         pszFullImgFname = NULL;
-         msFree(pszTag);
+          if(GET_LAYER(mapserv->map, mapserv->map->layerorder[j])->group && strcmp(GET_LAYER(mapserv->map, mapserv->map->layerorder[j])->group, papszGroups[i]) == 0) {
+            /* for all classes in layer */
+            if(legClassHtml) {
+              for (k=0; k<GET_LAYER(mapserv->map, mapserv->map->layerorder[j])->numclasses; k++) {
+                /* process all class tags */
+                if(!GET_LAYER(mapserv->map, mapserv->map->layerorder[j])->class[k]->name)
+                  continue;
+
+                if(generateClassTemplate(legClassHtml, mapserv->map, mapserv->map->layerorder[j], k, classArgs, &legClassHtmlCopy, pszPrefix) != MS_SUCCESS) {
+                  if(pszResult)
+                    free(pszResult);
+                  pszResult=NULL;
+                  goto error;
+                }
 
-         /* find the begining of tag */
-         pszImgTag = strstr(*pszInstr, "[leg_icon");
-      }
-      else {
-         pszImgTag = NULL;
-      }
-      
-      if(myHashTable)
-      {
-         msFreeHashTable(myHashTable);
-         myHashTable = NULL;
-      }
-   }
 
-   return MS_SUCCESS;
-}
+                /* concatenate to final result */
+                pszResult = msStringConcatenate(pszResult, legClassHtmlCopy);
 
-/*!
- * Replace all tags from group template
- * with correct value.
- * 
- * this function return a buffer containing
- * the template with correct values.
- * 
- * buffer must be freed by caller.
-*/
-int generateGroupTemplate(char* pszGroupTemplate, mapObj *map, char* pszGroupName, hashTableObj *oGroupArgs, char **pszTemp, char* pszPrefix)
-{
-   hashTableObj *myHashTable;
-   char pszStatus[3];   
-   char *pszClassImg;
-   char *pszOptFlag = NULL;
-   int i, j;
-   int nOptFlag = 15;
-   int bShowGroup;
-
-   *pszTemp = NULL;
-   
-   if(!pszGroupName || !pszGroupTemplate) {
-     msSetError(MS_WEBERR, "Invalid pointer.", "generateGroupTemplate()");
-     return MS_FAILURE;
-   }
-
-   /*
-    * Get the opt_flag is any.
-    */
-   if(oGroupArgs)
-       pszOptFlag = msLookupHashTable(oGroupArgs, "opt_flag");
+                if(legClassHtmlCopy) {
+                  free(legClassHtmlCopy);
+                  legClassHtmlCopy = NULL;
+                }
+              }
+            }
+          }
+        }
+      }
+    }
+  } else {
+    /* if no group template specified */
+    if(legLayerHtml) {
+      for (j=0; j<mapserv->map->numlayers; j++) {
+        /*
+         * if order_metadata is set and the order
+         * value is less than 0, dont display it
+         */
+        pszOrderMetadata = msLookupHashTable(layerArgs, "order_metadata");
+        if(pszOrderMetadata) {
+          pszOrderValue = msLookupHashTable(&(GET_LAYER(mapserv->map, mapserv->map->layerorder[j])->metadata), pszOrderMetadata);
+          if(pszOrderValue) {
+            nLegendOrder = atoi(pszOrderValue);
+            if(nLegendOrder < 0)
+              continue;
+          } else
+            nLegendOrder=0;
+        }
 
-   if(pszOptFlag)
-       nOptFlag = atoi(pszOptFlag);
+        /* process a layer tags */
+        if(generateLayerTemplate(legLayerHtml, mapserv->map, mapserv->map->layerorder[j], layerArgs, &legLayerHtmlCopy, pszPrefix) != MS_SUCCESS) {
+          if(pszResult)
+            free(pszResult);
+          pszResult=NULL;
+          goto error;
+        }
 
-   /*
-    * Check all layers, if one in the group
-    * should be visible, print the group.
-    * (Check for opt_flag)
-    */
-   bShowGroup = 0;
-   for (j=0; j<map->numlayers; j++)
-   {
-       if(GET_LAYER(map, map->layerorder[j])->group && 
-           strcmp(GET_LAYER(map, map->layerorder[j])->group, pszGroupName) == 0)
-       {
-           /* dont display layer is off. */
-           if( (nOptFlag & 2) == 0 && 
-               GET_LAYER(map, map->layerorder[j])->status == MS_OFF )
-               bShowGroup = 0;
-           else
-               bShowGroup = 1;
-
-           /* dont display layer is query. */
-           if( (nOptFlag & 4) == 0  && 
-               GET_LAYER(map, map->layerorder[j])->type == MS_LAYER_QUERY )
-               bShowGroup = 0;
-
-           /* dont display layer is annotation. */
-           if( (nOptFlag & 8) == 0 && 
-               GET_LAYER(map, map->layerorder[j])->type == MS_LAYER_ANNOTATION )
-               bShowGroup = 0;
-               
-
-           /* dont display layer if out of scale. */
-           if((nOptFlag & 1) == 0)
-           {
-               if(map->scaledenom > 0) {
-                   if((GET_LAYER(map, map->layerorder[j])->maxscaledenom > 0) && 
-                      (map->scaledenom > GET_LAYER(map, map->layerorder[j])->maxscaledenom))
-                       bShowGroup = 0;
-                   if((GET_LAYER(map, map->layerorder[j])->minscaledenom > 0) && 
-                      (map->scaledenom <= GET_LAYER(map, map->layerorder[j])->minscaledenom))
-                       bShowGroup = 0;
-               }
-           }
-
-           /* The group contains one visible layer */
-           /* Draw the group */
-           if( bShowGroup )
-               break;
-       }
-   }
-
-   if( ! bShowGroup )
-       return MS_SUCCESS;
-   
-   /*
-    * Work from a copy
-    */
-   *pszTemp = (char*)msSmallMalloc(strlen(pszGroupTemplate) + 1);
-   strcpy(*pszTemp, pszGroupTemplate);
-         
-   /*
-    * Change group tags
-    */
-   *pszTemp = msReplaceSubstring(*pszTemp, "[leg_group_name]", pszGroupName);
+        /* concatenate to final result */
+        pszResult = msStringConcatenate(pszResult, legLayerHtmlCopy);
 
-   
-   /*
-    * Create a hash table that contain info
-    * on current layer
-    */
-   myHashTable = msCreateHashTable();
+        if(legLayerHtmlCopy) {
+          free(legLayerHtmlCopy);
+          legLayerHtmlCopy = NULL;
+        }
 
-   /*
-    * Check for the first layer
-    * that belong to this group.
-    * Get his status and check for if.
-    */
-   for (j=0; j<map->numlayers; j++)
-   {
-      if(GET_LAYER(map, map->layerorder[j])->group && strcmp(GET_LAYER(map, map->layerorder[j])->group, pszGroupName) == 0)
-      {
-         snprintf(pszStatus, sizeof(pszStatus), "%d", GET_LAYER(map, map->layerorder[j])->status);
-         msInsertHashTable(myHashTable, "layer_status", pszStatus);
-         msInsertHashTable(myHashTable, "layer_visible", msLayerIsVisible(map, GET_LAYER(map, map->layerorder[j]))?"1":"0" );
-         msInsertHashTable(myHashTable, "layer_queryable", msIsLayerQueryable(GET_LAYER(map, map->layerorder[j]))?"1":"0" );
-         msInsertHashTable(myHashTable, "group_name", pszGroupName);
-
-         if(processIfTag(pszTemp, myHashTable, MS_FALSE) != MS_SUCCESS)
-           return MS_FAILURE;
-         
-         if(processIfTag(pszTemp, &(GET_LAYER(map, map->layerorder[j])->metadata), MS_FALSE) != MS_SUCCESS)
-           return MS_FAILURE;
-
-         if(processMetadata(pszTemp, &GET_LAYER(map, map->layerorder[j])->metadata) != MS_SUCCESS)
-           return MS_FAILURE;
-
-         break;
-      }
-   }
-  
-   msFreeHashTable(myHashTable);
+        /* for all classes in layer */
+        if(legClassHtml) {
+          for (k=0; k<GET_LAYER(mapserv->map, mapserv->map->layerorder[j])->numclasses; k++) {
+            /* process all class tags */
+            if(!GET_LAYER(mapserv->map, mapserv->map->layerorder[j])->class[k]->name)
+              continue;
+
+            if(generateClassTemplate(legClassHtml, mapserv->map, mapserv->map->layerorder[j], k, classArgs, &legClassHtmlCopy, pszPrefix) != MS_SUCCESS) {
+              if(pszResult)
+                free(pszResult);
+              pszResult=NULL;
+              goto error;
+            }
 
-   /*
-    * Process all metadata tags
-    * only web object is accessible
-   */
-   if(processMetadata(pszTemp, &(map->web.metadata)) != MS_SUCCESS)
-     return MS_FAILURE;
-   
-   /*
-    * check for if tag
-   */
-   if(processIfTag(pszTemp, &(map->web.metadata), MS_TRUE) != MS_SUCCESS)
-     return MS_FAILURE;
-   
-   /*
-    * Check if leg_icon tag exist
-    * if so display the first layer first class icon
-    */
-   pszClassImg = strstr(*pszTemp, "[leg_icon");
-   if(pszClassImg) {
-      /* find first layer of this group */
-      for (i=0; i<map->numlayers; i++)
-        if(GET_LAYER(map, map->layerorder[i])->group && strcmp(GET_LAYER(map, map->layerorder[i])->group, pszGroupName) == 0)
-          processIcon(map, map->layerorder[i], 0, pszTemp, pszPrefix);
-   }      
-      
-   return MS_SUCCESS;
-}
 
-/*!
- * Replace all tags from layer template
- * with correct value.
- * 
- * this function return a buffer containing
- * the template with correct values.
- * 
- * buffer must be freed by caller.
-*/
-int generateLayerTemplate(char *pszLayerTemplate, mapObj *map, int nIdxLayer, hashTableObj *oLayerArgs, char **pszTemp, char* pszPrefix)
-{
-   hashTableObj *myHashTable;
-   char szStatus[10];
-   char szType[10];
-   
-   int nOptFlag=0;
-   char *pszOptFlag = NULL;
-   char *pszClassImg;
-
-   char szTmpstr[128]; /* easily big enough for the couple of instances we need */
-
-   *pszTemp = NULL;
-   
-   if(!pszLayerTemplate || 
-       !map || 
-       nIdxLayer > map->numlayers ||
-       nIdxLayer < 0 ) {
-     msSetError(MS_WEBERR, "Invalid pointer.", "generateLayerTemplate()");
-     return MS_FAILURE;
-   }
-
-   if(oLayerArgs)
-       pszOptFlag = msLookupHashTable(oLayerArgs, "opt_flag");
-
-   if(pszOptFlag)
-     nOptFlag = atoi(pszOptFlag);
-
-   /* don't display deleted layers */
-   if(GET_LAYER(map, nIdxLayer)->status == MS_DELETE)
-     return MS_SUCCESS;
-
-   /* dont display layer is off. */
-   /* check this if Opt flag is not set */
-   if((nOptFlag & 2) == 0 && GET_LAYER(map, nIdxLayer)->status == MS_OFF)
-     return MS_SUCCESS;
-
-   /* dont display layer is query. */
-   /* check this if Opt flag is not set */
-   if((nOptFlag & 4) == 0  && GET_LAYER(map, nIdxLayer)->type == MS_LAYER_QUERY)
-     return MS_SUCCESS;
-
-   /* dont display layer is annotation. */
-   /* check this if Opt flag is not set       */
-   if((nOptFlag & 8) == 0 && GET_LAYER(map, nIdxLayer)->type == MS_LAYER_ANNOTATION)
-     return MS_SUCCESS;      
-
-   /* dont display layer if out of scale. */
-   /* check this if Opt flag is not set             */
-   if((nOptFlag & 1) == 0) {
-      if(map->scaledenom > 0) {
-         if((GET_LAYER(map, nIdxLayer)->maxscaledenom > 0) && (map->scaledenom > GET_LAYER(map, nIdxLayer)->maxscaledenom))
-           return MS_SUCCESS;
-         if((GET_LAYER(map, nIdxLayer)->minscaledenom > 0) && (map->scaledenom <= GET_LAYER(map, nIdxLayer)->minscaledenom))
-           return MS_SUCCESS;
+            /* concatenate to final result */
+            pszResult = msStringConcatenate(pszResult, legClassHtmlCopy);
+
+            if(legClassHtmlCopy) {
+              free(legClassHtmlCopy);
+              legClassHtmlCopy = NULL;
+            }
+          }
+        }
       }
-   }
+    } else { /* if no group and layer template specified */
+      if(legClassHtml) {
+        for (j=0; j<mapserv->map->numlayers; j++) {
+          /*
+           * if order_metadata is set and the order
+           * value is less than 0, dont display it
+           */
+          pszOrderMetadata = msLookupHashTable(layerArgs, "order_metadata");
+          if(pszOrderMetadata) {
+            pszOrderValue = msLookupHashTable(&(GET_LAYER(mapserv->map, mapserv->map->layerorder[j])->metadata), pszOrderMetadata);
+            if(pszOrderValue) {
+              nLegendOrder = atoi(pszOrderValue);
+              if(nLegendOrder < 0)
+                continue;
+            }
+          }
 
-   /*
-    * Work from a copy
-    */
-   *pszTemp = msStrdup(pszLayerTemplate);
+          for (k=0; k<GET_LAYER(mapserv->map, mapserv->map->layerorder[j])->numclasses; k++) {
+            if(!GET_LAYER(mapserv->map, mapserv->map->layerorder[j])->class[k]->name)
+              continue;
 
-   /*
-    * Change layer tags
-    */
-   *pszTemp = msReplaceSubstring(*pszTemp, "[leg_layer_name]", GET_LAYER(map, nIdxLayer)->name);
-   *pszTemp = msReplaceSubstring(*pszTemp, "[leg_layer_group]", GET_LAYER(map, nIdxLayer)->group);
-
-   snprintf(szTmpstr, sizeof(szTmpstr), "%d", nIdxLayer); 
-   *pszTemp = msReplaceSubstring(*pszTemp, "[leg_layer_index]", szTmpstr);
-
-   snprintf(szTmpstr, sizeof(szTmpstr), "%g", GET_LAYER(map, nIdxLayer)->minscaledenom); 
-   *pszTemp = msReplaceSubstring(*pszTemp, "[leg_layer_minscale]", szTmpstr);
-   *pszTemp = msReplaceSubstring(*pszTemp, "[leg_layer_minscaledenom]", szTmpstr);
-   snprintf(szTmpstr, sizeof(szTmpstr), "%g", GET_LAYER(map, nIdxLayer)->maxscaledenom); 
-   *pszTemp = msReplaceSubstring(*pszTemp, "[leg_layer_maxscale]", szTmpstr);
-   *pszTemp = msReplaceSubstring(*pszTemp, "[leg_layer_maxscaledenom]", szTmpstr);
-
-   /*
-    * Create a hash table that contain info
-    * on current layer
-    */
-   myHashTable = msCreateHashTable();
-   
-   /*
-    * for now, only status and type is required by template
-    */
-   snprintf(szStatus, sizeof(szStatus), "%d", GET_LAYER(map, nIdxLayer)->status);
-   msInsertHashTable(myHashTable, "layer_status", szStatus);
+            if(generateClassTemplate(legClassHtml, mapserv->map, mapserv->map->layerorder[j], k, classArgs, &legClassHtmlCopy, pszPrefix) != MS_SUCCESS) {
+              if(pszResult)
+                free(pszResult);
+              pszResult=NULL;
+              goto error;
+            }
 
-   snprintf(szType, sizeof(szType), "%d", GET_LAYER(map, nIdxLayer)->type);
-   msInsertHashTable(myHashTable, "layer_type", szType);
 
-   msInsertHashTable(myHashTable, "layer_name", (GET_LAYER(map, nIdxLayer)->name)? GET_LAYER(map, nIdxLayer)->name : "");
-   msInsertHashTable(myHashTable, "layer_group", (GET_LAYER(map, nIdxLayer)->group)? GET_LAYER(map, nIdxLayer)->group : "");
-   msInsertHashTable(myHashTable, "layer_visible", msLayerIsVisible(map, GET_LAYER(map, nIdxLayer))?"1":"0" );
-   msInsertHashTable(myHashTable, "layer_queryable", msIsLayerQueryable(GET_LAYER(map, nIdxLayer))?"1":"0" );
+            pszResult = msStringConcatenate(pszResult, legClassHtmlCopy);
 
-   if(processIfTag(pszTemp, myHashTable, MS_FALSE) != MS_SUCCESS)
-      return MS_FAILURE;
-   
-   if(processIfTag(pszTemp, &(GET_LAYER(map, nIdxLayer)->metadata), MS_FALSE) != MS_SUCCESS)
-      return MS_FAILURE;
-   
-   if(processIfTag(pszTemp, &(map->web.metadata), MS_TRUE) != MS_SUCCESS)
-      return MS_FAILURE;
+            if(legClassHtmlCopy) {
+              free(legClassHtmlCopy);
+              legClassHtmlCopy = NULL;
+            }
+          }
+        }
+      }
+    }
+  }
 
-   msFreeHashTable(myHashTable);
-   
-   /*
-    * Check if leg_icon tag exist
-    * if so display the first class icon
-    */
-   pszClassImg = strstr(*pszTemp, "[leg_icon");
-   if(pszClassImg) {
-      processIcon(map, nIdxLayer, 0, pszTemp, pszPrefix);
-   }      
-
-   /* process all metadata tags
-    * only current layer and web object
-    * metaddata are accessible
+  /* finish with the footer if present */
+  if(legFooterHtml) pszResult = msStringConcatenate(pszResult, legFooterHtml);
+
+  /*
+   * if we reach this point, that mean no error was generated.
+   * So check if template is null and initialize it to <space>.
    */
-   if(processMetadata(pszTemp, &GET_LAYER(map, nIdxLayer)->metadata) != MS_SUCCESS)
-      return MS_FAILURE;
+  if(pszResult == NULL) {
+    pszResult = msStringConcatenate(pszResult, " ");
+  }
 
-   if(processMetadata(pszTemp, &(map->web.metadata)) != MS_SUCCESS)
-      return MS_FAILURE;      
-   
-   return MS_SUCCESS;
-}
 
-/*!
- * Replace all tags from class template
- * with correct value.
- * 
- * this function return a buffer containing
- * the template with correct values.
- * 
- * buffer must be freed by caller.
-*/
-int generateClassTemplate(char* pszClassTemplate, mapObj *map, int nIdxLayer, int nIdxClass, hashTableObj *oClassArgs, char **pszTemp, char* pszPrefix)
-{
-   hashTableObj *myHashTable;
-   char szStatus[10];
-   char szType[10];
-   
-   char *pszClassImg;
-   int nOptFlag=0;
-   char *pszOptFlag = NULL;
-
-   char szTmpstr[128]; /* easily big enough for the couple of instances we need */
-
-   *pszTemp = NULL;
-   
-   if(!pszClassTemplate ||
-       !map || 
-       nIdxLayer > map->numlayers ||
-       nIdxLayer < 0 ||
-       nIdxClass > GET_LAYER(map, nIdxLayer)->numclasses ||
-       nIdxClass < 0) {
-        
-     msSetError(MS_WEBERR, "Invalid pointer.", "generateClassTemplate()");
-     return MS_FAILURE;
-   }
-
-   if(oClassArgs)
-     pszOptFlag = msLookupHashTable(oClassArgs, "Opt_flag");
-
-   if(pszOptFlag)
-     nOptFlag = atoi(pszOptFlag);
-      
-   /* don't display deleted layers */
-   if(GET_LAYER(map, nIdxLayer)->status == MS_DELETE)
-     return MS_SUCCESS;
-
-   /* dont display class if layer is off. */
-   /* check this if Opt flag is not set */
-   if((nOptFlag & 2) == 0 && GET_LAYER(map, nIdxLayer)->status == MS_OFF)
-     return MS_SUCCESS;
-
-   /* dont display class if layer is query. */
-   /* check this if Opt flag is not set       */
-   if((nOptFlag & 4) == 0 && GET_LAYER(map, nIdxLayer)->type == MS_LAYER_QUERY)
-     return MS_SUCCESS;
-      
-   /* dont display class if layer is annotation. */
-   /* check this if Opt flag is not set       */
-   if((nOptFlag & 8) == 0 && GET_LAYER(map, nIdxLayer)->type == MS_LAYER_ANNOTATION)
-     return MS_SUCCESS;
-      
-   /* dont display layer if out of scale. */
-   /* check this if Opt flag is not set */
-   if((nOptFlag & 1) == 0) {
-      if(map->scaledenom > 0) {
-         if((GET_LAYER(map, nIdxLayer)->maxscaledenom > 0) && (map->scaledenom > GET_LAYER(map, nIdxLayer)->maxscaledenom))
-           return MS_SUCCESS;
-         if((GET_LAYER(map, nIdxLayer)->minscaledenom > 0) && (map->scaledenom <= GET_LAYER(map, nIdxLayer)->minscaledenom))
-           return MS_SUCCESS;
-      }
-   }
-      
-   /*
-    * Work from a copy
-    */
-   *pszTemp = (char*)msSmallMalloc(strlen(pszClassTemplate) + 1);
-   strcpy(*pszTemp, pszClassTemplate);
-         
-   /*
-    * Change class tags
-    */
-   *pszTemp = msReplaceSubstring(*pszTemp, "[leg_class_name]", GET_LAYER(map, nIdxLayer)->class[nIdxClass]->name);
-   *pszTemp = msReplaceSubstring(*pszTemp, "[leg_class_title]", GET_LAYER(map, nIdxLayer)->class[nIdxClass]->title);
-   *pszTemp = msReplaceSubstring(*pszTemp, "[leg_layer_name]", GET_LAYER(map, nIdxLayer)->name);
-
-   snprintf(szTmpstr, sizeof(szTmpstr), "%d", nIdxClass); 
-   *pszTemp = msReplaceSubstring(*pszTemp, "[leg_class_index]", szTmpstr);
-
-   snprintf(szTmpstr, sizeof(szTmpstr), "%g", GET_LAYER(map, nIdxLayer)->class[nIdxClass]->minscaledenom); 
-   *pszTemp = msReplaceSubstring(*pszTemp, "[leg_class_minscale]", szTmpstr);
-   *pszTemp = msReplaceSubstring(*pszTemp, "[leg_class_minscaledenom]", szTmpstr);
-   snprintf(szTmpstr, sizeof(szTmpstr), "%g", GET_LAYER(map, nIdxLayer)->class[nIdxClass]->maxscaledenom); 
-   *pszTemp = msReplaceSubstring(*pszTemp, "[leg_class_maxscale]", szTmpstr);
-   *pszTemp = msReplaceSubstring(*pszTemp, "[leg_class_maxscaledenom]", szTmpstr);
-
-   /*
-    * Create a hash table that contain info
-    * on current layer
-    */
-   myHashTable = msCreateHashTable();
-   
-   /*
-    * for now, only status, type, name and group are  required by template
-    */
-   snprintf(szStatus, sizeof(szStatus), "%d", GET_LAYER(map, nIdxLayer)->status);
-   msInsertHashTable(myHashTable, "layer_status", szStatus);
-
-   snprintf(szType, sizeof(szType), "%d", GET_LAYER(map, nIdxLayer)->type);
-   msInsertHashTable(myHashTable, "layer_type", szType);   
-   
-   msInsertHashTable(myHashTable, "layer_name", 
-     (GET_LAYER(map, nIdxLayer)->name)? GET_LAYER(map, nIdxLayer)->name : "");
-   msInsertHashTable(myHashTable, "layer_group", 
-     (GET_LAYER(map, nIdxLayer)->group)? GET_LAYER(map, nIdxLayer)->group : "");
-   msInsertHashTable(myHashTable, "layer_visible", msLayerIsVisible(map, GET_LAYER(map, nIdxLayer))?"1":"0" );
-   msInsertHashTable(myHashTable, "layer_queryable", msIsLayerQueryable(GET_LAYER(map, nIdxLayer))?"1":"0" );
-   msInsertHashTable(myHashTable, "class_name", 
-     (GET_LAYER(map, nIdxLayer)->class[nIdxClass]->name)? GET_LAYER(map, nIdxLayer)->class[nIdxClass]->name : "");
-
-   if(processIfTag(pszTemp, myHashTable, MS_FALSE) != MS_SUCCESS)
-      return MS_FAILURE;
-   
-   if(processIfTag(pszTemp, &(GET_LAYER(map, nIdxLayer)->metadata), MS_FALSE) != MS_SUCCESS)
-      return MS_FAILURE;
-   
-   if(processIfTag(pszTemp, &(map->web.metadata), MS_TRUE) != MS_SUCCESS)
-      return MS_FAILURE;
+  /********************************************************************/
 
-   msFreeHashTable(myHashTable);   
-      
-   /*
-    * Check if leg_icon tag exist
-    */
-   pszClassImg = strstr(*pszTemp, "[leg_icon");
-   if(pszClassImg) {
-      processIcon(map, nIdxLayer, nIdxClass, pszTemp, pszPrefix);
-   }
-
-   /* process all metadata tags
-    * only current layer and web object
-    * metaddata are accessible
-   */
-   if(processMetadata(pszTemp, &GET_LAYER(map, nIdxLayer)->metadata) != MS_SUCCESS)
-      return MS_FAILURE;
-   
-   if(processMetadata(pszTemp, &(map->web.metadata)) != MS_SUCCESS)
-      return MS_FAILURE;      
-   
-   return MS_SUCCESS;
-}
+error:
 
-char *generateLegendTemplate(mapservObj *mapserv)
-{
-   FILE *stream;
-   char *file = NULL;
-   int length;
-   char *pszResult = NULL;
-   char *legGroupHtml = NULL;
-   char *legLayerHtml = NULL;
-   char *legClassHtml = NULL;
-   char *legLayerHtmlCopy = NULL;
-   char *legClassHtmlCopy = NULL;
-   char *legGroupHtmlCopy = NULL;
-   
-   char *legHeaderHtml = NULL;
-   char *legFooterHtml = NULL;
-
-   char *pszPrefix = NULL;
-   char *pszMapFname = NULL;
-   
-   struct stat tmpStat;
-   
-   char *pszOrderMetadata = NULL;
-   char *pszOrder = NULL;
-   
-   int i,j,k;
-   char **papszGroups = NULL;
-   int nGroupNames = 0;
-
-   int nLegendOrder = 0;
-   char *pszOrderValue;
-     
-   hashTableObj *groupArgs = NULL;
-   hashTableObj *layerArgs = NULL;
-   hashTableObj *classArgs = NULL;     
-
-   ms_regex_t re; /* compiled regular expression to be matched */ 
-
-   int  *panCurrentDrawingOrder = NULL;
-   char szPath[MS_MAXPATHLEN];
-
-   if(ms_regcomp(&re, MS_TEMPLATE_EXPR, MS_REG_EXTENDED|MS_REG_NOSUB) != 0) {
-      msSetError(MS_IOERR, "Error regcomp.", "generateLegendTemplate()");      
-      return NULL;
-   }
-
-   if(ms_regexec(&re, mapserv->map->legend.template, 0, NULL, 0) != 0) { /* no match */
-      msSetError(MS_IOERR, "Invalid template file name.", "generateLegendTemplate()");      
-     ms_regfree(&re);
-     return NULL;
-   }
-   ms_regfree(&re);
-
-/* -------------------------------------------------------------------- */
-/*      Save the current drawing order. The drawing order is reset      */
-/*      at the end of the function.                                     */
-/* -------------------------------------------------------------------- */
-   if(mapserv && mapserv->map && mapserv->map->numlayers > 0)
-   {
-       panCurrentDrawingOrder = 
-           (int *)msSmallMalloc(sizeof(int)*mapserv->map->numlayers); 
-      
-       for (i=0; i<mapserv->map->numlayers; i++)
-       {
-           if(mapserv->map->layerorder)
-               panCurrentDrawingOrder[i] = mapserv->map->layerorder[i];
-           else
-             panCurrentDrawingOrder[i] = i;  
-       }
-   }
-
-   /*
-    * build prefix filename
-    * for legend icon creation
-   */
-   for(i=0;i<mapserv->request->NumParams;i++) /* find the mapfile parameter first */
-     if(strcasecmp(mapserv->request->ParamNames[i], "map") == 0) break;
-  
-   if(i == mapserv->request->NumParams)
-   {
-       if( getenv("MS_MAPFILE"))
-           pszMapFname = msStringConcatenate(pszMapFname, getenv("MS_MAPFILE"));
-   }
-   else 
-   {
-      if(getenv(mapserv->request->ParamValues[i])) /* an environment references the actual file to use */
-        pszMapFname = msStringConcatenate(pszMapFname, getenv(mapserv->request->ParamValues[i]));
-      else
-        pszMapFname = msStringConcatenate(pszMapFname, mapserv->request->ParamValues[i]);
-   }
-   
-   if(pszMapFname)
-   {
-       if(stat(pszMapFname, &tmpStat) != -1)
-       {
-           int nLen;
-
-           nLen = (mapserv->map->name?strlen(mapserv->map->name):0)  + 50;
-           pszPrefix = (char*)msSmallMalloc((nLen+1) * sizeof(char));
-           snprintf(pszPrefix, nLen, "%s_%ld_%ld", 
-                    mapserv->map->name,
-                    (long) tmpStat.st_size, 
-                    (long) tmpStat.st_mtime);
-           pszPrefix[nLen] = '\0';
-       }
-   
-       free(pszMapFname);
-       pszMapFname = NULL;
-   }
-   else
-   {
-/* -------------------------------------------------------------------- */
-/*      map file name may not be avaible when the template functions    */
-/*      are called from mapscript. Use the time stamp as prefix.        */
-/* -------------------------------------------------------------------- */
-       char pszTime[20];
-       
-       snprintf(pszTime, sizeof(pszTime), "%ld", (long)time(NULL));      
-       pszPrefix = msStringConcatenate(pszPrefix, pszTime);
-   }
-
-       /* open template */
-   if((stream = fopen(msBuildPath(szPath, mapserv->map->mappath, mapserv->map->legend.template), "r")) == NULL) {
-      msSetError(MS_IOERR, "Error while opening template file.", "generateLegendTemplate()");
-      return NULL;
-   } 
-
-   fseek(stream, 0, SEEK_END);
-   length = ftell(stream);
-   rewind(stream);
-   
-   file = (char*)msSmallMalloc(length + 1);
-
-   if(!file) {
-     msSetError(MS_IOERR, "Error while allocating memory for template file.", "generateLegendTemplate()");
-     fclose(stream);
-     return NULL;
-   }
-   
-   /*
-    * Read all the template file
-    */
-   fread(file, length, 1, stream);
-/* Disabled for now due to Windows issue, see ticket #3814
-   if( 1 != fread(file, length, 1, stream)) {
-     msSetError(MS_IOERR, "Error while reading template file.", "generateLegendTemplate()");
-     free(file);
-     fclose(stream);
-     return NULL;
-   }
-*/
-   file[length] = '\0';
+  if(papszGroups) {
+    for (i=0; i<nGroupNames; i++)
+      msFree(papszGroups[i]);
 
-   if(msValidateContexts(mapserv->map) != MS_SUCCESS) return NULL; /* make sure there are no recursive REQUIRES or LABELREQUIRES expressions */
+    msFree(papszGroups);
+  }
 
-   /*
-    * Seperate header/footer, groups, layers and class
-    */
-   getInlineTag("leg_header_html", file, &legHeaderHtml);
-   getInlineTag("leg_footer_html", file, &legFooterHtml);
-   getInlineTag("leg_group_html", file, &legGroupHtml);
-   getInlineTag("leg_layer_html", file, &legLayerHtml);
-   getInlineTag("leg_class_html", file, &legClassHtml);
-   
-   /*
-    * Retrieve arguments of all three parts
-    */
-   if(legGroupHtml) 
-     if(getTagArgs("leg_group_html", file, &groupArgs) != MS_SUCCESS)
-       return NULL;
-   
-   if(legLayerHtml) 
-     if(getTagArgs("leg_layer_html", file, &layerArgs) != MS_SUCCESS)
-       return NULL;
-   
-   if(legClassHtml) 
-     if(getTagArgs("leg_class_html", file, &classArgs) != MS_SUCCESS)
-       return NULL;
+  msFreeHashTable(groupArgs);
+  msFreeHashTable(layerArgs);
+  msFreeHashTable(classArgs);
 
-      
-   mapserv->map->cellsize = msAdjustExtent(&(mapserv->map->extent), 
-                                         mapserv->map->width, 
-                                         mapserv->map->height);
-   if(msCalculateScale(mapserv->map->extent, mapserv->map->units, 
-                       mapserv->map->width, mapserv->map->height, 
-                       mapserv->map->resolution, &mapserv->map->scaledenom) != MS_SUCCESS)
-     return(NULL);
-   
-   /* start with the header if present */
-   if(legHeaderHtml) pszResult = msStringConcatenate(pszResult, legHeaderHtml);
-
-   /********************************************************************/
-
-   /*
-    * order layers if order_metadata args is set
-    * If not, keep default order
-    */
-   pszOrderMetadata = msLookupHashTable(layerArgs, "order_metadata");
-      
-   if(sortLayerByMetadata(mapserv->map, pszOrderMetadata) != MS_SUCCESS)
-     goto error;
-   
-/* -------------------------------------------------------------------- */
-/*      if the order tag is set to ascending or descending, the         */
-/*      current order will be changed to correspond to that.            */
-/* -------------------------------------------------------------------- */
-   pszOrder = msLookupHashTable(layerArgs, "order");
-   if(pszOrder && ((strcasecmp(pszOrder, "ASCENDING") == 0) ||
-                    (strcasecmp(pszOrder, "DESCENDING") == 0)))
-   {
-       if(sortLayerByOrder(mapserv->map, pszOrder) != MS_SUCCESS)
-         goto error;
-   }
-   
-   if(legGroupHtml) {
-      /* retrieve group names */
-      papszGroups = msGetAllGroupNames(mapserv->map, &nGroupNames);
-
-      for (i=0; i<nGroupNames; i++) {
-         /* process group tags */
-         if(generateGroupTemplate(legGroupHtml, mapserv->map, papszGroups[i], groupArgs, &legGroupHtmlCopy, pszPrefix) != MS_SUCCESS)
-         {
-            if(pszResult)
-              free(pszResult);
-            pszResult=NULL;
-            goto error;
-         }
-            
-         /* concatenate it to final result */
-         pszResult = msStringConcatenate(pszResult, legGroupHtmlCopy);
-
-/*         
-         if(!pszResult)
-         {
-            if(pszResult)
-              free(pszResult);
-            pszResult=NULL;
-            goto error;
-         }
-*/
-         
-         if(legGroupHtmlCopy)
-         {
-           free(legGroupHtmlCopy);
-           legGroupHtmlCopy = NULL;
-         }
-         
-         /* for all layers in group */
-         if(legLayerHtml) {
-           for (j=0; j<mapserv->map->numlayers; j++) {
-              /*
-               * if order_metadata is set and the order
-               * value is less than 0, dont display it
-               */
-              pszOrderMetadata = msLookupHashTable(layerArgs, "order_metadata");
-              if(pszOrderMetadata) {
-                 pszOrderValue = msLookupHashTable(&(GET_LAYER(mapserv->map, mapserv->map->layerorder[j])->metadata), pszOrderMetadata);
-                 if(pszOrderValue) {
-                    nLegendOrder = atoi(pszOrderValue);
-                    if(nLegendOrder < 0)
-                      continue;
-                 }
-              }
+  msFree(file);
 
-              if(GET_LAYER(mapserv->map, mapserv->map->layerorder[j])->group && strcmp(GET_LAYER(mapserv->map, mapserv->map->layerorder[j])->group, papszGroups[i]) == 0) {
-                 /* process all layer tags */
-                 if(generateLayerTemplate(legLayerHtml, mapserv->map, mapserv->map->layerorder[j], layerArgs, &legLayerHtmlCopy, pszPrefix) != MS_SUCCESS)
-                 {
-                    if(pszResult)
-                      free(pszResult);
-                    pszResult=NULL;
-                    goto error;
-                 }
-              
-                  
-                 /* concatenate to final result */
-                 pszResult = msStringConcatenate(pszResult, legLayerHtmlCopy);
-
-                 if(legLayerHtmlCopy)
-                 {
-                    free(legLayerHtmlCopy);
-                    legLayerHtmlCopy = NULL;
-                 }
-                 
-            
-                 /* for all classes in layer */
-                 if(legClassHtml) {
-                    for (k=0; k<GET_LAYER(mapserv->map, mapserv->map->layerorder[j])->numclasses; k++) {
-                       /* process all class tags */
-                       if(!GET_LAYER(mapserv->map, mapserv->map->layerorder[j])->class[k]->name)
-                         continue;
-
-                       if(generateClassTemplate(legClassHtml, mapserv->map, mapserv->map->layerorder[j], k, classArgs, &legClassHtmlCopy, pszPrefix) != MS_SUCCESS)
-                       {
-                          if(pszResult)
-                            free(pszResult);
-                          pszResult=NULL;
-                          goto error;
-                       }
-                 
-               
-                       /* concatenate to final result */
-                       pszResult = msStringConcatenate(pszResult, legClassHtmlCopy);
-
-                       if(legClassHtmlCopy) {
-                         free(legClassHtmlCopy);
-                         legClassHtmlCopy = NULL;
-                       }
-                    }
-                 }
-              }
-           }
-         }
-         else
-         if(legClassHtml){ /* no layer template specified but class and group template */
-           for (j=0; j<mapserv->map->numlayers; j++) {
-              /*
-               * if order_metadata is set and the order
-               * value is less than 0, dont display it
-               */
-              pszOrderMetadata = msLookupHashTable(layerArgs, "order_metadata");
-              if(pszOrderMetadata) {
-                 pszOrderValue = msLookupHashTable(&(GET_LAYER(mapserv->map, mapserv->map->layerorder[j])->metadata), pszOrderMetadata);
-                 if(pszOrderValue) {
-                    nLegendOrder = atoi(pszOrderValue);
-                    if(nLegendOrder < 0)
-                      continue;
-                 }
-              }
+  msFree(legGroupHtmlCopy);
+  msFree(legLayerHtmlCopy);
+  msFree(legClassHtmlCopy);
 
-              if(GET_LAYER(mapserv->map, mapserv->map->layerorder[j])->group && strcmp(GET_LAYER(mapserv->map, mapserv->map->layerorder[j])->group, papszGroups[i]) == 0) {
-                 /* for all classes in layer */
-                 if(legClassHtml) {
-                    for (k=0; k<GET_LAYER(mapserv->map, mapserv->map->layerorder[j])->numclasses; k++) {
-                       /* process all class tags */
-                       if(!GET_LAYER(mapserv->map, mapserv->map->layerorder[j])->class[k]->name)
-                         continue;
-
-                       if(generateClassTemplate(legClassHtml, mapserv->map, mapserv->map->layerorder[j], k, classArgs, &legClassHtmlCopy, pszPrefix) != MS_SUCCESS)
-                       {
-                          if(pszResult)
-                            free(pszResult);
-                          pszResult=NULL;
-                          goto error;
-                       }
-                 
-               
-                       /* concatenate to final result */
-                       pszResult = msStringConcatenate(pszResult, legClassHtmlCopy);
-
-                       if(legClassHtmlCopy) {
-                         free(legClassHtmlCopy);
-                         legClassHtmlCopy = NULL;
-                       }
-                    }
-                 }
-              }
-           }
-         }
-      }
-   }
-   else {
-      /* if no group template specified */
-      if(legLayerHtml) {
-         for (j=0; j<mapserv->map->numlayers; j++) {
-            /*
-             * if order_metadata is set and the order
-             * value is less than 0, dont display it
-             */
-            pszOrderMetadata = msLookupHashTable(layerArgs, "order_metadata");
-            if(pszOrderMetadata) {
-               pszOrderValue = msLookupHashTable(&(GET_LAYER(mapserv->map, mapserv->map->layerorder[j])->metadata), pszOrderMetadata);
-               if(pszOrderValue) {
-                  nLegendOrder = atoi(pszOrderValue);
-                  if(nLegendOrder < 0)
-                    continue;
-               }
-               else
-                  nLegendOrder=0;
-            }
+  msFree(legHeaderHtml);
+  msFree(legFooterHtml);
 
-            /* process a layer tags */
-            if(generateLayerTemplate(legLayerHtml, mapserv->map, mapserv->map->layerorder[j], layerArgs, &legLayerHtmlCopy, pszPrefix) != MS_SUCCESS)
-            {
-               if(pszResult)
-                 free(pszResult);
-               pszResult=NULL;
-               goto error;
-            }
-              
-            /* concatenate to final result */
-            pszResult = msStringConcatenate(pszResult, legLayerHtmlCopy);
+  msFree(legGroupHtml);
+  msFree(legLayerHtml);
+  msFree(legClassHtml);
+  msFree(pszPrefix);
 
-            if(legLayerHtmlCopy) {
-               free(legLayerHtmlCopy);
-               legLayerHtmlCopy = NULL;
-            }
-            
-            /* for all classes in layer */
-            if(legClassHtml) {
-               for (k=0; k<GET_LAYER(mapserv->map, mapserv->map->layerorder[j])->numclasses; k++) {
-                  /* process all class tags */
-                  if(!GET_LAYER(mapserv->map, mapserv->map->layerorder[j])->class[k]->name)
-                    continue;
-
-                  if(generateClassTemplate(legClassHtml, mapserv->map, mapserv->map->layerorder[j], k, classArgs, &legClassHtmlCopy, pszPrefix) != MS_SUCCESS)
-                  {
-                     if(pszResult)
-                       free(pszResult);
-                     pszResult=NULL;
-                     goto error;
-                  }
-          
-               
-                  /* concatenate to final result */
-                  pszResult = msStringConcatenate(pszResult, legClassHtmlCopy);
-  
-                  if(legClassHtmlCopy) {
-                    free(legClassHtmlCopy);
-                    legClassHtmlCopy = NULL;
-                  }
-               }
-            }         
-         }
-      }
-      else { /* if no group and layer template specified */
-         if(legClassHtml) {
-            for (j=0; j<mapserv->map->numlayers; j++) {
-               /*
-                * if order_metadata is set and the order
-                * value is less than 0, dont display it
-                */
-               pszOrderMetadata = msLookupHashTable(layerArgs, "order_metadata");
-               if(pszOrderMetadata) {
-                  pszOrderValue = msLookupHashTable(&(GET_LAYER(mapserv->map, mapserv->map->layerorder[j])->metadata), pszOrderMetadata);
-                  if(pszOrderValue) {
-                     nLegendOrder = atoi(pszOrderValue);
-                     if(nLegendOrder < 0)
-                       continue;
-                  }
-               }
+  fclose(stream);
 
-               for (k=0; k<GET_LAYER(mapserv->map, mapserv->map->layerorder[j])->numclasses; k++) {
-                  if(!GET_LAYER(mapserv->map, mapserv->map->layerorder[j])->class[k]->name)
-                    continue;
-                  
-                  if(generateClassTemplate(legClassHtml, mapserv->map, mapserv->map->layerorder[j], k, classArgs, &legClassHtmlCopy, pszPrefix) != MS_SUCCESS)
-                  {
-                     if(pszResult)
-                       free(pszResult);
-                     pszResult=NULL;
-                     goto error;
-                  }
-      
-               
-                  pszResult = msStringConcatenate(pszResult, legClassHtmlCopy);
-
-                  if(legClassHtmlCopy) {
-                    free(legClassHtmlCopy);
-                    legClassHtmlCopy = NULL;
-                  }
-               }
-            }
-         }
-      }
-   }
-   
-   /* finish with the footer if present */
-   if(legFooterHtml) pszResult = msStringConcatenate(pszResult, legFooterHtml);
-
-   /*
-    * if we reach this point, that mean no error was generated.
-    * So check if template is null and initialize it to <space>.
-    */
-   if(pszResult == NULL)
-   {
-      pszResult = msStringConcatenate(pszResult, " ");
-   }
-   
-   
-   /********************************************************************/
-      
-   error:
-      
-   if(papszGroups) {
-      for (i=0; i<nGroupNames; i++)
-        msFree(papszGroups[i]);
-
-      msFree(papszGroups);
-   }
-   
-   msFreeHashTable(groupArgs);
-   msFreeHashTable(layerArgs);
-   msFreeHashTable(classArgs);
-   
-   msFree(file);
-     
-   msFree(legGroupHtmlCopy);
-   msFree(legLayerHtmlCopy);
-   msFree(legClassHtmlCopy);
-      
-   msFree(legHeaderHtml);
-   msFree(legFooterHtml);
-
-   msFree(legGroupHtml);
-   msFree(legLayerHtml);
-   msFree(legClassHtml);
-   msFree(pszPrefix);
-
-   fclose(stream);
-
-/* -------------------------------------------------------------------- */
-/*      Reset the layerdrawing order.                                   */
-/* -------------------------------------------------------------------- */
-   if(panCurrentDrawingOrder && mapserv->map->layerorder)
-   {
-       for (i=0; i<mapserv->map->numlayers; i++)
-          mapserv->map->layerorder[i] =  panCurrentDrawingOrder[i];
-
-       free(panCurrentDrawingOrder);
-   }
-   
-   return pszResult;
+  /* -------------------------------------------------------------------- */
+  /*      Reset the layerdrawing order.                                   */
+  /* -------------------------------------------------------------------- */
+  if(panCurrentDrawingOrder && mapserv->map->layerorder) {
+    for (i=0; i<mapserv->map->numlayers; i++)
+      mapserv->map->layerorder[i] =  panCurrentDrawingOrder[i];
+
+    free(panCurrentDrawingOrder);
+  }
+
+  return pszResult;
 }
 
 char *processOneToManyJoin(mapservObj* mapserv, joinObj *join)
 {
   int records=MS_FALSE;
   FILE *stream=NULL;
-  char *outbuf; 
+  char *outbuf;
   char line[MS_BUFFER_LENGTH], *tmpline;
   char szPath[MS_MAXPATHLEN];
 
@@ -3489,7 +3434,7 @@ char *processOneToManyJoin(mapservObj* mapserv, joinObj *join)
   while(msJoinNext(join) == MS_SUCCESS) {
     /* First time through, deal with the header (if necessary) and open the main template. We only */
     /* want to do this if there are joined records. */
-    if(records == MS_FALSE) { 
+    if(records == MS_FALSE) {
       if(join->header != NULL) {
         if((stream = fopen(msBuildPath(szPath, mapserv->map->mappath, join->header), "r")) == NULL) {
           msSetError(MS_IOERR, "Error while opening join header file %s.", "processOneToManyJoin()", join->header);
@@ -3510,8 +3455,8 @@ char *processOneToManyJoin(mapservObj* mapserv, joinObj *join)
       if((stream = fopen(msBuildPath(szPath, mapserv->map->mappath, join->template), "r")) == NULL) {
         msSetError(MS_IOERR, "Error while opening join template file %s.", "processOneToManyJoin()", join->template);
         return(NULL);
-      }      
-      
+      }
+
       if(isValidTemplate(stream, join->template) != MS_TRUE) {
         fclose(stream);
         return NULL;
@@ -3519,7 +3464,7 @@ char *processOneToManyJoin(mapservObj* mapserv, joinObj *join)
 
       records = MS_TRUE;
     }
-    
+
     while(fgets(line, MS_BUFFER_LENGTH, stream) != NULL) { /* now on to the end of the template */
       if(strchr(line, '[') != NULL) {
         tmpline = processLine(mapserv, line, NULL, QUERY); /* no multiline tags are allowed in a join */
@@ -3529,12 +3474,12 @@ char *processOneToManyJoin(mapservObj* mapserv, joinObj *join)
       } else /* no subs, just echo */
         outbuf = msStringConcatenate(outbuf, line);
     }
-      
+
     rewind(stream);
     fgets(line, MS_BUFFER_LENGTH, stream); /* skip the first line since it's the magic string */
   } /* next record */
 
-  if(records==MS_TRUE && join->footer) {    
+  if(records==MS_TRUE && join->footer) {
     if((stream = fopen(msBuildPath(szPath, mapserv->map->mappath, join->footer), "r")) == NULL) {
       msSetError(MS_IOERR, "Error while opening join footer file %s.", "processOneToManyJoin()", join->footer);
       return(NULL);
@@ -3547,7 +3492,7 @@ char *processOneToManyJoin(mapservObj* mapserv, joinObj *join)
 
     /* echo file to the output buffer, no substitutions */
     while(fgets(line, MS_BUFFER_LENGTH, stream) != NULL) outbuf = msStringConcatenate(outbuf, line);
-    
+
     fclose(stream);
   }
 
@@ -3569,7 +3514,7 @@ static char *processLine(mapservObj *mapserv, char *instr, FILE *stream, int mod
   char repstr[PROCESSLINE_BUFLEN], substr[PROCESSLINE_BUFLEN], *outstr; /* repstr = replace string, substr = sub string */
   struct hashObj *tp=NULL;
   char *encodedstr;
-   
+
 #ifdef USE_PROJ
   rectObj llextent;
   pointObj llpoint;
@@ -3593,27 +3538,25 @@ static char *processLine(mapservObj *mapserv, char *instr, FILE *stream, int mod
     free(errmsg);
     free(encodedstr);
   }
-  
+
   if(strstr(outstr, "[legend]")) {
-     /* if there's a template legend specified, use it */
-     if(mapserv->map->legend.template) {
-        char *legendTemplate;
-
-        legendTemplate = generateLegendTemplate(mapserv);
-        if(legendTemplate) {
-          outstr = msReplaceSubstring(outstr, "[legend]", legendTemplate);
-     
-           free(legendTemplate);
-        }
-        else /* error already generated by (generateLegendTemplate()) */
-          return NULL;
-     }
-     else { /* if not display gif image with all legend icon */
-        snprintf(repstr, PROCESSLINE_BUFLEN, "%s%sleg%s.%s", mapserv->map->web.imageurl, mapserv->map->name, mapserv->Id, MS_IMAGE_EXTENSION(mapserv->map->outputformat));
-        outstr = msReplaceSubstring(outstr, "[legend]", repstr);
-     }
+    /* if there's a template legend specified, use it */
+    if(mapserv->map->legend.template) {
+      char *legendTemplate;
+
+      legendTemplate = generateLegendTemplate(mapserv);
+      if(legendTemplate) {
+        outstr = msReplaceSubstring(outstr, "[legend]", legendTemplate);
+
+        free(legendTemplate);
+      } else /* error already generated by (generateLegendTemplate()) */
+        return NULL;
+    } else { /* if not display gif image with all legend icon */
+      snprintf(repstr, PROCESSLINE_BUFLEN, "%s%sleg%s.%s", mapserv->map->web.imageurl, mapserv->map->name, mapserv->Id, MS_IMAGE_EXTENSION(mapserv->map->outputformat));
+      outstr = msReplaceSubstring(outstr, "[legend]", repstr);
+    }
   }
-   
+
   snprintf(repstr, PROCESSLINE_BUFLEN, "%s%ssb%s.%s", mapserv->map->web.imageurl, mapserv->map->name, mapserv->Id, MS_IMAGE_EXTENSION(mapserv->map->outputformat));
   outstr = msReplaceSubstring(outstr, "[scalebar]", repstr);
 
@@ -3621,34 +3564,37 @@ static char *processLine(mapservObj *mapserv, char *instr, FILE *stream, int mod
     snprintf(repstr, PROCESSLINE_BUFLEN, "%s%s%s%s", mapserv->map->web.imagepath, mapserv->map->name, mapserv->Id, MS_QUERY_EXTENSION);
     outstr = msReplaceSubstring(outstr, "[queryfile]", repstr);
   }
-  
+
   if(mapserv->savemap) {
     snprintf(repstr, PROCESSLINE_BUFLEN, "%s%s%s.map", mapserv->map->web.imagepath, mapserv->map->name, mapserv->Id);
     outstr = msReplaceSubstring(outstr, "[map]", repstr);
   }
 
+  if(strstr(outstr,"[mapserv_onlineresource]")) {
+    char *ol;
 #if defined(USE_WMS_SVR) || defined (USE_WFS_SVR) || defined (USE_WCS_SVR) || defined(USE_SOS_SVR) || defined(USE_WMS_LYR) || defined(USE_WFS_LYR)
-  outstr = msReplaceSubstring(outstr, "[mapserv_onlineresource]",
-                              msOWSGetOnlineResource(mapserv->map, "O", "onlineresource", mapserv->request));
+    ol = msOWSGetOnlineResource(mapserv->map, "O", "onlineresource", mapserv->request);
 #else
-  outstr = msReplaceSubstring(outstr, "[mapserv_onlineresource]",
-                              msBuildOnlineResource(mapserv->map, mapserv->request));  
+    ol = msBuildOnlineResource(mapserv->map, mapserv->request);
 #endif
+    outstr = msReplaceSubstring(outstr, "[mapserv_onlineresource]",ol);
+    msFree(ol);
+  }
 
   if(getenv("HTTP_HOST")) {
-    snprintf(repstr, PROCESSLINE_BUFLEN, "%s", getenv("HTTP_HOST")); 
+    snprintf(repstr, PROCESSLINE_BUFLEN, "%s", getenv("HTTP_HOST"));
     outstr = msReplaceSubstring(outstr, "[host]", repstr);
   }
-  if(getenv("SERVER_PORT")) { 
+  if(getenv("SERVER_PORT")) {
     snprintf(repstr, PROCESSLINE_BUFLEN, "%s", getenv("SERVER_PORT"));
     outstr = msReplaceSubstring(outstr, "[port]", repstr);
   }
-  
+
   snprintf(repstr, PROCESSLINE_BUFLEN, "%s", mapserv->Id);
   outstr = msReplaceSubstring(outstr, "[id]", repstr);
-  
+
   repstr[0] = '\0'; /* Layer list for a "POST" request */
-  for(i=0;i<mapserv->NumLayers;i++) {    
+  for(i=0; i<mapserv->NumLayers; i++) {
     strlcat(repstr, mapserv->Layers[i], sizeof(repstr));
     strlcat(repstr, " ", sizeof(repstr));
   }
@@ -3661,7 +3607,7 @@ static char *processLine(mapservObj *mapserv, char *instr, FILE *stream, int mod
 
   strcpy(repstr, ""); /* list of ALL layers that can be toggled */
   repstr[0] = '\0';
-  for(i=0;i<mapserv->map->numlayers;i++) {
+  for(i=0; i<mapserv->map->numlayers; i++) {
     if(GET_LAYER(mapserv->map, i)->status != MS_DEFAULT && GET_LAYER(mapserv->map, i)->name != NULL) {
       strlcat(repstr, GET_LAYER(mapserv->map, i)->name, sizeof(repstr));
       strlcat(repstr, " ", sizeof(repstr));
@@ -3673,8 +3619,8 @@ static char *processLine(mapservObj *mapserv, char *instr, FILE *stream, int mod
   encodedstr = msEncodeUrl(repstr);
   outstr = msReplaceSubstring(outstr, "[toggle_layers_esc]", encodedstr);
   free(encodedstr);
-  
-  for(i=0;i<mapserv->map->numlayers;i++) { /* Set form widgets (i.e. checkboxes, radio and select lists), note that default layers don't show up here */
+
+  for(i=0; i<mapserv->map->numlayers; i++) { /* Set form widgets (i.e. checkboxes, radio and select lists), note that default layers don't show up here */
     if(isOn(mapserv, GET_LAYER(mapserv->map, i)->name, GET_LAYER(mapserv->map, i)->group) == MS_TRUE) {
       if(GET_LAYER(mapserv->map, i)->group) {
         snprintf(substr, PROCESSLINE_BUFLEN, "[%s_select]", GET_LAYER(mapserv->map, i)->group);
@@ -3704,7 +3650,7 @@ static char *processLine(mapservObj *mapserv, char *instr, FILE *stream, int mod
     }
   }
 
-  for(i=-1;i<=1;i++) { /* make zoom direction persistant */
+  for(i=-1; i<=1; i++) { /* make zoom direction persistant */
     if(mapserv->ZoomDirection == i) {
       snprintf(substr, sizeof(substr), "[zoomdir_%d_select]", i);
       outstr = msReplaceSubstring(outstr, substr, "selected=\"selected\"");
@@ -3717,8 +3663,8 @@ static char *processLine(mapservObj *mapserv, char *instr, FILE *stream, int mod
       outstr = msReplaceSubstring(outstr, substr, "");
     }
   }
-  
-  for(i=MINZOOM;i<=MAXZOOM;i++) { /* make zoom persistant */
+
+  for(i=MINZOOM; i<=MAXZOOM; i++) { /* make zoom persistant */
     if(mapserv->Zoom == i) {
       snprintf(substr, sizeof(substr), "[zoom_%d_select]", i);
       outstr = msReplaceSubstring(outstr, substr, "selected=\"selected\"");
@@ -3733,17 +3679,17 @@ static char *processLine(mapservObj *mapserv, char *instr, FILE *stream, int mod
   }
 
   /* allow web object metadata access in template */
-  
-  /* 
+
+  /*
    * reworked by SG to use HashTable methods
    */
-  
+
   if(&(mapserv->map->web.metadata) && strstr(outstr, "web_")) {
     for (j=0; j<MS_HASHSIZE; j++) {
       if(mapserv->map->web.metadata.items[j] != NULL) {
         for(tp=mapserv->map->web.metadata.items[j]; tp!=NULL; tp=tp->next) {
           snprintf(substr, PROCESSLINE_BUFLEN, "[web_%s]", tp->key);
-          outstr = msReplaceSubstring(outstr, substr, tp->data);  
+          outstr = msReplaceSubstring(outstr, substr, tp->data);
           snprintf(substr, PROCESSLINE_BUFLEN, "[web_%s_esc]", tp->key);
 
           encodedstr = msEncodeUrl(tp->data);
@@ -3755,7 +3701,7 @@ static char *processLine(mapservObj *mapserv, char *instr, FILE *stream, int mod
   }
 
   /* allow layer metadata access in template */
-  for(i=0;i<mapserv->map->numlayers;i++) {
+  for(i=0; i<mapserv->map->numlayers; i++) {
     if(&(GET_LAYER(mapserv->map, i)->metadata) && GET_LAYER(mapserv->map, i)->name && strstr(outstr, GET_LAYER(mapserv->map, i)->name)) {
       for(j=0; j<MS_HASHSIZE; j++) {
         if(GET_LAYER(mapserv->map, i)->metadata.items[j] != NULL) {
@@ -3782,7 +3728,7 @@ static char *processLine(mapservObj *mapserv, char *instr, FILE *stream, int mod
   outstr = msReplaceSubstring(outstr, "[mapx]", repstr);
   snprintf(repstr, sizeof(repstr), "%f", mapserv->mappnt.y);
   outstr = msReplaceSubstring(outstr, "[mapy]", repstr);
-  
+
   snprintf(repstr, sizeof(repstr), "%f", mapserv->map->extent.minx); /* Individual mapextent elements for spatial query building, deprecated. */
   outstr = msReplaceSubstring(outstr, "[minx]", repstr);
   snprintf(repstr, sizeof(repstr), "%f", mapserv->map->extent.maxx);
@@ -3799,7 +3745,7 @@ static char *processLine(mapservObj *mapserv, char *instr, FILE *stream, int mod
     return(NULL);
   if(processExtentTag(mapserv, &outstr, "mapext_esc", &(mapserv->map->extent), &(mapserv->map->projection)) != MS_SUCCESS) /* depricated */
     return(NULL);
-   
+
   snprintf(repstr, sizeof(repstr), "%f", (mapserv->map->extent.maxx-mapserv->map->extent.minx)); /* useful for creating cachable extents (i.e. 0 0 dx dy) with legends and scalebars */
   outstr = msReplaceSubstring(outstr, "[dx]", repstr);
   snprintf(repstr, sizeof(repstr), "%f", (mapserv->map->extent.maxy-mapserv->map->extent.miny));
@@ -3818,11 +3764,11 @@ static char *processLine(mapservObj *mapserv, char *instr, FILE *stream, int mod
     return(NULL);
   if(processExtentTag(mapserv, &outstr, "rawext_esc", &(mapserv->RawExt), &(mapserv->map->projection)) != MS_SUCCESS) /* depricated */
     return(NULL);
-  
+
 #ifdef USE_PROJ
   if((strstr(outstr, "lat]") || strstr(outstr, "lon]") || strstr(outstr, "lon_esc]"))
-     && mapserv->map->projection.proj != NULL
-     && !pj_is_latlong(mapserv->map->projection.proj) ) {
+      && mapserv->map->projection.proj != NULL
+      && !pj_is_latlong(mapserv->map->projection.proj) ) {
     llextent=mapserv->map->extent;
     llpoint=mapserv->mappnt;
     msProjectRect(&(mapserv->map->projection), &(mapserv->map->latlon), &llextent);
@@ -3832,7 +3778,7 @@ static char *processLine(mapservObj *mapserv, char *instr, FILE *stream, int mod
     outstr = msReplaceSubstring(outstr, "[maplon]", repstr);
     snprintf(repstr, sizeof(repstr), "%f", llpoint.y);
     outstr = msReplaceSubstring(outstr, "[maplat]", repstr);
-    
+
     snprintf(repstr, sizeof(repstr), "%f", llextent.minx); /* map extent as lat/lon */
     outstr = msReplaceSubstring(outstr, "[minlon]", repstr);
     snprintf(repstr, sizeof(repstr), "%f", llextent.maxx);
@@ -3840,9 +3786,9 @@ static char *processLine(mapservObj *mapserv, char *instr, FILE *stream, int mod
     snprintf(repstr, sizeof(repstr), "%f", llextent.miny);
     outstr = msReplaceSubstring(outstr, "[minlat]", repstr);
     snprintf(repstr, sizeof(repstr), "%f", llextent.maxy);
-    outstr = msReplaceSubstring(outstr, "[maxlat]", repstr);    
+    outstr = msReplaceSubstring(outstr, "[maxlat]", repstr);
 
-    if(processExtentTag(mapserv, &outstr, "mapext_latlon", &(llextent), NULL) != MS_SUCCESS) 
+    if(processExtentTag(mapserv, &outstr, "mapext_latlon", &(llextent), NULL) != MS_SUCCESS)
       return(NULL);
     if(processExtentTag(mapserv, &outstr, "mapext_latlon_esc", &(llextent), NULL) != MS_SUCCESS) /* depricated */
       return(NULL);
@@ -3868,7 +3814,7 @@ static char *processLine(mapservObj *mapserv, char *instr, FILE *stream, int mod
 
   snprintf(repstr, sizeof(repstr), "%d %d", mapserv->map->width, mapserv->map->height);
   outstr = msReplaceSubstring(outstr, "[mapsize]", repstr);
-   
+
   encodedstr = msEncodeUrl(repstr);
   outstr = msReplaceSubstring(outstr, "[mapsize_esc]", encodedstr);
   free(encodedstr);
@@ -3877,27 +3823,27 @@ static char *processLine(mapservObj *mapserv, char *instr, FILE *stream, int mod
   outstr = msReplaceSubstring(outstr, "[mapwidth]", repstr);
   snprintf(repstr, sizeof(repstr), "%d", mapserv->map->height);
   outstr = msReplaceSubstring(outstr, "[mapheight]", repstr);
-  
+
   snprintf(repstr, sizeof(repstr), "%f", mapserv->map->scaledenom);
   outstr = msReplaceSubstring(outstr, "[scale]", repstr);
   outstr = msReplaceSubstring(outstr, "[scaledenom]", repstr);
   snprintf(repstr, sizeof(repstr), "%f", mapserv->map->cellsize);
   outstr = msReplaceSubstring(outstr, "[cellsize]", repstr);
-  
+
   snprintf(repstr, sizeof(repstr), "%.1f %.1f", (mapserv->map->width)/2.0, (mapserv->map->height)/2.0); /* not subtracting 1 from image dimensions (see bug 633) */
   outstr = msReplaceSubstring(outstr, "[center]", repstr);
   snprintf(repstr, sizeof(repstr), "%.1f", (mapserv->map->width)/2.0);
   outstr = msReplaceSubstring(outstr, "[center_x]", repstr);
   snprintf(repstr, sizeof(repstr), "%.1f", (mapserv->map->height)/2.0);
-  outstr = msReplaceSubstring(outstr, "[center_y]", repstr);      
+  outstr = msReplaceSubstring(outstr, "[center_y]", repstr);
 
   /* These are really for situations with multiple result sets only, but often used in header/footer   */
   snprintf(repstr, sizeof(repstr), "%d", mapserv->NR); /* total number of results */
-  outstr = msReplaceSubstring(outstr, "[nr]", repstr);  
+  outstr = msReplaceSubstring(outstr, "[nr]", repstr);
   snprintf(repstr, sizeof(repstr), "%d", mapserv->NL); /* total number of layers with results */
   outstr = msReplaceSubstring(outstr, "[nl]", repstr);
 
-  if(mapserv->resultlayer) {    
+  if(mapserv->resultlayer) {
     if(strstr(outstr, "[items]") != NULL) {
       char *itemstr=NULL;
 
@@ -3912,8 +3858,8 @@ static char *processLine(mapservObj *mapserv, char *instr, FILE *stream, int mod
     outstr = msReplaceSubstring(outstr, "[rn]", repstr);
     snprintf(repstr, sizeof(repstr), "%d", mapserv->LRN); /* sequential (eg. 1..n) result number within this layer */
     outstr = msReplaceSubstring(outstr, "[lrn]", repstr);
-    outstr = msReplaceSubstring(outstr, "[cl]", mapserv->resultlayer->name); /* current layer name     */
-    /* if(resultlayer->description) outstr = msReplaceSubstring(outstr, "[cd]", resultlayer->description); // current layer description     */
+    outstr = msReplaceSubstring(outstr, "[cl]", mapserv->resultlayer->name); /* current layer name */
+    /* if(resultlayer->description) outstr = msReplaceSubstring(outstr, "[cd]", resultlayer->description); */ /* current layer description */
   }
 
   if(mode != QUERY) {
@@ -3929,7 +3875,7 @@ static char *processLine(mapservObj *mapserv, char *instr, FILE *stream, int mod
           for(tp=mapserv->resultlayer->metadata.items[i]; tp!=NULL; tp=tp->next) {
             snprintf(substr, PROCESSLINE_BUFLEN, "[metadata_%s]", tp->key);
             outstr = msReplaceSubstring(outstr, substr, tp->data);
-     
+
             snprintf(substr, PROCESSLINE_BUFLEN, "[metadata_%s_esc]", tp->key);
             encodedstr = msEncodeUrl(tp->data);
             outstr = msReplaceSubstring(outstr, substr, encodedstr);
@@ -3938,14 +3884,14 @@ static char *processLine(mapservObj *mapserv, char *instr, FILE *stream, int mod
         }
       }
     }
-    
-    snprintf(repstr, sizeof(repstr), "%f %f", (mapserv->resultshape.bounds.maxx + mapserv->resultshape.bounds.minx)/2, (mapserv->resultshape.bounds.maxy + mapserv->resultshape.bounds.miny)/2); 
+
+    snprintf(repstr, sizeof(repstr), "%f %f", (mapserv->resultshape.bounds.maxx + mapserv->resultshape.bounds.minx)/2, (mapserv->resultshape.bounds.maxy + mapserv->resultshape.bounds.miny)/2);
     outstr = msReplaceSubstring(outstr, "[shpmid]", repstr);
     snprintf(repstr, sizeof(repstr), "%f", (mapserv->resultshape.bounds.maxx + mapserv->resultshape.bounds.minx)/2);
     outstr = msReplaceSubstring(outstr, "[shpmidx]", repstr);
     snprintf(repstr, sizeof(repstr), "%f", (mapserv->resultshape.bounds.maxy + mapserv->resultshape.bounds.miny)/2);
     outstr = msReplaceSubstring(outstr, "[shpmidy]", repstr);
-    
+
     if(processExtentTag(mapserv, &outstr, "shpext", &(mapserv->resultshape.bounds), &(mapserv->resultlayer->projection)) != MS_SUCCESS)
       return(NULL);
     if(processExtentTag(mapserv, &outstr, "shpext_esc", &(mapserv->resultshape.bounds), &(mapserv->resultlayer->projection)) != MS_SUCCESS) /* depricated */
@@ -3957,7 +3903,7 @@ static char *processLine(mapservObj *mapserv, char *instr, FILE *stream, int mod
     if(processShpxyTag(mapserv->resultlayer, &outstr, &mapserv->resultshape) != MS_SUCCESS)
       return(NULL);
 
-     if(processShplabelTag(mapserv->resultlayer, &outstr, &mapserv->resultshape) != MS_SUCCESS)
+    if(processShplabelTag(mapserv->resultlayer, &outstr, &mapserv->resultshape) != MS_SUCCESS)
       return(NULL);
 
     snprintf(repstr, sizeof(repstr), "%f", mapserv->resultshape.bounds.minx);
@@ -3968,11 +3914,11 @@ static char *processLine(mapservObj *mapserv, char *instr, FILE *stream, int mod
     outstr = msReplaceSubstring(outstr, "[shpmaxx]", repstr);
     snprintf(repstr, sizeof(repstr), "%f", mapserv->resultshape.bounds.maxy);
     outstr = msReplaceSubstring(outstr, "[shpmaxy]", repstr);
-    
+
     snprintf(repstr, sizeof(repstr), "%ld", mapserv->resultshape.index);
     outstr = msReplaceSubstring(outstr, "[shpidx]", repstr);
     snprintf(repstr, sizeof(repstr), "%d", mapserv->resultshape.tileindex);
-    outstr = msReplaceSubstring(outstr, "[tileidx]", repstr);  
+    outstr = msReplaceSubstring(outstr, "[tileidx]", repstr);
 
     /* return ALL attributes in one delimeted list */
     if(strstr(outstr, "[values]") != NULL) {
@@ -3983,7 +3929,7 @@ static char *processLine(mapservObj *mapserv, char *instr, FILE *stream, int mod
       free(valuestr);
     }
 
-    for(i=0;i<mapserv->resultlayer->numitems;i++) {
+    for(i=0; i<mapserv->resultlayer->numitems; i++) {
       /* by default let's encode attributes for HTML presentation */
       snprintf(substr, PROCESSLINE_BUFLEN, "[%s]", mapserv->resultlayer->items[i]);
       if(strstr(outstr, substr) != NULL) {
@@ -4005,16 +3951,16 @@ static char *processLine(mapservObj *mapserv, char *instr, FILE *stream, int mod
       if(strstr(outstr, substr) != NULL)
         outstr = msReplaceSubstring(outstr, substr, mapserv->resultshape.values[i]);
     }
-    
+
     if(processItemTag(mapserv->resultlayer, &outstr, &mapserv->resultshape) != MS_SUCCESS)
       return(NULL);
 
     /* handle joins in this next section */
     for(i=0; i<mapserv->resultlayer->numjoins; i++) {
       if(mapserv->resultlayer->joins[i].values) { /* join has data */
-        for(j=0;j<mapserv->resultlayer->joins[i].numitems;j++) {
+        for(j=0; j<mapserv->resultlayer->joins[i].numitems; j++) {
           /* by default let's encode attributes for HTML presentation */
-          snprintf(substr, PROCESSLINE_BUFLEN, "[%s_%s]", mapserv->resultlayer->joins[i].name, mapserv->resultlayer->joins[i].items[j]);        
+          snprintf(substr, PROCESSLINE_BUFLEN, "[%s_%s]", mapserv->resultlayer->joins[i].name, mapserv->resultlayer->joins[i].items[j]);
           if(strstr(outstr, substr) != NULL) {
             encodedstr = msEncodeHTMLEntities(mapserv->resultlayer->joins[i].values[j]);
             outstr = msReplaceSubstring(outstr, substr, encodedstr);
@@ -4034,14 +3980,14 @@ static char *processLine(mapservObj *mapserv, char *instr, FILE *stream, int mod
           if(strstr(outstr, substr) != NULL)
             outstr = msReplaceSubstring(outstr, substr, mapserv->resultlayer->joins[i].values[j]);
         }
-      } else if(mapserv->resultlayer->joins[i].type ==  MS_JOIN_ONE_TO_MANY){ /* one-to-many join */
+      } else if(mapserv->resultlayer->joins[i].type ==  MS_JOIN_ONE_TO_MANY) { /* one-to-many join */
         char *joinTemplate=NULL;
 
-        snprintf(substr, PROCESSLINE_BUFLEN, "[join_%s]", mapserv->resultlayer->joins[i].name);        
+        snprintf(substr, PROCESSLINE_BUFLEN, "[join_%s]", mapserv->resultlayer->joins[i].name);
         if(strstr(outstr, substr) != NULL) {
           joinTemplate = processOneToManyJoin(mapserv, &(mapserv->resultlayer->joins[i]));
           if(joinTemplate) {
-            outstr = msReplaceSubstring(outstr, substr, joinTemplate);     
+            outstr = msReplaceSubstring(outstr, substr, joinTemplate);
             free(joinTemplate);
           } else
             return NULL;
@@ -4054,7 +4000,7 @@ static char *processLine(mapservObj *mapserv, char *instr, FILE *stream, int mod
   if(processIncludeTag(mapserv, &outstr, stream, mode) != MS_SUCCESS)
     return(NULL);
 
-  for(i=0;i<mapserv->request->NumParams;i++) {
+  for(i=0; i<mapserv->request->NumParams; i++) {
     /* Replace [variable] tags using values from URL. We cannot offer a
      * [variable_raw] option here due to the risk of XSS
      */
@@ -4082,7 +4028,7 @@ int msReturnPage(mapservObj *mapserv, char *html, int mode, char **papszBuffer)
   int   nCurrentSize = 0;
   int   nExpandBuffer = 0;
 
-  ms_regex_t re; /* compiled regular expression to be matched */ 
+  ms_regex_t re; /* compiled regular expression to be matched */
   char szPath[MS_MAXPATHLEN];
 
   if(!html) {
@@ -4090,7 +4036,7 @@ int msReturnPage(mapservObj *mapserv, char *html, int mode, char **papszBuffer)
     return MS_FAILURE;
   }
 
-  if(ms_regcomp(&re, MS_TEMPLATE_EXPR, MS_REG_EXTENDED|MS_REG_NOSUB) != 0) {
+  if(ms_regcomp(&re, MS_TEMPLATE_EXPR, MS_REG_EXTENDED|MS_REG_NOSUB|MS_REG_ICASE) != 0) {
     msSetError(MS_REGEXERR, NULL, "msReturnPage()");
     return MS_FAILURE;
   }
@@ -4105,7 +4051,7 @@ int msReturnPage(mapservObj *mapserv, char *html, int mode, char **papszBuffer)
   if((stream = fopen(msBuildPath(szPath, mapserv->map->mappath, html), "r")) == NULL) {
     msSetError(MS_IOERR, html, "msReturnPage()");
     return MS_FAILURE;
-  } 
+  }
 
   if(isValidTemplate(stream, html) != MS_TRUE) {
     fclose(stream);
@@ -4140,7 +4086,7 @@ int msReturnPage(mapservObj *mapserv, char *html, int mode, char **papszBuffer)
           (*papszBuffer) = (char *) msSmallRealloc((*papszBuffer),sizeof(char)*nBufferSize);
         }
         strcat((*papszBuffer), tmpline);
-        nCurrentSize += strlen(tmpline);   
+        nCurrentSize += strlen(tmpline);
       } else
         msIO_fwrite(tmpline, strlen(tmpline), 1, stdout);
 
@@ -4154,7 +4100,7 @@ int msReturnPage(mapservObj *mapserv, char *html, int mode, char **papszBuffer)
         }
         strcat((*papszBuffer), line);
         nCurrentSize += strlen(line);
-      } else 
+      } else
         msIO_fwrite(line, strlen(line), 1, stdout);
     }
     if(!papszBuffer)
@@ -4209,7 +4155,7 @@ int msReturnNestedTemplateQuery(mapservObj* mapserv, char* pszMimeType, char **p
     nCurrentSize = 0;
     nExpandBuffer = 1;
   }
-  
+
   msInitShape(&(mapserv->resultshape));
 
   if((mapserv->Mode == ITEMQUERY) || (mapserv->Mode == QUERY)) { /* may need to handle a URL result set since these modes return exactly 1 result */
@@ -4223,9 +4169,9 @@ int msReturnNestedTemplateQuery(mapservObj* mapserv, char* pszMimeType, char **p
 
     if(i >= 0) { /* at least if no result found, mapserver will display an empty template. */
 
-      if(lp->resultcache->results[0].classindex >= 0 && lp->class[(int)(lp->resultcache->results[0].classindex)]->template) 
+      if(lp->resultcache->results[0].classindex >= 0 && lp->class[(int)(lp->resultcache->results[0].classindex)]->template)
         template = lp->class[(int)(lp->resultcache->results[0].classindex)]->template;
-      else 
+      else
         template = lp->template;
 
       if( template == NULL ) {
@@ -4236,19 +4182,21 @@ int msReturnNestedTemplateQuery(mapservObj* mapserv, char* pszMimeType, char **p
       if(TEMPLATE_TYPE(template) == MS_URL) {
         mapserv->resultlayer = lp;
 
-        // status = msLayerOpen(lp);
-        // if(status != MS_SUCCESS) return status;
-        
-        // status = msLayerGetItems(lp); /* retrieve all the item names */
-        // if(status != MS_SUCCESS) return status;
+#if 0
+        status = msLayerOpen(lp);
+        if(status != MS_SUCCESS) return status;
+
+        status = msLayerGetItems(lp); /* retrieve all the item names */
+        if(status != MS_SUCCESS) return status;
+#endif
 
         status = msLayerGetShape(lp, &(mapserv->resultshape), &(lp->resultcache->results[0]));
         if(status != MS_SUCCESS) return status;
 
         if(lp->numjoins > 0) {
-          for(k=0; k<lp->numjoins; k++) { 
+          for(k=0; k<lp->numjoins; k++) {
             status = msJoinConnect(lp, &(lp->joins[k]));
-            if(status != MS_SUCCESS) return status;  
+            if(status != MS_SUCCESS) return status;
 
             msJoinPrepare(&(lp->joins[k]), &(mapserv->resultshape));
             msJoinNext(&(lp->joins[k])); /* fetch the first row */
@@ -4260,9 +4208,9 @@ int msReturnNestedTemplateQuery(mapservObj* mapserv, char* pszMimeType, char **p
         }
 
         msFreeShape(&(mapserv->resultshape));
-        // msLayerClose(lp);
+        /* msLayerClose(lp); */
         mapserv->resultlayer = NULL;
-          
+
         return MS_SUCCESS;
       }
     }
@@ -4277,7 +4225,7 @@ int msReturnNestedTemplateQuery(mapservObj* mapserv, char* pszMimeType, char **p
 
     if(!lp->resultcache) continue;
 
-    if(lp->resultcache->numresults > 0) { 
+    if(lp->resultcache->numresults > 0) {
       mapserv->NL++;
       mapserv->NR += lp->resultcache->numresults;
     }
@@ -4288,7 +4236,7 @@ int msReturnNestedTemplateQuery(mapservObj* mapserv, char* pszMimeType, char **p
   ** so why should this. Note that new-style templates don't buffer the mime-type either.
   */
   if(papszBuffer && mapserv->sendheaders) {
-    snprintf(buffer, sizeof(buffer), "Content-type: %s%c%c", pszMimeType, 10, 10);
+    snprintf(buffer, sizeof(buffer), "Content-Type: %s%c%c", pszMimeType, 10, 10);
     if(nBufferSize <= (int)(nCurrentSize + strlen(buffer) + 1)) {
       nExpandBuffer++;
       (*papszBuffer) = (char *)msSmallRealloc((*papszBuffer), MS_TEMPLATE_BUFFER*nExpandBuffer);
@@ -4297,8 +4245,8 @@ int msReturnNestedTemplateQuery(mapservObj* mapserv, char* pszMimeType, char **p
     strcat((*papszBuffer), buffer);
     nCurrentSize += strlen(buffer);
   } else if(mapserv->sendheaders) {
-    msIO_printf("Content-type: %s%c%c", pszMimeType, 10, 10);
-    fflush(stdout);
+    msIO_setHeader("Content-Type",pszMimeType);
+    msIO_sendHeaders();
   }
 
   if(mapserv->map->web.header) {
@@ -4312,22 +4260,24 @@ int msReturnNestedTemplateQuery(mapservObj* mapserv, char* pszMimeType, char **p
     if(!lp->resultcache) continue;
     if(lp->resultcache->numresults <= 0) continue;
 
-    mapserv->NLR = lp->resultcache->numresults; 
+    mapserv->NLR = lp->resultcache->numresults;
+
+#if 0
+    status = msLayerOpen(lp); /* open this layer */
+    if(status != MS_SUCCESS) return status;
 
-    // status = msLayerOpen(lp); /* open this layer */
-    // if(status != MS_SUCCESS) return status;
+    status = msLayerGetItems(lp); /* retrieve all the item names */
+    if(status != MS_SUCCESS) return status;
+#endif
 
-    // status = msLayerGetItems(lp); /* retrieve all the item names */
-    // if(status != MS_SUCCESS) return status;
-    
     if(lp->numjoins > 0) { /* open any necessary JOINs here */
       for(k=0; k<lp->numjoins; k++) {
         status = msJoinConnect(lp, &(lp->joins[k]));
-        if(status != MS_SUCCESS) return status;        
+        if(status != MS_SUCCESS) return status;
       }
-    }  
+    }
 
-    if(lp->header) { 
+    if(lp->header) {
       if(msReturnPage(mapserv, lp->header, BROWSE, papszBuffer) != MS_SUCCESS) return MS_FAILURE;
     }
 
@@ -4346,13 +4296,13 @@ int msReturnNestedTemplateQuery(mapservObj* mapserv, char* pszMimeType, char **p
         }
       }
 
-      if(lp->resultcache->results[j].classindex >= 0 && lp->class[(int)(lp->resultcache->results[j].classindex)]->template) 
+      if(lp->resultcache->results[j].classindex >= 0 && lp->class[(int)(lp->resultcache->results[j].classindex)]->template)
         template = lp->class[(int)(lp->resultcache->results[j].classindex)]->template;
-      else 
+      else
         template = lp->template;
 
       if(msReturnPage(mapserv, template, QUERY, papszBuffer) != MS_SUCCESS) {
-        msFreeShape(&(mapserv->resultshape)); 
+        msFreeShape(&(mapserv->resultshape));
         return MS_FAILURE;
       }
 
@@ -4366,11 +4316,11 @@ int msReturnNestedTemplateQuery(mapservObj* mapserv, char* pszMimeType, char **p
       if(msReturnPage(mapserv, lp->footer, BROWSE, papszBuffer) != MS_SUCCESS) return MS_FAILURE;
     }
 
-    // msLayerClose(lp);
+    /* msLayerClose(lp); */
     mapserv->resultlayer = NULL;
   }
 
-  if(mapserv->map->web.footer) 
+  if(mapserv->map->web.footer)
     return msReturnPage(mapserv, mapserv->map->web.footer, BROWSE, papszBuffer);
 
   return MS_SUCCESS;
@@ -4378,63 +4328,67 @@ int msReturnNestedTemplateQuery(mapservObj* mapserv, char* pszMimeType, char **p
 
 int msReturnOpenLayersPage(mapservObj *mapserv)
 {
-    int i;
-    char *buffer = NULL, *layer = NULL;
-    const char *tmpUrl = NULL;
-    char *openlayersUrl = olUrl;
-    char *projection = NULL;
-
-    /* 2 CGI parameters are used in the template. we need to transform them
-     * to be sure the case match during the template processing. We also
-     * need to search the SRS/CRS parameter to get the projection info. OGC
-     * services version >= 1.3.0 uses CRS rather than SRS */
-    for( i=0; i<mapserv->request->NumParams; i++)
-    {
-        if( (strcasecmp(mapserv->request->ParamNames[i], "SRS") == 0) ||
-            (strcasecmp(mapserv->request->ParamNames[i], "CRS") == 0) ) {
-            projection = mapserv->request->ParamValues[i];
-        }
-        else if(strcasecmp(mapserv->request->ParamNames[i], "LAYERS") == 0) {
-            free(mapserv->request->ParamNames[i]);
-            mapserv->request->ParamNames[i] = msStrdup("LAYERS");
-        }
-        else if(strcasecmp(mapserv->request->ParamNames[i], "VERSION") == 0) {
-            free(mapserv->request->ParamNames[i]);
-            mapserv->request->ParamNames[i] = msStrdup("VERSION");
-        }
-    }
-
-    /* check if the environment variable or config MS_OPENLAYERS_JS_URL is set */
-    tmpUrl = msGetConfigOption(mapserv->map, "MS_OPENLAYERS_JS_URL");
-    if (tmpUrl)
-        openlayersUrl = (char*)tmpUrl;
-    else if (getenv("MS_OPENLAYERS_JS_URL")) 
-        openlayersUrl = getenv("MS_OPENLAYERS_JS_URL");
-
-    if (mapserv->Mode == BROWSE) {
-        msSetError(MS_WMSERR, "At least one layer name required in LAYERS.",
-                   "msWMSLoadGetMapParams()");
-        layer = processLine(mapserv, olLayerMapServerTag, NULL, BROWSE);
+  int i;
+  char *buffer = NULL, *layer = NULL;
+  const char *tmpUrl = NULL;
+  char *openlayersUrl = olUrl;
+  char *projection = NULL;
+  char *format = NULL;
+
+  /* 2 CGI parameters are used in the template. we need to transform them
+   * to be sure the case match during the template processing. We also
+   * need to search the SRS/CRS parameter to get the projection info. OGC
+   * services version >= 1.3.0 uses CRS rather than SRS */
+  for( i=0; i<mapserv->request->NumParams; i++) {
+    if( (strcasecmp(mapserv->request->ParamNames[i], "SRS") == 0) ||
+        (strcasecmp(mapserv->request->ParamNames[i], "CRS") == 0) ) {
+      projection = mapserv->request->ParamValues[i];
+    } else if(strcasecmp(mapserv->request->ParamNames[i], "LAYERS") == 0) {
+      free(mapserv->request->ParamNames[i]);
+      mapserv->request->ParamNames[i] = msStrdup("LAYERS");
+    } else if(strcasecmp(mapserv->request->ParamNames[i], "VERSION") == 0) {
+      free(mapserv->request->ParamNames[i]);
+      mapserv->request->ParamNames[i] = msStrdup("VERSION");
     }
-    else
-        layer = processLine(mapserv, olLayerWMSTag, NULL, BROWSE);
+  }
+  if(mapserv->map->outputformat->mimetype && *mapserv->map->outputformat->mimetype) {
+    format = mapserv->map->outputformat->mimetype;
+  }
 
-    buffer = processLine(mapserv, olTemplate, NULL, BROWSE);
-    buffer = msReplaceSubstring(buffer, "[openlayers_js_url]", openlayersUrl);
-    buffer = msReplaceSubstring(buffer, "[openlayers_layer]", layer);
-    if (projection)
-        buffer = msReplaceSubstring(buffer, "[openlayers_projection]", projection);
-    msIO_fwrite(buffer, strlen(buffer), 1, stdout);
-    free(layer);
-    free(buffer);
+  /* check if the environment variable or config MS_OPENLAYERS_JS_URL is set */
+  tmpUrl = msGetConfigOption(mapserv->map, "MS_OPENLAYERS_JS_URL");
+  if (tmpUrl)
+    openlayersUrl = (char*)tmpUrl;
+  else if (getenv("MS_OPENLAYERS_JS_URL"))
+    openlayersUrl = getenv("MS_OPENLAYERS_JS_URL");
+
+  if (mapserv->Mode == BROWSE) {
+    msSetError(MS_WMSERR, "At least one layer name required in LAYERS.",
+               "msWMSLoadGetMapParams()");
+    layer = processLine(mapserv, olLayerMapServerTag, NULL, BROWSE);
+  } else
+    layer = processLine(mapserv, olLayerWMSTag, NULL, BROWSE);
+
+  buffer = processLine(mapserv, olTemplate, NULL, BROWSE);
+  buffer = msReplaceSubstring(buffer, "[openlayers_js_url]", openlayersUrl);
+  buffer = msReplaceSubstring(buffer, "[openlayers_layer]", layer);
+  if (projection)
+    buffer = msReplaceSubstring(buffer, "[openlayers_projection]", projection);
+  if (format)
+    buffer = msReplaceSubstring(buffer, "[openlayers_format]", format);
+  else
+    buffer = msReplaceSubstring(buffer, "[openlayers_format]", "image/jpeg");
+  msIO_fwrite(buffer, strlen(buffer), 1, stdout);
+  free(layer);
+  free(buffer);
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 mapservObj *msAllocMapServObj()
 {
   mapservObj *mapserv = msSmallMalloc(sizeof(mapservObj));
-   
+
   mapserv->savemap=MS_FALSE;
   mapserv->savequery=MS_FALSE; /* should the query and/or map be saved  */
 
@@ -4457,9 +4411,9 @@ mapservObj *msAllocMapServObj()
 
   mapserv->fZoom=1;
   mapserv->Zoom=1; /* default for browsing */
-   
+
   mapserv->resultlayer=NULL;
-   
+
   mapserv->UseShapes=MS_FALSE;
 
   mapserv->mappnt.x=-1;
@@ -4470,23 +4424,23 @@ mapservObj *msAllocMapServObj()
   mapserv->Mode=BROWSE; /* can be BROWSE, QUERY, etc. */
 
   sprintf(mapserv->Id, "%ld%d", (long)time(NULL), (int)getpid());
-   
+
   mapserv->CoordSource=NONE;
   mapserv->ScaleDenom=0;
-   
+
   mapserv->ImgRows=-1;
   mapserv->ImgCols=-1;
-   
+
   mapserv->ImgExt.minx=-1;
   mapserv->ImgExt.miny=-1;
   mapserv->ImgExt.maxx=-1;
   mapserv->ImgExt.maxy=-1;
-   
+
   mapserv->ImgBox.minx=-1;
   mapserv->ImgBox.miny=-1;
   mapserv->ImgBox.maxx=-1;
   mapserv->ImgBox.maxy=-1;
-   
+
   mapserv->RefPnt.x=-1;
   mapserv->RefPnt.y=-1;
   mapserv->ImgPnt.x=-1;
@@ -4494,15 +4448,29 @@ mapservObj *msAllocMapServObj()
 
   mapserv->Buffer=0;
 
-  /* 
-  ** variables for multiple query results processing 
+  /*
+  ** variables for multiple query results processing
   */
   mapserv->RN=0; /* overall result number */
   mapserv->LRN=0; /* result number within a layer */
   mapserv->NL=0; /* total number of layers with results */
   mapserv->NR=0; /* total number or results */
   mapserv->NLR=0; /* number of results in a layer */
-   
+
+  mapserv->SearchMap=MS_FALSE; /* apply pan/zoom BEFORE doing the query (e.g. query the output image rather than the input image) */
+
+  mapserv->QueryFile=NULL;
+  mapserv->QueryLayer=NULL;
+  mapserv->SelectLayer=NULL;
+  mapserv->QueryLayerIndex=-1;
+  mapserv->SelectLayerIndex=-1;
+  mapserv->QueryItem=NULL;
+  mapserv->QueryString=NULL;
+  mapserv->ShapeIndex=-1;
+  mapserv->TileIndex=-1;
+  mapserv->QueryCoordSource=NONE;
+  mapserv->ZoomSize=0; /* zoom absolute magnitude (i.e. > 0) */
+
   return mapserv;
 }
 
@@ -4511,24 +4479,28 @@ void msFreeMapServObj(mapservObj* mapserv)
   int i;
 
   if(mapserv) {
-    if( mapserv->map )
-    {
-        msFreeMap(mapserv->map);
-        mapserv->map = NULL;
+    if( mapserv->map ) {
+      msFreeMap(mapserv->map);
+      mapserv->map = NULL;
     }
 
-    if( mapserv->request )
-    {
-        msFreeCgiObj(mapserv->request);
-        mapserv->request = NULL;
+    if( mapserv->request ) {
+      msFreeCgiObj(mapserv->request);
+      mapserv->request = NULL;
     }
 
-    for(i=0;i<mapserv->NumLayers;i++) 
+    for(i=0; i<mapserv->NumLayers; i++)
       msFree(mapserv->Layers[i]);
     msFree(mapserv->Layers);
 
     msFree(mapserv->icon);
 
+    msFree(mapserv->QueryItem);
+    msFree(mapserv->QueryString);
+    msFree(mapserv->QueryLayer);
+    msFree(mapserv->SelectLayer);
+    msFree(mapserv->QueryFile);
+
     msFree(mapserv);
   }
 }
@@ -4582,7 +4554,7 @@ int msGrowMapservLayers( mapservObj* mapserv )
 int msGenerateImages(mapservObj *mapserv, int bQueryMap, int bReturnOnError)
 {
   char buffer[1024];
-    
+
   if(mapserv) {
 
     /* render the map OR query map */
@@ -4590,7 +4562,7 @@ int msGenerateImages(mapservObj *mapserv, int bQueryMap, int bReturnOnError)
       imageObj *image = NULL;
 
       image = msDrawMap(mapserv->map, bQueryMap);
-      if(image) { 
+      if(image) {
         snprintf(buffer, sizeof(buffer), "%s%s%s.%s", mapserv->map->web.imagepath, mapserv->map->name, mapserv->Id, MS_IMAGE_EXTENSION(mapserv->map->outputformat));
 
         if(msSaveImage(mapserv->map, image, buffer) != MS_SUCCESS && bReturnOnError) {
@@ -4606,9 +4578,9 @@ int msGenerateImages(mapservObj *mapserv, int bQueryMap, int bReturnOnError)
     if(mapserv->map->legend.status == MS_ON) {
       imageObj *image = NULL;
       image = msDrawLegend(mapserv->map, MS_FALSE);
-      if(image) { 
+      if(image) {
         snprintf(buffer, sizeof(buffer), "%s%sleg%s.%s", mapserv->map->web.imagepath, mapserv->map->name, mapserv->Id, MS_IMAGE_EXTENSION(mapserv->map->outputformat));
-                
+
         if(msSaveImage(mapserv->map, image, buffer) != MS_SUCCESS && bReturnOnError) {
           msFreeImage(image);
           return MS_FAILURE;
@@ -4637,7 +4609,7 @@ int msGenerateImages(mapservObj *mapserv, int bQueryMap, int bReturnOnError)
     if(mapserv->map->reference.status == MS_ON) {
       imageObj *image;
       image = msDrawReferenceMap(mapserv->map);
-      if(image) { 
+      if(image) {
         snprintf(buffer, sizeof(buffer), "%s%sref%s.%s", mapserv->map->web.imagepath, mapserv->map->name, mapserv->Id, MS_IMAGE_EXTENSION(mapserv->map->outputformat));
         if(msSaveImage(mapserv->map, image, buffer) != MS_SUCCESS && bReturnOnError) {
           msFreeImage(image);
@@ -4647,18 +4619,18 @@ int msGenerateImages(mapservObj *mapserv, int bQueryMap, int bReturnOnError)
       } else if(bReturnOnError)
         return MS_FAILURE;
     }
-        
+
   }
-    
+
   return MS_SUCCESS;
 }
 
 /*
-** Utility function to open a template file, process it and 
-** and return into a buffer the processed template. Uses the 
-** template file from the web object. Returns NULL if there is 
+** Utility function to open a template file, process it and
+** and return into a buffer the processed template. Uses the
+** template file from the web object. Returns NULL if there is
 ** an error.
-*/ 
+*/
 char *msProcessTemplate(mapObj *map, int bGenerateImages, char **names, char **values, int numentries)
 {
   char *pszBuffer = NULL;
@@ -4677,7 +4649,7 @@ char *msProcessTemplate(mapObj *map, int bGenerateImages, char **names, char **v
       msFreeCharArray(mapserv->request->ParamValues, mapserv->request->NumParams);
       mapserv->request->ParamNames = names;
       mapserv->request->ParamValues = values;
-      mapserv->request->NumParams = numentries;    
+      mapserv->request->NumParams = numentries;
     }
 
     /*
@@ -4695,8 +4667,8 @@ char *msProcessTemplate(mapObj *map, int bGenerateImages, char **names, char **v
     ** TODO : use web minscaledenom/maxscaledenom depending on the scale.
     */
     if(msReturnPage(mapserv, mapserv->map->web.template, BROWSE, &pszBuffer) != MS_SUCCESS) {
-        msFree(pszBuffer);
-        pszBuffer = NULL;
+      msFree(pszBuffer);
+      pszBuffer = NULL;
     }
 
     /* Don't free the map and names and values arrays since they were passed by reference. */
@@ -4730,7 +4702,7 @@ char *msProcessLegendTemplate(mapObj *map, char **names, char **values, int nume
       msFreeCharArray(mapserv->request->ParamValues, mapserv->request->NumParams);
       mapserv->request->ParamNames = names;
       mapserv->request->ParamValues = values;
-      mapserv->request->NumParams = numentries;    
+      mapserv->request->NumParams = numentries;
     }
 
     pszOutBuf = generateLegendTemplate(mapserv);
@@ -4767,7 +4739,7 @@ char *msProcessQueryTemplate(mapObj *map, int bGenerateImages, char **names, cha
       msFreeCharArray(mapserv->request->ParamValues, mapserv->request->NumParams);
       mapserv->request->ParamNames = names;
       mapserv->request->ParamValues = values;
-      mapserv->request->NumParams = numentries;    
+      mapserv->request->NumParams = numentries;
     }
 
     if(bGenerateImages)
diff --git a/maptemplate.h b/maptemplate.h
index 21e323f..712eee5 100644
--- a/maptemplate.h
+++ b/maptemplate.h
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -42,23 +42,23 @@
 
 enum coordSources {NONE, FROMIMGPNT, FROMIMGBOX, FROMIMGSHAPE, FROMREFPNT, FROMUSERPNT, FROMUSERBOX, FROMUSERSHAPE, FROMBUF, FROMSCALE, FROMTILE};
 
-enum modes {BROWSE, ZOOMIN, ZOOMOUT, MAP, LEGEND, LEGENDICON, REFERENCE, SCALEBAR, COORDINATE, 
-            QUERY, NQUERY, ITEMQUERY, ITEMNQUERY, 
-            FEATUREQUERY, FEATURENQUERY, ITEMFEATUREQUERY, ITEMFEATURENQUERY, 
-            INDEXQUERY, TILE, OWS, WFS};
+enum modes {BROWSE, ZOOMIN, ZOOMOUT, MAP, LEGEND, LEGENDICON, REFERENCE, SCALEBAR, COORDINATE,
+            QUERY, NQUERY, ITEMQUERY, ITEMNQUERY,
+            FEATUREQUERY, FEATURENQUERY, ITEMFEATUREQUERY, ITEMFEATURENQUERY,
+            INDEXQUERY, TILE, OWS, WFS
+           };
 
 
 /* struct mapservObj
  * Global structure used by templates and mapserver CGI interface.
- * 
+ *
  * This structur was created to seperate template functionality
  * from the main mapserv file. Instead of moving all template
  * related functions in a new file (maptemplate.c) and change
  * their signatures to pass all global variables, we created this
  * structure with all global variables needed by template.
 */
-typedef struct
-{
+typedef struct {
   /* should the query and/or map be saved */
   int savemap, savequery;
 
@@ -70,12 +70,12 @@ typedef struct
 
   char **Layers;
   char *icon; /* layer:class combination that defines a legend icon */
-    
+
   int NumLayers; /* number of layers specfied by a use */
   int MaxLayers; /* Allocated size of Layers[] array */
 
   layerObj *resultlayer;
-   
+
   int UseShapes; /* are results of a query to be used in calculating an extent of some sort */
 
   shapeObj resultshape;
@@ -83,31 +83,49 @@ typedef struct
   rectObj RawExt;
 
   pointObj mappnt;
-  
-  double fZoom, Zoom;     
+
+  double fZoom, Zoom;
   int ZoomDirection; /* whether zooming in or out, default is pan or 0 */
 
   int Mode; /* can be BROWSE, QUERY, etc. */
-   
+
   int TileMode; /* can be GMAP, VE */
   char *TileCoords; /* for GMAP: 0 0 1; for VE: 013021023 */
-   
+
   char Id[IDSIZE]; /* big enough for time + pid */
-   
+
   int CoordSource;
   double ScaleDenom; /* used to create a map extent around a point */
 
   int ImgRows, ImgCols;
   rectObj ImgExt; /* Existing image's mapextent */
   rectObj ImgBox;
-   
+
   pointObj RefPnt;
   pointObj ImgPnt;
 
   double Buffer;
- 
-  /* 
-  ** variables for multiple query results processing 
+
+  int SearchMap; /* apply pan/zoom BEFORE doing the query (e.g. query the output image rather than the input image) */
+
+  char *QueryFile;
+  char *QueryLayer;
+  char *SelectLayer;
+  int QueryLayerIndex;
+  int SelectLayerIndex;
+
+  char *QueryItem;
+  char *QueryString;
+
+  int ShapeIndex;
+  int TileIndex;
+
+  int QueryCoordSource;
+
+  int ZoomSize; /* zoom absolute magnitude (i.e. > 0) */
+
+  /*
+  ** variables for multiple query results processing
   */
   int RN; /* overall result number */
   int LRN; /* result number within a layer */
@@ -115,8 +133,8 @@ typedef struct
   int NR; /* total number or results */
   int NLR; /* number of results in a layer */
 } mapservObj;
-   
-   
+
+
 
 /*! \fn msAllocMapServObj
  * Allocate memory for all variables in strusture
@@ -147,18 +165,18 @@ MS_DLL_EXPORT char *generateLegendTemplate(mapservObj *msObj);
 MS_DLL_EXPORT int msGenerateImages(mapservObj *msObj, int bQueryMap, int bReturnOnError);
 
 
-MS_DLL_EXPORT char *msProcessTemplate(mapObj *map, int bGenerateImages, 
-                         char **names, char **values, 
-                         int numentries);
+MS_DLL_EXPORT char *msProcessTemplate(mapObj *map, int bGenerateImages,
+                                      char **names, char **values,
+                                      int numentries);
 
 MS_DLL_EXPORT char *msProcessLegendTemplate(mapObj *map,
-                              char **names, char **values, 
-                              int numentries);
+    char **names, char **values,
+    int numentries);
 
 MS_DLL_EXPORT char *msProcessQueryTemplate(mapObj *map,
-                             int bGenerateImages, 
-                             char **names, char **values, 
-                             int numentries);
+    int bGenerateImages,
+    char **names, char **values,
+    int numentries);
 
 MS_DLL_EXPORT int msGrowMapservLayers( mapservObj* msObj );
 
diff --git a/mapthread.c b/mapthread.c
index ee9137c..013f8de 100644
--- a/mapthread.c
+++ b/mapthread.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -28,7 +28,7 @@
  ****************************************************************************/
 
 /******************************************************************************
- 
+
             THREAD-SAFE SUPPORT IN MAPSERVER
             ================================
 
@@ -37,81 +37,81 @@ If thread safety is enabled the USE_THREAD macro will be defined.
 Thread API (mapthread.h/c)
 --------------------------
 
-This API is made available to avoid having dependencies on different 
+This API is made available to avoid having dependencies on different
 thread libraries in lots of places in MapServer.  It is intended to provide
 minimal services required by mapserver and isn't intended to be broadly useful.
-It should be available for Win32 and pthreads environments.  It should be 
+It should be available for Win32 and pthreads environments.  It should be
 possible to implement for other thread libraries if needed.
 
-  int msGetThreadId(): 
-  	Returns the current threads integer id.  This can be used for making 
-        some information thread specific, as has been done for the global 
-        error context in maperror.c. 
+  int msGetThreadId():
+    Returns the current threads integer id.  This can be used for making
+        some information thread specific, as has been done for the global
+        error context in maperror.c.
 
-  void msAcquireLock(int): 
+  void msAcquireLock(int):
         Acquires the indicated Mutex.  If it is already held by another thread
         then this thread will block till the other thread releases it.  If
         this thread already holds the mutex then behaviour is undefined.  If
         the mutex id is not valid (not in the range 0 to TLOCK_STATIC_MAX)
-        then results are undefined. 
+        then results are undefined.
 
   void msReleaseLock(int):
-        Releases the indicated mutex.  If the lock id is invalid, or if the 
+        Releases the indicated mutex.  If the lock id is invalid, or if the
         mutex is not currently held by this thread then results are undefined.
 
 It is incredibly important to ensure that any mutex that is acquired is
 released as soon as possible.  Any flow of control that could result in a
-mutex not being release is going to be a disaster.  
+mutex not being release is going to be a disaster.
 
 The mutex numbers are defined in mapthread.h with the TLOCK_* codes.  If you
 need a new mutex, add a #define in mapthread.h for it.  Currently there is
-no "dynamic" mutex allocation, but this could be added.  
+no "dynamic" mutex allocation, but this could be added.
 
 
 Making Things Thread-safe
 -------------------------
 
 Generally, to make MapServer thread-safe it is necessary to ensure that
-different threads aren't read and updating common datastructures at the same 
-time and that all appropriate state be kept thread specific.   
+different threads aren't read and updating common datastructures at the same
+time and that all appropriate state be kept thread specific.
 
 Generally this will mean:
   o The previously global error status (errorObj ms_error) is now thread
-    specific.  Use msGetErrorObj() to get the current threads error state. 
+    specific.  Use msGetErrorObj() to get the current threads error state.
 
   o Use of subcomponents that are not thread safe need to be protected by
-    a Mutex (lock).  
+    a Mutex (lock).
 
-Currently a mutex is used for the entire map file parsing operation 
-(msLoadMap() in mapfile.c) since the yacc parser uses a number of global 
-variables.  
+Currently a mutex is used for the entire map file parsing operation
+(msLoadMap() in mapfile.c) since the yacc parser uses a number of global
+variables.
 
-It is also done with pj_init() from PROJ.4 since this does not appear to be 
-thread safe.  It isn't yet clear if pj_transform() is thread safe. 
+It is also done with pj_init() from PROJ.4 since this does not appear to be
+thread safe.  It isn't yet clear if pj_transform() is thread safe.
 
 It is expected that mutexes will need to be employed in a variety of other
 places to ensure serialized access to risky functionality.  This may apply
-to sublibraries like GDAL for instance. 
+to sublibraries like GDAL for instance.
 
 If a new section that is not thread-safe is identified (and assuming it
 can't be internally modified to make it thread-safe easily), it is necessary
-to define a new mutex (#define a TLOCK code in mapthread.h), and then 
-surround the resource with acquire and release lock calls. 
+to define a new mutex (#define a TLOCK code in mapthread.h), and then
+surround the resource with acquire and release lock calls.
 
-eg. 
+eg.
     msAcquireLock( TLOCK_PROJ );
     if( !(p->proj = pj_init(p->numargs, p->args)) ) {
         msReleaseLock( TLOCK_PROJ );
-        msSetError(MS_PROJERR, pj_strerrno(pj_errno), 
-                   "msProcessProjection()");	  
+        msSetError(MS_PROJERR, pj_strerrno(pj_errno),
+                   "msProcessProjection()");
         return(-1);
     }
-    
+
     msReleaseLock( TLOCK_PROJ );
 
-It is imperative that any acquired locks be released on all possible 
-control paths or else the MapServer will lock up as other thread try to 
-acquire the lock and block forever. 
+It is imperative that any acquired locks be released on all possible
+control paths or else the MapServer will lock up as other thread try to
+acquire the lock and block forever.
 
 
 Other Thread-safe Issues
@@ -121,13 +121,13 @@ Some issues are not easily corrected with Mutexes or other similar
 mechanisms.  The following restrictions currently apply to MapServer when
 trying to use it in thread-safe mode.  Note that failure to adhere to these
 constraints will not usually generate nice error messages, instead operation
-will just fail sometimes. 
+will just fail sometimes.
 
 1) It is currently assumed that a mapObj belongs only to one thread at a time.
-That is, there is no effort to syncronize access to a mapObj itself. 
+That is, there is no effort to syncronize access to a mapObj itself.
 
 2) Stuff that results in a chdir() call are problematic.  In particular, the
-.map file SHAPEPATH directive should not be used.  Use full paths to data 
+.map file SHAPEPATH directive should not be used.  Use full paths to data
 files instead.
 
 ******************************************************************************/
@@ -137,14 +137,15 @@ files instead.
 #include "mapserver.h"
 #include "mapthread.h"
 
-MS_CVSID("$Id$")
+
 
 #if defined(USE_THREAD)
 static int thread_debug = 0;
 
-static char *lock_names[] = 
-{ NULL, "PARSER", "GDAL", "ERROROBJ", "PROJ", "TTF", "POOL", "SDE", 
-  "ORACLE", "OWS", "LAYER_VTABLE", "IOCONTEXT", "TMPFILE", "DEBUGOBJ", NULL };
+static char *lock_names[] = {
+  NULL, "PARSER", "GDAL", "ERROROBJ", "PROJ", "TTF", "POOL", "SDE",
+  "ORACLE", "OWS", "LAYER_VTABLE", "IOCONTEXT", "TMPFILE", "DEBUGOBJ", NULL
+};
 #endif
 
 /************************************************************************/
@@ -167,17 +168,17 @@ static pthread_mutex_t mutex_locks[TLOCK_MAX];
 void msThreadInit()
 
 {
-    static pthread_mutex_t core_lock = PTHREAD_MUTEX_INITIALIZER;
+  static pthread_mutex_t core_lock = PTHREAD_MUTEX_INITIALIZER;
 
-    if( thread_debug )
-        fprintf( stderr, "msThreadInit() (posix)\n" );
+  if( thread_debug )
+    fprintf( stderr, "msThreadInit() (posix)\n" );
 
-    pthread_mutex_lock( &core_lock );
+  pthread_mutex_lock( &core_lock );
 
-    for( ; mutexes_initialized < TLOCK_STATIC_MAX; mutexes_initialized++ )
-        pthread_mutex_init( mutex_locks + mutexes_initialized, NULL );
+  for( ; mutexes_initialized < TLOCK_STATIC_MAX; mutexes_initialized++ )
+    pthread_mutex_init( mutex_locks + mutexes_initialized, NULL );
 
-    pthread_mutex_unlock( &core_lock );
+  pthread_mutex_unlock( &core_lock );
 }
 
 /************************************************************************/
@@ -187,7 +188,7 @@ void msThreadInit()
 int msGetThreadId()
 
 {
-    return (int) pthread_self();
+  return (int) pthread_self();
 }
 
 /************************************************************************/
@@ -197,16 +198,16 @@ int msGetThreadId()
 void msAcquireLock( int nLockId )
 
 {
-    if( mutexes_initialized == 0 )
-        msThreadInit();
+  if( mutexes_initialized == 0 )
+    msThreadInit();
 
-    assert( nLockId >= 0 && nLockId < mutexes_initialized );
+  assert( nLockId >= 0 && nLockId < mutexes_initialized );
 
-    if( thread_debug )
-        fprintf( stderr, "msAcquireLock(%d/%s) (posix)\n", 
-                 nLockId, lock_names[nLockId] );
+  if( thread_debug )
+    fprintf( stderr, "msAcquireLock(%d/%s) (posix)\n",
+             nLockId, lock_names[nLockId] );
 
-    pthread_mutex_lock( mutex_locks + nLockId );
+  pthread_mutex_lock( mutex_locks + nLockId );
 }
 
 /************************************************************************/
@@ -216,14 +217,14 @@ void msAcquireLock( int nLockId )
 void msReleaseLock( int nLockId )
 
 {
-    assert( mutexes_initialized > 0 );
-    assert( nLockId >= 0 && nLockId < mutexes_initialized );
+  assert( mutexes_initialized > 0 );
+  assert( nLockId >= 0 && nLockId < mutexes_initialized );
 
-    if( thread_debug )
-        fprintf( stderr, "msReleaseLock(%d/%s) (posix)\n", 
-                 nLockId, lock_names[nLockId] );
+  if( thread_debug )
+    fprintf( stderr, "msReleaseLock(%d/%s) (posix)\n",
+             nLockId, lock_names[nLockId] );
 
-    pthread_mutex_unlock( mutex_locks + nLockId );
+  pthread_mutex_unlock( mutex_locks + nLockId );
 }
 
 #endif /* defined(USE_THREAD) && !defined(_WIN32) */
@@ -248,24 +249,24 @@ static HANDLE mutex_locks[TLOCK_MAX];
 void msThreadInit()
 
 {
-/* static pthread_mutex_t core_lock = PTHREAD_MUTEX_INITIALIZER; */
-    static HANDLE core_lock = NULL;
+  /* static pthread_mutex_t core_lock = PTHREAD_MUTEX_INITIALIZER; */
+  static HANDLE core_lock = NULL;
 
-    if( mutexes_initialized >= TLOCK_STATIC_MAX )
-        return;
+  if( mutexes_initialized >= TLOCK_STATIC_MAX )
+    return;
 
-    if( thread_debug )
-        fprintf( stderr, "msThreadInit() (win32)\n" );
+  if( thread_debug )
+    fprintf( stderr, "msThreadInit() (win32)\n" );
 
-    if( core_lock == NULL )
-        core_lock = CreateMutex( NULL, TRUE, NULL );
-    else
-        WaitForSingleObject( core_lock, INFINITE );
+  if( core_lock == NULL )
+    core_lock = CreateMutex( NULL, TRUE, NULL );
+  else
+    WaitForSingleObject( core_lock, INFINITE );
 
-    for( ; mutexes_initialized < TLOCK_STATIC_MAX; mutexes_initialized++ )
-        mutex_locks[mutexes_initialized] = CreateMutex( NULL, FALSE, NULL );
+  for( ; mutexes_initialized < TLOCK_STATIC_MAX; mutexes_initialized++ )
+    mutex_locks[mutexes_initialized] = CreateMutex( NULL, FALSE, NULL );
 
-    ReleaseMutex( core_lock );
+  ReleaseMutex( core_lock );
 }
 
 /************************************************************************/
@@ -275,7 +276,7 @@ void msThreadInit()
 int msGetThreadId()
 
 {
-    return (int) GetCurrentThreadId();
+  return (int) GetCurrentThreadId();
 }
 
 /************************************************************************/
@@ -285,16 +286,16 @@ int msGetThreadId()
 void msAcquireLock( int nLockId )
 
 {
-    if( mutexes_initialized == 0 )
-        msThreadInit();
+  if( mutexes_initialized == 0 )
+    msThreadInit();
 
-    assert( nLockId >= 0 && nLockId < mutexes_initialized );
+  assert( nLockId >= 0 && nLockId < mutexes_initialized );
 
-    if( thread_debug )
-        fprintf( stderr, "msAcquireLock(%d/%s) (win32)\n", 
-                 nLockId, lock_names[nLockId] );
+  if( thread_debug )
+    fprintf( stderr, "msAcquireLock(%d/%s) (win32)\n",
+             nLockId, lock_names[nLockId] );
 
-    WaitForSingleObject( mutex_locks[nLockId], INFINITE );
+  WaitForSingleObject( mutex_locks[nLockId], INFINITE );
 }
 
 /************************************************************************/
@@ -304,14 +305,14 @@ void msAcquireLock( int nLockId )
 void msReleaseLock( int nLockId )
 
 {
-    assert( mutexes_initialized > 0 );
-    assert( nLockId >= 0 && nLockId < mutexes_initialized );
+  assert( mutexes_initialized > 0 );
+  assert( nLockId >= 0 && nLockId < mutexes_initialized );
 
-    if( thread_debug )
-        fprintf( stderr, "msReleaseLock(%d/%s) (win32)\n", 
-                 nLockId, lock_names[nLockId] );
+  if( thread_debug )
+    fprintf( stderr, "msReleaseLock(%d/%s) (win32)\n",
+             nLockId, lock_names[nLockId] );
 
-    ReleaseMutex( mutex_locks[nLockId] );
+  ReleaseMutex( mutex_locks[nLockId] );
 }
 
 #endif /* defined(USE_THREAD) && defined(_WIN32) */
diff --git a/mapthread.h b/mapthread.h
index c322db9..4b413bc 100644
--- a/mapthread.h
+++ b/mapthread.h
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -35,10 +35,10 @@ extern "C" {
 #endif
 
 #ifdef USE_THREAD
-void msThreadInit(void);
-int msGetThreadId(void);
-void msAcquireLock(int);
-void msReleaseLock(int);
+  void msThreadInit(void);
+  int msGetThreadId(void);
+  void msAcquireLock(int);
+  void msReleaseLock(int);
 #else
 #define msThreadInit()
 #define msGetThreadId() (0)
@@ -46,13 +46,13 @@ void msReleaseLock(int);
 #define msReleaseLock(x)
 #endif
 
-/*
-** lock ids - note there is a corresponding lock_names[] array in 
-** mapthread.c that needs to be extended when new ids are added.
-*/
+  /*
+  ** lock ids - note there is a corresponding lock_names[] array in
+  ** mapthread.c that needs to be extended when new ids are added.
+  */
 
-#define TLOCK_PARSER	1
-#define TLOCK_GDAL	2
+#define TLOCK_PARSER  1
+#define TLOCK_GDAL  2
 #define TLOCK_ERROROBJ  3
 #define TLOCK_PROJ      4
 #define TLOCK_TTF       5
@@ -65,6 +65,7 @@ void msReleaseLock(int);
 #define TLOCK_TMPFILE   12
 #define TLOCK_DEBUGOBJ  13
 #define TLOCK_OGR       14
+#define TLOCK_TIME      15
 
 #define TLOCK_STATIC_MAX 20
 #define TLOCK_MAX       100
diff --git a/maptile.c b/maptile.c
index 30b2af6..052cbb1 100644
--- a/maptile.c
+++ b/maptile.c
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id$ 
+ * $Id$
  *
  * Project:  MapServer
  * Purpose:  MapServer Tile Access API
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -30,8 +30,10 @@
 #include "maptile.h"
 #include "mapproject.h"
 
-static void msTileResetMetatileLevel(mapObj *map) {
-  hashTableObj *meta = &(map->web.metadata); 
+#ifdef USE_TILE_API
+static void msTileResetMetatileLevel(mapObj *map)
+{
+  hashTableObj *meta = &(map->web.metadata);
   const char *zero = "0";
   const char *value = NULL;
 
@@ -45,34 +47,35 @@ static void msTileResetMetatileLevel(mapObj *map) {
     msInsertHashTable(meta, "tile_metatile_level", zero);
   }
 }
+#endif
 
 /************************************************************************
  *                            msTileGetGMapCoords                       *
  ************************************************************************/
-static int msTileGetGMapCoords(const char *coordstring, int *x, int *y, int *zoom) {
+static int msTileGetGMapCoords(const char *coordstring, int *x, int *y, int *zoom)
+{
 
   int num_coords = 0;
   char **coords = NULL;
-  
+
   if( coordstring ) {
     coords = msStringSplit(coordstring, ' ', &(num_coords));
     if( num_coords != 3 ) {
       msSetError(MS_WEBERR, "Invalid number of tile coordinates (should be three).", "msTileSetup()");
       return MS_FAILURE;
     }
-  } 
-  else {
+  } else {
     msSetError(MS_WEBERR, "Tile parameter not set.", "msTileSetup()");
     return MS_FAILURE;
   }
-  
+
   if( x )
     *x = strtol(coords[0], NULL, 10);
   if( y )
     *y = strtol(coords[1], NULL, 10);
   if( zoom )
     *zoom = strtol(coords[2], NULL, 10);
- 
+
   return MS_SUCCESS;
 }
 
@@ -80,63 +83,63 @@ static int msTileGetGMapCoords(const char *coordstring, int *x, int *y, int *zoo
 /************************************************************************
  *                            msTileSetParams                           *
  ************************************************************************/
-static void msTileGetParams(mapObj *map, tileParams *params) {
+static void msTileGetParams(mapObj *map, tileParams *params)
+{
 
   const char *value = NULL;
-  hashTableObj *meta = &(map->web.metadata); 
-  
+  hashTableObj *meta = &(map->web.metadata);
+
   params->tile_size = SPHEREMERC_IMAGE_SIZE;
-  
+
   /* Check for tile buffer, set to buffer==0 as default */
   if((value = msLookupHashTable(meta, "tile_map_edge_buffer")) != NULL) {
     params->map_edge_buffer = atoi(value);
     if(map->debug)
       msDebug("msTileSetParams(): tile_map_edge_buffer = %d\n", params->map_edge_buffer);
-  }  
-  else
-    params->map_edge_buffer = 0;    
+  } else
+    params->map_edge_buffer = 0;
 
   /* Check for metatile size, set to tile==metatile as default */
   if((value = msLookupHashTable(meta, "tile_metatile_level")) != NULL) {
     params->metatile_level = atoi(value);
     /* Quietly force metatile_level to be sane */
-    if( params->metatile_level < 0 ) 
+    if( params->metatile_level < 0 )
       params->metatile_level = 0;
-    if( params->metatile_level > 2 ) 
+    if( params->metatile_level > 2 )
       params->metatile_level = 2;
     if(map->debug)
       msDebug("msTileSetParams(): tile_metatile_level = %d\n", params->metatile_level);
-  }  
-  else
+  } else
     params->metatile_level = 0;
-  
+
 }
 
 /************************************************************************
  *                            msTileExtractSubTile                      *
- *                                                                      * 
+ *                                                                      *
  ************************************************************************/
-static imageObj* msTileExtractSubTile(const mapservObj *msObj, const imageObj *img) {
- 
-  int width, height, mini, minj, maxi, maxj;
+static imageObj* msTileExtractSubTile(const mapservObj *msObj, const imageObj *img)
+{
+
+  int width, mini, minj;
   int zoom = 2;
   imageObj* imgOut = NULL;
   tileParams params;
   rendererVTableObj *renderer;
   rasterBufferObj imgBuffer;
-  
-  if( !MS_RENDERER_PLUGIN(msObj->map->outputformat) 
-		  || msObj->map->outputformat->renderer != img->format->renderer ||
-		  ! MS_MAP_RENDERER(msObj->map)->supports_pixel_buffer ) {
-	  msSetError(MS_MISCERR,"unsupported or mixed renderers","msTileExtractSubTile()");
-	  return NULL;
+
+  if( !MS_RENDERER_PLUGIN(msObj->map->outputformat)
+      || msObj->map->outputformat->renderer != img->format->renderer ||
+      ! MS_MAP_RENDERER(msObj->map)->supports_pixel_buffer ) {
+    msSetError(MS_MISCERR,"unsupported or mixed renderers","msTileExtractSubTile()");
+    return NULL;
   }
   renderer = MS_MAP_RENDERER(msObj->map);
-  
+
   if (renderer->getRasterBufferHandle((imageObj*)img,&imgBuffer) != MS_SUCCESS) {
-	  return NULL;
+    return NULL;
   }
-  
+
 
   /*
   ** Load the metatiling information from the map file.
@@ -147,23 +150,19 @@ static imageObj* msTileExtractSubTile(const mapservObj *msObj, const imageObj *i
   ** Initialize values for the metatile clip area.
   */
   width = img->width - 2*params.map_edge_buffer;
-  height = img->height - 2*params.map_edge_buffer;
   mini = params.map_edge_buffer;
   minj = params.map_edge_buffer;
-  maxi = img->width - params.map_edge_buffer - 1;
-  maxj = img->height - params.map_edge_buffer - 1;
-
+  
   if( msObj->TileMode == TILE_GMAP ) {
     int x, y, zoom;
-    
+
     if( msObj->TileCoords ) {
       if( msTileGetGMapCoords(msObj->TileCoords, &x, &y, &zoom) == MS_FAILURE )
         return NULL;
-    } 
-    else {
+    } else {
       msSetError(MS_WEBERR, "Tile parameter not set.", "msTileSetup()");
       return NULL;
-    }    
+    }
 
     if(msObj->map->debug)
       msDebug("msTileExtractSubTile(): gmaps coords (x: %d, y: %d)\n",x,y);
@@ -177,50 +176,47 @@ static imageObj* msTileExtractSubTile(const mapservObj *msObj, const imageObj *i
 
     if(msObj->map->debug)
       msDebug("msTileExtractSubTile(): gmaps image coords (x: %d, y: %d)\n",x,y);
-    
+
     mini = mini + x * params.tile_size;
     minj = minj + y * params.tile_size;
 
-  }
-  else if( msObj->TileMode == TILE_VE ) {
+  } else if( msObj->TileMode == TILE_VE ) {
     int tsize;
     int i = 0;
     char j = 0;
-  
-    if( strlen( msObj->TileCoords ) - params.metatile_level < 0 ) {
+
+    if( (int)strlen( msObj->TileCoords ) - params.metatile_level < 0 ) {
       return(NULL);
     }
-  
-    /* 
+
+    /*
     ** Process the last elements of the VE coordinate string to place the
     ** requested tile in the context of the metatile
     */
-    for( i = strlen( msObj->TileCoords ) - params.metatile_level; 
-         i < strlen( msObj->TileCoords ); 
-         i++ ) 
-    {
+    for( i = strlen( msObj->TileCoords ) - params.metatile_level;
+         i < strlen( msObj->TileCoords );
+         i++ ) {
       j = msObj->TileCoords[i];
       tsize = width / zoom;
       if( j == '1' || j == '3' ) mini += tsize;
       if( j == '2' || j == '3' ) minj += tsize;
       zoom *= 2;
     }
-  }
-  else {
+  } else {
     return(NULL); /* Huh? Should have a mode. */
   }
-  
+
   imgOut = msImageCreate(params.tile_size, params.tile_size, msObj->map->outputformat, NULL, NULL, msObj->map->resolution, msObj->map->defresolution, NULL);
-  
+
   if( imgOut == NULL ) {
     return NULL;
   }
-  
+
   if(msObj->map->debug)
     msDebug("msTileExtractSubTile(): extracting (%d x %d) tile, top corner (%d, %d)\n",params.tile_size,params.tile_size,mini,minj);
-  
-  
-  
+
+
+
   renderer->mergeRasterBuffer(imgOut,&imgBuffer,1.0,mini, minj,0, 0,params.tile_size, params.tile_size);
 
   return imgOut;
@@ -229,30 +225,31 @@ static imageObj* msTileExtractSubTile(const mapservObj *msObj, const imageObj *i
 
 /************************************************************************
  *                            msTileSetup                               *
- *                                                                      * 
+ *                                                                      *
  *  Called from mapserv.c, this is where the fun begins                 *
  *  Set up projections and test the parameters for legality.            *
  ************************************************************************/
-int msTileSetup(mapservObj* msObj) {
-#ifdef USE_TILE_API 
+int msTileSetup(mapservObj* msObj)
+{
+#ifdef USE_TILE_API
 
   char *outProjStr = NULL;
   tileParams params;
-  
+
   /*
   ** Load the metatiling information from the map file.
   */
   msTileGetParams(msObj->map, &params);
 
-  /* 
-  ** Ensure all the LAYERs have a projection. 
-  */  
-  if( msTileSetProjections(msObj->map) != 0 ) {
+  /*
+  ** Ensure all the LAYERs have a projection.
+  */
+  if( msMapSetLayerProjections(msObj->map) != 0 ) {
     return(MS_FAILURE);
   }
 
-  /* 
-  ** Set the projection string for this mode. 
+  /*
+  ** Set the projection string for this mode.
   */
   if( msObj->TileMode == TILE_GMAP || msObj->TileMode == TILE_VE ) {
     outProjStr = SPHEREMERC_PROJ4;
@@ -263,30 +260,29 @@ int msTileSetup(mapservObj* msObj) {
     msSetError(MS_CGIERR, "Unable to load projection string.", "msTileSetup()");
     return MS_FAILURE;
   }
-  
+
   /*
-  ** Set up the output extents for this tilemode and tile coordinates 
+  ** Set up the output extents for this tilemode and tile coordinates
   */
   if( msObj->TileMode == TILE_GMAP ) {
 
     int x, y, zoom;
     double zoomfactor;
-    
+
     if( msObj->TileCoords ) {
       if( msTileGetGMapCoords(msObj->TileCoords, &x, &y, &zoom) == MS_FAILURE )
         return MS_FAILURE;
-    } 
-    else {
+    } else {
       msSetError(MS_WEBERR, "Tile parameter not set.", "msTileSetup()");
       return MS_FAILURE;
     }
-    
+
     if( params.metatile_level >= zoom ) {
       msTileResetMetatileLevel(msObj->map);
     }
-    
+
     zoomfactor = pow(2.0, (double)zoom);
-    
+
     /*
     ** Check the input request for sanity.
     */
@@ -299,9 +295,8 @@ int msTileSetup(mapservObj* msObj) {
       return(MS_FAILURE);
     }
 
-  }
-  else if ( msObj->TileMode == TILE_VE ) {
-    
+  } else if ( msObj->TileMode == TILE_VE ) {
+
     if( strspn( msObj->TileCoords, "0123" ) < strlen( msObj->TileCoords ) ) {
       msSetError(MS_CGIERR, "VE tile name should only include characters 0, 1, 2 and 3.", "msTileSetup()");
       return(MS_FAILURE);
@@ -311,11 +306,10 @@ int msTileSetup(mapservObj* msObj) {
       msTileResetMetatileLevel(msObj->map);
     }
 
-  }
-  else {
+  } else {
     return(MS_FAILURE); /* Huh? Should have a mode. */
   }
-     
+
   return MS_SUCCESS;
 #else
   msSetError(MS_CGIERR, "Tile API is not available.", "msTileSetup()");
@@ -327,32 +321,32 @@ int msTileSetup(mapservObj* msObj) {
 
 /************************************************************************
  *                            msTileSetExtent                           *
- *                                                                      * 
+ *                                                                      *
  *  Based on the input parameters, set the output extent for this       *
  *  tile.                                                               *
  ************************************************************************/
-int msTileSetExtent(mapservObj* msObj) {
-#ifdef USE_TILE_API 
-  
+int msTileSetExtent(mapservObj* msObj)
+{
+#ifdef USE_TILE_API
+
   mapObj *map = msObj->map;
-  double	dx, dy, buffer;
+  double  dx, dy, buffer;
   tileParams params;
-  
+
   /* Read the tile-mode map file parameters */
   msTileGetParams(msObj->map, &params);
 
   if( msObj->TileMode == TILE_GMAP ) {
     int x, y, zoom;
     double zoomfactor, tilesize, xmin, xmax, ymin, ymax;
-    
+
     if( msObj->TileCoords ) {
       if( msTileGetGMapCoords(msObj->TileCoords, &x, &y, &zoom) == MS_FAILURE )
         return MS_FAILURE;
-    } 
-    else {
+    } else {
       msSetError(MS_WEBERR, "Tile parameter not set.", "msTileSetup()");
       return MS_FAILURE;
-    }    
+    }
 
     if(map->debug)
       msDebug("msTileSetExtent(): gmaps coords (x: %d, y: %d, z: %d)\n",x,y,zoom);
@@ -371,7 +365,7 @@ int msTileSetExtent(mapservObj* msObj) {
       msDebug("msTileSetExtent(): gmaps metacoords (x: %d, y: %d, z: %d)\n",x,y,zoom);
 
     zoomfactor = pow(2.0, (double)zoom);
-    
+
     /*
     ** Calculate the ground extents of the tile request.
     */
@@ -381,14 +375,13 @@ int msTileSetExtent(mapservObj* msObj) {
     xmax = ((x + 1) * tilesize) - (SPHEREMERC_GROUND_SIZE / 2.0);
     ymin = (SPHEREMERC_GROUND_SIZE / 2.0) - ((y + 1) * tilesize);
     ymax = (SPHEREMERC_GROUND_SIZE / 2.0) - (y * tilesize);
-    
+
     map->extent.minx = xmin;
     map->extent.maxx = xmax;
     map->extent.miny = ymin;
     map->extent.maxy = ymax;
-  
-  }
-  else if( msObj->TileMode == TILE_VE ) {
+
+  } else if( msObj->TileMode == TILE_VE ) {
 
     double minx = SPHEREMERC_GROUND_SIZE / -2.0;
     double miny = SPHEREMERC_GROUND_SIZE / -2.0;
@@ -398,8 +391,8 @@ int msTileSetExtent(mapservObj* msObj) {
     double tsize;
     int i = 0;
     char j = 0;
-    
-    /* 
+
+    /*
     ** Walk down the VE URL string, adjusting the extent each time.
     ** For meta-tiling cases, we stop early, to draw a larger image.
     */
@@ -412,18 +405,17 @@ int msTileSetExtent(mapservObj* msObj) {
       if( j == '0' || j == '1' ) miny += tsize;
       zoom *= 2.0;
     }
-    
+
     map->extent.minx = minx;
     map->extent.maxx = maxx;
     map->extent.miny = miny;
     map->extent.maxy = maxy;
 
-  }
-  else {
+  } else {
     return(MS_FAILURE); /* Huh? Should have a mode. */
   }
 
-  /* 
+  /*
   ** Set the output tile size.
   */
   msObj->ImgCols = SPHEREMERC_IMAGE_SIZE << params.metatile_level;
@@ -436,18 +428,18 @@ int msTileSetExtent(mapservObj* msObj) {
 
   /*
   ** Add the gutters
-  ** First calculate ground units in the buffer at current extent 
+  ** First calculate ground units in the buffer at current extent
   */
   buffer = params.map_edge_buffer * (map->extent.maxx - map->extent.minx) / (double)map->width;
-  /* 
-  ** Then adjust the map extents out by that amount 
+  /*
+  ** Then adjust the map extents out by that amount
   */
   map->extent.minx -= buffer;
   map->extent.maxx += buffer;
   map->extent.miny -= buffer;
   map->extent.maxy += buffer;
-  /* 
-  ** Finally adjust the map image size by the pixel buffer 
+  /*
+  ** Finally adjust the map image size by the pixel buffer
   */
   map->width += 2 * params.map_edge_buffer;
   map->height += 2 * params.map_edge_buffer;
@@ -456,8 +448,8 @@ int msTileSetExtent(mapservObj* msObj) {
 
   if(map->debug)
     msDebug("msTileSetExtent(): buffered image size (%d x %d)\n",map->width,map->height);
-  
-  /* 
+
+  /*
   ** Adjust the extents inwards by 1/2 pixel so they are from
   ** center-of-pixel to center-of-pixel, instead of edge-to-edge.
   ** This is the way mapserver does it.
@@ -469,12 +461,12 @@ int msTileSetExtent(mapservObj* msObj) {
   map->extent.miny += dy*0.5;
   map->extent.maxy -= dy*0.5;
 
-  /* 
-  ** Ensure the labelcache buffer is greater than the tile buffer. 
+  /*
+  ** Ensure the labelcache buffer is greater than the tile buffer.
   */
   if( params.map_edge_buffer > 0 ) {
     const char *value;
-    hashTableObj *meta = &(map->web.metadata); 
+    hashTableObj *meta = &(map->web.metadata);
     char tilebufferstr[64];
 
     /* Write the tile buffer to a string */
@@ -493,11 +485,11 @@ int msTileSetExtent(mapservObj* msObj) {
       msInsertHashTable(meta, "labelcache_map_edge_buffer", tilebufferstr);
     }
   }
-  
+
   if(map->debug) {
     msDebug( "msTileSetExtent (%f, %f) (%f, %f)\n", map->extent.minx, map->extent.miny, map->extent.maxx, map->extent.maxy);
   }
- 
+
   return MS_SUCCESS;
 #else
   msSetError(MS_CGIERR, "Tile API is not available.", "msTileSetExtent()");
@@ -506,52 +498,10 @@ int msTileSetExtent(mapservObj* msObj) {
 }
 
 
-/************************************************************************
- *                            msTileSetProjections                      *
- *                                                                      * 
- *   Ensure that all the layers in the map file have a projection       *
- *   by copying the map-level projection to all layers than have no     *
- *   projection.                                                        *
- ************************************************************************/
-
-int msTileSetProjections(mapObj* map) {
-
-  char *mapProjStr = NULL;
-  int i;
-    
-  if (map->projection.numargs <= 0) {
-    msSetError(MS_WMSERR, "Cannot set new SRS on a map that doesn't "
-                          "have any projection set. Please make sure your mapfile "
-                          "has a PROJECTION defined at the top level.", 
-                          "msTileSetProjectionst()");
-    return(MS_FAILURE);
-  }
-
-  for(i=0; i<map->numlayers; i++) {
-    /* This layer is turned on and needs a projection? */
-    if (GET_LAYER(map, i)->projection.numargs <= 0 &&
-        GET_LAYER(map, i)->status != MS_OFF &&
-        GET_LAYER(map, i)->transform == MS_TRUE) {
-   
-      /* Fetch main map projection string only now that we need it */
-      if (mapProjStr == NULL)
-        mapProjStr = msGetProjectionString(&(map->projection));
-      
-      /* Set the projection to the map file projection */  
-      if (msLoadProjectionString(&(GET_LAYER(map, i)->projection), mapProjStr) != 0) {
-        msSetError(MS_CGIERR, "Unable to set projection on layer.", "msTileSetProjectionst()");
-        return(MS_FAILURE);
-      }
-      GET_LAYER(map, i)->project = MS_TRUE;
-    }
-  }
-  msFree(mapProjStr);
-  return(MS_SUCCESS);
-}
 
 /************************************************************************
  *                            msDrawTile                                *
- *                                                                      * 
+ *                                                                      *
  *   Draw the tile once with gutters, metatiling and buffers, then      *
  *   clip out the final tile.                                           *
  *   WARNING: Call msTileSetExtent() first or this will be a pointless  *
@@ -566,8 +516,7 @@ imageObj* msTileDraw(mapservObj *msObj)
   img = msDrawMap(msObj->map, MS_FALSE);
   if( img == NULL )
     return NULL;
-  if( params.metatile_level > 0 || params.map_edge_buffer > 0 )
-  {
+  if( params.metatile_level > 0 || params.map_edge_buffer > 0 ) {
     imageObj *tmp = msTileExtractSubTile(msObj, img);
     msFreeImage(img);
     if( tmp == NULL )
diff --git a/maptile.h b/maptile.h
index 3f48f08..8467080 100644
--- a/maptile.h
+++ b/maptile.h
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id$ 
+ * $Id$
  *
  * Project:  MapServer
  * Purpose:  MapServer Tile Access API
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -26,22 +26,22 @@
  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  * DEALINGS IN THE SOFTWARE.
  ****************************************************************************/
- 
+
 #include "mapserver.h"
 #include "maptemplate.h"
 
 #ifdef USE_PROJ
 #define USE_TILE_API 1
-#endif 
+#endif
 
 #define SPHEREMERC_PROJ4 "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +units=m +k=1.0 +nadgrids=@null"
 #define SPHEREMERC_GROUND_SIZE (20037508.34*2)
 #define SPHEREMERC_IMAGE_SIZE 0x0100
 
 enum tileModes { TILE_GMAP, TILE_VE };
- 
-MS_DLL_EXPORT int msTileSetup(mapservObj *msObj); 
-MS_DLL_EXPORT int msTileSetExtent(mapservObj *msObj); 
+
+MS_DLL_EXPORT int msTileSetup(mapservObj *msObj);
+MS_DLL_EXPORT int msTileSetExtent(mapservObj *msObj);
 MS_DLL_EXPORT int msTileSetProjections(mapObj *map);
 MS_DLL_EXPORT imageObj* msTileDraw(mapservObj *msObj);
 
diff --git a/maptime.c b/maptime.c
index 2e8b63d..5e992ba 100644
--- a/maptime.c
+++ b/maptime.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -35,13 +35,13 @@
 #include "mapserver.h"
 #include "maptime.h"
 #include "maperror.h"
+#include "mapthread.h"
 
-MS_CVSID("$Id$")
 
 typedef struct {
   char pattern[64];
   ms_regex_t *regex;
-  char  format[32];  
+  char  format[32];
   char userformat[32];
   MS_TIME_RESOLUTION resolution;
 } timeFormatObj;
@@ -67,6 +67,42 @@ timeFormatObj ms_timeFormats[MS_NUMTIMEFORMATS] = {
 int *ms_limited_pattern = NULL;
 int ms_num_limited_pattern;
 
+int ms_time_inited = 0;
+int msTimeSetup() {
+  if(!ms_time_inited) {
+    msAcquireLock(TLOCK_TIME);
+    if(!ms_time_inited) {
+      int i;
+      for(i=0;i<MS_NUMTIMEFORMATS;i++) {
+        ms_timeFormats[i].regex = msSmallMalloc(sizeof(ms_regex_t));
+        if(0!=ms_regcomp(ms_timeFormats[i].regex, ms_timeFormats[i].pattern, MS_REG_EXTENDED|MS_REG_NOSUB)) {
+          msSetError(MS_REGEXERR, "Failed to compile expression (%s).", "msTimeSetup()", ms_timeFormats[i].pattern);
+          return MS_FAILURE;
+          /* TODO: free already inited regexes */
+        }
+      }
+      ms_limited_pattern = (int *)msSmallMalloc(sizeof(int)*MS_NUMTIMEFORMATS);
+      ms_num_limited_pattern = 0;
+      ms_time_inited = 1;
+    }
+    msReleaseLock(TLOCK_TIME);
+  }
+  return MS_SUCCESS;
+}
+
+void msTimeCleanup() {
+  if(ms_time_inited) {
+    int i;
+    for(i=0;i<MS_NUMTIMEFORMATS;i++) {
+      if(ms_timeFormats[i].regex) {
+        ms_regfree(ms_timeFormats[i].regex);
+        msFree(ms_timeFormats[i].regex);
+      }
+    }
+    msFree(ms_limited_pattern);
+  }
+}
+
 void msTimeInit(struct tm *time)
 {
   /* set all members to zero */
@@ -83,7 +119,8 @@ void msTimeInit(struct tm *time)
   return;
 }
 
-static int compareIntVals(int a, int b) { 
+static int compareIntVals(int a, int b)
+{
   if(a<b) return -1;
   else if(a>b) return 1;
   else return 0;
@@ -99,7 +136,7 @@ int msDateCompare(struct tm *time1, struct tm *time2)
     return result; /* not equal based on month */
   else if((result = compareIntVals(time1->tm_mday, time2->tm_mday)) != 0)
     return result; /* not equal based on day of month */
-  
+
   return(0); /* must be equal */
 }
 
@@ -127,11 +164,11 @@ int msTimeCompare(struct tm *time1, struct tm *time2)
 #include <sys/timeb.h>
 void msGettimeofday(struct mstimeval* tp, void* tzp)
 {
-    struct _timeb theTime;
- 
-    _ftime(&theTime);
-    tp->tv_sec = theTime.time;
-    tp->tv_usec = theTime.millitm * 1000;
+  struct _timeb theTime;
+
+  _ftime(&theTime);
+  tp->tv_sec = theTime.time;
+  tp->tv_usec = theTime.millitm * 1000;
 }
 #endif
 
@@ -142,7 +179,7 @@ char *strptime( const char *buf, const char *format, struct tm *timeptr );
 
 char *msStrptime(const char *s, const char *format, struct tm *tm)
 {
-    return strptime(s, format, tm);
+  return strptime(s, format, tm);
 }
 
 /**
@@ -151,118 +188,103 @@ char *msStrptime(const char *s, const char *format, struct tm *tm)
  */
 int msTimeMatchPattern(char *timestring, char *timeformat)
 {
-    int i =-1;
-
-    /* match the pattern format first and then check if the time string  */
-    /* matchs the pattern. If it is the case retrurn the MS_TRUE */
-    for (i=0; i<MS_NUMTIMEFORMATS; i++)
-    {
-        if (strcasecmp(ms_timeFormats[i].userformat, timeformat) == 0)
-          break;
-    }
-     
-    if (i >= 0 && i < MS_NUMTIMEFORMATS)
-    {
-        if(!ms_timeFormats[i].regex)
-        {
-            ms_timeFormats[i].regex = (ms_regex_t *) msSmallMalloc(sizeof(ms_regex_t));
-            ms_regcomp(ms_timeFormats[i].regex, 
-                    ms_timeFormats[i].pattern, MS_REG_EXTENDED|MS_REG_NOSUB);
-        }
-        if (ms_regexec(ms_timeFormats[i].regex, timestring, 0,NULL, 0) == 0)
-          return MS_TRUE;
-        
-    }
+  int i =-1;
+  if(msTimeSetup() != MS_SUCCESS) {
     return MS_FALSE;
+  }
+
+  /* match the pattern format first and then check if the time string  */
+  /* matchs the pattern. If it is the case retrurn the MS_TRUE */
+  for (i=0; i<MS_NUMTIMEFORMATS; i++) {
+    if (strcasecmp(ms_timeFormats[i].userformat, timeformat) == 0)
+      break;
+  }
+
+  if (i >= 0 && i < MS_NUMTIMEFORMATS) {
+    int match = ms_regexec(ms_timeFormats[i].regex, timestring, 0,NULL, 0);
+    if(match == 0)
+      return MS_TRUE;
+  }
+  return MS_FALSE;
 }
 
 
 void msUnsetLimitedPatternToUse()
 {
-    if (ms_limited_pattern &&  ms_num_limited_pattern > 0)
-      free(ms_limited_pattern);
-
-    ms_num_limited_pattern = 0;
+  msTimeSetup();
+  ms_num_limited_pattern = 0;
 }
 
 void msSetLimitedPattersToUse(char *patternstring)
 {
-    int *limitedpatternindice = NULL;
-    int numpatterns=0, i=0, j=0, ntmp=0;
-    char **patterns = NULL;
-
-    limitedpatternindice = (int *)msSmallMalloc(sizeof(int)*MS_NUMTIMEFORMATS);
-    
-    /* free previous setting */
-    msUnsetLimitedPatternToUse();
-
-    if (patternstring)
-    {
-        patterns = msStringSplit(patternstring, ',', &ntmp);
-        if (patterns && ntmp >= 1)
-        {
-            
-            for (i=0; i<ntmp; i++)
-            {
-                for (j=0; j<MS_NUMTIMEFORMATS; j++)
-                {
-                    if (strcasecmp( ms_timeFormats[j].userformat, patterns[i]) ==0)
-                    {
-                        limitedpatternindice[numpatterns] = j;
-                        numpatterns++;
-                        break;
-                    }
-                }
-            }
-            
-            msFreeCharArray(patterns, ntmp);
+  int *limitedpatternindice = NULL;
+  int numpatterns=0, i=0, j=0, ntmp=0;
+  char **patterns = NULL;
+  msTimeSetup();
+
+  limitedpatternindice = (int *)msSmallMalloc(sizeof(int)*MS_NUMTIMEFORMATS);
+
+  /* free previous setting */
+  msUnsetLimitedPatternToUse();
+
+  if (patternstring) {
+    patterns = msStringSplit(patternstring, ',', &ntmp);
+    if (patterns && ntmp >= 1) {
+
+      for (i=0; i<ntmp; i++) {
+        for (j=0; j<MS_NUMTIMEFORMATS; j++) {
+          if (strcasecmp( ms_timeFormats[j].userformat, patterns[i]) ==0) {
+            limitedpatternindice[numpatterns] = j;
+            numpatterns++;
+            break;
+          }
         }
+      }
+
+      msFreeCharArray(patterns, ntmp);
     }
+  }
 
-    if (numpatterns > 0)
-    {
-        ms_limited_pattern = (int *)msSmallMalloc(sizeof(int)*numpatterns);
-        for (i=0; i<numpatterns; i++)
-          ms_limited_pattern[i] = limitedpatternindice[i];
+  if (numpatterns > 0) {
+    for (i=0; i<numpatterns; i++)
+      ms_limited_pattern[i] = limitedpatternindice[i];
 
-        ms_num_limited_pattern = numpatterns;
-        free (limitedpatternindice);
-    }
-                                            
+    ms_num_limited_pattern = numpatterns;
+  }
+  free (limitedpatternindice);
 }
 
 
 
-int msParseTime(const char *string, struct tm *tm) {
+int msParseTime(const char *string, struct tm *tm)
+{
   int i, indice = 0;
   int num_patterns = 0;
   
+  if(msTimeSetup() != MS_SUCCESS) {
+    return MS_FALSE;
+  }
+
   /* if limited patterns are set, use then. Else use all the */
   /* patterns defined */
-  if (ms_limited_pattern &&  ms_num_limited_pattern > 0)
+  if (ms_num_limited_pattern > 0)
     num_patterns = ms_num_limited_pattern;
   else
     num_patterns = MS_NUMTIMEFORMATS;
 
   for(i=0; i<num_patterns; i++) {
-      if (ms_num_limited_pattern > 0)
-        indice = ms_limited_pattern[i];
-      else
-        indice = i;
-
-      if(!ms_timeFormats[indice].regex) { /* compile the expression */
-      ms_timeFormats[indice].regex = (ms_regex_t *) msSmallMalloc(sizeof(ms_regex_t)); 
-      if(ms_regcomp(ms_timeFormats[indice].regex, ms_timeFormats[indice].pattern, MS_REG_EXTENDED|MS_REG_NOSUB) != 0) {
-	msSetError(MS_REGEXERR, "Failed to compile expression (%s).", "msParseTime()", ms_timeFormats[indice].pattern);
-	return(MS_FALSE);
-      }
-    }  
+    int match;
+    if (ms_num_limited_pattern > 0)
+      indice = ms_limited_pattern[i];
+    else
+      indice = i;
 
+    match = ms_regexec(ms_timeFormats[indice].regex, string, 0,NULL, 0);
     /* test the expression against the string */
-    if(ms_regexec(ms_timeFormats[indice].regex, string, 0, NULL, 0) == 0) 
-    { /* match    */
-        msStrptime(string, ms_timeFormats[indice].format, tm);
-        return(MS_TRUE);
+    if(match == 0) {
+      /* match    */
+      msStrptime(string, ms_timeFormats[indice].format, tm);
+      return(MS_TRUE);
     }
   }
 
@@ -275,208 +297,185 @@ int msParseTime(const char *string, struct tm *tm) {
  */
 int msTimeGetResolution(const char *timestring)
 {
-    int i=0;
+  int i=0;
+
+  if (!timestring)
+    return -1;
 
-    if (!timestring)
+  for(i=0; i<MS_NUMTIMEFORMATS; i++) {
+    ms_regex_t *regex = (ms_regex_t *) msSmallMalloc(sizeof(ms_regex_t));
+    if(ms_regcomp(regex, ms_timeFormats[i].pattern,
+                  MS_REG_EXTENDED|MS_REG_NOSUB) != 0) {
+      msSetError(MS_REGEXERR, "Failed to compile expression (%s).", "msParseTime()", ms_timeFormats[i].pattern);
+      msFree(regex);
       return -1;
+    }
+    /* test the expression against the string */
+    if(ms_regexec(regex, timestring, 0, NULL, 0) == 0) {
+      /* match    */
+      ms_regfree(regex);
+      msFree(regex);
+      return ms_timeFormats[i].resolution;
+    }
+    ms_regfree(regex);
+    msFree(regex);
+  }
 
-     for(i=0; i<MS_NUMTIMEFORMATS; i++)
-     {
-         if(!ms_timeFormats[i].regex) 
-         {
-             ms_timeFormats[i].regex = (ms_regex_t *) msSmallMalloc(sizeof(ms_regex_t));                
-             if(ms_regcomp(ms_timeFormats[i].regex, ms_timeFormats[i].pattern, 
-                        MS_REG_EXTENDED|MS_REG_NOSUB) != 0) 
-             {
-                 msSetError(MS_REGEXERR, "Failed to compile expression (%s).", "msParseTime()", ms_timeFormats[i].pattern);
-                 return -1;
-             }
-         }
-         /* test the expression against the string */
-         if(ms_regexec(ms_timeFormats[i].regex, timestring, 0, NULL, 0) == 0) 
-         { /* match    */
-             return ms_timeFormats[i].resolution;
-         }
-     }
-      
-     return -1;
+  return -1;
 }
 
 
 int _msValidateTime(char *timestring,  const char *timeextent)
 {
-    int numelements, numextents, i, numranges;
-    struct tm  tmtimestart, tmtimeend, tmstart, tmend;
-    char **atimerange = NULL, **atimeelements= NULL, **atimeextents=NULL;
+  int numelements, numextents, i, numranges;
+  struct tm  tmtimestart, tmtimeend, tmstart, tmend;
+  char **atimerange = NULL, **atimeelements= NULL, **atimeextents=NULL;
 
-    if (!timestring || !timeextent)
-      return MS_FALSE;
+  if (!timestring || !timeextent)
+    return MS_FALSE;
 
-    if (strlen(timestring) <= 0 || 
-        strlen(timeextent) <= 0)
-       return MS_FALSE;
-  
+  if (strlen(timestring) <= 0 ||
+      strlen(timeextent) <= 0)
+    return MS_FALSE;
 
-    /* we first need to parse the timesting that is passed
-       so that we can determine if it is a descrete time
-       or a range */
-    
-    numelements = 0;
-    atimeelements = msStringSplit (timestring, '/', &numelements);
-    msTimeInit(&tmtimestart);
-    msTimeInit(&tmtimeend);
-
-    if (numelements == 1) /*descrete time*/
-    {
-        /*start end end times are the same*/
-        if (msParseTime(timestring, &tmtimestart) != MS_TRUE)
-        {       
-            msFreeCharArray(atimeelements, numelements);
-            return  MS_FALSE;
-        }
-        if (msParseTime(timestring, &tmtimeend) != MS_TRUE)
-        {
-            msFreeCharArray(atimeelements, numelements);
-            return  MS_FALSE;
-        }
+
+  /* we first need to parse the timesting that is passed
+     so that we can determine if it is a descrete time
+     or a range */
+
+  numelements = 0;
+  atimeelements = msStringSplit (timestring, '/', &numelements);
+  msTimeInit(&tmtimestart);
+  msTimeInit(&tmtimeend);
+
+  if (numelements == 1) { /*descrete time*/
+    /*start end end times are the same*/
+    if (msParseTime(timestring, &tmtimestart) != MS_TRUE) {
+      msFreeCharArray(atimeelements, numelements);
+      return  MS_FALSE;
     }
-    else if (numelements >=2)/*range */
-    {
-        if (msParseTime(atimeelements[0], &tmtimestart) != MS_TRUE)
-        {
-            msFreeCharArray(atimeelements, numelements);
-            return  MS_FALSE;
-        }
-        if (msParseTime(atimeelements[1], &tmtimeend) != MS_TRUE)
-        {
-            msFreeCharArray(atimeelements, numelements);
-            return  MS_FALSE;
-        }
+    if (msParseTime(timestring, &tmtimeend) != MS_TRUE) {
+      msFreeCharArray(atimeelements, numelements);
+      return  MS_FALSE;
     }
+  } else if (numelements >=2) { /*range */
+    if (msParseTime(atimeelements[0], &tmtimestart) != MS_TRUE) {
+      msFreeCharArray(atimeelements, numelements);
+      return  MS_FALSE;
+    }
+    if (msParseTime(atimeelements[1], &tmtimeend) != MS_TRUE) {
+      msFreeCharArray(atimeelements, numelements);
+      return  MS_FALSE;
+    }
+  }
 
-    msFreeCharArray(atimeelements, numelements);
-    
-
-    /* Now parse the time extent. Extents can be 
-      -  one range (2004-09-21/2004-09-25/resolution) 
-      -  multiple rages 2004-09-21/2004-09-25/res1,2004-09-21/2004-09-25/res2
-      - one value 2004-09-21
-      - mutiple values 2004-09-21,2004-09-22,2004-09-23
-    */
-    
-    numextents = 0;
-    atimeextents = msStringSplit (timeextent, ',', &numextents);
-    if (atimeextents == NULL || numextents <= 0)
-      return MS_FALSE;
-    
-    /*the time timestring should at be valid in one of the extents
-      defined */
-
-    for (i=0; i<numextents; i++)
-    {
-        /* build time structure for the extents */
-        msTimeInit(&tmstart);
-        msTimeInit(&tmend);
-        
-        numranges = 0;
-        atimerange = msStringSplit (atimeextents[i], '/', &numranges);
-        /* - one value 2004-09-21 */
-        if (numranges == 1)
-        {
-            /*time tested can either be descrete or a range */
-            
-            if (msParseTime(atimerange[0], &tmstart) == MS_TRUE &&
-                msParseTime(atimerange[0], &tmend) == MS_TRUE &&
-                msTimeCompare(&tmstart, &tmtimestart) <= 0 &&
-                msTimeCompare(&tmend, &tmtimeend) >= 0)
-            {
-                msFreeCharArray(atimerange, numranges);
-                msFreeCharArray(atimeextents, numextents);
-                return MS_TRUE;
-            }
-        }
-        /*2004-09-21/2004-09-25/res1*/
-        else if (numranges >= 2)
-        {
-            if (msParseTime(atimerange[0], &tmstart) == MS_TRUE &&
-                msParseTime(atimerange[1], &tmend) == MS_TRUE &&
-                msTimeCompare(&tmstart, &tmtimestart) <= 0 &&
-                msTimeCompare(&tmend, &tmtimeend) >= 0)
-            {
-                msFreeCharArray(atimerange, numranges);
-                msFreeCharArray(atimeextents, numextents);
-                return MS_TRUE;
-            }
-        }
-        msFreeCharArray(atimerange, numranges);
-        
+  msFreeCharArray(atimeelements, numelements);
 
-    }
-    msFreeCharArray(atimeextents, numextents);
+
+  /* Now parse the time extent. Extents can be
+    -  one range (2004-09-21/2004-09-25/resolution)
+    -  multiple rages 2004-09-21/2004-09-25/res1,2004-09-21/2004-09-25/res2
+    - one value 2004-09-21
+    - mutiple values 2004-09-21,2004-09-22,2004-09-23
+  */
+
+  numextents = 0;
+  atimeextents = msStringSplit (timeextent, ',', &numextents);
+  if (atimeextents == NULL || numextents <= 0)
     return MS_FALSE;
 
+  /*the time timestring should at be valid in one of the extents
+    defined */
+
+  for (i=0; i<numextents; i++) {
+    /* build time structure for the extents */
+    msTimeInit(&tmstart);
+    msTimeInit(&tmend);
+
+    numranges = 0;
+    atimerange = msStringSplit (atimeextents[i], '/', &numranges);
+    /* - one value 2004-09-21 */
+    if (numranges == 1) {
+      /*time tested can either be descrete or a range */
+
+      if (msParseTime(atimerange[0], &tmstart) == MS_TRUE &&
+          msParseTime(atimerange[0], &tmend) == MS_TRUE &&
+          msTimeCompare(&tmstart, &tmtimestart) <= 0 &&
+          msTimeCompare(&tmend, &tmtimeend) >= 0) {
+        msFreeCharArray(atimerange, numranges);
+        msFreeCharArray(atimeextents, numextents);
+        return MS_TRUE;
+      }
+    }
+    /*2004-09-21/2004-09-25/res1*/
+    else if (numranges >= 2) {
+      if (msParseTime(atimerange[0], &tmstart) == MS_TRUE &&
+          msParseTime(atimerange[1], &tmend) == MS_TRUE &&
+          msTimeCompare(&tmstart, &tmtimestart) <= 0 &&
+          msTimeCompare(&tmend, &tmtimeend) >= 0) {
+        msFreeCharArray(atimerange, numranges);
+        msFreeCharArray(atimeextents, numextents);
+        return MS_TRUE;
+      }
+    }
+    msFreeCharArray(atimerange, numranges);
+
+
+  }
+  msFreeCharArray(atimeextents, numextents);
+  return MS_FALSE;
+
 }
 
 
 
 int msValidateTimeValue(char *timestring, const char *timeextent)
 {
-    char **atimes =  NULL;
-    int i, numtimes=0;
-
-    /* we need to validate the time passsed in the request */
-    /* against the time extent defined */
-
-    if (!timestring || !timeextent)
-      return MS_FALSE;
-
-   
-    /* parse the time string. We support descrete times (eg 2004-09-21), */
-    /* multiple times (2004-09-21, 2004-09-22, ...) */
-    /* and range(s) (2004-09-21/2004-09-25, 2004-09-27/2004-09-29) */
-    if (strstr(timestring, ",") == NULL &&
-        strstr(timestring, "/") == NULL) /* discrete time */
-    {
-        return _msValidateTime(timestring,  timeextent);
-        
-    }
-    else
-    {
-        atimes = msStringSplit (timestring, ',', &numtimes);
-        if (numtimes >=1) /* multiple times */
-        {
-
-            if (strstr(atimes[0], "/") == NULL) /* multiple descrete times */
-            {
-                for (i=0; i<numtimes; i++)
-                {
-                    if (_msValidateTime(atimes[i], timeextent) == MS_FALSE)
-                    {
-                        msFreeCharArray(atimes, numtimes);
-                        return MS_FALSE;
-                    }
-                }
-                msFreeCharArray(atimes, numtimes);
-                return MS_TRUE;
-            }
-            else /* multiple ranges */
-            {
-                for (i=0; i<numtimes; i++)
-                {
-                    if (_msValidateTime(atimes[i], timeextent) == MS_FALSE)
-                    {
-                        msFreeCharArray(atimes, numtimes);
-                        return MS_FALSE;
-                    }
-                     
-                 }
-                 msFreeCharArray(atimes, numtimes);
-                 return MS_TRUE;
-            }
-            
+  char **atimes =  NULL;
+  int i, numtimes=0;
+
+  /* we need to validate the time passsed in the request */
+  /* against the time extent defined */
+
+  if (!timestring || !timeextent)
+    return MS_FALSE;
+
+
+  /* parse the time string. We support descrete times (eg 2004-09-21), */
+  /* multiple times (2004-09-21, 2004-09-22, ...) */
+  /* and range(s) (2004-09-21/2004-09-25, 2004-09-27/2004-09-29) */
+  if (strstr(timestring, ",") == NULL &&
+      strstr(timestring, "/") == NULL) { /* discrete time */
+    return _msValidateTime(timestring,  timeextent);
+
+  } else {
+    atimes = msStringSplit (timestring, ',', &numtimes);
+    if (numtimes >=1) { /* multiple times */
+
+      if (strstr(atimes[0], "/") == NULL) { /* multiple descrete times */
+        for (i=0; i<numtimes; i++) {
+          if (_msValidateTime(atimes[i], timeextent) == MS_FALSE) {
+            msFreeCharArray(atimes, numtimes);
+            return MS_FALSE;
+          }
+        }
+        msFreeCharArray(atimes, numtimes);
+        return MS_TRUE;
+      } else { /* multiple ranges */
+        for (i=0; i<numtimes; i++) {
+          if (_msValidateTime(atimes[i], timeextent) == MS_FALSE) {
+            msFreeCharArray(atimes, numtimes);
+            return MS_FALSE;
+          }
+
         }
+        msFreeCharArray(atimes, numtimes);
+        return MS_TRUE;
+      }
 
     }
-    return MS_FALSE;
+
+  }
+  return MS_FALSE;
 }
 
diff --git a/maptime.h b/maptime.h
index fb89df2..dc5ebb4 100644
--- a/maptime.h
+++ b/maptime.h
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -36,8 +36,8 @@
  */
 #if defined(_WIN32) && !defined(__CYGWIN__)
 struct mstimeval {
-    long    tv_sec;         /* seconds */
-    long    tv_usec;        /* and microseconds */
+  long    tv_sec;         /* seconds */
+  long    tv_usec;        /* and microseconds */
 };
 MS_DLL_EXPORT void msGettimeofday(struct mstimeval *t, void *__not_used_here__);
 #else
@@ -46,18 +46,17 @@ MS_DLL_EXPORT void msGettimeofday(struct mstimeval *t, void *__not_used_here__);
 #  define  msGettimeofday(t,u) gettimeofday(t,u)
 #endif
 
-typedef enum 
-{
-    TIME_RESOLUTION_UNDEFINED = -1,
-    TIME_RESOLUTION_MICROSECOND =0,
-    TIME_RESOLUTION_MILLISECOND =1,
-    TIME_RESOLUTION_SECOND =2,
-    TIME_RESOLUTION_MINUTE =3,
-    TIME_RESOLUTION_HOUR =4,
-    TIME_RESOLUTION_DAY =5,
-    TIME_RESOLUTION_MONTH =6,
-    TIME_RESOLUTION_YEAR =7
-}MS_TIME_RESOLUTION;
+typedef enum {
+  TIME_RESOLUTION_UNDEFINED = -1,
+  TIME_RESOLUTION_MICROSECOND =0,
+  TIME_RESOLUTION_MILLISECOND =1,
+  TIME_RESOLUTION_SECOND =2,
+  TIME_RESOLUTION_MINUTE =3,
+  TIME_RESOLUTION_HOUR =4,
+  TIME_RESOLUTION_DAY =5,
+  TIME_RESOLUTION_MONTH =6,
+  TIME_RESOLUTION_YEAR =7
+} MS_TIME_RESOLUTION;
 
 /* function prototypes */
 void msTimeInit(struct tm *time);
@@ -69,6 +68,7 @@ int msTimeMatchPattern(char *timestring, char *pattern);
 void msSetLimitedPattersToUse(char *patternstring);
 void msUnsetLimitedPatternToUse(void);
 int msTimeGetResolution(const char *timestring);
+void msTimeCleanup();
 
 int msValidateTimeValue(char *timestring, const char *timeextent);
 
diff --git a/maptree.c b/maptree.c
index 6ba081d..178fb42 100644
--- a/maptree.c
+++ b/maptree.c
@@ -2,7 +2,7 @@
  * $Id$
  *
  * Project:  MapServer
- * Purpose:  .qix spatial index implementation.  Derived from shapelib, and 
+ * Purpose:  .qix spatial index implementation.  Derived from shapelib, and
  *           relicensed with permission of Frank Warmerdam (shapelib author).
  * Author:   Steve Lime
  *
@@ -16,7 +16,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -31,7 +31,7 @@
 #include "mapserver.h"
 #include "maptree.h"
 
-MS_CVSID("$Id$")
+
 
 /* -------------------------------------------------------------------- */
 /*      If the following is 0.5, nodes will be split in half.  If it    */
@@ -47,155 +47,147 @@ static int treeAddShapeId(treeObj *tree, int id, rectObj rect);
 static void SwapWord( int length, void * wordP )
 {
   int i;
-  uchar	temp;
-  
-  for( i=0; i < length/2; i++ )
-    {
-      temp = ((uchar *) wordP)[i];
-      ((uchar *)wordP)[i] = ((uchar *) wordP)[length-i-1];
-      ((uchar *) wordP)[length-i-1] = temp;
-    }
+  uchar temp;
+
+  for( i=0; i < length/2; i++ ) {
+    temp = ((uchar *) wordP)[i];
+    ((uchar *)wordP)[i] = ((uchar *) wordP)[length-i-1];
+    ((uchar *) wordP)[length-i-1] = temp;
+  }
 }
 
 static void * SfRealloc( void * pMem, int nNewSize )
 
 {
-    if( pMem == NULL )
-        return( (void *) malloc(nNewSize) );
-    else
-        return( (void *) realloc(pMem,nNewSize) );
+  if( pMem == NULL )
+    return( (void *) malloc(nNewSize) );
+  else
+    return( (void *) realloc(pMem,nNewSize) );
 }
 
 static treeNodeObj *treeNodeCreate(rectObj rect)
 {
-    treeNodeObj	*node;
+  treeNodeObj *node;
 
-    node = (treeNodeObj *) msSmallMalloc(sizeof(treeNodeObj));
+  node = (treeNodeObj *) msSmallMalloc(sizeof(treeNodeObj));
 
-    node->numshapes = 0;
-    node->ids = NULL;
+  node->numshapes = 0;
+  node->ids = NULL;
 
-    node->numsubnodes = 0;
+  node->numsubnodes = 0;
 
-    memcpy(&(node->rect), &(rect), sizeof(rectObj));
+  memcpy(&(node->rect), &(rect), sizeof(rectObj));
 
-    return node;
+  return node;
 }
 
 
 SHPTreeHandle msSHPDiskTreeOpen(const char * pszTree, int debug)
 {
-    char		*pszFullname, *pszBasename;
-    SHPTreeHandle	psTree;
-  
-    char		pabyBuf[16];
-    int			i;
-    char		bBigEndian;
-    
-  /* -------------------------------------------------------------------- */
-  /*	Establish the byte order on this machine.			    */
-  /* -------------------------------------------------------------------- */
-    i = 1;
-    if( *((uchar *) &i) == 1 )
-      bBigEndian = MS_FALSE;
-    else
-      bBigEndian = MS_TRUE;
-  
-  /* -------------------------------------------------------------------- */
-  /*	Initialize the info structure.					    */
-  /* -------------------------------------------------------------------- */
-    psTree = (SHPTreeHandle) msSmallMalloc(sizeof(SHPTreeInfo));
-  
-  /* -------------------------------------------------------------------- */
-  /*	Compute the base (layer) name.  If there is any extension	    */
-  /*	on the passed in filename we will strip it off.			    */
-  /* -------------------------------------------------------------------- */
-    pszBasename = (char *) msSmallMalloc(strlen(pszTree)+5);
-    strcpy( pszBasename, pszTree );
-    for( i = strlen(pszBasename)-1; 
+  char    *pszFullname, *pszBasename;
+  SHPTreeHandle psTree;
+
+  char    pabyBuf[16];
+  int     i;
+  char    bBigEndian;
+
+  /* -------------------------------------------------------------------- */
+  /*  Establish the byte order on this machine.         */
+  /* -------------------------------------------------------------------- */
+  i = 1;
+  if( *((uchar *) &i) == 1 )
+    bBigEndian = MS_FALSE;
+  else
+    bBigEndian = MS_TRUE;
+
+  /* -------------------------------------------------------------------- */
+  /*  Initialize the info structure.              */
+  /* -------------------------------------------------------------------- */
+  psTree = (SHPTreeHandle) msSmallMalloc(sizeof(SHPTreeInfo));
+
+  /* -------------------------------------------------------------------- */
+  /*  Compute the base (layer) name.  If there is any extension     */
+  /*  on the passed in filename we will strip it off.         */
+  /* -------------------------------------------------------------------- */
+  pszBasename = (char *) msSmallMalloc(strlen(pszTree)+5);
+  strcpy( pszBasename, pszTree );
+  for( i = strlen(pszBasename)-1;
        i > 0 && pszBasename[i] != '.' && pszBasename[i] != '/'
-	 && pszBasename[i] != '\\';
+       && pszBasename[i] != '\\';
        i-- ) {}
-  
-    if( pszBasename[i] == '.' )
-      pszBasename[i] = '\0';
-  
+
+  if( pszBasename[i] == '.' )
+    pszBasename[i] = '\0';
+
   /* -------------------------------------------------------------------- */
-  /*	Open the .shp and .shx files.  Note that files pulled from	    */
-  /*	a PC to Unix with upper case filenames won't work!		    */
+  /*  Open the .shp and .shx files.  Note that files pulled from      */
+  /*  a PC to Unix with upper case filenames won't work!        */
   /* -------------------------------------------------------------------- */
-    pszFullname = (char *) msSmallMalloc(strlen(pszBasename) + 5);
-    sprintf( pszFullname, "%s%s", pszBasename, MS_INDEX_EXTENSION); 
-    psTree->fp = fopen(pszFullname, "rb" );
+  pszFullname = (char *) msSmallMalloc(strlen(pszBasename) + 5);
+  sprintf( pszFullname, "%s%s", pszBasename, MS_INDEX_EXTENSION);
+  psTree->fp = fopen(pszFullname, "rb" );
+
+  msFree(pszBasename); /* don't need these any more */
+  msFree(pszFullname);
 
-    msFree(pszBasename); /* don't need these any more */
-    msFree(pszFullname);    
+  if( psTree->fp == NULL ) {
+    msFree(psTree);
+    return( NULL );
+  }
 
-    if( psTree->fp == NULL ) {      
-      msFree(psTree);
-      return( NULL );
+  fread( pabyBuf, 8, 1, psTree->fp );
+
+  memcpy( &psTree->signature, pabyBuf, 3 );
+  if( strncmp(psTree->signature,"SQT",3) ) {
+    /* ---------------------------------------------------------------------- */
+    /*     must check if the 2 first bytes equal 0 of max depth that cannot   */
+    /*     be more than 65535. If yes, we must swap all value. The problem    */
+    /*     here is if there's no Depth (bytea 5,6,7,8 in the file) all bytes  */
+    /*     will be set to 0. So,we will test with the number of shapes (bytes */
+    /*     1,2,3,4) that cannot be more than 65535 too.                       */
+    /* ---------------------------------------------------------------------- */
+    if (debug) {
+      msDebug("WARNING in msSHPDiskTreeOpen(): %s is in old index format "
+              "which has been deprecated.  It is strongly recommended to "
+              "regenerate it in new format.\n", pszTree);
     }
-    
-    fread( pabyBuf, 8, 1, psTree->fp );
+    if((pabyBuf[4] == 0 && pabyBuf[5] == 0 &&
+        pabyBuf[6] == 0 && pabyBuf[7] == 0)) {
+      psTree->LSB_order = !(pabyBuf[0] == 0 && pabyBuf[1] == 0);
+    } else {
+      psTree->LSB_order = !(pabyBuf[4] == 0 && pabyBuf[5] == 0);
+    }
+    psTree->needswap = ((psTree->LSB_order) != (!bBigEndian));
 
-    memcpy( &psTree->signature, pabyBuf, 3 );
-    if( strncmp(psTree->signature,"SQT",3) )
-    {
-  /* ---------------------------------------------------------------------- */
-  /*     must check if the 2 first bytes equal 0 of max depth that cannot   */
-  /*     be more than 65535. If yes, we must swap all value. The problem    */
-  /*     here is if there's no Depth (bytea 5,6,7,8 in the file) all bytes  */
-  /*     will be set to 0. So,we will test with the number of shapes (bytes */
-  /*     1,2,3,4) that cannot be more than 65535 too.                       */
-  /* ---------------------------------------------------------------------- */
-      if (debug)
-      {
-          msDebug("WARNING in msSHPDiskTreeOpen(): %s is in old index format "
-                  "which has been deprecated.  It is strongly recommended to "
-                  "regenerate it in new format.\n", pszTree);
-      }
-      if((pabyBuf[4] == 0 && pabyBuf[5] == 0 && 
-          pabyBuf[6] == 0 && pabyBuf[7] == 0))
-      {
-        psTree->LSB_order = !(pabyBuf[0] == 0 && pabyBuf[1] == 0);
-      }
-      else
-      {
-        psTree->LSB_order = !(pabyBuf[4] == 0 && pabyBuf[5] == 0);
-      }
-      psTree->needswap = ((psTree->LSB_order) != (!bBigEndian));
+    /* ---------------------------------------------------------------------- */
+    /*     poor hack to see if this quadtree was created by a computer with a */
+    /*     different Endian                                                   */
+    /* ---------------------------------------------------------------------- */
+    psTree->version = 0;
+  } else {
+    psTree->needswap = (( pabyBuf[3] == MS_NEW_MSB_ORDER ) ^ ( bBigEndian ));
 
-  /* ---------------------------------------------------------------------- */
-  /*     poor hack to see if this quadtree was created by a computer with a */
-  /*     different Endian                                                   */
-  /* ---------------------------------------------------------------------- */
-      psTree->version = 0;
-    }
-    else
-    {
-      psTree->needswap = (( pabyBuf[3] == MS_NEW_MSB_ORDER ) ^ ( bBigEndian ));
+    psTree->LSB_order = ( pabyBuf[3] == MS_NEW_LSB_ORDER );
+    memcpy( &psTree->version, pabyBuf+4, 1 );
+    memcpy( &psTree->flags, pabyBuf+5, 3 );
 
-      psTree->LSB_order = ( pabyBuf[3] == MS_NEW_LSB_ORDER );      
-      memcpy( &psTree->version, pabyBuf+4, 1 );
-      memcpy( &psTree->flags, pabyBuf+5, 3 );
+    fread( pabyBuf, 8, 1, psTree->fp );
+  }
 
-      fread( pabyBuf, 8, 1, psTree->fp );
-    }
+  if( psTree->needswap ) SwapWord( 4, pabyBuf );
+  memcpy( &psTree->nShapes, pabyBuf, 4 );
 
-    if( psTree->needswap ) SwapWord( 4, pabyBuf );
-    memcpy( &psTree->nShapes, pabyBuf, 4 );
-  
-    if( psTree->needswap ) SwapWord( 4, pabyBuf+4 );
-    memcpy( &psTree->nDepth, pabyBuf+4, 4 );
-  
-    return( psTree );
+  if( psTree->needswap ) SwapWord( 4, pabyBuf+4 );
+  memcpy( &psTree->nDepth, pabyBuf+4, 4 );
+
+  return( psTree );
 }
 
 
 void msSHPDiskTreeClose(SHPTreeHandle disktree)
 {
-    fclose( disktree->fp );  
-    free( disktree );
+  fclose( disktree->fp );
+  free( disktree );
 }
 
 
@@ -211,7 +203,7 @@ treeObj *msCreateTree(shapefileObj *shapefile, int maxdepth)
   /*      Allocate the tree object                                        */
   /* -------------------------------------------------------------------- */
   tree = (treeObj *) msSmallMalloc(sizeof(treeObj));
-  
+
   tree->numshapes = shapefile->numshapes;
   tree->maxdepth = maxdepth;
 
@@ -221,7 +213,7 @@ treeObj *msCreateTree(shapefileObj *shapefile, int maxdepth)
   /* -------------------------------------------------------------------- */
   if( tree->maxdepth == 0 ) {
     int numnodes = 1;
-    
+
     while(numnodes*4 < shapefile->numshapes) {
       tree->maxdepth += 1;
       numnodes = numnodes * 2;
@@ -244,12 +236,12 @@ treeObj *msCreateTree(shapefileObj *shapefile, int maxdepth)
 static void destroyTreeNode(treeNodeObj *node)
 {
   int i;
-  
+
   for(i=0; i<node->numsubnodes; i++ ) {
-    if(node->subnode[i]) 
+    if(node->subnode[i])
       destroyTreeNode(node->subnode[i]);
   }
-  
+
   if(node->ids)
     free(node->ids);
 
@@ -272,13 +264,13 @@ static void treeSplitBounds( rectObj *in, rectObj *out1, rectObj *out2)
   /* -------------------------------------------------------------------- */
   memcpy(out1, in, sizeof(rectObj));
   memcpy(out2, in, sizeof(rectObj));
-  
+
   /* -------------------------------------------------------------------- */
   /*      Split in X direction.                                           */
   /* -------------------------------------------------------------------- */
   if((in->maxx - in->minx) > (in->maxy - in->miny)) {
     range = in->maxx - in->minx;
-    
+
     out1->maxx = in->minx + range * SPLITRATIO;
     out2->minx = in->maxx - range * SPLITRATIO;
   }
@@ -288,7 +280,7 @@ static void treeSplitBounds( rectObj *in, rectObj *out1, rectObj *out2)
   /* -------------------------------------------------------------------- */
   else {
     range = in->maxy - in->miny;
-    
+
     out1->maxy = in->miny + range * SPLITRATIO;
     out2->miny = in->maxy - range * SPLITRATIO;
   }
@@ -297,7 +289,7 @@ static void treeSplitBounds( rectObj *in, rectObj *out1, rectObj *out2)
 static int treeNodeAddShapeId( treeNodeObj *node, int id, rectObj rect, int maxdepth)
 {
   int i;
-    
+
   /* -------------------------------------------------------------------- */
   /*      If there are subnodes, then consider whether this object        */
   /*      will fit in them.                                               */
@@ -305,7 +297,7 @@ static int treeNodeAddShapeId( treeNodeObj *node, int id, rectObj rect, int maxd
   if( maxdepth > 1 && node->numsubnodes > 0 ) {
     for(i=0; i<node->numsubnodes; i++ ) {
       if( msRectContained(&rect, &node->subnode[i]->rect)) {
-	return treeNodeAddShapeId( node->subnode[i], id, rect, maxdepth-1);
+        return treeNodeAddShapeId( node->subnode[i], id, rect, maxdepth-1);
       }
     }
   }
@@ -321,56 +313,55 @@ static int treeNodeAddShapeId( treeNodeObj *node, int id, rectObj rect, int maxd
     treeSplitBounds(&node->rect, &half1, &half2);
     treeSplitBounds(&half1, &quad1, &quad2);
     treeSplitBounds(&half2, &quad3, &quad4);
-  
-    if(msRectContained(&rect, &quad1) || msRectContained(&rect, &quad2) || 	msRectContained(&rect, &quad3) || msRectContained(&rect, &quad4)) {
+
+    if(msRectContained(&rect, &quad1) || msRectContained(&rect, &quad2) ||  msRectContained(&rect, &quad3) || msRectContained(&rect, &quad4)) {
       node->numsubnodes = 4;
       node->subnode[0] = treeNodeCreate(quad1);
       node->subnode[1] = treeNodeCreate(quad2);
       node->subnode[2] = treeNodeCreate(quad3);
       node->subnode[3] = treeNodeCreate(quad4);
-      
+
       /* recurse back on this node now that it has subnodes */
       return(treeNodeAddShapeId(node, id, rect, maxdepth));
     }
   }
 #endif
 
-    /* -------------------------------------------------------------------- */
-    /*      Otherwise, consider creating two subnodes if could fit into     */
-    /*      them, and adding to the appropriate subnode.                    */
-    /* -------------------------------------------------------------------- */
+  /* -------------------------------------------------------------------- */
+  /*      Otherwise, consider creating two subnodes if could fit into     */
+  /*      them, and adding to the appropriate subnode.                    */
+  /* -------------------------------------------------------------------- */
 #if MAX_SUBNODE == 2
-    else if( maxdepth > 1 && node->numsubnodes == 0 ) {
-      rectObj half1, half2;
-      
-      treeSplitBounds(&node->rect, &half1, &half2);
-
-      if( msRectContained(&rect, &half1)) {
-	node->numsubnodes = 2;
-	node->subnode[0] = treeNodeCreate(half1);
-	node->subnode[1] = treeNodeCreate(half2);
-	
-	return(treeNodeAddShapeId(node->subnode[0], id, rect, maxdepth-1));
-      } else 
-	if(msRectContained(&rect, &half2)) {
-            node->numsubnodes = 2;
-            node->subnode[0] = treeNodeCreate(&half1);
-            node->subnode[1] = treeNodeCreate(&half2);
-
-            return(treeNodeAddShapeId(node->subnode[1], id, rect, maxdepth-1));
-        }
+  else if( maxdepth > 1 && node->numsubnodes == 0 ) {
+    rectObj half1, half2;
+
+    treeSplitBounds(&node->rect, &half1, &half2);
+
+    if( msRectContained(&rect, &half1)) {
+      node->numsubnodes = 2;
+      node->subnode[0] = treeNodeCreate(half1);
+      node->subnode[1] = treeNodeCreate(half2);
+
+      return(treeNodeAddShapeId(node->subnode[0], id, rect, maxdepth-1));
+    } else if(msRectContained(&rect, &half2)) {
+      node->numsubnodes = 2;
+      node->subnode[0] = treeNodeCreate(&half1);
+      node->subnode[1] = treeNodeCreate(&half2);
+
+      return(treeNodeAddShapeId(node->subnode[1], id, rect, maxdepth-1));
     }
+  }
 #endif /* MAX_SUBNODE == 2 */
 
-/* -------------------------------------------------------------------- */
-/*      If none of that worked, just add it to this nodes list.         */
-/* -------------------------------------------------------------------- */
-    node->numshapes++;
+  /* -------------------------------------------------------------------- */
+  /*      If none of that worked, just add it to this nodes list.         */
+  /* -------------------------------------------------------------------- */
+  node->numshapes++;
 
-    node->ids = SfRealloc( node->ids, sizeof(ms_int32) * node->numshapes );
-    node->ids[node->numshapes-1] = id;
+  node->ids = SfRealloc( node->ids, sizeof(ms_int32) * node->numshapes );
+  node->ids[node->numshapes-1] = id;
 
-    return MS_TRUE;
+  return MS_TRUE;
 }
 
 static int treeAddShapeId(treeObj *tree, int id, rectObj rect)
@@ -381,7 +372,7 @@ static int treeAddShapeId(treeObj *tree, int id, rectObj rect)
 static void treeCollectShapeIds(treeNodeObj *node, rectObj aoi, ms_bitarray status)
 {
   int i;
-    
+
   /* -------------------------------------------------------------------- */
   /*      Does this node overlap the area of interest at all?  If not,    */
   /*      return without adding to the list at all.                       */
@@ -394,7 +385,7 @@ static void treeCollectShapeIds(treeNodeObj *node, rectObj aoi, ms_bitarray stat
   /* -------------------------------------------------------------------- */
   for(i=0; i<node->numshapes; i++)
     msSetBit(status, node->ids[i], 1);
-  
+
   /* -------------------------------------------------------------------- */
   /*      Recurse to subnodes if they exist.                              */
   /* -------------------------------------------------------------------- */
@@ -413,7 +404,7 @@ ms_bitarray msSearchTree(treeObj *tree, rectObj aoi)
     msSetError(MS_MEMERR, NULL, "msSearchTree()");
     return(NULL);
   }
-  
+
   treeCollectShapeIds(tree->root, aoi, status);
 
   return(status);
@@ -421,30 +412,43 @@ ms_bitarray msSearchTree(treeObj *tree, rectObj aoi)
 
 static int treeNodeTrim( treeNodeObj *node )
 {
-    int	i;
+  int i;
 
-    /* -------------------------------------------------------------------- */
-    /*      Trim subtrees, and free subnodes that come back empty.          */
-    /* -------------------------------------------------------------------- */
-    for(i=0; i<node->numsubnodes; i++ ) {
-      if(treeNodeTrim(node->subnode[i])) {
-	destroyTreeNode(node->subnode[i]);
-	node->subnode[i] = node->subnode[node->numsubnodes-1];
-	node->numsubnodes--;
-	i--; /* process the new occupant of this subnode entry */
-      }
+  /* -------------------------------------------------------------------- */
+  /*      Trim subtrees, and free subnodes that come back empty.          */
+  /* -------------------------------------------------------------------- */
+  for(i=0; i<node->numsubnodes; i++ ) {
+    if(treeNodeTrim(node->subnode[i])) {
+      destroyTreeNode(node->subnode[i]);
+      node->subnode[i] = node->subnode[node->numsubnodes-1];
+      node->numsubnodes--;
+      i--; /* process the new occupant of this subnode entry */
     }
+  }
 
-    if( node->numsubnodes == 1 && node->numshapes == 0 ) {
-      node = node->subnode[0];
-    }
-/* if I only have 1 subnode promote that subnode to my positon */ 
+  /* -------------------------------------------------------------------- */
+  /*      If the current node has 1 subnode and no shapes, promote that   */
+  /*      subnode to the current node position.                           */
+  /* -------------------------------------------------------------------- */
+  if( node->numsubnodes == 1 && node->numshapes == 0) {
+    treeNodeObj* psSubNode = node->subnode[0];
+
+    memcpy(&node->rect, &psSubNode->rect,
+           sizeof(psSubNode->rect));
+    node->numshapes = psSubNode->numshapes;
+    assert(node->ids == NULL);
+    node->ids = psSubNode->ids;
+    node->numsubnodes = psSubNode->numsubnodes;
+    for( i = 0; i < psSubNode->numsubnodes; i++ )
+      node->subnode[i] = psSubNode->subnode[i];
+    free(psSubNode);
+  }
 
-    /* -------------------------------------------------------------------- */
-    /*      We should be trimmed if we have no subnodes, and no shapes.     */
-    /* -------------------------------------------------------------------- */
+  /* -------------------------------------------------------------------- */
+  /*      We should be trimmed if we have no subnodes, and no shapes.     */
+  /* -------------------------------------------------------------------- */
 
-    return(node->numsubnodes == 0 && node->numshapes == 0);
+  return(node->numsubnodes == 0 && node->numshapes == 0);
 }
 
 void msTreeTrim(treeObj *tree)
@@ -452,7 +456,7 @@ void msTreeTrim(treeObj *tree)
   treeNodeTrim(tree->root);
 }
 
-static void searchDiskTreeNode(SHPTreeHandle disktree, rectObj aoi, ms_bitarray status) 
+static void searchDiskTreeNode(SHPTreeHandle disktree, rectObj aoi, ms_bitarray status)
 {
   int i;
   ms_int32 offset;
@@ -469,7 +473,7 @@ static void searchDiskTreeNode(SHPTreeHandle disktree, rectObj aoi, ms_bitarray
   if ( disktree->needswap ) SwapWord ( 8, &rect.miny );
   if ( disktree->needswap ) SwapWord ( 8, &rect.maxx );
   if ( disktree->needswap ) SwapWord ( 8, &rect.maxy );
-      
+
   fread( &numshapes, 4, 1, disktree->fp );
   if ( disktree->needswap ) SwapWord ( 4, &numshapes );
 
@@ -482,16 +486,12 @@ static void searchDiskTreeNode(SHPTreeHandle disktree, rectObj aoi, ms_bitarray
     ids = (int *)msSmallMalloc(numshapes*sizeof(ms_int32));
 
     fread( ids, numshapes*sizeof(ms_int32), 1, disktree->fp );
-    if (disktree->needswap )
-    {
-      for( i=0; i<numshapes; i++ )
-      {
-        SwapWord( 4, &ids[i] );    
+    if (disktree->needswap ) {
+      for( i=0; i<numshapes; i++ ) {
+        SwapWord( 4, &ids[i] );
         msSetBit(status, ids[i], 1);
       }
-    }
-    else
-    {
+    } else {
       for(i=0; i<numshapes; i++)
         msSetBit(status, ids[i], 1);
     }
@@ -509,7 +509,7 @@ static void searchDiskTreeNode(SHPTreeHandle disktree, rectObj aoi, ms_bitarray
 
 ms_bitarray msSearchDiskTree(char *filename, rectObj aoi, int debug)
 {
-  SHPTreeHandle	disktree;
+  SHPTreeHandle disktree;
   ms_bitarray status=NULL;
 
   disktree = msSHPDiskTreeOpen (filename, debug);
@@ -534,7 +534,7 @@ ms_bitarray msSearchDiskTree(char *filename, rectObj aoi, int debug)
   return(status);
 }
 
-treeNodeObj *readTreeNode( SHPTreeHandle disktree ) 
+treeNodeObj *readTreeNode( SHPTreeHandle disktree )
 {
   int i,res;
   ms_int32 offset;
@@ -544,37 +544,36 @@ treeNodeObj *readTreeNode( SHPTreeHandle disktree )
   node->ids = NULL;
 
   res = fread( &offset, 4, 1, disktree->fp );
-  if ( !res ) 
-      return NULL;
+  if ( !res )
+    return NULL;
 
   if ( disktree->needswap ) SwapWord ( 4, &offset );
-   
+
   fread( &node->rect, sizeof(rectObj), 1, disktree->fp );
   if ( disktree->needswap ) SwapWord ( 8, &node->rect.minx );
   if ( disktree->needswap ) SwapWord ( 8, &node->rect.miny );
   if ( disktree->needswap ) SwapWord ( 8, &node->rect.maxx );
   if ( disktree->needswap ) SwapWord ( 8, &node->rect.maxy );
-      
+
   fread( &node->numshapes, 4, 1, disktree->fp );
   if ( disktree->needswap ) SwapWord ( 4, &node->numshapes );
   if( node->numshapes > 0 )
     node->ids = (ms_int32 *)msSmallMalloc(sizeof(ms_int32)*node->numshapes);
   fread( node->ids, node->numshapes*4, 1, disktree->fp );
-  for( i=0; i < node->numshapes; i++ )
-  {
-    if ( disktree->needswap ) SwapWord ( 4, &node->ids[i] );    
+  for( i=0; i < node->numshapes; i++ ) {
+    if ( disktree->needswap ) SwapWord ( 4, &node->ids[i] );
   }
 
   fread( &node->numsubnodes, 4, 1, disktree->fp );
   if ( disktree->needswap ) SwapWord ( 4, &node->numsubnodes );
-  
+
   return node;
 }
 
 treeObj *msReadTree(char *filename, int debug)
 {
   treeObj *tree=NULL;
-  SHPTreeHandle	disktree;
+  SHPTreeHandle disktree;
 
   disktree = msSHPDiskTreeOpen( filename, debug );
   if(!disktree) {
@@ -584,7 +583,7 @@ treeObj *msReadTree(char *filename, int debug)
 
   tree = (treeObj *) malloc(sizeof(treeObj));
   MS_CHECK_ALLOC(tree, sizeof(treeObj), NULL);
-  
+
   tree->numshapes = disktree->nShapes;
   tree->maxdepth = disktree->nDepth;
 
@@ -593,7 +592,7 @@ treeObj *msReadTree(char *filename, int debug)
   return(tree);
 }
 
-static ms_int32 getSubNodeOffset(treeNodeObj *node) 
+static ms_int32 getSubNodeOffset(treeNodeObj *node)
 {
   int i;
   ms_int32 offset=0;
@@ -607,31 +606,31 @@ static ms_int32 getSubNodeOffset(treeNodeObj *node)
 
   /* offset is the disk offset in the index file on disk       */
   /*   that format is (per node)                               */
-  /*      int       offset			4 bytes						*/
-  /*      rectObj   rect			4 * 8 bytes					*/
-  /*	  int		numShapes		4 bytes						*/
-  /*	  int		ids[numShapes]	4 * numShapes bytes			*/
-  /*	  int		numSubNodes		4 bytes						*/
-  /*				                                       */
-  
+  /*      int       offset      4 bytes           */
+  /*      rectObj   rect      4 * 8 bytes         */
+  /*    int   numShapes   4 bytes           */
+  /*    int   ids[numShapes]  4 * numShapes bytes     */
+  /*    int   numSubNodes   4 bytes           */
+  /*                                               */
+
   return(offset);
 }
 
 
-static void writeTreeNode(SHPTreeHandle disktree, treeNodeObj *node) 
+static void writeTreeNode(SHPTreeHandle disktree, treeNodeObj *node)
 {
   int i,j;
   ms_int32 offset;
   char *pabyRec = NULL;
 
   offset = getSubNodeOffset(node);
-  
+
   pabyRec = msSmallMalloc(sizeof(rectObj) + (3 * sizeof(ms_int32)) + (node->numshapes * sizeof(ms_int32)) );
 
   memcpy( pabyRec, &offset, 4);
   if( disktree->needswap ) SwapWord( 4, pabyRec );
-    
-   memcpy( pabyRec+4, &node->rect, sizeof(rectObj));
+
+  memcpy( pabyRec+4, &node->rect, sizeof(rectObj));
   for (i=0; i < 4; i++)
     if( disktree->needswap ) SwapWord( 8, pabyRec+4+(8*i) );
 
@@ -642,13 +641,13 @@ static void writeTreeNode(SHPTreeHandle disktree, treeNodeObj *node)
   memcpy( pabyRec+40, node->ids, j);
   for (i=0; i<node->numshapes; i++)
     if( disktree->needswap ) SwapWord( 4, pabyRec+40+(4*i));
-  
+
   memcpy( pabyRec+j+40, &node->numsubnodes, 4);
-  if( disktree->needswap ) SwapWord( 4, pabyRec+40+j ); 
+  if( disktree->needswap ) SwapWord( 4, pabyRec+40+j );
 
   fwrite( pabyRec, 44+j, 1, disktree->fp);
   free (pabyRec);
-  
+
   for(i=0; i<node->numsubnodes; i++ ) {
     if(node->subnode[i])
       writeTreeNode(disktree, node->subnode[i]);
@@ -656,104 +655,104 @@ static void writeTreeNode(SHPTreeHandle disktree, treeNodeObj *node)
 
 
   return;
-  
+
 }
 
 int msWriteTree(treeObj *tree, char *filename, int B_order)
 {
-  char		signature[3] = "SQT";
-  char		version = 1;
-  char		reserved[3] = {0,0,0};
+  char    signature[3] = "SQT";
+  char    version = 1;
+  char    reserved[3] = {0,0,0};
   SHPTreeHandle disktree;
-  int		i;
-  char		mtBigEndian;
-  char		pabyBuf[32];
-  char		*pszBasename, *pszFullname;
-  
-  
+  int   i;
+  char    mtBigEndian;
+  char    pabyBuf[32];
+  char    *pszBasename, *pszFullname;
+
+
   disktree = (SHPTreeHandle) malloc(sizeof(SHPTreeInfo));
   MS_CHECK_ALLOC(disktree, sizeof(SHPTreeInfo), MS_FALSE);
 
   /* -------------------------------------------------------------------- */
-  /*	Compute the base (layer) name.  If there is any extension	    */
-  /*	on the passed in filename we will strip it off.			    */
+  /*  Compute the base (layer) name.  If there is any extension     */
+  /*  on the passed in filename we will strip it off.         */
   /* -------------------------------------------------------------------- */
   pszBasename = (char *) msSmallMalloc(strlen(filename)+5);
   strcpy( pszBasename, filename );
-  for( i = strlen(pszBasename)-1; 
+  for( i = strlen(pszBasename)-1;
        i > 0 && pszBasename[i] != '.' && pszBasename[i] != '/'
-	 && pszBasename[i] != '\\';
+       && pszBasename[i] != '\\';
        i-- ) {}
-  
+
   if( pszBasename[i] == '.' )
     pszBasename[i] = '\0';
-  
+
   /* -------------------------------------------------------------------- */
-  /*	Open the .shp and .shx files.  Note that files pulled from	    */
-  /*	a PC to Unix with upper case filenames won't work!		    */
+  /*  Open the .shp and .shx files.  Note that files pulled from      */
+  /*  a PC to Unix with upper case filenames won't work!        */
   /* -------------------------------------------------------------------- */
   pszFullname = (char *) msSmallMalloc(strlen(pszBasename) + 5);
-  sprintf( pszFullname, "%s%s", pszBasename, MS_INDEX_EXTENSION); 
+  sprintf( pszFullname, "%s%s", pszBasename, MS_INDEX_EXTENSION);
   disktree->fp = fopen(pszFullname, "wb");
-  
+
   msFree(pszBasename); /* not needed */
   msFree(pszFullname);
-  
+
   if(!disktree->fp) {
     msFree(disktree);
     msSetError(MS_IOERR, NULL, "msWriteTree()");
     return(MS_FALSE);
   }
-  
-  
+
+
   /* for efficiency, trim the tree */
   msTreeTrim(tree);
-  
+
   /* -------------------------------------------------------------------- */
-  /*	Establish the byte order on this machine.			    */
+  /*  Establish the byte order on this machine.         */
   /* -------------------------------------------------------------------- */
   i = 1;
   if( *((uchar *) &i) == 1 )
     mtBigEndian = MS_FALSE;
   else
     mtBigEndian = MS_TRUE;
-  
+
   if( !(mtBigEndian ^ ( B_order == MS_LSB_ORDER || B_order == MS_NEW_LSB_ORDER )) )
     disktree->needswap = 1;
   else
     disktree->needswap = 0;
-  
+
   if( B_order == MS_NATIVE_ORDER )
     disktree->needswap = 0;
-  
+
   /* write the header */
-  if ( B_order > 0 ) {  
+  if ( B_order > 0 ) {
     memcpy( pabyBuf, &signature, 3 );
     memcpy (&disktree->signature, &signature, 3);
     pabyBuf[3] = B_order;
-    
+
     memcpy( pabyBuf+4, &version, 1);
     memcpy( pabyBuf+5, &reserved, 3);
-    
+
     memcpy( &disktree->version, &version, 1);
     memcpy( &disktree->flags, &reserved, 3);
-    
+
     fwrite( pabyBuf, 8, 1, disktree->fp );
   }
-  
+
   memcpy( pabyBuf, &tree->numshapes, 4 );
   if( disktree->needswap ) SwapWord( 4, pabyBuf );
-  
+
   memcpy( pabyBuf+4, &tree->maxdepth, 4 );
   if( disktree->needswap ) SwapWord( 4, pabyBuf+4 );
-  
+
   i = fwrite( pabyBuf, 8, 1, disktree->fp );
   if( !i ) {
     fprintf (stderr, "unable to write to index file ... exiting \n");
     return (MS_FALSE);
   }
-  
-  writeTreeNode(disktree, tree->root);  
+
+  writeTreeNode(disktree, tree->root);
 
   msSHPDiskTreeClose( disktree );
 
@@ -769,8 +768,8 @@ void msFilterTreeSearch(shapefileObj *shp, ms_bitarray status, rectObj search_re
   i = msGetNextBit(status, 0, shp->numshapes);
   while(i >= 0) {
     if(msSHPReadBounds(shp->hSHP, i, &shape_rect) == MS_SUCCESS) {
-	    if(msRectOverlap(&shape_rect, &search_rect) != MS_TRUE) {
-	      msSetBit(status, i, 0);
+      if(msRectOverlap(&shape_rect, &search_rect) != MS_TRUE) {
+        msSetBit(status, i, 0);
       }
     }
     i = msGetNextBit(status, i+1, shp->numshapes);
diff --git a/maptree.h b/maptree.h
index 3920c6a..1f9eebe 100644
--- a/maptree.h
+++ b/maptree.h
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -34,41 +34,40 @@
 extern "C" {
 #endif
 
-/* this can be 2 or 4 for binary or quad tree */
+  /* this can be 2 or 4 for binary or quad tree */
 #define MAX_SUBNODES 4
-   
-typedef struct shape_tree_node {
-  /* area covered by this node */
-  rectObj rect;
-  
-  /* list of shapes stored at this node. */
-  ms_int32 numshapes;
-  ms_int32 *ids;
-  
-  int numsubnodes;
-  struct shape_tree_node *subnode[MAX_SUBNODES];
-} treeNodeObj;
-
-typedef struct {
-  ms_int32 numshapes;
-  ms_int32 maxdepth;
-  treeNodeObj *root;
-} treeObj;
-
-
-typedef struct
-{
+
+  typedef struct shape_tree_node {
+    /* area covered by this node */
+    rectObj rect;
+
+    /* list of shapes stored at this node. */
+    ms_int32 numshapes;
+    ms_int32 *ids;
+
+    int numsubnodes;
+    struct shape_tree_node *subnode[MAX_SUBNODES];
+  } treeNodeObj;
+
+  typedef struct {
+    ms_int32 numshapes;
+    ms_int32 maxdepth;
+    treeNodeObj *root;
+  } treeObj;
+
+
+  typedef struct {
     FILE        *fp;
     char        signature[3];
-    char	LSB_order;
+    char  LSB_order;
     char        needswap;
-    char	version;
-    char	flags[3];
+    char  version;
+    char  flags[3];
 
     ms_int32        nShapes;
     ms_int32        nDepth;
-} SHPTreeInfo;
-typedef SHPTreeInfo * SHPTreeHandle;
+  } SHPTreeInfo;
+  typedef SHPTreeInfo * SHPTreeHandle;
 
 #define MS_LSB_ORDER -1
 #define MS_MSB_ORDER -2
@@ -77,21 +76,21 @@ typedef SHPTreeInfo * SHPTreeHandle;
 #define MS_NEW_MSB_ORDER 2
 
 
-MS_DLL_EXPORT SHPTreeHandle msSHPDiskTreeOpen(const char * pszTree, int debug);
-MS_DLL_EXPORT void msSHPDiskTreeClose(SHPTreeHandle disktree);
-MS_DLL_EXPORT treeNodeObj *readTreeNode( SHPTreeHandle disktree );
+  MS_DLL_EXPORT SHPTreeHandle msSHPDiskTreeOpen(const char * pszTree, int debug);
+  MS_DLL_EXPORT void msSHPDiskTreeClose(SHPTreeHandle disktree);
+  MS_DLL_EXPORT treeNodeObj *readTreeNode( SHPTreeHandle disktree );
 
-MS_DLL_EXPORT treeObj *msCreateTree(shapefileObj *shapefile, int maxdepth);
-MS_DLL_EXPORT void msTreeTrim(treeObj *tree);
-MS_DLL_EXPORT void msDestroyTree(treeObj *tree);
+  MS_DLL_EXPORT treeObj *msCreateTree(shapefileObj *shapefile, int maxdepth);
+  MS_DLL_EXPORT void msTreeTrim(treeObj *tree);
+  MS_DLL_EXPORT void msDestroyTree(treeObj *tree);
 
-MS_DLL_EXPORT ms_bitarray msSearchTree(treeObj *tree, rectObj aoi);
-MS_DLL_EXPORT ms_bitarray msSearchDiskTree(char *filename, rectObj aoi, int debug);
+  MS_DLL_EXPORT ms_bitarray msSearchTree(treeObj *tree, rectObj aoi);
+  MS_DLL_EXPORT ms_bitarray msSearchDiskTree(char *filename, rectObj aoi, int debug);
 
-MS_DLL_EXPORT treeObj *msReadTree(char *filename, int debug);
-MS_DLL_EXPORT int msWriteTree(treeObj *tree, char *filename, int LSB_order);
+  MS_DLL_EXPORT treeObj *msReadTree(char *filename, int debug);
+  MS_DLL_EXPORT int msWriteTree(treeObj *tree, char *filename, int LSB_order);
 
-MS_DLL_EXPORT void msFilterTreeSearch(shapefileObj *shp, ms_bitarray status, rectObj search_rect);
+  MS_DLL_EXPORT void msFilterTreeSearch(shapefileObj *shp, ms_bitarray status, rectObj search_rect);
 
 #ifdef __cplusplus
 }
diff --git a/mapunion.c b/mapunion.c
index 7a22edb..6f7c3bb 100644
--- a/mapunion.c
+++ b/mapunion.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -33,7 +33,7 @@
 #include <assert.h>
 #include "mapserver.h"
 
-MS_CVSID("$Id$")
+
 
 #define MSUNION_NUMITEMS        3
 #define MSUNION_SOURCELAYERNAME        "Union:SourceLayerName"
@@ -43,379 +43,420 @@ MS_CVSID("$Id$")
 #define MSUNION_SOURCELAYERVISIBLE        "Union:SourceLayerVisible"
 #define MSUNION_SOURCELAYERVISIBLEINDEX   -102
 
-typedef struct
-{
-    int layerIndex;  /* current source layer index */
-    int classIndex;  /* current class index */
-    char* classText;   /* current class text (autostyle) */
-    int layerCount;  /* number of the source layers */
-    layerObj* layers; /* structure to the source layers */
-    int *status;     /* the layer status */
-    int *classgroup; /* current array of the valid classes */
-    int nclasses;  /* number of the valid classes */
+typedef struct {
+  int layerIndex;  /* current source layer index */
+  int classIndex;  /* current class index */
+  char* classText;   /* current class text (autostyle) */
+  int layerCount;  /* number of the source layers */
+  layerObj* layers; /* structure to the source layers */
+  int *status;     /* the layer status */
+  int *classgroup; /* current array of the valid classes */
+  int nclasses;  /* number of the valid classes */
 } msUnionLayerInfo;
 
 /* Close the the combined layer */
 int msUnionLayerClose(layerObj *layer)
-{   
-    int i;
-    msUnionLayerInfo* layerinfo = (msUnionLayerInfo*)layer->layerinfo;
+{
+  int i;
+  msUnionLayerInfo* layerinfo = (msUnionLayerInfo*)layer->layerinfo;
+
+  if (!layerinfo)
+    return MS_SUCCESS;
 
-    if (!layerinfo)
-        return MS_SUCCESS;
+  if (!layer->map)
+    return MS_FAILURE;
+
+  for (i = 0; i < layerinfo->layerCount; i++) {
+    msLayerClose(&layerinfo->layers[i]);
+    freeLayer(&layerinfo->layers[i]);
+  }
+  msFree(layerinfo->layers);
+  msFree(layerinfo->status);
+  msFree(layerinfo->classgroup);
+  msFree(layerinfo->classText);
+  msFree(layerinfo);
+  layer->layerinfo = NULL;
+
+  return MS_SUCCESS;
+}
 
-    if (!layer->map)
-        return MS_FAILURE;
+int isScaleInRange(mapObj* map, layerObj *layer)
+{
+  if(map->scaledenom > 0) {
+    int i;
+    /* layer scale boundaries should be checked first */
+    if((layer->maxscaledenom > 0) && (map->scaledenom > layer->maxscaledenom))
+      return MS_FALSE;
+
+    if((layer->minscaledenom > 0) && (map->scaledenom <= layer->minscaledenom))
+      return MS_FALSE;
+
+    /* now check class scale boundaries (all layers *must* pass these tests) */
+    if(layer->numclasses > 0) {
+      for(i=0; i<layer->numclasses; i++) {
+        if((layer->class[i]->maxscaledenom > 0) && (map->scaledenom > layer->class[i]->maxscaledenom))
+          continue; /* can skip this one, next class */
+        if((layer->class[i]->minscaledenom > 0) && (map->scaledenom <= layer->class[i]->minscaledenom))
+          continue; /* can skip this one, next class */
+
+        break; /* can't skip this class (or layer for that matter) */
+      }
+      if(i == layer->numclasses)
+        return MS_FALSE;
 
-    for (i = 0; i < layerinfo->layerCount; i++)
-    {
-        msLayerClose(&layerinfo->layers[i]);
-        freeLayer(&layerinfo->layers[i]);
     }
-    msFree(layerinfo->layers);
-    msFree(layerinfo->status);
-    msFree(layerinfo->classgroup);
-    msFree(layerinfo->classText);
-    msFree(layerinfo);
-    layer->layerinfo = NULL;
 
-    return MS_SUCCESS;
+    if (layer->maxscaledenom <= 0 && layer->minscaledenom <= 0) {
+      if((layer->maxgeowidth > 0) && ((map->extent.maxx - map->extent.minx) > layer->maxgeowidth))
+        return MS_FALSE;
+
+      if((layer->mingeowidth > 0) && ((map->extent.maxx - map->extent.minx) < layer->mingeowidth))
+        return MS_FALSE;
+    }
+  }
+  return MS_TRUE;
 }
 
 int msUnionLayerOpen(layerObj *layer)
 {
-    msUnionLayerInfo *layerinfo;
-    char **layerNames;
-    mapObj* map;
-    int i;
-    int layerCount;
+  msUnionLayerInfo *layerinfo;
+  char **layerNames;
+  mapObj* map;
+  int i;
+  int layerCount;
+  const char* pkey;
+  int status_check;
+  int scale_check;
 
-    if (layer->layerinfo != NULL)
-    {
-      return MS_SUCCESS;  // Nothing to do... layer is already opened
-    }
-    
-    if (!layer->connection)
-    {
-        msSetError(MS_MISCERR, "The CONNECTION option is not specified for layer: %s", layer->name);
-        return MS_FAILURE;
-    }
+  if (layer->layerinfo != NULL) {
+    return MS_SUCCESS;  /* Nothing to do... layer is already opened */
+  }
 
-    if (!layer->map)
-    {
-        msSetError(MS_MISCERR, "No map assigned to this layer: %s", layer->name);
-        return MS_FAILURE;
-    }
+  if (!layer->connection) {
+    msSetError(MS_MISCERR, "The CONNECTION option is not specified for layer: %s", "msUnionLayerOpen()", layer->name);
+    return MS_FAILURE;
+  }
 
-    map = layer->map;
+  if (!layer->map) {
+    msSetError(MS_MISCERR, "No map assigned to this layer: %s", "msUnionLayerOpen()", layer->name);
+    return MS_FAILURE;
+  }
 
-    layerinfo =(msUnionLayerInfo*)malloc(sizeof(msUnionLayerInfo));
-    MS_CHECK_ALLOC(layerinfo, sizeof(msUnionLayerInfo), MS_FAILURE);
+  map = layer->map;
 
-    layer->layerinfo = layerinfo;
-    layerinfo->layerIndex = 0;
+  layerinfo =(msUnionLayerInfo*)malloc(sizeof(msUnionLayerInfo));
+  MS_CHECK_ALLOC(layerinfo, sizeof(msUnionLayerInfo), MS_FAILURE);
 
-    layerinfo->classgroup = NULL;
-    layerinfo->nclasses = 0;
+  layer->layerinfo = layerinfo;
+  layerinfo->layerIndex = 0;
 
-    layerinfo->layerCount = 0;
+  layerinfo->classgroup = NULL;
+  layerinfo->nclasses = 0;
 
-    layerinfo->classText = NULL;
-    
-    layerNames = msStringSplit(layer->connection, ',', &layerCount);
+  layerinfo->layerCount = 0;
+
+  layerinfo->classText = NULL;
+
+  pkey = msLayerGetProcessingKey(layer, "UNION_STATUS_CHECK");
+  if(pkey && strcasecmp(pkey, "true") == 0)
+    status_check = MS_TRUE;
+  else
+    status_check = MS_FALSE;
+
+  pkey = msLayerGetProcessingKey(layer, "UNION_SCALE_CHECK");
+  if(pkey && strcasecmp(pkey, "false") == 0)
+    scale_check = MS_FALSE;
+  else
+    scale_check = MS_TRUE;
+
+  pkey = msLayerGetProcessingKey(layer, "UNION_SRCLAYER_CLOSE_CONNECTION");
+
+  layerNames = msStringSplit(layer->connection, ',', &layerCount);
+
+  if (layerCount == 0) {
+    msSetError(MS_MISCERR, "No source layers specified in layer: %s", "msUnionLayerOpen()", layer->name);
+    if(layerNames)
+      msFreeCharArray(layerNames, layerinfo->layerCount);
+    msUnionLayerClose(layer);
+    return MS_FAILURE;
+  }
 
-    if (layerCount == 0)
-    {
-        msSetError(MS_MISCERR, "No source layers specified in layer: %s", layer->name);
+  layerinfo->layers =(layerObj*)malloc(layerCount * sizeof(layerObj));
+  MS_CHECK_ALLOC(layerinfo->layers, layerCount * sizeof(layerObj), MS_FAILURE);
+
+  layerinfo->status =(int*)malloc(layerCount * sizeof(int));
+  MS_CHECK_ALLOC(layerinfo->status, layerCount * sizeof(int), MS_FAILURE);
+
+  for(i=0; i < layerCount; i++) {
+    int layerindex = msGetLayerIndex(map, layerNames[i]);
+    if (layerindex >= 0 && layerindex < map->numlayers) {
+      layerObj* srclayer = map->layers[layerindex];
+
+      if (srclayer->type != layer->type) {
+        msSetError(MS_MISCERR, "The type of the source layer doesn't match with the union layer: %s", "msUnionLayerOpen()", srclayer->name);
         if(layerNames)
-                msFreeCharArray(layerNames, layerinfo->layerCount);
+          msFreeCharArray(layerNames, layerinfo->layerCount);
         msUnionLayerClose(layer);
         return MS_FAILURE;
-    }
+      }
 
-    layerinfo->layers =(layerObj*)malloc(layerCount * sizeof(layerObj));
-    MS_CHECK_ALLOC(layerinfo->layers, layerCount * sizeof(layerObj), MS_FAILURE);
-
-    layerinfo->status =(int*)malloc(layerCount * sizeof(int));
-    MS_CHECK_ALLOC(layerinfo->status, layerCount * sizeof(int), MS_FAILURE);
-
-    for(i=0; i < layerCount; i++)
-    {
-        int layerindex = msGetLayerIndex(map, layerNames[i]);
-        if (layerindex >= 0 && layerindex < map->numlayers)
-        {
-            layerObj* srclayer = map->layers[layerindex];
-
-            if (srclayer->type != layer->type)
-            {
-                msSetError(MS_MISCERR, "The type of the source layer doesn't match with the union layer: %s", srclayer->name);
-                if(layerNames)
-                        msFreeCharArray(layerNames, layerinfo->layerCount);
-                msUnionLayerClose(layer);
-                return MS_FAILURE;
-            }
-
-            /* we need to create a new layer in order make the singlepass query to work */
-            if(initLayer(&layerinfo->layers[i], map) == -1) 
-            {
-		        msSetError(MS_MISCERR, "Cannot initialize source layer: %s", srclayer->name);
-                if(layerNames)
-                        msFreeCharArray(layerNames, layerinfo->layerCount);
-                msUnionLayerClose(layer);
-                return MS_FAILURE;
-            }
-
-            ++layerinfo->layerCount; 
-
-	        if (msCopyLayer(&layerinfo->layers[i], srclayer) != MS_SUCCESS)
-            {
-		        msSetError(MS_MISCERR, "Cannot copy source layer: %s", srclayer->name);
-                if(layerNames)
-                        msFreeCharArray(layerNames, layerinfo->layerCount);
-                msUnionLayerClose(layer);
-                return MS_FAILURE;
-            }
-
-            /* disable the connection pool for this layer */
-            msLayerSetProcessingKey(&layerinfo->layers[i], "CLOSE_CONNECTION", "ALWAYS");
-
-            layerinfo->status[i] = msLayerOpen(&layerinfo->layers[i]);
-            if (layerinfo->status[i] != MS_SUCCESS)
-            {
-                if(layerNames)
-                    msFreeCharArray(layerNames, layerinfo->layerCount);
-                msUnionLayerClose(layer);
-                return MS_FAILURE;
-            }
-        }
-        else
-        {
-            msSetError(MS_MISCERR, "Invalid layer: %s", layerNames[i]);
-            if(layerNames)
-                msFreeCharArray(layerNames, layerinfo->layerCount);
-            msUnionLayerClose(layer);
-            return MS_FAILURE;
-        }
-    }
+      /* we need to create a new layer in order make the singlepass query to work */
+      if(initLayer(&layerinfo->layers[i], map) == -1) {
+        msSetError(MS_MISCERR, "Cannot initialize source layer: %s", "msUnionLayerOpen()", srclayer->name);
+        if(layerNames)
+          msFreeCharArray(layerNames, layerinfo->layerCount);
+        msUnionLayerClose(layer);
+        return MS_FAILURE;
+      }
 
-    if(layerNames)
+      ++layerinfo->layerCount;
+
+      if (msCopyLayer(&layerinfo->layers[i], srclayer) != MS_SUCCESS) {
+        msSetError(MS_MISCERR, "Cannot copy source layer: %s", "msUnionLayerOpen()", srclayer->name);
+        if(layerNames)
           msFreeCharArray(layerNames, layerinfo->layerCount);
-    
-    return MS_SUCCESS;
+        msUnionLayerClose(layer);
+        return MS_FAILURE;
+      }
+
+      if (pkey) {
+        /* override connection flag */
+        msLayerSetProcessingKey(&layerinfo->layers[i], "CLOSE_CONNECTION", pkey);
+      }
+
+      /* check is we should skip this source (status check) */
+      if (status_check && layerinfo->layers[i].status == MS_OFF) {
+        layerinfo->status[i] = MS_DONE;
+        continue;
+      }
+
+      /* check is we should skip this source (scale check) */
+      if (scale_check && isScaleInRange(map, &layerinfo->layers[i]) == MS_FALSE) {
+        layerinfo->status[i] = MS_DONE;
+        continue;
+      }
+
+      layerinfo->status[i] = msLayerOpen(&layerinfo->layers[i]);
+      if (layerinfo->status[i] != MS_SUCCESS) {
+        if(layerNames)
+          msFreeCharArray(layerNames, layerinfo->layerCount);
+        msUnionLayerClose(layer);
+        return MS_FAILURE;
+      }
+    } else {
+      msSetError(MS_MISCERR, "Invalid layer: %s", "msUnionLayerOpen()", layerNames[i]);
+      if(layerNames)
+        msFreeCharArray(layerNames, layerinfo->layerCount);
+      msUnionLayerClose(layer);
+      return MS_FAILURE;
+    }
+  }
+
+  if(layerNames)
+    msFreeCharArray(layerNames, layerinfo->layerCount);
+
+  return MS_SUCCESS;
 }
 
 /* Return MS_TRUE if layer is open, MS_FALSE otherwise. */
 int msUnionLayerIsOpen(layerObj *layer)
 {
-    if (layer->layerinfo)
-        return(MS_TRUE);
-    else
-        return(MS_FALSE);
+  if (layer->layerinfo)
+    return(MS_TRUE);
+  else
+    return(MS_FALSE);
 }
 
 /* Free the itemindexes array in a layer. */
 void msUnionLayerFreeItemInfo(layerObj *layer)
 {
-    int i;
-    msUnionLayerInfo* layerinfo = (msUnionLayerInfo*)layer->layerinfo;
+  int i;
+  msUnionLayerInfo* layerinfo = (msUnionLayerInfo*)layer->layerinfo;
 
-    if (!layerinfo || !layer->map)
-        return;
+  if (!layerinfo || !layer->map)
+    return;
 
-    msFree(layer->iteminfo);
+  msFree(layer->iteminfo);
 
-    layer->iteminfo = NULL;
+  layer->iteminfo = NULL;
 
-    for (i = 0; i < layerinfo->layerCount; i++)
-    {
-        msLayerFreeItemInfo(&layerinfo->layers[i]);
-        if(layerinfo->layers[i].items) 
-        {
-            /* need to remove the source layer items */
-            msFreeCharArray(layerinfo->layers[i].items, layerinfo->layers[i].numitems);
-            layerinfo->layers[i].items = NULL;
-            layerinfo->layers[i].numitems = 0;
-        }
+  for (i = 0; i < layerinfo->layerCount; i++) {
+    msLayerFreeItemInfo(&layerinfo->layers[i]);
+    if(layerinfo->layers[i].items) {
+      /* need to remove the source layer items */
+      msFreeCharArray(layerinfo->layers[i].items, layerinfo->layers[i].numitems);
+      layerinfo->layers[i].items = NULL;
+      layerinfo->layers[i].numitems = 0;
     }
+  }
 }
 
 /* clean up expression tokens */
 void msUnionLayerFreeExpressionTokens(layerObj *layer)
 {
-    int i,j;
-    freeExpressionTokens(&(layer->filter));
-    freeExpressionTokens(&(layer->cluster.group));
-    freeExpressionTokens(&(layer->cluster.filter));
-    for(i=0; i<layer->numclasses; i++) 
-    {    
-        freeExpressionTokens(&(layer->class[i]->expression));
-        freeExpressionTokens(&(layer->class[i]->text));
-        for(j=0; j<layer->class[i]->numstyles; j++)
-            freeExpressionTokens(&(layer->class[i]->styles[j]->_geomtransform));
-    }
+  int i,j;
+  freeExpressionTokens(&(layer->filter));
+  freeExpressionTokens(&(layer->cluster.group));
+  freeExpressionTokens(&(layer->cluster.filter));
+  for(i=0; i<layer->numclasses; i++) {
+    freeExpressionTokens(&(layer->class[i]->expression));
+    freeExpressionTokens(&(layer->class[i]->text));
+    for(j=0; j<layer->class[i]->numstyles; j++)
+      freeExpressionTokens(&(layer->class[i]->styles[j]->_geomtransform));
+  }
 }
 
 /* allocate the iteminfo index array - same order as the item list */
 int msUnionLayerInitItemInfo(layerObj *layer)
 {
-    int i, numitems;
-    int *itemindexes;
-    char* itemlist = NULL;
+  int i, numitems;
+  int *itemindexes;
+  char* itemlist = NULL;
 
-    msUnionLayerInfo* layerinfo = (msUnionLayerInfo*)layer->layerinfo;
+  msUnionLayerInfo* layerinfo = (msUnionLayerInfo*)layer->layerinfo;
 
-    if(layer->numitems == 0)
-    {
-        return MS_SUCCESS;
+  if(layer->numitems == 0) {
+    return MS_SUCCESS;
+  }
+
+  if (!layerinfo || !layer->map)
+    return MS_FAILURE;
+
+  /* Cleanup any previous item selection */
+  msUnionLayerFreeItemInfo(layer);
+
+  layer->iteminfo = (int *) malloc(sizeof(int) * layer->numitems);
+  MS_CHECK_ALLOC(layer->iteminfo, sizeof(int) * layer->numitems, MS_FAILURE);
+
+  itemindexes = (int*)layer->iteminfo;
+
+  /* check whether we require attributes from the source layers also */
+  numitems = 0;
+  for (i = 0; i < layer->numitems; i++) {
+    if (EQUAL(layer->items[i], MSUNION_SOURCELAYERNAME))
+      itemindexes[i] = MSUNION_SOURCELAYERNAMEINDEX;
+    else if (EQUAL(layer->items[i], MSUNION_SOURCELAYERGROUP))
+      itemindexes[i] = MSUNION_SOURCELAYERGROUPINDEX;
+    else if (EQUAL(layer->items[i], MSUNION_SOURCELAYERVISIBLE))
+      itemindexes[i] = MSUNION_SOURCELAYERVISIBLEINDEX;
+    else {
+      itemindexes[i] = numitems++;
+      if (itemlist) {
+        itemlist = msStringConcatenate(itemlist, ",");
+        itemlist = msStringConcatenate(itemlist, layer->items[i]);
+      } else {
+        itemlist = msStrdup(layer->items[i]);
+      }
     }
+  }
 
-    if (!layerinfo || !layer->map)
-        return MS_FAILURE;
-
-    /* Cleanup any previous item selection */
-    msUnionLayerFreeItemInfo(layer);
+  for (i = 0; i < layerinfo->layerCount; i++) {
+    layerObj* srclayer = &layerinfo->layers[i];
 
-    layer->iteminfo = (int *) malloc(sizeof(int) * layer->numitems);
-    MS_CHECK_ALLOC(layer->iteminfo, sizeof(int) * layer->numitems, MS_FAILURE);
+    if (layerinfo->status[i] != MS_SUCCESS)
+      continue; /* skip empty layers */
 
-    itemindexes = (int*)layer->iteminfo;
-
-    /* check whether we require attributes from the source layers also */
-    numitems = 0;
-    for (i = 0; i < layer->numitems; i++)
-    {
-        if (EQUAL(layer->items[i], MSUNION_SOURCELAYERNAME))
-            itemindexes[i] = MSUNION_SOURCELAYERNAMEINDEX;
-        else if (EQUAL(layer->items[i], MSUNION_SOURCELAYERGROUP))
-            itemindexes[i] = MSUNION_SOURCELAYERGROUPINDEX;
-        else if (EQUAL(layer->items[i], MSUNION_SOURCELAYERVISIBLE))
-            itemindexes[i] = MSUNION_SOURCELAYERVISIBLEINDEX;
-        else
-        {
-            itemindexes[i] = numitems++;
-            if (itemlist)
-            {
-                itemlist = msStringConcatenate(itemlist, ",");
-                itemlist = msStringConcatenate(itemlist, layer->items[i]);
-            }
-            else
-            {
-                itemlist = msStrdup(layer->items[i]);
-            }
-        }
-    }
+    msUnionLayerFreeExpressionTokens(srclayer);
 
-    for (i = 0; i < layerinfo->layerCount; i++)
-    { 
-        layerObj* srclayer = &layerinfo->layers[i];
-
-        msUnionLayerFreeExpressionTokens(srclayer);
-        
-        if (itemlist)
-        {
-            /* get items requested by the union layer plus the required items */
-            msLayerSetProcessingKey(srclayer, "ITEMS", itemlist);
-            if (msLayerWhichItems(srclayer, MS_TRUE, NULL) != MS_SUCCESS)
-            {
-                msFree(itemlist);
-                return MS_FAILURE;
-            }
-        }
-        else
-        {
-            /* get only the required items */
-            if (msLayerWhichItems(srclayer, MS_FALSE, NULL) != MS_SUCCESS)
-                return MS_FAILURE;
-        }
+    if (itemlist) {
+      /* get items requested by the union layer plus the required items */
+      msLayerSetProcessingKey(srclayer, "ITEMS", itemlist);
+      if (msLayerWhichItems(srclayer, MS_TRUE, NULL) != MS_SUCCESS) {
+        msFree(itemlist);
+        return MS_FAILURE;
+      }
+    } else {
+      /* get only the required items */
+      if (msLayerWhichItems(srclayer, MS_FALSE, NULL) != MS_SUCCESS)
+        return MS_FAILURE;
     }
+  }
 
-    msFree(itemlist);
-    return MS_SUCCESS;
+  msFree(itemlist);
+  return MS_SUCCESS;
 }
 
 int msUnionLayerWhichShapes(layerObj *layer, rectObj rect, int isQuery)
 {
-    int i;
-    layerObj* srclayer;
-    rectObj srcRect;
-    msUnionLayerInfo* layerinfo = (msUnionLayerInfo*)layer->layerinfo;
+  int i;
+  layerObj* srclayer;
+  rectObj srcRect;
+  msUnionLayerInfo* layerinfo = (msUnionLayerInfo*)layer->layerinfo;
 
-    if (!layerinfo || !layer->map)
-        return MS_FAILURE;
+  if (!layerinfo || !layer->map)
+    return MS_FAILURE;
 
-    for (i = 0; i < layerinfo->layerCount; i++)
-    {
-        layerObj* srclayer = &layerinfo->layers[i];
-
-        if (layer->styleitem && layer->numitems == 0)
-        {
-            /* need to initialize items */
-            msUnionLayerFreeExpressionTokens(srclayer);
-            
-            /* get only the required items */
-            if (msLayerWhichItems(srclayer, MS_FALSE, NULL) != MS_SUCCESS)
-                return MS_FAILURE;
-        }
+  for (i = 0; i < layerinfo->layerCount; i++) {
+    layerObj* srclayer = &layerinfo->layers[i];
 
-        srcRect = rect;
-#ifdef USE_PROJ
-        if(srclayer->transform == MS_TRUE && srclayer->project && layer->transform == MS_TRUE && layer->project &&msProjectionsDiffer(&(srclayer->projection), &(layer->projection)))
-            msProjectRect(&layer->projection, &srclayer->projection, &srcRect); /* project the searchrect to source coords */
-#endif        
-        layerinfo->status[i] = msLayerWhichShapes(srclayer, srcRect, isQuery);
-        if (layerinfo->status[i] == MS_FAILURE)
-            return MS_FAILURE;
+    if (layerinfo->status[i] != MS_SUCCESS)
+      continue; /* skip empty layers */
+
+    if (layer->styleitem && layer->numitems == 0) {
+      /* need to initialize items */
+      msUnionLayerFreeExpressionTokens(srclayer);
+
+      /* get only the required items */
+      if (msLayerWhichItems(srclayer, MS_FALSE, NULL) != MS_SUCCESS)
+        return MS_FAILURE;
     }
 
-    layerinfo->layerIndex = 0;
-    srclayer = &layerinfo->layers[0];
-    
-    msFree(layerinfo->classgroup);
+    srcRect = rect;
+#ifdef USE_PROJ
+    if(srclayer->transform == MS_TRUE && srclayer->project && layer->transform == MS_TRUE && layer->project &&msProjectionsDiffer(&(srclayer->projection), &(layer->projection)))
+      msProjectRect(&layer->projection, &srclayer->projection, &srcRect); /* project the searchrect to source coords */
+#endif
+    layerinfo->status[i] = msLayerWhichShapes(srclayer, srcRect, isQuery);
+    if (layerinfo->status[i] == MS_FAILURE)
+      return MS_FAILURE;
+  }
 
-    layerinfo->classgroup = NULL;
-    layerinfo->nclasses = 0;
+  layerinfo->layerIndex = 0;
+  srclayer = &layerinfo->layers[0];
 
-    if (srclayer->classgroup && srclayer->numclasses > 0)
-        layerinfo->classgroup = msAllocateValidClassGroups(srclayer, &layerinfo->nclasses);
+  msFree(layerinfo->classgroup);
 
-    return MS_SUCCESS;
+  layerinfo->classgroup = NULL;
+  layerinfo->nclasses = 0;
+
+  if (srclayer->classgroup && srclayer->numclasses > 0)
+    layerinfo->classgroup = msAllocateValidClassGroups(srclayer, &layerinfo->nclasses);
+
+  return MS_SUCCESS;
 }
 
 static int BuildFeatureAttributes(layerObj *layer, layerObj* srclayer, shapeObj *shape)
 {
-    int i;
-    char **values;
-    int* itemindexes = layer->iteminfo;
-    
-    values = malloc(sizeof(char*) * (layer->numitems));
-    MS_CHECK_ALLOC(values, layer->numitems * sizeof(char*), MS_FAILURE);;
-
-    for (i = 0; i < layer->numitems; i++)
-    {
-        if (itemindexes[i] == MSUNION_SOURCELAYERNAMEINDEX)
-            values[i] = msStrdup(srclayer->name);
-        else if (itemindexes[i] == MSUNION_SOURCELAYERGROUPINDEX)
-            values[i] = msStrdup(srclayer->group);
-        else if (itemindexes[i] == MSUNION_SOURCELAYERVISIBLEINDEX)
-        {
-            if (srclayer->status == MS_OFF)
-                values[i] = msStrdup("0");
-            else
-                values[i] = msStrdup("1");
-        }
-        else if (shape->values[itemindexes[i]])
-            values[i] = msStrdup(shape->values[itemindexes[i]]);
-        else
-            values[i] = msStrdup("");
-    }
+  int i;
+  char **values;
+  int* itemindexes = layer->iteminfo;
+
+  values = malloc(sizeof(char*) * (layer->numitems));
+  MS_CHECK_ALLOC(values, layer->numitems * sizeof(char*), MS_FAILURE);;
+
+  for (i = 0; i < layer->numitems; i++) {
+    if (itemindexes[i] == MSUNION_SOURCELAYERNAMEINDEX)
+      values[i] = msStrdup(srclayer->name);
+    else if (itemindexes[i] == MSUNION_SOURCELAYERGROUPINDEX)
+      values[i] = msStrdup(srclayer->group);
+    else if (itemindexes[i] == MSUNION_SOURCELAYERVISIBLEINDEX) {
+      if (srclayer->status == MS_OFF)
+        values[i] = msStrdup("0");
+      else
+        values[i] = msStrdup("1");
+    } else if (shape->values[itemindexes[i]])
+      values[i] = msStrdup(shape->values[itemindexes[i]]);
+    else
+      values[i] = msStrdup("");
+  }
 
-    if (shape->values)
-        msFreeCharArray(shape->values, shape->numvalues);
+  if (shape->values)
+    msFreeCharArray(shape->values, shape->numvalues);
 
-    shape->values = values;
-    shape->numvalues = layer->numitems;
+  shape->values = values;
+  shape->numvalues = layer->numitems;
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 /* find the next shape with the appropriate shape type */
@@ -423,281 +464,271 @@ static int BuildFeatureAttributes(layerObj *layer, layerObj* srclayer, shapeObj
 /* MS_DONE => no more data */
 int msUnionLayerNextShape(layerObj *layer, shapeObj *shape)
 {
-    int rv;
-    layerObj* srclayer;
-    msUnionLayerInfo* layerinfo = (msUnionLayerInfo*)layer->layerinfo;
-
-    if (!layerinfo || !layer->map)
-        return MS_FAILURE;
-
-    if (layerinfo->layerIndex < 0 || layerinfo->layerIndex >= layerinfo->layerCount)
-        return MS_FAILURE;
-
-    rv = MS_DONE;
-
-    while (layerinfo->layerIndex < layerinfo->layerCount)
-    {
-        srclayer = &layerinfo->layers[layerinfo->layerIndex];
-        if (layerinfo->status[layerinfo->layerIndex] == MS_SUCCESS)
-        {
-            while ((rv = srclayer->vtable->LayerNextShape(srclayer, shape)) == MS_SUCCESS)
-            {
-                if(layer->styleitem) 
-                {
-                    /* need to retrieve the source layer classindex if styleitem AUTO is set */
-                    layerinfo->classIndex = msShapeGetClass(srclayer, layer->map, shape, layerinfo->classgroup, layerinfo->nclasses);
-                    if(layerinfo->classIndex < 0 || layerinfo->classIndex >= srclayer->numclasses) 
-                    {
-                        // this shape is not visible, skip it
-                        msFreeShape(shape);
-                        if (rv == MS_SUCCESS)
-                            continue;
-                        else 
-                            break;
-                    }
-                    if(srclayer->styleitem && strcasecmp(srclayer->styleitem, "AUTO") != 0) 
-                    {
-                        /* Generic feature style handling as per RFC-61 */
-                        msLayerGetFeatureStyle(layer->map, srclayer, srclayer->class[layerinfo->classIndex], shape);
-                    }
-                    /* set up annotation */
-                    msFree(layerinfo->classText);
-                    if((srclayer->class[layerinfo->classIndex]->text.string || srclayer->labelitem) && 
-                        srclayer->class[layerinfo->classIndex]->label.size != -1)
-                        layerinfo->classText = msShapeGetAnnotation(srclayer, shape);
-                    else
-                        layerinfo->classText = NULL;
-                }
+  int rv;
+  layerObj* srclayer;
+  msUnionLayerInfo* layerinfo = (msUnionLayerInfo*)layer->layerinfo;
+
+  if (!layerinfo || !layer->map)
+    return MS_FAILURE;
+
+  if (layerinfo->layerIndex < 0 || layerinfo->layerIndex >= layerinfo->layerCount)
+    return MS_FAILURE;
+
+  rv = MS_DONE;
+
+  while (layerinfo->layerIndex < layerinfo->layerCount) {
+    srclayer = &layerinfo->layers[layerinfo->layerIndex];
+    if (layerinfo->status[layerinfo->layerIndex] == MS_SUCCESS) {
+      while ((rv = srclayer->vtable->LayerNextShape(srclayer, shape)) == MS_SUCCESS) {
+        if(layer->styleitem) {
+          /* need to retrieve the source layer classindex if styleitem AUTO is set */
+          layerinfo->classIndex = msShapeGetClass(srclayer, layer->map, shape, layerinfo->classgroup, layerinfo->nclasses);
+          if(layerinfo->classIndex < 0 || layerinfo->classIndex >= srclayer->numclasses) {
+            /*  this shape is not visible, skip it */
+            msFreeShape(shape);
+            if (rv == MS_SUCCESS)
+              continue;
+            else
+              break;
+          }
+          if(srclayer->styleitem && strcasecmp(srclayer->styleitem, "AUTO") != 0) {
+            /* Generic feature style handling as per RFC-61 */
+            msLayerGetFeatureStyle(layer->map, srclayer, srclayer->class[layerinfo->classIndex], shape);
+          }
+          /* set up annotation */
+          msFree(layerinfo->classText);
+          if(srclayer->class[layerinfo->classIndex]->numlabels > 0) {
+            msShapeGetAnnotation(srclayer, shape);
+            layerinfo->classText = msStrdup(srclayer->class[layerinfo->classIndex]->labels[0]->annotext); /* pull text from the first label only */
+          } else
+            layerinfo->classText = NULL;
+        }
 
 #ifdef USE_PROJ
-                /* reproject to the target layer */
-                if(srclayer->project && msProjectionsDiffer(&(srclayer->projection), &(layer->projection)))
-	                msProjectShape(&(srclayer->projection), &(layer->projection), shape);
-                else
-	                srclayer->project = MS_FALSE;
+        /* reproject to the target layer */
+        if(srclayer->project && msProjectionsDiffer(&(srclayer->projection), &(layer->projection)))
+          msProjectShape(&(srclayer->projection), &(layer->projection), shape);
+        else
+          srclayer->project = MS_FALSE;
 #endif
-                /* update the layer styles with the bound values */
-                if(msBindLayerToShape(srclayer, shape, MS_FALSE) != MS_SUCCESS)
-                    return MS_FAILURE;
-                
-                shape->tileindex = layerinfo->layerIndex;
-
-                /* construct the item array */
-                if (layer->iteminfo)
-                    rv = BuildFeatureAttributes(layer, srclayer, shape);
-
-                /* check the layer filter condition */
-                if(layer->filter.string != NULL && layer->numitems > 0 && layer->iteminfo)
-                {
-                    if (layer->filter.type == MS_EXPRESSION && layer->filter.tokens == NULL)
-                        msTokenizeExpression(&(layer->filter), layer->items, &(layer->numitems));
-
-                    if (!msEvalExpression(layer, shape, &(layer->filter), layer->filteritemindex)) 
-                    {
-                        /* this shape is filtered */
-                        msFreeShape(shape);
-                        continue;
-                    }
-                }
-
-                return rv;
-            }
-        }
+        /* update the layer styles with the bound values */
+        if(msBindLayerToShape(srclayer, shape, MS_FALSE) != MS_SUCCESS)
+          return MS_FAILURE;
 
-        ++layerinfo->layerIndex;
-        if (layerinfo->layerIndex == layerinfo->layerCount)
-        {
-            layerinfo->layerIndex = 0;
-            return MS_DONE;
+        shape->tileindex = layerinfo->layerIndex;
+
+        /* construct the item array */
+        if (layer->iteminfo)
+          rv = BuildFeatureAttributes(layer, srclayer, shape);
+
+        /* check the layer filter condition */
+        if(layer->filter.string != NULL && layer->numitems > 0 && layer->iteminfo) {
+          if (layer->filter.type == MS_EXPRESSION && layer->filter.tokens == NULL)
+            msTokenizeExpression(&(layer->filter), layer->items, &(layer->numitems));
+
+          if (!msEvalExpression(layer, shape, &(layer->filter), layer->filteritemindex)) {
+            /* this shape is filtered */
+            msFreeShape(shape);
+            continue;
+          }
         }
-        
-        /* allocate the classgroups for the next layer */
-        msFree(layerinfo->classgroup);
 
-        layerinfo->classgroup = NULL;
-        layerinfo->nclasses = 0;
+        return rv;
+      }
+    }
 
-        if (srclayer->classgroup && srclayer->numclasses > 0)
-            layerinfo->classgroup = msAllocateValidClassGroups(srclayer, &layerinfo->nclasses);
+    ++layerinfo->layerIndex;
+    if (layerinfo->layerIndex == layerinfo->layerCount) {
+      layerinfo->layerIndex = 0;
+      return MS_DONE;
     }
 
-    return rv;
+    /* allocate the classgroups for the next layer */
+    msFree(layerinfo->classgroup);
+
+    layerinfo->classgroup = NULL;
+    layerinfo->nclasses = 0;
+
+    if (srclayer->classgroup && srclayer->numclasses > 0)
+      layerinfo->classgroup = msAllocateValidClassGroups(srclayer, &layerinfo->nclasses);
+  }
+
+  return rv;
 }
 
 /* Random access of the feature. */
 int msUnionLayerGetShape(layerObj *layer, shapeObj *shape, resultObj *record)
 {
-	int rv;
-    layerObj* srclayer;
-    long tile = record->tileindex;
-    msUnionLayerInfo* layerinfo = (msUnionLayerInfo*)layer->layerinfo;
+  int rv;
+  layerObj* srclayer;
+  long tile = record->tileindex;
+  msUnionLayerInfo* layerinfo = (msUnionLayerInfo*)layer->layerinfo;
 
-    if (!layerinfo || !layer->map)
-        return MS_FAILURE;
+  if (!layerinfo || !layer->map)
+    return MS_FAILURE;
 
-    if (tile < 0 || tile >= layerinfo->layerCount)
-    {
-        msSetError(MS_MISCERR, "Invalid tile index: %s", layer->name);
-        return MS_FAILURE;
-    }
+  if (tile < 0 || tile >= layerinfo->layerCount) {
+    msSetError(MS_MISCERR, "Invalid tile index: %s", "msUnionLayerGetShape()", layer->name);
+    return MS_FAILURE;
+  }
 
-    srclayer = &layerinfo->layers[tile];
-    record->tileindex = 0;
-    rv = srclayer->vtable->LayerGetShape(srclayer, shape, record);
-    record->tileindex = tile;
+  srclayer = &layerinfo->layers[tile];
+  record->tileindex = 0;
+  rv = srclayer->vtable->LayerGetShape(srclayer, shape, record);
+  record->tileindex = tile;
 
-    if (rv == MS_SUCCESS)
-    {
+  if (rv == MS_SUCCESS) {
 #ifdef USE_PROJ
-            /* reproject to the target layer */
-            if(srclayer->project && msProjectionsDiffer(&(srclayer->projection), &(layer->projection)))
-	            msProjectShape(&(srclayer->projection), &(layer->projection), shape);
-            else
-	            srclayer->project = MS_FALSE;
+    /* reproject to the target layer */
+    if(srclayer->project && msProjectionsDiffer(&(srclayer->projection), &(layer->projection)))
+      msProjectShape(&(srclayer->projection), &(layer->projection), shape);
+    else
+      srclayer->project = MS_FALSE;
 #endif
-        shape->tileindex = tile;
+    shape->tileindex = tile;
 
-        /* construct the item array */
-        if (layer->iteminfo)
-            rv = BuildFeatureAttributes(layer, srclayer, shape);
-    }
+    /* construct the item array */
+    if (layer->iteminfo)
+      rv = BuildFeatureAttributes(layer, srclayer, shape);
+  }
 
-    return rv;
+  return rv;
 }
 
 /* Query for the items collection */
 int msUnionLayerGetItems(layerObj *layer)
 {
-    /* we support certain built in attributes */
-    layer->numitems = 2;
-    layer->items = malloc(sizeof(char*) * (layer->numitems));
-    MS_CHECK_ALLOC(layer->items, layer->numitems * sizeof(char*), MS_FAILURE);
-    layer->items[0] = msStrdup(MSUNION_SOURCELAYERNAME);
-    layer->items[1] = msStrdup(MSUNION_SOURCELAYERGROUP);
-
-    return msUnionLayerInitItemInfo(layer);
+  /* we support certain built in attributes */
+  layer->numitems = 2;
+  layer->items = malloc(sizeof(char*) * (layer->numitems));
+  MS_CHECK_ALLOC(layer->items, layer->numitems * sizeof(char*), MS_FAILURE);
+  layer->items[0] = msStrdup(MSUNION_SOURCELAYERNAME);
+  layer->items[1] = msStrdup(MSUNION_SOURCELAYERGROUP);
+
+  return msUnionLayerInitItemInfo(layer);
 }
 
 int msUnionLayerGetNumFeatures(layerObj *layer)
 {
-    int i, c, numFeatures;
-    msUnionLayerInfo* layerinfo = (msUnionLayerInfo*)layer->layerinfo;
+  int i, c, numFeatures;
+  msUnionLayerInfo* layerinfo = (msUnionLayerInfo*)layer->layerinfo;
 
-    if (!layerinfo || !layer->map)
-        return 0;
+  if (!layerinfo || !layer->map)
+    return 0;
 
-    numFeatures = 0;
+  numFeatures = 0;
 
-    for (i = 0; i < layerinfo->layerCount; i++)
-    {
-        c = msLayerGetNumFeatures(&layerinfo->layers[i]);
-        if (c > 0)
-            numFeatures += c;
-    }
+  for (i = 0; i < layerinfo->layerCount; i++) {
+    if (layerinfo->status[i] != MS_SUCCESS)
+      continue; /* skip empty layers */
+
+    c = msLayerGetNumFeatures(&layerinfo->layers[i]);
+    if (c > 0)
+      numFeatures += c;
+  }
 
-    return numFeatures;
+  return numFeatures;
 }
 
 static int msUnionLayerGetAutoStyle(mapObj *map, layerObj *layer, classObj *c, shapeObj* shape)
 {
-    layerObj* srclayer;
-    msUnionLayerInfo* layerinfo = (msUnionLayerInfo*)layer->layerinfo;
+  layerObj* srclayer;
+  msUnionLayerInfo* layerinfo = (msUnionLayerInfo*)layer->layerinfo;
 
-    if (!layerinfo || !layer->map)
+  if (!layerinfo || !layer->map)
+    return MS_FAILURE;
+
+  if (shape->tileindex < 0 || shape->tileindex >= layerinfo->layerCount) {
+    msSetError(MS_MISCERR, "Invalid tile index: %s", "msUnionLayerGetAutoStyle()", layer->name);
+    return MS_FAILURE;
+  }
+
+  srclayer = &layerinfo->layers[shape->tileindex];
+
+  if(srclayer->styleitem && strcasecmp(srclayer->styleitem, "AUTO") == 0) {
+    int rv;
+    int tileindex = shape->tileindex;
+    shape->tileindex = 0;
+    rv = msLayerGetAutoStyle(map, srclayer, c, shape);
+    shape->tileindex = tileindex;
+    return rv;
+  } else {
+    int i,j;
+    classObj* src = srclayer->class[layerinfo->classIndex];
+    /* copy the style from the current class index */
+    /* free any previous styles on the dst layer */
+
+    resetClassStyle(c);
+
+    for (i = 0; i < src->numstyles; i++) {
+      if (msMaybeAllocateClassStyle(c, i))
         return MS_FAILURE;
 
-    if (shape->tileindex < 0 || shape->tileindex >= layerinfo->layerCount)
-    {
-        msSetError(MS_MISCERR, "Invalid tile index: %s", layer->name);
+      if (msCopyStyle(c->styles[i], src->styles[i]) != MS_SUCCESS) {
+        msSetError(MS_MEMERR, "Failed to copy style.", "msUnionLayerGetAutoStyle()");
         return MS_FAILURE;
+      }
+      /* remove the bindings on the style */
+      for(j=0; j<MS_STYLE_BINDING_LENGTH; j++) {
+        msFree(c->styles[i]->bindings[j].item);
+        c->styles[i]->bindings[j].item = NULL;
+      }
+      c->styles[i]->numbindings = 0;
     }
 
-    srclayer = &layerinfo->layers[shape->tileindex];
+    for (i = 0; i < src->numlabels; i++) {
+      // RFC77 TODO: allocation need to be done, but is the right way (from mapcopy.c)?
+      if (msGrowClassLabels(c) == NULL)
+        return MS_FAILURE;
+      initLabel(c->labels[i]);
 
-    if(srclayer->styleitem && strcasecmp(srclayer->styleitem, "AUTO") == 0) 
-    {
-        int rv;
-        int tileindex = shape->tileindex;
-        shape->tileindex = 0;
-        rv = msLayerGetAutoStyle(map, srclayer, c, shape);
-        shape->tileindex = tileindex;
-        return rv;
+      if (msCopyLabel(c->labels[i], src->labels[i]) != MS_SUCCESS) {
+        msSetError(MS_MEMERR, "Failed to copy label.", "msUnionLayerGetAutoStyle()");
+        return MS_FAILURE;
+      }
+
+      /* remove the bindings on the label */
+      for(j=0; j<MS_LABEL_BINDING_LENGTH; j++) {
+        msFree(c->labels[i]->bindings[j].item);
+        c->labels[i]->bindings[j].item = NULL;
+      }
+      c->labels[i]->numbindings = 0;
     }
-    else
-    {
-        int i,j;
-        classObj* src = srclayer->class[layerinfo->classIndex];
-        /* copy the style from the current class index */
-        /* free any previous styles on the dst layer */
-
-        resetClassStyle(c);
-
-        for (i = 0; i < src->numstyles; i++) 
-        {
-            if (msMaybeAllocateClassStyle(c, i))
-                return MS_FAILURE;
-
-            if (msCopyStyle(c->styles[i], src->styles[i]) != MS_SUCCESS) 
-            {
-                msSetError(MS_MEMERR, "Failed to copy style.", "msUnionLayerGetAutoStyle()");
-                return MS_FAILURE;
-            }
-            /* remove the bindings on the style */
-            for(j=0; j<MS_STYLE_BINDING_LENGTH; j++)
-            {
-                msFree(c->styles[i]->bindings[j].item);
-                c->styles[i]->bindings[j].item = NULL;
-            }
-            c->styles[i]->numbindings = 0;
-        }
-
-        if (msCopyLabel(&(c->label), &(src->label)) != MS_SUCCESS) 
-        {
-            msSetError(MS_MEMERR, "Failed to copy label.", "msCopyClass()");
-            return MS_FAILURE;
-        }
+    c->numlabels = src->numlabels;
 
-        /* remove the bindings on the label */
-        for(j=0; j<MS_LABEL_BINDING_LENGTH; j++)
-        {
-            msFree(c->label.bindings[j].item);
-            c->label.bindings[j].item = NULL;
-        }
-        c->label.numbindings = 0;
-
-        c->type = src->type;
-        c->layer = layer;
-        c->text.string = layerinfo->classText;
-        layerinfo->classText = NULL;
-    }
-    return MS_SUCCESS;
+    c->type = src->type;
+    c->layer = layer;
+    c->text.string = layerinfo->classText;
+    layerinfo->classText = NULL;
+  }
+  return MS_SUCCESS;
 }
 
 int msUnionLayerCopyVirtualTable(layerVTableObj* vtable)
 {
-    vtable->LayerInitItemInfo = msUnionLayerInitItemInfo;
-    vtable->LayerFreeItemInfo = msUnionLayerFreeItemInfo;
-    vtable->LayerOpen = msUnionLayerOpen;
-    vtable->LayerIsOpen = msUnionLayerIsOpen;
-    vtable->LayerWhichShapes = msUnionLayerWhichShapes;
-    vtable->LayerNextShape = msUnionLayerNextShape;
-    vtable->LayerGetShape = msUnionLayerGetShape;
-
-    vtable->LayerClose = msUnionLayerClose;
-
-    vtable->LayerGetItems = msUnionLayerGetItems;
-    vtable->LayerCloseConnection = msUnionLayerClose;
-    vtable->LayerGetAutoStyle = msUnionLayerGetAutoStyle;
-    
-    vtable->LayerGetNumFeatures = msUnionLayerGetNumFeatures;
+  vtable->LayerInitItemInfo = msUnionLayerInitItemInfo;
+  vtable->LayerFreeItemInfo = msUnionLayerFreeItemInfo;
+  vtable->LayerOpen = msUnionLayerOpen;
+  vtable->LayerIsOpen = msUnionLayerIsOpen;
+  vtable->LayerWhichShapes = msUnionLayerWhichShapes;
+  vtable->LayerNextShape = msUnionLayerNextShape;
+  vtable->LayerGetShape = msUnionLayerGetShape;
 
-    return MS_SUCCESS;
+  vtable->LayerClose = msUnionLayerClose;
+
+  vtable->LayerGetItems = msUnionLayerGetItems;
+  vtable->LayerCloseConnection = msUnionLayerClose;
+  vtable->LayerGetAutoStyle = msUnionLayerGetAutoStyle;
+
+  vtable->LayerGetNumFeatures = msUnionLayerGetNumFeatures;
+
+  return MS_SUCCESS;
 }
 
 int msUnionLayerInitializeVirtualTable(layerObj *layer)
 {
-    assert(layer != NULL);
-    assert(layer->vtable != NULL);
+  assert(layer != NULL);
+  assert(layer->vtable != NULL);
 
-    return msUnionLayerCopyVirtualTable(layer->vtable);
+  return msUnionLayerCopyVirtualTable(layer->vtable);
 }
diff --git a/maputil.c b/maputil.c
index aa739e9..092d78d 100644
--- a/maputil.c
+++ b/maputil.c
@@ -19,7 +19,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -46,12 +46,21 @@
 #include <process.h>
 #endif
 
-MS_CVSID("$Id$")
+
 
 extern char *msyystring_buffer;
 extern int msyylex_destroy(void);
 extern int yyparse(parseObj *);
 
+int msScaleInBounds(double scale, double minscale, double maxscale)
+{
+  if(scale > 0) {
+    if(maxscale != -1 && scale >= maxscale) return MS_FALSE;
+    if(minscale != -1 && scale < minscale) return MS_FALSE;
+  }
+  return MS_TRUE;
+}
+
 /*
 ** Helper functions to convert from strings to other types or objects.
 */
@@ -74,7 +83,7 @@ static int bindColorAttribute(colorObj *attribute, char *value)
   int len;
 
   if(!value || ((len = strlen(value)) == 0)) return MS_FAILURE;
-  
+
   if(value[0] == '#' && (len == 7 || len == 9)) { /* got a hex color */
     char hex[2];
 
@@ -114,7 +123,9 @@ static int bindColorAttribute(colorObj *attribute, char *value)
   return MS_FAILURE; /* shouldn't get here */
 }
 
-static void bindStyle(layerObj *layer, shapeObj *shape, styleObj *style, int querymapMode) {
+static void bindStyle(layerObj *layer, shapeObj *shape, styleObj *style, int drawmode)
+{
+  assert(MS_DRAW_FEATURES(drawmode));
   if(style->numbindings > 0) {
     if(style->bindings[MS_STYLE_BINDING_SYMBOL].index != -1) {
       style->symbol = msGetSymbolIndex(&(layer->map->symbolset), shape->values[style->bindings[MS_STYLE_BINDING_SYMBOL].index], MS_TRUE);
@@ -132,130 +143,158 @@ static void bindStyle(layerObj *layer, shapeObj *shape, styleObj *style, int que
       style->width = 1;
       bindDoubleAttribute(&style->width, shape->values[style->bindings[MS_STYLE_BINDING_WIDTH].index]);
     }
-    if(style->bindings[MS_STYLE_BINDING_COLOR].index != -1 && (querymapMode != MS_TRUE)) {
+    if(style->bindings[MS_STYLE_BINDING_COLOR].index != -1 && !MS_DRAW_QUERY(drawmode)) {
       MS_INIT_COLOR(style->color, -1,-1,-1,255);
       bindColorAttribute(&style->color, shape->values[style->bindings[MS_STYLE_BINDING_COLOR].index]);
     }
-    if(style->bindings[MS_STYLE_BINDING_OUTLINECOLOR].index != -1 && (querymapMode != MS_TRUE)) {
+    if(style->bindings[MS_STYLE_BINDING_OUTLINECOLOR].index != -1 && !MS_DRAW_QUERY(drawmode)) {
       MS_INIT_COLOR(style->outlinecolor, -1,-1,-1,255);
       bindColorAttribute(&style->outlinecolor, shape->values[style->bindings[MS_STYLE_BINDING_OUTLINECOLOR].index]);
     }
     if(style->bindings[MS_STYLE_BINDING_OUTLINEWIDTH].index != -1) {
-        style->outlinewidth = 1;
-        bindDoubleAttribute(&style->outlinewidth, shape->values[style->bindings[MS_STYLE_BINDING_OUTLINEWIDTH].index]);
+      style->outlinewidth = 1;
+      bindDoubleAttribute(&style->outlinewidth, shape->values[style->bindings[MS_STYLE_BINDING_OUTLINEWIDTH].index]);
     }
     if(style->bindings[MS_STYLE_BINDING_OPACITY].index != -1) {
       style->opacity = 100;
       bindIntegerAttribute(&style->opacity, shape->values[style->bindings[MS_STYLE_BINDING_OPACITY].index]);
-
-      if(style->opacity < 100) {
-        int alpha;
-	alpha = MS_NINT(style->opacity*2.55);
-
-	style->color.alpha = alpha;
-	style->outlinecolor.alpha = alpha;
-	style->backgroundcolor.alpha = alpha;
-
-	style->mincolor.alpha = alpha;
-	style->maxcolor.alpha = alpha;
-      }
+    }
+    if(style->bindings[MS_STYLE_BINDING_OFFSET_X].index != -1) {
+      style->offsetx = 0;
+      bindDoubleAttribute(&style->offsetx, shape->values[style->bindings[MS_STYLE_BINDING_OFFSET_X].index]);
+    }
+    if(style->bindings[MS_STYLE_BINDING_OFFSET_Y].index != -1) {
+      style->offsety = 0;
+      bindDoubleAttribute(&style->offsety, shape->values[style->bindings[MS_STYLE_BINDING_OFFSET_Y].index]);
+    }
+    if(style->bindings[MS_STYLE_BINDING_POLAROFFSET_PIXEL].index != -1) {
+      style->polaroffsetpixel = 0;
+      bindDoubleAttribute(&style->polaroffsetpixel, shape->values[style->bindings[MS_STYLE_BINDING_POLAROFFSET_PIXEL].index]);
+    }
+    if(style->bindings[MS_STYLE_BINDING_POLAROFFSET_ANGLE].index != -1) {
+      style->polaroffsetangle = 0;
+      bindDoubleAttribute(&style->polaroffsetangle, shape->values[style->bindings[MS_STYLE_BINDING_POLAROFFSET_ANGLE].index]);
+    }
+    if(style->bindings[MS_STYLE_BINDING_OUTLINEWIDTH].index != -1) {
+      style->outlinewidth = 1;
+      bindDoubleAttribute(&style->outlinewidth, shape->values[style->bindings[MS_STYLE_BINDING_OUTLINEWIDTH].index]);
+    }
+    if(style->opacity < 100 || style->color.alpha != 255 ) {
+      int alpha;
+      alpha = MS_NINT(style->opacity*2.55);
+      style->color.alpha = alpha;
+      style->outlinecolor.alpha = alpha;
+      style->backgroundcolor.alpha = alpha;
+      style->mincolor.alpha = alpha;
+      style->maxcolor.alpha = alpha;
     }
   }
 }
 
-/*
-** Function to bind various layer properties to shape attributes.
-*/
-int msBindLayerToShape(layerObj *layer, shapeObj *shape, int querymapMode)
+static void bindLabel(layerObj *layer, shapeObj *shape, labelObj *label, int drawmode)
 {
-  int i, j;
-  labelObj *label; /* for brevity */
+  int i;
+  assert(MS_DRAW_LABELS(drawmode));
 
-  if(!layer || !shape) return MS_FAILURE;
+  /* check the label styleObj's (TODO: do we need to use querymapMode here? */
+  for(i=0; i<label->numstyles; i++) {
+    /* force MS_DRAWMODE_FEATURES for label styles */
+    bindStyle(layer, shape, label->styles[i], drawmode|MS_DRAWMODE_FEATURES); 
+  }
 
-  for(i=0; i<layer->numclasses; i++) {
+  if(label->numbindings > 0) {
+    if(label->bindings[MS_LABEL_BINDING_ANGLE].index != -1) {
+      label->angle = 0.0;
+      bindDoubleAttribute(&label->angle, shape->values[label->bindings[MS_LABEL_BINDING_ANGLE].index]);
+    }
 
-    /* check the styleObj's */
-    for(j=0; j<layer->class[i]->numstyles; j++) {
-      bindStyle(layer, shape, layer->class[i]->styles[j], querymapMode);
-    } /* next styleObj */
+    if(label->bindings[MS_LABEL_BINDING_SIZE].index != -1) {
+      label->size = 1;
+      bindDoubleAttribute(&label->size, shape->values[label->bindings[MS_LABEL_BINDING_SIZE].index]);
+    }
 
-    /* check the labelObj */
-    label = &(layer->class[i]->label);
+    if(label->bindings[MS_LABEL_BINDING_COLOR].index != -1) {
+      MS_INIT_COLOR(label->color, -1,-1,-1,255);
+      bindColorAttribute(&label->color, shape->values[label->bindings[MS_LABEL_BINDING_COLOR].index]);
+    }
 
-    /* check the label styleObj's */
-    for(j=0; j<label->numstyles; j++) {
-      bindStyle(layer, shape, label->styles[j], querymapMode);
+    if(label->bindings[MS_LABEL_BINDING_OUTLINECOLOR].index != -1) {
+      MS_INIT_COLOR(label->outlinecolor, -1,-1,-1,255);
+      bindColorAttribute(&label->outlinecolor, shape->values[label->bindings[MS_LABEL_BINDING_OUTLINECOLOR].index]);
     }
 
-    if(label->numbindings > 0) {
-      if(label->bindings[MS_LABEL_BINDING_ANGLE].index != -1) {
-        label->angle = 0.0;
-        bindDoubleAttribute(&label->angle, shape->values[label->bindings[MS_LABEL_BINDING_ANGLE].index]);
-      }
+    if(label->bindings[MS_LABEL_BINDING_FONT].index != -1) {
+      msFree(label->font);
+      label->font = msStrdup(shape->values[label->bindings[MS_LABEL_BINDING_FONT].index]);
+    }
 
-      if(label->bindings[MS_LABEL_BINDING_SIZE].index != -1) {
-        label->size = 1;
-        bindDoubleAttribute(&label->size, shape->values[label->bindings[MS_LABEL_BINDING_SIZE].index]);
-      }
+    if(label->bindings[MS_LABEL_BINDING_PRIORITY].index != -1) {
+      label->priority = MS_DEFAULT_LABEL_PRIORITY;
+      bindIntegerAttribute(&label->priority, shape->values[label->bindings[MS_LABEL_BINDING_PRIORITY].index]);
+    }
 
-      if(label->bindings[MS_LABEL_BINDING_COLOR].index != -1) {
-        MS_INIT_COLOR(label->color, -1,-1,-1,255);
-        bindColorAttribute(&label->color, shape->values[label->bindings[MS_LABEL_BINDING_COLOR].index]);
-      }
+    if(label->bindings[MS_LABEL_BINDING_SHADOWSIZEX].index != -1) {
+      label->shadowsizex = 1;
+      bindIntegerAttribute(&label->shadowsizex, shape->values[label->bindings[MS_LABEL_BINDING_SHADOWSIZEX].index]);
+    }
+    if(label->bindings[MS_LABEL_BINDING_SHADOWSIZEY].index != -1) {
+      label->shadowsizey = 1;
+      bindIntegerAttribute(&label->shadowsizey, shape->values[label->bindings[MS_LABEL_BINDING_SHADOWSIZEY].index]);
+    }
 
-      if(label->bindings[MS_LABEL_BINDING_OUTLINECOLOR].index != -1) {
-        MS_INIT_COLOR(label->outlinecolor, -1,-1,-1,255);
-        bindColorAttribute(&label->outlinecolor, shape->values[label->bindings[MS_LABEL_BINDING_OUTLINECOLOR].index]);
+    if(label->bindings[MS_LABEL_BINDING_POSITION].index != -1) {
+      int tmpPosition;
+      bindIntegerAttribute(&tmpPosition, shape->values[label->bindings[MS_LABEL_BINDING_POSITION].index]);
+      if(tmpPosition != 0) { /* is this test sufficient? */
+        label->position = tmpPosition;
+      } else { /* Integer binding failed, look for strings like cc, ul, lr, etc... */
+        if(strlen(shape->values[label->bindings[MS_LABEL_BINDING_POSITION].index]) == 2) {
+          char *vp = shape->values[label->bindings[MS_LABEL_BINDING_POSITION].index];
+          if(!strncasecmp(vp,"ul",2))
+            label->position = MS_UL;
+          else if(!strncasecmp(vp,"lr",2))
+            label->position = MS_LR;
+          else if(!strncasecmp(vp,"ur",2))
+            label->position = MS_UR;
+          else if(!strncasecmp(vp,"ll",2))
+            label->position = MS_LL;
+          else if(!strncasecmp(vp,"cr",2))
+            label->position = MS_CR;
+          else if(!strncasecmp(vp,"cl",2))
+            label->position = MS_CL;
+          else if(!strncasecmp(vp,"uc",2))
+            label->position = MS_UC;
+          else if(!strncasecmp(vp,"lc",2))
+            label->position = MS_LC;
+          else if(!strncasecmp(vp,"cc",2))
+            label->position = MS_CC;
+        }
       }
+    }
+  }
+}
 
-      if(label->bindings[MS_LABEL_BINDING_FONT].index != -1) {
-        msFree(label->font);
-        label->font = msStrdup(shape->values[label->bindings[MS_LABEL_BINDING_FONT].index]);
-      }
+/*
+** Function to bind various layer properties to shape attributes.
+*/
+int msBindLayerToShape(layerObj *layer, shapeObj *shape, int drawmode)
+{
+  int i, j;
 
-      if(label->bindings[MS_LABEL_BINDING_PRIORITY].index != -1) {
-        label->priority = MS_DEFAULT_LABEL_PRIORITY;
-        bindIntegerAttribute(&label->priority, shape->values[label->bindings[MS_LABEL_BINDING_PRIORITY].index]);
+  if(!layer || !shape) return MS_FAILURE;
+
+  for(i=0; i<layer->numclasses; i++) {
+    /* check the styleObj's */
+    if(MS_DRAW_FEATURES(drawmode)) {
+      for(j=0; j<layer->class[i]->numstyles; j++) {
+        bindStyle(layer, shape, layer->class[i]->styles[j], drawmode);
       }
+    }
 
-      if(label->bindings[MS_LABEL_BINDING_SHADOWSIZEX].index != -1) { 
-        label->shadowsizex = 1; 
-        bindIntegerAttribute(&label->shadowsizex, shape->values[label->bindings[MS_LABEL_BINDING_SHADOWSIZEX].index]); 
-      } 
-      if(label->bindings[MS_LABEL_BINDING_SHADOWSIZEY].index != -1) { 
-        label->shadowsizey = 1; 
-        bindIntegerAttribute(&label->shadowsizey, shape->values[label->bindings[MS_LABEL_BINDING_SHADOWSIZEY].index]); 
-      } 
-
-      if(label->bindings[MS_LABEL_BINDING_POSITION].index != -1) {
-        int tmpPosition;
-        bindIntegerAttribute(&tmpPosition, shape->values[label->bindings[MS_LABEL_BINDING_POSITION].index]);
-        if(tmpPosition != 0) { /* is this test sufficient */
-          label->position = tmpPosition;
-        } else { /* Integer binding failed, look for strings like cc,ul,lr etc */
-          if(strlen(shape->values[label->bindings[MS_LABEL_BINDING_POSITION].index]) == 2) {
-            char *vp = shape->values[label->bindings[MS_LABEL_BINDING_POSITION].index];
-            if(!strncasecmp(vp,"ul",2))
-              label->position = MS_UL;     
-            else if(!strncasecmp(vp,"lr",2))
-              label->position = MS_LR;     
-            else if(!strncasecmp(vp,"ur",2))
-              label->position = MS_UR;     
-            else if(!strncasecmp(vp,"ll",2))
-              label->position = MS_LL;     
-            else if(!strncasecmp(vp,"cr",2))
-              label->position = MS_CR;     
-            else if(!strncasecmp(vp,"cl",2))
-              label->position = MS_CL;     
-	    else if(!strncasecmp(vp,"uc",2))
-              label->position = MS_UC;     
-            else if(!strncasecmp(vp,"lc",2))
-              label->position = MS_LC;     
-            else if(!strncasecmp(vp,"cc",2))
-              label->position = MS_CC;     
-          }       
-        }
+    /* check the labelObj's */
+    if(MS_DRAW_LABELS(drawmode)) {
+      for(j=0; j<layer->class[i]->numlabels; j++) {
+        bindLabel(layer, shape, layer->class[i]->labels[j], drawmode);
       }
     }
   } /* next classObj */
@@ -266,17 +305,18 @@ int msBindLayerToShape(layerObj *layer, shapeObj *shape, int querymapMode)
 /*
  * Used to get red, green, blue integers separately based upon the color index
  */
-int getRgbColor(mapObj *map,int i,int *r,int *g,int *b) {
-/* check index range */
-    int status=1;
-    *r=*g=*b=-1;
-    if ((i > 0 ) && (i <= map->palette.numcolors) ) {
-       *r=map->palette.colors[i-1].red;
-       *g=map->palette.colors[i-1].green;
-       *b=map->palette.colors[i-1].blue;
-       status=0;
-    }
-    return status;
+int getRgbColor(mapObj *map,int i,int *r,int *g,int *b)
+{
+  /* check index range */
+  int status=1;
+  *r=*g=*b=-1;
+  if ((i > 0 ) && (i <= map->palette.numcolors) ) {
+    *r=map->palette.colors[i-1].red;
+    *g=map->palette.colors[i-1].green;
+    *b=map->palette.colors[i-1].blue;
+    status=0;
+  }
+  return status;
 }
 
 static int searchContextForTag(mapObj *map, char **ltags, char *tag, char *context, int requires)
@@ -295,7 +335,7 @@ static int searchContextForTag(mapObj *map, char **ltags, char *tag, char *conte
       if(requires == MS_TRUE) {
         if(searchContextForTag(map, ltags, tag, GET_LAYER(map, i)->requires, MS_TRUE) == MS_SUCCESS) return MS_SUCCESS;
       } else {
-        if(searchContextForTag(map, ltags, tag, GET_LAYER(map, i)->labelrequires, MS_FALSE) == MS_SUCCESS) return MS_SUCCESS;      
+        if(searchContextForTag(map, ltags, tag, GET_LAYER(map, i)->labelrequires, MS_FALSE) == MS_SUCCESS) return MS_SUCCESS;
       }
     }
   }
@@ -304,11 +344,11 @@ static int searchContextForTag(mapObj *map, char **ltags, char *tag, char *conte
 }
 
 /*
-** Function to take a look at all layers with REQUIRES/LABELREQUIRES set to make sure there are no 
+** Function to take a look at all layers with REQUIRES/LABELREQUIRES set to make sure there are no
 ** recursive context requirements set (e.g. layer1 requires layer2 and layer2 requires layer1). This
 ** is bug 1059.
 */
-int msValidateContexts(mapObj *map) 
+int msValidateContexts(mapObj *map)
 {
   int i;
   char **ltags;
@@ -325,7 +365,7 @@ int msValidateContexts(mapObj *map)
   }
 
   /* check each layer's REQUIRES and LABELREQUIRES parameters */
-  for(i=0; i<map->numlayers; i++) { 
+  for(i=0; i<map->numlayers; i++) {
     /* printf("working on layer %s, looking for references to %s\n", GET_LAYER(map, i)->name, ltags[i]); */
     if(searchContextForTag(map, ltags, ltags[i], GET_LAYER(map, i)->requires, MS_TRUE) == MS_SUCCESS) {
       msSetError(MS_PARSEERR, "Recursion error found for REQUIRES parameter for layer %s.", "msValidateContexts", GET_LAYER(map, i)->name);
@@ -363,7 +403,7 @@ int msEvalContext(mapObj *map, layerObj *layer, char *context)
   e.type = MS_EXPRESSION; /* todo */
 
   for(i=0; i<map->numlayers; i++) { /* step through all the layers */
-    if(layer->index == i) continue; /* skip the layer in question */    
+    if(layer->index == i) continue; /* skip the layer in question */
     if (GET_LAYER(map, i)->name == NULL) continue; /* Layer without name cannot be used in contexts */
 
     tag = (char *)msSmallMalloc(sizeof(char)*strlen(GET_LAYER(map, i)->name) + 3);
@@ -411,23 +451,22 @@ int msEvalExpression(layerObj *layer, shapeObj *shape, expressionObj *expression
   if(!expression->string) return MS_TRUE; /* empty expressions are ALWAYS true */
 
   switch(expression->type) {
-  case(MS_STRING):
-    if(itemindex == -1) {
-      msSetError(MS_MISCERR, "Cannot evaluate expression, no item index defined.", "msEvalExpression()");
-      return MS_FALSE;
-    }
-    if(itemindex >= layer->numitems) {
-      msSetError(MS_MISCERR, "Invalid item index.", "msEvalExpression()");
-      return MS_FALSE;
-    }
-    if(expression->flags & MS_EXP_INSENSITIVE) {
-      if(strcasecmp(expression->string, shape->values[itemindex]) == 0) return MS_TRUE; /* got a match */
-    } else {
-      if(strcmp(expression->string, shape->values[itemindex]) == 0) return MS_TRUE; /* got a match */
-    }
-    break;
-  case(MS_EXPRESSION):
-    {
+    case(MS_STRING):
+      if(itemindex == -1) {
+        msSetError(MS_MISCERR, "Cannot evaluate expression, no item index defined.", "msEvalExpression()");
+        return MS_FALSE;
+      }
+      if(itemindex >= layer->numitems || itemindex >= shape->numvalues) {
+        msSetError(MS_MISCERR, "Invalid item index.", "msEvalExpression()");
+        return MS_FALSE;
+      }
+      if(expression->flags & MS_EXP_INSENSITIVE) {
+        if(strcasecmp(expression->string, shape->values[itemindex]) == 0) return MS_TRUE; /* got a match */
+      } else {
+        if(strcmp(expression->string, shape->values[itemindex]) == 0) return MS_TRUE; /* got a match */
+      }
+      break;
+    case(MS_EXPRESSION): {
       int status;
       parseObj p;
 
@@ -446,33 +485,33 @@ int msEvalExpression(layerObj *layer, shapeObj *shape, expressionObj *expression
       return p.result.intval;
       break;
     }
-  case(MS_REGEX):
-    if(itemindex == -1) {
-      msSetError(MS_MISCERR, "Cannot evaluate expression, no item index defined.", "msEvalExpression()");
-      return MS_FALSE;
-    }
-    if(itemindex >= layer->numitems) {
-      msSetError(MS_MISCERR, "Invalid item index.", "msEvalExpression()");
-      return MS_FALSE;
-    }
+    case(MS_REGEX):
+      if(itemindex == -1) {
+        msSetError(MS_MISCERR, "Cannot evaluate expression, no item index defined.", "msEvalExpression()");
+        return MS_FALSE;
+      }
+      if(itemindex >= layer->numitems || itemindex >= shape->numvalues) {
+        msSetError(MS_MISCERR, "Invalid item index.", "msEvalExpression()");
+        return MS_FALSE;
+      }
 
-    if(!expression->compiled) {
-      if(expression->flags & MS_EXP_INSENSITIVE) {
-        if(ms_regcomp(&(expression->regex), expression->string, MS_REG_EXTENDED|MS_REG_NOSUB|MS_REG_ICASE) != 0) { /* compile the expression */
-          msSetError(MS_REGEXERR, "Invalid regular expression.", "msEvalExpression()");
-          return MS_FALSE;
-        }
-      } else {
-        if(ms_regcomp(&(expression->regex), expression->string, MS_REG_EXTENDED|MS_REG_NOSUB) != 0) { /* compile the expression */
-          msSetError(MS_REGEXERR, "Invalid regular expression.", "msEvalExpression()");
-          return MS_FALSE;
+      if(!expression->compiled) {
+        if(expression->flags & MS_EXP_INSENSITIVE) {
+          if(ms_regcomp(&(expression->regex), expression->string, MS_REG_EXTENDED|MS_REG_NOSUB|MS_REG_ICASE) != 0) { /* compile the expression */
+            msSetError(MS_REGEXERR, "Invalid regular expression.", "msEvalExpression()");
+            return MS_FALSE;
+          }
+        } else {
+          if(ms_regcomp(&(expression->regex), expression->string, MS_REG_EXTENDED|MS_REG_NOSUB) != 0) { /* compile the expression */
+            msSetError(MS_REGEXERR, "Invalid regular expression.", "msEvalExpression()");
+            return MS_FALSE;
+          }
         }
+        expression->compiled = MS_TRUE;
       }
-      expression->compiled = MS_TRUE;
-    }
 
-    if(ms_regexec(&(expression->regex), shape->values[itemindex], 0, NULL, 0) == 0) return MS_TRUE; /* got a match */
-    break;
+      if(ms_regexec(&(expression->regex), shape->values[itemindex], 0, NULL, 0) == 0) return MS_TRUE; /* got a match */
+      break;
   }
 
   return MS_FALSE;
@@ -480,55 +519,37 @@ int msEvalExpression(layerObj *layer, shapeObj *shape, expressionObj *expression
 
 int *msAllocateValidClassGroups(layerObj *lp, int *nclasses)
 {
-    int *classgroup = NULL;
-    int nvalidclass = 0, i=0;
+  int *classgroup = NULL;
+  int nvalidclass = 0, i=0;
 
-    if (!lp || !lp->classgroup || lp->numclasses <=0 || !nclasses)
-      return NULL;
+  if (!lp || !lp->classgroup || lp->numclasses <=0 || !nclasses)
+    return NULL;
 
-    classgroup = (int *)msSmallMalloc(sizeof(int)*lp->numclasses);       
-    nvalidclass = 0;
-    for (i=0; i<lp->numclasses; i++)
-    {
-        if (lp->class[i]->group && strcasecmp(lp->class[i]->group, lp->classgroup) == 0)
-        {
-            classgroup[nvalidclass] = i;
-            nvalidclass++;
-        }
-    }
-    if (nvalidclass > 0)
-    {
-        classgroup = (int *)msSmallRealloc(classgroup, sizeof(int)*nvalidclass);
-        *nclasses = nvalidclass;
-        return classgroup;
+  classgroup = (int *)msSmallMalloc(sizeof(int)*lp->numclasses);
+  nvalidclass = 0;
+  for (i=0; i<lp->numclasses; i++) {
+    if (lp->class[i]->group && strcasecmp(lp->class[i]->group, lp->classgroup) == 0) {
+      classgroup[nvalidclass] = i;
+      nvalidclass++;
     }
+  }
+  if (nvalidclass > 0) {
+    classgroup = (int *)msSmallRealloc(classgroup, sizeof(int)*nvalidclass);
+    *nclasses = nvalidclass;
+    return classgroup;
+  }
 
-    if (classgroup)
-      msFree(classgroup);
-    
-    return NULL;
-        
-}       
+  if (classgroup)
+    msFree(classgroup);
+
+  return NULL;
+
+}
 
 int msShapeGetClass(layerObj *layer, mapObj *map, shapeObj *shape, int *classgroup, int numclasses)
 {
   int i, iclass;
 
-  /* INLINE features do not work with expressions, allow the classindex */
-  /* value set prior to calling this function to carry through. */
-  if(layer->connectiontype == MS_INLINE) {
-    if(shape->classindex < 0 || shape->classindex >= layer->numclasses) return(-1);
-
-    if(map->scaledenom > 0) {  /* verify scaledenom here */
-      if((layer->class[shape->classindex]->maxscaledenom > 0) && (map->scaledenom > layer->class[shape->classindex]->maxscaledenom))
-        return(-1); /* can skip this feature */
-      if((layer->class[shape->classindex]->minscaledenom > 0) && (map->scaledenom <= layer->class[shape->classindex]->minscaledenom))
-        return(-1); /* can skip this feature */
-    }
-
-    return(shape->classindex);
-  }
-
   if (layer->numclasses > 0) {
     if (classgroup == NULL || numclasses <=0)
       numclasses = layer->numclasses;
@@ -539,91 +560,143 @@ int msShapeGetClass(layerObj *layer, mapObj *map, shapeObj *shape, int *classgro
       else
         iclass = i;
 
-       if (iclass < 0 || iclass >= layer->numclasses)        
-         continue; /* this should never happen but just in case */
+      if (iclass < 0 || iclass >= layer->numclasses)
+        continue; /* this should never happen but just in case */
 
-       if(map->scaledenom > 0) { /* verify scaledenom here  */
-         if((layer->class[iclass]->maxscaledenom > 0) && (map->scaledenom > layer->class[iclass]->maxscaledenom))
-           continue; /* can skip this one, next class */
-         if((layer->class[iclass]->minscaledenom > 0) && (map->scaledenom <= layer->class[iclass]->minscaledenom))
-           continue; /* can skip this one, next class */
-        }
+      if(map->scaledenom > 0) { /* verify scaledenom here  */
+        if((layer->class[iclass]->maxscaledenom > 0) && (map->scaledenom > layer->class[iclass]->maxscaledenom))
+          continue; /* can skip this one, next class */
+        if((layer->class[iclass]->minscaledenom > 0) && (map->scaledenom <= layer->class[iclass]->minscaledenom))
+          continue; /* can skip this one, next class */
+      }
 
-       /* verify the minfeaturesize */
-       if ((shape->type == MS_SHAPE_LINE || shape->type == MS_SHAPE_POLYGON) && (layer->class[iclass]->minfeaturesize > 0))
-       {
-           double minfeaturesize = Pix2LayerGeoref(map, layer,
-                                                   layer->class[iclass]->minfeaturesize);
-           if (msShapeCheckSize(shape, minfeaturesize) == MS_FALSE)
-               continue; //skip this one, next class
-       }
-
-       if(layer->class[iclass]->status != MS_DELETE && msEvalExpression(layer, shape, &(layer->class[iclass]->expression), layer->classitemindex) == MS_TRUE)
-	 return(iclass);
+      /* verify the minfeaturesize */
+      if ((shape->type == MS_SHAPE_LINE || shape->type == MS_SHAPE_POLYGON) && (layer->class[iclass]->minfeaturesize > 0)) {
+        double minfeaturesize = Pix2LayerGeoref(map, layer,
+                                                layer->class[iclass]->minfeaturesize);
+        if (msShapeCheckSize(shape, minfeaturesize) == MS_FALSE)
+          continue; /* skip this one, next class */
+      }
+
+      if(layer->class[iclass]->status != MS_DELETE && msEvalExpression(layer, shape, &(layer->class[iclass]->expression), layer->classitemindex) == MS_TRUE)
+        return(iclass);
     }
   }
 
   return(-1); /* no match */
 }
 
-char *msShapeGetAnnotation(layerObj *layer, shapeObj *shape)
+static char *evalTextExpression(expressionObj *expr, shapeObj *shape)
 {
-  char *tmpstr=NULL;
-
-  if(layer->class[shape->classindex]->text.string) { /* test for global label first */
-    switch(layer->class[shape->classindex]->text.type) {
-    case(MS_STRING):
-      {
-        char *target=NULL;
-        tokenListNodeObjPtr node=NULL;
-        tokenListNodeObjPtr nextNode=NULL;
-
-        tmpstr = msStrdup(layer->class[shape->classindex]->text.string);
-
-        node = layer->class[shape->classindex]->text.tokens;
-        if(node) {
-          while(node != NULL) {
-            nextNode = node->next;
-            if(node->token == MS_TOKEN_BINDING_DOUBLE || node->token == MS_TOKEN_BINDING_INTEGER || node->token == MS_TOKEN_BINDING_STRING || node->token == MS_TOKEN_BINDING_TIME) {
-              target = (char *) msSmallMalloc(strlen(node->tokenval.bindval.item) + 3);
-              sprintf(target, "[%s]", node->tokenval.bindval.item);
-              tmpstr = msReplaceSubstring(tmpstr, target, shape->values[node->tokenval.bindval.index]);
-              msFree(target);
-	    }
-            node = nextNode;
+  char *result=NULL;
+
+  if(!expr->string) return result; /* nothing to do */
+
+  switch(expr->type) {
+    case(MS_STRING): {
+      char *target=NULL;
+      tokenListNodeObjPtr node=NULL;
+      tokenListNodeObjPtr nextNode=NULL;
+
+      result = msStrdup(expr->string);
+
+      node = expr->tokens;
+      if(node) {
+        while(node != NULL) {
+          nextNode = node->next;
+          if(node->token == MS_TOKEN_BINDING_DOUBLE || node->token == MS_TOKEN_BINDING_INTEGER || node->token == MS_TOKEN_BINDING_STRING || node->token == MS_TOKEN_BINDING_TIME) {
+            target = (char *) msSmallMalloc(strlen(node->tokenval.bindval.item) + 3);
+            sprintf(target, "[%s]", node->tokenval.bindval.item);
+            result = msReplaceSubstring(result, target, shape->values[node->tokenval.bindval.index]);
+            msFree(target);
           }
+          node = nextNode;
         }
       }
-      break;
-    case(MS_EXPRESSION):
-      {
-        int status;
-        parseObj p;
-
-        p.shape = shape;
-        p.expr = &(layer->class[shape->classindex]->text);
-        p.expr->curtoken = p.expr->tokens; /* reset */
-        p.type = MS_PARSE_TYPE_STRING;
+      if(!strlen(result)) {
+        msFree(result);
+        result = NULL;
+      }
+    }
+    break;
+    case(MS_EXPRESSION): {
+      int status;
+      parseObj p;
 
-        status = yyparse(&p);
+      p.shape = shape;
+      p.expr = expr;
+      p.expr->curtoken = p.expr->tokens; /* reset */
+      p.type = MS_PARSE_TYPE_STRING;
 
-        if (status != 0) {
-	  msSetError(MS_PARSEERR, "Failed to process text expression: %s", "msShapeGetAnnotation", layer->class[shape->classindex]->text.string);
-	  return NULL;
-        }
+      status = yyparse(&p);
 
-        tmpstr = p.result.strval;        
-        break;
+      if (status != 0) {
+        msSetError(MS_PARSEERR, "Failed to process text expression: %s", "evalTextExpression", expr->string);
+        return NULL;
       }
+
+      result = p.result.strval;
+      break;
+    }
     default:
       break;
+  }
+  if(result && !strlen(result)) {
+    msFree(result);
+    result = NULL;
+  }
+  return result;
+}
+
+int msShapeGetAnnotation(layerObj *layer, shapeObj *shape)
+{
+  int i, j;
+
+  /* RFC77 TODO: check and throw some errors here... */
+  if(!layer || !shape) return MS_FAILURE;
+
+  i = shape->classindex;
+  for(j=0; j<layer->class[i]->numlabels; j++) {
+    labelObj *lbl = layer->class[i]->labels[j]; /* shortcut */
+
+    lbl->status = MS_ON;
+    if(layer->map->scaledenom > 0) {
+      if((lbl->maxscaledenom != -1) && (layer->map->scaledenom >= lbl->maxscaledenom)) {
+        lbl->status = MS_OFF;
+        continue; /* next label */
+      }
+      if((lbl->minscaledenom != -1) && (layer->map->scaledenom < lbl->minscaledenom)) {
+        lbl->status = MS_OFF;
+        continue; /* next label */
+      }
+    }
+    if(msEvalExpression(layer, shape, &(lbl->expression), -1) != MS_TRUE) {
+      lbl->status = MS_OFF;
+      continue; /* next label */
+    }
+
+    msFree(lbl->annotext);
+    lbl->annotext = NULL;
+
+    if(lbl->text.string) {
+      lbl->annotext = evalTextExpression(&(lbl->text), shape);
+    } else if(layer->class[i]->text.string) {
+      lbl->annotext = evalTextExpression(&(layer->class[i]->text), shape);
+    } else {
+      if (shape->values && layer->labelitemindex >= 0 && shape->values[layer->labelitemindex] && strlen(shape->values[layer->labelitemindex]) )
+        lbl->annotext = msStrdup(shape->values[layer->labelitemindex]);
+      else if(shape->text)
+        lbl->annotext = msStrdup(shape->text); /* last resort but common with iniline features */
+    }
+
+    if(lbl->annotext && (lbl->encoding || lbl->wrap || lbl->maxlength)) {
+      char *newtext = msTransformLabelText(layer->map , lbl, lbl->annotext);
+      free(lbl->annotext);
+      lbl->annotext = newtext;
     }
-  } else {
-    if (shape->values && layer->labelitemindex >= 0)
-      tmpstr = msStrdup(shape->values[layer->labelitemindex]);
   }
 
-  return(tmpstr);
+  return MS_SUCCESS;
 }
 
 /* Check if the shape is enough big to be drawn with the
@@ -633,13 +706,13 @@ char *msShapeGetAnnotation(layerObj *layer, shapeObj *shape)
  */
 int msShapeCheckSize(shapeObj *shape, double minfeaturesize)
 {
-    double dx = (shape->bounds.maxx-shape->bounds.minx);
-    double dy = (shape->bounds.maxy-shape->bounds.miny);
+  double dx = (shape->bounds.maxx-shape->bounds.minx);
+  double dy = (shape->bounds.maxy-shape->bounds.miny);
 
-    if (pow(minfeaturesize,2.0) > (pow(dx,2.0)+pow(dy,2.0)))
-        return MS_FALSE;
-    
-    return MS_TRUE;
+  if (pow(minfeaturesize,2.0) > (pow(dx,2.0)+pow(dy,2.0)))
+    return MS_FALSE;
+
+  return MS_TRUE;
 }
 
 /*
@@ -684,11 +757,11 @@ double msAdjustExtent(rectObj *rect, int width, int height)
 }
 
 /*
-** Rect must always contain a portion of bounds. If not, rect is 
+** Rect must always contain a portion of bounds. If not, rect is
 ** shifted to overlap by overlay percent. The dimensions of rect do
 ** not change but placement relative to bounds can.
 */
-int msConstrainExtent(rectObj *bounds, rectObj *rect, double overlay) 
+int msConstrainExtent(rectObj *bounds, rectObj *rect, double overlay)
 {
   double offset=0;
 
@@ -723,123 +796,120 @@ int msConstrainExtent(rectObj *bounds, rectObj *rect, double overlay)
 ** Note that map may be NULL. If it is set, then it is used for two things:
 ** - Deal with relative imagepaths (compute absolute path relative to map path)
 ** - Extract the georeferenced extents and coordinate system
-**   of the map for writing out with the image when appropriate 
-**   (primarily this means via msSaveImageGDAL() to something like GeoTIFF). 
+**   of the map for writing out with the image when appropriate
+**   (primarily this means via msSaveImageGDAL() to something like GeoTIFF).
 **
-** The filename is NULL when the image is supposed to be written to stdout. 
+** The filename is NULL when the image is supposed to be written to stdout.
 */
 
 int msSaveImage(mapObj *map, imageObj *img, char *filename)
 {
-    int nReturnVal = MS_FAILURE;
-    char szPath[MS_MAXPATHLEN];
-    struct mstimeval starttime, endtime;
+  int nReturnVal = MS_FAILURE;
+  char szPath[MS_MAXPATHLEN];
+  struct mstimeval starttime, endtime;
 
-    if(map && map->debug >= MS_DEBUGLEVEL_TUNING) {
-        msGettimeofday(&starttime, NULL);
-    }
+  if(map && map->debug >= MS_DEBUGLEVEL_TUNING) {
+    msGettimeofday(&starttime, NULL);
+  }
 
-    if (img)
-    {
+  if (img) {
 #ifdef USE_GDAL
-        if( MS_DRIVER_GDAL(img->format) )
-        {
-           if (map != NULL && filename != NULL )
-             nReturnVal = msSaveImageGDAL(map, img,
-                                          msBuildPath(szPath, map->mappath, 
-                                                      filename));
-           else
-             nReturnVal = msSaveImageGDAL(map, img, filename);
-        } else
+    if( MS_DRIVER_GDAL(img->format) ) {
+      if (map != NULL && filename != NULL )
+        nReturnVal = msSaveImageGDAL(map, img,
+                                     msBuildPath(szPath, map->mappath,
+                                         filename));
+      else
+        nReturnVal = msSaveImageGDAL(map, img, filename);
+    } else
 #endif
-       if (MS_RENDERER_PLUGIN(img->format)) {
-            rendererVTableObj *renderer = img->format->vtable;
-            FILE *stream = NULL;
-            if(filename) {
-               if(map)
-                  stream = fopen(msBuildPath(szPath, map->mappath, filename),"wb");
-               else
-                  stream = fopen(filename,"wb");
-
-               if(!stream) {
-                  msSetError(MS_IOERR, 
-                             "Failed to create output file (%s).", 
-                             "msSaveImage()", (map?szPath:filename) );
-                  return MS_FAILURE;
-               }
- 
-            } else {
-                if ( msIO_needBinaryStdout() == MS_FAILURE )
-                    return MS_FAILURE;
-                stream = stdout;
-            }
+      if (MS_RENDERER_PLUGIN(img->format)) {
+        rendererVTableObj *renderer = img->format->vtable;
+        FILE *stream = NULL;
+        if(filename) {
+          if(map)
+            stream = fopen(msBuildPath(szPath, map->mappath, filename),"wb");
+          else
+            stream = fopen(filename,"wb");
+
+          if(!stream) {
+            msSetError(MS_IOERR,
+                       "Failed to create output file (%s).",
+                       "msSaveImage()", (map?szPath:filename) );
+            return MS_FAILURE;
+          }
 
-           if(renderer->supports_pixel_buffer) {
-                rasterBufferObj data;
-                if(renderer->getRasterBufferHandle(img,&data) != MS_SUCCESS)
-                   return MS_FAILURE;
+        } else {
+          if ( msIO_needBinaryStdout() == MS_FAILURE )
+            return MS_FAILURE;
+          stream = stdout;
+        }
 
-                nReturnVal = msSaveRasterBuffer(map,&data,stream,img->format );
-            } else {
-                nReturnVal = renderer->saveImage(img, stream, img->format);
-            }
-            if( stream != stdout )
-                fclose(stream);
+        if(renderer->supports_pixel_buffer) {
+          rasterBufferObj data;
+          if(renderer->getRasterBufferHandle(img,&data) != MS_SUCCESS)
+            return MS_FAILURE;
 
+          nReturnVal = msSaveRasterBuffer(map,&data,stream,img->format );
+        } else {
+          nReturnVal = renderer->saveImage(img, map, stream, img->format);
         }
-        else if( MS_DRIVER_IMAGEMAP(img->format) )
-            nReturnVal = msSaveImageIM(img, filename, img->format);
-        else
-            msSetError(MS_MISCERR, "Unknown image type", 
-                       "msSaveImage()"); 
-    }
+        if( stream != stdout )
+          fclose(stream);
 
-    if(map && map->debug >= MS_DEBUGLEVEL_TUNING) {
-      msGettimeofday(&endtime, NULL);
-      msDebug("msSaveImage(%s) total time: %.3fs\n", 
-              (filename ? filename : "stdout"), 
-              (endtime.tv_sec+endtime.tv_usec/1.0e6)-
-              (starttime.tv_sec+starttime.tv_usec/1.0e6) );
-    }
+      } else if( MS_DRIVER_IMAGEMAP(img->format) )
+        nReturnVal = msSaveImageIM(img, filename, img->format);
+      else
+        msSetError(MS_MISCERR, "Unknown image type",
+                   "msSaveImage()");
+  }
 
-    return nReturnVal;
+  if(map && map->debug >= MS_DEBUGLEVEL_TUNING) {
+    msGettimeofday(&endtime, NULL);
+    msDebug("msSaveImage(%s) total time: %.3fs\n",
+            (filename ? filename : "stdout"),
+            (endtime.tv_sec+endtime.tv_usec/1.0e6)-
+            (starttime.tv_sec+starttime.tv_usec/1.0e6) );
+  }
+
+  return nReturnVal;
 }
 
 /*
 ** Generic function to save an image to a byte array.
-** - the return value is the pointer to the byte array 
+** - the return value is the pointer to the byte array
 ** - size_ptr contains the number of bytes returned
 ** - format: the desired output format
 **
 ** The caller is responsible to free the returned array
-** The function returns NULL if the output format is not supported. 
+** The function returns NULL if the output format is not supported.
 */
 
 unsigned char *msSaveImageBuffer(imageObj* image, int *size_ptr, outputFormatObj *format)
 {
-    *size_ptr = 0;
-    if( MS_RENDERER_PLUGIN(image->format)){
-        rasterBufferObj data;
-        rendererVTableObj *renderer = image->format->vtable;
-        if(renderer->supports_pixel_buffer) {
-            bufferObj buffer;
-            msBufferInit(&buffer);
-            renderer->getRasterBufferHandle(image,&data);
-            msSaveRasterBufferToBuffer(&data,&buffer,format);
-            *size_ptr = buffer.size;
-            return buffer.data;
-            //don't free the bufferObj as we don't own the bytes anymore
-        } else {
-            /* check if the renderer supports native buffer output */
-            if (renderer->saveImageBuffer)
-                return renderer->saveImageBuffer(image, size_ptr, format);
+  *size_ptr = 0;
+  if( MS_RENDERER_PLUGIN(image->format)) {
+    rasterBufferObj data;
+    rendererVTableObj *renderer = image->format->vtable;
+    if(renderer->supports_pixel_buffer) {
+      bufferObj buffer;
+      msBufferInit(&buffer);
+      renderer->getRasterBufferHandle(image,&data);
+      msSaveRasterBufferToBuffer(&data,&buffer,format);
+      *size_ptr = buffer.size;
+      return buffer.data;
+      /* don't free the bufferObj as we don't own the bytes anymore */
+    } else {
+      /* check if the renderer supports native buffer output */
+      if (renderer->saveImageBuffer)
+        return renderer->saveImageBuffer(image, size_ptr, format);
 
-	        msSetError(MS_MISCERR, "Unsupported image type", "msSaveImageBuffer()");
-            return NULL;
-        }
+      msSetError(MS_MISCERR, "Unsupported image type", "msSaveImageBuffer()");
+      return NULL;
     }
-	msSetError(MS_MISCERR, "Unsupported image type", "msSaveImage()");
-    return NULL;
+  }
+  msSetError(MS_MISCERR, "Unsupported image type", "msSaveImage()");
+  return NULL;
 }
 
 /**
@@ -847,43 +917,42 @@ unsigned char *msSaveImageBuffer(imageObj* image, int *size_ptr, outputFormatObj
  */
 void msFreeImage(imageObj *image)
 {
-    if (image)
-    {
-       if(MS_RENDERER_PLUGIN(image->format)) {
-          rendererVTableObj *renderer = image->format->vtable;
-          tileCacheObj *next,*cur = image->tilecache;
-          while(cur) {
-             msFreeImage(cur->image);
-             next = cur->next;
-             free(cur);
-             cur = next;
-          }
-          image->ntiles = 0;
-          renderer->freeImage(image);
-        } else if( MS_RENDERER_IMAGEMAP(image->format) )
-            msFreeImageIM(image);
-        else if( MS_RENDERER_RAWDATA(image->format) )
-            msFree(image->img.raw_16bit);
-        else
-            msSetError(MS_MISCERR, "Unknown image type", 
-                       "msFreeImage()"); 
-
-        if (image->imagepath)
-            free(image->imagepath);
-        if (image->imageurl)
-            free(image->imageurl);
-
-        if( --image->format->refcount < 1 )
-            msFreeOutputFormat( image->format );
-
-        image->imagepath = NULL;
-        image->imageurl = NULL;
-
-        msFree( image->img_mask );
-        image->img_mask= NULL;
-
-        msFree( image );
-    }     
+  if (image) {
+    if(MS_RENDERER_PLUGIN(image->format)) {
+      rendererVTableObj *renderer = image->format->vtable;
+      tileCacheObj *next,*cur = image->tilecache;
+      while(cur) {
+        msFreeImage(cur->image);
+        next = cur->next;
+        free(cur);
+        cur = next;
+      }
+      image->ntiles = 0;
+      renderer->freeImage(image);
+    } else if( MS_RENDERER_IMAGEMAP(image->format) )
+      msFreeImageIM(image);
+    else if( MS_RENDERER_RAWDATA(image->format) )
+      msFree(image->img.raw_16bit);
+    else
+      msSetError(MS_MISCERR, "Unknown image type",
+                 "msFreeImage()");
+
+    if (image->imagepath)
+      free(image->imagepath);
+    if (image->imageurl)
+      free(image->imageurl);
+
+    if( --image->format->refcount < 1 )
+      msFreeOutputFormat( image->format );
+
+    image->imagepath = NULL;
+    image->imageurl = NULL;
+
+    msFree( image->img_mask );
+    image->img_mask= NULL;
+
+    msFree( image );
+  }
 }
 
 /*
@@ -894,39 +963,33 @@ void msFreeImage(imageObj *image)
 */
 int *msGetLayersIndexByGroup(mapObj *map, char *groupname, int *pnCount)
 {
-    int         i;
-    int         iLayer = 0;
-    int         *aiIndex;
+  int         i;
+  int         iLayer = 0;
+  int         *aiIndex;
 
-    if(!groupname || !map || !pnCount)
-    {
-        return NULL;
-    }
+  if(!groupname || !map || !pnCount) {
+    return NULL;
+  }
 
-    aiIndex = (int *)msSmallMalloc(sizeof(int) * map->numlayers);
+  aiIndex = (int *)msSmallMalloc(sizeof(int) * map->numlayers);
 
-    for(i=0;i<map->numlayers; i++)
-    {
-        if(!GET_LAYER(map, i)->group) /* skip it */
-            continue;
-        if(strcmp(groupname, GET_LAYER(map, i)->group) == 0)
-        {
-            aiIndex[iLayer] = i;
-            iLayer++;
-        }
+  for(i=0; i<map->numlayers; i++) {
+    if(!GET_LAYER(map, i)->group) /* skip it */
+      continue;
+    if(strcmp(groupname, GET_LAYER(map, i)->group) == 0) {
+      aiIndex[iLayer] = i;
+      iLayer++;
     }
+  }
 
-    if (iLayer == 0)
-    {
-        free(aiIndex);
-        aiIndex = NULL;
-        *pnCount = 0;
-    }
-    else
-    {
-        aiIndex = (int *)msSmallRealloc(aiIndex, sizeof(int)* iLayer);
-        *pnCount = iLayer;
-    }
+  if (iLayer == 0) {
+    free(aiIndex);
+    aiIndex = NULL;
+    *pnCount = 0;
+  } else {
+    aiIndex = (int *)msSmallRealloc(aiIndex, sizeof(int)* iLayer);
+    *pnCount = iLayer;
+  }
 
   return aiIndex;
 }
@@ -946,99 +1009,91 @@ int *msGetLayersIndexByGroup(mapObj *map, char *groupname, int *pnCount)
 pointObj *msGetPointUsingMeasure(shapeObj *shape, double m)
 {
 #ifdef USE_POINT_Z_M
-    pointObj    *point = NULL;
-    lineObj     line;
-    double      dfMin = 0;
-    double      dfMax = 0;
-    int         i,j = 0;
-    int         bFound = 0;
-    double      dfFirstPointX = 0;
-    double      dfFirstPointY = 0;
-    double      dfFirstPointM = 0;
-    double      dfSecondPointX = 0;
-    double      dfSecondPointY = 0;
-    double      dfSecondPointM = 0;
-    double      dfCurrentM = 0;
-    double      dfFactor = 0;
-
-    if (shape &&  shape->numlines > 0)
-    {
-/* -------------------------------------------------------------------- */
-/*      check fir the first value (min) and the last value(max) to      */
-/*      see if the m is contained between these min and max.            */
-/* -------------------------------------------------------------------- */
-        line = shape->line[0];
-        dfMin = line.point[0].m;
-        line = shape->line[shape->numlines-1];
-        dfMax = line.point[line.numpoints-1].m;
-
-        if (m >= dfMin && m <= dfMax)
-        {
-            for (i=0; i<shape->numlines; i++)
-            {
-                line = shape->line[i];
-                
-                for (j=0; j<line.numpoints; j++)
-                {
-                    dfCurrentM = line.point[j].m;
-                    if (dfCurrentM > m)
-                    {
-                        bFound = 1;
-                        
-                        dfSecondPointX = line.point[j].x;
-                        dfSecondPointY = line.point[j].y;
-                        dfSecondPointM = line.point[j].m;
-                        
-/* -------------------------------------------------------------------- */
-/*      get the previous node xy values.                                */
-/* -------------------------------------------------------------------- */
-                        if (j > 0) /* not the first point of the line */
-                        {
-                            dfFirstPointX = line.point[j-1].x;
-                            dfFirstPointY = line.point[j-1].y;
-                            dfFirstPointM = line.point[j-1].m;
-                        }
-                        else /* get last point of previous line */
-                        {
-                            dfFirstPointX = shape->line[i-1].point[0].x;
-                            dfFirstPointY = shape->line[i-1].point[0].y;
-                            dfFirstPointM = shape->line[i-1].point[0].m;
-                        }
-                        break;
-                    }
-                }
+  pointObj    *point = NULL;
+  lineObj     line;
+  double      dfMin = 0;
+  double      dfMax = 0;
+  int         i,j = 0;
+  int         bFound = 0;
+  double      dfFirstPointX = 0;
+  double      dfFirstPointY = 0;
+  double      dfFirstPointM = 0;
+  double      dfSecondPointX = 0;
+  double      dfSecondPointY = 0;
+  double      dfSecondPointM = 0;
+  double      dfCurrentM = 0;
+  double      dfFactor = 0;
+
+  if (shape &&  shape->numlines > 0) {
+    /* -------------------------------------------------------------------- */
+    /*      check fir the first value (min) and the last value(max) to      */
+    /*      see if the m is contained between these min and max.            */
+    /* -------------------------------------------------------------------- */
+    line = shape->line[0];
+    dfMin = line.point[0].m;
+    line = shape->line[shape->numlines-1];
+    dfMax = line.point[line.numpoints-1].m;
+
+    if (m >= dfMin && m <= dfMax) {
+      for (i=0; i<shape->numlines; i++) {
+        line = shape->line[i];
+
+        for (j=0; j<line.numpoints; j++) {
+          dfCurrentM = line.point[j].m;
+          if (dfCurrentM > m) {
+            bFound = 1;
+
+            dfSecondPointX = line.point[j].x;
+            dfSecondPointY = line.point[j].y;
+            dfSecondPointM = line.point[j].m;
+
+            /* -------------------------------------------------------------------- */
+            /*      get the previous node xy values.                                */
+            /* -------------------------------------------------------------------- */
+            if (j > 0) { /* not the first point of the line */
+              dfFirstPointX = line.point[j-1].x;
+              dfFirstPointY = line.point[j-1].y;
+              dfFirstPointM = line.point[j-1].m;
+            } else { /* get last point of previous line */
+              dfFirstPointX = shape->line[i-1].point[0].x;
+              dfFirstPointY = shape->line[i-1].point[0].y;
+              dfFirstPointM = shape->line[i-1].point[0].m;
             }
+            break;
+          }
         }
-
-        if (!bFound) 
-          return NULL;
-
-/* -------------------------------------------------------------------- */
-/*      extrapolate the m value to get t he xy coordinate.              */
-/* -------------------------------------------------------------------- */
-
-        if (dfFirstPointM != dfSecondPointM) 
-          dfFactor = (m-dfFirstPointM)/(dfSecondPointM - dfFirstPointM); 
-        else
-          dfFactor = 0;
-
-        point = (pointObj *)msSmallMalloc(sizeof(pointObj));
-        
-        point->x = dfFirstPointX + (dfFactor * (dfSecondPointX - dfFirstPointX));
-        point->y = dfFirstPointY + 
-            (dfFactor * (dfSecondPointY - dfFirstPointY));
-        point->m = dfFirstPointM + 
-            (dfFactor * (dfSecondPointM - dfFirstPointM));
-        
-        return point;
+      }
     }
 
-    return NULL;
+    if (!bFound)
+      return NULL;
+
+    /* -------------------------------------------------------------------- */
+    /*      extrapolate the m value to get t he xy coordinate.              */
+    /* -------------------------------------------------------------------- */
+
+    if (dfFirstPointM != dfSecondPointM)
+      dfFactor = (m-dfFirstPointM)/(dfSecondPointM - dfFirstPointM);
+    else
+      dfFactor = 0;
+
+    point = (pointObj *)msSmallMalloc(sizeof(pointObj));
+
+    point->x = dfFirstPointX + (dfFactor * (dfSecondPointX - dfFirstPointX));
+    point->y = dfFirstPointY +
+               (dfFactor * (dfSecondPointY - dfFirstPointY));
+    point->m = dfFirstPointM +
+               (dfFactor * (dfSecondPointM - dfFirstPointM));
+
+    return point;
+  }
+
+  return NULL;
 #else
-    msSetError(MS_MISCERR, 
-               "The \"m\" parameter for points is unavailable in your build.",
-               "msGetPointUsingMeasure()");
-    return NULL;
+  msSetError(MS_MISCERR,
+             "The \"m\" parameter for points is unavailable in your build.",
+             "msGetPointUsingMeasure()");
+  return NULL;
 #endif /* USE_POINT_Z_M */
 }
 
@@ -1118,51 +1173,45 @@ pointObj *msGetPointUsingMeasure(shapeObj *shape, double m)
 /************************************************************************/
 pointObj *msIntersectionPointLine(pointObj *p, pointObj *a, pointObj *b)
 {
-    double r = 0;
-    double L = 0;
-    pointObj *result = NULL;
-
-    if (p && a && b)
-    {
-        L = sqrt(((b->x - a->x)*(b->x - a->x)) + 
-                 ((b->y - a->y)*(b->y - a->y)));
-
-        if (L != 0)
-          r = ((p->x - a->x)*(b->x - a->x) + (p->y - a->y)*(b->y - a->y))/(L*L);
-        else
-          r = 0;
-
-        result = (pointObj *)msSmallMalloc(sizeof(pointObj));
-/* -------------------------------------------------------------------- */
-/*      We want to make sure that the point returned is on the line     */
-/*                                                                      */
-/*              r=0      P = A                                          */
-/*              r=1      P = B                                          */
-/*              r<0      P is on the backward extension of AB           */
-/*              r>1      P is on the forward extension of AB            */
-/*                    0<r<1    P is interior to AB                      */
-/* -------------------------------------------------------------------- */
-        if (r < 0)
-        {
-            result->x = a->x;
-            result->y = a->y;
-        }
-        else if (r > 1)
-        {
-            result->x = b->x;
-            result->y = b->y;
-        }
-        else
-        {
-            result->x = a->x + r*(b->x - a->x);
-            result->y = a->y + r*(b->y - a->y);
-        }
+  double r = 0;
+  double L = 0;
+  pointObj *result = NULL;
+
+  if (p && a && b) {
+    L = sqrt(((b->x - a->x)*(b->x - a->x)) +
+             ((b->y - a->y)*(b->y - a->y)));
+
+    if (L != 0)
+      r = ((p->x - a->x)*(b->x - a->x) + (p->y - a->y)*(b->y - a->y))/(L*L);
+    else
+      r = 0;
+
+    result = (pointObj *)msSmallMalloc(sizeof(pointObj));
+    /* -------------------------------------------------------------------- */
+    /*      We want to make sure that the point returned is on the line     */
+    /*                                                                      */
+    /*              r=0      P = A                                          */
+    /*              r=1      P = B                                          */
+    /*              r<0      P is on the backward extension of AB           */
+    /*              r>1      P is on the forward extension of AB            */
+    /*                    0<r<1    P is interior to AB                      */
+    /* -------------------------------------------------------------------- */
+    if (r < 0) {
+      result->x = a->x;
+      result->y = a->y;
+    } else if (r > 1) {
+      result->x = b->x;
+      result->y = b->y;
+    } else {
+      result->x = a->x + r*(b->x - a->x);
+      result->y = a->y + r*(b->y - a->y);
+    }
 #ifdef USE_POINT_Z_M
-        result->m = 0;
+    result->m = 0;
 #endif
-    }
+  }
 
-    return result;
+  return result;
 }
 
 
@@ -1174,75 +1223,72 @@ pointObj *msIntersectionPointLine(pointObj *p, pointObj *a, pointObj *b)
 /*      shape and return the Measured value at the intersection.        */
 /************************************************************************/
 pointObj *msGetMeasureUsingPoint(shapeObj *shape, pointObj *point)
-{       
-    double      dfMinDist = 1e35;
-    double      dfDist = 0;
-    pointObj    oFirst;
-    pointObj    oSecond;
-    int         i, j = 0;
-    lineObj     line;
-    pointObj    *poIntersectionPt = NULL;
-    double      dfFactor = 0;
-    double      dfDistTotal, dfDistToIntersection = 0;
-
-    if (shape && point)
-    {
-        for (i=0; i<shape->numlines; i++)
-        {
-            line = shape->line[i];
-/* -------------------------------------------------------------------- */
-/*      for each line (2 consecutive lines) get the distance between    */
-/*      the line and the point and determine which line segment is      */
-/*      the closeset to the point.                                      */
-/* -------------------------------------------------------------------- */
-            for (j=0; j<line.numpoints-1; j++)
-            {
-                dfDist = msDistancePointToSegment(point, &line.point[j], &line.point[j+1]);
-                if (dfDist < dfMinDist)
-                {
-                    oFirst.x = line.point[j].x;
-                    oFirst.y = line.point[j].y;
+{
+  double      dfMinDist = 1e35;
+  double      dfDist = 0;
+  pointObj    oFirst;
+  pointObj    oSecond;
+  int         i, j = 0;
+  lineObj     line;
+  pointObj    *poIntersectionPt = NULL;
 #ifdef USE_POINT_Z_M
-                    oFirst.m = line.point[j].m;
+  double      dfFactor = 0;
+  double      dfDistTotal, dfDistToIntersection = 0;
 #endif
-                    
-                    oSecond.x =  line.point[j+1].x;
-                    oSecond.y =  line.point[j+1].y;
+
+  if (shape && point) {
+    for (i=0; i<shape->numlines; i++) {
+      line = shape->line[i];
+      /* -------------------------------------------------------------------- */
+      /*      for each line (2 consecutive lines) get the distance between    */
+      /*      the line and the point and determine which line segment is      */
+      /*      the closeset to the point.                                      */
+      /* -------------------------------------------------------------------- */
+      for (j=0; j<line.numpoints-1; j++) {
+        dfDist = msDistancePointToSegment(point, &line.point[j], &line.point[j+1]);
+        if (dfDist < dfMinDist) {
+          oFirst.x = line.point[j].x;
+          oFirst.y = line.point[j].y;
 #ifdef USE_POINT_Z_M
-                    oSecond.m =  line.point[j+1].m;
+          oFirst.m = line.point[j].m;
 #endif
 
-                    dfMinDist = dfDist;
-                }
-            }
-        }
-/* -------------------------------------------------------------------- */
-/*      once we have the nearest segment, look for the x,y location     */
-/*      which is the nearest intersection between the line and the      */
-/*      point.                                                          */
-/* -------------------------------------------------------------------- */
-        poIntersectionPt = msIntersectionPointLine(point, &oFirst, &oSecond);
-        if (poIntersectionPt)
-        {
-            dfDistTotal = sqrt(((oSecond.x - oFirst.x)*(oSecond.x - oFirst.x)) + 
-                               ((oSecond.y - oFirst.y)*(oSecond.y - oFirst.y)));
-
-            dfDistToIntersection = sqrt(((poIntersectionPt->x - oFirst.x)*
-                                         (poIntersectionPt->x - oFirst.x)) + 
-                                        ((poIntersectionPt->y - oFirst.y)*
-                                         (poIntersectionPt->y - oFirst.y)));
-
-            dfFactor = dfDistToIntersection / dfDistTotal;
-
+          oSecond.x =  line.point[j+1].x;
+          oSecond.y =  line.point[j+1].y;
 #ifdef USE_POINT_Z_M
-            poIntersectionPt->m = oFirst.m + (oSecond.m - oFirst.m)*dfFactor;
+          oSecond.m =  line.point[j+1].m;
 #endif
 
-            return poIntersectionPt;
+          dfMinDist = dfDist;
         }
-    
+      }
     }
-    return NULL;
+    /* -------------------------------------------------------------------- */
+    /*      once we have the nearest segment, look for the x,y location     */
+    /*      which is the nearest intersection between the line and the      */
+    /*      point.                                                          */
+    /* -------------------------------------------------------------------- */
+    poIntersectionPt = msIntersectionPointLine(point, &oFirst, &oSecond);
+    if (poIntersectionPt) {
+#ifdef USE_POINT_Z_M
+      dfDistTotal = sqrt(((oSecond.x - oFirst.x)*(oSecond.x - oFirst.x)) +
+                         ((oSecond.y - oFirst.y)*(oSecond.y - oFirst.y)));
+
+      dfDistToIntersection = sqrt(((poIntersectionPt->x - oFirst.x)*
+                                   (poIntersectionPt->x - oFirst.x)) +
+                                  ((poIntersectionPt->y - oFirst.y)*
+                                   (poIntersectionPt->y - oFirst.y)));
+
+      dfFactor = dfDistToIntersection / dfDistTotal;
+
+      poIntersectionPt->m = oFirst.m + (oSecond.m - oFirst.m)*dfFactor;
+#endif
+
+      return poIntersectionPt;
+    }
+
+  }
+  return NULL;
 }
 
 /* ==================================================================== */
@@ -1252,61 +1298,54 @@ pointObj *msGetMeasureUsingPoint(shapeObj *shape, pointObj *point)
 
 char **msGetAllGroupNames(mapObj *map, int *numTok)
 {
-    char        **papszGroups = NULL;
-    int         bFound = 0;
-    int         nCount = 0;
-    int         i = 0, j = 0;
-
-    *numTok = 0;
-   
-    if (!map->layerorder)
-    {
-       map->layerorder = (int*)msSmallMalloc(map->numlayers * sizeof(int));
-
-       /*
-        * Initiate to default order
-        */
-       for (i=0; i<map->numlayers; i++)
-         map->layerorder[i] = i;   
-    }
-   
-    if (map != NULL && map->numlayers > 0)
-    {
-        nCount = map->numlayers;
-        papszGroups = (char **)msSmallMalloc(sizeof(char *)*nCount);
-
-        for (i=0; i<nCount; i++)
-            papszGroups[i] = NULL;
-       
-        for (i=0; i<nCount; i++)
-        {
-            layerObj *lp;
-            lp = (GET_LAYER(map, map->layerorder[i]));
-
-            bFound = 0;
-            if (lp->group && lp->status != MS_DELETE)
-            {
-                for (j=0; j<*numTok; j++)
-                {
-                    if (papszGroups[j] &&
-                        strcmp(lp->group, papszGroups[j]) == 0)
-                    {
-                        bFound = 1;
-                        break;
-                    }
-                }
-                if (!bFound)
-                {
-                    /* New group... add to the list of groups found */
-                    papszGroups[(*numTok)] = msStrdup(lp->group);
-                    (*numTok)++;
-                }
-            }
-        }
+  char        **papszGroups = NULL;
+  int         bFound = 0;
+  int         nCount = 0;
+  int         i = 0, j = 0;
+
+  *numTok = 0;
+
+  if (!map->layerorder) {
+    map->layerorder = (int*)msSmallMalloc(map->numlayers * sizeof(int));
+
+    /*
+     * Initiate to default order
+     */
+    for (i=0; i<map->numlayers; i++)
+      map->layerorder[i] = i;
+  }
+
+  if (map != NULL && map->numlayers > 0) {
+    nCount = map->numlayers;
+    papszGroups = (char **)msSmallMalloc(sizeof(char *)*nCount);
+
+    for (i=0; i<nCount; i++)
+      papszGroups[i] = NULL;
 
+    for (i=0; i<nCount; i++) {
+      layerObj *lp;
+      lp = (GET_LAYER(map, map->layerorder[i]));
+
+      bFound = 0;
+      if (lp->group && lp->status != MS_DELETE) {
+        for (j=0; j<*numTok; j++) {
+          if (papszGroups[j] &&
+              strcmp(lp->group, papszGroups[j]) == 0) {
+            bFound = 1;
+            break;
+          }
+        }
+        if (!bFound) {
+          /* New group... add to the list of groups found */
+          papszGroups[(*numTok)] = msStrdup(lp->group);
+          (*numTok)++;
+        }
+      }
     }
-   
-    return papszGroups;
+
+  }
+
+  return papszGroups;
 }
 
 /************************************************************************/
@@ -1318,289 +1357,263 @@ static char *ForcedTmpBase = NULL;
 
 void msForceTmpFileBase( const char *new_base )
 {
-/* -------------------------------------------------------------------- */
-/*      Clear previous setting, if any.                                 */
-/* -------------------------------------------------------------------- */
-    if( ForcedTmpBase != NULL )
-    {
-        free( ForcedTmpBase );
-        ForcedTmpBase = NULL;
-    }
-    
-    tmpCount = -1;
+  /* -------------------------------------------------------------------- */
+  /*      Clear previous setting, if any.                                 */
+  /* -------------------------------------------------------------------- */
+  if( ForcedTmpBase != NULL ) {
+    free( ForcedTmpBase );
+    ForcedTmpBase = NULL;
+  }
+
+  tmpCount = -1;
 
-    if( new_base == NULL )
-        return;
+  if( new_base == NULL )
+    return;
 
-/* -------------------------------------------------------------------- */
-/*      Record new base.                                                */
-/* -------------------------------------------------------------------- */
-    ForcedTmpBase = msStrdup( new_base );
-    tmpCount = 0;
+  /* -------------------------------------------------------------------- */
+  /*      Record new base.                                                */
+  /* -------------------------------------------------------------------- */
+  ForcedTmpBase = msStrdup( new_base );
+  tmpCount = 0;
 }
 
 /**********************************************************************
  *                          msTmpFile()
  *
  * Generate a Unique temporary file.
- * 
+ *
  * Returns char* which must be freed by caller.
  **********************************************************************/
 char *msTmpFile(mapObj *map, const char *mappath, const char *tmppath, const char *ext)
 {
-    char szPath[MS_MAXPATHLEN];
-    const char *fullFname;
-    char *tmpFileName; /* big enough for time + pid + ext */
-    char *tmpBase = NULL;
+  char szPath[MS_MAXPATHLEN];
+  const char *fullFname;
+  char *tmpFileName; /* big enough for time + pid + ext */
+  char *tmpBase = NULL;
 
-    tmpBase = msTmpPath(map, mappath, tmppath);
-    tmpFileName = msTmpFilename(ext);
+  tmpBase = msTmpPath(map, mappath, tmppath);
+  tmpFileName = msTmpFilename(ext);
 
-    fullFname = msBuildPath(szPath, tmpBase, tmpFileName);
+  fullFname = msBuildPath(szPath, tmpBase, tmpFileName);
 
-    free(tmpFileName);
-    free(tmpBase);
+  free(tmpFileName);
+  free(tmpBase);
 
-    if (fullFname)
-        return msStrdup(fullFname);
+  if (fullFname)
+    return msStrdup(fullFname);
 
-    return NULL;
+  return NULL;
 }
 
 /**********************************************************************
  *                          msTmpPath()
  *
  * Return the temporary path based on the platform.
- * 
+ *
  * Returns char* which must be freed by caller.
  **********************************************************************/
 char *msTmpPath(mapObj *map, const char *mappath, const char *tmppath)
 {
-    char szPath[MS_MAXPATHLEN];
-    const char *fullPath;
-    const char *tmpBase;
+  char szPath[MS_MAXPATHLEN];
+  const char *fullPath;
+  const char *tmpBase;
 #ifdef _WIN32
-    DWORD dwRetVal = 0;
-    TCHAR lpTempPathBuffer[MAX_PATH];
+  DWORD dwRetVal = 0;
+  TCHAR lpTempPathBuffer[MAX_PATH];
 #endif
 
-    if( ForcedTmpBase != NULL )
-        tmpBase = ForcedTmpBase;
-    else if (tmppath != NULL)
-        tmpBase = tmppath;
-    else if (getenv("MS_TEMPPATH"))
-        tmpBase = getenv("MS_TEMPPATH");
-    else if (map && map->web.temppath)
-        tmpBase = map->web.temppath;
-    else /* default paths */
-    {
-#ifndef _WIN32        
-        tmpBase = "/tmp/";
+  if( ForcedTmpBase != NULL )
+    tmpBase = ForcedTmpBase;
+  else if (tmppath != NULL)
+    tmpBase = tmppath;
+  else if (getenv("MS_TEMPPATH"))
+    tmpBase = getenv("MS_TEMPPATH");
+  else if (map && map->web.temppath)
+    tmpBase = map->web.temppath;
+  else { /* default paths */
+#ifndef _WIN32
+    tmpBase = "/tmp/";
 #else
-        dwRetVal =  GetTempPath(MAX_PATH,          // length of the buffer
-                                lpTempPathBuffer); // buffer for path 
-        if (dwRetVal > MAX_PATH || (dwRetVal == 0))
-        {
-            tmpBase = "C:\\";
-        } 
-        else
-        {
-            tmpBase = (char*)lpTempPathBuffer;
-        }
-#endif
+    dwRetVal =  GetTempPath(MAX_PATH,          /* length of the buffer */
+                            lpTempPathBuffer); /* buffer for path */
+    if (dwRetVal > MAX_PATH || (dwRetVal == 0)) {
+      tmpBase = "C:\\";
+    } else {
+      tmpBase = (char*)lpTempPathBuffer;
     }
+#endif
+  }
 
-    fullPath = msBuildPath(szPath, mappath, tmpBase);
-    return strdup(fullPath);
+  fullPath = msBuildPath(szPath, mappath, tmpBase);
+  return strdup(fullPath);
 }
 
 /**********************************************************************
  *                          msTmpFilename()
  *
  * Generate a Unique temporary filename.
- * 
+ *
  * Returns char* which must be freed by caller.
  **********************************************************************/
 char *msTmpFilename(const char *ext)
 {
-    char *tmpFname;
-    int tmpFnameBufsize;
-    char *fullFname;
-    char tmpId[128]; /* big enough for time + pid + ext */
+  char *tmpFname;
+  int tmpFnameBufsize;
+  char *fullFname;
+  char tmpId[128]; /* big enough for time + pid + ext */
 
-    snprintf(tmpId, sizeof(tmpId), "%lx_%x",(long)time(NULL),(int)getpid());
+  snprintf(tmpId, sizeof(tmpId), "%lx_%x",(long)time(NULL),(int)getpid());
 
-    if (ext == NULL)  ext = "";
-    tmpFnameBufsize = strlen(tmpId) + 10 + strlen(ext) + 1;
-    tmpFname = (char*)msSmallMalloc(tmpFnameBufsize);
+  if (ext == NULL)  ext = "";
+  tmpFnameBufsize = strlen(tmpId) + 10 + strlen(ext) + 1;
+  tmpFname = (char*)msSmallMalloc(tmpFnameBufsize);
 
-    msAcquireLock( TLOCK_TMPFILE );
-    snprintf(tmpFname, tmpFnameBufsize, "%s_%x.%s", tmpId, tmpCount++, ext);
-    msReleaseLock( TLOCK_TMPFILE );
+  msAcquireLock( TLOCK_TMPFILE );
+  snprintf(tmpFname, tmpFnameBufsize, "%s_%x.%s", tmpId, tmpCount++, ext);
+  msReleaseLock( TLOCK_TMPFILE );
 
-    fullFname = strdup(tmpFname);
-    free(tmpFname);
+  fullFname = strdup(tmpFname);
+  free(tmpFname);
 
-    return fullFname;
+  return fullFname;
 }
 
 /**
  *  Generic function to Initalize an image object.
  */
-imageObj *msImageCreate(int width, int height, outputFormatObj *format, 
+imageObj *msImageCreate(int width, int height, outputFormatObj *format,
                         char *imagepath, char *imageurl, double resolution,
                         double defresolution, colorObj *bg)
 {
-    imageObj *image = NULL;
-    if(MS_RENDERER_PLUGIN(format)) {
-        
-    	image = format->vtable->createImage(width,height,format,bg);
-        if (image == NULL)
-        {
-            msSetError(MS_MEMERR, "Unable to create new image object.", "msImageCreate()");
-            return NULL;
-        }
+  imageObj *image = NULL;
+  if(MS_RENDERER_PLUGIN(format)) {
 
-    	image->format = format;
-        format->refcount++;
-
-        image->width = width;
-        image->height = height;
-        image->imagepath = NULL;
-        image->imageurl = NULL;
-        image->tilecache = NULL;
-        image->ntiles = 0;
-        image->resolution = resolution;
-        image->resolutionfactor = resolution/defresolution;
-
-        if (imagepath)
-            image->imagepath = msStrdup(imagepath);
-        if (imageurl)
-            image->imageurl = msStrdup(imageurl);
-
-        return image;
+    image = format->vtable->createImage(width,height,format,bg);
+    if (image == NULL) {
+      msSetError(MS_MEMERR, "Unable to create new image object.", "msImageCreate()");
+      return NULL;
     }
-    else if( MS_RENDERER_RAWDATA(format) )
-    {
-        if( format->imagemode != MS_IMAGEMODE_INT16
-            && format->imagemode != MS_IMAGEMODE_FLOAT32 
-            && format->imagemode != MS_IMAGEMODE_BYTE )
-        {
-            msSetError(MS_IMGERR, 
-                       "Attempt to use illegal imagemode with rawdata renderer.",
-                       "msImageCreate()" );
-            return NULL;
-        }
-
-        image = (imageObj *)calloc(1,sizeof(imageObj));
-        if (image == NULL)
-        {
-            msSetError(MS_MEMERR, "Unable to create new image object.", "msImageCreate()");
-            return NULL;
-        }
-
-        if( format->imagemode == MS_IMAGEMODE_INT16 )
-            image->img.raw_16bit = (short *) 
-                msSmallCalloc(sizeof(short),width*height*format->bands);
-        else if( format->imagemode == MS_IMAGEMODE_FLOAT32 )
-            image->img.raw_float = (float *) 
-                msSmallCalloc(sizeof(float),width*height*format->bands);
-        else if( format->imagemode == MS_IMAGEMODE_BYTE )
-            image->img.raw_byte = (unsigned char *) 
-                msSmallCalloc(sizeof(unsigned char),width*height*format->bands);
-
-        if( image->img.raw_16bit == NULL )
-        {
-            msFree( image );
-            msSetError(MS_IMGERR, 
-                       "Attempt to allocate raw image failed, out of memory.",
-                       "msImageCreate()" );
-            return NULL;
-        }
-
-        image->img_mask = msAllocBitArray( width*height );
-            
-        image->format = format;
-        format->refcount++;
-
-        image->width = width;
-        image->height = height;
-        image->imagepath = NULL;
-        image->imageurl = NULL;
-        image->resolution = resolution;
-        image->resolutionfactor = resolution/defresolution;
-
-        if (imagepath)
-            image->imagepath = msStrdup(imagepath);
-        if (imageurl)
-            image->imageurl = msStrdup(imageurl);
-
-        /* initialize to requested nullvalue if there is one */
-        if( msGetOutputFormatOption(image->format,"NULLVALUE",NULL) != NULL )
-        {
-            int i = image->width * image->height * format->bands;
-            const char *nullvalue = msGetOutputFormatOption(image->format,
-                                                            "NULLVALUE",NULL);
-
-            if( atof(nullvalue) == 0.0 )
-                /* nothing to do */;
-            else if( format->imagemode == MS_IMAGEMODE_INT16 )
-            {
-                short nv = atoi(nullvalue);
-                for( ; i > 0; )
-                    image->img.raw_16bit[--i] = nv;
-            }
-            else if( format->imagemode == MS_IMAGEMODE_FLOAT32 )
-            {
-                float nv = atoi(nullvalue);
-                for( ; i > 0; )
-                    image->img.raw_float[--i] = nv;
-            }
-            else if( format->imagemode == MS_IMAGEMODE_BYTE )
-            {
-                unsigned char nv = (unsigned char) atoi(nullvalue);
-
-                memset( image->img.raw_byte, nv, i );
-            }
-        }
 
-        return image;
+    image->format = format;
+    format->refcount++;
+
+    image->width = width;
+    image->height = height;
+    image->imagepath = NULL;
+    image->imageurl = NULL;
+    image->tilecache = NULL;
+    image->ntiles = 0;
+    image->resolution = resolution;
+    image->resolutionfactor = resolution/defresolution;
+
+    if (imagepath)
+      image->imagepath = msStrdup(imagepath);
+    if (imageurl)
+      image->imageurl = msStrdup(imageurl);
+  } else if( MS_RENDERER_RAWDATA(format) ) {
+    if( format->imagemode != MS_IMAGEMODE_INT16
+        && format->imagemode != MS_IMAGEMODE_FLOAT32
+        && format->imagemode != MS_IMAGEMODE_BYTE ) {
+      msSetError(MS_IMGERR,
+                 "Attempt to use illegal imagemode with rawdata renderer.",
+                 "msImageCreate()" );
+      return NULL;
     }
-    else if( MS_RENDERER_IMAGEMAP(format) )
-    {
-        image = msImageCreateIM(width, height, format,
-                                imagepath, imageurl, resolution, defresolution);
-        if( image != NULL ) msImageInitIM( image );
+
+    image = (imageObj *)calloc(1,sizeof(imageObj));
+    if (image == NULL) {
+      msSetError(MS_MEMERR, "Unable to create new image object.", "msImageCreate()");
+      return NULL;
     }
-    else 
-    {
-        msSetError(MS_MISCERR, 
-                   "Unsupported renderer requested, unable to initialize image.", 
-                   "msImageCreate()");
-        return NULL;
+
+    if( format->imagemode == MS_IMAGEMODE_INT16 )
+      image->img.raw_16bit = (short *)
+                             msSmallCalloc(sizeof(short),width*height*format->bands);
+    else if( format->imagemode == MS_IMAGEMODE_FLOAT32 )
+      image->img.raw_float = (float *)
+                             msSmallCalloc(sizeof(float),width*height*format->bands);
+    else if( format->imagemode == MS_IMAGEMODE_BYTE )
+      image->img.raw_byte = (unsigned char *)
+                            msSmallCalloc(sizeof(unsigned char),width*height*format->bands);
+
+    if( image->img.raw_16bit == NULL ) {
+      msFree( image );
+      msSetError(MS_IMGERR,
+                 "Attempt to allocate raw image failed, out of memory.",
+                 "msImageCreate()" );
+      return NULL;
     }
 
-    if(!image) 
-        msSetError(MS_GDERR, "Unable to initialize image.", "msImageCreate()");
+    image->img_mask = msAllocBitArray( width*height );
+
+    image->format = format;
+    format->refcount++;
+
+    image->width = width;
+    image->height = height;
+    image->imagepath = NULL;
+    image->imageurl = NULL;
+    image->resolution = resolution;
+    image->resolutionfactor = resolution/defresolution;
+
+    if (imagepath)
+      image->imagepath = msStrdup(imagepath);
+    if (imageurl)
+      image->imageurl = msStrdup(imageurl);
+
+    /* initialize to requested nullvalue if there is one */
+    if( msGetOutputFormatOption(image->format,"NULLVALUE",NULL) != NULL ) {
+      int i = image->width * image->height * format->bands;
+      const char *nullvalue = msGetOutputFormatOption(image->format,
+                              "NULLVALUE",NULL);
+
+      if( atof(nullvalue) == 0.0 )
+        /* nothing to do */;
+      else if( format->imagemode == MS_IMAGEMODE_INT16 ) {
+        short nv = atoi(nullvalue);
+        for( ; i > 0; )
+          image->img.raw_16bit[--i] = nv;
+      } else if( format->imagemode == MS_IMAGEMODE_FLOAT32 ) {
+        float nv = atoi(nullvalue);
+        for( ; i > 0; )
+          image->img.raw_float[--i] = nv;
+      } else if( format->imagemode == MS_IMAGEMODE_BYTE ) {
+        unsigned char nv = (unsigned char) atoi(nullvalue);
+
+        memset( image->img.raw_byte, nv, i );
+      }
+    }
+  } else if( MS_RENDERER_IMAGEMAP(format) ) {
+    image = msImageCreateIM(width, height, format,
+                            imagepath, imageurl, resolution, defresolution);
+  } else {
+    msSetError(MS_MISCERR,
+               "Unsupported renderer requested, unable to initialize image.",
+               "msImageCreate()");
+    return NULL;
+  }
 
-    return image;
+  if(!image)
+    msSetError(MS_GDERR, "Unable to initialize image.", "msImageCreate()");
+  image->refpt.x = image->refpt.y = 0;
+  return image;
 }
 
 
 /**
  * Generic function to transorm a point.
- * 
+ *
  */
-void  msTransformPoint(pointObj *point, rectObj *extent, double cellsize, 
-                       imageObj *image)   
+void  msTransformPoint(pointObj *point, rectObj *extent, double cellsize,
+                       imageObj *image)
 {
-    /*We should probabaly have a function defined at all the renders*/
-    if (image != NULL && MS_RENDERER_PLUGIN(image->format) && 
-        image->format->renderer == MS_RENDER_WITH_KML)
-      return;
+  /*We should probabaly have a function defined at all the renders*/
+  if (image != NULL && MS_RENDERER_PLUGIN(image->format) &&
+      image->format->renderer == MS_RENDER_WITH_KML)
+    return;
 
-    point->x = MS_MAP2IMAGE_X(point->x, extent->minx, cellsize);
-    point->y = MS_MAP2IMAGE_Y(point->y, extent->maxy, cellsize);
+  point->x = MS_MAP2IMAGE_X(point->x, extent->minx, cellsize);
+  point->y = MS_MAP2IMAGE_Y(point->y, extent->maxy, cellsize);
 }
 
 
@@ -1612,37 +1625,47 @@ void  msTransformPoint(pointObj *point, rectObj *extent, double cellsize,
 */
 
 /* vector difference */
-static pointObj point_diff(const pointObj a, const pointObj b) {
-  pointObj retv = {a.x-b.x,a.y-b.y
+static pointObj point_diff(const pointObj a, const pointObj b)
+{
+  pointObj retv;
+  retv.x = a.x-b.x;
+  retv.y = a.y-b.y;
 #ifdef USE_POINT_Z_M
-    ,a.z-b.z,a.m-b.m
+  retv.z = a.z-b.z;
+  retv.m = a.m-b.m;
 #endif
-  };
   return retv;
 }
 
 /* vector sum */
-static pointObj point_sum(const pointObj a, const pointObj b) {
-  pointObj retv = {a.x+b.x,a.y+b.y
+static pointObj point_sum(const pointObj a, const pointObj b)
+{
+  pointObj retv;
+  retv.x = a.x+b.x;
+  retv.y = a.y+b.y;
 #ifdef USE_POINT_Z_M
-    ,a.z+b.z,a.m+b.m
+  retv.z = a.z+b.z;
+  retv.m = a.m+b.m;
 #endif
-  };
   return retv;
 }
 
 /* vector multiply */
-static pointObj point_mul(const pointObj a, double b) {
-  pointObj retv= {a.x*b,a.y*b
+static pointObj point_mul(const pointObj a, double b)
+{
+  pointObj retv;
+  retv.x = a.x*b;
+  retv.y = a.y*b;
 #ifdef USE_POINT_Z_M
-    ,a.z*b,a.m*b
+  retv.z = a.z*b;
+  retv.m = a.m*b;
 #endif
-  };
   return retv;
 }
 
 /* vector ??? */
-static double point_abs2(const pointObj a) {
+static double point_abs2(const pointObj a)
+{
 #ifdef USE_POINT_Z_M
   return a.x*a.x+a.y*a.y+a.z*a.z+a.m*a.m;
 #else
@@ -1651,14 +1674,15 @@ static double point_abs2(const pointObj a) {
 }
 
 /* vector normal */
-static pointObj point_norm(const pointObj a) {
+static pointObj point_norm(const pointObj a)
+{
   double lenmul;
   pointObj retv;
 
 #ifdef USE_POINT_Z_M
-  if (a.x==0 && a.y==0 && a.z==0 && a.m==0) 
+  if (a.x==0 && a.y==0 && a.z==0 && a.m==0)
 #else
-  if (a.x==0 && a.y==0) 
+  if (a.x==0 && a.y==0)
 #endif
     return a;
 
@@ -1675,40 +1699,50 @@ static pointObj point_norm(const pointObj a) {
 }
 
 /* rotate a vector 90 degrees */
-static pointObj point_rotz90(const pointObj a) {
+static pointObj point_rotz90(const pointObj a)
+{
   double nx=-1.0*a.y, ny=a.x;
   pointObj retv=a;
-  retv.x=nx; retv.y=ny;
+  retv.x=nx;
+  retv.y=ny;
   return retv;
 }
 
 /* vector cross product (warning: z and m dimensions are ignored!) */
-static double point_cross(const pointObj a, const pointObj b) {
+static double point_cross(const pointObj a, const pointObj b)
+{
   return a.x*b.y-a.y*b.x;
 }
 
-/* 
+/*
 ** For offset corner point calculation 1/sin() is used
-** to avoid 1/0 division (and long spikes) we define a 
+** to avoid 1/0 division (and long spikes) we define a
 ** limit for sin().
 */
 #define CURVE_SIN_LIMIT 0.3
 
-shapeObj *msOffsetPolyline(shapeObj *p, double offsetx, double offsety) {
+shapeObj *msOffsetPolyline(shapeObj *p, double offsetx, double offsety)
+{
   int i, j, first,idx;
 
   shapeObj *ret = (shapeObj*)msSmallMalloc(sizeof(shapeObj));
   msInitShape(ret);
   ret->numlines = p->numlines;
   ret->line=(lineObj*)msSmallMalloc(sizeof(lineObj)*ret->numlines);
-  for(i=0;i<ret->numlines;i++) {
+  for(i=0; i<ret->numlines; i++) {
     ret->line[i].numpoints=p->line[i].numpoints;
     ret->line[i].point=(pointObj*)msSmallMalloc(sizeof(pointObj)*ret->line[i].numpoints);
   }
 
   if(offsety == -99) { /* complex calculations */
+    int ok = 0;
     for (i = 0; i < p->numlines; i++) {
       pointObj old_pt, old_diffdir, old_offdir;
+      if(p->line[i].numpoints<2) {
+        ret->line[i].numpoints = 0;
+        continue; /* skip degenerate lines */
+      }
+      ok =1;
       /* initialize old_offdir and old_diffdir, as gcc isn't smart enough to see that it
        * is not an error to do so, and prints a warning */
       old_offdir.x=old_offdir.y=old_diffdir.x=old_diffdir.y = 0;
@@ -1736,8 +1770,8 @@ shapeObj *msOffsetPolyline(shapeObj *p, double offsetx, double offsety) {
           if ((-1.0)*CURVE_SIN_LIMIT < sin_curve && sin_curve < CURVE_SIN_LIMIT) {
             /* do not calculate 1/sin, instead use a corner point approximation: average of the last and current offset direction and length */
 
-            /* 
-	    ** TODO: fair for obtuse inner angles, however, positive and negative
+            /*
+            ** TODO: fair for obtuse inner angles, however, positive and negative
             ** acute inner angles would need special handling - similar to LINECAP
             ** to avoid drawing of long spikes
             */
@@ -1745,26 +1779,29 @@ shapeObj *msOffsetPolyline(shapeObj *p, double offsetx, double offsety) {
           } else {
             double base_shift = -1.0*(1.0+cos_curve)/sin_curve;
             offpt = point_sum(old_pt, point_mul(point_sum(point_mul(diffdir,base_shift),offdir), offsetx));
-	  }
+          }
         }
         ret->line[i].point[idx]=offpt;
         idx++;
-        old_pt=pt; old_diffdir=diffdir; old_offdir=offdir;
+        old_pt=pt;
+        old_diffdir=diffdir;
+        old_offdir=offdir;
       }
-	            
+
       /* last point */
       if(first == 0) {
         pointObj offpt=point_sum(old_pt,point_mul(old_offdir,offsetx));
         ret->line[i].point[idx]=offpt;
         idx++;
       }
-            
+
       if(idx != p->line[i].numpoints) {
         /* printf("shouldn't happen :(\n"); */
         ret->line[i].numpoints=idx;
         ret->line=msSmallRealloc(ret->line,ret->line[i].numpoints*sizeof(pointObj));
       }
     }
+    if(!ok) ret->numlines = 0; /* all lines where degenerate */
   } else { /* normal offset (eg. drop shadow) */
     for (i = 0; i < p->numlines; i++) {
       for(j=0; j<p->line[i].numpoints; j++) {
@@ -1790,17 +1827,15 @@ shapeObj *msOffsetPolyline(shapeObj *p, double offsetx, double offsety) {
 int msSetup()
 {
 #ifdef USE_THREAD
-   msThreadInit();
+  msThreadInit();
 #endif
 
   /* Use MS_ERRORFILE and MS_DEBUGLEVEL env vars if set */
   if (msDebugInitFromEnv() != MS_SUCCESS)
     return MS_FAILURE;
 
-#ifdef USE_GD_FT
-  if (gdFontCacheSetup() != 0) {
-    return MS_FAILURE;
-   }
+#ifdef USE_GD
+  msGDSetup();
 #endif
 
 #ifdef USE_GEOS
@@ -1809,16 +1844,15 @@ int msSetup()
 
   return MS_SUCCESS;
 }
-  
+
 /* This is intended to be a function to cleanup anything that "hangs around"
    when all maps are destroyed, like Registered GDAL drivers, and so forth. */
-void msCleanup()
+void msCleanup(int signal)
 {
   msForceTmpFileBase( NULL );
   msConnPoolFinalCleanup();
   /* Lexer string parsing variable */
-  if (msyystring_buffer != NULL)
-  {
+  if (msyystring_buffer != NULL) {
     msFree(msyystring_buffer);
     msyystring_buffer = NULL;
   }
@@ -1826,12 +1860,12 @@ void msCleanup()
 
 #ifdef USE_OGR
   msOGRCleanup();
-#endif    
+#endif
 #ifdef USE_GDAL
   msGDALCleanup();
-#endif    
+#endif
 #ifdef USE_PROJ
-#  if PJ_VERSION >= 480
+#  if PJ_VERSION >= 470
   pj_clear_initcache();
 #  endif
   pj_deallocate_grids();
@@ -1841,14 +1875,26 @@ void msCleanup()
   msHTTPCleanup();
 #endif
 
-#ifdef USE_GD_FT
-  gdFontCacheShutdown(); 
+#ifdef USE_GD
+  msGDCleanup(signal);
 #endif
 
 #ifdef USE_GEOS
   msGEOSCleanup();
 #endif
-  
+
+/* make valgrind happy on debug code */
+#ifndef NDEBUG
+#ifdef USE_CAIRO
+  msCairoCleanup();
+#endif
+#if defined(USE_LIBXML2)
+  xmlCleanupParser();
+#endif
+#endif
+
+  msTimeCleanup();
+
   msIO_Cleanup();
 
   msResetErrorList();
@@ -1874,66 +1920,62 @@ void msCleanup()
 /************************************************************************/
 
 void msAlphaBlend( unsigned char red_src, unsigned char green_src,
-                    unsigned char blue_src, unsigned char alpha_src, 
-                    unsigned char *red_dst, unsigned char *green_dst,
-                    unsigned char *blue_dst, unsigned char *alpha_dst )
+                   unsigned char blue_src, unsigned char alpha_src,
+                   unsigned char *red_dst, unsigned char *green_dst,
+                   unsigned char *blue_dst, unsigned char *alpha_dst )
 {
-/* -------------------------------------------------------------------- */
-/*      Simple cases we want to handle fast.                            */
-/* -------------------------------------------------------------------- */
-    if( alpha_src == 0 )
-        return;
-    
-    if( alpha_src == 255 )
-    {
-        *red_dst = red_src;
-        *green_dst = green_src;
-        *blue_dst = blue_src;
-        if( alpha_dst )
-            *alpha_dst = 255;
-        return;
-    }
+  /* -------------------------------------------------------------------- */
+  /*      Simple cases we want to handle fast.                            */
+  /* -------------------------------------------------------------------- */
+  if( alpha_src == 0 )
+    return;
+
+  if( alpha_src == 255 ) {
+    *red_dst = red_src;
+    *green_dst = green_src;
+    *blue_dst = blue_src;
+    if( alpha_dst )
+      *alpha_dst = 255;
+    return;
+  }
 
-/* -------------------------------------------------------------------- */
-/*      Premultiple alpha for source values now.                        */
-/* -------------------------------------------------------------------- */
-    red_src   = red_src * alpha_src / 255;
-    green_src = green_src * alpha_src / 255;
-    blue_src  = blue_src * alpha_src / 255;
-
-/* -------------------------------------------------------------------- */
-/*      Another pretty fast case if there is nothing in the             */
-/*      destination to mix with.                                        */
-/* -------------------------------------------------------------------- */
-    if( alpha_dst && *alpha_dst == 0) {
-       *red_dst = red_src;
-       *green_dst = green_src;
-       *blue_dst = blue_src;
-       *alpha_dst = alpha_src;
-       return;
-    }
+  /* -------------------------------------------------------------------- */
+  /*      Premultiple alpha for source values now.                        */
+  /* -------------------------------------------------------------------- */
+  red_src   = red_src * alpha_src / 255;
+  green_src = green_src * alpha_src / 255;
+  blue_src  = blue_src * alpha_src / 255;
+
+  /* -------------------------------------------------------------------- */
+  /*      Another pretty fast case if there is nothing in the             */
+  /*      destination to mix with.                                        */
+  /* -------------------------------------------------------------------- */
+  if( alpha_dst && *alpha_dst == 0) {
+    *red_dst = red_src;
+    *green_dst = green_src;
+    *blue_dst = blue_src;
+    *alpha_dst = alpha_src;
+    return;
+  }
 
-/* -------------------------------------------------------------------- */
-/*      Cases with actual blending.                                     */
-/* -------------------------------------------------------------------- */
-    if(!alpha_dst || *alpha_dst == 255) 
-    {
-        int weight_dst = 256 - alpha_src;
-
-        *red_dst   = (256 * red_src   + *red_dst   * weight_dst) >> 8;
-        *green_dst = (256 * green_src + *green_dst * weight_dst) >> 8;
-        *blue_dst  = (256 * blue_src  + *blue_dst  * weight_dst) >> 8;
-    } 
-    else 
-    {
-        int   weight_dst = (256 - alpha_src);
-
-        *red_dst   = (256 * red_src   + *red_dst   * weight_dst) >> 8;
-        *green_dst = (256 * green_src + *green_dst * weight_dst) >> 8;
-        *blue_dst  = (256 * blue_src  + *blue_dst  * weight_dst) >> 8;
-
-        *alpha_dst = (256 * alpha_src + *alpha_dst * weight_dst) >> 8;
-    }
+  /* -------------------------------------------------------------------- */
+  /*      Cases with actual blending.                                     */
+  /* -------------------------------------------------------------------- */
+  if(!alpha_dst || *alpha_dst == 255) {
+    int weight_dst = 256 - alpha_src;
+
+    *red_dst   = (256 * red_src   + *red_dst   * weight_dst) >> 8;
+    *green_dst = (256 * green_src + *green_dst * weight_dst) >> 8;
+    *blue_dst  = (256 * blue_src  + *blue_dst  * weight_dst) >> 8;
+  } else {
+    int   weight_dst = (256 - alpha_src);
+
+    *red_dst   = (256 * red_src   + *red_dst   * weight_dst) >> 8;
+    *green_dst = (256 * green_src + *green_dst * weight_dst) >> 8;
+    *blue_dst  = (256 * blue_src  + *blue_dst  * weight_dst) >> 8;
+
+    *alpha_dst = (256 * alpha_src + *alpha_dst * weight_dst) >> 8;
+  }
 }
 
 /************************************************************************/
@@ -1944,130 +1986,135 @@ void msAlphaBlend( unsigned char red_src, unsigned char green_src,
 /************************************************************************/
 
 void msAlphaBlendPM( unsigned char red_src, unsigned char green_src,
-                     unsigned char blue_src, unsigned char alpha_src, 
+                     unsigned char blue_src, unsigned char alpha_src,
                      unsigned char *red_dst, unsigned char *green_dst,
                      unsigned char *blue_dst, unsigned char *alpha_dst )
 {
-/* -------------------------------------------------------------------- */
-/*      Simple cases we want to handle fast.                            */
-/* -------------------------------------------------------------------- */
-    if( alpha_src == 0 )
-        return;
-    
-    if( alpha_src == 255 )
-    {
-        *red_dst = red_src;
-        *green_dst = green_src;
-        *blue_dst = blue_src;
-        if( alpha_dst )
-            *alpha_dst = 255;
-        return;
-    }
+  /* -------------------------------------------------------------------- */
+  /*      Simple cases we want to handle fast.                            */
+  /* -------------------------------------------------------------------- */
+  if( alpha_src == 0 )
+    return;
+
+  if( alpha_src == 255 ) {
+    *red_dst = red_src;
+    *green_dst = green_src;
+    *blue_dst = blue_src;
+    if( alpha_dst )
+      *alpha_dst = 255;
+    return;
+  }
 
-/* -------------------------------------------------------------------- */
-/*      Another pretty fast case if there is nothing in the             */
-/*      destination to mix with.                                        */
-/* -------------------------------------------------------------------- */
-    if( alpha_dst && *alpha_dst == 0) {
-       *red_dst = red_src;
-       *green_dst = green_src;
-       *blue_dst = blue_src;
-       *alpha_dst = alpha_src;
-       return;
-    }
+  /* -------------------------------------------------------------------- */
+  /*      Another pretty fast case if there is nothing in the             */
+  /*      destination to mix with.                                        */
+  /* -------------------------------------------------------------------- */
+  if( alpha_dst && *alpha_dst == 0) {
+    *red_dst = red_src;
+    *green_dst = green_src;
+    *blue_dst = blue_src;
+    *alpha_dst = alpha_src;
+    return;
+  }
 
-/* -------------------------------------------------------------------- */
-/*      Cases with actual blending.                                     */
-/* -------------------------------------------------------------------- */
-    if(!alpha_dst || *alpha_dst == 255) 
-    {
-        int weight_dst = 256 - alpha_src;
-
-        *red_dst   = (256 * red_src   + *red_dst   * weight_dst) >> 8;
-        *green_dst = (256 * green_src + *green_dst * weight_dst) >> 8;
-        *blue_dst  = (256 * blue_src  + *blue_dst  * weight_dst) >> 8;
-    } 
-    else 
-    {
-        int   weight_dst = (256 - alpha_src);
-
-        *red_dst   = (256 * red_src   + *red_dst   * weight_dst) >> 8;
-        *green_dst = (256 * green_src + *green_dst * weight_dst) >> 8;
-        *blue_dst  = (256 * blue_src  + *blue_dst  * weight_dst) >> 8;
-
-        *alpha_dst = (256 * alpha_src + *alpha_dst * weight_dst) >> 8;
-    }
+  /* -------------------------------------------------------------------- */
+  /*      Cases with actual blending.                                     */
+  /* -------------------------------------------------------------------- */
+  if(!alpha_dst || *alpha_dst == 255) {
+    int weight_dst = 256 - alpha_src;
+
+    *red_dst   = (256 * red_src   + *red_dst   * weight_dst) >> 8;
+    *green_dst = (256 * green_src + *green_dst * weight_dst) >> 8;
+    *blue_dst  = (256 * blue_src  + *blue_dst  * weight_dst) >> 8;
+  } else {
+    int   weight_dst = (256 - alpha_src);
+
+    *red_dst   = (256 * red_src   + *red_dst   * weight_dst) >> 8;
+    *green_dst = (256 * green_src + *green_dst * weight_dst) >> 8;
+    *blue_dst  = (256 * blue_src  + *blue_dst  * weight_dst) >> 8;
+
+    *alpha_dst = (256 * alpha_src + *alpha_dst * weight_dst) >> 8;
+  }
 }
 
 /*
  RFC 24: check if the parent pointer is NULL and raise an error otherwise
 */
-int msCheckParentPointer(void* p, char *objname) {
-    char* fmt="The %s parent object is null";
-    char* msg=NULL;
-    if (p == NULL) {
-        if(objname != NULL) {
-            msg=malloc( sizeof(char) * ( ( strlen(fmt)+strlen(objname) ) ) );
-            if(msg == NULL) {
-                msg="A required parent object is null";
-            } else {
-                sprintf(msg, "The %s parent object is null", objname);
-            }
-        } else {
-            msg="A required parent object is null";
-        }
-        msSetError(MS_NULLPARENTERR, msg, "");
-        return MS_FAILURE;
+int msCheckParentPointer(void* p, char *objname)
+{
+  char* fmt="The %s parent object is null";
+  char* msg=NULL;
+  if (p == NULL) {
+    if(objname != NULL) {
+      msg=malloc( sizeof(char) * ( ( strlen(fmt)+strlen(objname) ) ) );
+      if(msg == NULL) {
+        msg="A required parent object is null";
+      } else {
+        sprintf(msg, "The %s parent object is null", objname);
+      }
+    } else {
+      msg="A required parent object is null";
     }
-    return MS_SUCCESS;
+    msSetError(MS_NULLPARENTERR, msg, "");
+    return MS_FAILURE;
+  }
+  return MS_SUCCESS;
 }
 
-void msBufferInit(bufferObj *buffer) {
-    buffer->data=NULL;
-    buffer->size=0;
-    buffer->available=0;
-    buffer->_next_allocation_size = MS_DEFAULT_BUFFER_ALLOC;
+void msBufferInit(bufferObj *buffer)
+{
+  buffer->data=NULL;
+  buffer->size=0;
+  buffer->available=0;
+  buffer->_next_allocation_size = MS_DEFAULT_BUFFER_ALLOC;
 }
 
-void msBufferResize(bufferObj *buffer, size_t target_size){
-    while(buffer->available <= target_size) {
-        buffer->data = msSmallRealloc(buffer->data,buffer->available+buffer->_next_allocation_size);
-        buffer->available += buffer->_next_allocation_size;
-        buffer->_next_allocation_size *= 2;
-    }
+void msBufferResize(bufferObj *buffer, size_t target_size)
+{
+  while(buffer->available <= target_size) {
+    buffer->data = msSmallRealloc(buffer->data,buffer->available+buffer->_next_allocation_size);
+    buffer->available += buffer->_next_allocation_size;
+    buffer->_next_allocation_size *= 2;
+  }
 }
 
-void msBufferAppend(bufferObj *buffer, void *data, size_t length) {
-    if(buffer->available < buffer->size+length) {
-        msBufferResize(buffer,buffer->size+length);
-    }
-    memcpy(&(buffer->data[buffer->size]),data,length);
-    buffer->size += length;
+void msBufferAppend(bufferObj *buffer, void *data, size_t length)
+{
+  if(buffer->available < buffer->size+length) {
+    msBufferResize(buffer,buffer->size+length);
+  }
+  memcpy(&(buffer->data[buffer->size]),data,length);
+  buffer->size += length;
 }
 
-void msBufferFree(bufferObj *buffer) {
-    if(buffer->available>0)
-        free(buffer->data);
+void msBufferFree(bufferObj *buffer)
+{
+  if(buffer->available>0)
+    free(buffer->data);
 }
 
 
-void msFreeRasterBuffer(rasterBufferObj *b) {
-    switch(b->type) {
+void msFreeRasterBuffer(rasterBufferObj *b)
+{
+  switch(b->type) {
     case MS_BUFFER_BYTE_RGBA:
-		msFree(b->data.rgba.pixels);
-		b->data.rgba.pixels = NULL;
-		break;
+      msFree(b->data.rgba.pixels);
+      b->data.rgba.pixels = NULL;
+      break;
     case MS_BUFFER_BYTE_PALETTE:
-    	msFree(b->data.palette.pixels);
-    	msFree(b->data.palette.palette);
-    	b->data.palette.pixels = NULL;
-    	b->data.palette.palette = NULL;
-    	break;
+      msFree(b->data.palette.pixels);
+      msFree(b->data.palette.palette);
+      b->data.palette.pixels = NULL;
+      b->data.palette.palette = NULL;
+      break;
+#ifdef USE_GD
     case MS_BUFFER_GD:
-    	gdImageDestroy(b->data.gd_img);
-        b->data.gd_img = NULL;
-        break;
-    }
+      gdImageDestroy(b->data.gd_img);
+      b->data.gd_img = NULL;
+      break;
+#endif
+  }
+
 }
 
 /*
@@ -2075,56 +2122,58 @@ void msFreeRasterBuffer(rasterBufferObj *b) {
 **
 ** msExtentsOverlap()
 **
-** Returns MS_TRUE if map extent and layer extent overlap, 
-** MS_FALSE if they are disjoint, and MS_UNKNOWN if there is 
+** Returns MS_TRUE if map extent and layer extent overlap,
+** MS_FALSE if they are disjoint, and MS_UNKNOWN if there is
 ** not enough info to calculate a deterministic answer.
 **
 */
 int msExtentsOverlap(mapObj *map, layerObj *layer)
 {
-    rectObj map_extent;
-    rectObj layer_extent;
-    
-    /* No extent info? Nothing we can do, return MS_UNKNOWN. */
-    if( (map->extent.minx == -1) && (map->extent.miny == -1) && (map->extent.maxx == -1 ) && (map->extent.maxy == -1) ) return MS_UNKNOWN;
-    if( (layer->extent.minx == -1) && (layer->extent.miny == -1) && (layer->extent.maxx == -1 ) && (layer->extent.maxy == -1) ) return MS_UNKNOWN;
-        
 #ifdef USE_PROJ
+  rectObj map_extent;
+  rectObj layer_extent;
+#endif
+
+  /* No extent info? Nothing we can do, return MS_UNKNOWN. */
+  if( (map->extent.minx == -1) && (map->extent.miny == -1) && (map->extent.maxx == -1 ) && (map->extent.maxy == -1) ) return MS_UNKNOWN;
+  if( (layer->extent.minx == -1) && (layer->extent.miny == -1) && (layer->extent.maxx == -1 ) && (layer->extent.maxy == -1) ) return MS_UNKNOWN;
 
-    /* No map projection? Let someone else sort this out. */
-    if( ! (map->projection.numargs > 0) ) 
-        return MS_UNKNOWN;
-
-    /* No layer projection? Perform naive comparison, because they are 
-    ** in the same projection. */
-    if( ! (layer->projection.numargs > 0) ) 
-        return msRectOverlap( &(map->extent), &(layer->extent) );
-    
-    /* We need to transform our rectangles for comparison, 
-    ** so we will work with copies and leave the originals intact. */
-    MS_COPYRECT(&map_extent, &(map->extent) );
-    MS_COPYRECT(&layer_extent, &(layer->extent) );
-
-    /* Transform map extents into geographics for comparison. */
-    if( msProjectRect(&(map->projection), &(map->latlon), &map_extent) )
-        return MS_UNKNOWN;
-        
-    /* Transform layer extents into geographics for comparison. */
-    if( msProjectRect(&(layer->projection), &(map->latlon), &layer_extent) )
-        return MS_UNKNOWN;
-
-    /* Simple case? Return simple answer. */
-    if ( map_extent.minx < map_extent.maxx && layer_extent.minx < layer_extent.maxx )
-        return msRectOverlap( &(map_extent), &(layer_extent) );
-        
-    /* Uh oh, one of the rects crosses the dateline!
-    ** Let someone else handle it. */
+#ifdef USE_PROJ
+
+  /* No map projection? Let someone else sort this out. */
+  if( ! (map->projection.numargs > 0) )
     return MS_UNKNOWN;
-   
+
+  /* No layer projection? Perform naive comparison, because they are
+  ** in the same projection. */
+  if( ! (layer->projection.numargs > 0) )
+    return msRectOverlap( &(map->extent), &(layer->extent) );
+
+  /* We need to transform our rectangles for comparison,
+  ** so we will work with copies and leave the originals intact. */
+  MS_COPYRECT(&map_extent, &(map->extent) );
+  MS_COPYRECT(&layer_extent, &(layer->extent) );
+
+  /* Transform map extents into geographics for comparison. */
+  if( msProjectRect(&(map->projection), &(map->latlon), &map_extent) )
+    return MS_UNKNOWN;
+
+  /* Transform layer extents into geographics for comparison. */
+  if( msProjectRect(&(layer->projection), &(map->latlon), &layer_extent) )
+    return MS_UNKNOWN;
+
+  /* Simple case? Return simple answer. */
+  if ( map_extent.minx < map_extent.maxx && layer_extent.minx < layer_extent.maxx )
+    return msRectOverlap( &(map_extent), &(layer_extent) );
+
+  /* Uh oh, one of the rects crosses the dateline!
+  ** Let someone else handle it. */
+  return MS_UNKNOWN;
+
 #else
-    /* No proj? Naive comparison. */
-    if( msRectOverlap( &(map->extent), &(layer->extent) ) ) return MS_TRUE;
-    return MS_FALSE;
+  /* No proj? Naive comparison. */
+  if( msRectOverlap( &(map->extent), &(layer->extent) ) ) return MS_TRUE;
+  return MS_FALSE;
 #endif
 
 }
@@ -2137,27 +2186,19 @@ int msExtentsOverlap(mapObj *map, layerObj *layer)
 
 void *msSmallMalloc( size_t nSize )
 {
-    void        *pReturn;
+  void        *pReturn;
 
-    if( nSize == 0 )
-        return NULL;
+  if( nSize == 0 )
+    return NULL;
 
-    if( nSize < 0 )
-    {
-        fprintf(stderr, "msSmallMalloc(%ld): Silly size requested.\n",
-                (long) nSize );
-        return NULL;
-    }
-    
-    pReturn = malloc( nSize );
-    if( pReturn == NULL )
-    {
-        fprintf(stderr, "msSmallMalloc(): Out of memory allocating %ld bytes.\n",
-                (long) nSize );
-        exit(1);
-    }
+  pReturn = malloc( nSize );
+  if( pReturn == NULL ) {
+    msIO_fprintf(stderr, "msSmallMalloc(): Out of memory allocating %ld bytes.\n",
+                 (long) nSize );
+    exit(1);
+  }
 
-    return pReturn;
+  return pReturn;
 }
 
 /************************************************************************/
@@ -2168,28 +2209,20 @@ void *msSmallMalloc( size_t nSize )
 
 void * msSmallRealloc( void * pData, size_t nNewSize )
 {
-    void        *pReturn;
-
-    if ( nNewSize == 0 )
-        return NULL;
+  void        *pReturn;
 
-    if( nNewSize < 0 )
-    {
-        fprintf(stderr, "msSmallRealloc(%ld): Silly size requested.\n",
-                (long) nNewSize );
-        return NULL;
-    }
+  if ( nNewSize == 0 )
+    return NULL;
 
-    pReturn = realloc( pData, nNewSize );
+  pReturn = realloc( pData, nNewSize );
 
-    if( pReturn == NULL )
-    {
-        fprintf(stderr, "msSmallRealloc(): Out of memory allocating %ld bytes.\n",
-                (long)nNewSize );
-        exit(1);
-    }
+  if( pReturn == NULL ) {
+    msIO_fprintf(stderr, "msSmallRealloc(): Out of memory allocating %ld bytes.\n",
+                 (long)nNewSize );
+    exit(1);
+  }
 
-    return pReturn;
+  return pReturn;
 }
 
 /************************************************************************/
@@ -2200,20 +2233,19 @@ void * msSmallRealloc( void * pData, size_t nNewSize )
 
 void *msSmallCalloc( size_t nCount, size_t nSize )
 {
-    void  *pReturn;
+  void  *pReturn;
 
-    if( nSize * nCount == 0 )
-        return NULL;
-    
-    pReturn = calloc( nCount, nSize );
-    if( pReturn == NULL )
-    {
-        fprintf(stderr, "msSmallCalloc(): Out of memory allocating %ld bytes.\n",
-                (long)(nCount*nSize));
-        exit(1);
-    }
+  if( nSize * nCount == 0 )
+    return NULL;
+
+  pReturn = calloc( nCount, nSize );
+  if( pReturn == NULL ) {
+    msIO_fprintf(stderr, "msSmallCalloc(): Out of memory allocating %ld bytes.\n",
+                 (long)(nCount*nSize));
+    exit(1);
+  }
 
-    return pReturn;
+  return pReturn;
 }
 
 /*
@@ -2228,63 +2260,55 @@ void *msSmallCalloc( size_t nCount, size_t nSize )
 */
 char *msBuildOnlineResource(mapObj *map, cgiRequestObj *req)
 {
-    char *online_resource = NULL;
-    const char *value, *hostname, *port, *script, *protocol="http", *mapparam=NULL;
-    int mapparam_len = 0;
-
-    hostname = getenv("SERVER_NAME");
-    port = getenv("SERVER_PORT");
-    script = getenv("SCRIPT_NAME");
-
-    /* HTTPS is set by Apache to "on" in an HTTPS server ... if not set */
-    /* then check SERVER_PORT: 443 is the default https port. */
-    if ( ((value=getenv("HTTPS")) && strcasecmp(value, "on") == 0) ||
-	 ((value=getenv("SERVER_PORT")) && atoi(value) == 443) )
-    {
-        protocol = "https";
-    }
+  char *online_resource = NULL;
+  const char *value, *hostname, *port, *script, *protocol="http", *mapparam=NULL;
+  int mapparam_len = 0;
+
+  hostname = getenv("SERVER_NAME");
+  port = getenv("SERVER_PORT");
+  script = getenv("SCRIPT_NAME");
+
+  /* HTTPS is set by Apache to "on" in an HTTPS server ... if not set */
+  /* then check SERVER_PORT: 443 is the default https port. */
+  if ( ((value=getenv("HTTPS")) && strcasecmp(value, "on") == 0) ||
+       ((value=getenv("SERVER_PORT")) && atoi(value) == 443) ) {
+    protocol = "https";
+  }
 
-    /* If map=.. was explicitly set then we'll include it in onlineresource
-     */
-    if (req->type == MS_GET_REQUEST)
-    {
-        int i;
-        for(i=0; i<req->NumParams; i++)
-        {
-            if (strcasecmp(req->ParamNames[i], "map") == 0)
-            {
-                mapparam = req->ParamValues[i];
-                mapparam_len = strlen(mapparam)+5; /* +5 for "map="+"&" */
-                break;
-            }
-        }
+  /* If map=.. was explicitly set then we'll include it in onlineresource
+   */
+  if (req->type == MS_GET_REQUEST) {
+    int i;
+    for(i=0; i<req->NumParams; i++) {
+      if (strcasecmp(req->ParamNames[i], "map") == 0) {
+        mapparam = req->ParamValues[i];
+        mapparam_len = strlen(mapparam)+5; /* +5 for "map="+"&" */
+        break;
+      }
     }
+  }
 
-    if (hostname && port && script) 
-    {
-        size_t buffer_size;
-        buffer_size = strlen(hostname)+strlen(port)+strlen(script)+mapparam_len+10;
-        online_resource = (char*)msSmallMalloc(buffer_size);
-        if ((atoi(port) == 80 && strcmp(protocol, "http") == 0) ||
-            (atoi(port) == 443 && strcmp(protocol, "https") == 0) )
-          snprintf(online_resource, buffer_size, "%s://%s%s?", protocol, hostname, script);
-        else
-          snprintf(online_resource, buffer_size, "%s://%s:%s%s?", protocol, hostname, port, script);
-
-        if (mapparam)
-        {
-            int baselen;
-            baselen = strlen(online_resource);
-            snprintf(online_resource+baselen, buffer_size-baselen, "map=%s&", mapparam);
-        }
-    }
-    else 
-    {
-        msSetError(MS_CGIERR, "Impossible to establish server URL.", "msBuildOnlineResource()");
-        return NULL;
+  if (hostname && port && script) {
+    size_t buffer_size;
+    buffer_size = strlen(hostname)+strlen(port)+strlen(script)+mapparam_len+11; /* 11 comes from https://[host]:[port][scriptname]?[map]\0, i.e. "https://:?\0" */
+    online_resource = (char*)msSmallMalloc(buffer_size);
+    if ((atoi(port) == 80 && strcmp(protocol, "http") == 0) ||
+        (atoi(port) == 443 && strcmp(protocol, "https") == 0) )
+      snprintf(online_resource, buffer_size, "%s://%s%s?", protocol, hostname, script);
+    else
+      snprintf(online_resource, buffer_size, "%s://%s:%s%s?", protocol, hostname, port, script);
+
+    if (mapparam) {
+      int baselen;
+      baselen = strlen(online_resource);
+      snprintf(online_resource+baselen, buffer_size-baselen, "map=%s&", mapparam);
     }
+  } else {
+    msSetError(MS_CGIERR, "Impossible to establish server URL.", "msBuildOnlineResource()");
+    return NULL;
+  }
 
-    return online_resource;
+  return online_resource;
 }
 
 
@@ -2295,10 +2319,55 @@ char *msBuildOnlineResource(mapObj *map, cgiRequestObj *req)
 /* Check if a integer is in a array */
 int msIntegerInArray(const int value, int *array, int numelements)
 {
-    int i;
-    for (i=0;i<numelements;++i) {
-        if (value == array[i])
-            return MS_TRUE;
+  int i;
+  for (i=0; i<numelements; ++i) {
+    if (value == array[i])
+      return MS_TRUE;
+  }
+  return MS_FALSE;
+}
+
+
+/************************************************************************
+ *                            msMapSetProjections                       *
+ *                                                                      *
+ *   Ensure that all the layers in the map file have a projection       *
+ *   by copying the map-level projection to all layers than have no     *
+ *   projection.                                                        *
+ ************************************************************************/
+
+int msMapSetLayerProjections(mapObj* map)
+{
+
+  char *mapProjStr = NULL;
+  int i;
+
+  if (map->projection.numargs <= 0) {
+    msSetError(MS_WMSERR, "Cannot set new SRS on a map that doesn't "
+               "have any projection set. Please make sure your mapfile "
+               "has a PROJECTION defined at the top level.",
+               "msTileSetProjectionst()");
+    return(MS_FAILURE);
+  }
+
+  for(i=0; i<map->numlayers; i++) {
+    /* This layer is turned on and needs a projection? */
+    if (GET_LAYER(map, i)->projection.numargs <= 0 &&
+        GET_LAYER(map, i)->status != MS_OFF &&
+        GET_LAYER(map, i)->transform == MS_TRUE) {
+
+      /* Fetch main map projection string only now that we need it */
+      if (mapProjStr == NULL)
+        mapProjStr = msGetProjectionString(&(map->projection));
+
+      /* Set the projection to the map file projection */
+      if (msLoadProjectionString(&(GET_LAYER(map, i)->projection), mapProjStr) != 0) {
+        msSetError(MS_CGIERR, "Unable to set projection on layer.", "msTileSetProjectionst()");
+        return(MS_FAILURE);
+      }
+      GET_LAYER(map, i)->project = MS_TRUE;
     }
-    return MS_FALSE;
+  }
+  msFree(mapProjStr);
+  return(MS_SUCCESS);
 }
diff --git a/mapuvraster.c b/mapuvraster.c
new file mode 100644
index 0000000..6f6a04d
--- /dev/null
+++ b/mapuvraster.c
@@ -0,0 +1,746 @@
+/**********************************************************************
+ * $Id: mapuv.c 12629 2011-10-06 18:06:34Z aboudreault $
+ *
+ * Project:  MapServer
+ * Purpose:  UV Layer
+ * Author:   Alan Boudreault (aboudreault at mapgears.com)
+ *
+ **********************************************************************
+ * Copyright (c) 2011, Alan Boudreault, MapGears
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies of this Software or works derived from this Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ **********************************************************************/
+
+#include "mapserver.h"
+#ifdef USE_GDAL
+
+#include <assert.h>
+#include <math.h>
+#include "mapresample.h"
+#include "mapthread.h"
+
+#define MSUVRASTER_NUMITEMS        6
+#define MSUVRASTER_ANGLE    "uv_angle"
+#define MSUVRASTER_ANGLEINDEX   -100
+#define MSUVRASTER_MINUS_ANGLE    "uv_minus_angle"
+#define MSUVRASTER_MINUSANGLEINDEX   -101
+#define MSUVRASTER_LENGTH    "uv_length"
+#define MSUVRASTER_LENGTHINDEX   -102
+#define MSUVRASTER_LENGTH_2    "uv_length_2"
+#define MSUVRASTER_LENGTH2INDEX   -103
+#define MSUVRASTER_U    "u"
+#define MSUVRASTER_UINDEX   -104
+#define MSUVRASTER_V    "v"
+#define MSUVRASTER_VINDEX   -105
+
+#define RQM_UNKNOWN               0
+#define RQM_ENTRY_PER_PIXEL       1
+#define RQM_HIST_ON_CLASS         2
+#define RQM_HIST_ON_VALUE         3
+
+typedef struct {
+
+  /* query cache results */
+  int query_results;
+  /* int query_alloc_max;
+  int query_request_max;
+  int query_result_hard_max;
+  int raster_query_mode; */
+  int band_count;
+
+  int refcount;
+
+  /* query bound in force
+     shapeObj *searchshape;*/
+
+  /* Only nearest result to this point.
+  int      range_mode; MS_QUERY_SINGLE, MS_QUERY_MULTIPLE or -1 (skip test)
+  double   range_dist;
+  pointObj target_point;*/
+
+  /* double   shape_tolerance; */
+
+  float **u; /* u values */
+  float **v; /* v values */
+  int width;
+  int height;
+  rectObj extent;
+  int     next_shape;
+  int x, y; /* used internally in msUVRasterLayerNextShape() */
+
+} uvRasterLayerInfo;
+
+static int msUVRASTERLayerInitItemInfo(layerObj *layer)
+{
+  uvRasterLayerInfo *uvlinfo = (uvRasterLayerInfo *) layer->layerinfo;
+  int   i;
+  int *itemindexes;
+
+  if (layer->numitems == 0)
+    return MS_SUCCESS;
+
+  if( uvlinfo == NULL ) {
+    msSetError(MS_MISCERR, "Assertion failed: GDAL layer not opened!!!",
+               "msUVRASTERLayerInitItemInfo()");
+    return(MS_FAILURE);
+  }
+
+  if (layer->iteminfo)
+    free(layer->iteminfo);
+
+  if((layer->iteminfo = (int *)malloc(sizeof(int)*layer->numitems))== NULL) {
+    msSetError(MS_MEMERR, NULL, "msUVRASTERLayerInitItemInfo()");
+    return(MS_FAILURE);
+  }
+
+  itemindexes = (int*)layer->iteminfo;
+  for(i=0; i<layer->numitems; i++) {
+    /* Special case for handling text string and angle coming from */
+    /* OGR style strings.  We use special attribute snames. */
+    if (EQUAL(layer->items[i], MSUVRASTER_ANGLE))
+      itemindexes[i] = MSUVRASTER_ANGLEINDEX;
+    if (EQUAL(layer->items[i], MSUVRASTER_MINUS_ANGLE))
+      itemindexes[i] = MSUVRASTER_MINUSANGLEINDEX;
+    else if (EQUAL(layer->items[i], MSUVRASTER_LENGTH))
+      itemindexes[i] = MSUVRASTER_LENGTHINDEX;
+    else if (EQUAL(layer->items[i], MSUVRASTER_LENGTH_2))
+      itemindexes[i] = MSUVRASTER_LENGTH2INDEX;
+    else if (EQUAL(layer->items[i], MSUVRASTER_U))
+      itemindexes[i] = MSUVRASTER_UINDEX;
+    else if (EQUAL(layer->items[i], MSUVRASTER_V))
+      itemindexes[i] = MSUVRASTER_VINDEX;
+
+    if(itemindexes[i] == -1) {
+      msSetError(MS_OGRERR,
+                 (char*)CPLSPrintf("Invalid Field name: %s",
+                                   layer->items[i]),
+                 "msUVRASTERLayerInitItemInfo()");
+      return(MS_FAILURE);
+    }
+  }
+
+  return(MS_SUCCESS);
+}
+
+
+void msUVRASTERLayerFreeItemInfo(layerObj *layer)
+{
+  if (layer->iteminfo)
+    free(layer->iteminfo);
+  layer->iteminfo = NULL;
+}
+
+static void msUVRasterLayerInfoInitialize(layerObj *layer)
+{
+  uvRasterLayerInfo *uvlinfo = (uvRasterLayerInfo *) layer->layerinfo;
+
+  if( uvlinfo != NULL )
+    return;
+
+  uvlinfo = (uvRasterLayerInfo *) msSmallCalloc(1,sizeof(uvRasterLayerInfo));
+  layer->layerinfo = uvlinfo;
+
+  uvlinfo->band_count = -1;
+  /* uvlinfo->raster_query_mode = RQM_ENTRY_PER_PIXEL; */
+  /* uvlinfo->range_mode = -1; /\* inactive *\/ */
+  /* uvlinfo->refcount = 0; */
+  /* uvlinfo->shape_tolerance = 0.0; */
+  uvlinfo->u = NULL;
+  uvlinfo->v = NULL;
+  uvlinfo->width = 0;
+  uvlinfo->height = 0;
+
+  /* uvlinfo->query_result_hard_max = 1000000; */
+
+  /* if( CSLFetchNameValue( layer->processing, "RASTER_QUERY_MAX_RESULT" )  */
+  /*     != NULL ) */
+  /* { */
+  /*     uvlinfo->query_result_hard_max =  */
+  /*         atoi(CSLFetchNameValue( layer->processing, "RASTER_QUERY_MAX_RESULT" )); */
+  /* } */
+}
+
+static void msUVRasterLayerInfoFree( layerObj *layer )
+
+{
+  uvRasterLayerInfo *uvlinfo = (uvRasterLayerInfo *) layer->layerinfo;
+  int i;
+
+  if( uvlinfo == NULL )
+    return;
+
+  if (uvlinfo->u) {
+    for (i=0; i<uvlinfo->width; ++i) {
+      free(uvlinfo->u[i]);
+    }
+    free(uvlinfo->u);
+  }
+
+  if (uvlinfo->v) {
+    for (i=0; i<uvlinfo->width; ++i) {
+      free(uvlinfo->v[i]);
+    }
+    free(uvlinfo->v);
+  }
+
+  free( uvlinfo );
+
+  layer->layerinfo = NULL;
+}
+
+int msUVRASTERLayerOpen(layerObj *layer)
+{
+  uvRasterLayerInfo *uvlinfo;
+
+  /* If we don't have info, initialize an empty one now */
+  if( layer->layerinfo == NULL )
+    msUVRasterLayerInfoInitialize( layer );
+
+  uvlinfo = (uvRasterLayerInfo *) layer->layerinfo;
+
+  uvlinfo->refcount = uvlinfo->refcount + 1;
+
+  return MS_SUCCESS;
+}
+
+int msUVRASTERLayerIsOpen(layerObj *layer)
+{
+  if (layer->layerinfo)
+    return MS_TRUE;
+  return MS_FALSE;
+}
+
+
+int msUVRASTERLayerClose(layerObj *layer)
+{
+  uvRasterLayerInfo *uvlinfo = (uvRasterLayerInfo *) layer->layerinfo;
+
+  if( uvlinfo != NULL ) {
+    uvlinfo->refcount--;
+
+    if( uvlinfo->refcount < 0 )
+      msUVRasterLayerInfoFree( layer );
+  }
+  return MS_SUCCESS;
+}
+
+int msUVRASTERLayerGetItems(layerObj *layer)
+{
+  uvRasterLayerInfo *uvlinfo = (uvRasterLayerInfo *) layer->layerinfo;
+
+  if( uvlinfo == NULL )
+    return MS_FAILURE;
+
+  layer->numitems = 0;
+  layer->items = (char **) msSmallCalloc(sizeof(char *),10);;
+
+  layer->items[layer->numitems++] = msStrdup(MSUVRASTER_ANGLE);
+  layer->items[layer->numitems++] = msStrdup(MSUVRASTER_MINUS_ANGLE);
+  layer->items[layer->numitems++] = msStrdup(MSUVRASTER_LENGTH);
+  layer->items[layer->numitems++] = msStrdup(MSUVRASTER_LENGTH_2);
+  layer->items[layer->numitems++] = msStrdup(MSUVRASTER_U);
+  layer->items[layer->numitems++] = msStrdup(MSUVRASTER_V);
+  layer->items[layer->numitems] = NULL;
+
+  return msUVRASTERLayerInitItemInfo(layer);
+}
+
+/**********************************************************************
+ *                     msUVRASTERGetValues()
+ *
+ * Special attribute names are used to return some UV params: uv_angle,
+ * uv_length, u and v.
+ **********************************************************************/
+static char **msUVRASTERGetValues(layerObj *layer, float *u, float *v)
+{
+  char **values;
+  int i = 0;
+  char tmp[100];
+  float size_scale;
+  int *itemindexes = (int*)layer->iteminfo;
+
+  if(layer->numitems == 0)
+    return(NULL);
+
+  if(!layer->iteminfo)  /* Should not happen... but just in case! */
+    if (msUVRASTERLayerInitItemInfo(layer) != MS_SUCCESS)
+      return NULL;
+
+  if((values = (char **)malloc(sizeof(char *)*layer->numitems)) == NULL) {
+    msSetError(MS_MEMERR, NULL, "msUVRASTERGetValues()");
+    return(NULL);
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*    Determine desired size_scale.  Default to 1 if not otherwise set  */
+  /* -------------------------------------------------------------------- */
+  size_scale = 1;
+  if( CSLFetchNameValue( layer->processing, "UV_SIZE_SCALE" ) != NULL ) {
+    size_scale =
+      atof(CSLFetchNameValue( layer->processing, "UV_SIZE_SCALE" ));
+  }
+
+  for(i=0; i<layer->numitems; i++) {
+    if (itemindexes[i] == MSUVRASTER_ANGLEINDEX) {
+      snprintf(tmp, 100, "%f", (atan2((double)*v, (double)*u) * 180 / MS_PI));
+      values[i] = msStrdup(tmp);
+    } else if (itemindexes[i] == MSUVRASTER_MINUSANGLEINDEX) {
+      double minus_angle;
+      minus_angle = (atan2((double)*v, (double)*u) * 180 / MS_PI)+180;
+      if (minus_angle >= 360)
+        minus_angle -= 360;
+      snprintf(tmp, 100, "%f", minus_angle);
+      values[i] = msStrdup(tmp);
+    } else if ( (itemindexes[i] == MSUVRASTER_LENGTHINDEX) ||
+                (itemindexes[i] == MSUVRASTER_LENGTH2INDEX) ) {
+      float length = sqrt((*u**u)+(*v**v))*size_scale;
+
+      if (itemindexes[i] == MSUVRASTER_LENGTHINDEX)
+        snprintf(tmp, 100, "%f", length);
+      else
+        snprintf(tmp, 100, "%f", length/2);
+
+      values[i] = msStrdup(tmp);
+    } else if (itemindexes[i] == MSUVRASTER_UINDEX) {
+      snprintf(tmp, 100, "%f",*u);
+      values[i] = msStrdup(tmp);
+    } else if (itemindexes[i] == MSUVRASTER_VINDEX) {
+      snprintf(tmp, 100, "%f",*v);
+      values[i] = msStrdup(tmp);
+    }
+  }
+
+  return values;
+}
+
+int msUVRASTERLayerWhichShapes(layerObj *layer, rectObj rect, int isQuery)
+{
+  uvRasterLayerInfo *uvlinfo = (uvRasterLayerInfo *) layer->layerinfo;
+  imageObj *image_tmp;
+  mapObj   map_tmp;
+  double map_cellsize;
+  unsigned int spacing;
+  int width, height, u_src_off, v_src_off, i, x, y;
+  char   **alteredProcessing = NULL;
+  char **savedProcessing = NULL;
+
+  if (layer->debug)
+    msDebug("Entering msUVRASTERLayerWhichShapes().\n");
+
+  if( uvlinfo == NULL )
+    return MS_FAILURE;
+
+  /* QUERY NOT SUPPORTED YET */
+  if (isQuery == MS_TRUE) {
+    msSetError( MS_MISCERR, "Query is not supported for UV layer.", "msUVRASTERLayerWhichShapes()" );
+    return MS_FAILURE;
+  }
+
+
+  if( CSLFetchNameValue( layer->processing, "BANDS" ) == NULL ) {
+    msSetError( MS_MISCERR, "BANDS processing option is required for UV layer. You have to specified 2 bands.",
+                "msUVRASTERLayerWhichShapes()" );
+    return MS_FAILURE;
+  }
+  /* -------------------------------------------------------------------- */
+  /*      Determine desired spacing.  Default to 32 if not otherwise set  */
+  /* -------------------------------------------------------------------- */
+  spacing = 32;
+  if( CSLFetchNameValue( layer->processing, "UV_SPACING" ) != NULL ) {
+    spacing =
+      atoi(CSLFetchNameValue( layer->processing, "UV_SPACING" ));
+  }
+
+  width = (int)ceil(layer->map->width/spacing);
+  height = (int)ceil(layer->map->height/spacing);
+  map_cellsize = MS_MAX(MS_CELLSIZE(rect.minx, rect.maxx,layer->map->width),
+                        MS_CELLSIZE(rect.miny,rect.maxy,layer->map->height));
+  map_tmp.cellsize = map_cellsize*spacing;
+  
+  if (layer->debug)
+    msDebug("msUVRASTERLayerWhichShapes(): width: %d, height: %d, cellsize: %g\n",
+            width, height, map_tmp.cellsize);
+
+  /* Initialize our dummy map */
+  MS_INIT_COLOR(map_tmp.imagecolor, 255,255,255,255);
+  map_tmp.resolution = layer->map->resolution;
+  map_tmp.defresolution = layer->map->defresolution;
+  map_tmp.outputformat = (outputFormatObj *) msSmallCalloc(1,sizeof(outputFormatObj));
+  uvlinfo->band_count = map_tmp.outputformat->bands = 2;
+  map_tmp.outputformat->name = NULL;
+  map_tmp.outputformat->driver = NULL;
+  map_tmp.outputformat->refcount = 0;
+  map_tmp.outputformat->vtable = NULL;
+  map_tmp.outputformat->device = NULL;
+  map_tmp.outputformat->renderer = MS_RENDER_WITH_RAWDATA;
+  map_tmp.outputformat->imagemode = MS_IMAGEMODE_FLOAT32;
+
+  map_tmp.configoptions = layer->map->configoptions;
+  map_tmp.mappath = layer->map->mappath;
+  map_tmp.shapepath = layer->map->shapepath;
+  map_tmp.extent.minx = rect.minx-(0.5*map_cellsize)+(0.5*map_tmp.cellsize);
+  map_tmp.extent.miny = rect.miny-(0.5*map_cellsize)+(0.5*map_tmp.cellsize);
+  map_tmp.extent.maxx = map_tmp.extent.minx+((width-1)*map_tmp.cellsize);
+  map_tmp.extent.maxy = map_tmp.extent.miny+((height-1)*map_tmp.cellsize);
+  map_tmp.gt.rotation_angle = 0.0;
+
+  msInitProjection(&map_tmp.projection);
+  msCopyProjection(&map_tmp.projection, &layer->projection);
+
+  if (layer->debug == 5)
+    msDebug("msUVRASTERLayerWhichShapes(): extent: %g %d %g %g\n",
+            map_tmp.extent.minx, map_tmp.extent.miny,
+            map_tmp.extent.maxx, map_tmp.extent.maxy);
+
+  /* important to use that function, to compute map
+     geotransform, used by the resampling*/
+  msMapSetSize(&map_tmp, width, height);
+
+  if (layer->debug == 5)
+    msDebug("msUVRASTERLayerWhichShapes(): geotransform: %g %g %g %g %g %g\n",
+            map_tmp.gt.geotransform[0], map_tmp.gt.geotransform[1],
+            map_tmp.gt.geotransform[2], map_tmp.gt.geotransform[3],
+            map_tmp.gt.geotransform[4], map_tmp.gt.geotransform[5]);
+
+  uvlinfo->extent = map_tmp.extent;
+
+  image_tmp = msImageCreate(width, height, map_tmp.outputformat,
+                            NULL, NULL, map_tmp.resolution, map_tmp.defresolution,
+                            &(map_tmp.imagecolor));
+
+  /* Default set to AVERAGE resampling */
+  if( CSLFetchNameValue( layer->processing, "RESAMPLE" ) == NULL ) {
+    alteredProcessing = CSLDuplicate( layer->processing );
+    alteredProcessing =
+      CSLSetNameValue( alteredProcessing, "RESAMPLE",
+                       "AVERAGE");
+    savedProcessing = layer->processing;
+    layer->processing = alteredProcessing;
+  }
+
+  if (msDrawRasterLayerLow(&map_tmp, layer, image_tmp, NULL ) == MS_FAILURE) {
+    msSetError(MS_MISCERR, "Unable to draw raster data.", NULL, "msUVRASTERLayerWhichShapes()" );
+    return MS_FAILURE;
+  }
+
+  /* restore the saved processing */
+  if (alteredProcessing != NULL)
+    layer->processing = savedProcessing;
+
+  /* free old query arrays */
+  if (uvlinfo->u) {
+    for (i=0; i<uvlinfo->width; ++i) {
+      free(uvlinfo->u[i]);
+    }
+    free(uvlinfo->u);
+  }
+
+  if (uvlinfo->v) {
+    for (i=0; i<uvlinfo->height; ++i) {
+      free(uvlinfo->v[i]);
+    }
+    free(uvlinfo->v);
+  }
+
+  /* Update our uv layer structure */
+  uvlinfo->width = width;
+  uvlinfo->height = height;
+  uvlinfo->query_results = width*height;
+
+  uvlinfo->u = (float **)msSmallMalloc(sizeof(float *)*width);
+  uvlinfo->v = (float **)msSmallMalloc(sizeof(float *)*width);
+
+  for (x = 0; x < width; ++x) {
+    uvlinfo->u[x] = (float *)msSmallMalloc(height * sizeof(float));
+    uvlinfo->v[x] = (float *)msSmallMalloc(height * sizeof(float));
+
+    for (y = 0; y < height; ++y) {
+      u_src_off = v_src_off = x + y * width;
+      v_src_off += width*height;
+
+      uvlinfo->u[x][y] = image_tmp->img.raw_float[u_src_off];
+      uvlinfo->v[x][y] = image_tmp->img.raw_float[v_src_off];
+
+      /* null vector? update the number of results  */
+      if (uvlinfo->u[x][y] == 0 && uvlinfo->v[x][y] == 0)
+        --uvlinfo->query_results;
+    }
+  }
+
+  msFreeImage(image_tmp); /* we do not need the imageObj anymore */
+
+  uvlinfo->next_shape = 0;
+
+  return MS_SUCCESS;
+}
+
+int msUVRASTERLayerGetShape(layerObj *layer, shapeObj *shape, resultObj *record)
+{
+  uvRasterLayerInfo *uvlinfo = (uvRasterLayerInfo *) layer->layerinfo;
+  lineObj line ;
+  pointObj point;
+  int i, j, k, x=0, y=0;
+  long shapeindex = record->shapeindex;
+
+  msFreeShape(shape);
+  shape->type = MS_SHAPE_NULL;
+
+  if( shapeindex < 0 || shapeindex >= uvlinfo->query_results ) {
+    msSetError(MS_MISCERR,
+               "Out of range shape index requested.  Requested %d\n"
+               "but only %d shapes available.",
+               "msUVRASTERLayerGetShape()",
+               shapeindex, uvlinfo->query_results );
+    return MS_FAILURE;
+  }
+
+  /* loop to the next non null vector */
+  k = 0;
+  for (i=0, x=-1; i<uvlinfo->width && k<=shapeindex; ++i, ++x) {
+    for (j=0, y=-1; j<uvlinfo->height && k<=shapeindex; ++j, ++k, ++y) {
+      if (uvlinfo->u[i][j] == 0 && uvlinfo->v[i][j] == 0)
+        --k;
+    }
+  }
+
+  point.x = Pix2Georef(x, 0, uvlinfo->width-1,
+                       uvlinfo->extent.minx, uvlinfo->extent.maxx, MS_FALSE);
+  point.y = Pix2Georef(y, 0, uvlinfo->height-1,
+                       uvlinfo->extent.miny, uvlinfo->extent.maxy, MS_TRUE);
+  if (layer->debug == 5)
+    msDebug("msUVRASTERLayerWhichShapes(): shapeindex: %d, x: %g, y: %g\n",
+            shapeindex, point.x, point.y);
+
+#ifdef USE_POINT_Z_M
+  point.m = 0.0;
+#endif
+
+  shape->type = MS_SHAPE_POINT;
+  line.numpoints = 1;
+  line.point = &point;
+  msAddLine( shape, &line );
+  msComputeBounds( shape );
+
+  shape->numvalues = layer->numitems;
+  shape->values = msUVRASTERGetValues(layer, &uvlinfo->u[x][y], &uvlinfo->v[x][y]);
+
+  return MS_SUCCESS;
+
+}
+
+int msUVRASTERLayerNextShape(layerObj *layer, shapeObj *shape)
+{
+  uvRasterLayerInfo *uvlinfo = (uvRasterLayerInfo *) layer->layerinfo;
+
+  if( uvlinfo->next_shape < 0
+      || uvlinfo->next_shape >= uvlinfo->query_results ) {
+    msFreeShape(shape);
+    shape->type = MS_SHAPE_NULL;
+    return MS_DONE;
+  } else {
+    resultObj record;
+
+    record.shapeindex = uvlinfo->next_shape++;
+    record.tileindex = 0;
+    record.classindex = record.resultindex = -1;
+
+    return msUVRASTERLayerGetShape( layer, shape, &record);
+  }
+}
+
+/************************************************************************/
+/*                       msUVRASTERLayerGetExtent()                     */
+/* Simple copy of the maprasterquery.c file. might change in the future */
+/************************************************************************/
+
+int msUVRASTERLayerGetExtent(layerObj *layer, rectObj *extent)
+
+{
+  char szPath[MS_MAXPATHLEN];
+  mapObj *map = layer->map;
+  double adfGeoTransform[6];
+  int nXSize, nYSize;
+  GDALDatasetH hDS;
+  shapefileObj *tileshpfile;
+  int tilelayerindex = -1;
+  CPLErr eErr = CE_Failure;
+  char *decrypted_path;
+
+  if( (!layer->data || strlen(layer->data) == 0)
+      && layer->tileindex == NULL) {
+    /* should we be issuing a specific error about not supporting
+       extents for tileindexed raster layers? */
+    return MS_FAILURE;
+  }
+
+  if( map == NULL )
+    return MS_FAILURE;
+
+  /* If the layer use a tileindex, return the extent of the tileindex shapefile/referenced layer */
+  if (layer->tileindex) {
+    tilelayerindex = msGetLayerIndex(map, layer->tileindex);
+    if(tilelayerindex != -1) /* does the tileindex reference another layer */
+      return msLayerGetExtent(GET_LAYER(map, tilelayerindex), extent);
+    else {
+      tileshpfile = (shapefileObj *) malloc(sizeof(shapefileObj));
+      MS_CHECK_ALLOC(tileshpfile, sizeof(shapefileObj), MS_FAILURE);
+
+      if(msShapefileOpen(tileshpfile, "rb", msBuildPath3(szPath, map->mappath, map->shapepath, layer->tileindex), MS_TRUE) == -1)
+        if(msShapefileOpen(tileshpfile, "rb", msBuildPath(szPath, map->mappath, layer->tileindex), MS_TRUE) == -1)
+          return MS_FAILURE;
+
+      *extent = tileshpfile->bounds;
+      msShapefileClose(tileshpfile);
+      free(tileshpfile);
+      return MS_SUCCESS;
+    }
+  }
+
+  msTryBuildPath3(szPath, map->mappath, map->shapepath, layer->data);
+  decrypted_path = msDecryptStringTokens( map, szPath );
+
+  msAcquireLock( TLOCK_GDAL );
+  if( decrypted_path ) {
+    hDS = GDALOpen(decrypted_path, GA_ReadOnly );
+    msFree( decrypted_path );
+  } else
+    hDS = NULL;
+
+  if( hDS != NULL ) {
+    nXSize = GDALGetRasterXSize( hDS );
+    nYSize = GDALGetRasterYSize( hDS );
+    eErr = GDALGetGeoTransform( hDS, adfGeoTransform );
+
+    GDALClose( hDS );
+  }
+
+  msReleaseLock( TLOCK_GDAL );
+
+  if( hDS == NULL || eErr != CE_None ) {
+    return MS_FAILURE;
+  }
+
+  /* If this appears to be an ungeoreferenced raster than flip it for
+     mapservers purposes. */
+  if( adfGeoTransform[5] == 1.0 && adfGeoTransform[3] == 0.0 ) {
+    adfGeoTransform[5] = -1.0;
+    adfGeoTransform[3] = nYSize;
+  }
+
+  extent->minx = adfGeoTransform[0];
+  extent->maxy = adfGeoTransform[3];
+
+  extent->maxx = adfGeoTransform[0] + nXSize * adfGeoTransform[1];
+  extent->miny = adfGeoTransform[3] + nYSize * adfGeoTransform[5];
+
+  return MS_SUCCESS;
+}
+
+
+/************************************************************************/
+/*                     msUVRASTERLayerSetTimeFilter()                   */
+/*                                                                      */
+/*      This function is actually just used in the context of           */
+/*      setting a filter on the tileindex for time based queries.       */
+/*      For instance via WMS requests.  So it isn't really related      */
+/*      to the "raster query" support at all.                           */
+/*                                                                      */
+/*      If a local shapefile tileindex is in use, we will set a         */
+/*      backtics filter (shapefile compatible).  If another layer is    */
+/*      being used as the tileindex then we will forward the            */
+/*      SetTimeFilter call to it.  If there is no tileindex in          */
+/*      place, we do nothing.                                           */
+/************************************************************************/
+
+int msUVRASTERLayerSetTimeFilter(layerObj *layer, const char *timestring,
+                                 const char *timefield)
+{
+  int tilelayerindex;
+
+  /* -------------------------------------------------------------------- */
+  /*      If we don't have a tileindex the time filter has no effect.     */
+  /* -------------------------------------------------------------------- */
+  if( layer->tileindex == NULL )
+    return MS_SUCCESS;
+
+  /* -------------------------------------------------------------------- */
+  /*      Find the tileindex layer.                                       */
+  /* -------------------------------------------------------------------- */
+  tilelayerindex = msGetLayerIndex(layer->map, layer->tileindex);
+
+  /* -------------------------------------------------------------------- */
+  /*      If we are using a local shapefile as our tileindex (that is     */
+  /*      to say, the tileindex name is not of another layer), then we    */
+  /*      just install a backtics style filter on the raster layer.       */
+  /*      This is propogated to the "working layer" created for the       */
+  /*      tileindex by code in mapraster.c.                               */
+  /* -------------------------------------------------------------------- */
+  if( tilelayerindex == -1 )
+    return msLayerMakeBackticsTimeFilter( layer, timestring, timefield );
+
+  /* -------------------------------------------------------------------- */
+  /*      Otherwise we invoke the tileindex layers SetTimeFilter          */
+  /*      method.                                                         */
+  /* -------------------------------------------------------------------- */
+  if ( msCheckParentPointer(layer->map,"map")==MS_FAILURE )
+    return MS_FAILURE;
+  return msLayerSetTimeFilter( layer->GET_LAYER(map,tilelayerindex),
+                               timestring, timefield );
+}
+
+
+/************************************************************************/
+/*                msRASTERLayerInitializeVirtualTable()                 */
+/************************************************************************/
+
+int
+msUVRASTERLayerInitializeVirtualTable(layerObj *layer)
+{
+  assert(layer != NULL);
+  assert(layer->vtable != NULL);
+
+  layer->vtable->LayerInitItemInfo = msUVRASTERLayerInitItemInfo;
+  layer->vtable->LayerFreeItemInfo = msUVRASTERLayerFreeItemInfo;
+  layer->vtable->LayerOpen = msUVRASTERLayerOpen;
+  layer->vtable->LayerIsOpen = msUVRASTERLayerIsOpen;
+  layer->vtable->LayerWhichShapes = msUVRASTERLayerWhichShapes;
+  layer->vtable->LayerNextShape = msUVRASTERLayerNextShape;
+  layer->vtable->LayerGetShape = msUVRASTERLayerGetShape;
+  layer->vtable->LayerClose = msUVRASTERLayerClose;
+  layer->vtable->LayerGetItems = msUVRASTERLayerGetItems;
+  layer->vtable->LayerGetExtent = msUVRASTERLayerGetExtent;
+  /* layer->vtable->LayerGetAutoStyle, use default */
+  /* layer->vtable->LayerApplyFilterToLayer, use default */
+  /* layer->vtable->LayerCloseConnection = msUVRASTERLayerClose; */
+  /* we use backtics for proper tileindex shapefile functioning */
+  layer->vtable->LayerSetTimeFilter = msUVRASTERLayerSetTimeFilter;
+  /* layer->vtable->LayerCreateItems, use default */
+  /* layer->vtable->LayerGetNumFeatures, use default */
+
+  return MS_SUCCESS;
+}
+
+#else
+int msUVRASTERLayerInitializeVirtualTable(layerObj *layer)
+{
+  msSetError(MS_MISCERR, "UVRaster Layer needs GDAL support, but it it not compiled in", "msUVRASTERLayerInitializeVirtualTable()");
+  return MS_FAILURE;
+}
+#endif
+
diff --git a/mapwcs.c b/mapwcs.c
index a173997..ceacabf 100644
--- a/mapwcs.c
+++ b/mapwcs.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -32,9 +32,9 @@
 #include "mapthread.h"
 #include <assert.h>
 
-MS_CVSID("$Id$")
 
-#ifdef USE_WCS_SVR
+
+#if defined(USE_WCS_SVR)
 
 #include "mapwcs.h"
 
@@ -47,58 +47,59 @@ MS_CVSID("$Id$")
 /************************************************************************/
 /*                    msWCSValidateRangeSetParam()                      */
 /************************************************************************/
-static int msWCSValidateRangeSetParam(layerObj *lp, char *name, const char *value) {
-    char **allowed_ri_values;
-    char **client_ri_values;
-    int  allowed_count, client_count;
-    int  i_client, i, all_match = 1;
-    char *tmpname = NULL;
-    const char *ri_values_list;
-
-    if( name == NULL )
-        return MS_FAILURE;
+static int msWCSValidateRangeSetParam(layerObj *lp, char *name, const char *value)
+{
+  char **allowed_ri_values;
+  char **client_ri_values;
+  int  allowed_count, client_count;
+  int  i_client, i, all_match = 1;
+  char *tmpname = NULL;
+  const char *ri_values_list;
+
+  if( name == NULL )
+    return MS_FAILURE;
 
-    /* Fetch the available values list for the rangeset item and tokenize */
-    tmpname = (char *)msSmallMalloc(sizeof(char)*strlen(name) + 10);
-    sprintf(tmpname,"%s_values", name);
-    ri_values_list = msOWSLookupMetadata(&(lp->metadata), "CO", tmpname);
-    msFree( tmpname );
-    
-    if (ri_values_list == NULL) 
-        return MS_FAILURE;
+  /* Fetch the available values list for the rangeset item and tokenize */
+  tmpname = (char *)msSmallMalloc(sizeof(char)*strlen(name) + 10);
+  sprintf(tmpname,"%s_values", name);
+  ri_values_list = msOWSLookupMetadata(&(lp->metadata), "CO", tmpname);
+  msFree( tmpname );
 
-    allowed_ri_values = msStringSplit( ri_values_list, ',', &allowed_count);
+  if (ri_values_list == NULL)
+    return MS_FAILURE;
 
-    /* Parse the client value list into tokens. */
-    client_ri_values = msStringSplit( value, ',', &client_count );
-    
-    /* test each client value against the allowed list. */
+  allowed_ri_values = msStringSplit( ri_values_list, ',', &allowed_count);
 
-    for( i_client = 0; all_match && i_client < client_count; i_client++ )
-    {
-        for( i = 0; 
-             i < allowed_count
-                 && strcasecmp(client_ri_values[i_client],
-                               allowed_ri_values[i]) != 0;
-             i++ ) {}
+  /* Parse the client value list into tokens. */
+  client_ri_values = msStringSplit( value, ',', &client_count );
 
-        if( i == allowed_count )
-            all_match = 0;
-    }
+  /* test each client value against the allowed list. */
 
-    msFreeCharArray(allowed_ri_values, allowed_count );
-    msFreeCharArray(client_ri_values, client_count );
+  for( i_client = 0; all_match && i_client < client_count; i_client++ ) {
+    for( i = 0;
+         i < allowed_count
+         && strcasecmp(client_ri_values[i_client],
+                       allowed_ri_values[i]) != 0;
+         i++ ) {}
 
-    if (all_match == 0) 
-        return MS_FAILURE;
-    else
-        return MS_SUCCESS;
+    if( i == allowed_count )
+      all_match = 0;
+  }
+
+  msFreeCharArray(allowed_ri_values, allowed_count );
+  msFreeCharArray(client_ri_values, client_count );
+
+  if (all_match == 0)
+    return MS_FAILURE;
+  else
+    return MS_SUCCESS;
 }
 
 /************************************************************************/
 /*                    msWCSConvertRangeSetToString()                    */
 /************************************************************************/
-static char *msWCSConvertRangeSetToString(const char *value) {
+static char *msWCSConvertRangeSetToString(const char *value)
+{
   char **tokens;
   int numtokens;
   double min, max, res;
@@ -111,20 +112,20 @@ static char *msWCSConvertRangeSetToString(const char *value) {
       msFreeCharArray(tokens, numtokens);
       return NULL; /* not a set of equally spaced intervals */
     }
-       
+
     min = atof(tokens[0]);
     max = atof(tokens[1]);
     res = atof(tokens[2]);
     msFreeCharArray(tokens, numtokens);
-    
+
     for(val=min; val<=max; val+=res) {
       if(val == min)
-        snprintf(buf1, sizeof(buf1), "%g", val);     
+        snprintf(buf1, sizeof(buf1), "%g", val);
       else
         snprintf(buf1, sizeof(buf1), ",%g", val);
       buf2 = msStringConcatenate(buf2, buf1);
     }
-   
+
     return buf2;
   } else
     return msStrdup(value);
@@ -140,31 +141,32 @@ int msWCSException(mapObj *map, const char *code, const char *locator,
   const char *encoding;
 
   if( version == NULL )
-      version = "1.0.0";
+    version = "1.0.0";
 
 #if defined(USE_LIBXML2)
   if( msOWSParseVersionString(version) >= OWS_2_0_0 )
-      return msWCSException20( map, code, locator, version );
+    return msWCSException20( map, code, locator, version );
 #endif
 
   if( msOWSParseVersionString(version) >= OWS_1_1_0 )
-      return msWCSException11( map, code, locator, version );
+    return msWCSException11( map, code, locator, version );
 
   encoding = msOWSLookupMetadata(&(map->web.metadata), "CO", "encoding");
   if (encoding)
-      msIO_printf("Content-type: application/vnd.ogc.se_xml; charset=%s%c%c", encoding,10,10);
+    msIO_setHeader("Content-Type","application/vnd.ogc.se_xml; charset=%s", encoding);
   else
-      msIO_printf("Content-type: application/vnd.ogc.se_xml%c%c",10,10);
+    msIO_setHeader("Content-Type","application/vnd.ogc.se_xml");
+  msIO_sendHeaders();
 
-  /* msIO_printf("Content-type: text/xml%c%c",10,10); */
+  /* msIO_printf("Content-Type: text/xml%c%c",10,10); */
 
   msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), NULL, "wcs_encoding", OWS_NOERR, "<?xml version='1.0' encoding=\"%s\" ?>\n", "ISO-8859-1");
 
   msIO_printf("<ServiceExceptionReport version=\"1.2.0\"\n");
-  msIO_printf("xmlns=\"http://www.opengis.net/ogc\" "); 
-  msIO_printf("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "); 
+  msIO_printf("xmlns=\"http://www.opengis.net/ogc\" ");
+  msIO_printf("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ");
   pszEncodedVal = msEncodeHTMLEntities(msOWSGetSchemasLocation(map));
-  msIO_printf("xsi:schemaLocation=\"http://www.opengis.net/ogc %s/wcs/1.0.0/OGC-exception.xsd\">\n", 
+  msIO_printf("xsi:schemaLocation=\"http://www.opengis.net/ogc %s/wcs/1.0.0/OGC-exception.xsd\">\n",
               pszEncodedVal);
   msFree(pszEncodedVal);
   msIO_printf("  <ServiceException");
@@ -179,6 +181,8 @@ int msWCSException(mapObj *map, const char *code, const char *locator,
   msIO_printf("  </ServiceException>\n");
   msIO_printf("</ServiceExceptionReport>\n");
 
+  msResetErrorList();
+
   return MS_FAILURE;
 }
 
@@ -210,7 +214,7 @@ static void msWCSPrintRequestCapability(const char *version, const char *request
 static wcsParamsObj *msWCSCreateParams()
 {
   wcsParamsObj *params;
- 
+
   params = (wcsParamsObj *) calloc(1, sizeof(wcsParamsObj));
   MS_CHECK_ALLOC(params, sizeof(wcsParamsObj), NULL);
 
@@ -230,11 +234,12 @@ void msWCSFreeParams(wcsParamsObj *params)
     if(params->service) free(params->service);
     if(params->section) free(params->section);
     if(params->crs) free(params->crs);
-    if(params->response_crs) free(params->response_crs);      
+    if(params->response_crs) free(params->response_crs);
     if(params->format) free(params->format);
     if(params->exceptions) free(params->exceptions);
     if(params->time) free(params->time);
     if(params->interpolation) free(params->interpolation);
+    CSLDestroy( params->coverages );
   }
 }
 
@@ -244,10 +249,10 @@ void msWCSFreeParams(wcsParamsObj *params)
 
 int msWCSIsLayerSupported(layerObj *layer)
 {
-    /* only raster layers, are elligible to be served via WCS, WMS rasters are not ok */
-    if((layer->type == MS_LAYER_RASTER) && layer->connectiontype != MS_WMS) return MS_TRUE;
+  /* only raster layers, are elligible to be served via WCS, WMS rasters are not ok */
+  if((layer->type == MS_LAYER_RASTER) && layer->connectiontype != MS_WMS) return MS_TRUE;
 
-    return MS_FALSE;
+  return MS_FALSE;
 }
 
 /************************************************************************/
@@ -255,16 +260,17 @@ int msWCSIsLayerSupported(layerObj *layer)
 /*                                                                      */
 /************************************************************************/
 
-const char *msWCSGetRequestParameter(cgiRequestObj *request, char *name) {
+const char *msWCSGetRequestParameter(cgiRequestObj *request, char *name)
+{
   int i;
 
   if(!request || !name) /* nothing to do */
-	return NULL;
+    return NULL;
 
   if(request->NumParams > 0) {
     for(i=0; i<request->NumParams; i++) {
-       if(strcasecmp(request->ParamNames[i], name) == 0)
-	     return request->ParamValues[i];
+      if(strcasecmp(request->ParamNames[i], name) == 0)
+        return request->ParamValues[i];
     }
   }
 
@@ -277,57 +283,57 @@ const char *msWCSGetRequestParameter(cgiRequestObj *request, char *name) {
 
 void msWCSSetDefaultBandsRangeSetInfo( wcsParamsObj *params,
                                        coverageMetadataObj *cm,
-                                       layerObj *lp ) 
+                                       layerObj *lp )
 {
-    
-    /* This function will provide default rangeset information for the "special" */
-    /* "bands" rangeset if it appears in the axes list but has no specifics provided */
-    /* in the metadata.   */
 
-    const char *value;
-    char *bandlist;
-    size_t bufferSize = 0;
-    int  i;
-
-    /* Does this item exist in the axes list?  */
-
-    value = msOWSLookupMetadata(&(lp->metadata), "CO", "rangeset_axes");
-    if( value == NULL )
-        return;
-
-    value = strstr(value,"bands");
-    if( value == NULL || (value[5] != '\0' && value[5] != ' ') )
-        return;
-
-    /* Are there any w*s_bands_ metadata already? If so, skip out. */
-    if( msOWSLookupMetadata(&(lp->metadata), "CO", "bands_description") != NULL
-        || msOWSLookupMetadata(&(lp->metadata), "CO", "bands_name") != NULL
-        || msOWSLookupMetadata(&(lp->metadata), "CO", "bands_label") != NULL
-        || msOWSLookupMetadata(&(lp->metadata), "CO", "bands_values") != NULL
-        || msOWSLookupMetadata(&(lp->metadata), "CO", "bands_values_semantic") != NULL
-        || msOWSLookupMetadata(&(lp->metadata), "CO", "bands_values_type") != NULL
-        || msOWSLookupMetadata(&(lp->metadata), "CO", "bands_rangeitem") != NULL
-        || msOWSLookupMetadata(&(lp->metadata), "CO", "bands_semantic") != NULL
-        || msOWSLookupMetadata(&(lp->metadata), "CO", "bands_refsys") != NULL
-        || msOWSLookupMetadata(&(lp->metadata), "CO", "bands_refsyslabel") != NULL
-        || msOWSLookupMetadata(&(lp->metadata), "CO", "bands_interval") != NULL )
-        return;
-
-    /* OK, we have decided to fill in the information. */
-
-    msInsertHashTable( &(lp->metadata), "wcs_bands_name", "bands" );
-    msInsertHashTable( &(lp->metadata), "wcs_bands_label", "Bands/Channels/Samples" );
-    msInsertHashTable( &(lp->metadata), "wcs_bands_rangeitem", "_bands" ); /* ? */
-
-    bufferSize = cm->bandcount*30+30;
-    bandlist = (char *) msSmallMalloc(bufferSize);
-    strcpy( bandlist, "1" );
-    for( i = 1; i < cm->bandcount; i++ )
-      snprintf( bandlist+strlen(bandlist), bufferSize-strlen(bandlist), ",%d", i+1 );
-    
-    msInsertHashTable( &(lp->metadata), "wcs_bands_values", bandlist );
-    free( bandlist );
-}    
+  /* This function will provide default rangeset information for the "special" */
+  /* "bands" rangeset if it appears in the axes list but has no specifics provided */
+  /* in the metadata.   */
+
+  const char *value;
+  char *bandlist;
+  size_t bufferSize = 0;
+  int  i;
+
+  /* Does this item exist in the axes list?  */
+
+  value = msOWSLookupMetadata(&(lp->metadata), "CO", "rangeset_axes");
+  if( value == NULL )
+    return;
+
+  value = strstr(value,"bands");
+  if( value == NULL || (value[5] != '\0' && value[5] != ' ') )
+    return;
+
+  /* Are there any w*s_bands_ metadata already? If so, skip out. */
+  if( msOWSLookupMetadata(&(lp->metadata), "CO", "bands_description") != NULL
+      || msOWSLookupMetadata(&(lp->metadata), "CO", "bands_name") != NULL
+      || msOWSLookupMetadata(&(lp->metadata), "CO", "bands_label") != NULL
+      || msOWSLookupMetadata(&(lp->metadata), "CO", "bands_values") != NULL
+      || msOWSLookupMetadata(&(lp->metadata), "CO", "bands_values_semantic") != NULL
+      || msOWSLookupMetadata(&(lp->metadata), "CO", "bands_values_type") != NULL
+      || msOWSLookupMetadata(&(lp->metadata), "CO", "bands_rangeitem") != NULL
+      || msOWSLookupMetadata(&(lp->metadata), "CO", "bands_semantic") != NULL
+      || msOWSLookupMetadata(&(lp->metadata), "CO", "bands_refsys") != NULL
+      || msOWSLookupMetadata(&(lp->metadata), "CO", "bands_refsyslabel") != NULL
+      || msOWSLookupMetadata(&(lp->metadata), "CO", "bands_interval") != NULL )
+    return;
+
+  /* OK, we have decided to fill in the information. */
+
+  msInsertHashTable( &(lp->metadata), "wcs_bands_name", "bands" );
+  msInsertHashTable( &(lp->metadata), "wcs_bands_label", "Bands/Channels/Samples" );
+  msInsertHashTable( &(lp->metadata), "wcs_bands_rangeitem", "_bands" ); /* ? */
+
+  bufferSize = cm->bandcount*30+30;
+  bandlist = (char *) msSmallMalloc(bufferSize);
+  strcpy( bandlist, "1" );
+  for( i = 1; i < cm->bandcount; i++ )
+    snprintf( bandlist+strlen(bandlist), bufferSize-strlen(bandlist), ",%d", i+1 );
+
+  msInsertHashTable( &(lp->metadata), "wcs_bands_values", bandlist );
+  free( bandlist );
+}
 
 /************************************************************************/
 /*                         msWCSParseRequest()                          */
@@ -339,305 +345,272 @@ static int msWCSParseRequest(cgiRequestObj *request, wcsParamsObj *params, mapOb
   char **tokens;
 
   if(!request || !params) /* nothing to do */
-	return MS_SUCCESS;
+    return MS_SUCCESS;
 
-/* -------------------------------------------------------------------- */
-/*      Check if this appears to be an XML POST WCS request.            */
-/* -------------------------------------------------------------------- */
+  /* -------------------------------------------------------------------- */
+  /*      Check if this appears to be an XML POST WCS request.            */
+  /* -------------------------------------------------------------------- */
 
   msDebug("msWCSParseRequest(): request is %s.\n", (request->type == MS_POST_REQUEST)?"POST":"KVP");
 
-  if( request->type == MS_POST_REQUEST 
-      && request->postrequest )
-  {
+  if( request->type == MS_POST_REQUEST
+      && request->postrequest ) {
 #if defined(USE_LIBXML2)
-      xmlDocPtr doc = NULL;
-      xmlNodePtr root = NULL, child = NULL;
-      char *tmp = NULL;
-
-      /* parse to DOM-Structure and get root element */
-      if((doc = xmlParseMemory(request->postrequest, strlen(request->postrequest)))
-              == NULL) {
-          xmlErrorPtr error = xmlGetLastError();
-          msSetError(MS_WCSERR, "XML parsing error: %s",
-                  "msWCSParseRequest()", error->message);
-          return MS_FAILURE;
-      }
-      root = xmlDocGetRootElement(doc);
-
-      /* Get service, version and request from root */
-      params->request = strdup((char *) root->name);
-      if ((tmp = (char *) xmlGetProp(root, BAD_CAST "service")) != NULL)
-          params->service = tmp;
-      if ((tmp = (char *) xmlGetProp(root, BAD_CAST "version")) != NULL)
-          params->version = tmp;
-
-      /* search first level children, either CoverageID,  */
-      for (child = root->children; child != NULL; child = child->next)
-      {
-          if (EQUAL((char *)child->name, "AcceptVersions"))
-          {
-              /* will be overridden to 1.1.1 anyway */
-          }
-          else if (EQUAL((char *) child->name, "UpdateSequence"))
-          {
-              params->updatesequence = (char *)xmlNodeGetContent(child);
+    xmlDocPtr doc = NULL;
+    xmlNodePtr root = NULL, child = NULL;
+    char *tmp = NULL;
+
+    /* parse to DOM-Structure and get root element */
+    if((doc = xmlParseMemory(request->postrequest, strlen(request->postrequest)))
+        == NULL) {
+      xmlErrorPtr error = xmlGetLastError();
+      msSetError(MS_WCSERR, "XML parsing error: %s",
+                 "msWCSParseRequest()", error->message);
+      return MS_FAILURE;
+    }
+    root = xmlDocGetRootElement(doc);
+
+    /* Get service, version and request from root */
+    params->request = strdup((char *) root->name);
+    if ((tmp = (char *) xmlGetProp(root, BAD_CAST "service")) != NULL)
+      params->service = tmp;
+    if ((tmp = (char *) xmlGetProp(root, BAD_CAST "version")) != NULL)
+      params->version = tmp;
+
+    /* search first level children, either CoverageID,  */
+    for (child = root->children; child != NULL; child = child->next) {
+      if (EQUAL((char *)child->name, "AcceptVersions")) {
+        /* will be overridden to 1.1.1 anyway */
+      } else if (EQUAL((char *) child->name, "UpdateSequence")) {
+        params->updatesequence = (char *)xmlNodeGetContent(child);
+      } else if (EQUAL((char *) child->name, "Sections")) {
+        xmlNodePtr sectionNode = NULL;
+        /* concatenate all sections by ',' */
+        for(sectionNode = child->children; sectionNode != NULL; sectionNode = sectionNode->next) {
+          char *content;
+          if(!EQUAL((char *)sectionNode->name, "Section"))
+            continue;
+          content = (char *)xmlNodeGetContent(sectionNode);
+          if(!params->section) {
+            params->section = content;
+          } else {
+            params->section = msStringConcatenate(params->section, ",");
+            params->section = msStringConcatenate(params->section, content);
+            xmlFree(content);
           }
-          else if (EQUAL((char *) child->name, "Sections"))
-          {
-              xmlNodePtr sectionNode = NULL;
-              /* concatenate all sections by ',' */
-              for(sectionNode = child->children; sectionNode != NULL; sectionNode = sectionNode->next)
-              {
-                  char *content;
-                  if(!EQUAL((char *)sectionNode->name, "Section"))
-                      continue;
-                  content = (char *)xmlNodeGetContent(sectionNode);
-                  if(!params->section)
-                  {
-                      params->section = content;
-                  }
-                  else
-                  {
-                      params->section = msStringConcatenate(params->section, ",");
-                      params->section = msStringConcatenate(params->section, content);
-                      xmlFree(content);
-                  }
+        }
+      } else if(EQUAL((char *) child->name, "AcceptFormats")) {
+        /* TODO: implement */
+      } else if(EQUAL((char *) child->name, "Identifier")) {
+        char *content = (char *)xmlNodeGetContent(child);
+        params->coverages = CSLAddString(params->coverages, content);
+        xmlFree(content);
+      } else if(EQUAL((char *) child->name, "DomainSubset")) {
+        xmlNodePtr tmpNode = NULL;
+        for(tmpNode = child->children; tmpNode != NULL; tmpNode = tmpNode->next) {
+          if(EQUAL((char *) tmpNode->name, "BoundingBox")) {
+            xmlNodePtr cornerNode = NULL;
+            params->crs = (char *)xmlGetProp(tmpNode, BAD_CAST "crs");
+            if( strncasecmp(params->crs,"urn:ogc:def:crs:",16) == 0
+                && strncasecmp(params->crs+strlen(params->crs)-8,"imageCRS",8)==0)
+              strcpy( params->crs, "imageCRS" );
+            for(cornerNode = tmpNode->children; cornerNode != NULL; cornerNode = cornerNode->next) {
+              if(EQUAL((char *) cornerNode->name, "LowerCorner")) {
+                char *value = (char *)xmlNodeGetContent(cornerNode);
+                tokens = msStringSplit(value, ' ', &n);
+                if(tokens==NULL || n < 2) {
+                  msSetError(MS_WCSERR, "Wrong number of arguments for LowerCorner",
+                             "msWCSParseRequest()");
+                  return msWCSException(map, "InvalidParameterValue", "LowerCorner",
+                                        params->version );
+                }
+                params->bbox.minx = atof(tokens[0]);
+                params->bbox.miny = atof(tokens[1]);
+                msFreeCharArray(tokens, n);
+                xmlFree(value);
               }
-          }
-          else if(EQUAL((char *) child->name, "AcceptFormats"))
-          {
-              /* TODO: implement */
-          }
-          else if(EQUAL((char *) child->name, "Identifier"))
-          {
-              char *content = (char *)xmlNodeGetContent(child);
-              params->coverages = CSLAddString(params->coverages, content);
-              xmlFree(content);
-          }
-          else if(EQUAL((char *) child->name, "DomainSubset"))
-          {
-              xmlNodePtr tmpNode = NULL;
-              for(tmpNode = child->children; tmpNode != NULL; tmpNode = tmpNode->next)
-              {
-                  if(EQUAL((char *) tmpNode->name, "BoundingBox"))
-                  {
-                      xmlNodePtr cornerNode = NULL;
-                      params->crs = (char *)xmlGetProp(tmpNode, BAD_CAST "crs");
-                      if( strncasecmp(params->crs,"urn:ogc:def:crs:",16) == 0
-                          && strncasecmp(params->crs+strlen(params->crs)-8,"imageCRS",8)==0)
-                         strcpy( params->crs, "imageCRS" );
-                      for(cornerNode = tmpNode->children; cornerNode != NULL; cornerNode = cornerNode->next)
-                      {
-                          if(EQUAL((char *) cornerNode->name, "LowerCorner"))
-                          {
-                              char *value = (char *)xmlNodeGetContent(cornerNode);
-                              tokens = msStringSplit(value, ' ', &n);
-                              if(tokens==NULL || n < 2) {
-                                msSetError(MS_WCSERR, "Wrong number of arguments for LowerCorner",
-                                           "msWCSParseRequest()");
-                                return msWCSException(map, "InvalidParameterValue", "LowerCorner",
-                                                      params->version );
-                              }
-                              params->bbox.minx = atof(tokens[0]);
-                              params->bbox.miny = atof(tokens[1]);
-                              msFreeCharArray(tokens, n);
-                              xmlFree(value);
-                          }
-                          if(EQUAL((char *) cornerNode->name, "UpperCorner"))
-                          {
-                              char *value = (char *)xmlNodeGetContent(cornerNode);
-                              tokens = msStringSplit(value, ' ', &n);
-                              if(tokens==NULL || n < 2) {
-                                msSetError(MS_WCSERR, "Wrong number of arguments for UpperCorner",
-                                           "msWCSParseRequest()");
-                                return msWCSException(map, "InvalidParameterValue", "UpperCorner",
-                                                      params->version );
-                              }
-                              params->bbox.maxx = atof(tokens[0]);
-                              params->bbox.maxy = atof(tokens[1]);
-                              msFreeCharArray(tokens, n);
-                              xmlFree(value);
-                          }
-                      }
-                  }
+              if(EQUAL((char *) cornerNode->name, "UpperCorner")) {
+                char *value = (char *)xmlNodeGetContent(cornerNode);
+                tokens = msStringSplit(value, ' ', &n);
+                if(tokens==NULL || n < 2) {
+                  msSetError(MS_WCSERR, "Wrong number of arguments for UpperCorner",
+                             "msWCSParseRequest()");
+                  return msWCSException(map, "InvalidParameterValue", "UpperCorner",
+                                        params->version );
+                }
+                params->bbox.maxx = atof(tokens[0]);
+                params->bbox.maxy = atof(tokens[1]);
+                msFreeCharArray(tokens, n);
+                xmlFree(value);
               }
+            }
           }
-          else if(EQUAL((char *) child->name, "RangeSubset"))
-          {
-              /* TODO: not implemented in mapserver WCS 1.1? */
-          }
-          else if(EQUAL((char *) child->name, "Output"))
-          {
-              xmlNodePtr tmpNode = NULL;
-              params->format = (char *)xmlGetProp(child, BAD_CAST "format");
-              for(tmpNode = child->children; tmpNode != NULL; tmpNode = tmpNode->next)
-              {
-                  if(EQUAL((char *) tmpNode->name, "GridCRS"))
-                  {
-                      xmlNodePtr crsNode = NULL;
-                      for(crsNode = tmpNode->children; crsNode != NULL; crsNode = crsNode->next)
-                      {
-                          if(EQUAL((char *) crsNode->name, "GridBaseCRS"))
-                          {
-                              params->response_crs = (char *) xmlNodeGetContent(crsNode);
-                          }
-                          else if (EQUAL((char *) crsNode->name, "GridOrigin"))
-                          {
-                              char *value = (char *)xmlNodeGetContent(crsNode);
-                              tokens = msStringSplit(value, ' ', &n);
-                              if(tokens==NULL || n < 2) {
-                                msSetError(MS_WCSERR, "Wrong number of arguments for GridOrigin",
-                                           "msWCSParseRequest()");
-                                return msWCSException(map, "InvalidParameterValue", "GridOffsets",
-                                                      params->version );
-                              }
-                              params->originx = atof(tokens[0]);
-                              params->originy = atof(tokens[1]);
-                              msFreeCharArray(tokens, n);
-                              xmlFree(value);
-                          }
-                          else if (EQUAL((char *) crsNode->name, "GridOffsets"))
-                          {
-                              char *value = (char *)xmlNodeGetContent(crsNode);
-                              tokens = msStringSplit(value, ' ', &n);
-                              if(tokens==NULL || n < 2) {
-                                  msSetError(MS_WCSERR, "Wrong number of arguments for GridOffsets",
-                                  "msWCSParseRequest()");
-                                  return msWCSException(map, "InvalidParameterValue", "GridOffsets",
-                                                        params->version );
-                              }
-                              /* take absolute values to convert to positive RESX/RESY style
-                              WCS 1.0 behavior.  *but* this does break some possibilities! */
-                              params->resx = fabs(atof(tokens[0]));
-                              params->resy = fabs(atof(tokens[1]));
-                              msFreeCharArray(tokens, n);
-                              xmlFree(value);
-                          }
-                      }
-                  }
+        }
+      } else if(EQUAL((char *) child->name, "RangeSubset")) {
+        /* TODO: not implemented in mapserver WCS 1.1? */
+      } else if(EQUAL((char *) child->name, "Output")) {
+        xmlNodePtr tmpNode = NULL;
+        params->format = (char *)xmlGetProp(child, BAD_CAST "format");
+        for(tmpNode = child->children; tmpNode != NULL; tmpNode = tmpNode->next) {
+          if(EQUAL((char *) tmpNode->name, "GridCRS")) {
+            xmlNodePtr crsNode = NULL;
+            for(crsNode = tmpNode->children; crsNode != NULL; crsNode = crsNode->next) {
+              if(EQUAL((char *) crsNode->name, "GridBaseCRS")) {
+                params->response_crs = (char *) xmlNodeGetContent(crsNode);
+              } else if (EQUAL((char *) crsNode->name, "GridOrigin")) {
+                char *value = (char *)xmlNodeGetContent(crsNode);
+                tokens = msStringSplit(value, ' ', &n);
+                if(tokens==NULL || n < 2) {
+                  msSetError(MS_WCSERR, "Wrong number of arguments for GridOrigin",
+                             "msWCSParseRequest()");
+                  return msWCSException(map, "InvalidParameterValue", "GridOffsets",
+                                        params->version );
+                }
+                params->originx = atof(tokens[0]);
+                params->originy = atof(tokens[1]);
+                msFreeCharArray(tokens, n);
+                xmlFree(value);
+              } else if (EQUAL((char *) crsNode->name, "GridOffsets")) {
+                char *value = (char *)xmlNodeGetContent(crsNode);
+                tokens = msStringSplit(value, ' ', &n);
+                if(tokens==NULL || n < 2) {
+                  msSetError(MS_WCSERR, "Wrong number of arguments for GridOffsets",
+                             "msWCSParseRequest()");
+                  return msWCSException(map, "InvalidParameterValue", "GridOffsets",
+                                        params->version );
+                }
+                /* take absolute values to convert to positive RESX/RESY style
+                WCS 1.0 behavior.  *but* this does break some possibilities! */
+                params->resx = fabs(atof(tokens[0]));
+                params->resy = fabs(atof(tokens[1]));
+                msFreeCharArray(tokens, n);
+                xmlFree(value);
               }
+            }
           }
+        }
       }
-      xmlFreeDoc(doc);
-      xmlCleanupParser();
-      return MS_SUCCESS;
+    }
+    xmlFreeDoc(doc);
+    xmlCleanupParser();
+    return MS_SUCCESS;
 #else /* defined(USE_LIBXML2) */
-      return MS_FAILURE;
+    msSetError(MS_WCSERR, "To enable POST requests, MapServer has to "
+               "be compiled with libxml2.", "msWCSParseRequest()");
+    return MS_FAILURE;
 #endif /* defined(USE_LIBXML2) */
   }
 
-/* -------------------------------------------------------------------- */
-/*      Extract WCS KVP Parameters.                                     */
-/* -------------------------------------------------------------------- */
+  /* -------------------------------------------------------------------- */
+  /*      Extract WCS KVP Parameters.                                     */
+  /* -------------------------------------------------------------------- */
   if(request->NumParams > 0) {
     for(i=0; i<request->NumParams; i++) {
-    
-       if(strcasecmp(request->ParamNames[i], "VERSION") == 0)
-           params->version = msStrdup(request->ParamValues[i]);
-       if(strcasecmp(request->ParamNames[i], "UPDATESEQUENCE") == 0)
-           params->updatesequence = msStrdup(request->ParamValues[i]);
-       else if(strcasecmp(request->ParamNames[i], "REQUEST") == 0)
-	     params->request = msStrdup(request->ParamValues[i]);
-       else if(strcasecmp(request->ParamNames[i], "INTERPOLATION") == 0)
-	     params->interpolation = msStrdup(request->ParamValues[i]);
-       else if(strcasecmp(request->ParamNames[i], "SERVICE") == 0)
-	     params->service = msStrdup(request->ParamValues[i]);
-       else if(strcasecmp(request->ParamNames[i], "SECTION") == 0) /* 1.0 */
-           params->section = msStrdup(request->ParamValues[i]); /* TODO: validate value here */
-       else if(strcasecmp(request->ParamNames[i], "SECTIONS") == 0) /* 1.1 */
-           params->section = msStrdup(request->ParamValues[i]); /* TODO: validate value here */
-
-       /* GetCoverage parameters. */
-       else if(strcasecmp(request->ParamNames[i], "BBOX") == 0) {
-         tokens = msStringSplit(request->ParamValues[i], ',', &n);
-         if(tokens==NULL || n != 4) {
-           msSetError(MS_WCSERR, "Wrong number of arguments for BBOX.", "msWCSParseRequest()");
-           return msWCSException(map, "InvalidParameterValue", "bbox",
-                                 params->version );
-         }
-         params->bbox.minx = atof(tokens[0]);
-         params->bbox.miny = atof(tokens[1]);
-         params->bbox.maxx = atof(tokens[2]);
-         params->bbox.maxy = atof(tokens[3]);
-           
-         msFreeCharArray(tokens, n);
-       } else if(strcasecmp(request->ParamNames[i], "RESX") == 0)
-         params->resx = atof(request->ParamValues[i]);
-       else if(strcasecmp(request->ParamNames[i], "RESY") == 0)
-         params->resy = atof(request->ParamValues[i]);
-       else if(strcasecmp(request->ParamNames[i], "WIDTH") == 0)
-         params->width = atoi(request->ParamValues[i]);
-       else if(strcasecmp(request->ParamNames[i], "HEIGHT") == 0)
-         params->height = atoi(request->ParamValues[i]);
-       else if(strcasecmp(request->ParamNames[i], "COVERAGE") == 0)
-         params->coverages = CSLAddString(params->coverages, request->ParamValues[i]);
-       else if(strcasecmp(request->ParamNames[i], "TIME") == 0)
-           params->time = msStrdup(request->ParamValues[i]);
-       else if(strcasecmp(request->ParamNames[i], "FORMAT") == 0)
-           params->format = msStrdup(request->ParamValues[i]);
-       else if(strcasecmp(request->ParamNames[i], "CRS") == 0)
-           params->crs = msStrdup(request->ParamValues[i]);
-       else if(strcasecmp(request->ParamNames[i], "RESPONSE_CRS") == 0)
-           params->response_crs = msStrdup(request->ParamValues[i]);
-
-       /* WCS 1.1 DescribeCoverage and GetCoverage ... */
-       else if(strcasecmp(request->ParamNames[i], "IDENTIFIER") == 0
-               || strcasecmp(request->ParamNames[i], "IDENTIFIERS") == 0 )
-       {
-           msDebug("msWCSParseRequest(): Whole String: %s\n", request->ParamValues[i]);
-           params->coverages = CSLAddString(params->coverages, request->ParamValues[i]);
-       }
-       /* WCS 1.1 style BOUNDINGBOX */
-       else if(strcasecmp(request->ParamNames[i], "BOUNDINGBOX") == 0) {
-         tokens = msStringSplit(request->ParamValues[i], ',', &n);
-         if(tokens==NULL || n < 5) {
-           msSetError(MS_WCSERR, "Wrong number of arguments for BOUNDINGBOX.", "msWCSParseRequest()");
-           return msWCSException(map, "InvalidParameterValue", "boundingbox",
-                                 params->version );
-         }
-
-         /* NOTE: WCS 1.1 boundingbox is center of pixel oriented, not edge
-            like in WCS 1.0.  So bbox semantics are wonky till this is fixed
-            later in the GetCoverage processing. */
-         params->bbox.minx = atof(tokens[0]);
-         params->bbox.miny = atof(tokens[1]);
-         params->bbox.maxx = atof(tokens[2]);
-         params->bbox.maxy = atof(tokens[3]);
-           
-         params->crs = msStrdup(tokens[4]);
-         msFreeCharArray(tokens, n);
-         /* normalize imageCRS urns to simply "imageCRS" */
-         if( strncasecmp(params->crs,"urn:ogc:def:crs:",16) == 0 
-             && strncasecmp(params->crs+strlen(params->crs)-8,"imageCRS",8)==0)
-             strcpy( params->crs, "imageCRS" );
-       } else if(strcasecmp(request->ParamNames[i], "GridOffsets") == 0) {
-         tokens = msStringSplit(request->ParamValues[i], ',', &n);
-         if(tokens==NULL || n < 2) {
-           msSetError(MS_WCSERR, "Wrong number of arguments for GridOffsets", 
-                      "msWCSParseRequest()");
-           return msWCSException(map, "InvalidParameterValue", "GridOffsets",
-                                 params->version );
-         }
-         /* take absolute values to convert to positive RESX/RESY style
-            WCS 1.0 behavior.  *but* this does break some possibilities! */
-         params->resx = fabs(atof(tokens[0])); 
-         params->resy = fabs(atof(tokens[1]));
-         msFreeCharArray(tokens, n);
-       } else if(strcasecmp(request->ParamNames[i], "GridOrigin") == 0) {
-         tokens = msStringSplit(request->ParamValues[i], ',', &n);
-         if(tokens==NULL || n < 2) {
-           msSetError(MS_WCSERR, "Wrong number of arguments for GridOrigin", 
-                      "msWCSParseRequest()");
-           return msWCSException(map, "InvalidParameterValue", "GridOffsets",
-                                 params->version );
-         }
-         params->originx = atof(tokens[0]);
-         params->originy = atof(tokens[1]);
-         msFreeCharArray(tokens, n);
-       }
-	   
-       /* and so on... */
+
+      if(strcasecmp(request->ParamNames[i], "VERSION") == 0)
+        params->version = msStrdup(request->ParamValues[i]);
+      if(strcasecmp(request->ParamNames[i], "UPDATESEQUENCE") == 0)
+        params->updatesequence = msStrdup(request->ParamValues[i]);
+      else if(strcasecmp(request->ParamNames[i], "REQUEST") == 0)
+        params->request = msStrdup(request->ParamValues[i]);
+      else if(strcasecmp(request->ParamNames[i], "INTERPOLATION") == 0)
+        params->interpolation = msStrdup(request->ParamValues[i]);
+      else if(strcasecmp(request->ParamNames[i], "SERVICE") == 0)
+        params->service = msStrdup(request->ParamValues[i]);
+      else if(strcasecmp(request->ParamNames[i], "SECTION") == 0) /* 1.0 */
+        params->section = msStrdup(request->ParamValues[i]); /* TODO: validate value here */
+      else if(strcasecmp(request->ParamNames[i], "SECTIONS") == 0) /* 1.1 */
+        params->section = msStrdup(request->ParamValues[i]); /* TODO: validate value here */
+
+      /* GetCoverage parameters. */
+      else if(strcasecmp(request->ParamNames[i], "BBOX") == 0) {
+        tokens = msStringSplit(request->ParamValues[i], ',', &n);
+        if(tokens==NULL || n != 4) {
+          msSetError(MS_WCSERR, "Wrong number of arguments for BBOX.", "msWCSParseRequest()");
+          return msWCSException(map, "InvalidParameterValue", "bbox",
+                                params->version );
+        }
+        params->bbox.minx = atof(tokens[0]);
+        params->bbox.miny = atof(tokens[1]);
+        params->bbox.maxx = atof(tokens[2]);
+        params->bbox.maxy = atof(tokens[3]);
+
+        msFreeCharArray(tokens, n);
+      } else if(strcasecmp(request->ParamNames[i], "RESX") == 0)
+        params->resx = atof(request->ParamValues[i]);
+      else if(strcasecmp(request->ParamNames[i], "RESY") == 0)
+        params->resy = atof(request->ParamValues[i]);
+      else if(strcasecmp(request->ParamNames[i], "WIDTH") == 0)
+        params->width = atoi(request->ParamValues[i]);
+      else if(strcasecmp(request->ParamNames[i], "HEIGHT") == 0)
+        params->height = atoi(request->ParamValues[i]);
+      else if(strcasecmp(request->ParamNames[i], "COVERAGE") == 0)
+        params->coverages = CSLAddString(params->coverages, request->ParamValues[i]);
+      else if(strcasecmp(request->ParamNames[i], "TIME") == 0)
+        params->time = msStrdup(request->ParamValues[i]);
+      else if(strcasecmp(request->ParamNames[i], "FORMAT") == 0)
+        params->format = msStrdup(request->ParamValues[i]);
+      else if(strcasecmp(request->ParamNames[i], "CRS") == 0)
+        params->crs = msStrdup(request->ParamValues[i]);
+      else if(strcasecmp(request->ParamNames[i], "RESPONSE_CRS") == 0)
+        params->response_crs = msStrdup(request->ParamValues[i]);
+
+      /* WCS 1.1 DescribeCoverage and GetCoverage ... */
+      else if(strcasecmp(request->ParamNames[i], "IDENTIFIER") == 0
+              || strcasecmp(request->ParamNames[i], "IDENTIFIERS") == 0 ) {
+        msDebug("msWCSParseRequest(): Whole String: %s\n", request->ParamValues[i]);
+        params->coverages = CSLAddString(params->coverages, request->ParamValues[i]);
+      }
+      /* WCS 1.1 style BOUNDINGBOX */
+      else if(strcasecmp(request->ParamNames[i], "BOUNDINGBOX") == 0) {
+        tokens = msStringSplit(request->ParamValues[i], ',', &n);
+        if(tokens==NULL || n < 5) {
+          msSetError(MS_WCSERR, "Wrong number of arguments for BOUNDINGBOX.", "msWCSParseRequest()");
+          return msWCSException(map, "InvalidParameterValue", "boundingbox",
+                                params->version );
+        }
+
+        /* NOTE: WCS 1.1 boundingbox is center of pixel oriented, not edge
+           like in WCS 1.0.  So bbox semantics are wonky till this is fixed
+           later in the GetCoverage processing. */
+        params->bbox.minx = atof(tokens[0]);
+        params->bbox.miny = atof(tokens[1]);
+        params->bbox.maxx = atof(tokens[2]);
+        params->bbox.maxy = atof(tokens[3]);
+
+        params->crs = msStrdup(tokens[4]);
+        msFreeCharArray(tokens, n);
+        /* normalize imageCRS urns to simply "imageCRS" */
+        if( strncasecmp(params->crs,"urn:ogc:def:crs:",16) == 0
+            && strncasecmp(params->crs+strlen(params->crs)-8,"imageCRS",8)==0)
+          strcpy( params->crs, "imageCRS" );
+      } else if(strcasecmp(request->ParamNames[i], "GridOffsets") == 0) {
+        tokens = msStringSplit(request->ParamValues[i], ',', &n);
+        if(tokens==NULL || n < 2) {
+          msSetError(MS_WCSERR, "Wrong number of arguments for GridOffsets",
+                     "msWCSParseRequest()");
+          return msWCSException(map, "InvalidParameterValue", "GridOffsets",
+                                params->version );
+        }
+        /* take absolute values to convert to positive RESX/RESY style
+           WCS 1.0 behavior.  *but* this does break some possibilities! */
+        params->resx = fabs(atof(tokens[0]));
+        params->resy = fabs(atof(tokens[1]));
+        msFreeCharArray(tokens, n);
+      } else if(strcasecmp(request->ParamNames[i], "GridOrigin") == 0) {
+        tokens = msStringSplit(request->ParamValues[i], ',', &n);
+        if(tokens==NULL || n < 2) {
+          msSetError(MS_WCSERR, "Wrong number of arguments for GridOrigin",
+                     "msWCSParseRequest()");
+          return msWCSException(map, "InvalidParameterValue", "GridOffsets",
+                                params->version );
+        }
+        params->originx = atof(tokens[0]);
+        params->originy = atof(tokens[1]);
+        msFreeCharArray(tokens, n);
+      }
+
+      /* and so on... */
     }
   }
   /* we are not dealing with an XML encoded request at this point */
@@ -653,8 +626,8 @@ static void msWCSGetCapabilities_Service_ResponsibleParty(mapObj *map)
   int bEnableTelephone=MS_FALSE, bEnableAddress=MS_FALSE, bEnableOnlineResource=MS_FALSE;
 
   /* the WCS-specific way */
-  if(msOWSLookupMetadata(&(map->web.metadata), "CO", "responsibleparty_individualname") || 
-     msOWSLookupMetadata(&(map->web.metadata), "CO", "responsibleparty_organizationname")) {
+  if(msOWSLookupMetadata(&(map->web.metadata), "CO", "responsibleparty_individualname") ||
+      msOWSLookupMetadata(&(map->web.metadata), "CO", "responsibleparty_organizationname")) {
 
     msIO_printf("<responsibleParty>\n");
     msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "CO", "responsibleparty_individualname", OWS_NOERR, "    <individualName>%s</individualName>\n", NULL);
@@ -662,34 +635,34 @@ static void msWCSGetCapabilities_Service_ResponsibleParty(mapObj *map)
     msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "CO", "responsibleparty_positionname", OWS_NOERR, "    <positionName>%s</positionName>\n", NULL);
 
     if(msOWSLookupMetadata(&(map->web.metadata), "CO", "responsibleparty_phone_voice") ||
-       msOWSLookupMetadata(&(map->web.metadata), "CO", "responsibleparty_phone_facsimile")) bEnableTelephone = MS_TRUE;
+        msOWSLookupMetadata(&(map->web.metadata), "CO", "responsibleparty_phone_facsimile")) bEnableTelephone = MS_TRUE;
 
     if(msOWSLookupMetadata(&(map->web.metadata), "CO", "responsibleparty_address_deliverypoint") ||
-       msOWSLookupMetadata(&(map->web.metadata), "CO", "responsibleparty_address_city") ||
-       msOWSLookupMetadata(&(map->web.metadata), "CO", "responsibleparty_address_administrativearea") ||
-       msOWSLookupMetadata(&(map->web.metadata), "CO", "responsibleparty_address_postalcode") ||
-       msOWSLookupMetadata(&(map->web.metadata), "CO", "responsibleparty_address_country") ||
-       msOWSLookupMetadata(&(map->web.metadata), "CO", "responsibleparty_address_electronicmailaddress")) bEnableAddress = MS_TRUE;
- 
+        msOWSLookupMetadata(&(map->web.metadata), "CO", "responsibleparty_address_city") ||
+        msOWSLookupMetadata(&(map->web.metadata), "CO", "responsibleparty_address_administrativearea") ||
+        msOWSLookupMetadata(&(map->web.metadata), "CO", "responsibleparty_address_postalcode") ||
+        msOWSLookupMetadata(&(map->web.metadata), "CO", "responsibleparty_address_country") ||
+        msOWSLookupMetadata(&(map->web.metadata), "CO", "responsibleparty_address_electronicmailaddress")) bEnableAddress = MS_TRUE;
+
     if(msOWSLookupMetadata(&(map->web.metadata), "CO", "responsibleparty_onlineresource")) bEnableOnlineResource = MS_TRUE;
 
     if(bEnableTelephone || bEnableAddress || bEnableOnlineResource) {
       msIO_printf("  <contactInfo>\n");
       if(bEnableTelephone) {
-	msIO_printf("    <phone>\n");
+        msIO_printf("    <phone>\n");
         msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "CO", "responsibleparty_phone_voice", OWS_NOERR, "    <voice>%s</voice>\n", NULL);
         msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "CO", "responsibleparty_phone_facsimile", OWS_NOERR, "    <facsimile>%s</facsimile>\n", NULL);
-	msIO_printf("    </phone>\n");
+        msIO_printf("    </phone>\n");
       }
       if(bEnableAddress) {
-	msIO_printf("    <address>\n");
+        msIO_printf("    <address>\n");
         msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "CO", "responsibleparty_address_deliverypoint", OWS_NOERR, "    <deliveryPoint>%s</deliveryPoint>\n", NULL);
         msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "CO", "responsibleparty_address_city", OWS_NOERR, "    <city>%s</city>\n", NULL);
         msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "CO", "responsibleparty_address_administrativearea", OWS_NOERR, "    <administrativeArea>%s</administrativeArea>\n", NULL);
         msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "CO", "responsibleparty_address_postalcode", OWS_NOERR, "    <postalCode>%s</postalCode>\n", NULL);
         msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "CO", "responsibleparty_address_country", OWS_NOERR, "    <country>%s</country>\n", NULL);
         msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "CO", "responsibleparty_address_electronicmailaddress", OWS_NOERR, "    <electronicMailAddress>%s</electronicMailAddress>\n", NULL);
-	msIO_printf("    </address>\n");
+        msIO_printf("    </address>\n");
       }
       msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "CO", "responsibleparty_onlineresource", OWS_NOERR, "    <onlineResource xlink:type=\"simple\" xlink:href=\"%s\"/>\n", NULL);
       msIO_printf("  </contactInfo>\n");
@@ -698,7 +671,7 @@ static void msWCSGetCapabilities_Service_ResponsibleParty(mapObj *map)
     msIO_printf("</responsibleParty>\n");
 
   } else if(msOWSLookupMetadata(&(map->web.metadata), "CO", "contactperson") ||
-       msOWSLookupMetadata(&(map->web.metadata), "CO", "contactorganization")) { /* leverage WMS contact information */
+            msOWSLookupMetadata(&(map->web.metadata), "CO", "contactorganization")) { /* leverage WMS contact information */
 
     msIO_printf("<responsibleParty>\n");
     msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "CO", "contactperson", OWS_NOERR, "    <individualName>%s</individualName>\n", NULL);
@@ -706,14 +679,14 @@ static void msWCSGetCapabilities_Service_ResponsibleParty(mapObj *map)
     msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "CO", "contactposition", OWS_NOERR, "    <positionName>%s</positionName>\n", NULL);
 
     if(msOWSLookupMetadata(&(map->web.metadata), "CO", "contactvoicetelephone") ||
-       msOWSLookupMetadata(&(map->web.metadata), "CO", "contactfacsimiletelephone")) bEnableTelephone = MS_TRUE;
+        msOWSLookupMetadata(&(map->web.metadata), "CO", "contactfacsimiletelephone")) bEnableTelephone = MS_TRUE;
 
     if(msOWSLookupMetadata(&(map->web.metadata), "CO", "address") ||
-       msOWSLookupMetadata(&(map->web.metadata), "CO", "city") ||
-       msOWSLookupMetadata(&(map->web.metadata), "CO", "stateorprovince") ||
-       msOWSLookupMetadata(&(map->web.metadata), "CO", "postcode") ||
-       msOWSLookupMetadata(&(map->web.metadata), "CO", "country") ||
-       msOWSLookupMetadata(&(map->web.metadata), "CO", "contactelectronicmailaddress")) bEnableAddress = MS_TRUE;
+        msOWSLookupMetadata(&(map->web.metadata), "CO", "city") ||
+        msOWSLookupMetadata(&(map->web.metadata), "CO", "stateorprovince") ||
+        msOWSLookupMetadata(&(map->web.metadata), "CO", "postcode") ||
+        msOWSLookupMetadata(&(map->web.metadata), "CO", "country") ||
+        msOWSLookupMetadata(&(map->web.metadata), "CO", "contactelectronicmailaddress")) bEnableAddress = MS_TRUE;
 
     if(msOWSLookupMetadata(&(map->web.metadata), "CO", "service_onlineresource")) bEnableOnlineResource = MS_TRUE;
 
@@ -755,20 +728,20 @@ static int msWCSGetCapabilities_Service(mapObj *map, wcsParamsObj *params)
     msIO_printf("<Service>\n");
   else
     msIO_printf("<Service\n"
-           "   version=\"%s\" \n"
-           "   updateSequence=\"%s\" \n"
-           "   xmlns=\"http://www.opengis.net/wcs\" \n" 
-           "   xmlns:xlink=\"http://www.w3.org/1999/xlink\" \n" 
-           "   xmlns:gml=\"http://www.opengis.net/gml\" \n" 
-           "   xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" 
-           "   xsi:schemaLocation=\"http://www.opengis.net/wcs %s/wcs/%s/wcsCapabilities.xsd\">\n", params->version, params->updatesequence, msOWSGetSchemasLocation(map), params->version); 
+                "   version=\"%s\" \n"
+                "   updateSequence=\"%s\" \n"
+                "   xmlns=\"http://www.opengis.net/wcs\" \n"
+                "   xmlns:xlink=\"http://www.w3.org/1999/xlink\" \n"
+                "   xmlns:gml=\"http://www.opengis.net/gml\" \n"
+                "   xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
+                "   xsi:schemaLocation=\"http://www.opengis.net/wcs %s/wcs/%s/wcsCapabilities.xsd\">\n", params->version, params->updatesequence, msOWSGetSchemasLocation(map), params->version);
 
   /* optional metadataLink */
-  msOWSPrintURLType(stdout, &(map->web.metadata), "CO", "metadatalink", 
-                    OWS_NOERR, 
-                    "  <metadataLink%s%s%s%s xlink:type=\"simple\"%s/>", 
-                    NULL, " metadataType=\"%s\"", NULL, NULL, NULL,  
-                    " xlink:href=\"%s\"", MS_FALSE, MS_FALSE, MS_FALSE, 
+  msOWSPrintURLType(stdout, &(map->web.metadata), "CO", "metadatalink",
+                    OWS_NOERR,
+                    "  <metadataLink%s%s%s%s xlink:type=\"simple\"%s/>",
+                    NULL, " metadataType=\"%s\"", NULL, NULL, NULL,
+                    " xlink:href=\"%s\"", MS_FALSE, MS_FALSE, MS_FALSE,
                     MS_FALSE, MS_TRUE, "other", NULL, NULL, NULL, NULL, NULL);
 
   msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "CO", "description", OWS_NOERR, "  <description>%s</description>\n", NULL);
@@ -797,11 +770,11 @@ static int msWCSGetCapabilities_Capability(mapObj *map, wcsParamsObj *params, cg
 {
   char *script_url=NULL, *script_url_encoded=NULL;
 
-   /* we need this server's onlineresource for the request section */
+  /* we need this server's onlineresource for the request section */
   if((script_url=msOWSGetOnlineResource(map, "CO", "onlineresource", req)) == NULL || (script_url_encoded = msEncodeHTMLEntities(script_url)) == NULL) {
-      free(script_url);
-      free(script_url_encoded);
-      return msWCSException(map, NULL, NULL, params->version );
+    free(script_url);
+    free(script_url_encoded);
+    return msWCSException(map, NULL, NULL, params->version );
   }
 
   /* start the Capabilty section, only need the full start tag if this is the only section requested */
@@ -809,23 +782,23 @@ static int msWCSGetCapabilities_Capability(mapObj *map, wcsParamsObj *params, cg
     msIO_printf("<Capability>\n");
   else
     msIO_printf("<Capability\n"
-           "   version=\"%s\" \n"
-           "   updateSequence=\"%s\" \n"
-           "   xmlns=\"http://www.opengis.net/wcs\" \n" 
-           "   xmlns:xlink=\"http://www.w3.org/1999/xlink\" \n" 
-           "   xmlns:gml=\"http://www.opengis.net/gml\" \n" 
-           "   xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" 
-           "   xsi:schemaLocation=\"http://www.opengis.net/wcs %s/wcs/%s/wcsCapabilities.xsd\">\n", params->version, params->updatesequence, msOWSGetSchemasLocation(map), params->version); 
+                "   version=\"%s\" \n"
+                "   updateSequence=\"%s\" \n"
+                "   xmlns=\"http://www.opengis.net/wcs\" \n"
+                "   xmlns:xlink=\"http://www.w3.org/1999/xlink\" \n"
+                "   xmlns:gml=\"http://www.opengis.net/gml\" \n"
+                "   xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
+                "   xsi:schemaLocation=\"http://www.opengis.net/wcs %s/wcs/%s/wcsCapabilities.xsd\">\n", params->version, params->updatesequence, msOWSGetSchemasLocation(map), params->version);
 
   /* describe the types of requests the server can handle */
   msIO_printf("  <Request>\n");
 
   msWCSPrintRequestCapability(params->version, "GetCapabilities", script_url_encoded);
-  if (msOWSRequestIsEnabled(map, NULL, "C", "DescribeCoverage", MS_TRUE)) 
-      msWCSPrintRequestCapability(params->version, "DescribeCoverage", script_url_encoded);
-  if (msOWSRequestIsEnabled(map, NULL, "C", "GetCoverage", MS_TRUE)) 
-      msWCSPrintRequestCapability(params->version, "GetCoverage", script_url_encoded);
- 
+  if (msOWSRequestIsEnabled(map, NULL, "C", "DescribeCoverage", MS_FALSE))
+    msWCSPrintRequestCapability(params->version, "DescribeCoverage", script_url_encoded);
+  if (msOWSRequestIsEnabled(map, NULL, "C", "GetCoverage", MS_FALSE))
+    msWCSPrintRequestCapability(params->version, "GetCoverage", script_url_encoded);
+
   msIO_printf("  </Request>\n");
 
   /* describe the exception formats the server can produce */
@@ -849,7 +822,7 @@ static int msWCSGetCapabilities_Capability(mapObj *map, wcsParamsObj *params, cg
 /*             msWCSGetCapabilities_CoverageOfferingBrief()             */
 /************************************************************************/
 
-static int msWCSGetCapabilities_CoverageOfferingBrief(layerObj *layer, wcsParamsObj *params) 
+static int msWCSGetCapabilities_CoverageOfferingBrief(layerObj *layer, wcsParamsObj *params)
 {
   coverageMetadataObj cm;
   int status;
@@ -858,16 +831,16 @@ static int msWCSGetCapabilities_CoverageOfferingBrief(layerObj *layer, wcsParams
 
   status = msWCSGetCoverageMetadata(layer, &cm);
   if(status != MS_SUCCESS) return MS_FAILURE;
- 
+
   /* start the CoverageOfferingBrief section */
   msIO_printf("  <CoverageOfferingBrief>\n"); /* is this tag right? (I hate schemas without ANY examples) */
 
   /* optional metadataLink */
-  msOWSPrintURLType(stdout, &(layer->metadata), "CO", "metadatalink", 
-                    OWS_NOERR, 
-                    "  <metadataLink%s%s%s%s xlink:type=\"simple\"%s/>", 
-                    NULL, " metadataType=\"%s\"", NULL, NULL, NULL,  
-                    " xlink:href=\"%s\"", MS_FALSE, MS_FALSE, MS_FALSE, 
+  msOWSPrintURLType(stdout, &(layer->metadata), "CO", "metadatalink",
+                    OWS_NOERR,
+                    "  <metadataLink%s%s%s%s xlink:type=\"simple\"%s/>",
+                    NULL, " metadataType=\"%s\"", NULL, NULL, NULL,
+                    " xlink:href=\"%s\"", MS_FALSE, MS_FALSE, MS_FALSE,
                     MS_FALSE, MS_TRUE, "other", NULL, NULL, NULL, NULL, NULL);
 
   msOWSPrintEncodeMetadata(stdout, &(layer->metadata), "CO", "description", OWS_NOERR, "    <description>%s</description>\n", NULL);
@@ -907,23 +880,26 @@ static int msWCSGetCapabilities_ContentMetadata(mapObj *map, wcsParamsObj *param
     msIO_printf("<ContentMetadata>\n");
   else
     msIO_printf("<ContentMetadata\n"
-           "   version=\"%s\" \n"
-           "   updateSequence=\"%s\" \n"
-           "   xmlns=\"http://www.opengis.net/wcs\" \n" 
-           "   xmlns:xlink=\"http://www.w3.org/1999/xlink\" \n" 
-           "   xmlns:gml=\"http://www.opengis.net/gml\" \n" 
-           "   xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" 
-           "   xsi:schemaLocation=\"http://www.opengis.net/wcs %s/wcs/%s/wcsCapabilities.xsd\">\n", params->version, params->updatesequence, msOWSGetSchemasLocation(map), params->version); 
-
-  for(i=0; i<map->numlayers; i++) {
-  
+                "   version=\"%s\" \n"
+                "   updateSequence=\"%s\" \n"
+                "   xmlns=\"http://www.opengis.net/wcs\" \n"
+                "   xmlns:xlink=\"http://www.w3.org/1999/xlink\" \n"
+                "   xmlns:gml=\"http://www.opengis.net/gml\" \n"
+                "   xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
+                "   xsi:schemaLocation=\"http://www.opengis.net/wcs %s/wcs/%s/wcsCapabilities.xsd\">\n", params->version, params->updatesequence, msOWSGetSchemasLocation(map), params->version);
+
+  if(ows_request->numlayers == 0) {
+    msIO_printf("  <!-- WARNING: No WCS layers are enabled. Check wcs/ows_enable_request settings. -->\n");
+  } else {
+    for(i=0; i<map->numlayers; i++) {
       if (!msIntegerInArray(GET_LAYER(map, i)->index, ows_request->enabled_layers, ows_request->numlayers))
-          continue;
-  
+        continue;
+
       if( msWCSGetCapabilities_CoverageOfferingBrief((GET_LAYER(map, i)), params) != MS_SUCCESS ) {
-          msIO_printf("</ContentMetadata>\n");
-          return MS_FAILURE;
+        msIO_printf("</ContentMetadata>\n");
+        return MS_FAILURE;
       }
+    }
   }
 
   /* done */
@@ -949,10 +925,9 @@ static int msWCSGetCapabilities(mapObj *map, wcsParamsObj *params, cgiRequestObj
 
   /* check version is valid */
   tmpInt = msOWSParseVersionString(params->version);
-  if (tmpInt == OWS_VERSION_BADFORMAT)
-  {
+  if (tmpInt == OWS_VERSION_BADFORMAT) {
     return msWCSException(map, "InvalidParameterValue",
-                          "request", "1.0.0 ");
+                          "version", "1.0.0 ");
   }
 
   /* negotiate version */
@@ -962,34 +937,34 @@ static int msWCSGetCapabilities(mapObj *map, wcsParamsObj *params, cgiRequestObj
   free(params->version);
   params->version = msStrdup(msOWSGetVersionString(tmpInt, tmpString));
 
-/* -------------------------------------------------------------------- */
-/*      1.1.x is sufficiently different we have a whole case for        */
-/*      it.  The remainder of this function is for 1.0.0.               */
-/* -------------------------------------------------------------------- */
-    if( strncmp(params->version,"1.1",3) == 0 )
-        return msWCSGetCapabilities11( map, params, req, ows_request);
-
-    updatesequence = msOWSLookupMetadata(&(map->web.metadata), "CO", "updatesequence");
-
-    if (params->updatesequence != NULL) {
-        i = msOWSNegotiateUpdateSequence(params->updatesequence, updatesequence);
-        if (i == 0) { /* current */
-            msSetError(MS_WCSERR, "UPDATESEQUENCE parameter (%s) is equal to server (%s)", "msWCSGetCapabilities()", params->updatesequence, updatesequence);
-            return msWCSException(map, "CurrentUpdateSequence", 
-                                  "updatesequence", params->version );
-        }
-        if (i > 0) { /* invalid */
-            msSetError(MS_WCSERR, "UPDATESEQUENCE parameter (%s) is higher than server (%s)", "msWCSGetCapabilities()", params->updatesequence, updatesequence);
-            return msWCSException(map, "InvalidUpdateSequence", 
-                                  "updatesequence", params->version );
-        }
-    }
+  /* -------------------------------------------------------------------- */
+  /*      1.1.x is sufficiently different we have a whole case for        */
+  /*      it.  The remainder of this function is for 1.0.0.               */
+  /* -------------------------------------------------------------------- */
+  if( strncmp(params->version,"1.1",3) == 0 )
+    return msWCSGetCapabilities11( map, params, req, ows_request);
+
+  updatesequence = msOWSLookupMetadata(&(map->web.metadata), "CO", "updatesequence");
 
-    else { /* set default updatesequence */
-      if(!updatesequence)
-        updatesequence = msStrdup("0");
-      params->updatesequence = msStrdup(updatesequence);
+  if (params->updatesequence != NULL) {
+    i = msOWSNegotiateUpdateSequence(params->updatesequence, updatesequence);
+    if (i == 0) { /* current */
+      msSetError(MS_WCSERR, "UPDATESEQUENCE parameter (%s) is equal to server (%s)", "msWCSGetCapabilities()", params->updatesequence, updatesequence);
+      return msWCSException(map, "CurrentUpdateSequence",
+                            "updatesequence", params->version );
     }
+    if (i > 0) { /* invalid */
+      msSetError(MS_WCSERR, "UPDATESEQUENCE parameter (%s) is higher than server (%s)", "msWCSGetCapabilities()", params->updatesequence, updatesequence);
+      return msWCSException(map, "InvalidUpdateSequence",
+                            "updatesequence", params->version );
+    }
+  }
+
+  else { /* set default updatesequence */
+    if(!updatesequence)
+      updatesequence = "0";
+    params->updatesequence = msStrdup(updatesequence);
+  }
 
   /* if a bum section param is passed, throw exception */
   if (params->section &&
@@ -997,56 +972,58 @@ static int msWCSGetCapabilities(mapObj *map, wcsParamsObj *params, cgiRequestObj
       strcasecmp(params->section, "/WCS_Capabilities/Capability") != 0 &&
       strcasecmp(params->section, "/WCS_Capabilities/ContentMetadata") != 0 &&
       strcasecmp(params->section, "/") != 0) {
-      if (encoding)
-          msIO_printf("Content-type: application/vnd.ogc.se_xml; charset=%s%c%c", encoding,10,10);
-      else
-          msIO_printf("Content-type: application/vnd.ogc.se_xml%c%c",10,10);
-      msSetError( MS_WCSERR,
-        "Invalid SECTION parameter \"%s\"",
-        "msWCSGetCapabilities()", params->section);
-      return msWCSException(map, "InvalidParameterValue", "section", 
-                            params->version );
+    if (encoding)
+      msIO_setHeader("Content-Type","application/vnd.ogc.se_xml; charset=%s", encoding);
+    else
+      msIO_setHeader("Content-Type","application/vnd.ogc.se_xml");
+    msIO_sendHeaders();
+    msSetError( MS_WCSERR,
+                "Invalid SECTION parameter \"%s\"",
+                "msWCSGetCapabilities()", params->section);
+    return msWCSException(map, "InvalidParameterValue", "section",
+                          params->version );
   }
 
   else {
-      if (encoding)
-          msIO_printf("Content-type: text/xml; charset=%s%c%c", encoding,10,10);
-      else
-          msIO_printf("Content-type: text/xml%c%c",10,10);
-  
+    if (encoding)
+      msIO_setHeader("Content-Type","text/xml; charset=%s", encoding);
+    else
+      msIO_setHeader("Content-Type","text/xml");
+    msIO_sendHeaders();
+
     /* print common capability elements  */
     /* TODO: DocType? */
 
-  if (!updatesequence)
-    updatesequence = msStrdup("0");
+    if (!updatesequence)
+      updatesequence = "0";
 
     msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), NULL, "wcs_encoding", OWS_NOERR, "<?xml version='1.0' encoding=\"%s\" standalone=\"no\" ?>\n", "ISO-8859-1");
-  
+
     if(!params->section || (params->section && strcasecmp(params->section, "/")  == 0)) msIO_printf("<WCS_Capabilities\n"
-                                "   version=\"%s\" \n"
-                                "   updateSequence=\"%s\" \n"
-                                "   xmlns=\"http://www.opengis.net/wcs\" \n" 
-                                "   xmlns:xlink=\"http://www.w3.org/1999/xlink\" \n" 
-                                "   xmlns:gml=\"http://www.opengis.net/gml\" \n" 
-                                "   xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" 
-                                "   xsi:schemaLocation=\"http://www.opengis.net/wcs %s/wcs/%s/wcsCapabilities.xsd\">\n", params->version, updatesequence, msOWSGetSchemasLocation(map), params->version); 
-           
+          "   version=\"%s\" \n"
+          "   updateSequence=\"%s\" \n"
+          "   xmlns=\"http://www.opengis.net/wcs\" \n"
+          "   xmlns:xlink=\"http://www.w3.org/1999/xlink\" \n"
+          "   xmlns:gml=\"http://www.opengis.net/gml\" \n"
+          "   xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
+          "   xsi:schemaLocation=\"http://www.opengis.net/wcs %s/wcs/%s/wcsCapabilities.xsd\">\n", params->version, updatesequence, msOWSGetSchemasLocation(map), params->version);
+
     /* print the various capability sections */
     if(!params->section || strcasecmp(params->section, "/WCS_Capabilities/Service") == 0)
       msWCSGetCapabilities_Service(map, params);
-  
+
     if(!params->section || strcasecmp(params->section, "/WCS_Capabilities/Capability")  == 0)
       msWCSGetCapabilities_Capability(map, params, req);
-  
+
     if(!params->section || strcasecmp(params->section, "/WCS_Capabilities/ContentMetadata")  == 0)
-        msWCSGetCapabilities_ContentMetadata(map, params, ows_request);
-  
+      msWCSGetCapabilities_ContentMetadata(map, params, ows_request);
+
     if(params->section && strcasecmp(params->section, "/")  == 0) {
       msWCSGetCapabilities_Service(map, params);
       msWCSGetCapabilities_Capability(map, params, req);
       msWCSGetCapabilities_ContentMetadata(map, params, ows_request);
     }
-  
+
     /* done */
     if(!params->section || (params->section && strcasecmp(params->section, "/")  == 0)) msIO_printf("</WCS_Capabilities>\n");
   }
@@ -1062,7 +1039,7 @@ static int msWCSDescribeCoverage_AxisDescription(layerObj *layer, char *name)
 {
   const char *value;
   char tag[100]; /* should be plenty of space */
-  
+
   msIO_printf("        <axisDescription>\n");
   msIO_printf("          <AxisDescription");
   snprintf(tag, sizeof(tag), "%s_semantic",  name); /* optional attributes follow (should escape?) */
@@ -1072,18 +1049,18 @@ static int msWCSDescribeCoverage_AxisDescription(layerObj *layer, char *name)
   snprintf(tag, sizeof(tag), "%s_refsyslabel", name);
   msOWSPrintEncodeMetadata(stdout, &(layer->metadata), "CO", tag, OWS_NOERR, " refSysLabel=\"%s\"", NULL);
   msIO_printf(">\n");
-  
+
   /* TODO: add metadataLink (optional) */
-  
+
   snprintf(tag, sizeof(tag), "%s_description", name);
   msOWSPrintEncodeMetadata(stdout, &(layer->metadata), "CO", tag, OWS_NOERR, "            <description>%s</description>\n", NULL);
   /* snprintf(tag, sizeof(tag), "%s_name", name); */
   /* msOWSPrintEncodeMetadata(stdout, &(layer->metadata), "CO", tag, OWS_WARN, "            <name>%s</name>\n", NULL); */
   msIO_printf("            <name>%s</name>\n", name);
- 
+
   snprintf(tag, sizeof(tag), "%s_label", name);
   msOWSPrintEncodeMetadata(stdout, &(layer->metadata), "CO", tag, OWS_WARN, "            <label>%s</label>\n", NULL);
-  
+
   /* Values */
   msIO_printf("            <values");
   snprintf(tag, sizeof(tag), "%s_values_semantic", name); /* optional attributes follow (should escape?) */
@@ -1091,35 +1068,35 @@ static int msWCSDescribeCoverage_AxisDescription(layerObj *layer, char *name)
   snprintf(tag, sizeof(tag), "%s_values_type", name);
   msOWSPrintEncodeMetadata(stdout, &(layer->metadata), "CO", tag, OWS_NOERR, " type=\"%s\"", NULL);
   msIO_printf(">\n");
-  
+
   /* single values, we do not support optional type and semantic attributes */
   snprintf(tag, sizeof(tag), "%s_values", name);
   if(msOWSLookupMetadata(&(layer->metadata), "CO", tag))
     msOWSPrintEncodeMetadataList(stdout, &(layer->metadata), "CO", tag, NULL, NULL, "              <singleValue>%s</singleValue>\n", NULL);
-  
+
   /* intervals, only one per axis for now, we do not support optional type, atomic and semantic attributes */
   snprintf(tag, sizeof(tag), "%s_interval", name);
   if((value = msOWSLookupMetadata(&(layer->metadata), "CO", tag)) != NULL) {
     char **tokens;
     int numtokens;
 
-     tokens = msStringSplit(value, '/', &numtokens);
-     if(tokens && numtokens > 0) {
-       msIO_printf("            <interval>\n");
-       if(numtokens >= 1) msIO_printf("            <min>%s</min>\n", tokens[0]); /* TODO: handle closure */
-       if(numtokens >= 2) msIO_printf("            <max>%s</max>\n", tokens[1]);
-       if(numtokens >= 3) msIO_printf("            <res>%s</res>\n", tokens[2]);
-       msIO_printf("            </interval>\n"); 
-     }
+    tokens = msStringSplit(value, '/', &numtokens);
+    if(tokens && numtokens > 0) {
+      msIO_printf("            <interval>\n");
+      if(numtokens >= 1) msIO_printf("            <min>%s</min>\n", tokens[0]); /* TODO: handle closure */
+      if(numtokens >= 2) msIO_printf("            <max>%s</max>\n", tokens[1]);
+      if(numtokens >= 3) msIO_printf("            <res>%s</res>\n", tokens[2]);
+      msIO_printf("            </interval>\n");
+    }
   }
-  
+
   /* TODO: add default (optional) */
-  
+
   msIO_printf("            </values>\n");
-  
+
   msIO_printf("          </AxisDescription>\n");
   msIO_printf("        </axisDescription>\n");
-  
+
   return MS_SUCCESS;
 }
 
@@ -1127,26 +1104,26 @@ static int msWCSDescribeCoverage_AxisDescription(layerObj *layer, char *name)
 /*               msWCSDescribeCoverage_CoverageOffering()               */
 /************************************************************************/
 
-static int msWCSDescribeCoverage_CoverageOffering(layerObj *layer, wcsParamsObj *params) 
+static int msWCSDescribeCoverage_CoverageOffering(layerObj *layer, wcsParamsObj *params)
 {
   char **tokens;
   int numtokens;
-  const char *value; 
+  const char *value;
   coverageMetadataObj cm;
   int i, status;
 
   if ( msCheckParentPointer(layer->map,"map")==MS_FAILURE )
-	return MS_FAILURE;
+    return MS_FAILURE;
 
   if(!msWCSIsLayerSupported(layer)) return MS_SUCCESS; /* not an error, this layer cannot be served via WCS */
-  
+
 
   status = msWCSGetCoverageMetadata(layer, &cm);
   if(status != MS_SUCCESS) return MS_FAILURE;
 
   /* fill in bands rangeset info, if required.  */
   msWCSSetDefaultBandsRangeSetInfo( params, &cm, layer );
-  
+
   /* start the Coverage section */
   msIO_printf("  <CoverageOffering>\n");
 
@@ -1157,7 +1134,7 @@ static int msWCSDescribeCoverage_CoverageOffering(layerObj *layer, wcsParamsObj
                     NULL, " metadataType=\"%s\"", NULL, NULL, NULL,
                     " xlink:href=\"%s\"", MS_FALSE, MS_FALSE, MS_FALSE,
                     MS_FALSE, MS_TRUE, "other", NULL, NULL, NULL, NULL, NULL);
-  
+
   msOWSPrintEncodeMetadata(stdout, &(layer->metadata), "CO", "description", OWS_NOERR, "  <description>%s</description>\n", NULL);
   msOWSPrintEncodeMetadata(stdout, &(layer->metadata), "CO", "name", OWS_NOERR, "  <name>%s</name>\n", layer->name);
 
@@ -1180,19 +1157,19 @@ static int msWCSDescribeCoverage_CoverageOffering(layerObj *layer, wcsParamsObj
 
   /* SpatialDomain */
   msIO_printf("      <spatialDomain>\n");
-  
+
   /* envelope in lat/lon */
   msIO_printf("        <gml:Envelope srsName=\"EPSG:4326\">\n");
   msIO_printf("          <gml:pos>%.15g %.15g</gml:pos>\n", cm.llextent.minx, cm.llextent.miny);
   msIO_printf("          <gml:pos>%.15g %.15g</gml:pos>\n", cm.llextent.maxx, cm.llextent.maxy);
   msIO_printf("        </gml:Envelope>\n");
-  
+
   /* envelope in the native srs */
-  if((value = msOWSGetEPSGProj(&(layer->projection), &(layer->metadata), "CO", MS_TRUE)) != NULL)    
+  if((value = msOWSGetEPSGProj(&(layer->projection), &(layer->metadata), "CO", MS_TRUE)) != NULL)
     msIO_printf("        <gml:Envelope srsName=\"%s\">\n", value);
   else if((value = msOWSGetEPSGProj(&(layer->map->projection), &(layer->map->web.metadata), "CO", MS_TRUE)) != NULL)
     msIO_printf("        <gml:Envelope srsName=\"%s\">\n", value);
-  else 
+  else
     msIO_printf("        <!-- NativeCRSs ERROR: missing required information, no SRSs defined -->\n");
   msIO_printf("          <gml:pos>%.15g %.15g</gml:pos>\n", cm.extent.minx, cm.extent.miny);
   msIO_printf("          <gml:pos>%.15g %.15g</gml:pos>\n", cm.extent.maxx, cm.extent.maxy);
@@ -1224,48 +1201,48 @@ static int msWCSDescribeCoverage_CoverageOffering(layerObj *layer, wcsParamsObj
     msIO_printf("      <temporalDomain>\n");
 
     /* TimePosition (should support a value AUTO, then we could mine positions from the timeitem) */
-    msOWSPrintEncodeMetadataList(stdout, &(layer->metadata), "CO", "timeposition", NULL, NULL, "        <gml:timePosition>%s</gml:timePosition>\n", NULL);    
+    msOWSPrintEncodeMetadataList(stdout, &(layer->metadata), "CO", "timeposition", NULL, NULL, "        <gml:timePosition>%s</gml:timePosition>\n", NULL);
 
     /* TODO:  add TimePeriod (only one per layer)  */
 
     msIO_printf("      </temporalDomain>\n");
   }
-  
+
   msIO_printf("    </domainSet>\n");
-  
+
   /* rangeSet */
   msIO_printf("    <rangeSet>\n");
   msIO_printf("      <RangeSet>\n"); /* TODO: there are some optional attributes */
 
   /* TODO: add metadataLink (optional) */
-  
+
   msOWSPrintEncodeMetadata(stdout, &(layer->metadata), "CO", "rangeset_description", OWS_NOERR, "        <description>%s</description>\n", NULL);
   msOWSPrintEncodeMetadata(stdout, &(layer->metadata), "CO", "rangeset_name", OWS_WARN, "        <name>%s</name>\n", NULL);
 
   msOWSPrintEncodeMetadata(stdout, &(layer->metadata), "CO", "rangeset_label", OWS_WARN, "        <label>%s</label>\n", NULL);
-  
+
   /* compound range sets */
   if((value = msOWSLookupMetadata(&(layer->metadata), "CO", "rangeset_axes")) != NULL) {
-     tokens = msStringSplit(value, ',', &numtokens);
-     if(tokens && numtokens > 0) {
-       for(i=0; i<numtokens; i++)
-         msWCSDescribeCoverage_AxisDescription(layer, tokens[i]);
-       msFreeCharArray(tokens, numtokens);
-     }
+    tokens = msStringSplit(value, ',', &numtokens);
+    if(tokens && numtokens > 0) {
+      for(i=0; i<numtokens; i++)
+        msWCSDescribeCoverage_AxisDescription(layer, tokens[i]);
+      msFreeCharArray(tokens, numtokens);
+    }
   }
 
   if((value = msOWSLookupMetadata(&(layer->metadata), "CO", "rangeset_nullvalue")) != NULL) {
-     msIO_printf("        <nullValues>\n");
-     msIO_printf("          <singleValue>%s</singleValue>\n", value);
-     msIO_printf("        </nullValues>\n");
+    msIO_printf("        <nullValues>\n");
+    msIO_printf("          <singleValue>%s</singleValue>\n", value);
+    msIO_printf("        </nullValues>\n");
   }
-  
+
   msIO_printf("      </RangeSet>\n");
   msIO_printf("    </rangeSet>\n");
 
   /* supportedCRSs */
   msIO_printf("    <supportedCRSs>\n");
-  
+
   /* requestResposeCRSs: check the layer metadata/projection, and then the map metadata/projection if necessary (should never get to the error message) */
   if((value = msOWSGetEPSGProj(&(layer->projection), &(layer->metadata), "CO", MS_FALSE)) != NULL) {
     tokens = msStringSplit(value, ' ', &numtokens);
@@ -1281,20 +1258,20 @@ static int msWCSDescribeCoverage_CoverageOffering(layerObj *layer, wcsParamsObj
         msIO_printf("      <requestResponseCRSs>%s</requestResponseCRSs>\n", tokens[i]);
       msFreeCharArray(tokens, numtokens);
     }
-  } else 
+  } else
     msIO_printf("      <!-- requestResponseCRSs ERROR: missing required information, no SRSs defined -->\n");
-  
+
   /* nativeCRSs (only one in our case) */
-  if((value = msOWSGetEPSGProj(&(layer->projection), &(layer->metadata), "CO", MS_TRUE)) != NULL)    
+  if((value = msOWSGetEPSGProj(&(layer->projection), &(layer->metadata), "CO", MS_TRUE)) != NULL)
     msIO_printf("      <nativeCRSs>%s</nativeCRSs>\n", value);
   else if((value = msOWSGetEPSGProj(&(layer->map->projection), &(layer->map->web.metadata), "CO", MS_TRUE)) != NULL)
     msIO_printf("      <nativeCRSs>%s</nativeCRSs>\n", value);
-  else 
+  else
     msIO_printf("      <!-- nativeCRSs ERROR: missing required information, no SRSs defined -->\n");
-  
+
   msIO_printf("    </supportedCRSs>\n");
-  
-  
+
+
   /* supportedFormats */
   msIO_printf("    <supportedFormats");
   msOWSPrintEncodeMetadata(stdout, &(layer->metadata), "CO", "nativeformat", OWS_NOERR, " nativeFormat=\"%s\"", NULL);
@@ -1308,15 +1285,16 @@ static int msWCSDescribeCoverage_CoverageOffering(layerObj *layer, wcsParamsObj
         msIO_printf("      <formats>%s</formats>\n", tokens[i]);
       msFreeCharArray(tokens, numtokens);
     }
+    msFree((char*)value);
   }
   msIO_printf("    </supportedFormats>\n");
-  
+
   msIO_printf("    <supportedInterpolations default=\"nearest neighbor\">\n");
   msIO_printf("      <interpolationMethod>nearest neighbor</interpolationMethod>\n" );
   msIO_printf("      <interpolationMethod>bilinear</interpolationMethod>\n" );
-/*  msIO_printf("      <interpolationMethod>bicubic</interpolationMethod>\n" ); */
+  /*  msIO_printf("      <interpolationMethod>bicubic</interpolationMethod>\n" ); */
   msIO_printf("    </supportedInterpolations>\n");
-  
+
 
   /* done */
   msIO_printf("  </CoverageOffering>\n");
@@ -1336,88 +1314,99 @@ static int msWCSDescribeCoverage(mapObj *map, wcsParamsObj *params, owsRequestOb
   int numcoverages=0;
   const char *encoding;
 
-  char *coverageName=NULL; 
+  char *coverageName=NULL;
 
   encoding = msOWSLookupMetadata(&(map->web.metadata), "CO", "encoding");
-/* -------------------------------------------------------------------- */
-/*      1.1.x is sufficiently different we have a whole case for        */
-/*      it.  The remainder of this function is for 1.0.0.               */
-/* -------------------------------------------------------------------- */
+  /* -------------------------------------------------------------------- */
+  /*      1.1.x is sufficiently different we have a whole case for        */
+  /*      it.  The remainder of this function is for 1.0.0.               */
+  /* -------------------------------------------------------------------- */
   if( strncmp(params->version,"1.1",3) == 0 )
-      return msWCSDescribeCoverage11( map, params, ows_request);
+    return msWCSDescribeCoverage11( map, params, ows_request);
 
-/* -------------------------------------------------------------------- */
-/*      Process 1.0.0...                                                */
-/* -------------------------------------------------------------------- */
+  /* -------------------------------------------------------------------- */
+  /*      Process 1.0.0...                                                */
+  /* -------------------------------------------------------------------- */
 
   if(params->coverages) { /* use the list, but validate it first */
     for(j=0; params->coverages[j]; j++) {
       coverages = msStringSplit(params->coverages[j], ',', &numcoverages);
       for(k=0; k<numcoverages; k++) {
-          
+
         for(i=0; i<map->numlayers; i++) {
           coverageName = msOWSGetEncodeMetadata(&(GET_LAYER(map, i)->metadata), "CO", "name", GET_LAYER(map, i)->name);
           if( EQUAL(coverageName, coverages[k]) &&
-              (msIntegerInArray(GET_LAYER(map, i)->index, ows_request->enabled_layers, ows_request->numlayers)) )
-              break;
+              (msIntegerInArray(GET_LAYER(map, i)->index, ows_request->enabled_layers, ows_request->numlayers)) ) {
+            msFree(coverageName);
+            break;
+          }
+          msFree(coverageName);
         }
 
         /* i = msGetLayerIndex(map, coverages[k]); */
         if(i == map->numlayers) { /* coverage not found */
-          msSetError( MS_WCSERR, "COVERAGE %s cannot be opened / does not exist", "msWCSDescribeCoverage()", coverages[k]);
+          msSetError( MS_WCSERR, "COVERAGE %s cannot be opened / does not exist. A layer might be disabled for \
+this request. Check wcs/ows_enable_request settings.", "msWCSDescribeCoverage()", coverages[k]);
           return msWCSException(map, "CoverageNotDefined", "coverage", params->version );
         }
       } /* next coverage */
+      msFreeCharArray(coverages,numcoverages);
     }
   }
- 
+
   updatesequence = msOWSLookupMetadata(&(map->web.metadata), "CO", "updatesequence");
   if (!updatesequence)
     updatesequence = msStrdup("0");
 
-  /* printf("Content-type: application/vnd.ogc.se_xml%c%c",10,10); */
+  /* printf("Content-Type: application/vnd.ogc.se_xml%c%c",10,10); */
   if (encoding)
-      msIO_printf("Content-type: text/xml; charset=%s%c%c", encoding,10,10);
+    msIO_setHeader("Content-Type","text/xml; charset=%s", encoding);
   else
-      msIO_printf("Content-type: text/xml%c%c",10,10);
+    msIO_setHeader("Content-Type","text/xml");
+  msIO_sendHeaders();
 
   /* print common capability elements  */
   msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), NULL, "wcs_encoding", OWS_NOERR, "<?xml version='1.0' encoding=\"%s\" ?>\n", "ISO-8859-1");
 
   /* start the DescribeCoverage section */
   msIO_printf("<CoverageDescription\n"
-         "   version=\"%s\" \n"
-         "   updateSequence=\"%s\" \n"
-         "   xmlns=\"http://www.opengis.net/wcs\" \n" 
-         "   xmlns:xlink=\"http://www.w3.org/1999/xlink\" \n" 
-         "   xmlns:gml=\"http://www.opengis.net/gml\" \n" 
-         "   xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" 
-         "   xsi:schemaLocation=\"http://www.opengis.net/wcs %s/wcs/%s/describeCoverage.xsd\">\n", params->version, updatesequence, msOWSGetSchemasLocation(map), params->version); 
+              "   version=\"%s\" \n"
+              "   updateSequence=\"%s\" \n"
+              "   xmlns=\"http://www.opengis.net/wcs\" \n"
+              "   xmlns:xlink=\"http://www.w3.org/1999/xlink\" \n"
+              "   xmlns:gml=\"http://www.opengis.net/gml\" \n"
+              "   xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
+              "   xsi:schemaLocation=\"http://www.opengis.net/wcs %s/wcs/%s/describeCoverage.xsd\">\n", params->version, updatesequence, msOWSGetSchemasLocation(map), params->version);
   if(params->coverages) { /* use the list */
     for( j = 0; params->coverages[j]; j++ ) {
       coverages = msStringSplit(params->coverages[j], ',', &numcoverages);
-      for(k=0;k<numcoverages;k++) {
+      for(k=0; k<numcoverages; k++) {
         for(i=0; i<map->numlayers; i++) {
           coverageName = msOWSGetEncodeMetadata(&(GET_LAYER(map, i)->metadata), "CO", "name", GET_LAYER(map, i)->name);
-          if( EQUAL(coverageName, coverages[k]) ) break;
-        }        
+          if( EQUAL(coverageName, coverages[k]) ) {
+            msFree(coverageName);
+            break;
+          }
+          msFree(coverageName);
+        }
         msWCSDescribeCoverage_CoverageOffering((GET_LAYER(map, i)), params);
       }
+      msFreeCharArray(coverages,numcoverages);
     }
   } else { /* return all layers */
-      for(i=0; i<map->numlayers; i++) {
-          if (!msIntegerInArray(GET_LAYER(map, i)->index, ows_request->enabled_layers, ows_request->numlayers))
-              continue;
+    for(i=0; i<map->numlayers; i++) {
+      if (!msIntegerInArray(GET_LAYER(map, i)->index, ows_request->enabled_layers, ows_request->numlayers))
+        continue;
 
-          msWCSDescribeCoverage_CoverageOffering((GET_LAYER(map, i)), params);
-      }
+      msWCSDescribeCoverage_CoverageOffering((GET_LAYER(map, i)), params);
+    }
   }
 
- 
- 
+
+
   /* done */
   msIO_printf("</CoverageDescription>\n");
-  
+
   return MS_SUCCESS;
 }
 
@@ -1425,7 +1414,7 @@ static int msWCSDescribeCoverage(mapObj *map, wcsParamsObj *params, owsRequestOb
 /*                       msWCSGetCoverageBands10()                      */
 /************************************************************************/
 
-static int msWCSGetCoverageBands10( mapObj *map, cgiRequestObj *request, 
+static int msWCSGetCoverageBands10( mapObj *map, cgiRequestObj *request,
                                     wcsParamsObj *params, layerObj *lp,
                                     char **p_bandlist )
 
@@ -1435,7 +1424,7 @@ static int msWCSGetCoverageBands10( mapObj *map, cgiRequestObj *request,
 
   /* Are there any non-spatio/temporal ranges to do subsetting on (e.g. bands) */
   value = msOWSLookupMetadata(&(lp->metadata), "CO", "rangeset_axes"); /* this will get all the compound range sets */
-  if(value) { 
+  if(value) {
     char **tokens;
     int numtokens;
     char tag[100];
@@ -1445,31 +1434,38 @@ static int msWCSGetCoverageBands10( mapObj *map, cgiRequestObj *request,
 
     for(i=0; i<numtokens; i++) {
       if((value = msWCSGetRequestParameter(request, tokens[i])) == NULL) continue; /* next rangeset parameter */
-      
-      /* ok, a parameter has been passed which matches a token in wcs_rangeset_axes */ 
+
+      /* ok, a parameter has been passed which matches a token in wcs_rangeset_axes */
       if(msWCSValidateRangeSetParam(lp, tokens[i], value) != MS_SUCCESS) {
+        int ret;
         msSetError( MS_WCSERR, "Error specifying \"%s\" parameter value(s).", "msWCSGetCoverage()", tokens[i]);
-        return msWCSException(map, "InvalidParameterValue", tokens[i], params->version );
+        ret = msWCSException(map, "InvalidParameterValue", tokens[i], params->version );
+        msFreeCharArray(tokens, numtokens);
+        return ret;
       }
-       
+
       /* xxxxx_rangeitem tells us how to subset */
       snprintf(tag, sizeof(tag), "%s_rangeitem", tokens[i]);
       if((rangeitem = msOWSLookupMetadata(&(lp->metadata), "CO", tag)) == NULL) {
         msSetError( MS_WCSERR, "Missing required metadata element \"%s\", unable to process %s=%s.", "msWCSGetCoverage()", tag, tokens[i], value);
+        msFreeCharArray(tokens, numtokens);
         return msWCSException(map, NULL, NULL, params->version);
       }
-         
+
       if(strcasecmp(rangeitem, "_bands") == 0) { /* special case, subset bands */
         *p_bandlist = msWCSConvertRangeSetToString(value);
-           
+
         if(!*p_bandlist) {
           msSetError( MS_WCSERR, "Error specifying \"%s\" parameter value(s).", "msWCSGetCoverage()", tokens[i]);
+          msFreeCharArray(tokens, numtokens);
           return msWCSException(map, NULL, NULL, params->version );
-        }          
+        }
       } else if(strcasecmp(rangeitem, "_pixels") == 0) { /* special case, subset pixels */
+        msFreeCharArray(tokens, numtokens);
         msSetError( MS_WCSERR, "Arbitrary range sets based on pixel values are not yet supported.", "msWCSGetCoverage()" );
         return msWCSException(map, NULL, NULL, params->version);
       } else {
+        msFreeCharArray(tokens, numtokens);
         msSetError( MS_WCSERR, "Arbitrary range sets based on tile (i.e. image) attributes are not yet supported.", "msWCSGetCoverage()" );
         return msWCSException(map, NULL, NULL, params->version );
       }
@@ -1479,7 +1475,7 @@ static int msWCSGetCoverageBands10( mapObj *map, cgiRequestObj *request,
   }
 
   return MS_SUCCESS;
-}    
+}
 
 /************************************************************************/
 /*                   msWCSGetCoverage_ImageCRSSetup()                   */
@@ -1491,73 +1487,70 @@ static int msWCSGetCoverageBands10( mapObj *map, cgiRequestObj *request,
 /************************************************************************/
 
 static int msWCSGetCoverage_ImageCRSSetup(
-    mapObj *map, cgiRequestObj *request, wcsParamsObj *params,
-    coverageMetadataObj *cm, layerObj *layer )
+  mapObj *map, cgiRequestObj *request, wcsParamsObj *params,
+  coverageMetadataObj *cm, layerObj *layer )
 
 {
-/* -------------------------------------------------------------------- */
-/*      Load map with the layer (coverage) coordinate system.  We       */
-/*      really need a set projectionObj from projectionObj function!    */
-/* -------------------------------------------------------------------- */
-    char *layer_proj = msGetProjectionString( &(layer->projection) );
-
-    if (msLoadProjectionString(&(map->projection), layer_proj) != 0)
-        return msWCSException( map, NULL, NULL, params->version );
-
-    free( layer_proj );
-    layer_proj = NULL;
-
-/* -------------------------------------------------------------------- */
-/*      Reset bounding box.                                             */
-/* -------------------------------------------------------------------- */
-    if( params->bbox.maxx != params->bbox.minx )
-    {
-        rectObj orig_bbox = params->bbox;
-        
-        params->bbox.minx = 
-            cm->geotransform[0]
-            + orig_bbox.minx * cm->geotransform[1]
-            + orig_bbox.miny * cm->geotransform[2];
-        params->bbox.maxy = 
-            cm->geotransform[3]
-            + orig_bbox.minx * cm->geotransform[4]
-            + orig_bbox.miny * cm->geotransform[5];
-        params->bbox.maxx = 
-            cm->geotransform[0]
-            + (orig_bbox.maxx+1) * cm->geotransform[1]
-            + (orig_bbox.maxy+1) * cm->geotransform[2];
-        params->bbox.miny = 
-            cm->geotransform[3]
-            + (orig_bbox.maxx+1) * cm->geotransform[4]
-            + (orig_bbox.maxy+1) * cm->geotransform[5];
-
-      /* WCS 1.1 boundbox is center of pixel oriented. */
-      if( strncasecmp(params->version,"1.1",3) == 0 )
-      {
-          params->bbox.minx += cm->geotransform[1]/2 + cm->geotransform[2]/2;
-          params->bbox.maxx -= cm->geotransform[1]/2 + cm->geotransform[2]/2;
-          params->bbox.maxy += cm->geotransform[4]/2 + cm->geotransform[5]/2;
-          params->bbox.miny -= cm->geotransform[4]/2 + cm->geotransform[5]/2;
-      }
-    }
+  /* -------------------------------------------------------------------- */
+  /*      Load map with the layer (coverage) coordinate system.  We       */
+  /*      really need a set projectionObj from projectionObj function!    */
+  /* -------------------------------------------------------------------- */
+  char *layer_proj = msGetProjectionString( &(layer->projection) );
+
+  if (msLoadProjectionString(&(map->projection), layer_proj) != 0)
+    return msWCSException( map, NULL, NULL, params->version );
 
-/* -------------------------------------------------------------------- */
-/*      Reset resolution.                                               */
-/* -------------------------------------------------------------------- */
-    if( params->resx != 0.0 )
-    {
-        params->resx = cm->geotransform[1] * params->resx;
-        params->resy = fabs(cm->geotransform[5] * params->resy);
+  free( layer_proj );
+  layer_proj = NULL;
+
+  /* -------------------------------------------------------------------- */
+  /*      Reset bounding box.                                             */
+  /* -------------------------------------------------------------------- */
+  if( params->bbox.maxx != params->bbox.minx ) {
+    rectObj orig_bbox = params->bbox;
+
+    params->bbox.minx =
+      cm->geotransform[0]
+      + orig_bbox.minx * cm->geotransform[1]
+      + orig_bbox.miny * cm->geotransform[2];
+    params->bbox.maxy =
+      cm->geotransform[3]
+      + orig_bbox.minx * cm->geotransform[4]
+      + orig_bbox.miny * cm->geotransform[5];
+    params->bbox.maxx =
+      cm->geotransform[0]
+      + (orig_bbox.maxx+1) * cm->geotransform[1]
+      + (orig_bbox.maxy+1) * cm->geotransform[2];
+    params->bbox.miny =
+      cm->geotransform[3]
+      + (orig_bbox.maxx+1) * cm->geotransform[4]
+      + (orig_bbox.maxy+1) * cm->geotransform[5];
+
+    /* WCS 1.1 boundbox is center of pixel oriented. */
+    if( strncasecmp(params->version,"1.1",3) == 0 ) {
+      params->bbox.minx += cm->geotransform[1]/2 + cm->geotransform[2]/2;
+      params->bbox.maxx -= cm->geotransform[1]/2 + cm->geotransform[2]/2;
+      params->bbox.maxy += cm->geotransform[4]/2 + cm->geotransform[5]/2;
+      params->bbox.miny -= cm->geotransform[4]/2 + cm->geotransform[5]/2;
     }
+  }
 
-    return MS_SUCCESS;
+  /* -------------------------------------------------------------------- */
+  /*      Reset resolution.                                               */
+  /* -------------------------------------------------------------------- */
+  if( params->resx != 0.0 ) {
+    params->resx = cm->geotransform[1] * params->resx;
+    params->resy = fabs(cm->geotransform[5] * params->resy);
+  }
+
+  return MS_SUCCESS;
 }
 
 /************************************************************************/
 /*                          msWCSGetCoverage()                          */
 /************************************************************************/
 
-static int msWCSGetCoverage(mapObj *map, cgiRequestObj *request, 
+static int msWCSGetCoverage(mapObj *map, cgiRequestObj *request,
                             wcsParamsObj *params, owsRequestObj *ows_request)
 {
   imageObj   *image;
@@ -1582,65 +1575,74 @@ static int msWCSGetCoverage(mapObj *map, cgiRequestObj *request,
   }
 
   if(!params->time && !params->bbox.minx && !params->bbox.miny
-     && !params->bbox.maxx && !params->bbox.maxy) {
+      && !params->bbox.maxx && !params->bbox.maxy) {
     msSetError(MS_WCSERR, "One of BBOX or TIME is required", "msWCSGetCoverage()");
     return msWCSException(map, "MissingParameterValue", "bbox/time", params->version);
   }
 
   if( params->coverages == NULL || params->coverages[0] == NULL ) {
-    msSetError( MS_WCSERR, 
-                "Required parameter COVERAGE was not supplied.", 
+    msSetError( MS_WCSERR,
+                "Required parameter COVERAGE was not supplied.",
                 "msWCSGetCoverage()");
     return msWCSException(map, "MissingParameterValue", "coverage", params->version);
   }
 
   /* For WCS 1.1, we need to normalize the axis order of the BBOX and
      resolution values some coordinate systems (eg. EPSG geographic) */
-  if( strncasecmp(params->version,"1.0",3) != 0 
-      && params->crs != NULL 
-      && strncasecmp(params->crs,"urn:",4) == 0 )
-  {
-      projectionObj proj;
-
-      msInitProjection( &proj );
-      if( msLoadProjectionString( &proj, (char *) params->crs ) == 0 )
-      {
-          msAxisNormalizePoints( &proj, 1, 
-                                 &(params->bbox.minx), 
-                                 &(params->bbox.miny) );
-          msAxisNormalizePoints( &proj, 1, 
-                                 &(params->bbox.maxx), 
-                                 &(params->bbox.maxy) );
-          msAxisNormalizePoints( &proj, 1, 
-                                 &(params->resx), 
-                                 &(params->resy) );
-          msAxisNormalizePoints( &proj, 1, 
-                                 &(params->originx), 
-                                 &(params->originy) );
-      }
-      else
-          msResetErrorList();
-      msFreeProjection( &proj );
+  if( strncasecmp(params->version,"1.0",3) != 0
+      && params->crs != NULL
+      && strncasecmp(params->crs,"urn:",4) == 0 ) {
+    projectionObj proj;
+
+    msInitProjection( &proj );
+    if( msLoadProjectionString( &proj, (char *) params->crs ) == 0 ) {
+      msAxisNormalizePoints( &proj, 1,
+                             &(params->bbox.minx),
+                             &(params->bbox.miny) );
+      msAxisNormalizePoints( &proj, 1,
+                             &(params->bbox.maxx),
+                             &(params->bbox.maxy) );
+      msAxisNormalizePoints( &proj, 1,
+                             &(params->resx),
+                             &(params->resy) );
+      msAxisNormalizePoints( &proj, 1,
+                             &(params->originx),
+                             &(params->originy) );
+    } else
+      msResetErrorList();
+    msFreeProjection( &proj );
   }
-  
+
   /* find the layer we are working with */
   lp = NULL;
   for(i=0; i<map->numlayers; i++) {
-     coverageName = msOWSGetEncodeMetadata(&(GET_LAYER(map, i)->metadata), "CO", "name", GET_LAYER(map, i)->name);
+    coverageName = msOWSGetEncodeMetadata(&(GET_LAYER(map, i)->metadata), "CO", "name", GET_LAYER(map, i)->name);
     if( EQUAL(coverageName, params->coverages[0]) &&
         (msIntegerInArray(GET_LAYER(map, i)->index, ows_request->enabled_layers, ows_request->numlayers)) ) {
       lp = GET_LAYER(map, i);
+      free( coverageName );
       break;
     }
+    free( coverageName );
   }
 
   if(lp == NULL) {
-    msSetError( MS_WCSERR, "COVERAGE=%s not found, not in supported layer list.", "msWCSGetCoverage()", params->coverages[0] );
+    msSetError( MS_WCSERR, "COVERAGE=%s not found, not in supported layer list. A layer might be disabled for \
+this request. Check wcs/ows_enable_request settings.", "msWCSGetCoverage()", params->coverages[0] );
     return msWCSException(map, "InvalidParameterValue", "coverage", params->version);
   }
 
   /* make sure the layer is on */
   lp->status = MS_ON;
+  
+  /* If the layer has no projection set, set it to the map's projection (#4079) */
+  if(lp->projection.numargs <=0) {
+    char *map_original_srs = msGetProjectionString(&(map->projection));
+    if (msLoadProjectionString(&(lp->projection), map_original_srs) != 0) {
+      msSetError( MS_WCSERR, "Error when setting map projection to a layer with no projection", "msWCSGetCoverage()" );
+      return msWCSException(map, NULL, NULL, params->version);
+    }
+  }
 
   /* we need the coverage metadata, since things like numbands may not be available otherwise */
   status = msWCSGetCoverageMetadata(lp, &cm);
@@ -1671,14 +1673,14 @@ static int msWCSGetCoverage(mapObj *map, cgiRequestObj *request,
 
     iUnits = GetMapserverUnitUsingProj(&(map->projection));
     if (iUnits != -1)
-        map->units = iUnits;
+      map->units = iUnits;
   }
 
   /* did we get a TIME value (support only a single value for now) */
   if(params->time) {
     int tli;
     layerObj *tlp=NULL;
-    
+
     /* need to handle NOW case */
 
     /* check format of TIME parameter */
@@ -1690,20 +1692,20 @@ static int msWCSGetCoverage(mapObj *map, cgiRequestObj *request,
       msSetError( MS_WCSERR, "Temporal ranges are not supported, only individual values.", "msWCSGetCoverage()" );
       return msWCSException(map, "InvalidParameterValue", "time", params->version);
     }
-      
+
     /* TODO: will need to expand this check if a time period is supported */
     value = msOWSLookupMetadata(&(lp->metadata), "CO", "timeposition");
     if(!value) {
       msSetError( MS_WCSERR, "The coverage does not support temporal subsetting.", "msWCSGetCoverage()" );
       return msWCSException(map, "InvalidParameterValue", "time", params->version );
     }
-    
+
     /* check if timestamp is covered by the wcs_timeposition definition */
     if (msValidateTimeValue(params->time, value) == MS_FALSE) {
       msSetError( MS_WCSERR, "The coverage does not have a time position of %s.", "msWCSGetCoverage()", params->time );
       return msWCSException(map, "InvalidParameterValue", "time", params->version);
     }
-      
+
     /* make sure layer is tiled appropriately */
     if(!lp->tileindex) {
       msSetError( MS_WCSERR, "Underlying layer is not tiled, unable to do temporal subsetting.", "msWCSGetCoverage()" );
@@ -1723,18 +1725,18 @@ static int msWCSGetCoverage(mapObj *map, cgiRequestObj *request,
       msSetError( MS_WCSERR, "Not enough information available to filter.", "msWCSGetCoverage()" );
       return msWCSException(map, NULL, NULL, params->version);
     }
-      
+
     /* override filteritem if specified in metadata */
     if(value) {
       if(tlp->filteritem) free(tlp->filteritem);
       tlp->filteritem = msStrdup(value);
     }
-      
+
     /* finally set the filter */
     freeExpression(&tlp->filter);
     msLayerSetTimeFilter(tlp, params->time, value);
   }
-           
+
   if( strncasecmp(params->version,"1.0",3) == 0 )
     status = msWCSGetCoverageBands10( map, request, params, lp, &bandlist );
   else
@@ -1755,14 +1757,14 @@ static int msWCSGetCoverage(mapObj *map, cgiRequestObj *request,
     }
   }
 
-  /* WCS 1.1+ GridOrigin is effectively resetting the minx/maxy 
+  /* WCS 1.1+ GridOrigin is effectively resetting the minx/maxy
      BOUNDINGBOX values, so apply that here */
   if( params->originx != 0.0 || params->originy != 0.0 ) {
     assert( strncasecmp(params->version,"1.0",3) != 0 ); /* should always be 1.0 in this logic. */
     params->bbox.minx = params->originx;
     params->bbox.maxy = params->originy;
   }
-    
+
   /* if necessary, project the BBOX to the map->projection */
   if(params->response_crs && params->crs) {
     projectionObj tmp_proj;
@@ -1786,7 +1788,7 @@ static int msWCSGetCoverage(mapObj *map, cgiRequestObj *request,
     params->resx = (params->bbox.maxx -params->bbox.minx) / params->width;
     params->resy = (params->bbox.maxy -params->bbox.miny) / params->height;
   }
-    
+
   /* compute cellsize/res from bbox and raster size. */
   if( (params->width == 0 || params->height == 0) && params->resx != 0 && params->resy != 0 ) {
 
@@ -1832,18 +1834,17 @@ static int msWCSGetCoverage(mapObj *map, cgiRequestObj *request,
       return msWCSException(map, "InvalidParameterValue", "interpolation", params->version);
     }
   }
-   
+
   /* apply region and size to map object.  */
   map->width = params->width;
   map->height = params->height;
 
   /* Are we exceeding the MAXSIZE limit on result size? */
-  if(map->width > map->maxsize || map->height > map->maxsize )
-  {
-      msSetError(MS_WCSERR, "Raster size out of range, width and height of resulting coverage must be no more than MAXSIZE=%d.", "msWCSGetCoverage()", map->maxsize);
+  if(map->width > map->maxsize || map->height > map->maxsize ) {
+    msSetError(MS_WCSERR, "Raster size out of range, width and height of resulting coverage must be no more than MAXSIZE=%d.", "msWCSGetCoverage()", map->maxsize);
 
-      return msWCSException(map, "InvalidParameterValue", 
-                            "width/height", params->version);
+    return msWCSException(map, "InvalidParameterValue",
+                          "width/height", params->version);
   }
 
   /* adjust OWS BBOX to MapServer's pixel model */
@@ -1855,14 +1856,14 @@ static int msWCSGetCoverage(mapObj *map, cgiRequestObj *request,
   }
 
   map->extent = params->bbox;
- 
+
   map->cellsize = params->resx; /* pick one, MapServer only supports square cells (what about msAdjustExtent here!) */
 
   msMapComputeGeotransform(map);
 
-  /* Do we need to fake out stuff for rotated support? */ 
-  if( map->gt.need_geotransform ) 
-      msMapSetFakedExtent( map ); 
+  /* Do we need to fake out stuff for rotated support? */
+  if( map->gt.need_geotransform )
+    msMapSetFakedExtent( map );
 
   map->projection.gt = map->gt;
 
@@ -1884,11 +1885,11 @@ static int msWCSGetCoverage(mapObj *map, cgiRequestObj *request,
   covextent.maxy = cm.extent.maxy;
 
   if(msRectOverlap(&reqextent, &covextent) == MS_FALSE) {
-      msSetError(MS_WCSERR, "Requested BBOX (%.15g,%.15g,%.15g,%.15g) is outside requested coverage BBOX (%.15g,%.15g,%.15g,%.15g)",
-                            "msWCSGetCoverage()",
-                            reqextent.minx, reqextent.miny, reqextent.maxx, reqextent.maxy,
-                            covextent.minx, covextent.miny, covextent.maxx, covextent.maxy);
-      return msWCSException(map, "NoApplicableCode", "bbox", params->version);
+    msSetError(MS_WCSERR, "Requested BBOX (%.15g,%.15g,%.15g,%.15g) is outside requested coverage BBOX (%.15g,%.15g,%.15g,%.15g)",
+               "msWCSGetCoverage()",
+               reqextent.minx, reqextent.miny, reqextent.maxx, reqextent.maxy,
+               covextent.minx, covextent.miny, covextent.maxx, covextent.maxy);
+    return msWCSException(map, "NoApplicableCode", "bbox", params->version);
   }
 
   /* check and make sure there is a format, and that it's valid (TODO: make sure in the layer metadata) */
@@ -1899,14 +1900,14 @@ static int msWCSGetCoverage(mapObj *map, cgiRequestObj *request,
   msApplyDefaultOutputFormats(map);
   if(msGetOutputFormatIndex(map,params->format) == -1) {
     msSetError( MS_WCSERR,  "Unrecognized value for the FORMAT parameter.", "msWCSGetCoverage()" );
-    return msWCSException(map, "InvalidParameterValue", "format", 
+    return msWCSException(map, "InvalidParameterValue", "format",
                           params->version );
   }
 
   /* create a temporary outputformat (we likely will need to tweak parts) */
   format = msCloneOutputFormat(msSelectOutputFormat(map,params->format));
-  msApplyOutputFormat(&(map->outputformat), format, MS_NOOVERRIDE, MS_NOOVERRIDE, MS_NOOVERRIDE); 
-           
+  msApplyOutputFormat(&(map->outputformat), format, MS_NOOVERRIDE, MS_NOOVERRIDE, MS_NOOVERRIDE);
+
   if(!bandlist) { /* build a bandlist (default is ALL bands) */
     bufferSize = cm.bandcount*30+30;
     bandlist = (char *) msSmallMalloc(bufferSize);
@@ -1917,13 +1918,14 @@ static int msWCSGetCoverage(mapObj *map, cgiRequestObj *request,
 
   /* apply nullvalue to the output format object if we have it */
   if((value = msOWSLookupMetadata(&(lp->metadata), "CO", "rangeset_nullvalue")) != NULL) {
-      msSetOutputFormatOption( map->outputformat, "NULLVALUE", value );
+    msSetOutputFormatOption( map->outputformat, "NULLVALUE", value );
   }
-  
+
   msLayerSetProcessingKey(lp, "BANDS", bandlist);
   snprintf(numbands, sizeof(numbands), "%d", msCountChars(bandlist, ',')+1);
   msSetOutputFormatOption(map->outputformat, "BAND_COUNT", numbands);
-               
+  free( bandlist );
+
   /* create the image object  */
   if(!map->outputformat) {
     msSetError(MS_WCSERR, "The map outputformat is missing!", "msWCSGetCoverage()");
@@ -1936,49 +1938,44 @@ static int msWCSGetCoverage(mapObj *map, cgiRequestObj *request,
   }
 
   if( image == NULL )
-      return msWCSException(map, NULL, NULL, params->version );
+    return msWCSException(map, NULL, NULL, params->version );
   if( MS_RENDERER_RAWDATA(map->outputformat) ) {
-     status = msDrawRasterLayerLow( map, lp, image, NULL );
+    status = msDrawRasterLayerLow( map, lp, image, NULL );
   } else {
-     MS_IMAGE_RENDERER(image)->getRasterBufferHandle(image,&rb);
+    MS_IMAGE_RENDERER(image)->getRasterBufferHandle(image,&rb);
 
-     /* Actually produce the "grid". */
-     status = msDrawRasterLayerLow( map, lp, image, &rb );
+    /* Actually produce the "grid". */
+    status = msDrawRasterLayerLow( map, lp, image, &rb );
   }
   if( status != MS_SUCCESS ) {
-      return msWCSException(map, NULL, NULL, params->version );
+    return msWCSException(map, NULL, NULL, params->version );
   }
 
 
-  if( strncmp(params->version, "1.1",3) == 0 )
-  {
-      msWCSReturnCoverage11( params, map, image );
-  }
-  else /* WCS 1.0.0 - just return the binary data with a content type */
-  {
-      const char *fo_filename;
-
-      /* Do we have a predefined filename? */
-      fo_filename = msGetOutputFormatOption( format, "FILENAME", NULL );
-      if( fo_filename )
-            msIO_fprintf( stdout, 
-                          "Content-Disposition: attachment; filename=%s\n",
-                          fo_filename );
-
-      /* Emit back to client. */
-      msIO_printf("Content-type: %s%c%c", 
-                  MS_IMAGE_MIME_TYPE(map->outputformat), 10,10);
-      status = msSaveImage(map, image, NULL);
-      
-      if( status != MS_SUCCESS )
-      {
-          /* unfortunately, the image content type will have already been sent
-             but that is hard for us to avoid.  The main error that could happen
-             here is a misconfigured tmp directory or running out of space. */
-          return msWCSException(map, NULL, NULL, params->version );
-      }
+  if( strncmp(params->version, "1.1",3) == 0 ) {
+    msWCSReturnCoverage11( params, map, image );
+  } else { /* WCS 1.0.0 - just return the binary data with a content type */
+    const char *fo_filename;
+
+    /* Do we have a predefined filename? */
+    fo_filename = msGetOutputFormatOption( format, "FILENAME", NULL );
+    if( fo_filename )
+      msIO_setHeader("Content-Disposition","attachment; filename=%s",
+                     fo_filename );
+
+    /* Emit back to client. */
+    msIO_setHeader("Content-Type",MS_IMAGE_MIME_TYPE(map->outputformat));
+    msIO_sendHeaders();
+    status = msSaveImage(map, image, NULL);
+
+    if( status != MS_SUCCESS ) {
+      /* unfortunately, the image content type will have already been sent
+         but that is hard for us to avoid.  The main error that could happen
+         here is a misconfigured tmp directory or running out of space. */
+      return msWCSException(map, NULL, NULL, params->version );
+    }
   }
-      
+
   /* Cleanup */
   msFreeImage(image);
   msApplyOutputFormat(&(map->outputformat), NULL, MS_NOOVERRIDE, MS_NOOVERRIDE, MS_NOOVERRIDE);
@@ -1996,130 +1993,219 @@ static int msWCSGetCoverage(mapObj *map, cgiRequestObj *request,
 
 int msWCSDispatch(mapObj *map, cgiRequestObj *request, owsRequestObj *ows_request)
 {
-#ifdef USE_WCS_SVR
-  wcsParamsObj *params;  
-  int retVal = MS_DONE;
-
-  /* First try to dispatch WCS 2.0.0.                                   */
-  /* TODO: Need to implement proper version negotiation (OWS Common)    */
-  /* once WCS 2.0.0 is fully specified.                                 */
-  /* Currently WCS 2.0.0 is only available if explicitly requested.     */
-  if ((retVal = msWCSDispatch20(map, request, ows_request)) != MS_DONE )
-  {
-    return retVal;
-  }
-
-  /* populate the service parameters */
-  params = msWCSCreateParams();
-  if( msWCSParseRequest(request, params, map) == MS_FAILURE )
-  {
-      msWCSFreeParams(params); /* clean up */
-      free(params);
-      return MS_FAILURE;
-  }
+#if defined(USE_WCS_SVR)
+  void *params = NULL; /* either wcsParamsObj* or wcs20ParamsObj* */
+  int status, retVal, operation;
+
+  /* If SERVICE is not set or not WCS exit gracefully. */
+  if (ows_request->service == NULL
+      || !EQUAL(ows_request->service, "WCS")) {
+    return MS_DONE;
+  }
+
+  /* If no REQUEST is set, exit with an error */
+  if (ows_request->request == NULL) {
+    /* The request has to be set. */
+    msSetError(MS_WCSERR, "Missing REQUEST parameter",
+               "msWCSDispatch()");
+    return msWCSException(map, "MissingParameterValue", "request",
+                          ows_request->version );
+  }
+
+  if (EQUAL(ows_request->request, "GetCapabilities")) {
+    operation = MS_WCS_GET_CAPABILITIES;
+  } else if (EQUAL(ows_request->request, "DescribeCoverage")) {
+    operation = MS_WCS_DESCRIBE_COVERAGE;
+  } else if (EQUAL(ows_request->request, "GetCoverage")) {
+    operation = MS_WCS_GET_COVERAGE;
+  } else {
+    msSetError(MS_WCSERR, "Invalid REQUEST parameter \"%s\"",
+               "msWCSDispatch()", ows_request->request);
+    return msWCSException(map, "InvalidParameterValue", "request",
+                          ows_request->version);
+  }
+
+  /* Check the number of enabled layers for the REQUEST */
+  msOWSRequestLayersEnabled(map, "C", ows_request->request, ows_request);
+  if (ows_request->numlayers == 0) {
+    int caps_globally_enabled = MS_FALSE, disabled = MS_FALSE;
+    const char *enable_request;
+    if(operation == MS_WCS_GET_CAPABILITIES) {
+      enable_request = msOWSLookupMetadata(&map->web.metadata, "OC", "enable_request");
+      caps_globally_enabled = msOWSParseRequestMetadata(enable_request, "GetCapabilities", &disabled);
+    }
 
-  /* If SERVICE is specified then it MUST be "WCS" */
-  if(params->service && strcasecmp(params->service, "WCS") != 0)
-  {
-      msWCSFreeParams(params); /* clean up */
-      free(params);
-      msDebug("msWCSDispatch(): SERVICE is not WCS\n");
-      return MS_DONE;
+    if(caps_globally_enabled == MS_FALSE) {
+      msSetError(MS_WCSERR, "WCS request not enabled. Check "
+                 "wcs/ows_enable_request settings.",
+                 "msWCSDispatch()");
+      return msWCSException(map, "InvalidParameterValue", "request",
+                            ows_request->version );
+    }
   }
 
-  /* If SERVICE and REQUEST not included then not a WCS request */
-  if(!params->service && !params->request)
-  {
-      msWCSFreeParams(params); /* clean up */
-      free(params);
-      msDebug("msWCSDispatch(): SERVICE and REQUEST not included\n");
-      return MS_DONE;
-  }
+  /* Check the VERSION parameter */
+  if (ows_request->version == NULL) {
+    /* If the VERSION parameter is not set, it is either */
+    /* an error (Describe and GetCoverage), or it has to */
+    /* be determined (GetCapabilities). To determine the */
+    /* version, the request has to be fully parsed to    */
+    /* obtain the ACCEPTVERSIONS parameter. If this is   */
+    /* present also, set version to "2.0.1".             */
+
+    if (operation == MS_WCS_GET_CAPABILITIES) {
+      /* Parse it as if it was a WCS 2.0 request */
+      wcs20ParamsObjPtr params_tmp = msWCSCreateParamsObj20();
+      status = msWCSParseRequest20(map, request, ows_request, params_tmp);
+      if (status == MS_FAILURE) {
+        msWCSFreeParamsObj20(params);
+        return msWCSException(map, "InvalidParameterValue",
+                              "request", "2.0.1");
+      }
 
-  msOWSRequestLayersEnabled(map, "C", params->request, ows_request);
-  if (ows_request->numlayers == 0)
-  {
-      msSetError(MS_WCSERR, "WCS request not enabled. Check wcs/ows_enable_request settings.", "msWCSDispatch()");
-      msWCSException(map, "InvalidParameterValue", "request",
-                     params->version );
-      msWCSFreeParams(params); /* clean up */
-      free(params);
-      params = NULL;
-      return MS_FAILURE;
-  }
+      /* VERSION negotiation */
+      if (params_tmp->accept_versions != NULL) {
+        /* choose highest acceptable */
+        int i, highest_version = 0;
+        char version_string[OWS_VERSION_MAXLEN];
+        for(i = 0; params_tmp->accept_versions[i] != NULL; ++i) {
+          int version = msOWSParseVersionString(params_tmp->accept_versions[i]);
+          if (version == OWS_VERSION_BADFORMAT) {
+            msWCSFreeParamsObj20(params_tmp);
+            return msWCSException(map, "InvalidParameterValue",
+                                  "version", NULL );
+          }
+          if(version > highest_version) {
+            highest_version = version;
+          }
+        }
+        msOWSGetVersionString(highest_version, version_string);
+        params_tmp->version = msStrdup(version_string);
+        ows_request->version = msStrdup(version_string);
+      } else {
+        /* set to highest acceptable */
+        params_tmp->version = msStrdup("2.0.1");
+        ows_request->version = msStrdup("2.0.1");
+      }
 
-  /*
-  ** ok, it's a WCS request, check what we can at a global level and then dispatch to the various request handlers
-  */
+      /* check if we can keep the params object */
+      if (EQUAL(params_tmp->version, "2.0.1")) {
+        params = params_tmp;
+      } else {
+        msWCSFreeParamsObj20(params_tmp);
+      }
+    } else { /* operation != GetCapabilities */
+      /* VERSION is mandatory in other requests */
+      msSetError(MS_WCSERR, "VERSION parameter not set.",
+                 "msWCSDispatch()");
+      return msWCSException(map, "InvalidParameterValue", "version",
+                            NULL );
+    }
+  } else {
+    /* Parse the VERSION parameter */
+    int requested_version = msOWSParseVersionString(ows_request->version);
+    if (requested_version == OWS_VERSION_BADFORMAT) {
+      /* Return an error if the VERSION is */
+      /* in an unsupported format.         */
+      return msWCSException(map, "InvalidParameterValue",
+                            "version", NULL );
+    }
 
-  /* check for existence of REQUEST parameter */
-  if (!params->request) {
-      msSetError(MS_WCSERR, "Missing REQUEST parameter", "msWCSDispatch()");
-      msWCSException(map, "MissingParameterValue", "request",
-                     params->version );
-    msWCSFreeParams(params); /* clean up */
-    free(params);
-    params = NULL;
-    return MS_FAILURE;
+    if (operation == MS_WCS_GET_CAPABILITIES) {
+      /* In case of GetCapabilities, make  */
+      char version_string[OWS_VERSION_MAXLEN];
+      int version, supported_versions[] =
+      {OWS_2_0_1, OWS_2_0_0, OWS_1_1_2, OWS_1_1_1, OWS_1_1_0, OWS_1_0_0};
+      version = msOWSNegotiateVersion(requested_version,
+                                      supported_versions,
+                                      sizeof(supported_versions)/sizeof(int));
+      msOWSGetVersionString(version, version_string);
+      msFree(ows_request->version);
+      ows_request->version = msStrdup(version_string);
+    }
   }
 
+  /* VERSION specific request handler */
+  if (strcmp(ows_request->version, "1.0.0") == 0
+      || strcmp(ows_request->version, "1.1.0") == 0
+      || strcmp(ows_request->version, "1.1.1") == 0
+      || strcmp(ows_request->version, "1.1.2") == 0) {
+    params = msWCSCreateParams();
+    status = msWCSParseRequest(request, params, map);
+    if (status == MS_FAILURE) {
+      msWCSFreeParams(params);
+      free(params);
+      return msWCSException(map, "InvalidParameterValue",
+                            "request", "2.0");
+    }
 
-  /* if either DescribeCoverage or GetCoverage, and version not passed
-     then return an exception */
-  if (((strcasecmp(params->request, "DescribeCoverage") == 0) ||
-     (strcasecmp(params->request, "GetCoverage") == 0)) &&
-     (!params->version)) {
-    msSetError(MS_WCSERR, "Missing VERSION parameter", "msWCSDispatch()");
-    msWCSException(map, "MissingParameterValue", "version", params->version);
-    msWCSFreeParams(params); /* clean up */
+    if (operation == MS_WCS_GET_CAPABILITIES) {
+      retVal = msWCSGetCapabilities(map, params, request, ows_request);
+    } else if (operation == MS_WCS_DESCRIBE_COVERAGE) {
+      retVal = msWCSDescribeCoverage(map, params, ows_request);
+    } else if (operation == MS_WCS_GET_COVERAGE) {
+      retVal = msWCSGetCoverage(map, request, params, ows_request);
+    }
+    msWCSFreeParams(params);
     free(params);
-    params = NULL;
-    return MS_FAILURE;
-  }
-
-  /* For GetCapabilities, if version is not set, then set to the highest
-     version supported.  This should be cleaned up once #996 gets implemented */
-  if (!params->version || strcasecmp(params->version, "") == 0 || params->version == NULL) { /* this is a GetCapabilities request, set version */
-    params->version = msStrdup("1.1.2");
-  }
+    return retVal;
+  } else if (strcmp(ows_request->version, "2.0.0") == 0
+             || strcmp(ows_request->version, "2.0.1") == 0) {
+#if defined(USE_LIBXML2)
+    int i;
+
+    if (params == NULL) {
+      params = msWCSCreateParamsObj20();
+      status = msWCSParseRequest20(map, request, ows_request, params);
+      if (status == MS_FAILURE) {
+        msWCSFreeParamsObj20(params);
+        return msWCSException(map, "InvalidParameterValue",
+                              "request", "2.0.1");
+      }
+    }
 
-  /* version is optional, but we do set a default value of 1.1.2, make sure request isn't for something different */
-  if((strcmp(params->version, "1.0.0") != 0
-     && strcmp(params->version, "1.1.0") != 0
-     && strcmp(params->version, "1.1.1") != 0
-     && strcmp(params->version, "1.1.2") != 0)
-     && strcasecmp(params->request, "GetCapabilities") != 0) {
-    msSetError(MS_WCSERR, "WCS Server does not support VERSION %s.", "msWCSDispatch()", params->version);
-    msWCSException(map, "InvalidParameterValue", "version", params->version);
-  
-    msWCSFreeParams(params); /* clean up */
-    free(params);
-    params = NULL;
+    /* check if all layer names are valid NCNames */
+    for(i = 0; i < map->numlayers; ++i) {
+      if(!msWCSIsLayerSupported(map->layers[i]))
+        continue;
+
+      /* Check if each layers name is a valid NCName. */
+      if (msEvalRegex("^[a-zA-z_][a-zA-Z0-9_.-]*$" , map->layers[i]->name) == MS_FALSE) {
+        msSetError(MS_WCSERR, "Layer name '%s' is not a valid NCName.",
+                   "msWCSDispatch()", map->layers[i]->name);
+        msWCSFreeParamsObj20(params);
+        return msWCSException(map, "mapserv", "Internal", "2.0.1");
+      }
+    }
 
-    return MS_FAILURE;
+    /* Call operation specific functions */
+    if (operation == MS_WCS_GET_CAPABILITIES) {
+      retVal = msWCSGetCapabilities20(map, request, params, ows_request);
+    } else if (operation == MS_WCS_DESCRIBE_COVERAGE) {
+      retVal = msWCSDescribeCoverage20(map, params, ows_request);
+    } else if (operation == MS_WCS_GET_COVERAGE) {
+      retVal = msWCSGetCoverage20(map, request, params, ows_request);
+    } else {
+      msSetError(MS_WCSERR, "Invalid request '%s'.",
+                 "msWCSDispatch20()", ows_request->request);
+      retVal = msWCSException20(map, "InvalidParameterValue",
+                                "request", "2.0.1");
+    }
+    /* clean up */
+    msWCSFreeParamsObj20(params);
+    return retVal;
+#else /* def USE_LIBXML2 */
+    msSetError(MS_WCSERR, "WCS 2.0 needs mapserver to be compiled with libxml2.",
+               "msWCSDispatch()");
+    return msWCSException(map, "mapserv", "NoApplicableCode", "2.0.1");
+#endif /* def USE_LIBXML2 */
+  } else { /* unsupported version */
+    msSetError(MS_WCSERR, "WCS Server does not support VERSION %s.",
+               "msWCSDispatch()", ows_request->version);
+    return msWCSException(map, "InvalidParameterValue",
+                          "version", ows_request->version);
   }
 
-  /*
-  ** Start dispatching requests
-  */
-  if(strcasecmp(params->request, "GetCapabilities") == 0)    
-    retVal = msWCSGetCapabilities(map, params, request, ows_request);
-  else if(strcasecmp(params->request, "DescribeCoverage") == 0)    
-    retVal = msWCSDescribeCoverage(map, params, ows_request);
-  else if(strcasecmp(params->request, "GetCoverage") == 0)    
-    retVal = msWCSGetCoverage(map, request, params, ows_request);
-  else {
-    msSetError(MS_WCSERR, "Invalid REQUEST parameter \"%s\"", "msWCSDispatch()", params->request);
-    msWCSException(map, "InvalidParameterValue", "request", params->version);
-    msWCSFreeParams(params); /* clean up */
-    free(params);
-    params = NULL;
-    return MS_FAILURE;
-  }  
-
-  msWCSFreeParams(params); /* clean up */
-  free(params);
-  return retVal; /* not a WCS request, let MapServer take it */
 #else
   msSetError(MS_WCSERR, "WCS server support is not available.", "msWCSDispatch()");
   return MS_FAILURE;
@@ -2136,11 +2222,11 @@ int msWCSGetCoverageMetadata( layerObj *layer, coverageMetadataObj *cm )
   char  *srs_urn = NULL;
   int i = 0;
   if ( msCheckParentPointer(layer->map,"map")==MS_FAILURE )
-	return MS_FAILURE;
+    return MS_FAILURE;
 
-/* -------------------------------------------------------------------- */
-/*      Get the SRS in WCS 1.0 format (eg. EPSG:n)                      */
-/* -------------------------------------------------------------------- */
+  /* -------------------------------------------------------------------- */
+  /*      Get the SRS in WCS 1.0 format (eg. EPSG:n)                      */
+  /* -------------------------------------------------------------------- */
   if((cm->srs = msOWSGetEPSGProj(&(layer->projection), &(layer->metadata), "CO", MS_TRUE)) == NULL) {
     if((cm->srs = msOWSGetEPSGProj(&(layer->map->projection), &(layer->map->web.metadata), "CO", MS_TRUE)) == NULL) {
       msSetError(MS_WCSERR, "Unable to determine the SRS for this layer, no projection defined and no metadata available.", "msWCSGetCoverageMetadata()");
@@ -2148,39 +2234,36 @@ int msWCSGetCoverageMetadata( layerObj *layer, coverageMetadataObj *cm )
     }
   }
 
-/* -------------------------------------------------------------------- */
-/*      Get the SRS in urn format.                                      */
-/* -------------------------------------------------------------------- */
-  if((srs_urn = msOWSGetProjURN(&(layer->projection), &(layer->metadata), 
+  /* -------------------------------------------------------------------- */
+  /*      Get the SRS in urn format.                                      */
+  /* -------------------------------------------------------------------- */
+  if((srs_urn = msOWSGetProjURN(&(layer->projection), &(layer->metadata),
                                 "CO", MS_TRUE)) == NULL) {
-      srs_urn = msOWSGetProjURN(&(layer->map->projection), 
-                                &(layer->map->web.metadata), 
-                                "CO", MS_TRUE);
-  }
-  
-  if( srs_urn != NULL )
-  {
-      if( strlen(srs_urn) > sizeof(cm->srs_urn) - 1 )
-      {
-          msSetError(MS_WCSERR, "SRS URN too long!", 
-                     "msWCSGetCoverageMetadata()");
-          return MS_FAILURE;
-      }
-          
-      strcpy( cm->srs_urn, srs_urn );
-      msFree( srs_urn );
+    srs_urn = msOWSGetProjURN(&(layer->map->projection),
+                              &(layer->map->web.metadata),
+                              "CO", MS_TRUE);
   }
-  else
-      cm->srs_urn[0] = '\0';
-          
+
+  if( srs_urn != NULL ) {
+    if( strlen(srs_urn) > sizeof(cm->srs_urn) - 1 ) {
+      msSetError(MS_WCSERR, "SRS URN too long!",
+                 "msWCSGetCoverageMetadata()");
+      return MS_FAILURE;
+    }
+
+    strcpy( cm->srs_urn, srs_urn );
+    msFree( srs_urn );
+  } else
+    cm->srs_urn[0] = '\0';
+
   /* -------------------------------------------------------------------- */
   /*      If we have "virtual dataset" metadata on the layer, then use    */
   /*      that in preference to inspecting the file(s).                   */
   /*      We require extent and either size or resolution.                */
   /* -------------------------------------------------------------------- */
-  if( msOWSLookupMetadata(&(layer->metadata), "CO", "extent") != NULL 
+  if( msOWSLookupMetadata(&(layer->metadata), "CO", "extent") != NULL
       && (msOWSLookupMetadata(&(layer->metadata), "CO", "resolution") != NULL
-          || msOWSLookupMetadata(&(layer->metadata), "CO", "size") != NULL) ){
+          || msOWSLookupMetadata(&(layer->metadata), "CO", "size") != NULL) ) {
     const char *value;
 
     /* get extent */
@@ -2190,14 +2273,14 @@ int msWCSGetCoverageMetadata( layerObj *layer, coverageMetadataObj *cm )
     cm->extent.maxy = 0.0;
     if( msOWSGetLayerExtent( layer->map, layer, "CO", &cm->extent ) == MS_FAILURE )
       return MS_FAILURE;
-    
+
     /* get resolution */
     cm->xresolution = 0.0;
     cm->yresolution = 0.0;
     if( (value = msOWSLookupMetadata(&(layer->metadata), "CO", "resolution")) != NULL ) {
       char **tokens;
       int n;
-            
+
       tokens = msStringSplit(value, ' ', &n);
       if( tokens == NULL || n != 2 ) {
         msSetError( MS_WCSERR, "Wrong number of arguments for wcs|ows_resolution metadata.", "msWCSGetCoverageMetadata()");
@@ -2215,7 +2298,7 @@ int msWCSGetCoverageMetadata( layerObj *layer, coverageMetadataObj *cm )
     if( (value=msOWSLookupMetadata(&(layer->metadata), "CO", "size")) != NULL ) {
       char **tokens;
       int n;
-            
+
       tokens = msStringSplit(value, ' ', &n);
       if( tokens == NULL || n != 2 ) {
         msSetError( MS_WCSERR, "Wrong number of arguments for wcs|ows_size metadata.", "msWCSGetCoverageDomain()");
@@ -2244,7 +2327,7 @@ int msWCSGetCoverageMetadata( layerObj *layer, coverageMetadataObj *cm )
       msSetError( MS_WCSERR, "Failed to collect extent and resolution for WCS coverage from metadata for layer '%s'.  Need value wcs|ows_resolution or wcs|ows_size values.", "msWCSGetCoverageMetadata()", layer->name );
       return MS_FAILURE;
     }
-        
+
     /* compute geotransform */
     cm->geotransform[0] = cm->extent.minx;
     cm->geotransform[1] = cm->xresolution;
@@ -2292,22 +2375,22 @@ int msWCSGetCoverageMetadata( layerObj *layer, coverageMetadataObj *cm )
     msTryBuildPath3(szPath,  layer->map->mappath, layer->map->shapepath, layer->data);
     decrypted_path = msDecryptStringTokens( layer->map, szPath );
     if( !decrypted_path )
-        return MS_FAILURE;
+      return MS_FAILURE;
 
     msAcquireLock( TLOCK_GDAL );
 
     hDS = GDALOpen( decrypted_path, GA_ReadOnly );
     if( hDS == NULL ) {
       const char *cpl_error_msg = CPLGetLastErrorMsg();
-        
+
       /* we wish to avoid reporting decrypted paths */
-      if( cpl_error_msg != NULL 
+      if( cpl_error_msg != NULL
           && strstr(cpl_error_msg,decrypted_path) != NULL
           && strcmp(decrypted_path,szPath) != 0 )
-          cpl_error_msg = NULL;
-      
+        cpl_error_msg = NULL;
+
       if( cpl_error_msg == NULL )
-          cpl_error_msg = "";
+        cpl_error_msg = "";
 
       msReleaseLock( TLOCK_GDAL );
 
@@ -2328,14 +2411,14 @@ int msWCSGetCoverageMetadata( layerObj *layer, coverageMetadataObj *cm )
     cm->extent.maxx = cm->geotransform[0] + cm->geotransform[1] * cm->xsize + cm->geotransform[2] * cm->ysize;
     cm->extent.miny = cm->geotransform[3] + cm->geotransform[4] * cm->xsize + cm->geotransform[5] * cm->ysize;
     cm->extent.maxy = cm->geotransform[3];
-    
+
     cm->xresolution = cm->geotransform[1];
     cm->yresolution = cm->geotransform[5];
 
     /* TODO: need to set resolution */
-    
+
     cm->bandcount = GDALGetRasterCount( hDS );
-        
+
     if( cm->bandcount == 0 ) {
       msReleaseLock( TLOCK_GDAL );
       msSetError( MS_WCSERR, "Raster file %s has no raster bands.  This cannot be used in a layer.", "msWCSGetCoverageMetadata()", layer->data );
@@ -2344,15 +2427,15 @@ int msWCSGetCoverageMetadata( layerObj *layer, coverageMetadataObj *cm )
 
     hBand = GDALGetRasterBand( hDS, 1 );
     switch( GDALGetRasterDataType( hBand ) ) {
-    case GDT_Byte:
-      cm->imagemode = MS_IMAGEMODE_BYTE;
-      break;
-    case GDT_Int16:
-      cm->imagemode = MS_IMAGEMODE_INT16;
-      break;
-    default:
-      cm->imagemode = MS_IMAGEMODE_FLOAT32;
-      break;
+      case GDT_Byte:
+        cm->imagemode = MS_IMAGEMODE_BYTE;
+        break;
+      case GDT_Int16:
+        cm->imagemode = MS_IMAGEMODE_INT16;
+        break;
+      default:
+        cm->imagemode = MS_IMAGEMODE_FLOAT32;
+        break;
     }
 
     /* color interpretation */
@@ -2366,14 +2449,13 @@ int msWCSGetCoverageMetadata( layerObj *layer, coverageMetadataObj *cm )
     GDALClose( hDS );
     msReleaseLock( TLOCK_GDAL );
   }
- 
+
   /* we must have the bounding box in lat/lon [WGS84(DD)/EPSG:4326] */
   cm->llextent = cm->extent;
-  
+
   /* Already in latlong .. use directly. */
-  if( layer->projection.proj != NULL && pj_is_latlong(layer->projection.proj))
-  {
-      /* no change */
+  if( layer->projection.proj != NULL && pj_is_latlong(layer->projection.proj)) {
+    /* no change */
   }
 
   else if (layer->projection.numargs > 0 && !pj_is_latlong(layer->projection.proj)) /* check the layer projection */
@@ -2390,7 +2472,7 @@ int msWCSGetCoverageMetadata( layerObj *layer, coverageMetadataObj *cm )
 
     snprintf(projstring, sizeof(projstring), "init=epsg:%.20s", cm->srs+5);
     if (msLoadProjectionString(&proj, projstring) != 0) return MS_FAILURE;
-    msProjectRect(&proj, NULL, &(cm->llextent));    
+    msProjectRect(&proj, NULL, &(cm->llextent));
   }
 
   return MS_SUCCESS;
diff --git a/mapwcs.h b/mapwcs.h
index b348185..4dcb53c 100644
--- a/mapwcs.h
+++ b/mapwcs.h
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -46,6 +46,11 @@
 
 #define MS_WCS_GML_COVERAGETYPE_RECTIFIED_GRID_COVERAGE "RectifiedGridCoverage"
 
+enum {
+  MS_WCS_GET_CAPABILITIES,
+  MS_WCS_DESCRIBE_COVERAGE,
+  MS_WCS_GET_COVERAGE
+};
 
 /*
 ** Structure to hold metadata taken from the image or image tile index
@@ -57,28 +62,28 @@ typedef struct {
   double geotransform[6];
   int xsize, ysize;
   double xresolution, yresolution;
-  int bandcount; 
+  int bandcount;
   int imagemode;
   const char *bandinterpretation[10];
 } coverageMetadataObj;
 
 typedef struct {
-  char *version;		/* 1.0.0 for now */
-  char *updatesequence;		/* string, int or timestampe */
-  char *request;		/* GetCapabilities|DescribeCoverage|GetCoverage */
-  char *service;		/* MUST be WCS */
-  char *section;		/* of capabilities document: /WCS_Capabilities/Service|/WCS_Capabilities/Capability|/WCS_Capabilities/ContentMetadata */
-  char **coverages;		/* NULL terminated list of coverages (in the case of a GetCoverage there will only be 1) */
-  char *crs;	        /* request coordinate reference system */
-  char *response_crs;	/* response coordinate reference system */
-  rectObj bbox;		    /* subset bounding box (3D), although we'll only use 2D */
+  char *version;    /* 1.0.0 for now */
+  char *updatesequence;   /* string, int or timestampe */
+  char *request;    /* GetCapabilities|DescribeCoverage|GetCoverage */
+  char *service;    /* MUST be WCS */
+  char *section;    /* of capabilities document: /WCS_Capabilities/Service|/WCS_Capabilities/Capability|/WCS_Capabilities/ContentMetadata */
+  char **coverages;   /* NULL terminated list of coverages (in the case of a GetCoverage there will only be 1) */
+  char *crs;          /* request coordinate reference system */
+  char *response_crs; /* response coordinate reference system */
+  rectObj bbox;       /* subset bounding box (3D), although we'll only use 2D */
   char *time;
-  long width, height, depth;	/* image dimensions */
+  long width, height, depth;  /* image dimensions */
   double originx, originy;      /* WCS 1.1 GridOrigin */
   double resx, resy, resz;      /* resolution */
   char *interpolation;          /* interpolationMethod */
   char *format;
-  char *exceptions;		/* exception MIME type, (default application=vnd.ogc.se_xml) */
+  char *exceptions;   /* exception MIME type, (default application=vnd.ogc.se_xml) */
 } wcsParamsObj;
 
 /* -------------------------------------------------------------------- */
@@ -88,7 +93,7 @@ typedef struct {
 /*      since they are for internal use within the core.                */
 /* -------------------------------------------------------------------- */
 void msWCSFreeParams(wcsParamsObj *params);
-int msWCSException(mapObj *map, const char *code, const char *locator, 
+int msWCSException(mapObj *map, const char *code, const char *locator,
                    const char *version);
 int msWCSIsLayerSupported(layerObj *layer);
 int msWCSGetCoverageMetadata( layerObj *layer, coverageMetadataObj *cm );
@@ -100,14 +105,14 @@ const char *msWCSGetRequestParameter(cgiRequestObj *request, char *name);
 /* -------------------------------------------------------------------- */
 /*      Some WCS 1.1 specific functions from mapwcs11.c                 */
 /* -------------------------------------------------------------------- */
-int msWCSGetCapabilities11(mapObj *map, wcsParamsObj *params, 
+int msWCSGetCapabilities11(mapObj *map, wcsParamsObj *params,
                            cgiRequestObj *req, owsRequestObj *ows_request);
 int msWCSDescribeCoverage11(mapObj *map, wcsParamsObj *params, owsRequestObj *ows_request);
 int msWCSReturnCoverage11( wcsParamsObj *params, mapObj *map, imageObj *image);
-int msWCSGetCoverageBands11( mapObj *map, cgiRequestObj *request, 
+int msWCSGetCoverageBands11( mapObj *map, cgiRequestObj *request,
                              wcsParamsObj *params, layerObj *lp,
                              char **p_bandlist );
-int msWCSException11(mapObj *map, const char *locator, 
+int msWCSException11(mapObj *map, const char *locator,
                      const char *exceptionCode, const char *version);
 
 
@@ -115,133 +120,137 @@ int msWCSException11(mapObj *map, const char *locator,
 /*      Some WCS 2.0 specific functions and structs from mapwcs20.c     */
 /* -------------------------------------------------------------------- */
 
-enum
-{
-    MS_WCS20_TRIM = 0,
-    MS_WCS20_SLICE = 1
+enum {
+  MS_WCS20_TRIM = 0,
+  MS_WCS20_SLICE = 1
 };
 
-enum
-{
-    MS_WCS20_ERROR_VALUE = -1,
-    MS_WCS20_SCALAR_VALUE = 0,
-    MS_WCS20_TIME_VALUE = 1,
-    MS_WCS20_UNDEFINED_VALUE = 2
+enum {
+  MS_WCS20_ERROR_VALUE = -1,
+  MS_WCS20_SCALAR_VALUE = 0,
+  MS_WCS20_TIME_VALUE = 1,
+  MS_WCS20_UNDEFINED_VALUE = 2
 };
 
 #define MS_WCS20_UNBOUNDED DBL_MAX
 #define MS_WCS20_UNBOUNDED_TIME 0xFFFFFFFF
 
-typedef struct
-{
-    union
-    {
-        double scalar;
-        time_t time;
-    };
-    int unbounded; /* 0 if bounded, 1 if unbounded */
+typedef struct {
+  union {
+    double scalar;
+    time_t time;
+  };
+  int unbounded; /* 0 if bounded, 1 if unbounded */
 } timeScalarUnion;
 
-typedef struct
-{
-    char *axis;         /* the name of the subsetted axis */
-    int operation;      /* Either TRIM or SLICE */
-    char *crs;          /* optional CRS to use */
-    int timeOrScalar;   /* 0 if scalar value, 1 if time value */
-    timeScalarUnion min; /* Minimum and Maximum of the subsetted axis;*/
-    timeScalarUnion max;
+typedef struct {
+  char *axis;         /* the name of the subsetted axis */
+  int operation;      /* Either TRIM or SLICE */
+  char *crs;          /* optional CRS to use */
+  int timeOrScalar;   /* 0 if scalar value, 1 if time value */
+  timeScalarUnion min; /* Minimum and Maximum of the subsetted axis;*/
+  timeScalarUnion max;
 } wcs20SubsetObj;
 typedef wcs20SubsetObj * wcs20SubsetObjPtr;
 
-typedef struct
-{
-    char *name;         /* name of the axis */
-    int size;           /* pixelsize of the axis */
-    double resolution;  /* resolution of the axis */
-    char *resolutionUOM; /* resolution units of measure */
-    wcs20SubsetObjPtr subset;
+typedef struct {
+  char *name;         /* name of the axis */
+  int size;           /* pixelsize of the axis */
+  double resolution;  /* resolution of the axis */
+  char *resolutionUOM; /* resolution units of measure */
+  wcs20SubsetObjPtr subset;
 } wcs20AxisObj;
 typedef wcs20AxisObj * wcs20AxisObjPtr;
 
-typedef struct
-{
-    char *version;      /* 2.0.0 */
-    char *request;      /* GetCapabilities|DescribeCoverage|GetCoverage */
-    char *service;      /* MUST be WCS */
-    char **accept_versions; /* NULL terminated list of Accepted versions */
-    char **sections;    /* NULL terminated list of GetCapabilities sections */
-    char *updatesequence; /* GetCapabilities updatesequence */
-    char **ids;         /* NULL terminated list of coverages (in the case of a GetCoverage there will only be 1) */
-    long width, height; /* image dimensions */
-    double resolutionX; /* image resolution in X axis */
-    double resolutionY; /* image resolution in Y axis */
-    char *resolutionUnits; /* Units of Measure for resolution */
-    char *format;       /* requested output format */
-    int multipart;      /* flag for multipart GML+image */
-    char *interpolation; /* requested interpolation method */
-    char *outputcrs;    /* requested CRS for output */
-    char *subsetcrs;    /* determined CRS of the subsets */
-    rectObj bbox;       /* determined Bounding Box */
-    int numaxes;        /* number of axes */
-    wcs20AxisObjPtr *axes; /* list of axes, NULL if none*/
-    char **range_subset;
+typedef struct {
+  char *version;      /* 2.0.0 v 2.0.1 */
+  char *request;      /* GetCapabilities|DescribeCoverage|GetCoverage */
+  char *service;      /* MUST be WCS */
+  char **accept_versions; /* NULL terminated list of Accepted versions */
+  char **sections;    /* NULL terminated list of GetCapabilities sections */
+  char *updatesequence; /* GetCapabilities updatesequence */
+  char **ids;         /* NULL terminated list of coverages (in the case of a GetCoverage there will only be 1) */
+  long width, height; /* image dimensions */
+  double resolutionX; /* image resolution in X axis */
+  double resolutionY; /* image resolution in Y axis */
+  char *resolutionUnits; /* Units of Measure for resolution */
+  char *format;       /* requested output format */
+  int multipart;      /* flag for multipart GML+image */
+  char *interpolation; /* requested interpolation method */
+  char *outputcrs;    /* requested CRS for output */
+  char *subsetcrs;    /* determined CRS of the subsets */
+  rectObj bbox;       /* determined Bounding Box */
+  int numaxes;        /* number of axes */
+  wcs20AxisObjPtr *axes; /* list of axes, NULL if none*/
+  char **range_subset;
 } wcs20ParamsObj;
 typedef wcs20ParamsObj * wcs20ParamsObjPtr;
 
-typedef struct
-{
-    union
-    {
-        struct
-        {
-            char *name;
-            char *interpretation;
-            char *uom;
-            char *definition;
-            char *description;
-        };
-        char *values[5];
+typedef struct {
+  union {
+    struct {
+      char *name;
+      char *interpretation;
+      char *uom;
+      char *definition;
+      char *description;
     };
-    double interval_min;
-    double interval_max;
-    int significant_figures;
+    char *values[5];
+  };
+  double interval_min;
+  double interval_max;
+  int significant_figures;
 } wcs20rasterbandMetadataObj;
 typedef wcs20rasterbandMetadataObj * wcs20rasterbandMetadataObjPtr;
 
-typedef struct
-{
-    char *native_format;    /* mime type of the native format */
-    const char *srs;
-    char srs_uri[200];
-    rectObj extent;
-    double geotransform[6];
-    double xresolution;
-    double yresolution;
-    int xsize;
-    int ysize;
-    int imagemode;
-    size_t numnilvalues;
-    char **nilvalues;
-    char **nilvalues_reasons;
-    size_t numbands;
-    wcs20rasterbandMetadataObjPtr bands;
+typedef struct {
+  char *native_format;    /* mime type of the native format */
+  const char *srs;
+  char srs_uri[200];
+  rectObj extent;
+  double geotransform[6];
+  double xresolution;
+  double yresolution;
+  int xsize;
+  int ysize;
+  int imagemode;
+  size_t numnilvalues;
+  char **nilvalues;
+  char **nilvalues_reasons;
+  size_t numbands;
+  wcs20rasterbandMetadataObjPtr bands;
 } wcs20coverageMetadataObj;
 typedef wcs20coverageMetadataObj * wcs20coverageMetadataObjPtr;
 
 #define MS_WCS_20_PROFILE_CORE      "http://www.opengis.net/spec/WCS/2.0/conf/core"
 #define MS_WCS_20_PROFILE_KVP       "http://www.opengis.net/spec/WCS_protocol-binding_get-kvp/1.0/conf/get-kvp"
 #define MS_WCS_20_PROFILE_POST      "http://www.opengis.net/spec/WCS_protocol-binding_post-xml/1.0/conf/post-xml"
-#define MS_WCS_20_PROFILE_GEOTIFF   "http://www.opengis.net/spec/WCS_encoding_geotiff/1.0/conf/geotiff"
-#define MS_WCS_20_PROFILE_GML_GEOTIFF "http://www.placeholder.com/GML_and_GeoTIFF"
+#define MS_WCS_20_PROFILE_GML       "http://www.opengis.net/spec/GMLCOV/1.0/conf/gml-coverage"
+#define MS_WCS_20_PROFILE_GML_MULTIPART "http://www.opengis.net/spec/GMLCOV/1.0/conf/multipart"
+#define MS_WCS_20_PROFILE_GML_SPECIAL "http://www.opengis.net/spec/GMLCOV/1.0/conf/special-format"
+#define MS_WCS_20_PROFILE_GML_GEOTIFF "http://www.opengis.net/spec/GMLCOV_geotiff-coverages/1.0/conf/geotiff-coverage"
+#define MS_WCS_20_PROFILE_GEOTIFF   "http://www.opengis.net/spec/WCS_geotiff-coverages/1.0/conf/geotiff-coverage"
 #define MS_WCS_20_PROFILE_CRS      "http://www.opengis.net/spec/WCS_service-model_crs-predefined/1.0/conf/crs-predefined"
-#define MS_WCS_20_PROFILE_IMAGECRS  "http://www.placeholder.com/IMAGECRS"
 #define MS_WCS_20_PROFILE_SCALING   "http://www.opengis.net/spec/WCS_service-model_scaling+interpolation/1.0/conf/scaling+interpolation"
 #define MS_WCS_20_PROFILE_RANGESUBSET "http://www.opengis.net/spec/WCS_service-model_band-subsetting/1.0/conf/band-subsetting"
 
-int msWCSDispatch20(mapObj *map, cgiRequestObj *request, owsRequestObj *ows_request);
+/* -------------------------------------------------------------------- */
+/*      WCS 2.0 function prototypes.                                    */
+/* -------------------------------------------------------------------- */
 
-int msWCSException20(mapObj *map, const char *locator,
-                     const char *exceptionCode, const char *version);
+wcs20ParamsObjPtr msWCSCreateParamsObj20();
+void msWCSFreeParamsObj20(wcs20ParamsObjPtr params);
+int msWCSParseRequest20(mapObj *map, cgiRequestObj *request, owsRequestObj *ows_request, wcs20ParamsObjPtr params);
+
+int msWCSException20(mapObj *map, const char *locator, const char *exceptionCode, const char *version);
+
+int msWCSGetCapabilities20(mapObj *map, cgiRequestObj *req, wcs20ParamsObjPtr params, owsRequestObj *ows_request);
+int msWCSDescribeCoverage20(mapObj *map, wcs20ParamsObjPtr params, owsRequestObj *ows_request);
+int msWCSGetCoverage20(mapObj *map, cgiRequestObj *request, wcs20ParamsObjPtr params, owsRequestObj *ows_request);
+
+/* -------------------------------------------------------------------- */
+/*      XML parsing helper macros.                                      */
+/* -------------------------------------------------------------------- */
 
 #define XML_FOREACH_CHILD(parent_node, child_node)              \
     for(child_node = parent_node->children; child_node != NULL; child_node = child_node->next)
diff --git a/mapwcs11.c b/mapwcs11.c
index d67e081..e49af52 100644
--- a/mapwcs11.c
+++ b/mapwcs11.c
@@ -17,7 +17,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -35,33 +35,38 @@
 #include "mapthread.h"
 #include "mapwcs.h"
 
-MS_CVSID("$Id$")
 
-#if defined(USE_WCS_SVR) && defined(USE_LIBXML2)
 
+#if defined(USE_WCS_SVR)
 #include "mapwcs.h"
-#include "maplibxml2.h"
 #include "gdal.h"
 #include "cpl_string.h" /* GDAL string handling */
+#endif
 
+#if defined(USE_LIBXML2)
+#include "maplibxml2.h"
+#endif
+
+#if defined(USE_WCS_SVR) && defined(USE_LIBXML2)
 /*
 ** msWCSException11()
 **
 ** Report current MapServer error in XML exception format.
 ** Wrapper function around msOWSCommonExceptionReport. Merely
 ** passes WCS specific info.
-** 
+**
 */
 
-int msWCSException11(mapObj *map, const char *locator, 
-                     const char *exceptionCode, const char *version) {
+int msWCSException11(mapObj *map, const char *locator,
+                     const char *exceptionCode, const char *version)
+{
   int size = 0;
   char *errorString     = NULL;
   char *errorMessage    = NULL;
   char *schemasLocation = NULL;
   const char * encoding;
 
-  xmlDocPtr  psDoc      = NULL;   
+  xmlDocPtr  psDoc      = NULL;
   xmlNodePtr psRootNode = NULL;
   xmlNsPtr   psNsOws    = NULL;
   xmlChar *buffer       = NULL;
@@ -79,15 +84,16 @@ int msWCSException11(mapObj *map, const char *locator,
 
   xmlDocSetRootElement(psDoc, psRootNode);
 
-  psNsOws = xmlNewNs(psRootNode, BAD_CAST "http://www.opengis.net/ows/1.1", BAD_CAST "ows");
+  xmlNewNs(psRootNode, BAD_CAST "http://www.opengis.net/ows/1.1", BAD_CAST "ows");
 
   if (encoding)
-      msIO_printf("Content-type: text/xml; charset=%s%c%c", encoding,10,10);
+    msIO_setHeader("Content-Type","text/xml; charset=%s", encoding);
   else
-      msIO_printf("Content-type: text/xml%c%c",10,10);
+    msIO_setHeader("Content-Type","text/xml");
+  msIO_sendHeaders();
 
   xmlDocDumpFormatMemoryEnc(psDoc, &buffer, &size, (encoding ? encoding : "ISO-8859-1"), 1);
-    
+
   msIO_printf("%s", buffer);
 
   /*free buffer and the document */
@@ -96,6 +102,7 @@ int msWCSException11(mapObj *map, const char *locator,
   free(schemasLocation);
   xmlFree(buffer);
   xmlFreeDoc(psDoc);
+  xmlFreeNs(psNsOws);
 
   /* clear error since we have already reported it */
   msResetErrorList();
@@ -114,116 +121,117 @@ int msWCSException11(mapObj *map, const char *locator,
 static char *msWCSGetFormatsList11( mapObj *map, layerObj *layer )
 
 {
-    char *format_list = msStrdup("");
-    char **tokens = NULL, **formats = NULL;
-    int  i, numtokens = 0, numformats;
-    const char *value;
-
-    msApplyDefaultOutputFormats(map);
-
-/* -------------------------------------------------------------------- */
-/*      Parse from layer metadata.                                      */
-/* -------------------------------------------------------------------- */
-    if( layer != NULL 
-        && (value = msOWSGetEncodeMetadata( &(layer->metadata),"CO","formats",
-                                            "GTiff" )) != NULL ) {
-        tokens = msStringSplit(value, ' ', &numtokens);
+  char *format_list = msStrdup("");
+  char **tokens = NULL, **formats = NULL;
+  int  i, numtokens = 0, numformats;
+  char *value;
+
+  msApplyDefaultOutputFormats(map);
+
+  /* -------------------------------------------------------------------- */
+  /*      Parse from layer metadata.                                      */
+  /* -------------------------------------------------------------------- */
+  if( layer != NULL
+      && (value = msOWSGetEncodeMetadata( &(layer->metadata),"CO","formats",
+                                          "GTiff" )) != NULL ) {
+    tokens = msStringSplit(value, ' ', &numtokens);
+    msFree(value);
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Parse from map.web metadata.                                    */
+  /* -------------------------------------------------------------------- */
+  else if((value = msOWSGetEncodeMetadata( &(map->web.metadata), "CO", "formats",
+                                           NULL)) != NULL ) {
+    tokens = msStringSplit(value, ' ', &numtokens);
+    msFree(value);
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Or generate from all configured raster output formats that      */
+  /*      look plausible.                                                 */
+  /* -------------------------------------------------------------------- */
+  else {
+    tokens = (char **) calloc(map->numoutputformats,sizeof(char*));
+    for( i = 0; i < map->numoutputformats; i++ ) {
+      switch( map->outputformatlist[i]->renderer ) {
+          /* seeminly normal raster format */
+#ifdef USE_GD
+        case MS_RENDER_WITH_GD:
+#endif
+        case MS_RENDER_WITH_AGG:
+        case MS_RENDER_WITH_RAWDATA:
+          tokens[numtokens++] = msStrdup(map->outputformatlist[i]->name);
+          break;
+
+          /* rest of formats aren't really WCS compatible */
+        default:
+          break;
+
+      }
     }
+  }
 
-/* -------------------------------------------------------------------- */
-/*      Or generate from all configured raster output formats that      */
-/*      look plausible.                                                 */
-/* -------------------------------------------------------------------- */
-    else
-    {
-        tokens = (char **) calloc(map->numoutputformats,sizeof(char*));
-        for( i = 0; i < map->numoutputformats; i++ )
-        {
-            switch( map->outputformatlist[i]->renderer )
-            {
-                /* seeminly normal raster format */
-              case MS_RENDER_WITH_GD:
-              case MS_RENDER_WITH_AGG:
-              case MS_RENDER_WITH_RAWDATA:
-                tokens[numtokens++] = msStrdup(map->outputformatlist[i]->name);
-                break;
-                
-                /* rest of formats aren't really WCS compatible */
-              default:
-                break;
-                
-            }
-        }
+  /* -------------------------------------------------------------------- */
+  /*      Convert outputFormatObj names into mime types and remove        */
+  /*      duplicates.                                                     */
+  /* -------------------------------------------------------------------- */
+  numformats = 0;
+  formats = (char **) calloc(sizeof(char*),numtokens);
+
+  for( i = 0; i < numtokens; i++ ) {
+    int format_i, j;
+    const char *mimetype;
+
+    for( format_i = 0; format_i < map->numoutputformats; format_i++ ) {
+      if( strcasecmp(map->outputformatlist[format_i]->name,
+                     tokens[i]) == 0 )
+        break;
     }
 
-/* -------------------------------------------------------------------- */
-/*      Convert outputFormatObj names into mime types and remove        */
-/*      duplicates.                                                     */
-/* -------------------------------------------------------------------- */
-    numformats = 0;
-    formats = (char **) calloc(sizeof(char*),numtokens);
-    
-    for( i = 0; i < numtokens; i++ )
-    {
-        int format_i, j;
-        const char *mimetype;
-        
-        for( format_i = 0; format_i < map->numoutputformats; format_i++ )
-        {
-            if( strcasecmp(map->outputformatlist[format_i]->name,
-                           tokens[i]) == 0 )
-                break;
-        }
-        
-
-        if( format_i == map->numoutputformats )
-        {
-            msDebug("Failed to find outputformat info on format '%s', ignore.\n",
-                    tokens[i] );
-            continue;
-        }
-
-        mimetype = map->outputformatlist[format_i]->mimetype;
-        if( mimetype == NULL || strlen(mimetype) == 0 )
-        {
-            msDebug("No mimetime for format '%s', ignoring.\n",
-                    tokens[i] );
-            continue;
-        }
-        
-        for( j = 0; j < numformats; j++ )
-        {
-            if( strcasecmp(mimetype,formats[j]) == 0 )
-                break;
-        }
-
-        if( j < numformats )
-        {
-            msDebug( "Format '%s' ignored since mimetype '%s' duplicates another outputFormatObj.\n", 
-                     tokens[i], mimetype );
-            continue;
-        }
-        
-        formats[numformats++] = msStrdup(mimetype);
+
+    if( format_i == map->numoutputformats ) {
+      msDebug("Failed to find outputformat info on format '%s', ignore.\n",
+              tokens[i] );
+      continue;
     }
 
-    msFreeCharArray(tokens,numtokens);
+    mimetype = map->outputformatlist[format_i]->mimetype;
+    if( mimetype == NULL || strlen(mimetype) == 0 ) {
+      msDebug("No mimetime for format '%s', ignoring.\n",
+              tokens[i] );
+      continue;
+    }
 
-/* -------------------------------------------------------------------- */
-/*      Turn mimetype list into comma delimited form for easy use       */
-/*      with xml functions.                                             */
-/* -------------------------------------------------------------------- */
-    for(i=0; i<numformats; i++) 
-    {
-        if(i > 0)
-        {
-            format_list = msStringConcatenate(format_list, (char *) ",");
-        }
-        format_list = msStringConcatenate(format_list, formats[i]);
+    for( j = 0; j < numformats; j++ ) {
+      if( strcasecmp(mimetype,formats[j]) == 0 )
+        break;
+    }
+
+    if( j < numformats ) {
+      msDebug( "Format '%s' ignored since mimetype '%s' duplicates another outputFormatObj.\n",
+               tokens[i], mimetype );
+      continue;
+    }
+
+    formats[numformats++] = msStrdup(mimetype);
+  }
+
+  msFreeCharArray(tokens,numtokens);
+
+  /* -------------------------------------------------------------------- */
+  /*      Turn mimetype list into comma delimited form for easy use       */
+  /*      with xml functions.                                             */
+  /* -------------------------------------------------------------------- */
+  for(i=0; i<numformats; i++) {
+    if(i > 0) {
+      format_list = msStringConcatenate(format_list, (char *) ",");
     }
-    msFreeCharArray(formats,numformats);
+    format_list = msStringConcatenate(format_list, formats[i]);
+  }
+  msFreeCharArray(formats,numformats);
 
-    return format_list;
+  return format_list;
 }
 
 /************************************************************************/
@@ -233,521 +241,517 @@ static char *msWCSGetFormatsList11( mapObj *map, layerObj *layer )
 /************************************************************************/
 
 static int msWCSGetCapabilities11_CoverageSummary(
-    mapObj *map, wcsParamsObj *params, cgiRequestObj *req, 
-    xmlDocPtr doc, xmlNodePtr psContents, layerObj *layer )
+  mapObj *map, wcsParamsObj *params, cgiRequestObj *req,
+  xmlDocPtr doc, xmlNodePtr psContents, layerObj *layer )
 
 {
-    coverageMetadataObj cm;
-    int status;
-    const char *value;
-    char *owned_value;
-    char *format_list;
-    xmlNodePtr psCSummary;
-    xmlNsPtr psOwsNs = xmlSearchNs( doc, psContents, BAD_CAST "ows" );
-    char **tokens = NULL;
-    int i = 0;
-    int n = 0;
-
-    status = msWCSGetCoverageMetadata(layer, &cm);
-    if(status != MS_SUCCESS) return MS_FAILURE;
-
-    psCSummary = xmlNewChild( psContents, NULL, BAD_CAST "CoverageSummary", NULL );
-
-/* -------------------------------------------------------------------- */
-/*      Title (from description)                                        */
-/* -------------------------------------------------------------------- */
-    value = msOWSLookupMetadata( &(layer->metadata), "CO", "description");
-    if( value == NULL )
-        value = msOWSLookupMetadata( &(layer->metadata), "CO", "title");
-        if( value == NULL )
-            value = layer->name;
-    xmlNewChild( psCSummary, psOwsNs, BAD_CAST "Title", BAD_CAST value );
-
-/* -------------------------------------------------------------------- */
-/*      Abstract                                                        */
-/* -------------------------------------------------------------------- */
-    value = msOWSLookupMetadata( &(layer->metadata), "CO", "abstract");
-    xmlNewChild( psCSummary, psOwsNs, BAD_CAST "Abstract", BAD_CAST value );
-
-/* -------------------------------------------------------------------- */
-/*      Keywords                                                        */
-/* -------------------------------------------------------------------- */
-    value = msOWSLookupMetadata(&(layer->metadata), "CO", "keywordlist");
-
-    if (value) {
-        xmlNodePtr psNode;
-
-        psNode = xmlNewChild(psCSummary, psOwsNs, BAD_CAST "Keywords", NULL);
-
-        tokens = msStringSplit(value, ',', &n);
-        if (tokens && n > 0) {
-            for (i=0; i<n; i++) {
-                xmlNewChild(psNode, NULL, BAD_CAST "Keyword", BAD_CAST tokens[i] );
-            }
-            msFreeCharArray(tokens, n);
-        }
+  coverageMetadataObj cm;
+  int status;
+  const char *value;
+  char *owned_value;
+  char *format_list;
+  xmlNodePtr psCSummary;
+  xmlNsPtr psOwsNs = xmlSearchNs( doc, psContents, BAD_CAST "ows" );
+  char **tokens = NULL;
+  int i = 0;
+  int n = 0;
+
+  status = msWCSGetCoverageMetadata(layer, &cm);
+  if(status != MS_SUCCESS) return MS_FAILURE;
+
+  psCSummary = xmlNewChild( psContents, NULL, BAD_CAST "CoverageSummary", NULL );
+
+  /* -------------------------------------------------------------------- */
+  /*      Title (from description)                                        */
+  /* -------------------------------------------------------------------- */
+  value = msOWSLookupMetadata( &(layer->metadata), "CO", "description");
+  if( value == NULL )
+    value = msOWSLookupMetadata( &(layer->metadata), "CO", "title");
+  if( value == NULL )
+    value = layer->name;
+  xmlNewChild( psCSummary, psOwsNs, BAD_CAST "Title", BAD_CAST value );
+
+  /* -------------------------------------------------------------------- */
+  /*      Abstract                                                        */
+  /* -------------------------------------------------------------------- */
+  value = msOWSLookupMetadata( &(layer->metadata), "CO", "abstract");
+  xmlNewChild( psCSummary, psOwsNs, BAD_CAST "Abstract", BAD_CAST value );
+
+  /* -------------------------------------------------------------------- */
+  /*      Keywords                                                        */
+  /* -------------------------------------------------------------------- */
+  value = msOWSLookupMetadata(&(layer->metadata), "CO", "keywordlist");
+
+  if (value) {
+    xmlNodePtr psNode;
+
+    psNode = xmlNewChild(psCSummary, psOwsNs, BAD_CAST "Keywords", NULL);
+
+    tokens = msStringSplit(value, ',', &n);
+    if (tokens && n > 0) {
+      for (i=0; i<n; i++) {
+        xmlNewChild(psNode, NULL, BAD_CAST "Keyword", BAD_CAST tokens[i] );
+      }
+      msFreeCharArray(tokens, n);
     }
+  }
 
-/* -------------------------------------------------------------------- */
-/*      Metadata Link                                                   */
-/* -------------------------------------------------------------------- */
-    value = msOWSLookupMetadata(&(layer->metadata), "CO", "metadatalink_href");
-
-    if (value)
-    {
-        xmlNodePtr psMetadata = xmlNewChild(psCSummary, psOwsNs, BAD_CAST "Metadata", NULL);
-        xmlNsPtr psXlinkNs = xmlSearchNs( doc, xmlDocGetRootElement(doc), BAD_CAST "xlink" );
-        const char *metadatalink_type = msOWSLookupMetadata(&(layer->metadata), "CO", "metadatalink_type");
-        const char *metadatalink_format = msOWSLookupMetadata(&(layer->metadata), "CO", "metadatalink_format");
-
-        xmlNewNsProp(psMetadata, psXlinkNs, BAD_CAST "type", BAD_CAST "simple");
-        xmlNewNsProp(psMetadata, psXlinkNs, BAD_CAST "href", BAD_CAST value);
-        if (metadatalink_type != NULL)
-        {
-            xmlNewProp(psMetadata, BAD_CAST "about", BAD_CAST metadatalink_type);
-        }
-        if (metadatalink_format != NULL)
-        {
-            xmlNewNsProp(psMetadata, psXlinkNs, BAD_CAST "role", BAD_CAST metadatalink_format);
-        }
+  /* -------------------------------------------------------------------- */
+  /*      Metadata Link                                                   */
+  /* -------------------------------------------------------------------- */
+  value = msOWSLookupMetadata(&(layer->metadata), "CO", "metadatalink_href");
+
+  if (value) {
+    xmlNodePtr psMetadata = xmlNewChild(psCSummary, psOwsNs, BAD_CAST "Metadata", NULL);
+    xmlNsPtr psXlinkNs = xmlSearchNs( doc, xmlDocGetRootElement(doc), BAD_CAST "xlink" );
+    const char *metadatalink_type = msOWSLookupMetadata(&(layer->metadata), "CO", "metadatalink_type");
+    const char *metadatalink_format = msOWSLookupMetadata(&(layer->metadata), "CO", "metadatalink_format");
+
+    xmlNewNsProp(psMetadata, psXlinkNs, BAD_CAST "type", BAD_CAST "simple");
+    xmlNewNsProp(psMetadata, psXlinkNs, BAD_CAST "href", BAD_CAST value);
+    if (metadatalink_type != NULL) {
+      xmlNewProp(psMetadata, BAD_CAST "about", BAD_CAST metadatalink_type);
+    }
+    if (metadatalink_format != NULL) {
+      xmlNewNsProp(psMetadata, psXlinkNs, BAD_CAST "role", BAD_CAST metadatalink_format);
     }
+  }
 
-/* -------------------------------------------------------------------- */
-/*      WGS84 bounding box.                                             */
-/* -------------------------------------------------------------------- */
-    xmlAddChild( 
-        psCSummary,
-        msOWSCommonWGS84BoundingBox( psOwsNs, 2,
-                                     cm.llextent.minx, cm.llextent.miny,
-                                     cm.llextent.maxx, cm.llextent.maxy ));
-
-/* -------------------------------------------------------------------- */
-/*      Supported CRSes.                                                */
-/* -------------------------------------------------------------------- */
-    if( (owned_value = 
-         msOWSGetProjURN( &(layer->projection), &(layer->metadata), 
+  /* -------------------------------------------------------------------- */
+  /*      WGS84 bounding box.                                             */
+  /* -------------------------------------------------------------------- */
+  xmlAddChild(
+    psCSummary,
+    msOWSCommonWGS84BoundingBox( psOwsNs, 2,
+                                 cm.llextent.minx, cm.llextent.miny,
+                                 cm.llextent.maxx, cm.llextent.maxy ));
+
+  /* -------------------------------------------------------------------- */
+  /*      Supported CRSes.                                                */
+  /* -------------------------------------------------------------------- */
+  if( (owned_value =
+         msOWSGetProjURN( &(layer->projection), &(layer->metadata),
                           "CO", MS_FALSE)) != NULL ) {
-        /* ok */
-    } else if((owned_value = 
-               msOWSGetProjURN( &(layer->map->projection), 
-                                &(layer->map->web.metadata), 
+    /* ok */
+  } else if((owned_value =
+               msOWSGetProjURN( &(layer->map->projection),
+                                &(layer->map->web.metadata),
                                 "CO", MS_FALSE)) != NULL ) {
-        /* ok */
-    } else 
-        msDebug( "mapwcs.c: missing required information, no SRSs defined.\n");
-    
-    if( owned_value != NULL && strlen(owned_value) > 0 ) 
-        msLibXml2GenerateList( psCSummary, NULL, "SupportedCRS", 
-                                owned_value, ' ' );
+    /* ok */
+  } else
+    msDebug( "mapwcs.c: missing required information, no SRSs defined.\n");
 
-    msFree( owned_value );
+  if( owned_value != NULL && strlen(owned_value) > 0 )
+    msLibXml2GenerateList( psCSummary, NULL, "SupportedCRS",
+                           owned_value, ' ' );
 
-/* -------------------------------------------------------------------- */
-/*      SupportedFormats                                                */
-/* -------------------------------------------------------------------- */
-    format_list = msWCSGetFormatsList11( map, layer );
+  msFree( owned_value );
 
-    if (strlen(format_list) > 0 )
-        msLibXml2GenerateList( psCSummary, NULL, "SupportedFormat",
-                                format_list, ',' );
+  /* -------------------------------------------------------------------- */
+  /*      SupportedFormats                                                */
+  /* -------------------------------------------------------------------- */
+  format_list = msWCSGetFormatsList11( map, layer );
 
-    msFree( format_list );
+  if (strlen(format_list) > 0 )
+    msLibXml2GenerateList( psCSummary, NULL, "SupportedFormat",
+                           format_list, ',' );
 
-/* -------------------------------------------------------------------- */
-/*      Identifier (layer name)                                         */
-/* -------------------------------------------------------------------- */
-    xmlNewChild( psCSummary, NULL, BAD_CAST "Identifier", BAD_CAST layer->name );
-  
-    return MS_SUCCESS;
+  msFree( format_list );
+
+  /* -------------------------------------------------------------------- */
+  /*      Identifier (layer name)                                         */
+  /* -------------------------------------------------------------------- */
+  xmlNewChild( psCSummary, NULL, BAD_CAST "Identifier", BAD_CAST layer->name );
+
+  return MS_SUCCESS;
 }
 
 /************************************************************************/
 /*                       msWCSGetCapabilities11()                       */
 /************************************************************************/
-int msWCSGetCapabilities11(mapObj *map, wcsParamsObj *params, 
+int msWCSGetCapabilities11(mapObj *map, wcsParamsObj *params,
                            cgiRequestObj *req, owsRequestObj *ows_request)
 {
-    xmlDocPtr psDoc = NULL;       /* document pointer */
-    xmlNodePtr psRootNode, psMainNode, psNode;
-    xmlNodePtr psTmpNode;
-    char *identifier_list = NULL, *format_list = NULL;
-    const char *updatesequence=NULL;
-    const char *encoding;
-    xmlNsPtr psOwsNs, psXLinkNs;
-    char *schemaLocation = NULL;
-    char *xsi_schemaLocation = NULL;
-    char *script_url=NULL, *script_url_encoded=NULL;
+  xmlDocPtr psDoc = NULL;       /* document pointer */
+  xmlNodePtr psRootNode, psMainNode, psNode;
+  char *identifier_list = NULL, *format_list = NULL;
+  const char *updatesequence=NULL;
+  const char *encoding;
+  xmlNsPtr psOwsNs, psXLinkNs;
+  char *schemaLocation = NULL;
+  char *xsi_schemaLocation = NULL;
+  char *script_url=NULL, *script_url_encoded=NULL;
+
+  xmlChar *buffer = NULL;
+  int size = 0, i;
+  msIOContext *context = NULL;
+
+  int ows_version = OWS_1_1_0;
+
+  /* -------------------------------------------------------------------- */
+  /*      Handle updatesequence                                           */
+  /* -------------------------------------------------------------------- */
+
+  updatesequence = msOWSLookupMetadata(&(map->web.metadata), "CO", "updatesequence");
+  encoding = msOWSLookupMetadata(&(map->web.metadata), "CO", "encoding");
 
-    xmlChar *buffer = NULL;
-    int size = 0, i;
-    msIOContext *context = NULL;
+  if (params->updatesequence != NULL) {
+    i = msOWSNegotiateUpdateSequence(params->updatesequence, updatesequence);
+    if (i == 0) { /* current */
+      msSetError(MS_WCSERR, "UPDATESEQUENCE parameter (%s) is equal to server (%s)", "msWCSGetCapabilities11()", params->updatesequence, updatesequence);
+      return msWCSException11(map, "updatesequence", "CurrentUpdateSequence", params->version);
+    }
+    if (i > 0) { /* invalid */
+      msSetError(MS_WCSERR, "UPDATESEQUENCE parameter (%s) is higher than server (%s)", "msWCSGetCapabilities11()", params->updatesequence, updatesequence);
+      return msWCSException11(map, "updatesequence", "InvalidUpdateSequence", params->version);
+    }
+  }
 
-    int ows_version = OWS_1_1_0;
+  /* -------------------------------------------------------------------- */
+  /*      Build list of layer identifiers available.                      */
+  /* -------------------------------------------------------------------- */
+  identifier_list = msStrdup("");
+  for(i=0; i<map->numlayers; i++) {
+    layerObj *layer = map->layers[i];
+    int       new_length;
 
-/* -------------------------------------------------------------------- */
-/*      Handle updatesequence                                           */
-/* -------------------------------------------------------------------- */
+    if(!msWCSIsLayerSupported(layer))
+      continue;
 
-    updatesequence = msOWSLookupMetadata(&(map->web.metadata), "CO", "updatesequence");
-    encoding = msOWSLookupMetadata(&(map->web.metadata), "CO", "encoding");
+    new_length = strlen(identifier_list) + strlen(layer->name) + 2;
+    identifier_list = (char *) realloc(identifier_list,new_length);
 
-    if (params->updatesequence != NULL) {
-      i = msOWSNegotiateUpdateSequence(params->updatesequence, updatesequence);
-      if (i == 0) { /* current */
-          msSetError(MS_WCSERR, "UPDATESEQUENCE parameter (%s) is equal to server (%s)", "msWCSGetCapabilities11()", params->updatesequence, updatesequence);
-          return msWCSException11(map, "updatesequence", "CurrentUpdateSequence", params->version);
-      }
-      if (i > 0) { /* invalid */
-          msSetError(MS_WCSERR, "UPDATESEQUENCE parameter (%s) is higher than server (%s)", "msWCSGetCapabilities11()", params->updatesequence, updatesequence);
-          return msWCSException11(map, "updatesequence", "InvalidUpdateSequence", params->version);
-      }
-    }
+    if( strlen(identifier_list) > 0 )
+      strcat( identifier_list, "," );
+    strcat( identifier_list, layer->name );
+  }
 
-/* -------------------------------------------------------------------- */
-/*      Build list of layer identifiers available.                      */
-/* -------------------------------------------------------------------- */
-    identifier_list = msStrdup("");
-    for(i=0; i<map->numlayers; i++)
-    {
-        layerObj *layer = map->layers[i];
-        int       new_length;
+  /* -------------------------------------------------------------------- */
+  /*      Create document.                                                */
+  /* -------------------------------------------------------------------- */
+  psDoc = xmlNewDoc(BAD_CAST "1.0");
 
-        if(!msWCSIsLayerSupported(layer)) 
-            continue;
+  psRootNode = xmlNewNode(NULL, BAD_CAST "Capabilities");
 
-        new_length = strlen(identifier_list) + strlen(layer->name) + 2;
-        identifier_list = (char *) realloc(identifier_list,new_length);
+  xmlDocSetRootElement(psDoc, psRootNode);
 
-        if( strlen(identifier_list) > 0 )
-            strcat( identifier_list, "," );
-        strcat( identifier_list, layer->name );
-    }
+  /* -------------------------------------------------------------------- */
+  /*      Name spaces                                                     */
+  /* -------------------------------------------------------------------- */
+  xmlSetNs(psRootNode, xmlNewNs(psRootNode, BAD_CAST "http://www.opengis.net/wcs/1.1", NULL));
+  psOwsNs = xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_OWS_110_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_OWS_NAMESPACE_PREFIX);
+  psXLinkNs = xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_W3C_XLINK_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_W3C_XLINK_NAMESPACE_PREFIX);
+  xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_W3C_XSI_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_W3C_XSI_NAMESPACE_PREFIX);
+  xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_OGC_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_OGC_NAMESPACE_PREFIX );
+
+  /*xmlNewProp(psRootNode, BAD_CAST " */
+  xmlNewProp(psRootNode, BAD_CAST "version", BAD_CAST params->version );
+
+  updatesequence = msOWSLookupMetadata(&(map->web.metadata), "CO", "updatesequence");
+
+  if (updatesequence)
+    xmlNewProp(psRootNode, BAD_CAST "updateSequence", BAD_CAST updatesequence);
+
+  schemaLocation = msEncodeHTMLEntities( msOWSGetSchemasLocation(map) );
+  xsi_schemaLocation = msStrdup("http://www.opengis.net/wcs/1.1");
+  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, " ");
+  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, schemaLocation);
+  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, "/wcs/1.1/wcsGetCapabilities.xsd ");
+  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, MS_OWSCOMMON_OWS_110_NAMESPACE_URI);
+  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, " ");
+  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, schemaLocation);
+  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, "/ows/1.1.0/owsAll.xsd");
+  xmlNewNsProp(psRootNode, NULL, BAD_CAST "xsi:schemaLocation", BAD_CAST xsi_schemaLocation);
+  msFree(schemaLocation);
+  msFree(xsi_schemaLocation);
+
+  /* -------------------------------------------------------------------- */
+  /*      Service metadata.                                               */
+  /* -------------------------------------------------------------------- */
+  if( params->section == NULL
+      || strstr(params->section,"All") != NULL
+      || strstr(params->section,"ServiceIdentification") != NULL ) {
+    xmlAddChild(psRootNode, msOWSCommonServiceIdentification(
+                              psOwsNs, map, "OGC WCS", params->version, "CO"));
+  }
 
-/* -------------------------------------------------------------------- */
-/*      Create document.                                                */
-/* -------------------------------------------------------------------- */
-    psDoc = xmlNewDoc(BAD_CAST "1.0");
-
-    psRootNode = xmlNewNode(NULL, BAD_CAST "Capabilities");
-
-    xmlDocSetRootElement(psDoc, psRootNode);
-
-/* -------------------------------------------------------------------- */
-/*      Name spaces                                                     */
-/* -------------------------------------------------------------------- */
-    xmlSetNs(psRootNode, xmlNewNs(psRootNode, BAD_CAST "http://www.opengis.net/wcs/1.1", NULL));
-    psOwsNs = xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_OWS_110_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_OWS_NAMESPACE_PREFIX);
-    psXLinkNs = xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_W3C_XLINK_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_W3C_XLINK_NAMESPACE_PREFIX);
-    xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_W3C_XSI_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_W3C_XSI_NAMESPACE_PREFIX);
-    xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_OGC_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_OGC_NAMESPACE_PREFIX );
-
-    /*xmlNewProp(psRootNode, BAD_CAST " */
-    xmlNewProp(psRootNode, BAD_CAST "version", BAD_CAST params->version );
-
-    updatesequence = msOWSLookupMetadata(&(map->web.metadata), "CO", "updatesequence");
-
-    if (updatesequence)
-      xmlNewProp(psRootNode, BAD_CAST "updateSequence", BAD_CAST updatesequence);
-
-    schemaLocation = msEncodeHTMLEntities( msOWSGetSchemasLocation(map) );
-    xsi_schemaLocation = msStrdup("http://www.opengis.net/wcs/1.1");
-    xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, " ");
-    xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, schemaLocation);
-    xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, "/wcs/1.1/wcsGetCapabilities.xsd ");
-    xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, MS_OWSCOMMON_OWS_110_NAMESPACE_URI);
-    xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, " ");
-    xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, schemaLocation);
-    xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, "/ows/1.1.0/owsAll.xsd");
-    xmlNewNsProp(psRootNode, NULL, BAD_CAST "xsi:schemaLocation", BAD_CAST xsi_schemaLocation);
-
-/* -------------------------------------------------------------------- */
-/*      Service metadata.                                               */
-/* -------------------------------------------------------------------- */
-    if( params->section == NULL 
-        || strstr(params->section,"All") != NULL
-        || strstr(params->section,"ServiceIdentification") != NULL )
-    {
-        psTmpNode = xmlAddChild(psRootNode, msOWSCommonServiceIdentification(
-                                    psOwsNs, map, "OGC WCS", params->version, "CO"));
-    }
+  /*service provider*/
+  if( params->section == NULL
+      || strstr(params->section,"All") != NULL
+      || strstr(params->section,"ServiceProvider") != NULL ) {
+    xmlAddChild(psRootNode, msOWSCommonServiceProvider(
+                              psOwsNs, psXLinkNs, map, "CO"));
+  }
 
-    /*service provider*/
-    if( params->section == NULL 
-        || strstr(params->section,"All") != NULL
-        || strstr(params->section,"ServiceProvider") != NULL )
-    {
-        psTmpNode = xmlAddChild(psRootNode, msOWSCommonServiceProvider(
-                                    psOwsNs, psXLinkNs, map, "CO"));
+  /* -------------------------------------------------------------------- */
+  /*      Operations metadata.                                            */
+  /* -------------------------------------------------------------------- */
+  /*operation metadata */
+  if ((script_url=msOWSGetOnlineResource(map, "CO", "onlineresource", req)) == NULL
+      || (script_url_encoded = msEncodeHTMLEntities(script_url)) == NULL) {
+    msSetError(MS_WCSERR, "Server URL not found", "msWCSGetCapabilities11()");
+    return msWCSException11(map, "mapserv", "NoApplicableCode", params->version);
+  }
+  free( script_url );
+
+  if( params->section == NULL
+      || strstr(params->section,"All") != NULL
+      || strstr(params->section,"OperationsMetadata") != NULL ) {
+    psMainNode= xmlAddChild(psRootNode,msOWSCommonOperationsMetadata(psOwsNs));
+
+    /* -------------------------------------------------------------------- */
+    /*      GetCapabilities - add Sections and AcceptVersions?              */
+    /* -------------------------------------------------------------------- */
+    psNode = msOWSCommonOperationsMetadataOperation(
+               psOwsNs, psXLinkNs,
+               "GetCapabilities", OWS_METHOD_GETPOST, script_url_encoded);
+
+    xmlAddChild(psMainNode, psNode);
+    xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(
+                  ows_version, psOwsNs, "Parameter", "service", "WCS"));
+    xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(
+                  ows_version, psOwsNs, "Parameter", "version", (char *)params->version));
+
+    /* -------------------------------------------------------------------- */
+    /*      DescribeCoverage                                                */
+    /* -------------------------------------------------------------------- */
+    if (msOWSRequestIsEnabled(map, NULL, "C", "DescribeCoverage", MS_FALSE)) {
+      psNode = msOWSCommonOperationsMetadataOperation(
+                 psOwsNs, psXLinkNs,
+                 "DescribeCoverage", OWS_METHOD_GETPOST, script_url_encoded);
+
+      xmlAddChild(psMainNode, psNode);
+      xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(
+                    ows_version, psOwsNs, "Parameter", "service", "WCS"));
+      xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(
+                    ows_version, psOwsNs, "Parameter", "version", (char *)params->version));
+      xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(
+                    ows_version, psOwsNs, "Parameter", "identifiers", identifier_list ));
     }
 
-/* -------------------------------------------------------------------- */
-/*      Operations metadata.                                            */
-/* -------------------------------------------------------------------- */
-    /*operation metadata */
-    if ((script_url=msOWSGetOnlineResource(map, "CO", "onlineresource", req)) == NULL 
-        || (script_url_encoded = msEncodeHTMLEntities(script_url)) == NULL)
-    {
-        msSetError(MS_WCSERR, "Server URL not found", "msWCSGetCapabilities11()");
-        return msWCSException11(map, "mapserv", "NoApplicableCode", params->version);
+    /* -------------------------------------------------------------------- */
+    /*      GetCoverage                                                     */
+    /* -------------------------------------------------------------------- */
+    if (msOWSRequestIsEnabled(map, NULL, "C", "GetCoverage", MS_FALSE)) {
+
+      psNode = msOWSCommonOperationsMetadataOperation(
+                 psOwsNs, psXLinkNs,
+                 "GetCoverage", OWS_METHOD_GETPOST, script_url_encoded);
+
+      format_list = msWCSGetFormatsList11( map, NULL );
+
+      xmlAddChild(psMainNode, psNode);
+      xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(
+                    ows_version, psOwsNs, "Parameter", "service", "WCS"));
+      xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(
+                    ows_version, psOwsNs, "Parameter", "version", (char *)params->version));
+      xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(
+                    ows_version, psOwsNs, "Parameter", "Identifier", identifier_list ));
+      xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(
+                    ows_version, psOwsNs, "Parameter", "InterpolationType",
+                    "NEAREST_NEIGHBOUR,BILINEAR" ));
+      xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(
+                    ows_version, psOwsNs, "Parameter", "format", format_list ));
+      xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(
+                    ows_version, psOwsNs, "Parameter", "store", "false" ));
+      xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(
+                    ows_version, psOwsNs, "Parameter", "GridBaseCRS",
+                    "urn:ogc:def:crs:epsg::4326" ));
+
+      msFree( format_list );
     }
-    free( script_url );
+  }
 
-    if( params->section == NULL 
-        || strstr(params->section,"All") != NULL
-        || strstr(params->section,"OperationsMetadata") != NULL )
-    {
-        psMainNode= xmlAddChild(psRootNode,msOWSCommonOperationsMetadata(psOwsNs));
-
-/* -------------------------------------------------------------------- */
-/*      GetCapabilities - add Sections and AcceptVersions?              */
-/* -------------------------------------------------------------------- */
-        psNode = msOWSCommonOperationsMetadataOperation( 
-            psOwsNs, psXLinkNs,
-            "GetCapabilities", OWS_METHOD_GETPOST, script_url_encoded);
-        
-        xmlAddChild(psMainNode, psNode);
-        xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(
-                        ows_version, psOwsNs, "Parameter", "service", "WCS"));
-        xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(
-                        ows_version, psOwsNs, "Parameter", "version", (char *)params->version));
-
-/* -------------------------------------------------------------------- */
-/*      DescribeCoverage                                                */
-/* -------------------------------------------------------------------- */
-        if (msOWSRequestIsEnabled(map, NULL, "C", "DescribeCoverage", MS_TRUE)) 
-        {
-            psNode = msOWSCommonOperationsMetadataOperation(
-                psOwsNs, psXLinkNs,
-                "DescribeCoverage", OWS_METHOD_GETPOST, script_url_encoded);
-            
-            xmlAddChild(psMainNode, psNode);
-            xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(
-                            ows_version, psOwsNs, "Parameter", "service", "WCS"));
-            xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(
-                            ows_version, psOwsNs, "Parameter", "version", (char *)params->version));
-            xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(
-                            ows_version, psOwsNs, "Parameter", "identifiers", identifier_list ));
-        }
-        
-/* -------------------------------------------------------------------- */
-/*      GetCoverage                                                     */
-/* -------------------------------------------------------------------- */
-        if (msOWSRequestIsEnabled(map, NULL, "C", "GetCoverage", MS_TRUE)) 
-        {
-
-            psNode = msOWSCommonOperationsMetadataOperation(
-                psOwsNs, psXLinkNs,
-                "GetCoverage", OWS_METHOD_GETPOST, script_url_encoded);
-            
-            format_list = msWCSGetFormatsList11( map, NULL );
-            
-            xmlAddChild(psMainNode, psNode);
-            xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(
-                            ows_version, psOwsNs, "Parameter", "service", "WCS"));
-            xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(
-                            ows_version, psOwsNs, "Parameter", "version", (char *)params->version));
-            xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(
-                            ows_version, psOwsNs, "Parameter", "Identifier", identifier_list ));
-            xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(
-                            ows_version, psOwsNs, "Parameter", "InterpolationType", 
-                            "NEAREST_NEIGHBOUR,BILINEAR" ));
-            xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(
-                            ows_version, psOwsNs, "Parameter", "format", format_list ));
-            xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(
-                            ows_version, psOwsNs, "Parameter", "store", "false" ));
-            xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(
-                            ows_version, psOwsNs, "Parameter", "GridBaseCRS", 
-                            "urn:ogc:def:crs:epsg::4326" ));
-        
-            msFree( format_list );
-        }
-    }    
-
-/* -------------------------------------------------------------------- */
-/*      Contents section.                                               */
-/* -------------------------------------------------------------------- */
-    if( params->section == NULL 
-        || strstr(params->section,"All") != NULL
-        || strstr(params->section,"Contents") != NULL )
-    {
-        psMainNode = xmlNewChild( psRootNode, NULL, BAD_CAST "Contents", NULL );
-
-        for(i=0; i<map->numlayers; i++)
-        {
-            layerObj *layer = map->layers[i];
-            int       status;
-            
-            if(!msWCSIsLayerSupported(layer)) 
-                continue;
-            
-            if (!msIntegerInArray(layer->index, ows_request->enabled_layers, ows_request->numlayers))
-                continue;
-
-            status = msWCSGetCapabilities11_CoverageSummary( 
-                map, params, req, psDoc, psMainNode, layer );
-            if(status != MS_SUCCESS) return MS_FAILURE;
-        }
+  /* -------------------------------------------------------------------- */
+  /*      Contents section.                                               */
+  /* -------------------------------------------------------------------- */
+  if( params->section == NULL
+      || strstr(params->section,"All") != NULL
+      || strstr(params->section,"Contents") != NULL ) {
+    psMainNode = xmlNewChild( psRootNode, NULL, BAD_CAST "Contents", NULL );
+
+    if(ows_request->numlayers == 0) {
+      xmlAddChild(psMainNode,
+                  xmlNewComment(BAD_CAST "WARNING: No WCS layers are enabled. "
+                                "Check wcs/ows_enable_request settings."));
+    } else {
+      for(i=0; i<map->numlayers; i++) {
+        layerObj *layer = map->layers[i];
+        int       status;
+
+        if(!msWCSIsLayerSupported(layer))
+          continue;
+
+        if (!msIntegerInArray(layer->index, ows_request->enabled_layers, ows_request->numlayers))
+          continue;
+
+        status = msWCSGetCapabilities11_CoverageSummary(
+                   map, params, req, psDoc, psMainNode, layer );
+        if(status != MS_SUCCESS) return MS_FAILURE;
+      }
     }
+  }
 
-/* -------------------------------------------------------------------- */
-/*      Write out the document.                                         */
-/* -------------------------------------------------------------------- */
+  /* -------------------------------------------------------------------- */
+  /*      Write out the document.                                         */
+  /* -------------------------------------------------------------------- */
 
-    if( msIO_needBinaryStdout() == MS_FAILURE )
-        return MS_FAILURE;
-     
-    if (encoding)
-        msIO_printf("Content-type: text/xml; charset=%s%c%c", encoding,10,10);
-    else
-        msIO_printf("Content-type: text/xml%c%c",10,10);
-    
-    context = msIO_getHandler(stdout);
+  if( msIO_needBinaryStdout() == MS_FAILURE )
+    return MS_FAILURE;
 
-    xmlDocDumpFormatMemoryEnc(psDoc, &buffer, &size, (encoding ? encoding : "ISO-8859-1"), 1);
-    msIO_contextWrite(context, buffer, size);
-    xmlFree(buffer);
+  if (encoding)
+    msIO_setHeader("Content-Type","text/xml; charset=%s", encoding);
+  else
+    msIO_setHeader("Content-Type","text/xml");
+  msIO_sendHeaders();
+
+  context = msIO_getHandler(stdout);
+
+  xmlDocDumpFormatMemoryEnc(psDoc, &buffer, &size, (encoding ? encoding : "ISO-8859-1"), 1);
+  msIO_contextWrite(context, buffer, size);
+  xmlFree(buffer);
 
-    /*free buffer and the document */
-    /*xmlFree(buffer);*/
-    xmlFreeDoc(psDoc);
+  /*free buffer and the document */
+  /*xmlFree(buffer);*/
+  xmlFreeDoc(psDoc);
 
-    xmlCleanupParser();
+  xmlCleanupParser();
 
-    /* clean up */
-    free( script_url_encoded );
-    free( identifier_list );
+  /* clean up */
+  free( script_url_encoded );
+  free( identifier_list );
 
-    return(MS_SUCCESS);
+  return(MS_SUCCESS);
 }
 
 /************************************************************************/
 /*            msWCSDescribeCoverage_CoverageDescription11()             */
 /************************************************************************/
 
-static int 
+static int
 msWCSDescribeCoverage_CoverageDescription11(
-    layerObj *layer, wcsParamsObj *params, xmlNodePtr psRootNode,
-    xmlNsPtr psOwsNs )
+  layerObj *layer, wcsParamsObj *params, xmlNodePtr psRootNode,
+  xmlNsPtr psOwsNs )
 
 {
-    int status;
-    coverageMetadataObj cm;
-    xmlNodePtr psCD, psDomain, psSD, psGridCRS;
-    const char *value;
-
-/* -------------------------------------------------------------------- */
-/*      Verify layer is processable.                                    */
-/* -------------------------------------------------------------------- */
-    if( msCheckParentPointer(layer->map,"map") == MS_FAILURE )
-	return MS_FAILURE;
-
-    if(!msWCSIsLayerSupported(layer)) 
-        return MS_SUCCESS;
-    
-/* -------------------------------------------------------------------- */
-/*      Setup coverage metadata.                                        */
-/* -------------------------------------------------------------------- */
-    status = msWCSGetCoverageMetadata(layer, &cm);
-    if(status != MS_SUCCESS) return status;
-
-    /* fill in bands rangeset info, if required.  */
-    msWCSSetDefaultBandsRangeSetInfo( params, &cm, layer );
-
-/* -------------------------------------------------------------------- */
-/*      Create CoverageDescription node.                                */
-/* -------------------------------------------------------------------- */
-    psCD = xmlNewChild( psRootNode, NULL, BAD_CAST "CoverageDescription", NULL );
-    
-/* -------------------------------------------------------------------- */
-/*      Title (from description)                                        */
-/* -------------------------------------------------------------------- */
-    value = msOWSLookupMetadata( &(layer->metadata), "CO", "description");
-    if( value == NULL )
-        value = layer->name;
-    xmlNewChild( psCD, psOwsNs, BAD_CAST "Title", BAD_CAST value );
-
-/* -------------------------------------------------------------------- */
-/*      Abstract                                                        */
-/* -------------------------------------------------------------------- */
-    value = msOWSLookupMetadata( &(layer->metadata), "CO", "abstract");
-    xmlNewChild( psCD, psOwsNs, BAD_CAST "Abstract", BAD_CAST value );
-
-/* -------------------------------------------------------------------- */
-/*      Keywords                                                        */
-/* -------------------------------------------------------------------- */
-    value = msOWSLookupMetadata(&(layer->metadata), "CO", "keywordlist");
-
-    if (value)
-        msLibXml2GenerateList( 
-            xmlNewChild(psCD, psOwsNs, BAD_CAST "Keywords", NULL),
-            NULL, "Keyword", value, ',' );
-
-/* -------------------------------------------------------------------- */
-/*      Identifier (layer name)                                         */
-/* -------------------------------------------------------------------- */
-    xmlNewChild( psCD, NULL, BAD_CAST "Identifier", BAD_CAST layer->name);
-
-/* -------------------------------------------------------------------- */
-/*      Domain                                                          */
-/* -------------------------------------------------------------------- */
-    psDomain = xmlNewChild( psCD, NULL, BAD_CAST "Domain", NULL );
-
-/* -------------------------------------------------------------------- */
-/*      SpatialDomain                                                   */
-/* -------------------------------------------------------------------- */
-    psSD = xmlNewChild( psDomain, NULL, BAD_CAST "SpatialDomain", NULL );
-
-/* -------------------------------------------------------------------- */
-/*      imageCRS bounding box.                                          */
-/* -------------------------------------------------------------------- */
-    xmlAddChild( 
-        psSD,
-        msOWSCommonBoundingBox( psOwsNs, "urn:ogc:def:crs:OGC::imageCRS",
-                                2, 0, 0, cm.xsize-1, cm.ysize-1 ));
-
-/* -------------------------------------------------------------------- */
-/*      native CRS bounding box.                                        */
-/* -------------------------------------------------------------------- */
-    xmlAddChild( 
-        psSD,
-        msOWSCommonBoundingBox( psOwsNs, cm.srs_urn, 2, 
-                                cm.extent.minx, cm.extent.miny,
-                                cm.extent.maxx, cm.extent.maxy ));
-
-/* -------------------------------------------------------------------- */
-/*      WGS84 bounding box.                                             */
-/* -------------------------------------------------------------------- */
-    xmlAddChild( 
-        psSD,
-        msOWSCommonWGS84BoundingBox( psOwsNs, 2,
-                                     cm.llextent.minx, cm.llextent.miny,
-                                     cm.llextent.maxx, cm.llextent.maxy ));
-
-/* -------------------------------------------------------------------- */
-/*      GridCRS                                                         */
-/* -------------------------------------------------------------------- */
-    {
-        char format_buf[500];
-
-        psGridCRS = xmlNewChild( psSD, NULL, BAD_CAST "GridCRS", NULL );
-
-        
-        xmlNewChild( psGridCRS, NULL, BAD_CAST "GridBaseCRS", BAD_CAST cm.srs_urn );
-        xmlNewChild( psGridCRS, NULL, BAD_CAST "GridType", 
-                     BAD_CAST "urn:ogc:def:method:WCS:1.1:2dSimpleGrid" );
-
-        sprintf( format_buf, "%.15g %.15g", 
-                 cm.geotransform[0]+cm.geotransform[1]/2+cm.geotransform[2]/2, 
-                 cm.geotransform[3]+cm.geotransform[4]/2+cm.geotransform[5]/2);
-        xmlNewChild( psGridCRS, NULL, BAD_CAST "GridOrigin", BAD_CAST format_buf );
-
-        sprintf( format_buf, "%.15g %.15g", 
-                 cm.geotransform[1], cm.geotransform[5] );
-        xmlNewChild( psGridCRS, NULL, BAD_CAST "GridOffsets", BAD_CAST format_buf );
+  int status;
+  coverageMetadataObj cm;
+  xmlNodePtr psCD, psDomain, psSD, psGridCRS;
+  const char *value;
+
+  /* -------------------------------------------------------------------- */
+  /*      Verify layer is processable.                                    */
+  /* -------------------------------------------------------------------- */
+  if( msCheckParentPointer(layer->map,"map") == MS_FAILURE )
+    return MS_FAILURE;
+
+  if(!msWCSIsLayerSupported(layer))
+    return MS_SUCCESS;
 
-        xmlNewChild( psGridCRS, NULL, BAD_CAST "GridCS", 
-                     BAD_CAST "urn:ogc:def:cs:OGC:0.0:Grid2dSquareCS" );
-    }
+  /* -------------------------------------------------------------------- */
+  /*      Setup coverage metadata.                                        */
+  /* -------------------------------------------------------------------- */
+  status = msWCSGetCoverageMetadata(layer, &cm);
+  if(status != MS_SUCCESS) return status;
+
+  /* fill in bands rangeset info, if required.  */
+  msWCSSetDefaultBandsRangeSetInfo( params, &cm, layer );
+
+  /* -------------------------------------------------------------------- */
+  /*      Create CoverageDescription node.                                */
+  /* -------------------------------------------------------------------- */
+  psCD = xmlNewChild( psRootNode, NULL, BAD_CAST "CoverageDescription", NULL );
+
+  /* -------------------------------------------------------------------- */
+  /*      Title (from description)                                        */
+  /* -------------------------------------------------------------------- */
+  value = msOWSLookupMetadata( &(layer->metadata), "CO", "description");
+  if( value == NULL )
+    value = layer->name;
+  xmlNewChild( psCD, psOwsNs, BAD_CAST "Title", BAD_CAST value );
+
+  /* -------------------------------------------------------------------- */
+  /*      Abstract                                                        */
+  /* -------------------------------------------------------------------- */
+  value = msOWSLookupMetadata( &(layer->metadata), "CO", "abstract");
+  xmlNewChild( psCD, psOwsNs, BAD_CAST "Abstract", BAD_CAST value );
+
+  /* -------------------------------------------------------------------- */
+  /*      Keywords                                                        */
+  /* -------------------------------------------------------------------- */
+  value = msOWSLookupMetadata(&(layer->metadata), "CO", "keywordlist");
+
+  if (value)
+    msLibXml2GenerateList(
+      xmlNewChild(psCD, psOwsNs, BAD_CAST "Keywords", NULL),
+      NULL, "Keyword", value, ',' );
+
+  /* -------------------------------------------------------------------- */
+  /*      Identifier (layer name)                                         */
+  /* -------------------------------------------------------------------- */
+  xmlNewChild( psCD, NULL, BAD_CAST "Identifier", BAD_CAST layer->name);
+
+  /* -------------------------------------------------------------------- */
+  /*      Domain                                                          */
+  /* -------------------------------------------------------------------- */
+  psDomain = xmlNewChild( psCD, NULL, BAD_CAST "Domain", NULL );
+
+  /* -------------------------------------------------------------------- */
+  /*      SpatialDomain                                                   */
+  /* -------------------------------------------------------------------- */
+  psSD = xmlNewChild( psDomain, NULL, BAD_CAST "SpatialDomain", NULL );
+
+  /* -------------------------------------------------------------------- */
+  /*      imageCRS bounding box.                                          */
+  /* -------------------------------------------------------------------- */
+  xmlAddChild(
+    psSD,
+    msOWSCommonBoundingBox( psOwsNs, "urn:ogc:def:crs:OGC::imageCRS",
+                            2, 0, 0, cm.xsize-1, cm.ysize-1 ));
+
+  /* -------------------------------------------------------------------- */
+  /*      native CRS bounding box.                                        */
+  /* -------------------------------------------------------------------- */
+  xmlAddChild(
+    psSD,
+    msOWSCommonBoundingBox( psOwsNs, cm.srs_urn, 2,
+                            cm.extent.minx, cm.extent.miny,
+                            cm.extent.maxx, cm.extent.maxy ));
+
+  /* -------------------------------------------------------------------- */
+  /*      WGS84 bounding box.                                             */
+  /* -------------------------------------------------------------------- */
+  xmlAddChild(
+    psSD,
+    msOWSCommonWGS84BoundingBox( psOwsNs, 2,
+                                 cm.llextent.minx, cm.llextent.miny,
+                                 cm.llextent.maxx, cm.llextent.maxy ));
+
+  /* -------------------------------------------------------------------- */
+  /*      GridCRS                                                         */
+  /* -------------------------------------------------------------------- */
+  {
+    char format_buf[500];
+
+    psGridCRS = xmlNewChild( psSD, NULL, BAD_CAST "GridCRS", NULL );
+
+
+    xmlNewChild( psGridCRS, NULL, BAD_CAST "GridBaseCRS", BAD_CAST cm.srs_urn );
+    xmlNewChild( psGridCRS, NULL, BAD_CAST "GridType",
+                 BAD_CAST "urn:ogc:def:method:WCS:1.1:2dSimpleGrid" );
+
+    sprintf( format_buf, "%.15g %.15g",
+             cm.geotransform[0]+cm.geotransform[1]/2+cm.geotransform[2]/2,
+             cm.geotransform[3]+cm.geotransform[4]/2+cm.geotransform[5]/2);
+    xmlNewChild( psGridCRS, NULL, BAD_CAST "GridOrigin", BAD_CAST format_buf );
+
+    sprintf( format_buf, "%.15g %.15g",
+             cm.geotransform[1], cm.geotransform[5] );
+    xmlNewChild( psGridCRS, NULL, BAD_CAST "GridOffsets", BAD_CAST format_buf );
+
+    xmlNewChild( psGridCRS, NULL, BAD_CAST "GridCS",
+                 BAD_CAST "urn:ogc:def:cs:OGC:0.0:Grid2dSquareCS" );
+  }
 
 
 
@@ -759,126 +763,128 @@ msWCSDescribeCoverage_CoverageDescription11(
     msIO_printf("      <temporalDomain>\n");
 
     /* TimePosition (should support a value AUTO, then we could mine positions from the timeitem) */
-    msOWSPrintEncodeMetadataList(stdout, &(layer->metadata), "CO", "timeposition", NULL, NULL, "        <gml:timePosition>%s</gml:timePosition>\n", NULL);    
+    msOWSPrintEncodeMetadataList(stdout, &(layer->metadata), "CO", "timeposition", NULL, NULL, "        <gml:timePosition>%s</gml:timePosition>\n", NULL);
 
     /* TODO:  add TimePeriod (only one per layer)  */
 
     msIO_printf("      </temporalDomain>\n");
   }
-  
+
   msIO_printf("    </domainSet>\n");
 #endif
 
-/* -------------------------------------------------------------------- */
-/*      Range                                                           */
-/* -------------------------------------------------------------------- */
+  /* -------------------------------------------------------------------- */
+  /*      Range                                                           */
+  /* -------------------------------------------------------------------- */
+  {
+    xmlNodePtr psField, psInterpMethods, psAxis;
+    char *value;
+
+    psField =
+      xmlNewChild(
+        xmlNewChild( psCD, NULL, BAD_CAST "Range", NULL ),
+        NULL, BAD_CAST "Field", NULL );
+
+    value = msOWSGetEncodeMetadata( &(layer->metadata), "CO",
+                                    "rangeset_label", NULL );
+    if( value )
+      xmlNewChild( psField, psOwsNs, BAD_CAST "Title", BAD_CAST value );
+    msFree(value);
+
+    /* ows:Abstract? TODO */
+
+    value = msOWSGetEncodeMetadata( &(layer->metadata), "CO",
+                                    "rangeset_name", "raster" );
+    xmlNewChild( psField, NULL, BAD_CAST "Identifier", BAD_CAST value );
+    msFree(value);
+
+    xmlNewChild(
+        xmlNewChild( psField, NULL, BAD_CAST "Definition", NULL ),
+        psOwsNs, BAD_CAST "AnyValue", NULL );
+
+    /* NullValue */
+    value = msOWSGetEncodeMetadata( &(layer->metadata), "CO",
+                                    "rangeset_nullvalue", NULL);
+    if( value )
+      xmlNewChild( psField, NULL, BAD_CAST "NullValue",
+                   BAD_CAST value );
+    msFree(value);
+
+    /* InterpolationMethods */
+    psInterpMethods =
+      xmlNewChild( psField, NULL, BAD_CAST "InterpolationMethods", NULL );
+
+    xmlNewChild( psInterpMethods, NULL, BAD_CAST "InterpolationMethod", BAD_CAST "bilinear" );
+    xmlNewChild( psInterpMethods, NULL,
+                 BAD_CAST "Default", BAD_CAST "nearest neighbor" );
+
+    /* -------------------------------------------------------------------- */
+    /*      Bands axis.                                                     */
+    /* -------------------------------------------------------------------- */
     {
-        xmlNodePtr psField, psInterpMethods, psAxis, psDefinition;
-        const char *value;
-
-        psField = 
-            xmlNewChild(
-                xmlNewChild( psCD, NULL, BAD_CAST "Range", NULL ),
-                NULL, BAD_CAST "Field", NULL );
-        
-        value = msOWSGetEncodeMetadata( &(layer->metadata), "CO", 
-                                        "rangeset_label", NULL );
-        if( value )
-            xmlNewChild( psField, psOwsNs, BAD_CAST "Title", BAD_CAST value );
-
-        /* ows:Abstract? TODO */
-
-        value = msOWSGetEncodeMetadata( &(layer->metadata), "CO", 
-                                        "rangeset_name", "raster" );
-        xmlNewChild( psField, NULL, BAD_CAST "Identifier", BAD_CAST value );
-       
-        psDefinition =
-            xmlNewChild(
-                xmlNewChild( psField, NULL, BAD_CAST "Definition", NULL ),
-                psOwsNs, BAD_CAST "AnyValue", NULL );
-
-        /* NullValue */
-        value = msOWSGetEncodeMetadata( &(layer->metadata), "CO", 
-                                        "rangeset_nullvalue", NULL);
-        if( value )
-            xmlNewChild( psField, NULL, BAD_CAST "NullValue", 
-                         BAD_CAST value );
-
-        /* InterpolationMethods */
-        psInterpMethods = 
-            xmlNewChild( psField, NULL, BAD_CAST "InterpolationMethods", NULL );
-
-        xmlNewChild( psInterpMethods, NULL, BAD_CAST "InterpolationMethod", BAD_CAST "bilinear" );
-        xmlNewChild( psInterpMethods, NULL, 
-                     BAD_CAST "Default", BAD_CAST "nearest neighbor" );
-
-/* -------------------------------------------------------------------- */
-/*      Bands axis.                                                     */
-/* -------------------------------------------------------------------- */
-        {
-            xmlNodePtr psKeys;
-            int iBand;
-
-            value = msOWSGetEncodeMetadata( &(layer->metadata), "CO", 
-                                            "bands_name", "bands" );
-            psAxis = xmlNewChild( psField, NULL, BAD_CAST "Axis", NULL );
-            xmlNewProp( psAxis, BAD_CAST "identifier", BAD_CAST value );
-            
-            psKeys = xmlNewChild( psAxis, NULL, BAD_CAST 
-                                  "AvailableKeys",  NULL );
-            
-            for( iBand = 0; iBand < cm.bandcount; iBand++ )
-            {
-                char szBandName[32];
-
-                snprintf( szBandName, sizeof(szBandName), "%d", iBand+1 );
-                xmlNewChild( psKeys, NULL, BAD_CAST "Key", 
-                             BAD_CAST szBandName );
-            }
-        }
-    }        
-        
-/* -------------------------------------------------------------------- */
-/*      SupportedCRS                                                    */
-/* -------------------------------------------------------------------- */
-    {
-        char *owned_value;
-        
-        if( (owned_value = 
-             msOWSGetProjURN( &(layer->projection), &(layer->metadata), 
-                              "CO", MS_FALSE)) != NULL ) {
-            /* ok */
-        } else if((owned_value = 
-                   msOWSGetProjURN( &(layer->map->projection), 
-                                    &(layer->map->web.metadata), 
-                                    "CO", MS_FALSE)) != NULL ) {
-            /* ok */
-        } else 
-            msDebug( "mapwcs.c: missing required information, no SRSs defined.\n");
-        
-        if( owned_value != NULL && strlen(owned_value) > 0 ) 
-            msLibXml2GenerateList( psCD, NULL, "SupportedCRS", 
-                                    owned_value, ' ' );
-
-        msFree( owned_value );
-    }
+      xmlNodePtr psKeys;
+      int iBand;
 
-/* -------------------------------------------------------------------- */
-/*      SupportedFormats                                                */
-/* -------------------------------------------------------------------- */
-    {
-        char *format_list;
-        
-        format_list = msWCSGetFormatsList11( layer->map, layer );
-        
-        if (strlen(format_list) > 0 )
-            msLibXml2GenerateList( psCD, NULL, "SupportedFormat", 
-                                    format_list, ',' );
-        
-        msFree( format_list );
+      value = msOWSGetEncodeMetadata( &(layer->metadata), "CO",
+                                      "bands_name", "bands" );
+      psAxis = xmlNewChild( psField, NULL, BAD_CAST "Axis", NULL );
+      xmlNewProp( psAxis, BAD_CAST "identifier", BAD_CAST value );
+      msFree(value);
+
+      psKeys = xmlNewChild( psAxis, NULL, BAD_CAST
+                            "AvailableKeys",  NULL );
+
+      for( iBand = 0; iBand < cm.bandcount; iBand++ ) {
+        char szBandName[32];
+
+        snprintf( szBandName, sizeof(szBandName), "%d", iBand+1 );
+        xmlNewChild( psKeys, NULL, BAD_CAST "Key",
+                     BAD_CAST szBandName );
+      }
     }
-    
-    return MS_SUCCESS;
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      SupportedCRS                                                    */
+  /* -------------------------------------------------------------------- */
+  {
+    char *owned_value;
+
+    if( (owned_value =
+           msOWSGetProjURN( &(layer->projection), &(layer->metadata),
+                            "CO", MS_FALSE)) != NULL ) {
+      /* ok */
+    } else if((owned_value =
+                 msOWSGetProjURN( &(layer->map->projection),
+                                  &(layer->map->web.metadata),
+                                  "CO", MS_FALSE)) != NULL ) {
+      /* ok */
+    } else
+      msDebug( "mapwcs.c: missing required information, no SRSs defined.\n");
+
+    if( owned_value != NULL && strlen(owned_value) > 0 )
+      msLibXml2GenerateList( psCD, NULL, "SupportedCRS",
+                             owned_value, ' ' );
+
+    msFree( owned_value );
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      SupportedFormats                                                */
+  /* -------------------------------------------------------------------- */
+  {
+    char *format_list;
+
+    format_list = msWCSGetFormatsList11( layer->map, layer );
+
+    if (strlen(format_list) > 0 )
+      msLibXml2GenerateList( psCD, NULL, "SupportedFormat",
+                             format_list, ',' );
+
+    msFree( format_list );
+  }
+
+  return MS_SUCCESS;
 }
 
 /************************************************************************/
@@ -887,130 +893,131 @@ msWCSDescribeCoverage_CoverageDescription11(
 
 int msWCSDescribeCoverage11(mapObj *map, wcsParamsObj *params, owsRequestObj *ows_request)
 {
-    xmlDocPtr psDoc = NULL;       /* document pointer */
-    xmlNodePtr psRootNode;
-    xmlNsPtr psOwsNs, psXLinkNs;
-    char *schemaLocation = NULL;
-    char *xsi_schemaLocation = NULL;
-    const char *encoding;
-
-    int i,j;
-
-    encoding = msOWSLookupMetadata(&(map->web.metadata), "CO", "encoding");
-
-/* -------------------------------------------------------------------- */
-/*      We will actually get the coverages list as a single item in     */
-/*      a string list with that item having the comma delimited         */
-/*      coverage names.  Split it up now, and assign back in place      */
-/*      of the old coverages list.                                      */
-/* -------------------------------------------------------------------- */
-    if( CSLCount(params->coverages) == 1 )
-    {
-        char **old_coverages = params->coverages;
-        params->coverages = CSLTokenizeStringComplex( old_coverages[0], ",",
-                                                      FALSE, FALSE );
-        CSLDestroy( old_coverages );
-    }
+  xmlDocPtr psDoc = NULL;       /* document pointer */
+  xmlNodePtr psRootNode;
+  xmlNsPtr psOwsNs;
+  char *schemaLocation = NULL;
+  char *xsi_schemaLocation = NULL;
+  const char *encoding;
+
+  int i,j;
+
+  encoding = msOWSLookupMetadata(&(map->web.metadata), "CO", "encoding");
 
-/* -------------------------------------------------------------------- */
-/*      Validate that the requested coverages exist as named layers.    */
-/* -------------------------------------------------------------------- */
-    if(params->coverages) { /* use the list */
-        for( j = 0; params->coverages[j]; j++ ) {
-            i = msGetLayerIndex(map, params->coverages[j]);
-            if ( (i == -1) || 
-                 (!msIntegerInArray(GET_LAYER(map, i)->index, ows_request->enabled_layers, ows_request->numlayers)) )
-            {
-                msSetError( MS_WCSERR,
-                            "COVERAGE %s cannot be opened / does not exist",
-                            "msWCSDescribeCoverage()", params->coverages[j]);
-                return msWCSException11(map, "coverage", "CoverageNotDefined", params->version);
-            }
-        }
+  /* -------------------------------------------------------------------- */
+  /*      We will actually get the coverages list as a single item in     */
+  /*      a string list with that item having the comma delimited         */
+  /*      coverage names.  Split it up now, and assign back in place      */
+  /*      of the old coverages list.                                      */
+  /* -------------------------------------------------------------------- */
+  if( CSLCount(params->coverages) == 1 ) {
+    char **old_coverages = params->coverages;
+    params->coverages = CSLTokenizeStringComplex( old_coverages[0], ",",
+                        FALSE, FALSE );
+    CSLDestroy( old_coverages );
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Validate that the requested coverages exist as named layers.    */
+  /* -------------------------------------------------------------------- */
+  if(params->coverages) { /* use the list */
+    for( j = 0; params->coverages[j]; j++ ) {
+      i = msGetLayerIndex(map, params->coverages[j]);
+      if ( (i == -1) ||
+           (!msIntegerInArray(GET_LAYER(map, i)->index, ows_request->enabled_layers, ows_request->numlayers)) ) {
+        msSetError( MS_WCSERR,
+                    "COVERAGE %s cannot be opened / does not exist",
+                    "msWCSDescribeCoverage()", params->coverages[j]);
+        return msWCSException11(map, "coverage", "CoverageNotDefined", params->version);
+      }
     }
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Create document.                                                */
+  /* -------------------------------------------------------------------- */
+  psDoc = xmlNewDoc(BAD_CAST "1.0");
+
+  psRootNode = xmlNewNode(NULL, BAD_CAST "CoverageDescriptions");
 
-/* -------------------------------------------------------------------- */
-/*      Create document.                                                */
-/* -------------------------------------------------------------------- */
-    psDoc = xmlNewDoc(BAD_CAST "1.0");
-
-    psRootNode = xmlNewNode(NULL, BAD_CAST "CoverageDescriptions");
-
-    xmlDocSetRootElement(psDoc, psRootNode);
-
-/* -------------------------------------------------------------------- */
-/*      Name spaces                                                     */
-/* -------------------------------------------------------------------- */
-    xmlSetNs(psRootNode, xmlNewNs(psRootNode, BAD_CAST "http://www.opengis.net/wcs/1.1", NULL));
-    psOwsNs = xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_OWS_110_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_OWS_NAMESPACE_PREFIX);
-    psXLinkNs = xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_W3C_XLINK_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_W3C_XLINK_NAMESPACE_PREFIX);
-    xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_W3C_XSI_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_W3C_XSI_NAMESPACE_PREFIX);
-    xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_OGC_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_OGC_NAMESPACE_PREFIX );
-
-    schemaLocation = msEncodeHTMLEntities( msOWSGetSchemasLocation(map) );
-    xsi_schemaLocation = msStrdup("http://www.opengis.net/wcs/1.1");
-    xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, " ");
-    xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, schemaLocation);
-    xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, "/wcs/1.1/wcsDescribeCoverage.xsd ");
-    xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, MS_OWSCOMMON_OWS_110_NAMESPACE_URI);
-    xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, " ");
-    xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, schemaLocation);
-    xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, "/ows/1.1.0/owsAll.xsd");
-    xmlNewNsProp(psRootNode, NULL, BAD_CAST "xsi:schemaLocation", BAD_CAST xsi_schemaLocation);
-
-/* -------------------------------------------------------------------- */
-/*      Generate a CoverageDescription for each requested coverage.     */
-/* -------------------------------------------------------------------- */
-
-    if(params->coverages) { /* use the list */
-        for( j = 0; params->coverages[j]; j++ ) {
-            i = msGetLayerIndex(map, params->coverages[j]);
-            msWCSDescribeCoverage_CoverageDescription11((GET_LAYER(map, i)), 
-                                                        params, psRootNode,
-                                                        psOwsNs );
-        }
-    } else { /* return all layers */
-        for(i=0; i<map->numlayers; i++) {
-
-            if (!msIntegerInArray(GET_LAYER(map, i)->index, ows_request->enabled_layers, ows_request->numlayers))
-                continue;
-
-            msWCSDescribeCoverage_CoverageDescription11((GET_LAYER(map, i)), 
-                                                        params, psRootNode,
-                                                        psOwsNs );
-        }
+  xmlDocSetRootElement(psDoc, psRootNode);
+
+  /* -------------------------------------------------------------------- */
+  /*      Name spaces                                                     */
+  /* -------------------------------------------------------------------- */
+  xmlSetNs(psRootNode, xmlNewNs(psRootNode, BAD_CAST "http://www.opengis.net/wcs/1.1", NULL));
+  psOwsNs = xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_OWS_110_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_OWS_NAMESPACE_PREFIX);
+  xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_W3C_XLINK_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_W3C_XLINK_NAMESPACE_PREFIX);
+  xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_W3C_XSI_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_W3C_XSI_NAMESPACE_PREFIX);
+  xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_OGC_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_OGC_NAMESPACE_PREFIX );
+
+  schemaLocation = msEncodeHTMLEntities( msOWSGetSchemasLocation(map) );
+  xsi_schemaLocation = msStrdup("http://www.opengis.net/wcs/1.1");
+  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, " ");
+  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, schemaLocation);
+  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, "/wcs/1.1/wcsDescribeCoverage.xsd ");
+  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, MS_OWSCOMMON_OWS_110_NAMESPACE_URI);
+  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, " ");
+  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, schemaLocation);
+  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, "/ows/1.1.0/owsAll.xsd");
+  xmlNewNsProp(psRootNode, NULL, BAD_CAST "xsi:schemaLocation", BAD_CAST xsi_schemaLocation);
+  msFree(schemaLocation);
+  msFree(xsi_schemaLocation);
+
+  /* -------------------------------------------------------------------- */
+  /*      Generate a CoverageDescription for each requested coverage.     */
+  /* -------------------------------------------------------------------- */
+
+  if(params->coverages) { /* use the list */
+    for( j = 0; params->coverages[j]; j++ ) {
+      i = msGetLayerIndex(map, params->coverages[j]);
+      msWCSDescribeCoverage_CoverageDescription11((GET_LAYER(map, i)),
+          params, psRootNode,
+          psOwsNs );
     }
-  
-/* -------------------------------------------------------------------- */
-/*      Write out the document.                                         */
-/* -------------------------------------------------------------------- */
-    {
-        xmlChar *buffer = NULL;
-        int size = 0;
-        msIOContext *context = NULL;
-
-        if( msIO_needBinaryStdout() == MS_FAILURE )
-            return MS_FAILURE;
-     
-        if (encoding)
-            msIO_printf("Content-type: text/xml; charset=%s%c%c", encoding,10,10);
-        else
-            msIO_printf("Content-type: text/xml%c%c",10,10);
-    
-        context = msIO_getHandler(stdout);
-
-        xmlDocDumpFormatMemoryEnc(psDoc, &buffer, &size, (encoding ? encoding : "ISO-8859-1"), 1);
-        msIO_contextWrite(context, buffer, size);
-        xmlFree(buffer);
+  } else { /* return all layers */
+    for(i=0; i<map->numlayers; i++) {
+
+      if (!msIntegerInArray(GET_LAYER(map, i)->index, ows_request->enabled_layers, ows_request->numlayers))
+        continue;
+
+      msWCSDescribeCoverage_CoverageDescription11((GET_LAYER(map, i)),
+          params, psRootNode,
+          psOwsNs );
     }
-        
-/* -------------------------------------------------------------------- */
-/*      Cleanup                                                         */
-/* -------------------------------------------------------------------- */
-    xmlFreeDoc(psDoc);
-    xmlCleanupParser();
+  }
 
-    return MS_SUCCESS;
+  /* -------------------------------------------------------------------- */
+  /*      Write out the document.                                         */
+  /* -------------------------------------------------------------------- */
+  {
+    xmlChar *buffer = NULL;
+    int size = 0;
+    msIOContext *context = NULL;
+
+    if( msIO_needBinaryStdout() == MS_FAILURE )
+      return MS_FAILURE;
+
+    if (encoding)
+      msIO_setHeader("Content-Type","text/xml; charset=%s", encoding);
+    else
+      msIO_setHeader("Content-Type","text/xml");
+    msIO_sendHeaders();
+
+    context = msIO_getHandler(stdout);
+
+    xmlDocDumpFormatMemoryEnc(psDoc, &buffer, &size, (encoding ? encoding : "ISO-8859-1"), 1);
+    msIO_contextWrite(context, buffer, size);
+    xmlFree(buffer);
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Cleanup                                                         */
+  /* -------------------------------------------------------------------- */
+  xmlFreeDoc(psDoc);
+  xmlCleanupParser();
+
+  return MS_SUCCESS;
 }
 
 #endif /* defined(USE_WCS_SVR) && defined(USE_LIBXML2) */
@@ -1031,119 +1038,112 @@ int msWCSDescribeCoverage11(mapObj *map, wcsParamsObj *params, owsRequestObj *ow
 /************************************************************************/
 
 #if defined(USE_WCS_SVR)
-int msWCSGetCoverageBands11( mapObj *map, cgiRequestObj *request, 
+int msWCSGetCoverageBands11( mapObj *map, cgiRequestObj *request,
                              wcsParamsObj *params, layerObj *lp,
                              char **p_bandlist )
 
 {
-    char *rangesubset, *field_id;
-    const char *axis_id, *value;
-    int i;
-
-/* -------------------------------------------------------------------- */
-/*      Fetch the RangeSubset from the parameters, skip building a      */
-/*      bands list if not found.                                        */
-/* -------------------------------------------------------------------- */
-    value = msWCSGetRequestParameter(request, "RangeSubset");
-    if( value == NULL )
-        return MS_SUCCESS;
-
-    rangesubset = msStrdup(value);
-
-/* -------------------------------------------------------------------- */
-/*      What is the <Field identifier=...> (rangeset_name)?             */
-/* -------------------------------------------------------------------- */
-    value = msOWSLookupMetadata( &(lp->metadata), "CO", "rangeset_name" );
-    if( value == NULL )
-        value = "raster";
-    field_id = msStrdup(value);
-
-/* -------------------------------------------------------------------- */
-/*      What is the <Axis identifier=...> (bands_name)?                 */
-/* -------------------------------------------------------------------- */
-    axis_id = msOWSLookupMetadata( &(lp->metadata), "CO", "bands_name" );
-    if( axis_id == NULL )
-        axis_id = "bands";
-
-/* -------------------------------------------------------------------- */
-/*      Parse out the field identifier from the request and verify.     */
-/* -------------------------------------------------------------------- */
-    value = rangesubset + strlen(field_id);
-
-    if( strcasecmp(rangesubset,field_id) == 0 )
-        return MS_SUCCESS; /* we only got field ... default options */
-
-    if( strlen(rangesubset) <= strlen(field_id)+1 
-        || strncasecmp(rangesubset,field_id,strlen(field_id)) != 0 
-        || (*value != '[' && *value != ':') )
-    {
-        msSetError( MS_WCSERR, 
-                    "RangeSubset field name malformed, expected '%s', got RangeSubset=%s",
-                    "msWCSGetCoverageBands11()", 
-                    field_id, rangesubset );
-        return msWCSException11(map, "mapserv", "NoApplicableCode", params->version);
-    }
+  char *rangesubset, *field_id;
+  const char *axis_id, *value;
+  int i;
+
+  /* -------------------------------------------------------------------- */
+  /*      Fetch the RangeSubset from the parameters, skip building a      */
+  /*      bands list if not found.                                        */
+  /* -------------------------------------------------------------------- */
+  value = msWCSGetRequestParameter(request, "RangeSubset");
+  if( value == NULL )
+    return MS_SUCCESS;
 
-    free( field_id );
-    field_id = NULL;
-    
-/* -------------------------------------------------------------------- */
-/*      Parse out the interpolation, if found.                          */
-/* -------------------------------------------------------------------- */
-    if( *value == ':' )
-    {
-        assert( params->interpolation == NULL );
-        params->interpolation = msStrdup(value+1);
-        for( i = 0; params->interpolation[i] != '\0'; i++ )
-        {
-            if( params->interpolation[i] == '[' )
-            {
-                params->interpolation[i] = '\0';
-                break;
-            }
-        }
-
-        value += strlen(params->interpolation) + 1;
+  rangesubset = msStrdup(value);
+
+  /* -------------------------------------------------------------------- */
+  /*      What is the <Field identifier=...> (rangeset_name)?             */
+  /* -------------------------------------------------------------------- */
+  value = msOWSLookupMetadata( &(lp->metadata), "CO", "rangeset_name" );
+  if( value == NULL )
+    value = "raster";
+  field_id = msStrdup(value);
+
+  /* -------------------------------------------------------------------- */
+  /*      What is the <Axis identifier=...> (bands_name)?                 */
+  /* -------------------------------------------------------------------- */
+  axis_id = msOWSLookupMetadata( &(lp->metadata), "CO", "bands_name" );
+  if( axis_id == NULL )
+    axis_id = "bands";
+
+  /* -------------------------------------------------------------------- */
+  /*      Parse out the field identifier from the request and verify.     */
+  /* -------------------------------------------------------------------- */
+  value = rangesubset + strlen(field_id);
+
+  if( strcasecmp(rangesubset,field_id) == 0 )
+    return MS_SUCCESS; /* we only got field ... default options */
+
+  if( strlen(rangesubset) <= strlen(field_id)+1
+      || strncasecmp(rangesubset,field_id,strlen(field_id)) != 0
+      || (*value != '[' && *value != ':') ) {
+    msSetError( MS_WCSERR,
+                "RangeSubset field name malformed, expected '%s', got RangeSubset=%s",
+                "msWCSGetCoverageBands11()",
+                field_id, rangesubset );
+    return msWCSException11(map, "mapserv", "NoApplicableCode", params->version);
+  }
+
+  free( field_id );
+  field_id = NULL;
+
+  /* -------------------------------------------------------------------- */
+  /*      Parse out the interpolation, if found.                          */
+  /* -------------------------------------------------------------------- */
+  if( *value == ':' ) {
+    assert( params->interpolation == NULL );
+    params->interpolation = msStrdup(value+1);
+    for( i = 0; params->interpolation[i] != '\0'; i++ ) {
+      if( params->interpolation[i] == '[' ) {
+        params->interpolation[i] = '\0';
+        break;
+      }
     }
 
-/* -------------------------------------------------------------------- */
-/*      Parse out the axis name, and verify.                            */
-/* -------------------------------------------------------------------- */
-    if( *value != '[' )
-        return MS_SUCCESS;
+    value += strlen(params->interpolation) + 1;
+  }
 
-    value++;
+  /* -------------------------------------------------------------------- */
+  /*      Parse out the axis name, and verify.                            */
+  /* -------------------------------------------------------------------- */
+  if( *value != '[' )
+    return MS_SUCCESS;
 
-    if( strlen(value) <= strlen(axis_id)+1
-        || strncasecmp(value,axis_id,strlen(axis_id)) != 0
-        || value[strlen(axis_id)] != '[' )
-    {
-        msSetError( MS_WCSERR, 
-                    "RangeSubset axis name malformed, expected '%s', got RangeSubset=%s",
-                    "msWCSGetCoverageBands11()", 
-                    axis_id, rangesubset );
-        return msWCSException11(map, "mapserv", "NoApplicableCode", params->version);
-    }
+  value++;
 
-/* -------------------------------------------------------------------- */
-/*      Parse the band list.  Basically assuming the band list is       */
-/*      everything from here to a close ';'.                            */
-/* -------------------------------------------------------------------- */
-    value += strlen(axis_id) + 1;
+  if( strlen(value) <= strlen(axis_id)+1
+      || strncasecmp(value,axis_id,strlen(axis_id)) != 0
+      || value[strlen(axis_id)] != '[' ) {
+    msSetError( MS_WCSERR,
+                "RangeSubset axis name malformed, expected '%s', got RangeSubset=%s",
+                "msWCSGetCoverageBands11()",
+                axis_id, rangesubset );
+    return msWCSException11(map, "mapserv", "NoApplicableCode", params->version);
+  }
 
-    *p_bandlist = msStrdup(value);
+  /* -------------------------------------------------------------------- */
+  /*      Parse the band list.  Basically assuming the band list is       */
+  /*      everything from here to a close ';'.                            */
+  /* -------------------------------------------------------------------- */
+  value += strlen(axis_id) + 1;
 
-    for( i = 0; (*p_bandlist)[i] != '\0'; i++ )
-    {
-        if( (*p_bandlist)[i] == '[' )
-        {
-            (*p_bandlist)[i] = '\0';
-            break;
-        }
+  *p_bandlist = msStrdup(value);
+
+  for( i = 0; (*p_bandlist)[i] != '\0'; i++ ) {
+    if( (*p_bandlist)[i] == '[' ) {
+      (*p_bandlist)[i] = '\0';
+      break;
     }
+  }
 
-    return MS_SUCCESS;
-}    
+  return MS_SUCCESS;
+}
 #endif
 
 /************************************************************************/
@@ -1154,246 +1154,231 @@ int msWCSGetCoverageBands11( mapObj *map, cgiRequestObj *request,
 /************************************************************************/
 
 #if defined(USE_WCS_SVR)
-int  msWCSReturnCoverage11( wcsParamsObj *params, mapObj *map, 
+int  msWCSReturnCoverage11( wcsParamsObj *params, mapObj *map,
                             imageObj *image )
 {
-    int status, i;
-    char *filename = NULL;
-    const char *encoding;
-    const char *fo_filename;
-
-    encoding = msOWSLookupMetadata(&(map->web.metadata), "CO", "encoding");
-
-    fo_filename = msGetOutputFormatOption( image->format, "FILENAME", NULL );
-        
-/* -------------------------------------------------------------------- */
-/*      Fetch the driver we will be using and check if it supports      */
-/*      VSIL IO.                                                        */
-/* -------------------------------------------------------------------- */
-#ifdef GDAL_DCAP_VIRTUALIO
-    if( EQUALN(image->format->driver,"GDAL/",5) )
-    {
-        GDALDriverH hDriver;
-        const char *pszExtension = image->format->extension;
-
-        msAcquireLock( TLOCK_GDAL );
-        hDriver = GDALGetDriverByName( image->format->driver+5 );
-        if( hDriver == NULL )
-        {
-            msReleaseLock( TLOCK_GDAL );
-            msSetError( MS_MISCERR, 
-                        "Failed to find %s driver.",
-                        "msWCSReturnCoverage11()", 
-                        image->format->driver+5 );
-            return msWCSException11(map, "mapserv", "NoApplicableCode", 
-                                    params->version);
-        }
-        
-        if( pszExtension == NULL )
-            pszExtension = "img.tmp";
-
-        if( GDALGetMetadataItem( hDriver, GDAL_DCAP_VIRTUALIO, NULL ) 
-            != NULL )
-        {
-            if( fo_filename )
-                filename = msStrdup(CPLFormFilename("/vsimem/wcsout",
-                                                    fo_filename,NULL));
-            else
-                filename = msStrdup(CPLFormFilename("/vsimem/wcsout", 
-                                                    "out", pszExtension ));
-
-/*            CleanVSIDir( "/vsimem/wcsout" ); */
-            
-            msReleaseLock( TLOCK_GDAL );
-            status = msSaveImage(map, image, filename);
-            if( status != MS_SUCCESS )
-            {
-                msSetError(MS_MISCERR, "msSaveImage() failed", 
-                           "msWCSReturnCoverage11()");
-                return msWCSException11(map, "mapserv", "NoApplicableCode", 
-                                        params->version);
-            }
-        }
-        msReleaseLock( TLOCK_GDAL );
+  int status, i;
+  char *filename = NULL;
+  char *base_dir = NULL;
+  const char *encoding;
+  const char *fo_filename;
+
+  encoding = msOWSLookupMetadata(&(map->web.metadata), "CO", "encoding");
+
+  fo_filename = msGetOutputFormatOption( image->format, "FILENAME", NULL );
+
+  /* -------------------------------------------------------------------- */
+  /*      Fetch the driver we will be using and check if it supports      */
+  /*      VSIL IO.                                                        */
+  /* -------------------------------------------------------------------- */
+  if( EQUALN(image->format->driver,"GDAL/",5) ) {
+    GDALDriverH hDriver;
+    const char *pszExtension = image->format->extension;
+
+    msAcquireLock( TLOCK_GDAL );
+    hDriver = GDALGetDriverByName( image->format->driver+5 );
+    if( hDriver == NULL ) {
+      msReleaseLock( TLOCK_GDAL );
+      msSetError( MS_MISCERR,
+                  "Failed to find %s driver.",
+                  "msWCSReturnCoverage11()",
+                  image->format->driver+5 );
+      return msWCSException11(map, "mapserv", "NoApplicableCode",
+                              params->version);
     }
-#endif
 
-/* -------------------------------------------------------------------- */
-/*      Output stock header.                                            */
-/* -------------------------------------------------------------------- */
-    if (encoding)
-        msIO_fprintf( 
-            stdout, 
-            "Content-Type: multipart/mixed; boundary=wcs%c%c"
-            "--wcs\n"
-            "Content-Type: text/xml; charset=%s\n"
-            "Content-ID: wcs.xml%c%c"
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
-            "<Coverages\n"
-            "     xmlns=\"http://www.opengis.net/wcs/1.1\"\n"
-            "     xmlns:ows=\"http://www.opengis.net/ows/1.1\"\n"
-            "     xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n"
-            "     xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
-            "     xsi:schemaLocation=\"http://www.opengis.net/ows/1.1 ../owsCoverages.xsd\">\n"
-            "  <Coverage>\n",
-            10, 10,
-            encoding,
-            10, 10 );
-    else
-        msIO_fprintf( 
-            stdout, 
-            "Content-Type: multipart/mixed; boundary=wcs%c%c"
-            "--wcs\n"
-            "Content-Type: text/xml\n"
-            "Content-ID: wcs.xml%c%c"
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
-            "<Coverages\n"
-            "     xmlns=\"http://www.opengis.net/wcs/1.1\"\n"
-            "     xmlns:ows=\"http://www.opengis.net/ows/1.1\"\n"
-            "     xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n"
-            "     xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
-            "     xsi:schemaLocation=\"http://www.opengis.net/ows/1.1 ../owsCoverages.xsd\">\n"
-            "  <Coverage>\n",
-            10, 10,
-            10, 10 );
-
-/* -------------------------------------------------------------------- */
-/*      If we weren't able to write data under /vsimem, then we just    */
-/*      output a single "stock" filename.                               */
-/* -------------------------------------------------------------------- */
-    if( filename == NULL )
-    {
-        msIO_fprintf( 
-            stdout,
-            "    <ows:Reference xlink:href=\"cid:coverage/wcs.%s\"/>\n"
-            "  </Coverage>\n"
-            "</Coverages>\n"
-            "--wcs\n"
-            "Content-Type: %s\n"
-            "Content-Description: coverage data\n"
-            "Content-Transfer-Encoding: binary\n"
-            "Content-ID: coverage/wcs.%s\n"
-            "Content-Disposition: INLINE%c%c",
-            MS_IMAGE_EXTENSION(map->outputformat),
-            MS_IMAGE_MIME_TYPE(map->outputformat),
-            MS_IMAGE_EXTENSION(map->outputformat),
-            10, 10 );
-
-        status = msSaveImage(map, image, NULL);
-        if( status != MS_SUCCESS )
-        {
-            msSetError( MS_MISCERR, "msSaveImage() failed", "msWCSReturnCoverage11()");
-            return msWCSException11(map, "mapserv", "NoApplicableCode", params->version);
-        }
-
-        msIO_fprintf( stdout, "\n--wcs--%c%c", 10, 10 );
-        return MS_SUCCESS;
+    if( pszExtension == NULL )
+      pszExtension = "img.tmp";
+
+    if( GDALGetMetadataItem( hDriver, GDAL_DCAP_VIRTUALIO, NULL )
+        != NULL ) {
+      base_dir = msTmpFile(map, map->mappath, "/vsimem/wcsout", NULL);
+      if( fo_filename )
+        filename = msStrdup(CPLFormFilename(base_dir,
+                                            fo_filename,NULL));
+      else
+        filename = msStrdup(CPLFormFilename(base_dir,
+                                            "out", pszExtension ));
+
+      /*            CleanVSIDir( "/vsimem/wcsout" ); */
+
+      msReleaseLock( TLOCK_GDAL );
+      status = msSaveImage(map, image, filename);
+      if( status != MS_SUCCESS ) {
+        msFree(filename);
+        msSetError(MS_MISCERR, "msSaveImage() failed",
+                   "msWCSReturnCoverage11()");
+        return msWCSException11(map, "mapserv", "NoApplicableCode",
+                                params->version);
+      }
     }
+    msReleaseLock( TLOCK_GDAL );
+  }
 
-/* -------------------------------------------------------------------- */
-/*      When potentially listing multiple files, we take great care     */
-/*      to identify the "primary" file and list it first.  In fact      */
-/*      it is the only file listed in the coverages document.           */
-/* -------------------------------------------------------------------- */
-#ifdef GDAL_DCAP_VIRTUALIO
-    {
-        char **all_files = CPLReadDir( "/vsimem/wcsout" );
-        int count = CSLCount(all_files);
-
-        if( msIO_needBinaryStdout() == MS_FAILURE )
-            return MS_FAILURE;
-
-        msAcquireLock( TLOCK_GDAL );
-        for( i = count-1; i >= 0; i-- )
-        {
-            const char *this_file = all_files[i];
-
-            if( EQUAL(this_file,".") || EQUAL(this_file,"..") )
-            {
-                all_files = CSLRemoveStrings( all_files, i, 1, NULL );
-                continue;
-            }
-
-            if( i > 0 && EQUAL(this_file,CPLGetFilename(filename)) )
-            {
-                all_files = CSLRemoveStrings( all_files, i, 1, NULL );
-                all_files = CSLInsertString(all_files,0,CPLGetFilename(filename));
-                i++;
-            }
-        }
-        
-        msIO_fprintf( 
-            stdout,
-            "    <ows:Reference xlink:href=\"cid:coverage/%s\"/>\n"
-            "  </Coverage>\n"
-            "</Coverages>\n",
-            CPLGetFilename(filename) );
-
-/* -------------------------------------------------------------------- */
-/*      Dump all the files in the memory directory as mime sections.    */
-/* -------------------------------------------------------------------- */
-        count = CSLCount(all_files);
-
-        for( i = 0; i < count; i++ )
-        {
-            const char *mimetype = NULL;
-            FILE *fp; 
-            unsigned char block[4000];
-            int bytes_read;
-
-            if( i == 0 )
-                mimetype = MS_IMAGE_MIME_TYPE(map->outputformat);
-            
-            if( mimetype == NULL )
-                mimetype = "application/octet-stream";
-
-            msIO_fprintf( 
-                stdout, 
-                "--wcs\n"
-                "Content-Type: %s\n"
-                "Content-Description: coverage data\n"
-                "Content-Transfer-Encoding: binary\n"
-                "Content-ID: coverage/%s\n"
-                "Content-Disposition: INLINE%c%c",
-                mimetype, 
-                all_files[i], 
-                10, 10 );
-
-            fp = VSIFOpenL( 
-                CPLFormFilename("/vsimem/wcsout", all_files[i], NULL),
-                "rb" );
-            if( fp == NULL )
-            {
-                msReleaseLock( TLOCK_GDAL );
-                msSetError( MS_MISCERR, 
-                            "Failed to open %s for streaming to stdout.",
-                            "msWCSReturnCoverage11()", all_files[i] );
-                return MS_FAILURE;
-            }
-            
-            while( (bytes_read = VSIFReadL(block, 1, sizeof(block), fp)) > 0 )
-                msIO_fwrite( block, 1, bytes_read, stdout );
-
-            VSIFCloseL( fp );
-
-            VSIUnlink( all_files[i] );
-        }
-
-        CSLDestroy( all_files );
+  /* -------------------------------------------------------------------- */
+  /*      Output stock header.                                            */
+  /* -------------------------------------------------------------------- */
+  if (encoding) {
+    msIO_setHeader("Content-Type","multipart/mixed; boundary=wcs");
+    msIO_sendHeaders();
+    msIO_fprintf(
+      stdout,
+      "\r\n--wcs\r\n"
+      "Content-Type: text/xml; charset=%s\r\n"
+      "Content-ID: wcs.xml\r\n\r\n"
+      "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+      "<Coverages\n"
+      "     xmlns=\"http://www.opengis.net/wcs/1.1\"\n"
+      "     xmlns:ows=\"http://www.opengis.net/ows/1.1\"\n"
+      "     xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n"
+      "     xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
+      "     xsi:schemaLocation=\"http://www.opengis.net/ows/1.1 ../owsCoverages.xsd\">\n"
+      "  <Coverage>\n",
+      encoding);
+  } else {
+    msIO_setHeader("Content-Type","multipart/mixed; boundary=wcs");
+    msIO_sendHeaders();
+    msIO_fprintf(
+      stdout,
+      "\r\n--wcs\r\n"
+      "Content-Type: text/xml\r\n"
+      "Content-ID: wcs.xml\r\n\r\n"
+      "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+      "<Coverages\n"
+      "     xmlns=\"http://www.opengis.net/wcs/1.1\"\n"
+      "     xmlns:ows=\"http://www.opengis.net/ows/1.1\"\n"
+      "     xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n"
+      "     xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
+      "     xsi:schemaLocation=\"http://www.opengis.net/ows/1.1 ../owsCoverages.xsd\">\n"
+      "  <Coverage>\n");
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      If we weren't able to write data under /vsimem, then we just    */
+  /*      output a single "stock" filename.                               */
+  /* -------------------------------------------------------------------- */
+  if( filename == NULL ) {
+    msIO_fprintf(
+      stdout,
+      "    <ows:Reference xlink:href=\"cid:coverage/wcs.%s\"/>\n"
+      "  </Coverage>\n"
+      "</Coverages>\n"
+      "\r\n--wcs\r\n"
+      "Content-Type: %s\r\n"
+      "Content-Description: coverage data\r\n"
+      "Content-Transfer-Encoding: binary\r\n"
+      "Content-ID: coverage/wcs.%s\r\n"
+      "Content-Disposition: INLINE\r\n\r\n",
+      MS_IMAGE_EXTENSION(map->outputformat),
+      MS_IMAGE_MIME_TYPE(map->outputformat),
+      MS_IMAGE_EXTENSION(map->outputformat));
+
+    status = msSaveImage(map, image, NULL);
+    if( status != MS_SUCCESS ) {
+      msSetError( MS_MISCERR, "msSaveImage() failed", "msWCSReturnCoverage11()");
+      return msWCSException11(map, "mapserv", "NoApplicableCode", params->version);
+    }
+
+    msIO_fprintf( stdout, "\r\n--wcs--\r\n" );
+    return MS_SUCCESS;
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      When potentially listing multiple files, we take great care     */
+  /*      to identify the "primary" file and list it first.  In fact      */
+  /*      it is the only file listed in the coverages document.           */
+  /* -------------------------------------------------------------------- */
+  {
+    char **all_files = CPLReadDir( base_dir );
+    int count = CSLCount(all_files);
+
+    if( msIO_needBinaryStdout() == MS_FAILURE )
+      return MS_FAILURE;
+
+    msAcquireLock( TLOCK_GDAL );
+    for( i = count-1; i >= 0; i-- ) {
+      const char *this_file = all_files[i];
+
+      if( EQUAL(this_file,".") || EQUAL(this_file,"..") ) {
+        all_files = CSLRemoveStrings( all_files, i, 1, NULL );
+        continue;
+      }
+
+      if( i > 0 && EQUAL(this_file,CPLGetFilename(filename)) ) {
+        all_files = CSLRemoveStrings( all_files, i, 1, NULL );
+        all_files = CSLInsertString(all_files,0,CPLGetFilename(filename));
+        i++;
+      }
+    }
+
+    msIO_fprintf(
+      stdout,
+      "    <ows:Reference xlink:href=\"cid:coverage/%s\"/>\n"
+      "  </Coverage>\n"
+      "</Coverages>\n",
+      CPLGetFilename(filename) );
+
+    /* -------------------------------------------------------------------- */
+    /*      Dump all the files in the memory directory as mime sections.    */
+    /* -------------------------------------------------------------------- */
+    count = CSLCount(all_files);
+
+    for( i = 0; i < count; i++ ) {
+      const char *mimetype = NULL;
+      FILE *fp;
+      unsigned char block[4000];
+      int bytes_read;
+
+      if( i == 0 )
+        mimetype = MS_IMAGE_MIME_TYPE(map->outputformat);
+
+      if( mimetype == NULL )
+        mimetype = "application/octet-stream";
+
+      msIO_fprintf(
+        stdout,
+        "\r\n--wcs\r\n"
+        "Content-Type: %s\r\n"
+        "Content-Description: coverage data\r\n"
+        "Content-Transfer-Encoding: binary\r\n"
+        "Content-ID: coverage/%s\r\n"
+        "Content-Disposition: INLINE\r\n\r\n",
+        mimetype,
+        all_files[i]);
+
+      fp = VSIFOpenL(
+             CPLFormFilename(base_dir, all_files[i], NULL),
+             "rb" );
+      if( fp == NULL ) {
         msReleaseLock( TLOCK_GDAL );
+        msSetError( MS_MISCERR,
+                    "Failed to open %s for streaming to stdout.",
+                    "msWCSReturnCoverage11()", all_files[i] );
+        return MS_FAILURE;
+      }
+
+      while( (bytes_read = VSIFReadL(block, 1, sizeof(block), fp)) > 0 )
+        msIO_fwrite( block, 1, bytes_read, stdout );
 
-        msIO_fprintf( stdout, "\n--wcs--%c%c", 10, 10 );
-        return MS_SUCCESS;
+      VSIFCloseL( fp );
+
+      VSIUnlink( CPLFormFilename(base_dir, all_files[i], NULL) );
     }
-#else
+
+    msFree(base_dir);
+    msFree(filename);
+    CSLDestroy( all_files );
+    msReleaseLock( TLOCK_GDAL );
+
+    msIO_fprintf( stdout, "\r\n--wcs--\r\n" );
     return MS_SUCCESS;
-#endif /* def GDAL_DCAP_VIRTUALIO */
+  }
 }
 #endif /* defined(USE_WCS_SVR) && defined(USE_LIBXML2) */
 
 /************************************************************************/
 /* ==================================================================== */
-/*	If we don't have libxml2 but WCS SVR was selected, then         */
+/*  If we don't have libxml2 but WCS SVR was selected, then         */
 /*      report WCS 1.1 requests as unsupported.                         */
 /* ==================================================================== */
 /************************************************************************/
@@ -1404,31 +1389,31 @@ int  msWCSReturnCoverage11( wcsParamsObj *params, mapObj *map,
 
 /* ==================================================================== */
 
-int msWCSDescribeCoverage11(mapObj *map, wcsParamsObj *params)
-
+int msWCSDescribeCoverage11(mapObj *map, wcsParamsObj *params,
+                            owsRequestObj *ows_request)
 {
-    msSetError( MS_WCSERR,
-                "WCS 1.1 request made, but mapserver requires libxml2 for WCS 1.1 services and this is not configured.",
-                "msWCSDescribeCoverage11()", "NoApplicableCode" );
-    return msWCSException11(map, "mapserv", "NoApplicableCode", params->version);
+  msSetError( MS_WCSERR,
+              "WCS 1.1 request made, but mapserver requires libxml2 for WCS 1.1 services and this is not configured.",
+              "msWCSDescribeCoverage11()", "NoApplicableCode" );
+  return msWCSException11(map, "mapserv", "NoApplicableCode", params->version);
 }
 
 /* ==================================================================== */
 
-int msWCSGetCapabilities11(mapObj *map, wcsParamsObj *params, 
-                                  cgiRequestObj *req)
-
+int msWCSGetCapabilities11(mapObj *map, wcsParamsObj *params,
+                           cgiRequestObj *req, owsRequestObj *ows_request)
 {
-    msSetError( MS_WCSERR,
-                "WCS 1.1 request made, but mapserver requires libxml2 for WCS 1.1 services and this is not configured.",
-                "msWCSGetCapabilities11()", "NoApplicableCode" );
+  msSetError( MS_WCSERR,
+              "WCS 1.1 request made, but mapserver requires libxml2 for WCS 1.1 services and this is not configured.",
+              "msWCSGetCapabilities11()", "NoApplicableCode" );
 
-    return msWCSException11(map, "mapserv", "NoApplicableCode", params->version);
+  return msWCSException11(map, "mapserv", "NoApplicableCode", params->version);
 }
 
-int msWCSException11(mapObj *map, const char *locator, const char *exceptionCode, const char *version) {
-    /* fallback to reporting using 1.0 style exceptions. */
-    return msWCSException( map, locator, exceptionCode, "1.0.0" );
+int msWCSException11(mapObj *map, const char *locator, const char *exceptionCode, const char *version)
+{
+  /* fallback to reporting using 1.0 style exceptions. */
+  return msWCSException( map, locator, exceptionCode, "1.0.0" );
 }
 
 #endif /* defined(USE_WCS_SVR) && !defined(USE_LIBXML2) */
diff --git a/mapwcs20.c b/mapwcs20.c
index 8f40e66..33a282d 100644
--- a/mapwcs20.c
+++ b/mapwcs20.c
@@ -44,17 +44,16 @@
 #include "cpl_string.h"
 #include <proj_api.h>
 #include <string.h>
-#include "mapaxisorder.h"
 
 #if defined(USE_LIBXML2)
 
-    #include <libxml/tree.h>
-    #include "maplibxml2.h"
-    #include <libxml/parser.h>
+#include <libxml/tree.h>
+#include "maplibxml2.h"
+#include <libxml/parser.h>
 
 #endif /* defined(USE_LIBXML2) */
 
-MS_CVSID("$Id$")
+
 
 /************************************************************************/
 /*                   msStringParseInteger()                             */
@@ -68,17 +67,14 @@ MS_CVSID("$Id$")
 
 static int msStringParseInteger(const char *string, int *dest)
 {
-    char *parse_check;
-    *dest = (int)strtol(string, &parse_check, 0);
-    if(parse_check == string)
-    {
-        return MS_FAILURE;
-    }
-    else if(parse_check - strlen(string) != string)
-    {
-        return MS_DONE;
-    }
-    return MS_SUCCESS;
+  char *parse_check;
+  *dest = (int)strtol(string, &parse_check, 0);
+  if(parse_check == string) {
+    return MS_FAILURE;
+  } else if(parse_check - strlen(string) != string) {
+    return MS_DONE;
+  }
+  return MS_SUCCESS;
 }
 
 /************************************************************************/
@@ -93,17 +89,14 @@ static int msStringParseInteger(const char *string, int *dest)
 
 static int msStringParseDouble(const char *string, double *dest)
 {
-    char *parse_check = NULL;
-    *dest = strtod(string, &parse_check);
-    if(parse_check == string)
-    {
-        return MS_FAILURE;
-    }
-    else if(parse_check - strlen(string) != string)
-    {
-        return MS_DONE;
-    }
-    return MS_SUCCESS;
+  char *parse_check = NULL;
+  *dest = strtod(string, &parse_check);
+  if(parse_check == string) {
+    return MS_FAILURE;
+  } else if(parse_check - strlen(string) != string) {
+    return MS_DONE;
+  }
+  return MS_SUCCESS;
 }
 
 /************************************************************************/
@@ -115,58 +108,41 @@ static int msStringParseDouble(const char *string, double *dest)
 
 static int msWCSParseTimeOrScalar20(timeScalarUnion *u, const char *string)
 {
-    struct tm time;
-    if (string)
-    {
-        while(*string == ' ')
-            string ++;
-    }
-
-    if (!string || strlen(string) == 0 || !u)
-    {
-        msSetError(MS_WCSERR, "Invalid string", "msWCSParseTimeOrScalar20()");
-        return MS_WCS20_ERROR_VALUE;
-    }
-    /* if the string is equal to "*" it means the value
-     *  of the interval is unbounded                    */
-    if (EQUAL(string, "*"))
-    {
-        u->scalar = MS_WCS20_UNBOUNDED;
-        u->unbounded = 1;
-        return MS_WCS20_UNDEFINED_VALUE;
-    }
-
-    /* if returned a valid value, use it */
-    if (msStringParseDouble(string, &(u->scalar)) == MS_SUCCESS)
-    {
-        return MS_WCS20_SCALAR_VALUE;
-    }
-    /* otherwise it might be a time value */
-    msTimeInit(&time);
-    if (msParseTime(string, &time) == MS_TRUE)
-    {
-        u->time = mktime(&time);
-        return MS_WCS20_TIME_VALUE;
-    }
-    /* the value could neither be parsed as a double nor as a time value */
-    else
-    {
-        msSetError(MS_WCSERR,
-                "String %s could not be parsed to a time or scalar value",
-                "msWCSParseTimeOrScalar20()");
-        return MS_WCS20_ERROR_VALUE;
-    }
-}
-
-/************************************************************************/
-/*                   msStringIsNCName()                                 */
-/*                                                                      */
-/*      Evaluates if a string is a valid NCName.                        */
-/************************************************************************/
-
-static int msStringIsNCName(char *string)
-{
-    return msEvalRegex("^[a-zA-z_][a-zA-Z0-9_.-]*$" , string);
+  struct tm time;
+  if (string) {
+    while(*string == ' ')
+      string ++;
+  }
+
+  if (!string || strlen(string) == 0 || !u) {
+    msSetError(MS_WCSERR, "Invalid string", "msWCSParseTimeOrScalar20()");
+    return MS_WCS20_ERROR_VALUE;
+  }
+  /* if the string is equal to "*" it means the value
+   *  of the interval is unbounded                    */
+  if (EQUAL(string, "*")) {
+    u->scalar = MS_WCS20_UNBOUNDED;
+    u->unbounded = 1;
+    return MS_WCS20_UNDEFINED_VALUE;
+  }
+
+  /* if returned a valid value, use it */
+  if (msStringParseDouble(string, &(u->scalar)) == MS_SUCCESS) {
+    return MS_WCS20_SCALAR_VALUE;
+  }
+  /* otherwise it might be a time value */
+  msTimeInit(&time);
+  if (msParseTime(string, &time) == MS_TRUE) {
+    u->time = mktime(&time);
+    return MS_WCS20_TIME_VALUE;
+  }
+  /* the value could neither be parsed as a double nor as a time value */
+  else {
+    msSetError(MS_WCSERR,
+               "String %s could not be parsed to a time or scalar value",
+               "msWCSParseTimeOrScalar20()");
+    return MS_WCS20_ERROR_VALUE;
+  }
 }
 
 /************************************************************************/
@@ -178,16 +154,16 @@ static int msStringIsNCName(char *string)
 
 static wcs20SubsetObjPtr msWCSCreateSubsetObj20()
 {
-    wcs20SubsetObjPtr subset = (wcs20SubsetObjPtr) malloc(sizeof(wcs20SubsetObj));
-    MS_CHECK_ALLOC(subset, sizeof(wcs20SubsetObj), NULL);
+  wcs20SubsetObjPtr subset = (wcs20SubsetObjPtr) malloc(sizeof(wcs20SubsetObj));
+  MS_CHECK_ALLOC(subset, sizeof(wcs20SubsetObj), NULL);
 
-    subset->axis = NULL;
-    subset->crs = NULL;
-    subset->min.scalar = subset->max.scalar = MS_WCS20_UNBOUNDED;
-    subset->min.unbounded = subset->max.unbounded = 0;
-    subset->operation = MS_WCS20_SLICE;
+  subset->axis = NULL;
+  subset->crs = NULL;
+  subset->min.scalar = subset->max.scalar = MS_WCS20_UNBOUNDED;
+  subset->min.unbounded = subset->max.unbounded = 0;
+  subset->operation = MS_WCS20_SLICE;
 
-    return subset;
+  return subset;
 }
 
 /************************************************************************/
@@ -198,13 +174,12 @@ static wcs20SubsetObjPtr msWCSCreateSubsetObj20()
 
 static void msWCSFreeSubsetObj20(wcs20SubsetObjPtr subset)
 {
-    if (NULL == subset)
-    {
-        return;
-    }
-    msFree(subset->axis);
-    msFree(subset->crs);
-    msFree(subset);
+  if (NULL == subset) {
+    return;
+  }
+  msFree(subset->axis);
+  msFree(subset->crs);
+  msFree(subset);
 }
 
 /************************************************************************/
@@ -216,16 +191,16 @@ static void msWCSFreeSubsetObj20(wcs20SubsetObjPtr subset)
 
 static wcs20AxisObjPtr msWCSCreateAxisObj20()
 {
-    wcs20AxisObj *axis = (wcs20AxisObjPtr)malloc(sizeof(wcs20AxisObj));
-    MS_CHECK_ALLOC(axis, sizeof(wcs20AxisObj), NULL);
+  wcs20AxisObj *axis = (wcs20AxisObjPtr)malloc(sizeof(wcs20AxisObj));
+  MS_CHECK_ALLOC(axis, sizeof(wcs20AxisObj), NULL);
 
-    axis->name = NULL;
-    axis->size = 0;
-    axis->resolution = MS_WCS20_UNBOUNDED;
-    axis->resolutionUOM = NULL;
-    axis->subset = NULL;
+  axis->name = NULL;
+  axis->size = 0;
+  axis->resolution = MS_WCS20_UNBOUNDED;
+  axis->resolutionUOM = NULL;
+  axis->subset = NULL;
 
-    return axis;
+  return axis;
 }
 
 /************************************************************************/
@@ -236,15 +211,14 @@ static wcs20AxisObjPtr msWCSCreateAxisObj20()
 
 static void msWCSFreeAxisObj20(wcs20AxisObjPtr axis)
 {
-    if(NULL == axis)
-    {
-        return;
-    }
-
-    msFree(axis->name);
-    msFree(axis->resolutionUOM);
-    msWCSFreeSubsetObj20(axis->subset);
-    msFree(axis);
+  if(NULL == axis) {
+    return;
+  }
+
+  msFree(axis->name);
+  msFree(axis->resolutionUOM);
+  msWCSFreeSubsetObj20(axis->subset);
+  msFree(axis);
 }
 
 /************************************************************************/
@@ -255,17 +229,15 @@ static void msWCSFreeAxisObj20(wcs20AxisObjPtr axis)
 /************************************************************************/
 
 static wcs20AxisObjPtr msWCSFindAxis20(wcs20ParamsObjPtr params,
-        const char *name)
+                                       const char *name)
 {
-    int i = 0;
-    for(i = 0; i < params->numaxes; ++i)
-    {
-        if(EQUAL(params->axes[i]->name, name))
-        {
-            return params->axes[i];
-        }
+  int i = 0;
+  for(i = 0; i < params->numaxes; ++i) {
+    if(EQUAL(params->axes[i]->name, name)) {
+      return params->axes[i];
     }
-    return NULL;
+  }
+  return NULL;
 }
 
 /************************************************************************/
@@ -277,10 +249,10 @@ static wcs20AxisObjPtr msWCSFindAxis20(wcs20ParamsObjPtr params,
 
 static void msWCSInsertAxisObj20(wcs20ParamsObjPtr params, wcs20AxisObjPtr axis)
 {
-    params->numaxes++;
-    params->axes = (wcs20AxisObjPtr*) msSmallRealloc(params->axes,
-            sizeof(wcs20AxisObjPtr) * (params->numaxes));
-    params->axes[params->numaxes - 1] = axis;
+  params->numaxes++;
+  params->axes = (wcs20AxisObjPtr*) msSmallRealloc(params->axes,
+                 sizeof(wcs20AxisObjPtr) * (params->numaxes));
+  params->axes[params->numaxes - 1] = axis;
 }
 
 /************************************************************************/
@@ -292,34 +264,34 @@ static void msWCSInsertAxisObj20(wcs20ParamsObjPtr params, wcs20AxisObjPtr axis)
 
 wcs20ParamsObjPtr msWCSCreateParamsObj20()
 {
-    wcs20ParamsObjPtr params
-        = (wcs20ParamsObjPtr) malloc(sizeof(wcs20ParamsObj));
-    MS_CHECK_ALLOC(params, sizeof(wcs20ParamsObj), NULL);
-
-    params->version         = NULL;
-    params->request         = NULL;
-    params->service         = NULL;
-    params->accept_versions = NULL;
-    params->sections        = NULL;
-    params->updatesequence  = NULL;
-    params->ids             = NULL;
-    params->width           = 0;
-    params->height          = 0;
-    params->resolutionX     = MS_WCS20_UNBOUNDED;
-    params->resolutionY     = MS_WCS20_UNBOUNDED;
-    params->resolutionUnits = NULL;
-    params->numaxes         = 0;
-    params->axes            = NULL;
-    params->format          = NULL;
-    params->multipart       = 0;
-    params->interpolation   = NULL;
-    params->outputcrs       = NULL;
-    params->subsetcrs       = NULL;
-    params->bbox.minx = params->bbox.miny = -DBL_MAX;
-    params->bbox.maxx = params->bbox.maxy =  DBL_MAX;
-    params->range_subset    = NULL;
-
-    return params;
+  wcs20ParamsObjPtr params
+    = (wcs20ParamsObjPtr) malloc(sizeof(wcs20ParamsObj));
+  MS_CHECK_ALLOC(params, sizeof(wcs20ParamsObj), NULL);
+
+  params->version         = NULL;
+  params->request         = NULL;
+  params->service         = NULL;
+  params->accept_versions = NULL;
+  params->sections        = NULL;
+  params->updatesequence  = NULL;
+  params->ids             = NULL;
+  params->width           = 0;
+  params->height          = 0;
+  params->resolutionX     = MS_WCS20_UNBOUNDED;
+  params->resolutionY     = MS_WCS20_UNBOUNDED;
+  params->resolutionUnits = NULL;
+  params->numaxes         = 0;
+  params->axes            = NULL;
+  params->format          = NULL;
+  params->multipart       = 0;
+  params->interpolation   = NULL;
+  params->outputcrs       = NULL;
+  params->subsetcrs       = NULL;
+  params->bbox.minx = params->bbox.miny = -DBL_MAX;
+  params->bbox.maxx = params->bbox.maxy =  DBL_MAX;
+  params->range_subset    = NULL;
+
+  return params;
 }
 
 /************************************************************************/
@@ -330,31 +302,29 @@ wcs20ParamsObjPtr msWCSCreateParamsObj20()
 
 void msWCSFreeParamsObj20(wcs20ParamsObjPtr params)
 {
-    if (NULL == params)
-    {
-        return;
-    }
-
-    msFree(params->version);
-    msFree(params->request);
-    msFree(params->service);
-    CSLDestroy(params->accept_versions);
-    CSLDestroy(params->sections);
-    msFree(params->updatesequence);
-    CSLDestroy(params->ids);
-    msFree(params->resolutionUnits);
-    msFree(params->format);
-    msFree(params->interpolation);
-    msFree(params->outputcrs);
-    msFree(params->subsetcrs);
-    while(params->numaxes > 0)
-    {
-        params->numaxes -= 1;
-        msWCSFreeAxisObj20(params->axes[params->numaxes]);
-    }
-    msFree(params->axes);
-    CSLDestroy(params->range_subset);
-    msFree(params);
+  if (NULL == params) {
+    return;
+  }
+
+  msFree(params->version);
+  msFree(params->request);
+  msFree(params->service);
+  CSLDestroy(params->accept_versions);
+  CSLDestroy(params->sections);
+  msFree(params->updatesequence);
+  CSLDestroy(params->ids);
+  msFree(params->resolutionUnits);
+  msFree(params->format);
+  msFree(params->interpolation);
+  msFree(params->outputcrs);
+  msFree(params->subsetcrs);
+  while(params->numaxes > 0) {
+    params->numaxes -= 1;
+    msWCSFreeAxisObj20(params->axes[params->numaxes]);
+  }
+  msFree(params->axes);
+  CSLDestroy(params->range_subset);
+  msFree(params);
 }
 
 /************************************************************************/
@@ -365,117 +335,101 @@ void msWCSFreeParamsObj20(wcs20ParamsObjPtr params)
 /************************************************************************/
 
 static int msWCSParseSubset20(wcs20SubsetObjPtr subset, const char *axis,
-        const char *crs, const char *min, const char *max)
+                              const char *crs, const char *min, const char *max)
 {
-    int ts1, ts2;
-    ts1 = ts2 = MS_WCS20_UNDEFINED_VALUE;
+  int ts1, ts2;
+  ts1 = ts2 = MS_WCS20_UNDEFINED_VALUE;
 
-    if (subset == NULL)
-    {
-        return MS_FAILURE;
-    }
+  if (subset == NULL) {
+    return MS_FAILURE;
+  }
 
-    if (axis == NULL || strlen(axis) == 0)
-    {
-        msSetError(MS_WCSERR, "Subset axis is not given.",
-                "msWCSParseSubset20()");
-        return MS_FAILURE;
-    }
+  if (axis == NULL || strlen(axis) == 0) {
+    msSetError(MS_WCSERR, "Subset axis is not given.",
+               "msWCSParseSubset20()");
+    return MS_FAILURE;
+  }
 
-    subset->axis = msStrdup(axis);
-    if (crs != NULL)
-    {
-        subset->crs = msStrdup(crs);
-    }
+  subset->axis = msStrdup(axis);
+  if (crs != NULL) {
+    subset->crs = msStrdup(crs);
+  }
 
-    /* Parse first (probably only) part of interval/point;
-     * check whether its a time value or a scalar value     */
-    ts1 = msWCSParseTimeOrScalar20(&(subset->min), min);
-    if (ts1 == MS_WCS20_ERROR_VALUE)
-    {
-        return MS_FAILURE;
+  /* Parse first (probably only) part of interval/point;
+   * check whether its a time value or a scalar value     */
+  ts1 = msWCSParseTimeOrScalar20(&(subset->min), min);
+  if (ts1 == MS_WCS20_ERROR_VALUE) {
+    return MS_FAILURE;
+  }
+
+  /* check if its an interval */
+  /* if there is a comma, then it is */
+  if (max != NULL && strlen(max) > 0) {
+    subset->operation = MS_WCS20_TRIM;
+
+    /* Parse the second value of the interval */
+    ts2 = msWCSParseTimeOrScalar20(&(subset->max), max);
+    if (ts2 == MS_WCS20_ERROR_VALUE) {
+      return MS_FAILURE;
+    }
+
+    /* if at least one boundary is defined, use that value */
+    if ((ts1 == MS_WCS20_UNDEFINED_VALUE) ^ (ts2
+        == MS_WCS20_UNDEFINED_VALUE)) {
+      if (ts1 == MS_WCS20_UNDEFINED_VALUE) {
+        ts1 = ts2;
+      }
+    }
+    /* if time and scalar values do not fit, throw an error */
+    else if (ts1 != MS_WCS20_UNDEFINED_VALUE && ts2
+             != MS_WCS20_UNDEFINED_VALUE && ts1 != ts2) {
+      msSetError(MS_WCSERR,
+                 "Interval error: minimum is a %s value, maximum is a %s value",
+                 "msWCSParseSubset20()", ts1 ? "time" : "scalar",
+                 ts2 ? "time" : "scalar");
+      return MS_FAILURE;
+    }
+    /* if both min and max are unbounded -> throw an error */
+    if (subset->min.unbounded && subset->max.unbounded) {
+      msSetError(MS_WCSERR, "Invalid values: no bounds could be parsed",
+                 "msWCSParseSubset20()");
+      return MS_FAILURE;
+    }
+  }
+  /* there is no second value, therefore it is a point.
+   * consequently set the operation to slice */
+  else {
+    subset->operation = MS_WCS20_SLICE;
+    if (ts1 == MS_WCS20_UNDEFINED_VALUE) {
+      msSetError(MS_WCSERR, "Invalid point value given",
+                 "msWCSParseSubset20()");
+      return MS_FAILURE;
     }
+  }
 
-    /* check if its an interval */
-    /* if there is a comma, then it is */
-    if (max != NULL && strlen(max) > 0)
-    {
-        subset->operation = MS_WCS20_TRIM;
-
-        /* Parse the second value of the interval */
-        ts2 = msWCSParseTimeOrScalar20(&(subset->max), max);
-        if (ts2 == MS_WCS20_ERROR_VALUE)
-        {
-            return MS_FAILURE;
-        }
+  subset->timeOrScalar = ts1;
 
-        /* if at least one boundary is defined, use that value */
-        if ((ts1 == MS_WCS20_UNDEFINED_VALUE) ^ (ts2
-                == MS_WCS20_UNDEFINED_VALUE))
-        {
-            if (ts1 == MS_WCS20_UNDEFINED_VALUE)
-            {
-                ts1 = ts2;
-            }
-        }
-        /* if time and scalar values do not fit, throw an error */
-        else if (ts1 != MS_WCS20_UNDEFINED_VALUE && ts2
-                != MS_WCS20_UNDEFINED_VALUE && ts1 != ts2)
-        {
-            msSetError(MS_WCSERR,
-                    "Interval error: minimum is a %s value, maximum is a %s value",
-                    "msWCSParseSubset20()", ts1 ? "time" : "scalar",
-                    ts2 ? "time" : "scalar");
-            return MS_FAILURE;
-        }
-        /* if both min and max are unbounded -> throw an error */
-        if (subset->min.unbounded && subset->max.unbounded)
-        {
-            msSetError(MS_WCSERR, "Invalid values: no bounds could be parsed",
-                    "msWCSParseSubset20()");
-            return MS_FAILURE;
-        }
-    }
-    /* there is no second value, therefore it is a point.
-     * consequently set the operation to slice */
-    else
-    {
-        subset->operation = MS_WCS20_SLICE;
-        if (ts1 == MS_WCS20_UNDEFINED_VALUE)
-        {
-            msSetError(MS_WCSERR, "Invalid point value given",
-                    "msWCSParseSubset20()");
-            return MS_FAILURE;
-        }
+  /* check whether the min is smaller than the max */
+  if (subset->operation == MS_WCS20_TRIM) {
+    if(subset->timeOrScalar == MS_WCS20_SCALAR_VALUE && subset->min.scalar == MS_WCS20_UNBOUNDED) {
+      subset->min.scalar = -MS_WCS20_UNBOUNDED;
     }
 
-    subset->timeOrScalar = ts1;
-
-    /* check whether the min is smaller than the max */
-    if (subset->operation == MS_WCS20_TRIM)
-    {
-        if(subset->timeOrScalar == MS_WCS20_SCALAR_VALUE && subset->min.scalar == MS_WCS20_UNBOUNDED)
-        {
-            subset->min.scalar = -MS_WCS20_UNBOUNDED;
-        }
-
-        if (subset->timeOrScalar == MS_WCS20_TIME_VALUE && subset->min.time
-                > subset->max.time)
-        {
-            msSetError(MS_WCSERR,
-                    "Minimum value of subset axis %s is larger than maximum value",
-                    "msWCSParseSubset20()", subset->axis);
-            return MS_FAILURE;
-        }
-        if (subset->timeOrScalar == MS_WCS20_SCALAR_VALUE && subset->min.scalar > subset->max.scalar)
-        {
-            msSetError(MS_WCSERR,
-                    "Minimum value (%f) of subset axis '%s' is larger than maximum value (%f).",
-                    "msWCSParseSubset20()", subset->min.scalar, subset->axis, subset->max.scalar);
-            return MS_FAILURE;
-        }
+    if (subset->timeOrScalar == MS_WCS20_TIME_VALUE && subset->min.time
+        > subset->max.time) {
+      msSetError(MS_WCSERR,
+                 "Minimum value of subset axis %s is larger than maximum value",
+                 "msWCSParseSubset20()", subset->axis);
+      return MS_FAILURE;
     }
-    return MS_SUCCESS;
+    if (subset->timeOrScalar == MS_WCS20_SCALAR_VALUE && subset->min.scalar > subset->max.scalar) {
+      msSetError(MS_WCSERR,
+                 "Minimum value (%f) of subset axis '%s' is larger than maximum value (%f).",
+                 "msWCSParseSubset20()", subset->min.scalar, subset->axis, subset->max.scalar);
+      return MS_FAILURE;
+    }
+  }
+  return MS_SUCCESS;
 }
 
 /************************************************************************/
@@ -488,49 +442,45 @@ static int msWCSParseSubset20(wcs20SubsetObjPtr subset, const char *axis,
 
 static int msWCSParseSubsetKVPString20(wcs20SubsetObjPtr subset, char *string)
 {
-    char *axis, *crs, *min, *max;
-
-    axis = string;
-    crs = NULL;
-    min = NULL;
-    max = NULL;
-
-    /* find first '(' */
-    min = strchr(string, '(');
+  char *axis, *crs, *min, *max;
 
-    /* if min could not be found, the string is invalid */
-    if (min == NULL)
-    {
-        msSetError(MS_WCSERR, "Invalid axis subset string: '%s'",
-                "msWCSParseSubsetKVPString20()", string);
-        return MS_FAILURE;
-    }
-    /* set min to first letter */
-    *min = '\0';
-    ++min;
-
-    /* cut the trailing ')' */
-    if (min[strlen(min) - 1] == ')')
-    {
-        min[strlen(min) - 1] = '\0';
-    }
-    /* look if also a max is defined */
-    max = strchr(min, ',');
-    if (max != NULL)
-    {
-        *max = '\0';
-        ++max;
-    }
+  axis = string;
+  crs = NULL;
+  min = NULL;
+  max = NULL;
 
-    /* look if also a crs is defined */
-    crs = strchr(axis, ',');
-    if (crs != NULL)
-    {
-        *crs = '\0';
-        ++crs;
-    }
+  /* find first '(' */
+  min = strchr(string, '(');
 
-    return msWCSParseSubset20(subset, axis, crs, min, max);
+  /* if min could not be found, the string is invalid */
+  if (min == NULL) {
+    msSetError(MS_WCSERR, "Invalid axis subset string: '%s'",
+               "msWCSParseSubsetKVPString20()", string);
+    return MS_FAILURE;
+  }
+  /* set min to first letter */
+  *min = '\0';
+  ++min;
+
+  /* cut the trailing ')' */
+  if (min[strlen(min) - 1] == ')') {
+    min[strlen(min) - 1] = '\0';
+  }
+  /* look if also a max is defined */
+  max = strchr(min, ',');
+  if (max != NULL) {
+    *max = '\0';
+    ++max;
+  }
+
+  /* look if also a crs is defined */
+  crs = strchr(axis, ',');
+  if (crs != NULL) {
+    *crs = '\0';
+    ++crs;
+  }
+
+  return msWCSParseSubset20(subset, axis, crs, min, max);
 }
 
 /************************************************************************/
@@ -542,42 +492,39 @@ static int msWCSParseSubsetKVPString20(wcs20SubsetObjPtr subset, char *string)
 
 static int msWCSParseSizeString20(char *string, char *outAxis, size_t axisStringLen, int *outSize)
 {
-    char *number = NULL;
-    char *check = NULL;
+  char *number = NULL;
+  char *check = NULL;
 
-    /* find first '(', the character before the number */
-    number = strchr(string, '(');
+  /* find first '(', the character before the number */
+  number = strchr(string, '(');
 
-    if(NULL == number)
-    {
-        msSetError(MS_WCSERR, "Invalid size parameter value.",
-                "msWCSParseSize20()");
-        return MS_FAILURE;
-    }
+  if(NULL == number) {
+    msSetError(MS_WCSERR, "Invalid size parameter value.",
+               "msWCSParseSize20()");
+    return MS_FAILURE;
+  }
 
-    /* cut trailing ')' */
-    check = strchr(string, ')');
-    if(NULL == check)
-    {
-        msSetError(MS_WCSERR, "Invalid size parameter value.",
-                "msWCSParseSize20()");
-        return MS_FAILURE;
-    }
-    *number = '\0';
-    ++number;
-    *check = '\0';
+  /* cut trailing ')' */
+  check = strchr(string, ')');
+  if(NULL == check) {
+    msSetError(MS_WCSERR, "Invalid size parameter value.",
+               "msWCSParseSize20()");
+    return MS_FAILURE;
+  }
+  *number = '\0';
+  ++number;
+  *check = '\0';
 
-    strlcpy(outAxis, string, axisStringLen);
+  strlcpy(outAxis, string, axisStringLen);
 
-    /* parse size value */
-    if(msStringParseInteger(number, outSize) != MS_SUCCESS)
-    {
-        msSetError(MS_WCSERR, "Parameter value '%s' is not a valid integer.",
-                "msWCSParseSize20()", number);
-        return MS_FAILURE;
-    }
+  /* parse size value */
+  if(msStringParseInteger(number, outSize) != MS_SUCCESS) {
+    msSetError(MS_WCSERR, "Parameter value '%s' is not a valid integer.",
+               "msWCSParseSize20()", number);
+    return MS_FAILURE;
+  }
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 /************************************************************************/
@@ -589,45 +536,42 @@ static int msWCSParseSizeString20(char *string, char *outAxis, size_t axisString
 /************************************************************************/
 
 static int msWCSParseResolutionString20(char *string,
-        char *outAxis, size_t axisStringLen, double *outResolution)
+                                        char *outAxis, size_t axisStringLen, double *outResolution)
 {
-    char *number = NULL;
-    char *check = NULL;
+  char *number = NULL;
+  char *check = NULL;
 
-    /* find brackets */
-    number = strchr(string, '(');
+  /* find brackets */
+  number = strchr(string, '(');
 
-    if(NULL == number)
-    {
-        msSetError(MS_WCSERR, "Invalid resolution parameter value.",
-                "msWCSParseSize20()", string);
-        return MS_FAILURE;
-    }
+  if(NULL == number) {
+    msSetError(MS_WCSERR, "Invalid resolution parameter value.",
+               "msWCSParseSize20()", string);
+    return MS_FAILURE;
+  }
 
-    /* cut trailing ')' */
-    check = strchr(string, ')');
-    if(NULL == check)
-    {
-        msSetError(MS_WCSERR, "Invalid size parameter value.",
-                "msWCSParseSize20()");
-        return MS_FAILURE;
-    }
+  /* cut trailing ')' */
+  check = strchr(string, ')');
+  if(NULL == check) {
+    msSetError(MS_WCSERR, "Invalid size parameter value.",
+               "msWCSParseSize20()");
+    return MS_FAILURE;
+  }
 
-    *number = '\0';
-    ++number;
-    *check = '\0';
+  *number = '\0';
+  ++number;
+  *check = '\0';
 
-    strlcpy(outAxis, string, axisStringLen);
+  strlcpy(outAxis, string, axisStringLen);
 
-    if(msStringParseDouble(number, outResolution) != MS_SUCCESS)
-    {
-        *outResolution = MS_WCS20_UNBOUNDED;
-        msSetError(MS_WCSERR, "Invalid resolution parameter value.",
-                "msWCSParseSize20()", string);
-        return MS_FAILURE;
-    }
+  if(msStringParseDouble(number, outResolution) != MS_SUCCESS) {
+    *outResolution = MS_WCS20_UNBOUNDED;
+    msSetError(MS_WCSERR, "Invalid resolution parameter value.",
+               "msWCSParseSize20()", string);
+    return MS_FAILURE;
+  }
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 /************************************************************************/
@@ -638,60 +582,46 @@ static int msWCSParseResolutionString20(char *string,
 /************************************************************************/
 #if defined(USE_LIBXML2)
 static int msWCSParseRequest20_XMLGetCapabilities(
-        xmlNodePtr root, wcs20ParamsObjPtr params)
+  xmlNodePtr root, wcs20ParamsObjPtr params)
 {
-    xmlNodePtr child;
-    char *content = NULL;
-    XML_FOREACH_CHILD(root, child)
-    {
-        XML_LOOP_IGNORE_COMMENT_OR_TEXT(child)
-        else if (EQUAL((char *)child->name, "AcceptVersions"))
-        {
-            xmlNodePtr versionNode = NULL;
-            XML_FOREACH_CHILD(child, versionNode)
-            {
-                //for(child = firstChild->children; child != NULL; child = child->next)
-                XML_LOOP_IGNORE_COMMENT_OR_TEXT(versionNode);
-                XML_ASSERT_NODE_NAME(versionNode, "Version");
-
-                content = (char *)xmlNodeGetContent(versionNode);
-                params->accept_versions = CSLAddString(params->accept_versions, content);
-                xmlFree(content);
-            }
-        }
-        else if(EQUAL((char *)child->name, "Sections"))
-        {
-            xmlNodePtr sectionNode = NULL;
-            XML_FOREACH_CHILD(child, sectionNode)
-            {
-                XML_LOOP_IGNORE_COMMENT_OR_TEXT(sectionNode)
-                XML_ASSERT_NODE_NAME(sectionNode, "Section");
-
-                content = (char *)xmlNodeGetContent(sectionNode);
-                params->sections = CSLAddString(params->sections, content);
-                xmlFree(content);
-            }
-        }
-        else if(EQUAL((char *)child->name, "UpdateSequence"))
-        {
-            params->updatesequence =
-                    (char *)xmlNodeGetContent(child);
-        }
-        else if(EQUAL((char *)child->name, "AcceptFormats"))
-        {
-            /* Maybe not necessary, since only format is xml.   */
-            /* At least ignore it, to not generate an error.    */
-        }
-        else if(EQUAL((char *)child->name, "AcceptLanguages"))
-        {
-            /* ignore */
-        }
-        else
-        {
-            XML_UNKNOWN_NODE_ERROR(child);
-        }
-    }
-    return MS_SUCCESS;
+  xmlNodePtr child;
+  char *content = NULL;
+  XML_FOREACH_CHILD(root, child) {
+    XML_LOOP_IGNORE_COMMENT_OR_TEXT(child)
+    else if (EQUAL((char *)child->name, "AcceptVersions")) {
+      xmlNodePtr versionNode = NULL;
+      XML_FOREACH_CHILD(child, versionNode) {
+        /* for(child = firstChild->children; child != NULL; child = child->next) */
+        XML_LOOP_IGNORE_COMMENT_OR_TEXT(versionNode);
+        XML_ASSERT_NODE_NAME(versionNode, "Version");
+
+        content = (char *)xmlNodeGetContent(versionNode);
+        params->accept_versions = CSLAddString(params->accept_versions, content);
+        xmlFree(content);
+      }
+    } else if(EQUAL((char *)child->name, "Sections")) {
+      xmlNodePtr sectionNode = NULL;
+      XML_FOREACH_CHILD(child, sectionNode) {
+        XML_LOOP_IGNORE_COMMENT_OR_TEXT(sectionNode)
+        XML_ASSERT_NODE_NAME(sectionNode, "Section");
+
+        content = (char *)xmlNodeGetContent(sectionNode);
+        params->sections = CSLAddString(params->sections, content);
+        xmlFree(content);
+      }
+    } else if(EQUAL((char *)child->name, "UpdateSequence")) {
+      params->updatesequence =
+        (char *)xmlNodeGetContent(child);
+    } else if(EQUAL((char *)child->name, "AcceptFormats")) {
+      /* Maybe not necessary, since only format is xml.   */
+      /* At least ignore it, to not generate an error.    */
+    } else if(EQUAL((char *)child->name, "AcceptLanguages")) {
+      /* ignore */
+    } else {
+      XML_UNKNOWN_NODE_ERROR(child);
+    }
+  }
+  return MS_SUCCESS;
 }
 #endif
 
@@ -703,31 +633,29 @@ static int msWCSParseRequest20_XMLGetCapabilities(
 /************************************************************************/
 #if defined(USE_LIBXML2)
 static int msWCSParseRequest20_XMLDescribeCoverage(
-        xmlNodePtr root, wcs20ParamsObjPtr params)
+  xmlNodePtr root, wcs20ParamsObjPtr params)
 {
-    xmlNodePtr child;
-    int numIds = 0;
-    char *id;
-
-    XML_FOREACH_CHILD(root, child)
-    {
-        XML_LOOP_IGNORE_COMMENT_OR_TEXT(child)
-        XML_ASSERT_NODE_NAME(child, "CoverageID");
-
-        /* Node content is the coverage ID */
-        id = (char *)xmlNodeGetContent(child);
-        if (id == NULL || strlen(id) == 0)
-        {
-            msSetError(MS_WCSERR, "CoverageID could not be parsed.",
-                    "msWCSParseRequest20_XMLDescribeCoverage()");
-            return MS_FAILURE;
-        }
-        /* insert coverage ID into the list */
-        ++numIds;
-        params->ids = CSLAddString(params->ids, (char *)id);
-        xmlFree(id);
-    }
-    return MS_SUCCESS;
+  xmlNodePtr child;
+  int numIds = 0;
+  char *id;
+
+  XML_FOREACH_CHILD(root, child) {
+    XML_LOOP_IGNORE_COMMENT_OR_TEXT(child)
+    XML_ASSERT_NODE_NAME(child, "CoverageID");
+
+    /* Node content is the coverage ID */
+    id = (char *)xmlNodeGetContent(child);
+    if (id == NULL || strlen(id) == 0) {
+      msSetError(MS_WCSERR, "CoverageID could not be parsed.",
+                 "msWCSParseRequest20_XMLDescribeCoverage()");
+      return MS_FAILURE;
+    }
+    /* insert coverage ID into the list */
+    ++numIds;
+    params->ids = CSLAddString(params->ids, (char *)id);
+    xmlFree(id);
+  }
+  return MS_SUCCESS;
 }
 #endif
 
@@ -739,235 +667,188 @@ static int msWCSParseRequest20_XMLDescribeCoverage(
 /************************************************************************/
 #if defined(USE_LIBXML2)
 static int msWCSParseRequest20_XMLGetCoverage(
-        xmlNodePtr root, wcs20ParamsObjPtr params)
+  xmlNodePtr root, wcs20ParamsObjPtr params)
 {
-    xmlNodePtr child;
-    int numIds = 0;
-    char *id;
-
-    XML_FOREACH_CHILD(root, child)
-    {
-        XML_LOOP_IGNORE_COMMENT_OR_TEXT(child)
-        else if (EQUAL((char *)child->name, "CoverageID"))
-        {
-            /* Node content is the coverage ID */
-            id = (char *)xmlNodeGetContent(child);
-            if (id == NULL || strlen(id) == 0)
-            {
-                msSetError(MS_WCSERR, "CoverageID could not be parsed.",
-                        "msWCSParseRequest20_XMLGetCoverage()");
-                return MS_FAILURE;
-            }
-
-            /* insert coverage ID into the list */
-            ++numIds;
-            params->ids = CSLAddString(params->ids, (char *)id);
-            xmlFree(id);
-        }
-        else if (EQUAL((char *) child->name, "Format"))
-        {
-            params->format = (char *)xmlNodeGetContent(child);
-        }
-        else if (EQUAL((char *) child->name, "Mediatype"))
-        {
-            char *content = (char *)xmlNodeGetContent(child);
-            if(content != NULL && EQUAL(content, "multipart/mixed"))
-            {
-                params->multipart = MS_TRUE;
-            }
-            xmlFree(content);
-        }
-        else if (EQUAL((char *) child->name, "DimensionTrim"))
-        {
-            wcs20AxisObjPtr axis = NULL;
-            wcs20SubsetObjPtr subset = NULL;
-            xmlNodePtr node = NULL;
-            char *axisName = NULL, *min = NULL, *max = NULL, *crs = NULL;
-
-            /* get strings for axis, min and max */
-            XML_FOREACH_CHILD(child, node)
-            {
-                XML_LOOP_IGNORE_COMMENT_OR_TEXT(node)
-                else if (EQUAL((char *)node->name, "Dimension"))
-                {
-                    if (axisName != NULL)
-                    {
-                        msSetError(MS_WCSERR,
-                                "Parameter 'Dimension' is already set.",
-                                "msWCSParseRequest20_XMLGetCoverage()");
-                        return MS_FAILURE;
-                    }
-                    axisName = (char *) xmlNodeGetContent(node);
-                    crs = (char *) xmlGetProp(node, BAD_CAST "crs");
-                }
-                else if (EQUAL((char *)node->name, "trimLow"))
-                {
-                    min = (char *) xmlNodeGetContent(node);
-                }
-                else if (EQUAL((char *)node->name, "trimHigh"))
-                {
-                    max = (char *) xmlNodeGetContent(node);
-                }
-                else
-                {
-                    msFree(axisName);
-                    msFree(min);
-                    msFree(max);
-                    msFree(crs);
-                    XML_UNKNOWN_NODE_ERROR(node);
-                }
-            }
-            if(NULL == (subset = msWCSCreateSubsetObj20()))
-            {
-                msFree(axisName);
-                msFree(min);
-                msFree(max);
-                msFree(crs);
-                return MS_FAILURE;
-            }
-
-            /* min and max have to have a value */
-            if(min == NULL )
-            {
-                min = msStrdup("*");
-            }
-            if(max == NULL)
-            {
-                max = msStrdup("*");
-            }
-            if (msWCSParseSubset20(subset, axisName, crs, min, max)
-                    == MS_FAILURE)
-            {
-                msWCSFreeSubsetObj20(subset);
-                return MS_FAILURE;
-            }
-
-            if(NULL == (axis = msWCSFindAxis20(params, subset->axis)))
-            {
-                if(NULL == (axis = msWCSCreateAxisObj20()))
-                {
-                    msFree(axisName);
-                    msFree(min);
-                    msFree(max);
-                    msFree(crs);
-                    return MS_FAILURE;
-                }
-                axis->name = msStrdup(subset->axis);
-                msWCSInsertAxisObj20(params, axis);
-            }
-
-            axis->subset = subset;
-
-            /* cleanup */
-            msFree(axisName);
-            msFree(min);
-            msFree(max);
-            msFree(crs);
-        }
-        else if(EQUAL((char *) child->name, "DimensionSlice"))
-        {
-            msSetError(MS_WCSERR, "Operation '%s' is not supported by MapServer.",
-                    "msWCSParseRequest20_XMLGetCoverage()", (char *)child->name);
+  xmlNodePtr child;
+  int numIds = 0;
+  char *id;
+
+  XML_FOREACH_CHILD(root, child) {
+    XML_LOOP_IGNORE_COMMENT_OR_TEXT(child)
+    else if (EQUAL((char *)child->name, "CoverageID")) {
+      /* Node content is the coverage ID */
+      id = (char *)xmlNodeGetContent(child);
+      if (id == NULL || strlen(id) == 0) {
+        msSetError(MS_WCSERR, "CoverageID could not be parsed.",
+                   "msWCSParseRequest20_XMLGetCoverage()");
+        return MS_FAILURE;
+      }
+
+      /* insert coverage ID into the list */
+      ++numIds;
+      params->ids = CSLAddString(params->ids, (char *)id);
+      xmlFree(id);
+    } else if (EQUAL((char *) child->name, "Format")) {
+      params->format = (char *)xmlNodeGetContent(child);
+    } else if (EQUAL((char *) child->name, "Mediatype")) {
+      char *content = (char *)xmlNodeGetContent(child);
+      if(content != NULL && (EQUAL(content, "multipart/mixed")
+                          || EQUAL(content, "multipart/related"))) {
+        params->multipart = MS_TRUE;
+      }
+      xmlFree(content);
+    } else if (EQUAL((char *) child->name, "DimensionTrim")) {
+      wcs20AxisObjPtr axis = NULL;
+      wcs20SubsetObjPtr subset = NULL;
+      xmlNodePtr node = NULL;
+      char *axisName = NULL, *min = NULL, *max = NULL, *crs = NULL;
+
+      /* get strings for axis, min and max */
+      XML_FOREACH_CHILD(child, node) {
+        XML_LOOP_IGNORE_COMMENT_OR_TEXT(node)
+        else if (EQUAL((char *)node->name, "Dimension")) {
+          if (axisName != NULL) {
+            msSetError(MS_WCSERR,
+                       "Parameter 'Dimension' is already set.",
+                       "msWCSParseRequest20_XMLGetCoverage()");
             return MS_FAILURE;
+          }
+          axisName = (char *) xmlNodeGetContent(node);
+          crs = (char *) xmlGetProp(node, BAD_CAST "crs");
+        } else if (EQUAL((char *)node->name, "trimLow")) {
+          min = (char *) xmlNodeGetContent(node);
+        } else if (EQUAL((char *)node->name, "trimHigh")) {
+          max = (char *) xmlNodeGetContent(node);
+        } else {
+          msFree(axisName);
+          msFree(min);
+          msFree(max);
+          msFree(crs);
+          XML_UNKNOWN_NODE_ERROR(node);
+        }
+      }
+      if(NULL == (subset = msWCSCreateSubsetObj20())) {
+        msFree(axisName);
+        msFree(min);
+        msFree(max);
+        msFree(crs);
+        return MS_FAILURE;
+      }
+
+      /* min and max have to have a value */
+      if(min == NULL ) {
+        min = msStrdup("*");
+      }
+      if(max == NULL) {
+        max = msStrdup("*");
+      }
+      if (msWCSParseSubset20(subset, axisName, crs, min, max)
+          == MS_FAILURE) {
+        msWCSFreeSubsetObj20(subset);
+        return MS_FAILURE;
+      }
+
+      if(NULL == (axis = msWCSFindAxis20(params, subset->axis))) {
+        if(NULL == (axis = msWCSCreateAxisObj20())) {
+          msFree(axisName);
+          msFree(min);
+          msFree(max);
+          msFree(crs);
+          return MS_FAILURE;
+        }
+        axis->name = msStrdup(subset->axis);
+        msWCSInsertAxisObj20(params, axis);
+      }
+
+      axis->subset = subset;
+
+      /* cleanup */
+      msFree(axisName);
+      msFree(min);
+      msFree(max);
+      msFree(crs);
+    } else if(EQUAL((char *) child->name, "DimensionSlice")) {
+      msSetError(MS_WCSERR, "Operation '%s' is not supported by MapServer.",
+                 "msWCSParseRequest20_XMLGetCoverage()", (char *)child->name);
+      return MS_FAILURE;
+    } else if(EQUAL((char *) child->name, "Size")) {
+      wcs20AxisObjPtr axis;
+      char *axisName;
+      char *content;
+
+      if(NULL == (axisName = (char *) xmlGetProp(child, BAD_CAST "dimension")) ) {
+        msSetError(MS_WCSERR, "Attribute 'dimension' is missing in element 'Size'.",
+                   "msWCSParseRequest20_XMLGetCoverage()");
+        return MS_FAILURE;
+      }
+
+      if(NULL == (axis = msWCSFindAxis20(params, axisName))) {
+        if(NULL == (axis = msWCSCreateAxisObj20())) {
+          return MS_FAILURE;
         }
-        else if(EQUAL((char *) child->name, "Size"))
-        {
-            wcs20AxisObjPtr axis;
-            char *axisName;
-            char *content;
-
-            if(NULL == (axisName = (char *) xmlGetProp(child, BAD_CAST "dimension")) )
-            {
-                msSetError(MS_WCSERR, "Attribute 'dimension' is missing in element 'Size'.",
-                        "msWCSParseRequest20_XMLGetCoverage()");
-                return MS_FAILURE;
-            }
+        axis->name = msStrdup(axisName);
+        msWCSInsertAxisObj20(params, axis);
+      }
 
-            if(NULL == (axis = msWCSFindAxis20(params, axisName)))
-            {
-                if(NULL == (axis = msWCSCreateAxisObj20()))
-                {
-                    return MS_FAILURE;
-                }
-                axis->name = msStrdup(axisName);
-                msWCSInsertAxisObj20(params, axis);
-            }
+      content = (char *)xmlNodeGetContent(child);
+      if(msStringParseInteger(content, &(axis->size)) != MS_SUCCESS) {
+        msSetError(MS_WCSERR, "Value of element 'Size' could not "
+                   "be parsed to a valid integer.",
+                   "msWCSParseRequest20_XMLGetCoverage()");
+        return MS_FAILURE;
+      }
+      xmlFree(content);
+    } else if(EQUAL((char *) child->name, "Resolution")) {
+      wcs20AxisObjPtr axis;
+      char *axisName;
+      char *content;
+
+      if(NULL == (axisName = (char *) xmlGetProp(child, BAD_CAST "dimension"))) {
+        msSetError(MS_WCSERR, "Attribute 'dimension' is missing "
+                   "in element 'Resolution'.",
+                   "msWCSParseRequest20_XMLGetCoverage()", (char *)child->name);
+        return MS_FAILURE;
+      }
 
-            content = (char *)xmlNodeGetContent(child);
-            if(msStringParseInteger(content, &(axis->size)) != MS_SUCCESS)
-            {
-                msSetError(MS_WCSERR, "Value of element 'Size' could not "
-                        "be parsed to a valid integer.",
-                        "msWCSParseRequest20_XMLGetCoverage()");
-                return MS_FAILURE;
-            }
-            xmlFree(content);
+      if(NULL == (axis = msWCSFindAxis20(params, axisName))) {
+        if(NULL == (axis = msWCSCreateAxisObj20())) {
+          return MS_FAILURE;
         }
-        else if(EQUAL((char *) child->name, "Resolution"))
-        {
-            wcs20AxisObjPtr axis;
-            char *axisName;
-            char *content;
-
-            if(NULL == (axisName = (char *) xmlGetProp(child, BAD_CAST "dimension")))
-            {
-                msSetError(MS_WCSERR, "Attribute 'dimension' is missing "
-                        "in element 'Resolution'.",
-                        "msWCSParseRequest20_XMLGetCoverage()", (char *)child->name);
-                return MS_FAILURE;
-            }
+        axis->name = msStrdup(axisName);
+        msWCSInsertAxisObj20(params, axis);
+      }
 
-            if(NULL == (axis = msWCSFindAxis20(params, axisName)))
-            {
-                if(NULL == (axis = msWCSCreateAxisObj20()))
-                {
-                    return MS_FAILURE;
-                }
-                axis->name = msStrdup(axisName);
-                msWCSInsertAxisObj20(params, axis);
-            }
-
-            axis->resolutionUOM = (char *) xmlGetProp(child, BAD_CAST "uom");
+      axis->resolutionUOM = (char *) xmlGetProp(child, BAD_CAST "uom");
 
-            content = (char *)xmlNodeGetContent(child);
-            if(msStringParseDouble(content, &(axis->resolution)) != MS_SUCCESS)
-            {
-                msSetError(MS_WCSERR, "Value of element 'Resolution' could not "
-                        "be parsed to a valid value.",
-                        "msWCSParseRequest20_XMLGetCoverage()");
-                xmlFree(content);
-                return MS_FAILURE;
-            }
-            xmlFree(content);
-        }
-        else if(EQUAL((char *) child->name, "Interpolation"))
-        {
-            params->interpolation = (char *) xmlNodeGetContent(child);
-        }
-        else if(EQUAL((char *) child->name, "OutputCRS"))
-        {
-            params->outputcrs = (char *) xmlNodeGetContent(child);
-        }
-        else if(EQUAL((char *) child->name, "rangeSubset"))
-        {
-            xmlNodePtr bandNode = NULL;
-            XML_FOREACH_CHILD(child, bandNode)
-            {
-                char *content = NULL;
-                XML_ASSERT_NODE_NAME(bandNode, "band");
-
-                content = (char *)xmlNodeGetContent(bandNode);
-                params->range_subset =
-                        CSLAddString(params->range_subset, content);
-                xmlFree(content);
-            }
-        }
-        else
-        {
-            XML_UNKNOWN_NODE_ERROR(child);
-        }
-    }
-    return MS_SUCCESS;
+      content = (char *)xmlNodeGetContent(child);
+      if(msStringParseDouble(content, &(axis->resolution)) != MS_SUCCESS) {
+        msSetError(MS_WCSERR, "Value of element 'Resolution' could not "
+                   "be parsed to a valid value.",
+                   "msWCSParseRequest20_XMLGetCoverage()");
+        xmlFree(content);
+        return MS_FAILURE;
+      }
+      xmlFree(content);
+    } else if(EQUAL((char *) child->name, "Interpolation")) {
+      params->interpolation = (char *) xmlNodeGetContent(child);
+    } else if(EQUAL((char *) child->name, "OutputCRS")) {
+      params->outputcrs = (char *) xmlNodeGetContent(child);
+    } else if(EQUAL((char *) child->name, "rangeSubset")) {
+      xmlNodePtr bandNode = NULL;
+      XML_FOREACH_CHILD(child, bandNode) {
+        char *content = NULL;
+        XML_ASSERT_NODE_NAME(bandNode, "band");
+
+        content = (char *)xmlNodeGetContent(bandNode);
+        params->range_subset =
+          CSLAddString(params->range_subset, content);
+        xmlFree(content);
+      }
+    } else {
+      XML_UNKNOWN_NODE_ERROR(child);
+    }
+  }
+  return MS_SUCCESS;
 }
 #endif
 
@@ -980,378 +861,219 @@ static int msWCSParseRequest20_XMLGetCoverage(
 /*      before the parameters can be extracted.                         */
 /************************************************************************/
 
-int msWCSParseRequest20(cgiRequestObj *request, wcs20ParamsObjPtr params)
+int msWCSParseRequest20(mapObj *map,
+                        cgiRequestObj *request,
+                        owsRequestObj *ows_request,
+                        wcs20ParamsObjPtr params)
 {
-    int i;
-    if (params == NULL || request == NULL)
-    {
-        msSetError(MS_WCSERR, "Internal error.", "msWCSParseRequest20()");
-        return MS_FAILURE;
-    }
+  int i;
+  if (params == NULL || request == NULL || ows_request == NULL) {
+    msSetError(MS_WCSERR, "Internal error.", "msWCSParseRequest20()");
+    return MS_FAILURE;
+  }
 
-    /* Parse the POST request */
-    if (request->type == MS_POST_REQUEST && request->postrequest &&
-            strlen(request->postrequest))
-    {
+  /* Copy arbitrary service, version and request. */
+  params->service = msStrdup(ows_request->service);
+  if(ows_request->version != NULL) {
+    params->version = msStrdup(ows_request->version);
+  }
+  params->request = msStrdup(ows_request->request);
+
+
+  /* Parse the POST request */
+  if (request->type == MS_POST_REQUEST) {
 #if defined(USE_LIBXML2)
-        xmlDocPtr doc = NULL;
-        xmlNodePtr root = NULL;
-        int ret = MS_SUCCESS;
-
-        msDebug("msWCSParseRequest20(): Parsing request %s\n",
-                request->postrequest);
-
-        if (params->version    != NULL
-            || params->request != NULL
-            || params->service != NULL
-            || params->ids     != NULL
-            || params->axes    != NULL)
-        {
-            msSetError(MS_WCSERR, "Params object has already been parsed",
-                    "msWCSParseRequest20()");
-            return MS_FAILURE;
-        }
+    xmlDocPtr doc = ows_request->document;
+    xmlNodePtr root = NULL;
+    const char *validate;
+    int ret = MS_SUCCESS;
+
+    /* parse to DOM-Structure and get root element */
+    if(doc == NULL) {
+      xmlErrorPtr error = xmlGetLastError();
+      msSetError(MS_WCSERR, "XML parsing error: %s",
+                 "msWCSParseRequest20()", error->message);
+      return MS_FAILURE;
+    }
+
+    root = xmlDocGetRootElement(doc);
+
+    validate = msOWSLookupMetadata(&(map->web.metadata), "CO", "validate_xml");
+    if (validate != NULL && EQUAL(validate, "TRUE")) {
+      char *schema_dir = msStrdup(msOWSLookupMetadata(&(map->web.metadata),
+                                  "CO", "schemas_dir"));
+      if (schema_dir != NULL
+          && (params->version == NULL ||
+              EQUALN(params->version, "2.0", 3))) {
+        schema_dir = msStringConcatenate(schema_dir,
+                                         "wcs/2.0.0/wcsAll.xsd");
+        if (msOWSSchemaValidation(schema_dir, request->postrequest) != 0) {
+          msSetError(MS_WCSERR, "Invalid POST request. "
+                     "XML is not valid",
+                     "msWCSParseRequest20()");
+          return MS_FAILURE;
+        }
+      }
+      msFree(schema_dir);
+    }
+
+    if(EQUAL(params->request, "GetCapabilities")) {
+      ret = msWCSParseRequest20_XMLGetCapabilities(root, params);
+    } else if(params->version != NULL && EQUALN(params->version, "2.0", 3)) {
+      if(EQUAL(params->request, "DescribeCoverage")) {
+        ret = msWCSParseRequest20_XMLDescribeCoverage(root, params);
+      } else if(EQUAL(params->request, "GetCoverage")) {
+        ret = msWCSParseRequest20_XMLGetCoverage(root, params);
+      }
+    }
+    return ret;
 
-        /* parse to DOM-Structure and get root element */
-        doc = xmlParseMemory(request->postrequest, strlen(request->postrequest));
-        if(doc == NULL)
-        {
-            xmlErrorPtr error = xmlGetLastError();
-            msSetError(MS_WCSERR, "XML parsing error: %s",
-                    "msWCSParseRequest20()", error->message);
-            return MS_FAILURE;
+#else /* defined(USE_LIBXML2) */
+    /* TODO: maybe with CPLXML? */
+    return MS_DONE;
+#endif /* defined(USE_LIBXML2) */
+  }
+
+  /* Parse the KVP GET request */
+  for (i = 0; i < request->NumParams; ++i) {
+    char *key = NULL, *value = NULL;
+    char **tokens;
+    int num, j;
+    key = request->ParamNames[i];
+    value = request->ParamValues[i];
+
+    if (EQUAL(key, "VERSION")) {
+      continue;
+    } else if (EQUAL(key, "REQUEST")) {
+      continue;
+    } else if (EQUAL(key, "SERVICE")) {
+      continue;
+    } else if (EQUAL(key, "ACCEPTVERSIONS")) {
+      tokens = msStringSplit(value, ',', &num);
+      for(j = 0; j < num; ++j) {
+        params->accept_versions =
+          CSLAddString(params->accept_versions, tokens[j]);
+      }
+      msFreeCharArray(tokens, num);
+    } else if (EQUAL(key, "SECTIONS")) {
+      tokens = msStringSplit(value, ',', &num);
+      for(j = 0; j < num; ++j) {
+        params->sections =
+          CSLAddString(params->sections, tokens[j]);
+      }
+      msFreeCharArray(tokens, num);
+    } else if (EQUAL(key, "UPDATESEQUENCE")) {
+      params->updatesequence = msStrdup(value);
+    } else if (EQUAL(key, "ACCEPTFORMATS")) {
+      /* ignore */
+    } else if (EQUAL(key, "ACCEPTLANGUAGES")) {
+      /* ignore */
+    } else if (EQUAL(key, "COVERAGEID")) {
+      if (params->ids != NULL) {
+        msSetError(MS_WCSERR, "Parameter 'CoverageID' is already set. "
+                   "For multiple IDs use a comma separated list.",
+                   "msWCSParseRequest20()");
+        return MS_FAILURE;
+      }
+      params->ids = CSLTokenizeString2(value, ",",0);
+    } else if (EQUAL(key, "FORMAT")) {
+      params->format = msStrdup(value);
+    } else if (EQUAL(key, "MEDIATYPE")) {
+      if(EQUAL(value, "multipart/mixed") || EQUAL(value, "multipart/related")) {
+        params->multipart = MS_TRUE;
+      }
+    } else if (EQUAL(key, "INTERPOLATION")) {
+      params->interpolation = msStrdup(value);
+    } else if (EQUAL(key, "OUTPUTCRS")) {
+      params->outputcrs = msStrdup(value);
+    } else if (EQUALN(key, "SIZE", 4)) {
+      wcs20AxisObjPtr axis = NULL;
+      char axisName[500];
+      int size = 0;
+
+      if(msWCSParseSizeString20(value, axisName, sizeof(axisName), &size) == MS_FAILURE) {
+        return MS_FAILURE;
+      }
+
+      if(NULL == (axis = msWCSFindAxis20(params, axisName))) {
+        if(NULL == (axis = msWCSCreateAxisObj20())) {
+          return MS_FAILURE;
         }
-        root = xmlDocGetRootElement(doc);
+        axis->name = msStrdup(axisName);
+        msWCSInsertAxisObj20(params, axis);
+      }
 
-        /* Get service, version and request from root */
-        params->request = msStrdup((char *) root->name);
-        params->service = (char *) xmlGetProp(root, BAD_CAST "service");
-        params->version = (char *) xmlGetProp(root, BAD_CAST "version");
+      /* check if the size of the axis is already set */
+      if(axis->size != 0) {
+        msSetError(MS_WCSERR, "The size of the axis is already set.",
+                   "msWCSParseRequest20()");
+        return MS_FAILURE;
+      }
+      axis->size = size;
+    } else if (EQUALN(key, "RESOLUTION", 10)) {
+      wcs20AxisObjPtr axis = NULL;
+      char axisName[500];
+      double resolution = 0;
+
+      if(msWCSParseResolutionString20(value, axisName, sizeof(axisName), &resolution) == MS_FAILURE) {
+        return MS_FAILURE;
+      }
 
-        if(params->service != NULL && EQUAL(params->service, "WCS"))
-        {
-            if(EQUAL(params->request, "GetCapabilities"))
-            {
-                ret = msWCSParseRequest20_XMLGetCapabilities(root, params);
-            }
-            else if(params->version != NULL && EQUALN(params->version, "2.0", 3))
-            {
-                if(EQUAL(params->request, "DescribeCoverage"))
-                {
-                    ret = msWCSParseRequest20_XMLDescribeCoverage(root, params);
-                }
-                else if(EQUAL(params->request, "GetCoverage"))
-                {
-                    ret = msWCSParseRequest20_XMLGetCoverage(root, params);
-                }
-            }
-        }
-        else
-        {
-            ret = MS_DONE;
+      /* check if axis object already exists, otherwise create a new one */
+      if(NULL == (axis = msWCSFindAxis20(params, axisName))) {
+        if(NULL == (axis = msWCSCreateAxisObj20())) {
+          return MS_FAILURE;
         }
+        axis->name = msStrdup(axisName);
+        msWCSInsertAxisObj20(params, axis);
+      }
 
-        xmlFreeDoc(doc);
-        xmlCleanupParser();
-
-        return ret;
+      /* check if the resolution of the axis is already set */
+      if(axis->resolution != MS_WCS20_UNBOUNDED) {
+        msSetError(MS_WCSERR, "The resolution of the axis is already set.",
+                   "msWCSParseRequest20()");
+        return MS_FAILURE;
+      }
+      axis->resolution = resolution;
+    } else if (EQUALN(key, "SUBSET", 6)) {
+      wcs20AxisObjPtr axis = NULL;
+      wcs20SubsetObjPtr subset = msWCSCreateSubsetObj20();
+      if(NULL == subset) {
+        return MS_FAILURE;
+      }
+      if (msWCSParseSubsetKVPString20(subset, value) == MS_FAILURE) {
+        msWCSFreeSubsetObj20(subset);
+        return MS_FAILURE;
+      }
 
-#else /* defined(USE_LIBXML2) */
-        /* 'Parse' the xml line by line, only find out Version and Service */
-        char **lines = NULL;
-        int numLines = 0, i;
-        lines = msStringSplit(request->postrequest, '\n', &numLines);
-        for(i = 0; i < numLines; ++i)
-        {
-            char **tokens = NULL;
-            int numTokens = 0, j = 0;
-
-            if(EQUALN(lines[i], "<?xml", 5))
-                continue;
-
-            tokens = msStringSplit(lines[i], ' ', &numTokens);
-            for(j = 0; j < numTokens; ++j)
-            {
-                if(EQUALN(tokens[j], "SERVICE", strlen("SERVICE")))
-                {
-                    int k;
-                    char *value = strchr(tokens[j], '=');
-                    if(value == NULL)
-                        continue;
-                    ++value;
-                    if(value[0] == '"' || value[0] == '\'')
-                        ++value;
-
-                    for(k = strlen(value) - 1; k > 0; --k)
-                    {
-                        if(value[k] == '\'' || value[k] == '"')
-                        {
-                            value[k] = '\0';
-                            break;
-                        }
-                    }
-
-                    params->service = msStrdup(value);
-                }
-                else if(EQUALN(tokens[j], "VERSION", strlen("VERSION")))
-                {
-                    int k;
-                    char *value = strchr(tokens[j], '=');
-                    if(value == NULL)
-                        continue;
-                    ++value;
-                    if(value[0] == '"' || value[0] == '\'')
-                        ++value;
-
-                    for(k = strlen(value) - 1; k > 0; --k)
-                    {
-                        if(value[k] == '\'' || value[k] == '"')
-                        {
-                            value[k] = '\0';
-                            break;
-                        }
-                    }
-
-                    params->version = msStrdup(value);
-                }
-            }
-            msFreeCharArray(tokens, numTokens);
+      if(NULL == (axis = msWCSFindAxis20(params, subset->axis))) {
+        if(NULL == (axis = msWCSCreateAxisObj20())) {
+          return MS_FAILURE;
         }
-        msFreeCharArray(lines, numLines);
-        return MS_SUCCESS;
-#endif /* defined(USE_LIBXML2) */
-    }
+        axis->name = msStrdup(subset->axis);
+        msWCSInsertAxisObj20(params, axis);
+      }
 
-    /* Parse the KVP GET request */
-    for (i = 0; i < request->NumParams; ++i)
-    {
-        char *key = NULL, *value = NULL;
-        char **tokens;
-        int num, j;
-        key = request->ParamNames[i];
-        value = request->ParamValues[i];
-
-        if (EQUAL(key, "VERSION"))
-        {
-            if (params->version)
-            {
-                msSetError(MS_WCSERR, "Parameter 'Version' is already set.",
-                        "msWCSParseRequest20()");
-                return MS_FAILURE;
-            }
-            params->version = msStrdup(value);
-        }
-        else if (EQUAL(key, "REQUEST"))
-        {
-            if (params->request)
-            {
-                msSetError(MS_WCSERR, "Parameter 'Request' is already set.",
-                        "msWCSParseRequest20()");
-                return MS_FAILURE;
-            }
-            params->request = msStrdup(value);
-        }
-        else if (EQUAL(key, "SERVICE"))
-        {
-            if (params->service)
-            {
-                msSetError(MS_WCSERR, "Parameter 'Service' is already set.",
-                        "msWCSParseRequest20()");
-                return MS_FAILURE;
-            }
-            params->service = msStrdup(value);
-        }
-        else if (EQUAL(key, "ACCEPTVERSIONS"))
-        {
-            tokens = msStringSplit(value, ',', &num);
-            for(j = 0; j < num; ++j)
-            {
-                params->accept_versions =
-                        CSLAddString(params->accept_versions, tokens[j]);
-            }
-            msFreeCharArray(tokens, num);
-        }
-        else if (EQUAL(key, "SECTIONS"))
-        {
-            tokens = msStringSplit(value, ',', &num);
-            for(j = 0; j < num; ++j)
-            {
-                params->sections =
-                        CSLAddString(params->sections, tokens[j]);
-            }
-            msFreeCharArray(tokens, num);
-        }
-        else if (EQUAL(key, "UPDATESEQUENCE"))
-        {
-            params->updatesequence = msStrdup(value);
-        }
-        else if (EQUAL(key, "ACCEPTFORMATS"))
-        {
-            /* ignore */
-        }
-        else if (EQUAL(key, "ACCEPTLANGUAGES"))
-        {
-            /* ignore */
-        }
-        else if (EQUAL(key, "COVERAGEID"))
-        {
-            if (params->ids != NULL)
-            {
-                msSetError(MS_WCSERR, "Parameter 'CoverageID' is already set. "
-                        "For multiple IDs use a comma separated list.",
-                        "msWCSParseRequest20()");
-                return MS_FAILURE;
-            }
-            tokens = msStringSplit(value, ',', &num);
-            params->ids = (char **) VSICalloc(num + 1, sizeof(char *));
-            if (params->ids == NULL)
-            {
-                fprintf(stderr, "VSICalloc(): Out of memory allocating %ld bytes.\n",
-                        (long)((num + 1)*sizeof(char *)));
-                exit(1);
-            }
-            for (j = 0; j < num; ++j)
-            {
-                params->ids[j] = VSIStrdup(tokens[j]);
-                if (params->ids[j] == NULL)
-                {
-                    fprintf(stderr, "VSIStrdup(): Out of memory allocating %ld bytes.\n",
-                        (long)(strlen(tokens[j])));
-                    exit(1);
-                }
-            }
-            msFreeCharArray(tokens, num);
-        }
-        else if (EQUAL(key, "FORMAT"))
-        {
-            params->format = msStrdup(value);
-        }
-        else if (EQUAL(key, "MEDIATYPE"))
-        {
-            if(EQUAL(value, "multipart/mixed"))
-            {
-                params->multipart = MS_TRUE;
-            }
-        }
-        else if (EQUAL(key, "INTERPOLATION"))
-        {
-            params->interpolation = msStrdup(value);
-        }
-        else if (EQUAL(key, "OUTPUTCRS"))
-        {
-            params->outputcrs = msStrdup(value);
-        }
-        else if (EQUALN(key, "SIZE", 4))
-        {
-            wcs20AxisObjPtr axis = NULL;
-            char axisName[500];
-            int size = 0;
-
-            if(msWCSParseSizeString20(value, axisName, sizeof(axisName), &size) == MS_FAILURE)
-            {
-                return MS_FAILURE;
-            }
-
-            if(NULL == (axis = msWCSFindAxis20(params, axisName)))
-            {
-                if(NULL == (axis = msWCSCreateAxisObj20()))
-                {
-                    return MS_FAILURE;
-                }
-                axis->name = msStrdup(axisName);
-                msWCSInsertAxisObj20(params, axis);
-            }
-
-            /* check if the size of the axis is already set */
-            if(axis->size != 0)
-            {
-                msSetError(MS_WCSERR, "The size of the axis is already set.",
-                        "msWCSParseRequest20()");
-                return MS_FAILURE;
-            }
-            axis->size = size;
-        }
-        else if (EQUALN(key, "RESOLUTION", 10))
-        {
-            wcs20AxisObjPtr axis = NULL;
-            char axisName[500];
-            double resolution = 0;
-
-            if(msWCSParseResolutionString20(value, axisName, sizeof(axisName), &resolution) == MS_FAILURE)
-            {
-                return MS_FAILURE;
-            }
-
-            /* check if axis object already exists, otherwise create a new one */
-            if(NULL == (axis = msWCSFindAxis20(params, axisName)))
-            {
-                if(NULL == (axis = msWCSCreateAxisObj20()))
-                {
-                    return MS_FAILURE;
-                }
-                axis->name = msStrdup(axisName);
-                msWCSInsertAxisObj20(params, axis);
-            }
-
-            /* check if the resolution of the axis is already set */
-            if(axis->resolution != MS_WCS20_UNBOUNDED)
-            {
-                msSetError(MS_WCSERR, "The resolution of the axis is already set.",
-                        "msWCSParseRequest20()");
-                return MS_FAILURE;
-            }
-            axis->resolution = resolution;
-        }
-        else if (EQUALN(key, "SUBSET", 6))
-        {
-            wcs20AxisObjPtr axis = NULL;
-            wcs20SubsetObjPtr subset = msWCSCreateSubsetObj20();
-            if(NULL == subset)
-            {
-                return MS_FAILURE;
-            }
-            if (msWCSParseSubsetKVPString20(subset, value) == MS_FAILURE)
-            {
-                msWCSFreeSubsetObj20(subset);
-                return MS_FAILURE;
-            }
-
-            if(NULL == (axis = msWCSFindAxis20(params, subset->axis)))
-            {
-                if(NULL == (axis = msWCSCreateAxisObj20()))
-                {
-                    return MS_FAILURE;
-                }
-                axis->name = msStrdup(subset->axis);
-                msWCSInsertAxisObj20(params, axis);
-            }
-
-            if(NULL != axis->subset)
-            {
-                msSetError(MS_WCSERR, "The axis '%s' is already subsetted.",
-                        "msWCSParseRequest20()", axis->name);
-                msWCSFreeSubsetObj20(subset);
-                return MS_FAILURE;
-            }
-            axis->subset = subset;
-        }
-        else if(EQUAL(key, "RANGESUBSET"))
-        {
-            tokens = msStringSplit(value, ',', &num);
-            for(j = 0; j < num; ++j)
-            {
-                params->range_subset =
-                        CSLAddString(params->range_subset, tokens[j]);
-            }
-            msFreeCharArray(tokens, num);
-        }
-        /* Ignore all other parameters here */
-    }
-
-
-
-    return MS_SUCCESS;
-}
+      if(NULL != axis->subset) {
+        msSetError(MS_WCSERR, "The axis '%s' is already subsetted.",
+                   "msWCSParseRequest20()", axis->name);
+        msWCSFreeSubsetObj20(subset);
+        return MS_FAILURE;
+      }
+      axis->subset = subset;
+    } else if(EQUAL(key, "RANGESUBSET")) {
+      tokens = msStringSplit(value, ',', &num);
+      for(j = 0; j < num; ++j) {
+        params->range_subset =
+          CSLAddString(params->range_subset, tokens[j]);
+      }
+      msFreeCharArray(tokens, num);
+    }
+    /* Ignore all other parameters here */
+  }
+
+  return MS_SUCCESS;
+}
 
 #if defined(USE_LIBXML2)
 
@@ -1364,81 +1086,70 @@ int msWCSParseRequest20(cgiRequestObj *request, wcs20ParamsObjPtr params)
 /*      axis is found for a given axis, an error is returned.           */
 /************************************************************************/
 static int msWCSValidateAndFindAxes20(
-        wcs20ParamsObjPtr params,
-        char*** validAxisNames,
-        int numAxis,
-        wcs20AxisObjPtr outAxes[])
+  wcs20ParamsObjPtr params,
+  char*** validAxisNames,
+  int numAxis,
+  wcs20AxisObjPtr outAxes[])
 {
-    int iParamAxis, iAcceptedAxis, iName, i;
+  int iParamAxis, iAcceptedAxis, iName, i;
 
-    for(i = 0; i < numAxis; ++i)
-    {
-        outAxes[i] = NULL;
-    }
+  for(i = 0; i < numAxis; ++i) {
+    outAxes[i] = NULL;
+  }
 
-    /* iterate over all subsets */
-    for(iParamAxis = 0; iParamAxis < params->numaxes; ++iParamAxis)
-    {
-        int found = 0;
+  /* iterate over all subsets */
+  for(iParamAxis = 0; iParamAxis < params->numaxes; ++iParamAxis) {
+    int found = 0;
 
-        /* check if subset is valid */
-        if(params->axes[iParamAxis]->subset != NULL)
-        {
-            if(params->axes[iParamAxis]->subset->timeOrScalar == MS_WCS20_TIME_VALUE)
-            {
-                msSetError(MS_WCSERR, "Time values for subsets are not supported. ",
-                        "msWCSCreateBoundingBox20()");
-                return MS_FAILURE;
-            }
-            if(params->axes[iParamAxis]->subset->operation == MS_WCS20_SLICE)
-            {
-                msSetError(MS_WCSERR, "Subset operation 'slice' is not supported.",
-                        "msWCSCreateBoundingBox20()");
-                return MS_FAILURE;
-            }
-        }
+    /* check if subset is valid */
+    if(params->axes[iParamAxis]->subset != NULL) {
+      if(params->axes[iParamAxis]->subset->timeOrScalar == MS_WCS20_TIME_VALUE) {
+        msSetError(MS_WCSERR, "Time values for subsets are not supported. ",
+                   "msWCSCreateBoundingBox20()");
+        return MS_FAILURE;
+      }
+      if(params->axes[iParamAxis]->subset->operation == MS_WCS20_SLICE) {
+        msSetError(MS_WCSERR, "Subset operation 'slice' is not supported.",
+                   "msWCSCreateBoundingBox20()");
+        return MS_FAILURE;
+      }
+    }
+
+    /* iterate over all given axes */
+    for(iAcceptedAxis = 0; iAcceptedAxis < numAxis; ++iAcceptedAxis ) {
+      /* iterate over all possible names for the current axis */
+      for(iName = 0; validAxisNames[iAcceptedAxis][iName] != NULL ; ++iName) {
+        /* compare axis name with current possible name */
+        if(EQUAL(params->axes[iParamAxis]->name, validAxisNames[iAcceptedAxis][iName])) {
+          /* if there is already a sample for the axis, throw error */
+          if(outAxes[iAcceptedAxis] != NULL) {
+            msSetError(MS_WCSERR, "The axis with the name '%s' corresponds "
+                       "to the same axis as the subset with the name '%s'.",
+                       "msWCSValidateAndFindSubsets20()",
+                       outAxes[iAcceptedAxis]->name, params->axes[iParamAxis]->name);
+            return MS_FAILURE;
+          }
 
-        /* iterate over all given axes */
-        for(iAcceptedAxis = 0; iAcceptedAxis < numAxis; ++iAcceptedAxis )
-        {
-            /* iterate over all possible names for the current axis */
-            for(iName = 0; validAxisNames[iAcceptedAxis][iName] != NULL ; ++iName)
-            {
-                /* compare axis name with current possible name */
-                if(EQUAL(params->axes[iParamAxis]->name, validAxisNames[iAcceptedAxis][iName]))
-                {
-                    /* if there is already a sample for the axis, throw error */
-                    if(outAxes[iAcceptedAxis] != NULL)
-                    {
-                        msSetError(MS_WCSERR, "The axis with the name '%s' corresponds "
-                                "to the same axis as the subset with the name '%s'.",
-                                "msWCSValidateAndFindSubsets20()",
-                                outAxes[iAcceptedAxis]->name, params->axes[iParamAxis]->name);
-                        return MS_FAILURE;
-                    }
-
-                    /* if match is found, save it */
-                    outAxes[iAcceptedAxis] = params->axes[iParamAxis];
-                    found = 1;
-                    break;
-                }
-            }
-            if (found)
-            {
-                break;
-            }
+          /* if match is found, save it */
+          outAxes[iAcceptedAxis] = params->axes[iParamAxis];
+          found = 1;
+          break;
         }
+      }
+      if (found) {
+        break;
+      }
+    }
 
-        /* no valid representation for current subset found */
-        /* exit and throw error                             */
-        if(found == 0)
-        {
-            msSetError(MS_WCSERR, "Invalid subset axis '%s'.",
-                    "msWCSValidateAndFindSubsets20()", params->axes[iParamAxis]->name);
-            return MS_FAILURE;
-        }
+    /* no valid representation for current subset found */
+    /* exit and throw error                             */
+    if(found == 0) {
+      msSetError(MS_WCSERR, "Invalid subset axis '%s'.",
+                 "msWCSValidateAndFindSubsets20()", params->axes[iParamAxis]->name);
+      return MS_FAILURE;
     }
-    return MS_SUCCESS;
+  }
+  return MS_SUCCESS;
 }
 
 /************************************************************************/
@@ -1450,34 +1161,34 @@ static int msWCSValidateAndFindAxes20(
 
 static void msWCSPrepareNamespaces20(xmlDocPtr pDoc, xmlNodePtr psRootNode, mapObj* map)
 {
-    xmlNsPtr psXsiNs;
-    char *schemaLocation = NULL;
-    char *xsi_schemaLocation = NULL;
-
-    xmlSetNs(psRootNode, xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_WCS_20_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_WCS_NAMESPACE_PREFIX));
-
-    xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_OWS_20_NAMESPACE_URI,        BAD_CAST MS_OWSCOMMON_OWS_NAMESPACE_PREFIX);
-    xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_OGC_NAMESPACE_URI,           BAD_CAST MS_OWSCOMMON_OGC_NAMESPACE_PREFIX );
-    xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_W3C_XSI_NAMESPACE_URI,       BAD_CAST MS_OWSCOMMON_W3C_XSI_NAMESPACE_PREFIX);
-    xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_W3C_XLINK_NAMESPACE_URI,     BAD_CAST MS_OWSCOMMON_W3C_XLINK_NAMESPACE_PREFIX);
-    xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_WCS_20_NAMESPACE_URI,        BAD_CAST MS_OWSCOMMON_WCS_NAMESPACE_PREFIX);
-    xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_GML_32_NAMESPACE_URI,        BAD_CAST MS_OWSCOMMON_GML_NAMESPACE_PREFIX);
-    xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_GMLCOV_10_NAMESPACE_URI,     BAD_CAST MS_OWSCOMMON_GMLCOV_NAMESPACE_PREFIX);
-    xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_SWE_20_NAMESPACE_URI,        BAD_CAST MS_OWSCOMMON_SWE_NAMESPACE_PREFIX);
-
-    psXsiNs = xmlSearchNs(pDoc, psRootNode, BAD_CAST MS_OWSCOMMON_W3C_XSI_NAMESPACE_PREFIX);
-
-    schemaLocation = msEncodeHTMLEntities( msOWSGetSchemasLocation(map) );
-    xsi_schemaLocation = msStrdup(MS_OWSCOMMON_WCS_20_NAMESPACE_URI);
-    xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, " ");
-    xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, schemaLocation);
-    xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, MS_OWSCOMMON_WCS_20_SCHEMAS_LOCATION);
-    xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, " ");
-
-    xmlNewNsProp(psRootNode, psXsiNs, BAD_CAST "schemaLocation", BAD_CAST xsi_schemaLocation);
-
-    msFree(schemaLocation);
-    msFree(xsi_schemaLocation);
+  xmlNsPtr psXsiNs;
+  char *schemaLocation = NULL;
+  char *xsi_schemaLocation = NULL;
+
+  xmlSetNs(psRootNode, xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_WCS_20_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_WCS_NAMESPACE_PREFIX));
+
+  xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_OWS_20_NAMESPACE_URI,        BAD_CAST MS_OWSCOMMON_OWS_NAMESPACE_PREFIX);
+  xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_OGC_NAMESPACE_URI,           BAD_CAST MS_OWSCOMMON_OGC_NAMESPACE_PREFIX );
+  xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_W3C_XSI_NAMESPACE_URI,       BAD_CAST MS_OWSCOMMON_W3C_XSI_NAMESPACE_PREFIX);
+  xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_W3C_XLINK_NAMESPACE_URI,     BAD_CAST MS_OWSCOMMON_W3C_XLINK_NAMESPACE_PREFIX);
+  xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_WCS_20_NAMESPACE_URI,        BAD_CAST MS_OWSCOMMON_WCS_NAMESPACE_PREFIX);
+  xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_GML_32_NAMESPACE_URI,        BAD_CAST MS_OWSCOMMON_GML_NAMESPACE_PREFIX);
+  xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_GMLCOV_10_NAMESPACE_URI,     BAD_CAST MS_OWSCOMMON_GMLCOV_NAMESPACE_PREFIX);
+  xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_SWE_20_NAMESPACE_URI,        BAD_CAST MS_OWSCOMMON_SWE_NAMESPACE_PREFIX);
+
+  psXsiNs = xmlSearchNs(pDoc, psRootNode, BAD_CAST MS_OWSCOMMON_W3C_XSI_NAMESPACE_PREFIX);
+
+  schemaLocation = msEncodeHTMLEntities( msOWSGetSchemasLocation(map) );
+  xsi_schemaLocation = msStrdup(MS_OWSCOMMON_WCS_20_NAMESPACE_URI);
+  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, " ");
+  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, schemaLocation);
+  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, MS_OWSCOMMON_WCS_20_SCHEMAS_LOCATION);
+  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, " ");
+
+  xmlNewNsProp(psRootNode, psXsiNs, BAD_CAST "schemaLocation", BAD_CAST xsi_schemaLocation);
+
+  msFree(schemaLocation);
+  msFree(xsi_schemaLocation);
 }
 
 /************************************************************************/
@@ -1488,111 +1199,111 @@ static void msWCSPrepareNamespaces20(xmlDocPtr pDoc, xmlNodePtr psRootNode, mapO
 
 static char *msWCSGetFormatsList20( mapObj *map, layerObj *layer )
 {
-    char *format_list = msStrdup("");
-    char **tokens = NULL, **formats = NULL;
-    int  i, numtokens = 0, numformats;
-    const char *value;
-
-    /* -------------------------------------------------------------------- */
-    /*      Parse from layer metadata.                                      */
-    /* -------------------------------------------------------------------- */
-    if( layer != NULL
-        && (value = msOWSGetEncodeMetadata( &(layer->metadata),"CO","formats",
-                                            NULL )) != NULL )
-    {
-        tokens = msStringSplit(value, ' ', &numtokens);
-    }
-
-    /* -------------------------------------------------------------------- */
-    /*      Or generate from all configured raster output formats that      */
-    /*      look plausible.                                                 */
-    /* -------------------------------------------------------------------- */
-    else
-    {
-        tokens = (char **) msSmallCalloc(map->numoutputformats,sizeof(char*));
-        for( i = 0; i < map->numoutputformats; i++ )
-        {
-            switch( map->outputformatlist[i]->renderer )
-            {
-            /* seemingly normal raster format */
-            case MS_RENDER_WITH_GD:
-            case MS_RENDER_WITH_AGG:
-            case MS_RENDER_WITH_RAWDATA:
-                tokens[numtokens++] = msStrdup(map->outputformatlist[i]->name);
-                break;
-            /* rest of formats aren't really WCS compatible */
-            default:
-                break;
-            }
-        }
+  char *format_list = msStrdup("");
+  char **tokens = NULL, **formats = NULL;
+  int  i, numtokens = 0, numformats;
+  char *value;
+
+  /* -------------------------------------------------------------------- */
+  /*      Parse from layer metadata.                                      */
+  /* -------------------------------------------------------------------- */
+  if( layer != NULL
+      && (value = msOWSGetEncodeMetadata( &(layer->metadata),"CO","formats",
+                                          NULL )) != NULL ) {
+    tokens = msStringSplit(value, ' ', &numtokens);
+    msFree(value);
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Parse from map.web metadata.                                    */
+  /* -------------------------------------------------------------------- */
+  else if((value = msOWSGetEncodeMetadata( &(map->web.metadata), "CO", "formats",
+                                           NULL)) != NULL ) {
+    tokens = msStringSplit(value, ' ', &numtokens);
+    msFree(value);
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Or generate from all configured raster output formats that      */
+  /*      look plausible.                                                 */
+  /* -------------------------------------------------------------------- */
+  else {
+    tokens = (char **) msSmallCalloc(map->numoutputformats,sizeof(char*));
+    for( i = 0; i < map->numoutputformats; i++ ) {
+      switch( map->outputformatlist[i]->renderer ) {
+          /* seemingly normal raster format */
+#ifdef USE_GD
+        case MS_RENDER_WITH_GD:
+#endif
+        case MS_RENDER_WITH_AGG:
+        case MS_RENDER_WITH_RAWDATA:
+          tokens[numtokens++] = msStrdup(map->outputformatlist[i]->name);
+          break;
+          /* rest of formats aren't really WCS compatible */
+        default:
+          break;
+      }
     }
+  }
 
-    /* -------------------------------------------------------------------- */
-    /*      Convert outputFormatObj names into mime types and remove        */
-    /*      duplicates.                                                     */
-    /* -------------------------------------------------------------------- */
-    numformats = 0;
-    formats = (char **) msSmallCalloc(sizeof(char*),numtokens);
-
-    for( i = 0; i < numtokens; i++ )
-    {
-        int format_i, j;
-        const char *mimetype;
+  /* -------------------------------------------------------------------- */
+  /*      Convert outputFormatObj names into mime types and remove        */
+  /*      duplicates.                                                     */
+  /* -------------------------------------------------------------------- */
+  numformats = 0;
+  formats = (char **) msSmallCalloc(sizeof(char*),numtokens);
 
-        for( format_i = 0; format_i < map->numoutputformats; format_i++ )
-        {
-            if( EQUAL(map->outputformatlist[format_i]->name, tokens[i]) )
-                break;
-        }
+  for( i = 0; i < numtokens; i++ ) {
+    int format_i, j;
+    const char *mimetype;
 
-        if( format_i == map->numoutputformats )
-        {
-            msDebug("Failed to find outputformat info on format '%s', ignore.\n",
-                    tokens[i] );
-            continue;
-        }
+    for( format_i = 0; format_i < map->numoutputformats; format_i++ ) {
+      if( EQUAL(map->outputformatlist[format_i]->name, tokens[i]) )
+        break;
+    }
 
-        mimetype = map->outputformatlist[format_i]->mimetype;
-        if( mimetype == NULL || strlen(mimetype) == 0 )
-        {
-            msDebug("No mimetime for format '%s', ignoring.\n",
-                    tokens[i] );
-            continue;
-        }
+    if( format_i == map->numoutputformats ) {
+      msDebug("Failed to find outputformat info on format '%s', ignore.\n",
+              tokens[i] );
+      continue;
+    }
 
-        for( j = 0; j < numformats; j++ )
-        {
-            if( EQUAL(mimetype,formats[j]) )
-                break;
-        }
+    mimetype = map->outputformatlist[format_i]->mimetype;
+    if( mimetype == NULL || strlen(mimetype) == 0 ) {
+      msDebug("No mimetime for format '%s', ignoring.\n",
+              tokens[i] );
+      continue;
+    }
 
-        if( j < numformats )
-        {
-            msDebug( "Format '%s' ignored since mimetype '%s' duplicates another outputFormatObj.\n",
-                     tokens[i], mimetype );
-            continue;
-        }
+    for( j = 0; j < numformats; j++ ) {
+      if( EQUAL(mimetype,formats[j]) )
+        break;
+    }
 
-        formats[numformats++] = msStrdup(mimetype);
+    if( j < numformats ) {
+      msDebug( "Format '%s' ignored since mimetype '%s' duplicates another outputFormatObj.\n",
+               tokens[i], mimetype );
+      continue;
     }
 
-    msFreeCharArray(tokens,numtokens);
+    formats[numformats++] = msStrdup(mimetype);
+  }
 
-    /* -------------------------------------------------------------------- */
-    /*      Turn mimetype list into comma delimited form for easy use       */
-    /*      with xml functions.                                             */
-    /* -------------------------------------------------------------------- */
-    for(i = 0; i < numformats; i++)
-    {
-        if(i > 0)
-        {
-            format_list = msStringConcatenate(format_list, (char *) ",");
-        }
-        format_list = msStringConcatenate(format_list, formats[i]);
+  msFreeCharArray(tokens,numtokens);
+
+  /* -------------------------------------------------------------------- */
+  /*      Turn mimetype list into comma delimited form for easy use       */
+  /*      with xml functions.                                             */
+  /* -------------------------------------------------------------------- */
+  for(i = 0; i < numformats; i++) {
+    if(i > 0) {
+      format_list = msStringConcatenate(format_list, (char *) ",");
     }
-    msFreeCharArray(formats,numformats);
+    format_list = msStringConcatenate(format_list, formats[i]);
+  }
+  msFreeCharArray(formats,numformats);
 
-    return format_list;
+  return format_list;
 }
 
 /************************************************************************/
@@ -1603,27 +1314,21 @@ static char *msWCSGetFormatsList20( mapObj *map, layerObj *layer )
 
 static int msWCSSwapAxes20(char *srs_uri)
 {
-    int srid = 0, i;
-    /* get SRID from the srs uri */
-    if(srs_uri != NULL && strlen(srs_uri) > 0) {
-        if(sscanf(srs_uri, "http://www.opengis.net/def/crs/EPSG/0/%d", &srid) != EOF)
-            ;
-        else if(sscanf(srs_uri, "http://www.opengis.net/def/crs/%d", &srid) != EOF)
-            ;
-        else
-            srid = 0;
-    }
-    if (srid == 0)
-        return MS_FALSE;
-
-    /*check the static table*/
-    for (i=0; i<AXIS_ORIENTATION_TABLE_SIZE; i++)
-    {
-        if (axisOrientationEpsgCodes[i].code == srid)
-          return MS_TRUE;
-    }
-
+  int srid = 0;
+
+  /* get SRID from the srs uri */
+  if(srs_uri != NULL && strlen(srs_uri) > 0) {
+    if(sscanf(srs_uri, "http://www.opengis.net/def/crs/EPSG/0/%d", &srid) != EOF)
+      ;
+    else if(sscanf(srs_uri, "http://www.opengis.net/def/crs/%d", &srid) != EOF)
+      ;
+    else
+      srid = 0;
+  }
+  if (srid == 0)
     return MS_FALSE;
+
+  return msIsAxisInverted(srid);
 }
 
 /************************************************************************/
@@ -1633,60 +1338,48 @@ static int msWCSSwapAxes20(char *srs_uri)
 /************************************************************************/
 
 static void msWCSCommon20_CreateBoundedBy(layerObj *layer, wcs20coverageMetadataObjPtr cm,
-        xmlNsPtr psGmlNs, xmlNodePtr psRoot, projectionObj *projection, int swapAxes)
+    xmlNsPtr psGmlNs, xmlNodePtr psRoot, projectionObj *projection, int swapAxes)
 {
-    xmlNodePtr psBoundedBy, psEnvelope;
-    char lowerCorner[100], upperCorner[100], axisLabels[100], uomLabels[100];
-
-    psBoundedBy = xmlNewChild( psRoot, psGmlNs, BAD_CAST "boundedBy", NULL);
-    {
-        psEnvelope = xmlNewChild(psBoundedBy, psGmlNs, BAD_CAST "Envelope", NULL);
-        {
-            xmlNewProp(psEnvelope, BAD_CAST "srsName", BAD_CAST cm->srs_uri);
-
-            if(projection->proj != NULL && pj_is_latlong(projection->proj))
-            {
-                if (swapAxes == MS_FALSE)
-                {
-                    strlcpy(axisLabels, "long lat", sizeof(axisLabels));
-                }
-                else
-                {
-                    strlcpy(axisLabels, "lat long", sizeof(axisLabels));
-                }
-                strlcpy(uomLabels, "deg deg", sizeof(uomLabels));
-            }
-            else
-            {
-                if (swapAxes == MS_FALSE)
-                {
-                    strlcpy(axisLabels, "x y", sizeof(axisLabels));
-                }
-                else
-                {
-                    strlcpy(axisLabels, "y x", sizeof(axisLabels));
-                }
-                strlcpy(uomLabels, "m m", sizeof(uomLabels));
-            }
-            xmlNewProp(psEnvelope, BAD_CAST "axisLabels", BAD_CAST axisLabels);
-            xmlNewProp(psEnvelope, BAD_CAST "uomLabels", BAD_CAST uomLabels);
-            xmlNewProp(psEnvelope, BAD_CAST "srsDimension", BAD_CAST "2");
-
-            if (swapAxes == MS_FALSE)
-            {
-                snprintf(lowerCorner, sizeof(lowerCorner), "%.15g %.15g", cm->extent.minx, cm->extent.miny);
-                snprintf(upperCorner, sizeof(upperCorner), "%.15g %.15g", cm->extent.maxx, cm->extent.maxy);
-            }
-            else
-            {
-                snprintf(lowerCorner, sizeof(lowerCorner), "%.15g %.15g", cm->extent.miny, cm->extent.minx);
-                snprintf(upperCorner, sizeof(upperCorner), "%.15g %.15g", cm->extent.maxy, cm->extent.maxx);
-            }
-
-            xmlNewChild(psEnvelope, psGmlNs, BAD_CAST "lowerCorner", BAD_CAST lowerCorner);
-            xmlNewChild(psEnvelope, psGmlNs, BAD_CAST "upperCorner", BAD_CAST upperCorner);
-        }
-    }
+  xmlNodePtr psBoundedBy, psEnvelope;
+  char lowerCorner[100], upperCorner[100], axisLabels[100], uomLabels[100];
+
+  psBoundedBy = xmlNewChild( psRoot, psGmlNs, BAD_CAST "boundedBy", NULL);
+  {
+    psEnvelope = xmlNewChild(psBoundedBy, psGmlNs, BAD_CAST "Envelope", NULL);
+    {
+      xmlNewProp(psEnvelope, BAD_CAST "srsName", BAD_CAST cm->srs_uri);
+
+      if(projection->proj != NULL && pj_is_latlong(projection->proj)) {
+        if (swapAxes == MS_FALSE) {
+          strlcpy(axisLabels, "long lat", sizeof(axisLabels));
+        } else {
+          strlcpy(axisLabels, "lat long", sizeof(axisLabels));
+        }
+        strlcpy(uomLabels, "deg deg", sizeof(uomLabels));
+      } else {
+        if (swapAxes == MS_FALSE) {
+          strlcpy(axisLabels, "x y", sizeof(axisLabels));
+        } else {
+          strlcpy(axisLabels, "y x", sizeof(axisLabels));
+        }
+        strlcpy(uomLabels, "m m", sizeof(uomLabels));
+      }
+      xmlNewProp(psEnvelope, BAD_CAST "axisLabels", BAD_CAST axisLabels);
+      xmlNewProp(psEnvelope, BAD_CAST "uomLabels", BAD_CAST uomLabels);
+      xmlNewProp(psEnvelope, BAD_CAST "srsDimension", BAD_CAST "2");
+
+      if (swapAxes == MS_FALSE) {
+        snprintf(lowerCorner, sizeof(lowerCorner), "%.15g %.15g", cm->extent.minx, cm->extent.miny);
+        snprintf(upperCorner, sizeof(upperCorner), "%.15g %.15g", cm->extent.maxx, cm->extent.maxy);
+      } else {
+        snprintf(lowerCorner, sizeof(lowerCorner), "%.15g %.15g", cm->extent.miny, cm->extent.minx);
+        snprintf(upperCorner, sizeof(upperCorner), "%.15g %.15g", cm->extent.maxy, cm->extent.maxx);
+      }
+
+      xmlNewChild(psEnvelope, psGmlNs, BAD_CAST "lowerCorner", BAD_CAST lowerCorner);
+      xmlNewChild(psEnvelope, psGmlNs, BAD_CAST "upperCorner", BAD_CAST upperCorner);
+    }
+  }
 }
 
 /************************************************************************/
@@ -1696,94 +1389,77 @@ static void msWCSCommon20_CreateBoundedBy(layerObj *layer, wcs20coverageMetadata
 /************************************************************************/
 
 static void msWCSCommon20_CreateDomainSet(layerObj* layer, wcs20coverageMetadataObjPtr cm,
-        xmlNsPtr psGmlNs, xmlNodePtr psRoot, projectionObj *projection, int swapAxes)
+    xmlNsPtr psGmlNs, xmlNodePtr psRoot, projectionObj *projection, int swapAxes)
 {
-    xmlNodePtr psDomainSet, psGrid, psLimits, psGridEnvelope, psOrigin,
-        psPos, psOffsetX, psOffsetY;
-    char low[100], high[100], id[100], point[100], resx[100], resy[100], axisLabels[100];
-
-    psDomainSet = xmlNewChild( psRoot, psGmlNs, BAD_CAST "domainSet", NULL);
-    {
-        psGrid = xmlNewChild(psDomainSet, psGmlNs, BAD_CAST "RectifiedGrid", NULL);
-        {
-            xmlNewProp(psGrid, BAD_CAST "dimension", BAD_CAST "2");
-            snprintf(id, sizeof(id), "grid_%s", layer->name);
-            xmlNewNsProp(psGrid, psGmlNs, BAD_CAST "id", BAD_CAST id);
-
-            psLimits = xmlNewChild(psGrid, psGmlNs, BAD_CAST "limits", NULL);
-            {
-                psGridEnvelope = xmlNewChild(psLimits, psGmlNs, BAD_CAST "GridEnvelope", NULL);
-                {
-                    strlcpy(low, "0 0", sizeof(low));
-                    snprintf(high, sizeof(high), "%d %d", cm->xsize - 1, cm->ysize - 1);
-
-                    xmlNewChild(psGridEnvelope, psGmlNs, BAD_CAST "low", BAD_CAST low);
-                    xmlNewChild(psGridEnvelope, psGmlNs, BAD_CAST "high", BAD_CAST high);
-                }
-            }
-            
-
-
-            if(projection->proj != NULL && pj_is_latlong(projection->proj))
-            {
-                if (swapAxes == MS_FALSE)
-                {
-                    strlcpy(axisLabels, "long lat", sizeof(axisLabels));
-                }
-                else
-                {
-                    strlcpy(axisLabels, "lat long", sizeof(axisLabels));
-                }
-            }
-            else
-            {
-                if (swapAxes == MS_FALSE)
-                {
-                    strlcpy(axisLabels, "x y", sizeof(axisLabels));
-                }
-                else
-                {
-                    strlcpy(axisLabels, "y x", sizeof(axisLabels));
-                }
-            }
- 
-            xmlNewChild(psGrid, psGmlNs, BAD_CAST "axisLabels", BAD_CAST axisLabels);
- 
-            psOrigin = xmlNewChild(psGrid, psGmlNs, BAD_CAST "origin", NULL);
-            {
-                if (swapAxes == MS_FALSE)
-                {
-                    snprintf(point, sizeof(point), "%f %f", cm->extent.minx, cm->extent.maxy);
-                }
-                else
-                {
-                    snprintf(point, sizeof(point), "%f %f", cm->extent.maxy, cm->extent.minx);
-                }
-                psOrigin = xmlNewChild(psOrigin, psGmlNs, BAD_CAST "Point", NULL);
-                snprintf(id, sizeof(id), "grid_origin_%s", layer->name);
-                xmlNewNsProp(psOrigin, psGmlNs, BAD_CAST "id", BAD_CAST id);
-                xmlNewProp(psOrigin, BAD_CAST "srsName", BAD_CAST cm->srs_uri);
-
-                psPos = xmlNewChild(psOrigin, psGmlNs, BAD_CAST "pos", BAD_CAST point);
-            }
-
-            if (swapAxes == MS_FALSE)
-            {
-                snprintf(resx, sizeof(resx), "%f 0", cm->xresolution);
-                snprintf(resy, sizeof(resy), "0 %f", -fabs(cm->yresolution));
-            }
-            else
-            {
-                snprintf(resx, sizeof(resx), "0 %f", cm->xresolution);
-                snprintf(resy, sizeof(resy), "%f 0", -fabs(cm->yresolution));
-            }
-            psOffsetX = xmlNewChild(psGrid, psGmlNs, BAD_CAST "offsetVector", BAD_CAST resx);
-            psOffsetY = xmlNewChild(psGrid, psGmlNs, BAD_CAST "offsetVector", BAD_CAST resy);
-
-            xmlNewProp(psOffsetX, BAD_CAST "srsName", BAD_CAST cm->srs_uri);
-            xmlNewProp(psOffsetY, BAD_CAST "srsName", BAD_CAST cm->srs_uri);
-        }
-    }
+  xmlNodePtr psDomainSet, psGrid, psLimits, psGridEnvelope, psOrigin,
+             psOffsetX, psOffsetY;
+  char low[100], high[100], id[100], point[100], resx[100], resy[100], axisLabels[100];
+
+  psDomainSet = xmlNewChild( psRoot, psGmlNs, BAD_CAST "domainSet", NULL);
+  {
+    psGrid = xmlNewChild(psDomainSet, psGmlNs, BAD_CAST "RectifiedGrid", NULL);
+    {
+      xmlNewProp(psGrid, BAD_CAST "dimension", BAD_CAST "2");
+      snprintf(id, sizeof(id), "grid_%s", layer->name);
+      xmlNewNsProp(psGrid, psGmlNs, BAD_CAST "id", BAD_CAST id);
+
+      psLimits = xmlNewChild(psGrid, psGmlNs, BAD_CAST "limits", NULL);
+      {
+        psGridEnvelope = xmlNewChild(psLimits, psGmlNs, BAD_CAST "GridEnvelope", NULL);
+        {
+          strlcpy(low, "0 0", sizeof(low));
+          snprintf(high, sizeof(high), "%d %d", cm->xsize - 1, cm->ysize - 1);
+
+          xmlNewChild(psGridEnvelope, psGmlNs, BAD_CAST "low", BAD_CAST low);
+          xmlNewChild(psGridEnvelope, psGmlNs, BAD_CAST "high", BAD_CAST high);
+        }
+      }
+
+      if(projection->proj != NULL && pj_is_latlong(projection->proj)) {
+        if (swapAxes == MS_FALSE) {
+          strlcpy(axisLabels, "long lat", sizeof(axisLabels));
+        } else {
+          strlcpy(axisLabels, "lat long", sizeof(axisLabels));
+        }
+      } else {
+        if (swapAxes == MS_FALSE) {
+          strlcpy(axisLabels, "x y", sizeof(axisLabels));
+        } else {
+          strlcpy(axisLabels, "y x", sizeof(axisLabels));
+        }
+      }
+
+      xmlNewChild(psGrid, psGmlNs, BAD_CAST "axisLabels", BAD_CAST axisLabels);
+
+      psOrigin = xmlNewChild(psGrid, psGmlNs, BAD_CAST "origin", NULL);
+      {
+        if (swapAxes == MS_FALSE) {
+          snprintf(point, sizeof(point), "%f %f", cm->extent.minx, cm->extent.maxy);
+        } else {
+          snprintf(point, sizeof(point), "%f %f", cm->extent.maxy, cm->extent.minx);
+        }
+        psOrigin = xmlNewChild(psOrigin, psGmlNs, BAD_CAST "Point", NULL);
+        snprintf(id, sizeof(id), "grid_origin_%s", layer->name);
+        xmlNewNsProp(psOrigin, psGmlNs, BAD_CAST "id", BAD_CAST id);
+        xmlNewProp(psOrigin, BAD_CAST "srsName", BAD_CAST cm->srs_uri);
+
+        xmlNewChild(psOrigin, psGmlNs, BAD_CAST "pos", BAD_CAST point);
+      }
+
+      if (swapAxes == MS_FALSE) {
+        snprintf(resx, sizeof(resx), "%f 0", cm->xresolution);
+        snprintf(resy, sizeof(resy), "0 %f", -fabs(cm->yresolution));
+      } else {
+        snprintf(resx, sizeof(resx), "0 %f", cm->xresolution);
+        snprintf(resy, sizeof(resy), "%f 0", -fabs(cm->yresolution));
+      }
+      psOffsetX = xmlNewChild(psGrid, psGmlNs, BAD_CAST "offsetVector", BAD_CAST resx);
+      psOffsetY = xmlNewChild(psGrid, psGmlNs, BAD_CAST "offsetVector", BAD_CAST resy);
+
+      xmlNewProp(psOffsetX, BAD_CAST "srsName", BAD_CAST cm->srs_uri);
+      xmlNewProp(psOffsetY, BAD_CAST "srsName", BAD_CAST cm->srs_uri);
+    }
+  }
 }
 
 /************************************************************************/
@@ -1793,113 +1469,96 @@ static void msWCSCommon20_CreateDomainSet(layerObj* layer, wcs20coverageMetadata
 /************************************************************************/
 
 static void msWCSCommon20_CreateRangeType(layerObj* layer, wcs20coverageMetadataObjPtr cm, char *bands,
-        xmlNsPtr psGmlNs, xmlNsPtr psGmlcovNs, xmlNsPtr psSweNs, xmlNsPtr psXLinkNs, xmlNodePtr psRoot)
+    xmlNsPtr psGmlNs, xmlNsPtr psGmlcovNs, xmlNsPtr psSweNs, xmlNsPtr psXLinkNs, xmlNodePtr psRoot)
 {
-    xmlNodePtr psRangeType, psDataRecord, psField, psQuantity,
-        psUom, psConstraint, psAllowedValues = NULL, psNilValues = NULL;
-    char **arr = NULL;
-    int i, num = 0;
-
-    if(NULL != bands)
-    {
-        arr = msStringSplit(bands, ',', &num);
-    }
-
-    psRangeType = xmlNewChild( psRoot, psGmlcovNs, BAD_CAST "rangeType", NULL);
-    psDataRecord  = xmlNewChild(psRangeType, psSweNs, BAD_CAST "DataRecord", NULL);
-
-    /* iterate over every band */
-    for(i = 0; i < cm->numbands; ++i)
-    {
-        /* only add bands that are in the range subset */
-        if (NULL != arr && num > 0)
-        {
-            int found = MS_FALSE, j, repr;
-            for(j = 0; j < num; ++j)
-            {
-                msStringParseInteger(arr[j], &repr);
-                if(repr == i + 1)
-                {
-                    found = MS_TRUE;
-                    break;
-                }
-            }
-            if(found == MS_FALSE)
-            {
-                /* ignore this band since it is not in the range subset */
-                continue;
-            }
-        }
-
-        /* add field tag */
-        psField = xmlNewChild(psDataRecord, psSweNs, BAD_CAST "field", NULL);
-
-        if(cm->bands[i].name != NULL)
-        {
-            xmlNewProp(psField, BAD_CAST "name", BAD_CAST cm->bands[i].name);
-        }
-        else
-        {
-            xmlNewProp(psField, BAD_CAST "name", BAD_CAST "band");
-        }
-        /* add Quantity tag */
-        psQuantity = xmlNewChild(psField, psSweNs, BAD_CAST "Quantity", NULL);
-        if(cm->bands[i].definition != NULL)
-        {
-            xmlNewProp(psQuantity, BAD_CAST "definition", BAD_CAST cm->bands[i].definition);
-        }
-        if(cm->bands[i].description != NULL)
-        {
-            xmlNewChild(psQuantity, psSweNs, BAD_CAST "description", BAD_CAST cm->bands[i].description);
-        }
-
-        /* if there are given nilvalues -> add them to the first field */
-        /* all other fields get a reference to these */
-        if(cm->numnilvalues > 0)
-        {
-            int j;
-            psNilValues = xmlNewChild(
-                xmlNewChild(psQuantity, psSweNs, BAD_CAST "nilValues", NULL),
-                psSweNs, BAD_CAST "NilValues", NULL);
-            for(j = 0; j < cm->numnilvalues; ++j)
-            {
-                xmlNodePtr psTemp =
-                    xmlNewChild(psNilValues, psSweNs, BAD_CAST "nilValue", BAD_CAST cm->nilvalues[j]);
-                if(j < cm->numnilvalues)
-                    xmlNewProp(psTemp, BAD_CAST "reason", BAD_CAST cm->nilvalues_reasons[j]);
-            }
-        }
-        else /* create an empty nilValues tag */
-        {
-            xmlNewChild(psQuantity, psSweNs, BAD_CAST "nilValues", NULL);
-        }
-
-        psUom = xmlNewChild(psQuantity, psSweNs, BAD_CAST "uom", NULL);
-        if(cm->bands[i].uom != NULL)
-        {
-            xmlNewProp(psUom, BAD_CAST "code", BAD_CAST cm->bands[i].uom);
-        }
-        else
-        {
-            xmlNewProp(psUom, BAD_CAST "code", BAD_CAST "W.m-2.Sr-1");
-        }
-
-        /* add constraint */
-        psConstraint = xmlNewChild(psQuantity, psSweNs, BAD_CAST "constraint", NULL);
-        
-        {
-            char interval[100], significant_figures[100];
-            psAllowedValues = xmlNewChild(psConstraint, psSweNs, BAD_CAST "AllowedValues", NULL);
-
-            /* Interval */
-            snprintf(interval, sizeof(interval), "%.5g %.5g", cm->bands[i].interval_min, cm->bands[i].interval_max);
-            xmlNewChild(psAllowedValues, psSweNs, BAD_CAST "interval", BAD_CAST interval);
-
-            /* Significant figures */
-            snprintf(significant_figures, sizeof(significant_figures), "%d", cm->bands[i].significant_figures);
-            xmlNewChild(psAllowedValues, psSweNs, BAD_CAST "significantFigures", BAD_CAST significant_figures);
-        }
-    }
+  xmlNodePtr psRangeType, psDataRecord, psField, psQuantity,
+             psUom, psConstraint, psAllowedValues = NULL, psNilValues = NULL;
+  char **arr = NULL;
+  int i, num = 0;
+
+  if(NULL != bands) {
+    arr = msStringSplit(bands, ',', &num);
+  }
+
+  psRangeType = xmlNewChild( psRoot, psGmlcovNs, BAD_CAST "rangeType", NULL);
+  psDataRecord  = xmlNewChild(psRangeType, psSweNs, BAD_CAST "DataRecord", NULL);
+
+  /* iterate over every band */
+  for(i = 0; i < cm->numbands; ++i) {
+    /* only add bands that are in the range subset */
+    if (NULL != arr && num > 0) {
+      int found = MS_FALSE, j, repr;
+      for(j = 0; j < num; ++j) {
+        msStringParseInteger(arr[j], &repr);
+        if(repr == i + 1) {
+          found = MS_TRUE;
+          break;
+        }
+      }
+      if(found == MS_FALSE) {
+        /* ignore this band since it is not in the range subset */
+        continue;
+      }
+    }
+
+    /* add field tag */
+    psField = xmlNewChild(psDataRecord, psSweNs, BAD_CAST "field", NULL);
+
+    if(cm->bands[i].name != NULL) {
+      xmlNewProp(psField, BAD_CAST "name", BAD_CAST cm->bands[i].name);
+    } else {
+      xmlNewProp(psField, BAD_CAST "name", BAD_CAST "band");
+    }
+    /* add Quantity tag */
+    psQuantity = xmlNewChild(psField, psSweNs, BAD_CAST "Quantity", NULL);
+    if(cm->bands[i].definition != NULL) {
+      xmlNewProp(psQuantity, BAD_CAST "definition", BAD_CAST cm->bands[i].definition);
+    }
+    if(cm->bands[i].description != NULL) {
+      xmlNewChild(psQuantity, psSweNs, BAD_CAST "description", BAD_CAST cm->bands[i].description);
+    }
+
+    /* if there are given nilvalues -> add them to the first field */
+    /* all other fields get a reference to these */
+    if(cm->numnilvalues > 0) {
+      int j;
+      psNilValues = xmlNewChild(
+                      xmlNewChild(psQuantity, psSweNs, BAD_CAST "nilValues", NULL),
+                      psSweNs, BAD_CAST "NilValues", NULL);
+      for(j = 0; j < cm->numnilvalues; ++j) {
+        xmlNodePtr psTemp =
+          xmlNewChild(psNilValues, psSweNs, BAD_CAST "nilValue", BAD_CAST cm->nilvalues[j]);
+        if(j < cm->numnilvalues)
+          xmlNewProp(psTemp, BAD_CAST "reason", BAD_CAST cm->nilvalues_reasons[j]);
+      }
+    } else { /* create an empty nilValues tag */
+      xmlNewChild(psQuantity, psSweNs, BAD_CAST "nilValues", NULL);
+    }
+
+    psUom = xmlNewChild(psQuantity, psSweNs, BAD_CAST "uom", NULL);
+    if(cm->bands[i].uom != NULL) {
+      xmlNewProp(psUom, BAD_CAST "code", BAD_CAST cm->bands[i].uom);
+    } else {
+      xmlNewProp(psUom, BAD_CAST "code", BAD_CAST "W.m-2.Sr-1");
+    }
+
+    /* add constraint */
+    psConstraint = xmlNewChild(psQuantity, psSweNs, BAD_CAST "constraint", NULL);
+
+    {
+      char interval[100], significant_figures[100];
+      psAllowedValues = xmlNewChild(psConstraint, psSweNs, BAD_CAST "AllowedValues", NULL);
+
+      /* Interval */
+      snprintf(interval, sizeof(interval), "%.5g %.5g", cm->bands[i].interval_min, cm->bands[i].interval_max);
+      xmlNewChild(psAllowedValues, psSweNs, BAD_CAST "interval", BAD_CAST interval);
+
+      /* Significant figures */
+      snprintf(significant_figures, sizeof(significant_figures), "%d", cm->bands[i].significant_figures);
+      xmlNewChild(psAllowedValues, psSweNs, BAD_CAST "significantFigures", BAD_CAST significant_figures);
+    }
+  }
+  msFreeCharArray(arr,num);
 }
 
 /************************************************************************/
@@ -1910,33 +1569,35 @@ static void msWCSCommon20_CreateRangeType(layerObj* layer, wcs20coverageMetadata
 
 static int msWCSWriteDocument20(mapObj* map, xmlDocPtr psDoc)
 {
-    xmlChar *buffer = NULL;
-    int size = 0;
-    msIOContext *context = NULL;
+  xmlChar *buffer = NULL;
+  int size = 0;
+  msIOContext *context = NULL;
+  const char *contenttype = NULL;
 
-    const char *encoding = msOWSLookupMetadata(&(map->web.metadata), "CO", "encoding");
+  const char *encoding = msOWSLookupMetadata(&(map->web.metadata), "CO", "encoding");
 
-    if( msIO_needBinaryStdout() == MS_FAILURE )
-    {
-        return MS_FAILURE;
-    }
+  if( msIO_needBinaryStdout() == MS_FAILURE ) {
+    return MS_FAILURE;
+  }
 
-    if (encoding)
-    {
-        msIO_printf("Content-type: text/xml; charset=%s%c%c", encoding,10,10);
-    }
-    else
-    {
-        msIO_printf("Content-type: text/xml%c%c",10,10);
-    }
+  if( EQUAL((char *)xmlDocGetRootElement(psDoc)->name, "RectifiedGridCoverage") )
+    contenttype = msStrdup("application/gml+xml");
+  else
+    contenttype = msStrdup("text/xml");
 
-    context = msIO_getHandler(stdout);
+  if (encoding)
+    msIO_setHeader("Content-Type","%s; charset=%s", contenttype, encoding);
+  else
+    msIO_setHeader("Content-Type","%s", contenttype);
+  msIO_sendHeaders();
 
-    xmlDocDumpFormatMemoryEnc(psDoc, &buffer, &size, (encoding ? encoding : "ISO-8859-1"), 1);
-    msIO_contextWrite(context, buffer, size);
-    xmlFree(buffer);
+  context = msIO_getHandler(stdout);
 
-    return MS_SUCCESS;
+  xmlDocDumpFormatMemoryEnc(psDoc, &buffer, &size, (encoding ? encoding : "ISO-8859-1"), 1);
+  msIO_contextWrite(context, buffer, size);
+  xmlFree(buffer);
+
+  return MS_SUCCESS;
 }
 
 /************************************************************************/
@@ -1948,213 +1609,215 @@ static int msWCSWriteDocument20(mapObj* map, xmlDocPtr psDoc)
 
 static int msWCSWriteFile20(mapObj* map, imageObj* image, wcs20ParamsObjPtr params, int multipart)
 {
-    int status;
-    char* filename = NULL;
-    const char *fo_filename;
-    int i;
-
-    fo_filename = msGetOutputFormatOption( image->format, "FILENAME", NULL );
+  int status;
+  char* filename = NULL;
+  char *base_dir = NULL;
+  const char *fo_filename;
+  int i;
+
+  fo_filename = msGetOutputFormatOption( image->format, "FILENAME", NULL );
+
+  /* -------------------------------------------------------------------- */
+  /*      Fetch the driver we will be using and check if it supports      */
+  /*      VSIL IO.                                                        */
+  /* -------------------------------------------------------------------- */
+  if( EQUALN(image->format->driver,"GDAL/",5) ) {
+    GDALDriverH hDriver;
+    const char *pszExtension = image->format->extension;
+
+    msAcquireLock( TLOCK_GDAL );
+    hDriver = GDALGetDriverByName( image->format->driver+5 );
+    if( hDriver == NULL ) {
+      msReleaseLock( TLOCK_GDAL );
+      msSetError( MS_MISCERR,
+                  "Failed to find %s driver.",
+                  "msWCSWriteFile20()",
+                  image->format->driver+5 );
+      return msWCSException(map, "mapserv", "NoApplicableCode",
+                            params->version);
+    }
+
+    if( pszExtension == NULL )
+      pszExtension = "img.tmp";
+
+    if( GDALGetMetadataItem( hDriver, GDAL_DCAP_VIRTUALIO, NULL )
+        != NULL ) {
+      base_dir = msTmpFile(map, map->mappath, "/vsimem/wcsout", NULL);
+      if( fo_filename )
+        filename = msStrdup(CPLFormFilename(base_dir,
+                                            fo_filename,NULL));
+      else
+        filename = msStrdup(CPLFormFilename(base_dir,
+                                            "out", pszExtension ));
+
+      /*            CleanVSIDir( "/vsimem/wcsout" ); */
+
+      msReleaseLock( TLOCK_GDAL );
+      status = msSaveImage(map, image, filename);
+      if( status != MS_SUCCESS ) {
+        msSetError(MS_MISCERR, "msSaveImage() failed",
+                   "msWCSWriteFile20()");
+        return msWCSException20(map, "mapserv", "NoApplicableCode",
+                                params->version);
+      }
+    }
+    msReleaseLock( TLOCK_GDAL );
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      If we weren't able to write data under /vsimem, then we just    */
+  /*      output a single "stock" filename.                               */
+  /* -------------------------------------------------------------------- */
+  if( filename == NULL ) {
+    if(multipart) {
+      msIO_fprintf( stdout, "\r\n--wcs\r\n" );
+      msIO_fprintf(
+        stdout,
+        "Content-Type: %s\r\n"
+        "Content-Description: coverage data\r\n"
+        "Content-Transfer-Encoding: binary\r\n",
+        MS_IMAGE_MIME_TYPE(map->outputformat));
+
+      if( fo_filename != NULL )
+        msIO_fprintf( stdout,
+                      "Content-ID: coverage/%s\r\n"
+                      "Content-Disposition: INLINE; filename=%s\r\n\r\n",
+                      fo_filename,
+                      fo_filename);
+      else
+        msIO_fprintf( stdout,
+                      "Content-ID: coverage/wcs.%s\r\n"
+                      "Content-Disposition: INLINE\r\n\r\n",
+                      MS_IMAGE_EXTENSION(map->outputformat));
+    } else {
+      msIO_setHeader("Content-Type",MS_IMAGE_MIME_TYPE(map->outputformat));
+      msIO_setHeader("Content-Description","coverage data");
+      msIO_setHeader("Content-Transfer-Encoding","binary");
+
+      if( fo_filename != NULL ) {
+        msIO_setHeader("Content-ID","coverage/%s",fo_filename);
+        msIO_setHeader("Content-Disposition","INLINE; filename=%s",fo_filename);
+      } else {
+        msIO_setHeader("Content-ID","coverage/wcs.%s",MS_IMAGE_EXTENSION(map->outputformat));
+        msIO_setHeader("Content-Disposition","INLINE");
+      }
+      msIO_sendHeaders();
+    }
+
+    status = msSaveImage(map, image, NULL);
+    if( status != MS_SUCCESS ) {
+      msSetError( MS_MISCERR, "msSaveImage() failed", "msWCSWriteFile20()");
+      return msWCSException(map, "mapserv", "NoApplicableCode", params->version);
+    }
+    if(multipart)
+      msIO_fprintf( stdout, "\r\n--wcs--\r\n" );
+    return MS_SUCCESS;
+  }
 
-    /* -------------------------------------------------------------------- */
-    /*      Fetch the driver we will be using and check if it supports      */
-    /*      VSIL IO.                                                        */
-    /* -------------------------------------------------------------------- */
-#ifdef GDAL_DCAP_VIRTUALIO
-    if( EQUALN(image->format->driver,"GDAL/",5) )
-    {
-        GDALDriverH hDriver;
-        const char *pszExtension = image->format->extension;
+  /* -------------------------------------------------------------------- */
+  /*      When potentially listing multiple files, we take great care     */
+  /*      to identify the "primary" file and list it first.  In fact      */
+  /*      it is the only file listed in the coverages document.           */
+  /* -------------------------------------------------------------------- */
+  {
+    char **all_files = CPLReadDir( base_dir );
+    int count = CSLCount(all_files);
 
-        msAcquireLock( TLOCK_GDAL );
-        hDriver = GDALGetDriverByName( image->format->driver+5 );
-        if( hDriver == NULL )
-        {
-            msReleaseLock( TLOCK_GDAL );
-            msSetError( MS_MISCERR,
-                        "Failed to find %s driver.",
-                        "msWCSWriteFile20()",
-                        image->format->driver+5 );
-            return msWCSException(map, "mapserv", "NoApplicableCode",
-                                  params->version);
-        }
+    if( msIO_needBinaryStdout() == MS_FAILURE )
+      return MS_FAILURE;
 
-        if( pszExtension == NULL )
-            pszExtension = "img.tmp";
+    msAcquireLock( TLOCK_GDAL );
+    for( i = count-1; i >= 0; i-- ) {
+      const char *this_file = all_files[i];
 
-        if( GDALGetMetadataItem( hDriver, GDAL_DCAP_VIRTUALIO, NULL )
-            != NULL )
-        {
-            if( fo_filename )
-                filename = msStrdup(CPLFormFilename("/vsimem/wcsout",
-                                                    fo_filename,NULL));
-            else
-                filename = msStrdup(CPLFormFilename("/vsimem/wcsout", 
-                                                    "out", pszExtension ));
-
-            /*            CleanVSIDir( "/vsimem/wcsout" ); */
-
-            msReleaseLock( TLOCK_GDAL );
-            status = msSaveImage(map, image, filename);
-            if( status != MS_SUCCESS )
-            {
-                msSetError(MS_MISCERR, "msSaveImage() failed",
-                           "msWCSWriteFile20()");
-                return msWCSException20(map, "mapserv", "NoApplicableCode",
-                                        params->version);
-            }
-        }
-        msReleaseLock( TLOCK_GDAL );
-    }
-#endif
+      if( EQUAL(this_file,".") || EQUAL(this_file,"..") ) {
+        all_files = CSLRemoveStrings( all_files, i, 1, NULL );
+        continue;
+      }
 
-    /* -------------------------------------------------------------------- */
-    /*      If we weren't able to write data under /vsimem, then we just    */
-    /*      output a single "stock" filename.                               */
-    /* -------------------------------------------------------------------- */
-    if( filename == NULL )
-    {
-        if(multipart)
-        {
-            msIO_fprintf( stdout, "--wcs\n" );
-        }
-        msIO_fprintf(
-            stdout,
-            "Content-Type: %s\n"
-            "Content-Description: coverage data\n"
-            "Content-Transfer-Encoding: binary\n",
-            MS_IMAGE_MIME_TYPE(map->outputformat));
-
-        if( fo_filename != NULL )
-            msIO_fprintf( stdout, 
-                "Content-ID: coverage/%s\n"
-                "Content-Disposition: attachment; filename=%s%c%c",
-                fo_filename,
-                fo_filename,
-                10, 10 );
-        else
-            msIO_fprintf( stdout, 
-                "Content-ID: coverage/wcs.%s\n"
-                "Content-Disposition: INLINE%c%c",
-                MS_IMAGE_EXTENSION(map->outputformat),
-                10, 10 );
-
-        status = msSaveImage(map, image, NULL);
-        if( status != MS_SUCCESS )
-        {
-            msSetError( MS_MISCERR, "msSaveImage() failed", "msWCSWriteFile20()");
-            return msWCSException(map, "mapserv", "NoApplicableCode", params->version);
-        }
-        if(multipart)
-            msIO_fprintf( stdout, "\n--wcs--%c%c", 10, 10 );
-        return MS_SUCCESS;
+      if( i > 0 && EQUAL(this_file,CPLGetFilename(filename)) ) {
+        all_files = CSLRemoveStrings( all_files, i, 1, NULL );
+        all_files = CSLInsertString(all_files,0,CPLGetFilename(filename));
+        i++;
+      }
     }
 
     /* -------------------------------------------------------------------- */
-    /*      When potentially listing multiple files, we take great care     */
-    /*      to identify the "primary" file and list it first.  In fact      */
-    /*      it is the only file listed in the coverages document.           */
+    /*      Dump all the files in the memory directory as mime sections.    */
     /* -------------------------------------------------------------------- */
-#ifdef GDAL_DCAP_VIRTUALIO
-    {
-        char **all_files = CPLReadDir( "/vsimem/wcsout" );
-        int count = CSLCount(all_files);
-
-        if( msIO_needBinaryStdout() == MS_FAILURE )
-            return MS_FAILURE;
-
-        msAcquireLock( TLOCK_GDAL );
-        for( i = count-1; i >= 0; i-- )
-        {
-            const char *this_file = all_files[i];
-
-            if( EQUAL(this_file,".") || EQUAL(this_file,"..") )
-            {
-                all_files = CSLRemoveStrings( all_files, i, 1, NULL );
-                continue;
-            }
-
-            if( i > 0 && EQUAL(this_file,CPLGetFilename(filename)) )
-            {
-                all_files = CSLRemoveStrings( all_files, i, 1, NULL );
-                all_files = CSLInsertString(all_files,0,CPLGetFilename(filename));
-                i++;
-            }
-        }
+    count = CSLCount(all_files);
 
-        /* -------------------------------------------------------------------- */
-        /*      Dump all the files in the memory directory as mime sections.    */
-        /* -------------------------------------------------------------------- */
-        count = CSLCount(all_files);
-
-        if(count > 1 && multipart == MS_FALSE)
-        {
-            msDebug( "msWCSWriteFile20(): force multipart output without gml summary because we have multiple files in the result.\n" );
+    if(count > 1 && multipart == MS_FALSE) {
+      msDebug( "msWCSWriteFile20(): force multipart output without gml summary because we have multiple files in the result.\n" );
 
-            multipart = MS_TRUE;
-            msIO_printf(
-                "Content-Type: multipart/mixed; boundary=wcs%c%c", 10, 10);
-        }
+      multipart = MS_TRUE;
+      msIO_setHeader("Content-Type","multipart/related; boundary=wcs");
+      msIO_sendHeaders();
+    }
 
-        for( i = 0; i < count; i++ )
-        {
-            const char *mimetype = NULL;
-            FILE *fp;
-            unsigned char block[4000];
-            int bytes_read;
-
-            if( i == 0
-                && !EQUAL(MS_IMAGE_MIME_TYPE(map->outputformat), "unknown") )
-                mimetype = MS_IMAGE_MIME_TYPE(map->outputformat);
-
-            if( mimetype == NULL )
-                mimetype = "application/octet-stream";
-            if(multipart)
-            {
-                msIO_fprintf( stdout, "--wcs\n" );
-            }
+    for( i = 0; i < count; i++ ) {
+      const char *mimetype = NULL;
+      FILE *fp;
+      unsigned char block[4000];
+      int bytes_read;
 
-            msIO_fprintf(
-                stdout,
-                "Content-Type: %s\n"
-                "Content-Description: coverage data\n"
-                "Content-Transfer-Encoding: binary\n"
-                "Content-ID: coverage/%s\n"
-                "Content-Disposition: attachment; filename=%s%c%c",
-                mimetype,
-                all_files[i],
-                all_files[i],
-                10, 10 );
-
-            fp = VSIFOpenL(
-                CPLFormFilename("/vsimem/wcsout", all_files[i], NULL),
-                "rb" );
-            if( fp == NULL )
-            {
-                msReleaseLock( TLOCK_GDAL );
-                msSetError( MS_MISCERR,
-                            "Failed to open %s for streaming to stdout.",
-                            "msWCSWriteFile20()", all_files[i] );
-                return MS_FAILURE;
-            }
+      if( i == 0
+          && !EQUAL(MS_IMAGE_MIME_TYPE(map->outputformat), "unknown") )
+        mimetype = MS_IMAGE_MIME_TYPE(map->outputformat);
 
-            while( (bytes_read = VSIFReadL(block, 1, sizeof(block), fp)) > 0 )
-                msIO_fwrite( block, 1, bytes_read, stdout );
+      if( mimetype == NULL )
+        mimetype = "application/octet-stream";
+      if(multipart) {
+        msIO_fprintf( stdout, "\r\n--wcs\r\n" );
+        msIO_fprintf(
+          stdout,
+          "Content-Type: %s\r\n"
+          "Content-Description: coverage data\r\n"
+          "Content-Transfer-Encoding: binary\r\n"
+          "Content-ID: coverage/%s\r\n"
+          "Content-Disposition: INLINE; filename=%s\r\n\r\n",
+          mimetype,
+          all_files[i],
+          all_files[i]);
+      } else {
+        msIO_setHeader("Content-Type",mimetype);
+        msIO_setHeader("Content-Description","coverage data");
+        msIO_setHeader("Content-Transfer-Encoding","binary");
+        msIO_setHeader("Content-ID","coverage/%s",all_files[i]);
+        msIO_setHeader("Content-Disposition","INLINE; filename=%s",all_files[i]);
+        msIO_sendHeaders();
+      }
+
+
+      fp = VSIFOpenL(
+             CPLFormFilename(base_dir, all_files[i], NULL),
+             "rb" );
+      if( fp == NULL ) {
+        msReleaseLock( TLOCK_GDAL );
+        msSetError( MS_MISCERR,
+                    "Failed to open %s for streaming to stdout.",
+                    "msWCSWriteFile20()", all_files[i] );
+        return MS_FAILURE;
+      }
 
-            VSIFCloseL( fp );
+      while( (bytes_read = VSIFReadL(block, 1, sizeof(block), fp)) > 0 )
+        msIO_fwrite( block, 1, bytes_read, stdout );
 
-            VSIUnlink( all_files[i] );
-        }
+      VSIFCloseL( fp );
 
-        msFree(filename);
-        CSLDestroy( all_files );
-        msReleaseLock( TLOCK_GDAL );
-        if(multipart)
-            msIO_fprintf( stdout, "\n--wcs--%c%c", 10, 10 );
-        return MS_SUCCESS;
+      VSIUnlink( CPLFormFilename(base_dir, all_files[i], NULL) );
     }
-#endif /* def GDAL_DCAP_VIRTUALIO */
 
+    msFree(base_dir);
+    msFree(filename);
+    CSLDestroy( all_files );
+    msReleaseLock( TLOCK_GDAL );
+    if(multipart)
+      msIO_fprintf( stdout, "\r\n--wcs--\r\n" );
     return MS_SUCCESS;
+  }
+
+  return MS_SUCCESS;
 }
 
 /************************************************************************/
@@ -2164,24 +1827,22 @@ static int msWCSWriteFile20(mapObj* map, imageObj* image, wcs20ParamsObjPtr para
 /************************************************************************/
 
 static const char *msWCSLookupRangesetAxisMetadata20(hashTableObj *table,
-        const char *axis, const char *item)
+    const char *axis, const char *item)
 {
-    char buf[500], *value;
+  char buf[500], *value;
 
-    if(table == NULL || axis == NULL || item == NULL)
-    {
-        return NULL;
-    }
-
-    strlcpy(buf, axis, sizeof(buf));
-    strlcat(buf, "_", sizeof(buf));
-    strlcat(buf, item, sizeof(buf));
-    if((value = msLookupHashTable(table, buf)) != NULL)
-    {
-        return value;
-    }
-    return msOWSLookupMetadata(table, "CO", buf);
-}
+  if(table == NULL || axis == NULL || item == NULL) {
+    return NULL;
+  }
+
+  strlcpy(buf, axis, sizeof(buf));
+  strlcat(buf, "_", sizeof(buf));
+  strlcat(buf, item, sizeof(buf));
+  if((value = msLookupHashTable(table, buf)) != NULL) {
+    return value;
+  }
+  return msOWSLookupMetadata(table, "CO", buf);
+}
 
 /************************************************************************/
 /*                   msWCSGetCoverageMetadata20()                       */
@@ -2192,528 +1853,465 @@ static const char *msWCSLookupRangesetAxisMetadata20(hashTableObj *table,
 
 static int msWCSGetCoverageMetadata20(layerObj *layer, wcs20coverageMetadataObj *cm)
 {
-    char  *srs_uri = NULL;
-    int i = 0;
-    if ( msCheckParentPointer(layer->map,"map") == MS_FAILURE )
-        return MS_FAILURE;
+  char  *srs_uri = NULL;
+  int i = 0;
+  if ( msCheckParentPointer(layer->map,"map") == MS_FAILURE )
+    return MS_FAILURE;
 
-    if((cm->srs = msOWSGetEPSGProj(&(layer->projection),
-            &(layer->metadata), "CO", MS_TRUE)) == NULL)
-    {
-        if((cm->srs = msOWSGetEPSGProj(&(layer->map->projection),
-                &(layer->map->web.metadata), "CO", MS_TRUE)) == NULL)
-        {
-            msSetError(MS_WCSERR, "Unable to determine the SRS for this layer, "
-                    "no projection defined and no metadata available.",
-                    "msWCSGetCoverageMetadata20()");
-            return MS_FAILURE;
-        }
+  if((cm->srs = msOWSGetEPSGProj(&(layer->projection),
+                                 &(layer->metadata), "CO", MS_TRUE)) == NULL) {
+    if((cm->srs = msOWSGetEPSGProj(&(layer->map->projection),
+                                   &(layer->map->web.metadata), "CO", MS_TRUE)) == NULL) {
+      msSetError(MS_WCSERR, "Unable to determine the SRS for this layer, "
+                 "no projection defined and no metadata available.",
+                 "msWCSGetCoverageMetadata20()");
+      return MS_FAILURE;
+    }
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Get the SRS in uri format.                                      */
+  /* -------------------------------------------------------------------- */
+  if((srs_uri = msOWSGetProjURI(&(layer->projection), &(layer->metadata),
+                                "CO", MS_TRUE)) == NULL) {
+    srs_uri = msOWSGetProjURI(&(layer->map->projection),
+                              &(layer->map->web.metadata), "CO", MS_TRUE);
+  }
+
+  if( srs_uri != NULL ) {
+    if( strlen(srs_uri) > sizeof(cm->srs_uri) - 1 ) {
+      msSetError(MS_WCSERR, "SRS URI too long!",
+                 "msWCSGetCoverageMetadata()");
+      return MS_FAILURE;
+    }
+
+    strlcpy( cm->srs_uri, srs_uri, sizeof(cm->srs_uri) );
+    msFree( srs_uri );
+  } else {
+    cm->srs_uri[0] = '\0';
+  }
+
+  /* setup nilvalues */
+  cm->numnilvalues = 0;
+  cm->nilvalues = NULL;
+  cm->nilvalues_reasons = NULL;
+  cm->native_format = NULL;
+
+  /* -------------------------------------------------------------------- */
+  /*      If we have "virtual dataset" metadata on the layer, then use    */
+  /*      that in preference to inspecting the file(s).                   */
+  /*      We require extent and either size or resolution.                */
+  /* -------------------------------------------------------------------- */
+  if( msOWSLookupMetadata(&(layer->metadata), "CO", "extent") != NULL
+      && (msOWSLookupMetadata(&(layer->metadata), "CO", "resolution") != NULL
+          || msOWSLookupMetadata(&(layer->metadata), "CO", "size") != NULL) ) {
+    const char *value;
+
+    /* get extent */
+    cm->extent.minx = 0.0;
+    cm->extent.maxx = 0.0;
+    cm->extent.miny = 0.0;
+    cm->extent.maxy = 0.0;
+    if( msOWSGetLayerExtent( layer->map, layer, "CO", &cm->extent ) == MS_FAILURE )
+      return MS_FAILURE;
+
+    /* get resolution */
+    cm->xresolution = 0.0;
+    cm->yresolution = 0.0;
+    if( (value = msOWSLookupMetadata(&(layer->metadata), "CO", "resolution")) != NULL ) {
+      char **tokens;
+      int n;
+
+      tokens = msStringSplit(value, ' ', &n);
+      if( tokens == NULL || n != 2 ) {
+        msSetError( MS_WCSERR, "Wrong number of arguments for wcs|ows_resolution metadata.", "msWCSGetCoverageMetadata20()");
+        msFreeCharArray( tokens, n );
+        return MS_FAILURE;
+      }
+      cm->xresolution = atof(tokens[0]);
+      cm->yresolution = atof(tokens[1]);
+      msFreeCharArray( tokens, n );
+    }
+
+    /* get Size (in pixels and lines) */
+    cm->xsize = 0;
+    cm->ysize = 0;
+    if( (value=msOWSLookupMetadata(&(layer->metadata), "CO", "size")) != NULL ) {
+      char **tokens;
+      int n;
+
+      tokens = msStringSplit(value, ' ', &n);
+      if( tokens == NULL || n != 2 ) {
+        msSetError( MS_WCSERR, "Wrong number of arguments for wcs|ows_size metadata.", "msWCSGetCoverageMetadata20()");
+        msFreeCharArray( tokens, n );
+        return MS_FAILURE;
+      }
+      cm->xsize = atoi(tokens[0]);
+      cm->ysize = atoi(tokens[1]);
+      msFreeCharArray( tokens, n );
     }
 
-    /* -------------------------------------------------------------------- */
-    /*      Get the SRS in uri format.                                      */
-    /* -------------------------------------------------------------------- */
-    if((srs_uri = msOWSGetProjURI(&(layer->projection), &(layer->metadata),
-        "CO", MS_TRUE)) == NULL)
-    {
-        srs_uri = msOWSGetProjURI(&(layer->map->projection),
-                &(layer->map->web.metadata), "CO", MS_TRUE);
+    /* try to compute raster size */
+    if( cm->xsize == 0 && cm->ysize == 0 && cm->xresolution != 0.0 && cm->yresolution != 0.0 && cm->extent.minx != cm->extent.maxx && cm->extent.miny != cm->extent.maxy ) {
+      cm->xsize = (int) ((cm->extent.maxx - cm->extent.minx) / cm->xresolution + 0.5);
+      cm->ysize = (int) fabs((cm->extent.maxy - cm->extent.miny) / cm->yresolution + 0.5);
     }
 
-    if( srs_uri != NULL )
-    {
-        if( strlen(srs_uri) > sizeof(cm->srs_uri) - 1 )
-        {
-            msSetError(MS_WCSERR, "SRS URI too long!",
-                    "msWCSGetCoverageMetadata()");
-            return MS_FAILURE;
-        }
+    /* try to compute raster resolution */
+    if( (cm->xresolution == 0.0 || cm->yresolution == 0.0) && cm->xsize != 0 && cm->ysize != 0 ) {
+      cm->xresolution = (cm->extent.maxx - cm->extent.minx) / cm->xsize;
+      cm->yresolution = (cm->extent.maxy - cm->extent.miny) / cm->ysize;
+    }
 
-        strlcpy( cm->srs_uri, srs_uri, sizeof(cm->srs_uri) );
-        msFree( srs_uri );
+    /* do we have information to do anything */
+    if( cm->xresolution == 0.0 || cm->yresolution == 0.0 || cm->xsize == 0 || cm->ysize == 0 ) {
+      msSetError( MS_WCSERR, "Failed to collect extent and resolution for WCS coverage from metadata for layer '%s'.  Need value wcs|ows_resolution or wcs|ows_size values.", "msWCSGetCoverageMetadata20()", layer->name );
+      return MS_FAILURE;
     }
-    else
-    {
-        cm->srs_uri[0] = '\0';
+
+    /* compute geotransform */
+    cm->geotransform[0] = cm->extent.minx;
+    cm->geotransform[1] = cm->xresolution;
+    cm->geotransform[2] = 0.0;
+    cm->geotransform[3] = cm->extent.maxy;
+    cm->geotransform[4] = 0.0;
+    cm->geotransform[5] = -fabs(cm->yresolution);
+
+    /* get bands count, or assume 1 if not found */
+    cm->numbands = 1;
+    if( (value = msOWSLookupMetadata(&(layer->metadata), "CO", "bandcount")) != NULL) {
+      int numbands = 0;
+      msStringParseInteger(value, &numbands);
+      cm->numbands = (size_t)numbands;
     }
 
-    /* setup nilvalues */
-    cm->numnilvalues = 0;
-    cm->nilvalues = NULL;
-    cm->nilvalues_reasons = NULL;
-    cm->native_format = NULL;
+    cm->bands = msSmallCalloc(sizeof(wcs20rasterbandMetadataObj), cm->numbands);
 
-    /* -------------------------------------------------------------------- */
-    /*      If we have "virtual dataset" metadata on the layer, then use    */
-    /*      that in preference to inspecting the file(s).                   */
-    /*      We require extent and either size or resolution.                */
-    /* -------------------------------------------------------------------- */
-    if( msOWSLookupMetadata(&(layer->metadata), "CO", "extent") != NULL
-        && (msOWSLookupMetadata(&(layer->metadata), "CO", "resolution") != NULL
-        || msOWSLookupMetadata(&(layer->metadata), "CO", "size") != NULL) )
-    {
-        const char *value;
-
-        /* get extent */
-        cm->extent.minx = 0.0;
-        cm->extent.maxx = 0.0;
-        cm->extent.miny = 0.0;
-        cm->extent.maxy = 0.0;
-        if( msOWSGetLayerExtent( layer->map, layer, "CO", &cm->extent ) == MS_FAILURE )
+    /* get bands type, or assume float if not found */
+    cm->imagemode = MS_IMAGEMODE_FLOAT32;
+    if( (value = msOWSLookupMetadata(&(layer->metadata), "CO", "imagemode")) != NULL ) {
+      if( EQUAL(value,"INT16") )
+        cm->imagemode = MS_IMAGEMODE_INT16;
+      else if( EQUAL(value,"FLOAT32") )
+        cm->imagemode = MS_IMAGEMODE_FLOAT32;
+      else if( EQUAL(value,"BYTE") )
+        cm->imagemode = MS_IMAGEMODE_BYTE;
+      else {
+        msSetError( MS_WCSERR, "Content of wcs|ows_imagemode (%s) not recognised.  Should be one of BYTE, INT16 or FLOAT32.", "msWCSGetCoverageMetadata20()", value );
         return MS_FAILURE;
+      }
+    }
 
-        /* get resolution */
-        cm->xresolution = 0.0;
-        cm->yresolution = 0.0;
-        if( (value = msOWSLookupMetadata(&(layer->metadata), "CO", "resolution")) != NULL )
-        {
-            char **tokens;
-            int n;
-
-            tokens = msStringSplit(value, ' ', &n);
-            if( tokens == NULL || n != 2 )
-            {
-                msSetError( MS_WCSERR, "Wrong number of arguments for wcs|ows_resolution metadata.", "msWCSGetCoverageMetadata20()");
-                msFreeCharArray( tokens, n );
-                return MS_FAILURE;
-            }
-            cm->xresolution = atof(tokens[0]);
-            cm->yresolution = atof(tokens[1]);
-            msFreeCharArray( tokens, n );
-        }
-
-        /* get Size (in pixels and lines) */
-        cm->xsize = 0;
-        cm->ysize = 0;
-        if( (value=msOWSLookupMetadata(&(layer->metadata), "CO", "size")) != NULL )
-        {
-            char **tokens;
-            int n;
-
-            tokens = msStringSplit(value, ' ', &n);
-            if( tokens == NULL || n != 2 )
-            {
-                msSetError( MS_WCSERR, "Wrong number of arguments for wcs|ows_size metadata.", "msWCSGetCoverageMetadata20()");
-                msFreeCharArray( tokens, n );
-                return MS_FAILURE;
-            }
-            cm->xsize = atoi(tokens[0]);
-            cm->ysize = atoi(tokens[1]);
-            msFreeCharArray( tokens, n );
-        }
+    if( (value = msOWSLookupMetadata(&(layer->metadata), "CO", "native_format")) != NULL ) {
+      cm->native_format = msStrdup(value);
+    }
 
-        /* try to compute raster size */
-        if( cm->xsize == 0 && cm->ysize == 0 && cm->xresolution != 0.0 && cm->yresolution != 0.0 && cm->extent.minx != cm->extent.maxx && cm->extent.miny != cm->extent.maxy )
-        {
-            cm->xsize = (int) ((cm->extent.maxx - cm->extent.minx) / cm->xresolution + 0.5);
-            cm->ysize = (int) fabs((cm->extent.maxy - cm->extent.miny) / cm->yresolution + 0.5);
-        }
+    /* determine nilvalues and reasons */
+    {
+      int n_nilvalues = 0, n_nilvalues_reasons = 0;
+      char **t_nilvalues = NULL, **t_nilvalues_reasons = NULL;
+      if( (value = msOWSLookupMetadata(&(layer->metadata), "CO", "nilvalues")) != NULL ) {
+        t_nilvalues = msStringSplit(value, ' ', &n_nilvalues);
+      } else if((value = msOWSLookupMetadata(&(layer->metadata), "CO", "rangeset_nullvalue")) != NULL) {
+        t_nilvalues = msStringSplit(value, ' ', &n_nilvalues);
+      }
 
-        /* try to compute raster resolution */
-        if( (cm->xresolution == 0.0 || cm->yresolution == 0.0) && cm->xsize != 0 && cm->ysize != 0 )
-        {
-            cm->xresolution = (cm->extent.maxx - cm->extent.minx) / cm->xsize;
-            cm->yresolution = (cm->extent.maxy - cm->extent.miny) / cm->ysize;
-        }
+      if( (value = msOWSLookupMetadata(&(layer->metadata), "CO", "nilvalues_reasons")) != NULL ) {
+        t_nilvalues_reasons = msStringSplit(value, ' ', &n_nilvalues_reasons);
+      }
 
-        /* do we have information to do anything */
-        if( cm->xresolution == 0.0 || cm->yresolution == 0.0 || cm->xsize == 0 || cm->ysize == 0 )
-        {
-            msSetError( MS_WCSERR, "Failed to collect extent and resolution for WCS coverage from metadata for layer '%s'.  Need value wcs|ows_resolution or wcs|ows_size values.", "msWCSGetCoverageMetadata20()", layer->name );
+      if(n_nilvalues > 0) {
+        int i;
+        cm->numnilvalues = n_nilvalues;
+        cm->nilvalues = msSmallCalloc(sizeof(char*), n_nilvalues);
+        cm->nilvalues_reasons = msSmallCalloc(sizeof(char*), n_nilvalues);
+        for(i = 0; i < n_nilvalues; ++i) {
+          cm->nilvalues[i] = msStrdup(t_nilvalues[i]);
+          if(i < n_nilvalues_reasons) {
+            cm->nilvalues_reasons[i] = msStrdup(t_nilvalues_reasons[i]);
+          } else {
+            cm->nilvalues_reasons[i] = msStrdup("");
+          }
+        }
+      }
+      msFreeCharArray(t_nilvalues, n_nilvalues);
+      msFreeCharArray(t_nilvalues_reasons, n_nilvalues_reasons);
+    }
+
+    {
+      int num_band_names = 0, i, j;
+      char **band_names = NULL;
+
+      char *wcs11_band_names_key = "rangeset_axes";
+      char *wcs20_band_names_key = "band_names";
+
+      char *wcs11_interval_key = "interval";
+      char *wcs20_interval_key = "interval";
+      char *interval_key = NULL;
+
+      char *significant_figures_key = "significant_figures";
+
+      char *wcs11_keys[] =
+      { "label", "semantic", "values_type", "values_semantic", "description" };
+      char *wcs20_keys[] =
+      { "band_name", "band_interpretation", "band_uom", "band_definition", "band_description" };
+      char **keys = NULL;
+
+      char **interval_array;
+      int num_interval;
+
+      wcs20rasterbandMetadataObj default_values;
+
+      /* Decide whether WCS1.1 or WCS2.0 keys should be used */
+      if( (value = msOWSLookupMetadata(&(layer->metadata), "CO", wcs20_band_names_key) ) != NULL ) {
+        keys = wcs20_keys;
+        interval_key = wcs20_interval_key;
+        band_names = msStringSplit(value, ' ', &num_band_names);
+      } else if( (value = msOWSLookupMetadata(&(layer->metadata), "CO", wcs11_band_names_key)) != NULL ) {
+        keys = wcs11_keys;
+        interval_key = wcs11_interval_key;
+        band_names = msStringSplit(value, ' ', &num_band_names);
+      }
+
+      /* return with error when number of bands does not match    */
+      /* the number of names                                      */
+      if (num_band_names != cm->numbands && num_band_names != 0) {
+        msFreeCharArray(band_names, num_band_names);
+        msSetError( MS_WCSERR,
+                    "Wrong number of band names given in layer '%s'. "
+                    "Expected %d, got %d.", "msWCSGetCoverageMetadata20()",
+                    layer->name, cm->numbands, num_band_names );
+        return MS_FAILURE;
+      }
+
+      /* look up default metadata values */
+      for(j = 1; j < 5; ++j) {
+        if(keys != NULL) {
+          default_values.values[j] = (char *)msOWSLookupMetadata(&(layer->metadata), "CO", keys[j]);
+        }
+      }
+
+      /* set default values for interval and significant figures */
+      switch(cm->imagemode) {
+        case MS_IMAGEMODE_BYTE:
+        case MS_IMAGEMODE_PC256:
+          default_values.interval_min = 0.;
+          default_values.interval_max = 255.;
+          default_values.significant_figures = 3;
+          break;
+        case MS_IMAGEMODE_INT16:
+          default_values.interval_min = 0.;
+          default_values.interval_max = (double)USHRT_MAX;
+          default_values.significant_figures = 5;
+          break;
+        case MS_IMAGEMODE_FLOAT32:
+          default_values.interval_min = -FLT_MAX;
+          default_values.interval_max = FLT_MAX;
+          default_values.significant_figures = 12;
+          break;
+      }
+
+      /* lookup default interval values */
+      if (interval_key != NULL
+          && (value = msOWSLookupMetadata(&(layer->metadata), "CO", interval_key)) != NULL) {
+        interval_array = msStringSplit(value, ' ', &num_interval);
+
+        if (num_interval != 2
+            || msStringParseDouble(interval_array[0], &(default_values.interval_min)) != MS_SUCCESS
+            || msStringParseDouble(interval_array[1], &(default_values.interval_max)) != MS_SUCCESS) {
+          msFreeCharArray(band_names, num_band_names);
+          msFreeCharArray(interval_array, num_interval);
+          msSetError(MS_WCSERR, "Wrong interval format for default axis.",
+                     "msWCSGetCoverageMetadata20()");
+          return MS_FAILURE;
+        }
+        msFreeCharArray(interval_array, num_interval);
+      }
+
+      /* lookup default value for significant figures */
+      if((value = msOWSLookupMetadata(&(layer->metadata), "CO", significant_figures_key)) != NULL) {
+        if(msStringParseInteger(value, &(default_values.significant_figures)) != MS_SUCCESS) {
+          msFreeCharArray(band_names, num_band_names);
+          msSetError(MS_WCSERR, "Wrong significant figures format "
+                     "for default axis.",
+                     "msWCSGetCoverageMetadata20()");
+          return MS_FAILURE;
+        }
+      }
+
+      /* iterate over every band */
+      for(i = 0; i < cm->numbands; ++i) {
+        cm->bands[i].name = NULL;
+
+        /* look up band metadata or copy defaults */
+        if(num_band_names != 0) {
+          cm->bands[i].name = msStrdup(band_names[i]);
+          for(j = 1; j < 5; ++j) {
+            value = (char *)msWCSLookupRangesetAxisMetadata20(&(layer->metadata),
+                    cm->bands[i].name, keys[j]);
+            if(value != NULL) {
+              cm->bands[i].values[j] = msStrdup(value);
+            } else if(default_values.values[j] != NULL) {
+              cm->bands[i].values[j] = msStrdup(default_values.values[j]);
+            }
+          }
+        }
+
+        /* set up interval */
+        value = (char *)msWCSLookupRangesetAxisMetadata20(&(layer->metadata),
+                cm->bands[i].name, interval_key);
+        if(value != NULL) {
+          num_interval = 0;
+          interval_array = msStringSplit(value, ' ', &num_interval);
+
+          if (num_interval != 2
+              || msStringParseDouble(interval_array[0], &(cm->bands[i].interval_min)) != MS_SUCCESS
+              || msStringParseDouble(interval_array[1], &(cm->bands[i].interval_max)) != MS_SUCCESS) {
+            msFreeCharArray(band_names, num_band_names);
+            msFreeCharArray(interval_array, num_interval);
+            msSetError(MS_WCSERR, "Wrong interval format for axis %s.",
+                       "msWCSGetCoverageMetadata20()", cm->bands[i].name);
             return MS_FAILURE;
-        }
-
-        /* compute geotransform */
-        cm->geotransform[0] = cm->extent.minx;
-        cm->geotransform[1] = cm->xresolution;
-        cm->geotransform[2] = 0.0;
-        cm->geotransform[3] = cm->extent.maxy;
-        cm->geotransform[4] = 0.0;
-        cm->geotransform[5] = -fabs(cm->yresolution);
-
-        /* get bands count, or assume 1 if not found */
-        cm->numbands = 1;
-        if( (value = msOWSLookupMetadata(&(layer->metadata), "CO", "bandcount")) != NULL)
-        {
-            int numbands = 0;
-            msStringParseInteger(value, &numbands);
-            cm->numbands = (size_t)numbands;
-        }
-
-        cm->bands = msSmallCalloc(sizeof(wcs20rasterbandMetadataObj), cm->numbands);
-
-        /* get bands type, or assume float if not found */
-        cm->imagemode = MS_IMAGEMODE_FLOAT32;
-        if( (value = msOWSLookupMetadata(&(layer->metadata), "CO", "imagemode")) != NULL )
-        {
-            if( EQUAL(value,"INT16") )
-                cm->imagemode = MS_IMAGEMODE_INT16;
-            else if( EQUAL(value,"FLOAT32") )
-                cm->imagemode = MS_IMAGEMODE_FLOAT32;
-            else if( EQUAL(value,"BYTE") )
-                cm->imagemode = MS_IMAGEMODE_BYTE;
-            else
-            {
-                msSetError( MS_WCSERR, "Content of wcs|ows_imagemode (%s) not recognised.  Should be one of BYTE, INT16 or FLOAT32.", "msWCSGetCoverageMetadata20()", value );
-                return MS_FAILURE;
-            }
-        }
-
-        if( (value = msOWSLookupMetadata(&(layer->metadata), "CO", "native_format")) != NULL )
-        {
-            cm->native_format = msStrdup(value);
-        }
-
-        /* determine nilvalues and reasons */
-        {
-            int n_nilvalues = 0, n_nilvalues_reasons = 0;
-            char **t_nilvalues = NULL, **t_nilvalues_reasons = NULL;
-            if( (value = msOWSLookupMetadata(&(layer->metadata), "CO", "nilvalues")) != NULL )
-            {
-                t_nilvalues = msStringSplit(value, ' ', &n_nilvalues);
-            }
-            else if((value = msOWSLookupMetadata(&(layer->metadata), "CO", "rangeset_nullvalue")) != NULL)
-            {
-                t_nilvalues = msStringSplit(value, ' ', &n_nilvalues);
-            }
+          }
 
-            if( (value = msOWSLookupMetadata(&(layer->metadata), "CO", "nilvalues_reasons")) != NULL )
-            {
-                t_nilvalues_reasons = msStringSplit(value, ' ', &n_nilvalues_reasons);
-            }
-
-            if(n_nilvalues > 0)
-            {
-                int i;
-                cm->numnilvalues = n_nilvalues;
-                cm->nilvalues = msSmallCalloc(sizeof(char*), n_nilvalues);
-                cm->nilvalues_reasons = msSmallCalloc(sizeof(char*), n_nilvalues);
-                for(i = 0; i < n_nilvalues; ++i)
-                {
-                    cm->nilvalues[i] = msStrdup(t_nilvalues[i]);
-                    if(i < n_nilvalues_reasons)
-                    {
-                        cm->nilvalues_reasons[i] = msStrdup(t_nilvalues_reasons[i]);
-                    }
-                    else
-                    {
-                        cm->nilvalues_reasons[i] = msStrdup("");
-                    }
-                }
-            }
-            msFreeCharArray(t_nilvalues, n_nilvalues);
-            msFreeCharArray(t_nilvalues_reasons, n_nilvalues_reasons);
+          msFreeCharArray(interval_array, num_interval);
+        } else {
+          cm->bands[i].interval_min = default_values.interval_min;
+          cm->bands[i].interval_max = default_values.interval_max;
         }
 
-        {
-            int num_band_names = 0, i, j;
-            char **band_names = NULL;
-
-            char *wcs11_band_names_key = "rangeset_axes";
-            char *wcs20_band_names_key = "band_names";
-
-            char *wcs11_interval_key = "interval";
-            char *wcs20_interval_key = "interval";
-            char *interval_key = NULL;
-
-            char *significant_figures_key = "significant_figures";
-
-            char *wcs11_keys[] =
-            { "label", "semantic", "values_type", "values_semantic", "description" };
-            char *wcs20_keys[] =
-            { "band_name", "band_interpretation", "band_uom", "band_definition", "band_description" };
-            char **keys = NULL;
-
-            char **interval_array;
-            int num_interval;
-
-            wcs20rasterbandMetadataObj default_values;
-
-            /* Decide whether WCS1.1 or WCS2.0 keys should be used */
-            if( (value = msOWSLookupMetadata(&(layer->metadata), "CO", wcs20_band_names_key) ) != NULL )
-            {
-                keys = wcs20_keys;
-                interval_key = wcs20_interval_key;
-                band_names = msStringSplit(value, ' ', &num_band_names);
-            }
-            else if( (value = msOWSLookupMetadata(&(layer->metadata), "CO", wcs11_band_names_key)) != NULL )
-            {
-                keys = wcs11_keys;
-                interval_key = wcs11_interval_key;
-                band_names = msStringSplit(value, ' ', &num_band_names);
-            }
-
-            /* return with error when number of bands does not match    */
-            /* the number of names                                      */
-            if (num_band_names != cm->numbands && num_band_names != 0)
-            {
-                msFreeCharArray(band_names, num_band_names);
-                msSetError( MS_WCSERR,
-                        "Wrong number of band names given in layer '%s'. "
-                        "Expected %d, got %d.", "msWCSGetCoverageMetadata20()",
-                        layer->name, cm->numbands, num_band_names );
-                return MS_FAILURE;
-            }
-
-            /* look up default metadata values */
-            for(j = 1; j < 5; ++j)
-            {
-                if(keys != NULL)
-                {
-                    default_values.values[j] = (char *)msOWSLookupMetadata(&(layer->metadata), "CO", keys[j]);
-                }
-            }
-            
-            /* set default values for interval and significant figures */
-            switch(cm->imagemode)
-            {
-            case MS_IMAGEMODE_BYTE:
-            case MS_IMAGEMODE_PC256:
-                default_values.interval_min = 0.;
-                default_values.interval_max = 255.;
-                default_values.significant_figures = 3;
-                break;
-            case MS_IMAGEMODE_INT16:
-                default_values.interval_min = 0.;
-                default_values.interval_max = (double)USHRT_MAX;
-                default_values.significant_figures = 5;
-                break;
-            case MS_IMAGEMODE_FLOAT32:
-                default_values.interval_min = -FLT_MAX;
-                default_values.interval_max = FLT_MAX;
-                default_values.significant_figures = 12;
-                break;
-            }
-
-            /* lookup default interval values */
-            if (interval_key != NULL
-                && (value = msOWSLookupMetadata(&(layer->metadata), "CO", interval_key)) != NULL)
-            {
-                interval_array = msStringSplit(value, ' ', &num_interval);
-
-                if (num_interval != 2
-                    || msStringParseDouble(interval_array[0], &(default_values.interval_min)) != MS_SUCCESS
-                    || msStringParseDouble(interval_array[1], &(default_values.interval_max)) != MS_SUCCESS)
-                {
-                    msFreeCharArray(band_names, num_band_names);
-                    msFreeCharArray(interval_array, num_interval);
-                    msSetError(MS_WCSERR, "Wrong interval format for default axis.",
-                            "msWCSGetCoverageMetadata20()");
-                    return MS_FAILURE;
-                }
-                msFreeCharArray(interval_array, num_interval);
-            }
-
-            /* lookup default value for significant figures */
-            if((value = msOWSLookupMetadata(&(layer->metadata), "CO", significant_figures_key)) != NULL)
-            {
-                if(msStringParseInteger(value, &(default_values.significant_figures)) != MS_SUCCESS)
-                {
-                    msFreeCharArray(band_names, num_band_names);
-                    msSetError(MS_WCSERR, "Wrong significant figures format "
-                            "for default axis.",
-                            "msWCSGetCoverageMetadata20()");
-                    return MS_FAILURE;
-                }
-            }
-
-            /* iterate over every band */
-            for(i = 0; i < cm->numbands; ++i)
-            {
-                cm->bands[i].name = NULL;
-                
-                /* look up band metadata or copy defaults */
-                if(num_band_names != 0)
-                {
-                    cm->bands[i].name = msStrdup(band_names[i]);
-                    for(j = 1; j < 5; ++j)
-                    {
-                        value = (char *)msWCSLookupRangesetAxisMetadata20(&(layer->metadata),
-                                cm->bands[i].name, keys[j]);
-                        if(value != NULL)
-                        {
-                            cm->bands[i].values[j] = msStrdup(value);
-                        }
-                        else if(default_values.values[j] != NULL)
-                        {
-                            cm->bands[i].values[j] = msStrdup(default_values.values[j]);
-                        }
-                    }
-                }
-
-                /* set up interval */
-                value = (char *)msWCSLookupRangesetAxisMetadata20(&(layer->metadata),
-                        cm->bands[i].name, interval_key);
-                if(value != NULL)
-                {
-                    num_interval = 0;
-                    interval_array = msStringSplit(value, ' ', &num_interval);
-
-                    if (num_interval != 2
-                        || msStringParseDouble(interval_array[0], &(cm->bands[i].interval_min)) != MS_SUCCESS
-                        || msStringParseDouble(interval_array[1], &(cm->bands[i].interval_max)) != MS_SUCCESS)
-                    {
-                        msFreeCharArray(band_names, num_band_names);
-                        msFreeCharArray(interval_array, num_interval);
-                        msSetError(MS_WCSERR, "Wrong interval format for axis %s.",
-                                "msWCSGetCoverageMetadata20()", cm->bands[i].name);
-                        return MS_FAILURE;
-                    }
-
-                    msFreeCharArray(interval_array, num_interval);
-                }
-                else
-                {
-                    cm->bands[i].interval_min = default_values.interval_min;
-                    cm->bands[i].interval_max = default_values.interval_max;
-                }
-
-                /* set up significant figures */
-                value = (char *)msWCSLookupRangesetAxisMetadata20(&(layer->metadata),
-                        cm->bands[i].name, significant_figures_key);
-                if(value != NULL)
-                {
-                    if(msStringParseInteger(value, &(cm->bands[i].significant_figures)) != MS_SUCCESS)
-                    {
-                        msFreeCharArray(band_names, num_band_names);
-                        msSetError(MS_WCSERR, "Wrong significant figures format "
-                                "for axis %s.",
-                                "msWCSGetCoverageMetadata20()", cm->bands[i].name);
-                        return MS_FAILURE;
-                    }
-                }
-                else
-                {
-                    cm->bands[i].significant_figures = default_values.significant_figures;
-                }
-            }
-
+        /* set up significant figures */
+        value = (char *)msWCSLookupRangesetAxisMetadata20(&(layer->metadata),
+                cm->bands[i].name, significant_figures_key);
+        if(value != NULL) {
+          if(msStringParseInteger(value, &(cm->bands[i].significant_figures)) != MS_SUCCESS) {
             msFreeCharArray(band_names, num_band_names);
-        }
-    }
-    else if( layer->data == NULL )
-    { /* no virtual metadata, not ok unless we're talking 1 image, hopefully we can fix that */
-        msSetError( MS_WCSERR, "RASTER Layer with no DATA statement and no WCS virtual dataset metadata.  Tileindexed raster layers not supported for WCS without virtual dataset metadata (cm->extent, wcs_res, wcs_size).", "msWCSGetCoverageMetadata20()" );
-        return MS_FAILURE;
-    }
-    else
-    {   /* work from the file (e.g. DATA) */
-        GDALDatasetH hDS;
-        GDALDriverH hDriver;
-        GDALRasterBandH hBand;
-        const char szPath[MS_MAXPATHLEN];
-        const char *driver_short_name, *driver_long_name;
-
-        msGDALInitialize();
-
-        msTryBuildPath3((char *)szPath,  layer->map->mappath, layer->map->shapepath, layer->data);
-        msAcquireLock( TLOCK_GDAL );
-        hDS = GDALOpen( szPath, GA_ReadOnly );
-        if( hDS == NULL )
-        {
-            msReleaseLock( TLOCK_GDAL );
-            msSetError( MS_IOERR, "%s", "msWCSGetCoverageMetadata20()", CPLGetLastErrorMsg() );
+            msSetError(MS_WCSERR, "Wrong significant figures format "
+                       "for axis %s.",
+                       "msWCSGetCoverageMetadata20()", cm->bands[i].name);
             return MS_FAILURE;
+          }
+        } else {
+          cm->bands[i].significant_figures = default_values.significant_figures;
         }
+      }
 
-        msGetGDALGeoTransform( hDS, layer->map, layer, cm->geotransform );
-
-        cm->xsize = GDALGetRasterXSize( hDS );
-        cm->ysize = GDALGetRasterYSize( hDS );
-
-        cm->extent.minx = cm->geotransform[0];
-        cm->extent.maxx = cm->geotransform[0] + cm->geotransform[1] * cm->xsize + cm->geotransform[2] * cm->ysize;
-        cm->extent.miny = cm->geotransform[3] + cm->geotransform[4] * cm->xsize + cm->geotransform[5] * cm->ysize;
-        cm->extent.maxy = cm->geotransform[3];
-
-        cm->xresolution = cm->geotransform[1];
-        cm->yresolution = cm->geotransform[5];
+      msFreeCharArray(band_names, num_band_names);
+    }
+  } else if( layer->data == NULL ) {
+    /* no virtual metadata, not ok unless we're talking 1 image, hopefully we can fix that */
+    msSetError( MS_WCSERR, "RASTER Layer with no DATA statement and no WCS virtual dataset metadata.  Tileindexed raster layers not supported for WCS without virtual dataset metadata (cm->extent, wcs_res, wcs_size).", "msWCSGetCoverageMetadata20()" );
+    return MS_FAILURE;
+  } else {
+    /* work from the file (e.g. DATA) */
+    GDALDatasetH hDS;
+    GDALDriverH hDriver;
+    GDALRasterBandH hBand;
+    const char szPath[MS_MAXPATHLEN];
+    const char *driver_short_name, *driver_long_name;
 
-        cm->numbands = GDALGetRasterCount( hDS );
+    msGDALInitialize();
 
-        /* TODO nilvalues? */
+    msTryBuildPath3((char *)szPath,  layer->map->mappath, layer->map->shapepath, layer->data);
+    msAcquireLock( TLOCK_GDAL );
+    hDS = GDALOpen( szPath, GA_ReadOnly );
+    if( hDS == NULL ) {
+      msReleaseLock( TLOCK_GDAL );
+      msSetError( MS_IOERR, "%s", "msWCSGetCoverageMetadata20()", CPLGetLastErrorMsg() );
+      return MS_FAILURE;
+    }
 
-        if( cm->numbands == 0 )
-        {
-            msReleaseLock( TLOCK_GDAL );
-            msSetError( MS_WCSERR, "Raster file %s has no raster bands.  This cannot be used in a layer.", "msWCSGetCoverageMetadata20()", layer->data );
-            return MS_FAILURE;
-        }
+    msGetGDALGeoTransform( hDS, layer->map, layer, cm->geotransform );
 
-        hBand = GDALGetRasterBand( hDS, 1 );
-        switch( GDALGetRasterDataType( hBand ) )
-        {
-        case GDT_Byte:
-            cm->imagemode = MS_IMAGEMODE_BYTE;
-            break;
-        case GDT_Int16:
-            cm->imagemode = MS_IMAGEMODE_INT16;
-            break;
-        default:
-            cm->imagemode = MS_IMAGEMODE_FLOAT32;
-            break;
-        }
+    cm->xsize = GDALGetRasterXSize( hDS );
+    cm->ysize = GDALGetRasterYSize( hDS );
 
-        cm->bands = msSmallCalloc(sizeof(wcs20rasterbandMetadataObj), cm->numbands);
+    cm->extent.minx = cm->geotransform[0];
+    cm->extent.maxx = cm->geotransform[0] + cm->geotransform[1] * cm->xsize + cm->geotransform[2] * cm->ysize;
+    cm->extent.miny = cm->geotransform[3] + cm->geotransform[4] * cm->xsize + cm->geotransform[5] * cm->ysize;
+    cm->extent.maxy = cm->geotransform[3];
 
-        /* get as much band metadata as possible */
-        for(i = 0; i < cm->numbands; ++i)
-        {
-            char bandname[32];
-            GDALColorInterp colorInterp;
-            hBand = GDALGetRasterBand(hDS, i + 1);
-            snprintf(bandname, sizeof(bandname), "band%d", i+1);
-            cm->bands[i].name = msStrdup(bandname);
-            colorInterp = GDALGetRasterColorInterpretation(hBand);
-            cm->bands[i].interpretation = msStrdup(GDALGetColorInterpretationName(colorInterp));
-            cm->bands[i].uom = msStrdup(GDALGetRasterUnitType(hBand));
-            if(strlen(cm->bands[i].uom) == 0)
-            {
-                msFree(cm->bands[i].uom);
-                cm->bands[i].uom = NULL;
-            }
+    cm->xresolution = cm->geotransform[1];
+    cm->yresolution = cm->geotransform[5];
 
-            /* set up interval and significant figures */
-            switch(cm->imagemode)
-            {
-            case MS_IMAGEMODE_BYTE:
-            case MS_IMAGEMODE_PC256:
-                cm->bands[i].interval_min = 0.;
-                cm->bands[i].interval_max = 255.;
-                cm->bands[i].significant_figures = 3;
-                break;
-            case MS_IMAGEMODE_INT16:
-                cm->bands[i].interval_min = 0.;
-                cm->bands[i].interval_max = (double)USHRT_MAX;
-                cm->bands[i].significant_figures = 5;
-                break;
-            case MS_IMAGEMODE_FLOAT32:
-                cm->bands[i].interval_min = -FLT_MAX;
-                cm->bands[i].interval_max = FLT_MAX;
-                cm->bands[i].significant_figures = 12;
-                break;
-            }
-        }
+    cm->numbands = GDALGetRasterCount( hDS );
 
-        hDriver = GDALGetDatasetDriver(hDS);
-        driver_short_name = GDALGetDriverShortName(hDriver);
-        driver_long_name = GDALGetDriverLongName(hDriver);
-        /* TODO: improve this, exchange strstr() */
-        for(i = 0; i < layer->map->numoutputformats; ++i)
-        {
-            if(strstr( layer->map->outputformatlist[i]->driver, driver_short_name) != NULL
-               || strstr(layer->map->outputformatlist[i]->driver, driver_long_name) != NULL)
-            {
-                cm->native_format = msStrdup(layer->map->outputformatlist[i]->mimetype);
-                break;
-            }
-        }
+    /* TODO nilvalues? */
 
-        GDALClose( hDS );
-        msReleaseLock( TLOCK_GDAL );
+    if( cm->numbands == 0 ) {
+      msReleaseLock( TLOCK_GDAL );
+      msSetError( MS_WCSERR, "Raster file %s has no raster bands.  This cannot be used in a layer.", "msWCSGetCoverageMetadata20()", layer->data );
+      return MS_FAILURE;
     }
 
-    return MS_SUCCESS;
+    hBand = GDALGetRasterBand( hDS, 1 );
+    switch( GDALGetRasterDataType( hBand ) ) {
+      case GDT_Byte:
+        cm->imagemode = MS_IMAGEMODE_BYTE;
+        break;
+      case GDT_Int16:
+        cm->imagemode = MS_IMAGEMODE_INT16;
+        break;
+      default:
+        cm->imagemode = MS_IMAGEMODE_FLOAT32;
+        break;
+    }
+
+    cm->bands = msSmallCalloc(sizeof(wcs20rasterbandMetadataObj), cm->numbands);
+
+    /* get as much band metadata as possible */
+    for(i = 0; i < cm->numbands; ++i) {
+      char bandname[32];
+      GDALColorInterp colorInterp;
+      hBand = GDALGetRasterBand(hDS, i + 1);
+      snprintf(bandname, sizeof(bandname), "band%d", i+1);
+      cm->bands[i].name = msStrdup(bandname);
+      colorInterp = GDALGetRasterColorInterpretation(hBand);
+      cm->bands[i].interpretation = msStrdup(GDALGetColorInterpretationName(colorInterp));
+      cm->bands[i].uom = msStrdup(GDALGetRasterUnitType(hBand));
+      if(strlen(cm->bands[i].uom) == 0) {
+        msFree(cm->bands[i].uom);
+        cm->bands[i].uom = NULL;
+      }
+
+      /* set up interval and significant figures */
+      switch(cm->imagemode) {
+        case MS_IMAGEMODE_BYTE:
+        case MS_IMAGEMODE_PC256:
+          cm->bands[i].interval_min = 0.;
+          cm->bands[i].interval_max = 255.;
+          cm->bands[i].significant_figures = 3;
+          break;
+        case MS_IMAGEMODE_INT16:
+          cm->bands[i].interval_min = 0.;
+          cm->bands[i].interval_max = (double)USHRT_MAX;
+          cm->bands[i].significant_figures = 5;
+          break;
+        case MS_IMAGEMODE_FLOAT32:
+          cm->bands[i].interval_min = -FLT_MAX;
+          cm->bands[i].interval_max = FLT_MAX;
+          cm->bands[i].significant_figures = 12;
+          break;
+      }
+    }
+
+    hDriver = GDALGetDatasetDriver(hDS);
+    driver_short_name = GDALGetDriverShortName(hDriver);
+    driver_long_name = GDALGetDriverLongName(hDriver);
+    /* TODO: improve this, exchange strstr() */
+    for(i = 0; i < layer->map->numoutputformats; ++i) {
+      if(strstr( layer->map->outputformatlist[i]->driver, driver_short_name) != NULL
+          || strstr(layer->map->outputformatlist[i]->driver, driver_long_name) != NULL) {
+        cm->native_format = msStrdup(layer->map->outputformatlist[i]->mimetype);
+        break;
+      }
+    }
+
+    GDALClose( hDS );
+    msReleaseLock( TLOCK_GDAL );
+  }
+
+  return MS_SUCCESS;
 }
 
 /************************************************************************/
@@ -2725,25 +2323,22 @@ static int msWCSGetCoverageMetadata20(layerObj *layer, wcs20coverageMetadataObj
 
 static int msWCSClearCoverageMetadata20(wcs20coverageMetadataObj *cm)
 {
-    int i = 0, j = 0;
-    msFree(cm->native_format);
-    for(i = 0; i < cm->numnilvalues; ++i)
-    {
-        msFree(cm->nilvalues[i]);
-        msFree(cm->nilvalues_reasons[i]);
-    }
-    msFree(cm->nilvalues);
-    msFree(cm->nilvalues_reasons);
-
-    for(i = 0; i < cm->numbands; ++i)
-    {
-        for(j = 0; j < 5; ++j)
-        {
-            msFree(cm->bands[i].values[j]);
-        }
-    }
-    msFree(cm->bands);
-    return MS_SUCCESS;
+  int i = 0, j = 0;
+  msFree(cm->native_format);
+  for(i = 0; i < cm->numnilvalues; ++i) {
+    msFree(cm->nilvalues[i]);
+    msFree(cm->nilvalues_reasons[i]);
+  }
+  msFree(cm->nilvalues);
+  msFree(cm->nilvalues_reasons);
+
+  for(i = 0; i < cm->numbands; ++i) {
+    for(j = 0; j < 5; ++j) {
+      msFree(cm->bands[i].values[j]);
+    }
+  }
+  msFree(cm->bands);
+  return MS_SUCCESS;
 }
 
 /************************************************************************/
@@ -2755,155 +2350,151 @@ static int msWCSClearCoverageMetadata20(wcs20coverageMetadataObj *cm)
 int msWCSException20(mapObj *map, const char *exceptionCode,
                      const char *locator, const char *version)
 {
-    int size = 0;
-    char *errorString = NULL;
-    char *errorMessage = NULL;
-    char *schemasLocation = NULL;
-    const char * encoding;
-    char *xsi_schemaLocation = NULL;
-    char version_string[OWS_VERSION_MAXLEN];
-
-    xmlDocPtr psDoc = NULL;
-    xmlNodePtr psRootNode = NULL;
-    xmlNodePtr psMainNode = NULL;
-    xmlNodePtr psNode = NULL;
-    xmlNsPtr psNsOws = NULL;
-    xmlNsPtr psNsXsi = NULL;
-    xmlChar *buffer = NULL;
-
-    encoding = msOWSLookupMetadata(&(map->web.metadata), "CO", "encoding");
-    errorString = msGetErrorString("\n");
-    errorMessage = msEncodeHTMLEntities(errorString);
-    schemasLocation = msEncodeHTMLEntities(msOWSGetSchemasLocation(map));
-
-    psDoc = xmlNewDoc(BAD_CAST "1.0");
-
-    psRootNode = xmlNewNode(NULL, BAD_CAST "ExceptionReport");
-    psNsOws = xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_OWS_20_NAMESPACE_URI,
-                BAD_CAST MS_OWSCOMMON_OWS_NAMESPACE_PREFIX);
-    xmlSetNs(psRootNode, psNsOws);
-
-    psNsXsi = xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_W3C_XSI_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_W3C_XSI_NAMESPACE_PREFIX);
-
-    /* add attributes to root element */
-    xmlNewProp(psRootNode, BAD_CAST "version", BAD_CAST version);
-    xmlNewProp(psRootNode, BAD_CAST "xml:lang", BAD_CAST msOWSGetLanguage(map, "exception"));
-
-    /* get 2 digits version string: '2.0' */
-    msOWSGetVersionString(OWS_2_0_0, version_string);
-    version_string[3]= '\0';
-
-    xsi_schemaLocation = msStrdup((char *)psNsOws->href);
-    xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, " ");
-    xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, (char *)schemasLocation);
-    xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, "/ows/");
-    xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, version_string);
-    xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, "/owsExceptionReport.xsd");
-
-    /* add namespace'd attributes to root element */
-    xmlNewNsProp(psRootNode, psNsXsi, BAD_CAST "schemaLocation", BAD_CAST xsi_schemaLocation);
-
-    /* add child element */
-    psMainNode = xmlNewChild(psRootNode, NULL, BAD_CAST "Exception", NULL);
-
-    /* add attributes to child */
-    xmlNewProp(psMainNode, BAD_CAST "exceptionCode", BAD_CAST exceptionCode);
-
-    if (locator != NULL)
-    {
-        xmlNewProp(psMainNode, BAD_CAST "locator", BAD_CAST locator);
-    }
-
-    if (errorMessage != NULL)
-    {
-        psNode = xmlNewChild(psMainNode, NULL, BAD_CAST "ExceptionText", BAD_CAST errorMessage);
-    }
-
-    /*psRootNode = msOWSCommonExceptionReport(psNsOws, OWS_2_0_0,
-            schemasLocation, version, msOWSGetLanguage(map, "exception"),
-            exceptionCode, locator, errorMessage);*/
-
-    xmlDocSetRootElement(psDoc, psRootNode);
-
-    if (encoding)
-        msIO_printf("Content-type: text/xml; charset=%s%c%c", encoding, 10, 10);
-    else
-        msIO_printf("Content-type: text/xml%c%c", 10, 10);
-
-    xmlDocDumpFormatMemoryEnc(psDoc, &buffer, &size, (encoding ? encoding
-            : "ISO-8859-1"), 1);
-
-    msIO_printf("%s", buffer);
-
-    //free buffer and the document
-    free(errorString);
-    free(errorMessage);
-    free(schemasLocation);
-    free(xsi_schemaLocation);
-    xmlFree(buffer);
-    xmlFreeDoc(psDoc);
-
-    /* clear error since we have already reported it */
-    msResetErrorList();
-    return MS_FAILURE;
+  int size = 0;
+  char *errorString = NULL;
+  char *errorMessage = NULL;
+  char *schemasLocation = NULL;
+  const char * encoding;
+  char *xsi_schemaLocation = NULL;
+  char version_string[OWS_VERSION_MAXLEN];
+
+  xmlDocPtr psDoc = NULL;
+  xmlNodePtr psRootNode = NULL;
+  xmlNodePtr psMainNode = NULL;
+  xmlNsPtr psNsOws = NULL;
+  xmlNsPtr psNsXsi = NULL;
+  xmlChar *buffer = NULL;
+
+  encoding = msOWSLookupMetadata(&(map->web.metadata), "CO", "encoding");
+  errorString = msGetErrorString("\n");
+  errorMessage = msEncodeHTMLEntities(errorString);
+  schemasLocation = msEncodeHTMLEntities(msOWSGetSchemasLocation(map));
+
+  psDoc = xmlNewDoc(BAD_CAST "1.0");
+
+  psRootNode = xmlNewNode(NULL, BAD_CAST "ExceptionReport");
+  psNsOws = xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_OWS_20_NAMESPACE_URI,
+                     BAD_CAST MS_OWSCOMMON_OWS_NAMESPACE_PREFIX);
+  xmlSetNs(psRootNode, psNsOws);
+
+  psNsXsi = xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_W3C_XSI_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_W3C_XSI_NAMESPACE_PREFIX);
+
+  /* add attributes to root element */
+  xmlNewProp(psRootNode, BAD_CAST "version", BAD_CAST version);
+  xmlNewProp(psRootNode, BAD_CAST "xml:lang", BAD_CAST msOWSGetLanguage(map, "exception"));
+
+  /* get 2 digits version string: '2.0' */
+  msOWSGetVersionString(OWS_2_0_0, version_string);
+  version_string[3]= '\0';
+
+  xsi_schemaLocation = msStrdup((char *)psNsOws->href);
+  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, " ");
+  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, (char *)schemasLocation);
+  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, "/ows/");
+  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, version_string);
+  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, "/owsExceptionReport.xsd");
+
+  /* add namespace'd attributes to root element */
+  xmlNewNsProp(psRootNode, psNsXsi, BAD_CAST "schemaLocation", BAD_CAST xsi_schemaLocation);
+
+  /* add child element */
+  psMainNode = xmlNewChild(psRootNode, NULL, BAD_CAST "Exception", NULL);
+
+  /* add attributes to child */
+  xmlNewProp(psMainNode, BAD_CAST "exceptionCode", BAD_CAST exceptionCode);
+
+  if (locator != NULL) {
+    xmlNewProp(psMainNode, BAD_CAST "locator", BAD_CAST locator);
+  }
+
+  if (errorMessage != NULL) {
+    xmlNewChild(psMainNode, NULL, BAD_CAST "ExceptionText", BAD_CAST errorMessage);
+  }
+
+  /*psRootNode = msOWSCommonExceptionReport(psNsOws, OWS_2_0_0,
+          schemasLocation, version, msOWSGetLanguage(map, "exception"),
+          exceptionCode, locator, errorMessage);*/
+
+  xmlDocSetRootElement(psDoc, psRootNode);
+
+  if (encoding)
+    msIO_setHeader("Content-Type","text/xml; charset=%s", encoding);
+  else
+    msIO_setHeader("Content-Type","text/xml");
+  msIO_sendHeaders();
+
+  xmlDocDumpFormatMemoryEnc(psDoc, &buffer, &size, (encoding ? encoding
+                            : "ISO-8859-1"), 1);
+
+  msIO_printf("%s", buffer);
+
+  /* free buffer and the document */
+  free(errorString);
+  free(errorMessage);
+  free(schemasLocation);
+  free(xsi_schemaLocation);
+  xmlFree(buffer);
+  xmlFreeDoc(psDoc);
+
+  /* clear error since we have already reported it */
+  msResetErrorList();
+  return MS_FAILURE;
 }
 
 #define MAX_MIMES 20
 
 static int msWCSGetCapabilities20_CreateProfiles(
-        mapObj *map, xmlNodePtr psServiceIdentification, xmlNsPtr psOwsNs)
+  mapObj *map, xmlNodePtr psServiceIdentification, xmlNsPtr psOwsNs)
 {
-    xmlNodePtr psProfile, psTmpNode;
-    char *available_mime_types[MAX_MIMES];
-    int i = 0;
-
-    /* even indices are urls, uneven are mime-types, or null*/
-    char *urls_and_mime_types[] =
-    {
-        MS_WCS_20_PROFILE_CORE,     NULL,
-        MS_WCS_20_PROFILE_KVP,      NULL,
-        MS_WCS_20_PROFILE_POST,     NULL,
-        MS_WCS_20_PROFILE_CRS,     NULL,
-        MS_WCS_20_PROFILE_IMAGECRS, NULL,
-        MS_WCS_20_PROFILE_GEOTIFF,  "image/tiff",
-        MS_WCS_20_PROFILE_GML_GEOTIFF, NULL,
-        MS_WCS_20_PROFILE_SCALING, NULL,
-        MS_WCS_20_PROFILE_RANGESUBSET, NULL,
-        NULL, NULL /* guardian */
-    };
-
-    /* navigate to node where profiles shall be inserted */
-    for(psTmpNode = psServiceIdentification->children; psTmpNode->next != NULL; psTmpNode = psTmpNode->next)
-    {
-        if(EQUAL((char *)psTmpNode->name, "ServiceTypeVersion"))
-            break;
-    }
-
-    /* get list of all available mime types */
-    msGetOutputFormatMimeList(map, available_mime_types, MAX_MIMES);
-
-    while(urls_and_mime_types[i] != NULL)
-    {
-        char *mime_type;
-        mime_type = urls_and_mime_types[i+1];
-
-        /* check if there is a mime type */
-        if(mime_type != NULL)
-        {
-            /* check if the mime_type is in the list of outputformats */
-            if(CSLPartialFindString(available_mime_types, mime_type) == -1)
-                continue;
-        }
-
-        /* create a new node and attach it in the tree */
-        psProfile = xmlNewNode(psOwsNs, BAD_CAST "Profile");
-        xmlNodeSetContent(psProfile, BAD_CAST urls_and_mime_types[i]);
-        xmlAddNextSibling(psTmpNode, psProfile);
-
-        psTmpNode = psProfile;
-        i += 2;
-    }
-    return MS_SUCCESS;
+  xmlNodePtr psProfile, psTmpNode;
+  char *available_mime_types[MAX_MIMES];
+  int i = 0;
+
+  /* even indices are urls, uneven are mime-types, or null*/
+  char *urls_and_mime_types[] = {
+    MS_WCS_20_PROFILE_CORE,     NULL,
+    MS_WCS_20_PROFILE_KVP,      NULL,
+    MS_WCS_20_PROFILE_POST,     NULL,
+    MS_WCS_20_PROFILE_GML,      NULL,
+    MS_WCS_20_PROFILE_GML_MULTIPART, NULL,
+    MS_WCS_20_PROFILE_GML_SPECIAL, NULL,
+    MS_WCS_20_PROFILE_GML_GEOTIFF, "image/tiff",
+    MS_WCS_20_PROFILE_GEOTIFF,  "image/tiff",
+    MS_WCS_20_PROFILE_CRS,     NULL,
+    MS_WCS_20_PROFILE_SCALING, NULL,
+    MS_WCS_20_PROFILE_RANGESUBSET, NULL,
+    NULL, NULL /* guardian */
+  };
+
+  /* navigate to node where profiles shall be inserted */
+  for(psTmpNode = psServiceIdentification->children; psTmpNode->next != NULL; psTmpNode = psTmpNode->next) {
+    if(EQUAL((char *)psTmpNode->name, "ServiceTypeVersion"))
+      break;
+  }
+
+  /* get list of all available mime types */
+  msGetOutputFormatMimeList(map, available_mime_types, MAX_MIMES);
+
+  while(urls_and_mime_types[i] != NULL) {
+    char *mime_type;
+    mime_type = urls_and_mime_types[i+1];
+
+    /* check if there is a mime type */
+    if(mime_type != NULL) {
+      /* check if the mime_type is in the list of outputformats */
+      if(CSLPartialFindString(available_mime_types, mime_type) == -1)
+        continue;
+    }
+
+    /* create a new node and attach it in the tree */
+    psProfile = xmlNewNode(psOwsNs, BAD_CAST "Profile");
+    xmlNodeSetContent(psProfile, BAD_CAST urls_and_mime_types[i]);
+    xmlAddNextSibling(psTmpNode, psProfile);
+
+    psTmpNode = psProfile;
+    i += 2;
+  }
+  return MS_SUCCESS;
 }
 
 /************************************************************************/
@@ -2914,48 +2505,45 @@ static int msWCSGetCapabilities20_CreateProfiles(
 /************************************************************************/
 
 static int msWCSGetCapabilities20_CoverageSummary(
-    mapObj *map, wcs20ParamsObjPtr params,
-    xmlDocPtr doc, xmlNodePtr psContents, layerObj *layer )
+  mapObj *map, wcs20ParamsObjPtr params,
+  xmlDocPtr doc, xmlNodePtr psContents, layerObj *layer )
 {
-    wcs20coverageMetadataObj cm;
-    int status;
-    xmlNodePtr psCSummary, psMetadata;
-    const char *metadatalink_href = msOWSLookupMetadata(&(layer->metadata), "CO", "metadatalink_href");
+  wcs20coverageMetadataObj cm;
+  int status;
+  xmlNodePtr psCSummary, psMetadata;
+  const char *metadatalink_href = msOWSLookupMetadata(&(layer->metadata), "CO", "metadatalink_href");
 
 
-    xmlNsPtr psWcsNs = xmlSearchNs( doc, xmlDocGetRootElement(doc), BAD_CAST "wcs" );
-    xmlNsPtr psOwsNs = xmlSearchNs( doc, xmlDocGetRootElement(doc), BAD_CAST "ows" );
-    xmlNsPtr psXlinkNs = xmlSearchNs( doc, xmlDocGetRootElement(doc), BAD_CAST "xlink" );
+  xmlNsPtr psWcsNs = xmlSearchNs( doc, xmlDocGetRootElement(doc), BAD_CAST "wcs" );
+  xmlNsPtr psOwsNs = xmlSearchNs( doc, xmlDocGetRootElement(doc), BAD_CAST "ows" );
+  xmlNsPtr psXlinkNs = xmlSearchNs( doc, xmlDocGetRootElement(doc), BAD_CAST "xlink" );
 
-    status = msWCSGetCoverageMetadata20(layer, &cm);
-    if(status != MS_SUCCESS) return MS_FAILURE;
+  status = msWCSGetCoverageMetadata20(layer, &cm);
+  if(status != MS_SUCCESS) return MS_FAILURE;
 
-    psCSummary = xmlNewChild( psContents, psWcsNs, BAD_CAST "CoverageSummary", NULL );
-    xmlNewChild(psCSummary, psWcsNs, BAD_CAST "CoverageId", BAD_CAST layer->name);
-    xmlNewChild(psCSummary, psWcsNs, BAD_CAST "CoverageSubtype", BAD_CAST "RectifiedGridCoverage");
+  psCSummary = xmlNewChild( psContents, psWcsNs, BAD_CAST "CoverageSummary", NULL );
+  xmlNewChild(psCSummary, psWcsNs, BAD_CAST "CoverageId", BAD_CAST layer->name);
+  xmlNewChild(psCSummary, psWcsNs, BAD_CAST "CoverageSubtype", BAD_CAST "RectifiedGridCoverage");
 
-    /* Add references to additional coverage metadata */
-    if (metadatalink_href != NULL)
-    {
-        const char *metadatalink_type = msOWSLookupMetadata(&(layer->metadata), "CO", "metadatalink_type");
-        const char *metadatalink_format = msOWSLookupMetadata(&(layer->metadata), "CO", "metadatalink_format");
+  /* Add references to additional coverage metadata */
+  if (metadatalink_href != NULL) {
+    const char *metadatalink_type = msOWSLookupMetadata(&(layer->metadata), "CO", "metadatalink_type");
+    const char *metadatalink_format = msOWSLookupMetadata(&(layer->metadata), "CO", "metadatalink_format");
 
-        psMetadata = xmlNewChild(psCSummary, psOwsNs, BAD_CAST "Metadata", NULL);
-        xmlNewNsProp(psMetadata, psXlinkNs, BAD_CAST "type", BAD_CAST "simple");
-        xmlNewNsProp(psMetadata, psXlinkNs, BAD_CAST "href", BAD_CAST metadatalink_href);
-        if (metadatalink_type != NULL)
-        {
-            xmlNewProp(psMetadata, BAD_CAST "about", BAD_CAST metadatalink_type);
-        }
-        if (metadatalink_format != NULL)
-        {
-            xmlNewNsProp(psMetadata, psXlinkNs, BAD_CAST "role", BAD_CAST metadatalink_format);
-        }
+    psMetadata = xmlNewChild(psCSummary, psOwsNs, BAD_CAST "Metadata", NULL);
+    xmlNewNsProp(psMetadata, psXlinkNs, BAD_CAST "type", BAD_CAST "simple");
+    xmlNewNsProp(psMetadata, psXlinkNs, BAD_CAST "href", BAD_CAST metadatalink_href);
+    if (metadatalink_type != NULL) {
+      xmlNewProp(psMetadata, BAD_CAST "about", BAD_CAST metadatalink_type);
+    }
+    if (metadatalink_format != NULL) {
+      xmlNewNsProp(psMetadata, psXlinkNs, BAD_CAST "role", BAD_CAST metadatalink_format);
     }
+  }
 
-    msWCSClearCoverageMetadata20(&cm);
+  msWCSClearCoverageMetadata20(&cm);
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 /************************************************************************/
@@ -2969,183 +2557,185 @@ static int msWCSGetCapabilities20_CoverageSummary(
 int msWCSGetCapabilities20(mapObj *map, cgiRequestObj *req,
                            wcs20ParamsObjPtr params, owsRequestObj *ows_request)
 {
-    xmlDocPtr psDoc = NULL;       /* document pointer */
-    xmlNodePtr psRootNode,
-            psOperationsNode,
-            psNode;
-    const char *updatesequence = NULL;
-    xmlNsPtr psOwsNs = NULL,
-            psXLinkNs = NULL,
-            psWcsNs = NULL,
-            psGmlNs = NULL;
-    char *script_url=NULL, *script_url_encoded=NULL;
-    int i;
-
-    /* -------------------------------------------------------------------- */
-    /*      Create document.                                                */
-    /* -------------------------------------------------------------------- */
-    psDoc = xmlNewDoc(BAD_CAST "1.0");
-
-    psRootNode = xmlNewNode(NULL, BAD_CAST "Capabilities");
-
-    xmlDocSetRootElement(psDoc, psRootNode);
-
-    /* -------------------------------------------------------------------- */
-    /*      Name spaces                                                     */
-    /* -------------------------------------------------------------------- */
-
-    msWCSPrepareNamespaces20(psDoc, psRootNode, map);
-
-    /* lookup namespaces */
-    psOwsNs = xmlSearchNs( psDoc, psRootNode, BAD_CAST MS_OWSCOMMON_OWS_NAMESPACE_PREFIX );
-    psWcsNs = xmlSearchNs( psDoc, psRootNode, BAD_CAST MS_OWSCOMMON_WCS_NAMESPACE_PREFIX );
-    psGmlNs = xmlSearchNs( psDoc, psRootNode, BAD_CAST MS_OWSCOMMON_GML_NAMESPACE_PREFIX );
-    psXLinkNs = xmlSearchNs( psDoc, psRootNode, BAD_CAST "xlink" );
-
-    xmlSetNs(psRootNode, psWcsNs);
-
-    xmlNewProp(psRootNode, BAD_CAST "version", BAD_CAST params->version );
-
-    updatesequence = msOWSLookupMetadata(&(map->web.metadata), "CO", "updatesequence");
-    if (params->updatesequence != NULL)
-    {
-        i = msOWSNegotiateUpdateSequence(params->updatesequence, updatesequence);
-        if (i == 0) /* current */
-        {
-            msSetError(MS_WCSERR, "UPDATESEQUENCE parameter (%s) is equal to server (%s)",
-                    "msWCSGetCapabilities20()", params->updatesequence, updatesequence);
-            return msWCSException(map, "updatesequence",
-                    "CurrentUpdateSequence", params->version);
-        }
-        if (i > 0) /* invalid */
-        {
-            msSetError(MS_WCSERR, "UPDATESEQUENCE parameter (%s) is higher than server (%s)",
-                    "msWCSGetCapabilities20()", params->updatesequence, updatesequence);
-            return msWCSException(map, "updatesequence",
-                    "InvalidUpdateSequence", params->version);
-        }
-    }
-    if(updatesequence != NULL)
-    {
-        xmlNewProp(psRootNode, BAD_CAST "updateSequence", BAD_CAST updatesequence);
-    }
+  xmlDocPtr psDoc = NULL;       /* document pointer */
+  xmlNodePtr psRootNode,
+             psOperationsNode,
+             psNode;
+  const char *updatesequence = NULL;
+  xmlNsPtr psOwsNs = NULL,
+           psXLinkNs = NULL,
+           psWcsNs = NULL;
+  char *script_url=NULL, *script_url_encoded=NULL, *format_list=NULL;
+  int i;
+
+  /* -------------------------------------------------------------------- */
+  /*      Create document.                                                */
+  /* -------------------------------------------------------------------- */
+  psDoc = xmlNewDoc(BAD_CAST "1.0");
+
+  psRootNode = xmlNewNode(NULL, BAD_CAST "Capabilities");
+
+  xmlDocSetRootElement(psDoc, psRootNode);
+
+  /* -------------------------------------------------------------------- */
+  /*      Name spaces                                                     */
+  /* -------------------------------------------------------------------- */
+
+  msWCSPrepareNamespaces20(psDoc, psRootNode, map);
+
+  /* lookup namespaces */
+  psOwsNs = xmlSearchNs( psDoc, psRootNode, BAD_CAST MS_OWSCOMMON_OWS_NAMESPACE_PREFIX );
+  psWcsNs = xmlSearchNs( psDoc, psRootNode, BAD_CAST MS_OWSCOMMON_WCS_NAMESPACE_PREFIX );
+  xmlSearchNs( psDoc, psRootNode, BAD_CAST MS_OWSCOMMON_GML_NAMESPACE_PREFIX );
+  psXLinkNs = xmlSearchNs( psDoc, psRootNode, BAD_CAST "xlink" );
+
+  xmlSetNs(psRootNode, psWcsNs);
+
+  xmlNewProp(psRootNode, BAD_CAST "version", BAD_CAST params->version );
+
+  updatesequence = msOWSLookupMetadata(&(map->web.metadata), "CO", "updatesequence");
+  if (params->updatesequence != NULL) {
+    i = msOWSNegotiateUpdateSequence(params->updatesequence, updatesequence);
+    if (i == 0) { /* current */
+      msSetError(MS_WCSERR, "UPDATESEQUENCE parameter (%s) is equal to server (%s)",
+                 "msWCSGetCapabilities20()", params->updatesequence, updatesequence);
+      xmlFreeDoc(psDoc);
+      return msWCSException(map, "updatesequence",
+                            "CurrentUpdateSequence", params->version);
+    }
+    if (i > 0) { /* invalid */
+      msSetError(MS_WCSERR, "UPDATESEQUENCE parameter (%s) is higher than server (%s)",
+                 "msWCSGetCapabilities20()", params->updatesequence, updatesequence);
+      xmlFreeDoc(psDoc);
+      return msWCSException(map, "updatesequence",
+                            "InvalidUpdateSequence", params->version);
+    }
+  }
+  if(updatesequence != NULL) {
+    xmlNewProp(psRootNode, BAD_CAST "updateSequence", BAD_CAST updatesequence);
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Service identification.                                         */
+  /* -------------------------------------------------------------------- */
+  if ( MS_WCS_20_CAPABILITIES_INCLUDE_SECTION(params, "ServiceIdentification") ) {
+    psNode = xmlAddChild(psRootNode, msOWSCommonServiceIdentification(
+                           psOwsNs, map, "OGC WCS", params->version, "CO"));
+    msWCSGetCapabilities20_CreateProfiles(map, psNode, psOwsNs);
+  }
+
+  /* Service Provider */
+  if ( MS_WCS_20_CAPABILITIES_INCLUDE_SECTION(params, "ServiceProvider") ) {
+    xmlAddChild(psRootNode,
+                msOWSCommonServiceProvider(psOwsNs, psXLinkNs, map, "CO"));
+  }
 
-    /* -------------------------------------------------------------------- */
-    /*      Service identification.                                         */
-    /* -------------------------------------------------------------------- */
-    if ( MS_WCS_20_CAPABILITIES_INCLUDE_SECTION(params, "ServiceIdentification") )
-    {
-        psNode = xmlAddChild(psRootNode, msOWSCommonServiceIdentification(
-                                    psOwsNs, map, "OGC WCS", params->version, "CO"));
-        msWCSGetCapabilities20_CreateProfiles(map, psNode, psOwsNs);
+  /* -------------------------------------------------------------------- */
+  /*      Operations metadata.                                            */
+  /* -------------------------------------------------------------------- */
+  if ( MS_WCS_20_CAPABILITIES_INCLUDE_SECTION(params, "OperationsMetadata") ) {
+    if ((script_url = msOWSGetOnlineResource(map, "CO", "onlineresource", req)) == NULL
+        || (script_url_encoded = msEncodeHTMLEntities(script_url)) == NULL) {
+      xmlFreeDoc(psDoc);
+      msSetError(MS_WCSERR, "Server URL not found", "msWCSGetCapabilities20()");
+      return msWCSException(map, "mapserv", "NoApplicableCode", params->version);
     }
+    free(script_url);
 
-    /* Service Provider */
-    if ( MS_WCS_20_CAPABILITIES_INCLUDE_SECTION(params, "ServiceProvider") )
-    {
-        xmlAddChild(psRootNode,
-                msOWSCommonServiceProvider(psOwsNs, psXLinkNs, map, "CO"));
-    }
+    psOperationsNode = xmlAddChild(psRootNode,msOWSCommonOperationsMetadata(psOwsNs));
 
     /* -------------------------------------------------------------------- */
-    /*      Operations metadata.                                            */
+    /*      GetCapabilities - add Sections and AcceptVersions?              */
     /* -------------------------------------------------------------------- */
-    if ( MS_WCS_20_CAPABILITIES_INCLUDE_SECTION(params, "OperationsMetadata") )
-    {
-        if ((script_url = msOWSGetOnlineResource(map, "CO", "onlineresource", req)) == NULL
-            || (script_url_encoded = msEncodeHTMLEntities(script_url)) == NULL)
-        {
-            msSetError(MS_WCSERR, "Server URL not found", "msWCSGetCapabilities20()");
-            return msWCSException(map, "mapserv", "NoApplicableCode", params->version);
-        }
-        free(script_url);
-
-        psOperationsNode = xmlAddChild(psRootNode,msOWSCommonOperationsMetadata(psOwsNs));
-
-        /* -------------------------------------------------------------------- */
-        /*      GetCapabilities - add Sections and AcceptVersions?              */
-        /* -------------------------------------------------------------------- */
-        psNode = msOWSCommonOperationsMetadataOperation(
-            psOwsNs, psXLinkNs,
-            "GetCapabilities", OWS_METHOD_GETPOST, script_url_encoded);
-        
-        xmlAddChild(psNode->last->last->last,
-            msOWSCommonOperationsMetadataDomainType(OWS_2_0_0, psOwsNs, "Constraint",
-                                                    "PostEncoding", "XML"));
-        xmlAddChild(psOperationsNode, psNode);
-
-        /* -------------------------------------------------------------------- */
-        /*      DescribeCoverage                                                */
-        /* -------------------------------------------------------------------- */
-        if (msOWSRequestIsEnabled(map, NULL, "C", "DescribeCoverage", MS_TRUE)) 
-        {
-            psNode = msOWSCommonOperationsMetadataOperation(
-                psOwsNs, psXLinkNs,
-                "DescribeCoverage", OWS_METHOD_GETPOST, script_url_encoded);
-            xmlAddChild(psNode->last->last->last,
-                msOWSCommonOperationsMetadataDomainType(OWS_2_0_0, psOwsNs, "Constraint",
-                                                        "PostEncoding", "XML"));
-            xmlAddChild(psOperationsNode, psNode);
-        }
+    psNode = msOWSCommonOperationsMetadataOperation(
+               psOwsNs, psXLinkNs,
+               "GetCapabilities", OWS_METHOD_GETPOST, script_url_encoded);
 
-        /* -------------------------------------------------------------------- */
-        /*      GetCoverage                                                     */
-        /* -------------------------------------------------------------------- */
-        if (msOWSRequestIsEnabled(map, NULL, "C", "GetCoverage", MS_TRUE)) 
-        {
-            psNode = msOWSCommonOperationsMetadataOperation(
-                psOwsNs, psXLinkNs,
-                "GetCoverage", OWS_METHOD_GETPOST, script_url_encoded);
-            
-            xmlAddChild(psNode->last->last->last,
+    xmlAddChild(psNode->last->last->last,
                 msOWSCommonOperationsMetadataDomainType(OWS_2_0_0, psOwsNs, "Constraint",
-                                                        "PostEncoding", "XML"));
-            xmlAddChild(psOperationsNode, psNode);
-        }
-        msFree(script_url_encoded);
-    }
-
-    /* -------------------------------------------------------------------- */
-    /*      Service metadata.                                               */
-    /* -------------------------------------------------------------------- */
-    /* it is mandatory, but unused for now */
-    xmlAddChild(psRootNode, xmlNewNode(psWcsNs, BAD_CAST "ServiceMetadata"));
+                    "PostEncoding", "XML"));
+    xmlAddChild(psOperationsNode, psNode);
 
     /* -------------------------------------------------------------------- */
-    /*      Contents section.                                               */
+    /*      DescribeCoverage                                                */
     /* -------------------------------------------------------------------- */
-    if ( MS_WCS_20_CAPABILITIES_INCLUDE_SECTION(params, "Contents") )
-    {
-        psNode = xmlNewChild( psRootNode, psWcsNs, BAD_CAST "Contents", NULL );
-
-        for(i = 0; i < map->numlayers; ++i)
-        {
-            layerObj *layer = map->layers[i];
-            int       status;
-
-            if(!msWCSIsLayerSupported(layer))
-                continue;
-
-            if (!msIntegerInArray(layer->index, ows_request->enabled_layers, ows_request->numlayers))
-                continue;
-
-            status = msWCSGetCapabilities20_CoverageSummary(
-                map, params, psDoc, psNode, layer );
-            if(status != MS_SUCCESS)
-            {
-                xmlFreeDoc(psDoc);
-                xmlCleanupParser();
-                return msWCSException(map, "mapserv", "Internal", params->version);
-            }
-        }
+    if (msOWSRequestIsEnabled(map, NULL, "C", "DescribeCoverage", MS_FALSE)) {
+      psNode = msOWSCommonOperationsMetadataOperation(
+                 psOwsNs, psXLinkNs,
+                 "DescribeCoverage", OWS_METHOD_GETPOST, script_url_encoded);
+      xmlAddChild(psNode->last->last->last,
+                  msOWSCommonOperationsMetadataDomainType(OWS_2_0_0, psOwsNs, "Constraint",
+                      "PostEncoding", "XML"));
+      xmlAddChild(psOperationsNode, psNode);
     }
+
     /* -------------------------------------------------------------------- */
-    /*      Write out the document and clean up.                            */
+    /*      GetCoverage                                                     */
     /* -------------------------------------------------------------------- */
-    msWCSWriteDocument20(map, psDoc);
-    xmlFreeDoc(psDoc);
-    xmlCleanupParser();
-    return MS_SUCCESS;
+    if (msOWSRequestIsEnabled(map, NULL, "C", "GetCoverage", MS_FALSE)) {
+      psNode = msOWSCommonOperationsMetadataOperation(
+                 psOwsNs, psXLinkNs,
+                 "GetCoverage", OWS_METHOD_GETPOST, script_url_encoded);
+
+      xmlAddChild(psNode->last->last->last,
+                  msOWSCommonOperationsMetadataDomainType(OWS_2_0_0, psOwsNs, "Constraint",
+                      "PostEncoding", "XML"));
+      xmlAddChild(psOperationsNode, psNode);
+    }
+    msFree(script_url_encoded);
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Service metadata.                                               */
+  /* -------------------------------------------------------------------- */
+
+  if ( MS_WCS_20_CAPABILITIES_INCLUDE_SECTION(params, "ServiceMetadata") ) {
+    psNode = xmlNewChild(psRootNode, psWcsNs, BAD_CAST "ServiceMetadata", NULL);
+
+    /* Add formats list */
+    format_list = msWCSGetFormatsList20(map, NULL);
+    msLibXml2GenerateList(psNode, psWcsNs, "formatSupported", format_list, ',');
+    msFree(format_list);
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Contents section.                                               */
+  /* -------------------------------------------------------------------- */
+  if ( MS_WCS_20_CAPABILITIES_INCLUDE_SECTION(params, "Contents") ) {
+    psNode = xmlNewChild( psRootNode, psWcsNs, BAD_CAST "Contents", NULL );
+
+    if(ows_request->numlayers == 0) {
+      xmlAddChild(psNode,
+                  xmlNewComment(BAD_CAST("WARNING: No WCS layers are enabled. "
+                                         "Check wcs/ows_enable_request settings.")));
+    } else {
+      for(i = 0; i < map->numlayers; ++i) {
+        layerObj *layer = map->layers[i];
+        int       status;
+
+        if(!msWCSIsLayerSupported(layer))
+          continue;
+
+        if (!msIntegerInArray(layer->index, ows_request->enabled_layers, ows_request->numlayers))
+          continue;
+
+        status = msWCSGetCapabilities20_CoverageSummary(
+                   map, params, psDoc, psNode, layer );
+        if(status != MS_SUCCESS) {
+          xmlFreeDoc(psDoc);
+          xmlCleanupParser();
+          return msWCSException(map, "mapserv", "Internal", params->version);
+        }
+      }
+    }
+  }
+  /* -------------------------------------------------------------------- */
+  /*      Write out the document and clean up.                            */
+  /* -------------------------------------------------------------------- */
+  msWCSWriteDocument20(map, psDoc);
+  xmlFreeDoc(psDoc);
+  xmlCleanupParser();
+  return MS_SUCCESS;
 }
 
 /************************************************************************/
@@ -3158,142 +2748,141 @@ int msWCSGetCapabilities20(mapObj *map, cgiRequestObj *req,
 static int msWCSDescribeCoverage20_CoverageDescription(mapObj *map,
     layerObj *layer, wcs20ParamsObjPtr params, xmlDocPtr psDoc, xmlNodePtr psRootNode )
 {
-    int status, swapAxes;
-    wcs20coverageMetadataObj cm;
-    xmlNodePtr psCD;
-    xmlNsPtr psWcsNs, psGmlNs, psGmlcovNs, psSweNs, psXLinkNs;
-    psWcsNs = psGmlNs = psGmlcovNs = psSweNs = psXLinkNs = NULL;
-
-    psWcsNs    = xmlSearchNs(psDoc, xmlDocGetRootElement(psDoc), BAD_CAST MS_OWSCOMMON_WCS_NAMESPACE_PREFIX);
-    psGmlNs    = xmlSearchNs(psDoc, xmlDocGetRootElement(psDoc), BAD_CAST MS_OWSCOMMON_GML_NAMESPACE_PREFIX);
-    psGmlcovNs = xmlSearchNs(psDoc, xmlDocGetRootElement(psDoc), BAD_CAST MS_OWSCOMMON_GMLCOV_NAMESPACE_PREFIX);
-    psSweNs    = xmlSearchNs(psDoc, xmlDocGetRootElement(psDoc), BAD_CAST MS_OWSCOMMON_SWE_NAMESPACE_PREFIX);
-    psXLinkNs  = xmlSearchNs(psDoc, xmlDocGetRootElement(psDoc), BAD_CAST MS_OWSCOMMON_W3C_XLINK_NAMESPACE_PREFIX);
+  int status, swapAxes;
+  wcs20coverageMetadataObj cm;
+  xmlNodePtr psCD;
+  xmlNsPtr psWcsNs, psGmlNs, psGmlcovNs, psSweNs, psXLinkNs;
+  psWcsNs = psGmlNs = psGmlcovNs = psSweNs = psXLinkNs = NULL;
+
+  psWcsNs    = xmlSearchNs(psDoc, xmlDocGetRootElement(psDoc), BAD_CAST MS_OWSCOMMON_WCS_NAMESPACE_PREFIX);
+  psGmlNs    = xmlSearchNs(psDoc, xmlDocGetRootElement(psDoc), BAD_CAST MS_OWSCOMMON_GML_NAMESPACE_PREFIX);
+  psGmlcovNs = xmlSearchNs(psDoc, xmlDocGetRootElement(psDoc), BAD_CAST MS_OWSCOMMON_GMLCOV_NAMESPACE_PREFIX);
+  psSweNs    = xmlSearchNs(psDoc, xmlDocGetRootElement(psDoc), BAD_CAST MS_OWSCOMMON_SWE_NAMESPACE_PREFIX);
+  psXLinkNs  = xmlSearchNs(psDoc, xmlDocGetRootElement(psDoc), BAD_CAST MS_OWSCOMMON_W3C_XLINK_NAMESPACE_PREFIX);
+
+  /* -------------------------------------------------------------------- */
+  /*      Verify layer is processable.                                    */
+  /* -------------------------------------------------------------------- */
+  if( msCheckParentPointer(layer->map,"map") == MS_FAILURE )
+    return MS_FAILURE;
 
-    /* -------------------------------------------------------------------- */
-    /*      Verify layer is processable.                                    */
-    /* -------------------------------------------------------------------- */
-    if( msCheckParentPointer(layer->map,"map") == MS_FAILURE )
-        return MS_FAILURE;
+  if(!msWCSIsLayerSupported(layer))
+    return MS_SUCCESS;
 
-    if(!msWCSIsLayerSupported(layer))
-        return MS_SUCCESS;
+  /* -------------------------------------------------------------------- */
+  /*      Setup coverage metadata.                                        */
+  /* -------------------------------------------------------------------- */
+  status = msWCSGetCoverageMetadata20(layer, &cm);
+  if(status != MS_SUCCESS)
+    return status;
 
-    /* -------------------------------------------------------------------- */
-    /*      Setup coverage metadata.                                        */
-    /* -------------------------------------------------------------------- */
-    status = msWCSGetCoverageMetadata20(layer, &cm);
-    if(status != MS_SUCCESS)
-        return status;
+  swapAxes = msWCSSwapAxes20(cm.srs_uri);
 
-    swapAxes = msWCSSwapAxes20(cm.srs_uri);
+  /* fill in bands rangeset info, if required. */
+  /* msWCSSetDefaultBandsRangeSetInfo( NULL, &cm, layer ); */
 
-    /* fill in bands rangeset info, if required. */
-    /* msWCSSetDefaultBandsRangeSetInfo( NULL, &cm, layer ); */
+  /* -------------------------------------------------------------------- */
+  /*      Create CoverageDescription node.                                */
+  /* -------------------------------------------------------------------- */
+  psCD = xmlNewChild( psRootNode, psWcsNs, BAD_CAST "CoverageDescription", NULL );
+  xmlNewNsProp(psCD, psGmlNs, BAD_CAST "id", BAD_CAST layer->name);
 
-    /* -------------------------------------------------------------------- */
-    /*      Create CoverageDescription node.                                */
-    /* -------------------------------------------------------------------- */
-    psCD = xmlNewChild( psRootNode, psWcsNs, BAD_CAST "CoverageDescription", NULL );
-    xmlNewNsProp(psCD, psGmlNs, BAD_CAST "id", BAD_CAST layer->name);
+  /* -------------------------------------------------------------------- */
+  /*      gml:boundedBy                                                   */
+  /* -------------------------------------------------------------------- */
+  msWCSCommon20_CreateBoundedBy(layer, &cm, psGmlNs, psCD, &(layer->projection), swapAxes);
 
-    /* -------------------------------------------------------------------- */
-    /*      gml:boundedBy                                                   */
-    /* -------------------------------------------------------------------- */
-    msWCSCommon20_CreateBoundedBy(layer, &cm, psGmlNs, psCD, &(layer->projection), swapAxes);
+  xmlNewChild(psCD, psWcsNs, BAD_CAST "CoverageId", BAD_CAST layer->name);
 
-    xmlNewChild(psCD, psWcsNs, BAD_CAST "CoverageId", BAD_CAST layer->name);
+  /* -------------------------------------------------------------------- */
+  /*      gml:domainSet                                                   */
+  /* -------------------------------------------------------------------- */
+  msWCSCommon20_CreateDomainSet(layer, &cm, psGmlNs, psCD, &(layer->projection), swapAxes);
 
-    /* -------------------------------------------------------------------- */
-    /*      gml:domainSet                                                   */
-    /* -------------------------------------------------------------------- */
-    msWCSCommon20_CreateDomainSet(layer, &cm, psGmlNs, psCD, &(layer->projection), swapAxes);
+  /* -------------------------------------------------------------------- */
+  /*      gmlcov:rangeType                                                */
+  /* -------------------------------------------------------------------- */
+  msWCSCommon20_CreateRangeType(layer, &cm, NULL, psGmlNs, psGmlcovNs, psSweNs, psXLinkNs, psCD);
+
+  /* -------------------------------------------------------------------- */
+  /*      wcs:ServiceParameters                                           */
+  /* -------------------------------------------------------------------- */
+  {
+    xmlNodePtr psSP;
+
+    psSP = xmlNewChild( psCD, psWcsNs, BAD_CAST "ServiceParameters", NULL);
+    xmlNewChild(psSP, psWcsNs, BAD_CAST "CoverageSubtype", BAD_CAST "RectifiedGridCoverage");
 
     /* -------------------------------------------------------------------- */
-    /*      gmlcov:rangeType                                                */
+    /*      SupportedCRS                                                    */
     /* -------------------------------------------------------------------- */
-    msWCSCommon20_CreateRangeType(layer, &cm, NULL, psGmlNs, psGmlcovNs, psSweNs, psXLinkNs, psCD);
+    /* for now, WCS 2.0 does not allow per coverage CRS definitions */
+    /*{
+      xmlNodePtr psSupportedCrss;
+      char *owned_value;
+
+      psSupportedCrss = xmlNewChild(psSP, psWcsNs,
+                                    BAD_CAST "SupportedCRSs", NULL);
+
+      if ((owned_value = msOWSGetProjURI(&(layer->projection),
+                                         &(layer->metadata), "CO", MS_FALSE)) != NULL)
+      { }
+      else if ((owned_value = msOWSGetProjURI(&(layer->map->projection),
+                                              &(layer->map->web.metadata), "CO", MS_FALSE)) != NULL)
+      { }
+      else {
+        msDebug("missing required information, no SRSs defined.\n");
+      }
+
+      if (owned_value != NULL && strlen(owned_value) > 0) {
+        msLibXml2GenerateList(psSupportedCrss, psWcsNs,
+                              "SupportedCRS", owned_value, ' ');
+      }
+
+      xmlNewChild(psSupportedCrss, psWcsNs,
+                  BAD_CAST "NativeCRS", BAD_CAST cm.srs_uri);
+
+      msFree(owned_value);
+    }*/
 
     /* -------------------------------------------------------------------- */
-    /*      wcs:ServiceParameters                                           */
+    /*      SupportedFormats                                                */
     /* -------------------------------------------------------------------- */
-    {
-        xmlNodePtr psSP;
+    /* for now, WCS 2.0 does not allow per coverage format definitions */
+    /*{
+      xmlNodePtr psSupportedFormats;
+      char *format_list;
 
-        psSP = xmlNewChild( psCD, psWcsNs, BAD_CAST "ServiceParameters", NULL);
-        xmlNewChild(psSP, psWcsNs, BAD_CAST "CoverageSubtype", BAD_CAST "RectifiedGridCoverage");
+      psSupportedFormats =
+      xmlNewChild(psSP, psWcsNs, BAD_CAST "SupportedFormats", NULL);
 
-        /* -------------------------------------------------------------------- */
-        /*      SupportedCRS                                                    */
-        /* -------------------------------------------------------------------- */
+      format_list = msWCSGetFormatsList20(layer->map, layer);
 
-        {
-            xmlNodePtr psSupportedCrss;
-            char *owned_value;
-
-            psSupportedCrss = xmlNewChild(psSP, psWcsNs,
-                    BAD_CAST "SupportedCRSs", NULL);
-
-            if ((owned_value = msOWSGetProjURI(&(layer->projection),
-                    &(layer->metadata), "CO", MS_FALSE)) != NULL)
-            { }
-            else if ((owned_value = msOWSGetProjURI(&(layer->map->projection),
-                    &(layer->map->web.metadata), "CO", MS_FALSE)) != NULL)
-            { }
-            else
-            {
-                msDebug("missing required information, no SRSs defined.\n");
-            }
-
-            if (owned_value != NULL && strlen(owned_value) > 0)
-            {
-                msLibXml2GenerateList(psSupportedCrss, psWcsNs,
-                        "SupportedCRS", owned_value, ' ');
-            }
+      if (strlen(format_list) > 0) {
+        msLibXml2GenerateList(psSupportedFormats, psWcsNs,
+                              "SupportedFormat", format_list, ',');
 
-            xmlNewChild(psSupportedCrss, psWcsNs,
-                    BAD_CAST "NativeCRS", BAD_CAST cm.srs_uri);
+      msFree(format_list);
+    }*/
 
-            msFree(owned_value);
-        }
 
-        /* -------------------------------------------------------------------- */
-        /*      SupportedFormats                                                */
-        /* -------------------------------------------------------------------- */
-        {
-            xmlNodePtr psSupportedFormats;
-            char *format_list;
+    /* -------------------------------------------------------------------- */
+    /*      nativeFormat                                                    */
+    /* -------------------------------------------------------------------- */
+    xmlNewChild(psSP, psWcsNs,
+                BAD_CAST "nativeFormat", BAD_CAST (cm.native_format ?
+                    cm.native_format : ""));
 
-            psSupportedFormats =
-                    xmlNewChild(psSP, psWcsNs, BAD_CAST "SupportedFormats", NULL);
+    if (!cm.native_format) {
+      msDebug("msWCSDescribeCoverage20_CoverageDescription(): "
+              "No native format specified.\n");
+    }
+  }
 
-            format_list = msWCSGetFormatsList20(layer->map, layer);
+  msWCSClearCoverageMetadata20(&cm);
 
-            if (strlen(format_list) > 0)
-            {
-                msLibXml2GenerateList(psSupportedFormats, psWcsNs,
-                        "SupportedFormat", format_list, ',');
-            }
-
-            if(cm.native_format != NULL)
-            {
-                xmlNewChild(psSupportedFormats, psWcsNs,
-                        BAD_CAST "NativeFormat", BAD_CAST cm.native_format);
-            }
-            else
-            {
-                msDebug("msWCSDescribeCoverage20_CoverageDescription(): "
-                        "No native format specified.\n");
-            }
-
-            msFree(format_list);
-        }
-    }
-
-    msWCSClearCoverageMetadata20(&cm);
-
-    return MS_SUCCESS;
-}
+  return MS_SUCCESS;
+}
 
 /************************************************************************/
 /*                   msWCSDescribeCoverage20()                          */
@@ -3306,62 +2895,57 @@ static int msWCSDescribeCoverage20_CoverageDescription(mapObj *map,
 
 int msWCSDescribeCoverage20(mapObj *map, wcs20ParamsObjPtr params, owsRequestObj *ows_request)
 {
-    xmlDocPtr psDoc = NULL; /* document pointer */
-    xmlNodePtr psRootNode;
-    xmlNsPtr psWcsNs = NULL;
-    int i, j;
-
-    /* create DOM document and root node */
-    psDoc = xmlNewDoc(BAD_CAST "1.0");
-    psRootNode = xmlNewNode(NULL, BAD_CAST "CoverageDescriptions");
-    xmlDocSetRootElement(psDoc, psRootNode);
-
-    /* prepare initial namespace definitions */
-    msWCSPrepareNamespaces20(psDoc, psRootNode, map);
-
-    psWcsNs = xmlSearchNs(psDoc, psRootNode,
-            BAD_CAST MS_OWSCOMMON_WCS_NAMESPACE_PREFIX);
-    xmlSetNs(psRootNode, psWcsNs);
-
-    /* check if IDs are given */
-    if (params->ids)
-    {
-        /* for each given ID in the ID-list */
-        for (j = 0; params->ids[j]; j++)
-        {
-            i = msGetLayerIndex(map, params->ids[j]);
-            if (i == -1 || (!msIntegerInArray(GET_LAYER(map, i)->index, ows_request->enabled_layers, ows_request->numlayers)) )
-            {
-                msSetError(MS_WCSERR, "Unknown coverage: (%s)",
-                        "msWCSDescribeCoverage20()", params->ids[j]);
-                return msWCSException(map, "NoSuchCoverage", "coverage",
-                        params->version);
-            }
-            /* create coverage description for the specified layer */
-            if(msWCSDescribeCoverage20_CoverageDescription(map, (GET_LAYER(map, i)),
-                    params, psDoc, psRootNode) == MS_FAILURE)
-            {
-                msSetError(MS_WCSERR, "Error retrieving coverage description.", "msWCSDescribeCoverage20()");
-                return msWCSException(map, "MissingParameterValue", "coverage",
-                        params->version);
-            }
-        }
-    }
-    else
-    {   /* Throw error, since IDs are mandatory */
-        msSetError(MS_WCSERR, "Missing COVERAGEID parameter.", "msWCSDescribeCoverage20()");
+  xmlDocPtr psDoc = NULL; /* document pointer */
+  xmlNodePtr psRootNode;
+  xmlNsPtr psWcsNs = NULL;
+  int i, j;
+
+  /* create DOM document and root node */
+  psDoc = xmlNewDoc(BAD_CAST "1.0");
+  psRootNode = xmlNewNode(NULL, BAD_CAST "CoverageDescriptions");
+  xmlDocSetRootElement(psDoc, psRootNode);
+
+  /* prepare initial namespace definitions */
+  msWCSPrepareNamespaces20(psDoc, psRootNode, map);
+
+  psWcsNs = xmlSearchNs(psDoc, psRootNode,
+                        BAD_CAST MS_OWSCOMMON_WCS_NAMESPACE_PREFIX);
+  xmlSetNs(psRootNode, psWcsNs);
+
+  /* check if IDs are given */
+  if (params->ids) {
+    /* for each given ID in the ID-list */
+    for (j = 0; params->ids[j]; j++) {
+      i = msGetLayerIndex(map, params->ids[j]);
+      if (i == -1 || (!msIntegerInArray(GET_LAYER(map, i)->index, ows_request->enabled_layers, ows_request->numlayers)) ) {
+        msSetError(MS_WCSERR, "Unknown coverage: (%s)",
+                   "msWCSDescribeCoverage20()", params->ids[j]);
+        return msWCSException(map, "NoSuchCoverage", "coverage",
+                              params->version);
+      }
+      /* create coverage description for the specified layer */
+      if(msWCSDescribeCoverage20_CoverageDescription(map, (GET_LAYER(map, i)),
+          params, psDoc, psRootNode) == MS_FAILURE) {
+        msSetError(MS_WCSERR, "Error retrieving coverage description.", "msWCSDescribeCoverage20()");
         return msWCSException(map, "MissingParameterValue", "coverage",
-                params->version);
+                              params->version);
+      }
     }
+  } else {
+    /* Throw error, since IDs are mandatory */
+    msSetError(MS_WCSERR, "Missing COVERAGEID parameter.", "msWCSDescribeCoverage20()");
+    return msWCSException(map, "MissingParameterValue", "coverage",
+                          params->version);
+  }
 
-    /* write out the DOM document to the stream */
-    msWCSWriteDocument20(map, psDoc);
+  /* write out the DOM document to the stream */
+  msWCSWriteDocument20(map, psDoc);
 
-    /* cleanup */
-    xmlFreeDoc(psDoc);
-    xmlCleanupParser();
+  /* cleanup */
+  xmlFreeDoc(psDoc);
+  xmlCleanupParser();
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 /************************************************************************/
@@ -3375,102 +2959,86 @@ int msWCSDescribeCoverage20(mapObj *map, wcs20ParamsObjPtr params, owsRequestObj
 
 static int msWCSGetCoverage20_FinalizeParamsObj(wcs20ParamsObjPtr params)
 {
-    int returnValue;
-    static const int numAxis = 2;
-    char *validXAxisNames[] = {"x", "xaxis", "x-axis", "x_axis", "long", "long_axis", "long-axis", "lon", "lon_axis", "lon-axis", NULL};
-    char *validYAxisNames[] = {"y", "yaxis", "y-axis", "y_axis", "lat", "lat_axis", "lat-axis", NULL};
-    char ***validAxisNames;
-    char *crs = NULL;
-    wcs20AxisObjPtr *axes;
-
-    axes = (wcs20AxisObjPtr*)msSmallMalloc(sizeof(wcs20AxisObjPtr) * numAxis);
-
-    validAxisNames = msSmallCalloc(sizeof(char**), numAxis);
-    validAxisNames[0] = validXAxisNames;
-    validAxisNames[1] = validYAxisNames;
-
-    returnValue = msWCSValidateAndFindAxes20(params, validAxisNames, numAxis, axes);
-    msFree(validAxisNames);
-    if(returnValue != MS_SUCCESS)
-    {
-        msFree(axes);
-        return MS_FAILURE;
-    }
-
-    if (axes[0] != NULL)
-    {
-        if(axes[0]->subset != NULL)
-        {
-            msDebug("Subset for X-axis found: %s\n", axes[0]->subset->axis);
-            if (!axes[0]->subset->min.unbounded)
-                params->bbox.minx = axes[0]->subset->min.scalar;
-            if (!axes[0]->subset->max.unbounded)
-                params->bbox.maxx = axes[0]->subset->max.scalar;
-            crs = axes[0]->subset->crs;
-        }
-        params->width = axes[0]->size;
-        params->resolutionX = axes[0]->resolution;
-        if(axes[0]->resolutionUOM != NULL)
-        {
-            params->resolutionUnits = msStrdup(axes[0]->resolutionUOM);
-        }
-    }
-
-    if (axes[1] != NULL)
-    {
-        if(axes[1]->subset != NULL)
-        {
-            msDebug("Subset for Y-axis found: %s\n", axes[1]->subset->axis);
-            if (!axes[1]->subset->min.unbounded)
-                params->bbox.miny = axes[1]->subset->min.scalar;
-            if (!axes[1]->subset->max.unbounded)
-                params->bbox.maxy = axes[1]->subset->max.scalar;
-            if(crs != NULL && axes[0] != NULL && axes[0]->subset!= NULL)
-            {
-                if(!EQUAL(crs, axes[1]->subset->crs))
-                {
-                    msSetError(MS_WCSERR, "CRS for axis %s and axis %s are not the same.",
-                            "msWCSCreateBoundingBox20()", axes[0]->name, axes[1]->name);
-                    msFree(axes);
-                    return MS_FAILURE;
-                }
-            }
-            else
-            {
-                crs = axes[1]->subset->crs;
-            }
-        }
-        params->height = axes[1]->size;
-        params->resolutionY = axes[1]->resolution;
-
-        if(params->resolutionUnits == NULL && axes[1]->resolutionUOM != NULL)
-        {
-            params->resolutionUnits = msStrdup(axes[1]->resolutionUOM);
-        }
-        else if(params->resolutionUnits != NULL && axes[1]->resolutionUOM != NULL
-                && !EQUAL(params->resolutionUnits, axes[1]->resolutionUOM))
-        {
-            msSetError(MS_WCSERR, "The units of measure of the resolution for"
-                    "axis %s and axis %s are not the same.",
-                    "msWCSCreateBoundingBox20()", axes[0]->name, axes[1]->name);
-            msFree(axes);
-            return MS_FAILURE;
-        }
-    }
-
+  int returnValue;
+  static const int numAxis = 2;
+  char *validXAxisNames[] = {"x", "xaxis", "x-axis", "x_axis", "long", "long_axis", "long-axis", "lon", "lon_axis", "lon-axis", NULL};
+  char *validYAxisNames[] = {"y", "yaxis", "y-axis", "y_axis", "lat", "lat_axis", "lat-axis", NULL};
+  char ***validAxisNames;
+  char *crs = NULL;
+  wcs20AxisObjPtr *axes;
+
+  axes = (wcs20AxisObjPtr*)msSmallMalloc(sizeof(wcs20AxisObjPtr) * numAxis);
+
+  validAxisNames = msSmallCalloc(sizeof(char**), numAxis);
+  validAxisNames[0] = validXAxisNames;
+  validAxisNames[1] = validYAxisNames;
+
+  returnValue = msWCSValidateAndFindAxes20(params, validAxisNames, numAxis, axes);
+  msFree(validAxisNames);
+  if(returnValue != MS_SUCCESS) {
     msFree(axes);
-
-    /* check if projections are equal */
-    if(crs != NULL)
-    {
-        params->subsetcrs = msStrdup(crs);
-    }
-    else
-    {
-        params->subsetcrs = msStrdup("imageCRS");
-    }
-
-    return MS_SUCCESS;
+    return MS_FAILURE;
+  }
+
+  if (axes[0] != NULL) {
+    if(axes[0]->subset != NULL) {
+      msDebug("Subset for X-axis found: %s\n", axes[0]->subset->axis);
+      if (!axes[0]->subset->min.unbounded)
+        params->bbox.minx = axes[0]->subset->min.scalar;
+      if (!axes[0]->subset->max.unbounded)
+        params->bbox.maxx = axes[0]->subset->max.scalar;
+      crs = axes[0]->subset->crs;
+    }
+    params->width = axes[0]->size;
+    params->resolutionX = axes[0]->resolution;
+    if(axes[0]->resolutionUOM != NULL) {
+      params->resolutionUnits = msStrdup(axes[0]->resolutionUOM);
+    }
+  }
+
+  if (axes[1] != NULL) {
+    if(axes[1]->subset != NULL) {
+      msDebug("Subset for Y-axis found: %s\n", axes[1]->subset->axis);
+      if (!axes[1]->subset->min.unbounded)
+        params->bbox.miny = axes[1]->subset->min.scalar;
+      if (!axes[1]->subset->max.unbounded)
+        params->bbox.maxy = axes[1]->subset->max.scalar;
+      if(crs != NULL && axes[0] != NULL && axes[0]->subset!= NULL) {
+        if(!EQUAL(crs, axes[1]->subset->crs)) {
+          msSetError(MS_WCSERR, "CRS for axis %s and axis %s are not the same.",
+                     "msWCSCreateBoundingBox20()", axes[0]->name, axes[1]->name);
+          msFree(axes);
+          return MS_FAILURE;
+        }
+      } else {
+        crs = axes[1]->subset->crs;
+      }
+    }
+    params->height = axes[1]->size;
+    params->resolutionY = axes[1]->resolution;
+
+    if(params->resolutionUnits == NULL && axes[1]->resolutionUOM != NULL) {
+      params->resolutionUnits = msStrdup(axes[1]->resolutionUOM);
+    } else if(params->resolutionUnits != NULL && axes[1]->resolutionUOM != NULL
+              && !EQUAL(params->resolutionUnits, axes[1]->resolutionUOM)) {
+      msSetError(MS_WCSERR, "The units of measure of the resolution for"
+                 "axis %s and axis %s are not the same.",
+                 "msWCSCreateBoundingBox20()", axes[0]->name, axes[1]->name);
+      msFree(axes);
+      return MS_FAILURE;
+    }
+  }
+
+  msFree(axes);
+
+  /* check if projections are equal */
+  if(crs != NULL) {
+    params->subsetcrs = msStrdup(crs);
+  } else {
+    params->subsetcrs = msStrdup("imageCRS");
+  }
+
+  return MS_SUCCESS;
 }
 
 /************************************************************************/
@@ -3481,77 +3049,68 @@ static int msWCSGetCoverage20_FinalizeParamsObj(wcs20ParamsObjPtr params)
 /************************************************************************/
 
 static int msWCSGetCoverage20_GetBands(mapObj *map, layerObj *layer,
-        wcs20ParamsObjPtr params, wcs20coverageMetadataObjPtr cm, char **bandlist)
+                                       wcs20ParamsObjPtr params, wcs20coverageMetadataObjPtr cm, char **bandlist)
 {
-    int i = 0, count, maxlen, index;
-    char *current = NULL, *tmp = NULL;
-    char **band_ids = NULL;
-
-    /* if rangesubset parameter is not given, default to all bands */
-    if(NULL == params->range_subset)
-    {
-        *bandlist = msStrdup("1");
-        for(i = 1; i < cm->numbands; ++i)
-        {
-            char strnumber[10];
-            snprintf(strnumber, sizeof(strnumber), ",%d", i + 1);
-            *bandlist = msStringConcatenate(*bandlist, strnumber);
-        }
-        return MS_SUCCESS;
+  int i = 0, count, maxlen, index;
+  char *tmp = NULL;
+  char **band_ids = NULL;
+
+  /* if rangesubset parameter is not given, default to all bands */
+  if(NULL == params->range_subset) {
+    *bandlist = msStrdup("1");
+    for(i = 1; i < cm->numbands; ++i) {
+      char strnumber[10];
+      snprintf(strnumber, sizeof(strnumber), ",%d", i + 1);
+      *bandlist = msStringConcatenate(*bandlist, strnumber);
     }
+    return MS_SUCCESS;
+  }
 
-    count = CSLCount(params->range_subset);
-    maxlen = count * 4 * sizeof(char);
-    *bandlist = msSmallCalloc(sizeof(char), maxlen);
-    current = *bandlist;
+  count = CSLCount(params->range_subset);
+  maxlen = count * 4 * sizeof(char);
+  *bandlist = msSmallCalloc(sizeof(char), maxlen);
 
-    if (NULL == (tmp = msOWSGetEncodeMetadata(&layer->metadata,
-                        "CO", "rangeset_axes", NULL)))
-    {
-        tmp = msOWSGetEncodeMetadata(&layer->metadata,
-                        "CO", "band_names", NULL);
-    }
+  if (NULL == (tmp = msOWSGetEncodeMetadata(&layer->metadata,
+                     "CO", "rangeset_axes", NULL))) {
+    tmp = msOWSGetEncodeMetadata(&layer->metadata,
+                                 "CO", "band_names", NULL);
+  }
 
-    if(NULL != tmp)
-    {
-        band_ids = CSLTokenizeString2(tmp, " ", 0);
-        msFree(tmp);
-    }
-
-    for(i = 0; i < count; ++i)
-    {
-        /* print ',' if not the first value */
-        if(i != 0)
-        {
-            current = strlcat(*bandlist, ",", maxlen) + *bandlist;
-        }
+  if(NULL != tmp) {
+    band_ids = CSLTokenizeString2(tmp, " ", 0);
+    msFree(tmp);
+  }
 
-        /* check if the string represents an integer */
-        if(msStringParseInteger(params->range_subset[i], &index) == MS_SUCCESS)
-        {
-            tmp = msIntToString((int)index);
-            strlcat(*bandlist, tmp, maxlen);
-            msFree(tmp);
-            continue;
-        }
+  for(i = 0; i < count; ++i) {
+    /* print ',' if not the first value */
+    if(i != 0) {
+      strlcat(*bandlist, ",", maxlen);
+    }
 
-        /* check if the string is equal to a band identifier    */
-        /* if so, what is the index of the band                 */
-        index = CSLFindString(band_ids, params->range_subset[i]);
-        if(index != -1)
-        {
-            tmp = msIntToString((int)index + 1);
-            strlcat(*bandlist, tmp, maxlen);
-            msFree(tmp);
-            continue;
-        }
+    /* check if the string represents an integer */
+    if(msStringParseInteger(params->range_subset[i], &index) == MS_SUCCESS) {
+      tmp = msIntToString((int)index);
+      strlcat(*bandlist, tmp, maxlen);
+      msFree(tmp);
+      continue;
+    }
 
-        msSetError(MS_WCSERR, "'%s' is not a valid band identifier.",
-                       "msWCSGetCoverage20_GetBands()", params->range_subset[i]);
-        return MS_FAILURE;
+    /* check if the string is equal to a band identifier    */
+    /* if so, what is the index of the band                 */
+    index = CSLFindString(band_ids, params->range_subset[i]);
+    if(index != -1) {
+      tmp = msIntToString((int)index + 1);
+      strlcat(*bandlist, tmp, maxlen);
+      msFree(tmp);
+      continue;
     }
-    CSLDestroy(band_ids);
-    return MS_SUCCESS;
+
+    msSetError(MS_WCSERR, "'%s' is not a valid band identifier.",
+               "msWCSGetCoverage20_GetBands()", params->range_subset[i]);
+    return MS_FAILURE;
+  }
+  CSLDestroy(band_ids);
+  return MS_SUCCESS;
 }
 
 /************************************************************************/
@@ -3565,693 +3124,516 @@ static int msWCSGetCoverage20_GetBands(mapObj *map, layerObj *layer,
 int msWCSGetCoverage20(mapObj *map, cgiRequestObj *request,
                        wcs20ParamsObjPtr params, owsRequestObj *ows_request)
 {
-    layerObj *layer = NULL;
-    wcs20coverageMetadataObj cm;
-    imageObj *image = NULL;
-    outputFormatObj *format = NULL;
-
-    rectObj subsets, bbox;
-    projectionObj imageProj;
-
-    int status, i;
-    double x_1, x_2, y_1, y_2;
-    char *coverageName, *bandlist=NULL, numbands[8];
-
-    /* number of coverage ids should be 1 */
-    if (params->ids == NULL || params->ids[0] == NULL) {
-        msSetError(MS_WCSERR, "Required parameter CoverageID was not supplied.",
-                   "msWCSGetCoverage20()");
-        return msWCSException(map, "MissingParameterValue", "coverage",
-                              params->version);
-    }
-    if (params->ids[1] != NULL) {
-        msSetError(MS_WCSERR, "GetCoverage operation supports only one coverage.",
-                   "msWCSGetCoverage20()");
-        return msWCSException(map, "TooManyParameterValues", "coverage",
-                              params->version);
-    }
-
-    /* find the right layer */
-    layer = NULL;
-    for(i = 0; i < map->numlayers; i++) {
-        coverageName = msOWSGetEncodeMetadata(&(GET_LAYER(map, i)->metadata),
-                                              "CO", "name",
-                                              GET_LAYER(map, i)->name);
-        if (EQUAL(coverageName, params->ids[0]) && 
-            (msIntegerInArray(GET_LAYER(map, i)->index, ows_request->enabled_layers, ows_request->numlayers)))
-        {
-            layer = GET_LAYER(map, i);
-            i = map->numlayers; /* to exit loop don't use break, we want to free resources first */
-        }
-        msFree(coverageName);
-    }
-
-    /* throw exception if no Layer was found */
-    if (layer == NULL)
-    {
-        msSetError(MS_WCSERR,
-                "COVERAGE=%s not found, not in supported layer list.",
-                "msWCSGetCoverage20()", params->ids[0]);
-        return msWCSException(map, "InvalidParameterValue", "coverage",
-                params->version);
-    }
-    /* retrieve coverage metadata  */
-    status = msWCSGetCoverageMetadata20(layer, &cm);
-    if (status != MS_SUCCESS) return MS_FAILURE;
-
-    /* fill in bands rangeset info, if required.  */
-    //msWCSSetDefaultBandsRangeSetInfo(NULL, &cm, layer );
-
-    /* set  resolution, size and maximum extent */
-    layer->extent = map->extent = cm.extent;
-    map->cellsize = cm.xresolution;
-    map->width = cm.xsize;
-    map->height = cm.ysize;
-
-    /************************************************************************/
-    /*      finalize the params object. determine subset crs and subset     */
-    /*      bbox. Also project the image to the subset crs.                 */
-    /************************************************************************/
-
-    msInitProjection(&imageProj);
-    if (msLoadProjectionString(&imageProj, cm.srs) == -1)
-    {
-        msSetError(MS_WCSERR,
-            "Error loading CRS %s.",
-            "msWCSGetCoverage20()", params->subsetcrs);
-        return msWCSException(map, "InvalidParameterValue",
-            "projection", params->version);
-    }
+  layerObj *layer = NULL;
+  wcs20coverageMetadataObj cm;
+  imageObj *image = NULL;
+  outputFormatObj *format = NULL;
 
-    if(msWCSGetCoverage20_FinalizeParamsObj(params) == MS_FAILURE)
-    {
-        return msWCSException(map, "InvalidParameterValue", "extent", params->version);
-    }
+  rectObj subsets, bbox;
+  projectionObj imageProj;
 
-    subsets = params->bbox;
-
-    if(EQUAL(params->subsetcrs, "imageCRS"))
-    {
-        /* subsets are in imageCRS; reproject them to real coordinates */
-        rectObj orig_bbox = subsets;
+  int status, i;
+  double x_1, x_2, y_1, y_2;
+  char *coverageName, *bandlist=NULL, numbands[8];
 
-        msFreeProjection(&(map->projection));
-        map->projection = imageProj;
-
-        if(subsets.minx != -DBL_MAX || subsets.maxx != DBL_MAX)
-        {
-            x_1 = cm.geotransform[0]
-                + orig_bbox.minx * cm.geotransform[1]
-                + orig_bbox.miny * cm.geotransform[2];
-            x_2 = cm.geotransform[0]
-                + (orig_bbox.maxx+1) * cm.geotransform[1]
-                + (orig_bbox.maxy+1) * cm.geotransform[2];
-
-            subsets.minx = MIN(x_1, x_2);
-            subsets.maxx = MAX(x_1, x_2);
-        }
-        if(subsets.miny != -DBL_MAX || subsets.maxy != DBL_MAX)
-        {
-            y_1 = cm.geotransform[3]
-                + (orig_bbox.maxx+1) * cm.geotransform[4]
-                + (orig_bbox.maxy+1) * cm.geotransform[5];
-            /*subsets.miny -= cm.geotransform[4]/2 + cm.geotransform[5]/2;*/
-            y_2 = cm.geotransform[3]
-                + orig_bbox.minx * cm.geotransform[4]
-                + orig_bbox.miny * cm.geotransform[5];
-
-            subsets.miny = MIN(y_1, y_2);
-            subsets.maxy = MAX(y_1, y_2);
-        }
-    }
-    else /* if crs is not the 'imageCRS' */
-    {
-        projectionObj subsetProj;
-
-        /* if the subsets have a crs given, project the image extent to it */
-        msInitProjection(&subsetProj);
-        if(msLoadProjectionString(&subsetProj, params->subsetcrs) != MS_SUCCESS)
-        {
-            msSetError(MS_WCSERR,
-                "Error loading CRS %s.",
-                "msWCSGetCoverage20()", params->subsetcrs);
-            return msWCSException(map, "InvalidParameterValue",
-                "projection", params->version);
-        }
+  /* number of coverage ids should be 1 */
+  if (params->ids == NULL || params->ids[0] == NULL) {
+    msSetError(MS_WCSERR, "Required parameter CoverageID was not supplied.",
+               "msWCSGetCoverage20()");
+    return msWCSException(map, "MissingParameterValue", "coverage",
+                          params->version);
+  }
+  if (params->ids[1] != NULL) {
+    msSetError(MS_WCSERR, "GetCoverage operation supports only one coverage.",
+               "msWCSGetCoverage20()");
+    return msWCSException(map, "TooManyParameterValues", "coverage",
+                          params->version);
+  }
+
+  /* find the right layer */
+  layer = NULL;
+  for(i = 0; i < map->numlayers; i++) {
+    coverageName = msOWSGetEncodeMetadata(&(GET_LAYER(map, i)->metadata),
+                                          "CO", "name",
+                                          GET_LAYER(map, i)->name);
+    if (EQUAL(coverageName, params->ids[0]) &&
+        (msIntegerInArray(GET_LAYER(map, i)->index, ows_request->enabled_layers, ows_request->numlayers))) {
+      layer = GET_LAYER(map, i);
+      i = map->numlayers; /* to exit loop don't use break, we want to free resources first */
+    }
+    msFree(coverageName);
+  }
+
+  /* throw exception if no Layer was found */
+  if (layer == NULL) {
+    msSetError(MS_WCSERR,
+               "COVERAGE=%s not found, not in supported layer list. A layer might be disabled for \
+this request. Check wcs/ows_enable_request settings.", "msWCSGetCoverage20()", params->ids[0]);
+    return msWCSException(map, "InvalidParameterValue", "coverage",
+                          params->version);
+  }
+  /* retrieve coverage metadata  */
+  status = msWCSGetCoverageMetadata20(layer, &cm);
+  if (status != MS_SUCCESS) {
+    msWCSClearCoverageMetadata20(&cm);
+    return MS_FAILURE;
+  }
 
-        if(msProjectionsDiffer(&imageProj, &subsetProj))
-        {
-            msProjectRect(&imageProj, &subsetProj, &(layer->extent));
-            map->extent = layer->extent;
-            msFreeProjection(&(map->projection));
-            map->projection = subsetProj;
-            msFreeProjection(&imageProj);
-        }
-        else
-        {
-            msFreeProjection(&(map->projection));
-            map->projection = imageProj;
-            msFreeProjection(&subsetProj);
-        }
-    }
+  /* fill in bands rangeset info, if required.  */
+  /* msWCSSetDefaultBandsRangeSetInfo(NULL, &cm, layer ); */
 
-    /* create boundings of params subsets and image extent */
-    if(msRectOverlap(&subsets, &(layer->extent)) == MS_FALSE)
-    {
-        /* extent and bbox do not overlap -> exit */
-        msSetError(MS_WCSERR, "Image extent does not intersect with desired region.",
-                "msWCSGetCoverage20()");
-        return msWCSException(map, "ExtentError", "extent", params->version);
-    }
+  /* set  resolution, size and maximum extent */
+  layer->extent = map->extent = cm.extent;
+  map->cellsize = cm.xresolution;
+  map->width = cm.xsize;
+  map->height = cm.ysize;
 
-    /* write combined bounding box */
-    bbox.minx = MAX(subsets.minx, map->extent.minx);
-    bbox.miny = MAX(subsets.miny, map->extent.miny);
-    bbox.maxx = MIN(subsets.maxx, map->extent.maxx);
-    bbox.maxy = MIN(subsets.maxy, map->extent.maxy);
+  /************************************************************************/
+  /*      finalize the params object. determine subset crs and subset     */
+  /*      bbox. Also project the image to the subset crs.                 */
+  /************************************************************************/
 
-    /* check if we are overspecified  */
-    if((params->width != 0 &&  params->resolutionX != MS_WCS20_UNBOUNDED)
-            || (params->height != 0 && params->resolutionY != MS_WCS20_UNBOUNDED))
-    {
-        msSetError(MS_WCSERR, "GetCoverage operation supports only one of SIZE or RESOLUTION per axis.",
+  msInitProjection(&imageProj);
+  if (msLoadProjectionString(&imageProj, cm.srs) == -1) {
+    msWCSClearCoverageMetadata20(&cm);
+    msSetError(MS_WCSERR,
+               "Error loading CRS %s.",
+               "msWCSGetCoverage20()", params->subsetcrs);
+    return msWCSException(map, "InvalidParameterValue",
+                          "projection", params->version);
+  }
+
+  if(msWCSGetCoverage20_FinalizeParamsObj(params) == MS_FAILURE) {
+    msWCSClearCoverageMetadata20(&cm);
+    return msWCSException(map, "InvalidParameterValue", "extent", params->version);
+  }
+
+  subsets = params->bbox;
+
+  if(EQUAL(params->subsetcrs, "imageCRS")) {
+    /* subsets are in imageCRS; reproject them to real coordinates */
+    rectObj orig_bbox = subsets;
+
+    msFreeProjection(&(map->projection));
+    map->projection = imageProj;
+
+    if(subsets.minx != -DBL_MAX || subsets.maxx != DBL_MAX) {
+      x_1 = cm.geotransform[0]
+            + orig_bbox.minx * cm.geotransform[1]
+            + orig_bbox.miny * cm.geotransform[2];
+      x_2 = cm.geotransform[0]
+            + (orig_bbox.maxx+1) * cm.geotransform[1]
+            + (orig_bbox.maxy+1) * cm.geotransform[2];
+
+      subsets.minx = MIN(x_1, x_2);
+      subsets.maxx = MAX(x_1, x_2);
+    }
+    if(subsets.miny != -DBL_MAX || subsets.maxy != DBL_MAX) {
+      y_1 = cm.geotransform[3]
+            + (orig_bbox.maxx+1) * cm.geotransform[4]
+            + (orig_bbox.maxy+1) * cm.geotransform[5];
+      /*subsets.miny -= cm.geotransform[4]/2 + cm.geotransform[5]/2;*/
+      y_2 = cm.geotransform[3]
+            + orig_bbox.minx * cm.geotransform[4]
+            + orig_bbox.miny * cm.geotransform[5];
+
+      subsets.miny = MIN(y_1, y_2);
+      subsets.maxy = MAX(y_1, y_2);
+    }
+  } else { /* if crs is not the 'imageCRS' */
+    projectionObj subsetProj;
+
+    /* if the subsets have a crs given, project the image extent to it */
+    msInitProjection(&subsetProj);
+    if(msLoadProjectionString(&subsetProj, params->subsetcrs) != MS_SUCCESS) {
+      msWCSClearCoverageMetadata20(&cm);
+      msSetError(MS_WCSERR,
+                 "Error loading CRS %s.",
+                 "msWCSGetCoverage20()", params->subsetcrs);
+      return msWCSException(map, "InvalidParameterValue",
+                            "projection", params->version);
+    }
+
+    if(msProjectionsDiffer(&imageProj, &subsetProj)) {
+      msProjectRect(&imageProj, &subsetProj, &(layer->extent));
+      map->extent = layer->extent;
+      msFreeProjection(&(map->projection));
+      map->projection = subsetProj;
+      msFreeProjection(&imageProj);
+    } else {
+      msFreeProjection(&(map->projection));
+      map->projection = imageProj;
+      msFreeProjection(&subsetProj);
+    }
+  }
+
+  /* create boundings of params subsets and image extent */
+  if(msRectOverlap(&subsets, &(layer->extent)) == MS_FALSE) {
+    /* extent and bbox do not overlap -> exit */
+    msWCSClearCoverageMetadata20(&cm);
+    msSetError(MS_WCSERR, "Image extent does not intersect with desired region.",
+               "msWCSGetCoverage20()");
+    return msWCSException(map, "ExtentError", "extent", params->version);
+  }
+
+  /* write combined bounding box */
+  bbox.minx = MAX(subsets.minx, map->extent.minx);
+  bbox.miny = MAX(subsets.miny, map->extent.miny);
+  bbox.maxx = MIN(subsets.maxx, map->extent.maxx);
+  bbox.maxy = MIN(subsets.maxy, map->extent.maxy);
+
+  /* check if we are overspecified  */
+  if((params->width != 0 &&  params->resolutionX != MS_WCS20_UNBOUNDED)
+      || (params->height != 0 && params->resolutionY != MS_WCS20_UNBOUNDED)) {
+    msWCSClearCoverageMetadata20(&cm);
+    msSetError(MS_WCSERR, "GetCoverage operation supports only one of SIZE or RESOLUTION per axis.",
                "msWCSGetCoverage20()");
-        return msWCSException(map, "TooManyParameterValues", "coverage",
+    return msWCSException(map, "TooManyParameterValues", "coverage",
                           params->version);
-    }
-
-    /************************************************************************/
-    /* check both axes: see if either size or resolution are given (and     */
-    /* calculate the other value). If both are not given, calculate them    */
-    /* from the bounding box.                                               */
-    /************************************************************************/
-
-    /* check x axis */
-    if(params->width != 0)
-    {
-        /* TODO Unit Of Measure? */
-        params->resolutionX = (bbox.maxx - bbox.minx) / params->width;
-    }
-    else if(params->resolutionX != MS_WCS20_UNBOUNDED)
-    {
-        params->width = MS_NINT((bbox.maxx - bbox.minx) / params->resolutionX);
-    }
-    else
-    {
-        if(ABS(bbox.maxx - bbox.minx) != ABS(map->extent.maxx - map->extent.minx))
-        {
-            double total = ABS(map->extent.maxx - map->extent.minx),
-                    part = ABS(bbox.maxx - bbox.minx);
-            params->width = MS_NINT((part * map->width) / total);
-        }
-        else
-        {
-            params->width = map->width;
-        }
+  }
+
+  /************************************************************************/
+  /* check both axes: see if either size or resolution are given (and     */
+  /* calculate the other value). If both are not given, calculate them    */
+  /* from the bounding box.                                               */
+  /************************************************************************/
+
+  /* check x axis */
+  if(params->width != 0) {
+    /* TODO Unit Of Measure? */
+    params->resolutionX = (bbox.maxx - bbox.minx) / params->width;
+  } else if(params->resolutionX != MS_WCS20_UNBOUNDED) {
+    params->width = MS_NINT((bbox.maxx - bbox.minx) / params->resolutionX);
+  } else {
+    if(ABS(bbox.maxx - bbox.minx) != ABS(map->extent.maxx - map->extent.minx)) {
+      double total = ABS(map->extent.maxx - map->extent.minx),
+             part = ABS(bbox.maxx - bbox.minx);
+      params->width = MS_NINT((part * map->width) / total);
+    } else {
+      params->width = map->width;
+    }
+
+    params->resolutionX = (bbox.maxx - bbox.minx) / params->width;
+  }
+
+  /* check y axis */
+  if(params->height != 0) {
+    params->resolutionY = (bbox.maxy - bbox.miny) / params->height;
+  } else if(params->resolutionY != MS_WCS20_UNBOUNDED) {
+    params->height = MS_NINT((bbox.maxy - bbox.miny) / params->resolutionY);
+  } else {
+    if(ABS(bbox.maxy - bbox.miny) != ABS(map->extent.maxy - map->extent.miny)) {
+      double total = ABS(map->extent.maxy - map->extent.miny),
+             part = ABS(bbox.maxy - bbox.miny);
+      params->height = MS_NINT((part * map->height) / total);
+    } else {
+      params->height = map->height;
+    }
+
+    params->resolutionY = (bbox.maxy - bbox.miny) / params->height;
+  }
+
+  /* WCS 2.0 is center of pixel oriented */
+  bbox.minx += params->resolutionX * 0.5;
+  bbox.maxx -= params->resolutionX * 0.5;
+  bbox.miny += params->resolutionY * 0.5;
+  bbox.maxy -= params->resolutionY * 0.5;
+
+  /* if parameter 'outputcrs' is given, project the image to this crs */
+  if(params->outputcrs != NULL) {
+    projectionObj outputProj;
+
+    msInitProjection(&outputProj);
+    if(msLoadProjectionString(&outputProj, params->outputcrs) == -1) {
+      msFreeProjection(&outputProj);
+      msWCSClearCoverageMetadata20(&cm);
+      return msWCSException(map, "InvalidParameterValue", "coverage",
+                            params->version);
+    }
+    if(msProjectionsDiffer(&(map->projection), &outputProj)) {
+
+      msDebug("msWCSGetCoverage20(): projecting to outputcrs %s\n", params->outputcrs);
+
+      msProjectRect(&(map->projection), &outputProj, &bbox);
+      msFreeProjection(&(map->projection));
+      map->projection = outputProj;
+
+      /* recalculate resolutions, needed if UOM changes (e.g: deg -> m) */
+      params->resolutionX = (bbox.maxx - bbox.minx) / params->width;
+      params->resolutionY = (bbox.maxy - bbox.miny) / params->height;
+    }
+  }
+
+  /* set the bounding box as new map extent */
+  map->extent = bbox;
+  map->width = params->width;
+  map->height = params->height;
+
+  /* Are we exceeding the MAXSIZE limit on result size? */
+  if(map->width > map->maxsize || map->height > map->maxsize ) {
+    msWCSClearCoverageMetadata20(&cm);
+    msSetError(MS_WCSERR, "Raster size out of range, width and height of "
+               "resulting coverage must be no more than MAXSIZE=%d.",
+               "msWCSGetCoverage20()", map->maxsize);
+
+    return msWCSException(map, "InvalidParameterValue",
+                          "size", params->version);
+  }
+
+  /* Mapserver only supports square cells */
+  if (params->resolutionX <= params->resolutionY)
+    map->cellsize = params->resolutionX;
+  else
+    map->cellsize = params->resolutionY;
+
+  msDebug("msWCSGetCoverage20(): Set parameters from original"
+          "data. Width: %d, height: %d, cellsize: %f, extent: %f,%f,%f,%f\n",
+          map->width, map->height, map->cellsize, map->extent.minx,
+          map->extent.miny, map->extent.maxx, map->extent.maxy);
+
+  /**
+   * Which format to use?
+   *
+   * 1) format parameter
+   * 2) native format (from metadata) or GDAL format of the input dataset
+   * 3) exception
+   **/
+
+  if (!params->format) {
+    if (cm.native_format) {
+      params->format = msStrdup(cm.native_format);
+    }
+  }
+
+  if (!params->format) {
+    msSetError(MS_WCSERR, "Output format could not be automatically determined. "
+               "Use the FORMAT parameter to specify a format.",
+               "msWCSGetCoverage20()");
+    msWCSClearCoverageMetadata20(&cm);
+    return msWCSException(map, "MissingParameterValue", "format",
+                          params->version);
+  }
 
-        params->resolutionX = (bbox.maxx - bbox.minx) / params->width;
-    }
+  /*    make sure layer is on   */
+  layer->status = MS_ON;
 
-    /* check y axis */
-    if(params->height != 0)
-    {
-        params->resolutionY = (bbox.maxy - bbox.miny) / params->height;
-    }
-    else if(params->resolutionY != MS_WCS20_UNBOUNDED)
-    {
-        params->height = MS_NINT((bbox.maxy - bbox.miny) / params->resolutionY);
-    }
-    else
-    {
-        if(ABS(bbox.maxy - bbox.miny) != ABS(map->extent.maxy - map->extent.miny))
-        {
-            double total = ABS(map->extent.maxy - map->extent.miny),
-                    part = ABS(bbox.maxy - bbox.miny);
-            params->height = MS_NINT((part * map->height) / total);
-        }
-        else
-        {
-            params->height = map->height;
-        }
+  msMapComputeGeotransform(map);
 
-        params->resolutionY = (bbox.maxy - bbox.miny) / params->height;
-    }
+  /*    fill in bands rangeset info, if required.  */
+  /* msWCSSetDefaultBandsRangeSetInfo(params, &cm, layer); */
+  /* msDebug("Bandcount: %d\n", cm.bandcount); */
 
-    /* WCS 2.0 is center of pixel oriented */
-    bbox.minx += params->resolutionX * 0.5;
-    bbox.maxx -= params->resolutionX * 0.5;
-    bbox.miny += params->resolutionY * 0.5;
-    bbox.maxy -= params->resolutionY * 0.5;
+  msApplyDefaultOutputFormats(map);
 
-    /* if parameter 'outputcrs' is given, project the image to this crs */
-    if(params->outputcrs != NULL)
-    {
-        projectionObj outputProj;
+  if (msGetOutputFormatIndex(map, params->format) == -1) {
+    msSetError(MS_WCSERR, "Unrecognized value '%s' for the FORMAT parameter.",
+               "msWCSGetCoverage20()", params->format);
+    msWCSClearCoverageMetadata20(&cm);
+    return msWCSException(map, "InvalidParameterValue", "format",
+                          params->version);
+  }
 
-        msInitProjection(&outputProj);
-        if(msLoadProjectionString(&outputProj, params->outputcrs) == -1)
-        {
-            msFreeProjection(&outputProj);
-            return msWCSException(map, "InvalidParameterValue", "coverage",
-                  params->version);
-        }
-        if(msProjectionsDiffer(&(map->projection), &outputProj))
-        {
+  /* create a temporary outputformat (we likely will need to tweak parts) */
+  format = msCloneOutputFormat(msSelectOutputFormat(map, params->format));
+  msApplyOutputFormat(&(map->outputformat), format, MS_NOOVERRIDE,
+                      MS_NOOVERRIDE, MS_NOOVERRIDE);
 
-            msDebug("msWCSGetCoverage20(): projecting to outputcrs %s\n", params->outputcrs);
+  if(msWCSGetCoverage20_GetBands(map, layer, params, &cm, &bandlist) != MS_SUCCESS) {
+    msFree(bandlist);
+    msWCSClearCoverageMetadata20(&cm);
+    return msWCSException(map, "InvalidParameterValue", "rangesubset",
+                          params->version);
+  }
+  msLayerSetProcessingKey(layer, "BANDS", bandlist);
+  snprintf(numbands, sizeof(numbands), "%d", msCountChars(bandlist, ',')+1);
+  msSetOutputFormatOption(map->outputformat, "BAND_COUNT", numbands);
+
+  /* check for the interpolation */
+  /* Defaults to NEAREST */
+  if(params->interpolation != NULL) {
+    if(EQUALN(params->interpolation,"NEAREST",7)) {
+      msLayerSetProcessingKey(layer, "RESAMPLE", "NEAREST");
+    } else if(EQUAL(params->interpolation,"BILINEAR")) {
+      msLayerSetProcessingKey(layer, "RESAMPLE", "BILINEAR");
+    } else if(EQUAL(params->interpolation,"AVERAGE")) {
+      msLayerSetProcessingKey(layer, "RESAMPLE", "AVERAGE");
+    } else {
+      msFree(bandlist);
+      msSetError( MS_WCSERR, "'%s' specifies an unsupported interpolation method.",
+                  "msWCSGetCoverage20()", params->interpolation );
+      msWCSClearCoverageMetadata20(&cm);
+      return msWCSException(map, "InvalidParameterValue", "interpolation", params->version);
+    }
+  } else {
+    msLayerSetProcessingKey(layer, "RESAMPLE", "NEAREST");
+  }
+
+  /* since the dataset is only used in one layer, set it to be    */
+  /* closed after drawing the layer. This normally defaults to    */
+  /* DEFER and will produce a memory leak, because the dataset    */
+  /* will not be closed.                                          */
+  if( msLayerGetProcessingKey(layer, "CLOSE_CONNECTION") == NULL ) {
+    msLayerSetProcessingKey(layer, "CLOSE_CONNECTION", "NORMAL");
+  }
+
+  /* create the image object  */
+  if (!map->outputformat) {
+    msWCSClearCoverageMetadata20(&cm);
+    msFree(bandlist);
+    msSetError(MS_WCSERR, "The map outputformat is missing!",
+               "msWCSGetCoverage20()");
+    return msWCSException(map, NULL, NULL, params->version);
+  } else if (MS_RENDERER_PLUGIN(map->outputformat)) {
+    image = msImageCreate(map->width, map->height, map->outputformat,
+                          map->web.imagepath, map->web.imageurl, map->resolution,
+                          map->defresolution, &map->imagecolor);
+  } else if (MS_RENDERER_RAWDATA(map->outputformat)) {
+    image = msImageCreate(map->width, map->height, map->outputformat,
+                          map->web.imagepath, map->web.imageurl, map->resolution,
+                          map->defresolution, &map->imagecolor);
+  } else {
+    msFree(bandlist);
+    msWCSClearCoverageMetadata20(&cm);
+    msSetError(MS_WCSERR, "Map outputformat not supported for WCS!",
+               "msWCSGetCoverage20()");
+    return msWCSException(map, NULL, NULL, params->version);
+  }
 
-            msProjectRect(&(map->projection), &outputProj, &bbox);
-            msFreeProjection(&(map->projection));
-            map->projection = outputProj;
+  if (image == NULL) {
+    msFree(bandlist);
+    msWCSClearCoverageMetadata20(&cm);
+    return msWCSException(map, NULL, NULL, params->version);
+  }
+
+  /* Actually produce the "grid". */
+  if( MS_RENDERER_RAWDATA(map->outputformat) ) {
+    status = msDrawRasterLayerLow( map, layer, image, NULL );
+  } else {
+    rasterBufferObj rb;
+    MS_IMAGE_RENDERER(image)->getRasterBufferHandle(image,&rb);
+    status = msDrawRasterLayerLow( map, layer, image, &rb );
+  }
+
+  if( status != MS_SUCCESS ) {
+    msFree(bandlist);
+    msFreeImage(image);
+    msWCSClearCoverageMetadata20(&cm);
+    return msWCSException(map, NULL, NULL, params->version );
+  }
 
-            /* recalculate resolutions, needed if UOM changes (e.g: deg -> m) */
-            params->resolutionX = (bbox.maxx - bbox.minx) / params->width;
-            params->resolutionY = (bbox.maxy - bbox.miny) / params->height;
-        }
-    }
+  /* GML+Image */
+  /* Embed the image into multipart message */
+  if(params->multipart == MS_TRUE) {
+    xmlDocPtr psDoc = NULL;       /* document pointer */
+    xmlNodePtr psRootNode, psRangeSet, psFile, psRangeParameters;
+    xmlNsPtr psGmlNs = NULL,
+             psGmlcovNs = NULL,
+             psSweNs = NULL,
+             psXLinkNs = NULL;
+    wcs20coverageMetadataObj tmpCm;
+    char *srs_uri, *default_filename;
+    const char *filename;
+    char *file_ref, *role;
+    int length = 0, swapAxes;
+
+    /* Create Document  */
+    psDoc = xmlNewDoc(BAD_CAST "1.0");
+    psRootNode = xmlNewNode(NULL, BAD_CAST MS_WCS_GML_COVERAGETYPE_RECTIFIED_GRID_COVERAGE);
+    xmlDocSetRootElement(psDoc, psRootNode);
 
-    /* set the bounding box as new map extent */
-    map->extent = bbox;
-    map->width = params->width;
-    map->height = params->height;
+    msWCSPrepareNamespaces20(psDoc, psRootNode, map);
 
-    /* Are we exceeding the MAXSIZE limit on result size? */
-    if(map->width > map->maxsize || map->height > map->maxsize )
-    {
-        msSetError(MS_WCSERR, "Raster size out of range, width and height of "
-                              "resulting coverage must be no more than MAXSIZE=%d.",
-                              "msWCSGetCoverage20()", map->maxsize);
+    psGmlNs    = xmlSearchNs(psDoc, psRootNode, BAD_CAST MS_OWSCOMMON_GML_NAMESPACE_PREFIX);
+    psGmlcovNs = xmlSearchNs(psDoc, psRootNode, BAD_CAST MS_OWSCOMMON_GMLCOV_NAMESPACE_PREFIX);
+    psSweNs    = xmlSearchNs(psDoc, psRootNode, BAD_CAST MS_OWSCOMMON_SWE_NAMESPACE_PREFIX);
+    xmlSearchNs(psDoc, psRootNode, BAD_CAST MS_OWSCOMMON_WCS_NAMESPACE_PREFIX);
+    psXLinkNs  = xmlSearchNs(psDoc, psRootNode, BAD_CAST MS_OWSCOMMON_W3C_XLINK_NAMESPACE_PREFIX);
 
-        return msWCSException(map, "InvalidParameterValue", 
-                                   "size", params->version);
-    }
+    xmlNewNsProp(psRootNode, psGmlNs, BAD_CAST "id", BAD_CAST layer->name);
 
-    /* Mapserver only supports square cells */
-    if (params->resolutionX <= params->resolutionY)
-        map->cellsize = params->resolutionX;
-    else
-        map->cellsize = params->resolutionY;
+    xmlSetNs(psRootNode, psGmlcovNs);
 
-    msDebug("msWCSGetCoverage20(): Set parameters from original"
-                   "data. Width: %d, height: %d, cellsize: %f, extent: %f,%f,%f,%f\n",
-               map->width, map->height, map->cellsize, map->extent.minx,
-               map->extent.miny, map->extent.maxx, map->extent.maxy);
+    srs_uri = msOWSGetProjURI(&map->projection, NULL, "CO", 1);
 
-    if (!params->format)
-    {
-        msSetError(MS_WCSERR, "Required parameter FORMAT was not supplied.",
-                "msWCSGetCoverage20()");
-        return msWCSException(map, "MissingParameterValue", "format",
-                params->version);
-    }
+    tmpCm = cm;
+    tmpCm.extent = map->extent;
+    tmpCm.xsize = map->width;
+    tmpCm.ysize = map->height;
+    strlcpy(tmpCm.srs_uri, srs_uri, sizeof(tmpCm.srs_uri));
 
-    /*    make sure layer is on   */
-    layer->status = MS_ON;
+    tmpCm.xresolution = map->gt.geotransform[1];
+    tmpCm.yresolution = map->gt.geotransform[5];
 
-    msMapComputeGeotransform(map);
+    tmpCm.extent.minx = MIN(map->gt.geotransform[0], map->gt.geotransform[0] + map->width * tmpCm.xresolution);
+    tmpCm.extent.miny = MIN(map->gt.geotransform[3], map->gt.geotransform[3] + map->height * tmpCm.yresolution);
+    tmpCm.extent.maxx = MAX(map->gt.geotransform[0], map->gt.geotransform[0] + map->width * tmpCm.xresolution);
+    tmpCm.extent.maxy = MAX(map->gt.geotransform[3], map->gt.geotransform[3] + map->height * tmpCm.yresolution);
 
-    /*    fill in bands rangeset info, if required.  */
-    //msWCSSetDefaultBandsRangeSetInfo(params, &cm, layer);
-    //msDebug("Bandcount: %d\n", cm.bandcount);
+    swapAxes = msWCSSwapAxes20(srs_uri);
+    msFree(srs_uri);
 
-    msApplyDefaultOutputFormats(map);
+    /* Setup layer information  */
+    msWCSCommon20_CreateBoundedBy(layer, &tmpCm, psGmlNs, psRootNode, &(map->projection), swapAxes);
+    msWCSCommon20_CreateDomainSet(layer, &tmpCm, psGmlNs, psRootNode, &(map->projection), swapAxes);
 
-    if (msGetOutputFormatIndex(map, params->format) == -1)
-    {
-        msSetError(MS_WCSERR, "Unrecognized value '%s' for the FORMAT parameter.",
-                "msWCSGetCoverage20()", params->format);
-        return msWCSException(map, "InvalidParameterValue", "format",
-                params->version);
-    }
+    psRangeSet = xmlNewChild(psRootNode, psGmlNs, BAD_CAST "rangeSet", NULL);
+    psFile     = xmlNewChild(psRangeSet, psGmlNs, BAD_CAST "File", NULL);
 
-    /* create a temporary outputformat (we likely will need to tweak parts) */
-    format = msCloneOutputFormat(msSelectOutputFormat(map, params->format));
-    msApplyOutputFormat(&(map->outputformat), format, MS_NOOVERRIDE,
-            MS_NOOVERRIDE, MS_NOOVERRIDE);
+    /* TODO: wait for updated specifications */
+    psRangeParameters = xmlNewChild(psFile, psGmlNs, BAD_CAST "rangeParameters", NULL);
 
-    if(msWCSGetCoverage20_GetBands(map, layer, params, &cm, &bandlist) != MS_SUCCESS)
-    {
-        return msWCSException(map, "InvalidParameterValue", "rangesubset",
-                params->version);
-    }
-    msLayerSetProcessingKey(layer, "BANDS", bandlist);
-    snprintf(numbands, sizeof(numbands), "%d", msCountChars(bandlist, ',')+1);
-    msSetOutputFormatOption(map->outputformat, "BAND_COUNT", numbands);
+    default_filename = msStrdup("out.");
+    default_filename = msStringConcatenate(default_filename, MS_IMAGE_EXTENSION(image->format));
 
-    /* check for the interpolation */
-    /* Defaults to NEAREST */
-    if(params->interpolation != NULL)
-    {
-        if(EQUALN(params->interpolation,"NEAREST",7))
-        {
-            msLayerSetProcessingKey(layer, "RESAMPLE", "NEAREST");
-        }
-        else if(EQUAL(params->interpolation,"BILINEAR"))
-        {
-            msLayerSetProcessingKey(layer, "RESAMPLE", "BILINEAR");
-        }
-        else if(EQUAL(params->interpolation,"AVERAGE"))
-        {
-            msLayerSetProcessingKey(layer, "RESAMPLE", "AVERAGE");
-        }
-        else
-        {
-            msSetError( MS_WCSERR, "'%s' specifies an unsupported interpolation method.",
-                    "msWCSGetCoverage20()", params->interpolation );
-            return msWCSException(map, "InvalidParameterValue", "interpolation", params->version);
-        }
-    }
-    else
-    {
-        msLayerSetProcessingKey(layer, "RESAMPLE", "NEAREST");
-    }
+    filename = msGetOutputFormatOption(image->format, "FILENAME", default_filename);
+    length = strlen("cid:coverage/") + strlen(filename) + 1;
+    file_ref = msSmallMalloc(length);
+    strlcpy(file_ref, "cid:coverage/", length);
+    strlcat(file_ref, filename, length);
+    msFree(default_filename);
 
-    /* since the dataset is only used in one layer, set it to be    */
-    /* closed after drawing the layer. This normally defaults to    */
-    /* DEFER and will produce a memory leak, because the dataset    */
-    /* will not be closed.                                          */
-    if( msLayerGetProcessingKey(layer, "CLOSE_CONNECTION") == NULL )
-    {
-        msLayerSetProcessingKey(layer, "CLOSE_CONNECTION", "NORMAL");
+    if(EQUAL(MS_IMAGE_MIME_TYPE(map->outputformat), "image/tiff")) {
+      length = strlen(MS_WCS_20_PROFILE_GML_GEOTIFF) + 1;
+      role = msSmallMalloc(length);
+      strlcpy(role, MS_WCS_20_PROFILE_GML_GEOTIFF, length);
+    } else {
+      length = strlen(MS_IMAGE_MIME_TYPE(map->outputformat)) + 1;
+      role = msSmallMalloc(length);
+      strlcpy(role, MS_IMAGE_MIME_TYPE(map->outputformat), length);
     }
 
-    /* create the image object  */
-    if (!map->outputformat)
-    {
-        msSetError(MS_WCSERR, "The map outputformat is missing!",
-                "msWCSGetCoverage20()");
-        return msWCSException(map, NULL, NULL, params->version);
-    }
-    else if (MS_RENDERER_PLUGIN(map->outputformat))
-    {
-        image = msImageCreate(map->width, map->height, map->outputformat,
-                map->web.imagepath, map->web.imageurl, map->resolution,
-                map->defresolution, &map->imagecolor); 
-    } 
-    else if (MS_RENDERER_RAWDATA(map->outputformat)) 
-    { 
-        image = msImageCreate(map->width, map->height, map->outputformat,
-                map->web.imagepath, map->web.imageurl, map->resolution,
-                map->defresolution, &map->imagecolor);
-    }
-    else
-    {
-        msFree(bandlist);
-        msSetError(MS_WCSERR, "Map outputformat not supported for WCS!",
-                "msWCSGetCoverage20()");
-        return msWCSException(map, NULL, NULL, params->version);
-    }
+    xmlNewNsProp(psRangeParameters, psXLinkNs, BAD_CAST "href", BAD_CAST file_ref);
+    xmlNewNsProp(psRangeParameters, psXLinkNs, BAD_CAST "role", BAD_CAST role);
+    xmlNewNsProp(psRangeParameters, psXLinkNs, BAD_CAST "arcrole", BAD_CAST "fileReference");
 
-    if (image == NULL)
-    {
-        msFree(bandlist);
-        return msWCSException(map, NULL, NULL, params->version);
-    }
+    xmlNewChild(psFile, psGmlNs, BAD_CAST "fileReference", BAD_CAST file_ref);
+    xmlNewChild(psFile, psGmlNs, BAD_CAST "fileStructure", NULL);
+    xmlNewChild(psFile, psGmlNs, BAD_CAST "mimeType", BAD_CAST MS_IMAGE_MIME_TYPE(map->outputformat));
 
-    /* Actually produce the "grid". */
-    if( MS_RENDERER_RAWDATA(map->outputformat) )
-    {
-        status = msDrawRasterLayerLow( map, layer, image, NULL );
-    }
-    else
-    {
-        rasterBufferObj rb;
-        MS_IMAGE_RENDERER(image)->getRasterBufferHandle(image,&rb);
-        status = msDrawRasterLayerLow( map, layer, image, &rb );
-    }
+    msWCSCommon20_CreateRangeType(layer, &cm, bandlist, psGmlNs, psGmlcovNs, psSweNs, psXLinkNs, psRootNode);
 
-    if( status != MS_SUCCESS )
-    {
-        msFree(bandlist);
-        msFreeImage(image);
-        return msWCSException(map, NULL, NULL, params->version );
-    }
+    msIO_setHeader("Content-Type","multipart/related; boundary=wcs");
+    msIO_sendHeaders();
+    msIO_printf("\r\n--wcs\r\n");
 
-    /* GML+Image */
-    /* Embed the image into multipart message */
-    if(params->multipart == MS_TRUE)
-    {
-        xmlDocPtr psDoc = NULL;       /* document pointer */
-        xmlNodePtr psRootNode, psRangeSet, psFile, psRangeParameters;
-        xmlNsPtr psGmlNs = NULL,
-            psGmlcovNs = NULL,
-            psSweNs = NULL,
-            psWcsNs = NULL,
-            psXLinkNs = NULL;
-        wcs20coverageMetadataObj tmpCm;
-        char *srs_uri, *default_filename;
-        const char *filename;
-        char *file_ref;
-        int length = 0, swapAxes;
-
-        /* Create Document  */
-        psDoc = xmlNewDoc(BAD_CAST "1.0");
-        psRootNode = xmlNewNode(NULL, BAD_CAST MS_WCS_GML_COVERAGETYPE_RECTIFIED_GRID_COVERAGE);
-        xmlDocSetRootElement(psDoc, psRootNode);
-
-        msWCSPrepareNamespaces20(psDoc, psRootNode, map);
-
-        psGmlNs    = xmlSearchNs(psDoc, psRootNode, BAD_CAST MS_OWSCOMMON_GML_NAMESPACE_PREFIX);
-        psGmlcovNs = xmlSearchNs(psDoc, psRootNode, BAD_CAST MS_OWSCOMMON_GMLCOV_NAMESPACE_PREFIX);
-        psSweNs    = xmlSearchNs(psDoc, psRootNode, BAD_CAST MS_OWSCOMMON_SWE_NAMESPACE_PREFIX);
-        psWcsNs    = xmlSearchNs(psDoc, psRootNode, BAD_CAST MS_OWSCOMMON_WCS_NAMESPACE_PREFIX);
-        psXLinkNs  = xmlSearchNs(psDoc, psRootNode, BAD_CAST MS_OWSCOMMON_W3C_XLINK_NAMESPACE_PREFIX);
-
-        xmlNewNsProp(psRootNode, psGmlNs, BAD_CAST "id", BAD_CAST layer->name);
-
-        xmlSetNs(psRootNode, psGmlcovNs);
-
-        srs_uri = msOWSGetProjURI(&map->projection, NULL, "CO", 1);
-
-        tmpCm = cm;
-        tmpCm.extent = map->extent;
-        tmpCm.xsize = map->width;
-        tmpCm.ysize = map->height;
-        strlcpy(tmpCm.srs_uri, srs_uri, sizeof(tmpCm.srs_uri));
-        
-        tmpCm.xresolution = map->gt.geotransform[1];
-        tmpCm.yresolution = map->gt.geotransform[5];
-        
-        tmpCm.extent.minx = MIN(map->gt.geotransform[0], map->gt.geotransform[0] + map->width * tmpCm.xresolution);
-        tmpCm.extent.miny = MIN(map->gt.geotransform[3], map->gt.geotransform[3] + map->height * tmpCm.yresolution);
-        tmpCm.extent.maxx = MAX(map->gt.geotransform[0], map->gt.geotransform[0] + map->width * tmpCm.xresolution);
-        tmpCm.extent.maxy = MAX(map->gt.geotransform[3], map->gt.geotransform[3] + map->height * tmpCm.yresolution);
-
-        swapAxes = msWCSSwapAxes20(srs_uri);
-        msFree(srs_uri);
-
-        /* Setup layer information  */
-        msWCSCommon20_CreateBoundedBy(layer, &tmpCm, psGmlNs, psRootNode, &(map->projection), swapAxes);
-        msWCSCommon20_CreateDomainSet(layer, &tmpCm, psGmlNs, psRootNode, &(map->projection), swapAxes);
-
-        psRangeSet = xmlNewChild(psRootNode, psGmlNs, BAD_CAST "rangeSet", NULL);
-        psFile     = xmlNewChild(psRangeSet, psGmlNs, BAD_CAST "File", NULL);
-
-        /* TODO: wait for updated specifications */
-        psRangeParameters = xmlNewChild(psFile, psGmlNs, BAD_CAST "rangeParameters", NULL);
-
-        default_filename = msStrdup("out.");
-        default_filename = msStringConcatenate(default_filename, MS_IMAGE_EXTENSION(image->format));
-
-        filename = msGetOutputFormatOption(image->format, "FILENAME", default_filename);
-        length = strlen("coverage/") + strlen(filename) + 1;
-        file_ref = msSmallMalloc(length);
-        strlcpy(file_ref, "coverage/", length);
-        strlcat(file_ref, filename, length);
-
-        xmlNewNsProp(psRangeParameters, psXLinkNs, BAD_CAST "href", BAD_CAST file_ref);
-        xmlNewNsProp(psRangeParameters, psXLinkNs, BAD_CAST "role", BAD_CAST MS_IMAGE_MIME_TYPE(map->outputformat));
-        xmlNewNsProp(psRangeParameters, psXLinkNs, BAD_CAST "arcrole", BAD_CAST "fileReference");
-
-        xmlNewChild(psFile, psGmlNs, BAD_CAST "fileReference", BAD_CAST file_ref);
-        xmlNewChild(psFile, psGmlNs, BAD_CAST "fileStructure", NULL);
-        xmlNewChild(psFile, psGmlNs, BAD_CAST "mimeType", BAD_CAST MS_IMAGE_MIME_TYPE(map->outputformat));
-
-        msWCSCommon20_CreateRangeType(layer, &cm, bandlist, psGmlNs, psGmlcovNs, psSweNs, psXLinkNs, psRootNode);
-
-        msIO_printf( "Content-Type: multipart/mixed; boundary=wcs%c%c"
-                     "--wcs\n", 10, 10);
-
-        msWCSWriteDocument20(map, psDoc);
-        msWCSWriteFile20(map, image, params, 1);
-
-        msFree(file_ref);
-        xmlFreeDoc(psDoc);
-        xmlCleanupParser();
-    }
-    /* just print out the file without gml */
-    else
-    {
-        msWCSWriteFile20(map, image, params, 0);
-    }
+    msWCSWriteDocument20(map, psDoc);
+    msWCSWriteFile20(map, image, params, 1);
 
-    msFree(bandlist);
-    msWCSClearCoverageMetadata20(&cm);
-    msFreeImage(image);
-    return MS_SUCCESS;
+    msFree(file_ref);
+    msFree(role);
+    xmlFreeDoc(psDoc);
+    xmlCleanupParser();
+  /* just print out the file without gml */
+  } else {
+    msWCSWriteFile20(map, image, params, 0);
+  }
+
+  msFree(bandlist);
+  msWCSClearCoverageMetadata20(&cm);
+  msFreeImage(image);
+  return MS_SUCCESS;
 }
 
 #endif /* defined(USE_LIBXML2) */
 
-/************************************************************************/
-/*                   msWCSDispatch20()                                  */
-/*                                                                      */
-/*      Dispatches a mapserver request. First the cgiRequest is         */
-/*      parsed. Afterwards version and service are beeing checked.      */
-/*      If they aren't compliant, MS_DONE is returned. Otherwise        */
-/*      either GetCapabilities, DescribeCoverage or GetCoverage         */
-/*      operations are executed.                                        */
-/************************************************************************/
-
-int msWCSDispatch20(mapObj *map, cgiRequestObj *request, owsRequestObj *ows_request)
-{
-    wcs20ParamsObjPtr params = NULL;
-    int returnValue = MS_FAILURE, status;
-
-    params = msWCSCreateParamsObj20();
-    status = msWCSParseRequest20(request, params);
-
-#if defined(USE_LIBXML2)
-    if(status == MS_FAILURE)
-    {
-        msDebug("msWCSDispatch20(): Parse error occurred.\n");
-        msWCSException20(map, "InvalidParameterValue", "request", "2.0.0" );
-        msWCSFreeParamsObj20(params);
-        return MS_FAILURE;
-    }
-    else if(status == MS_DONE)
-    {
-        /* could not be parsed, but no error */
-        /* continue for now...               */
-    }
-
-    /* first check if Service is WCS */
-    if (params->service == NULL
-        || !EQUAL(params->service, "WCS"))
-    {
-        /* The service is not WCS, exit with MS_DONE */
-        msDebug("msWCSDispatch20(): wrong service (%s)\n",
-                (params->service != NULL) ? params->service : "none");
-        msWCSFreeParamsObj20(params);
-        msResetErrorList();
-        return MS_DONE;
-    }
-
-    /* check if request is set */
-    if(params->request == NULL)
-    {
-        /* If service is WCS, a request must be set. */
-        /* Therefore, exit with a failure.           */
-        msSetError(MS_WCSERR, "Missing REQUEST parameter",
-                "msWCSDispatch20()");
-        msWCSException20(map, "MissingParameterValue", "request",
-                params->version );
-        msWCSFreeParamsObj20(params); /* clean up */
-        return MS_FAILURE;
-    }
-
-    /* Handle version negotiation for GetCapabilities. */
-    /* Only if accepted versions are given, and not a  */
-    /* predefined version.                             */
-    if (EQUAL(params->request, "GetCapabilities")
-        && params->accept_versions != NULL
-        && params->version         == NULL)
-    {
-        int i, highest_version = 0;
-        char version_string[OWS_VERSION_MAXLEN];
-        for(i = 0; params->accept_versions[i] != NULL; ++i)
-        {
-            int version = msOWSParseVersionString(params->accept_versions[i]);
-            if (version == OWS_VERSION_BADFORMAT)
-            {
-                msWCSException20(map, "InvalidParameterValue",
-                        "request", "2.0.0" );
-                msWCSFreeParamsObj20(params);
-                return MS_FAILURE;
-            }
-            if(version > highest_version)
-            {
-                highest_version = version;
-            }
-        }
-        msOWSGetVersionString(highest_version, version_string);
-        params->version = msStrdup(version_string);
-    }
-
-    /* Now the version has to be set */
-    if(params->version == NULL
-        || !EQUAL(params->version, "2.0.0"))
-    {
-        msDebug("msWCSDispatch20(): version and service are not compliant with WCS 2.0.0\n");
-        msWCSFreeParamsObj20(params);
-        msResetErrorList();
-        return MS_DONE;
-    }
-
-    msOWSRequestLayersEnabled(map, "C", params->request, ows_request);
-    if (ows_request->numlayers == 0)
-    {
-        msSetError(MS_WCSERR, "WCS request not enabled. Check wcs/ows_enable_request settings.", "msWCSDispatch20()");
-        msWCSException20(map, "InvalidParameterValue", "request",
-                         params->version );
-        msWCSFreeParamsObj20(params); /* clean up */
-        return MS_FAILURE;
-    }
-
-    /* check if all layer names are valid NCNames */
-    {
-        int i;
-        for(i = 0; i < map->numlayers; ++i)
-        {
-            if(!msWCSIsLayerSupported(map->layers[i]))
-                continue;
-
-            if(msStringIsNCName(map->layers[i]->name) == MS_FALSE)
-            {
-                msSetError(MS_WCSERR, "Layer name '%s' is not a valid NCName.",
-                        "msWCSDescribeCoverage20()", map->layers[i]->name);
-                msWCSFreeParamsObj20(params);
-                return msWCSException(map, "mapserv", "Internal", "2.0.0");
-            }
-        }
-    }
-
-    /* Call operation specific functions */
-    if (EQUAL(params->request, "GetCapabilities"))
-    {
-        returnValue = msWCSGetCapabilities20(map, request, params, ows_request);
-    }
-    else if (EQUAL(params->request, "DescribeCoverage"))
-    {
-        returnValue = msWCSDescribeCoverage20(map, params, ows_request);
-    }
-    else if (EQUAL(params->request, "GetCoverage"))
-    {
-        returnValue = msWCSGetCoverage20(map, request, params, ows_request);
-    }
-    else
-    {
-        msSetError(MS_WCSERR, "Invalid request '%s'.",
-                "msWCSDispatch20()", params->request);
-        returnValue = msWCSException20(map, "InvalidParameterValue",
-                "request", params->version);
-    }
-    /* clean up */
-    msWCSFreeParamsObj20(params);
-    return returnValue;
-
-#else /* defined(USE_LIBXML2) */
-    if(params->service && params->version &&
-            EQUAL(params->service, "WCS") && EQUAL(params->version, "2.0.0"))
-    {
-        msSetError(MS_WCSERR, "WCS 2.0.0 needs mapserver to be compiled with libxml2.", "msWCSDispatch20()");
-        return msWCSException(map, "mapserv", "NoApplicableCode", "1.0.0");
-    }
-    else
-    {
-        return MS_DONE;
-    }
-#endif /* defined(USE_LIBXML2) */
-}
-
 #endif /* defined(USE_WCS_SVR) */
diff --git a/mapwfs.c b/mapwfs.c
index 4c6f87a..1b1d10b 100644
--- a/mapwfs.c
+++ b/mapwfs.c
@@ -14,21 +14,21 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
+ *
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  ****************************************************************************/
 
 #include "mapserver.h"
 
-MS_CVSID("$Id$")
+
 
 #if defined(USE_WFS_SVR)
 
@@ -52,230 +52,219 @@ MS_CVSID("$Id$")
 int msWFSException(mapObj *map, const char *locator, const char *code,
                    const char *version )
 {
-    const char *encoding;
-    char *schemalocation = NULL;
-    /* In WFS, exceptions are always XML.
-    */
+  const char *encoding;
+  char *schemalocation = NULL;
+  /* In WFS, exceptions are always XML.
+  */
 
-    if( version == NULL )
-      version = "1.1.0";
+  if( version == NULL )
+    version = "1.1.0";
 
-    if( msOWSParseVersionString(version) >= OWS_1_1_0 )
-      return msWFSException11( map, locator, code, version );
+  if( msOWSParseVersionString(version) >= OWS_1_1_0 )
+    return msWFSException11( map, locator, code, version );
 
-    encoding = msOWSLookupMetadata(&(map->web.metadata), "FO", "encoding");
-    if (encoding)
-        msIO_printf("Content-type: text/xml; charset=%s%c%c", encoding,10,10);
-    else
-        msIO_printf("Content-type: text/xml%c%c",10,10);
-
-    msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "FO", "encoding", OWS_NOERR,
-                "<?xml version='1.0' encoding=\"%s\" ?>\n", "ISO-8859-1");
-
-    msIO_printf("<ServiceExceptionReport ");
-    msIO_printf("version=\"1.2.0\" ");
-    msIO_printf("xmlns=\"http://www.opengis.net/ogc\" ");
-    msIO_printf("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ");
-    schemalocation = msEncodeHTMLEntities(msOWSGetSchemasLocation(map));
-    msIO_printf("xsi:schemaLocation=\"http://www.opengis.net/ogc %s/wfs/1.0.0/OGC-exception.xsd\">\n", schemalocation);
-    free(schemalocation);
-    msIO_printf("  <ServiceException code=\"%s\" locator=\"%s\">\n", code, locator);
-    /* Optional <Locator> element currently unused. */
-    /* msIO_printf("    <Message>\n"); */
-    msWriteErrorXML(stdout);
-    /* msIO_printf("    </Message>\n"); */
-    msIO_printf("  </ServiceException>\n");
-    msIO_printf("</ServiceExceptionReport>\n");
-
-    return MS_FAILURE; /* so we can call 'return msWFSException();' anywhere */
+  encoding = msOWSLookupMetadata(&(map->web.metadata), "FO", "encoding");
+  if (encoding)
+    msIO_setHeader("Content-Type","text/xml; charset=%s", encoding);
+  else
+    msIO_setHeader("Content-Type","text/xml");
+  msIO_sendHeaders();
+
+  msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "FO", "encoding", OWS_NOERR,
+                           "<?xml version='1.0' encoding=\"%s\" ?>\n", "ISO-8859-1");
+
+  msIO_printf("<ServiceExceptionReport ");
+  msIO_printf("version=\"1.2.0\" ");
+  msIO_printf("xmlns=\"http://www.opengis.net/ogc\" ");
+  msIO_printf("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ");
+  schemalocation = msEncodeHTMLEntities(msOWSGetSchemasLocation(map));
+  msIO_printf("xsi:schemaLocation=\"http://www.opengis.net/ogc %s/wfs/1.0.0/OGC-exception.xsd\">\n", schemalocation);
+  free(schemalocation);
+  msIO_printf("  <ServiceException code=\"%s\" locator=\"%s\">\n", code, locator);
+  /* Optional <Locator> element currently unused. */
+  /* msIO_printf("    <Message>\n"); */
+  msWriteErrorXML(stdout);
+  /* msIO_printf("    </Message>\n"); */
+  msIO_printf("  </ServiceException>\n");
+  msIO_printf("</ServiceExceptionReport>\n");
+
+  return MS_FAILURE; /* so we can call 'return msWFSException();' anywhere */
 }
 
 /*
 ** Helper function to build a list of output formats.
-** 
+**
 ** Given a layer it will return all formats valid for that layer, otherwise
-** all formats permitted on layers in the map are returned.  The string 
+** all formats permitted on layers in the map are returned.  The string
 ** returned should be freed by the caller.
 */
 
-char *msWFSGetOutputFormatList(mapObj *map, layerObj *layer, 
+char *msWFSGetOutputFormatList(mapObj *map, layerObj *layer,
                                const char *version )
 {
-    int i, got_map_list = 0;
-    static const int out_list_size = 20000;
-    char *out_list = (char*) msSmallCalloc(1,out_list_size);
+  int i, got_map_list = 0;
+  static const int out_list_size = 20000;
+  char *out_list = (char*) msSmallCalloc(1,out_list_size);
 
-    if( strncasecmp(version,"1.0",3) != 0 )
-        strcpy(out_list,"text/xml; subtype=gml/3.1.1");
-    else
-        strcpy(out_list,"GML2");
+  if( strncasecmp(version,"1.0",3) != 0 )
+    strcpy(out_list,"text/xml; subtype=gml/3.1.1");
+  else
+    strcpy(out_list,"GML2");
 
-    for( i = 0; i < map->numlayers; i++ )
-    {
-        const char *format_list;
-        layerObj *lp;
-        int j, n;
-        char **tokens;
-        
-        lp = GET_LAYER(map, i);
-        if( layer != NULL && layer != lp )
-            continue;
-        
-        format_list = msOWSLookupMetadata(&(lp->metadata), 
-                                          "F","getfeature_formatlist");
-
-        if( format_list == NULL && !got_map_list )
-        {
-            format_list = msOWSLookupMetadata(&(map->web.metadata), 
-                                              "F","getfeature_formatlist");
-            got_map_list = 1;
-        }
+  for( i = 0; i < map->numlayers; i++ ) {
+    const char *format_list;
+    layerObj *lp;
+    int j, n;
+    char **tokens;
 
-        if( format_list == NULL )
-            continue;
-
-        n = 0;
-        tokens = msStringSplit(format_list, ',', &n);
-        
-        for( j = 0; j < n; j++ )
-        {
-            int iformat;
-            const char *fname, *hit;
-            outputFormatObj *format_obj;
-            
-            msStringTrim( tokens[j] );
-            iformat = msGetOutputFormatIndex(map,tokens[j]);
-            if( iformat < 0 )
-                continue;
+    lp = GET_LAYER(map, i);
+    if( layer != NULL && layer != lp )
+      continue;
 
-            format_obj = map->outputformatlist[iformat];
-            
-            fname = format_obj->name;
-            if( strncasecmp(version,"1.0",3) != 0 
-                && format_obj->mimetype != NULL )
-                fname = format_obj->mimetype;
+    format_list = msOWSLookupMetadata(&(lp->metadata),
+                                      "F","getfeature_formatlist");
 
-            hit = strstr(out_list,fname);
-            if( hit != NULL 
-                && (hit[strlen(fname)] == '\0' || hit[strlen(fname)] == ','))
-                continue;
+    if( format_list == NULL && !got_map_list ) {
+      format_list = msOWSLookupMetadata(&(map->web.metadata),
+                                        "F","getfeature_formatlist");
+      got_map_list = 1;
+    }
 
-            if( strlen(out_list) + strlen(fname)+3 < out_list_size )
-            {
-                strcat( out_list, "," );
-                strcat( out_list, fname );
-            }
-            else
-                break;
-        }
+    if( format_list == NULL )
+      continue;
+
+    n = 0;
+    tokens = msStringSplit(format_list, ',', &n);
+
+    for( j = 0; j < n; j++ ) {
+      int iformat;
+      const char *fname, *hit;
+      outputFormatObj *format_obj;
+
+      msStringTrim( tokens[j] );
+      iformat = msGetOutputFormatIndex(map,tokens[j]);
+      if( iformat < 0 )
+        continue;
 
-        msFreeCharArray( tokens, n );
+      format_obj = map->outputformatlist[iformat];
+
+      fname = format_obj->name;
+      if( strncasecmp(version,"1.0",3) != 0
+          && format_obj->mimetype != NULL )
+        fname = format_obj->mimetype;
+
+      hit = strstr(out_list,fname);
+      if( hit != NULL
+          && (hit[strlen(fname)] == '\0' || hit[strlen(fname)] == ','))
+        continue;
+
+      if( strlen(out_list) + strlen(fname)+3 < out_list_size ) {
+        strcat( out_list, "," );
+        strcat( out_list, fname );
+      } else
+        break;
     }
 
-    return out_list;
+    msFreeCharArray( tokens, n );
+  }
+
+  return out_list;
 }
 
 /*
 **
 */
 static void msWFSPrintRequestCap(const char *wmtver, const char *request,
-                                 const char *script_url, 
-                                 const char *format_tag, 
+                                 const char *script_url,
+                                 const char *format_tag,
                                  const char *formats_list)
 {
-    msIO_printf("    <%s>\n", request);
+  msIO_printf("    <%s>\n", request);
 
-    /* We expect to receive a NULL-terminated args list of formats */
-    if (format_tag != NULL)
-    {
-        int i, n;
-        char **tokens;
+  /* We expect to receive a NULL-terminated args list of formats */
+  if (format_tag != NULL) {
+    int i, n;
+    char **tokens;
 
-        n = 0;
-        tokens = msStringSplit(formats_list, ',', &n);
+    n = 0;
+    tokens = msStringSplit(formats_list, ',', &n);
 
-        msIO_printf("      <%s>\n", format_tag);
+    msIO_printf("      <%s>\n", format_tag);
 
-        for( i = 0; i < n; i++ )
-        {
-            msIO_printf("        <%s/>\n", tokens[i] );
-        }
+    for( i = 0; i < n; i++ ) {
+      msIO_printf("        <%s/>\n", tokens[i] );
+    }
 
-        msFreeCharArray( tokens, n );
+    msFreeCharArray( tokens, n );
 
-        msIO_printf("      </%s>\n", format_tag);
-    }
+    msIO_printf("      </%s>\n", format_tag);
+  }
 
-    msIO_printf("      <DCPType>\n");
-    msIO_printf("        <HTTP>\n");
-    msIO_printf("          <Get onlineResource=\"%s\" />\n", script_url);
-    msIO_printf("        </HTTP>\n");
-    msIO_printf("      </DCPType>\n");
-    msIO_printf("      <DCPType>\n");
-    msIO_printf("        <HTTP>\n");
-    msIO_printf("          <Post onlineResource=\"%s\" />\n", script_url);
-    msIO_printf("        </HTTP>\n");
-    msIO_printf("      </DCPType>\n");
+  msIO_printf("      <DCPType>\n");
+  msIO_printf("        <HTTP>\n");
+  msIO_printf("          <Get onlineResource=\"%s\" />\n", script_url);
+  msIO_printf("        </HTTP>\n");
+  msIO_printf("      </DCPType>\n");
+  msIO_printf("      <DCPType>\n");
+  msIO_printf("        <HTTP>\n");
+  msIO_printf("          <Post onlineResource=\"%s\" />\n", script_url);
+  msIO_printf("        </HTTP>\n");
+  msIO_printf("      </DCPType>\n");
 
 
-    msIO_printf("    </%s>\n", request);
+  msIO_printf("    </%s>\n", request);
 }
 
 
 /* msWFSLocateSRSInList()
 **
-** Utility function to check if a space separated list contains  the one passed in argument. 
+** Utility function to check if a space separated list contains  the one passed in argument.
 **  The list comes normaly from ows_srs metadata, and is expected to use the simple EPSG notation
 ** (EPSG:4326 ESPG:42304 ...). The srs comes from the query string and can either
 ** be of simple EPSG format or using gc:def:crs:EPSG:xxx format
 */
 int msWFSLocateSRSInList(const char *pszList, const char *srs)
 {
-    int nTokens,i;
-    char **tokens = NULL;
-    int bFound = MS_FALSE;
-    char epsg_string[100];
-    const char *code;
-
-    if (!pszList || !srs)
-      return MS_FALSE;
-
-    if (strncasecmp(srs, "EPSG:",5) == 0)
-      code = srs+5;
-    else if (strncasecmp(srs, "urn:ogc:def:crs:EPSG:",21) == 0)
-    {
-        if (srs[21] == ':')
-          code = srs+21;
-        else
-          code = srs+20;
-
-         while( *code != ':' && *code != '\0')
-           code++;
-         if( *code == ':' )
-           code++;
-    }
-    else if (strncasecmp(srs, "urn:EPSG:geographicCRS:",23) == 0)
-      code = srs + 23;
+  int nTokens,i;
+  char **tokens = NULL;
+  int bFound = MS_FALSE;
+  char epsg_string[100];
+  const char *code;
+
+  if (!pszList || !srs)
+    return MS_FALSE;
+
+  if (strncasecmp(srs, "EPSG:",5) == 0)
+    code = srs+5;
+  else if (strncasecmp(srs, "urn:ogc:def:crs:EPSG:",21) == 0) {
+    if (srs[21] == ':')
+      code = srs+21;
     else
-      return MS_FALSE;
-    
-    snprintf( epsg_string, sizeof(epsg_string), "EPSG:%s", code );
-
-    tokens = msStringSplit(pszList, ' ', &nTokens );
-    if (tokens && nTokens > 0)
-    {
-        for (i=0; i<nTokens; i++)
-        {
-            if (strcasecmp(tokens[i],  epsg_string) == 0)
-            {
-                bFound = MS_TRUE;
-                break;
-            }
-        }
-        msFreeCharArray(tokens, nTokens);
+      code = srs+20;
+
+    while( *code != ':' && *code != '\0')
+      code++;
+    if( *code == ':' )
+      code++;
+  } else if (strncasecmp(srs, "urn:EPSG:geographicCRS:",23) == 0)
+    code = srs + 23;
+  else
+    return MS_FALSE;
+
+  snprintf( epsg_string, sizeof(epsg_string), "EPSG:%s", code );
+
+  tokens = msStringSplit(pszList, ' ', &nTokens );
+  if (tokens && nTokens > 0) {
+    for (i=0; i<nTokens; i++) {
+      if (strcasecmp(tokens[i],  epsg_string) == 0) {
+        bFound = MS_TRUE;
+        break;
+      }
     }
-    
-    return bFound;
+    msFreeCharArray(tokens, nTokens);
+  }
+
+  return bFound;
 }
 
 /* msWFSGetFeatureApplySRS()
@@ -285,180 +274,161 @@ int msWFSLocateSRSInList(const char *pszList, const char *srs)
 */
 static int msWFSGetFeatureApplySRS(mapObj *map, const char *srs, const char *version)
 {
-    int nVersion = OWS_1_1_0;
-    const char *pszLayerSRS=NULL;
-    const char *pszMapSRS=NULL;
-    char *pszOutputSRS=NULL;
-    layerObj *lp;
-    int i;
-    
-    if (version && strncmp(version,"1.0",3)==0)
-      nVersion = OWS_1_0_0;
-
-    /*validation of SRS
-      - wfs 1.0 does not have an srsname parameter so all queried layers should be advertized using the
-        same srs. For wfs 1.1.0 an srsName can be passed, we should validate that It is valid for all 
-        queries layers
-    */
-    pszMapSRS = msOWSGetEPSGProj(&(map->projection), &(map->web.metadata), "FO", MS_TRUE);
-    if(pszMapSRS && nVersion >  OWS_1_0_0)
-      msLoadProjectionStringEPSG(&(map->projection), pszMapSRS);
-
-    if (srs == NULL || nVersion == OWS_1_0_0)
-    {
-        for (i=0; i<map->numlayers; i++)
-        {
-            lp = GET_LAYER(map, i);
-            if (lp->status != MS_ON)
-              continue;
+  int nVersion = OWS_1_1_0;
+  const char *pszLayerSRS=NULL;
+  const char *pszMapSRS=NULL;
+  char *pszOutputSRS=NULL;
+  layerObj *lp;
+  int i;
+
+  if (version && strncmp(version,"1.0",3)==0)
+    nVersion = OWS_1_0_0;
+
+  /*validation of SRS
+    - wfs 1.0 does not have an srsname parameter so all queried layers should be advertized using the
+      same srs. For wfs 1.1.0 an srsName can be passed, we should validate that It is valid for all
+      queries layers
+  */
+  pszMapSRS = msOWSGetEPSGProj(&(map->projection), &(map->web.metadata), "FO", MS_TRUE);
+  if(pszMapSRS && nVersion >  OWS_1_0_0)
+    msLoadProjectionStringEPSG(&(map->projection), pszMapSRS);
+
+  if (srs == NULL || nVersion == OWS_1_0_0) {
+    for (i=0; i<map->numlayers; i++) {
+      lp = GET_LAYER(map, i);
+      if (lp->status != MS_ON)
+        continue;
+
+      if (pszMapSRS)
+        pszLayerSRS = pszMapSRS;
+      else
+        pszLayerSRS = msOWSGetEPSGProj(&(lp->projection), &(lp->metadata), "FO", MS_TRUE);
+
+      if (pszLayerSRS == NULL) {
+        msSetError(MS_WFSERR,
+                   "Server config error: SRS must be set at least at the map or at the layer level.",
+                   "msWFSGetFeature()");
+        if (pszOutputSRS)
+          msFree(pszOutputSRS);
+        return MS_FAILURE;
+      }
+      if (pszOutputSRS == NULL)
+        pszOutputSRS = msStrdup(pszLayerSRS);
+      else if (strcasecmp(pszLayerSRS,pszOutputSRS) != 0) {
+        msSetError(MS_WFSERR,
+                   "Invalid GetFeature Request: All TYPENAMES in a single GetFeature request must have been advertized in the same SRS.  Please check the capabilities and reformulate your request.",
+                   "msWFSGetFeature()");
+        if (pszOutputSRS)
+          msFree(pszOutputSRS);
+        return MS_FAILURE;
+      }
 
-            if (pszMapSRS)
-              pszLayerSRS = pszMapSRS;
-            else
-              pszLayerSRS = msOWSGetEPSGProj(&(lp->projection), &(lp->metadata), "FO", MS_TRUE);
-              
-            if (pszLayerSRS == NULL) 
-            {
-                msSetError(MS_WFSERR, 
-                           "Server config error: SRS must be set at least at the map or at the layer level.",
-                           "msWFSGetFeature()");
-                if (pszOutputSRS)
-                  msFree(pszOutputSRS);
-                return MS_FAILURE;
-            }
-            if (pszOutputSRS == NULL)
-              pszOutputSRS = msStrdup(pszLayerSRS);
-            else if (strcasecmp(pszLayerSRS,pszOutputSRS) != 0) 
-            {
-                msSetError(MS_WFSERR, 
-                           "Invalid GetFeature Request: All TYPENAMES in a single GetFeature request must have been advertized in the same SRS.  Please check the capabilities and reformulate your request.",
-                           "msWFSGetFeature()");
-                if (pszOutputSRS)
-                  msFree(pszOutputSRS);
-                return MS_FAILURE;
-            }
-            
-        }
     }
-    else /*srs is given so it should be valid for all layers*/
-    {
-        /*get all the srs defined at the map level and check them aginst the srsName passed
-          as argument*/
-        pszMapSRS = msOWSGetEPSGProj(&(map->projection), &(map->web.metadata), "FO", MS_FALSE);
-        if (pszMapSRS)
-        {
-            if (!msWFSLocateSRSInList(pszMapSRS, srs))
-            {
-                msSetError(MS_WFSERR, 
-                           "Invalid GetFeature Request:Invalid SRS.  Please check the capabilities and reformulate your request.",
-                           "msWFSGetFeature()");
-                return MS_FAILURE;
-            }
-            pszOutputSRS = msStrdup(srs);
+  } else { /*srs is given so it should be valid for all layers*/
+    /*get all the srs defined at the map level and check them aginst the srsName passed
+      as argument*/
+    pszMapSRS = msOWSGetEPSGProj(&(map->projection), &(map->web.metadata), "FO", MS_FALSE);
+    if (pszMapSRS) {
+      if (!msWFSLocateSRSInList(pszMapSRS, srs)) {
+        msSetError(MS_WFSERR,
+                   "Invalid GetFeature Request:Invalid SRS.  Please check the capabilities and reformulate your request.",
+                   "msWFSGetFeature()");
+        return MS_FAILURE;
+      }
+      pszOutputSRS = msStrdup(srs);
+    } else {
+      for (i=0; i<map->numlayers; i++) {
+        lp = GET_LAYER(map, i);
+        if (lp->status != MS_ON)
+          continue;
+
+        pszLayerSRS = msOWSGetEPSGProj(&(lp->projection), &(lp->metadata), "FO", MS_FALSE);
+        if (!pszLayerSRS) {
+          msSetError(MS_WFSERR,
+                     "Server config error: SRS must be set at least at the map or at the layer level.",
+                     "msWFSGetFeature()");
+          return MS_FAILURE;
         }
-        else
-        {
-            for (i=0; i<map->numlayers; i++)
-            {
-                lp = GET_LAYER(map, i);
-                if (lp->status != MS_ON)
-                  continue;
-                
-                pszLayerSRS = msOWSGetEPSGProj(&(lp->projection), &(lp->metadata), "FO", MS_FALSE);
-                if (!pszLayerSRS)
-                {
-                    msSetError(MS_WFSERR, 
-		       "Server config error: SRS must be set at least at the map or at the layer level.",
-		       "msWFSGetFeature()");
-                    return MS_FAILURE;
-                }
-                if (!msWFSLocateSRSInList(pszLayerSRS, srs))
-                {
-                    msSetError(MS_WFSERR, 
-                               "Invalid GetFeature Request:Invalid SRS.  Please check the capabilities and reformulate your request.",
-                               "msWFSGetFeature()");
-                    return MS_FAILURE;
-                }
-            }
-            pszOutputSRS = msStrdup(srs);
+        if (!msWFSLocateSRSInList(pszLayerSRS, srs)) {
+          msSetError(MS_WFSERR,
+                     "Invalid GetFeature Request:Invalid SRS.  Please check the capabilities and reformulate your request.",
+                     "msWFSGetFeature()");
+          return MS_FAILURE;
         }
+      }
+      pszOutputSRS = msStrdup(srs);
     }
+  }
 
-    if (pszOutputSRS && nVersion >= OWS_1_1_0)
-    {    
-        projectionObj sProjTmp;
-        int nTmp=0;
-         
-        msInitProjection(&sProjTmp);
-         nTmp = msLoadProjectionStringEPSG(&(sProjTmp), pszOutputSRS);        
-         if (nTmp == 0)
-         {
-             msProjectRect(&(map->projection), &(sProjTmp), &map->extent);
-             msFreeProjection(&(sProjTmp));
-         }
-          /*check if the srs passed is valid. Assuming that it is an EPSG:xxx format,
-            Or urn:ogc:def:crs:EPSG:xxx format. */
-        if (strncasecmp(pszOutputSRS, "EPSG:", 5) == 0 ||
-            strncasecmp(pszOutputSRS, "urn:ogc:def:crs:EPSG:",21) == 0)
-        {
-            /*we load the projection sting in the map and possibly 
-              set the axis order*/
-            msFreeProjection(&map->projection);
-            msLoadProjectionStringEPSG(&(map->projection), pszOutputSRS);
-        }
-        else if (strncasecmp(pszOutputSRS, "urn:EPSG:geographicCRS:",23) == 0)
-        {
-            char epsg_string[100];
-            const char *code;
-            
-
-            code = pszOutputSRS + 23;
-            
-            snprintf( epsg_string, sizeof(epsg_string), "EPSG:%s", code );
-            
-            /*we load the projection sting in the map and possibly 
-              set the axis order*/
-            /*reproject the map extent from current projection to output projection*/
-
-            msFreeProjection(&map->projection);
-            msLoadProjectionStringEPSG(&(map->projection), epsg_string);
-        }
+  if (pszOutputSRS && nVersion >= OWS_1_1_0) {
+    projectionObj sProjTmp;
+    int nTmp=0;
+
+    msInitProjection(&sProjTmp);
+    nTmp = msLoadProjectionStringEPSG(&(sProjTmp), pszOutputSRS);
+    if (nTmp == 0) {
+      msProjectRect(&(map->projection), &(sProjTmp), &map->extent);
     }
-    /* Set map output projection to which output features should be reprojected */
-    else if (pszOutputSRS && strncasecmp(pszOutputSRS, "EPSG:", 5) == 0) 
-    {
-        int nTmp =0;
-        projectionObj sProjTmp;
+    msFreeProjection(&(sProjTmp));
+    /*check if the srs passed is valid. Assuming that it is an EPSG:xxx format,
+      Or urn:ogc:def:crs:EPSG:xxx format. */
+    if (strncasecmp(pszOutputSRS, "EPSG:", 5) == 0 ||
+        strncasecmp(pszOutputSRS, "urn:ogc:def:crs:EPSG:",21) == 0) {
+      /*we load the projection sting in the map and possibly
+        set the axis order*/
+      msFreeProjection(&map->projection);
+      msLoadProjectionStringEPSG(&(map->projection), pszOutputSRS);
+    } else if (strncasecmp(pszOutputSRS, "urn:EPSG:geographicCRS:",23) == 0) {
+      char epsg_string[100];
+      const char *code;
+
+
+      code = pszOutputSRS + 23;
+
+      snprintf( epsg_string, sizeof(epsg_string), "EPSG:%s", code );
+
+      /*we load the projection sting in the map and possibly
+        set the axis order*/
+      /*reproject the map extent from current projection to output projection*/
+
+      msFreeProjection(&map->projection);
+      msLoadProjectionStringEPSG(&(map->projection), epsg_string);
+    }
+  }
+  /* Set map output projection to which output features should be reprojected */
+  else if (pszOutputSRS && strncasecmp(pszOutputSRS, "EPSG:", 5) == 0) {
+    int nTmp =0;
+    projectionObj sProjTmp;
+
+    /*reproject the map extent from current projection to output projection*/
+    msInitProjection(&sProjTmp);
+    if (nVersion >= OWS_1_1_0)
+      nTmp = msLoadProjectionStringEPSG(&(sProjTmp), pszOutputSRS);
+    else
+      nTmp = msLoadProjectionString(&(sProjTmp), pszOutputSRS);
 
-        /*reproject the map extent from current projection to output projection*/
-        msInitProjection(&sProjTmp);
-        if (nVersion >= OWS_1_1_0)
-          nTmp = msLoadProjectionStringEPSG(&(sProjTmp), pszOutputSRS);
-        else
-          nTmp = msLoadProjectionString(&(sProjTmp), pszOutputSRS);
-        
-        if (nTmp == 0)
-          msProjectRect(&(map->projection), &(sProjTmp), &map->extent);
-        msFreeProjection(&(sProjTmp));
+    if (nTmp == 0)
+      msProjectRect(&(map->projection), &(sProjTmp), &map->extent);
+    msFreeProjection(&(sProjTmp));
 
-        msFreeProjection(&map->projection);
-        msInitProjection(&map->projection);
+    msFreeProjection(&map->projection);
+    msInitProjection(&map->projection);
 
-        if (nVersion >= OWS_1_1_0)
-          nTmp = msLoadProjectionStringEPSG(&(map->projection), pszOutputSRS);
-        else
-          nTmp = msLoadProjectionString(&(map->projection), pszOutputSRS);
+    if (nVersion >= OWS_1_1_0)
+      nTmp = msLoadProjectionStringEPSG(&(map->projection), pszOutputSRS);
+    else
+      nTmp = msLoadProjectionString(&(map->projection), pszOutputSRS);
 
-        if (nTmp != 0) {
-            msSetError(MS_WFSERR, "msLoadProjectionString() failed", "msWFSGetFeature()");
-            return MS_FAILURE;
-        }
+    if (nTmp != 0) {
+      msSetError(MS_WFSERR, "msLoadProjectionString() failed", "msWFSGetFeature()");
+      return MS_FAILURE;
     }
-    
+  }
+
 
-    if (pszOutputSRS)
-      msFree(pszOutputSRS);
-    return MS_SUCCESS;
+  if (pszOutputSRS)
+    msFree(pszOutputSRS);
+  return MS_SUCCESS;
 }
 
 
@@ -469,19 +439,18 @@ static int msWFSGetFeatureApplySRS(mapObj *map, const char *srs, const char *ver
 */
 int msWFSIsLayerSupported(layerObj *lp)
 {
-    /* In order to be supported, lp->type must be specified, even for 
-    ** layers that are OGR, SDE, SDO, etc connections.
-    */
-    if ((lp->type == MS_LAYER_POINT ||
-         lp->type == MS_LAYER_LINE ||
-         lp->type == MS_LAYER_POLYGON ) &&
-        lp->connectiontype != MS_WMS && 
-        lp->connectiontype != MS_GRATICULE)
-    {
-        return 1; /* true */
-    }
+  /* In order to be supported, lp->type must be specified, even for
+  ** layers that are OGR, SDE, SDO, etc connections.
+  */
+  if ((lp->type == MS_LAYER_POINT ||
+       lp->type == MS_LAYER_LINE ||
+       lp->type == MS_LAYER_POLYGON ) &&
+      lp->connectiontype != MS_WMS &&
+      lp->connectiontype != MS_GRATICULE) {
+    return 1; /* true */
+  }
 
-    return 0; /* false */
+  return 0; /* false */
 }
 
 
@@ -492,20 +461,19 @@ int msWFSIsLayerSupported(layerObj *lp)
 const char *msWFSGetGeomElementName(mapObj *map, layerObj *lp)
 {
 
-    switch(lp->type)
-    {
-        case MS_LAYER_POINT:
-          return "pointProperty";
-        case MS_LAYER_LINE:
-          return "lineStringProperty";
-        case MS_LAYER_POLYGON:
-          return "polygonProperty";
-        default:
-          break;
-    }
+  switch(lp->type) {
+    case MS_LAYER_POINT:
+      return "pointProperty";
+    case MS_LAYER_LINE:
+      return "lineStringProperty";
+    case MS_LAYER_POLYGON:
+      return "polygonProperty";
+    default:
+      break;
+  }
+
+  return "???unknown???";
 
-    return "???unknown???";
-    
 }
 
 /* msWFSGetGeomType()
@@ -518,19 +486,18 @@ const char *msWFSGetGeomElementName(mapObj *map, layerObj *lp)
 static const char *msWFSGetGeomType(layerObj *lp)
 {
 
-    switch(lp->type)
-    {
-      case MS_LAYER_POINT:
-        return "PointPropertyType";
-      case MS_LAYER_LINE:
-        return "LineStringPropertyType";
-      case MS_LAYER_POLYGON:
-        return "PolygonPropertyType";
-      default:
-        break;
-    }
+  switch(lp->type) {
+    case MS_LAYER_POINT:
+      return "PointPropertyType";
+    case MS_LAYER_LINE:
+      return "LineStringPropertyType";
+    case MS_LAYER_POLYGON:
+      return "PolygonPropertyType";
+    default:
+      break;
+  }
 
-    return "???unknown???";
+  return "???unknown???";
 }
 #endif /* def notdef */
 
@@ -539,102 +506,91 @@ static const char *msWFSGetGeomType(layerObj *lp)
 */
 int msWFSDumpLayer(mapObj *map, layerObj *lp)
 {
-   rectObj ext;
-   const char *pszWfsSrs = NULL;
-   projectionObj poWfs;
-   int result = 0;
-   
-   msIO_printf("    <FeatureType>\n");
-
-   if (lp->name && strlen(lp->name) > 0 &&
-       (msIsXMLTagValid(lp->name) == MS_FALSE || isdigit(lp->name[0])))
-     msIO_fprintf(stdout, "<!-- WARNING: The layer name '%s' might contain spaces or "
-                        "invalid characters or may start with a number. This could lead to potential problems. -->\n",lp->name);
-   
-   msOWSPrintEncodeParam(stdout, "LAYER.NAME", lp->name, OWS_WARN, 
-                         "        <Name>%s</Name>\n", NULL);
-
-   msOWSPrintEncodeMetadata(stdout, &(lp->metadata), "FO", "title", 
-                            OWS_WARN, "        <Title>%s</Title>\n", lp->name);
-
-   msOWSPrintEncodeMetadata(stdout, &(lp->metadata), "FO", "abstract", 
-                         OWS_NOERR, "        <Abstract>%s</Abstract>\n", NULL);
-
-   msOWSPrintEncodeMetadataList(stdout, &(lp->metadata), "FO", 
-                                "keywordlist", 
-                                "        <Keywords>\n", 
-                                "        </Keywords>\n",
-                                "          %s\n", NULL);
-
-   /* In WFS, every layer must have exactly one SRS and there is none at */
-   /* the top level contrary to WMS */
-   /*  */
-   /* So here is the way we'll deal with SRS: */
-   /* 1- If a top-level map projection (or wfs_srs metadata) is set then */
-   /* all layers are advertized in the map's projection and they will */
-   /* be reprojected on the fly in the GetFeature request. */
-   /* 2- If there is no top-level map projection (or wfs_srs metadata) then */
-   /* each layer is advertized in its own projection as defined in the */
-   /* layer's projection object or wfs_srs metadata. */
-   /*  */
-   if (msOWSGetEPSGProj(&(map->projection),&(map->web.metadata),"FO",MS_TRUE) != NULL)
-   {
-       /* Map has a SRS.  Use it for all layers. */
-       pszWfsSrs = msOWSGetEPSGProj(&(map->projection),&(map->web.metadata), "FO", MS_TRUE);
-   }
-   else
-   {
-       /* Map has no SRS.  Use layer SRS or produce a warning. */
-       pszWfsSrs = msOWSGetEPSGProj(&(lp->projection),&(lp->metadata), "FO", MS_TRUE);
-   }
-
-   msOWSPrintEncodeParam(stdout, "(at least one of) MAP.PROJECTION, LAYER.PROJECTION or wfs_srs metadata", 
-                  pszWfsSrs, OWS_WARN, "        <SRS>%s</SRS>\n", NULL);
-
-   /* If layer has no proj set then use map->proj for bounding box. */
-   if (msOWSGetLayerExtent(map, lp, "FO", &ext) == MS_SUCCESS)
-   {
-       msInitProjection(&poWfs);
-       if (pszWfsSrs != NULL)
-           result = msLoadProjectionString(&(poWfs), pszWfsSrs);
-       
-       if(lp->projection.numargs > 0) 
-       {
-           msOWSPrintLatLonBoundingBox(stdout, "        ", &(ext), 
-                                       &(lp->projection), &(poWfs), OWS_WFS);
-       } 
-       else 
-       {
-           msOWSPrintLatLonBoundingBox(stdout, "        ", &(ext), 
-                                       &(map->projection), &(poWfs), OWS_WFS);
-       }
-       msFreeProjection(&poWfs);
-   }
-   else
-   {
-       msIO_printf("<!-- WARNING: Optional LatLongBoundingBox could not be established for this layer.  Consider setting the EXTENT in the LAYER object, or wfs_extent metadata. Also check that your data exists in the DATA statement -->\n");
-   }
-
-   msOWSPrintURLType(stdout, &(lp->metadata), "FO", "metadataurl", 
-                     OWS_NOERR, NULL, "MetadataURL", " type=\"%s\"", 
-                     NULL, NULL, " format=\"%s\"", "%s", 
-                     MS_TRUE, MS_FALSE, MS_FALSE, MS_TRUE, MS_TRUE, 
-                     NULL, NULL, NULL, NULL, NULL, "        ");
-
-   if (msOWSLookupMetadata(&(lp->metadata), "OFG", "featureid") == NULL)
-   {
-       msIO_fprintf(stdout, "<!-- WARNING: Required Feature Id attribute (fid) not specified for this feature type. Make sure you set one of wfs_featureid, ows_featureid or gml_featureid metadata. -->\n");
-   }
-
-   msIO_printf("    </FeatureType>\n");
-      
-   return MS_SUCCESS;
+  rectObj ext;
+  const char *pszWfsSrs = NULL;
+  projectionObj poWfs;
+
+  msIO_printf("    <FeatureType>\n");
+
+  if (lp->name && strlen(lp->name) > 0 &&
+      (msIsXMLTagValid(lp->name) == MS_FALSE || isdigit(lp->name[0])))
+    msIO_fprintf(stdout, "<!-- WARNING: The layer name '%s' might contain spaces or "
+                 "invalid characters or may start with a number. This could lead to potential problems. -->\n",lp->name);
+
+  msOWSPrintEncodeParam(stdout, "LAYER.NAME", lp->name, OWS_WARN,
+                        "        <Name>%s</Name>\n", NULL);
+
+  msOWSPrintEncodeMetadata(stdout, &(lp->metadata), "FO", "title",
+                           OWS_WARN, "        <Title>%s</Title>\n", lp->name);
+
+  msOWSPrintEncodeMetadata(stdout, &(lp->metadata), "FO", "abstract",
+                           OWS_NOERR, "        <Abstract>%s</Abstract>\n", NULL);
+
+  msOWSPrintEncodeMetadataList(stdout, &(lp->metadata), "FO",
+                               "keywordlist",
+                               "        <Keywords>\n",
+                               "        </Keywords>\n",
+                               "          %s\n", NULL);
+
+  /* In WFS, every layer must have exactly one SRS and there is none at */
+  /* the top level contrary to WMS */
+  /*  */
+  /* So here is the way we'll deal with SRS: */
+  /* 1- If a top-level map projection (or wfs_srs metadata) is set then */
+  /* all layers are advertized in the map's projection and they will */
+  /* be reprojected on the fly in the GetFeature request. */
+  /* 2- If there is no top-level map projection (or wfs_srs metadata) then */
+  /* each layer is advertized in its own projection as defined in the */
+  /* layer's projection object or wfs_srs metadata. */
+  /*  */
+  if (msOWSGetEPSGProj(&(map->projection),&(map->web.metadata),"FO",MS_TRUE) != NULL) {
+    /* Map has a SRS.  Use it for all layers. */
+    pszWfsSrs = msOWSGetEPSGProj(&(map->projection),&(map->web.metadata), "FO", MS_TRUE);
+  } else {
+    /* Map has no SRS.  Use layer SRS or produce a warning. */
+    pszWfsSrs = msOWSGetEPSGProj(&(lp->projection),&(lp->metadata), "FO", MS_TRUE);
+  }
+
+  msOWSPrintEncodeParam(stdout, "(at least one of) MAP.PROJECTION, LAYER.PROJECTION or wfs_srs metadata",
+                        pszWfsSrs, OWS_WARN, "        <SRS>%s</SRS>\n", NULL);
+
+  /* If layer has no proj set then use map->proj for bounding box. */
+  if (msOWSGetLayerExtent(map, lp, "FO", &ext) == MS_SUCCESS) {
+    msInitProjection(&poWfs);
+    if (pszWfsSrs != NULL)
+      msLoadProjectionString(&(poWfs), pszWfsSrs);
+
+    if(lp->projection.numargs > 0) {
+      msOWSPrintLatLonBoundingBox(stdout, "        ", &(ext),
+                                  &(lp->projection), &(poWfs), OWS_WFS);
+    } else {
+      msOWSPrintLatLonBoundingBox(stdout, "        ", &(ext),
+                                  &(map->projection), &(poWfs), OWS_WFS);
+    }
+    msFreeProjection(&poWfs);
+  } else {
+    msIO_printf("<!-- WARNING: Optional LatLongBoundingBox could not be established for this layer.  Consider setting the EXTENT in the LAYER object, or wfs_extent metadata. Also check that your data exists in the DATA statement -->\n");
+  }
+
+  msOWSPrintURLType(stdout, &(lp->metadata), "FO", "metadataurl",
+                    OWS_NOERR, NULL, "MetadataURL", " type=\"%s\"",
+                    NULL, NULL, " format=\"%s\"", "%s",
+                    MS_TRUE, MS_FALSE, MS_FALSE, MS_TRUE, MS_TRUE,
+                    NULL, NULL, NULL, NULL, NULL, "        ");
+
+  if (msOWSLookupMetadata(&(lp->metadata), "OFG", "featureid") == NULL) {
+    msIO_fprintf(stdout, "<!-- WARNING: Required Feature Id attribute (fid) not specified for this feature type. Make sure you set one of wfs_featureid, ows_featureid or gml_featureid metadata. -->\n");
+  }
+
+  msIO_printf("    </FeatureType>\n");
+
+  return MS_SUCCESS;
 }
 
 /*
 ** msWFSGetCapabilities()
 */
-int msWFSGetCapabilities(mapObj *map, wfsParamsObj *wfsparams, cgiRequestObj *req, owsRequestObj *ows_request) 
+int msWFSGetCapabilities(mapObj *map, wfsParamsObj *wfsparams, cgiRequestObj *req, owsRequestObj *ows_request)
 {
   char *script_url=NULL, *script_url_encoded;
   const char *updatesequence=NULL;
@@ -648,39 +604,35 @@ int msWFSGetCapabilities(mapObj *map, wfsParamsObj *wfsparams, cgiRequestObj *re
   int i=0, tmpInt=0;
 
   /* acceptversions: do OWS Common style of version negotiation */
-  if (wfsparams->pszAcceptVersions && strlen(wfsparams->pszAcceptVersions) > 0)
-  {     
-      char **tokens;
-      int i, j;
-
-      tokens = msStringSplit(wfsparams->pszAcceptVersions, ',', &j);
-      for (i=0; i<j;i++) 
-      {
-          int iVersion = 0;
-        
-          iVersion = msOWSParseVersionString(tokens[i]);
-
-          if (iVersion == -1) {
-              msSetError(MS_WFSERR, "Invalid version format.", "msWFSGetCapabilities()", tokens[i]);
-              msFreeCharArray(tokens, j);
-              return msWFSException(map, "acceptversions", "VersionNegotiationFailed",wmtver);
-          }
+  if (wfsparams->pszAcceptVersions && strlen(wfsparams->pszAcceptVersions) > 0) {
+    char **tokens;
+    int i, j;
 
-          /* negotiate version */
-          tmpInt = msOWSCommonNegotiateVersion(iVersion, wfsSupportedVersions, wfsNumSupportedVersions);
-          if (tmpInt != -1)
-            break;
+    tokens = msStringSplit(wfsparams->pszAcceptVersions, ',', &j);
+    for (i=0; i<j; i++) {
+      int iVersion = 0;
+
+      iVersion = msOWSParseVersionString(tokens[i]);
+
+      if (iVersion == -1) {
+        msSetError(MS_WFSERR, "Invalid version format.", "msWFSGetCapabilities()", tokens[i]);
+        msFreeCharArray(tokens, j);
+        return msWFSException(map, "acceptversions", "VersionNegotiationFailed",wmtver);
       }
-       msFreeCharArray(tokens, j);
-       if(tmpInt == -1)
-       {
-           msSetError(MS_WFSERR, "ACCEPTVERSIONS list (%s) does not match supported versions", "msWFSGetCapabilities()", wfsparams->pszAcceptVersions);
-           return msWFSException(map, "acceptversions", "VersionNegotiationFailed",wmtver);
-       }
-  }
-  else
-  /* negotiate version */
-    tmpInt = msOWSNegotiateVersion(msOWSParseVersionString(wfsparams->pszVersion), wfsSupportedVersions, 
+
+      /* negotiate version */
+      tmpInt = msOWSCommonNegotiateVersion(iVersion, wfsSupportedVersions, wfsNumSupportedVersions);
+      if (tmpInt != -1)
+        break;
+    }
+    msFreeCharArray(tokens, j);
+    if(tmpInt == -1) {
+      msSetError(MS_WFSERR, "ACCEPTVERSIONS list (%s) does not match supported versions", "msWFSGetCapabilities()", wfsparams->pszAcceptVersions);
+      return msWFSException(map, "acceptversions", "VersionNegotiationFailed",wmtver);
+    }
+  } else
+    /* negotiate version */
+    tmpInt = msOWSNegotiateVersion(msOWSParseVersionString(wfsparams->pszVersion), wfsSupportedVersions,
                                    wfsNumSupportedVersions);
 
   /* set result as string and carry on */
@@ -696,10 +648,9 @@ int msWFSGetCapabilities(mapObj *map, wfsParamsObj *wfsparams, cgiRequestObj *re
 
   /* We need this server's onlineresource. */
   if ((script_url=msOWSGetOnlineResource(map, "FO", "onlineresource", req)) == NULL ||
-      (script_url_encoded = msEncodeHTMLEntities(script_url)) == NULL)
-  {
-      msSetError(MS_WFSERR, "Server URL not found", "msWFSGetCapabilities()");
-      return msWFSException(map, "mapserv", "NoApplicableCode", wmtver);
+      (script_url_encoded = msEncodeHTMLEntities(script_url)) == NULL) {
+    msSetError(MS_WFSERR, "Server URL not found", "msWFSGetCapabilities()");
+    return msWFSException(map, "mapserv", "NoApplicableCode", wmtver);
   }
   free(script_url);
   script_url = NULL;
@@ -710,39 +661,40 @@ int msWFSGetCapabilities(mapObj *map, wfsParamsObj *wfsparams, cgiRequestObj *re
     updatesequence = msStrdup("0");
 
   if (wfsparams->pszUpdateSequence != NULL) {
-      i = msOWSNegotiateUpdateSequence(wfsparams->pszUpdateSequence, updatesequence);
-      if (i == 0) { /* current */
-          msSetError(MS_WFSERR, "UPDATESEQUENCE parameter (%s) is equal to server (%s)", "msWFSGetCapabilities()", wfsparams->pszUpdateSequence, updatesequence);
-          free(script_url_encoded);
-          return msWFSException(map, "updatesequence", "CurrentUpdateSequence", wmtver);
-      }
-      if (i > 0) { /* invalid */
-          msSetError(MS_WFSERR, "UPDATESEQUENCE parameter (%s) is higher than server (%s)", "msWFSGetCapabilities()", wfsparams->pszUpdateSequence, updatesequence);
-          free(script_url_encoded);
-          return msWFSException(map, "updatesequence", "InvalidUpdateSequence", wmtver);
-      }
+    i = msOWSNegotiateUpdateSequence(wfsparams->pszUpdateSequence, updatesequence);
+    if (i == 0) { /* current */
+      msSetError(MS_WFSERR, "UPDATESEQUENCE parameter (%s) is equal to server (%s)", "msWFSGetCapabilities()", wfsparams->pszUpdateSequence, updatesequence);
+      free(script_url_encoded);
+      return msWFSException(map, "updatesequence", "CurrentUpdateSequence", wmtver);
+    }
+    if (i > 0) { /* invalid */
+      msSetError(MS_WFSERR, "UPDATESEQUENCE parameter (%s) is higher than server (%s)", "msWFSGetCapabilities()", wfsparams->pszUpdateSequence, updatesequence);
+      free(script_url_encoded);
+      return msWFSException(map, "updatesequence", "InvalidUpdateSequence", wmtver);
+    }
   }
 
   encoding = msOWSLookupMetadata(&(map->web.metadata), "FO", "encoding");
-    if (encoding)
-        msIO_printf("Content-type: text/xml; charset=%s%c%c", encoding,10,10);
-    else
-        msIO_printf("Content-type: text/xml%c%c",10,10);
+  if (encoding)
+    msIO_setHeader("Content-Type","text/xml; charset=%s", encoding);
+  else
+    msIO_setHeader("Content-Type","text/xml");
+  msIO_sendHeaders();
 
   msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "FO", "encoding", OWS_NOERR,
-                "<?xml version='1.0' encoding=\"%s\" ?>\n",
-                "ISO-8859-1");
+                           "<?xml version='1.0' encoding=\"%s\" ?>\n",
+                           "ISO-8859-1");
 
 
   msIO_printf("<WFS_Capabilities \n"
-         "   version=\"%s\" \n"
-         "   updateSequence=\"%s\" \n"
-         "   xmlns=\"http://www.opengis.net/wfs\" \n"
-         "   xmlns:ogc=\"http://www.opengis.net/ogc\" \n"
-         "   xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
-         "   xsi:schemaLocation=\"http://www.opengis.net/wfs %s/wfs/%s/WFS-capabilities.xsd\">\n",
-         wmtver, updatesequence,
-         msOWSGetSchemasLocation(map), wmtver);
+              "   version=\"%s\" \n"
+              "   updateSequence=\"%s\" \n"
+              "   xmlns=\"http://www.opengis.net/wfs\" \n"
+              "   xmlns:ogc=\"http://www.opengis.net/ogc\" \n"
+              "   xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
+              "   xsi:schemaLocation=\"http://www.opengis.net/wfs %s/wfs/%s/WFS-capabilities.xsd\">\n",
+              wmtver, updatesequence,
+              msOWSGetSchemasLocation(map), wmtver);
 
   /* Report MapServer Version Information */
   msIO_printf("\n<!-- %s -->\n\n", msGetVersion());
@@ -751,64 +703,63 @@ int msWFSGetCapabilities(mapObj *map, wfsParamsObj *wfsparams, cgiRequestObj *re
   ** SERVICE definition
   */
   msIO_printf("<Service>\n");
- msIO_printf("  <Name>MapServer WFS</Name>\n");
+  msIO_printf("  <Name>MapServer WFS</Name>\n");
 
   /* the majority of this section is dependent on appropriately named metadata in the WEB object */
-  msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "FO", "title", 
+  msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "FO", "title",
                            OWS_WARN, "  <Title>%s</Title>\n", map->name);
-  msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "FO", "abstract", 
+  msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "FO", "abstract",
                            OWS_NOERR, "  <Abstract>%s</Abstract>\n", NULL);
 
-  msOWSPrintEncodeMetadataList(stdout, &(map->web.metadata), "FO", 
-                               "keywordlist", 
+  msOWSPrintEncodeMetadataList(stdout, &(map->web.metadata), "FO",
+                               "keywordlist",
                                "  <Keywords>\n", "  </Keywords>\n",
                                "    %s\n", NULL);
 
   /* Service/onlineresource */
   /* Defaults to same as request onlineresource if wfs_service_onlineresource  */
   /* is not set. */
-  msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), 
+  msOWSPrintEncodeMetadata(stdout, &(map->web.metadata),
                            "FO", "service_onlineresource", OWS_NOERR,
-                           "  <OnlineResource>%s</OnlineResource>\n", 
+                           "  <OnlineResource>%s</OnlineResource>\n",
                            script_url_encoded);
 
-  msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "FO", "fees", 
+  msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "FO", "fees",
                            OWS_NOERR, "  <Fees>%s</Fees>\n", NULL);
-  
-  msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "FO", 
+
+  msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "FO",
                            "accessconstraints", OWS_NOERR,
-                           "  <AccessConstraints>%s</AccessConstraints>\n", 
+                           "  <AccessConstraints>%s</AccessConstraints>\n",
                            NULL);
 
   msIO_printf("</Service>\n\n");
 
-  /* 
+  /*
   ** CAPABILITY definitions: list of supported requests
   */
 
   msIO_printf("<Capability>\n");
 
   msIO_printf("  <Request>\n");
-  msWFSPrintRequestCap(wmtver, "GetCapabilities", script_url_encoded, 
+  msWFSPrintRequestCap(wmtver, "GetCapabilities", script_url_encoded,
                        NULL, NULL);
   /* msWFSPrintRequestCap(wmtver, "DescribeFeatureType", script_url_encoded, "SchemaDescriptionLanguage", "XMLSCHEMA", "SFE_XMLSCHEMA", NULL); */
   /* msWFSPrintRequestCap(wmtver, "GetFeature", script_url_encoded, "ResultFormat", "GML2", "GML3", NULL); */
 
   /* don't advertise the GML3 or GML for SFE support */
-  if (msOWSRequestIsEnabled(map, NULL, "F", "DescribeFeatureType", MS_TRUE)) 
-      msWFSPrintRequestCap(wmtver, "DescribeFeatureType", script_url_encoded, "SchemaDescriptionLanguage", "XMLSCHEMA" );
+  if (msOWSRequestIsEnabled(map, NULL, "F", "DescribeFeatureType", MS_TRUE))
+    msWFSPrintRequestCap(wmtver, "DescribeFeatureType", script_url_encoded, "SchemaDescriptionLanguage", "XMLSCHEMA" );
 
-  if (msOWSRequestIsEnabled(map, NULL, "F", "GetFeature", MS_TRUE)) 
-  {
-      formats_list = msWFSGetOutputFormatList( map, NULL, wfsparams->pszVersion );
-      msWFSPrintRequestCap(wmtver, "GetFeature", script_url_encoded, "ResultFormat", formats_list );
-      msFree( formats_list );
+  if (msOWSRequestIsEnabled(map, NULL, "F", "GetFeature", MS_TRUE)) {
+    formats_list = msWFSGetOutputFormatList( map, NULL, wfsparams->pszVersion );
+    msWFSPrintRequestCap(wmtver, "GetFeature", script_url_encoded, "ResultFormat", formats_list );
+    msFree( formats_list );
   }
 
   msIO_printf("  </Request>\n");
   msIO_printf("</Capability>\n\n");
 
-  /* 
+  /*
   ** FeatureTypeList: layers
   */
 
@@ -820,21 +771,19 @@ int msWFSGetCapabilities(mapObj *map, wfsParamsObj *wfsparams, cgiRequestObj *re
   msIO_printf("    <Query/>\n");
   msIO_printf("  </Operations>\n");
 
-  for(i=0; i<map->numlayers; i++)
-  {
-      layerObj *lp;
-      lp = GET_LAYER(map, i);
+  for(i=0; i<map->numlayers; i++) {
+    layerObj *lp;
+    lp = GET_LAYER(map, i);
 
-      if (lp->status == MS_DELETE)
-         continue;
+    if (lp->status == MS_DELETE)
+      continue;
 
-      if (!msIntegerInArray(lp->index, ows_request->enabled_layers, ows_request->numlayers))
-          continue;
+    if (!msIntegerInArray(lp->index, ows_request->enabled_layers, ows_request->numlayers))
+      continue;
 
-      if (msWFSIsLayerSupported(lp))
-      {
-          msWFSDumpLayer(map, lp);
-      }
+    if (msWFSIsLayerSupported(lp)) {
+      msWFSDumpLayer(map, lp);
+    }
   }
 
   msIO_printf("</FeatureTypeList>\n\n");
@@ -887,49 +836,49 @@ int msWFSGetCapabilities(mapObj *map, wfsParamsObj *wfsparams, cgiRequestObj *re
 ** Helper functions for producing XML schema.
 */
 
-static const char *msWFSGetGeometryType(char *type, int outputformat) 
+static const char *msWFSGetGeometryType(char *type, int outputformat)
 {
   if(!type) return "???undefined???";
-  
+
   if(strcasecmp(type, "point") == 0) {
     switch(outputformat) {
-    case OWS_GML2:
-    case OWS_GML3:
-      return "PointPropertyType";
+      case OWS_GML2:
+      case OWS_GML3:
+        return "PointPropertyType";
     }
   } else if(strcasecmp(type, "multipoint") == 0) {
     switch(outputformat) {
-    case OWS_GML2:
-    case OWS_GML3:
-      return "MultiPointPropertyType";
+      case OWS_GML2:
+      case OWS_GML3:
+        return "MultiPointPropertyType";
     }
   } else if(strcasecmp(type, "line") == 0) {
     switch(outputformat) {
-    case OWS_GML2:
-      return "LineStringPropertyType";
-    case OWS_GML3:
-      return "CurvePropertyType";
+      case OWS_GML2:
+        return "LineStringPropertyType";
+      case OWS_GML3:
+        return "CurvePropertyType";
     }
   } else if(strcasecmp(type, "multiline") == 0) {
     switch(outputformat) {
-    case OWS_GML2:
-      return "MultiLineStringPropertyType";
-    case OWS_GML3:
-      return "MultiCurvePropertyType";
+      case OWS_GML2:
+        return "MultiLineStringPropertyType";
+      case OWS_GML3:
+        return "MultiCurvePropertyType";
     }
   } else if(strcasecmp(type, "polygon") == 0) {
     switch(outputformat) {
-    case OWS_GML2:
-      return "PolygonPropertyType";
-    case OWS_GML3:
-      return "SurfacePropertyType";
+      case OWS_GML2:
+        return "PolygonPropertyType";
+      case OWS_GML3:
+        return "SurfacePropertyType";
     }
   } else if(strcasecmp(type, "multipolygon") == 0) {
     switch(outputformat) {
-    case OWS_GML2:
-      return "MultiPolygonPropertyType";
-    case OWS_GML3:
-      return "MultiSurfacePropertyType";
+      case OWS_GML2:
+        return "MultiPolygonPropertyType";
+      case OWS_GML3:
+        return "MultiSurfacePropertyType";
     }
   }
 
@@ -937,7 +886,7 @@ static const char *msWFSGetGeometryType(char *type, int outputformat)
 }
 
 static void msWFSWriteGeometryElement(FILE *stream, gmlGeometryListObj *geometryList, int outputformat, const char *tab)
-{ 
+{
   int i;
   gmlGeometryObj *geometry=NULL;
 
@@ -959,12 +908,12 @@ static void msWFSWriteGeometryElement(FILE *stream, gmlGeometryListObj *geometry
       msIO_fprintf(stream, "%s<choice>\n", tab);
       for(i=0; i<geometryList->numgeometries; i++) {
         geometry = &(geometryList->geometries[i]);
-	
-      msIO_fprintf(stream, "  %s<element name=\"%s\" type=\"gml:%s\" minOccurs=\"%d\"", tab, geometry->name, msWFSGetGeometryType(geometry->type, outputformat), geometry->occurmin);
-      if(geometry->occurmax == OWS_GML_OCCUR_UNBOUNDED)
-        msIO_fprintf(stream, " maxOccurs=\"unbounded\"/>\n");
-      else
-	      msIO_fprintf(stream, " maxOccurs=\"%d\"/>\n", geometry->occurmax);	
+
+        msIO_fprintf(stream, "  %s<element name=\"%s\" type=\"gml:%s\" minOccurs=\"%d\"", tab, geometry->name, msWFSGetGeometryType(geometry->type, outputformat), geometry->occurmin);
+        if(geometry->occurmax == OWS_GML_OCCUR_UNBOUNDED)
+          msIO_fprintf(stream, " maxOccurs=\"unbounded\"/>\n");
+        else
+          msIO_fprintf(stream, " maxOccurs=\"%d\"/>\n", geometry->occurmax);
       }
       msIO_fprintf(stream, "%s</choice>\n", tab);
     }
@@ -980,7 +929,7 @@ static void msWFSWriteItemElement(FILE *stream, gmlItemObj *item, const char *ta
 
   if(!stream || !item || !tab) return;
   if(!item->visible) return; /* not exposing this attribute */
-	if(item->template) return; /* can't adequately deal with templated items yet */
+  if(item->template) return; /* can't adequately deal with templated items yet */
 
   if(item->alias) /* TODO: what about name spaces embedded in the alias? */
     element_name = item->alias;
@@ -1016,7 +965,7 @@ static void msWFSWriteGroupElement(FILE *stream, gmlGroupObj *group, const char
   else
     msIO_fprintf(stream, "%s<element name=\"%s\" type=\"%s:%sType\"/>\n", tab, group->name, namespace, group->name);
 
-	return;
+  return;
 }
 
 static void msWFSWriteGroupElementType(FILE *stream, gmlGroupObj *group, gmlItemListObj *itemList, gmlConstantListObj *constantList, const char *tab)
@@ -1036,28 +985,28 @@ static void msWFSWriteGroupElementType(FILE *stream, gmlGroupObj *group, gmlItem
     msIO_fprintf(stream, "%s<complexType name=\"%s\">\n", tab, group->type);
   else
     msIO_fprintf(stream, "%s<complexType name=\"%sType\">\n", tab, group->name);
-  
+
   msIO_fprintf(stream, "%s  <sequence>\n", tab);
 
-  /* now the items/constants (e.g. elements) in the group */ 
+  /* now the items/constants (e.g. elements) in the group */
   for(i=0; i<group->numitems; i++) {
     for(j=0; j<constantList->numconstants; j++) { /* find the right gmlConstantObj */
       constant = &(constantList->constants[j]);
-      if(strcasecmp(constant->name, group->items[i]) == 0) { 
+      if(strcasecmp(constant->name, group->items[i]) == 0) {
         msWFSWriteConstantElement(stream, constant, element_tab);
-	      break;
+        break;
       }
     }
     if(j != constantList->numconstants) continue; /* found this item */
     for(j=0; j<itemList->numitems; j++) { /* find the right gmlItemObj */
       item = &(itemList->items[j]);
-      if(strcasecmp(item->name, group->items[i]) == 0) { 
+      if(strcasecmp(item->name, group->items[i]) == 0) {
         msWFSWriteItemElement(stream, item, element_tab);
         break;
       }
     }
   }
-  
+
   msIO_fprintf(stream, "%s  </sequence>\n", tab);
   msIO_fprintf(stream, "%s</complexType>\n", tab);
 
@@ -1080,7 +1029,7 @@ int msWFSDescribeFeatureType(mapObj *map, wfsParamsObj *paramsObj, owsRequestObj
   char *user_namespace_uri_encoded = NULL;
   const char *collection_name = OWS_WFS_FEATURE_COLLECTION_NAME;
   char *encoded_name = NULL, *encoded;
-  
+
   int outputformat = OWS_DEFAULT_SCHEMA; /* default output is GML 2.1 compliant schema*/
 
   gmlNamespaceListObj *namespaceList=NULL; /* for external application schema support */
@@ -1099,60 +1048,54 @@ int msWFSDescribeFeatureType(mapObj *map, wfsParamsObj *paramsObj, owsRequestObj
         msFreeCharArray(tokens, n);
         tokens = NULL;
         for (i=0; i<numlayers; i++) {
-            tokens = msStringSplit(layers[i], ':', &n);
-            if (tokens && n==2) {
-                free(layers[i]);
-                layers[i] = msStrdup(tokens[1]);
-            }
-            if (tokens)
-                msFreeCharArray(tokens, n);
-            tokens = NULL;
+          tokens = msStringSplit(layers[i], ':', &n);
+          if (tokens && n==2) {
+            free(layers[i]);
+            layers[i] = msStrdup(tokens[1]);
+          }
+          if (tokens)
+            msFreeCharArray(tokens, n);
+          tokens = NULL;
         }
       }
       if (tokens)
-          msFreeCharArray(tokens, n);
+        msFreeCharArray(tokens, n);
     }
-  } 
+  }
+
 
-  
   if (paramsObj->pszOutputFormat) {
     if(strcasecmp(paramsObj->pszOutputFormat, "XMLSCHEMA") == 0 ||
-       strstr(paramsObj->pszOutputFormat, "gml/2")!= NULL)
-    {
-	mimetype = msEncodeHTMLEntities("text/xml; subtype=gml/2.1.2");
-	outputformat = OWS_DEFAULT_SCHEMA;
-    }
-    else if(strcasecmp(paramsObj->pszOutputFormat, "SFE_XMLSCHEMA") == 0 ||
-            strstr(paramsObj->pszOutputFormat, "gml/3")!= NULL)
-    {
-	mimetype = msEncodeHTMLEntities("text/xml; subtype=gml/3.1.1");
-	outputformat = OWS_SFE_SCHEMA;
-    }
-    else {
+        strstr(paramsObj->pszOutputFormat, "gml/2")!= NULL) {
+      mimetype = msEncodeHTMLEntities("text/xml; subtype=gml/2.1.2");
+      outputformat = OWS_DEFAULT_SCHEMA;
+    } else if(strcasecmp(paramsObj->pszOutputFormat, "SFE_XMLSCHEMA") == 0 ||
+              strstr(paramsObj->pszOutputFormat, "gml/3")!= NULL) {
+      mimetype = msEncodeHTMLEntities("text/xml; subtype=gml/3.1.1");
+      outputformat = OWS_SFE_SCHEMA;
+    } else {
       msSetError(MS_WFSERR, "Unsupported DescribeFeatureType outputFormat (%s).", "msWFSDescribeFeatureType()", paramsObj->pszOutputFormat);
       return msWFSException(map, "outputformat", "InvalidParameterValue", paramsObj->pszVersion);
     }
   }
 
   /*set the output format to gml3 for wfs1.1*/
-  if(mimetype == NULL)
-  {
-      if (paramsObj->pszVersion == NULL || strncmp(paramsObj->pszVersion,"1.1",3) == 0 )
-      {
-          mimetype = msEncodeHTMLEntities("text/xml; subtype=gml/3.1.1");
-          outputformat = OWS_SFE_SCHEMA;
-      }
-      else
-        mimetype = msEncodeHTMLEntities("text/xml");
+  if(mimetype == NULL) {
+    if (paramsObj->pszVersion == NULL || strncmp(paramsObj->pszVersion,"1.1",3) == 0 ) {
+      mimetype = msEncodeHTMLEntities("text/xml; subtype=gml/3.1.1");
+      outputformat = OWS_SFE_SCHEMA;
+    } else
+      mimetype = msEncodeHTMLEntities("text/xml");
   }
 
   /* Validate layers */
   if (numlayers > 0) {
     for (i=0; i<numlayers; i++) {
-        int index = msGetLayerIndex(map, layers[i]);
-        if ( (index < 0) || (!msIntegerInArray(GET_LAYER(map, index)->index, ows_request->enabled_layers, ows_request->numlayers)) ) {
-	      msSetError(MS_WFSERR, "Invalid typename (%s).", "msWFSDescribeFeatureType()", layers[i]);/* paramsObj->pszTypeName); */
-              return msWFSException(map, "typename", "InvalidParameterValue", paramsObj->pszVersion);
+      int index = msGetLayerIndex(map, layers[i]);
+      if ( (index < 0) || (!msIntegerInArray(GET_LAYER(map, index)->index, ows_request->enabled_layers, ows_request->numlayers)) ) {
+        msSetError(MS_WFSERR, "Invalid typename (%s). A layer might be disabled for \
+this request. Check wfs/ows_enable_request settings.", "msWFSDescribeFeatureType()", layers[i]);/* paramsObj->pszTypeName); */
+        return msWFSException(map, "typename", "InvalidParameterValue", paramsObj->pszVersion);
       }
     }
   }
@@ -1161,46 +1104,46 @@ int msWFSDescribeFeatureType(mapObj *map, wfsParamsObj *paramsObj, owsRequestObj
   ** retrieve any necessary external namespace/schema configuration information
   */
   namespaceList = msGMLGetNamespaces(&(map->web), "G");
-  if (namespaceList == NULL)
-  {
-      msSetError(MS_MISCERR, "Unable to populate namespace list", "msWFSDescribeFeatureType()");
-      return MS_FAILURE;
+  if (namespaceList == NULL) {
+    msSetError(MS_MISCERR, "Unable to populate namespace list", "msWFSDescribeFeatureType()");
+    return MS_FAILURE;
   }
 
   /*
   ** DescribeFeatureType response
   */
   value = msOWSLookupMetadata(&(map->web.metadata), "FO", "encoding");
-  
+
   if (value)
-    msIO_printf("Content-type: %s; charset=%s%c%c", mimetype,value,10,10);
+    msIO_setHeader("Content-Type","%s; charset=%s",mimetype, value);
   else
-    msIO_printf("Content-type: %s%c%c",mimetype,10,10);
+    msIO_setHeader("Content-Type",mimetype);
+  msIO_sendHeaders();
 
   if (mimetype)
     msFree(mimetype);
 
   msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "FO", "encoding", OWS_NOERR,
-			   "<?xml version='1.0' encoding=\"%s\" ?>\n",
-			   "ISO-8859-1");
+                           "<?xml version='1.0' encoding=\"%s\" ?>\n",
+                           "ISO-8859-1");
 
   value = msOWSLookupMetadata(&(map->web.metadata), "FO", "namespace_uri");
   if(value) user_namespace_uri = value;
   user_namespace_uri_encoded = msEncodeHTMLEntities(user_namespace_uri);
 
   value = msOWSLookupMetadata(&(map->web.metadata), "FO", "namespace_prefix");
-  if(value) user_namespace_prefix = value;  
+  if(value) user_namespace_prefix = value;
   if(user_namespace_prefix != NULL && msIsXMLTagValid(user_namespace_prefix) == MS_FALSE)
     msIO_printf("<!-- WARNING: The value '%s' is not valid XML namespace. -->\n", user_namespace_prefix);
-    
+
   msIO_printf("<schema\n"
-		"   targetNamespace=\"%s\" \n"
-		"   xmlns:%s=\"%s\" \n"
-		"   xmlns:ogc=\"http://www.opengis.net/ogc\"\n"
-		"   xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\n"
-		"   xmlns=\"http://www.w3.org/2001/XMLSchema\"\n"
-		"   xmlns:gml=\"http://www.opengis.net/gml\"\n",  
-		user_namespace_uri_encoded, user_namespace_prefix,  user_namespace_uri_encoded);
+              "   targetNamespace=\"%s\" \n"
+              "   xmlns:%s=\"%s\" \n"
+              "   xmlns:ogc=\"http://www.opengis.net/ogc\"\n"
+              "   xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\n"
+              "   xmlns=\"http://www.w3.org/2001/XMLSchema\"\n"
+              "   xmlns:gml=\"http://www.opengis.net/gml\"\n",
+              user_namespace_uri_encoded, user_namespace_prefix,  user_namespace_uri_encoded);
 
   /* any additional namespaces */
   for(i=0; i<namespaceList->numnamespaces; i++) {
@@ -1218,14 +1161,14 @@ int msWFSDescribeFeatureType(mapObj *map, wfsParamsObj *paramsObj, owsRequestObj
   encoded = msEncodeHTMLEntities( msOWSGetSchemasLocation(map) );
   if(outputformat == OWS_SFE_SCHEMA) /* reference GML 3.1.1 schema */
     msIO_printf("\n  <import namespace=\"http://www.opengis.net/gml\"\n"
-		"          schemaLocation=\"%s/gml/3.1.1/base/gml.xsd\" />\n", encoded);
+                "          schemaLocation=\"%s/gml/3.1.1/base/gml.xsd\" />\n", encoded);
   else /* default GML 2.1.x schema */
     msIO_printf("\n  <import namespace=\"http://www.opengis.net/gml\"\n"
-	      "          schemaLocation=\"%s/gml/2.1.2/feature.xsd\" />\n", encoded);
+                "          schemaLocation=\"%s/gml/2.1.2/feature.xsd\" />\n", encoded);
   msFree(encoded);
 
   /* any additional namespace includes */
-    for(i=0; i<namespaceList->numnamespaces; i++) {
+  for(i=0; i<namespaceList->numnamespaces; i++) {
     if(namespaceList->namespaces[i].uri && namespaceList->namespaces[i].schemalocation) {
       char *schema_location_encoded=NULL, *uri_encoded=NULL;
 
@@ -1243,7 +1186,7 @@ int msWFSDescribeFeatureType(mapObj *map, wfsParamsObj *paramsObj, owsRequestObj
   if(outputformat == OWS_SFE_SCHEMA && strncmp(paramsObj->pszVersion,"1.1",3) != 0) {
     value = msOWSLookupMetadata(&(map->web.metadata), "FO", "feature_collection");
     if(value) collection_name = value;
-    
+
     msIO_printf("  <element name=\"%s\" type=\"%s:%sType\" substitutionGroup=\"gml:_FeatureCollection\"/>\n", collection_name, user_namespace_prefix, collection_name);
     msIO_printf("  <complexType name=\"%sType\">\n", collection_name);
     msIO_printf("    <complexContent>\n");
@@ -1252,24 +1195,24 @@ int msWFSDescribeFeatureType(mapObj *map, wfsParamsObj *paramsObj, owsRequestObj
     msIO_printf("      </extension>\n");
     msIO_printf("    </complexContent>\n");
     msIO_printf("  </complexType>\n");
-  } 
+  }
 
   /*
-  ** loop through layers 
+  ** loop through layers
   */
   for(i=0; i<map->numlayers; i++)  {
     layerObj *lp;
     int j, bFound = 0;
-    
+
     lp = GET_LAYER(map, i);
 
     for (j=0; j<numlayers && !bFound; j++) {
       if ( lp->name && strcasecmp(lp->name, layers[j]) == 0)
-      bFound = 1;
+        bFound = 1;
     }
 
-    if ((numlayers == 0 || bFound) && msWFSIsLayerSupported(lp) && 
-        (msIntegerInArray(lp->index, ows_request->enabled_layers, ows_request->numlayers)) ) {        
+    if ((numlayers == 0 || bFound) && msWFSIsLayerSupported(lp) &&
+        (msIntegerInArray(lp->index, ows_request->enabled_layers, ows_request->numlayers)) ) {
 
       /*
       ** OK, describe this layer IF you can open it and retrieve items
@@ -1291,38 +1234,37 @@ int msWFSDescribeFeatureType(mapObj *map, wfsParamsObj *paramsObj, owsRequestObj
           constantList = msGMLGetConstants(lp, "G");
           groupList = msGMLGetGroups(lp, "G");
           geometryList = msGMLGetGeometries(lp, "GFO");
-          if (itemList == NULL || constantList == NULL || groupList == NULL || geometryList == NULL)
-          {
-              msSetError(MS_MISCERR, "Unable to populate item and group metadata structures", "msWFSDescribeFeatureType()");
-              return MS_FAILURE;
+          if (itemList == NULL || constantList == NULL || groupList == NULL || geometryList == NULL) {
+            msSetError(MS_MISCERR, "Unable to populate item and group metadata structures", "msWFSDescribeFeatureType()");
+            return MS_FAILURE;
           }
 
           value = msOWSLookupMetadata(&(lp->metadata), "OFG", "namespace_prefix");
-          if(value) 
+          if(value)
             layer_namespace_prefix = value;
           else
             layer_namespace_prefix = user_namespace_prefix;
 
-          /* value = msOWSLookupMetadata(&(lp->metadata), "OFG", "layername"); */      
-          encoded_name = msEncodeHTMLEntities( lp->name );          
+          /* value = msOWSLookupMetadata(&(lp->metadata), "OFG", "layername"); */
+          encoded_name = msEncodeHTMLEntities( lp->name );
           value = msOWSLookupMetadata(&(lp->metadata), "OFG", "layer_type");
           if(value) {
             encoded_type = msEncodeHTMLEntities(value);
             msIO_printf("\n"
-                      "  <element name=\"%s\" \n"
-                      "           type=\"%s:%s\" \n"
-                      "           substitutionGroup=\"gml:_Feature\" />\n\n",
-                      encoded_name, layer_namespace_prefix, encoded_type);
+                        "  <element name=\"%s\" \n"
+                        "           type=\"%s:%s\" \n"
+                        "           substitutionGroup=\"gml:_Feature\" />\n\n",
+                        encoded_name, layer_namespace_prefix, encoded_type);
             msFree(encoded_type);
           } else
             msIO_printf("\n"
-                      "  <element name=\"%s\" \n"
-                      "           type=\"%s:%sType\" \n"
-                      "           substitutionGroup=\"gml:_Feature\" />\n\n",
-                      encoded_name, layer_namespace_prefix, encoded_name);
+                        "  <element name=\"%s\" \n"
+                        "           type=\"%s:%sType\" \n"
+                        "           substitutionGroup=\"gml:_Feature\" />\n\n",
+                        encoded_name, layer_namespace_prefix, encoded_name);
 
           if(strcmp(layer_namespace_prefix, user_namespace_prefix) != 0)
-						continue; /* the rest is defined in an external schema */
+            continue; /* the rest is defined in an external schema */
 
           msIO_printf("  <complexType name=\"%sType\">\n", encoded_name);
           msIO_printf("    <complexContent>\n");
@@ -1334,15 +1276,15 @@ int msWFSDescribeFeatureType(mapObj *map, wfsParamsObj *paramsObj, owsRequestObj
 
           /* write the constant-based schema elements */
           for(k=0; k<constantList->numconstants; k++) {
-            constant = &(constantList->constants[k]);  
-            if(msItemInGroups(constant->name, groupList) == MS_FALSE) 
+            constant = &(constantList->constants[k]);
+            if(msItemInGroups(constant->name, groupList) == MS_FALSE)
               msWFSWriteConstantElement(stdout, constant, "          ");
           }
 
           /* write the item-based schema elements */
           for(k=0; k<itemList->numitems; k++) {
-            item = &(itemList->items[k]);  
-            if(msItemInGroups(item->name, groupList) == MS_FALSE) 
+            item = &(itemList->items[k]);
+            if(msItemInGroups(item->name, groupList) == MS_FALSE)
               msWFSWriteItemElement(stdout, item, "          ");
           }
 
@@ -1368,21 +1310,21 @@ int msWFSDescribeFeatureType(mapObj *map, wfsParamsObj *paramsObj, owsRequestObj
       } else {
         msIO_printf("\n\n<!-- ERROR: Failed opening layer %s -->\n\n", encoded_name);
       }
-          
+
     }
   }
-  
+
   /*
   ** Done!
   */
   msIO_printf("\n</schema>\n");
-  
+
   msFree(encoded_name);
   msFree(user_namespace_uri_encoded);
-  
+
   if(layers)
     msFreeCharArray(layers, numlayers);
-    
+
   msGMLFreeNamespaces(namespaceList);
 
   return MS_SUCCESS;
@@ -1396,13 +1338,13 @@ int msWFSDescribeFeatureType(mapObj *map, wfsParamsObj *paramsObj, owsRequestObj
 */
 
 typedef struct {
-    const char *user_namespace_prefix;
-    const char *user_namespace_uri;
-    char       *user_namespace_uri_encoded;
-    const char *collection_name;
-    const char *typename;
-    char       *script_url, *script_url_encoded;
-    const char *output_schema_format;
+  const char *user_namespace_prefix;
+  const char *user_namespace_uri;
+  char       *user_namespace_uri_encoded;
+  const char *collection_name;
+  const char *typename;
+  char       *script_url, *script_url_encoded;
+  const char *output_schema_format;
 } WFSGMLInfo;
 
 static int msWFSGetFeature_GMLPreamble( mapObj *map,
@@ -1414,167 +1356,158 @@ static int msWFSGetFeature_GMLPreamble( mapObj *map,
                                         int iNumberOfFeatures )
 
 {
-    const char *value;
-    int i;
-    char       *encoded, *encoded_typename, *encoded_schema;
-    gmlNamespaceListObj *namespaceList=NULL; /* for external application schema support */
-
-    namespaceList = msGMLGetNamespaces(&(map->web), "G");
-    if (namespaceList == NULL)
-    {
-        msSetError(MS_MISCERR, "Unable to populate namespace list", "msWFSGetFeature_GMLPreamble()");
-        return MS_FAILURE;
-    }
+  const char *value;
+  int i;
+  char       *encoded, *encoded_typename, *encoded_schema;
+  gmlNamespaceListObj *namespaceList=NULL; /* for external application schema support */
 
-    /*
-    ** Establish script_url.
-    */
-    
-    if ((gmlinfo->script_url=msOWSGetOnlineResource(map,"FO","onlineresource",req)) ==NULL ||
-        (gmlinfo->script_url_encoded = msEncodeHTMLEntities(gmlinfo->script_url)) == NULL) {
-      msSetError(MS_WFSERR, "Server URL not found", "msWFSGetFeature()");
-      return msWFSException(map, "mapserv", "NoApplicableCode", paramsObj->pszVersion);
-    }
+  namespaceList = msGMLGetNamespaces(&(map->web), "G");
+  if (namespaceList == NULL) {
+    msSetError(MS_MISCERR, "Unable to populate namespace list", "msWFSGetFeature_GMLPreamble()");
+    return MS_FAILURE;
+  }
 
-    /*
-    ** Write encoding.
-    */
-    msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "FO", 
-                             "encoding", OWS_NOERR,
-                             "<?xml version='1.0' encoding=\"%s\" ?>\n",
-                             "ISO-8859-1");
-
-    value = msOWSLookupMetadata(&(map->web.metadata), "FO", "namespace_uri");
-    if(value) gmlinfo->user_namespace_uri = value;
-    gmlinfo->user_namespace_uri_encoded = 
-        msEncodeHTMLEntities(gmlinfo->user_namespace_uri);
-        
-    value = msOWSLookupMetadata(&(map->web.metadata), "FO", "namespace_prefix");
-    if(value) gmlinfo->user_namespace_prefix = value;
-        
-    if(gmlinfo->user_namespace_prefix != NULL && msIsXMLTagValid(gmlinfo->user_namespace_prefix) == MS_FALSE)
-        msIO_printf("<!-- WARNING: The value '%s' is not valid XML namespace. -->\n", gmlinfo->user_namespace_prefix);
-        
-    value = msOWSLookupMetadata(&(map->web.metadata), "FO", "feature_collection");
-    if(value) gmlinfo->collection_name = value;
-        
-    encoded = msEncodeHTMLEntities( paramsObj->pszVersion );
-    encoded_typename = msEncodeHTMLEntities( gmlinfo->typename );
-    encoded_schema = msEncodeHTMLEntities( msOWSGetSchemasLocation(map) );
-        
-    /*
-    ** GML 2.x
-    */
-    if(outputformat == OWS_GML2) { /* use a wfs:FeatureCollection */
-        msIO_printf("<wfs:FeatureCollection\n"
-                    "   xmlns:%s=\"%s\"\n"  
-                    "   xmlns:wfs=\"http://www.opengis.net/wfs\"\n"
-                    "   xmlns:gml=\"http://www.opengis.net/gml\"\n"
-                    "   xmlns:ogc=\"http://www.opengis.net/ogc\"\n"
-                    "   xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n",
-                    gmlinfo->user_namespace_prefix, 
-                    gmlinfo->user_namespace_uri_encoded);
-            
-        /* any additional namespaces */
-        for(i=0; i<namespaceList->numnamespaces; i++) {
-            if(namespaceList->namespaces[i].uri) {
-                char *uri_encoded=NULL;
-                    
-                uri_encoded = msEncodeHTMLEntities(namespaceList->namespaces[i].uri);
-                msIO_printf("   xmlns:%s=\"%s\" \n", namespaceList->namespaces[i].prefix, uri_encoded);
-                msFree(uri_encoded);
-            }
-        }
-        msIO_printf("   xsi:schemaLocation=\"http://www.opengis.net/wfs %s/wfs/%s/WFS-basic.xsd \n"
-                    "                       %s %sSERVICE=WFS&VERSION=%s&REQUEST=DescribeFeatureType&TYPENAME=%s&OUTPUTFORMAT=%s\">\n",
-                    encoded_schema, encoded, 
-                    gmlinfo->user_namespace_uri_encoded, 
-                    gmlinfo->script_url_encoded, encoded, 
-                    encoded_typename, gmlinfo->output_schema_format);
-    } 
-
-    /*
-    ** GML 3
-    */
-    else 
-    {
-        if(paramsObj->pszVersion && strncmp(paramsObj->pszVersion,"1.1",3) == 0 )
-        {
-            msIO_printf("<wfs:FeatureCollection\n"
-                        "   xmlns:%s=\"%s\"\n"  
-                        "   xmlns:gml=\"http://www.opengis.net/gml\"\n"
-                        "   xmlns:wfs=\"http://www.opengis.net/wfs\"\n"
-                        "   xmlns:ogc=\"http://www.opengis.net/ogc\"\n"
-                        "   xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n",
-                        gmlinfo->user_namespace_prefix, 
-                        gmlinfo->user_namespace_uri_encoded);
-        }
-        else
-        {
-            msIO_printf("<%s:%s\n"
-                        "   version=\"1.0.0\"\n"
-                        "   xmlns:%s=\"%s\"\n"  
-                        "   xmlns:gml=\"http://www.opengis.net/gml\"\n"
-                        "   xmlns:ogc=\"http://www.opengis.net/ogc\"\n"
-                        "   xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n",
-                        gmlinfo->user_namespace_prefix, 
-                        gmlinfo->collection_name, 
-                        gmlinfo->user_namespace_prefix, 
-                        gmlinfo->user_namespace_uri_encoded);
-        }
-        /* any additional namespaces */
-        for(i=0; i<namespaceList->numnamespaces; i++) {
-            if(namespaceList->namespaces[i].uri) {
-                char *uri_encoded=NULL;
-                    
-                uri_encoded = msEncodeHTMLEntities(namespaceList->namespaces[i].uri);
-                msIO_printf("   xmlns:%s=\"%s\" \n", namespaceList->namespaces[i].prefix, uri_encoded);
-                msFree(uri_encoded);
-            }
-        }
+  /*
+  ** Establish script_url.
+  */
 
-        if(paramsObj->pszVersion && strncmp(paramsObj->pszVersion,"1.1",3) == 0)
-        {
-            if (iResultTypeHits == 1)
-            {
-                char timestring[100];
-                struct tm *now;
-                time_t tim=time(NULL);
-                
-                now=localtime(&tim);
-                
-                snprintf(timestring, sizeof(timestring), "%d-%02d-%02dT%02d:%02d:%02d",
-                         now->tm_year+1900, now->tm_mon+1, now->tm_mday,
-                         now->tm_hour, now->tm_min, now->tm_sec);
-                
-                msIO_printf("   xsi:schemaLocation=\"%s %sSERVICE=WFS&VERSION=%s&REQUEST=DescribeFeatureType&TYPENAME=%s&OUTPUTFORMAT=%s  http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.1.0/wfs.xsd\" timeStamp=\"%s\" numberOfFeatures=\"%d\">\n",
-                            gmlinfo->user_namespace_uri_encoded, 
-                            gmlinfo->script_url_encoded, encoded, 
-                            encoded_typename, 
-                            gmlinfo->output_schema_format, 
-                            timestring, iNumberOfFeatures);
-            }
-            else
-                msIO_printf("   xsi:schemaLocation=\"%s %sSERVICE=WFS&VERSION=%s&REQUEST=DescribeFeatureType&TYPENAME=%s&OUTPUTFORMAT=%s  http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.1.0/wfs.xsd\">\n",
-                            gmlinfo->user_namespace_uri_encoded, 
-                            gmlinfo->script_url_encoded, encoded, 
-                            encoded_typename, 
-                            gmlinfo->output_schema_format);
-        }
-        else
-            msIO_printf("   xsi:schemaLocation=\"%s %sSERVICE=WFS&VERSION=%s&REQUEST=DescribeFeatureType&TYPENAME=%s&OUTPUTFORMAT=%s\">\n",
-                        gmlinfo->user_namespace_uri_encoded, 
-                        gmlinfo->script_url_encoded, encoded, 
-                        encoded_typename, gmlinfo->output_schema_format);
-    }
-    
-    msFree(encoded);
-    msFree(encoded_schema);
-    msFree(encoded_typename);
-    
-    msGMLFreeNamespaces(namespaceList);
-
-    return MS_SUCCESS;
+  if ((gmlinfo->script_url=msOWSGetOnlineResource(map,"FO","onlineresource",req)) ==NULL ||
+      (gmlinfo->script_url_encoded = msEncodeHTMLEntities(gmlinfo->script_url)) == NULL) {
+    msSetError(MS_WFSERR, "Server URL not found", "msWFSGetFeature()");
+    return msWFSException(map, "mapserv", "NoApplicableCode", paramsObj->pszVersion);
+  }
+
+  /*
+  ** Write encoding.
+  */
+  msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "FO",
+                           "encoding", OWS_NOERR,
+                           "<?xml version='1.0' encoding=\"%s\" ?>\n",
+                           "ISO-8859-1");
+
+  value = msOWSLookupMetadata(&(map->web.metadata), "FO", "namespace_uri");
+  if(value) gmlinfo->user_namespace_uri = value;
+  gmlinfo->user_namespace_uri_encoded =
+    msEncodeHTMLEntities(gmlinfo->user_namespace_uri);
+
+  value = msOWSLookupMetadata(&(map->web.metadata), "FO", "namespace_prefix");
+  if(value) gmlinfo->user_namespace_prefix = value;
+
+  if(gmlinfo->user_namespace_prefix != NULL && msIsXMLTagValid(gmlinfo->user_namespace_prefix) == MS_FALSE)
+    msIO_printf("<!-- WARNING: The value '%s' is not valid XML namespace. -->\n", gmlinfo->user_namespace_prefix);
+
+  value = msOWSLookupMetadata(&(map->web.metadata), "FO", "feature_collection");
+  if(value) gmlinfo->collection_name = value;
+
+  encoded = msEncodeHTMLEntities( paramsObj->pszVersion );
+  encoded_typename = msEncodeHTMLEntities( gmlinfo->typename );
+  encoded_schema = msEncodeHTMLEntities( msOWSGetSchemasLocation(map) );
+
+  /*
+  ** GML 2.x
+  */
+  if(outputformat == OWS_GML2) { /* use a wfs:FeatureCollection */
+    msIO_printf("<wfs:FeatureCollection\n"
+                "   xmlns:%s=\"%s\"\n"
+                "   xmlns:wfs=\"http://www.opengis.net/wfs\"\n"
+                "   xmlns:gml=\"http://www.opengis.net/gml\"\n"
+                "   xmlns:ogc=\"http://www.opengis.net/ogc\"\n"
+                "   xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n",
+                gmlinfo->user_namespace_prefix,
+                gmlinfo->user_namespace_uri_encoded);
+
+    /* any additional namespaces */
+    for(i=0; i<namespaceList->numnamespaces; i++) {
+      if(namespaceList->namespaces[i].uri) {
+        char *uri_encoded=NULL;
+
+        uri_encoded = msEncodeHTMLEntities(namespaceList->namespaces[i].uri);
+        msIO_printf("   xmlns:%s=\"%s\" \n", namespaceList->namespaces[i].prefix, uri_encoded);
+        msFree(uri_encoded);
+      }
+    }
+    msIO_printf("   xsi:schemaLocation=\"http://www.opengis.net/wfs %s/wfs/%s/WFS-basic.xsd \n"
+                "                       %s %sSERVICE=WFS&VERSION=%s&REQUEST=DescribeFeatureType&TYPENAME=%s&OUTPUTFORMAT=%s\">\n",
+                encoded_schema, encoded,
+                gmlinfo->user_namespace_uri_encoded,
+                gmlinfo->script_url_encoded, encoded,
+                encoded_typename, gmlinfo->output_schema_format);
+  }
+
+  /*
+  ** GML 3
+  */
+  else {
+    if(paramsObj->pszVersion && strncmp(paramsObj->pszVersion,"1.1",3) == 0 ) {
+      msIO_printf("<wfs:FeatureCollection\n"
+                  "   xmlns:%s=\"%s\"\n"
+                  "   xmlns:gml=\"http://www.opengis.net/gml\"\n"
+                  "   xmlns:wfs=\"http://www.opengis.net/wfs\"\n"
+                  "   xmlns:ogc=\"http://www.opengis.net/ogc\"\n"
+                  "   xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n",
+                  gmlinfo->user_namespace_prefix,
+                  gmlinfo->user_namespace_uri_encoded);
+    } else {
+      msIO_printf("<%s:%s\n"
+                  "   version=\"1.0.0\"\n"
+                  "   xmlns:%s=\"%s\"\n"
+                  "   xmlns:gml=\"http://www.opengis.net/gml\"\n"
+                  "   xmlns:ogc=\"http://www.opengis.net/ogc\"\n"
+                  "   xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n",
+                  gmlinfo->user_namespace_prefix,
+                  gmlinfo->collection_name,
+                  gmlinfo->user_namespace_prefix,
+                  gmlinfo->user_namespace_uri_encoded);
+    }
+    /* any additional namespaces */
+    for(i=0; i<namespaceList->numnamespaces; i++) {
+      if(namespaceList->namespaces[i].uri) {
+        char *uri_encoded=NULL;
+
+        uri_encoded = msEncodeHTMLEntities(namespaceList->namespaces[i].uri);
+        msIO_printf("   xmlns:%s=\"%s\" \n", namespaceList->namespaces[i].prefix, uri_encoded);
+        msFree(uri_encoded);
+      }
+    }
+
+    if(paramsObj->pszVersion && strncmp(paramsObj->pszVersion,"1.1",3) == 0) {
+      if (iResultTypeHits == 1) {
+        char timestring[100];
+        struct tm *now;
+        time_t tim=time(NULL);
+
+        now=localtime(&tim);
+
+        snprintf(timestring, sizeof(timestring), "%d-%02d-%02dT%02d:%02d:%02d",
+                 now->tm_year+1900, now->tm_mon+1, now->tm_mday,
+                 now->tm_hour, now->tm_min, now->tm_sec);
+
+        msIO_printf("   xsi:schemaLocation=\"%s %sSERVICE=WFS&VERSION=%s&REQUEST=DescribeFeatureType&TYPENAME=%s&OUTPUTFORMAT=%s  http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.1.0/wfs.xsd\" timeStamp=\"%s\" numberOfFeatures=\"%d\">\n",
+                    gmlinfo->user_namespace_uri_encoded,
+                    gmlinfo->script_url_encoded, encoded,
+                    encoded_typename,
+                    gmlinfo->output_schema_format,
+                    timestring, iNumberOfFeatures);
+      } else
+        msIO_printf("   xsi:schemaLocation=\"%s %sSERVICE=WFS&VERSION=%s&REQUEST=DescribeFeatureType&TYPENAME=%s&OUTPUTFORMAT=%s  http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.1.0/wfs.xsd\">\n",
+                    gmlinfo->user_namespace_uri_encoded,
+                    gmlinfo->script_url_encoded, encoded,
+                    encoded_typename,
+                    gmlinfo->output_schema_format);
+    } else
+      msIO_printf("   xsi:schemaLocation=\"%s %sSERVICE=WFS&VERSION=%s&REQUEST=DescribeFeatureType&TYPENAME=%s&OUTPUTFORMAT=%s\">\n",
+                  gmlinfo->user_namespace_uri_encoded,
+                  gmlinfo->script_url_encoded, encoded,
+                  encoded_typename, gmlinfo->output_schema_format);
+  }
+
+  msFree(encoded);
+  msFree(encoded_schema);
+  msFree(encoded_typename);
+
+  msGMLFreeNamespaces(namespaceList);
+
+  return MS_SUCCESS;
 }
 
 /*
@@ -1591,48 +1524,47 @@ static int msWFSGetFeature_GMLPostfix( mapObj *map,
                                        int maxfeatures,
                                        int iResultTypeHits,
                                        int iNumberOfFeatures )
-    
+
 {
-    if (((iNumberOfFeatures==0) || (maxfeatures == 0)) && iResultTypeHits == 0) {
-      msIO_printf("   <gml:boundedBy>\n"); 
-      if(outputformat == OWS_GML3)
-        msIO_printf("      <gml:Null>missing</gml:Null>\n");
-      else
-        msIO_printf("      <gml:null>missing</gml:null>\n");
-      msIO_printf("   </gml:boundedBy>\n"); 
-    }
-    
+  if (((iNumberOfFeatures==0) || (maxfeatures == 0)) && iResultTypeHits == 0) {
+    msIO_printf("   <gml:boundedBy>\n");
+    if(outputformat == OWS_GML3)
+      msIO_printf("      <gml:Null>missing</gml:Null>\n");
+    else
+      msIO_printf("      <gml:null>missing</gml:null>\n");
+    msIO_printf("   </gml:boundedBy>\n");
+  }
+
 
-    if(outputformat == OWS_GML2)
-      msIO_printf("</wfs:FeatureCollection>\n\n");
+  if(outputformat == OWS_GML2)
+    msIO_printf("</wfs:FeatureCollection>\n\n");
+  else {
+    if(paramsObj->pszVersion && strncmp(paramsObj->pszVersion,"1.1",3) == 0)
+      msIO_printf("</wfs:FeatureCollection>\n\n", gmlinfo->user_namespace_prefix, gmlinfo->collection_name);
     else
-    {
-      if(paramsObj->pszVersion && strncmp(paramsObj->pszVersion,"1.1",3) == 0)
-        msIO_printf("</wfs:FeatureCollection>\n\n", gmlinfo->user_namespace_prefix, gmlinfo->collection_name);
-      else
-        msIO_printf("</%s:%s>\n\n", gmlinfo->user_namespace_prefix, gmlinfo->collection_name);
-    }
+      msIO_printf("</%s:%s>\n\n", gmlinfo->user_namespace_prefix, gmlinfo->collection_name);
+  }
 
-    free(gmlinfo->script_url);
-    free(gmlinfo->script_url_encoded);
-    msFree(gmlinfo->user_namespace_uri_encoded);
+  free(gmlinfo->script_url);
+  free(gmlinfo->script_url_encoded);
+  msFree(gmlinfo->user_namespace_uri_encoded);
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 /*
 ** msWFSGetFeature()
 */
 int msWFSGetFeature(mapObj *map, wfsParamsObj *paramsObj, cgiRequestObj *req, owsRequestObj *ows_request)
-  /* const char *wmtver, char **names, char **values, int numentries) */
+/* const char *wmtver, char **names, char **values, int numentries) */
 {
-  int   i, j, status; 
+  int   i, j, status;
   int   maxfeatures=-1,startindex=-1;
   rectObj     bbox;
-  
+
   char **layers = NULL;
   int numlayers = 0;
-  
+
   char   *pszFilter = NULL;
   int bFilterSet = 0;
   int bBBOXSet = 0;
@@ -1643,23 +1575,24 @@ int msWFSGetFeature(mapObj *map, wfsParamsObj *paramsObj, cgiRequestObj *req, ow
   const char *tmpmaxfeatures = NULL;
   WFSGMLInfo gmlinfo;
 
-  const char *output_mime_type = "text/xml; subtype=gml/3.1.1";  
+  const char *output_mime_type = "text/xml; subtype=gml/3.1.1";
   int outputformat = OWS_GML2; /* default output is GML 2.1 */
   outputFormatObj *psFormat = NULL;
-   
+
   char **aFIDLayers = NULL;
   char **aFIDValues = NULL;
   int iFIDLayers = 0;
   int iNumberOfFeatures = 0;
   int iResultTypeHits = 0;
-  
+
   char **papszPropertyName = NULL;
   int nPropertyNames = 0;
   int nQueriedLayers=0;
   layerObj *lpQueried=NULL;
 
-  /*use msLayerGetShape instead of msLayerResultsGetShape of complex filter #3305*/
+  /*use msLayerGetShape instead of msLayerResultsGetShape of complex filter #3305
   int bComplexFilter = MS_FALSE;
+  */
 
   /* Initialize gml options */
   memset( &gmlinfo, 0, sizeof(gmlinfo) );
@@ -1667,35 +1600,33 @@ int msWFSGetFeature(mapObj *map, wfsParamsObj *paramsObj, cgiRequestObj *req, ow
   gmlinfo.user_namespace_uri = "http://mapserver.gis.umn.edu/mapserver";
   gmlinfo.collection_name = OWS_WFS_FEATURE_COLLECTION_NAME;
   gmlinfo.typename = "";
-  gmlinfo.output_schema_format = "XMLSCHEMA";  
+  gmlinfo.output_schema_format = "XMLSCHEMA";
 
   /* Default filter is map extents */
   bbox = map->extent;
-  
+
   /* Read CGI parameters */
   /*  */
   /* __TODO__ Need to support XML encoded requests */
   /*  */
 
-  if (paramsObj->pszResultType != NULL)
-  {
+  if (paramsObj->pszResultType != NULL) {
     if (strcasecmp(paramsObj->pszResultType, "hits") == 0)
       iResultTypeHits = 1;
-  }  
+  }
 
   /* typename is mandatory unlsess featureid is specfied. We do not
      support featureid */
-  if (paramsObj->pszTypeName==NULL && paramsObj->pszFeatureId == NULL)
-  {
-      msSetError(MS_WFSERR, 
-                 "Incomplete WFS request: TYPENAME parameter missing", 
-                 "msWFSGetFeature()");
-      return msWFSException(map, "typename", "MissingParameterValue", paramsObj->pszVersion);
+  if (paramsObj->pszTypeName==NULL && paramsObj->pszFeatureId == NULL) {
+    msSetError(MS_WFSERR,
+               "Incomplete WFS request: TYPENAME parameter missing",
+               "msWFSGetFeature()");
+    return msWFSException(map, "typename", "MissingParameterValue", paramsObj->pszVersion);
   }
 
   if(paramsObj->pszTypeName) {
-      int j, k, y,z;
-    
+    int j, k, y,z;
+
     char **tokens;
     int n=0, i=0;
     char szTmp[256];
@@ -1703,259 +1634,228 @@ int msWFSGetFeature(mapObj *map, wfsParamsObj *paramsObj, cgiRequestObj *req, ow
 
     /* keep a ref for layer use. */
     gmlinfo.typename = paramsObj->pszTypeName;
-        
+
     /* Parse comma-delimited list of type names (layers) */
     /*  */
     /* __TODO__ Need to handle type grouping, e.g. "(l1,l2),l3,l4" */
     /*  */
     layers = msStringSplit(gmlinfo.typename, ',', &numlayers);
-    
+
     /* ==================================================================== */
     /*      TODO: check if the typename contains namespaces (ex cdf:Other), */
     /*      If that is the case extract only the layer name.                */
     /* ==================================================================== */
-    
+
     if (layers==NULL || numlayers < 1) {
       msSetError(MS_WFSERR, "At least one type name required in TYPENAME parameter.", "msWFSGetFeature()");
       return msWFSException(map, "typename", "InvalidParameterValue", paramsObj->pszVersion);
     }
-    
+
     tokens = msStringSplit(layers[0], ':', &n);
     if (tokens && n==2 && msGetLayerIndex(map, layers[0]) < 0) {
       msFreeCharArray(tokens, n);
       for (i=0; i<numlayers; i++) {
-	tokens = msStringSplit(layers[i], ':', &n);
-	if (tokens && n==2) {
-	  free(layers[i]);
-	  layers[i] = msStrdup(tokens[1]);
-	}
-	if (tokens)
-	  msFreeCharArray(tokens, n);
+        tokens = msStringSplit(layers[i], ':', &n);
+        if (tokens && n==2) {
+          free(layers[i]);
+          layers[i] = msStrdup(tokens[1]);
+        }
+        if (tokens)
+          msFreeCharArray(tokens, n);
       }
-    }
-    else
+    } else
       msFreeCharArray(tokens, n);
 
-   
+
 
     /* Keep only selected layers, set to OFF by default. */
     for(j=0; j<map->numlayers; j++) {
       layerObj *lp;
-      
+
       lp = GET_LAYER(map, j);
-      
+
       /* Keep only selected layers, set to OFF by default. */
       lp->status = MS_OFF;
     }
 
     for (k=0; k<numlayers; k++) {
-      int bLayerFound = MS_FALSE; 
-      
+      int bLayerFound = MS_FALSE;
+
       for (j=0; j<map->numlayers; j++) {
-	layerObj *lp;
+        layerObj *lp;
         char   *pszPropertyName = NULL;
 
-	lp = GET_LAYER(map, j);
-	
-	if (msWFSIsLayerSupported(lp) && lp->name && (strcasecmp(lp->name, layers[k]) == 0) && 
+        lp = GET_LAYER(map, j);
+
+        if (msWFSIsLayerSupported(lp) && lp->name && (strcasecmp(lp->name, layers[k]) == 0) &&
             (msIntegerInArray(lp->index, ows_request->enabled_layers, ows_request->numlayers)) ) {
-	  bLayerFound = MS_TRUE;
-	  
-	  lp->status = MS_ON;
-	  if (lp->template == NULL) {
-	    /* Force setting a template to enable query. */
-	    lp->template = msStrdup("ttt.html");
-	  }
+          bLayerFound = MS_TRUE;
+
+          lp->status = MS_ON;
+          if (lp->template == NULL) {
+            /* Force setting a template to enable query. */
+            lp->template = msStrdup("ttt.html");
+          }
 
           /* set the gml_include_items METADATA */
-          if (paramsObj->pszPropertyName) 
-          {
-              pszPropertyName = paramsObj->pszPropertyName;
-
-              /*we parse the propertyname parameter only once*/
-              if (papszPropertyName == NULL)
-              {
-                  if (strlen(pszPropertyName) > 0 && (pszPropertyName[0] == '(' || numlayers == 1))
-                  {
-                      if (numlayers == 1 && pszPropertyName[0] != '(')
-                      {
-                        /* Accept PROPERTYNAME without () when there is a single TYPENAME */
-                          char* pszTmpPropertyName = msSmallMalloc(1+strlen(pszPropertyName)+1+1);
-                          sprintf(pszTmpPropertyName, "(%s)", pszPropertyName);
-                          tokens = msStringSplit(pszTmpPropertyName+1, '(', &nPropertyNames);
-                          free(pszTmpPropertyName);
-                      }
-                      else
-                          tokens = msStringSplit(pszPropertyName+1, '(', &nPropertyNames);
-
-                      /*expecting to always have a list of property names equal to
-                        the number of layers(typename)*/
-                      if (nPropertyNames != numlayers)
-                      {
-                          if (tokens) 
-                            msFreeCharArray(tokens, nPropertyNames);
-                          msSetError(MS_WFSERR, 
-                                     "Optional PROPERTYNAME parameter. A list of properties may be specified for each type name. Example TYPENAME=name1&name2&PROPERTYNAME=(prop1,prop2)(prop1)", 
-                                     "msWFSGetFeature()");
-                          return msWFSException(map, "PROPERTYNAME", "InvalidParameterValue", paramsObj->pszVersion);
-                      }
-                      
-                      papszPropertyName = (char **)msSmallMalloc(sizeof(char *)*nPropertyNames);
-                      for (i=0; i<nPropertyNames; i++) 
-                      {
-                          if (strlen(tokens[i]) > 0)
-                          {
-                              /*trim namespaces. PROPERTYNAME=(ns:prop1,ns:prop2)(prop1)*/
-                              if (strstr(tokens[i], ":"))
-                              {
-                                  char **tokens1, **tokens2;
-                                  int n1=0,n2=0,l=0;
-                                  char *pszTmp = NULL;
-
-                                  tokens1 = msStringSplit(tokens[i], ',', &n1);
-                                  for (l=0;l<n1;l++)
-                                  {
-                                      if (pszTmp!=NULL)
-                                        pszTmp = msStringConcatenate(pszTmp,",");
-
-                                      if (strstr(tokens1[l],":"))
-                                      {
-                                          tokens2 = msStringSplit(tokens1[l], ':', &n2);
-                                          if (tokens2 && n2==2)
-                                            pszTmp = msStringConcatenate(pszTmp, tokens2[1]);
-                                          else
-                                            pszTmp = msStringConcatenate(pszTmp,tokens1[l]); 
-                                          if (tokens2 && n2>0)
-                                            msFreeCharArray(tokens2, n2);
-                                      }
-                                      else
-                                        pszTmp = msStringConcatenate(pszTmp,tokens1[l]);
-                                  }
-                                  papszPropertyName[i] = msStrdup(pszTmp);
-                                  msFree(pszTmp);
-                                  if (tokens1 && n1>0)
-                                    msFreeCharArray(tokens1, n1);
-                              }
-                              else
-                                papszPropertyName[i] = msStrdup(tokens[i]);
-                              /* remove trailing ) */
-                              papszPropertyName[i][strlen(papszPropertyName[i])-1] = '\0';
-                          }
+          if (paramsObj->pszPropertyName) {
+            pszPropertyName = paramsObj->pszPropertyName;
+
+            /*we parse the propertyname parameter only once*/
+            if (papszPropertyName == NULL) {
+              if (strlen(pszPropertyName) > 0 && (pszPropertyName[0] == '(' || numlayers == 1)) {
+                if (numlayers == 1 && pszPropertyName[0] != '(') {
+                  /* Accept PROPERTYNAME without () when there is a single TYPENAME */
+                  char* pszTmpPropertyName = msSmallMalloc(1+strlen(pszPropertyName)+1+1);
+                  sprintf(pszTmpPropertyName, "(%s)", pszPropertyName);
+                  tokens = msStringSplit(pszTmpPropertyName+1, '(', &nPropertyNames);
+                  free(pszTmpPropertyName);
+                } else
+                  tokens = msStringSplit(pszPropertyName+1, '(', &nPropertyNames);
+
+                /*expecting to always have a list of property names equal to
+                  the number of layers(typename)*/
+                if (nPropertyNames != numlayers) {
+                  if (tokens)
+                    msFreeCharArray(tokens, nPropertyNames);
+                  msSetError(MS_WFSERR,
+                             "Optional PROPERTYNAME parameter. A list of properties may be specified for each type name. Example TYPENAME=name1&name2&PROPERTYNAME=(prop1,prop2)(prop1)",
+                             "msWFSGetFeature()");
+                  return msWFSException(map, "PROPERTYNAME", "InvalidParameterValue", paramsObj->pszVersion);
+                }
+
+                papszPropertyName = (char **)msSmallMalloc(sizeof(char *)*nPropertyNames);
+                for (i=0; i<nPropertyNames; i++) {
+                  if (strlen(tokens[i]) > 0) {
+                    /*trim namespaces. PROPERTYNAME=(ns:prop1,ns:prop2)(prop1)*/
+                    if (strstr(tokens[i], ":")) {
+                      char **tokens1, **tokens2;
+                      int n1=0,n2=0,l=0;
+                      char *pszTmp = NULL;
+
+                      tokens1 = msStringSplit(tokens[i], ',', &n1);
+                      for (l=0; l<n1; l++) {
+                        if (pszTmp!=NULL)
+                          pszTmp = msStringConcatenate(pszTmp,",");
+
+                        if (strstr(tokens1[l],":")) {
+                          tokens2 = msStringSplit(tokens1[l], ':', &n2);
+                          if (tokens2 && n2==2)
+                            pszTmp = msStringConcatenate(pszTmp, tokens2[1]);
                           else
-                            papszPropertyName[i] = NULL; /*should return an error*/
+                            pszTmp = msStringConcatenate(pszTmp,tokens1[l]);
+                          if (tokens2 && n2>0)
+                            msFreeCharArray(tokens2, n2);
+                        } else
+                          pszTmp = msStringConcatenate(pszTmp,tokens1[l]);
                       }
-                      if (tokens) 
-                        msFreeCharArray(tokens, nPropertyNames);
+                      papszPropertyName[i] = msStrdup(pszTmp);
+                      msFree(pszTmp);
+                      if (tokens1 && n1>0)
+                        msFreeCharArray(tokens1, n1);
+                    } else
+                      papszPropertyName[i] = msStrdup(tokens[i]);
+                    /* remove trailing ) */
+                    papszPropertyName[i][strlen(papszPropertyName[i])-1] = '\0';
+                  } else
+                    papszPropertyName[i] = NULL; /*should return an error*/
+                }
+                if (tokens)
+                  msFreeCharArray(tokens, nPropertyNames);
+              } else {
+                msSetError(MS_WFSERR,
+                           "Optional PROPERTYNAME parameter. A list of properties may be specified for each type name. Example TYPENAME=name1&name2&PROPERTYNAME=(prop1,prop2)(prop1)",
+                           "msWFSGetFeature()");
+                return msWFSException(map, "PROPERTYNAME", "InvalidParameterValue", paramsObj->pszVersion);
+              }
+            }
+            /*do an alias replace for the current layer*/
+            if (papszPropertyName && msLayerOpen(lp) == MS_SUCCESS && msLayerGetItems(lp) == MS_SUCCESS) {
+              for(z=0; z<lp->numitems; z++) {
+                if (!lp->items[z] || strlen(lp->items[z]) <= 0)
+                  continue;
+                snprintf(szTmp, sizeof(szTmp), "%s_alias", lp->items[z]);
+                pszFullName = msOWSLookupMetadata(&(lp->metadata), "G", szTmp);
+                if (pszFullName)
+                  papszPropertyName[k] = msReplaceSubstring(papszPropertyName[k], pszFullName, lp->items[z]);
+
+              }
+
+              /*validate that the property names passed are part of the items list*/
+              tokens = msStringSplit(papszPropertyName[k], ',', &n);
+              for (y=0; y<n; y++) {
+                if (tokens[y] && strlen(tokens[y]) > 0) {
+                  if (strcasecmp(tokens[y], "*") == 0 ||
+                      strcasecmp(tokens[y], "!") == 0)
+                    continue;
+                  for(z=0; z<lp->numitems; z++) {
+                    if (strcasecmp(tokens[y], lp->items[z]) == 0)
+                      break;
                   }
+                  /*we need to check of the property name is the geometry name; In that case it
+                    is a valid property name*/
+                  if (msOWSLookupMetadata(&(lp->metadata), "OFG", "geometries") != NULL)
+                    snprintf(szTmp, sizeof(szTmp), "%s", msOWSLookupMetadata(&(lp->metadata), "OFG", "geometries"));
                   else
-                  {
-                      msSetError(MS_WFSERR, 
-                                     "Optional PROPERTYNAME parameter. A list of properties may be specified for each type name. Example TYPENAME=name1&name2&PROPERTYNAME=(prop1,prop2)(prop1)", 
-                                     "msWFSGetFeature()");
-                          return msWFSException(map, "PROPERTYNAME", "InvalidParameterValue", paramsObj->pszVersion);
+                    snprintf(szTmp, sizeof(szTmp), OWS_GML_DEFAULT_GEOMETRY_NAME);
+                  if (z == lp->numitems && strcasecmp(tokens[y], szTmp) != 0) {
+                    msSetError(MS_WFSERR,
+                               "Invalid PROPERTYNAME %s",  "msWFSGetFeature()", tokens[y]);
+                    msFreeCharArray(tokens, n);
+                    return msWFSException(map, "PROPERTYNAME", "InvalidParameterValue", paramsObj->pszVersion);
                   }
+                }
               }
-              /*do an alias replace for the current layer*/
-              if (papszPropertyName && msLayerOpen(lp) == MS_SUCCESS && msLayerGetItems(lp) == MS_SUCCESS) 
-              {
-                  for(z=0; z<lp->numitems; z++) 
-                  {
-                      if (!lp->items[z] || strlen(lp->items[z]) <= 0)
-                        continue;
-                      snprintf(szTmp, sizeof(szTmp), "%s_alias", lp->items[z]);
-                      pszFullName = msOWSLookupMetadata(&(lp->metadata), "G", szTmp);
-                      if (pszFullName)
-                        papszPropertyName[k] = msReplaceSubstring(papszPropertyName[k], pszFullName, lp->items[z]);
-                  
-                  }
+              if (tokens && n > 0)
+                msFreeCharArray(tokens, n);
+              msLayerClose(lp);
+            }
 
-                  /*validate that the property names passed are part of the items list*/
-                  tokens = msStringSplit(papszPropertyName[k], ',', &n);
-                  for (y=0; y<n; y++)
-                  {
-                      if (tokens[y] && strlen(tokens[y]) > 0)
-                      {
-                          if (strcasecmp(tokens[y], "*") == 0 ||
-                              strcasecmp(tokens[y], "!") == 0)
-                            continue;
-                          for(z=0; z<lp->numitems; z++) 
-                          {
-                              if (strcasecmp(tokens[y], lp->items[z]) == 0)
-                                break;
-                          }
-                          /*we need to check of the property name is the geometry name; In that case it
-                            is a valid property name*/
-                          if (msOWSLookupMetadata(&(lp->metadata), "OFG", "geometries") != NULL) 
-                              snprintf(szTmp, sizeof(szTmp), "%s", msOWSLookupMetadata(&(lp->metadata), "OFG", "geometries"));
-                          else
-                              snprintf(szTmp, sizeof(szTmp), OWS_GML_DEFAULT_GEOMETRY_NAME);
-                          if (z == lp->numitems && strcasecmp(tokens[y], szTmp) != 0)
-                          {
-                              msSetError(MS_WFSERR, 
-                                         "Invalid PROPERTYNAME %s",  "msWFSGetFeature()", tokens[y]);
-                              msFreeCharArray(tokens, n);
-                              return msWFSException(map, "PROPERTYNAME", "InvalidParameterValue", paramsObj->pszVersion);
-                          }
-                      }
-                  }
-                  if (tokens && n > 0)
-                    msFreeCharArray(tokens, n);
-                  msLayerClose(lp);
-              } 
-                      
-
-              if (papszPropertyName) 
-              {
-                  if (strlen(papszPropertyName[k]) > 0)
-                  {
-                      if (strcasecmp(papszPropertyName[k], "*") == 0)
-                      {
-                          msInsertHashTable(&(lp->metadata), "GML_INCLUDE_ITEMS", "all");
-                      }
-                      /*this character is only used internally and allows postrequest to 
-                        have a proper property name parsing. It means do not affect what was set
-                      in the map file, It is set necessary when a wfs post request is used with 
-                      several query elements, with some having property names and some not*/
-                      else if (strcasecmp(papszPropertyName[k], "!") == 0)
-                      {
-                      }
-                      else
-                      {
-                          msInsertHashTable(&(lp->metadata), "GML_INCLUDE_ITEMS", papszPropertyName[k]);
 
-                          /* exclude geometry if it was not asked for */
-                          if (msOWSLookupMetadata(&(lp->metadata), "OFG", "geometries") != NULL) 
-                            snprintf(szTmp, sizeof(szTmp), "%s", msOWSLookupMetadata(&(lp->metadata), "OFG", "geometries"));
-                          else
-                            snprintf(szTmp, sizeof(szTmp), OWS_GML_DEFAULT_GEOMETRY_NAME);
-                          
-                          if (strstr(papszPropertyName[k], szTmp) == NULL) 
-                            msInsertHashTable(&(lp->metadata), "GML_GEOMETRIES", "none");
-                      }
-                  }
-                  else /*empty string*/
-                     msInsertHashTable(&(lp->metadata), "GML_GEOMETRIES", "none");
+            if (papszPropertyName) {
+              if (strlen(papszPropertyName[k]) > 0) {
+                if (strcasecmp(papszPropertyName[k], "*") == 0) {
+                  msInsertHashTable(&(lp->metadata), "GML_INCLUDE_ITEMS", "all");
+                }
+                /*this character is only used internally and allows postrequest to
+                  have a proper property name parsing. It means do not affect what was set
+                in the map file, It is set necessary when a wfs post request is used with
+                several query elements, with some having property names and some not*/
+                else if (strcasecmp(papszPropertyName[k], "!") == 0) {
+                } else {
+                  msInsertHashTable(&(lp->metadata), "GML_INCLUDE_ITEMS", papszPropertyName[k]);
+
+                  /* exclude geometry if it was not asked for */
+                  if (msOWSLookupMetadata(&(lp->metadata), "OFG", "geometries") != NULL)
+                    snprintf(szTmp, sizeof(szTmp), "%s", msOWSLookupMetadata(&(lp->metadata), "OFG", "geometries"));
+                  else
+                    snprintf(szTmp, sizeof(szTmp), OWS_GML_DEFAULT_GEOMETRY_NAME);
 
-              }
+                  if (strstr(papszPropertyName[k], szTmp) == NULL)
+                    msInsertHashTable(&(lp->metadata), "GML_GEOMETRIES", "none");
+                }
+              } else /*empty string*/
+                msInsertHashTable(&(lp->metadata), "GML_GEOMETRIES", "none");
+
+            }
           }
         }
       }
 
       if (!bLayerFound) {
-	/* Requested layer name was not in capabilities:
-	 * either it just doesn't exist
-	 */
-	msSetError(MS_WFSERR, 
-		   "TYPENAME '%s' doesn't exist in this server.  Please check the capabilities and reformulate your request.",
-		   "msWFSGetFeature()", layers[k]);
-	return msWFSException(map, "typename", "InvalidParameterValue", paramsObj->pszVersion);
+        /* Requested layer name was not in capabilities:
+         * either it just doesn't exist
+         */
+        msSetError(MS_WFSERR,
+                   "TYPENAME '%s' doesn't exist in this server.  Please check the capabilities and reformulate your request.",
+                   "msWFSGetFeature()", layers[k]);
+        return msWFSException(map, "typename", "InvalidParameterValue", paramsObj->pszVersion);
       }
     }
   }
 
 
-  if (papszPropertyName && nPropertyNames > 0)
-  {
+  if (papszPropertyName && nPropertyNames > 0) {
     for (i=0; i<nPropertyNames; i++)
       msFree(papszPropertyName[i]);
 
@@ -1974,69 +1874,64 @@ int msWFSGetFeature(mapObj *map, wfsParamsObj *paramsObj, cgiRequestObj *req, ow
       gmlinfo.output_schema_format = "SFE_XMLSCHEMA";
       output_mime_type = "text/xml; subtype=gml/3.1.1";
     } else {
-        const char *format_list;
-        hashTableObj *md;
+      const char *format_list;
+      hashTableObj *md;
 
-        /* validate selected format against all selected layers. */
-        for(j=0; j < map->numlayers; j++) {
-            layerObj *lp;
-      
-            lp = GET_LAYER(map, j);
+      /* validate selected format against all selected layers. */
+      for(j=0; j < map->numlayers; j++) {
+        layerObj *lp;
 
-            if( lp->status != MS_ON )
-                continue;
+        lp = GET_LAYER(map, j);
 
-            md = &(lp->metadata);
-            format_list = msOWSLookupMetadata(md, "F","getfeature_formatlist");
-            if( format_list == NULL )
-            {
-                md = &(map->web.metadata);
-                format_list = msOWSLookupMetadata(md, "F","getfeature_formatlist");
-            }
-            if (format_list)
-            {
-                psFormat = msOwsIsOutputFormatValid(
-                    map, paramsObj->pszOutputFormat, md,
-                    "F", "getfeature_formatlist");
-            }
-            if (psFormat == NULL)
-            {
-                msSetError(MS_WFSERR, 
-                           "'%s' is not a permitted output format for layer '%s', review wfs_formats setting.",
-                           "msWFSGetFeature()",
-                           paramsObj->pszOutputFormat,
-                           lp->name );
-                return msWFSException(map, "outputformat", 
-                                      "InvalidParameterValue",
-                                      paramsObj->pszVersion );
-            }
+        if( lp->status != MS_ON )
+          continue;
 
-            if( psFormat->imagemode != MS_IMAGEMODE_FEATURE )
-            {
-                msSetError(MS_WFSERR, 
-                           "OUTPUTFORMAT '%s' does not have IMAGEMODE FEATURE, and is not permitted for WFS output.",
-                           "msWFSGetFeature()",
-                           paramsObj->pszOutputFormat );
-                return msWFSException( map, "outputformat",
-                                       "InvalidParameterValue",
-                                       paramsObj->pszVersion );
-            }
+        md = &(lp->metadata);
+        format_list = msOWSLookupMetadata(md, "F","getfeature_formatlist");
+        if( format_list == NULL ) {
+          md = &(map->web.metadata);
+          format_list = msOWSLookupMetadata(md, "F","getfeature_formatlist");
+        }
+        if (format_list) {
+          psFormat = msOwsIsOutputFormatValid(
+                       map, paramsObj->pszOutputFormat, md,
+                       "F", "getfeature_formatlist");
+        }
+        if (psFormat == NULL) {
+          msSetError(MS_WFSERR,
+                     "'%s' is not a permitted output format for layer '%s', review wfs_getfeature_formatlist setting.",
+                     "msWFSGetFeature()",
+                     paramsObj->pszOutputFormat,
+                     lp->name );
+          return msWFSException(map, "outputformat",
+                                "InvalidParameterValue",
+                                paramsObj->pszVersion );
         }
-    } 
 
-  /* If OUTPUTFORMAT not set, default to gml */
-  } else {
-      /*set the output format using the version if available*/
-      if(paramsObj->pszVersion == NULL || strncmp(paramsObj->pszVersion,"1.1",3) == 0 )
-      {
-          outputformat = OWS_GML3;
-          gmlinfo.output_schema_format = "text/xml;%20subtype=gml/3.1.1";
-          output_mime_type = "text/xml; subtype=gml/3.1.1";
+        if( psFormat->imagemode != MS_IMAGEMODE_FEATURE ) {
+          msSetError(MS_WFSERR,
+                     "OUTPUTFORMAT '%s' does not have IMAGEMODE FEATURE, and is not permitted for WFS output.",
+                     "msWFSGetFeature()",
+                     paramsObj->pszOutputFormat );
+          return msWFSException( map, "outputformat",
+                                 "InvalidParameterValue",
+                                 paramsObj->pszVersion );
+        }
       }
+    }
+
+    /* If OUTPUTFORMAT not set, default to gml */
+  } else {
+    /*set the output format using the version if available*/
+    if(paramsObj->pszVersion == NULL || strncmp(paramsObj->pszVersion,"1.1",3) == 0 ) {
+      outputformat = OWS_GML3;
+      gmlinfo.output_schema_format = "text/xml;%20subtype=gml/3.1.1";
+      output_mime_type = "text/xml; subtype=gml/3.1.1";
+    }
   }
 
   if(strncmp(paramsObj->pszVersion,"1.0",3) == 0 ) {
-          output_mime_type = "text/xml";
+    output_mime_type = "text/xml";
   }
 
   /* else if (strcasecmp(names[i], "PROPERTYNAME") == 0) */
@@ -2053,73 +1948,57 @@ int msWFSGetFeature(mapObj *map, wfsParamsObj *paramsObj, cgiRequestObj *req, ow
   }
 
   nQueriedLayers=0;
-  for(j=0; j<map->numlayers; j++) 
-  {
-      layerObj *lp;
-      lp = GET_LAYER(map, j);
-      if (lp->status == MS_ON)
-      {
-          lpQueried = GET_LAYER(map, j);
-          nQueriedLayers++;
-      }
+  for(j=0; j<map->numlayers; j++) {
+    layerObj *lp;
+    lp = GET_LAYER(map, j);
+    if (lp->status == MS_ON) {
+      lpQueried = GET_LAYER(map, j);
+      nQueriedLayers++;
+    }
   }
-  
-  if (paramsObj->nStartIndex > 0)
+
+  if (paramsObj->nStartIndex > 0) {
     startindex = paramsObj->nStartIndex;
+    map->query.startindex = startindex;    
+  } 
 
 
-  /*maxfeatures set but no startindex*/
-  if (maxfeatures > 0 && startindex < 0)
-  {
-      for(j=0; j<map->numlayers; j++) 
-      {
-          layerObj *lp;
-          lp = GET_LAYER(map, j);
-          if (lp->status == MS_ON)
-          {
-              /*over-ride the value only if it is unset or wfs maxfeattures is
-                lower that what is currently set*/
-              if (lp->maxfeatures <=0 || (lp->maxfeatures > 0 && maxfeatures < lp->maxfeatures))
-                lp->maxfeatures = maxfeatures;
-          }
-      }
-  }
-  
-  /*no maxfeatures set but startindex set*/
-  if (maxfeatures <=0 && startindex > 0)
-  {
-      if (nQueriedLayers == 1 && msLayerSupportsPaging(lpQueried))
-      {
-          lpQueried->startindex = startindex;
-          startindex = -1;
+  /* maxfeatures set */
+  if (maxfeatures > 0) {
+    for(j=0; j<map->numlayers; j++) {
+      layerObj *lp;
+      lp = GET_LAYER(map, j);
+      if (lp->status == MS_ON) {
+        /*over-ride the value only if it is unset or wfs maxfeattures is
+          lower that what is currently set*/
+        if (lp->maxfeatures <=0 || (lp->maxfeatures > 0 && maxfeatures < lp->maxfeatures))
+          lp->maxfeatures = maxfeatures;
       }
+    }
+    map->query.maxfeatures = maxfeatures;
   }
 
-  /*maxfeatures set and startindex set*/
-  if (maxfeatures >0 && startindex > 0)
-  {
-      if (nQueriedLayers == 1 && msLayerSupportsPaging(lpQueried))
-      {
-          lpQueried->startindex = startindex;
-          if (lpQueried->maxfeatures <=0 || 
-              (lpQueried->maxfeatures > 0 && maxfeatures < lpQueried->maxfeatures))
-            lpQueried->maxfeatures = maxfeatures;
-          
-          startindex = -1;
-          maxfeatures = -1;
+  /* startindex set */
+  if (startindex > 0 && nQueriedLayers > 1) {
+    for(j=0; j<map->numlayers; j++) {
+      layerObj *lp;
+      lp = GET_LAYER(map, j);
+      if (lp->status == MS_ON) {
+        msLayerEnablePaging(lp, MS_FALSE);
       }
+    }
+  } else if (startindex > 0 && lpQueried) {
+    lpQueried->startindex = startindex;    
   }
 
-
-  
   if (paramsObj->pszFilter) {
     bFilterSet = 1;
     pszFilter = paramsObj->pszFilter;
-  } 
+  }
   if (paramsObj->pszBbox) {
     char **tokens;
     int n;
-    
+
 
     tokens = msStringSplit(paramsObj->pszBbox, ',', &n);
     if (tokens==NULL || (n != 4 && n !=5)) {
@@ -2143,543 +2022,446 @@ int msWFSGetFeature(mapObj *map, wfsParamsObj *paramsObj, cgiRequestObj *req, ow
     bFeatureIdSet = 1;
   }
 
-
- 
 #ifdef USE_OGR
-    if (bFilterSet && pszFilter && strlen(pszFilter) > 0) {
-      char **tokens = NULL;
-      int nFilters;
-      FilterEncodingNode *psNode = NULL;
-      int iLayerIndex =1;
-      char **paszFilter = NULL;
-      errorObj   *ms_error;
-      
-      /* -------------------------------------------------------------------- */
-      /*      Validate the parameters. When a FILTER parameter is given,      */
-      /*      It needs the TYPENAME parameter for the layers. Also Filter     */
-      /*      is Mutually exclusive with FEATUREID and BBOX (see wfs specs    */
-      /*      1.0 section 13.7.3 on GetFeature)                               */
-      /*                                                                      */
-      /* -------------------------------------------------------------------- */
+  if (bFilterSet && pszFilter && strlen(pszFilter) > 0) {
+    char **tokens = NULL;
+    int nFilters;
+    FilterEncodingNode *psNode = NULL;
+    int iLayerIndex =1;
+    char **paszFilter = NULL;
+    errorObj   *ms_error;
+
+    /* -------------------------------------------------------------------- */
+    /*      Validate the parameters. When a FILTER parameter is given,      */
+    /*      It needs the TYPENAME parameter for the layers. Also Filter     */
+    /*      is Mutually exclusive with FEATUREID and BBOX (see wfs specs    */
+    /*      1.0 section 13.7.3 on GetFeature)                               */
+    /*                                                                      */
+    /* -------------------------------------------------------------------- */
+
+    if (gmlinfo.typename == NULL || strlen(gmlinfo.typename) <= 0 || layers == NULL || numlayers <= 0) {
+      msSetError(MS_WFSERR,
+                 "Required TYPENAME parameter missing for GetFeature with a FILTER parameter.",
+                 "msWFSGetFeature()");
+      return msWFSException(map, "typename", "MissingParameterValue", paramsObj->pszVersion);
+    }
 
-      if (gmlinfo.typename == NULL || strlen(gmlinfo.typename) <= 0 || layers == NULL || numlayers <= 0) {
-	msSetError(MS_WFSERR, 
-                   "Required TYPENAME parameter missing for GetFeature with a FILTER parameter.", 
-                   "msWFSGetFeature()");
-	return msWFSException(map, "typename", "MissingParameterValue", paramsObj->pszVersion);
-      }
-       
-      if (bBBOXSet) {
-	msSetError(MS_WFSERR, 
-                   "BBOX parameter and FILTER parameter are mutually exclusive in GetFeature.", 
-                   "msWFSGetFeature()");
-	return msWFSException(map, "mapserv", "NoApplicableCode", paramsObj->pszVersion);
-      }
+    if (bBBOXSet) {
+      msSetError(MS_WFSERR,
+                 "BBOX parameter and FILTER parameter are mutually exclusive in GetFeature.",
+                 "msWFSGetFeature()");
+      return msWFSException(map, "mapserv", "NoApplicableCode", paramsObj->pszVersion);
+    }
 
-      if (bFeatureIdSet) {
-	msSetError(MS_WFSERR, 
-                   "FEATUREID parameter and FILTER parameter are mutually exclusive in GetFeature.", 
-                   "msWFSGetFeature()");
-	return msWFSException(map, "mapserv", "NoApplicableCode", paramsObj->pszVersion);
+    if (bFeatureIdSet) {
+      msSetError(MS_WFSERR,
+                 "FEATUREID parameter and FILTER parameter are mutually exclusive in GetFeature.",
+                 "msWFSGetFeature()");
+      return msWFSException(map, "mapserv", "NoApplicableCode", paramsObj->pszVersion);
+    }
+
+    /* -------------------------------------------------------------------- */
+    /*      Parse the Filter parameter. If there are several Filter         */
+    /*      parameters, each Filter is inside a parantheses. Eg :           */
+    /*      FILTER=(<Filter><Within><PropertyName>                          */
+    /*      INWATERA_1M/WKB_GEOM|INWATERA_1M/WKB_GEOM                       */
+    /*      <PropertyName><gml:Box><gml:coordinates>10,10 20,20</gml:coordinates>*/
+    /*      </gml:Box></Within></Filter>)(<Filter><Within><PropertyName>    */
+    /*      INWATERA_1M/WKB_GEOM<PropertyName><gml:Box><gml:coordinates>10,10*/
+    /*      20,20</gml:coordinates></gml:Box></Within></Filter>)            */
+    /* -------------------------------------------------------------------- */
+    nFilters = 0;
+    if (strlen(pszFilter) > 0 && pszFilter[0] == '(') {
+      tokens = msStringSplit(pszFilter+1, '(', &nFilters);
+
+      if (tokens &&  nFilters > 0 && numlayers == nFilters) {
+        paszFilter = (char **)msSmallMalloc(sizeof(char *)*nFilters);
+        for (i=0; i<nFilters; i++)
+          paszFilter[i] = msStrdup(tokens[i]);
+
+        msFreeCharArray(tokens, nFilters);
       }
+    } else if (numlayers == 1) {
+      nFilters=1;
+      paszFilter = (char **)msSmallMalloc(sizeof(char *)*nFilters);
+      paszFilter[0] = pszFilter;
+    }
 
-      /* -------------------------------------------------------------------- */
-      /*      Parse the Filter parameter. If there are several Filter         */
-      /*      parameters, each Filter is inside a parantheses. Eg :           */
-      /*      FILTER=(<Filter><Within><PropertyName>                          */
-      /*      INWATERA_1M/WKB_GEOM|INWATERA_1M/WKB_GEOM                       */
-      /*      <PropertyName><gml:Box><gml:coordinates>10,10 20,20</gml:coordinates>*/
-      /*      </gml:Box></Within></Filter>)(<Filter><Within><PropertyName>    */
-      /*      INWATERA_1M/WKB_GEOM<PropertyName><gml:Box><gml:coordinates>10,10*/
-      /*      20,20</gml:coordinates></gml:Box></Within></Filter>)            */
-      /* -------------------------------------------------------------------- */
-      nFilters = 0;
-      if (strlen(pszFilter) > 0 && pszFilter[0] == '(') 
-      {
-          tokens = msStringSplit(pszFilter+1, '(', &nFilters);
-	
-          if (tokens &&  nFilters > 0 && numlayers == nFilters)
-          {
-              paszFilter = (char **)msSmallMalloc(sizeof(char *)*nFilters);
-              for (i=0; i<nFilters; i++)
-                paszFilter[i] = msStrdup(tokens[i]);
-	
-              msFreeCharArray(tokens, nFilters);
-          }
-      } 
-      else if (numlayers == 1)
-      {
-          nFilters=1;
-          paszFilter = (char **)msSmallMalloc(sizeof(char *)*nFilters);
-          paszFilter[0] = pszFilter;
+    if (numlayers != nFilters) {
+      msSetError(MS_WFSERR, "Wrong number of filter elements, one filter must be specified for each feature type listed in the TYPENAME parameter.",
+                 "msWFSGetFeature()");
+      return msWFSException(map, "filter", "InvalidParameterValue", paramsObj->pszVersion);
+    }
+    /* -------------------------------------------------------------------- */
+    /*      run through the filters and build the class expressions.        */
+    /*      TODO: items may have namespace prefixes, or reference aliases,  */
+    /*      or groups. Need to be a bit more sophisticated here.            */
+    /* -------------------------------------------------------------------- */
+    for (i=0; i<nFilters; i++) {
+      iLayerIndex = msGetLayerIndex(map, layers[i]);
+      if (iLayerIndex < 0) {
+        msSetError(MS_WFSERR, "Invalid Typename in GetFeature : %s. A layer might be disabled for \
+this request. Check wfs/ows_enable_request settings.", "msWFSGetFeature()", layers[i]);
+        return msWFSException(map, "typename", "InvalidParameterValue", paramsObj->pszVersion);
       }
-      
-      if (numlayers != nFilters)
-      {
-          msSetError(MS_WFSERR, "Wrong number of filter elements, one filter must be specified for each feature type listed in the TYPENAME parameter.",
-                     "msWFSGetFeature()");
-          return msWFSException(map, "filter", "InvalidParameterValue", paramsObj->pszVersion);
+      psNode = FLTParseFilterEncoding(paszFilter[i]);
+
+      if (!psNode) {
+        msSetError(MS_WFSERR,
+                   "Invalid or Unsupported FILTER in GetFeature : %s",
+                   "msWFSGetFeature()", pszFilter);
+        return msWFSException(map, "filter", "InvalidParameterValue", paramsObj->pszVersion);
       }
-      /* -------------------------------------------------------------------- */
-      /*      run through the filters and build the class expressions.        */
-      /*      TODO: items may have namespace prefixes, or reference aliases,  */
-      /*      or groups. Need to be a bit more sophisticated here.            */
-      /* -------------------------------------------------------------------- */
-      for (i=0; i<nFilters; i++) {
-	iLayerIndex = msGetLayerIndex(map, layers[i]);
-	if (iLayerIndex < 0) {
-	  msSetError(MS_WFSERR, "Invalid Typename in GetFeature : %s", "msWFSGetFeature()", layers[i]);
-	  return msWFSException(map, "typename", "InvalidParameterValue", paramsObj->pszVersion);
-	}
-	psNode = FLTParseFilterEncoding(paszFilter[i]);
-	
-        /*if we have a complex filter, make sure that paging is done at the gml output level
-          and not at the driver level #3305*/
-        bComplexFilter = (!FLTIsSimpleFilter(psNode));
-        if (bComplexFilter && nQueriedLayers == 1 && lpQueried &&
-            msLayerSupportsPaging(lpQueried) && 
-            (lpQueried->startindex > 0 && lpQueried->maxfeatures > 0))
-        {
-            startindex = lpQueried->startindex;
-            lpQueried->startindex = -1;
-
-            maxfeatures = lpQueried->maxfeatures;
-            lpQueried->maxfeatures = -1;
-        }
 
-	if (!psNode) {
-	  msSetError(MS_WFSERR, 
-		     "Invalid or Unsupported FILTER in GetFeature : %s", 
-		     "msWFSGetFeature()", pszFilter);
-	  return msWFSException(map, "filter", "InvalidParameterValue", paramsObj->pszVersion);
-	}
+      /*preparse the filter for gml aliases*/
+      FLTPreParseFilterForAlias(psNode, map, iLayerIndex, "G");
 
-        /*preparse the filter for gml aliases*/
-        FLTPreParseFilterForAlias(psNode, map, iLayerIndex, "G");
+      if (msWFSGetFeatureApplySRS(map, paramsObj->pszSrs, paramsObj->pszVersion) == MS_FAILURE)
+        return msWFSException(map, "typename", "InvalidParameterValue", paramsObj->pszVersion);
 
-        /* run filter.  If no results are found, do not throw exception */
-        /* this is a null result */
-        if( FLTApplyFilterToLayer(psNode, map, iLayerIndex) != MS_SUCCESS ) 
-        {
-            ms_error = msGetErrorObj();
-	
-            if(ms_error->code != MS_NOTFOUND)
-            {
-                msSetError(MS_WFSERR, "FLTApplyFilterToLayer() failed", "msWFSGetFeature()", pszFilter);
-                return msWFSException(map, "mapserv", "NoApplicableCode", paramsObj->pszVersion);
-            }
-        }
+      /* run filter.  If no results are found, do not throw exception */
+      /* this is a null result */
+      if( FLTApplyFilterToLayer(psNode, map, iLayerIndex) != MS_SUCCESS ) {
+        ms_error = msGetErrorObj();
 
-         FLTFreeFilterEncodingNode( psNode );
-        psNode = NULL;
+        if(ms_error->code != MS_NOTFOUND) {
+          msSetError(MS_WFSERR, "FLTApplyFilterToLayer() failed", "msWFSGetFeature()", pszFilter);
+          return msWFSException(map, "mapserv", "NoApplicableCode", paramsObj->pszVersion);
+        }
       }
 
-      if (paszFilter)
-	free(paszFilter);
-    }/* end if filter set */
-
+      FLTFreeFilterEncodingNode( psNode );
+      psNode = NULL;
+    }
 
-    if (bFeatureIdSet)
-    {
-        char **tokens = NULL, **tokens1=NULL ;
-        int nTokens = 0, j=0, nTokens1=0, k=0;
-        FilterEncodingNode *psNode = NULL;
+    if (paszFilter)
+      free(paszFilter);
+  }/* end if filter set */
 
-        /* Keep only selected layers, set to OFF by default. */
-        for(j=0; j<map->numlayers; j++) 
-        {
-            layerObj *lp;
-            lp = GET_LAYER(map, j);
-            lp->status = MS_OFF;
-        }
-        /*featureid can be a list INWATERA_1M.1234, INWATERA_1M.1235
-        We will keep all the feature id from the same layer together
-        so that an OR would be applied if several of them are present
-        */
-         tokens = msStringSplit(paramsObj->pszFeatureId, ',', &nTokens);
-         iFIDLayers = 0;
-         if (tokens && nTokens >=1)
-         {
-             aFIDLayers = (char **)msSmallMalloc(sizeof(char *)*nTokens);
-             aFIDValues = (char **)msSmallMalloc(sizeof(char *)*nTokens);
-             for (j=0; j<nTokens; j++)
-             {
-                 aFIDLayers[j] = NULL;
-                 aFIDValues[j] = NULL;
-             }
-             for (j=0; j<nTokens; j++)
-             {
-                 tokens1 = msStringSplit(tokens[j], '.', &nTokens1);
-                 if (tokens1 && nTokens1 == 2)
-                 {
-                     for (k=0; k<iFIDLayers; k++)
-                     {
-                         if (strcasecmp(aFIDLayers[k], tokens1[0]) == 0)
-                           break;
-                     }
-                     if (k == iFIDLayers)
-                     {
-                         aFIDLayers[iFIDLayers] = msStrdup(tokens1[0]);
-                         iFIDLayers++;
-                     }
-                     if (aFIDValues[k] != NULL)
-                       aFIDValues[k] = msStringConcatenate(aFIDValues[k], ",");
-                     aFIDValues[k] = msStringConcatenate( aFIDValues[k], tokens1[1]);
-                 }
-                 else
-                 {
-                     msSetError(MS_WFSERR, 
-		     "Invalid FeatureId in GetFeature. Expecting layername.value : %s", 
-		     "msWFSGetFeature()", pszFilter);
-                     if (tokens)
-                       msFreeCharArray(tokens, nTokens);
-                     if (tokens1)
-                       msFreeCharArray(tokens1, nTokens1);
-                     return msWFSException(map, "featureid", "InvalidParameterValue", paramsObj->pszVersion);
-                 }
-                 if (tokens1)
-                    msFreeCharArray(tokens1, nTokens1);
-             }
-         }
-         if (tokens)
-           msFreeCharArray(tokens, nTokens);
-    
-         /*turn on the layers and make sure projections are set properly*/
-         for (j=0; j< iFIDLayers; j++)
-         {
-             for (k=0; k<map->numlayers; k++) 
-             {
-                 layerObj *lp;
-                 lp = GET_LAYER(map, k);
-                 if (msWFSIsLayerSupported(lp) && lp->name && 
-                     strcasecmp(lp->name, aFIDLayers[j]) == 0)
-                 {
-                     lp->status = MS_ON;
-                 }
-             }
-             if (msWFSGetFeatureApplySRS(map, paramsObj->pszSrs, paramsObj->pszVersion) == MS_FAILURE)
-               return msWFSException(map, "typename", "InvalidParameterValue", paramsObj->pszVersion);
-         }
-    
-         for (j=0; j< iFIDLayers; j++)
-         {
-             for (k=0; k<map->numlayers; k++) 
-             {
-                 layerObj *lp;
-                 lp = GET_LAYER(map, k);
-                 if (msWFSIsLayerSupported(lp) && lp->name && 
-                     strcasecmp(lp->name, aFIDLayers[j]) == 0)
-                 {
-                     lp->status = MS_ON;
-                     if (lp->template == NULL) {
-                         /* Force setting a template to enable query. */
-                         lp->template = msStrdup("ttt.html");
-                     }
-                     psNode = FLTCreateFeatureIdFilterEncoding(aFIDValues[j]);
-
-                     if( FLTApplyFilterToLayer(psNode, map, lp->index) != MS_SUCCESS ) {
-                       msSetError(MS_WFSERR, "FLTApplyFilterToLayer() failed", "msWFSGetFeature");
-                       return msWFSException(map, "mapserv", "NoApplicableCode", paramsObj->pszVersion);
-                     }
-
-                     FLTFreeFilterEncodingNode( psNode );
-                     psNode = NULL;
-                     break;
-                 }
-             }
-             if (k == map->numlayers)/*layer not found*/
-             {
-                 msSetError(MS_WFSERR, 
-                            "Invalid typename given with FeatureId in GetFeature : %s", "msWFSGetFeature()", 
-                            aFIDLayers[j]);
-
-                 if (aFIDLayers && aFIDValues)
-                 {      
-                     for (j=0; j<iFIDLayers; j++)
-                     {
-                         msFree(aFIDLayers[j]);
-                         msFree(aFIDValues[j]);
-                     }
-                     msFree(aFIDLayers);
-                     msFree(aFIDValues);
-                 }
-                 return msWFSException(map, "featureid", "InvalidParameterValue", paramsObj->pszVersion);
-             }
-         }
-
-         if (aFIDLayers && aFIDValues)
-         {
-             for (j=0; j<iFIDLayers; j++)
-             {
-                 msFree(aFIDLayers[j]);
-                 msFree(aFIDValues[j]);
-             }
-             msFree(aFIDLayers);
-             msFree(aFIDValues);
-         }
-    }
-#endif /* USE_OGR */
 
-    
-    if(layers)
-      msFreeCharArray(layers, numlayers);
+  if (bFeatureIdSet) {
+    char **tokens = NULL, **tokens1=NULL ;
+    int nTokens = 0, j=0, nTokens1=0, k=0;
+    FilterEncodingNode *psNode = NULL;
 
- 
- if (msWFSGetFeatureApplySRS(map, paramsObj->pszSrs, paramsObj->pszVersion) == MS_FAILURE)
-      return msWFSException(map, "typename", "InvalidParameterValue", paramsObj->pszVersion);
- 
-    /*
-    ** Perform Query (only BBOX for now)
+    /* Keep only selected layers, set to OFF by default. */
+    for(j=0; j<map->numlayers; j++) {
+      layerObj *lp;
+      lp = GET_LAYER(map, j);
+      lp->status = MS_OFF;
+    }
+    /*featureid can be a list INWATERA_1M.1234, INWATERA_1M.1235
+    We will keep all the feature id from the same layer together
+    so that an OR would be applied if several of them are present
     */
-    /* __TODO__ Using a rectangle query may not be the most efficient way */
-    /* to do things here. */
-    if (!bFilterSet && !bFeatureIdSet) {
-
-      if (!bBBOXSet)
-      {
-          const char *pszMapSRS=NULL, *pszLayerSRS=NULL;
-          bbox = map->extent;
-          map->query.type = MS_QUERY_BY_RECT; /* setup the query */
-          map->query.mode = MS_QUERY_MULTIPLE;
-
-          /*if srsName was given for wfs 1.1.0, It is at this point loaded into the 
-            map object and should be used*/
-          if(!paramsObj->pszSrs)
-            pszMapSRS = msOWSGetEPSGProj(&(map->projection), &(map->web.metadata), "FO", MS_TRUE);
-          for(j=0; j<map->numlayers; j++) 
-          {
-              layerObj *lp;
-              rectObj ext;
-              int status;
-              lp = GET_LAYER(map, j);
-              if (lp->status == MS_ON)
-              {
-                   if (msOWSGetLayerExtent(map, lp, "FO", &ext) == MS_SUCCESS) 
-                   {
-
-                       if (pszMapSRS != NULL && strncmp(pszMapSRS, "EPSG:", 5) == 0) {
-                
-                           if( msOWSParseVersionString(paramsObj->pszVersion) >= OWS_1_1_0 )
-                             status = msLoadProjectionStringEPSG(&(map->projection), pszMapSRS);
-                           else
-                             status = msLoadProjectionString(&(map->projection), pszMapSRS);
-
-                           if (status != 0) {
-                               msSetError(MS_WFSERR, "msLoadProjectionString() failed: %s", 
-                                          "msWFSGetFeature()", pszMapSRS);        
-                               return msWFSException(map, "mapserv", "NoApplicableCode", 
-                                                     paramsObj->pszVersion);
-                           }
-                           
-                       }
-
-                       /*make sure that the layer projectsion is loaded. 
-                         It could come from a ows/wfs_srs metadata*/
-                       if (lp->projection.numargs == 0)
-                       {
-                           pszLayerSRS = msOWSGetEPSGProj(&(lp->projection), &(lp->metadata), "FO", MS_TRUE);
-                           if (pszLayerSRS)
-                           {
-                               if (strncmp(pszLayerSRS, "EPSG:", 5) == 0) 
-                               {
-                                   if( msOWSParseVersionString(paramsObj->pszVersion) >= OWS_1_1_0 )
-                                     msLoadProjectionStringEPSG(&(lp->projection), pszLayerSRS);
-                                   else
-                                     msLoadProjectionString(&(lp->projection), pszLayerSRS);
-                               }
-                           }
-                       }
-
-                       if (msProjectionsDiffer(&map->projection, &lp->projection) == MS_TRUE) {
-                           msProjectRect(&lp->projection, &map->projection, &(ext));
-                       }
-                       bbox = ext;
-                   }
-                   map->query.rect = bbox;
-                   map->query.layer = j;
-                   if(msQueryByRect(map) != MS_SUCCESS) 
-                   {
-                       errorObj   *ms_error;
-                       ms_error = msGetErrorObj();
-	
-                       if(ms_error->code != MS_NOTFOUND) {
-                           msSetError(MS_WFSERR, "ms_error->code not found", "msWFSGetFeature()");
-                           return msWFSException(map, "mapserv", "NoApplicableCode", paramsObj->pszVersion);
-                       }
-                   }
-              }
-          }
+    tokens = msStringSplit(paramsObj->pszFeatureId, ',', &nTokens);
+    iFIDLayers = 0;
+    if (tokens && nTokens >=1) {
+      aFIDLayers = (char **)msSmallMalloc(sizeof(char *)*nTokens);
+      aFIDValues = (char **)msSmallMalloc(sizeof(char *)*nTokens);
+      for (j=0; j<nTokens; j++) {
+        aFIDLayers[j] = NULL;
+        aFIDValues[j] = NULL;
       }
-      else
-      {
-          if (sBBoxSrs)
-          {
-              int status;
-              projectionObj sProjTmp;
-
-              msInitProjection(&sProjTmp);
-              /*do the axis order for now. It is unclear if the bbox are expected
-                ro respect the axis oder defined in the projectsion #3296*/
-              
-              if(strncmp(paramsObj->pszVersion,"1.1",3) == 0)
-              {
-                  if ((status=msLoadProjectionStringEPSG(&sProjTmp, sBBoxSrs)) == 0)
-                  {
-                      msAxisNormalizePoints( &sProjTmp, 1, &bbox.minx, &bbox.miny );
-                      msAxisNormalizePoints( &sProjTmp, 1, &bbox.maxx, &bbox.maxy );
-                  }
-              }
-              else
-                status = msLoadProjectionString(&sProjTmp, sBBoxSrs);
-               
-               if (status == 0 &&  map->projection.numargs > 0)
-                 msProjectRect(&sProjTmp, &map->projection, &bbox);
-
-               msFree(sBBoxSrs);
+      for (j=0; j<nTokens; j++) {
+        tokens1 = msStringSplit(tokens[j], '.', &nTokens1);
+        if (tokens1 && nTokens1 == 2) {
+          for (k=0; k<iFIDLayers; k++) {
+            if (strcasecmp(aFIDLayers[k], tokens1[0]) == 0)
+              break;
           }
-          map->query.type = MS_QUERY_BY_RECT; /* setup the query */
-          map->query.mode = MS_QUERY_MULTIPLE;
-          map->query.rect = bbox;
-
-          if(msQueryByRect(map) != MS_SUCCESS) {
-              errorObj   *ms_error;
-              ms_error = msGetErrorObj();
-	
-              if(ms_error->code != MS_NOTFOUND) {
-                  msSetError(MS_WFSERR, "ms_error->code not found", "msWFSGetFeature()");
-                  return msWFSException(map, "mapserv", "NoApplicableCode", paramsObj->pszVersion);
-              }
+          if (k == iFIDLayers) {
+            aFIDLayers[iFIDLayers] = msStrdup(tokens1[0]);
+            iFIDLayers++;
           }
+          if (aFIDValues[k] != NULL)
+            aFIDValues[k] = msStringConcatenate(aFIDValues[k], ",");
+          aFIDValues[k] = msStringConcatenate( aFIDValues[k], tokens1[1]);
+        } else {
+          msSetError(MS_WFSERR,
+                     "Invalid FeatureId in GetFeature. Expecting layername.value : %s",
+                     "msWFSGetFeature()", pszFilter);
+          if (tokens)
+            msFreeCharArray(tokens, nTokens);
+          if (tokens1)
+            msFreeCharArray(tokens1, nTokens1);
+          return msWFSException(map, "featureid", "InvalidParameterValue", paramsObj->pszVersion);
+        }
+        if (tokens1)
+          msFreeCharArray(tokens1, nTokens1);
       }
     }
+    if (tokens)
+      msFreeCharArray(tokens, nTokens);
 
-    /* if no results where written (TODO: this needs to be GML2/3 specific I imagine */
-    for(j=0; j<map->numlayers; j++) {
-      if (GET_LAYER(map, j)->resultcache && GET_LAYER(map, j)->resultcache->numresults > 0)
-      {
-        iNumberOfFeatures += GET_LAYER(map, j)->resultcache->numresults;
+    /*turn on the layers and make sure projections are set properly*/
+    for (j=0; j< iFIDLayers; j++) {
+      for (k=0; k<map->numlayers; k++) {
+        layerObj *lp;
+        lp = GET_LAYER(map, k);
+        if (msWFSIsLayerSupported(lp) && lp->name &&
+            strcasecmp(lp->name, aFIDLayers[j]) == 0) {
+          lp->status = MS_ON;
+        }
+        if (msWFSGetFeatureApplySRS(map, paramsObj->pszSrs, paramsObj->pszVersion) == MS_FAILURE)
+          return msWFSException(map, "typename", "InvalidParameterValue", paramsObj->pszVersion);
       }
     }
-    if(maxfeatures > 0 && maxfeatures < iNumberOfFeatures)
-      iNumberOfFeatures = maxfeatures;
-
-    /*
-    ** GML Header generation.
-    */
 
-    status = MS_SUCCESS;
-
-    if( psFormat == NULL )
-    {
-        value = msOWSLookupMetadata(&(map->web.metadata), "FO", "encoding");
-        if (value)
-            msIO_printf("Content-type: %s; charset=%s%c%c", 
-                        output_mime_type, value,10,10);
-        else
-            msIO_printf("Content-type: %s%c%c", output_mime_type,10,10);
-
-        msWFSGetFeature_GMLPreamble( map, req, &gmlinfo, paramsObj, 
-                                     outputformat,
-                                     iResultTypeHits, 
-                                     iNumberOfFeatures );
-    }
-    
-    /* handle case of maxfeatures = 0 */
-    /*internally use a start index that start with with 0 as the first index*/
-    if( psFormat == NULL )
-    {
-        if(maxfeatures != 0 && iResultTypeHits == 0)
-            status = msGMLWriteWFSQuery(map, stdout, startindex-1, maxfeatures, 
-                                        (char *) gmlinfo.user_namespace_prefix,
-                                        outputformat);
-    }
-    else 
-    {
-        int to_allow = maxfeatures, to_skip = startindex-1;
-        mapservObj *mapserv = msAllocMapServObj();
-
-        /* Setup dummy mapserv object */
-        mapserv->sendheaders = MS_TRUE;
-        mapserv->map = map;
-        msFreeCgiObj(mapserv->request);
-        mapserv->request = req;
-        map->querymap.status = MS_FALSE;
-
-        /* trim the query result(s) if maxfeatures or startindex set. */
-        for( j=0; j < map->numlayers; j++ ) {
-            layerObj *lp = GET_LAYER(map, j);
-            if (lp->resultcache && lp->resultcache->numresults > 0)
-            {
-                if( to_skip > 0 && lp->resultcache->numresults < to_skip )
-                {
-                    to_skip -= lp->resultcache->numresults;
-                    lp->resultcache->numresults = 0;
-                }
-                else if( to_skip > 0 )
-                {
-                    memmove( lp->resultcache->results + 0,
-                             lp->resultcache->results + to_skip, 
-                             sizeof(resultObj) * (lp->resultcache->numresults - to_skip) );
-                    lp->resultcache->numresults -= to_skip;
-                    to_skip = 0;
-                }
+    for (j=0; j< iFIDLayers; j++) {
+      for (k=0; k<map->numlayers; k++) {
+        layerObj *lp;
+        lp = GET_LAYER(map, k);
+        if (msWFSIsLayerSupported(lp) && lp->name &&
+            strcasecmp(lp->name, aFIDLayers[j]) == 0) {
+          lp->status = MS_ON;
+          if (lp->template == NULL) {
+            /* Force setting a template to enable query. */
+            lp->template = msStrdup("ttt.html");
+          }
+          psNode = FLTCreateFeatureIdFilterEncoding(aFIDValues[j]);
+          
+          if( FLTApplyFilterToLayer(psNode, map, lp->index) != MS_SUCCESS ) {
+            msSetError(MS_WFSERR, "FLTApplyFilterToLayer() failed", "msWFSGetFeature");
+            return msWFSException(map, "mapserv", "NoApplicableCode", paramsObj->pszVersion);
+          }
 
-                if( maxfeatures > 0 )
-                {
-                    if( lp->resultcache->numresults > to_allow )
-                    {
-                        lp->resultcache->numresults = to_allow;
-                        to_allow = 0;
-                    }
-                    else 
-                    {
-                        to_allow -= lp->resultcache->numresults;
-                        if( to_allow < 0 )
-                            to_allow = 0;
-
-                    }
-                }
-            }
+          FLTFreeFilterEncodingNode( psNode );
+          psNode = NULL;
+          break;
         }
-
-        status = msReturnTemplateQuery( mapserv, psFormat->name, NULL );
-
-        mapserv->request = NULL;
-        mapserv->map = NULL;
-
-        msFreeMapServObj( mapserv );
-
-        if( status != MS_SUCCESS )
-        {
-            return msWFSException(map, "mapserv", "NoApplicableCode",
-                                  paramsObj->pszVersion );
+      }
+      if (k == map->numlayers) { /*layer not found*/
+        msSetError(MS_WFSERR,
+                   "Invalid typename given with FeatureId in GetFeature : %s. A layer might be disabled for \
+this request. Check wfs/ows_enable_request settings.", "msWFSGetFeature()",
+                   aFIDLayers[j]);
+
+        if (aFIDLayers && aFIDValues) {
+          for (j=0; j<iFIDLayers; j++) {
+            msFree(aFIDLayers[j]);
+            msFree(aFIDValues[j]);
+          }
+          msFree(aFIDLayers);
+          msFree(aFIDValues);
         }
+        return msWFSException(map, "featureid", "InvalidParameterValue", paramsObj->pszVersion);
+      }
     }
 
-    if( psFormat == NULL && status == MS_SUCCESS )
-    {
-        msWFSGetFeature_GMLPostfix( map, req, &gmlinfo, paramsObj, 
-                                    outputformat, 
-                                    maxfeatures, iResultTypeHits, iNumberOfFeatures );
+    if (aFIDLayers && aFIDValues) {
+      for (j=0; j<iFIDLayers; j++) {
+        msFree(aFIDLayers[j]);
+        msFree(aFIDValues[j]);
+      }
+      msFree(aFIDLayers);
+      msFree(aFIDValues);
     }
+  }
+#endif /* USE_OGR */
 
-    /*
-    ** Done! Now a bit of clean-up.
-    */    
 
-    return status;
-}
+  if(layers)
+    msFreeCharArray(layers, numlayers);
 
+  /* Apply the requested SRS */
+  if (msWFSGetFeatureApplySRS(map, paramsObj->pszSrs, paramsObj->pszVersion) == MS_FAILURE)
+    return msWFSException(map, "typename", "InvalidParameterValue", paramsObj->pszVersion);
+  
+  /*
+  ** Perform Query (only BBOX for now)
+  */
+  /* __TODO__ Using a rectangle query may not be the most efficient way */
+  /* to do things here. */
+  if (!bFilterSet && !bFeatureIdSet) {
+
+    if (!bBBOXSet) {
+      const char *pszMapSRS=NULL, *pszLayerSRS=NULL;
+      bbox = map->extent;
+      map->query.type = MS_QUERY_BY_RECT; /* setup the query */
+      map->query.mode = MS_QUERY_MULTIPLE;
+
+      /*if srsName was given for wfs 1.1.0, It is at this point loaded into the
+        map object and should be used*/
+      if(!paramsObj->pszSrs)
+        pszMapSRS = msOWSGetEPSGProj(&(map->projection), &(map->web.metadata), "FO", MS_TRUE);
+      for(j=0; j<map->numlayers; j++) {
+        layerObj *lp;
+        rectObj ext;
+        int status;
+        lp = GET_LAYER(map, j);
+        if (lp->status == MS_ON) {
+          if (msOWSGetLayerExtent(map, lp, "FO", &ext) == MS_SUCCESS) {
 
-#endif /* USE_WFS_SVR */
+            if (pszMapSRS != NULL && strncmp(pszMapSRS, "EPSG:", 5) == 0) {
 
+              if( msOWSParseVersionString(paramsObj->pszVersion) >= OWS_1_1_0 )
+                status = msLoadProjectionStringEPSG(&(map->projection), pszMapSRS);
+              else
+                status = msLoadProjectionString(&(map->projection), pszMapSRS);
 
-/*
-** msWFSDispatch() is the entry point for WFS requests.
-** - If this is a valid request then it is processed and MS_SUCCESS is returned
-**   on success, or MS_FAILURE on failure.
-** - If this does not appear to be a valid WFS request then MS_DONE
-**   is returned and MapServer is expected to process this as a regular
+              if (status != 0) {
+                msSetError(MS_WFSERR, "msLoadProjectionString() failed: %s",
+                           "msWFSGetFeature()", pszMapSRS);
+                return msWFSException(map, "mapserv", "NoApplicableCode",
+                                      paramsObj->pszVersion);
+              }
+
+            }
+
+            /*make sure that the layer projectsion is loaded.
+              It could come from a ows/wfs_srs metadata*/
+            if (lp->projection.numargs == 0) {
+              pszLayerSRS = msOWSGetEPSGProj(&(lp->projection), &(lp->metadata), "FO", MS_TRUE);
+              if (pszLayerSRS) {
+                if (strncmp(pszLayerSRS, "EPSG:", 5) == 0) {
+                  if( msOWSParseVersionString(paramsObj->pszVersion) >= OWS_1_1_0 )
+                    msLoadProjectionStringEPSG(&(lp->projection), pszLayerSRS);
+                  else
+                    msLoadProjectionString(&(lp->projection), pszLayerSRS);
+                }
+              }
+            }
+
+            if (msProjectionsDiffer(&map->projection, &lp->projection) == MS_TRUE) {
+              msProjectRect(&lp->projection, &map->projection, &(ext));
+            }
+            bbox = ext;
+          }
+          map->query.rect = bbox;
+          map->query.layer = j;
+          if(msQueryByRect(map) != MS_SUCCESS) {
+            errorObj   *ms_error;
+            ms_error = msGetErrorObj();
+
+            if(ms_error->code != MS_NOTFOUND) {
+              msSetError(MS_WFSERR, "ms_error->code not found", "msWFSGetFeature()");
+              return msWFSException(map, "mapserv", "NoApplicableCode", paramsObj->pszVersion);
+            }
+          }
+        }
+      }
+    } else {
+      if (sBBoxSrs) {
+        int status;
+        projectionObj sProjTmp;
+
+        msInitProjection(&sProjTmp);
+        /*do the axis order for now. It is unclear if the bbox are expected
+          ro respect the axis oder defined in the projectsion #3296*/
+
+        if(strncmp(paramsObj->pszVersion,"1.1",3) == 0) {
+          if ((status=msLoadProjectionStringEPSG(&sProjTmp, sBBoxSrs)) == 0) {
+            msAxisNormalizePoints( &sProjTmp, 1, &bbox.minx, &bbox.miny );
+            msAxisNormalizePoints( &sProjTmp, 1, &bbox.maxx, &bbox.maxy );
+          }
+        } else
+          status = msLoadProjectionString(&sProjTmp, sBBoxSrs);
+
+        if (status == 0 &&  map->projection.numargs > 0)
+          msProjectRect(&sProjTmp, &map->projection, &bbox);
+
+        msFree(sBBoxSrs);
+      }
+      map->query.type = MS_QUERY_BY_RECT; /* setup the query */
+      map->query.mode = MS_QUERY_MULTIPLE;
+      map->query.rect = bbox;
+
+      if(msQueryByRect(map) != MS_SUCCESS) {
+        errorObj   *ms_error;
+        ms_error = msGetErrorObj();
+
+        if(ms_error->code != MS_NOTFOUND) {
+          msSetError(MS_WFSERR, "ms_error->code not found", "msWFSGetFeature()");
+          return msWFSException(map, "mapserv", "NoApplicableCode", paramsObj->pszVersion);
+        }
+      }
+    }
+  }
+
+  /* if no results where written (TODO: this needs to be GML2/3 specific I imagine */
+  for(j=0; j<map->numlayers; j++) {
+    if (GET_LAYER(map, j)->resultcache && GET_LAYER(map, j)->resultcache->numresults > 0) {
+      iNumberOfFeatures += GET_LAYER(map, j)->resultcache->numresults;
+    }
+  }
+
+  /*
+  ** GML Header generation.
+  */
+
+  status = MS_SUCCESS;
+
+  if( psFormat == NULL ) {
+    value = msOWSLookupMetadata(&(map->web.metadata), "FO", "encoding");
+    if (value)
+      msIO_setHeader("Content-Type","%s; charset=%s", output_mime_type,value);
+    else
+      msIO_setHeader("Content-Type",output_mime_type);
+    msIO_sendHeaders();
+
+    status = msWFSGetFeature_GMLPreamble( map, req, &gmlinfo, paramsObj,
+                                 outputformat,
+                                 iResultTypeHits,
+                                 iNumberOfFeatures );
+    if(status != MS_SUCCESS) {
+      return MS_FAILURE;
+    }
+  }
+
+  /* handle case of maxfeatures = 0 */
+  /*internally use a start index that start with 0 as the first index*/
+  if( psFormat == NULL ) {
+    if(maxfeatures != 0 && iResultTypeHits == 0)
+      status = msGMLWriteWFSQuery(map, stdout,
+                                  (char *) gmlinfo.user_namespace_prefix,
+                                  outputformat);
+  } else {
+    mapservObj *mapserv = msAllocMapServObj();
+
+    /* Setup dummy mapserv object */
+    mapserv->sendheaders = MS_TRUE;
+    mapserv->map = map;
+    msFreeCgiObj(mapserv->request);
+    mapserv->request = req;
+    map->querymap.status = MS_FALSE;
+
+    status = msReturnTemplateQuery( mapserv, psFormat->name, NULL );
+
+    mapserv->request = NULL;
+    mapserv->map = NULL;
+
+    msFreeMapServObj( mapserv );
+
+    if( status != MS_SUCCESS ) {
+      return msWFSException(map, "mapserv", "NoApplicableCode",
+                            paramsObj->pszVersion );
+    }
+  }
+
+  if( psFormat == NULL && status == MS_SUCCESS ) {
+    msWFSGetFeature_GMLPostfix( map, req, &gmlinfo, paramsObj,
+                                outputformat,
+                                maxfeatures, iResultTypeHits, iNumberOfFeatures );
+  }
+
+  /*
+  ** Done! Now a bit of clean-up.
+  */
+
+  return status;
+}
+
+
+#endif /* USE_WFS_SVR */
+
+
+/*
+** msWFSDispatch() is the entry point for WFS requests.
+** - If this is a valid request then it is processed and MS_SUCCESS is returned
+**   on success, or MS_FAILURE on failure.
+** - If this does not appear to be a valid WFS request then MS_DONE
+**   is returned and MapServer is expected to process this as a regular
 **   MapServer request.
 */
 int msWFSDispatch(mapObj *map, cgiRequestObj *requestobj, owsRequestObj *ows_request, int force_wfs_mode)
@@ -2699,215 +2481,198 @@ int msWFSDispatch(mapObj *map, cgiRequestObj *requestobj, owsRequestObj *ows_req
   if (msWFSParseRequest(map, requestobj, ows_request, paramsObj, force_wfs_mode) == MS_FAILURE)
     return msWFSException(map, "request", "InvalidRequest", NULL);
 
-  if (force_wfs_mode)
-  {
-      /*request is always required*/
-      if (paramsObj->pszRequest==NULL || strlen(paramsObj->pszRequest)<=0)
-      {
-          msSetError(MS_WFSERR, 
-                 "Incomplete WFS request: REQUEST parameter missing", 
-                     "msWFSDispatch()");
-          returnvalue = msWFSException(map, "request", "MissingParameterValue", paramsObj->pszVersion);
-          msWFSFreeParamsObj(paramsObj);
-          free(paramsObj);
-          paramsObj = NULL;
-          return returnvalue;
-      }
-      
-      /*version:
-        wfs 1.0 and 1.1.0 POST request: optional
-        wfs 1.0 and 1.1.0 GET request: optional for getcapabilities and required for describefeatute and getfeature
-       */
-      if (paramsObj->pszVersion == NULL && requestobj && requestobj->postrequest == MS_FALSE && 
-          strcasecmp(paramsObj->pszRequest, "GetCapabilities") != 0)
-      {
-          msSetError(MS_WFSERR, 
-                 "Invalid WFS request: VERSION parameter missing", 
+  if (force_wfs_mode) {
+    /*request is always required*/
+    if (paramsObj->pszRequest==NULL || strlen(paramsObj->pszRequest)<=0) {
+      msSetError(MS_WFSERR,
+                 "Incomplete WFS request: REQUEST parameter missing",
                  "msWFSDispatch()");
-          returnvalue = msWFSException(map, "version", "MissingParameterValue", paramsObj->pszVersion);
-          msWFSFreeParamsObj(paramsObj);
-          free(paramsObj);
-          paramsObj = NULL;
-          return returnvalue;
-      }
-
-      if (paramsObj->pszVersion == NULL || strlen(paramsObj->pszVersion) <=0)
-        paramsObj->pszVersion = msStrdup("1.1.0");
-
-      /*service 
-        wfs 1.0 and 1.1.0 GET: required and should be set to WFS
-        wfs 1.0 POST: required
-        wfs 1.1.1 POST: optional
-      */
-      if ((paramsObj->pszService == NULL || strlen(paramsObj->pszService) == 0) &&
-          ((requestobj && requestobj->postrequest == MS_FALSE) || strcasecmp(paramsObj->pszVersion,"1.0") ==0))
-      {
-            msSetError(MS_WFSERR, 
-                 "Invalid WFS request: Missing SERVICE parameter", 
-                 "msWFSDispatch()");
-          returnvalue = msWFSException(map, "service", "MissingParameterValue", paramsObj->pszVersion);
-          msWFSFreeParamsObj(paramsObj);
-          free(paramsObj);
-          paramsObj = NULL;
-          return returnvalue;
-      }
-
-      if (paramsObj->pszService == NULL || strlen(paramsObj->pszService) == 0)
-        paramsObj->pszService = msStrdup("WFS");
-
-      if (paramsObj->pszService!=NULL && strcasecmp(paramsObj->pszService, "WFS") != 0)
-      {
-          msSetError(MS_WFSERR, 
-                 "Invalid WFS request: SERVICE parameter must be set to WFS", 
-                 "msWFSDispatch()");
-          returnvalue = msWFSException(map, "service", "InvalidParameterValue", paramsObj->pszVersion);
-          msWFSFreeParamsObj(paramsObj);
-          free(paramsObj);
-          paramsObj = NULL;
-          return returnvalue;
-      }
-      if (paramsObj->pszService == NULL && strcasecmp(paramsObj->pszVersion, "1.0") == 0)
-      {
-          msSetError(MS_WFSERR, 
-                 "Invalid WFS request: SERVICE parameter missing", 
-                 "msWFSDispatch()");
-          returnvalue = msWFSException(map, "service", "MissingParameterValue", paramsObj->pszVersion);
-          msWFSFreeParamsObj(paramsObj);
-          free(paramsObj);
-          paramsObj = NULL;
-          return returnvalue;
-      }
-      
-  }
-  /* If SERVICE is specified then it MUST be "WFS" */
-  if (paramsObj->pszService != NULL && 
-      strcasecmp(paramsObj->pszService, "WFS") != 0)
-  {
+      returnvalue = msWFSException(map, "request", "MissingParameterValue", paramsObj->pszVersion);
       msWFSFreeParamsObj(paramsObj);
       free(paramsObj);
       paramsObj = NULL;
-      return MS_DONE;  /* Not a WFS request */
-  }
+      return returnvalue;
+    }
 
-  /* If SERVICE, VERSION and REQUEST not included than this isn't a WFS req*/
-  if (paramsObj->pszService == NULL && paramsObj->pszVersion==NULL && 
-      paramsObj->pszRequest==NULL)
-  {
+    /*version:
+      wfs 1.0 and 1.1.0 POST request: optional
+      wfs 1.0 and 1.1.0 GET request: optional for getcapabilities and required for describefeatute and getfeature
+     */
+    if (paramsObj->pszVersion == NULL && requestobj && requestobj->postrequest == MS_FALSE &&
+        strcasecmp(paramsObj->pszRequest, "GetCapabilities") != 0) {
+      msSetError(MS_WFSERR,
+                 "Invalid WFS request: VERSION parameter missing",
+                 "msWFSDispatch()");
+      returnvalue = msWFSException(map, "version", "MissingParameterValue", paramsObj->pszVersion);
       msWFSFreeParamsObj(paramsObj);
       free(paramsObj);
       paramsObj = NULL;
-      return MS_DONE;  /* Not a WFS request */
-  }
+      return returnvalue;
+    }
 
-  /* VERSION *and* REQUEST *and* SERVICE required by all WFS requests including 
-   * GetCapabilities.
-   */
-  if (paramsObj->pszVersion==NULL || strlen(paramsObj->pszVersion)<=0)
-  {
-      msSetError(MS_WFSERR, 
-                 "Incomplete WFS request: VERSION parameter missing", 
+    if (paramsObj->pszVersion == NULL || strlen(paramsObj->pszVersion) <=0)
+      paramsObj->pszVersion = msStrdup("1.1.0");
+
+    /*service
+      wfs 1.0 and 1.1.0 GET: required and should be set to WFS
+      wfs 1.0 POST: required
+      wfs 1.1.1 POST: optional
+    */
+    if ((paramsObj->pszService == NULL || strlen(paramsObj->pszService) == 0) &&
+        ((requestobj && requestobj->postrequest == MS_FALSE) || strcasecmp(paramsObj->pszVersion,"1.0") ==0)) {
+      msSetError(MS_WFSERR,
+                 "Invalid WFS request: Missing SERVICE parameter",
                  "msWFSDispatch()");
-       
-      returnvalue = msWFSException11(map, "version", "MissingParameterValue", "1.1.0");
+      returnvalue = msWFSException(map, "service", "MissingParameterValue", paramsObj->pszVersion);
       msWFSFreeParamsObj(paramsObj);
       free(paramsObj);
       paramsObj = NULL;
       return returnvalue;
-  }
-  
-  if (paramsObj->pszRequest==NULL || strlen(paramsObj->pszRequest)<=0)
-  {
-      msSetError(MS_WFSERR, 
-                 "Incomplete WFS request: REQUEST parameter missing", 
+    }
+
+    if (paramsObj->pszService == NULL || strlen(paramsObj->pszService) == 0)
+      paramsObj->pszService = msStrdup("WFS");
+
+    if (paramsObj->pszService!=NULL && strcasecmp(paramsObj->pszService, "WFS") != 0) {
+      msSetError(MS_WFSERR,
+                 "Invalid WFS request: SERVICE parameter must be set to WFS",
                  "msWFSDispatch()");
-      returnvalue = msWFSException(map, "request", "MissingParameterValue", paramsObj->pszVersion);
+      returnvalue = msWFSException(map, "service", "InvalidParameterValue", paramsObj->pszVersion);
       msWFSFreeParamsObj(paramsObj);
       free(paramsObj);
       paramsObj = NULL;
       return returnvalue;
-  }
-  
-  if (paramsObj->pszService==NULL || strlen(paramsObj->pszService)<=0)
-  {
-      msSetError(MS_WFSERR, 
-                 "Incomplete WFS request: SERVICE parameter missing", 
+    }
+    if (paramsObj->pszService == NULL && strcasecmp(paramsObj->pszVersion, "1.0") == 0) {
+      msSetError(MS_WFSERR,
+                 "Invalid WFS request: SERVICE parameter missing",
                  "msWFSDispatch()");
-       
       returnvalue = msWFSException(map, "service", "MissingParameterValue", paramsObj->pszVersion);
       msWFSFreeParamsObj(paramsObj);
       free(paramsObj);
       paramsObj = NULL;
       return returnvalue;
+    }
+
+  }
+  /* If SERVICE is specified then it MUST be "WFS" */
+  if (paramsObj->pszService != NULL &&
+      strcasecmp(paramsObj->pszService, "WFS") != 0) {
+    msWFSFreeParamsObj(paramsObj);
+    free(paramsObj);
+    paramsObj = NULL;
+    return MS_DONE;  /* Not a WFS request */
   }
 
-  if ((status = msOWSMakeAllLayersUnique(map)) != MS_SUCCESS)
-  {
-      msSetError(MS_WFSERR, "msOWSMakeAllLayersUnique() failed", "msWFSDispatch()");
-      returnvalue = msWFSException(map, "mapserv", "NoApplicableCode", paramsObj->pszVersion);
-      msWFSFreeParamsObj(paramsObj);
-      free(paramsObj);
-      paramsObj = NULL;
-      return returnvalue;
+  /* If SERVICE, VERSION and REQUEST not included than this isn't a WFS req*/
+  if (paramsObj->pszService == NULL && paramsObj->pszVersion==NULL &&
+      paramsObj->pszRequest==NULL) {
+    msWFSFreeParamsObj(paramsObj);
+    free(paramsObj);
+    paramsObj = NULL;
+    return MS_DONE;  /* Not a WFS request */
+  }
+
+  /* VERSION *and* REQUEST *and* SERVICE required by all WFS requests including
+   * GetCapabilities.
+   */
+  if (paramsObj->pszVersion==NULL || strlen(paramsObj->pszVersion)<=0) {
+    msSetError(MS_WFSERR,
+               "Incomplete WFS request: VERSION parameter missing",
+               "msWFSDispatch()");
+
+    returnvalue = msWFSException11(map, "version", "MissingParameterValue", "1.1.0");
+    msWFSFreeParamsObj(paramsObj);
+    free(paramsObj);
+    paramsObj = NULL;
+    return returnvalue;
+  }
+
+  if (paramsObj->pszRequest==NULL || strlen(paramsObj->pszRequest)<=0) {
+    msSetError(MS_WFSERR,
+               "Incomplete WFS request: REQUEST parameter missing",
+               "msWFSDispatch()");
+    returnvalue = msWFSException(map, "request", "MissingParameterValue", paramsObj->pszVersion);
+    msWFSFreeParamsObj(paramsObj);
+    free(paramsObj);
+    paramsObj = NULL;
+    return returnvalue;
+  }
+
+  if (paramsObj->pszService==NULL || strlen(paramsObj->pszService)<=0) {
+    msSetError(MS_WFSERR,
+               "Incomplete WFS request: SERVICE parameter missing",
+               "msWFSDispatch()");
+
+    returnvalue = msWFSException(map, "service", "MissingParameterValue", paramsObj->pszVersion);
+    msWFSFreeParamsObj(paramsObj);
+    free(paramsObj);
+    paramsObj = NULL;
+    return returnvalue;
+  }
+
+  if ((status = msOWSMakeAllLayersUnique(map)) != MS_SUCCESS) {
+    msSetError(MS_WFSERR, "msOWSMakeAllLayersUnique() failed", "msWFSDispatch()");
+    returnvalue = msWFSException(map, "mapserv", "NoApplicableCode", paramsObj->pszVersion);
+    msWFSFreeParamsObj(paramsObj);
+    free(paramsObj);
+    paramsObj = NULL;
+    return returnvalue;
   }
   /*
   ** Start dispatching requests
   */
-  if (strcasecmp(paramsObj->pszRequest, "GetCapabilities") == 0 ) 
-  {
-      msOWSRequestLayersEnabled(map, "F", paramsObj->pszRequest, ows_request);
-      if (ows_request->numlayers == 0)
-      {
-          msSetError(MS_WFSERR, "WFS request not enabled. Check wfs/ows_enable_request settings.", "msWFSDispatch()");
-          returnvalue = msWFSException(map, "request", "InvalidParameterValue", paramsObj->pszVersion);
-          msWFSFreeParamsObj(paramsObj);
-          free(paramsObj);
-          paramsObj = NULL;
-          return returnvalue;
-      }
-
-      returnvalue = msWFSGetCapabilities(map, paramsObj, requestobj, ows_request);
+  if (strcasecmp(paramsObj->pszRequest, "GetCapabilities") == 0 ) {
+    msOWSRequestLayersEnabled(map, "F", paramsObj->pszRequest, ows_request);
+    if (ows_request->numlayers == 0) {
+      msSetError(MS_WFSERR, "WFS request not enabled. Check wfs/ows_enable_request settings.", "msWFSDispatch()");
+      returnvalue = msWFSException(map, "request", "InvalidParameterValue", paramsObj->pszVersion);
       msWFSFreeParamsObj(paramsObj);
       free(paramsObj);
       paramsObj = NULL;
       return returnvalue;
+    }
+
+    returnvalue = msWFSGetCapabilities(map, paramsObj, requestobj, ows_request);
+    msWFSFreeParamsObj(paramsObj);
+    free(paramsObj);
+    paramsObj = NULL;
+    return returnvalue;
   }
 
   /*
   ** Validate VERSION against the versions that we support... we don't do this
   ** for GetCapabilities in order to allow version negociation.
   */
-  if (strcmp(paramsObj->pszVersion, "1.0.0") != 0 && 
-      strcmp(paramsObj->pszVersion, "1.1.0") != 0)
-  {
-      msSetError(MS_WFSERR, 
-                 "WFS Server does not support VERSION %s.", 
-                 "msWFSDispatch()", paramsObj->pszVersion);
-      returnvalue = msWFSException11(map, "version", "InvalidParameterValue","1.1.0");
+  if (strcmp(paramsObj->pszVersion, "1.0.0") != 0 &&
+      strcmp(paramsObj->pszVersion, "1.1.0") != 0) {
+    msSetError(MS_WFSERR,
+               "WFS Server does not support VERSION %s.",
+               "msWFSDispatch()", paramsObj->pszVersion);
+    returnvalue = msWFSException11(map, "version", "InvalidParameterValue","1.1.0");
+    msWFSFreeParamsObj(paramsObj);
+    free(paramsObj);
+    paramsObj = NULL;
+    return returnvalue;
+
+  }
+
+  /* Since the function can still return MS_DONE, we add an extra service check to not call
+     msOWSRequestLayersEnabled twice */
+  if (strcasecmp(paramsObj->pszService, "WFS") == 0) {
+    msOWSRequestLayersEnabled(map, "F", paramsObj->pszRequest, ows_request);
+    if (ows_request->numlayers == 0) {
+      msSetError(MS_WFSERR, "WFS request not enabled. Check wfs/ows_enable_request settings.", "msWFSDispatch()");
+      returnvalue = msWFSException(map, "request", "InvalidParameterValue", paramsObj->pszVersion);
       msWFSFreeParamsObj(paramsObj);
       free(paramsObj);
       paramsObj = NULL;
       return returnvalue;
-                                                                 
-  }
-
-  /* Since the function can still return MS_DONE, we add an extra service check to not call 
-     msOWSRequestLayersEnabled twice */
-  if (strcasecmp(paramsObj->pszService, "WFS") == 0) 
-  {
-      msOWSRequestLayersEnabled(map, "F", paramsObj->pszRequest, ows_request);
-      if (ows_request->numlayers == 0)
-      {
-          msSetError(MS_WFSERR, "WFS request not enabled. Check wfs/ows_enable_request settings.", "msWFSDispatch()");
-          returnvalue = msWFSException(map, "request", "InvalidParameterValue", paramsObj->pszVersion);
-          msWFSFreeParamsObj(paramsObj);
-          free(paramsObj);
-          paramsObj = NULL;
-          return returnvalue;
-      }
+    }
   }
 
   returnvalue = MS_DONE;
-  /* Continue dispatching... 
+  /* Continue dispatching...
    */
   if (strcasecmp(paramsObj->pszRequest, "DescribeFeatureType") == 0)
     returnvalue = msWFSDescribeFeatureType(map, paramsObj, ows_request);
@@ -2918,19 +2683,16 @@ int msWFSDispatch(mapObj *map, cgiRequestObj *requestobj, owsRequestObj *ows_req
 
   else if (strcasecmp(paramsObj->pszRequest, "GetFeatureWithLock") == 0 ||
            strcasecmp(paramsObj->pszRequest, "LockFeature") == 0 ||
-           strcasecmp(paramsObj->pszRequest, "Transaction") == 0 )
-  {
-      /* Unsupported WFS request */
-      msSetError(MS_WFSERR, "Unsupported WFS request: %s", "msWFSDispatch()",
-                 paramsObj->pszRequest);
-      returnvalue = msWFSException(map, "request", "InvalidParameterValue", paramsObj->pszVersion);
-  }
-  else if (strcasecmp(paramsObj->pszService, "WFS") == 0)
-  {
-      /* Invalid WFS request */
-      msSetError(MS_WFSERR, "Invalid WFS request: %s", "msWFSDispatch()",
-                 paramsObj->pszRequest);
-      returnvalue = msWFSException(map, "request", "InvalidParameterValue", paramsObj->pszVersion);
+           strcasecmp(paramsObj->pszRequest, "Transaction") == 0 ) {
+    /* Unsupported WFS request */
+    msSetError(MS_WFSERR, "Unsupported WFS request: %s", "msWFSDispatch()",
+               paramsObj->pszRequest);
+    returnvalue = msWFSException(map, "request", "InvalidParameterValue", paramsObj->pszVersion);
+  } else if (strcasecmp(paramsObj->pszService, "WFS") == 0) {
+    /* Invalid WFS request */
+    msSetError(MS_WFSERR, "Invalid WFS request: %s", "msWFSDispatch()",
+               paramsObj->pszRequest);
+    returnvalue = msWFSException(map, "request", "InvalidParameterValue", paramsObj->pszVersion);
   }
 
   /* This was not detected as a WFS request... let MapServer handle it */
@@ -2940,7 +2702,7 @@ int msWFSDispatch(mapObj *map, cgiRequestObj *requestobj, owsRequestObj *ows_req
   return returnvalue;
 
 #else
-  msSetError(MS_WFSERR, "WFS server support is not available.", 
+  msSetError(MS_WFSERR, "WFS server support is not available.",
              "msWFSDispatch()");
   return(MS_FAILURE);
 #endif
@@ -2954,13 +2716,13 @@ int msWFSDispatch(mapObj *map, cgiRequestObj *requestobj, owsRequestObj *ows_req
 /************************************************************************/
 wfsParamsObj *msWFSCreateParamsObj()
 {
-    wfsParamsObj *paramsObj = (wfsParamsObj *)calloc(1, sizeof(wfsParamsObj));
-    MS_CHECK_ALLOC(paramsObj, sizeof(wfsParamsObj), NULL);
+  wfsParamsObj *paramsObj = (wfsParamsObj *)calloc(1, sizeof(wfsParamsObj));
+  MS_CHECK_ALLOC(paramsObj, sizeof(wfsParamsObj), NULL);
 
-    paramsObj->nMaxFeatures = -1;
-    paramsObj->nStartIndex = -1;
+  paramsObj->nMaxFeatures = -1;
+  paramsObj->nStartIndex = -1;
 
-    return paramsObj;
+  return paramsObj;
 }
 
 
@@ -2972,22 +2734,22 @@ wfsParamsObj *msWFSCreateParamsObj()
 /************************************************************************/
 void msWFSFreeParamsObj(wfsParamsObj *wfsparams)
 {
-    if (wfsparams)
-    {
-        free(wfsparams->pszVersion);
-        free(wfsparams->pszUpdateSequence);
-        free(wfsparams->pszRequest);
-        free(wfsparams->pszService);
-        free(wfsparams->pszTypeName);
-        free(wfsparams->pszFilter);
-        free(wfsparams->pszBbox);
-        free(wfsparams->pszOutputFormat);
-        free(wfsparams->pszFeatureId);
-        free(wfsparams->pszSrs);
-        free(wfsparams->pszResultType);
-        free(wfsparams->pszPropertyName);
-        free(wfsparams->pszAcceptVersions);
-    }
+  if (wfsparams) {
+    free(wfsparams->pszVersion);
+    free(wfsparams->pszUpdateSequence);
+    free(wfsparams->pszRequest);
+    free(wfsparams->pszService);
+    free(wfsparams->pszTypeName);
+    free(wfsparams->pszFilter);
+    free(wfsparams->pszBbox);
+    free(wfsparams->pszGeometryName);
+    free(wfsparams->pszOutputFormat);
+    free(wfsparams->pszFeatureId);
+    free(wfsparams->pszSrs);
+    free(wfsparams->pszResultType);
+    free(wfsparams->pszPropertyName);
+    free(wfsparams->pszAcceptVersions);
+  }
 }
 
 const char *msWFSGetDefaultVersion(mapObj *map)
@@ -3006,658 +2768,595 @@ int msWFSParseRequest(mapObj *map, cgiRequestObj *request, owsRequestObj *ows_re
                       wfsParamsObj *wfsparams, int force_wfs_mode)
 {
 #ifdef USE_WFS_SVR
-    int i = 0;
-        
-    if (!request || !wfsparams)
-      return MS_FAILURE;
-    
-    if (request->NumParams > 0)
-    {
-        for(i=0; i<request->NumParams; i++) 
-        {
-            if (request->ParamNames[i] && request->ParamValues[i])
-            {
-                if (strcasecmp(request->ParamNames[i], "VERSION") == 0)
-                  wfsparams->pszVersion = msStrdup(request->ParamValues[i]);
-
-                else if (strcasecmp(request->ParamNames[i], "UPDATESEQUENCE") == 0)
-                  wfsparams->pszUpdateSequence = msStrdup(request->ParamValues[i]);
-
-                else if (strcasecmp(request->ParamNames[i], "REQUEST") == 0)
-                  wfsparams->pszRequest = msStrdup(request->ParamValues[i]);
-                
-                else if (strcasecmp(request->ParamNames[i], "SERVICE") == 0)
-                  wfsparams->pszService = msStrdup(request->ParamValues[i]);
-             
-                else if (strcasecmp(request->ParamNames[i], "MAXFEATURES") == 0)
-                  wfsparams->nMaxFeatures = atoi(request->ParamValues[i]);
-
-                else if (strcasecmp(request->ParamNames[i], "STARTINDEX") == 0)
-                  wfsparams->nStartIndex = atoi(request->ParamValues[i]);
-                
-                else if (strcasecmp(request->ParamNames[i], "BBOX") == 0)
-                  wfsparams->pszBbox = msStrdup(request->ParamValues[i]);
-                
-                else if (strcasecmp(request->ParamNames[i], "SRSNAME") == 0)
-                  wfsparams->pszSrs = msStrdup(request->ParamValues[i]);
-
-                else if (strcasecmp(request->ParamNames[i], "RESULTTYPE") == 0)
-                  wfsparams->pszResultType = msStrdup(request->ParamValues[i]);
-
-                else if (strcasecmp(request->ParamNames[i], "TYPENAME") == 0)
-                  wfsparams->pszTypeName = msStrdup(request->ParamValues[i]);
-                
-                else if (strcasecmp(request->ParamNames[i], "FILTER") == 0)
-                  wfsparams->pszFilter = msStrdup(request->ParamValues[i]);
-                
-                else if (strcasecmp(request->ParamNames[i], "OUTPUTFORMAT") == 0)
-                  wfsparams->pszOutputFormat = msStrdup(request->ParamValues[i]);
-
-                else if (strcasecmp(request->ParamNames[i], "FEATUREID") == 0)
-                  wfsparams->pszFeatureId = msStrdup(request->ParamValues[i]);
-                
-                else if (strcasecmp(request->ParamNames[i], "PROPERTYNAME") == 0)
-                  wfsparams->pszPropertyName = msStrdup(request->ParamValues[i]);
-                
-                else if (strcasecmp(request->ParamNames[i], "ACCEPTVERSIONS") == 0)
-                  wfsparams->pszAcceptVersions = msStrdup(request->ParamValues[i]);
-
-                
-            }
-        }
-        /* version is optional is the GetCapabilities. If not */
-        /* provided, set it. Default it to 1.1.0*/
-        if (wfsparams->pszVersion == NULL &&
-            wfsparams->pszRequest && 
-            strcasecmp(wfsparams->pszRequest, "GetCapabilities") == 0)
-        {
-          wfsparams->pszVersion = msStrdup(msWFSGetDefaultVersion(map));
-        }
+  int i = 0;
+
+  if (!request || !wfsparams)
+    return MS_FAILURE;
+
+  if (request->NumParams > 0) {
+    for(i=0; i<request->NumParams; i++) {
+      if (request->ParamNames[i] && request->ParamValues[i]) {
+        if (strcasecmp(request->ParamNames[i], "VERSION") == 0)
+          wfsparams->pszVersion = msStrdup(request->ParamValues[i]);
+
+        else if (strcasecmp(request->ParamNames[i], "UPDATESEQUENCE") == 0)
+          wfsparams->pszUpdateSequence = msStrdup(request->ParamValues[i]);
+
+        else if (strcasecmp(request->ParamNames[i], "REQUEST") == 0)
+          wfsparams->pszRequest = msStrdup(request->ParamValues[i]);
+
+        else if (strcasecmp(request->ParamNames[i], "SERVICE") == 0)
+          wfsparams->pszService = msStrdup(request->ParamValues[i]);
+
+        else if (strcasecmp(request->ParamNames[i], "MAXFEATURES") == 0)
+          wfsparams->nMaxFeatures = atoi(request->ParamValues[i]);
+
+        else if (strcasecmp(request->ParamNames[i], "STARTINDEX") == 0)
+          wfsparams->nStartIndex = atoi(request->ParamValues[i]);
+
+        else if (strcasecmp(request->ParamNames[i], "BBOX") == 0)
+          wfsparams->pszBbox = msStrdup(request->ParamValues[i]);
+
+        else if (strcasecmp(request->ParamNames[i], "SRSNAME") == 0)
+          wfsparams->pszSrs = msStrdup(request->ParamValues[i]);
+
+        else if (strcasecmp(request->ParamNames[i], "RESULTTYPE") == 0)
+          wfsparams->pszResultType = msStrdup(request->ParamValues[i]);
+
+        else if (strcasecmp(request->ParamNames[i], "TYPENAME") == 0)
+          wfsparams->pszTypeName = msStrdup(request->ParamValues[i]);
+
+        else if (strcasecmp(request->ParamNames[i], "FILTER") == 0)
+          wfsparams->pszFilter = msStrdup(request->ParamValues[i]);
+
+        else if (strcasecmp(request->ParamNames[i], "OUTPUTFORMAT") == 0)
+          wfsparams->pszOutputFormat = msStrdup(request->ParamValues[i]);
+
+        else if (strcasecmp(request->ParamNames[i], "FEATUREID") == 0)
+          wfsparams->pszFeatureId = msStrdup(request->ParamValues[i]);
+
+        else if (strcasecmp(request->ParamNames[i], "PROPERTYNAME") == 0)
+          wfsparams->pszPropertyName = msStrdup(request->ParamValues[i]);
+
+        else if (strcasecmp(request->ParamNames[i], "ACCEPTVERSIONS") == 0)
+          wfsparams->pszAcceptVersions = msStrdup(request->ParamValues[i]);
+
+
+      }
     }
+    /* version is optional is the GetCapabilities. If not */
+    /* provided, set it. Default it to 1.1.0*/
+    if (wfsparams->pszVersion == NULL &&
+        wfsparams->pszRequest &&
+        strcasecmp(wfsparams->pszRequest, "GetCapabilities") == 0) {
+      wfsparams->pszVersion = msStrdup(msWFSGetDefaultVersion(map));
+    }
+  }
 
-/* -------------------------------------------------------------------- */
-/*      Parse the post request. It is assumed to be an XML document.    */
-/* -------------------------------------------------------------------- */
+  /* -------------------------------------------------------------------- */
+  /*      Parse the post request. It is assumed to be an XML document.    */
+  /* -------------------------------------------------------------------- */
 #ifdef USE_OGR
-    if (request->postrequest)
-    {
+  if (request->postrequest) {
 #ifdef WFS_USE_LIBXML2
-        xmlDocPtr doc;
-        xmlNodePtr rootnode, node, node1;
-        char *schema_file =NULL;
-        const char *schema_location=NULL, *validate=NULL;
-        const char *pszValue=NULL;
-        char *pszTmp=NULL;
-        char *pszLayerPropertyName=NULL, *pszLayerFilter=NULL;
-
-        //xmlXPathAxisFunc
-        /* load document */
-        doc = xmlParseDoc((xmlChar *)request->postrequest);
-        if (doc == NULL || (rootnode = xmlDocGetRootElement(doc)) == NULL) 
-        {
-            msSetError(MS_WFSERR, "Invalid POST request.  XML is not well-formed", "msWFSParseRequest()");
+    xmlDocPtr doc;
+    xmlNodePtr rootnode, node, node1;
+    char *schema_file =NULL;
+    const char *schema_location=NULL, *validate=NULL;
+    const char *pszValue=NULL;
+    char *pszTmp=NULL;
+    char *pszLayerPropertyName=NULL, *pszLayerFilter=NULL;
+
+    /* xmlXPathAxisFunc */
+    /* load document */
+    doc = xmlParseDoc((xmlChar *)request->postrequest);
+    if (doc == NULL || (rootnode = xmlDocGetRootElement(doc)) == NULL) {
+      msSetError(MS_WFSERR, "Invalid POST request.  XML is not well-formed", "msWFSParseRequest()");
+      return MS_FAILURE;
+    }
+
+    /*get the request*/
+    if (strcasecmp(rootnode->name, "GetCapabilities") == 0)
+      wfsparams->pszRequest = "GetCapabilities";
+    else if (strcasecmp(rootnode->name, "GetFeature") == 0)
+      wfsparams->pszRequest = "GetFeature";
+    else if (strcasecmp(rootnode->name, "DescribeFeatureType") == 0)
+      wfsparams->pszRequest = "DescribeFeatureType";
+
+    msOWSRequestLayersEnabled(map, "F", wfsparams->pszRequest, ows_request);
+    if (wfsparams->pszRequest == NULL) {
+      /* Unsupported WFS request */
+      msSetError(MS_WFSERR, "Unsupported WFS request.", "msWFSParseRequest()");
+      return MS_FAILURE;
+    }
+
+    if (ows_request->numlayers == 0) {
+      /* not enabled WFS request */
+      msSetError(MS_WFSERR, "WFS request not enabled. Check wfs/ows_enable_request settings.", "msWFSParseRequest()");
+      return MS_FAILURE;
+    }
+
+    /*get version and service if available*/
+    pszValue = xmlGetProp(rootnode, (xmlChar *)"version");
+    if (pszValue)
+      wfsparams->pszVersion = msStrdup(pszValue);
+    pszValue = xmlGetProp(rootnode, (xmlChar *)"service");
+    if (pszValue)
+      wfsparams->pszService = msStrdup(pszValue);
+
+
+    /* version is optional for the GetCapabilities. If not provided, set it*/
+    if (wfsparams->pszVersion == NULL &&
+        strcmp(wfsparams->pszRequest,"GetCapabilities") == 0) {
+      wfsparams->pszVersion = msStrdup(msWFSGetDefaultVersion(map));
+    }
+
+
+    /*do we validate the xml ?*/
+    validate = msOWSLookupMetadata(&(map->web.metadata), "FO", "validate_xml");
+    if (validate && strcasecmp(validate, "true") == 0 &&
+        (schema_location = msOWSLookupMetadata(&(map->web.metadata), "FO", "schemas_dir"))) {
+      if ((wfsparams->pszService  && strcmp(wfsparams->pszService, "WFS") == 0) ||
+          force_wfs_mode) {
+        schema_file = msStringConcatenate(schema_file, schema_location);
+        if (wfsparams->pszVersion == NULL ||
+            strncasecmp(wfsparams->pszVersion, "1.1", 3) ==0) {
+          schema_file = msStringConcatenate(schema_file,  "wfs/1.1.0/wfs.xsd");
+          if (msOWSSchemaValidation(schema_file, request->postrequest) != 0) {
+            msSetError(MS_WFSERR, "Invalid POST request.  XML is not valid", "msWFSParseRequest()");
             return MS_FAILURE;
+          }
         }
-        
-        /*get the request*/
-        if (strcasecmp(rootnode->name, "GetCapabilities") == 0)
-          wfsparams->pszRequest = "GetCapabilities";
-        else if (strcasecmp(rootnode->name, "GetFeature") == 0)
-          wfsparams->pszRequest = "GetFeature";
-        else if (strcasecmp(rootnode->name, "DescribeFeatureType") == 0)
-          wfsparams->pszRequest = "DescribeFeatureType";
-
-        msOWSRequestLayersEnabled(map, "F", wfsparams->pszRequest, ows_request);
-        if (wfsparams->pszRequest == NULL)
-        {
-          /* Unsupported WFS request */
-            msSetError(MS_WFSERR, "Unsupported WFS request.", "msWFSParseRequest()");
-            return MS_FAILURE;
+      }
+    }
+
+    /*parse describefeature*/
+    if (strcmp(wfsparams->pszRequest,"DescribeFeatureType") == 0) {
+      /*look for TypeName and outputFormat*/
+      for (node = rootnode->children; node; node = node->next) {
+        if (node->type != XML_ELEMENT_NODE)
+          continue;
+
+        if (strcmp(node->name, "TypeName") == 0) {
+          pszValue = xmlNodeGetContent(node);
+          if (wfsparams->pszTypeName == NULL)
+            wfsparams->pszTypeName = msStrdup(pszValue);
+          else {
+            wfsparams->pszTypeName =
+              msStringConcatenate(wfsparams->pszTypeName, ",");
+            wfsparams->pszTypeName =
+              msStringConcatenate(wfsparams->pszTypeName, pszValue);
+          }
         }
+      }
+      pszValue = xmlGetProp(rootnode, (xmlChar *)"outputFormat");
+      if (pszValue)
+        wfsparams->pszOutputFormat = msStrdup(pszValue);
+    }
 
-        if (ows_request->numlayers == 0)
-        {
-            /* not enabled WFS request */
-            msSetError(MS_WFSERR, "WFS request not enabled. Check wfs/ows_enable_request settings.", "msWFSParseRequest()");
-            return MS_FAILURE;
+    /*parse GetFeature*/
+    if (strcmp(wfsparams->pszRequest,"GetFeature") == 0) {
+      pszValue = xmlGetProp(rootnode, (xmlChar *)"resultType");
+      if (pszValue)
+        wfsparams->pszResultType = msStrdup(pszValue);
+
+      pszValue = xmlGetProp(rootnode, (xmlChar *)"maxFeatures");
+      if (pszValue)
+        wfsparams->nMaxFeatures = atoi(pszValue);
+
+      pszValue = xmlGetProp(rootnode, (xmlChar *)"startIndex");
+      if (pszValue)
+        wfsparams->nStartIndex = atoi(pszValue);
+
+      pszValue = xmlGetProp(rootnode, (xmlChar *)"outputFormat");
+      if (pszValue)
+        wfsparams->pszOutputFormat = msStrdup(pszValue);
+
+      /* free typename and filter. There may have been */
+      /* values if they were passed in the URL */
+      if (wfsparams->pszTypeName)
+        free(wfsparams->pszTypeName);
+      wfsparams->pszTypeName = NULL;
+
+      if (wfsparams->pszFilter)
+        free(wfsparams->pszFilter);
+      wfsparams->pszFilter = NULL;
+
+      for (node = rootnode->children; node; node = node->next) {
+        if (node->type != XML_ELEMENT_NODE)
+          continue;
+
+        if (strcmp(node->name, "Query") == 0) {
+          /* get SRS: TODO support srs per layer. Now we only have one srs
+           that applies to al layers*/
+          pszValue = xmlGetProp(node, (xmlChar *)"srsName");
+          if (pszValue) {
+            if (wfsparams->pszSrs )
+              msFree( wfsparams->pszSrs);
+            wfsparams->pszSrs = msStrdup(pszValue);
+          }
+          /*type name*/
+          pszValue = xmlGetProp(node, (xmlChar *)"typeName");
+          if (pszValue) {
+            if (wfsparams->pszTypeName == NULL)
+              wfsparams->pszTypeName = msStrdup(pszValue);
+            else {
+              wfsparams->pszTypeName =
+                msStringConcatenate(wfsparams->pszTypeName, ",");
+              wfsparams->pszTypeName =
+                msStringConcatenate(wfsparams->pszTypeName, pszValue);
+            }
+          }
+          /*PropertyName and Filter*/
+          pszLayerPropertyName = NULL;
+          pszLayerFilter = NULL;
+          for (node1 = node->children; node1; node1 = node1->next) {
+            if (node1->type != XML_ELEMENT_NODE)
+              continue;
+
+            if (strcmp(node1->name, "PropertyName") == 0) {
+              pszValue = xmlNodeGetContent(node1);
+              if (pszLayerPropertyName == NULL)
+                pszLayerPropertyName = msStrdup(pszValue);
+              else {
+                pszLayerPropertyName=
+                  msStringConcatenate(pszLayerPropertyName, ",");
+                pszLayerPropertyName =
+                  msStringConcatenate(pszLayerPropertyName, pszValue);
+              }
+            }
+            if (strcmp(node1->name, "Filter") == 0) {
+
+              pszValue = xmlNodeGetContent(node1);
+              if (pszValue) {
+                xmlBufferPtr buffer;
+
+                pszTmp = NULL;
+                buffer = xmlBufferCreate();
+                xmlNodeDump(buffer, node1->doc, node1, 0, 0);
+
+                pszTmp = msStringConcatenate(pszTmp, "(");
+                pszTmp = msStringConcatenate(pszTmp, buffer->content);
+                pszTmp = msStringConcatenate(pszTmp, ")");
+
+                xmlBufferFree(buffer);
+                wfsparams->pszFilter =
+                  msStringConcatenate(wfsparams->pszFilter,pszTmp);
+                msFree(pszTmp);
+              }
+            }
+          }
+          pszTmp = NULL;
+          if (pszLayerPropertyName == NULL)
+            pszTmp = msStrdup("(!)");
+          else {
+            pszTmp = msStringConcatenate(pszTmp, "(");
+            pszTmp = msStringConcatenate(pszTmp, pszLayerPropertyName);
+            pszTmp = msStringConcatenate(pszTmp, ")");
+            msFree(pszLayerPropertyName);
+          }
+          wfsparams->pszPropertyName = msStringConcatenate(wfsparams->pszPropertyName, pszTmp);
+          msFree(pszTmp);
+
+        }/*Query node*/
+      }
+
+    }
+
+
+    /* check for request */
+    /* only works??? if <wfs:getCapbilites ...>
+    psXPathTmp = msLibXml2GetXPath(doc, context, (xmlChar *)"/wfs:GetCapabilities|/GetCapabilities");
+    psXPathTmp = msLibXml2GetXPath(doc, context, (xmlChar *)"/GetCapabilities");
+    psXPathTmp = msLibXml2GetXPath(doc, context, (xmlChar *)"/wfs:GetCapabilities");
+    psXPathTmp = msLibXml2GetXPath(doc, context, (xmlChar *)"GetCapabilities");
+    psXPathTmp = msLibXml2GetXPath(doc, context, (xmlChar *)"//GetCapabilities");
+    */
+#else /*#ifdef WFS_USE_LIBXML2*/
+    CPLXMLNode *psRoot, *psQuery, *psFilter, *psTypeName,  *psPropertyName  = NULL;
+    CPLXMLNode *psGetFeature = NULL;
+    CPLXMLNode  *psGetCapabilities = NULL;
+    CPLXMLNode *psDescribeFeature = NULL;
+    CPLXMLNode *psOperation = NULL;
+    const char *pszValue;
+    char *pszSerializedFilter, *pszTmp, *pszTmp2 = NULL;
+    int bMultiLayer = 0;
+
+    psRoot = CPLParseXMLString(request->postrequest);
+    if(map->debug == MS_DEBUGLEVEL_VVV) {
+      msDebug("msWFSParseRequest(): WFS post request: %s\n", request->postrequest);
+    }
+    if (psRoot) {
+      /* need to strip namespaces */
+      CPLStripXMLNamespace(psRoot, NULL, 1);
+      for( psOperation = psRoot;
+           psOperation != NULL;
+           psOperation = psOperation->psNext ) {
+        if(psOperation->eType == CXT_Element) {
+          if(strcasecmp(psOperation->pszValue,"GetFeature")==0) {
+            psGetFeature = psOperation;
+            break;
+          } else if(strcasecmp(psOperation->pszValue,"GetCapabilities")==0) {
+            psGetCapabilities = psOperation;
+            pszValue = CPLGetXMLValue(psGetFeature,  "updateSequence", NULL);
+
+            if (pszValue)
+              wfsparams->pszUpdateSequence = msStrdup(pszValue);
+
+            break;
+          } else if(strcasecmp(psOperation->pszValue,
+                               "DescribeFeatureType")==0) {
+            psDescribeFeature = psOperation;
+            break;
+          }
+          /* these are unsupported requests. Just set the  */
+          /* request value and return; */
+          else if (strcasecmp(psOperation->pszValue,
+                              "GetFeatureWithLock") == 0) {
+            wfsparams->pszRequest = msStrdup("GetFeatureWithLock");
+            break;
+          } else if (strcasecmp(psOperation->pszValue,
+                                "LockFeature") == 0) {
+            wfsparams->pszRequest = msStrdup("LockFeature");
+            break;
+          } else if (strcasecmp(psOperation->pszValue,
+                                "Transaction") == 0) {
+            wfsparams->pszRequest = msStrdup("Transaction");
+            break;
+          }
         }
+      }
 
-        /*get version and service if available*/
-        pszValue = xmlGetProp(rootnode, (xmlChar *)"version");
+      /* -------------------------------------------------------------------- */
+      /*      Parse the GetFeature                                            */
+      /* -------------------------------------------------------------------- */
+      if (psGetFeature) {
+        wfsparams->pszRequest = msStrdup("GetFeature");
+
+        pszValue = CPLGetXMLValue(psGetFeature,  "version",
+                                  NULL);
         if (pszValue)
           wfsparams->pszVersion = msStrdup(pszValue);
-        pszValue = xmlGetProp(rootnode, (xmlChar *)"service");
+
+        pszValue = CPLGetXMLValue(psGetFeature,  "service",
+                                  NULL);
         if (pszValue)
-          wfsparams->pszService = msStrdup(pszValue);     
-
-        
-        /* version is optional for the GetCapabilities. If not provided, set it*/
-        if (wfsparams->pszVersion == NULL && 
-            strcmp(wfsparams->pszRequest,"GetCapabilities") == 0)
-        {
-           wfsparams->pszVersion = msStrdup(msWFSGetDefaultVersion(map));
-        }
+          wfsparams->pszService = msStrdup(pszValue);
 
+        pszValue = CPLGetXMLValue(psGetFeature,  "resultType",
+                                  NULL);
+        if (pszValue)
+          wfsparams->pszResultType = msStrdup(pszValue);
 
-        /*do we validate the xml ?*/
-        validate = msOWSLookupMetadata(&(map->web.metadata), "FO", "validate_xml");
-        if (validate && strcasecmp(validate, "true") == 0 &&
-            (schema_location = msOWSLookupMetadata(&(map->web.metadata), "FO", "schemas_dir")))
-        {       
-            if ((wfsparams->pszService  && strcmp(wfsparams->pszService, "WFS") == 0) ||
-                force_wfs_mode)
-            {
-                schema_file = msStringConcatenate(schema_file, schema_location);
-                if (wfsparams->pszVersion == NULL || 
-                    strncasecmp(wfsparams->pszVersion, "1.1", 3) ==0)
-                {
-                    schema_file = msStringConcatenate(schema_file,  "wfs/1.1.0/wfs.xsd");
-                    if (msOWSSchemaValidation(schema_file, request->postrequest) != 0)
-                    {
-                        msSetError(MS_WFSERR, "Invalid POST request.  XML is not valid", "msWFSParseRequest()");
-                        return MS_FAILURE;
-                    }
-                }
-            }
-        } 
-
-        /*parse describefeature*/
-        if (strcmp(wfsparams->pszRequest,"DescribeFeatureType") == 0)
-        {
-            /*look for TypeName and outputFormat*/
-            for (node = rootnode->children; node; node = node->next) 
-            {
-                if (node->type != XML_ELEMENT_NODE)
-                  continue;
+        pszValue = CPLGetXMLValue(psGetFeature,  "maxFeatures",
+                                  NULL);
+        if (pszValue)
+          wfsparams->nMaxFeatures = atoi(pszValue);
 
-                if (strcmp(node->name, "TypeName") == 0)
-                {
-                    pszValue = xmlNodeGetContent(node);
-                    if (wfsparams->pszTypeName == NULL)
-                      wfsparams->pszTypeName = msStrdup(pszValue);
-                    else
-                    {
-                        wfsparams->pszTypeName = 
-                          msStringConcatenate(wfsparams->pszTypeName, ",");
-                        wfsparams->pszTypeName = 
-                          msStringConcatenate(wfsparams->pszTypeName, pszValue);
-                    }
-                }
-            }
-            pszValue = xmlGetProp(rootnode, (xmlChar *)"outputFormat");
-            if (pszValue)
-              wfsparams->pszOutputFormat = msStrdup(pszValue);            
-        }  
+        pszValue = CPLGetXMLValue(psGetFeature,  "startIndex",
+                                  NULL);
+        if (pszValue)
+          wfsparams->nStartIndex = atoi(pszValue);
 
-        /*parse GetFeature*/
-        if (strcmp(wfsparams->pszRequest,"GetFeature") == 0)
-        {
-            pszValue = xmlGetProp(rootnode, (xmlChar *)"resultType");
+        pszValue = CPLGetXMLValue(psGetFeature, "outputFormat",
+                                  NULL);
+        if (pszValue)
+          wfsparams->pszOutputFormat = msStrdup(pszValue);
+
+        psQuery = CPLGetXMLNode(psGetFeature, "Query");
+        if (psQuery) {
+
+          /* free typname and filter. There may have been */
+          /* values if they were passed in the URL */
+          if (wfsparams->pszTypeName)
+            free(wfsparams->pszTypeName);
+          wfsparams->pszTypeName = NULL;
+
+          if (wfsparams->pszFilter)
+            free(wfsparams->pszFilter);
+          wfsparams->pszFilter = NULL;
+
+          if (psQuery->psNext && psQuery->psNext->pszValue &&
+              strcasecmp(psQuery->psNext->pszValue, "Query") == 0)
+            bMultiLayer = 1;
+
+          /* -------------------------------------------------------------------- */
+          /*      Parse typenames and filters. If there are multiple queries,     */
+          /*      typenames will be build with comma between thme                 */
+          /*      (typename1,typename2,...) and filters will be build with        */
+          /*      bracets enclosinf the filters :(filter1)(filter2)...            */
+          /*      propertynames are stored like (property1,property2)(property1)  */
+          /* -------------------------------------------------------------------- */
+          while (psQuery &&  psQuery->pszValue &&
+                 strcasecmp(psQuery->pszValue, "Query") == 0) {
+            /* get SRS */
+            pszValue = CPLGetXMLValue(psGetFeature,  "srsName",
+                                      NULL);
             if (pszValue)
-              wfsparams->pszResultType = msStrdup(pszValue);
+              wfsparams->pszSrs = msStrdup(pszValue);
+
+            /* parse typenames */
+            pszValue = CPLGetXMLValue(psQuery,
+                                      "typename", NULL);
+            if (pszValue) {
+              if (wfsparams->pszTypeName == NULL)
+                wfsparams->pszTypeName = msStrdup(pszValue);
+              else {
+                pszTmp = msStrdup(wfsparams->pszTypeName);
+                wfsparams->pszTypeName =
+                  (char *)msSmallRealloc(wfsparams->pszTypeName,
+                                         sizeof(char)*
+                                         (strlen(pszTmp)+
+                                          strlen(pszValue)+2));
+
+                sprintf(wfsparams->pszTypeName,"%s,%s",pszTmp,
+                        pszValue);
+                free(pszTmp);
+              }
+            }
 
-            pszValue = xmlGetProp(rootnode, (xmlChar *)"maxFeatures");
-            if (pszValue)
-              wfsparams->nMaxFeatures = atoi(pszValue);
+            /*parse property name*/
+            psPropertyName = CPLGetXMLNode(psQuery, "PropertyName");
+            pszTmp2= NULL;
 
-            pszValue = xmlGetProp(rootnode, (xmlChar *)"startIndex");
-            if (pszValue)
-              wfsparams->nStartIndex = atoi(pszValue);
-            
-            pszValue = xmlGetProp(rootnode, (xmlChar *)"outputFormat");
-            if (pszValue)
-              wfsparams->pszOutputFormat = msStrdup(pszValue);            
-
-            /* free typename and filter. There may have been */
-            /* values if they were passed in the URL */
-            if (wfsparams->pszTypeName)    
-              free(wfsparams->pszTypeName);
-            wfsparams->pszTypeName = NULL;
-                        
-            if (wfsparams->pszFilter)    
-              free(wfsparams->pszFilter);
-            wfsparams->pszFilter = NULL;
-
-            for (node = rootnode->children; node; node = node->next) 
-            {
-                if (node->type != XML_ELEMENT_NODE)
-                  continue;
+            /*when there is no PropertyName, we outpout (!) so that it is parsed properly in GetFeature*/
+            if (psPropertyName == NULL)
+              pszTmp2 = msStrdup("!");
 
-                if (strcmp(node->name, "Query") == 0)
-                {
-                    /* get SRS: TODO support srs per layer. Now we only have one srs 
-                     that applies to al layers*/
-                    pszValue = xmlGetProp(node, (xmlChar *)"srsName");
-                    if (pszValue)
-                    {
-                        if (wfsparams->pszSrs )
-                          msFree( wfsparams->pszSrs);
-                        wfsparams->pszSrs = msStrdup(pszValue);
-                    }
-                    /*type name*/
-                    pszValue = xmlGetProp(node, (xmlChar *)"typeName");
-                    if (pszValue)
-                    {   
-                        if (wfsparams->pszTypeName == NULL)
-                          wfsparams->pszTypeName = msStrdup(pszValue);
-                        else
-                        {
-                            wfsparams->pszTypeName = 
-                              msStringConcatenate(wfsparams->pszTypeName, ",");
-                            wfsparams->pszTypeName = 
-                              msStringConcatenate(wfsparams->pszTypeName, pszValue);
-                        }
-                    }
-                    /*PropertyName and Filter*/
-                    pszLayerPropertyName = NULL;
-                    pszLayerFilter = NULL;
-                    for (node1 = node->children; node1; node1 = node1->next) 
-                    {
-                        if (node1->type != XML_ELEMENT_NODE)
-                          continue;
-
-                        if (strcmp(node1->name, "PropertyName") == 0)
-                        {
-                            pszValue = xmlNodeGetContent(node1);
-                            if (pszLayerPropertyName == NULL)
-                              pszLayerPropertyName = msStrdup(pszValue);
-                            else
-                            {   
-                                pszLayerPropertyName= 
-                                  msStringConcatenate(pszLayerPropertyName, ",");
-                                pszLayerPropertyName = 
-                                  msStringConcatenate(pszLayerPropertyName, pszValue);
-                            }
-                        }
-                        if (strcmp(node1->name, "Filter") == 0)
-                        {
-                            
-                            pszValue = xmlNodeGetContent(node1);
-                            if (pszValue)
-                            {   
-                                xmlBufferPtr buffer;
-
-                                pszTmp = NULL;
-                                buffer = xmlBufferCreate();
-                                xmlNodeDump(buffer, node1->doc, node1, 0, 0);
-
-                                pszTmp = msStringConcatenate(pszTmp, "(");
-                                pszTmp = msStringConcatenate(pszTmp, buffer->content);
-                                pszTmp = msStringConcatenate(pszTmp, ")");
-                                
-                                xmlBufferFree(buffer);
-                                wfsparams->pszFilter = 
-                                  msStringConcatenate(wfsparams->pszFilter,pszTmp);
-                                msFree(pszTmp);
-                            }
-                        }
-                    }
-                    pszTmp = NULL;
-                    if (pszLayerPropertyName == NULL)
-                      pszTmp = msStrdup("(!)");
-                    else
-                    {
-                        pszTmp = msStringConcatenate(pszTmp, "(");
-                        pszTmp = msStringConcatenate(pszTmp, pszLayerPropertyName);
-                        pszTmp = msStringConcatenate(pszTmp, ")");
-                        msFree(pszLayerPropertyName);
-                    }
-                    wfsparams->pszPropertyName = msStringConcatenate(wfsparams->pszPropertyName, pszTmp);
-                    msFree(pszTmp);
-                        
-                }/*Query node*/
+            while (psPropertyName) {
+              if (!psPropertyName->pszValue ||
+                  strcasecmp(psPropertyName->pszValue, "PropertyName") != 0) {
+                psPropertyName = psPropertyName->psNext;
+                continue;
+              }
+              pszValue = CPLGetXMLValue(psPropertyName, NULL, NULL);
+              if (pszTmp2 == NULL) {
+                pszTmp2 = msStrdup(pszValue);
+              } else {
+                pszTmp = msStrdup(pszTmp2);
+                pszTmp2 = (char *)msSmallRealloc(pszTmp2, sizeof(char)* (strlen(pszTmp)+ strlen(pszValue)+2));
+                sprintf(pszTmp2,"%s,%s",pszTmp, pszValue);
+                msFree(pszTmp);
+              }
+              psPropertyName = psPropertyName->psNext;
+            }
+            if (pszTmp2) {
+              pszTmp = msStrdup(pszTmp2);
+              pszTmp2 = (char *)msSmallRealloc(pszTmp2, sizeof(char)* (strlen(pszTmp)+ 3));
+              sprintf(pszTmp2,"(%s)", pszTmp);
+              msFree(pszTmp);
+
+              if (wfsparams->pszPropertyName == NULL)
+                wfsparams->pszPropertyName = msStrdup(pszTmp2);
+              else {
+                pszTmp = msStrdup(wfsparams->pszPropertyName);
+                wfsparams->pszPropertyName =
+                  (char *)msSmallRealloc(wfsparams->pszPropertyName,
+                                         sizeof(char)*(strlen(pszTmp)+ strlen(pszTmp2)+1));
+                sprintf(wfsparams->pszPropertyName,"%s%s",wfsparams->pszPropertyName,
+                        pszTmp2);
+                msFree(pszTmp);
+              }
+              msFree(pszTmp2);
+              pszTmp2 = NULL;
             }
 
-        }              
-        
-        
-         /* check for request */
-        /* only works??? if <wfs:getCapbilites ...>
-        psXPathTmp = msLibXml2GetXPath(doc, context, (xmlChar *)"/wfs:GetCapabilities|/GetCapabilities");
-        psXPathTmp = msLibXml2GetXPath(doc, context, (xmlChar *)"/GetCapabilities");
-        psXPathTmp = msLibXml2GetXPath(doc, context, (xmlChar *)"/wfs:GetCapabilities");
-        psXPathTmp = msLibXml2GetXPath(doc, context, (xmlChar *)"GetCapabilities");
-        psXPathTmp = msLibXml2GetXPath(doc, context, (xmlChar *)"//GetCapabilities");
-        */
-#else /*#ifdef WFS_USE_LIBXML2*/
-        CPLXMLNode *psRoot, *psQuery, *psFilter, *psTypeName,  *psPropertyName  = NULL;
-        CPLXMLNode *psGetFeature = NULL;
-        CPLXMLNode  *psGetCapabilities = NULL;
-        CPLXMLNode *psDescribeFeature = NULL;
-        CPLXMLNode *psOperation = NULL;
-        const char *pszValue;
-        char *pszSerializedFilter, *pszTmp, *pszTmp2 = NULL;
-        int bMultiLayer = 0;
-
-        psRoot = CPLParseXMLString(request->postrequest);
-        if(map->debug == MS_DEBUGLEVEL_VVV)
-        {
-            msDebug("msWFSParseRequest(): WFS post request: %s\n", request->postrequest);
-        }
-        if (psRoot)
-        {
-            /* need to strip namespaces */
-            CPLStripXMLNamespace(psRoot, NULL, 1);
-            for( psOperation = psRoot; 
-                 psOperation != NULL; 
-                 psOperation = psOperation->psNext )
-            {
-                if(psOperation->eType == CXT_Element)
-                {
-                    if(strcasecmp(psOperation->pszValue,"GetFeature")==0)
-                    {
-                        psGetFeature = psOperation;
-                        break;
-                    }
-                    else if(strcasecmp(psOperation->pszValue,"GetCapabilities")==0)
-                    {
-                        psGetCapabilities = psOperation;
-                        pszValue = CPLGetXMLValue(psGetFeature,  "updateSequence", NULL);
-
-                        if (pszValue)
-                            wfsparams->pszUpdateSequence = msStrdup(pszValue);
-
-                        break;
-                    }
-                    else if(strcasecmp(psOperation->pszValue,
-                                       "DescribeFeatureType")==0)
-                    {
-                        psDescribeFeature = psOperation;
-                        break;
-                    }
-                    /* these are unsupported requests. Just set the  */
-                    /* request value and return; */
-                    else if (strcasecmp(psOperation->pszValue, 
-                                        "GetFeatureWithLock") == 0)
-                    {
-                        wfsparams->pszRequest = msStrdup("GetFeatureWithLock");
-                         break;
-                    }
-                    else if (strcasecmp(psOperation->pszValue, 
-                                        "LockFeature") == 0)
-                    {
-                        wfsparams->pszRequest = msStrdup("LockFeature");
-                         break;
-                    }
-                    else if (strcasecmp(psOperation->pszValue, 
-                                        "Transaction") == 0)
-                    {
-                        wfsparams->pszRequest = msStrdup("Transaction");
-                        break;
-                    }
+            /* parse filter */
+            psFilter = CPLGetXMLNode(psQuery, "Filter");
+
+            if (psFilter) {
+              if (!bMultiLayer)
+                wfsparams->pszFilter = CPLSerializeXMLTree(psFilter);
+              else {
+                pszSerializedFilter = CPLSerializeXMLTree(psFilter);
+                pszTmp = (char *)msSmallMalloc(sizeof(char)*
+                                               (strlen(pszSerializedFilter)+3));
+                sprintf(pszTmp, "(%s)", pszSerializedFilter);
+                free(pszSerializedFilter);
+
+                if (wfsparams->pszFilter == NULL)
+                  wfsparams->pszFilter = msStrdup(pszTmp);
+                else {
+                  pszSerializedFilter = msStrdup(wfsparams->pszFilter);
+                  wfsparams->pszFilter =
+                    (char *)msSmallRealloc(wfsparams->pszFilter,
+                                           sizeof(char)*
+                                           (strlen(pszSerializedFilter)+
+                                            strlen(pszTmp)+1));
+                  sprintf(wfsparams->pszFilter, "%s%s",
+                          pszSerializedFilter, pszTmp);
+
+                  free(pszSerializedFilter);
                 }
+                free(pszTmp);
+              }
             }
 
-/* -------------------------------------------------------------------- */
-/*      Parse the GetFeature                                            */
-/* -------------------------------------------------------------------- */
-            if (psGetFeature)
-            {
-                wfsparams->pszRequest = msStrdup("GetFeature");
-            
-                pszValue = CPLGetXMLValue(psGetFeature,  "version",
-                                                 NULL);
-                if (pszValue)
-                  wfsparams->pszVersion = msStrdup(pszValue);
-                
-                pszValue = CPLGetXMLValue(psGetFeature,  "service",
-                                                 NULL);
-                if (pszValue)
-                  wfsparams->pszService = msStrdup(pszValue);
-
-                pszValue = CPLGetXMLValue(psGetFeature,  "resultType",
-                                                 NULL);
-                if (pszValue)
-                  wfsparams->pszResultType = msStrdup(pszValue);
-
-                pszValue = CPLGetXMLValue(psGetFeature,  "maxFeatures",
-                                                 NULL);
-                if (pszValue)
-                  wfsparams->nMaxFeatures = atoi(pszValue);
-
-                pszValue = CPLGetXMLValue(psGetFeature,  "startIndex",
-                                                 NULL);
-                if (pszValue)
-                  wfsparams->nStartIndex = atoi(pszValue);
-
-                pszValue = CPLGetXMLValue(psGetFeature, "outputFormat", 
-                                                 NULL);
-                if (pszValue)
-                  wfsparams->pszOutputFormat = msStrdup(pszValue);
-
-                psQuery = CPLGetXMLNode(psGetFeature, "Query");
-                if (psQuery)
-                {
-                   
-                    /* free typname and filter. There may have been */
-                    /* values if they were passed in the URL */
-                    if (wfsparams->pszTypeName)    
-                      free(wfsparams->pszTypeName);
-                    wfsparams->pszTypeName = NULL;
-                        
-                    if (wfsparams->pszFilter)    
-                      free(wfsparams->pszFilter);
-                    wfsparams->pszFilter = NULL;
-                    
-                    if (psQuery->psNext && psQuery->psNext->pszValue &&
-                        strcasecmp(psQuery->psNext->pszValue, "Query") == 0)
-                      bMultiLayer = 1;
-
-/* -------------------------------------------------------------------- */
-/*      Parse typenames and filters. If there are multiple queries,     */
-/*      typenames will be build with comma between thme                 */
-/*      (typename1,typename2,...) and filters will be build with        */
-/*      bracets enclosinf the filters :(filter1)(filter2)...            */
-/*      propertynames are stored like (property1,property2)(property1)  */
-/* -------------------------------------------------------------------- */
-                    while (psQuery &&  psQuery->pszValue && 
-                           strcasecmp(psQuery->pszValue, "Query") == 0)
-                    {
-                        /* get SRS */
-                        pszValue = CPLGetXMLValue(psGetFeature,  "srsName",
-                                                 NULL);
-                        if (pszValue)
-                          wfsparams->pszSrs = msStrdup(pszValue);
-
-                        /* parse typenames */
-                        pszValue = CPLGetXMLValue(psQuery,
-                                                         "typename", NULL);
-                        if (pszValue)
-                        {
-                            if (wfsparams->pszTypeName == NULL)
-                              wfsparams->pszTypeName = msStrdup(pszValue);
-                            else
-                            {
-                                pszTmp = msStrdup(wfsparams->pszTypeName);
-                                wfsparams->pszTypeName = 
-                                  (char *)msSmallRealloc(wfsparams->pszTypeName,
-                                                         sizeof(char)*
-                                                         (strlen(pszTmp)+
-                                                          strlen(pszValue)+2));
-                                
-                                sprintf(wfsparams->pszTypeName,"%s,%s",pszTmp, 
-                                        pszValue);
-                                free(pszTmp);
-                            }
-                        }
-                        
-                        /*parse property name*/
-                        psPropertyName = CPLGetXMLNode(psQuery, "PropertyName");
-                        pszTmp2= NULL;
-
-                        /*when there is no PropertyName, we outpout (!) so that it is parsed properly in GetFeature*/
-                        if (psPropertyName == NULL)
-                          pszTmp2 = msStrdup("!");
-
-                        while (psPropertyName)
-                        {
-                            if (!psPropertyName->pszValue || 
-                                strcasecmp(psPropertyName->pszValue, "PropertyName") != 0)
-                            {
-                                psPropertyName = psPropertyName->psNext;
-                                continue;
-                            }
-                            pszValue = CPLGetXMLValue(psPropertyName, NULL, NULL);
-                            if (pszTmp2 == NULL) {
-                                pszTmp2 = msStrdup(pszValue);
-                            } 
-                            else 
-                            {
-                                pszTmp = msStrdup(pszTmp2);
-                                pszTmp2 = (char *)msSmallRealloc(pszTmp2, sizeof(char)* (strlen(pszTmp)+ strlen(pszValue)+2));
-                                sprintf(pszTmp2,"%s,%s",pszTmp, pszValue);
-                                msFree(pszTmp);
-                            }
-                            psPropertyName = psPropertyName->psNext;
-                        }
-                        if (pszTmp2)
-                        {
-                            pszTmp = msStrdup(pszTmp2);
-                            pszTmp2 = (char *)msSmallRealloc(pszTmp2, sizeof(char)* (strlen(pszTmp)+ 3));
-                            sprintf(pszTmp2,"(%s)", pszTmp);
-                            msFree(pszTmp);
-
-                            if (wfsparams->pszPropertyName == NULL)
-                              wfsparams->pszPropertyName = msStrdup(pszTmp2);
-                            else
-                            {
-                                pszTmp = msStrdup(wfsparams->pszPropertyName);
-                                wfsparams->pszPropertyName =
-                                  (char *)msSmallRealloc(wfsparams->pszPropertyName,
-                                                  sizeof(char)*(strlen(pszTmp)+ strlen(pszTmp2)+1));
-                                sprintf(wfsparams->pszPropertyName,"%s%s",wfsparams->pszPropertyName,
-                                        pszTmp2);
-                                msFree(pszTmp);
-                            }
-                            msFree(pszTmp2);
-                            pszTmp2 = NULL;
-                        }
-                            
-                        /* parse filter */
-                        psFilter = CPLGetXMLNode(psQuery, "Filter");
-
-                        if (psFilter)
-                        {
-                            if (!bMultiLayer)
-                              wfsparams->pszFilter = CPLSerializeXMLTree(psFilter);
-                            else
-                            {
-                                pszSerializedFilter = CPLSerializeXMLTree(psFilter);
-                                pszTmp = (char *)msSmallMalloc(sizeof(char)*
-                                                        (strlen(pszSerializedFilter)+3));
-                                sprintf(pszTmp, "(%s)", pszSerializedFilter);
-                                free(pszSerializedFilter);
-
-                                if (wfsparams->pszFilter == NULL)
-                                  wfsparams->pszFilter = msStrdup(pszTmp);
-                                else
-                                {
-                                    pszSerializedFilter = msStrdup(wfsparams->pszFilter);
-                                    wfsparams->pszFilter = 
-                                      (char *)msSmallRealloc(wfsparams->pszFilter,
-                                                             sizeof(char)*
-                                                             (strlen(pszSerializedFilter)+
-                                                              strlen(pszTmp)+1));
-                                    sprintf(wfsparams->pszFilter, "%s%s",
-                                            pszSerializedFilter, pszTmp);
-
-                                    free(pszSerializedFilter);
-                                }
-                                free(pszTmp);
-                            }
-                        }
-                    
-                        psQuery = psQuery->psNext;
-                    }/* while psQuery */
-                }
-            }/* end of GetFeatures */
-
-/* -------------------------------------------------------------------- */
-/*      Parse GetCapabilities.                                          */
-/* -------------------------------------------------------------------- */
-            if (psGetCapabilities)
-            {
-                wfsparams->pszRequest = msStrdup("GetCapabilities");
-                pszValue = CPLGetXMLValue(psGetCapabilities,  "version",
-                                                 NULL);
-                /* version is optional for the GetCapabilities. If not */
-                /* provided, set it. */
-                if (pszValue)
-                  wfsparams->pszVersion = msStrdup(pszValue);
-                else
-                  wfsparams->pszVersion = msStrdup(msStrdup(msWFSGetDefaultVersion(map)));
-
-                 pszValue = 
-                   CPLGetXMLValue(psGetCapabilities, "service",
-                                         NULL);
-                if (pszValue)
-                  wfsparams->pszService = msStrdup(pszValue);
-            }/* end of GetCapabilites */
-/* -------------------------------------------------------------------- */
-/*      Parse DescribeFeatureType                                       */
-/* -------------------------------------------------------------------- */
-            if (psDescribeFeature)
-            {
-                wfsparams->pszRequest = msStrdup("DescribeFeatureType");
-
-                pszValue = CPLGetXMLValue(psDescribeFeature, "version",
-                                                 NULL);
-                if (pszValue)
-                  wfsparams->pszVersion = msStrdup(pszValue);
-
-                pszValue = CPLGetXMLValue(psDescribeFeature, "service",
-                                                 NULL);
-                if (pszValue)
-                  wfsparams->pszService = msStrdup(pszValue);
-
-                pszValue = CPLGetXMLValue(psDescribeFeature,
-                                                 "outputFormat", 
-                                                 NULL);
-                if (pszValue)
-                  wfsparams->pszOutputFormat = msStrdup(pszValue);
-
-                psTypeName = CPLGetXMLNode(psDescribeFeature, "TypeName");
-                if (psTypeName)
-                {
-                    /* free typname and filter. There may have been */
-                    /* values if they were passed in the URL */
-                    if (wfsparams->pszTypeName)    
-                      free(wfsparams->pszTypeName);
-                    wfsparams->pszTypeName = NULL;
-
-                    while (psTypeName && psTypeName->pszValue &&
-                           strcasecmp(psTypeName->pszValue, "TypeName") == 0)
-                    {
-                        if (psTypeName->psChild && psTypeName->psChild->pszValue)
-                        {
-                            pszValue = psTypeName->psChild->pszValue;
-                            if (wfsparams->pszTypeName == NULL)
-                              wfsparams->pszTypeName = msStrdup(pszValue);
-                            else
-                            {
-                                pszTmp = msStrdup(wfsparams->pszTypeName);
-                                wfsparams->pszTypeName = 
-                                  (char *)msSmallRealloc(wfsparams->pszTypeName,
-                                                         sizeof(char)*
-                                                         (strlen(pszTmp)+
-                                                          strlen(pszValue)+2));
-                                
-                                sprintf(wfsparams->pszTypeName,"%s,%s",pszTmp, 
-                                        pszValue);
-                                free(pszTmp);
-                            }
-                        }
-                        psTypeName = psTypeName->psNext;
-                    }
-                }
+            psQuery = psQuery->psNext;
+          }/* while psQuery */
+        }
+      }/* end of GetFeatures */
+
+      /* -------------------------------------------------------------------- */
+      /*      Parse GetCapabilities.                                          */
+      /* -------------------------------------------------------------------- */
+      if (psGetCapabilities) {
+        wfsparams->pszRequest = msStrdup("GetCapabilities");
+        pszValue = CPLGetXMLValue(psGetCapabilities,  "version",
+                                  NULL);
+        /* version is optional for the GetCapabilities. If not */
+        /* provided, set it. */
+        if (pszValue)
+          wfsparams->pszVersion = msStrdup(pszValue);
+        else
+          wfsparams->pszVersion = msStrdup(msStrdup(msWFSGetDefaultVersion(map)));
 
-            }/* end of DescibeFeatureType */
+        pszValue =
+          CPLGetXMLValue(psGetCapabilities, "service",
+                         NULL);
+        if (pszValue)
+          wfsparams->pszService = msStrdup(pszValue);
+      }/* end of GetCapabilites */
+      /* -------------------------------------------------------------------- */
+      /*      Parse DescribeFeatureType                                       */
+      /* -------------------------------------------------------------------- */
+      if (psDescribeFeature) {
+        wfsparams->pszRequest = msStrdup("DescribeFeatureType");
+
+        pszValue = CPLGetXMLValue(psDescribeFeature, "version",
+                                  NULL);
+        if (pszValue)
+          wfsparams->pszVersion = msStrdup(pszValue);
+
+        pszValue = CPLGetXMLValue(psDescribeFeature, "service",
+                                  NULL);
+        if (pszValue)
+          wfsparams->pszService = msStrdup(pszValue);
+
+        pszValue = CPLGetXMLValue(psDescribeFeature,
+                                  "outputFormat",
+                                  NULL);
+        if (pszValue)
+          wfsparams->pszOutputFormat = msStrdup(pszValue);
+
+        psTypeName = CPLGetXMLNode(psDescribeFeature, "TypeName");
+        if (psTypeName) {
+          /* free typname and filter. There may have been */
+          /* values if they were passed in the URL */
+          if (wfsparams->pszTypeName)
+            free(wfsparams->pszTypeName);
+          wfsparams->pszTypeName = NULL;
+
+          while (psTypeName && psTypeName->pszValue &&
+                 strcasecmp(psTypeName->pszValue, "TypeName") == 0) {
+            if (psTypeName->psChild && psTypeName->psChild->pszValue) {
+              pszValue = psTypeName->psChild->pszValue;
+              if (wfsparams->pszTypeName == NULL)
+                wfsparams->pszTypeName = msStrdup(pszValue);
+              else {
+                pszTmp = msStrdup(wfsparams->pszTypeName);
+                wfsparams->pszTypeName =
+                  (char *)msSmallRealloc(wfsparams->pszTypeName,
+                                         sizeof(char)*
+                                         (strlen(pszTmp)+
+                                          strlen(pszValue)+2));
+
+                sprintf(wfsparams->pszTypeName,"%s,%s",pszTmp,
+                        pszValue);
+                free(pszTmp);
+              }
+            }
+            psTypeName = psTypeName->psNext;
+          }
         }
-#endif /*USE_LIBXML2_WFS*/
-        
+
+      }/* end of DescibeFeatureType */
     }
+#endif /*USE_LIBXML2_WFS*/
+
+  }
 #endif
 #endif
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
diff --git a/mapwfs11.c b/mapwfs11.c
index 1b4fe9b..590b49e 100644
--- a/mapwfs11.c
+++ b/mapwfs11.c
@@ -2,7 +2,7 @@
  * $Id$
  *
  * Project:  MapServer
- * Purpose:  OGC WFS 1.1.0 implementation. This file holds some WFS 1.1.0 
+ * Purpose:  OGC WFS 1.1.0 implementation. This file holds some WFS 1.1.0
  *           specific functions but other parts are still implemented in mapwfs.c.
  * Author:   Y. Assefa, DM Solutions Group (assefa at dmsolutions.ca)
  *
@@ -15,22 +15,22 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
+ *
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  ****************************************************************************/
 
 #include "mapserver.h"
 #include "mapows.h"
 
-MS_CVSID("$Id$")
+
 
 #if defined(USE_WFS_SVR) && defined(USE_LIBXML2)
 #include "maplibxml2.h"
@@ -41,210 +41,211 @@ MS_CVSID("$Id$")
 /*                          msWFSException11()                          */
 /************************************************************************/
 
-int msWFSException11(mapObj *map, const char *locator, 
+int msWFSException11(mapObj *map, const char *locator,
                      const char *exceptionCode, const char *version)
 {
-    int size = 0;
-    char *errorString     = NULL;
-    char *errorMessage    = NULL;
-    char *schemasLocation = NULL;
-    const char *encoding;
+  int size = 0;
+  char *errorString     = NULL;
+  char *errorMessage    = NULL;
+  char *schemasLocation = NULL;
+  const char *encoding;
 
-    xmlDocPtr  psDoc      = NULL;   
-    xmlNodePtr psRootNode = NULL;
-    xmlNsPtr   psNsOws    = NULL;
-    xmlChar *buffer       = NULL;
-    
-    if (version == NULL)
-       version = "1.1.0";
+  xmlDocPtr  psDoc      = NULL;
+  xmlNodePtr psRootNode = NULL;
+  xmlNsPtr   psNsOws    = NULL;
+  xmlChar *buffer       = NULL;
 
-    psNsOws = xmlNewNs(NULL, BAD_CAST "http://www.opengis.net/ows", BAD_CAST "ows");
+  if (version == NULL)
+    version = "1.1.0";
 
-    encoding = msOWSLookupMetadata(&(map->web.metadata), "FO", "encoding");
+  psNsOws = xmlNewNs(NULL, BAD_CAST "http://www.opengis.net/ows", BAD_CAST "ows");
 
-    errorString = msGetErrorString("\n");
-    errorMessage = msEncodeHTMLEntities(errorString);
-    schemasLocation = msEncodeHTMLEntities(msOWSGetSchemasLocation(map));
+  encoding = msOWSLookupMetadata(&(map->web.metadata), "FO", "encoding");
 
-    psDoc = xmlNewDoc(BAD_CAST "1.0");
+  errorString = msGetErrorString("\n");
+  errorMessage = msEncodeHTMLEntities(errorString);
+  schemasLocation = msEncodeHTMLEntities(msOWSGetSchemasLocation(map));
 
-    psRootNode = msOWSCommonExceptionReport(psNsOws, OWS_1_0_0, schemasLocation, version, msOWSGetLanguage(map, "exception"), exceptionCode, locator, errorMessage);
+  psDoc = xmlNewDoc(BAD_CAST "1.0");
 
-    xmlDocSetRootElement(psDoc, psRootNode);
+  psRootNode = msOWSCommonExceptionReport(psNsOws, OWS_1_0_0, schemasLocation, version, msOWSGetLanguage(map, "exception"), exceptionCode, locator, errorMessage);
 
-    xmlNewNs(psRootNode, BAD_CAST "http://www.opengis.net/ows", BAD_CAST "ows");
+  xmlDocSetRootElement(psDoc, psRootNode);
 
-    if (encoding)
-        msIO_printf("Content-type: text/xml; charset=%s%c%c", encoding,10,10);
-    else
-        msIO_printf("Content-type: text/xml%c%c",10,10);
+  xmlNewNs(psRootNode, BAD_CAST "http://www.opengis.net/ows", BAD_CAST "ows");
 
-    xmlDocDumpFormatMemoryEnc(psDoc, &buffer, &size, (encoding ? encoding : "ISO-8859-1"), 1);
-    
-    msIO_printf("%s", buffer);
+  if (encoding)
+    msIO_setHeader("Content-Type","text/xml; charset=%s", encoding);
+  else
+    msIO_setHeader("Content-Type","text/xml");
+  msIO_sendHeaders();
 
-    /*free buffer and the document */
-    free(errorString);
-    free(errorMessage);
-    free(schemasLocation);
-    xmlFree(buffer);
-    xmlFreeDoc(psDoc);
-    xmlFreeNs(psNsOws);
+  xmlDocDumpFormatMemoryEnc(psDoc, &buffer, &size, (encoding ? encoding : "ISO-8859-1"), 1);
 
-    /* clear error since we have already reported it */
-    msResetErrorList();
+  msIO_printf("%s", buffer);
 
-    return MS_FAILURE;
+  /*free buffer and the document */
+  free(errorString);
+  free(errorMessage);
+  free(schemasLocation);
+  xmlFree(buffer);
+  xmlFreeDoc(psDoc);
+  xmlFreeNs(psNsOws);
+
+  /* clear error since we have already reported it */
+  msResetErrorList();
+
+  return MS_FAILURE;
 }
-    
+
 
 /************************************************************************/
 /*                             msWFSDumpLayer11                         */
 /************************************************************************/
 static xmlNodePtr msWFSDumpLayer11(mapObj *map, layerObj *lp, xmlNsPtr psNsOws)
 {
-    rectObj ext;
-   
-    xmlNodePtr psRootNode, psNode;
-    const char *value    = NULL;
-    const char *encoding = NULL;
-    char *encoded=NULL;
-    char *valueToFree;
-    char **tokens;
-    int n=0,i=0;      
-
-    encoding = msOWSLookupMetadata(&(map->web.metadata), "FO", "encoding");
-    if (!encoding)
-      encoding = "ISO-8859-1";
-
-    psRootNode = xmlNewNode(NULL, BAD_CAST "FeatureType");
-
-    /*if there is an encoding using it on some of the items*/
-    psNode = msOWSCommonxmlNewChildEncoded(psRootNode, NULL, "Name", lp->name, encoding);
+  rectObj ext;
 
+  xmlNodePtr psRootNode, psNode;
+  const char *value    = NULL;
+  const char *encoding = NULL;
+  char *encoded=NULL;
+  char *valueToFree;
+  char **tokens;
+  int n=0,i=0;
 
-    if (lp->name && strlen(lp->name) > 0 &&
-        (msIsXMLTagValid(lp->name) == MS_FALSE || isdigit(lp->name[0])))
-      xmlAddSibling(psNode,
-                    xmlNewComment(BAD_CAST "WARNING: The layer name '%s' might contain spaces or "
-                                  "invalid characters or may start with a number. This could lead to potential problems"));
-   
-    value = msOWSLookupMetadata(&(lp->metadata), "FO", "title");
-    if (!value)
-      value =(const char*)lp->name;
+  encoding = msOWSLookupMetadata(&(map->web.metadata), "FO", "encoding");
+  if (!encoding)
+    encoding = "ISO-8859-1";
 
-    psNode = msOWSCommonxmlNewChildEncoded(psRootNode, NULL, "Title", value, encoding);
+  psRootNode = xmlNewNode(NULL, BAD_CAST "FeatureType");
 
- 
-    value = msOWSLookupMetadata(&(lp->metadata), "FO", "abstract");
-    if (value)
-      psNode = msOWSCommonxmlNewChildEncoded(psRootNode, NULL, "Abstract", value, encoding);
+  /* add namespace to layer name */
+  value = msOWSLookupMetadata(&(map->web.metadata), "FO", "namespace_prefix");
+  if(value) {
+    n = strlen(value)+strlen(lp->name)+1+1;
+    valueToFree = (char *) msSmallMalloc(sizeof(char*)*n);
+    snprintf(valueToFree, n, "%s%s%s", (value ? value : ""), (value ? ":" : ""), lp->name);
 
+    /*if there is an encoding using it on some of the items*/
+    psNode = msOWSCommonxmlNewChildEncoded(psRootNode, NULL, "Name", valueToFree, encoding);
+    msFree(valueToFree);
+  } else {
+    psNode = msOWSCommonxmlNewChildEncoded(psRootNode, NULL, "Name", lp->name, encoding);
+  }
 
+  if (lp->name && strlen(lp->name) > 0 &&
+      (msIsXMLTagValid(lp->name) == MS_FALSE || isdigit(lp->name[0])))
+    xmlAddSibling(psNode,
+                  xmlNewComment(BAD_CAST "WARNING: The layer name '%s' might contain spaces or "
+                                "invalid characters or may start with a number. This could lead to potential problems"));
 
-    value = msOWSLookupMetadata(&(lp->metadata), "FO", "keywordlist");
+  value = msOWSLookupMetadata(&(lp->metadata), "FO", "title");
+  if (!value)
+    value =(const char*)lp->name;
 
-    if (value)
-    {
-	if (encoding)
-	  encoded = msGetEncodedString(value, encoding);
-        else
-          encoded = msGetEncodedString(value, "ISO-8859-1");
+  psNode = msOWSCommonxmlNewChildEncoded(psRootNode, NULL, "Title", value, encoding);
 
-        msLibXml2GenerateList(
-            xmlNewChild(psRootNode, psNsOws, BAD_CAST "Keywords", NULL),
-            NULL, "Keyword", encoded, ',' );
-	msFree(encoded);
-    }
-      /*support DefaultSRS and OtherSRS*/
-    valueToFree = msOWSGetProjURN(&(map->projection),&(map->web.metadata),"FO",MS_FALSE);
-    if (!valueToFree)
-      valueToFree = msOWSGetProjURN(&(lp->projection), &(lp->metadata), "FO", MS_FALSE);
-
-    if (valueToFree)
-    {
-        tokens = msStringSplit(valueToFree, ' ', &n);
-        if (tokens && n > 0)
-        {
-            psNode = xmlNewChild(psRootNode, NULL, BAD_CAST "DefaultSRS", BAD_CAST tokens[0]);
-            for (i=1; i<n; i++)
-              psNode = xmlNewChild(psRootNode, NULL, BAD_CAST "OtherSRS", BAD_CAST tokens[i]);
-
-            msFreeCharArray(tokens, n);
-        }
-    }
-    else
-      xmlAddSibling(psNode,
-                    xmlNewComment(BAD_CAST "WARNING: Mandatory mapfile parameter: (at least one of) MAP.PROJECTION, LAYER.PROJECTION or wfs/ows_srs metadata was missing in this context."));
 
-    free(valueToFree);
-    valueToFree = NULL;
+  value = msOWSLookupMetadata(&(lp->metadata), "FO", "abstract");
+  if (value)
+    psNode = msOWSCommonxmlNewChildEncoded(psRootNode, NULL, "Abstract", value, encoding);
 
-    /*TODO: adevertize only gml3?*/
-    psNode = xmlNewNode(NULL, BAD_CAST "OutputFormats");
-    xmlAddChild(psRootNode, psNode);
 
-    {
-        char *formats_list = msWFSGetOutputFormatList( map, lp, "1.1.0" );
-        int iformat, n;
-        char **tokens;
 
-        n = 0;
-        tokens = msStringSplit(formats_list, ',', &n);
+  value = msOWSLookupMetadata(&(lp->metadata), "FO", "keywordlist");
 
-        for( iformat = 0; iformat < n; iformat++ )
-            xmlNewChild(psNode, NULL, BAD_CAST "Format", 
-                        BAD_CAST tokens[iformat] );
-        msFree( formats_list );
-        msFreeCharArray( tokens, n );
-    }
-  
-    /*bbox*/
-    if (msOWSGetLayerExtent(map, lp, "FO", &ext) == MS_SUCCESS)
-    {   
-        /*convert to latlong*/
-        if (lp->projection.numargs > 0)
-        {
-            if (!pj_is_latlong(&lp->projection.proj))
-              msProjectRect(&lp->projection, NULL, &ext);
-        }
-        else if (map->projection.numargs > 0 && !pj_is_latlong(&map->projection.proj))
-          msProjectRect(&map->projection, NULL, &ext);
-
-        xmlAddChild(psRootNode,
-                    msOWSCommonWGS84BoundingBox( psNsOws, 2,
-                                                 ext.minx, ext.miny,
-                                                 ext.maxx, ext.maxy));
-    }
+  if (value) {
+    if (encoding)
+      encoded = msGetEncodedString(value, encoding);
     else
-    {
-        xmlNewChild(psRootNode, psNsOws, BAD_CAST "WGS84BoundingBox", NULL);
-        xmlAddSibling(psNode,
-                      xmlNewComment(BAD_CAST "WARNING: Optional WGS84BoundingBox could not be established for this layer.  Consider setting the EXTENT in the LAYER object, or wfs_extent metadata. Also check that your data exists in the DATA statement"));
+      encoded = msGetEncodedString(value, "ISO-8859-1");
+
+    msLibXml2GenerateList(
+      xmlNewChild(psRootNode, psNsOws, BAD_CAST "Keywords", NULL),
+      NULL, "Keyword", encoded, ',' );
+    msFree(encoded);
+  }
+  /*support DefaultSRS and OtherSRS*/
+  valueToFree = msOWSGetProjURN(&(map->projection),&(map->web.metadata),"FO",MS_FALSE);
+  if (!valueToFree)
+    valueToFree = msOWSGetProjURN(&(lp->projection), &(lp->metadata), "FO", MS_FALSE);
+
+  if (valueToFree) {
+    tokens = msStringSplit(valueToFree, ' ', &n);
+    if (tokens && n > 0) {
+      psNode = xmlNewChild(psRootNode, NULL, BAD_CAST "DefaultSRS", BAD_CAST tokens[0]);
+      for (i=1; i<n; i++)
+        psNode = xmlNewChild(psRootNode, NULL, BAD_CAST "OtherSRS", BAD_CAST tokens[i]);
+
+      msFreeCharArray(tokens, n);
     }
+  } else
+    xmlAddSibling(psNode,
+                  xmlNewComment(BAD_CAST "WARNING: Mandatory mapfile parameter: (at least one of) MAP.PROJECTION, LAYER.PROJECTION or wfs/ows_srs metadata was missing in this context."));
 
-    value = msOWSLookupMetadata(&(lp->metadata), "FO", "metadataurl_href");
+  free(valueToFree);
+  valueToFree = NULL;
 
-    if (value)
-    {
-        psNode = xmlNewChild(psRootNode, NULL, BAD_CAST "MetadataURL", BAD_CAST value);
+  /*TODO: adevertize only gml3?*/
+  psNode = xmlNewNode(NULL, BAD_CAST "OutputFormats");
+  xmlAddChild(psRootNode, psNode);
 
-        value = msOWSLookupMetadata(&(lp->metadata), "FO", "metadataurl_format");
+  {
+    char *formats_list = msWFSGetOutputFormatList( map, lp, "1.1.0" );
+    int iformat, n;
+    char **tokens;
 
-        if (!value)
-          value = msStrdup("text/html"); /* default */
+    n = 0;
+    tokens = msStringSplit(formats_list, ',', &n);
+
+    for( iformat = 0; iformat < n; iformat++ )
+      xmlNewChild(psNode, NULL, BAD_CAST "Format",
+                  BAD_CAST tokens[iformat] );
+    msFree( formats_list );
+    msFreeCharArray( tokens, n );
+  }
+
+  /*bbox*/
+  if (msOWSGetLayerExtent(map, lp, "FO", &ext) == MS_SUCCESS) {
+    /*convert to latlong*/
+    if (lp->projection.numargs > 0) {
+      if (!pj_is_latlong(&lp->projection.proj))
+        msProjectRect(&lp->projection, NULL, &ext);
+    } else if (map->projection.numargs > 0 && !pj_is_latlong(&map->projection.proj))
+      msProjectRect(&map->projection, NULL, &ext);
+
+    xmlAddChild(psRootNode,
+                msOWSCommonWGS84BoundingBox( psNsOws, 2,
+                    ext.minx, ext.miny,
+                    ext.maxx, ext.maxy));
+  } else {
+    xmlNewChild(psRootNode, psNsOws, BAD_CAST "WGS84BoundingBox", NULL);
+    xmlAddSibling(psNode,
+                  xmlNewComment(BAD_CAST "WARNING: Optional WGS84BoundingBox could not be established for this layer.  Consider setting the EXTENT in the LAYER object, or wfs_extent metadata. Also check that your data exists in the DATA statement"));
+  }
+
+  value = msOWSLookupMetadata(&(lp->metadata), "FO", "metadataurl_href");
+
+  if (value) {
+    psNode = xmlNewChild(psRootNode, NULL, BAD_CAST "MetadataURL", BAD_CAST value);
+
+    value = msOWSLookupMetadata(&(lp->metadata), "FO", "metadataurl_format");
 
-        xmlNewProp(psNode, BAD_CAST "format", BAD_CAST value);
+    if (!value)
+      value = msStrdup("text/html"); /* default */
 
-        value = msOWSLookupMetadata(&(lp->metadata), "FO", "metadataurl_type");
+    xmlNewProp(psNode, BAD_CAST "format", BAD_CAST value);
 
-        if (!value)
-          value = msStrdup("FGDC"); /* default */
+    value = msOWSLookupMetadata(&(lp->metadata), "FO", "metadataurl_type");
 
-        xmlNewProp(psNode, BAD_CAST "type", BAD_CAST value);
-    }
+    if (!value)
+      value = msStrdup("FGDC"); /* default */
+
+    xmlNewProp(psNode, BAD_CAST "type", BAD_CAST value);
+  }
 
-    return psRootNode;
+  return psRootNode;
 }
 
 /************************************************************************/
@@ -252,240 +253,259 @@ static xmlNodePtr msWFSDumpLayer11(mapObj *map, layerObj *lp, xmlNsPtr psNsOws)
 /*                                                                      */
 /*      Return the capabilities document for wfs 1.1.0                  */
 /************************************************************************/
-int msWFSGetCapabilities11(mapObj *map, wfsParamsObj *params, 
-                           cgiRequestObj *req, owsRequestObj *ows_request) 
+int msWFSGetCapabilities11(mapObj *map, wfsParamsObj *params,
+                           cgiRequestObj *req, owsRequestObj *ows_request)
 {
-    xmlDocPtr psDoc = NULL;       /* document pointer */
-    xmlNodePtr psRootNode, psMainNode, psNode, psFtNode;
-    xmlNodePtr psTmpNode;
-    const char *updatesequence=NULL;
-    xmlNsPtr psNsOws, psNsXLink, psNsOgc;
-    char *schemalocation = NULL;
-    char *xsi_schemaLocation = NULL;
-
-    char *script_url=NULL, *script_url_encoded=NULL, *formats_list;
-    const char *value = NULL;
-    const char *encoding;
-
-    xmlChar *buffer = NULL;
-    int size = 0, i;
-    msIOContext *context = NULL;
-
-    int ows_version = OWS_1_0_0;
-
-/* -------------------------------------------------------------------- */
-/*      Handle updatesequence                                           */
-/* -------------------------------------------------------------------- */
-
-    updatesequence = msOWSLookupMetadata(&(map->web.metadata), "FO", "updatesequence");
-
-    encoding = msOWSLookupMetadata(&(map->web.metadata), "FO", "encoding");
-
-    if (params->pszUpdateSequence != NULL) {
-      i = msOWSNegotiateUpdateSequence(params->pszUpdateSequence, updatesequence);
-      if (i == 0) { /* current */
-          msSetError(MS_WFSERR, "UPDATESEQUENCE parameter (%s) is equal to server (%s)", "msWFSGetCapabilities11()", params->pszUpdateSequence, updatesequence);
-          return msWFSException11(map, "updatesequence", "CurrentUpdateSequence", params->pszVersion);
-      }
-      if (i > 0) { /* invalid */
-          msSetError(MS_WFSERR, "UPDATESEQUENCE parameter (%s) is higher than server (%s)", "msWFSGetCapabilities11()", params->pszUpdateSequence, updatesequence);
-          return msWFSException11(map, "updatesequence", "InvalidUpdateSequence", params->pszVersion);
-      }
+  xmlDocPtr psDoc = NULL;       /* document pointer */
+  xmlNodePtr psRootNode, psMainNode, psNode, psFtNode;
+  const char *updatesequence=NULL;
+  xmlNsPtr psNsOws, psNsXLink, psNsOgc;
+  char *schemalocation = NULL;
+  char *xsi_schemaLocation = NULL;
+  const char *user_namespace_prefix = NULL;
+  const char *user_namespace_uri = NULL;
+  gmlNamespaceListObj *namespaceList=NULL; /* for external application schema support */
+
+  char *script_url=NULL, *script_url_encoded=NULL, *formats_list;
+  const char *value = NULL;
+  const char *encoding;
+
+  xmlChar *buffer = NULL;
+  int size = 0, i;
+  msIOContext *context = NULL;
+
+  int ows_version = OWS_1_0_0;
+
+  /* -------------------------------------------------------------------- */
+  /*      Handle updatesequence                                           */
+  /* -------------------------------------------------------------------- */
+
+  updatesequence = msOWSLookupMetadata(&(map->web.metadata), "FO", "updatesequence");
+
+  encoding = msOWSLookupMetadata(&(map->web.metadata), "FO", "encoding");
+
+  if (params->pszUpdateSequence != NULL) {
+    i = msOWSNegotiateUpdateSequence(params->pszUpdateSequence, updatesequence);
+    if (i == 0) { /* current */
+      msSetError(MS_WFSERR, "UPDATESEQUENCE parameter (%s) is equal to server (%s)", "msWFSGetCapabilities11()", params->pszUpdateSequence, updatesequence);
+      return msWFSException11(map, "updatesequence", "CurrentUpdateSequence", params->pszVersion);
     }
-
-/* -------------------------------------------------------------------- */
-/*      Create document.                                                */
-/* -------------------------------------------------------------------- */
-    psDoc = xmlNewDoc(BAD_CAST "1.0");
-
-    psRootNode = xmlNewNode(NULL, BAD_CAST "WFS_Capabilities");
-
-    xmlDocSetRootElement(psDoc, psRootNode);
-
-/* -------------------------------------------------------------------- */
-/*      Name spaces                                                     */
-/* -------------------------------------------------------------------- */
-    /*default name space*/      
-    xmlNewProp(psRootNode, BAD_CAST "xmlns", BAD_CAST "http://www.opengis.net/wfs");
-    
-    xmlSetNs(psRootNode, xmlNewNs(psRootNode, BAD_CAST "http://www.opengis.net/gml", BAD_CAST "gml"));
-    xmlSetNs(psRootNode, xmlNewNs(psRootNode, BAD_CAST "http://www.opengis.net/wfs", BAD_CAST "wfs"));
-    
-    psNsOws = xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_OWS_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_OWS_NAMESPACE_PREFIX);
-    psNsXLink = xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_W3C_XLINK_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_W3C_XLINK_NAMESPACE_PREFIX);
-    xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_W3C_XSI_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_W3C_XSI_NAMESPACE_PREFIX);
-    xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_OGC_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_OGC_NAMESPACE_PREFIX );
-
-    xmlNewProp(psRootNode, BAD_CAST "version", BAD_CAST params->pszVersion );
-
-    updatesequence = msOWSLookupMetadata(&(map->web.metadata), "FO", "updatesequence");
-
-    if (updatesequence)
-      xmlNewProp(psRootNode, BAD_CAST "updateSequence", BAD_CAST updatesequence);
-
-    /*schema*/
-    schemalocation = msEncodeHTMLEntities( msOWSGetSchemasLocation(map) );
-    xsi_schemaLocation = msStrdup("http://www.opengis.net/wfs");
-    xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, " ");
-    xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, schemalocation);
-    xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, "/wfs/1.1.0/wfs.xsd");
-    xmlNewNsProp(psRootNode, NULL, BAD_CAST "xsi:schemaLocation", BAD_CAST xsi_schemaLocation);
-
-/* -------------------------------------------------------------------- */
-/*      Service metadata.                                               */
-/* -------------------------------------------------------------------- */
-
-    psTmpNode = xmlAddChild(psRootNode, 
-                            msOWSCommonServiceIdentification(psNsOws, map, "OGC WFS", params->pszVersion, "FO"));
-
-    /*service provider*/
-    psTmpNode = xmlAddChild(psRootNode, msOWSCommonServiceProvider(
-                                psNsOws, psNsXLink, map, "FO"));
-
-    /*operation metadata */
-    if ((script_url=msOWSGetOnlineResource(map, "FO", "onlineresource", req)) == NULL 
-        || (script_url_encoded = msEncodeHTMLEntities(script_url)) == NULL)
-    {
-        msSetError(MS_WFSERR, "Server URL not found", "msWFSGetCapabilities11()");
-        return msWFSException11(map, "mapserv", "NoApplicableCode", params->pszVersion);
+    if (i > 0) { /* invalid */
+      msSetError(MS_WFSERR, "UPDATESEQUENCE parameter (%s) is higher than server (%s)", "msWFSGetCapabilities11()", params->pszUpdateSequence, updatesequence);
+      return msWFSException11(map, "updatesequence", "InvalidUpdateSequence", params->pszVersion);
+    }
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Create document.                                                */
+  /* -------------------------------------------------------------------- */
+  psDoc = xmlNewDoc(BAD_CAST "1.0");
+
+  psRootNode = xmlNewNode(NULL, BAD_CAST "WFS_Capabilities");
+
+  xmlDocSetRootElement(psDoc, psRootNode);
+
+  /* -------------------------------------------------------------------- */
+  /*      Name spaces                                                     */
+  /* -------------------------------------------------------------------- */
+  /*default name space*/
+  xmlNewProp(psRootNode, BAD_CAST "xmlns", BAD_CAST "http://www.opengis.net/wfs");
+
+  xmlSetNs(psRootNode, xmlNewNs(psRootNode, BAD_CAST "http://www.opengis.net/gml", BAD_CAST "gml"));
+  xmlSetNs(psRootNode, xmlNewNs(psRootNode, BAD_CAST "http://www.opengis.net/wfs", BAD_CAST "wfs"));
+
+  psNsOws = xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_OWS_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_OWS_NAMESPACE_PREFIX);
+  psNsXLink = xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_W3C_XLINK_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_W3C_XLINK_NAMESPACE_PREFIX);
+  xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_W3C_XSI_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_W3C_XSI_NAMESPACE_PREFIX);
+  xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_OGC_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_OGC_NAMESPACE_PREFIX );
+
+  value = msOWSLookupMetadata(&(map->web.metadata), "FO", "namespace_uri");
+  if(value) user_namespace_uri = value;
+
+  value = msOWSLookupMetadata(&(map->web.metadata), "FO", "namespace_prefix");
+  if(value) user_namespace_prefix = value;
+  if(user_namespace_prefix != NULL && msIsXMLTagValid(user_namespace_prefix) == MS_FALSE)
+    msIO_printf("<!-- WARNING: The value '%s' is not valid XML namespace. -->\n", user_namespace_prefix);
+  else
+    xmlNewNs(psRootNode, BAD_CAST user_namespace_uri, BAD_CAST user_namespace_prefix);
+
+  /* any additional namespaces */
+  namespaceList = msGMLGetNamespaces(&(map->web), "G");
+  for(i=0; i<namespaceList->numnamespaces; i++) {
+    if(namespaceList->namespaces[i].uri) {
+      xmlNewNs(psRootNode, BAD_CAST namespaceList->namespaces[i].uri, BAD_CAST namespaceList->namespaces[i].prefix);
     }
+  }
+  msGMLFreeNamespaces(namespaceList);
+  
+
+  xmlNewProp(psRootNode, BAD_CAST "version", BAD_CAST params->pszVersion );
 
-/* -------------------------------------------------------------------- */
-/*      Operations metadata.                                            */
-/* -------------------------------------------------------------------- */
-    psMainNode= xmlAddChild(psRootNode,msOWSCommonOperationsMetadata(psNsOws));
-
-/* -------------------------------------------------------------------- */
-/*      GetCapabilities                                                 */
-/* -------------------------------------------------------------------- */
-    psNode = xmlAddChild(psMainNode, 
-                         msOWSCommonOperationsMetadataOperation(psNsOws,psNsXLink,"GetCapabilities", 
-                                                                OWS_METHOD_GETPOST, script_url_encoded));
-    
+  updatesequence = msOWSLookupMetadata(&(map->web.metadata), "FO", "updatesequence");
+
+  if (updatesequence)
+    xmlNewProp(psRootNode, BAD_CAST "updateSequence", BAD_CAST updatesequence);
+
+  /*schema*/
+  schemalocation = msEncodeHTMLEntities( msOWSGetSchemasLocation(map) );
+  xsi_schemaLocation = msStrdup("http://www.opengis.net/wfs");
+  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, " ");
+  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, schemalocation);
+  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, "/wfs/1.1.0/wfs.xsd");
+  xmlNewNsProp(psRootNode, NULL, BAD_CAST "xsi:schemaLocation", BAD_CAST xsi_schemaLocation);
+
+  /* -------------------------------------------------------------------- */
+  /*      Service metadata.                                               */
+  /* -------------------------------------------------------------------- */
+
+  xmlAddChild(psRootNode,
+                          msOWSCommonServiceIdentification(psNsOws, map, "OGC WFS", params->pszVersion, "FO"));
+
+  /*service provider*/
+  xmlAddChild(psRootNode, msOWSCommonServiceProvider(
+                            psNsOws, psNsXLink, map, "FO"));
+
+  /*operation metadata */
+  if ((script_url=msOWSGetOnlineResource(map, "FO", "onlineresource", req)) == NULL
+      || (script_url_encoded = msEncodeHTMLEntities(script_url)) == NULL) {
+    msSetError(MS_WFSERR, "Server URL not found", "msWFSGetCapabilities11()");
+    return msWFSException11(map, "mapserv", "NoApplicableCode", params->pszVersion);
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Operations metadata.                                            */
+  /* -------------------------------------------------------------------- */
+  psMainNode= xmlAddChild(psRootNode,msOWSCommonOperationsMetadata(psNsOws));
+
+  /* -------------------------------------------------------------------- */
+  /*      GetCapabilities                                                 */
+  /* -------------------------------------------------------------------- */
+  psNode = xmlAddChild(psMainNode,
+                       msOWSCommonOperationsMetadataOperation(psNsOws,psNsXLink,"GetCapabilities",
+                           OWS_METHOD_GETPOST, script_url_encoded));
+
+  xmlAddChild(psMainNode, psNode);
+  xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(
+                ows_version, psNsOws, "Parameter", "service", "WFS"));
+  /*accept version*/
+  xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,
+              "Parameter", "AcceptVersions",
+              "1.0.0,1.1.0"));
+  /*format*/
+  xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,
+              "Parameter", "AcceptFormats",
+              "text/xml"));
+
+
+  /* -------------------------------------------------------------------- */
+  /*      DescribeFeatureType                                             */
+  /* -------------------------------------------------------------------- */
+  if (msOWSRequestIsEnabled(map, NULL, "F", "DescribeFeatureType", MS_TRUE)) {
+    psNode = xmlAddChild(psMainNode,
+                         msOWSCommonOperationsMetadataOperation(psNsOws,psNsXLink,"DescribeFeatureType",
+                             OWS_METHOD_GETPOST, script_url_encoded));
     xmlAddChild(psMainNode, psNode);
-    xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(
-                    ows_version, psNsOws, "Parameter", "service", "WFS"));
-    /*accept version*/
-    xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws, 
-                                                                "Parameter", "AcceptVersions", 
-                                                                "1.0.0,1.1.0"));
-    /*format*/
-    xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws, 
-                                                                "Parameter", "AcceptFormats", 
-                                                                "text/xml"));
-
-
-/* -------------------------------------------------------------------- */
-/*      DescribeFeatureType                                             */
-/* -------------------------------------------------------------------- */
-    if (msOWSRequestIsEnabled(map, NULL, "F", "DescribeFeatureType", MS_TRUE)) 
-    {
-        psNode = xmlAddChild(psMainNode, 
-                             msOWSCommonOperationsMetadataOperation(psNsOws,psNsXLink,"DescribeFeatureType", 
-                                                                 OWS_METHOD_GETPOST, script_url_encoded));
-        xmlAddChild(psMainNode, psNode);
-        
-        /*output format*/
-        xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws, 
-                                                                    "Parameter", "outputFormat", 
-                                                                    "XMLSCHEMA,text/xml; subtype=gml/2.1.2,text/xml; subtype=gml/3.1.1"));
-    }
 
-/* -------------------------------------------------------------------- */
-/*      GetFeature                                                      */
-/* -------------------------------------------------------------------- */
-    if (msOWSRequestIsEnabled(map, NULL, "F", "GetFeature", MS_TRUE)) 
-    {
-
-        psNode = xmlAddChild(psMainNode, 
-                             msOWSCommonOperationsMetadataOperation(psNsOws,psNsXLink,"GetFeature", 
-                                                                 OWS_METHOD_GETPOST, script_url_encoded));
-        xmlAddChild(psMainNode, psNode);
-        
-        xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,
-                                                                    "Parameter", "resultType", 
-                                                                    "results,hits"));
-
-        formats_list = msWFSGetOutputFormatList( map, NULL, "1.1.0" );
-        xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws, 
-                                                                    "Parameter", "outputFormat", 
-                                                                    formats_list));
-        msFree( formats_list );
-
-        value = msOWSLookupMetadata(&(map->web.metadata), "FO", "maxfeatures");
-
-        if (value) {
-            xmlAddChild(psMainNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,
-                                                                            "Constraint", "DefaultMaxFeatures",
-                                                                            (char *)value));
-        }
+    /*output format*/
+    xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,
+                "Parameter", "outputFormat",
+                "XMLSCHEMA,text/xml; subtype=gml/2.1.2,text/xml; subtype=gml/3.1.1"));
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      GetFeature                                                      */
+  /* -------------------------------------------------------------------- */
+  if (msOWSRequestIsEnabled(map, NULL, "F", "GetFeature", MS_TRUE)) {
+
+    psNode = xmlAddChild(psMainNode,
+                         msOWSCommonOperationsMetadataOperation(psNsOws,psNsXLink,"GetFeature",
+                             OWS_METHOD_GETPOST, script_url_encoded));
+    xmlAddChild(psMainNode, psNode);
+
+    xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,
+                "Parameter", "resultType",
+                "results,hits"));
+
+    formats_list = msWFSGetOutputFormatList( map, NULL, "1.1.0" );
+    xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,
+                "Parameter", "outputFormat",
+                formats_list));
+    msFree( formats_list );
+
+    value = msOWSLookupMetadata(&(map->web.metadata), "FO", "maxfeatures");
+
+    if (value) {
+      xmlAddChild(psMainNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,
+                  "Constraint", "DefaultMaxFeatures",
+                  (char *)value));
     }
+  }
 
-/* -------------------------------------------------------------------- */
-/*      FeatureTypeList                                                 */
-/* -------------------------------------------------------------------- */
-     
-     psFtNode = xmlNewNode(NULL, BAD_CAST "FeatureTypeList");
-     xmlAddChild(psRootNode, psFtNode);
-     psNode = xmlNewChild(psFtNode, NULL, BAD_CAST "Operations", NULL);
-     xmlNewChild(psNode, NULL, BAD_CAST "Operation", BAD_CAST "Query");
-     
-     for(i=0; i<map->numlayers; i++)
-     {
-         layerObj *lp;
-         lp = GET_LAYER(map, i);
-         
-         if (!msIntegerInArray(lp->index, ows_request->enabled_layers, ows_request->numlayers))
-             continue;
-
-         /* List only vector layers in which DUMP=TRUE */
-         if (msWFSIsLayerSupported(lp))
-           xmlAddChild(psFtNode, msWFSDumpLayer11(map, lp, psNsOws));
-     }
-     
-     
-     
-     
-     
-/* -------------------------------------------------------------------- */
-/*      Filter capabilities.                                            */
-/* -------------------------------------------------------------------- */
-
-     psNsOgc = xmlNewNs(NULL, BAD_CAST MS_OWSCOMMON_OGC_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_OGC_NAMESPACE_PREFIX);
-     xmlAddChild(psRootNode, FLTGetCapabilities(psNsOgc, psNsOgc, MS_FALSE));
-/* -------------------------------------------------------------------- */
-/*      Write out the document.                                         */
-/* -------------------------------------------------------------------- */
-
-    if( msIO_needBinaryStdout() == MS_FAILURE )
-        return MS_FAILURE;
-     
-    if (encoding)
-        msIO_printf("Content-type: text/xml; charset=%s%c%c", encoding,10,10);
-    else
-        msIO_printf("Content-type: text/xml%c%c",10,10);
-    
-    context = msIO_getHandler(stdout);
+  /* -------------------------------------------------------------------- */
+  /*      FeatureTypeList                                                 */
+  /* -------------------------------------------------------------------- */
 
-    xmlDocDumpFormatMemoryEnc(psDoc, &buffer, &size, (encoding ? encoding : "ISO-8859-1"), 1);
-    msIO_contextWrite(context, buffer, size);
-    xmlFree(buffer);
+  psFtNode = xmlNewNode(NULL, BAD_CAST "FeatureTypeList");
+  xmlAddChild(psRootNode, psFtNode);
+  psNode = xmlNewChild(psFtNode, NULL, BAD_CAST "Operations", NULL);
+  xmlNewChild(psNode, NULL, BAD_CAST "Operation", BAD_CAST "Query");
 
-    /*free buffer and the document */
-    /*xmlFree(buffer);*/
-    xmlFreeDoc(psDoc);
-    xmlFreeNs(psNsOgc);
+  for(i=0; i<map->numlayers; i++) {
+    layerObj *lp;
+    lp = GET_LAYER(map, i);
 
-    free(script_url);	
-     free(script_url_encoded);
-    free(xsi_schemaLocation);
-    free(schemalocation);
+    if (!msIntegerInArray(lp->index, ows_request->enabled_layers, ows_request->numlayers))
+      continue;
 
-    xmlCleanupParser();
+    /* List only vector layers in which DUMP=TRUE */
+    if (msWFSIsLayerSupported(lp))
+      xmlAddChild(psFtNode, msWFSDumpLayer11(map, lp, psNsOws));
+  }
 
-    return(MS_SUCCESS);
+
+
+
+
+  /* -------------------------------------------------------------------- */
+  /*      Filter capabilities.                                            */
+  /* -------------------------------------------------------------------- */
+
+  psNsOgc = xmlNewNs(NULL, BAD_CAST MS_OWSCOMMON_OGC_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_OGC_NAMESPACE_PREFIX);
+  xmlAddChild(psRootNode, FLTGetCapabilities(psNsOgc, psNsOgc, MS_FALSE));
+  /* -------------------------------------------------------------------- */
+  /*      Write out the document.                                         */
+  /* -------------------------------------------------------------------- */
+
+  if( msIO_needBinaryStdout() == MS_FAILURE )
+    return MS_FAILURE;
+
+  if (encoding)
+    msIO_setHeader("Content-Type","text/xml; charset=%s", encoding);
+  else
+    msIO_setHeader("Content-Type","text/xml");
+  msIO_sendHeaders();
+
+  context = msIO_getHandler(stdout);
+
+  xmlDocDumpFormatMemoryEnc(psDoc, &buffer, &size, (encoding ? encoding : "ISO-8859-1"), 1);
+  msIO_contextWrite(context, buffer, size);
+  xmlFree(buffer);
+
+  /*free buffer and the document */
+  /*xmlFree(buffer);*/
+  xmlFreeDoc(psDoc);
+  xmlFreeNs(psNsOgc);
+
+  free(script_url);
+  free(script_url_encoded);
+  free(xsi_schemaLocation);
+  free(schemalocation);
+
+  xmlCleanupParser();
+
+  return(MS_SUCCESS);
 }
-    
+
 
 #endif /*defined(USE_WFS_SVR) && defined(USE_LIBXML2)*/
 
@@ -493,20 +513,21 @@ int msWFSGetCapabilities11(mapObj *map, wfsParamsObj *params,
 
 
 
-int msWFSGetCapabilities11(mapObj *map, wfsParamsObj *params, 
-                           cgiRequestObj *req)
+int msWFSGetCapabilities11(mapObj *map, wfsParamsObj *params,
+                           cgiRequestObj *req, owsRequestObj *ows_request)
 
 {
-    msSetError( MS_WFSERR,
-                "WFS 1.1 request made, but mapserver requires libxml2 for WFS 1.1 services and this is not configured.",
-                "msWFSGetCapabilities11()", "NoApplicableCode" );
+  msSetError( MS_WFSERR,
+              "WFS 1.1 request made, but mapserver requires libxml2 for WFS 1.1 services and this is not configured.",
+              "msWFSGetCapabilities11()", "NoApplicableCode" );
 
-    return msWFSException11(map, "mapserv", "NoApplicableCode", params->pszVersion);
+  return msWFSException11(map, "mapserv", "NoApplicableCode", params->pszVersion);
 }
 
-int msWFSException11(mapObj *map, const char *locator, const char *exceptionCode, const char *version) {
-    /* fallback to reporting using 1.0 style exceptions. */
-    return msWFSException( map, locator, exceptionCode, "1.0.0" );
+int msWFSException11(mapObj *map, const char *locator, const char *exceptionCode, const char *version)
+{
+  /* fallback to reporting using 1.0 style exceptions. */
+  return msWFSException( map, locator, exceptionCode, "1.0.0" );
 }
 
 #endif /* defined(USE_WFS_SVR) && !defined(USE_LIBXML2) */
diff --git a/mapwfslayer.c b/mapwfslayer.c
index 4617976..61473b1 100644
--- a/mapwfslayer.c
+++ b/mapwfslayer.c
@@ -14,16 +14,16 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
+ *
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  ****************************************************************************/
 
 #include "mapserver.h"
@@ -37,7 +37,7 @@
 #include <process.h>
 #endif
 
-MS_CVSID("$Id$")
+
 
 #define WFS_V_0_0_14  14
 #define WFS_V_1_0_0  100
@@ -61,386 +61,372 @@ MS_CVSID("$Id$")
 /*      projection.                                                     */
 /*                                                                      */
 /************************************************************************/
-static wfsParamsObj *msBuildRequestParams(mapObj *map, layerObj *lp, 
-                                          rectObj *bbox_ret)
+static wfsParamsObj *msBuildRequestParams(mapObj *map, layerObj *lp,
+    rectObj *bbox_ret)
 {
-    wfsParamsObj *psParams = NULL;
-    rectObj bbox;
-    const char *pszTmp; 
-    int nLength, i = 0;
-    char *pszVersion, *pszTypeName = NULL;
+  wfsParamsObj *psParams = NULL;
+  rectObj bbox;
+  const char *pszTmp;
+  int nLength, i = 0;
+  char *pszVersion, *pszTypeName, *pszGeometryName = NULL;
 
-    if (!map || !lp || !bbox_ret)
-      return NULL;
+  if (!map || !lp || !bbox_ret)
+    return NULL;
 
-    if (lp->connection == NULL)
-      return NULL;
-    
-    psParams = msWFSCreateParamsObj();
-    pszTmp = msOWSLookupMetadata(&(lp->metadata), "FO", "version");
-    if (pszTmp)
-      psParams->pszVersion = msStrdup(pszTmp);
-    else
-    {
-        pszTmp = strstr(lp->connection, "VERSION=");
-        if (!pszTmp)
-           pszTmp = strstr(lp->connection, "version=");
-        if (pszTmp)
-        {
-            pszVersion = strchr(pszTmp, '=')+1;
-            if (strncmp(pszVersion, "0.0.14", 6) == 0)
-              psParams->pszVersion = msStrdup("0.0.14");
-            else if (strncmp(pszVersion, "1.0.0", 5) == 0)
-              psParams->pszVersion = msStrdup("1.0.0");
-        }
-    }
+  if (lp->connection == NULL)
+    return NULL;
 
-    /*the service is always set to WFS : see bug 1302 */
-    psParams->pszService = msStrdup("WFS");
-
-    /*
-    pszTmp = msOWSLookupMetadata(&(lp->metadata), "FO", "service");
-    if (pszTmp)
-      psParams->pszService = msStrdup(pszTmp);
-    else
-    {
-        pszTmp = strstr(lp->connection, "SERVICE=");
-        if (!pszTmp)
-          pszTmp = strstr(lp->connection, "service=");
-        if (pszTmp)
-        {
-            pszService = strchr(pszTmp, '=')+1;
-            if (strncmp(pszService, "WFS", 3) == 0)
-              psParams->pszService = msStrdup("WFS");
-        }
+  psParams = msWFSCreateParamsObj();
+  pszTmp = msOWSLookupMetadata(&(lp->metadata), "FO", "version");
+  if (pszTmp)
+    psParams->pszVersion = msStrdup(pszTmp);
+  else {
+    pszTmp = strstr(lp->connection, "VERSION=");
+    if (!pszTmp)
+      pszTmp = strstr(lp->connection, "version=");
+    if (pszTmp) {
+      pszVersion = strchr(pszTmp, '=')+1;
+      if (strncmp(pszVersion, "0.0.14", 6) == 0)
+        psParams->pszVersion = msStrdup("0.0.14");
+      else if (strncmp(pszVersion, "1.0.0", 5) == 0)
+        psParams->pszVersion = msStrdup("1.0.0");
     }
-    */
-
-    pszTmp = msOWSLookupMetadata(&(lp->metadata), "FO", "typename");
-    if (pszTmp)
-      psParams->pszTypeName = msStrdup(pszTmp);
-    else
-    {
-        pszTmp = strstr(lp->connection, "TYPENAME=");
-        if (!pszTmp)
-          pszTmp = strstr(lp->connection, "typename=");
-        if (pszTmp)
-        {
-            pszTypeName = strchr(pszTmp, '=')+1;
-            if (pszTypeName)
-            {
-                nLength = strlen(pszTypeName);
-                if (nLength > 0)
-                {
-                    for (i=0; i<nLength; i++)
-                    {
-                        if (pszTypeName[i] == '&')
-                          break;
-                    }
-
-                    if (i<nLength)
-                    {
-                        char *pszTypeNameTmp = NULL;
-                        pszTypeNameTmp = msStrdup(pszTypeName);
-                        pszTypeNameTmp[i] = '\0';
-                        psParams->pszTypeName = msStrdup(pszTypeNameTmp);
-                        free(pszTypeNameTmp);
-                    }
-                    else
-                      psParams->pszTypeName = msStrdup(pszTypeName);
-                }
-            }
+  }
+
+  /*the service is always set to WFS : see bug 1302 */
+  psParams->pszService = msStrdup("WFS");
+
+  /*
+  pszTmp = msOWSLookupMetadata(&(lp->metadata), "FO", "service");
+  if (pszTmp)
+    psParams->pszService = msStrdup(pszTmp);
+  else
+  {
+      pszTmp = strstr(lp->connection, "SERVICE=");
+      if (!pszTmp)
+        pszTmp = strstr(lp->connection, "service=");
+      if (pszTmp)
+      {
+          pszService = strchr(pszTmp, '=')+1;
+          if (strncmp(pszService, "WFS", 3) == 0)
+            psParams->pszService = msStrdup("WFS");
+      }
+  }
+  */
+
+  pszTmp = msOWSLookupMetadata(&(lp->metadata), "FO", "geometryname");
+  if (pszTmp)
+    psParams->pszGeometryName = msStrdup(pszTmp);
+
+  pszTmp = msOWSLookupMetadata(&(lp->metadata), "FO", "typename");
+  if (pszTmp)
+    psParams->pszTypeName = msStrdup(pszTmp);
+  else {
+    pszTmp = strstr(lp->connection, "TYPENAME=");
+    if (!pszTmp)
+      pszTmp = strstr(lp->connection, "typename=");
+    if (pszTmp) {
+      pszTypeName = strchr(pszTmp, '=')+1;
+      if (pszTypeName) {
+        nLength = strlen(pszTypeName);
+        if (nLength > 0) {
+          for (i=0; i<nLength; i++) {
+            if (pszTypeName[i] == '&')
+              break;
+          }
+
+          if (i<nLength) {
+            char *pszTypeNameTmp = NULL;
+            pszTypeNameTmp = msStrdup(pszTypeName);
+            pszTypeNameTmp[i] = '\0';
+            psParams->pszTypeName = msStrdup(pszTypeNameTmp);
+            free(pszTypeNameTmp);
+          } else
+            psParams->pszTypeName = msStrdup(pszTypeName);
         }
+      }
     }
-
-    pszTmp = msOWSLookupMetadata(&(lp->metadata), "FO", "filter");
-    if (pszTmp && strlen(pszTmp) > 0)
-    {
-        if (strstr(pszTmp, "<Filter>") !=NULL || strstr(pszTmp, "<ogc:Filter>") != NULL)
-          psParams->pszFilter = msStrdup(pszTmp);
-        else
-        {
-            psParams->pszFilter = msStringConcatenate(psParams->pszFilter, "<ogc:Filter>");
-            psParams->pszFilter = msStringConcatenate(psParams->pszFilter, (char*)pszTmp);
-            psParams->pszFilter = msStringConcatenate(psParams->pszFilter, "</ogc:Filter>");
-        }
+  }
+
+  pszTmp = msOWSLookupMetadata(&(lp->metadata), "FO", "filter");
+  if (pszTmp && strlen(pszTmp) > 0) {
+    if (strstr(pszTmp, "<Filter>") !=NULL || strstr(pszTmp, "<ogc:Filter") != NULL)
+      psParams->pszFilter = msStrdup(pszTmp);
+    else {
+      psParams->pszFilter = msStringConcatenate(psParams->pszFilter, "<ogc:Filter xmlns:ogc=\"http://www.opengis.net/ogc\">");
+      psParams->pszFilter = msStringConcatenate(psParams->pszFilter, (char*)pszTmp);
+      psParams->pszFilter = msStringConcatenate(psParams->pszFilter, "</ogc:Filter>");
     }
+  }
+
+  pszTmp = msOWSLookupMetadata(&(lp->metadata), "FO", "maxfeatures");
+  if (pszTmp)
+    psParams->nMaxFeatures = atoi(pszTmp);
+
+  /* Request is always GetFeature; */
+  psParams->pszRequest = msStrdup("GetFeature");
 
-     pszTmp = msOWSLookupMetadata(&(lp->metadata), "FO", "maxfeatures");
-     if (pszTmp)
-       psParams->nMaxFeatures = atoi(pszTmp);
-
-    /* Request is always GetFeature; */
-    psParams->pszRequest = msStrdup("GetFeature");
-
-               
-/* ------------------------------------------------------------------
- * Figure the SRS we'll use for the request.
- * - Fetch the map SRS (if it's EPSG)
- * - Check if map SRS is listed in layer wfs_srs metadata
- * - If map SRS is valid for this layer then use it
- * - Otherwise request layer in its default SRS and we'll reproject later
- * ------------------------------------------------------------------ */
-
-/* __TODO__ WFS servers support only one SRS... need to decide how we'll */
-/* handle this and document it well. */
-/* It's likely that we'll simply reproject the BBOX to teh layer's projection. */
-
-/* ------------------------------------------------------------------
- * Set layer SRS and reproject map extents to the layer's SRS
- * ------------------------------------------------------------------ */
+
+  /* ------------------------------------------------------------------
+   * Figure the SRS we'll use for the request.
+   * - Fetch the map SRS (if it's EPSG)
+   * - Check if map SRS is listed in layer wfs_srs metadata
+   * - If map SRS is valid for this layer then use it
+   * - Otherwise request layer in its default SRS and we'll reproject later
+   * ------------------------------------------------------------------ */
+
+  /* __TODO__ WFS servers support only one SRS... need to decide how we'll */
+  /* handle this and document it well. */
+  /* It's likely that we'll simply reproject the BBOX to teh layer's projection. */
+
+  /* ------------------------------------------------------------------
+   * Set layer SRS and reproject map extents to the layer's SRS
+   * ------------------------------------------------------------------ */
 #ifdef __TODO__
-    /* No need to set lp->proj if it's already set to the right EPSG code */
-    if ((pszTmp = msGetEPSGProj(&(lp->projection), NULL, MS_TRUE)) == NULL ||
-        strcasecmp(pszEPSG, pszTmp) != 0)
-    {
-        char szProj[20];
-        snprintf(szProj, sizeof(szProj), "init=epsg:%s", pszEPSG+5);
-        if (msLoadProjectionString(&(lp->projection), szProj) != 0)
-            return NULL;
-    }
+  /* No need to set lp->proj if it's already set to the right EPSG code */
+  if ((pszTmp = msGetEPSGProj(&(lp->projection), NULL, MS_TRUE)) == NULL ||
+      strcasecmp(pszEPSG, pszTmp) != 0) {
+    char szProj[20];
+    snprintf(szProj, sizeof(szProj), "init=epsg:%s", pszEPSG+5);
+    if (msLoadProjectionString(&(lp->projection), szProj) != 0)
+      return NULL;
+  }
 #endif
 
-    bbox = map->extent;
-    if (msProjectionsDiffer(&(map->projection), &(lp->projection)))
-    {
-        msProjectRect(&(map->projection), &(lp->projection), &bbox);
-    }
+  bbox = map->extent;
+  if (msProjectionsDiffer(&(map->projection), &(lp->projection))) {
+    msProjectRect(&(map->projection), &(lp->projection), &bbox);
+  }
 
-    if (bbox_ret != NULL)
-      *bbox_ret = bbox;
+  if (bbox_ret != NULL)
+    *bbox_ret = bbox;
 
-    return psParams;
+  return psParams;
 
 }
 
 /**********************************************************************
  *                          msBuildWFSLayerPostRequest()
  *
- * Build a WFS GetFeature xml document for a Post Request.  
+ * Build a WFS GetFeature xml document for a Post Request.
  *
- * Returns a reference to a newly allocated string that should be freed 
+ * Returns a reference to a newly allocated string that should be freed
  * by the caller.
  **********************************************************************/
-static char *msBuildWFSLayerPostRequest(mapObj *map, layerObj *lp, 
-                                        rectObj *bbox, wfsParamsObj *psParams) 
+static char *msBuildWFSLayerPostRequest(mapObj *map, layerObj *lp,
+                                        rectObj *bbox, wfsParamsObj *psParams)
 {
-    char *pszPostReq = NULL;
-    char *pszFilter = NULL;
-    size_t bufferSize = 0;
-
-    if (psParams->pszVersion == NULL || 
-        (strncmp(psParams->pszVersion, "0.0.14", 6) != 0 &&
-        strncmp(psParams->pszVersion, "1.0.0", 5)) != 0)
-    {
-        msSetError(MS_WFSCONNERR, "MapServer supports only WFS 1.0.0 or 0.0.14 (please verify the version metadata wfs_version).", "msBuildWFSLayerPostRequest()");
-        return NULL;
-    }
+  char *pszPostReq = NULL;
+  char *pszFilter = NULL;
+  char *pszGeometryName = "Geometry";
+  size_t bufferSize = 0;
+
+  if (psParams->pszVersion == NULL ||
+      (strncmp(psParams->pszVersion, "0.0.14", 6) != 0 &&
+       strncmp(psParams->pszVersion, "1.0.0", 5)) != 0) {
+    msSetError(MS_WFSCONNERR, "MapServer supports only WFS 1.0.0 or 0.0.14 (please verify the version metadata wfs_version).", "msBuildWFSLayerPostRequest()");
+    return NULL;
+  }
 
-    
-
-    if (psParams->pszTypeName == NULL)
-    {
-        msSetError(MS_WFSCONNERR, "Metadata wfs_typename must be set in the layer", "msBuildWFSLayerPostRequest()");
-        return NULL;
-    } 
-    
-    
-
-    if (psParams->pszFilter)
-      pszFilter = psParams->pszFilter;
-    else
-    {
-        bufferSize = 500;
-        pszFilter = (char *)msSmallMalloc(bufferSize);
-        snprintf(pszFilter, bufferSize, "<ogc:Filter>\n"
-"<ogc:BBOX>\n"
-"<ogc:PropertyName>Geometry</ogc:PropertyName>\n"
-"<gml:Box>\n"
-"<gml:coordinates>%f,%f %f,%f</gml:coordinates>\n"
-"</gml:Box>\n"
-"</ogc:BBOX>\n"
-"</ogc:Filter>",bbox->minx, bbox->miny, bbox->maxx, bbox->maxy);
-    }
-    
-    bufferSize = strlen(pszFilter)+500;
-    pszPostReq = (char *)msSmallMalloc(bufferSize);
-    if (psParams->nMaxFeatures > 0)
-      snprintf(pszPostReq, bufferSize, "<?xml version=\"1.0\" ?>\n"
-"<wfs:GetFeature\n"
-"service=\"WFS\"\n"
-"version=\"1.0.0\"\n"
-"maxFeatures=\"%d\"\n"
-"outputFormat=\"GML2\">\n"
-"<wfs:Query typeName=\"%s\">\n"
-"%s"
-"</wfs:Query>\n"
-"</wfs:GetFeature>\n", psParams->nMaxFeatures, psParams->pszTypeName, pszFilter);
-    else
-      snprintf(pszPostReq, bufferSize, "<?xml version=\"1.0\" ?>\n"
-"<wfs:GetFeature\n"
-"service=\"WFS\"\n"
-"version=\"1.0.0\"\n"
-"outputFormat=\"GML2\">\n"
-"<wfs:Query typeName=\"%s\">\n"
-"%s"
-"</wfs:Query>\n"
-"</wfs:GetFeature>\n", psParams->pszTypeName, pszFilter);
-    if (psParams->pszFilter == NULL)
-      free(pszFilter);
-
-
-    return pszPostReq; 
+
+
+  if (psParams->pszTypeName == NULL) {
+    msSetError(MS_WFSCONNERR, "Metadata wfs_typename must be set in the layer", "msBuildWFSLayerPostRequest()");
+    return NULL;
+  }
+
+
+  if (psParams->pszGeometryName) {
+    pszGeometryName = psParams->pszGeometryName;
+  }
+
+  if (psParams->pszFilter)
+    pszFilter = psParams->pszFilter;
+  else {
+    bufferSize = 500;
+    pszFilter = (char *)msSmallMalloc(bufferSize);
+    snprintf(pszFilter, bufferSize, "<ogc:Filter>\n"
+             "<ogc:BBOX>\n"
+             "<ogc:PropertyName>%s</ogc:PropertyName>\n"
+             "<gml:Box>\n"
+             "<gml:coordinates>%f,%f %f,%f</gml:coordinates>\n"
+             "</gml:Box>\n"
+             "</ogc:BBOX>\n"
+             "</ogc:Filter>", pszGeometryName, bbox->minx, bbox->miny, bbox->maxx, bbox->maxy);
+  }
+
+  bufferSize = strlen(pszFilter)+500;
+  pszPostReq = (char *)msSmallMalloc(bufferSize);
+  if (psParams->nMaxFeatures > 0)
+    snprintf(pszPostReq, bufferSize, "<?xml version=\"1.0\" ?>\n"
+             "<wfs:GetFeature\n"
+             "service=\"WFS\"\n"
+             "version=\"1.0.0\"\n"
+             "maxFeatures=\"%d\"\n"
+             "outputFormat=\"GML2\"\n"
+			 "xmlns:wfs=\"http://www.opengis.net/wfs\" xmlns:ogc=\"http://www.opengis.net/ogc\" xsi:schemaLocation=\"http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.0.0/wfs.xsd\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:gml=\"http://www.opengis.net/gml\">\n"
+             "<wfs:Query typeName=\"%s\">\n"
+             "%s"
+             "</wfs:Query>\n"
+             "</wfs:GetFeature>\n", psParams->nMaxFeatures, psParams->pszTypeName, pszFilter);
+  else
+    snprintf(pszPostReq, bufferSize, "<?xml version=\"1.0\" ?>\n"
+             "<wfs:GetFeature\n"
+             "service=\"WFS\"\n"
+             "version=\"1.0.0\"\n"
+             "outputFormat=\"GML2\"\n"
+             "xmlns:wfs=\"http://www.opengis.net/wfs\" xmlns:ogc=\"http://www.opengis.net/ogc\" xsi:schemaLocation=\"http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.0.0/wfs.xsd\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:gml=\"http://www.opengis.net/gml\">\n"
+             "<wfs:Query typeName=\"%s\">\n"
+             "%s"
+             "</wfs:Query>\n"
+             "</wfs:GetFeature>\n", psParams->pszTypeName, pszFilter);
+  if (psParams->pszFilter == NULL)
+    free(pszFilter);
+
+
+  return pszPostReq;
 }
 
 /**********************************************************************
  *                          msBuildWFSLayerGetURL()
  *
- * Build a WFS GetFeature URL for a Get Request.  
+ * Build a WFS GetFeature URL for a Get Request.
  *
- * Returns a reference to a newly allocated string that should be freed 
+ * Returns a reference to a newly allocated string that should be freed
  * by the caller.
  **********************************************************************/
 static char *msBuildWFSLayerGetURL(mapObj *map, layerObj *lp, rectObj *bbox,
-                                   wfsParamsObj *psParams) 
+                                   wfsParamsObj *psParams)
 {
-    char *pszURL = NULL, *pszOnlineResource=NULL;
-    const char *pszTmp; 
-    char *pszVersion, *pszService, *pszTypename = NULL;
-    int bVersionInConnection = 0, bServiceInConnection = 0;
-    int bTypenameInConnection = 0;
-    size_t bufferSize = 0;
-
-    if (lp->connectiontype != MS_WFS || lp->connection == NULL)
-    {
-        msSetError(MS_WFSCONNERR, "Call supported only for CONNECTIONTYPE WFS",
-                   "msBuildWFSLayerGetURL()");
-        return NULL;
+  char *pszURL = NULL, *pszOnlineResource=NULL;
+  const char *pszTmp;
+  char *pszVersion, *pszService, *pszTypename = NULL;
+  int bVersionInConnection = 0, bServiceInConnection = 0;
+  int bTypenameInConnection = 0;
+  size_t bufferSize = 0;
+
+  if (lp->connectiontype != MS_WFS || lp->connection == NULL) {
+    msSetError(MS_WFSCONNERR, "Call supported only for CONNECTIONTYPE WFS",
+               "msBuildWFSLayerGetURL()");
+    return NULL;
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Find out request version. Look first for the wfs_version        */
+  /*      metedata. If not available try to find out if the CONNECTION    */
+  /*      string contains the version. This last test is done for         */
+  /*      backward compatiblity but is depericated.                       */
+  /* -------------------------------------------------------------------- */
+  pszVersion = psParams->pszVersion;
+  if (!pszVersion) {
+    if ((pszTmp = strstr(lp->connection, "VERSION=")) == NULL &&
+        (pszTmp = strstr(lp->connection, "version=")) == NULL ) {
+      msSetError(MS_WFSCONNERR, "Metadata wfs_version must be set in the layer", "msBuildWFSLayerGetURL()");
+      return NULL;
     }
+    pszVersion = strchr(pszTmp, '=')+1;
+    bVersionInConnection = 1;
+  }
 
-/* -------------------------------------------------------------------- */
-/*      Find out request version. Look first for the wfs_version        */
-/*      metedata. If not available try to find out if the CONNECTION    */
-/*      string contains the version. This last test is done for         */
-/*      backward compatiblity but is depericated.                       */
-/* -------------------------------------------------------------------- */
-    pszVersion = psParams->pszVersion;
-    if (!pszVersion)
-    {
-      if ((pszTmp = strstr(lp->connection, "VERSION=")) == NULL &&
-          (pszTmp = strstr(lp->connection, "version=")) == NULL )
-      {
-        msSetError(MS_WFSCONNERR, "Metadata wfs_version must be set in the layer", "msBuildWFSLayerGetURL()");
-        return NULL;
-      }
-      pszVersion = strchr(pszTmp, '=')+1;
-      bVersionInConnection = 1;
-    }
-    
-   
-    if (strncmp(pszVersion, "0.0.14", 6) != 0 &&
-        strncmp(pszVersion, "1.0.0", 5) != 0 &&
-         strncmp(pszVersion, "1.1", 3) != 0)
-    {
-        msSetError(MS_WFSCONNERR, "MapServer supports only WFS 1.0.0 or 0.0.14 (please verify the version metadata wfs_version).", "msBuildWFSLayerGetURL()");
-        return NULL;
-    }
 
-/* -------------------------------------------------------------------- */
-/*      Find out the service. It is always set to WFS in function       */
-/*      msBuildRequestParms  (check Bug 1302 for details).              */
-/* -------------------------------------------------------------------- */
-    pszService = psParams->pszService;
-    
-   
-/* -------------------------------------------------------------------- */
-/*      Find out the typename. Look first for the wfs_tyename           */
-/*      metadata. If not available try to find out if the CONNECTION    */
-/*      string contains it. This last test is done for                  */
-/*      backward compatiblity but is depericated.                       */
-/* -------------------------------------------------------------------- */
-    pszTypename = psParams->pszTypeName;
-    if (!pszTypename)
-    {
-      if ((pszTmp = strstr(lp->connection, "TYPENAME=")) == NULL &&
-          (pszTmp = strstr(lp->connection, "typename=")) == NULL )
-      {
-        msSetError(MS_WFSCONNERR, "Metadata wfs_typename must be set in the layer", "msBuildWFSLayerGetURL()");
-        return NULL;
-      }
-      bTypenameInConnection = 1;
-    }
-    
-
-/* -------------------------------------------------------------------- 
- * Build the request URL.
- * At this point we set only the following parameters for GetFeature:
- *   REQUEST
- *   BBOX
- *   VERSION
- *   SERVICE
- *   TYPENAME
- *   FILTER
- *   MAXFEATURES
- *
- * For backward compatiblity the user could also have in the connection
- * string the following parameters (but it is depricated):
- *   VERSION
- *   SERVICE
- *   TYPENAME
- * -------------------------------------------------------------------- */
-    /* Make sure we have a big enough buffer for the URL */
-    bufferSize = strlen(lp->connection)+1024;
-    pszURL = (char *)malloc(bufferSize);
-    MS_CHECK_ALLOC(pszURL, bufferSize, NULL);
-
-    /* __TODO__ We have to urlencode each value... especially the BBOX values */
-    /* because if they end up in exponent format (123e+06) the + will be seen */
-    /* as a space by the remote server. */
-
-/* -------------------------------------------------------------------- */
-/*      build the URL,                                                  */
-/* -------------------------------------------------------------------- */
-    /* make sure connection ends with "&" or "?" */
-    pszOnlineResource = msOWSTerminateOnlineResource(lp->connection);
-    snprintf(pszURL, bufferSize, "%s", pszOnlineResource);
-    msFree(pszOnlineResource);
-
-    /* REQUEST */
-    snprintf(pszURL + strlen(pszURL), bufferSize-strlen(pszURL),  "&REQUEST=GetFeature");
-
-    /* VERSION */
-    if (!bVersionInConnection)
-      snprintf(pszURL + strlen(pszURL), bufferSize-strlen(pszURL),  "&VERSION=%s", pszVersion);
-    
-    /* SERVICE */
-    if (!bServiceInConnection)
-        snprintf(pszURL + strlen(pszURL), bufferSize-strlen(pszURL),  "&SERVICE=%s", pszService);
-
-    /* TYPENAME */
-    if (!bTypenameInConnection)
-      snprintf(pszURL + strlen(pszURL), bufferSize-strlen(pszURL),  "&TYPENAME=%s", pszTypename);
-
-/* -------------------------------------------------------------------- */
-/*      If the filter parameter is given in the wfs_filter metadata,    */
-/*      we use it and do not send the BBOX paramter as they are         */
-/*      mutually exclusive.                                             */
-/* -------------------------------------------------------------------- */
-    if (psParams->pszFilter)
-    {   
-        snprintf(pszURL + strlen(pszURL), bufferSize-strlen(pszURL), "&FILTER=%s",
-                 msEncodeUrl(psParams->pszFilter));
+  if (strncmp(pszVersion, "0.0.14", 6) != 0 &&
+      strncmp(pszVersion, "1.0.0", 5) != 0 &&
+      strncmp(pszVersion, "1.1", 3) != 0) {
+    msSetError(MS_WFSCONNERR, "MapServer supports only WFS 1.0.0 or 0.0.14 (please verify the version metadata wfs_version).", "msBuildWFSLayerGetURL()");
+    return NULL;
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Find out the service. It is always set to WFS in function       */
+  /*      msBuildRequestParms  (check Bug 1302 for details).              */
+  /* -------------------------------------------------------------------- */
+  pszService = psParams->pszService;
+
+
+  /* -------------------------------------------------------------------- */
+  /*      Find out the typename. Look first for the wfs_tyename           */
+  /*      metadata. If not available try to find out if the CONNECTION    */
+  /*      string contains it. This last test is done for                  */
+  /*      backward compatiblity but is depericated.                       */
+  /* -------------------------------------------------------------------- */
+  pszTypename = psParams->pszTypeName;
+  if (!pszTypename) {
+    if ((pszTmp = strstr(lp->connection, "TYPENAME=")) == NULL &&
+        (pszTmp = strstr(lp->connection, "typename=")) == NULL ) {
+      msSetError(MS_WFSCONNERR, "Metadata wfs_typename must be set in the layer", "msBuildWFSLayerGetURL()");
+      return NULL;
     }
-    else
-      snprintf(pszURL + strlen(pszURL), bufferSize-strlen(pszURL), 
-               "&BBOX=%.15g,%.15g,%.15g,%.15g",
-               bbox->minx, bbox->miny, bbox->maxx, bbox->maxy);
-    
-    if (psParams->nMaxFeatures > 0)
-      snprintf(pszURL + strlen(pszURL), bufferSize-strlen(pszURL),
-               "&MAXFEATURES=%d", psParams->nMaxFeatures);
-
-    return pszURL;
+    bTypenameInConnection = 1;
+  }
+
+
+  /* --------------------------------------------------------------------
+   * Build the request URL.
+   * At this point we set only the following parameters for GetFeature:
+   *   REQUEST
+   *   BBOX
+   *   VERSION
+   *   SERVICE
+   *   TYPENAME
+   *   FILTER
+   *   MAXFEATURES
+   *
+   * For backward compatiblity the user could also have in the connection
+   * string the following parameters (but it is depricated):
+   *   VERSION
+   *   SERVICE
+   *   TYPENAME
+   * -------------------------------------------------------------------- */
+  /* Make sure we have a big enough buffer for the URL */
+  bufferSize = strlen(lp->connection)+1024;
+  pszURL = (char *)malloc(bufferSize);
+  MS_CHECK_ALLOC(pszURL, bufferSize, NULL);
+
+  /* __TODO__ We have to urlencode each value... especially the BBOX values */
+  /* because if they end up in exponent format (123e+06) the + will be seen */
+  /* as a space by the remote server. */
+
+  /* -------------------------------------------------------------------- */
+  /*      build the URL,                                                  */
+  /* -------------------------------------------------------------------- */
+  /* make sure connection ends with "&" or "?" */
+  pszOnlineResource = msOWSTerminateOnlineResource(lp->connection);
+  snprintf(pszURL, bufferSize, "%s", pszOnlineResource);
+  msFree(pszOnlineResource);
+
+  /* REQUEST */
+  snprintf(pszURL + strlen(pszURL), bufferSize-strlen(pszURL),  "&REQUEST=GetFeature");
+
+  /* VERSION */
+  if (!bVersionInConnection)
+    snprintf(pszURL + strlen(pszURL), bufferSize-strlen(pszURL),  "&VERSION=%s", pszVersion);
+
+  /* SERVICE */
+  if (!bServiceInConnection)
+    snprintf(pszURL + strlen(pszURL), bufferSize-strlen(pszURL),  "&SERVICE=%s", pszService);
+
+  /* TYPENAME */
+  if (!bTypenameInConnection)
+    snprintf(pszURL + strlen(pszURL), bufferSize-strlen(pszURL),  "&TYPENAME=%s", pszTypename);
+
+  /* -------------------------------------------------------------------- */
+  /*      If the filter parameter is given in the wfs_filter metadata,    */
+  /*      we use it and do not send the BBOX paramter as they are         */
+  /*      mutually exclusive.                                             */
+  /* -------------------------------------------------------------------- */
+  if (psParams->pszFilter) {
+    snprintf(pszURL + strlen(pszURL), bufferSize-strlen(pszURL), "&FILTER=%s",
+             msEncodeUrl(psParams->pszFilter));
+  } else
+    snprintf(pszURL + strlen(pszURL), bufferSize-strlen(pszURL),
+             "&BBOX=%.15g,%.15g,%.15g,%.15g",
+             bbox->minx, bbox->miny, bbox->maxx, bbox->maxy);
+
+  if (psParams->nMaxFeatures > 0)
+    snprintf(pszURL + strlen(pszURL), bufferSize-strlen(pszURL),
+             "&MAXFEATURES=%d", psParams->nMaxFeatures);
+
+  return pszURL;
 
 }
 
@@ -448,13 +434,12 @@ static char *msBuildWFSLayerGetURL(mapObj *map, layerObj *lp, rectObj *bbox,
  *                          msWFSLayerInfo
  *
  **********************************************************************/
-typedef struct ms_wfs_layer_info_t
-{
-    char        *pszGMLFilename;
-    rectObj     rect;                     /* set by WhichShapes */
-    char        *pszGetUrl;
-    int         nStatus;           /* HTTP status */
-    int         bLayerHasValidGML;  /* False until msWFSLayerWhichShapes() is called and determines the result GML is valid with features*/
+typedef struct ms_wfs_layer_info_t {
+  char        *pszGMLFilename;
+  rectObj     rect;                     /* set by WhichShapes */
+  char        *pszGetUrl;
+  int         nStatus;           /* HTTP status */
+  int         bLayerHasValidGML;  /* False until msWFSLayerWhichShapes() is called and determines the result GML is valid with features*/
 } msWFSLayerInfo;
 
 
@@ -464,18 +449,18 @@ typedef struct ms_wfs_layer_info_t
  **********************************************************************/
 static msWFSLayerInfo *msAllocWFSLayerInfo(void)
 {
-    msWFSLayerInfo *psInfo;
+  msWFSLayerInfo *psInfo;
 
-    psInfo = (msWFSLayerInfo*)calloc(1,sizeof(msWFSLayerInfo));
-    MS_CHECK_ALLOC(psInfo, sizeof(msWFSLayerInfo), NULL);
+  psInfo = (msWFSLayerInfo*)calloc(1,sizeof(msWFSLayerInfo));
+  MS_CHECK_ALLOC(psInfo, sizeof(msWFSLayerInfo), NULL);
 
-    psInfo->pszGMLFilename = NULL;
-    psInfo->rect.minx = psInfo->rect.maxx = 0;
-    psInfo->rect.miny = psInfo->rect.maxy = 0;
-    psInfo->pszGetUrl = NULL;
-    psInfo->nStatus = 0;
+  psInfo->pszGMLFilename = NULL;
+  psInfo->rect.minx = psInfo->rect.maxx = 0;
+  psInfo->rect.miny = psInfo->rect.maxy = 0;
+  psInfo->pszGetUrl = NULL;
+  psInfo->nStatus = 0;
 
-    return psInfo;
+  return psInfo;
 }
 
 /**********************************************************************
@@ -484,15 +469,14 @@ static msWFSLayerInfo *msAllocWFSLayerInfo(void)
  **********************************************************************/
 static void msFreeWFSLayerInfo(msWFSLayerInfo *psInfo)
 {
-    if (psInfo)
-    {
-        if (psInfo->pszGMLFilename)
-            free(psInfo->pszGMLFilename);
-        if (psInfo->pszGetUrl)
-            free(psInfo->pszGetUrl);
-
-        free(psInfo);
-    }
+  if (psInfo) {
+    if (psInfo->pszGMLFilename)
+      free(psInfo->pszGMLFilename);
+    if (psInfo->pszGetUrl)
+      free(psInfo->pszGetUrl);
+
+    free(psInfo);
+  }
 }
 
 #endif /* USE_WFS_LYR */
@@ -507,200 +491,174 @@ static void msFreeWFSLayerInfo(msWFSLayerInfo *psInfo)
  **********************************************************************/
 
 int msPrepareWFSLayerRequest(int nLayerId, mapObj *map, layerObj *lp,
-                             httpRequestObj *pasReqInfo, int *numRequests) 
+                             httpRequestObj *pasReqInfo, int *numRequests)
 {
 #ifdef USE_WFS_LYR
-    char *pszURL = NULL;
-    const char *pszTmp;
-    rectObj bbox;
-    int nTimeout;
-    int nStatus = MS_SUCCESS;
-    msWFSLayerInfo *psInfo = NULL;
-    int bPostRequest = 0;
-    wfsParamsObj *psParams = NULL;
-    char *pszHTTPCookieData = NULL;
-    
-
-    if (lp->connectiontype != MS_WFS || lp->connection == NULL)
+  char *pszURL = NULL;
+  const char *pszTmp;
+  rectObj bbox;
+  int nTimeout;
+  int nStatus = MS_SUCCESS;
+  msWFSLayerInfo *psInfo = NULL;
+  int bPostRequest = 0;
+  wfsParamsObj *psParams = NULL;
+  char *pszHTTPCookieData = NULL;
+
+
+  if (lp->connectiontype != MS_WFS || lp->connection == NULL)
+    return MS_FAILURE;
+
+  /* ------------------------------------------------------------------
+   * Build a params object that will be used by to build the request,
+    this will also set layer projection and compute BBOX in that projection.
+   * ------------------------------------------------------------------ */
+  psParams = msBuildRequestParams(map, lp, &bbox);
+  if (!psParams)
+    return MS_FAILURE;
+
+  /* -------------------------------------------------------------------- */
+  /*      Depending on the metadata wfs_request_method, build a Get or    */
+  /*      a Post URL.                                                     */
+  /*    If it is a Get request the URL would contain all the parameters in*/
+  /*      the string;                                                     */
+  /*      If it is a Post request, the URL will only contain the          */
+  /*      connection string comming from the layer.                       */
+  /* -------------------------------------------------------------------- */
+  if ((pszTmp = msOWSLookupMetadata(&(lp->metadata),
+                                    "FO", "request_method")) != NULL) {
+    if (strncmp(pszTmp, "GET", 3) ==0) {
+      pszURL = msBuildWFSLayerGetURL(map, lp, &bbox, psParams);
+      if (!pszURL) {
+        /* an error was already reported. */
         return MS_FAILURE;
-
-/* ------------------------------------------------------------------
- * Build a params object that will be used by to build the request, 
-  this will also set layer projection and compute BBOX in that projection.
- * ------------------------------------------------------------------ */
-    psParams = msBuildRequestParams(map, lp, &bbox);
-    if (!psParams)
-      return MS_FAILURE;
-
-/* -------------------------------------------------------------------- */
-/*      Depending on the metadata wfs_request_method, build a Get or    */
-/*      a Post URL.                                                     */
-/*    If it is a Get request the URL would contain all the parameters in*/
-/*      the string;                                                     */
-/*      If it is a Post request, the URL will only contain the          */
-/*      connection string comming from the layer.                       */
-/* -------------------------------------------------------------------- */
-    if ((pszTmp = msOWSLookupMetadata(&(lp->metadata), 
-                                      "FO", "request_method")) != NULL)
-    {
-        if (strncmp(pszTmp, "GET", 3) ==0)
-        {
-            pszURL = msBuildWFSLayerGetURL(map, lp, &bbox, psParams);
-            if (!pszURL)
-            {
-              /* an error was already reported. */
-                return MS_FAILURE;
-            }
-        }
-    }
-    /* else it is a post request and just get the connection string */
-    if (!pszURL)
-    {
-        bPostRequest = 1;
-        pszURL = msStrdup(lp->connection);
-    }
-
-    
-/* ------------------------------------------------------------------
- * check to see if a the metadata wfs_connectiontimeout is set. If it is 
- * the case we will use it, else we use the default which is 30 seconds.
- * First check the metadata in the layer object and then in the map object.
- * ------------------------------------------------------------------ */
-    nTimeout = 30;  /* Default is 30 seconds  */
-    if ((pszTmp = msOWSLookupMetadata(&(lp->metadata), 
-                                      "FO", "connectiontimeout")) != NULL)
-    {
-        nTimeout = atoi(pszTmp);
-    }
-    else if ((pszTmp = msOWSLookupMetadata(&(map->web.metadata), 
-                                           "FO", "connectiontimeout")) != NULL)
-    {
-        nTimeout = atoi(pszTmp);
-    }
-
-/*------------------------------------------------------------------
- * Check to see if there's a HTTP Cookie to forward
- * If Cookie differ between the two connection, it's NOT OK to merge
- * the connection
- * ------------------------------------------------------------------ */
-    if ((pszTmp = msOWSLookupMetadata(&(lp->metadata), 
-                                      "MO", "http_cookie")) != NULL)
-    {
-        if(strcasecmp(pszTmp, "forward") == 0)
-        {
-            pszTmp= msLookupHashTable(&(map->web.metadata),"http_cookie_data");
-            if(pszTmp != NULL)
-            {
-                pszHTTPCookieData = msStrdup(pszTmp);
-            }
-        }
-        else
-        {
-            pszHTTPCookieData = msStrdup(pszTmp);
-        }
+      }
     }
-    else if ((pszTmp = msOWSLookupMetadata(&(map->web.metadata), 
-                                           "MO", "http_cookie")) != NULL)
-    {
-        if(strcasecmp(pszTmp, "forward") == 0)
-        {
-            pszTmp= msLookupHashTable(&(map->web.metadata),"http_cookie_data");
-            if(pszTmp != NULL)
-            {
-                pszHTTPCookieData = msStrdup(pszTmp);
-            }
-        }
-        else
-        {
-            pszHTTPCookieData = msStrdup(pszTmp);
-        }
+  }
+  /* else it is a post request and just get the connection string */
+  if (!pszURL) {
+    bPostRequest = 1;
+    pszURL = msStrdup(lp->connection);
+  }
+
+
+  /* ------------------------------------------------------------------
+   * check to see if a the metadata wfs_connectiontimeout is set. If it is
+   * the case we will use it, else we use the default which is 30 seconds.
+   * First check the metadata in the layer object and then in the map object.
+   * ------------------------------------------------------------------ */
+  nTimeout = 30;  /* Default is 30 seconds  */
+  if ((pszTmp = msOWSLookupMetadata(&(lp->metadata),
+                                    "FO", "connectiontimeout")) != NULL) {
+    nTimeout = atoi(pszTmp);
+  } else if ((pszTmp = msOWSLookupMetadata(&(map->web.metadata),
+                       "FO", "connectiontimeout")) != NULL) {
+    nTimeout = atoi(pszTmp);
+  }
+
+  /*------------------------------------------------------------------
+   * Check to see if there's a HTTP Cookie to forward
+   * If Cookie differ between the two connection, it's NOT OK to merge
+   * the connection
+   * ------------------------------------------------------------------ */
+  if ((pszTmp = msOWSLookupMetadata(&(lp->metadata),
+                                    "MO", "http_cookie")) != NULL) {
+    if(strcasecmp(pszTmp, "forward") == 0) {
+      pszTmp= msLookupHashTable(&(map->web.metadata),"http_cookie_data");
+      if(pszTmp != NULL) {
+        pszHTTPCookieData = msStrdup(pszTmp);
+      }
+    } else {
+      pszHTTPCookieData = msStrdup(pszTmp);
     }
-
-/* ------------------------------------------------------------------
- * If nLayerId == -1 then we need to figure it
- * ------------------------------------------------------------------ */
-    if (nLayerId == -1)
-    {
-        int iLayer;
-        for(iLayer=0; iLayer < map->numlayers; iLayer++)
-        {
-            if (GET_LAYER(map, iLayer) == lp)
-            {
-                nLayerId = iLayer;
-                break;
-            }
-        }
+  } else if ((pszTmp = msOWSLookupMetadata(&(map->web.metadata),
+                       "MO", "http_cookie")) != NULL) {
+    if(strcasecmp(pszTmp, "forward") == 0) {
+      pszTmp= msLookupHashTable(&(map->web.metadata),"http_cookie_data");
+      if(pszTmp != NULL) {
+        pszHTTPCookieData = msStrdup(pszTmp);
+      }
+    } else {
+      pszHTTPCookieData = msStrdup(pszTmp);
     }
-
-/* ------------------------------------------------------------------
- * Add a request to the array (already preallocated)
- * ------------------------------------------------------------------ */
-    pasReqInfo[(*numRequests)].nLayerId = nLayerId;
-    pasReqInfo[(*numRequests)].pszGetUrl = pszURL;
-
-    if (bPostRequest)
-    {
-        pasReqInfo[(*numRequests)].pszPostRequest = 
-            msBuildWFSLayerPostRequest(map, lp, &bbox, psParams);
-        pasReqInfo[(*numRequests)].pszPostContentType =
-            msStrdup("text/xml");
+  }
+
+  /* ------------------------------------------------------------------
+   * If nLayerId == -1 then we need to figure it
+   * ------------------------------------------------------------------ */
+  if (nLayerId == -1) {
+    int iLayer;
+    for(iLayer=0; iLayer < map->numlayers; iLayer++) {
+      if (GET_LAYER(map, iLayer) == lp) {
+        nLayerId = iLayer;
+        break;
+      }
     }
+  }
+
+  /* ------------------------------------------------------------------
+   * Add a request to the array (already preallocated)
+   * ------------------------------------------------------------------ */
+  pasReqInfo[(*numRequests)].nLayerId = nLayerId;
+  pasReqInfo[(*numRequests)].pszGetUrl = pszURL;
+
+  if (bPostRequest) {
+    pasReqInfo[(*numRequests)].pszPostRequest =
+      msBuildWFSLayerPostRequest(map, lp, &bbox, psParams);
+    pasReqInfo[(*numRequests)].pszPostContentType =
+      msStrdup("text/xml");
+  }
+
+
+  /* We'll store the remote server's response to a tmp file. */
+  pasReqInfo[(*numRequests)].pszOutputFile = msTmpFile(map, map->mappath, NULL, "tmp.gml");
+
+  /* TODO: Implement Caching of GML responses. There was an older caching
+   * method, but it suffered from a race condition. See #3137.
+   */
+
+  pasReqInfo[(*numRequests)].pszHTTPCookieData = pszHTTPCookieData;
+  pszHTTPCookieData = NULL;
+  pasReqInfo[(*numRequests)].nStatus = 0;
+  pasReqInfo[(*numRequests)].nTimeout = nTimeout;
+  pasReqInfo[(*numRequests)].bbox = bbox;
+  pasReqInfo[(*numRequests)].debug = lp->debug;
+
+  /* ------------------------------------------------------------------
+   * Pre-Open the layer now, (i.e. alloc and fill msWFSLayerInfo inside
+   * layer obj).  Layer will be ready for use when the main mapserver
+   * code calls msLayerOpen().
+   * ------------------------------------------------------------------ */
+  if (lp->wfslayerinfo != NULL) {
+    psInfo =(msWFSLayerInfo*)(lp->wfslayerinfo);
+  } else {
+    lp->wfslayerinfo = psInfo = msAllocWFSLayerInfo();
+  }
 
+  if (psInfo->pszGMLFilename)
+    free(psInfo->pszGMLFilename);
+  psInfo->pszGMLFilename=msStrdup(pasReqInfo[(*numRequests)].pszOutputFile);
 
-    /* We'll store the remote server's response to a tmp file. */
-    pasReqInfo[(*numRequests)].pszOutputFile = msTmpFile(map, map->mappath, NULL, "tmp.gml");
-
-    /* TODO: Implement Caching of GML responses. There was an older caching 
-     * method, but it suffered from a race condition. See #3137.
-     */ 
-
-    pasReqInfo[(*numRequests)].pszHTTPCookieData = pszHTTPCookieData;
-    pszHTTPCookieData = NULL;
-    pasReqInfo[(*numRequests)].nStatus = 0;
-    pasReqInfo[(*numRequests)].nTimeout = nTimeout;
-    pasReqInfo[(*numRequests)].bbox = bbox;
-    pasReqInfo[(*numRequests)].debug = lp->debug;
-
-/* ------------------------------------------------------------------
- * Pre-Open the layer now, (i.e. alloc and fill msWFSLayerInfo inside 
- * layer obj).  Layer will be ready for use when the main mapserver 
- * code calls msLayerOpen().
- * ------------------------------------------------------------------ */
-    if (lp->wfslayerinfo != NULL)
-    {
-        psInfo =(msWFSLayerInfo*)(lp->wfslayerinfo);
-    }
-    else
-    {
-        lp->wfslayerinfo = psInfo = msAllocWFSLayerInfo();
-    }
+  psInfo->rect = pasReqInfo[(*numRequests)].bbox;
 
-    if (psInfo->pszGMLFilename) 
-        free(psInfo->pszGMLFilename);
-    psInfo->pszGMLFilename=msStrdup(pasReqInfo[(*numRequests)].pszOutputFile);
- 
-    psInfo->rect = pasReqInfo[(*numRequests)].bbox;
+  if (psInfo->pszGetUrl)
+    free(psInfo->pszGetUrl);
+  psInfo->pszGetUrl = msStrdup(pasReqInfo[(*numRequests)].pszGetUrl);
 
-    if (psInfo->pszGetUrl) 
-        free(psInfo->pszGetUrl);
-    psInfo->pszGetUrl = msStrdup(pasReqInfo[(*numRequests)].pszGetUrl);
+  psInfo->nStatus = 0;
 
-    psInfo->nStatus = 0;
+  (*numRequests)++;
 
-    (*numRequests)++;
-
-    if (psParams)
-    {
-        msWFSFreeParamsObj(psParams);
-        psParams = NULL;
-    }
-    return nStatus;
+  if (psParams) {
+    msWFSFreeParamsObj(psParams);
+    psParams = NULL;
+  }
+  return nStatus;
 
 #else
-/* ------------------------------------------------------------------
- * WFS CONNECTION Support not included...
- * ------------------------------------------------------------------ */
-  msSetError(MS_WFSCONNERR, "WFS CLIENT CONNECTION support is not available.", 
+  /* ------------------------------------------------------------------
+   * WFS CONNECTION Support not included...
+   * ------------------------------------------------------------------ */
+  msSetError(MS_WFSCONNERR, "WFS CLIENT CONNECTION support is not available.",
              "msPrepareWFSLayerRequest");
   return(MS_FAILURE);
 
@@ -719,22 +677,21 @@ int msPrepareWFSLayerRequest(int nLayerId, mapObj *map, layerObj *lp,
 void msWFSUpdateRequestInfo(layerObj *lp, httpRequestObj *pasReqInfo)
 {
 #ifdef USE_WFS_LYR
-    if (lp->wfslayerinfo)
-    {
-        msWFSLayerInfo *psInfo = NULL;
+  if (lp->wfslayerinfo) {
+    msWFSLayerInfo *psInfo = NULL;
 
-        psInfo =(msWFSLayerInfo*)(lp->wfslayerinfo);
+    psInfo =(msWFSLayerInfo*)(lp->wfslayerinfo);
 
-        /* Copy request results infos to msWFSLayerInfo struct */
-        /* For now there is only nStatus, but we should eventually add */
-        /* mime type and WFS exceptions information. */
-        psInfo->nStatus = pasReqInfo->nStatus;
-    }
+    /* Copy request results infos to msWFSLayerInfo struct */
+    /* For now there is only nStatus, but we should eventually add */
+    /* mime type and WFS exceptions information. */
+    psInfo->nStatus = pasReqInfo->nStatus;
+  }
 #else
-/* ------------------------------------------------------------------
- * WFS CONNECTION Support not included...
- * ------------------------------------------------------------------ */
-  msSetError(MS_WFSCONNERR, "WFS CLIENT CONNECTION support is not available.", 
+  /* ------------------------------------------------------------------
+   * WFS CONNECTION Support not included...
+   * ------------------------------------------------------------------ */
+  msSetError(MS_WFSCONNERR, "WFS CLIENT CONNECTION support is not available.",
              "msWFSUpdateRequestInfo()");
 #endif /* USE_WFS_LYR */
 }
@@ -748,94 +705,85 @@ void msWFSUpdateRequestInfo(layerObj *lp, httpRequestObj *pasReqInfo)
  *
  **********************************************************************/
 
-int msWFSLayerOpen(layerObj *lp, 
-                   const char *pszGMLFilename, rectObj *defaultBBOX) 
+int msWFSLayerOpen(layerObj *lp,
+                   const char *pszGMLFilename, rectObj *defaultBBOX)
 {
 #ifdef USE_WFS_LYR
-    int status = MS_SUCCESS;
-    msWFSLayerInfo *psInfo = NULL;
-    
-    if ( msCheckParentPointer(lp->map,"map")==MS_FAILURE )
-		return MS_FAILURE;
-
-    if (lp->wfslayerinfo != NULL)
-    {
-        psInfo =(msWFSLayerInfo*)lp->wfslayerinfo;
-
-        /* Layer already opened.  If explicit filename requested then check */
-        /* that file was already opened with the same filename. */
-        /* If no explicit filename requested then we'll try to reuse the */
-        /* previously opened layer... this will happen in a msDrawMap() call. */
-        if (pszGMLFilename == NULL ||
-            (psInfo->pszGMLFilename && pszGMLFilename && 
-             strcmp(psInfo->pszGMLFilename, pszGMLFilename) == 0) )
-        {
-            if (lp->layerinfo == NULL)
-            {
-	      if (msWFSLayerWhichShapes(lp, psInfo->rect, MS_FALSE) == MS_FAILURE) /* no access to context (draw vs. query) here, although I doubt it matters... */
-                  return MS_FAILURE;
-            }
-            return MS_SUCCESS;  /* Nothing to do... layer is already opened */
-        }
-        else
-        {
-            /* Hmmm... should we produce a fatal error? */
-            /* For now we'll just close the layer and reopen it. */
-            if (lp->debug)
-                msDebug("msWFSLayerOpen(): Layer already opened (%s)\n",
-                        lp->name?lp->name:"(null)" );
-            msWFSLayerClose(lp);
-        }
-    }
+  int status = MS_SUCCESS;
+  msWFSLayerInfo *psInfo = NULL;
 
-/* ------------------------------------------------------------------
- * Alloc and fill msWFSLayerInfo inside layer obj
- * ------------------------------------------------------------------ */
-    lp->wfslayerinfo = psInfo = msAllocWFSLayerInfo();
+  if ( msCheckParentPointer(lp->map,"map")==MS_FAILURE )
+    return MS_FAILURE;
 
-    if (pszGMLFilename)
-        psInfo->pszGMLFilename = msStrdup(pszGMLFilename);
-    else
-    {
-        psInfo->pszGMLFilename = msTmpFile(lp->map, 
-                                           lp->map->mappath,
-                                           NULL, 
-                                           "tmp.gml");
-    }
+  if (lp->wfslayerinfo != NULL) {
+    psInfo =(msWFSLayerInfo*)lp->wfslayerinfo;
 
-    if (defaultBBOX)
-    {
-        /* __TODO__ If new bbox differs from current one then we should */
-        /* invalidate current GML file in cache */
-        psInfo->rect = *defaultBBOX;
-    }
-    else
-    {
-        /* Use map bbox by default */
-        psInfo->rect = lp->map->extent;
+    /* Layer already opened.  If explicit filename requested then check */
+    /* that file was already opened with the same filename. */
+    /* If no explicit filename requested then we'll try to reuse the */
+    /* previously opened layer... this will happen in a msDrawMap() call. */
+    if (pszGMLFilename == NULL ||
+        (psInfo->pszGMLFilename && pszGMLFilename &&
+         strcmp(psInfo->pszGMLFilename, pszGMLFilename) == 0) ) {
+      if (lp->layerinfo == NULL) {
+        if (msWFSLayerWhichShapes(lp, psInfo->rect, MS_FALSE) == MS_FAILURE) /* no access to context (draw vs. query) here, although I doubt it matters... */
+          return MS_FAILURE;
+      }
+      return MS_SUCCESS;  /* Nothing to do... layer is already opened */
+    } else {
+      /* Hmmm... should we produce a fatal error? */
+      /* For now we'll just close the layer and reopen it. */
+      if (lp->debug)
+        msDebug("msWFSLayerOpen(): Layer already opened (%s)\n",
+                lp->name?lp->name:"(null)" );
+      msWFSLayerClose(lp);
     }
-
-    /* We will call whichshapes() now and force downloading layer right */
-    /* away.  This saves from having to call DescribeFeatureType and */
-    /* parsing the response (being lazy I guess) and anyway given the */
-    /* way we work with layers right now the bbox is unlikely to change */
-    /* between now and the time whichshapes() would have been called by */
-    /* the MapServer core. */
+  }
+
+  /* ------------------------------------------------------------------
+   * Alloc and fill msWFSLayerInfo inside layer obj
+   * ------------------------------------------------------------------ */
+  lp->wfslayerinfo = psInfo = msAllocWFSLayerInfo();
+
+  if (pszGMLFilename)
+    psInfo->pszGMLFilename = msStrdup(pszGMLFilename);
+  else {
+    psInfo->pszGMLFilename = msTmpFile(lp->map,
+                                       lp->map->mappath,
+                                       NULL,
+                                       "tmp.gml");
+  }
+
+  if (defaultBBOX) {
+    /* __TODO__ If new bbox differs from current one then we should */
+    /* invalidate current GML file in cache */
+    psInfo->rect = *defaultBBOX;
+  } else {
+    /* Use map bbox by default */
+    psInfo->rect = lp->map->extent;
+  }
+
+  /* We will call whichshapes() now and force downloading layer right */
+  /* away.  This saves from having to call DescribeFeatureType and */
+  /* parsing the response (being lazy I guess) and anyway given the */
+  /* way we work with layers right now the bbox is unlikely to change */
+  /* between now and the time whichshapes() would have been called by */
+  /* the MapServer core. */
 #ifdef USE_PROJ
-    if((lp->map->projection.numargs > 0) && (lp->projection.numargs > 0))
-        msProjectRect(&lp->map->projection, &lp->projection, &psInfo->rect); /* project the searchrect to source coords */
+  if((lp->map->projection.numargs > 0) && (lp->projection.numargs > 0))
+    msProjectRect(&lp->map->projection, &lp->projection, &psInfo->rect); /* project the searchrect to source coords */
 #endif
 
-    if (msWFSLayerWhichShapes(lp, psInfo->rect, MS_FALSE) == MS_FAILURE)  /* no access to context (draw vs. query) here, although I doubt it matters... */
-        status = MS_FAILURE;
-    
+  if (msWFSLayerWhichShapes(lp, psInfo->rect, MS_FALSE) == MS_FAILURE)  /* no access to context (draw vs. query) here, although I doubt it matters... */
+    status = MS_FAILURE;
 
-    return status;
+
+  return status;
 #else
-/* ------------------------------------------------------------------
- * WFS CONNECTION Support not included...
- * ------------------------------------------------------------------ */
-  msSetError(MS_WFSCONNERR, "WFS CLIENT CONNECTION support is not available.", 
+  /* ------------------------------------------------------------------
+   * WFS CONNECTION Support not included...
+   * ------------------------------------------------------------------ */
+  msSetError(MS_WFSCONNERR, "WFS CLIENT CONNECTION support is not available.",
              "msWFSLayerOpen()");
   return(MS_FAILURE);
 
@@ -847,10 +795,10 @@ int msWFSLayerOpen(layerObj *lp,
  *
  * Overloaded version of msWFSLayerOpen for virtual table architecture
  **********************************************************************/
-int 
+int
 msWFSLayerOpenVT(layerObj *lp)
 {
-	return msWFSLayerOpen(lp, NULL, NULL);
+  return msWFSLayerOpen(lp, NULL, NULL);
 }
 
 /**********************************************************************
@@ -860,18 +808,18 @@ msWFSLayerOpenVT(layerObj *lp)
  *
  **********************************************************************/
 
-int msWFSLayerIsOpen(layerObj *lp) 
+int msWFSLayerIsOpen(layerObj *lp)
 {
 #ifdef USE_WFS_LYR
-    if (lp->wfslayerinfo != NULL)
-        return MS_TRUE;
+  if (lp->wfslayerinfo != NULL)
+    return MS_TRUE;
 
-    return MS_FALSE;
+  return MS_FALSE;
 #else
-/* ------------------------------------------------------------------
- * WFS CONNECTION Support not included...
- * ------------------------------------------------------------------ */
-  msSetError(MS_WFSCONNERR, "WFS CLIENT CONNECTION support is not available.", 
+  /* ------------------------------------------------------------------
+   * WFS CONNECTION Support not included...
+   * ------------------------------------------------------------------ */
+  msSetError(MS_WFSCONNERR, "WFS CLIENT CONNECTION support is not available.",
              "msWFSLayerIsOpen()");
   return(MS_FALSE);
 
@@ -885,11 +833,11 @@ int msWFSLayerIsOpen(layerObj *lp)
 
 int msWFSLayerInitItemInfo(layerObj *layer)
 {
-    /* Nothing to do here.  OGR will do its own initialization when it */
-    /* opens the actual file. */
-    /* Note that we didn't implement our own msWFSLayerFreeItemInfo() */
-    /* so that the OGR one gets called. */
-    return MS_SUCCESS;
+  /* Nothing to do here.  OGR will do its own initialization when it */
+  /* opens the actual file. */
+  /* Note that we didn't implement our own msWFSLayerFreeItemInfo() */
+  /* so that the OGR one gets called. */
+  return MS_SUCCESS;
 }
 
 /**********************************************************************
@@ -899,30 +847,28 @@ int msWFSLayerInitItemInfo(layerObj *layer)
 int msWFSLayerGetShape(layerObj *layer, shapeObj *shape, resultObj *record)
 {
 #ifdef USE_WFS_LYR
-    msWFSLayerInfo* psInfo = NULL;
-
-    if(layer != NULL && layer->wfslayerinfo != NULL)
-    	psInfo = (msWFSLayerInfo*)layer->wfslayerinfo;
-    else
-    {
-      msSetError(MS_WFSERR, "Layer is not opened.", "msWFSLayerGetShape()");
-      return MS_FAILURE;
-    }
-
-    if(psInfo->bLayerHasValidGML)
-      return msOGRLayerGetShape(layer, shape, record);
-    else
-    {
-          /* Layer is successful, but there is no data to process */
-        msFreeShape(shape);
-        shape->type = MS_SHAPE_NULL;
-        return MS_FAILURE;
-    }
+  msWFSLayerInfo* psInfo = NULL;
+
+  if(layer != NULL && layer->wfslayerinfo != NULL)
+    psInfo = (msWFSLayerInfo*)layer->wfslayerinfo;
+  else {
+    msSetError(MS_WFSERR, "Layer is not opened.", "msWFSLayerGetShape()");
+    return MS_FAILURE;
+  }
+
+  if(psInfo->bLayerHasValidGML)
+    return msOGRLayerGetShape(layer, shape, record);
+  else {
+    /* Layer is successful, but there is no data to process */
+    msFreeShape(shape);
+    shape->type = MS_SHAPE_NULL;
+    return MS_FAILURE;
+  }
 #else
-/* ------------------------------------------------------------------
- * WFS CONNECTION Support not included...
- * ------------------------------------------------------------------ */
-  msSetError(MS_WFSCONNERR, "WFS CLIENT CONNECTION support is not available.", 
+  /* ------------------------------------------------------------------
+   * WFS CONNECTION Support not included...
+   * ------------------------------------------------------------------ */
+  msSetError(MS_WFSCONNERR, "WFS CLIENT CONNECTION support is not available.",
              "msWFSLayerGetShape()");
   return(MS_FAILURE);
 #endif /* USE_WFS_LYR */
@@ -936,30 +882,28 @@ int msWFSLayerGetShape(layerObj *layer, shapeObj *shape, resultObj *record)
 int msWFSLayerNextShape(layerObj *layer, shapeObj *shape)
 {
 #ifdef USE_WFS_LYR
-    msWFSLayerInfo* psInfo = NULL;
-
-    if(layer != NULL && layer->wfslayerinfo != NULL)
-      psInfo = (msWFSLayerInfo*)layer->wfslayerinfo;
-    else
-    {
-	msSetError(MS_WFSERR, "Layer is not opened.", "msWFSLayerNextShape()");
-	return MS_FAILURE;
-    }
-
-    if(psInfo->bLayerHasValidGML)
-      return msOGRLayerNextShape(layer, shape);
-    else
-    {
-        /* Layer is successful, but there is no data to process */
-        msFreeShape(shape);
-        shape->type = MS_SHAPE_NULL;
-        return MS_FAILURE;
-    }
+  msWFSLayerInfo* psInfo = NULL;
+
+  if(layer != NULL && layer->wfslayerinfo != NULL)
+    psInfo = (msWFSLayerInfo*)layer->wfslayerinfo;
+  else {
+    msSetError(MS_WFSERR, "Layer is not opened.", "msWFSLayerNextShape()");
+    return MS_FAILURE;
+  }
+
+  if(psInfo->bLayerHasValidGML)
+    return msOGRLayerNextShape(layer, shape);
+  else {
+    /* Layer is successful, but there is no data to process */
+    msFreeShape(shape);
+    shape->type = MS_SHAPE_NULL;
+    return MS_FAILURE;
+  }
 #else
-/* ------------------------------------------------------------------
- * WFS CONNECTION Support not included...
- * ------------------------------------------------------------------ */
-  msSetError(MS_WFSCONNERR, "WFS CLIENT CONNECTION support is not available.", 
+  /* ------------------------------------------------------------------
+   * WFS CONNECTION Support not included...
+   * ------------------------------------------------------------------ */
+  msSetError(MS_WFSCONNERR, "WFS CLIENT CONNECTION support is not available.",
              "msWFSLayerNextShape()");
   return(MS_FAILURE);
 #endif /* USE_WFS_LYR */
@@ -970,32 +914,30 @@ int msWFSLayerNextShape(layerObj *layer, shapeObj *shape)
  *                          msWFSLayerGetExtent()
  *
  **********************************************************************/
-int msWFSLayerGetExtent(layerObj *layer, rectObj *extent) 
+int msWFSLayerGetExtent(layerObj *layer, rectObj *extent)
 {
 #ifdef USE_WFS_LYR
-    msWFSLayerInfo* psInfo = NULL;
-
-    if(layer != NULL && layer->wfslayerinfo != NULL)
-      psInfo = (msWFSLayerInfo*)layer->wfslayerinfo;
-    else
-    {
-	msSetError(MS_WFSERR, "Layer is not opened.", "msWFSLayerGetExtent()");
-	return MS_FAILURE;
-    }
-
-    if(psInfo->bLayerHasValidGML)
-      return msOGRLayerGetExtent(layer, extent);
-    else
-    {
-        /* Layer is successful, but there is no data to process */
-        msSetError(MS_WFSERR, "Unable to get extents for this layer.", "msWFSLayerGetExtent()");
-        return MS_FAILURE;
-    }
+  msWFSLayerInfo* psInfo = NULL;
+
+  if(layer != NULL && layer->wfslayerinfo != NULL)
+    psInfo = (msWFSLayerInfo*)layer->wfslayerinfo;
+  else {
+    msSetError(MS_WFSERR, "Layer is not opened.", "msWFSLayerGetExtent()");
+    return MS_FAILURE;
+  }
+
+  if(psInfo->bLayerHasValidGML)
+    return msOGRLayerGetExtent(layer, extent);
+  else {
+    /* Layer is successful, but there is no data to process */
+    msSetError(MS_WFSERR, "Unable to get extents for this layer.", "msWFSLayerGetExtent()");
+    return MS_FAILURE;
+  }
 #else
-/* ------------------------------------------------------------------
- * WFS CONNECTION Support not included...
- * ------------------------------------------------------------------ */
-  msSetError(MS_WFSCONNERR, "WFS CLIENT CONNECTION support is not available.", 
+  /* ------------------------------------------------------------------
+   * WFS CONNECTION Support not included...
+   * ------------------------------------------------------------------ */
+  msSetError(MS_WFSCONNERR, "WFS CLIENT CONNECTION support is not available.",
              "msWFSLayerGetExtent()");
   return(MS_FAILURE);
 #endif /* USE_WFS_LYR */
@@ -1010,35 +952,33 @@ int msWFSLayerGetExtent(layerObj *layer, rectObj *extent)
 int msWFSLayerGetItems(layerObj *layer)
 {
 #ifdef USE_WFS_LYR
-    /* For now this method simply lets OGR parse the GML and figure the  */
-    /* schema itself. */
-    /* It could also be implemented to call DescribeFeatureType for */
-    /* this layer, but we don't need to do it so why waste resources? */
-
-    msWFSLayerInfo* psInfo = NULL;
-
-    if(layer != NULL && layer->wfslayerinfo != NULL)
-    	psInfo = (msWFSLayerInfo*)layer->wfslayerinfo;
-    else
-    {
-	msSetError(MS_WFSERR, "Layer is not opened.", "msWFSLayerGetItems()");
-	return MS_FAILURE;
-    }
-
-    if(psInfo->bLayerHasValidGML)
-        return msOGRLayerGetItems(layer);
-    else
-    {
-        /* Layer is successful, but there is no data to process */
-        layer->numitems = 0;
-	layer->items = NULL;
-        return MS_SUCCESS;
-    }
+  /* For now this method simply lets OGR parse the GML and figure the  */
+  /* schema itself. */
+  /* It could also be implemented to call DescribeFeatureType for */
+  /* this layer, but we don't need to do it so why waste resources? */
+
+  msWFSLayerInfo* psInfo = NULL;
+
+  if(layer != NULL && layer->wfslayerinfo != NULL)
+    psInfo = (msWFSLayerInfo*)layer->wfslayerinfo;
+  else {
+    msSetError(MS_WFSERR, "Layer is not opened.", "msWFSLayerGetItems()");
+    return MS_FAILURE;
+  }
+
+  if(psInfo->bLayerHasValidGML)
+    return msOGRLayerGetItems(layer);
+  else {
+    /* Layer is successful, but there is no data to process */
+    layer->numitems = 0;
+    layer->items = NULL;
+    return MS_SUCCESS;
+  }
 #else
-/* ------------------------------------------------------------------
- * WFS CONNECTION Support not included...
- * ------------------------------------------------------------------ */
-  msSetError(MS_WFSCONNERR, "WFS CLIENT CONNECTION support is not available.", 
+  /* ------------------------------------------------------------------
+   * WFS CONNECTION Support not included...
+   * ------------------------------------------------------------------ */
+  msSetError(MS_WFSCONNERR, "WFS CLIENT CONNECTION support is not available.",
              "msWFSLayerGetItems()");
   return(MS_FAILURE);
 #endif /* USE_WFS_LYR */
@@ -1053,174 +993,161 @@ int msWFSLayerGetItems(layerObj *layer)
 int msWFSLayerWhichShapes(layerObj *lp, rectObj rect, int isQuery)
 {
 #ifdef USE_WFS_LYR
-    msWFSLayerInfo *psInfo;
-    int status = MS_SUCCESS;
-    const char *pszTmp;
-    FILE *fp;
-    
-    if ( msCheckParentPointer(lp->map,"map")==MS_FAILURE )
-		return MS_FAILURE;
-    
+  msWFSLayerInfo *psInfo;
+  int status = MS_SUCCESS;
+  const char *pszTmp;
+  FILE *fp;
 
-    psInfo =(msWFSLayerInfo*)lp->wfslayerinfo;
+  if ( msCheckParentPointer(lp->map,"map")==MS_FAILURE )
+    return MS_FAILURE;
 
-    if (psInfo == NULL)
-    {
-        msSetError(MS_WFSCONNERR, "Assertion failed: WFS layer not opened!!!", 
-                   "msWFSLayerWhichShapes()");
-        return(MS_FAILURE);
-    }
 
-/* ------------------------------------------------------------------
- * Check if layer overlaps current view window (using wfs_latlonboundingbox)
- * ------------------------------------------------------------------ */
-    if ((pszTmp = msOWSLookupMetadata(&(lp->metadata), 
-                                      "FO", "latlonboundingbox")) != NULL)
-    {
-        char **tokens;
-        int n;
-        rectObj ext;
-
-        tokens = msStringSplit(pszTmp, ' ', &n);
-        if (tokens==NULL || n != 4) {
-            msSetError(MS_WFSCONNERR, "Wrong number of values in 'wfs_latlonboundingbox' metadata.",
-                       "msWFSLayerWhichShapes()");
-            return MS_FAILURE;
-        }
+  psInfo =(msWFSLayerInfo*)lp->wfslayerinfo;
 
-        ext.minx = atof(tokens[0]);
-        ext.miny = atof(tokens[1]);
-        ext.maxx = atof(tokens[2]);
-        ext.maxy = atof(tokens[3]);
+  if (psInfo == NULL) {
+    msSetError(MS_WFSCONNERR, "Assertion failed: WFS layer not opened!!!",
+               "msWFSLayerWhichShapes()");
+    return(MS_FAILURE);
+  }
+
+  /* ------------------------------------------------------------------
+   * Check if layer overlaps current view window (using wfs_latlonboundingbox)
+   * ------------------------------------------------------------------ */
+  if ((pszTmp = msOWSLookupMetadata(&(lp->metadata),
+                                    "FO", "latlonboundingbox")) != NULL) {
+    char **tokens;
+    int n;
+    rectObj ext;
+
+    tokens = msStringSplit(pszTmp, ' ', &n);
+    if (tokens==NULL || n != 4) {
+      msSetError(MS_WFSCONNERR, "Wrong number of values in 'wfs_latlonboundingbox' metadata.",
+                 "msWFSLayerWhichShapes()");
+      return MS_FAILURE;
+    }
 
-        msFreeCharArray(tokens, n);
+    ext.minx = atof(tokens[0]);
+    ext.miny = atof(tokens[1]);
+    ext.maxx = atof(tokens[2]);
+    ext.maxy = atof(tokens[3]);
 
-        /* Reproject latlonboundingbox to the selected SRS for the layer and */
-        /* check if it overlaps the bbox that we calculated for the request */
+    msFreeCharArray(tokens, n);
 
-        msProjectRect(&(lp->map->latlon), &(lp->projection), &ext);
-        if (!msRectOverlap(&rect, &ext))
-        {
-            /* No overlap... nothing to do. If layer was never opened, go open it.*/
-            if (lp->layerinfo)
-              return MS_DONE;  /* No overlap. */
-        }
+    /* Reproject latlonboundingbox to the selected SRS for the layer and */
+    /* check if it overlaps the bbox that we calculated for the request */
+
+    msProjectRect(&(lp->map->latlon), &(lp->projection), &ext);
+    if (!msRectOverlap(&rect, &ext)) {
+      /* No overlap... nothing to do. If layer was never opened, go open it.*/
+      if (lp->layerinfo)
+        return MS_DONE;  /* No overlap. */
     }
+  }
 
 
- /* ------------------------------------------------------------------
-  * __TODO__ If new bbox differs from current one then we should
-  * invalidate current GML file in cache
-  * ------------------------------------------------------------------ */
-    psInfo->rect = rect;
+  /* ------------------------------------------------------------------
+   * __TODO__ If new bbox differs from current one then we should
+   * invalidate current GML file in cache
+   * ------------------------------------------------------------------ */
+  psInfo->rect = rect;
 
 
-/* ------------------------------------------------------------------
- * If file not downloaded yet then do it now.
- * ------------------------------------------------------------------ */
-    if (psInfo->nStatus == 0)
-    {
-        httpRequestObj asReqInfo[2];
-        int numReq = 0;
+  /* ------------------------------------------------------------------
+   * If file not downloaded yet then do it now.
+   * ------------------------------------------------------------------ */
+  if (psInfo->nStatus == 0) {
+    httpRequestObj asReqInfo[2];
+    int numReq = 0;
 
-        msHTTPInitRequestObj(asReqInfo, 2);
+    msHTTPInitRequestObj(asReqInfo, 2);
 
-        if ( msPrepareWFSLayerRequest(-1, lp->map, lp,
-                                      asReqInfo, &numReq) == MS_FAILURE  ||
-             msOWSExecuteRequests(asReqInfo, numReq, 
-                                  lp->map, MS_TRUE) == MS_FAILURE )
-        {
-            /* Delete tmp file... we don't want it to stick around. */
-            unlink(asReqInfo[0].pszOutputFile);
-            return MS_FAILURE;
-        }
+    if ( msPrepareWFSLayerRequest(-1, lp->map, lp,
+                                  asReqInfo, &numReq) == MS_FAILURE  ||
+         msOWSExecuteRequests(asReqInfo, numReq,
+                              lp->map, MS_TRUE) == MS_FAILURE ) {
+      /* Delete tmp file... we don't want it to stick around. */
+      unlink(asReqInfo[0].pszOutputFile);
+      return MS_FAILURE;
+    }
 
-        /* Cleanup */
-        msHTTPFreeRequestObj(asReqInfo, numReq);
+    /* Cleanup */
+    msHTTPFreeRequestObj(asReqInfo, numReq);
 
-    }
+  }
 
-    if ( !MS_HTTP_SUCCESS( psInfo->nStatus ) )
-    {
-        /* Delete tmp file... we don't want it to stick around. */
-        unlink(psInfo->pszGMLFilename);
+  if ( !MS_HTTP_SUCCESS( psInfo->nStatus ) ) {
+    /* Delete tmp file... we don't want it to stick around. */
+    unlink(psInfo->pszGMLFilename);
 
-        msSetError(MS_WFSCONNERR, 
-                   "Got HTTP status %d downloading WFS layer %s", 
-                   "msWFSLayerWhichShapes()",
-                   psInfo->nStatus, lp->name?lp->name:"(null)");
-        return(MS_FAILURE);
-    }
+    msSetError(MS_WFSCONNERR,
+               "Got HTTP status %d downloading WFS layer %s",
+               "msWFSLayerWhichShapes()",
+               psInfo->nStatus, lp->name?lp->name:"(null)");
+    return(MS_FAILURE);
+  }
 
-/* ------------------------------------------------------------------
- * Check that file is really GML... it could be an exception, or just junk.
- * ------------------------------------------------------------------ */
-    if ((fp = fopen(psInfo->pszGMLFilename, "r")) != NULL)
-    {
-        char szHeader[2000];
-        int  nBytes = 0;
-
-        nBytes = fread( szHeader, 1, sizeof(szHeader)-1, fp );
-        fclose(fp);
-
-        if (nBytes < 0)
-            nBytes = 0;
-        szHeader[nBytes] = '\0';
-
-        if ( nBytes == 0 )
-        {
-            msSetError(MS_WFSCONNERR, 
-                       "WFS request produced no oputput for layer %s.",
-                       "msWFSLayerWhichShapes()",
-                       lp->name?lp->name:"(null)");
-            return(MS_FAILURE);
+  /* ------------------------------------------------------------------
+   * Check that file is really GML... it could be an exception, or just junk.
+   * ------------------------------------------------------------------ */
+  if ((fp = fopen(psInfo->pszGMLFilename, "r")) != NULL) {
+    char szHeader[2000];
+    int  nBytes = 0;
+
+    nBytes = fread( szHeader, 1, sizeof(szHeader)-1, fp );
+    fclose(fp);
+
+    if (nBytes < 0)
+      nBytes = 0;
+    szHeader[nBytes] = '\0';
+
+    if ( nBytes == 0 ) {
+      msSetError(MS_WFSCONNERR,
+                 "WFS request produced no oputput for layer %s.",
+                 "msWFSLayerWhichShapes()",
+                 lp->name?lp->name:"(null)");
+      return(MS_FAILURE);
 
-        }
-        if ( strstr(szHeader, "<WFS_Exception>") ||
-             strstr(szHeader, "<ServiceExceptionReport>") )
-        {
-            msOWSProcessException(lp, psInfo->pszGMLFilename,
-                                  MS_WFSCONNERR, "msWFSLayerWhichShapes()" );
-            return MS_FAILURE;
-        }
-        else if ( strstr(szHeader,"opengis.net/gml") &&
-                  strstr(szHeader,"featureMember>") == NULL )
-        {
-            /* This looks like valid GML, but contains 0 features. */
-            return MS_DONE;
-        }
-        else if ( strstr(szHeader,"opengis.net/gml") == NULL ||
-                  strstr(szHeader,"featureMember>") == NULL )
-        {
-            /* This is probably just junk. */
-            msSetError(MS_WFSCONNERR, 
-                       "WFS request produced unexpected output (junk?) for layer %s.",
-                       "msWFSLayerWhichShapes()",
-                       lp->name?lp->name:"(null)");
-            return(MS_FAILURE);
-        }
-        
-        /* If we got this far, it must be a valid GML dataset... keep going */
     }
+    if ( strstr(szHeader, "<WFS_Exception>") ||
+         strstr(szHeader, "<ServiceExceptionReport>") ) {
+      msOWSProcessException(lp, psInfo->pszGMLFilename,
+                            MS_WFSCONNERR, "msWFSLayerWhichShapes()" );
+      return MS_FAILURE;
+    } else if ( strstr(szHeader,"opengis.net/gml") &&
+                strstr(szHeader,"featureMember>") == NULL ) {
+      /* This looks like valid GML, but contains 0 features. */
+      return MS_DONE;
+    } else if ( strstr(szHeader,"opengis.net/gml") == NULL ||
+                strstr(szHeader,"featureMember>") == NULL ) {
+      /* This is probably just junk. */
+      msSetError(MS_WFSCONNERR,
+                 "WFS request produced unexpected output (junk?) for layer %s.",
+                 "msWFSLayerWhichShapes()",
+                 lp->name?lp->name:"(null)");
+      return(MS_FAILURE);
+    }
+
+    /* If we got this far, it must be a valid GML dataset... keep going */
+  }
 
 
-/* ------------------------------------------------------------------
- * Open GML file using OGR.
- * ------------------------------------------------------------------ */
-    if ((status = msOGRLayerOpen(lp, psInfo->pszGMLFilename)) != MS_SUCCESS)
-        return status;
-    
-    status = msOGRLayerWhichShapes(lp, rect, isQuery);
-   
-    /* Mark that the OGR Layer is valid */
-    psInfo->bLayerHasValidGML = MS_TRUE;
-    
+  /* ------------------------------------------------------------------
+   * Open GML file using OGR.
+   * ------------------------------------------------------------------ */
+  if ((status = msOGRLayerOpen(lp, psInfo->pszGMLFilename)) != MS_SUCCESS)
     return status;
+
+  status = msOGRLayerWhichShapes(lp, rect, isQuery);
+
+  /* Mark that the OGR Layer is valid */
+  psInfo->bLayerHasValidGML = MS_TRUE;
+
+  return status;
 #else
-/* ------------------------------------------------------------------
- * WFS CONNECTION Support not included...
- * ------------------------------------------------------------------ */
-  msSetError(MS_WFSCONNERR, "WFS CLIENT CONNECTION support is not available.", 
+  /* ------------------------------------------------------------------
+   * WFS CONNECTION Support not included...
+   * ------------------------------------------------------------------ */
+  msSetError(MS_WFSCONNERR, "WFS CLIENT CONNECTION support is not available.",
              "msWFSLayerWhichShapes()");
   return(MS_FAILURE);
 
@@ -1238,29 +1165,29 @@ int msWFSLayerClose(layerObj *lp)
 {
 #ifdef USE_WFS_LYR
 
-/* ------------------------------------------------------------------
- * Cleanup OGR connection
- * ------------------------------------------------------------------ */
-    if (lp->layerinfo)
-        msOGRLayerClose(lp);
+  /* ------------------------------------------------------------------
+   * Cleanup OGR connection
+   * ------------------------------------------------------------------ */
+  if (lp->layerinfo)
+    msOGRLayerClose(lp);
 
-/* ------------------------------------------------------------------
- * Cleanup WFS connection info.
- * __TODO__ For now we flush everything, but we should try to cache some stuff
- * ------------------------------------------------------------------ */
-    /* __TODO__ unlink()  .gml file and OGR's schema file if they exist */
-    /* unlink( */
+  /* ------------------------------------------------------------------
+   * Cleanup WFS connection info.
+   * __TODO__ For now we flush everything, but we should try to cache some stuff
+   * ------------------------------------------------------------------ */
+  /* __TODO__ unlink()  .gml file and OGR's schema file if they exist */
+  /* unlink( */
 
-    msFreeWFSLayerInfo(lp->wfslayerinfo);
-    lp->wfslayerinfo = NULL;
+  msFreeWFSLayerInfo(lp->wfslayerinfo);
+  lp->wfslayerinfo = NULL;
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 
 #else
-/* ------------------------------------------------------------------
- * WFS CONNECTION Support not included...
- * ------------------------------------------------------------------ */
-  msSetError(MS_WFSCONNERR, "WFS CLIENT CONNECTION support is not available.", 
+  /* ------------------------------------------------------------------
+   * WFS CONNECTION Support not included...
+   * ------------------------------------------------------------------ */
+  msSetError(MS_WFSCONNERR, "WFS CLIENT CONNECTION support is not available.",
              "msWFSLayerClose()");
   return(MS_FAILURE);
 
@@ -1290,10 +1217,10 @@ char *msWFSExecuteGetFeature(layerObj *lp)
   return gmltmpfile;
 
 #else
-/* ------------------------------------------------------------------
- * WFS CONNECTION Support not included...
- * ------------------------------------------------------------------ */
-  msSetError(MS_WFSCONNERR, "WFS CLIENT CONNECTION support is not available.", 
+  /* ------------------------------------------------------------------
+   * WFS CONNECTION Support not included...
+   * ------------------------------------------------------------------ */
+  msSetError(MS_WFSCONNERR, "WFS CLIENT CONNECTION support is not available.",
              "msExecuteWFSGetFeature()");
   return NULL;
 
@@ -1304,28 +1231,28 @@ char *msWFSExecuteGetFeature(layerObj *lp)
 int
 msWFSLayerInitializeVirtualTable(layerObj *layer)
 {
-    assert(layer != NULL);
-    assert(layer->vtable != NULL);
-
-    layer->vtable->LayerInitItemInfo = msWFSLayerInitItemInfo;
-    layer->vtable->LayerFreeItemInfo = msOGRLayerFreeItemInfo; /* yes, OGR */
-    layer->vtable->LayerOpen = msWFSLayerOpenVT;
-    layer->vtable->LayerIsOpen = msWFSLayerIsOpen;
-    layer->vtable->LayerWhichShapes = msWFSLayerWhichShapes;
-    layer->vtable->LayerNextShape = msWFSLayerNextShape;
-    // layer->vtable->LayerResultsGetShape = msWFSLayerResultGetShape; 
-    layer->vtable->LayerGetShape = msWFSLayerGetShape;
-    layer->vtable->LayerClose = msWFSLayerClose;
-    layer->vtable->LayerGetItems = msWFSLayerGetItems;
-    layer->vtable->LayerGetExtent = msWFSLayerGetExtent;
-    /* layer->vtable->LayerGetAutoStyle, use default */
-    /* layer->vtable->LayerApplyFilterToLayer, use default */
-    /* layer->vtable->LayerCloseConnection, use default */
-    layer->vtable->LayerSetTimeFilter = msLayerMakePlainTimeFilter;
-    /* layer->vtable->LayerCreateItems, use default */
-    /* layer->vtable->LayerGetNumFeatures, use default */
-    /* layer->vtable->LayerGetAutoProjection, use defaut*/
-
-    return MS_SUCCESS;
+  assert(layer != NULL);
+  assert(layer->vtable != NULL);
+
+  layer->vtable->LayerInitItemInfo = msWFSLayerInitItemInfo;
+  layer->vtable->LayerFreeItemInfo = msOGRLayerFreeItemInfo; /* yes, OGR */
+  layer->vtable->LayerOpen = msWFSLayerOpenVT;
+  layer->vtable->LayerIsOpen = msWFSLayerIsOpen;
+  layer->vtable->LayerWhichShapes = msWFSLayerWhichShapes;
+  layer->vtable->LayerNextShape = msWFSLayerNextShape;
+  /* layer->vtable->LayerResultsGetShape = msWFSLayerResultGetShape; */
+  layer->vtable->LayerGetShape = msWFSLayerGetShape;
+  layer->vtable->LayerClose = msWFSLayerClose;
+  layer->vtable->LayerGetItems = msWFSLayerGetItems;
+  layer->vtable->LayerGetExtent = msWFSLayerGetExtent;
+  /* layer->vtable->LayerGetAutoStyle, use default */
+  /* layer->vtable->LayerApplyFilterToLayer, use default */
+  /* layer->vtable->LayerCloseConnection, use default */
+  layer->vtable->LayerSetTimeFilter = msLayerMakePlainTimeFilter;
+  /* layer->vtable->LayerCreateItems, use default */
+  /* layer->vtable->LayerGetNumFeatures, use default */
+  /* layer->vtable->LayerGetAutoProjection, use defaut*/
+
+  return MS_SUCCESS;
 }
 
diff --git a/mapwms.c b/mapwms.c
index 060fb8e..30d5c11 100644
--- a/mapwms.c
+++ b/mapwms.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -36,6 +36,7 @@
 #include "maptemplate.h"
 
 #include "mapogcsld.h"
+#include "mapogcfilter.h"
 
 #include "maptime.h"
 #include "mapproject.h"
@@ -48,7 +49,7 @@
 #include <process.h>
 #endif
 
-MS_CVSID("$Id$")
+
 
 /* ==================================================================
  * WMS Server stuff.
@@ -67,133 +68,125 @@ int ogrEnabled = 0;
 ** Report current MapServer error in requested format.
 */
 
-int msWMSException(mapObj *map, int nVersion, const char *exception_code, 
+int msWMSException(mapObj *map, int nVersion, const char *exception_code,
                    char *wms_exception_format)
 {
-    const char *encoding;
-    char *schemalocation = NULL;
+  const char *encoding;
+  char *schemalocation = NULL;
 
-    /* Default to WMS 1.3.0 exceptions if version not set yet */
-    if (nVersion <= 0)
-        nVersion = OWS_1_3_0;
+  /* Default to WMS 1.3.0 exceptions if version not set yet */
+  if (nVersion <= 0)
+    nVersion = OWS_1_3_0;
 
-    /* get scheam location */
-    schemalocation = msEncodeHTMLEntities( msOWSGetSchemasLocation(map) );
+  /* get scheam location */
+  schemalocation = msEncodeHTMLEntities( msOWSGetSchemasLocation(map) );
 
-    encoding = msOWSLookupMetadata(&(map->web.metadata), "MO", "encoding");
+  encoding = msOWSLookupMetadata(&(map->web.metadata), "MO", "encoding");
 
   /* Establish default exception format depending on VERSION */
-  if (wms_exception_format == NULL)
-  {
-      if (nVersion <= OWS_1_0_0)
-        wms_exception_format = "INIMAGE";  /* WMS 1.0.0 */
-      else if (nVersion <= OWS_1_0_7)
-        wms_exception_format = "SE_XML";   /* WMS 1.0.1 to 1.0.7 */
-      else if (nVersion <= OWS_1_1_1)
-        wms_exception_format = "application/vnd.ogc.se_xml"; /* WMS 1.1.0 and later */
-      else
-        wms_exception_format = "text/xml";
+  if (wms_exception_format == NULL) {
+    if (nVersion <= OWS_1_0_0)
+      wms_exception_format = "INIMAGE";  /* WMS 1.0.0 */
+    else if (nVersion <= OWS_1_0_7)
+      wms_exception_format = "SE_XML";   /* WMS 1.0.1 to 1.0.7 */
+    else if (nVersion <= OWS_1_1_1)
+      wms_exception_format = "application/vnd.ogc.se_xml"; /* WMS 1.1.0 and later */
+    else
+      wms_exception_format = "text/xml";
   }
 
   if (strcasecmp(wms_exception_format, "INIMAGE") == 0 ||
       strcasecmp(wms_exception_format, "BLANK") == 0 ||
       strcasecmp(wms_exception_format, "application/vnd.ogc.se_inimage")== 0 ||
-      strcasecmp(wms_exception_format, "application/vnd.ogc.se_blank") == 0)
-  {
+      strcasecmp(wms_exception_format, "application/vnd.ogc.se_blank") == 0) {
     int blank = 0;
 
     if (strcasecmp(wms_exception_format, "BLANK") == 0 ||
-        strcasecmp(wms_exception_format, "application/vnd.ogc.se_blank") == 0)
-    {
-        blank = 1;
+        strcasecmp(wms_exception_format, "application/vnd.ogc.se_blank") == 0) {
+      blank = 1;
     }
 
     msWriteErrorImage(map, NULL, blank);
 
-  }
-  else if (strcasecmp(wms_exception_format, "WMS_XML") == 0) /* Only in V1.0.0 */
-  {
-      if (encoding)
-          msIO_printf("Content-type: text/xml; charset=%s%c%c", encoding,10,10);
-      else
-          msIO_printf("Content-type: text/xml%c%c",10,10);
+  } else if (strcasecmp(wms_exception_format, "WMS_XML") == 0) { /* Only in V1.0.0 */
+    if (encoding)
+      msIO_setHeader("Content-Type","text/xml; charset=%s", encoding);
+    else
+      msIO_setHeader("Content-Type","text/xml");
+    msIO_sendHeaders();
 
     msIO_printf("<WMTException version=\"1.0.0\">\n");
     msWriteErrorXML(stdout);
     msIO_printf("</WMTException>\n");
-  }
-  else /* XML error, the default: SE_XML (1.0.1 to 1.0.7) */
-       /* or application/vnd.ogc.se_xml (1.1.0 and later) */
+  } else /* XML error, the default: SE_XML (1.0.1 to 1.0.7) */
+    /* or application/vnd.ogc.se_xml (1.1.0 and later) */
   {
-    if (nVersion <= OWS_1_0_7)
-    {
+    if (nVersion <= OWS_1_0_7) {
       /* In V1.0.1 to 1.0.7, the MIME type was text/xml */
-        if (encoding)
-            msIO_printf("Content-type: text/xml; charset=%s%c%c", encoding,10,10);
-        else
-            msIO_printf("Content-type: text/xml%c%c",10,10);
+      if (encoding)
+        msIO_setHeader("Content-Type","text/xml; charset=%s", encoding);
+      else
+        msIO_setHeader("Content-Type","text/xml");
+      msIO_sendHeaders();
 
       msOWSPrintEncodeMetadata(stdout, &(map->web.metadata),
                                "MO", "encoding", OWS_NOERR,
-                "<?xml version='1.0' encoding=\"%s\" standalone=\"no\" ?>\n",
-                    "ISO-8859-1");
+                               "<?xml version='1.0' encoding=\"%s\" standalone=\"no\" ?>\n",
+                               "ISO-8859-1");
       msIO_printf("<!DOCTYPE ServiceExceptionReport SYSTEM \"http://www.digitalearth.gov/wmt/xml/exception_1_0_1.dtd\">\n");
 
       msIO_printf("<ServiceExceptionReport version=\"1.0.1\">\n");
-    }
-    else if (nVersion <= OWS_1_1_0)
-    {
+    } else if (nVersion <= OWS_1_1_0) {
       /* In V1.1.0 and later, we have OGC-specific MIME types */
       /* we cannot return anything else than application/vnd.ogc.se_xml here. */
-        if (encoding)
-            msIO_printf("Content-type: application/vnd.ogc.se_xml; charset=%s%c%c", encoding,10,10);
-        else
-            msIO_printf("Content-type: application/vnd.ogc.se_xml%c%c",10,10);
-        
+      if (encoding)
+        msIO_setHeader("Content-Type","application/vnd.ogc.se_xml; charset=%s", encoding);
+      else
+        msIO_setHeader("Content-Type","application/vnd.ogc.se_xml");
+      msIO_sendHeaders();
+
       msOWSPrintEncodeMetadata(stdout, &(map->web.metadata),
                                "MO", "encoding", OWS_NOERR,
-                "<?xml version='1.0' encoding=\"%s\" standalone=\"no\" ?>\n",
-                         "ISO-8859-1");
+                               "<?xml version='1.0' encoding=\"%s\" standalone=\"no\" ?>\n",
+                               "ISO-8859-1");
+
 
-      
       msIO_printf("<!DOCTYPE ServiceExceptionReport SYSTEM \"%s/wms/1.1.0/exception_1_1_0.dtd\">\n",schemalocation);
 
       msIO_printf("<ServiceExceptionReport version=\"1.1.0\">\n");
-    }
-    else if (nVersion <= OWS_1_1_1)/* 1.1.1 */
-    {
+    } else if (nVersion <= OWS_1_1_1) { /* 1.1.1 */
+      if (encoding)
+        msIO_setHeader("Content-Type","application/vnd.ogc.se_xml; charset=%s", encoding);
+      else
+        msIO_setHeader("Content-Type","application/vnd.ogc.se_xml");
+      msIO_sendHeaders();
+
+      msOWSPrintEncodeMetadata(stdout, &(map->web.metadata),
+                               "MO", "encoding", OWS_NOERR,
+                               "<?xml version='1.0' encoding=\"%s\" standalone=\"no\" ?>\n",
+                               "ISO-8859-1");
+      msIO_printf("<!DOCTYPE ServiceExceptionReport SYSTEM \"%s/wms/1.1.1/exception_1_1_1.dtd\">\n", schemalocation);
+      msIO_printf("<ServiceExceptionReport version=\"1.1.1\">\n");
+    } else { /*1.3.0*/
+      if (strcasecmp(wms_exception_format, "application/vnd.ogc.se_xml") == 0) {
         if (encoding)
-            msIO_printf("Content-type: application/vnd.ogc.se_xml; charset=%s%c%c", encoding,10,10);
+          msIO_setHeader("Content-Type","application/vnd.ogc.se_xml; charset=%s", encoding);
         else
-            msIO_printf("Content-type: application/vnd.ogc.se_xml%c%c",10,10);
-
-
-        msOWSPrintEncodeMetadata(stdout, &(map->web.metadata),
-                                 "MO", "encoding", OWS_NOERR,
-                  "<?xml version='1.0' encoding=\"%s\" standalone=\"no\" ?>\n",
-                           "ISO-8859-1");
-        msIO_printf("<!DOCTYPE ServiceExceptionReport SYSTEM \"%s/wms/1.1.1/exception_1_1_1.dtd\">\n", schemalocation);
-        msIO_printf("<ServiceExceptionReport version=\"1.1.1\">\n");
-    }
-    else /*1.3.0*/
-    {
-        if (strcasecmp(wms_exception_format, "application/vnd.ogc.se_xml") == 0)
-            if (encoding)
-                msIO_printf("Content-type: application/vnd.ogc.se_xml; charset=%s%c%c", encoding,10,10);
-            else
-                msIO_printf("Content-type: application/vnd.ogc.se_xml%c%c",10,10);
+          msIO_setHeader("Content-Type","application/vnd.ogc.se_xml");
+      } else {
+        if (encoding)
+          msIO_setHeader("Content-Type","text/xml; charset=%s", encoding);
         else
-            if (encoding)
-                msIO_printf("Content-type: text/xml; charset=%s%c%c", encoding,10,10);
-            else
-                msIO_printf("Content-type: text/xml%c%c",10,10);
+          msIO_setHeader("Content-Type","text/xml");
+      }
+      msIO_sendHeaders();
 
-        msOWSPrintEncodeMetadata(stdout, &(map->web.metadata),
-                                 "MO", "encoding", OWS_NOERR,
-                  "<?xml version='1.0' encoding=\"%s\" standalone=\"no\" ?>\n",
-                           "ISO-8859-1");
-        msIO_printf("<ServiceExceptionReport version=\"1.3.0\" xmlns=\"http://www.opengis.net/ogc\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.opengis.net/ogc %s/wms/1.3.0/exceptions_1_3_0.xsd\">\n",
-                    schemalocation);
+      msOWSPrintEncodeMetadata(stdout, &(map->web.metadata),
+                               "MO", "encoding", OWS_NOERR,
+                               "<?xml version='1.0' encoding=\"%s\" standalone=\"no\" ?>\n",
+                               "ISO-8859-1");
+      msIO_printf("<ServiceExceptionReport version=\"1.3.0\" xmlns=\"http://www.opengis.net/ogc\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.opengis.net/ogc %s/wms/1.3.0/exceptions_1_3_0.xsd\">\n",
+                  schemalocation);
     }
 
 
@@ -205,74 +198,60 @@ int msWMSException(mapObj *map, int nVersion, const char *exception_code,
     msIO_printf("</ServiceException>\n");
     msIO_printf("</ServiceExceptionReport>\n");
 
-    free(schemalocation);
-
   }
+  free(schemalocation);
 
   return MS_FAILURE; /* so that we can call 'return msWMSException();' anywhere */
 }
 
 void msWMSSetTimePattern(const char *timepatternstring, char *timestring)
 {
-    char *time = NULL;
-    char **atimes, **tokens = NULL;
-    int numtimes, ntmp, i = 0;
-    char *tmpstr = NULL;
-
-    if (timepatternstring && timestring)
-    {
-        /* parse the time parameter to extract a distinct time. */
-        /* time value can be dicrete times (eg 2004-09-21), */
-        /* multiple times (2004-09-21, 2004-09-22, ...) */
-        /* and range(s) (2004-09-21/2004-09-25, 2004-09-27/2004-09-29) */
-        if (strstr(timestring, ",") == NULL &&
-            strstr(timestring, "/") == NULL) /* discrete time */
-        {
-            time = msStrdup(timestring);
-        }
-        else
-        {
-            atimes = msStringSplit (timestring, ',', &numtimes);
-            if (numtimes >=1 && atimes)
-            {
-                tokens = msStringSplit(atimes[0],  '/', &ntmp);
-                if (ntmp == 2 && tokens) /* range */
-                {
-                    time = msStrdup(tokens[0]);
-                }
-                else /* multiple times */
-                {
-                    time = msStrdup(atimes[0]);
-                }
-                msFreeCharArray(tokens, ntmp);
-                msFreeCharArray(atimes, numtimes);
-            }
+  char *time = NULL;
+  char **atimes, **tokens = NULL;
+  int numtimes, ntmp, i = 0;
+  char *tmpstr = NULL;
+
+  if (timepatternstring && timestring) {
+    /* parse the time parameter to extract a distinct time. */
+    /* time value can be dicrete times (eg 2004-09-21), */
+    /* multiple times (2004-09-21, 2004-09-22, ...) */
+    /* and range(s) (2004-09-21/2004-09-25, 2004-09-27/2004-09-29) */
+    if (strstr(timestring, ",") == NULL &&
+        strstr(timestring, "/") == NULL) { /* discrete time */
+      time = msStrdup(timestring);
+    } else {
+      atimes = msStringSplit (timestring, ',', &numtimes);
+      if (numtimes >=1 && atimes) {
+        tokens = msStringSplit(atimes[0],  '/', &ntmp);
+        if (ntmp == 2 && tokens) { /* range */
+          time = msStrdup(tokens[0]);
+        } else { /* multiple times */
+          time = msStrdup(atimes[0]);
         }
-        /* get the pattern to use */
-        if (time)
-        {
-            tokens = msStringSplit(timepatternstring, ',', &ntmp);
-            if (tokens && ntmp >= 1)
-            {
-                for (i=0; i<ntmp; i++)
-                {
-                  if (tokens[i] && strlen(tokens[i]) > 0)
-                  {
-                      msStringTrimBlanks(tokens[i]);
-                      tmpstr = msStringTrimLeft(tokens[i]);
-                      if (msTimeMatchPattern(time, tmpstr) == MS_TRUE)
-                      {
-                          msSetLimitedPattersToUse(tmpstr);
-                          break;
-                      }
-                  }
-                }
-                msFreeCharArray(tokens, ntmp);
+        msFreeCharArray(tokens, ntmp);
+        msFreeCharArray(atimes, numtimes);
+      }
+    }
+    /* get the pattern to use */
+    if (time) {
+      tokens = msStringSplit(timepatternstring, ',', &ntmp);
+      if (tokens && ntmp >= 1) {
+        for (i=0; i<ntmp; i++) {
+          if (tokens[i] && strlen(tokens[i]) > 0) {
+            msStringTrimBlanks(tokens[i]);
+            tmpstr = msStringTrimLeft(tokens[i]);
+            if (msTimeMatchPattern(time, tmpstr) == MS_TRUE) {
+              msSetLimitedPattersToUse(tmpstr);
+              break;
             }
-            free(time);
+          }
         }
-
+        msFreeCharArray(tokens, ntmp);
+      }
+      free(time);
     }
+
+  }
 }
 
 /*
@@ -280,102 +259,513 @@ void msWMSSetTimePattern(const char *timepatternstring, char *timestring)
 */
 int msWMSApplyTime(mapObj *map, int version, char *time, char *wms_exception_format)
 {
-    int i=0;
-    layerObj *lp = NULL;
-    const char *timeextent, *timefield, *timedefault, *timpattern = NULL;
+  int i=0;
+  layerObj *lp = NULL;
+  const char *timeextent, *timefield, *timedefault, *timpattern = NULL;
 
-    if (map)
-    {
-        for (i=0; i<map->numlayers; i++)
-        {
-            lp = (GET_LAYER(map, i));
-            if (lp->status != MS_ON && lp->status != MS_DEFAULT)
+  if (map) {
+    for (i=0; i<map->numlayers; i++) {
+      lp = (GET_LAYER(map, i));
+      if (lp->status != MS_ON && lp->status != MS_DEFAULT)
+        continue;
+      /* check if the layer is time aware */
+      timeextent = msOWSLookupMetadata(&(lp->metadata), "MO",
+                                       "timeextent");
+      timefield =  msOWSLookupMetadata(&(lp->metadata), "MO",
+                                       "timeitem");
+      timedefault =  msOWSLookupMetadata(&(lp->metadata), "MO",
+                                         "timedefault");
+      if (timeextent && timefield) {
+        /* check to see if the time value is given. If not */
+        /* use default time. If default time is not available */
+        /* send an exception */
+        if (time == NULL || strlen(time) <=0) {
+          if (timedefault == NULL) {
+            msSetError(MS_WMSERR, "No Time value was given, and no default time value defined.", "msWMSApplyTime");
+            return msWMSException(map, version, "MissingDimensionValue", wms_exception_format);
+          } else {
+            if (msValidateTimeValue((char *)timedefault, timeextent) == MS_FALSE) {
+              msSetError(MS_WMSERR, "No Time value was given, and the default time value %s is invalid or outside the time extent defined %s", "msWMSApplyTime", timedefault, timeextent);
+              /* return MS_FALSE; */
+              return msWMSException(map, version,
+                                    "InvalidDimensionValue", wms_exception_format);
+            }
+            msLayerSetTimeFilter(lp, timedefault, timefield);
+          }
+        } else {
+          /* check if given time is in the range */
+          if (msValidateTimeValue(time, timeextent) == MS_FALSE) {
+            if (timedefault == NULL) {
+              msSetError(MS_WMSERR, "Time value(s) %s given is invalid or outside the time extent defined (%s).", "msWMSApplyTime", time, timeextent);
+              /* return MS_FALSE; */
+              return msWMSException(map, version,
+                                    "InvalidDimensionValue", wms_exception_format);
+            } else {
+              if (msValidateTimeValue((char *)timedefault, timeextent) == MS_FALSE) {
+                msSetError(MS_WMSERR, "Time value(s) %s given is invalid or outside the time extent defined (%s), and default time set is invalid (%s)", "msWMSApplyTime", time, timeextent, timedefault);
+                /* return MS_FALSE; */
+                return msWMSException(map, version,
+                                      "InvalidDimensionValue",  wms_exception_format);
+              } else
+                msLayerSetTimeFilter(lp, timedefault, timefield);
+            }
+
+          } else {
+            /* build the time string */
+            msLayerSetTimeFilter(lp, time, timefield);
+            timeextent= NULL;
+          }
+        }
+      }
+    }
+    /* check to see if there is a list of possible patterns defined */
+    /* if it is the case, use it to set the time pattern to use */
+    /* for the request */
+
+    timpattern = msOWSLookupMetadata(&(map->web.metadata), "MO",
+                                     "timeformat");
+    if (timpattern && time && strlen(time) > 0)
+      msWMSSetTimePattern(timpattern, time);
+  }
+
+  return MS_SUCCESS;
+}
+
+/*
+** msWMSPrepareNestedGroups()
+**
+** purpose: Parse WMS_LAYER_GROUP settings into arrays
+**
+** params:
+** - nestedGroups: This array holds the arrays of groups that have been set
+**                 through the WMS_LAYER_GROUP metadata
+** - numNestedGroups: This array holds the number of groups set in
+**                    WMS_LAYER_GROUP for each layer
+** - isUsedInNestedGroup: This array indicates if the layer is used as group
+**                        as set through the WMS_LAYER_GROUP metadata
+*/
+void msWMSPrepareNestedGroups(mapObj* map, int nVersion, char*** nestedGroups, int* numNestedGroups, int* isUsedInNestedGroup)
+{
+  int i, j, k;
+  const char* groups;
+  char* errorMsg;
+
+  for (i = 0; i < map->numlayers; i++) {
+    nestedGroups[i] = NULL; /* default */
+    numNestedGroups[i] = 0; /* default */
+    isUsedInNestedGroup[i] = 0; /* default */
+
+    groups = msOWSLookupMetadata(&(GET_LAYER(map, i)->metadata), "MO", "layer_group");
+    if ((groups != NULL) && (strlen(groups) != 0)) {
+      if (GET_LAYER(map, i)->group != NULL && strlen(GET_LAYER(map, i)->group) != 0) {
+        errorMsg = "It is not allowed to set both the GROUP and WMS_LAYER_GROUP for a layer";
+        msSetError(MS_WMSERR, errorMsg, "msWMSPrepareNestedGroups()", NULL);
+        msIO_fprintf(stdout, "<!-- ERROR: %s -->\n", errorMsg);
+        /* cannot return exception at this point because we are already writing to stdout */
+      } else {
+        if (groups[0] != '/') {
+          errorMsg = "The WMS_LAYER_GROUP metadata does not start with a '/'";
+          msSetError(MS_WMSERR, errorMsg, "msWMSPrepareNestedGroups()", NULL);
+          msIO_fprintf(stdout, "<!-- ERROR: %s -->\n", errorMsg);
+          /* cannot return exception at this point because we are already writing to stdout */
+        } else {
+          /* split into subgroups. Start at address + 1 because the first '/' would cause an extra empty group */
+          nestedGroups[i] = msStringSplit(groups + 1, '/', &numNestedGroups[i]);
+          /* */
+          for (j = 0; j < map->numlayers; j++) {
+            if (isUsedInNestedGroup[j])
               continue;
-            /* check if the layer is time aware */
-            timeextent = msOWSLookupMetadata(&(lp->metadata), "MO",
-                                             "timeextent");
-            timefield =  msOWSLookupMetadata(&(lp->metadata), "MO",
-                                             "timeitem");
-            timedefault =  msOWSLookupMetadata(&(lp->metadata), "MO",
-                                             "timedefault");
-            if (timeextent && timefield)
-            {
-                /* check to see if the time value is given. If not */
-                /* use default time. If default time is not available */
-                /* send an exception */
-                if (time == NULL || strlen(time) <=0)
-                {
-                    if (timedefault == NULL)
-                    {
-                        msSetError(MS_WMSERR, "No Time value was given, and no default time value defined.", "msWMSApplyTime");
-                        return msWMSException(map, version, "MissingDimensionValue", wms_exception_format);
-                    }
-                    else
-                    {
-                        if (msValidateTimeValue((char *)timedefault, timeextent) == MS_FALSE)
-                        {
-                            msSetError(MS_WMSERR, "No Time value was given, and the default time value %s is invalid or outside the time extent defined %s", "msWMSApplyTime", timedefault, timeextent);
-                        /* return MS_FALSE; */
-                            return msWMSException(map, version,
-                                                  "InvalidDimensionValue", wms_exception_format);
-                        }
-                        msLayerSetTimeFilter(lp, timedefault, timefield);
-                    }
-                }
-                else
-                {
-                    /* check if given time is in the range */
-                    if (msValidateTimeValue(time, timeextent) == MS_FALSE)
-                    {
-                        if (timedefault == NULL)
-                        {
-                            msSetError(MS_WMSERR, "Time value(s) %s given is invalid or outside the time extent defined (%s).", "msWMSApplyTime", time, timeextent);
-                        /* return MS_FALSE; */
-                            return msWMSException(map, version,
-                                                  "InvalidDimensionValue", wms_exception_format);
-                        }
-                        else
-                        {
-                            if (msValidateTimeValue((char *)timedefault, timeextent) == MS_FALSE)
-                            {
-                                msSetError(MS_WMSERR, "Time value(s) %s given is invalid or outside the time extent defined (%s), and default time set is invalid (%s)", "msWMSApplyTime", time, timeextent, timedefault);
-                        /* return MS_FALSE; */
-                                return msWMSException(map, version,
-                                                      "InvalidDimensionValue",  wms_exception_format);
-                            }
-                            else
-                              msLayerSetTimeFilter(lp, timedefault, timefield);
-                        }
-                            
-                    }
-                    else
-                    {
-                    /* build the time string */
-                        msLayerSetTimeFilter(lp, time, timefield);
-                        timeextent= NULL;
-                    }
-                }
+
+            for (k=0; k<numNestedGroups[i]; k++) {
+              if ( GET_LAYER(map, j)->name && strcasecmp(GET_LAYER(map, j)->name, nestedGroups[i][k]) == 0 ) {
+                isUsedInNestedGroup[j] = 1;
+                break;
+              }
+            }
+          }
+        }
+      }
+    }
+  }
+}
+
+/*
+** Validate that a given dimension is inside the extents defined
+*/
+int msWMSValidateDimensionValue(char *value, const char *dimensionextent, int forcecharcter)
+{
+  char **extents=NULL, **ranges=NULL, **onerange=NULL;
+  int numextents;
+  char **aextentvalues = NULL;
+  int nextentvalues=0;
+  pointObj *aextentranges=NULL;
+  int nextentranges=0;
+
+  int isextentavalue = MS_FALSE, isextentarange=MS_FALSE;
+  int i,j, ntmp;
+  char **uservalues=NULL;
+  int numuservalues=0;
+  char *stmp = NULL;
+  int ischaracter = MS_FALSE;
+  float minval, maxval,currentval,mincurrentval,maxcurrentval, mincurrentrange, maxcurrentrange;
+
+  int uservaluevalid= MS_FALSE;
+
+  if (forcecharcter)
+    ischaracter = MS_TRUE;
+
+  if (!value || !dimensionextent)
+    return MS_FALSE;
+
+  /*for the value, we support descrete values (2005) */
+  /* multiple values (abc, def, ...) */
+  /* and range(s) (1000/2000, 3000/5000) */
+  /** we do not support resolution*/
+
+  /* -------------------------------------------------------------------- */
+  /*      parse the extent first.                                         */
+  /* -------------------------------------------------------------------- */
+  extents = msStringSplit (dimensionextent, ',', &numextents);
+  if (numextents == 1) {
+    if (strstr(dimensionextent, "/") == NULL) {
+      /*single value*/
+      isextentavalue = MS_TRUE;
+      nextentvalues = 1;
+      aextentvalues = (char **)msSmallMalloc(sizeof(char *));
+      msStringTrim(extents[0]);
+      aextentvalues[0] = msStrdup(dimensionextent);
+      if (!forcecharcter)
+        ischaracter= !FLTIsNumeric((char *)dimensionextent);
+
+    } else {
+      ntmp = -1;
+      ranges = msStringSplit (dimensionextent, '/', &ntmp);
+      if(ranges && (ntmp == 2 || ntmp == 3)) {
+        /*single range*/
+        isextentarange = MS_TRUE;
+        aextentranges = msSmallMalloc(sizeof(pointObj));
+        nextentranges=1;
+        aextentranges[0].x = atof(ranges[0]);
+        aextentranges[0].y = atof(ranges[1]);
+        /*ranges should be numeric*/
+        ischaracter = MS_FALSE;
+      }
+      if (ranges && ntmp > 0) {
+        msFreeCharArray(ranges, ntmp);
+        ranges = NULL;
+      }
+    }
+  } else if (numextents > 1) { /*check if it is muliple values or mutliple ranges*/
+    if (strstr(dimensionextent, "/") == NULL) {
+      /*multiple values*/
+      isextentavalue = MS_TRUE;
+      aextentvalues = (char **)msSmallMalloc(sizeof(char *)*numextents);
+      for (i=0; i<numextents; i++) {
+        stmp = msStrdup(extents[i]);
+        msStringTrim(stmp);
+        aextentvalues[i] = msStrdup(stmp);
+        msFree(stmp);
+      }
+      nextentvalues = numextents;
+      if (!forcecharcter)
+        ischaracter= !FLTIsNumeric(aextentvalues[0]);
+    } else { /*multiple range extent*/
+      int isvalidextent = MS_TRUE;
+      /*ranges should be numeric*/
+      ischaracter = MS_FALSE;
+      isextentarange = MS_TRUE;
+      aextentranges = msSmallMalloc(sizeof(pointObj) * numextents);
+      nextentranges=0;
+
+      for (i=0; i<numextents; i++) {
+        onerange = msStringSplit(extents[i], '/', &ntmp);
+        if (!onerange || (ntmp != 2 && ntmp != 3)) {
+          isvalidextent = MS_FALSE;
+          break;
+        }
+        if (isvalidextent) {
+
+          aextentranges[nextentranges].x = atof(onerange[0]);
+          aextentranges[nextentranges++].y = atof(onerange[1]);
+        }
+        if (onerange && ntmp > 0 ) {
+          msFreeCharArray(onerange, ntmp);
+          onerange = NULL;
+        }
+      }
+      if (!isvalidextent) {
+        msFree(aextentranges);
+        nextentranges = 0;
+        isextentarange = MS_FALSE;
+      }
+    }
+  }
+
+  if (numextents > 0) {
+    msFreeCharArray(extents, numextents);
+    extents = NULL;
+  }
+
+
+
+
+  /* make sure that we got a valid extent*/
+  if (!isextentavalue && !isextentarange) {
+    return MS_FALSE;
+  }
+
+  /*for the extent of the dimesion, we support
+  single value,  or list of mulitiple values comma separated,
+  a single range or multipe ranges */
+
+
+  uservalues = msStringSplit (value, ',', &numuservalues);
+  uservaluevalid = MS_FALSE;
+  if (numuservalues == 1) {
+    /*user iput=single*/
+    /*is it descret or range*/
+    ranges = msStringSplit(uservalues[0], '/', &ntmp);
+    if (ntmp == 1) { /*discrete*/
+      if (isextentavalue) {
+        /*single user value, single/multiple values extent*/
+        for (i=0; i<nextentvalues; i++) {
+          if (ischaracter)
+            uservaluevalid = !strcmp(uservalues[0], aextentvalues[i]);
+          else {
+            if (atof(uservalues[0]) == atof(aextentvalues[i]))
+              uservaluevalid = MS_TRUE;
+          }
+          if(uservaluevalid)
+            break;
+        }
+      } else if (isextentarange) {
+        /*single user value, single/multiple range extent*/
+        currentval = atof(uservalues[0]);
+
+        for (i=0; i<nextentranges; i++) {
+          minval = aextentranges[i].x;
+          maxval = aextentranges[i].y;
+          if (currentval >= minval && currentval <= maxval) {
+            uservaluevalid= MS_TRUE;
+            break;
+          }
+        }
+      }
+    } else if (ntmp == 2 || ntmp == 3) { /*range*/
+      /*user input=single range. In this case the extents must
+       be of a range type.*/
+      mincurrentval = atof(ranges[0]);
+      maxcurrentval = atof(ranges[1]);
+      if (isextentarange) {
+        for (i=0; i<nextentranges; i++) {
+          minval = aextentranges[i].x;
+          maxval = aextentranges[i].y;
+
+          if(minval <= mincurrentval && maxval >= maxcurrentval &&
+              minval <= maxval) {
+            uservaluevalid= MS_TRUE;
+            break;
+          }
+        }
+      }
+    }
+    if (ranges && ntmp > 0)
+      msFreeCharArray(ranges, ntmp);
+  } else if (numuservalues > 1) { /*user input=multiple*/
+    if (strstr(value, "/") == NULL) {
+      /*user input=multiple value*/
+      int valueisvalid = MS_FALSE;
+      for (i=0; i<numuservalues; i++) {
+        valueisvalid = MS_FALSE;
+        if (isextentavalue) {
+          /*user input is multiple values, extent is defned as one or multiple values*/
+          for (j=0; j<nextentvalues; j++) {
+            if (ischaracter) {
+              if (strcmp(uservalues[i], aextentvalues[j]) == 0) {
+                valueisvalid = MS_TRUE;
+                break;
+              }
+            } else {
+              if (atof(uservalues[i]) == atof(aextentvalues[j])) {
+                valueisvalid = MS_TRUE;
+                break;
+              }
+            }
+          }
+          /*every value shoule be valid*/
+          if (!valueisvalid)
+            break;
+        } else if (isextentarange) {
+          /*user input is multiple values, extent is defned as one or multiple ranges*/
+          for (j=0; j<nextentranges; j++) {
+            minval = aextentranges[j].x;
+            maxval = aextentranges[j].y;
+            currentval = atof(uservalues[i]);
+            if(minval <= currentval && maxval >= currentval &&
+                minval <= maxval) {
+              valueisvalid = MS_TRUE;
+              break;
+            }
+          }
+          if (!valueisvalid)
+            break;
+        }
+      }
+      uservaluevalid = valueisvalid;
+    } else { /*user input multiple ranges*/
+      int valueisvalid = MS_TRUE;
+
+      for (i=0; i<numuservalues; i++) {
+        /*each ranges should be valid*/
+        onerange = msStringSplit(uservalues[i], '/', &ntmp);
+        if (ntmp == 2 || ntmp == 3) {
+          mincurrentval = atof(onerange[0]);
+          maxcurrentval = atof(onerange[1]);
+
+          /*extent must be defined also as a rangle*/
+          if (isextentarange) {
+            for (j=0; j<nextentranges; j++) {
+              mincurrentrange = aextentranges[j].x;
+              maxcurrentrange = aextentranges[j].y;
+
+              if(mincurrentval >=mincurrentrange && maxcurrentval <= maxcurrentrange &&
+                  mincurrentval <= maxcurrentval) {
+                break;
+              }
+
             }
+            if (j == nextentranges) {
+              valueisvalid = MS_FALSE;
+              msFreeCharArray(onerange, ntmp);
+              break;
+            }
+          }
+        } else {
+          valueisvalid = MS_FALSE;
         }
-        /* check to see if there is a list of possible patterns defined */
-        /* if it is the case, use it to set the time pattern to use */
-        /* for the request */
-
-        timpattern = msOWSLookupMetadata(&(map->web.metadata), "MO",
-                                         "timeformat");
-        if (timpattern && time && strlen(time) > 0)
-          msWMSSetTimePattern(timpattern, time);
+        msFreeCharArray(onerange, ntmp);
+      }
+      uservaluevalid = valueisvalid;
     }
 
-    return MS_SUCCESS;
+  }
+  if(uservalues && numuservalues > 0)
+    msFreeCharArray(uservalues, numuservalues);
+
+  if (aextentvalues && nextentvalues > 0) {
+    for (i=0; i<nextentvalues; i++)
+      msFree(aextentvalues[i]);
+    msFree(aextentvalues);
+  }
+
+  if(aextentranges && nextentranges > 0) {
+    msFree(aextentranges);
+  }
+
+  if(uservaluevalid)
+    return MS_TRUE;
+
+  return MS_FALSE;
 }
 
 
+int msWMSApplyDimensionLayer(layerObj *lp, const char *item, char *value, int forcecharcter)
+{
+  int result = MS_FALSE;
+  char *pszExpression=NULL;
+
+  if (lp && item && value) {
+    /*for the value, we support descrete values (2005) */
+    /* multiple values (abc, def, ...) */
+    /* and range(s) (1000/2000, 3000/5000) */
+    pszExpression = FLTGetExpressionForValuesRanges(lp, (char *)item, value,  forcecharcter);
+
+    if (pszExpression) {
+      if(FLTApplyExpressionToLayer(lp, pszExpression))
+        result = MS_TRUE;
+      msFree(pszExpression);
+    }
+  }
+  return result;
+}
+
+
+int msWMSApplyDimension(layerObj *lp, int version, char *dimensionname, char *value,
+                        char *wms_exception_format)
+{
+  char *dimensionitemname=NULL, *dimensionextentname=NULL, *dimensiontypename=NULL;
+  char *dimensionunitname=NULL, *dimensiondefaultname=NULL;
+  const char *dimensionitem, *dimensionextent, *dimensiontype, *dimensionunit, *dimensiondefault;
+  int forcecharcter;
+  int result = MS_FALSE;
+  char *dimension = NULL, *currentvalue=NULL;
+
+  if (lp && dimensionname && value) {
+    /*check if the dimension name passes starts with dim_. All dimensions should start with dim_, except elevation*/
+    if (strncasecmp(dimensionname, "dim_", 4) == 0)
+      dimension = msStrdup(dimensionname+4);
+    else
+      dimension = msStrdup(dimensionname);
+
+    /*if value is empty and a default is defined, use it*/
+    if (strlen(value) > 0)
+      currentvalue = msStrdup(value);
+    else {
+      dimensiondefaultname = msStrdup(dimension);
+      dimensiondefaultname = msStringConcatenate(dimensiondefaultname, "_default");
+      dimensiondefault = msOWSLookupMetadata(&(lp->metadata), "M", dimensiondefaultname);
+      if (dimensiondefault && strlen(dimensiondefault) > 0)
+        currentvalue = msStrdup(dimensiondefault);
+    }
+
+    /*check if the manadatory metada related to the dimension are set*/
+    dimensionitemname = msStrdup(dimension);
+    dimensionitemname = msStringConcatenate(dimensionitemname, "_item");
+    dimensionitem = msOWSLookupMetadata(&(lp->metadata), "M", dimensionitemname);
+
+    dimensionextentname = msStrdup(dimension);
+    dimensionextentname = msStringConcatenate(dimensionextentname, "_extent");
+    dimensionextent = msOWSLookupMetadata(&(lp->metadata), "M", dimensionextentname);
+
+    dimensionunitname = msStrdup(dimension);
+    dimensionunitname = msStringConcatenate(dimensionunitname, "_units");
+    dimensionunit = msOWSLookupMetadata(&(lp->metadata), "M", dimensionunitname);
+
+    /*if the server want to force the type to character*/
+    dimensiontypename = msStrdup(dimension);
+    dimensiontypename = msStringConcatenate(dimensiontypename, "_type");
+    dimensiontype = msOWSLookupMetadata(&(lp->metadata), "M", dimensiontypename);
+    forcecharcter = MS_FALSE;
+    if (dimensiontype && strcasecmp(dimensiontype, "Character") == 0)
+      forcecharcter = MS_TRUE;
+
+    if (dimensionitem && dimensionextent && dimensionunit && currentvalue) {
+      if(msWMSValidateDimensionValue(currentvalue, dimensionextent, forcecharcter)) {
+        result = msWMSApplyDimensionLayer(lp, dimensionitem, currentvalue, forcecharcter);
+      } else {
+        msSetError(MS_WMSERR, "Dimension %s with a value of %s is invalid or outside the extents defined", "msWMSApplyDimension",
+                   dimension, currentvalue);
+        result =  MS_FALSE;
+      }
+    } else
+      msSetError(MS_WMSERR, "Dimension %s : invalid settings. Make sure that item, units and extent are set.", "msWMSApplyDimension",
+                 dimension, currentvalue);
+
+    msFree(dimensionitemname);
+    msFree(dimensionextentname);
+    msFree(dimensiontypename);
+    msFree(dimensionunitname);
+    msFree(dimensiondefaultname);
+    msFree(dimension);
+    msFree(currentvalue);
+  }
+  return result;
+}
 /*
 **
 */
 int msWMSLoadGetMapParams(mapObj *map, int nVersion,
-                          char **names, char **values, int numentries, char *wms_exception_format, 
+                          char **names, char **values, int numentries, char *wms_exception_format,
                           const char *wms_request, owsRequestObj *ows_request)
 {
   int i, adjust_extent = MS_FALSE, nonsquare_enabled = MS_FALSE;
@@ -393,10 +783,10 @@ int msWMSLoadGetMapParams(mapObj *map, int nVersion,
   char srsbuffer[100];
   int epsgvalid = MS_FALSE;
   const char *projstring;
-   int timerequest = 0;
-   char *stime = NULL;
-   char **tokens=NULL;
-   int n,j;
+  int timerequest = 0;
+  char *stime = NULL;
+  char **tokens=NULL;
+  int n,j;
   int srsfound = 0;
   int bboxfound = 0;
   int formatfound = 0;
@@ -406,175 +796,182 @@ int msWMSLoadGetMapParams(mapObj *map, int nVersion,
   int status = 0;
   const char *layerlimit = NULL;
 
-  char *bboxrequest=NULL;
   const char *sldenabled=NULL;
   char *sld_url=NULL, *sld_body=NULL;
 
-   epsgbuf[0]='\0';
-   srsbuffer[0]='\0';
+  epsgbuf[0]='\0';
+  srsbuffer[0]='\0';
 
 
   /* Some of the getMap parameters are actually required depending on the */
   /* request, but for now we assume all are optional and the map file */
   /* defaults will apply. */
 
-   msAdjustExtent(&(map->extent), map->width, map->height);
+  msAdjustExtent(&(map->extent), map->width, map->height);
+
+  /*
+    Check for SLDs first. If SLD is available LAYERS and STYLES parameters are non mandatory
+   */
+  for(i=0; map && i<numentries; i++) {
+    /* check if SLD is passed.  If yes, check for OGR support */
+    if (strcasecmp(names[i], "SLD") == 0 || strcasecmp(names[i], "SLD_BODY") == 0) {
+      sldenabled = msOWSLookupMetadata(&(map->web.metadata), "MO", "sld_enabled");
+
+      if (sldenabled == NULL)
+        sldenabled = "true";
 
-   
+      if (ogrEnabled == 0) {
+        msSetError(MS_WMSERR, "OGR support is not available.", "msWMSLoadGetMapParams()");
+        return msWMSException(map, nVersion, NULL, wms_exception_format);
+      } else {
+        if (strcasecmp(sldenabled, "true") == 0) {
+          if (strcasecmp(names[i], "SLD") == 0) {
+            sld_url =  values[i];
+          }
+          if (strcasecmp(names[i], "SLD_BODY") == 0) {
+            sld_body =  values[i];
+          }
+        }
+      }
+    }
+  }
 
-   for(i=0; map && i<numentries; i++)
-   {
+  for(i=0; map && i<numentries; i++) {
     /* getMap parameters */
 
-    if (strcasecmp(names[i], "REQUEST") == 0)
-    {
+    if (strcasecmp(names[i], "REQUEST") == 0) {
       request = values[i];
     }
 
-    
-    /* check if SLD is passed.  If yes, check for OGR support */
-    if (strcasecmp(names[i], "SLD") == 0 || strcasecmp(names[i], "SLD_BODY") == 0)
-    {
-       sldenabled = msOWSLookupMetadata(&(map->web.metadata), "MO", "sld_enabled");
 
-       if (sldenabled == NULL)
-         sldenabled = "true";
 
-       if (ogrEnabled == 0)
-       {
-          msSetError(MS_WMSERR, "OGR support is not available.", "msWMSLoadGetMapParams()");
-          return msWMSException(map, nVersion, NULL, wms_exception_format);
-       }
-       else
-       {
-          if (strcasecmp(sldenabled, "true") == 0)
-          {
-            if (strcasecmp(names[i], "SLD") == 0)
-            {
-              sld_url =  values[i];
-            }
-            if (strcasecmp(names[i], "SLD_BODY") == 0)
-            {
-              sld_body =  values[i];
-            }
-          }
-       }
-    }
 
-    if (strcasecmp(names[i], "LAYERS") == 0)
-    {
+    if (strcasecmp(names[i], "LAYERS") == 0) {
       int  j, k, iLayer, *layerOrder;
-      
+      char ***nestedGroups = NULL;
+      int *numNestedGroups = NULL;
+      int *isUsedInNestedGroup = NULL;
+
       layerOrder = (int*)malloc(map->numlayers * sizeof(int));
       MS_CHECK_ALLOC(layerOrder, map->numlayers * sizeof(int), MS_FAILURE)
 
       layers = msStringSplit(values[i], ',', &numlayers);
       if (layers==NULL || strlen(values[i]) <=0 ||   numlayers < 1) {
-        msSetError(MS_WMSERR, "At least one layer name required in LAYERS.",
-                   "msWMSLoadGetMapParams()");
-        return msWMSException(map, nVersion, NULL, wms_exception_format);
+        numlayers = 0;
+        if (sld_url == NULL &&   sld_body == NULL) {
+          msFreeCharArray(layers,numlayers);
+          msFree(layerOrder);
+          msSetError(MS_WMSERR, "At least one layer name required in LAYERS.",
+                     "msWMSLoadGetMapParams()");
+          return msWMSException(map, nVersion, NULL, wms_exception_format);
+        }
       }
 
       if (nVersion >= OWS_1_3_0) {
         layerlimit = msOWSLookupMetadata(&(map->web.metadata), "MO", "layerlimit");
         if(layerlimit) {
           if (numlayers > atoi(layerlimit)) {
+            msFreeCharArray(layers,numlayers);
+            msFree(layerOrder);
             msSetError(MS_WMSERR, "Number of layers requested exceeds LayerLimit.",
-                     "msWMSLoadGetMapParams()");
+                       "msWMSLoadGetMapParams()");
             return msWMSException(map, nVersion, NULL, wms_exception_format);
           }
         }
       }
 
-      for (iLayer=0; iLayer < map->numlayers; iLayer++)
-      {
-          map->layerorder[iLayer] = iLayer;
-          layerOrder[iLayer] = 0;
+      for (iLayer=0; iLayer < map->numlayers; iLayer++) {
+        map->layerorder[iLayer] = iLayer;
+        layerOrder[iLayer] = 0;
       }
 
-      for(j=0; j<map->numlayers; j++)
-      {
+      for(j=0; j<map->numlayers; j++) {
         /* Keep only layers with status=DEFAULT by default */
         /* Layer with status DEFAULT is drawn first. */
         if (GET_LAYER(map, j)->status != MS_DEFAULT)
-           GET_LAYER(map, j)->status = MS_OFF;
-        else
-        {
-           map->layerorder[nLayerOrder++] = j;
-           layerOrder[j] = 1;
+          GET_LAYER(map, j)->status = MS_OFF;
+        else {
+          map->layerorder[nLayerOrder++] = j;
+          layerOrder[j] = 1;
         }
       }
 
-      for (k=0; k<numlayers; k++)
-      {
-          layerfound = 0;
-          for (j=0; j<map->numlayers; j++)
-          {
-              /* Turn on selected layers only. */
-              if ( ((GET_LAYER(map, j)->name &&
-                     strcasecmp(GET_LAYER(map, j)->name, layers[k]) == 0) ||
-                    (map->name && strcasecmp(map->name, layers[k]) == 0) ||
-                    (GET_LAYER(map, j)->group && strcasecmp(GET_LAYER(map, j)->group, layers[k]) == 0)) &&
-                   ((msIntegerInArray(GET_LAYER(map, j)->index, ows_request->enabled_layers, ows_request->numlayers))) )
-              {
-                  if (GET_LAYER(map, j)->status != MS_DEFAULT)
-                  {
-                     if (layerOrder[j] == 0)
-                     {
-                        map->layerorder[nLayerOrder++] = j;
-                        layerOrder[j] = 1;
-                        GET_LAYER(map, j)->status = MS_ON;
-                     }
-                  }
-                  validlayers++;
-                  layerfound = 1;
+      nestedGroups = (char***)msSmallCalloc(map->numlayers, sizeof(char**));
+      numNestedGroups = (int*)msSmallCalloc(map->numlayers, sizeof(int));
+      isUsedInNestedGroup = (int*)msSmallCalloc(map->numlayers, sizeof(int));
+      msWMSPrepareNestedGroups(map, nVersion, nestedGroups, numNestedGroups, isUsedInNestedGroup);
+
+      for (k=0; k<numlayers; k++) {
+        layerfound = 0;
+        for (j=0; j<map->numlayers; j++) {
+          /* Turn on selected layers only. */
+          if ( ((GET_LAYER(map, j)->name &&
+                 strcasecmp(GET_LAYER(map, j)->name, layers[k]) == 0) ||
+                (map->name && strcasecmp(map->name, layers[k]) == 0) ||
+                (GET_LAYER(map, j)->group && strcasecmp(GET_LAYER(map, j)->group, layers[k]) == 0) ||
+                ((numNestedGroups[j] >0) && msStringInArray(layers[k], nestedGroups[j], numNestedGroups[j]))) &&
+               ((msIntegerInArray(GET_LAYER(map, j)->index, ows_request->enabled_layers, ows_request->numlayers))) ) {
+            if (GET_LAYER(map, j)->status != MS_DEFAULT) {
+              if (layerOrder[j] == 0) {
+                map->layerorder[nLayerOrder++] = j;
+                layerOrder[j] = 1;
+                GET_LAYER(map, j)->status = MS_ON;
               }
+            }
+            validlayers++;
+            layerfound = 1;
           }
-          if (layerfound == 0)
-            invalidlayers++;
+        }
+        if (layerfound == 0 && numlayers>0)
+          invalidlayers++;
+
+      }
 
+      /* free the stuff used for nested layers */
+      for (k = 0; k < map->numlayers; k++) {
+        if (numNestedGroups[k] > 0) {
+          msFreeCharArray(nestedGroups[k], numNestedGroups[k]);
+        }
       }
+      free(nestedGroups);
+      free(numNestedGroups);
+      free(isUsedInNestedGroup);
 
       /* set all layers with status off at end of array */
-      for (j=0; j<map->numlayers; j++)
-      {
-         if (GET_LAYER(map, j)->status == MS_OFF)
-            if (layerOrder[j] == 0)
-               map->layerorder[nLayerOrder++] = j;
+      for (j=0; j<map->numlayers; j++) {
+        if (GET_LAYER(map, j)->status == MS_OFF)
+          if (layerOrder[j] == 0)
+            map->layerorder[nLayerOrder++] = j;
       }
-      
+
       free(layerOrder);
       msFreeCharArray(layers, numlayers);
-    }
-    else if (strcasecmp(names[i], "STYLES") == 0) {
-        styles = values[i];
+    } else if (strcasecmp(names[i], "STYLES") == 0) {
+      styles = values[i];
 
-    }
-    else if ((strcasecmp(names[i], "SRS") == 0 && nVersion < OWS_1_3_0) || 
-             (strcasecmp(names[i], "CRS") == 0 && nVersion >= OWS_1_3_0)) {
+    } else if ((strcasecmp(names[i], "SRS") == 0 && nVersion < OWS_1_3_0) ||
+               (strcasecmp(names[i], "CRS") == 0 && nVersion >= OWS_1_3_0)) {
       srsfound = 1;
       /* SRS is in format "EPSG:epsg_id" or "AUTO:proj_id,unit_id,lon0,lat0" */
-      if (strncasecmp(values[i], "EPSG:", 5) == 0)
-      {
+      if (strncasecmp(values[i], "EPSG:", 5) == 0) {
         /* SRS=EPSG:xxxx */
-        
-        /*don't need to copy init=xxx since the srsbudder is only
-          used with msLoadProjection and that does alreay the job*/
-        //snprintf(srsbuffer, 100, "init=epsg:%.20s", values[i]+5);
 
-        
+        /* don't need to copy init=xxx since the srsbudder is only
+           used with msLoadProjection and that does alreay the job */
+        /* snprintf(srsbuffer, 100, "init=epsg:%.20s", values[i]+5); */
+
+
         snprintf(srsbuffer, sizeof(srsbuffer), "EPSG:%.20s",values[i]+5);
         snprintf(epsgbuf, sizeof(epsgbuf), "EPSG:%.20s",values[i]+5);
-       
+
         /* This test was to correct a request by the OCG cite 1.3.0 test
          sending CRS=ESPG:4326,  Bug:*/
-        if (nVersion >= OWS_1_3_0)
-        {
-            if (srsbuffer[strlen(srsbuffer)-1] == ',')
-              srsbuffer[strlen(srsbuffer)-1] = '\0';
-            if (epsgbuf[strlen(epsgbuf)-1] == ',')
-              epsgbuf[strlen(epsgbuf)-1] = '\0';
-            
+        if (nVersion >= OWS_1_3_0) {
+          if (srsbuffer[strlen(srsbuffer)-1] == ',')
+            srsbuffer[strlen(srsbuffer)-1] = '\0';
+          if (epsgbuf[strlen(epsgbuf)-1] == ',')
+            epsgbuf[strlen(epsgbuf)-1] = '\0';
+
         }
 
         /* we need to wait until all params are read before */
@@ -588,9 +985,7 @@ int msWMSLoadGetMapParams(mapObj *map, int nVersion,
         if (iUnits != -1)
           map->units = iUnits;
         */
-      }
-      else if (strncasecmp(values[i], "AUTO:", 5) == 0 && nVersion < OWS_1_3_0)
-      {
+      } else if (strncasecmp(values[i], "AUTO:", 5) == 0 && nVersion < OWS_1_3_0) {
         snprintf(srsbuffer, sizeof(srsbuffer), "%s",  values[i]);
         /* SRS=AUTO:proj_id,unit_id,lon0,lat0 */
         /*
@@ -601,31 +996,23 @@ int msWMSLoadGetMapParams(mapObj *map, int nVersion,
         if (iUnits != -1)
           map->units = iUnits;
         */
+      } else if (nVersion >= OWS_1_3_0 && (strncasecmp(values[i], "AUTO2:", 6) == 0 ||
+                                           strncasecmp(values[i], "CRS:", 4) == 0)) {
+        snprintf(srsbuffer, sizeof(srsbuffer), "%s",  values[i]);
+      } else {
+        if (nVersion >= OWS_1_3_0) {
+          msSetError(MS_WMSERR,
+                     "Unsupported CRS namespace (only EPSG, AUTO2, CRS currently supported).",
+                     "msWMSLoadGetMapParams()");
+          return msWMSException(map, nVersion, "InvalidCRS", wms_exception_format);
+        } else {
+          msSetError(MS_WMSERR,
+                     "Unsupported SRS namespace (only EPSG and AUTO currently supported).",
+                     "msWMSLoadGetMapParams()");
+          return msWMSException(map, nVersion, "InvalidSRS", wms_exception_format);
+        }
       }
-      else if (nVersion >= OWS_1_3_0 && (strncasecmp(values[i], "AUTO2:", 6) == 0 ||
-                                         strncasecmp(values[i], "CRS:", 4) == 0))
-      {
-          snprintf(srsbuffer, sizeof(srsbuffer), "%s",  values[i]);
-      }
-      else
-      {
-          if (nVersion >= OWS_1_3_0)
-          {
-              msSetError(MS_WMSERR,
-                         "Unsupported CRS namespace (only EPSG, AUTO2, CRS currently supported).",
-                         "msWMSLoadGetMapParams()");
-              return msWMSException(map, nVersion, "InvalidCRS", wms_exception_format);
-          }
-          else
-          {
-              msSetError(MS_WMSERR,
-                         "Unsupported SRS namespace (only EPSG and AUTO currently supported).",
-                         "msWMSLoadGetMapParams()");
-              return msWMSException(map, nVersion, "InvalidSRS", wms_exception_format);
-          }
-      }
-    }
-    else if (strcasecmp(names[i], "BBOX") == 0) {
+    } else if (strcasecmp(names[i], "BBOX") == 0) {
       char **tokens;
       int n;
       bboxfound = 1;
@@ -635,88 +1022,73 @@ int msWMSLoadGetMapParams(mapObj *map, int nVersion,
                    "msWMSLoadGetMapParams()");
         return msWMSException(map, nVersion, NULL, wms_exception_format);
       }
-      bboxrequest = values[i];
+      map->extent.minx = atof(tokens[0]);
+      map->extent.miny = atof(tokens[1]);
+      map->extent.maxx = atof(tokens[2]);
+      map->extent.maxy = atof(tokens[3]);
 
+      msFreeCharArray(tokens, n);
+      
       /*for wms 1.3.0 we will do the validation of the bbox after all parameters
        are read to account for the axes order*/
-      if (nVersion < OWS_1_3_0)
-      {
-          map->extent.minx = atof(tokens[0]);
-          map->extent.miny = atof(tokens[1]);
-          map->extent.maxx = atof(tokens[2]);
-          map->extent.maxy = atof(tokens[3]);
+      if (nVersion < OWS_1_3_0) {
 
-          msFreeCharArray(tokens, n);
-
-          /* validate bbox values */
-          if ( map->extent.minx >= map->extent.maxx ||
-               map->extent.miny >=  map->extent.maxy)
-          {
-              msSetError(MS_WMSERR,
-                         "Invalid values for BBOX.",
-                         "msWMSLoadGetMapParams()");
-              return msWMSException(map, nVersion, NULL, wms_exception_format);
-          }
-          adjust_extent = MS_TRUE;
+        /* validate bbox values */
+        if ( map->extent.minx >= map->extent.maxx ||
+             map->extent.miny >=  map->extent.maxy) {
+          msSetError(MS_WMSERR,
+                     "Invalid values for BBOX.",
+                     "msWMSLoadGetMapParams()");
+          return msWMSException(map, nVersion, NULL, wms_exception_format);
+        }
+        adjust_extent = MS_TRUE;
       }
-    }
-    else if (strcasecmp(names[i], "WIDTH") == 0) {
+    } else if (strcasecmp(names[i], "WIDTH") == 0) {
       widthfound = 1;
       map->width = atoi(values[i]);
-    }
-    else if (strcasecmp(names[i], "HEIGHT") == 0) {
+    } else if (strcasecmp(names[i], "HEIGHT") == 0) {
       heightfound = 1;
       map->height = atoi(values[i]);
-    }
-    else if (strcasecmp(names[i], "FORMAT") == 0) {
+    } else if (strcasecmp(names[i], "FORMAT") == 0) {
       const char *format_list = NULL;
       formatfound = 1;
 
-      if (strcasecmp(values[i], "application/openlayers")!=0)
-      {
-          /*check to see if a predefined list is given*/
-          format_list = msOWSLookupMetadata(&(map->web.metadata), "M","getmap_formatlist");
-          if (format_list)
-          {
-              format = msOwsIsOutputFormatValid(map, values[i], &(map->web.metadata),
-                                                "M", "getmap_formatlist");
-              if (format == NULL &&
-                  strcasecmp(values[i], "application/openlayers")!=0)
-              {
-                  msSetError(MS_IMGERR,
-                             "Unsupported output format (%s).",
-                             "msWMSLoadGetMapParams()",
-                             values[i] );
-                  return msWMSException(map, nVersion, "InvalidFormat", wms_exception_format);
-              }
+      if (strcasecmp(values[i], "application/openlayers")!=0) {
+        /*check to see if a predefined list is given*/
+        format_list = msOWSLookupMetadata(&(map->web.metadata), "M","getmap_formatlist");
+        if (format_list) {
+          format = msOwsIsOutputFormatValid(map, values[i], &(map->web.metadata),
+                                            "M", "getmap_formatlist");
+          if (format == NULL) {
+            msSetError(MS_IMGERR,
+                       "Unsupported output format (%s).",
+                       "msWMSLoadGetMapParams()",
+                       values[i] );
+            return msWMSException(map, nVersion, "InvalidFormat", wms_exception_format);
           }
-          else
-          {
-              format = msSelectOutputFormat( map, values[i] );
-              if( format == NULL ||
-                  (strncasecmp(format->driver, "GD/", 3) != 0 &&
-                   strncasecmp(format->driver, "GDAL/", 5) != 0 && 
-                   strncasecmp(format->driver, "AGG/", 4) != 0 &&
-                   strncasecmp(format->driver, "CAIRO/", 6) != 0 &&
-                   strncasecmp(format->driver, "OGL/", 4) != 0 &&
-                   strncasecmp(format->driver, "KML", 3) != 0 &&
-                   strncasecmp(format->driver, "KMZ", 3) != 0))
-                  {
-                      msSetError(MS_IMGERR,
-                                 "Unsupported output format (%s).",
-                                 "msWMSLoadGetMapParams()",
-                                 values[i] );
-                      return msWMSException(map, nVersion, "InvalidFormat", wms_exception_format);
-                  }
+        } else {
+          format = msSelectOutputFormat( map, values[i] );
+          if( format == NULL ||
+              (strncasecmp(format->driver, "GD/", 3) != 0 &&
+               strncasecmp(format->driver, "GDAL/", 5) != 0 &&
+               strncasecmp(format->driver, "AGG/", 4) != 0 &&
+               strncasecmp(format->driver, "CAIRO/", 6) != 0 &&
+               strncasecmp(format->driver, "OGL/", 4) != 0 &&
+               strncasecmp(format->driver, "KML", 3) != 0 &&
+               strncasecmp(format->driver, "KMZ", 3) != 0)) {
+            msSetError(MS_IMGERR,
+                       "Unsupported output format (%s).",
+                       "msWMSLoadGetMapParams()",
+                       values[i] );
+            return msWMSException(map, nVersion, "InvalidFormat", wms_exception_format);
           }
+        }
       }
       msFree( map->imagetype );
       map->imagetype = msStrdup(values[i]);
-    }
-    else if (strcasecmp(names[i], "TRANSPARENT") == 0) {
+    } else if (strcasecmp(names[i], "TRANSPARENT") == 0) {
       transparent = (strcasecmp(values[i], "TRUE") == 0);
-    }
-    else if (strcasecmp(names[i], "BGCOLOR") == 0) {
+    } else if (strcasecmp(names[i], "BGCOLOR") == 0) {
       long c;
       c = strtol(values[i], NULL, 16);
       map->imagecolor.red = (c/0x10000)&0xff;
@@ -726,446 +1098,564 @@ int msWMSLoadGetMapParams(mapObj *map, int nVersion,
 
     /* value of time can be empty. We should look for a default value */
     /* see function msWMSApplyTime */
-    else if (strcasecmp(names[i], "TIME") == 0)/* &&  values[i]) */
-    {
-        stime = values[i];
-        timerequest = 1;
+    else if (strcasecmp(names[i], "TIME") == 0) { /* &&  values[i]) */
+      stime = values[i];
+      timerequest = 1;
     }
     /* Vendor-specific ANGLE param (for map rotation), added in ticket #3332,
      * also supported by GeoServer
      */
-    else if (strcasecmp(names[i], "ANGLE") == 0)
-    {
-        msMapSetRotation(map, atof(values[i]));
+    else if (strcasecmp(names[i], "ANGLE") == 0) {
+      msMapSetRotation(map, atof(values[i]));
     }
   }
 
-   /*validate the exception format WMS 1.3.0 section 7.3.3.11*/
-
-   if (nVersion >= OWS_1_3_0 && wms_exception_format != NULL)
-   {    
-       if (strcasecmp(wms_exception_format, "INIMAGE") != 0 &&
-           strcasecmp(wms_exception_format, "BLANK") != 0 &&
-           strcasecmp(wms_exception_format, "XML") != 0)
-       {
-           msSetError(MS_WMSERR,
-                      "Invalid format %s for the EXCEPTIONS parameter.",
-                      "msWMSLoadGetMapParams()",  wms_exception_format);
-           return msWMSException(map, nVersion, "InvalidFormat", wms_exception_format);
-       }
-   }
-   if (bboxfound && bboxrequest && nVersion >= OWS_1_3_0)
-   {
-       char **tokens;
-       int n;
-       rectObj rect;
-       projectionObj proj;
-       tokens = msStringSplit(bboxrequest, ',', &n);
-       
-       /*we have already validated that the request format when reding
-        the request parameters*/
-       rect.minx = atof(tokens[0]);
-       rect.miny = atof(tokens[1]);
-       rect.maxx = atof(tokens[2]);
-       rect.maxy = atof(tokens[3]);
-   
-       msFreeCharArray(tokens, n);
-
-       /*try to adjust the axes if necessary*/
-       if (strlen(srsbuffer) > 1)
-       {
-            msInitProjection(&proj);
-            if (msLoadProjectionStringEPSG(&proj, (char *)srsbuffer) == 0)
-            {
-                msAxisNormalizePoints( &proj, 1, &rect.minx, &rect.miny );
-                msAxisNormalizePoints( &proj, 1, &rect.maxx, &rect.maxy );
-            }
-            msFreeProjection( &proj );
-       }
-       /*if the CRS is AUTO2:auto_crs_id,factor,lon0,lat0,
-        we need to grab the factor patameter and use it with the bbox*/
-       if (strlen(srsbuffer) > 1 && strncasecmp(srsbuffer, "AUTO2:", 6) == 0)
-       {
-           char **args;
-           int numargs;
-           double factor;
-           args = msStringSplit(srsbuffer, ',', &numargs);
-           if (numargs == 4)
-           {
-               factor = atof(args[1]);
-               if (factor > 0 && factor != 1.0)
-               {
-                   rect.minx = rect.minx*factor;
-                   rect.miny = rect.miny*factor;
-                   rect.maxx = rect.maxx*factor;
-                   rect.maxx = rect.maxy*factor;
-               }
-           }
-           msFreeCharArray(args, numargs);
-       }
-
-       map->extent.minx = rect.minx;
-       map->extent.miny = rect.miny;
-       map->extent.maxx = rect.maxx;
-       map->extent.maxy = rect.maxy;
-
-       /* validate bbox values */
-       if ( map->extent.minx >= map->extent.maxx ||
-            map->extent.miny >=  map->extent.maxy)
-       {
-           msSetError(MS_WMSERR,
-                      "Invalid values for BBOX.",
-                      "msWMSLoadGetMapParams()");
-           return msWMSException(map, nVersion, NULL, wms_exception_format);
-       }
-       adjust_extent = MS_TRUE;
-   }
-   
+  /*validate the exception format WMS 1.3.0 section 7.3.3.11*/
+
+  if (nVersion >= OWS_1_3_0 && wms_exception_format != NULL) {
+    if (strcasecmp(wms_exception_format, "INIMAGE") != 0 &&
+        strcasecmp(wms_exception_format, "BLANK") != 0 &&
+        strcasecmp(wms_exception_format, "XML") != 0) {
+      msSetError(MS_WMSERR,
+                 "Invalid format %s for the EXCEPTIONS parameter.",
+                 "msWMSLoadGetMapParams()",  wms_exception_format);
+      return msWMSException(map, nVersion, "InvalidFormat", wms_exception_format);
+    }
+  }
+  if (bboxfound && nVersion >= OWS_1_3_0) {
+    rectObj rect;
+    projectionObj proj;
+
+    /*we have already validated that the request format when reding
+     the request parameters*/
+    rect = map->extent;
+
+    /*try to adjust the axes if necessary*/
+    if (strlen(srsbuffer) > 1) {
+      msInitProjection(&proj);
+      if (msLoadProjectionStringEPSG(&proj, (char *)srsbuffer) == 0) {
+        msAxisNormalizePoints( &proj, 1, &rect.minx, &rect.miny );
+        msAxisNormalizePoints( &proj, 1, &rect.maxx, &rect.maxy );
+      }
+      msFreeProjection( &proj );
+    }
+    /*if the CRS is AUTO2:auto_crs_id,factor,lon0,lat0,
+     we need to grab the factor patameter and use it with the bbox*/
+    if (strlen(srsbuffer) > 1 && strncasecmp(srsbuffer, "AUTO2:", 6) == 0) {
+      char **args;
+      int numargs;
+      double factor;
+      args = msStringSplit(srsbuffer, ',', &numargs);
+      if (numargs == 4) {
+        factor = atof(args[1]);
+        if (factor > 0 && factor != 1.0) {
+          rect.minx = rect.minx*factor;
+          rect.miny = rect.miny*factor;
+          rect.maxx = rect.maxx*factor;
+          rect.maxx = rect.maxy*factor;
+        }
+      }
+      msFreeCharArray(args, numargs);
+    }
+
+    map->extent = rect;
+
+    /* validate bbox values */
+    if ( map->extent.minx >= map->extent.maxx ||
+         map->extent.miny >=  map->extent.maxy) {
+      msSetError(MS_WMSERR,
+                 "Invalid values for BBOX.",
+                 "msWMSLoadGetMapParams()");
+      return msWMSException(map, nVersion, NULL, wms_exception_format);
+    }
+    adjust_extent = MS_TRUE;
+  }
+
   /*
   ** If any select layers have a default time, we will apply the default
   ** time value even if no TIME request was in the url.
   */
-  if( !timerequest && map )
-  {
-      for (i=0; i<map->numlayers && !timerequest; i++)
-      {
-          layerObj *lp = NULL;
+  if( !timerequest && map ) {
+    for (i=0; i<map->numlayers && !timerequest; i++) {
+      layerObj *lp = NULL;
 
-          lp = (GET_LAYER(map, i));
-          if (lp->status != MS_ON && lp->status != MS_DEFAULT)
-              continue;
+      lp = (GET_LAYER(map, i));
+      if (lp->status != MS_ON && lp->status != MS_DEFAULT)
+        continue;
 
-          if( msOWSLookupMetadata(&(lp->metadata), "MO", "timedefault") )
-              timerequest = 1;
-      }
+      if( msOWSLookupMetadata(&(lp->metadata), "MO", "timedefault") )
+        timerequest = 1;
+    }
   }
 
   /*
-  ** Apply time filters if available in the request.  
+  ** Apply time filters if available in the request.
   */
-  if (timerequest)
-  {
-      if (msWMSApplyTime(map, nVersion, stime, wms_exception_format) == MS_FAILURE)
-      {
-          return MS_FAILURE;/* msWMSException(map, nVersion, "InvalidTimeRequest"); */
+  if (timerequest) {
+    if (msWMSApplyTime(map, nVersion, stime, wms_exception_format) == MS_FAILURE) {
+      return MS_FAILURE;/* msWMSException(map, nVersion, "InvalidTimeRequest"); */
+    }
+  }
+
+  /*
+  ** Check/apply  wms dimensions
+  ** all dimension requests shoul start with dim_xxxx, except time and elevation.
+  */
+  for (i=0; i<map->numlayers; i++) {
+    layerObj *lp = NULL;
+    const char *dimensionlist = NULL;
+    char **tokens;
+    int ntokens=0,k;
+
+    lp = (GET_LAYER(map, i));
+    if (lp->status != MS_ON && lp->status != MS_DEFAULT)
+      continue;
+
+    dimensionlist = msOWSLookupMetadata(&(lp->metadata), "M", "dimensionlist");
+    /*
+    if (!dimensionlist)
+    dimensionlist = msOWSLookupMetadata(&(map->web.metadata), "M", "dimensionlist");
+    */
+    if (dimensionlist) {
+      tokens = msStringSplit(dimensionlist,  ',', &ntokens);
+      if (tokens && ntokens > 0) {
+        char *dimensionname=NULL;
+        char *stmp = NULL;
+        for (j=0; j<ntokens; j++) {
+          for(k=0; map && k<numentries; k++) {
+            if (strcasecmp(names[k], "elevation") == 0)
+              dimensionname = msStrdup(names[k]);
+            else {
+
+              /*
+                dimensionname = msStrdup("dim_");
+                dimensionname = msStringConcatenate(dimensionname, names[k]);
+              */
+              dimensionname = msStrdup(names[k]);
+            }
+
+            /*the dim_ is supposed to be part of the dimension name in the request*/
+            if (strcasecmp(tokens[j], "elevation") == 0)
+              stmp = msStrdup(tokens[j]);
+            else {
+              stmp =  msStrdup("dim_");
+              msStringTrim(tokens[j]);
+              stmp = msStringConcatenate(stmp, tokens[j]);
+            }
+            if (strcasecmp(dimensionname, stmp) == 0) {
+              if (!msWMSApplyDimension(lp, nVersion, dimensionname, values[k],
+                                       wms_exception_format)) {
+                msFreeCharArray(tokens, ntokens);
+                msFree(dimensionname);
+                msFree(stmp);
+
+                return msWMSException(lp->map, nVersion, "InvalidDimensionValue",  wms_exception_format);
+              }
+              msFree(dimensionname);
+              msFree(stmp);
+              break;
+            }
+            msFree(dimensionname);
+            msFree(stmp);
+          }
+        }
+        msFreeCharArray(tokens, ntokens);
       }
-  } 
+    }
+  }
+
   /*
   ** Apply the selected output format (if one was selected), and override
   ** the transparency if needed.
   */
 
   if( format != NULL )
-      msApplyOutputFormat( &(map->outputformat), format, transparent,
-                           MS_NOOVERRIDE, MS_NOOVERRIDE );
+    msApplyOutputFormat( &(map->outputformat), format, transparent,
+                         MS_NOOVERRIDE, MS_NOOVERRIDE );
 
-  /* Validate all layers given. 
+  /* Validate all layers given.
   ** If an invalid layer is sent, return an exception.
   */
-  if (validlayers == 0 || invalidlayers > 0)
-  {
-      msSetError(MS_WMSERR, "Invalid layer(s) given in the LAYERS parameter.",
+  if (validlayers == 0 || invalidlayers > 0) {
+    if (invalidlayers > 0) {
+      msSetError(MS_WMSERR, "Invalid layer(s) given in the LAYERS parameter. A layer might be disabled for \
+this request. Check wms/ows_enable_request settings.",
                  "msWMSLoadGetMapParams()");
       return msWMSException(map, nVersion, "LayerNotDefined", wms_exception_format);
+    }
+    if (validlayers == 0 && sld_url == NULL &&   sld_body == NULL) {
+      msSetError(MS_WMSERR, "Missing required parameter LAYERS", "msWMSLoadGetMapParams()");
+      return msWMSException(map, nVersion, "MissingParameterValue", wms_exception_format);
+    }
   }
 
   /* validate srs value: When the SRS parameter in a GetMap request contains a
-  ** SRS that is valid for some, but not all of the layers being requested, 
+  ** SRS that is valid for some, but not all of the layers being requested,
   ** then the server shall throw a Service Exception (code = "InvalidSRS").
   ** Validate first against epsg in the map and if no matching srs is found
   ** validate all layers requested.
   */
-  if (epsgbuf != NULL && strlen(epsgbuf) > 1)
-  {
-      epsgvalid = MS_FALSE;
-      projstring = msOWSGetEPSGProj(&(map->projection), &(map->web.metadata),
-                                    "MO", MS_FALSE);
-      if (projstring)
-      {
-          tokens = msStringSplit(projstring, ' ', &n);
-          if (tokens && n > 0)
-          {
-              for(i=0; i<n; i++)
-              {
-                  if (strcasecmp(tokens[i], epsgbuf) == 0)
-                  {
-                      epsgvalid = MS_TRUE;
-                      break;
-                  }
-              }
-              msFreeCharArray(tokens, n);
+  if (epsgbuf != NULL && strlen(epsgbuf) > 1) {
+    epsgvalid = MS_FALSE;
+    projstring = msOWSGetEPSGProj(&(map->projection), &(map->web.metadata),
+                                  "MO", MS_FALSE);
+    if (projstring) {
+      tokens = msStringSplit(projstring, ' ', &n);
+      if (tokens && n > 0) {
+        for(i=0; i<n; i++) {
+          if (strcasecmp(tokens[i], epsgbuf) == 0) {
+            epsgvalid = MS_TRUE;
+            break;
           }
+        }
+        msFreeCharArray(tokens, n);
       }
-      if (epsgvalid == MS_FALSE)
-      {
-          for (i=0; i<map->numlayers; i++)
-          {
-              epsgvalid = MS_FALSE;
-              if (GET_LAYER(map, i)->status == MS_ON)
-              {
-                  projstring = msOWSGetEPSGProj(&(GET_LAYER(map, i)->projection),
-                                                &(GET_LAYER(map, i)->metadata),
-                                                "MO", MS_FALSE);
-                  if (projstring)
-                  {
-                      tokens = msStringSplit(projstring, ' ', &n);
-                      if (tokens && n > 0)
-                      {
-                          for(j=0; j<n; j++)
-                          {
-                              if (strcasecmp(tokens[j], epsgbuf) == 0)
-                              {
-                                  epsgvalid = MS_TRUE;
-                                  break;
-                              }
-                          }
-                          msFreeCharArray(tokens, n);
-                      }
-                  }
-                  if (epsgvalid == MS_FALSE)
-                  {
-                      if (nVersion >= OWS_1_3_0)
-                      {
-                          msSetError(MS_WMSERR, "Invalid CRS given : CRS must be valid for all requested layers.",
-                                     "msWMSLoadGetMapParams()");
-                          return msWMSException(map, nVersion, "InvalidSRS", wms_exception_format);
-                      }
-                      else
-                      {
-                          msSetError(MS_WMSERR, "Invalid SRS given : SRS must be valid for all requested layers.",
-                                     "msWMSLoadGetMapParams()");
-                          return msWMSException(map, nVersion, "InvalidSRS", wms_exception_format);
-                      }
-                  }
+    }
+    if (epsgvalid == MS_FALSE) {
+      for (i=0; i<map->numlayers; i++) {
+        epsgvalid = MS_FALSE;
+        if (GET_LAYER(map, i)->status == MS_ON) {
+          projstring = msOWSGetEPSGProj(&(GET_LAYER(map, i)->projection),
+                                        &(GET_LAYER(map, i)->metadata),
+                                        "MO", MS_FALSE);
+          if (projstring) {
+            tokens = msStringSplit(projstring, ' ', &n);
+            if (tokens && n > 0) {
+              for(j=0; j<n; j++) {
+                if (strcasecmp(tokens[j], epsgbuf) == 0) {
+                  epsgvalid = MS_TRUE;
+                  break;
+                }
               }
+              msFreeCharArray(tokens, n);
+            }
           }
+          if (epsgvalid == MS_FALSE) {
+            if (nVersion >= OWS_1_3_0) {
+              msSetError(MS_WMSERR, "Invalid CRS given : CRS must be valid for all requested layers.",
+                         "msWMSLoadGetMapParams()");
+              return msWMSException(map, nVersion, "InvalidSRS", wms_exception_format);
+            } else {
+              msSetError(MS_WMSERR, "Invalid SRS given : SRS must be valid for all requested layers.",
+                         "msWMSLoadGetMapParams()");
+              return msWMSException(map, nVersion, "InvalidSRS", wms_exception_format);
+            }
+          }
+        }
       }
+    }
   }
 
-  /* Validate requested image size. 
+  /* Validate requested image size.
    */
   if(map->width > map->maxsize || map->height > map->maxsize ||
-     map->width < 1 || map->height < 1)
-  {
-      msSetError(MS_WMSERR, "Image size out of range, WIDTH and HEIGHT must be between 1 and %d pixels.", "msWMSLoadGetMapParams()", map->maxsize);
+      map->width < 1 || map->height < 1) {
+    msSetError(MS_WMSERR, "Image size out of range, WIDTH and HEIGHT must be between 1 and %d pixels.", "msWMSLoadGetMapParams()", map->maxsize);
 
-      /* Restore valid default values in case errors INIMAGE are used */
-      map->width = 400;
-      map->height= 300;
-      return msWMSException(map, nVersion, NULL, wms_exception_format);
+    /* Restore valid default values in case errors INIMAGE are used */
+    map->width = 400;
+    map->height= 300;
+    return msWMSException(map, nVersion, NULL, wms_exception_format);
   }
 
   /* Check whether requested BBOX and width/height result in non-square pixels
    */
   nonsquare_enabled = msTestConfigOption( map, "MS_NONSQUARE", MS_FALSE );
-  if (!nonsquare_enabled)
-  {
-      double dx, dy, reqy;
-      dx = MS_ABS(map->extent.maxx - map->extent.minx);
-      dy = MS_ABS(map->extent.maxy - map->extent.miny);
-
-      reqy = ((double)map->width) * dy / dx;
-
-      /* Allow up to 1 pixel of error on the width/height ratios. */
-      /* If more than 1 pixel then enable non-square pixels */
-      if ( MS_ABS((reqy - (double)map->height)) > 1.0 )
-      {
-          if (map->debug)
-              msDebug("msWMSLoadGetMapParams(): enabling non-square pixels.\n");
-          msSetConfigOption(map, "MS_NONSQUARE", "YES");
-          nonsquare_enabled = MS_TRUE;
-      }
+  if (!nonsquare_enabled) {
+    double dx, dy, reqy;
+    dx = MS_ABS(map->extent.maxx - map->extent.minx);
+    dy = MS_ABS(map->extent.maxy - map->extent.miny);
+
+    reqy = ((double)map->width) * dy / dx;
+
+    /* Allow up to 1 pixel of error on the width/height ratios. */
+    /* If more than 1 pixel then enable non-square pixels */
+    if ( MS_ABS((reqy - (double)map->height)) > 1.0 ) {
+      if (map->debug)
+        msDebug("msWMSLoadGetMapParams(): enabling non-square pixels.\n");
+      msSetConfigOption(map, "MS_NONSQUARE", "YES");
+      nonsquare_enabled = MS_TRUE;
+    }
   }
 
   /* If the requested SRS is different from the default mapfile projection, or
   ** if a BBOX resulting in non-square pixels is requested then
-  ** copy the original mapfile's projection to any layer that doesn't already 
-  ** have a projection. This will prevent problems when users forget to 
+  ** copy the original mapfile's projection to any layer that doesn't already
+  ** have a projection. This will prevent problems when users forget to
   ** explicitly set a projection on all layers in a WMS mapfile.
   */
-  if ((srsbuffer != NULL && strlen(srsbuffer) > 1) || nonsquare_enabled)
-  {
-      projectionObj newProj;
+  if ((srsbuffer != NULL && strlen(srsbuffer) > 1) || nonsquare_enabled) {
+    projectionObj newProj;
 
-      if (map->projection.numargs <= 0)
-      {
-          if (nVersion >= OWS_1_3_0)
-          {
-              msSetError(MS_WMSERR, "Cannot set new CRS on a map that doesn't "
-                         "have any projection set. Please make sure your mapfile "
-                         "has a projection defined at the top level.", 
-                         "msWMSLoadGetMapParams()");
-              return msWMSException(map, nVersion, "InvalidCRS", wms_exception_format);
-          }
-          else
-          {
-               msSetError(MS_WMSERR, "Cannot set new SRS on a map that doesn't "
-                         "have any projection set. Please make sure your mapfile "
-                         "has a projection defined at the top level.", 
-                         "msWMSLoadGetMapParams()");
-               return msWMSException(map, nVersion, "InvalidSRS", wms_exception_format);
-          }
+    if (map->projection.numargs <= 0) {
+      if (nVersion >= OWS_1_3_0) {
+        msSetError(MS_WMSERR, "Cannot set new CRS on a map that doesn't "
+                   "have any projection set. Please make sure your mapfile "
+                   "has a projection defined at the top level.",
+                   "msWMSLoadGetMapParams()");
+        return msWMSException(map, nVersion, "InvalidCRS", wms_exception_format);
+      } else {
+        msSetError(MS_WMSERR, "Cannot set new SRS on a map that doesn't "
+                   "have any projection set. Please make sure your mapfile "
+                   "has a projection defined at the top level.",
+                   "msWMSLoadGetMapParams()");
+        return msWMSException(map, nVersion, "InvalidSRS", wms_exception_format);
       }
-      
-      msInitProjection(&newProj);
-      if (srsbuffer != NULL && strlen(srsbuffer) > 1)
-      {
-          int nTmp;
-          
-          if (nVersion >= OWS_1_3_0)   
-            nTmp = msLoadProjectionStringEPSG(&newProj, srsbuffer);
-          else 
-            nTmp = msLoadProjectionString(&newProj, srsbuffer);
-          if (nTmp != 0)
-          { 
-              msFreeProjection(&newProj);
-              return msWMSException(map, nVersion, NULL, wms_exception_format);
-          }
+    }
+
+    msInitProjection(&newProj);
+    if (srsbuffer != NULL && strlen(srsbuffer) > 1) {
+      int nTmp;
+
+      if (nVersion >= OWS_1_3_0)
+        nTmp = msLoadProjectionStringEPSG(&newProj, srsbuffer);
+      else
+        nTmp = msLoadProjectionString(&newProj, srsbuffer);
+      if (nTmp != 0) {
+        msFreeProjection(&newProj);
+        return msWMSException(map, nVersion, NULL, wms_exception_format);
       }
+    }
 
-      if (nonsquare_enabled || 
-          msProjectionsDiffer(&(map->projection), &newProj))
-      {
-          char *original_srs = NULL;
-
-          for(i=0; i<map->numlayers; i++)
-          {
-              if (GET_LAYER(map, i)->projection.numargs <= 0 &&
-                  GET_LAYER(map, i)->status != MS_OFF &&
-                  GET_LAYER(map, i)->transform == MS_TRUE)
-              {
-                  /* This layer is turned on and needs a projection */
-
-                  /* Fetch main map projection string only now that we need it */
-                  if (original_srs == NULL)
-                      original_srs = msGetProjectionString(&(map->projection));
-
-                  if (msLoadProjectionString(&(GET_LAYER(map, i)->projection),
-                                             original_srs) != 0)
-                  {
-                      msFreeProjection(&newProj);
-                      return msWMSException(map, nVersion, NULL, wms_exception_format);
-                  }
-                  GET_LAYER(map, i)->project = MS_TRUE;
-              }
-          }
+    if (nonsquare_enabled ||
+        msProjectionsDiffer(&(map->projection), &newProj)) {
+      char *original_srs = NULL;
+
+      for(i=0; i<map->numlayers; i++) {
+        if (GET_LAYER(map, i)->projection.numargs <= 0 &&
+            GET_LAYER(map, i)->status != MS_OFF &&
+            GET_LAYER(map, i)->transform == MS_TRUE) {
+          /* This layer is turned on and needs a projection */
 
-          msFree(original_srs);
+          /* Fetch main map projection string only now that we need it */
+          if (original_srs == NULL)
+            original_srs = msGetProjectionString(&(map->projection));
+
+          if (msLoadProjectionString(&(GET_LAYER(map, i)->projection),
+                                     original_srs) != 0) {
+            msFreeProjection(&newProj);
+            return msWMSException(map, nVersion, NULL, wms_exception_format);
+          }
+          GET_LAYER(map, i)->project = MS_TRUE;
+        }
       }
 
-      msFreeProjection(&newProj);
+      msFree(original_srs);
+    }
+
+    msFreeProjection(&newProj);
   }
 
   /* apply the srs to the map file. This is only done after validating */
   /* that the srs given as parameter is valid for all layers */
-  if (srsbuffer != NULL && strlen(srsbuffer) > 1)
-  {
-      int nTmp;
-      msFreeProjection(&map->projection);
-      msInitProjection(&map->projection);
-      if (nVersion >= OWS_1_3_0)
-        nTmp = msLoadProjectionStringEPSG(&(map->projection), srsbuffer);
-      else
-        nTmp = msLoadProjectionString(&(map->projection), srsbuffer);
+  if (srsbuffer != NULL && strlen(srsbuffer) > 1) {
+    int nTmp;
+    msFreeProjection(&map->projection);
+    msInitProjection(&map->projection);
+    if (nVersion >= OWS_1_3_0)
+      nTmp = msLoadProjectionStringEPSG(&(map->projection), srsbuffer);
+    else
+      nTmp = msLoadProjectionString(&(map->projection), srsbuffer);
 
-      if (nTmp != 0)
-        return msWMSException(map, nVersion, NULL, wms_exception_format);
+    if (nTmp != 0)
+      return msWMSException(map, nVersion, NULL, wms_exception_format);
 
-      iUnits = GetMapserverUnitUsingProj(&(map->projection));
-      if (iUnits != -1)
-        map->units = iUnits;
+    iUnits = GetMapserverUnitUsingProj(&(map->projection));
+    if (iUnits != -1)
+      map->units = iUnits;
   }
 
-  /*apply sld if defined. This is done here so that bbox and srs are already applied*/
-  if (sld_url)
-  {
-      if ((status = msSLDApplySLDURL(map, sld_url, -1, NULL)) != MS_SUCCESS)
+  if (sld_url || sld_body) {
+    int nLayersBefore, nLayerAfter;
+    char request_tmp[32];
+    char *pszLayerNames = NULL;
+    nLayersBefore = map->numlayers;
+
+
+    /* -------------------------------------------------------------------- */
+    /*      if LAYERS parameter was not given, set all layers to off        */
+    /* -------------------------------------------------------------------- */
+    if (validlayers == 0) { /*no LAYERS parameter is give*/
+      for(j=0; j<map->numlayers; j++) {
+        if (GET_LAYER(map, j)->status != MS_DEFAULT)
+          GET_LAYER(map, j)->status = MS_OFF;
+      }
+    }
+
+
+    /*apply sld if defined. This is done here so that bbox and srs are already applied*/
+    if (sld_url) {
+      if ((status = msSLDApplySLDURL(map, sld_url, -1, NULL, &pszLayerNames)) != MS_SUCCESS)
         return msWMSException(map, nVersion, NULL, wms_exception_format);
-      
-  }
-  else if (sld_body)
-  {
-      if ((status =msSLDApplySLD(map, sld_body, -1, NULL)) != MS_SUCCESS)
+    } else if (sld_body) {
+      if ((status =msSLDApplySLD(map, sld_body, -1, NULL, &pszLayerNames)) != MS_SUCCESS)
         return msWMSException(map, nVersion, NULL, wms_exception_format);
+    }
+    /* -------------------------------------------------------------------- */
+    /*      SLD and styles can use the same layer multiple times. If        */
+    /*      that is the case we duplicate the layer for drawing             */
+    /*      purpose. We need to reset the ows request enable settings (#1602)*/
+    /* -------------------------------------------------------------------- */
+    nLayerAfter=map->numlayers;
+    if (nLayersBefore != nLayerAfter) {
+      strlcpy(request_tmp, "GetMap", sizeof(request_tmp));
+      msOWSRequestLayersEnabled(map, "M", request_tmp, ows_request);
+    }
+
+    /* -------------------------------------------------------------------- */
+    /*      We need to take into account where the LAYERS parameter was     */
+    /*      not given (the LAYERS is option when an SLD is given). In       */
+    /*      this particular case, we need to turn on the layers             */
+    /*      identified the SLD (#1166).                                     */
+    /*                                                                      */
+    /* -------------------------------------------------------------------- */
+    if (validlayers == 0) {
+      if (pszLayerNames) {
+        char **tokens;
+        int ntokens=0;
+        tokens = msStringSplit(pszLayerNames, ',', &ntokens);
+        if (ntokens >0) {
+          for (i=0; i<ntokens; i++) {
+            for (j=0; j<map->numlayers; j++) {
+              if ( ((GET_LAYER(map, j)->name &&
+                     strcasecmp(GET_LAYER(map, j)->name, tokens[i]) == 0) ||
+                    (map->name && strcasecmp(map->name, tokens[i]) == 0) ||
+                    (GET_LAYER(map, j)->group && strcasecmp(GET_LAYER(map, j)->group, tokens[i]) == 0)) &&
+                   ((msIntegerInArray(GET_LAYER(map, j)->index, ows_request->enabled_layers, ows_request->numlayers))) ) {
+                if (GET_LAYER(map, j)->status != MS_DEFAULT)
+                  GET_LAYER(map, j)->status = MS_ON;
+              }
+            }
+          }
+        }
+      }
+    }
+    msFree(pszLayerNames);
+
   }
   /* Validate Styles :
-  ** mapserv does not advertize any styles (the default styles are the
-  ** one that are used. So we are expecting here to have empty values
+  ** MapServer advertize styles through th group setting in a class object.
+  ** If no styles are set MapServer expects to have empty values
   ** for the styles parameter (...&STYLES=&...) Or for multiple Styles/Layers,
   ** we could have ...&STYLES=,,,. If that is not the
   ** case, we generate an exception.
   */
-  if(styles && strlen(styles) > 0)
-  {
-      char **tokens;
-      int n=0, i=0, k=0;
-      char **layers=NULL;
-      int numlayers =0;
-      layerObj *lp = NULL;
+  if(styles && strlen(styles) > 0) {
+    char **tokens;
+    int n=0, i=0, k=0, l=0,m=0;
+    char **layers=NULL;
+    int numlayers =0;
+    layerObj *lp = NULL;
 
-      tokens = msStringSplit(styles, ',' ,&n);
-      for (i=0; i<n; i++)
-      {
-          if (tokens[i] && strlen(tokens[i]) > 0 && 
-              strcasecmp(tokens[i],"default") != 0)
-          {
-              if (layers == NULL)
-              {
-                  for(j=0; j<numentries; j++)
-                  {     
-                      if (strcasecmp(names[j], "LAYERS") == 0)
-                      {
-                          layers = msStringSplit(values[j], ',', &numlayers);
-                      }
-                  }
+    tokens = msStringSplitComplex(styles, ",",&n,MS_ALLOWEMPTYTOKENS);
+    for (i=0; i<n; i++) {
+      if (tokens[i] && strlen(tokens[i]) > 0 &&
+          strcasecmp(tokens[i],"default") != 0) {
+        if (layers == NULL) {
+          int bLayerInserted = MS_FALSE;
+          char request_tmp[32];
+
+          for(j=0; j<numentries; j++) {
+            if (strcasecmp(names[j], "LAYERS") == 0) {
+              layers = msStringSplit(values[j], ',', &numlayers);
+            }
+          }
+          /* -------------------------------------------------------------------- */
+          /*      If the same layer is given more that once, we need to           */
+          /*      duplicate it.                                                   */
+          /* -------------------------------------------------------------------- */
+          if (layers && numlayers>0) {
+            for (m=0; m<numlayers; m++) {
+              layerObj *psTmpLayer=NULL;
+              int nIndex;
+              char tmpId[128];
+              for (l=0; l<numlayers; l++) {
+                nIndex = msGetLayerIndex(map, layers[m]);
+                if (m !=l && strcasecmp(layers[m], layers[l])== 0 &&
+                    nIndex != -1) {
+                  psTmpLayer = (layerObj *) malloc(sizeof(layerObj));
+                  initLayer(psTmpLayer, map);
+                  msCopyLayer(psTmpLayer, GET_LAYER(map,nIndex));
+                  /* open the source layer */
+                  if ( !psTmpLayer->vtable)
+                    msInitializeVirtualTable(psTmpLayer);
+
+                  /*make the name unique*/
+                  snprintf(tmpId, sizeof(tmpId), "%lx_%x_%d",(long)time(NULL),(int)getpid(),
+                           map->numlayers);
+                  if (psTmpLayer->name)
+                    msFree(psTmpLayer->name);
+                  psTmpLayer->name = strdup(tmpId);
+                  msFree(layers[l]);
+                  layers[l] = strdup(tmpId);
+                  msInsertLayer(map, psTmpLayer, -1);
+                  bLayerInserted =MS_TRUE;
+                  /* layer was copied, we need to decrement its refcount */
+                  MS_REFCNT_DECR(psTmpLayer);
+                }
               }
-              if (layers && numlayers == n)
-              {
-                  for (j=0; j<map->numlayers; j++)
-                  {
-                      if ((GET_LAYER(map, j)->name &&
-                           strcasecmp(GET_LAYER(map, j)->name, layers[i]) == 0) ||
-                          (map->name && strcasecmp(map->name, layers[i]) == 0) ||
-                          (GET_LAYER(map, j)->group && strcasecmp(GET_LAYER(map, j)->group, layers[i]) == 0))
-                      {
-                          lp =   GET_LAYER(map, j);
-                          for (k=0; k<lp->numclasses; k++)
-                          {
-                              if (lp->class[k]->group && strcasecmp(lp->class[k]->group, tokens[i]) == 0)
-                              {
-                                  if (lp->classgroup)
-                                    msFree(lp->classgroup);
-                                  lp->classgroup = msStrdup( tokens[i]);
-                                  break;
-                              }
-                          }
-                          if (k == lp->numclasses)
-                          {
-                              msSetError(MS_WMSERR, "Style (%s) not defined on layer.",
-                                         "msWMSLoadGetMapParams()", tokens[i]);
-                              msFreeCharArray(tokens, n);
-                              msFreeCharArray(layers, numlayers);
-                              
-                              return msWMSException(map, nVersion, "StyleNotDefined", wms_exception_format);
-                          }
-                      }
-                                     
-                  }
+            }
+          }
+
+          if (bLayerInserted) {
+            strlcpy(request_tmp, "GetMap", sizeof(request_tmp));
+            msOWSRequestLayersEnabled(map, "M", request_tmp, ows_request);
+          }
+
+        }
+        if (layers && numlayers == n) {
+          for (j=0; j<map->numlayers; j++) {
+            if ((GET_LAYER(map, j)->name &&
+                 strcasecmp(GET_LAYER(map, j)->name, layers[i]) == 0) ||
+                (GET_LAYER(map, j)->group && strcasecmp(GET_LAYER(map, j)->group, layers[i]) == 0)) {
+              lp =   GET_LAYER(map, j);
+              for (k=0; k<lp->numclasses; k++) {
+                if (lp->class[k]->group && strcasecmp(lp->class[k]->group, tokens[i]) == 0) {
+                  msFree(lp->classgroup);
+                  lp->classgroup = msStrdup( tokens[i]);
+                  break;
+                }
               }
-              else
-              {
-                  msSetError(MS_WMSERR, "Invalid style (%s). Mapserver is expecting an empty string for the STYLES : STYLES= or STYLES=,,, or using keyword default  STYLES=default,default, ...",
-                             "msWMSLoadGetMapParams()", styles);
-                  if (tokens && n > 0)
+              if (k == lp->numclasses) {
+                msSetError(MS_WMSERR, "Style (%s) not defined on layer.",
+                           "msWMSLoadGetMapParams()", tokens[i]);
+                msFreeCharArray(tokens, n);
+                msFreeCharArray(layers, numlayers);
+
+                return msWMSException(map, nVersion, "StyleNotDefined", wms_exception_format);
+              }
+            /* Check the style of the root layer */
+            } else if (map->name && strcasecmp(map->name, layers[i]) == 0) {
+                const char *styleName = NULL;
+                char *pszEncodedStyleName = NULL;
+                styleName = msOWSLookupMetadata(&(map->web.metadata), "MO", "style_name");
+                if (styleName == NULL)
+                  styleName = "default";
+                pszEncodedStyleName = msEncodeHTMLEntities(styleName);
+                if (strcasecmp(pszEncodedStyleName, tokens[i]) != 0) {
+                    msSetError(MS_WMSERR, "Style (%s) not defined on root layer.",
+                               "msWMSLoadGetMapParams()", tokens[i]);
                     msFreeCharArray(tokens, n);
-                  if (layers && numlayers > 0)
                     msFreeCharArray(layers, numlayers);
-                  return msWMSException(map, nVersion, "StyleNotDefined", wms_exception_format);
-              }
+                    msFree(pszEncodedStyleName);
+
+                    return msWMSException(map, nVersion, "StyleNotDefined", wms_exception_format);
+                }
+                msFree(pszEncodedStyleName);
+            }
+
           }
+        } else {
+          msSetError(MS_WMSERR, "Invalid style (%s). Mapserver is expecting an empty string for the STYLES : STYLES= or STYLES=,,, or using keyword default  STYLES=default,default, ...",
+                     "msWMSLoadGetMapParams()", styles);
+          msFreeCharArray(tokens, n);
+          msFreeCharArray(layers, numlayers);
+          return msWMSException(map, nVersion, "StyleNotDefined", wms_exception_format);
+        }
       }
-      if (tokens && n > 0)
-        msFreeCharArray(tokens, n);
+    }
+    msFreeCharArray(tokens, n);
+    msFreeCharArray(layers, numlayers);
   }
 
   /*
@@ -1174,22 +1664,20 @@ int msWMSLoadGetMapParams(mapObj *map, int nVersion,
   ** in by half a pixel.  We wait till here because we want to ensure we
   ** are doing this in terms of the correct WIDTH and HEIGHT.
   */
-  if( adjust_extent )
-  {
-      double	dx, dy;
+  if( adjust_extent ) {
+    double  dx, dy;
 
-      dx = (map->extent.maxx - map->extent.minx) / map->width;
-      map->extent.minx += dx*0.5;
-      map->extent.maxx -= dx*0.5;
+    dx = (map->extent.maxx - map->extent.minx) / map->width;
+    map->extent.minx += dx*0.5;
+    map->extent.maxx -= dx*0.5;
 
-      dy = (map->extent.maxy - map->extent.miny) / map->height;
-      map->extent.miny += dy*0.5;
-      map->extent.maxy -= dy*0.5;
+    dy = (map->extent.maxy - map->extent.miny) / map->height;
+    map->extent.miny += dy*0.5;
+    map->extent.maxy -= dy*0.5;
   }
 
   if (request && strcasecmp(request, "DescribeLayer") != 0) {
-    if (srsfound == 0)
-    {
+    if (srsfound == 0) {
       if ( nVersion >= OWS_1_3_0)
         msSetError(MS_WMSERR, "Missing required parameter CRS", "msWMSLoadGetMapParams()");
       else
@@ -1198,30 +1686,26 @@ int msWMSLoadGetMapParams(mapObj *map, int nVersion,
       return msWMSException(map, nVersion, "MissingParameterValue", wms_exception_format);
     }
 
-    if (bboxfound == 0)
-    {
+    if (bboxfound == 0) {
       msSetError(MS_WMSERR, "Missing required parameter BBOX", "msWMSLoadGetMapParams()");
       return msWMSException(map, nVersion, "MissingParameterValue", wms_exception_format);
-    }  
+    }
 
-    if (formatfound == 0 && (strcasecmp(request, "GetMap") == 0 || strcasecmp(request, "map") == 0))
-    {
+    if (formatfound == 0 && (strcasecmp(request, "GetMap") == 0 || strcasecmp(request, "map") == 0)) {
       msSetError(MS_WMSERR, "Missing required parameter FORMAT", "msWMSLoadGetMapParams()");
       return msWMSException(map, nVersion, "MissingParameterValue", wms_exception_format);
     }
 
-    if (widthfound == 0)
-    {
+    if (widthfound == 0) {
       msSetError(MS_WMSERR, "Missing required parameter WIDTH", "msWMSLoadGetMapParams()");
       return msWMSException(map, nVersion, "MissingParameterValue", wms_exception_format);
     }
 
-    if (heightfound == 0)
-    {
+    if (heightfound == 0) {
       msSetError(MS_WMSERR, "Missing required parameter HEIGHT", "msWMSLoadGetMapParams()");
       return msWMSException(map, nVersion, "MissingParameterValue", wms_exception_format);
     }
-  
+
   }
 
   return MS_SUCCESS;
@@ -1231,7 +1715,7 @@ int msWMSLoadGetMapParams(mapObj *map, int nVersion,
 **
 */
 static void msWMSPrintRequestCap(int nVersion, const char *request,
-                              const char *script_url, const char *formats, ...)
+                                 const char *script_url, const char *formats, ...)
 {
   va_list argp;
   const char *fmt;
@@ -1242,24 +1726,21 @@ static void msWMSPrintRequestCap(int nVersion, const char *request,
   /* We expect to receive a NULL-terminated args list of formats */
   va_start(argp, formats);
   fmt = formats;
-  while(fmt != NULL)
-  {
-      /* Special case for early WMS with subelements in Format (bug 908) */
-      if( nVersion <= OWS_1_0_7 )
-      {
-          encoded = msStrdup( fmt );
-      }
+  while(fmt != NULL) {
+    /* Special case for early WMS with subelements in Format (bug 908) */
+    if( nVersion <= OWS_1_0_7 ) {
+      encoded = msStrdup( fmt );
+    }
 
-      /* otherwise we HTML code special characters */
-      else
-      {
-          encoded = msEncodeHTMLEntities(fmt);
-      }
+    /* otherwise we HTML code special characters */
+    else {
+      encoded = msEncodeHTMLEntities(fmt);
+    }
 
-      msIO_printf("      <Format>%s</Format>\n", encoded);
-      msFree(encoded);
+    msIO_printf("      <Format>%s</Format>\n", encoded);
+    msFree(encoded);
 
-      fmt = va_arg(argp, const char *);
+    fmt = va_arg(argp, const char *);
   }
   va_end(argp);
 
@@ -1281,79 +1762,74 @@ static void msWMSPrintRequestCap(int nVersion, const char *request,
 
 
 
-void msWMSPrintAttribution(FILE *stream, const char *tabspace, 
+void msWMSPrintAttribution(FILE *stream, const char *tabspace,
                            hashTableObj *metadata,
                            const char *namespaces)
 {
-    const char *title, *onlineres, *logourl;
-    char * pszEncodedValue=NULL;
-
-    if (stream && metadata)
-    {
-        title = msOWSLookupMetadata(metadata, "MO", 
-                                  "attribution_title");
-        onlineres = msOWSLookupMetadata(metadata, "MO", 
-                                  "attribution_onlineresource");
-        logourl = msOWSLookupMetadata(metadata, "MO", 
+  const char *title, *onlineres, *logourl;
+  char * pszEncodedValue=NULL;
+
+  if (stream && metadata) {
+    title = msOWSLookupMetadata(metadata, "MO",
+                                "attribution_title");
+    onlineres = msOWSLookupMetadata(metadata, "MO",
+                                    "attribution_onlineresource");
+    logourl = msOWSLookupMetadata(metadata, "MO",
                                   "attribution_logourl_width");
 
-        if (title || onlineres || logourl)
-        {
-            msIO_printf("%s<Attribution>\n",tabspace);
-            if (title)
-            {
-                pszEncodedValue = msEncodeHTMLEntities(title);
-                msIO_fprintf(stream, "%s%s<Title>%s</Title>\n", tabspace,
-                             tabspace, pszEncodedValue);
-                free(pszEncodedValue);
-            }
+    if (title || onlineres || logourl) {
+      msIO_printf("%s<Attribution>\n",tabspace);
+      if (title) {
+        pszEncodedValue = msEncodeHTMLEntities(title);
+        msIO_fprintf(stream, "%s%s<Title>%s</Title>\n", tabspace,
+                     tabspace, pszEncodedValue);
+        free(pszEncodedValue);
+      }
 
-            if (onlineres)
-            {
-                pszEncodedValue = msEncodeHTMLEntities(onlineres);
-                msIO_fprintf(stream, "%s%s<OnlineResource xmlns:xlink=\"http://www.w3.org/1999/xlink\" xlink:href=\"%s\"/>\n", tabspace, tabspace,
-                             pszEncodedValue);
-                free(pszEncodedValue);
-            }
-         
-            if (logourl)
-            {
-                msOWSPrintURLType(stream, metadata, "MO","attribution_logourl",
-                                  OWS_NOERR, NULL, "LogoURL", NULL,
-                                  " width=\"%s\"", " height=\"%s\"",
-                                  ">\n             <Format>%s</Format",
-                                  "\n             <OnlineResource "
-                                  "xmlns:xlink=\"http://www.w3.org/1999/xlink\""
-                                  " xlink:type=\"simple\" xlink:href=\"%s\"/>\n"
-                                  "          ",
-                                  MS_FALSE, MS_TRUE, MS_TRUE, MS_TRUE, MS_TRUE,
-                                  NULL, NULL, NULL, NULL, NULL, "        ");
+      if (onlineres) {
+        pszEncodedValue = msEncodeHTMLEntities(onlineres);
+        msIO_fprintf(stream, "%s%s<OnlineResource xmlns:xlink=\"http://www.w3.org/1999/xlink\" xlink:href=\"%s\"/>\n", tabspace, tabspace,
+                     pszEncodedValue);
+        free(pszEncodedValue);
+      }
 
-                
-            }
-            msIO_printf("%s</Attribution>\n", tabspace);
+      if (logourl) {
+        msOWSPrintURLType(stream, metadata, "MO","attribution_logourl",
+                          OWS_NOERR, NULL, "LogoURL", NULL,
+                          " width=\"%s\"", " height=\"%s\"",
+                          ">\n             <Format>%s</Format",
+                          "\n             <OnlineResource "
+                          "xmlns:xlink=\"http://www.w3.org/1999/xlink\""
+                          " xlink:type=\"simple\" xlink:href=\"%s\"/>\n"
+                          "          ",
+                          MS_FALSE, MS_TRUE, MS_TRUE, MS_TRUE, MS_TRUE,
+                          NULL, NULL, NULL, NULL, NULL, "        ");
+
+
+      }
+      msIO_printf("%s</Attribution>\n", tabspace);
 
-        }
     }
+  }
 }
-          
+
 
 /*
 ** msWMSPrintScaleHint()
 **
 ** Print a Min/MaxScaleDenominator tag for the layer if applicable.
-** used for WMS >=1.3.0 
+** used for WMS >=1.3.0
 */
 void msWMSPrintScaleDenominator(const char *tabspace, double minscaledenom,
                                 double maxscaledenom)
 {
-    if (minscaledenom > 0)
-      msIO_printf("%s<MinScaleDenominator>%g</MinScaleDenominator>\n",
-                  tabspace, minscaledenom);
-    
-    if (maxscaledenom > 0)
-      msIO_printf("%s<MaxScaleDenominator>%g</MaxScaleDenominator>\n",
-                  tabspace, maxscaledenom);
+  if (minscaledenom > 0)
+    msIO_printf("%s<MinScaleDenominator>%g</MinScaleDenominator>\n",
+                tabspace, minscaledenom);
+
+  if (maxscaledenom > 0)
+    msIO_printf("%s<MaxScaleDenominator>%g</MaxScaleDenominator>\n",
+                tabspace, maxscaledenom);
 }
 
 
@@ -1380,554 +1856,729 @@ void msWMSPrintScaleHint(const char *tabspace, double minscaledenom,
   if (maxscaledenom > 0)
     scalehintmax = diag*(maxscaledenom/resolution)/msInchesPerUnit(MS_METERS,0);
 
-  if (scalehintmin > 0.0 || scalehintmax > 0.0)
-  {
-      msIO_printf("%s<ScaleHint min=\"%.15g\" max=\"%.15g\" />\n",
-             tabspace, scalehintmin, scalehintmax);
-      if (scalehintmax == 0.0)
-          msIO_printf("%s<!-- WARNING: Only MINSCALEDENOM and no MAXSCALEDENOM specified in "
-                 "the mapfile. A default value of 0 has been returned for the "
-                 "Max ScaleHint but this is probably not what you want. -->\n",
-                 tabspace);
+  if (scalehintmin > 0.0 || scalehintmax > 0.0) {
+    msIO_printf("%s<ScaleHint min=\"%.15g\" max=\"%.15g\" />\n",
+                tabspace, scalehintmin, scalehintmax);
+    if (scalehintmax == 0.0)
+      msIO_printf("%s<!-- WARNING: Only MINSCALEDENOM and no MAXSCALEDENOM specified in "
+                  "the mapfile. A default value of 0 has been returned for the "
+                  "Max ScaleHint but this is probably not what you want. -->\n",
+                  tabspace);
   }
 }
 
-
 /*
-** msDumpLayer()
+** msWMSPrintAuthorityURL()
+**
+** Print an AuthorityURL tag if applicable.
 */
-int msDumpLayer(mapObj *map, layerObj *lp, int nVersion, const char *script_url_encoded, const char *indent)
+void msWMSPrintAuthorityURL(FILE *stream, const char *tabspace,
+                            hashTableObj *metadata, const char *namespaces)
 {
-   rectObj ext;
-   const char *value;
-   const char *pszWmsTimeExtent, *pszWmsTimeDefault= NULL, *pszStyle=NULL;
-   const char *pszLegendURL=NULL;
-   char *pszMetadataName=NULL, *mimetype=NULL;
-   char **classgroups = NULL;
-   int iclassgroups=0 ,j=0;
-   char szVersionBuf[OWS_VERSION_MAXLEN];
-   size_t bufferSize = 0;
-
-   /* if the layer status is set to MS_DEFAULT, output a warning */
-   if (lp->status == MS_DEFAULT)
-     msIO_fprintf(stdout, "<!-- WARNING: This layer has its status set to DEFAULT and will always be displayed when doing a GetMap request even if it is not requested by the client. This is not in line with the expected behavior of a WMS server. Using status ON or OFF is recommended. -->\n");
- 
-   if (nVersion <= OWS_1_0_7)
-   {
-       msIO_printf("%s    <Layer queryable=\"%d\">\n",
-              indent, msIsLayerQueryable(lp));
-   }
-   else
-   {
-       /* 1.1.0 and later: opaque and cascaded are new. */
-       int cascaded=0, opaque=0;
-       if ((value = msOWSLookupMetadata(&(lp->metadata), "MO", "opaque")) != NULL)
-           opaque = atoi(value);
-       if (lp->connectiontype == MS_WMS)
-           cascaded = 1;
-
-       msIO_printf("%s    <Layer queryable=\"%d\" opaque=\"%d\" cascaded=\"%d\">\n",
-              indent, msIsLayerQueryable(lp), opaque, cascaded);
-   }
-   
-   if (lp->name && strlen(lp->name) > 0 &&
-       (msIsXMLTagValid(lp->name) == MS_FALSE || isdigit(lp->name[0])))
-     msIO_fprintf(stdout, "<!-- WARNING: The layer name '%s' might contain spaces or "
-                        "invalid characters or may start with a number. This could lead to potential problems. -->\n", 
-                  lp->name);
-   msOWSPrintEncodeParam(stdout, "LAYER.NAME", lp->name, OWS_NOERR,
-                         "        <Name>%s</Name>\n", NULL);
-
-   /* the majority of this section is dependent on appropriately named metadata in the LAYER object */
-   msOWSPrintEncodeMetadata(stdout, &(lp->metadata), "MO", "title",
-                            OWS_WARN, "        <Title>%s</Title>\n", lp->name);
-
-   msOWSPrintEncodeMetadata(stdout, &(lp->metadata), "MO", "abstract",
-                         OWS_NOERR, "        <Abstract>%s</Abstract>\n", NULL);
-
-   if (nVersion == OWS_1_0_0)
-   {
-       /* <Keywords> in V 1.0.0 */
-       /* The 1.0.0 spec doesn't specify which delimiter to use so let's use spaces */
-       msOWSPrintEncodeMetadataList(stdout, &(lp->metadata), "MO",
-                                    "keywordlist",
-                                    "        <Keywords>",
-                                    "        </Keywords>\n",
-                                    "%s ", NULL);
-   }
-   else
-   {
-       /* <KeywordList><Keyword> ... in V1.0.6+ */
-       msOWSPrintEncodeMetadataList(stdout, &(lp->metadata), "MO",
-                                    "keywordlist",
-                                    "        <KeywordList>\n",
-                                    "        </KeywordList>\n",
-                                    "          <Keyword>%s</Keyword>\n", NULL);
-   }
-
-   if (msOWSGetEPSGProj(&(map->projection),&(map->web.metadata),
-                        "MO", MS_FALSE) == NULL)
-   {
-       /* If map has no proj then every layer MUST have one or produce a warning */
-       if (nVersion > OWS_1_1_0)
-       {
-           /* starting 1.1.1 SRS are given in individual tags */
-           if (nVersion >= OWS_1_3_0)
-             msOWSPrintEncodeParamList(stdout, "(at least one of) "
-                                       "MAP.PROJECTION, LAYER.PROJECTION "
-                                       "or wms_srs metadata", 
-                                       msOWSGetEPSGProj(&(lp->projection), 
-                                                      &(lp->metadata),
-                                                      "MO", MS_FALSE),
-                                     OWS_WARN, ' ', NULL, NULL, 
-                                     "        <CRS>%s</CRS>\n", NULL);
-           else
-             msOWSPrintEncodeParamList(stdout, "(at least one of) "
-                                       "MAP.PROJECTION, LAYER.PROJECTION "
-                                       "or wms_srs metadata", 
-                                       msOWSGetEPSGProj(&(lp->projection), 
-                                                      &(lp->metadata),
-                                                      "MO", MS_FALSE),
-                                     OWS_WARN, ' ', NULL, NULL, 
-                                     "        <SRS>%s</SRS>\n", NULL);
-       }
-       else
-         msOWSPrintEncodeParam(stdout, "(at least one of) MAP.PROJECTION, "
-                               "LAYER.PROJECTION or wms_srs metadata",
-                               msOWSGetEPSGProj(&(lp->projection),
-                                                &(lp->metadata), "MO", MS_FALSE),
-                               OWS_WARN, "        <SRS>%s</SRS>\n", NULL);
-   }
-   else
-   {
-       /* No warning required in this case since there's at least a map proj. */
-       if (nVersion > OWS_1_1_0)
-       {
-           /* starting 1.1.1 SRS are given in individual tags */
-           if (nVersion >=  OWS_1_3_0)
-             msOWSPrintEncodeParamList(stdout, "(at least one of) "
-                                     "MAP.PROJECTION, LAYER.PROJECTION "
-                                     "or wms_srs metadata", 
-                                     msOWSGetEPSGProj(&(lp->projection), 
-                                                      &(lp->metadata),
-                                                      "MO", MS_FALSE),
-                                     OWS_NOERR, ' ', NULL, NULL, 
-                                     "        <CRS>%s</CRS>\n", NULL);
-           else
-             msOWSPrintEncodeParamList(stdout, "(at least one of) "
-                                     "MAP.PROJECTION, LAYER.PROJECTION "
-                                     "or wms_srs metadata", 
-                                     msOWSGetEPSGProj(&(lp->projection), 
-                                                      &(lp->metadata),
-                                                      "MO", MS_FALSE),
-                                     OWS_NOERR, ' ', NULL, NULL, 
-                                     "        <SRS>%s</SRS>\n", NULL);
-       }
-       else
-         msOWSPrintEncodeParam(stdout,
-                               " LAYER.PROJECTION (or wms_srs metadata)",
-                               msOWSGetEPSGProj(&(lp->projection),
-                                                &(lp->metadata),"MO",MS_FALSE),
-                               OWS_NOERR, "        <SRS>%s</SRS>\n", NULL);
-   }
-
-   /* If layer has no proj set then use map->proj for bounding box. */
-   if (msOWSGetLayerExtent(map, lp, "MO", &ext) == MS_SUCCESS)
-   {
-       if(lp->projection.numargs > 0)
-       {
-           if (nVersion >= OWS_1_3_0)
-             msOWSPrintEX_GeographicBoundingBox(stdout, "    ", &(ext),
-                                                &(lp->projection));
-           else
-             msOWSPrintLatLonBoundingBox(stdout, "        ", &(ext),
-                                         &(lp->projection), NULL, OWS_WMS);
-
-           msOWSPrintBoundingBox( stdout,"        ", &(ext), &(lp->projection),
-                                  &(lp->metadata), &(map->web.metadata), "MO", nVersion );
-       }
-       else
-       {
-           if (nVersion >= OWS_1_3_0)
-             msOWSPrintEX_GeographicBoundingBox(stdout, "    ", &(ext),
-                                                &(map->projection));
-           else
-              msOWSPrintLatLonBoundingBox(stdout, "        ", &(ext),
-                                         &(map->projection), NULL, OWS_WMS);
-           msOWSPrintBoundingBox(stdout,"        ", &(ext), &(map->projection),
-                                 &(lp->metadata), &(map->web.metadata), "MO", nVersion );
-       }
-   }
-   else
-   {
-       if (nVersion >= OWS_1_3_0)
-         msIO_printf("        <!-- WARNING: Optional Ex_GeographicBoundingBox could not be established for this layer.  Consider setting the EXTENT in the LAYER object, or wms_extent metadata. Also check that your data exists in the DATA statement -->\n");
-       else
-         msIO_printf("        <!-- WARNING: Optional LatLonBoundingBox could not be established for this layer.  Consider setting the EXTENT in the LAYER object, or wms_extent metadata. Also check that your data exists in the DATA statement -->\n");
-   }
-
-   /* time support */
-   pszWmsTimeExtent = msOWSLookupMetadata(&(lp->metadata), "MO", "timeextent");
-   if (pszWmsTimeExtent)
-   {
-       pszWmsTimeDefault = msOWSLookupMetadata(&(lp->metadata),  "MO",
-                                               "timedefault");
-
-       if (nVersion >= OWS_1_3_0) {
-         if (pszWmsTimeDefault)
-           msIO_fprintf(stdout, "        <Dimension name=\"time\" units=\"ISO8601\" default=\"%s\" nearestValue=\"0\">%s</Dimension>\n",pszWmsTimeDefault, pszWmsTimeExtent);
-         else
-           msIO_fprintf(stdout, "        <Dimension name=\"time\" units=\"ISO8601\" nearestValue=\"0\">%s</Dimension>\n",pszWmsTimeExtent);
-       }
-
-       else {
-         msIO_fprintf(stdout, "        <Dimension name=\"time\" units=\"ISO8601\"/>\n");
-         if (pszWmsTimeDefault)
-           msIO_fprintf(stdout, "        <Extent name=\"time\" default=\"%s\" nearestValue=\"0\">%s</Extent>\n",pszWmsTimeDefault, pszWmsTimeExtent);
-         else
-           msIO_fprintf(stdout, "        <Extent name=\"time\" nearestValue=\"0\">%s</Extent>\n",pszWmsTimeExtent);
-       }
-   }
+  const char *pszWmsAuthorityName;
+  const char *pszWMSAuthorityHref;
+  char *pszTemplateName=NULL, *pszTemplateHref=NULL;
 
-  if (nVersion >= OWS_1_0_7) {
-    msWMSPrintAttribution(stdout, "    ", &(lp->metadata), "MO");
-  }
-
-  /* AuthorityURL support and Identifier support, only available > WMS 1.1.0 */
-  if(nVersion >= OWS_1_1_0)
-  {
-    const char *pszWmsAuthorityName = msOWSLookupMetadata(&(lp->metadata), "MO", "authorityurl_name");
-    const char *pszWMSAuthorityHref = msOWSLookupMetadata(&(lp->metadata), "MO", "authorityurl_href");
-    const char *pszWMSIdentifierAuthority = msOWSLookupMetadata(&(lp->metadata), "MO", "identifier_authority");
-    const char *pszWMSIdentifierValue = msOWSLookupMetadata(&(lp->metadata), "MO", "identifier_value");
+  if (stream && metadata) {
+    pszWmsAuthorityName = msOWSLookupMetadata(metadata, namespaces, "authorityurl_name");
+    pszWMSAuthorityHref = msOWSLookupMetadata(metadata, namespaces, "authorityurl_href");
 
     /* AuthorityURL only makes sense if you have *both* the name and url */
-    if( pszWmsAuthorityName && pszWMSAuthorityHref )
-    {
-       msOWSPrintEncodeMetadata(stdout, &(lp->metadata), "MO", "authorityurl_name",
-                                OWS_NOERR, "        <AuthorityURL name=\"%s\">\n",
-                                NULL);
-       msOWSPrintEncodeMetadata(stdout, &(lp->metadata), "MO", "authorityurl_href",
-                                OWS_NOERR, "          <OnlineResource xmlns:xlink=\"http://www.w3.org/1999/xlink\" xlink:href=\"%s\"/>\n",
-                                NULL);
-       msIO_printf("        </AuthorityURL>\n");
-    }
-    else if ( pszWmsAuthorityName || pszWMSAuthorityHref )
-    {
-       msIO_printf("        <!-- WARNING: Both wms_authorityurl_name and wms_authorityurl_href must be set to output an AuthorityURL -->\n");
+    if( pszWmsAuthorityName && pszWMSAuthorityHref ) {
+      pszTemplateName = msStringConcatenate(msStrdup(tabspace), "<AuthorityURL name=\"%s\">\n");
+      msOWSPrintEncodeMetadata(stream, metadata, namespaces, "authorityurl_name",
+                               OWS_NOERR, pszTemplateName,
+                               NULL);
+      pszTemplateHref = msStringConcatenate(msStrdup(tabspace), "  <OnlineResource xmlns:xlink=\"http://www.w3.org/1999/xlink\" xlink:href=\"%s\"/>\n");
+      msOWSPrintEncodeMetadata(stream, metadata, namespaces, "authorityurl_href",
+                               OWS_NOERR, pszTemplateHref,
+                               NULL);
+      msIO_printf("%s</AuthorityURL>\n", tabspace);
+    } else if ( pszWmsAuthorityName || pszWMSAuthorityHref ) {
+      msIO_printf("%s<!-- WARNING: Both wms_authorityurl_name and wms_authorityurl_href must be set to output an AuthorityURL -->\n", tabspace);
     }
+  }
+  msFree(pszTemplateName);
+  msFree(pszTemplateHref);
+}
+
+/*
+** msWMSPrintIdentifier()
+**
+** Print an Identifier tag if applicable.
+*/
+void msWMSPrintIdentifier(FILE *stream, const char *tabspace,
+                          hashTableObj *metadata, const char *namespaces)
+{
+  const char *pszWMSIdentifierAuthority;
+  const char *pszWMSIdentifierValue;
+  char *pszTemplate=NULL;
+
+  if (stream && metadata) {
+    pszWMSIdentifierAuthority = msOWSLookupMetadata(metadata, namespaces, "identifier_authority");
+    pszWMSIdentifierValue = msOWSLookupMetadata(metadata, namespaces, "identifier_value");
+
     /* Identifier only makes sense if you have *both* the authority and value */
-    if( pszWMSIdentifierAuthority && pszWMSIdentifierValue )
-    {
-      msOWSPrintEncodeMetadata(stdout, &(lp->metadata), "MO", "identifier_authority",
-                               OWS_NOERR, "        <Identifier authority=\"%s\">",
+    if( pszWMSIdentifierAuthority && pszWMSIdentifierValue ) {
+      pszTemplate = msStringConcatenate(msStrdup(tabspace), "<Identifier authority=\"%s\">");
+      msOWSPrintEncodeMetadata(stream, metadata, namespaces, "identifier_authority",
+                               OWS_NOERR, pszTemplate,
                                NULL);
-      msOWSPrintEncodeMetadata(stdout, &(lp->metadata), "MO", "identifier_value",
+      msOWSPrintEncodeMetadata(stream, metadata, namespaces, "identifier_value",
                                OWS_NOERR, "%s</Identifier>\n",
                                NULL);
+    } else if ( pszWMSIdentifierAuthority || pszWMSIdentifierValue ) {
+      msIO_printf("%s<!-- WARNING: Both wms_identifier_authority and wms_identifier_value must be set to output an Identifier -->\n", tabspace);
     }
-    else if ( pszWMSIdentifierAuthority || pszWMSIdentifierValue )
-    {
-       msIO_printf("        <!-- WARNING: Both wms_identifier_authority and wms_identifier_value must be set to output an Identifier -->\n");
-    }
-
   }
+  msFree(pszTemplate);
+}
 
-   if(nVersion >= OWS_1_1_0)
-       msOWSPrintURLType(stdout, &(lp->metadata), "MO", "metadataurl", 
-                         OWS_NOERR, NULL, "MetadataURL", " type=\"%s\"", 
-                         NULL, NULL, ">\n          <Format>%s</Format", 
-                         "\n          <OnlineResource xmlns:xlink=\""
-                         "http://www.w3.org/1999/xlink\" "
-                         "xlink:type=\"simple\" xlink:href=\"%s\"/>\n        ",
-                         MS_TRUE, MS_FALSE, MS_FALSE, MS_TRUE, MS_TRUE, 
-                         NULL, NULL, NULL, NULL, NULL, "        ");
-
-   if(nVersion < OWS_1_1_0)
-       msOWSPrintEncodeMetadata(stdout, &(lp->metadata), "MO", "dataurl_href",
-                                OWS_NOERR, "        <DataURL>%s</DataURL>\n", 
-                                NULL);
-   else
-       msOWSPrintURLType(stdout, &(lp->metadata), "MO", "dataurl", 
-                         OWS_NOERR, NULL, "DataURL", NULL, NULL, NULL, 
-                         ">\n          <Format>%s</Format", 
-                         "\n          <OnlineResource xmlns:xlink=\""
-                         "http://www.w3.org/1999/xlink\" "
-                         "xlink:type=\"simple\" xlink:href=\"%s\"/>\n        ", 
-                         MS_FALSE, MS_FALSE, MS_FALSE, MS_TRUE, MS_TRUE, 
-                         NULL, NULL, NULL, NULL, NULL, "        ");
-
-   /* The LegendURL reside in a style. The Web Map Context spec already  */
-   /* included the support on this in mapserver. However, it is not in the  */
-   /* wms_legendurl_... metadatas it's in the styles metadata, */
-   /* In wms_style_<style_name>_lengendurl_... metadata. So we have to detect */
-   /* the current style before reading it. Also in the Style block, we need */
-   /* a Title and a name. We can get those in wms_style. */
-   pszStyle = msOWSLookupMetadata(&(lp->metadata), "MO", "style");
-   if (pszStyle)
-   {
-       bufferSize = strlen(pszStyle)+205;
-       pszMetadataName = (char*)msSmallMalloc(bufferSize);
-       snprintf(pszMetadataName, bufferSize, "style_%s_legendurl_href", pszStyle);
-       pszLegendURL = msOWSLookupMetadata(&(lp->metadata), "MO", pszMetadataName);
-   }
-   else
-     pszStyle = "default";
-
-       
-   if(nVersion <= OWS_1_0_0 && pszLegendURL)
-   {
-       /* First, print the style block */
-       msIO_fprintf(stdout, "        <Style>\n");
-       msIO_fprintf(stdout, "          <Name>%s</Name>\n", pszStyle);
-       msIO_fprintf(stdout, "          <Title>%s</Title>\n", pszStyle);
-
-          
-       /* Inside, print the legend url block */
-       msOWSPrintEncodeMetadata(stdout, &(lp->metadata), "MO", 
-                                pszMetadataName,
-                                OWS_NOERR, 
-                                "          <StyleURL>%s</StyleURL>\n", 
-                                NULL);
-
-       /* close the style block */
-       msIO_fprintf(stdout, "        </Style>\n");
-
-   }
-   else if(nVersion >= OWS_1_1_0)
-   {
-       if (pszLegendURL)
-       {
-           /* First, print the style block */
-           msIO_fprintf(stdout, "        <Style>\n");
-           msIO_fprintf(stdout, "          <Name>%s</Name>\n", pszStyle);
-           msIO_fprintf(stdout, "          <Title>%s</Title>\n", pszStyle);
-
-           
-           /* Inside, print the legend url block */
-           snprintf(pszMetadataName, bufferSize, "style_%s_legendurl", pszStyle);
-           msOWSPrintURLType(stdout, &(lp->metadata), "MO",pszMetadataName,
-                             OWS_NOERR, NULL, "LegendURL", NULL, 
-                             " width=\"%s\"", " height=\"%s\"", 
-                             ">\n             <Format>%s</Format", 
-                             "\n             <OnlineResource "
-                             "xmlns:xlink=\"http://www.w3.org/1999/xlink\""
-                             " xlink:type=\"simple\" xlink:href=\"%s\"/>\n"
-                             "          ",
-                             MS_FALSE, MS_TRUE, MS_TRUE, MS_TRUE, MS_TRUE, 
-                             NULL, NULL, NULL, NULL, NULL, "          ");
-           msIO_fprintf(stdout, "        </Style>\n");
-               
-       }
-       else
-       {
-           if (script_url_encoded)
-           {
-               if (lp->connectiontype != MS_WMS && 
-                   lp->connectiontype != MS_WFS &&
-                   lp->connectiontype != MS_UNUSED_1 &&
-                   lp->numclasses > 0)
-               {
-                   char width[10], height[10];
-                   char *legendurl = NULL;
-                   size_t bufferSize = 0;
-                   int classnameset = 0, i=0;
-                   for (i=0; i<lp->numclasses; i++)
-                   {
-                       if (lp->class[i]->name && 
-                           strlen(lp->class[i]->name) > 0)
-                       {
-                           classnameset = 1;
-                           break;
-                       }
-                   }
-                   if (classnameset)
-                   {
-                       int size_x=0, size_y=0;
-                       int layer_index[1];
-                       layer_index[0] = lp->index;
-                       if (msLegendCalcSize(map, 1, &size_x, &size_y,  layer_index, 1) == MS_SUCCESS)
-                       {
-                           snprintf(width, sizeof(width), "%d", size_x);
-                           snprintf(height, sizeof(height), "%d", size_y);
-
-                           bufferSize = strlen(script_url_encoded)+200;
-                           legendurl = (char*)msSmallMalloc(bufferSize);
-
-#ifdef USE_GD_PNG
-                           mimetype = msEncodeHTMLEntities("image/png");
-#endif
-#ifdef USE_GD_GIF
-                           if (!mimetype)
-                             mimetype = msEncodeHTMLEntities("image/gif");
-#endif
+/*
+** msWMSPrintKeywordlist()
+**
+** Print a Keywordlist tag if applicable.
+*/
+void msWMSPrintKeywordlist(FILE *stream, const char *tabspace,
+                           const char *name, hashTableObj *metadata,
+                           const char *namespaces, int nVersion)
+{
+  char newname[28];            /* max. rootlayer_keywordlist_items          */
+  char vocname[33];            /* max. rootlayer_keywordlist_vocabulary     */
+  const char *vocabularylist;  /* to be read from metadata                  */
+  char **tokens = NULL;        /* splitted vocabularylist                   */
+  char *pszName=NULL,          /* key to lookup keywords with vocabulary    */
+        *pszTemplate1=NULL,     /* templates for msOWSPrintEncodeMetadataList*/
+         *pszTemplate2=NULL;
+  int i, sName, sTemplate, ntokens = 0;
+
+  newname[0]='\0';
+  vocname[0]='\0';
+  snprintf(newname, sizeof(newname), "%s_items", name);
+  snprintf(vocname, sizeof(vocname), "%s_vocabulary", name);
 
-#ifdef USE_GD_JPEG
-                           if (!mimetype)
-                             mimetype = msEncodeHTMLEntities("image/jpeg");
-#endif
-                           if (!mimetype)
-                               mimetype = msEncodeHTMLEntities(MS_IMAGE_MIME_TYPE(map->outputformat));
-
-                           /* -------------------------------------------------------------------- */
-                           /*      check if the group parameters for the classes are set. We       */
-                           /*      should then publish the deffrent class groups as diffrent styles.*/
-                           /* -------------------------------------------------------------------- */
-                           iclassgroups = 0;
-                           classgroups = NULL;
-                           for (i=0; i<lp->numclasses; i++)
-                           {
-                               if (lp->class[i]->name && lp->class[i]->group)
-                               {
-                                   if (!classgroups)
-                                   {
-                                       classgroups = (char **)msSmallMalloc(sizeof(char *));
-                                       classgroups[iclassgroups++]= msStrdup(lp->class[i]->group);
-                                   }
-                                   else
-                                   {
-                                       for (j=0; j<iclassgroups; j++)
-                                       {
-                                           if (strcasecmp(classgroups[j], lp->class[i]->group) == 0)
-                                             break;
-                                       }
-                                       if (j == iclassgroups)
-                                       {
-                                           iclassgroups++;
-                                           classgroups = (char **)msSmallRealloc(classgroups, sizeof(char *)*iclassgroups);
-                                           classgroups[iclassgroups-1]= msStrdup(lp->class[i]->group);
-                                       }
-                                   }
-                               }
-                           }
-                           if (classgroups == NULL)
-                           {
-                               classgroups = (char **)msSmallMalloc(sizeof(char *));
-                               classgroups[0]= msStrdup("default");
-                               iclassgroups = 1;
-                           }
-                           for (i=0; i<iclassgroups; i++)
-                           {
-                               char *name_encoded = msEncodeHTMLEntities(lp->name);
-                               if (nVersion >= OWS_1_3_0)
-                                   snprintf(legendurl, bufferSize, "%sversion=%s&service=WMS&request=GetLegendGraphic&sld_version=1.1.0&layer=%s&format=%s&STYLE=%s",  
-                                           script_url_encoded,msOWSGetVersionString(nVersion, szVersionBuf),name_encoded,
-                                           mimetype,  classgroups[i]);
-                               else 
-                                   snprintf(legendurl, bufferSize, "%sversion=%s&service=WMS&request=GetLegendGraphic&layer=%s&format=%s&STYLE=%s",  
-                                           script_url_encoded,msOWSGetVersionString(nVersion, szVersionBuf),name_encoded,
-                                           mimetype,  classgroups[i]);
-
-                               msFree(name_encoded);
-
-                               msIO_fprintf(stdout, "        <Style>\n");
-                               msIO_fprintf(stdout, "          <Name>%s</Name>\n",  classgroups[i]);
-                               msIO_fprintf(stdout, "          <Title>%s</Title>\n", classgroups[i]);
-                      
-                               msOWSPrintURLType(stdout, NULL, 
-                                                 "O", "ttt",
-                                                 OWS_NOERR, NULL, 
-                                                 "LegendURL", NULL, 
-                                                 " width=\"%s\"", " height=\"%s\"", 
-                                                 ">\n             <Format>%s</Format", 
-                                                 "\n             <OnlineResource "
-                                                 "xmlns:xlink=\"http://www.w3.org/1999/xlink\""
-                                                 " xlink:type=\"simple\" xlink:href=\"%s\"/>\n"
-                                                 "          ",
-                                                 MS_FALSE, MS_FALSE, MS_FALSE, MS_FALSE, MS_FALSE, 
-                                                 NULL, width, height, mimetype, legendurl, "          ");
-                       
-
-                               msIO_fprintf(stdout, "        </Style>\n");
-                           }
-                           msFree(legendurl);
-                           for (i=0; i<iclassgroups; i++)
-                             msFree(classgroups[i]);
-                           msFree(classgroups);
-
-                           msFree(mimetype);
-                       }
-                   }
-               }       
-           }
-       }
-   }
-   
-   msFree(pszMetadataName);
-
-   if (nVersion <  OWS_1_3_0)
-     msWMSPrintScaleHint("        ", lp->minscaledenom, lp->maxscaledenom, map->resolution);
-   else
-     msWMSPrintScaleDenominator("        ", lp->minscaledenom, lp->maxscaledenom);
-   msIO_printf("%s    </Layer>\n", indent);
-
-   return MS_SUCCESS;
+  if (nVersion == OWS_1_0_0) {
+    /* <Keywords> in V 1.0.0 */
+    /* The 1.0.0 spec doesn't specify which delimiter to use so let's use spaces */
+    pszTemplate1 = msStringConcatenate(msStrdup(tabspace), "<Keywords>");
+    pszTemplate2 = msStringConcatenate(msStrdup(tabspace), "</Keywords>\n");
+    msOWSPrintEncodeMetadataList(stream, metadata, namespaces,
+                                 name, pszTemplate1, pszTemplate2,
+                                 "%s ", NULL);
+  } else if ( msOWSLookupMetadata(metadata, namespaces, name) ||
+              msOWSLookupMetadata(metadata, namespaces, newname) ||
+              msOWSLookupMetadata(metadata, namespaces, vocname) ) {
+    /* <KeywordList><Keyword> ... in V1.0.6+ */
+    msIO_printf("%s<KeywordList>\n", tabspace);
+    pszTemplate1 = msStringConcatenate(msStrdup(tabspace), "    <Keyword>%s</Keyword>\n");
+    /* print old styled ..._keywordlist */
+    msOWSPrintEncodeMetadataList(stream, metadata, namespaces,
+                                 name, NULL, NULL,
+                                 pszTemplate1, NULL);
+    /* print new styled ..._keywordlist_items */
+    msOWSPrintEncodeMetadataList(stream, metadata, namespaces,
+                                 newname, NULL, NULL,
+                                 pszTemplate1, NULL);
+
+    /* find out if there's a vocabulary list set */
+    vocabularylist = msOWSLookupMetadata(metadata, namespaces, vocname);
+    if ( vocabularylist && nVersion >= OWS_1_3_0 ) {
+      tokens = msStringSplit(vocabularylist, ',', &ntokens);
+      if ( tokens && ntokens > 0 ) {
+        /* In order to do malloc only once, the length of the metadata*/
+        /* key to lookup is calculated from "rootlayer_keywordlist"   */
+        /* plus "_items" plus the length of all vocabulary items      */
+        /* concatenate.                                               */
+        /* The same is done with template string used for printing the*/
+        /* keyword list. Here the string is tabspace + "    <Keyword  */
+        /* vocabulary="" + ... + "">%s</Keyword>\n"                   */
+        sName = 22 + 6 + strlen(vocabularylist) +1;
+        pszName = (char*)msSmallMalloc(sName);
+
+        sTemplate = strlen(tabspace)+4+21+strlen(vocabularylist)+17+1;
+        pszTemplate2 = (char*)msSmallMalloc(sTemplate);
+
+        for (i=0; i<ntokens; i++) {
+          snprintf(pszName, sName,
+                   "%s_%s_items", name, tokens[i]);
+          snprintf(pszTemplate2, sTemplate,
+                   "%s    <Keyword vocabulary=\"%s\">%s</Keyword>\n",
+                   tabspace, tokens[i], "%s");
+          msOWSPrintEncodeMetadataList(stream, metadata, namespaces,
+                                       pszName, NULL, NULL,
+                                       pszTemplate2, NULL);
+        }
+        msFree(pszName);
+      }
+      msFreeCharArray(tokens, ntokens);
+    }
+    msIO_printf("%s</KeywordList>\n", tabspace);
+  }
+  msFree(pszTemplate1);
+  msFree(pszTemplate2);
 }
 
 /*
- * msWMSPrepareNestedGroups
- */
-void msWMSPrepareNestedGroups(mapObj* map, int nVersion, char*** nestedGroups, int* numNestedGroups)
+** msDumpLayer()
+*/
+int msDumpLayer(mapObj *map, layerObj *lp, int nVersion, const char *script_url_encoded, const char *indent, const char *validated_language, int grouplayer)
 {
-  int i;
-  const char* groups;
-  char* errorMsg;
+  rectObj ext;
+  const char *value;
+  const char *pszWmsTimeExtent, *pszWmsTimeDefault= NULL, *pszStyle=NULL;
+  const char *pszLegendURL=NULL;
+  char *pszMetadataName=NULL, *mimetype=NULL;
+  char **classgroups = NULL;
+  int iclassgroups=0;
+  char szVersionBuf[OWS_VERSION_MAXLEN];
+  size_t bufferSize = 0;
+  const char *pszDimensionlist=NULL;
 
-  for (i = 0; i < map->numlayers; i++)
-  {
-    nestedGroups[i] = NULL; /* default */
-    numNestedGroups[i] = 0; /* default */
-    
-    groups = msOWSLookupMetadata(&(GET_LAYER(map, i)->metadata), "MO", "layer_group");
-    if ((groups != NULL) && (strlen(groups) != 0))
-    {
-      if (GET_LAYER(map, i)->group != NULL && strlen(GET_LAYER(map, i)->group) != 0)
-      {
-        errorMsg = "It is not allowed to set both the GROUP and WMS_LAYER_GROUP for a layer";
-        msSetError(MS_WMSERR, errorMsg, "msWMSPrepareNestedGroups()", NULL);
-        msIO_fprintf(stdout, "<!-- ERROR: %s -->\n", errorMsg);
-        /* cannot return exception at this point because we are already writing to stdout */
-      }
+  /* if the layer status is set to MS_DEFAULT, output a warning */
+  if (lp->status == MS_DEFAULT)
+    msIO_fprintf(stdout, "<!-- WARNING: This layer has its status set to DEFAULT and will always be displayed when doing a GetMap request even if it is not requested by the client. This is not in line with the expected behavior of a WMS server. Using status ON or OFF is recommended. -->\n");
+
+  if (nVersion <= OWS_1_0_7) {
+    msIO_printf("%s    <Layer queryable=\"%d\">\n",
+                indent, msIsLayerQueryable(lp));
+  } else {
+    /* 1.1.0 and later: opaque and cascaded are new. */
+    int cascaded=0, opaque=0;
+    if ((value = msOWSLookupMetadata(&(lp->metadata), "MO", "opaque")) != NULL)
+      opaque = atoi(value);
+    if (lp->connectiontype == MS_WMS)
+      cascaded = 1;
+
+    msIO_printf("%s    <Layer queryable=\"%d\" opaque=\"%d\" cascaded=\"%d\">\n",
+                indent, msIsLayerQueryable(lp), opaque, cascaded);
+  }
+
+  if (lp->name && strlen(lp->name) > 0 &&
+      (msIsXMLTagValid(lp->name) == MS_FALSE || isdigit(lp->name[0])))
+    msIO_fprintf(stdout, "<!-- WARNING: The layer name '%s' might contain spaces or "
+                 "invalid characters or may start with a number. This could lead to potential problems. -->\n",
+                 lp->name);
+  msOWSPrintEncodeParam(stdout, "LAYER.NAME", lp->name, OWS_NOERR,
+                        "        <Name>%s</Name>\n", NULL);
+
+  /* the majority of this section is dependent on appropriately named metadata in the LAYER object */
+  msOWSPrintEncodeMetadata2(stdout, &(lp->metadata), "MO", "title",
+                            OWS_WARN, "        <Title>%s</Title>\n", lp->name, validated_language);
+
+  msOWSPrintEncodeMetadata2(stdout, &(lp->metadata), "MO", "abstract",
+                            OWS_NOERR, "        <Abstract>%s</Abstract>\n", NULL, validated_language);
+
+  msWMSPrintKeywordlist(stdout, "        ", "keywordlist", &(lp->metadata), "MO", nVersion);
+
+  if (msOWSGetEPSGProj(&(map->projection),&(map->web.metadata),
+                       "MO", MS_FALSE) == NULL) {
+    /* If map has no proj then every layer MUST have one or produce a warning */
+    if (nVersion > OWS_1_1_0) {
+      /* starting 1.1.1 SRS are given in individual tags */
+      if (nVersion >= OWS_1_3_0)
+        msOWSPrintEncodeParamList(stdout, "(at least one of) "
+                                  "MAP.PROJECTION, LAYER.PROJECTION "
+                                  "or wms_srs metadata",
+                                  msOWSGetEPSGProj(&(lp->projection),
+                                      &(lp->metadata),
+                                      "MO", MS_FALSE),
+                                  OWS_WARN, ' ', NULL, NULL,
+                                  "        <CRS>%s</CRS>\n", NULL);
       else
-      {
-        if (groups[0] != '/')
-        {      
-          errorMsg = "The WMS_LAYER_GROUP metadata does not start with a '/'";
-          msSetError(MS_WMSERR, errorMsg, "msWMSPrepareNestedGroups()", NULL);
-          msIO_fprintf(stdout, "<!-- ERROR: %s -->\n", errorMsg);
-          /* cannot return exception at this point because we are already writing to stdout */
+        msOWSPrintEncodeParamList(stdout, "(at least one of) "
+                                  "MAP.PROJECTION, LAYER.PROJECTION "
+                                  "or wms_srs metadata",
+                                  msOWSGetEPSGProj(&(lp->projection),
+                                      &(lp->metadata),
+                                      "MO", MS_FALSE),
+                                  OWS_WARN, ' ', NULL, NULL,
+                                  "        <SRS>%s</SRS>\n", NULL);
+    } else
+      msOWSPrintEncodeParam(stdout, "(at least one of) MAP.PROJECTION, "
+                            "LAYER.PROJECTION or wms_srs metadata",
+                            msOWSGetEPSGProj(&(lp->projection),
+                                             &(lp->metadata), "MO", MS_FALSE),
+                            OWS_WARN, "        <SRS>%s</SRS>\n", NULL);
+  } else {
+    /* No warning required in this case since there's at least a map proj. */
+    if (nVersion > OWS_1_1_0) {
+      /* starting 1.1.1 SRS are given in individual tags */
+      if (nVersion >=  OWS_1_3_0)
+        msOWSPrintEncodeParamList(stdout, "(at least one of) "
+                                  "MAP.PROJECTION, LAYER.PROJECTION "
+                                  "or wms_srs metadata",
+                                  msOWSGetEPSGProj(&(lp->projection),
+                                      &(lp->metadata),
+                                      "MO", MS_FALSE),
+                                  OWS_NOERR, ' ', NULL, NULL,
+                                  "        <CRS>%s</CRS>\n", NULL);
+      else
+        msOWSPrintEncodeParamList(stdout, "(at least one of) "
+                                  "MAP.PROJECTION, LAYER.PROJECTION "
+                                  "or wms_srs metadata",
+                                  msOWSGetEPSGProj(&(lp->projection),
+                                      &(lp->metadata),
+                                      "MO", MS_FALSE),
+                                  OWS_NOERR, ' ', NULL, NULL,
+                                  "        <SRS>%s</SRS>\n", NULL);
+    } else
+      msOWSPrintEncodeParam(stdout,
+                            " LAYER.PROJECTION (or wms_srs metadata)",
+                            msOWSGetEPSGProj(&(lp->projection),
+                                             &(lp->metadata),"MO",MS_FALSE),
+                            OWS_NOERR, "        <SRS>%s</SRS>\n", NULL);
+  }
+
+  /* If layer has no proj set then use map->proj for bounding box. */
+  if (msOWSGetLayerExtent(map, lp, "MO", &ext) == MS_SUCCESS) {
+    if(lp->projection.numargs > 0) {
+      if (nVersion >= OWS_1_3_0)
+        msOWSPrintEX_GeographicBoundingBox(stdout, "        ", &(ext),
+                                           &(lp->projection));
+      else
+        msOWSPrintLatLonBoundingBox(stdout, "        ", &(ext),
+                                    &(lp->projection), NULL, OWS_WMS);
+
+      msOWSPrintBoundingBox( stdout,"        ", &(ext), &(lp->projection),
+                             &(lp->metadata), &(map->web.metadata), "MO", nVersion );
+    } else {
+      if (nVersion >= OWS_1_3_0)
+        msOWSPrintEX_GeographicBoundingBox(stdout, "        ", &(ext),
+                                           &(map->projection));
+      else
+        msOWSPrintLatLonBoundingBox(stdout, "        ", &(ext),
+                                    &(map->projection), NULL, OWS_WMS);
+      msOWSPrintBoundingBox(stdout,"        ", &(ext), &(map->projection),
+                            &(lp->metadata), &(map->web.metadata), "MO", nVersion );
+    }
+  } else {
+    if (nVersion >= OWS_1_3_0)
+      msIO_printf("        <!-- WARNING: Optional Ex_GeographicBoundingBox could not be established for this layer.  Consider setting the EXTENT in the LAYER object, or wms_extent metadata. Also check that your data exists in the DATA statement -->\n");
+    else
+      msIO_printf("        <!-- WARNING: Optional LatLonBoundingBox could not be established for this layer.  Consider setting the EXTENT in the LAYER object, or wms_extent metadata. Also check that your data exists in the DATA statement -->\n");
+  }
+
+  /* time support */
+  pszWmsTimeExtent = msOWSLookupMetadata(&(lp->metadata), "MO", "timeextent");
+  if (pszWmsTimeExtent) {
+    pszWmsTimeDefault = msOWSLookupMetadata(&(lp->metadata),  "MO",
+                                            "timedefault");
+
+    if (nVersion >= OWS_1_3_0) {
+      if (pszWmsTimeDefault)
+        msIO_fprintf(stdout, "        <Dimension name=\"time\" units=\"ISO8601\" default=\"%s\" nearestValue=\"0\">%s</Dimension>\n",pszWmsTimeDefault, pszWmsTimeExtent);
+      else
+        msIO_fprintf(stdout, "        <Dimension name=\"time\" units=\"ISO8601\" nearestValue=\"0\">%s</Dimension>\n",pszWmsTimeExtent);
+    }
+
+    else {
+      msIO_fprintf(stdout, "        <Dimension name=\"time\" units=\"ISO8601\"/>\n");
+      if (pszWmsTimeDefault)
+        msIO_fprintf(stdout, "        <Extent name=\"time\" default=\"%s\" nearestValue=\"0\">%s</Extent>\n",pszWmsTimeDefault, pszWmsTimeExtent);
+      else
+        msIO_fprintf(stdout, "        <Extent name=\"time\" nearestValue=\"0\">%s</Extent>\n",pszWmsTimeExtent);
+    }
+  }
+
+  /*dimensions support: elevation + other user defined dimensions*/
+  pszDimensionlist = msOWSLookupMetadata(&(lp->metadata), "M", "dimensionlist");
+  if (pszDimensionlist) {
+    char **tokens = NULL;
+    int ntokens = 0;
+    char *pszDimension=NULL, *pszDimensionItemName=NULL, *pszDimensionExtentName=NULL, *pszDimensionUnitName=NULL, *pszDimensionDefaultName=NULL;
+    const char *pszDimensionItem=NULL, *pszDimensionExtent=NULL, *pszDimensionUnit=NULL, *pszDimensionDefault=NULL;
+    int i;
+
+    tokens = msStringSplit(pszDimensionlist,  ',', &ntokens);
+    if (tokens && ntokens > 0) {
+      for (i=0; i<ntokens; i++) {
+        /*check if manadatory unit and extent are set. Item should also be set. default value is optional*/
+        pszDimension = msStrdup(tokens[i]);
+        msStringTrim(pszDimension);
+
+        pszDimensionItemName = msStrdup(pszDimension);
+        pszDimensionItemName = msStringConcatenate(pszDimensionItemName, "_item");
+        pszDimensionItem = msOWSLookupMetadata(&(lp->metadata), "M", pszDimensionItemName);
+
+        pszDimensionExtentName = msStrdup(pszDimension);
+        pszDimensionExtentName = msStringConcatenate(pszDimensionExtentName, "_extent");
+        pszDimensionExtent = msOWSLookupMetadata(&(lp->metadata), "M", pszDimensionExtentName);
+
+        pszDimensionUnitName = msStrdup(pszDimension);
+        pszDimensionUnitName = msStringConcatenate(pszDimensionUnitName, "_units");
+        pszDimensionUnit = msOWSLookupMetadata(&(lp->metadata), "M", pszDimensionUnitName);
+
+        pszDimensionDefaultName = msStrdup(pszDimension);
+        pszDimensionDefaultName = msStringConcatenate(pszDimensionDefaultName, "_default");
+        pszDimensionDefault = msOWSLookupMetadata(&(lp->metadata), "M", pszDimensionDefaultName);
+
+        if (pszDimensionItem && pszDimensionExtent && pszDimensionUnit) {
+          if (nVersion >= OWS_1_3_0) {
+            if(pszDimensionDefault && strlen(pszDimensionDefault) > 0)
+              msIO_fprintf(stdout, "        <Dimension name=\"%s\" units=\"%s\" default=\"%s\" multipleValues=\"1\" nearestValue=\"0\">%s</Dimension>\n",
+                           pszDimension, pszDimensionUnit, pszDimensionDefault, pszDimensionExtent);
+            else
+              msIO_fprintf(stdout, "        <Dimension name=\"%s\" units=\"%s\"  multipleValues=\"1\"  nearestValue=\"0\">%s</Dimension>\n",
+                           pszDimension, pszDimensionUnit, pszDimensionExtent);
+          } else {
+            msIO_fprintf(stdout, "        <Dimension name=\"%s\" units=\"%s\"/>\n", pszDimension, pszDimensionUnit);
+            if(pszDimensionDefault && strlen(pszDimensionDefault) > 0)
+              msIO_fprintf(stdout, "        <Extent name=\"%s\" default=\"%s\" nearestValue=\"0\">%s</Extent>\n",
+                           pszDimension, pszDimensionDefault, pszDimensionExtent);
+            else
+              msIO_fprintf(stdout, "        <Extent name=\"%s\" nearestValue=\"0\">%s</Extent>\n",
+                           pszDimension, pszDimensionExtent);
+          }
         }
-        else
-        {
-          /* split into subgroups. Start at adres + 1 because the first '/' would cause an extra emtpy group */
-          nestedGroups[i] = msStringSplit(groups + 1, '/', &numNestedGroups[i]); 
+        msFree(pszDimension);
+        msFree(pszDimensionItemName);
+        msFree(pszDimensionUnitName);
+        msFree(pszDimensionExtentName);
+        msFree(pszDimensionDefaultName);
+
+      }
+      msFreeCharArray(tokens, ntokens);
+    }
+  }
+
+
+  if (nVersion >= OWS_1_0_7) {
+    msWMSPrintAttribution(stdout, "    ", &(lp->metadata), "MO");
+  }
+
+  /* AuthorityURL support and Identifier support, only available >= WMS 1.1.0 */
+  if(nVersion >= OWS_1_1_0) {
+    msWMSPrintAuthorityURL(stdout, "        ", &(lp->metadata), "MO");
+    msWMSPrintIdentifier(stdout, "        ", &(lp->metadata), "MO");
+  }
+
+  if(nVersion >= OWS_1_1_0)
+    msOWSPrintURLType(stdout, &(lp->metadata), "MO", "metadataurl",
+                      OWS_NOERR, NULL, "MetadataURL", " type=\"%s\"",
+                      NULL, NULL, ">\n          <Format>%s</Format",
+                      "\n          <OnlineResource xmlns:xlink=\""
+                      "http://www.w3.org/1999/xlink\" "
+                      "xlink:type=\"simple\" xlink:href=\"%s\"/>\n        ",
+                      MS_TRUE, MS_FALSE, MS_FALSE, MS_TRUE, MS_TRUE,
+                      NULL, NULL, NULL, NULL, NULL, "        ");
+
+  if(nVersion < OWS_1_1_0)
+    msOWSPrintEncodeMetadata(stdout, &(lp->metadata), "MO", "dataurl_href",
+                             OWS_NOERR, "        <DataURL>%s</DataURL>\n",
+                             NULL);
+  else
+    msOWSPrintURLType(stdout, &(lp->metadata), "MO", "dataurl",
+                      OWS_NOERR, NULL, "DataURL", NULL, NULL, NULL,
+                      ">\n          <Format>%s</Format",
+                      "\n          <OnlineResource xmlns:xlink=\""
+                      "http://www.w3.org/1999/xlink\" "
+                      "xlink:type=\"simple\" xlink:href=\"%s\"/>\n        ",
+                      MS_FALSE, MS_FALSE, MS_FALSE, MS_TRUE, MS_TRUE,
+                      NULL, NULL, NULL, NULL, NULL, "        ");
+
+  /* The LegendURL reside in a style. The Web Map Context spec already  */
+  /* included the support on this in mapserver. However, it is not in the  */
+  /* wms_legendurl_... metadatas it's in the styles metadata, */
+  /* In wms_style_<style_name>_lengendurl_... metadata. So we have to detect */
+  /* the current style before reading it. Also in the Style block, we need */
+  /* a Title and a name. Title is derived from wms_style_<style>_title, */
+  /* which allows mutiple style definitions, e.g. by using classgroups. */
+  bufferSize = 512; /* We don't know about possible style name lengths, yet */
+  pszMetadataName = (char*)msSmallMalloc(bufferSize);
+  pszStyle = msOWSLookupMetadata(&(lp->metadata), "MO", "style");
+  if (pszStyle) {
+    snprintf(pszMetadataName, bufferSize, "style_%s_legendurl_href", pszStyle);
+    pszLegendURL = msOWSLookupMetadata(&(lp->metadata), "MO", pszMetadataName);
+  } else
+    pszStyle = "default";
+
+
+  if(nVersion <= OWS_1_0_0 && pszLegendURL) {
+    /* First, print the style block */
+    msIO_fprintf(stdout, "        <Style>\n");
+    msIO_fprintf(stdout, "          <Name>%s</Name>\n", pszStyle);
+    /* Print the real Title or Style name otherwise */
+    snprintf(pszMetadataName, bufferSize, "style_%s_title", pszStyle);
+    msOWSPrintEncodeMetadata2(stdout, &(lp->metadata), "MO",
+                              pszMetadataName,
+                              OWS_NOERR,
+                              "          <Title>%s</Title>\n",
+                              pszStyle, validated_language);
+
+    /* Inside, print the legend url block */
+    snprintf(pszMetadataName, bufferSize, "style_%s_legendurl_href", pszStyle);
+    msOWSPrintEncodeMetadata(stdout, &(lp->metadata), "MO",
+                             pszMetadataName,
+                             OWS_NOERR,
+                             "          <StyleURL>%s</StyleURL>\n",
+                             NULL);
+
+    /* close the style block */
+    msIO_fprintf(stdout, "        </Style>\n");
+
+  } else if(nVersion >= OWS_1_1_0) {
+    if (pszLegendURL) {
+      /* First, print the style block */
+      msIO_fprintf(stdout, "        <Style>\n");
+      msIO_fprintf(stdout, "          <Name>%s</Name>\n", pszStyle);
+      /* Print the real Title or Style name otherwise */
+      snprintf(pszMetadataName, bufferSize, "style_%s_title", pszStyle);
+      msOWSPrintEncodeMetadata2(stdout, &(lp->metadata), "MO",
+                                pszMetadataName,
+                                OWS_NOERR,
+                                "          <Title>%s</Title>\n",
+                                pszStyle, validated_language);
+
+
+      /* Inside, print the legend url block */
+      snprintf(pszMetadataName, bufferSize, "style_%s_legendurl", pszStyle);
+      msOWSPrintURLType(stdout, &(lp->metadata), "MO",pszMetadataName,
+                        OWS_NOERR, NULL, "LegendURL", NULL,
+                        " width=\"%s\"", " height=\"%s\"",
+                        ">\n             <Format>%s</Format",
+                        "\n             <OnlineResource "
+                        "xmlns:xlink=\"http://www.w3.org/1999/xlink\""
+                        " xlink:type=\"simple\" xlink:href=\"%s\"/>\n"
+                        "          ",
+                        MS_FALSE, MS_TRUE, MS_TRUE, MS_TRUE, MS_TRUE,
+                        NULL, NULL, NULL, NULL, NULL, "          ");
+      msIO_fprintf(stdout, "        </Style>\n");
+
+    } else {
+      if (script_url_encoded) {
+        if (lp->connectiontype != MS_WMS &&
+            lp->connectiontype != MS_WFS &&
+            lp->connectiontype != MS_UNUSED_1 &&
+            lp->numclasses > 0) {
+          char width[10], height[10];
+          char *legendurl = NULL;
+          size_t bufferSize = 0;
+          int classnameset = 0, i=0;
+          for (i=0; i<lp->numclasses; i++) {
+            if (lp->class[i]->name &&
+                strlen(lp->class[i]->name) > 0) {
+              classnameset = 1;
+              break;
+            }
+          }
+          if (classnameset) {
+            int j=0, k=0, l=0, size_x=0, size_y=0, num_layers=0;
+            int *group_layers = (int *)msSmallMalloc(sizeof(int)*map->numlayers);
+            char ***nestedGroups = NULL;
+            int *numNestedGroups = NULL;
+            int *isUsedInNestedGroup = NULL;
+
+            nestedGroups = (char***)msSmallCalloc(map->numlayers, sizeof(char**));
+            numNestedGroups = (int*)msSmallCalloc(map->numlayers, sizeof(int));
+            isUsedInNestedGroup = (int*)msSmallCalloc(map->numlayers, sizeof(int));
+            msWMSPrepareNestedGroups(map, nVersion, nestedGroups, numNestedGroups, isUsedInNestedGroup);
+
+            num_layers = 1;
+            group_layers[0] = lp->index;
+            if (isUsedInNestedGroup[lp->index]) {
+              for (j=0; j < map->numlayers; j++) {
+                for(k = 0; k < numNestedGroups[j]; k++) {
+                  if (strcasecmp(lp->name, nestedGroups[j][k]) == 0) {
+                    group_layers[num_layers++] = j;
+                    break;
+                  }
+                }
+              }
+            }
+            group_layers =(int *)msSmallRealloc(group_layers, sizeof(int)*num_layers);
+            
+            if (msLegendCalcSize(map, 1, &size_x, &size_y,  group_layers, num_layers) == MS_SUCCESS) {
+              const char *styleName = NULL;
+              char *pszEncodedStyleName = NULL;
+              layerObj *lp2 = NULL;
+
+              snprintf(width, sizeof(width), "%d", size_x);
+              snprintf(height, sizeof(height), "%d", size_y);
+
+              bufferSize = strlen(script_url_encoded)+300;
+              legendurl = (char*)msSmallMalloc(bufferSize);
+
+#if defined USE_GD_PNG || defined USE_PNG
+              mimetype = msEncodeHTMLEntities("image/png");
+#endif
+#if defined USE_GD_GIF
+              if (!mimetype)
+                mimetype = msEncodeHTMLEntities("image/gif");
+#endif
+
+#if defined USE_GD_JPEG || defined USE_JPEG
+              if (!mimetype)
+                mimetype = msEncodeHTMLEntities("image/jpeg");
+#endif
+              if (!mimetype)
+                mimetype = msEncodeHTMLEntities(MS_IMAGE_MIME_TYPE(map->outputformat));
+
+              /* -------------------------------------------------------------------- */
+              /*      check if the group parameters for the classes are set. We       */
+              /*      should then publish the different class groups as different styles.*/
+              /* -------------------------------------------------------------------- */
+              iclassgroups = 0;
+              classgroups = NULL;
+
+              styleName = msOWSLookupMetadata(&(map->web.metadata), "MO", "style_name");
+              if (styleName == NULL)
+                styleName = "default";
+              pszEncodedStyleName = msEncodeHTMLEntities(styleName);
+
+              for (i=0; i<lp->numclasses; i++) {
+                if (lp->class[i]->name && lp->class[i]->group) {
+                  /* Check that style is not inherited from root layer (#4442). */
+                  if (strcasecmp(pszEncodedStyleName, lp->class[i]->group) == 0)
+                    continue;
+                  /* Check that style is not inherited from group layer(s) (#4442). */
+                  if (numNestedGroups[lp->index] > 0) {
+                    for (j=0; j<numNestedGroups[lp->index]; j++) {
+                      for (k=0; k < map->numlayers; k++) {
+                        if (GET_LAYER(map, k)->name && strcasecmp(GET_LAYER(map, k)->name, nestedGroups[lp->index][j]) == 0) {
+                          lp2 = (GET_LAYER(map, k));
+                          for (l=0; l < lp2->numclasses; l++) {
+                            if (strcasecmp(lp2->class[l]->group, lp->class[i]->group) == 0)
+                              break;
+                          }
+                          break;
+                        }
+                      }
+                      if (l < lp2->numclasses)
+                        break;
+                    }
+                    if (j < numNestedGroups[lp->index])
+                      continue;
+                  }
+                  if (!classgroups) {
+                    classgroups = (char **)msSmallMalloc(sizeof(char *));
+                    classgroups[iclassgroups++]= msStrdup(lp->class[i]->group);
+                  } else {
+                    /* Output style only once. */
+                    for (j=0; j<iclassgroups; j++) {
+                      if (strcasecmp(classgroups[j], lp->class[i]->group) == 0)
+                        break;
+                    }
+                    if (j == iclassgroups) {
+                      iclassgroups++;
+                      classgroups = (char **)msSmallRealloc(classgroups, sizeof(char *)*iclassgroups);
+                      classgroups[iclassgroups-1]= msStrdup(lp->class[i]->group);
+                    }
+                  }
+                }
+              }
+              msFree(pszEncodedStyleName);
+              if (classgroups == NULL) {
+                classgroups = (char **)msSmallMalloc(sizeof(char *));
+                classgroups[0]= msStrdup("default");
+                iclassgroups = 1;
+              }
+              for (i=0; i<iclassgroups; i++) {
+                char *name_encoded = msEncodeHTMLEntities(lp->name);
+                char *classgroup_encoded = msEncodeHTMLEntities(classgroups[i]);
+                if (nVersion >= OWS_1_3_0)
+                  snprintf(legendurl, bufferSize, "%sversion=%s&service=WMS&request=GetLegendGraphic&sld_version=1.1.0&layer=%s&format=%s&STYLE=%s",
+                           script_url_encoded,msOWSGetVersionString(nVersion, szVersionBuf),name_encoded,
+                           mimetype,  classgroup_encoded);
+                else
+                  snprintf(legendurl, bufferSize, "%sversion=%s&service=WMS&request=GetLegendGraphic&layer=%s&format=%s&STYLE=%s",
+                           script_url_encoded,msOWSGetVersionString(nVersion, szVersionBuf),name_encoded,
+                           mimetype,  classgroup_encoded);
+
+                msFree(name_encoded);
+                msFree(classgroup_encoded);
+
+                msIO_fprintf(stdout, "        <Style>\n");
+                msIO_fprintf(stdout, "          <Name>%s</Name>\n",  classgroups[i]);
+                snprintf(pszMetadataName, bufferSize, "style_%s_title", classgroups[i]);
+                msOWSPrintEncodeMetadata2(stdout, &(lp->metadata), "MO",
+                                          pszMetadataName,
+                                          OWS_NOERR,
+                                          "          <Title>%s</Title>\n",
+                                          classgroups[i], validated_language);
+
+                /* A legendurl from wms_style_<style>_legendurl_href will override a self generated legend graphic */
+                snprintf(pszMetadataName, bufferSize, "style_%s_legendurl_href", classgroups[i]);
+                pszLegendURL = msOWSLookupMetadata(&(lp->metadata), "MO", pszMetadataName);
+                if (pszLegendURL) {
+                  snprintf(pszMetadataName, bufferSize, "style_%s_legendurl", classgroups[i]);
+                  msOWSPrintURLType(stdout, &(lp->metadata),
+                                    "MO", pszMetadataName,
+                                    OWS_NOERR, NULL,
+                                    "LegendURL", NULL,
+                                    " width=\"%s\"", " height=\"%s\"",
+                                    ">\n             <Format>%s</Format",
+                                    "\n             <OnlineResource "
+                                    "xmlns:xlink=\"http://www.w3.org/1999/xlink\""
+                                    " xlink:type=\"simple\" xlink:href=\"%s\"/>\n"
+                                    "          ",
+                                    MS_FALSE, MS_TRUE, MS_TRUE, MS_TRUE, MS_TRUE,
+                                    NULL, NULL, NULL, NULL, NULL, "          ");
+                } else {
+                  msOWSPrintURLType(stdout, NULL,
+                                    "O", "ttt",
+                                    OWS_NOERR, NULL,
+                                    "LegendURL", NULL,
+                                    " width=\"%s\"", " height=\"%s\"",
+                                    ">\n             <Format>%s</Format",
+                                    "\n             <OnlineResource "
+                                    "xmlns:xlink=\"http://www.w3.org/1999/xlink\""
+                                    " xlink:type=\"simple\" xlink:href=\"%s\"/>\n"
+                                    "          ",
+                                    MS_FALSE, MS_FALSE, MS_FALSE, MS_FALSE, MS_FALSE,
+                                    NULL, width, height, mimetype, legendurl, "          ");
+                }
+                msIO_fprintf(stdout, "        </Style>\n");
+              }
+              msFree(legendurl);
+              msFreeCharArray(classgroups, iclassgroups);
+              msFree(mimetype);
+            }
+            /* free the stuff used for nested layers */
+            for (i = 0; i < map->numlayers; i++) {
+              if (numNestedGroups[i] > 0) {
+                msFreeCharArray(nestedGroups[i], numNestedGroups[i]);
+              }
+            }
+            free(nestedGroups);
+            free(numNestedGroups);
+            free(isUsedInNestedGroup);
+            free(group_layers);
+          }
         }
       }
     }
   }
-}
 
+  msFree(pszMetadataName);
+
+  if (nVersion <  OWS_1_3_0)
+    msWMSPrintScaleHint("        ", lp->minscaledenom, lp->maxscaledenom, map->resolution);
+  else
+    msWMSPrintScaleDenominator("        ", lp->minscaledenom, lp->maxscaledenom);
+
+  if ( grouplayer == MS_FALSE )
+    msIO_printf("%s    </Layer>\n", indent);
+
+  return MS_SUCCESS;
+}
 
 /*
  * msWMSIsSubGroup
  */
 int msWMSIsSubGroup(char** currentGroups, int currentLevel, char** otherGroups, int numOtherGroups)
 {
-   int i;
-   /* no match if otherGroups[] has less levels than currentLevel */
-   if (numOtherGroups <= currentLevel) 
-   {
-      return MS_FALSE;
-   }
-   /* compare all groups below the current level */
-   for (i = 0; i <= currentLevel; i++)
-   {
-      if (strcmp(currentGroups[i], otherGroups[i]) != 0)
-      {
-         return MS_FALSE; /* if one of these is not equal it is not a sub group */
-      }
-   }
-   return MS_TRUE;
+  int i;
+  /* no match if otherGroups[] has less levels than currentLevel */
+  if (numOtherGroups <= currentLevel) {
+    return MS_FALSE;
+  }
+  /* compare all groups below the current level */
+  for (i = 0; i <= currentLevel; i++) {
+    if (strcmp(currentGroups[i], otherGroups[i]) != 0) {
+      return MS_FALSE; /* if one of these is not equal it is not a sub group */
+    }
+  }
+  return MS_TRUE;
 }
 
 /***********************************************************************************
@@ -1937,7 +2588,7 @@ int msWMSIsSubGroup(char** currentGroups, int currentLevel, char** otherGroups,
  * "WMS_LAYER_GROUP" metadata set.                                                 *
  *                                                                                 *
  * params:                                                                         *
- * -map: The main map object                                                       *      
+ * -map: The main map object                                                       *
  * -nVersion: OGC WMS version                                                      *
  * -pabLayerProcessed: boolean array indicating which layers have been dealt with. *
  * -index: the index of the current layer.                                         *
@@ -1946,65 +2597,80 @@ int msWMSIsSubGroup(char** currentGroups, int currentLevel, char** otherGroups,
  *   been set through the WMS_LAYER_GROUP metadata                                 *
  * -numNestedGroups: This array holds the number of nested groups for each layer   *
  ***********************************************************************************/
-void msWMSPrintNestedGroups(mapObj* map, int nVersion, char* pabLayerProcessed, 
-	int index, int level, char*** nestedGroups, int* numNestedGroups, const char *script_url_encoded)
+void msWMSPrintNestedGroups(mapObj* map, int nVersion, char* pabLayerProcessed,
+                            int index, int level, char*** nestedGroups, int* numNestedGroups, int* isUsedInNestedGroup, const char *script_url_encoded, const char *validated_language)
 {
-   int j;
+  int i, j;
+  char *indent = NULL;
+  indent = msStrdup("");
+
+  for (i = 0; i < level; i++) {
+    indent = msStringConcatenate(indent, "  ");
+  }
 
-   if (numNestedGroups[index] <= level) /* no more subgroups */
-   {
+  if (numNestedGroups[index] <= level) { /* no more subgroups */
+    if ((!pabLayerProcessed[index]) && (!isUsedInNestedGroup[index])) {
       /* we are at the deepest level of the group branchings, so add layer now. */
-      msDumpLayer(map, GET_LAYER(map, index), nVersion, script_url_encoded, "");
+      msDumpLayer(map, GET_LAYER(map, index), nVersion, script_url_encoded, indent, validated_language, MS_FALSE);
       pabLayerProcessed[index] = 1; /* done */
-   }
-   else /* not yet there, we have to deal with this group and possible subgroups and layers. */
-   {
-      /* Beginning of a new group... enclose the group in a layer block */
-      msIO_printf("    <Layer>\n");
-      msIO_printf("    <Title>%s</Title>\n", nestedGroups[index][level]);      
-
-      /* Look for one group deeper in the current layer */
-      if (!pabLayerProcessed[index])
-      {
-         msWMSPrintNestedGroups(map, nVersion, pabLayerProcessed,
-                                index, level + 1, nestedGroups, 
-                                numNestedGroups, script_url_encoded);
+    }
+  } else { /* not yet there, we have to deal with this group and possible subgroups and layers. */
+    for (j = 0; j < map->numlayers; j++) {
+      if ( GET_LAYER(map, j)->name && strcasecmp(GET_LAYER(map, j)->name, nestedGroups[index][level]) == 0 ) {
+        break;
       }
+    }
 
-      /* look for subgroups in other layers. */
-      for (j = index + 1; j < map->numlayers; j++) 
-      {
-         if (msWMSIsSubGroup(nestedGroups[index], level, nestedGroups[j], numNestedGroups[j]))
-         {
-            if (!pabLayerProcessed[j])
-            {
-               msWMSPrintNestedGroups(map, nVersion, pabLayerProcessed,
-                                      j, level + 1, nestedGroups, 
-                                      numNestedGroups, script_url_encoded);
-            }
-         }
-         else
-         {
-            /* TODO: if we would sort all layers on "WMS_LAYER_GROUP" beforehand */
-            /* we could break out of this loop at this point, which would increase */
-            /* performance.  */
-         }
+    /* Beginning of a new group... enclose the group in a layer block */
+    if ( j < map->numlayers ) {
+      if (!pabLayerProcessed[j]) {
+        msDumpLayer(map, GET_LAYER(map, j), nVersion, script_url_encoded, indent, validated_language, MS_TRUE);
+        pabLayerProcessed[j] = 1; /* done */
+      }
+    } else {
+      msIO_printf("%s    <Layer>\n", indent);
+      msIO_printf("%s      <Title>%s</Title>\n", indent, nestedGroups[index][level]);
+    }
+
+    /* Look for one group deeper in the current layer */
+    if (!pabLayerProcessed[index]) {
+      msWMSPrintNestedGroups(map, nVersion, pabLayerProcessed,
+                             index, level + 1, nestedGroups,
+                             numNestedGroups, isUsedInNestedGroup,
+                             script_url_encoded, validated_language);
+    }
+
+    /* look for subgroups in other layers. */
+    for (j = index + 1; j < map->numlayers; j++) {
+      if (msWMSIsSubGroup(nestedGroups[index], level, nestedGroups[j], numNestedGroups[j])) {
+        if (!pabLayerProcessed[j]) {
+          msWMSPrintNestedGroups(map, nVersion, pabLayerProcessed,
+                                 j, level + 1, nestedGroups,
+                                 numNestedGroups, isUsedInNestedGroup,
+                                 script_url_encoded, validated_language);
+        }
+      } else {
+        /* TODO: if we would sort all layers on "WMS_LAYER_GROUP" beforehand */
+        /* we could break out of this loop at this point, which would increase */
+        /* performance.  */
       }
-      /* Close group layer block */
-      msIO_printf("    </Layer>\n");
-   }
-   
+    }
+    /* Close group layer block */
+    msIO_printf("%s    </Layer>\n", indent);
+  }
+
+  msFree(indent);
 } /* msWMSPrintNestedGroups */
 
 /*
 ** msWMSGetCapabilities()
 */
-int msWMSGetCapabilities(mapObj *map, int nVersion, cgiRequestObj *req, owsRequestObj *ows_request, 
-                         const char *requested_updatesequence, char *wms_exception_format)
+int msWMSGetCapabilities(mapObj *map, int nVersion, cgiRequestObj *req, owsRequestObj *ows_request,
+                         const char *requested_updatesequence, char *wms_exception_format, const char *requested_language)
 {
   char *dtd_url = NULL;
   char *script_url=NULL, *script_url_encoded=NULL;
-  
+
   char szVersionBuf[OWS_VERSION_MAXLEN];
   char *schemalocation = NULL;
   const char *updatesequence=NULL;
@@ -2016,7 +2682,8 @@ int msWMSGetCapabilities(mapObj *map, int nVersion, cgiRequestObj *req, owsReque
   const char *format_list=NULL;
   char **tokens = NULL;
   int numtokens = 0;
-   
+  char *validated_language = NULL;
+
   updatesequence = msOWSLookupMetadata(&(map->web.metadata), "MO", "updatesequence");
 
   sldenabled = msOWSLookupMetadata(&(map->web.metadata), "MO", "sld_enabled");
@@ -2024,24 +2691,24 @@ int msWMSGetCapabilities(mapObj *map, int nVersion, cgiRequestObj *req, owsReque
   encoding = msOWSLookupMetadata(&(map->web.metadata), "MO", "encoding");
 
   if (sldenabled == NULL)
-      sldenabled = "true";
+    sldenabled = "true";
 
   if (requested_updatesequence != NULL) {
-      i = msOWSNegotiateUpdateSequence(requested_updatesequence, updatesequence);
-      if (i == 0) { /* current */
-          msSetError(MS_WMSERR, "UPDATESEQUENCE parameter (%s) is equal to server (%s)", "msWMSGetCapabilities()", requested_updatesequence, updatesequence);
-          return msWMSException(map, nVersion, "CurrentUpdateSequence", wms_exception_format);
-      }
-      if (i > 0) { /* invalid */
-          msSetError(MS_WMSERR, "UPDATESEQUENCE parameter (%s) is higher than server (%s)", "msWMSGetCapabilities()", requested_updatesequence, updatesequence);
-          return msWMSException(map, nVersion, "InvalidUpdateSequence", wms_exception_format);
-      }
+    i = msOWSNegotiateUpdateSequence(requested_updatesequence, updatesequence);
+    if (i == 0) { /* current */
+      msSetError(MS_WMSERR, "UPDATESEQUENCE parameter (%s) is equal to server (%s)", "msWMSGetCapabilities()", requested_updatesequence, updatesequence);
+      return msWMSException(map, nVersion, "CurrentUpdateSequence", wms_exception_format);
+    }
+    if (i > 0) { /* invalid */
+      msSetError(MS_WMSERR, "UPDATESEQUENCE parameter (%s) is higher than server (%s)", "msWMSGetCapabilities()", requested_updatesequence, updatesequence);
+      return msWMSException(map, nVersion, "InvalidUpdateSequence", wms_exception_format);
+    }
   }
 
   schemalocation = msEncodeHTMLEntities( msOWSGetSchemasLocation(map) );
 
   if (nVersion < 0)
-      nVersion = OWS_1_3_0;     /* Default to 1.3.0 */
+    nVersion = OWS_1_3_0;     /* Default to 1.3.0 */
 
   /* Decide which version we're going to return. */
   if (nVersion < OWS_1_0_7) {
@@ -2054,13 +2721,11 @@ int msWMSGetCapabilities(mapObj *map, int nVersion, cgiRequestObj *req, owsReque
     nVersion = OWS_1_0_7;
     dtd_url = msStrdup(schemalocation);
     dtd_url = msStringConcatenate(dtd_url, "/wms/1.0.7/capabilities_1_0_7.dtd");
-  }
-  else if (nVersion < OWS_1_1_1) {
+  } else if (nVersion < OWS_1_1_1) {
     nVersion = OWS_1_1_0;
     dtd_url = msStrdup(schemalocation);
     dtd_url = msStringConcatenate(dtd_url, "/wms/1.1.0/capabilities_1_1_0.dtd");
-  }
-  else if (nVersion < OWS_1_3_0) {
+  } else if (nVersion < OWS_1_3_0) {
     nVersion = OWS_1_1_1;
     dtd_url = msStrdup(schemalocation);
     /* this exception was added to accomadote the OGC test suite (Bug 1576)*/
@@ -2068,46 +2733,64 @@ int msWMSGetCapabilities(mapObj *map, int nVersion, cgiRequestObj *req, owsReque
       dtd_url = msStringConcatenate(dtd_url, "/wms/1.1.1/WMS_MS_Capabilities.dtd");
     else
       dtd_url = msStringConcatenate(dtd_url, "/wms/1.1.1/capabilities_1_1_1.dtd");
+  } else
+    nVersion = OWS_1_3_0;
+
+  /* This function owns validated_language, so remember to free it later*/
+  validated_language = msOWSGetLanguageFromList(map, "MO", requested_language);
+
+  if (validated_language != NULL) {
+    for(i=0; i<map->numlayers; i++) {
+      layerObj *layer = GET_LAYER(map, i);
+      if(layer->data) layer->data = msCaseReplaceSubstring(layer->data, "%language%", validated_language);
+      if(layer->connection) layer->connection = msCaseReplaceSubstring(layer->connection, "%language%", validated_language);
+    }
   }
-  else
-     nVersion = OWS_1_3_0;
 
   /* We need this server's onlineresource. */
   /* Default to use the value of the "onlineresource" metadata, and if not */
   /* set then build it: "http://$(SERVER_NAME):$(SERVER_PORT)$(SCRIPT_NAME)?" */
   /* the returned string should be freed once we're done with it. */
-  if ((script_url=msOWSGetOnlineResource(map, "MO", "onlineresource", req)) == NULL ||
-      (script_url_encoded = msEncodeHTMLEntities(script_url)) == NULL)
-  {
-      return msWMSException(map, nVersion, NULL, wms_exception_format);
+  if ((script_url=msOWSGetOnlineResource2(map, "MO", "onlineresource", req, validated_language)) == NULL ||
+      (script_url_encoded = msEncodeHTMLEntities(script_url)) == NULL) {
+    msFree(validated_language);
+    return msWMSException(map, nVersion, NULL, wms_exception_format);
   }
 
   if (nVersion <= OWS_1_0_7 || nVersion >= OWS_1_3_0)   /* 1.0.0 to 1.0.7 and >=1.3.0*/
-      if (encoding)
-          msIO_printf("Content-type: text/xml; charset=%s%c%c", encoding,10,10);
-      else
-          msIO_printf("Content-type: text/xml%c%c",10,10);
+    if (encoding)
+      msIO_setHeader("Content-Type","text/xml; charset=%s", encoding);
+    else
+      msIO_setHeader("Content-Type","text/xml");
   else /* 1.1.0 and later */
-      if (encoding)
-          msIO_printf("Content-type: application/vnd.ogc.wms_xml; charset=%s%c%c", encoding,10,10);
-      else
-          msIO_printf("Content-type: application/vnd.ogc.wms_xml%c%c",10,10);
+    if (encoding)
+      msIO_setHeader("Content-Type","application/vnd.ogc.wms_xml; charset=%s", encoding);
+    else
+      msIO_setHeader("Content-Type","application/vnd.ogc.wms_xml");
+  msIO_sendHeaders();
 
   msOWSPrintEncodeMetadata(stdout, &(map->web.metadata),
                            "MO", "encoding", OWS_NOERR,
-                "<?xml version='1.0' encoding=\"%s\" standalone=\"no\" ?>\n",
-                "ISO-8859-1");
+                           "<?xml version='1.0' encoding=\"%s\" standalone=\"no\" ?>\n",
+                           "ISO-8859-1");
 
   /*TODO review wms1.3.0*/
-  if ( nVersion < OWS_1_3_0)
-  {
-      msIO_printf("<!DOCTYPE WMT_MS_Capabilities SYSTEM \"%s\"\n", dtd_url);
-      msIO_printf(" [\n");
-
+  if ( nVersion < OWS_1_3_0) {
+    msIO_printf("<!DOCTYPE WMT_MS_Capabilities SYSTEM \"%s\"\n", dtd_url);
+    msIO_printf(" [\n");
+
+    if (nVersion == OWS_1_1_1 && msOWSLookupMetadata(&(map->web.metadata), "MO", "inspire_capabilities") ) {
+      msIO_printf("<!ELEMENT VendorSpecificCapabilities (inspire_vs:ExtendedCapabilities)><!ELEMENT inspire_vs:ExtendedCapabilities ((inspire_common:MetadataUrl, inspire_common:SupportedLanguages, inspire_common:ResponseLanguage) | (inspire_common:ResourceLocator+, inspire_common:ResourceType, inspire_common:TemporalReference+, inspire_common:Conformity+, inspire_common:MetadataPointOfContact+, inspire_common:MetadataDate, inspire_common:SpatialDataServiceType, inspire_common:MandatoryKeyword+, inspire_common:Keyword*, inspire_common:SupportedLanguages, inspire_common:ResponseLanguage, inspire_common:MetadataUrl?))><!ATTLIST inspire_vs:ExtendedCapabilities xmlns:inspire_vs CDATA #FIXED \"http://inspire.ec.europa.eu/schemas/inspire_vs/1.0\" ><!ELEMENT inspire_common:MetadataUrl (inspire_common:URL, inspire_common:MediaType*)><!ATTLIST inspire_common:MetadataUrl xmlns:inspire_common CDATA #FIXED \"http://inspire.ec.europa.eu/schemas/common/1.0\" xmlns:xsi CDATA #FIXED \"http://www.w3.org/2001/XMLSchema-instance\" xsi:type CDATA #FIXED \"inspire_common:resourceLocatorType\" ><!ELEMENT inspire_common:URL (#PCDATA)><!ATTLIST inspire_common:URL xmlns:inspire_common CDATA #FIXED \"http://inspire.ec.europa.eu/schemas/common/1.0\"><!ELEMENT inspire_common:MediaType (#PCDATA)><!ATTLIST inspire_common:MediaType xmlns:inspire_common CDATA #FIXED \"http://inspire.ec.europa.eu/schemas/common/1.0\"><!ELEMENT inspire_common:SupportedLanguages (inspire_common:DefaultLanguage, inspire_common:SupportedLanguage*)><!ATTLIST inspire_common:SupportedLanguages xmlns:inspire_common CDATA #FIXED \"http://inspire.ec.europa.eu/schemas/common/1.0\" ><!ELEMENT inspire_common:DefaultLanguage (inspire_common:Language)><!ATTLIST inspire_common:DefaultLanguage xmlns:inspire_common CDATA #FIXED \"http://inspire.ec.europa.eu/schemas/common/1.0\" ><!ELEMENT inspire_common:SupportedLanguage (inspire_common:Language)><!ATTLIST inspire_common:SupportedLanguage xmlns:inspire_common CDATA #FIXED \"http://inspire.ec.europa.eu/schemas/common/1.0\" >"
+                  "<!ELEMENT inspire_common:ResponseLanguage (inspire_common:Language)><!ATTLIST inspire_common:ResponseLanguage xmlns:inspire_common CDATA #FIXED \"http://inspire.ec.europa.eu/schemas/common/1.0\" ><!ELEMENT inspire_common:Language (#PCDATA)><!ATTLIST inspire_common:Language xmlns:inspire_common CDATA #FIXED \"http://inspire.ec.europa.eu/schemas/common/1.0\" ><!ELEMENT inspire_common:ResourceLocator (inspire_common:URL, inspire_common:MediaType*)><!ATTLIST inspire_common:ResourceLocator xmlns:inspire_common CDATA #FIXED \"http://inspire.ec.europa.eu/schemas/common/1.0\"><!ELEMENT inspire_common:ResourceType (#PCDATA)> <!ATTLIST inspire_common:ResourceType xmlns:inspire_common CDATA #FIXED \"http://inspire.ec.europa.eu/schemas/common/1.0\" ><!ELEMENT inspire_common:TemporalReference (inspire_common:DateOfCreation?, inspire_common:DateOfLastRevision?, inspire_common:DateOfPublication*, inspire_common:TemporalExtent*)><!ATTLIST inspire_common:TemporalReference xmlns:inspire_common CDATA #FIXED \"http://inspire.ec.europa.eu/schemas/common/1.0\" ><!ELEMENT inspire_common:DateOfCreation (#PCDATA)> <!ATTLIST inspire_common:DateOfCreation xmlns:inspire_common CDATA #FIXED \"http://inspire.ec.europa.eu/schemas/common/1.0\"><!ELEMENT inspire_common:DateOfLastRevision (#PCDATA)><!ATTLIST inspire_common:DateOfLastRevision xmlns:inspire_common CDATA #FIXED \"http://inspire.ec.europa.eu/schemas/common/1.0\"><!ELEMENT inspire_common:DateOfPublication (#PCDATA)><!ATTLIST inspire_common:DateOfPublication xmlns:inspire_common CDATA #FIXED \"http://inspire.ec.europa.eu/schemas/common/1.0\"><!ELEMENT inspire_common:TemporalExtent (inspire_common:IndividualDate | inspire_common:IntervalOfDates)><!ATTLIST inspire_common:TemporalExtent xmlns:inspire_common CDATA #FIXED \"http://inspire.ec.europa.eu/schemas/common/1.0\" ><!ELEMENT inspire_common:IndividualDate (#PCDATA)> <!ATTLIST inspire_common:IndividualDate xmlns:inspire_common CDATA #FIXED \"http://inspire.ec.europa.eu/schemas/common/1.0\">"
+                  "<!ELEMENT inspire_common:IntervalOfDates (inspire_common:StartingDate, inspire_common:EndDate)><!ATTLIST inspire_common:IntervalOfDates xmlns:inspire_common CDATA #FIXED \"http://inspire.ec.europa.eu/schemas/common/1.0\" ><!ELEMENT inspire_common:StartingDate (#PCDATA)><!ATTLIST inspire_common:StartingDate xmlns:inspire_common CDATA #FIXED \"http://inspire.ec.europa.eu/schemas/common/1.0\" ><!ELEMENT inspire_common:EndDate (#PCDATA)><!ATTLIST inspire_common:EndDate xmlns:inspire_common CDATA #FIXED \"http://inspire.ec.europa.eu/schemas/common/1.0\" ><!ELEMENT inspire_common:Conformity (inspire_common:Specification, inspire_common:Degree)><!ATTLIST inspire_common:Conformity xmlns:inspire_common CDATA #FIXED \"http://inspire.ec.europa.eu/schemas/common/1.0\" ><!ELEMENT inspire_common:Specification (inspire_common:Title, (inspire_common:DateOfPublication | inspire_common:DateOfCreation | inspire_common:DateOfLastRevision), inspire_common:URI*, inspire_common:ResourceLocator*)><!ATTLIST inspire_common:Specification xmlns:inspire_common CDATA #FIXED \"http://inspire.ec.europa.eu/schemas/common/1.0\" ><!ELEMENT inspire_common:Title (#PCDATA)><!ATTLIST inspire_common:Title xmlns:inspire_common CDATA #FIXED \"http://inspire.ec.europa.eu/schemas/common/1.0\" ><!ELEMENT inspire_common:URI (#PCDATA)><!ATTLIST inspire_common:URI xmlns:inspire_common CDATA #FIXED \"http://inspire.ec.europa.eu/schemas/common/1.0\" ><!ELEMENT inspire_common:Degree (#PCDATA)><!ATTLIST inspire_common:Degree xmlns:inspire_common CDATA #FIXED \"http://inspire.ec.europa.eu/schemas/common/1.0\" ><!ELEMENT inspire_common:MetadataPointOfContact (inspire_common:OrganisationName, inspire_common:EmailAddress)><!ATTLIST inspire_common:MetadataPointOfContact xmlns:inspire_common CDATA #FIXED \"http://inspire.ec.europa.eu/schemas/common/1.0\" >"
+                  "<!ELEMENT inspire_common:OrganisationName (#PCDATA)><!ATTLIST inspire_common:OrganisationName  xmlns:inspire_common CDATA #FIXED \"http://inspire.ec.europa.eu/schemas/common/1.0\" ><!ELEMENT inspire_common:EmailAddress (#PCDATA)><!ATTLIST inspire_common:EmailAddress xmlns:inspire_common CDATA #FIXED \"http://inspire.ec.europa.eu/schemas/common/1.0\" ><!ELEMENT inspire_common:MetadataDate (#PCDATA)><!ATTLIST inspire_common:MetadataDate xmlns:inspire_common CDATA #FIXED \"http://inspire.ec.europa.eu/schemas/common/1.0\" ><!ELEMENT inspire_common:SpatialDataServiceType (#PCDATA)><!ATTLIST inspire_common:SpatialDataServiceType xmlns:inspire_common CDATA #FIXED \"http://inspire.ec.europa.eu/schemas/common/1.0\" ><!ELEMENT inspire_common:MandatoryKeyword (inspire_common:KeywordValue)><!ATTLIST inspire_common:MandatoryKeyword xmlns:inspire_common CDATA #FIXED \"http://inspire.ec.europa.eu/schemas/common/1.0\" ><!ELEMENT inspire_common:KeywordValue (#PCDATA)><!ATTLIST inspire_common:KeywordValue xmlns:inspire_common CDATA #FIXED \"http://inspire.ec.europa.eu/schemas/common/1.0\" >"
+                  "<!ELEMENT inspire_common:Keyword (inspire_common:OriginatingControlledVocabulary?, inspire_common:KeywordValue)><!ATTLIST inspire_common:Keyword xmlns:inspire_common CDATA #FIXED \"http://inspire.ec.europa.eu/schemas/common/1.0\" xmlns:xsi CDATA #FIXED \"http://www.w3.org/2001/XMLSchemainstance\" xsi:type (inspire_common:inspireTheme_bul | inspire_common:inspireTheme_cze | inspire_common:inspireTheme_dan | inspire_common:inspireTheme_dut | inspire_common:inspireTheme_eng | inspire_common:inspireTheme_est | inspire_common:inspireTheme_fin | inspire_common:inspireTheme_fre | inspire_common:inspireTheme_ger | inspire_common:inspireTheme_gre | inspire_common:inspireTheme_hun | inspire_common:inspireTheme_gle | inspire_common:inspireTheme_ita | inspire_common:inspireTheme_lav | inspire_common:inspireTheme_lit | inspire_common:inspireTheme_mlt | inspire_common:inspireTheme_pol | inspire_common:inspireTheme_por | inspire_common:inspireTheme_rum | inspire_common:inspireTheme_slo | inspire_common:inspireTheme_slv | inspire_common:inspireTheme_spa | inspire_common:inspireTheme_swe) #IMPLIED ><!ELEMENT inspire_common:OriginatingControlledVocabulary (inspire_common:Title, (inspire_common:DateOfPublication | inspire_common:DateOfCreation | inspire_common:DateOfLastRevision), inspire_common:URI*, inspire_common:ResourceLocator*)><!ATTLIST inspire_common:OriginatingControlledVocabulary xmlns:inspire_common CDATA #FIXED \"http://inspire.ec.europa.eu/schemas/common/1.0\">\n");
+    } else {
       /* some mapserver specific declarations will go here */
       msIO_printf(" <!ELEMENT VendorSpecificCapabilities EMPTY>\n");
+    }
 
-      msIO_printf(" ]>  <!-- end of DOCTYPE declaration -->\n\n");
+    msIO_printf(" ]>  <!-- end of DOCTYPE declaration -->\n\n");
   }
 
   updatesequence = msOWSLookupMetadata(&(map->web.metadata), "MO", "updatesequence");
@@ -2116,21 +2799,33 @@ int msWMSGetCapabilities(mapObj *map, int nVersion, cgiRequestObj *req, owsReque
                 msOWSGetVersionString(nVersion, szVersionBuf));
   else
     msIO_printf("<WMT_MS_Capabilities version=\"%s\"",
-                  msOWSGetVersionString(nVersion, szVersionBuf));
+                msOWSGetVersionString(nVersion, szVersionBuf));
   if (updatesequence)
     msIO_printf(" updateSequence=\"%s\"",updatesequence);
 
-  
-  if ( nVersion == OWS_1_3_0)
-  {
-      msIO_printf("  xmlns=\"http://www.opengis.net/wms\""
-                  "   xmlns:sld=\"http://www.opengis.net/sld\""
-                  "   xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
-                  "   xmlns:ms=\"http://mapserver.gis.umn.edu/mapserver\""
-                  "   xsi:schemaLocation=\"http://www.opengis.net/wms %s/wms/%s/capabilities_1_3_0.xsd "
-                  " http://www.opengis.net/sld http://schemas.opengis.net/sld/1.1.0/sld_capabilities.xsd "
-                  " http://mapserver.gis.umn.edu/mapserver %sservice=WMS&version=1.3.0&request=GetSchemaExtension\"",
-         msOWSGetSchemasLocation(map), msOWSGetVersionString(nVersion, szVersionBuf), script_url_encoded);
+
+  if ( nVersion == OWS_1_3_0) {
+    msIO_printf("  xmlns=\"http://www.opengis.net/wms\""
+                "   xmlns:sld=\"http://www.opengis.net/sld\""
+                "   xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+                "   xmlns:ms=\"http://mapserver.gis.umn.edu/mapserver\"");
+
+    if ( msOWSLookupMetadata(&(map->web.metadata), "MO", "inspire_capabilities") ) {
+      msIO_printf("   xmlns:inspire_common=\"http://inspire.ec.europa.eu/schemas/common/1.0\""
+                  "   xmlns:inspire_vs=\"http://inspire.ec.europa.eu/schemas/inspire_vs/1.0\"" );
+    }
+
+    msIO_printf("   xsi:schemaLocation=\"http://www.opengis.net/wms %s/wms/%s/capabilities_1_3_0.xsd "
+                " http://www.opengis.net/sld http://schemas.opengis.net/sld/1.1.0/sld_capabilities.xsd ",
+                msOWSGetSchemasLocation(map), msOWSGetVersionString(nVersion, szVersionBuf));
+
+    if ( msOWSLookupMetadata(&(map->web.metadata), "MO", "inspire_capabilities") ) {
+      msIO_printf(" http://inspire.ec.europa.eu/schemas/inspire_vs/1.0 "
+                  " http://inspire.ec.europa.eu/schemas/inspire_vs/1.0/inspire_vs.xsd");
+    }
+
+    msIO_printf(" http://mapserver.gis.umn.edu/mapserver %sservice=WMS&version=1.3.0&request=GetSchemaExtension\"",
+                script_url_encoded);
   }
 
   msIO_printf(">\n");
@@ -2145,49 +2840,31 @@ int msWMSGetCapabilities(mapObj *map, int nVersion, cgiRequestObj *req, owsReque
 
   /* Service name is defined by the spec and changed at v1.0.0 */
   if (nVersion <= OWS_1_0_7)
-      msIO_printf("  <Name>GetMap</Name>\n");  /* v 1.0.0 to 1.0.7 */
+    msIO_printf("  <Name>GetMap</Name>\n");  /* v 1.0.0 to 1.0.7 */
   else if (nVersion > OWS_1_0_7 && nVersion < OWS_1_3_0)
-      msIO_printf("  <Name>OGC:WMS</Name>\n"); /* v 1.1.0 to 1.1.1*/
+    msIO_printf("  <Name>OGC:WMS</Name>\n"); /* v 1.1.0 to 1.1.1*/
   else
-      msIO_printf("  <Name>WMS</Name>\n"); /* v 1.3.0+ */
-  
+    msIO_printf("  <Name>WMS</Name>\n"); /* v 1.3.0+ */
+
 
   /* the majority of this section is dependent on appropriately named metadata in the WEB object */
-  msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "MO", "title",
-                           OWS_WARN, "  <Title>%s</Title>\n", map->name);
-  msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "MO", "abstract",
-                           OWS_NOERR, "  <Abstract>%s</Abstract>\n", NULL);
+  msOWSPrintEncodeMetadata2(stdout, &(map->web.metadata), "MO", "title",
+                            OWS_WARN, "  <Title>%s</Title>\n", map->name, validated_language);
+  msOWSPrintEncodeMetadata2(stdout, &(map->web.metadata), "MO", "abstract",
+                            OWS_NOERR, "  <Abstract>%s</Abstract>\n", NULL, validated_language);
 
-  if (nVersion == OWS_1_0_0)
-  {
-      /* <Keywords> in V 1.0.0 */
-      /* The 1.0.0 spec doesn't specify which delimiter to use so let's use spaces */
-      msOWSPrintEncodeMetadataList(stdout, &(map->web.metadata),
-                                   "MO", "keywordlist",
-                                   "        <Keywords>",
-                                   "        </Keywords>\n",
-                                   "%s ", NULL);
-  }
-  else
-  {
-      /* <KeywordList><Keyword> ... in V1.0.6+ */
-      msOWSPrintEncodeMetadataList(stdout, &(map->web.metadata),
-                                   "MO", "keywordlist",
-                                   "        <KeywordList>\n",
-                                   "        </KeywordList>\n",
-                                   "          <Keyword>%s</Keyword>\n", NULL);
-  }
+  msWMSPrintKeywordlist(stdout, "  ", "keywordlist", &(map->web.metadata), "MO", nVersion);
 
   /* Service/onlineresource */
   /* Defaults to same as request onlineresource if wms_service_onlineresource  */
   /* is not set. */
   if (nVersion== OWS_1_0_0)
-    msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), 
+    msOWSPrintEncodeMetadata(stdout, &(map->web.metadata),
                              "MO", "service_onlineresource", OWS_NOERR,
-                             "  <OnlineResource>%s</OnlineResource>\n", 
+                             "  <OnlineResource>%s</OnlineResource>\n",
                              script_url_encoded);
   else
-    msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), 
+    msOWSPrintEncodeMetadata(stdout, &(map->web.metadata),
                              "MO", "service_onlineresource", OWS_NOERR,
                              "  <OnlineResource xmlns:xlink=\"http://www.w3.org/1999/xlink\" xlink:href=\"%s\"/>\n",
                              script_url_encoded);
@@ -2202,16 +2879,15 @@ int msWMSGetCapabilities(mapObj *map, int nVersion, cgiRequestObj *req, owsReque
 
   msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "MO",
                            "accessconstraints", OWS_NOERR,
-                        "  <AccessConstraints>%s</AccessConstraints>\n", NULL);
+                           "  <AccessConstraints>%s</AccessConstraints>\n", NULL);
 
-  if (nVersion >= OWS_1_3_0)
-  {
-      layerlimit = msOWSLookupMetadata(&(map->web.metadata), "MO", "layerlimit");
-      if (layerlimit) {
-        msIO_printf("  <LayerLimit>%s</LayerLimit>\n", layerlimit);
-      }
-      msIO_printf("  <MaxWidth>%d</MaxWidth>\n", map->maxsize);
-      msIO_printf("  <MaxHeight>%d</MaxHeight>\n", map->maxsize);
+  if (nVersion >= OWS_1_3_0) {
+    layerlimit = msOWSLookupMetadata(&(map->web.metadata), "MO", "layerlimit");
+    if (layerlimit) {
+      msIO_printf("  <LayerLimit>%s</LayerLimit>\n", layerlimit);
+    }
+    msIO_printf("  <MaxWidth>%d</MaxWidth>\n", map->maxsize);
+    msIO_printf("  <MaxHeight>%d</MaxHeight>\n", map->maxsize);
   }
 
   msIO_printf("</Service>\n\n");
@@ -2220,172 +2896,155 @@ int msWMSGetCapabilities(mapObj *map, int nVersion, cgiRequestObj *req, owsReque
   msIO_printf("<Capability>\n");
   msIO_printf("  <Request>\n");
 
-  if (nVersion <= OWS_1_0_7)
-  {
+  if (nVersion <= OWS_1_0_7) {
     /* WMS 1.0.0 to 1.0.7 - We don't try to use outputformats list here for now */
-      if (msOWSRequestIsEnabled(map, NULL, "M", "GetMap", MS_TRUE)) 
-          msWMSPrintRequestCap(nVersion, "Map", script_url_encoded, ""
+    if (msOWSRequestIsEnabled(map, NULL, "M", "GetMap", MS_FALSE))
+      msWMSPrintRequestCap(nVersion, "Map", script_url_encoded, ""
 
 #ifdef USE_GD_GIF
-                      "<GIF />"
+                           "<GIF />"
 #endif
-#ifdef USE_GD_PNG
-                      "<PNG />"
+#if defined USE_GD_PNG || defined USE_PNG
+                           "<PNG />"
 #endif
-#ifdef USE_GD_JPEG
-                      "<JPEG />"
+#if defined USE_GD_JPEG || defined USE_JPEG
+                           "<JPEG />"
 #endif
-                       "<SVG />"  
-                      , NULL);
-      if (msOWSRequestIsEnabled(map, NULL, "M", "GetCapabilities", MS_TRUE)) 
-          msWMSPrintRequestCap(nVersion, "Capabilities", script_url_encoded, "<WMS_XML />", NULL);
-      if (msOWSRequestIsEnabled(map, NULL, "M", "GetFeatureInfo", MS_TRUE)) 
-          msWMSPrintRequestCap(nVersion, "FeatureInfo", script_url_encoded, "<MIME /><GML.1 />", NULL);
-  }
-  else
-  {
+                           "<SVG />"
+                           , NULL);
+    if (msOWSRequestIsEnabled(map, NULL, "M", "GetCapabilities", MS_FALSE))
+      msWMSPrintRequestCap(nVersion, "Capabilities", script_url_encoded, "<WMS_XML />", NULL);
+    if (msOWSRequestIsEnabled(map, NULL, "M", "GetFeatureInfo", MS_FALSE))
+      msWMSPrintRequestCap(nVersion, "FeatureInfo", script_url_encoded, "<MIME /><GML.1 />", NULL);
+  } else {
     char *mime_list[20];
-     int mime_count = 0;
-     int max_mime = 20;
+    int mime_count = 0;
+    int max_mime = 20;
     /* WMS 1.1.0 and later */
     /* Note changes to the request names, their ordering, and to the formats */
 
-     if (msOWSRequestIsEnabled(map, NULL, "M", "GetCapabilities", MS_TRUE)) 
-     {
-         if (nVersion >= OWS_1_3_0)
-             msWMSPrintRequestCap(nVersion, "GetCapabilities", script_url_encoded,
-                                  "text/xml",
-                                  NULL);
-         else
-             msWMSPrintRequestCap(nVersion, "GetCapabilities", script_url_encoded,
-                                  "application/vnd.ogc.wms_xml",
-                                  NULL);
-     }
+    if (msOWSRequestIsEnabled(map, NULL, "M", "GetCapabilities", MS_FALSE)) {
+      if (nVersion >= OWS_1_3_0)
+        msWMSPrintRequestCap(nVersion, "GetCapabilities", script_url_encoded,
+                             "text/xml",
+                             NULL);
+      else
+        msWMSPrintRequestCap(nVersion, "GetCapabilities", script_url_encoded,
+                             "application/vnd.ogc.wms_xml",
+                             NULL);
+    }
 
     msGetOutputFormatMimeListWMS(map,mime_list,sizeof(mime_list)/sizeof(char*));
-    if (msOWSRequestIsEnabled(map, NULL, "M", "GetMap", MS_TRUE))
-        msWMSPrintRequestCap(nVersion, "GetMap", script_url_encoded,
-                             mime_list[0], mime_list[1], mime_list[2], mime_list[3],
-                             mime_list[4], mime_list[5], mime_list[6], mime_list[7],
-                             mime_list[8], mime_list[9], mime_list[10], mime_list[11],
-                             mime_list[12], mime_list[13], mime_list[14], mime_list[15],
-                             mime_list[16], mime_list[17], mime_list[18], mime_list[19],
-                             NULL );
+    if (msOWSRequestIsEnabled(map, NULL, "M", "GetMap", MS_FALSE))
+      msWMSPrintRequestCap(nVersion, "GetMap", script_url_encoded,
+                           mime_list[0], mime_list[1], mime_list[2], mime_list[3],
+                           mime_list[4], mime_list[5], mime_list[6], mime_list[7],
+                           mime_list[8], mime_list[9], mime_list[10], mime_list[11],
+                           mime_list[12], mime_list[13], mime_list[14], mime_list[15],
+                           mime_list[16], mime_list[17], mime_list[18], mime_list[19],
+                           NULL );
 
     format_list = msOWSLookupMetadata(&(map->web.metadata), "M",
                                       "getfeatureinfo_formatlist");
     /*feature_info_mime_type depricated for MapServer 6.0*/
     if (!format_list)
-       format_list = msOWSLookupMetadata(&(map->web.metadata), "MO", 
-                                         "feature_info_mime_type");
-    
-    if (format_list && strlen(format_list) > 0) 
-    {
-        tokens = msStringSplit(format_list,  ',', &numtokens);
-        if (tokens && numtokens > 0)
-        {
-            mime_count = 0;
-            for(i=0; i < numtokens; i++ )
-            {
-                msStringTrim(tokens[i]);
-                /*text plain and gml do not need to be a format and accepted by default*/
-                /*can not really validate since the old way of using template
-                  with wei->header, layer->template ... should be kept*/
-                if (strlen(tokens[i]) > 0 && mime_count<max_mime)
-                    mime_list[mime_count++] = tokens[i];
-            }
-        }
-        /*add text/plain and gml */
-        if (strcasestr(format_list, "GML") == 0 &&
-            strcasestr(format_list, "application/vnd.ogc.gml") == 0)
-        {
-            if (mime_count<max_mime)
-              mime_list[mime_count++] = "application/vnd.ogc.gml";
+      format_list = msOWSLookupMetadata(&(map->web.metadata), "MO",
+                                        "feature_info_mime_type");
+
+    if (format_list && strlen(format_list) > 0) {
+      tokens = msStringSplit(format_list,  ',', &numtokens);
+      if (tokens && numtokens > 0) {
+        mime_count = 0;
+        for(i=0; i < numtokens; i++ ) {
+          msStringTrim(tokens[i]);
+          /*text plain and gml do not need to be a format and accepted by default*/
+          /*can not really validate since the old way of using template
+            with wei->header, layer->template ... should be kept*/
+          if (strlen(tokens[i]) > 0 && mime_count<max_mime)
+            mime_list[mime_count++] = tokens[i];
         }
-        if (strcasestr(format_list, "text/plain") == 0 &&
-            strcasestr(format_list, "MIME") == 0)
-        {
-            if (mime_count<max_mime)
-              mime_list[mime_count++] = "text/plain";
-            else /*force always this format*/
-              mime_list[max_mime-1] = "text/plain";
-        }
-        
-        
-        if (msOWSRequestIsEnabled(map, NULL, "M", "GetFeatureInfo", MS_TRUE)) 
-        {
-            if (mime_count>0)
-            {
-                if (mime_count<max_mime)
-                    mime_list[mime_count] = NULL;
-                msWMSPrintRequestCap(nVersion, "GetFeatureInfo", script_url_encoded,
-                                     mime_list[0], mime_list[1], mime_list[2], mime_list[3],
-                                     mime_list[4], mime_list[5], mime_list[6], mime_list[7],
-                                     mime_list[8], mime_list[9], mime_list[10], mime_list[11],
-                                     mime_list[12], mime_list[13], mime_list[14], mime_list[15],
-                                     mime_list[16], mime_list[17], mime_list[18], mime_list[19],
-                                     NULL);
-            }
-            /*if all formats given are invalid go to default*/
-            else
-                msWMSPrintRequestCap(nVersion, "GetFeatureInfo", script_url_encoded,
-                                     "text/plain",
-                                     "application/vnd.ogc.gml",
-                                     NULL);
+      }
+      /*add text/plain and gml */
+      if (strcasestr(format_list, "GML") == 0 &&
+          strcasestr(format_list, "application/vnd.ogc.gml") == 0) {
+        if (mime_count<max_mime)
+          mime_list[mime_count++] = "application/vnd.ogc.gml";
+      }
+      if (strcasestr(format_list, "text/plain") == 0 &&
+          strcasestr(format_list, "MIME") == 0) {
+        if (mime_count<max_mime)
+          mime_list[mime_count++] = "text/plain";
+        else /*force always this format*/
+          mime_list[max_mime-1] = "text/plain";
+      }
+
+
+      if (msOWSRequestIsEnabled(map, NULL, "M", "GetFeatureInfo", MS_FALSE)) {
+        if (mime_count>0) {
+          if (mime_count<max_mime)
+            mime_list[mime_count] = NULL;
+          msWMSPrintRequestCap(nVersion, "GetFeatureInfo", script_url_encoded,
+                               mime_list[0], mime_list[1], mime_list[2], mime_list[3],
+                               mime_list[4], mime_list[5], mime_list[6], mime_list[7],
+                               mime_list[8], mime_list[9], mime_list[10], mime_list[11],
+                               mime_list[12], mime_list[13], mime_list[14], mime_list[15],
+                               mime_list[16], mime_list[17], mime_list[18], mime_list[19],
+                               NULL);
         }
+        /*if all formats given are invalid go to default*/
+        else
+          msWMSPrintRequestCap(nVersion, "GetFeatureInfo", script_url_encoded,
+                               "text/plain",
+                               "application/vnd.ogc.gml",
+                               NULL);
+      }
 
-        if (numtokens>0)
-          msFreeCharArray(tokens, numtokens);
+      if (numtokens>0)
+        msFreeCharArray(tokens, numtokens);
+    } else {
+      if (msOWSRequestIsEnabled(map, NULL, "M", "GetFeatureInfo", MS_FALSE))
+        msWMSPrintRequestCap(nVersion, "GetFeatureInfo", script_url_encoded,
+                             "text/plain",
+                             "application/vnd.ogc.gml",
+                             NULL);
     }
-    else 
-    {
-        if (msOWSRequestIsEnabled(map, NULL, "M", "GetFeatureInfo", MS_TRUE)) 
-            msWMSPrintRequestCap(nVersion, "GetFeatureInfo", script_url_encoded,
-                                 "text/plain",
-                                 "application/vnd.ogc.gml",
-                                 NULL);
-    }
-    
+
 
     if (strcasecmp(sldenabled, "true") == 0) {
-        if (msOWSRequestIsEnabled(map, NULL, "M", "DescribeLayer", MS_TRUE)) 
-        {
-            if (nVersion == OWS_1_3_0)
-                msWMSPrintRequestCap(nVersion, "sld:DescribeLayer", script_url_encoded, "text/xml", NULL);
-            else
-                msWMSPrintRequestCap(nVersion, "DescribeLayer", script_url_encoded, "text/xml", NULL);
-        }
+      if (msOWSRequestIsEnabled(map, NULL, "M", "DescribeLayer", MS_FALSE)) {
+        if (nVersion == OWS_1_3_0)
+          msWMSPrintRequestCap(nVersion, "sld:DescribeLayer", script_url_encoded, "text/xml", NULL);
+        else
+          msWMSPrintRequestCap(nVersion, "DescribeLayer", script_url_encoded, "text/xml", NULL);
+      }
 
-        msGetOutputFormatMimeListImg(map,mime_list,sizeof(mime_list)/sizeof(char*));
-
-        if (nVersion >= OWS_1_1_1) {
-           if (nVersion == OWS_1_3_0)
-           {
-               if (msOWSRequestIsEnabled(map, NULL, "M", "GetLegendGraphic", MS_TRUE)) 
-                   msWMSPrintRequestCap(nVersion, "sld:GetLegendGraphic", script_url_encoded,
-                                        mime_list[0], mime_list[1], mime_list[2], mime_list[3],
-                                        mime_list[4], mime_list[5], mime_list[6], mime_list[7],
-                                        mime_list[8], mime_list[9], mime_list[10], mime_list[11],
-                                        mime_list[12], mime_list[13], mime_list[14], mime_list[15],
-                                        mime_list[16], mime_list[17], mime_list[18], mime_list[19],
-                                        NULL );
-               if (msOWSRequestIsEnabled(map, NULL, "M", "GetStyles", MS_TRUE)) 
-                   msWMSPrintRequestCap(nVersion, "ms:GetStyles", script_url_encoded, "text/xml", NULL);
-           }
-           else 
-           {
-               if (msOWSRequestIsEnabled(map, NULL, "M", "GetLegendGraphic", MS_TRUE)) 
-                   msWMSPrintRequestCap(nVersion, "GetLegendGraphic", script_url_encoded,
-                                        mime_list[0], mime_list[1], mime_list[2], mime_list[3],
-                                        mime_list[4], mime_list[5], mime_list[6], mime_list[7],
-                                        mime_list[8], mime_list[9], mime_list[10], mime_list[11],
-                                        mime_list[12], mime_list[13], mime_list[14], mime_list[15],
-                                        mime_list[16], mime_list[17], mime_list[18], mime_list[19],
-                                        NULL );
-               if (msOWSRequestIsEnabled(map, NULL, "M", "GetStyles", MS_TRUE)) 
-                   msWMSPrintRequestCap(nVersion, "GetStyles", script_url_encoded, "text/xml", NULL);
-           }
-       }
+      msGetOutputFormatMimeListImg(map,mime_list,sizeof(mime_list)/sizeof(char*));
+
+      if (nVersion >= OWS_1_1_1) {
+        if (nVersion == OWS_1_3_0) {
+          if (msOWSRequestIsEnabled(map, NULL, "M", "GetLegendGraphic", MS_FALSE))
+            msWMSPrintRequestCap(nVersion, "sld:GetLegendGraphic", script_url_encoded,
+                                 mime_list[0], mime_list[1], mime_list[2], mime_list[3],
+                                 mime_list[4], mime_list[5], mime_list[6], mime_list[7],
+                                 mime_list[8], mime_list[9], mime_list[10], mime_list[11],
+                                 mime_list[12], mime_list[13], mime_list[14], mime_list[15],
+                                 mime_list[16], mime_list[17], mime_list[18], mime_list[19],
+                                 NULL );
+          if (msOWSRequestIsEnabled(map, NULL, "M", "GetStyles", MS_FALSE))
+            msWMSPrintRequestCap(nVersion, "ms:GetStyles", script_url_encoded, "text/xml", NULL);
+        } else {
+          if (msOWSRequestIsEnabled(map, NULL, "M", "GetLegendGraphic", MS_FALSE))
+            msWMSPrintRequestCap(nVersion, "GetLegendGraphic", script_url_encoded,
+                                 mime_list[0], mime_list[1], mime_list[2], mime_list[3],
+                                 mime_list[4], mime_list[5], mime_list[6], mime_list[7],
+                                 mime_list[8], mime_list[9], mime_list[10], mime_list[11],
+                                 mime_list[12], mime_list[13], mime_list[14], mime_list[15],
+                                 mime_list[16], mime_list[17], mime_list[18], mime_list[19],
+                                 NULL );
+          if (msOWSRequestIsEnabled(map, NULL, "M", "GetStyles", MS_FALSE))
+            msWMSPrintRequestCap(nVersion, "GetStyles", script_url_encoded, "text/xml", NULL);
+        }
+      }
     }
   }
 
@@ -2393,29 +3052,32 @@ int msWMSGetCapabilities(mapObj *map, int nVersion, cgiRequestObj *req, owsReque
 
   msIO_printf("  <Exception>\n");
   if (nVersion <= OWS_1_0_7)
-      msIO_printf("    <Format><BLANK /><INIMAGE /><WMS_XML /></Format>\n");
-  else if (nVersion <= OWS_1_1_1)
-  {
-      msIO_printf("    <Format>application/vnd.ogc.se_xml</Format>\n");
-      msIO_printf("    <Format>application/vnd.ogc.se_inimage</Format>\n");
-      msIO_printf("    <Format>application/vnd.ogc.se_blank</Format>\n");
-  }
-  else /*>=1.3.0*/
-  {
-       msIO_printf("    <Format>XML</Format>\n");
-       msIO_printf("    <Format>INIMAGE</Format>\n");
-       msIO_printf("    <Format>BLANK</Format>\n");
-       
+    msIO_printf("    <Format><BLANK /><INIMAGE /><WMS_XML /></Format>\n");
+  else if (nVersion <= OWS_1_1_1) {
+    msIO_printf("    <Format>application/vnd.ogc.se_xml</Format>\n");
+    msIO_printf("    <Format>application/vnd.ogc.se_inimage</Format>\n");
+    msIO_printf("    <Format>application/vnd.ogc.se_blank</Format>\n");
+  } else { /*>=1.3.0*/
+    msIO_printf("    <Format>XML</Format>\n");
+    msIO_printf("    <Format>INIMAGE</Format>\n");
+    msIO_printf("    <Format>BLANK</Format>\n");
+
   }
   msIO_printf("  </Exception>\n");
 
-
-  if (nVersion != OWS_1_3_0) 
-    msIO_printf("  <VendorSpecificCapabilities />\n"); /* nothing yet */
+  if (nVersion != OWS_1_3_0) {
+    /* INSPIRE extended capabilities for WMS 1.1.1 */
+    if (nVersion == OWS_1_1_1 && msOWSLookupMetadata(&(map->web.metadata), "MO", "inspire_capabilities") ) {
+      msIO_printf("  <VendorSpecificCapabilities>\n");
+      msOWSPrintInspireCommonExtendedCapabilities(stdout, map, "MO", OWS_WARN, "inspire_vs:ExtendedCapabilities", validated_language, OWS_WMS);
+      msIO_printf("  </VendorSpecificCapabilities>\n");
+    } else {
+      msIO_printf("  <VendorSpecificCapabilities />\n"); /* nothing yet */
+    }
+  }
 
   /* SLD support */
-  if (strcasecmp(sldenabled, "true") == 0)
-  {
+  if (strcasecmp(sldenabled, "true") == 0) {
     if (nVersion >= OWS_1_0_7) {
       if (nVersion >= OWS_1_3_0)
         msIO_printf("  <sld:UserDefinedSymbolization SupportSLD=\"1\" UserLayer=\"0\" UserStyle=\"1\" RemoteWFS=\"0\" InlineFeature=\"0\" RemoteWCS=\"0\"/>\n");
@@ -2424,288 +3086,426 @@ int msWMSGetCapabilities(mapObj *map, int nVersion, cgiRequestObj *req, owsReque
     }
   }
 
-  /* Top-level layer with map extents and SRS, encloses all map layers */
-  msIO_printf("  <Layer>\n");
-
-  /* Layer Name is optional but title is mandatory. */
-  if (map->name && strlen(map->name) > 0 &&
-      (msIsXMLTagValid(map->name) == MS_FALSE || isdigit(map->name[0])))
-    msIO_fprintf(stdout, "<!-- WARNING: The layer name '%s' might contain spaces or "
-                 "invalid characters or may start with a number. This could lead to potential problems. -->\n", 
-                 map->name);
-  msOWSPrintEncodeParam(stdout, "MAP.NAME", map->name, OWS_NOERR,
-                        "    <Name>%s</Name>\n", NULL);
-
-  if (msOWSLookupMetadata(&(map->web.metadata), "MO", "rootlayer_title"))
-    msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "MO", "rootlayer_title", OWS_WARN, "    <Title>%s</Title>\n", map->name);
-
-  else 
-    msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "MO", "title", OWS_WARN, "    <Title>%s</Title>\n", map->name);
+  /* INSPIRE extended capabilities for WMS 1.3.0 */
+  if (nVersion >= OWS_1_3_0 && msOWSLookupMetadata(&(map->web.metadata), "MO", "inspire_capabilities") ) {
+    msOWSPrintInspireCommonExtendedCapabilities(stdout, map, "MO", OWS_WARN, "inspire_vs:ExtendedCapabilities", validated_language, OWS_WMS);
+  }
 
-  if (msOWSLookupMetadata(&(map->web.metadata), "MO", "rootlayer_abstract"))
-    msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "MO", "rootlayer_abstract", OWS_NOERR, "    <Abstract>%s</Abstract>\n", map->name);
-  else
-    msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "MO", "abstract", OWS_NOERR, "    <Abstract>%s</Abstract>\n", map->name);
+  /* Top-level layer with map extents and SRS, encloses all map layers */
+  /* Output only if at least one layers is enabled. */
+  if (ows_request->numlayers == 0) {
+    msIO_fprintf(stdout, "  <!-- WARNING: No WMS layers are enabled. Check wms/ows_enable_request settings. -->\n");
+  } else {
+    msIO_printf("  <Layer>\n");
 
+    /* Layer Name is optional but title is mandatory. */
+    if (map->name && strlen(map->name) > 0 &&
+        (msIsXMLTagValid(map->name) == MS_FALSE || isdigit(map->name[0])))
+      msIO_fprintf(stdout, "<!-- WARNING: The layer name '%s' might contain spaces or "
+                   "invalid characters or may start with a number. This could lead to potential problems. -->\n",
+                   map->name);
+    msOWSPrintEncodeParam(stdout, "MAP.NAME", map->name, OWS_NOERR,
+                          "    <Name>%s</Name>\n", NULL);
 
-  if (msOWSLookupMetadata(&(map->web.metadata), "MO", "rootlayer_keywordlist"))
-    pszTmp = msStrdup("rootlayer_keywordlist");
-   else
-    pszTmp = msStrdup("keywordlist");
+    if (msOWSLookupMetadataWithLanguage(&(map->web.metadata), "MO", "rootlayer_title", validated_language))
+      msOWSPrintEncodeMetadata2(stdout, &(map->web.metadata), "MO", "rootlayer_title", OWS_WARN, "    <Title>%s</Title>\n", map->name, validated_language);
 
-  if (nVersion == OWS_1_0_0)
-  {
-     /* <Keywords> in V 1.0.0 */
-     /* The 1.0.0 spec doesn't specify which delimiter to use so let's use spaces */
-     msOWSPrintEncodeMetadataList(stdout, &(map->web.metadata), "MO",
-                                  pszTmp,
-                                  "    <Keywords>",
-                                  "    </Keywords>\n",
-                                  "%s ", NULL);
-  }
-  else
-  {
-     /* <KeywordList><Keyword> ... in V1.0.6+ */
-     msOWSPrintEncodeMetadataList(stdout, &(map->web.metadata), "MO",
-                                  pszTmp,
-                                  "    <KeywordList>\n",
-                                  "    </KeywordList>\n",
-                                  "     <Keyword>%s</Keyword>\n", NULL);
-  }
+    else
+      msOWSPrintEncodeMetadata2(stdout, &(map->web.metadata), "MO", "title", OWS_WARN, "    <Title>%s</Title>\n", map->name, validated_language);
 
-  msFree(pszTmp);
+    if (msOWSLookupMetadataWithLanguage(&(map->web.metadata), "MO", "rootlayer_abstract", validated_language))
+      msOWSPrintEncodeMetadata2(stdout, &(map->web.metadata), "MO", "rootlayer_abstract", OWS_NOERR, "    <Abstract>%s</Abstract>\n", map->name, validated_language);
+    else
+      msOWSPrintEncodeMetadata2(stdout, &(map->web.metadata), "MO", "abstract", OWS_NOERR, "    <Abstract>%s</Abstract>\n", map->name, validated_language);
 
-  /* According to normative comments in the 1.0.7 DTD, the root layer's SRS tag */
-  /* is REQUIRED.  It also suggests that we use an empty SRS element if there */
-  /* is no common SRS. */
-  if (nVersion > OWS_1_1_0)
-  {
+    if (msOWSLookupMetadata(&(map->web.metadata), "MO", "rootlayer_keywordlist") ||
+        msOWSLookupMetadata(&(map->web.metadata), "MO", "rootlayer_keywordlist_vocabulary"))
+      pszTmp = msStrdup("rootlayer_keywordlist");
+    else
+      pszTmp = msStrdup("keywordlist");
+    msWMSPrintKeywordlist(stdout, "    ", pszTmp, &(map->web.metadata), "MO", nVersion);
+    msFree(pszTmp);
+
+    /* According to normative comments in the 1.0.7 DTD, the root layer's SRS tag */
+    /* is REQUIRED.  It also suggests that we use an empty SRS element if there */
+    /* is no common SRS. */
+    if (nVersion > OWS_1_1_0) {
       /* starting 1.1.1 SRS are given in individual tags */
       if (nVersion >= OWS_1_3_0)
-          msOWSPrintEncodeParamList(stdout, "(at least one of) "
-                                "MAP.PROJECTION, LAYER.PROJECTION "
-                                "or wms_srs metadata", 
-                                msOWSGetEPSGProj(&(map->projection), 
-                                                 &(map->web.metadata),
-                                                 "MO", MS_FALSE),
-                                OWS_WARN, ' ', NULL, NULL, 
-                                "    <CRS>%s</CRS>\n", "");
+        msOWSPrintEncodeParamList(stdout, "(at least one of) "
+                                  "MAP.PROJECTION, LAYER.PROJECTION "
+                                  "or wms_srs metadata",
+                                  msOWSGetEPSGProj(&(map->projection),
+                                      &(map->web.metadata),
+                                      "MO", MS_FALSE),
+                                  OWS_WARN, ' ', NULL, NULL,
+                                  "    <CRS>%s</CRS>\n", "");
       else
         msOWSPrintEncodeParamList(stdout, "(at least one of) "
-                                "MAP.PROJECTION, LAYER.PROJECTION "
-                                "or wms_srs metadata", 
-                                msOWSGetEPSGProj(&(map->projection), 
-                                                 &(map->web.metadata),
-                                                 "MO", MS_FALSE),
-                                OWS_WARN, ' ', NULL, NULL, 
-                                "    <SRS>%s</SRS>\n", "");
-  }
-  else
+                                  "MAP.PROJECTION, LAYER.PROJECTION "
+                                  "or wms_srs metadata",
+                                  msOWSGetEPSGProj(&(map->projection),
+                                      &(map->web.metadata),
+                                      "MO", MS_FALSE),
+                                  OWS_WARN, ' ', NULL, NULL,
+                                  "    <SRS>%s</SRS>\n", "");
+    } else
       /* If map has no proj then every layer MUST have one or produce a warning */
-    msOWSPrintEncodeParam(stdout, "MAP.PROJECTION (or wms_srs metadata)",
-                            msOWSGetEPSGProj(&(map->projection), 
+      msOWSPrintEncodeParam(stdout, "MAP.PROJECTION (or wms_srs metadata)",
+                            msOWSGetEPSGProj(&(map->projection),
                                              &(map->web.metadata),
                                              "MO", MS_FALSE),
                             OWS_WARN, "    <SRS>%s</SRS>\n", "");
 
-  if (nVersion >= OWS_1_3_0)
-    msOWSPrintEX_GeographicBoundingBox(stdout, "    ", &(map->extent),
-                                       &(map->projection));
-  else
-    msOWSPrintLatLonBoundingBox(stdout, "    ", &(map->extent),
-                                &(map->projection), NULL, OWS_WMS);
+    if (nVersion >= OWS_1_3_0)
+      msOWSPrintEX_GeographicBoundingBox(stdout, "    ", &(map->extent),
+                                         &(map->projection));
+    else
+      msOWSPrintLatLonBoundingBox(stdout, "    ", &(map->extent),
+                                  &(map->projection), NULL, OWS_WMS);
 
-  msOWSPrintBoundingBox( stdout, "    ", &(map->extent), &(map->projection),
-                         NULL, &(map->web.metadata), "MO", nVersion);
+    msOWSPrintBoundingBox( stdout, "    ", &(map->extent), &(map->projection),
+                           NULL, &(map->web.metadata), "MO", nVersion);
 
-  if (nVersion >= OWS_1_0_7) {
-    msWMSPrintAttribution(stdout, "    ", &(map->web.metadata), "MO");
-  }
+    if (nVersion >= OWS_1_0_7) {
+      msWMSPrintAttribution(stdout, "    ", &(map->web.metadata), "MO");
+    }
 
-  if (nVersion <  OWS_1_3_0)
-    msWMSPrintScaleHint("    ", map->web.minscaledenom, map->web.maxscaledenom,
-                        map->resolution);
-  else
-    msWMSPrintScaleDenominator("    ", map->web.minscaledenom, map->web.maxscaledenom);
+    /* AuthorityURL support and Identifier support, only available >= WMS 1.1.0 */
+    if(nVersion >= OWS_1_1_0) {
+      msWMSPrintAuthorityURL(stdout, "    ", &(map->web.metadata), "MO");
+      msWMSPrintIdentifier(stdout, "    ", &(map->web.metadata), "MO");
+    }
+
+    /* MetadataURL */
+    if(nVersion >= OWS_1_1_0)
+      msOWSPrintURLType(stdout, &(map->web.metadata), "MO", "metadataurl",
+                        OWS_NOERR, NULL, "MetadataURL", " type=\"%s\"",
+                        NULL, NULL, ">\n      <Format>%s</Format",
+                        "\n      <OnlineResource xmlns:xlink=\""
+                        "http://www.w3.org/1999/xlink\" "
+                        "xlink:type=\"simple\" xlink:href=\"%s\"/>\n    ",
+                        MS_TRUE, MS_FALSE, MS_FALSE, MS_TRUE, MS_TRUE,
+                        NULL, NULL, NULL, NULL, NULL, "    ");
+
+    /* DataURL */
+    if(nVersion < OWS_1_1_0)
+      msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "MO", "dataurl_href",
+                               OWS_NOERR, "    <DataURL>%s</DataURL>\n",
+                               NULL);
+    else
+      msOWSPrintURLType(stdout, &(map->web.metadata), "MO", "dataurl",
+                        OWS_NOERR, NULL, "DataURL", NULL, NULL, NULL,
+                        ">\n      <Format>%s</Format",
+                        "\n      <OnlineResource xmlns:xlink=\""
+                        "http://www.w3.org/1999/xlink\" "
+                        "xlink:type=\"simple\" xlink:href=\"%s\"/>\n    ",
+                        MS_FALSE, MS_FALSE, MS_FALSE, MS_TRUE, MS_TRUE,
+                        NULL, NULL, NULL, NULL, NULL, "    ");
+
+    if (nVersion <  OWS_1_3_0)
+      msWMSPrintScaleHint("    ", map->web.minscaledenom, map->web.maxscaledenom,
+                          map->resolution);
+    else
+      msWMSPrintScaleDenominator("    ", map->web.minscaledenom, map->web.maxscaledenom);
+
+    if (map->name && strlen(map->name) > 0 && msOWSLookupMetadata(&(map->web.metadata), "MO", "inspire_capabilities") ) {
+      char *pszEncodedName = NULL;
+      const char *styleName = NULL;
+      char *pszEncodedStyleName = NULL;
+      const char *legendURL = NULL;
+
+      pszEncodedName = msEncodeHTMLEntities(map->name);
+
+      styleName = msOWSLookupMetadata(&(map->web.metadata), "MO", "style_name");
+      if (styleName == NULL)
+        styleName = "default";
+
+      pszEncodedStyleName = msEncodeHTMLEntities(styleName);
+
+      msIO_fprintf(stdout, "    <Style>\n");
+      msIO_fprintf(stdout, "       <Name>%s</Name>\n", pszEncodedStyleName);
+      msOWSPrintEncodeMetadata2(stdout, &(map->web.metadata), "MO",
+                                "style_title",
+                                OWS_NOERR,
+                                "       <Title>%s</Title>\n",
+                                styleName, validated_language);
+
+      legendURL = msOWSLookupMetadata(&(map->web.metadata), "MO", "style_legendurl_href");
+      if (legendURL) {
+        msOWSPrintURLType(stdout, &(map->web.metadata),
+                          "MO", "style_legendurl",
+                          OWS_NOERR, NULL,
+                          "LegendURL", NULL,
+                          " width=\"%s\"", " height=\"%s\"",
+                          ">\n          <Format>%s</Format",
+                          "\n          <OnlineResource "
+                          "xmlns:xlink=\"http://www.w3.org/1999/xlink\""
+                          " xlink:type=\"simple\" xlink:href=\"%s\"/>\n"
+                          "       ",
+                          MS_FALSE, MS_TRUE, MS_TRUE, MS_TRUE, MS_TRUE,
+                          NULL, NULL, NULL, NULL, NULL, "       ");
+      } else {
+        int i, num_layers = 0;
+        int *group_layers = (int *)msSmallMalloc(sizeof(int)*map->numlayers);
+
+        for(i=0; i<map->numlayers; i++)
+          if (msIntegerInArray(GET_LAYER(map, i)->index, ows_request->enabled_layers, ows_request->numlayers))
+            group_layers[num_layers++] = i;
+
+        if (num_layers > 0) {
+          int size_x=0, size_y=0;
+          size_t bufferSize = 0;
+          char *pszLegendURL = NULL;
+          char *pszMimetype = NULL;
+          char **tokens = NULL;
+          int numtokens = 0;
+          char width[10], height[10];
+
+          group_layers =(int *)msSmallRealloc(group_layers, sizeof(int)*num_layers);
+          if (msLegendCalcSize(map, 1, &size_x, &size_y,  group_layers , num_layers) == MS_SUCCESS) {
+            bufferSize = strlen(script_url_encoded)+300;
+            pszLegendURL = (char*)msSmallMalloc(bufferSize);
+            snprintf(width, sizeof(width), "%d", size_x);
+            snprintf(height, sizeof(height), "%d", size_y);
+
+            format_list = msOWSLookupMetadata(&(map->web.metadata), "M", "getlegendgraphic_formatlist");
+            if (format_list && strlen(format_list) > 0) {
+              tokens = msStringSplit(format_list,  ',', &numtokens);
+              if (tokens && numtokens > 0) {
+                /*just grab the first mime type*/
+                pszMimetype = msEncodeHTMLEntities(tokens[0]);
+                msFreeCharArray(tokens, numtokens);
+              }
+            } else
+              pszMimetype = msEncodeHTMLEntities("image/png");
 
+            if (nVersion >= OWS_1_3_0)
+              snprintf(pszLegendURL, bufferSize, "%sversion=%s&service=WMS&request=GetLegendGraphic&sld_version=1.1.0&layer=%s&format=%s&STYLE=%s", script_url_encoded,msOWSGetVersionString(nVersion, szVersionBuf),pszEncodedName,
+                       pszMimetype, pszEncodedStyleName);
+            else
+              snprintf(pszLegendURL, bufferSize, "%sversion=%s&service=WMS&request=GetLegendGraphic&layer=%s&format=%s&STYLE=%s", script_url_encoded,msOWSGetVersionString(nVersion, szVersionBuf),pszEncodedName,
+                       pszMimetype, pszEncodedStyleName);
+
+            msOWSPrintURLType(stdout, NULL,
+                              "O", "ttt",
+                              OWS_NOERR, NULL,
+                              "LegendURL", NULL,
+                              " width=\"%s\"", " height=\"%s\"",
+                              ">\n          <Format>%s</Format",
+                              "\n          <OnlineResource "
+                              "xmlns:xlink=\"http://www.w3.org/1999/xlink\""
+                              " xlink:type=\"simple\" xlink:href=\"%s\"/>\n"
+                              "       ",
+                              MS_FALSE, MS_FALSE, MS_FALSE, MS_FALSE, MS_FALSE,
+                              NULL, width, height, pszMimetype, pszLegendURL, "       ");
+          }
+          msFree(pszLegendURL);
+          msFree(pszMimetype);
+        }
+        msFree(group_layers);
+      }
+      msIO_fprintf(stdout, "    </Style>\n");
+      msFree(pszEncodedName);
+      msFree(pszEncodedStyleName);
+    }
 
-  /*  */
-  /* Dump list of layers organized by groups.  Layers with no group are listed */
-  /* individually, at the same level as the groups in the layer hierarchy */
-  /*  */
-  if (map->numlayers)
-  {
-     int i, j;
-     char *pabLayerProcessed = NULL;
-     char ***nestedGroups = NULL; 
-     int *numNestedGroups = NULL; 
-
-     /* We'll use this array of booleans to track which layer/group have been */
-     /* processed already */
-     pabLayerProcessed = (char *)msSmallCalloc(map->numlayers, sizeof(char*));
-     /* This array holds the arrays of groups that have been set through the WMS_LAYER_GROUP metadata */
-     nestedGroups = (char***)msSmallCalloc(map->numlayers, sizeof(char**));
-     /* This array holds the number of groups set in WMS_LAYER_GROUP for each layer */
-     numNestedGroups = (int*)msSmallCalloc(map->numlayers, sizeof(int));
-
-     msWMSPrepareNestedGroups(map, nVersion, nestedGroups, numNestedGroups);
-
-     for(i=0; i<map->numlayers; i++)
-     {
-         layerObj *lp;
-         lp = (GET_LAYER(map, i));
-
-         if (pabLayerProcessed[i] || (lp->status == MS_DELETE) || 
-             (!msIntegerInArray(lp->index, ows_request->enabled_layers, ows_request->numlayers)))
-             continue;  /* Layer is hidden or has already been handled */
-         
-         if (numNestedGroups[i] > 0) 
-         {
-            /* Has nested groups.  */
-             msWMSPrintNestedGroups(map, nVersion, pabLayerProcessed, i, 0, 
-                                    nestedGroups, numNestedGroups, 
-                                    script_url_encoded);
-         }
-         else if (lp->group == NULL || strlen(lp->group) == 0)
-         {
-             /* This layer is not part of a group... dump it directly */
-             msDumpLayer(map, lp, nVersion, script_url_encoded, "");
-             pabLayerProcessed[i] = 1;
-         }
-         else
-         {
-             /* Beginning of a new group... enclose the group in a layer block */
-             msIO_printf("    <Layer>\n");
-
-             /* Layer Name is optional but title is mandatory. */
-             if (lp->group &&  strlen(lp->group) > 0 &&
-                 (msIsXMLTagValid(lp->group) == MS_FALSE || isdigit(lp->group[0])))
-               msIO_fprintf(stdout, "<!-- WARNING: The layer name '%s' might contain spaces or "
-                        "invalid characters or may start with a number. This could lead to potential problems. -->\n", 
-                            lp->group);
-             msOWSPrintEncodeParam(stdout, "GROUP.NAME", lp->group,
-                                   OWS_NOERR, "      <Name>%s</Name>\n", NULL);
-             msOWSPrintGroupMetadata(stdout, map, lp->group,
-                                     "MO", "GROUP_TITLE", OWS_WARN,
-                                     "      <Title>%s</Title>\n", lp->group);
-             msOWSPrintGroupMetadata(stdout, map, lp->group,
-                                     "MO", "GROUP_ABSTRACT", OWS_NOERR,
-                                     "      <Abstract>%s</Abstract>\n", lp->group);
-
-             /*build a getlegendgraphicurl*/
-             if( script_url_encoded)
-             {
-                 int num_layers = 0;
-                 size_t bufferSize = 0;
-                 char width[10], height[10];
-                 char *name_encoded = msEncodeHTMLEntities(lp->group);
-                 int *group_layers = (int *)msSmallMalloc(sizeof(int)*map->numlayers);
-                 char *legendurl = NULL;
-                 int size_x=0, size_y=0;
-                 char *mimetype = NULL;
-                 char **tokens = NULL;
-                 int numtokens = 0;
-
-                 for(j=i; j<map->numlayers; j++)
-                   if (!pabLayerProcessed[j] &&
-                       GET_LAYER(map, j)->group &&
-                       strcmp(lp->group, GET_LAYER(map, j)->group) == 0 )
-                     group_layers[num_layers++] = j;
-                 if ( num_layers > 0)
-                 {
-                     group_layers =(int *)msSmallRealloc(group_layers,  sizeof(int)*num_layers);
-
-                     if (msLegendCalcSize(map, 1, &size_x, &size_y,  group_layers , num_layers) == MS_SUCCESS)
-                     {
-                         bufferSize = strlen(script_url_encoded)+200;
-                         legendurl = (char*)msSmallMalloc(bufferSize);
-                         snprintf(width, sizeof(width), "%d", size_x);
-                         snprintf(height, sizeof(height), "%d", size_y);
-
-                         format_list = msOWSLookupMetadata(&(map->web.metadata), "M",
-                                                           "getlegendgraphic_formatlist");
-                         if (format_list && strlen(format_list) > 0) 
-                         {
-                             tokens = msStringSplit(format_list,  ',', &numtokens);
-                             if (tokens && numtokens > 0)
-                             {
-                                 /*just grab the first mime type*/
-                                 mimetype = msEncodeHTMLEntities(tokens[0]);
-                                 msFreeCharArray(tokens, numtokens);
-                             }
-                         }
-                         else
-                           mimetype = msEncodeHTMLEntities("image/png; mode=24bit");
-
-                         if (nVersion >= OWS_1_3_0)
-                           
-                           snprintf(legendurl, bufferSize, "%sversion=%s&service=WMS&request=GetLegendGraphic&sld_version=1.1.0&layer=%s&format=%s&STYLE=default", script_url_encoded,msOWSGetVersionString(nVersion, szVersionBuf),name_encoded,
-                                    mimetype);
-                         else 
-                           snprintf(legendurl, bufferSize, "%sversion=%s&service=WMS&request=GetLegendGraphic&layer=%s&format=%s&STYLE=default", script_url_encoded,msOWSGetVersionString(nVersion, szVersionBuf),name_encoded,
-                                    mimetype);
-                         msIO_fprintf(stdout, "        <Style>\n");
-                         msIO_fprintf(stdout, "          <Name>default</Name>\n");
-                         msIO_fprintf(stdout, "          <Title>default</Title>\n");
-                      
-                         msOWSPrintURLType(stdout, NULL, 
-                                           "O", "ttt",
-                                           OWS_NOERR, NULL, 
-                                           "LegendURL", NULL, 
-                                           " width=\"%s\"", " height=\"%s\"", 
-                                           ">\n             <Format>%s</Format", 
-                                           "\n             <OnlineResource "
-                                           "xmlns:xlink=\"http://www.w3.org/1999/xlink\""
-                                           " xlink:type=\"simple\" xlink:href=\"%s\"/>\n"
-                                           "          ",
-                                           MS_FALSE, MS_FALSE, MS_FALSE, MS_FALSE, MS_FALSE, 
-                                           NULL, width, height, mimetype, legendurl, "          ");
-                 
-
-                         msIO_fprintf(stdout, "        </Style>\n");
-                         msFree(legendurl);
-                         msFree(mimetype);
-                         msFree(name_encoded);
-
-                 
-                     
-                     }
-                 }
-             }
-             /* Dump all layers for this group */
-             for(j=i; j<map->numlayers; j++)
-             {
-                 if (!pabLayerProcessed[j] &&
-                     GET_LAYER(map, j)->group &&
-                     strcmp(lp->group, GET_LAYER(map, j)->group) == 0 )
-                 {
-                     msDumpLayer(map, (GET_LAYER(map, j)), nVersion, script_url_encoded, "  ");
-                     pabLayerProcessed[j] = 1;
-                 }
-             }
-
-             /* Close group layer block */
-             msIO_printf("    </Layer>\n");
-         }
-     }
-
-     free(pabLayerProcessed);
-
-     /* free the stuff used for nested layers */
-     for (i = 0; i < map->numlayers; i++)
-     {
-       if (numNestedGroups[i] > 0)
-       {
-         msFreeCharArray(nestedGroups[i], numNestedGroups[i]);
-       }
-     }
-     free(nestedGroups);
-     free(numNestedGroups);
+    /*  */
+    /* Dump list of layers organized by groups.  Layers with no group are listed */
+    /* individually, at the same level as the groups in the layer hierarchy */
+    /*  */
+    if (map->numlayers) {
+      int i, j;
+      char *pabLayerProcessed = NULL;
+      char ***nestedGroups = NULL;
+      int *numNestedGroups = NULL;
+      int *isUsedInNestedGroup = NULL;
+
+      /* We'll use this array of booleans to track which layer/group have been */
+      /* processed already */
+      pabLayerProcessed = (char *)msSmallCalloc(map->numlayers, sizeof(char*));
+
+      nestedGroups = (char***)msSmallCalloc(map->numlayers, sizeof(char**));
+      numNestedGroups = (int*)msSmallCalloc(map->numlayers, sizeof(int));
+      isUsedInNestedGroup = (int*)msSmallCalloc(map->numlayers, sizeof(int));
+      msWMSPrepareNestedGroups(map, nVersion, nestedGroups, numNestedGroups, isUsedInNestedGroup);
+
+      for(i=0; i<map->numlayers; i++) {
+        layerObj *lp;
+        lp = (GET_LAYER(map, i));
+
+        if (pabLayerProcessed[i] || (lp->status == MS_DELETE) ||
+            (!msIntegerInArray(lp->index, ows_request->enabled_layers, ows_request->numlayers)))
+          continue;  /* Layer is hidden or has already been handled */
+
+        if (numNestedGroups[i] > 0) {
+          /* Has nested groups.  */
+          msWMSPrintNestedGroups(map, nVersion, pabLayerProcessed, i, 0,
+                                 nestedGroups, numNestedGroups, isUsedInNestedGroup,
+                                 script_url_encoded, validated_language);
+        } else if (lp->group == NULL || strlen(lp->group) == 0) {
+          /* Don't dump layer if it is used in wms_group_layer. */
+          if (!isUsedInNestedGroup[i]) {
+            /* This layer is not part of a group... dump it directly */
+            msDumpLayer(map, lp, nVersion, script_url_encoded, "", validated_language, MS_FALSE);
+            pabLayerProcessed[i] = 1;
+          }
+        } else {
+          /* Beginning of a new group... enclose the group in a layer block */
+          msIO_printf("    <Layer>\n");
+
+          /* Layer Name is optional but title is mandatory. */
+          if (lp->group &&  strlen(lp->group) > 0 &&
+              (msIsXMLTagValid(lp->group) == MS_FALSE || isdigit(lp->group[0])))
+            msIO_fprintf(stdout, "<!-- WARNING: The layer name '%s' might contain spaces or "
+                         "invalid characters or may start with a number. This could lead to potential problems. -->\n",
+                         lp->group);
+          msOWSPrintEncodeParam(stdout, "GROUP.NAME", lp->group,
+                                OWS_NOERR, "      <Name>%s</Name>\n", NULL);
+          msOWSPrintGroupMetadata2(stdout, map, lp->group,
+                                   "MO", "GROUP_TITLE", OWS_WARN,
+                                   "      <Title>%s</Title>\n", lp->group, validated_language);
+          msOWSPrintGroupMetadata2(stdout, map, lp->group,
+                                   "MO", "GROUP_ABSTRACT", OWS_NOERR,
+                                   "      <Abstract>%s</Abstract>\n", lp->group, validated_language);
+
+          /*build a getlegendgraphicurl*/
+          if( script_url_encoded) {
+            if (lp->group && strlen(lp->group) > 0) {
+              char *pszEncodedName = NULL;
+              const char *styleName = NULL;
+              char *pszEncodedStyleName = NULL;
+              const char *legendURL = NULL;
+
+              pszEncodedName = msEncodeHTMLEntities(lp->group);
+
+              styleName = msOWSLookupMetadata(&(lp->metadata), "MO", "group_style_name");
+              if (styleName == NULL)
+                styleName = "default";
+
+              pszEncodedStyleName = msEncodeHTMLEntities(styleName);
+
+              msIO_fprintf(stdout, "    <Style>\n");
+              msIO_fprintf(stdout, "       <Name>%s</Name>\n", pszEncodedStyleName);
+              msOWSPrintEncodeMetadata(stdout, &(lp->metadata), "MO",
+                                       "group_style_title",
+                                       OWS_NOERR,
+                                       "       <Title>%s</Title>\n",
+                                       styleName);
+
+              legendURL = msOWSLookupMetadata(&(lp->metadata), "MO", "group_style_legendurl_href");
+              if (legendURL) {
+                msOWSPrintURLType(stdout, &(lp->metadata),
+                                  "MO", "group_style_legendurl",
+                                  OWS_NOERR, NULL,
+                                  "LegendURL", NULL,
+                                  " width=\"%s\"", " height=\"%s\"",
+                                  ">\n          <Format>%s</Format",
+                                  "\n          <OnlineResource "
+                                  "xmlns:xlink=\"http://www.w3.org/1999/xlink\""
+                                  " xlink:type=\"simple\" xlink:href=\"%s\"/>\n"
+                                  "       ",
+                                  MS_FALSE, MS_TRUE, MS_TRUE, MS_TRUE, MS_TRUE,
+                                  NULL, NULL, NULL, NULL, NULL, "       ");
+              } else {
+                int num_layers = 0;
+                int *group_layers = (int *)msSmallMalloc(sizeof(int)*map->numlayers);
+
+                for(j=i; j<map->numlayers; j++)
+                  if (!pabLayerProcessed[j] &&
+                      GET_LAYER(map, j)->group &&
+                      strcmp(lp->group, GET_LAYER(map, j)->group) == 0 &&
+                      msIntegerInArray(GET_LAYER(map, j)->index, ows_request->enabled_layers, ows_request->numlayers))
+                    group_layers[num_layers++] = j;
+
+                if (num_layers > 0) {
+                  int size_x=0, size_y=0;
+                  size_t bufferSize = 0;
+                  char *pszLegendURL = NULL;
+                  char *pszMimetype = NULL;
+                  char **tokens = NULL;
+                  int numtokens = 0;
+                  char width[10], height[10];
+
+                  group_layers =(int *)msSmallRealloc(group_layers,  sizeof(int)*num_layers);
+                  if (msLegendCalcSize(map, 1, &size_x, &size_y,  group_layers , num_layers) == MS_SUCCESS) {
+                    bufferSize = strlen(script_url_encoded)+300;
+                    pszLegendURL = (char*)msSmallMalloc(bufferSize);
+                    snprintf(width, sizeof(width), "%d", size_x);
+                    snprintf(height, sizeof(height), "%d", size_y);
+
+                    format_list = msOWSLookupMetadata(&(map->web.metadata), "M", "getlegendgraphic_formatlist");
+                    if (format_list && strlen(format_list) > 0) {
+                      tokens = msStringSplit(format_list,  ',', &numtokens);
+                      if (tokens && numtokens > 0) {
+                        /*just grab the first mime type*/
+                        pszMimetype = msEncodeHTMLEntities(tokens[0]);
+                        msFreeCharArray(tokens, numtokens);
+                      }
+                    } else
+                      pszMimetype = msEncodeHTMLEntities("image/png");
 
+                    if (nVersion >= OWS_1_3_0)
+                      snprintf(pszLegendURL, bufferSize, "%sversion=%s&service=WMS&request=GetLegendGraphic&sld_version=1.1.0&layer=%s&format=%s&STYLE=%s", script_url_encoded,msOWSGetVersionString(nVersion, szVersionBuf),pszEncodedName,
+                               pszMimetype, pszEncodedStyleName);
+                    else
+                      snprintf(pszLegendURL, bufferSize, "%sversion=%s&service=WMS&request=GetLegendGraphic&layer=%s&format=%s&STYLE=%s", script_url_encoded,msOWSGetVersionString(nVersion, szVersionBuf),pszEncodedName,
+                               pszMimetype, pszEncodedStyleName);
+
+                    msOWSPrintURLType(stdout, NULL,
+                                      "O", "ttt",
+                                      OWS_NOERR, NULL,
+                                      "LegendURL", NULL,
+                                      " width=\"%s\"", " height=\"%s\"",
+                                      ">\n          <Format>%s</Format",
+                                      "\n          <OnlineResource "
+                                      "xmlns:xlink=\"http://www.w3.org/1999/xlink\""
+                                      " xlink:type=\"simple\" xlink:href=\"%s\"/>\n"
+                                      "       ",
+                                      MS_FALSE, MS_FALSE, MS_FALSE, MS_FALSE, MS_FALSE,
+                                      NULL, width, height, pszMimetype, pszLegendURL, "       ");
+
+                    msFree(pszLegendURL);
+                    msFree(pszMimetype);
+                  }
+                }
+              }
+              msIO_fprintf(stdout, "    </Style>\n");
+              msFree(pszEncodedName);
+              msFree(pszEncodedStyleName);
+            }
+          }
 
-  }
+          /* Dump all layers for this group */
+          for(j=i; j<map->numlayers; j++) {
+            if (!pabLayerProcessed[j] &&
+                GET_LAYER(map, j)->group &&
+                strcmp(lp->group, GET_LAYER(map, j)->group) == 0 &&
+                msIntegerInArray(GET_LAYER(map, j)->index, ows_request->enabled_layers, ows_request->numlayers)) {
+              msDumpLayer(map, (GET_LAYER(map, j)), nVersion, script_url_encoded, "  ", validated_language, MS_FALSE);
+              pabLayerProcessed[j] = 1;
+            }
+          }
+          /* Close group layer block */
+          msIO_printf("    </Layer>\n");
+        }
+      }
+
+      free(pabLayerProcessed);
+
+      /* free the stuff used for nested layers */
+      for (i = 0; i < map->numlayers; i++) {
+        if (numNestedGroups[i] > 0) {
+          msFreeCharArray(nestedGroups[i], numNestedGroups[i]);
+        }
+      }
+      free(nestedGroups);
+      free(numNestedGroups);
+      free(isUsedInNestedGroup);
+    }
 
-  msIO_printf("  </Layer>\n");
+    msIO_printf("  </Layer>\n");
+  }
 
   msIO_printf("</Capability>\n");
   if ( nVersion >= OWS_1_3_0)
@@ -2713,6 +3513,8 @@ int msWMSGetCapabilities(mapObj *map, int nVersion, cgiRequestObj *req, owsReque
   else
     msIO_printf("</WMT_MS_Capabilities>\n");
 
+  msFree(validated_language);
+
   free(script_url);
   free(script_url_encoded);
 
@@ -2728,85 +3530,69 @@ int msWMSGetCapabilities(mapObj *map, int nVersion, cgiRequestObj *req, owsReque
 */
 int msTranslateWMS2Mapserv(char **names, char **values, int *numentries)
 {
-   int i=0;
-   int tmpNumentries = *numentries;;
-
-   for (i=0; i<*numentries; i++)
-   {
-      if (strcasecmp("X", names[i]) == 0)
-      {
-         values[tmpNumentries] = msStrdup(values[i]);
-         names[tmpNumentries] = msStrdup("img.x");
+  int i=0;
+  int tmpNumentries = *numentries;;
 
-         tmpNumentries++;
-      }
-      else
-      if (strcasecmp("Y", names[i]) == 0)
-      {
-         values[tmpNumentries] = msStrdup(values[i]);
-         names[tmpNumentries] = msStrdup("img.y");
+  for (i=0; i<*numentries; i++) {
+    if (strcasecmp("X", names[i]) == 0) {
+      values[tmpNumentries] = msStrdup(values[i]);
+      names[tmpNumentries] = msStrdup("img.x");
 
-         tmpNumentries++;
-      }
-      else
-      if (strcasecmp("LAYERS", names[i]) == 0)
-      {
-         char **layers;
-         int tok;
-         int j;
+      tmpNumentries++;
+    } else if (strcasecmp("Y", names[i]) == 0) {
+      values[tmpNumentries] = msStrdup(values[i]);
+      names[tmpNumentries] = msStrdup("img.y");
 
-         layers = msStringSplit(values[i], ',', &tok);
+      tmpNumentries++;
+    } else if (strcasecmp("LAYERS", names[i]) == 0) {
+      char **layers;
+      int tok;
+      int j;
 
-         for (j=0; j<tok; j++)
-         {
-            values[tmpNumentries] = layers[j];
-            layers[j] = NULL;
-            names[tmpNumentries] = msStrdup("layer");
+      layers = msStringSplit(values[i], ',', &tok);
 
-            tmpNumentries++;
-         }
+      for (j=0; j<tok; j++) {
+        values[tmpNumentries] = layers[j];
+        layers[j] = NULL;
+        names[tmpNumentries] = msStrdup("layer");
 
-         free(layers);
+        tmpNumentries++;
       }
-      else
-      if (strcasecmp("QUERY_LAYERS", names[i]) == 0)
-      {
-         char **layers;
-         int tok;
-         int j;
 
-         layers = msStringSplit(values[i], ',', &tok);
+      free(layers);
+    } else if (strcasecmp("QUERY_LAYERS", names[i]) == 0) {
+      char **layers;
+      int tok;
+      int j;
 
-         for (j=0; j<tok; j++)
-         {
-            values[tmpNumentries] = layers[j];
-            layers[j] = NULL;
-            names[tmpNumentries] = msStrdup("qlayer");
+      layers = msStringSplit(values[i], ',', &tok);
 
-            tmpNumentries++;
-         }
+      for (j=0; j<tok; j++) {
+        values[tmpNumentries] = layers[j];
+        layers[j] = NULL;
+        names[tmpNumentries] = msStrdup("qlayer");
 
-         free(layers);
+        tmpNumentries++;
       }
-      else
-      if (strcasecmp("BBOX", names[i]) == 0)
-      {
-         char *imgext;
 
-         /* Note msReplaceSubstring() works on the string itself, so we need to make a copy */
-         imgext = msStrdup(values[i]);
-         imgext = msReplaceSubstring(imgext, ",", " ");
+      free(layers);
+    } else if (strcasecmp("BBOX", names[i]) == 0) {
+      char *imgext;
 
-         values[tmpNumentries] = imgext;
-         names[tmpNumentries] = msStrdup("imgext");
+      /* Note msReplaceSubstring() works on the string itself, so we need to make a copy */
+      imgext = msStrdup(values[i]);
+      imgext = msReplaceSubstring(imgext, ",", " ");
 
-         tmpNumentries++;
-      }
-   }
+      values[tmpNumentries] = imgext;
+      names[tmpNumentries] = msStrdup("imgext");
+
+      tmpNumentries++;
+    }
+  }
 
-   *numentries = tmpNumentries;
+  *numentries = tmpNumentries;
 
-   return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 /*
@@ -2825,196 +3611,183 @@ int msWMSGetMap(mapObj *map, int nVersion, char **names, char **values, int nume
   /* The spec states that this should not happen so that we can deliver */
   /* maps to devices with non-square pixels. */
 
+  /* If there was an SLD in the request, we need to treat it */
+  /* diffrently : some SLD may contain spatial filters requiring */
+  /* to do a query. While parsing the SLD and applying it to the */
+  /* layer, we added a temporary metadata on the layer */
+  /* (tmp_wms_sld_query) for layers with a spatial filter. */
 
-/* If there was an SLD in the request, we need to treat it */
-/* diffrently : some SLD may contain spatial filters requiring */
-/* to do a query. While parsing the SLD and applying it to the */
-/* layer, we added a temporary metadata on the layer */
-/* (tmp_wms_sld_query) for layers with a spatial filter. */
-
-  for (i=0; i<numentries; i++)
-  {
+  for (i=0; i<numentries; i++) {
     if ((strcasecmp(names[i], "SLD") == 0 && values[i] && strlen(values[i]) > 0) ||
-        (strcasecmp(names[i], "SLD_BODY") == 0 && values[i] && strlen(values[i]) > 0))
-    {
-        sldrequested = MS_TRUE;
-        break;
+        (strcasecmp(names[i], "SLD_BODY") == 0 && values[i] && strlen(values[i]) > 0)) {
+      sldrequested = MS_TRUE;
+      break;
     }
   }
-  if (sldrequested)
-  {
-      for (i=0; i<map->numlayers; i++)
-      {
-          if (msLookupHashTable(&(GET_LAYER(map, i)->metadata), "tmp_wms_sld_query"))
-          {
-              sldspatialfilter = MS_TRUE;
-              break;
-          }
+  if (sldrequested) {
+    for (i=0; i<map->numlayers; i++) {
+      if (msLookupHashTable(&(GET_LAYER(map, i)->metadata), "tmp_wms_sld_query")) {
+        sldspatialfilter = MS_TRUE;
+        break;
       }
+    }
   }
 
   /* turn off layer if WMS GetMap is not enabled */
   for (i=0; i<map->numlayers; i++)
-      if (!msIntegerInArray(GET_LAYER(map, i)->index, ows_request->enabled_layers, ows_request->numlayers))
-          GET_LAYER(map, i)->status = MS_OFF;
-
-  if (sldrequested && sldspatialfilter)
-  {
-      /* set the quermap style so that only selected features will be retruned */
-      map->querymap.status = MS_ON;
-      map->querymap.style = MS_SELECTED;
+    if (!msIntegerInArray(GET_LAYER(map, i)->index, ows_request->enabled_layers, ows_request->numlayers))
+      GET_LAYER(map, i)->status = MS_OFF;
+
+  if (sldrequested && sldspatialfilter) {
+    /* set the quermap style so that only selected features will be retruned */
+    map->querymap.status = MS_ON;
+    map->querymap.style = MS_SELECTED;
+
+    img = msPrepareImage(map, MS_TRUE);
+
+    /* compute layer scale factors now */
+    for(i=0; i<map->numlayers; i++) {
+      if(GET_LAYER(map, i)->sizeunits != MS_PIXELS)
+        GET_LAYER(map, i)->scalefactor = (msInchesPerUnit(GET_LAYER(map, i)->sizeunits,0)/msInchesPerUnit(map->units,0)) / map->cellsize;
+      else if(GET_LAYER(map, i)->symbolscaledenom > 0 && map->scaledenom > 0)
+        GET_LAYER(map, i)->scalefactor = GET_LAYER(map, i)->symbolscaledenom/map->scaledenom;
+      else
+        GET_LAYER(map, i)->scalefactor = 1;
+    }
+    for (i=0; i<map->numlayers; i++) {
+      if (msLookupHashTable(&(GET_LAYER(map, i)->metadata), "tmp_wms_sld_query") &&
+          (GET_LAYER(map, i)->type == MS_LAYER_POINT ||
+           GET_LAYER(map, i)->type == MS_LAYER_LINE ||
+           GET_LAYER(map, i)->type == MS_LAYER_POLYGON ||
+           GET_LAYER(map, i)->type == MS_LAYER_ANNOTATION ||
+           GET_LAYER(map, i)->type == MS_LAYER_TILEINDEX))
 
-      img = msPrepareImage(map, MS_TRUE);
-      
-      /* compute layer scale factors now */
-      for(i=0;i<map->numlayers; i++) {
-          if(GET_LAYER(map, i)->sizeunits != MS_PIXELS)
-            GET_LAYER(map, i)->scalefactor = (msInchesPerUnit(GET_LAYER(map, i)->sizeunits,0)/msInchesPerUnit(map->units,0)) / map->cellsize;
-          else if(GET_LAYER(map, i)->symbolscaledenom > 0 && map->scaledenom > 0)
-            GET_LAYER(map, i)->scalefactor = GET_LAYER(map, i)->symbolscaledenom/map->scaledenom;
-          else
-            GET_LAYER(map, i)->scalefactor = 1;
-      }
-      for (i=0; i<map->numlayers; i++)
       {
-          if (msLookupHashTable(&(GET_LAYER(map, i)->metadata), "tmp_wms_sld_query") &&
-              (GET_LAYER(map, i)->type == MS_LAYER_POINT || 
-               GET_LAYER(map, i)->type == MS_LAYER_LINE ||
-               GET_LAYER(map, i)->type == MS_LAYER_POLYGON ||
-               GET_LAYER(map, i)->type == MS_LAYER_ANNOTATION ||
-               GET_LAYER(map, i)->type == MS_LAYER_TILEINDEX))
-               
-          {
-              /* make sure that there is a resultcache. If not just ignore */
-              /* the layer */
-              if (GET_LAYER(map, i)->resultcache)
-                msDrawQueryLayer(map, GET_LAYER(map, i), img);
-          }
-
-          else
-            msDrawLayer(map, GET_LAYER(map, i), img);
+        /* make sure that there is a resultcache. If not just ignore */
+        /* the layer */
+        if (GET_LAYER(map, i)->resultcache)
+          msDrawQueryLayer(map, GET_LAYER(map, i), img);
       }
 
-  }
-  else 
-      img = msDrawMap(map, MS_FALSE);
+      else
+        msDrawLayer(map, GET_LAYER(map, i), img);
+    }
+
+  } else
+    img = msDrawMap(map, MS_FALSE);
   if (img == NULL)
     return msWMSException(map, nVersion, NULL, wms_exception_format);
-  
+
   /* Set the HTTP Cache-control headers if they are defined
      in the map object */
-  
+
   if( (http_max_age = msOWSLookupMetadata(&(map->web.metadata), "MO", "http_max_age")) ) {
-    msIO_printf("Cache-Control: max-age=%s\n", http_max_age , 10, 10);
+    msIO_setHeader("Cache-Control","max-age=%s", http_max_age);
   }
-  
-  if (strcasecmp(map->imagetype, "application/openlayers")!=0)
-  {
-      msIO_printf("Content-type: %s%c%c",
-                  MS_IMAGE_MIME_TYPE(map->outputformat), 10,10);
-      if (msSaveImage(map, img, NULL) != MS_SUCCESS)
-        return msWMSException(map, nVersion, NULL, wms_exception_format);
 
+  if (strcasecmp(map->imagetype, "application/openlayers")!=0) {
+    msIO_setHeader("Content-Type",MS_IMAGE_MIME_TYPE(map->outputformat));
+    msIO_sendHeaders();
+    if (msSaveImage(map, img, NULL) != MS_SUCCESS) {
       msFreeImage(img);
+      return msWMSException(map, nVersion, NULL, wms_exception_format);
+    }
   }
+  msFreeImage(img);
 
   return(MS_SUCCESS);
 }
 
 int msDumpResult(mapObj *map, int bFormatHtml, int nVersion, char *wms_exception_format)
 {
-   int numresults=0;
-   int i;
-
-   for(i=0; i<map->numlayers; i++)
-   {
-      int j, k, *itemvisible;
-      char **incitems=NULL;
-      int numincitems=0;
-      char **excitems=NULL;
-      int numexcitems=0;
-      const char *value;
-
-      layerObj *lp;
-      lp = (GET_LAYER(map, i));
+  int numresults=0;
+  int i;
 
-      if(lp->status != MS_ON || lp->resultcache==NULL || lp->resultcache->numresults == 0)
-        continue;
+  for(i=0; i<map->numlayers; i++) {
+    int j, k, *itemvisible;
+    char **incitems=NULL;
+    int numincitems=0;
+    char **excitems=NULL;
+    int numexcitems=0;
+    const char *value;
 
-      /* if(msLayerOpen(lp) != MS_SUCCESS || msLayerGetItems(lp) != MS_SUCCESS)
-	   return msWMSException(map, nVersion, NULL); */
+    layerObj *lp;
+    lp = (GET_LAYER(map, i));
 
-      /* Use metadata to control which fields to output. We use the same 
-       * metadata names as for GML:
-       * wms/ows_include_items: comma delimited list or keyword 'all'
-       * wms/ows_exclude_items: comma delimited list (all items are excluded by default)
-       */
-      /* get a list of items that should be excluded in output */
-      if((value = msOWSLookupMetadata(&(lp->metadata), "MO", "include_items")) != NULL)  
-          incitems = msStringSplit(value, ',', &numincitems);
+    if(lp->status != MS_ON || lp->resultcache==NULL || lp->resultcache->numresults == 0)
+      continue;
 
-      /* get a list of items that should be excluded in output */
-      if((value = msOWSLookupMetadata(&(lp->metadata), "MO", "exclude_items")) != NULL)  
-          excitems = msStringSplit(value, ',', &numexcitems);
+    /* if(msLayerOpen(lp) != MS_SUCCESS || msLayerGetItems(lp) != MS_SUCCESS)
+     return msWMSException(map, nVersion, NULL); */
 
-      itemvisible = (int*)msSmallMalloc(lp->numitems*sizeof(int));
-      for(k=0; k<lp->numitems; k++)
-      {
-          int l;
+    /* Use metadata to control which fields to output. We use the same
+     * metadata names as for GML:
+     * wms/ows_include_items: comma delimited list or keyword 'all'
+     * wms/ows_exclude_items: comma delimited list (all items are excluded by default)
+     */
+    /* get a list of items that should be excluded in output */
+    if((value = msOWSLookupMetadata(&(lp->metadata), "MO", "include_items")) != NULL)
+      incitems = msStringSplit(value, ',', &numincitems);
+
+    /* get a list of items that should be excluded in output */
+    if((value = msOWSLookupMetadata(&(lp->metadata), "MO", "exclude_items")) != NULL)
+      excitems = msStringSplit(value, ',', &numexcitems);
+
+    itemvisible = (int*)msSmallMalloc(lp->numitems*sizeof(int));
+    for(k=0; k<lp->numitems; k++) {
+      int l;
+
+      itemvisible[k] = MS_FALSE;
+
+      /* check visibility, included items first... */
+      if(numincitems == 1 && strcasecmp("all", incitems[0]) == 0) {
+        itemvisible[k] = MS_TRUE;
+      } else {
+        for(l=0; l<numincitems; l++) {
+          if(strcasecmp(lp->items[k], incitems[l]) == 0)
+            itemvisible[k] = MS_TRUE;
+        }
+      }
 
+      /* ...and now excluded items */
+      for(l=0; l<numexcitems; l++) {
+        if(strcasecmp(lp->items[k], excitems[l]) == 0)
           itemvisible[k] = MS_FALSE;
-
-          /* check visibility, included items first... */
-          if(numincitems == 1 && strcasecmp("all", incitems[0]) == 0) {
-              itemvisible[k] = MS_TRUE;
-          } else {
-              for(l=0; l<numincitems; l++) {
-                  if(strcasecmp(lp->items[k], incitems[l]) == 0)
-                      itemvisible[k] = MS_TRUE;
-              }
-          }
-
-          /* ...and now excluded items */
-          for(l=0; l<numexcitems; l++) {
-              if(strcasecmp(lp->items[k], excitems[l]) == 0)
-                  itemvisible[k] = MS_FALSE;
-          }
       }
+    }
 
-      msFreeCharArray(incitems, numincitems);
-      msFreeCharArray(excitems, numexcitems);
-
-      /* Output selected shapes for this layer */
-      msIO_printf("\nLayer '%s'\n", lp->name);
+    msFreeCharArray(incitems, numincitems);
+    msFreeCharArray(excitems, numexcitems);
 
-      for(j=0; j<lp->resultcache->numresults; j++) {
-        shapeObj shape;
+    /* Output selected shapes for this layer */
+    msIO_printf("\nLayer '%s'\n", lp->name);
 
-        msInitShape(&shape);
-        if (msLayerGetShape(lp, &shape, &(lp->resultcache->results[j])) != MS_SUCCESS)
-        {
-            msFree(itemvisible);
-            return msWMSException(map, nVersion, NULL, wms_exception_format);
-        }
+    for(j=0; j<lp->resultcache->numresults; j++) {
+      shapeObj shape;
 
-        msIO_printf("  Feature %ld: \n", lp->resultcache->results[j].shapeindex);
+      msInitShape(&shape);
+      if (msLayerGetShape(lp, &shape, &(lp->resultcache->results[j])) != MS_SUCCESS) {
+        msFree(itemvisible);
+        return msWMSException(map, nVersion, NULL, wms_exception_format);
+      }
 
-        for(k=0; k<lp->numitems; k++)
-        {
-            if (itemvisible[k])
-                msIO_printf("    %s = '%s'\n", lp->items[k], shape.values[k]);
-        }
+      msIO_printf("  Feature %ld: \n", lp->resultcache->results[j].shapeindex);
 
-        msFreeShape(&shape);
-        numresults++;
+      for(k=0; k<lp->numitems; k++) {
+        if (itemvisible[k])
+          msIO_printf("    %s = '%s'\n", lp->items[k], shape.values[k]);
       }
 
-      msFree(itemvisible);
-
-      /* msLayerClose(lp); */
+      msFreeShape(&shape);
+      numresults++;
     }
 
-   return numresults;
+    msFree(itemvisible);
+
+    /* msLayerClose(lp); */
+  }
+
+  return numresults;
 }
 
 
@@ -3036,9 +3809,20 @@ int msWMSFeatureInfo(mapObj *map, int nVersion, char **names, char **values, int
   int valid_format=MS_FALSE;
   int format_found = MS_FALSE;
   int use_bbox = MS_FALSE;
+  int wms_layer =  MS_FALSE;
+  const char *wms_connection = NULL;
+  int numOWSLayers = 0;
+  char ***nestedGroups = NULL;
+  int *numNestedGroups = NULL;
+  int *isUsedInNestedGroup = NULL;
 
   encoding = msOWSLookupMetadata(&(map->web.metadata), "MO", "encoding");
 
+  nestedGroups = (char***)msSmallCalloc(map->numlayers, sizeof(char**));
+  numNestedGroups = (int*)msSmallCalloc(map->numlayers, sizeof(int));
+  isUsedInNestedGroup = (int*)msSmallCalloc(map->numlayers, sizeof(int));
+  msWMSPrepareNestedGroups(map, nVersion, nestedGroups, numNestedGroups, isUsedInNestedGroup);
+
   for(i=0; map && i<numentries; i++) {
     if(strcasecmp(names[i], "QUERY_LAYERS") == 0) {
       char **layers;
@@ -3052,96 +3836,114 @@ int msWMSFeatureInfo(mapObj *map, int nVersion, char **names, char **values, int
         return msWMSException(map, nVersion, "LayerNotDefined", wms_exception_format);
       }
 
-      
-        
+
+
       for(j=0; j<map->numlayers; j++) {
         /* Force all layers OFF by default */
-	GET_LAYER(map, j)->status = MS_OFF;
+        GET_LAYER(map, j)->status = MS_OFF;
         for(k=0; k<numlayers; k++) {
-         if (((GET_LAYER(map, j)->name && strcasecmp(GET_LAYER(map, j)->name, layers[k]) == 0) ||
-              (map->name && strcasecmp(map->name, layers[k]) == 0) ||
-              (GET_LAYER(map, j)->group && strcasecmp(GET_LAYER(map, j)->group, layers[k]) == 0)) &&
-             (msIntegerInArray(GET_LAYER(map, j)->index, ows_request->enabled_layers, ows_request->numlayers)) )
-            {
-                numlayers_found++;     
-                GET_LAYER(map, j)->status = MS_ON;               
+          if (((GET_LAYER(map, j)->name && strcasecmp(GET_LAYER(map, j)->name, layers[k]) == 0) ||
+               (map->name && strcasecmp(map->name, layers[k]) == 0) ||
+               (GET_LAYER(map, j)->group && strcasecmp(GET_LAYER(map, j)->group, layers[k]) == 0) ||
+               ((numNestedGroups[j] >0) && msStringInArray(layers[k], nestedGroups[j], numNestedGroups[j]))) &&
+              (msIntegerInArray(GET_LAYER(map, j)->index, ows_request->enabled_layers, ows_request->numlayers)) ) {
+            if (GET_LAYER(map, j)->connectiontype == MS_WMS) {
+              wms_layer = MS_TRUE;
+              wms_connection = GET_LAYER(map, j)->connection;
+            }
+
+            /* Don't turn on layers that are not queryable but have sublayers. */
+            if ((msIsLayerQueryable(GET_LAYER(map, j))) || isUsedInNestedGroup[j] == 0) {
+              numlayers_found++;
+              GET_LAYER(map, j)->status = MS_ON;
             }
+          }
         }
       }
 
       msFreeCharArray(layers, numlayers);
-    } else if (strcasecmp(names[i], "INFO_FORMAT") == 0)
-    {
-        if (values[i] && strlen(values[i]) > 0)
-        {
-            info_format = values[i];
-            format_found = MS_TRUE;
-        }
-    }
-    else if (strcasecmp(names[i], "FEATURE_COUNT") == 0)
+    } else if (strcasecmp(names[i], "INFO_FORMAT") == 0) {
+      if (values[i] && strlen(values[i]) > 0) {
+        info_format = values[i];
+        format_found = MS_TRUE;
+      }
+    } else if (strcasecmp(names[i], "FEATURE_COUNT") == 0)
       feature_count = atoi(values[i]);
     else if(strcasecmp(names[i], "X") == 0 || strcasecmp(names[i], "I") == 0)
       point.x = atof(values[i]);
     else if (strcasecmp(names[i], "Y") == 0 || strcasecmp(names[i], "J") == 0)
       point.y = atof(values[i]);
-    else if (strcasecmp(names[i], "RADIUS") == 0)
-    {
-        /* RADIUS in pixels. */
-        /* This is not part of the spec, but some servers such as cubeserv */
-        /* support it as a vendor-specific feature. */
-        /* It's easy for MapServer to handle this so let's do it! */
-
-        /* Special RADIUS value that changes the query into a bbox query */
-        /* based on the bbox in the request parameters. */
-        if( strcasecmp(values[i], "BBOX") == 0)
-        {
-            use_bbox = MS_TRUE;
-        }
-        else
-        {
-            int j;
-            for(j=0; j<map->numlayers; j++)
-            {
-                GET_LAYER(map, j)->tolerance = atoi(values[i]);
-                GET_LAYER(map, j)->toleranceunits = MS_PIXELS;
-            }
+    else if (strcasecmp(names[i], "RADIUS") == 0) {
+      /* RADIUS in pixels. */
+      /* This is not part of the spec, but some servers such as cubeserv */
+      /* support it as a vendor-specific feature. */
+      /* It's easy for MapServer to handle this so let's do it! */
+
+      /* Special RADIUS value that changes the query into a bbox query */
+      /* based on the bbox in the request parameters. */
+      if( strcasecmp(values[i], "BBOX") == 0) {
+        use_bbox = MS_TRUE;
+      } else {
+        int j;
+        for(j=0; j<map->numlayers; j++) {
+          GET_LAYER(map, j)->tolerance = atoi(values[i]);
+          GET_LAYER(map, j)->toleranceunits = MS_PIXELS;
         }
+      }
     }
 
   }
 
-  if(numlayers_found == 0) 
-  {
-      if (query_layer)
-      {
-          msSetError(MS_WMSERR, "Layer(s) specified in QUERY_LAYERS parameter is not offered by the service instance.", "msWMSFeatureInfo()");
-          return msWMSException(map, nVersion, "LayerNotDefined", wms_exception_format);
-      }
-      else
-      {
-          msSetError(MS_WMSERR, "Required QUERY_LAYERS parameter missing for getFeatureInfo.", "msWMSFeatureInfo()");
-          return msWMSException(map, nVersion, "LayerNotDefined", wms_exception_format);
-      }
+  /* free the stuff used for nested layers */
+  for (i = 0; i < map->numlayers; i++) {
+    if (numNestedGroups[i] > 0) {
+      msFreeCharArray(nestedGroups[i], numNestedGroups[i]);
+    }
+  }
+  free(nestedGroups);
+  free(numNestedGroups);
+  free(isUsedInNestedGroup);
+
+  if(numlayers_found == 0) {
+    if (query_layer) {
+      msSetError(MS_WMSERR, "Layer(s) specified in QUERY_LAYERS parameter is not offered by the service instance.", "msWMSFeatureInfo()");
+      return msWMSException(map, nVersion, "LayerNotDefined", wms_exception_format);
+    } else {
+      msSetError(MS_WMSERR, "Required QUERY_LAYERS parameter missing for getFeatureInfo.", "msWMSFeatureInfo()");
+      return msWMSException(map, nVersion, "LayerNotDefined", wms_exception_format);
+    }
   }
 
-  /*make sure to initialize the map scale so that layers that are scale dependent are resepected for 
-    the query*/ 
+  /*make sure to initialize the map scale so that layers that are scale dependent are resepected for
+    the query*/
   msCalculateScale(map->extent,map->units,map->width,map->height, map->resolution, &map->scaledenom);
-  
-/* -------------------------------------------------------------------- */
-/*      check if all layers selected are queryable. If not send an      */
-/*      exception.                                                      */
-/* -------------------------------------------------------------------- */
-  
-  for (i=0; i<map->numlayers; i++)
-  {
-      if (GET_LAYER(map, i)->status == MS_ON && !msIsLayerQueryable(GET_LAYER(map, i)))
-      { 
-          msSetError(MS_WMSERR, "Requested layer(s) are not queryable.", "msWMSFeatureInfo()");
+
+  /* -------------------------------------------------------------------- */
+  /*      check if all layers selected are queryable. If not send an      */
+  /*      exception.                                                      */
+  /* -------------------------------------------------------------------- */
+
+  /* If a layer of type WMS was found... all layers have to be of that type and with the same connection */
+  for (i=0; i<map->numlayers; i++) {
+    if (GET_LAYER(map, i)->status == MS_ON) {
+      if (!msIsLayerQueryable(GET_LAYER(map, i))) {
+        msSetError(MS_WMSERR, "Requested layer(s) are not queryable.", "msWMSFeatureInfo()");
+        return msWMSException(map, nVersion, "LayerNotQueryable", wms_exception_format);
+      } else if (wms_layer == MS_TRUE) {
+        if ( (GET_LAYER(map, i)->connectiontype != MS_WMS) || (strcasecmp(wms_connection, GET_LAYER(map, i)->connection) != 0) ) {
+          msSetError(MS_WMSERR, "Requested WMS layer(s) are not queryable: type or connection differ", "msWMSFeatureInfo()");
           return msWMSException(map, nVersion, "LayerNotQueryable", wms_exception_format);
+        }
+        ++numOWSLayers;
       }
+    }
   }
 
+  /* It's a valid Cascading WMS GetFeatureInfo request */
+  if (wms_layer)
+    return msWMSLayerExecuteRequest(map, numOWSLayers, point.x, point.y,
+                                    feature_count, info_format, WMS_GETFEATUREINFO);
+
   if( use_bbox == MS_FALSE ) {
 
     if(point.x == -1.0 || point.y == -1.0) {
@@ -3153,13 +3955,11 @@ int msWMSFeatureInfo(mapObj *map, int nVersion, char **names, char **values, int
     }
 
     /*wms1.3.0: check if the points are valid*/
-    if (nVersion >= OWS_1_3_0)
-    {
-        if (point.x > map->width || point.y > map->height)
-        {
-            msSetError(MS_WMSERR, "Invalid I/J values", "msWMSFeatureInfo()");
-            return msWMSException(map, nVersion, "InvalidPoint", wms_exception_format);
-        }
+    if (nVersion >= OWS_1_3_0) {
+      if (point.x > map->width || point.y > map->height) {
+        msSetError(MS_WMSERR, "Invalid I/J values", "msWMSFeatureInfo()");
+        return msWMSException(map, nVersion, "InvalidPoint", wms_exception_format);
+      }
     }
     /* Perform the actual query */
     cellx = MS_CELLSIZE(map->extent.minx, map->extent.maxx, map->width); /* note: don't adjust extent, WMS assumes incoming extent is correct */
@@ -3167,18 +3967,18 @@ int msWMSFeatureInfo(mapObj *map, int nVersion, char **names, char **values, int
     point.x = MS_IMAGE2MAP_X(point.x, map->extent.minx, cellx);
     point.y = MS_IMAGE2MAP_Y(point.y, map->extent.maxy, celly);
 
-    /* WMS 1.3.0 states that feature_count is *per layer*. 
+    /* WMS 1.3.0 states that feature_count is *per layer*.
      * Its value is a positive integer, if omitted then the default is 1
      */
     if (feature_count < 1)
-        feature_count = 1;
+      feature_count = 1;
 
     map->query.type = MS_QUERY_BY_POINT;
     map->query.mode = (feature_count==1?MS_QUERY_SINGLE:MS_QUERY_MULTIPLE);
     map->query.layer = -1;
     map->query.point = point;
     map->query.buffer = 0;
-    map->query.maxresults = feature_count; 
+    map->query.maxresults = feature_count;
 
     if(msQueryByPoint(map) != MS_SUCCESS)
       if((query_status=ms_error->code) != MS_NOTFOUND) return msWMSException(map, nVersion, NULL, wms_exception_format);
@@ -3195,45 +3995,43 @@ int msWMSFeatureInfo(mapObj *map, int nVersion, char **names, char **values, int
   }
 
   /*validate the INFO_FORMAT*/
-   valid_format = MS_FALSE;
+  valid_format = MS_FALSE;
   format_list = msOWSLookupMetadata(&(map->web.metadata), "M",
-                                      "getfeatureinfo_formatlist");
-   /*feature_info_mime_type depricated for MapServer 6.0*/
+                                    "getfeatureinfo_formatlist");
+  /*feature_info_mime_type depricated for MapServer 6.0*/
   if (!format_list)
-    format_list = msOWSLookupMetadata(&(map->web.metadata), "MO", 
-                                       "feature_info_mime_type");
-  if (format_list)
-  {
-      /*can not really validate if it is a valid output format
-        since old way of using template with web->header/footer and
-        layer templates need to still be supported. 
-        We can only validate if it was part of the format list*/
-      if (strcasestr(format_list, info_format))
-        valid_format = MS_TRUE;
+    format_list = msOWSLookupMetadata(&(map->web.metadata), "MO",
+                                      "feature_info_mime_type");
+  if (format_list) {
+    /*can not really validate if it is a valid output format
+      since old way of using template with web->header/footer and
+      layer templates need to still be supported.
+      We can only validate if it was part of the format list*/
+    if (strcasestr(format_list, info_format))
+      valid_format = MS_TRUE;
   }
-   /*check to see if the format passed is text/plain or GML and if is
-     defined in the formatlist. If that is the case, It is a valid format*/
-   if (strcasecmp(info_format, "MIME") == 0 ||
-       strcasecmp(info_format, "text/plain") == 0 ||
-       strncasecmp(info_format, "GML", 3) == 0 || 
-       strcasecmp(info_format, "application/vnd.ogc.gml") == 0) 
-     valid_format = MS_TRUE;
-   
-   
-   /*last case: if the info_format is not part of the request, it defaults to MIME*/
-   if (!valid_format && format_found == MS_FALSE)
-     valid_format =MS_TRUE;
-
-   if (!valid_format)
-   {
-       msSetError(MS_WMSERR, "Unsupported INFO_FORMAT value (%s).", 
-                  "msWMSFeatureInfo()", info_format);
-       if (nVersion >= OWS_1_3_0)
-         return msWMSException(map, nVersion, "InvalidFormat", wms_exception_format);
-       else
-         return msWMSException(map, nVersion, NULL, wms_exception_format);
-   }
-           
+  /*check to see if the format passed is text/plain or GML and if is
+    defined in the formatlist. If that is the case, It is a valid format*/
+  if (strcasecmp(info_format, "MIME") == 0 ||
+      strcasecmp(info_format, "text/plain") == 0 ||
+      strncasecmp(info_format, "GML", 3) == 0 ||
+      strcasecmp(info_format, "application/vnd.ogc.gml") == 0)
+    valid_format = MS_TRUE;
+
+
+  /*last case: if the info_format is not part of the request, it defaults to MIME*/
+  if (!valid_format && format_found == MS_FALSE)
+    valid_format =MS_TRUE;
+
+  if (!valid_format) {
+    msSetError(MS_WMSERR, "Unsupported INFO_FORMAT value (%s).",
+               "msWMSFeatureInfo()", info_format);
+    if (nVersion >= OWS_1_3_0)
+      return msWMSException(map, nVersion, "InvalidFormat", wms_exception_format);
+    else
+      return msWMSException(map, nVersion, NULL, wms_exception_format);
+  }
+
   /* Generate response */
   if (strcasecmp(info_format, "MIME") == 0 ||
       strcasecmp(info_format, "text/plain") == 0) {
@@ -3242,9 +4040,10 @@ int msWMSFeatureInfo(mapObj *map, int nVersion, char **names, char **values, int
     int numresults = 0;
 
     if (encoding)
-        msIO_printf("Content-type: text/plain; charset=%s%c%c", encoding,10,10);
+      msIO_setHeader("Content-Type","text/plain; charset=%s", encoding);
     else
-        msIO_printf("Content-type: text/plain%c%c",10,10);
+      msIO_setHeader("Content-Type","text/plain");
+    msIO_sendHeaders();
     msIO_printf("GetFeatureInfo results:\n");
 
     numresults = msDumpResult(map, 0, nVersion, wms_exception_format);
@@ -3254,55 +4053,51 @@ int msWMSFeatureInfo(mapObj *map, int nVersion, char **names, char **values, int
   } else if (strncasecmp(info_format, "GML", 3) == 0 ||  /* accept GML.1 or GML */
              strcasecmp(info_format, "application/vnd.ogc.gml") == 0) {
 
-    if (nVersion <= OWS_1_0_7)
-        if (encoding)
-            msIO_printf("Content-type: text/xml; charset=%s%c%c", encoding,10,10);
-        else
-            msIO_printf("Content-type: text/xml%c%c",10,10);
-    else
-        if (encoding)
-            msIO_printf("Content-type: application/vnd.ogc.gml; charset=%s%c%c", encoding,10,10);
-        else
-            msIO_printf("Content-type: application/vnd.ogc.gml%c%c",10,10);
-
+    if (nVersion <= OWS_1_0_7)   /* 1.0.0 to 1.0.7 */
+      if (encoding)
+        msIO_setHeader("Content-Type","text/xml; charset=%s", encoding);
+      else
+        msIO_setHeader("Content-Type","text/xml");
+    else /* 1.1.0 and later */
+      if (encoding)
+        msIO_setHeader("Content-Type","application/vnd.ogc.gml; charset=%s", encoding);
+      else
+        msIO_setHeader("Content-Type","application/vnd.ogc.gml");
+    msIO_sendHeaders();
     msGMLWriteQuery(map, NULL, "MGO"); /* default is stdout */
 
-  } 
-  else
-  {
-     mapservObj *msObj;
-
-     msObj = msAllocMapServObj();
-
-     /* Translate some vars from WMS to mapserv */
-     msTranslateWMS2Mapserv(names, values, &numentries);
-
-     msObj->map = map;
-     msFreeCharArray(msObj->request->ParamNames, msObj->request->NumParams);
-     msFreeCharArray(msObj->request->ParamValues, msObj->request->NumParams);
-     msObj->request->ParamNames = names;
-     msObj->request->ParamValues = values;
-     msObj->Mode = QUERY;
-     msObj->request->NumParams = numentries;
-     msObj->mappnt.x = point.x;
-     msObj->mappnt.y = point.y;
-
-     if (query_status == MS_NOTFOUND && msObj->map->web.empty)
-     {
-         if(msReturnURL(msObj, msObj->map->web.empty, BROWSE) != MS_SUCCESS)
-           return msWMSException(map, nVersion, NULL, wms_exception_format);
-     }
-     else if (msReturnTemplateQuery(msObj, (char *)info_format, NULL) != MS_SUCCESS)
-       return msWMSException(map, nVersion, NULL, wms_exception_format);
-
-     /* We don't want to free the map, and param names/values since they */
-     /* belong to the caller, set them to NULL before freeing the mapservObj */
-     msObj->map = NULL;
-     msObj->request->ParamNames = NULL;
-     msObj->request->ParamValues = NULL;
-     msObj->request->NumParams = 0;
-
-     msFreeMapServObj(msObj);
+  } else {
+    mapservObj *msObj;
+
+    msObj = msAllocMapServObj();
+
+    /* Translate some vars from WMS to mapserv */
+    msTranslateWMS2Mapserv(names, values, &numentries);
+
+    msObj->map = map;
+    msFreeCharArray(msObj->request->ParamNames, msObj->request->NumParams);
+    msFreeCharArray(msObj->request->ParamValues, msObj->request->NumParams);
+    msObj->request->ParamNames = names;
+    msObj->request->ParamValues = values;
+    msObj->Mode = QUERY;
+    msObj->request->NumParams = numentries;
+    msObj->mappnt.x = point.x;
+    msObj->mappnt.y = point.y;
+
+    if (query_status == MS_NOTFOUND && msObj->map->web.empty) {
+      if(msReturnURL(msObj, msObj->map->web.empty, BROWSE) != MS_SUCCESS)
+        return msWMSException(map, nVersion, NULL, wms_exception_format);
+    } else if (msReturnTemplateQuery(msObj, (char *)info_format, NULL) != MS_SUCCESS)
+      return msWMSException(map, nVersion, NULL, wms_exception_format);
+
+    /* We don't want to free the map, and param names/values since they */
+    /* belong to the caller, set them to NULL before freeing the mapservObj */
+    msObj->map = NULL;
+    msObj->request->ParamNames = NULL;
+    msObj->request->ParamValues = NULL;
+    msObj->request->NumParams = 0;
+
+    msFreeMapServObj(msObj);
   }
 
   return(MS_SUCCESS);
@@ -3319,456 +4114,476 @@ int msWMSDescribeLayer(mapObj *map, int nVersion, char **names,
   int numlayers = 0;
   int j, k;
   layerObj *lp = NULL;
-  const char *pszOnlineResMapWFS = NULL, *pszOnlineResLyrWFS = NULL; 
+  const char *pszOnlineResMapWFS = NULL, *pszOnlineResLyrWFS = NULL;
   const char *pszOnlineResMapWCS = NULL, *pszOnlineResLyrWCS = NULL;
   char *pszOnlineResEncoded=NULL, *pszLayerName=NULL;
   char *schemalocation = NULL;
   char *version = NULL;
   char *sld_version = NULL;
   const char *encoding;
+  char ***nestedGroups = NULL;
+  int *numNestedGroups = NULL;
+  int *isUsedInNestedGroup = NULL;
 
   encoding = msOWSLookupMetadata(&(map->web.metadata), "MO", "encoding");
 
   for(i=0; map && i<numentries; i++) {
-      if(strcasecmp(names[i], "LAYERS") == 0) {
-          layers = msStringSplit(values[i], ',', &numlayers);
-      }
-      if(strcasecmp(names[i], "VERSION") == 0) {
-          version = values[i];
-      }
-      if(strcasecmp(names[i], "SLD_VERSION") == 0) {
-          sld_version = values[i];
-      }
+    if(strcasecmp(names[i], "LAYERS") == 0) {
+      layers = msStringSplit(values[i], ',', &numlayers);
+    }
+    if(strcasecmp(names[i], "VERSION") == 0) {
+      version = values[i];
+    }
+    if(strcasecmp(names[i], "SLD_VERSION") == 0) {
+      sld_version = values[i];
+    }
   }
 
-  if (nVersion >= OWS_1_3_0 && sld_version == NULL)
-  {
-      msSetError(MS_WMSERR, "Missing required parameter SLD_VERSION", "DescribeLayer()");
-      return msWMSException(map, nVersion, "MissingParameterValue", wms_exception_format);
+  if (nVersion >= OWS_1_3_0 && sld_version == NULL) {
+    msSetError(MS_WMSERR, "Missing required parameter SLD_VERSION", "DescribeLayer()");
+    return msWMSException(map, nVersion, "MissingParameterValue", wms_exception_format);
   }
-  if (nVersion >= OWS_1_3_0 && strcasecmp(sld_version, "1.1.0") != 0)
-  {
-      msSetError(MS_WMSERR, "SLD_VERSION must be 1.1.0", "DescribeLayer()");
-      return msWMSException(map, nVersion, "InvalidParameterValue", wms_exception_format);
+  if (nVersion >= OWS_1_3_0 && strcasecmp(sld_version, "1.1.0") != 0) {
+    msSetError(MS_WMSERR, "SLD_VERSION must be 1.1.0", "DescribeLayer()");
+    return msWMSException(map, nVersion, "InvalidParameterValue", wms_exception_format);
   }
 
   if (encoding)
-      msIO_printf("Content-type: text/xml; charset=%s%c%c", encoding,10,10);
+    msIO_setHeader("Content-Type","text/xml; charset=%s", encoding);
   else
-      msIO_printf("Content-type: text/xml%c%c",10,10);
+    msIO_setHeader("Content-Type","text/xml");
+  msIO_sendHeaders();
 
   msOWSPrintEncodeMetadata(stdout, &(map->web.metadata),
-                            "MO", "encoding", OWS_NOERR,
-                            "<?xml version='1.0' encoding=\"%s\"?>\n",
-                            "ISO-8859-1");
+                           "MO", "encoding", OWS_NOERR,
+                           "<?xml version='1.0' encoding=\"%s\"?>\n",
+                           "ISO-8859-1");
 
-   schemalocation = msEncodeHTMLEntities(msOWSGetSchemasLocation(map));
-   if (nVersion < OWS_1_3_0)
-   {
-      
-       msIO_printf("<!DOCTYPE WMS_DescribeLayerResponse SYSTEM \"%s/wms/1.1.1/WMS_DescribeLayerResponse.dtd\">\n", schemalocation);
-      
+  schemalocation = msEncodeHTMLEntities(msOWSGetSchemasLocation(map));
+  if (nVersion < OWS_1_3_0) {
 
-       msIO_printf("<WMS_DescribeLayerResponse version=\"%s\" >\n", version);
-   }
-   else
-   {
-       msIO_printf("<DescribeLayerResponse xmlns=\"http://www.opengis.net/sld\" xmlns:ows=\"http://www.opengis.net/ows\" xmlns:se=\"http://www.opengis.net/se\" xmlns:wfs=\"http://www.opengis.net/wfs\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xsi:schemaLocation=\"http://www.opengis.net/sld %s/sld/1.1.0/DescribeLayer.xsd\">\n", schemalocation);
-       msIO_printf("<Version>%s</Version>\n",sld_version);
-       
-   }
-    free(schemalocation);
-
-   /* check if map-level metadata wfs(wcs)_onlineresource is available */
-   pszOnlineResMapWFS = msOWSLookupMetadata(&(map->web.metadata), "FO", "onlineresource");
-   if (pszOnlineResMapWFS && strlen(pszOnlineResMapWFS) == 0)
-       pszOnlineResMapWFS = NULL;
-
-   pszOnlineResMapWCS = msOWSLookupMetadata(&(map->web.metadata), "CO", "onlineresource");
-   if (pszOnlineResMapWCS && strlen(pszOnlineResMapWCS) == 0)
-     pszOnlineResMapWCS = NULL;
-
-   for(j=0; j<numlayers; j++)
-   {
-       for(k=0; k<map->numlayers; k++)
-       {
-         lp = GET_LAYER(map, k);
-         if (lp->name && strcasecmp(lp->name, layers[j]) == 0)
-         {
-             /* Look for a WFS onlineresouce at the layer level and then at
-              * the map level.
-              */
-           pszOnlineResLyrWFS = msOWSLookupMetadata(&(lp->metadata), "FO",
-                                                    "onlineresource");
-           pszOnlineResLyrWCS = msOWSLookupMetadata(&(lp->metadata), "CO",
-                                                    "onlineresource");
-           if (pszOnlineResLyrWFS == NULL || strlen(pszOnlineResLyrWFS) == 0)
-               pszOnlineResLyrWFS = pszOnlineResMapWFS;
-
-           if (pszOnlineResLyrWCS == NULL || strlen(pszOnlineResLyrWCS) == 0)
-               pszOnlineResLyrWCS = pszOnlineResMapWCS;
-
-           if (pszOnlineResLyrWFS && (lp->type == MS_LAYER_POINT ||
-                                      lp->type == MS_LAYER_LINE ||
-                                      lp->type == MS_LAYER_POLYGON) )
-           {
-             pszOnlineResEncoded = msEncodeHTMLEntities(pszOnlineResLyrWFS);
-             pszLayerName = msEncodeHTMLEntities(lp->name);
-
-             if (nVersion < OWS_1_3_0)
-             {
-                 msIO_printf("<LayerDescription name=\"%s\" wfs=\"%s\" owsType=\"WFS\" owsURL=\"%s\">\n",
-                             pszLayerName, pszOnlineResEncoded, pszOnlineResEncoded);
-                 msIO_printf("<Query typeName=\"%s\" />\n", pszLayerName);
-                 msIO_printf("</LayerDescription>\n");
-             }
-             else /*wms 1.3.0*/
-             {
-                 msIO_printf("  <LayerDescription>\n");
-                 msIO_printf("    <owsType>wfs</owsType>\n");
-                 msIO_printf("    <se:OnlineResource xlink:type=\"simple\" xlink:href=\"%s\"/>\n", 
-                             pszOnlineResEncoded);
-                 msIO_printf("    <TypeName>\n");
-                 msIO_printf("      <se:FeatureTypeName>%s</se:FeatureTypeName>\n",pszLayerName);
-                 msIO_printf("    </TypeName>\n");
-                 msIO_printf("  </LayerDescription>\n");
-             }
-           
-             msFree(pszOnlineResEncoded);
-             msFree(pszLayerName);
-           }
-           else if (pszOnlineResLyrWCS && lp->type == MS_LAYER_RASTER &&
-                    lp->connectiontype != MS_WMS)
-           {
-               pszOnlineResEncoded = msEncodeHTMLEntities(pszOnlineResLyrWCS);
-               pszLayerName = msEncodeHTMLEntities(lp->name);
-
-               if (nVersion < OWS_1_3_0)
-               {
-                   msIO_printf("<LayerDescription name=\"%s\"  owsType=\"WCS\" owsURL=\"%s\">\n",
-                               pszLayerName, pszOnlineResEncoded);
-                   msIO_printf("<Query typeName=\"%s\" />\n", pszLayerName);
-                   msIO_printf("</LayerDescription>\n");
-
-                   msFree(pszOnlineResEncoded);
-                   msFree(pszLayerName);
-               }        
-               else
-               {
-                   msIO_printf("  <LayerDescription>\n");
-                   msIO_printf("    <owsType>wcs</owsType>\n");
-                   msIO_printf("    <se:OnlineResource xlink:type=\"simple\" xlink:href=\"%s\"/>\n", 
-                               pszOnlineResEncoded);
-                   msIO_printf("    <TypeName>\n");
-                   msIO_printf("      <se:CoverageTypeName>%s</se:CoverageTypeName>\n",pszLayerName);
-                   msIO_printf("    </TypeName>\n");
-                   msIO_printf("  </LayerDescription>\n");
-               }
-           }
-           else
-           {
-             char *pszLayerName;
-             pszLayerName = msEncodeHTMLEntities(lp->name);
-
-             if (nVersion < OWS_1_3_0)
-               msIO_printf("<LayerDescription name=\"%s\"></LayerDescription>\n",
-                           pszLayerName);
-             else /*wms 1.3.0*/
-             {
-                 msIO_printf("  <LayerDescription>\n");
-                 /*need to have a owstype for the DescribeLayer to be valid*/
-                 if (lp->type == MS_LAYER_RASTER && lp->connectiontype != MS_WMS)
-                   msIO_printf("    <owsType>wcs</owsType>\n");
-                 else
-                    msIO_printf("    <owsType>wfs</owsType>\n");
-
-                 msIO_printf("    <se:OnlineResource xlink:type=\"simple\"/>\n"); 
-                 msIO_printf("    <TypeName>\n");
-                 if (lp->type == MS_LAYER_RASTER && lp->connectiontype != MS_WMS)
-                   msIO_printf("      <se:CoverageTypeName>%s</se:CoverageTypeName>\n",pszLayerName);
-                 else
-                   msIO_printf("      <se:FeatureTypeName>%s</se:FeatureTypeName>\n",pszLayerName);
-                 msIO_printf("    </TypeName>\n");
-                 msIO_printf("  </LayerDescription>\n");
-             }
-
-             msFree(pszLayerName);
-           }
-           break;
-         }
-       }
-   }
-
-   if (nVersion < OWS_1_3_0)
-     msIO_printf("</WMS_DescribeLayerResponse>\n");
-   else
-      msIO_printf("</DescribeLayerResponse>\n");
-
-   if (layers)
-     msFreeCharArray(layers, numlayers);
-
-   return(MS_SUCCESS);
+    msIO_printf("<!DOCTYPE WMS_DescribeLayerResponse SYSTEM \"%s/wms/1.1.1/WMS_DescribeLayerResponse.dtd\">\n", schemalocation);
+
+
+    msIO_printf("<WMS_DescribeLayerResponse version=\"%s\" >\n", version);
+  } else {
+    msIO_printf("<DescribeLayerResponse xmlns=\"http://www.opengis.net/sld\" xmlns:ows=\"http://www.opengis.net/ows\" xmlns:se=\"http://www.opengis.net/se\" xmlns:wfs=\"http://www.opengis.net/wfs\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xsi:schemaLocation=\"http://www.opengis.net/sld %s/sld/1.1.0/DescribeLayer.xsd\">\n", schemalocation);
+    msIO_printf("<Version>%s</Version>\n",sld_version);
+
+  }
+  free(schemalocation);
+
+  /* check if map-level metadata wfs(wcs)_onlineresource is available */
+  pszOnlineResMapWFS = msOWSLookupMetadata(&(map->web.metadata), "FO", "onlineresource");
+  if (pszOnlineResMapWFS && strlen(pszOnlineResMapWFS) == 0)
+    pszOnlineResMapWFS = NULL;
+
+  pszOnlineResMapWCS = msOWSLookupMetadata(&(map->web.metadata), "CO", "onlineresource");
+  if (pszOnlineResMapWCS && strlen(pszOnlineResMapWCS) == 0)
+    pszOnlineResMapWCS = NULL;
+
+  nestedGroups = (char***)msSmallCalloc(map->numlayers, sizeof(char**));
+  numNestedGroups = (int*)msSmallCalloc(map->numlayers, sizeof(int));
+  isUsedInNestedGroup = (int*)msSmallCalloc(map->numlayers, sizeof(int));
+  msWMSPrepareNestedGroups(map, nVersion, nestedGroups, numNestedGroups, isUsedInNestedGroup);
+
+  for(j=0; j<numlayers; j++) {
+    for(k=0; k<map->numlayers; k++) {
+      lp = GET_LAYER(map, k);
+
+      if ((map->name && strcasecmp(map->name, layers[j]) == 0) ||
+          (lp->name && strcasecmp(lp->name, layers[j]) == 0) ||
+          (lp->group && strcasecmp(lp->group, layers[j]) == 0) ||
+          ((numNestedGroups[k] >0) && msStringInArray(layers[j], nestedGroups[k], numNestedGroups[k]))) {
+        /* Look for a WFS onlineresouce at the layer level and then at
+         * the map level.
+         */
+        pszOnlineResLyrWFS = msOWSLookupMetadata(&(lp->metadata), "FO",
+                             "onlineresource");
+        pszOnlineResLyrWCS = msOWSLookupMetadata(&(lp->metadata), "CO",
+                             "onlineresource");
+        if (pszOnlineResLyrWFS == NULL || strlen(pszOnlineResLyrWFS) == 0)
+          pszOnlineResLyrWFS = pszOnlineResMapWFS;
+
+        if (pszOnlineResLyrWCS == NULL || strlen(pszOnlineResLyrWCS) == 0)
+          pszOnlineResLyrWCS = pszOnlineResMapWCS;
+
+        if (pszOnlineResLyrWFS && (lp->type == MS_LAYER_POINT ||
+                                   lp->type == MS_LAYER_LINE ||
+                                   lp->type == MS_LAYER_POLYGON) ) {
+          pszOnlineResEncoded = msEncodeHTMLEntities(pszOnlineResLyrWFS);
+          pszLayerName = msEncodeHTMLEntities(lp->name);
+
+          if (nVersion < OWS_1_3_0) {
+            msIO_printf("<LayerDescription name=\"%s\" wfs=\"%s\" owsType=\"WFS\" owsURL=\"%s\">\n",
+                        pszLayerName, pszOnlineResEncoded, pszOnlineResEncoded);
+            msIO_printf("<Query typeName=\"%s\" />\n", pszLayerName);
+            msIO_printf("</LayerDescription>\n");
+          } else { /*wms 1.3.0*/
+            msIO_printf("  <LayerDescription>\n");
+            msIO_printf("    <owsType>wfs</owsType>\n");
+            msIO_printf("    <se:OnlineResource xlink:type=\"simple\" xlink:href=\"%s\"/>\n",
+                        pszOnlineResEncoded);
+            msIO_printf("    <TypeName>\n");
+            msIO_printf("      <se:FeatureTypeName>%s</se:FeatureTypeName>\n",pszLayerName);
+            msIO_printf("    </TypeName>\n");
+            msIO_printf("  </LayerDescription>\n");
+          }
+
+          msFree(pszOnlineResEncoded);
+          msFree(pszLayerName);
+        } else if (pszOnlineResLyrWCS && lp->type == MS_LAYER_RASTER &&
+                   lp->connectiontype != MS_WMS) {
+          pszOnlineResEncoded = msEncodeHTMLEntities(pszOnlineResLyrWCS);
+          pszLayerName = msEncodeHTMLEntities(lp->name);
+
+          if (nVersion < OWS_1_3_0) {
+            msIO_printf("<LayerDescription name=\"%s\"  owsType=\"WCS\" owsURL=\"%s\">\n",
+                        pszLayerName, pszOnlineResEncoded);
+            msIO_printf("<Query typeName=\"%s\" />\n", pszLayerName);
+            msIO_printf("</LayerDescription>\n");
+
+            msFree(pszOnlineResEncoded);
+            msFree(pszLayerName);
+          } else {
+            msIO_printf("  <LayerDescription>\n");
+            msIO_printf("    <owsType>wcs</owsType>\n");
+            msIO_printf("    <se:OnlineResource xlink:type=\"simple\" xlink:href=\"%s\"/>\n",
+                        pszOnlineResEncoded);
+            msIO_printf("    <TypeName>\n");
+            msIO_printf("      <se:CoverageTypeName>%s</se:CoverageTypeName>\n",pszLayerName);
+            msIO_printf("    </TypeName>\n");
+            msIO_printf("  </LayerDescription>\n");
+          }
+        } else {
+          char *pszLayerName;
+          pszLayerName = msEncodeHTMLEntities(lp->name);
+
+          if (nVersion < OWS_1_3_0)
+            msIO_printf("<LayerDescription name=\"%s\"></LayerDescription>\n",
+                        pszLayerName);
+          else { /*wms 1.3.0*/
+            msIO_printf("  <LayerDescription>\n");
+            /*need to have a owstype for the DescribeLayer to be valid*/
+            if (lp->type == MS_LAYER_RASTER && lp->connectiontype != MS_WMS)
+              msIO_printf("    <owsType>wcs</owsType>\n");
+            else
+              msIO_printf("    <owsType>wfs</owsType>\n");
+
+            msIO_printf("    <se:OnlineResource xlink:type=\"simple\"/>\n");
+            msIO_printf("    <TypeName>\n");
+            if (lp->type == MS_LAYER_RASTER && lp->connectiontype != MS_WMS)
+              msIO_printf("      <se:CoverageTypeName>%s</se:CoverageTypeName>\n",pszLayerName);
+            else
+              msIO_printf("      <se:FeatureTypeName>%s</se:FeatureTypeName>\n",pszLayerName);
+            msIO_printf("    </TypeName>\n");
+            msIO_printf("  </LayerDescription>\n");
+          }
+
+          msFree(pszLayerName);
+        }
+        /* break; */
+      }
+    }
+  }
+
+  if (nVersion < OWS_1_3_0)
+    msIO_printf("</WMS_DescribeLayerResponse>\n");
+  else
+    msIO_printf("</DescribeLayerResponse>\n");
+
+  if (layers)
+    msFreeCharArray(layers, numlayers);
+
+  /* free the stuff used for nested layers */
+  for (i = 0; i < map->numlayers; i++) {
+    if (numNestedGroups[i] > 0) {
+      msFreeCharArray(nestedGroups[i], numNestedGroups[i]);
+    }
+  }
+  free(nestedGroups);
+  free(numNestedGroups);
+  free(isUsedInNestedGroup);
+
+  return(MS_SUCCESS);
 }
 
 
 /*
 ** msWMSGetLegendGraphic()
 */
-int msWMSGetLegendGraphic(mapObj *map, int nVersion, char **names,
-                          char **values, int numentries, char *wms_exception_format, owsRequestObj *ows_request)
+int msWMSLegendGraphic(mapObj *map, int nVersion, char **names,
+                       char **values, int numentries, char *wms_exception_format, owsRequestObj *ows_request)
 {
-    char *pszLayer = NULL;
-    char *pszFormat = NULL;
-    char *psRule = NULL;
-    char *psScale = NULL;
-    int iLayerIndex = -1;
-    outputFormatObj *psFormat = NULL;
-    imageObj *img=NULL;
-    int i = 0;
-    int nWidth = -1, nHeight =-1;
-    char *pszStyle = NULL;
-    char *sld_version = NULL;
-    const char *sldenabled = NULL;
-    const char *format_list = NULL;
-    layerObj *lp;
-    int nLayers =0;
-
-    sldenabled = msOWSLookupMetadata(&(map->web.metadata), "MO", "sld_enabled");
-
-    if (sldenabled == NULL)
-       sldenabled = "true";
-
-     for(i=0; map && i<numentries; i++)
-     {
-         if (strcasecmp(names[i], "LAYER") == 0)
-         {
-             pszLayer = values[i];
-         }
-         else if (strcasecmp(names[i], "WIDTH") == 0)
-           nWidth = atoi(values[i]);
-         else if (strcasecmp(names[i], "HEIGHT") == 0)
-           nHeight = atoi(values[i]);
-         else if (strcasecmp(names[i], "FORMAT") == 0)
-           pszFormat = values[i];
+  char *pszLayer = NULL;
+  char *pszFormat = NULL;
+  char *psRule = NULL;
+  char *psScale = NULL;
+  int iLayerIndex = -1;
+  outputFormatObj *psFormat = NULL;
+  imageObj *img=NULL;
+  int j, i = 0;
+  int nWidth = -1, nHeight =-1;
+  char *pszStyle = NULL;
+  char *sld_version = NULL;
+  int wms_layer =  MS_FALSE;
+  const char *sldenabled = NULL;
+  const char *format_list = NULL;
+  layerObj *lp;
+  int nLayers =0;
+  char ***nestedGroups = NULL;
+  int *numNestedGroups = NULL;
+  int *isUsedInNestedGroup = NULL;
+
+  sldenabled = msOWSLookupMetadata(&(map->web.metadata), "MO", "sld_enabled");
+
+  if (sldenabled == NULL)
+    sldenabled = "true";
+
+  for(i=0; map && i<numentries; i++) {
+    if (strcasecmp(names[i], "LAYER") == 0) {
+      pszLayer = values[i];
+    } else if (strcasecmp(names[i], "WIDTH") == 0)
+      nWidth = atoi(values[i]);
+    else if (strcasecmp(names[i], "HEIGHT") == 0)
+      nHeight = atoi(values[i]);
+    else if (strcasecmp(names[i], "FORMAT") == 0)
+      pszFormat = values[i];
+    else if (strcasecmp(names[i], "SCALE") == 0)
+      psScale = values[i];
 #ifdef USE_OGR
-/* -------------------------------------------------------------------- */
-/*      SLD support :                                                   */
-/*        - check if the SLD parameter is there. it is supposed to      */
-/*      refer a valid URL containing an SLD document.                   */
-/*        - check the SLD_BODY parameter that should contain the SLD    */
-/*      xml string.                                                     */
-/* -------------------------------------------------------------------- */
-         else if (strcasecmp(names[i], "SLD") == 0 &&
-                  values[i] && strlen(values[i]) > 0 && strcasecmp(sldenabled, "true") == 0)
-             msSLDApplySLDURL(map, values[i], -1, NULL);
-         else if (strcasecmp(names[i], "SLD_BODY") == 0 &&
-                  values[i] && strlen(values[i]) > 0 && strcasecmp(sldenabled, "true") == 0)
-             msSLDApplySLD(map, values[i], -1, NULL);
-         else if (strcasecmp(names[i], "RULE") == 0)
-           psRule = values[i];
-         else if (strcasecmp(names[i], "SCALE") == 0)
-           psScale = values[i];
-         else if (strcasecmp(names[i], "STYLE") == 0)
-           pszStyle = values[i];
-         else if(strcasecmp(names[i], "SLD_VERSION") == 0) 
-           sld_version = values[i];
+    /* -------------------------------------------------------------------- */
+    /*      SLD support :                                                   */
+    /*        - check if the SLD parameter is there. it is supposed to      */
+    /*      refer a valid URL containing an SLD document.                   */
+    /*        - check the SLD_BODY parameter that should contain the SLD    */
+    /*      xml string.                                                     */
+    /* -------------------------------------------------------------------- */
+    else if (strcasecmp(names[i], "SLD") == 0 &&
+             values[i] && strlen(values[i]) > 0 && strcasecmp(sldenabled, "true") == 0)
+      msSLDApplySLDURL(map, values[i], -1, NULL, NULL);
+    else if (strcasecmp(names[i], "SLD_BODY") == 0 &&
+             values[i] && strlen(values[i]) > 0 && strcasecmp(sldenabled, "true") == 0)
+      msSLDApplySLD(map, values[i], -1, NULL, NULL);
+    else if (strcasecmp(names[i], "RULE") == 0)
+      psRule = values[i];
+    else if (strcasecmp(names[i], "STYLE") == 0)
+      pszStyle = values[i];
 #endif
-     }
-
-     if (!pszLayer)
-     {
-         msSetError(MS_WMSERR, "Mandatory LAYER parameter missing in GetLegendGraphic request.", "msWMSGetLegendGraphic()");
-         return msWMSException(map, nVersion, "LayerNotDefined", wms_exception_format);
-     }
-     if (!pszFormat)
-     {
-         msSetError(MS_WMSERR, "Mandatory FORMAT parameter missing in GetLegendGraphic request.", "msWMSGetLegendGraphic()");
-         return msWMSException(map, nVersion, "InvalidFormat", wms_exception_format);
-     }
-
-     if (nVersion >= OWS_1_3_0 && sld_version == NULL)
-     {
-         msSetError(MS_WMSERR, "Missing required parameter SLD_VERSION", "GetLegendGraphic()");
-         return msWMSException(map, nVersion, "MissingParameterValue", wms_exception_format);
-     }
-     if (nVersion >= OWS_1_3_0 && strcasecmp(sld_version, "1.1.0") != 0)
-     {
-         msSetError(MS_WMSERR, "SLD_VERSION must be 1.1.0", "GetLegendGraphic()");
-         return msWMSException(map, nVersion, "InvalidParameterValue", wms_exception_format);
-     }
-     /* check if layer name is valid. we check for layer's and group's name*/
-     for (i=0; i<map->numlayers; i++)
-     {
-         lp = GET_LAYER(map, i);
-         if ( ((lp->name && strcasecmp(lp->name, pszLayer) == 0) ||
-               (lp->group && strcasecmp(lp->group, pszLayer) == 0)) &&
-              (msIntegerInArray(lp->index, ows_request->enabled_layers, ows_request->numlayers)) )
-           {
-               nLayers++;
-               lp->status = MS_ON;
-               iLayerIndex = i;
-           }
-         else
-           lp->status = MS_OFF;
-     }  
-
-     if (nLayers == 0)
-     {
-         msSetError(MS_WMSERR, "Invalid layer given in the LAYER parameter.",
+    /* -------------------------------------------------------------------- */
+    /*      SLD support:                                                    */
+    /*        - because the request parameter "sld_version" is required in  */
+    /*          in WMS 1.3.0, it will be set regardless of OGR support.     */
+    /* -------------------------------------------------------------------- */
+    else if(strcasecmp(names[i], "SLD_VERSION") == 0)
+      sld_version = values[i];
+  }
+
+  if (!pszLayer) {
+    msSetError(MS_WMSERR, "Mandatory LAYER parameter missing in GetLegendGraphic request.", "msWMSGetLegendGraphic()");
+    return msWMSException(map, nVersion, "LayerNotDefined", wms_exception_format);
+  }
+  if (!pszFormat) {
+    msSetError(MS_WMSERR, "Mandatory FORMAT parameter missing in GetLegendGraphic request.", "msWMSGetLegendGraphic()");
+    return msWMSException(map, nVersion, "InvalidFormat", wms_exception_format);
+  }
+
+  if (nVersion >= OWS_1_3_0 && sld_version == NULL) {
+    msSetError(MS_WMSERR, "Missing required parameter SLD_VERSION", "GetLegendGraphic()");
+    return msWMSException(map, nVersion, "MissingParameterValue", wms_exception_format);
+  }
+  if (nVersion >= OWS_1_3_0 && strcasecmp(sld_version, "1.1.0") != 0) {
+    msSetError(MS_WMSERR, "SLD_VERSION must be 1.1.0", "GetLegendGraphic()");
+    return msWMSException(map, nVersion, "InvalidParameterValue", wms_exception_format);
+  }
+
+  nestedGroups = (char***)msSmallCalloc(map->numlayers, sizeof(char**));
+  numNestedGroups = (int*)msSmallCalloc(map->numlayers, sizeof(int));
+  isUsedInNestedGroup = (int*)msSmallCalloc(map->numlayers, sizeof(int));
+  msWMSPrepareNestedGroups(map, nVersion, nestedGroups, numNestedGroups, isUsedInNestedGroup);
+
+  /* check if layer name is valid. we check for layer's and group's name */
+  /* as well as wms_layer_group names */
+  for (i=0; i<map->numlayers; i++) {
+    lp = GET_LAYER(map, i);
+    if (  ((map->name && strcasecmp(map->name, pszLayer) == 0) ||
+           (lp->name && strcasecmp(lp->name, pszLayer) == 0) ||
+           (lp->group && strcasecmp(lp->group, pszLayer) == 0) ||
+           ((numNestedGroups[i] >0) && (msStringInArray(pszLayer, nestedGroups[i], numNestedGroups[i]))) ) &&
+          (msIntegerInArray(lp->index, ows_request->enabled_layers, ows_request->numlayers)) ) {
+      nLayers++;
+      lp->status = MS_ON;
+      iLayerIndex = i;
+      if (GET_LAYER(map, i)->connectiontype == MS_WMS) {
+        /* we do not cascade a wms layer if it contains at least
+         * one class with the property name set */
+        wms_layer = MS_TRUE;
+        for (j=0; j<lp->numclasses; j++) {
+          if (lp->class[j]->name != NULL && strlen(lp->class[j]->name)>0) {
+            wms_layer = MS_FALSE;
+            break;
+          }
+        }
+      }
+    } else
+      lp->status = MS_OFF;
+  }
+
+  /* free the stuff used for nested layers */
+  for (i = 0; i < map->numlayers; i++) {
+    if (numNestedGroups[i] > 0) {
+      msFreeCharArray(nestedGroups[i], numNestedGroups[i]);
+    }
+  }
+  free(nestedGroups);
+  free(numNestedGroups);
+  free(isUsedInNestedGroup);
+
+  if (nLayers == 0) {
+    msSetError(MS_WMSERR, "Invalid layer given in the LAYER parameter. A layer might be disabled for \
+this request. Check wms/ows_enable_request settings.",
+               "msWMSGetLegendGraphic()");
+    return msWMSException(map, nVersion, "LayerNotDefined", wms_exception_format);
+  }
+
+  /* validate format */
+
+  /*check to see if a predefined list is given*/
+  format_list = msOWSLookupMetadata(&(map->web.metadata), "M","getlegendgraphic_formatlist");
+  if (format_list) {
+    psFormat = msOwsIsOutputFormatValid(map, pszFormat, &(map->web.metadata),
+                                        "M", "getlegendgraphic_formatlist");
+    if (psFormat == NULL) {
+      msSetError(MS_IMGERR,
+                 "Unsupported output format (%s).",
+                 "msWMSGetLegendGraphic()",
+                 pszFormat);
+      return msWMSException(map, nVersion, "InvalidFormat", wms_exception_format);
+    }
+  } else {
+    psFormat = msSelectOutputFormat( map, pszFormat);
+    if( psFormat == NULL || ! MS_RENDERER_PLUGIN(psFormat) )
+      /* msDrawLegend and msCreateLegendIcon both switch the alpha channel to gd
+      ** after creation, so they can be called here without going through
+      ** the msAlphaGD2AGG functions */
+    {
+      msSetError(MS_IMGERR,
+                 "Unsupported output format (%s).",
+                 "msWMSGetLegendGraphic()",
+                 pszFormat);
+      return msWMSException(map, nVersion, "InvalidFormat", wms_exception_format);
+    }
+  }
+  msApplyOutputFormat(&(map->outputformat), psFormat, MS_NOOVERRIDE,
+                      MS_NOOVERRIDE, MS_NOOVERRIDE );
+
+  /* if SCALE was provided in request, calculate an extent and use a default width and height */
+  if ( psScale != NULL ) {
+    double scale, cellsize;
+
+    scale = atof(psScale);
+    map->width = 600;
+    map->height = 600;
+
+    cellsize = (scale/map->resolution)/msInchesPerUnit(map->units, 0.0);
+
+    map->extent.maxx = cellsize*map->width/2.0;
+    map->extent.maxy = cellsize*map->height/2.0;
+    map->extent.minx = -map->extent.maxx;
+    map->extent.miny = -map->extent.maxy;
+  }
+  
+  /* It's a valid Cascading WMS GetLegendGraphic request */
+  if (wms_layer)
+    return msWMSLayerExecuteRequest(map, 1, 0, 0,
+                                    0, NULL, WMS_GETLEGENDGRAPHIC);
+
+  /*if STYLE is set, check if it is a valid style (valid = at least one
+    of the classes have a the group value equals to the style */
+  /*style is only validated when there is only one layer #3411*/
+  if (nLayers == 1 &&  pszStyle && strlen(pszStyle) > 0 && strcasecmp(pszStyle, "default") != 0) {
+    for (i=0; i<GET_LAYER(map, iLayerIndex)->numclasses; i++) {
+      if (GET_LAYER(map, iLayerIndex)->class[i]->group &&
+          strcasecmp(GET_LAYER(map, iLayerIndex)->class[i]->group, pszStyle) == 0)
+        break;
+    }
+
+    if (i == GET_LAYER(map, iLayerIndex)->numclasses) {
+      msSetError(MS_WMSERR, "style used in the STYLE parameter is not defined on the layer.",
                  "msWMSGetLegendGraphic()");
-         return msWMSException(map, nVersion, "LayerNotDefined", wms_exception_format);
-     }
-
-     /* validate format */
-     
-     /*check to see if a predefined list is given*/
-     format_list = msOWSLookupMetadata(&(map->web.metadata), "M","getlegendgraphic_formatlist");        
-     if (format_list)
-     {
-         psFormat = msOwsIsOutputFormatValid(map, pszFormat, &(map->web.metadata),
-                                             "M", "getlegendgraphic_formatlist");
-         if (psFormat == NULL)
-         {
-             msSetError(MS_IMGERR,
-                        "Unsupported output format (%s).",
-                        "msWMSGetLegendGraphic()",
-                        pszFormat);
-             return msWMSException(map, nVersion, "InvalidFormat", wms_exception_format);
-         }
-     }
-     else
-     {
-         psFormat = msSelectOutputFormat( map, pszFormat);
-         if( psFormat == NULL || ! MS_RENDERER_PLUGIN(psFormat) ) 
-           /* msDrawLegend and msCreateLegendIcon both switch the alpha channel to gd
-           ** after creation, so they can be called here without going through
-           ** the msAlphaGD2AGG functions */
-         {
-             msSetError(MS_IMGERR,
-                        "Unsupported output format (%s).",
-                        "msWMSGetLegendGraphic()",
-                        pszFormat);
-             return msWMSException(map, nVersion, "InvalidFormat", wms_exception_format);
-         }
-     }
-     msApplyOutputFormat(&(map->outputformat), psFormat, MS_NOOVERRIDE,
-                          MS_NOOVERRIDE, MS_NOOVERRIDE );
-
-     /*if STYLE is set, check if it is a valid style (valid = at least one
-       of the classes have a the group value equals to the style */
-     /*style is only validated when there is only one layer #3411*/
-     if (nLayers == 1 &&  pszStyle && strlen(pszStyle) > 0 && strcasecmp(pszStyle, "default") != 0)
-     {
-         for (i=0; i<GET_LAYER(map, iLayerIndex)->numclasses; i++)
-         {
-              if (GET_LAYER(map, iLayerIndex)->class[i]->group &&
-                  strcasecmp(GET_LAYER(map, iLayerIndex)->class[i]->group, pszStyle) == 0)
-                break;
-         }
-              
-         if (i == GET_LAYER(map, iLayerIndex)->numclasses)
-         {
-             msSetError(MS_WMSERR, "style used in the STYLE parameter is not defined on the layer.", 
-                        "msWMSGetLegendGraphic()");
-             return msWMSException(map, nVersion, "StyleNotDefined", wms_exception_format);
-         }
-         else
-         {
-             if (GET_LAYER(map, iLayerIndex)->classgroup)
-               msFree(GET_LAYER(map, iLayerIndex)->classgroup);
-             GET_LAYER(map, iLayerIndex)->classgroup = msStrdup(pszStyle);
-             
-         }
-     }
-
-     if ( psRule == NULL || nLayers > 1)
-     {
-         /* if SCALE was provided in request, calculate an extent and use a default width and height */
-         if ( psScale != NULL )
-         {
-             double center_y, scale, cellsize;
-
-             scale = atof(psScale);
-             map->width = 600;
-             map->height = 600;
-             center_y = 0.0;
-
-             cellsize = (scale/map->resolution)/msInchesPerUnit(map->units, center_y);
-
-             map->extent.minx = 0.0 - cellsize*map->width/2.0;
-             map->extent.miny = 0.0 - cellsize*map->height/2.0;
-             map->extent.maxx = 0.0 + cellsize*map->width/2.0;
-             map->extent.maxy = 0.0 + cellsize*map->height/2.0;
-
-             img = msDrawLegend(map, MS_FALSE);
-         }
-         else
-         {
-             /* Scale-independent legend */
-             img = msDrawLegend(map, MS_TRUE);
-         }
-     }
-     else
-     {
-         /* RULE was specified. Get the class corresponding to the RULE */
-         /* (RULE = class->name) */
-         
-         for (i=0; i<GET_LAYER(map, iLayerIndex)->numclasses; i++)
-         {
-             if (GET_LAYER(map, iLayerIndex)->classgroup && 
-                 (GET_LAYER(map, iLayerIndex)->class[i]->group == NULL ||
-                  strcasecmp(GET_LAYER(map, iLayerIndex)->class[i]->group, 
-                             GET_LAYER(map, iLayerIndex)->classgroup) != 0))
-               continue;
-
-             if (GET_LAYER(map, iLayerIndex)->class[i]->name && 
-                 strlen(GET_LAYER(map, iLayerIndex)->class[i]->name) > 0 &&
-                 strcasecmp(GET_LAYER(map, iLayerIndex)->class[i]->name,psRule) == 0)
-               break;
-             
-         }
-         if (i < GET_LAYER(map, iLayerIndex)->numclasses)
-         {
-         /* set the map legend parameters */
-             if (nWidth < 0)
-             {
-                 if (map->legend.keysizex > 0)
-                   nWidth = map->legend.keysizex;
-                 else
-                   nWidth = 20; /* default values : this in not defined in the specs */
-             }
-             if (nHeight < 0)
-             {
-                 if (map->legend.keysizey > 0)
-                   nHeight = map->legend.keysizey;
-                 else
-                   nHeight = 20;
-             }
-             
-             img = msCreateLegendIcon(map, GET_LAYER(map, iLayerIndex), 
-                                      GET_LAYER(map, iLayerIndex)->class[i],
-                                      nWidth, nHeight);
-         }
-         if (img == NULL)
-         {
-             msSetError(MS_IMGERR,
-                        "Unavailable RULE (%s).",
-                        "msWMSGetLegendGraphic()",
-                        psRule);
-             return msWMSException(map, nVersion, "InvalidRule", wms_exception_format);
-         }
-     }
-
-     if (img == NULL)
-       return msWMSException(map, nVersion, NULL, wms_exception_format);
-
-     msIO_printf("Content-type: %s%c%c", MS_IMAGE_MIME_TYPE(map->outputformat), 10,10);
-     if (msSaveImage(map, img, NULL) != MS_SUCCESS)
-       return msWMSException(map, nVersion, NULL, wms_exception_format);
-
-     msFreeImage(img);
-
-     return(MS_SUCCESS);
+      return msWMSException(map, nVersion, "StyleNotDefined", wms_exception_format);
+    } else {
+      msFree(GET_LAYER(map, iLayerIndex)->classgroup);
+      GET_LAYER(map, iLayerIndex)->classgroup = msStrdup(pszStyle);
+
+    }
+  }
+
+  if ( psRule == NULL || nLayers > 1) {
+    if ( psScale != NULL ) {
+      /* Scale-dependent legend. map->scaledenom will be calculated in msDrawLegend */
+      img = msDrawLegend(map, MS_FALSE);
+    } else {
+      /* Scale-independent legend */
+      img = msDrawLegend(map, MS_TRUE);
+    }
+  } else {
+    /* RULE was specified. Get the class corresponding to the RULE */
+    /* (RULE = class->name) */
+    /* TBT FIXME? also check the map->scaledenom if multiple scale-dependant classes with same name */
+
+    for (i=0; i<GET_LAYER(map, iLayerIndex)->numclasses; i++) {
+      if (GET_LAYER(map, iLayerIndex)->classgroup &&
+          (GET_LAYER(map, iLayerIndex)->class[i]->group == NULL ||
+           strcasecmp(GET_LAYER(map, iLayerIndex)->class[i]->group,
+                      GET_LAYER(map, iLayerIndex)->classgroup) != 0))
+        continue;
+
+      if (GET_LAYER(map, iLayerIndex)->class[i]->name &&
+          strlen(GET_LAYER(map, iLayerIndex)->class[i]->name) > 0 &&
+          strcasecmp(GET_LAYER(map, iLayerIndex)->class[i]->name,psRule) == 0)
+        break;
+
+    }
+    if (i < GET_LAYER(map, iLayerIndex)->numclasses) {
+      /* set the map legend parameters */
+      if (nWidth < 0) {
+        if (map->legend.keysizex > 0)
+          nWidth = map->legend.keysizex;
+        else
+          nWidth = 20; /* default values : this in not defined in the specs */
+      }
+      if (nHeight < 0) {
+        if (map->legend.keysizey > 0)
+          nHeight = map->legend.keysizey;
+        else
+          nHeight = 20;
+      }
+
+      img = msCreateLegendIcon(map, GET_LAYER(map, iLayerIndex),
+                               GET_LAYER(map, iLayerIndex)->class[i],
+                               nWidth, nHeight);
+    }
+    if (img == NULL) {
+      msSetError(MS_IMGERR,
+                 "Unavailable RULE (%s).",
+                 "msWMSGetLegendGraphic()",
+                 psRule);
+      return msWMSException(map, nVersion, "InvalidRule", wms_exception_format);
+    }
+  }
+
+  if (img == NULL)
+    return msWMSException(map, nVersion, NULL, wms_exception_format);
+
+  msIO_setHeader("Content-Type",MS_IMAGE_MIME_TYPE(map->outputformat));
+  msIO_sendHeaders();
+  if (msSaveImage(map, img, NULL) != MS_SUCCESS)
+    return msWMSException(map, nVersion, NULL, wms_exception_format);
+
+  msFreeImage(img);
+
+  return(MS_SUCCESS);
 }
 
 
@@ -3780,109 +4595,125 @@ int msWMSGetStyles(mapObj *map, int nVersion, char **names,
                    char **values, int numentries, char *wms_exception_format)
 
 {
-    int i,j,k;
-    int validlayer = 0;
-    int numlayers = 0;
-    char **layers = NULL;
-    char  *sld = NULL;
-    const char *encoding;
+  int i,j,k;
+  int validlayer = 0;
+  int numlayers = 0;
+  char **layers = NULL;
+  char  *sld = NULL;
+  const char *encoding;
 
-    encoding = msOWSLookupMetadata(&(map->web.metadata), "MO", "encoding");
+  char ***nestedGroups = NULL;
+  int *numNestedGroups = NULL;
+  int *isUsedInNestedGroup = NULL;
 
-    for(i=0; map && i<numentries; i++)
-    {
-        /* getMap parameters */
-        if (strcasecmp(names[i], "LAYERS") == 0)
-        {
-            layers = msStringSplit(values[i], ',', &numlayers);
-            if (layers==NULL || numlayers < 1) {
-                msSetError(MS_WMSERR, "At least one layer name required in LAYERS.",
-                   "msWMSGetStyles()");
-                return msWMSException(map, nVersion, NULL, wms_exception_format);
-            }
-            for(j=0; j<map->numlayers; j++)
-               GET_LAYER(map, j)->status = MS_OFF;
-
-            for (k=0; k<numlayers; k++)
-            {
-                for (j=0; j<map->numlayers; j++)
-                {
-                    if ((GET_LAYER(map, j)->name &&
-                         strcasecmp(GET_LAYER(map, j)->name, layers[k]) == 0) ||
-                        (GET_LAYER(map, j)->group &&
-                         strcasecmp(GET_LAYER(map, j)->group, layers[k]) == 0))
-                    {
-                        GET_LAYER(map, j)->status = MS_ON;
-                        validlayer =1;
-                    }
-                }
-            }
+  encoding = msOWSLookupMetadata(&(map->web.metadata), "MO", "encoding");
+
+  nestedGroups = (char***)msSmallCalloc(map->numlayers, sizeof(char**));
+  numNestedGroups = (int*)msSmallCalloc(map->numlayers, sizeof(int));
+  isUsedInNestedGroup = (int*)msSmallCalloc(map->numlayers, sizeof(int));
+  msWMSPrepareNestedGroups(map, nVersion, nestedGroups, numNestedGroups, isUsedInNestedGroup);
 
-            msFreeCharArray(layers, numlayers);
+  for(i=0; map && i<numentries; i++) {
+    /* getMap parameters */
+    if (strcasecmp(names[i], "LAYERS") == 0) {
+      layers = msStringSplit(values[i], ',', &numlayers);
+      if (layers==NULL || numlayers < 1) {
+        msSetError(MS_WMSERR, "At least one layer name required in LAYERS.",
+                   "msWMSGetStyles()");
+        return msWMSException(map, nVersion, NULL, wms_exception_format);
+      }
+      for(j=0; j<map->numlayers; j++)
+        GET_LAYER(map, j)->status = MS_OFF;
+
+      for (k=0; k<numlayers; k++) {
+        for (j=0; j<map->numlayers; j++) {
+          if ((map->name &&
+               strcasecmp(map->name, layers[k]) == 0) ||
+              (GET_LAYER(map, j)->name &&
+               strcasecmp(GET_LAYER(map, j)->name, layers[k]) == 0) ||
+              (GET_LAYER(map, j)->group &&
+               strcasecmp(GET_LAYER(map, j)->group, layers[k]) == 0) ||
+              ((numNestedGroups[j] >0) && msStringInArray(layers[k], nestedGroups[j], numNestedGroups[j])) ) {
+            GET_LAYER(map, j)->status = MS_ON;
+            validlayer =1;
+          }
         }
+      }
 
+      msFreeCharArray(layers, numlayers);
     }
 
-    /* validate all layers given. If an invalid layer is sent, return an exception. */
-    if (validlayer == 0)
-    {
-        msSetError(MS_WMSERR, "Invalid layer(s) given in the LAYERS parameter.",
-                   "msWMSGetStyles()");
-        return msWMSException(map, nVersion, "LayerNotDefined", wms_exception_format);
-    }
+  }
 
-    if (nVersion <= OWS_1_1_1)
-    {
-        if (encoding)
-            msIO_printf("Content-type: application/vnd.ogc.sld+xml; charset=%s%c%c", encoding,10,10);
-        else
-            msIO_printf("Content-type: application/vnd.ogc.sld+xml%c%c",10,10);
-        sld = msSLDGenerateSLD(map, -1, "1.0.0");
+  /* free the stuff used for nested layers */
+  for (i = 0; i < map->numlayers; i++) {
+    if (numNestedGroups[i] > 0) {
+      msFreeCharArray(nestedGroups[i], numNestedGroups[i]);
     }
+  }
+  free(nestedGroups);
+  free(numNestedGroups);
+  free(isUsedInNestedGroup);
+
+  /* validate all layers given. If an invalid layer is sent, return an exception. */
+  if (validlayer == 0) {
+    msSetError(MS_WMSERR, "Invalid layer(s) given in the LAYERS parameter. A layer might be disabled for \
+this request. Check wms/ows_enable_request settings.",
+               "msWMSGetStyles()");
+    return msWMSException(map, nVersion, "LayerNotDefined", wms_exception_format);
+  }
+
+  if (nVersion <= OWS_1_1_1) {
+    if (encoding)
+      msIO_setHeader("Content-Type","application/vnd.ogc.sld+xml; charset=%s", encoding);
     else
-    {   
-      /*for wms 1.3.0 generate a 1.1 sld*/
-        if (encoding)
-            msIO_printf("Content-type: text/xml; charset=%s%c%c", encoding,10,10);
-        else
-            msIO_printf("Content-type: text/xml%c%c",10,10);
-        sld = msSLDGenerateSLD(map, -1, "1.1.0");
-    }
-    if (sld)
-    {
-        msIO_printf("%s\n", sld);
-        free(sld);
-    }
+      msIO_setHeader("Content-Type","application/vnd.ogc.sld+xml");
+    msIO_sendHeaders();
+    sld = msSLDGenerateSLD(map, -1, "1.0.0");
+  } else {
+    /*for wms 1.3.0 generate a 1.1 sld*/
+    if (encoding)
+      msIO_setHeader("Content-Type","text/xml; charset=%s", encoding);
+    else
+      msIO_setHeader("Content-Type","text/xml");
+    msIO_sendHeaders();
+    sld = msSLDGenerateSLD(map, -1, "1.1.0");
+  }
+  if (sld) {
+    msIO_printf("%s\n", sld);
+    free(sld);
+  }
 
-    return(MS_SUCCESS);
+  return(MS_SUCCESS);
 }
 
-int msWMSGetSchemaExtension(mapObj *map) 
+int msWMSGetSchemaExtension(mapObj *map)
 {
-    char *schemalocation = NULL;
-    const char *encoding;
+  char *schemalocation = NULL;
+  const char *encoding;
 
-    schemalocation = msEncodeHTMLEntities(msOWSGetSchemasLocation(map));
+  schemalocation = msEncodeHTMLEntities(msOWSGetSchemasLocation(map));
 
-    encoding = msOWSLookupMetadata(&(map->web.metadata), "MO", "encoding");
+  encoding = msOWSLookupMetadata(&(map->web.metadata), "MO", "encoding");
 
-    if (encoding)
-        msIO_printf("Content-type: text/xml; charset=%s%c%c", encoding,10,10);
-    else
-        msIO_printf("Content-type: text/xml%c%c",10,10);
+  if (encoding)
+    msIO_setHeader("Content-Type","text/xml; charset=%s", encoding);
+  else
+    msIO_setHeader("Content-Type","text/xml");
+  msIO_sendHeaders();
 
-    msOWSPrintEncodeMetadata(stdout, &(map->web.metadata),
-                            "MO", "encoding", OWS_NOERR,
-                            "<?xml version='1.0' encoding=\"%s\"?>\n",
-                            "ISO-8859-1");
-    msIO_printf("<schema xmlns=\"http://www.w3.org/2001/XMLSchema\" xmlns:wms=\"http://www.opengis.net/wms\" xmlns:ms=\"http://mapserver.gis.umn.edu/mapserver\" targetNamespace=\"http://mapserver.gis.umn.edu/mapserver\" elementFormDefault=\"qualified\" version=\"1.0.0\">\n");
-    msIO_printf("  <import namespace=\"http://www.opengis.net/wms\" schemaLocation=\"%s/wms/1.3.0/capabilities_1_3_0.xsd\"/>\n", schemalocation);
-    msIO_printf("  <element name=\"GetStyles\" type=\"wms:OperationType\" substitutionGroup=\"wms:_ExtendedOperation\"/>\n");
-    msIO_printf("</schema>");
+  msOWSPrintEncodeMetadata(stdout, &(map->web.metadata),
+                           "MO", "encoding", OWS_NOERR,
+                           "<?xml version='1.0' encoding=\"%s\"?>\n",
+                           "ISO-8859-1");
+  msIO_printf("<schema xmlns=\"http://www.w3.org/2001/XMLSchema\" xmlns:wms=\"http://www.opengis.net/wms\" xmlns:ms=\"http://mapserver.gis.umn.edu/mapserver\" targetNamespace=\"http://mapserver.gis.umn.edu/mapserver\" elementFormDefault=\"qualified\" version=\"1.0.0\">\n");
+  msIO_printf("  <import namespace=\"http://www.opengis.net/wms\" schemaLocation=\"%s/wms/1.3.0/capabilities_1_3_0.xsd\"/>\n", schemalocation);
+  msIO_printf("  <element name=\"GetStyles\" type=\"wms:OperationType\" substitutionGroup=\"wms:_ExtendedOperation\"/>\n");
+  msIO_printf("</schema>");
 
-    free(schemalocation);
+  free(schemalocation);
 
-    return(MS_SUCCESS);
+  return(MS_SUCCESS);
 }
 
 #endif /* USE_WMS_SVR */
@@ -3900,10 +4731,11 @@ int msWMSDispatch(mapObj *map, cgiRequestObj *req, owsRequestObj *ows_request, i
 {
 #ifdef USE_WMS_SVR
   int i, status, nVersion=OWS_VERSION_NOTSET;
-  const char *version=NULL, *request=NULL, *service=NULL, *format=NULL, *updatesequence=NULL;
+  const char *version=NULL, *request=NULL, *service=NULL, *format=NULL, *updatesequence=NULL, *language=NULL;
   const char * encoding;
   char *wms_exception_format = NULL;
-  
+  char *validated_language = NULL;
+
   encoding = msOWSLookupMetadata(&(map->web.metadata), "MO", "encoding");
 
   /*
@@ -3911,51 +4743,49 @@ int msWMSDispatch(mapObj *map, cgiRequestObj *req, owsRequestObj *ows_request, i
   */
   /* VERSION (WMTVER in 1.0.0) and REQUEST must be present in a valid request */
   for(i=0; i<req->NumParams; i++) {
-      if(strcasecmp(req->ParamNames[i], "VERSION") == 0)
-        version = req->ParamValues[i];
-      else if (strcasecmp(req->ParamNames[i], "WMTVER") == 0 && version == NULL)
-        version = req->ParamValues[i];
-      else if (strcasecmp(req->ParamNames[i], "UPDATESEQUENCE") == 0)
-        updatesequence = req->ParamValues[i];
-      else if (strcasecmp(req->ParamNames[i], "REQUEST") == 0)
-        request = req->ParamValues[i];
-      else if (strcasecmp(req->ParamNames[i], "EXCEPTIONS") == 0)
-        wms_exception_format = req->ParamValues[i];
-      else if (strcasecmp(req->ParamNames[i], "SERVICE") == 0)
-        service = req->ParamValues[i];
-      else if (strcasecmp(req->ParamNames[i], "FORMAT") == 0)
-        format = req->ParamValues[i];
+    if(strcasecmp(req->ParamNames[i], "VERSION") == 0)
+      version = req->ParamValues[i];
+    else if (strcasecmp(req->ParamNames[i], "WMTVER") == 0 && version == NULL)
+      version = req->ParamValues[i];
+    else if (strcasecmp(req->ParamNames[i], "UPDATESEQUENCE") == 0)
+      updatesequence = req->ParamValues[i];
+    else if (strcasecmp(req->ParamNames[i], "REQUEST") == 0)
+      request = req->ParamValues[i];
+    else if (strcasecmp(req->ParamNames[i], "EXCEPTIONS") == 0)
+      wms_exception_format = req->ParamValues[i];
+    else if (strcasecmp(req->ParamNames[i], "SERVICE") == 0)
+      service = req->ParamValues[i];
+    else if (strcasecmp(req->ParamNames[i], "FORMAT") == 0)
+      format = req->ParamValues[i];
+    else if (strcasecmp(req->ParamNames[i], "LANGUAGE") == 0 && msOWSLookupMetadata(&(map->web.metadata), "MO", "inspire_capabilities"))
+      language = req->ParamValues[i];
   }
 
   /* If SERVICE is specified then it MUST be "WMS" */
   if (service != NULL && strcasecmp(service, "WMS") != 0)
-      return MS_DONE;  /* Not a WMS request */
+    return MS_DONE;  /* Not a WMS request */
 
   nVersion = msOWSParseVersionString(version);
-  if (nVersion == OWS_VERSION_BADFORMAT)
-  {
-       /* Invalid version format. msSetError() has been called by 
-        * msOWSParseVersionString() and we return the error as an exception 
-        */
-      return msWMSException(map, OWS_VERSION_NOTSET, NULL, wms_exception_format);
+  if (nVersion == OWS_VERSION_BADFORMAT) {
+    /* Invalid version format. msSetError() has been called by
+     * msOWSParseVersionString() and we return the error as an exception
+     */
+    return msWMSException(map, OWS_VERSION_NOTSET, NULL, wms_exception_format);
   }
 
   /*
   ** GetCapbilities request needs the service parametr defined as WMS:
   see section 7.1.3.2 wms 1.1.1 specs for decsription.
   */
-  if (request && service == NULL && 
+  if (request && service == NULL &&
       (strcasecmp(request, "capabilities") == 0 ||
        strcasecmp(request, "GetCapabilities") == 0) &&
-      (nVersion >= OWS_1_0_7 || nVersion == OWS_VERSION_NOTSET))
-  {
-      if (force_wms_mode)
-      {
-          msSetError(MS_WMSERR, "Required SERVICE parameter missing.", "msWMSDispatch");
-          return msWMSException(map, nVersion, "ServiceNotDefined", wms_exception_format);
-      }
-      else
-        return MS_DONE;
+      (nVersion >= OWS_1_0_7 || nVersion == OWS_VERSION_NOTSET)) {
+    if (force_wms_mode) {
+      msSetError(MS_WMSERR, "Required SERVICE parameter missing.", "msWMSDispatch");
+      return msWMSException(map, nVersion, "ServiceNotDefined", wms_exception_format);
+    } else
+      return MS_DONE;
   }
 
   /*
@@ -3963,130 +4793,127 @@ int msWMSDispatch(mapObj *map, cgiRequestObj *req, owsRequestObj *ows_request, i
   ** vs the versions we actually support.
   */
   if (request && (strcasecmp(request, "capabilities") == 0 ||
-                  strcasecmp(request, "GetCapabilities") == 0) )
-  {
-      if (nVersion == OWS_VERSION_NOTSET)
-      {
-          version = msOWSLookupMetadata(&(map->web.metadata), "M", "getcapabilities_version");
-          if (version)
-            nVersion = msOWSParseVersionString(version);
-          else
-            nVersion = OWS_1_3_0;/* VERSION is optional with getCapabilities only */
-      }
+                  strcasecmp(request, "GetCapabilities") == 0) ) {
+    const char *enable_request;
+    int globally_enabled, disabled = MS_FALSE;
+
+    if (nVersion == OWS_VERSION_NOTSET) {
+      version = msOWSLookupMetadata(&(map->web.metadata), "M", "getcapabilities_version");
+      if (version)
+        nVersion = msOWSParseVersionString(version);
+      else
+        nVersion = OWS_1_3_0;/* VERSION is optional with getCapabilities only */
+    }
 
-      if ((status = msOWSMakeAllLayersUnique(map)) != MS_SUCCESS)
-        return msWMSException(map, nVersion, NULL, wms_exception_format);
+    if ((status = msOWSMakeAllLayersUnique(map)) != MS_SUCCESS)
+      return msWMSException(map, nVersion, NULL, wms_exception_format);
 
-      msOWSRequestLayersEnabled(map, "M", "GetCapabilities", ows_request); 
-      if (ows_request->numlayers == 0)
-      {
-          msSetError(MS_WMSERR, "WMS request not enabled. Check wms/ows_enable_request settings.", "msWMSGetCapabilities()");
-          return msWMSException(map, nVersion, NULL, wms_exception_format);
-      }
-      return msWMSGetCapabilities(map, nVersion, req, ows_request, updatesequence, wms_exception_format);
-  }
-  else if (request && (strcasecmp(request, "context") == 0 ||
-                       strcasecmp(request, "GetContext") == 0) )
-  {
-      /* Return a context document with all layers in this mapfile
-       * This is not a standard WMS request.
-       * __TODO__ The real implementation should actually return only context
-       * info for selected layers in the LAYERS parameter.
-       */
-      const char *getcontext_enabled;
-      getcontext_enabled = msOWSLookupMetadata(&(map->web.metadata),
-                                               "MO", "getcontext_enabled");
-
-      if (nVersion != OWS_VERSION_NOTSET)
-      {
-          /* VERSION, if specified, is Map Context version, not WMS version */
-          /* Pass it via wms_context_version metadata */
-          char szVersion[OWS_VERSION_MAXLEN];
-          msInsertHashTable(&(map->web.metadata), "wms_context_version",
-                            msOWSGetVersionString(nVersion, szVersion));
-      }
-      /* Now set version to 1.1.1 for error handling purposes */
-      nVersion = OWS_1_1_1;
+    msOWSRequestLayersEnabled(map, "M", "GetCapabilities", ows_request);
 
-      if (getcontext_enabled==NULL || atoi(getcontext_enabled) == 0)
-      {
-        msSetError(MS_WMSERR, "GetContext not enabled on this server.",
-                   "msWMSDispatch()");
-        return msWMSException(map, nVersion, NULL, wms_exception_format);
-      }
+    enable_request = msOWSLookupMetadata(&map->web.metadata, "OM", "enable_request");
+    globally_enabled = msOWSParseRequestMetadata(enable_request, "GetCapabilities", &disabled);
 
-      if ((status = msOWSMakeAllLayersUnique(map)) != MS_SUCCESS)
-        return msWMSException(map, nVersion, NULL, wms_exception_format);
+    if (ows_request->numlayers == 0 && !globally_enabled) {
+      msSetError(MS_WMSERR, "WMS request not enabled. Check wms/ows_enable_request settings.", "msWMSGetCapabilities()");
+      return msWMSException(map, nVersion, NULL, wms_exception_format);
+    }
+    return msWMSGetCapabilities(map, nVersion, req, ows_request, updatesequence, wms_exception_format, language);
+  } else if (request && (strcasecmp(request, "context") == 0 ||
+                         strcasecmp(request, "GetContext") == 0) ) {
+    /* Return a context document with all layers in this mapfile
+     * This is not a standard WMS request.
+     * __TODO__ The real implementation should actually return only context
+     * info for selected layers in the LAYERS parameter.
+     */
+    const char *getcontext_enabled;
+    getcontext_enabled = msOWSLookupMetadata(&(map->web.metadata),
+                         "MO", "getcontext_enabled");
+
+    if (nVersion != OWS_VERSION_NOTSET) {
+      /* VERSION, if specified, is Map Context version, not WMS version */
+      /* Pass it via wms_context_version metadata */
+      char szVersion[OWS_VERSION_MAXLEN];
+      msInsertHashTable(&(map->web.metadata), "wms_context_version",
+                        msOWSGetVersionString(nVersion, szVersion));
+    }
+    /* Now set version to 1.1.1 for error handling purposes */
+    nVersion = OWS_1_1_1;
 
-      if (encoding)
-          msIO_printf("Content-type: text/xml; charset=%s%c%c", encoding,10,10);
-      else
-          msIO_printf("Content-type: text/xml%c%c",10,10);
+    if (getcontext_enabled==NULL || atoi(getcontext_enabled) == 0) {
+      msSetError(MS_WMSERR, "GetContext not enabled on this server.",
+                 "msWMSDispatch()");
+      return msWMSException(map, nVersion, NULL, wms_exception_format);
+    }
 
-      if ( msWriteMapContext(map, stdout) != MS_SUCCESS )
-        return msWMSException(map, nVersion, NULL, wms_exception_format);
-      /* Request completed */
-      return MS_SUCCESS;
-  }
-  else if (request && strcasecmp(request, "GetMap") == 0 &&
-           format && strcasecmp(format,  "image/txt") == 0)
-  {
-      /* Until someone adds full support for ASCII graphics this should do. ;) */
-      if (encoding)
-          msIO_printf("Content-type: text/plain; charset=%s%c%c", encoding,10,10);
-      else
-          msIO_printf("Content-type: text/plain%c%c",10,10);
-      msIO_printf(".\n               ,,ggddY\"\"\"Ybbgg,,\n          ,agd888b,_ "
-             "\"Y8, ___'\"\"Ybga,\n       ,gdP\"\"88888888baa,.\"\"8b    \""
-             "888g,\n     ,dP\"     ]888888888P'  \"Y     '888Yb,\n   ,dP\""
-             "      ,88888888P\"  db,       \"8P\"\"Yb,\n  ,8\"       ,8888"
-             "88888b, d8888a           \"8,\n ,8'        d88888888888,88P\""
-             "' a,          '8,\n,8'         88888888888888PP\"  \"\"      "
-             "     '8,\nd'          I88888888888P\"                   'b\n8"
-             "           '8\"88P\"\"Y8P'                      8\n8         "
-             "   Y 8[  _ \"                        8\n8              \"Y8d8"
-             "b  \"Y a                   8\n8                 '\"\"8d,   __"
-             "                 8\nY,                    '\"8bd888b,        "
-             "     ,P\n'8,                     ,d8888888baaa       ,8'\n '8"
-             ",                    888888888888'      ,8'\n  '8a           "
-             "        \"8888888888I      a8'\n   'Yba                  'Y88"
-             "88888P'    adP'\n     \"Yba                 '888888P'   adY\""
-             "\n       '\"Yba,             d8888P\" ,adP\"' \n          '\""
-             "Y8baa,      ,d888P,ad8P\"' \n               ''\"\"YYba8888P\""
-             "\"''\n");
-      return MS_SUCCESS;
+    if ((status = msOWSMakeAllLayersUnique(map)) != MS_SUCCESS)
+      return msWMSException(map, nVersion, NULL, wms_exception_format);
+
+    if (encoding)
+      msIO_setHeader("Content-Type","text/xml; charset=%s", encoding);
+    else
+      msIO_setHeader("Content-Type","text/xml");
+    msIO_sendHeaders();
+
+    if ( msWriteMapContext(map, stdout) != MS_SUCCESS )
+      return msWMSException(map, nVersion, NULL, wms_exception_format);
+    /* Request completed */
+    return MS_SUCCESS;
+  } else if (request && strcasecmp(request, "GetMap") == 0 &&
+             format && strcasecmp(format,  "image/txt") == 0) {
+    /* Until someone adds full support for ASCII graphics this should do. ;) */
+    if (encoding)
+      msIO_setHeader("Content-Type","text/plain; charset=%s", encoding);
+    else
+      msIO_setHeader("Content-Type","text/plain");
+    msIO_sendHeaders();
+    msIO_printf(".\n               ,,ggddY\"\"\"Ybbgg,,\n          ,agd888b,_ "
+                "\"Y8, ___'\"\"Ybga,\n       ,gdP\"\"88888888baa,.\"\"8b    \""
+                "888g,\n     ,dP\"     ]888888888P'  \"Y     '888Yb,\n   ,dP\""
+                "      ,88888888P\"  db,       \"8P\"\"Yb,\n  ,8\"       ,8888"
+                "88888b, d8888a           \"8,\n ,8'        d88888888888,88P\""
+                "' a,          '8,\n,8'         88888888888888PP\"  \"\"      "
+                "     '8,\nd'          I88888888888P\"                   'b\n8"
+                "           '8\"88P\"\"Y8P'                      8\n8         "
+                "   Y 8[  _ \"                        8\n8              \"Y8d8"
+                "b  \"Y a                   8\n8                 '\"\"8d,   __"
+                "                 8\nY,                    '\"8bd888b,        "
+                "     ,P\n'8,                     ,d8888888baaa       ,8'\n '8"
+                ",                    888888888888'      ,8'\n  '8a           "
+                "        \"8888888888I      a8'\n   'Yba                  'Y88"
+                "88888P'    adP'\n     \"Yba                 '888888P'   adY\""
+                "\n       '\"Yba,             d8888P\" ,adP\"' \n          '\""
+                "Y8baa,      ,d888P,ad8P\"' \n               ''\"\"YYba8888P\""
+                "\"''\n");
+    return MS_SUCCESS;
   }
 
   /* If SERVICE, VERSION and REQUEST not included than this isn't a WMS req*/
   if (service == NULL && nVersion == OWS_VERSION_NOTSET && request==NULL)
-      return MS_DONE;  /* Not a WMS request */
+    return MS_DONE;  /* Not a WMS request */
 
   /* VERSION *and* REQUEST required by both getMap and getFeatureInfo */
-  if (nVersion == OWS_VERSION_NOTSET)
-  {
-      msSetError(MS_WMSERR,
-                 "Incomplete WMS request: VERSION parameter missing",
-                 "msWMSDispatch()");
-      return msWMSException(map, OWS_VERSION_NOTSET, NULL, wms_exception_format);
+  if (nVersion == OWS_VERSION_NOTSET) {
+    msSetError(MS_WMSERR,
+               "Incomplete WMS request: VERSION parameter missing",
+               "msWMSDispatch()");
+    return msWMSException(map, OWS_VERSION_NOTSET, NULL, wms_exception_format);
   }
 
-   /*check if the version is one of the supported vcersions*/
+  /*check if the version is one of the supported vcersions*/
   if (nVersion != OWS_1_0_0 &&  nVersion != OWS_1_0_6 &&
-         nVersion != OWS_1_0_7 && nVersion != OWS_1_1_0 &&
-         nVersion != OWS_1_1_1 && nVersion != OWS_1_3_0)
-  {
-      msSetError(MS_WMSERR,
-                   "Invalid WMS version: VERSION %s is not supported. Supported versions are 1.0.0, 1.0.6, 1.0.7, 1.1.0, 1.1.1, 1.3.0",
-                   "msWMSDispatch()", version);
-      return msWMSException(map, OWS_VERSION_NOTSET, NULL, wms_exception_format);
+      nVersion != OWS_1_0_7 && nVersion != OWS_1_1_0 &&
+      nVersion != OWS_1_1_1 && nVersion != OWS_1_3_0) {
+    msSetError(MS_WMSERR,
+               "Invalid WMS version: VERSION %s is not supported. Supported versions are 1.0.0, 1.0.6, 1.0.7, 1.1.0, 1.1.1, 1.3.0",
+               "msWMSDispatch()", version);
+    return msWMSException(map, OWS_VERSION_NOTSET, NULL, wms_exception_format);
   }
 
-  if (request==NULL)
-  {
-      msSetError(MS_WMSERR,
-                 "Incomplete WMS request: REQUEST parameter missing",
-                 "msWMSDispatch()");
-      return msWMSException(map, nVersion, NULL, wms_exception_format);
+  if (request==NULL) {
+    msSetError(MS_WMSERR,
+               "Incomplete WMS request: REQUEST parameter missing",
+               "msWMSDispatch()");
+    return msWMSException(map, nVersion, NULL, wms_exception_format);
   }
 
   /* hack !? The function can return MS_DONE ... be sure it's a wms request
@@ -4095,31 +4922,29 @@ int msWMSDispatch(mapObj *map, cgiRequestObj *req, owsRequestObj *ows_request, i
        (strcasecmp(request, "GetLegendGraphic") == 0) ||
        (strcasecmp(request, "GetSchemaExtension") == 0) ||
        (strcasecmp(request, "map") == 0 || strcasecmp(request, "GetMap") == 0) ||
-       (strcasecmp(request, "feature_info") == 0 || strcasecmp(request, "GetFeatureInfo") == 0) || 
-       (strcasecmp(request, "DescribeLayer") == 0) )
-  {
-      char request_tmp[32];
-      if (strcasecmp(request, "map") == 0)
-          strlcpy(request_tmp, "GetMap", sizeof(request_tmp));
-      else if (strcasecmp(request, "feature_info") == 0)
-          strlcpy(request_tmp, "GetFeatureInfo", sizeof(request_tmp));
-      else
-          strlcpy(request_tmp, request, sizeof(request_tmp));
+       (strcasecmp(request, "feature_info") == 0 || strcasecmp(request, "GetFeatureInfo") == 0) ||
+       (strcasecmp(request, "DescribeLayer") == 0) ) {
+    char request_tmp[32];
+    if (strcasecmp(request, "map") == 0)
+      strlcpy(request_tmp, "GetMap", sizeof(request_tmp));
+    else if (strcasecmp(request, "feature_info") == 0)
+      strlcpy(request_tmp, "GetFeatureInfo", sizeof(request_tmp));
+    else
+      strlcpy(request_tmp, request, sizeof(request_tmp));
 
-      msOWSRequestLayersEnabled(map, "M", request_tmp, ows_request); 
-      if (ows_request->numlayers == 0)
-      {
-          msSetError(MS_WMSERR, "WMS request not enabled. Check wms/ows_enable_request settings.", "msWMSDispatch()");
-          return msWMSException(map, nVersion, NULL, wms_exception_format);
-      }
+    msOWSRequestLayersEnabled(map, "M", request_tmp, ows_request);
+    if (ows_request->numlayers == 0) {
+      msSetError(MS_WMSERR, "WMS request not enabled. Check wms/ows_enable_request settings.", "msWMSDispatch()");
+      return msWMSException(map, nVersion, NULL, wms_exception_format);
+    }
   }
 
   if ((status = msOWSMakeAllLayersUnique(map)) != MS_SUCCESS)
     return msWMSException(map, nVersion, NULL, wms_exception_format);
 
   if (strcasecmp(request, "GetLegendGraphic") == 0)
-    return msWMSGetLegendGraphic(map, nVersion, req->ParamNames, req->ParamValues, req->NumParams,
-                                 wms_exception_format, ows_request);
+    return msWMSLegendGraphic(map, nVersion, req->ParamNames, req->ParamValues, req->NumParams,
+                              wms_exception_format, ows_request);
 
   if (strcasecmp(request, "GetStyles") == 0)
     return msWMSGetStyles(map, nVersion, req->ParamNames, req->ParamValues, req->NumParams,
@@ -4130,32 +4955,38 @@ int msWMSDispatch(mapObj *map, cgiRequestObj *req, owsRequestObj *ows_request, i
 
   /* getMap parameters are used by both getMap and getFeatureInfo */
   if (strcasecmp(request, "map") == 0 || strcasecmp(request, "GetMap") == 0 ||
-      strcasecmp(request, "feature_info") == 0 || strcasecmp(request, "GetFeatureInfo") == 0 || strcasecmp(request, "DescribeLayer") == 0)
-  {
-      
-      status = msWMSLoadGetMapParams(map, nVersion, req->ParamNames, req->ParamValues, req->NumParams, 
-                                     wms_exception_format, request, ows_request);
-      if (status != MS_SUCCESS) return status;
+      strcasecmp(request, "feature_info") == 0 || strcasecmp(request, "GetFeatureInfo") == 0 || strcasecmp(request, "DescribeLayer") == 0) {
+
+    status = msWMSLoadGetMapParams(map, nVersion, req->ParamNames, req->ParamValues, req->NumParams,
+                                   wms_exception_format, request, ows_request);
+    if (status != MS_SUCCESS) return status;
   }
 
+  /* This function owns validated_language, so remember to free it later*/
+  validated_language = msOWSGetLanguageFromList(map, "MO", language);
+  if (validated_language != NULL) {
+    for(i=0; i<map->numlayers; i++) {
+      layerObj *layer = GET_LAYER(map, i);
+      if(layer->data) layer->data = msCaseReplaceSubstring(layer->data, "%language%", validated_language);
+      if(layer->connection) layer->connection = msCaseReplaceSubstring(layer->connection, "%language%", validated_language);
+    }
+  }
+  msFree(validated_language);
 
   if (strcasecmp(request, "map") == 0 || strcasecmp(request, "GetMap") == 0)
-     return msWMSGetMap(map, nVersion, req->ParamNames, req->ParamValues, req->NumParams, wms_exception_format, ows_request);
+    return msWMSGetMap(map, nVersion, req->ParamNames, req->ParamValues, req->NumParams, wms_exception_format, ows_request);
   else if (strcasecmp(request, "feature_info") == 0 || strcasecmp(request, "GetFeatureInfo") == 0)
     return msWMSFeatureInfo(map, nVersion, req->ParamNames, req->ParamValues, req->NumParams, wms_exception_format, ows_request);
-  else if (strcasecmp(request, "DescribeLayer") == 0)
-  {
-      return msWMSDescribeLayer(map, nVersion, req->ParamNames, req->ParamValues, req->NumParams,  
-                                wms_exception_format);
+  else if (strcasecmp(request, "DescribeLayer") == 0) {
+    return msWMSDescribeLayer(map, nVersion, req->ParamNames, req->ParamValues, req->NumParams,
+                              wms_exception_format);
   }
 
   /* Hummmm... incomplete or unsupported WMS request */
-  if (service != NULL && strcasecmp(service, "WMS") == 0)
-  {
-      msSetError(MS_WMSERR, "Incomplete or unsupported WMS request", "msWMSDispatch()");
-      return msWMSException(map, nVersion, NULL, wms_exception_format);
-  }
-  else
+  if (service != NULL && strcasecmp(service, "WMS") == 0) {
+    msSetError(MS_WMSERR, "Incomplete or unsupported WMS request", "msWMSDispatch()");
+    return msWMSException(map, nVersion, NULL, wms_exception_format);
+  } else
     return MS_DONE;  /* Not a WMS request */
 #else
   msSetError(MS_WMSERR, "WMS server support is not available.", "msWMSDispatch()");
diff --git a/mapwmslayer.c b/mapwmslayer.c
index 499901f..5a98671 100644
--- a/mapwmslayer.c
+++ b/mapwmslayer.c
@@ -14,16 +14,16 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in 
+ *
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  * DEALINGS IN THE SOFTWARE.
  *****************************************************************************/
 
@@ -49,14 +49,14 @@ void CleanVSIDir( const char *pszDir );
  *                          msInitWmsParamsObj()
  *
  **********************************************************************/
-int msInitWmsParamsObj(wmsParamsObj *wmsparams) 
+int msInitWmsParamsObj(wmsParamsObj *wmsparams)
 {
-    wmsparams->onlineresource = NULL;
-    wmsparams->params = msCreateHashTable();
-    wmsparams->numparams=0;
-    wmsparams->httpcookiedata = NULL;
+  wmsparams->onlineresource = NULL;
+  wmsparams->params = msCreateHashTable();
+  wmsparams->numparams=0;
+  wmsparams->httpcookiedata = NULL;
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 
 /**********************************************************************
@@ -64,17 +64,17 @@ int msInitWmsParamsObj(wmsParamsObj *wmsparams)
  *
  * Frees the contents of the object, but not the object itself.
  **********************************************************************/
-void msFreeWmsParamsObj(wmsParamsObj *wmsparams) 
+void msFreeWmsParamsObj(wmsParamsObj *wmsparams)
 {
-    msFree(wmsparams->onlineresource);
-    wmsparams->onlineresource = NULL;
+  msFree(wmsparams->onlineresource);
+  wmsparams->onlineresource = NULL;
 
-    msFreeHashTable(wmsparams->params);
-    wmsparams->params = NULL;
+  msFreeHashTable(wmsparams->params);
+  wmsparams->params = NULL;
 
-    msFree(wmsparams->httpcookiedata);
+  msFree(wmsparams->httpcookiedata);
 
-    wmsparams->numparams=0;
+  wmsparams->numparams=0;
 }
 
 /**********************************************************************
@@ -83,50 +83,41 @@ void msFreeWmsParamsObj(wmsParamsObj *wmsparams)
  **********************************************************************/
 
 #ifdef USE_WMS_LYR
-static int msSetWMSParamString(wmsParamsObj *psWMSParams, 
+static int msSetWMSParamString(wmsParamsObj *psWMSParams,
                                const char *name, const char * value,
-                               int urlencode) 
+                               int urlencode)
 {
-    if (urlencode)
-    {
-        char *pszTmp;
-
-        /*
-         *  Special case handling for characters the WMS specification
-         *  says should not be encoded, when they occur in certain
-         *  parameters.
-         *  
-         *  TODO: WMS 1.3 removes SRS and FORMAT from the set of 
-         *        exceptional cases.
-         */
-        if( strcmp(name,"LAYERS") == 0 ||
-            strcmp(name,"STYLES") == 0 ||
-            strcmp(name,"BBOX") == 0 )
-        {
-            pszTmp = msEncodeUrlExcept(value,',');
-        }
-        else if ( strcmp(name,"SRS") == 0 )
-        {
-            pszTmp = msEncodeUrlExcept(value,':');
-        }
-        else if ( strcmp(name,"FORMAT") == 0 )
-        {
-            pszTmp = msEncodeUrlExcept(value,'/');
-        }
-        else {
-            pszTmp = msEncodeUrl(value);
-        }
-
-        msInsertHashTable(psWMSParams->params, name, pszTmp);
-        msFree(pszTmp);
-    }
-    else
-    {
-        msInsertHashTable(psWMSParams->params, name, value);
-    }
-    psWMSParams->numparams++;
-
-    return MS_SUCCESS;
+  if (urlencode) {
+    char *pszTmp;
+
+    /*
+     *  Special case handling for characters the WMS specification
+     *  says should not be encoded, when they occur in certain
+     *  parameters.
+     *
+     *  TODO: WMS 1.3 removes SRS and FORMAT from the set of
+     *        exceptional cases.
+     */
+    if( strcmp(name,"LAYERS") == 0 ||
+        strcmp(name,"STYLES") == 0 ||
+        strcmp(name,"BBOX") == 0 ) {
+      pszTmp = msEncodeUrlExcept(value,',');
+    } else if ( strcmp(name,"SRS") == 0 ) {
+      pszTmp = msEncodeUrlExcept(value,':');
+    } else if ( strcmp(name,"FORMAT") == 0 ) {
+      pszTmp = msEncodeUrlExcept(value,'/');
+    } else {
+      pszTmp = msEncodeUrl(value);
+    }
+
+    msInsertHashTable(psWMSParams->params, name, pszTmp);
+    msFree(pszTmp);
+  } else {
+    msInsertHashTable(psWMSParams->params, name, value);
+  }
+  psWMSParams->numparams++;
+
+  return MS_SUCCESS;
 }
 #endif /* def USE_WMS_LYR */
 
@@ -136,16 +127,16 @@ static int msSetWMSParamString(wmsParamsObj *psWMSParams,
  **********************************************************************/
 
 #ifdef USE_WMS_LYR
-static int msSetWMSParamInt(wmsParamsObj *wmsparams, 
-                            const char *name, int value) 
+static int msSetWMSParamInt(wmsParamsObj *wmsparams,
+                            const char *name, int value)
 {
-    char szBuf[100];
+  char szBuf[100];
 
-    snprintf(szBuf, sizeof(szBuf), "%d", value);
-    msInsertHashTable(wmsparams->params, name, szBuf);
-    wmsparams->numparams++;
+  snprintf(szBuf, sizeof(szBuf), "%d", value);
+  msInsertHashTable(wmsparams->params, name, szBuf);
+  wmsparams->numparams++;
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 }
 #endif /* def USE_WMS_LYR */
 
@@ -153,60 +144,57 @@ static int msSetWMSParamInt(wmsParamsObj *wmsparams,
  *                          msBuildWMSParamsUrl()
  *
  **********************************************************************/
-static char *msBuildURLFromWMSParams(wmsParamsObj *wmsparams) 
+static char *msBuildURLFromWMSParams(wmsParamsObj *wmsparams)
 {
-    const char *key, *value;
-    size_t bufferSize = 0;
-    int nLen;
-    char *pszURL;
-
-    /* Compute size required for URL buffer 
-     */
-    nLen = strlen(wmsparams->onlineresource) + 3;
-
-    key = msFirstKeyFromHashTable(wmsparams->params);
-    while (key != NULL)
-    {
-        value = msLookupHashTable(wmsparams->params, key);
-        nLen += strlen(key) + strlen(value) + 2;
-
-        key = msNextKeyFromHashTable(wmsparams->params, key);
-    }
-
-    bufferSize = nLen+1;
-    pszURL = (char*)msSmallMalloc(bufferSize);
-
-    /* Start with the onlineresource value and append trailing '?' or '&' 
-     * if missing.
-     */
-    strcpy(pszURL, wmsparams->onlineresource);
-    if (strchr(pszURL, '?') == NULL)
-        strcat(pszURL, "?");
-    else
-    {
-        char *c;
-        c = pszURL+strlen(pszURL)-1;
-        if (*c != '?' && *c != '&')
-            strcpy(c+1, "&");
-    }
-
-    /* Now add all the parameters 
-     */
-    nLen = strlen(pszURL);
-    key = msFirstKeyFromHashTable(wmsparams->params);
-    while (key != NULL)
-    {
-        value = msLookupHashTable(wmsparams->params, key);
-        snprintf(pszURL+nLen, bufferSize-nLen, "%s=%s&", key, value);
-        nLen += strlen(key) + strlen(value) + 2;
-        key = msNextKeyFromHashTable(wmsparams->params, key);
-    }
-
-    /* Get rid of trailing '&'*/
-    pszURL[nLen-1] = '\0';
-
-
-    return pszURL;
+  const char *key, *value;
+  size_t bufferSize = 0;
+  int nLen;
+  char *pszURL;
+
+  /* Compute size required for URL buffer
+   */
+  nLen = strlen(wmsparams->onlineresource) + 3;
+
+  key = msFirstKeyFromHashTable(wmsparams->params);
+  while (key != NULL) {
+    value = msLookupHashTable(wmsparams->params, key);
+    nLen += strlen(key) + strlen(value) + 2;
+
+    key = msNextKeyFromHashTable(wmsparams->params, key);
+  }
+
+  bufferSize = nLen+1;
+  pszURL = (char*)msSmallMalloc(bufferSize);
+
+  /* Start with the onlineresource value and append trailing '?' or '&'
+   * if missing.
+   */
+  strcpy(pszURL, wmsparams->onlineresource);
+  if (strchr(pszURL, '?') == NULL)
+    strcat(pszURL, "?");
+  else {
+    char *c;
+    c = pszURL+strlen(pszURL)-1;
+    if (*c != '?' && *c != '&')
+      strcpy(c+1, "&");
+  }
+
+  /* Now add all the parameters
+   */
+  nLen = strlen(pszURL);
+  key = msFirstKeyFromHashTable(wmsparams->params);
+  while (key != NULL) {
+    value = msLookupHashTable(wmsparams->params, key);
+    snprintf(pszURL+nLen, bufferSize-nLen, "%s=%s&", key, value);
+    nLen += strlen(key) + strlen(value) + 2;
+    key = msNextKeyFromHashTable(wmsparams->params, key);
+  }
+
+  /* Get rid of trailing '&'*/
+  pszURL[nLen-1] = '\0';
+
+
+  return pszURL;
 }
 
 
@@ -216,7 +204,7 @@ static char *msBuildURLFromWMSParams(wmsParamsObj *wmsparams)
 /**********************************************************************
  *                          msBuildWMSLayerURLBase()
  *
- * Build the base of a GetMap or GetFeatureInfo URL using metadata.  
+ * Build the base of a GetMap or GetFeatureInfo URL using metadata.
  * The parameters to set are:
  *   VERSION
  *   LAYERS
@@ -225,222 +213,189 @@ static char *msBuildURLFromWMSParams(wmsParamsObj *wmsparams)
  *   STYLES
  *   QUERY_LAYERS (for queriable layers only)
  *
- * Returns a reference to a newly allocated string that should be freed 
+ * Returns a reference to a newly allocated string that should be freed
  * by the caller.
  **********************************************************************/
 static int msBuildWMSLayerURLBase(mapObj *map, layerObj *lp,
-                                  wmsParamsObj *psWMSParams) 
+                                  wmsParamsObj *psWMSParams)
 {
-    const char *pszOnlineResource, *pszVersion, *pszName, *pszFormat;
-    const char *pszFormatList, *pszStyle, *pszStyleList, *pszTime;
-    const char *pszBgColor, *pszTransparent;
-    const char *pszSLD=NULL, *pszStyleSLDBody=NULL, *pszVersionKeyword=NULL;
-    const char *pszSLDBody=NULL, *pszSLDURL = NULL;
-    char *pszSLDGenerated = NULL;
-
-    /* If lp->connection is not set then use wms_onlineresource metadata */
-    pszOnlineResource = lp->connection;
-    if (pszOnlineResource == NULL) 
-      pszOnlineResource = msOWSLookupMetadata(&(lp->metadata), 
-                                              "MO", "onlineresource");
-
-    pszVersion =        msOWSLookupMetadata(&(lp->metadata), "MO", "server_version");
-    pszName =           msOWSLookupMetadata(&(lp->metadata), "MO", "name");
-    pszFormat =         msOWSLookupMetadata(&(lp->metadata), "MO", "format");
-    pszFormatList =     msOWSLookupMetadata(&(lp->metadata), "MO", "formatlist");
-    pszStyle =          msOWSLookupMetadata(&(lp->metadata), "MO", "style");
-    pszStyleList =      msOWSLookupMetadata(&(lp->metadata), "MO", "stylelist");
-    pszTime =           msOWSLookupMetadata(&(lp->metadata), "MO", "time");
-    pszSLDBody =        msOWSLookupMetadata(&(lp->metadata), "MO", "sld_body");
-    pszSLDURL =         msOWSLookupMetadata(&(lp->metadata), "MO", "sld_url");
-    pszBgColor =        msOWSLookupMetadata(&(lp->metadata), "MO", "bgcolor");
-    pszTransparent =    msOWSLookupMetadata(&(lp->metadata), "MO", "transparent");
-
-    if (pszOnlineResource==NULL || pszVersion==NULL || pszName==NULL)
-    {
-        msSetError(MS_WMSCONNERR, 
-                   "One of wms_onlineresource, wms_server_version, wms_name "
-                   "metadata is missing in layer %s.  "
-                   "Please either provide a valid CONNECTION URL, or provide "
-                   "those values in the layer's metadata.\n", 
-                   "msBuildWMSLayerURLBase()", lp->name);
-        return MS_FAILURE;
-    }
-
-    psWMSParams->onlineresource = msStrdup(pszOnlineResource);
-
-    if (strncmp(pszVersion, "1.0.7", 5) < 0) 
-        pszVersionKeyword = "WMTVER";
-    else
-        pszVersionKeyword = "VERSION";
-
-    msSetWMSParamString(psWMSParams, pszVersionKeyword, pszVersion, MS_FALSE);
-    msSetWMSParamString(psWMSParams, "SERVICE", "WMS",     MS_FALSE);
-    msSetWMSParamString(psWMSParams, "LAYERS",  pszName,   MS_TRUE);
-
-    if (pszFormat==NULL && pszFormatList==NULL)
-    {
-        msSetError(MS_WMSCONNERR, 
-                   "At least wms_format or wms_formatlist is required for "
-                   "layer %s.  "
-                   "Please either provide a valid CONNECTION URL, or provide "
-                   "those values in the layer's metadata.\n", 
-                   "msBuildWMSLayerURLBase()", lp->name);
-        return MS_FAILURE;
-    }
-
-    if (pszFormat != NULL)
-    {
-        msSetWMSParamString(psWMSParams, "FORMAT",  pszFormat, MS_TRUE);
-    }
-    else
-    {
-        /* Look for the first format in list that matches */
-        char **papszTok;
-        int i, n;
-        papszTok = msStringSplit(pszFormatList, ',', &n);
-
-        for(i=0; pszFormat==NULL && i<n; i++)
-        {
-            if (0 
-#ifdef USE_GD_GIF
-                || strcasecmp(papszTok[i], "GIF")
-                || strcasecmp(papszTok[i], "image/gif")
+  const char *pszOnlineResource, *pszVersion, *pszName, *pszFormat;
+  const char *pszFormatList, *pszStyle, /* *pszStyleList,*/ *pszTime;
+  const char *pszBgColor, *pszTransparent;
+  const char *pszSLD=NULL, *pszStyleSLDBody=NULL, *pszVersionKeyword=NULL;
+  const char *pszSLDBody=NULL, *pszSLDURL = NULL;
+  char *pszSLDGenerated = NULL;
+
+  /* If lp->connection is not set then use wms_onlineresource metadata */
+  pszOnlineResource = lp->connection;
+  if (pszOnlineResource == NULL)
+    pszOnlineResource = msOWSLookupMetadata(&(lp->metadata),
+                                            "MO", "onlineresource");
+
+  pszVersion =        msOWSLookupMetadata(&(lp->metadata), "MO", "server_version");
+  pszName =           msOWSLookupMetadata(&(lp->metadata), "MO", "name");
+  pszFormat =         msOWSLookupMetadata(&(lp->metadata), "MO", "format");
+  pszFormatList =     msOWSLookupMetadata(&(lp->metadata), "MO", "formatlist");
+  pszStyle =          msOWSLookupMetadata(&(lp->metadata), "MO", "style");
+  /*pszStyleList =      msOWSLookupMetadata(&(lp->metadata), "MO", "stylelist");*/
+  pszTime =           msOWSLookupMetadata(&(lp->metadata), "MO", "time");
+  pszSLDBody =        msOWSLookupMetadata(&(lp->metadata), "MO", "sld_body");
+  pszSLDURL =         msOWSLookupMetadata(&(lp->metadata), "MO", "sld_url");
+  pszBgColor =        msOWSLookupMetadata(&(lp->metadata), "MO", "bgcolor");
+  pszTransparent =    msOWSLookupMetadata(&(lp->metadata), "MO", "transparent");
+
+  if (pszOnlineResource==NULL || pszVersion==NULL || pszName==NULL) {
+    msSetError(MS_WMSCONNERR,
+               "One of wms_onlineresource, wms_server_version, wms_name "
+               "metadata is missing in layer %s.  "
+               "Please either provide a valid CONNECTION URL, or provide "
+               "those values in the layer's metadata.\n",
+               "msBuildWMSLayerURLBase()", lp->name);
+    return MS_FAILURE;
+  }
+
+  psWMSParams->onlineresource = msStrdup(pszOnlineResource);
+
+  if (strncmp(pszVersion, "1.0.7", 5) < 0)
+    pszVersionKeyword = "WMTVER";
+  else
+    pszVersionKeyword = "VERSION";
+
+  msSetWMSParamString(psWMSParams, pszVersionKeyword, pszVersion, MS_FALSE);
+  msSetWMSParamString(psWMSParams, "SERVICE", "WMS",     MS_FALSE);
+  msSetWMSParamString(psWMSParams, "LAYERS",  pszName,   MS_TRUE);
+
+  if (pszFormat==NULL && pszFormatList==NULL) {
+    msSetError(MS_WMSCONNERR,
+               "At least wms_format or wms_formatlist is required for "
+               "layer %s.  "
+               "Please either provide a valid CONNECTION URL, or provide "
+               "those values in the layer's metadata.\n",
+               "msBuildWMSLayerURLBase()", lp->name);
+    return MS_FAILURE;
+  }
+
+  if (pszFormat != NULL) {
+    msSetWMSParamString(psWMSParams, "FORMAT",  pszFormat, MS_TRUE);
+  } else {
+    /* Look for the first format in list that matches */
+    char **papszTok;
+    int i, n;
+    papszTok = msStringSplit(pszFormatList, ',', &n);
+
+    for(i=0; pszFormat==NULL && i<n; i++) {
+      if (0
+#if defined USE_GD_PNG || defined USE_PNG
+          || strcasecmp(papszTok[i], "PNG")
+          || strcasecmp(papszTok[i], "image/png")
 #endif
-#ifdef USE_GD_PNG
-                || strcasecmp(papszTok[i], "PNG")
-                || strcasecmp(papszTok[i], "image/png")
+#if defined USE_GD_JPEG || defined USE_JPEG
+          || strcasecmp(papszTok[i], "JPEG")
+          || strcasecmp(papszTok[i], "image/jpeg")
 #endif
-#ifdef USE_GD_JPEG
-                || strcasecmp(papszTok[i], "JPEG")
-                || strcasecmp(papszTok[i], "image/jpeg")
-#endif
-#ifdef USE_GD_WBMP
-                || strcasecmp(papszTok[i], "WBMP")
-                || strcasecmp(papszTok[i], "image/vnd.wap.wbmp")
+#ifdef USE_GD_GIF
+          || strcasecmp(papszTok[i], "GIF")
+          || strcasecmp(papszTok[i], "image/gif")
 #endif
-                )
-            {
-                pszFormat = papszTok[i];
-            }
-        }
-
-        if (pszFormat)
-        {
-            msSetWMSParamString(psWMSParams, "FORMAT",  pszFormat, MS_TRUE);
-            msFreeCharArray(papszTok, n);
-        }
-        else
-        {
-            msSetError(MS_WMSCONNERR, 
-                       "Could not find a format that matches supported input "
-                       "formats in wms_formatlist metdata in layer %s.  "
-                       "Please either provide a valid CONNECTION URL, or "
-                       "provide the required layer metadata.\n", 
-                       "msBuildWMSLayerURLBase()", lp->name);
-            msFreeCharArray(papszTok, n);
-            return MS_FAILURE;
-        }
-    }
-
-    if (pszStyle==NULL)
-    {
-        /* When no style is selected, use "" which is a valid default. */
+         ) {
+        pszFormat = papszTok[i];
+      }
+    }
+
+    if (pszFormat) {
+      msSetWMSParamString(psWMSParams, "FORMAT",  pszFormat, MS_TRUE);
+      msFreeCharArray(papszTok, n);
+    } else {
+      msSetError(MS_WMSCONNERR,
+                 "Could not find a format that matches supported input "
+                 "formats in wms_formatlist metdata in layer %s.  "
+                 "Please either provide a valid CONNECTION URL, or "
+                 "provide the required layer metadata.\n",
+                 "msBuildWMSLayerURLBase()", lp->name);
+      msFreeCharArray(papszTok, n);
+      return MS_FAILURE;
+    }
+  }
+
+  if (pszStyle==NULL) {
+    /* When no style is selected, use "" which is a valid default. */
+    pszStyle = "";
+  } else {
+    /* Was a wms_style_..._sld URL provided? */
+    char szBuf[100];
+    snprintf(szBuf, sizeof(szBuf), "style_%.80s_sld", pszStyle);
+    pszSLD = msOWSLookupMetadata(&(lp->metadata), "MO", szBuf);
+    snprintf(szBuf, sizeof(szBuf), "style_%.80s_sld_body", pszStyle);
+    pszStyleSLDBody = msOWSLookupMetadata(&(lp->metadata), "MO", szBuf);
+
+    if (pszSLD || pszStyleSLDBody) {
+      /* SLD URL is set.  If this defn. came from a map context then */
+      /* the style name may just be an internal name: "Style{%d}" if */
+      /* that's the case then we should not pass this name via the URL */
+      if (strncmp(pszStyle, "Style{", 6) == 0)
         pszStyle = "";
     }
-    else
-    {
-        /* Was a wms_style_..._sld URL provided? */
-        char szBuf[100];
-        snprintf(szBuf, sizeof(szBuf), "style_%.80s_sld", pszStyle);
-        pszSLD = msOWSLookupMetadata(&(lp->metadata), "MO", szBuf);
-        snprintf(szBuf, sizeof(szBuf), "style_%.80s_sld_body", pszStyle);
-        pszStyleSLDBody = msOWSLookupMetadata(&(lp->metadata), "MO", szBuf);
-
-        if (pszSLD || pszStyleSLDBody)
-        {
-            /* SLD URL is set.  If this defn. came from a map context then */
-            /* the style name may just be an internal name: "Style{%d}" if */
-            /* that's the case then we should not pass this name via the URL */
-            if (strncmp(pszStyle, "Style{", 6) == 0)
-                pszStyle = "";
-        }
-    }
-
-    /*  set STYLES no matter what, even if it's empty (i.e. "STYLES=")
-     *  styles is a required param of WMS
-     */
-
-    msSetWMSParamString(psWMSParams, "STYLES", pszStyle, MS_TRUE);
-
-    if (pszSLD != NULL)
-    {
-        /* Only SLD is set */
-        msSetWMSParamString(psWMSParams, "SLD",    pszSLD,   MS_TRUE);
-    }
-    else if (pszStyleSLDBody != NULL)
-    {
-        /* SLDBODY are set */
-        msSetWMSParamString(psWMSParams, "SLD_BODY", pszStyleSLDBody, MS_TRUE);
-    }
-
-    if (msIsLayerQueryable(lp))
-    {
-        msSetWMSParamString(psWMSParams, "QUERY_LAYERS", pszName, MS_TRUE);
-    }
-    if (pszTime && strlen(pszTime) > 0)
-    {
-        msSetWMSParamString(psWMSParams, "TIME",   pszTime,  MS_TRUE);
-    }
-
-    /* if  the metadata wms_sld_body is set to AUTO, we generate
-     * the sld based on classes found in the map file and send
-     * it in the URL. If diffrent from AUTO, we are assuming that
-     * it is a valid sld.
-     */
-    if (pszSLDBody)
-    {
-        if (strcasecmp(pszSLDBody, "AUTO") == 0)
-        {
-            if (pszVersion && strncmp(pszVersion, "1.3.0", 5) == 0)
-              pszSLDGenerated = msSLDGenerateSLD(map, lp->index, "1.1.0");
-            else
-              pszSLDGenerated = msSLDGenerateSLD(map, lp->index, NULL);
-
-            if (pszSLDGenerated)
-            {
-                msSetWMSParamString(psWMSParams, "SLD_BODY", 
-                                    pszSLDGenerated, MS_TRUE);
-                free(pszSLDGenerated);
-            }
-        }
-        else
-        {
-            msSetWMSParamString(psWMSParams, "SLD_BODY", pszSLDBody, MS_TRUE);
-        }
-
-    }
-    
-    if (pszSLDURL)
-    {
-        msSetWMSParamString(psWMSParams, "SLD", pszSLDURL, MS_TRUE);
-    }	
-
-    if (pszBgColor)
-    {
-        msSetWMSParamString(psWMSParams, "BGCOLOR", pszBgColor, MS_TRUE);
-    }
-
-    if (pszTransparent)
-    {
-        msSetWMSParamString(psWMSParams, "TRANSPARENT", pszTransparent, MS_TRUE);
-    }
-    else 
-    {
-        msSetWMSParamString(psWMSParams, "TRANSPARENT", "TRUE", MS_TRUE);
-    }
-
-    return MS_SUCCESS;
+  }
+
+  /*  set STYLES no matter what, even if it's empty (i.e. "STYLES=")
+   *  styles is a required param of WMS
+   */
+
+  msSetWMSParamString(psWMSParams, "STYLES", pszStyle, MS_TRUE);
+
+  if (pszSLD != NULL) {
+    /* Only SLD is set */
+    msSetWMSParamString(psWMSParams, "SLD",    pszSLD,   MS_TRUE);
+  } else if (pszStyleSLDBody != NULL) {
+    /* SLDBODY are set */
+    msSetWMSParamString(psWMSParams, "SLD_BODY", pszStyleSLDBody, MS_TRUE);
+  }
+
+  if (msIsLayerQueryable(lp)) {
+    msSetWMSParamString(psWMSParams, "QUERY_LAYERS", pszName, MS_TRUE);
+  }
+  if (pszTime && strlen(pszTime) > 0) {
+    msSetWMSParamString(psWMSParams, "TIME",   pszTime,  MS_TRUE);
+  }
+
+  /* if  the metadata wms_sld_body is set to AUTO, we generate
+   * the sld based on classes found in the map file and send
+   * it in the URL. If diffrent from AUTO, we are assuming that
+   * it is a valid sld.
+   */
+  if (pszSLDBody) {
+    if (strcasecmp(pszSLDBody, "AUTO") == 0) {
+      if (pszVersion && strncmp(pszVersion, "1.3.0", 5) == 0)
+        pszSLDGenerated = msSLDGenerateSLD(map, lp->index, "1.1.0");
+      else
+        pszSLDGenerated = msSLDGenerateSLD(map, lp->index, NULL);
+
+      if (pszSLDGenerated) {
+        msSetWMSParamString(psWMSParams, "SLD_BODY",
+                            pszSLDGenerated, MS_TRUE);
+        free(pszSLDGenerated);
+      }
+    } else {
+      msSetWMSParamString(psWMSParams, "SLD_BODY", pszSLDBody, MS_TRUE);
+    }
+
+  }
+
+  if (pszSLDURL) {
+    msSetWMSParamString(psWMSParams, "SLD", pszSLDURL, MS_TRUE);
+  }
+
+  if (pszBgColor) {
+    msSetWMSParamString(psWMSParams, "BGCOLOR", pszBgColor, MS_TRUE);
+  }
+
+  if (pszTransparent) {
+    msSetWMSParamString(psWMSParams, "TRANSPARENT", pszTransparent, MS_TRUE);
+  } else {
+    msSetWMSParamString(psWMSParams, "TRANSPARENT", "TRUE", MS_TRUE);
+  }
+
+  return MS_SUCCESS;
 }
 
 #endif /* USE_WMS_LYR */
@@ -449,13 +404,11 @@ static int msBuildWMSLayerURLBase(mapObj *map, layerObj *lp,
 /**********************************************************************
  *                          msBuildWMSLayerURL()
  *
- * Build a GetMap or GetFeatureInfo URL.  
+ * Build a GetMap or GetFeatureInfo URL.
  *
- * Returns a reference to a newly allocated string that should be freed 
+ * Returns a reference to a newly allocated string that should be freed
  * by the caller.
  **********************************************************************/
-#define WMS_GETMAP         1
-#define WMS_GETFEATUREINFO 2
 
 static int
 msBuildWMSLayerURL(mapObj *map, layerObj *lp, int nRequestType,
@@ -465,429 +418,439 @@ msBuildWMSLayerURL(mapObj *map, layerObj *lp, int nRequestType,
                    wmsParamsObj *psWMSParams)
 {
 #ifdef USE_WMS_LYR
-    char *pszEPSG = NULL;
-    const char *pszVersion, *pszTmp, *pszRequestParam, *pszExceptionsParam, *pszQueryLayers=NULL;
-    rectObj bbox;
-    int bbox_width = map->width, bbox_height = map->height;
-    int nVersion=OWS_VERSION_NOTSET;
-    
-    if (lp->connectiontype != MS_WMS)
-    {
-        msSetError(MS_WMSCONNERR, "Call supported only for CONNECTIONTYPE WMS",
-                   "msBuildWMSLayerURL()");
-        return MS_FAILURE;
-    }
-
-/* ------------------------------------------------------------------
- * Find out request version
- * ------------------------------------------------------------------ */
-    if (lp->connection == NULL ||
-        ((pszVersion = strstr(lp->connection, "VERSION=")) == NULL &&
-         (pszVersion = strstr(lp->connection, "version=")) == NULL &&
-         (pszVersion = strstr(lp->connection, "WMTVER=")) == NULL &&
-         (pszVersion = strstr(lp->connection, "wmtver=")) == NULL ) )
-    {
-        /* CONNECTION missing or seems incomplete... try to build from metadata */
-        if (msBuildWMSLayerURLBase(map, lp, psWMSParams) != MS_SUCCESS)
-            return MS_FAILURE;  /* An error already produced. */
-
-        /* If we received MS_SUCCESS then version must have been set */
-        pszVersion = msLookupHashTable(psWMSParams->params, "VERSION");
-        if (pszVersion ==NULL)
-            pszVersion = msLookupHashTable(psWMSParams->params, "WMTVER");
-
-        nVersion = msOWSParseVersionString(pszVersion);
-    }
+  char *pszEPSG = NULL;
+  const char *pszVersion, *pszTmp, *pszRequestParam, *pszExceptionsParam,
+        *pszLayer=NULL, *pszQueryLayers=NULL;
+  rectObj bbox;
+  int bbox_width = map->width, bbox_height = map->height;
+  int nVersion=OWS_VERSION_NOTSET;
+
+  if (lp->connectiontype != MS_WMS) {
+    msSetError(MS_WMSCONNERR, "Call supported only for CONNECTIONTYPE WMS",
+               "msBuildWMSLayerURL()");
+    return MS_FAILURE;
+  }
+
+  /* ------------------------------------------------------------------
+   * Find out request version
+   * ------------------------------------------------------------------ */
+  if (lp->connection == NULL ||
+      ((pszVersion = strstr(lp->connection, "VERSION=")) == NULL &&
+       (pszVersion = strstr(lp->connection, "version=")) == NULL &&
+       (pszVersion = strstr(lp->connection, "WMTVER=")) == NULL &&
+       (pszVersion = strstr(lp->connection, "wmtver=")) == NULL ) ) {
+    /* CONNECTION missing or seems incomplete... try to build from metadata */
+    if (msBuildWMSLayerURLBase(map, lp, psWMSParams) != MS_SUCCESS)
+      return MS_FAILURE;  /* An error already produced. */
+
+    /* If we received MS_SUCCESS then version must have been set */
+    pszVersion = msLookupHashTable(psWMSParams->params, "VERSION");
+    if (pszVersion ==NULL)
+      pszVersion = msLookupHashTable(psWMSParams->params, "WMTVER");
+
+    nVersion = msOWSParseVersionString(pszVersion);
+  } else {
+    /* CONNECTION string seems complete, start with that. */
+    char *pszDelimiter;
+    psWMSParams->onlineresource = msStrdup(lp->connection);
+
+    /* Fetch version info */
+    pszVersion = strchr(pszVersion, '=')+1;
+    pszDelimiter = strchr(pszVersion, '&');
+    if (pszDelimiter != NULL)
+      *pszDelimiter = '\0';
+    nVersion = msOWSParseVersionString(pszVersion);
+    if (pszDelimiter != NULL)
+      *pszDelimiter = '&';
+  }
+
+  switch (nVersion) {
+    case OWS_1_0_8:
+      nVersion = OWS_1_1_0;    /* 1.0.8 == 1.1.0 */
+      break;
+    case OWS_1_0_0:
+    case OWS_1_0_1:
+    case OWS_1_0_7:
+    case OWS_1_1_0:
+    case OWS_1_1_1:
+      /* All is good, this is a supported version. */
+      break;
+    default:
+      /* Not a supported version */
+      msSetError(MS_WMSCONNERR, "MapServer supports only WMS 1.0.0 to 1.1.1 (please verify the VERSION parameter in the connection string).", "msBuildWMSLayerURL()");
+      return MS_FAILURE;
+  }
+
+  /* ------------------------------------------------------------------
+   * For GetFeatureInfo requests, make sure QUERY_LAYERS is included
+   * ------------------------------------------------------------------ */
+  if  (nRequestType == WMS_GETFEATUREINFO &&
+       strstr(psWMSParams->onlineresource, "QUERY_LAYERS=") == NULL &&
+       strstr(psWMSParams->onlineresource, "query_layers=") == NULL &&
+       msLookupHashTable(psWMSParams->params, "QUERY_LAYERS") == NULL) {
+    pszQueryLayers = msOWSLookupMetadata(&(lp->metadata), "MO", "name");
+
+    if (pszQueryLayers == NULL) {
+      msSetError(MS_WMSCONNERR, "wms_name not set or WMS Connection String must contain the QUERY_LAYERS parameter to support GetFeatureInfo requests (with name in uppercase).", "msBuildWMSLayerURL()");
+      return MS_FAILURE;
+    }
+  }
+
+  /* ------------------------------------------------------------------
+   * For GetLegendGraphic requests, make sure LAYER is included
+   * ------------------------------------------------------------------ */
+  if  (nRequestType == WMS_GETLEGENDGRAPHIC &&
+       strstr(psWMSParams->onlineresource, "LAYER=") == NULL &&
+       strstr(psWMSParams->onlineresource, "layer=") == NULL &&
+       msLookupHashTable(psWMSParams->params, "LAYER") == NULL) {
+    pszLayer = msOWSLookupMetadata(&(lp->metadata), "MO", "name");
+
+    if (pszLayer == NULL) {
+      msSetError(MS_WMSCONNERR, "wms_name not set or WMS Connection String must contain the LAYER parameter to support GetLegendGraphic requests (with name in uppercase).", "msBuildWMSLayerURL()");
+      return MS_FAILURE;
+    }
+  }
+
+  /* ------------------------------------------------------------------
+   * Figure the SRS we'll use for the request.
+   * - Fetch the map SRS (if it's EPSG)
+   * - Check if map SRS is listed in layer wms_srs metadata
+   * - If map SRS is valid for this layer then use it
+   * - Otherwise request layer in its default SRS and we'll reproject later
+   * ------------------------------------------------------------------ */
+  if ((pszEPSG = (char*)msOWSGetEPSGProj(&(map->projection),
+                                         NULL, NULL, MS_TRUE)) != NULL &&
+      (pszEPSG = msStrdup(pszEPSG)) != NULL &&
+      (strncasecmp(pszEPSG, "EPSG:", 5) == 0 ||
+       strncasecmp(pszEPSG, "AUTO:", 5) == 0) ) {
+    const char *pszLyrEPSG, *pszFound;
+    int nLen;
+    char *pszPtr = NULL;
+
+    /* If it's an AUTO projection then keep only id and strip off  */
+    /* the parameters for now (we'll restore them at the end) */
+    if (strncasecmp(pszEPSG, "AUTO:", 5) == 0) {
+      if ((pszPtr = strchr(pszEPSG, ',')))
+        *pszPtr = '\0';
+    }
+
+    nLen = strlen(pszEPSG);
+
+    pszLyrEPSG = msOWSGetEPSGProj(&(lp->projection), &(lp->metadata),
+                                  "MO", MS_FALSE);
+
+    if (pszLyrEPSG == NULL ||
+        (pszFound = strstr(pszLyrEPSG, pszEPSG)) == NULL ||
+        ! ((*(pszFound+nLen) == '\0') || isspace(*(pszFound+nLen))) ) {
+      /* Not found in Layer's list of SRS (including projection object) */
+      free(pszEPSG);
+      pszEPSG = NULL;
+    }
+    if (pszEPSG && pszPtr)
+      *pszPtr = ',';  /* Restore full AUTO:... definition */
+  }
+
+  if (pszEPSG == NULL &&
+      ((pszEPSG = (char*)msOWSGetEPSGProj(&(lp->projection), &(lp->metadata),
+                                          "MO", MS_TRUE)) == NULL ||
+       (pszEPSG = msStrdup(pszEPSG)) == NULL ||
+       (strncasecmp(pszEPSG, "EPSG:", 5) != 0 &&
+        strncasecmp(pszEPSG, "AUTO:", 5) != 0 ) ) ) {
+    msSetError(MS_WMSCONNERR, "Layer must have an EPSG or AUTO projection code (in its PROJECTION object or wms_srs metadata)", "msBuildWMSLayerURL()");
+    if (pszEPSG) free(pszEPSG);
+    return MS_FAILURE;
+  }
+
+  /* ------------------------------------------------------------------
+   * For an AUTO projection, set the Units,lon0,lat0 if not already set
+   * ------------------------------------------------------------------ */
+  if (strncasecmp(pszEPSG, "AUTO:", 5) == 0 &&
+      strchr(pszEPSG, ',') == NULL) {
+    pointObj oPoint;
+    char *pszNewEPSG;
+
+    /* Use center of map view for lon0,lat0 */
+    oPoint.x = (map->extent.minx + map->extent.maxx)/2.0;
+    oPoint.y = (map->extent.miny + map->extent.maxy)/2.0;
+    msProjectPoint(&(map->projection), &(map->latlon), &oPoint);
+
+    pszNewEPSG = (char*)msSmallMalloc(101*sizeof(char));
+
+    snprintf(pszNewEPSG, 100, "%s,9001,%.16g,%.16g",
+             pszEPSG, oPoint.x, oPoint.y);
+    pszNewEPSG[100]='\0';
+    free(pszEPSG);
+    pszEPSG=pszNewEPSG;
+  }
+
+  /* ------------------------------------------------------------------
+   * Set layer SRS.
+   * ------------------------------------------------------------------ */
+  /* No need to set lp->proj if it's already set to the right EPSG code */
+  if ((pszTmp = msOWSGetEPSGProj(&(lp->projection), NULL, "MO", MS_TRUE)) == NULL ||
+      strcasecmp(pszEPSG, pszTmp) != 0) {
+    const char *ows_srs;
+
+    /* no need to set lp->proj if it is already set and there is only
+       one item in the _srs metadata for this layer - we will assume
+       the projection block matches the _srs metadata (the search for ' '
+       in ows_srs is a test to see if there are multiple EPSG: codes) */
+    if( lp->projection.numargs == 0
+        || (ows_srs = msOWSGetEPSGProj(NULL,&(lp->metadata), "MO", MS_FALSE)) == NULL
+        || (strchr(ows_srs,' ') != NULL) ) {
+      if (strncasecmp(pszEPSG, "EPSG:", 5) == 0) {
+        char szProj[20];
+        snprintf(szProj, sizeof(szProj), "init=epsg:%s", pszEPSG+5);
+
+        if (msLoadProjectionString(&(lp->projection), szProj) != 0)
+          return MS_FAILURE;
+      } else {
+        if (msLoadProjectionString(&(lp->projection), pszEPSG) != 0)
+          return MS_FAILURE;
+      }
+    }
+  }
+
+  /* ------------------------------------------------------------------
+   * Adjust for MapServer EXTENT being center of pixel and WMS BBOX being
+   * edge of pixel (#2843).
+   * ------------------------------------------------------------------ */
+  bbox = map->extent;
+
+  bbox.minx -= map->cellsize * 0.5;
+  bbox.maxx += map->cellsize * 0.5;
+  bbox.miny -= map->cellsize * 0.5;
+  bbox.maxy += map->cellsize * 0.5;
+
+  /* -------------------------------------------------------------------- */
+  /*      Reproject if needed.                                            */
+  /* -------------------------------------------------------------------- */
+  if (msProjectionsDiffer(&(map->projection), &(lp->projection))) {
+    msProjectRect(&(map->projection), &(lp->projection), &bbox);
+
+    /* -------------------------------------------------------------------- */
+    /*      Sometimes our remote WMS only accepts square pixel              */
+    /*      requests.  If this is the case adjust adjust the number of      */
+    /*      pixels or lines in the request so that the pixels are           */
+    /*      square.                                                         */
+    /* -------------------------------------------------------------------- */
+    {
+      const char *nonsquare_ok =
+        msOWSLookupMetadata(&(lp->metadata),
+                            "MO", "nonsquare_ok");
+
+      /* assume nonsquare_ok is false */
+      if( nonsquare_ok != NULL
+          && (strcasecmp(nonsquare_ok,"no") == 0
+              || strcasecmp(nonsquare_ok,"false") == 0) ) {
+        double cellsize_x = (bbox.maxx-bbox.minx) / bbox_width;
+        double cellsize_y = (bbox.maxy-bbox.miny) / bbox_height;
+
+        if( cellsize_x < cellsize_y * 0.999999 ) {
+          int new_bbox_height =
+            ceil((cellsize_y/cellsize_x) * bbox_height);
+
+          if (lp->debug)
+            msDebug("NONSQUARE_OK=%s, adjusted HEIGHT from %d to %d to equalize cellsize at %g.\n",
+                    nonsquare_ok,
+                    bbox_height, new_bbox_height, cellsize_x );
+          bbox_height = new_bbox_height;
+        } else if( cellsize_y < cellsize_x * 0.999999 ) {
+          int new_bbox_width =
+            ceil((cellsize_x/cellsize_y) * bbox_width);
+
+          if (lp->debug)
+            msDebug("NONSQUARE_OK=%s, adjusted WIDTH from %d to %d to equalize cellsize at %g.\n",
+                    nonsquare_ok,
+                    bbox_width, new_bbox_width, cellsize_y );
+          bbox_width = new_bbox_width;
+        } else {
+          if (lp->debug)
+            msDebug("NONSQUARE_OK=%s, but cellsize was already square - no change.\n",
+                    nonsquare_ok );
+        }
+      }
+    }
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      If the layer has predefined extents, and a predefined           */
+  /*      projection that matches the request projection, then            */
+  /*      consider restricting the BBOX to match the limits.              */
+  /* -------------------------------------------------------------------- */
+  if( bbox_width != 0 ) {
+    const char *ows_srs;
+    rectObj  layer_rect;
+
+    ows_srs = msOWSGetEPSGProj(&(lp->projection), &(lp->metadata),
+                               "MO", MS_FALSE);
+
+    if( ows_srs && strchr(ows_srs,' ') == NULL
+        && msOWSGetLayerExtent( map, lp, "MO", &layer_rect) == MS_SUCCESS ) {
+      /* fulloverlap */
+      if( msRectContained( &bbox, &layer_rect ) ) {
+        /* no changes */
+      }
+
+      /* no overlap */
+      else if( !msRectOverlap( &layer_rect, &bbox ) ) {
+        bbox_width = 0;
+        bbox_height = 0;
+      }
+
+      else {
+        double cellsize_x = (bbox.maxx-bbox.minx) / bbox_width;
+        double cellsize_y = (bbox.maxy-bbox.miny) / bbox_height;
+        double cellsize = MIN(cellsize_x,cellsize_y);
+
+        msRectIntersect( &bbox, &layer_rect );
+
+        bbox_width = ceil((bbox.maxx - bbox.minx) / cellsize);
+        bbox_height = ceil((bbox.maxy - bbox.miny) / cellsize);
+      }
+    }
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Potentially return the bbox.                                    */
+  /* -------------------------------------------------------------------- */
+  if (bbox_ret != NULL)
+    *bbox_ret = bbox;
+
+  if( width_ret != NULL )
+    *width_ret = bbox_width;
+
+  if( height_ret != NULL )
+    *height_ret = bbox_height;
+
+  /* ------------------------------------------------------------------
+   * Build the request URL.
+   * At this point we set only the following parameters for GetMap:
+   *   REQUEST
+   *   SRS
+   *   BBOX
+   *
+   * And for GetFeatureInfo:
+   *   X
+   *   Y
+   *   INFO_FORMAT
+   *   FEATURE_COUNT (only if nFeatureCount > 0)
+   *
+   * The connection string should contain all other required params,
+   * including:
+   *   VERSION
+   *   LAYERS
+   *   FORMAT
+   *   TRANSPARENT
+   *   STYLES
+   *   QUERY_LAYERS (for queryable layers only)
+   * ------------------------------------------------------------------ */
+
+  if (nRequestType == WMS_GETFEATUREINFO) {
+    char szBuf[100] = "";
+
+    if (nVersion >= OWS_1_0_7)
+      pszRequestParam = "GetFeatureInfo";
     else
-    {
-        /* CONNECTION string seems complete, start with that. */
-        char *pszDelimiter;
-        psWMSParams->onlineresource = msStrdup(lp->connection);
-
-        /* Fetch version info */
-        pszVersion = strchr(pszVersion, '=')+1;
-        pszDelimiter = strchr(pszVersion, '&');
-        if (pszDelimiter != NULL)
-            *pszDelimiter = '\0';
-        nVersion = msOWSParseVersionString(pszVersion);
-        if (pszDelimiter != NULL)
-            *pszDelimiter = '&';
-    }
+      pszRequestParam = "feature_info";
 
-    switch (nVersion)
-    {
-      case OWS_1_0_8:
-        nVersion = OWS_1_1_0;    /* 1.0.8 == 1.1.0 */
-        break;
-      case OWS_1_0_0:
-      case OWS_1_0_1:
-      case OWS_1_0_7:
-      case OWS_1_1_0:
-      case OWS_1_1_1:
-        /* All is good, this is a supported version. */
-        break;
-      default:
-        /* Not a supported version */
-        msSetError(MS_WMSCONNERR, "MapServer supports only WMS 1.0.0 to 1.1.1 (please verify the VERSION parameter in the connection string).", "msBuildWMSLayerURL()");
-        return MS_FAILURE;
-    }
+    if (nVersion >= OWS_1_1_0)
+      pszExceptionsParam = "application/vnd.ogc.se_xml";
+    else if (nVersion > OWS_1_1_0)  /* 1.0.1 to 1.0.7 */
+      pszExceptionsParam = "SE_XML";
+    else
+      pszExceptionsParam = "WMS_XML";
 
-/* ------------------------------------------------------------------
- * For GetFeatureInfo requests, make sure QUERY_LAYERS is included
- * ------------------------------------------------------------------ */
-    if  (nRequestType == WMS_GETFEATUREINFO &&
-         strstr(psWMSParams->onlineresource, "QUERY_LAYERS=") == NULL &&
-         strstr(psWMSParams->onlineresource, "query_layers=") == NULL &&
-         msLookupHashTable(psWMSParams->params, "QUERY_LAYERS") == NULL)
-    {
-        pszQueryLayers = msOWSLookupMetadata(&(lp->metadata), "MO", "name");
+    msSetWMSParamString(psWMSParams, "REQUEST", pszRequestParam, MS_FALSE);
+    msSetWMSParamInt(   psWMSParams, "WIDTH",   bbox_width);
+    msSetWMSParamInt(   psWMSParams, "HEIGHT",  bbox_height);
+    msSetWMSParamString(psWMSParams, "SRS",     pszEPSG, MS_FALSE);
 
-        if (pszQueryLayers == NULL) {
-             msSetError(MS_WMSCONNERR, "wms_name not set or WMS Connection String must contain the QUERY_LAYERS parameter to support GetFeatureInfo requests (with name in uppercase).", "msBuildWMSLayerURL()");
-             return MS_FAILURE;
-        }
-    }
+    snprintf(szBuf, sizeof(szBuf), "%.15g,%.15g,%.15g,%.15g",
+             bbox.minx, bbox.miny, bbox.maxx, bbox.maxy);
+    msSetWMSParamString(psWMSParams, "BBOX",    szBuf, MS_TRUE);
 
-/* ------------------------------------------------------------------
- * Figure the SRS we'll use for the request.
- * - Fetch the map SRS (if it's EPSG)
- * - Check if map SRS is listed in layer wms_srs metadata
- * - If map SRS is valid for this layer then use it
- * - Otherwise request layer in its default SRS and we'll reproject later
- * ------------------------------------------------------------------ */
-    if ((pszEPSG = (char*)msOWSGetEPSGProj(&(map->projection), 
-                                           NULL, NULL, MS_TRUE)) != NULL &&
-        (pszEPSG = msStrdup(pszEPSG)) != NULL &&
-        (strncasecmp(pszEPSG, "EPSG:", 5) == 0 ||
-         strncasecmp(pszEPSG, "AUTO:", 5) == 0) )
-    {
-        const char *pszLyrEPSG, *pszFound;
-        int nLen;
-        char *pszPtr = NULL;
-
-        /* If it's an AUTO projection then keep only id and strip off  */
-        /* the parameters for now (we'll restore them at the end) */
-        if (strncasecmp(pszEPSG, "AUTO:", 5) == 0)
-        {
-            if ((pszPtr = strchr(pszEPSG, ',')))
-                *pszPtr = '\0';
-        }
+    msSetWMSParamInt(   psWMSParams, "X",       nClickX);
+    msSetWMSParamInt(   psWMSParams, "Y",       nClickY);
 
-        nLen = strlen(pszEPSG);
+    msSetWMSParamString(psWMSParams, "EXCEPTIONS", pszExceptionsParam, MS_FALSE);
+    msSetWMSParamString(psWMSParams, "INFO_FORMAT", pszInfoFormat, MS_TRUE);
 
-        pszLyrEPSG = msOWSGetEPSGProj(&(lp->projection), &(lp->metadata),
-                                      "MO", MS_FALSE);
-
-        if (pszLyrEPSG == NULL ||
-            (pszFound = strstr(pszLyrEPSG, pszEPSG)) == NULL ||
-            ! ((*(pszFound+nLen) == '\0') || isspace(*(pszFound+nLen))) )
-        {
-            /* Not found in Layer's list of SRS (including projection object) */
-            free(pszEPSG);
-            pszEPSG = NULL;
-        }
-        if (pszEPSG && pszPtr)
-            *pszPtr = ',';  /* Restore full AUTO:... definition */
+    if (pszQueryLayers) { /* not set in CONNECTION string */
+      msSetWMSParamString(psWMSParams, "QUERY_LAYERS", pszQueryLayers, MS_FALSE);
     }
 
-    if (pszEPSG == NULL &&
-        ((pszEPSG = (char*)msOWSGetEPSGProj(&(lp->projection), &(lp->metadata),
-                                            "MO", MS_TRUE)) == NULL ||
-         (pszEPSG = msStrdup(pszEPSG)) == NULL ||
-         (strncasecmp(pszEPSG, "EPSG:", 5) != 0 &&
-          strncasecmp(pszEPSG, "AUTO:", 5) != 0 ) ) )
-    {
-        msSetError(MS_WMSCONNERR, "Layer must have an EPSG or AUTO projection code (in its PROJECTION object or wms_srs metadata)", "msBuildWMSLayerURL()");
-        if (pszEPSG) free(pszEPSG);
-        return MS_FAILURE;
+    /* If FEATURE_COUNT <= 0 then don't pass this parameter */
+    /* The spec states that FEATURE_COUNT must be greater than zero */
+    /* and if not passed then the behavior is up to the server */
+    if (nFeatureCount > 0) {
+      msSetWMSParamInt(psWMSParams, "FEATURE_COUNT", nFeatureCount);
     }
 
-/* ------------------------------------------------------------------
- * For an AUTO projection, set the Units,lon0,lat0 if not already set
- * ------------------------------------------------------------------ */
-    if (strncasecmp(pszEPSG, "AUTO:", 5) == 0 &&
-        strchr(pszEPSG, ',') == NULL)
-    {
-        pointObj oPoint;
-        char *pszNewEPSG;
-
-        /* Use center of map view for lon0,lat0 */
-        oPoint.x = (map->extent.minx + map->extent.maxx)/2.0;
-        oPoint.y = (map->extent.miny + map->extent.maxy)/2.0;
-        msProjectPoint(&(map->projection), &(map->latlon), &oPoint);
-
-        pszNewEPSG = (char*)msSmallMalloc(101*sizeof(char));
-
-        snprintf(pszNewEPSG, 100, "%s,9001,%.16g,%.16g", 
-                 pszEPSG, oPoint.x, oPoint.y);
-        pszNewEPSG[100]='\0';
-        free(pszEPSG);
-        pszEPSG=pszNewEPSG;
+  } else if (nRequestType == WMS_GETLEGENDGRAPHIC) {
+    if(map->extent.maxx > map->extent.minx && map->width > 0 && map->height > 0) {
+      char szBuf[20] = "";
+      double scaledenom;
+      msCalculateScale(map->extent, map->units, map->width, map->height,
+                     map->resolution, &scaledenom);
+      snprintf(szBuf, 20, "%g",scaledenom);
+      msSetWMSParamString(psWMSParams, "SCALE", szBuf, MS_FALSE);
     }
+    pszRequestParam = "GetLegendGraphic";
 
-/* ------------------------------------------------------------------
- * Set layer SRS.
- * ------------------------------------------------------------------ */
-    /* No need to set lp->proj if it's already set to the right EPSG code */
-    if ((pszTmp = msOWSGetEPSGProj(&(lp->projection), NULL, "MO", MS_TRUE)) == NULL ||
-        strcasecmp(pszEPSG, pszTmp) != 0)
-    {
-        const char *ows_srs;
-
-        /* no need to set lp->proj if it is already set and there is only 
-           one item in the _srs metadata for this layer - we will assume
-           the projection block matches the _srs metadata (the search for ' '
-           in ows_srs is a test to see if there are multiple EPSG: codes) */
-        if( lp->projection.numargs == 0 
-            || (ows_srs = msOWSGetEPSGProj(NULL,&(lp->metadata), "MO", MS_FALSE)) == NULL
-            || (strchr(ows_srs,' ') != NULL) )
-        {
-            if (strncasecmp(pszEPSG, "EPSG:", 5) == 0)
-            {
-                char szProj[20];
-                snprintf(szProj, sizeof(szProj), "init=epsg:%s", pszEPSG+5);
-
-                if (msLoadProjectionString(&(lp->projection), szProj) != 0)
-                    return MS_FAILURE;
-            }
-            else
-            {
-                if (msLoadProjectionString(&(lp->projection), pszEPSG) != 0)
-                    return MS_FAILURE;
-            }
-        }
+    pszExceptionsParam = msOWSLookupMetadata(&(lp->metadata),
+                         "MO", "exceptions_format");
+    if (pszExceptionsParam == NULL) {
+      if (nVersion >= OWS_1_1_0)
+        pszExceptionsParam = "application/vnd.ogc.se_inimage";
+      else
+        pszExceptionsParam = "INIMAGE";
     }
 
-/* ------------------------------------------------------------------
- * Adjust for MapServer EXTENT being center of pixel and WMS BBOX being 
- * edge of pixel (#2843).
- * ------------------------------------------------------------------ */
-    bbox = map->extent;
-
-    bbox.minx -= map->cellsize * 0.5;
-    bbox.maxx += map->cellsize * 0.5;
-    bbox.miny -= map->cellsize * 0.5;
-    bbox.maxy += map->cellsize * 0.5;
-
-/* -------------------------------------------------------------------- */
-/*      Reproject if needed.                                            */
-/* -------------------------------------------------------------------- */
-    if (msProjectionsDiffer(&(map->projection), &(lp->projection)))
-    {
-        msProjectRect(&(map->projection), &(lp->projection), &bbox);
-
-/* -------------------------------------------------------------------- */
-/*      Sometimes our remote WMS only accepts square pixel              */
-/*      requests.  If this is the case adjust adjust the number of      */
-/*      pixels or lines in the request so that the pixels are           */
-/*      square.                                                         */
-/* -------------------------------------------------------------------- */
-        {
-            const char *nonsquare_ok = 
-                msOWSLookupMetadata(&(lp->metadata), 
-                                    "MO", "nonsquare_ok");
-            
-            /* assume nonsquare_ok is false */
-            if( nonsquare_ok != NULL 
-                && (strcasecmp(nonsquare_ok,"no") == 0 
-                    || strcasecmp(nonsquare_ok,"false") == 0) )
-            {
-                double cellsize_x = (bbox.maxx-bbox.minx) / bbox_width;
-                double cellsize_y = (bbox.maxy-bbox.miny) / bbox_height;
-
-                if( cellsize_x < cellsize_y * 0.999999 )
-                {
-                    int new_bbox_height = 
-                        ceil((cellsize_y/cellsize_x) * bbox_height);
-
-                    if (lp->debug)
-                        msDebug("NONSQUARE_OK=%s, adjusted HEIGHT from %d to %d to equalize cellsize at %g.\n",
-                                nonsquare_ok, 
-                                bbox_height, new_bbox_height, cellsize_x );
-                    bbox_height = new_bbox_height;
-                }
-                else if( cellsize_y < cellsize_x * 0.999999 )
-                {
-                    int new_bbox_width = 
-                        ceil((cellsize_x/cellsize_y) * bbox_width);
-
-                    if (lp->debug)
-                        msDebug("NONSQUARE_OK=%s, adjusted WIDTH from %d to %d to equalize cellsize at %g.\n",
-                                nonsquare_ok,
-                                bbox_width, new_bbox_width, cellsize_y );
-                    bbox_width = new_bbox_width;
-                }
-                else
-                {
-                    if (lp->debug)
-                        msDebug("NONSQUARE_OK=%s, but cellsize was already square - no change.\n",
-                                nonsquare_ok );
-                }
-            }
-        }
-    }
-
-/* -------------------------------------------------------------------- */
-/*      If the layer has predefined extents, and a predefined           */
-/*      projection that matches the request projection, then            */
-/*      consider restricting the BBOX to match the limits.              */
-/* -------------------------------------------------------------------- */
-    if( bbox_width != 0 )
-    {
-        const char *ows_srs;
-        rectObj  layer_rect;
-
-        ows_srs = msOWSGetEPSGProj(&(lp->projection), &(lp->metadata), 
-                                   "MO", MS_FALSE);
-
-        if( ows_srs && strchr(ows_srs,' ') == NULL 
-            && msOWSGetLayerExtent( map, lp, "MO", &layer_rect) == MS_SUCCESS )
-        {
-            /* fulloverlap */
-            if( msRectContained( &bbox, &layer_rect ) )
-            {
-                /* no changes */
-            }
-           
-            /* no overlap */
-            else if( !msRectOverlap( &layer_rect, &bbox ) )
-            {
-                bbox_width = 0;
-                bbox_height = 0;
-            }
-
-            else
-            {
-                double cellsize_x = (bbox.maxx-bbox.minx) / bbox_width;
-                double cellsize_y = (bbox.maxy-bbox.miny) / bbox_height;
-                double cellsize = MIN(cellsize_x,cellsize_y);
-                
-                msRectIntersect( &bbox, &layer_rect );
-                
-                bbox_width = ceil((bbox.maxx - bbox.minx) / cellsize);
-                bbox_height = ceil((bbox.maxy - bbox.miny) / cellsize);
-            }
-        }
+    if (pszLayer) { /* not set in CONNECTION string */
+      msSetWMSParamString(psWMSParams, "LAYER", pszLayer, MS_FALSE);
     }
 
-/* -------------------------------------------------------------------- */
-/*      Potentially return the bbox.                                    */
-/* -------------------------------------------------------------------- */
-    if (bbox_ret != NULL)
-        *bbox_ret = bbox;
-
-    if( width_ret != NULL )
-        *width_ret = bbox_width;
+    msSetWMSParamString(psWMSParams, "REQUEST", pszRequestParam, MS_FALSE);
+    msSetWMSParamString(psWMSParams, "SRS",     pszEPSG, MS_FALSE);
 
-    if( height_ret != NULL )
-        *height_ret = bbox_height;
+  } else { /* if (nRequestType == WMS_GETMAP) */
+    char szBuf[100] = "";
 
-/* ------------------------------------------------------------------
- * Build the request URL.
- * At this point we set only the following parameters for GetMap:
- *   REQUEST
- *   SRS
- *   BBOX
- *
- * And for GetFeatureInfo:
- *   X
- *   Y
- *   INFO_FORMAT
- *   FEATURE_COUNT (only if nFeatureCount > 0)
- *
- * The connection string should contain all other required params, 
- * including:
- *   VERSION
- *   LAYERS
- *   FORMAT
- *   TRANSPARENT
- *   STYLES
- *   QUERY_LAYERS (for queryable layers only)
- * ------------------------------------------------------------------ */
-
-    if (nRequestType == WMS_GETFEATUREINFO)
-    {
-        char szBuf[100] = "";
-
-        if (nVersion >= OWS_1_0_7)
-            pszRequestParam = "GetFeatureInfo";
-        else
-            pszRequestParam = "feature_info";
-
-        if (nVersion >= OWS_1_1_0)
-            pszExceptionsParam = "application/vnd.ogc.se_xml";
-        else if (nVersion > OWS_1_1_0)  /* 1.0.1 to 1.0.7 */
-            pszExceptionsParam = "SE_XML";
-        else
-            pszExceptionsParam = "WMS_XML";
-
-        msSetWMSParamString(psWMSParams, "REQUEST", pszRequestParam, MS_FALSE);
-        msSetWMSParamInt(   psWMSParams, "WIDTH",   bbox_width);
-        msSetWMSParamInt(   psWMSParams, "HEIGHT",  bbox_height);
-        msSetWMSParamString(psWMSParams, "SRS",     pszEPSG, MS_FALSE);
-
-        snprintf(szBuf, sizeof(szBuf), "%.15g,%.15g,%.15g,%.15g", 
-                 bbox.minx, bbox.miny, bbox.maxx, bbox.maxy);
-        msSetWMSParamString(psWMSParams, "BBOX",    szBuf, MS_TRUE);
- 
-        msSetWMSParamInt(   psWMSParams, "X",       nClickX);
-        msSetWMSParamInt(   psWMSParams, "Y",       nClickY);
- 
-        msSetWMSParamString(psWMSParams, "EXCEPTIONS", pszExceptionsParam, MS_FALSE);
-        msSetWMSParamString(psWMSParams, "INFO_FORMAT", pszInfoFormat, MS_TRUE);
-
-        if (pszQueryLayers) { /* not set in CONNECTION string */
-          msSetWMSParamString(psWMSParams, "QUERY_LAYERS", pszQueryLayers, MS_FALSE);
-        }
-
-        /* If FEATURE_COUNT <= 0 then don't pass this parameter */
-        /* The spec states that FEATURE_COUNT must be greater than zero */
-        /* and if not passed then the behavior is up to the server */
-        if (nFeatureCount > 0)
-        {
-            msSetWMSParamInt(psWMSParams, "FEATURE_COUNT", nFeatureCount);
-        }
+    if (nVersion >= OWS_1_0_7)
+      pszRequestParam = "GetMap";
+    else
+      pszRequestParam = "map";
 
+    pszExceptionsParam = msOWSLookupMetadata(&(lp->metadata),
+                         "MO", "exceptions_format");
+    if (pszExceptionsParam == NULL) {
+      if (nVersion >= OWS_1_1_0)
+        pszExceptionsParam = "application/vnd.ogc.se_inimage";
+      else
+        pszExceptionsParam = "INIMAGE";
     }
-    else /* if (nRequestType == WMS_GETMAP) */
-    {
-        char szBuf[100] = "";
-
-        if (nVersion >= OWS_1_0_7)
-            pszRequestParam = "GetMap";
-        else
-            pszRequestParam = "map";
-
-        pszExceptionsParam = msOWSLookupMetadata(&(lp->metadata), 
-                                                 "MO", "exceptions_format");
-        if (pszExceptionsParam == NULL)
-        {
-            if (nVersion >= OWS_1_1_0)
-                pszExceptionsParam = "application/vnd.ogc.se_inimage";
-            else
-                pszExceptionsParam = "INIMAGE";
-        }
 
-        msSetWMSParamString(psWMSParams, "REQUEST", pszRequestParam, MS_FALSE);
-        msSetWMSParamInt(   psWMSParams, "WIDTH",   bbox_width);
-        msSetWMSParamInt(   psWMSParams, "HEIGHT",  bbox_height);
-        msSetWMSParamString(psWMSParams, "SRS",     pszEPSG, MS_FALSE);
+    msSetWMSParamString(psWMSParams, "REQUEST", pszRequestParam, MS_FALSE);
+    msSetWMSParamInt(   psWMSParams, "WIDTH",   bbox_width);
+    msSetWMSParamInt(   psWMSParams, "HEIGHT",  bbox_height);
+    msSetWMSParamString(psWMSParams, "SRS",     pszEPSG, MS_FALSE);
 
-        snprintf(szBuf, sizeof(szBuf), "%.15g,%.15g,%.15g,%.15g", 
-                 bbox.minx, bbox.miny, bbox.maxx, bbox.maxy);
-        msSetWMSParamString(psWMSParams, "BBOX",    szBuf, MS_TRUE);
-        msSetWMSParamString(psWMSParams, "EXCEPTIONS",  pszExceptionsParam, MS_FALSE);
-    }
+    snprintf(szBuf, sizeof(szBuf), "%.15g,%.15g,%.15g,%.15g",
+             bbox.minx, bbox.miny, bbox.maxx, bbox.maxy);
+    msSetWMSParamString(psWMSParams, "BBOX",    szBuf, MS_TRUE);
+    msSetWMSParamString(psWMSParams, "EXCEPTIONS",  pszExceptionsParam, MS_FALSE);
+  }
 
-    free(pszEPSG);
+  free(pszEPSG);
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 
 #else
-/* ------------------------------------------------------------------
- * WMS CONNECTION Support not included...
- * ------------------------------------------------------------------ */
-  msSetError(MS_WMSCONNERR, "WMS CLIENT CONNECTION support is not available.", 
+  /* ------------------------------------------------------------------
+   * WMS CONNECTION Support not included...
+   * ------------------------------------------------------------------ */
+  msSetError(MS_WMSCONNERR, "WMS CLIENT CONNECTION support is not available.",
              "msBuildWMSLayerURL()");
   return MS_FAILURE;
 
@@ -901,480 +864,451 @@ msBuildWMSLayerURL(mapObj *map, layerObj *lp, int nRequestType,
  *
  * Build a GetFeatureInfo URL for this layer.
  *
- * Returns a reference to a newly allocated string that should be freed 
+ * Returns a reference to a newly allocated string that should be freed
  * by the caller.
  **********************************************************************/
 char *msWMSGetFeatureInfoURL(mapObj *map, layerObj *lp,
                              int nClickX, int nClickY, int nFeatureCount,
-                             const char *pszInfoFormat) 
+                             const char *pszInfoFormat)
 {
-    wmsParamsObj sThisWMSParams;
-    char *pszURL;
+  wmsParamsObj sThisWMSParams;
+  char *pszURL;
 
-    msInitWmsParamsObj(&sThisWMSParams);
+  msInitWmsParamsObj(&sThisWMSParams);
 
-    if (msBuildWMSLayerURL(map, lp, WMS_GETFEATUREINFO,
-                           nClickX, nClickY, nFeatureCount,
-                           pszInfoFormat, NULL, NULL, NULL,
-                           &sThisWMSParams)!= MS_SUCCESS)
-    {
-        return NULL;
-    }
+  if (msBuildWMSLayerURL(map, lp, WMS_GETFEATUREINFO,
+                         nClickX, nClickY, nFeatureCount,
+                         pszInfoFormat, NULL, NULL, NULL,
+                         &sThisWMSParams)!= MS_SUCCESS) {
+    return NULL;
+  }
 
-    pszURL = msBuildURLFromWMSParams(&sThisWMSParams);
-    msFreeWmsParamsObj(&sThisWMSParams);
+  pszURL = msBuildURLFromWMSParams(&sThisWMSParams);
+  msFreeWmsParamsObj(&sThisWMSParams);
 
-    return pszURL;
+  return pszURL;
 }
 
-
 /**********************************************************************
  *                          msPrepareWMSLayerRequest()
  *
  **********************************************************************/
 
 int msPrepareWMSLayerRequest(int nLayerId, mapObj *map, layerObj *lp,
-                             enum MS_CONNECTION_TYPE lastconnectiontype,
+                             int nRequestType, enum MS_CONNECTION_TYPE lastconnectiontype,
                              wmsParamsObj *psLastWMSParams,
-                             httpRequestObj *pasReqInfo, int *numRequests) 
+                             int nClickX, int nClickY, int nFeatureCount, const char *pszInfoFormat,
+                             httpRequestObj *pasReqInfo, int *numRequests)
 {
 #ifdef USE_WMS_LYR
-    char *pszURL = NULL, *pszHTTPCookieData = NULL;
-    const char *pszTmp;
-    rectObj bbox;
-    int bbox_width, bbox_height;
-    int nTimeout, bOkToMerge, bForceSeparateRequest, bCacheToDisk;
-    wmsParamsObj sThisWMSParams;
-    
-    char    *pszProxyHost=NULL;
-    long     nProxyPort=0;
-    char    *pszProxyUsername=NULL, *pszProxyPassword=NULL;
-    char    *pszHttpAuthUsername=NULL, *pszHttpAuthPassword=NULL;
-    enum MS_HTTP_AUTH_TYPE eHttpAuthType = MS_BASIC;
-    enum MS_HTTP_AUTH_TYPE eProxyAuthType = MS_BASIC;
-    enum MS_HTTP_PROXY_TYPE eProxyType = MS_HTTP;
-
-    if (lp->connectiontype != MS_WMS)
-        return MS_FAILURE;
-
-    msInitWmsParamsObj(&sThisWMSParams);
-
-/* ------------------------------------------------------------------
- * Build the request URL, this will also set layer projection and
- * compute BBOX in that projection.
- * ------------------------------------------------------------------ */
-    if ( msBuildWMSLayerURL(map, lp, WMS_GETMAP,
-                            0, 0, 0, NULL, &bbox, &bbox_width, &bbox_height,
-                            &sThisWMSParams) != MS_SUCCESS)
-    {
-        /* an error was already reported. */
-        msFreeWmsParamsObj(&sThisWMSParams);
-        return MS_FAILURE;
-    }
-
-/* ------------------------------------------------------------------
- * Check if the request is empty, perhaps due to reprojection problems
- * or wms_extents restrictions.
- * ------------------------------------------------------------------ */
-    if( bbox_width == 0 || bbox_height == 0 )
-    {
-        msFreeWmsParamsObj(&sThisWMSParams);
-        return MS_SUCCESS;  /* No overlap. */
-    }
-
-/* ------------------------------------------------------------------
- * Check if layer overlaps current view window (using wms_latlonboundingbox)
- * ------------------------------------------------------------------ */
-    if ((pszTmp = msOWSLookupMetadata(&(lp->metadata), 
-                                      "MO", "latlonboundingbox")) != NULL)
-    {
-        char **tokens;
-        int n;
-        rectObj ext;
-
-        tokens = msStringSplit(pszTmp, ' ', &n);
-        if (tokens==NULL || n != 4) {
-            msSetError(MS_WMSCONNERR, "Wrong number of arguments for 'wms_latlonboundingbox' metadata.",
-                       "msDrawWMSLayer()");
-            msFreeWmsParamsObj(&sThisWMSParams);
-            return MS_FAILURE;
-        }
-
-        ext.minx = atof(tokens[0]);
-        ext.miny = atof(tokens[1]);
-        ext.maxx = atof(tokens[2]);
-        ext.maxy = atof(tokens[3]);
-
-        msFreeCharArray(tokens, n);
-
-        /* Reproject latlonboundingbox to the selected SRS for the layer and */
-        /* check if it overlaps the bbox that we calculated for the request */
-
-        msProjectRect(&(map->latlon), &(lp->projection), &ext);
-        if (!msRectOverlap(&bbox, &ext))
-        {
-            /* No overlap... nothing to do */
-
-            msFreeWmsParamsObj(&sThisWMSParams);
-            return MS_SUCCESS;  /* No overlap. */
-        }
-    }
+  char *pszURL = NULL, *pszHTTPCookieData = NULL;
+  const char *pszTmp;
+  rectObj bbox;
+  int bbox_width, bbox_height;
+  int nTimeout, bOkToMerge, bForceSeparateRequest, bCacheToDisk;
+  wmsParamsObj sThisWMSParams;
+
+  char    *pszProxyHost=NULL;
+  long     nProxyPort=0;
+  char    *pszProxyUsername=NULL, *pszProxyPassword=NULL;
+  char    *pszHttpAuthUsername=NULL, *pszHttpAuthPassword=NULL;
+  enum MS_HTTP_AUTH_TYPE eHttpAuthType = MS_BASIC;
+  enum MS_HTTP_AUTH_TYPE eProxyAuthType = MS_BASIC;
+  enum MS_HTTP_PROXY_TYPE eProxyType = MS_HTTP;
+
+  if (lp->connectiontype != MS_WMS)
+    return MS_FAILURE;
+
+  msInitWmsParamsObj(&sThisWMSParams);
+
+  /* ------------------------------------------------------------------
+   * Build the request URL, this will also set layer projection and
+   * compute BBOX in that projection.
+   * ------------------------------------------------------------------ */
+
+
+  if (nRequestType == WMS_GETMAP &&
+      ( msBuildWMSLayerURL(map, lp, WMS_GETMAP,
+                           0, 0, 0, NULL, &bbox, &bbox_width, &bbox_height,
+                           &sThisWMSParams) != MS_SUCCESS) ) {
+    /* an error was already reported. */
+    msFreeWmsParamsObj(&sThisWMSParams);
+    return MS_FAILURE;
+  }
+
+  else if (nRequestType == WMS_GETFEATUREINFO &&
+           msBuildWMSLayerURL(map, lp, WMS_GETFEATUREINFO,
+                              nClickX, nClickY, nFeatureCount, pszInfoFormat,
+                              NULL, NULL, NULL,
+                              &sThisWMSParams) != MS_SUCCESS ) {
+    /* an error was already reported. */
+    msFreeWmsParamsObj(&sThisWMSParams);
+    return MS_FAILURE;
+  } else if (nRequestType == WMS_GETLEGENDGRAPHIC &&
+             msBuildWMSLayerURL(map, lp, WMS_GETLEGENDGRAPHIC,
+                                0, 0, 0, NULL,
+                                NULL, NULL, NULL,
+                                &sThisWMSParams) != MS_SUCCESS ) {
+    /* an error was already reported. */
+    msFreeWmsParamsObj(&sThisWMSParams);
+    return MS_FAILURE;
+  }
 
-/* ------------------------------------------------------------------
- * check to see if a the metadata wms_connectiontimeout is set. If it is 
- * the case we will use it, else we use the default which is 30 seconds.
- * First check the metadata in the layer object and then in the map object.
- * ------------------------------------------------------------------ */
-    nTimeout = 30;  /* Default is 30 seconds  */
-    if ((pszTmp = msOWSLookupMetadata(&(lp->metadata), 
-                                      "MO", "connectiontimeout")) != NULL)
-    {
-        nTimeout = atoi(pszTmp); 
-    }
-    else if ((pszTmp = msOWSLookupMetadata(&(map->web.metadata), 
-                                           "MO", "connectiontimeout")) != NULL)
-    {
-        nTimeout = atoi(pszTmp);
-    }
-    
-/* ------------------------------------------------------------------
- * Check for authentication and proxying metadata. If the metadata is not found
- * in the layer metadata, check the map-level metadata.
- * ------------------------------------------------------------------ */
-    if ((pszTmp = msOWSLookupMetadata2(&(lp->metadata), &(map->web.metadata),
-                                       "MO", "proxy_host")) != NULL)
-    {
-        pszProxyHost = msStrdup(pszTmp);
-    }
-    
-    if ((pszTmp = msOWSLookupMetadata2(&(lp->metadata), &(map->web.metadata),
-                                       "MO", "proxy_port")) != NULL)
-    {
-        nProxyPort = atol(pszTmp);
-    }
-    
-    if ((pszTmp = msOWSLookupMetadata2(&(lp->metadata), &(map->web.metadata),
-                                       "MO", "proxy_type")) != NULL)
-    {
-        
-        if (strcasecmp(pszTmp, "HTTP") == 0)
-            eProxyType = MS_HTTP;
-        else if (strcasecmp(pszTmp, "SOCKS5") == 0)
-            eProxyType = MS_SOCKS5;
-        else
-        {
-            msSetError(MS_WMSERR, "Invalid proxy_type metadata '%s' specified",
-                       "msPrepareWMSLayerRequest()", pszTmp);
-            return MS_FAILURE;
-        }
-    }
-    
-    if ((pszTmp = msOWSLookupMetadata2(&(lp->metadata), &(map->web.metadata),
-                                       "MO", "proxy_auth_type")) != NULL)
-    {
-        if (strcasecmp(pszTmp, "BASIC") == 0)
-            eProxyAuthType = MS_BASIC;
-        else if (strcasecmp(pszTmp, "DIGEST") == 0)
-            eProxyAuthType = MS_DIGEST;
-        else if (strcasecmp(pszTmp, "NTLM") == 0)
-            eProxyAuthType = MS_NTLM;
-        else if (strcasecmp(pszTmp, "ANY") == 0)
-            eProxyAuthType = MS_ANY;
-        else if (strcasecmp(pszTmp, "ANYSAFE") == 0)
-            eProxyAuthType = MS_ANYSAFE;
-        else
-        {
-            msSetError(MS_WMSERR, "Invalid proxy_auth_type metadata '%s' specified",
-                       "msPrepareWMSLayerRequest()", pszTmp);
-            return MS_FAILURE;
-        }
-    }
-    
-    
-    if ((pszTmp = msOWSLookupMetadata2(&(lp->metadata), &(map->web.metadata),
-                                       "MO", "proxy_username")) != NULL)
-    {
-        pszProxyUsername = msStrdup(pszTmp);
-    }
-    
-    if ((pszTmp = msOWSLookupMetadata2(&(lp->metadata), &(map->web.metadata),
-                                       "MO", "proxy_password")) != NULL)
-    {
-        pszProxyPassword = msDecryptStringTokens(map, pszTmp);
-        if (pszProxyPassword == NULL) {
-            return(MS_FAILURE);  /* An error should already have been produced */
-        }
-    }
-    
-    if ((pszTmp = msOWSLookupMetadata2(&(lp->metadata), &(map->web.metadata),
-                                       "MO", "auth_type")) != NULL)
-    {
-        if (strcasecmp(pszTmp, "BASIC") == 0)
-            eHttpAuthType = MS_BASIC;
-        else if (strcasecmp(pszTmp, "DIGEST") == 0)
-            eHttpAuthType = MS_DIGEST;
-        else if (strcasecmp(pszTmp, "NTLM") == 0)
-            eHttpAuthType = MS_NTLM;
-        else if (strcasecmp(pszTmp, "ANY") == 0)
-            eHttpAuthType = MS_ANY;
-        else if (strcasecmp(pszTmp, "ANYSAFE") == 0)
-            eHttpAuthType = MS_ANYSAFE;
-        else
-        {
-            msSetError(MS_WMSERR, "Invalid auth_type metadata '%s' specified",
-                       "msPrepareWMSLayerRequest()", pszTmp);
-            return MS_FAILURE;
-        }
-    }
-    
-    if ((pszTmp = msOWSLookupMetadata2(&(lp->metadata), &(map->web.metadata),
-                                       "MO", "auth_username")) != NULL)
-    {
-        pszHttpAuthUsername = msStrdup(pszTmp);
-    }
-    
-    if ((pszTmp = msOWSLookupMetadata2(&(lp->metadata), &(map->web.metadata),
-                                       "MO", "auth_password")) != NULL)
-    {
-        pszHttpAuthPassword = msDecryptStringTokens(map, pszTmp);
-        if (pszHttpAuthPassword == NULL) {
-            return(MS_FAILURE);  /* An error should already have been produced */
-        }
-    }
 
-/* ------------------------------------------------------------------
- * Check if we want to use in memory images instead of writing to disk.
- * ------------------------------------------------------------------ */
-    if ((pszTmp = msOWSLookupMetadata(&(lp->metadata), 
-                                      "MO", "cache_to_disk")) != NULL)
-    {
-        if( strcasecmp(pszTmp,"true") == 0
-            || strcasecmp(pszTmp,"on") == 0
-            || strcasecmp(pszTmp,"yes") == 0 )
-            bCacheToDisk = MS_TRUE;
-        else
-            bCacheToDisk = atoi(pszTmp);
-    }
+  /* ------------------------------------------------------------------
+   * Check if the request is empty, perhaps due to reprojection problems
+   * or wms_extents restrictions.
+   * ------------------------------------------------------------------ */
+  if ((nRequestType == WMS_GETMAP) && (bbox_width == 0 || bbox_height == 0) ) {
+    msFreeWmsParamsObj(&sThisWMSParams);
+    return MS_SUCCESS;  /* No overlap. */
+  }
+
+  /* ------------------------------------------------------------------
+   * Check if layer overlaps current view window (using wms_latlonboundingbox)
+   * ------------------------------------------------------------------ */
+  if ((pszTmp = msOWSLookupMetadata(&(lp->metadata),
+                                    "MO", "latlonboundingbox")) != NULL) {
+    char **tokens;
+    int n;
+    rectObj ext;
+
+    tokens = msStringSplit(pszTmp, ' ', &n);
+    if (tokens==NULL || n != 4) {
+      msSetError(MS_WMSCONNERR, "Wrong number of arguments for 'wms_latlonboundingbox' metadata.",
+                 "msDrawWMSLayer()");
+      msFreeWmsParamsObj(&sThisWMSParams);
+      return MS_FAILURE;
+    }
+
+    ext.minx = atof(tokens[0]);
+    ext.miny = atof(tokens[1]);
+    ext.maxx = atof(tokens[2]);
+    ext.maxy = atof(tokens[3]);
+
+    msFreeCharArray(tokens, n);
+
+    /* Reproject latlonboundingbox to the selected SRS for the layer and */
+    /* check if it overlaps the bbox that we calculated for the request */
+
+    msProjectRect(&(map->latlon), &(lp->projection), &ext);
+    if (!msRectOverlap(&bbox, &ext)) {
+      /* No overlap... nothing to do */
+
+      msFreeWmsParamsObj(&sThisWMSParams);
+      return MS_SUCCESS;  /* No overlap. */
+    }
+  }
+
+  /* ------------------------------------------------------------------
+   * check to see if a the metadata wms_connectiontimeout is set. If it is
+   * the case we will use it, else we use the default which is 30 seconds.
+   * First check the metadata in the layer object and then in the map object.
+   * ------------------------------------------------------------------ */
+  nTimeout = 30;  /* Default is 30 seconds  */
+  if ((pszTmp = msOWSLookupMetadata(&(lp->metadata),
+                                    "MO", "connectiontimeout")) != NULL) {
+    nTimeout = atoi(pszTmp);
+  } else if ((pszTmp = msOWSLookupMetadata(&(map->web.metadata),
+                       "MO", "connectiontimeout")) != NULL) {
+    nTimeout = atoi(pszTmp);
+  }
+
+  /* ------------------------------------------------------------------
+   * Check for authentication and proxying metadata. If the metadata is not found
+   * in the layer metadata, check the map-level metadata.
+   * ------------------------------------------------------------------ */
+  if ((pszTmp = msOWSLookupMetadata2(&(lp->metadata), &(map->web.metadata),
+                                     "MO", "proxy_host")) != NULL) {
+    pszProxyHost = msStrdup(pszTmp);
+  }
+
+  if ((pszTmp = msOWSLookupMetadata2(&(lp->metadata), &(map->web.metadata),
+                                     "MO", "proxy_port")) != NULL) {
+    nProxyPort = atol(pszTmp);
+  }
+
+  if ((pszTmp = msOWSLookupMetadata2(&(lp->metadata), &(map->web.metadata),
+                                     "MO", "proxy_type")) != NULL) {
+
+    if (strcasecmp(pszTmp, "HTTP") == 0)
+      eProxyType = MS_HTTP;
+    else if (strcasecmp(pszTmp, "SOCKS5") == 0)
+      eProxyType = MS_SOCKS5;
+    else {
+      msSetError(MS_WMSERR, "Invalid proxy_type metadata '%s' specified",
+                 "msPrepareWMSLayerRequest()", pszTmp);
+      return MS_FAILURE;
+    }
+  }
+
+  if ((pszTmp = msOWSLookupMetadata2(&(lp->metadata), &(map->web.metadata),
+                                     "MO", "proxy_auth_type")) != NULL) {
+    if (strcasecmp(pszTmp, "BASIC") == 0)
+      eProxyAuthType = MS_BASIC;
+    else if (strcasecmp(pszTmp, "DIGEST") == 0)
+      eProxyAuthType = MS_DIGEST;
+    else if (strcasecmp(pszTmp, "NTLM") == 0)
+      eProxyAuthType = MS_NTLM;
+    else if (strcasecmp(pszTmp, "ANY") == 0)
+      eProxyAuthType = MS_ANY;
+    else if (strcasecmp(pszTmp, "ANYSAFE") == 0)
+      eProxyAuthType = MS_ANYSAFE;
+    else {
+      msSetError(MS_WMSERR, "Invalid proxy_auth_type metadata '%s' specified",
+                 "msPrepareWMSLayerRequest()", pszTmp);
+      return MS_FAILURE;
+    }
+  }
+
+
+  if ((pszTmp = msOWSLookupMetadata2(&(lp->metadata), &(map->web.metadata),
+                                     "MO", "proxy_username")) != NULL) {
+    pszProxyUsername = msStrdup(pszTmp);
+  }
+
+  if ((pszTmp = msOWSLookupMetadata2(&(lp->metadata), &(map->web.metadata),
+                                     "MO", "proxy_password")) != NULL) {
+    pszProxyPassword = msDecryptStringTokens(map, pszTmp);
+    if (pszProxyPassword == NULL) {
+      return(MS_FAILURE);  /* An error should already have been produced */
+    }
+  }
+
+  if ((pszTmp = msOWSLookupMetadata2(&(lp->metadata), &(map->web.metadata),
+                                     "MO", "auth_type")) != NULL) {
+    if (strcasecmp(pszTmp, "BASIC") == 0)
+      eHttpAuthType = MS_BASIC;
+    else if (strcasecmp(pszTmp, "DIGEST") == 0)
+      eHttpAuthType = MS_DIGEST;
+    else if (strcasecmp(pszTmp, "NTLM") == 0)
+      eHttpAuthType = MS_NTLM;
+    else if (strcasecmp(pszTmp, "ANY") == 0)
+      eHttpAuthType = MS_ANY;
+    else if (strcasecmp(pszTmp, "ANYSAFE") == 0)
+      eHttpAuthType = MS_ANYSAFE;
+    else {
+      msSetError(MS_WMSERR, "Invalid auth_type metadata '%s' specified",
+                 "msPrepareWMSLayerRequest()", pszTmp);
+      return MS_FAILURE;
+    }
+  }
+
+  if ((pszTmp = msOWSLookupMetadata2(&(lp->metadata), &(map->web.metadata),
+                                     "MO", "auth_username")) != NULL) {
+    pszHttpAuthUsername = msStrdup(pszTmp);
+  }
+
+  if ((pszTmp = msOWSLookupMetadata2(&(lp->metadata), &(map->web.metadata),
+                                     "MO", "auth_password")) != NULL) {
+    pszHttpAuthPassword = msDecryptStringTokens(map, pszTmp);
+    if (pszHttpAuthPassword == NULL) {
+      return(MS_FAILURE);  /* An error should already have been produced */
+    }
+  }
+
+  /* ------------------------------------------------------------------
+   * Check if we want to use in memory images instead of writing to disk.
+   * ------------------------------------------------------------------ */
+  if ((pszTmp = msOWSLookupMetadata(&(lp->metadata),
+                                    "MO", "cache_to_disk")) != NULL) {
+    if( strcasecmp(pszTmp,"true") == 0
+        || strcasecmp(pszTmp,"on") == 0
+        || strcasecmp(pszTmp,"yes") == 0 )
+      bCacheToDisk = MS_TRUE;
     else
-        bCacheToDisk = MS_FALSE;
-
-    if( bCacheToDisk )
-    {
-        /* We'll store the remote server's response to a tmp file. */
-        if (map->web.imagepath == NULL || strlen(map->web.imagepath) == 0)
-        {
-            msSetError(MS_WMSERR, 
-                       "WEB.IMAGEPATH must be set to use WMS client connections.",
-                       "msPrepareWMSLayerRequest()");
-            return MS_FAILURE;
-        }
-    }
-
-/* ------------------------------------------------------------------
- * Check if layer can be merged with previous WMS layer requests
- * Metadata wms_force_separate_request can be set to 1 to prevent this
- * this layer from being combined with any other layer.
- * ------------------------------------------------------------------ */
-    bForceSeparateRequest = MS_FALSE;
-    if ((pszTmp = msOWSLookupMetadata(&(lp->metadata), 
-                                      "MO", "force_separate_request")) != NULL)
-    {
-        bForceSeparateRequest = atoi(pszTmp); 
-    }
-    bOkToMerge = MS_FALSE;
-    if (!bForceSeparateRequest &&
-        lastconnectiontype == MS_WMS &&
-        psLastWMSParams != NULL &&
-        sThisWMSParams.numparams == psLastWMSParams->numparams &&
-        strcmp(sThisWMSParams.onlineresource, 
-               psLastWMSParams->onlineresource) == 0)
-    {
-        const char *key, *value1, *value2;
-        bOkToMerge = MS_TRUE;
-
-        key = msFirstKeyFromHashTable(sThisWMSParams.params);
-        while (key != NULL && bOkToMerge == MS_TRUE)
-        {
-            /* Skip parameters whose values can be different */
-            if (!(strcmp(key, "LAYERS") == 0 ||
-                  strcmp(key, "QUERY_LAYERS") == 0 ||
-                  strcmp(key, "STYLES") == 0) )
-            {
-                value1 = msLookupHashTable(psLastWMSParams->params, key);
-                value2 = msLookupHashTable(sThisWMSParams.params, key);
-
-                if (value1==NULL || value2==NULL ||
-                    strcmp(value1, value2) != 0)
-                {
-                    bOkToMerge = MS_FALSE;
-                    break;
-                }
-            }
-            key = msNextKeyFromHashTable(sThisWMSParams.params, key);
-        }
-    }
-
-/*------------------------------------------------------------------
- * Check to see if there's a HTTP Cookie to forward
- * If Cookie differ between the two connection, it's NOT OK to merge
- * the connection
- * ------------------------------------------------------------------ */
-    if ((pszTmp = msOWSLookupMetadata(&(lp->metadata), 
-                                      "MO", "http_cookie")) != NULL)
-    {
-        if(strcasecmp(pszTmp, "forward") == 0)
-        {
-            pszTmp= msLookupHashTable(&(map->web.metadata),"http_cookie_data");
-            if(pszTmp != NULL)
-            {
-                pszHTTPCookieData = msStrdup(pszTmp);
-            }
-        }
-        else
-        {
-            pszHTTPCookieData = msStrdup(pszTmp);
-        }
-    }
-    else if ((pszTmp = msOWSLookupMetadata(&(map->web.metadata), 
-                                           "MO", "http_cookie")) != NULL)
-    {
-        if(strcasecmp(pszTmp, "forward") == 0)
-        {
-            pszTmp= msLookupHashTable(&(map->web.metadata),"http_cookie_data");
-            if(pszTmp != NULL)
-            {
-                pszHTTPCookieData = msStrdup(pszTmp);
-            }
-        }
-        else
-        {
-            pszHTTPCookieData = msStrdup(pszTmp);
+      bCacheToDisk = atoi(pszTmp);
+  } else
+    bCacheToDisk = MS_FALSE;
+
+  if( bCacheToDisk ) {
+    /* We'll store the remote server's response to a tmp file. */
+    if (map->web.imagepath == NULL || strlen(map->web.imagepath) == 0) {
+      msSetError(MS_WMSERR,
+                 "WEB.IMAGEPATH must be set to use WMS client connections.",
+                 "msPrepareWMSLayerRequest()");
+      return MS_FAILURE;
+    }
+  }
+
+  /* ------------------------------------------------------------------
+   * Check if layer can be merged with previous WMS layer requests
+   * Metadata wms_force_separate_request can be set to 1 to prevent this
+   * this layer from being combined with any other layer.
+   * ------------------------------------------------------------------ */
+  bForceSeparateRequest = MS_FALSE;
+  if ((pszTmp = msOWSLookupMetadata(&(lp->metadata),
+                                    "MO", "force_separate_request")) != NULL) {
+    bForceSeparateRequest = atoi(pszTmp);
+  }
+  bOkToMerge = MS_FALSE;
+  if (!bForceSeparateRequest &&
+      lastconnectiontype == MS_WMS &&
+      psLastWMSParams != NULL &&
+      sThisWMSParams.numparams == psLastWMSParams->numparams &&
+      strcmp(sThisWMSParams.onlineresource,
+             psLastWMSParams->onlineresource) == 0) {
+    const char *key, *value1, *value2;
+    bOkToMerge = MS_TRUE;
+
+    key = msFirstKeyFromHashTable(sThisWMSParams.params);
+    while (key != NULL && bOkToMerge == MS_TRUE) {
+      /* Skip parameters whose values can be different */
+      if (!(strcmp(key, "LAYERS") == 0 ||
+            strcmp(key, "QUERY_LAYERS") == 0 ||
+            strcmp(key, "STYLES") == 0) ) {
+        value1 = msLookupHashTable(psLastWMSParams->params, key);
+        value2 = msLookupHashTable(sThisWMSParams.params, key);
+
+        if (value1==NULL || value2==NULL ||
+            strcmp(value1, value2) != 0) {
+          bOkToMerge = MS_FALSE;
+          break;
         }
-    }
-
-    if(bOkToMerge && pszHTTPCookieData != sThisWMSParams.httpcookiedata)
-    {
-        if(pszHTTPCookieData == NULL || sThisWMSParams.httpcookiedata == NULL)
-        {
-            bOkToMerge = MS_FALSE;
-        }
-        if(strcmp(pszHTTPCookieData, sThisWMSParams.httpcookiedata) != 0)
-        {
-            bOkToMerge = MS_FALSE;
-        }
-    }
-
-    if (bOkToMerge)
-    {
-        /* Merge both requests into sThisWMSParams
-         */
-        const char *value1, *value2;
-        char *keys[] = {"LAYERS", "QUERY_LAYERS", "STYLES"};
-        int i;
-
-        for(i=0; i<3; i++)
-        {
-            value1 = msLookupHashTable(psLastWMSParams->params, keys[i]);
-            value2 = msLookupHashTable(sThisWMSParams.params, keys[i]);
-            if (value1 && value2)
-            {
-                char *pszBuf;
-                int nLen;
-
-                nLen = strlen(value1) + strlen(value2) +2;
-                pszBuf = malloc(nLen);
-                MS_CHECK_ALLOC(pszBuf, nLen, MS_FAILURE);
-
-                snprintf(pszBuf, nLen, "%s,%s", value1, value2);
-                msSetWMSParamString(&sThisWMSParams, keys[i], pszBuf,MS_FALSE);
-
-                /* This key existed already, we don't want it counted twice */
-                sThisWMSParams.numparams--;
-
-                msFree(pszBuf);
-            }
-        }
-    }
-
-        
-/* ------------------------------------------------------------------
- * Build new request URL
- * ------------------------------------------------------------------ */
-    pszURL = msBuildURLFromWMSParams(&sThisWMSParams);
-
-    if (bOkToMerge && (*numRequests)>0)
-    {
-/* ------------------------------------------------------------------
- * Update the last request in the array:  (*numRequests)-1
- * ------------------------------------------------------------------ */
-        msFree(pasReqInfo[(*numRequests)-1].pszGetUrl);
-        pasReqInfo[(*numRequests)-1].pszGetUrl = pszURL;
-        pszURL = NULL;
-        pasReqInfo[(*numRequests)-1].debug |= lp->debug;
-        if (nTimeout > pasReqInfo[(*numRequests)-1].nTimeout)
-            pasReqInfo[(*numRequests)-1].nTimeout = nTimeout;
-    }
-    else
-    {
-/* ------------------------------------------------------------------
- * Add a request to the array (already preallocated)
- * ------------------------------------------------------------------ */
-        pasReqInfo[(*numRequests)].nLayerId = nLayerId;
-        pasReqInfo[(*numRequests)].pszGetUrl = pszURL;
-        pszURL = NULL;
-        pasReqInfo[(*numRequests)].pszHTTPCookieData = pszHTTPCookieData;
-        pszHTTPCookieData = NULL;
-        if( bCacheToDisk )
-            pasReqInfo[(*numRequests)].pszOutputFile =
-                msTmpFile(map, map->mappath, NULL, "img.tmp");
-        else
-            pasReqInfo[(*numRequests)].pszOutputFile = NULL;
-        pasReqInfo[(*numRequests)].nStatus = 0;
-        pasReqInfo[(*numRequests)].nTimeout = nTimeout;
-        pasReqInfo[(*numRequests)].bbox   = bbox;
-        pasReqInfo[(*numRequests)].width  = bbox_width;
-        pasReqInfo[(*numRequests)].height = bbox_height;
-        pasReqInfo[(*numRequests)].debug = lp->debug;
-        
-        pasReqInfo[(*numRequests)].pszProxyAddress  = pszProxyHost;
-        pasReqInfo[(*numRequests)].nProxyPort       = nProxyPort;
-        pasReqInfo[(*numRequests)].eProxyType       = eProxyType;
-        pasReqInfo[(*numRequests)].eProxyAuthType   = eProxyAuthType;
-        pasReqInfo[(*numRequests)].pszProxyUsername = pszProxyUsername;
-        pasReqInfo[(*numRequests)].pszProxyPassword = pszProxyPassword;
-        pasReqInfo[(*numRequests)].eHttpAuthType    = eHttpAuthType;
-        pasReqInfo[(*numRequests)].pszHttpUsername  = pszHttpAuthUsername;
-        pasReqInfo[(*numRequests)].pszHttpPassword  = pszHttpAuthPassword;
-        
-        (*numRequests)++;
-    }
-
+      }
+      key = msNextKeyFromHashTable(sThisWMSParams.params, key);
+    }
+  }
+
+  /*------------------------------------------------------------------
+   * Check to see if there's a HTTP Cookie to forward
+   * If Cookie differ between the two connection, it's NOT OK to merge
+   * the connection
+   * ------------------------------------------------------------------ */
+  if ((pszTmp = msOWSLookupMetadata(&(lp->metadata),
+                                    "MO", "http_cookie")) != NULL) {
+    if(strcasecmp(pszTmp, "forward") == 0) {
+      pszTmp= msLookupHashTable(&(map->web.metadata),"http_cookie_data");
+      if(pszTmp != NULL) {
+        pszHTTPCookieData = msStrdup(pszTmp);
+      }
+    } else {
+      pszHTTPCookieData = msStrdup(pszTmp);
+    }
+  } else if ((pszTmp = msOWSLookupMetadata(&(map->web.metadata),
+                       "MO", "http_cookie")) != NULL) {
+    if(strcasecmp(pszTmp, "forward") == 0) {
+      pszTmp= msLookupHashTable(&(map->web.metadata),"http_cookie_data");
+      if(pszTmp != NULL) {
+        pszHTTPCookieData = msStrdup(pszTmp);
+      }
+    } else {
+      pszHTTPCookieData = msStrdup(pszTmp);
+    }
+  }
+
+  if(bOkToMerge && pszHTTPCookieData != sThisWMSParams.httpcookiedata) {
+    if(pszHTTPCookieData == NULL || sThisWMSParams.httpcookiedata == NULL) {
+      bOkToMerge = MS_FALSE;
+    }
+    if(strcmp(pszHTTPCookieData, sThisWMSParams.httpcookiedata) != 0) {
+      bOkToMerge = MS_FALSE;
+    }
+  }
+
+  if (bOkToMerge) {
+    /* Merge both requests into sThisWMSParams
+     */
+    const char *value1, *value2;
+    char *keys[] = {"LAYERS", "QUERY_LAYERS", "STYLES"};
+    int i;
+
+    for(i=0; i<3; i++) {
+      value1 = msLookupHashTable(psLastWMSParams->params, keys[i]);
+      value2 = msLookupHashTable(sThisWMSParams.params, keys[i]);
+      if (value1 && value2) {
+        char *pszBuf;
+        int nLen;
 
-/* ------------------------------------------------------------------
- * Replace contents of psLastWMSParams with sThisWMSParams 
- * unless bForceSeparateRequest is set in which case we make it empty
- * ------------------------------------------------------------------ */
-    if (psLastWMSParams)
-    {
-        msFreeWmsParamsObj(psLastWMSParams);
-        if (!bForceSeparateRequest)
-            *psLastWMSParams = sThisWMSParams;
-        else
-            msInitWmsParamsObj(psLastWMSParams);
-    }
+        nLen = strlen(value1) + strlen(value2) +2;
+        pszBuf = malloc(nLen);
+        MS_CHECK_ALLOC(pszBuf, nLen, MS_FAILURE);
+
+        snprintf(pszBuf, nLen, "%s,%s", value1, value2);
+        msSetWMSParamString(&sThisWMSParams, keys[i], pszBuf,MS_FALSE);
+
+        /* This key existed already, we don't want it counted twice */
+        sThisWMSParams.numparams--;
+
+        msFree(pszBuf);
+      }
+    }
+  }
+
+
+  /* ------------------------------------------------------------------
+   * Build new request URL
+   * ------------------------------------------------------------------ */
+  pszURL = msBuildURLFromWMSParams(&sThisWMSParams);
+
+  if (bOkToMerge && (*numRequests)>0) {
+    /* ------------------------------------------------------------------
+     * Update the last request in the array:  (*numRequests)-1
+     * ------------------------------------------------------------------ */
+    msFree(pasReqInfo[(*numRequests)-1].pszGetUrl);
+    pasReqInfo[(*numRequests)-1].pszGetUrl = pszURL;
+    pszURL = NULL;
+    pasReqInfo[(*numRequests)-1].debug |= lp->debug;
+    if (nTimeout > pasReqInfo[(*numRequests)-1].nTimeout)
+      pasReqInfo[(*numRequests)-1].nTimeout = nTimeout;
+  } else {
+    /* ------------------------------------------------------------------
+     * Add a request to the array (already preallocated)
+     * ------------------------------------------------------------------ */
+    pasReqInfo[(*numRequests)].nLayerId = nLayerId;
+    pasReqInfo[(*numRequests)].pszGetUrl = pszURL;
+
+    pszURL = NULL;
+    pasReqInfo[(*numRequests)].pszHTTPCookieData = pszHTTPCookieData;
+    pszHTTPCookieData = NULL;
+    if( bCacheToDisk ) {
+      pasReqInfo[(*numRequests)].pszOutputFile =
+        msTmpFile(map, map->mappath, NULL, "wms.tmp");
+    } else
+      pasReqInfo[(*numRequests)].pszOutputFile = NULL;
+    pasReqInfo[(*numRequests)].nStatus = 0;
+    pasReqInfo[(*numRequests)].nTimeout = nTimeout;
+    pasReqInfo[(*numRequests)].bbox   = bbox;
+    pasReqInfo[(*numRequests)].width  = bbox_width;
+    pasReqInfo[(*numRequests)].height = bbox_height;
+    pasReqInfo[(*numRequests)].debug = lp->debug;
+
+    pasReqInfo[(*numRequests)].pszProxyAddress  = pszProxyHost;
+    pasReqInfo[(*numRequests)].nProxyPort       = nProxyPort;
+    pasReqInfo[(*numRequests)].eProxyType       = eProxyType;
+    pasReqInfo[(*numRequests)].eProxyAuthType   = eProxyAuthType;
+    pasReqInfo[(*numRequests)].pszProxyUsername = pszProxyUsername;
+    pasReqInfo[(*numRequests)].pszProxyPassword = pszProxyPassword;
+    pasReqInfo[(*numRequests)].eHttpAuthType    = eHttpAuthType;
+    pasReqInfo[(*numRequests)].pszHttpUsername  = pszHttpAuthUsername;
+    pasReqInfo[(*numRequests)].pszHttpPassword  = pszHttpAuthPassword;
+
+    (*numRequests)++;
+  }
+
+
+  /* ------------------------------------------------------------------
+   * Replace contents of psLastWMSParams with sThisWMSParams
+   * unless bForceSeparateRequest is set in which case we make it empty
+   * ------------------------------------------------------------------ */
+  if (psLastWMSParams) {
+    msFreeWmsParamsObj(psLastWMSParams);
+    if (!bForceSeparateRequest)
+      *psLastWMSParams = sThisWMSParams;
     else
-    {
-        /* Can't copy it, so we just free it */
-        msFreeWmsParamsObj(&sThisWMSParams);
-    }
+      msInitWmsParamsObj(psLastWMSParams);
+  } else {
+    /* Can't copy it, so we just free it */
+    msFreeWmsParamsObj(&sThisWMSParams);
+  }
 
-    return MS_SUCCESS;
+  return MS_SUCCESS;
 
 #else
-/* ------------------------------------------------------------------
- * WMS CONNECTION Support not included...
- * ------------------------------------------------------------------ */
-  msSetError(MS_WMSCONNERR, "WMS CLIENT CONNECTION support is not available.", 
+  /* ------------------------------------------------------------------
+   * WMS CONNECTION Support not included...
+   * ------------------------------------------------------------------ */
+  msSetError(MS_WMSCONNERR, "WMS CLIENT CONNECTION support is not available.",
              "msDrawWMSLayer()");
   return(MS_FAILURE);
 
@@ -1387,242 +1321,326 @@ int msPrepareWMSLayerRequest(int nLayerId, mapObj *map, layerObj *lp,
  *
  **********************************************************************/
 
-int msDrawWMSLayerLow(int nLayerId, httpRequestObj *pasReqInfo, 
-                      int numRequests, mapObj *map, layerObj *lp, imageObj *img) 
+int msDrawWMSLayerLow(int nLayerId, httpRequestObj *pasReqInfo,
+                      int numRequests, mapObj *map, layerObj *lp, imageObj *img)
 {
 #ifdef USE_WMS_LYR
-    int status = MS_SUCCESS;
-    int iReq = -1;
-    char szPath[MS_MAXPATHLEN];
-    int currenttype;
-    int currentconnectiontype;
-    int numclasses;
-    char *mem_filename = NULL;
-
-/* ------------------------------------------------------------------
- * Find the request info for this layer in the array, based on nLayerId
- * ------------------------------------------------------------------ */
-    for(iReq=0; iReq<numRequests; iReq++)
-    {
-        if (pasReqInfo[iReq].nLayerId == nLayerId)
-            break;
-    }
+  int status = MS_SUCCESS;
+  int iReq = -1;
+  char szPath[MS_MAXPATHLEN];
+  int currenttype;
+  int currentconnectiontype;
+  int numclasses;
+  char *mem_filename = NULL;
+
+  /* ------------------------------------------------------------------
+   * Find the request info for this layer in the array, based on nLayerId
+   * ------------------------------------------------------------------ */
+  for(iReq=0; iReq<numRequests; iReq++) {
+    if (pasReqInfo[iReq].nLayerId == nLayerId)
+      break;
+  }
+
+  if (iReq == numRequests) {
+    /* This layer was skipped or was included in a multi-layers
+     * request ... nothing to do.
+     */
+    return MS_SUCCESS;
+  }
+
+  if ( !MS_HTTP_SUCCESS( pasReqInfo[iReq].nStatus ) ) {
+    /* ====================================================================
+          Failed downloading layer... we log an error but we still return
+          SUCCESS here so that the layer is only skipped intead of aborting
+          the whole draw map.
+     ==================================================================== */
+    msSetError(MS_WMSERR,
+               "WMS GetMap request failed for layer '%s' (Status %d: %s).",
+               "msDrawWMSLayerLow()",
+               (lp->name?lp->name:"(null)"),
+               pasReqInfo[iReq].nStatus, pasReqInfo[iReq].pszErrBuf );
 
-    if (iReq == numRequests)
-    {
-        /* This layer was skipped or was included in a multi-layers 
-         * request ... nothing to do.
+    return MS_SUCCESS;
+  }
+
+  /* ------------------------------------------------------------------
+   * Check the Content-Type of the response to see if we got an exception,
+   * if yes then try to parse it and pass the info to msSetError().
+   * We log an error but we still return SUCCESS here so that the layer
+   * is only skipped intead of aborting the whole draw map.
+   * ------------------------------------------------------------------ */
+  if (pasReqInfo[iReq].pszContentType &&
+      (strcmp(pasReqInfo[iReq].pszContentType, "text/xml") == 0 ||
+       strcmp(pasReqInfo[iReq].pszContentType, "application/vnd.ogc.se_xml") == 0)) {
+    FILE *fp;
+    char szBuf[MS_BUFFER_LENGTH];
+
+    if( pasReqInfo[iReq].pszOutputFile ) {
+      fp = fopen(pasReqInfo[iReq].pszOutputFile, "r");
+      if (fp) {
+        /* TODO: For now we'll only read the first chunk and return it
+         * via msSetError()... we should really try to parse the XML
+         * and extract the exception code/message though
          */
-        return MS_SUCCESS;  
-    }
-
-    if ( !MS_HTTP_SUCCESS( pasReqInfo[iReq].nStatus ) )
-    {
-/* ==================================================================== 
-      Failed downloading layer... we log an error but we still return 
-      SUCCESS here so that the layer is only skipped intead of aborting
-      the whole draw map.
- ==================================================================== */
-        msSetError(MS_WMSERR, 
-                   "WMS GetMap request failed for layer '%s' (Status %d: %s).",
-                   "msDrawWMSLayerLow()", 
-                   (lp->name?lp->name:"(null)"), 
-                   pasReqInfo[iReq].nStatus, pasReqInfo[iReq].pszErrBuf );
-
-        return MS_SUCCESS;
-    }
+        size_t nSize;
 
-/* ------------------------------------------------------------------
- * Check the content-type of the response to see if we got an exception,
- * if yes then try to parse it and pass the info to msSetError().
- * We log an error but we still return SUCCESS here so that the layer 
- * is only skipped intead of aborting the whole draw map.
- * ------------------------------------------------------------------ */
-    if (pasReqInfo[iReq].pszContentType &&
-        (strcmp(pasReqInfo[iReq].pszContentType, "text/xml") == 0 ||
-         strcmp(pasReqInfo[iReq].pszContentType, "application/vnd.ogc.se_xml") == 0))
-    {
-        FILE *fp;
-        char szBuf[MS_BUFFER_LENGTH];
-        
-        if( pasReqInfo[iReq].pszOutputFile )
-        {
-            fp = fopen(pasReqInfo[iReq].pszOutputFile, "r");
-            if (fp)
-            {
-                /* TODO: For now we'll only read the first chunk and return it
-                 * via msSetError()... we should really try to parse the XML
-                 * and extract the exception code/message though
-                 */
-                size_t nSize;
-                
-                nSize = fread(szBuf, sizeof(char), MS_BUFFER_LENGTH-1, fp);
-                if (nSize >= 0 && nSize < MS_BUFFER_LENGTH)
-                    szBuf[nSize] = '\0';
-                else
-                {
-                    strlcpy(szBuf, "(!!!)", sizeof(szBuf)); /* This should never happen */
-                }
-                
-                fclose(fp);
-                
-                /* We're done with the remote server's response... delete it. */
-                if (!lp->debug)
-                    unlink(pasReqInfo[iReq].pszOutputFile);
-            }
-            else
-            {
-                strlcpy(szBuf, "(Failed to open exception response)", sizeof(szBuf));
-            }
-        }
-        else
-        {
-            strlcpy( szBuf, pasReqInfo[iReq].result_data, MS_BUFFER_LENGTH );
+        nSize = fread(szBuf, sizeof(char), MS_BUFFER_LENGTH-1, fp);
+        if (nSize < MS_BUFFER_LENGTH)
+          szBuf[nSize] = '\0';
+        else {
+          strlcpy(szBuf, "(!!!)", sizeof(szBuf)); /* This should never happen */
         }
 
-        if (lp->debug)
-            msDebug("WMS GetMap request got XML exception for layer '%s': %s.",
-                    (lp->name?lp->name:"(null)"), szBuf );
+        fclose(fp);
 
-        msSetError(MS_WMSERR, 
-                   "WMS GetMap request got XML exception for layer '%s': %s.",
-                   "msDrawWMSLayerLow()", 
-                   (lp->name?lp->name:"(null)"), szBuf );
-
-        return MS_SUCCESS;
+        /* We're done with the remote server's response... delete it. */
+        if (!lp->debug)
+          unlink(pasReqInfo[iReq].pszOutputFile);
+      } else {
+        strlcpy(szBuf, "(Failed to open exception response)", sizeof(szBuf));
+      }
+    } else {
+      strlcpy( szBuf, pasReqInfo[iReq].result_data, MS_BUFFER_LENGTH );
     }
 
-/* ------------------------------------------------------------------
- * If the output was written to a memory buffer, then we will need
- * to attach a "VSI" name to this buffer.
- * ------------------------------------------------------------------ */
-    if( pasReqInfo[iReq].pszOutputFile == NULL )
-    {
-        CleanVSIDir( "/vsimem/msout" );
-        mem_filename = msTmpFile(map, NULL, "/vsimem/msout/", "img.tmp" );
-        
-        VSIFCloseL( 
-            VSIFileFromMemBuffer( mem_filename, 
-                                  (GByte*) pasReqInfo[iReq].result_data,
-                                  (vsi_l_offset) pasReqInfo[iReq].result_size,
-                                  FALSE ) );
-    }
+    if (lp->debug)
+      msDebug("WMS GetMap request got XML exception for layer '%s': %s.",
+              (lp->name?lp->name:"(null)"), szBuf );
 
-/* ------------------------------------------------------------------
- * Prepare layer for drawing, reprojecting the image received from the
- * server if needed...
- * ------------------------------------------------------------------ */
-    /* keep the current type that will be restored at the end of this  */
-    /* function. */
-    currenttype = lp->type;
-    currentconnectiontype = lp->connectiontype;
-    lp->type = MS_LAYER_RASTER;
-    lp->connectiontype = MS_SHAPEFILE;
-
-    /* set the classes to 0 so that It won't do client side */
-    /* classification if an sld was set. */
-    numclasses = lp->numclasses;
-
-    /* ensure the file connection is closed right away after the layer */ 
-    /* is rendered */ 
-    msLayerSetProcessingKey( lp, "CLOSE_CONNECTION", "NORMAL");
-
-    if (msOWSLookupMetadata(&(lp->metadata), "MO", "sld_body") ||
-        msOWSLookupMetadata(&(lp->metadata), "MO", "sld_url"))        
-      lp->numclasses = 0;
-
-    if (lp->data) free(lp->data);
-    if( mem_filename != NULL )
-        lp->data = mem_filename;
-    else
-        lp->data =  msStrdup(pasReqInfo[iReq].pszOutputFile);
+    msSetError(MS_WMSERR,
+               "WMS GetMap request got XML exception for layer '%s': %s.",
+               "msDrawWMSLayerLow()",
+               (lp->name?lp->name:"(null)"), szBuf );
 
-    /* #3138 If PROCESSING "RESAMPLE=..." is set we cannot use the simple case */
-    if (!msProjectionsDiffer(&(map->projection), &(lp->projection)) && 
-         (msLayerGetProcessingKey(lp, "RESAMPLE") == NULL) )
-    {
-        /* The simple case... no reprojection needed... render layer directly. */
-        lp->transform = MS_FALSE;
-        /* if (msDrawRasterLayerLow(map, lp, img) != 0) */
-        /* status = MS_FAILURE; */
-         if (msDrawLayer(map, lp, img) != 0)
-            status = MS_FAILURE;
-    }
-    else
-    {
-        FILE *fp;
-        char *wldfile;
-        /* OK, we have to resample the raster to map projection... */
-        lp->transform = MS_TRUE;
-        msLayerSetProcessingKey( lp, "LOAD_WHOLE_IMAGE", "YES" ); 
-
-        /* Create a world file with raster extents */
-        /* One line per value, in this order: cx, 0, 0, cy, ulx, uly */
-        wldfile = msBuildPath(szPath, lp->map->mappath, lp->data);
-        if (wldfile && (strlen(wldfile)>=3))    
-            strcpy(wldfile+strlen(wldfile)-3, "wld");
-        if (wldfile && (fp = VSIFOpenL(wldfile, "wt")) != NULL)
-        {
-            double dfCellSizeX = MS_CELLSIZE(pasReqInfo[iReq].bbox.minx,
-                                             pasReqInfo[iReq].bbox.maxx, 
-                                             pasReqInfo[iReq].width);	
-            double dfCellSizeY = MS_CELLSIZE(pasReqInfo[iReq].bbox.maxy,
-                                             pasReqInfo[iReq].bbox.miny, 
-                                             pasReqInfo[iReq].height);
-            char world_text[5000];
-
-            sprintf( world_text, "%.12f\n0\n0\n%.12f\n%.12f\n%.12f\n",
-                     dfCellSizeX, 
-                     dfCellSizeY,
-                     pasReqInfo[iReq].bbox.minx + dfCellSizeX * 0.5,
-                     pasReqInfo[iReq].bbox.maxy + dfCellSizeY * 0.5 );
-
-            VSIFWriteL( world_text, 1, strlen(world_text), fp );
-            VSIFCloseL( fp );
-
-            /* GDAL should be called to reproject automatically. */
-            if (msDrawLayer(map, lp, img) != 0)
-                status = MS_FAILURE;
-
-            if (!lp->debug)
-                VSIUnlink( wldfile );
-        }
-        else
-        {
-            msSetError(MS_WMSCONNERR, 
-                       "Unable to create wld file for WMS slide.", 
-                       "msDrawWMSLayer()");
-            status = MS_FAILURE;
-        }
-
-    } 
+    return MS_SUCCESS;
+  }
+
+  /* ------------------------------------------------------------------
+   * If the output was written to a memory buffer, then we will need
+   * to attach a "VSI" name to this buffer.
+   * ------------------------------------------------------------------ */
+  if( pasReqInfo[iReq].pszOutputFile == NULL ) {
+    CleanVSIDir( "/vsimem/msout" );
+    mem_filename = msTmpFile(map, NULL, "/vsimem/msout/", "img.tmp" );
+
+    VSIFCloseL(
+      VSIFileFromMemBuffer( mem_filename,
+                            (GByte*) pasReqInfo[iReq].result_data,
+                            (vsi_l_offset) pasReqInfo[iReq].result_size,
+                            FALSE ) );
+  }
+
+  /* ------------------------------------------------------------------
+   * Prepare layer for drawing, reprojecting the image received from the
+   * server if needed...
+   * ------------------------------------------------------------------ */
+  /* keep the current type that will be restored at the end of this  */
+  /* function. */
+  currenttype = lp->type;
+  currentconnectiontype = lp->connectiontype;
+  lp->type = MS_LAYER_RASTER;
+  lp->connectiontype = MS_SHAPEFILE;
+
+  /* set the classes to 0 so that It won't do client side */
+  /* classification if an sld was set. */
+  numclasses = lp->numclasses;
+
+  /* ensure the file connection is closed right away after the layer */
+  /* is rendered */
+  msLayerSetProcessingKey( lp, "CLOSE_CONNECTION", "NORMAL");
+
+  if (msOWSLookupMetadata(&(lp->metadata), "MO", "sld_body") ||
+      msOWSLookupMetadata(&(lp->metadata), "MO", "sld_url"))
+    lp->numclasses = 0;
+
+  if (lp->data) free(lp->data);
+  if( mem_filename != NULL )
+    lp->data = mem_filename;
+  else
+    lp->data =  msStrdup(pasReqInfo[iReq].pszOutputFile);
+
+  /* #3138 If PROCESSING "RESAMPLE=..." is set we cannot use the simple case */
+  if (!msProjectionsDiffer(&(map->projection), &(lp->projection)) &&
+      (msLayerGetProcessingKey(lp, "RESAMPLE") == NULL) ) {
+    /* The simple case... no reprojection needed... render layer directly. */
+    lp->transform = MS_FALSE;
+    /* if (msDrawRasterLayerLow(map, lp, img) != 0) */
+    /* status = MS_FAILURE; */
+    if (msDrawLayer(map, lp, img) != 0)
+      status = MS_FAILURE;
+  } else {
+    FILE *fp;
+    char *wldfile;
+    /* OK, we have to resample the raster to map projection... */
+    lp->transform = MS_TRUE;
+    msLayerSetProcessingKey( lp, "LOAD_WHOLE_IMAGE", "YES" );
+
+    /* Create a world file with raster extents */
+    /* One line per value, in this order: cx, 0, 0, cy, ulx, uly */
+    wldfile = msBuildPath(szPath, lp->map->mappath, lp->data);
+    if (wldfile && (strlen(wldfile)>=3))
+      strcpy(wldfile+strlen(wldfile)-3, "wld");
+    if (wldfile && (fp = VSIFOpenL(wldfile, "wt")) != NULL) {
+      double dfCellSizeX = MS_CELLSIZE(pasReqInfo[iReq].bbox.minx,
+                                       pasReqInfo[iReq].bbox.maxx,
+                                       pasReqInfo[iReq].width);
+      double dfCellSizeY = MS_CELLSIZE(pasReqInfo[iReq].bbox.maxy,
+                                       pasReqInfo[iReq].bbox.miny,
+                                       pasReqInfo[iReq].height);
+      char world_text[5000];
+
+      sprintf( world_text, "%.12f\n0\n0\n%.12f\n%.12f\n%.12f\n",
+               dfCellSizeX,
+               dfCellSizeY,
+               pasReqInfo[iReq].bbox.minx + dfCellSizeX * 0.5,
+               pasReqInfo[iReq].bbox.maxy + dfCellSizeY * 0.5 );
+
+      VSIFWriteL( world_text, 1, strlen(world_text), fp );
+      VSIFCloseL( fp );
+
+      /* GDAL should be called to reproject automatically. */
+      if (msDrawLayer(map, lp, img) != 0)
+        status = MS_FAILURE;
+
+      if (!lp->debug)
+        VSIUnlink( wldfile );
+    } else {
+      msSetError(MS_WMSCONNERR,
+                 "Unable to create wld file for WMS slide.",
+                 "msDrawWMSLayer()");
+      status = MS_FAILURE;
+    }
+
+  }
+
+  /* We're done with the remote server's response... delete it. */
+  if (!lp->debug)
+    VSIUnlink(lp->data);
+
+  /* restore prveious type */
+  lp->type = currenttype;
+  lp->connectiontype = currentconnectiontype;
+
+  /* restore previous numclasses */
+  lp->numclasses = numclasses;
+
+  free(lp->data);
+  lp->data = NULL;
+
+  return status;
 
-    /* We're done with the remote server's response... delete it. */
-    if (!lp->debug)
-        VSIUnlink(lp->data);
+#else
+  /* ------------------------------------------------------------------
+   * WMS CONNECTION Support not included...
+   * ------------------------------------------------------------------ */
+  msSetError(MS_WMSCONNERR, "WMS CLIENT CONNECTION support is not available.",
+             "msDrawWMSLayer()");
+  return(MS_FAILURE);
 
-    /* restore prveious type */
-    lp->type = currenttype;
-    lp->connectiontype = currentconnectiontype;
+#endif /* USE_WMS_LYR */
 
-    /* restore previous numclasses */
-    lp->numclasses = numclasses;
+}
 
-    free(lp->data);
-    lp->data = NULL;
 
-    return status;
+int msWMSLayerExecuteRequest(mapObj *map, int nOWSLayers, int nClickX, int nClickY,
+                             int nFeatureCount, const char *pszInfoFormat, int type)
+{
+#ifdef USE_WMS_LYR
 
+  msIOContext *context;
+
+  httpRequestObj *pasReqInfo;
+  wmsParamsObj sLastWMSParams;
+  int i, numReq = 0;
+
+  pasReqInfo = (httpRequestObj *)msSmallMalloc((nOWSLayers+1)*sizeof(httpRequestObj));
+  msHTTPInitRequestObj(pasReqInfo, nOWSLayers+1);
+  msInitWmsParamsObj(&sLastWMSParams);
+
+  /* Generate the http request */
+  for (i=0; i<map->numlayers; i++) {
+    if (GET_LAYER(map,map->layerorder[i])->status == MS_ON) {
+      if (type == WMS_GETFEATUREINFO &&
+          msPrepareWMSLayerRequest(map->layerorder[i], map, GET_LAYER(map,map->layerorder[i]),
+                                   WMS_GETFEATUREINFO,
+                                   MS_WMS, &sLastWMSParams,
+                                   nClickX, nClickY, nFeatureCount, pszInfoFormat,
+                                   pasReqInfo, &numReq) == MS_FAILURE) {
+        msFreeWmsParamsObj(&sLastWMSParams);
+        msFree(pasReqInfo);
+        return MS_FAILURE;
+      } else if (msPrepareWMSLayerRequest(map->layerorder[i], map, GET_LAYER(map,map->layerorder[i]),
+                                          WMS_GETLEGENDGRAPHIC,
+                                          MS_WMS, &sLastWMSParams,
+                                          0, 0, 0, NULL,
+                                          pasReqInfo, &numReq) == MS_FAILURE) {
+        msFreeWmsParamsObj(&sLastWMSParams);
+        msFree(pasReqInfo);
+        return MS_FAILURE;
+      }
+    }
+  }
+
+  if (msOWSExecuteRequests(pasReqInfo, numReq, map, MS_FALSE) == MS_FAILURE) {
+    msHTTPFreeRequestObj(pasReqInfo, numReq);
+    msFree(pasReqInfo);
+    msFreeWmsParamsObj(&sLastWMSParams);
+    return MS_FAILURE;
+  }
+
+  context = msIO_getHandler( stdout );
+  if( context == NULL ) {
+    msHTTPFreeRequestObj(pasReqInfo, numReq);
+    msFree(pasReqInfo);
+    msFreeWmsParamsObj(&sLastWMSParams);
+    return MS_FAILURE;
+  }
+
+  msIO_printf("Content-Type: %s%c%c",pasReqInfo[0].pszContentType, 10,10);
+
+  if( pasReqInfo[0].pszOutputFile ) {
+    FILE *fp;
+    char szBuf[MS_BUFFER_LENGTH];
+
+    fp = fopen(pasReqInfo[0].pszOutputFile, "r");
+    if (fp) {
+      while(1) {
+        size_t nSize;
+        nSize = fread(szBuf, sizeof(char), MS_BUFFER_LENGTH-1, fp);
+        if (nSize > 0)
+          msIO_contextWrite( context,
+                             szBuf,
+                             nSize);
+        if (nSize != MS_BUFFER_LENGTH-1)
+          break;
+      }
+      fclose(fp);
+      if (!map->debug)
+        unlink(pasReqInfo[0].pszOutputFile);
+    } else {
+      msSetError(MS_IOERR, "'%s'.",
+                 "msWMSLayerExecuteRequest()", pasReqInfo[0].pszOutputFile);
+      return MS_FAILURE;
+    }
+  } else {
+    msIO_contextWrite( context,
+                       pasReqInfo[0].result_data,
+                       pasReqInfo[0].result_size );
+  }
+
+  msHTTPFreeRequestObj(pasReqInfo, numReq);
+  msFree(pasReqInfo);
+  msFreeWmsParamsObj(&sLastWMSParams);
+
+  return MS_SUCCESS;
 #else
-/* ------------------------------------------------------------------
- * WMS CONNECTION Support not included...
- * ------------------------------------------------------------------ */
-  msSetError(MS_WMSCONNERR, "WMS CLIENT CONNECTION support is not available.", 
-             "msDrawWMSLayer()");
+  /* ------------------------------------------------------------------
+   * WMS CONNECTION Support not included...
+   * ------------------------------------------------------------------ */
+  msSetError(MS_WMSCONNERR, "WMS CLIENT CONNECTION support is not available.",
+             "msWMSLayerExecuteRequest()");
   return(MS_FAILURE);
 
 #endif /* USE_WMS_LYR */
 
 }
-
-
diff --git a/mapxbase.c b/mapxbase.c
index 2b01b3c..2dfc38a 100644
--- a/mapxbase.c
+++ b/mapxbase.c
@@ -2,7 +2,7 @@
  * $Id$
  *
  * Project:  MapServer
- * Purpose:  .dbf access API.  Derived from shapelib, and relicensed with 
+ * Purpose:  .dbf access API.  Derived from shapelib, and relicensed with
  *           permission of Frank Warmerdam (shapelib author).
  * Author:   Steve Lime and the MapServer team.
  *
@@ -16,7 +16,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -34,7 +34,7 @@
 #include <stdlib.h> /* for atof() and atoi() */
 #include <math.h>
 
-MS_CVSID("$Id$")
+
 
 /* try to use a large file version of fseek for files up to 4GB (#3514) */
 #if _MSC_VER > 1310
@@ -54,10 +54,10 @@ MS_CVSID("$Id$")
 static void * SfRealloc( void * pMem, int nNewSize )
 
 {
-    if( pMem == NULL )
-        return( (void *) malloc(nNewSize) );
-    else
-        return( (void *) realloc(pMem,nNewSize) );
+  if( pMem == NULL )
+    return( (void *) malloc(nNewSize) );
+  else
+    return( (void *) realloc(pMem,nNewSize) );
 }
 
 /************************************************************************/
@@ -71,48 +71,47 @@ static void * SfRealloc( void * pMem, int nNewSize )
 static void writeHeader(DBFHandle psDBF)
 
 {
-    uchar	abyHeader[32];
-    int		i;
+  uchar abyHeader[32];
+  int   i;
 
-    if( !psDBF->bNoHeader )
-        return;
+  if( !psDBF->bNoHeader )
+    return;
 
-    psDBF->bNoHeader = MS_FALSE;
+  psDBF->bNoHeader = MS_FALSE;
 
-    /* -------------------------------------------------------------------- */
-    /*	Initialize the file header information.		    		    */
-    /* -------------------------------------------------------------------- */
-    for( i = 0; i < 32; i++ )
-        abyHeader[i] = 0;
+  /* -------------------------------------------------------------------- */
+  /*  Initialize the file header information.               */
+  /* -------------------------------------------------------------------- */
+  for( i = 0; i < 32; i++ )
+    abyHeader[i] = 0;
 
-    abyHeader[0] = 0x03;		/* memo field? - just copying 	*/
+  abyHeader[0] = 0x03;    /* memo field? - just copying   */
 
-    /* date updated on close, record count preset at zero */
+  /* date updated on close, record count preset at zero */
 
-    abyHeader[8] = psDBF->nHeaderLength % 256;
-    abyHeader[9] = psDBF->nHeaderLength / 256;
-    
-    abyHeader[10] = psDBF->nRecordLength % 256;
-    abyHeader[11] = psDBF->nRecordLength / 256;
+  abyHeader[8] = psDBF->nHeaderLength % 256;
+  abyHeader[9] = psDBF->nHeaderLength / 256;
 
-    /* -------------------------------------------------------------------- */
-    /*      Write the initial 32 byte file header, and all the field        */
-    /*      descriptions.                                     		    */
-    /* -------------------------------------------------------------------- */
-    fseek( psDBF->fp, 0, 0 );
-    fwrite( abyHeader, 32, 1, psDBF->fp );
-    fwrite( psDBF->pszHeader, 32, psDBF->nFields, psDBF->fp );
-
-    /* -------------------------------------------------------------------- */
-    /*      Write out the newline character if there is room for it.        */
-    /* -------------------------------------------------------------------- */
-    if( psDBF->nHeaderLength > 32*psDBF->nFields + 32 )
-    {
-        char	cNewline;
-
-        cNewline = 0x0d;
-        fwrite( &cNewline, 1, 1, psDBF->fp );
-    }
+  abyHeader[10] = psDBF->nRecordLength % 256;
+  abyHeader[11] = psDBF->nRecordLength / 256;
+
+  /* -------------------------------------------------------------------- */
+  /*      Write the initial 32 byte file header, and all the field        */
+  /*      descriptions.                                             */
+  /* -------------------------------------------------------------------- */
+  fseek( psDBF->fp, 0, 0 );
+  fwrite( abyHeader, 32, 1, psDBF->fp );
+  fwrite( psDBF->pszHeader, 32, psDBF->nFields, psDBF->fp );
+
+  /* -------------------------------------------------------------------- */
+  /*      Write out the newline character if there is room for it.        */
+  /* -------------------------------------------------------------------- */
+  if( psDBF->nHeaderLength > 32*psDBF->nFields + 32 ) {
+    char  cNewline;
+
+    cNewline = 0x0d;
+    fwrite( &cNewline, 1, 1, psDBF->fp );
+  }
 }
 
 /************************************************************************/
@@ -123,132 +122,124 @@ static void writeHeader(DBFHandle psDBF)
 static void flushRecord( DBFHandle psDBF )
 
 {
-    unsigned int nRecordOffset;
+  unsigned int nRecordOffset;
 
-    if( psDBF->bCurrentRecordModified && psDBF->nCurrentRecord > -1 )
-    {
-	psDBF->bCurrentRecordModified = MS_FALSE;
+  if( psDBF->bCurrentRecordModified && psDBF->nCurrentRecord > -1 ) {
+    psDBF->bCurrentRecordModified = MS_FALSE;
 
-	nRecordOffset = psDBF->nRecordLength * psDBF->nCurrentRecord 
-	                                             + psDBF->nHeaderLength;
+    nRecordOffset = psDBF->nRecordLength * psDBF->nCurrentRecord
+                    + psDBF->nHeaderLength;
 
-	safe_fseek( psDBF->fp, nRecordOffset, 0 );
-	fwrite( psDBF->pszCurrentRecord, psDBF->nRecordLength, 1, psDBF->fp );
-    }
+    safe_fseek( psDBF->fp, nRecordOffset, 0 );
+    fwrite( psDBF->pszCurrentRecord, psDBF->nRecordLength, 1, psDBF->fp );
+  }
 }
 
 /************************************************************************/
 /*                              msDBFOpen()                             */
 /*                                                                      */
 /*      Open a .dbf file.                                               */
-/************************************************************************/   
+/************************************************************************/
 DBFHandle msDBFOpen( const char * pszFilename, const char * pszAccess )
 
 {
-    DBFHandle		psDBF;
-    uchar		*pabyBuf;
-    int			nFields, nRecords, nHeadLen, nRecLen, iField;
-    char	        *pszDBFFilename;
-
-    /* -------------------------------------------------------------------- */
-    /*      We only allow the access strings "rb" and "r+".                 */
-    /* -------------------------------------------------------------------- */
-    if( strcmp(pszAccess,"r") != 0 && strcmp(pszAccess,"r+") != 0 
-        && strcmp(pszAccess,"rb") != 0 && strcmp(pszAccess,"r+b") != 0 )
-        return( NULL );
-    
-    /* -------------------------------------------------------------------- */
-    /*	Ensure the extension is converted to dbf or DBF if it is 	    */
-    /*	currently .shp or .shx.						    */
-    /* -------------------------------------------------------------------- */
-    pszDBFFilename = (char *) msSmallMalloc(strlen(pszFilename)+1);
-    strcpy( pszDBFFilename, pszFilename );
-    
-    if( strcmp(pszFilename+strlen(pszFilename)-4,".shp") 
-	|| strcmp(pszFilename+strlen(pszFilename)-4,".shx") )
-    {
-        strcpy( pszDBFFilename+strlen(pszDBFFilename)-4, ".dbf");
-    }
-    else if( strcmp(pszFilename+strlen(pszFilename)-4,".SHP") 
-	     || strcmp(pszFilename+strlen(pszFilename)-4,".SHX") )
-    {
-        strcpy( pszDBFFilename+strlen(pszDBFFilename)-4, ".DBF");
-    }
+  DBFHandle   psDBF;
+  uchar   *pabyBuf;
+  int     nFields, nRecords, nHeadLen, nRecLen, iField;
+  char          *pszDBFFilename;
 
-    /* -------------------------------------------------------------------- */
-    /*      Open the file.                                                  */
-    /* -------------------------------------------------------------------- */
-    psDBF = (DBFHandle) calloc( 1, sizeof(DBFInfo) );
-    MS_CHECK_ALLOC(psDBF, sizeof(DBFInfo), NULL);
-    psDBF->fp = fopen( pszDBFFilename, pszAccess );
-    if( psDBF->fp == NULL )
-        return( NULL );
-
-    psDBF->bNoHeader = MS_FALSE;
-    psDBF->nCurrentRecord = -1;
-    psDBF->bCurrentRecordModified = MS_FALSE;
+  /* -------------------------------------------------------------------- */
+  /*      We only allow the access strings "rb" and "r+".                 */
+  /* -------------------------------------------------------------------- */
+  if( strcmp(pszAccess,"r") != 0 && strcmp(pszAccess,"r+") != 0
+      && strcmp(pszAccess,"rb") != 0 && strcmp(pszAccess,"r+b") != 0 )
+    return( NULL );
+
+  /* -------------------------------------------------------------------- */
+  /*  Ensure the extension is converted to dbf or DBF if it is      */
+  /*  currently .shp or .shx.               */
+  /* -------------------------------------------------------------------- */
+  pszDBFFilename = (char *) msSmallMalloc(strlen(pszFilename)+1);
+  strcpy( pszDBFFilename, pszFilename );
+
+  if( strcmp(pszFilename+strlen(pszFilename)-4,".shp")
+      || strcmp(pszFilename+strlen(pszFilename)-4,".shx") ) {
+    strcpy( pszDBFFilename+strlen(pszDBFFilename)-4, ".dbf");
+  } else if( strcmp(pszFilename+strlen(pszFilename)-4,".SHP")
+             || strcmp(pszFilename+strlen(pszFilename)-4,".SHX") ) {
+    strcpy( pszDBFFilename+strlen(pszDBFFilename)-4, ".DBF");
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Open the file.                                                  */
+  /* -------------------------------------------------------------------- */
+  psDBF = (DBFHandle) calloc( 1, sizeof(DBFInfo) );
+  MS_CHECK_ALLOC(psDBF, sizeof(DBFInfo), NULL);
+  psDBF->fp = fopen( pszDBFFilename, pszAccess );
+  if( psDBF->fp == NULL )
+    return( NULL );
+
+  psDBF->bNoHeader = MS_FALSE;
+  psDBF->nCurrentRecord = -1;
+  psDBF->bCurrentRecordModified = MS_FALSE;
+
+  psDBF->pszStringField = NULL;
+  psDBF->nStringFieldLen = 0;
+
+  free( pszDBFFilename );
+
+  /* -------------------------------------------------------------------- */
+  /*  Read Table Header info                                              */
+  /* -------------------------------------------------------------------- */
+  pabyBuf = (uchar *) msSmallMalloc(500);
+  fread( pabyBuf, 32, 1, psDBF->fp );
+
+  psDBF->nRecords = nRecords =
+                      pabyBuf[4] + pabyBuf[5]*256 + pabyBuf[6]*256*256 + pabyBuf[7]*256*256*256;
+
+  psDBF->nHeaderLength = nHeadLen = pabyBuf[8] + pabyBuf[9]*256;
+  psDBF->nRecordLength = nRecLen = pabyBuf[10] + pabyBuf[11]*256;
+
+  psDBF->nFields = nFields = (nHeadLen - 32) / 32;
+
+  psDBF->pszCurrentRecord = (char *) msSmallMalloc(nRecLen);
+
+  /* -------------------------------------------------------------------- */
+  /*  Read in Field Definitions                                           */
+  /* -------------------------------------------------------------------- */
+  pabyBuf = (uchar *) SfRealloc(pabyBuf,nHeadLen);
+  psDBF->pszHeader = (char *) pabyBuf;
+
+  fseek( psDBF->fp, 32, 0 );
+  fread( pabyBuf, nHeadLen, 1, psDBF->fp );
+
+  psDBF->panFieldOffset = (int *) msSmallMalloc(sizeof(int) * nFields);
+  psDBF->panFieldSize = (int *) msSmallMalloc(sizeof(int) * nFields);
+  psDBF->panFieldDecimals = (int *) msSmallMalloc(sizeof(int) * nFields);
+  psDBF->pachFieldType = (char *) msSmallMalloc(sizeof(char) * nFields);
 
-    psDBF->pszStringField = NULL;
-    psDBF->nStringFieldLen = 0;    
-
-    free( pszDBFFilename );
-
-    /* -------------------------------------------------------------------- */
-    /*  Read Table Header info                                              */
-    /* -------------------------------------------------------------------- */
-    pabyBuf = (uchar *) msSmallMalloc(500);
-    fread( pabyBuf, 32, 1, psDBF->fp );
-
-    psDBF->nRecords = nRecords = 
-     pabyBuf[4] + pabyBuf[5]*256 + pabyBuf[6]*256*256 + pabyBuf[7]*256*256*256;
-
-    psDBF->nHeaderLength = nHeadLen = pabyBuf[8] + pabyBuf[9]*256;
-    psDBF->nRecordLength = nRecLen = pabyBuf[10] + pabyBuf[11]*256;
-    
-    psDBF->nFields = nFields = (nHeadLen - 32) / 32;
-
-    psDBF->pszCurrentRecord = (char *) msSmallMalloc(nRecLen);
-
-    /* -------------------------------------------------------------------- */
-    /*  Read in Field Definitions                                           */
-    /* -------------------------------------------------------------------- */
-    pabyBuf = (uchar *) SfRealloc(pabyBuf,nHeadLen);
-    psDBF->pszHeader = (char *) pabyBuf;
-
-    fseek( psDBF->fp, 32, 0 );
-    fread( pabyBuf, nHeadLen, 1, psDBF->fp );
-
-    psDBF->panFieldOffset = (int *) msSmallMalloc(sizeof(int) * nFields);
-    psDBF->panFieldSize = (int *) msSmallMalloc(sizeof(int) * nFields);
-    psDBF->panFieldDecimals = (int *) msSmallMalloc(sizeof(int) * nFields);
-    psDBF->pachFieldType = (char *) msSmallMalloc(sizeof(char) * nFields);
-
-    for( iField = 0; iField < nFields; iField++ )
-    {
-	uchar		*pabyFInfo;
-
-	pabyFInfo = pabyBuf+iField*32;
-
-	if( pabyFInfo[11] == 'N' || pabyFInfo[11] == 'F' )
-	{
-	    psDBF->panFieldSize[iField] = pabyFInfo[16];
-	    psDBF->panFieldDecimals[iField] = pabyFInfo[17];
-	}
-	else
-	{
-	    psDBF->panFieldSize[iField] = pabyFInfo[16] + pabyFInfo[17]*256;
-	    psDBF->panFieldDecimals[iField] = 0;
-	}
-
-	psDBF->pachFieldType[iField] = (char) pabyFInfo[11];
-	if( iField == 0 )
-	    psDBF->panFieldOffset[iField] = 1;
-	else
-	    psDBF->panFieldOffset[iField] = 
-	      psDBF->panFieldOffset[iField-1] + psDBF->panFieldSize[iField-1];
+  for( iField = 0; iField < nFields; iField++ ) {
+    uchar   *pabyFInfo;
+
+    pabyFInfo = pabyBuf+iField*32;
+
+    if( pabyFInfo[11] == 'N' || pabyFInfo[11] == 'F' ) {
+      psDBF->panFieldSize[iField] = pabyFInfo[16];
+      psDBF->panFieldDecimals[iField] = pabyFInfo[17];
+    } else {
+      psDBF->panFieldSize[iField] = pabyFInfo[16] + pabyFInfo[17]*256;
+      psDBF->panFieldDecimals[iField] = 0;
     }
 
-    return( psDBF );
+    psDBF->pachFieldType[iField] = (char) pabyFInfo[11];
+    if( iField == 0 )
+      psDBF->panFieldOffset[iField] = 1;
+    else
+      psDBF->panFieldOffset[iField] =
+        psDBF->panFieldOffset[iField-1] + psDBF->panFieldSize[iField-1];
+  }
+
+  return( psDBF );
 }
 
 /************************************************************************/
@@ -260,54 +251,52 @@ void  msDBFClose(DBFHandle psDBF)
   /* -------------------------------------------------------------------- */
   /*      Write out header if not already written.                        */
   /* -------------------------------------------------------------------- */
-    if( psDBF->bNoHeader )
-        writeHeader( psDBF );
+  if( psDBF->bNoHeader )
+    writeHeader( psDBF );
 
-    flushRecord( psDBF );
+  flushRecord( psDBF );
 
-    /* -------------------------------------------------------------------- */
-    /*      Update last access date, and number of records if we have       */
-    /*	write access.                					    */ 
-    /* -------------------------------------------------------------------- */
-    if( psDBF->bUpdated )
-    {
-	uchar		abyFileHeader[32];
+  /* -------------------------------------------------------------------- */
+  /*      Update last access date, and number of records if we have       */
+  /*  write access.                             */
+  /* -------------------------------------------------------------------- */
+  if( psDBF->bUpdated ) {
+    uchar   abyFileHeader[32];
 
-	fseek( psDBF->fp, 0, 0 );
-	fread( abyFileHeader, 32, 1, psDBF->fp );
+    fseek( psDBF->fp, 0, 0 );
+    fread( abyFileHeader, 32, 1, psDBF->fp );
 
-	abyFileHeader[1] = 95;			/* YY */
-	abyFileHeader[2] = 7;			/* MM */
-	abyFileHeader[3] = 26;			/* DD */
+    abyFileHeader[1] = 95;      /* YY */
+    abyFileHeader[2] = 7;     /* MM */
+    abyFileHeader[3] = 26;      /* DD */
 
-	abyFileHeader[4] = psDBF->nRecords % 256;
-	abyFileHeader[5] = (psDBF->nRecords/256) % 256;
-	abyFileHeader[6] = (psDBF->nRecords/(256*256)) % 256;
-	abyFileHeader[7] = (psDBF->nRecords/(256*256*256)) % 256;
+    abyFileHeader[4] = psDBF->nRecords % 256;
+    abyFileHeader[5] = (psDBF->nRecords/256) % 256;
+    abyFileHeader[6] = (psDBF->nRecords/(256*256)) % 256;
+    abyFileHeader[7] = (psDBF->nRecords/(256*256*256)) % 256;
 
-	fseek( psDBF->fp, 0, 0 );
-	fwrite( abyFileHeader, 32, 1, psDBF->fp );
-    }
+    fseek( psDBF->fp, 0, 0 );
+    fwrite( abyFileHeader, 32, 1, psDBF->fp );
+  }
 
-    /* -------------------------------------------------------------------- */
-    /*      Close, and free resources.                                      */
-    /* -------------------------------------------------------------------- */
-    fclose( psDBF->fp );
-
-    if( psDBF->panFieldOffset != NULL )
-    {
-        free( psDBF->panFieldOffset );
-        free( psDBF->panFieldSize );
-        free( psDBF->panFieldDecimals );
-        free( psDBF->pachFieldType );
-    }
+  /* -------------------------------------------------------------------- */
+  /*      Close, and free resources.                                      */
+  /* -------------------------------------------------------------------- */
+  fclose( psDBF->fp );
+
+  if( psDBF->panFieldOffset != NULL ) {
+    free( psDBF->panFieldOffset );
+    free( psDBF->panFieldSize );
+    free( psDBF->panFieldDecimals );
+    free( psDBF->pachFieldType );
+  }
 
-    free( psDBF->pszHeader );
-    free( psDBF->pszCurrentRecord );
+  free( psDBF->pszHeader );
+  free( psDBF->pszCurrentRecord );
 
-    if(psDBF->pszStringField) free(psDBF->pszStringField);
+  if(psDBF->pszStringField) free(psDBF->pszStringField);
 
-    free( psDBF );
+  free( psDBF );
 }
 
 /************************************************************************/
@@ -318,58 +307,57 @@ void  msDBFClose(DBFHandle psDBF)
 DBFHandle msDBFCreate( const char * pszFilename )
 
 {
-    DBFHandle	psDBF;
-    FILE	*fp;
-
-    /* -------------------------------------------------------------------- */
-    /*      Create the file.                                                */
-    /* -------------------------------------------------------------------- */
-    fp = fopen( pszFilename, "wb" );
-    if( fp == NULL )
-        return( NULL );
-
-    fputc( 0, fp );
-    fclose( fp );
-
-    fp = fopen( pszFilename, "rb+" );
-    if( fp == NULL )
-        return( NULL );
-
-    /* -------------------------------------------------------------------- */
-    /*	Create the info structure.			  		    */
-    /* -------------------------------------------------------------------- */
-    psDBF = (DBFHandle) malloc(sizeof(DBFInfo));
-    if (psDBF == NULL)
-    {
-        msSetError(MS_MEMERR, "%s: %d: Out of memory allocating %u bytes.\n", "msDBFCreate()",
-                   __FILE__, __LINE__, sizeof(DBFInfo));
-        fclose(fp);
-        return NULL;
-    }
+  DBFHandle psDBF;
+  FILE  *fp;
 
-    psDBF->fp = fp;
-    psDBF->nRecords = 0;
-    psDBF->nFields = 0;
-    psDBF->nRecordLength = 1;
-    psDBF->nHeaderLength = 33;
-    
-    psDBF->panFieldOffset = NULL;
-    psDBF->panFieldSize = NULL;
-    psDBF->panFieldDecimals = NULL;
-    psDBF->pachFieldType = NULL;
-    psDBF->pszHeader = NULL;
-
-    psDBF->nCurrentRecord = -1;
-    psDBF->bCurrentRecordModified = MS_FALSE;
-    psDBF->pszCurrentRecord = NULL;
+  /* -------------------------------------------------------------------- */
+  /*      Create the file.                                                */
+  /* -------------------------------------------------------------------- */
+  fp = fopen( pszFilename, "wb" );
+  if( fp == NULL )
+    return( NULL );
+
+  fputc( 0, fp );
+  fclose( fp );
+
+  fp = fopen( pszFilename, "rb+" );
+  if( fp == NULL )
+    return( NULL );
+
+  /* -------------------------------------------------------------------- */
+  /*  Create the info structure.                */
+  /* -------------------------------------------------------------------- */
+  psDBF = (DBFHandle) malloc(sizeof(DBFInfo));
+  if (psDBF == NULL) {
+    msSetError(MS_MEMERR, "%s: %d: Out of memory allocating %u bytes.\n", "msDBFCreate()",
+               __FILE__, __LINE__, sizeof(DBFInfo));
+    fclose(fp);
+    return NULL;
+  }
+
+  psDBF->fp = fp;
+  psDBF->nRecords = 0;
+  psDBF->nFields = 0;
+  psDBF->nRecordLength = 1;
+  psDBF->nHeaderLength = 33;
 
-    psDBF->pszStringField = NULL;
-    psDBF->nStringFieldLen = 0;    
+  psDBF->panFieldOffset = NULL;
+  psDBF->panFieldSize = NULL;
+  psDBF->panFieldDecimals = NULL;
+  psDBF->pachFieldType = NULL;
+  psDBF->pszHeader = NULL;
 
-    psDBF->bNoHeader = MS_TRUE;
-    psDBF->bUpdated = MS_FALSE;
+  psDBF->nCurrentRecord = -1;
+  psDBF->bCurrentRecordModified = MS_FALSE;
+  psDBF->pszCurrentRecord = NULL;
 
-    return( psDBF );
+  psDBF->pszStringField = NULL;
+  psDBF->nStringFieldLen = 0;
+
+  psDBF->bNoHeader = MS_TRUE;
+  psDBF->bUpdated = MS_FALSE;
+
+  return( psDBF );
 }
 
 /************************************************************************/
@@ -378,92 +366,89 @@ DBFHandle msDBFCreate( const char * pszFilename )
 /*      Add a field to a newly created .dbf file before any records     */
 /*      are written.                                                    */
 /************************************************************************/
-int	msDBFAddField(DBFHandle psDBF, const char * pszFieldName, DBFFieldType eType, int nWidth, int nDecimals )
+int msDBFAddField(DBFHandle psDBF, const char * pszFieldName, DBFFieldType eType, int nWidth, int nDecimals )
 {
-    char	*pszFInfo;
-    int		i;
+  char  *pszFInfo;
+  int   i;
 
-    /* -------------------------------------------------------------------- */
-    /*      Do some checking to ensure we can add records to this file.     */
-    /* -------------------------------------------------------------------- */
-    if( psDBF->nRecords > 0 )
-        return( MS_FALSE );
+  /* -------------------------------------------------------------------- */
+  /*      Do some checking to ensure we can add records to this file.     */
+  /* -------------------------------------------------------------------- */
+  if( psDBF->nRecords > 0 )
+    return( MS_FALSE );
 
-    if( !psDBF->bNoHeader )
-        return( MS_FALSE );
+  if( !psDBF->bNoHeader )
+    return( MS_FALSE );
 
-    if( eType != FTDouble && nDecimals != 0 )
-        return( MS_FALSE );
+  if( eType != FTDouble && nDecimals != 0 )
+    return( MS_FALSE );
 
-    /* -------------------------------------------------------------------- */
-    /*      SfRealloc all the arrays larger to hold the additional field    */
-    /*      information.                                                    */
-    /* -------------------------------------------------------------------- */
-    psDBF->nFields++;
+  /* -------------------------------------------------------------------- */
+  /*      SfRealloc all the arrays larger to hold the additional field    */
+  /*      information.                                                    */
+  /* -------------------------------------------------------------------- */
+  psDBF->nFields++;
 
-    psDBF->panFieldOffset = (int *) 
-      SfRealloc( psDBF->panFieldOffset, sizeof(int) * psDBF->nFields );
+  psDBF->panFieldOffset = (int *)
+                          SfRealloc( psDBF->panFieldOffset, sizeof(int) * psDBF->nFields );
 
-    psDBF->panFieldSize = (int *) 
-      SfRealloc( psDBF->panFieldSize, sizeof(int) * psDBF->nFields );
+  psDBF->panFieldSize = (int *)
+                        SfRealloc( psDBF->panFieldSize, sizeof(int) * psDBF->nFields );
 
-    psDBF->panFieldDecimals = (int *) 
-      SfRealloc( psDBF->panFieldDecimals, sizeof(int) * psDBF->nFields );
+  psDBF->panFieldDecimals = (int *)
+                            SfRealloc( psDBF->panFieldDecimals, sizeof(int) * psDBF->nFields );
 
-    psDBF->pachFieldType = (char *) 
-      SfRealloc( psDBF->pachFieldType, sizeof(char) * psDBF->nFields );
+  psDBF->pachFieldType = (char *)
+                         SfRealloc( psDBF->pachFieldType, sizeof(char) * psDBF->nFields );
 
-    /* -------------------------------------------------------------------- */
-    /*      Assign the new field information fields.                        */
-    /* -------------------------------------------------------------------- */
-    psDBF->panFieldOffset[psDBF->nFields-1] = psDBF->nRecordLength;
-    psDBF->nRecordLength += nWidth;
-    psDBF->panFieldSize[psDBF->nFields-1] = nWidth;
-    psDBF->panFieldDecimals[psDBF->nFields-1] = nDecimals;
+  /* -------------------------------------------------------------------- */
+  /*      Assign the new field information fields.                        */
+  /* -------------------------------------------------------------------- */
+  psDBF->panFieldOffset[psDBF->nFields-1] = psDBF->nRecordLength;
+  psDBF->nRecordLength += nWidth;
+  psDBF->panFieldSize[psDBF->nFields-1] = nWidth;
+  psDBF->panFieldDecimals[psDBF->nFields-1] = nDecimals;
 
-    if( eType == FTString )
-        psDBF->pachFieldType[psDBF->nFields-1] = 'C';
-    else
-        psDBF->pachFieldType[psDBF->nFields-1] = 'N';
+  if( eType == FTString )
+    psDBF->pachFieldType[psDBF->nFields-1] = 'C';
+  else
+    psDBF->pachFieldType[psDBF->nFields-1] = 'N';
 
-    /* -------------------------------------------------------------------- */
-    /*      Extend the required header information.                         */
-    /* -------------------------------------------------------------------- */
-    psDBF->nHeaderLength += 32;
-    psDBF->bUpdated = MS_FALSE;
+  /* -------------------------------------------------------------------- */
+  /*      Extend the required header information.                         */
+  /* -------------------------------------------------------------------- */
+  psDBF->nHeaderLength += 32;
+  psDBF->bUpdated = MS_FALSE;
 
-    psDBF->pszHeader = (char *) SfRealloc(psDBF->pszHeader,psDBF->nFields*32);
+  psDBF->pszHeader = (char *) SfRealloc(psDBF->pszHeader,psDBF->nFields*32);
 
-    pszFInfo = psDBF->pszHeader + 32 * (psDBF->nFields-1);
+  pszFInfo = psDBF->pszHeader + 32 * (psDBF->nFields-1);
 
-    for( i = 0; i < 32; i++ )
-        pszFInfo[i] = '\0';
+  for( i = 0; i < 32; i++ )
+    pszFInfo[i] = '\0';
 
-    if( strlen(pszFieldName) < 10 )
-        strncpy( pszFInfo, pszFieldName, strlen(pszFieldName));
-    else
-        strncpy( pszFInfo, pszFieldName, 10);
+  if( strlen(pszFieldName) < 10 )
+    strncpy( pszFInfo, pszFieldName, strlen(pszFieldName));
+  else
+    strncpy( pszFInfo, pszFieldName, 10);
 
-    pszFInfo[11] = psDBF->pachFieldType[psDBF->nFields-1];
+  pszFInfo[11] = psDBF->pachFieldType[psDBF->nFields-1];
 
-    if( eType == FTString )
-    {
-        pszFInfo[16] = nWidth % 256;
-        pszFInfo[17] = nWidth / 256;
-    }
-    else
-    {
-        pszFInfo[16] = nWidth;
-        pszFInfo[17] = nDecimals;
-    }
-    
-    /* -------------------------------------------------------------------- */
-    /*      Make the current record buffer appropriately larger.            */
-    /* -------------------------------------------------------------------- */
-    psDBF->pszCurrentRecord = (char *) SfRealloc(psDBF->pszCurrentRecord,
-					       psDBF->nRecordLength);
-
-    return( psDBF->nFields-1 );
+  if( eType == FTString ) {
+    pszFInfo[16] = nWidth % 256;
+    pszFInfo[17] = nWidth / 256;
+  } else {
+    pszFInfo[16] = nWidth;
+    pszFInfo[17] = nDecimals;
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Make the current record buffer appropriately larger.            */
+  /* -------------------------------------------------------------------- */
+  psDBF->pszCurrentRecord = (char *) SfRealloc(psDBF->pszCurrentRecord,
+                            psDBF->nRecordLength);
+
+  return( psDBF->nFields-1 );
 }
 
 /************************************************************************/
@@ -476,26 +461,25 @@ int	msDBFAddField(DBFHandle psDBF, const char * pszFieldName, DBFFieldType eType
 
 int DBFIsValueNULL( const char* pszValue, char type )
 
-{   
-    switch(type)
-    {
-      case 'N':
-      case 'F':
-        /* NULL numeric fields have value "****************" */
-        return pszValue[0] == '*';
-
-      case 'D':
-        /* NULL date fields have value "00000000" */
-        return strncmp(pszValue,"00000000",8) == 0;
-
-      case 'L':
-        /* NULL boolean fields have value "?" */
-        return pszValue[0] == '?';
-
-      default:
-        /* empty string fields are considered NULL */
-        return strlen(pszValue) == 0;
-    }
+{
+  switch(type) {
+    case 'N':
+    case 'F':
+      /* NULL numeric fields have value "****************" */
+      return pszValue[0] == '*';
+
+    case 'D':
+      /* NULL date fields have value "00000000" */
+      return strncmp(pszValue,"00000000",8) == 0;
+
+    case 'L':
+      /* NULL boolean fields have value "?" */
+      return pszValue[0] == '?';
+
+    default:
+      /* empty string fields are considered NULL */
+      return strlen(pszValue) == 0;
+  }
 }
 
 /************************************************************************/
@@ -506,91 +490,86 @@ int DBFIsValueNULL( const char* pszValue, char type )
 static char *msDBFReadAttribute(DBFHandle psDBF, int hEntity, int iField )
 
 {
-    int	       	i;
-    unsigned int nRecordOffset;
-    uchar	*pabyRec;
-    char	*pReturnField = NULL;
-    
-    /* -------------------------------------------------------------------- */
-    /*	Is the request valid?                  				    */
-    /* -------------------------------------------------------------------- */
-    if( iField < 0 || iField >= psDBF->nFields ) 
-    {
-        msSetError(MS_DBFERR, "Invalid field index %d.", "msDBFReadAttribute()",iField );
-        return( NULL );
-    }
+  int         i;
+  unsigned int nRecordOffset;
+  uchar *pabyRec;
+  char  *pReturnField = NULL;
 
-    if( hEntity < 0 || hEntity >= psDBF->nRecords )
-    {
-        msSetError(MS_DBFERR, "Invalid record number %d.", "msDBFReadAttribute()",hEntity );
-        return( NULL );
-    }
+  /* -------------------------------------------------------------------- */
+  /*  Is the request valid?                             */
+  /* -------------------------------------------------------------------- */
+  if( iField < 0 || iField >= psDBF->nFields ) {
+    msSetError(MS_DBFERR, "Invalid field index %d.", "msDBFReadAttribute()",iField );
+    return( NULL );
+  }
 
-    /* -------------------------------------------------------------------- */
-    /*	Have we read the record?					    */
-    /* -------------------------------------------------------------------- */
-    if( psDBF->nCurrentRecord != hEntity )
-    {
-	flushRecord( psDBF );
+  if( hEntity < 0 || hEntity >= psDBF->nRecords ) {
+    msSetError(MS_DBFERR, "Invalid record number %d.", "msDBFReadAttribute()",hEntity );
+    return( NULL );
+  }
 
-	nRecordOffset = psDBF->nRecordLength * hEntity + psDBF->nHeaderLength;
+  /* -------------------------------------------------------------------- */
+  /*  Have we read the record?              */
+  /* -------------------------------------------------------------------- */
+  if( psDBF->nCurrentRecord != hEntity ) {
+    flushRecord( psDBF );
 
-	safe_fseek( psDBF->fp, nRecordOffset, 0 );
-	fread( psDBF->pszCurrentRecord, psDBF->nRecordLength, 1, psDBF->fp );
+    nRecordOffset = psDBF->nRecordLength * hEntity + psDBF->nHeaderLength;
 
-	psDBF->nCurrentRecord = hEntity;
-    }
+    safe_fseek( psDBF->fp, nRecordOffset, 0 );
+    fread( psDBF->pszCurrentRecord, psDBF->nRecordLength, 1, psDBF->fp );
 
-    pabyRec = (uchar *) psDBF->pszCurrentRecord;
-    /* DEBUG */
-    /* printf("CurrentRecord(%c):%s\n", psDBF->pachFieldType[iField], pabyRec); */
-
-    /* -------------------------------------------------------------------- */
-    /*	Ensure our field buffer is large enough to hold this buffer.	    */
-    /* -------------------------------------------------------------------- */
-    if( psDBF->panFieldSize[iField]+1 > psDBF->nStringFieldLen )
-    {
-	psDBF->nStringFieldLen = psDBF->panFieldSize[iField]*2 + 10;
-	psDBF->pszStringField = (char *) SfRealloc(psDBF->pszStringField,psDBF->nStringFieldLen);
-    }
+    psDBF->nCurrentRecord = hEntity;
+  }
 
-    /* -------------------------------------------------------------------- */
-    /*	Extract the requested field.					    */
-    /* -------------------------------------------------------------------- */
-    strncpy( psDBF->pszStringField,(char *) pabyRec+psDBF->panFieldOffset[iField], psDBF->panFieldSize[iField] );
-    psDBF->pszStringField[psDBF->panFieldSize[iField]] = '\0';
-
-    /*
-    ** Trim trailing blanks (SDL Modification)
-    */ 
-    for(i=strlen(psDBF->pszStringField)-1;i>=0;i--) {
-      if(psDBF->pszStringField[i] != ' ') { 
-	psDBF->pszStringField[i+1] = '\0'; 
-	break;
-      }
+  pabyRec = (uchar *) psDBF->pszCurrentRecord;
+  /* DEBUG */
+  /* printf("CurrentRecord(%c):%s\n", psDBF->pachFieldType[iField], pabyRec); */
+
+  /* -------------------------------------------------------------------- */
+  /*  Ensure our field buffer is large enough to hold this buffer.      */
+  /* -------------------------------------------------------------------- */
+  if( psDBF->panFieldSize[iField]+1 > psDBF->nStringFieldLen ) {
+    psDBF->nStringFieldLen = psDBF->panFieldSize[iField]*2 + 10;
+    psDBF->pszStringField = (char *) SfRealloc(psDBF->pszStringField,psDBF->nStringFieldLen);
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*  Extract the requested field.              */
+  /* -------------------------------------------------------------------- */
+  strncpy( psDBF->pszStringField,(char *) pabyRec+psDBF->panFieldOffset[iField], psDBF->panFieldSize[iField] );
+  psDBF->pszStringField[psDBF->panFieldSize[iField]] = '\0';
+
+  /*
+  ** Trim trailing blanks (SDL Modification)
+  */
+  for(i=strlen(psDBF->pszStringField)-1; i>=0; i--) {
+    if(psDBF->pszStringField[i] != ' ') {
+      psDBF->pszStringField[i+1] = '\0';
+      break;
     }
+  }
+
+  if(i == -1) psDBF->pszStringField[0] = '\0'; /* whole string is blank (SDL fix)       */
 
-    if(i == -1) psDBF->pszStringField[0] = '\0'; /* whole string is blank (SDL fix)       */
-
-    /*
-    ** Trim/skip leading blanks (SDL/DM Modification - only on numeric types)
-    */ 
-    if( psDBF->pachFieldType[iField] == 'N' || psDBF->pachFieldType[iField] == 'F' || psDBF->pachFieldType[iField] == 'D' ) {
-        for(i=0; psDBF->pszStringField[i] != '\0' ;i++) {
-            if(psDBF->pszStringField[i] != ' ')
-                break;	
-        }
-        pReturnField = psDBF->pszStringField+i;
+  /*
+  ** Trim/skip leading blanks (SDL/DM Modification - only on numeric types)
+  */
+  if( psDBF->pachFieldType[iField] == 'N' || psDBF->pachFieldType[iField] == 'F' || psDBF->pachFieldType[iField] == 'D' ) {
+    for(i=0; psDBF->pszStringField[i] != '\0' ; i++) {
+      if(psDBF->pszStringField[i] != ' ')
+        break;
     }
-    else
-        pReturnField = psDBF->pszStringField;
-
-    /*  detect null values */
-    if ( DBFIsValueNULL( pReturnField, psDBF->pachFieldType[iField] )  ) {
-	if (psDBF->pachFieldType[iField] == 'N' || psDBF->pachFieldType[iField] == 'F' || psDBF->pachFieldType[iField] == 'D')
-		pReturnField="0";	
-    }	
-    return( pReturnField );
+    pReturnField = psDBF->pszStringField+i;
+  } else
+    pReturnField = psDBF->pszStringField;
+
+  /*  detect null values */
+  if ( DBFIsValueNULL( pReturnField, psDBF->pachFieldType[iField] )  ) {
+    if (psDBF->pachFieldType[iField] == 'N' || psDBF->pachFieldType[iField] == 'F' || psDBF->pachFieldType[iField] == 'D')
+      pReturnField="0";
+  }
+  return( pReturnField );
 }
 
 /************************************************************************/
@@ -598,7 +577,7 @@ static char *msDBFReadAttribute(DBFHandle psDBF, int hEntity, int iField )
 /*                                                                      */
 /*      Read an integer attribute.                                      */
 /************************************************************************/
-int	msDBFReadIntegerAttribute( DBFHandle psDBF, int iRecord, int iField )
+int msDBFReadIntegerAttribute( DBFHandle psDBF, int iRecord, int iField )
 
 {
   return(atoi(msDBFReadAttribute( psDBF, iRecord, iField )));
@@ -609,7 +588,7 @@ int	msDBFReadIntegerAttribute( DBFHandle psDBF, int iRecord, int iField )
 /*                                                                      */
 /*      Read a double attribute.                                        */
 /************************************************************************/
-double	msDBFReadDoubleAttribute( DBFHandle psDBF, int iRecord, int iField )
+double  msDBFReadDoubleAttribute( DBFHandle psDBF, int iRecord, int iField )
 {
   return(atof(msDBFReadAttribute( psDBF, iRecord, iField )));
 }
@@ -621,7 +600,7 @@ double	msDBFReadDoubleAttribute( DBFHandle psDBF, int iRecord, int iField )
 /************************************************************************/
 const char *msDBFReadStringAttribute( DBFHandle psDBF, int iRecord, int iField )
 {
-  return( msDBFReadAttribute( psDBF, iRecord, iField ) );  
+  return( msDBFReadAttribute( psDBF, iRecord, iField ) );
 }
 
 /************************************************************************/
@@ -629,7 +608,7 @@ const char *msDBFReadStringAttribute( DBFHandle psDBF, int iRecord, int iField )
 /*                                                                      */
 /*      Return the number of fields in this table.                      */
 /************************************************************************/
-int	msDBFGetFieldCount( DBFHandle psDBF )
+int msDBFGetFieldCount( DBFHandle psDBF )
 {
   return( psDBF->nFields );
 }
@@ -639,7 +618,7 @@ int	msDBFGetFieldCount( DBFHandle psDBF )
 /*                                                                      */
 /*      Return the number of records in this table.                     */
 /************************************************************************/
-int	msDBFGetRecordCount( DBFHandle psDBF )
+int msDBFGetRecordCount( DBFHandle psDBF )
 {
   return( psDBF->nRecords );
 }
@@ -653,126 +632,120 @@ DBFFieldType msDBFGetFieldInfo( DBFHandle psDBF, int iField, char * pszFieldName
 {
   if( iField < 0 || iField >= psDBF->nFields )
     return( FTInvalid );
-  
+
   if( pnWidth != NULL )
     *pnWidth = psDBF->panFieldSize[iField];
-  
+
   if( pnDecimals != NULL )
     *pnDecimals = psDBF->panFieldDecimals[iField];
-  
-  if( pszFieldName != NULL )
-    {
-      int	i;
-      
-      strncpy( pszFieldName, (char *) psDBF->pszHeader+iField*32, 11 );
-      pszFieldName[11] = '\0';
-      for( i = 10; i > 0 && pszFieldName[i] == ' '; i-- )
-	pszFieldName[i] = '\0';
-    }
-  
-  if( psDBF->pachFieldType[iField] == 'N' 
+
+  if( pszFieldName != NULL ) {
+    int i;
+
+    strncpy( pszFieldName, (char *) psDBF->pszHeader+iField*32, 11 );
+    pszFieldName[11] = '\0';
+    for( i = 10; i > 0 && pszFieldName[i] == ' '; i-- )
+      pszFieldName[i] = '\0';
+  }
+
+  if( psDBF->pachFieldType[iField] == 'N'
       || psDBF->pachFieldType[iField] == 'F'
-      || psDBF->pachFieldType[iField] == 'D' )
-    {
-      if( psDBF->panFieldDecimals[iField] > 0 )
-	return( FTDouble );
-      else
-	return( FTInteger );
-    }
-  else
-    {
-      return( FTString );
-    }
+      || psDBF->pachFieldType[iField] == 'D' ) {
+    if( psDBF->panFieldDecimals[iField] > 0 )
+      return( FTDouble );
+    else
+      return( FTInteger );
+  } else {
+    return( FTString );
+  }
 }
 
 /************************************************************************/
 /*                         msDBFWriteAttribute()                        */
-/*									*/
-/*	Write an attribute record to the file.				*/
+/*                  */
+/*  Write an attribute record to the file.        */
 /************************************************************************/
 static int msDBFWriteAttribute(DBFHandle psDBF, int hEntity, int iField, void * pValue )
 {
-  unsigned int	       	nRecordOffset;
+  unsigned int          nRecordOffset;
   int  i, j;
-  uchar	*pabyRec;
-  char	szSField[40], szFormat[12];
-  
+  uchar *pabyRec;
+  char  szSField[40], szFormat[12];
+
   /* -------------------------------------------------------------------- */
-  /*	Is this a valid record?						  */
+  /*  Is this a valid record?             */
   /* -------------------------------------------------------------------- */
   if( hEntity < 0 || hEntity > psDBF->nRecords )
     return( MS_FALSE );
-  
+
   if( psDBF->bNoHeader )
     writeHeader(psDBF);
-  
+
   /* -------------------------------------------------------------------- */
   /*      Is this a brand new record?                                     */
   /* -------------------------------------------------------------------- */
-  if( hEntity == psDBF->nRecords )
-    {
-      flushRecord( psDBF );
-      
-      psDBF->nRecords++;
-      for( i = 0; i < psDBF->nRecordLength; i++ )
-	psDBF->pszCurrentRecord[i] = ' ';
-      
-      psDBF->nCurrentRecord = hEntity;
-    }
-  
+  if( hEntity == psDBF->nRecords ) {
+    flushRecord( psDBF );
+
+    psDBF->nRecords++;
+    for( i = 0; i < psDBF->nRecordLength; i++ )
+      psDBF->pszCurrentRecord[i] = ' ';
+
+    psDBF->nCurrentRecord = hEntity;
+  }
+
   /* -------------------------------------------------------------------- */
   /*      Is this an existing record, but different than the last one     */
   /*      we accessed?                                                    */
   /* -------------------------------------------------------------------- */
-  if( psDBF->nCurrentRecord != hEntity )
-    {
-      flushRecord( psDBF );
-      
-      nRecordOffset = psDBF->nRecordLength * hEntity + psDBF->nHeaderLength;
-      
-      safe_fseek( psDBF->fp, nRecordOffset, 0 );
-      fread( psDBF->pszCurrentRecord, psDBF->nRecordLength, 1, psDBF->fp );
+  if( psDBF->nCurrentRecord != hEntity ) {
+    flushRecord( psDBF );
+
+    nRecordOffset = psDBF->nRecordLength * hEntity + psDBF->nHeaderLength;
+
+    safe_fseek( psDBF->fp, nRecordOffset, 0 );
+    fread( psDBF->pszCurrentRecord, psDBF->nRecordLength, 1, psDBF->fp );
+
+    psDBF->nCurrentRecord = hEntity;
+  }
 
-      psDBF->nCurrentRecord = hEntity;
-    }
-  
   pabyRec = (uchar *) psDBF->pszCurrentRecord;
-  
+
   /* -------------------------------------------------------------------- */
   /*      Assign all the record fields.                                   */
   /* -------------------------------------------------------------------- */
   switch( psDBF->pachFieldType[iField] ) {
-  case 'D':
-  case 'N':
-  case 'F':
-    if( psDBF->panFieldDecimals[iField] == 0 ) {
-      snprintf( szFormat, sizeof(szFormat), "%%%dd", psDBF->panFieldSize[iField] );
-      snprintf(szSField, sizeof(szSField), szFormat, (int) *((double *) pValue) );
-      if( (int) strlen(szSField) > psDBF->panFieldSize[iField] )
-	szSField[psDBF->panFieldSize[iField]] = '\0';
-      strncpy((char *) (pabyRec+psDBF->panFieldOffset[iField]), szSField, strlen(szSField) );
-    } else {
-      snprintf( szFormat, sizeof(szFormat), "%%%d.%df", psDBF->panFieldSize[iField], psDBF->panFieldDecimals[iField] );
-      snprintf(szSField, sizeof(szSField), szFormat, *((double *) pValue) );
-      if( (int) strlen(szSField) > psDBF->panFieldSize[iField] )
-	szSField[psDBF->panFieldSize[iField]] = '\0';
-      strncpy((char *) (pabyRec+psDBF->panFieldOffset[iField]),  szSField, strlen(szSField) );
-    }
-    break;
-    
-  default:
-    if( (int) strlen((char *) pValue) > psDBF->panFieldSize[iField] )
-      j = psDBF->panFieldSize[iField];
-    else
-      j = strlen((char *) pValue);
-    
-    strncpy((char *) (pabyRec+psDBF->panFieldOffset[iField]), (char *) pValue, j );
-    break;
+    case 'D':
+    case 'N':
+    case 'F':
+      if( psDBF->panFieldDecimals[iField] == 0 ) {
+        snprintf( szFormat, sizeof(szFormat), "%%%dd", psDBF->panFieldSize[iField] );
+        snprintf(szSField, sizeof(szSField), szFormat, (int) *((double *) pValue) );
+        if( (int) strlen(szSField) > psDBF->panFieldSize[iField] )
+          szSField[psDBF->panFieldSize[iField]] = '\0';
+        strncpy((char *) (pabyRec+psDBF->panFieldOffset[iField]), szSField, strlen(szSField) );
+      } else {
+        snprintf( szFormat, sizeof(szFormat), "%%%d.%df", psDBF->panFieldSize[iField], psDBF->panFieldDecimals[iField] );
+        snprintf(szSField, sizeof(szSField), szFormat, *((double *) pValue) );
+        if( (int) strlen(szSField) > psDBF->panFieldSize[iField] )
+          szSField[psDBF->panFieldSize[iField]] = '\0';
+        strncpy((char *) (pabyRec+psDBF->panFieldOffset[iField]),  szSField, strlen(szSField) );
+      }
+      break;
+
+    default:
+      if( (int) strlen((char *) pValue) > psDBF->panFieldSize[iField] )
+        j = psDBF->panFieldSize[iField];
+      else
+        j = strlen((char *) pValue);
+
+      strncpy((char *) (pabyRec+psDBF->panFieldOffset[iField]), (char *) pValue, j );
+      break;
   }
-  
+
   psDBF->bCurrentRecordModified = MS_TRUE;
   psDBF->bUpdated = MS_TRUE;
-  
+
   return( MS_TRUE );
 }
 
@@ -792,10 +765,10 @@ int msDBFWriteDoubleAttribute( DBFHandle psDBF, int iRecord, int iField, double
 /*      Write a integer attribute.                                      */
 /************************************************************************/
 
-int msDBFWriteIntegerAttribute( DBFHandle psDBF, int iRecord, int iField,	int nValue )
+int msDBFWriteIntegerAttribute( DBFHandle psDBF, int iRecord, int iField, int nValue )
 {
-  double	dValue = nValue;
-  
+  double  dValue = nValue;
+
   return( msDBFWriteAttribute( psDBF, iRecord, iField, (void *) &dValue ) );
 }
 
@@ -815,23 +788,22 @@ int msDBFWriteStringAttribute( DBFHandle psDBF, int iRecord, int iField, const c
 int msDBFGetItemIndex(DBFHandle dbffile, char *name)
 {
   int i;
-  DBFFieldType dbfField;
-  int fWidth,fnDecimals; /* field width and number of decimals */    
+  int fWidth,fnDecimals; /* field width and number of decimals */
   char fName[32]; /* field name */
 
   if(!name) {
-    msSetError(MS_MISCERR, "NULL item name passed.", "msGetItemIndex()");    
+    msSetError(MS_MISCERR, "NULL item name passed.", "msGetItemIndex()");
     return(-1);
   }
 
   /* does name exist as a field? */
-  for(i=0;i<msDBFGetFieldCount(dbffile);i++) {
-    dbfField = msDBFGetFieldInfo(dbffile,i,fName,&fWidth,&fnDecimals);
+  for(i=0; i<msDBFGetFieldCount(dbffile); i++) {
+    msDBFGetFieldInfo(dbffile,i,fName,&fWidth,&fnDecimals);
     if(strcasecmp(name,fName) == 0) /* found it */
       return(i);
   }
 
-  msSetError(MS_DBFERR, "Item '%s' not found.", "msDBFGetItemIndex()",name);  
+  msSetError(MS_DBFERR, "Item '%s' not found.", "msDBFGetItemIndex()",name);
   return(-1); /* item not found */
 }
 
@@ -852,7 +824,7 @@ char **msDBFGetItems(DBFHandle dbffile)
   items = (char **)malloc(sizeof(char *)*nFields);
   MS_CHECK_ALLOC(items, sizeof(char *)*nFields, NULL);
 
-  for(i=0;i<nFields;i++) {
+  for(i=0; i<nFields; i++) {
     msDBFGetFieldInfo(dbffile, i, fName, NULL, NULL);
     items[i] = msStrdup(fName);
   }
@@ -876,7 +848,7 @@ char **msDBFGetValues(DBFHandle dbffile, int record)
   values = (char **)malloc(sizeof(char *)*nFields);
   MS_CHECK_ALLOC(values, sizeof(char *)*nFields, NULL);
 
-  for(i=0;i<nFields;i++)
+  for(i=0; i<nFields; i++)
     values[i] = msStrdup(msDBFReadStringAttribute(dbffile, record, i));
 
   return(values);
@@ -887,13 +859,13 @@ int *msDBFGetItemIndexes(DBFHandle dbffile, char **items, int numitems)
   int *itemindexes=NULL, i;
 
   if(numitems == 0) return(NULL);
-  
+
   itemindexes = (int *)malloc(sizeof(int)*numitems);
   MS_CHECK_ALLOC(itemindexes, sizeof(int)*numitems, NULL);
-  
-  for(i=0;i<numitems;i++) {
+
+  for(i=0; i<numitems; i++) {
     itemindexes[i] = msDBFGetItemIndex(dbffile, items[i]);
-    if(itemindexes[i] == -1) { 
+    if(itemindexes[i] == -1) {
       free(itemindexes);
       return(NULL); /* item not found */
     }
@@ -913,10 +885,12 @@ char **msDBFGetValueList(DBFHandle dbffile, int record, int *itemindexes, int nu
   values = (char **)malloc(sizeof(char *)*numitems);
   MS_CHECK_ALLOC(values, sizeof(char *)*numitems, NULL);
 
-  for(i=0;i<numitems;i++) {
+  for(i=0; i<numitems; i++) {
     value = msDBFReadStringAttribute(dbffile, record, itemindexes[i]);
-    if (value == NULL)
+    if (value == NULL) {
+      free(values);
       return NULL; /* Error already reported by msDBFReadStringAttribute() */
+    }
     values[i] = msStrdup(value);
   }
 
diff --git a/mapxml.c b/mapxml.c
index b9b7283..beff945 100644
--- a/mapxml.c
+++ b/mapxml.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -26,9 +26,10 @@
  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  * DEALINGS IN THE SOFTWARE.
  ****************************************************************************/
+#include "mapserver.h"
+
 #ifdef USE_XMLMAPFILE
 
-#include "mapserver.h"
 #include <libxslt/xslt.h>
 #include "libexslt/exslt.h"
 #include <libxslt/transform.h>
@@ -38,54 +39,51 @@
 
 extern int xmlLoadExtDtdDefaultValue;
 
-int msTransformXmlMapfile(const char *stylesheet, const char *xmlMapfile, FILE *tmpfile) 
+int msTransformXmlMapfile(const char *stylesheet, const char *xmlMapfile, FILE *tmpfile)
 {
-    xsltStylesheetPtr cur = NULL;
-    int status = MS_FAILURE;
-    xmlDocPtr doc, res;
+  xsltStylesheetPtr cur = NULL;
+  int status = MS_FAILURE;
+  xmlDocPtr doc, res;
+
+  exsltRegisterAll();
+  xsltRegisterTestModule();
 
-    exsltRegisterAll();
-    xsltRegisterTestModule();
+  xmlSubstituteEntitiesDefault(1);
+  xmlLoadExtDtdDefaultValue = 1;
 
-    xmlSubstituteEntitiesDefault(1);
-    xmlLoadExtDtdDefaultValue = 1;
+  cur = xsltParseStylesheetFile((const xmlChar *)stylesheet);
+  if (cur == NULL) {
+    msSetError(MS_MISCERR, "Failed to load xslt stylesheet", "msTransformXmlMapfile()");
+    goto done;
+  }
 
-    cur = xsltParseStylesheetFile((const xmlChar *)stylesheet);
-    if (cur == NULL) 
-    {
-        msSetError(MS_MISCERR, "Failed to load xslt stylesheet", "msTransformXmlMapfile()"); 
-        goto done;
-    }
-    
-    doc = xmlParseFile(xmlMapfile);
-    if (doc == NULL) 
-    {
-        msSetError(MS_MISCERR, "Failed to load xml mapfile", "msTransformXmlMapfile()"); 
-        goto done;
-    }
+  doc = xmlParseFile(xmlMapfile);
+  if (doc == NULL) {
+    msSetError(MS_MISCERR, "Failed to load xml mapfile", "msTransformXmlMapfile()");
+    goto done;
+  }
 
-    res = xsltApplyStylesheet(cur, doc, NULL);
-    if (res == NULL) 
-    {
-        msSetError(MS_MISCERR, "Failed to apply style sheet to %s", "msTransformXmlMapfile()", xmlMapfile); 
-        goto done;
-    }
+  res = xsltApplyStylesheet(cur, doc, NULL);
+  if (res == NULL) {
+    msSetError(MS_MISCERR, "Failed to apply style sheet to %s", "msTransformXmlMapfile()", xmlMapfile);
+    goto done;
+  }
 
-    if ( xsltSaveResultToFile(tmpfile, res, cur) != -1 )
-        status =  MS_SUCCESS;
+  if ( xsltSaveResultToFile(tmpfile, res, cur) != -1 )
+    status =  MS_SUCCESS;
 
 done:
-    if (cur)
-        xsltFreeStylesheet(cur);
-    if (res)
-        xmlFreeDoc(res);
-    if (doc)
-        xmlFreeDoc(doc);
+  if (cur)
+    xsltFreeStylesheet(cur);
+  if (res)
+    xmlFreeDoc(res);
+  if (doc)
+    xmlFreeDoc(doc);
 
-    xsltCleanupGlobals();
-    xmlCleanupParser();
+  xsltCleanupGlobals();
+  xmlCleanupParser();
 
-    return status;
+  return status;
 }
 
 #endif
diff --git a/mapxmp.c b/mapxmp.c
new file mode 100644
index 0000000..f394fb4
--- /dev/null
+++ b/mapxmp.c
@@ -0,0 +1,295 @@
+/******************************************************************************
+ * $Id: mapchart.c 11880 2011-07-07 19:51:37Z sdlime $
+ *
+ * Project:  MapServer
+ * Purpose:  XMP embedded image metadata (MS-RFC-7X)
+ * Author:   Paul Ramsey <pramsey at opengeo.org>
+ *
+ ******************************************************************************
+ * Copyright (c) 1996-2007 Regents of the University of Minnesota.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies of this Software or works derived from this Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ ****************************************************************************/
+
+#include "mapserver.h"
+
+
+#ifdef USE_EXEMPI
+
+/* To pull parts out of hash keys */
+#include <regex.h>
+
+/* To write the XMP XML into the files */
+#include <xmp.h>
+#include <xmpconsts.h>
+
+/**
+* Get standard Exempi namespace URI for a given namespace string
+*/
+static const char*
+msXmpUri(char *ns_name)
+{
+  /* Creative Commons */
+  if( strcmp(ns_name, "cc") == 0 )
+    return NS_CC;
+  /* Dublin Core */
+  else if( strcmp(ns_name, "dc") == 0 )
+    return NS_DC;
+  /* XMP Meta */
+  else if( strcmp(ns_name, "meta") == 0 )
+    return NS_XMP_META;
+  /* XMP Rights */
+  else if( strcmp(ns_name, "rights") == 0 )
+    return NS_XAP_RIGHTS;
+  /* EXIF */
+  else if( strcmp(ns_name, "exif") == 0 )
+    return NS_EXIF;
+  /* TIFF */
+  else if( strcmp(ns_name, "tiff") == 0 )
+    return NS_TIFF;
+  /* Photoshop Camera Raw Schema */
+  else if( strcmp(ns_name, "crs") == 0 )
+    return NS_CAMERA_RAW_SETTINGS;
+  /* Photoshop */
+  else if( strcmp(ns_name, "photoshop") == 0 )
+    return NS_PHOTOSHOP;
+  else
+    return NULL;
+}
+
+#endif
+
+/**
+* Is there any XMP metadata in the map file for us to worry about?
+*/
+int
+msXmpPresent( mapObj *map )
+{
+#ifdef USE_EXEMPI
+
+  /* Read the WEB.METADATA */
+  hashTableObj hash_metadata = map->web.metadata;
+  const char *key = NULL;
+  int rv = MS_FALSE;
+
+  /* Check all the keys for "xmp_" start pattern */
+  key = msFirstKeyFromHashTable(&hash_metadata);
+
+  /* No first key? No license info. */
+  if ( ! key )
+    return MS_FALSE;
+
+  do {
+    /* Found one! Break out and return true */
+    if ( strcasestr(key, "xmp_") == key ) {
+      rv = MS_TRUE;
+      break;
+    }
+  } while( (key = msNextKeyFromHashTable(&hash_metadata, key)) );
+
+  return rv;
+
+#else
+  return MS_FALSE;
+#endif
+}
+
+
+/**
+* Is there any XMP metadata in the map file for us to worry about?
+*/
+int
+msXmpWrite( mapObj *map, const char *filename )
+{
+#ifdef USE_EXEMPI
+
+  /* Should hold our keys */
+  hashTableObj hash_metadata = map->web.metadata;
+  /* Temporary place for custom name spaces */
+  hashTableObj hash_ns;
+  /* We use regex to strip out the namespace and XMP key value from the metadata key */
+  regex_t xmp_regex;
+  const char *xmp_ns_str = "^xmp_(.+)_namespace$";
+  const char *xmp_tag_str = "^xmp_(.+)_(.+)$";
+  const char *key = NULL;
+  static int regflags = REG_ICASE | REG_EXTENDED;
+
+  /* XMP object and file pointers */
+  XmpPtr xmp;
+  XmpFilePtr f;
+
+  /* Force the hash table to empty */
+  hash_ns.numitems = 0;
+
+  /* Prepare XMP library */
+  xmp_init();
+  f = xmp_files_open_new(filename, XMP_OPEN_FORUPDATE);
+  if ( ! f ) {
+    msSetError( MS_MISCERR,
+                "Unable to open temporary file '%s' to write XMP info",
+                "msXmpWrite()", filename );
+    return MS_FAILURE;
+  }
+
+  /* Create a new XMP structure if the file doesn't already have one */
+  xmp = xmp_files_get_new_xmp(f);
+  if ( xmp == NULL )
+    xmp = xmp_new_empty();
+
+  /* Check we can write to the file */
+  if ( ! xmp_files_can_put_xmp(f, xmp) ) {
+    msSetError( MS_MISCERR,
+                "Unable to write XMP information to '%s'",
+                "msXmpWrite()", filename );
+    return MS_FAILURE;
+  }
+
+  /* Compile our "xmp_*_namespace" regex */
+  if ( regcomp(&xmp_regex, xmp_ns_str, regflags) ) {
+    msSetError( MS_MISCERR,
+                "Unable compile regex '%s'",
+                "msXmpWrite()", xmp_ns_str );
+    return MS_FAILURE;
+  }
+
+  /* Check all the keys for "xmp_*_namespace" pattern */
+  initHashTable(&hash_ns);
+  key = msFirstKeyFromHashTable(&hash_metadata);
+
+  /* No first key? No license info. We shouldn't get here. */
+  if ( ! key )
+    return MS_SUCCESS;
+
+  do {
+    /* Our regex has one match slot */
+    regmatch_t matches[2];
+
+    /* Found a custom namespace entry! Store it for later. */
+    if ( 0 == regexec(&xmp_regex, key, 2, matches, 0) ) {
+      size_t ns_size = 0;
+      char *ns_name = NULL;
+      const char *ns_uri;
+
+      /* Copy in the namespace name */
+      ns_size = matches[1].rm_eo - matches[1].rm_so;
+      ns_name = msSmallMalloc(ns_size + 1);
+      memcpy(ns_name, key + matches[1].rm_so, ns_size);
+      ns_name[ns_size] = 0; /* null terminate */
+
+      /* Copy in the namespace uri */
+      ns_uri = msLookupHashTable(&hash_metadata, key);
+      msInsertHashTable(&hash_ns, ns_name, ns_uri);
+      xmp_register_namespace(ns_uri, ns_name, NULL);
+      msFree(ns_name);
+    }
+  } while( (key = msNextKeyFromHashTable(&hash_metadata, key)) );
+  /* Clean up regex */
+  regfree(&xmp_regex);
+
+
+  /* Compile our "xmp_*_*" regex */
+  if ( regcomp(&xmp_regex, xmp_tag_str, regflags) ) {
+    msFreeHashItems(&hash_ns);
+    msSetError( MS_MISCERR,
+                "Unable compile regex '%s'",
+                "msXmpWrite()", xmp_tag_str );
+    return MS_FAILURE;
+  }
+
+  /* Check all the keys for "xmp_*_*" pattern */
+  key = msFirstKeyFromHashTable(&hash_metadata);
+  do {
+    /* Our regex has two match slots */
+    regmatch_t matches[3];
+
+    /* Found a namespace entry! Write it into XMP. */
+    if ( 0 == regexec(&xmp_regex, key, 3, matches, 0) ) {
+      /* Get the namespace and tag name */
+      size_t ns_name_size = matches[1].rm_eo - matches[1].rm_so;
+      size_t ns_tag_size = matches[2].rm_eo - matches[2].rm_so;
+      char *ns_name = msSmallMalloc(ns_name_size + 1);
+      char *ns_tag = msSmallMalloc(ns_tag_size + 1);
+      const char *ns_uri = NULL;
+      memcpy(ns_name, key + matches[1].rm_so, ns_name_size);
+      memcpy(ns_tag, key + matches[2].rm_so, ns_tag_size);
+      ns_name[ns_name_size] = 0; /* null terminate */
+      ns_tag[ns_tag_size] = 0; /* null terminate */
+
+      if ( strcmp(ns_tag,"namespace") == 0 ) {
+        msFree(ns_name);
+        msFree(ns_tag);
+        continue;
+      }
+
+      /* If this is a default name space?... */
+      if ( (ns_uri = msXmpUri(ns_name)) ) {
+        xmp_register_namespace(ns_uri, ns_name, NULL);
+        xmp_set_property(xmp, ns_uri, ns_tag, msLookupHashTable(&hash_metadata, key), 0);
+      }
+      /* Or maybe it's a custom one?... */
+      else if ( (ns_uri = msLookupHashTable(&hash_ns, ns_name)) ) {
+        xmp_set_property(xmp, ns_uri, ns_tag, msLookupHashTable(&hash_metadata, key), 0);
+      }
+      /* Or perhaps we're screwed. */
+      else {
+        msFreeHashItems(&hash_ns);
+        msFree(ns_name);
+        msFree(ns_tag);
+        msSetError( MS_MISCERR,
+                    "Unable to identify XMP namespace '%s' in metadata key '%s'",
+                    "msXmpWrite()", ns_name, key );
+        return MS_FAILURE;
+      }
+      msFree(ns_name);
+      msFree(ns_tag);
+    }
+  } while( (key = msNextKeyFromHashTable(&hash_metadata, key)) );
+
+  /* Clean up regex */
+  regfree(&xmp_regex);
+
+  /* Write out the XMP */
+  if ( !xmp_files_put_xmp(f, xmp) ) {
+    msFreeHashItems(&hash_ns);
+    msSetError( MS_MISCERR,
+                "Unable to execute '%s' on pointer %p",
+                "msXmpWrite()", "xmp_files_put_xmp", f );
+    return MS_FAILURE;
+  }
+
+  /* Write out the file and flush */
+  if ( !xmp_files_close(f, XMP_CLOSE_SAFEUPDATE) ) {
+    msFreeHashItems(&hash_ns);
+    msSetError( MS_MISCERR,
+                "Unable to execute '%s' on pointer %p",
+                "msXmpWrite()", "xmp_files_close", f );
+    return MS_FAILURE;
+  }
+
+  msFreeHashItems(&hash_ns);
+  xmp_free(xmp);
+  xmp_terminate();
+
+  return MS_SUCCESS;
+
+#else
+  return MS_FAILURE;
+#endif
+}
+
diff --git a/mod_mapserver.c b/mod_mapserver.c
new file mode 100644
index 0000000..3bfa212
--- /dev/null
+++ b/mod_mapserver.c
@@ -0,0 +1,459 @@
+/*
+ *  mod_mapserver.c -- Apache sample wms module
+ */
+
+#include "httpd.h"
+#include "http_config.h"
+#include "http_protocol.h"
+#include "http_log.h"
+#include "ap_config.h"
+#include "apr.h"
+#include "apr_strings.h"
+#include "apr_tables.h"
+#include "apr_file_info.h"
+
+#include "mapserver.h"  /* for mapObj */
+#include "cgiutil.h"
+#include "mapserv.h"
+
+module AP_MODULE_DECLARE_DATA mapserver_module;
+
+typedef struct {
+  apr_pool_t *config_pool;
+  apr_time_t mtime;
+  char   *mapfile_name;
+  char   *uri;
+  mapObj *map;
+} mapserver_dir_config;
+
+/* These are the IO redirection hooks. They are mostly copied over from
+ * mapio.c. Note that cbData contains Apache's request_rec!
+ */
+static int
+msIO_apacheWrite (void *cbData, void *data, int byteCount)
+{
+  /* simply use the block writing function which is very similiar to fwrite */
+  return ap_rwrite (data, byteCount, (request_rec*) cbData);
+}
+
+static int
+msIO_apacheError (void *cbData, void *data, int byteCount)
+{
+  /* error reporting is done through the log file... */
+  ap_log_error (APLOG_MARK, APLOG_ERR, 0, NULL, (char*) data);
+  return strlen ((char*) data);
+}
+
+int
+msIO_installApacheRedirect (request_rec *r)
+{
+  msIOContext stdout_ctx, stderr_ctx;
+
+  stdout_ctx.label         = "apache";
+  stdout_ctx.write_channel = MS_TRUE;
+  stdout_ctx.readWriteFunc = msIO_apacheWrite;
+  stdout_ctx.cbData        = (void*) r;
+
+  stderr_ctx.label         = "apache";
+  stderr_ctx.write_channel = MS_TRUE;
+  stderr_ctx.readWriteFunc = msIO_apacheError;
+  stderr_ctx.cbData        = (void*) r;
+
+  msIO_installHandlers (NULL, &stdout_ctx, &stderr_ctx);
+
+  return MS_TRUE;
+}
+
+/* The maximum number of arguments we support. The number is taken from
+ * cgiutil.h I think. It is only used for easier param decoding.
+ */
+#define WMS_MAX_ARGS 100
+
+/* This is our simple query decoding function. Should be improved but for now
+ * it works...
+ */
+static int
+mapserver_decode_args (apr_pool_t *p, char *args,
+                       char ***ParamNames, char ***ParamValues)
+{
+  char **argv = NULL;
+  int    i;
+  int    n;
+  int    argc = 0;
+  char  *sep;
+
+  /* alloc the name/value pointer list */
+  argv = (char**) apr_pcalloc (p, (WMS_MAX_ARGS + 1) * 2 * sizeof (char*));
+  *ParamNames  = argv;
+  *ParamValues = argv + WMS_MAX_ARGS + 1;
+  /* No arguments? Then we're done */
+  if (!args) return 0;
+
+  argv [0] = args;
+
+  /* separate the arguments */
+  for (i = 1, n = 0; args [n] && (i < WMS_MAX_ARGS); n++)
+    if (args [n] == '&') {
+      argv [i++] = args + n + 1;
+      args [n  ] = '\0';
+    }
+
+  /* eleminate empty args */
+  for (n = 0, i = 0; argv [i]; i++)
+    if (*(argv [i]) != '\0')
+      argv [n++] = argv [i];
+    else
+      argv [i  ] = NULL;
+
+  /* argument count is the number of non-zero arguments! */
+  argc = n;
+
+  /* split the name/value pairs */
+  for (i = 0; argv [i]; i++) {
+    sep = strchr (argv [i], '=');
+    if (!sep) continue;
+    *sep = '\0';
+    argv [i + WMS_MAX_ARGS + 1] = (char*) apr_pstrdup (p, sep + 1);
+
+    if (ap_unescape_url (argv [i + WMS_MAX_ARGS + 1]) == HTTP_BAD_REQUEST) {
+      ap_log_error (APLOG_MARK, APLOG_ERR, 0, NULL,
+                    "%s: malformed URI, couldn't unescape parm %s",
+                    __func__, argv [i]);
+
+      argv [i + WMS_MAX_ARGS + 1] = NULL;
+    } else {
+      plustospace (argv [i + WMS_MAX_ARGS + 1]);
+    }
+  }
+  return argc;
+}
+
+static char*
+mapserver_read_post_data (request_rec *r)
+{
+  int   status;
+  int   size;
+  long  blen, rsize, rpos = 0;
+  char *buffer = NULL;
+  char  buf [512];
+
+  if ((status = ap_setup_client_block (r, REQUEST_CHUNKED_ERROR)) != OK)
+    return NULL;
+
+  if (!ap_should_client_block (r))
+    return NULL;
+
+  buffer = (char*) apr_palloc (r->pool, r->remaining + 1);
+  size = r->remaining;
+  buffer [size] = '\0';
+
+  if (!buffer)
+    return NULL;
+
+  while ((blen = ap_get_client_block (r, buf, sizeof (buf))) > 0) {
+    if (rpos + blen > size) {
+      rsize = blen - rpos;
+    } else {
+      rsize = blen;
+    }
+    memcpy ((char*) buffer + rpos, buf, rsize);
+    rpos += rsize;
+  }
+
+  return buffer;
+}
+
+/*
+** Extract Map File name from params and load it.
+** Returns map object or NULL on error.
+*/
+static mapObj*
+msModuleLoadMap(mapservObj *mapserv, mapserver_dir_config *conf)
+{
+  int i;
+  /* OK, here's the magic: we take the mapObj from our stored config.
+   * We will use a copy of it created by msCopyMap since MapServer
+   * modifies the object at several places during request processing
+   */
+  mapObj *map = msNewMapObj ();
+  if(!map) return NULL;
+  msCopyMap (map, conf->map);
+
+
+  /* check for any %variable% substitutions here, also do any map_ changes, we do this here so WMS/WFS  */
+  /* services can take advantage of these "vendor specific" extensions */
+  for(i=0; i<mapserv->request->NumParams; i++) {
+    /*
+    ** a few CGI variables should be skipped altogether
+    **
+    ** qstring: there is separate per layer validation for attribute queries and the substitution checks
+    **          below conflict with that so we avoid it here
+    */
+    if(strncasecmp(mapserv->request->ParamNames[i],"qstring",7) == 0) continue;
+
+    if(strncasecmp(mapserv->request->ParamNames[i],"map_",4) == 0 || strncasecmp(mapserv->request->ParamNames[i],"map.",4) == 0) { /* check to see if there are any additions to the mapfile */
+      if(msUpdateMapFromURL(map, mapserv->request->ParamNames[i], mapserv->request->ParamValues[i]) != MS_SUCCESS) {
+        msFreeMap(map);
+        return NULL;
+      }
+      continue;
+    }
+  }
+
+  msApplySubstitutions(map, mapserv->request->ParamNames, mapserv->request->ParamValues, mapserv->request->NumParams);
+  msApplyDefaultSubstitutions(map);
+
+  /* check to see if a ogc map context is passed as argument. if there */
+  /* is one load it */
+
+  for(i=0; i<mapserv->request->NumParams; i++) {
+    if(strcasecmp(mapserv->request->ParamNames[i],"context") == 0) {
+      if(mapserv->request->ParamValues[i] && strlen(mapserv->request->ParamValues[i]) > 0) {
+        if(strncasecmp(mapserv->request->ParamValues[i],"http",4) == 0) {
+          if(msGetConfigOption(map, "CGI_CONTEXT_URL"))
+            msLoadMapContextURL(map, mapserv->request->ParamValues[i], MS_FALSE);
+        } else
+          msLoadMapContext(map, mapserv->request->ParamValues[i], MS_FALSE);
+      }
+    }
+  }
+  /*
+   * RFC-42 HTTP Cookie Forwarding
+   * Here we set the http_cookie_data metadata to handle the
+   * HTTP Cookie Forwarding. The content of this metadata is the cookie
+   * content. In the future, this metadata will probably be replaced
+   * by an object that is part of the mapObject that would contain
+   * information on the application status (such as cookie).
+   */
+  if( mapserv->request->httpcookiedata != NULL ) {
+    msInsertHashTable( &(map->web.metadata), "http_cookie_data",
+                       mapserv->request->httpcookiedata );
+  }
+
+  return map;
+}
+
+/***
+ * The main request handler.
+ **/
+static int
+mapserver_handler (request_rec *r)
+{
+  /* aquire the apropriate configuration for this directory */
+  mapserver_dir_config *conf;
+  conf = (mapserver_dir_config*) ap_get_module_config (r->per_dir_config,
+         &mapserver_module);
+
+  /* decline the request if there's no map configured */
+  if (!conf || !conf->map)
+    return DECLINED;
+
+  apr_finfo_t mapstat;
+  if (apr_stat (&mapstat, conf->mapfile_name, APR_FINFO_MTIME, r->pool) == APR_SUCCESS) {
+    if (apr_time_sec (mapstat.mtime) > apr_time_sec (conf->mtime)) {
+      mapObj *newmap = msLoadMap (conf->mapfile_name, NULL);
+      if (newmap) {
+        msFreeMap (conf->map);
+        conf->map   = newmap;
+        conf->mtime = mapstat.mtime;
+      } else {
+        ap_log_error (APLOG_MARK, APLOG_WARNING, 0, NULL,
+                      "unable to reload map file %s", conf->mapfile_name);
+      }
+    }
+  } else {
+    ap_log_error (APLOG_MARK, APLOG_WARNING, 0, NULL,
+                  "%s: unable to stat file %s", __func__, conf->mapfile_name);
+  }
+
+  /* make a copy of the URI so we can modify it safely */
+  char *uri          = apr_pstrdup (r->pool, r->uri);
+  int   len          = strlen (uri);
+  int   conf_uri_len = strlen (conf->uri);
+
+  /* If the URI points to a subdirectory we want to decline.
+   */
+  if (len > conf_uri_len)
+    return DECLINED;
+
+  int    argc          = 0;
+  char **ParamNames    = NULL;
+  char **ParamValues   = NULL;
+  char  *post_data     = NULL;
+  int    szMethod      = -1;
+  char  *szContentType = NULL;
+  mapservObj *mapserv = NULL;
+
+  /* Try decoding the query string */
+  if (r->method_number == M_GET) {
+    argc = mapserver_decode_args (r->pool, (char*) apr_pstrdup (r->pool, r->args),
+                                  &ParamNames, &ParamValues);
+    szMethod = MS_GET_REQUEST;
+  } else if (r->method_number == M_POST) {
+    szContentType = (char*) apr_table_get (r->headers_in, "Content-Type");
+    post_data = mapserver_read_post_data (r);
+    szMethod  = MS_POST_REQUEST;
+    if (strcmp (szContentType, "application/x-www-form-urlencoded") == 0) {
+      argc = mapserver_decode_args (r->pool, (char*) apr_pstrdup (r->pool, r->args),
+                                    &ParamNames, &ParamValues);
+    }
+  } else
+    return HTTP_METHOD_NOT_ALLOWED;
+
+  if (!argc && !post_data)
+    return HTTP_BAD_REQUEST;
+
+  /* Now we install the IO redirection.
+  */
+  if (msIO_installApacheRedirect (r) != MS_TRUE)
+    ap_log_error (APLOG_MARK, APLOG_ERR, 0, NULL,
+                  "%s: could not install apache redirect", __func__);
+
+
+  mapserv = msAllocMapServObj();
+  mapserv->request->NumParams   = argc;
+  mapserv->request->ParamNames  = ParamNames;
+  mapserv->request->ParamValues = ParamValues;
+  mapserv->request->type        = (enum MS_REQUEST_TYPE) szMethod;
+  mapserv->request->postrequest = post_data;
+  mapserv->request->contenttype = szContentType;
+
+  //mapserv->map = msModuleLoadMap(mapserv,conf);
+  mapserv->map = conf->map;
+  if(!mapserv->map) {
+    msCGIWriteError(mapserv);
+    goto end_request;
+  }
+
+  if(msCGIDispatchRequest(mapserv) != MS_SUCCESS) {
+    msCGIWriteError(mapserv);
+    goto end_request;
+  }
+
+
+end_request:
+  if(mapserv) {
+    msCGIWriteLog(mapserv,MS_FALSE);
+    mapserv->request->ParamNames  = NULL;
+    mapserv->request->ParamValues = NULL;
+    mapserv->request->postrequest = NULL;
+    mapserv->request->contenttype = NULL;
+    mapserv->map = NULL;
+    msFreeMapServObj(mapserv);
+  }
+  msResetErrorList();
+
+
+  /* Check if status was set inside MapServer functions. If it was, we
+   * return it's value instead of simply OK. This is to support redirects
+   * from maptemplate.c
+   */
+  if (r->status == HTTP_MOVED_TEMPORARILY)
+    return r->status;
+
+  return OK;
+}
+
+/* This function will be called on startup to allow us to register our
+ * handler. We don't do anything else yet...
+ */
+static void
+mapserver_register_hooks (apr_pool_t *p)
+{
+  ap_hook_handler (mapserver_handler, NULL, NULL, APR_HOOK_MIDDLE);
+}
+
+/* That's the second part of the overall magic. This function will be called
+ * when the configuration reaches the "WMS_Map" parameter. It will be passed
+ * in as argument and should contain the full path and name of the map file.
+ * We try to load it and store the resulting mapObj in the config of the
+ * current directory. If we fail we throw a message...
+ */
+static const char*
+mapserver_set_map (cmd_parms *cmd, void *config, const char *arg)
+{
+  mapserver_dir_config *conf = (mapserver_dir_config*) config;
+  /* if the mapObj already exists the WMS_Map was given more than once -
+   * may be the user forgot to comment something out...
+   */
+  if (conf->map) {
+    msWriteError (stderr);
+    return (char*) apr_psprintf (cmd->temp_pool,
+                                 "An MAP-file has already been registered for "
+                                 "this URI - not accepting '%s'.", arg );
+  }
+  /* Simply try loading the argument as map file. */
+  conf->mapfile_name = apr_pstrdup(cmd->pool, arg);
+  conf->map = msLoadMap ((char*) arg, NULL);
+
+  /* Ooops - we failed. We report it and fail. So beware: Always do a
+   * configcheck before really restarting your web server!
+   */
+
+  if (!conf->map) {
+    msWriteError (stderr);
+    return (char*) apr_psprintf (cmd->temp_pool,
+                                 "The given MAP-file '%s' could not be loaded",
+                                 arg);
+  }
+
+  apr_finfo_t status;
+  if (apr_stat (&status, conf->mapfile_name, APR_FINFO_MTIME, cmd->pool) != APR_SUCCESS) {
+    ap_log_error (APLOG_MARK, APLOG_WARNING, 0, NULL,
+                  "%s: unable to stat file %s", __func__, conf->mapfile_name);
+  }
+  conf->mtime = status.mtime;
+  return NULL;
+}
+
+/* This function creates the (default) directory configuration. Well, we have
+ * no defaults to set so we simply alloc the memory...
+ */
+static void*
+mapserver_create_dir_config (apr_pool_t *p, char *dir)
+{
+  mapserver_dir_config *newconf;
+  newconf = (mapserver_dir_config*) apr_pcalloc (p, sizeof (mapserver_dir_config));
+  newconf->config_pool = p;
+  newconf->uri = apr_pstrdup (p, dir);
+  newconf->map = NULL;
+  newconf->mapfile_name = NULL;
+  newconf->mtime = apr_time_from_sec (0);
+
+  if (dir) {
+    int len = strlen (dir);
+    if (len > 1 && dir [len - 1] == '/' )
+      newconf->uri [len - 1] = '\0';
+  }
+  return newconf;
+}
+
+/* This structure defines our single config option which takes exactly one
+ * argument.
+ */
+static const command_rec mapserver_options[] = {
+  AP_INIT_TAKE1(
+    "Mapfile",
+    mapserver_set_map,
+    NULL,
+    ACCESS_CONF,
+    "WMS_Map <Path to map file>"
+  ),
+  {NULL}
+};
+
+/* The following structure declares everything Apache needs to treat us as
+ * a module. Merging would mean inheriting from the parent directory but that
+ * doesn't make much sense here since we would only inherit the map file...
+ */
+/* Dispatch list for API hooks */
+module AP_MODULE_DECLARE_DATA mapserver_module = {
+  STANDARD20_MODULE_STUFF,
+  mapserver_create_dir_config,  /* create per-dir    config structures */
+  NULL,     /* merge  per-dir    config structures */
+  NULL,     /* create per-server config structures */
+  NULL,     /* merge  per-server config structures */
+  mapserver_options,    /* table of config file commands       */
+  mapserver_register_hooks    /* register hooks                      */
+};
+
diff --git a/msencrypt.c b/msencrypt.c
index c77efda..fdf77df 100644
--- a/msencrypt.c
+++ b/msencrypt.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -29,60 +29,51 @@
 
 #include "mapserver.h"
 
-MS_CVSID("$Id$")
+
 
 void PrintUsage()
 {
-    printf("Usage: msencrypt <-keygen filename>|<-key filename string_to_encrypt>\n");
+  printf("Usage: msencrypt <-keygen filename>|<-key filename string_to_encrypt>\n");
 }
 
 int main(int argc, char *argv[])
 {
 
-    if (argc == 3 && strcmp(argv[1], "-keygen")==0)
-    {
+  if (argc == 3 && strcmp(argv[1], "-keygen")==0) {
 
-/* TODO: Move this to a function */
-        unsigned char pabyKey[16];
-        char szKeyEncoded[50];
-        FILE *fp;
-        msGenerateEncryptionKey(pabyKey);
-        msHexEncode(pabyKey, szKeyEncoded, 16);
+    /* TODO: Move this to a function */
+    unsigned char pabyKey[16];
+    char szKeyEncoded[50];
+    FILE *fp;
+    msGenerateEncryptionKey(pabyKey);
+    msHexEncode(pabyKey, szKeyEncoded, 16);
 
-        if ((fp = fopen(argv[2], "wt")) != NULL)
-        {
-            fprintf(fp, "%s\n", szKeyEncoded);
-            fclose(fp);
-        }
-        else
-        {
-            printf("ERROR: Failed writing to %s\n", argv[2]);
-            return -1;
-        }
+    if ((fp = fopen(argv[2], "wt")) != NULL) {
+      fprintf(fp, "%s\n", szKeyEncoded);
+      fclose(fp);
+    } else {
+      printf("ERROR: Failed writing to %s\n", argv[2]);
+      return -1;
     }
-    else if (argc == 4 && strcmp(argv[1], "-key")==0)
-    {
-        unsigned char key[16];
-        char *pszBuf;
+  } else if (argc == 4 && strcmp(argv[1], "-key")==0) {
+    unsigned char key[16];
+    char *pszBuf;
 
-        if (msReadEncryptionKeyFromFile(argv[2], key) != MS_SUCCESS)
-        {
-            printf("ERROR: Failed reading key from file %s\n", argv[2]);
-            return -1;
-        }
+    if (msReadEncryptionKeyFromFile(argv[2], key) != MS_SUCCESS) {
+      printf("ERROR: Failed reading key from file %s\n", argv[2]);
+      return -1;
+    }
 
-        pszBuf = (char*)malloc((strlen(argv[3])*2+17)*sizeof(char));
-        MS_CHECK_ALLOC(pszBuf, (strlen(argv[3])*2+17)*sizeof(char), -1);
+    pszBuf = (char*)malloc((strlen(argv[3])*2+17)*sizeof(char));
+    MS_CHECK_ALLOC(pszBuf, (strlen(argv[3])*2+17)*sizeof(char), -1);
 
-        msEncryptStringWithKey(key, argv[3], pszBuf);
+    msEncryptStringWithKey(key, argv[3], pszBuf);
 
-        printf("%s\n", pszBuf);
-        msFree(pszBuf);
-    }
-    else
-    {
-        PrintUsage();
-    }
+    printf("%s\n", pszBuf);
+    msFree(pszBuf);
+  } else {
+    PrintUsage();
+  }
 
-    return 0;
+  return 0;
 }
diff --git a/nmake.opt b/nmake.opt
index d0f3f25..fc3c3bc 100644
--- a/nmake.opt
+++ b/nmake.opt
@@ -685,7 +685,7 @@ FT_LIB=$(FT_DIR)/objs/win32/vc2008/freetype239.lib
 # GD include and library
 GD_INC= -I$(GD_DIR)
 GD_LIBS= $(GD_LIB) $(JPEG_LIB) $(PNG_LIB) $(FT_LIB)
-GD= $(OUTPUT_PNG) $(OUTPUT_JPEG) $(OUTPUT_WBMP) $(OUTPUT_GIF) $(ANNOTATION_FT) $(GD_HAS_GETBITMAPFONT) $(GD_HAS_FTEX_XSHOW)
+GD= -DUSE_GD $(OUTPUT_PNG) $(OUTPUT_JPEG) $(OUTPUT_WBMP) $(OUTPUT_GIF) $(ANNOTATION_FT) $(GD_HAS_GETBITMAPFONT) $(GD_HAS_FTEX_XSHOW)
 
 # Tiff library on input
 !IFDEF TIFF
@@ -781,11 +781,6 @@ renderers\agg\src\agg_svg_parser.obj renderers\agg\src\agg_svg_path_renderer.obj
 renderers\agg\src\agg_svg_path_tokenizer.obj renderers\agg\src\clipper.obj
 !ENDIF
 
-!IFDEF AGG_SVG_SYMBOL
-AGG_LIB= -lexpat
-AGG_OBJ=$(AGG_OBJ) renderers/agg/src/agg_svg_parser.obj renderers/agg/src/agg_svg_path_renderer.obj renderers/agg/src/agg_svg_path_tokenizer.obj
-!ENDIF
-
 # Setup PDF includes and libs
 !IFDEF PDF
 PDF_LIB=$(PDF_DIR)/libs/pdflib/Release_DLL/pdflib.lib
@@ -880,7 +875,7 @@ MS_DEFS = $(REGEX_OPT) $(STRINGS) $(POSTGIS) \
           $(WFS) $(WFSCLIENT) $(WCS) $(PDF) $(EGIS) \
           $(USE_GD_ANTIALIAS) $(ORACLE) \
           $(SDE_OPT) $(ICONV) $(GEOS) $(ZLIB) $(SOS)  $(XML2_ENABLED) $(AGG) \
-          $(OGL) $(CAIRO) $(RGBA_PNG_ENABLED) $(FRIBIDI) $(AGG_SVG_SYMBOLS) $(KML) $(GIF) $(CURL)
+          $(OGL) $(CAIRO) $(RGBA_PNG_ENABLED) $(FRIBIDI) $(KML) $(GIF) $(CURL)
 
 !IFDEF WIN64
 MS_CFLAGS=$(INCLUDES) $(MS_DEFS) -DWIN32 -D_WIN32 -DUSE_GENERIC_MS_NINT
diff --git a/opengl/glext.h b/opengl/glext.h
index 838b416..efd1e27 100644
--- a/opengl/glext.h
+++ b/opengl/glext.h
@@ -1,6569 +1,6569 @@
-#ifndef __glext_h_
-#define __glext_h_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/******************************************************************************
-
- Copyright NVIDIA Corporation 2005
-
- TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED
- *AS IS* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS
- OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF 
- MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  IN NO EVENT SHALL 
- NVIDIA OR ITS SUPPLIERS BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT, OR 
- CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR 
- LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, 
- OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR INABILITY TO USE 
- THIS SOFTWARE, EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 
- DAMAGES.
-
-******************************************************************************/
-
-/*
-** License Applicability. Except to the extent portions of this file are
-** made subject to an alternative license as permitted in the SGI Free
-** Software License B, Version 1.1 (the "License"), the contents of this
-** file are subject only to the provisions of the License. You may not use
-** this file except in compliance with the License. You may obtain a copy
-** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
-** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
-** 
-** http://oss.sgi.com/projects/FreeB
-** 
-** Note that, as provided in the License, the Software is distributed on an
-** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
-** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
-** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
-** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
-** 
-** Original Code. The Original Code is: OpenGL Sample Implementation,
-** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
-** Inc. The Original Code is Copyright (c) 1991-2004 Silicon Graphics, Inc.
-** Copyright in any portions created by third parties is as indicated
-** elsewhere herein. All Rights Reserved.
-** 
-** Additional Notice Provisions: This software was created using the
-** OpenGL(R) version 1.2.1 Sample Implementation published by SGI, but has
-** not been independently verified as being compliant with the OpenGL(R)
-** version 1.2.1 Specification.
-*/
-
-#if defined(_WIN32) && !defined(APIENTRY) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__)
-#define WIN32_LEAN_AND_MEAN 1
-#include <windows.h>
-#endif
-
-#ifndef APIENTRY
-#define APIENTRY
-#endif
-#ifndef APIENTRYP
-#define APIENTRYP APIENTRY *
-#endif
-#ifndef GLAPI
-#define GLAPI extern
-#endif
-
-/*************************************************************/
-
-/* Header file version number, required by OpenGL ABI for Linux */
-/* glext.h last updated 2005/06/06 */
-/* Current version at http://oss.sgi.com/projects/ogl-sample/registry/ */
-#define GL_GLEXT_VERSION 28
-
-#ifndef GL_VERSION_1_2
-#define GL_UNSIGNED_BYTE_3_3_2            0x8032
-#define GL_UNSIGNED_SHORT_4_4_4_4         0x8033
-#define GL_UNSIGNED_SHORT_5_5_5_1         0x8034
-#define GL_UNSIGNED_INT_8_8_8_8           0x8035
-#define GL_UNSIGNED_INT_10_10_10_2        0x8036
-#define GL_RESCALE_NORMAL                 0x803A
-#define GL_TEXTURE_BINDING_3D             0x806A
-#define GL_PACK_SKIP_IMAGES               0x806B
-#define GL_PACK_IMAGE_HEIGHT              0x806C
-#define GL_UNPACK_SKIP_IMAGES             0x806D
-#define GL_UNPACK_IMAGE_HEIGHT            0x806E
-#define GL_TEXTURE_3D                     0x806F
-#define GL_PROXY_TEXTURE_3D               0x8070
-#define GL_TEXTURE_DEPTH                  0x8071
-#define GL_TEXTURE_WRAP_R                 0x8072
-#define GL_MAX_3D_TEXTURE_SIZE            0x8073
-#define GL_UNSIGNED_BYTE_2_3_3_REV        0x8362
-#define GL_UNSIGNED_SHORT_5_6_5           0x8363
-#define GL_UNSIGNED_SHORT_5_6_5_REV       0x8364
-#define GL_UNSIGNED_SHORT_4_4_4_4_REV     0x8365
-#define GL_UNSIGNED_SHORT_1_5_5_5_REV     0x8366
-#define GL_UNSIGNED_INT_8_8_8_8_REV       0x8367
-#define GL_UNSIGNED_INT_2_10_10_10_REV    0x8368
-#define GL_BGR                            0x80E0
-#define GL_BGRA                           0x80E1
-#define GL_MAX_ELEMENTS_VERTICES          0x80E8
-#define GL_MAX_ELEMENTS_INDICES           0x80E9
-#define GL_CLAMP_TO_EDGE                  0x812F
-#define GL_TEXTURE_MIN_LOD                0x813A
-#define GL_TEXTURE_MAX_LOD                0x813B
-#define GL_TEXTURE_BASE_LEVEL             0x813C
-#define GL_TEXTURE_MAX_LEVEL              0x813D
-#define GL_LIGHT_MODEL_COLOR_CONTROL      0x81F8
-#define GL_SINGLE_COLOR                   0x81F9
-#define GL_SEPARATE_SPECULAR_COLOR        0x81FA
-#define GL_SMOOTH_POINT_SIZE_RANGE        0x0B12
-#define GL_SMOOTH_POINT_SIZE_GRANULARITY  0x0B13
-#define GL_SMOOTH_LINE_WIDTH_RANGE        0x0B22
-#define GL_SMOOTH_LINE_WIDTH_GRANULARITY  0x0B23
-#define GL_ALIASED_POINT_SIZE_RANGE       0x846D
-#define GL_ALIASED_LINE_WIDTH_RANGE       0x846E
-#endif
-
-#ifndef GL_ARB_imaging
-#define GL_CONSTANT_COLOR                 0x8001
-#define GL_ONE_MINUS_CONSTANT_COLOR       0x8002
-#define GL_CONSTANT_ALPHA                 0x8003
-#define GL_ONE_MINUS_CONSTANT_ALPHA       0x8004
-#define GL_BLEND_COLOR                    0x8005
-#define GL_FUNC_ADD                       0x8006
-#define GL_MIN                            0x8007
-#define GL_MAX                            0x8008
-#define GL_BLEND_EQUATION                 0x8009
-#define GL_FUNC_SUBTRACT                  0x800A
-#define GL_FUNC_REVERSE_SUBTRACT          0x800B
-#define GL_CONVOLUTION_1D                 0x8010
-#define GL_CONVOLUTION_2D                 0x8011
-#define GL_SEPARABLE_2D                   0x8012
-#define GL_CONVOLUTION_BORDER_MODE        0x8013
-#define GL_CONVOLUTION_FILTER_SCALE       0x8014
-#define GL_CONVOLUTION_FILTER_BIAS        0x8015
-#define GL_REDUCE                         0x8016
-#define GL_CONVOLUTION_FORMAT             0x8017
-#define GL_CONVOLUTION_WIDTH              0x8018
-#define GL_CONVOLUTION_HEIGHT             0x8019
-#define GL_MAX_CONVOLUTION_WIDTH          0x801A
-#define GL_MAX_CONVOLUTION_HEIGHT         0x801B
-#define GL_POST_CONVOLUTION_RED_SCALE     0x801C
-#define GL_POST_CONVOLUTION_GREEN_SCALE   0x801D
-#define GL_POST_CONVOLUTION_BLUE_SCALE    0x801E
-#define GL_POST_CONVOLUTION_ALPHA_SCALE   0x801F
-#define GL_POST_CONVOLUTION_RED_BIAS      0x8020
-#define GL_POST_CONVOLUTION_GREEN_BIAS    0x8021
-#define GL_POST_CONVOLUTION_BLUE_BIAS     0x8022
-#define GL_POST_CONVOLUTION_ALPHA_BIAS    0x8023
-#define GL_HISTOGRAM                      0x8024
-#define GL_PROXY_HISTOGRAM                0x8025
-#define GL_HISTOGRAM_WIDTH                0x8026
-#define GL_HISTOGRAM_FORMAT               0x8027
-#define GL_HISTOGRAM_RED_SIZE             0x8028
-#define GL_HISTOGRAM_GREEN_SIZE           0x8029
-#define GL_HISTOGRAM_BLUE_SIZE            0x802A
-#define GL_HISTOGRAM_ALPHA_SIZE           0x802B
-#define GL_HISTOGRAM_LUMINANCE_SIZE       0x802C
-#define GL_HISTOGRAM_SINK                 0x802D
-#define GL_MINMAX                         0x802E
-#define GL_MINMAX_FORMAT                  0x802F
-#define GL_MINMAX_SINK                    0x8030
-#define GL_TABLE_TOO_LARGE                0x8031
-#define GL_COLOR_MATRIX                   0x80B1
-#define GL_COLOR_MATRIX_STACK_DEPTH       0x80B2
-#define GL_MAX_COLOR_MATRIX_STACK_DEPTH   0x80B3
-#define GL_POST_COLOR_MATRIX_RED_SCALE    0x80B4
-#define GL_POST_COLOR_MATRIX_GREEN_SCALE  0x80B5
-#define GL_POST_COLOR_MATRIX_BLUE_SCALE   0x80B6
-#define GL_POST_COLOR_MATRIX_ALPHA_SCALE  0x80B7
-#define GL_POST_COLOR_MATRIX_RED_BIAS     0x80B8
-#define GL_POST_COLOR_MATRIX_GREEN_BIAS   0x80B9
-#define GL_POST_COLOR_MATRIX_BLUE_BIAS    0x80BA
-#define GL_POST_COLOR_MATRIX_ALPHA_BIAS   0x80BB
-#define GL_COLOR_TABLE                    0x80D0
-#define GL_POST_CONVOLUTION_COLOR_TABLE   0x80D1
-#define GL_POST_COLOR_MATRIX_COLOR_TABLE  0x80D2
-#define GL_PROXY_COLOR_TABLE              0x80D3
-#define GL_PROXY_POST_CONVOLUTION_COLOR_TABLE 0x80D4
-#define GL_PROXY_POST_COLOR_MATRIX_COLOR_TABLE 0x80D5
-#define GL_COLOR_TABLE_SCALE              0x80D6
-#define GL_COLOR_TABLE_BIAS               0x80D7
-#define GL_COLOR_TABLE_FORMAT             0x80D8
-#define GL_COLOR_TABLE_WIDTH              0x80D9
-#define GL_COLOR_TABLE_RED_SIZE           0x80DA
-#define GL_COLOR_TABLE_GREEN_SIZE         0x80DB
-#define GL_COLOR_TABLE_BLUE_SIZE          0x80DC
-#define GL_COLOR_TABLE_ALPHA_SIZE         0x80DD
-#define GL_COLOR_TABLE_LUMINANCE_SIZE     0x80DE
-#define GL_COLOR_TABLE_INTENSITY_SIZE     0x80DF
-#define GL_CONSTANT_BORDER                0x8151
-#define GL_REPLICATE_BORDER               0x8153
-#define GL_CONVOLUTION_BORDER_COLOR       0x8154
-#endif
-
-#ifndef GL_VERSION_1_3
-#define GL_TEXTURE0                       0x84C0
-#define GL_TEXTURE1                       0x84C1
-#define GL_TEXTURE2                       0x84C2
-#define GL_TEXTURE3                       0x84C3
-#define GL_TEXTURE4                       0x84C4
-#define GL_TEXTURE5                       0x84C5
-#define GL_TEXTURE6                       0x84C6
-#define GL_TEXTURE7                       0x84C7
-#define GL_TEXTURE8                       0x84C8
-#define GL_TEXTURE9                       0x84C9
-#define GL_TEXTURE10                      0x84CA
-#define GL_TEXTURE11                      0x84CB
-#define GL_TEXTURE12                      0x84CC
-#define GL_TEXTURE13                      0x84CD
-#define GL_TEXTURE14                      0x84CE
-#define GL_TEXTURE15                      0x84CF
-#define GL_TEXTURE16                      0x84D0
-#define GL_TEXTURE17                      0x84D1
-#define GL_TEXTURE18                      0x84D2
-#define GL_TEXTURE19                      0x84D3
-#define GL_TEXTURE20                      0x84D4
-#define GL_TEXTURE21                      0x84D5
-#define GL_TEXTURE22                      0x84D6
-#define GL_TEXTURE23                      0x84D7
-#define GL_TEXTURE24                      0x84D8
-#define GL_TEXTURE25                      0x84D9
-#define GL_TEXTURE26                      0x84DA
-#define GL_TEXTURE27                      0x84DB
-#define GL_TEXTURE28                      0x84DC
-#define GL_TEXTURE29                      0x84DD
-#define GL_TEXTURE30                      0x84DE
-#define GL_TEXTURE31                      0x84DF
-#define GL_ACTIVE_TEXTURE                 0x84E0
-#define GL_CLIENT_ACTIVE_TEXTURE          0x84E1
-#define GL_MAX_TEXTURE_UNITS              0x84E2
-#define GL_TRANSPOSE_MODELVIEW_MATRIX     0x84E3
-#define GL_TRANSPOSE_PROJECTION_MATRIX    0x84E4
-#define GL_TRANSPOSE_TEXTURE_MATRIX       0x84E5
-#define GL_TRANSPOSE_COLOR_MATRIX         0x84E6
-#define GL_MULTISAMPLE                    0x809D
-#define GL_SAMPLE_ALPHA_TO_COVERAGE       0x809E
-#define GL_SAMPLE_ALPHA_TO_ONE            0x809F
-#define GL_SAMPLE_COVERAGE                0x80A0
-#define GL_SAMPLE_BUFFERS                 0x80A8
-#define GL_SAMPLES                        0x80A9
-#define GL_SAMPLE_COVERAGE_VALUE          0x80AA
-#define GL_SAMPLE_COVERAGE_INVERT         0x80AB
-#define GL_MULTISAMPLE_BIT                0x20000000
-#define GL_NORMAL_MAP                     0x8511
-#define GL_REFLECTION_MAP                 0x8512
-#define GL_TEXTURE_CUBE_MAP               0x8513
-#define GL_TEXTURE_BINDING_CUBE_MAP       0x8514
-#define GL_TEXTURE_CUBE_MAP_POSITIVE_X    0x8515
-#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X    0x8516
-#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y    0x8517
-#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y    0x8518
-#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z    0x8519
-#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z    0x851A
-#define GL_PROXY_TEXTURE_CUBE_MAP         0x851B
-#define GL_MAX_CUBE_MAP_TEXTURE_SIZE      0x851C
-#define GL_COMPRESSED_ALPHA               0x84E9
-#define GL_COMPRESSED_LUMINANCE           0x84EA
-#define GL_COMPRESSED_LUMINANCE_ALPHA     0x84EB
-#define GL_COMPRESSED_INTENSITY           0x84EC
-#define GL_COMPRESSED_RGB                 0x84ED
-#define GL_COMPRESSED_RGBA                0x84EE
-#define GL_TEXTURE_COMPRESSION_HINT       0x84EF
-#define GL_TEXTURE_COMPRESSED_IMAGE_SIZE  0x86A0
-#define GL_TEXTURE_COMPRESSED             0x86A1
-#define GL_NUM_COMPRESSED_TEXTURE_FORMATS 0x86A2
-#define GL_COMPRESSED_TEXTURE_FORMATS     0x86A3
-#define GL_CLAMP_TO_BORDER                0x812D
-#define GL_COMBINE                        0x8570
-#define GL_COMBINE_RGB                    0x8571
-#define GL_COMBINE_ALPHA                  0x8572
-#define GL_SOURCE0_RGB                    0x8580
-#define GL_SOURCE1_RGB                    0x8581
-#define GL_SOURCE2_RGB                    0x8582
-#define GL_SOURCE0_ALPHA                  0x8588
-#define GL_SOURCE1_ALPHA                  0x8589
-#define GL_SOURCE2_ALPHA                  0x858A
-#define GL_OPERAND0_RGB                   0x8590
-#define GL_OPERAND1_RGB                   0x8591
-#define GL_OPERAND2_RGB                   0x8592
-#define GL_OPERAND0_ALPHA                 0x8598
-#define GL_OPERAND1_ALPHA                 0x8599
-#define GL_OPERAND2_ALPHA                 0x859A
-#define GL_RGB_SCALE                      0x8573
-#define GL_ADD_SIGNED                     0x8574
-#define GL_INTERPOLATE                    0x8575
-#define GL_SUBTRACT                       0x84E7
-#define GL_CONSTANT                       0x8576
-#define GL_PRIMARY_COLOR                  0x8577
-#define GL_PREVIOUS                       0x8578
-#define GL_DOT3_RGB                       0x86AE
-#define GL_DOT3_RGBA                      0x86AF
-#endif
-
-#ifndef GL_VERSION_1_4
-#define GL_BLEND_DST_RGB                  0x80C8
-#define GL_BLEND_SRC_RGB                  0x80C9
-#define GL_BLEND_DST_ALPHA                0x80CA
-#define GL_BLEND_SRC_ALPHA                0x80CB
-#define GL_POINT_SIZE_MIN                 0x8126
-#define GL_POINT_SIZE_MAX                 0x8127
-#define GL_POINT_FADE_THRESHOLD_SIZE      0x8128
-#define GL_POINT_DISTANCE_ATTENUATION     0x8129
-#define GL_GENERATE_MIPMAP                0x8191
-#define GL_GENERATE_MIPMAP_HINT           0x8192
-#define GL_DEPTH_COMPONENT16              0x81A5
-#define GL_DEPTH_COMPONENT24              0x81A6
-#define GL_DEPTH_COMPONENT32              0x81A7
-#define GL_MIRRORED_REPEAT                0x8370
-#define GL_FOG_COORDINATE_SOURCE          0x8450
-#define GL_FOG_COORDINATE                 0x8451
-#define GL_FRAGMENT_DEPTH                 0x8452
-#define GL_CURRENT_FOG_COORDINATE         0x8453
-#define GL_FOG_COORDINATE_ARRAY_TYPE      0x8454
-#define GL_FOG_COORDINATE_ARRAY_STRIDE    0x8455
-#define GL_FOG_COORDINATE_ARRAY_POINTER   0x8456
-#define GL_FOG_COORDINATE_ARRAY           0x8457
-#define GL_COLOR_SUM                      0x8458
-#define GL_CURRENT_SECONDARY_COLOR        0x8459
-#define GL_SECONDARY_COLOR_ARRAY_SIZE     0x845A
-#define GL_SECONDARY_COLOR_ARRAY_TYPE     0x845B
-#define GL_SECONDARY_COLOR_ARRAY_STRIDE   0x845C
-#define GL_SECONDARY_COLOR_ARRAY_POINTER  0x845D
-#define GL_SECONDARY_COLOR_ARRAY          0x845E
-#define GL_MAX_TEXTURE_LOD_BIAS           0x84FD
-#define GL_TEXTURE_FILTER_CONTROL         0x8500
-#define GL_TEXTURE_LOD_BIAS               0x8501
-#define GL_INCR_WRAP                      0x8507
-#define GL_DECR_WRAP                      0x8508
-#define GL_TEXTURE_DEPTH_SIZE             0x884A
-#define GL_DEPTH_TEXTURE_MODE             0x884B
-#define GL_TEXTURE_COMPARE_MODE           0x884C
-#define GL_TEXTURE_COMPARE_FUNC           0x884D
-#define GL_COMPARE_R_TO_TEXTURE           0x884E
-#endif
-
-#ifndef GL_VERSION_1_5
-#define GL_BUFFER_SIZE                    0x8764
-#define GL_BUFFER_USAGE                   0x8765
-#define GL_QUERY_COUNTER_BITS             0x8864
-#define GL_CURRENT_QUERY                  0x8865
-#define GL_QUERY_RESULT                   0x8866
-#define GL_QUERY_RESULT_AVAILABLE         0x8867
-#define GL_ARRAY_BUFFER                   0x8892
-#define GL_ELEMENT_ARRAY_BUFFER           0x8893
-#define GL_ARRAY_BUFFER_BINDING           0x8894
-#define GL_ELEMENT_ARRAY_BUFFER_BINDING   0x8895
-#define GL_VERTEX_ARRAY_BUFFER_BINDING    0x8896
-#define GL_NORMAL_ARRAY_BUFFER_BINDING    0x8897
-#define GL_COLOR_ARRAY_BUFFER_BINDING     0x8898
-#define GL_INDEX_ARRAY_BUFFER_BINDING     0x8899
-#define GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING 0x889A
-#define GL_EDGE_FLAG_ARRAY_BUFFER_BINDING 0x889B
-#define GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING 0x889C
-#define GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING 0x889D
-#define GL_WEIGHT_ARRAY_BUFFER_BINDING    0x889E
-#define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING 0x889F
-#define GL_READ_ONLY                      0x88B8
-#define GL_WRITE_ONLY                     0x88B9
-#define GL_READ_WRITE                     0x88BA
-#define GL_BUFFER_ACCESS                  0x88BB
-#define GL_BUFFER_MAPPED                  0x88BC
-#define GL_BUFFER_MAP_POINTER             0x88BD
-#define GL_STREAM_DRAW                    0x88E0
-#define GL_STREAM_READ                    0x88E1
-#define GL_STREAM_COPY                    0x88E2
-#define GL_STATIC_DRAW                    0x88E4
-#define GL_STATIC_READ                    0x88E5
-#define GL_STATIC_COPY                    0x88E6
-#define GL_DYNAMIC_DRAW                   0x88E8
-#define GL_DYNAMIC_READ                   0x88E9
-#define GL_DYNAMIC_COPY                   0x88EA
-#define GL_SAMPLES_PASSED                 0x8914
-#define GL_FOG_COORD_SRC                  GL_FOG_COORDINATE_SOURCE
-#define GL_FOG_COORD                      GL_FOG_COORDINATE
-#define GL_CURRENT_FOG_COORD              GL_CURRENT_FOG_COORDINATE
-#define GL_FOG_COORD_ARRAY_TYPE           GL_FOG_COORDINATE_ARRAY_TYPE
-#define GL_FOG_COORD_ARRAY_STRIDE         GL_FOG_COORDINATE_ARRAY_STRIDE
-#define GL_FOG_COORD_ARRAY_POINTER        GL_FOG_COORDINATE_ARRAY_POINTER
-#define GL_FOG_COORD_ARRAY                GL_FOG_COORDINATE_ARRAY
-#define GL_FOG_COORD_ARRAY_BUFFER_BINDING GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING
-#define GL_SRC0_RGB                       GL_SOURCE0_RGB
-#define GL_SRC1_RGB                       GL_SOURCE1_RGB
-#define GL_SRC2_RGB                       GL_SOURCE2_RGB
-#define GL_SRC0_ALPHA                     GL_SOURCE0_ALPHA
-#define GL_SRC1_ALPHA                     GL_SOURCE1_ALPHA
-#define GL_SRC2_ALPHA                     GL_SOURCE2_ALPHA
-#endif
-
-#ifndef GL_VERSION_2_0
-#define GL_BLEND_EQUATION_RGB             GL_BLEND_EQUATION
-#define GL_VERTEX_ATTRIB_ARRAY_ENABLED    0x8622
-#define GL_VERTEX_ATTRIB_ARRAY_SIZE       0x8623
-#define GL_VERTEX_ATTRIB_ARRAY_STRIDE     0x8624
-#define GL_VERTEX_ATTRIB_ARRAY_TYPE       0x8625
-#define GL_CURRENT_VERTEX_ATTRIB          0x8626
-#define GL_VERTEX_PROGRAM_POINT_SIZE      0x8642
-#define GL_VERTEX_PROGRAM_TWO_SIDE        0x8643
-#define GL_VERTEX_ATTRIB_ARRAY_POINTER    0x8645
-#define GL_STENCIL_BACK_FUNC              0x8800
-#define GL_STENCIL_BACK_FAIL              0x8801
-#define GL_STENCIL_BACK_PASS_DEPTH_FAIL   0x8802
-#define GL_STENCIL_BACK_PASS_DEPTH_PASS   0x8803
-#define GL_MAX_DRAW_BUFFERS               0x8824
-#define GL_DRAW_BUFFER0                   0x8825
-#define GL_DRAW_BUFFER1                   0x8826
-#define GL_DRAW_BUFFER2                   0x8827
-#define GL_DRAW_BUFFER3                   0x8828
-#define GL_DRAW_BUFFER4                   0x8829
-#define GL_DRAW_BUFFER5                   0x882A
-#define GL_DRAW_BUFFER6                   0x882B
-#define GL_DRAW_BUFFER7                   0x882C
-#define GL_DRAW_BUFFER8                   0x882D
-#define GL_DRAW_BUFFER9                   0x882E
-#define GL_DRAW_BUFFER10                  0x882F
-#define GL_DRAW_BUFFER11                  0x8830
-#define GL_DRAW_BUFFER12                  0x8831
-#define GL_DRAW_BUFFER13                  0x8832
-#define GL_DRAW_BUFFER14                  0x8833
-#define GL_DRAW_BUFFER15                  0x8834
-#define GL_BLEND_EQUATION_ALPHA           0x883D
-#define GL_POINT_SPRITE                   0x8861
-#define GL_COORD_REPLACE                  0x8862
-#define GL_MAX_VERTEX_ATTRIBS             0x8869
-#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED 0x886A
-#define GL_MAX_TEXTURE_COORDS             0x8871
-#define GL_MAX_TEXTURE_IMAGE_UNITS        0x8872
-#define GL_FRAGMENT_SHADER                0x8B30
-#define GL_VERTEX_SHADER                  0x8B31
-#define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS 0x8B49
-#define GL_MAX_VERTEX_UNIFORM_COMPONENTS  0x8B4A
-#define GL_MAX_VARYING_FLOATS             0x8B4B
-#define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS 0x8B4C
-#define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS 0x8B4D
-#define GL_SHADER_TYPE                    0x8B4F
-#define GL_FLOAT_VEC2                     0x8B50
-#define GL_FLOAT_VEC3                     0x8B51
-#define GL_FLOAT_VEC4                     0x8B52
-#define GL_INT_VEC2                       0x8B53
-#define GL_INT_VEC3                       0x8B54
-#define GL_INT_VEC4                       0x8B55
-#define GL_BOOL                           0x8B56
-#define GL_BOOL_VEC2                      0x8B57
-#define GL_BOOL_VEC3                      0x8B58
-#define GL_BOOL_VEC4                      0x8B59
-#define GL_FLOAT_MAT2                     0x8B5A
-#define GL_FLOAT_MAT3                     0x8B5B
-#define GL_FLOAT_MAT4                     0x8B5C
-#define GL_SAMPLER_1D                     0x8B5D
-#define GL_SAMPLER_2D                     0x8B5E
-#define GL_SAMPLER_3D                     0x8B5F
-#define GL_SAMPLER_CUBE                   0x8B60
-#define GL_SAMPLER_1D_SHADOW              0x8B61
-#define GL_SAMPLER_2D_SHADOW              0x8B62
-#define GL_DELETE_STATUS                  0x8B80
-#define GL_COMPILE_STATUS                 0x8B81
-#define GL_LINK_STATUS                    0x8B82
-#define GL_VALIDATE_STATUS                0x8B83
-#define GL_INFO_LOG_LENGTH                0x8B84
-#define GL_ATTACHED_SHADERS               0x8B85
-#define GL_ACTIVE_UNIFORMS                0x8B86
-#define GL_ACTIVE_UNIFORM_MAX_LENGTH      0x8B87
-#define GL_SHADER_SOURCE_LENGTH           0x8B88
-#define GL_ACTIVE_ATTRIBUTES              0x8B89
-#define GL_ACTIVE_ATTRIBUTE_MAX_LENGTH    0x8B8A
-#define GL_FRAGMENT_SHADER_DERIVATIVE_HINT 0x8B8B
-#define GL_SHADING_LANGUAGE_VERSION       0x8B8C
-#define GL_CURRENT_PROGRAM                0x8B8D
-#define GL_POINT_SPRITE_COORD_ORIGIN      0x8CA0
-#define GL_LOWER_LEFT                     0x8CA1
-#define GL_UPPER_LEFT                     0x8CA2
-#define GL_STENCIL_BACK_REF               0x8CA3
-#define GL_STENCIL_BACK_VALUE_MASK        0x8CA4
-#define GL_STENCIL_BACK_WRITEMASK         0x8CA5
-#endif
-
-#ifndef GL_ARB_multitexture
-#define GL_TEXTURE0_ARB                   0x84C0
-#define GL_TEXTURE1_ARB                   0x84C1
-#define GL_TEXTURE2_ARB                   0x84C2
-#define GL_TEXTURE3_ARB                   0x84C3
-#define GL_TEXTURE4_ARB                   0x84C4
-#define GL_TEXTURE5_ARB                   0x84C5
-#define GL_TEXTURE6_ARB                   0x84C6
-#define GL_TEXTURE7_ARB                   0x84C7
-#define GL_TEXTURE8_ARB                   0x84C8
-#define GL_TEXTURE9_ARB                   0x84C9
-#define GL_TEXTURE10_ARB                  0x84CA
-#define GL_TEXTURE11_ARB                  0x84CB
-#define GL_TEXTURE12_ARB                  0x84CC
-#define GL_TEXTURE13_ARB                  0x84CD
-#define GL_TEXTURE14_ARB                  0x84CE
-#define GL_TEXTURE15_ARB                  0x84CF
-#define GL_TEXTURE16_ARB                  0x84D0
-#define GL_TEXTURE17_ARB                  0x84D1
-#define GL_TEXTURE18_ARB                  0x84D2
-#define GL_TEXTURE19_ARB                  0x84D3
-#define GL_TEXTURE20_ARB                  0x84D4
-#define GL_TEXTURE21_ARB                  0x84D5
-#define GL_TEXTURE22_ARB                  0x84D6
-#define GL_TEXTURE23_ARB                  0x84D7
-#define GL_TEXTURE24_ARB                  0x84D8
-#define GL_TEXTURE25_ARB                  0x84D9
-#define GL_TEXTURE26_ARB                  0x84DA
-#define GL_TEXTURE27_ARB                  0x84DB
-#define GL_TEXTURE28_ARB                  0x84DC
-#define GL_TEXTURE29_ARB                  0x84DD
-#define GL_TEXTURE30_ARB                  0x84DE
-#define GL_TEXTURE31_ARB                  0x84DF
-#define GL_ACTIVE_TEXTURE_ARB             0x84E0
-#define GL_CLIENT_ACTIVE_TEXTURE_ARB      0x84E1
-#define GL_MAX_TEXTURE_UNITS_ARB          0x84E2
-#endif
-
-#ifndef GL_ARB_transpose_matrix
-#define GL_TRANSPOSE_MODELVIEW_MATRIX_ARB 0x84E3
-#define GL_TRANSPOSE_PROJECTION_MATRIX_ARB 0x84E4
-#define GL_TRANSPOSE_TEXTURE_MATRIX_ARB   0x84E5
-#define GL_TRANSPOSE_COLOR_MATRIX_ARB     0x84E6
-#endif
-
-#ifndef GL_ARB_multisample
-#define GL_MULTISAMPLE_ARB                0x809D
-#define GL_SAMPLE_ALPHA_TO_COVERAGE_ARB   0x809E
-#define GL_SAMPLE_ALPHA_TO_ONE_ARB        0x809F
-#define GL_SAMPLE_COVERAGE_ARB            0x80A0
-#define GL_SAMPLE_BUFFERS_ARB             0x80A8
-#define GL_SAMPLES_ARB                    0x80A9
-#define GL_SAMPLE_COVERAGE_VALUE_ARB      0x80AA
-#define GL_SAMPLE_COVERAGE_INVERT_ARB     0x80AB
-#define GL_MULTISAMPLE_BIT_ARB            0x20000000
-#endif
-
-#ifndef GL_ARB_texture_env_add
-#endif
-
-#ifndef GL_ARB_texture_cube_map
-#define GL_NORMAL_MAP_ARB                 0x8511
-#define GL_REFLECTION_MAP_ARB             0x8512
-#define GL_TEXTURE_CUBE_MAP_ARB           0x8513
-#define GL_TEXTURE_BINDING_CUBE_MAP_ARB   0x8514
-#define GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB 0x8515
-#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB 0x8516
-#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB 0x8517
-#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB 0x8518
-#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB 0x8519
-#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB 0x851A
-#define GL_PROXY_TEXTURE_CUBE_MAP_ARB     0x851B
-#define GL_MAX_CUBE_MAP_TEXTURE_SIZE_ARB  0x851C
-#endif
-
-#ifndef GL_ARB_texture_compression
-#define GL_COMPRESSED_ALPHA_ARB           0x84E9
-#define GL_COMPRESSED_LUMINANCE_ARB       0x84EA
-#define GL_COMPRESSED_LUMINANCE_ALPHA_ARB 0x84EB
-#define GL_COMPRESSED_INTENSITY_ARB       0x84EC
-#define GL_COMPRESSED_RGB_ARB             0x84ED
-#define GL_COMPRESSED_RGBA_ARB            0x84EE
-#define GL_TEXTURE_COMPRESSION_HINT_ARB   0x84EF
-#define GL_TEXTURE_COMPRESSED_IMAGE_SIZE_ARB 0x86A0
-#define GL_TEXTURE_COMPRESSED_ARB         0x86A1
-#define GL_NUM_COMPRESSED_TEXTURE_FORMATS_ARB 0x86A2
-#define GL_COMPRESSED_TEXTURE_FORMATS_ARB 0x86A3
-#endif
-
-#ifndef GL_ARB_texture_border_clamp
-#define GL_CLAMP_TO_BORDER_ARB            0x812D
-#endif
-
-#ifndef GL_ARB_point_parameters
-#define GL_POINT_SIZE_MIN_ARB             0x8126
-#define GL_POINT_SIZE_MAX_ARB             0x8127
-#define GL_POINT_FADE_THRESHOLD_SIZE_ARB  0x8128
-#define GL_POINT_DISTANCE_ATTENUATION_ARB 0x8129
-#endif
-
-#ifndef GL_ARB_vertex_blend
-#define GL_MAX_VERTEX_UNITS_ARB           0x86A4
-#define GL_ACTIVE_VERTEX_UNITS_ARB        0x86A5
-#define GL_WEIGHT_SUM_UNITY_ARB           0x86A6
-#define GL_VERTEX_BLEND_ARB               0x86A7
-#define GL_CURRENT_WEIGHT_ARB             0x86A8
-#define GL_WEIGHT_ARRAY_TYPE_ARB          0x86A9
-#define GL_WEIGHT_ARRAY_STRIDE_ARB        0x86AA
-#define GL_WEIGHT_ARRAY_SIZE_ARB          0x86AB
-#define GL_WEIGHT_ARRAY_POINTER_ARB       0x86AC
-#define GL_WEIGHT_ARRAY_ARB               0x86AD
-#define GL_MODELVIEW0_ARB                 0x1700
-#define GL_MODELVIEW1_ARB                 0x850A
-#define GL_MODELVIEW2_ARB                 0x8722
-#define GL_MODELVIEW3_ARB                 0x8723
-#define GL_MODELVIEW4_ARB                 0x8724
-#define GL_MODELVIEW5_ARB                 0x8725
-#define GL_MODELVIEW6_ARB                 0x8726
-#define GL_MODELVIEW7_ARB                 0x8727
-#define GL_MODELVIEW8_ARB                 0x8728
-#define GL_MODELVIEW9_ARB                 0x8729
-#define GL_MODELVIEW10_ARB                0x872A
-#define GL_MODELVIEW11_ARB                0x872B
-#define GL_MODELVIEW12_ARB                0x872C
-#define GL_MODELVIEW13_ARB                0x872D
-#define GL_MODELVIEW14_ARB                0x872E
-#define GL_MODELVIEW15_ARB                0x872F
-#define GL_MODELVIEW16_ARB                0x8730
-#define GL_MODELVIEW17_ARB                0x8731
-#define GL_MODELVIEW18_ARB                0x8732
-#define GL_MODELVIEW19_ARB                0x8733
-#define GL_MODELVIEW20_ARB                0x8734
-#define GL_MODELVIEW21_ARB                0x8735
-#define GL_MODELVIEW22_ARB                0x8736
-#define GL_MODELVIEW23_ARB                0x8737
-#define GL_MODELVIEW24_ARB                0x8738
-#define GL_MODELVIEW25_ARB                0x8739
-#define GL_MODELVIEW26_ARB                0x873A
-#define GL_MODELVIEW27_ARB                0x873B
-#define GL_MODELVIEW28_ARB                0x873C
-#define GL_MODELVIEW29_ARB                0x873D
-#define GL_MODELVIEW30_ARB                0x873E
-#define GL_MODELVIEW31_ARB                0x873F
-#endif
-
-#ifndef GL_ARB_matrix_palette
-#define GL_MATRIX_PALETTE_ARB             0x8840
-#define GL_MAX_MATRIX_PALETTE_STACK_DEPTH_ARB 0x8841
-#define GL_MAX_PALETTE_MATRICES_ARB       0x8842
-#define GL_CURRENT_PALETTE_MATRIX_ARB     0x8843
-#define GL_MATRIX_INDEX_ARRAY_ARB         0x8844
-#define GL_CURRENT_MATRIX_INDEX_ARB       0x8845
-#define GL_MATRIX_INDEX_ARRAY_SIZE_ARB    0x8846
-#define GL_MATRIX_INDEX_ARRAY_TYPE_ARB    0x8847
-#define GL_MATRIX_INDEX_ARRAY_STRIDE_ARB  0x8848
-#define GL_MATRIX_INDEX_ARRAY_POINTER_ARB 0x8849
-#endif
-
-#ifndef GL_ARB_texture_env_combine
-#define GL_COMBINE_ARB                    0x8570
-#define GL_COMBINE_RGB_ARB                0x8571
-#define GL_COMBINE_ALPHA_ARB              0x8572
-#define GL_SOURCE0_RGB_ARB                0x8580
-#define GL_SOURCE1_RGB_ARB                0x8581
-#define GL_SOURCE2_RGB_ARB                0x8582
-#define GL_SOURCE0_ALPHA_ARB              0x8588
-#define GL_SOURCE1_ALPHA_ARB              0x8589
-#define GL_SOURCE2_ALPHA_ARB              0x858A
-#define GL_OPERAND0_RGB_ARB               0x8590
-#define GL_OPERAND1_RGB_ARB               0x8591
-#define GL_OPERAND2_RGB_ARB               0x8592
-#define GL_OPERAND0_ALPHA_ARB             0x8598
-#define GL_OPERAND1_ALPHA_ARB             0x8599
-#define GL_OPERAND2_ALPHA_ARB             0x859A
-#define GL_RGB_SCALE_ARB                  0x8573
-#define GL_ADD_SIGNED_ARB                 0x8574
-#define GL_INTERPOLATE_ARB                0x8575
-#define GL_SUBTRACT_ARB                   0x84E7
-#define GL_CONSTANT_ARB                   0x8576
-#define GL_PRIMARY_COLOR_ARB              0x8577
-#define GL_PREVIOUS_ARB                   0x8578
-#endif
-
-#ifndef GL_ARB_texture_env_crossbar
-#endif
-
-#ifndef GL_ARB_texture_env_dot3
-#define GL_DOT3_RGB_ARB                   0x86AE
-#define GL_DOT3_RGBA_ARB                  0x86AF
-#endif
-
-#ifndef GL_ARB_texture_mirrored_repeat
-#define GL_MIRRORED_REPEAT_ARB            0x8370
-#endif
-
-#ifndef GL_ARB_depth_texture
-#define GL_DEPTH_COMPONENT16_ARB          0x81A5
-#define GL_DEPTH_COMPONENT24_ARB          0x81A6
-#define GL_DEPTH_COMPONENT32_ARB          0x81A7
-#define GL_TEXTURE_DEPTH_SIZE_ARB         0x884A
-#define GL_DEPTH_TEXTURE_MODE_ARB         0x884B
-#endif
-
-#ifndef GL_ARB_shadow
-#define GL_TEXTURE_COMPARE_MODE_ARB       0x884C
-#define GL_TEXTURE_COMPARE_FUNC_ARB       0x884D
-#define GL_COMPARE_R_TO_TEXTURE_ARB       0x884E
-#endif
-
-#ifndef GL_ARB_shadow_ambient
-#define GL_TEXTURE_COMPARE_FAIL_VALUE_ARB 0x80BF
-#endif
-
-#ifndef GL_ARB_window_pos
-#endif
-
-#ifndef GL_ARB_vertex_program
-#define GL_COLOR_SUM_ARB                  0x8458
-#define GL_VERTEX_PROGRAM_ARB             0x8620
-#define GL_VERTEX_ATTRIB_ARRAY_ENABLED_ARB 0x8622
-#define GL_VERTEX_ATTRIB_ARRAY_SIZE_ARB   0x8623
-#define GL_VERTEX_ATTRIB_ARRAY_STRIDE_ARB 0x8624
-#define GL_VERTEX_ATTRIB_ARRAY_TYPE_ARB   0x8625
-#define GL_CURRENT_VERTEX_ATTRIB_ARB      0x8626
-#define GL_PROGRAM_LENGTH_ARB             0x8627
-#define GL_PROGRAM_STRING_ARB             0x8628
-#define GL_MAX_PROGRAM_MATRIX_STACK_DEPTH_ARB 0x862E
-#define GL_MAX_PROGRAM_MATRICES_ARB       0x862F
-#define GL_CURRENT_MATRIX_STACK_DEPTH_ARB 0x8640
-#define GL_CURRENT_MATRIX_ARB             0x8641
-#define GL_VERTEX_PROGRAM_POINT_SIZE_ARB  0x8642
-#define GL_VERTEX_PROGRAM_TWO_SIDE_ARB    0x8643
-#define GL_VERTEX_ATTRIB_ARRAY_POINTER_ARB 0x8645
-#define GL_PROGRAM_ERROR_POSITION_ARB     0x864B
-#define GL_PROGRAM_BINDING_ARB            0x8677
-#define GL_MAX_VERTEX_ATTRIBS_ARB         0x8869
-#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED_ARB 0x886A
-#define GL_PROGRAM_ERROR_STRING_ARB       0x8874
-#define GL_PROGRAM_FORMAT_ASCII_ARB       0x8875
-#define GL_PROGRAM_FORMAT_ARB             0x8876
-#define GL_PROGRAM_INSTRUCTIONS_ARB       0x88A0
-#define GL_MAX_PROGRAM_INSTRUCTIONS_ARB   0x88A1
-#define GL_PROGRAM_NATIVE_INSTRUCTIONS_ARB 0x88A2
-#define GL_MAX_PROGRAM_NATIVE_INSTRUCTIONS_ARB 0x88A3
-#define GL_PROGRAM_TEMPORARIES_ARB        0x88A4
-#define GL_MAX_PROGRAM_TEMPORARIES_ARB    0x88A5
-#define GL_PROGRAM_NATIVE_TEMPORARIES_ARB 0x88A6
-#define GL_MAX_PROGRAM_NATIVE_TEMPORARIES_ARB 0x88A7
-#define GL_PROGRAM_PARAMETERS_ARB         0x88A8
-#define GL_MAX_PROGRAM_PARAMETERS_ARB     0x88A9
-#define GL_PROGRAM_NATIVE_PARAMETERS_ARB  0x88AA
-#define GL_MAX_PROGRAM_NATIVE_PARAMETERS_ARB 0x88AB
-#define GL_PROGRAM_ATTRIBS_ARB            0x88AC
-#define GL_MAX_PROGRAM_ATTRIBS_ARB        0x88AD
-#define GL_PROGRAM_NATIVE_ATTRIBS_ARB     0x88AE
-#define GL_MAX_PROGRAM_NATIVE_ATTRIBS_ARB 0x88AF
-#define GL_PROGRAM_ADDRESS_REGISTERS_ARB  0x88B0
-#define GL_MAX_PROGRAM_ADDRESS_REGISTERS_ARB 0x88B1
-#define GL_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB 0x88B2
-#define GL_MAX_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB 0x88B3
-#define GL_MAX_PROGRAM_LOCAL_PARAMETERS_ARB 0x88B4
-#define GL_MAX_PROGRAM_ENV_PARAMETERS_ARB 0x88B5
-#define GL_PROGRAM_UNDER_NATIVE_LIMITS_ARB 0x88B6
-#define GL_TRANSPOSE_CURRENT_MATRIX_ARB   0x88B7
-#define GL_MATRIX0_ARB                    0x88C0
-#define GL_MATRIX1_ARB                    0x88C1
-#define GL_MATRIX2_ARB                    0x88C2
-#define GL_MATRIX3_ARB                    0x88C3
-#define GL_MATRIX4_ARB                    0x88C4
-#define GL_MATRIX5_ARB                    0x88C5
-#define GL_MATRIX6_ARB                    0x88C6
-#define GL_MATRIX7_ARB                    0x88C7
-#define GL_MATRIX8_ARB                    0x88C8
-#define GL_MATRIX9_ARB                    0x88C9
-#define GL_MATRIX10_ARB                   0x88CA
-#define GL_MATRIX11_ARB                   0x88CB
-#define GL_MATRIX12_ARB                   0x88CC
-#define GL_MATRIX13_ARB                   0x88CD
-#define GL_MATRIX14_ARB                   0x88CE
-#define GL_MATRIX15_ARB                   0x88CF
-#define GL_MATRIX16_ARB                   0x88D0
-#define GL_MATRIX17_ARB                   0x88D1
-#define GL_MATRIX18_ARB                   0x88D2
-#define GL_MATRIX19_ARB                   0x88D3
-#define GL_MATRIX20_ARB                   0x88D4
-#define GL_MATRIX21_ARB                   0x88D5
-#define GL_MATRIX22_ARB                   0x88D6
-#define GL_MATRIX23_ARB                   0x88D7
-#define GL_MATRIX24_ARB                   0x88D8
-#define GL_MATRIX25_ARB                   0x88D9
-#define GL_MATRIX26_ARB                   0x88DA
-#define GL_MATRIX27_ARB                   0x88DB
-#define GL_MATRIX28_ARB                   0x88DC
-#define GL_MATRIX29_ARB                   0x88DD
-#define GL_MATRIX30_ARB                   0x88DE
-#define GL_MATRIX31_ARB                   0x88DF
-#endif
-
-#ifndef GL_ARB_fragment_program
-#define GL_FRAGMENT_PROGRAM_ARB           0x8804
-#define GL_PROGRAM_ALU_INSTRUCTIONS_ARB   0x8805
-#define GL_PROGRAM_TEX_INSTRUCTIONS_ARB   0x8806
-#define GL_PROGRAM_TEX_INDIRECTIONS_ARB   0x8807
-#define GL_PROGRAM_NATIVE_ALU_INSTRUCTIONS_ARB 0x8808
-#define GL_PROGRAM_NATIVE_TEX_INSTRUCTIONS_ARB 0x8809
-#define GL_PROGRAM_NATIVE_TEX_INDIRECTIONS_ARB 0x880A
-#define GL_MAX_PROGRAM_ALU_INSTRUCTIONS_ARB 0x880B
-#define GL_MAX_PROGRAM_TEX_INSTRUCTIONS_ARB 0x880C
-#define GL_MAX_PROGRAM_TEX_INDIRECTIONS_ARB 0x880D
-#define GL_MAX_PROGRAM_NATIVE_ALU_INSTRUCTIONS_ARB 0x880E
-#define GL_MAX_PROGRAM_NATIVE_TEX_INSTRUCTIONS_ARB 0x880F
-#define GL_MAX_PROGRAM_NATIVE_TEX_INDIRECTIONS_ARB 0x8810
-#define GL_MAX_TEXTURE_COORDS_ARB         0x8871
-#define GL_MAX_TEXTURE_IMAGE_UNITS_ARB    0x8872
-#endif
-
-#ifndef GL_ARB_vertex_buffer_object
-#define GL_BUFFER_SIZE_ARB                0x8764
-#define GL_BUFFER_USAGE_ARB               0x8765
-#define GL_ARRAY_BUFFER_ARB               0x8892
-#define GL_ELEMENT_ARRAY_BUFFER_ARB       0x8893
-#define GL_ARRAY_BUFFER_BINDING_ARB       0x8894
-#define GL_ELEMENT_ARRAY_BUFFER_BINDING_ARB 0x8895
-#define GL_VERTEX_ARRAY_BUFFER_BINDING_ARB 0x8896
-#define GL_NORMAL_ARRAY_BUFFER_BINDING_ARB 0x8897
-#define GL_COLOR_ARRAY_BUFFER_BINDING_ARB 0x8898
-#define GL_INDEX_ARRAY_BUFFER_BINDING_ARB 0x8899
-#define GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING_ARB 0x889A
-#define GL_EDGE_FLAG_ARRAY_BUFFER_BINDING_ARB 0x889B
-#define GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING_ARB 0x889C
-#define GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING_ARB 0x889D
-#define GL_WEIGHT_ARRAY_BUFFER_BINDING_ARB 0x889E
-#define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING_ARB 0x889F
-#define GL_READ_ONLY_ARB                  0x88B8
-#define GL_WRITE_ONLY_ARB                 0x88B9
-#define GL_READ_WRITE_ARB                 0x88BA
-#define GL_BUFFER_ACCESS_ARB              0x88BB
-#define GL_BUFFER_MAPPED_ARB              0x88BC
-#define GL_BUFFER_MAP_POINTER_ARB         0x88BD
-#define GL_STREAM_DRAW_ARB                0x88E0
-#define GL_STREAM_READ_ARB                0x88E1
-#define GL_STREAM_COPY_ARB                0x88E2
-#define GL_STATIC_DRAW_ARB                0x88E4
-#define GL_STATIC_READ_ARB                0x88E5
-#define GL_STATIC_COPY_ARB                0x88E6
-#define GL_DYNAMIC_DRAW_ARB               0x88E8
-#define GL_DYNAMIC_READ_ARB               0x88E9
-#define GL_DYNAMIC_COPY_ARB               0x88EA
-#endif
-
-#ifndef GL_ARB_occlusion_query
-#define GL_QUERY_COUNTER_BITS_ARB         0x8864
-#define GL_CURRENT_QUERY_ARB              0x8865
-#define GL_QUERY_RESULT_ARB               0x8866
-#define GL_QUERY_RESULT_AVAILABLE_ARB     0x8867
-#define GL_SAMPLES_PASSED_ARB             0x8914
-#endif
-
-#ifndef GL_ARB_shader_objects
-#define GL_PROGRAM_OBJECT_ARB             0x8B40
-#define GL_SHADER_OBJECT_ARB              0x8B48
-#define GL_OBJECT_TYPE_ARB                0x8B4E
-#define GL_OBJECT_SUBTYPE_ARB             0x8B4F
-#define GL_FLOAT_VEC2_ARB                 0x8B50
-#define GL_FLOAT_VEC3_ARB                 0x8B51
-#define GL_FLOAT_VEC4_ARB                 0x8B52
-#define GL_INT_VEC2_ARB                   0x8B53
-#define GL_INT_VEC3_ARB                   0x8B54
-#define GL_INT_VEC4_ARB                   0x8B55
-#define GL_BOOL_ARB                       0x8B56
-#define GL_BOOL_VEC2_ARB                  0x8B57
-#define GL_BOOL_VEC3_ARB                  0x8B58
-#define GL_BOOL_VEC4_ARB                  0x8B59
-#define GL_FLOAT_MAT2_ARB                 0x8B5A
-#define GL_FLOAT_MAT3_ARB                 0x8B5B
-#define GL_FLOAT_MAT4_ARB                 0x8B5C
-#define GL_SAMPLER_1D_ARB                 0x8B5D
-#define GL_SAMPLER_2D_ARB                 0x8B5E
-#define GL_SAMPLER_3D_ARB                 0x8B5F
-#define GL_SAMPLER_CUBE_ARB               0x8B60
-#define GL_SAMPLER_1D_SHADOW_ARB          0x8B61
-#define GL_SAMPLER_2D_SHADOW_ARB          0x8B62
-#define GL_SAMPLER_2D_RECT_ARB            0x8B63
-#define GL_SAMPLER_2D_RECT_SHADOW_ARB     0x8B64
-#define GL_OBJECT_DELETE_STATUS_ARB       0x8B80
-#define GL_OBJECT_COMPILE_STATUS_ARB      0x8B81
-#define GL_OBJECT_LINK_STATUS_ARB         0x8B82
-#define GL_OBJECT_VALIDATE_STATUS_ARB     0x8B83
-#define GL_OBJECT_INFO_LOG_LENGTH_ARB     0x8B84
-#define GL_OBJECT_ATTACHED_OBJECTS_ARB    0x8B85
-#define GL_OBJECT_ACTIVE_UNIFORMS_ARB     0x8B86
-#define GL_OBJECT_ACTIVE_UNIFORM_MAX_LENGTH_ARB 0x8B87
-#define GL_OBJECT_SHADER_SOURCE_LENGTH_ARB 0x8B88
-#endif
-
-#ifndef GL_ARB_vertex_shader
-#define GL_VERTEX_SHADER_ARB              0x8B31
-#define GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB 0x8B4A
-#define GL_MAX_VARYING_FLOATS_ARB         0x8B4B
-#define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB 0x8B4C
-#define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB 0x8B4D
-#define GL_OBJECT_ACTIVE_ATTRIBUTES_ARB   0x8B89
-#define GL_OBJECT_ACTIVE_ATTRIBUTE_MAX_LENGTH_ARB 0x8B8A
-#endif
-
-#ifndef GL_ARB_fragment_shader
-#define GL_FRAGMENT_SHADER_ARB            0x8B30
-#define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS_ARB 0x8B49
-#define GL_FRAGMENT_SHADER_DERIVATIVE_HINT_ARB 0x8B8B
-#endif
-
-#ifndef GL_ARB_shading_language_100
-#define GL_SHADING_LANGUAGE_VERSION_ARB   0x8B8C
-#endif
-
-#ifndef GL_ARB_texture_non_power_of_two
-#endif
-
-#ifndef GL_ARB_point_sprite
-#define GL_POINT_SPRITE_ARB               0x8861
-#define GL_COORD_REPLACE_ARB              0x8862
-#endif
-
-#ifndef GL_ARB_fragment_program_shadow
-#endif
-
-#ifndef GL_ARB_draw_buffers
-#define GL_MAX_DRAW_BUFFERS_ARB           0x8824
-#define GL_DRAW_BUFFER0_ARB               0x8825
-#define GL_DRAW_BUFFER1_ARB               0x8826
-#define GL_DRAW_BUFFER2_ARB               0x8827
-#define GL_DRAW_BUFFER3_ARB               0x8828
-#define GL_DRAW_BUFFER4_ARB               0x8829
-#define GL_DRAW_BUFFER5_ARB               0x882A
-#define GL_DRAW_BUFFER6_ARB               0x882B
-#define GL_DRAW_BUFFER7_ARB               0x882C
-#define GL_DRAW_BUFFER8_ARB               0x882D
-#define GL_DRAW_BUFFER9_ARB               0x882E
-#define GL_DRAW_BUFFER10_ARB              0x882F
-#define GL_DRAW_BUFFER11_ARB              0x8830
-#define GL_DRAW_BUFFER12_ARB              0x8831
-#define GL_DRAW_BUFFER13_ARB              0x8832
-#define GL_DRAW_BUFFER14_ARB              0x8833
-#define GL_DRAW_BUFFER15_ARB              0x8834
-#endif
-
-#ifndef GL_ARB_texture_rectangle
-#define GL_TEXTURE_RECTANGLE_ARB          0x84F5
-#define GL_TEXTURE_BINDING_RECTANGLE_ARB  0x84F6
-#define GL_PROXY_TEXTURE_RECTANGLE_ARB    0x84F7
-#define GL_MAX_RECTANGLE_TEXTURE_SIZE_ARB 0x84F8
-#endif
-
-#ifndef GL_ARB_color_buffer_float
-#define GL_RGBA_FLOAT_MODE_ARB            0x8820
-#define GL_CLAMP_VERTEX_COLOR_ARB         0x891A
-#define GL_CLAMP_FRAGMENT_COLOR_ARB       0x891B
-#define GL_CLAMP_READ_COLOR_ARB           0x891C
-#define GL_FIXED_ONLY_ARB                 0x891D
-#endif
-
-#ifndef GL_ARB_half_float_pixel
-#define GL_HALF_FLOAT_ARB                 0x140B
-#endif
-
-#ifndef GL_ARB_texture_float
-#define GL_TEXTURE_RED_TYPE_ARB           0x8C10
-#define GL_TEXTURE_GREEN_TYPE_ARB         0x8C11
-#define GL_TEXTURE_BLUE_TYPE_ARB          0x8C12
-#define GL_TEXTURE_ALPHA_TYPE_ARB         0x8C13
-#define GL_TEXTURE_LUMINANCE_TYPE_ARB     0x8C14
-#define GL_TEXTURE_INTENSITY_TYPE_ARB     0x8C15
-#define GL_TEXTURE_DEPTH_TYPE_ARB         0x8C16
-#define GL_UNSIGNED_NORMALIZED_ARB        0x8C17
-#define GL_RGBA32F_ARB                    0x8814
-#define GL_RGB32F_ARB                     0x8815
-#define GL_ALPHA32F_ARB                   0x8816
-#define GL_INTENSITY32F_ARB               0x8817
-#define GL_LUMINANCE32F_ARB               0x8818
-#define GL_LUMINANCE_ALPHA32F_ARB         0x8819
-#define GL_RGBA16F_ARB                    0x881A
-#define GL_RGB16F_ARB                     0x881B
-#define GL_ALPHA16F_ARB                   0x881C
-#define GL_INTENSITY16F_ARB               0x881D
-#define GL_LUMINANCE16F_ARB               0x881E
-#define GL_LUMINANCE_ALPHA16F_ARB         0x881F
-#endif
-
-#ifndef GL_ARB_pixel_buffer_object
-#define GL_PIXEL_PACK_BUFFER_ARB          0x88EB
-#define GL_PIXEL_UNPACK_BUFFER_ARB        0x88EC
-#define GL_PIXEL_PACK_BUFFER_BINDING_ARB  0x88ED
-#define GL_PIXEL_UNPACK_BUFFER_BINDING_ARB 0x88EF
-#endif
-
-#ifndef GL_EXT_abgr
-#define GL_ABGR_EXT                       0x8000
-#endif
-
-#ifndef GL_EXT_blend_color
-#define GL_CONSTANT_COLOR_EXT             0x8001
-#define GL_ONE_MINUS_CONSTANT_COLOR_EXT   0x8002
-#define GL_CONSTANT_ALPHA_EXT             0x8003
-#define GL_ONE_MINUS_CONSTANT_ALPHA_EXT   0x8004
-#define GL_BLEND_COLOR_EXT                0x8005
-#endif
-
-#ifndef GL_EXT_polygon_offset
-#define GL_POLYGON_OFFSET_EXT             0x8037
-#define GL_POLYGON_OFFSET_FACTOR_EXT      0x8038
-#define GL_POLYGON_OFFSET_BIAS_EXT        0x8039
-#endif
-
-#ifndef GL_EXT_texture
-#define GL_ALPHA4_EXT                     0x803B
-#define GL_ALPHA8_EXT                     0x803C
-#define GL_ALPHA12_EXT                    0x803D
-#define GL_ALPHA16_EXT                    0x803E
-#define GL_LUMINANCE4_EXT                 0x803F
-#define GL_LUMINANCE8_EXT                 0x8040
-#define GL_LUMINANCE12_EXT                0x8041
-#define GL_LUMINANCE16_EXT                0x8042
-#define GL_LUMINANCE4_ALPHA4_EXT          0x8043
-#define GL_LUMINANCE6_ALPHA2_EXT          0x8044
-#define GL_LUMINANCE8_ALPHA8_EXT          0x8045
-#define GL_LUMINANCE12_ALPHA4_EXT         0x8046
-#define GL_LUMINANCE12_ALPHA12_EXT        0x8047
-#define GL_LUMINANCE16_ALPHA16_EXT        0x8048
-#define GL_INTENSITY_EXT                  0x8049
-#define GL_INTENSITY4_EXT                 0x804A
-#define GL_INTENSITY8_EXT                 0x804B
-#define GL_INTENSITY12_EXT                0x804C
-#define GL_INTENSITY16_EXT                0x804D
-#define GL_RGB2_EXT                       0x804E
-#define GL_RGB4_EXT                       0x804F
-#define GL_RGB5_EXT                       0x8050
-#define GL_RGB8_EXT                       0x8051
-#define GL_RGB10_EXT                      0x8052
-#define GL_RGB12_EXT                      0x8053
-#define GL_RGB16_EXT                      0x8054
-#define GL_RGBA2_EXT                      0x8055
-#define GL_RGBA4_EXT                      0x8056
-#define GL_RGB5_A1_EXT                    0x8057
-#define GL_RGBA8_EXT                      0x8058
-#define GL_RGB10_A2_EXT                   0x8059
-#define GL_RGBA12_EXT                     0x805A
-#define GL_RGBA16_EXT                     0x805B
-#define GL_TEXTURE_RED_SIZE_EXT           0x805C
-#define GL_TEXTURE_GREEN_SIZE_EXT         0x805D
-#define GL_TEXTURE_BLUE_SIZE_EXT          0x805E
-#define GL_TEXTURE_ALPHA_SIZE_EXT         0x805F
-#define GL_TEXTURE_LUMINANCE_SIZE_EXT     0x8060
-#define GL_TEXTURE_INTENSITY_SIZE_EXT     0x8061
-#define GL_REPLACE_EXT                    0x8062
-#define GL_PROXY_TEXTURE_1D_EXT           0x8063
-#define GL_PROXY_TEXTURE_2D_EXT           0x8064
-#define GL_TEXTURE_TOO_LARGE_EXT          0x8065
-#endif
-
-#ifndef GL_EXT_texture3D
-#define GL_PACK_SKIP_IMAGES_EXT           0x806B
-#define GL_PACK_IMAGE_HEIGHT_EXT          0x806C
-#define GL_UNPACK_SKIP_IMAGES_EXT         0x806D
-#define GL_UNPACK_IMAGE_HEIGHT_EXT        0x806E
-#define GL_TEXTURE_3D_EXT                 0x806F
-#define GL_PROXY_TEXTURE_3D_EXT           0x8070
-#define GL_TEXTURE_DEPTH_EXT              0x8071
-#define GL_TEXTURE_WRAP_R_EXT             0x8072
-#define GL_MAX_3D_TEXTURE_SIZE_EXT        0x8073
-#endif
-
-#ifndef GL_SGIS_texture_filter4
-#define GL_FILTER4_SGIS                   0x8146
-#define GL_TEXTURE_FILTER4_SIZE_SGIS      0x8147
-#endif
-
-#ifndef GL_EXT_subtexture
-#endif
-
-#ifndef GL_EXT_copy_texture
-#endif
-
-#ifndef GL_EXT_histogram
-#define GL_HISTOGRAM_EXT                  0x8024
-#define GL_PROXY_HISTOGRAM_EXT            0x8025
-#define GL_HISTOGRAM_WIDTH_EXT            0x8026
-#define GL_HISTOGRAM_FORMAT_EXT           0x8027
-#define GL_HISTOGRAM_RED_SIZE_EXT         0x8028
-#define GL_HISTOGRAM_GREEN_SIZE_EXT       0x8029
-#define GL_HISTOGRAM_BLUE_SIZE_EXT        0x802A
-#define GL_HISTOGRAM_ALPHA_SIZE_EXT       0x802B
-#define GL_HISTOGRAM_LUMINANCE_SIZE_EXT   0x802C
-#define GL_HISTOGRAM_SINK_EXT             0x802D
-#define GL_MINMAX_EXT                     0x802E
-#define GL_MINMAX_FORMAT_EXT              0x802F
-#define GL_MINMAX_SINK_EXT                0x8030
-#define GL_TABLE_TOO_LARGE_EXT            0x8031
-#endif
-
-#ifndef GL_EXT_convolution
-#define GL_CONVOLUTION_1D_EXT             0x8010
-#define GL_CONVOLUTION_2D_EXT             0x8011
-#define GL_SEPARABLE_2D_EXT               0x8012
-#define GL_CONVOLUTION_BORDER_MODE_EXT    0x8013
-#define GL_CONVOLUTION_FILTER_SCALE_EXT   0x8014
-#define GL_CONVOLUTION_FILTER_BIAS_EXT    0x8015
-#define GL_REDUCE_EXT                     0x8016
-#define GL_CONVOLUTION_FORMAT_EXT         0x8017
-#define GL_CONVOLUTION_WIDTH_EXT          0x8018
-#define GL_CONVOLUTION_HEIGHT_EXT         0x8019
-#define GL_MAX_CONVOLUTION_WIDTH_EXT      0x801A
-#define GL_MAX_CONVOLUTION_HEIGHT_EXT     0x801B
-#define GL_POST_CONVOLUTION_RED_SCALE_EXT 0x801C
-#define GL_POST_CONVOLUTION_GREEN_SCALE_EXT 0x801D
-#define GL_POST_CONVOLUTION_BLUE_SCALE_EXT 0x801E
-#define GL_POST_CONVOLUTION_ALPHA_SCALE_EXT 0x801F
-#define GL_POST_CONVOLUTION_RED_BIAS_EXT  0x8020
-#define GL_POST_CONVOLUTION_GREEN_BIAS_EXT 0x8021
-#define GL_POST_CONVOLUTION_BLUE_BIAS_EXT 0x8022
-#define GL_POST_CONVOLUTION_ALPHA_BIAS_EXT 0x8023
-#endif
-
-#ifndef GL_SGI_color_matrix
-#define GL_COLOR_MATRIX_SGI               0x80B1
-#define GL_COLOR_MATRIX_STACK_DEPTH_SGI   0x80B2
-#define GL_MAX_COLOR_MATRIX_STACK_DEPTH_SGI 0x80B3
-#define GL_POST_COLOR_MATRIX_RED_SCALE_SGI 0x80B4
-#define GL_POST_COLOR_MATRIX_GREEN_SCALE_SGI 0x80B5
-#define GL_POST_COLOR_MATRIX_BLUE_SCALE_SGI 0x80B6
-#define GL_POST_COLOR_MATRIX_ALPHA_SCALE_SGI 0x80B7
-#define GL_POST_COLOR_MATRIX_RED_BIAS_SGI 0x80B8
-#define GL_POST_COLOR_MATRIX_GREEN_BIAS_SGI 0x80B9
-#define GL_POST_COLOR_MATRIX_BLUE_BIAS_SGI 0x80BA
-#define GL_POST_COLOR_MATRIX_ALPHA_BIAS_SGI 0x80BB
-#endif
-
-#ifndef GL_SGI_color_table
-#define GL_COLOR_TABLE_SGI                0x80D0
-#define GL_POST_CONVOLUTION_COLOR_TABLE_SGI 0x80D1
-#define GL_POST_COLOR_MATRIX_COLOR_TABLE_SGI 0x80D2
-#define GL_PROXY_COLOR_TABLE_SGI          0x80D3
-#define GL_PROXY_POST_CONVOLUTION_COLOR_TABLE_SGI 0x80D4
-#define GL_PROXY_POST_COLOR_MATRIX_COLOR_TABLE_SGI 0x80D5
-#define GL_COLOR_TABLE_SCALE_SGI          0x80D6
-#define GL_COLOR_TABLE_BIAS_SGI           0x80D7
-#define GL_COLOR_TABLE_FORMAT_SGI         0x80D8
-#define GL_COLOR_TABLE_WIDTH_SGI          0x80D9
-#define GL_COLOR_TABLE_RED_SIZE_SGI       0x80DA
-#define GL_COLOR_TABLE_GREEN_SIZE_SGI     0x80DB
-#define GL_COLOR_TABLE_BLUE_SIZE_SGI      0x80DC
-#define GL_COLOR_TABLE_ALPHA_SIZE_SGI     0x80DD
-#define GL_COLOR_TABLE_LUMINANCE_SIZE_SGI 0x80DE
-#define GL_COLOR_TABLE_INTENSITY_SIZE_SGI 0x80DF
-#endif
-
-#ifndef GL_SGIS_pixel_texture
-#define GL_PIXEL_TEXTURE_SGIS             0x8353
-#define GL_PIXEL_FRAGMENT_RGB_SOURCE_SGIS 0x8354
-#define GL_PIXEL_FRAGMENT_ALPHA_SOURCE_SGIS 0x8355
-#define GL_PIXEL_GROUP_COLOR_SGIS         0x8356
-#endif
-
-#ifndef GL_SGIX_pixel_texture
-#define GL_PIXEL_TEX_GEN_SGIX             0x8139
-#define GL_PIXEL_TEX_GEN_MODE_SGIX        0x832B
-#endif
-
-#ifndef GL_SGIS_texture4D
-#define GL_PACK_SKIP_VOLUMES_SGIS         0x8130
-#define GL_PACK_IMAGE_DEPTH_SGIS          0x8131
-#define GL_UNPACK_SKIP_VOLUMES_SGIS       0x8132
-#define GL_UNPACK_IMAGE_DEPTH_SGIS        0x8133
-#define GL_TEXTURE_4D_SGIS                0x8134
-#define GL_PROXY_TEXTURE_4D_SGIS          0x8135
-#define GL_TEXTURE_4DSIZE_SGIS            0x8136
-#define GL_TEXTURE_WRAP_Q_SGIS            0x8137
-#define GL_MAX_4D_TEXTURE_SIZE_SGIS       0x8138
-#define GL_TEXTURE_4D_BINDING_SGIS        0x814F
-#endif
-
-#ifndef GL_SGI_texture_color_table
-#define GL_TEXTURE_COLOR_TABLE_SGI        0x80BC
-#define GL_PROXY_TEXTURE_COLOR_TABLE_SGI  0x80BD
-#endif
-
-#ifndef GL_EXT_cmyka
-#define GL_CMYK_EXT                       0x800C
-#define GL_CMYKA_EXT                      0x800D
-#define GL_PACK_CMYK_HINT_EXT             0x800E
-#define GL_UNPACK_CMYK_HINT_EXT           0x800F
-#endif
-
-#ifndef GL_EXT_texture_object
-#define GL_TEXTURE_PRIORITY_EXT           0x8066
-#define GL_TEXTURE_RESIDENT_EXT           0x8067
-#define GL_TEXTURE_1D_BINDING_EXT         0x8068
-#define GL_TEXTURE_2D_BINDING_EXT         0x8069
-#define GL_TEXTURE_3D_BINDING_EXT         0x806A
-#endif
-
-#ifndef GL_SGIS_detail_texture
-#define GL_DETAIL_TEXTURE_2D_SGIS         0x8095
-#define GL_DETAIL_TEXTURE_2D_BINDING_SGIS 0x8096
-#define GL_LINEAR_DETAIL_SGIS             0x8097
-#define GL_LINEAR_DETAIL_ALPHA_SGIS       0x8098
-#define GL_LINEAR_DETAIL_COLOR_SGIS       0x8099
-#define GL_DETAIL_TEXTURE_LEVEL_SGIS      0x809A
-#define GL_DETAIL_TEXTURE_MODE_SGIS       0x809B
-#define GL_DETAIL_TEXTURE_FUNC_POINTS_SGIS 0x809C
-#endif
-
-#ifndef GL_SGIS_sharpen_texture
-#define GL_LINEAR_SHARPEN_SGIS            0x80AD
-#define GL_LINEAR_SHARPEN_ALPHA_SGIS      0x80AE
-#define GL_LINEAR_SHARPEN_COLOR_SGIS      0x80AF
-#define GL_SHARPEN_TEXTURE_FUNC_POINTS_SGIS 0x80B0
-#endif
-
-#ifndef GL_EXT_packed_pixels
-#define GL_UNSIGNED_BYTE_3_3_2_EXT        0x8032
-#define GL_UNSIGNED_SHORT_4_4_4_4_EXT     0x8033
-#define GL_UNSIGNED_SHORT_5_5_5_1_EXT     0x8034
-#define GL_UNSIGNED_INT_8_8_8_8_EXT       0x8035
-#define GL_UNSIGNED_INT_10_10_10_2_EXT    0x8036
-#endif
-
-#ifndef GL_SGIS_texture_lod
-#define GL_TEXTURE_MIN_LOD_SGIS           0x813A
-#define GL_TEXTURE_MAX_LOD_SGIS           0x813B
-#define GL_TEXTURE_BASE_LEVEL_SGIS        0x813C
-#define GL_TEXTURE_MAX_LEVEL_SGIS         0x813D
-#endif
-
-#ifndef GL_SGIS_multisample
-#define GL_MULTISAMPLE_SGIS               0x809D
-#define GL_SAMPLE_ALPHA_TO_MASK_SGIS      0x809E
-#define GL_SAMPLE_ALPHA_TO_ONE_SGIS       0x809F
-#define GL_SAMPLE_MASK_SGIS               0x80A0
-#define GL_1PASS_SGIS                     0x80A1
-#define GL_2PASS_0_SGIS                   0x80A2
-#define GL_2PASS_1_SGIS                   0x80A3
-#define GL_4PASS_0_SGIS                   0x80A4
-#define GL_4PASS_1_SGIS                   0x80A5
-#define GL_4PASS_2_SGIS                   0x80A6
-#define GL_4PASS_3_SGIS                   0x80A7
-#define GL_SAMPLE_BUFFERS_SGIS            0x80A8
-#define GL_SAMPLES_SGIS                   0x80A9
-#define GL_SAMPLE_MASK_VALUE_SGIS         0x80AA
-#define GL_SAMPLE_MASK_INVERT_SGIS        0x80AB
-#define GL_SAMPLE_PATTERN_SGIS            0x80AC
-#endif
-
-#ifndef GL_EXT_rescale_normal
-#define GL_RESCALE_NORMAL_EXT             0x803A
-#endif
-
-#ifndef GL_EXT_vertex_array
-#define GL_VERTEX_ARRAY_EXT               0x8074
-#define GL_NORMAL_ARRAY_EXT               0x8075
-#define GL_COLOR_ARRAY_EXT                0x8076
-#define GL_INDEX_ARRAY_EXT                0x8077
-#define GL_TEXTURE_COORD_ARRAY_EXT        0x8078
-#define GL_EDGE_FLAG_ARRAY_EXT            0x8079
-#define GL_VERTEX_ARRAY_SIZE_EXT          0x807A
-#define GL_VERTEX_ARRAY_TYPE_EXT          0x807B
-#define GL_VERTEX_ARRAY_STRIDE_EXT        0x807C
-#define GL_VERTEX_ARRAY_COUNT_EXT         0x807D
-#define GL_NORMAL_ARRAY_TYPE_EXT          0x807E
-#define GL_NORMAL_ARRAY_STRIDE_EXT        0x807F
-#define GL_NORMAL_ARRAY_COUNT_EXT         0x8080
-#define GL_COLOR_ARRAY_SIZE_EXT           0x8081
-#define GL_COLOR_ARRAY_TYPE_EXT           0x8082
-#define GL_COLOR_ARRAY_STRIDE_EXT         0x8083
-#define GL_COLOR_ARRAY_COUNT_EXT          0x8084
-#define GL_INDEX_ARRAY_TYPE_EXT           0x8085
-#define GL_INDEX_ARRAY_STRIDE_EXT         0x8086
-#define GL_INDEX_ARRAY_COUNT_EXT          0x8087
-#define GL_TEXTURE_COORD_ARRAY_SIZE_EXT   0x8088
-#define GL_TEXTURE_COORD_ARRAY_TYPE_EXT   0x8089
-#define GL_TEXTURE_COORD_ARRAY_STRIDE_EXT 0x808A
-#define GL_TEXTURE_COORD_ARRAY_COUNT_EXT  0x808B
-#define GL_EDGE_FLAG_ARRAY_STRIDE_EXT     0x808C
-#define GL_EDGE_FLAG_ARRAY_COUNT_EXT      0x808D
-#define GL_VERTEX_ARRAY_POINTER_EXT       0x808E
-#define GL_NORMAL_ARRAY_POINTER_EXT       0x808F
-#define GL_COLOR_ARRAY_POINTER_EXT        0x8090
-#define GL_INDEX_ARRAY_POINTER_EXT        0x8091
-#define GL_TEXTURE_COORD_ARRAY_POINTER_EXT 0x8092
-#define GL_EDGE_FLAG_ARRAY_POINTER_EXT    0x8093
-#endif
-
-#ifndef GL_EXT_misc_attribute
-#endif
-
-#ifndef GL_SGIS_generate_mipmap
-#define GL_GENERATE_MIPMAP_SGIS           0x8191
-#define GL_GENERATE_MIPMAP_HINT_SGIS      0x8192
-#endif
-
-#ifndef GL_SGIX_clipmap
-#define GL_LINEAR_CLIPMAP_LINEAR_SGIX     0x8170
-#define GL_TEXTURE_CLIPMAP_CENTER_SGIX    0x8171
-#define GL_TEXTURE_CLIPMAP_FRAME_SGIX     0x8172
-#define GL_TEXTURE_CLIPMAP_OFFSET_SGIX    0x8173
-#define GL_TEXTURE_CLIPMAP_VIRTUAL_DEPTH_SGIX 0x8174
-#define GL_TEXTURE_CLIPMAP_LOD_OFFSET_SGIX 0x8175
-#define GL_TEXTURE_CLIPMAP_DEPTH_SGIX     0x8176
-#define GL_MAX_CLIPMAP_DEPTH_SGIX         0x8177
-#define GL_MAX_CLIPMAP_VIRTUAL_DEPTH_SGIX 0x8178
-#define GL_NEAREST_CLIPMAP_NEAREST_SGIX   0x844D
-#define GL_NEAREST_CLIPMAP_LINEAR_SGIX    0x844E
-#define GL_LINEAR_CLIPMAP_NEAREST_SGIX    0x844F
-#endif
-
-#ifndef GL_SGIX_shadow
-#define GL_TEXTURE_COMPARE_SGIX           0x819A
-#define GL_TEXTURE_COMPARE_OPERATOR_SGIX  0x819B
-#define GL_TEXTURE_LEQUAL_R_SGIX          0x819C
-#define GL_TEXTURE_GEQUAL_R_SGIX          0x819D
-#endif
-
-#ifndef GL_SGIS_texture_edge_clamp
-#define GL_CLAMP_TO_EDGE_SGIS             0x812F
-#endif
-
-#ifndef GL_SGIS_texture_border_clamp
-#define GL_CLAMP_TO_BORDER_SGIS           0x812D
-#endif
-
-#ifndef GL_EXT_blend_minmax
-#define GL_FUNC_ADD_EXT                   0x8006
-#define GL_MIN_EXT                        0x8007
-#define GL_MAX_EXT                        0x8008
-#define GL_BLEND_EQUATION_EXT             0x8009
-#endif
-
-#ifndef GL_EXT_blend_subtract
-#define GL_FUNC_SUBTRACT_EXT              0x800A
-#define GL_FUNC_REVERSE_SUBTRACT_EXT      0x800B
-#endif
-
-#ifndef GL_EXT_blend_logic_op
-#endif
-
-#ifndef GL_SGIX_interlace
-#define GL_INTERLACE_SGIX                 0x8094
-#endif
-
-#ifndef GL_SGIX_pixel_tiles
-#define GL_PIXEL_TILE_BEST_ALIGNMENT_SGIX 0x813E
-#define GL_PIXEL_TILE_CACHE_INCREMENT_SGIX 0x813F
-#define GL_PIXEL_TILE_WIDTH_SGIX          0x8140
-#define GL_PIXEL_TILE_HEIGHT_SGIX         0x8141
-#define GL_PIXEL_TILE_GRID_WIDTH_SGIX     0x8142
-#define GL_PIXEL_TILE_GRID_HEIGHT_SGIX    0x8143
-#define GL_PIXEL_TILE_GRID_DEPTH_SGIX     0x8144
-#define GL_PIXEL_TILE_CACHE_SIZE_SGIX     0x8145
-#endif
-
-#ifndef GL_SGIS_texture_select
-#define GL_DUAL_ALPHA4_SGIS               0x8110
-#define GL_DUAL_ALPHA8_SGIS               0x8111
-#define GL_DUAL_ALPHA12_SGIS              0x8112
-#define GL_DUAL_ALPHA16_SGIS              0x8113
-#define GL_DUAL_LUMINANCE4_SGIS           0x8114
-#define GL_DUAL_LUMINANCE8_SGIS           0x8115
-#define GL_DUAL_LUMINANCE12_SGIS          0x8116
-#define GL_DUAL_LUMINANCE16_SGIS          0x8117
-#define GL_DUAL_INTENSITY4_SGIS           0x8118
-#define GL_DUAL_INTENSITY8_SGIS           0x8119
-#define GL_DUAL_INTENSITY12_SGIS          0x811A
-#define GL_DUAL_INTENSITY16_SGIS          0x811B
-#define GL_DUAL_LUMINANCE_ALPHA4_SGIS     0x811C
-#define GL_DUAL_LUMINANCE_ALPHA8_SGIS     0x811D
-#define GL_QUAD_ALPHA4_SGIS               0x811E
-#define GL_QUAD_ALPHA8_SGIS               0x811F
-#define GL_QUAD_LUMINANCE4_SGIS           0x8120
-#define GL_QUAD_LUMINANCE8_SGIS           0x8121
-#define GL_QUAD_INTENSITY4_SGIS           0x8122
-#define GL_QUAD_INTENSITY8_SGIS           0x8123
-#define GL_DUAL_TEXTURE_SELECT_SGIS       0x8124
-#define GL_QUAD_TEXTURE_SELECT_SGIS       0x8125
-#endif
-
-#ifndef GL_SGIX_sprite
-#define GL_SPRITE_SGIX                    0x8148
-#define GL_SPRITE_MODE_SGIX               0x8149
-#define GL_SPRITE_AXIS_SGIX               0x814A
-#define GL_SPRITE_TRANSLATION_SGIX        0x814B
-#define GL_SPRITE_AXIAL_SGIX              0x814C
-#define GL_SPRITE_OBJECT_ALIGNED_SGIX     0x814D
-#define GL_SPRITE_EYE_ALIGNED_SGIX        0x814E
-#endif
-
-#ifndef GL_SGIX_texture_multi_buffer
-#define GL_TEXTURE_MULTI_BUFFER_HINT_SGIX 0x812E
-#endif
-
-#ifndef GL_EXT_point_parameters
-#define GL_POINT_SIZE_MIN_EXT             0x8126
-#define GL_POINT_SIZE_MAX_EXT             0x8127
-#define GL_POINT_FADE_THRESHOLD_SIZE_EXT  0x8128
-#define GL_DISTANCE_ATTENUATION_EXT       0x8129
-#endif
-
-#ifndef GL_SGIS_point_parameters
-#define GL_POINT_SIZE_MIN_SGIS            0x8126
-#define GL_POINT_SIZE_MAX_SGIS            0x8127
-#define GL_POINT_FADE_THRESHOLD_SIZE_SGIS 0x8128
-#define GL_DISTANCE_ATTENUATION_SGIS      0x8129
-#endif
-
-#ifndef GL_SGIX_instruments
-#define GL_INSTRUMENT_BUFFER_POINTER_SGIX 0x8180
-#define GL_INSTRUMENT_MEASUREMENTS_SGIX   0x8181
-#endif
-
-#ifndef GL_SGIX_texture_scale_bias
-#define GL_POST_TEXTURE_FILTER_BIAS_SGIX  0x8179
-#define GL_POST_TEXTURE_FILTER_SCALE_SGIX 0x817A
-#define GL_POST_TEXTURE_FILTER_BIAS_RANGE_SGIX 0x817B
-#define GL_POST_TEXTURE_FILTER_SCALE_RANGE_SGIX 0x817C
-#endif
-
-#ifndef GL_SGIX_framezoom
-#define GL_FRAMEZOOM_SGIX                 0x818B
-#define GL_FRAMEZOOM_FACTOR_SGIX          0x818C
-#define GL_MAX_FRAMEZOOM_FACTOR_SGIX      0x818D
-#endif
-
-#ifndef GL_SGIX_tag_sample_buffer
-#endif
-
-#ifndef GL_FfdMaskSGIX
-#define GL_TEXTURE_DEFORMATION_BIT_SGIX   0x00000001
-#define GL_GEOMETRY_DEFORMATION_BIT_SGIX  0x00000002
-#endif
-
-#ifndef GL_SGIX_polynomial_ffd
-#define GL_GEOMETRY_DEFORMATION_SGIX      0x8194
-#define GL_TEXTURE_DEFORMATION_SGIX       0x8195
-#define GL_DEFORMATIONS_MASK_SGIX         0x8196
-#define GL_MAX_DEFORMATION_ORDER_SGIX     0x8197
-#endif
-
-#ifndef GL_SGIX_reference_plane
-#define GL_REFERENCE_PLANE_SGIX           0x817D
-#define GL_REFERENCE_PLANE_EQUATION_SGIX  0x817E
-#endif
-
-#ifndef GL_SGIX_flush_raster
-#endif
-
-#ifndef GL_SGIX_depth_texture
-#define GL_DEPTH_COMPONENT16_SGIX         0x81A5
-#define GL_DEPTH_COMPONENT24_SGIX         0x81A6
-#define GL_DEPTH_COMPONENT32_SGIX         0x81A7
-#endif
-
-#ifndef GL_SGIS_fog_function
-#define GL_FOG_FUNC_SGIS                  0x812A
-#define GL_FOG_FUNC_POINTS_SGIS           0x812B
-#define GL_MAX_FOG_FUNC_POINTS_SGIS       0x812C
-#endif
-
-#ifndef GL_SGIX_fog_offset
-#define GL_FOG_OFFSET_SGIX                0x8198
-#define GL_FOG_OFFSET_VALUE_SGIX          0x8199
-#endif
-
-#ifndef GL_HP_image_transform
-#define GL_IMAGE_SCALE_X_HP               0x8155
-#define GL_IMAGE_SCALE_Y_HP               0x8156
-#define GL_IMAGE_TRANSLATE_X_HP           0x8157
-#define GL_IMAGE_TRANSLATE_Y_HP           0x8158
-#define GL_IMAGE_ROTATE_ANGLE_HP          0x8159
-#define GL_IMAGE_ROTATE_ORIGIN_X_HP       0x815A
-#define GL_IMAGE_ROTATE_ORIGIN_Y_HP       0x815B
-#define GL_IMAGE_MAG_FILTER_HP            0x815C
-#define GL_IMAGE_MIN_FILTER_HP            0x815D
-#define GL_IMAGE_CUBIC_WEIGHT_HP          0x815E
-#define GL_CUBIC_HP                       0x815F
-#define GL_AVERAGE_HP                     0x8160
-#define GL_IMAGE_TRANSFORM_2D_HP          0x8161
-#define GL_POST_IMAGE_TRANSFORM_COLOR_TABLE_HP 0x8162
-#define GL_PROXY_POST_IMAGE_TRANSFORM_COLOR_TABLE_HP 0x8163
-#endif
-
-#ifndef GL_HP_convolution_border_modes
-#define GL_IGNORE_BORDER_HP               0x8150
-#define GL_CONSTANT_BORDER_HP             0x8151
-#define GL_REPLICATE_BORDER_HP            0x8153
-#define GL_CONVOLUTION_BORDER_COLOR_HP    0x8154
-#endif
-
-#ifndef GL_INGR_palette_buffer
-#endif
-
-#ifndef GL_SGIX_texture_add_env
-#define GL_TEXTURE_ENV_BIAS_SGIX          0x80BE
-#endif
-
-#ifndef GL_EXT_color_subtable
-#endif
-
-#ifndef GL_PGI_vertex_hints
-#define GL_VERTEX_DATA_HINT_PGI           0x1A22A
-#define GL_VERTEX_CONSISTENT_HINT_PGI     0x1A22B
-#define GL_MATERIAL_SIDE_HINT_PGI         0x1A22C
-#define GL_MAX_VERTEX_HINT_PGI            0x1A22D
-#define GL_COLOR3_BIT_PGI                 0x00010000
-#define GL_COLOR4_BIT_PGI                 0x00020000
-#define GL_EDGEFLAG_BIT_PGI               0x00040000
-#define GL_INDEX_BIT_PGI                  0x00080000
-#define GL_MAT_AMBIENT_BIT_PGI            0x00100000
-#define GL_MAT_AMBIENT_AND_DIFFUSE_BIT_PGI 0x00200000
-#define GL_MAT_DIFFUSE_BIT_PGI            0x00400000
-#define GL_MAT_EMISSION_BIT_PGI           0x00800000
-#define GL_MAT_COLOR_INDEXES_BIT_PGI      0x01000000
-#define GL_MAT_SHININESS_BIT_PGI          0x02000000
-#define GL_MAT_SPECULAR_BIT_PGI           0x04000000
-#define GL_NORMAL_BIT_PGI                 0x08000000
-#define GL_TEXCOORD1_BIT_PGI              0x10000000
-#define GL_TEXCOORD2_BIT_PGI              0x20000000
-#define GL_TEXCOORD3_BIT_PGI              0x40000000
-#define GL_TEXCOORD4_BIT_PGI              0x80000000
-#define GL_VERTEX23_BIT_PGI               0x00000004
-#define GL_VERTEX4_BIT_PGI                0x00000008
-#endif
-
-#ifndef GL_PGI_misc_hints
-#define GL_PREFER_DOUBLEBUFFER_HINT_PGI   0x1A1F8
-#define GL_CONSERVE_MEMORY_HINT_PGI       0x1A1FD
-#define GL_RECLAIM_MEMORY_HINT_PGI        0x1A1FE
-#define GL_NATIVE_GRAPHICS_HANDLE_PGI     0x1A202
-#define GL_NATIVE_GRAPHICS_BEGIN_HINT_PGI 0x1A203
-#define GL_NATIVE_GRAPHICS_END_HINT_PGI   0x1A204
-#define GL_ALWAYS_FAST_HINT_PGI           0x1A20C
-#define GL_ALWAYS_SOFT_HINT_PGI           0x1A20D
-#define GL_ALLOW_DRAW_OBJ_HINT_PGI        0x1A20E
-#define GL_ALLOW_DRAW_WIN_HINT_PGI        0x1A20F
-#define GL_ALLOW_DRAW_FRG_HINT_PGI        0x1A210
-#define GL_ALLOW_DRAW_MEM_HINT_PGI        0x1A211
-#define GL_STRICT_DEPTHFUNC_HINT_PGI      0x1A216
-#define GL_STRICT_LIGHTING_HINT_PGI       0x1A217
-#define GL_STRICT_SCISSOR_HINT_PGI        0x1A218
-#define GL_FULL_STIPPLE_HINT_PGI          0x1A219
-#define GL_CLIP_NEAR_HINT_PGI             0x1A220
-#define GL_CLIP_FAR_HINT_PGI              0x1A221
-#define GL_WIDE_LINE_HINT_PGI             0x1A222
-#define GL_BACK_NORMALS_HINT_PGI          0x1A223
-#endif
-
-#ifndef GL_EXT_paletted_texture
-#define GL_COLOR_INDEX1_EXT               0x80E2
-#define GL_COLOR_INDEX2_EXT               0x80E3
-#define GL_COLOR_INDEX4_EXT               0x80E4
-#define GL_COLOR_INDEX8_EXT               0x80E5
-#define GL_COLOR_INDEX12_EXT              0x80E6
-#define GL_COLOR_INDEX16_EXT              0x80E7
-#define GL_TEXTURE_INDEX_SIZE_EXT         0x80ED
-#endif
-
-#ifndef GL_EXT_clip_volume_hint
-#define GL_CLIP_VOLUME_CLIPPING_HINT_EXT  0x80F0
-#endif
-
-#ifndef GL_SGIX_list_priority
-#define GL_LIST_PRIORITY_SGIX             0x8182
-#endif
-
-#ifndef GL_SGIX_ir_instrument1
-#define GL_IR_INSTRUMENT1_SGIX            0x817F
-#endif
-
-#ifndef GL_SGIX_calligraphic_fragment
-#define GL_CALLIGRAPHIC_FRAGMENT_SGIX     0x8183
-#endif
-
-#ifndef GL_SGIX_texture_lod_bias
-#define GL_TEXTURE_LOD_BIAS_S_SGIX        0x818E
-#define GL_TEXTURE_LOD_BIAS_T_SGIX        0x818F
-#define GL_TEXTURE_LOD_BIAS_R_SGIX        0x8190
-#endif
-
-#ifndef GL_SGIX_shadow_ambient
-#define GL_SHADOW_AMBIENT_SGIX            0x80BF
-#endif
-
-#ifndef GL_EXT_index_texture
-#endif
-
-#ifndef GL_EXT_index_material
-#define GL_INDEX_MATERIAL_EXT             0x81B8
-#define GL_INDEX_MATERIAL_PARAMETER_EXT   0x81B9
-#define GL_INDEX_MATERIAL_FACE_EXT        0x81BA
-#endif
-
-#ifndef GL_EXT_index_func
-#define GL_INDEX_TEST_EXT                 0x81B5
-#define GL_INDEX_TEST_FUNC_EXT            0x81B6
-#define GL_INDEX_TEST_REF_EXT             0x81B7
-#endif
-
-#ifndef GL_EXT_index_array_formats
-#define GL_IUI_V2F_EXT                    0x81AD
-#define GL_IUI_V3F_EXT                    0x81AE
-#define GL_IUI_N3F_V2F_EXT                0x81AF
-#define GL_IUI_N3F_V3F_EXT                0x81B0
-#define GL_T2F_IUI_V2F_EXT                0x81B1
-#define GL_T2F_IUI_V3F_EXT                0x81B2
-#define GL_T2F_IUI_N3F_V2F_EXT            0x81B3
-#define GL_T2F_IUI_N3F_V3F_EXT            0x81B4
-#endif
-
-#ifndef GL_EXT_compiled_vertex_array
-#define GL_ARRAY_ELEMENT_LOCK_FIRST_EXT   0x81A8
-#define GL_ARRAY_ELEMENT_LOCK_COUNT_EXT   0x81A9
-#endif
-
-#ifndef GL_EXT_cull_vertex
-#define GL_CULL_VERTEX_EXT                0x81AA
-#define GL_CULL_VERTEX_EYE_POSITION_EXT   0x81AB
-#define GL_CULL_VERTEX_OBJECT_POSITION_EXT 0x81AC
-#endif
-
-#ifndef GL_SGIX_ycrcb
-#define GL_YCRCB_422_SGIX                 0x81BB
-#define GL_YCRCB_444_SGIX                 0x81BC
-#endif
-
-#ifndef GL_SGIX_fragment_lighting
-#define GL_FRAGMENT_LIGHTING_SGIX         0x8400
-#define GL_FRAGMENT_COLOR_MATERIAL_SGIX   0x8401
-#define GL_FRAGMENT_COLOR_MATERIAL_FACE_SGIX 0x8402
-#define GL_FRAGMENT_COLOR_MATERIAL_PARAMETER_SGIX 0x8403
-#define GL_MAX_FRAGMENT_LIGHTS_SGIX       0x8404
-#define GL_MAX_ACTIVE_LIGHTS_SGIX         0x8405
-#define GL_CURRENT_RASTER_NORMAL_SGIX     0x8406
-#define GL_LIGHT_ENV_MODE_SGIX            0x8407
-#define GL_FRAGMENT_LIGHT_MODEL_LOCAL_VIEWER_SGIX 0x8408
-#define GL_FRAGMENT_LIGHT_MODEL_TWO_SIDE_SGIX 0x8409
-#define GL_FRAGMENT_LIGHT_MODEL_AMBIENT_SGIX 0x840A
-#define GL_FRAGMENT_LIGHT_MODEL_NORMAL_INTERPOLATION_SGIX 0x840B
-#define GL_FRAGMENT_LIGHT0_SGIX           0x840C
-#define GL_FRAGMENT_LIGHT1_SGIX           0x840D
-#define GL_FRAGMENT_LIGHT2_SGIX           0x840E
-#define GL_FRAGMENT_LIGHT3_SGIX           0x840F
-#define GL_FRAGMENT_LIGHT4_SGIX           0x8410
-#define GL_FRAGMENT_LIGHT5_SGIX           0x8411
-#define GL_FRAGMENT_LIGHT6_SGIX           0x8412
-#define GL_FRAGMENT_LIGHT7_SGIX           0x8413
-#endif
-
-#ifndef GL_IBM_rasterpos_clip
-#define GL_RASTER_POSITION_UNCLIPPED_IBM  0x19262
-#endif
-
-#ifndef GL_HP_texture_lighting
-#define GL_TEXTURE_LIGHTING_MODE_HP       0x8167
-#define GL_TEXTURE_POST_SPECULAR_HP       0x8168
-#define GL_TEXTURE_PRE_SPECULAR_HP        0x8169
-#endif
-
-#ifndef GL_EXT_draw_range_elements
-#define GL_MAX_ELEMENTS_VERTICES_EXT      0x80E8
-#define GL_MAX_ELEMENTS_INDICES_EXT       0x80E9
-#endif
-
-#ifndef GL_WIN_phong_shading
-#define GL_PHONG_WIN                      0x80EA
-#define GL_PHONG_HINT_WIN                 0x80EB
-#endif
-
-#ifndef GL_WIN_specular_fog
-#define GL_FOG_SPECULAR_TEXTURE_WIN       0x80EC
-#endif
-
-#ifndef GL_EXT_light_texture
-#define GL_FRAGMENT_MATERIAL_EXT          0x8349
-#define GL_FRAGMENT_NORMAL_EXT            0x834A
-#define GL_FRAGMENT_COLOR_EXT             0x834C
-#define GL_ATTENUATION_EXT                0x834D
-#define GL_SHADOW_ATTENUATION_EXT         0x834E
-#define GL_TEXTURE_APPLICATION_MODE_EXT   0x834F
-#define GL_TEXTURE_LIGHT_EXT              0x8350
-#define GL_TEXTURE_MATERIAL_FACE_EXT      0x8351
-#define GL_TEXTURE_MATERIAL_PARAMETER_EXT 0x8352
-/* reuse GL_FRAGMENT_DEPTH_EXT */
-#endif
-
-#ifndef GL_SGIX_blend_alpha_minmax
-#define GL_ALPHA_MIN_SGIX                 0x8320
-#define GL_ALPHA_MAX_SGIX                 0x8321
-#endif
-
-#ifndef GL_SGIX_impact_pixel_texture
-#define GL_PIXEL_TEX_GEN_Q_CEILING_SGIX   0x8184
-#define GL_PIXEL_TEX_GEN_Q_ROUND_SGIX     0x8185
-#define GL_PIXEL_TEX_GEN_Q_FLOOR_SGIX     0x8186
-#define GL_PIXEL_TEX_GEN_ALPHA_REPLACE_SGIX 0x8187
-#define GL_PIXEL_TEX_GEN_ALPHA_NO_REPLACE_SGIX 0x8188
-#define GL_PIXEL_TEX_GEN_ALPHA_LS_SGIX    0x8189
-#define GL_PIXEL_TEX_GEN_ALPHA_MS_SGIX    0x818A
-#endif
-
-#ifndef GL_EXT_bgra
-#define GL_BGR_EXT                        0x80E0
-#define GL_BGRA_EXT                       0x80E1
-#endif
-
-#ifndef GL_SGIX_async
-#define GL_ASYNC_MARKER_SGIX              0x8329
-#endif
-
-#ifndef GL_SGIX_async_pixel
-#define GL_ASYNC_TEX_IMAGE_SGIX           0x835C
-#define GL_ASYNC_DRAW_PIXELS_SGIX         0x835D
-#define GL_ASYNC_READ_PIXELS_SGIX         0x835E
-#define GL_MAX_ASYNC_TEX_IMAGE_SGIX       0x835F
-#define GL_MAX_ASYNC_DRAW_PIXELS_SGIX     0x8360
-#define GL_MAX_ASYNC_READ_PIXELS_SGIX     0x8361
-#endif
-
-#ifndef GL_SGIX_async_histogram
-#define GL_ASYNC_HISTOGRAM_SGIX           0x832C
-#define GL_MAX_ASYNC_HISTOGRAM_SGIX       0x832D
-#endif
-
-#ifndef GL_INTEL_texture_scissor
-#endif
-
-#ifndef GL_INTEL_parallel_arrays
-#define GL_PARALLEL_ARRAYS_INTEL          0x83F4
-#define GL_VERTEX_ARRAY_PARALLEL_POINTERS_INTEL 0x83F5
-#define GL_NORMAL_ARRAY_PARALLEL_POINTERS_INTEL 0x83F6
-#define GL_COLOR_ARRAY_PARALLEL_POINTERS_INTEL 0x83F7
-#define GL_TEXTURE_COORD_ARRAY_PARALLEL_POINTERS_INTEL 0x83F8
-#endif
-
-#ifndef GL_HP_occlusion_test
-#define GL_OCCLUSION_TEST_HP              0x8165
-#define GL_OCCLUSION_TEST_RESULT_HP       0x8166
-#endif
-
-#ifndef GL_EXT_pixel_transform
-#define GL_PIXEL_TRANSFORM_2D_EXT         0x8330
-#define GL_PIXEL_MAG_FILTER_EXT           0x8331
-#define GL_PIXEL_MIN_FILTER_EXT           0x8332
-#define GL_PIXEL_CUBIC_WEIGHT_EXT         0x8333
-#define GL_CUBIC_EXT                      0x8334
-#define GL_AVERAGE_EXT                    0x8335
-#define GL_PIXEL_TRANSFORM_2D_STACK_DEPTH_EXT 0x8336
-#define GL_MAX_PIXEL_TRANSFORM_2D_STACK_DEPTH_EXT 0x8337
-#define GL_PIXEL_TRANSFORM_2D_MATRIX_EXT  0x8338
-#endif
-
-#ifndef GL_EXT_pixel_transform_color_table
-#endif
-
-#ifndef GL_EXT_shared_texture_palette
-#define GL_SHARED_TEXTURE_PALETTE_EXT     0x81FB
-#endif
-
-#ifndef GL_EXT_separate_specular_color
-#define GL_LIGHT_MODEL_COLOR_CONTROL_EXT  0x81F8
-#define GL_SINGLE_COLOR_EXT               0x81F9
-#define GL_SEPARATE_SPECULAR_COLOR_EXT    0x81FA
-#endif
-
-#ifndef GL_EXT_secondary_color
-#define GL_COLOR_SUM_EXT                  0x8458
-#define GL_CURRENT_SECONDARY_COLOR_EXT    0x8459
-#define GL_SECONDARY_COLOR_ARRAY_SIZE_EXT 0x845A
-#define GL_SECONDARY_COLOR_ARRAY_TYPE_EXT 0x845B
-#define GL_SECONDARY_COLOR_ARRAY_STRIDE_EXT 0x845C
-#define GL_SECONDARY_COLOR_ARRAY_POINTER_EXT 0x845D
-#define GL_SECONDARY_COLOR_ARRAY_EXT      0x845E
-#endif
-
-#ifndef GL_EXT_texture_perturb_normal
-#define GL_PERTURB_EXT                    0x85AE
-#define GL_TEXTURE_NORMAL_EXT             0x85AF
-#endif
-
-#ifndef GL_EXT_multi_draw_arrays
-#endif
-
-#ifndef GL_EXT_fog_coord
-#define GL_FOG_COORDINATE_SOURCE_EXT      0x8450
-#define GL_FOG_COORDINATE_EXT             0x8451
-#define GL_FRAGMENT_DEPTH_EXT             0x8452
-#define GL_CURRENT_FOG_COORDINATE_EXT     0x8453
-#define GL_FOG_COORDINATE_ARRAY_TYPE_EXT  0x8454
-#define GL_FOG_COORDINATE_ARRAY_STRIDE_EXT 0x8455
-#define GL_FOG_COORDINATE_ARRAY_POINTER_EXT 0x8456
-#define GL_FOG_COORDINATE_ARRAY_EXT       0x8457
-#endif
-
-#ifndef GL_REND_screen_coordinates
-#define GL_SCREEN_COORDINATES_REND        0x8490
-#define GL_INVERTED_SCREEN_W_REND         0x8491
-#endif
-
-#ifndef GL_EXT_coordinate_frame
-#define GL_TANGENT_ARRAY_EXT              0x8439
-#define GL_BINORMAL_ARRAY_EXT             0x843A
-#define GL_CURRENT_TANGENT_EXT            0x843B
-#define GL_CURRENT_BINORMAL_EXT           0x843C
-#define GL_TANGENT_ARRAY_TYPE_EXT         0x843E
-#define GL_TANGENT_ARRAY_STRIDE_EXT       0x843F
-#define GL_BINORMAL_ARRAY_TYPE_EXT        0x8440
-#define GL_BINORMAL_ARRAY_STRIDE_EXT      0x8441
-#define GL_TANGENT_ARRAY_POINTER_EXT      0x8442
-#define GL_BINORMAL_ARRAY_POINTER_EXT     0x8443
-#define GL_MAP1_TANGENT_EXT               0x8444
-#define GL_MAP2_TANGENT_EXT               0x8445
-#define GL_MAP1_BINORMAL_EXT              0x8446
-#define GL_MAP2_BINORMAL_EXT              0x8447
-#endif
-
-#ifndef GL_EXT_texture_env_combine
-#define GL_COMBINE_EXT                    0x8570
-#define GL_COMBINE_RGB_EXT                0x8571
-#define GL_COMBINE_ALPHA_EXT              0x8572
-#define GL_RGB_SCALE_EXT                  0x8573
-#define GL_ADD_SIGNED_EXT                 0x8574
-#define GL_INTERPOLATE_EXT                0x8575
-#define GL_CONSTANT_EXT                   0x8576
-#define GL_PRIMARY_COLOR_EXT              0x8577
-#define GL_PREVIOUS_EXT                   0x8578
-#define GL_SOURCE0_RGB_EXT                0x8580
-#define GL_SOURCE1_RGB_EXT                0x8581
-#define GL_SOURCE2_RGB_EXT                0x8582
-#define GL_SOURCE0_ALPHA_EXT              0x8588
-#define GL_SOURCE1_ALPHA_EXT              0x8589
-#define GL_SOURCE2_ALPHA_EXT              0x858A
-#define GL_OPERAND0_RGB_EXT               0x8590
-#define GL_OPERAND1_RGB_EXT               0x8591
-#define GL_OPERAND2_RGB_EXT               0x8592
-#define GL_OPERAND0_ALPHA_EXT             0x8598
-#define GL_OPERAND1_ALPHA_EXT             0x8599
-#define GL_OPERAND2_ALPHA_EXT             0x859A
-#endif
-
-#ifndef GL_APPLE_specular_vector
-#define GL_LIGHT_MODEL_SPECULAR_VECTOR_APPLE 0x85B0
-#endif
-
-#ifndef GL_APPLE_transform_hint
-#define GL_TRANSFORM_HINT_APPLE           0x85B1
-#endif
-
-#ifndef GL_SGIX_fog_scale
-#define GL_FOG_SCALE_SGIX                 0x81FC
-#define GL_FOG_SCALE_VALUE_SGIX           0x81FD
-#endif
-
-#ifndef GL_SUNX_constant_data
-#define GL_UNPACK_CONSTANT_DATA_SUNX      0x81D5
-#define GL_TEXTURE_CONSTANT_DATA_SUNX     0x81D6
-#endif
-
-#ifndef GL_SUN_global_alpha
-#define GL_GLOBAL_ALPHA_SUN               0x81D9
-#define GL_GLOBAL_ALPHA_FACTOR_SUN        0x81DA
-#endif
-
-#ifndef GL_SUN_triangle_list
-#define GL_RESTART_SUN                    0x0001
-#define GL_REPLACE_MIDDLE_SUN             0x0002
-#define GL_REPLACE_OLDEST_SUN             0x0003
-#define GL_TRIANGLE_LIST_SUN              0x81D7
-#define GL_REPLACEMENT_CODE_SUN           0x81D8
-#define GL_REPLACEMENT_CODE_ARRAY_SUN     0x85C0
-#define GL_REPLACEMENT_CODE_ARRAY_TYPE_SUN 0x85C1
-#define GL_REPLACEMENT_CODE_ARRAY_STRIDE_SUN 0x85C2
-#define GL_REPLACEMENT_CODE_ARRAY_POINTER_SUN 0x85C3
-#define GL_R1UI_V3F_SUN                   0x85C4
-#define GL_R1UI_C4UB_V3F_SUN              0x85C5
-#define GL_R1UI_C3F_V3F_SUN               0x85C6
-#define GL_R1UI_N3F_V3F_SUN               0x85C7
-#define GL_R1UI_C4F_N3F_V3F_SUN           0x85C8
-#define GL_R1UI_T2F_V3F_SUN               0x85C9
-#define GL_R1UI_T2F_N3F_V3F_SUN           0x85CA
-#define GL_R1UI_T2F_C4F_N3F_V3F_SUN       0x85CB
-#endif
-
-#ifndef GL_SUN_vertex
-#endif
-
-#ifndef GL_EXT_blend_func_separate
-#define GL_BLEND_DST_RGB_EXT              0x80C8
-#define GL_BLEND_SRC_RGB_EXT              0x80C9
-#define GL_BLEND_DST_ALPHA_EXT            0x80CA
-#define GL_BLEND_SRC_ALPHA_EXT            0x80CB
-#endif
-
-#ifndef GL_INGR_color_clamp
-#define GL_RED_MIN_CLAMP_INGR             0x8560
-#define GL_GREEN_MIN_CLAMP_INGR           0x8561
-#define GL_BLUE_MIN_CLAMP_INGR            0x8562
-#define GL_ALPHA_MIN_CLAMP_INGR           0x8563
-#define GL_RED_MAX_CLAMP_INGR             0x8564
-#define GL_GREEN_MAX_CLAMP_INGR           0x8565
-#define GL_BLUE_MAX_CLAMP_INGR            0x8566
-#define GL_ALPHA_MAX_CLAMP_INGR           0x8567
-#endif
-
-#ifndef GL_INGR_interlace_read
-#define GL_INTERLACE_READ_INGR            0x8568
-#endif
-
-#ifndef GL_EXT_stencil_wrap
-#define GL_INCR_WRAP_EXT                  0x8507
-#define GL_DECR_WRAP_EXT                  0x8508
-#endif
-
-#ifndef GL_EXT_422_pixels
-#define GL_422_EXT                        0x80CC
-#define GL_422_REV_EXT                    0x80CD
-#define GL_422_AVERAGE_EXT                0x80CE
-#define GL_422_REV_AVERAGE_EXT            0x80CF
-#endif
-
-#ifndef GL_NV_texgen_reflection
-#define GL_NORMAL_MAP_NV                  0x8511
-#define GL_REFLECTION_MAP_NV              0x8512
-#endif
-
-#ifndef GL_EXT_texture_cube_map
-#define GL_NORMAL_MAP_EXT                 0x8511
-#define GL_REFLECTION_MAP_EXT             0x8512
-#define GL_TEXTURE_CUBE_MAP_EXT           0x8513
-#define GL_TEXTURE_BINDING_CUBE_MAP_EXT   0x8514
-#define GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT 0x8515
-#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT 0x8516
-#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT 0x8517
-#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT 0x8518
-#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT 0x8519
-#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT 0x851A
-#define GL_PROXY_TEXTURE_CUBE_MAP_EXT     0x851B
-#define GL_MAX_CUBE_MAP_TEXTURE_SIZE_EXT  0x851C
-#endif
-
-#ifndef GL_SUN_convolution_border_modes
-#define GL_WRAP_BORDER_SUN                0x81D4
-#endif
-
-#ifndef GL_EXT_texture_env_add
-#endif
-
-#ifndef GL_EXT_texture_lod_bias
-#define GL_MAX_TEXTURE_LOD_BIAS_EXT       0x84FD
-#define GL_TEXTURE_FILTER_CONTROL_EXT     0x8500
-#define GL_TEXTURE_LOD_BIAS_EXT           0x8501
-#endif
-
-#ifndef GL_EXT_texture_filter_anisotropic
-#define GL_TEXTURE_MAX_ANISOTROPY_EXT     0x84FE
-#define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF
-#endif
-
-#ifndef GL_EXT_vertex_weighting
-#define GL_MODELVIEW0_STACK_DEPTH_EXT     GL_MODELVIEW_STACK_DEPTH
-#define GL_MODELVIEW1_STACK_DEPTH_EXT     0x8502
-#define GL_MODELVIEW0_MATRIX_EXT          GL_MODELVIEW_MATRIX
-#define GL_MODELVIEW1_MATRIX_EXT          0x8506
-#define GL_VERTEX_WEIGHTING_EXT           0x8509
-#define GL_MODELVIEW0_EXT                 GL_MODELVIEW
-#define GL_MODELVIEW1_EXT                 0x850A
-#define GL_CURRENT_VERTEX_WEIGHT_EXT      0x850B
-#define GL_VERTEX_WEIGHT_ARRAY_EXT        0x850C
-#define GL_VERTEX_WEIGHT_ARRAY_SIZE_EXT   0x850D
-#define GL_VERTEX_WEIGHT_ARRAY_TYPE_EXT   0x850E
-#define GL_VERTEX_WEIGHT_ARRAY_STRIDE_EXT 0x850F
-#define GL_VERTEX_WEIGHT_ARRAY_POINTER_EXT 0x8510
-#endif
-
-#ifndef GL_NV_light_max_exponent
-#define GL_MAX_SHININESS_NV               0x8504
-#define GL_MAX_SPOT_EXPONENT_NV           0x8505
-#endif
-
-#ifndef GL_NV_vertex_array_range
-#define GL_VERTEX_ARRAY_RANGE_NV          0x851D
-#define GL_VERTEX_ARRAY_RANGE_LENGTH_NV   0x851E
-#define GL_VERTEX_ARRAY_RANGE_VALID_NV    0x851F
-#define GL_MAX_VERTEX_ARRAY_RANGE_ELEMENT_NV 0x8520
-#define GL_VERTEX_ARRAY_RANGE_POINTER_NV  0x8521
-#endif
-
-#ifndef GL_NV_register_combiners
-#define GL_REGISTER_COMBINERS_NV          0x8522
-#define GL_VARIABLE_A_NV                  0x8523
-#define GL_VARIABLE_B_NV                  0x8524
-#define GL_VARIABLE_C_NV                  0x8525
-#define GL_VARIABLE_D_NV                  0x8526
-#define GL_VARIABLE_E_NV                  0x8527
-#define GL_VARIABLE_F_NV                  0x8528
-#define GL_VARIABLE_G_NV                  0x8529
-#define GL_CONSTANT_COLOR0_NV             0x852A
-#define GL_CONSTANT_COLOR1_NV             0x852B
-#define GL_PRIMARY_COLOR_NV               0x852C
-#define GL_SECONDARY_COLOR_NV             0x852D
-#define GL_SPARE0_NV                      0x852E
-#define GL_SPARE1_NV                      0x852F
-#define GL_DISCARD_NV                     0x8530
-#define GL_E_TIMES_F_NV                   0x8531
-#define GL_SPARE0_PLUS_SECONDARY_COLOR_NV 0x8532
-#define GL_UNSIGNED_IDENTITY_NV           0x8536
-#define GL_UNSIGNED_INVERT_NV             0x8537
-#define GL_EXPAND_NORMAL_NV               0x8538
-#define GL_EXPAND_NEGATE_NV               0x8539
-#define GL_HALF_BIAS_NORMAL_NV            0x853A
-#define GL_HALF_BIAS_NEGATE_NV            0x853B
-#define GL_SIGNED_IDENTITY_NV             0x853C
-#define GL_SIGNED_NEGATE_NV               0x853D
-#define GL_SCALE_BY_TWO_NV                0x853E
-#define GL_SCALE_BY_FOUR_NV               0x853F
-#define GL_SCALE_BY_ONE_HALF_NV           0x8540
-#define GL_BIAS_BY_NEGATIVE_ONE_HALF_NV   0x8541
-#define GL_COMBINER_INPUT_NV              0x8542
-#define GL_COMBINER_MAPPING_NV            0x8543
-#define GL_COMBINER_COMPONENT_USAGE_NV    0x8544
-#define GL_COMBINER_AB_DOT_PRODUCT_NV     0x8545
-#define GL_COMBINER_CD_DOT_PRODUCT_NV     0x8546
-#define GL_COMBINER_MUX_SUM_NV            0x8547
-#define GL_COMBINER_SCALE_NV              0x8548
-#define GL_COMBINER_BIAS_NV               0x8549
-#define GL_COMBINER_AB_OUTPUT_NV          0x854A
-#define GL_COMBINER_CD_OUTPUT_NV          0x854B
-#define GL_COMBINER_SUM_OUTPUT_NV         0x854C
-#define GL_MAX_GENERAL_COMBINERS_NV       0x854D
-#define GL_NUM_GENERAL_COMBINERS_NV       0x854E
-#define GL_COLOR_SUM_CLAMP_NV             0x854F
-#define GL_COMBINER0_NV                   0x8550
-#define GL_COMBINER1_NV                   0x8551
-#define GL_COMBINER2_NV                   0x8552
-#define GL_COMBINER3_NV                   0x8553
-#define GL_COMBINER4_NV                   0x8554
-#define GL_COMBINER5_NV                   0x8555
-#define GL_COMBINER6_NV                   0x8556
-#define GL_COMBINER7_NV                   0x8557
-/* reuse GL_TEXTURE0_ARB */
-/* reuse GL_TEXTURE1_ARB */
-/* reuse GL_ZERO */
-/* reuse GL_NONE */
-/* reuse GL_FOG */
-#endif
-
-#ifndef GL_NV_fog_distance
-#define GL_FOG_DISTANCE_MODE_NV           0x855A
-#define GL_EYE_RADIAL_NV                  0x855B
-#define GL_EYE_PLANE_ABSOLUTE_NV          0x855C
-/* reuse GL_EYE_PLANE */
-#endif
-
-#ifndef GL_NV_texgen_emboss
-#define GL_EMBOSS_LIGHT_NV                0x855D
-#define GL_EMBOSS_CONSTANT_NV             0x855E
-#define GL_EMBOSS_MAP_NV                  0x855F
-#endif
-
-#ifndef GL_NV_blend_square
-#endif
-
-#ifndef GL_NV_texture_env_combine4
-#define GL_COMBINE4_NV                    0x8503
-#define GL_SOURCE3_RGB_NV                 0x8583
-#define GL_SOURCE3_ALPHA_NV               0x858B
-#define GL_OPERAND3_RGB_NV                0x8593
-#define GL_OPERAND3_ALPHA_NV              0x859B
-#endif
-
-#ifndef GL_MESA_resize_buffers
-#endif
-
-#ifndef GL_MESA_window_pos
-#endif
-
-#ifndef GL_EXT_texture_compression_s3tc
-#define GL_COMPRESSED_RGB_S3TC_DXT1_EXT   0x83F0
-#define GL_COMPRESSED_RGBA_S3TC_DXT1_EXT  0x83F1
-#define GL_COMPRESSED_RGBA_S3TC_DXT3_EXT  0x83F2
-#define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT  0x83F3
-#endif
-
-#ifndef GL_IBM_cull_vertex
-#define GL_CULL_VERTEX_IBM                103050
-#endif
-
-#ifndef GL_IBM_multimode_draw_arrays
-#endif
-
-#ifndef GL_IBM_vertex_array_lists
-#define GL_VERTEX_ARRAY_LIST_IBM          103070
-#define GL_NORMAL_ARRAY_LIST_IBM          103071
-#define GL_COLOR_ARRAY_LIST_IBM           103072
-#define GL_INDEX_ARRAY_LIST_IBM           103073
-#define GL_TEXTURE_COORD_ARRAY_LIST_IBM   103074
-#define GL_EDGE_FLAG_ARRAY_LIST_IBM       103075
-#define GL_FOG_COORDINATE_ARRAY_LIST_IBM  103076
-#define GL_SECONDARY_COLOR_ARRAY_LIST_IBM 103077
-#define GL_VERTEX_ARRAY_LIST_STRIDE_IBM   103080
-#define GL_NORMAL_ARRAY_LIST_STRIDE_IBM   103081
-#define GL_COLOR_ARRAY_LIST_STRIDE_IBM    103082
-#define GL_INDEX_ARRAY_LIST_STRIDE_IBM    103083
-#define GL_TEXTURE_COORD_ARRAY_LIST_STRIDE_IBM 103084
-#define GL_EDGE_FLAG_ARRAY_LIST_STRIDE_IBM 103085
-#define GL_FOG_COORDINATE_ARRAY_LIST_STRIDE_IBM 103086
-#define GL_SECONDARY_COLOR_ARRAY_LIST_STRIDE_IBM 103087
-#endif
-
-#ifndef GL_SGIX_subsample
-#define GL_PACK_SUBSAMPLE_RATE_SGIX       0x85A0
-#define GL_UNPACK_SUBSAMPLE_RATE_SGIX     0x85A1
-#define GL_PIXEL_SUBSAMPLE_4444_SGIX      0x85A2
-#define GL_PIXEL_SUBSAMPLE_2424_SGIX      0x85A3
-#define GL_PIXEL_SUBSAMPLE_4242_SGIX      0x85A4
-#endif
-
-#ifndef GL_SGIX_ycrcb_subsample
-#endif
-
-#ifndef GL_SGIX_ycrcba
-#define GL_YCRCB_SGIX                     0x8318
-#define GL_YCRCBA_SGIX                    0x8319
-#endif
-
-#ifndef GL_SGI_depth_pass_instrument
-#define GL_DEPTH_PASS_INSTRUMENT_SGIX     0x8310
-#define GL_DEPTH_PASS_INSTRUMENT_COUNTERS_SGIX 0x8311
-#define GL_DEPTH_PASS_INSTRUMENT_MAX_SGIX 0x8312
-#endif
-
-#ifndef GL_3DFX_texture_compression_FXT1
-#define GL_COMPRESSED_RGB_FXT1_3DFX       0x86B0
-#define GL_COMPRESSED_RGBA_FXT1_3DFX      0x86B1
-#endif
-
-#ifndef GL_3DFX_multisample
-#define GL_MULTISAMPLE_3DFX               0x86B2
-#define GL_SAMPLE_BUFFERS_3DFX            0x86B3
-#define GL_SAMPLES_3DFX                   0x86B4
-#define GL_MULTISAMPLE_BIT_3DFX           0x20000000
-#endif
-
-#ifndef GL_3DFX_tbuffer
-#endif
-
-#ifndef GL_EXT_multisample
-#define GL_MULTISAMPLE_EXT                0x809D
-#define GL_SAMPLE_ALPHA_TO_MASK_EXT       0x809E
-#define GL_SAMPLE_ALPHA_TO_ONE_EXT        0x809F
-#define GL_SAMPLE_MASK_EXT                0x80A0
-#define GL_1PASS_EXT                      0x80A1
-#define GL_2PASS_0_EXT                    0x80A2
-#define GL_2PASS_1_EXT                    0x80A3
-#define GL_4PASS_0_EXT                    0x80A4
-#define GL_4PASS_1_EXT                    0x80A5
-#define GL_4PASS_2_EXT                    0x80A6
-#define GL_4PASS_3_EXT                    0x80A7
-#define GL_SAMPLE_BUFFERS_EXT             0x80A8
-#define GL_SAMPLES_EXT                    0x80A9
-#define GL_SAMPLE_MASK_VALUE_EXT          0x80AA
-#define GL_SAMPLE_MASK_INVERT_EXT         0x80AB
-#define GL_SAMPLE_PATTERN_EXT             0x80AC
-#define GL_MULTISAMPLE_BIT_EXT            0x20000000
-#endif
-
-#ifndef GL_SGIX_vertex_preclip
-#define GL_VERTEX_PRECLIP_SGIX            0x83EE
-#define GL_VERTEX_PRECLIP_HINT_SGIX       0x83EF
-#endif
-
-#ifndef GL_SGIX_convolution_accuracy
-#define GL_CONVOLUTION_HINT_SGIX          0x8316
-#endif
-
-#ifndef GL_SGIX_resample
-#define GL_PACK_RESAMPLE_SGIX             0x842C
-#define GL_UNPACK_RESAMPLE_SGIX           0x842D
-#define GL_RESAMPLE_REPLICATE_SGIX        0x842E
-#define GL_RESAMPLE_ZERO_FILL_SGIX        0x842F
-#define GL_RESAMPLE_DECIMATE_SGIX         0x8430
-#endif
-
-#ifndef GL_SGIS_point_line_texgen
-#define GL_EYE_DISTANCE_TO_POINT_SGIS     0x81F0
-#define GL_OBJECT_DISTANCE_TO_POINT_SGIS  0x81F1
-#define GL_EYE_DISTANCE_TO_LINE_SGIS      0x81F2
-#define GL_OBJECT_DISTANCE_TO_LINE_SGIS   0x81F3
-#define GL_EYE_POINT_SGIS                 0x81F4
-#define GL_OBJECT_POINT_SGIS              0x81F5
-#define GL_EYE_LINE_SGIS                  0x81F6
-#define GL_OBJECT_LINE_SGIS               0x81F7
-#endif
-
-#ifndef GL_SGIS_texture_color_mask
-#define GL_TEXTURE_COLOR_WRITEMASK_SGIS   0x81EF
-#endif
-
-#ifndef GL_EXT_texture_env_dot3
-#define GL_DOT3_RGB_EXT                   0x8740
-#define GL_DOT3_RGBA_EXT                  0x8741
-#endif
-
-#ifndef GL_ATI_texture_mirror_once
-#define GL_MIRROR_CLAMP_ATI               0x8742
-#define GL_MIRROR_CLAMP_TO_EDGE_ATI       0x8743
-#endif
-
-#ifndef GL_NV_fence
-#define GL_ALL_COMPLETED_NV               0x84F2
-#define GL_FENCE_STATUS_NV                0x84F3
-#define GL_FENCE_CONDITION_NV             0x84F4
-#endif
-
-#ifndef GL_IBM_texture_mirrored_repeat
-#define GL_MIRRORED_REPEAT_IBM            0x8370
-#endif
-
-#ifndef GL_NV_evaluators
-#define GL_EVAL_2D_NV                     0x86C0
-#define GL_EVAL_TRIANGULAR_2D_NV          0x86C1
-#define GL_MAP_TESSELLATION_NV            0x86C2
-#define GL_MAP_ATTRIB_U_ORDER_NV          0x86C3
-#define GL_MAP_ATTRIB_V_ORDER_NV          0x86C4
-#define GL_EVAL_FRACTIONAL_TESSELLATION_NV 0x86C5
-#define GL_EVAL_VERTEX_ATTRIB0_NV         0x86C6
-#define GL_EVAL_VERTEX_ATTRIB1_NV         0x86C7
-#define GL_EVAL_VERTEX_ATTRIB2_NV         0x86C8
-#define GL_EVAL_VERTEX_ATTRIB3_NV         0x86C9
-#define GL_EVAL_VERTEX_ATTRIB4_NV         0x86CA
-#define GL_EVAL_VERTEX_ATTRIB5_NV         0x86CB
-#define GL_EVAL_VERTEX_ATTRIB6_NV         0x86CC
-#define GL_EVAL_VERTEX_ATTRIB7_NV         0x86CD
-#define GL_EVAL_VERTEX_ATTRIB8_NV         0x86CE
-#define GL_EVAL_VERTEX_ATTRIB9_NV         0x86CF
-#define GL_EVAL_VERTEX_ATTRIB10_NV        0x86D0
-#define GL_EVAL_VERTEX_ATTRIB11_NV        0x86D1
-#define GL_EVAL_VERTEX_ATTRIB12_NV        0x86D2
-#define GL_EVAL_VERTEX_ATTRIB13_NV        0x86D3
-#define GL_EVAL_VERTEX_ATTRIB14_NV        0x86D4
-#define GL_EVAL_VERTEX_ATTRIB15_NV        0x86D5
-#define GL_MAX_MAP_TESSELLATION_NV        0x86D6
-#define GL_MAX_RATIONAL_EVAL_ORDER_NV     0x86D7
-#endif
-
-#ifndef GL_NV_packed_depth_stencil
-#define GL_DEPTH_STENCIL_NV               0x84F9
-#define GL_UNSIGNED_INT_24_8_NV           0x84FA
-#endif
-
-#ifndef GL_NV_register_combiners2
-#define GL_PER_STAGE_CONSTANTS_NV         0x8535
-#endif
-
-#ifndef GL_NV_texture_compression_vtc
-#endif
-
-#ifndef GL_NV_texture_rectangle
-#define GL_TEXTURE_RECTANGLE_NV           0x84F5
-#define GL_TEXTURE_BINDING_RECTANGLE_NV   0x84F6
-#define GL_PROXY_TEXTURE_RECTANGLE_NV     0x84F7
-#define GL_MAX_RECTANGLE_TEXTURE_SIZE_NV  0x84F8
-#endif
-
-#ifndef GL_NV_texture_shader
-#define GL_OFFSET_TEXTURE_RECTANGLE_NV    0x864C
-#define GL_OFFSET_TEXTURE_RECTANGLE_SCALE_NV 0x864D
-#define GL_DOT_PRODUCT_TEXTURE_RECTANGLE_NV 0x864E
-#define GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV 0x86D9
-#define GL_UNSIGNED_INT_S8_S8_8_8_NV      0x86DA
-#define GL_UNSIGNED_INT_8_8_S8_S8_REV_NV  0x86DB
-#define GL_DSDT_MAG_INTENSITY_NV          0x86DC
-#define GL_SHADER_CONSISTENT_NV           0x86DD
-#define GL_TEXTURE_SHADER_NV              0x86DE
-#define GL_SHADER_OPERATION_NV            0x86DF
-#define GL_CULL_MODES_NV                  0x86E0
-#define GL_OFFSET_TEXTURE_MATRIX_NV       0x86E1
-#define GL_OFFSET_TEXTURE_SCALE_NV        0x86E2
-#define GL_OFFSET_TEXTURE_BIAS_NV         0x86E3
-#define GL_OFFSET_TEXTURE_2D_MATRIX_NV    GL_OFFSET_TEXTURE_MATRIX_NV
-#define GL_OFFSET_TEXTURE_2D_SCALE_NV     GL_OFFSET_TEXTURE_SCALE_NV
-#define GL_OFFSET_TEXTURE_2D_BIAS_NV      GL_OFFSET_TEXTURE_BIAS_NV
-#define GL_PREVIOUS_TEXTURE_INPUT_NV      0x86E4
-#define GL_CONST_EYE_NV                   0x86E5
-#define GL_PASS_THROUGH_NV                0x86E6
-#define GL_CULL_FRAGMENT_NV               0x86E7
-#define GL_OFFSET_TEXTURE_2D_NV           0x86E8
-#define GL_DEPENDENT_AR_TEXTURE_2D_NV     0x86E9
-#define GL_DEPENDENT_GB_TEXTURE_2D_NV     0x86EA
-#define GL_DOT_PRODUCT_NV                 0x86EC
-#define GL_DOT_PRODUCT_DEPTH_REPLACE_NV   0x86ED
-#define GL_DOT_PRODUCT_TEXTURE_2D_NV      0x86EE
-#define GL_DOT_PRODUCT_TEXTURE_CUBE_MAP_NV 0x86F0
-#define GL_DOT_PRODUCT_DIFFUSE_CUBE_MAP_NV 0x86F1
-#define GL_DOT_PRODUCT_REFLECT_CUBE_MAP_NV 0x86F2
-#define GL_DOT_PRODUCT_CONST_EYE_REFLECT_CUBE_MAP_NV 0x86F3
-#define GL_HILO_NV                        0x86F4
-#define GL_DSDT_NV                        0x86F5
-#define GL_DSDT_MAG_NV                    0x86F6
-#define GL_DSDT_MAG_VIB_NV                0x86F7
-#define GL_HILO16_NV                      0x86F8
-#define GL_SIGNED_HILO_NV                 0x86F9
-#define GL_SIGNED_HILO16_NV               0x86FA
-#define GL_SIGNED_RGBA_NV                 0x86FB
-#define GL_SIGNED_RGBA8_NV                0x86FC
-#define GL_SIGNED_RGB_NV                  0x86FE
-#define GL_SIGNED_RGB8_NV                 0x86FF
-#define GL_SIGNED_LUMINANCE_NV            0x8701
-#define GL_SIGNED_LUMINANCE8_NV           0x8702
-#define GL_SIGNED_LUMINANCE_ALPHA_NV      0x8703
-#define GL_SIGNED_LUMINANCE8_ALPHA8_NV    0x8704
-#define GL_SIGNED_ALPHA_NV                0x8705
-#define GL_SIGNED_ALPHA8_NV               0x8706
-#define GL_SIGNED_INTENSITY_NV            0x8707
-#define GL_SIGNED_INTENSITY8_NV           0x8708
-#define GL_DSDT8_NV                       0x8709
-#define GL_DSDT8_MAG8_NV                  0x870A
-#define GL_DSDT8_MAG8_INTENSITY8_NV       0x870B
-#define GL_SIGNED_RGB_UNSIGNED_ALPHA_NV   0x870C
-#define GL_SIGNED_RGB8_UNSIGNED_ALPHA8_NV 0x870D
-#define GL_HI_SCALE_NV                    0x870E
-#define GL_LO_SCALE_NV                    0x870F
-#define GL_DS_SCALE_NV                    0x8710
-#define GL_DT_SCALE_NV                    0x8711
-#define GL_MAGNITUDE_SCALE_NV             0x8712
-#define GL_VIBRANCE_SCALE_NV              0x8713
-#define GL_HI_BIAS_NV                     0x8714
-#define GL_LO_BIAS_NV                     0x8715
-#define GL_DS_BIAS_NV                     0x8716
-#define GL_DT_BIAS_NV                     0x8717
-#define GL_MAGNITUDE_BIAS_NV              0x8718
-#define GL_VIBRANCE_BIAS_NV               0x8719
-#define GL_TEXTURE_BORDER_VALUES_NV       0x871A
-#define GL_TEXTURE_HI_SIZE_NV             0x871B
-#define GL_TEXTURE_LO_SIZE_NV             0x871C
-#define GL_TEXTURE_DS_SIZE_NV             0x871D
-#define GL_TEXTURE_DT_SIZE_NV             0x871E
-#define GL_TEXTURE_MAG_SIZE_NV            0x871F
-#endif
-
-#ifndef GL_NV_texture_shader2
-#define GL_DOT_PRODUCT_TEXTURE_3D_NV      0x86EF
-#endif
-
-#ifndef GL_NV_vertex_array_range2
-#define GL_VERTEX_ARRAY_RANGE_WITHOUT_FLUSH_NV 0x8533
-#endif
-
-#ifndef GL_NV_vertex_program
-#define GL_VERTEX_PROGRAM_NV              0x8620
-#define GL_VERTEX_STATE_PROGRAM_NV        0x8621
-#define GL_ATTRIB_ARRAY_SIZE_NV           0x8623
-#define GL_ATTRIB_ARRAY_STRIDE_NV         0x8624
-#define GL_ATTRIB_ARRAY_TYPE_NV           0x8625
-#define GL_CURRENT_ATTRIB_NV              0x8626
-#define GL_PROGRAM_LENGTH_NV              0x8627
-#define GL_PROGRAM_STRING_NV              0x8628
-#define GL_MODELVIEW_PROJECTION_NV        0x8629
-#define GL_IDENTITY_NV                    0x862A
-#define GL_INVERSE_NV                     0x862B
-#define GL_TRANSPOSE_NV                   0x862C
-#define GL_INVERSE_TRANSPOSE_NV           0x862D
-#define GL_MAX_TRACK_MATRIX_STACK_DEPTH_NV 0x862E
-#define GL_MAX_TRACK_MATRICES_NV          0x862F
-#define GL_MATRIX0_NV                     0x8630
-#define GL_MATRIX1_NV                     0x8631
-#define GL_MATRIX2_NV                     0x8632
-#define GL_MATRIX3_NV                     0x8633
-#define GL_MATRIX4_NV                     0x8634
-#define GL_MATRIX5_NV                     0x8635
-#define GL_MATRIX6_NV                     0x8636
-#define GL_MATRIX7_NV                     0x8637
-#define GL_CURRENT_MATRIX_STACK_DEPTH_NV  0x8640
-#define GL_CURRENT_MATRIX_NV              0x8641
-#define GL_VERTEX_PROGRAM_POINT_SIZE_NV   0x8642
-#define GL_VERTEX_PROGRAM_TWO_SIDE_NV     0x8643
-#define GL_PROGRAM_PARAMETER_NV           0x8644
-#define GL_ATTRIB_ARRAY_POINTER_NV        0x8645
-#define GL_PROGRAM_TARGET_NV              0x8646
-#define GL_PROGRAM_RESIDENT_NV            0x8647
-#define GL_TRACK_MATRIX_NV                0x8648
-#define GL_TRACK_MATRIX_TRANSFORM_NV      0x8649
-#define GL_VERTEX_PROGRAM_BINDING_NV      0x864A
-#define GL_PROGRAM_ERROR_POSITION_NV      0x864B
-#define GL_VERTEX_ATTRIB_ARRAY0_NV        0x8650
-#define GL_VERTEX_ATTRIB_ARRAY1_NV        0x8651
-#define GL_VERTEX_ATTRIB_ARRAY2_NV        0x8652
-#define GL_VERTEX_ATTRIB_ARRAY3_NV        0x8653
-#define GL_VERTEX_ATTRIB_ARRAY4_NV        0x8654
-#define GL_VERTEX_ATTRIB_ARRAY5_NV        0x8655
-#define GL_VERTEX_ATTRIB_ARRAY6_NV        0x8656
-#define GL_VERTEX_ATTRIB_ARRAY7_NV        0x8657
-#define GL_VERTEX_ATTRIB_ARRAY8_NV        0x8658
-#define GL_VERTEX_ATTRIB_ARRAY9_NV        0x8659
-#define GL_VERTEX_ATTRIB_ARRAY10_NV       0x865A
-#define GL_VERTEX_ATTRIB_ARRAY11_NV       0x865B
-#define GL_VERTEX_ATTRIB_ARRAY12_NV       0x865C
-#define GL_VERTEX_ATTRIB_ARRAY13_NV       0x865D
-#define GL_VERTEX_ATTRIB_ARRAY14_NV       0x865E
-#define GL_VERTEX_ATTRIB_ARRAY15_NV       0x865F
-#define GL_MAP1_VERTEX_ATTRIB0_4_NV       0x8660
-#define GL_MAP1_VERTEX_ATTRIB1_4_NV       0x8661
-#define GL_MAP1_VERTEX_ATTRIB2_4_NV       0x8662
-#define GL_MAP1_VERTEX_ATTRIB3_4_NV       0x8663
-#define GL_MAP1_VERTEX_ATTRIB4_4_NV       0x8664
-#define GL_MAP1_VERTEX_ATTRIB5_4_NV       0x8665
-#define GL_MAP1_VERTEX_ATTRIB6_4_NV       0x8666
-#define GL_MAP1_VERTEX_ATTRIB7_4_NV       0x8667
-#define GL_MAP1_VERTEX_ATTRIB8_4_NV       0x8668
-#define GL_MAP1_VERTEX_ATTRIB9_4_NV       0x8669
-#define GL_MAP1_VERTEX_ATTRIB10_4_NV      0x866A
-#define GL_MAP1_VERTEX_ATTRIB11_4_NV      0x866B
-#define GL_MAP1_VERTEX_ATTRIB12_4_NV      0x866C
-#define GL_MAP1_VERTEX_ATTRIB13_4_NV      0x866D
-#define GL_MAP1_VERTEX_ATTRIB14_4_NV      0x866E
-#define GL_MAP1_VERTEX_ATTRIB15_4_NV      0x866F
-#define GL_MAP2_VERTEX_ATTRIB0_4_NV       0x8670
-#define GL_MAP2_VERTEX_ATTRIB1_4_NV       0x8671
-#define GL_MAP2_VERTEX_ATTRIB2_4_NV       0x8672
-#define GL_MAP2_VERTEX_ATTRIB3_4_NV       0x8673
-#define GL_MAP2_VERTEX_ATTRIB4_4_NV       0x8674
-#define GL_MAP2_VERTEX_ATTRIB5_4_NV       0x8675
-#define GL_MAP2_VERTEX_ATTRIB6_4_NV       0x8676
-#define GL_MAP2_VERTEX_ATTRIB7_4_NV       0x8677
-#define GL_MAP2_VERTEX_ATTRIB8_4_NV       0x8678
-#define GL_MAP2_VERTEX_ATTRIB9_4_NV       0x8679
-#define GL_MAP2_VERTEX_ATTRIB10_4_NV      0x867A
-#define GL_MAP2_VERTEX_ATTRIB11_4_NV      0x867B
-#define GL_MAP2_VERTEX_ATTRIB12_4_NV      0x867C
-#define GL_MAP2_VERTEX_ATTRIB13_4_NV      0x867D
-#define GL_MAP2_VERTEX_ATTRIB14_4_NV      0x867E
-#define GL_MAP2_VERTEX_ATTRIB15_4_NV      0x867F
-#endif
-
-#ifndef GL_SGIX_texture_coordinate_clamp
-#define GL_TEXTURE_MAX_CLAMP_S_SGIX       0x8369
-#define GL_TEXTURE_MAX_CLAMP_T_SGIX       0x836A
-#define GL_TEXTURE_MAX_CLAMP_R_SGIX       0x836B
-#endif
-
-#ifndef GL_SGIX_scalebias_hint
-#define GL_SCALEBIAS_HINT_SGIX            0x8322
-#endif
-
-#ifndef GL_OML_interlace
-#define GL_INTERLACE_OML                  0x8980
-#define GL_INTERLACE_READ_OML             0x8981
-#endif
-
-#ifndef GL_OML_subsample
-#define GL_FORMAT_SUBSAMPLE_24_24_OML     0x8982
-#define GL_FORMAT_SUBSAMPLE_244_244_OML   0x8983
-#endif
-
-#ifndef GL_OML_resample
-#define GL_PACK_RESAMPLE_OML              0x8984
-#define GL_UNPACK_RESAMPLE_OML            0x8985
-#define GL_RESAMPLE_REPLICATE_OML         0x8986
-#define GL_RESAMPLE_ZERO_FILL_OML         0x8987
-#define GL_RESAMPLE_AVERAGE_OML           0x8988
-#define GL_RESAMPLE_DECIMATE_OML          0x8989
-#endif
-
-#ifndef GL_NV_copy_depth_to_color
-#define GL_DEPTH_STENCIL_TO_RGBA_NV       0x886E
-#define GL_DEPTH_STENCIL_TO_BGRA_NV       0x886F
-#endif
-
-#ifndef GL_ATI_envmap_bumpmap
-#define GL_BUMP_ROT_MATRIX_ATI            0x8775
-#define GL_BUMP_ROT_MATRIX_SIZE_ATI       0x8776
-#define GL_BUMP_NUM_TEX_UNITS_ATI         0x8777
-#define GL_BUMP_TEX_UNITS_ATI             0x8778
-#define GL_DUDV_ATI                       0x8779
-#define GL_DU8DV8_ATI                     0x877A
-#define GL_BUMP_ENVMAP_ATI                0x877B
-#define GL_BUMP_TARGET_ATI                0x877C
-#endif
-
-#ifndef GL_ATI_fragment_shader
-#define GL_FRAGMENT_SHADER_ATI            0x8920
-#define GL_REG_0_ATI                      0x8921
-#define GL_REG_1_ATI                      0x8922
-#define GL_REG_2_ATI                      0x8923
-#define GL_REG_3_ATI                      0x8924
-#define GL_REG_4_ATI                      0x8925
-#define GL_REG_5_ATI                      0x8926
-#define GL_REG_6_ATI                      0x8927
-#define GL_REG_7_ATI                      0x8928
-#define GL_REG_8_ATI                      0x8929
-#define GL_REG_9_ATI                      0x892A
-#define GL_REG_10_ATI                     0x892B
-#define GL_REG_11_ATI                     0x892C
-#define GL_REG_12_ATI                     0x892D
-#define GL_REG_13_ATI                     0x892E
-#define GL_REG_14_ATI                     0x892F
-#define GL_REG_15_ATI                     0x8930
-#define GL_REG_16_ATI                     0x8931
-#define GL_REG_17_ATI                     0x8932
-#define GL_REG_18_ATI                     0x8933
-#define GL_REG_19_ATI                     0x8934
-#define GL_REG_20_ATI                     0x8935
-#define GL_REG_21_ATI                     0x8936
-#define GL_REG_22_ATI                     0x8937
-#define GL_REG_23_ATI                     0x8938
-#define GL_REG_24_ATI                     0x8939
-#define GL_REG_25_ATI                     0x893A
-#define GL_REG_26_ATI                     0x893B
-#define GL_REG_27_ATI                     0x893C
-#define GL_REG_28_ATI                     0x893D
-#define GL_REG_29_ATI                     0x893E
-#define GL_REG_30_ATI                     0x893F
-#define GL_REG_31_ATI                     0x8940
-#define GL_CON_0_ATI                      0x8941
-#define GL_CON_1_ATI                      0x8942
-#define GL_CON_2_ATI                      0x8943
-#define GL_CON_3_ATI                      0x8944
-#define GL_CON_4_ATI                      0x8945
-#define GL_CON_5_ATI                      0x8946
-#define GL_CON_6_ATI                      0x8947
-#define GL_CON_7_ATI                      0x8948
-#define GL_CON_8_ATI                      0x8949
-#define GL_CON_9_ATI                      0x894A
-#define GL_CON_10_ATI                     0x894B
-#define GL_CON_11_ATI                     0x894C
-#define GL_CON_12_ATI                     0x894D
-#define GL_CON_13_ATI                     0x894E
-#define GL_CON_14_ATI                     0x894F
-#define GL_CON_15_ATI                     0x8950
-#define GL_CON_16_ATI                     0x8951
-#define GL_CON_17_ATI                     0x8952
-#define GL_CON_18_ATI                     0x8953
-#define GL_CON_19_ATI                     0x8954
-#define GL_CON_20_ATI                     0x8955
-#define GL_CON_21_ATI                     0x8956
-#define GL_CON_22_ATI                     0x8957
-#define GL_CON_23_ATI                     0x8958
-#define GL_CON_24_ATI                     0x8959
-#define GL_CON_25_ATI                     0x895A
-#define GL_CON_26_ATI                     0x895B
-#define GL_CON_27_ATI                     0x895C
-#define GL_CON_28_ATI                     0x895D
-#define GL_CON_29_ATI                     0x895E
-#define GL_CON_30_ATI                     0x895F
-#define GL_CON_31_ATI                     0x8960
-#define GL_MOV_ATI                        0x8961
-#define GL_ADD_ATI                        0x8963
-#define GL_MUL_ATI                        0x8964
-#define GL_SUB_ATI                        0x8965
-#define GL_DOT3_ATI                       0x8966
-#define GL_DOT4_ATI                       0x8967
-#define GL_MAD_ATI                        0x8968
-#define GL_LERP_ATI                       0x8969
-#define GL_CND_ATI                        0x896A
-#define GL_CND0_ATI                       0x896B
-#define GL_DOT2_ADD_ATI                   0x896C
-#define GL_SECONDARY_INTERPOLATOR_ATI     0x896D
-#define GL_NUM_FRAGMENT_REGISTERS_ATI     0x896E
-#define GL_NUM_FRAGMENT_CONSTANTS_ATI     0x896F
-#define GL_NUM_PASSES_ATI                 0x8970
-#define GL_NUM_INSTRUCTIONS_PER_PASS_ATI  0x8971
-#define GL_NUM_INSTRUCTIONS_TOTAL_ATI     0x8972
-#define GL_NUM_INPUT_INTERPOLATOR_COMPONENTS_ATI 0x8973
-#define GL_NUM_LOOPBACK_COMPONENTS_ATI    0x8974
-#define GL_COLOR_ALPHA_PAIRING_ATI        0x8975
-#define GL_SWIZZLE_STR_ATI                0x8976
-#define GL_SWIZZLE_STQ_ATI                0x8977
-#define GL_SWIZZLE_STR_DR_ATI             0x8978
-#define GL_SWIZZLE_STQ_DQ_ATI             0x8979
-#define GL_SWIZZLE_STRQ_ATI               0x897A
-#define GL_SWIZZLE_STRQ_DQ_ATI            0x897B
-#define GL_RED_BIT_ATI                    0x00000001
-#define GL_GREEN_BIT_ATI                  0x00000002
-#define GL_BLUE_BIT_ATI                   0x00000004
-#define GL_2X_BIT_ATI                     0x00000001
-#define GL_4X_BIT_ATI                     0x00000002
-#define GL_8X_BIT_ATI                     0x00000004
-#define GL_HALF_BIT_ATI                   0x00000008
-#define GL_QUARTER_BIT_ATI                0x00000010
-#define GL_EIGHTH_BIT_ATI                 0x00000020
-#define GL_SATURATE_BIT_ATI               0x00000040
-#define GL_COMP_BIT_ATI                   0x00000002
-#define GL_NEGATE_BIT_ATI                 0x00000004
-#define GL_BIAS_BIT_ATI                   0x00000008
-#endif
-
-#ifndef GL_ATI_pn_triangles
-#define GL_PN_TRIANGLES_ATI               0x87F0
-#define GL_MAX_PN_TRIANGLES_TESSELATION_LEVEL_ATI 0x87F1
-#define GL_PN_TRIANGLES_POINT_MODE_ATI    0x87F2
-#define GL_PN_TRIANGLES_NORMAL_MODE_ATI   0x87F3
-#define GL_PN_TRIANGLES_TESSELATION_LEVEL_ATI 0x87F4
-#define GL_PN_TRIANGLES_POINT_MODE_LINEAR_ATI 0x87F5
-#define GL_PN_TRIANGLES_POINT_MODE_CUBIC_ATI 0x87F6
-#define GL_PN_TRIANGLES_NORMAL_MODE_LINEAR_ATI 0x87F7
-#define GL_PN_TRIANGLES_NORMAL_MODE_QUADRATIC_ATI 0x87F8
-#endif
-
-#ifndef GL_ATI_vertex_array_object
-#define GL_STATIC_ATI                     0x8760
-#define GL_DYNAMIC_ATI                    0x8761
-#define GL_PRESERVE_ATI                   0x8762
-#define GL_DISCARD_ATI                    0x8763
-#define GL_OBJECT_BUFFER_SIZE_ATI         0x8764
-#define GL_OBJECT_BUFFER_USAGE_ATI        0x8765
-#define GL_ARRAY_OBJECT_BUFFER_ATI        0x8766
-#define GL_ARRAY_OBJECT_OFFSET_ATI        0x8767
-#endif
-
-#ifndef GL_EXT_vertex_shader
-#define GL_VERTEX_SHADER_EXT              0x8780
-#define GL_VERTEX_SHADER_BINDING_EXT      0x8781
-#define GL_OP_INDEX_EXT                   0x8782
-#define GL_OP_NEGATE_EXT                  0x8783
-#define GL_OP_DOT3_EXT                    0x8784
-#define GL_OP_DOT4_EXT                    0x8785
-#define GL_OP_MUL_EXT                     0x8786
-#define GL_OP_ADD_EXT                     0x8787
-#define GL_OP_MADD_EXT                    0x8788
-#define GL_OP_FRAC_EXT                    0x8789
-#define GL_OP_MAX_EXT                     0x878A
-#define GL_OP_MIN_EXT                     0x878B
-#define GL_OP_SET_GE_EXT                  0x878C
-#define GL_OP_SET_LT_EXT                  0x878D
-#define GL_OP_CLAMP_EXT                   0x878E
-#define GL_OP_FLOOR_EXT                   0x878F
-#define GL_OP_ROUND_EXT                   0x8790
-#define GL_OP_EXP_BASE_2_EXT              0x8791
-#define GL_OP_LOG_BASE_2_EXT              0x8792
-#define GL_OP_POWER_EXT                   0x8793
-#define GL_OP_RECIP_EXT                   0x8794
-#define GL_OP_RECIP_SQRT_EXT              0x8795
-#define GL_OP_SUB_EXT                     0x8796
-#define GL_OP_CROSS_PRODUCT_EXT           0x8797
-#define GL_OP_MULTIPLY_MATRIX_EXT         0x8798
-#define GL_OP_MOV_EXT                     0x8799
-#define GL_OUTPUT_VERTEX_EXT              0x879A
-#define GL_OUTPUT_COLOR0_EXT              0x879B
-#define GL_OUTPUT_COLOR1_EXT              0x879C
-#define GL_OUTPUT_TEXTURE_COORD0_EXT      0x879D
-#define GL_OUTPUT_TEXTURE_COORD1_EXT      0x879E
-#define GL_OUTPUT_TEXTURE_COORD2_EXT      0x879F
-#define GL_OUTPUT_TEXTURE_COORD3_EXT      0x87A0
-#define GL_OUTPUT_TEXTURE_COORD4_EXT      0x87A1
-#define GL_OUTPUT_TEXTURE_COORD5_EXT      0x87A2
-#define GL_OUTPUT_TEXTURE_COORD6_EXT      0x87A3
-#define GL_OUTPUT_TEXTURE_COORD7_EXT      0x87A4
-#define GL_OUTPUT_TEXTURE_COORD8_EXT      0x87A5
-#define GL_OUTPUT_TEXTURE_COORD9_EXT      0x87A6
-#define GL_OUTPUT_TEXTURE_COORD10_EXT     0x87A7
-#define GL_OUTPUT_TEXTURE_COORD11_EXT     0x87A8
-#define GL_OUTPUT_TEXTURE_COORD12_EXT     0x87A9
-#define GL_OUTPUT_TEXTURE_COORD13_EXT     0x87AA
-#define GL_OUTPUT_TEXTURE_COORD14_EXT     0x87AB
-#define GL_OUTPUT_TEXTURE_COORD15_EXT     0x87AC
-#define GL_OUTPUT_TEXTURE_COORD16_EXT     0x87AD
-#define GL_OUTPUT_TEXTURE_COORD17_EXT     0x87AE
-#define GL_OUTPUT_TEXTURE_COORD18_EXT     0x87AF
-#define GL_OUTPUT_TEXTURE_COORD19_EXT     0x87B0
-#define GL_OUTPUT_TEXTURE_COORD20_EXT     0x87B1
-#define GL_OUTPUT_TEXTURE_COORD21_EXT     0x87B2
-#define GL_OUTPUT_TEXTURE_COORD22_EXT     0x87B3
-#define GL_OUTPUT_TEXTURE_COORD23_EXT     0x87B4
-#define GL_OUTPUT_TEXTURE_COORD24_EXT     0x87B5
-#define GL_OUTPUT_TEXTURE_COORD25_EXT     0x87B6
-#define GL_OUTPUT_TEXTURE_COORD26_EXT     0x87B7
-#define GL_OUTPUT_TEXTURE_COORD27_EXT     0x87B8
-#define GL_OUTPUT_TEXTURE_COORD28_EXT     0x87B9
-#define GL_OUTPUT_TEXTURE_COORD29_EXT     0x87BA
-#define GL_OUTPUT_TEXTURE_COORD30_EXT     0x87BB
-#define GL_OUTPUT_TEXTURE_COORD31_EXT     0x87BC
-#define GL_OUTPUT_FOG_EXT                 0x87BD
-#define GL_SCALAR_EXT                     0x87BE
-#define GL_VECTOR_EXT                     0x87BF
-#define GL_MATRIX_EXT                     0x87C0
-#define GL_VARIANT_EXT                    0x87C1
-#define GL_INVARIANT_EXT                  0x87C2
-#define GL_LOCAL_CONSTANT_EXT             0x87C3
-#define GL_LOCAL_EXT                      0x87C4
-#define GL_MAX_VERTEX_SHADER_INSTRUCTIONS_EXT 0x87C5
-#define GL_MAX_VERTEX_SHADER_VARIANTS_EXT 0x87C6
-#define GL_MAX_VERTEX_SHADER_INVARIANTS_EXT 0x87C7
-#define GL_MAX_VERTEX_SHADER_LOCAL_CONSTANTS_EXT 0x87C8
-#define GL_MAX_VERTEX_SHADER_LOCALS_EXT   0x87C9
-#define GL_MAX_OPTIMIZED_VERTEX_SHADER_INSTRUCTIONS_EXT 0x87CA
-#define GL_MAX_OPTIMIZED_VERTEX_SHADER_VARIANTS_EXT 0x87CB
-#define GL_MAX_OPTIMIZED_VERTEX_SHADER_LOCAL_CONSTANTS_EXT 0x87CC
-#define GL_MAX_OPTIMIZED_VERTEX_SHADER_INVARIANTS_EXT 0x87CD
-#define GL_MAX_OPTIMIZED_VERTEX_SHADER_LOCALS_EXT 0x87CE
-#define GL_VERTEX_SHADER_INSTRUCTIONS_EXT 0x87CF
-#define GL_VERTEX_SHADER_VARIANTS_EXT     0x87D0
-#define GL_VERTEX_SHADER_INVARIANTS_EXT   0x87D1
-#define GL_VERTEX_SHADER_LOCAL_CONSTANTS_EXT 0x87D2
-#define GL_VERTEX_SHADER_LOCALS_EXT       0x87D3
-#define GL_VERTEX_SHADER_OPTIMIZED_EXT    0x87D4
-#define GL_X_EXT                          0x87D5
-#define GL_Y_EXT                          0x87D6
-#define GL_Z_EXT                          0x87D7
-#define GL_W_EXT                          0x87D8
-#define GL_NEGATIVE_X_EXT                 0x87D9
-#define GL_NEGATIVE_Y_EXT                 0x87DA
-#define GL_NEGATIVE_Z_EXT                 0x87DB
-#define GL_NEGATIVE_W_EXT                 0x87DC
-#define GL_ZERO_EXT                       0x87DD
-#define GL_ONE_EXT                        0x87DE
-#define GL_NEGATIVE_ONE_EXT               0x87DF
-#define GL_NORMALIZED_RANGE_EXT           0x87E0
-#define GL_FULL_RANGE_EXT                 0x87E1
-#define GL_CURRENT_VERTEX_EXT             0x87E2
-#define GL_MVP_MATRIX_EXT                 0x87E3
-#define GL_VARIANT_VALUE_EXT              0x87E4
-#define GL_VARIANT_DATATYPE_EXT           0x87E5
-#define GL_VARIANT_ARRAY_STRIDE_EXT       0x87E6
-#define GL_VARIANT_ARRAY_TYPE_EXT         0x87E7
-#define GL_VARIANT_ARRAY_EXT              0x87E8
-#define GL_VARIANT_ARRAY_POINTER_EXT      0x87E9
-#define GL_INVARIANT_VALUE_EXT            0x87EA
-#define GL_INVARIANT_DATATYPE_EXT         0x87EB
-#define GL_LOCAL_CONSTANT_VALUE_EXT       0x87EC
-#define GL_LOCAL_CONSTANT_DATATYPE_EXT    0x87ED
-#endif
-
-#ifndef GL_ATI_vertex_streams
-#define GL_MAX_VERTEX_STREAMS_ATI         0x876B
-#define GL_VERTEX_STREAM0_ATI             0x876C
-#define GL_VERTEX_STREAM1_ATI             0x876D
-#define GL_VERTEX_STREAM2_ATI             0x876E
-#define GL_VERTEX_STREAM3_ATI             0x876F
-#define GL_VERTEX_STREAM4_ATI             0x8770
-#define GL_VERTEX_STREAM5_ATI             0x8771
-#define GL_VERTEX_STREAM6_ATI             0x8772
-#define GL_VERTEX_STREAM7_ATI             0x8773
-#define GL_VERTEX_SOURCE_ATI              0x8774
-#endif
-
-#ifndef GL_ATI_element_array
-#define GL_ELEMENT_ARRAY_ATI              0x8768
-#define GL_ELEMENT_ARRAY_TYPE_ATI         0x8769
-#define GL_ELEMENT_ARRAY_POINTER_ATI      0x876A
-#endif
-
-#ifndef GL_SUN_mesh_array
-#define GL_QUAD_MESH_SUN                  0x8614
-#define GL_TRIANGLE_MESH_SUN              0x8615
-#endif
-
-#ifndef GL_SUN_slice_accum
-#define GL_SLICE_ACCUM_SUN                0x85CC
-#endif
-
-#ifndef GL_NV_multisample_filter_hint
-#define GL_MULTISAMPLE_FILTER_HINT_NV     0x8534
-#endif
-
-#ifndef GL_NV_depth_clamp
-#define GL_DEPTH_CLAMP_NV                 0x864F
-#endif
-
-#ifndef GL_NV_occlusion_query
-#define GL_PIXEL_COUNTER_BITS_NV          0x8864
-#define GL_CURRENT_OCCLUSION_QUERY_ID_NV  0x8865
-#define GL_PIXEL_COUNT_NV                 0x8866
-#define GL_PIXEL_COUNT_AVAILABLE_NV       0x8867
-#endif
-
-#ifndef GL_NV_point_sprite
-#define GL_POINT_SPRITE_NV                0x8861
-#define GL_COORD_REPLACE_NV               0x8862
-#define GL_POINT_SPRITE_R_MODE_NV         0x8863
-#endif
-
-#ifndef GL_NV_texture_shader3
-#define GL_OFFSET_PROJECTIVE_TEXTURE_2D_NV 0x8850
-#define GL_OFFSET_PROJECTIVE_TEXTURE_2D_SCALE_NV 0x8851
-#define GL_OFFSET_PROJECTIVE_TEXTURE_RECTANGLE_NV 0x8852
-#define GL_OFFSET_PROJECTIVE_TEXTURE_RECTANGLE_SCALE_NV 0x8853
-#define GL_OFFSET_HILO_TEXTURE_2D_NV      0x8854
-#define GL_OFFSET_HILO_TEXTURE_RECTANGLE_NV 0x8855
-#define GL_OFFSET_HILO_PROJECTIVE_TEXTURE_2D_NV 0x8856
-#define GL_OFFSET_HILO_PROJECTIVE_TEXTURE_RECTANGLE_NV 0x8857
-#define GL_DEPENDENT_HILO_TEXTURE_2D_NV   0x8858
-#define GL_DEPENDENT_RGB_TEXTURE_3D_NV    0x8859
-#define GL_DEPENDENT_RGB_TEXTURE_CUBE_MAP_NV 0x885A
-#define GL_DOT_PRODUCT_PASS_THROUGH_NV    0x885B
-#define GL_DOT_PRODUCT_TEXTURE_1D_NV      0x885C
-#define GL_DOT_PRODUCT_AFFINE_DEPTH_REPLACE_NV 0x885D
-#define GL_HILO8_NV                       0x885E
-#define GL_SIGNED_HILO8_NV                0x885F
-#define GL_FORCE_BLUE_TO_ONE_NV           0x8860
-#endif
-
-#ifndef GL_NV_vertex_program1_1
-#endif
-
-#ifndef GL_EXT_shadow_funcs
-#endif
-
-#ifndef GL_EXT_stencil_two_side
-#define GL_STENCIL_TEST_TWO_SIDE_EXT      0x8910
-#define GL_ACTIVE_STENCIL_FACE_EXT        0x8911
-#endif
-
-#ifndef GL_ATI_text_fragment_shader
-#define GL_TEXT_FRAGMENT_SHADER_ATI       0x8200
-#endif
-
-#ifndef GL_APPLE_client_storage
-#define GL_UNPACK_CLIENT_STORAGE_APPLE    0x85B2
-#endif
-
-#ifndef GL_APPLE_element_array
-#define GL_ELEMENT_ARRAY_APPLE            0x8768
-#define GL_ELEMENT_ARRAY_TYPE_APPLE       0x8769
-#define GL_ELEMENT_ARRAY_POINTER_APPLE    0x876A
-#endif
-
-#ifndef GL_APPLE_fence
-#define GL_DRAW_PIXELS_APPLE              0x8A0A
-#define GL_FENCE_APPLE                    0x8A0B
-#endif
-
-#ifndef GL_APPLE_vertex_array_object
-#define GL_VERTEX_ARRAY_BINDING_APPLE     0x85B5
-#endif
-
-#ifndef GL_APPLE_vertex_array_range
-#define GL_VERTEX_ARRAY_RANGE_APPLE       0x851D
-#define GL_VERTEX_ARRAY_RANGE_LENGTH_APPLE 0x851E
-#define GL_VERTEX_ARRAY_STORAGE_HINT_APPLE 0x851F
-#define GL_VERTEX_ARRAY_RANGE_POINTER_APPLE 0x8521
-#define GL_STORAGE_CACHED_APPLE           0x85BE
-#define GL_STORAGE_SHARED_APPLE           0x85BF
-#endif
-
-#ifndef GL_APPLE_ycbcr_422
-#define GL_YCBCR_422_APPLE                0x85B9
-#define GL_UNSIGNED_SHORT_8_8_APPLE       0x85BA
-#define GL_UNSIGNED_SHORT_8_8_REV_APPLE   0x85BB
-#endif
-
-#ifndef GL_S3_s3tc
-#define GL_RGB_S3TC                       0x83A0
-#define GL_RGB4_S3TC                      0x83A1
-#define GL_RGBA_S3TC                      0x83A2
-#define GL_RGBA4_S3TC                     0x83A3
-#endif
-
-#ifndef GL_ATI_draw_buffers
-#define GL_MAX_DRAW_BUFFERS_ATI           0x8824
-#define GL_DRAW_BUFFER0_ATI               0x8825
-#define GL_DRAW_BUFFER1_ATI               0x8826
-#define GL_DRAW_BUFFER2_ATI               0x8827
-#define GL_DRAW_BUFFER3_ATI               0x8828
-#define GL_DRAW_BUFFER4_ATI               0x8829
-#define GL_DRAW_BUFFER5_ATI               0x882A
-#define GL_DRAW_BUFFER6_ATI               0x882B
-#define GL_DRAW_BUFFER7_ATI               0x882C
-#define GL_DRAW_BUFFER8_ATI               0x882D
-#define GL_DRAW_BUFFER9_ATI               0x882E
-#define GL_DRAW_BUFFER10_ATI              0x882F
-#define GL_DRAW_BUFFER11_ATI              0x8830
-#define GL_DRAW_BUFFER12_ATI              0x8831
-#define GL_DRAW_BUFFER13_ATI              0x8832
-#define GL_DRAW_BUFFER14_ATI              0x8833
-#define GL_DRAW_BUFFER15_ATI              0x8834
-#endif
-
-#ifndef GL_ATI_pixel_format_float
-#define GL_TYPE_RGBA_FLOAT_ATI            0x8820
-#define GL_COLOR_CLEAR_UNCLAMPED_VALUE_ATI 0x8835
-#endif
-
-#ifndef GL_ATI_texture_env_combine3
-#define GL_MODULATE_ADD_ATI               0x8744
-#define GL_MODULATE_SIGNED_ADD_ATI        0x8745
-#define GL_MODULATE_SUBTRACT_ATI          0x8746
-#endif
-
-#ifndef GL_ATI_texture_float
-#define GL_RGBA_FLOAT32_ATI               0x8814
-#define GL_RGB_FLOAT32_ATI                0x8815
-#define GL_ALPHA_FLOAT32_ATI              0x8816
-#define GL_INTENSITY_FLOAT32_ATI          0x8817
-#define GL_LUMINANCE_FLOAT32_ATI          0x8818
-#define GL_LUMINANCE_ALPHA_FLOAT32_ATI    0x8819
-#define GL_RGBA_FLOAT16_ATI               0x881A
-#define GL_RGB_FLOAT16_ATI                0x881B
-#define GL_ALPHA_FLOAT16_ATI              0x881C
-#define GL_INTENSITY_FLOAT16_ATI          0x881D
-#define GL_LUMINANCE_FLOAT16_ATI          0x881E
-#define GL_LUMINANCE_ALPHA_FLOAT16_ATI    0x881F
-#endif
-
-#ifndef GL_NV_float_buffer
-#define GL_FLOAT_R_NV                     0x8880
-#define GL_FLOAT_RG_NV                    0x8881
-#define GL_FLOAT_RGB_NV                   0x8882
-#define GL_FLOAT_RGBA_NV                  0x8883
-#define GL_FLOAT_R16_NV                   0x8884
-#define GL_FLOAT_R32_NV                   0x8885
-#define GL_FLOAT_RG16_NV                  0x8886
-#define GL_FLOAT_RG32_NV                  0x8887
-#define GL_FLOAT_RGB16_NV                 0x8888
-#define GL_FLOAT_RGB32_NV                 0x8889
-#define GL_FLOAT_RGBA16_NV                0x888A
-#define GL_FLOAT_RGBA32_NV                0x888B
-#define GL_TEXTURE_FLOAT_COMPONENTS_NV    0x888C
-#define GL_FLOAT_CLEAR_COLOR_VALUE_NV     0x888D
-#define GL_FLOAT_RGBA_MODE_NV             0x888E
-#endif
-
-#ifndef GL_NV_fragment_program
-#define GL_MAX_FRAGMENT_PROGRAM_LOCAL_PARAMETERS_NV 0x8868
-#define GL_FRAGMENT_PROGRAM_NV            0x8870
-#define GL_MAX_TEXTURE_COORDS_NV          0x8871
-#define GL_MAX_TEXTURE_IMAGE_UNITS_NV     0x8872
-#define GL_FRAGMENT_PROGRAM_BINDING_NV    0x8873
-#define GL_PROGRAM_ERROR_STRING_NV        0x8874
-#endif
-
-#ifndef GL_NV_half_float
-#define GL_HALF_FLOAT_NV                  0x140B
-#endif
-
-#ifndef GL_NV_pixel_data_range
-#define GL_WRITE_PIXEL_DATA_RANGE_NV      0x8878
-#define GL_READ_PIXEL_DATA_RANGE_NV       0x8879
-#define GL_WRITE_PIXEL_DATA_RANGE_LENGTH_NV 0x887A
-#define GL_READ_PIXEL_DATA_RANGE_LENGTH_NV 0x887B
-#define GL_WRITE_PIXEL_DATA_RANGE_POINTER_NV 0x887C
-#define GL_READ_PIXEL_DATA_RANGE_POINTER_NV 0x887D
-#endif
-
-#ifndef GL_NV_primitive_restart
-#define GL_PRIMITIVE_RESTART_NV           0x8558
-#define GL_PRIMITIVE_RESTART_INDEX_NV     0x8559
-#endif
-
-#ifndef GL_NV_texture_expand_normal
-#define GL_TEXTURE_UNSIGNED_REMAP_MODE_NV 0x888F
-#endif
-
-#ifndef GL_NV_vertex_program2
-#endif
-
-#ifndef GL_ATI_map_object_buffer
-#endif
-
-#ifndef GL_ATI_separate_stencil
-#define GL_STENCIL_BACK_FUNC_ATI          0x8800
-#define GL_STENCIL_BACK_FAIL_ATI          0x8801
-#define GL_STENCIL_BACK_PASS_DEPTH_FAIL_ATI 0x8802
-#define GL_STENCIL_BACK_PASS_DEPTH_PASS_ATI 0x8803
-#endif
-
-#ifndef GL_ATI_vertex_attrib_array_object
-#endif
-
-#ifndef GL_OES_read_format
-#define GL_IMPLEMENTATION_COLOR_READ_TYPE_OES 0x8B9A
-#define GL_IMPLEMENTATION_COLOR_READ_FORMAT_OES 0x8B9B
-#endif
-
-#ifndef GL_EXT_depth_bounds_test
-#define GL_DEPTH_BOUNDS_TEST_EXT          0x8890
-#define GL_DEPTH_BOUNDS_EXT               0x8891
-#endif
-
-#ifndef GL_EXT_texture_mirror_clamp
-#define GL_MIRROR_CLAMP_EXT               0x8742
-#define GL_MIRROR_CLAMP_TO_EDGE_EXT       0x8743
-#define GL_MIRROR_CLAMP_TO_BORDER_EXT     0x8912
-#endif
-
-#ifndef GL_EXT_blend_equation_separate
-#define GL_BLEND_EQUATION_RGB_EXT         GL_BLEND_EQUATION
-#define GL_BLEND_EQUATION_ALPHA_EXT       0x883D
-#endif
-
-#ifndef GL_MESA_pack_invert
-#define GL_PACK_INVERT_MESA               0x8758
-#endif
-
-#ifndef GL_MESA_ycbcr_texture
-#define GL_UNSIGNED_SHORT_8_8_MESA        0x85BA
-#define GL_UNSIGNED_SHORT_8_8_REV_MESA    0x85BB
-#define GL_YCBCR_MESA                     0x8757
-#endif
-
-#ifndef GL_EXT_pixel_buffer_object
-#define GL_PIXEL_PACK_BUFFER_EXT          0x88EB
-#define GL_PIXEL_UNPACK_BUFFER_EXT        0x88EC
-#define GL_PIXEL_PACK_BUFFER_BINDING_EXT  0x88ED
-#define GL_PIXEL_UNPACK_BUFFER_BINDING_EXT 0x88EF
-#endif
-
-#ifndef GL_NV_fragment_program_option
-#endif
-
-#ifndef GL_NV_fragment_program2
-#define GL_MAX_PROGRAM_EXEC_INSTRUCTIONS_NV 0x88F4
-#define GL_MAX_PROGRAM_CALL_DEPTH_NV      0x88F5
-#define GL_MAX_PROGRAM_IF_DEPTH_NV        0x88F6
-#define GL_MAX_PROGRAM_LOOP_DEPTH_NV      0x88F7
-#define GL_MAX_PROGRAM_LOOP_COUNT_NV      0x88F8
-#endif
-
-#ifndef GL_NV_vertex_program2_option
-/* reuse GL_MAX_PROGRAM_EXEC_INSTRUCTIONS_NV */
-/* reuse GL_MAX_PROGRAM_CALL_DEPTH_NV */
-#endif
-
-#ifndef GL_NV_vertex_program3
-/* reuse GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB */
-#endif
-
-#ifndef GL_EXT_framebuffer_object
-#define GL_INVALID_FRAMEBUFFER_OPERATION_EXT 0x0506
-#define GL_MAX_RENDERBUFFER_SIZE_EXT      0x84E8
-#define GL_FRAMEBUFFER_BINDING_EXT        0x8CA6
-#define GL_RENDERBUFFER_BINDING_EXT       0x8CA7
-#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE_EXT 0x8CD0
-#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_EXT 0x8CD1
-#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL_EXT 0x8CD2
-#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE_EXT 0x8CD3
-#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_3D_ZOFFSET_EXT 0x8CD4
-#define GL_FRAMEBUFFER_COMPLETE_EXT       0x8CD5
-#define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT 0x8CD6
-#define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT 0x8CD7
-#define GL_FRAMEBUFFER_INCOMPLETE_DUPLICATE_ATTACHMENT_EXT 0x8CD8
-#define GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT 0x8CD9
-#define GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT 0x8CDA
-#define GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT 0x8CDB
-#define GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT 0x8CDC
-#define GL_FRAMEBUFFER_UNSUPPORTED_EXT    0x8CDD
-#define GL_MAX_COLOR_ATTACHMENTS_EXT      0x8CDF
-#define GL_COLOR_ATTACHMENT0_EXT          0x8CE0
-#define GL_COLOR_ATTACHMENT1_EXT          0x8CE1
-#define GL_COLOR_ATTACHMENT2_EXT          0x8CE2
-#define GL_COLOR_ATTACHMENT3_EXT          0x8CE3
-#define GL_COLOR_ATTACHMENT4_EXT          0x8CE4
-#define GL_COLOR_ATTACHMENT5_EXT          0x8CE5
-#define GL_COLOR_ATTACHMENT6_EXT          0x8CE6
-#define GL_COLOR_ATTACHMENT7_EXT          0x8CE7
-#define GL_COLOR_ATTACHMENT8_EXT          0x8CE8
-#define GL_COLOR_ATTACHMENT9_EXT          0x8CE9
-#define GL_COLOR_ATTACHMENT10_EXT         0x8CEA
-#define GL_COLOR_ATTACHMENT11_EXT         0x8CEB
-#define GL_COLOR_ATTACHMENT12_EXT         0x8CEC
-#define GL_COLOR_ATTACHMENT13_EXT         0x8CED
-#define GL_COLOR_ATTACHMENT14_EXT         0x8CEE
-#define GL_COLOR_ATTACHMENT15_EXT         0x8CEF
-#define GL_DEPTH_ATTACHMENT_EXT           0x8D00
-#define GL_STENCIL_ATTACHMENT_EXT         0x8D20
-#define GL_FRAMEBUFFER_EXT                0x8D40
-#define GL_RENDERBUFFER_EXT               0x8D41
-#define GL_RENDERBUFFER_WIDTH_EXT         0x8D42
-#define GL_RENDERBUFFER_HEIGHT_EXT        0x8D43
-#define GL_RENDERBUFFER_INTERNAL_FORMAT_EXT 0x8D44
-#define GL_STENCIL_INDEX_EXT              0x8D45
-#define GL_STENCIL_INDEX1_EXT             0x8D46
-#define GL_STENCIL_INDEX4_EXT             0x8D47
-#define GL_STENCIL_INDEX8_EXT             0x8D48
-#define GL_STENCIL_INDEX16_EXT            0x8D49
-#define GL_RENDERBUFFER_RED_SIZE_EXT      0x8D50
-#define GL_RENDERBUFFER_GREEN_SIZE_EXT    0x8D51
-#define GL_RENDERBUFFER_BLUE_SIZE_EXT     0x8D52
-#define GL_RENDERBUFFER_ALPHA_SIZE_EXT    0x8D53
-#define GL_RENDERBUFFER_DEPTH_SIZE_EXT    0x8D54
-#define GL_RENDERBUFFER_STENCIL_SIZE_EXT  0x8D55
-#endif
-
-#ifndef GL_GREMEDY_string_marker
-#endif
-
-#ifndef GL_EXT_Cg_shader
-#define GL_CG_VERTEX_SHADER_EXT           0x890E
-#define GL_CG_FRAGMENT_SHADER_EXT         0x890E
-#endif
-
-#ifndef GL_NV_element_array
-#define GL_ELEMENT_ARRAY_TYPE_NV          0x8769
-#define GL_ELEMENT_ARRAY_POINTER_NV       0x876A
-#endif
-
-#ifndef GL_NV_pixel_buffer_object
-#define GL_PIXEL_PACK_BUFFER_NV             0x88EB
-#define GL_PIXEL_UNPACK_BUFFER_NV           0x88EC
-#define GL_PIXEL_PACK_BUFFER_BINDING_NV     0x88ED
-#define GL_PIXEL_UNPACK_BUFFER_BINDING_NV   0x88EF
-#endif
-
-#ifndef GL_NV_stencil_two_side
-#define GL_STENCIL_TEST_TWO_SIDE_NV       0x8910
-#define GL_ACTIVE_STENCIL_FACE_NV         0x8911
-#endif
-
-/*************************************************************/
-
-#include <stddef.h>
-#ifndef GL_VERSION_2_0
-/* GL type for program/shader text */
-typedef char GLchar;			/* native character */
-#endif
-
-#ifndef GL_VERSION_1_5
-/* GL types for handling large vertex buffer objects */
-typedef ptrdiff_t GLintptr;
-typedef ptrdiff_t GLsizeiptr;
-#endif
-
-#ifndef GL_ARB_vertex_buffer_object
-/* GL types for handling large vertex buffer objects */
-typedef ptrdiff_t GLintptrARB;
-typedef ptrdiff_t GLsizeiptrARB;
-#endif
-
-#ifndef GL_ARB_shader_objects
-/* GL types for handling shader object handles and program/shader text */
-typedef char GLcharARB;		/* native character */
-typedef unsigned int GLhandleARB;	/* shader object handle */
-#endif
-
-/* GL types for "half" precision (s10e5) float data in host memory */
-#ifndef GL_ARB_half_float_pixel
-typedef unsigned short GLhalfARB;
-#endif
-
-#ifndef GL_NV_half_float
-typedef unsigned short GLhalfNV;
-#endif
-
-#ifndef GL_VERSION_1_2
-#define GL_VERSION_1_2 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glBlendColor (GLclampf, GLclampf, GLclampf, GLclampf);
-GLAPI void APIENTRY glBlendEquation (GLenum);
-GLAPI void APIENTRY glDrawRangeElements (GLenum, GLuint, GLuint, GLsizei, GLenum, const GLvoid *);
-GLAPI void APIENTRY glColorTable (GLenum, GLenum, GLsizei, GLenum, GLenum, const GLvoid *);
-GLAPI void APIENTRY glColorTableParameterfv (GLenum, GLenum, const GLfloat *);
-GLAPI void APIENTRY glColorTableParameteriv (GLenum, GLenum, const GLint *);
-GLAPI void APIENTRY glCopyColorTable (GLenum, GLenum, GLint, GLint, GLsizei);
-GLAPI void APIENTRY glGetColorTable (GLenum, GLenum, GLenum, GLvoid *);
-GLAPI void APIENTRY glGetColorTableParameterfv (GLenum, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetColorTableParameteriv (GLenum, GLenum, GLint *);
-GLAPI void APIENTRY glColorSubTable (GLenum, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *);
-GLAPI void APIENTRY glCopyColorSubTable (GLenum, GLsizei, GLint, GLint, GLsizei);
-GLAPI void APIENTRY glConvolutionFilter1D (GLenum, GLenum, GLsizei, GLenum, GLenum, const GLvoid *);
-GLAPI void APIENTRY glConvolutionFilter2D (GLenum, GLenum, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *);
-GLAPI void APIENTRY glConvolutionParameterf (GLenum, GLenum, GLfloat);
-GLAPI void APIENTRY glConvolutionParameterfv (GLenum, GLenum, const GLfloat *);
-GLAPI void APIENTRY glConvolutionParameteri (GLenum, GLenum, GLint);
-GLAPI void APIENTRY glConvolutionParameteriv (GLenum, GLenum, const GLint *);
-GLAPI void APIENTRY glCopyConvolutionFilter1D (GLenum, GLenum, GLint, GLint, GLsizei);
-GLAPI void APIENTRY glCopyConvolutionFilter2D (GLenum, GLenum, GLint, GLint, GLsizei, GLsizei);
-GLAPI void APIENTRY glGetConvolutionFilter (GLenum, GLenum, GLenum, GLvoid *);
-GLAPI void APIENTRY glGetConvolutionParameterfv (GLenum, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetConvolutionParameteriv (GLenum, GLenum, GLint *);
-GLAPI void APIENTRY glGetSeparableFilter (GLenum, GLenum, GLenum, GLvoid *, GLvoid *, GLvoid *);
-GLAPI void APIENTRY glSeparableFilter2D (GLenum, GLenum, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *, const GLvoid *);
-GLAPI void APIENTRY glGetHistogram (GLenum, GLboolean, GLenum, GLenum, GLvoid *);
-GLAPI void APIENTRY glGetHistogramParameterfv (GLenum, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetHistogramParameteriv (GLenum, GLenum, GLint *);
-GLAPI void APIENTRY glGetMinmax (GLenum, GLboolean, GLenum, GLenum, GLvoid *);
-GLAPI void APIENTRY glGetMinmaxParameterfv (GLenum, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetMinmaxParameteriv (GLenum, GLenum, GLint *);
-GLAPI void APIENTRY glHistogram (GLenum, GLsizei, GLenum, GLboolean);
-GLAPI void APIENTRY glMinmax (GLenum, GLenum, GLboolean);
-GLAPI void APIENTRY glResetHistogram (GLenum);
-GLAPI void APIENTRY glResetMinmax (GLenum);
-GLAPI void APIENTRY glTexImage3D (GLenum, GLint, GLint, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *);
-GLAPI void APIENTRY glTexSubImage3D (GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *);
-GLAPI void APIENTRY glCopyTexSubImage3D (GLenum, GLint, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLBLENDCOLORPROC) (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);
-typedef void (APIENTRYP PFNGLBLENDEQUATIONPROC) (GLenum mode);
-typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTSPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid *indices);
-typedef void (APIENTRYP PFNGLCOLORTABLEPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *table);
-typedef void (APIENTRYP PFNGLCOLORTABLEPARAMETERFVPROC) (GLenum target, GLenum pname, const GLfloat *params);
-typedef void (APIENTRYP PFNGLCOLORTABLEPARAMETERIVPROC) (GLenum target, GLenum pname, const GLint *params);
-typedef void (APIENTRYP PFNGLCOPYCOLORTABLEPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width);
-typedef void (APIENTRYP PFNGLGETCOLORTABLEPROC) (GLenum target, GLenum format, GLenum type, GLvoid *table);
-typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLCOLORSUBTABLEPROC) (GLenum target, GLsizei start, GLsizei count, GLenum format, GLenum type, const GLvoid *data);
-typedef void (APIENTRYP PFNGLCOPYCOLORSUBTABLEPROC) (GLenum target, GLsizei start, GLint x, GLint y, GLsizei width);
-typedef void (APIENTRYP PFNGLCONVOLUTIONFILTER1DPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *image);
-typedef void (APIENTRYP PFNGLCONVOLUTIONFILTER2DPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *image);
-typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERFPROC) (GLenum target, GLenum pname, GLfloat params);
-typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERFVPROC) (GLenum target, GLenum pname, const GLfloat *params);
-typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERIPROC) (GLenum target, GLenum pname, GLint params);
-typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERIVPROC) (GLenum target, GLenum pname, const GLint *params);
-typedef void (APIENTRYP PFNGLCOPYCONVOLUTIONFILTER1DPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width);
-typedef void (APIENTRYP PFNGLCOPYCONVOLUTIONFILTER2DPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height);
-typedef void (APIENTRYP PFNGLGETCONVOLUTIONFILTERPROC) (GLenum target, GLenum format, GLenum type, GLvoid *image);
-typedef void (APIENTRYP PFNGLGETCONVOLUTIONPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETCONVOLUTIONPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETSEPARABLEFILTERPROC) (GLenum target, GLenum format, GLenum type, GLvoid *row, GLvoid *column, GLvoid *span);
-typedef void (APIENTRYP PFNGLSEPARABLEFILTER2DPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *row, const GLvoid *column);
-typedef void (APIENTRYP PFNGLGETHISTOGRAMPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLvoid *values);
-typedef void (APIENTRYP PFNGLGETHISTOGRAMPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETHISTOGRAMPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETMINMAXPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLvoid *values);
-typedef void (APIENTRYP PFNGLGETMINMAXPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETMINMAXPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLHISTOGRAMPROC) (GLenum target, GLsizei width, GLenum internalformat, GLboolean sink);
-typedef void (APIENTRYP PFNGLMINMAXPROC) (GLenum target, GLenum internalformat, GLboolean sink);
-typedef void (APIENTRYP PFNGLRESETHISTOGRAMPROC) (GLenum target);
-typedef void (APIENTRYP PFNGLRESETMINMAXPROC) (GLenum target);
-typedef void (APIENTRYP PFNGLTEXIMAGE3DPROC) (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
-typedef void (APIENTRYP PFNGLTEXSUBIMAGE3DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid *pixels);
-typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE3DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height);
-#endif
-
-#ifndef GL_VERSION_1_3
-#define GL_VERSION_1_3 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glActiveTexture (GLenum);
-GLAPI void APIENTRY glClientActiveTexture (GLenum);
-GLAPI void APIENTRY glMultiTexCoord1d (GLenum, GLdouble);
-GLAPI void APIENTRY glMultiTexCoord1dv (GLenum, const GLdouble *);
-GLAPI void APIENTRY glMultiTexCoord1f (GLenum, GLfloat);
-GLAPI void APIENTRY glMultiTexCoord1fv (GLenum, const GLfloat *);
-GLAPI void APIENTRY glMultiTexCoord1i (GLenum, GLint);
-GLAPI void APIENTRY glMultiTexCoord1iv (GLenum, const GLint *);
-GLAPI void APIENTRY glMultiTexCoord1s (GLenum, GLshort);
-GLAPI void APIENTRY glMultiTexCoord1sv (GLenum, const GLshort *);
-GLAPI void APIENTRY glMultiTexCoord2d (GLenum, GLdouble, GLdouble);
-GLAPI void APIENTRY glMultiTexCoord2dv (GLenum, const GLdouble *);
-GLAPI void APIENTRY glMultiTexCoord2f (GLenum, GLfloat, GLfloat);
-GLAPI void APIENTRY glMultiTexCoord2fv (GLenum, const GLfloat *);
-GLAPI void APIENTRY glMultiTexCoord2i (GLenum, GLint, GLint);
-GLAPI void APIENTRY glMultiTexCoord2iv (GLenum, const GLint *);
-GLAPI void APIENTRY glMultiTexCoord2s (GLenum, GLshort, GLshort);
-GLAPI void APIENTRY glMultiTexCoord2sv (GLenum, const GLshort *);
-GLAPI void APIENTRY glMultiTexCoord3d (GLenum, GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glMultiTexCoord3dv (GLenum, const GLdouble *);
-GLAPI void APIENTRY glMultiTexCoord3f (GLenum, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glMultiTexCoord3fv (GLenum, const GLfloat *);
-GLAPI void APIENTRY glMultiTexCoord3i (GLenum, GLint, GLint, GLint);
-GLAPI void APIENTRY glMultiTexCoord3iv (GLenum, const GLint *);
-GLAPI void APIENTRY glMultiTexCoord3s (GLenum, GLshort, GLshort, GLshort);
-GLAPI void APIENTRY glMultiTexCoord3sv (GLenum, const GLshort *);
-GLAPI void APIENTRY glMultiTexCoord4d (GLenum, GLdouble, GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glMultiTexCoord4dv (GLenum, const GLdouble *);
-GLAPI void APIENTRY glMultiTexCoord4f (GLenum, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glMultiTexCoord4fv (GLenum, const GLfloat *);
-GLAPI void APIENTRY glMultiTexCoord4i (GLenum, GLint, GLint, GLint, GLint);
-GLAPI void APIENTRY glMultiTexCoord4iv (GLenum, const GLint *);
-GLAPI void APIENTRY glMultiTexCoord4s (GLenum, GLshort, GLshort, GLshort, GLshort);
-GLAPI void APIENTRY glMultiTexCoord4sv (GLenum, const GLshort *);
-GLAPI void APIENTRY glLoadTransposeMatrixf (const GLfloat *);
-GLAPI void APIENTRY glLoadTransposeMatrixd (const GLdouble *);
-GLAPI void APIENTRY glMultTransposeMatrixf (const GLfloat *);
-GLAPI void APIENTRY glMultTransposeMatrixd (const GLdouble *);
-GLAPI void APIENTRY glSampleCoverage (GLclampf, GLboolean);
-GLAPI void APIENTRY glCompressedTexImage3D (GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLsizei, const GLvoid *);
-GLAPI void APIENTRY glCompressedTexImage2D (GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLsizei, const GLvoid *);
-GLAPI void APIENTRY glCompressedTexImage1D (GLenum, GLint, GLenum, GLsizei, GLint, GLsizei, const GLvoid *);
-GLAPI void APIENTRY glCompressedTexSubImage3D (GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid *);
-GLAPI void APIENTRY glCompressedTexSubImage2D (GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid *);
-GLAPI void APIENTRY glCompressedTexSubImage1D (GLenum, GLint, GLint, GLsizei, GLenum, GLsizei, const GLvoid *);
-GLAPI void APIENTRY glGetCompressedTexImage (GLenum, GLint, GLvoid *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLACTIVETEXTUREPROC) (GLenum texture);
-typedef void (APIENTRYP PFNGLCLIENTACTIVETEXTUREPROC) (GLenum texture);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD1DPROC) (GLenum target, GLdouble s);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD1DVPROC) (GLenum target, const GLdouble *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD1FPROC) (GLenum target, GLfloat s);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD1FVPROC) (GLenum target, const GLfloat *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD1IPROC) (GLenum target, GLint s);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD1IVPROC) (GLenum target, const GLint *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD1SPROC) (GLenum target, GLshort s);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD1SVPROC) (GLenum target, const GLshort *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD2DPROC) (GLenum target, GLdouble s, GLdouble t);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD2DVPROC) (GLenum target, const GLdouble *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD2FPROC) (GLenum target, GLfloat s, GLfloat t);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD2FVPROC) (GLenum target, const GLfloat *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD2IPROC) (GLenum target, GLint s, GLint t);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD2IVPROC) (GLenum target, const GLint *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD2SPROC) (GLenum target, GLshort s, GLshort t);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD2SVPROC) (GLenum target, const GLshort *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD3DPROC) (GLenum target, GLdouble s, GLdouble t, GLdouble r);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD3DVPROC) (GLenum target, const GLdouble *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD3FPROC) (GLenum target, GLfloat s, GLfloat t, GLfloat r);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD3FVPROC) (GLenum target, const GLfloat *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD3IPROC) (GLenum target, GLint s, GLint t, GLint r);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD3IVPROC) (GLenum target, const GLint *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD3SPROC) (GLenum target, GLshort s, GLshort t, GLshort r);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD3SVPROC) (GLenum target, const GLshort *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD4DPROC) (GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD4DVPROC) (GLenum target, const GLdouble *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD4FPROC) (GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD4FVPROC) (GLenum target, const GLfloat *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD4IPROC) (GLenum target, GLint s, GLint t, GLint r, GLint q);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD4IVPROC) (GLenum target, const GLint *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD4SPROC) (GLenum target, GLshort s, GLshort t, GLshort r, GLshort q);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD4SVPROC) (GLenum target, const GLshort *v);
-typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXFPROC) (const GLfloat *m);
-typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXDPROC) (const GLdouble *m);
-typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXFPROC) (const GLfloat *m);
-typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXDPROC) (const GLdouble *m);
-typedef void (APIENTRYP PFNGLSAMPLECOVERAGEPROC) (GLclampf value, GLboolean invert);
-typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE3DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *data);
-typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE2DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *data);
-typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE1DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid *data);
-typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid *data);
-typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *data);
-typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC) (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const GLvoid *data);
-typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXIMAGEPROC) (GLenum target, GLint level, GLvoid *img);
-#endif
-
-#ifndef GL_VERSION_1_4
-#define GL_VERSION_1_4 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glBlendFuncSeparate (GLenum, GLenum, GLenum, GLenum);
-GLAPI void APIENTRY glFogCoordf (GLfloat);
-GLAPI void APIENTRY glFogCoordfv (const GLfloat *);
-GLAPI void APIENTRY glFogCoordd (GLdouble);
-GLAPI void APIENTRY glFogCoorddv (const GLdouble *);
-GLAPI void APIENTRY glFogCoordPointer (GLenum, GLsizei, const GLvoid *);
-GLAPI void APIENTRY glMultiDrawArrays (GLenum, GLint *, GLsizei *, GLsizei);
-GLAPI void APIENTRY glMultiDrawElements (GLenum, const GLsizei *, GLenum, const GLvoid* *, GLsizei);
-GLAPI void APIENTRY glPointParameterf (GLenum, GLfloat);
-GLAPI void APIENTRY glPointParameterfv (GLenum, const GLfloat *);
-GLAPI void APIENTRY glPointParameteri (GLenum, GLint);
-GLAPI void APIENTRY glPointParameteriv (GLenum, const GLint *);
-GLAPI void APIENTRY glSecondaryColor3b (GLbyte, GLbyte, GLbyte);
-GLAPI void APIENTRY glSecondaryColor3bv (const GLbyte *);
-GLAPI void APIENTRY glSecondaryColor3d (GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glSecondaryColor3dv (const GLdouble *);
-GLAPI void APIENTRY glSecondaryColor3f (GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glSecondaryColor3fv (const GLfloat *);
-GLAPI void APIENTRY glSecondaryColor3i (GLint, GLint, GLint);
-GLAPI void APIENTRY glSecondaryColor3iv (const GLint *);
-GLAPI void APIENTRY glSecondaryColor3s (GLshort, GLshort, GLshort);
-GLAPI void APIENTRY glSecondaryColor3sv (const GLshort *);
-GLAPI void APIENTRY glSecondaryColor3ub (GLubyte, GLubyte, GLubyte);
-GLAPI void APIENTRY glSecondaryColor3ubv (const GLubyte *);
-GLAPI void APIENTRY glSecondaryColor3ui (GLuint, GLuint, GLuint);
-GLAPI void APIENTRY glSecondaryColor3uiv (const GLuint *);
-GLAPI void APIENTRY glSecondaryColor3us (GLushort, GLushort, GLushort);
-GLAPI void APIENTRY glSecondaryColor3usv (const GLushort *);
-GLAPI void APIENTRY glSecondaryColorPointer (GLint, GLenum, GLsizei, const GLvoid *);
-GLAPI void APIENTRY glWindowPos2d (GLdouble, GLdouble);
-GLAPI void APIENTRY glWindowPos2dv (const GLdouble *);
-GLAPI void APIENTRY glWindowPos2f (GLfloat, GLfloat);
-GLAPI void APIENTRY glWindowPos2fv (const GLfloat *);
-GLAPI void APIENTRY glWindowPos2i (GLint, GLint);
-GLAPI void APIENTRY glWindowPos2iv (const GLint *);
-GLAPI void APIENTRY glWindowPos2s (GLshort, GLshort);
-GLAPI void APIENTRY glWindowPos2sv (const GLshort *);
-GLAPI void APIENTRY glWindowPos3d (GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glWindowPos3dv (const GLdouble *);
-GLAPI void APIENTRY glWindowPos3f (GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glWindowPos3fv (const GLfloat *);
-GLAPI void APIENTRY glWindowPos3i (GLint, GLint, GLint);
-GLAPI void APIENTRY glWindowPos3iv (const GLint *);
-GLAPI void APIENTRY glWindowPos3s (GLshort, GLshort, GLshort);
-GLAPI void APIENTRY glWindowPos3sv (const GLshort *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);
-typedef void (APIENTRYP PFNGLFOGCOORDFPROC) (GLfloat coord);
-typedef void (APIENTRYP PFNGLFOGCOORDFVPROC) (const GLfloat *coord);
-typedef void (APIENTRYP PFNGLFOGCOORDDPROC) (GLdouble coord);
-typedef void (APIENTRYP PFNGLFOGCOORDDVPROC) (const GLdouble *coord);
-typedef void (APIENTRYP PFNGLFOGCOORDPOINTERPROC) (GLenum type, GLsizei stride, const GLvoid *pointer);
-typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSPROC) (GLenum mode, GLint *first, GLsizei *count, GLsizei primcount);
-typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSPROC) (GLenum mode, const GLsizei *count, GLenum type, const GLvoid* *indices, GLsizei primcount);
-typedef void (APIENTRYP PFNGLPOINTPARAMETERFPROC) (GLenum pname, GLfloat param);
-typedef void (APIENTRYP PFNGLPOINTPARAMETERFVPROC) (GLenum pname, const GLfloat *params);
-typedef void (APIENTRYP PFNGLPOINTPARAMETERIPROC) (GLenum pname, GLint param);
-typedef void (APIENTRYP PFNGLPOINTPARAMETERIVPROC) (GLenum pname, const GLint *params);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BPROC) (GLbyte red, GLbyte green, GLbyte blue);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BVPROC) (const GLbyte *v);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DPROC) (GLdouble red, GLdouble green, GLdouble blue);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DVPROC) (const GLdouble *v);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FPROC) (GLfloat red, GLfloat green, GLfloat blue);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FVPROC) (const GLfloat *v);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IPROC) (GLint red, GLint green, GLint blue);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IVPROC) (const GLint *v);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SPROC) (GLshort red, GLshort green, GLshort blue);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SVPROC) (const GLshort *v);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBPROC) (GLubyte red, GLubyte green, GLubyte blue);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBVPROC) (const GLubyte *v);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIPROC) (GLuint red, GLuint green, GLuint blue);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIVPROC) (const GLuint *v);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USPROC) (GLushort red, GLushort green, GLushort blue);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USVPROC) (const GLushort *v);
-typedef void (APIENTRYP PFNGLSECONDARYCOLORPOINTERPROC) (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
-typedef void (APIENTRYP PFNGLWINDOWPOS2DPROC) (GLdouble x, GLdouble y);
-typedef void (APIENTRYP PFNGLWINDOWPOS2DVPROC) (const GLdouble *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS2FPROC) (GLfloat x, GLfloat y);
-typedef void (APIENTRYP PFNGLWINDOWPOS2FVPROC) (const GLfloat *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS2IPROC) (GLint x, GLint y);
-typedef void (APIENTRYP PFNGLWINDOWPOS2IVPROC) (const GLint *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS2SPROC) (GLshort x, GLshort y);
-typedef void (APIENTRYP PFNGLWINDOWPOS2SVPROC) (const GLshort *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS3DPROC) (GLdouble x, GLdouble y, GLdouble z);
-typedef void (APIENTRYP PFNGLWINDOWPOS3DVPROC) (const GLdouble *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS3FPROC) (GLfloat x, GLfloat y, GLfloat z);
-typedef void (APIENTRYP PFNGLWINDOWPOS3FVPROC) (const GLfloat *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS3IPROC) (GLint x, GLint y, GLint z);
-typedef void (APIENTRYP PFNGLWINDOWPOS3IVPROC) (const GLint *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS3SPROC) (GLshort x, GLshort y, GLshort z);
-typedef void (APIENTRYP PFNGLWINDOWPOS3SVPROC) (const GLshort *v);
-#endif
-
-#ifndef GL_VERSION_1_5
-#define GL_VERSION_1_5 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glGenQueries (GLsizei, GLuint *);
-GLAPI void APIENTRY glDeleteQueries (GLsizei, const GLuint *);
-GLAPI GLboolean APIENTRY glIsQuery (GLuint);
-GLAPI void APIENTRY glBeginQuery (GLenum, GLuint);
-GLAPI void APIENTRY glEndQuery (GLenum);
-GLAPI void APIENTRY glGetQueryiv (GLenum, GLenum, GLint *);
-GLAPI void APIENTRY glGetQueryObjectiv (GLuint, GLenum, GLint *);
-GLAPI void APIENTRY glGetQueryObjectuiv (GLuint, GLenum, GLuint *);
-GLAPI void APIENTRY glBindBuffer (GLenum, GLuint);
-GLAPI void APIENTRY glDeleteBuffers (GLsizei, const GLuint *);
-GLAPI void APIENTRY glGenBuffers (GLsizei, GLuint *);
-GLAPI GLboolean APIENTRY glIsBuffer (GLuint);
-GLAPI void APIENTRY glBufferData (GLenum, GLsizeiptr, const GLvoid *, GLenum);
-GLAPI void APIENTRY glBufferSubData (GLenum, GLintptr, GLsizeiptr, const GLvoid *);
-GLAPI void APIENTRY glGetBufferSubData (GLenum, GLintptr, GLsizeiptr, GLvoid *);
-GLAPI GLvoid* APIENTRY glMapBuffer (GLenum, GLenum);
-GLAPI GLboolean APIENTRY glUnmapBuffer (GLenum);
-GLAPI void APIENTRY glGetBufferParameteriv (GLenum, GLenum, GLint *);
-GLAPI void APIENTRY glGetBufferPointerv (GLenum, GLenum, GLvoid* *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLGENQUERIESPROC) (GLsizei n, GLuint *ids);
-typedef void (APIENTRYP PFNGLDELETEQUERIESPROC) (GLsizei n, const GLuint *ids);
-typedef GLboolean (APIENTRYP PFNGLISQUERYPROC) (GLuint id);
-typedef void (APIENTRYP PFNGLBEGINQUERYPROC) (GLenum target, GLuint id);
-typedef void (APIENTRYP PFNGLENDQUERYPROC) (GLenum target);
-typedef void (APIENTRYP PFNGLGETQUERYIVPROC) (GLenum target, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETQUERYOBJECTIVPROC) (GLuint id, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETQUERYOBJECTUIVPROC) (GLuint id, GLenum pname, GLuint *params);
-typedef void (APIENTRYP PFNGLBINDBUFFERPROC) (GLenum target, GLuint buffer);
-typedef void (APIENTRYP PFNGLDELETEBUFFERSPROC) (GLsizei n, const GLuint *buffers);
-typedef void (APIENTRYP PFNGLGENBUFFERSPROC) (GLsizei n, GLuint *buffers);
-typedef GLboolean (APIENTRYP PFNGLISBUFFERPROC) (GLuint buffer);
-typedef void (APIENTRYP PFNGLBUFFERDATAPROC) (GLenum target, GLsizeiptr size, const GLvoid *data, GLenum usage);
-typedef void (APIENTRYP PFNGLBUFFERSUBDATAPROC) (GLenum target, GLintptr offset, GLsizeiptr size, const GLvoid *data);
-typedef void (APIENTRYP PFNGLGETBUFFERSUBDATAPROC) (GLenum target, GLintptr offset, GLsizeiptr size, GLvoid *data);
-typedef GLvoid* (APIENTRYP PFNGLMAPBUFFERPROC) (GLenum target, GLenum access);
-typedef GLboolean (APIENTRYP PFNGLUNMAPBUFFERPROC) (GLenum target);
-typedef void (APIENTRYP PFNGLGETBUFFERPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETBUFFERPOINTERVPROC) (GLenum target, GLenum pname, GLvoid* *params);
-#endif
-
-#ifndef GL_VERSION_2_0
-#define GL_VERSION_2_0 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glBlendEquationSeparate (GLenum, GLenum);
-GLAPI void APIENTRY glDrawBuffers (GLsizei, const GLenum *);
-GLAPI void APIENTRY glStencilOpSeparate (GLenum, GLenum, GLenum, GLenum);
-GLAPI void APIENTRY glStencilFuncSeparate (GLenum, GLenum, GLint, GLuint);
-GLAPI void APIENTRY glStencilMaskSeparate (GLenum, GLuint);
-GLAPI void APIENTRY glAttachShader (GLuint, GLuint);
-GLAPI void APIENTRY glBindAttribLocation (GLuint, GLuint, const GLchar *);
-GLAPI void APIENTRY glCompileShader (GLuint);
-GLAPI GLuint APIENTRY glCreateProgram (void);
-GLAPI GLuint APIENTRY glCreateShader (GLenum);
-GLAPI void APIENTRY glDeleteProgram (GLuint);
-GLAPI void APIENTRY glDeleteShader (GLuint);
-GLAPI void APIENTRY glDetachShader (GLuint, GLuint);
-GLAPI void APIENTRY glDisableVertexAttribArray (GLuint);
-GLAPI void APIENTRY glEnableVertexAttribArray (GLuint);
-GLAPI void APIENTRY glGetActiveAttrib (GLuint, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLchar *);
-GLAPI void APIENTRY glGetActiveUniform (GLuint, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLchar *);
-GLAPI void APIENTRY glGetAttachedShaders (GLuint, GLsizei, GLsizei *, GLuint *);
-GLAPI GLint APIENTRY glGetAttribLocation (GLuint, const GLchar *);
-GLAPI void APIENTRY glGetProgramiv (GLuint, GLenum, GLint *);
-GLAPI void APIENTRY glGetProgramInfoLog (GLuint, GLsizei, GLsizei *, GLchar *);
-GLAPI void APIENTRY glGetShaderiv (GLuint, GLenum, GLint *);
-GLAPI void APIENTRY glGetShaderInfoLog (GLuint, GLsizei, GLsizei *, GLchar *);
-GLAPI void APIENTRY glGetShaderSource (GLuint, GLsizei, GLsizei *, GLchar *);
-GLAPI GLint APIENTRY glGetUniformLocation (GLuint, const GLchar *);
-GLAPI void APIENTRY glGetUniformfv (GLuint, GLint, GLfloat *);
-GLAPI void APIENTRY glGetUniformiv (GLuint, GLint, GLint *);
-GLAPI void APIENTRY glGetVertexAttribdv (GLuint, GLenum, GLdouble *);
-GLAPI void APIENTRY glGetVertexAttribfv (GLuint, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetVertexAttribiv (GLuint, GLenum, GLint *);
-GLAPI void APIENTRY glGetVertexAttribPointerv (GLuint, GLenum, GLvoid* *);
-GLAPI GLboolean APIENTRY glIsProgram (GLuint);
-GLAPI GLboolean APIENTRY glIsShader (GLuint);
-GLAPI void APIENTRY glLinkProgram (GLuint);
-GLAPI void APIENTRY glShaderSource (GLuint, GLsizei, const GLchar* *, const GLint *);
-GLAPI void APIENTRY glUseProgram (GLuint);
-GLAPI void APIENTRY glUniform1f (GLint, GLfloat);
-GLAPI void APIENTRY glUniform2f (GLint, GLfloat, GLfloat);
-GLAPI void APIENTRY glUniform3f (GLint, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glUniform4f (GLint, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glUniform1i (GLint, GLint);
-GLAPI void APIENTRY glUniform2i (GLint, GLint, GLint);
-GLAPI void APIENTRY glUniform3i (GLint, GLint, GLint, GLint);
-GLAPI void APIENTRY glUniform4i (GLint, GLint, GLint, GLint, GLint);
-GLAPI void APIENTRY glUniform1fv (GLint, GLsizei, const GLfloat *);
-GLAPI void APIENTRY glUniform2fv (GLint, GLsizei, const GLfloat *);
-GLAPI void APIENTRY glUniform3fv (GLint, GLsizei, const GLfloat *);
-GLAPI void APIENTRY glUniform4fv (GLint, GLsizei, const GLfloat *);
-GLAPI void APIENTRY glUniform1iv (GLint, GLsizei, const GLint *);
-GLAPI void APIENTRY glUniform2iv (GLint, GLsizei, const GLint *);
-GLAPI void APIENTRY glUniform3iv (GLint, GLsizei, const GLint *);
-GLAPI void APIENTRY glUniform4iv (GLint, GLsizei, const GLint *);
-GLAPI void APIENTRY glUniformMatrix2fv (GLint, GLsizei, GLboolean, const GLfloat *);
-GLAPI void APIENTRY glUniformMatrix3fv (GLint, GLsizei, GLboolean, const GLfloat *);
-GLAPI void APIENTRY glUniformMatrix4fv (GLint, GLsizei, GLboolean, const GLfloat *);
-GLAPI void APIENTRY glValidateProgram (GLuint);
-GLAPI void APIENTRY glVertexAttrib1d (GLuint, GLdouble);
-GLAPI void APIENTRY glVertexAttrib1dv (GLuint, const GLdouble *);
-GLAPI void APIENTRY glVertexAttrib1f (GLuint, GLfloat);
-GLAPI void APIENTRY glVertexAttrib1fv (GLuint, const GLfloat *);
-GLAPI void APIENTRY glVertexAttrib1s (GLuint, GLshort);
-GLAPI void APIENTRY glVertexAttrib1sv (GLuint, const GLshort *);
-GLAPI void APIENTRY glVertexAttrib2d (GLuint, GLdouble, GLdouble);
-GLAPI void APIENTRY glVertexAttrib2dv (GLuint, const GLdouble *);
-GLAPI void APIENTRY glVertexAttrib2f (GLuint, GLfloat, GLfloat);
-GLAPI void APIENTRY glVertexAttrib2fv (GLuint, const GLfloat *);
-GLAPI void APIENTRY glVertexAttrib2s (GLuint, GLshort, GLshort);
-GLAPI void APIENTRY glVertexAttrib2sv (GLuint, const GLshort *);
-GLAPI void APIENTRY glVertexAttrib3d (GLuint, GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glVertexAttrib3dv (GLuint, const GLdouble *);
-GLAPI void APIENTRY glVertexAttrib3f (GLuint, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glVertexAttrib3fv (GLuint, const GLfloat *);
-GLAPI void APIENTRY glVertexAttrib3s (GLuint, GLshort, GLshort, GLshort);
-GLAPI void APIENTRY glVertexAttrib3sv (GLuint, const GLshort *);
-GLAPI void APIENTRY glVertexAttrib4Nbv (GLuint, const GLbyte *);
-GLAPI void APIENTRY glVertexAttrib4Niv (GLuint, const GLint *);
-GLAPI void APIENTRY glVertexAttrib4Nsv (GLuint, const GLshort *);
-GLAPI void APIENTRY glVertexAttrib4Nub (GLuint, GLubyte, GLubyte, GLubyte, GLubyte);
-GLAPI void APIENTRY glVertexAttrib4Nubv (GLuint, const GLubyte *);
-GLAPI void APIENTRY glVertexAttrib4Nuiv (GLuint, const GLuint *);
-GLAPI void APIENTRY glVertexAttrib4Nusv (GLuint, const GLushort *);
-GLAPI void APIENTRY glVertexAttrib4bv (GLuint, const GLbyte *);
-GLAPI void APIENTRY glVertexAttrib4d (GLuint, GLdouble, GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glVertexAttrib4dv (GLuint, const GLdouble *);
-GLAPI void APIENTRY glVertexAttrib4f (GLuint, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glVertexAttrib4fv (GLuint, const GLfloat *);
-GLAPI void APIENTRY glVertexAttrib4iv (GLuint, const GLint *);
-GLAPI void APIENTRY glVertexAttrib4s (GLuint, GLshort, GLshort, GLshort, GLshort);
-GLAPI void APIENTRY glVertexAttrib4sv (GLuint, const GLshort *);
-GLAPI void APIENTRY glVertexAttrib4ubv (GLuint, const GLubyte *);
-GLAPI void APIENTRY glVertexAttrib4uiv (GLuint, const GLuint *);
-GLAPI void APIENTRY glVertexAttrib4usv (GLuint, const GLushort *);
-GLAPI void APIENTRY glVertexAttribPointer (GLuint, GLint, GLenum, GLboolean, GLsizei, const GLvoid *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEPROC) (GLenum modeRGB, GLenum modeAlpha);
-typedef void (APIENTRYP PFNGLDRAWBUFFERSPROC) (GLsizei n, const GLenum *bufs);
-typedef void (APIENTRYP PFNGLSTENCILOPSEPARATEPROC) (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass);
-typedef void (APIENTRYP PFNGLSTENCILFUNCSEPARATEPROC) (GLenum frontfunc, GLenum backfunc, GLint ref, GLuint mask);
-typedef void (APIENTRYP PFNGLSTENCILMASKSEPARATEPROC) (GLenum face, GLuint mask);
-typedef void (APIENTRYP PFNGLATTACHSHADERPROC) (GLuint program, GLuint shader);
-typedef void (APIENTRYP PFNGLBINDATTRIBLOCATIONPROC) (GLuint program, GLuint index, const GLchar *name);
-typedef void (APIENTRYP PFNGLCOMPILESHADERPROC) (GLuint shader);
-typedef GLuint (APIENTRYP PFNGLCREATEPROGRAMPROC) (void);
-typedef GLuint (APIENTRYP PFNGLCREATESHADERPROC) (GLenum type);
-typedef void (APIENTRYP PFNGLDELETEPROGRAMPROC) (GLuint program);
-typedef void (APIENTRYP PFNGLDELETESHADERPROC) (GLuint shader);
-typedef void (APIENTRYP PFNGLDETACHSHADERPROC) (GLuint program, GLuint shader);
-typedef void (APIENTRYP PFNGLDISABLEVERTEXATTRIBARRAYPROC) (GLuint index);
-typedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYPROC) (GLuint index);
-typedef void (APIENTRYP PFNGLGETACTIVEATTRIBPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name);
-typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name);
-typedef void (APIENTRYP PFNGLGETATTACHEDSHADERSPROC) (GLuint program, GLsizei maxCount, GLsizei *count, GLuint *obj);
-typedef GLint (APIENTRYP PFNGLGETATTRIBLOCATIONPROC) (GLuint program, const GLchar *name);
-typedef void (APIENTRYP PFNGLGETPROGRAMIVPROC) (GLuint program, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETPROGRAMINFOLOGPROC) (GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
-typedef void (APIENTRYP PFNGLGETSHADERIVPROC) (GLuint shader, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETSHADERINFOLOGPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
-typedef void (APIENTRYP PFNGLGETSHADERSOURCEPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *source);
-typedef GLint (APIENTRYP PFNGLGETUNIFORMLOCATIONPROC) (GLuint program, const GLchar *name);
-typedef void (APIENTRYP PFNGLGETUNIFORMFVPROC) (GLuint program, GLint location, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETUNIFORMIVPROC) (GLuint program, GLint location, GLint *params);
-typedef void (APIENTRYP PFNGLGETVERTEXATTRIBDVPROC) (GLuint index, GLenum pname, GLdouble *params);
-typedef void (APIENTRYP PFNGLGETVERTEXATTRIBFVPROC) (GLuint index, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVPROC) (GLuint index, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVPROC) (GLuint index, GLenum pname, GLvoid* *pointer);
-typedef GLboolean (APIENTRYP PFNGLISPROGRAMPROC) (GLuint program);
-typedef GLboolean (APIENTRYP PFNGLISSHADERPROC) (GLuint shader);
-typedef void (APIENTRYP PFNGLLINKPROGRAMPROC) (GLuint program);
-typedef void (APIENTRYP PFNGLSHADERSOURCEPROC) (GLuint shader, GLsizei count, const GLchar* *string, const GLint *length);
-typedef void (APIENTRYP PFNGLUSEPROGRAMPROC) (GLuint program);
-typedef void (APIENTRYP PFNGLUNIFORM1FPROC) (GLint location, GLfloat v0);
-typedef void (APIENTRYP PFNGLUNIFORM2FPROC) (GLint location, GLfloat v0, GLfloat v1);
-typedef void (APIENTRYP PFNGLUNIFORM3FPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2);
-typedef void (APIENTRYP PFNGLUNIFORM4FPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);
-typedef void (APIENTRYP PFNGLUNIFORM1IPROC) (GLint location, GLint v0);
-typedef void (APIENTRYP PFNGLUNIFORM2IPROC) (GLint location, GLint v0, GLint v1);
-typedef void (APIENTRYP PFNGLUNIFORM3IPROC) (GLint location, GLint v0, GLint v1, GLint v2);
-typedef void (APIENTRYP PFNGLUNIFORM4IPROC) (GLint location, GLint v0, GLint v1, GLint v2, GLint v3);
-typedef void (APIENTRYP PFNGLUNIFORM1FVPROC) (GLint location, GLsizei count, const GLfloat *value);
-typedef void (APIENTRYP PFNGLUNIFORM2FVPROC) (GLint location, GLsizei count, const GLfloat *value);
-typedef void (APIENTRYP PFNGLUNIFORM3FVPROC) (GLint location, GLsizei count, const GLfloat *value);
-typedef void (APIENTRYP PFNGLUNIFORM4FVPROC) (GLint location, GLsizei count, const GLfloat *value);
-typedef void (APIENTRYP PFNGLUNIFORM1IVPROC) (GLint location, GLsizei count, const GLint *value);
-typedef void (APIENTRYP PFNGLUNIFORM2IVPROC) (GLint location, GLsizei count, const GLint *value);
-typedef void (APIENTRYP PFNGLUNIFORM3IVPROC) (GLint location, GLsizei count, const GLint *value);
-typedef void (APIENTRYP PFNGLUNIFORM4IVPROC) (GLint location, GLsizei count, const GLint *value);
-typedef void (APIENTRYP PFNGLUNIFORMMATRIX2FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
-typedef void (APIENTRYP PFNGLUNIFORMMATRIX3FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
-typedef void (APIENTRYP PFNGLUNIFORMMATRIX4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
-typedef void (APIENTRYP PFNGLVALIDATEPROGRAMPROC) (GLuint program);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB1DPROC) (GLuint index, GLdouble x);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB1DVPROC) (GLuint index, const GLdouble *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB1FPROC) (GLuint index, GLfloat x);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB1FVPROC) (GLuint index, const GLfloat *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB1SPROC) (GLuint index, GLshort x);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB1SVPROC) (GLuint index, const GLshort *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB2DPROC) (GLuint index, GLdouble x, GLdouble y);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB2DVPROC) (GLuint index, const GLdouble *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB2FPROC) (GLuint index, GLfloat x, GLfloat y);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB2FVPROC) (GLuint index, const GLfloat *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB2SPROC) (GLuint index, GLshort x, GLshort y);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB2SVPROC) (GLuint index, const GLshort *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB3DPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB3DVPROC) (GLuint index, const GLdouble *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB3FPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB3FVPROC) (GLuint index, const GLfloat *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB3SPROC) (GLuint index, GLshort x, GLshort y, GLshort z);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB3SVPROC) (GLuint index, const GLshort *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4NBVPROC) (GLuint index, const GLbyte *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4NIVPROC) (GLuint index, const GLint *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4NSVPROC) (GLuint index, const GLshort *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBPROC) (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBVPROC) (GLuint index, const GLubyte *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUIVPROC) (GLuint index, const GLuint *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUSVPROC) (GLuint index, const GLushort *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4BVPROC) (GLuint index, const GLbyte *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4DPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4DVPROC) (GLuint index, const GLdouble *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4FPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4FVPROC) (GLuint index, const GLfloat *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4IVPROC) (GLuint index, const GLint *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4SPROC) (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4SVPROC) (GLuint index, const GLshort *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBVPROC) (GLuint index, const GLubyte *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4UIVPROC) (GLuint index, const GLuint *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4USVPROC) (GLuint index, const GLushort *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer);
-#endif
-
-#ifndef GL_ARB_multitexture
-#define GL_ARB_multitexture 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glActiveTextureARB (GLenum);
-GLAPI void APIENTRY glClientActiveTextureARB (GLenum);
-GLAPI void APIENTRY glMultiTexCoord1dARB (GLenum, GLdouble);
-GLAPI void APIENTRY glMultiTexCoord1dvARB (GLenum, const GLdouble *);
-GLAPI void APIENTRY glMultiTexCoord1fARB (GLenum, GLfloat);
-GLAPI void APIENTRY glMultiTexCoord1fvARB (GLenum, const GLfloat *);
-GLAPI void APIENTRY glMultiTexCoord1iARB (GLenum, GLint);
-GLAPI void APIENTRY glMultiTexCoord1ivARB (GLenum, const GLint *);
-GLAPI void APIENTRY glMultiTexCoord1sARB (GLenum, GLshort);
-GLAPI void APIENTRY glMultiTexCoord1svARB (GLenum, const GLshort *);
-GLAPI void APIENTRY glMultiTexCoord2dARB (GLenum, GLdouble, GLdouble);
-GLAPI void APIENTRY glMultiTexCoord2dvARB (GLenum, const GLdouble *);
-GLAPI void APIENTRY glMultiTexCoord2fARB (GLenum, GLfloat, GLfloat);
-GLAPI void APIENTRY glMultiTexCoord2fvARB (GLenum, const GLfloat *);
-GLAPI void APIENTRY glMultiTexCoord2iARB (GLenum, GLint, GLint);
-GLAPI void APIENTRY glMultiTexCoord2ivARB (GLenum, const GLint *);
-GLAPI void APIENTRY glMultiTexCoord2sARB (GLenum, GLshort, GLshort);
-GLAPI void APIENTRY glMultiTexCoord2svARB (GLenum, const GLshort *);
-GLAPI void APIENTRY glMultiTexCoord3dARB (GLenum, GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glMultiTexCoord3dvARB (GLenum, const GLdouble *);
-GLAPI void APIENTRY glMultiTexCoord3fARB (GLenum, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glMultiTexCoord3fvARB (GLenum, const GLfloat *);
-GLAPI void APIENTRY glMultiTexCoord3iARB (GLenum, GLint, GLint, GLint);
-GLAPI void APIENTRY glMultiTexCoord3ivARB (GLenum, const GLint *);
-GLAPI void APIENTRY glMultiTexCoord3sARB (GLenum, GLshort, GLshort, GLshort);
-GLAPI void APIENTRY glMultiTexCoord3svARB (GLenum, const GLshort *);
-GLAPI void APIENTRY glMultiTexCoord4dARB (GLenum, GLdouble, GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glMultiTexCoord4dvARB (GLenum, const GLdouble *);
-GLAPI void APIENTRY glMultiTexCoord4fARB (GLenum, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glMultiTexCoord4fvARB (GLenum, const GLfloat *);
-GLAPI void APIENTRY glMultiTexCoord4iARB (GLenum, GLint, GLint, GLint, GLint);
-GLAPI void APIENTRY glMultiTexCoord4ivARB (GLenum, const GLint *);
-GLAPI void APIENTRY glMultiTexCoord4sARB (GLenum, GLshort, GLshort, GLshort, GLshort);
-GLAPI void APIENTRY glMultiTexCoord4svARB (GLenum, const GLshort *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLACTIVETEXTUREARBPROC) (GLenum texture);
-typedef void (APIENTRYP PFNGLCLIENTACTIVETEXTUREARBPROC) (GLenum texture);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD1DARBPROC) (GLenum target, GLdouble s);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD1DVARBPROC) (GLenum target, const GLdouble *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD1FARBPROC) (GLenum target, GLfloat s);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD1FVARBPROC) (GLenum target, const GLfloat *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD1IARBPROC) (GLenum target, GLint s);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD1IVARBPROC) (GLenum target, const GLint *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD1SARBPROC) (GLenum target, GLshort s);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD1SVARBPROC) (GLenum target, const GLshort *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD2DARBPROC) (GLenum target, GLdouble s, GLdouble t);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD2DVARBPROC) (GLenum target, const GLdouble *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD2FARBPROC) (GLenum target, GLfloat s, GLfloat t);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD2FVARBPROC) (GLenum target, const GLfloat *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD2IARBPROC) (GLenum target, GLint s, GLint t);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD2IVARBPROC) (GLenum target, const GLint *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD2SARBPROC) (GLenum target, GLshort s, GLshort t);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD2SVARBPROC) (GLenum target, const GLshort *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD3DARBPROC) (GLenum target, GLdouble s, GLdouble t, GLdouble r);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD3DVARBPROC) (GLenum target, const GLdouble *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD3FARBPROC) (GLenum target, GLfloat s, GLfloat t, GLfloat r);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD3FVARBPROC) (GLenum target, const GLfloat *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD3IARBPROC) (GLenum target, GLint s, GLint t, GLint r);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD3IVARBPROC) (GLenum target, const GLint *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD3SARBPROC) (GLenum target, GLshort s, GLshort t, GLshort r);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD3SVARBPROC) (GLenum target, const GLshort *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD4DARBPROC) (GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD4DVARBPROC) (GLenum target, const GLdouble *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD4FARBPROC) (GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD4FVARBPROC) (GLenum target, const GLfloat *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD4IARBPROC) (GLenum target, GLint s, GLint t, GLint r, GLint q);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD4IVARBPROC) (GLenum target, const GLint *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD4SARBPROC) (GLenum target, GLshort s, GLshort t, GLshort r, GLshort q);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD4SVARBPROC) (GLenum target, const GLshort *v);
-#endif
-
-#ifndef GL_ARB_transpose_matrix
-#define GL_ARB_transpose_matrix 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glLoadTransposeMatrixfARB (const GLfloat *);
-GLAPI void APIENTRY glLoadTransposeMatrixdARB (const GLdouble *);
-GLAPI void APIENTRY glMultTransposeMatrixfARB (const GLfloat *);
-GLAPI void APIENTRY glMultTransposeMatrixdARB (const GLdouble *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXFARBPROC) (const GLfloat *m);
-typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXDARBPROC) (const GLdouble *m);
-typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXFARBPROC) (const GLfloat *m);
-typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXDARBPROC) (const GLdouble *m);
-#endif
-
-#ifndef GL_ARB_multisample
-#define GL_ARB_multisample 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glSampleCoverageARB (GLclampf, GLboolean);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLSAMPLECOVERAGEARBPROC) (GLclampf value, GLboolean invert);
-#endif
-
-#ifndef GL_ARB_texture_env_add
-#define GL_ARB_texture_env_add 1
-#endif
-
-#ifndef GL_ARB_texture_cube_map
-#define GL_ARB_texture_cube_map 1
-#endif
-
-#ifndef GL_ARB_texture_compression
-#define GL_ARB_texture_compression 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glCompressedTexImage3DARB (GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLsizei, const GLvoid *);
-GLAPI void APIENTRY glCompressedTexImage2DARB (GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLsizei, const GLvoid *);
-GLAPI void APIENTRY glCompressedTexImage1DARB (GLenum, GLint, GLenum, GLsizei, GLint, GLsizei, const GLvoid *);
-GLAPI void APIENTRY glCompressedTexSubImage3DARB (GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid *);
-GLAPI void APIENTRY glCompressedTexSubImage2DARB (GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid *);
-GLAPI void APIENTRY glCompressedTexSubImage1DARB (GLenum, GLint, GLint, GLsizei, GLenum, GLsizei, const GLvoid *);
-GLAPI void APIENTRY glGetCompressedTexImageARB (GLenum, GLint, GLvoid *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE3DARBPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *data);
-typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE2DARBPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *data);
-typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE1DARBPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid *data);
-typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE3DARBPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid *data);
-typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE2DARBPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *data);
-typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE1DARBPROC) (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const GLvoid *data);
-typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXIMAGEARBPROC) (GLenum target, GLint level, GLvoid *img);
-#endif
-
-#ifndef GL_ARB_texture_border_clamp
-#define GL_ARB_texture_border_clamp 1
-#endif
-
-#ifndef GL_ARB_point_parameters
-#define GL_ARB_point_parameters 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glPointParameterfARB (GLenum, GLfloat);
-GLAPI void APIENTRY glPointParameterfvARB (GLenum, const GLfloat *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLPOINTPARAMETERFARBPROC) (GLenum pname, GLfloat param);
-typedef void (APIENTRYP PFNGLPOINTPARAMETERFVARBPROC) (GLenum pname, const GLfloat *params);
-#endif
-
-#ifndef GL_ARB_vertex_blend
-#define GL_ARB_vertex_blend 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glWeightbvARB (GLint, const GLbyte *);
-GLAPI void APIENTRY glWeightsvARB (GLint, const GLshort *);
-GLAPI void APIENTRY glWeightivARB (GLint, const GLint *);
-GLAPI void APIENTRY glWeightfvARB (GLint, const GLfloat *);
-GLAPI void APIENTRY glWeightdvARB (GLint, const GLdouble *);
-GLAPI void APIENTRY glWeightubvARB (GLint, const GLubyte *);
-GLAPI void APIENTRY glWeightusvARB (GLint, const GLushort *);
-GLAPI void APIENTRY glWeightuivARB (GLint, const GLuint *);
-GLAPI void APIENTRY glWeightPointerARB (GLint, GLenum, GLsizei, const GLvoid *);
-GLAPI void APIENTRY glVertexBlendARB (GLint);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLWEIGHTBVARBPROC) (GLint size, const GLbyte *weights);
-typedef void (APIENTRYP PFNGLWEIGHTSVARBPROC) (GLint size, const GLshort *weights);
-typedef void (APIENTRYP PFNGLWEIGHTIVARBPROC) (GLint size, const GLint *weights);
-typedef void (APIENTRYP PFNGLWEIGHTFVARBPROC) (GLint size, const GLfloat *weights);
-typedef void (APIENTRYP PFNGLWEIGHTDVARBPROC) (GLint size, const GLdouble *weights);
-typedef void (APIENTRYP PFNGLWEIGHTUBVARBPROC) (GLint size, const GLubyte *weights);
-typedef void (APIENTRYP PFNGLWEIGHTUSVARBPROC) (GLint size, const GLushort *weights);
-typedef void (APIENTRYP PFNGLWEIGHTUIVARBPROC) (GLint size, const GLuint *weights);
-typedef void (APIENTRYP PFNGLWEIGHTPOINTERARBPROC) (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
-typedef void (APIENTRYP PFNGLVERTEXBLENDARBPROC) (GLint count);
-#endif
-
-#ifndef GL_ARB_matrix_palette
-#define GL_ARB_matrix_palette 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glCurrentPaletteMatrixARB (GLint);
-GLAPI void APIENTRY glMatrixIndexubvARB (GLint, const GLubyte *);
-GLAPI void APIENTRY glMatrixIndexusvARB (GLint, const GLushort *);
-GLAPI void APIENTRY glMatrixIndexuivARB (GLint, const GLuint *);
-GLAPI void APIENTRY glMatrixIndexPointerARB (GLint, GLenum, GLsizei, const GLvoid *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLCURRENTPALETTEMATRIXARBPROC) (GLint index);
-typedef void (APIENTRYP PFNGLMATRIXINDEXUBVARBPROC) (GLint size, const GLubyte *indices);
-typedef void (APIENTRYP PFNGLMATRIXINDEXUSVARBPROC) (GLint size, const GLushort *indices);
-typedef void (APIENTRYP PFNGLMATRIXINDEXUIVARBPROC) (GLint size, const GLuint *indices);
-typedef void (APIENTRYP PFNGLMATRIXINDEXPOINTERARBPROC) (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
-#endif
-
-#ifndef GL_ARB_texture_env_combine
-#define GL_ARB_texture_env_combine 1
-#endif
-
-#ifndef GL_ARB_texture_env_crossbar
-#define GL_ARB_texture_env_crossbar 1
-#endif
-
-#ifndef GL_ARB_texture_env_dot3
-#define GL_ARB_texture_env_dot3 1
-#endif
-
-#ifndef GL_ARB_texture_mirrored_repeat
-#define GL_ARB_texture_mirrored_repeat 1
-#endif
-
-#ifndef GL_ARB_depth_texture
-#define GL_ARB_depth_texture 1
-#endif
-
-#ifndef GL_ARB_shadow
-#define GL_ARB_shadow 1
-#endif
-
-#ifndef GL_ARB_shadow_ambient
-#define GL_ARB_shadow_ambient 1
-#endif
-
-#ifndef GL_ARB_window_pos
-#define GL_ARB_window_pos 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glWindowPos2dARB (GLdouble, GLdouble);
-GLAPI void APIENTRY glWindowPos2dvARB (const GLdouble *);
-GLAPI void APIENTRY glWindowPos2fARB (GLfloat, GLfloat);
-GLAPI void APIENTRY glWindowPos2fvARB (const GLfloat *);
-GLAPI void APIENTRY glWindowPos2iARB (GLint, GLint);
-GLAPI void APIENTRY glWindowPos2ivARB (const GLint *);
-GLAPI void APIENTRY glWindowPos2sARB (GLshort, GLshort);
-GLAPI void APIENTRY glWindowPos2svARB (const GLshort *);
-GLAPI void APIENTRY glWindowPos3dARB (GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glWindowPos3dvARB (const GLdouble *);
-GLAPI void APIENTRY glWindowPos3fARB (GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glWindowPos3fvARB (const GLfloat *);
-GLAPI void APIENTRY glWindowPos3iARB (GLint, GLint, GLint);
-GLAPI void APIENTRY glWindowPos3ivARB (const GLint *);
-GLAPI void APIENTRY glWindowPos3sARB (GLshort, GLshort, GLshort);
-GLAPI void APIENTRY glWindowPos3svARB (const GLshort *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLWINDOWPOS2DARBPROC) (GLdouble x, GLdouble y);
-typedef void (APIENTRYP PFNGLWINDOWPOS2DVARBPROC) (const GLdouble *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS2FARBPROC) (GLfloat x, GLfloat y);
-typedef void (APIENTRYP PFNGLWINDOWPOS2FVARBPROC) (const GLfloat *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS2IARBPROC) (GLint x, GLint y);
-typedef void (APIENTRYP PFNGLWINDOWPOS2IVARBPROC) (const GLint *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS2SARBPROC) (GLshort x, GLshort y);
-typedef void (APIENTRYP PFNGLWINDOWPOS2SVARBPROC) (const GLshort *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS3DARBPROC) (GLdouble x, GLdouble y, GLdouble z);
-typedef void (APIENTRYP PFNGLWINDOWPOS3DVARBPROC) (const GLdouble *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS3FARBPROC) (GLfloat x, GLfloat y, GLfloat z);
-typedef void (APIENTRYP PFNGLWINDOWPOS3FVARBPROC) (const GLfloat *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS3IARBPROC) (GLint x, GLint y, GLint z);
-typedef void (APIENTRYP PFNGLWINDOWPOS3IVARBPROC) (const GLint *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS3SARBPROC) (GLshort x, GLshort y, GLshort z);
-typedef void (APIENTRYP PFNGLWINDOWPOS3SVARBPROC) (const GLshort *v);
-#endif
-
-#ifndef GL_ARB_vertex_program
-#define GL_ARB_vertex_program 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glVertexAttrib1dARB (GLuint, GLdouble);
-GLAPI void APIENTRY glVertexAttrib1dvARB (GLuint, const GLdouble *);
-GLAPI void APIENTRY glVertexAttrib1fARB (GLuint, GLfloat);
-GLAPI void APIENTRY glVertexAttrib1fvARB (GLuint, const GLfloat *);
-GLAPI void APIENTRY glVertexAttrib1sARB (GLuint, GLshort);
-GLAPI void APIENTRY glVertexAttrib1svARB (GLuint, const GLshort *);
-GLAPI void APIENTRY glVertexAttrib2dARB (GLuint, GLdouble, GLdouble);
-GLAPI void APIENTRY glVertexAttrib2dvARB (GLuint, const GLdouble *);
-GLAPI void APIENTRY glVertexAttrib2fARB (GLuint, GLfloat, GLfloat);
-GLAPI void APIENTRY glVertexAttrib2fvARB (GLuint, const GLfloat *);
-GLAPI void APIENTRY glVertexAttrib2sARB (GLuint, GLshort, GLshort);
-GLAPI void APIENTRY glVertexAttrib2svARB (GLuint, const GLshort *);
-GLAPI void APIENTRY glVertexAttrib3dARB (GLuint, GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glVertexAttrib3dvARB (GLuint, const GLdouble *);
-GLAPI void APIENTRY glVertexAttrib3fARB (GLuint, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glVertexAttrib3fvARB (GLuint, const GLfloat *);
-GLAPI void APIENTRY glVertexAttrib3sARB (GLuint, GLshort, GLshort, GLshort);
-GLAPI void APIENTRY glVertexAttrib3svARB (GLuint, const GLshort *);
-GLAPI void APIENTRY glVertexAttrib4NbvARB (GLuint, const GLbyte *);
-GLAPI void APIENTRY glVertexAttrib4NivARB (GLuint, const GLint *);
-GLAPI void APIENTRY glVertexAttrib4NsvARB (GLuint, const GLshort *);
-GLAPI void APIENTRY glVertexAttrib4NubARB (GLuint, GLubyte, GLubyte, GLubyte, GLubyte);
-GLAPI void APIENTRY glVertexAttrib4NubvARB (GLuint, const GLubyte *);
-GLAPI void APIENTRY glVertexAttrib4NuivARB (GLuint, const GLuint *);
-GLAPI void APIENTRY glVertexAttrib4NusvARB (GLuint, const GLushort *);
-GLAPI void APIENTRY glVertexAttrib4bvARB (GLuint, const GLbyte *);
-GLAPI void APIENTRY glVertexAttrib4dARB (GLuint, GLdouble, GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glVertexAttrib4dvARB (GLuint, const GLdouble *);
-GLAPI void APIENTRY glVertexAttrib4fARB (GLuint, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glVertexAttrib4fvARB (GLuint, const GLfloat *);
-GLAPI void APIENTRY glVertexAttrib4ivARB (GLuint, const GLint *);
-GLAPI void APIENTRY glVertexAttrib4sARB (GLuint, GLshort, GLshort, GLshort, GLshort);
-GLAPI void APIENTRY glVertexAttrib4svARB (GLuint, const GLshort *);
-GLAPI void APIENTRY glVertexAttrib4ubvARB (GLuint, const GLubyte *);
-GLAPI void APIENTRY glVertexAttrib4uivARB (GLuint, const GLuint *);
-GLAPI void APIENTRY glVertexAttrib4usvARB (GLuint, const GLushort *);
-GLAPI void APIENTRY glVertexAttribPointerARB (GLuint, GLint, GLenum, GLboolean, GLsizei, const GLvoid *);
-GLAPI void APIENTRY glEnableVertexAttribArrayARB (GLuint);
-GLAPI void APIENTRY glDisableVertexAttribArrayARB (GLuint);
-GLAPI void APIENTRY glProgramStringARB (GLenum, GLenum, GLsizei, const GLvoid *);
-GLAPI void APIENTRY glBindProgramARB (GLenum, GLuint);
-GLAPI void APIENTRY glDeleteProgramsARB (GLsizei, const GLuint *);
-GLAPI void APIENTRY glGenProgramsARB (GLsizei, GLuint *);
-GLAPI void APIENTRY glProgramEnvParameter4dARB (GLenum, GLuint, GLdouble, GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glProgramEnvParameter4dvARB (GLenum, GLuint, const GLdouble *);
-GLAPI void APIENTRY glProgramEnvParameter4fARB (GLenum, GLuint, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glProgramEnvParameter4fvARB (GLenum, GLuint, const GLfloat *);
-GLAPI void APIENTRY glProgramLocalParameter4dARB (GLenum, GLuint, GLdouble, GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glProgramLocalParameter4dvARB (GLenum, GLuint, const GLdouble *);
-GLAPI void APIENTRY glProgramLocalParameter4fARB (GLenum, GLuint, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glProgramLocalParameter4fvARB (GLenum, GLuint, const GLfloat *);
-GLAPI void APIENTRY glGetProgramEnvParameterdvARB (GLenum, GLuint, GLdouble *);
-GLAPI void APIENTRY glGetProgramEnvParameterfvARB (GLenum, GLuint, GLfloat *);
-GLAPI void APIENTRY glGetProgramLocalParameterdvARB (GLenum, GLuint, GLdouble *);
-GLAPI void APIENTRY glGetProgramLocalParameterfvARB (GLenum, GLuint, GLfloat *);
-GLAPI void APIENTRY glGetProgramivARB (GLenum, GLenum, GLint *);
-GLAPI void APIENTRY glGetProgramStringARB (GLenum, GLenum, GLvoid *);
-GLAPI void APIENTRY glGetVertexAttribdvARB (GLuint, GLenum, GLdouble *);
-GLAPI void APIENTRY glGetVertexAttribfvARB (GLuint, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetVertexAttribivARB (GLuint, GLenum, GLint *);
-GLAPI void APIENTRY glGetVertexAttribPointervARB (GLuint, GLenum, GLvoid* *);
-GLAPI GLboolean APIENTRY glIsProgramARB (GLuint);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLVERTEXATTRIB1DARBPROC) (GLuint index, GLdouble x);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB1DVARBPROC) (GLuint index, const GLdouble *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB1FARBPROC) (GLuint index, GLfloat x);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB1FVARBPROC) (GLuint index, const GLfloat *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB1SARBPROC) (GLuint index, GLshort x);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB1SVARBPROC) (GLuint index, const GLshort *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB2DARBPROC) (GLuint index, GLdouble x, GLdouble y);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB2DVARBPROC) (GLuint index, const GLdouble *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB2FARBPROC) (GLuint index, GLfloat x, GLfloat y);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB2FVARBPROC) (GLuint index, const GLfloat *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB2SARBPROC) (GLuint index, GLshort x, GLshort y);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB2SVARBPROC) (GLuint index, const GLshort *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB3DARBPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB3DVARBPROC) (GLuint index, const GLdouble *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB3FARBPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB3FVARBPROC) (GLuint index, const GLfloat *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB3SARBPROC) (GLuint index, GLshort x, GLshort y, GLshort z);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB3SVARBPROC) (GLuint index, const GLshort *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4NBVARBPROC) (GLuint index, const GLbyte *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4NIVARBPROC) (GLuint index, const GLint *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4NSVARBPROC) (GLuint index, const GLshort *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBARBPROC) (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBVARBPROC) (GLuint index, const GLubyte *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUIVARBPROC) (GLuint index, const GLuint *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUSVARBPROC) (GLuint index, const GLushort *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4BVARBPROC) (GLuint index, const GLbyte *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4DARBPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4DVARBPROC) (GLuint index, const GLdouble *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4FARBPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4FVARBPROC) (GLuint index, const GLfloat *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4IVARBPROC) (GLuint index, const GLint *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4SARBPROC) (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4SVARBPROC) (GLuint index, const GLshort *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBVARBPROC) (GLuint index, const GLubyte *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4UIVARBPROC) (GLuint index, const GLuint *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4USVARBPROC) (GLuint index, const GLushort *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERARBPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer);
-typedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYARBPROC) (GLuint index);
-typedef void (APIENTRYP PFNGLDISABLEVERTEXATTRIBARRAYARBPROC) (GLuint index);
-typedef void (APIENTRYP PFNGLPROGRAMSTRINGARBPROC) (GLenum target, GLenum format, GLsizei len, const GLvoid *string);
-typedef void (APIENTRYP PFNGLBINDPROGRAMARBPROC) (GLenum target, GLuint program);
-typedef void (APIENTRYP PFNGLDELETEPROGRAMSARBPROC) (GLsizei n, const GLuint *programs);
-typedef void (APIENTRYP PFNGLGENPROGRAMSARBPROC) (GLsizei n, GLuint *programs);
-typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETER4DARBPROC) (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
-typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETER4DVARBPROC) (GLenum target, GLuint index, const GLdouble *params);
-typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETER4FARBPROC) (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
-typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETER4FVARBPROC) (GLenum target, GLuint index, const GLfloat *params);
-typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETER4DARBPROC) (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
-typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETER4DVARBPROC) (GLenum target, GLuint index, const GLdouble *params);
-typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETER4FARBPROC) (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
-typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETER4FVARBPROC) (GLenum target, GLuint index, const GLfloat *params);
-typedef void (APIENTRYP PFNGLGETPROGRAMENVPARAMETERDVARBPROC) (GLenum target, GLuint index, GLdouble *params);
-typedef void (APIENTRYP PFNGLGETPROGRAMENVPARAMETERFVARBPROC) (GLenum target, GLuint index, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETPROGRAMLOCALPARAMETERDVARBPROC) (GLenum target, GLuint index, GLdouble *params);
-typedef void (APIENTRYP PFNGLGETPROGRAMLOCALPARAMETERFVARBPROC) (GLenum target, GLuint index, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETPROGRAMIVARBPROC) (GLenum target, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETPROGRAMSTRINGARBPROC) (GLenum target, GLenum pname, GLvoid *string);
-typedef void (APIENTRYP PFNGLGETVERTEXATTRIBDVARBPROC) (GLuint index, GLenum pname, GLdouble *params);
-typedef void (APIENTRYP PFNGLGETVERTEXATTRIBFVARBPROC) (GLuint index, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVARBPROC) (GLuint index, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVARBPROC) (GLuint index, GLenum pname, GLvoid* *pointer);
-typedef GLboolean (APIENTRYP PFNGLISPROGRAMARBPROC) (GLuint program);
-#endif
-
-#ifndef GL_ARB_fragment_program
-#define GL_ARB_fragment_program 1
-/* All ARB_fragment_program entry points are shared with ARB_vertex_program. */
-#endif
-
-#ifndef GL_ARB_vertex_buffer_object
-#define GL_ARB_vertex_buffer_object 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glBindBufferARB (GLenum, GLuint);
-GLAPI void APIENTRY glDeleteBuffersARB (GLsizei, const GLuint *);
-GLAPI void APIENTRY glGenBuffersARB (GLsizei, GLuint *);
-GLAPI GLboolean APIENTRY glIsBufferARB (GLuint);
-GLAPI void APIENTRY glBufferDataARB (GLenum, GLsizeiptrARB, const GLvoid *, GLenum);
-GLAPI void APIENTRY glBufferSubDataARB (GLenum, GLintptrARB, GLsizeiptrARB, const GLvoid *);
-GLAPI void APIENTRY glGetBufferSubDataARB (GLenum, GLintptrARB, GLsizeiptrARB, GLvoid *);
-GLAPI GLvoid* APIENTRY glMapBufferARB (GLenum, GLenum);
-GLAPI GLboolean APIENTRY glUnmapBufferARB (GLenum);
-GLAPI void APIENTRY glGetBufferParameterivARB (GLenum, GLenum, GLint *);
-GLAPI void APIENTRY glGetBufferPointervARB (GLenum, GLenum, GLvoid* *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLBINDBUFFERARBPROC) (GLenum target, GLuint buffer);
-typedef void (APIENTRYP PFNGLDELETEBUFFERSARBPROC) (GLsizei n, const GLuint *buffers);
-typedef void (APIENTRYP PFNGLGENBUFFERSARBPROC) (GLsizei n, GLuint *buffers);
-typedef GLboolean (APIENTRYP PFNGLISBUFFERARBPROC) (GLuint buffer);
-typedef void (APIENTRYP PFNGLBUFFERDATAARBPROC) (GLenum target, GLsizeiptrARB size, const GLvoid *data, GLenum usage);
-typedef void (APIENTRYP PFNGLBUFFERSUBDATAARBPROC) (GLenum target, GLintptrARB offset, GLsizeiptrARB size, const GLvoid *data);
-typedef void (APIENTRYP PFNGLGETBUFFERSUBDATAARBPROC) (GLenum target, GLintptrARB offset, GLsizeiptrARB size, GLvoid *data);
-typedef GLvoid* (APIENTRYP PFNGLMAPBUFFERARBPROC) (GLenum target, GLenum access);
-typedef GLboolean (APIENTRYP PFNGLUNMAPBUFFERARBPROC) (GLenum target);
-typedef void (APIENTRYP PFNGLGETBUFFERPARAMETERIVARBPROC) (GLenum target, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETBUFFERPOINTERVARBPROC) (GLenum target, GLenum pname, GLvoid* *params);
-#endif
-
-#ifndef GL_ARB_occlusion_query
-#define GL_ARB_occlusion_query 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glGenQueriesARB (GLsizei, GLuint *);
-GLAPI void APIENTRY glDeleteQueriesARB (GLsizei, const GLuint *);
-GLAPI GLboolean APIENTRY glIsQueryARB (GLuint);
-GLAPI void APIENTRY glBeginQueryARB (GLenum, GLuint);
-GLAPI void APIENTRY glEndQueryARB (GLenum);
-GLAPI void APIENTRY glGetQueryivARB (GLenum, GLenum, GLint *);
-GLAPI void APIENTRY glGetQueryObjectivARB (GLuint, GLenum, GLint *);
-GLAPI void APIENTRY glGetQueryObjectuivARB (GLuint, GLenum, GLuint *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLGENQUERIESARBPROC) (GLsizei n, GLuint *ids);
-typedef void (APIENTRYP PFNGLDELETEQUERIESARBPROC) (GLsizei n, const GLuint *ids);
-typedef GLboolean (APIENTRYP PFNGLISQUERYARBPROC) (GLuint id);
-typedef void (APIENTRYP PFNGLBEGINQUERYARBPROC) (GLenum target, GLuint id);
-typedef void (APIENTRYP PFNGLENDQUERYARBPROC) (GLenum target);
-typedef void (APIENTRYP PFNGLGETQUERYIVARBPROC) (GLenum target, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETQUERYOBJECTIVARBPROC) (GLuint id, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETQUERYOBJECTUIVARBPROC) (GLuint id, GLenum pname, GLuint *params);
-#endif
-
-#ifndef GL_ARB_shader_objects
-#define GL_ARB_shader_objects 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glDeleteObjectARB (GLhandleARB);
-GLAPI GLhandleARB APIENTRY glGetHandleARB (GLenum);
-GLAPI void APIENTRY glDetachObjectARB (GLhandleARB, GLhandleARB);
-GLAPI GLhandleARB APIENTRY glCreateShaderObjectARB (GLenum);
-GLAPI void APIENTRY glShaderSourceARB (GLhandleARB, GLsizei, const GLcharARB* *, const GLint *);
-GLAPI void APIENTRY glCompileShaderARB (GLhandleARB);
-GLAPI GLhandleARB APIENTRY glCreateProgramObjectARB (void);
-GLAPI void APIENTRY glAttachObjectARB (GLhandleARB, GLhandleARB);
-GLAPI void APIENTRY glLinkProgramARB (GLhandleARB);
-GLAPI void APIENTRY glUseProgramObjectARB (GLhandleARB);
-GLAPI void APIENTRY glValidateProgramARB (GLhandleARB);
-GLAPI void APIENTRY glUniform1fARB (GLint, GLfloat);
-GLAPI void APIENTRY glUniform2fARB (GLint, GLfloat, GLfloat);
-GLAPI void APIENTRY glUniform3fARB (GLint, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glUniform4fARB (GLint, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glUniform1iARB (GLint, GLint);
-GLAPI void APIENTRY glUniform2iARB (GLint, GLint, GLint);
-GLAPI void APIENTRY glUniform3iARB (GLint, GLint, GLint, GLint);
-GLAPI void APIENTRY glUniform4iARB (GLint, GLint, GLint, GLint, GLint);
-GLAPI void APIENTRY glUniform1fvARB (GLint, GLsizei, const GLfloat *);
-GLAPI void APIENTRY glUniform2fvARB (GLint, GLsizei, const GLfloat *);
-GLAPI void APIENTRY glUniform3fvARB (GLint, GLsizei, const GLfloat *);
-GLAPI void APIENTRY glUniform4fvARB (GLint, GLsizei, const GLfloat *);
-GLAPI void APIENTRY glUniform1ivARB (GLint, GLsizei, const GLint *);
-GLAPI void APIENTRY glUniform2ivARB (GLint, GLsizei, const GLint *);
-GLAPI void APIENTRY glUniform3ivARB (GLint, GLsizei, const GLint *);
-GLAPI void APIENTRY glUniform4ivARB (GLint, GLsizei, const GLint *);
-GLAPI void APIENTRY glUniformMatrix2fvARB (GLint, GLsizei, GLboolean, const GLfloat *);
-GLAPI void APIENTRY glUniformMatrix3fvARB (GLint, GLsizei, GLboolean, const GLfloat *);
-GLAPI void APIENTRY glUniformMatrix4fvARB (GLint, GLsizei, GLboolean, const GLfloat *);
-GLAPI void APIENTRY glGetObjectParameterfvARB (GLhandleARB, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetObjectParameterivARB (GLhandleARB, GLenum, GLint *);
-GLAPI void APIENTRY glGetInfoLogARB (GLhandleARB, GLsizei, GLsizei *, GLcharARB *);
-GLAPI void APIENTRY glGetAttachedObjectsARB (GLhandleARB, GLsizei, GLsizei *, GLhandleARB *);
-GLAPI GLint APIENTRY glGetUniformLocationARB (GLhandleARB, const GLcharARB *);
-GLAPI void APIENTRY glGetActiveUniformARB (GLhandleARB, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLcharARB *);
-GLAPI void APIENTRY glGetUniformfvARB (GLhandleARB, GLint, GLfloat *);
-GLAPI void APIENTRY glGetUniformivARB (GLhandleARB, GLint, GLint *);
-GLAPI void APIENTRY glGetShaderSourceARB (GLhandleARB, GLsizei, GLsizei *, GLcharARB *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLDELETEOBJECTARBPROC) (GLhandleARB obj);
-typedef GLhandleARB (APIENTRYP PFNGLGETHANDLEARBPROC) (GLenum pname);
-typedef void (APIENTRYP PFNGLDETACHOBJECTARBPROC) (GLhandleARB containerObj, GLhandleARB attachedObj);
-typedef GLhandleARB (APIENTRYP PFNGLCREATESHADEROBJECTARBPROC) (GLenum shaderType);
-typedef void (APIENTRYP PFNGLSHADERSOURCEARBPROC) (GLhandleARB shaderObj, GLsizei count, const GLcharARB* *string, const GLint *length);
-typedef void (APIENTRYP PFNGLCOMPILESHADERARBPROC) (GLhandleARB shaderObj);
-typedef GLhandleARB (APIENTRYP PFNGLCREATEPROGRAMOBJECTARBPROC) (void);
-typedef void (APIENTRYP PFNGLATTACHOBJECTARBPROC) (GLhandleARB containerObj, GLhandleARB obj);
-typedef void (APIENTRYP PFNGLLINKPROGRAMARBPROC) (GLhandleARB programObj);
-typedef void (APIENTRYP PFNGLUSEPROGRAMOBJECTARBPROC) (GLhandleARB programObj);
-typedef void (APIENTRYP PFNGLVALIDATEPROGRAMARBPROC) (GLhandleARB programObj);
-typedef void (APIENTRYP PFNGLUNIFORM1FARBPROC) (GLint location, GLfloat v0);
-typedef void (APIENTRYP PFNGLUNIFORM2FARBPROC) (GLint location, GLfloat v0, GLfloat v1);
-typedef void (APIENTRYP PFNGLUNIFORM3FARBPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2);
-typedef void (APIENTRYP PFNGLUNIFORM4FARBPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);
-typedef void (APIENTRYP PFNGLUNIFORM1IARBPROC) (GLint location, GLint v0);
-typedef void (APIENTRYP PFNGLUNIFORM2IARBPROC) (GLint location, GLint v0, GLint v1);
-typedef void (APIENTRYP PFNGLUNIFORM3IARBPROC) (GLint location, GLint v0, GLint v1, GLint v2);
-typedef void (APIENTRYP PFNGLUNIFORM4IARBPROC) (GLint location, GLint v0, GLint v1, GLint v2, GLint v3);
-typedef void (APIENTRYP PFNGLUNIFORM1FVARBPROC) (GLint location, GLsizei count, const GLfloat *value);
-typedef void (APIENTRYP PFNGLUNIFORM2FVARBPROC) (GLint location, GLsizei count, const GLfloat *value);
-typedef void (APIENTRYP PFNGLUNIFORM3FVARBPROC) (GLint location, GLsizei count, const GLfloat *value);
-typedef void (APIENTRYP PFNGLUNIFORM4FVARBPROC) (GLint location, GLsizei count, const GLfloat *value);
-typedef void (APIENTRYP PFNGLUNIFORM1IVARBPROC) (GLint location, GLsizei count, const GLint *value);
-typedef void (APIENTRYP PFNGLUNIFORM2IVARBPROC) (GLint location, GLsizei count, const GLint *value);
-typedef void (APIENTRYP PFNGLUNIFORM3IVARBPROC) (GLint location, GLsizei count, const GLint *value);
-typedef void (APIENTRYP PFNGLUNIFORM4IVARBPROC) (GLint location, GLsizei count, const GLint *value);
-typedef void (APIENTRYP PFNGLUNIFORMMATRIX2FVARBPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
-typedef void (APIENTRYP PFNGLUNIFORMMATRIX3FVARBPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
-typedef void (APIENTRYP PFNGLUNIFORMMATRIX4FVARBPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
-typedef void (APIENTRYP PFNGLGETOBJECTPARAMETERFVARBPROC) (GLhandleARB obj, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETOBJECTPARAMETERIVARBPROC) (GLhandleARB obj, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETINFOLOGARBPROC) (GLhandleARB obj, GLsizei maxLength, GLsizei *length, GLcharARB *infoLog);
-typedef void (APIENTRYP PFNGLGETATTACHEDOBJECTSARBPROC) (GLhandleARB containerObj, GLsizei maxCount, GLsizei *count, GLhandleARB *obj);
-typedef GLint (APIENTRYP PFNGLGETUNIFORMLOCATIONARBPROC) (GLhandleARB programObj, const GLcharARB *name);
-typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMARBPROC) (GLhandleARB programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name);
-typedef void (APIENTRYP PFNGLGETUNIFORMFVARBPROC) (GLhandleARB programObj, GLint location, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETUNIFORMIVARBPROC) (GLhandleARB programObj, GLint location, GLint *params);
-typedef void (APIENTRYP PFNGLGETSHADERSOURCEARBPROC) (GLhandleARB obj, GLsizei maxLength, GLsizei *length, GLcharARB *source);
-#endif
-
-#ifndef GL_ARB_vertex_shader
-#define GL_ARB_vertex_shader 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glBindAttribLocationARB (GLhandleARB, GLuint, const GLcharARB *);
-GLAPI void APIENTRY glGetActiveAttribARB (GLhandleARB, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLcharARB *);
-GLAPI GLint APIENTRY glGetAttribLocationARB (GLhandleARB, const GLcharARB *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLBINDATTRIBLOCATIONARBPROC) (GLhandleARB programObj, GLuint index, const GLcharARB *name);
-typedef void (APIENTRYP PFNGLGETACTIVEATTRIBARBPROC) (GLhandleARB programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name);
-typedef GLint (APIENTRYP PFNGLGETATTRIBLOCATIONARBPROC) (GLhandleARB programObj, const GLcharARB *name);
-#endif
-
-#ifndef GL_ARB_fragment_shader
-#define GL_ARB_fragment_shader 1
-#endif
-
-#ifndef GL_ARB_shading_language_100
-#define GL_ARB_shading_language_100 1
-#endif
-
-#ifndef GL_ARB_texture_non_power_of_two
-#define GL_ARB_texture_non_power_of_two 1
-#endif
-
-#ifndef GL_ARB_point_sprite
-#define GL_ARB_point_sprite 1
-#endif
-
-#ifndef GL_ARB_fragment_program_shadow
-#define GL_ARB_fragment_program_shadow 1
-#endif
-
-#ifndef GL_ARB_draw_buffers
-#define GL_ARB_draw_buffers 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glDrawBuffersARB (GLsizei, const GLenum *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLDRAWBUFFERSARBPROC) (GLsizei n, const GLenum *bufs);
-#endif
-
-#ifndef GL_ARB_texture_rectangle
-#define GL_ARB_texture_rectangle 1
-#endif
-
-#ifndef GL_ARB_color_buffer_float
-#define GL_ARB_color_buffer_float 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glClampColorARB (GLenum, GLenum);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLCLAMPCOLORARBPROC) (GLenum target, GLenum clamp);
-#endif
-
-#ifndef GL_ARB_half_float_pixel
-#define GL_ARB_half_float_pixel 1
-#endif
-
-#ifndef GL_ARB_texture_float
-#define GL_ARB_texture_float 1
-#endif
-
-#ifndef GL_ARB_pixel_buffer_object
-#define GL_ARB_pixel_buffer_object 1
-#endif
-
-#ifndef GL_EXT_abgr
-#define GL_EXT_abgr 1
-#endif
-
-#ifndef GL_EXT_blend_color
-#define GL_EXT_blend_color 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glBlendColorEXT (GLclampf, GLclampf, GLclampf, GLclampf);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLBLENDCOLOREXTPROC) (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);
-#endif
-
-#ifndef GL_EXT_polygon_offset
-#define GL_EXT_polygon_offset 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glPolygonOffsetEXT (GLfloat, GLfloat);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLPOLYGONOFFSETEXTPROC) (GLfloat factor, GLfloat bias);
-#endif
-
-#ifndef GL_EXT_texture
-#define GL_EXT_texture 1
-#endif
-
-#ifndef GL_EXT_texture3D
-#define GL_EXT_texture3D 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glTexImage3DEXT (GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *);
-GLAPI void APIENTRY glTexSubImage3DEXT (GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLTEXIMAGE3DEXTPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
-typedef void (APIENTRYP PFNGLTEXSUBIMAGE3DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid *pixels);
-#endif
-
-#ifndef GL_SGIS_texture_filter4
-#define GL_SGIS_texture_filter4 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glGetTexFilterFuncSGIS (GLenum, GLenum, GLfloat *);
-GLAPI void APIENTRY glTexFilterFuncSGIS (GLenum, GLenum, GLsizei, const GLfloat *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLGETTEXFILTERFUNCSGISPROC) (GLenum target, GLenum filter, GLfloat *weights);
-typedef void (APIENTRYP PFNGLTEXFILTERFUNCSGISPROC) (GLenum target, GLenum filter, GLsizei n, const GLfloat *weights);
-#endif
-
-#ifndef GL_EXT_subtexture
-#define GL_EXT_subtexture 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glTexSubImage1DEXT (GLenum, GLint, GLint, GLsizei, GLenum, GLenum, const GLvoid *);
-GLAPI void APIENTRY glTexSubImage2DEXT (GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLTEXSUBIMAGE1DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const GLvoid *pixels);
-typedef void (APIENTRYP PFNGLTEXSUBIMAGE2DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels);
-#endif
-
-#ifndef GL_EXT_copy_texture
-#define GL_EXT_copy_texture 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glCopyTexImage1DEXT (GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLint);
-GLAPI void APIENTRY glCopyTexImage2DEXT (GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLsizei, GLint);
-GLAPI void APIENTRY glCopyTexSubImage1DEXT (GLenum, GLint, GLint, GLint, GLint, GLsizei);
-GLAPI void APIENTRY glCopyTexSubImage2DEXT (GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei);
-GLAPI void APIENTRY glCopyTexSubImage3DEXT (GLenum, GLint, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLCOPYTEXIMAGE1DEXTPROC) (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border);
-typedef void (APIENTRYP PFNGLCOPYTEXIMAGE2DEXTPROC) (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border);
-typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE1DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width);
-typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE2DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);
-typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE3DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height);
-#endif
-
-#ifndef GL_EXT_histogram
-#define GL_EXT_histogram 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glGetHistogramEXT (GLenum, GLboolean, GLenum, GLenum, GLvoid *);
-GLAPI void APIENTRY glGetHistogramParameterfvEXT (GLenum, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetHistogramParameterivEXT (GLenum, GLenum, GLint *);
-GLAPI void APIENTRY glGetMinmaxEXT (GLenum, GLboolean, GLenum, GLenum, GLvoid *);
-GLAPI void APIENTRY glGetMinmaxParameterfvEXT (GLenum, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetMinmaxParameterivEXT (GLenum, GLenum, GLint *);
-GLAPI void APIENTRY glHistogramEXT (GLenum, GLsizei, GLenum, GLboolean);
-GLAPI void APIENTRY glMinmaxEXT (GLenum, GLenum, GLboolean);
-GLAPI void APIENTRY glResetHistogramEXT (GLenum);
-GLAPI void APIENTRY glResetMinmaxEXT (GLenum);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLGETHISTOGRAMEXTPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLvoid *values);
-typedef void (APIENTRYP PFNGLGETHISTOGRAMPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETHISTOGRAMPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETMINMAXEXTPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLvoid *values);
-typedef void (APIENTRYP PFNGLGETMINMAXPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETMINMAXPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLHISTOGRAMEXTPROC) (GLenum target, GLsizei width, GLenum internalformat, GLboolean sink);
-typedef void (APIENTRYP PFNGLMINMAXEXTPROC) (GLenum target, GLenum internalformat, GLboolean sink);
-typedef void (APIENTRYP PFNGLRESETHISTOGRAMEXTPROC) (GLenum target);
-typedef void (APIENTRYP PFNGLRESETMINMAXEXTPROC) (GLenum target);
-#endif
-
-#ifndef GL_EXT_convolution
-#define GL_EXT_convolution 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glConvolutionFilter1DEXT (GLenum, GLenum, GLsizei, GLenum, GLenum, const GLvoid *);
-GLAPI void APIENTRY glConvolutionFilter2DEXT (GLenum, GLenum, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *);
-GLAPI void APIENTRY glConvolutionParameterfEXT (GLenum, GLenum, GLfloat);
-GLAPI void APIENTRY glConvolutionParameterfvEXT (GLenum, GLenum, const GLfloat *);
-GLAPI void APIENTRY glConvolutionParameteriEXT (GLenum, GLenum, GLint);
-GLAPI void APIENTRY glConvolutionParameterivEXT (GLenum, GLenum, const GLint *);
-GLAPI void APIENTRY glCopyConvolutionFilter1DEXT (GLenum, GLenum, GLint, GLint, GLsizei);
-GLAPI void APIENTRY glCopyConvolutionFilter2DEXT (GLenum, GLenum, GLint, GLint, GLsizei, GLsizei);
-GLAPI void APIENTRY glGetConvolutionFilterEXT (GLenum, GLenum, GLenum, GLvoid *);
-GLAPI void APIENTRY glGetConvolutionParameterfvEXT (GLenum, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetConvolutionParameterivEXT (GLenum, GLenum, GLint *);
-GLAPI void APIENTRY glGetSeparableFilterEXT (GLenum, GLenum, GLenum, GLvoid *, GLvoid *, GLvoid *);
-GLAPI void APIENTRY glSeparableFilter2DEXT (GLenum, GLenum, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *, const GLvoid *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLCONVOLUTIONFILTER1DEXTPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *image);
-typedef void (APIENTRYP PFNGLCONVOLUTIONFILTER2DEXTPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *image);
-typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERFEXTPROC) (GLenum target, GLenum pname, GLfloat params);
-typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERFVEXTPROC) (GLenum target, GLenum pname, const GLfloat *params);
-typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERIEXTPROC) (GLenum target, GLenum pname, GLint params);
-typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERIVEXTPROC) (GLenum target, GLenum pname, const GLint *params);
-typedef void (APIENTRYP PFNGLCOPYCONVOLUTIONFILTER1DEXTPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width);
-typedef void (APIENTRYP PFNGLCOPYCONVOLUTIONFILTER2DEXTPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height);
-typedef void (APIENTRYP PFNGLGETCONVOLUTIONFILTEREXTPROC) (GLenum target, GLenum format, GLenum type, GLvoid *image);
-typedef void (APIENTRYP PFNGLGETCONVOLUTIONPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETCONVOLUTIONPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETSEPARABLEFILTEREXTPROC) (GLenum target, GLenum format, GLenum type, GLvoid *row, GLvoid *column, GLvoid *span);
-typedef void (APIENTRYP PFNGLSEPARABLEFILTER2DEXTPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *row, const GLvoid *column);
-#endif
-
-#ifndef GL_EXT_color_matrix
-#define GL_EXT_color_matrix 1
-#endif
-
-#ifndef GL_SGI_color_table
-#define GL_SGI_color_table 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glColorTableSGI (GLenum, GLenum, GLsizei, GLenum, GLenum, const GLvoid *);
-GLAPI void APIENTRY glColorTableParameterfvSGI (GLenum, GLenum, const GLfloat *);
-GLAPI void APIENTRY glColorTableParameterivSGI (GLenum, GLenum, const GLint *);
-GLAPI void APIENTRY glCopyColorTableSGI (GLenum, GLenum, GLint, GLint, GLsizei);
-GLAPI void APIENTRY glGetColorTableSGI (GLenum, GLenum, GLenum, GLvoid *);
-GLAPI void APIENTRY glGetColorTableParameterfvSGI (GLenum, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetColorTableParameterivSGI (GLenum, GLenum, GLint *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLCOLORTABLESGIPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *table);
-typedef void (APIENTRYP PFNGLCOLORTABLEPARAMETERFVSGIPROC) (GLenum target, GLenum pname, const GLfloat *params);
-typedef void (APIENTRYP PFNGLCOLORTABLEPARAMETERIVSGIPROC) (GLenum target, GLenum pname, const GLint *params);
-typedef void (APIENTRYP PFNGLCOPYCOLORTABLESGIPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width);
-typedef void (APIENTRYP PFNGLGETCOLORTABLESGIPROC) (GLenum target, GLenum format, GLenum type, GLvoid *table);
-typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERFVSGIPROC) (GLenum target, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERIVSGIPROC) (GLenum target, GLenum pname, GLint *params);
-#endif
-
-#ifndef GL_SGIX_pixel_texture
-#define GL_SGIX_pixel_texture 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glPixelTexGenSGIX (GLenum);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLPIXELTEXGENSGIXPROC) (GLenum mode);
-#endif
-
-#ifndef GL_SGIS_pixel_texture
-#define GL_SGIS_pixel_texture 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glPixelTexGenParameteriSGIS (GLenum, GLint);
-GLAPI void APIENTRY glPixelTexGenParameterivSGIS (GLenum, const GLint *);
-GLAPI void APIENTRY glPixelTexGenParameterfSGIS (GLenum, GLfloat);
-GLAPI void APIENTRY glPixelTexGenParameterfvSGIS (GLenum, const GLfloat *);
-GLAPI void APIENTRY glGetPixelTexGenParameterivSGIS (GLenum, GLint *);
-GLAPI void APIENTRY glGetPixelTexGenParameterfvSGIS (GLenum, GLfloat *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLPIXELTEXGENPARAMETERISGISPROC) (GLenum pname, GLint param);
-typedef void (APIENTRYP PFNGLPIXELTEXGENPARAMETERIVSGISPROC) (GLenum pname, const GLint *params);
-typedef void (APIENTRYP PFNGLPIXELTEXGENPARAMETERFSGISPROC) (GLenum pname, GLfloat param);
-typedef void (APIENTRYP PFNGLPIXELTEXGENPARAMETERFVSGISPROC) (GLenum pname, const GLfloat *params);
-typedef void (APIENTRYP PFNGLGETPIXELTEXGENPARAMETERIVSGISPROC) (GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETPIXELTEXGENPARAMETERFVSGISPROC) (GLenum pname, GLfloat *params);
-#endif
-
-#ifndef GL_SGIS_texture4D
-#define GL_SGIS_texture4D 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glTexImage4DSGIS (GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *);
-GLAPI void APIENTRY glTexSubImage4DSGIS (GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLTEXIMAGE4DSGISPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLsizei size4d, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
-typedef void (APIENTRYP PFNGLTEXSUBIMAGE4DSGISPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint woffset, GLsizei width, GLsizei height, GLsizei depth, GLsizei size4d, GLenum format, GLenum type, const GLvoid *pixels);
-#endif
-
-#ifndef GL_SGI_texture_color_table
-#define GL_SGI_texture_color_table 1
-#endif
-
-#ifndef GL_EXT_cmyka
-#define GL_EXT_cmyka 1
-#endif
-
-#ifndef GL_EXT_texture_object
-#define GL_EXT_texture_object 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI GLboolean APIENTRY glAreTexturesResidentEXT (GLsizei, const GLuint *, GLboolean *);
-GLAPI void APIENTRY glBindTextureEXT (GLenum, GLuint);
-GLAPI void APIENTRY glDeleteTexturesEXT (GLsizei, const GLuint *);
-GLAPI void APIENTRY glGenTexturesEXT (GLsizei, GLuint *);
-GLAPI GLboolean APIENTRY glIsTextureEXT (GLuint);
-GLAPI void APIENTRY glPrioritizeTexturesEXT (GLsizei, const GLuint *, const GLclampf *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef GLboolean (APIENTRYP PFNGLARETEXTURESRESIDENTEXTPROC) (GLsizei n, const GLuint *textures, GLboolean *residences);
-typedef void (APIENTRYP PFNGLBINDTEXTUREEXTPROC) (GLenum target, GLuint texture);
-typedef void (APIENTRYP PFNGLDELETETEXTURESEXTPROC) (GLsizei n, const GLuint *textures);
-typedef void (APIENTRYP PFNGLGENTEXTURESEXTPROC) (GLsizei n, GLuint *textures);
-typedef GLboolean (APIENTRYP PFNGLISTEXTUREEXTPROC) (GLuint texture);
-typedef void (APIENTRYP PFNGLPRIORITIZETEXTURESEXTPROC) (GLsizei n, const GLuint *textures, const GLclampf *priorities);
-#endif
-
-#ifndef GL_SGIS_detail_texture
-#define GL_SGIS_detail_texture 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glDetailTexFuncSGIS (GLenum, GLsizei, const GLfloat *);
-GLAPI void APIENTRY glGetDetailTexFuncSGIS (GLenum, GLfloat *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLDETAILTEXFUNCSGISPROC) (GLenum target, GLsizei n, const GLfloat *points);
-typedef void (APIENTRYP PFNGLGETDETAILTEXFUNCSGISPROC) (GLenum target, GLfloat *points);
-#endif
-
-#ifndef GL_SGIS_sharpen_texture
-#define GL_SGIS_sharpen_texture 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glSharpenTexFuncSGIS (GLenum, GLsizei, const GLfloat *);
-GLAPI void APIENTRY glGetSharpenTexFuncSGIS (GLenum, GLfloat *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLSHARPENTEXFUNCSGISPROC) (GLenum target, GLsizei n, const GLfloat *points);
-typedef void (APIENTRYP PFNGLGETSHARPENTEXFUNCSGISPROC) (GLenum target, GLfloat *points);
-#endif
-
-#ifndef GL_EXT_packed_pixels
-#define GL_EXT_packed_pixels 1
-#endif
-
-#ifndef GL_SGIS_texture_lod
-#define GL_SGIS_texture_lod 1
-#endif
-
-#ifndef GL_SGIS_multisample
-#define GL_SGIS_multisample 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glSampleMaskSGIS (GLclampf, GLboolean);
-GLAPI void APIENTRY glSamplePatternSGIS (GLenum);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLSAMPLEMASKSGISPROC) (GLclampf value, GLboolean invert);
-typedef void (APIENTRYP PFNGLSAMPLEPATTERNSGISPROC) (GLenum pattern);
-#endif
-
-#ifndef GL_EXT_rescale_normal
-#define GL_EXT_rescale_normal 1
-#endif
-
-#ifndef GL_EXT_vertex_array
-#define GL_EXT_vertex_array 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glArrayElementEXT (GLint);
-GLAPI void APIENTRY glColorPointerEXT (GLint, GLenum, GLsizei, GLsizei, const GLvoid *);
-GLAPI void APIENTRY glDrawArraysEXT (GLenum, GLint, GLsizei);
-GLAPI void APIENTRY glEdgeFlagPointerEXT (GLsizei, GLsizei, const GLboolean *);
-GLAPI void APIENTRY glGetPointervEXT (GLenum, GLvoid* *);
-GLAPI void APIENTRY glIndexPointerEXT (GLenum, GLsizei, GLsizei, const GLvoid *);
-GLAPI void APIENTRY glNormalPointerEXT (GLenum, GLsizei, GLsizei, const GLvoid *);
-GLAPI void APIENTRY glTexCoordPointerEXT (GLint, GLenum, GLsizei, GLsizei, const GLvoid *);
-GLAPI void APIENTRY glVertexPointerEXT (GLint, GLenum, GLsizei, GLsizei, const GLvoid *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLARRAYELEMENTEXTPROC) (GLint i);
-typedef void (APIENTRYP PFNGLCOLORPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer);
-typedef void (APIENTRYP PFNGLDRAWARRAYSEXTPROC) (GLenum mode, GLint first, GLsizei count);
-typedef void (APIENTRYP PFNGLEDGEFLAGPOINTEREXTPROC) (GLsizei stride, GLsizei count, const GLboolean *pointer);
-typedef void (APIENTRYP PFNGLGETPOINTERVEXTPROC) (GLenum pname, GLvoid* *params);
-typedef void (APIENTRYP PFNGLINDEXPOINTEREXTPROC) (GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer);
-typedef void (APIENTRYP PFNGLNORMALPOINTEREXTPROC) (GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer);
-typedef void (APIENTRYP PFNGLTEXCOORDPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer);
-typedef void (APIENTRYP PFNGLVERTEXPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer);
-#endif
-
-#ifndef GL_EXT_misc_attribute
-#define GL_EXT_misc_attribute 1
-#endif
-
-#ifndef GL_SGIS_generate_mipmap
-#define GL_SGIS_generate_mipmap 1
-#endif
-
-#ifndef GL_SGIX_clipmap
-#define GL_SGIX_clipmap 1
-#endif
-
-#ifndef GL_SGIX_shadow
-#define GL_SGIX_shadow 1
-#endif
-
-#ifndef GL_SGIS_texture_edge_clamp
-#define GL_SGIS_texture_edge_clamp 1
-#endif
-
-#ifndef GL_SGIS_texture_border_clamp
-#define GL_SGIS_texture_border_clamp 1
-#endif
-
-#ifndef GL_EXT_blend_minmax
-#define GL_EXT_blend_minmax 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glBlendEquationEXT (GLenum);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLBLENDEQUATIONEXTPROC) (GLenum mode);
-#endif
-
-#ifndef GL_EXT_blend_subtract
-#define GL_EXT_blend_subtract 1
-#endif
-
-#ifndef GL_EXT_blend_logic_op
-#define GL_EXT_blend_logic_op 1
-#endif
-
-#ifndef GL_SGIX_interlace
-#define GL_SGIX_interlace 1
-#endif
-
-#ifndef GL_SGIX_pixel_tiles
-#define GL_SGIX_pixel_tiles 1
-#endif
-
-#ifndef GL_SGIX_texture_select
-#define GL_SGIX_texture_select 1
-#endif
-
-#ifndef GL_SGIX_sprite
-#define GL_SGIX_sprite 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glSpriteParameterfSGIX (GLenum, GLfloat);
-GLAPI void APIENTRY glSpriteParameterfvSGIX (GLenum, const GLfloat *);
-GLAPI void APIENTRY glSpriteParameteriSGIX (GLenum, GLint);
-GLAPI void APIENTRY glSpriteParameterivSGIX (GLenum, const GLint *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLSPRITEPARAMETERFSGIXPROC) (GLenum pname, GLfloat param);
-typedef void (APIENTRYP PFNGLSPRITEPARAMETERFVSGIXPROC) (GLenum pname, const GLfloat *params);
-typedef void (APIENTRYP PFNGLSPRITEPARAMETERISGIXPROC) (GLenum pname, GLint param);
-typedef void (APIENTRYP PFNGLSPRITEPARAMETERIVSGIXPROC) (GLenum pname, const GLint *params);
-#endif
-
-#ifndef GL_SGIX_texture_multi_buffer
-#define GL_SGIX_texture_multi_buffer 1
-#endif
-
-#ifndef GL_EXT_point_parameters
-#define GL_EXT_point_parameters 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glPointParameterfEXT (GLenum, GLfloat);
-GLAPI void APIENTRY glPointParameterfvEXT (GLenum, const GLfloat *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLPOINTPARAMETERFEXTPROC) (GLenum pname, GLfloat param);
-typedef void (APIENTRYP PFNGLPOINTPARAMETERFVEXTPROC) (GLenum pname, const GLfloat *params);
-#endif
-
-#ifndef GL_SGIS_point_parameters
-#define GL_SGIS_point_parameters 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glPointParameterfSGIS (GLenum, GLfloat);
-GLAPI void APIENTRY glPointParameterfvSGIS (GLenum, const GLfloat *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLPOINTPARAMETERFSGISPROC) (GLenum pname, GLfloat param);
-typedef void (APIENTRYP PFNGLPOINTPARAMETERFVSGISPROC) (GLenum pname, const GLfloat *params);
-#endif
-
-#ifndef GL_SGIX_instruments
-#define GL_SGIX_instruments 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI GLint APIENTRY glGetInstrumentsSGIX (void);
-GLAPI void APIENTRY glInstrumentsBufferSGIX (GLsizei, GLint *);
-GLAPI GLint APIENTRY glPollInstrumentsSGIX (GLint *);
-GLAPI void APIENTRY glReadInstrumentsSGIX (GLint);
-GLAPI void APIENTRY glStartInstrumentsSGIX (void);
-GLAPI void APIENTRY glStopInstrumentsSGIX (GLint);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef GLint (APIENTRYP PFNGLGETINSTRUMENTSSGIXPROC) (void);
-typedef void (APIENTRYP PFNGLINSTRUMENTSBUFFERSGIXPROC) (GLsizei size, GLint *buffer);
-typedef GLint (APIENTRYP PFNGLPOLLINSTRUMENTSSGIXPROC) (GLint *marker_p);
-typedef void (APIENTRYP PFNGLREADINSTRUMENTSSGIXPROC) (GLint marker);
-typedef void (APIENTRYP PFNGLSTARTINSTRUMENTSSGIXPROC) (void);
-typedef void (APIENTRYP PFNGLSTOPINSTRUMENTSSGIXPROC) (GLint marker);
-#endif
-
-#ifndef GL_SGIX_texture_scale_bias
-#define GL_SGIX_texture_scale_bias 1
-#endif
-
-#ifndef GL_SGIX_framezoom
-#define GL_SGIX_framezoom 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glFrameZoomSGIX (GLint);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLFRAMEZOOMSGIXPROC) (GLint factor);
-#endif
-
-#ifndef GL_SGIX_tag_sample_buffer
-#define GL_SGIX_tag_sample_buffer 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glTagSampleBufferSGIX (void);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLTAGSAMPLEBUFFERSGIXPROC) (void);
-#endif
-
-#ifndef GL_SGIX_polynomial_ffd
-#define GL_SGIX_polynomial_ffd 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glDeformationMap3dSGIX (GLenum, GLdouble, GLdouble, GLint, GLint, GLdouble, GLdouble, GLint, GLint, GLdouble, GLdouble, GLint, GLint, const GLdouble *);
-GLAPI void APIENTRY glDeformationMap3fSGIX (GLenum, GLfloat, GLfloat, GLint, GLint, GLfloat, GLfloat, GLint, GLint, GLfloat, GLfloat, GLint, GLint, const GLfloat *);
-GLAPI void APIENTRY glDeformSGIX (GLbitfield);
-GLAPI void APIENTRY glLoadIdentityDeformationMapSGIX (GLbitfield);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLDEFORMATIONMAP3DSGIXPROC) (GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, GLdouble w1, GLdouble w2, GLint wstride, GLint worder, const GLdouble *points);
-typedef void (APIENTRYP PFNGLDEFORMATIONMAP3FSGIXPROC) (GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, GLfloat w1, GLfloat w2, GLint wstride, GLint worder, const GLfloat *points);
-typedef void (APIENTRYP PFNGLDEFORMSGIXPROC) (GLbitfield mask);
-typedef void (APIENTRYP PFNGLLOADIDENTITYDEFORMATIONMAPSGIXPROC) (GLbitfield mask);
-#endif
-
-#ifndef GL_SGIX_reference_plane
-#define GL_SGIX_reference_plane 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glReferencePlaneSGIX (const GLdouble *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLREFERENCEPLANESGIXPROC) (const GLdouble *equation);
-#endif
-
-#ifndef GL_SGIX_flush_raster
-#define GL_SGIX_flush_raster 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glFlushRasterSGIX (void);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLFLUSHRASTERSGIXPROC) (void);
-#endif
-
-#ifndef GL_SGIX_depth_texture
-#define GL_SGIX_depth_texture 1
-#endif
-
-#ifndef GL_SGIS_fog_function
-#define GL_SGIS_fog_function 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glFogFuncSGIS (GLsizei, const GLfloat *);
-GLAPI void APIENTRY glGetFogFuncSGIS (GLfloat *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLFOGFUNCSGISPROC) (GLsizei n, const GLfloat *points);
-typedef void (APIENTRYP PFNGLGETFOGFUNCSGISPROC) (GLfloat *points);
-#endif
-
-#ifndef GL_SGIX_fog_offset
-#define GL_SGIX_fog_offset 1
-#endif
-
-#ifndef GL_HP_image_transform
-#define GL_HP_image_transform 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glImageTransformParameteriHP (GLenum, GLenum, GLint);
-GLAPI void APIENTRY glImageTransformParameterfHP (GLenum, GLenum, GLfloat);
-GLAPI void APIENTRY glImageTransformParameterivHP (GLenum, GLenum, const GLint *);
-GLAPI void APIENTRY glImageTransformParameterfvHP (GLenum, GLenum, const GLfloat *);
-GLAPI void APIENTRY glGetImageTransformParameterivHP (GLenum, GLenum, GLint *);
-GLAPI void APIENTRY glGetImageTransformParameterfvHP (GLenum, GLenum, GLfloat *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLIMAGETRANSFORMPARAMETERIHPPROC) (GLenum target, GLenum pname, GLint param);
-typedef void (APIENTRYP PFNGLIMAGETRANSFORMPARAMETERFHPPROC) (GLenum target, GLenum pname, GLfloat param);
-typedef void (APIENTRYP PFNGLIMAGETRANSFORMPARAMETERIVHPPROC) (GLenum target, GLenum pname, const GLint *params);
-typedef void (APIENTRYP PFNGLIMAGETRANSFORMPARAMETERFVHPPROC) (GLenum target, GLenum pname, const GLfloat *params);
-typedef void (APIENTRYP PFNGLGETIMAGETRANSFORMPARAMETERIVHPPROC) (GLenum target, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETIMAGETRANSFORMPARAMETERFVHPPROC) (GLenum target, GLenum pname, GLfloat *params);
-#endif
-
-#ifndef GL_HP_convolution_border_modes
-#define GL_HP_convolution_border_modes 1
-#endif
-
-#ifndef GL_SGIX_texture_add_env
-#define GL_SGIX_texture_add_env 1
-#endif
-
-#ifndef GL_EXT_color_subtable
-#define GL_EXT_color_subtable 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glColorSubTableEXT (GLenum, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *);
-GLAPI void APIENTRY glCopyColorSubTableEXT (GLenum, GLsizei, GLint, GLint, GLsizei);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLCOLORSUBTABLEEXTPROC) (GLenum target, GLsizei start, GLsizei count, GLenum format, GLenum type, const GLvoid *data);
-typedef void (APIENTRYP PFNGLCOPYCOLORSUBTABLEEXTPROC) (GLenum target, GLsizei start, GLint x, GLint y, GLsizei width);
-#endif
-
-#ifndef GL_PGI_vertex_hints
-#define GL_PGI_vertex_hints 1
-#endif
-
-#ifndef GL_PGI_misc_hints
-#define GL_PGI_misc_hints 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glHintPGI (GLenum, GLint);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLHINTPGIPROC) (GLenum target, GLint mode);
-#endif
-
-#ifndef GL_EXT_paletted_texture
-#define GL_EXT_paletted_texture 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glColorTableEXT (GLenum, GLenum, GLsizei, GLenum, GLenum, const GLvoid *);
-GLAPI void APIENTRY glGetColorTableEXT (GLenum, GLenum, GLenum, GLvoid *);
-GLAPI void APIENTRY glGetColorTableParameterivEXT (GLenum, GLenum, GLint *);
-GLAPI void APIENTRY glGetColorTableParameterfvEXT (GLenum, GLenum, GLfloat *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLCOLORTABLEEXTPROC) (GLenum target, GLenum internalFormat, GLsizei width, GLenum format, GLenum type, const GLvoid *table);
-typedef void (APIENTRYP PFNGLGETCOLORTABLEEXTPROC) (GLenum target, GLenum format, GLenum type, GLvoid *data);
-typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params);
-#endif
-
-#ifndef GL_EXT_clip_volume_hint
-#define GL_EXT_clip_volume_hint 1
-#endif
-
-#ifndef GL_SGIX_list_priority
-#define GL_SGIX_list_priority 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glGetListParameterfvSGIX (GLuint, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetListParameterivSGIX (GLuint, GLenum, GLint *);
-GLAPI void APIENTRY glListParameterfSGIX (GLuint, GLenum, GLfloat);
-GLAPI void APIENTRY glListParameterfvSGIX (GLuint, GLenum, const GLfloat *);
-GLAPI void APIENTRY glListParameteriSGIX (GLuint, GLenum, GLint);
-GLAPI void APIENTRY glListParameterivSGIX (GLuint, GLenum, const GLint *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLGETLISTPARAMETERFVSGIXPROC) (GLuint list, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETLISTPARAMETERIVSGIXPROC) (GLuint list, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLLISTPARAMETERFSGIXPROC) (GLuint list, GLenum pname, GLfloat param);
-typedef void (APIENTRYP PFNGLLISTPARAMETERFVSGIXPROC) (GLuint list, GLenum pname, const GLfloat *params);
-typedef void (APIENTRYP PFNGLLISTPARAMETERISGIXPROC) (GLuint list, GLenum pname, GLint param);
-typedef void (APIENTRYP PFNGLLISTPARAMETERIVSGIXPROC) (GLuint list, GLenum pname, const GLint *params);
-#endif
-
-#ifndef GL_SGIX_ir_instrument1
-#define GL_SGIX_ir_instrument1 1
-#endif
-
-#ifndef GL_SGIX_calligraphic_fragment
-#define GL_SGIX_calligraphic_fragment 1
-#endif
-
-#ifndef GL_SGIX_texture_lod_bias
-#define GL_SGIX_texture_lod_bias 1
-#endif
-
-#ifndef GL_SGIX_shadow_ambient
-#define GL_SGIX_shadow_ambient 1
-#endif
-
-#ifndef GL_EXT_index_texture
-#define GL_EXT_index_texture 1
-#endif
-
-#ifndef GL_EXT_index_material
-#define GL_EXT_index_material 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glIndexMaterialEXT (GLenum, GLenum);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLINDEXMATERIALEXTPROC) (GLenum face, GLenum mode);
-#endif
-
-#ifndef GL_EXT_index_func
-#define GL_EXT_index_func 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glIndexFuncEXT (GLenum, GLclampf);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLINDEXFUNCEXTPROC) (GLenum func, GLclampf ref);
-#endif
-
-#ifndef GL_EXT_index_array_formats
-#define GL_EXT_index_array_formats 1
-#endif
-
-#ifndef GL_EXT_compiled_vertex_array
-#define GL_EXT_compiled_vertex_array 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glLockArraysEXT (GLint, GLsizei);
-GLAPI void APIENTRY glUnlockArraysEXT (void);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLLOCKARRAYSEXTPROC) (GLint first, GLsizei count);
-typedef void (APIENTRYP PFNGLUNLOCKARRAYSEXTPROC) (void);
-#endif
-
-#ifndef GL_EXT_cull_vertex
-#define GL_EXT_cull_vertex 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glCullParameterdvEXT (GLenum, GLdouble *);
-GLAPI void APIENTRY glCullParameterfvEXT (GLenum, GLfloat *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLCULLPARAMETERDVEXTPROC) (GLenum pname, GLdouble *params);
-typedef void (APIENTRYP PFNGLCULLPARAMETERFVEXTPROC) (GLenum pname, GLfloat *params);
-#endif
-
-#ifndef GL_SGIX_ycrcb
-#define GL_SGIX_ycrcb 1
-#endif
-
-#ifndef GL_SGIX_fragment_lighting
-#define GL_SGIX_fragment_lighting 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glFragmentColorMaterialSGIX (GLenum, GLenum);
-GLAPI void APIENTRY glFragmentLightfSGIX (GLenum, GLenum, GLfloat);
-GLAPI void APIENTRY glFragmentLightfvSGIX (GLenum, GLenum, const GLfloat *);
-GLAPI void APIENTRY glFragmentLightiSGIX (GLenum, GLenum, GLint);
-GLAPI void APIENTRY glFragmentLightivSGIX (GLenum, GLenum, const GLint *);
-GLAPI void APIENTRY glFragmentLightModelfSGIX (GLenum, GLfloat);
-GLAPI void APIENTRY glFragmentLightModelfvSGIX (GLenum, const GLfloat *);
-GLAPI void APIENTRY glFragmentLightModeliSGIX (GLenum, GLint);
-GLAPI void APIENTRY glFragmentLightModelivSGIX (GLenum, const GLint *);
-GLAPI void APIENTRY glFragmentMaterialfSGIX (GLenum, GLenum, GLfloat);
-GLAPI void APIENTRY glFragmentMaterialfvSGIX (GLenum, GLenum, const GLfloat *);
-GLAPI void APIENTRY glFragmentMaterialiSGIX (GLenum, GLenum, GLint);
-GLAPI void APIENTRY glFragmentMaterialivSGIX (GLenum, GLenum, const GLint *);
-GLAPI void APIENTRY glGetFragmentLightfvSGIX (GLenum, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetFragmentLightivSGIX (GLenum, GLenum, GLint *);
-GLAPI void APIENTRY glGetFragmentMaterialfvSGIX (GLenum, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetFragmentMaterialivSGIX (GLenum, GLenum, GLint *);
-GLAPI void APIENTRY glLightEnviSGIX (GLenum, GLint);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLFRAGMENTCOLORMATERIALSGIXPROC) (GLenum face, GLenum mode);
-typedef void (APIENTRYP PFNGLFRAGMENTLIGHTFSGIXPROC) (GLenum light, GLenum pname, GLfloat param);
-typedef void (APIENTRYP PFNGLFRAGMENTLIGHTFVSGIXPROC) (GLenum light, GLenum pname, const GLfloat *params);
-typedef void (APIENTRYP PFNGLFRAGMENTLIGHTISGIXPROC) (GLenum light, GLenum pname, GLint param);
-typedef void (APIENTRYP PFNGLFRAGMENTLIGHTIVSGIXPROC) (GLenum light, GLenum pname, const GLint *params);
-typedef void (APIENTRYP PFNGLFRAGMENTLIGHTMODELFSGIXPROC) (GLenum pname, GLfloat param);
-typedef void (APIENTRYP PFNGLFRAGMENTLIGHTMODELFVSGIXPROC) (GLenum pname, const GLfloat *params);
-typedef void (APIENTRYP PFNGLFRAGMENTLIGHTMODELISGIXPROC) (GLenum pname, GLint param);
-typedef void (APIENTRYP PFNGLFRAGMENTLIGHTMODELIVSGIXPROC) (GLenum pname, const GLint *params);
-typedef void (APIENTRYP PFNGLFRAGMENTMATERIALFSGIXPROC) (GLenum face, GLenum pname, GLfloat param);
-typedef void (APIENTRYP PFNGLFRAGMENTMATERIALFVSGIXPROC) (GLenum face, GLenum pname, const GLfloat *params);
-typedef void (APIENTRYP PFNGLFRAGMENTMATERIALISGIXPROC) (GLenum face, GLenum pname, GLint param);
-typedef void (APIENTRYP PFNGLFRAGMENTMATERIALIVSGIXPROC) (GLenum face, GLenum pname, const GLint *params);
-typedef void (APIENTRYP PFNGLGETFRAGMENTLIGHTFVSGIXPROC) (GLenum light, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETFRAGMENTLIGHTIVSGIXPROC) (GLenum light, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETFRAGMENTMATERIALFVSGIXPROC) (GLenum face, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETFRAGMENTMATERIALIVSGIXPROC) (GLenum face, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLLIGHTENVISGIXPROC) (GLenum pname, GLint param);
-#endif
-
-#ifndef GL_IBM_rasterpos_clip
-#define GL_IBM_rasterpos_clip 1
-#endif
-
-#ifndef GL_HP_texture_lighting
-#define GL_HP_texture_lighting 1
-#endif
-
-#ifndef GL_EXT_draw_range_elements
-#define GL_EXT_draw_range_elements 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glDrawRangeElementsEXT (GLenum, GLuint, GLuint, GLsizei, GLenum, const GLvoid *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTSEXTPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid *indices);
-#endif
-
-#ifndef GL_WIN_phong_shading
-#define GL_WIN_phong_shading 1
-#endif
-
-#ifndef GL_WIN_specular_fog
-#define GL_WIN_specular_fog 1
-#endif
-
-#ifndef GL_EXT_light_texture
-#define GL_EXT_light_texture 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glApplyTextureEXT (GLenum);
-GLAPI void APIENTRY glTextureLightEXT (GLenum);
-GLAPI void APIENTRY glTextureMaterialEXT (GLenum, GLenum);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLAPPLYTEXTUREEXTPROC) (GLenum mode);
-typedef void (APIENTRYP PFNGLTEXTURELIGHTEXTPROC) (GLenum pname);
-typedef void (APIENTRYP PFNGLTEXTUREMATERIALEXTPROC) (GLenum face, GLenum mode);
-#endif
-
-#ifndef GL_SGIX_blend_alpha_minmax
-#define GL_SGIX_blend_alpha_minmax 1
-#endif
-
-#ifndef GL_EXT_bgra
-#define GL_EXT_bgra 1
-#endif
-
-#ifndef GL_SGIX_async
-#define GL_SGIX_async 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glAsyncMarkerSGIX (GLuint);
-GLAPI GLint APIENTRY glFinishAsyncSGIX (GLuint *);
-GLAPI GLint APIENTRY glPollAsyncSGIX (GLuint *);
-GLAPI GLuint APIENTRY glGenAsyncMarkersSGIX (GLsizei);
-GLAPI void APIENTRY glDeleteAsyncMarkersSGIX (GLuint, GLsizei);
-GLAPI GLboolean APIENTRY glIsAsyncMarkerSGIX (GLuint);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLASYNCMARKERSGIXPROC) (GLuint marker);
-typedef GLint (APIENTRYP PFNGLFINISHASYNCSGIXPROC) (GLuint *markerp);
-typedef GLint (APIENTRYP PFNGLPOLLASYNCSGIXPROC) (GLuint *markerp);
-typedef GLuint (APIENTRYP PFNGLGENASYNCMARKERSSGIXPROC) (GLsizei range);
-typedef void (APIENTRYP PFNGLDELETEASYNCMARKERSSGIXPROC) (GLuint marker, GLsizei range);
-typedef GLboolean (APIENTRYP PFNGLISASYNCMARKERSGIXPROC) (GLuint marker);
-#endif
-
-#ifndef GL_SGIX_async_pixel
-#define GL_SGIX_async_pixel 1
-#endif
-
-#ifndef GL_SGIX_async_histogram
-#define GL_SGIX_async_histogram 1
-#endif
-
-#ifndef GL_INTEL_parallel_arrays
-#define GL_INTEL_parallel_arrays 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glVertexPointervINTEL (GLint, GLenum, const GLvoid* *);
-GLAPI void APIENTRY glNormalPointervINTEL (GLenum, const GLvoid* *);
-GLAPI void APIENTRY glColorPointervINTEL (GLint, GLenum, const GLvoid* *);
-GLAPI void APIENTRY glTexCoordPointervINTEL (GLint, GLenum, const GLvoid* *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLVERTEXPOINTERVINTELPROC) (GLint size, GLenum type, const GLvoid* *pointer);
-typedef void (APIENTRYP PFNGLNORMALPOINTERVINTELPROC) (GLenum type, const GLvoid* *pointer);
-typedef void (APIENTRYP PFNGLCOLORPOINTERVINTELPROC) (GLint size, GLenum type, const GLvoid* *pointer);
-typedef void (APIENTRYP PFNGLTEXCOORDPOINTERVINTELPROC) (GLint size, GLenum type, const GLvoid* *pointer);
-#endif
-
-#ifndef GL_HP_occlusion_test
-#define GL_HP_occlusion_test 1
-#endif
-
-#ifndef GL_EXT_pixel_transform
-#define GL_EXT_pixel_transform 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glPixelTransformParameteriEXT (GLenum, GLenum, GLint);
-GLAPI void APIENTRY glPixelTransformParameterfEXT (GLenum, GLenum, GLfloat);
-GLAPI void APIENTRY glPixelTransformParameterivEXT (GLenum, GLenum, const GLint *);
-GLAPI void APIENTRY glPixelTransformParameterfvEXT (GLenum, GLenum, const GLfloat *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLPIXELTRANSFORMPARAMETERIEXTPROC) (GLenum target, GLenum pname, GLint param);
-typedef void (APIENTRYP PFNGLPIXELTRANSFORMPARAMETERFEXTPROC) (GLenum target, GLenum pname, GLfloat param);
-typedef void (APIENTRYP PFNGLPIXELTRANSFORMPARAMETERIVEXTPROC) (GLenum target, GLenum pname, const GLint *params);
-typedef void (APIENTRYP PFNGLPIXELTRANSFORMPARAMETERFVEXTPROC) (GLenum target, GLenum pname, const GLfloat *params);
-#endif
-
-#ifndef GL_EXT_pixel_transform_color_table
-#define GL_EXT_pixel_transform_color_table 1
-#endif
-
-#ifndef GL_EXT_shared_texture_palette
-#define GL_EXT_shared_texture_palette 1
-#endif
-
-#ifndef GL_EXT_separate_specular_color
-#define GL_EXT_separate_specular_color 1
-#endif
-
-#ifndef GL_EXT_secondary_color
-#define GL_EXT_secondary_color 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glSecondaryColor3bEXT (GLbyte, GLbyte, GLbyte);
-GLAPI void APIENTRY glSecondaryColor3bvEXT (const GLbyte *);
-GLAPI void APIENTRY glSecondaryColor3dEXT (GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glSecondaryColor3dvEXT (const GLdouble *);
-GLAPI void APIENTRY glSecondaryColor3fEXT (GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glSecondaryColor3fvEXT (const GLfloat *);
-GLAPI void APIENTRY glSecondaryColor3iEXT (GLint, GLint, GLint);
-GLAPI void APIENTRY glSecondaryColor3ivEXT (const GLint *);
-GLAPI void APIENTRY glSecondaryColor3sEXT (GLshort, GLshort, GLshort);
-GLAPI void APIENTRY glSecondaryColor3svEXT (const GLshort *);
-GLAPI void APIENTRY glSecondaryColor3ubEXT (GLubyte, GLubyte, GLubyte);
-GLAPI void APIENTRY glSecondaryColor3ubvEXT (const GLubyte *);
-GLAPI void APIENTRY glSecondaryColor3uiEXT (GLuint, GLuint, GLuint);
-GLAPI void APIENTRY glSecondaryColor3uivEXT (const GLuint *);
-GLAPI void APIENTRY glSecondaryColor3usEXT (GLushort, GLushort, GLushort);
-GLAPI void APIENTRY glSecondaryColor3usvEXT (const GLushort *);
-GLAPI void APIENTRY glSecondaryColorPointerEXT (GLint, GLenum, GLsizei, const GLvoid *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BEXTPROC) (GLbyte red, GLbyte green, GLbyte blue);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BVEXTPROC) (const GLbyte *v);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DEXTPROC) (GLdouble red, GLdouble green, GLdouble blue);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DVEXTPROC) (const GLdouble *v);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FEXTPROC) (GLfloat red, GLfloat green, GLfloat blue);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FVEXTPROC) (const GLfloat *v);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IEXTPROC) (GLint red, GLint green, GLint blue);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IVEXTPROC) (const GLint *v);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SEXTPROC) (GLshort red, GLshort green, GLshort blue);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SVEXTPROC) (const GLshort *v);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBEXTPROC) (GLubyte red, GLubyte green, GLubyte blue);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBVEXTPROC) (const GLubyte *v);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIEXTPROC) (GLuint red, GLuint green, GLuint blue);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIVEXTPROC) (const GLuint *v);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USEXTPROC) (GLushort red, GLushort green, GLushort blue);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USVEXTPROC) (const GLushort *v);
-typedef void (APIENTRYP PFNGLSECONDARYCOLORPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
-#endif
-
-#ifndef GL_EXT_texture_perturb_normal
-#define GL_EXT_texture_perturb_normal 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glTextureNormalEXT (GLenum);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLTEXTURENORMALEXTPROC) (GLenum mode);
-#endif
-
-#ifndef GL_EXT_multi_draw_arrays
-#define GL_EXT_multi_draw_arrays 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glMultiDrawArraysEXT (GLenum, GLint *, GLsizei *, GLsizei);
-GLAPI void APIENTRY glMultiDrawElementsEXT (GLenum, const GLsizei *, GLenum, const GLvoid* *, GLsizei);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSEXTPROC) (GLenum mode, GLint *first, GLsizei *count, GLsizei primcount);
-typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSEXTPROC) (GLenum mode, const GLsizei *count, GLenum type, const GLvoid* *indices, GLsizei primcount);
-#endif
-
-#ifndef GL_EXT_fog_coord
-#define GL_EXT_fog_coord 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glFogCoordfEXT (GLfloat);
-GLAPI void APIENTRY glFogCoordfvEXT (const GLfloat *);
-GLAPI void APIENTRY glFogCoorddEXT (GLdouble);
-GLAPI void APIENTRY glFogCoorddvEXT (const GLdouble *);
-GLAPI void APIENTRY glFogCoordPointerEXT (GLenum, GLsizei, const GLvoid *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLFOGCOORDFEXTPROC) (GLfloat coord);
-typedef void (APIENTRYP PFNGLFOGCOORDFVEXTPROC) (const GLfloat *coord);
-typedef void (APIENTRYP PFNGLFOGCOORDDEXTPROC) (GLdouble coord);
-typedef void (APIENTRYP PFNGLFOGCOORDDVEXTPROC) (const GLdouble *coord);
-typedef void (APIENTRYP PFNGLFOGCOORDPOINTEREXTPROC) (GLenum type, GLsizei stride, const GLvoid *pointer);
-#endif
-
-#ifndef GL_REND_screen_coordinates
-#define GL_REND_screen_coordinates 1
-#endif
-
-#ifndef GL_EXT_coordinate_frame
-#define GL_EXT_coordinate_frame 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glTangent3bEXT (GLbyte, GLbyte, GLbyte);
-GLAPI void APIENTRY glTangent3bvEXT (const GLbyte *);
-GLAPI void APIENTRY glTangent3dEXT (GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glTangent3dvEXT (const GLdouble *);
-GLAPI void APIENTRY glTangent3fEXT (GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glTangent3fvEXT (const GLfloat *);
-GLAPI void APIENTRY glTangent3iEXT (GLint, GLint, GLint);
-GLAPI void APIENTRY glTangent3ivEXT (const GLint *);
-GLAPI void APIENTRY glTangent3sEXT (GLshort, GLshort, GLshort);
-GLAPI void APIENTRY glTangent3svEXT (const GLshort *);
-GLAPI void APIENTRY glBinormal3bEXT (GLbyte, GLbyte, GLbyte);
-GLAPI void APIENTRY glBinormal3bvEXT (const GLbyte *);
-GLAPI void APIENTRY glBinormal3dEXT (GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glBinormal3dvEXT (const GLdouble *);
-GLAPI void APIENTRY glBinormal3fEXT (GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glBinormal3fvEXT (const GLfloat *);
-GLAPI void APIENTRY glBinormal3iEXT (GLint, GLint, GLint);
-GLAPI void APIENTRY glBinormal3ivEXT (const GLint *);
-GLAPI void APIENTRY glBinormal3sEXT (GLshort, GLshort, GLshort);
-GLAPI void APIENTRY glBinormal3svEXT (const GLshort *);
-GLAPI void APIENTRY glTangentPointerEXT (GLenum, GLsizei, const GLvoid *);
-GLAPI void APIENTRY glBinormalPointerEXT (GLenum, GLsizei, const GLvoid *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLTANGENT3BEXTPROC) (GLbyte tx, GLbyte ty, GLbyte tz);
-typedef void (APIENTRYP PFNGLTANGENT3BVEXTPROC) (const GLbyte *v);
-typedef void (APIENTRYP PFNGLTANGENT3DEXTPROC) (GLdouble tx, GLdouble ty, GLdouble tz);
-typedef void (APIENTRYP PFNGLTANGENT3DVEXTPROC) (const GLdouble *v);
-typedef void (APIENTRYP PFNGLTANGENT3FEXTPROC) (GLfloat tx, GLfloat ty, GLfloat tz);
-typedef void (APIENTRYP PFNGLTANGENT3FVEXTPROC) (const GLfloat *v);
-typedef void (APIENTRYP PFNGLTANGENT3IEXTPROC) (GLint tx, GLint ty, GLint tz);
-typedef void (APIENTRYP PFNGLTANGENT3IVEXTPROC) (const GLint *v);
-typedef void (APIENTRYP PFNGLTANGENT3SEXTPROC) (GLshort tx, GLshort ty, GLshort tz);
-typedef void (APIENTRYP PFNGLTANGENT3SVEXTPROC) (const GLshort *v);
-typedef void (APIENTRYP PFNGLBINORMAL3BEXTPROC) (GLbyte bx, GLbyte by, GLbyte bz);
-typedef void (APIENTRYP PFNGLBINORMAL3BVEXTPROC) (const GLbyte *v);
-typedef void (APIENTRYP PFNGLBINORMAL3DEXTPROC) (GLdouble bx, GLdouble by, GLdouble bz);
-typedef void (APIENTRYP PFNGLBINORMAL3DVEXTPROC) (const GLdouble *v);
-typedef void (APIENTRYP PFNGLBINORMAL3FEXTPROC) (GLfloat bx, GLfloat by, GLfloat bz);
-typedef void (APIENTRYP PFNGLBINORMAL3FVEXTPROC) (const GLfloat *v);
-typedef void (APIENTRYP PFNGLBINORMAL3IEXTPROC) (GLint bx, GLint by, GLint bz);
-typedef void (APIENTRYP PFNGLBINORMAL3IVEXTPROC) (const GLint *v);
-typedef void (APIENTRYP PFNGLBINORMAL3SEXTPROC) (GLshort bx, GLshort by, GLshort bz);
-typedef void (APIENTRYP PFNGLBINORMAL3SVEXTPROC) (const GLshort *v);
-typedef void (APIENTRYP PFNGLTANGENTPOINTEREXTPROC) (GLenum type, GLsizei stride, const GLvoid *pointer);
-typedef void (APIENTRYP PFNGLBINORMALPOINTEREXTPROC) (GLenum type, GLsizei stride, const GLvoid *pointer);
-#endif
-
-#ifndef GL_EXT_texture_env_combine
-#define GL_EXT_texture_env_combine 1
-#endif
-
-#ifndef GL_APPLE_specular_vector
-#define GL_APPLE_specular_vector 1
-#endif
-
-#ifndef GL_APPLE_transform_hint
-#define GL_APPLE_transform_hint 1
-#endif
-
-#ifndef GL_SGIX_fog_scale
-#define GL_SGIX_fog_scale 1
-#endif
-
-#ifndef GL_SUNX_constant_data
-#define GL_SUNX_constant_data 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glFinishTextureSUNX (void);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLFINISHTEXTURESUNXPROC) (void);
-#endif
-
-#ifndef GL_SUN_global_alpha
-#define GL_SUN_global_alpha 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glGlobalAlphaFactorbSUN (GLbyte);
-GLAPI void APIENTRY glGlobalAlphaFactorsSUN (GLshort);
-GLAPI void APIENTRY glGlobalAlphaFactoriSUN (GLint);
-GLAPI void APIENTRY glGlobalAlphaFactorfSUN (GLfloat);
-GLAPI void APIENTRY glGlobalAlphaFactordSUN (GLdouble);
-GLAPI void APIENTRY glGlobalAlphaFactorubSUN (GLubyte);
-GLAPI void APIENTRY glGlobalAlphaFactorusSUN (GLushort);
-GLAPI void APIENTRY glGlobalAlphaFactoruiSUN (GLuint);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORBSUNPROC) (GLbyte factor);
-typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORSSUNPROC) (GLshort factor);
-typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORISUNPROC) (GLint factor);
-typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORFSUNPROC) (GLfloat factor);
-typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORDSUNPROC) (GLdouble factor);
-typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORUBSUNPROC) (GLubyte factor);
-typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORUSSUNPROC) (GLushort factor);
-typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORUISUNPROC) (GLuint factor);
-#endif
-
-#ifndef GL_SUN_triangle_list
-#define GL_SUN_triangle_list 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glReplacementCodeuiSUN (GLuint);
-GLAPI void APIENTRY glReplacementCodeusSUN (GLushort);
-GLAPI void APIENTRY glReplacementCodeubSUN (GLubyte);
-GLAPI void APIENTRY glReplacementCodeuivSUN (const GLuint *);
-GLAPI void APIENTRY glReplacementCodeusvSUN (const GLushort *);
-GLAPI void APIENTRY glReplacementCodeubvSUN (const GLubyte *);
-GLAPI void APIENTRY glReplacementCodePointerSUN (GLenum, GLsizei, const GLvoid* *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLREPLACEMENTCODEUISUNPROC) (GLuint code);
-typedef void (APIENTRYP PFNGLREPLACEMENTCODEUSSUNPROC) (GLushort code);
-typedef void (APIENTRYP PFNGLREPLACEMENTCODEUBSUNPROC) (GLubyte code);
-typedef void (APIENTRYP PFNGLREPLACEMENTCODEUIVSUNPROC) (const GLuint *code);
-typedef void (APIENTRYP PFNGLREPLACEMENTCODEUSVSUNPROC) (const GLushort *code);
-typedef void (APIENTRYP PFNGLREPLACEMENTCODEUBVSUNPROC) (const GLubyte *code);
-typedef void (APIENTRYP PFNGLREPLACEMENTCODEPOINTERSUNPROC) (GLenum type, GLsizei stride, const GLvoid* *pointer);
-#endif
-
-#ifndef GL_SUN_vertex
-#define GL_SUN_vertex 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glColor4ubVertex2fSUN (GLubyte, GLubyte, GLubyte, GLubyte, GLfloat, GLfloat);
-GLAPI void APIENTRY glColor4ubVertex2fvSUN (const GLubyte *, const GLfloat *);
-GLAPI void APIENTRY glColor4ubVertex3fSUN (GLubyte, GLubyte, GLubyte, GLubyte, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glColor4ubVertex3fvSUN (const GLubyte *, const GLfloat *);
-GLAPI void APIENTRY glColor3fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glColor3fVertex3fvSUN (const GLfloat *, const GLfloat *);
-GLAPI void APIENTRY glNormal3fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glNormal3fVertex3fvSUN (const GLfloat *, const GLfloat *);
-GLAPI void APIENTRY glColor4fNormal3fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glColor4fNormal3fVertex3fvSUN (const GLfloat *, const GLfloat *, const GLfloat *);
-GLAPI void APIENTRY glTexCoord2fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glTexCoord2fVertex3fvSUN (const GLfloat *, const GLfloat *);
-GLAPI void APIENTRY glTexCoord4fVertex4fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glTexCoord4fVertex4fvSUN (const GLfloat *, const GLfloat *);
-GLAPI void APIENTRY glTexCoord2fColor4ubVertex3fSUN (GLfloat, GLfloat, GLubyte, GLubyte, GLubyte, GLubyte, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glTexCoord2fColor4ubVertex3fvSUN (const GLfloat *, const GLubyte *, const GLfloat *);
-GLAPI void APIENTRY glTexCoord2fColor3fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glTexCoord2fColor3fVertex3fvSUN (const GLfloat *, const GLfloat *, const GLfloat *);
-GLAPI void APIENTRY glTexCoord2fNormal3fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glTexCoord2fNormal3fVertex3fvSUN (const GLfloat *, const GLfloat *, const GLfloat *);
-GLAPI void APIENTRY glTexCoord2fColor4fNormal3fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glTexCoord2fColor4fNormal3fVertex3fvSUN (const GLfloat *, const GLfloat *, const GLfloat *, const GLfloat *);
-GLAPI void APIENTRY glTexCoord4fColor4fNormal3fVertex4fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glTexCoord4fColor4fNormal3fVertex4fvSUN (const GLfloat *, const GLfloat *, const GLfloat *, const GLfloat *);
-GLAPI void APIENTRY glReplacementCodeuiVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glReplacementCodeuiVertex3fvSUN (const GLuint *, const GLfloat *);
-GLAPI void APIENTRY glReplacementCodeuiColor4ubVertex3fSUN (GLuint, GLubyte, GLubyte, GLubyte, GLubyte, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glReplacementCodeuiColor4ubVertex3fvSUN (const GLuint *, const GLubyte *, const GLfloat *);
-GLAPI void APIENTRY glReplacementCodeuiColor3fVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glReplacementCodeuiColor3fVertex3fvSUN (const GLuint *, const GLfloat *, const GLfloat *);
-GLAPI void APIENTRY glReplacementCodeuiNormal3fVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glReplacementCodeuiNormal3fVertex3fvSUN (const GLuint *, const GLfloat *, const GLfloat *);
-GLAPI void APIENTRY glReplacementCodeuiColor4fNormal3fVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glReplacementCodeuiColor4fNormal3fVertex3fvSUN (const GLuint *, const GLfloat *, const GLfloat *, const GLfloat *);
-GLAPI void APIENTRY glReplacementCodeuiTexCoord2fVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glReplacementCodeuiTexCoord2fVertex3fvSUN (const GLuint *, const GLfloat *, const GLfloat *);
-GLAPI void APIENTRY glReplacementCodeuiTexCoord2fNormal3fVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glReplacementCodeuiTexCoord2fNormal3fVertex3fvSUN (const GLuint *, const GLfloat *, const GLfloat *, const GLfloat *);
-GLAPI void APIENTRY glReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fvSUN (const GLuint *, const GLfloat *, const GLfloat *, const GLfloat *, const GLfloat *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLCOLOR4UBVERTEX2FSUNPROC) (GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y);
-typedef void (APIENTRYP PFNGLCOLOR4UBVERTEX2FVSUNPROC) (const GLubyte *c, const GLfloat *v);
-typedef void (APIENTRYP PFNGLCOLOR4UBVERTEX3FSUNPROC) (GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z);
-typedef void (APIENTRYP PFNGLCOLOR4UBVERTEX3FVSUNPROC) (const GLubyte *c, const GLfloat *v);
-typedef void (APIENTRYP PFNGLCOLOR3FVERTEX3FSUNPROC) (GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z);
-typedef void (APIENTRYP PFNGLCOLOR3FVERTEX3FVSUNPROC) (const GLfloat *c, const GLfloat *v);
-typedef void (APIENTRYP PFNGLNORMAL3FVERTEX3FSUNPROC) (GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
-typedef void (APIENTRYP PFNGLNORMAL3FVERTEX3FVSUNPROC) (const GLfloat *n, const GLfloat *v);
-typedef void (APIENTRYP PFNGLCOLOR4FNORMAL3FVERTEX3FSUNPROC) (GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
-typedef void (APIENTRYP PFNGLCOLOR4FNORMAL3FVERTEX3FVSUNPROC) (const GLfloat *c, const GLfloat *n, const GLfloat *v);
-typedef void (APIENTRYP PFNGLTEXCOORD2FVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLfloat x, GLfloat y, GLfloat z);
-typedef void (APIENTRYP PFNGLTEXCOORD2FVERTEX3FVSUNPROC) (const GLfloat *tc, const GLfloat *v);
-typedef void (APIENTRYP PFNGLTEXCOORD4FVERTEX4FSUNPROC) (GLfloat s, GLfloat t, GLfloat p, GLfloat q, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
-typedef void (APIENTRYP PFNGLTEXCOORD4FVERTEX4FVSUNPROC) (const GLfloat *tc, const GLfloat *v);
-typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR4UBVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z);
-typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR4UBVERTEX3FVSUNPROC) (const GLfloat *tc, const GLubyte *c, const GLfloat *v);
-typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR3FVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z);
-typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR3FVERTEX3FVSUNPROC) (const GLfloat *tc, const GLfloat *c, const GLfloat *v);
-typedef void (APIENTRYP PFNGLTEXCOORD2FNORMAL3FVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
-typedef void (APIENTRYP PFNGLTEXCOORD2FNORMAL3FVERTEX3FVSUNPROC) (const GLfloat *tc, const GLfloat *n, const GLfloat *v);
-typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR4FNORMAL3FVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
-typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR4FNORMAL3FVERTEX3FVSUNPROC) (const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v);
-typedef void (APIENTRYP PFNGLTEXCOORD4FCOLOR4FNORMAL3FVERTEX4FSUNPROC) (GLfloat s, GLfloat t, GLfloat p, GLfloat q, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
-typedef void (APIENTRYP PFNGLTEXCOORD4FCOLOR4FNORMAL3FVERTEX4FVSUNPROC) (const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v);
-typedef void (APIENTRYP PFNGLREPLACEMENTCODEUIVERTEX3FSUNPROC) (GLuint rc, GLfloat x, GLfloat y, GLfloat z);
-typedef void (APIENTRYP PFNGLREPLACEMENTCODEUIVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *v);
-typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR4UBVERTEX3FSUNPROC) (GLuint rc, GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z);
-typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR4UBVERTEX3FVSUNPROC) (const GLuint *rc, const GLubyte *c, const GLfloat *v);
-typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR3FVERTEX3FSUNPROC) (GLuint rc, GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z);
-typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *c, const GLfloat *v);
-typedef void (APIENTRYP PFNGLREPLACEMENTCODEUINORMAL3FVERTEX3FSUNPROC) (GLuint rc, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
-typedef void (APIENTRYP PFNGLREPLACEMENTCODEUINORMAL3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *n, const GLfloat *v);
-typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR4FNORMAL3FVERTEX3FSUNPROC) (GLuint rc, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
-typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR4FNORMAL3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *c, const GLfloat *n, const GLfloat *v);
-typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FVERTEX3FSUNPROC) (GLuint rc, GLfloat s, GLfloat t, GLfloat x, GLfloat y, GLfloat z);
-typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *tc, const GLfloat *v);
-typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FNORMAL3FVERTEX3FSUNPROC) (GLuint rc, GLfloat s, GLfloat t, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
-typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FNORMAL3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *tc, const GLfloat *n, const GLfloat *v);
-typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FCOLOR4FNORMAL3FVERTEX3FSUNPROC) (GLuint rc, GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
-typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FCOLOR4FNORMAL3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v);
-#endif
-
-#ifndef GL_EXT_blend_func_separate
-#define GL_EXT_blend_func_separate 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glBlendFuncSeparateEXT (GLenum, GLenum, GLenum, GLenum);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEEXTPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);
-#endif
-
-#ifndef GL_INGR_blend_func_separate
-#define GL_INGR_blend_func_separate 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glBlendFuncSeparateINGR (GLenum, GLenum, GLenum, GLenum);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEINGRPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);
-#endif
-
-#ifndef GL_INGR_color_clamp
-#define GL_INGR_color_clamp 1
-#endif
-
-#ifndef GL_INGR_interlace_read
-#define GL_INGR_interlace_read 1
-#endif
-
-#ifndef GL_EXT_stencil_wrap
-#define GL_EXT_stencil_wrap 1
-#endif
-
-#ifndef GL_EXT_422_pixels
-#define GL_EXT_422_pixels 1
-#endif
-
-#ifndef GL_NV_texgen_reflection
-#define GL_NV_texgen_reflection 1
-#endif
-
-#ifndef GL_SUN_convolution_border_modes
-#define GL_SUN_convolution_border_modes 1
-#endif
-
-#ifndef GL_EXT_texture_env_add
-#define GL_EXT_texture_env_add 1
-#endif
-
-#ifndef GL_EXT_texture_lod_bias
-#define GL_EXT_texture_lod_bias 1
-#endif
-
-#ifndef GL_EXT_texture_filter_anisotropic
-#define GL_EXT_texture_filter_anisotropic 1
-#endif
-
-#ifndef GL_EXT_vertex_weighting
-#define GL_EXT_vertex_weighting 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glVertexWeightfEXT (GLfloat);
-GLAPI void APIENTRY glVertexWeightfvEXT (const GLfloat *);
-GLAPI void APIENTRY glVertexWeightPointerEXT (GLsizei, GLenum, GLsizei, const GLvoid *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLVERTEXWEIGHTFEXTPROC) (GLfloat weight);
-typedef void (APIENTRYP PFNGLVERTEXWEIGHTFVEXTPROC) (const GLfloat *weight);
-typedef void (APIENTRYP PFNGLVERTEXWEIGHTPOINTEREXTPROC) (GLsizei size, GLenum type, GLsizei stride, const GLvoid *pointer);
-#endif
-
-#ifndef GL_NV_light_max_exponent
-#define GL_NV_light_max_exponent 1
-#endif
-
-#ifndef GL_NV_vertex_array_range
-#define GL_NV_vertex_array_range 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glFlushVertexArrayRangeNV (void);
-GLAPI void APIENTRY glVertexArrayRangeNV (GLsizei, const GLvoid *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLFLUSHVERTEXARRAYRANGENVPROC) (void);
-typedef void (APIENTRYP PFNGLVERTEXARRAYRANGENVPROC) (GLsizei length, const GLvoid *pointer);
-#endif
-
-#ifndef GL_NV_register_combiners
-#define GL_NV_register_combiners 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glCombinerParameterfvNV (GLenum, const GLfloat *);
-GLAPI void APIENTRY glCombinerParameterfNV (GLenum, GLfloat);
-GLAPI void APIENTRY glCombinerParameterivNV (GLenum, const GLint *);
-GLAPI void APIENTRY glCombinerParameteriNV (GLenum, GLint);
-GLAPI void APIENTRY glCombinerInputNV (GLenum, GLenum, GLenum, GLenum, GLenum, GLenum);
-GLAPI void APIENTRY glCombinerOutputNV (GLenum, GLenum, GLenum, GLenum, GLenum, GLenum, GLenum, GLboolean, GLboolean, GLboolean);
-GLAPI void APIENTRY glFinalCombinerInputNV (GLenum, GLenum, GLenum, GLenum);
-GLAPI void APIENTRY glGetCombinerInputParameterfvNV (GLenum, GLenum, GLenum, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetCombinerInputParameterivNV (GLenum, GLenum, GLenum, GLenum, GLint *);
-GLAPI void APIENTRY glGetCombinerOutputParameterfvNV (GLenum, GLenum, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetCombinerOutputParameterivNV (GLenum, GLenum, GLenum, GLint *);
-GLAPI void APIENTRY glGetFinalCombinerInputParameterfvNV (GLenum, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetFinalCombinerInputParameterivNV (GLenum, GLenum, GLint *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLCOMBINERPARAMETERFVNVPROC) (GLenum pname, const GLfloat *params);
-typedef void (APIENTRYP PFNGLCOMBINERPARAMETERFNVPROC) (GLenum pname, GLfloat param);
-typedef void (APIENTRYP PFNGLCOMBINERPARAMETERIVNVPROC) (GLenum pname, const GLint *params);
-typedef void (APIENTRYP PFNGLCOMBINERPARAMETERINVPROC) (GLenum pname, GLint param);
-typedef void (APIENTRYP PFNGLCOMBINERINPUTNVPROC) (GLenum stage, GLenum portion, GLenum variable, GLenum input, GLenum mapping, GLenum componentUsage);
-typedef void (APIENTRYP PFNGLCOMBINEROUTPUTNVPROC) (GLenum stage, GLenum portion, GLenum abOutput, GLenum cdOutput, GLenum sumOutput, GLenum scale, GLenum bias, GLboolean abDotProduct, GLboolean cdDotProduct, GLboolean muxSum);
-typedef void (APIENTRYP PFNGLFINALCOMBINERINPUTNVPROC) (GLenum variable, GLenum input, GLenum mapping, GLenum componentUsage);
-typedef void (APIENTRYP PFNGLGETCOMBINERINPUTPARAMETERFVNVPROC) (GLenum stage, GLenum portion, GLenum variable, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETCOMBINERINPUTPARAMETERIVNVPROC) (GLenum stage, GLenum portion, GLenum variable, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETCOMBINEROUTPUTPARAMETERFVNVPROC) (GLenum stage, GLenum portion, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETCOMBINEROUTPUTPARAMETERIVNVPROC) (GLenum stage, GLenum portion, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETFINALCOMBINERINPUTPARAMETERFVNVPROC) (GLenum variable, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETFINALCOMBINERINPUTPARAMETERIVNVPROC) (GLenum variable, GLenum pname, GLint *params);
-#endif
-
-#ifndef GL_NV_fog_distance
-#define GL_NV_fog_distance 1
-#endif
-
-#ifndef GL_NV_texgen_emboss
-#define GL_NV_texgen_emboss 1
-#endif
-
-#ifndef GL_NV_blend_square
-#define GL_NV_blend_square 1
-#endif
-
-#ifndef GL_NV_texture_env_combine4
-#define GL_NV_texture_env_combine4 1
-#endif
-
-#ifndef GL_MESA_resize_buffers
-#define GL_MESA_resize_buffers 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glResizeBuffersMESA (void);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLRESIZEBUFFERSMESAPROC) (void);
-#endif
-
-#ifndef GL_MESA_window_pos
-#define GL_MESA_window_pos 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glWindowPos2dMESA (GLdouble, GLdouble);
-GLAPI void APIENTRY glWindowPos2dvMESA (const GLdouble *);
-GLAPI void APIENTRY glWindowPos2fMESA (GLfloat, GLfloat);
-GLAPI void APIENTRY glWindowPos2fvMESA (const GLfloat *);
-GLAPI void APIENTRY glWindowPos2iMESA (GLint, GLint);
-GLAPI void APIENTRY glWindowPos2ivMESA (const GLint *);
-GLAPI void APIENTRY glWindowPos2sMESA (GLshort, GLshort);
-GLAPI void APIENTRY glWindowPos2svMESA (const GLshort *);
-GLAPI void APIENTRY glWindowPos3dMESA (GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glWindowPos3dvMESA (const GLdouble *);
-GLAPI void APIENTRY glWindowPos3fMESA (GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glWindowPos3fvMESA (const GLfloat *);
-GLAPI void APIENTRY glWindowPos3iMESA (GLint, GLint, GLint);
-GLAPI void APIENTRY glWindowPos3ivMESA (const GLint *);
-GLAPI void APIENTRY glWindowPos3sMESA (GLshort, GLshort, GLshort);
-GLAPI void APIENTRY glWindowPos3svMESA (const GLshort *);
-GLAPI void APIENTRY glWindowPos4dMESA (GLdouble, GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glWindowPos4dvMESA (const GLdouble *);
-GLAPI void APIENTRY glWindowPos4fMESA (GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glWindowPos4fvMESA (const GLfloat *);
-GLAPI void APIENTRY glWindowPos4iMESA (GLint, GLint, GLint, GLint);
-GLAPI void APIENTRY glWindowPos4ivMESA (const GLint *);
-GLAPI void APIENTRY glWindowPos4sMESA (GLshort, GLshort, GLshort, GLshort);
-GLAPI void APIENTRY glWindowPos4svMESA (const GLshort *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLWINDOWPOS2DMESAPROC) (GLdouble x, GLdouble y);
-typedef void (APIENTRYP PFNGLWINDOWPOS2DVMESAPROC) (const GLdouble *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS2FMESAPROC) (GLfloat x, GLfloat y);
-typedef void (APIENTRYP PFNGLWINDOWPOS2FVMESAPROC) (const GLfloat *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS2IMESAPROC) (GLint x, GLint y);
-typedef void (APIENTRYP PFNGLWINDOWPOS2IVMESAPROC) (const GLint *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS2SMESAPROC) (GLshort x, GLshort y);
-typedef void (APIENTRYP PFNGLWINDOWPOS2SVMESAPROC) (const GLshort *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS3DMESAPROC) (GLdouble x, GLdouble y, GLdouble z);
-typedef void (APIENTRYP PFNGLWINDOWPOS3DVMESAPROC) (const GLdouble *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS3FMESAPROC) (GLfloat x, GLfloat y, GLfloat z);
-typedef void (APIENTRYP PFNGLWINDOWPOS3FVMESAPROC) (const GLfloat *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS3IMESAPROC) (GLint x, GLint y, GLint z);
-typedef void (APIENTRYP PFNGLWINDOWPOS3IVMESAPROC) (const GLint *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS3SMESAPROC) (GLshort x, GLshort y, GLshort z);
-typedef void (APIENTRYP PFNGLWINDOWPOS3SVMESAPROC) (const GLshort *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS4DMESAPROC) (GLdouble x, GLdouble y, GLdouble z, GLdouble w);
-typedef void (APIENTRYP PFNGLWINDOWPOS4DVMESAPROC) (const GLdouble *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS4FMESAPROC) (GLfloat x, GLfloat y, GLfloat z, GLfloat w);
-typedef void (APIENTRYP PFNGLWINDOWPOS4FVMESAPROC) (const GLfloat *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS4IMESAPROC) (GLint x, GLint y, GLint z, GLint w);
-typedef void (APIENTRYP PFNGLWINDOWPOS4IVMESAPROC) (const GLint *v);
-typedef void (APIENTRYP PFNGLWINDOWPOS4SMESAPROC) (GLshort x, GLshort y, GLshort z, GLshort w);
-typedef void (APIENTRYP PFNGLWINDOWPOS4SVMESAPROC) (const GLshort *v);
-#endif
-
-#ifndef GL_EXT_texture_compression_s3tc
-#define GL_EXT_texture_compression_s3tc 1
-#endif
-
-#ifndef GL_IBM_cull_vertex
-#define GL_IBM_cull_vertex 1
-#endif
-
-#ifndef GL_IBM_multimode_draw_arrays
-#define GL_IBM_multimode_draw_arrays 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glMultiModeDrawArraysIBM (const GLenum *, const GLint *, const GLsizei *, GLsizei, GLint);
-GLAPI void APIENTRY glMultiModeDrawElementsIBM (const GLenum *, const GLsizei *, GLenum, const GLvoid* const *, GLsizei, GLint);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLMULTIMODEDRAWARRAYSIBMPROC) (const GLenum *mode, const GLint *first, const GLsizei *count, GLsizei primcount, GLint modestride);
-typedef void (APIENTRYP PFNGLMULTIMODEDRAWELEMENTSIBMPROC) (const GLenum *mode, const GLsizei *count, GLenum type, const GLvoid* const *indices, GLsizei primcount, GLint modestride);
-#endif
-
-#ifndef GL_IBM_vertex_array_lists
-#define GL_IBM_vertex_array_lists 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glColorPointerListIBM (GLint, GLenum, GLint, const GLvoid* *, GLint);
-GLAPI void APIENTRY glSecondaryColorPointerListIBM (GLint, GLenum, GLint, const GLvoid* *, GLint);
-GLAPI void APIENTRY glEdgeFlagPointerListIBM (GLint, const GLboolean* *, GLint);
-GLAPI void APIENTRY glFogCoordPointerListIBM (GLenum, GLint, const GLvoid* *, GLint);
-GLAPI void APIENTRY glIndexPointerListIBM (GLenum, GLint, const GLvoid* *, GLint);
-GLAPI void APIENTRY glNormalPointerListIBM (GLenum, GLint, const GLvoid* *, GLint);
-GLAPI void APIENTRY glTexCoordPointerListIBM (GLint, GLenum, GLint, const GLvoid* *, GLint);
-GLAPI void APIENTRY glVertexPointerListIBM (GLint, GLenum, GLint, const GLvoid* *, GLint);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLCOLORPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);
-typedef void (APIENTRYP PFNGLSECONDARYCOLORPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);
-typedef void (APIENTRYP PFNGLEDGEFLAGPOINTERLISTIBMPROC) (GLint stride, const GLboolean* *pointer, GLint ptrstride);
-typedef void (APIENTRYP PFNGLFOGCOORDPOINTERLISTIBMPROC) (GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);
-typedef void (APIENTRYP PFNGLINDEXPOINTERLISTIBMPROC) (GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);
-typedef void (APIENTRYP PFNGLNORMALPOINTERLISTIBMPROC) (GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);
-typedef void (APIENTRYP PFNGLTEXCOORDPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);
-typedef void (APIENTRYP PFNGLVERTEXPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);
-#endif
-
-#ifndef GL_SGIX_subsample
-#define GL_SGIX_subsample 1
-#endif
-
-#ifndef GL_SGIX_ycrcba
-#define GL_SGIX_ycrcba 1
-#endif
-
-#ifndef GL_SGIX_ycrcb_subsample
-#define GL_SGIX_ycrcb_subsample 1
-#endif
-
-#ifndef GL_SGIX_depth_pass_instrument
-#define GL_SGIX_depth_pass_instrument 1
-#endif
-
-#ifndef GL_3DFX_texture_compression_FXT1
-#define GL_3DFX_texture_compression_FXT1 1
-#endif
-
-#ifndef GL_3DFX_multisample
-#define GL_3DFX_multisample 1
-#endif
-
-#ifndef GL_3DFX_tbuffer
-#define GL_3DFX_tbuffer 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glTbufferMask3DFX (GLuint);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLTBUFFERMASK3DFXPROC) (GLuint mask);
-#endif
-
-#ifndef GL_EXT_multisample
-#define GL_EXT_multisample 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glSampleMaskEXT (GLclampf, GLboolean);
-GLAPI void APIENTRY glSamplePatternEXT (GLenum);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLSAMPLEMASKEXTPROC) (GLclampf value, GLboolean invert);
-typedef void (APIENTRYP PFNGLSAMPLEPATTERNEXTPROC) (GLenum pattern);
-#endif
-
-#ifndef GL_SGIX_vertex_preclip
-#define GL_SGIX_vertex_preclip 1
-#endif
-
-#ifndef GL_SGIX_convolution_accuracy
-#define GL_SGIX_convolution_accuracy 1
-#endif
-
-#ifndef GL_SGIX_resample
-#define GL_SGIX_resample 1
-#endif
-
-#ifndef GL_SGIS_point_line_texgen
-#define GL_SGIS_point_line_texgen 1
-#endif
-
-#ifndef GL_SGIS_texture_color_mask
-#define GL_SGIS_texture_color_mask 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glTextureColorMaskSGIS (GLboolean, GLboolean, GLboolean, GLboolean);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLTEXTURECOLORMASKSGISPROC) (GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha);
-#endif
-
-#ifndef GL_SGIX_igloo_interface
-#define GL_SGIX_igloo_interface 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glIglooInterfaceSGIX (GLenum, const GLvoid *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLIGLOOINTERFACESGIXPROC) (GLenum pname, const GLvoid *params);
-#endif
-
-#ifndef GL_EXT_texture_env_dot3
-#define GL_EXT_texture_env_dot3 1
-#endif
-
-#ifndef GL_ATI_texture_mirror_once
-#define GL_ATI_texture_mirror_once 1
-#endif
-
-#ifndef GL_NV_fence
-#define GL_NV_fence 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glDeleteFencesNV (GLsizei, const GLuint *);
-GLAPI void APIENTRY glGenFencesNV (GLsizei, GLuint *);
-GLAPI GLboolean APIENTRY glIsFenceNV (GLuint);
-GLAPI GLboolean APIENTRY glTestFenceNV (GLuint);
-GLAPI void APIENTRY glGetFenceivNV (GLuint, GLenum, GLint *);
-GLAPI void APIENTRY glFinishFenceNV (GLuint);
-GLAPI void APIENTRY glSetFenceNV (GLuint, GLenum);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLDELETEFENCESNVPROC) (GLsizei n, const GLuint *fences);
-typedef void (APIENTRYP PFNGLGENFENCESNVPROC) (GLsizei n, GLuint *fences);
-typedef GLboolean (APIENTRYP PFNGLISFENCENVPROC) (GLuint fence);
-typedef GLboolean (APIENTRYP PFNGLTESTFENCENVPROC) (GLuint fence);
-typedef void (APIENTRYP PFNGLGETFENCEIVNVPROC) (GLuint fence, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLFINISHFENCENVPROC) (GLuint fence);
-typedef void (APIENTRYP PFNGLSETFENCENVPROC) (GLuint fence, GLenum condition);
-#endif
-
-#ifndef GL_NV_evaluators
-#define GL_NV_evaluators 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glMapControlPointsNV (GLenum, GLuint, GLenum, GLsizei, GLsizei, GLint, GLint, GLboolean, const GLvoid *);
-GLAPI void APIENTRY glMapParameterivNV (GLenum, GLenum, const GLint *);
-GLAPI void APIENTRY glMapParameterfvNV (GLenum, GLenum, const GLfloat *);
-GLAPI void APIENTRY glGetMapControlPointsNV (GLenum, GLuint, GLenum, GLsizei, GLsizei, GLboolean, GLvoid *);
-GLAPI void APIENTRY glGetMapParameterivNV (GLenum, GLenum, GLint *);
-GLAPI void APIENTRY glGetMapParameterfvNV (GLenum, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetMapAttribParameterivNV (GLenum, GLuint, GLenum, GLint *);
-GLAPI void APIENTRY glGetMapAttribParameterfvNV (GLenum, GLuint, GLenum, GLfloat *);
-GLAPI void APIENTRY glEvalMapsNV (GLenum, GLenum);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLMAPCONTROLPOINTSNVPROC) (GLenum target, GLuint index, GLenum type, GLsizei ustride, GLsizei vstride, GLint uorder, GLint vorder, GLboolean packed, const GLvoid *points);
-typedef void (APIENTRYP PFNGLMAPPARAMETERIVNVPROC) (GLenum target, GLenum pname, const GLint *params);
-typedef void (APIENTRYP PFNGLMAPPARAMETERFVNVPROC) (GLenum target, GLenum pname, const GLfloat *params);
-typedef void (APIENTRYP PFNGLGETMAPCONTROLPOINTSNVPROC) (GLenum target, GLuint index, GLenum type, GLsizei ustride, GLsizei vstride, GLboolean packed, GLvoid *points);
-typedef void (APIENTRYP PFNGLGETMAPPARAMETERIVNVPROC) (GLenum target, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETMAPPARAMETERFVNVPROC) (GLenum target, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETMAPATTRIBPARAMETERIVNVPROC) (GLenum target, GLuint index, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETMAPATTRIBPARAMETERFVNVPROC) (GLenum target, GLuint index, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLEVALMAPSNVPROC) (GLenum target, GLenum mode);
-#endif
-
-#ifndef GL_NV_packed_depth_stencil
-#define GL_NV_packed_depth_stencil 1
-#endif
-
-#ifndef GL_NV_register_combiners2
-#define GL_NV_register_combiners2 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glCombinerStageParameterfvNV (GLenum, GLenum, const GLfloat *);
-GLAPI void APIENTRY glGetCombinerStageParameterfvNV (GLenum, GLenum, GLfloat *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLCOMBINERSTAGEPARAMETERFVNVPROC) (GLenum stage, GLenum pname, const GLfloat *params);
-typedef void (APIENTRYP PFNGLGETCOMBINERSTAGEPARAMETERFVNVPROC) (GLenum stage, GLenum pname, GLfloat *params);
-#endif
-
-#ifndef GL_NV_texture_compression_vtc
-#define GL_NV_texture_compression_vtc 1
-#endif
-
-#ifndef GL_NV_texture_rectangle
-#define GL_NV_texture_rectangle 1
-#endif
-
-#ifndef GL_NV_texture_shader
-#define GL_NV_texture_shader 1
-#endif
-
-#ifndef GL_NV_texture_shader2
-#define GL_NV_texture_shader2 1
-#endif
-
-#ifndef GL_NV_vertex_array_range2
-#define GL_NV_vertex_array_range2 1
-#endif
-
-#ifndef GL_NV_vertex_program
-#define GL_NV_vertex_program 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI GLboolean APIENTRY glAreProgramsResidentNV (GLsizei, const GLuint *, GLboolean *);
-GLAPI void APIENTRY glBindProgramNV (GLenum, GLuint);
-GLAPI void APIENTRY glDeleteProgramsNV (GLsizei, const GLuint *);
-GLAPI void APIENTRY glExecuteProgramNV (GLenum, GLuint, const GLfloat *);
-GLAPI void APIENTRY glGenProgramsNV (GLsizei, GLuint *);
-GLAPI void APIENTRY glGetProgramParameterdvNV (GLenum, GLuint, GLenum, GLdouble *);
-GLAPI void APIENTRY glGetProgramParameterfvNV (GLenum, GLuint, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetProgramivNV (GLuint, GLenum, GLint *);
-GLAPI void APIENTRY glGetProgramStringNV (GLuint, GLenum, GLubyte *);
-GLAPI void APIENTRY glGetTrackMatrixivNV (GLenum, GLuint, GLenum, GLint *);
-GLAPI void APIENTRY glGetVertexAttribdvNV (GLuint, GLenum, GLdouble *);
-GLAPI void APIENTRY glGetVertexAttribfvNV (GLuint, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetVertexAttribivNV (GLuint, GLenum, GLint *);
-GLAPI void APIENTRY glGetVertexAttribPointervNV (GLuint, GLenum, GLvoid* *);
-GLAPI GLboolean APIENTRY glIsProgramNV (GLuint);
-GLAPI void APIENTRY glLoadProgramNV (GLenum, GLuint, GLsizei, const GLubyte *);
-GLAPI void APIENTRY glProgramParameter4dNV (GLenum, GLuint, GLdouble, GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glProgramParameter4dvNV (GLenum, GLuint, const GLdouble *);
-GLAPI void APIENTRY glProgramParameter4fNV (GLenum, GLuint, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glProgramParameter4fvNV (GLenum, GLuint, const GLfloat *);
-GLAPI void APIENTRY glProgramParameters4dvNV (GLenum, GLuint, GLuint, const GLdouble *);
-GLAPI void APIENTRY glProgramParameters4fvNV (GLenum, GLuint, GLuint, const GLfloat *);
-GLAPI void APIENTRY glRequestResidentProgramsNV (GLsizei, const GLuint *);
-GLAPI void APIENTRY glTrackMatrixNV (GLenum, GLuint, GLenum, GLenum);
-GLAPI void APIENTRY glVertexAttribPointerNV (GLuint, GLint, GLenum, GLsizei, const GLvoid *);
-GLAPI void APIENTRY glVertexAttrib1dNV (GLuint, GLdouble);
-GLAPI void APIENTRY glVertexAttrib1dvNV (GLuint, const GLdouble *);
-GLAPI void APIENTRY glVertexAttrib1fNV (GLuint, GLfloat);
-GLAPI void APIENTRY glVertexAttrib1fvNV (GLuint, const GLfloat *);
-GLAPI void APIENTRY glVertexAttrib1sNV (GLuint, GLshort);
-GLAPI void APIENTRY glVertexAttrib1svNV (GLuint, const GLshort *);
-GLAPI void APIENTRY glVertexAttrib2dNV (GLuint, GLdouble, GLdouble);
-GLAPI void APIENTRY glVertexAttrib2dvNV (GLuint, const GLdouble *);
-GLAPI void APIENTRY glVertexAttrib2fNV (GLuint, GLfloat, GLfloat);
-GLAPI void APIENTRY glVertexAttrib2fvNV (GLuint, const GLfloat *);
-GLAPI void APIENTRY glVertexAttrib2sNV (GLuint, GLshort, GLshort);
-GLAPI void APIENTRY glVertexAttrib2svNV (GLuint, const GLshort *);
-GLAPI void APIENTRY glVertexAttrib3dNV (GLuint, GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glVertexAttrib3dvNV (GLuint, const GLdouble *);
-GLAPI void APIENTRY glVertexAttrib3fNV (GLuint, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glVertexAttrib3fvNV (GLuint, const GLfloat *);
-GLAPI void APIENTRY glVertexAttrib3sNV (GLuint, GLshort, GLshort, GLshort);
-GLAPI void APIENTRY glVertexAttrib3svNV (GLuint, const GLshort *);
-GLAPI void APIENTRY glVertexAttrib4dNV (GLuint, GLdouble, GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glVertexAttrib4dvNV (GLuint, const GLdouble *);
-GLAPI void APIENTRY glVertexAttrib4fNV (GLuint, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glVertexAttrib4fvNV (GLuint, const GLfloat *);
-GLAPI void APIENTRY glVertexAttrib4sNV (GLuint, GLshort, GLshort, GLshort, GLshort);
-GLAPI void APIENTRY glVertexAttrib4svNV (GLuint, const GLshort *);
-GLAPI void APIENTRY glVertexAttrib4ubNV (GLuint, GLubyte, GLubyte, GLubyte, GLubyte);
-GLAPI void APIENTRY glVertexAttrib4ubvNV (GLuint, const GLubyte *);
-GLAPI void APIENTRY glVertexAttribs1dvNV (GLuint, GLsizei, const GLdouble *);
-GLAPI void APIENTRY glVertexAttribs1fvNV (GLuint, GLsizei, const GLfloat *);
-GLAPI void APIENTRY glVertexAttribs1svNV (GLuint, GLsizei, const GLshort *);
-GLAPI void APIENTRY glVertexAttribs2dvNV (GLuint, GLsizei, const GLdouble *);
-GLAPI void APIENTRY glVertexAttribs2fvNV (GLuint, GLsizei, const GLfloat *);
-GLAPI void APIENTRY glVertexAttribs2svNV (GLuint, GLsizei, const GLshort *);
-GLAPI void APIENTRY glVertexAttribs3dvNV (GLuint, GLsizei, const GLdouble *);
-GLAPI void APIENTRY glVertexAttribs3fvNV (GLuint, GLsizei, const GLfloat *);
-GLAPI void APIENTRY glVertexAttribs3svNV (GLuint, GLsizei, const GLshort *);
-GLAPI void APIENTRY glVertexAttribs4dvNV (GLuint, GLsizei, const GLdouble *);
-GLAPI void APIENTRY glVertexAttribs4fvNV (GLuint, GLsizei, const GLfloat *);
-GLAPI void APIENTRY glVertexAttribs4svNV (GLuint, GLsizei, const GLshort *);
-GLAPI void APIENTRY glVertexAttribs4ubvNV (GLuint, GLsizei, const GLubyte *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef GLboolean (APIENTRYP PFNGLAREPROGRAMSRESIDENTNVPROC) (GLsizei n, const GLuint *programs, GLboolean *residences);
-typedef void (APIENTRYP PFNGLBINDPROGRAMNVPROC) (GLenum target, GLuint id);
-typedef void (APIENTRYP PFNGLDELETEPROGRAMSNVPROC) (GLsizei n, const GLuint *programs);
-typedef void (APIENTRYP PFNGLEXECUTEPROGRAMNVPROC) (GLenum target, GLuint id, const GLfloat *params);
-typedef void (APIENTRYP PFNGLGENPROGRAMSNVPROC) (GLsizei n, GLuint *programs);
-typedef void (APIENTRYP PFNGLGETPROGRAMPARAMETERDVNVPROC) (GLenum target, GLuint index, GLenum pname, GLdouble *params);
-typedef void (APIENTRYP PFNGLGETPROGRAMPARAMETERFVNVPROC) (GLenum target, GLuint index, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETPROGRAMIVNVPROC) (GLuint id, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETPROGRAMSTRINGNVPROC) (GLuint id, GLenum pname, GLubyte *program);
-typedef void (APIENTRYP PFNGLGETTRACKMATRIXIVNVPROC) (GLenum target, GLuint address, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETVERTEXATTRIBDVNVPROC) (GLuint index, GLenum pname, GLdouble *params);
-typedef void (APIENTRYP PFNGLGETVERTEXATTRIBFVNVPROC) (GLuint index, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVNVPROC) (GLuint index, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVNVPROC) (GLuint index, GLenum pname, GLvoid* *pointer);
-typedef GLboolean (APIENTRYP PFNGLISPROGRAMNVPROC) (GLuint id);
-typedef void (APIENTRYP PFNGLLOADPROGRAMNVPROC) (GLenum target, GLuint id, GLsizei len, const GLubyte *program);
-typedef void (APIENTRYP PFNGLPROGRAMPARAMETER4DNVPROC) (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
-typedef void (APIENTRYP PFNGLPROGRAMPARAMETER4DVNVPROC) (GLenum target, GLuint index, const GLdouble *v);
-typedef void (APIENTRYP PFNGLPROGRAMPARAMETER4FNVPROC) (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
-typedef void (APIENTRYP PFNGLPROGRAMPARAMETER4FVNVPROC) (GLenum target, GLuint index, const GLfloat *v);
-typedef void (APIENTRYP PFNGLPROGRAMPARAMETERS4DVNVPROC) (GLenum target, GLuint index, GLuint count, const GLdouble *v);
-typedef void (APIENTRYP PFNGLPROGRAMPARAMETERS4FVNVPROC) (GLenum target, GLuint index, GLuint count, const GLfloat *v);
-typedef void (APIENTRYP PFNGLREQUESTRESIDENTPROGRAMSNVPROC) (GLsizei n, const GLuint *programs);
-typedef void (APIENTRYP PFNGLTRACKMATRIXNVPROC) (GLenum target, GLuint address, GLenum matrix, GLenum transform);
-typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERNVPROC) (GLuint index, GLint fsize, GLenum type, GLsizei stride, const GLvoid *pointer);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB1DNVPROC) (GLuint index, GLdouble x);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB1DVNVPROC) (GLuint index, const GLdouble *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB1FNVPROC) (GLuint index, GLfloat x);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB1FVNVPROC) (GLuint index, const GLfloat *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB1SNVPROC) (GLuint index, GLshort x);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB1SVNVPROC) (GLuint index, const GLshort *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB2DNVPROC) (GLuint index, GLdouble x, GLdouble y);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB2DVNVPROC) (GLuint index, const GLdouble *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB2FNVPROC) (GLuint index, GLfloat x, GLfloat y);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB2FVNVPROC) (GLuint index, const GLfloat *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB2SNVPROC) (GLuint index, GLshort x, GLshort y);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB2SVNVPROC) (GLuint index, const GLshort *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB3DNVPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB3DVNVPROC) (GLuint index, const GLdouble *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB3FNVPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB3FVNVPROC) (GLuint index, const GLfloat *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB3SNVPROC) (GLuint index, GLshort x, GLshort y, GLshort z);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB3SVNVPROC) (GLuint index, const GLshort *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4DNVPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4DVNVPROC) (GLuint index, const GLdouble *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4FNVPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4FVNVPROC) (GLuint index, const GLfloat *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4SNVPROC) (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4SVNVPROC) (GLuint index, const GLshort *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBNVPROC) (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBVNVPROC) (GLuint index, const GLubyte *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIBS1DVNVPROC) (GLuint index, GLsizei count, const GLdouble *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIBS1FVNVPROC) (GLuint index, GLsizei count, const GLfloat *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIBS1SVNVPROC) (GLuint index, GLsizei count, const GLshort *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIBS2DVNVPROC) (GLuint index, GLsizei count, const GLdouble *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIBS2FVNVPROC) (GLuint index, GLsizei count, const GLfloat *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIBS2SVNVPROC) (GLuint index, GLsizei count, const GLshort *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIBS3DVNVPROC) (GLuint index, GLsizei count, const GLdouble *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIBS3FVNVPROC) (GLuint index, GLsizei count, const GLfloat *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIBS3SVNVPROC) (GLuint index, GLsizei count, const GLshort *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIBS4DVNVPROC) (GLuint index, GLsizei count, const GLdouble *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIBS4FVNVPROC) (GLuint index, GLsizei count, const GLfloat *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIBS4SVNVPROC) (GLuint index, GLsizei count, const GLshort *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIBS4UBVNVPROC) (GLuint index, GLsizei count, const GLubyte *v);
-#endif
-
-#ifndef GL_SGIX_texture_coordinate_clamp
-#define GL_SGIX_texture_coordinate_clamp 1
-#endif
-
-#ifndef GL_SGIX_scalebias_hint
-#define GL_SGIX_scalebias_hint 1
-#endif
-
-#ifndef GL_OML_interlace
-#define GL_OML_interlace 1
-#endif
-
-#ifndef GL_OML_subsample
-#define GL_OML_subsample 1
-#endif
-
-#ifndef GL_OML_resample
-#define GL_OML_resample 1
-#endif
-
-#ifndef GL_NV_copy_depth_to_color
-#define GL_NV_copy_depth_to_color 1
-#endif
-
-#ifndef GL_ATI_envmap_bumpmap
-#define GL_ATI_envmap_bumpmap 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glTexBumpParameterivATI (GLenum, const GLint *);
-GLAPI void APIENTRY glTexBumpParameterfvATI (GLenum, const GLfloat *);
-GLAPI void APIENTRY glGetTexBumpParameterivATI (GLenum, GLint *);
-GLAPI void APIENTRY glGetTexBumpParameterfvATI (GLenum, GLfloat *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLTEXBUMPPARAMETERIVATIPROC) (GLenum pname, const GLint *param);
-typedef void (APIENTRYP PFNGLTEXBUMPPARAMETERFVATIPROC) (GLenum pname, const GLfloat *param);
-typedef void (APIENTRYP PFNGLGETTEXBUMPPARAMETERIVATIPROC) (GLenum pname, GLint *param);
-typedef void (APIENTRYP PFNGLGETTEXBUMPPARAMETERFVATIPROC) (GLenum pname, GLfloat *param);
-#endif
-
-#ifndef GL_ATI_fragment_shader
-#define GL_ATI_fragment_shader 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI GLuint APIENTRY glGenFragmentShadersATI (GLuint);
-GLAPI void APIENTRY glBindFragmentShaderATI (GLuint);
-GLAPI void APIENTRY glDeleteFragmentShaderATI (GLuint);
-GLAPI void APIENTRY glBeginFragmentShaderATI (void);
-GLAPI void APIENTRY glEndFragmentShaderATI (void);
-GLAPI void APIENTRY glPassTexCoordATI (GLuint, GLuint, GLenum);
-GLAPI void APIENTRY glSampleMapATI (GLuint, GLuint, GLenum);
-GLAPI void APIENTRY glColorFragmentOp1ATI (GLenum, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint);
-GLAPI void APIENTRY glColorFragmentOp2ATI (GLenum, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint);
-GLAPI void APIENTRY glColorFragmentOp3ATI (GLenum, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint);
-GLAPI void APIENTRY glAlphaFragmentOp1ATI (GLenum, GLuint, GLuint, GLuint, GLuint, GLuint);
-GLAPI void APIENTRY glAlphaFragmentOp2ATI (GLenum, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint);
-GLAPI void APIENTRY glAlphaFragmentOp3ATI (GLenum, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint);
-GLAPI void APIENTRY glSetFragmentShaderConstantATI (GLuint, const GLfloat *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef GLuint (APIENTRYP PFNGLGENFRAGMENTSHADERSATIPROC) (GLuint range);
-typedef void (APIENTRYP PFNGLBINDFRAGMENTSHADERATIPROC) (GLuint id);
-typedef void (APIENTRYP PFNGLDELETEFRAGMENTSHADERATIPROC) (GLuint id);
-typedef void (APIENTRYP PFNGLBEGINFRAGMENTSHADERATIPROC) (void);
-typedef void (APIENTRYP PFNGLENDFRAGMENTSHADERATIPROC) (void);
-typedef void (APIENTRYP PFNGLPASSTEXCOORDATIPROC) (GLuint dst, GLuint coord, GLenum swizzle);
-typedef void (APIENTRYP PFNGLSAMPLEMAPATIPROC) (GLuint dst, GLuint interp, GLenum swizzle);
-typedef void (APIENTRYP PFNGLCOLORFRAGMENTOP1ATIPROC) (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod);
-typedef void (APIENTRYP PFNGLCOLORFRAGMENTOP2ATIPROC) (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod);
-typedef void (APIENTRYP PFNGLCOLORFRAGMENTOP3ATIPROC) (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod, GLuint arg3, GLuint arg3Rep, GLuint arg3Mod);
-typedef void (APIENTRYP PFNGLALPHAFRAGMENTOP1ATIPROC) (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod);
-typedef void (APIENTRYP PFNGLALPHAFRAGMENTOP2ATIPROC) (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod);
-typedef void (APIENTRYP PFNGLALPHAFRAGMENTOP3ATIPROC) (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod, GLuint arg3, GLuint arg3Rep, GLuint arg3Mod);
-typedef void (APIENTRYP PFNGLSETFRAGMENTSHADERCONSTANTATIPROC) (GLuint dst, const GLfloat *value);
-#endif
-
-#ifndef GL_ATI_pn_triangles
-#define GL_ATI_pn_triangles 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glPNTrianglesiATI (GLenum, GLint);
-GLAPI void APIENTRY glPNTrianglesfATI (GLenum, GLfloat);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLPNTRIANGLESIATIPROC) (GLenum pname, GLint param);
-typedef void (APIENTRYP PFNGLPNTRIANGLESFATIPROC) (GLenum pname, GLfloat param);
-#endif
-
-#ifndef GL_ATI_vertex_array_object
-#define GL_ATI_vertex_array_object 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI GLuint APIENTRY glNewObjectBufferATI (GLsizei, const GLvoid *, GLenum);
-GLAPI GLboolean APIENTRY glIsObjectBufferATI (GLuint);
-GLAPI void APIENTRY glUpdateObjectBufferATI (GLuint, GLuint, GLsizei, const GLvoid *, GLenum);
-GLAPI void APIENTRY glGetObjectBufferfvATI (GLuint, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetObjectBufferivATI (GLuint, GLenum, GLint *);
-GLAPI void APIENTRY glFreeObjectBufferATI (GLuint);
-GLAPI void APIENTRY glArrayObjectATI (GLenum, GLint, GLenum, GLsizei, GLuint, GLuint);
-GLAPI void APIENTRY glGetArrayObjectfvATI (GLenum, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetArrayObjectivATI (GLenum, GLenum, GLint *);
-GLAPI void APIENTRY glVariantArrayObjectATI (GLuint, GLenum, GLsizei, GLuint, GLuint);
-GLAPI void APIENTRY glGetVariantArrayObjectfvATI (GLuint, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetVariantArrayObjectivATI (GLuint, GLenum, GLint *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef GLuint (APIENTRYP PFNGLNEWOBJECTBUFFERATIPROC) (GLsizei size, const GLvoid *pointer, GLenum usage);
-typedef GLboolean (APIENTRYP PFNGLISOBJECTBUFFERATIPROC) (GLuint buffer);
-typedef void (APIENTRYP PFNGLUPDATEOBJECTBUFFERATIPROC) (GLuint buffer, GLuint offset, GLsizei size, const GLvoid *pointer, GLenum preserve);
-typedef void (APIENTRYP PFNGLGETOBJECTBUFFERFVATIPROC) (GLuint buffer, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETOBJECTBUFFERIVATIPROC) (GLuint buffer, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLFREEOBJECTBUFFERATIPROC) (GLuint buffer);
-typedef void (APIENTRYP PFNGLARRAYOBJECTATIPROC) (GLenum array, GLint size, GLenum type, GLsizei stride, GLuint buffer, GLuint offset);
-typedef void (APIENTRYP PFNGLGETARRAYOBJECTFVATIPROC) (GLenum array, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETARRAYOBJECTIVATIPROC) (GLenum array, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLVARIANTARRAYOBJECTATIPROC) (GLuint id, GLenum type, GLsizei stride, GLuint buffer, GLuint offset);
-typedef void (APIENTRYP PFNGLGETVARIANTARRAYOBJECTFVATIPROC) (GLuint id, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETVARIANTARRAYOBJECTIVATIPROC) (GLuint id, GLenum pname, GLint *params);
-#endif
-
-#ifndef GL_EXT_vertex_shader
-#define GL_EXT_vertex_shader 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glBeginVertexShaderEXT (void);
-GLAPI void APIENTRY glEndVertexShaderEXT (void);
-GLAPI void APIENTRY glBindVertexShaderEXT (GLuint);
-GLAPI GLuint APIENTRY glGenVertexShadersEXT (GLuint);
-GLAPI void APIENTRY glDeleteVertexShaderEXT (GLuint);
-GLAPI void APIENTRY glShaderOp1EXT (GLenum, GLuint, GLuint);
-GLAPI void APIENTRY glShaderOp2EXT (GLenum, GLuint, GLuint, GLuint);
-GLAPI void APIENTRY glShaderOp3EXT (GLenum, GLuint, GLuint, GLuint, GLuint);
-GLAPI void APIENTRY glSwizzleEXT (GLuint, GLuint, GLenum, GLenum, GLenum, GLenum);
-GLAPI void APIENTRY glWriteMaskEXT (GLuint, GLuint, GLenum, GLenum, GLenum, GLenum);
-GLAPI void APIENTRY glInsertComponentEXT (GLuint, GLuint, GLuint);
-GLAPI void APIENTRY glExtractComponentEXT (GLuint, GLuint, GLuint);
-GLAPI GLuint APIENTRY glGenSymbolsEXT (GLenum, GLenum, GLenum, GLuint);
-GLAPI void APIENTRY glSetInvariantEXT (GLuint, GLenum, const GLvoid *);
-GLAPI void APIENTRY glSetLocalConstantEXT (GLuint, GLenum, const GLvoid *);
-GLAPI void APIENTRY glVariantbvEXT (GLuint, const GLbyte *);
-GLAPI void APIENTRY glVariantsvEXT (GLuint, const GLshort *);
-GLAPI void APIENTRY glVariantivEXT (GLuint, const GLint *);
-GLAPI void APIENTRY glVariantfvEXT (GLuint, const GLfloat *);
-GLAPI void APIENTRY glVariantdvEXT (GLuint, const GLdouble *);
-GLAPI void APIENTRY glVariantubvEXT (GLuint, const GLubyte *);
-GLAPI void APIENTRY glVariantusvEXT (GLuint, const GLushort *);
-GLAPI void APIENTRY glVariantuivEXT (GLuint, const GLuint *);
-GLAPI void APIENTRY glVariantPointerEXT (GLuint, GLenum, GLuint, const GLvoid *);
-GLAPI void APIENTRY glEnableVariantClientStateEXT (GLuint);
-GLAPI void APIENTRY glDisableVariantClientStateEXT (GLuint);
-GLAPI GLuint APIENTRY glBindLightParameterEXT (GLenum, GLenum);
-GLAPI GLuint APIENTRY glBindMaterialParameterEXT (GLenum, GLenum);
-GLAPI GLuint APIENTRY glBindTexGenParameterEXT (GLenum, GLenum, GLenum);
-GLAPI GLuint APIENTRY glBindTextureUnitParameterEXT (GLenum, GLenum);
-GLAPI GLuint APIENTRY glBindParameterEXT (GLenum);
-GLAPI GLboolean APIENTRY glIsVariantEnabledEXT (GLuint, GLenum);
-GLAPI void APIENTRY glGetVariantBooleanvEXT (GLuint, GLenum, GLboolean *);
-GLAPI void APIENTRY glGetVariantIntegervEXT (GLuint, GLenum, GLint *);
-GLAPI void APIENTRY glGetVariantFloatvEXT (GLuint, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetVariantPointervEXT (GLuint, GLenum, GLvoid* *);
-GLAPI void APIENTRY glGetInvariantBooleanvEXT (GLuint, GLenum, GLboolean *);
-GLAPI void APIENTRY glGetInvariantIntegervEXT (GLuint, GLenum, GLint *);
-GLAPI void APIENTRY glGetInvariantFloatvEXT (GLuint, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetLocalConstantBooleanvEXT (GLuint, GLenum, GLboolean *);
-GLAPI void APIENTRY glGetLocalConstantIntegervEXT (GLuint, GLenum, GLint *);
-GLAPI void APIENTRY glGetLocalConstantFloatvEXT (GLuint, GLenum, GLfloat *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLBEGINVERTEXSHADEREXTPROC) (void);
-typedef void (APIENTRYP PFNGLENDVERTEXSHADEREXTPROC) (void);
-typedef void (APIENTRYP PFNGLBINDVERTEXSHADEREXTPROC) (GLuint id);
-typedef GLuint (APIENTRYP PFNGLGENVERTEXSHADERSEXTPROC) (GLuint range);
-typedef void (APIENTRYP PFNGLDELETEVERTEXSHADEREXTPROC) (GLuint id);
-typedef void (APIENTRYP PFNGLSHADEROP1EXTPROC) (GLenum op, GLuint res, GLuint arg1);
-typedef void (APIENTRYP PFNGLSHADEROP2EXTPROC) (GLenum op, GLuint res, GLuint arg1, GLuint arg2);
-typedef void (APIENTRYP PFNGLSHADEROP3EXTPROC) (GLenum op, GLuint res, GLuint arg1, GLuint arg2, GLuint arg3);
-typedef void (APIENTRYP PFNGLSWIZZLEEXTPROC) (GLuint res, GLuint in, GLenum outX, GLenum outY, GLenum outZ, GLenum outW);
-typedef void (APIENTRYP PFNGLWRITEMASKEXTPROC) (GLuint res, GLuint in, GLenum outX, GLenum outY, GLenum outZ, GLenum outW);
-typedef void (APIENTRYP PFNGLINSERTCOMPONENTEXTPROC) (GLuint res, GLuint src, GLuint num);
-typedef void (APIENTRYP PFNGLEXTRACTCOMPONENTEXTPROC) (GLuint res, GLuint src, GLuint num);
-typedef GLuint (APIENTRYP PFNGLGENSYMBOLSEXTPROC) (GLenum datatype, GLenum storagetype, GLenum range, GLuint components);
-typedef void (APIENTRYP PFNGLSETINVARIANTEXTPROC) (GLuint id, GLenum type, const GLvoid *addr);
-typedef void (APIENTRYP PFNGLSETLOCALCONSTANTEXTPROC) (GLuint id, GLenum type, const GLvoid *addr);
-typedef void (APIENTRYP PFNGLVARIANTBVEXTPROC) (GLuint id, const GLbyte *addr);
-typedef void (APIENTRYP PFNGLVARIANTSVEXTPROC) (GLuint id, const GLshort *addr);
-typedef void (APIENTRYP PFNGLVARIANTIVEXTPROC) (GLuint id, const GLint *addr);
-typedef void (APIENTRYP PFNGLVARIANTFVEXTPROC) (GLuint id, const GLfloat *addr);
-typedef void (APIENTRYP PFNGLVARIANTDVEXTPROC) (GLuint id, const GLdouble *addr);
-typedef void (APIENTRYP PFNGLVARIANTUBVEXTPROC) (GLuint id, const GLubyte *addr);
-typedef void (APIENTRYP PFNGLVARIANTUSVEXTPROC) (GLuint id, const GLushort *addr);
-typedef void (APIENTRYP PFNGLVARIANTUIVEXTPROC) (GLuint id, const GLuint *addr);
-typedef void (APIENTRYP PFNGLVARIANTPOINTEREXTPROC) (GLuint id, GLenum type, GLuint stride, const GLvoid *addr);
-typedef void (APIENTRYP PFNGLENABLEVARIANTCLIENTSTATEEXTPROC) (GLuint id);
-typedef void (APIENTRYP PFNGLDISABLEVARIANTCLIENTSTATEEXTPROC) (GLuint id);
-typedef GLuint (APIENTRYP PFNGLBINDLIGHTPARAMETEREXTPROC) (GLenum light, GLenum value);
-typedef GLuint (APIENTRYP PFNGLBINDMATERIALPARAMETEREXTPROC) (GLenum face, GLenum value);
-typedef GLuint (APIENTRYP PFNGLBINDTEXGENPARAMETEREXTPROC) (GLenum unit, GLenum coord, GLenum value);
-typedef GLuint (APIENTRYP PFNGLBINDTEXTUREUNITPARAMETEREXTPROC) (GLenum unit, GLenum value);
-typedef GLuint (APIENTRYP PFNGLBINDPARAMETEREXTPROC) (GLenum value);
-typedef GLboolean (APIENTRYP PFNGLISVARIANTENABLEDEXTPROC) (GLuint id, GLenum cap);
-typedef void (APIENTRYP PFNGLGETVARIANTBOOLEANVEXTPROC) (GLuint id, GLenum value, GLboolean *data);
-typedef void (APIENTRYP PFNGLGETVARIANTINTEGERVEXTPROC) (GLuint id, GLenum value, GLint *data);
-typedef void (APIENTRYP PFNGLGETVARIANTFLOATVEXTPROC) (GLuint id, GLenum value, GLfloat *data);
-typedef void (APIENTRYP PFNGLGETVARIANTPOINTERVEXTPROC) (GLuint id, GLenum value, GLvoid* *data);
-typedef void (APIENTRYP PFNGLGETINVARIANTBOOLEANVEXTPROC) (GLuint id, GLenum value, GLboolean *data);
-typedef void (APIENTRYP PFNGLGETINVARIANTINTEGERVEXTPROC) (GLuint id, GLenum value, GLint *data);
-typedef void (APIENTRYP PFNGLGETINVARIANTFLOATVEXTPROC) (GLuint id, GLenum value, GLfloat *data);
-typedef void (APIENTRYP PFNGLGETLOCALCONSTANTBOOLEANVEXTPROC) (GLuint id, GLenum value, GLboolean *data);
-typedef void (APIENTRYP PFNGLGETLOCALCONSTANTINTEGERVEXTPROC) (GLuint id, GLenum value, GLint *data);
-typedef void (APIENTRYP PFNGLGETLOCALCONSTANTFLOATVEXTPROC) (GLuint id, GLenum value, GLfloat *data);
-#endif
-
-#ifndef GL_ATI_vertex_streams
-#define GL_ATI_vertex_streams 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glVertexStream1sATI (GLenum, GLshort);
-GLAPI void APIENTRY glVertexStream1svATI (GLenum, const GLshort *);
-GLAPI void APIENTRY glVertexStream1iATI (GLenum, GLint);
-GLAPI void APIENTRY glVertexStream1ivATI (GLenum, const GLint *);
-GLAPI void APIENTRY glVertexStream1fATI (GLenum, GLfloat);
-GLAPI void APIENTRY glVertexStream1fvATI (GLenum, const GLfloat *);
-GLAPI void APIENTRY glVertexStream1dATI (GLenum, GLdouble);
-GLAPI void APIENTRY glVertexStream1dvATI (GLenum, const GLdouble *);
-GLAPI void APIENTRY glVertexStream2sATI (GLenum, GLshort, GLshort);
-GLAPI void APIENTRY glVertexStream2svATI (GLenum, const GLshort *);
-GLAPI void APIENTRY glVertexStream2iATI (GLenum, GLint, GLint);
-GLAPI void APIENTRY glVertexStream2ivATI (GLenum, const GLint *);
-GLAPI void APIENTRY glVertexStream2fATI (GLenum, GLfloat, GLfloat);
-GLAPI void APIENTRY glVertexStream2fvATI (GLenum, const GLfloat *);
-GLAPI void APIENTRY glVertexStream2dATI (GLenum, GLdouble, GLdouble);
-GLAPI void APIENTRY glVertexStream2dvATI (GLenum, const GLdouble *);
-GLAPI void APIENTRY glVertexStream3sATI (GLenum, GLshort, GLshort, GLshort);
-GLAPI void APIENTRY glVertexStream3svATI (GLenum, const GLshort *);
-GLAPI void APIENTRY glVertexStream3iATI (GLenum, GLint, GLint, GLint);
-GLAPI void APIENTRY glVertexStream3ivATI (GLenum, const GLint *);
-GLAPI void APIENTRY glVertexStream3fATI (GLenum, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glVertexStream3fvATI (GLenum, const GLfloat *);
-GLAPI void APIENTRY glVertexStream3dATI (GLenum, GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glVertexStream3dvATI (GLenum, const GLdouble *);
-GLAPI void APIENTRY glVertexStream4sATI (GLenum, GLshort, GLshort, GLshort, GLshort);
-GLAPI void APIENTRY glVertexStream4svATI (GLenum, const GLshort *);
-GLAPI void APIENTRY glVertexStream4iATI (GLenum, GLint, GLint, GLint, GLint);
-GLAPI void APIENTRY glVertexStream4ivATI (GLenum, const GLint *);
-GLAPI void APIENTRY glVertexStream4fATI (GLenum, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glVertexStream4fvATI (GLenum, const GLfloat *);
-GLAPI void APIENTRY glVertexStream4dATI (GLenum, GLdouble, GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glVertexStream4dvATI (GLenum, const GLdouble *);
-GLAPI void APIENTRY glNormalStream3bATI (GLenum, GLbyte, GLbyte, GLbyte);
-GLAPI void APIENTRY glNormalStream3bvATI (GLenum, const GLbyte *);
-GLAPI void APIENTRY glNormalStream3sATI (GLenum, GLshort, GLshort, GLshort);
-GLAPI void APIENTRY glNormalStream3svATI (GLenum, const GLshort *);
-GLAPI void APIENTRY glNormalStream3iATI (GLenum, GLint, GLint, GLint);
-GLAPI void APIENTRY glNormalStream3ivATI (GLenum, const GLint *);
-GLAPI void APIENTRY glNormalStream3fATI (GLenum, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glNormalStream3fvATI (GLenum, const GLfloat *);
-GLAPI void APIENTRY glNormalStream3dATI (GLenum, GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glNormalStream3dvATI (GLenum, const GLdouble *);
-GLAPI void APIENTRY glClientActiveVertexStreamATI (GLenum);
-GLAPI void APIENTRY glVertexBlendEnviATI (GLenum, GLint);
-GLAPI void APIENTRY glVertexBlendEnvfATI (GLenum, GLfloat);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLVERTEXSTREAM1SATIPROC) (GLenum stream, GLshort x);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM1SVATIPROC) (GLenum stream, const GLshort *coords);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM1IATIPROC) (GLenum stream, GLint x);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM1IVATIPROC) (GLenum stream, const GLint *coords);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM1FATIPROC) (GLenum stream, GLfloat x);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM1FVATIPROC) (GLenum stream, const GLfloat *coords);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM1DATIPROC) (GLenum stream, GLdouble x);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM1DVATIPROC) (GLenum stream, const GLdouble *coords);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM2SATIPROC) (GLenum stream, GLshort x, GLshort y);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM2SVATIPROC) (GLenum stream, const GLshort *coords);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM2IATIPROC) (GLenum stream, GLint x, GLint y);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM2IVATIPROC) (GLenum stream, const GLint *coords);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM2FATIPROC) (GLenum stream, GLfloat x, GLfloat y);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM2FVATIPROC) (GLenum stream, const GLfloat *coords);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM2DATIPROC) (GLenum stream, GLdouble x, GLdouble y);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM2DVATIPROC) (GLenum stream, const GLdouble *coords);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM3SATIPROC) (GLenum stream, GLshort x, GLshort y, GLshort z);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM3SVATIPROC) (GLenum stream, const GLshort *coords);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM3IATIPROC) (GLenum stream, GLint x, GLint y, GLint z);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM3IVATIPROC) (GLenum stream, const GLint *coords);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM3FATIPROC) (GLenum stream, GLfloat x, GLfloat y, GLfloat z);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM3FVATIPROC) (GLenum stream, const GLfloat *coords);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM3DATIPROC) (GLenum stream, GLdouble x, GLdouble y, GLdouble z);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM3DVATIPROC) (GLenum stream, const GLdouble *coords);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM4SATIPROC) (GLenum stream, GLshort x, GLshort y, GLshort z, GLshort w);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM4SVATIPROC) (GLenum stream, const GLshort *coords);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM4IATIPROC) (GLenum stream, GLint x, GLint y, GLint z, GLint w);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM4IVATIPROC) (GLenum stream, const GLint *coords);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM4FATIPROC) (GLenum stream, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM4FVATIPROC) (GLenum stream, const GLfloat *coords);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM4DATIPROC) (GLenum stream, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
-typedef void (APIENTRYP PFNGLVERTEXSTREAM4DVATIPROC) (GLenum stream, const GLdouble *coords);
-typedef void (APIENTRYP PFNGLNORMALSTREAM3BATIPROC) (GLenum stream, GLbyte nx, GLbyte ny, GLbyte nz);
-typedef void (APIENTRYP PFNGLNORMALSTREAM3BVATIPROC) (GLenum stream, const GLbyte *coords);
-typedef void (APIENTRYP PFNGLNORMALSTREAM3SATIPROC) (GLenum stream, GLshort nx, GLshort ny, GLshort nz);
-typedef void (APIENTRYP PFNGLNORMALSTREAM3SVATIPROC) (GLenum stream, const GLshort *coords);
-typedef void (APIENTRYP PFNGLNORMALSTREAM3IATIPROC) (GLenum stream, GLint nx, GLint ny, GLint nz);
-typedef void (APIENTRYP PFNGLNORMALSTREAM3IVATIPROC) (GLenum stream, const GLint *coords);
-typedef void (APIENTRYP PFNGLNORMALSTREAM3FATIPROC) (GLenum stream, GLfloat nx, GLfloat ny, GLfloat nz);
-typedef void (APIENTRYP PFNGLNORMALSTREAM3FVATIPROC) (GLenum stream, const GLfloat *coords);
-typedef void (APIENTRYP PFNGLNORMALSTREAM3DATIPROC) (GLenum stream, GLdouble nx, GLdouble ny, GLdouble nz);
-typedef void (APIENTRYP PFNGLNORMALSTREAM3DVATIPROC) (GLenum stream, const GLdouble *coords);
-typedef void (APIENTRYP PFNGLCLIENTACTIVEVERTEXSTREAMATIPROC) (GLenum stream);
-typedef void (APIENTRYP PFNGLVERTEXBLENDENVIATIPROC) (GLenum pname, GLint param);
-typedef void (APIENTRYP PFNGLVERTEXBLENDENVFATIPROC) (GLenum pname, GLfloat param);
-#endif
-
-#ifndef GL_ATI_element_array
-#define GL_ATI_element_array 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glElementPointerATI (GLenum, const GLvoid *);
-GLAPI void APIENTRY glDrawElementArrayATI (GLenum, GLsizei);
-GLAPI void APIENTRY glDrawRangeElementArrayATI (GLenum, GLuint, GLuint, GLsizei);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLELEMENTPOINTERATIPROC) (GLenum type, const GLvoid *pointer);
-typedef void (APIENTRYP PFNGLDRAWELEMENTARRAYATIPROC) (GLenum mode, GLsizei count);
-typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTARRAYATIPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count);
-#endif
-
-#ifndef GL_SUN_mesh_array
-#define GL_SUN_mesh_array 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glDrawMeshArraysSUN (GLenum, GLint, GLsizei, GLsizei);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLDRAWMESHARRAYSSUNPROC) (GLenum mode, GLint first, GLsizei count, GLsizei width);
-#endif
-
-#ifndef GL_SUN_slice_accum
-#define GL_SUN_slice_accum 1
-#endif
-
-#ifndef GL_NV_multisample_filter_hint
-#define GL_NV_multisample_filter_hint 1
-#endif
-
-#ifndef GL_NV_depth_clamp
-#define GL_NV_depth_clamp 1
-#endif
-
-#ifndef GL_NV_occlusion_query
-#define GL_NV_occlusion_query 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glGenOcclusionQueriesNV (GLsizei, GLuint *);
-GLAPI void APIENTRY glDeleteOcclusionQueriesNV (GLsizei, const GLuint *);
-GLAPI GLboolean APIENTRY glIsOcclusionQueryNV (GLuint);
-GLAPI void APIENTRY glBeginOcclusionQueryNV (GLuint);
-GLAPI void APIENTRY glEndOcclusionQueryNV (void);
-GLAPI void APIENTRY glGetOcclusionQueryivNV (GLuint, GLenum, GLint *);
-GLAPI void APIENTRY glGetOcclusionQueryuivNV (GLuint, GLenum, GLuint *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLGENOCCLUSIONQUERIESNVPROC) (GLsizei n, GLuint *ids);
-typedef void (APIENTRYP PFNGLDELETEOCCLUSIONQUERIESNVPROC) (GLsizei n, const GLuint *ids);
-typedef GLboolean (APIENTRYP PFNGLISOCCLUSIONQUERYNVPROC) (GLuint id);
-typedef void (APIENTRYP PFNGLBEGINOCCLUSIONQUERYNVPROC) (GLuint id);
-typedef void (APIENTRYP PFNGLENDOCCLUSIONQUERYNVPROC) (void);
-typedef void (APIENTRYP PFNGLGETOCCLUSIONQUERYIVNVPROC) (GLuint id, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGETOCCLUSIONQUERYUIVNVPROC) (GLuint id, GLenum pname, GLuint *params);
-#endif
-
-#ifndef GL_NV_point_sprite
-#define GL_NV_point_sprite 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glPointParameteriNV (GLenum, GLint);
-GLAPI void APIENTRY glPointParameterivNV (GLenum, const GLint *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLPOINTPARAMETERINVPROC) (GLenum pname, GLint param);
-typedef void (APIENTRYP PFNGLPOINTPARAMETERIVNVPROC) (GLenum pname, const GLint *params);
-#endif
-
-#ifndef GL_NV_texture_shader3
-#define GL_NV_texture_shader3 1
-#endif
-
-#ifndef GL_NV_vertex_program1_1
-#define GL_NV_vertex_program1_1 1
-#endif
-
-#ifndef GL_EXT_shadow_funcs
-#define GL_EXT_shadow_funcs 1
-#endif
-
-#ifndef GL_EXT_stencil_two_side
-#define GL_EXT_stencil_two_side 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glActiveStencilFaceEXT (GLenum);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLACTIVESTENCILFACEEXTPROC) (GLenum face);
-#endif
-
-#ifndef GL_ATI_text_fragment_shader
-#define GL_ATI_text_fragment_shader 1
-#endif
-
-#ifndef GL_APPLE_client_storage
-#define GL_APPLE_client_storage 1
-#endif
-
-#ifndef GL_APPLE_element_array
-#define GL_APPLE_element_array 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glElementPointerAPPLE (GLenum, const GLvoid *);
-GLAPI void APIENTRY glDrawElementArrayAPPLE (GLenum, GLint, GLsizei);
-GLAPI void APIENTRY glDrawRangeElementArrayAPPLE (GLenum, GLuint, GLuint, GLint, GLsizei);
-GLAPI void APIENTRY glMultiDrawElementArrayAPPLE (GLenum, const GLint *, const GLsizei *, GLsizei);
-GLAPI void APIENTRY glMultiDrawRangeElementArrayAPPLE (GLenum, GLuint, GLuint, const GLint *, const GLsizei *, GLsizei);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLELEMENTPOINTERAPPLEPROC) (GLenum type, const GLvoid *pointer);
-typedef void (APIENTRYP PFNGLDRAWELEMENTARRAYAPPLEPROC) (GLenum mode, GLint first, GLsizei count);
-typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTARRAYAPPLEPROC) (GLenum mode, GLuint start, GLuint end, GLint first, GLsizei count);
-typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTARRAYAPPLEPROC) (GLenum mode, const GLint *first, const GLsizei *count, GLsizei primcount);
-typedef void (APIENTRYP PFNGLMULTIDRAWRANGEELEMENTARRAYAPPLEPROC) (GLenum mode, GLuint start, GLuint end, const GLint *first, const GLsizei *count, GLsizei primcount);
-#endif
-
-#ifndef GL_APPLE_fence
-#define GL_APPLE_fence 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glGenFencesAPPLE (GLsizei, GLuint *);
-GLAPI void APIENTRY glDeleteFencesAPPLE (GLsizei, const GLuint *);
-GLAPI void APIENTRY glSetFenceAPPLE (GLuint);
-GLAPI GLboolean APIENTRY glIsFenceAPPLE (GLuint);
-GLAPI GLboolean APIENTRY glTestFenceAPPLE (GLuint);
-GLAPI void APIENTRY glFinishFenceAPPLE (GLuint);
-GLAPI GLboolean APIENTRY glTestObjectAPPLE (GLenum, GLuint);
-GLAPI void APIENTRY glFinishObjectAPPLE (GLenum, GLint);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLGENFENCESAPPLEPROC) (GLsizei n, GLuint *fences);
-typedef void (APIENTRYP PFNGLDELETEFENCESAPPLEPROC) (GLsizei n, const GLuint *fences);
-typedef void (APIENTRYP PFNGLSETFENCEAPPLEPROC) (GLuint fence);
-typedef GLboolean (APIENTRYP PFNGLISFENCEAPPLEPROC) (GLuint fence);
-typedef GLboolean (APIENTRYP PFNGLTESTFENCEAPPLEPROC) (GLuint fence);
-typedef void (APIENTRYP PFNGLFINISHFENCEAPPLEPROC) (GLuint fence);
-typedef GLboolean (APIENTRYP PFNGLTESTOBJECTAPPLEPROC) (GLenum object, GLuint name);
-typedef void (APIENTRYP PFNGLFINISHOBJECTAPPLEPROC) (GLenum object, GLint name);
-#endif
-
-#ifndef GL_APPLE_vertex_array_object
-#define GL_APPLE_vertex_array_object 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glBindVertexArrayAPPLE (GLuint);
-GLAPI void APIENTRY glDeleteVertexArraysAPPLE (GLsizei, const GLuint *);
-GLAPI void APIENTRY glGenVertexArraysAPPLE (GLsizei, const GLuint *);
-GLAPI GLboolean APIENTRY glIsVertexArrayAPPLE (GLuint);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLBINDVERTEXARRAYAPPLEPROC) (GLuint array);
-typedef void (APIENTRYP PFNGLDELETEVERTEXARRAYSAPPLEPROC) (GLsizei n, const GLuint *arrays);
-typedef void (APIENTRYP PFNGLGENVERTEXARRAYSAPPLEPROC) (GLsizei n, const GLuint *arrays);
-typedef GLboolean (APIENTRYP PFNGLISVERTEXARRAYAPPLEPROC) (GLuint array);
-#endif
-
-#ifndef GL_APPLE_vertex_array_range
-#define GL_APPLE_vertex_array_range 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glVertexArrayRangeAPPLE (GLsizei, GLvoid *);
-GLAPI void APIENTRY glFlushVertexArrayRangeAPPLE (GLsizei, GLvoid *);
-GLAPI void APIENTRY glVertexArrayParameteriAPPLE (GLenum, GLint);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLVERTEXARRAYRANGEAPPLEPROC) (GLsizei length, GLvoid *pointer);
-typedef void (APIENTRYP PFNGLFLUSHVERTEXARRAYRANGEAPPLEPROC) (GLsizei length, GLvoid *pointer);
-typedef void (APIENTRYP PFNGLVERTEXARRAYPARAMETERIAPPLEPROC) (GLenum pname, GLint param);
-#endif
-
-#ifndef GL_APPLE_ycbcr_422
-#define GL_APPLE_ycbcr_422 1
-#endif
-
-#ifndef GL_S3_s3tc
-#define GL_S3_s3tc 1
-#endif
-
-#ifndef GL_ATI_draw_buffers
-#define GL_ATI_draw_buffers 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glDrawBuffersATI (GLsizei, const GLenum *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLDRAWBUFFERSATIPROC) (GLsizei n, const GLenum *bufs);
-#endif
-
-#ifndef GL_ATI_pixel_format_float
-#define GL_ATI_pixel_format_float 1
-/* This is really a WGL extension, but defines some associated GL enums.
- * ATI does not export "GL_ATI_pixel_format_float" in the GL_EXTENSIONS string.
- */
-#endif
-
-#ifndef GL_ATI_texture_env_combine3
-#define GL_ATI_texture_env_combine3 1
-#endif
-
-#ifndef GL_ATI_texture_float
-#define GL_ATI_texture_float 1
-#endif
-
-#ifndef GL_NV_float_buffer
-#define GL_NV_float_buffer 1
-#endif
-
-#ifndef GL_NV_fragment_program
-#define GL_NV_fragment_program 1
-/* Some NV_fragment_program entry points are shared with ARB_vertex_program. */
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glProgramNamedParameter4fNV (GLuint, GLsizei, const GLubyte *, GLfloat, GLfloat, GLfloat, GLfloat);
-GLAPI void APIENTRY glProgramNamedParameter4dNV (GLuint, GLsizei, const GLubyte *, GLdouble, GLdouble, GLdouble, GLdouble);
-GLAPI void APIENTRY glProgramNamedParameter4fvNV (GLuint, GLsizei, const GLubyte *, const GLfloat *);
-GLAPI void APIENTRY glProgramNamedParameter4dvNV (GLuint, GLsizei, const GLubyte *, const GLdouble *);
-GLAPI void APIENTRY glGetProgramNamedParameterfvNV (GLuint, GLsizei, const GLubyte *, GLfloat *);
-GLAPI void APIENTRY glGetProgramNamedParameterdvNV (GLuint, GLsizei, const GLubyte *, GLdouble *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLPROGRAMNAMEDPARAMETER4FNVPROC) (GLuint id, GLsizei len, const GLubyte *name, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
-typedef void (APIENTRYP PFNGLPROGRAMNAMEDPARAMETER4DNVPROC) (GLuint id, GLsizei len, const GLubyte *name, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
-typedef void (APIENTRYP PFNGLPROGRAMNAMEDPARAMETER4FVNVPROC) (GLuint id, GLsizei len, const GLubyte *name, const GLfloat *v);
-typedef void (APIENTRYP PFNGLPROGRAMNAMEDPARAMETER4DVNVPROC) (GLuint id, GLsizei len, const GLubyte *name, const GLdouble *v);
-typedef void (APIENTRYP PFNGLGETPROGRAMNAMEDPARAMETERFVNVPROC) (GLuint id, GLsizei len, const GLubyte *name, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETPROGRAMNAMEDPARAMETERDVNVPROC) (GLuint id, GLsizei len, const GLubyte *name, GLdouble *params);
-#endif
-
-#ifndef GL_NV_half_float
-#define GL_NV_half_float 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glVertex2hNV (GLhalfNV, GLhalfNV);
-GLAPI void APIENTRY glVertex2hvNV (const GLhalfNV *);
-GLAPI void APIENTRY glVertex3hNV (GLhalfNV, GLhalfNV, GLhalfNV);
-GLAPI void APIENTRY glVertex3hvNV (const GLhalfNV *);
-GLAPI void APIENTRY glVertex4hNV (GLhalfNV, GLhalfNV, GLhalfNV, GLhalfNV);
-GLAPI void APIENTRY glVertex4hvNV (const GLhalfNV *);
-GLAPI void APIENTRY glNormal3hNV (GLhalfNV, GLhalfNV, GLhalfNV);
-GLAPI void APIENTRY glNormal3hvNV (const GLhalfNV *);
-GLAPI void APIENTRY glColor3hNV (GLhalfNV, GLhalfNV, GLhalfNV);
-GLAPI void APIENTRY glColor3hvNV (const GLhalfNV *);
-GLAPI void APIENTRY glColor4hNV (GLhalfNV, GLhalfNV, GLhalfNV, GLhalfNV);
-GLAPI void APIENTRY glColor4hvNV (const GLhalfNV *);
-GLAPI void APIENTRY glTexCoord1hNV (GLhalfNV);
-GLAPI void APIENTRY glTexCoord1hvNV (const GLhalfNV *);
-GLAPI void APIENTRY glTexCoord2hNV (GLhalfNV, GLhalfNV);
-GLAPI void APIENTRY glTexCoord2hvNV (const GLhalfNV *);
-GLAPI void APIENTRY glTexCoord3hNV (GLhalfNV, GLhalfNV, GLhalfNV);
-GLAPI void APIENTRY glTexCoord3hvNV (const GLhalfNV *);
-GLAPI void APIENTRY glTexCoord4hNV (GLhalfNV, GLhalfNV, GLhalfNV, GLhalfNV);
-GLAPI void APIENTRY glTexCoord4hvNV (const GLhalfNV *);
-GLAPI void APIENTRY glMultiTexCoord1hNV (GLenum, GLhalfNV);
-GLAPI void APIENTRY glMultiTexCoord1hvNV (GLenum, const GLhalfNV *);
-GLAPI void APIENTRY glMultiTexCoord2hNV (GLenum, GLhalfNV, GLhalfNV);
-GLAPI void APIENTRY glMultiTexCoord2hvNV (GLenum, const GLhalfNV *);
-GLAPI void APIENTRY glMultiTexCoord3hNV (GLenum, GLhalfNV, GLhalfNV, GLhalfNV);
-GLAPI void APIENTRY glMultiTexCoord3hvNV (GLenum, const GLhalfNV *);
-GLAPI void APIENTRY glMultiTexCoord4hNV (GLenum, GLhalfNV, GLhalfNV, GLhalfNV, GLhalfNV);
-GLAPI void APIENTRY glMultiTexCoord4hvNV (GLenum, const GLhalfNV *);
-GLAPI void APIENTRY glFogCoordhNV (GLhalfNV);
-GLAPI void APIENTRY glFogCoordhvNV (const GLhalfNV *);
-GLAPI void APIENTRY glSecondaryColor3hNV (GLhalfNV, GLhalfNV, GLhalfNV);
-GLAPI void APIENTRY glSecondaryColor3hvNV (const GLhalfNV *);
-GLAPI void APIENTRY glVertexWeighthNV (GLhalfNV);
-GLAPI void APIENTRY glVertexWeighthvNV (const GLhalfNV *);
-GLAPI void APIENTRY glVertexAttrib1hNV (GLuint, GLhalfNV);
-GLAPI void APIENTRY glVertexAttrib1hvNV (GLuint, const GLhalfNV *);
-GLAPI void APIENTRY glVertexAttrib2hNV (GLuint, GLhalfNV, GLhalfNV);
-GLAPI void APIENTRY glVertexAttrib2hvNV (GLuint, const GLhalfNV *);
-GLAPI void APIENTRY glVertexAttrib3hNV (GLuint, GLhalfNV, GLhalfNV, GLhalfNV);
-GLAPI void APIENTRY glVertexAttrib3hvNV (GLuint, const GLhalfNV *);
-GLAPI void APIENTRY glVertexAttrib4hNV (GLuint, GLhalfNV, GLhalfNV, GLhalfNV, GLhalfNV);
-GLAPI void APIENTRY glVertexAttrib4hvNV (GLuint, const GLhalfNV *);
-GLAPI void APIENTRY glVertexAttribs1hvNV (GLuint, GLsizei, const GLhalfNV *);
-GLAPI void APIENTRY glVertexAttribs2hvNV (GLuint, GLsizei, const GLhalfNV *);
-GLAPI void APIENTRY glVertexAttribs3hvNV (GLuint, GLsizei, const GLhalfNV *);
-GLAPI void APIENTRY glVertexAttribs4hvNV (GLuint, GLsizei, const GLhalfNV *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLVERTEX2HNVPROC) (GLhalfNV x, GLhalfNV y);
-typedef void (APIENTRYP PFNGLVERTEX2HVNVPROC) (const GLhalfNV *v);
-typedef void (APIENTRYP PFNGLVERTEX3HNVPROC) (GLhalfNV x, GLhalfNV y, GLhalfNV z);
-typedef void (APIENTRYP PFNGLVERTEX3HVNVPROC) (const GLhalfNV *v);
-typedef void (APIENTRYP PFNGLVERTEX4HNVPROC) (GLhalfNV x, GLhalfNV y, GLhalfNV z, GLhalfNV w);
-typedef void (APIENTRYP PFNGLVERTEX4HVNVPROC) (const GLhalfNV *v);
-typedef void (APIENTRYP PFNGLNORMAL3HNVPROC) (GLhalfNV nx, GLhalfNV ny, GLhalfNV nz);
-typedef void (APIENTRYP PFNGLNORMAL3HVNVPROC) (const GLhalfNV *v);
-typedef void (APIENTRYP PFNGLCOLOR3HNVPROC) (GLhalfNV red, GLhalfNV green, GLhalfNV blue);
-typedef void (APIENTRYP PFNGLCOLOR3HVNVPROC) (const GLhalfNV *v);
-typedef void (APIENTRYP PFNGLCOLOR4HNVPROC) (GLhalfNV red, GLhalfNV green, GLhalfNV blue, GLhalfNV alpha);
-typedef void (APIENTRYP PFNGLCOLOR4HVNVPROC) (const GLhalfNV *v);
-typedef void (APIENTRYP PFNGLTEXCOORD1HNVPROC) (GLhalfNV s);
-typedef void (APIENTRYP PFNGLTEXCOORD1HVNVPROC) (const GLhalfNV *v);
-typedef void (APIENTRYP PFNGLTEXCOORD2HNVPROC) (GLhalfNV s, GLhalfNV t);
-typedef void (APIENTRYP PFNGLTEXCOORD2HVNVPROC) (const GLhalfNV *v);
-typedef void (APIENTRYP PFNGLTEXCOORD3HNVPROC) (GLhalfNV s, GLhalfNV t, GLhalfNV r);
-typedef void (APIENTRYP PFNGLTEXCOORD3HVNVPROC) (const GLhalfNV *v);
-typedef void (APIENTRYP PFNGLTEXCOORD4HNVPROC) (GLhalfNV s, GLhalfNV t, GLhalfNV r, GLhalfNV q);
-typedef void (APIENTRYP PFNGLTEXCOORD4HVNVPROC) (const GLhalfNV *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD1HNVPROC) (GLenum target, GLhalfNV s);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD1HVNVPROC) (GLenum target, const GLhalfNV *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD2HNVPROC) (GLenum target, GLhalfNV s, GLhalfNV t);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD2HVNVPROC) (GLenum target, const GLhalfNV *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD3HNVPROC) (GLenum target, GLhalfNV s, GLhalfNV t, GLhalfNV r);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD3HVNVPROC) (GLenum target, const GLhalfNV *v);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD4HNVPROC) (GLenum target, GLhalfNV s, GLhalfNV t, GLhalfNV r, GLhalfNV q);
-typedef void (APIENTRYP PFNGLMULTITEXCOORD4HVNVPROC) (GLenum target, const GLhalfNV *v);
-typedef void (APIENTRYP PFNGLFOGCOORDHNVPROC) (GLhalfNV fog);
-typedef void (APIENTRYP PFNGLFOGCOORDHVNVPROC) (const GLhalfNV *fog);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3HNVPROC) (GLhalfNV red, GLhalfNV green, GLhalfNV blue);
-typedef void (APIENTRYP PFNGLSECONDARYCOLOR3HVNVPROC) (const GLhalfNV *v);
-typedef void (APIENTRYP PFNGLVERTEXWEIGHTHNVPROC) (GLhalfNV weight);
-typedef void (APIENTRYP PFNGLVERTEXWEIGHTHVNVPROC) (const GLhalfNV *weight);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB1HNVPROC) (GLuint index, GLhalfNV x);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB1HVNVPROC) (GLuint index, const GLhalfNV *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB2HNVPROC) (GLuint index, GLhalfNV x, GLhalfNV y);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB2HVNVPROC) (GLuint index, const GLhalfNV *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB3HNVPROC) (GLuint index, GLhalfNV x, GLhalfNV y, GLhalfNV z);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB3HVNVPROC) (GLuint index, const GLhalfNV *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4HNVPROC) (GLuint index, GLhalfNV x, GLhalfNV y, GLhalfNV z, GLhalfNV w);
-typedef void (APIENTRYP PFNGLVERTEXATTRIB4HVNVPROC) (GLuint index, const GLhalfNV *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIBS1HVNVPROC) (GLuint index, GLsizei n, const GLhalfNV *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIBS2HVNVPROC) (GLuint index, GLsizei n, const GLhalfNV *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIBS3HVNVPROC) (GLuint index, GLsizei n, const GLhalfNV *v);
-typedef void (APIENTRYP PFNGLVERTEXATTRIBS4HVNVPROC) (GLuint index, GLsizei n, const GLhalfNV *v);
-#endif
-
-#ifndef GL_NV_pixel_data_range
-#define GL_NV_pixel_data_range 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glPixelDataRangeNV (GLenum, GLsizei, GLvoid *);
-GLAPI void APIENTRY glFlushPixelDataRangeNV (GLenum);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLPIXELDATARANGENVPROC) (GLenum target, GLsizei length, GLvoid *pointer);
-typedef void (APIENTRYP PFNGLFLUSHPIXELDATARANGENVPROC) (GLenum target);
-#endif
-
-#ifndef GL_NV_primitive_restart
-#define GL_NV_primitive_restart 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glPrimitiveRestartNV (void);
-GLAPI void APIENTRY glPrimitiveRestartIndexNV (GLuint);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLPRIMITIVERESTARTNVPROC) (void);
-typedef void (APIENTRYP PFNGLPRIMITIVERESTARTINDEXNVPROC) (GLuint index);
-#endif
-
-#ifndef GL_NV_texture_expand_normal
-#define GL_NV_texture_expand_normal 1
-#endif
-
-#ifndef GL_NV_vertex_program2
-#define GL_NV_vertex_program2 1
-#endif
-
-#ifndef GL_ATI_map_object_buffer
-#define GL_ATI_map_object_buffer 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI GLvoid* APIENTRY glMapObjectBufferATI (GLuint);
-GLAPI void APIENTRY glUnmapObjectBufferATI (GLuint);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef GLvoid* (APIENTRYP PFNGLMAPOBJECTBUFFERATIPROC) (GLuint buffer);
-typedef void (APIENTRYP PFNGLUNMAPOBJECTBUFFERATIPROC) (GLuint buffer);
-#endif
-
-#ifndef GL_ATI_separate_stencil
-#define GL_ATI_separate_stencil 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glStencilOpSeparateATI (GLenum, GLenum, GLenum, GLenum);
-GLAPI void APIENTRY glStencilFuncSeparateATI (GLenum, GLenum, GLint, GLuint);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLSTENCILOPSEPARATEATIPROC) (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass);
-typedef void (APIENTRYP PFNGLSTENCILFUNCSEPARATEATIPROC) (GLenum frontfunc, GLenum backfunc, GLint ref, GLuint mask);
-#endif
-
-#ifndef GL_ATI_vertex_attrib_array_object
-#define GL_ATI_vertex_attrib_array_object 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glVertexAttribArrayObjectATI (GLuint, GLint, GLenum, GLboolean, GLsizei, GLuint, GLuint);
-GLAPI void APIENTRY glGetVertexAttribArrayObjectfvATI (GLuint, GLenum, GLfloat *);
-GLAPI void APIENTRY glGetVertexAttribArrayObjectivATI (GLuint, GLenum, GLint *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLVERTEXATTRIBARRAYOBJECTATIPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, GLuint buffer, GLuint offset);
-typedef void (APIENTRYP PFNGLGETVERTEXATTRIBARRAYOBJECTFVATIPROC) (GLuint index, GLenum pname, GLfloat *params);
-typedef void (APIENTRYP PFNGLGETVERTEXATTRIBARRAYOBJECTIVATIPROC) (GLuint index, GLenum pname, GLint *params);
-#endif
-
-#ifndef GL_OES_read_format
-#define GL_OES_read_format 1
-#endif
-
-#ifndef GL_EXT_depth_bounds_test
-#define GL_EXT_depth_bounds_test 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glDepthBoundsEXT (GLclampd, GLclampd);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLDEPTHBOUNDSEXTPROC) (GLclampd zmin, GLclampd zmax);
-#endif
-
-#ifndef GL_EXT_texture_mirror_clamp
-#define GL_EXT_texture_mirror_clamp 1
-#endif
-
-#ifndef GL_EXT_blend_equation_separate
-#define GL_EXT_blend_equation_separate 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glBlendEquationSeparateEXT (GLenum, GLenum);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEEXTPROC) (GLenum modeRGB, GLenum modeAlpha);
-#endif
-
-#ifndef GL_MESA_pack_invert
-#define GL_MESA_pack_invert 1
-#endif
-
-#ifndef GL_MESA_ycbcr_texture
-#define GL_MESA_ycbcr_texture 1
-#endif
-
-#ifndef GL_EXT_pixel_buffer_object
-#define GL_EXT_pixel_buffer_object 1
-#endif
-
-#ifndef GL_NV_fragment_program_option
-#define GL_NV_fragment_program_option 1
-#endif
-
-#ifndef GL_NV_fragment_program2
-#define GL_NV_fragment_program2 1
-#endif
-
-#ifndef GL_NV_vertex_program2_option
-#define GL_NV_vertex_program2_option 1
-#endif
-
-#ifndef GL_NV_vertex_program3
-#define GL_NV_vertex_program3 1
-#endif
-
-#ifndef GL_EXT_framebuffer_object
-#define GL_EXT_framebuffer_object 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI GLboolean APIENTRY glIsRenderbufferEXT (GLuint);
-GLAPI void APIENTRY glBindRenderbufferEXT (GLenum, GLuint);
-GLAPI void APIENTRY glDeleteRenderbuffersEXT (GLsizei, const GLuint *);
-GLAPI void APIENTRY glGenRenderbuffersEXT (GLsizei, GLuint *);
-GLAPI void APIENTRY glRenderbufferStorageEXT (GLenum, GLenum, GLsizei, GLsizei);
-GLAPI void APIENTRY glGetRenderbufferParameterivEXT (GLenum, GLenum, GLint *);
-GLAPI GLboolean APIENTRY glIsFramebufferEXT (GLuint);
-GLAPI void APIENTRY glBindFramebufferEXT (GLenum, GLuint);
-GLAPI void APIENTRY glDeleteFramebuffersEXT (GLsizei, const GLuint *);
-GLAPI void APIENTRY glGenFramebuffersEXT (GLsizei, GLuint *);
-GLAPI GLenum APIENTRY glCheckFramebufferStatusEXT (GLenum);
-GLAPI void APIENTRY glFramebufferTexture1DEXT (GLenum, GLenum, GLenum, GLuint, GLint);
-GLAPI void APIENTRY glFramebufferTexture2DEXT (GLenum, GLenum, GLenum, GLuint, GLint);
-GLAPI void APIENTRY glFramebufferTexture3DEXT (GLenum, GLenum, GLenum, GLuint, GLint, GLint);
-GLAPI void APIENTRY glFramebufferRenderbufferEXT (GLenum, GLenum, GLenum, GLuint);
-GLAPI void APIENTRY glGetFramebufferAttachmentParameterivEXT (GLenum, GLenum, GLenum, GLint *);
-GLAPI void APIENTRY glGenerateMipmapEXT (GLenum);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef GLboolean (APIENTRYP PFNGLISRENDERBUFFEREXTPROC) (GLuint renderbuffer);
-typedef void (APIENTRYP PFNGLBINDRENDERBUFFEREXTPROC) (GLenum target, GLuint renderbuffer);
-typedef void (APIENTRYP PFNGLDELETERENDERBUFFERSEXTPROC) (GLsizei n, const GLuint *renderbuffers);
-typedef void (APIENTRYP PFNGLGENRENDERBUFFERSEXTPROC) (GLsizei n, GLuint *renderbuffers);
-typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEEXTPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height);
-typedef void (APIENTRYP PFNGLGETRENDERBUFFERPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params);
-typedef GLboolean (APIENTRYP PFNGLISFRAMEBUFFEREXTPROC) (GLuint framebuffer);
-typedef void (APIENTRYP PFNGLBINDFRAMEBUFFEREXTPROC) (GLenum target, GLuint framebuffer);
-typedef void (APIENTRYP PFNGLDELETEFRAMEBUFFERSEXTPROC) (GLsizei n, const GLuint *framebuffers);
-typedef void (APIENTRYP PFNGLGENFRAMEBUFFERSEXTPROC) (GLsizei n, GLuint *framebuffers);
-typedef GLenum (APIENTRYP PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC) (GLenum target);
-typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE1DEXTPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
-typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE2DEXTPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
-typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE3DEXTPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset);
-typedef void (APIENTRYP PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC) (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer);
-typedef void (APIENTRYP PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVEXTPROC) (GLenum target, GLenum attachment, GLenum pname, GLint *params);
-typedef void (APIENTRYP PFNGLGENERATEMIPMAPEXTPROC) (GLenum target);
-#endif
-
-#ifndef GL_GREMEDY_string_marker
-#define GL_GREMEDY_string_marker 1
-#ifdef GL_GLEXT_PROTOTYPES
-GLAPI void APIENTRY glStringMarkerGREMEDY (GLsizei, const GLvoid *);
-#endif /* GL_GLEXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLSTRINGMARKERGREMEDYPROC) (GLsizei len, const GLvoid *string);
-#endif
-
-#ifndef GL_EXT_Cg_shader
-#define GL_EXT_Cg_shader 1
-#endif
-
-#ifndef GL_NV_element_array
-#define GL_NV_element_array 1
-#ifdef GL_GLEXT_PROTOTYPES
-extern void APIENTRY glElementPointerNV(GLenum type, const GLvoid *pointer);
-extern void APIENTRY glDrawElementArrayNV(GLenum mode, GLint first, GLsizei count);
-extern void APIENTRY glDrawRangeElementArrayNV(GLenum mode, GLuint start, GLuint end, GLint first, GLsizei count);
-extern void APIENTRY glMultiDrawElementArrayNV(GLenum mode, const GLint *first, const GLsizei *count, GLsizei primcount);
-extern void APIENTRY glMultiDrawRangeElementArrayNV(GLenum mode, GLuint start, GLuint end, const GLint *first, const GLsizei *count, GLsizei primcount);
-#endif
-typedef void (APIENTRY * PFNGLELEMENTPOINTERNVPROC) (GLenum type, const GLvoid *pointer);
-typedef void (APIENTRY * PFNGLDRAWELEMENTARRAYNVPROC) (GLenum mode, GLint first, GLsizei count);
-typedef void (APIENTRY * PFNGLDRAWRANGEELEMENTARRAYNVPROC) (GLenum mode, GLuint start, GLuint end, GLint first, GLsizei count);
-typedef void (APIENTRY * PFNGLMULTIDRAWELEMENTARRAYNVPROC) (GLenum mode, const GLint *first, const GLsizei *count, GLsizei primcount);
-typedef void (APIENTRY * PFNGLMULTIDRAWRANGEELEMENTARRAYNVPROC) (GLenum mode, GLuint start, GLuint end, const GLint *first, const GLsizei *count, GLsizei primcount);
-#endif
-
-#ifndef GL_NV_pixel_buffer_object
-#define GL_NV_pixel_buffer_object 1
-#endif
-
-#ifndef GL_NV_stencil_two_side
-#define GL_NV_stencil_two_side 1
-#ifdef GL_GLEXT_PROTOTYPES
-extern void APIENTRY glActiveStencilFaceNV(GLenum face);
-#endif
-typedef void (APIENTRY * PFNGLACTIVESTENCILFACENVPROC) (GLenum face);
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
+#ifndef __glext_h_
+#define __glext_h_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+  /******************************************************************************
+
+   Copyright NVIDIA Corporation 2005
+
+   TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED
+   *AS IS* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS
+   OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF
+   MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  IN NO EVENT SHALL
+   NVIDIA OR ITS SUPPLIERS BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT, OR
+   CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR
+   LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION,
+   OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR INABILITY TO USE
+   THIS SOFTWARE, EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+   DAMAGES.
+
+  ******************************************************************************/
+
+  /*
+  ** License Applicability. Except to the extent portions of this file are
+  ** made subject to an alternative license as permitted in the SGI Free
+  ** Software License B, Version 1.1 (the "License"), the contents of this
+  ** file are subject only to the provisions of the License. You may not use
+  ** this file except in compliance with the License. You may obtain a copy
+  ** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
+  ** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
+  **
+  ** http://oss.sgi.com/projects/FreeB
+  **
+  ** Note that, as provided in the License, the Software is distributed on an
+  ** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
+  ** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
+  ** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
+  ** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
+  **
+  ** Original Code. The Original Code is: OpenGL Sample Implementation,
+  ** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
+  ** Inc. The Original Code is Copyright (c) 1991-2004 Silicon Graphics, Inc.
+  ** Copyright in any portions created by third parties is as indicated
+  ** elsewhere herein. All Rights Reserved.
+  **
+  ** Additional Notice Provisions: This software was created using the
+  ** OpenGL(R) version 1.2.1 Sample Implementation published by SGI, but has
+  ** not been independently verified as being compliant with the OpenGL(R)
+  ** version 1.2.1 Specification.
+  */
+
+#if defined(_WIN32) && !defined(APIENTRY) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__)
+#define WIN32_LEAN_AND_MEAN 1
+#include <windows.h>
+#endif
+
+#ifndef APIENTRY
+#define APIENTRY
+#endif
+#ifndef APIENTRYP
+#define APIENTRYP APIENTRY *
+#endif
+#ifndef GLAPI
+#define GLAPI extern
+#endif
+
+  /*************************************************************/
+
+  /* Header file version number, required by OpenGL ABI for Linux */
+  /* glext.h last updated 2005/06/06 */
+  /* Current version at http://oss.sgi.com/projects/ogl-sample/registry/ */
+#define GL_GLEXT_VERSION 28
+
+#ifndef GL_VERSION_1_2
+#define GL_UNSIGNED_BYTE_3_3_2            0x8032
+#define GL_UNSIGNED_SHORT_4_4_4_4         0x8033
+#define GL_UNSIGNED_SHORT_5_5_5_1         0x8034
+#define GL_UNSIGNED_INT_8_8_8_8           0x8035
+#define GL_UNSIGNED_INT_10_10_10_2        0x8036
+#define GL_RESCALE_NORMAL                 0x803A
+#define GL_TEXTURE_BINDING_3D             0x806A
+#define GL_PACK_SKIP_IMAGES               0x806B
+#define GL_PACK_IMAGE_HEIGHT              0x806C
+#define GL_UNPACK_SKIP_IMAGES             0x806D
+#define GL_UNPACK_IMAGE_HEIGHT            0x806E
+#define GL_TEXTURE_3D                     0x806F
+#define GL_PROXY_TEXTURE_3D               0x8070
+#define GL_TEXTURE_DEPTH                  0x8071
+#define GL_TEXTURE_WRAP_R                 0x8072
+#define GL_MAX_3D_TEXTURE_SIZE            0x8073
+#define GL_UNSIGNED_BYTE_2_3_3_REV        0x8362
+#define GL_UNSIGNED_SHORT_5_6_5           0x8363
+#define GL_UNSIGNED_SHORT_5_6_5_REV       0x8364
+#define GL_UNSIGNED_SHORT_4_4_4_4_REV     0x8365
+#define GL_UNSIGNED_SHORT_1_5_5_5_REV     0x8366
+#define GL_UNSIGNED_INT_8_8_8_8_REV       0x8367
+#define GL_UNSIGNED_INT_2_10_10_10_REV    0x8368
+#define GL_BGR                            0x80E0
+#define GL_BGRA                           0x80E1
+#define GL_MAX_ELEMENTS_VERTICES          0x80E8
+#define GL_MAX_ELEMENTS_INDICES           0x80E9
+#define GL_CLAMP_TO_EDGE                  0x812F
+#define GL_TEXTURE_MIN_LOD                0x813A
+#define GL_TEXTURE_MAX_LOD                0x813B
+#define GL_TEXTURE_BASE_LEVEL             0x813C
+#define GL_TEXTURE_MAX_LEVEL              0x813D
+#define GL_LIGHT_MODEL_COLOR_CONTROL      0x81F8
+#define GL_SINGLE_COLOR                   0x81F9
+#define GL_SEPARATE_SPECULAR_COLOR        0x81FA
+#define GL_SMOOTH_POINT_SIZE_RANGE        0x0B12
+#define GL_SMOOTH_POINT_SIZE_GRANULARITY  0x0B13
+#define GL_SMOOTH_LINE_WIDTH_RANGE        0x0B22
+#define GL_SMOOTH_LINE_WIDTH_GRANULARITY  0x0B23
+#define GL_ALIASED_POINT_SIZE_RANGE       0x846D
+#define GL_ALIASED_LINE_WIDTH_RANGE       0x846E
+#endif
+
+#ifndef GL_ARB_imaging
+#define GL_CONSTANT_COLOR                 0x8001
+#define GL_ONE_MINUS_CONSTANT_COLOR       0x8002
+#define GL_CONSTANT_ALPHA                 0x8003
+#define GL_ONE_MINUS_CONSTANT_ALPHA       0x8004
+#define GL_BLEND_COLOR                    0x8005
+#define GL_FUNC_ADD                       0x8006
+#define GL_MIN                            0x8007
+#define GL_MAX                            0x8008
+#define GL_BLEND_EQUATION                 0x8009
+#define GL_FUNC_SUBTRACT                  0x800A
+#define GL_FUNC_REVERSE_SUBTRACT          0x800B
+#define GL_CONVOLUTION_1D                 0x8010
+#define GL_CONVOLUTION_2D                 0x8011
+#define GL_SEPARABLE_2D                   0x8012
+#define GL_CONVOLUTION_BORDER_MODE        0x8013
+#define GL_CONVOLUTION_FILTER_SCALE       0x8014
+#define GL_CONVOLUTION_FILTER_BIAS        0x8015
+#define GL_REDUCE                         0x8016
+#define GL_CONVOLUTION_FORMAT             0x8017
+#define GL_CONVOLUTION_WIDTH              0x8018
+#define GL_CONVOLUTION_HEIGHT             0x8019
+#define GL_MAX_CONVOLUTION_WIDTH          0x801A
+#define GL_MAX_CONVOLUTION_HEIGHT         0x801B
+#define GL_POST_CONVOLUTION_RED_SCALE     0x801C
+#define GL_POST_CONVOLUTION_GREEN_SCALE   0x801D
+#define GL_POST_CONVOLUTION_BLUE_SCALE    0x801E
+#define GL_POST_CONVOLUTION_ALPHA_SCALE   0x801F
+#define GL_POST_CONVOLUTION_RED_BIAS      0x8020
+#define GL_POST_CONVOLUTION_GREEN_BIAS    0x8021
+#define GL_POST_CONVOLUTION_BLUE_BIAS     0x8022
+#define GL_POST_CONVOLUTION_ALPHA_BIAS    0x8023
+#define GL_HISTOGRAM                      0x8024
+#define GL_PROXY_HISTOGRAM                0x8025
+#define GL_HISTOGRAM_WIDTH                0x8026
+#define GL_HISTOGRAM_FORMAT               0x8027
+#define GL_HISTOGRAM_RED_SIZE             0x8028
+#define GL_HISTOGRAM_GREEN_SIZE           0x8029
+#define GL_HISTOGRAM_BLUE_SIZE            0x802A
+#define GL_HISTOGRAM_ALPHA_SIZE           0x802B
+#define GL_HISTOGRAM_LUMINANCE_SIZE       0x802C
+#define GL_HISTOGRAM_SINK                 0x802D
+#define GL_MINMAX                         0x802E
+#define GL_MINMAX_FORMAT                  0x802F
+#define GL_MINMAX_SINK                    0x8030
+#define GL_TABLE_TOO_LARGE                0x8031
+#define GL_COLOR_MATRIX                   0x80B1
+#define GL_COLOR_MATRIX_STACK_DEPTH       0x80B2
+#define GL_MAX_COLOR_MATRIX_STACK_DEPTH   0x80B3
+#define GL_POST_COLOR_MATRIX_RED_SCALE    0x80B4
+#define GL_POST_COLOR_MATRIX_GREEN_SCALE  0x80B5
+#define GL_POST_COLOR_MATRIX_BLUE_SCALE   0x80B6
+#define GL_POST_COLOR_MATRIX_ALPHA_SCALE  0x80B7
+#define GL_POST_COLOR_MATRIX_RED_BIAS     0x80B8
+#define GL_POST_COLOR_MATRIX_GREEN_BIAS   0x80B9
+#define GL_POST_COLOR_MATRIX_BLUE_BIAS    0x80BA
+#define GL_POST_COLOR_MATRIX_ALPHA_BIAS   0x80BB
+#define GL_COLOR_TABLE                    0x80D0
+#define GL_POST_CONVOLUTION_COLOR_TABLE   0x80D1
+#define GL_POST_COLOR_MATRIX_COLOR_TABLE  0x80D2
+#define GL_PROXY_COLOR_TABLE              0x80D3
+#define GL_PROXY_POST_CONVOLUTION_COLOR_TABLE 0x80D4
+#define GL_PROXY_POST_COLOR_MATRIX_COLOR_TABLE 0x80D5
+#define GL_COLOR_TABLE_SCALE              0x80D6
+#define GL_COLOR_TABLE_BIAS               0x80D7
+#define GL_COLOR_TABLE_FORMAT             0x80D8
+#define GL_COLOR_TABLE_WIDTH              0x80D9
+#define GL_COLOR_TABLE_RED_SIZE           0x80DA
+#define GL_COLOR_TABLE_GREEN_SIZE         0x80DB
+#define GL_COLOR_TABLE_BLUE_SIZE          0x80DC
+#define GL_COLOR_TABLE_ALPHA_SIZE         0x80DD
+#define GL_COLOR_TABLE_LUMINANCE_SIZE     0x80DE
+#define GL_COLOR_TABLE_INTENSITY_SIZE     0x80DF
+#define GL_CONSTANT_BORDER                0x8151
+#define GL_REPLICATE_BORDER               0x8153
+#define GL_CONVOLUTION_BORDER_COLOR       0x8154
+#endif
+
+#ifndef GL_VERSION_1_3
+#define GL_TEXTURE0                       0x84C0
+#define GL_TEXTURE1                       0x84C1
+#define GL_TEXTURE2                       0x84C2
+#define GL_TEXTURE3                       0x84C3
+#define GL_TEXTURE4                       0x84C4
+#define GL_TEXTURE5                       0x84C5
+#define GL_TEXTURE6                       0x84C6
+#define GL_TEXTURE7                       0x84C7
+#define GL_TEXTURE8                       0x84C8
+#define GL_TEXTURE9                       0x84C9
+#define GL_TEXTURE10                      0x84CA
+#define GL_TEXTURE11                      0x84CB
+#define GL_TEXTURE12                      0x84CC
+#define GL_TEXTURE13                      0x84CD
+#define GL_TEXTURE14                      0x84CE
+#define GL_TEXTURE15                      0x84CF
+#define GL_TEXTURE16                      0x84D0
+#define GL_TEXTURE17                      0x84D1
+#define GL_TEXTURE18                      0x84D2
+#define GL_TEXTURE19                      0x84D3
+#define GL_TEXTURE20                      0x84D4
+#define GL_TEXTURE21                      0x84D5
+#define GL_TEXTURE22                      0x84D6
+#define GL_TEXTURE23                      0x84D7
+#define GL_TEXTURE24                      0x84D8
+#define GL_TEXTURE25                      0x84D9
+#define GL_TEXTURE26                      0x84DA
+#define GL_TEXTURE27                      0x84DB
+#define GL_TEXTURE28                      0x84DC
+#define GL_TEXTURE29                      0x84DD
+#define GL_TEXTURE30                      0x84DE
+#define GL_TEXTURE31                      0x84DF
+#define GL_ACTIVE_TEXTURE                 0x84E0
+#define GL_CLIENT_ACTIVE_TEXTURE          0x84E1
+#define GL_MAX_TEXTURE_UNITS              0x84E2
+#define GL_TRANSPOSE_MODELVIEW_MATRIX     0x84E3
+#define GL_TRANSPOSE_PROJECTION_MATRIX    0x84E4
+#define GL_TRANSPOSE_TEXTURE_MATRIX       0x84E5
+#define GL_TRANSPOSE_COLOR_MATRIX         0x84E6
+#define GL_MULTISAMPLE                    0x809D
+#define GL_SAMPLE_ALPHA_TO_COVERAGE       0x809E
+#define GL_SAMPLE_ALPHA_TO_ONE            0x809F
+#define GL_SAMPLE_COVERAGE                0x80A0
+#define GL_SAMPLE_BUFFERS                 0x80A8
+#define GL_SAMPLES                        0x80A9
+#define GL_SAMPLE_COVERAGE_VALUE          0x80AA
+#define GL_SAMPLE_COVERAGE_INVERT         0x80AB
+#define GL_MULTISAMPLE_BIT                0x20000000
+#define GL_NORMAL_MAP                     0x8511
+#define GL_REFLECTION_MAP                 0x8512
+#define GL_TEXTURE_CUBE_MAP               0x8513
+#define GL_TEXTURE_BINDING_CUBE_MAP       0x8514
+#define GL_TEXTURE_CUBE_MAP_POSITIVE_X    0x8515
+#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X    0x8516
+#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y    0x8517
+#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y    0x8518
+#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z    0x8519
+#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z    0x851A
+#define GL_PROXY_TEXTURE_CUBE_MAP         0x851B
+#define GL_MAX_CUBE_MAP_TEXTURE_SIZE      0x851C
+#define GL_COMPRESSED_ALPHA               0x84E9
+#define GL_COMPRESSED_LUMINANCE           0x84EA
+#define GL_COMPRESSED_LUMINANCE_ALPHA     0x84EB
+#define GL_COMPRESSED_INTENSITY           0x84EC
+#define GL_COMPRESSED_RGB                 0x84ED
+#define GL_COMPRESSED_RGBA                0x84EE
+#define GL_TEXTURE_COMPRESSION_HINT       0x84EF
+#define GL_TEXTURE_COMPRESSED_IMAGE_SIZE  0x86A0
+#define GL_TEXTURE_COMPRESSED             0x86A1
+#define GL_NUM_COMPRESSED_TEXTURE_FORMATS 0x86A2
+#define GL_COMPRESSED_TEXTURE_FORMATS     0x86A3
+#define GL_CLAMP_TO_BORDER                0x812D
+#define GL_COMBINE                        0x8570
+#define GL_COMBINE_RGB                    0x8571
+#define GL_COMBINE_ALPHA                  0x8572
+#define GL_SOURCE0_RGB                    0x8580
+#define GL_SOURCE1_RGB                    0x8581
+#define GL_SOURCE2_RGB                    0x8582
+#define GL_SOURCE0_ALPHA                  0x8588
+#define GL_SOURCE1_ALPHA                  0x8589
+#define GL_SOURCE2_ALPHA                  0x858A
+#define GL_OPERAND0_RGB                   0x8590
+#define GL_OPERAND1_RGB                   0x8591
+#define GL_OPERAND2_RGB                   0x8592
+#define GL_OPERAND0_ALPHA                 0x8598
+#define GL_OPERAND1_ALPHA                 0x8599
+#define GL_OPERAND2_ALPHA                 0x859A
+#define GL_RGB_SCALE                      0x8573
+#define GL_ADD_SIGNED                     0x8574
+#define GL_INTERPOLATE                    0x8575
+#define GL_SUBTRACT                       0x84E7
+#define GL_CONSTANT                       0x8576
+#define GL_PRIMARY_COLOR                  0x8577
+#define GL_PREVIOUS                       0x8578
+#define GL_DOT3_RGB                       0x86AE
+#define GL_DOT3_RGBA                      0x86AF
+#endif
+
+#ifndef GL_VERSION_1_4
+#define GL_BLEND_DST_RGB                  0x80C8
+#define GL_BLEND_SRC_RGB                  0x80C9
+#define GL_BLEND_DST_ALPHA                0x80CA
+#define GL_BLEND_SRC_ALPHA                0x80CB
+#define GL_POINT_SIZE_MIN                 0x8126
+#define GL_POINT_SIZE_MAX                 0x8127
+#define GL_POINT_FADE_THRESHOLD_SIZE      0x8128
+#define GL_POINT_DISTANCE_ATTENUATION     0x8129
+#define GL_GENERATE_MIPMAP                0x8191
+#define GL_GENERATE_MIPMAP_HINT           0x8192
+#define GL_DEPTH_COMPONENT16              0x81A5
+#define GL_DEPTH_COMPONENT24              0x81A6
+#define GL_DEPTH_COMPONENT32              0x81A7
+#define GL_MIRRORED_REPEAT                0x8370
+#define GL_FOG_COORDINATE_SOURCE          0x8450
+#define GL_FOG_COORDINATE                 0x8451
+#define GL_FRAGMENT_DEPTH                 0x8452
+#define GL_CURRENT_FOG_COORDINATE         0x8453
+#define GL_FOG_COORDINATE_ARRAY_TYPE      0x8454
+#define GL_FOG_COORDINATE_ARRAY_STRIDE    0x8455
+#define GL_FOG_COORDINATE_ARRAY_POINTER   0x8456
+#define GL_FOG_COORDINATE_ARRAY           0x8457
+#define GL_COLOR_SUM                      0x8458
+#define GL_CURRENT_SECONDARY_COLOR        0x8459
+#define GL_SECONDARY_COLOR_ARRAY_SIZE     0x845A
+#define GL_SECONDARY_COLOR_ARRAY_TYPE     0x845B
+#define GL_SECONDARY_COLOR_ARRAY_STRIDE   0x845C
+#define GL_SECONDARY_COLOR_ARRAY_POINTER  0x845D
+#define GL_SECONDARY_COLOR_ARRAY          0x845E
+#define GL_MAX_TEXTURE_LOD_BIAS           0x84FD
+#define GL_TEXTURE_FILTER_CONTROL         0x8500
+#define GL_TEXTURE_LOD_BIAS               0x8501
+#define GL_INCR_WRAP                      0x8507
+#define GL_DECR_WRAP                      0x8508
+#define GL_TEXTURE_DEPTH_SIZE             0x884A
+#define GL_DEPTH_TEXTURE_MODE             0x884B
+#define GL_TEXTURE_COMPARE_MODE           0x884C
+#define GL_TEXTURE_COMPARE_FUNC           0x884D
+#define GL_COMPARE_R_TO_TEXTURE           0x884E
+#endif
+
+#ifndef GL_VERSION_1_5
+#define GL_BUFFER_SIZE                    0x8764
+#define GL_BUFFER_USAGE                   0x8765
+#define GL_QUERY_COUNTER_BITS             0x8864
+#define GL_CURRENT_QUERY                  0x8865
+#define GL_QUERY_RESULT                   0x8866
+#define GL_QUERY_RESULT_AVAILABLE         0x8867
+#define GL_ARRAY_BUFFER                   0x8892
+#define GL_ELEMENT_ARRAY_BUFFER           0x8893
+#define GL_ARRAY_BUFFER_BINDING           0x8894
+#define GL_ELEMENT_ARRAY_BUFFER_BINDING   0x8895
+#define GL_VERTEX_ARRAY_BUFFER_BINDING    0x8896
+#define GL_NORMAL_ARRAY_BUFFER_BINDING    0x8897
+#define GL_COLOR_ARRAY_BUFFER_BINDING     0x8898
+#define GL_INDEX_ARRAY_BUFFER_BINDING     0x8899
+#define GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING 0x889A
+#define GL_EDGE_FLAG_ARRAY_BUFFER_BINDING 0x889B
+#define GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING 0x889C
+#define GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING 0x889D
+#define GL_WEIGHT_ARRAY_BUFFER_BINDING    0x889E
+#define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING 0x889F
+#define GL_READ_ONLY                      0x88B8
+#define GL_WRITE_ONLY                     0x88B9
+#define GL_READ_WRITE                     0x88BA
+#define GL_BUFFER_ACCESS                  0x88BB
+#define GL_BUFFER_MAPPED                  0x88BC
+#define GL_BUFFER_MAP_POINTER             0x88BD
+#define GL_STREAM_DRAW                    0x88E0
+#define GL_STREAM_READ                    0x88E1
+#define GL_STREAM_COPY                    0x88E2
+#define GL_STATIC_DRAW                    0x88E4
+#define GL_STATIC_READ                    0x88E5
+#define GL_STATIC_COPY                    0x88E6
+#define GL_DYNAMIC_DRAW                   0x88E8
+#define GL_DYNAMIC_READ                   0x88E9
+#define GL_DYNAMIC_COPY                   0x88EA
+#define GL_SAMPLES_PASSED                 0x8914
+#define GL_FOG_COORD_SRC                  GL_FOG_COORDINATE_SOURCE
+#define GL_FOG_COORD                      GL_FOG_COORDINATE
+#define GL_CURRENT_FOG_COORD              GL_CURRENT_FOG_COORDINATE
+#define GL_FOG_COORD_ARRAY_TYPE           GL_FOG_COORDINATE_ARRAY_TYPE
+#define GL_FOG_COORD_ARRAY_STRIDE         GL_FOG_COORDINATE_ARRAY_STRIDE
+#define GL_FOG_COORD_ARRAY_POINTER        GL_FOG_COORDINATE_ARRAY_POINTER
+#define GL_FOG_COORD_ARRAY                GL_FOG_COORDINATE_ARRAY
+#define GL_FOG_COORD_ARRAY_BUFFER_BINDING GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING
+#define GL_SRC0_RGB                       GL_SOURCE0_RGB
+#define GL_SRC1_RGB                       GL_SOURCE1_RGB
+#define GL_SRC2_RGB                       GL_SOURCE2_RGB
+#define GL_SRC0_ALPHA                     GL_SOURCE0_ALPHA
+#define GL_SRC1_ALPHA                     GL_SOURCE1_ALPHA
+#define GL_SRC2_ALPHA                     GL_SOURCE2_ALPHA
+#endif
+
+#ifndef GL_VERSION_2_0
+#define GL_BLEND_EQUATION_RGB             GL_BLEND_EQUATION
+#define GL_VERTEX_ATTRIB_ARRAY_ENABLED    0x8622
+#define GL_VERTEX_ATTRIB_ARRAY_SIZE       0x8623
+#define GL_VERTEX_ATTRIB_ARRAY_STRIDE     0x8624
+#define GL_VERTEX_ATTRIB_ARRAY_TYPE       0x8625
+#define GL_CURRENT_VERTEX_ATTRIB          0x8626
+#define GL_VERTEX_PROGRAM_POINT_SIZE      0x8642
+#define GL_VERTEX_PROGRAM_TWO_SIDE        0x8643
+#define GL_VERTEX_ATTRIB_ARRAY_POINTER    0x8645
+#define GL_STENCIL_BACK_FUNC              0x8800
+#define GL_STENCIL_BACK_FAIL              0x8801
+#define GL_STENCIL_BACK_PASS_DEPTH_FAIL   0x8802
+#define GL_STENCIL_BACK_PASS_DEPTH_PASS   0x8803
+#define GL_MAX_DRAW_BUFFERS               0x8824
+#define GL_DRAW_BUFFER0                   0x8825
+#define GL_DRAW_BUFFER1                   0x8826
+#define GL_DRAW_BUFFER2                   0x8827
+#define GL_DRAW_BUFFER3                   0x8828
+#define GL_DRAW_BUFFER4                   0x8829
+#define GL_DRAW_BUFFER5                   0x882A
+#define GL_DRAW_BUFFER6                   0x882B
+#define GL_DRAW_BUFFER7                   0x882C
+#define GL_DRAW_BUFFER8                   0x882D
+#define GL_DRAW_BUFFER9                   0x882E
+#define GL_DRAW_BUFFER10                  0x882F
+#define GL_DRAW_BUFFER11                  0x8830
+#define GL_DRAW_BUFFER12                  0x8831
+#define GL_DRAW_BUFFER13                  0x8832
+#define GL_DRAW_BUFFER14                  0x8833
+#define GL_DRAW_BUFFER15                  0x8834
+#define GL_BLEND_EQUATION_ALPHA           0x883D
+#define GL_POINT_SPRITE                   0x8861
+#define GL_COORD_REPLACE                  0x8862
+#define GL_MAX_VERTEX_ATTRIBS             0x8869
+#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED 0x886A
+#define GL_MAX_TEXTURE_COORDS             0x8871
+#define GL_MAX_TEXTURE_IMAGE_UNITS        0x8872
+#define GL_FRAGMENT_SHADER                0x8B30
+#define GL_VERTEX_SHADER                  0x8B31
+#define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS 0x8B49
+#define GL_MAX_VERTEX_UNIFORM_COMPONENTS  0x8B4A
+#define GL_MAX_VARYING_FLOATS             0x8B4B
+#define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS 0x8B4C
+#define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS 0x8B4D
+#define GL_SHADER_TYPE                    0x8B4F
+#define GL_FLOAT_VEC2                     0x8B50
+#define GL_FLOAT_VEC3                     0x8B51
+#define GL_FLOAT_VEC4                     0x8B52
+#define GL_INT_VEC2                       0x8B53
+#define GL_INT_VEC3                       0x8B54
+#define GL_INT_VEC4                       0x8B55
+#define GL_BOOL                           0x8B56
+#define GL_BOOL_VEC2                      0x8B57
+#define GL_BOOL_VEC3                      0x8B58
+#define GL_BOOL_VEC4                      0x8B59
+#define GL_FLOAT_MAT2                     0x8B5A
+#define GL_FLOAT_MAT3                     0x8B5B
+#define GL_FLOAT_MAT4                     0x8B5C
+#define GL_SAMPLER_1D                     0x8B5D
+#define GL_SAMPLER_2D                     0x8B5E
+#define GL_SAMPLER_3D                     0x8B5F
+#define GL_SAMPLER_CUBE                   0x8B60
+#define GL_SAMPLER_1D_SHADOW              0x8B61
+#define GL_SAMPLER_2D_SHADOW              0x8B62
+#define GL_DELETE_STATUS                  0x8B80
+#define GL_COMPILE_STATUS                 0x8B81
+#define GL_LINK_STATUS                    0x8B82
+#define GL_VALIDATE_STATUS                0x8B83
+#define GL_INFO_LOG_LENGTH                0x8B84
+#define GL_ATTACHED_SHADERS               0x8B85
+#define GL_ACTIVE_UNIFORMS                0x8B86
+#define GL_ACTIVE_UNIFORM_MAX_LENGTH      0x8B87
+#define GL_SHADER_SOURCE_LENGTH           0x8B88
+#define GL_ACTIVE_ATTRIBUTES              0x8B89
+#define GL_ACTIVE_ATTRIBUTE_MAX_LENGTH    0x8B8A
+#define GL_FRAGMENT_SHADER_DERIVATIVE_HINT 0x8B8B
+#define GL_SHADING_LANGUAGE_VERSION       0x8B8C
+#define GL_CURRENT_PROGRAM                0x8B8D
+#define GL_POINT_SPRITE_COORD_ORIGIN      0x8CA0
+#define GL_LOWER_LEFT                     0x8CA1
+#define GL_UPPER_LEFT                     0x8CA2
+#define GL_STENCIL_BACK_REF               0x8CA3
+#define GL_STENCIL_BACK_VALUE_MASK        0x8CA4
+#define GL_STENCIL_BACK_WRITEMASK         0x8CA5
+#endif
+
+#ifndef GL_ARB_multitexture
+#define GL_TEXTURE0_ARB                   0x84C0
+#define GL_TEXTURE1_ARB                   0x84C1
+#define GL_TEXTURE2_ARB                   0x84C2
+#define GL_TEXTURE3_ARB                   0x84C3
+#define GL_TEXTURE4_ARB                   0x84C4
+#define GL_TEXTURE5_ARB                   0x84C5
+#define GL_TEXTURE6_ARB                   0x84C6
+#define GL_TEXTURE7_ARB                   0x84C7
+#define GL_TEXTURE8_ARB                   0x84C8
+#define GL_TEXTURE9_ARB                   0x84C9
+#define GL_TEXTURE10_ARB                  0x84CA
+#define GL_TEXTURE11_ARB                  0x84CB
+#define GL_TEXTURE12_ARB                  0x84CC
+#define GL_TEXTURE13_ARB                  0x84CD
+#define GL_TEXTURE14_ARB                  0x84CE
+#define GL_TEXTURE15_ARB                  0x84CF
+#define GL_TEXTURE16_ARB                  0x84D0
+#define GL_TEXTURE17_ARB                  0x84D1
+#define GL_TEXTURE18_ARB                  0x84D2
+#define GL_TEXTURE19_ARB                  0x84D3
+#define GL_TEXTURE20_ARB                  0x84D4
+#define GL_TEXTURE21_ARB                  0x84D5
+#define GL_TEXTURE22_ARB                  0x84D6
+#define GL_TEXTURE23_ARB                  0x84D7
+#define GL_TEXTURE24_ARB                  0x84D8
+#define GL_TEXTURE25_ARB                  0x84D9
+#define GL_TEXTURE26_ARB                  0x84DA
+#define GL_TEXTURE27_ARB                  0x84DB
+#define GL_TEXTURE28_ARB                  0x84DC
+#define GL_TEXTURE29_ARB                  0x84DD
+#define GL_TEXTURE30_ARB                  0x84DE
+#define GL_TEXTURE31_ARB                  0x84DF
+#define GL_ACTIVE_TEXTURE_ARB             0x84E0
+#define GL_CLIENT_ACTIVE_TEXTURE_ARB      0x84E1
+#define GL_MAX_TEXTURE_UNITS_ARB          0x84E2
+#endif
+
+#ifndef GL_ARB_transpose_matrix
+#define GL_TRANSPOSE_MODELVIEW_MATRIX_ARB 0x84E3
+#define GL_TRANSPOSE_PROJECTION_MATRIX_ARB 0x84E4
+#define GL_TRANSPOSE_TEXTURE_MATRIX_ARB   0x84E5
+#define GL_TRANSPOSE_COLOR_MATRIX_ARB     0x84E6
+#endif
+
+#ifndef GL_ARB_multisample
+#define GL_MULTISAMPLE_ARB                0x809D
+#define GL_SAMPLE_ALPHA_TO_COVERAGE_ARB   0x809E
+#define GL_SAMPLE_ALPHA_TO_ONE_ARB        0x809F
+#define GL_SAMPLE_COVERAGE_ARB            0x80A0
+#define GL_SAMPLE_BUFFERS_ARB             0x80A8
+#define GL_SAMPLES_ARB                    0x80A9
+#define GL_SAMPLE_COVERAGE_VALUE_ARB      0x80AA
+#define GL_SAMPLE_COVERAGE_INVERT_ARB     0x80AB
+#define GL_MULTISAMPLE_BIT_ARB            0x20000000
+#endif
+
+#ifndef GL_ARB_texture_env_add
+#endif
+
+#ifndef GL_ARB_texture_cube_map
+#define GL_NORMAL_MAP_ARB                 0x8511
+#define GL_REFLECTION_MAP_ARB             0x8512
+#define GL_TEXTURE_CUBE_MAP_ARB           0x8513
+#define GL_TEXTURE_BINDING_CUBE_MAP_ARB   0x8514
+#define GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB 0x8515
+#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB 0x8516
+#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB 0x8517
+#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB 0x8518
+#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB 0x8519
+#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB 0x851A
+#define GL_PROXY_TEXTURE_CUBE_MAP_ARB     0x851B
+#define GL_MAX_CUBE_MAP_TEXTURE_SIZE_ARB  0x851C
+#endif
+
+#ifndef GL_ARB_texture_compression
+#define GL_COMPRESSED_ALPHA_ARB           0x84E9
+#define GL_COMPRESSED_LUMINANCE_ARB       0x84EA
+#define GL_COMPRESSED_LUMINANCE_ALPHA_ARB 0x84EB
+#define GL_COMPRESSED_INTENSITY_ARB       0x84EC
+#define GL_COMPRESSED_RGB_ARB             0x84ED
+#define GL_COMPRESSED_RGBA_ARB            0x84EE
+#define GL_TEXTURE_COMPRESSION_HINT_ARB   0x84EF
+#define GL_TEXTURE_COMPRESSED_IMAGE_SIZE_ARB 0x86A0
+#define GL_TEXTURE_COMPRESSED_ARB         0x86A1
+#define GL_NUM_COMPRESSED_TEXTURE_FORMATS_ARB 0x86A2
+#define GL_COMPRESSED_TEXTURE_FORMATS_ARB 0x86A3
+#endif
+
+#ifndef GL_ARB_texture_border_clamp
+#define GL_CLAMP_TO_BORDER_ARB            0x812D
+#endif
+
+#ifndef GL_ARB_point_parameters
+#define GL_POINT_SIZE_MIN_ARB             0x8126
+#define GL_POINT_SIZE_MAX_ARB             0x8127
+#define GL_POINT_FADE_THRESHOLD_SIZE_ARB  0x8128
+#define GL_POINT_DISTANCE_ATTENUATION_ARB 0x8129
+#endif
+
+#ifndef GL_ARB_vertex_blend
+#define GL_MAX_VERTEX_UNITS_ARB           0x86A4
+#define GL_ACTIVE_VERTEX_UNITS_ARB        0x86A5
+#define GL_WEIGHT_SUM_UNITY_ARB           0x86A6
+#define GL_VERTEX_BLEND_ARB               0x86A7
+#define GL_CURRENT_WEIGHT_ARB             0x86A8
+#define GL_WEIGHT_ARRAY_TYPE_ARB          0x86A9
+#define GL_WEIGHT_ARRAY_STRIDE_ARB        0x86AA
+#define GL_WEIGHT_ARRAY_SIZE_ARB          0x86AB
+#define GL_WEIGHT_ARRAY_POINTER_ARB       0x86AC
+#define GL_WEIGHT_ARRAY_ARB               0x86AD
+#define GL_MODELVIEW0_ARB                 0x1700
+#define GL_MODELVIEW1_ARB                 0x850A
+#define GL_MODELVIEW2_ARB                 0x8722
+#define GL_MODELVIEW3_ARB                 0x8723
+#define GL_MODELVIEW4_ARB                 0x8724
+#define GL_MODELVIEW5_ARB                 0x8725
+#define GL_MODELVIEW6_ARB                 0x8726
+#define GL_MODELVIEW7_ARB                 0x8727
+#define GL_MODELVIEW8_ARB                 0x8728
+#define GL_MODELVIEW9_ARB                 0x8729
+#define GL_MODELVIEW10_ARB                0x872A
+#define GL_MODELVIEW11_ARB                0x872B
+#define GL_MODELVIEW12_ARB                0x872C
+#define GL_MODELVIEW13_ARB                0x872D
+#define GL_MODELVIEW14_ARB                0x872E
+#define GL_MODELVIEW15_ARB                0x872F
+#define GL_MODELVIEW16_ARB                0x8730
+#define GL_MODELVIEW17_ARB                0x8731
+#define GL_MODELVIEW18_ARB                0x8732
+#define GL_MODELVIEW19_ARB                0x8733
+#define GL_MODELVIEW20_ARB                0x8734
+#define GL_MODELVIEW21_ARB                0x8735
+#define GL_MODELVIEW22_ARB                0x8736
+#define GL_MODELVIEW23_ARB                0x8737
+#define GL_MODELVIEW24_ARB                0x8738
+#define GL_MODELVIEW25_ARB                0x8739
+#define GL_MODELVIEW26_ARB                0x873A
+#define GL_MODELVIEW27_ARB                0x873B
+#define GL_MODELVIEW28_ARB                0x873C
+#define GL_MODELVIEW29_ARB                0x873D
+#define GL_MODELVIEW30_ARB                0x873E
+#define GL_MODELVIEW31_ARB                0x873F
+#endif
+
+#ifndef GL_ARB_matrix_palette
+#define GL_MATRIX_PALETTE_ARB             0x8840
+#define GL_MAX_MATRIX_PALETTE_STACK_DEPTH_ARB 0x8841
+#define GL_MAX_PALETTE_MATRICES_ARB       0x8842
+#define GL_CURRENT_PALETTE_MATRIX_ARB     0x8843
+#define GL_MATRIX_INDEX_ARRAY_ARB         0x8844
+#define GL_CURRENT_MATRIX_INDEX_ARB       0x8845
+#define GL_MATRIX_INDEX_ARRAY_SIZE_ARB    0x8846
+#define GL_MATRIX_INDEX_ARRAY_TYPE_ARB    0x8847
+#define GL_MATRIX_INDEX_ARRAY_STRIDE_ARB  0x8848
+#define GL_MATRIX_INDEX_ARRAY_POINTER_ARB 0x8849
+#endif
+
+#ifndef GL_ARB_texture_env_combine
+#define GL_COMBINE_ARB                    0x8570
+#define GL_COMBINE_RGB_ARB                0x8571
+#define GL_COMBINE_ALPHA_ARB              0x8572
+#define GL_SOURCE0_RGB_ARB                0x8580
+#define GL_SOURCE1_RGB_ARB                0x8581
+#define GL_SOURCE2_RGB_ARB                0x8582
+#define GL_SOURCE0_ALPHA_ARB              0x8588
+#define GL_SOURCE1_ALPHA_ARB              0x8589
+#define GL_SOURCE2_ALPHA_ARB              0x858A
+#define GL_OPERAND0_RGB_ARB               0x8590
+#define GL_OPERAND1_RGB_ARB               0x8591
+#define GL_OPERAND2_RGB_ARB               0x8592
+#define GL_OPERAND0_ALPHA_ARB             0x8598
+#define GL_OPERAND1_ALPHA_ARB             0x8599
+#define GL_OPERAND2_ALPHA_ARB             0x859A
+#define GL_RGB_SCALE_ARB                  0x8573
+#define GL_ADD_SIGNED_ARB                 0x8574
+#define GL_INTERPOLATE_ARB                0x8575
+#define GL_SUBTRACT_ARB                   0x84E7
+#define GL_CONSTANT_ARB                   0x8576
+#define GL_PRIMARY_COLOR_ARB              0x8577
+#define GL_PREVIOUS_ARB                   0x8578
+#endif
+
+#ifndef GL_ARB_texture_env_crossbar
+#endif
+
+#ifndef GL_ARB_texture_env_dot3
+#define GL_DOT3_RGB_ARB                   0x86AE
+#define GL_DOT3_RGBA_ARB                  0x86AF
+#endif
+
+#ifndef GL_ARB_texture_mirrored_repeat
+#define GL_MIRRORED_REPEAT_ARB            0x8370
+#endif
+
+#ifndef GL_ARB_depth_texture
+#define GL_DEPTH_COMPONENT16_ARB          0x81A5
+#define GL_DEPTH_COMPONENT24_ARB          0x81A6
+#define GL_DEPTH_COMPONENT32_ARB          0x81A7
+#define GL_TEXTURE_DEPTH_SIZE_ARB         0x884A
+#define GL_DEPTH_TEXTURE_MODE_ARB         0x884B
+#endif
+
+#ifndef GL_ARB_shadow
+#define GL_TEXTURE_COMPARE_MODE_ARB       0x884C
+#define GL_TEXTURE_COMPARE_FUNC_ARB       0x884D
+#define GL_COMPARE_R_TO_TEXTURE_ARB       0x884E
+#endif
+
+#ifndef GL_ARB_shadow_ambient
+#define GL_TEXTURE_COMPARE_FAIL_VALUE_ARB 0x80BF
+#endif
+
+#ifndef GL_ARB_window_pos
+#endif
+
+#ifndef GL_ARB_vertex_program
+#define GL_COLOR_SUM_ARB                  0x8458
+#define GL_VERTEX_PROGRAM_ARB             0x8620
+#define GL_VERTEX_ATTRIB_ARRAY_ENABLED_ARB 0x8622
+#define GL_VERTEX_ATTRIB_ARRAY_SIZE_ARB   0x8623
+#define GL_VERTEX_ATTRIB_ARRAY_STRIDE_ARB 0x8624
+#define GL_VERTEX_ATTRIB_ARRAY_TYPE_ARB   0x8625
+#define GL_CURRENT_VERTEX_ATTRIB_ARB      0x8626
+#define GL_PROGRAM_LENGTH_ARB             0x8627
+#define GL_PROGRAM_STRING_ARB             0x8628
+#define GL_MAX_PROGRAM_MATRIX_STACK_DEPTH_ARB 0x862E
+#define GL_MAX_PROGRAM_MATRICES_ARB       0x862F
+#define GL_CURRENT_MATRIX_STACK_DEPTH_ARB 0x8640
+#define GL_CURRENT_MATRIX_ARB             0x8641
+#define GL_VERTEX_PROGRAM_POINT_SIZE_ARB  0x8642
+#define GL_VERTEX_PROGRAM_TWO_SIDE_ARB    0x8643
+#define GL_VERTEX_ATTRIB_ARRAY_POINTER_ARB 0x8645
+#define GL_PROGRAM_ERROR_POSITION_ARB     0x864B
+#define GL_PROGRAM_BINDING_ARB            0x8677
+#define GL_MAX_VERTEX_ATTRIBS_ARB         0x8869
+#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED_ARB 0x886A
+#define GL_PROGRAM_ERROR_STRING_ARB       0x8874
+#define GL_PROGRAM_FORMAT_ASCII_ARB       0x8875
+#define GL_PROGRAM_FORMAT_ARB             0x8876
+#define GL_PROGRAM_INSTRUCTIONS_ARB       0x88A0
+#define GL_MAX_PROGRAM_INSTRUCTIONS_ARB   0x88A1
+#define GL_PROGRAM_NATIVE_INSTRUCTIONS_ARB 0x88A2
+#define GL_MAX_PROGRAM_NATIVE_INSTRUCTIONS_ARB 0x88A3
+#define GL_PROGRAM_TEMPORARIES_ARB        0x88A4
+#define GL_MAX_PROGRAM_TEMPORARIES_ARB    0x88A5
+#define GL_PROGRAM_NATIVE_TEMPORARIES_ARB 0x88A6
+#define GL_MAX_PROGRAM_NATIVE_TEMPORARIES_ARB 0x88A7
+#define GL_PROGRAM_PARAMETERS_ARB         0x88A8
+#define GL_MAX_PROGRAM_PARAMETERS_ARB     0x88A9
+#define GL_PROGRAM_NATIVE_PARAMETERS_ARB  0x88AA
+#define GL_MAX_PROGRAM_NATIVE_PARAMETERS_ARB 0x88AB
+#define GL_PROGRAM_ATTRIBS_ARB            0x88AC
+#define GL_MAX_PROGRAM_ATTRIBS_ARB        0x88AD
+#define GL_PROGRAM_NATIVE_ATTRIBS_ARB     0x88AE
+#define GL_MAX_PROGRAM_NATIVE_ATTRIBS_ARB 0x88AF
+#define GL_PROGRAM_ADDRESS_REGISTERS_ARB  0x88B0
+#define GL_MAX_PROGRAM_ADDRESS_REGISTERS_ARB 0x88B1
+#define GL_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB 0x88B2
+#define GL_MAX_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB 0x88B3
+#define GL_MAX_PROGRAM_LOCAL_PARAMETERS_ARB 0x88B4
+#define GL_MAX_PROGRAM_ENV_PARAMETERS_ARB 0x88B5
+#define GL_PROGRAM_UNDER_NATIVE_LIMITS_ARB 0x88B6
+#define GL_TRANSPOSE_CURRENT_MATRIX_ARB   0x88B7
+#define GL_MATRIX0_ARB                    0x88C0
+#define GL_MATRIX1_ARB                    0x88C1
+#define GL_MATRIX2_ARB                    0x88C2
+#define GL_MATRIX3_ARB                    0x88C3
+#define GL_MATRIX4_ARB                    0x88C4
+#define GL_MATRIX5_ARB                    0x88C5
+#define GL_MATRIX6_ARB                    0x88C6
+#define GL_MATRIX7_ARB                    0x88C7
+#define GL_MATRIX8_ARB                    0x88C8
+#define GL_MATRIX9_ARB                    0x88C9
+#define GL_MATRIX10_ARB                   0x88CA
+#define GL_MATRIX11_ARB                   0x88CB
+#define GL_MATRIX12_ARB                   0x88CC
+#define GL_MATRIX13_ARB                   0x88CD
+#define GL_MATRIX14_ARB                   0x88CE
+#define GL_MATRIX15_ARB                   0x88CF
+#define GL_MATRIX16_ARB                   0x88D0
+#define GL_MATRIX17_ARB                   0x88D1
+#define GL_MATRIX18_ARB                   0x88D2
+#define GL_MATRIX19_ARB                   0x88D3
+#define GL_MATRIX20_ARB                   0x88D4
+#define GL_MATRIX21_ARB                   0x88D5
+#define GL_MATRIX22_ARB                   0x88D6
+#define GL_MATRIX23_ARB                   0x88D7
+#define GL_MATRIX24_ARB                   0x88D8
+#define GL_MATRIX25_ARB                   0x88D9
+#define GL_MATRIX26_ARB                   0x88DA
+#define GL_MATRIX27_ARB                   0x88DB
+#define GL_MATRIX28_ARB                   0x88DC
+#define GL_MATRIX29_ARB                   0x88DD
+#define GL_MATRIX30_ARB                   0x88DE
+#define GL_MATRIX31_ARB                   0x88DF
+#endif
+
+#ifndef GL_ARB_fragment_program
+#define GL_FRAGMENT_PROGRAM_ARB           0x8804
+#define GL_PROGRAM_ALU_INSTRUCTIONS_ARB   0x8805
+#define GL_PROGRAM_TEX_INSTRUCTIONS_ARB   0x8806
+#define GL_PROGRAM_TEX_INDIRECTIONS_ARB   0x8807
+#define GL_PROGRAM_NATIVE_ALU_INSTRUCTIONS_ARB 0x8808
+#define GL_PROGRAM_NATIVE_TEX_INSTRUCTIONS_ARB 0x8809
+#define GL_PROGRAM_NATIVE_TEX_INDIRECTIONS_ARB 0x880A
+#define GL_MAX_PROGRAM_ALU_INSTRUCTIONS_ARB 0x880B
+#define GL_MAX_PROGRAM_TEX_INSTRUCTIONS_ARB 0x880C
+#define GL_MAX_PROGRAM_TEX_INDIRECTIONS_ARB 0x880D
+#define GL_MAX_PROGRAM_NATIVE_ALU_INSTRUCTIONS_ARB 0x880E
+#define GL_MAX_PROGRAM_NATIVE_TEX_INSTRUCTIONS_ARB 0x880F
+#define GL_MAX_PROGRAM_NATIVE_TEX_INDIRECTIONS_ARB 0x8810
+#define GL_MAX_TEXTURE_COORDS_ARB         0x8871
+#define GL_MAX_TEXTURE_IMAGE_UNITS_ARB    0x8872
+#endif
+
+#ifndef GL_ARB_vertex_buffer_object
+#define GL_BUFFER_SIZE_ARB                0x8764
+#define GL_BUFFER_USAGE_ARB               0x8765
+#define GL_ARRAY_BUFFER_ARB               0x8892
+#define GL_ELEMENT_ARRAY_BUFFER_ARB       0x8893
+#define GL_ARRAY_BUFFER_BINDING_ARB       0x8894
+#define GL_ELEMENT_ARRAY_BUFFER_BINDING_ARB 0x8895
+#define GL_VERTEX_ARRAY_BUFFER_BINDING_ARB 0x8896
+#define GL_NORMAL_ARRAY_BUFFER_BINDING_ARB 0x8897
+#define GL_COLOR_ARRAY_BUFFER_BINDING_ARB 0x8898
+#define GL_INDEX_ARRAY_BUFFER_BINDING_ARB 0x8899
+#define GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING_ARB 0x889A
+#define GL_EDGE_FLAG_ARRAY_BUFFER_BINDING_ARB 0x889B
+#define GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING_ARB 0x889C
+#define GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING_ARB 0x889D
+#define GL_WEIGHT_ARRAY_BUFFER_BINDING_ARB 0x889E
+#define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING_ARB 0x889F
+#define GL_READ_ONLY_ARB                  0x88B8
+#define GL_WRITE_ONLY_ARB                 0x88B9
+#define GL_READ_WRITE_ARB                 0x88BA
+#define GL_BUFFER_ACCESS_ARB              0x88BB
+#define GL_BUFFER_MAPPED_ARB              0x88BC
+#define GL_BUFFER_MAP_POINTER_ARB         0x88BD
+#define GL_STREAM_DRAW_ARB                0x88E0
+#define GL_STREAM_READ_ARB                0x88E1
+#define GL_STREAM_COPY_ARB                0x88E2
+#define GL_STATIC_DRAW_ARB                0x88E4
+#define GL_STATIC_READ_ARB                0x88E5
+#define GL_STATIC_COPY_ARB                0x88E6
+#define GL_DYNAMIC_DRAW_ARB               0x88E8
+#define GL_DYNAMIC_READ_ARB               0x88E9
+#define GL_DYNAMIC_COPY_ARB               0x88EA
+#endif
+
+#ifndef GL_ARB_occlusion_query
+#define GL_QUERY_COUNTER_BITS_ARB         0x8864
+#define GL_CURRENT_QUERY_ARB              0x8865
+#define GL_QUERY_RESULT_ARB               0x8866
+#define GL_QUERY_RESULT_AVAILABLE_ARB     0x8867
+#define GL_SAMPLES_PASSED_ARB             0x8914
+#endif
+
+#ifndef GL_ARB_shader_objects
+#define GL_PROGRAM_OBJECT_ARB             0x8B40
+#define GL_SHADER_OBJECT_ARB              0x8B48
+#define GL_OBJECT_TYPE_ARB                0x8B4E
+#define GL_OBJECT_SUBTYPE_ARB             0x8B4F
+#define GL_FLOAT_VEC2_ARB                 0x8B50
+#define GL_FLOAT_VEC3_ARB                 0x8B51
+#define GL_FLOAT_VEC4_ARB                 0x8B52
+#define GL_INT_VEC2_ARB                   0x8B53
+#define GL_INT_VEC3_ARB                   0x8B54
+#define GL_INT_VEC4_ARB                   0x8B55
+#define GL_BOOL_ARB                       0x8B56
+#define GL_BOOL_VEC2_ARB                  0x8B57
+#define GL_BOOL_VEC3_ARB                  0x8B58
+#define GL_BOOL_VEC4_ARB                  0x8B59
+#define GL_FLOAT_MAT2_ARB                 0x8B5A
+#define GL_FLOAT_MAT3_ARB                 0x8B5B
+#define GL_FLOAT_MAT4_ARB                 0x8B5C
+#define GL_SAMPLER_1D_ARB                 0x8B5D
+#define GL_SAMPLER_2D_ARB                 0x8B5E
+#define GL_SAMPLER_3D_ARB                 0x8B5F
+#define GL_SAMPLER_CUBE_ARB               0x8B60
+#define GL_SAMPLER_1D_SHADOW_ARB          0x8B61
+#define GL_SAMPLER_2D_SHADOW_ARB          0x8B62
+#define GL_SAMPLER_2D_RECT_ARB            0x8B63
+#define GL_SAMPLER_2D_RECT_SHADOW_ARB     0x8B64
+#define GL_OBJECT_DELETE_STATUS_ARB       0x8B80
+#define GL_OBJECT_COMPILE_STATUS_ARB      0x8B81
+#define GL_OBJECT_LINK_STATUS_ARB         0x8B82
+#define GL_OBJECT_VALIDATE_STATUS_ARB     0x8B83
+#define GL_OBJECT_INFO_LOG_LENGTH_ARB     0x8B84
+#define GL_OBJECT_ATTACHED_OBJECTS_ARB    0x8B85
+#define GL_OBJECT_ACTIVE_UNIFORMS_ARB     0x8B86
+#define GL_OBJECT_ACTIVE_UNIFORM_MAX_LENGTH_ARB 0x8B87
+#define GL_OBJECT_SHADER_SOURCE_LENGTH_ARB 0x8B88
+#endif
+
+#ifndef GL_ARB_vertex_shader
+#define GL_VERTEX_SHADER_ARB              0x8B31
+#define GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB 0x8B4A
+#define GL_MAX_VARYING_FLOATS_ARB         0x8B4B
+#define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB 0x8B4C
+#define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB 0x8B4D
+#define GL_OBJECT_ACTIVE_ATTRIBUTES_ARB   0x8B89
+#define GL_OBJECT_ACTIVE_ATTRIBUTE_MAX_LENGTH_ARB 0x8B8A
+#endif
+
+#ifndef GL_ARB_fragment_shader
+#define GL_FRAGMENT_SHADER_ARB            0x8B30
+#define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS_ARB 0x8B49
+#define GL_FRAGMENT_SHADER_DERIVATIVE_HINT_ARB 0x8B8B
+#endif
+
+#ifndef GL_ARB_shading_language_100
+#define GL_SHADING_LANGUAGE_VERSION_ARB   0x8B8C
+#endif
+
+#ifndef GL_ARB_texture_non_power_of_two
+#endif
+
+#ifndef GL_ARB_point_sprite
+#define GL_POINT_SPRITE_ARB               0x8861
+#define GL_COORD_REPLACE_ARB              0x8862
+#endif
+
+#ifndef GL_ARB_fragment_program_shadow
+#endif
+
+#ifndef GL_ARB_draw_buffers
+#define GL_MAX_DRAW_BUFFERS_ARB           0x8824
+#define GL_DRAW_BUFFER0_ARB               0x8825
+#define GL_DRAW_BUFFER1_ARB               0x8826
+#define GL_DRAW_BUFFER2_ARB               0x8827
+#define GL_DRAW_BUFFER3_ARB               0x8828
+#define GL_DRAW_BUFFER4_ARB               0x8829
+#define GL_DRAW_BUFFER5_ARB               0x882A
+#define GL_DRAW_BUFFER6_ARB               0x882B
+#define GL_DRAW_BUFFER7_ARB               0x882C
+#define GL_DRAW_BUFFER8_ARB               0x882D
+#define GL_DRAW_BUFFER9_ARB               0x882E
+#define GL_DRAW_BUFFER10_ARB              0x882F
+#define GL_DRAW_BUFFER11_ARB              0x8830
+#define GL_DRAW_BUFFER12_ARB              0x8831
+#define GL_DRAW_BUFFER13_ARB              0x8832
+#define GL_DRAW_BUFFER14_ARB              0x8833
+#define GL_DRAW_BUFFER15_ARB              0x8834
+#endif
+
+#ifndef GL_ARB_texture_rectangle
+#define GL_TEXTURE_RECTANGLE_ARB          0x84F5
+#define GL_TEXTURE_BINDING_RECTANGLE_ARB  0x84F6
+#define GL_PROXY_TEXTURE_RECTANGLE_ARB    0x84F7
+#define GL_MAX_RECTANGLE_TEXTURE_SIZE_ARB 0x84F8
+#endif
+
+#ifndef GL_ARB_color_buffer_float
+#define GL_RGBA_FLOAT_MODE_ARB            0x8820
+#define GL_CLAMP_VERTEX_COLOR_ARB         0x891A
+#define GL_CLAMP_FRAGMENT_COLOR_ARB       0x891B
+#define GL_CLAMP_READ_COLOR_ARB           0x891C
+#define GL_FIXED_ONLY_ARB                 0x891D
+#endif
+
+#ifndef GL_ARB_half_float_pixel
+#define GL_HALF_FLOAT_ARB                 0x140B
+#endif
+
+#ifndef GL_ARB_texture_float
+#define GL_TEXTURE_RED_TYPE_ARB           0x8C10
+#define GL_TEXTURE_GREEN_TYPE_ARB         0x8C11
+#define GL_TEXTURE_BLUE_TYPE_ARB          0x8C12
+#define GL_TEXTURE_ALPHA_TYPE_ARB         0x8C13
+#define GL_TEXTURE_LUMINANCE_TYPE_ARB     0x8C14
+#define GL_TEXTURE_INTENSITY_TYPE_ARB     0x8C15
+#define GL_TEXTURE_DEPTH_TYPE_ARB         0x8C16
+#define GL_UNSIGNED_NORMALIZED_ARB        0x8C17
+#define GL_RGBA32F_ARB                    0x8814
+#define GL_RGB32F_ARB                     0x8815
+#define GL_ALPHA32F_ARB                   0x8816
+#define GL_INTENSITY32F_ARB               0x8817
+#define GL_LUMINANCE32F_ARB               0x8818
+#define GL_LUMINANCE_ALPHA32F_ARB         0x8819
+#define GL_RGBA16F_ARB                    0x881A
+#define GL_RGB16F_ARB                     0x881B
+#define GL_ALPHA16F_ARB                   0x881C
+#define GL_INTENSITY16F_ARB               0x881D
+#define GL_LUMINANCE16F_ARB               0x881E
+#define GL_LUMINANCE_ALPHA16F_ARB         0x881F
+#endif
+
+#ifndef GL_ARB_pixel_buffer_object
+#define GL_PIXEL_PACK_BUFFER_ARB          0x88EB
+#define GL_PIXEL_UNPACK_BUFFER_ARB        0x88EC
+#define GL_PIXEL_PACK_BUFFER_BINDING_ARB  0x88ED
+#define GL_PIXEL_UNPACK_BUFFER_BINDING_ARB 0x88EF
+#endif
+
+#ifndef GL_EXT_abgr
+#define GL_ABGR_EXT                       0x8000
+#endif
+
+#ifndef GL_EXT_blend_color
+#define GL_CONSTANT_COLOR_EXT             0x8001
+#define GL_ONE_MINUS_CONSTANT_COLOR_EXT   0x8002
+#define GL_CONSTANT_ALPHA_EXT             0x8003
+#define GL_ONE_MINUS_CONSTANT_ALPHA_EXT   0x8004
+#define GL_BLEND_COLOR_EXT                0x8005
+#endif
+
+#ifndef GL_EXT_polygon_offset
+#define GL_POLYGON_OFFSET_EXT             0x8037
+#define GL_POLYGON_OFFSET_FACTOR_EXT      0x8038
+#define GL_POLYGON_OFFSET_BIAS_EXT        0x8039
+#endif
+
+#ifndef GL_EXT_texture
+#define GL_ALPHA4_EXT                     0x803B
+#define GL_ALPHA8_EXT                     0x803C
+#define GL_ALPHA12_EXT                    0x803D
+#define GL_ALPHA16_EXT                    0x803E
+#define GL_LUMINANCE4_EXT                 0x803F
+#define GL_LUMINANCE8_EXT                 0x8040
+#define GL_LUMINANCE12_EXT                0x8041
+#define GL_LUMINANCE16_EXT                0x8042
+#define GL_LUMINANCE4_ALPHA4_EXT          0x8043
+#define GL_LUMINANCE6_ALPHA2_EXT          0x8044
+#define GL_LUMINANCE8_ALPHA8_EXT          0x8045
+#define GL_LUMINANCE12_ALPHA4_EXT         0x8046
+#define GL_LUMINANCE12_ALPHA12_EXT        0x8047
+#define GL_LUMINANCE16_ALPHA16_EXT        0x8048
+#define GL_INTENSITY_EXT                  0x8049
+#define GL_INTENSITY4_EXT                 0x804A
+#define GL_INTENSITY8_EXT                 0x804B
+#define GL_INTENSITY12_EXT                0x804C
+#define GL_INTENSITY16_EXT                0x804D
+#define GL_RGB2_EXT                       0x804E
+#define GL_RGB4_EXT                       0x804F
+#define GL_RGB5_EXT                       0x8050
+#define GL_RGB8_EXT                       0x8051
+#define GL_RGB10_EXT                      0x8052
+#define GL_RGB12_EXT                      0x8053
+#define GL_RGB16_EXT                      0x8054
+#define GL_RGBA2_EXT                      0x8055
+#define GL_RGBA4_EXT                      0x8056
+#define GL_RGB5_A1_EXT                    0x8057
+#define GL_RGBA8_EXT                      0x8058
+#define GL_RGB10_A2_EXT                   0x8059
+#define GL_RGBA12_EXT                     0x805A
+#define GL_RGBA16_EXT                     0x805B
+#define GL_TEXTURE_RED_SIZE_EXT           0x805C
+#define GL_TEXTURE_GREEN_SIZE_EXT         0x805D
+#define GL_TEXTURE_BLUE_SIZE_EXT          0x805E
+#define GL_TEXTURE_ALPHA_SIZE_EXT         0x805F
+#define GL_TEXTURE_LUMINANCE_SIZE_EXT     0x8060
+#define GL_TEXTURE_INTENSITY_SIZE_EXT     0x8061
+#define GL_REPLACE_EXT                    0x8062
+#define GL_PROXY_TEXTURE_1D_EXT           0x8063
+#define GL_PROXY_TEXTURE_2D_EXT           0x8064
+#define GL_TEXTURE_TOO_LARGE_EXT          0x8065
+#endif
+
+#ifndef GL_EXT_texture3D
+#define GL_PACK_SKIP_IMAGES_EXT           0x806B
+#define GL_PACK_IMAGE_HEIGHT_EXT          0x806C
+#define GL_UNPACK_SKIP_IMAGES_EXT         0x806D
+#define GL_UNPACK_IMAGE_HEIGHT_EXT        0x806E
+#define GL_TEXTURE_3D_EXT                 0x806F
+#define GL_PROXY_TEXTURE_3D_EXT           0x8070
+#define GL_TEXTURE_DEPTH_EXT              0x8071
+#define GL_TEXTURE_WRAP_R_EXT             0x8072
+#define GL_MAX_3D_TEXTURE_SIZE_EXT        0x8073
+#endif
+
+#ifndef GL_SGIS_texture_filter4
+#define GL_FILTER4_SGIS                   0x8146
+#define GL_TEXTURE_FILTER4_SIZE_SGIS      0x8147
+#endif
+
+#ifndef GL_EXT_subtexture
+#endif
+
+#ifndef GL_EXT_copy_texture
+#endif
+
+#ifndef GL_EXT_histogram
+#define GL_HISTOGRAM_EXT                  0x8024
+#define GL_PROXY_HISTOGRAM_EXT            0x8025
+#define GL_HISTOGRAM_WIDTH_EXT            0x8026
+#define GL_HISTOGRAM_FORMAT_EXT           0x8027
+#define GL_HISTOGRAM_RED_SIZE_EXT         0x8028
+#define GL_HISTOGRAM_GREEN_SIZE_EXT       0x8029
+#define GL_HISTOGRAM_BLUE_SIZE_EXT        0x802A
+#define GL_HISTOGRAM_ALPHA_SIZE_EXT       0x802B
+#define GL_HISTOGRAM_LUMINANCE_SIZE_EXT   0x802C
+#define GL_HISTOGRAM_SINK_EXT             0x802D
+#define GL_MINMAX_EXT                     0x802E
+#define GL_MINMAX_FORMAT_EXT              0x802F
+#define GL_MINMAX_SINK_EXT                0x8030
+#define GL_TABLE_TOO_LARGE_EXT            0x8031
+#endif
+
+#ifndef GL_EXT_convolution
+#define GL_CONVOLUTION_1D_EXT             0x8010
+#define GL_CONVOLUTION_2D_EXT             0x8011
+#define GL_SEPARABLE_2D_EXT               0x8012
+#define GL_CONVOLUTION_BORDER_MODE_EXT    0x8013
+#define GL_CONVOLUTION_FILTER_SCALE_EXT   0x8014
+#define GL_CONVOLUTION_FILTER_BIAS_EXT    0x8015
+#define GL_REDUCE_EXT                     0x8016
+#define GL_CONVOLUTION_FORMAT_EXT         0x8017
+#define GL_CONVOLUTION_WIDTH_EXT          0x8018
+#define GL_CONVOLUTION_HEIGHT_EXT         0x8019
+#define GL_MAX_CONVOLUTION_WIDTH_EXT      0x801A
+#define GL_MAX_CONVOLUTION_HEIGHT_EXT     0x801B
+#define GL_POST_CONVOLUTION_RED_SCALE_EXT 0x801C
+#define GL_POST_CONVOLUTION_GREEN_SCALE_EXT 0x801D
+#define GL_POST_CONVOLUTION_BLUE_SCALE_EXT 0x801E
+#define GL_POST_CONVOLUTION_ALPHA_SCALE_EXT 0x801F
+#define GL_POST_CONVOLUTION_RED_BIAS_EXT  0x8020
+#define GL_POST_CONVOLUTION_GREEN_BIAS_EXT 0x8021
+#define GL_POST_CONVOLUTION_BLUE_BIAS_EXT 0x8022
+#define GL_POST_CONVOLUTION_ALPHA_BIAS_EXT 0x8023
+#endif
+
+#ifndef GL_SGI_color_matrix
+#define GL_COLOR_MATRIX_SGI               0x80B1
+#define GL_COLOR_MATRIX_STACK_DEPTH_SGI   0x80B2
+#define GL_MAX_COLOR_MATRIX_STACK_DEPTH_SGI 0x80B3
+#define GL_POST_COLOR_MATRIX_RED_SCALE_SGI 0x80B4
+#define GL_POST_COLOR_MATRIX_GREEN_SCALE_SGI 0x80B5
+#define GL_POST_COLOR_MATRIX_BLUE_SCALE_SGI 0x80B6
+#define GL_POST_COLOR_MATRIX_ALPHA_SCALE_SGI 0x80B7
+#define GL_POST_COLOR_MATRIX_RED_BIAS_SGI 0x80B8
+#define GL_POST_COLOR_MATRIX_GREEN_BIAS_SGI 0x80B9
+#define GL_POST_COLOR_MATRIX_BLUE_BIAS_SGI 0x80BA
+#define GL_POST_COLOR_MATRIX_ALPHA_BIAS_SGI 0x80BB
+#endif
+
+#ifndef GL_SGI_color_table
+#define GL_COLOR_TABLE_SGI                0x80D0
+#define GL_POST_CONVOLUTION_COLOR_TABLE_SGI 0x80D1
+#define GL_POST_COLOR_MATRIX_COLOR_TABLE_SGI 0x80D2
+#define GL_PROXY_COLOR_TABLE_SGI          0x80D3
+#define GL_PROXY_POST_CONVOLUTION_COLOR_TABLE_SGI 0x80D4
+#define GL_PROXY_POST_COLOR_MATRIX_COLOR_TABLE_SGI 0x80D5
+#define GL_COLOR_TABLE_SCALE_SGI          0x80D6
+#define GL_COLOR_TABLE_BIAS_SGI           0x80D7
+#define GL_COLOR_TABLE_FORMAT_SGI         0x80D8
+#define GL_COLOR_TABLE_WIDTH_SGI          0x80D9
+#define GL_COLOR_TABLE_RED_SIZE_SGI       0x80DA
+#define GL_COLOR_TABLE_GREEN_SIZE_SGI     0x80DB
+#define GL_COLOR_TABLE_BLUE_SIZE_SGI      0x80DC
+#define GL_COLOR_TABLE_ALPHA_SIZE_SGI     0x80DD
+#define GL_COLOR_TABLE_LUMINANCE_SIZE_SGI 0x80DE
+#define GL_COLOR_TABLE_INTENSITY_SIZE_SGI 0x80DF
+#endif
+
+#ifndef GL_SGIS_pixel_texture
+#define GL_PIXEL_TEXTURE_SGIS             0x8353
+#define GL_PIXEL_FRAGMENT_RGB_SOURCE_SGIS 0x8354
+#define GL_PIXEL_FRAGMENT_ALPHA_SOURCE_SGIS 0x8355
+#define GL_PIXEL_GROUP_COLOR_SGIS         0x8356
+#endif
+
+#ifndef GL_SGIX_pixel_texture
+#define GL_PIXEL_TEX_GEN_SGIX             0x8139
+#define GL_PIXEL_TEX_GEN_MODE_SGIX        0x832B
+#endif
+
+#ifndef GL_SGIS_texture4D
+#define GL_PACK_SKIP_VOLUMES_SGIS         0x8130
+#define GL_PACK_IMAGE_DEPTH_SGIS          0x8131
+#define GL_UNPACK_SKIP_VOLUMES_SGIS       0x8132
+#define GL_UNPACK_IMAGE_DEPTH_SGIS        0x8133
+#define GL_TEXTURE_4D_SGIS                0x8134
+#define GL_PROXY_TEXTURE_4D_SGIS          0x8135
+#define GL_TEXTURE_4DSIZE_SGIS            0x8136
+#define GL_TEXTURE_WRAP_Q_SGIS            0x8137
+#define GL_MAX_4D_TEXTURE_SIZE_SGIS       0x8138
+#define GL_TEXTURE_4D_BINDING_SGIS        0x814F
+#endif
+
+#ifndef GL_SGI_texture_color_table
+#define GL_TEXTURE_COLOR_TABLE_SGI        0x80BC
+#define GL_PROXY_TEXTURE_COLOR_TABLE_SGI  0x80BD
+#endif
+
+#ifndef GL_EXT_cmyka
+#define GL_CMYK_EXT                       0x800C
+#define GL_CMYKA_EXT                      0x800D
+#define GL_PACK_CMYK_HINT_EXT             0x800E
+#define GL_UNPACK_CMYK_HINT_EXT           0x800F
+#endif
+
+#ifndef GL_EXT_texture_object
+#define GL_TEXTURE_PRIORITY_EXT           0x8066
+#define GL_TEXTURE_RESIDENT_EXT           0x8067
+#define GL_TEXTURE_1D_BINDING_EXT         0x8068
+#define GL_TEXTURE_2D_BINDING_EXT         0x8069
+#define GL_TEXTURE_3D_BINDING_EXT         0x806A
+#endif
+
+#ifndef GL_SGIS_detail_texture
+#define GL_DETAIL_TEXTURE_2D_SGIS         0x8095
+#define GL_DETAIL_TEXTURE_2D_BINDING_SGIS 0x8096
+#define GL_LINEAR_DETAIL_SGIS             0x8097
+#define GL_LINEAR_DETAIL_ALPHA_SGIS       0x8098
+#define GL_LINEAR_DETAIL_COLOR_SGIS       0x8099
+#define GL_DETAIL_TEXTURE_LEVEL_SGIS      0x809A
+#define GL_DETAIL_TEXTURE_MODE_SGIS       0x809B
+#define GL_DETAIL_TEXTURE_FUNC_POINTS_SGIS 0x809C
+#endif
+
+#ifndef GL_SGIS_sharpen_texture
+#define GL_LINEAR_SHARPEN_SGIS            0x80AD
+#define GL_LINEAR_SHARPEN_ALPHA_SGIS      0x80AE
+#define GL_LINEAR_SHARPEN_COLOR_SGIS      0x80AF
+#define GL_SHARPEN_TEXTURE_FUNC_POINTS_SGIS 0x80B0
+#endif
+
+#ifndef GL_EXT_packed_pixels
+#define GL_UNSIGNED_BYTE_3_3_2_EXT        0x8032
+#define GL_UNSIGNED_SHORT_4_4_4_4_EXT     0x8033
+#define GL_UNSIGNED_SHORT_5_5_5_1_EXT     0x8034
+#define GL_UNSIGNED_INT_8_8_8_8_EXT       0x8035
+#define GL_UNSIGNED_INT_10_10_10_2_EXT    0x8036
+#endif
+
+#ifndef GL_SGIS_texture_lod
+#define GL_TEXTURE_MIN_LOD_SGIS           0x813A
+#define GL_TEXTURE_MAX_LOD_SGIS           0x813B
+#define GL_TEXTURE_BASE_LEVEL_SGIS        0x813C
+#define GL_TEXTURE_MAX_LEVEL_SGIS         0x813D
+#endif
+
+#ifndef GL_SGIS_multisample
+#define GL_MULTISAMPLE_SGIS               0x809D
+#define GL_SAMPLE_ALPHA_TO_MASK_SGIS      0x809E
+#define GL_SAMPLE_ALPHA_TO_ONE_SGIS       0x809F
+#define GL_SAMPLE_MASK_SGIS               0x80A0
+#define GL_1PASS_SGIS                     0x80A1
+#define GL_2PASS_0_SGIS                   0x80A2
+#define GL_2PASS_1_SGIS                   0x80A3
+#define GL_4PASS_0_SGIS                   0x80A4
+#define GL_4PASS_1_SGIS                   0x80A5
+#define GL_4PASS_2_SGIS                   0x80A6
+#define GL_4PASS_3_SGIS                   0x80A7
+#define GL_SAMPLE_BUFFERS_SGIS            0x80A8
+#define GL_SAMPLES_SGIS                   0x80A9
+#define GL_SAMPLE_MASK_VALUE_SGIS         0x80AA
+#define GL_SAMPLE_MASK_INVERT_SGIS        0x80AB
+#define GL_SAMPLE_PATTERN_SGIS            0x80AC
+#endif
+
+#ifndef GL_EXT_rescale_normal
+#define GL_RESCALE_NORMAL_EXT             0x803A
+#endif
+
+#ifndef GL_EXT_vertex_array
+#define GL_VERTEX_ARRAY_EXT               0x8074
+#define GL_NORMAL_ARRAY_EXT               0x8075
+#define GL_COLOR_ARRAY_EXT                0x8076
+#define GL_INDEX_ARRAY_EXT                0x8077
+#define GL_TEXTURE_COORD_ARRAY_EXT        0x8078
+#define GL_EDGE_FLAG_ARRAY_EXT            0x8079
+#define GL_VERTEX_ARRAY_SIZE_EXT          0x807A
+#define GL_VERTEX_ARRAY_TYPE_EXT          0x807B
+#define GL_VERTEX_ARRAY_STRIDE_EXT        0x807C
+#define GL_VERTEX_ARRAY_COUNT_EXT         0x807D
+#define GL_NORMAL_ARRAY_TYPE_EXT          0x807E
+#define GL_NORMAL_ARRAY_STRIDE_EXT        0x807F
+#define GL_NORMAL_ARRAY_COUNT_EXT         0x8080
+#define GL_COLOR_ARRAY_SIZE_EXT           0x8081
+#define GL_COLOR_ARRAY_TYPE_EXT           0x8082
+#define GL_COLOR_ARRAY_STRIDE_EXT         0x8083
+#define GL_COLOR_ARRAY_COUNT_EXT          0x8084
+#define GL_INDEX_ARRAY_TYPE_EXT           0x8085
+#define GL_INDEX_ARRAY_STRIDE_EXT         0x8086
+#define GL_INDEX_ARRAY_COUNT_EXT          0x8087
+#define GL_TEXTURE_COORD_ARRAY_SIZE_EXT   0x8088
+#define GL_TEXTURE_COORD_ARRAY_TYPE_EXT   0x8089
+#define GL_TEXTURE_COORD_ARRAY_STRIDE_EXT 0x808A
+#define GL_TEXTURE_COORD_ARRAY_COUNT_EXT  0x808B
+#define GL_EDGE_FLAG_ARRAY_STRIDE_EXT     0x808C
+#define GL_EDGE_FLAG_ARRAY_COUNT_EXT      0x808D
+#define GL_VERTEX_ARRAY_POINTER_EXT       0x808E
+#define GL_NORMAL_ARRAY_POINTER_EXT       0x808F
+#define GL_COLOR_ARRAY_POINTER_EXT        0x8090
+#define GL_INDEX_ARRAY_POINTER_EXT        0x8091
+#define GL_TEXTURE_COORD_ARRAY_POINTER_EXT 0x8092
+#define GL_EDGE_FLAG_ARRAY_POINTER_EXT    0x8093
+#endif
+
+#ifndef GL_EXT_misc_attribute
+#endif
+
+#ifndef GL_SGIS_generate_mipmap
+#define GL_GENERATE_MIPMAP_SGIS           0x8191
+#define GL_GENERATE_MIPMAP_HINT_SGIS      0x8192
+#endif
+
+#ifndef GL_SGIX_clipmap
+#define GL_LINEAR_CLIPMAP_LINEAR_SGIX     0x8170
+#define GL_TEXTURE_CLIPMAP_CENTER_SGIX    0x8171
+#define GL_TEXTURE_CLIPMAP_FRAME_SGIX     0x8172
+#define GL_TEXTURE_CLIPMAP_OFFSET_SGIX    0x8173
+#define GL_TEXTURE_CLIPMAP_VIRTUAL_DEPTH_SGIX 0x8174
+#define GL_TEXTURE_CLIPMAP_LOD_OFFSET_SGIX 0x8175
+#define GL_TEXTURE_CLIPMAP_DEPTH_SGIX     0x8176
+#define GL_MAX_CLIPMAP_DEPTH_SGIX         0x8177
+#define GL_MAX_CLIPMAP_VIRTUAL_DEPTH_SGIX 0x8178
+#define GL_NEAREST_CLIPMAP_NEAREST_SGIX   0x844D
+#define GL_NEAREST_CLIPMAP_LINEAR_SGIX    0x844E
+#define GL_LINEAR_CLIPMAP_NEAREST_SGIX    0x844F
+#endif
+
+#ifndef GL_SGIX_shadow
+#define GL_TEXTURE_COMPARE_SGIX           0x819A
+#define GL_TEXTURE_COMPARE_OPERATOR_SGIX  0x819B
+#define GL_TEXTURE_LEQUAL_R_SGIX          0x819C
+#define GL_TEXTURE_GEQUAL_R_SGIX          0x819D
+#endif
+
+#ifndef GL_SGIS_texture_edge_clamp
+#define GL_CLAMP_TO_EDGE_SGIS             0x812F
+#endif
+
+#ifndef GL_SGIS_texture_border_clamp
+#define GL_CLAMP_TO_BORDER_SGIS           0x812D
+#endif
+
+#ifndef GL_EXT_blend_minmax
+#define GL_FUNC_ADD_EXT                   0x8006
+#define GL_MIN_EXT                        0x8007
+#define GL_MAX_EXT                        0x8008
+#define GL_BLEND_EQUATION_EXT             0x8009
+#endif
+
+#ifndef GL_EXT_blend_subtract
+#define GL_FUNC_SUBTRACT_EXT              0x800A
+#define GL_FUNC_REVERSE_SUBTRACT_EXT      0x800B
+#endif
+
+#ifndef GL_EXT_blend_logic_op
+#endif
+
+#ifndef GL_SGIX_interlace
+#define GL_INTERLACE_SGIX                 0x8094
+#endif
+
+#ifndef GL_SGIX_pixel_tiles
+#define GL_PIXEL_TILE_BEST_ALIGNMENT_SGIX 0x813E
+#define GL_PIXEL_TILE_CACHE_INCREMENT_SGIX 0x813F
+#define GL_PIXEL_TILE_WIDTH_SGIX          0x8140
+#define GL_PIXEL_TILE_HEIGHT_SGIX         0x8141
+#define GL_PIXEL_TILE_GRID_WIDTH_SGIX     0x8142
+#define GL_PIXEL_TILE_GRID_HEIGHT_SGIX    0x8143
+#define GL_PIXEL_TILE_GRID_DEPTH_SGIX     0x8144
+#define GL_PIXEL_TILE_CACHE_SIZE_SGIX     0x8145
+#endif
+
+#ifndef GL_SGIS_texture_select
+#define GL_DUAL_ALPHA4_SGIS               0x8110
+#define GL_DUAL_ALPHA8_SGIS               0x8111
+#define GL_DUAL_ALPHA12_SGIS              0x8112
+#define GL_DUAL_ALPHA16_SGIS              0x8113
+#define GL_DUAL_LUMINANCE4_SGIS           0x8114
+#define GL_DUAL_LUMINANCE8_SGIS           0x8115
+#define GL_DUAL_LUMINANCE12_SGIS          0x8116
+#define GL_DUAL_LUMINANCE16_SGIS          0x8117
+#define GL_DUAL_INTENSITY4_SGIS           0x8118
+#define GL_DUAL_INTENSITY8_SGIS           0x8119
+#define GL_DUAL_INTENSITY12_SGIS          0x811A
+#define GL_DUAL_INTENSITY16_SGIS          0x811B
+#define GL_DUAL_LUMINANCE_ALPHA4_SGIS     0x811C
+#define GL_DUAL_LUMINANCE_ALPHA8_SGIS     0x811D
+#define GL_QUAD_ALPHA4_SGIS               0x811E
+#define GL_QUAD_ALPHA8_SGIS               0x811F
+#define GL_QUAD_LUMINANCE4_SGIS           0x8120
+#define GL_QUAD_LUMINANCE8_SGIS           0x8121
+#define GL_QUAD_INTENSITY4_SGIS           0x8122
+#define GL_QUAD_INTENSITY8_SGIS           0x8123
+#define GL_DUAL_TEXTURE_SELECT_SGIS       0x8124
+#define GL_QUAD_TEXTURE_SELECT_SGIS       0x8125
+#endif
+
+#ifndef GL_SGIX_sprite
+#define GL_SPRITE_SGIX                    0x8148
+#define GL_SPRITE_MODE_SGIX               0x8149
+#define GL_SPRITE_AXIS_SGIX               0x814A
+#define GL_SPRITE_TRANSLATION_SGIX        0x814B
+#define GL_SPRITE_AXIAL_SGIX              0x814C
+#define GL_SPRITE_OBJECT_ALIGNED_SGIX     0x814D
+#define GL_SPRITE_EYE_ALIGNED_SGIX        0x814E
+#endif
+
+#ifndef GL_SGIX_texture_multi_buffer
+#define GL_TEXTURE_MULTI_BUFFER_HINT_SGIX 0x812E
+#endif
+
+#ifndef GL_EXT_point_parameters
+#define GL_POINT_SIZE_MIN_EXT             0x8126
+#define GL_POINT_SIZE_MAX_EXT             0x8127
+#define GL_POINT_FADE_THRESHOLD_SIZE_EXT  0x8128
+#define GL_DISTANCE_ATTENUATION_EXT       0x8129
+#endif
+
+#ifndef GL_SGIS_point_parameters
+#define GL_POINT_SIZE_MIN_SGIS            0x8126
+#define GL_POINT_SIZE_MAX_SGIS            0x8127
+#define GL_POINT_FADE_THRESHOLD_SIZE_SGIS 0x8128
+#define GL_DISTANCE_ATTENUATION_SGIS      0x8129
+#endif
+
+#ifndef GL_SGIX_instruments
+#define GL_INSTRUMENT_BUFFER_POINTER_SGIX 0x8180
+#define GL_INSTRUMENT_MEASUREMENTS_SGIX   0x8181
+#endif
+
+#ifndef GL_SGIX_texture_scale_bias
+#define GL_POST_TEXTURE_FILTER_BIAS_SGIX  0x8179
+#define GL_POST_TEXTURE_FILTER_SCALE_SGIX 0x817A
+#define GL_POST_TEXTURE_FILTER_BIAS_RANGE_SGIX 0x817B
+#define GL_POST_TEXTURE_FILTER_SCALE_RANGE_SGIX 0x817C
+#endif
+
+#ifndef GL_SGIX_framezoom
+#define GL_FRAMEZOOM_SGIX                 0x818B
+#define GL_FRAMEZOOM_FACTOR_SGIX          0x818C
+#define GL_MAX_FRAMEZOOM_FACTOR_SGIX      0x818D
+#endif
+
+#ifndef GL_SGIX_tag_sample_buffer
+#endif
+
+#ifndef GL_FfdMaskSGIX
+#define GL_TEXTURE_DEFORMATION_BIT_SGIX   0x00000001
+#define GL_GEOMETRY_DEFORMATION_BIT_SGIX  0x00000002
+#endif
+
+#ifndef GL_SGIX_polynomial_ffd
+#define GL_GEOMETRY_DEFORMATION_SGIX      0x8194
+#define GL_TEXTURE_DEFORMATION_SGIX       0x8195
+#define GL_DEFORMATIONS_MASK_SGIX         0x8196
+#define GL_MAX_DEFORMATION_ORDER_SGIX     0x8197
+#endif
+
+#ifndef GL_SGIX_reference_plane
+#define GL_REFERENCE_PLANE_SGIX           0x817D
+#define GL_REFERENCE_PLANE_EQUATION_SGIX  0x817E
+#endif
+
+#ifndef GL_SGIX_flush_raster
+#endif
+
+#ifndef GL_SGIX_depth_texture
+#define GL_DEPTH_COMPONENT16_SGIX         0x81A5
+#define GL_DEPTH_COMPONENT24_SGIX         0x81A6
+#define GL_DEPTH_COMPONENT32_SGIX         0x81A7
+#endif
+
+#ifndef GL_SGIS_fog_function
+#define GL_FOG_FUNC_SGIS                  0x812A
+#define GL_FOG_FUNC_POINTS_SGIS           0x812B
+#define GL_MAX_FOG_FUNC_POINTS_SGIS       0x812C
+#endif
+
+#ifndef GL_SGIX_fog_offset
+#define GL_FOG_OFFSET_SGIX                0x8198
+#define GL_FOG_OFFSET_VALUE_SGIX          0x8199
+#endif
+
+#ifndef GL_HP_image_transform
+#define GL_IMAGE_SCALE_X_HP               0x8155
+#define GL_IMAGE_SCALE_Y_HP               0x8156
+#define GL_IMAGE_TRANSLATE_X_HP           0x8157
+#define GL_IMAGE_TRANSLATE_Y_HP           0x8158
+#define GL_IMAGE_ROTATE_ANGLE_HP          0x8159
+#define GL_IMAGE_ROTATE_ORIGIN_X_HP       0x815A
+#define GL_IMAGE_ROTATE_ORIGIN_Y_HP       0x815B
+#define GL_IMAGE_MAG_FILTER_HP            0x815C
+#define GL_IMAGE_MIN_FILTER_HP            0x815D
+#define GL_IMAGE_CUBIC_WEIGHT_HP          0x815E
+#define GL_CUBIC_HP                       0x815F
+#define GL_AVERAGE_HP                     0x8160
+#define GL_IMAGE_TRANSFORM_2D_HP          0x8161
+#define GL_POST_IMAGE_TRANSFORM_COLOR_TABLE_HP 0x8162
+#define GL_PROXY_POST_IMAGE_TRANSFORM_COLOR_TABLE_HP 0x8163
+#endif
+
+#ifndef GL_HP_convolution_border_modes
+#define GL_IGNORE_BORDER_HP               0x8150
+#define GL_CONSTANT_BORDER_HP             0x8151
+#define GL_REPLICATE_BORDER_HP            0x8153
+#define GL_CONVOLUTION_BORDER_COLOR_HP    0x8154
+#endif
+
+#ifndef GL_INGR_palette_buffer
+#endif
+
+#ifndef GL_SGIX_texture_add_env
+#define GL_TEXTURE_ENV_BIAS_SGIX          0x80BE
+#endif
+
+#ifndef GL_EXT_color_subtable
+#endif
+
+#ifndef GL_PGI_vertex_hints
+#define GL_VERTEX_DATA_HINT_PGI           0x1A22A
+#define GL_VERTEX_CONSISTENT_HINT_PGI     0x1A22B
+#define GL_MATERIAL_SIDE_HINT_PGI         0x1A22C
+#define GL_MAX_VERTEX_HINT_PGI            0x1A22D
+#define GL_COLOR3_BIT_PGI                 0x00010000
+#define GL_COLOR4_BIT_PGI                 0x00020000
+#define GL_EDGEFLAG_BIT_PGI               0x00040000
+#define GL_INDEX_BIT_PGI                  0x00080000
+#define GL_MAT_AMBIENT_BIT_PGI            0x00100000
+#define GL_MAT_AMBIENT_AND_DIFFUSE_BIT_PGI 0x00200000
+#define GL_MAT_DIFFUSE_BIT_PGI            0x00400000
+#define GL_MAT_EMISSION_BIT_PGI           0x00800000
+#define GL_MAT_COLOR_INDEXES_BIT_PGI      0x01000000
+#define GL_MAT_SHININESS_BIT_PGI          0x02000000
+#define GL_MAT_SPECULAR_BIT_PGI           0x04000000
+#define GL_NORMAL_BIT_PGI                 0x08000000
+#define GL_TEXCOORD1_BIT_PGI              0x10000000
+#define GL_TEXCOORD2_BIT_PGI              0x20000000
+#define GL_TEXCOORD3_BIT_PGI              0x40000000
+#define GL_TEXCOORD4_BIT_PGI              0x80000000
+#define GL_VERTEX23_BIT_PGI               0x00000004
+#define GL_VERTEX4_BIT_PGI                0x00000008
+#endif
+
+#ifndef GL_PGI_misc_hints
+#define GL_PREFER_DOUBLEBUFFER_HINT_PGI   0x1A1F8
+#define GL_CONSERVE_MEMORY_HINT_PGI       0x1A1FD
+#define GL_RECLAIM_MEMORY_HINT_PGI        0x1A1FE
+#define GL_NATIVE_GRAPHICS_HANDLE_PGI     0x1A202
+#define GL_NATIVE_GRAPHICS_BEGIN_HINT_PGI 0x1A203
+#define GL_NATIVE_GRAPHICS_END_HINT_PGI   0x1A204
+#define GL_ALWAYS_FAST_HINT_PGI           0x1A20C
+#define GL_ALWAYS_SOFT_HINT_PGI           0x1A20D
+#define GL_ALLOW_DRAW_OBJ_HINT_PGI        0x1A20E
+#define GL_ALLOW_DRAW_WIN_HINT_PGI        0x1A20F
+#define GL_ALLOW_DRAW_FRG_HINT_PGI        0x1A210
+#define GL_ALLOW_DRAW_MEM_HINT_PGI        0x1A211
+#define GL_STRICT_DEPTHFUNC_HINT_PGI      0x1A216
+#define GL_STRICT_LIGHTING_HINT_PGI       0x1A217
+#define GL_STRICT_SCISSOR_HINT_PGI        0x1A218
+#define GL_FULL_STIPPLE_HINT_PGI          0x1A219
+#define GL_CLIP_NEAR_HINT_PGI             0x1A220
+#define GL_CLIP_FAR_HINT_PGI              0x1A221
+#define GL_WIDE_LINE_HINT_PGI             0x1A222
+#define GL_BACK_NORMALS_HINT_PGI          0x1A223
+#endif
+
+#ifndef GL_EXT_paletted_texture
+#define GL_COLOR_INDEX1_EXT               0x80E2
+#define GL_COLOR_INDEX2_EXT               0x80E3
+#define GL_COLOR_INDEX4_EXT               0x80E4
+#define GL_COLOR_INDEX8_EXT               0x80E5
+#define GL_COLOR_INDEX12_EXT              0x80E6
+#define GL_COLOR_INDEX16_EXT              0x80E7
+#define GL_TEXTURE_INDEX_SIZE_EXT         0x80ED
+#endif
+
+#ifndef GL_EXT_clip_volume_hint
+#define GL_CLIP_VOLUME_CLIPPING_HINT_EXT  0x80F0
+#endif
+
+#ifndef GL_SGIX_list_priority
+#define GL_LIST_PRIORITY_SGIX             0x8182
+#endif
+
+#ifndef GL_SGIX_ir_instrument1
+#define GL_IR_INSTRUMENT1_SGIX            0x817F
+#endif
+
+#ifndef GL_SGIX_calligraphic_fragment
+#define GL_CALLIGRAPHIC_FRAGMENT_SGIX     0x8183
+#endif
+
+#ifndef GL_SGIX_texture_lod_bias
+#define GL_TEXTURE_LOD_BIAS_S_SGIX        0x818E
+#define GL_TEXTURE_LOD_BIAS_T_SGIX        0x818F
+#define GL_TEXTURE_LOD_BIAS_R_SGIX        0x8190
+#endif
+
+#ifndef GL_SGIX_shadow_ambient
+#define GL_SHADOW_AMBIENT_SGIX            0x80BF
+#endif
+
+#ifndef GL_EXT_index_texture
+#endif
+
+#ifndef GL_EXT_index_material
+#define GL_INDEX_MATERIAL_EXT             0x81B8
+#define GL_INDEX_MATERIAL_PARAMETER_EXT   0x81B9
+#define GL_INDEX_MATERIAL_FACE_EXT        0x81BA
+#endif
+
+#ifndef GL_EXT_index_func
+#define GL_INDEX_TEST_EXT                 0x81B5
+#define GL_INDEX_TEST_FUNC_EXT            0x81B6
+#define GL_INDEX_TEST_REF_EXT             0x81B7
+#endif
+
+#ifndef GL_EXT_index_array_formats
+#define GL_IUI_V2F_EXT                    0x81AD
+#define GL_IUI_V3F_EXT                    0x81AE
+#define GL_IUI_N3F_V2F_EXT                0x81AF
+#define GL_IUI_N3F_V3F_EXT                0x81B0
+#define GL_T2F_IUI_V2F_EXT                0x81B1
+#define GL_T2F_IUI_V3F_EXT                0x81B2
+#define GL_T2F_IUI_N3F_V2F_EXT            0x81B3
+#define GL_T2F_IUI_N3F_V3F_EXT            0x81B4
+#endif
+
+#ifndef GL_EXT_compiled_vertex_array
+#define GL_ARRAY_ELEMENT_LOCK_FIRST_EXT   0x81A8
+#define GL_ARRAY_ELEMENT_LOCK_COUNT_EXT   0x81A9
+#endif
+
+#ifndef GL_EXT_cull_vertex
+#define GL_CULL_VERTEX_EXT                0x81AA
+#define GL_CULL_VERTEX_EYE_POSITION_EXT   0x81AB
+#define GL_CULL_VERTEX_OBJECT_POSITION_EXT 0x81AC
+#endif
+
+#ifndef GL_SGIX_ycrcb
+#define GL_YCRCB_422_SGIX                 0x81BB
+#define GL_YCRCB_444_SGIX                 0x81BC
+#endif
+
+#ifndef GL_SGIX_fragment_lighting
+#define GL_FRAGMENT_LIGHTING_SGIX         0x8400
+#define GL_FRAGMENT_COLOR_MATERIAL_SGIX   0x8401
+#define GL_FRAGMENT_COLOR_MATERIAL_FACE_SGIX 0x8402
+#define GL_FRAGMENT_COLOR_MATERIAL_PARAMETER_SGIX 0x8403
+#define GL_MAX_FRAGMENT_LIGHTS_SGIX       0x8404
+#define GL_MAX_ACTIVE_LIGHTS_SGIX         0x8405
+#define GL_CURRENT_RASTER_NORMAL_SGIX     0x8406
+#define GL_LIGHT_ENV_MODE_SGIX            0x8407
+#define GL_FRAGMENT_LIGHT_MODEL_LOCAL_VIEWER_SGIX 0x8408
+#define GL_FRAGMENT_LIGHT_MODEL_TWO_SIDE_SGIX 0x8409
+#define GL_FRAGMENT_LIGHT_MODEL_AMBIENT_SGIX 0x840A
+#define GL_FRAGMENT_LIGHT_MODEL_NORMAL_INTERPOLATION_SGIX 0x840B
+#define GL_FRAGMENT_LIGHT0_SGIX           0x840C
+#define GL_FRAGMENT_LIGHT1_SGIX           0x840D
+#define GL_FRAGMENT_LIGHT2_SGIX           0x840E
+#define GL_FRAGMENT_LIGHT3_SGIX           0x840F
+#define GL_FRAGMENT_LIGHT4_SGIX           0x8410
+#define GL_FRAGMENT_LIGHT5_SGIX           0x8411
+#define GL_FRAGMENT_LIGHT6_SGIX           0x8412
+#define GL_FRAGMENT_LIGHT7_SGIX           0x8413
+#endif
+
+#ifndef GL_IBM_rasterpos_clip
+#define GL_RASTER_POSITION_UNCLIPPED_IBM  0x19262
+#endif
+
+#ifndef GL_HP_texture_lighting
+#define GL_TEXTURE_LIGHTING_MODE_HP       0x8167
+#define GL_TEXTURE_POST_SPECULAR_HP       0x8168
+#define GL_TEXTURE_PRE_SPECULAR_HP        0x8169
+#endif
+
+#ifndef GL_EXT_draw_range_elements
+#define GL_MAX_ELEMENTS_VERTICES_EXT      0x80E8
+#define GL_MAX_ELEMENTS_INDICES_EXT       0x80E9
+#endif
+
+#ifndef GL_WIN_phong_shading
+#define GL_PHONG_WIN                      0x80EA
+#define GL_PHONG_HINT_WIN                 0x80EB
+#endif
+
+#ifndef GL_WIN_specular_fog
+#define GL_FOG_SPECULAR_TEXTURE_WIN       0x80EC
+#endif
+
+#ifndef GL_EXT_light_texture
+#define GL_FRAGMENT_MATERIAL_EXT          0x8349
+#define GL_FRAGMENT_NORMAL_EXT            0x834A
+#define GL_FRAGMENT_COLOR_EXT             0x834C
+#define GL_ATTENUATION_EXT                0x834D
+#define GL_SHADOW_ATTENUATION_EXT         0x834E
+#define GL_TEXTURE_APPLICATION_MODE_EXT   0x834F
+#define GL_TEXTURE_LIGHT_EXT              0x8350
+#define GL_TEXTURE_MATERIAL_FACE_EXT      0x8351
+#define GL_TEXTURE_MATERIAL_PARAMETER_EXT 0x8352
+  /* reuse GL_FRAGMENT_DEPTH_EXT */
+#endif
+
+#ifndef GL_SGIX_blend_alpha_minmax
+#define GL_ALPHA_MIN_SGIX                 0x8320
+#define GL_ALPHA_MAX_SGIX                 0x8321
+#endif
+
+#ifndef GL_SGIX_impact_pixel_texture
+#define GL_PIXEL_TEX_GEN_Q_CEILING_SGIX   0x8184
+#define GL_PIXEL_TEX_GEN_Q_ROUND_SGIX     0x8185
+#define GL_PIXEL_TEX_GEN_Q_FLOOR_SGIX     0x8186
+#define GL_PIXEL_TEX_GEN_ALPHA_REPLACE_SGIX 0x8187
+#define GL_PIXEL_TEX_GEN_ALPHA_NO_REPLACE_SGIX 0x8188
+#define GL_PIXEL_TEX_GEN_ALPHA_LS_SGIX    0x8189
+#define GL_PIXEL_TEX_GEN_ALPHA_MS_SGIX    0x818A
+#endif
+
+#ifndef GL_EXT_bgra
+#define GL_BGR_EXT                        0x80E0
+#define GL_BGRA_EXT                       0x80E1
+#endif
+
+#ifndef GL_SGIX_async
+#define GL_ASYNC_MARKER_SGIX              0x8329
+#endif
+
+#ifndef GL_SGIX_async_pixel
+#define GL_ASYNC_TEX_IMAGE_SGIX           0x835C
+#define GL_ASYNC_DRAW_PIXELS_SGIX         0x835D
+#define GL_ASYNC_READ_PIXELS_SGIX         0x835E
+#define GL_MAX_ASYNC_TEX_IMAGE_SGIX       0x835F
+#define GL_MAX_ASYNC_DRAW_PIXELS_SGIX     0x8360
+#define GL_MAX_ASYNC_READ_PIXELS_SGIX     0x8361
+#endif
+
+#ifndef GL_SGIX_async_histogram
+#define GL_ASYNC_HISTOGRAM_SGIX           0x832C
+#define GL_MAX_ASYNC_HISTOGRAM_SGIX       0x832D
+#endif
+
+#ifndef GL_INTEL_texture_scissor
+#endif
+
+#ifndef GL_INTEL_parallel_arrays
+#define GL_PARALLEL_ARRAYS_INTEL          0x83F4
+#define GL_VERTEX_ARRAY_PARALLEL_POINTERS_INTEL 0x83F5
+#define GL_NORMAL_ARRAY_PARALLEL_POINTERS_INTEL 0x83F6
+#define GL_COLOR_ARRAY_PARALLEL_POINTERS_INTEL 0x83F7
+#define GL_TEXTURE_COORD_ARRAY_PARALLEL_POINTERS_INTEL 0x83F8
+#endif
+
+#ifndef GL_HP_occlusion_test
+#define GL_OCCLUSION_TEST_HP              0x8165
+#define GL_OCCLUSION_TEST_RESULT_HP       0x8166
+#endif
+
+#ifndef GL_EXT_pixel_transform
+#define GL_PIXEL_TRANSFORM_2D_EXT         0x8330
+#define GL_PIXEL_MAG_FILTER_EXT           0x8331
+#define GL_PIXEL_MIN_FILTER_EXT           0x8332
+#define GL_PIXEL_CUBIC_WEIGHT_EXT         0x8333
+#define GL_CUBIC_EXT                      0x8334
+#define GL_AVERAGE_EXT                    0x8335
+#define GL_PIXEL_TRANSFORM_2D_STACK_DEPTH_EXT 0x8336
+#define GL_MAX_PIXEL_TRANSFORM_2D_STACK_DEPTH_EXT 0x8337
+#define GL_PIXEL_TRANSFORM_2D_MATRIX_EXT  0x8338
+#endif
+
+#ifndef GL_EXT_pixel_transform_color_table
+#endif
+
+#ifndef GL_EXT_shared_texture_palette
+#define GL_SHARED_TEXTURE_PALETTE_EXT     0x81FB
+#endif
+
+#ifndef GL_EXT_separate_specular_color
+#define GL_LIGHT_MODEL_COLOR_CONTROL_EXT  0x81F8
+#define GL_SINGLE_COLOR_EXT               0x81F9
+#define GL_SEPARATE_SPECULAR_COLOR_EXT    0x81FA
+#endif
+
+#ifndef GL_EXT_secondary_color
+#define GL_COLOR_SUM_EXT                  0x8458
+#define GL_CURRENT_SECONDARY_COLOR_EXT    0x8459
+#define GL_SECONDARY_COLOR_ARRAY_SIZE_EXT 0x845A
+#define GL_SECONDARY_COLOR_ARRAY_TYPE_EXT 0x845B
+#define GL_SECONDARY_COLOR_ARRAY_STRIDE_EXT 0x845C
+#define GL_SECONDARY_COLOR_ARRAY_POINTER_EXT 0x845D
+#define GL_SECONDARY_COLOR_ARRAY_EXT      0x845E
+#endif
+
+#ifndef GL_EXT_texture_perturb_normal
+#define GL_PERTURB_EXT                    0x85AE
+#define GL_TEXTURE_NORMAL_EXT             0x85AF
+#endif
+
+#ifndef GL_EXT_multi_draw_arrays
+#endif
+
+#ifndef GL_EXT_fog_coord
+#define GL_FOG_COORDINATE_SOURCE_EXT      0x8450
+#define GL_FOG_COORDINATE_EXT             0x8451
+#define GL_FRAGMENT_DEPTH_EXT             0x8452
+#define GL_CURRENT_FOG_COORDINATE_EXT     0x8453
+#define GL_FOG_COORDINATE_ARRAY_TYPE_EXT  0x8454
+#define GL_FOG_COORDINATE_ARRAY_STRIDE_EXT 0x8455
+#define GL_FOG_COORDINATE_ARRAY_POINTER_EXT 0x8456
+#define GL_FOG_COORDINATE_ARRAY_EXT       0x8457
+#endif
+
+#ifndef GL_REND_screen_coordinates
+#define GL_SCREEN_COORDINATES_REND        0x8490
+#define GL_INVERTED_SCREEN_W_REND         0x8491
+#endif
+
+#ifndef GL_EXT_coordinate_frame
+#define GL_TANGENT_ARRAY_EXT              0x8439
+#define GL_BINORMAL_ARRAY_EXT             0x843A
+#define GL_CURRENT_TANGENT_EXT            0x843B
+#define GL_CURRENT_BINORMAL_EXT           0x843C
+#define GL_TANGENT_ARRAY_TYPE_EXT         0x843E
+#define GL_TANGENT_ARRAY_STRIDE_EXT       0x843F
+#define GL_BINORMAL_ARRAY_TYPE_EXT        0x8440
+#define GL_BINORMAL_ARRAY_STRIDE_EXT      0x8441
+#define GL_TANGENT_ARRAY_POINTER_EXT      0x8442
+#define GL_BINORMAL_ARRAY_POINTER_EXT     0x8443
+#define GL_MAP1_TANGENT_EXT               0x8444
+#define GL_MAP2_TANGENT_EXT               0x8445
+#define GL_MAP1_BINORMAL_EXT              0x8446
+#define GL_MAP2_BINORMAL_EXT              0x8447
+#endif
+
+#ifndef GL_EXT_texture_env_combine
+#define GL_COMBINE_EXT                    0x8570
+#define GL_COMBINE_RGB_EXT                0x8571
+#define GL_COMBINE_ALPHA_EXT              0x8572
+#define GL_RGB_SCALE_EXT                  0x8573
+#define GL_ADD_SIGNED_EXT                 0x8574
+#define GL_INTERPOLATE_EXT                0x8575
+#define GL_CONSTANT_EXT                   0x8576
+#define GL_PRIMARY_COLOR_EXT              0x8577
+#define GL_PREVIOUS_EXT                   0x8578
+#define GL_SOURCE0_RGB_EXT                0x8580
+#define GL_SOURCE1_RGB_EXT                0x8581
+#define GL_SOURCE2_RGB_EXT                0x8582
+#define GL_SOURCE0_ALPHA_EXT              0x8588
+#define GL_SOURCE1_ALPHA_EXT              0x8589
+#define GL_SOURCE2_ALPHA_EXT              0x858A
+#define GL_OPERAND0_RGB_EXT               0x8590
+#define GL_OPERAND1_RGB_EXT               0x8591
+#define GL_OPERAND2_RGB_EXT               0x8592
+#define GL_OPERAND0_ALPHA_EXT             0x8598
+#define GL_OPERAND1_ALPHA_EXT             0x8599
+#define GL_OPERAND2_ALPHA_EXT             0x859A
+#endif
+
+#ifndef GL_APPLE_specular_vector
+#define GL_LIGHT_MODEL_SPECULAR_VECTOR_APPLE 0x85B0
+#endif
+
+#ifndef GL_APPLE_transform_hint
+#define GL_TRANSFORM_HINT_APPLE           0x85B1
+#endif
+
+#ifndef GL_SGIX_fog_scale
+#define GL_FOG_SCALE_SGIX                 0x81FC
+#define GL_FOG_SCALE_VALUE_SGIX           0x81FD
+#endif
+
+#ifndef GL_SUNX_constant_data
+#define GL_UNPACK_CONSTANT_DATA_SUNX      0x81D5
+#define GL_TEXTURE_CONSTANT_DATA_SUNX     0x81D6
+#endif
+
+#ifndef GL_SUN_global_alpha
+#define GL_GLOBAL_ALPHA_SUN               0x81D9
+#define GL_GLOBAL_ALPHA_FACTOR_SUN        0x81DA
+#endif
+
+#ifndef GL_SUN_triangle_list
+#define GL_RESTART_SUN                    0x0001
+#define GL_REPLACE_MIDDLE_SUN             0x0002
+#define GL_REPLACE_OLDEST_SUN             0x0003
+#define GL_TRIANGLE_LIST_SUN              0x81D7
+#define GL_REPLACEMENT_CODE_SUN           0x81D8
+#define GL_REPLACEMENT_CODE_ARRAY_SUN     0x85C0
+#define GL_REPLACEMENT_CODE_ARRAY_TYPE_SUN 0x85C1
+#define GL_REPLACEMENT_CODE_ARRAY_STRIDE_SUN 0x85C2
+#define GL_REPLACEMENT_CODE_ARRAY_POINTER_SUN 0x85C3
+#define GL_R1UI_V3F_SUN                   0x85C4
+#define GL_R1UI_C4UB_V3F_SUN              0x85C5
+#define GL_R1UI_C3F_V3F_SUN               0x85C6
+#define GL_R1UI_N3F_V3F_SUN               0x85C7
+#define GL_R1UI_C4F_N3F_V3F_SUN           0x85C8
+#define GL_R1UI_T2F_V3F_SUN               0x85C9
+#define GL_R1UI_T2F_N3F_V3F_SUN           0x85CA
+#define GL_R1UI_T2F_C4F_N3F_V3F_SUN       0x85CB
+#endif
+
+#ifndef GL_SUN_vertex
+#endif
+
+#ifndef GL_EXT_blend_func_separate
+#define GL_BLEND_DST_RGB_EXT              0x80C8
+#define GL_BLEND_SRC_RGB_EXT              0x80C9
+#define GL_BLEND_DST_ALPHA_EXT            0x80CA
+#define GL_BLEND_SRC_ALPHA_EXT            0x80CB
+#endif
+
+#ifndef GL_INGR_color_clamp
+#define GL_RED_MIN_CLAMP_INGR             0x8560
+#define GL_GREEN_MIN_CLAMP_INGR           0x8561
+#define GL_BLUE_MIN_CLAMP_INGR            0x8562
+#define GL_ALPHA_MIN_CLAMP_INGR           0x8563
+#define GL_RED_MAX_CLAMP_INGR             0x8564
+#define GL_GREEN_MAX_CLAMP_INGR           0x8565
+#define GL_BLUE_MAX_CLAMP_INGR            0x8566
+#define GL_ALPHA_MAX_CLAMP_INGR           0x8567
+#endif
+
+#ifndef GL_INGR_interlace_read
+#define GL_INTERLACE_READ_INGR            0x8568
+#endif
+
+#ifndef GL_EXT_stencil_wrap
+#define GL_INCR_WRAP_EXT                  0x8507
+#define GL_DECR_WRAP_EXT                  0x8508
+#endif
+
+#ifndef GL_EXT_422_pixels
+#define GL_422_EXT                        0x80CC
+#define GL_422_REV_EXT                    0x80CD
+#define GL_422_AVERAGE_EXT                0x80CE
+#define GL_422_REV_AVERAGE_EXT            0x80CF
+#endif
+
+#ifndef GL_NV_texgen_reflection
+#define GL_NORMAL_MAP_NV                  0x8511
+#define GL_REFLECTION_MAP_NV              0x8512
+#endif
+
+#ifndef GL_EXT_texture_cube_map
+#define GL_NORMAL_MAP_EXT                 0x8511
+#define GL_REFLECTION_MAP_EXT             0x8512
+#define GL_TEXTURE_CUBE_MAP_EXT           0x8513
+#define GL_TEXTURE_BINDING_CUBE_MAP_EXT   0x8514
+#define GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT 0x8515
+#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT 0x8516
+#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT 0x8517
+#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT 0x8518
+#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT 0x8519
+#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT 0x851A
+#define GL_PROXY_TEXTURE_CUBE_MAP_EXT     0x851B
+#define GL_MAX_CUBE_MAP_TEXTURE_SIZE_EXT  0x851C
+#endif
+
+#ifndef GL_SUN_convolution_border_modes
+#define GL_WRAP_BORDER_SUN                0x81D4
+#endif
+
+#ifndef GL_EXT_texture_env_add
+#endif
+
+#ifndef GL_EXT_texture_lod_bias
+#define GL_MAX_TEXTURE_LOD_BIAS_EXT       0x84FD
+#define GL_TEXTURE_FILTER_CONTROL_EXT     0x8500
+#define GL_TEXTURE_LOD_BIAS_EXT           0x8501
+#endif
+
+#ifndef GL_EXT_texture_filter_anisotropic
+#define GL_TEXTURE_MAX_ANISOTROPY_EXT     0x84FE
+#define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF
+#endif
+
+#ifndef GL_EXT_vertex_weighting
+#define GL_MODELVIEW0_STACK_DEPTH_EXT     GL_MODELVIEW_STACK_DEPTH
+#define GL_MODELVIEW1_STACK_DEPTH_EXT     0x8502
+#define GL_MODELVIEW0_MATRIX_EXT          GL_MODELVIEW_MATRIX
+#define GL_MODELVIEW1_MATRIX_EXT          0x8506
+#define GL_VERTEX_WEIGHTING_EXT           0x8509
+#define GL_MODELVIEW0_EXT                 GL_MODELVIEW
+#define GL_MODELVIEW1_EXT                 0x850A
+#define GL_CURRENT_VERTEX_WEIGHT_EXT      0x850B
+#define GL_VERTEX_WEIGHT_ARRAY_EXT        0x850C
+#define GL_VERTEX_WEIGHT_ARRAY_SIZE_EXT   0x850D
+#define GL_VERTEX_WEIGHT_ARRAY_TYPE_EXT   0x850E
+#define GL_VERTEX_WEIGHT_ARRAY_STRIDE_EXT 0x850F
+#define GL_VERTEX_WEIGHT_ARRAY_POINTER_EXT 0x8510
+#endif
+
+#ifndef GL_NV_light_max_exponent
+#define GL_MAX_SHININESS_NV               0x8504
+#define GL_MAX_SPOT_EXPONENT_NV           0x8505
+#endif
+
+#ifndef GL_NV_vertex_array_range
+#define GL_VERTEX_ARRAY_RANGE_NV          0x851D
+#define GL_VERTEX_ARRAY_RANGE_LENGTH_NV   0x851E
+#define GL_VERTEX_ARRAY_RANGE_VALID_NV    0x851F
+#define GL_MAX_VERTEX_ARRAY_RANGE_ELEMENT_NV 0x8520
+#define GL_VERTEX_ARRAY_RANGE_POINTER_NV  0x8521
+#endif
+
+#ifndef GL_NV_register_combiners
+#define GL_REGISTER_COMBINERS_NV          0x8522
+#define GL_VARIABLE_A_NV                  0x8523
+#define GL_VARIABLE_B_NV                  0x8524
+#define GL_VARIABLE_C_NV                  0x8525
+#define GL_VARIABLE_D_NV                  0x8526
+#define GL_VARIABLE_E_NV                  0x8527
+#define GL_VARIABLE_F_NV                  0x8528
+#define GL_VARIABLE_G_NV                  0x8529
+#define GL_CONSTANT_COLOR0_NV             0x852A
+#define GL_CONSTANT_COLOR1_NV             0x852B
+#define GL_PRIMARY_COLOR_NV               0x852C
+#define GL_SECONDARY_COLOR_NV             0x852D
+#define GL_SPARE0_NV                      0x852E
+#define GL_SPARE1_NV                      0x852F
+#define GL_DISCARD_NV                     0x8530
+#define GL_E_TIMES_F_NV                   0x8531
+#define GL_SPARE0_PLUS_SECONDARY_COLOR_NV 0x8532
+#define GL_UNSIGNED_IDENTITY_NV           0x8536
+#define GL_UNSIGNED_INVERT_NV             0x8537
+#define GL_EXPAND_NORMAL_NV               0x8538
+#define GL_EXPAND_NEGATE_NV               0x8539
+#define GL_HALF_BIAS_NORMAL_NV            0x853A
+#define GL_HALF_BIAS_NEGATE_NV            0x853B
+#define GL_SIGNED_IDENTITY_NV             0x853C
+#define GL_SIGNED_NEGATE_NV               0x853D
+#define GL_SCALE_BY_TWO_NV                0x853E
+#define GL_SCALE_BY_FOUR_NV               0x853F
+#define GL_SCALE_BY_ONE_HALF_NV           0x8540
+#define GL_BIAS_BY_NEGATIVE_ONE_HALF_NV   0x8541
+#define GL_COMBINER_INPUT_NV              0x8542
+#define GL_COMBINER_MAPPING_NV            0x8543
+#define GL_COMBINER_COMPONENT_USAGE_NV    0x8544
+#define GL_COMBINER_AB_DOT_PRODUCT_NV     0x8545
+#define GL_COMBINER_CD_DOT_PRODUCT_NV     0x8546
+#define GL_COMBINER_MUX_SUM_NV            0x8547
+#define GL_COMBINER_SCALE_NV              0x8548
+#define GL_COMBINER_BIAS_NV               0x8549
+#define GL_COMBINER_AB_OUTPUT_NV          0x854A
+#define GL_COMBINER_CD_OUTPUT_NV          0x854B
+#define GL_COMBINER_SUM_OUTPUT_NV         0x854C
+#define GL_MAX_GENERAL_COMBINERS_NV       0x854D
+#define GL_NUM_GENERAL_COMBINERS_NV       0x854E
+#define GL_COLOR_SUM_CLAMP_NV             0x854F
+#define GL_COMBINER0_NV                   0x8550
+#define GL_COMBINER1_NV                   0x8551
+#define GL_COMBINER2_NV                   0x8552
+#define GL_COMBINER3_NV                   0x8553
+#define GL_COMBINER4_NV                   0x8554
+#define GL_COMBINER5_NV                   0x8555
+#define GL_COMBINER6_NV                   0x8556
+#define GL_COMBINER7_NV                   0x8557
+  /* reuse GL_TEXTURE0_ARB */
+  /* reuse GL_TEXTURE1_ARB */
+  /* reuse GL_ZERO */
+  /* reuse GL_NONE */
+  /* reuse GL_FOG */
+#endif
+
+#ifndef GL_NV_fog_distance
+#define GL_FOG_DISTANCE_MODE_NV           0x855A
+#define GL_EYE_RADIAL_NV                  0x855B
+#define GL_EYE_PLANE_ABSOLUTE_NV          0x855C
+  /* reuse GL_EYE_PLANE */
+#endif
+
+#ifndef GL_NV_texgen_emboss
+#define GL_EMBOSS_LIGHT_NV                0x855D
+#define GL_EMBOSS_CONSTANT_NV             0x855E
+#define GL_EMBOSS_MAP_NV                  0x855F
+#endif
+
+#ifndef GL_NV_blend_square
+#endif
+
+#ifndef GL_NV_texture_env_combine4
+#define GL_COMBINE4_NV                    0x8503
+#define GL_SOURCE3_RGB_NV                 0x8583
+#define GL_SOURCE3_ALPHA_NV               0x858B
+#define GL_OPERAND3_RGB_NV                0x8593
+#define GL_OPERAND3_ALPHA_NV              0x859B
+#endif
+
+#ifndef GL_MESA_resize_buffers
+#endif
+
+#ifndef GL_MESA_window_pos
+#endif
+
+#ifndef GL_EXT_texture_compression_s3tc
+#define GL_COMPRESSED_RGB_S3TC_DXT1_EXT   0x83F0
+#define GL_COMPRESSED_RGBA_S3TC_DXT1_EXT  0x83F1
+#define GL_COMPRESSED_RGBA_S3TC_DXT3_EXT  0x83F2
+#define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT  0x83F3
+#endif
+
+#ifndef GL_IBM_cull_vertex
+#define GL_CULL_VERTEX_IBM                103050
+#endif
+
+#ifndef GL_IBM_multimode_draw_arrays
+#endif
+
+#ifndef GL_IBM_vertex_array_lists
+#define GL_VERTEX_ARRAY_LIST_IBM          103070
+#define GL_NORMAL_ARRAY_LIST_IBM          103071
+#define GL_COLOR_ARRAY_LIST_IBM           103072
+#define GL_INDEX_ARRAY_LIST_IBM           103073
+#define GL_TEXTURE_COORD_ARRAY_LIST_IBM   103074
+#define GL_EDGE_FLAG_ARRAY_LIST_IBM       103075
+#define GL_FOG_COORDINATE_ARRAY_LIST_IBM  103076
+#define GL_SECONDARY_COLOR_ARRAY_LIST_IBM 103077
+#define GL_VERTEX_ARRAY_LIST_STRIDE_IBM   103080
+#define GL_NORMAL_ARRAY_LIST_STRIDE_IBM   103081
+#define GL_COLOR_ARRAY_LIST_STRIDE_IBM    103082
+#define GL_INDEX_ARRAY_LIST_STRIDE_IBM    103083
+#define GL_TEXTURE_COORD_ARRAY_LIST_STRIDE_IBM 103084
+#define GL_EDGE_FLAG_ARRAY_LIST_STRIDE_IBM 103085
+#define GL_FOG_COORDINATE_ARRAY_LIST_STRIDE_IBM 103086
+#define GL_SECONDARY_COLOR_ARRAY_LIST_STRIDE_IBM 103087
+#endif
+
+#ifndef GL_SGIX_subsample
+#define GL_PACK_SUBSAMPLE_RATE_SGIX       0x85A0
+#define GL_UNPACK_SUBSAMPLE_RATE_SGIX     0x85A1
+#define GL_PIXEL_SUBSAMPLE_4444_SGIX      0x85A2
+#define GL_PIXEL_SUBSAMPLE_2424_SGIX      0x85A3
+#define GL_PIXEL_SUBSAMPLE_4242_SGIX      0x85A4
+#endif
+
+#ifndef GL_SGIX_ycrcb_subsample
+#endif
+
+#ifndef GL_SGIX_ycrcba
+#define GL_YCRCB_SGIX                     0x8318
+#define GL_YCRCBA_SGIX                    0x8319
+#endif
+
+#ifndef GL_SGI_depth_pass_instrument
+#define GL_DEPTH_PASS_INSTRUMENT_SGIX     0x8310
+#define GL_DEPTH_PASS_INSTRUMENT_COUNTERS_SGIX 0x8311
+#define GL_DEPTH_PASS_INSTRUMENT_MAX_SGIX 0x8312
+#endif
+
+#ifndef GL_3DFX_texture_compression_FXT1
+#define GL_COMPRESSED_RGB_FXT1_3DFX       0x86B0
+#define GL_COMPRESSED_RGBA_FXT1_3DFX      0x86B1
+#endif
+
+#ifndef GL_3DFX_multisample
+#define GL_MULTISAMPLE_3DFX               0x86B2
+#define GL_SAMPLE_BUFFERS_3DFX            0x86B3
+#define GL_SAMPLES_3DFX                   0x86B4
+#define GL_MULTISAMPLE_BIT_3DFX           0x20000000
+#endif
+
+#ifndef GL_3DFX_tbuffer
+#endif
+
+#ifndef GL_EXT_multisample
+#define GL_MULTISAMPLE_EXT                0x809D
+#define GL_SAMPLE_ALPHA_TO_MASK_EXT       0x809E
+#define GL_SAMPLE_ALPHA_TO_ONE_EXT        0x809F
+#define GL_SAMPLE_MASK_EXT                0x80A0
+#define GL_1PASS_EXT                      0x80A1
+#define GL_2PASS_0_EXT                    0x80A2
+#define GL_2PASS_1_EXT                    0x80A3
+#define GL_4PASS_0_EXT                    0x80A4
+#define GL_4PASS_1_EXT                    0x80A5
+#define GL_4PASS_2_EXT                    0x80A6
+#define GL_4PASS_3_EXT                    0x80A7
+#define GL_SAMPLE_BUFFERS_EXT             0x80A8
+#define GL_SAMPLES_EXT                    0x80A9
+#define GL_SAMPLE_MASK_VALUE_EXT          0x80AA
+#define GL_SAMPLE_MASK_INVERT_EXT         0x80AB
+#define GL_SAMPLE_PATTERN_EXT             0x80AC
+#define GL_MULTISAMPLE_BIT_EXT            0x20000000
+#endif
+
+#ifndef GL_SGIX_vertex_preclip
+#define GL_VERTEX_PRECLIP_SGIX            0x83EE
+#define GL_VERTEX_PRECLIP_HINT_SGIX       0x83EF
+#endif
+
+#ifndef GL_SGIX_convolution_accuracy
+#define GL_CONVOLUTION_HINT_SGIX          0x8316
+#endif
+
+#ifndef GL_SGIX_resample
+#define GL_PACK_RESAMPLE_SGIX             0x842C
+#define GL_UNPACK_RESAMPLE_SGIX           0x842D
+#define GL_RESAMPLE_REPLICATE_SGIX        0x842E
+#define GL_RESAMPLE_ZERO_FILL_SGIX        0x842F
+#define GL_RESAMPLE_DECIMATE_SGIX         0x8430
+#endif
+
+#ifndef GL_SGIS_point_line_texgen
+#define GL_EYE_DISTANCE_TO_POINT_SGIS     0x81F0
+#define GL_OBJECT_DISTANCE_TO_POINT_SGIS  0x81F1
+#define GL_EYE_DISTANCE_TO_LINE_SGIS      0x81F2
+#define GL_OBJECT_DISTANCE_TO_LINE_SGIS   0x81F3
+#define GL_EYE_POINT_SGIS                 0x81F4
+#define GL_OBJECT_POINT_SGIS              0x81F5
+#define GL_EYE_LINE_SGIS                  0x81F6
+#define GL_OBJECT_LINE_SGIS               0x81F7
+#endif
+
+#ifndef GL_SGIS_texture_color_mask
+#define GL_TEXTURE_COLOR_WRITEMASK_SGIS   0x81EF
+#endif
+
+#ifndef GL_EXT_texture_env_dot3
+#define GL_DOT3_RGB_EXT                   0x8740
+#define GL_DOT3_RGBA_EXT                  0x8741
+#endif
+
+#ifndef GL_ATI_texture_mirror_once
+#define GL_MIRROR_CLAMP_ATI               0x8742
+#define GL_MIRROR_CLAMP_TO_EDGE_ATI       0x8743
+#endif
+
+#ifndef GL_NV_fence
+#define GL_ALL_COMPLETED_NV               0x84F2
+#define GL_FENCE_STATUS_NV                0x84F3
+#define GL_FENCE_CONDITION_NV             0x84F4
+#endif
+
+#ifndef GL_IBM_texture_mirrored_repeat
+#define GL_MIRRORED_REPEAT_IBM            0x8370
+#endif
+
+#ifndef GL_NV_evaluators
+#define GL_EVAL_2D_NV                     0x86C0
+#define GL_EVAL_TRIANGULAR_2D_NV          0x86C1
+#define GL_MAP_TESSELLATION_NV            0x86C2
+#define GL_MAP_ATTRIB_U_ORDER_NV          0x86C3
+#define GL_MAP_ATTRIB_V_ORDER_NV          0x86C4
+#define GL_EVAL_FRACTIONAL_TESSELLATION_NV 0x86C5
+#define GL_EVAL_VERTEX_ATTRIB0_NV         0x86C6
+#define GL_EVAL_VERTEX_ATTRIB1_NV         0x86C7
+#define GL_EVAL_VERTEX_ATTRIB2_NV         0x86C8
+#define GL_EVAL_VERTEX_ATTRIB3_NV         0x86C9
+#define GL_EVAL_VERTEX_ATTRIB4_NV         0x86CA
+#define GL_EVAL_VERTEX_ATTRIB5_NV         0x86CB
+#define GL_EVAL_VERTEX_ATTRIB6_NV         0x86CC
+#define GL_EVAL_VERTEX_ATTRIB7_NV         0x86CD
+#define GL_EVAL_VERTEX_ATTRIB8_NV         0x86CE
+#define GL_EVAL_VERTEX_ATTRIB9_NV         0x86CF
+#define GL_EVAL_VERTEX_ATTRIB10_NV        0x86D0
+#define GL_EVAL_VERTEX_ATTRIB11_NV        0x86D1
+#define GL_EVAL_VERTEX_ATTRIB12_NV        0x86D2
+#define GL_EVAL_VERTEX_ATTRIB13_NV        0x86D3
+#define GL_EVAL_VERTEX_ATTRIB14_NV        0x86D4
+#define GL_EVAL_VERTEX_ATTRIB15_NV        0x86D5
+#define GL_MAX_MAP_TESSELLATION_NV        0x86D6
+#define GL_MAX_RATIONAL_EVAL_ORDER_NV     0x86D7
+#endif
+
+#ifndef GL_NV_packed_depth_stencil
+#define GL_DEPTH_STENCIL_NV               0x84F9
+#define GL_UNSIGNED_INT_24_8_NV           0x84FA
+#endif
+
+#ifndef GL_NV_register_combiners2
+#define GL_PER_STAGE_CONSTANTS_NV         0x8535
+#endif
+
+#ifndef GL_NV_texture_compression_vtc
+#endif
+
+#ifndef GL_NV_texture_rectangle
+#define GL_TEXTURE_RECTANGLE_NV           0x84F5
+#define GL_TEXTURE_BINDING_RECTANGLE_NV   0x84F6
+#define GL_PROXY_TEXTURE_RECTANGLE_NV     0x84F7
+#define GL_MAX_RECTANGLE_TEXTURE_SIZE_NV  0x84F8
+#endif
+
+#ifndef GL_NV_texture_shader
+#define GL_OFFSET_TEXTURE_RECTANGLE_NV    0x864C
+#define GL_OFFSET_TEXTURE_RECTANGLE_SCALE_NV 0x864D
+#define GL_DOT_PRODUCT_TEXTURE_RECTANGLE_NV 0x864E
+#define GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV 0x86D9
+#define GL_UNSIGNED_INT_S8_S8_8_8_NV      0x86DA
+#define GL_UNSIGNED_INT_8_8_S8_S8_REV_NV  0x86DB
+#define GL_DSDT_MAG_INTENSITY_NV          0x86DC
+#define GL_SHADER_CONSISTENT_NV           0x86DD
+#define GL_TEXTURE_SHADER_NV              0x86DE
+#define GL_SHADER_OPERATION_NV            0x86DF
+#define GL_CULL_MODES_NV                  0x86E0
+#define GL_OFFSET_TEXTURE_MATRIX_NV       0x86E1
+#define GL_OFFSET_TEXTURE_SCALE_NV        0x86E2
+#define GL_OFFSET_TEXTURE_BIAS_NV         0x86E3
+#define GL_OFFSET_TEXTURE_2D_MATRIX_NV    GL_OFFSET_TEXTURE_MATRIX_NV
+#define GL_OFFSET_TEXTURE_2D_SCALE_NV     GL_OFFSET_TEXTURE_SCALE_NV
+#define GL_OFFSET_TEXTURE_2D_BIAS_NV      GL_OFFSET_TEXTURE_BIAS_NV
+#define GL_PREVIOUS_TEXTURE_INPUT_NV      0x86E4
+#define GL_CONST_EYE_NV                   0x86E5
+#define GL_PASS_THROUGH_NV                0x86E6
+#define GL_CULL_FRAGMENT_NV               0x86E7
+#define GL_OFFSET_TEXTURE_2D_NV           0x86E8
+#define GL_DEPENDENT_AR_TEXTURE_2D_NV     0x86E9
+#define GL_DEPENDENT_GB_TEXTURE_2D_NV     0x86EA
+#define GL_DOT_PRODUCT_NV                 0x86EC
+#define GL_DOT_PRODUCT_DEPTH_REPLACE_NV   0x86ED
+#define GL_DOT_PRODUCT_TEXTURE_2D_NV      0x86EE
+#define GL_DOT_PRODUCT_TEXTURE_CUBE_MAP_NV 0x86F0
+#define GL_DOT_PRODUCT_DIFFUSE_CUBE_MAP_NV 0x86F1
+#define GL_DOT_PRODUCT_REFLECT_CUBE_MAP_NV 0x86F2
+#define GL_DOT_PRODUCT_CONST_EYE_REFLECT_CUBE_MAP_NV 0x86F3
+#define GL_HILO_NV                        0x86F4
+#define GL_DSDT_NV                        0x86F5
+#define GL_DSDT_MAG_NV                    0x86F6
+#define GL_DSDT_MAG_VIB_NV                0x86F7
+#define GL_HILO16_NV                      0x86F8
+#define GL_SIGNED_HILO_NV                 0x86F9
+#define GL_SIGNED_HILO16_NV               0x86FA
+#define GL_SIGNED_RGBA_NV                 0x86FB
+#define GL_SIGNED_RGBA8_NV                0x86FC
+#define GL_SIGNED_RGB_NV                  0x86FE
+#define GL_SIGNED_RGB8_NV                 0x86FF
+#define GL_SIGNED_LUMINANCE_NV            0x8701
+#define GL_SIGNED_LUMINANCE8_NV           0x8702
+#define GL_SIGNED_LUMINANCE_ALPHA_NV      0x8703
+#define GL_SIGNED_LUMINANCE8_ALPHA8_NV    0x8704
+#define GL_SIGNED_ALPHA_NV                0x8705
+#define GL_SIGNED_ALPHA8_NV               0x8706
+#define GL_SIGNED_INTENSITY_NV            0x8707
+#define GL_SIGNED_INTENSITY8_NV           0x8708
+#define GL_DSDT8_NV                       0x8709
+#define GL_DSDT8_MAG8_NV                  0x870A
+#define GL_DSDT8_MAG8_INTENSITY8_NV       0x870B
+#define GL_SIGNED_RGB_UNSIGNED_ALPHA_NV   0x870C
+#define GL_SIGNED_RGB8_UNSIGNED_ALPHA8_NV 0x870D
+#define GL_HI_SCALE_NV                    0x870E
+#define GL_LO_SCALE_NV                    0x870F
+#define GL_DS_SCALE_NV                    0x8710
+#define GL_DT_SCALE_NV                    0x8711
+#define GL_MAGNITUDE_SCALE_NV             0x8712
+#define GL_VIBRANCE_SCALE_NV              0x8713
+#define GL_HI_BIAS_NV                     0x8714
+#define GL_LO_BIAS_NV                     0x8715
+#define GL_DS_BIAS_NV                     0x8716
+#define GL_DT_BIAS_NV                     0x8717
+#define GL_MAGNITUDE_BIAS_NV              0x8718
+#define GL_VIBRANCE_BIAS_NV               0x8719
+#define GL_TEXTURE_BORDER_VALUES_NV       0x871A
+#define GL_TEXTURE_HI_SIZE_NV             0x871B
+#define GL_TEXTURE_LO_SIZE_NV             0x871C
+#define GL_TEXTURE_DS_SIZE_NV             0x871D
+#define GL_TEXTURE_DT_SIZE_NV             0x871E
+#define GL_TEXTURE_MAG_SIZE_NV            0x871F
+#endif
+
+#ifndef GL_NV_texture_shader2
+#define GL_DOT_PRODUCT_TEXTURE_3D_NV      0x86EF
+#endif
+
+#ifndef GL_NV_vertex_array_range2
+#define GL_VERTEX_ARRAY_RANGE_WITHOUT_FLUSH_NV 0x8533
+#endif
+
+#ifndef GL_NV_vertex_program
+#define GL_VERTEX_PROGRAM_NV              0x8620
+#define GL_VERTEX_STATE_PROGRAM_NV        0x8621
+#define GL_ATTRIB_ARRAY_SIZE_NV           0x8623
+#define GL_ATTRIB_ARRAY_STRIDE_NV         0x8624
+#define GL_ATTRIB_ARRAY_TYPE_NV           0x8625
+#define GL_CURRENT_ATTRIB_NV              0x8626
+#define GL_PROGRAM_LENGTH_NV              0x8627
+#define GL_PROGRAM_STRING_NV              0x8628
+#define GL_MODELVIEW_PROJECTION_NV        0x8629
+#define GL_IDENTITY_NV                    0x862A
+#define GL_INVERSE_NV                     0x862B
+#define GL_TRANSPOSE_NV                   0x862C
+#define GL_INVERSE_TRANSPOSE_NV           0x862D
+#define GL_MAX_TRACK_MATRIX_STACK_DEPTH_NV 0x862E
+#define GL_MAX_TRACK_MATRICES_NV          0x862F
+#define GL_MATRIX0_NV                     0x8630
+#define GL_MATRIX1_NV                     0x8631
+#define GL_MATRIX2_NV                     0x8632
+#define GL_MATRIX3_NV                     0x8633
+#define GL_MATRIX4_NV                     0x8634
+#define GL_MATRIX5_NV                     0x8635
+#define GL_MATRIX6_NV                     0x8636
+#define GL_MATRIX7_NV                     0x8637
+#define GL_CURRENT_MATRIX_STACK_DEPTH_NV  0x8640
+#define GL_CURRENT_MATRIX_NV              0x8641
+#define GL_VERTEX_PROGRAM_POINT_SIZE_NV   0x8642
+#define GL_VERTEX_PROGRAM_TWO_SIDE_NV     0x8643
+#define GL_PROGRAM_PARAMETER_NV           0x8644
+#define GL_ATTRIB_ARRAY_POINTER_NV        0x8645
+#define GL_PROGRAM_TARGET_NV              0x8646
+#define GL_PROGRAM_RESIDENT_NV            0x8647
+#define GL_TRACK_MATRIX_NV                0x8648
+#define GL_TRACK_MATRIX_TRANSFORM_NV      0x8649
+#define GL_VERTEX_PROGRAM_BINDING_NV      0x864A
+#define GL_PROGRAM_ERROR_POSITION_NV      0x864B
+#define GL_VERTEX_ATTRIB_ARRAY0_NV        0x8650
+#define GL_VERTEX_ATTRIB_ARRAY1_NV        0x8651
+#define GL_VERTEX_ATTRIB_ARRAY2_NV        0x8652
+#define GL_VERTEX_ATTRIB_ARRAY3_NV        0x8653
+#define GL_VERTEX_ATTRIB_ARRAY4_NV        0x8654
+#define GL_VERTEX_ATTRIB_ARRAY5_NV        0x8655
+#define GL_VERTEX_ATTRIB_ARRAY6_NV        0x8656
+#define GL_VERTEX_ATTRIB_ARRAY7_NV        0x8657
+#define GL_VERTEX_ATTRIB_ARRAY8_NV        0x8658
+#define GL_VERTEX_ATTRIB_ARRAY9_NV        0x8659
+#define GL_VERTEX_ATTRIB_ARRAY10_NV       0x865A
+#define GL_VERTEX_ATTRIB_ARRAY11_NV       0x865B
+#define GL_VERTEX_ATTRIB_ARRAY12_NV       0x865C
+#define GL_VERTEX_ATTRIB_ARRAY13_NV       0x865D
+#define GL_VERTEX_ATTRIB_ARRAY14_NV       0x865E
+#define GL_VERTEX_ATTRIB_ARRAY15_NV       0x865F
+#define GL_MAP1_VERTEX_ATTRIB0_4_NV       0x8660
+#define GL_MAP1_VERTEX_ATTRIB1_4_NV       0x8661
+#define GL_MAP1_VERTEX_ATTRIB2_4_NV       0x8662
+#define GL_MAP1_VERTEX_ATTRIB3_4_NV       0x8663
+#define GL_MAP1_VERTEX_ATTRIB4_4_NV       0x8664
+#define GL_MAP1_VERTEX_ATTRIB5_4_NV       0x8665
+#define GL_MAP1_VERTEX_ATTRIB6_4_NV       0x8666
+#define GL_MAP1_VERTEX_ATTRIB7_4_NV       0x8667
+#define GL_MAP1_VERTEX_ATTRIB8_4_NV       0x8668
+#define GL_MAP1_VERTEX_ATTRIB9_4_NV       0x8669
+#define GL_MAP1_VERTEX_ATTRIB10_4_NV      0x866A
+#define GL_MAP1_VERTEX_ATTRIB11_4_NV      0x866B
+#define GL_MAP1_VERTEX_ATTRIB12_4_NV      0x866C
+#define GL_MAP1_VERTEX_ATTRIB13_4_NV      0x866D
+#define GL_MAP1_VERTEX_ATTRIB14_4_NV      0x866E
+#define GL_MAP1_VERTEX_ATTRIB15_4_NV      0x866F
+#define GL_MAP2_VERTEX_ATTRIB0_4_NV       0x8670
+#define GL_MAP2_VERTEX_ATTRIB1_4_NV       0x8671
+#define GL_MAP2_VERTEX_ATTRIB2_4_NV       0x8672
+#define GL_MAP2_VERTEX_ATTRIB3_4_NV       0x8673
+#define GL_MAP2_VERTEX_ATTRIB4_4_NV       0x8674
+#define GL_MAP2_VERTEX_ATTRIB5_4_NV       0x8675
+#define GL_MAP2_VERTEX_ATTRIB6_4_NV       0x8676
+#define GL_MAP2_VERTEX_ATTRIB7_4_NV       0x8677
+#define GL_MAP2_VERTEX_ATTRIB8_4_NV       0x8678
+#define GL_MAP2_VERTEX_ATTRIB9_4_NV       0x8679
+#define GL_MAP2_VERTEX_ATTRIB10_4_NV      0x867A
+#define GL_MAP2_VERTEX_ATTRIB11_4_NV      0x867B
+#define GL_MAP2_VERTEX_ATTRIB12_4_NV      0x867C
+#define GL_MAP2_VERTEX_ATTRIB13_4_NV      0x867D
+#define GL_MAP2_VERTEX_ATTRIB14_4_NV      0x867E
+#define GL_MAP2_VERTEX_ATTRIB15_4_NV      0x867F
+#endif
+
+#ifndef GL_SGIX_texture_coordinate_clamp
+#define GL_TEXTURE_MAX_CLAMP_S_SGIX       0x8369
+#define GL_TEXTURE_MAX_CLAMP_T_SGIX       0x836A
+#define GL_TEXTURE_MAX_CLAMP_R_SGIX       0x836B
+#endif
+
+#ifndef GL_SGIX_scalebias_hint
+#define GL_SCALEBIAS_HINT_SGIX            0x8322
+#endif
+
+#ifndef GL_OML_interlace
+#define GL_INTERLACE_OML                  0x8980
+#define GL_INTERLACE_READ_OML             0x8981
+#endif
+
+#ifndef GL_OML_subsample
+#define GL_FORMAT_SUBSAMPLE_24_24_OML     0x8982
+#define GL_FORMAT_SUBSAMPLE_244_244_OML   0x8983
+#endif
+
+#ifndef GL_OML_resample
+#define GL_PACK_RESAMPLE_OML              0x8984
+#define GL_UNPACK_RESAMPLE_OML            0x8985
+#define GL_RESAMPLE_REPLICATE_OML         0x8986
+#define GL_RESAMPLE_ZERO_FILL_OML         0x8987
+#define GL_RESAMPLE_AVERAGE_OML           0x8988
+#define GL_RESAMPLE_DECIMATE_OML          0x8989
+#endif
+
+#ifndef GL_NV_copy_depth_to_color
+#define GL_DEPTH_STENCIL_TO_RGBA_NV       0x886E
+#define GL_DEPTH_STENCIL_TO_BGRA_NV       0x886F
+#endif
+
+#ifndef GL_ATI_envmap_bumpmap
+#define GL_BUMP_ROT_MATRIX_ATI            0x8775
+#define GL_BUMP_ROT_MATRIX_SIZE_ATI       0x8776
+#define GL_BUMP_NUM_TEX_UNITS_ATI         0x8777
+#define GL_BUMP_TEX_UNITS_ATI             0x8778
+#define GL_DUDV_ATI                       0x8779
+#define GL_DU8DV8_ATI                     0x877A
+#define GL_BUMP_ENVMAP_ATI                0x877B
+#define GL_BUMP_TARGET_ATI                0x877C
+#endif
+
+#ifndef GL_ATI_fragment_shader
+#define GL_FRAGMENT_SHADER_ATI            0x8920
+#define GL_REG_0_ATI                      0x8921
+#define GL_REG_1_ATI                      0x8922
+#define GL_REG_2_ATI                      0x8923
+#define GL_REG_3_ATI                      0x8924
+#define GL_REG_4_ATI                      0x8925
+#define GL_REG_5_ATI                      0x8926
+#define GL_REG_6_ATI                      0x8927
+#define GL_REG_7_ATI                      0x8928
+#define GL_REG_8_ATI                      0x8929
+#define GL_REG_9_ATI                      0x892A
+#define GL_REG_10_ATI                     0x892B
+#define GL_REG_11_ATI                     0x892C
+#define GL_REG_12_ATI                     0x892D
+#define GL_REG_13_ATI                     0x892E
+#define GL_REG_14_ATI                     0x892F
+#define GL_REG_15_ATI                     0x8930
+#define GL_REG_16_ATI                     0x8931
+#define GL_REG_17_ATI                     0x8932
+#define GL_REG_18_ATI                     0x8933
+#define GL_REG_19_ATI                     0x8934
+#define GL_REG_20_ATI                     0x8935
+#define GL_REG_21_ATI                     0x8936
+#define GL_REG_22_ATI                     0x8937
+#define GL_REG_23_ATI                     0x8938
+#define GL_REG_24_ATI                     0x8939
+#define GL_REG_25_ATI                     0x893A
+#define GL_REG_26_ATI                     0x893B
+#define GL_REG_27_ATI                     0x893C
+#define GL_REG_28_ATI                     0x893D
+#define GL_REG_29_ATI                     0x893E
+#define GL_REG_30_ATI                     0x893F
+#define GL_REG_31_ATI                     0x8940
+#define GL_CON_0_ATI                      0x8941
+#define GL_CON_1_ATI                      0x8942
+#define GL_CON_2_ATI                      0x8943
+#define GL_CON_3_ATI                      0x8944
+#define GL_CON_4_ATI                      0x8945
+#define GL_CON_5_ATI                      0x8946
+#define GL_CON_6_ATI                      0x8947
+#define GL_CON_7_ATI                      0x8948
+#define GL_CON_8_ATI                      0x8949
+#define GL_CON_9_ATI                      0x894A
+#define GL_CON_10_ATI                     0x894B
+#define GL_CON_11_ATI                     0x894C
+#define GL_CON_12_ATI                     0x894D
+#define GL_CON_13_ATI                     0x894E
+#define GL_CON_14_ATI                     0x894F
+#define GL_CON_15_ATI                     0x8950
+#define GL_CON_16_ATI                     0x8951
+#define GL_CON_17_ATI                     0x8952
+#define GL_CON_18_ATI                     0x8953
+#define GL_CON_19_ATI                     0x8954
+#define GL_CON_20_ATI                     0x8955
+#define GL_CON_21_ATI                     0x8956
+#define GL_CON_22_ATI                     0x8957
+#define GL_CON_23_ATI                     0x8958
+#define GL_CON_24_ATI                     0x8959
+#define GL_CON_25_ATI                     0x895A
+#define GL_CON_26_ATI                     0x895B
+#define GL_CON_27_ATI                     0x895C
+#define GL_CON_28_ATI                     0x895D
+#define GL_CON_29_ATI                     0x895E
+#define GL_CON_30_ATI                     0x895F
+#define GL_CON_31_ATI                     0x8960
+#define GL_MOV_ATI                        0x8961
+#define GL_ADD_ATI                        0x8963
+#define GL_MUL_ATI                        0x8964
+#define GL_SUB_ATI                        0x8965
+#define GL_DOT3_ATI                       0x8966
+#define GL_DOT4_ATI                       0x8967
+#define GL_MAD_ATI                        0x8968
+#define GL_LERP_ATI                       0x8969
+#define GL_CND_ATI                        0x896A
+#define GL_CND0_ATI                       0x896B
+#define GL_DOT2_ADD_ATI                   0x896C
+#define GL_SECONDARY_INTERPOLATOR_ATI     0x896D
+#define GL_NUM_FRAGMENT_REGISTERS_ATI     0x896E
+#define GL_NUM_FRAGMENT_CONSTANTS_ATI     0x896F
+#define GL_NUM_PASSES_ATI                 0x8970
+#define GL_NUM_INSTRUCTIONS_PER_PASS_ATI  0x8971
+#define GL_NUM_INSTRUCTIONS_TOTAL_ATI     0x8972
+#define GL_NUM_INPUT_INTERPOLATOR_COMPONENTS_ATI 0x8973
+#define GL_NUM_LOOPBACK_COMPONENTS_ATI    0x8974
+#define GL_COLOR_ALPHA_PAIRING_ATI        0x8975
+#define GL_SWIZZLE_STR_ATI                0x8976
+#define GL_SWIZZLE_STQ_ATI                0x8977
+#define GL_SWIZZLE_STR_DR_ATI             0x8978
+#define GL_SWIZZLE_STQ_DQ_ATI             0x8979
+#define GL_SWIZZLE_STRQ_ATI               0x897A
+#define GL_SWIZZLE_STRQ_DQ_ATI            0x897B
+#define GL_RED_BIT_ATI                    0x00000001
+#define GL_GREEN_BIT_ATI                  0x00000002
+#define GL_BLUE_BIT_ATI                   0x00000004
+#define GL_2X_BIT_ATI                     0x00000001
+#define GL_4X_BIT_ATI                     0x00000002
+#define GL_8X_BIT_ATI                     0x00000004
+#define GL_HALF_BIT_ATI                   0x00000008
+#define GL_QUARTER_BIT_ATI                0x00000010
+#define GL_EIGHTH_BIT_ATI                 0x00000020
+#define GL_SATURATE_BIT_ATI               0x00000040
+#define GL_COMP_BIT_ATI                   0x00000002
+#define GL_NEGATE_BIT_ATI                 0x00000004
+#define GL_BIAS_BIT_ATI                   0x00000008
+#endif
+
+#ifndef GL_ATI_pn_triangles
+#define GL_PN_TRIANGLES_ATI               0x87F0
+#define GL_MAX_PN_TRIANGLES_TESSELATION_LEVEL_ATI 0x87F1
+#define GL_PN_TRIANGLES_POINT_MODE_ATI    0x87F2
+#define GL_PN_TRIANGLES_NORMAL_MODE_ATI   0x87F3
+#define GL_PN_TRIANGLES_TESSELATION_LEVEL_ATI 0x87F4
+#define GL_PN_TRIANGLES_POINT_MODE_LINEAR_ATI 0x87F5
+#define GL_PN_TRIANGLES_POINT_MODE_CUBIC_ATI 0x87F6
+#define GL_PN_TRIANGLES_NORMAL_MODE_LINEAR_ATI 0x87F7
+#define GL_PN_TRIANGLES_NORMAL_MODE_QUADRATIC_ATI 0x87F8
+#endif
+
+#ifndef GL_ATI_vertex_array_object
+#define GL_STATIC_ATI                     0x8760
+#define GL_DYNAMIC_ATI                    0x8761
+#define GL_PRESERVE_ATI                   0x8762
+#define GL_DISCARD_ATI                    0x8763
+#define GL_OBJECT_BUFFER_SIZE_ATI         0x8764
+#define GL_OBJECT_BUFFER_USAGE_ATI        0x8765
+#define GL_ARRAY_OBJECT_BUFFER_ATI        0x8766
+#define GL_ARRAY_OBJECT_OFFSET_ATI        0x8767
+#endif
+
+#ifndef GL_EXT_vertex_shader
+#define GL_VERTEX_SHADER_EXT              0x8780
+#define GL_VERTEX_SHADER_BINDING_EXT      0x8781
+#define GL_OP_INDEX_EXT                   0x8782
+#define GL_OP_NEGATE_EXT                  0x8783
+#define GL_OP_DOT3_EXT                    0x8784
+#define GL_OP_DOT4_EXT                    0x8785
+#define GL_OP_MUL_EXT                     0x8786
+#define GL_OP_ADD_EXT                     0x8787
+#define GL_OP_MADD_EXT                    0x8788
+#define GL_OP_FRAC_EXT                    0x8789
+#define GL_OP_MAX_EXT                     0x878A
+#define GL_OP_MIN_EXT                     0x878B
+#define GL_OP_SET_GE_EXT                  0x878C
+#define GL_OP_SET_LT_EXT                  0x878D
+#define GL_OP_CLAMP_EXT                   0x878E
+#define GL_OP_FLOOR_EXT                   0x878F
+#define GL_OP_ROUND_EXT                   0x8790
+#define GL_OP_EXP_BASE_2_EXT              0x8791
+#define GL_OP_LOG_BASE_2_EXT              0x8792
+#define GL_OP_POWER_EXT                   0x8793
+#define GL_OP_RECIP_EXT                   0x8794
+#define GL_OP_RECIP_SQRT_EXT              0x8795
+#define GL_OP_SUB_EXT                     0x8796
+#define GL_OP_CROSS_PRODUCT_EXT           0x8797
+#define GL_OP_MULTIPLY_MATRIX_EXT         0x8798
+#define GL_OP_MOV_EXT                     0x8799
+#define GL_OUTPUT_VERTEX_EXT              0x879A
+#define GL_OUTPUT_COLOR0_EXT              0x879B
+#define GL_OUTPUT_COLOR1_EXT              0x879C
+#define GL_OUTPUT_TEXTURE_COORD0_EXT      0x879D
+#define GL_OUTPUT_TEXTURE_COORD1_EXT      0x879E
+#define GL_OUTPUT_TEXTURE_COORD2_EXT      0x879F
+#define GL_OUTPUT_TEXTURE_COORD3_EXT      0x87A0
+#define GL_OUTPUT_TEXTURE_COORD4_EXT      0x87A1
+#define GL_OUTPUT_TEXTURE_COORD5_EXT      0x87A2
+#define GL_OUTPUT_TEXTURE_COORD6_EXT      0x87A3
+#define GL_OUTPUT_TEXTURE_COORD7_EXT      0x87A4
+#define GL_OUTPUT_TEXTURE_COORD8_EXT      0x87A5
+#define GL_OUTPUT_TEXTURE_COORD9_EXT      0x87A6
+#define GL_OUTPUT_TEXTURE_COORD10_EXT     0x87A7
+#define GL_OUTPUT_TEXTURE_COORD11_EXT     0x87A8
+#define GL_OUTPUT_TEXTURE_COORD12_EXT     0x87A9
+#define GL_OUTPUT_TEXTURE_COORD13_EXT     0x87AA
+#define GL_OUTPUT_TEXTURE_COORD14_EXT     0x87AB
+#define GL_OUTPUT_TEXTURE_COORD15_EXT     0x87AC
+#define GL_OUTPUT_TEXTURE_COORD16_EXT     0x87AD
+#define GL_OUTPUT_TEXTURE_COORD17_EXT     0x87AE
+#define GL_OUTPUT_TEXTURE_COORD18_EXT     0x87AF
+#define GL_OUTPUT_TEXTURE_COORD19_EXT     0x87B0
+#define GL_OUTPUT_TEXTURE_COORD20_EXT     0x87B1
+#define GL_OUTPUT_TEXTURE_COORD21_EXT     0x87B2
+#define GL_OUTPUT_TEXTURE_COORD22_EXT     0x87B3
+#define GL_OUTPUT_TEXTURE_COORD23_EXT     0x87B4
+#define GL_OUTPUT_TEXTURE_COORD24_EXT     0x87B5
+#define GL_OUTPUT_TEXTURE_COORD25_EXT     0x87B6
+#define GL_OUTPUT_TEXTURE_COORD26_EXT     0x87B7
+#define GL_OUTPUT_TEXTURE_COORD27_EXT     0x87B8
+#define GL_OUTPUT_TEXTURE_COORD28_EXT     0x87B9
+#define GL_OUTPUT_TEXTURE_COORD29_EXT     0x87BA
+#define GL_OUTPUT_TEXTURE_COORD30_EXT     0x87BB
+#define GL_OUTPUT_TEXTURE_COORD31_EXT     0x87BC
+#define GL_OUTPUT_FOG_EXT                 0x87BD
+#define GL_SCALAR_EXT                     0x87BE
+#define GL_VECTOR_EXT                     0x87BF
+#define GL_MATRIX_EXT                     0x87C0
+#define GL_VARIANT_EXT                    0x87C1
+#define GL_INVARIANT_EXT                  0x87C2
+#define GL_LOCAL_CONSTANT_EXT             0x87C3
+#define GL_LOCAL_EXT                      0x87C4
+#define GL_MAX_VERTEX_SHADER_INSTRUCTIONS_EXT 0x87C5
+#define GL_MAX_VERTEX_SHADER_VARIANTS_EXT 0x87C6
+#define GL_MAX_VERTEX_SHADER_INVARIANTS_EXT 0x87C7
+#define GL_MAX_VERTEX_SHADER_LOCAL_CONSTANTS_EXT 0x87C8
+#define GL_MAX_VERTEX_SHADER_LOCALS_EXT   0x87C9
+#define GL_MAX_OPTIMIZED_VERTEX_SHADER_INSTRUCTIONS_EXT 0x87CA
+#define GL_MAX_OPTIMIZED_VERTEX_SHADER_VARIANTS_EXT 0x87CB
+#define GL_MAX_OPTIMIZED_VERTEX_SHADER_LOCAL_CONSTANTS_EXT 0x87CC
+#define GL_MAX_OPTIMIZED_VERTEX_SHADER_INVARIANTS_EXT 0x87CD
+#define GL_MAX_OPTIMIZED_VERTEX_SHADER_LOCALS_EXT 0x87CE
+#define GL_VERTEX_SHADER_INSTRUCTIONS_EXT 0x87CF
+#define GL_VERTEX_SHADER_VARIANTS_EXT     0x87D0
+#define GL_VERTEX_SHADER_INVARIANTS_EXT   0x87D1
+#define GL_VERTEX_SHADER_LOCAL_CONSTANTS_EXT 0x87D2
+#define GL_VERTEX_SHADER_LOCALS_EXT       0x87D3
+#define GL_VERTEX_SHADER_OPTIMIZED_EXT    0x87D4
+#define GL_X_EXT                          0x87D5
+#define GL_Y_EXT                          0x87D6
+#define GL_Z_EXT                          0x87D7
+#define GL_W_EXT                          0x87D8
+#define GL_NEGATIVE_X_EXT                 0x87D9
+#define GL_NEGATIVE_Y_EXT                 0x87DA
+#define GL_NEGATIVE_Z_EXT                 0x87DB
+#define GL_NEGATIVE_W_EXT                 0x87DC
+#define GL_ZERO_EXT                       0x87DD
+#define GL_ONE_EXT                        0x87DE
+#define GL_NEGATIVE_ONE_EXT               0x87DF
+#define GL_NORMALIZED_RANGE_EXT           0x87E0
+#define GL_FULL_RANGE_EXT                 0x87E1
+#define GL_CURRENT_VERTEX_EXT             0x87E2
+#define GL_MVP_MATRIX_EXT                 0x87E3
+#define GL_VARIANT_VALUE_EXT              0x87E4
+#define GL_VARIANT_DATATYPE_EXT           0x87E5
+#define GL_VARIANT_ARRAY_STRIDE_EXT       0x87E6
+#define GL_VARIANT_ARRAY_TYPE_EXT         0x87E7
+#define GL_VARIANT_ARRAY_EXT              0x87E8
+#define GL_VARIANT_ARRAY_POINTER_EXT      0x87E9
+#define GL_INVARIANT_VALUE_EXT            0x87EA
+#define GL_INVARIANT_DATATYPE_EXT         0x87EB
+#define GL_LOCAL_CONSTANT_VALUE_EXT       0x87EC
+#define GL_LOCAL_CONSTANT_DATATYPE_EXT    0x87ED
+#endif
+
+#ifndef GL_ATI_vertex_streams
+#define GL_MAX_VERTEX_STREAMS_ATI         0x876B
+#define GL_VERTEX_STREAM0_ATI             0x876C
+#define GL_VERTEX_STREAM1_ATI             0x876D
+#define GL_VERTEX_STREAM2_ATI             0x876E
+#define GL_VERTEX_STREAM3_ATI             0x876F
+#define GL_VERTEX_STREAM4_ATI             0x8770
+#define GL_VERTEX_STREAM5_ATI             0x8771
+#define GL_VERTEX_STREAM6_ATI             0x8772
+#define GL_VERTEX_STREAM7_ATI             0x8773
+#define GL_VERTEX_SOURCE_ATI              0x8774
+#endif
+
+#ifndef GL_ATI_element_array
+#define GL_ELEMENT_ARRAY_ATI              0x8768
+#define GL_ELEMENT_ARRAY_TYPE_ATI         0x8769
+#define GL_ELEMENT_ARRAY_POINTER_ATI      0x876A
+#endif
+
+#ifndef GL_SUN_mesh_array
+#define GL_QUAD_MESH_SUN                  0x8614
+#define GL_TRIANGLE_MESH_SUN              0x8615
+#endif
+
+#ifndef GL_SUN_slice_accum
+#define GL_SLICE_ACCUM_SUN                0x85CC
+#endif
+
+#ifndef GL_NV_multisample_filter_hint
+#define GL_MULTISAMPLE_FILTER_HINT_NV     0x8534
+#endif
+
+#ifndef GL_NV_depth_clamp
+#define GL_DEPTH_CLAMP_NV                 0x864F
+#endif
+
+#ifndef GL_NV_occlusion_query
+#define GL_PIXEL_COUNTER_BITS_NV          0x8864
+#define GL_CURRENT_OCCLUSION_QUERY_ID_NV  0x8865
+#define GL_PIXEL_COUNT_NV                 0x8866
+#define GL_PIXEL_COUNT_AVAILABLE_NV       0x8867
+#endif
+
+#ifndef GL_NV_point_sprite
+#define GL_POINT_SPRITE_NV                0x8861
+#define GL_COORD_REPLACE_NV               0x8862
+#define GL_POINT_SPRITE_R_MODE_NV         0x8863
+#endif
+
+#ifndef GL_NV_texture_shader3
+#define GL_OFFSET_PROJECTIVE_TEXTURE_2D_NV 0x8850
+#define GL_OFFSET_PROJECTIVE_TEXTURE_2D_SCALE_NV 0x8851
+#define GL_OFFSET_PROJECTIVE_TEXTURE_RECTANGLE_NV 0x8852
+#define GL_OFFSET_PROJECTIVE_TEXTURE_RECTANGLE_SCALE_NV 0x8853
+#define GL_OFFSET_HILO_TEXTURE_2D_NV      0x8854
+#define GL_OFFSET_HILO_TEXTURE_RECTANGLE_NV 0x8855
+#define GL_OFFSET_HILO_PROJECTIVE_TEXTURE_2D_NV 0x8856
+#define GL_OFFSET_HILO_PROJECTIVE_TEXTURE_RECTANGLE_NV 0x8857
+#define GL_DEPENDENT_HILO_TEXTURE_2D_NV   0x8858
+#define GL_DEPENDENT_RGB_TEXTURE_3D_NV    0x8859
+#define GL_DEPENDENT_RGB_TEXTURE_CUBE_MAP_NV 0x885A
+#define GL_DOT_PRODUCT_PASS_THROUGH_NV    0x885B
+#define GL_DOT_PRODUCT_TEXTURE_1D_NV      0x885C
+#define GL_DOT_PRODUCT_AFFINE_DEPTH_REPLACE_NV 0x885D
+#define GL_HILO8_NV                       0x885E
+#define GL_SIGNED_HILO8_NV                0x885F
+#define GL_FORCE_BLUE_TO_ONE_NV           0x8860
+#endif
+
+#ifndef GL_NV_vertex_program1_1
+#endif
+
+#ifndef GL_EXT_shadow_funcs
+#endif
+
+#ifndef GL_EXT_stencil_two_side
+#define GL_STENCIL_TEST_TWO_SIDE_EXT      0x8910
+#define GL_ACTIVE_STENCIL_FACE_EXT        0x8911
+#endif
+
+#ifndef GL_ATI_text_fragment_shader
+#define GL_TEXT_FRAGMENT_SHADER_ATI       0x8200
+#endif
+
+#ifndef GL_APPLE_client_storage
+#define GL_UNPACK_CLIENT_STORAGE_APPLE    0x85B2
+#endif
+
+#ifndef GL_APPLE_element_array
+#define GL_ELEMENT_ARRAY_APPLE            0x8768
+#define GL_ELEMENT_ARRAY_TYPE_APPLE       0x8769
+#define GL_ELEMENT_ARRAY_POINTER_APPLE    0x876A
+#endif
+
+#ifndef GL_APPLE_fence
+#define GL_DRAW_PIXELS_APPLE              0x8A0A
+#define GL_FENCE_APPLE                    0x8A0B
+#endif
+
+#ifndef GL_APPLE_vertex_array_object
+#define GL_VERTEX_ARRAY_BINDING_APPLE     0x85B5
+#endif
+
+#ifndef GL_APPLE_vertex_array_range
+#define GL_VERTEX_ARRAY_RANGE_APPLE       0x851D
+#define GL_VERTEX_ARRAY_RANGE_LENGTH_APPLE 0x851E
+#define GL_VERTEX_ARRAY_STORAGE_HINT_APPLE 0x851F
+#define GL_VERTEX_ARRAY_RANGE_POINTER_APPLE 0x8521
+#define GL_STORAGE_CACHED_APPLE           0x85BE
+#define GL_STORAGE_SHARED_APPLE           0x85BF
+#endif
+
+#ifndef GL_APPLE_ycbcr_422
+#define GL_YCBCR_422_APPLE                0x85B9
+#define GL_UNSIGNED_SHORT_8_8_APPLE       0x85BA
+#define GL_UNSIGNED_SHORT_8_8_REV_APPLE   0x85BB
+#endif
+
+#ifndef GL_S3_s3tc
+#define GL_RGB_S3TC                       0x83A0
+#define GL_RGB4_S3TC                      0x83A1
+#define GL_RGBA_S3TC                      0x83A2
+#define GL_RGBA4_S3TC                     0x83A3
+#endif
+
+#ifndef GL_ATI_draw_buffers
+#define GL_MAX_DRAW_BUFFERS_ATI           0x8824
+#define GL_DRAW_BUFFER0_ATI               0x8825
+#define GL_DRAW_BUFFER1_ATI               0x8826
+#define GL_DRAW_BUFFER2_ATI               0x8827
+#define GL_DRAW_BUFFER3_ATI               0x8828
+#define GL_DRAW_BUFFER4_ATI               0x8829
+#define GL_DRAW_BUFFER5_ATI               0x882A
+#define GL_DRAW_BUFFER6_ATI               0x882B
+#define GL_DRAW_BUFFER7_ATI               0x882C
+#define GL_DRAW_BUFFER8_ATI               0x882D
+#define GL_DRAW_BUFFER9_ATI               0x882E
+#define GL_DRAW_BUFFER10_ATI              0x882F
+#define GL_DRAW_BUFFER11_ATI              0x8830
+#define GL_DRAW_BUFFER12_ATI              0x8831
+#define GL_DRAW_BUFFER13_ATI              0x8832
+#define GL_DRAW_BUFFER14_ATI              0x8833
+#define GL_DRAW_BUFFER15_ATI              0x8834
+#endif
+
+#ifndef GL_ATI_pixel_format_float
+#define GL_TYPE_RGBA_FLOAT_ATI            0x8820
+#define GL_COLOR_CLEAR_UNCLAMPED_VALUE_ATI 0x8835
+#endif
+
+#ifndef GL_ATI_texture_env_combine3
+#define GL_MODULATE_ADD_ATI               0x8744
+#define GL_MODULATE_SIGNED_ADD_ATI        0x8745
+#define GL_MODULATE_SUBTRACT_ATI          0x8746
+#endif
+
+#ifndef GL_ATI_texture_float
+#define GL_RGBA_FLOAT32_ATI               0x8814
+#define GL_RGB_FLOAT32_ATI                0x8815
+#define GL_ALPHA_FLOAT32_ATI              0x8816
+#define GL_INTENSITY_FLOAT32_ATI          0x8817
+#define GL_LUMINANCE_FLOAT32_ATI          0x8818
+#define GL_LUMINANCE_ALPHA_FLOAT32_ATI    0x8819
+#define GL_RGBA_FLOAT16_ATI               0x881A
+#define GL_RGB_FLOAT16_ATI                0x881B
+#define GL_ALPHA_FLOAT16_ATI              0x881C
+#define GL_INTENSITY_FLOAT16_ATI          0x881D
+#define GL_LUMINANCE_FLOAT16_ATI          0x881E
+#define GL_LUMINANCE_ALPHA_FLOAT16_ATI    0x881F
+#endif
+
+#ifndef GL_NV_float_buffer
+#define GL_FLOAT_R_NV                     0x8880
+#define GL_FLOAT_RG_NV                    0x8881
+#define GL_FLOAT_RGB_NV                   0x8882
+#define GL_FLOAT_RGBA_NV                  0x8883
+#define GL_FLOAT_R16_NV                   0x8884
+#define GL_FLOAT_R32_NV                   0x8885
+#define GL_FLOAT_RG16_NV                  0x8886
+#define GL_FLOAT_RG32_NV                  0x8887
+#define GL_FLOAT_RGB16_NV                 0x8888
+#define GL_FLOAT_RGB32_NV                 0x8889
+#define GL_FLOAT_RGBA16_NV                0x888A
+#define GL_FLOAT_RGBA32_NV                0x888B
+#define GL_TEXTURE_FLOAT_COMPONENTS_NV    0x888C
+#define GL_FLOAT_CLEAR_COLOR_VALUE_NV     0x888D
+#define GL_FLOAT_RGBA_MODE_NV             0x888E
+#endif
+
+#ifndef GL_NV_fragment_program
+#define GL_MAX_FRAGMENT_PROGRAM_LOCAL_PARAMETERS_NV 0x8868
+#define GL_FRAGMENT_PROGRAM_NV            0x8870
+#define GL_MAX_TEXTURE_COORDS_NV          0x8871
+#define GL_MAX_TEXTURE_IMAGE_UNITS_NV     0x8872
+#define GL_FRAGMENT_PROGRAM_BINDING_NV    0x8873
+#define GL_PROGRAM_ERROR_STRING_NV        0x8874
+#endif
+
+#ifndef GL_NV_half_float
+#define GL_HALF_FLOAT_NV                  0x140B
+#endif
+
+#ifndef GL_NV_pixel_data_range
+#define GL_WRITE_PIXEL_DATA_RANGE_NV      0x8878
+#define GL_READ_PIXEL_DATA_RANGE_NV       0x8879
+#define GL_WRITE_PIXEL_DATA_RANGE_LENGTH_NV 0x887A
+#define GL_READ_PIXEL_DATA_RANGE_LENGTH_NV 0x887B
+#define GL_WRITE_PIXEL_DATA_RANGE_POINTER_NV 0x887C
+#define GL_READ_PIXEL_DATA_RANGE_POINTER_NV 0x887D
+#endif
+
+#ifndef GL_NV_primitive_restart
+#define GL_PRIMITIVE_RESTART_NV           0x8558
+#define GL_PRIMITIVE_RESTART_INDEX_NV     0x8559
+#endif
+
+#ifndef GL_NV_texture_expand_normal
+#define GL_TEXTURE_UNSIGNED_REMAP_MODE_NV 0x888F
+#endif
+
+#ifndef GL_NV_vertex_program2
+#endif
+
+#ifndef GL_ATI_map_object_buffer
+#endif
+
+#ifndef GL_ATI_separate_stencil
+#define GL_STENCIL_BACK_FUNC_ATI          0x8800
+#define GL_STENCIL_BACK_FAIL_ATI          0x8801
+#define GL_STENCIL_BACK_PASS_DEPTH_FAIL_ATI 0x8802
+#define GL_STENCIL_BACK_PASS_DEPTH_PASS_ATI 0x8803
+#endif
+
+#ifndef GL_ATI_vertex_attrib_array_object
+#endif
+
+#ifndef GL_OES_read_format
+#define GL_IMPLEMENTATION_COLOR_READ_TYPE_OES 0x8B9A
+#define GL_IMPLEMENTATION_COLOR_READ_FORMAT_OES 0x8B9B
+#endif
+
+#ifndef GL_EXT_depth_bounds_test
+#define GL_DEPTH_BOUNDS_TEST_EXT          0x8890
+#define GL_DEPTH_BOUNDS_EXT               0x8891
+#endif
+
+#ifndef GL_EXT_texture_mirror_clamp
+#define GL_MIRROR_CLAMP_EXT               0x8742
+#define GL_MIRROR_CLAMP_TO_EDGE_EXT       0x8743
+#define GL_MIRROR_CLAMP_TO_BORDER_EXT     0x8912
+#endif
+
+#ifndef GL_EXT_blend_equation_separate
+#define GL_BLEND_EQUATION_RGB_EXT         GL_BLEND_EQUATION
+#define GL_BLEND_EQUATION_ALPHA_EXT       0x883D
+#endif
+
+#ifndef GL_MESA_pack_invert
+#define GL_PACK_INVERT_MESA               0x8758
+#endif
+
+#ifndef GL_MESA_ycbcr_texture
+#define GL_UNSIGNED_SHORT_8_8_MESA        0x85BA
+#define GL_UNSIGNED_SHORT_8_8_REV_MESA    0x85BB
+#define GL_YCBCR_MESA                     0x8757
+#endif
+
+#ifndef GL_EXT_pixel_buffer_object
+#define GL_PIXEL_PACK_BUFFER_EXT          0x88EB
+#define GL_PIXEL_UNPACK_BUFFER_EXT        0x88EC
+#define GL_PIXEL_PACK_BUFFER_BINDING_EXT  0x88ED
+#define GL_PIXEL_UNPACK_BUFFER_BINDING_EXT 0x88EF
+#endif
+
+#ifndef GL_NV_fragment_program_option
+#endif
+
+#ifndef GL_NV_fragment_program2
+#define GL_MAX_PROGRAM_EXEC_INSTRUCTIONS_NV 0x88F4
+#define GL_MAX_PROGRAM_CALL_DEPTH_NV      0x88F5
+#define GL_MAX_PROGRAM_IF_DEPTH_NV        0x88F6
+#define GL_MAX_PROGRAM_LOOP_DEPTH_NV      0x88F7
+#define GL_MAX_PROGRAM_LOOP_COUNT_NV      0x88F8
+#endif
+
+#ifndef GL_NV_vertex_program2_option
+  /* reuse GL_MAX_PROGRAM_EXEC_INSTRUCTIONS_NV */
+  /* reuse GL_MAX_PROGRAM_CALL_DEPTH_NV */
+#endif
+
+#ifndef GL_NV_vertex_program3
+  /* reuse GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB */
+#endif
+
+#ifndef GL_EXT_framebuffer_object
+#define GL_INVALID_FRAMEBUFFER_OPERATION_EXT 0x0506
+#define GL_MAX_RENDERBUFFER_SIZE_EXT      0x84E8
+#define GL_FRAMEBUFFER_BINDING_EXT        0x8CA6
+#define GL_RENDERBUFFER_BINDING_EXT       0x8CA7
+#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE_EXT 0x8CD0
+#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_EXT 0x8CD1
+#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL_EXT 0x8CD2
+#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE_EXT 0x8CD3
+#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_3D_ZOFFSET_EXT 0x8CD4
+#define GL_FRAMEBUFFER_COMPLETE_EXT       0x8CD5
+#define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT 0x8CD6
+#define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT 0x8CD7
+#define GL_FRAMEBUFFER_INCOMPLETE_DUPLICATE_ATTACHMENT_EXT 0x8CD8
+#define GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT 0x8CD9
+#define GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT 0x8CDA
+#define GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT 0x8CDB
+#define GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT 0x8CDC
+#define GL_FRAMEBUFFER_UNSUPPORTED_EXT    0x8CDD
+#define GL_MAX_COLOR_ATTACHMENTS_EXT      0x8CDF
+#define GL_COLOR_ATTACHMENT0_EXT          0x8CE0
+#define GL_COLOR_ATTACHMENT1_EXT          0x8CE1
+#define GL_COLOR_ATTACHMENT2_EXT          0x8CE2
+#define GL_COLOR_ATTACHMENT3_EXT          0x8CE3
+#define GL_COLOR_ATTACHMENT4_EXT          0x8CE4
+#define GL_COLOR_ATTACHMENT5_EXT          0x8CE5
+#define GL_COLOR_ATTACHMENT6_EXT          0x8CE6
+#define GL_COLOR_ATTACHMENT7_EXT          0x8CE7
+#define GL_COLOR_ATTACHMENT8_EXT          0x8CE8
+#define GL_COLOR_ATTACHMENT9_EXT          0x8CE9
+#define GL_COLOR_ATTACHMENT10_EXT         0x8CEA
+#define GL_COLOR_ATTACHMENT11_EXT         0x8CEB
+#define GL_COLOR_ATTACHMENT12_EXT         0x8CEC
+#define GL_COLOR_ATTACHMENT13_EXT         0x8CED
+#define GL_COLOR_ATTACHMENT14_EXT         0x8CEE
+#define GL_COLOR_ATTACHMENT15_EXT         0x8CEF
+#define GL_DEPTH_ATTACHMENT_EXT           0x8D00
+#define GL_STENCIL_ATTACHMENT_EXT         0x8D20
+#define GL_FRAMEBUFFER_EXT                0x8D40
+#define GL_RENDERBUFFER_EXT               0x8D41
+#define GL_RENDERBUFFER_WIDTH_EXT         0x8D42
+#define GL_RENDERBUFFER_HEIGHT_EXT        0x8D43
+#define GL_RENDERBUFFER_INTERNAL_FORMAT_EXT 0x8D44
+#define GL_STENCIL_INDEX_EXT              0x8D45
+#define GL_STENCIL_INDEX1_EXT             0x8D46
+#define GL_STENCIL_INDEX4_EXT             0x8D47
+#define GL_STENCIL_INDEX8_EXT             0x8D48
+#define GL_STENCIL_INDEX16_EXT            0x8D49
+#define GL_RENDERBUFFER_RED_SIZE_EXT      0x8D50
+#define GL_RENDERBUFFER_GREEN_SIZE_EXT    0x8D51
+#define GL_RENDERBUFFER_BLUE_SIZE_EXT     0x8D52
+#define GL_RENDERBUFFER_ALPHA_SIZE_EXT    0x8D53
+#define GL_RENDERBUFFER_DEPTH_SIZE_EXT    0x8D54
+#define GL_RENDERBUFFER_STENCIL_SIZE_EXT  0x8D55
+#endif
+
+#ifndef GL_GREMEDY_string_marker
+#endif
+
+#ifndef GL_EXT_Cg_shader
+#define GL_CG_VERTEX_SHADER_EXT           0x890E
+#define GL_CG_FRAGMENT_SHADER_EXT         0x890E
+#endif
+
+#ifndef GL_NV_element_array
+#define GL_ELEMENT_ARRAY_TYPE_NV          0x8769
+#define GL_ELEMENT_ARRAY_POINTER_NV       0x876A
+#endif
+
+#ifndef GL_NV_pixel_buffer_object
+#define GL_PIXEL_PACK_BUFFER_NV             0x88EB
+#define GL_PIXEL_UNPACK_BUFFER_NV           0x88EC
+#define GL_PIXEL_PACK_BUFFER_BINDING_NV     0x88ED
+#define GL_PIXEL_UNPACK_BUFFER_BINDING_NV   0x88EF
+#endif
+
+#ifndef GL_NV_stencil_two_side
+#define GL_STENCIL_TEST_TWO_SIDE_NV       0x8910
+#define GL_ACTIVE_STENCIL_FACE_NV         0x8911
+#endif
+
+  /*************************************************************/
+
+#include <stddef.h>
+#ifndef GL_VERSION_2_0
+  /* GL type for program/shader text */
+  typedef char GLchar;      /* native character */
+#endif
+
+#ifndef GL_VERSION_1_5
+  /* GL types for handling large vertex buffer objects */
+  typedef ptrdiff_t GLintptr;
+  typedef ptrdiff_t GLsizeiptr;
+#endif
+
+#ifndef GL_ARB_vertex_buffer_object
+  /* GL types for handling large vertex buffer objects */
+  typedef ptrdiff_t GLintptrARB;
+  typedef ptrdiff_t GLsizeiptrARB;
+#endif
+
+#ifndef GL_ARB_shader_objects
+  /* GL types for handling shader object handles and program/shader text */
+  typedef char GLcharARB;   /* native character */
+  typedef unsigned int GLhandleARB; /* shader object handle */
+#endif
+
+  /* GL types for "half" precision (s10e5) float data in host memory */
+#ifndef GL_ARB_half_float_pixel
+  typedef unsigned short GLhalfARB;
+#endif
+
+#ifndef GL_NV_half_float
+  typedef unsigned short GLhalfNV;
+#endif
+
+#ifndef GL_VERSION_1_2
+#define GL_VERSION_1_2 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glBlendColor (GLclampf, GLclampf, GLclampf, GLclampf);
+  GLAPI void APIENTRY glBlendEquation (GLenum);
+  GLAPI void APIENTRY glDrawRangeElements (GLenum, GLuint, GLuint, GLsizei, GLenum, const GLvoid *);
+  GLAPI void APIENTRY glColorTable (GLenum, GLenum, GLsizei, GLenum, GLenum, const GLvoid *);
+  GLAPI void APIENTRY glColorTableParameterfv (GLenum, GLenum, const GLfloat *);
+  GLAPI void APIENTRY glColorTableParameteriv (GLenum, GLenum, const GLint *);
+  GLAPI void APIENTRY glCopyColorTable (GLenum, GLenum, GLint, GLint, GLsizei);
+  GLAPI void APIENTRY glGetColorTable (GLenum, GLenum, GLenum, GLvoid *);
+  GLAPI void APIENTRY glGetColorTableParameterfv (GLenum, GLenum, GLfloat *);
+  GLAPI void APIENTRY glGetColorTableParameteriv (GLenum, GLenum, GLint *);
+  GLAPI void APIENTRY glColorSubTable (GLenum, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *);
+  GLAPI void APIENTRY glCopyColorSubTable (GLenum, GLsizei, GLint, GLint, GLsizei);
+  GLAPI void APIENTRY glConvolutionFilter1D (GLenum, GLenum, GLsizei, GLenum, GLenum, const GLvoid *);
+  GLAPI void APIENTRY glConvolutionFilter2D (GLenum, GLenum, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *);
+  GLAPI void APIENTRY glConvolutionParameterf (GLenum, GLenum, GLfloat);
+  GLAPI void APIENTRY glConvolutionParameterfv (GLenum, GLenum, const GLfloat *);
+  GLAPI void APIENTRY glConvolutionParameteri (GLenum, GLenum, GLint);
+  GLAPI void APIENTRY glConvolutionParameteriv (GLenum, GLenum, const GLint *);
+  GLAPI void APIENTRY glCopyConvolutionFilter1D (GLenum, GLenum, GLint, GLint, GLsizei);
+  GLAPI void APIENTRY glCopyConvolutionFilter2D (GLenum, GLenum, GLint, GLint, GLsizei, GLsizei);
+  GLAPI void APIENTRY glGetConvolutionFilter (GLenum, GLenum, GLenum, GLvoid *);
+  GLAPI void APIENTRY glGetConvolutionParameterfv (GLenum, GLenum, GLfloat *);
+  GLAPI void APIENTRY glGetConvolutionParameteriv (GLenum, GLenum, GLint *);
+  GLAPI void APIENTRY glGetSeparableFilter (GLenum, GLenum, GLenum, GLvoid *, GLvoid *, GLvoid *);
+  GLAPI void APIENTRY glSeparableFilter2D (GLenum, GLenum, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *, const GLvoid *);
+  GLAPI void APIENTRY glGetHistogram (GLenum, GLboolean, GLenum, GLenum, GLvoid *);
+  GLAPI void APIENTRY glGetHistogramParameterfv (GLenum, GLenum, GLfloat *);
+  GLAPI void APIENTRY glGetHistogramParameteriv (GLenum, GLenum, GLint *);
+  GLAPI void APIENTRY glGetMinmax (GLenum, GLboolean, GLenum, GLenum, GLvoid *);
+  GLAPI void APIENTRY glGetMinmaxParameterfv (GLenum, GLenum, GLfloat *);
+  GLAPI void APIENTRY glGetMinmaxParameteriv (GLenum, GLenum, GLint *);
+  GLAPI void APIENTRY glHistogram (GLenum, GLsizei, GLenum, GLboolean);
+  GLAPI void APIENTRY glMinmax (GLenum, GLenum, GLboolean);
+  GLAPI void APIENTRY glResetHistogram (GLenum);
+  GLAPI void APIENTRY glResetMinmax (GLenum);
+  GLAPI void APIENTRY glTexImage3D (GLenum, GLint, GLint, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *);
+  GLAPI void APIENTRY glTexSubImage3D (GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *);
+  GLAPI void APIENTRY glCopyTexSubImage3D (GLenum, GLint, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLBLENDCOLORPROC) (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);
+  typedef void (APIENTRYP PFNGLBLENDEQUATIONPROC) (GLenum mode);
+  typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTSPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid *indices);
+  typedef void (APIENTRYP PFNGLCOLORTABLEPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *table);
+  typedef void (APIENTRYP PFNGLCOLORTABLEPARAMETERFVPROC) (GLenum target, GLenum pname, const GLfloat *params);
+  typedef void (APIENTRYP PFNGLCOLORTABLEPARAMETERIVPROC) (GLenum target, GLenum pname, const GLint *params);
+  typedef void (APIENTRYP PFNGLCOPYCOLORTABLEPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width);
+  typedef void (APIENTRYP PFNGLGETCOLORTABLEPROC) (GLenum target, GLenum format, GLenum type, GLvoid *table);
+  typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params);
+  typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params);
+  typedef void (APIENTRYP PFNGLCOLORSUBTABLEPROC) (GLenum target, GLsizei start, GLsizei count, GLenum format, GLenum type, const GLvoid *data);
+  typedef void (APIENTRYP PFNGLCOPYCOLORSUBTABLEPROC) (GLenum target, GLsizei start, GLint x, GLint y, GLsizei width);
+  typedef void (APIENTRYP PFNGLCONVOLUTIONFILTER1DPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *image);
+  typedef void (APIENTRYP PFNGLCONVOLUTIONFILTER2DPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *image);
+  typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERFPROC) (GLenum target, GLenum pname, GLfloat params);
+  typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERFVPROC) (GLenum target, GLenum pname, const GLfloat *params);
+  typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERIPROC) (GLenum target, GLenum pname, GLint params);
+  typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERIVPROC) (GLenum target, GLenum pname, const GLint *params);
+  typedef void (APIENTRYP PFNGLCOPYCONVOLUTIONFILTER1DPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width);
+  typedef void (APIENTRYP PFNGLCOPYCONVOLUTIONFILTER2DPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height);
+  typedef void (APIENTRYP PFNGLGETCONVOLUTIONFILTERPROC) (GLenum target, GLenum format, GLenum type, GLvoid *image);
+  typedef void (APIENTRYP PFNGLGETCONVOLUTIONPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params);
+  typedef void (APIENTRYP PFNGLGETCONVOLUTIONPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params);
+  typedef void (APIENTRYP PFNGLGETSEPARABLEFILTERPROC) (GLenum target, GLenum format, GLenum type, GLvoid *row, GLvoid *column, GLvoid *span);
+  typedef void (APIENTRYP PFNGLSEPARABLEFILTER2DPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *row, const GLvoid *column);
+  typedef void (APIENTRYP PFNGLGETHISTOGRAMPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLvoid *values);
+  typedef void (APIENTRYP PFNGLGETHISTOGRAMPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params);
+  typedef void (APIENTRYP PFNGLGETHISTOGRAMPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params);
+  typedef void (APIENTRYP PFNGLGETMINMAXPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLvoid *values);
+  typedef void (APIENTRYP PFNGLGETMINMAXPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params);
+  typedef void (APIENTRYP PFNGLGETMINMAXPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params);
+  typedef void (APIENTRYP PFNGLHISTOGRAMPROC) (GLenum target, GLsizei width, GLenum internalformat, GLboolean sink);
+  typedef void (APIENTRYP PFNGLMINMAXPROC) (GLenum target, GLenum internalformat, GLboolean sink);
+  typedef void (APIENTRYP PFNGLRESETHISTOGRAMPROC) (GLenum target);
+  typedef void (APIENTRYP PFNGLRESETMINMAXPROC) (GLenum target);
+  typedef void (APIENTRYP PFNGLTEXIMAGE3DPROC) (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+  typedef void (APIENTRYP PFNGLTEXSUBIMAGE3DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid *pixels);
+  typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE3DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+#endif
+
+#ifndef GL_VERSION_1_3
+#define GL_VERSION_1_3 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glActiveTexture (GLenum);
+  GLAPI void APIENTRY glClientActiveTexture (GLenum);
+  GLAPI void APIENTRY glMultiTexCoord1d (GLenum, GLdouble);
+  GLAPI void APIENTRY glMultiTexCoord1dv (GLenum, const GLdouble *);
+  GLAPI void APIENTRY glMultiTexCoord1f (GLenum, GLfloat);
+  GLAPI void APIENTRY glMultiTexCoord1fv (GLenum, const GLfloat *);
+  GLAPI void APIENTRY glMultiTexCoord1i (GLenum, GLint);
+  GLAPI void APIENTRY glMultiTexCoord1iv (GLenum, const GLint *);
+  GLAPI void APIENTRY glMultiTexCoord1s (GLenum, GLshort);
+  GLAPI void APIENTRY glMultiTexCoord1sv (GLenum, const GLshort *);
+  GLAPI void APIENTRY glMultiTexCoord2d (GLenum, GLdouble, GLdouble);
+  GLAPI void APIENTRY glMultiTexCoord2dv (GLenum, const GLdouble *);
+  GLAPI void APIENTRY glMultiTexCoord2f (GLenum, GLfloat, GLfloat);
+  GLAPI void APIENTRY glMultiTexCoord2fv (GLenum, const GLfloat *);
+  GLAPI void APIENTRY glMultiTexCoord2i (GLenum, GLint, GLint);
+  GLAPI void APIENTRY glMultiTexCoord2iv (GLenum, const GLint *);
+  GLAPI void APIENTRY glMultiTexCoord2s (GLenum, GLshort, GLshort);
+  GLAPI void APIENTRY glMultiTexCoord2sv (GLenum, const GLshort *);
+  GLAPI void APIENTRY glMultiTexCoord3d (GLenum, GLdouble, GLdouble, GLdouble);
+  GLAPI void APIENTRY glMultiTexCoord3dv (GLenum, const GLdouble *);
+  GLAPI void APIENTRY glMultiTexCoord3f (GLenum, GLfloat, GLfloat, GLfloat);
+  GLAPI void APIENTRY glMultiTexCoord3fv (GLenum, const GLfloat *);
+  GLAPI void APIENTRY glMultiTexCoord3i (GLenum, GLint, GLint, GLint);
+  GLAPI void APIENTRY glMultiTexCoord3iv (GLenum, const GLint *);
+  GLAPI void APIENTRY glMultiTexCoord3s (GLenum, GLshort, GLshort, GLshort);
+  GLAPI void APIENTRY glMultiTexCoord3sv (GLenum, const GLshort *);
+  GLAPI void APIENTRY glMultiTexCoord4d (GLenum, GLdouble, GLdouble, GLdouble, GLdouble);
+  GLAPI void APIENTRY glMultiTexCoord4dv (GLenum, const GLdouble *);
+  GLAPI void APIENTRY glMultiTexCoord4f (GLenum, GLfloat, GLfloat, GLfloat, GLfloat);
+  GLAPI void APIENTRY glMultiTexCoord4fv (GLenum, const GLfloat *);
+  GLAPI void APIENTRY glMultiTexCoord4i (GLenum, GLint, GLint, GLint, GLint);
+  GLAPI void APIENTRY glMultiTexCoord4iv (GLenum, const GLint *);
+  GLAPI void APIENTRY glMultiTexCoord4s (GLenum, GLshort, GLshort, GLshort, GLshort);
+  GLAPI void APIENTRY glMultiTexCoord4sv (GLenum, const GLshort *);
+  GLAPI void APIENTRY glLoadTransposeMatrixf (const GLfloat *);
+  GLAPI void APIENTRY glLoadTransposeMatrixd (const GLdouble *);
+  GLAPI void APIENTRY glMultTransposeMatrixf (const GLfloat *);
+  GLAPI void APIENTRY glMultTransposeMatrixd (const GLdouble *);
+  GLAPI void APIENTRY glSampleCoverage (GLclampf, GLboolean);
+  GLAPI void APIENTRY glCompressedTexImage3D (GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLsizei, const GLvoid *);
+  GLAPI void APIENTRY glCompressedTexImage2D (GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLsizei, const GLvoid *);
+  GLAPI void APIENTRY glCompressedTexImage1D (GLenum, GLint, GLenum, GLsizei, GLint, GLsizei, const GLvoid *);
+  GLAPI void APIENTRY glCompressedTexSubImage3D (GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid *);
+  GLAPI void APIENTRY glCompressedTexSubImage2D (GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid *);
+  GLAPI void APIENTRY glCompressedTexSubImage1D (GLenum, GLint, GLint, GLsizei, GLenum, GLsizei, const GLvoid *);
+  GLAPI void APIENTRY glGetCompressedTexImage (GLenum, GLint, GLvoid *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLACTIVETEXTUREPROC) (GLenum texture);
+  typedef void (APIENTRYP PFNGLCLIENTACTIVETEXTUREPROC) (GLenum texture);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD1DPROC) (GLenum target, GLdouble s);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD1DVPROC) (GLenum target, const GLdouble *v);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD1FPROC) (GLenum target, GLfloat s);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD1FVPROC) (GLenum target, const GLfloat *v);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD1IPROC) (GLenum target, GLint s);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD1IVPROC) (GLenum target, const GLint *v);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD1SPROC) (GLenum target, GLshort s);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD1SVPROC) (GLenum target, const GLshort *v);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD2DPROC) (GLenum target, GLdouble s, GLdouble t);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD2DVPROC) (GLenum target, const GLdouble *v);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD2FPROC) (GLenum target, GLfloat s, GLfloat t);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD2FVPROC) (GLenum target, const GLfloat *v);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD2IPROC) (GLenum target, GLint s, GLint t);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD2IVPROC) (GLenum target, const GLint *v);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD2SPROC) (GLenum target, GLshort s, GLshort t);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD2SVPROC) (GLenum target, const GLshort *v);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD3DPROC) (GLenum target, GLdouble s, GLdouble t, GLdouble r);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD3DVPROC) (GLenum target, const GLdouble *v);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD3FPROC) (GLenum target, GLfloat s, GLfloat t, GLfloat r);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD3FVPROC) (GLenum target, const GLfloat *v);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD3IPROC) (GLenum target, GLint s, GLint t, GLint r);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD3IVPROC) (GLenum target, const GLint *v);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD3SPROC) (GLenum target, GLshort s, GLshort t, GLshort r);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD3SVPROC) (GLenum target, const GLshort *v);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD4DPROC) (GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD4DVPROC) (GLenum target, const GLdouble *v);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD4FPROC) (GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD4FVPROC) (GLenum target, const GLfloat *v);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD4IPROC) (GLenum target, GLint s, GLint t, GLint r, GLint q);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD4IVPROC) (GLenum target, const GLint *v);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD4SPROC) (GLenum target, GLshort s, GLshort t, GLshort r, GLshort q);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD4SVPROC) (GLenum target, const GLshort *v);
+  typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXFPROC) (const GLfloat *m);
+  typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXDPROC) (const GLdouble *m);
+  typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXFPROC) (const GLfloat *m);
+  typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXDPROC) (const GLdouble *m);
+  typedef void (APIENTRYP PFNGLSAMPLECOVERAGEPROC) (GLclampf value, GLboolean invert);
+  typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE3DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *data);
+  typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE2DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *data);
+  typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE1DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid *data);
+  typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid *data);
+  typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *data);
+  typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC) (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const GLvoid *data);
+  typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXIMAGEPROC) (GLenum target, GLint level, GLvoid *img);
+#endif
+
+#ifndef GL_VERSION_1_4
+#define GL_VERSION_1_4 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glBlendFuncSeparate (GLenum, GLenum, GLenum, GLenum);
+  GLAPI void APIENTRY glFogCoordf (GLfloat);
+  GLAPI void APIENTRY glFogCoordfv (const GLfloat *);
+  GLAPI void APIENTRY glFogCoordd (GLdouble);
+  GLAPI void APIENTRY glFogCoorddv (const GLdouble *);
+  GLAPI void APIENTRY glFogCoordPointer (GLenum, GLsizei, const GLvoid *);
+  GLAPI void APIENTRY glMultiDrawArrays (GLenum, GLint *, GLsizei *, GLsizei);
+  GLAPI void APIENTRY glMultiDrawElements (GLenum, const GLsizei *, GLenum, const GLvoid* *, GLsizei);
+  GLAPI void APIENTRY glPointParameterf (GLenum, GLfloat);
+  GLAPI void APIENTRY glPointParameterfv (GLenum, const GLfloat *);
+  GLAPI void APIENTRY glPointParameteri (GLenum, GLint);
+  GLAPI void APIENTRY glPointParameteriv (GLenum, const GLint *);
+  GLAPI void APIENTRY glSecondaryColor3b (GLbyte, GLbyte, GLbyte);
+  GLAPI void APIENTRY glSecondaryColor3bv (const GLbyte *);
+  GLAPI void APIENTRY glSecondaryColor3d (GLdouble, GLdouble, GLdouble);
+  GLAPI void APIENTRY glSecondaryColor3dv (const GLdouble *);
+  GLAPI void APIENTRY glSecondaryColor3f (GLfloat, GLfloat, GLfloat);
+  GLAPI void APIENTRY glSecondaryColor3fv (const GLfloat *);
+  GLAPI void APIENTRY glSecondaryColor3i (GLint, GLint, GLint);
+  GLAPI void APIENTRY glSecondaryColor3iv (const GLint *);
+  GLAPI void APIENTRY glSecondaryColor3s (GLshort, GLshort, GLshort);
+  GLAPI void APIENTRY glSecondaryColor3sv (const GLshort *);
+  GLAPI void APIENTRY glSecondaryColor3ub (GLubyte, GLubyte, GLubyte);
+  GLAPI void APIENTRY glSecondaryColor3ubv (const GLubyte *);
+  GLAPI void APIENTRY glSecondaryColor3ui (GLuint, GLuint, GLuint);
+  GLAPI void APIENTRY glSecondaryColor3uiv (const GLuint *);
+  GLAPI void APIENTRY glSecondaryColor3us (GLushort, GLushort, GLushort);
+  GLAPI void APIENTRY glSecondaryColor3usv (const GLushort *);
+  GLAPI void APIENTRY glSecondaryColorPointer (GLint, GLenum, GLsizei, const GLvoid *);
+  GLAPI void APIENTRY glWindowPos2d (GLdouble, GLdouble);
+  GLAPI void APIENTRY glWindowPos2dv (const GLdouble *);
+  GLAPI void APIENTRY glWindowPos2f (GLfloat, GLfloat);
+  GLAPI void APIENTRY glWindowPos2fv (const GLfloat *);
+  GLAPI void APIENTRY glWindowPos2i (GLint, GLint);
+  GLAPI void APIENTRY glWindowPos2iv (const GLint *);
+  GLAPI void APIENTRY glWindowPos2s (GLshort, GLshort);
+  GLAPI void APIENTRY glWindowPos2sv (const GLshort *);
+  GLAPI void APIENTRY glWindowPos3d (GLdouble, GLdouble, GLdouble);
+  GLAPI void APIENTRY glWindowPos3dv (const GLdouble *);
+  GLAPI void APIENTRY glWindowPos3f (GLfloat, GLfloat, GLfloat);
+  GLAPI void APIENTRY glWindowPos3fv (const GLfloat *);
+  GLAPI void APIENTRY glWindowPos3i (GLint, GLint, GLint);
+  GLAPI void APIENTRY glWindowPos3iv (const GLint *);
+  GLAPI void APIENTRY glWindowPos3s (GLshort, GLshort, GLshort);
+  GLAPI void APIENTRY glWindowPos3sv (const GLshort *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);
+  typedef void (APIENTRYP PFNGLFOGCOORDFPROC) (GLfloat coord);
+  typedef void (APIENTRYP PFNGLFOGCOORDFVPROC) (const GLfloat *coord);
+  typedef void (APIENTRYP PFNGLFOGCOORDDPROC) (GLdouble coord);
+  typedef void (APIENTRYP PFNGLFOGCOORDDVPROC) (const GLdouble *coord);
+  typedef void (APIENTRYP PFNGLFOGCOORDPOINTERPROC) (GLenum type, GLsizei stride, const GLvoid *pointer);
+  typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSPROC) (GLenum mode, GLint *first, GLsizei *count, GLsizei primcount);
+  typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSPROC) (GLenum mode, const GLsizei *count, GLenum type, const GLvoid* *indices, GLsizei primcount);
+  typedef void (APIENTRYP PFNGLPOINTPARAMETERFPROC) (GLenum pname, GLfloat param);
+  typedef void (APIENTRYP PFNGLPOINTPARAMETERFVPROC) (GLenum pname, const GLfloat *params);
+  typedef void (APIENTRYP PFNGLPOINTPARAMETERIPROC) (GLenum pname, GLint param);
+  typedef void (APIENTRYP PFNGLPOINTPARAMETERIVPROC) (GLenum pname, const GLint *params);
+  typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BPROC) (GLbyte red, GLbyte green, GLbyte blue);
+  typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BVPROC) (const GLbyte *v);
+  typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DPROC) (GLdouble red, GLdouble green, GLdouble blue);
+  typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DVPROC) (const GLdouble *v);
+  typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FPROC) (GLfloat red, GLfloat green, GLfloat blue);
+  typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FVPROC) (const GLfloat *v);
+  typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IPROC) (GLint red, GLint green, GLint blue);
+  typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IVPROC) (const GLint *v);
+  typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SPROC) (GLshort red, GLshort green, GLshort blue);
+  typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SVPROC) (const GLshort *v);
+  typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBPROC) (GLubyte red, GLubyte green, GLubyte blue);
+  typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBVPROC) (const GLubyte *v);
+  typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIPROC) (GLuint red, GLuint green, GLuint blue);
+  typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIVPROC) (const GLuint *v);
+  typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USPROC) (GLushort red, GLushort green, GLushort blue);
+  typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USVPROC) (const GLushort *v);
+  typedef void (APIENTRYP PFNGLSECONDARYCOLORPOINTERPROC) (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+  typedef void (APIENTRYP PFNGLWINDOWPOS2DPROC) (GLdouble x, GLdouble y);
+  typedef void (APIENTRYP PFNGLWINDOWPOS2DVPROC) (const GLdouble *v);
+  typedef void (APIENTRYP PFNGLWINDOWPOS2FPROC) (GLfloat x, GLfloat y);
+  typedef void (APIENTRYP PFNGLWINDOWPOS2FVPROC) (const GLfloat *v);
+  typedef void (APIENTRYP PFNGLWINDOWPOS2IPROC) (GLint x, GLint y);
+  typedef void (APIENTRYP PFNGLWINDOWPOS2IVPROC) (const GLint *v);
+  typedef void (APIENTRYP PFNGLWINDOWPOS2SPROC) (GLshort x, GLshort y);
+  typedef void (APIENTRYP PFNGLWINDOWPOS2SVPROC) (const GLshort *v);
+  typedef void (APIENTRYP PFNGLWINDOWPOS3DPROC) (GLdouble x, GLdouble y, GLdouble z);
+  typedef void (APIENTRYP PFNGLWINDOWPOS3DVPROC) (const GLdouble *v);
+  typedef void (APIENTRYP PFNGLWINDOWPOS3FPROC) (GLfloat x, GLfloat y, GLfloat z);
+  typedef void (APIENTRYP PFNGLWINDOWPOS3FVPROC) (const GLfloat *v);
+  typedef void (APIENTRYP PFNGLWINDOWPOS3IPROC) (GLint x, GLint y, GLint z);
+  typedef void (APIENTRYP PFNGLWINDOWPOS3IVPROC) (const GLint *v);
+  typedef void (APIENTRYP PFNGLWINDOWPOS3SPROC) (GLshort x, GLshort y, GLshort z);
+  typedef void (APIENTRYP PFNGLWINDOWPOS3SVPROC) (const GLshort *v);
+#endif
+
+#ifndef GL_VERSION_1_5
+#define GL_VERSION_1_5 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glGenQueries (GLsizei, GLuint *);
+  GLAPI void APIENTRY glDeleteQueries (GLsizei, const GLuint *);
+  GLAPI GLboolean APIENTRY glIsQuery (GLuint);
+  GLAPI void APIENTRY glBeginQuery (GLenum, GLuint);
+  GLAPI void APIENTRY glEndQuery (GLenum);
+  GLAPI void APIENTRY glGetQueryiv (GLenum, GLenum, GLint *);
+  GLAPI void APIENTRY glGetQueryObjectiv (GLuint, GLenum, GLint *);
+  GLAPI void APIENTRY glGetQueryObjectuiv (GLuint, GLenum, GLuint *);
+  GLAPI void APIENTRY glBindBuffer (GLenum, GLuint);
+  GLAPI void APIENTRY glDeleteBuffers (GLsizei, const GLuint *);
+  GLAPI void APIENTRY glGenBuffers (GLsizei, GLuint *);
+  GLAPI GLboolean APIENTRY glIsBuffer (GLuint);
+  GLAPI void APIENTRY glBufferData (GLenum, GLsizeiptr, const GLvoid *, GLenum);
+  GLAPI void APIENTRY glBufferSubData (GLenum, GLintptr, GLsizeiptr, const GLvoid *);
+  GLAPI void APIENTRY glGetBufferSubData (GLenum, GLintptr, GLsizeiptr, GLvoid *);
+  GLAPI GLvoid* APIENTRY glMapBuffer (GLenum, GLenum);
+  GLAPI GLboolean APIENTRY glUnmapBuffer (GLenum);
+  GLAPI void APIENTRY glGetBufferParameteriv (GLenum, GLenum, GLint *);
+  GLAPI void APIENTRY glGetBufferPointerv (GLenum, GLenum, GLvoid* *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLGENQUERIESPROC) (GLsizei n, GLuint *ids);
+  typedef void (APIENTRYP PFNGLDELETEQUERIESPROC) (GLsizei n, const GLuint *ids);
+  typedef GLboolean (APIENTRYP PFNGLISQUERYPROC) (GLuint id);
+  typedef void (APIENTRYP PFNGLBEGINQUERYPROC) (GLenum target, GLuint id);
+  typedef void (APIENTRYP PFNGLENDQUERYPROC) (GLenum target);
+  typedef void (APIENTRYP PFNGLGETQUERYIVPROC) (GLenum target, GLenum pname, GLint *params);
+  typedef void (APIENTRYP PFNGLGETQUERYOBJECTIVPROC) (GLuint id, GLenum pname, GLint *params);
+  typedef void (APIENTRYP PFNGLGETQUERYOBJECTUIVPROC) (GLuint id, GLenum pname, GLuint *params);
+  typedef void (APIENTRYP PFNGLBINDBUFFERPROC) (GLenum target, GLuint buffer);
+  typedef void (APIENTRYP PFNGLDELETEBUFFERSPROC) (GLsizei n, const GLuint *buffers);
+  typedef void (APIENTRYP PFNGLGENBUFFERSPROC) (GLsizei n, GLuint *buffers);
+  typedef GLboolean (APIENTRYP PFNGLISBUFFERPROC) (GLuint buffer);
+  typedef void (APIENTRYP PFNGLBUFFERDATAPROC) (GLenum target, GLsizeiptr size, const GLvoid *data, GLenum usage);
+  typedef void (APIENTRYP PFNGLBUFFERSUBDATAPROC) (GLenum target, GLintptr offset, GLsizeiptr size, const GLvoid *data);
+  typedef void (APIENTRYP PFNGLGETBUFFERSUBDATAPROC) (GLenum target, GLintptr offset, GLsizeiptr size, GLvoid *data);
+  typedef GLvoid* (APIENTRYP PFNGLMAPBUFFERPROC) (GLenum target, GLenum access);
+  typedef GLboolean (APIENTRYP PFNGLUNMAPBUFFERPROC) (GLenum target);
+  typedef void (APIENTRYP PFNGLGETBUFFERPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params);
+  typedef void (APIENTRYP PFNGLGETBUFFERPOINTERVPROC) (GLenum target, GLenum pname, GLvoid* *params);
+#endif
+
+#ifndef GL_VERSION_2_0
+#define GL_VERSION_2_0 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glBlendEquationSeparate (GLenum, GLenum);
+  GLAPI void APIENTRY glDrawBuffers (GLsizei, const GLenum *);
+  GLAPI void APIENTRY glStencilOpSeparate (GLenum, GLenum, GLenum, GLenum);
+  GLAPI void APIENTRY glStencilFuncSeparate (GLenum, GLenum, GLint, GLuint);
+  GLAPI void APIENTRY glStencilMaskSeparate (GLenum, GLuint);
+  GLAPI void APIENTRY glAttachShader (GLuint, GLuint);
+  GLAPI void APIENTRY glBindAttribLocation (GLuint, GLuint, const GLchar *);
+  GLAPI void APIENTRY glCompileShader (GLuint);
+  GLAPI GLuint APIENTRY glCreateProgram (void);
+  GLAPI GLuint APIENTRY glCreateShader (GLenum);
+  GLAPI void APIENTRY glDeleteProgram (GLuint);
+  GLAPI void APIENTRY glDeleteShader (GLuint);
+  GLAPI void APIENTRY glDetachShader (GLuint, GLuint);
+  GLAPI void APIENTRY glDisableVertexAttribArray (GLuint);
+  GLAPI void APIENTRY glEnableVertexAttribArray (GLuint);
+  GLAPI void APIENTRY glGetActiveAttrib (GLuint, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLchar *);
+  GLAPI void APIENTRY glGetActiveUniform (GLuint, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLchar *);
+  GLAPI void APIENTRY glGetAttachedShaders (GLuint, GLsizei, GLsizei *, GLuint *);
+  GLAPI GLint APIENTRY glGetAttribLocation (GLuint, const GLchar *);
+  GLAPI void APIENTRY glGetProgramiv (GLuint, GLenum, GLint *);
+  GLAPI void APIENTRY glGetProgramInfoLog (GLuint, GLsizei, GLsizei *, GLchar *);
+  GLAPI void APIENTRY glGetShaderiv (GLuint, GLenum, GLint *);
+  GLAPI void APIENTRY glGetShaderInfoLog (GLuint, GLsizei, GLsizei *, GLchar *);
+  GLAPI void APIENTRY glGetShaderSource (GLuint, GLsizei, GLsizei *, GLchar *);
+  GLAPI GLint APIENTRY glGetUniformLocation (GLuint, const GLchar *);
+  GLAPI void APIENTRY glGetUniformfv (GLuint, GLint, GLfloat *);
+  GLAPI void APIENTRY glGetUniformiv (GLuint, GLint, GLint *);
+  GLAPI void APIENTRY glGetVertexAttribdv (GLuint, GLenum, GLdouble *);
+  GLAPI void APIENTRY glGetVertexAttribfv (GLuint, GLenum, GLfloat *);
+  GLAPI void APIENTRY glGetVertexAttribiv (GLuint, GLenum, GLint *);
+  GLAPI void APIENTRY glGetVertexAttribPointerv (GLuint, GLenum, GLvoid* *);
+  GLAPI GLboolean APIENTRY glIsProgram (GLuint);
+  GLAPI GLboolean APIENTRY glIsShader (GLuint);
+  GLAPI void APIENTRY glLinkProgram (GLuint);
+  GLAPI void APIENTRY glShaderSource (GLuint, GLsizei, const GLchar* *, const GLint *);
+  GLAPI void APIENTRY glUseProgram (GLuint);
+  GLAPI void APIENTRY glUniform1f (GLint, GLfloat);
+  GLAPI void APIENTRY glUniform2f (GLint, GLfloat, GLfloat);
+  GLAPI void APIENTRY glUniform3f (GLint, GLfloat, GLfloat, GLfloat);
+  GLAPI void APIENTRY glUniform4f (GLint, GLfloat, GLfloat, GLfloat, GLfloat);
+  GLAPI void APIENTRY glUniform1i (GLint, GLint);
+  GLAPI void APIENTRY glUniform2i (GLint, GLint, GLint);
+  GLAPI void APIENTRY glUniform3i (GLint, GLint, GLint, GLint);
+  GLAPI void APIENTRY glUniform4i (GLint, GLint, GLint, GLint, GLint);
+  GLAPI void APIENTRY glUniform1fv (GLint, GLsizei, const GLfloat *);
+  GLAPI void APIENTRY glUniform2fv (GLint, GLsizei, const GLfloat *);
+  GLAPI void APIENTRY glUniform3fv (GLint, GLsizei, const GLfloat *);
+  GLAPI void APIENTRY glUniform4fv (GLint, GLsizei, const GLfloat *);
+  GLAPI void APIENTRY glUniform1iv (GLint, GLsizei, const GLint *);
+  GLAPI void APIENTRY glUniform2iv (GLint, GLsizei, const GLint *);
+  GLAPI void APIENTRY glUniform3iv (GLint, GLsizei, const GLint *);
+  GLAPI void APIENTRY glUniform4iv (GLint, GLsizei, const GLint *);
+  GLAPI void APIENTRY glUniformMatrix2fv (GLint, GLsizei, GLboolean, const GLfloat *);
+  GLAPI void APIENTRY glUniformMatrix3fv (GLint, GLsizei, GLboolean, const GLfloat *);
+  GLAPI void APIENTRY glUniformMatrix4fv (GLint, GLsizei, GLboolean, const GLfloat *);
+  GLAPI void APIENTRY glValidateProgram (GLuint);
+  GLAPI void APIENTRY glVertexAttrib1d (GLuint, GLdouble);
+  GLAPI void APIENTRY glVertexAttrib1dv (GLuint, const GLdouble *);
+  GLAPI void APIENTRY glVertexAttrib1f (GLuint, GLfloat);
+  GLAPI void APIENTRY glVertexAttrib1fv (GLuint, const GLfloat *);
+  GLAPI void APIENTRY glVertexAttrib1s (GLuint, GLshort);
+  GLAPI void APIENTRY glVertexAttrib1sv (GLuint, const GLshort *);
+  GLAPI void APIENTRY glVertexAttrib2d (GLuint, GLdouble, GLdouble);
+  GLAPI void APIENTRY glVertexAttrib2dv (GLuint, const GLdouble *);
+  GLAPI void APIENTRY glVertexAttrib2f (GLuint, GLfloat, GLfloat);
+  GLAPI void APIENTRY glVertexAttrib2fv (GLuint, const GLfloat *);
+  GLAPI void APIENTRY glVertexAttrib2s (GLuint, GLshort, GLshort);
+  GLAPI void APIENTRY glVertexAttrib2sv (GLuint, const GLshort *);
+  GLAPI void APIENTRY glVertexAttrib3d (GLuint, GLdouble, GLdouble, GLdouble);
+  GLAPI void APIENTRY glVertexAttrib3dv (GLuint, const GLdouble *);
+  GLAPI void APIENTRY glVertexAttrib3f (GLuint, GLfloat, GLfloat, GLfloat);
+  GLAPI void APIENTRY glVertexAttrib3fv (GLuint, const GLfloat *);
+  GLAPI void APIENTRY glVertexAttrib3s (GLuint, GLshort, GLshort, GLshort);
+  GLAPI void APIENTRY glVertexAttrib3sv (GLuint, const GLshort *);
+  GLAPI void APIENTRY glVertexAttrib4Nbv (GLuint, const GLbyte *);
+  GLAPI void APIENTRY glVertexAttrib4Niv (GLuint, const GLint *);
+  GLAPI void APIENTRY glVertexAttrib4Nsv (GLuint, const GLshort *);
+  GLAPI void APIENTRY glVertexAttrib4Nub (GLuint, GLubyte, GLubyte, GLubyte, GLubyte);
+  GLAPI void APIENTRY glVertexAttrib4Nubv (GLuint, const GLubyte *);
+  GLAPI void APIENTRY glVertexAttrib4Nuiv (GLuint, const GLuint *);
+  GLAPI void APIENTRY glVertexAttrib4Nusv (GLuint, const GLushort *);
+  GLAPI void APIENTRY glVertexAttrib4bv (GLuint, const GLbyte *);
+  GLAPI void APIENTRY glVertexAttrib4d (GLuint, GLdouble, GLdouble, GLdouble, GLdouble);
+  GLAPI void APIENTRY glVertexAttrib4dv (GLuint, const GLdouble *);
+  GLAPI void APIENTRY glVertexAttrib4f (GLuint, GLfloat, GLfloat, GLfloat, GLfloat);
+  GLAPI void APIENTRY glVertexAttrib4fv (GLuint, const GLfloat *);
+  GLAPI void APIENTRY glVertexAttrib4iv (GLuint, const GLint *);
+  GLAPI void APIENTRY glVertexAttrib4s (GLuint, GLshort, GLshort, GLshort, GLshort);
+  GLAPI void APIENTRY glVertexAttrib4sv (GLuint, const GLshort *);
+  GLAPI void APIENTRY glVertexAttrib4ubv (GLuint, const GLubyte *);
+  GLAPI void APIENTRY glVertexAttrib4uiv (GLuint, const GLuint *);
+  GLAPI void APIENTRY glVertexAttrib4usv (GLuint, const GLushort *);
+  GLAPI void APIENTRY glVertexAttribPointer (GLuint, GLint, GLenum, GLboolean, GLsizei, const GLvoid *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEPROC) (GLenum modeRGB, GLenum modeAlpha);
+  typedef void (APIENTRYP PFNGLDRAWBUFFERSPROC) (GLsizei n, const GLenum *bufs);
+  typedef void (APIENTRYP PFNGLSTENCILOPSEPARATEPROC) (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass);
+  typedef void (APIENTRYP PFNGLSTENCILFUNCSEPARATEPROC) (GLenum frontfunc, GLenum backfunc, GLint ref, GLuint mask);
+  typedef void (APIENTRYP PFNGLSTENCILMASKSEPARATEPROC) (GLenum face, GLuint mask);
+  typedef void (APIENTRYP PFNGLATTACHSHADERPROC) (GLuint program, GLuint shader);
+  typedef void (APIENTRYP PFNGLBINDATTRIBLOCATIONPROC) (GLuint program, GLuint index, const GLchar *name);
+  typedef void (APIENTRYP PFNGLCOMPILESHADERPROC) (GLuint shader);
+  typedef GLuint (APIENTRYP PFNGLCREATEPROGRAMPROC) (void);
+  typedef GLuint (APIENTRYP PFNGLCREATESHADERPROC) (GLenum type);
+  typedef void (APIENTRYP PFNGLDELETEPROGRAMPROC) (GLuint program);
+  typedef void (APIENTRYP PFNGLDELETESHADERPROC) (GLuint shader);
+  typedef void (APIENTRYP PFNGLDETACHSHADERPROC) (GLuint program, GLuint shader);
+  typedef void (APIENTRYP PFNGLDISABLEVERTEXATTRIBARRAYPROC) (GLuint index);
+  typedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYPROC) (GLuint index);
+  typedef void (APIENTRYP PFNGLGETACTIVEATTRIBPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name);
+  typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name);
+  typedef void (APIENTRYP PFNGLGETATTACHEDSHADERSPROC) (GLuint program, GLsizei maxCount, GLsizei *count, GLuint *obj);
+  typedef GLint (APIENTRYP PFNGLGETATTRIBLOCATIONPROC) (GLuint program, const GLchar *name);
+  typedef void (APIENTRYP PFNGLGETPROGRAMIVPROC) (GLuint program, GLenum pname, GLint *params);
+  typedef void (APIENTRYP PFNGLGETPROGRAMINFOLOGPROC) (GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
+  typedef void (APIENTRYP PFNGLGETSHADERIVPROC) (GLuint shader, GLenum pname, GLint *params);
+  typedef void (APIENTRYP PFNGLGETSHADERINFOLOGPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
+  typedef void (APIENTRYP PFNGLGETSHADERSOURCEPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *source);
+  typedef GLint (APIENTRYP PFNGLGETUNIFORMLOCATIONPROC) (GLuint program, const GLchar *name);
+  typedef void (APIENTRYP PFNGLGETUNIFORMFVPROC) (GLuint program, GLint location, GLfloat *params);
+  typedef void (APIENTRYP PFNGLGETUNIFORMIVPROC) (GLuint program, GLint location, GLint *params);
+  typedef void (APIENTRYP PFNGLGETVERTEXATTRIBDVPROC) (GLuint index, GLenum pname, GLdouble *params);
+  typedef void (APIENTRYP PFNGLGETVERTEXATTRIBFVPROC) (GLuint index, GLenum pname, GLfloat *params);
+  typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVPROC) (GLuint index, GLenum pname, GLint *params);
+  typedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVPROC) (GLuint index, GLenum pname, GLvoid* *pointer);
+  typedef GLboolean (APIENTRYP PFNGLISPROGRAMPROC) (GLuint program);
+  typedef GLboolean (APIENTRYP PFNGLISSHADERPROC) (GLuint shader);
+  typedef void (APIENTRYP PFNGLLINKPROGRAMPROC) (GLuint program);
+  typedef void (APIENTRYP PFNGLSHADERSOURCEPROC) (GLuint shader, GLsizei count, const GLchar* *string, const GLint *length);
+  typedef void (APIENTRYP PFNGLUSEPROGRAMPROC) (GLuint program);
+  typedef void (APIENTRYP PFNGLUNIFORM1FPROC) (GLint location, GLfloat v0);
+  typedef void (APIENTRYP PFNGLUNIFORM2FPROC) (GLint location, GLfloat v0, GLfloat v1);
+  typedef void (APIENTRYP PFNGLUNIFORM3FPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2);
+  typedef void (APIENTRYP PFNGLUNIFORM4FPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);
+  typedef void (APIENTRYP PFNGLUNIFORM1IPROC) (GLint location, GLint v0);
+  typedef void (APIENTRYP PFNGLUNIFORM2IPROC) (GLint location, GLint v0, GLint v1);
+  typedef void (APIENTRYP PFNGLUNIFORM3IPROC) (GLint location, GLint v0, GLint v1, GLint v2);
+  typedef void (APIENTRYP PFNGLUNIFORM4IPROC) (GLint location, GLint v0, GLint v1, GLint v2, GLint v3);
+  typedef void (APIENTRYP PFNGLUNIFORM1FVPROC) (GLint location, GLsizei count, const GLfloat *value);
+  typedef void (APIENTRYP PFNGLUNIFORM2FVPROC) (GLint location, GLsizei count, const GLfloat *value);
+  typedef void (APIENTRYP PFNGLUNIFORM3FVPROC) (GLint location, GLsizei count, const GLfloat *value);
+  typedef void (APIENTRYP PFNGLUNIFORM4FVPROC) (GLint location, GLsizei count, const GLfloat *value);
+  typedef void (APIENTRYP PFNGLUNIFORM1IVPROC) (GLint location, GLsizei count, const GLint *value);
+  typedef void (APIENTRYP PFNGLUNIFORM2IVPROC) (GLint location, GLsizei count, const GLint *value);
+  typedef void (APIENTRYP PFNGLUNIFORM3IVPROC) (GLint location, GLsizei count, const GLint *value);
+  typedef void (APIENTRYP PFNGLUNIFORM4IVPROC) (GLint location, GLsizei count, const GLint *value);
+  typedef void (APIENTRYP PFNGLUNIFORMMATRIX2FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+  typedef void (APIENTRYP PFNGLUNIFORMMATRIX3FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+  typedef void (APIENTRYP PFNGLUNIFORMMATRIX4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+  typedef void (APIENTRYP PFNGLVALIDATEPROGRAMPROC) (GLuint program);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB1DPROC) (GLuint index, GLdouble x);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB1DVPROC) (GLuint index, const GLdouble *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB1FPROC) (GLuint index, GLfloat x);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB1FVPROC) (GLuint index, const GLfloat *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB1SPROC) (GLuint index, GLshort x);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB1SVPROC) (GLuint index, const GLshort *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB2DPROC) (GLuint index, GLdouble x, GLdouble y);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB2DVPROC) (GLuint index, const GLdouble *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB2FPROC) (GLuint index, GLfloat x, GLfloat y);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB2FVPROC) (GLuint index, const GLfloat *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB2SPROC) (GLuint index, GLshort x, GLshort y);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB2SVPROC) (GLuint index, const GLshort *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB3DPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB3DVPROC) (GLuint index, const GLdouble *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB3FPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB3FVPROC) (GLuint index, const GLfloat *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB3SPROC) (GLuint index, GLshort x, GLshort y, GLshort z);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB3SVPROC) (GLuint index, const GLshort *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB4NBVPROC) (GLuint index, const GLbyte *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB4NIVPROC) (GLuint index, const GLint *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB4NSVPROC) (GLuint index, const GLshort *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBPROC) (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBVPROC) (GLuint index, const GLubyte *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUIVPROC) (GLuint index, const GLuint *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUSVPROC) (GLuint index, const GLushort *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB4BVPROC) (GLuint index, const GLbyte *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB4DPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB4DVPROC) (GLuint index, const GLdouble *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB4FPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB4FVPROC) (GLuint index, const GLfloat *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB4IVPROC) (GLuint index, const GLint *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB4SPROC) (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB4SVPROC) (GLuint index, const GLshort *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBVPROC) (GLuint index, const GLubyte *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB4UIVPROC) (GLuint index, const GLuint *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB4USVPROC) (GLuint index, const GLushort *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer);
+#endif
+
+#ifndef GL_ARB_multitexture
+#define GL_ARB_multitexture 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glActiveTextureARB (GLenum);
+  GLAPI void APIENTRY glClientActiveTextureARB (GLenum);
+  GLAPI void APIENTRY glMultiTexCoord1dARB (GLenum, GLdouble);
+  GLAPI void APIENTRY glMultiTexCoord1dvARB (GLenum, const GLdouble *);
+  GLAPI void APIENTRY glMultiTexCoord1fARB (GLenum, GLfloat);
+  GLAPI void APIENTRY glMultiTexCoord1fvARB (GLenum, const GLfloat *);
+  GLAPI void APIENTRY glMultiTexCoord1iARB (GLenum, GLint);
+  GLAPI void APIENTRY glMultiTexCoord1ivARB (GLenum, const GLint *);
+  GLAPI void APIENTRY glMultiTexCoord1sARB (GLenum, GLshort);
+  GLAPI void APIENTRY glMultiTexCoord1svARB (GLenum, const GLshort *);
+  GLAPI void APIENTRY glMultiTexCoord2dARB (GLenum, GLdouble, GLdouble);
+  GLAPI void APIENTRY glMultiTexCoord2dvARB (GLenum, const GLdouble *);
+  GLAPI void APIENTRY glMultiTexCoord2fARB (GLenum, GLfloat, GLfloat);
+  GLAPI void APIENTRY glMultiTexCoord2fvARB (GLenum, const GLfloat *);
+  GLAPI void APIENTRY glMultiTexCoord2iARB (GLenum, GLint, GLint);
+  GLAPI void APIENTRY glMultiTexCoord2ivARB (GLenum, const GLint *);
+  GLAPI void APIENTRY glMultiTexCoord2sARB (GLenum, GLshort, GLshort);
+  GLAPI void APIENTRY glMultiTexCoord2svARB (GLenum, const GLshort *);
+  GLAPI void APIENTRY glMultiTexCoord3dARB (GLenum, GLdouble, GLdouble, GLdouble);
+  GLAPI void APIENTRY glMultiTexCoord3dvARB (GLenum, const GLdouble *);
+  GLAPI void APIENTRY glMultiTexCoord3fARB (GLenum, GLfloat, GLfloat, GLfloat);
+  GLAPI void APIENTRY glMultiTexCoord3fvARB (GLenum, const GLfloat *);
+  GLAPI void APIENTRY glMultiTexCoord3iARB (GLenum, GLint, GLint, GLint);
+  GLAPI void APIENTRY glMultiTexCoord3ivARB (GLenum, const GLint *);
+  GLAPI void APIENTRY glMultiTexCoord3sARB (GLenum, GLshort, GLshort, GLshort);
+  GLAPI void APIENTRY glMultiTexCoord3svARB (GLenum, const GLshort *);
+  GLAPI void APIENTRY glMultiTexCoord4dARB (GLenum, GLdouble, GLdouble, GLdouble, GLdouble);
+  GLAPI void APIENTRY glMultiTexCoord4dvARB (GLenum, const GLdouble *);
+  GLAPI void APIENTRY glMultiTexCoord4fARB (GLenum, GLfloat, GLfloat, GLfloat, GLfloat);
+  GLAPI void APIENTRY glMultiTexCoord4fvARB (GLenum, const GLfloat *);
+  GLAPI void APIENTRY glMultiTexCoord4iARB (GLenum, GLint, GLint, GLint, GLint);
+  GLAPI void APIENTRY glMultiTexCoord4ivARB (GLenum, const GLint *);
+  GLAPI void APIENTRY glMultiTexCoord4sARB (GLenum, GLshort, GLshort, GLshort, GLshort);
+  GLAPI void APIENTRY glMultiTexCoord4svARB (GLenum, const GLshort *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLACTIVETEXTUREARBPROC) (GLenum texture);
+  typedef void (APIENTRYP PFNGLCLIENTACTIVETEXTUREARBPROC) (GLenum texture);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD1DARBPROC) (GLenum target, GLdouble s);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD1DVARBPROC) (GLenum target, const GLdouble *v);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD1FARBPROC) (GLenum target, GLfloat s);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD1FVARBPROC) (GLenum target, const GLfloat *v);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD1IARBPROC) (GLenum target, GLint s);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD1IVARBPROC) (GLenum target, const GLint *v);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD1SARBPROC) (GLenum target, GLshort s);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD1SVARBPROC) (GLenum target, const GLshort *v);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD2DARBPROC) (GLenum target, GLdouble s, GLdouble t);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD2DVARBPROC) (GLenum target, const GLdouble *v);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD2FARBPROC) (GLenum target, GLfloat s, GLfloat t);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD2FVARBPROC) (GLenum target, const GLfloat *v);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD2IARBPROC) (GLenum target, GLint s, GLint t);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD2IVARBPROC) (GLenum target, const GLint *v);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD2SARBPROC) (GLenum target, GLshort s, GLshort t);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD2SVARBPROC) (GLenum target, const GLshort *v);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD3DARBPROC) (GLenum target, GLdouble s, GLdouble t, GLdouble r);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD3DVARBPROC) (GLenum target, const GLdouble *v);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD3FARBPROC) (GLenum target, GLfloat s, GLfloat t, GLfloat r);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD3FVARBPROC) (GLenum target, const GLfloat *v);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD3IARBPROC) (GLenum target, GLint s, GLint t, GLint r);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD3IVARBPROC) (GLenum target, const GLint *v);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD3SARBPROC) (GLenum target, GLshort s, GLshort t, GLshort r);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD3SVARBPROC) (GLenum target, const GLshort *v);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD4DARBPROC) (GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD4DVARBPROC) (GLenum target, const GLdouble *v);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD4FARBPROC) (GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD4FVARBPROC) (GLenum target, const GLfloat *v);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD4IARBPROC) (GLenum target, GLint s, GLint t, GLint r, GLint q);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD4IVARBPROC) (GLenum target, const GLint *v);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD4SARBPROC) (GLenum target, GLshort s, GLshort t, GLshort r, GLshort q);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD4SVARBPROC) (GLenum target, const GLshort *v);
+#endif
+
+#ifndef GL_ARB_transpose_matrix
+#define GL_ARB_transpose_matrix 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glLoadTransposeMatrixfARB (const GLfloat *);
+  GLAPI void APIENTRY glLoadTransposeMatrixdARB (const GLdouble *);
+  GLAPI void APIENTRY glMultTransposeMatrixfARB (const GLfloat *);
+  GLAPI void APIENTRY glMultTransposeMatrixdARB (const GLdouble *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXFARBPROC) (const GLfloat *m);
+  typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXDARBPROC) (const GLdouble *m);
+  typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXFARBPROC) (const GLfloat *m);
+  typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXDARBPROC) (const GLdouble *m);
+#endif
+
+#ifndef GL_ARB_multisample
+#define GL_ARB_multisample 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glSampleCoverageARB (GLclampf, GLboolean);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLSAMPLECOVERAGEARBPROC) (GLclampf value, GLboolean invert);
+#endif
+
+#ifndef GL_ARB_texture_env_add
+#define GL_ARB_texture_env_add 1
+#endif
+
+#ifndef GL_ARB_texture_cube_map
+#define GL_ARB_texture_cube_map 1
+#endif
+
+#ifndef GL_ARB_texture_compression
+#define GL_ARB_texture_compression 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glCompressedTexImage3DARB (GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLsizei, const GLvoid *);
+  GLAPI void APIENTRY glCompressedTexImage2DARB (GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLsizei, const GLvoid *);
+  GLAPI void APIENTRY glCompressedTexImage1DARB (GLenum, GLint, GLenum, GLsizei, GLint, GLsizei, const GLvoid *);
+  GLAPI void APIENTRY glCompressedTexSubImage3DARB (GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid *);
+  GLAPI void APIENTRY glCompressedTexSubImage2DARB (GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid *);
+  GLAPI void APIENTRY glCompressedTexSubImage1DARB (GLenum, GLint, GLint, GLsizei, GLenum, GLsizei, const GLvoid *);
+  GLAPI void APIENTRY glGetCompressedTexImageARB (GLenum, GLint, GLvoid *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE3DARBPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *data);
+  typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE2DARBPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *data);
+  typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE1DARBPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid *data);
+  typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE3DARBPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid *data);
+  typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE2DARBPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *data);
+  typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE1DARBPROC) (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const GLvoid *data);
+  typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXIMAGEARBPROC) (GLenum target, GLint level, GLvoid *img);
+#endif
+
+#ifndef GL_ARB_texture_border_clamp
+#define GL_ARB_texture_border_clamp 1
+#endif
+
+#ifndef GL_ARB_point_parameters
+#define GL_ARB_point_parameters 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glPointParameterfARB (GLenum, GLfloat);
+  GLAPI void APIENTRY glPointParameterfvARB (GLenum, const GLfloat *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLPOINTPARAMETERFARBPROC) (GLenum pname, GLfloat param);
+  typedef void (APIENTRYP PFNGLPOINTPARAMETERFVARBPROC) (GLenum pname, const GLfloat *params);
+#endif
+
+#ifndef GL_ARB_vertex_blend
+#define GL_ARB_vertex_blend 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glWeightbvARB (GLint, const GLbyte *);
+  GLAPI void APIENTRY glWeightsvARB (GLint, const GLshort *);
+  GLAPI void APIENTRY glWeightivARB (GLint, const GLint *);
+  GLAPI void APIENTRY glWeightfvARB (GLint, const GLfloat *);
+  GLAPI void APIENTRY glWeightdvARB (GLint, const GLdouble *);
+  GLAPI void APIENTRY glWeightubvARB (GLint, const GLubyte *);
+  GLAPI void APIENTRY glWeightusvARB (GLint, const GLushort *);
+  GLAPI void APIENTRY glWeightuivARB (GLint, const GLuint *);
+  GLAPI void APIENTRY glWeightPointerARB (GLint, GLenum, GLsizei, const GLvoid *);
+  GLAPI void APIENTRY glVertexBlendARB (GLint);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLWEIGHTBVARBPROC) (GLint size, const GLbyte *weights);
+  typedef void (APIENTRYP PFNGLWEIGHTSVARBPROC) (GLint size, const GLshort *weights);
+  typedef void (APIENTRYP PFNGLWEIGHTIVARBPROC) (GLint size, const GLint *weights);
+  typedef void (APIENTRYP PFNGLWEIGHTFVARBPROC) (GLint size, const GLfloat *weights);
+  typedef void (APIENTRYP PFNGLWEIGHTDVARBPROC) (GLint size, const GLdouble *weights);
+  typedef void (APIENTRYP PFNGLWEIGHTUBVARBPROC) (GLint size, const GLubyte *weights);
+  typedef void (APIENTRYP PFNGLWEIGHTUSVARBPROC) (GLint size, const GLushort *weights);
+  typedef void (APIENTRYP PFNGLWEIGHTUIVARBPROC) (GLint size, const GLuint *weights);
+  typedef void (APIENTRYP PFNGLWEIGHTPOINTERARBPROC) (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+  typedef void (APIENTRYP PFNGLVERTEXBLENDARBPROC) (GLint count);
+#endif
+
+#ifndef GL_ARB_matrix_palette
+#define GL_ARB_matrix_palette 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glCurrentPaletteMatrixARB (GLint);
+  GLAPI void APIENTRY glMatrixIndexubvARB (GLint, const GLubyte *);
+  GLAPI void APIENTRY glMatrixIndexusvARB (GLint, const GLushort *);
+  GLAPI void APIENTRY glMatrixIndexuivARB (GLint, const GLuint *);
+  GLAPI void APIENTRY glMatrixIndexPointerARB (GLint, GLenum, GLsizei, const GLvoid *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLCURRENTPALETTEMATRIXARBPROC) (GLint index);
+  typedef void (APIENTRYP PFNGLMATRIXINDEXUBVARBPROC) (GLint size, const GLubyte *indices);
+  typedef void (APIENTRYP PFNGLMATRIXINDEXUSVARBPROC) (GLint size, const GLushort *indices);
+  typedef void (APIENTRYP PFNGLMATRIXINDEXUIVARBPROC) (GLint size, const GLuint *indices);
+  typedef void (APIENTRYP PFNGLMATRIXINDEXPOINTERARBPROC) (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+#endif
+
+#ifndef GL_ARB_texture_env_combine
+#define GL_ARB_texture_env_combine 1
+#endif
+
+#ifndef GL_ARB_texture_env_crossbar
+#define GL_ARB_texture_env_crossbar 1
+#endif
+
+#ifndef GL_ARB_texture_env_dot3
+#define GL_ARB_texture_env_dot3 1
+#endif
+
+#ifndef GL_ARB_texture_mirrored_repeat
+#define GL_ARB_texture_mirrored_repeat 1
+#endif
+
+#ifndef GL_ARB_depth_texture
+#define GL_ARB_depth_texture 1
+#endif
+
+#ifndef GL_ARB_shadow
+#define GL_ARB_shadow 1
+#endif
+
+#ifndef GL_ARB_shadow_ambient
+#define GL_ARB_shadow_ambient 1
+#endif
+
+#ifndef GL_ARB_window_pos
+#define GL_ARB_window_pos 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glWindowPos2dARB (GLdouble, GLdouble);
+  GLAPI void APIENTRY glWindowPos2dvARB (const GLdouble *);
+  GLAPI void APIENTRY glWindowPos2fARB (GLfloat, GLfloat);
+  GLAPI void APIENTRY glWindowPos2fvARB (const GLfloat *);
+  GLAPI void APIENTRY glWindowPos2iARB (GLint, GLint);
+  GLAPI void APIENTRY glWindowPos2ivARB (const GLint *);
+  GLAPI void APIENTRY glWindowPos2sARB (GLshort, GLshort);
+  GLAPI void APIENTRY glWindowPos2svARB (const GLshort *);
+  GLAPI void APIENTRY glWindowPos3dARB (GLdouble, GLdouble, GLdouble);
+  GLAPI void APIENTRY glWindowPos3dvARB (const GLdouble *);
+  GLAPI void APIENTRY glWindowPos3fARB (GLfloat, GLfloat, GLfloat);
+  GLAPI void APIENTRY glWindowPos3fvARB (const GLfloat *);
+  GLAPI void APIENTRY glWindowPos3iARB (GLint, GLint, GLint);
+  GLAPI void APIENTRY glWindowPos3ivARB (const GLint *);
+  GLAPI void APIENTRY glWindowPos3sARB (GLshort, GLshort, GLshort);
+  GLAPI void APIENTRY glWindowPos3svARB (const GLshort *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLWINDOWPOS2DARBPROC) (GLdouble x, GLdouble y);
+  typedef void (APIENTRYP PFNGLWINDOWPOS2DVARBPROC) (const GLdouble *v);
+  typedef void (APIENTRYP PFNGLWINDOWPOS2FARBPROC) (GLfloat x, GLfloat y);
+  typedef void (APIENTRYP PFNGLWINDOWPOS2FVARBPROC) (const GLfloat *v);
+  typedef void (APIENTRYP PFNGLWINDOWPOS2IARBPROC) (GLint x, GLint y);
+  typedef void (APIENTRYP PFNGLWINDOWPOS2IVARBPROC) (const GLint *v);
+  typedef void (APIENTRYP PFNGLWINDOWPOS2SARBPROC) (GLshort x, GLshort y);
+  typedef void (APIENTRYP PFNGLWINDOWPOS2SVARBPROC) (const GLshort *v);
+  typedef void (APIENTRYP PFNGLWINDOWPOS3DARBPROC) (GLdouble x, GLdouble y, GLdouble z);
+  typedef void (APIENTRYP PFNGLWINDOWPOS3DVARBPROC) (const GLdouble *v);
+  typedef void (APIENTRYP PFNGLWINDOWPOS3FARBPROC) (GLfloat x, GLfloat y, GLfloat z);
+  typedef void (APIENTRYP PFNGLWINDOWPOS3FVARBPROC) (const GLfloat *v);
+  typedef void (APIENTRYP PFNGLWINDOWPOS3IARBPROC) (GLint x, GLint y, GLint z);
+  typedef void (APIENTRYP PFNGLWINDOWPOS3IVARBPROC) (const GLint *v);
+  typedef void (APIENTRYP PFNGLWINDOWPOS3SARBPROC) (GLshort x, GLshort y, GLshort z);
+  typedef void (APIENTRYP PFNGLWINDOWPOS3SVARBPROC) (const GLshort *v);
+#endif
+
+#ifndef GL_ARB_vertex_program
+#define GL_ARB_vertex_program 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glVertexAttrib1dARB (GLuint, GLdouble);
+  GLAPI void APIENTRY glVertexAttrib1dvARB (GLuint, const GLdouble *);
+  GLAPI void APIENTRY glVertexAttrib1fARB (GLuint, GLfloat);
+  GLAPI void APIENTRY glVertexAttrib1fvARB (GLuint, const GLfloat *);
+  GLAPI void APIENTRY glVertexAttrib1sARB (GLuint, GLshort);
+  GLAPI void APIENTRY glVertexAttrib1svARB (GLuint, const GLshort *);
+  GLAPI void APIENTRY glVertexAttrib2dARB (GLuint, GLdouble, GLdouble);
+  GLAPI void APIENTRY glVertexAttrib2dvARB (GLuint, const GLdouble *);
+  GLAPI void APIENTRY glVertexAttrib2fARB (GLuint, GLfloat, GLfloat);
+  GLAPI void APIENTRY glVertexAttrib2fvARB (GLuint, const GLfloat *);
+  GLAPI void APIENTRY glVertexAttrib2sARB (GLuint, GLshort, GLshort);
+  GLAPI void APIENTRY glVertexAttrib2svARB (GLuint, const GLshort *);
+  GLAPI void APIENTRY glVertexAttrib3dARB (GLuint, GLdouble, GLdouble, GLdouble);
+  GLAPI void APIENTRY glVertexAttrib3dvARB (GLuint, const GLdouble *);
+  GLAPI void APIENTRY glVertexAttrib3fARB (GLuint, GLfloat, GLfloat, GLfloat);
+  GLAPI void APIENTRY glVertexAttrib3fvARB (GLuint, const GLfloat *);
+  GLAPI void APIENTRY glVertexAttrib3sARB (GLuint, GLshort, GLshort, GLshort);
+  GLAPI void APIENTRY glVertexAttrib3svARB (GLuint, const GLshort *);
+  GLAPI void APIENTRY glVertexAttrib4NbvARB (GLuint, const GLbyte *);
+  GLAPI void APIENTRY glVertexAttrib4NivARB (GLuint, const GLint *);
+  GLAPI void APIENTRY glVertexAttrib4NsvARB (GLuint, const GLshort *);
+  GLAPI void APIENTRY glVertexAttrib4NubARB (GLuint, GLubyte, GLubyte, GLubyte, GLubyte);
+  GLAPI void APIENTRY glVertexAttrib4NubvARB (GLuint, const GLubyte *);
+  GLAPI void APIENTRY glVertexAttrib4NuivARB (GLuint, const GLuint *);
+  GLAPI void APIENTRY glVertexAttrib4NusvARB (GLuint, const GLushort *);
+  GLAPI void APIENTRY glVertexAttrib4bvARB (GLuint, const GLbyte *);
+  GLAPI void APIENTRY glVertexAttrib4dARB (GLuint, GLdouble, GLdouble, GLdouble, GLdouble);
+  GLAPI void APIENTRY glVertexAttrib4dvARB (GLuint, const GLdouble *);
+  GLAPI void APIENTRY glVertexAttrib4fARB (GLuint, GLfloat, GLfloat, GLfloat, GLfloat);
+  GLAPI void APIENTRY glVertexAttrib4fvARB (GLuint, const GLfloat *);
+  GLAPI void APIENTRY glVertexAttrib4ivARB (GLuint, const GLint *);
+  GLAPI void APIENTRY glVertexAttrib4sARB (GLuint, GLshort, GLshort, GLshort, GLshort);
+  GLAPI void APIENTRY glVertexAttrib4svARB (GLuint, const GLshort *);
+  GLAPI void APIENTRY glVertexAttrib4ubvARB (GLuint, const GLubyte *);
+  GLAPI void APIENTRY glVertexAttrib4uivARB (GLuint, const GLuint *);
+  GLAPI void APIENTRY glVertexAttrib4usvARB (GLuint, const GLushort *);
+  GLAPI void APIENTRY glVertexAttribPointerARB (GLuint, GLint, GLenum, GLboolean, GLsizei, const GLvoid *);
+  GLAPI void APIENTRY glEnableVertexAttribArrayARB (GLuint);
+  GLAPI void APIENTRY glDisableVertexAttribArrayARB (GLuint);
+  GLAPI void APIENTRY glProgramStringARB (GLenum, GLenum, GLsizei, const GLvoid *);
+  GLAPI void APIENTRY glBindProgramARB (GLenum, GLuint);
+  GLAPI void APIENTRY glDeleteProgramsARB (GLsizei, const GLuint *);
+  GLAPI void APIENTRY glGenProgramsARB (GLsizei, GLuint *);
+  GLAPI void APIENTRY glProgramEnvParameter4dARB (GLenum, GLuint, GLdouble, GLdouble, GLdouble, GLdouble);
+  GLAPI void APIENTRY glProgramEnvParameter4dvARB (GLenum, GLuint, const GLdouble *);
+  GLAPI void APIENTRY glProgramEnvParameter4fARB (GLenum, GLuint, GLfloat, GLfloat, GLfloat, GLfloat);
+  GLAPI void APIENTRY glProgramEnvParameter4fvARB (GLenum, GLuint, const GLfloat *);
+  GLAPI void APIENTRY glProgramLocalParameter4dARB (GLenum, GLuint, GLdouble, GLdouble, GLdouble, GLdouble);
+  GLAPI void APIENTRY glProgramLocalParameter4dvARB (GLenum, GLuint, const GLdouble *);
+  GLAPI void APIENTRY glProgramLocalParameter4fARB (GLenum, GLuint, GLfloat, GLfloat, GLfloat, GLfloat);
+  GLAPI void APIENTRY glProgramLocalParameter4fvARB (GLenum, GLuint, const GLfloat *);
+  GLAPI void APIENTRY glGetProgramEnvParameterdvARB (GLenum, GLuint, GLdouble *);
+  GLAPI void APIENTRY glGetProgramEnvParameterfvARB (GLenum, GLuint, GLfloat *);
+  GLAPI void APIENTRY glGetProgramLocalParameterdvARB (GLenum, GLuint, GLdouble *);
+  GLAPI void APIENTRY glGetProgramLocalParameterfvARB (GLenum, GLuint, GLfloat *);
+  GLAPI void APIENTRY glGetProgramivARB (GLenum, GLenum, GLint *);
+  GLAPI void APIENTRY glGetProgramStringARB (GLenum, GLenum, GLvoid *);
+  GLAPI void APIENTRY glGetVertexAttribdvARB (GLuint, GLenum, GLdouble *);
+  GLAPI void APIENTRY glGetVertexAttribfvARB (GLuint, GLenum, GLfloat *);
+  GLAPI void APIENTRY glGetVertexAttribivARB (GLuint, GLenum, GLint *);
+  GLAPI void APIENTRY glGetVertexAttribPointervARB (GLuint, GLenum, GLvoid* *);
+  GLAPI GLboolean APIENTRY glIsProgramARB (GLuint);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB1DARBPROC) (GLuint index, GLdouble x);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB1DVARBPROC) (GLuint index, const GLdouble *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB1FARBPROC) (GLuint index, GLfloat x);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB1FVARBPROC) (GLuint index, const GLfloat *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB1SARBPROC) (GLuint index, GLshort x);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB1SVARBPROC) (GLuint index, const GLshort *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB2DARBPROC) (GLuint index, GLdouble x, GLdouble y);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB2DVARBPROC) (GLuint index, const GLdouble *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB2FARBPROC) (GLuint index, GLfloat x, GLfloat y);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB2FVARBPROC) (GLuint index, const GLfloat *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB2SARBPROC) (GLuint index, GLshort x, GLshort y);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB2SVARBPROC) (GLuint index, const GLshort *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB3DARBPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB3DVARBPROC) (GLuint index, const GLdouble *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB3FARBPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB3FVARBPROC) (GLuint index, const GLfloat *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB3SARBPROC) (GLuint index, GLshort x, GLshort y, GLshort z);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB3SVARBPROC) (GLuint index, const GLshort *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB4NBVARBPROC) (GLuint index, const GLbyte *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB4NIVARBPROC) (GLuint index, const GLint *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB4NSVARBPROC) (GLuint index, const GLshort *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBARBPROC) (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBVARBPROC) (GLuint index, const GLubyte *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUIVARBPROC) (GLuint index, const GLuint *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUSVARBPROC) (GLuint index, const GLushort *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB4BVARBPROC) (GLuint index, const GLbyte *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB4DARBPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB4DVARBPROC) (GLuint index, const GLdouble *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB4FARBPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB4FVARBPROC) (GLuint index, const GLfloat *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB4IVARBPROC) (GLuint index, const GLint *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB4SARBPROC) (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB4SVARBPROC) (GLuint index, const GLshort *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBVARBPROC) (GLuint index, const GLubyte *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB4UIVARBPROC) (GLuint index, const GLuint *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB4USVARBPROC) (GLuint index, const GLushort *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERARBPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer);
+  typedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYARBPROC) (GLuint index);
+  typedef void (APIENTRYP PFNGLDISABLEVERTEXATTRIBARRAYARBPROC) (GLuint index);
+  typedef void (APIENTRYP PFNGLPROGRAMSTRINGARBPROC) (GLenum target, GLenum format, GLsizei len, const GLvoid *string);
+  typedef void (APIENTRYP PFNGLBINDPROGRAMARBPROC) (GLenum target, GLuint program);
+  typedef void (APIENTRYP PFNGLDELETEPROGRAMSARBPROC) (GLsizei n, const GLuint *programs);
+  typedef void (APIENTRYP PFNGLGENPROGRAMSARBPROC) (GLsizei n, GLuint *programs);
+  typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETER4DARBPROC) (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+  typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETER4DVARBPROC) (GLenum target, GLuint index, const GLdouble *params);
+  typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETER4FARBPROC) (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+  typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETER4FVARBPROC) (GLenum target, GLuint index, const GLfloat *params);
+  typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETER4DARBPROC) (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+  typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETER4DVARBPROC) (GLenum target, GLuint index, const GLdouble *params);
+  typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETER4FARBPROC) (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+  typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETER4FVARBPROC) (GLenum target, GLuint index, const GLfloat *params);
+  typedef void (APIENTRYP PFNGLGETPROGRAMENVPARAMETERDVARBPROC) (GLenum target, GLuint index, GLdouble *params);
+  typedef void (APIENTRYP PFNGLGETPROGRAMENVPARAMETERFVARBPROC) (GLenum target, GLuint index, GLfloat *params);
+  typedef void (APIENTRYP PFNGLGETPROGRAMLOCALPARAMETERDVARBPROC) (GLenum target, GLuint index, GLdouble *params);
+  typedef void (APIENTRYP PFNGLGETPROGRAMLOCALPARAMETERFVARBPROC) (GLenum target, GLuint index, GLfloat *params);
+  typedef void (APIENTRYP PFNGLGETPROGRAMIVARBPROC) (GLenum target, GLenum pname, GLint *params);
+  typedef void (APIENTRYP PFNGLGETPROGRAMSTRINGARBPROC) (GLenum target, GLenum pname, GLvoid *string);
+  typedef void (APIENTRYP PFNGLGETVERTEXATTRIBDVARBPROC) (GLuint index, GLenum pname, GLdouble *params);
+  typedef void (APIENTRYP PFNGLGETVERTEXATTRIBFVARBPROC) (GLuint index, GLenum pname, GLfloat *params);
+  typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVARBPROC) (GLuint index, GLenum pname, GLint *params);
+  typedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVARBPROC) (GLuint index, GLenum pname, GLvoid* *pointer);
+  typedef GLboolean (APIENTRYP PFNGLISPROGRAMARBPROC) (GLuint program);
+#endif
+
+#ifndef GL_ARB_fragment_program
+#define GL_ARB_fragment_program 1
+  /* All ARB_fragment_program entry points are shared with ARB_vertex_program. */
+#endif
+
+#ifndef GL_ARB_vertex_buffer_object
+#define GL_ARB_vertex_buffer_object 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glBindBufferARB (GLenum, GLuint);
+  GLAPI void APIENTRY glDeleteBuffersARB (GLsizei, const GLuint *);
+  GLAPI void APIENTRY glGenBuffersARB (GLsizei, GLuint *);
+  GLAPI GLboolean APIENTRY glIsBufferARB (GLuint);
+  GLAPI void APIENTRY glBufferDataARB (GLenum, GLsizeiptrARB, const GLvoid *, GLenum);
+  GLAPI void APIENTRY glBufferSubDataARB (GLenum, GLintptrARB, GLsizeiptrARB, const GLvoid *);
+  GLAPI void APIENTRY glGetBufferSubDataARB (GLenum, GLintptrARB, GLsizeiptrARB, GLvoid *);
+  GLAPI GLvoid* APIENTRY glMapBufferARB (GLenum, GLenum);
+  GLAPI GLboolean APIENTRY glUnmapBufferARB (GLenum);
+  GLAPI void APIENTRY glGetBufferParameterivARB (GLenum, GLenum, GLint *);
+  GLAPI void APIENTRY glGetBufferPointervARB (GLenum, GLenum, GLvoid* *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLBINDBUFFERARBPROC) (GLenum target, GLuint buffer);
+  typedef void (APIENTRYP PFNGLDELETEBUFFERSARBPROC) (GLsizei n, const GLuint *buffers);
+  typedef void (APIENTRYP PFNGLGENBUFFERSARBPROC) (GLsizei n, GLuint *buffers);
+  typedef GLboolean (APIENTRYP PFNGLISBUFFERARBPROC) (GLuint buffer);
+  typedef void (APIENTRYP PFNGLBUFFERDATAARBPROC) (GLenum target, GLsizeiptrARB size, const GLvoid *data, GLenum usage);
+  typedef void (APIENTRYP PFNGLBUFFERSUBDATAARBPROC) (GLenum target, GLintptrARB offset, GLsizeiptrARB size, const GLvoid *data);
+  typedef void (APIENTRYP PFNGLGETBUFFERSUBDATAARBPROC) (GLenum target, GLintptrARB offset, GLsizeiptrARB size, GLvoid *data);
+  typedef GLvoid* (APIENTRYP PFNGLMAPBUFFERARBPROC) (GLenum target, GLenum access);
+  typedef GLboolean (APIENTRYP PFNGLUNMAPBUFFERARBPROC) (GLenum target);
+  typedef void (APIENTRYP PFNGLGETBUFFERPARAMETERIVARBPROC) (GLenum target, GLenum pname, GLint *params);
+  typedef void (APIENTRYP PFNGLGETBUFFERPOINTERVARBPROC) (GLenum target, GLenum pname, GLvoid* *params);
+#endif
+
+#ifndef GL_ARB_occlusion_query
+#define GL_ARB_occlusion_query 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glGenQueriesARB (GLsizei, GLuint *);
+  GLAPI void APIENTRY glDeleteQueriesARB (GLsizei, const GLuint *);
+  GLAPI GLboolean APIENTRY glIsQueryARB (GLuint);
+  GLAPI void APIENTRY glBeginQueryARB (GLenum, GLuint);
+  GLAPI void APIENTRY glEndQueryARB (GLenum);
+  GLAPI void APIENTRY glGetQueryivARB (GLenum, GLenum, GLint *);
+  GLAPI void APIENTRY glGetQueryObjectivARB (GLuint, GLenum, GLint *);
+  GLAPI void APIENTRY glGetQueryObjectuivARB (GLuint, GLenum, GLuint *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLGENQUERIESARBPROC) (GLsizei n, GLuint *ids);
+  typedef void (APIENTRYP PFNGLDELETEQUERIESARBPROC) (GLsizei n, const GLuint *ids);
+  typedef GLboolean (APIENTRYP PFNGLISQUERYARBPROC) (GLuint id);
+  typedef void (APIENTRYP PFNGLBEGINQUERYARBPROC) (GLenum target, GLuint id);
+  typedef void (APIENTRYP PFNGLENDQUERYARBPROC) (GLenum target);
+  typedef void (APIENTRYP PFNGLGETQUERYIVARBPROC) (GLenum target, GLenum pname, GLint *params);
+  typedef void (APIENTRYP PFNGLGETQUERYOBJECTIVARBPROC) (GLuint id, GLenum pname, GLint *params);
+  typedef void (APIENTRYP PFNGLGETQUERYOBJECTUIVARBPROC) (GLuint id, GLenum pname, GLuint *params);
+#endif
+
+#ifndef GL_ARB_shader_objects
+#define GL_ARB_shader_objects 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glDeleteObjectARB (GLhandleARB);
+  GLAPI GLhandleARB APIENTRY glGetHandleARB (GLenum);
+  GLAPI void APIENTRY glDetachObjectARB (GLhandleARB, GLhandleARB);
+  GLAPI GLhandleARB APIENTRY glCreateShaderObjectARB (GLenum);
+  GLAPI void APIENTRY glShaderSourceARB (GLhandleARB, GLsizei, const GLcharARB* *, const GLint *);
+  GLAPI void APIENTRY glCompileShaderARB (GLhandleARB);
+  GLAPI GLhandleARB APIENTRY glCreateProgramObjectARB (void);
+  GLAPI void APIENTRY glAttachObjectARB (GLhandleARB, GLhandleARB);
+  GLAPI void APIENTRY glLinkProgramARB (GLhandleARB);
+  GLAPI void APIENTRY glUseProgramObjectARB (GLhandleARB);
+  GLAPI void APIENTRY glValidateProgramARB (GLhandleARB);
+  GLAPI void APIENTRY glUniform1fARB (GLint, GLfloat);
+  GLAPI void APIENTRY glUniform2fARB (GLint, GLfloat, GLfloat);
+  GLAPI void APIENTRY glUniform3fARB (GLint, GLfloat, GLfloat, GLfloat);
+  GLAPI void APIENTRY glUniform4fARB (GLint, GLfloat, GLfloat, GLfloat, GLfloat);
+  GLAPI void APIENTRY glUniform1iARB (GLint, GLint);
+  GLAPI void APIENTRY glUniform2iARB (GLint, GLint, GLint);
+  GLAPI void APIENTRY glUniform3iARB (GLint, GLint, GLint, GLint);
+  GLAPI void APIENTRY glUniform4iARB (GLint, GLint, GLint, GLint, GLint);
+  GLAPI void APIENTRY glUniform1fvARB (GLint, GLsizei, const GLfloat *);
+  GLAPI void APIENTRY glUniform2fvARB (GLint, GLsizei, const GLfloat *);
+  GLAPI void APIENTRY glUniform3fvARB (GLint, GLsizei, const GLfloat *);
+  GLAPI void APIENTRY glUniform4fvARB (GLint, GLsizei, const GLfloat *);
+  GLAPI void APIENTRY glUniform1ivARB (GLint, GLsizei, const GLint *);
+  GLAPI void APIENTRY glUniform2ivARB (GLint, GLsizei, const GLint *);
+  GLAPI void APIENTRY glUniform3ivARB (GLint, GLsizei, const GLint *);
+  GLAPI void APIENTRY glUniform4ivARB (GLint, GLsizei, const GLint *);
+  GLAPI void APIENTRY glUniformMatrix2fvARB (GLint, GLsizei, GLboolean, const GLfloat *);
+  GLAPI void APIENTRY glUniformMatrix3fvARB (GLint, GLsizei, GLboolean, const GLfloat *);
+  GLAPI void APIENTRY glUniformMatrix4fvARB (GLint, GLsizei, GLboolean, const GLfloat *);
+  GLAPI void APIENTRY glGetObjectParameterfvARB (GLhandleARB, GLenum, GLfloat *);
+  GLAPI void APIENTRY glGetObjectParameterivARB (GLhandleARB, GLenum, GLint *);
+  GLAPI void APIENTRY glGetInfoLogARB (GLhandleARB, GLsizei, GLsizei *, GLcharARB *);
+  GLAPI void APIENTRY glGetAttachedObjectsARB (GLhandleARB, GLsizei, GLsizei *, GLhandleARB *);
+  GLAPI GLint APIENTRY glGetUniformLocationARB (GLhandleARB, const GLcharARB *);
+  GLAPI void APIENTRY glGetActiveUniformARB (GLhandleARB, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLcharARB *);
+  GLAPI void APIENTRY glGetUniformfvARB (GLhandleARB, GLint, GLfloat *);
+  GLAPI void APIENTRY glGetUniformivARB (GLhandleARB, GLint, GLint *);
+  GLAPI void APIENTRY glGetShaderSourceARB (GLhandleARB, GLsizei, GLsizei *, GLcharARB *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLDELETEOBJECTARBPROC) (GLhandleARB obj);
+  typedef GLhandleARB (APIENTRYP PFNGLGETHANDLEARBPROC) (GLenum pname);
+  typedef void (APIENTRYP PFNGLDETACHOBJECTARBPROC) (GLhandleARB containerObj, GLhandleARB attachedObj);
+  typedef GLhandleARB (APIENTRYP PFNGLCREATESHADEROBJECTARBPROC) (GLenum shaderType);
+  typedef void (APIENTRYP PFNGLSHADERSOURCEARBPROC) (GLhandleARB shaderObj, GLsizei count, const GLcharARB* *string, const GLint *length);
+  typedef void (APIENTRYP PFNGLCOMPILESHADERARBPROC) (GLhandleARB shaderObj);
+  typedef GLhandleARB (APIENTRYP PFNGLCREATEPROGRAMOBJECTARBPROC) (void);
+  typedef void (APIENTRYP PFNGLATTACHOBJECTARBPROC) (GLhandleARB containerObj, GLhandleARB obj);
+  typedef void (APIENTRYP PFNGLLINKPROGRAMARBPROC) (GLhandleARB programObj);
+  typedef void (APIENTRYP PFNGLUSEPROGRAMOBJECTARBPROC) (GLhandleARB programObj);
+  typedef void (APIENTRYP PFNGLVALIDATEPROGRAMARBPROC) (GLhandleARB programObj);
+  typedef void (APIENTRYP PFNGLUNIFORM1FARBPROC) (GLint location, GLfloat v0);
+  typedef void (APIENTRYP PFNGLUNIFORM2FARBPROC) (GLint location, GLfloat v0, GLfloat v1);
+  typedef void (APIENTRYP PFNGLUNIFORM3FARBPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2);
+  typedef void (APIENTRYP PFNGLUNIFORM4FARBPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);
+  typedef void (APIENTRYP PFNGLUNIFORM1IARBPROC) (GLint location, GLint v0);
+  typedef void (APIENTRYP PFNGLUNIFORM2IARBPROC) (GLint location, GLint v0, GLint v1);
+  typedef void (APIENTRYP PFNGLUNIFORM3IARBPROC) (GLint location, GLint v0, GLint v1, GLint v2);
+  typedef void (APIENTRYP PFNGLUNIFORM4IARBPROC) (GLint location, GLint v0, GLint v1, GLint v2, GLint v3);
+  typedef void (APIENTRYP PFNGLUNIFORM1FVARBPROC) (GLint location, GLsizei count, const GLfloat *value);
+  typedef void (APIENTRYP PFNGLUNIFORM2FVARBPROC) (GLint location, GLsizei count, const GLfloat *value);
+  typedef void (APIENTRYP PFNGLUNIFORM3FVARBPROC) (GLint location, GLsizei count, const GLfloat *value);
+  typedef void (APIENTRYP PFNGLUNIFORM4FVARBPROC) (GLint location, GLsizei count, const GLfloat *value);
+  typedef void (APIENTRYP PFNGLUNIFORM1IVARBPROC) (GLint location, GLsizei count, const GLint *value);
+  typedef void (APIENTRYP PFNGLUNIFORM2IVARBPROC) (GLint location, GLsizei count, const GLint *value);
+  typedef void (APIENTRYP PFNGLUNIFORM3IVARBPROC) (GLint location, GLsizei count, const GLint *value);
+  typedef void (APIENTRYP PFNGLUNIFORM4IVARBPROC) (GLint location, GLsizei count, const GLint *value);
+  typedef void (APIENTRYP PFNGLUNIFORMMATRIX2FVARBPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+  typedef void (APIENTRYP PFNGLUNIFORMMATRIX3FVARBPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+  typedef void (APIENTRYP PFNGLUNIFORMMATRIX4FVARBPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+  typedef void (APIENTRYP PFNGLGETOBJECTPARAMETERFVARBPROC) (GLhandleARB obj, GLenum pname, GLfloat *params);
+  typedef void (APIENTRYP PFNGLGETOBJECTPARAMETERIVARBPROC) (GLhandleARB obj, GLenum pname, GLint *params);
+  typedef void (APIENTRYP PFNGLGETINFOLOGARBPROC) (GLhandleARB obj, GLsizei maxLength, GLsizei *length, GLcharARB *infoLog);
+  typedef void (APIENTRYP PFNGLGETATTACHEDOBJECTSARBPROC) (GLhandleARB containerObj, GLsizei maxCount, GLsizei *count, GLhandleARB *obj);
+  typedef GLint (APIENTRYP PFNGLGETUNIFORMLOCATIONARBPROC) (GLhandleARB programObj, const GLcharARB *name);
+  typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMARBPROC) (GLhandleARB programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name);
+  typedef void (APIENTRYP PFNGLGETUNIFORMFVARBPROC) (GLhandleARB programObj, GLint location, GLfloat *params);
+  typedef void (APIENTRYP PFNGLGETUNIFORMIVARBPROC) (GLhandleARB programObj, GLint location, GLint *params);
+  typedef void (APIENTRYP PFNGLGETSHADERSOURCEARBPROC) (GLhandleARB obj, GLsizei maxLength, GLsizei *length, GLcharARB *source);
+#endif
+
+#ifndef GL_ARB_vertex_shader
+#define GL_ARB_vertex_shader 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glBindAttribLocationARB (GLhandleARB, GLuint, const GLcharARB *);
+  GLAPI void APIENTRY glGetActiveAttribARB (GLhandleARB, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLcharARB *);
+  GLAPI GLint APIENTRY glGetAttribLocationARB (GLhandleARB, const GLcharARB *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLBINDATTRIBLOCATIONARBPROC) (GLhandleARB programObj, GLuint index, const GLcharARB *name);
+  typedef void (APIENTRYP PFNGLGETACTIVEATTRIBARBPROC) (GLhandleARB programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name);
+  typedef GLint (APIENTRYP PFNGLGETATTRIBLOCATIONARBPROC) (GLhandleARB programObj, const GLcharARB *name);
+#endif
+
+#ifndef GL_ARB_fragment_shader
+#define GL_ARB_fragment_shader 1
+#endif
+
+#ifndef GL_ARB_shading_language_100
+#define GL_ARB_shading_language_100 1
+#endif
+
+#ifndef GL_ARB_texture_non_power_of_two
+#define GL_ARB_texture_non_power_of_two 1
+#endif
+
+#ifndef GL_ARB_point_sprite
+#define GL_ARB_point_sprite 1
+#endif
+
+#ifndef GL_ARB_fragment_program_shadow
+#define GL_ARB_fragment_program_shadow 1
+#endif
+
+#ifndef GL_ARB_draw_buffers
+#define GL_ARB_draw_buffers 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glDrawBuffersARB (GLsizei, const GLenum *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLDRAWBUFFERSARBPROC) (GLsizei n, const GLenum *bufs);
+#endif
+
+#ifndef GL_ARB_texture_rectangle
+#define GL_ARB_texture_rectangle 1
+#endif
+
+#ifndef GL_ARB_color_buffer_float
+#define GL_ARB_color_buffer_float 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glClampColorARB (GLenum, GLenum);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLCLAMPCOLORARBPROC) (GLenum target, GLenum clamp);
+#endif
+
+#ifndef GL_ARB_half_float_pixel
+#define GL_ARB_half_float_pixel 1
+#endif
+
+#ifndef GL_ARB_texture_float
+#define GL_ARB_texture_float 1
+#endif
+
+#ifndef GL_ARB_pixel_buffer_object
+#define GL_ARB_pixel_buffer_object 1
+#endif
+
+#ifndef GL_EXT_abgr
+#define GL_EXT_abgr 1
+#endif
+
+#ifndef GL_EXT_blend_color
+#define GL_EXT_blend_color 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glBlendColorEXT (GLclampf, GLclampf, GLclampf, GLclampf);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLBLENDCOLOREXTPROC) (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);
+#endif
+
+#ifndef GL_EXT_polygon_offset
+#define GL_EXT_polygon_offset 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glPolygonOffsetEXT (GLfloat, GLfloat);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLPOLYGONOFFSETEXTPROC) (GLfloat factor, GLfloat bias);
+#endif
+
+#ifndef GL_EXT_texture
+#define GL_EXT_texture 1
+#endif
+
+#ifndef GL_EXT_texture3D
+#define GL_EXT_texture3D 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glTexImage3DEXT (GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *);
+  GLAPI void APIENTRY glTexSubImage3DEXT (GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLTEXIMAGE3DEXTPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+  typedef void (APIENTRYP PFNGLTEXSUBIMAGE3DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid *pixels);
+#endif
+
+#ifndef GL_SGIS_texture_filter4
+#define GL_SGIS_texture_filter4 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glGetTexFilterFuncSGIS (GLenum, GLenum, GLfloat *);
+  GLAPI void APIENTRY glTexFilterFuncSGIS (GLenum, GLenum, GLsizei, const GLfloat *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLGETTEXFILTERFUNCSGISPROC) (GLenum target, GLenum filter, GLfloat *weights);
+  typedef void (APIENTRYP PFNGLTEXFILTERFUNCSGISPROC) (GLenum target, GLenum filter, GLsizei n, const GLfloat *weights);
+#endif
+
+#ifndef GL_EXT_subtexture
+#define GL_EXT_subtexture 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glTexSubImage1DEXT (GLenum, GLint, GLint, GLsizei, GLenum, GLenum, const GLvoid *);
+  GLAPI void APIENTRY glTexSubImage2DEXT (GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLTEXSUBIMAGE1DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const GLvoid *pixels);
+  typedef void (APIENTRYP PFNGLTEXSUBIMAGE2DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels);
+#endif
+
+#ifndef GL_EXT_copy_texture
+#define GL_EXT_copy_texture 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glCopyTexImage1DEXT (GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLint);
+  GLAPI void APIENTRY glCopyTexImage2DEXT (GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLsizei, GLint);
+  GLAPI void APIENTRY glCopyTexSubImage1DEXT (GLenum, GLint, GLint, GLint, GLint, GLsizei);
+  GLAPI void APIENTRY glCopyTexSubImage2DEXT (GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei);
+  GLAPI void APIENTRY glCopyTexSubImage3DEXT (GLenum, GLint, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLCOPYTEXIMAGE1DEXTPROC) (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border);
+  typedef void (APIENTRYP PFNGLCOPYTEXIMAGE2DEXTPROC) (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border);
+  typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE1DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width);
+  typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE2DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+  typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE3DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+#endif
+
+#ifndef GL_EXT_histogram
+#define GL_EXT_histogram 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glGetHistogramEXT (GLenum, GLboolean, GLenum, GLenum, GLvoid *);
+  GLAPI void APIENTRY glGetHistogramParameterfvEXT (GLenum, GLenum, GLfloat *);
+  GLAPI void APIENTRY glGetHistogramParameterivEXT (GLenum, GLenum, GLint *);
+  GLAPI void APIENTRY glGetMinmaxEXT (GLenum, GLboolean, GLenum, GLenum, GLvoid *);
+  GLAPI void APIENTRY glGetMinmaxParameterfvEXT (GLenum, GLenum, GLfloat *);
+  GLAPI void APIENTRY glGetMinmaxParameterivEXT (GLenum, GLenum, GLint *);
+  GLAPI void APIENTRY glHistogramEXT (GLenum, GLsizei, GLenum, GLboolean);
+  GLAPI void APIENTRY glMinmaxEXT (GLenum, GLenum, GLboolean);
+  GLAPI void APIENTRY glResetHistogramEXT (GLenum);
+  GLAPI void APIENTRY glResetMinmaxEXT (GLenum);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLGETHISTOGRAMEXTPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLvoid *values);
+  typedef void (APIENTRYP PFNGLGETHISTOGRAMPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params);
+  typedef void (APIENTRYP PFNGLGETHISTOGRAMPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params);
+  typedef void (APIENTRYP PFNGLGETMINMAXEXTPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLvoid *values);
+  typedef void (APIENTRYP PFNGLGETMINMAXPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params);
+  typedef void (APIENTRYP PFNGLGETMINMAXPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params);
+  typedef void (APIENTRYP PFNGLHISTOGRAMEXTPROC) (GLenum target, GLsizei width, GLenum internalformat, GLboolean sink);
+  typedef void (APIENTRYP PFNGLMINMAXEXTPROC) (GLenum target, GLenum internalformat, GLboolean sink);
+  typedef void (APIENTRYP PFNGLRESETHISTOGRAMEXTPROC) (GLenum target);
+  typedef void (APIENTRYP PFNGLRESETMINMAXEXTPROC) (GLenum target);
+#endif
+
+#ifndef GL_EXT_convolution
+#define GL_EXT_convolution 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glConvolutionFilter1DEXT (GLenum, GLenum, GLsizei, GLenum, GLenum, const GLvoid *);
+  GLAPI void APIENTRY glConvolutionFilter2DEXT (GLenum, GLenum, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *);
+  GLAPI void APIENTRY glConvolutionParameterfEXT (GLenum, GLenum, GLfloat);
+  GLAPI void APIENTRY glConvolutionParameterfvEXT (GLenum, GLenum, const GLfloat *);
+  GLAPI void APIENTRY glConvolutionParameteriEXT (GLenum, GLenum, GLint);
+  GLAPI void APIENTRY glConvolutionParameterivEXT (GLenum, GLenum, const GLint *);
+  GLAPI void APIENTRY glCopyConvolutionFilter1DEXT (GLenum, GLenum, GLint, GLint, GLsizei);
+  GLAPI void APIENTRY glCopyConvolutionFilter2DEXT (GLenum, GLenum, GLint, GLint, GLsizei, GLsizei);
+  GLAPI void APIENTRY glGetConvolutionFilterEXT (GLenum, GLenum, GLenum, GLvoid *);
+  GLAPI void APIENTRY glGetConvolutionParameterfvEXT (GLenum, GLenum, GLfloat *);
+  GLAPI void APIENTRY glGetConvolutionParameterivEXT (GLenum, GLenum, GLint *);
+  GLAPI void APIENTRY glGetSeparableFilterEXT (GLenum, GLenum, GLenum, GLvoid *, GLvoid *, GLvoid *);
+  GLAPI void APIENTRY glSeparableFilter2DEXT (GLenum, GLenum, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *, const GLvoid *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLCONVOLUTIONFILTER1DEXTPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *image);
+  typedef void (APIENTRYP PFNGLCONVOLUTIONFILTER2DEXTPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *image);
+  typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERFEXTPROC) (GLenum target, GLenum pname, GLfloat params);
+  typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERFVEXTPROC) (GLenum target, GLenum pname, const GLfloat *params);
+  typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERIEXTPROC) (GLenum target, GLenum pname, GLint params);
+  typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERIVEXTPROC) (GLenum target, GLenum pname, const GLint *params);
+  typedef void (APIENTRYP PFNGLCOPYCONVOLUTIONFILTER1DEXTPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width);
+  typedef void (APIENTRYP PFNGLCOPYCONVOLUTIONFILTER2DEXTPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height);
+  typedef void (APIENTRYP PFNGLGETCONVOLUTIONFILTEREXTPROC) (GLenum target, GLenum format, GLenum type, GLvoid *image);
+  typedef void (APIENTRYP PFNGLGETCONVOLUTIONPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params);
+  typedef void (APIENTRYP PFNGLGETCONVOLUTIONPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params);
+  typedef void (APIENTRYP PFNGLGETSEPARABLEFILTEREXTPROC) (GLenum target, GLenum format, GLenum type, GLvoid *row, GLvoid *column, GLvoid *span);
+  typedef void (APIENTRYP PFNGLSEPARABLEFILTER2DEXTPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *row, const GLvoid *column);
+#endif
+
+#ifndef GL_EXT_color_matrix
+#define GL_EXT_color_matrix 1
+#endif
+
+#ifndef GL_SGI_color_table
+#define GL_SGI_color_table 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glColorTableSGI (GLenum, GLenum, GLsizei, GLenum, GLenum, const GLvoid *);
+  GLAPI void APIENTRY glColorTableParameterfvSGI (GLenum, GLenum, const GLfloat *);
+  GLAPI void APIENTRY glColorTableParameterivSGI (GLenum, GLenum, const GLint *);
+  GLAPI void APIENTRY glCopyColorTableSGI (GLenum, GLenum, GLint, GLint, GLsizei);
+  GLAPI void APIENTRY glGetColorTableSGI (GLenum, GLenum, GLenum, GLvoid *);
+  GLAPI void APIENTRY glGetColorTableParameterfvSGI (GLenum, GLenum, GLfloat *);
+  GLAPI void APIENTRY glGetColorTableParameterivSGI (GLenum, GLenum, GLint *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLCOLORTABLESGIPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *table);
+  typedef void (APIENTRYP PFNGLCOLORTABLEPARAMETERFVSGIPROC) (GLenum target, GLenum pname, const GLfloat *params);
+  typedef void (APIENTRYP PFNGLCOLORTABLEPARAMETERIVSGIPROC) (GLenum target, GLenum pname, const GLint *params);
+  typedef void (APIENTRYP PFNGLCOPYCOLORTABLESGIPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width);
+  typedef void (APIENTRYP PFNGLGETCOLORTABLESGIPROC) (GLenum target, GLenum format, GLenum type, GLvoid *table);
+  typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERFVSGIPROC) (GLenum target, GLenum pname, GLfloat *params);
+  typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERIVSGIPROC) (GLenum target, GLenum pname, GLint *params);
+#endif
+
+#ifndef GL_SGIX_pixel_texture
+#define GL_SGIX_pixel_texture 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glPixelTexGenSGIX (GLenum);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLPIXELTEXGENSGIXPROC) (GLenum mode);
+#endif
+
+#ifndef GL_SGIS_pixel_texture
+#define GL_SGIS_pixel_texture 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glPixelTexGenParameteriSGIS (GLenum, GLint);
+  GLAPI void APIENTRY glPixelTexGenParameterivSGIS (GLenum, const GLint *);
+  GLAPI void APIENTRY glPixelTexGenParameterfSGIS (GLenum, GLfloat);
+  GLAPI void APIENTRY glPixelTexGenParameterfvSGIS (GLenum, const GLfloat *);
+  GLAPI void APIENTRY glGetPixelTexGenParameterivSGIS (GLenum, GLint *);
+  GLAPI void APIENTRY glGetPixelTexGenParameterfvSGIS (GLenum, GLfloat *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLPIXELTEXGENPARAMETERISGISPROC) (GLenum pname, GLint param);
+  typedef void (APIENTRYP PFNGLPIXELTEXGENPARAMETERIVSGISPROC) (GLenum pname, const GLint *params);
+  typedef void (APIENTRYP PFNGLPIXELTEXGENPARAMETERFSGISPROC) (GLenum pname, GLfloat param);
+  typedef void (APIENTRYP PFNGLPIXELTEXGENPARAMETERFVSGISPROC) (GLenum pname, const GLfloat *params);
+  typedef void (APIENTRYP PFNGLGETPIXELTEXGENPARAMETERIVSGISPROC) (GLenum pname, GLint *params);
+  typedef void (APIENTRYP PFNGLGETPIXELTEXGENPARAMETERFVSGISPROC) (GLenum pname, GLfloat *params);
+#endif
+
+#ifndef GL_SGIS_texture4D
+#define GL_SGIS_texture4D 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glTexImage4DSGIS (GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *);
+  GLAPI void APIENTRY glTexSubImage4DSGIS (GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLTEXIMAGE4DSGISPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLsizei size4d, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+  typedef void (APIENTRYP PFNGLTEXSUBIMAGE4DSGISPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint woffset, GLsizei width, GLsizei height, GLsizei depth, GLsizei size4d, GLenum format, GLenum type, const GLvoid *pixels);
+#endif
+
+#ifndef GL_SGI_texture_color_table
+#define GL_SGI_texture_color_table 1
+#endif
+
+#ifndef GL_EXT_cmyka
+#define GL_EXT_cmyka 1
+#endif
+
+#ifndef GL_EXT_texture_object
+#define GL_EXT_texture_object 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI GLboolean APIENTRY glAreTexturesResidentEXT (GLsizei, const GLuint *, GLboolean *);
+  GLAPI void APIENTRY glBindTextureEXT (GLenum, GLuint);
+  GLAPI void APIENTRY glDeleteTexturesEXT (GLsizei, const GLuint *);
+  GLAPI void APIENTRY glGenTexturesEXT (GLsizei, GLuint *);
+  GLAPI GLboolean APIENTRY glIsTextureEXT (GLuint);
+  GLAPI void APIENTRY glPrioritizeTexturesEXT (GLsizei, const GLuint *, const GLclampf *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef GLboolean (APIENTRYP PFNGLARETEXTURESRESIDENTEXTPROC) (GLsizei n, const GLuint *textures, GLboolean *residences);
+  typedef void (APIENTRYP PFNGLBINDTEXTUREEXTPROC) (GLenum target, GLuint texture);
+  typedef void (APIENTRYP PFNGLDELETETEXTURESEXTPROC) (GLsizei n, const GLuint *textures);
+  typedef void (APIENTRYP PFNGLGENTEXTURESEXTPROC) (GLsizei n, GLuint *textures);
+  typedef GLboolean (APIENTRYP PFNGLISTEXTUREEXTPROC) (GLuint texture);
+  typedef void (APIENTRYP PFNGLPRIORITIZETEXTURESEXTPROC) (GLsizei n, const GLuint *textures, const GLclampf *priorities);
+#endif
+
+#ifndef GL_SGIS_detail_texture
+#define GL_SGIS_detail_texture 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glDetailTexFuncSGIS (GLenum, GLsizei, const GLfloat *);
+  GLAPI void APIENTRY glGetDetailTexFuncSGIS (GLenum, GLfloat *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLDETAILTEXFUNCSGISPROC) (GLenum target, GLsizei n, const GLfloat *points);
+  typedef void (APIENTRYP PFNGLGETDETAILTEXFUNCSGISPROC) (GLenum target, GLfloat *points);
+#endif
+
+#ifndef GL_SGIS_sharpen_texture
+#define GL_SGIS_sharpen_texture 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glSharpenTexFuncSGIS (GLenum, GLsizei, const GLfloat *);
+  GLAPI void APIENTRY glGetSharpenTexFuncSGIS (GLenum, GLfloat *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLSHARPENTEXFUNCSGISPROC) (GLenum target, GLsizei n, const GLfloat *points);
+  typedef void (APIENTRYP PFNGLGETSHARPENTEXFUNCSGISPROC) (GLenum target, GLfloat *points);
+#endif
+
+#ifndef GL_EXT_packed_pixels
+#define GL_EXT_packed_pixels 1
+#endif
+
+#ifndef GL_SGIS_texture_lod
+#define GL_SGIS_texture_lod 1
+#endif
+
+#ifndef GL_SGIS_multisample
+#define GL_SGIS_multisample 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glSampleMaskSGIS (GLclampf, GLboolean);
+  GLAPI void APIENTRY glSamplePatternSGIS (GLenum);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLSAMPLEMASKSGISPROC) (GLclampf value, GLboolean invert);
+  typedef void (APIENTRYP PFNGLSAMPLEPATTERNSGISPROC) (GLenum pattern);
+#endif
+
+#ifndef GL_EXT_rescale_normal
+#define GL_EXT_rescale_normal 1
+#endif
+
+#ifndef GL_EXT_vertex_array
+#define GL_EXT_vertex_array 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glArrayElementEXT (GLint);
+  GLAPI void APIENTRY glColorPointerEXT (GLint, GLenum, GLsizei, GLsizei, const GLvoid *);
+  GLAPI void APIENTRY glDrawArraysEXT (GLenum, GLint, GLsizei);
+  GLAPI void APIENTRY glEdgeFlagPointerEXT (GLsizei, GLsizei, const GLboolean *);
+  GLAPI void APIENTRY glGetPointervEXT (GLenum, GLvoid* *);
+  GLAPI void APIENTRY glIndexPointerEXT (GLenum, GLsizei, GLsizei, const GLvoid *);
+  GLAPI void APIENTRY glNormalPointerEXT (GLenum, GLsizei, GLsizei, const GLvoid *);
+  GLAPI void APIENTRY glTexCoordPointerEXT (GLint, GLenum, GLsizei, GLsizei, const GLvoid *);
+  GLAPI void APIENTRY glVertexPointerEXT (GLint, GLenum, GLsizei, GLsizei, const GLvoid *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLARRAYELEMENTEXTPROC) (GLint i);
+  typedef void (APIENTRYP PFNGLCOLORPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer);
+  typedef void (APIENTRYP PFNGLDRAWARRAYSEXTPROC) (GLenum mode, GLint first, GLsizei count);
+  typedef void (APIENTRYP PFNGLEDGEFLAGPOINTEREXTPROC) (GLsizei stride, GLsizei count, const GLboolean *pointer);
+  typedef void (APIENTRYP PFNGLGETPOINTERVEXTPROC) (GLenum pname, GLvoid* *params);
+  typedef void (APIENTRYP PFNGLINDEXPOINTEREXTPROC) (GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer);
+  typedef void (APIENTRYP PFNGLNORMALPOINTEREXTPROC) (GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer);
+  typedef void (APIENTRYP PFNGLTEXCOORDPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer);
+  typedef void (APIENTRYP PFNGLVERTEXPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer);
+#endif
+
+#ifndef GL_EXT_misc_attribute
+#define GL_EXT_misc_attribute 1
+#endif
+
+#ifndef GL_SGIS_generate_mipmap
+#define GL_SGIS_generate_mipmap 1
+#endif
+
+#ifndef GL_SGIX_clipmap
+#define GL_SGIX_clipmap 1
+#endif
+
+#ifndef GL_SGIX_shadow
+#define GL_SGIX_shadow 1
+#endif
+
+#ifndef GL_SGIS_texture_edge_clamp
+#define GL_SGIS_texture_edge_clamp 1
+#endif
+
+#ifndef GL_SGIS_texture_border_clamp
+#define GL_SGIS_texture_border_clamp 1
+#endif
+
+#ifndef GL_EXT_blend_minmax
+#define GL_EXT_blend_minmax 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glBlendEquationEXT (GLenum);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLBLENDEQUATIONEXTPROC) (GLenum mode);
+#endif
+
+#ifndef GL_EXT_blend_subtract
+#define GL_EXT_blend_subtract 1
+#endif
+
+#ifndef GL_EXT_blend_logic_op
+#define GL_EXT_blend_logic_op 1
+#endif
+
+#ifndef GL_SGIX_interlace
+#define GL_SGIX_interlace 1
+#endif
+
+#ifndef GL_SGIX_pixel_tiles
+#define GL_SGIX_pixel_tiles 1
+#endif
+
+#ifndef GL_SGIX_texture_select
+#define GL_SGIX_texture_select 1
+#endif
+
+#ifndef GL_SGIX_sprite
+#define GL_SGIX_sprite 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glSpriteParameterfSGIX (GLenum, GLfloat);
+  GLAPI void APIENTRY glSpriteParameterfvSGIX (GLenum, const GLfloat *);
+  GLAPI void APIENTRY glSpriteParameteriSGIX (GLenum, GLint);
+  GLAPI void APIENTRY glSpriteParameterivSGIX (GLenum, const GLint *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLSPRITEPARAMETERFSGIXPROC) (GLenum pname, GLfloat param);
+  typedef void (APIENTRYP PFNGLSPRITEPARAMETERFVSGIXPROC) (GLenum pname, const GLfloat *params);
+  typedef void (APIENTRYP PFNGLSPRITEPARAMETERISGIXPROC) (GLenum pname, GLint param);
+  typedef void (APIENTRYP PFNGLSPRITEPARAMETERIVSGIXPROC) (GLenum pname, const GLint *params);
+#endif
+
+#ifndef GL_SGIX_texture_multi_buffer
+#define GL_SGIX_texture_multi_buffer 1
+#endif
+
+#ifndef GL_EXT_point_parameters
+#define GL_EXT_point_parameters 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glPointParameterfEXT (GLenum, GLfloat);
+  GLAPI void APIENTRY glPointParameterfvEXT (GLenum, const GLfloat *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLPOINTPARAMETERFEXTPROC) (GLenum pname, GLfloat param);
+  typedef void (APIENTRYP PFNGLPOINTPARAMETERFVEXTPROC) (GLenum pname, const GLfloat *params);
+#endif
+
+#ifndef GL_SGIS_point_parameters
+#define GL_SGIS_point_parameters 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glPointParameterfSGIS (GLenum, GLfloat);
+  GLAPI void APIENTRY glPointParameterfvSGIS (GLenum, const GLfloat *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLPOINTPARAMETERFSGISPROC) (GLenum pname, GLfloat param);
+  typedef void (APIENTRYP PFNGLPOINTPARAMETERFVSGISPROC) (GLenum pname, const GLfloat *params);
+#endif
+
+#ifndef GL_SGIX_instruments
+#define GL_SGIX_instruments 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI GLint APIENTRY glGetInstrumentsSGIX (void);
+  GLAPI void APIENTRY glInstrumentsBufferSGIX (GLsizei, GLint *);
+  GLAPI GLint APIENTRY glPollInstrumentsSGIX (GLint *);
+  GLAPI void APIENTRY glReadInstrumentsSGIX (GLint);
+  GLAPI void APIENTRY glStartInstrumentsSGIX (void);
+  GLAPI void APIENTRY glStopInstrumentsSGIX (GLint);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef GLint (APIENTRYP PFNGLGETINSTRUMENTSSGIXPROC) (void);
+  typedef void (APIENTRYP PFNGLINSTRUMENTSBUFFERSGIXPROC) (GLsizei size, GLint *buffer);
+  typedef GLint (APIENTRYP PFNGLPOLLINSTRUMENTSSGIXPROC) (GLint *marker_p);
+  typedef void (APIENTRYP PFNGLREADINSTRUMENTSSGIXPROC) (GLint marker);
+  typedef void (APIENTRYP PFNGLSTARTINSTRUMENTSSGIXPROC) (void);
+  typedef void (APIENTRYP PFNGLSTOPINSTRUMENTSSGIXPROC) (GLint marker);
+#endif
+
+#ifndef GL_SGIX_texture_scale_bias
+#define GL_SGIX_texture_scale_bias 1
+#endif
+
+#ifndef GL_SGIX_framezoom
+#define GL_SGIX_framezoom 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glFrameZoomSGIX (GLint);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLFRAMEZOOMSGIXPROC) (GLint factor);
+#endif
+
+#ifndef GL_SGIX_tag_sample_buffer
+#define GL_SGIX_tag_sample_buffer 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glTagSampleBufferSGIX (void);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLTAGSAMPLEBUFFERSGIXPROC) (void);
+#endif
+
+#ifndef GL_SGIX_polynomial_ffd
+#define GL_SGIX_polynomial_ffd 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glDeformationMap3dSGIX (GLenum, GLdouble, GLdouble, GLint, GLint, GLdouble, GLdouble, GLint, GLint, GLdouble, GLdouble, GLint, GLint, const GLdouble *);
+  GLAPI void APIENTRY glDeformationMap3fSGIX (GLenum, GLfloat, GLfloat, GLint, GLint, GLfloat, GLfloat, GLint, GLint, GLfloat, GLfloat, GLint, GLint, const GLfloat *);
+  GLAPI void APIENTRY glDeformSGIX (GLbitfield);
+  GLAPI void APIENTRY glLoadIdentityDeformationMapSGIX (GLbitfield);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLDEFORMATIONMAP3DSGIXPROC) (GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, GLdouble w1, GLdouble w2, GLint wstride, GLint worder, const GLdouble *points);
+  typedef void (APIENTRYP PFNGLDEFORMATIONMAP3FSGIXPROC) (GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, GLfloat w1, GLfloat w2, GLint wstride, GLint worder, const GLfloat *points);
+  typedef void (APIENTRYP PFNGLDEFORMSGIXPROC) (GLbitfield mask);
+  typedef void (APIENTRYP PFNGLLOADIDENTITYDEFORMATIONMAPSGIXPROC) (GLbitfield mask);
+#endif
+
+#ifndef GL_SGIX_reference_plane
+#define GL_SGIX_reference_plane 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glReferencePlaneSGIX (const GLdouble *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLREFERENCEPLANESGIXPROC) (const GLdouble *equation);
+#endif
+
+#ifndef GL_SGIX_flush_raster
+#define GL_SGIX_flush_raster 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glFlushRasterSGIX (void);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLFLUSHRASTERSGIXPROC) (void);
+#endif
+
+#ifndef GL_SGIX_depth_texture
+#define GL_SGIX_depth_texture 1
+#endif
+
+#ifndef GL_SGIS_fog_function
+#define GL_SGIS_fog_function 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glFogFuncSGIS (GLsizei, const GLfloat *);
+  GLAPI void APIENTRY glGetFogFuncSGIS (GLfloat *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLFOGFUNCSGISPROC) (GLsizei n, const GLfloat *points);
+  typedef void (APIENTRYP PFNGLGETFOGFUNCSGISPROC) (GLfloat *points);
+#endif
+
+#ifndef GL_SGIX_fog_offset
+#define GL_SGIX_fog_offset 1
+#endif
+
+#ifndef GL_HP_image_transform
+#define GL_HP_image_transform 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glImageTransformParameteriHP (GLenum, GLenum, GLint);
+  GLAPI void APIENTRY glImageTransformParameterfHP (GLenum, GLenum, GLfloat);
+  GLAPI void APIENTRY glImageTransformParameterivHP (GLenum, GLenum, const GLint *);
+  GLAPI void APIENTRY glImageTransformParameterfvHP (GLenum, GLenum, const GLfloat *);
+  GLAPI void APIENTRY glGetImageTransformParameterivHP (GLenum, GLenum, GLint *);
+  GLAPI void APIENTRY glGetImageTransformParameterfvHP (GLenum, GLenum, GLfloat *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLIMAGETRANSFORMPARAMETERIHPPROC) (GLenum target, GLenum pname, GLint param);
+  typedef void (APIENTRYP PFNGLIMAGETRANSFORMPARAMETERFHPPROC) (GLenum target, GLenum pname, GLfloat param);
+  typedef void (APIENTRYP PFNGLIMAGETRANSFORMPARAMETERIVHPPROC) (GLenum target, GLenum pname, const GLint *params);
+  typedef void (APIENTRYP PFNGLIMAGETRANSFORMPARAMETERFVHPPROC) (GLenum target, GLenum pname, const GLfloat *params);
+  typedef void (APIENTRYP PFNGLGETIMAGETRANSFORMPARAMETERIVHPPROC) (GLenum target, GLenum pname, GLint *params);
+  typedef void (APIENTRYP PFNGLGETIMAGETRANSFORMPARAMETERFVHPPROC) (GLenum target, GLenum pname, GLfloat *params);
+#endif
+
+#ifndef GL_HP_convolution_border_modes
+#define GL_HP_convolution_border_modes 1
+#endif
+
+#ifndef GL_SGIX_texture_add_env
+#define GL_SGIX_texture_add_env 1
+#endif
+
+#ifndef GL_EXT_color_subtable
+#define GL_EXT_color_subtable 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glColorSubTableEXT (GLenum, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *);
+  GLAPI void APIENTRY glCopyColorSubTableEXT (GLenum, GLsizei, GLint, GLint, GLsizei);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLCOLORSUBTABLEEXTPROC) (GLenum target, GLsizei start, GLsizei count, GLenum format, GLenum type, const GLvoid *data);
+  typedef void (APIENTRYP PFNGLCOPYCOLORSUBTABLEEXTPROC) (GLenum target, GLsizei start, GLint x, GLint y, GLsizei width);
+#endif
+
+#ifndef GL_PGI_vertex_hints
+#define GL_PGI_vertex_hints 1
+#endif
+
+#ifndef GL_PGI_misc_hints
+#define GL_PGI_misc_hints 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glHintPGI (GLenum, GLint);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLHINTPGIPROC) (GLenum target, GLint mode);
+#endif
+
+#ifndef GL_EXT_paletted_texture
+#define GL_EXT_paletted_texture 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glColorTableEXT (GLenum, GLenum, GLsizei, GLenum, GLenum, const GLvoid *);
+  GLAPI void APIENTRY glGetColorTableEXT (GLenum, GLenum, GLenum, GLvoid *);
+  GLAPI void APIENTRY glGetColorTableParameterivEXT (GLenum, GLenum, GLint *);
+  GLAPI void APIENTRY glGetColorTableParameterfvEXT (GLenum, GLenum, GLfloat *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLCOLORTABLEEXTPROC) (GLenum target, GLenum internalFormat, GLsizei width, GLenum format, GLenum type, const GLvoid *table);
+  typedef void (APIENTRYP PFNGLGETCOLORTABLEEXTPROC) (GLenum target, GLenum format, GLenum type, GLvoid *data);
+  typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params);
+  typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params);
+#endif
+
+#ifndef GL_EXT_clip_volume_hint
+#define GL_EXT_clip_volume_hint 1
+#endif
+
+#ifndef GL_SGIX_list_priority
+#define GL_SGIX_list_priority 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glGetListParameterfvSGIX (GLuint, GLenum, GLfloat *);
+  GLAPI void APIENTRY glGetListParameterivSGIX (GLuint, GLenum, GLint *);
+  GLAPI void APIENTRY glListParameterfSGIX (GLuint, GLenum, GLfloat);
+  GLAPI void APIENTRY glListParameterfvSGIX (GLuint, GLenum, const GLfloat *);
+  GLAPI void APIENTRY glListParameteriSGIX (GLuint, GLenum, GLint);
+  GLAPI void APIENTRY glListParameterivSGIX (GLuint, GLenum, const GLint *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLGETLISTPARAMETERFVSGIXPROC) (GLuint list, GLenum pname, GLfloat *params);
+  typedef void (APIENTRYP PFNGLGETLISTPARAMETERIVSGIXPROC) (GLuint list, GLenum pname, GLint *params);
+  typedef void (APIENTRYP PFNGLLISTPARAMETERFSGIXPROC) (GLuint list, GLenum pname, GLfloat param);
+  typedef void (APIENTRYP PFNGLLISTPARAMETERFVSGIXPROC) (GLuint list, GLenum pname, const GLfloat *params);
+  typedef void (APIENTRYP PFNGLLISTPARAMETERISGIXPROC) (GLuint list, GLenum pname, GLint param);
+  typedef void (APIENTRYP PFNGLLISTPARAMETERIVSGIXPROC) (GLuint list, GLenum pname, const GLint *params);
+#endif
+
+#ifndef GL_SGIX_ir_instrument1
+#define GL_SGIX_ir_instrument1 1
+#endif
+
+#ifndef GL_SGIX_calligraphic_fragment
+#define GL_SGIX_calligraphic_fragment 1
+#endif
+
+#ifndef GL_SGIX_texture_lod_bias
+#define GL_SGIX_texture_lod_bias 1
+#endif
+
+#ifndef GL_SGIX_shadow_ambient
+#define GL_SGIX_shadow_ambient 1
+#endif
+
+#ifndef GL_EXT_index_texture
+#define GL_EXT_index_texture 1
+#endif
+
+#ifndef GL_EXT_index_material
+#define GL_EXT_index_material 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glIndexMaterialEXT (GLenum, GLenum);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLINDEXMATERIALEXTPROC) (GLenum face, GLenum mode);
+#endif
+
+#ifndef GL_EXT_index_func
+#define GL_EXT_index_func 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glIndexFuncEXT (GLenum, GLclampf);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLINDEXFUNCEXTPROC) (GLenum func, GLclampf ref);
+#endif
+
+#ifndef GL_EXT_index_array_formats
+#define GL_EXT_index_array_formats 1
+#endif
+
+#ifndef GL_EXT_compiled_vertex_array
+#define GL_EXT_compiled_vertex_array 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glLockArraysEXT (GLint, GLsizei);
+  GLAPI void APIENTRY glUnlockArraysEXT (void);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLLOCKARRAYSEXTPROC) (GLint first, GLsizei count);
+  typedef void (APIENTRYP PFNGLUNLOCKARRAYSEXTPROC) (void);
+#endif
+
+#ifndef GL_EXT_cull_vertex
+#define GL_EXT_cull_vertex 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glCullParameterdvEXT (GLenum, GLdouble *);
+  GLAPI void APIENTRY glCullParameterfvEXT (GLenum, GLfloat *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLCULLPARAMETERDVEXTPROC) (GLenum pname, GLdouble *params);
+  typedef void (APIENTRYP PFNGLCULLPARAMETERFVEXTPROC) (GLenum pname, GLfloat *params);
+#endif
+
+#ifndef GL_SGIX_ycrcb
+#define GL_SGIX_ycrcb 1
+#endif
+
+#ifndef GL_SGIX_fragment_lighting
+#define GL_SGIX_fragment_lighting 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glFragmentColorMaterialSGIX (GLenum, GLenum);
+  GLAPI void APIENTRY glFragmentLightfSGIX (GLenum, GLenum, GLfloat);
+  GLAPI void APIENTRY glFragmentLightfvSGIX (GLenum, GLenum, const GLfloat *);
+  GLAPI void APIENTRY glFragmentLightiSGIX (GLenum, GLenum, GLint);
+  GLAPI void APIENTRY glFragmentLightivSGIX (GLenum, GLenum, const GLint *);
+  GLAPI void APIENTRY glFragmentLightModelfSGIX (GLenum, GLfloat);
+  GLAPI void APIENTRY glFragmentLightModelfvSGIX (GLenum, const GLfloat *);
+  GLAPI void APIENTRY glFragmentLightModeliSGIX (GLenum, GLint);
+  GLAPI void APIENTRY glFragmentLightModelivSGIX (GLenum, const GLint *);
+  GLAPI void APIENTRY glFragmentMaterialfSGIX (GLenum, GLenum, GLfloat);
+  GLAPI void APIENTRY glFragmentMaterialfvSGIX (GLenum, GLenum, const GLfloat *);
+  GLAPI void APIENTRY glFragmentMaterialiSGIX (GLenum, GLenum, GLint);
+  GLAPI void APIENTRY glFragmentMaterialivSGIX (GLenum, GLenum, const GLint *);
+  GLAPI void APIENTRY glGetFragmentLightfvSGIX (GLenum, GLenum, GLfloat *);
+  GLAPI void APIENTRY glGetFragmentLightivSGIX (GLenum, GLenum, GLint *);
+  GLAPI void APIENTRY glGetFragmentMaterialfvSGIX (GLenum, GLenum, GLfloat *);
+  GLAPI void APIENTRY glGetFragmentMaterialivSGIX (GLenum, GLenum, GLint *);
+  GLAPI void APIENTRY glLightEnviSGIX (GLenum, GLint);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLFRAGMENTCOLORMATERIALSGIXPROC) (GLenum face, GLenum mode);
+  typedef void (APIENTRYP PFNGLFRAGMENTLIGHTFSGIXPROC) (GLenum light, GLenum pname, GLfloat param);
+  typedef void (APIENTRYP PFNGLFRAGMENTLIGHTFVSGIXPROC) (GLenum light, GLenum pname, const GLfloat *params);
+  typedef void (APIENTRYP PFNGLFRAGMENTLIGHTISGIXPROC) (GLenum light, GLenum pname, GLint param);
+  typedef void (APIENTRYP PFNGLFRAGMENTLIGHTIVSGIXPROC) (GLenum light, GLenum pname, const GLint *params);
+  typedef void (APIENTRYP PFNGLFRAGMENTLIGHTMODELFSGIXPROC) (GLenum pname, GLfloat param);
+  typedef void (APIENTRYP PFNGLFRAGMENTLIGHTMODELFVSGIXPROC) (GLenum pname, const GLfloat *params);
+  typedef void (APIENTRYP PFNGLFRAGMENTLIGHTMODELISGIXPROC) (GLenum pname, GLint param);
+  typedef void (APIENTRYP PFNGLFRAGMENTLIGHTMODELIVSGIXPROC) (GLenum pname, const GLint *params);
+  typedef void (APIENTRYP PFNGLFRAGMENTMATERIALFSGIXPROC) (GLenum face, GLenum pname, GLfloat param);
+  typedef void (APIENTRYP PFNGLFRAGMENTMATERIALFVSGIXPROC) (GLenum face, GLenum pname, const GLfloat *params);
+  typedef void (APIENTRYP PFNGLFRAGMENTMATERIALISGIXPROC) (GLenum face, GLenum pname, GLint param);
+  typedef void (APIENTRYP PFNGLFRAGMENTMATERIALIVSGIXPROC) (GLenum face, GLenum pname, const GLint *params);
+  typedef void (APIENTRYP PFNGLGETFRAGMENTLIGHTFVSGIXPROC) (GLenum light, GLenum pname, GLfloat *params);
+  typedef void (APIENTRYP PFNGLGETFRAGMENTLIGHTIVSGIXPROC) (GLenum light, GLenum pname, GLint *params);
+  typedef void (APIENTRYP PFNGLGETFRAGMENTMATERIALFVSGIXPROC) (GLenum face, GLenum pname, GLfloat *params);
+  typedef void (APIENTRYP PFNGLGETFRAGMENTMATERIALIVSGIXPROC) (GLenum face, GLenum pname, GLint *params);
+  typedef void (APIENTRYP PFNGLLIGHTENVISGIXPROC) (GLenum pname, GLint param);
+#endif
+
+#ifndef GL_IBM_rasterpos_clip
+#define GL_IBM_rasterpos_clip 1
+#endif
+
+#ifndef GL_HP_texture_lighting
+#define GL_HP_texture_lighting 1
+#endif
+
+#ifndef GL_EXT_draw_range_elements
+#define GL_EXT_draw_range_elements 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glDrawRangeElementsEXT (GLenum, GLuint, GLuint, GLsizei, GLenum, const GLvoid *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTSEXTPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid *indices);
+#endif
+
+#ifndef GL_WIN_phong_shading
+#define GL_WIN_phong_shading 1
+#endif
+
+#ifndef GL_WIN_specular_fog
+#define GL_WIN_specular_fog 1
+#endif
+
+#ifndef GL_EXT_light_texture
+#define GL_EXT_light_texture 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glApplyTextureEXT (GLenum);
+  GLAPI void APIENTRY glTextureLightEXT (GLenum);
+  GLAPI void APIENTRY glTextureMaterialEXT (GLenum, GLenum);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLAPPLYTEXTUREEXTPROC) (GLenum mode);
+  typedef void (APIENTRYP PFNGLTEXTURELIGHTEXTPROC) (GLenum pname);
+  typedef void (APIENTRYP PFNGLTEXTUREMATERIALEXTPROC) (GLenum face, GLenum mode);
+#endif
+
+#ifndef GL_SGIX_blend_alpha_minmax
+#define GL_SGIX_blend_alpha_minmax 1
+#endif
+
+#ifndef GL_EXT_bgra
+#define GL_EXT_bgra 1
+#endif
+
+#ifndef GL_SGIX_async
+#define GL_SGIX_async 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glAsyncMarkerSGIX (GLuint);
+  GLAPI GLint APIENTRY glFinishAsyncSGIX (GLuint *);
+  GLAPI GLint APIENTRY glPollAsyncSGIX (GLuint *);
+  GLAPI GLuint APIENTRY glGenAsyncMarkersSGIX (GLsizei);
+  GLAPI void APIENTRY glDeleteAsyncMarkersSGIX (GLuint, GLsizei);
+  GLAPI GLboolean APIENTRY glIsAsyncMarkerSGIX (GLuint);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLASYNCMARKERSGIXPROC) (GLuint marker);
+  typedef GLint (APIENTRYP PFNGLFINISHASYNCSGIXPROC) (GLuint *markerp);
+  typedef GLint (APIENTRYP PFNGLPOLLASYNCSGIXPROC) (GLuint *markerp);
+  typedef GLuint (APIENTRYP PFNGLGENASYNCMARKERSSGIXPROC) (GLsizei range);
+  typedef void (APIENTRYP PFNGLDELETEASYNCMARKERSSGIXPROC) (GLuint marker, GLsizei range);
+  typedef GLboolean (APIENTRYP PFNGLISASYNCMARKERSGIXPROC) (GLuint marker);
+#endif
+
+#ifndef GL_SGIX_async_pixel
+#define GL_SGIX_async_pixel 1
+#endif
+
+#ifndef GL_SGIX_async_histogram
+#define GL_SGIX_async_histogram 1
+#endif
+
+#ifndef GL_INTEL_parallel_arrays
+#define GL_INTEL_parallel_arrays 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glVertexPointervINTEL (GLint, GLenum, const GLvoid* *);
+  GLAPI void APIENTRY glNormalPointervINTEL (GLenum, const GLvoid* *);
+  GLAPI void APIENTRY glColorPointervINTEL (GLint, GLenum, const GLvoid* *);
+  GLAPI void APIENTRY glTexCoordPointervINTEL (GLint, GLenum, const GLvoid* *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLVERTEXPOINTERVINTELPROC) (GLint size, GLenum type, const GLvoid* *pointer);
+  typedef void (APIENTRYP PFNGLNORMALPOINTERVINTELPROC) (GLenum type, const GLvoid* *pointer);
+  typedef void (APIENTRYP PFNGLCOLORPOINTERVINTELPROC) (GLint size, GLenum type, const GLvoid* *pointer);
+  typedef void (APIENTRYP PFNGLTEXCOORDPOINTERVINTELPROC) (GLint size, GLenum type, const GLvoid* *pointer);
+#endif
+
+#ifndef GL_HP_occlusion_test
+#define GL_HP_occlusion_test 1
+#endif
+
+#ifndef GL_EXT_pixel_transform
+#define GL_EXT_pixel_transform 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glPixelTransformParameteriEXT (GLenum, GLenum, GLint);
+  GLAPI void APIENTRY glPixelTransformParameterfEXT (GLenum, GLenum, GLfloat);
+  GLAPI void APIENTRY glPixelTransformParameterivEXT (GLenum, GLenum, const GLint *);
+  GLAPI void APIENTRY glPixelTransformParameterfvEXT (GLenum, GLenum, const GLfloat *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLPIXELTRANSFORMPARAMETERIEXTPROC) (GLenum target, GLenum pname, GLint param);
+  typedef void (APIENTRYP PFNGLPIXELTRANSFORMPARAMETERFEXTPROC) (GLenum target, GLenum pname, GLfloat param);
+  typedef void (APIENTRYP PFNGLPIXELTRANSFORMPARAMETERIVEXTPROC) (GLenum target, GLenum pname, const GLint *params);
+  typedef void (APIENTRYP PFNGLPIXELTRANSFORMPARAMETERFVEXTPROC) (GLenum target, GLenum pname, const GLfloat *params);
+#endif
+
+#ifndef GL_EXT_pixel_transform_color_table
+#define GL_EXT_pixel_transform_color_table 1
+#endif
+
+#ifndef GL_EXT_shared_texture_palette
+#define GL_EXT_shared_texture_palette 1
+#endif
+
+#ifndef GL_EXT_separate_specular_color
+#define GL_EXT_separate_specular_color 1
+#endif
+
+#ifndef GL_EXT_secondary_color
+#define GL_EXT_secondary_color 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glSecondaryColor3bEXT (GLbyte, GLbyte, GLbyte);
+  GLAPI void APIENTRY glSecondaryColor3bvEXT (const GLbyte *);
+  GLAPI void APIENTRY glSecondaryColor3dEXT (GLdouble, GLdouble, GLdouble);
+  GLAPI void APIENTRY glSecondaryColor3dvEXT (const GLdouble *);
+  GLAPI void APIENTRY glSecondaryColor3fEXT (GLfloat, GLfloat, GLfloat);
+  GLAPI void APIENTRY glSecondaryColor3fvEXT (const GLfloat *);
+  GLAPI void APIENTRY glSecondaryColor3iEXT (GLint, GLint, GLint);
+  GLAPI void APIENTRY glSecondaryColor3ivEXT (const GLint *);
+  GLAPI void APIENTRY glSecondaryColor3sEXT (GLshort, GLshort, GLshort);
+  GLAPI void APIENTRY glSecondaryColor3svEXT (const GLshort *);
+  GLAPI void APIENTRY glSecondaryColor3ubEXT (GLubyte, GLubyte, GLubyte);
+  GLAPI void APIENTRY glSecondaryColor3ubvEXT (const GLubyte *);
+  GLAPI void APIENTRY glSecondaryColor3uiEXT (GLuint, GLuint, GLuint);
+  GLAPI void APIENTRY glSecondaryColor3uivEXT (const GLuint *);
+  GLAPI void APIENTRY glSecondaryColor3usEXT (GLushort, GLushort, GLushort);
+  GLAPI void APIENTRY glSecondaryColor3usvEXT (const GLushort *);
+  GLAPI void APIENTRY glSecondaryColorPointerEXT (GLint, GLenum, GLsizei, const GLvoid *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BEXTPROC) (GLbyte red, GLbyte green, GLbyte blue);
+  typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BVEXTPROC) (const GLbyte *v);
+  typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DEXTPROC) (GLdouble red, GLdouble green, GLdouble blue);
+  typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DVEXTPROC) (const GLdouble *v);
+  typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FEXTPROC) (GLfloat red, GLfloat green, GLfloat blue);
+  typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FVEXTPROC) (const GLfloat *v);
+  typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IEXTPROC) (GLint red, GLint green, GLint blue);
+  typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IVEXTPROC) (const GLint *v);
+  typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SEXTPROC) (GLshort red, GLshort green, GLshort blue);
+  typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SVEXTPROC) (const GLshort *v);
+  typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBEXTPROC) (GLubyte red, GLubyte green, GLubyte blue);
+  typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBVEXTPROC) (const GLubyte *v);
+  typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIEXTPROC) (GLuint red, GLuint green, GLuint blue);
+  typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIVEXTPROC) (const GLuint *v);
+  typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USEXTPROC) (GLushort red, GLushort green, GLushort blue);
+  typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USVEXTPROC) (const GLushort *v);
+  typedef void (APIENTRYP PFNGLSECONDARYCOLORPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+#endif
+
+#ifndef GL_EXT_texture_perturb_normal
+#define GL_EXT_texture_perturb_normal 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glTextureNormalEXT (GLenum);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLTEXTURENORMALEXTPROC) (GLenum mode);
+#endif
+
+#ifndef GL_EXT_multi_draw_arrays
+#define GL_EXT_multi_draw_arrays 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glMultiDrawArraysEXT (GLenum, GLint *, GLsizei *, GLsizei);
+  GLAPI void APIENTRY glMultiDrawElementsEXT (GLenum, const GLsizei *, GLenum, const GLvoid* *, GLsizei);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSEXTPROC) (GLenum mode, GLint *first, GLsizei *count, GLsizei primcount);
+  typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSEXTPROC) (GLenum mode, const GLsizei *count, GLenum type, const GLvoid* *indices, GLsizei primcount);
+#endif
+
+#ifndef GL_EXT_fog_coord
+#define GL_EXT_fog_coord 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glFogCoordfEXT (GLfloat);
+  GLAPI void APIENTRY glFogCoordfvEXT (const GLfloat *);
+  GLAPI void APIENTRY glFogCoorddEXT (GLdouble);
+  GLAPI void APIENTRY glFogCoorddvEXT (const GLdouble *);
+  GLAPI void APIENTRY glFogCoordPointerEXT (GLenum, GLsizei, const GLvoid *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLFOGCOORDFEXTPROC) (GLfloat coord);
+  typedef void (APIENTRYP PFNGLFOGCOORDFVEXTPROC) (const GLfloat *coord);
+  typedef void (APIENTRYP PFNGLFOGCOORDDEXTPROC) (GLdouble coord);
+  typedef void (APIENTRYP PFNGLFOGCOORDDVEXTPROC) (const GLdouble *coord);
+  typedef void (APIENTRYP PFNGLFOGCOORDPOINTEREXTPROC) (GLenum type, GLsizei stride, const GLvoid *pointer);
+#endif
+
+#ifndef GL_REND_screen_coordinates
+#define GL_REND_screen_coordinates 1
+#endif
+
+#ifndef GL_EXT_coordinate_frame
+#define GL_EXT_coordinate_frame 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glTangent3bEXT (GLbyte, GLbyte, GLbyte);
+  GLAPI void APIENTRY glTangent3bvEXT (const GLbyte *);
+  GLAPI void APIENTRY glTangent3dEXT (GLdouble, GLdouble, GLdouble);
+  GLAPI void APIENTRY glTangent3dvEXT (const GLdouble *);
+  GLAPI void APIENTRY glTangent3fEXT (GLfloat, GLfloat, GLfloat);
+  GLAPI void APIENTRY glTangent3fvEXT (const GLfloat *);
+  GLAPI void APIENTRY glTangent3iEXT (GLint, GLint, GLint);
+  GLAPI void APIENTRY glTangent3ivEXT (const GLint *);
+  GLAPI void APIENTRY glTangent3sEXT (GLshort, GLshort, GLshort);
+  GLAPI void APIENTRY glTangent3svEXT (const GLshort *);
+  GLAPI void APIENTRY glBinormal3bEXT (GLbyte, GLbyte, GLbyte);
+  GLAPI void APIENTRY glBinormal3bvEXT (const GLbyte *);
+  GLAPI void APIENTRY glBinormal3dEXT (GLdouble, GLdouble, GLdouble);
+  GLAPI void APIENTRY glBinormal3dvEXT (const GLdouble *);
+  GLAPI void APIENTRY glBinormal3fEXT (GLfloat, GLfloat, GLfloat);
+  GLAPI void APIENTRY glBinormal3fvEXT (const GLfloat *);
+  GLAPI void APIENTRY glBinormal3iEXT (GLint, GLint, GLint);
+  GLAPI void APIENTRY glBinormal3ivEXT (const GLint *);
+  GLAPI void APIENTRY glBinormal3sEXT (GLshort, GLshort, GLshort);
+  GLAPI void APIENTRY glBinormal3svEXT (const GLshort *);
+  GLAPI void APIENTRY glTangentPointerEXT (GLenum, GLsizei, const GLvoid *);
+  GLAPI void APIENTRY glBinormalPointerEXT (GLenum, GLsizei, const GLvoid *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLTANGENT3BEXTPROC) (GLbyte tx, GLbyte ty, GLbyte tz);
+  typedef void (APIENTRYP PFNGLTANGENT3BVEXTPROC) (const GLbyte *v);
+  typedef void (APIENTRYP PFNGLTANGENT3DEXTPROC) (GLdouble tx, GLdouble ty, GLdouble tz);
+  typedef void (APIENTRYP PFNGLTANGENT3DVEXTPROC) (const GLdouble *v);
+  typedef void (APIENTRYP PFNGLTANGENT3FEXTPROC) (GLfloat tx, GLfloat ty, GLfloat tz);
+  typedef void (APIENTRYP PFNGLTANGENT3FVEXTPROC) (const GLfloat *v);
+  typedef void (APIENTRYP PFNGLTANGENT3IEXTPROC) (GLint tx, GLint ty, GLint tz);
+  typedef void (APIENTRYP PFNGLTANGENT3IVEXTPROC) (const GLint *v);
+  typedef void (APIENTRYP PFNGLTANGENT3SEXTPROC) (GLshort tx, GLshort ty, GLshort tz);
+  typedef void (APIENTRYP PFNGLTANGENT3SVEXTPROC) (const GLshort *v);
+  typedef void (APIENTRYP PFNGLBINORMAL3BEXTPROC) (GLbyte bx, GLbyte by, GLbyte bz);
+  typedef void (APIENTRYP PFNGLBINORMAL3BVEXTPROC) (const GLbyte *v);
+  typedef void (APIENTRYP PFNGLBINORMAL3DEXTPROC) (GLdouble bx, GLdouble by, GLdouble bz);
+  typedef void (APIENTRYP PFNGLBINORMAL3DVEXTPROC) (const GLdouble *v);
+  typedef void (APIENTRYP PFNGLBINORMAL3FEXTPROC) (GLfloat bx, GLfloat by, GLfloat bz);
+  typedef void (APIENTRYP PFNGLBINORMAL3FVEXTPROC) (const GLfloat *v);
+  typedef void (APIENTRYP PFNGLBINORMAL3IEXTPROC) (GLint bx, GLint by, GLint bz);
+  typedef void (APIENTRYP PFNGLBINORMAL3IVEXTPROC) (const GLint *v);
+  typedef void (APIENTRYP PFNGLBINORMAL3SEXTPROC) (GLshort bx, GLshort by, GLshort bz);
+  typedef void (APIENTRYP PFNGLBINORMAL3SVEXTPROC) (const GLshort *v);
+  typedef void (APIENTRYP PFNGLTANGENTPOINTEREXTPROC) (GLenum type, GLsizei stride, const GLvoid *pointer);
+  typedef void (APIENTRYP PFNGLBINORMALPOINTEREXTPROC) (GLenum type, GLsizei stride, const GLvoid *pointer);
+#endif
+
+#ifndef GL_EXT_texture_env_combine
+#define GL_EXT_texture_env_combine 1
+#endif
+
+#ifndef GL_APPLE_specular_vector
+#define GL_APPLE_specular_vector 1
+#endif
+
+#ifndef GL_APPLE_transform_hint
+#define GL_APPLE_transform_hint 1
+#endif
+
+#ifndef GL_SGIX_fog_scale
+#define GL_SGIX_fog_scale 1
+#endif
+
+#ifndef GL_SUNX_constant_data
+#define GL_SUNX_constant_data 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glFinishTextureSUNX (void);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLFINISHTEXTURESUNXPROC) (void);
+#endif
+
+#ifndef GL_SUN_global_alpha
+#define GL_SUN_global_alpha 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glGlobalAlphaFactorbSUN (GLbyte);
+  GLAPI void APIENTRY glGlobalAlphaFactorsSUN (GLshort);
+  GLAPI void APIENTRY glGlobalAlphaFactoriSUN (GLint);
+  GLAPI void APIENTRY glGlobalAlphaFactorfSUN (GLfloat);
+  GLAPI void APIENTRY glGlobalAlphaFactordSUN (GLdouble);
+  GLAPI void APIENTRY glGlobalAlphaFactorubSUN (GLubyte);
+  GLAPI void APIENTRY glGlobalAlphaFactorusSUN (GLushort);
+  GLAPI void APIENTRY glGlobalAlphaFactoruiSUN (GLuint);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORBSUNPROC) (GLbyte factor);
+  typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORSSUNPROC) (GLshort factor);
+  typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORISUNPROC) (GLint factor);
+  typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORFSUNPROC) (GLfloat factor);
+  typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORDSUNPROC) (GLdouble factor);
+  typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORUBSUNPROC) (GLubyte factor);
+  typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORUSSUNPROC) (GLushort factor);
+  typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORUISUNPROC) (GLuint factor);
+#endif
+
+#ifndef GL_SUN_triangle_list
+#define GL_SUN_triangle_list 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glReplacementCodeuiSUN (GLuint);
+  GLAPI void APIENTRY glReplacementCodeusSUN (GLushort);
+  GLAPI void APIENTRY glReplacementCodeubSUN (GLubyte);
+  GLAPI void APIENTRY glReplacementCodeuivSUN (const GLuint *);
+  GLAPI void APIENTRY glReplacementCodeusvSUN (const GLushort *);
+  GLAPI void APIENTRY glReplacementCodeubvSUN (const GLubyte *);
+  GLAPI void APIENTRY glReplacementCodePointerSUN (GLenum, GLsizei, const GLvoid* *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLREPLACEMENTCODEUISUNPROC) (GLuint code);
+  typedef void (APIENTRYP PFNGLREPLACEMENTCODEUSSUNPROC) (GLushort code);
+  typedef void (APIENTRYP PFNGLREPLACEMENTCODEUBSUNPROC) (GLubyte code);
+  typedef void (APIENTRYP PFNGLREPLACEMENTCODEUIVSUNPROC) (const GLuint *code);
+  typedef void (APIENTRYP PFNGLREPLACEMENTCODEUSVSUNPROC) (const GLushort *code);
+  typedef void (APIENTRYP PFNGLREPLACEMENTCODEUBVSUNPROC) (const GLubyte *code);
+  typedef void (APIENTRYP PFNGLREPLACEMENTCODEPOINTERSUNPROC) (GLenum type, GLsizei stride, const GLvoid* *pointer);
+#endif
+
+#ifndef GL_SUN_vertex
+#define GL_SUN_vertex 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glColor4ubVertex2fSUN (GLubyte, GLubyte, GLubyte, GLubyte, GLfloat, GLfloat);
+  GLAPI void APIENTRY glColor4ubVertex2fvSUN (const GLubyte *, const GLfloat *);
+  GLAPI void APIENTRY glColor4ubVertex3fSUN (GLubyte, GLubyte, GLubyte, GLubyte, GLfloat, GLfloat, GLfloat);
+  GLAPI void APIENTRY glColor4ubVertex3fvSUN (const GLubyte *, const GLfloat *);
+  GLAPI void APIENTRY glColor3fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
+  GLAPI void APIENTRY glColor3fVertex3fvSUN (const GLfloat *, const GLfloat *);
+  GLAPI void APIENTRY glNormal3fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
+  GLAPI void APIENTRY glNormal3fVertex3fvSUN (const GLfloat *, const GLfloat *);
+  GLAPI void APIENTRY glColor4fNormal3fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
+  GLAPI void APIENTRY glColor4fNormal3fVertex3fvSUN (const GLfloat *, const GLfloat *, const GLfloat *);
+  GLAPI void APIENTRY glTexCoord2fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
+  GLAPI void APIENTRY glTexCoord2fVertex3fvSUN (const GLfloat *, const GLfloat *);
+  GLAPI void APIENTRY glTexCoord4fVertex4fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
+  GLAPI void APIENTRY glTexCoord4fVertex4fvSUN (const GLfloat *, const GLfloat *);
+  GLAPI void APIENTRY glTexCoord2fColor4ubVertex3fSUN (GLfloat, GLfloat, GLubyte, GLubyte, GLubyte, GLubyte, GLfloat, GLfloat, GLfloat);
+  GLAPI void APIENTRY glTexCoord2fColor4ubVertex3fvSUN (const GLfloat *, const GLubyte *, const GLfloat *);
+  GLAPI void APIENTRY glTexCoord2fColor3fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
+  GLAPI void APIENTRY glTexCoord2fColor3fVertex3fvSUN (const GLfloat *, const GLfloat *, const GLfloat *);
+  GLAPI void APIENTRY glTexCoord2fNormal3fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
+  GLAPI void APIENTRY glTexCoord2fNormal3fVertex3fvSUN (const GLfloat *, const GLfloat *, const GLfloat *);
+  GLAPI void APIENTRY glTexCoord2fColor4fNormal3fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
+  GLAPI void APIENTRY glTexCoord2fColor4fNormal3fVertex3fvSUN (const GLfloat *, const GLfloat *, const GLfloat *, const GLfloat *);
+  GLAPI void APIENTRY glTexCoord4fColor4fNormal3fVertex4fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
+  GLAPI void APIENTRY glTexCoord4fColor4fNormal3fVertex4fvSUN (const GLfloat *, const GLfloat *, const GLfloat *, const GLfloat *);
+  GLAPI void APIENTRY glReplacementCodeuiVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat);
+  GLAPI void APIENTRY glReplacementCodeuiVertex3fvSUN (const GLuint *, const GLfloat *);
+  GLAPI void APIENTRY glReplacementCodeuiColor4ubVertex3fSUN (GLuint, GLubyte, GLubyte, GLubyte, GLubyte, GLfloat, GLfloat, GLfloat);
+  GLAPI void APIENTRY glReplacementCodeuiColor4ubVertex3fvSUN (const GLuint *, const GLubyte *, const GLfloat *);
+  GLAPI void APIENTRY glReplacementCodeuiColor3fVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
+  GLAPI void APIENTRY glReplacementCodeuiColor3fVertex3fvSUN (const GLuint *, const GLfloat *, const GLfloat *);
+  GLAPI void APIENTRY glReplacementCodeuiNormal3fVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
+  GLAPI void APIENTRY glReplacementCodeuiNormal3fVertex3fvSUN (const GLuint *, const GLfloat *, const GLfloat *);
+  GLAPI void APIENTRY glReplacementCodeuiColor4fNormal3fVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
+  GLAPI void APIENTRY glReplacementCodeuiColor4fNormal3fVertex3fvSUN (const GLuint *, const GLfloat *, const GLfloat *, const GLfloat *);
+  GLAPI void APIENTRY glReplacementCodeuiTexCoord2fVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
+  GLAPI void APIENTRY glReplacementCodeuiTexCoord2fVertex3fvSUN (const GLuint *, const GLfloat *, const GLfloat *);
+  GLAPI void APIENTRY glReplacementCodeuiTexCoord2fNormal3fVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
+  GLAPI void APIENTRY glReplacementCodeuiTexCoord2fNormal3fVertex3fvSUN (const GLuint *, const GLfloat *, const GLfloat *, const GLfloat *);
+  GLAPI void APIENTRY glReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
+  GLAPI void APIENTRY glReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fvSUN (const GLuint *, const GLfloat *, const GLfloat *, const GLfloat *, const GLfloat *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLCOLOR4UBVERTEX2FSUNPROC) (GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y);
+  typedef void (APIENTRYP PFNGLCOLOR4UBVERTEX2FVSUNPROC) (const GLubyte *c, const GLfloat *v);
+  typedef void (APIENTRYP PFNGLCOLOR4UBVERTEX3FSUNPROC) (GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z);
+  typedef void (APIENTRYP PFNGLCOLOR4UBVERTEX3FVSUNPROC) (const GLubyte *c, const GLfloat *v);
+  typedef void (APIENTRYP PFNGLCOLOR3FVERTEX3FSUNPROC) (GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z);
+  typedef void (APIENTRYP PFNGLCOLOR3FVERTEX3FVSUNPROC) (const GLfloat *c, const GLfloat *v);
+  typedef void (APIENTRYP PFNGLNORMAL3FVERTEX3FSUNPROC) (GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
+  typedef void (APIENTRYP PFNGLNORMAL3FVERTEX3FVSUNPROC) (const GLfloat *n, const GLfloat *v);
+  typedef void (APIENTRYP PFNGLCOLOR4FNORMAL3FVERTEX3FSUNPROC) (GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
+  typedef void (APIENTRYP PFNGLCOLOR4FNORMAL3FVERTEX3FVSUNPROC) (const GLfloat *c, const GLfloat *n, const GLfloat *v);
+  typedef void (APIENTRYP PFNGLTEXCOORD2FVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLfloat x, GLfloat y, GLfloat z);
+  typedef void (APIENTRYP PFNGLTEXCOORD2FVERTEX3FVSUNPROC) (const GLfloat *tc, const GLfloat *v);
+  typedef void (APIENTRYP PFNGLTEXCOORD4FVERTEX4FSUNPROC) (GLfloat s, GLfloat t, GLfloat p, GLfloat q, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+  typedef void (APIENTRYP PFNGLTEXCOORD4FVERTEX4FVSUNPROC) (const GLfloat *tc, const GLfloat *v);
+  typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR4UBVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z);
+  typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR4UBVERTEX3FVSUNPROC) (const GLfloat *tc, const GLubyte *c, const GLfloat *v);
+  typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR3FVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z);
+  typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR3FVERTEX3FVSUNPROC) (const GLfloat *tc, const GLfloat *c, const GLfloat *v);
+  typedef void (APIENTRYP PFNGLTEXCOORD2FNORMAL3FVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
+  typedef void (APIENTRYP PFNGLTEXCOORD2FNORMAL3FVERTEX3FVSUNPROC) (const GLfloat *tc, const GLfloat *n, const GLfloat *v);
+  typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR4FNORMAL3FVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
+  typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR4FNORMAL3FVERTEX3FVSUNPROC) (const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v);
+  typedef void (APIENTRYP PFNGLTEXCOORD4FCOLOR4FNORMAL3FVERTEX4FSUNPROC) (GLfloat s, GLfloat t, GLfloat p, GLfloat q, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+  typedef void (APIENTRYP PFNGLTEXCOORD4FCOLOR4FNORMAL3FVERTEX4FVSUNPROC) (const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v);
+  typedef void (APIENTRYP PFNGLREPLACEMENTCODEUIVERTEX3FSUNPROC) (GLuint rc, GLfloat x, GLfloat y, GLfloat z);
+  typedef void (APIENTRYP PFNGLREPLACEMENTCODEUIVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *v);
+  typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR4UBVERTEX3FSUNPROC) (GLuint rc, GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z);
+  typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR4UBVERTEX3FVSUNPROC) (const GLuint *rc, const GLubyte *c, const GLfloat *v);
+  typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR3FVERTEX3FSUNPROC) (GLuint rc, GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z);
+  typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *c, const GLfloat *v);
+  typedef void (APIENTRYP PFNGLREPLACEMENTCODEUINORMAL3FVERTEX3FSUNPROC) (GLuint rc, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
+  typedef void (APIENTRYP PFNGLREPLACEMENTCODEUINORMAL3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *n, const GLfloat *v);
+  typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR4FNORMAL3FVERTEX3FSUNPROC) (GLuint rc, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
+  typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR4FNORMAL3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *c, const GLfloat *n, const GLfloat *v);
+  typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FVERTEX3FSUNPROC) (GLuint rc, GLfloat s, GLfloat t, GLfloat x, GLfloat y, GLfloat z);
+  typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *tc, const GLfloat *v);
+  typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FNORMAL3FVERTEX3FSUNPROC) (GLuint rc, GLfloat s, GLfloat t, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
+  typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FNORMAL3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *tc, const GLfloat *n, const GLfloat *v);
+  typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FCOLOR4FNORMAL3FVERTEX3FSUNPROC) (GLuint rc, GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
+  typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FCOLOR4FNORMAL3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v);
+#endif
+
+#ifndef GL_EXT_blend_func_separate
+#define GL_EXT_blend_func_separate 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glBlendFuncSeparateEXT (GLenum, GLenum, GLenum, GLenum);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEEXTPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);
+#endif
+
+#ifndef GL_INGR_blend_func_separate
+#define GL_INGR_blend_func_separate 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glBlendFuncSeparateINGR (GLenum, GLenum, GLenum, GLenum);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEINGRPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);
+#endif
+
+#ifndef GL_INGR_color_clamp
+#define GL_INGR_color_clamp 1
+#endif
+
+#ifndef GL_INGR_interlace_read
+#define GL_INGR_interlace_read 1
+#endif
+
+#ifndef GL_EXT_stencil_wrap
+#define GL_EXT_stencil_wrap 1
+#endif
+
+#ifndef GL_EXT_422_pixels
+#define GL_EXT_422_pixels 1
+#endif
+
+#ifndef GL_NV_texgen_reflection
+#define GL_NV_texgen_reflection 1
+#endif
+
+#ifndef GL_SUN_convolution_border_modes
+#define GL_SUN_convolution_border_modes 1
+#endif
+
+#ifndef GL_EXT_texture_env_add
+#define GL_EXT_texture_env_add 1
+#endif
+
+#ifndef GL_EXT_texture_lod_bias
+#define GL_EXT_texture_lod_bias 1
+#endif
+
+#ifndef GL_EXT_texture_filter_anisotropic
+#define GL_EXT_texture_filter_anisotropic 1
+#endif
+
+#ifndef GL_EXT_vertex_weighting
+#define GL_EXT_vertex_weighting 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glVertexWeightfEXT (GLfloat);
+  GLAPI void APIENTRY glVertexWeightfvEXT (const GLfloat *);
+  GLAPI void APIENTRY glVertexWeightPointerEXT (GLsizei, GLenum, GLsizei, const GLvoid *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLVERTEXWEIGHTFEXTPROC) (GLfloat weight);
+  typedef void (APIENTRYP PFNGLVERTEXWEIGHTFVEXTPROC) (const GLfloat *weight);
+  typedef void (APIENTRYP PFNGLVERTEXWEIGHTPOINTEREXTPROC) (GLsizei size, GLenum type, GLsizei stride, const GLvoid *pointer);
+#endif
+
+#ifndef GL_NV_light_max_exponent
+#define GL_NV_light_max_exponent 1
+#endif
+
+#ifndef GL_NV_vertex_array_range
+#define GL_NV_vertex_array_range 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glFlushVertexArrayRangeNV (void);
+  GLAPI void APIENTRY glVertexArrayRangeNV (GLsizei, const GLvoid *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLFLUSHVERTEXARRAYRANGENVPROC) (void);
+  typedef void (APIENTRYP PFNGLVERTEXARRAYRANGENVPROC) (GLsizei length, const GLvoid *pointer);
+#endif
+
+#ifndef GL_NV_register_combiners
+#define GL_NV_register_combiners 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glCombinerParameterfvNV (GLenum, const GLfloat *);
+  GLAPI void APIENTRY glCombinerParameterfNV (GLenum, GLfloat);
+  GLAPI void APIENTRY glCombinerParameterivNV (GLenum, const GLint *);
+  GLAPI void APIENTRY glCombinerParameteriNV (GLenum, GLint);
+  GLAPI void APIENTRY glCombinerInputNV (GLenum, GLenum, GLenum, GLenum, GLenum, GLenum);
+  GLAPI void APIENTRY glCombinerOutputNV (GLenum, GLenum, GLenum, GLenum, GLenum, GLenum, GLenum, GLboolean, GLboolean, GLboolean);
+  GLAPI void APIENTRY glFinalCombinerInputNV (GLenum, GLenum, GLenum, GLenum);
+  GLAPI void APIENTRY glGetCombinerInputParameterfvNV (GLenum, GLenum, GLenum, GLenum, GLfloat *);
+  GLAPI void APIENTRY glGetCombinerInputParameterivNV (GLenum, GLenum, GLenum, GLenum, GLint *);
+  GLAPI void APIENTRY glGetCombinerOutputParameterfvNV (GLenum, GLenum, GLenum, GLfloat *);
+  GLAPI void APIENTRY glGetCombinerOutputParameterivNV (GLenum, GLenum, GLenum, GLint *);
+  GLAPI void APIENTRY glGetFinalCombinerInputParameterfvNV (GLenum, GLenum, GLfloat *);
+  GLAPI void APIENTRY glGetFinalCombinerInputParameterivNV (GLenum, GLenum, GLint *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLCOMBINERPARAMETERFVNVPROC) (GLenum pname, const GLfloat *params);
+  typedef void (APIENTRYP PFNGLCOMBINERPARAMETERFNVPROC) (GLenum pname, GLfloat param);
+  typedef void (APIENTRYP PFNGLCOMBINERPARAMETERIVNVPROC) (GLenum pname, const GLint *params);
+  typedef void (APIENTRYP PFNGLCOMBINERPARAMETERINVPROC) (GLenum pname, GLint param);
+  typedef void (APIENTRYP PFNGLCOMBINERINPUTNVPROC) (GLenum stage, GLenum portion, GLenum variable, GLenum input, GLenum mapping, GLenum componentUsage);
+  typedef void (APIENTRYP PFNGLCOMBINEROUTPUTNVPROC) (GLenum stage, GLenum portion, GLenum abOutput, GLenum cdOutput, GLenum sumOutput, GLenum scale, GLenum bias, GLboolean abDotProduct, GLboolean cdDotProduct, GLboolean muxSum);
+  typedef void (APIENTRYP PFNGLFINALCOMBINERINPUTNVPROC) (GLenum variable, GLenum input, GLenum mapping, GLenum componentUsage);
+  typedef void (APIENTRYP PFNGLGETCOMBINERINPUTPARAMETERFVNVPROC) (GLenum stage, GLenum portion, GLenum variable, GLenum pname, GLfloat *params);
+  typedef void (APIENTRYP PFNGLGETCOMBINERINPUTPARAMETERIVNVPROC) (GLenum stage, GLenum portion, GLenum variable, GLenum pname, GLint *params);
+  typedef void (APIENTRYP PFNGLGETCOMBINEROUTPUTPARAMETERFVNVPROC) (GLenum stage, GLenum portion, GLenum pname, GLfloat *params);
+  typedef void (APIENTRYP PFNGLGETCOMBINEROUTPUTPARAMETERIVNVPROC) (GLenum stage, GLenum portion, GLenum pname, GLint *params);
+  typedef void (APIENTRYP PFNGLGETFINALCOMBINERINPUTPARAMETERFVNVPROC) (GLenum variable, GLenum pname, GLfloat *params);
+  typedef void (APIENTRYP PFNGLGETFINALCOMBINERINPUTPARAMETERIVNVPROC) (GLenum variable, GLenum pname, GLint *params);
+#endif
+
+#ifndef GL_NV_fog_distance
+#define GL_NV_fog_distance 1
+#endif
+
+#ifndef GL_NV_texgen_emboss
+#define GL_NV_texgen_emboss 1
+#endif
+
+#ifndef GL_NV_blend_square
+#define GL_NV_blend_square 1
+#endif
+
+#ifndef GL_NV_texture_env_combine4
+#define GL_NV_texture_env_combine4 1
+#endif
+
+#ifndef GL_MESA_resize_buffers
+#define GL_MESA_resize_buffers 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glResizeBuffersMESA (void);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLRESIZEBUFFERSMESAPROC) (void);
+#endif
+
+#ifndef GL_MESA_window_pos
+#define GL_MESA_window_pos 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glWindowPos2dMESA (GLdouble, GLdouble);
+  GLAPI void APIENTRY glWindowPos2dvMESA (const GLdouble *);
+  GLAPI void APIENTRY glWindowPos2fMESA (GLfloat, GLfloat);
+  GLAPI void APIENTRY glWindowPos2fvMESA (const GLfloat *);
+  GLAPI void APIENTRY glWindowPos2iMESA (GLint, GLint);
+  GLAPI void APIENTRY glWindowPos2ivMESA (const GLint *);
+  GLAPI void APIENTRY glWindowPos2sMESA (GLshort, GLshort);
+  GLAPI void APIENTRY glWindowPos2svMESA (const GLshort *);
+  GLAPI void APIENTRY glWindowPos3dMESA (GLdouble, GLdouble, GLdouble);
+  GLAPI void APIENTRY glWindowPos3dvMESA (const GLdouble *);
+  GLAPI void APIENTRY glWindowPos3fMESA (GLfloat, GLfloat, GLfloat);
+  GLAPI void APIENTRY glWindowPos3fvMESA (const GLfloat *);
+  GLAPI void APIENTRY glWindowPos3iMESA (GLint, GLint, GLint);
+  GLAPI void APIENTRY glWindowPos3ivMESA (const GLint *);
+  GLAPI void APIENTRY glWindowPos3sMESA (GLshort, GLshort, GLshort);
+  GLAPI void APIENTRY glWindowPos3svMESA (const GLshort *);
+  GLAPI void APIENTRY glWindowPos4dMESA (GLdouble, GLdouble, GLdouble, GLdouble);
+  GLAPI void APIENTRY glWindowPos4dvMESA (const GLdouble *);
+  GLAPI void APIENTRY glWindowPos4fMESA (GLfloat, GLfloat, GLfloat, GLfloat);
+  GLAPI void APIENTRY glWindowPos4fvMESA (const GLfloat *);
+  GLAPI void APIENTRY glWindowPos4iMESA (GLint, GLint, GLint, GLint);
+  GLAPI void APIENTRY glWindowPos4ivMESA (const GLint *);
+  GLAPI void APIENTRY glWindowPos4sMESA (GLshort, GLshort, GLshort, GLshort);
+  GLAPI void APIENTRY glWindowPos4svMESA (const GLshort *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLWINDOWPOS2DMESAPROC) (GLdouble x, GLdouble y);
+  typedef void (APIENTRYP PFNGLWINDOWPOS2DVMESAPROC) (const GLdouble *v);
+  typedef void (APIENTRYP PFNGLWINDOWPOS2FMESAPROC) (GLfloat x, GLfloat y);
+  typedef void (APIENTRYP PFNGLWINDOWPOS2FVMESAPROC) (const GLfloat *v);
+  typedef void (APIENTRYP PFNGLWINDOWPOS2IMESAPROC) (GLint x, GLint y);
+  typedef void (APIENTRYP PFNGLWINDOWPOS2IVMESAPROC) (const GLint *v);
+  typedef void (APIENTRYP PFNGLWINDOWPOS2SMESAPROC) (GLshort x, GLshort y);
+  typedef void (APIENTRYP PFNGLWINDOWPOS2SVMESAPROC) (const GLshort *v);
+  typedef void (APIENTRYP PFNGLWINDOWPOS3DMESAPROC) (GLdouble x, GLdouble y, GLdouble z);
+  typedef void (APIENTRYP PFNGLWINDOWPOS3DVMESAPROC) (const GLdouble *v);
+  typedef void (APIENTRYP PFNGLWINDOWPOS3FMESAPROC) (GLfloat x, GLfloat y, GLfloat z);
+  typedef void (APIENTRYP PFNGLWINDOWPOS3FVMESAPROC) (const GLfloat *v);
+  typedef void (APIENTRYP PFNGLWINDOWPOS3IMESAPROC) (GLint x, GLint y, GLint z);
+  typedef void (APIENTRYP PFNGLWINDOWPOS3IVMESAPROC) (const GLint *v);
+  typedef void (APIENTRYP PFNGLWINDOWPOS3SMESAPROC) (GLshort x, GLshort y, GLshort z);
+  typedef void (APIENTRYP PFNGLWINDOWPOS3SVMESAPROC) (const GLshort *v);
+  typedef void (APIENTRYP PFNGLWINDOWPOS4DMESAPROC) (GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+  typedef void (APIENTRYP PFNGLWINDOWPOS4DVMESAPROC) (const GLdouble *v);
+  typedef void (APIENTRYP PFNGLWINDOWPOS4FMESAPROC) (GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+  typedef void (APIENTRYP PFNGLWINDOWPOS4FVMESAPROC) (const GLfloat *v);
+  typedef void (APIENTRYP PFNGLWINDOWPOS4IMESAPROC) (GLint x, GLint y, GLint z, GLint w);
+  typedef void (APIENTRYP PFNGLWINDOWPOS4IVMESAPROC) (const GLint *v);
+  typedef void (APIENTRYP PFNGLWINDOWPOS4SMESAPROC) (GLshort x, GLshort y, GLshort z, GLshort w);
+  typedef void (APIENTRYP PFNGLWINDOWPOS4SVMESAPROC) (const GLshort *v);
+#endif
+
+#ifndef GL_EXT_texture_compression_s3tc
+#define GL_EXT_texture_compression_s3tc 1
+#endif
+
+#ifndef GL_IBM_cull_vertex
+#define GL_IBM_cull_vertex 1
+#endif
+
+#ifndef GL_IBM_multimode_draw_arrays
+#define GL_IBM_multimode_draw_arrays 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glMultiModeDrawArraysIBM (const GLenum *, const GLint *, const GLsizei *, GLsizei, GLint);
+  GLAPI void APIENTRY glMultiModeDrawElementsIBM (const GLenum *, const GLsizei *, GLenum, const GLvoid* const *, GLsizei, GLint);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLMULTIMODEDRAWARRAYSIBMPROC) (const GLenum *mode, const GLint *first, const GLsizei *count, GLsizei primcount, GLint modestride);
+  typedef void (APIENTRYP PFNGLMULTIMODEDRAWELEMENTSIBMPROC) (const GLenum *mode, const GLsizei *count, GLenum type, const GLvoid* const *indices, GLsizei primcount, GLint modestride);
+#endif
+
+#ifndef GL_IBM_vertex_array_lists
+#define GL_IBM_vertex_array_lists 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glColorPointerListIBM (GLint, GLenum, GLint, const GLvoid* *, GLint);
+  GLAPI void APIENTRY glSecondaryColorPointerListIBM (GLint, GLenum, GLint, const GLvoid* *, GLint);
+  GLAPI void APIENTRY glEdgeFlagPointerListIBM (GLint, const GLboolean* *, GLint);
+  GLAPI void APIENTRY glFogCoordPointerListIBM (GLenum, GLint, const GLvoid* *, GLint);
+  GLAPI void APIENTRY glIndexPointerListIBM (GLenum, GLint, const GLvoid* *, GLint);
+  GLAPI void APIENTRY glNormalPointerListIBM (GLenum, GLint, const GLvoid* *, GLint);
+  GLAPI void APIENTRY glTexCoordPointerListIBM (GLint, GLenum, GLint, const GLvoid* *, GLint);
+  GLAPI void APIENTRY glVertexPointerListIBM (GLint, GLenum, GLint, const GLvoid* *, GLint);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLCOLORPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);
+  typedef void (APIENTRYP PFNGLSECONDARYCOLORPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);
+  typedef void (APIENTRYP PFNGLEDGEFLAGPOINTERLISTIBMPROC) (GLint stride, const GLboolean* *pointer, GLint ptrstride);
+  typedef void (APIENTRYP PFNGLFOGCOORDPOINTERLISTIBMPROC) (GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);
+  typedef void (APIENTRYP PFNGLINDEXPOINTERLISTIBMPROC) (GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);
+  typedef void (APIENTRYP PFNGLNORMALPOINTERLISTIBMPROC) (GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);
+  typedef void (APIENTRYP PFNGLTEXCOORDPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);
+  typedef void (APIENTRYP PFNGLVERTEXPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);
+#endif
+
+#ifndef GL_SGIX_subsample
+#define GL_SGIX_subsample 1
+#endif
+
+#ifndef GL_SGIX_ycrcba
+#define GL_SGIX_ycrcba 1
+#endif
+
+#ifndef GL_SGIX_ycrcb_subsample
+#define GL_SGIX_ycrcb_subsample 1
+#endif
+
+#ifndef GL_SGIX_depth_pass_instrument
+#define GL_SGIX_depth_pass_instrument 1
+#endif
+
+#ifndef GL_3DFX_texture_compression_FXT1
+#define GL_3DFX_texture_compression_FXT1 1
+#endif
+
+#ifndef GL_3DFX_multisample
+#define GL_3DFX_multisample 1
+#endif
+
+#ifndef GL_3DFX_tbuffer
+#define GL_3DFX_tbuffer 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glTbufferMask3DFX (GLuint);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLTBUFFERMASK3DFXPROC) (GLuint mask);
+#endif
+
+#ifndef GL_EXT_multisample
+#define GL_EXT_multisample 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glSampleMaskEXT (GLclampf, GLboolean);
+  GLAPI void APIENTRY glSamplePatternEXT (GLenum);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLSAMPLEMASKEXTPROC) (GLclampf value, GLboolean invert);
+  typedef void (APIENTRYP PFNGLSAMPLEPATTERNEXTPROC) (GLenum pattern);
+#endif
+
+#ifndef GL_SGIX_vertex_preclip
+#define GL_SGIX_vertex_preclip 1
+#endif
+
+#ifndef GL_SGIX_convolution_accuracy
+#define GL_SGIX_convolution_accuracy 1
+#endif
+
+#ifndef GL_SGIX_resample
+#define GL_SGIX_resample 1
+#endif
+
+#ifndef GL_SGIS_point_line_texgen
+#define GL_SGIS_point_line_texgen 1
+#endif
+
+#ifndef GL_SGIS_texture_color_mask
+#define GL_SGIS_texture_color_mask 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glTextureColorMaskSGIS (GLboolean, GLboolean, GLboolean, GLboolean);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLTEXTURECOLORMASKSGISPROC) (GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha);
+#endif
+
+#ifndef GL_SGIX_igloo_interface
+#define GL_SGIX_igloo_interface 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glIglooInterfaceSGIX (GLenum, const GLvoid *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLIGLOOINTERFACESGIXPROC) (GLenum pname, const GLvoid *params);
+#endif
+
+#ifndef GL_EXT_texture_env_dot3
+#define GL_EXT_texture_env_dot3 1
+#endif
+
+#ifndef GL_ATI_texture_mirror_once
+#define GL_ATI_texture_mirror_once 1
+#endif
+
+#ifndef GL_NV_fence
+#define GL_NV_fence 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glDeleteFencesNV (GLsizei, const GLuint *);
+  GLAPI void APIENTRY glGenFencesNV (GLsizei, GLuint *);
+  GLAPI GLboolean APIENTRY glIsFenceNV (GLuint);
+  GLAPI GLboolean APIENTRY glTestFenceNV (GLuint);
+  GLAPI void APIENTRY glGetFenceivNV (GLuint, GLenum, GLint *);
+  GLAPI void APIENTRY glFinishFenceNV (GLuint);
+  GLAPI void APIENTRY glSetFenceNV (GLuint, GLenum);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLDELETEFENCESNVPROC) (GLsizei n, const GLuint *fences);
+  typedef void (APIENTRYP PFNGLGENFENCESNVPROC) (GLsizei n, GLuint *fences);
+  typedef GLboolean (APIENTRYP PFNGLISFENCENVPROC) (GLuint fence);
+  typedef GLboolean (APIENTRYP PFNGLTESTFENCENVPROC) (GLuint fence);
+  typedef void (APIENTRYP PFNGLGETFENCEIVNVPROC) (GLuint fence, GLenum pname, GLint *params);
+  typedef void (APIENTRYP PFNGLFINISHFENCENVPROC) (GLuint fence);
+  typedef void (APIENTRYP PFNGLSETFENCENVPROC) (GLuint fence, GLenum condition);
+#endif
+
+#ifndef GL_NV_evaluators
+#define GL_NV_evaluators 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glMapControlPointsNV (GLenum, GLuint, GLenum, GLsizei, GLsizei, GLint, GLint, GLboolean, const GLvoid *);
+  GLAPI void APIENTRY glMapParameterivNV (GLenum, GLenum, const GLint *);
+  GLAPI void APIENTRY glMapParameterfvNV (GLenum, GLenum, const GLfloat *);
+  GLAPI void APIENTRY glGetMapControlPointsNV (GLenum, GLuint, GLenum, GLsizei, GLsizei, GLboolean, GLvoid *);
+  GLAPI void APIENTRY glGetMapParameterivNV (GLenum, GLenum, GLint *);
+  GLAPI void APIENTRY glGetMapParameterfvNV (GLenum, GLenum, GLfloat *);
+  GLAPI void APIENTRY glGetMapAttribParameterivNV (GLenum, GLuint, GLenum, GLint *);
+  GLAPI void APIENTRY glGetMapAttribParameterfvNV (GLenum, GLuint, GLenum, GLfloat *);
+  GLAPI void APIENTRY glEvalMapsNV (GLenum, GLenum);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLMAPCONTROLPOINTSNVPROC) (GLenum target, GLuint index, GLenum type, GLsizei ustride, GLsizei vstride, GLint uorder, GLint vorder, GLboolean packed, const GLvoid *points);
+  typedef void (APIENTRYP PFNGLMAPPARAMETERIVNVPROC) (GLenum target, GLenum pname, const GLint *params);
+  typedef void (APIENTRYP PFNGLMAPPARAMETERFVNVPROC) (GLenum target, GLenum pname, const GLfloat *params);
+  typedef void (APIENTRYP PFNGLGETMAPCONTROLPOINTSNVPROC) (GLenum target, GLuint index, GLenum type, GLsizei ustride, GLsizei vstride, GLboolean packed, GLvoid *points);
+  typedef void (APIENTRYP PFNGLGETMAPPARAMETERIVNVPROC) (GLenum target, GLenum pname, GLint *params);
+  typedef void (APIENTRYP PFNGLGETMAPPARAMETERFVNVPROC) (GLenum target, GLenum pname, GLfloat *params);
+  typedef void (APIENTRYP PFNGLGETMAPATTRIBPARAMETERIVNVPROC) (GLenum target, GLuint index, GLenum pname, GLint *params);
+  typedef void (APIENTRYP PFNGLGETMAPATTRIBPARAMETERFVNVPROC) (GLenum target, GLuint index, GLenum pname, GLfloat *params);
+  typedef void (APIENTRYP PFNGLEVALMAPSNVPROC) (GLenum target, GLenum mode);
+#endif
+
+#ifndef GL_NV_packed_depth_stencil
+#define GL_NV_packed_depth_stencil 1
+#endif
+
+#ifndef GL_NV_register_combiners2
+#define GL_NV_register_combiners2 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glCombinerStageParameterfvNV (GLenum, GLenum, const GLfloat *);
+  GLAPI void APIENTRY glGetCombinerStageParameterfvNV (GLenum, GLenum, GLfloat *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLCOMBINERSTAGEPARAMETERFVNVPROC) (GLenum stage, GLenum pname, const GLfloat *params);
+  typedef void (APIENTRYP PFNGLGETCOMBINERSTAGEPARAMETERFVNVPROC) (GLenum stage, GLenum pname, GLfloat *params);
+#endif
+
+#ifndef GL_NV_texture_compression_vtc
+#define GL_NV_texture_compression_vtc 1
+#endif
+
+#ifndef GL_NV_texture_rectangle
+#define GL_NV_texture_rectangle 1
+#endif
+
+#ifndef GL_NV_texture_shader
+#define GL_NV_texture_shader 1
+#endif
+
+#ifndef GL_NV_texture_shader2
+#define GL_NV_texture_shader2 1
+#endif
+
+#ifndef GL_NV_vertex_array_range2
+#define GL_NV_vertex_array_range2 1
+#endif
+
+#ifndef GL_NV_vertex_program
+#define GL_NV_vertex_program 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI GLboolean APIENTRY glAreProgramsResidentNV (GLsizei, const GLuint *, GLboolean *);
+  GLAPI void APIENTRY glBindProgramNV (GLenum, GLuint);
+  GLAPI void APIENTRY glDeleteProgramsNV (GLsizei, const GLuint *);
+  GLAPI void APIENTRY glExecuteProgramNV (GLenum, GLuint, const GLfloat *);
+  GLAPI void APIENTRY glGenProgramsNV (GLsizei, GLuint *);
+  GLAPI void APIENTRY glGetProgramParameterdvNV (GLenum, GLuint, GLenum, GLdouble *);
+  GLAPI void APIENTRY glGetProgramParameterfvNV (GLenum, GLuint, GLenum, GLfloat *);
+  GLAPI void APIENTRY glGetProgramivNV (GLuint, GLenum, GLint *);
+  GLAPI void APIENTRY glGetProgramStringNV (GLuint, GLenum, GLubyte *);
+  GLAPI void APIENTRY glGetTrackMatrixivNV (GLenum, GLuint, GLenum, GLint *);
+  GLAPI void APIENTRY glGetVertexAttribdvNV (GLuint, GLenum, GLdouble *);
+  GLAPI void APIENTRY glGetVertexAttribfvNV (GLuint, GLenum, GLfloat *);
+  GLAPI void APIENTRY glGetVertexAttribivNV (GLuint, GLenum, GLint *);
+  GLAPI void APIENTRY glGetVertexAttribPointervNV (GLuint, GLenum, GLvoid* *);
+  GLAPI GLboolean APIENTRY glIsProgramNV (GLuint);
+  GLAPI void APIENTRY glLoadProgramNV (GLenum, GLuint, GLsizei, const GLubyte *);
+  GLAPI void APIENTRY glProgramParameter4dNV (GLenum, GLuint, GLdouble, GLdouble, GLdouble, GLdouble);
+  GLAPI void APIENTRY glProgramParameter4dvNV (GLenum, GLuint, const GLdouble *);
+  GLAPI void APIENTRY glProgramParameter4fNV (GLenum, GLuint, GLfloat, GLfloat, GLfloat, GLfloat);
+  GLAPI void APIENTRY glProgramParameter4fvNV (GLenum, GLuint, const GLfloat *);
+  GLAPI void APIENTRY glProgramParameters4dvNV (GLenum, GLuint, GLuint, const GLdouble *);
+  GLAPI void APIENTRY glProgramParameters4fvNV (GLenum, GLuint, GLuint, const GLfloat *);
+  GLAPI void APIENTRY glRequestResidentProgramsNV (GLsizei, const GLuint *);
+  GLAPI void APIENTRY glTrackMatrixNV (GLenum, GLuint, GLenum, GLenum);
+  GLAPI void APIENTRY glVertexAttribPointerNV (GLuint, GLint, GLenum, GLsizei, const GLvoid *);
+  GLAPI void APIENTRY glVertexAttrib1dNV (GLuint, GLdouble);
+  GLAPI void APIENTRY glVertexAttrib1dvNV (GLuint, const GLdouble *);
+  GLAPI void APIENTRY glVertexAttrib1fNV (GLuint, GLfloat);
+  GLAPI void APIENTRY glVertexAttrib1fvNV (GLuint, const GLfloat *);
+  GLAPI void APIENTRY glVertexAttrib1sNV (GLuint, GLshort);
+  GLAPI void APIENTRY glVertexAttrib1svNV (GLuint, const GLshort *);
+  GLAPI void APIENTRY glVertexAttrib2dNV (GLuint, GLdouble, GLdouble);
+  GLAPI void APIENTRY glVertexAttrib2dvNV (GLuint, const GLdouble *);
+  GLAPI void APIENTRY glVertexAttrib2fNV (GLuint, GLfloat, GLfloat);
+  GLAPI void APIENTRY glVertexAttrib2fvNV (GLuint, const GLfloat *);
+  GLAPI void APIENTRY glVertexAttrib2sNV (GLuint, GLshort, GLshort);
+  GLAPI void APIENTRY glVertexAttrib2svNV (GLuint, const GLshort *);
+  GLAPI void APIENTRY glVertexAttrib3dNV (GLuint, GLdouble, GLdouble, GLdouble);
+  GLAPI void APIENTRY glVertexAttrib3dvNV (GLuint, const GLdouble *);
+  GLAPI void APIENTRY glVertexAttrib3fNV (GLuint, GLfloat, GLfloat, GLfloat);
+  GLAPI void APIENTRY glVertexAttrib3fvNV (GLuint, const GLfloat *);
+  GLAPI void APIENTRY glVertexAttrib3sNV (GLuint, GLshort, GLshort, GLshort);
+  GLAPI void APIENTRY glVertexAttrib3svNV (GLuint, const GLshort *);
+  GLAPI void APIENTRY glVertexAttrib4dNV (GLuint, GLdouble, GLdouble, GLdouble, GLdouble);
+  GLAPI void APIENTRY glVertexAttrib4dvNV (GLuint, const GLdouble *);
+  GLAPI void APIENTRY glVertexAttrib4fNV (GLuint, GLfloat, GLfloat, GLfloat, GLfloat);
+  GLAPI void APIENTRY glVertexAttrib4fvNV (GLuint, const GLfloat *);
+  GLAPI void APIENTRY glVertexAttrib4sNV (GLuint, GLshort, GLshort, GLshort, GLshort);
+  GLAPI void APIENTRY glVertexAttrib4svNV (GLuint, const GLshort *);
+  GLAPI void APIENTRY glVertexAttrib4ubNV (GLuint, GLubyte, GLubyte, GLubyte, GLubyte);
+  GLAPI void APIENTRY glVertexAttrib4ubvNV (GLuint, const GLubyte *);
+  GLAPI void APIENTRY glVertexAttribs1dvNV (GLuint, GLsizei, const GLdouble *);
+  GLAPI void APIENTRY glVertexAttribs1fvNV (GLuint, GLsizei, const GLfloat *);
+  GLAPI void APIENTRY glVertexAttribs1svNV (GLuint, GLsizei, const GLshort *);
+  GLAPI void APIENTRY glVertexAttribs2dvNV (GLuint, GLsizei, const GLdouble *);
+  GLAPI void APIENTRY glVertexAttribs2fvNV (GLuint, GLsizei, const GLfloat *);
+  GLAPI void APIENTRY glVertexAttribs2svNV (GLuint, GLsizei, const GLshort *);
+  GLAPI void APIENTRY glVertexAttribs3dvNV (GLuint, GLsizei, const GLdouble *);
+  GLAPI void APIENTRY glVertexAttribs3fvNV (GLuint, GLsizei, const GLfloat *);
+  GLAPI void APIENTRY glVertexAttribs3svNV (GLuint, GLsizei, const GLshort *);
+  GLAPI void APIENTRY glVertexAttribs4dvNV (GLuint, GLsizei, const GLdouble *);
+  GLAPI void APIENTRY glVertexAttribs4fvNV (GLuint, GLsizei, const GLfloat *);
+  GLAPI void APIENTRY glVertexAttribs4svNV (GLuint, GLsizei, const GLshort *);
+  GLAPI void APIENTRY glVertexAttribs4ubvNV (GLuint, GLsizei, const GLubyte *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef GLboolean (APIENTRYP PFNGLAREPROGRAMSRESIDENTNVPROC) (GLsizei n, const GLuint *programs, GLboolean *residences);
+  typedef void (APIENTRYP PFNGLBINDPROGRAMNVPROC) (GLenum target, GLuint id);
+  typedef void (APIENTRYP PFNGLDELETEPROGRAMSNVPROC) (GLsizei n, const GLuint *programs);
+  typedef void (APIENTRYP PFNGLEXECUTEPROGRAMNVPROC) (GLenum target, GLuint id, const GLfloat *params);
+  typedef void (APIENTRYP PFNGLGENPROGRAMSNVPROC) (GLsizei n, GLuint *programs);
+  typedef void (APIENTRYP PFNGLGETPROGRAMPARAMETERDVNVPROC) (GLenum target, GLuint index, GLenum pname, GLdouble *params);
+  typedef void (APIENTRYP PFNGLGETPROGRAMPARAMETERFVNVPROC) (GLenum target, GLuint index, GLenum pname, GLfloat *params);
+  typedef void (APIENTRYP PFNGLGETPROGRAMIVNVPROC) (GLuint id, GLenum pname, GLint *params);
+  typedef void (APIENTRYP PFNGLGETPROGRAMSTRINGNVPROC) (GLuint id, GLenum pname, GLubyte *program);
+  typedef void (APIENTRYP PFNGLGETTRACKMATRIXIVNVPROC) (GLenum target, GLuint address, GLenum pname, GLint *params);
+  typedef void (APIENTRYP PFNGLGETVERTEXATTRIBDVNVPROC) (GLuint index, GLenum pname, GLdouble *params);
+  typedef void (APIENTRYP PFNGLGETVERTEXATTRIBFVNVPROC) (GLuint index, GLenum pname, GLfloat *params);
+  typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVNVPROC) (GLuint index, GLenum pname, GLint *params);
+  typedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVNVPROC) (GLuint index, GLenum pname, GLvoid* *pointer);
+  typedef GLboolean (APIENTRYP PFNGLISPROGRAMNVPROC) (GLuint id);
+  typedef void (APIENTRYP PFNGLLOADPROGRAMNVPROC) (GLenum target, GLuint id, GLsizei len, const GLubyte *program);
+  typedef void (APIENTRYP PFNGLPROGRAMPARAMETER4DNVPROC) (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+  typedef void (APIENTRYP PFNGLPROGRAMPARAMETER4DVNVPROC) (GLenum target, GLuint index, const GLdouble *v);
+  typedef void (APIENTRYP PFNGLPROGRAMPARAMETER4FNVPROC) (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+  typedef void (APIENTRYP PFNGLPROGRAMPARAMETER4FVNVPROC) (GLenum target, GLuint index, const GLfloat *v);
+  typedef void (APIENTRYP PFNGLPROGRAMPARAMETERS4DVNVPROC) (GLenum target, GLuint index, GLuint count, const GLdouble *v);
+  typedef void (APIENTRYP PFNGLPROGRAMPARAMETERS4FVNVPROC) (GLenum target, GLuint index, GLuint count, const GLfloat *v);
+  typedef void (APIENTRYP PFNGLREQUESTRESIDENTPROGRAMSNVPROC) (GLsizei n, const GLuint *programs);
+  typedef void (APIENTRYP PFNGLTRACKMATRIXNVPROC) (GLenum target, GLuint address, GLenum matrix, GLenum transform);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERNVPROC) (GLuint index, GLint fsize, GLenum type, GLsizei stride, const GLvoid *pointer);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB1DNVPROC) (GLuint index, GLdouble x);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB1DVNVPROC) (GLuint index, const GLdouble *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB1FNVPROC) (GLuint index, GLfloat x);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB1FVNVPROC) (GLuint index, const GLfloat *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB1SNVPROC) (GLuint index, GLshort x);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB1SVNVPROC) (GLuint index, const GLshort *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB2DNVPROC) (GLuint index, GLdouble x, GLdouble y);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB2DVNVPROC) (GLuint index, const GLdouble *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB2FNVPROC) (GLuint index, GLfloat x, GLfloat y);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB2FVNVPROC) (GLuint index, const GLfloat *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB2SNVPROC) (GLuint index, GLshort x, GLshort y);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB2SVNVPROC) (GLuint index, const GLshort *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB3DNVPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB3DVNVPROC) (GLuint index, const GLdouble *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB3FNVPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB3FVNVPROC) (GLuint index, const GLfloat *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB3SNVPROC) (GLuint index, GLshort x, GLshort y, GLshort z);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB3SVNVPROC) (GLuint index, const GLshort *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB4DNVPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB4DVNVPROC) (GLuint index, const GLdouble *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB4FNVPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB4FVNVPROC) (GLuint index, const GLfloat *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB4SNVPROC) (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB4SVNVPROC) (GLuint index, const GLshort *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBNVPROC) (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBVNVPROC) (GLuint index, const GLubyte *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIBS1DVNVPROC) (GLuint index, GLsizei count, const GLdouble *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIBS1FVNVPROC) (GLuint index, GLsizei count, const GLfloat *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIBS1SVNVPROC) (GLuint index, GLsizei count, const GLshort *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIBS2DVNVPROC) (GLuint index, GLsizei count, const GLdouble *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIBS2FVNVPROC) (GLuint index, GLsizei count, const GLfloat *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIBS2SVNVPROC) (GLuint index, GLsizei count, const GLshort *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIBS3DVNVPROC) (GLuint index, GLsizei count, const GLdouble *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIBS3FVNVPROC) (GLuint index, GLsizei count, const GLfloat *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIBS3SVNVPROC) (GLuint index, GLsizei count, const GLshort *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIBS4DVNVPROC) (GLuint index, GLsizei count, const GLdouble *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIBS4FVNVPROC) (GLuint index, GLsizei count, const GLfloat *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIBS4SVNVPROC) (GLuint index, GLsizei count, const GLshort *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIBS4UBVNVPROC) (GLuint index, GLsizei count, const GLubyte *v);
+#endif
+
+#ifndef GL_SGIX_texture_coordinate_clamp
+#define GL_SGIX_texture_coordinate_clamp 1
+#endif
+
+#ifndef GL_SGIX_scalebias_hint
+#define GL_SGIX_scalebias_hint 1
+#endif
+
+#ifndef GL_OML_interlace
+#define GL_OML_interlace 1
+#endif
+
+#ifndef GL_OML_subsample
+#define GL_OML_subsample 1
+#endif
+
+#ifndef GL_OML_resample
+#define GL_OML_resample 1
+#endif
+
+#ifndef GL_NV_copy_depth_to_color
+#define GL_NV_copy_depth_to_color 1
+#endif
+
+#ifndef GL_ATI_envmap_bumpmap
+#define GL_ATI_envmap_bumpmap 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glTexBumpParameterivATI (GLenum, const GLint *);
+  GLAPI void APIENTRY glTexBumpParameterfvATI (GLenum, const GLfloat *);
+  GLAPI void APIENTRY glGetTexBumpParameterivATI (GLenum, GLint *);
+  GLAPI void APIENTRY glGetTexBumpParameterfvATI (GLenum, GLfloat *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLTEXBUMPPARAMETERIVATIPROC) (GLenum pname, const GLint *param);
+  typedef void (APIENTRYP PFNGLTEXBUMPPARAMETERFVATIPROC) (GLenum pname, const GLfloat *param);
+  typedef void (APIENTRYP PFNGLGETTEXBUMPPARAMETERIVATIPROC) (GLenum pname, GLint *param);
+  typedef void (APIENTRYP PFNGLGETTEXBUMPPARAMETERFVATIPROC) (GLenum pname, GLfloat *param);
+#endif
+
+#ifndef GL_ATI_fragment_shader
+#define GL_ATI_fragment_shader 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI GLuint APIENTRY glGenFragmentShadersATI (GLuint);
+  GLAPI void APIENTRY glBindFragmentShaderATI (GLuint);
+  GLAPI void APIENTRY glDeleteFragmentShaderATI (GLuint);
+  GLAPI void APIENTRY glBeginFragmentShaderATI (void);
+  GLAPI void APIENTRY glEndFragmentShaderATI (void);
+  GLAPI void APIENTRY glPassTexCoordATI (GLuint, GLuint, GLenum);
+  GLAPI void APIENTRY glSampleMapATI (GLuint, GLuint, GLenum);
+  GLAPI void APIENTRY glColorFragmentOp1ATI (GLenum, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint);
+  GLAPI void APIENTRY glColorFragmentOp2ATI (GLenum, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint);
+  GLAPI void APIENTRY glColorFragmentOp3ATI (GLenum, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint);
+  GLAPI void APIENTRY glAlphaFragmentOp1ATI (GLenum, GLuint, GLuint, GLuint, GLuint, GLuint);
+  GLAPI void APIENTRY glAlphaFragmentOp2ATI (GLenum, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint);
+  GLAPI void APIENTRY glAlphaFragmentOp3ATI (GLenum, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint);
+  GLAPI void APIENTRY glSetFragmentShaderConstantATI (GLuint, const GLfloat *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef GLuint (APIENTRYP PFNGLGENFRAGMENTSHADERSATIPROC) (GLuint range);
+  typedef void (APIENTRYP PFNGLBINDFRAGMENTSHADERATIPROC) (GLuint id);
+  typedef void (APIENTRYP PFNGLDELETEFRAGMENTSHADERATIPROC) (GLuint id);
+  typedef void (APIENTRYP PFNGLBEGINFRAGMENTSHADERATIPROC) (void);
+  typedef void (APIENTRYP PFNGLENDFRAGMENTSHADERATIPROC) (void);
+  typedef void (APIENTRYP PFNGLPASSTEXCOORDATIPROC) (GLuint dst, GLuint coord, GLenum swizzle);
+  typedef void (APIENTRYP PFNGLSAMPLEMAPATIPROC) (GLuint dst, GLuint interp, GLenum swizzle);
+  typedef void (APIENTRYP PFNGLCOLORFRAGMENTOP1ATIPROC) (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod);
+  typedef void (APIENTRYP PFNGLCOLORFRAGMENTOP2ATIPROC) (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod);
+  typedef void (APIENTRYP PFNGLCOLORFRAGMENTOP3ATIPROC) (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod, GLuint arg3, GLuint arg3Rep, GLuint arg3Mod);
+  typedef void (APIENTRYP PFNGLALPHAFRAGMENTOP1ATIPROC) (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod);
+  typedef void (APIENTRYP PFNGLALPHAFRAGMENTOP2ATIPROC) (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod);
+  typedef void (APIENTRYP PFNGLALPHAFRAGMENTOP3ATIPROC) (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod, GLuint arg3, GLuint arg3Rep, GLuint arg3Mod);
+  typedef void (APIENTRYP PFNGLSETFRAGMENTSHADERCONSTANTATIPROC) (GLuint dst, const GLfloat *value);
+#endif
+
+#ifndef GL_ATI_pn_triangles
+#define GL_ATI_pn_triangles 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glPNTrianglesiATI (GLenum, GLint);
+  GLAPI void APIENTRY glPNTrianglesfATI (GLenum, GLfloat);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLPNTRIANGLESIATIPROC) (GLenum pname, GLint param);
+  typedef void (APIENTRYP PFNGLPNTRIANGLESFATIPROC) (GLenum pname, GLfloat param);
+#endif
+
+#ifndef GL_ATI_vertex_array_object
+#define GL_ATI_vertex_array_object 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI GLuint APIENTRY glNewObjectBufferATI (GLsizei, const GLvoid *, GLenum);
+  GLAPI GLboolean APIENTRY glIsObjectBufferATI (GLuint);
+  GLAPI void APIENTRY glUpdateObjectBufferATI (GLuint, GLuint, GLsizei, const GLvoid *, GLenum);
+  GLAPI void APIENTRY glGetObjectBufferfvATI (GLuint, GLenum, GLfloat *);
+  GLAPI void APIENTRY glGetObjectBufferivATI (GLuint, GLenum, GLint *);
+  GLAPI void APIENTRY glFreeObjectBufferATI (GLuint);
+  GLAPI void APIENTRY glArrayObjectATI (GLenum, GLint, GLenum, GLsizei, GLuint, GLuint);
+  GLAPI void APIENTRY glGetArrayObjectfvATI (GLenum, GLenum, GLfloat *);
+  GLAPI void APIENTRY glGetArrayObjectivATI (GLenum, GLenum, GLint *);
+  GLAPI void APIENTRY glVariantArrayObjectATI (GLuint, GLenum, GLsizei, GLuint, GLuint);
+  GLAPI void APIENTRY glGetVariantArrayObjectfvATI (GLuint, GLenum, GLfloat *);
+  GLAPI void APIENTRY glGetVariantArrayObjectivATI (GLuint, GLenum, GLint *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef GLuint (APIENTRYP PFNGLNEWOBJECTBUFFERATIPROC) (GLsizei size, const GLvoid *pointer, GLenum usage);
+  typedef GLboolean (APIENTRYP PFNGLISOBJECTBUFFERATIPROC) (GLuint buffer);
+  typedef void (APIENTRYP PFNGLUPDATEOBJECTBUFFERATIPROC) (GLuint buffer, GLuint offset, GLsizei size, const GLvoid *pointer, GLenum preserve);
+  typedef void (APIENTRYP PFNGLGETOBJECTBUFFERFVATIPROC) (GLuint buffer, GLenum pname, GLfloat *params);
+  typedef void (APIENTRYP PFNGLGETOBJECTBUFFERIVATIPROC) (GLuint buffer, GLenum pname, GLint *params);
+  typedef void (APIENTRYP PFNGLFREEOBJECTBUFFERATIPROC) (GLuint buffer);
+  typedef void (APIENTRYP PFNGLARRAYOBJECTATIPROC) (GLenum array, GLint size, GLenum type, GLsizei stride, GLuint buffer, GLuint offset);
+  typedef void (APIENTRYP PFNGLGETARRAYOBJECTFVATIPROC) (GLenum array, GLenum pname, GLfloat *params);
+  typedef void (APIENTRYP PFNGLGETARRAYOBJECTIVATIPROC) (GLenum array, GLenum pname, GLint *params);
+  typedef void (APIENTRYP PFNGLVARIANTARRAYOBJECTATIPROC) (GLuint id, GLenum type, GLsizei stride, GLuint buffer, GLuint offset);
+  typedef void (APIENTRYP PFNGLGETVARIANTARRAYOBJECTFVATIPROC) (GLuint id, GLenum pname, GLfloat *params);
+  typedef void (APIENTRYP PFNGLGETVARIANTARRAYOBJECTIVATIPROC) (GLuint id, GLenum pname, GLint *params);
+#endif
+
+#ifndef GL_EXT_vertex_shader
+#define GL_EXT_vertex_shader 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glBeginVertexShaderEXT (void);
+  GLAPI void APIENTRY glEndVertexShaderEXT (void);
+  GLAPI void APIENTRY glBindVertexShaderEXT (GLuint);
+  GLAPI GLuint APIENTRY glGenVertexShadersEXT (GLuint);
+  GLAPI void APIENTRY glDeleteVertexShaderEXT (GLuint);
+  GLAPI void APIENTRY glShaderOp1EXT (GLenum, GLuint, GLuint);
+  GLAPI void APIENTRY glShaderOp2EXT (GLenum, GLuint, GLuint, GLuint);
+  GLAPI void APIENTRY glShaderOp3EXT (GLenum, GLuint, GLuint, GLuint, GLuint);
+  GLAPI void APIENTRY glSwizzleEXT (GLuint, GLuint, GLenum, GLenum, GLenum, GLenum);
+  GLAPI void APIENTRY glWriteMaskEXT (GLuint, GLuint, GLenum, GLenum, GLenum, GLenum);
+  GLAPI void APIENTRY glInsertComponentEXT (GLuint, GLuint, GLuint);
+  GLAPI void APIENTRY glExtractComponentEXT (GLuint, GLuint, GLuint);
+  GLAPI GLuint APIENTRY glGenSymbolsEXT (GLenum, GLenum, GLenum, GLuint);
+  GLAPI void APIENTRY glSetInvariantEXT (GLuint, GLenum, const GLvoid *);
+  GLAPI void APIENTRY glSetLocalConstantEXT (GLuint, GLenum, const GLvoid *);
+  GLAPI void APIENTRY glVariantbvEXT (GLuint, const GLbyte *);
+  GLAPI void APIENTRY glVariantsvEXT (GLuint, const GLshort *);
+  GLAPI void APIENTRY glVariantivEXT (GLuint, const GLint *);
+  GLAPI void APIENTRY glVariantfvEXT (GLuint, const GLfloat *);
+  GLAPI void APIENTRY glVariantdvEXT (GLuint, const GLdouble *);
+  GLAPI void APIENTRY glVariantubvEXT (GLuint, const GLubyte *);
+  GLAPI void APIENTRY glVariantusvEXT (GLuint, const GLushort *);
+  GLAPI void APIENTRY glVariantuivEXT (GLuint, const GLuint *);
+  GLAPI void APIENTRY glVariantPointerEXT (GLuint, GLenum, GLuint, const GLvoid *);
+  GLAPI void APIENTRY glEnableVariantClientStateEXT (GLuint);
+  GLAPI void APIENTRY glDisableVariantClientStateEXT (GLuint);
+  GLAPI GLuint APIENTRY glBindLightParameterEXT (GLenum, GLenum);
+  GLAPI GLuint APIENTRY glBindMaterialParameterEXT (GLenum, GLenum);
+  GLAPI GLuint APIENTRY glBindTexGenParameterEXT (GLenum, GLenum, GLenum);
+  GLAPI GLuint APIENTRY glBindTextureUnitParameterEXT (GLenum, GLenum);
+  GLAPI GLuint APIENTRY glBindParameterEXT (GLenum);
+  GLAPI GLboolean APIENTRY glIsVariantEnabledEXT (GLuint, GLenum);
+  GLAPI void APIENTRY glGetVariantBooleanvEXT (GLuint, GLenum, GLboolean *);
+  GLAPI void APIENTRY glGetVariantIntegervEXT (GLuint, GLenum, GLint *);
+  GLAPI void APIENTRY glGetVariantFloatvEXT (GLuint, GLenum, GLfloat *);
+  GLAPI void APIENTRY glGetVariantPointervEXT (GLuint, GLenum, GLvoid* *);
+  GLAPI void APIENTRY glGetInvariantBooleanvEXT (GLuint, GLenum, GLboolean *);
+  GLAPI void APIENTRY glGetInvariantIntegervEXT (GLuint, GLenum, GLint *);
+  GLAPI void APIENTRY glGetInvariantFloatvEXT (GLuint, GLenum, GLfloat *);
+  GLAPI void APIENTRY glGetLocalConstantBooleanvEXT (GLuint, GLenum, GLboolean *);
+  GLAPI void APIENTRY glGetLocalConstantIntegervEXT (GLuint, GLenum, GLint *);
+  GLAPI void APIENTRY glGetLocalConstantFloatvEXT (GLuint, GLenum, GLfloat *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLBEGINVERTEXSHADEREXTPROC) (void);
+  typedef void (APIENTRYP PFNGLENDVERTEXSHADEREXTPROC) (void);
+  typedef void (APIENTRYP PFNGLBINDVERTEXSHADEREXTPROC) (GLuint id);
+  typedef GLuint (APIENTRYP PFNGLGENVERTEXSHADERSEXTPROC) (GLuint range);
+  typedef void (APIENTRYP PFNGLDELETEVERTEXSHADEREXTPROC) (GLuint id);
+  typedef void (APIENTRYP PFNGLSHADEROP1EXTPROC) (GLenum op, GLuint res, GLuint arg1);
+  typedef void (APIENTRYP PFNGLSHADEROP2EXTPROC) (GLenum op, GLuint res, GLuint arg1, GLuint arg2);
+  typedef void (APIENTRYP PFNGLSHADEROP3EXTPROC) (GLenum op, GLuint res, GLuint arg1, GLuint arg2, GLuint arg3);
+  typedef void (APIENTRYP PFNGLSWIZZLEEXTPROC) (GLuint res, GLuint in, GLenum outX, GLenum outY, GLenum outZ, GLenum outW);
+  typedef void (APIENTRYP PFNGLWRITEMASKEXTPROC) (GLuint res, GLuint in, GLenum outX, GLenum outY, GLenum outZ, GLenum outW);
+  typedef void (APIENTRYP PFNGLINSERTCOMPONENTEXTPROC) (GLuint res, GLuint src, GLuint num);
+  typedef void (APIENTRYP PFNGLEXTRACTCOMPONENTEXTPROC) (GLuint res, GLuint src, GLuint num);
+  typedef GLuint (APIENTRYP PFNGLGENSYMBOLSEXTPROC) (GLenum datatype, GLenum storagetype, GLenum range, GLuint components);
+  typedef void (APIENTRYP PFNGLSETINVARIANTEXTPROC) (GLuint id, GLenum type, const GLvoid *addr);
+  typedef void (APIENTRYP PFNGLSETLOCALCONSTANTEXTPROC) (GLuint id, GLenum type, const GLvoid *addr);
+  typedef void (APIENTRYP PFNGLVARIANTBVEXTPROC) (GLuint id, const GLbyte *addr);
+  typedef void (APIENTRYP PFNGLVARIANTSVEXTPROC) (GLuint id, const GLshort *addr);
+  typedef void (APIENTRYP PFNGLVARIANTIVEXTPROC) (GLuint id, const GLint *addr);
+  typedef void (APIENTRYP PFNGLVARIANTFVEXTPROC) (GLuint id, const GLfloat *addr);
+  typedef void (APIENTRYP PFNGLVARIANTDVEXTPROC) (GLuint id, const GLdouble *addr);
+  typedef void (APIENTRYP PFNGLVARIANTUBVEXTPROC) (GLuint id, const GLubyte *addr);
+  typedef void (APIENTRYP PFNGLVARIANTUSVEXTPROC) (GLuint id, const GLushort *addr);
+  typedef void (APIENTRYP PFNGLVARIANTUIVEXTPROC) (GLuint id, const GLuint *addr);
+  typedef void (APIENTRYP PFNGLVARIANTPOINTEREXTPROC) (GLuint id, GLenum type, GLuint stride, const GLvoid *addr);
+  typedef void (APIENTRYP PFNGLENABLEVARIANTCLIENTSTATEEXTPROC) (GLuint id);
+  typedef void (APIENTRYP PFNGLDISABLEVARIANTCLIENTSTATEEXTPROC) (GLuint id);
+  typedef GLuint (APIENTRYP PFNGLBINDLIGHTPARAMETEREXTPROC) (GLenum light, GLenum value);
+  typedef GLuint (APIENTRYP PFNGLBINDMATERIALPARAMETEREXTPROC) (GLenum face, GLenum value);
+  typedef GLuint (APIENTRYP PFNGLBINDTEXGENPARAMETEREXTPROC) (GLenum unit, GLenum coord, GLenum value);
+  typedef GLuint (APIENTRYP PFNGLBINDTEXTUREUNITPARAMETEREXTPROC) (GLenum unit, GLenum value);
+  typedef GLuint (APIENTRYP PFNGLBINDPARAMETEREXTPROC) (GLenum value);
+  typedef GLboolean (APIENTRYP PFNGLISVARIANTENABLEDEXTPROC) (GLuint id, GLenum cap);
+  typedef void (APIENTRYP PFNGLGETVARIANTBOOLEANVEXTPROC) (GLuint id, GLenum value, GLboolean *data);
+  typedef void (APIENTRYP PFNGLGETVARIANTINTEGERVEXTPROC) (GLuint id, GLenum value, GLint *data);
+  typedef void (APIENTRYP PFNGLGETVARIANTFLOATVEXTPROC) (GLuint id, GLenum value, GLfloat *data);
+  typedef void (APIENTRYP PFNGLGETVARIANTPOINTERVEXTPROC) (GLuint id, GLenum value, GLvoid* *data);
+  typedef void (APIENTRYP PFNGLGETINVARIANTBOOLEANVEXTPROC) (GLuint id, GLenum value, GLboolean *data);
+  typedef void (APIENTRYP PFNGLGETINVARIANTINTEGERVEXTPROC) (GLuint id, GLenum value, GLint *data);
+  typedef void (APIENTRYP PFNGLGETINVARIANTFLOATVEXTPROC) (GLuint id, GLenum value, GLfloat *data);
+  typedef void (APIENTRYP PFNGLGETLOCALCONSTANTBOOLEANVEXTPROC) (GLuint id, GLenum value, GLboolean *data);
+  typedef void (APIENTRYP PFNGLGETLOCALCONSTANTINTEGERVEXTPROC) (GLuint id, GLenum value, GLint *data);
+  typedef void (APIENTRYP PFNGLGETLOCALCONSTANTFLOATVEXTPROC) (GLuint id, GLenum value, GLfloat *data);
+#endif
+
+#ifndef GL_ATI_vertex_streams
+#define GL_ATI_vertex_streams 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glVertexStream1sATI (GLenum, GLshort);
+  GLAPI void APIENTRY glVertexStream1svATI (GLenum, const GLshort *);
+  GLAPI void APIENTRY glVertexStream1iATI (GLenum, GLint);
+  GLAPI void APIENTRY glVertexStream1ivATI (GLenum, const GLint *);
+  GLAPI void APIENTRY glVertexStream1fATI (GLenum, GLfloat);
+  GLAPI void APIENTRY glVertexStream1fvATI (GLenum, const GLfloat *);
+  GLAPI void APIENTRY glVertexStream1dATI (GLenum, GLdouble);
+  GLAPI void APIENTRY glVertexStream1dvATI (GLenum, const GLdouble *);
+  GLAPI void APIENTRY glVertexStream2sATI (GLenum, GLshort, GLshort);
+  GLAPI void APIENTRY glVertexStream2svATI (GLenum, const GLshort *);
+  GLAPI void APIENTRY glVertexStream2iATI (GLenum, GLint, GLint);
+  GLAPI void APIENTRY glVertexStream2ivATI (GLenum, const GLint *);
+  GLAPI void APIENTRY glVertexStream2fATI (GLenum, GLfloat, GLfloat);
+  GLAPI void APIENTRY glVertexStream2fvATI (GLenum, const GLfloat *);
+  GLAPI void APIENTRY glVertexStream2dATI (GLenum, GLdouble, GLdouble);
+  GLAPI void APIENTRY glVertexStream2dvATI (GLenum, const GLdouble *);
+  GLAPI void APIENTRY glVertexStream3sATI (GLenum, GLshort, GLshort, GLshort);
+  GLAPI void APIENTRY glVertexStream3svATI (GLenum, const GLshort *);
+  GLAPI void APIENTRY glVertexStream3iATI (GLenum, GLint, GLint, GLint);
+  GLAPI void APIENTRY glVertexStream3ivATI (GLenum, const GLint *);
+  GLAPI void APIENTRY glVertexStream3fATI (GLenum, GLfloat, GLfloat, GLfloat);
+  GLAPI void APIENTRY glVertexStream3fvATI (GLenum, const GLfloat *);
+  GLAPI void APIENTRY glVertexStream3dATI (GLenum, GLdouble, GLdouble, GLdouble);
+  GLAPI void APIENTRY glVertexStream3dvATI (GLenum, const GLdouble *);
+  GLAPI void APIENTRY glVertexStream4sATI (GLenum, GLshort, GLshort, GLshort, GLshort);
+  GLAPI void APIENTRY glVertexStream4svATI (GLenum, const GLshort *);
+  GLAPI void APIENTRY glVertexStream4iATI (GLenum, GLint, GLint, GLint, GLint);
+  GLAPI void APIENTRY glVertexStream4ivATI (GLenum, const GLint *);
+  GLAPI void APIENTRY glVertexStream4fATI (GLenum, GLfloat, GLfloat, GLfloat, GLfloat);
+  GLAPI void APIENTRY glVertexStream4fvATI (GLenum, const GLfloat *);
+  GLAPI void APIENTRY glVertexStream4dATI (GLenum, GLdouble, GLdouble, GLdouble, GLdouble);
+  GLAPI void APIENTRY glVertexStream4dvATI (GLenum, const GLdouble *);
+  GLAPI void APIENTRY glNormalStream3bATI (GLenum, GLbyte, GLbyte, GLbyte);
+  GLAPI void APIENTRY glNormalStream3bvATI (GLenum, const GLbyte *);
+  GLAPI void APIENTRY glNormalStream3sATI (GLenum, GLshort, GLshort, GLshort);
+  GLAPI void APIENTRY glNormalStream3svATI (GLenum, const GLshort *);
+  GLAPI void APIENTRY glNormalStream3iATI (GLenum, GLint, GLint, GLint);
+  GLAPI void APIENTRY glNormalStream3ivATI (GLenum, const GLint *);
+  GLAPI void APIENTRY glNormalStream3fATI (GLenum, GLfloat, GLfloat, GLfloat);
+  GLAPI void APIENTRY glNormalStream3fvATI (GLenum, const GLfloat *);
+  GLAPI void APIENTRY glNormalStream3dATI (GLenum, GLdouble, GLdouble, GLdouble);
+  GLAPI void APIENTRY glNormalStream3dvATI (GLenum, const GLdouble *);
+  GLAPI void APIENTRY glClientActiveVertexStreamATI (GLenum);
+  GLAPI void APIENTRY glVertexBlendEnviATI (GLenum, GLint);
+  GLAPI void APIENTRY glVertexBlendEnvfATI (GLenum, GLfloat);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLVERTEXSTREAM1SATIPROC) (GLenum stream, GLshort x);
+  typedef void (APIENTRYP PFNGLVERTEXSTREAM1SVATIPROC) (GLenum stream, const GLshort *coords);
+  typedef void (APIENTRYP PFNGLVERTEXSTREAM1IATIPROC) (GLenum stream, GLint x);
+  typedef void (APIENTRYP PFNGLVERTEXSTREAM1IVATIPROC) (GLenum stream, const GLint *coords);
+  typedef void (APIENTRYP PFNGLVERTEXSTREAM1FATIPROC) (GLenum stream, GLfloat x);
+  typedef void (APIENTRYP PFNGLVERTEXSTREAM1FVATIPROC) (GLenum stream, const GLfloat *coords);
+  typedef void (APIENTRYP PFNGLVERTEXSTREAM1DATIPROC) (GLenum stream, GLdouble x);
+  typedef void (APIENTRYP PFNGLVERTEXSTREAM1DVATIPROC) (GLenum stream, const GLdouble *coords);
+  typedef void (APIENTRYP PFNGLVERTEXSTREAM2SATIPROC) (GLenum stream, GLshort x, GLshort y);
+  typedef void (APIENTRYP PFNGLVERTEXSTREAM2SVATIPROC) (GLenum stream, const GLshort *coords);
+  typedef void (APIENTRYP PFNGLVERTEXSTREAM2IATIPROC) (GLenum stream, GLint x, GLint y);
+  typedef void (APIENTRYP PFNGLVERTEXSTREAM2IVATIPROC) (GLenum stream, const GLint *coords);
+  typedef void (APIENTRYP PFNGLVERTEXSTREAM2FATIPROC) (GLenum stream, GLfloat x, GLfloat y);
+  typedef void (APIENTRYP PFNGLVERTEXSTREAM2FVATIPROC) (GLenum stream, const GLfloat *coords);
+  typedef void (APIENTRYP PFNGLVERTEXSTREAM2DATIPROC) (GLenum stream, GLdouble x, GLdouble y);
+  typedef void (APIENTRYP PFNGLVERTEXSTREAM2DVATIPROC) (GLenum stream, const GLdouble *coords);
+  typedef void (APIENTRYP PFNGLVERTEXSTREAM3SATIPROC) (GLenum stream, GLshort x, GLshort y, GLshort z);
+  typedef void (APIENTRYP PFNGLVERTEXSTREAM3SVATIPROC) (GLenum stream, const GLshort *coords);
+  typedef void (APIENTRYP PFNGLVERTEXSTREAM3IATIPROC) (GLenum stream, GLint x, GLint y, GLint z);
+  typedef void (APIENTRYP PFNGLVERTEXSTREAM3IVATIPROC) (GLenum stream, const GLint *coords);
+  typedef void (APIENTRYP PFNGLVERTEXSTREAM3FATIPROC) (GLenum stream, GLfloat x, GLfloat y, GLfloat z);
+  typedef void (APIENTRYP PFNGLVERTEXSTREAM3FVATIPROC) (GLenum stream, const GLfloat *coords);
+  typedef void (APIENTRYP PFNGLVERTEXSTREAM3DATIPROC) (GLenum stream, GLdouble x, GLdouble y, GLdouble z);
+  typedef void (APIENTRYP PFNGLVERTEXSTREAM3DVATIPROC) (GLenum stream, const GLdouble *coords);
+  typedef void (APIENTRYP PFNGLVERTEXSTREAM4SATIPROC) (GLenum stream, GLshort x, GLshort y, GLshort z, GLshort w);
+  typedef void (APIENTRYP PFNGLVERTEXSTREAM4SVATIPROC) (GLenum stream, const GLshort *coords);
+  typedef void (APIENTRYP PFNGLVERTEXSTREAM4IATIPROC) (GLenum stream, GLint x, GLint y, GLint z, GLint w);
+  typedef void (APIENTRYP PFNGLVERTEXSTREAM4IVATIPROC) (GLenum stream, const GLint *coords);
+  typedef void (APIENTRYP PFNGLVERTEXSTREAM4FATIPROC) (GLenum stream, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+  typedef void (APIENTRYP PFNGLVERTEXSTREAM4FVATIPROC) (GLenum stream, const GLfloat *coords);
+  typedef void (APIENTRYP PFNGLVERTEXSTREAM4DATIPROC) (GLenum stream, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+  typedef void (APIENTRYP PFNGLVERTEXSTREAM4DVATIPROC) (GLenum stream, const GLdouble *coords);
+  typedef void (APIENTRYP PFNGLNORMALSTREAM3BATIPROC) (GLenum stream, GLbyte nx, GLbyte ny, GLbyte nz);
+  typedef void (APIENTRYP PFNGLNORMALSTREAM3BVATIPROC) (GLenum stream, const GLbyte *coords);
+  typedef void (APIENTRYP PFNGLNORMALSTREAM3SATIPROC) (GLenum stream, GLshort nx, GLshort ny, GLshort nz);
+  typedef void (APIENTRYP PFNGLNORMALSTREAM3SVATIPROC) (GLenum stream, const GLshort *coords);
+  typedef void (APIENTRYP PFNGLNORMALSTREAM3IATIPROC) (GLenum stream, GLint nx, GLint ny, GLint nz);
+  typedef void (APIENTRYP PFNGLNORMALSTREAM3IVATIPROC) (GLenum stream, const GLint *coords);
+  typedef void (APIENTRYP PFNGLNORMALSTREAM3FATIPROC) (GLenum stream, GLfloat nx, GLfloat ny, GLfloat nz);
+  typedef void (APIENTRYP PFNGLNORMALSTREAM3FVATIPROC) (GLenum stream, const GLfloat *coords);
+  typedef void (APIENTRYP PFNGLNORMALSTREAM3DATIPROC) (GLenum stream, GLdouble nx, GLdouble ny, GLdouble nz);
+  typedef void (APIENTRYP PFNGLNORMALSTREAM3DVATIPROC) (GLenum stream, const GLdouble *coords);
+  typedef void (APIENTRYP PFNGLCLIENTACTIVEVERTEXSTREAMATIPROC) (GLenum stream);
+  typedef void (APIENTRYP PFNGLVERTEXBLENDENVIATIPROC) (GLenum pname, GLint param);
+  typedef void (APIENTRYP PFNGLVERTEXBLENDENVFATIPROC) (GLenum pname, GLfloat param);
+#endif
+
+#ifndef GL_ATI_element_array
+#define GL_ATI_element_array 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glElementPointerATI (GLenum, const GLvoid *);
+  GLAPI void APIENTRY glDrawElementArrayATI (GLenum, GLsizei);
+  GLAPI void APIENTRY glDrawRangeElementArrayATI (GLenum, GLuint, GLuint, GLsizei);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLELEMENTPOINTERATIPROC) (GLenum type, const GLvoid *pointer);
+  typedef void (APIENTRYP PFNGLDRAWELEMENTARRAYATIPROC) (GLenum mode, GLsizei count);
+  typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTARRAYATIPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count);
+#endif
+
+#ifndef GL_SUN_mesh_array
+#define GL_SUN_mesh_array 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glDrawMeshArraysSUN (GLenum, GLint, GLsizei, GLsizei);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLDRAWMESHARRAYSSUNPROC) (GLenum mode, GLint first, GLsizei count, GLsizei width);
+#endif
+
+#ifndef GL_SUN_slice_accum
+#define GL_SUN_slice_accum 1
+#endif
+
+#ifndef GL_NV_multisample_filter_hint
+#define GL_NV_multisample_filter_hint 1
+#endif
+
+#ifndef GL_NV_depth_clamp
+#define GL_NV_depth_clamp 1
+#endif
+
+#ifndef GL_NV_occlusion_query
+#define GL_NV_occlusion_query 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glGenOcclusionQueriesNV (GLsizei, GLuint *);
+  GLAPI void APIENTRY glDeleteOcclusionQueriesNV (GLsizei, const GLuint *);
+  GLAPI GLboolean APIENTRY glIsOcclusionQueryNV (GLuint);
+  GLAPI void APIENTRY glBeginOcclusionQueryNV (GLuint);
+  GLAPI void APIENTRY glEndOcclusionQueryNV (void);
+  GLAPI void APIENTRY glGetOcclusionQueryivNV (GLuint, GLenum, GLint *);
+  GLAPI void APIENTRY glGetOcclusionQueryuivNV (GLuint, GLenum, GLuint *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLGENOCCLUSIONQUERIESNVPROC) (GLsizei n, GLuint *ids);
+  typedef void (APIENTRYP PFNGLDELETEOCCLUSIONQUERIESNVPROC) (GLsizei n, const GLuint *ids);
+  typedef GLboolean (APIENTRYP PFNGLISOCCLUSIONQUERYNVPROC) (GLuint id);
+  typedef void (APIENTRYP PFNGLBEGINOCCLUSIONQUERYNVPROC) (GLuint id);
+  typedef void (APIENTRYP PFNGLENDOCCLUSIONQUERYNVPROC) (void);
+  typedef void (APIENTRYP PFNGLGETOCCLUSIONQUERYIVNVPROC) (GLuint id, GLenum pname, GLint *params);
+  typedef void (APIENTRYP PFNGLGETOCCLUSIONQUERYUIVNVPROC) (GLuint id, GLenum pname, GLuint *params);
+#endif
+
+#ifndef GL_NV_point_sprite
+#define GL_NV_point_sprite 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glPointParameteriNV (GLenum, GLint);
+  GLAPI void APIENTRY glPointParameterivNV (GLenum, const GLint *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLPOINTPARAMETERINVPROC) (GLenum pname, GLint param);
+  typedef void (APIENTRYP PFNGLPOINTPARAMETERIVNVPROC) (GLenum pname, const GLint *params);
+#endif
+
+#ifndef GL_NV_texture_shader3
+#define GL_NV_texture_shader3 1
+#endif
+
+#ifndef GL_NV_vertex_program1_1
+#define GL_NV_vertex_program1_1 1
+#endif
+
+#ifndef GL_EXT_shadow_funcs
+#define GL_EXT_shadow_funcs 1
+#endif
+
+#ifndef GL_EXT_stencil_two_side
+#define GL_EXT_stencil_two_side 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glActiveStencilFaceEXT (GLenum);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLACTIVESTENCILFACEEXTPROC) (GLenum face);
+#endif
+
+#ifndef GL_ATI_text_fragment_shader
+#define GL_ATI_text_fragment_shader 1
+#endif
+
+#ifndef GL_APPLE_client_storage
+#define GL_APPLE_client_storage 1
+#endif
+
+#ifndef GL_APPLE_element_array
+#define GL_APPLE_element_array 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glElementPointerAPPLE (GLenum, const GLvoid *);
+  GLAPI void APIENTRY glDrawElementArrayAPPLE (GLenum, GLint, GLsizei);
+  GLAPI void APIENTRY glDrawRangeElementArrayAPPLE (GLenum, GLuint, GLuint, GLint, GLsizei);
+  GLAPI void APIENTRY glMultiDrawElementArrayAPPLE (GLenum, const GLint *, const GLsizei *, GLsizei);
+  GLAPI void APIENTRY glMultiDrawRangeElementArrayAPPLE (GLenum, GLuint, GLuint, const GLint *, const GLsizei *, GLsizei);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLELEMENTPOINTERAPPLEPROC) (GLenum type, const GLvoid *pointer);
+  typedef void (APIENTRYP PFNGLDRAWELEMENTARRAYAPPLEPROC) (GLenum mode, GLint first, GLsizei count);
+  typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTARRAYAPPLEPROC) (GLenum mode, GLuint start, GLuint end, GLint first, GLsizei count);
+  typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTARRAYAPPLEPROC) (GLenum mode, const GLint *first, const GLsizei *count, GLsizei primcount);
+  typedef void (APIENTRYP PFNGLMULTIDRAWRANGEELEMENTARRAYAPPLEPROC) (GLenum mode, GLuint start, GLuint end, const GLint *first, const GLsizei *count, GLsizei primcount);
+#endif
+
+#ifndef GL_APPLE_fence
+#define GL_APPLE_fence 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glGenFencesAPPLE (GLsizei, GLuint *);
+  GLAPI void APIENTRY glDeleteFencesAPPLE (GLsizei, const GLuint *);
+  GLAPI void APIENTRY glSetFenceAPPLE (GLuint);
+  GLAPI GLboolean APIENTRY glIsFenceAPPLE (GLuint);
+  GLAPI GLboolean APIENTRY glTestFenceAPPLE (GLuint);
+  GLAPI void APIENTRY glFinishFenceAPPLE (GLuint);
+  GLAPI GLboolean APIENTRY glTestObjectAPPLE (GLenum, GLuint);
+  GLAPI void APIENTRY glFinishObjectAPPLE (GLenum, GLint);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLGENFENCESAPPLEPROC) (GLsizei n, GLuint *fences);
+  typedef void (APIENTRYP PFNGLDELETEFENCESAPPLEPROC) (GLsizei n, const GLuint *fences);
+  typedef void (APIENTRYP PFNGLSETFENCEAPPLEPROC) (GLuint fence);
+  typedef GLboolean (APIENTRYP PFNGLISFENCEAPPLEPROC) (GLuint fence);
+  typedef GLboolean (APIENTRYP PFNGLTESTFENCEAPPLEPROC) (GLuint fence);
+  typedef void (APIENTRYP PFNGLFINISHFENCEAPPLEPROC) (GLuint fence);
+  typedef GLboolean (APIENTRYP PFNGLTESTOBJECTAPPLEPROC) (GLenum object, GLuint name);
+  typedef void (APIENTRYP PFNGLFINISHOBJECTAPPLEPROC) (GLenum object, GLint name);
+#endif
+
+#ifndef GL_APPLE_vertex_array_object
+#define GL_APPLE_vertex_array_object 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glBindVertexArrayAPPLE (GLuint);
+  GLAPI void APIENTRY glDeleteVertexArraysAPPLE (GLsizei, const GLuint *);
+  GLAPI void APIENTRY glGenVertexArraysAPPLE (GLsizei, const GLuint *);
+  GLAPI GLboolean APIENTRY glIsVertexArrayAPPLE (GLuint);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLBINDVERTEXARRAYAPPLEPROC) (GLuint array);
+  typedef void (APIENTRYP PFNGLDELETEVERTEXARRAYSAPPLEPROC) (GLsizei n, const GLuint *arrays);
+  typedef void (APIENTRYP PFNGLGENVERTEXARRAYSAPPLEPROC) (GLsizei n, const GLuint *arrays);
+  typedef GLboolean (APIENTRYP PFNGLISVERTEXARRAYAPPLEPROC) (GLuint array);
+#endif
+
+#ifndef GL_APPLE_vertex_array_range
+#define GL_APPLE_vertex_array_range 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glVertexArrayRangeAPPLE (GLsizei, GLvoid *);
+  GLAPI void APIENTRY glFlushVertexArrayRangeAPPLE (GLsizei, GLvoid *);
+  GLAPI void APIENTRY glVertexArrayParameteriAPPLE (GLenum, GLint);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLVERTEXARRAYRANGEAPPLEPROC) (GLsizei length, GLvoid *pointer);
+  typedef void (APIENTRYP PFNGLFLUSHVERTEXARRAYRANGEAPPLEPROC) (GLsizei length, GLvoid *pointer);
+  typedef void (APIENTRYP PFNGLVERTEXARRAYPARAMETERIAPPLEPROC) (GLenum pname, GLint param);
+#endif
+
+#ifndef GL_APPLE_ycbcr_422
+#define GL_APPLE_ycbcr_422 1
+#endif
+
+#ifndef GL_S3_s3tc
+#define GL_S3_s3tc 1
+#endif
+
+#ifndef GL_ATI_draw_buffers
+#define GL_ATI_draw_buffers 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glDrawBuffersATI (GLsizei, const GLenum *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLDRAWBUFFERSATIPROC) (GLsizei n, const GLenum *bufs);
+#endif
+
+#ifndef GL_ATI_pixel_format_float
+#define GL_ATI_pixel_format_float 1
+  /* This is really a WGL extension, but defines some associated GL enums.
+   * ATI does not export "GL_ATI_pixel_format_float" in the GL_EXTENSIONS string.
+   */
+#endif
+
+#ifndef GL_ATI_texture_env_combine3
+#define GL_ATI_texture_env_combine3 1
+#endif
+
+#ifndef GL_ATI_texture_float
+#define GL_ATI_texture_float 1
+#endif
+
+#ifndef GL_NV_float_buffer
+#define GL_NV_float_buffer 1
+#endif
+
+#ifndef GL_NV_fragment_program
+#define GL_NV_fragment_program 1
+  /* Some NV_fragment_program entry points are shared with ARB_vertex_program. */
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glProgramNamedParameter4fNV (GLuint, GLsizei, const GLubyte *, GLfloat, GLfloat, GLfloat, GLfloat);
+  GLAPI void APIENTRY glProgramNamedParameter4dNV (GLuint, GLsizei, const GLubyte *, GLdouble, GLdouble, GLdouble, GLdouble);
+  GLAPI void APIENTRY glProgramNamedParameter4fvNV (GLuint, GLsizei, const GLubyte *, const GLfloat *);
+  GLAPI void APIENTRY glProgramNamedParameter4dvNV (GLuint, GLsizei, const GLubyte *, const GLdouble *);
+  GLAPI void APIENTRY glGetProgramNamedParameterfvNV (GLuint, GLsizei, const GLubyte *, GLfloat *);
+  GLAPI void APIENTRY glGetProgramNamedParameterdvNV (GLuint, GLsizei, const GLubyte *, GLdouble *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLPROGRAMNAMEDPARAMETER4FNVPROC) (GLuint id, GLsizei len, const GLubyte *name, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+  typedef void (APIENTRYP PFNGLPROGRAMNAMEDPARAMETER4DNVPROC) (GLuint id, GLsizei len, const GLubyte *name, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+  typedef void (APIENTRYP PFNGLPROGRAMNAMEDPARAMETER4FVNVPROC) (GLuint id, GLsizei len, const GLubyte *name, const GLfloat *v);
+  typedef void (APIENTRYP PFNGLPROGRAMNAMEDPARAMETER4DVNVPROC) (GLuint id, GLsizei len, const GLubyte *name, const GLdouble *v);
+  typedef void (APIENTRYP PFNGLGETPROGRAMNAMEDPARAMETERFVNVPROC) (GLuint id, GLsizei len, const GLubyte *name, GLfloat *params);
+  typedef void (APIENTRYP PFNGLGETPROGRAMNAMEDPARAMETERDVNVPROC) (GLuint id, GLsizei len, const GLubyte *name, GLdouble *params);
+#endif
+
+#ifndef GL_NV_half_float
+#define GL_NV_half_float 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glVertex2hNV (GLhalfNV, GLhalfNV);
+  GLAPI void APIENTRY glVertex2hvNV (const GLhalfNV *);
+  GLAPI void APIENTRY glVertex3hNV (GLhalfNV, GLhalfNV, GLhalfNV);
+  GLAPI void APIENTRY glVertex3hvNV (const GLhalfNV *);
+  GLAPI void APIENTRY glVertex4hNV (GLhalfNV, GLhalfNV, GLhalfNV, GLhalfNV);
+  GLAPI void APIENTRY glVertex4hvNV (const GLhalfNV *);
+  GLAPI void APIENTRY glNormal3hNV (GLhalfNV, GLhalfNV, GLhalfNV);
+  GLAPI void APIENTRY glNormal3hvNV (const GLhalfNV *);
+  GLAPI void APIENTRY glColor3hNV (GLhalfNV, GLhalfNV, GLhalfNV);
+  GLAPI void APIENTRY glColor3hvNV (const GLhalfNV *);
+  GLAPI void APIENTRY glColor4hNV (GLhalfNV, GLhalfNV, GLhalfNV, GLhalfNV);
+  GLAPI void APIENTRY glColor4hvNV (const GLhalfNV *);
+  GLAPI void APIENTRY glTexCoord1hNV (GLhalfNV);
+  GLAPI void APIENTRY glTexCoord1hvNV (const GLhalfNV *);
+  GLAPI void APIENTRY glTexCoord2hNV (GLhalfNV, GLhalfNV);
+  GLAPI void APIENTRY glTexCoord2hvNV (const GLhalfNV *);
+  GLAPI void APIENTRY glTexCoord3hNV (GLhalfNV, GLhalfNV, GLhalfNV);
+  GLAPI void APIENTRY glTexCoord3hvNV (const GLhalfNV *);
+  GLAPI void APIENTRY glTexCoord4hNV (GLhalfNV, GLhalfNV, GLhalfNV, GLhalfNV);
+  GLAPI void APIENTRY glTexCoord4hvNV (const GLhalfNV *);
+  GLAPI void APIENTRY glMultiTexCoord1hNV (GLenum, GLhalfNV);
+  GLAPI void APIENTRY glMultiTexCoord1hvNV (GLenum, const GLhalfNV *);
+  GLAPI void APIENTRY glMultiTexCoord2hNV (GLenum, GLhalfNV, GLhalfNV);
+  GLAPI void APIENTRY glMultiTexCoord2hvNV (GLenum, const GLhalfNV *);
+  GLAPI void APIENTRY glMultiTexCoord3hNV (GLenum, GLhalfNV, GLhalfNV, GLhalfNV);
+  GLAPI void APIENTRY glMultiTexCoord3hvNV (GLenum, const GLhalfNV *);
+  GLAPI void APIENTRY glMultiTexCoord4hNV (GLenum, GLhalfNV, GLhalfNV, GLhalfNV, GLhalfNV);
+  GLAPI void APIENTRY glMultiTexCoord4hvNV (GLenum, const GLhalfNV *);
+  GLAPI void APIENTRY glFogCoordhNV (GLhalfNV);
+  GLAPI void APIENTRY glFogCoordhvNV (const GLhalfNV *);
+  GLAPI void APIENTRY glSecondaryColor3hNV (GLhalfNV, GLhalfNV, GLhalfNV);
+  GLAPI void APIENTRY glSecondaryColor3hvNV (const GLhalfNV *);
+  GLAPI void APIENTRY glVertexWeighthNV (GLhalfNV);
+  GLAPI void APIENTRY glVertexWeighthvNV (const GLhalfNV *);
+  GLAPI void APIENTRY glVertexAttrib1hNV (GLuint, GLhalfNV);
+  GLAPI void APIENTRY glVertexAttrib1hvNV (GLuint, const GLhalfNV *);
+  GLAPI void APIENTRY glVertexAttrib2hNV (GLuint, GLhalfNV, GLhalfNV);
+  GLAPI void APIENTRY glVertexAttrib2hvNV (GLuint, const GLhalfNV *);
+  GLAPI void APIENTRY glVertexAttrib3hNV (GLuint, GLhalfNV, GLhalfNV, GLhalfNV);
+  GLAPI void APIENTRY glVertexAttrib3hvNV (GLuint, const GLhalfNV *);
+  GLAPI void APIENTRY glVertexAttrib4hNV (GLuint, GLhalfNV, GLhalfNV, GLhalfNV, GLhalfNV);
+  GLAPI void APIENTRY glVertexAttrib4hvNV (GLuint, const GLhalfNV *);
+  GLAPI void APIENTRY glVertexAttribs1hvNV (GLuint, GLsizei, const GLhalfNV *);
+  GLAPI void APIENTRY glVertexAttribs2hvNV (GLuint, GLsizei, const GLhalfNV *);
+  GLAPI void APIENTRY glVertexAttribs3hvNV (GLuint, GLsizei, const GLhalfNV *);
+  GLAPI void APIENTRY glVertexAttribs4hvNV (GLuint, GLsizei, const GLhalfNV *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLVERTEX2HNVPROC) (GLhalfNV x, GLhalfNV y);
+  typedef void (APIENTRYP PFNGLVERTEX2HVNVPROC) (const GLhalfNV *v);
+  typedef void (APIENTRYP PFNGLVERTEX3HNVPROC) (GLhalfNV x, GLhalfNV y, GLhalfNV z);
+  typedef void (APIENTRYP PFNGLVERTEX3HVNVPROC) (const GLhalfNV *v);
+  typedef void (APIENTRYP PFNGLVERTEX4HNVPROC) (GLhalfNV x, GLhalfNV y, GLhalfNV z, GLhalfNV w);
+  typedef void (APIENTRYP PFNGLVERTEX4HVNVPROC) (const GLhalfNV *v);
+  typedef void (APIENTRYP PFNGLNORMAL3HNVPROC) (GLhalfNV nx, GLhalfNV ny, GLhalfNV nz);
+  typedef void (APIENTRYP PFNGLNORMAL3HVNVPROC) (const GLhalfNV *v);
+  typedef void (APIENTRYP PFNGLCOLOR3HNVPROC) (GLhalfNV red, GLhalfNV green, GLhalfNV blue);
+  typedef void (APIENTRYP PFNGLCOLOR3HVNVPROC) (const GLhalfNV *v);
+  typedef void (APIENTRYP PFNGLCOLOR4HNVPROC) (GLhalfNV red, GLhalfNV green, GLhalfNV blue, GLhalfNV alpha);
+  typedef void (APIENTRYP PFNGLCOLOR4HVNVPROC) (const GLhalfNV *v);
+  typedef void (APIENTRYP PFNGLTEXCOORD1HNVPROC) (GLhalfNV s);
+  typedef void (APIENTRYP PFNGLTEXCOORD1HVNVPROC) (const GLhalfNV *v);
+  typedef void (APIENTRYP PFNGLTEXCOORD2HNVPROC) (GLhalfNV s, GLhalfNV t);
+  typedef void (APIENTRYP PFNGLTEXCOORD2HVNVPROC) (const GLhalfNV *v);
+  typedef void (APIENTRYP PFNGLTEXCOORD3HNVPROC) (GLhalfNV s, GLhalfNV t, GLhalfNV r);
+  typedef void (APIENTRYP PFNGLTEXCOORD3HVNVPROC) (const GLhalfNV *v);
+  typedef void (APIENTRYP PFNGLTEXCOORD4HNVPROC) (GLhalfNV s, GLhalfNV t, GLhalfNV r, GLhalfNV q);
+  typedef void (APIENTRYP PFNGLTEXCOORD4HVNVPROC) (const GLhalfNV *v);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD1HNVPROC) (GLenum target, GLhalfNV s);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD1HVNVPROC) (GLenum target, const GLhalfNV *v);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD2HNVPROC) (GLenum target, GLhalfNV s, GLhalfNV t);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD2HVNVPROC) (GLenum target, const GLhalfNV *v);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD3HNVPROC) (GLenum target, GLhalfNV s, GLhalfNV t, GLhalfNV r);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD3HVNVPROC) (GLenum target, const GLhalfNV *v);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD4HNVPROC) (GLenum target, GLhalfNV s, GLhalfNV t, GLhalfNV r, GLhalfNV q);
+  typedef void (APIENTRYP PFNGLMULTITEXCOORD4HVNVPROC) (GLenum target, const GLhalfNV *v);
+  typedef void (APIENTRYP PFNGLFOGCOORDHNVPROC) (GLhalfNV fog);
+  typedef void (APIENTRYP PFNGLFOGCOORDHVNVPROC) (const GLhalfNV *fog);
+  typedef void (APIENTRYP PFNGLSECONDARYCOLOR3HNVPROC) (GLhalfNV red, GLhalfNV green, GLhalfNV blue);
+  typedef void (APIENTRYP PFNGLSECONDARYCOLOR3HVNVPROC) (const GLhalfNV *v);
+  typedef void (APIENTRYP PFNGLVERTEXWEIGHTHNVPROC) (GLhalfNV weight);
+  typedef void (APIENTRYP PFNGLVERTEXWEIGHTHVNVPROC) (const GLhalfNV *weight);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB1HNVPROC) (GLuint index, GLhalfNV x);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB1HVNVPROC) (GLuint index, const GLhalfNV *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB2HNVPROC) (GLuint index, GLhalfNV x, GLhalfNV y);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB2HVNVPROC) (GLuint index, const GLhalfNV *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB3HNVPROC) (GLuint index, GLhalfNV x, GLhalfNV y, GLhalfNV z);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB3HVNVPROC) (GLuint index, const GLhalfNV *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB4HNVPROC) (GLuint index, GLhalfNV x, GLhalfNV y, GLhalfNV z, GLhalfNV w);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIB4HVNVPROC) (GLuint index, const GLhalfNV *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIBS1HVNVPROC) (GLuint index, GLsizei n, const GLhalfNV *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIBS2HVNVPROC) (GLuint index, GLsizei n, const GLhalfNV *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIBS3HVNVPROC) (GLuint index, GLsizei n, const GLhalfNV *v);
+  typedef void (APIENTRYP PFNGLVERTEXATTRIBS4HVNVPROC) (GLuint index, GLsizei n, const GLhalfNV *v);
+#endif
+
+#ifndef GL_NV_pixel_data_range
+#define GL_NV_pixel_data_range 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glPixelDataRangeNV (GLenum, GLsizei, GLvoid *);
+  GLAPI void APIENTRY glFlushPixelDataRangeNV (GLenum);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLPIXELDATARANGENVPROC) (GLenum target, GLsizei length, GLvoid *pointer);
+  typedef void (APIENTRYP PFNGLFLUSHPIXELDATARANGENVPROC) (GLenum target);
+#endif
+
+#ifndef GL_NV_primitive_restart
+#define GL_NV_primitive_restart 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glPrimitiveRestartNV (void);
+  GLAPI void APIENTRY glPrimitiveRestartIndexNV (GLuint);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLPRIMITIVERESTARTNVPROC) (void);
+  typedef void (APIENTRYP PFNGLPRIMITIVERESTARTINDEXNVPROC) (GLuint index);
+#endif
+
+#ifndef GL_NV_texture_expand_normal
+#define GL_NV_texture_expand_normal 1
+#endif
+
+#ifndef GL_NV_vertex_program2
+#define GL_NV_vertex_program2 1
+#endif
+
+#ifndef GL_ATI_map_object_buffer
+#define GL_ATI_map_object_buffer 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI GLvoid* APIENTRY glMapObjectBufferATI (GLuint);
+  GLAPI void APIENTRY glUnmapObjectBufferATI (GLuint);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef GLvoid* (APIENTRYP PFNGLMAPOBJECTBUFFERATIPROC) (GLuint buffer);
+  typedef void (APIENTRYP PFNGLUNMAPOBJECTBUFFERATIPROC) (GLuint buffer);
+#endif
+
+#ifndef GL_ATI_separate_stencil
+#define GL_ATI_separate_stencil 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glStencilOpSeparateATI (GLenum, GLenum, GLenum, GLenum);
+  GLAPI void APIENTRY glStencilFuncSeparateATI (GLenum, GLenum, GLint, GLuint);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLSTENCILOPSEPARATEATIPROC) (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass);
+  typedef void (APIENTRYP PFNGLSTENCILFUNCSEPARATEATIPROC) (GLenum frontfunc, GLenum backfunc, GLint ref, GLuint mask);
+#endif
+
+#ifndef GL_ATI_vertex_attrib_array_object
+#define GL_ATI_vertex_attrib_array_object 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glVertexAttribArrayObjectATI (GLuint, GLint, GLenum, GLboolean, GLsizei, GLuint, GLuint);
+  GLAPI void APIENTRY glGetVertexAttribArrayObjectfvATI (GLuint, GLenum, GLfloat *);
+  GLAPI void APIENTRY glGetVertexAttribArrayObjectivATI (GLuint, GLenum, GLint *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLVERTEXATTRIBARRAYOBJECTATIPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, GLuint buffer, GLuint offset);
+  typedef void (APIENTRYP PFNGLGETVERTEXATTRIBARRAYOBJECTFVATIPROC) (GLuint index, GLenum pname, GLfloat *params);
+  typedef void (APIENTRYP PFNGLGETVERTEXATTRIBARRAYOBJECTIVATIPROC) (GLuint index, GLenum pname, GLint *params);
+#endif
+
+#ifndef GL_OES_read_format
+#define GL_OES_read_format 1
+#endif
+
+#ifndef GL_EXT_depth_bounds_test
+#define GL_EXT_depth_bounds_test 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glDepthBoundsEXT (GLclampd, GLclampd);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLDEPTHBOUNDSEXTPROC) (GLclampd zmin, GLclampd zmax);
+#endif
+
+#ifndef GL_EXT_texture_mirror_clamp
+#define GL_EXT_texture_mirror_clamp 1
+#endif
+
+#ifndef GL_EXT_blend_equation_separate
+#define GL_EXT_blend_equation_separate 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glBlendEquationSeparateEXT (GLenum, GLenum);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEEXTPROC) (GLenum modeRGB, GLenum modeAlpha);
+#endif
+
+#ifndef GL_MESA_pack_invert
+#define GL_MESA_pack_invert 1
+#endif
+
+#ifndef GL_MESA_ycbcr_texture
+#define GL_MESA_ycbcr_texture 1
+#endif
+
+#ifndef GL_EXT_pixel_buffer_object
+#define GL_EXT_pixel_buffer_object 1
+#endif
+
+#ifndef GL_NV_fragment_program_option
+#define GL_NV_fragment_program_option 1
+#endif
+
+#ifndef GL_NV_fragment_program2
+#define GL_NV_fragment_program2 1
+#endif
+
+#ifndef GL_NV_vertex_program2_option
+#define GL_NV_vertex_program2_option 1
+#endif
+
+#ifndef GL_NV_vertex_program3
+#define GL_NV_vertex_program3 1
+#endif
+
+#ifndef GL_EXT_framebuffer_object
+#define GL_EXT_framebuffer_object 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI GLboolean APIENTRY glIsRenderbufferEXT (GLuint);
+  GLAPI void APIENTRY glBindRenderbufferEXT (GLenum, GLuint);
+  GLAPI void APIENTRY glDeleteRenderbuffersEXT (GLsizei, const GLuint *);
+  GLAPI void APIENTRY glGenRenderbuffersEXT (GLsizei, GLuint *);
+  GLAPI void APIENTRY glRenderbufferStorageEXT (GLenum, GLenum, GLsizei, GLsizei);
+  GLAPI void APIENTRY glGetRenderbufferParameterivEXT (GLenum, GLenum, GLint *);
+  GLAPI GLboolean APIENTRY glIsFramebufferEXT (GLuint);
+  GLAPI void APIENTRY glBindFramebufferEXT (GLenum, GLuint);
+  GLAPI void APIENTRY glDeleteFramebuffersEXT (GLsizei, const GLuint *);
+  GLAPI void APIENTRY glGenFramebuffersEXT (GLsizei, GLuint *);
+  GLAPI GLenum APIENTRY glCheckFramebufferStatusEXT (GLenum);
+  GLAPI void APIENTRY glFramebufferTexture1DEXT (GLenum, GLenum, GLenum, GLuint, GLint);
+  GLAPI void APIENTRY glFramebufferTexture2DEXT (GLenum, GLenum, GLenum, GLuint, GLint);
+  GLAPI void APIENTRY glFramebufferTexture3DEXT (GLenum, GLenum, GLenum, GLuint, GLint, GLint);
+  GLAPI void APIENTRY glFramebufferRenderbufferEXT (GLenum, GLenum, GLenum, GLuint);
+  GLAPI void APIENTRY glGetFramebufferAttachmentParameterivEXT (GLenum, GLenum, GLenum, GLint *);
+  GLAPI void APIENTRY glGenerateMipmapEXT (GLenum);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef GLboolean (APIENTRYP PFNGLISRENDERBUFFEREXTPROC) (GLuint renderbuffer);
+  typedef void (APIENTRYP PFNGLBINDRENDERBUFFEREXTPROC) (GLenum target, GLuint renderbuffer);
+  typedef void (APIENTRYP PFNGLDELETERENDERBUFFERSEXTPROC) (GLsizei n, const GLuint *renderbuffers);
+  typedef void (APIENTRYP PFNGLGENRENDERBUFFERSEXTPROC) (GLsizei n, GLuint *renderbuffers);
+  typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEEXTPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height);
+  typedef void (APIENTRYP PFNGLGETRENDERBUFFERPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params);
+  typedef GLboolean (APIENTRYP PFNGLISFRAMEBUFFEREXTPROC) (GLuint framebuffer);
+  typedef void (APIENTRYP PFNGLBINDFRAMEBUFFEREXTPROC) (GLenum target, GLuint framebuffer);
+  typedef void (APIENTRYP PFNGLDELETEFRAMEBUFFERSEXTPROC) (GLsizei n, const GLuint *framebuffers);
+  typedef void (APIENTRYP PFNGLGENFRAMEBUFFERSEXTPROC) (GLsizei n, GLuint *framebuffers);
+  typedef GLenum (APIENTRYP PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC) (GLenum target);
+  typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE1DEXTPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
+  typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE2DEXTPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
+  typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE3DEXTPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset);
+  typedef void (APIENTRYP PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC) (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer);
+  typedef void (APIENTRYP PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVEXTPROC) (GLenum target, GLenum attachment, GLenum pname, GLint *params);
+  typedef void (APIENTRYP PFNGLGENERATEMIPMAPEXTPROC) (GLenum target);
+#endif
+
+#ifndef GL_GREMEDY_string_marker
+#define GL_GREMEDY_string_marker 1
+#ifdef GL_GLEXT_PROTOTYPES
+  GLAPI void APIENTRY glStringMarkerGREMEDY (GLsizei, const GLvoid *);
+#endif /* GL_GLEXT_PROTOTYPES */
+  typedef void (APIENTRYP PFNGLSTRINGMARKERGREMEDYPROC) (GLsizei len, const GLvoid *string);
+#endif
+
+#ifndef GL_EXT_Cg_shader
+#define GL_EXT_Cg_shader 1
+#endif
+
+#ifndef GL_NV_element_array
+#define GL_NV_element_array 1
+#ifdef GL_GLEXT_PROTOTYPES
+  extern void APIENTRY glElementPointerNV(GLenum type, const GLvoid *pointer);
+  extern void APIENTRY glDrawElementArrayNV(GLenum mode, GLint first, GLsizei count);
+  extern void APIENTRY glDrawRangeElementArrayNV(GLenum mode, GLuint start, GLuint end, GLint first, GLsizei count);
+  extern void APIENTRY glMultiDrawElementArrayNV(GLenum mode, const GLint *first, const GLsizei *count, GLsizei primcount);
+  extern void APIENTRY glMultiDrawRangeElementArrayNV(GLenum mode, GLuint start, GLuint end, const GLint *first, const GLsizei *count, GLsizei primcount);
+#endif
+  typedef void (APIENTRY * PFNGLELEMENTPOINTERNVPROC) (GLenum type, const GLvoid *pointer);
+  typedef void (APIENTRY * PFNGLDRAWELEMENTARRAYNVPROC) (GLenum mode, GLint first, GLsizei count);
+  typedef void (APIENTRY * PFNGLDRAWRANGEELEMENTARRAYNVPROC) (GLenum mode, GLuint start, GLuint end, GLint first, GLsizei count);
+  typedef void (APIENTRY * PFNGLMULTIDRAWELEMENTARRAYNVPROC) (GLenum mode, const GLint *first, const GLsizei *count, GLsizei primcount);
+  typedef void (APIENTRY * PFNGLMULTIDRAWRANGEELEMENTARRAYNVPROC) (GLenum mode, GLuint start, GLuint end, const GLint *first, const GLsizei *count, GLsizei primcount);
+#endif
+
+#ifndef GL_NV_pixel_buffer_object
+#define GL_NV_pixel_buffer_object 1
+#endif
+
+#ifndef GL_NV_stencil_two_side
+#define GL_NV_stencil_two_side 1
+#ifdef GL_GLEXT_PROTOTYPES
+  extern void APIENTRY glActiveStencilFaceNV(GLenum face);
+#endif
+  typedef void (APIENTRY * PFNGLACTIVESTENCILFACENVPROC) (GLenum face);
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/opengl/wglext.h b/opengl/wglext.h
index 3024f7a..413cbde 100644
--- a/opengl/wglext.h
+++ b/opengl/wglext.h
@@ -1,662 +1,662 @@
-#ifndef __wglext_h_
-#define __wglext_h_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/*
-** License Applicability. Except to the extent portions of this file are
-** made subject to an alternative license as permitted in the SGI Free
-** Software License B, Version 1.1 (the "License"), the contents of this
-** file are subject only to the provisions of the License. You may not use
-** this file except in compliance with the License. You may obtain a copy
-** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
-** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
-** 
-** http://oss.sgi.com/projects/FreeB
-** 
-** Note that, as provided in the License, the Software is distributed on an
-** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
-** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
-** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
-** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
-** 
-** Original Code. The Original Code is: OpenGL Sample Implementation,
-** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
-** Inc. The Original Code is Copyright (c) 1991-2004 Silicon Graphics, Inc.
-** Copyright in any portions created by third parties is as indicated
-** elsewhere herein. All Rights Reserved.
-** 
-** Additional Notice Provisions: This software was created using the
-** OpenGL(R) version 1.2.1 Sample Implementation published by SGI, but has
-** not been independently verified as being compliant with the OpenGL(R)
-** version 1.2.1 Specification.
-*/
-
-#if defined(_WIN32) && !defined(APIENTRY) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__)
-#define WIN32_LEAN_AND_MEAN 1
-#include <windows.h>
-#endif
-
-#ifndef APIENTRY
-#define APIENTRY
-#endif
-#ifndef APIENTRYP
-#define APIENTRYP APIENTRY *
-#endif
-#ifndef GLAPI
-#define GLAPI extern
-#endif
-
-/*************************************************************/
-
-/* Header file version number */
-/* wglext.h last updated 2005/01/07 */
-/* Current version at http://oss.sgi.com/projects/ogl-sample/registry/ */
-#define WGL_WGLEXT_VERSION 6
-
-#ifndef WGL_ARB_buffer_region
-#define WGL_FRONT_COLOR_BUFFER_BIT_ARB 0x00000001
-#define WGL_BACK_COLOR_BUFFER_BIT_ARB  0x00000002
-#define WGL_DEPTH_BUFFER_BIT_ARB       0x00000004
-#define WGL_STENCIL_BUFFER_BIT_ARB     0x00000008
-#endif
-
-#ifndef WGL_ARB_multisample
-#define WGL_SAMPLE_BUFFERS_ARB         0x2041
-#define WGL_SAMPLES_ARB                0x2042
-#endif
-
-#ifndef WGL_ARB_extensions_string
-#endif
-
-#ifndef WGL_ARB_pixel_format
-#define WGL_NUMBER_PIXEL_FORMATS_ARB   0x2000
-#define WGL_DRAW_TO_WINDOW_ARB         0x2001
-#define WGL_DRAW_TO_BITMAP_ARB         0x2002
-#define WGL_ACCELERATION_ARB           0x2003
-#define WGL_NEED_PALETTE_ARB           0x2004
-#define WGL_NEED_SYSTEM_PALETTE_ARB    0x2005
-#define WGL_SWAP_LAYER_BUFFERS_ARB     0x2006
-#define WGL_SWAP_METHOD_ARB            0x2007
-#define WGL_NUMBER_OVERLAYS_ARB        0x2008
-#define WGL_NUMBER_UNDERLAYS_ARB       0x2009
-#define WGL_TRANSPARENT_ARB            0x200A
-#define WGL_TRANSPARENT_RED_VALUE_ARB  0x2037
-#define WGL_TRANSPARENT_GREEN_VALUE_ARB 0x2038
-#define WGL_TRANSPARENT_BLUE_VALUE_ARB 0x2039
-#define WGL_TRANSPARENT_ALPHA_VALUE_ARB 0x203A
-#define WGL_TRANSPARENT_INDEX_VALUE_ARB 0x203B
-#define WGL_SHARE_DEPTH_ARB            0x200C
-#define WGL_SHARE_STENCIL_ARB          0x200D
-#define WGL_SHARE_ACCUM_ARB            0x200E
-#define WGL_SUPPORT_GDI_ARB            0x200F
-#define WGL_SUPPORT_OPENGL_ARB         0x2010
-#define WGL_DOUBLE_BUFFER_ARB          0x2011
-#define WGL_STEREO_ARB                 0x2012
-#define WGL_PIXEL_TYPE_ARB             0x2013
-#define WGL_COLOR_BITS_ARB             0x2014
-#define WGL_RED_BITS_ARB               0x2015
-#define WGL_RED_SHIFT_ARB              0x2016
-#define WGL_GREEN_BITS_ARB             0x2017
-#define WGL_GREEN_SHIFT_ARB            0x2018
-#define WGL_BLUE_BITS_ARB              0x2019
-#define WGL_BLUE_SHIFT_ARB             0x201A
-#define WGL_ALPHA_BITS_ARB             0x201B
-#define WGL_ALPHA_SHIFT_ARB            0x201C
-#define WGL_ACCUM_BITS_ARB             0x201D
-#define WGL_ACCUM_RED_BITS_ARB         0x201E
-#define WGL_ACCUM_GREEN_BITS_ARB       0x201F
-#define WGL_ACCUM_BLUE_BITS_ARB        0x2020
-#define WGL_ACCUM_ALPHA_BITS_ARB       0x2021
-#define WGL_DEPTH_BITS_ARB             0x2022
-#define WGL_STENCIL_BITS_ARB           0x2023
-#define WGL_AUX_BUFFERS_ARB            0x2024
-#define WGL_NO_ACCELERATION_ARB        0x2025
-#define WGL_GENERIC_ACCELERATION_ARB   0x2026
-#define WGL_FULL_ACCELERATION_ARB      0x2027
-#define WGL_SWAP_EXCHANGE_ARB          0x2028
-#define WGL_SWAP_COPY_ARB              0x2029
-#define WGL_SWAP_UNDEFINED_ARB         0x202A
-#define WGL_TYPE_RGBA_ARB              0x202B
-#define WGL_TYPE_COLORINDEX_ARB        0x202C
-#endif
-
-#ifndef WGL_ARB_make_current_read
-#define ERROR_INVALID_PIXEL_TYPE_ARB   0x2043
-#define ERROR_INCOMPATIBLE_DEVICE_CONTEXTS_ARB 0x2054
-#endif
-
-#ifndef WGL_ARB_pbuffer
-#define WGL_DRAW_TO_PBUFFER_ARB        0x202D
-#define WGL_MAX_PBUFFER_PIXELS_ARB     0x202E
-#define WGL_MAX_PBUFFER_WIDTH_ARB      0x202F
-#define WGL_MAX_PBUFFER_HEIGHT_ARB     0x2030
-#define WGL_PBUFFER_LARGEST_ARB        0x2033
-#define WGL_PBUFFER_WIDTH_ARB          0x2034
-#define WGL_PBUFFER_HEIGHT_ARB         0x2035
-#define WGL_PBUFFER_LOST_ARB           0x2036
-#endif
-
-#ifndef WGL_ARB_render_texture
-#define WGL_BIND_TO_TEXTURE_RGB_ARB    0x2070
-#define WGL_BIND_TO_TEXTURE_RGBA_ARB   0x2071
-#define WGL_TEXTURE_FORMAT_ARB         0x2072
-#define WGL_TEXTURE_TARGET_ARB         0x2073
-#define WGL_MIPMAP_TEXTURE_ARB         0x2074
-#define WGL_TEXTURE_RGB_ARB            0x2075
-#define WGL_TEXTURE_RGBA_ARB           0x2076
-#define WGL_NO_TEXTURE_ARB             0x2077
-#define WGL_TEXTURE_CUBE_MAP_ARB       0x2078
-#define WGL_TEXTURE_1D_ARB             0x2079
-#define WGL_TEXTURE_2D_ARB             0x207A
-#define WGL_MIPMAP_LEVEL_ARB           0x207B
-#define WGL_CUBE_MAP_FACE_ARB          0x207C
-#define WGL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB 0x207D
-#define WGL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB 0x207E
-#define WGL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB 0x207F
-#define WGL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB 0x2080
-#define WGL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB 0x2081
-#define WGL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB 0x2082
-#define WGL_FRONT_LEFT_ARB             0x2083
-#define WGL_FRONT_RIGHT_ARB            0x2084
-#define WGL_BACK_LEFT_ARB              0x2085
-#define WGL_BACK_RIGHT_ARB             0x2086
-#define WGL_AUX0_ARB                   0x2087
-#define WGL_AUX1_ARB                   0x2088
-#define WGL_AUX2_ARB                   0x2089
-#define WGL_AUX3_ARB                   0x208A
-#define WGL_AUX4_ARB                   0x208B
-#define WGL_AUX5_ARB                   0x208C
-#define WGL_AUX6_ARB                   0x208D
-#define WGL_AUX7_ARB                   0x208E
-#define WGL_AUX8_ARB                   0x208F
-#define WGL_AUX9_ARB                   0x2090
-#endif
-
-#ifndef WGL_ARB_pixel_format_float
-#define WGL_TYPE_RGBA_FLOAT_ARB        0x21A0
-#endif
-
-#ifndef WGL_EXT_make_current_read
-#define ERROR_INVALID_PIXEL_TYPE_EXT   0x2043
-#endif
-
-#ifndef WGL_EXT_pixel_format
-#define WGL_NUMBER_PIXEL_FORMATS_EXT   0x2000
-#define WGL_DRAW_TO_WINDOW_EXT         0x2001
-#define WGL_DRAW_TO_BITMAP_EXT         0x2002
-#define WGL_ACCELERATION_EXT           0x2003
-#define WGL_NEED_PALETTE_EXT           0x2004
-#define WGL_NEED_SYSTEM_PALETTE_EXT    0x2005
-#define WGL_SWAP_LAYER_BUFFERS_EXT     0x2006
-#define WGL_SWAP_METHOD_EXT            0x2007
-#define WGL_NUMBER_OVERLAYS_EXT        0x2008
-#define WGL_NUMBER_UNDERLAYS_EXT       0x2009
-#define WGL_TRANSPARENT_EXT            0x200A
-#define WGL_TRANSPARENT_VALUE_EXT      0x200B
-#define WGL_SHARE_DEPTH_EXT            0x200C
-#define WGL_SHARE_STENCIL_EXT          0x200D
-#define WGL_SHARE_ACCUM_EXT            0x200E
-#define WGL_SUPPORT_GDI_EXT            0x200F
-#define WGL_SUPPORT_OPENGL_EXT         0x2010
-#define WGL_DOUBLE_BUFFER_EXT          0x2011
-#define WGL_STEREO_EXT                 0x2012
-#define WGL_PIXEL_TYPE_EXT             0x2013
-#define WGL_COLOR_BITS_EXT             0x2014
-#define WGL_RED_BITS_EXT               0x2015
-#define WGL_RED_SHIFT_EXT              0x2016
-#define WGL_GREEN_BITS_EXT             0x2017
-#define WGL_GREEN_SHIFT_EXT            0x2018
-#define WGL_BLUE_BITS_EXT              0x2019
-#define WGL_BLUE_SHIFT_EXT             0x201A
-#define WGL_ALPHA_BITS_EXT             0x201B
-#define WGL_ALPHA_SHIFT_EXT            0x201C
-#define WGL_ACCUM_BITS_EXT             0x201D
-#define WGL_ACCUM_RED_BITS_EXT         0x201E
-#define WGL_ACCUM_GREEN_BITS_EXT       0x201F
-#define WGL_ACCUM_BLUE_BITS_EXT        0x2020
-#define WGL_ACCUM_ALPHA_BITS_EXT       0x2021
-#define WGL_DEPTH_BITS_EXT             0x2022
-#define WGL_STENCIL_BITS_EXT           0x2023
-#define WGL_AUX_BUFFERS_EXT            0x2024
-#define WGL_NO_ACCELERATION_EXT        0x2025
-#define WGL_GENERIC_ACCELERATION_EXT   0x2026
-#define WGL_FULL_ACCELERATION_EXT      0x2027
-#define WGL_SWAP_EXCHANGE_EXT          0x2028
-#define WGL_SWAP_COPY_EXT              0x2029
-#define WGL_SWAP_UNDEFINED_EXT         0x202A
-#define WGL_TYPE_RGBA_EXT              0x202B
-#define WGL_TYPE_COLORINDEX_EXT        0x202C
-#endif
-
-#ifndef WGL_EXT_pbuffer
-#define WGL_DRAW_TO_PBUFFER_EXT        0x202D
-#define WGL_MAX_PBUFFER_PIXELS_EXT     0x202E
-#define WGL_MAX_PBUFFER_WIDTH_EXT      0x202F
-#define WGL_MAX_PBUFFER_HEIGHT_EXT     0x2030
-#define WGL_OPTIMAL_PBUFFER_WIDTH_EXT  0x2031
-#define WGL_OPTIMAL_PBUFFER_HEIGHT_EXT 0x2032
-#define WGL_PBUFFER_LARGEST_EXT        0x2033
-#define WGL_PBUFFER_WIDTH_EXT          0x2034
-#define WGL_PBUFFER_HEIGHT_EXT         0x2035
-#endif
-
-#ifndef WGL_EXT_depth_float
-#define WGL_DEPTH_FLOAT_EXT            0x2040
-#endif
-
-#ifndef WGL_3DFX_multisample
-#define WGL_SAMPLE_BUFFERS_3DFX        0x2060
-#define WGL_SAMPLES_3DFX               0x2061
-#endif
-
-#ifndef WGL_EXT_multisample
-#define WGL_SAMPLE_BUFFERS_EXT         0x2041
-#define WGL_SAMPLES_EXT                0x2042
-#endif
-
-#ifndef WGL_I3D_digital_video_control
-#define WGL_DIGITAL_VIDEO_CURSOR_ALPHA_FRAMEBUFFER_I3D 0x2050
-#define WGL_DIGITAL_VIDEO_CURSOR_ALPHA_VALUE_I3D 0x2051
-#define WGL_DIGITAL_VIDEO_CURSOR_INCLUDED_I3D 0x2052
-#define WGL_DIGITAL_VIDEO_GAMMA_CORRECTED_I3D 0x2053
-#endif
-
-#ifndef WGL_I3D_gamma
-#define WGL_GAMMA_TABLE_SIZE_I3D       0x204E
-#define WGL_GAMMA_EXCLUDE_DESKTOP_I3D  0x204F
-#endif
-
-#ifndef WGL_I3D_genlock
-#define WGL_GENLOCK_SOURCE_MULTIVIEW_I3D 0x2044
-#define WGL_GENLOCK_SOURCE_EXTENAL_SYNC_I3D 0x2045
-#define WGL_GENLOCK_SOURCE_EXTENAL_FIELD_I3D 0x2046
-#define WGL_GENLOCK_SOURCE_EXTENAL_TTL_I3D 0x2047
-#define WGL_GENLOCK_SOURCE_DIGITAL_SYNC_I3D 0x2048
-#define WGL_GENLOCK_SOURCE_DIGITAL_FIELD_I3D 0x2049
-#define WGL_GENLOCK_SOURCE_EDGE_FALLING_I3D 0x204A
-#define WGL_GENLOCK_SOURCE_EDGE_RISING_I3D 0x204B
-#define WGL_GENLOCK_SOURCE_EDGE_BOTH_I3D 0x204C
-#endif
-
-#ifndef WGL_I3D_image_buffer
-#define WGL_IMAGE_BUFFER_MIN_ACCESS_I3D 0x00000001
-#define WGL_IMAGE_BUFFER_LOCK_I3D      0x00000002
-#endif
-
-#ifndef WGL_I3D_swap_frame_lock
-#endif
-
-#ifndef WGL_NV_render_depth_texture
-#define WGL_BIND_TO_TEXTURE_DEPTH_NV   0x20A3
-#define WGL_BIND_TO_TEXTURE_RECTANGLE_DEPTH_NV 0x20A4
-#define WGL_DEPTH_TEXTURE_FORMAT_NV    0x20A5
-#define WGL_TEXTURE_DEPTH_COMPONENT_NV 0x20A6
-#define WGL_DEPTH_COMPONENT_NV         0x20A7
-#endif
-
-#ifndef WGL_NV_render_texture_rectangle
-#define WGL_BIND_TO_TEXTURE_RECTANGLE_RGB_NV 0x20A0
-#define WGL_BIND_TO_TEXTURE_RECTANGLE_RGBA_NV 0x20A1
-#define WGL_TEXTURE_RECTANGLE_NV       0x20A2
-#endif
-
-#ifndef WGL_ATI_pixel_format_float
-#define WGL_TYPE_RGBA_FLOAT_ATI        0x21A0
-#define WGL_RGBA_FLOAT_MODE_ATI        0x8820
-#define WGL_COLOR_CLEAR_UNCLAMPED_VALUE_ATI 0x8835
-#endif
-
-#ifndef WGL_NV_float_buffer
-#define WGL_FLOAT_COMPONENTS_NV        0x20B0
-#define WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_R_NV 0x20B1
-#define WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RG_NV 0x20B2
-#define WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RGB_NV 0x20B3
-#define WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RGBA_NV 0x20B4
-#define WGL_TEXTURE_FLOAT_R_NV         0x20B5
-#define WGL_TEXTURE_FLOAT_RG_NV        0x20B6
-#define WGL_TEXTURE_FLOAT_RGB_NV       0x20B7
-#define WGL_TEXTURE_FLOAT_RGBA_NV      0x20B8
-#endif
-
-#ifndef WGL_NV_swap_group
-#endif
-
-
-/*************************************************************/
-
-#ifndef WGL_ARB_pbuffer
-DECLARE_HANDLE(HPBUFFERARB);
-#endif
-#ifndef WGL_EXT_pbuffer
-DECLARE_HANDLE(HPBUFFEREXT);
-#endif
-
-#ifndef WGL_ARB_buffer_region
-#define WGL_ARB_buffer_region 1
-#ifdef WGL_WGLEXT_PROTOTYPES
-extern HANDLE WINAPI wglCreateBufferRegionARB (HDC, int, UINT);
-extern VOID WINAPI wglDeleteBufferRegionARB (HANDLE);
-extern BOOL WINAPI wglSaveBufferRegionARB (HANDLE, int, int, int, int);
-extern BOOL WINAPI wglRestoreBufferRegionARB (HANDLE, int, int, int, int, int, int);
-#endif /* WGL_WGLEXT_PROTOTYPES */
-typedef HANDLE (WINAPI * PFNWGLCREATEBUFFERREGIONARBPROC) (HDC hDC, int iLayerPlane, UINT uType);
-typedef VOID (WINAPI * PFNWGLDELETEBUFFERREGIONARBPROC) (HANDLE hRegion);
-typedef BOOL (WINAPI * PFNWGLSAVEBUFFERREGIONARBPROC) (HANDLE hRegion, int x, int y, int width, int height);
-typedef BOOL (WINAPI * PFNWGLRESTOREBUFFERREGIONARBPROC) (HANDLE hRegion, int x, int y, int width, int height, int xSrc, int ySrc);
-#endif
-
-#ifndef WGL_ARB_multisample
-#define WGL_ARB_multisample 1
-#endif
-
-#ifndef WGL_ARB_extensions_string
-#define WGL_ARB_extensions_string 1
-#ifdef WGL_WGLEXT_PROTOTYPES
-extern const char * WINAPI wglGetExtensionsStringARB (HDC);
-#endif /* WGL_WGLEXT_PROTOTYPES */
-typedef const char * (WINAPI * PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
-#endif
-
-#ifndef WGL_ARB_pixel_format
-#define WGL_ARB_pixel_format 1
-#ifdef WGL_WGLEXT_PROTOTYPES
-extern BOOL WINAPI wglGetPixelFormatAttribivARB (HDC, int, int, UINT, const int *, int *);
-extern BOOL WINAPI wglGetPixelFormatAttribfvARB (HDC, int, int, UINT, const int *, FLOAT *);
-extern BOOL WINAPI wglChoosePixelFormatARB (HDC, const int *, const FLOAT *, UINT, int *, UINT *);
-#endif /* WGL_WGLEXT_PROTOTYPES */
-typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
-typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBFVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, FLOAT *pfValues);
-typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
-#endif
-
-#ifndef WGL_ARB_make_current_read
-#define WGL_ARB_make_current_read 1
-#ifdef WGL_WGLEXT_PROTOTYPES
-extern BOOL WINAPI wglMakeContextCurrentARB (HDC, HDC, HGLRC);
-extern HDC WINAPI wglGetCurrentReadDCARB (void);
-#endif /* WGL_WGLEXT_PROTOTYPES */
-typedef BOOL (WINAPI * PFNWGLMAKECONTEXTCURRENTARBPROC) (HDC hDrawDC, HDC hReadDC, HGLRC hglrc);
-typedef HDC (WINAPI * PFNWGLGETCURRENTREADDCARBPROC) (void);
-#endif
-
-#ifndef WGL_ARB_pbuffer
-#define WGL_ARB_pbuffer 1
-#ifdef WGL_WGLEXT_PROTOTYPES
-extern HPBUFFERARB WINAPI wglCreatePbufferARB (HDC, int, int, int, const int *);
-extern HDC WINAPI wglGetPbufferDCARB (HPBUFFERARB);
-extern int WINAPI wglReleasePbufferDCARB (HPBUFFERARB, HDC);
-extern BOOL WINAPI wglDestroyPbufferARB (HPBUFFERARB);
-extern BOOL WINAPI wglQueryPbufferARB (HPBUFFERARB, int, int *);
-#endif /* WGL_WGLEXT_PROTOTYPES */
-typedef HPBUFFERARB (WINAPI * PFNWGLCREATEPBUFFERARBPROC) (HDC hDC, int iPixelFormat, int iWidth, int iHeight, const int *piAttribList);
-typedef HDC (WINAPI * PFNWGLGETPBUFFERDCARBPROC) (HPBUFFERARB hPbuffer);
-typedef int (WINAPI * PFNWGLRELEASEPBUFFERDCARBPROC) (HPBUFFERARB hPbuffer, HDC hDC);
-typedef BOOL (WINAPI * PFNWGLDESTROYPBUFFERARBPROC) (HPBUFFERARB hPbuffer);
-typedef BOOL (WINAPI * PFNWGLQUERYPBUFFERARBPROC) (HPBUFFERARB hPbuffer, int iAttribute, int *piValue);
-#endif
-
-#ifndef WGL_ARB_render_texture
-#define WGL_ARB_render_texture 1
-#ifdef WGL_WGLEXT_PROTOTYPES
-extern BOOL WINAPI wglBindTexImageARB (HPBUFFERARB, int);
-extern BOOL WINAPI wglReleaseTexImageARB (HPBUFFERARB, int);
-extern BOOL WINAPI wglSetPbufferAttribARB (HPBUFFERARB, const int *);
-#endif /* WGL_WGLEXT_PROTOTYPES */
-typedef BOOL (WINAPI * PFNWGLBINDTEXIMAGEARBPROC) (HPBUFFERARB hPbuffer, int iBuffer);
-typedef BOOL (WINAPI * PFNWGLRELEASETEXIMAGEARBPROC) (HPBUFFERARB hPbuffer, int iBuffer);
-typedef BOOL (WINAPI * PFNWGLSETPBUFFERATTRIBARBPROC) (HPBUFFERARB hPbuffer, const int *piAttribList);
-#endif
-
-#ifndef WGL_ARB_pixel_format_float
-#define WGL_ARB_pixel_format_float 1
-#endif
-
-#ifndef WGL_EXT_display_color_table
-#define WGL_EXT_display_color_table 1
-#ifdef WGL_WGLEXT_PROTOTYPES
-extern GLboolean WINAPI wglCreateDisplayColorTableEXT (GLushort);
-extern GLboolean WINAPI wglLoadDisplayColorTableEXT (const GLushort *, GLuint);
-extern GLboolean WINAPI wglBindDisplayColorTableEXT (GLushort);
-extern VOID WINAPI wglDestroyDisplayColorTableEXT (GLushort);
-#endif /* WGL_WGLEXT_PROTOTYPES */
-typedef GLboolean (WINAPI * PFNWGLCREATEDISPLAYCOLORTABLEEXTPROC) (GLushort id);
-typedef GLboolean (WINAPI * PFNWGLLOADDISPLAYCOLORTABLEEXTPROC) (const GLushort *table, GLuint length);
-typedef GLboolean (WINAPI * PFNWGLBINDDISPLAYCOLORTABLEEXTPROC) (GLushort id);
-typedef VOID (WINAPI * PFNWGLDESTROYDISPLAYCOLORTABLEEXTPROC) (GLushort id);
-#endif
-
-#ifndef WGL_EXT_extensions_string
-#define WGL_EXT_extensions_string 1
-#ifdef WGL_WGLEXT_PROTOTYPES
-extern const char * WINAPI wglGetExtensionsStringEXT (void);
-#endif /* WGL_WGLEXT_PROTOTYPES */
-typedef const char * (WINAPI * PFNWGLGETEXTENSIONSSTRINGEXTPROC) (void);
-#endif
-
-#ifndef WGL_EXT_make_current_read
-#define WGL_EXT_make_current_read 1
-#ifdef WGL_WGLEXT_PROTOTYPES
-extern BOOL WINAPI wglMakeContextCurrentEXT (HDC, HDC, HGLRC);
-extern HDC WINAPI wglGetCurrentReadDCEXT (void);
-#endif /* WGL_WGLEXT_PROTOTYPES */
-typedef BOOL (WINAPI * PFNWGLMAKECONTEXTCURRENTEXTPROC) (HDC hDrawDC, HDC hReadDC, HGLRC hglrc);
-typedef HDC (WINAPI * PFNWGLGETCURRENTREADDCEXTPROC) (void);
-#endif
-
-#ifndef WGL_EXT_pbuffer
-#define WGL_EXT_pbuffer 1
-#ifdef WGL_WGLEXT_PROTOTYPES
-extern HPBUFFEREXT WINAPI wglCreatePbufferEXT (HDC, int, int, int, const int *);
-extern HDC WINAPI wglGetPbufferDCEXT (HPBUFFEREXT);
-extern int WINAPI wglReleasePbufferDCEXT (HPBUFFEREXT, HDC);
-extern BOOL WINAPI wglDestroyPbufferEXT (HPBUFFEREXT);
-extern BOOL WINAPI wglQueryPbufferEXT (HPBUFFEREXT, int, int *);
-#endif /* WGL_WGLEXT_PROTOTYPES */
-typedef HPBUFFEREXT (WINAPI * PFNWGLCREATEPBUFFEREXTPROC) (HDC hDC, int iPixelFormat, int iWidth, int iHeight, const int *piAttribList);
-typedef HDC (WINAPI * PFNWGLGETPBUFFERDCEXTPROC) (HPBUFFEREXT hPbuffer);
-typedef int (WINAPI * PFNWGLRELEASEPBUFFERDCEXTPROC) (HPBUFFEREXT hPbuffer, HDC hDC);
-typedef BOOL (WINAPI * PFNWGLDESTROYPBUFFEREXTPROC) (HPBUFFEREXT hPbuffer);
-typedef BOOL (WINAPI * PFNWGLQUERYPBUFFEREXTPROC) (HPBUFFEREXT hPbuffer, int iAttribute, int *piValue);
-#endif
-
-#ifndef WGL_EXT_pixel_format
-#define WGL_EXT_pixel_format 1
-#ifdef WGL_WGLEXT_PROTOTYPES
-extern BOOL WINAPI wglGetPixelFormatAttribivEXT (HDC, int, int, UINT, int *, int *);
-extern BOOL WINAPI wglGetPixelFormatAttribfvEXT (HDC, int, int, UINT, int *, FLOAT *);
-extern BOOL WINAPI wglChoosePixelFormatEXT (HDC, const int *, const FLOAT *, UINT, int *, UINT *);
-#endif /* WGL_WGLEXT_PROTOTYPES */
-typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVEXTPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, int *piAttributes, int *piValues);
-typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBFVEXTPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, int *piAttributes, FLOAT *pfValues);
-typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATEXTPROC) (HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
-#endif
-
-#ifndef WGL_EXT_swap_control
-#define WGL_EXT_swap_control 1
-#ifdef WGL_WGLEXT_PROTOTYPES
-extern BOOL WINAPI wglSwapIntervalEXT (int);
-extern int WINAPI wglGetSwapIntervalEXT (void);
-#endif /* WGL_WGLEXT_PROTOTYPES */
-typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
-typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
-#endif
-
-#ifndef WGL_EXT_depth_float
-#define WGL_EXT_depth_float 1
-#endif
-
-#ifndef WGL_NV_vertex_array_range
-#define WGL_NV_vertex_array_range 1
-#ifdef WGL_WGLEXT_PROTOTYPES
-extern void* WINAPI wglAllocateMemoryNV (GLsizei, GLfloat, GLfloat, GLfloat);
-extern void WINAPI wglFreeMemoryNV (void *);
-#endif /* WGL_WGLEXT_PROTOTYPES */
-typedef void* (WINAPI * PFNWGLALLOCATEMEMORYNVPROC) (GLsizei size, GLfloat readfreq, GLfloat writefreq, GLfloat priority);
-typedef void (WINAPI * PFNWGLFREEMEMORYNVPROC) (void *pointer);
-#endif
-
-#ifndef WGL_3DFX_multisample
-#define WGL_3DFX_multisample 1
-#endif
-
-#ifndef WGL_EXT_multisample
-#define WGL_EXT_multisample 1
-#endif
-
-#ifndef WGL_OML_sync_control
-#define WGL_OML_sync_control 1
-#ifdef WGL_WGLEXT_PROTOTYPES
-extern BOOL WINAPI wglGetSyncValuesOML (HDC, INT64 *, INT64 *, INT64 *);
-extern BOOL WINAPI wglGetMscRateOML (HDC, INT32 *, INT32 *);
-extern INT64 WINAPI wglSwapBuffersMscOML (HDC, INT64, INT64, INT64);
-extern INT64 WINAPI wglSwapLayerBuffersMscOML (HDC, int, INT64, INT64, INT64);
-extern BOOL WINAPI wglWaitForMscOML (HDC, INT64, INT64, INT64, INT64 *, INT64 *, INT64 *);
-extern BOOL WINAPI wglWaitForSbcOML (HDC, INT64, INT64 *, INT64 *, INT64 *);
-#endif /* WGL_WGLEXT_PROTOTYPES */
-typedef BOOL (WINAPI * PFNWGLGETSYNCVALUESOMLPROC) (HDC hdc, INT64 *ust, INT64 *msc, INT64 *sbc);
-typedef BOOL (WINAPI * PFNWGLGETMSCRATEOMLPROC) (HDC hdc, INT32 *numerator, INT32 *denominator);
-typedef INT64 (WINAPI * PFNWGLSWAPBUFFERSMSCOMLPROC) (HDC hdc, INT64 target_msc, INT64 divisor, INT64 remainder);
-typedef INT64 (WINAPI * PFNWGLSWAPLAYERBUFFERSMSCOMLPROC) (HDC hdc, int fuPlanes, INT64 target_msc, INT64 divisor, INT64 remainder);
-typedef BOOL (WINAPI * PFNWGLWAITFORMSCOMLPROC) (HDC hdc, INT64 target_msc, INT64 divisor, INT64 remainder, INT64 *ust, INT64 *msc, INT64 *sbc);
-typedef BOOL (WINAPI * PFNWGLWAITFORSBCOMLPROC) (HDC hdc, INT64 target_sbc, INT64 *ust, INT64 *msc, INT64 *sbc);
-#endif
-
-#ifndef WGL_I3D_digital_video_control
-#define WGL_I3D_digital_video_control 1
-#ifdef WGL_WGLEXT_PROTOTYPES
-extern BOOL WINAPI wglGetDigitalVideoParametersI3D (HDC, int, int *);
-extern BOOL WINAPI wglSetDigitalVideoParametersI3D (HDC, int, const int *);
-#endif /* WGL_WGLEXT_PROTOTYPES */
-typedef BOOL (WINAPI * PFNWGLGETDIGITALVIDEOPARAMETERSI3DPROC) (HDC hDC, int iAttribute, int *piValue);
-typedef BOOL (WINAPI * PFNWGLSETDIGITALVIDEOPARAMETERSI3DPROC) (HDC hDC, int iAttribute, const int *piValue);
-#endif
-
-#ifndef WGL_I3D_gamma
-#define WGL_I3D_gamma 1
-#ifdef WGL_WGLEXT_PROTOTYPES
-extern BOOL WINAPI wglGetGammaTableParametersI3D (HDC, int, int *);
-extern BOOL WINAPI wglSetGammaTableParametersI3D (HDC, int, const int *);
-extern BOOL WINAPI wglGetGammaTableI3D (HDC, int, USHORT *, USHORT *, USHORT *);
-extern BOOL WINAPI wglSetGammaTableI3D (HDC, int, const USHORT *, const USHORT *, const USHORT *);
-#endif /* WGL_WGLEXT_PROTOTYPES */
-typedef BOOL (WINAPI * PFNWGLGETGAMMATABLEPARAMETERSI3DPROC) (HDC hDC, int iAttribute, int *piValue);
-typedef BOOL (WINAPI * PFNWGLSETGAMMATABLEPARAMETERSI3DPROC) (HDC hDC, int iAttribute, const int *piValue);
-typedef BOOL (WINAPI * PFNWGLGETGAMMATABLEI3DPROC) (HDC hDC, int iEntries, USHORT *puRed, USHORT *puGreen, USHORT *puBlue);
-typedef BOOL (WINAPI * PFNWGLSETGAMMATABLEI3DPROC) (HDC hDC, int iEntries, const USHORT *puRed, const USHORT *puGreen, const USHORT *puBlue);
-#endif
-
-#ifndef WGL_I3D_genlock
-#define WGL_I3D_genlock 1
-#ifdef WGL_WGLEXT_PROTOTYPES
-extern BOOL WINAPI wglEnableGenlockI3D (HDC);
-extern BOOL WINAPI wglDisableGenlockI3D (HDC);
-extern BOOL WINAPI wglIsEnabledGenlockI3D (HDC, BOOL *);
-extern BOOL WINAPI wglGenlockSourceI3D (HDC, UINT);
-extern BOOL WINAPI wglGetGenlockSourceI3D (HDC, UINT *);
-extern BOOL WINAPI wglGenlockSourceEdgeI3D (HDC, UINT);
-extern BOOL WINAPI wglGetGenlockSourceEdgeI3D (HDC, UINT *);
-extern BOOL WINAPI wglGenlockSampleRateI3D (HDC, UINT);
-extern BOOL WINAPI wglGetGenlockSampleRateI3D (HDC, UINT *);
-extern BOOL WINAPI wglGenlockSourceDelayI3D (HDC, UINT);
-extern BOOL WINAPI wglGetGenlockSourceDelayI3D (HDC, UINT *);
-extern BOOL WINAPI wglQueryGenlockMaxSourceDelayI3D (HDC, UINT *, UINT *);
-#endif /* WGL_WGLEXT_PROTOTYPES */
-typedef BOOL (WINAPI * PFNWGLENABLEGENLOCKI3DPROC) (HDC hDC);
-typedef BOOL (WINAPI * PFNWGLDISABLEGENLOCKI3DPROC) (HDC hDC);
-typedef BOOL (WINAPI * PFNWGLISENABLEDGENLOCKI3DPROC) (HDC hDC, BOOL *pFlag);
-typedef BOOL (WINAPI * PFNWGLGENLOCKSOURCEI3DPROC) (HDC hDC, UINT uSource);
-typedef BOOL (WINAPI * PFNWGLGETGENLOCKSOURCEI3DPROC) (HDC hDC, UINT *uSource);
-typedef BOOL (WINAPI * PFNWGLGENLOCKSOURCEEDGEI3DPROC) (HDC hDC, UINT uEdge);
-typedef BOOL (WINAPI * PFNWGLGETGENLOCKSOURCEEDGEI3DPROC) (HDC hDC, UINT *uEdge);
-typedef BOOL (WINAPI * PFNWGLGENLOCKSAMPLERATEI3DPROC) (HDC hDC, UINT uRate);
-typedef BOOL (WINAPI * PFNWGLGETGENLOCKSAMPLERATEI3DPROC) (HDC hDC, UINT *uRate);
-typedef BOOL (WINAPI * PFNWGLGENLOCKSOURCEDELAYI3DPROC) (HDC hDC, UINT uDelay);
-typedef BOOL (WINAPI * PFNWGLGETGENLOCKSOURCEDELAYI3DPROC) (HDC hDC, UINT *uDelay);
-typedef BOOL (WINAPI * PFNWGLQUERYGENLOCKMAXSOURCEDELAYI3DPROC) (HDC hDC, UINT *uMaxLineDelay, UINT *uMaxPixelDelay);
-#endif
-
-#ifndef WGL_I3D_image_buffer
-#define WGL_I3D_image_buffer 1
-#ifdef WGL_WGLEXT_PROTOTYPES
-extern LPVOID WINAPI wglCreateImageBufferI3D (HDC, DWORD, UINT);
-extern BOOL WINAPI wglDestroyImageBufferI3D (HDC, LPVOID);
-extern BOOL WINAPI wglAssociateImageBufferEventsI3D (HDC, const HANDLE *, const LPVOID *, const DWORD *, UINT);
-extern BOOL WINAPI wglReleaseImageBufferEventsI3D (HDC, const LPVOID *, UINT);
-#endif /* WGL_WGLEXT_PROTOTYPES */
-typedef LPVOID (WINAPI * PFNWGLCREATEIMAGEBUFFERI3DPROC) (HDC hDC, DWORD dwSize, UINT uFlags);
-typedef BOOL (WINAPI * PFNWGLDESTROYIMAGEBUFFERI3DPROC) (HDC hDC, LPVOID pAddress);
-typedef BOOL (WINAPI * PFNWGLASSOCIATEIMAGEBUFFEREVENTSI3DPROC) (HDC hDC, const HANDLE *pEvent, const LPVOID *pAddress, const DWORD *pSize, UINT count);
-typedef BOOL (WINAPI * PFNWGLRELEASEIMAGEBUFFEREVENTSI3DPROC) (HDC hDC, const LPVOID *pAddress, UINT count);
-#endif
-
-#ifndef WGL_I3D_swap_frame_lock
-#define WGL_I3D_swap_frame_lock 1
-#ifdef WGL_WGLEXT_PROTOTYPES
-extern BOOL WINAPI wglEnableFrameLockI3D (void);
-extern BOOL WINAPI wglDisableFrameLockI3D (void);
-extern BOOL WINAPI wglIsEnabledFrameLockI3D (BOOL *);
-extern BOOL WINAPI wglQueryFrameLockMasterI3D (BOOL *);
-#endif /* WGL_WGLEXT_PROTOTYPES */
-typedef BOOL (WINAPI * PFNWGLENABLEFRAMELOCKI3DPROC) (void);
-typedef BOOL (WINAPI * PFNWGLDISABLEFRAMELOCKI3DPROC) (void);
-typedef BOOL (WINAPI * PFNWGLISENABLEDFRAMELOCKI3DPROC) (BOOL *pFlag);
-typedef BOOL (WINAPI * PFNWGLQUERYFRAMELOCKMASTERI3DPROC) (BOOL *pFlag);
-#endif
-
-#ifndef WGL_I3D_swap_frame_usage
-#define WGL_I3D_swap_frame_usage 1
-#ifdef WGL_WGLEXT_PROTOTYPES
-extern BOOL WINAPI wglGetFrameUsageI3D (float *);
-extern BOOL WINAPI wglBeginFrameTrackingI3D (void);
-extern BOOL WINAPI wglEndFrameTrackingI3D (void);
-extern BOOL WINAPI wglQueryFrameTrackingI3D (DWORD *, DWORD *, float *);
-#endif /* WGL_WGLEXT_PROTOTYPES */
-typedef BOOL (WINAPI * PFNWGLGETFRAMEUSAGEI3DPROC) (float *pUsage);
-typedef BOOL (WINAPI * PFNWGLBEGINFRAMETRACKINGI3DPROC) (void);
-typedef BOOL (WINAPI * PFNWGLENDFRAMETRACKINGI3DPROC) (void);
-typedef BOOL (WINAPI * PFNWGLQUERYFRAMETRACKINGI3DPROC) (DWORD *pFrameCount, DWORD *pMissedFrames, float *pLastMissedUsage);
-#endif
-
-#ifndef WGL_ATI_pixel_format_float
-#define WGL_ATI_pixel_format_float 1
-#endif
-
-#ifndef WGL_NV_render_depth_texture
-#define WGL_NV_render_depth_texture 1
-#endif
-
-#ifndef WGL_NV_render_texture_rectangle
-#define WGL_NV_render_texture_rectangle 1
-#endif
-
-#ifndef WGL_NV_float_buffer
-#define WGL_NV_float_buffer 1
-#endif
-
-#ifndef WGL_NV_swap_group
-#define WGL_NV_swap_group 1
-#ifdef WGL_WGLEXT_PROTOTYPES
-extern BOOL WINAPI wglJoinSwapGroupNV(HDC hDC, GLuint group);
-extern BOOL WINAPI wglBindSwapBarrierNV(GLuint group, GLuint barrier);
-extern BOOL WINAPI wglQuerySwapGroupNV(HDC hDC GLuint *group, GLuint *barrier);
-extern BOOL WINAPI wglQueryMaxSwapGroupsNV(HDC hDC, GLuint *maxGroups, GLuint *maxBarriers);
-extern BOOL WINAPI wglQueryFrameCountNV(HDC hDC, GLuint *count);
-extern BOOL WINAPI wglResetFrameCountNV(HDC hDC);
-#endif /* WGL_WGLEXT_PROTOTYPES */
-typedef BOOL (WINAPI * PFNWGLJOINSWAPGROUPNVPROC) (HDC hDC, GLuint group);
-typedef BOOL (WINAPI * PFNWGLBINDSWAPBARRIERNVPROC) (GLuint group, GLuint barrier);
-typedef BOOL (WINAPI * PFNWGLQUERYSWAPGROUPNVPROC) (HDC hDC, GLuint *group, GLuint *barrier);
-typedef BOOL (WINAPI * PFNWGLQUERYMAXSWAPGROUPSNVPROC) (HDC hDC, GLuint *maxGroups, GLuint *maxBarriers);
-typedef BOOL (WINAPI * PFNWGLQUERYFRAMECOUNTNVPROC) (HDC hDC, GLuint *count);
-typedef BOOL (WINAPI * PFNWGLRESETFRAMECOUNTNVPROC) (HDC hDC);
-#endif
-
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
+#ifndef __wglext_h_
+#define __wglext_h_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+  /*
+  ** License Applicability. Except to the extent portions of this file are
+  ** made subject to an alternative license as permitted in the SGI Free
+  ** Software License B, Version 1.1 (the "License"), the contents of this
+  ** file are subject only to the provisions of the License. You may not use
+  ** this file except in compliance with the License. You may obtain a copy
+  ** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
+  ** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
+  **
+  ** http://oss.sgi.com/projects/FreeB
+  **
+  ** Note that, as provided in the License, the Software is distributed on an
+  ** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
+  ** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
+  ** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
+  ** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
+  **
+  ** Original Code. The Original Code is: OpenGL Sample Implementation,
+  ** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
+  ** Inc. The Original Code is Copyright (c) 1991-2004 Silicon Graphics, Inc.
+  ** Copyright in any portions created by third parties is as indicated
+  ** elsewhere herein. All Rights Reserved.
+  **
+  ** Additional Notice Provisions: This software was created using the
+  ** OpenGL(R) version 1.2.1 Sample Implementation published by SGI, but has
+  ** not been independently verified as being compliant with the OpenGL(R)
+  ** version 1.2.1 Specification.
+  */
+
+#if defined(_WIN32) && !defined(APIENTRY) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__)
+#define WIN32_LEAN_AND_MEAN 1
+#include <windows.h>
+#endif
+
+#ifndef APIENTRY
+#define APIENTRY
+#endif
+#ifndef APIENTRYP
+#define APIENTRYP APIENTRY *
+#endif
+#ifndef GLAPI
+#define GLAPI extern
+#endif
+
+  /*************************************************************/
+
+  /* Header file version number */
+  /* wglext.h last updated 2005/01/07 */
+  /* Current version at http://oss.sgi.com/projects/ogl-sample/registry/ */
+#define WGL_WGLEXT_VERSION 6
+
+#ifndef WGL_ARB_buffer_region
+#define WGL_FRONT_COLOR_BUFFER_BIT_ARB 0x00000001
+#define WGL_BACK_COLOR_BUFFER_BIT_ARB  0x00000002
+#define WGL_DEPTH_BUFFER_BIT_ARB       0x00000004
+#define WGL_STENCIL_BUFFER_BIT_ARB     0x00000008
+#endif
+
+#ifndef WGL_ARB_multisample
+#define WGL_SAMPLE_BUFFERS_ARB         0x2041
+#define WGL_SAMPLES_ARB                0x2042
+#endif
+
+#ifndef WGL_ARB_extensions_string
+#endif
+
+#ifndef WGL_ARB_pixel_format
+#define WGL_NUMBER_PIXEL_FORMATS_ARB   0x2000
+#define WGL_DRAW_TO_WINDOW_ARB         0x2001
+#define WGL_DRAW_TO_BITMAP_ARB         0x2002
+#define WGL_ACCELERATION_ARB           0x2003
+#define WGL_NEED_PALETTE_ARB           0x2004
+#define WGL_NEED_SYSTEM_PALETTE_ARB    0x2005
+#define WGL_SWAP_LAYER_BUFFERS_ARB     0x2006
+#define WGL_SWAP_METHOD_ARB            0x2007
+#define WGL_NUMBER_OVERLAYS_ARB        0x2008
+#define WGL_NUMBER_UNDERLAYS_ARB       0x2009
+#define WGL_TRANSPARENT_ARB            0x200A
+#define WGL_TRANSPARENT_RED_VALUE_ARB  0x2037
+#define WGL_TRANSPARENT_GREEN_VALUE_ARB 0x2038
+#define WGL_TRANSPARENT_BLUE_VALUE_ARB 0x2039
+#define WGL_TRANSPARENT_ALPHA_VALUE_ARB 0x203A
+#define WGL_TRANSPARENT_INDEX_VALUE_ARB 0x203B
+#define WGL_SHARE_DEPTH_ARB            0x200C
+#define WGL_SHARE_STENCIL_ARB          0x200D
+#define WGL_SHARE_ACCUM_ARB            0x200E
+#define WGL_SUPPORT_GDI_ARB            0x200F
+#define WGL_SUPPORT_OPENGL_ARB         0x2010
+#define WGL_DOUBLE_BUFFER_ARB          0x2011
+#define WGL_STEREO_ARB                 0x2012
+#define WGL_PIXEL_TYPE_ARB             0x2013
+#define WGL_COLOR_BITS_ARB             0x2014
+#define WGL_RED_BITS_ARB               0x2015
+#define WGL_RED_SHIFT_ARB              0x2016
+#define WGL_GREEN_BITS_ARB             0x2017
+#define WGL_GREEN_SHIFT_ARB            0x2018
+#define WGL_BLUE_BITS_ARB              0x2019
+#define WGL_BLUE_SHIFT_ARB             0x201A
+#define WGL_ALPHA_BITS_ARB             0x201B
+#define WGL_ALPHA_SHIFT_ARB            0x201C
+#define WGL_ACCUM_BITS_ARB             0x201D
+#define WGL_ACCUM_RED_BITS_ARB         0x201E
+#define WGL_ACCUM_GREEN_BITS_ARB       0x201F
+#define WGL_ACCUM_BLUE_BITS_ARB        0x2020
+#define WGL_ACCUM_ALPHA_BITS_ARB       0x2021
+#define WGL_DEPTH_BITS_ARB             0x2022
+#define WGL_STENCIL_BITS_ARB           0x2023
+#define WGL_AUX_BUFFERS_ARB            0x2024
+#define WGL_NO_ACCELERATION_ARB        0x2025
+#define WGL_GENERIC_ACCELERATION_ARB   0x2026
+#define WGL_FULL_ACCELERATION_ARB      0x2027
+#define WGL_SWAP_EXCHANGE_ARB          0x2028
+#define WGL_SWAP_COPY_ARB              0x2029
+#define WGL_SWAP_UNDEFINED_ARB         0x202A
+#define WGL_TYPE_RGBA_ARB              0x202B
+#define WGL_TYPE_COLORINDEX_ARB        0x202C
+#endif
+
+#ifndef WGL_ARB_make_current_read
+#define ERROR_INVALID_PIXEL_TYPE_ARB   0x2043
+#define ERROR_INCOMPATIBLE_DEVICE_CONTEXTS_ARB 0x2054
+#endif
+
+#ifndef WGL_ARB_pbuffer
+#define WGL_DRAW_TO_PBUFFER_ARB        0x202D
+#define WGL_MAX_PBUFFER_PIXELS_ARB     0x202E
+#define WGL_MAX_PBUFFER_WIDTH_ARB      0x202F
+#define WGL_MAX_PBUFFER_HEIGHT_ARB     0x2030
+#define WGL_PBUFFER_LARGEST_ARB        0x2033
+#define WGL_PBUFFER_WIDTH_ARB          0x2034
+#define WGL_PBUFFER_HEIGHT_ARB         0x2035
+#define WGL_PBUFFER_LOST_ARB           0x2036
+#endif
+
+#ifndef WGL_ARB_render_texture
+#define WGL_BIND_TO_TEXTURE_RGB_ARB    0x2070
+#define WGL_BIND_TO_TEXTURE_RGBA_ARB   0x2071
+#define WGL_TEXTURE_FORMAT_ARB         0x2072
+#define WGL_TEXTURE_TARGET_ARB         0x2073
+#define WGL_MIPMAP_TEXTURE_ARB         0x2074
+#define WGL_TEXTURE_RGB_ARB            0x2075
+#define WGL_TEXTURE_RGBA_ARB           0x2076
+#define WGL_NO_TEXTURE_ARB             0x2077
+#define WGL_TEXTURE_CUBE_MAP_ARB       0x2078
+#define WGL_TEXTURE_1D_ARB             0x2079
+#define WGL_TEXTURE_2D_ARB             0x207A
+#define WGL_MIPMAP_LEVEL_ARB           0x207B
+#define WGL_CUBE_MAP_FACE_ARB          0x207C
+#define WGL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB 0x207D
+#define WGL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB 0x207E
+#define WGL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB 0x207F
+#define WGL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB 0x2080
+#define WGL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB 0x2081
+#define WGL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB 0x2082
+#define WGL_FRONT_LEFT_ARB             0x2083
+#define WGL_FRONT_RIGHT_ARB            0x2084
+#define WGL_BACK_LEFT_ARB              0x2085
+#define WGL_BACK_RIGHT_ARB             0x2086
+#define WGL_AUX0_ARB                   0x2087
+#define WGL_AUX1_ARB                   0x2088
+#define WGL_AUX2_ARB                   0x2089
+#define WGL_AUX3_ARB                   0x208A
+#define WGL_AUX4_ARB                   0x208B
+#define WGL_AUX5_ARB                   0x208C
+#define WGL_AUX6_ARB                   0x208D
+#define WGL_AUX7_ARB                   0x208E
+#define WGL_AUX8_ARB                   0x208F
+#define WGL_AUX9_ARB                   0x2090
+#endif
+
+#ifndef WGL_ARB_pixel_format_float
+#define WGL_TYPE_RGBA_FLOAT_ARB        0x21A0
+#endif
+
+#ifndef WGL_EXT_make_current_read
+#define ERROR_INVALID_PIXEL_TYPE_EXT   0x2043
+#endif
+
+#ifndef WGL_EXT_pixel_format
+#define WGL_NUMBER_PIXEL_FORMATS_EXT   0x2000
+#define WGL_DRAW_TO_WINDOW_EXT         0x2001
+#define WGL_DRAW_TO_BITMAP_EXT         0x2002
+#define WGL_ACCELERATION_EXT           0x2003
+#define WGL_NEED_PALETTE_EXT           0x2004
+#define WGL_NEED_SYSTEM_PALETTE_EXT    0x2005
+#define WGL_SWAP_LAYER_BUFFERS_EXT     0x2006
+#define WGL_SWAP_METHOD_EXT            0x2007
+#define WGL_NUMBER_OVERLAYS_EXT        0x2008
+#define WGL_NUMBER_UNDERLAYS_EXT       0x2009
+#define WGL_TRANSPARENT_EXT            0x200A
+#define WGL_TRANSPARENT_VALUE_EXT      0x200B
+#define WGL_SHARE_DEPTH_EXT            0x200C
+#define WGL_SHARE_STENCIL_EXT          0x200D
+#define WGL_SHARE_ACCUM_EXT            0x200E
+#define WGL_SUPPORT_GDI_EXT            0x200F
+#define WGL_SUPPORT_OPENGL_EXT         0x2010
+#define WGL_DOUBLE_BUFFER_EXT          0x2011
+#define WGL_STEREO_EXT                 0x2012
+#define WGL_PIXEL_TYPE_EXT             0x2013
+#define WGL_COLOR_BITS_EXT             0x2014
+#define WGL_RED_BITS_EXT               0x2015
+#define WGL_RED_SHIFT_EXT              0x2016
+#define WGL_GREEN_BITS_EXT             0x2017
+#define WGL_GREEN_SHIFT_EXT            0x2018
+#define WGL_BLUE_BITS_EXT              0x2019
+#define WGL_BLUE_SHIFT_EXT             0x201A
+#define WGL_ALPHA_BITS_EXT             0x201B
+#define WGL_ALPHA_SHIFT_EXT            0x201C
+#define WGL_ACCUM_BITS_EXT             0x201D
+#define WGL_ACCUM_RED_BITS_EXT         0x201E
+#define WGL_ACCUM_GREEN_BITS_EXT       0x201F
+#define WGL_ACCUM_BLUE_BITS_EXT        0x2020
+#define WGL_ACCUM_ALPHA_BITS_EXT       0x2021
+#define WGL_DEPTH_BITS_EXT             0x2022
+#define WGL_STENCIL_BITS_EXT           0x2023
+#define WGL_AUX_BUFFERS_EXT            0x2024
+#define WGL_NO_ACCELERATION_EXT        0x2025
+#define WGL_GENERIC_ACCELERATION_EXT   0x2026
+#define WGL_FULL_ACCELERATION_EXT      0x2027
+#define WGL_SWAP_EXCHANGE_EXT          0x2028
+#define WGL_SWAP_COPY_EXT              0x2029
+#define WGL_SWAP_UNDEFINED_EXT         0x202A
+#define WGL_TYPE_RGBA_EXT              0x202B
+#define WGL_TYPE_COLORINDEX_EXT        0x202C
+#endif
+
+#ifndef WGL_EXT_pbuffer
+#define WGL_DRAW_TO_PBUFFER_EXT        0x202D
+#define WGL_MAX_PBUFFER_PIXELS_EXT     0x202E
+#define WGL_MAX_PBUFFER_WIDTH_EXT      0x202F
+#define WGL_MAX_PBUFFER_HEIGHT_EXT     0x2030
+#define WGL_OPTIMAL_PBUFFER_WIDTH_EXT  0x2031
+#define WGL_OPTIMAL_PBUFFER_HEIGHT_EXT 0x2032
+#define WGL_PBUFFER_LARGEST_EXT        0x2033
+#define WGL_PBUFFER_WIDTH_EXT          0x2034
+#define WGL_PBUFFER_HEIGHT_EXT         0x2035
+#endif
+
+#ifndef WGL_EXT_depth_float
+#define WGL_DEPTH_FLOAT_EXT            0x2040
+#endif
+
+#ifndef WGL_3DFX_multisample
+#define WGL_SAMPLE_BUFFERS_3DFX        0x2060
+#define WGL_SAMPLES_3DFX               0x2061
+#endif
+
+#ifndef WGL_EXT_multisample
+#define WGL_SAMPLE_BUFFERS_EXT         0x2041
+#define WGL_SAMPLES_EXT                0x2042
+#endif
+
+#ifndef WGL_I3D_digital_video_control
+#define WGL_DIGITAL_VIDEO_CURSOR_ALPHA_FRAMEBUFFER_I3D 0x2050
+#define WGL_DIGITAL_VIDEO_CURSOR_ALPHA_VALUE_I3D 0x2051
+#define WGL_DIGITAL_VIDEO_CURSOR_INCLUDED_I3D 0x2052
+#define WGL_DIGITAL_VIDEO_GAMMA_CORRECTED_I3D 0x2053
+#endif
+
+#ifndef WGL_I3D_gamma
+#define WGL_GAMMA_TABLE_SIZE_I3D       0x204E
+#define WGL_GAMMA_EXCLUDE_DESKTOP_I3D  0x204F
+#endif
+
+#ifndef WGL_I3D_genlock
+#define WGL_GENLOCK_SOURCE_MULTIVIEW_I3D 0x2044
+#define WGL_GENLOCK_SOURCE_EXTENAL_SYNC_I3D 0x2045
+#define WGL_GENLOCK_SOURCE_EXTENAL_FIELD_I3D 0x2046
+#define WGL_GENLOCK_SOURCE_EXTENAL_TTL_I3D 0x2047
+#define WGL_GENLOCK_SOURCE_DIGITAL_SYNC_I3D 0x2048
+#define WGL_GENLOCK_SOURCE_DIGITAL_FIELD_I3D 0x2049
+#define WGL_GENLOCK_SOURCE_EDGE_FALLING_I3D 0x204A
+#define WGL_GENLOCK_SOURCE_EDGE_RISING_I3D 0x204B
+#define WGL_GENLOCK_SOURCE_EDGE_BOTH_I3D 0x204C
+#endif
+
+#ifndef WGL_I3D_image_buffer
+#define WGL_IMAGE_BUFFER_MIN_ACCESS_I3D 0x00000001
+#define WGL_IMAGE_BUFFER_LOCK_I3D      0x00000002
+#endif
+
+#ifndef WGL_I3D_swap_frame_lock
+#endif
+
+#ifndef WGL_NV_render_depth_texture
+#define WGL_BIND_TO_TEXTURE_DEPTH_NV   0x20A3
+#define WGL_BIND_TO_TEXTURE_RECTANGLE_DEPTH_NV 0x20A4
+#define WGL_DEPTH_TEXTURE_FORMAT_NV    0x20A5
+#define WGL_TEXTURE_DEPTH_COMPONENT_NV 0x20A6
+#define WGL_DEPTH_COMPONENT_NV         0x20A7
+#endif
+
+#ifndef WGL_NV_render_texture_rectangle
+#define WGL_BIND_TO_TEXTURE_RECTANGLE_RGB_NV 0x20A0
+#define WGL_BIND_TO_TEXTURE_RECTANGLE_RGBA_NV 0x20A1
+#define WGL_TEXTURE_RECTANGLE_NV       0x20A2
+#endif
+
+#ifndef WGL_ATI_pixel_format_float
+#define WGL_TYPE_RGBA_FLOAT_ATI        0x21A0
+#define WGL_RGBA_FLOAT_MODE_ATI        0x8820
+#define WGL_COLOR_CLEAR_UNCLAMPED_VALUE_ATI 0x8835
+#endif
+
+#ifndef WGL_NV_float_buffer
+#define WGL_FLOAT_COMPONENTS_NV        0x20B0
+#define WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_R_NV 0x20B1
+#define WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RG_NV 0x20B2
+#define WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RGB_NV 0x20B3
+#define WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RGBA_NV 0x20B4
+#define WGL_TEXTURE_FLOAT_R_NV         0x20B5
+#define WGL_TEXTURE_FLOAT_RG_NV        0x20B6
+#define WGL_TEXTURE_FLOAT_RGB_NV       0x20B7
+#define WGL_TEXTURE_FLOAT_RGBA_NV      0x20B8
+#endif
+
+#ifndef WGL_NV_swap_group
+#endif
+
+
+  /*************************************************************/
+
+#ifndef WGL_ARB_pbuffer
+  DECLARE_HANDLE(HPBUFFERARB);
+#endif
+#ifndef WGL_EXT_pbuffer
+  DECLARE_HANDLE(HPBUFFEREXT);
+#endif
+
+#ifndef WGL_ARB_buffer_region
+#define WGL_ARB_buffer_region 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+  extern HANDLE WINAPI wglCreateBufferRegionARB (HDC, int, UINT);
+  extern VOID WINAPI wglDeleteBufferRegionARB (HANDLE);
+  extern BOOL WINAPI wglSaveBufferRegionARB (HANDLE, int, int, int, int);
+  extern BOOL WINAPI wglRestoreBufferRegionARB (HANDLE, int, int, int, int, int, int);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+  typedef HANDLE (WINAPI * PFNWGLCREATEBUFFERREGIONARBPROC) (HDC hDC, int iLayerPlane, UINT uType);
+  typedef VOID (WINAPI * PFNWGLDELETEBUFFERREGIONARBPROC) (HANDLE hRegion);
+  typedef BOOL (WINAPI * PFNWGLSAVEBUFFERREGIONARBPROC) (HANDLE hRegion, int x, int y, int width, int height);
+  typedef BOOL (WINAPI * PFNWGLRESTOREBUFFERREGIONARBPROC) (HANDLE hRegion, int x, int y, int width, int height, int xSrc, int ySrc);
+#endif
+
+#ifndef WGL_ARB_multisample
+#define WGL_ARB_multisample 1
+#endif
+
+#ifndef WGL_ARB_extensions_string
+#define WGL_ARB_extensions_string 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+  extern const char * WINAPI wglGetExtensionsStringARB (HDC);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+  typedef const char * (WINAPI * PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
+#endif
+
+#ifndef WGL_ARB_pixel_format
+#define WGL_ARB_pixel_format 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+  extern BOOL WINAPI wglGetPixelFormatAttribivARB (HDC, int, int, UINT, const int *, int *);
+  extern BOOL WINAPI wglGetPixelFormatAttribfvARB (HDC, int, int, UINT, const int *, FLOAT *);
+  extern BOOL WINAPI wglChoosePixelFormatARB (HDC, const int *, const FLOAT *, UINT, int *, UINT *);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+  typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
+  typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBFVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, FLOAT *pfValues);
+  typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
+#endif
+
+#ifndef WGL_ARB_make_current_read
+#define WGL_ARB_make_current_read 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+  extern BOOL WINAPI wglMakeContextCurrentARB (HDC, HDC, HGLRC);
+  extern HDC WINAPI wglGetCurrentReadDCARB (void);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+  typedef BOOL (WINAPI * PFNWGLMAKECONTEXTCURRENTARBPROC) (HDC hDrawDC, HDC hReadDC, HGLRC hglrc);
+  typedef HDC (WINAPI * PFNWGLGETCURRENTREADDCARBPROC) (void);
+#endif
+
+#ifndef WGL_ARB_pbuffer
+#define WGL_ARB_pbuffer 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+  extern HPBUFFERARB WINAPI wglCreatePbufferARB (HDC, int, int, int, const int *);
+  extern HDC WINAPI wglGetPbufferDCARB (HPBUFFERARB);
+  extern int WINAPI wglReleasePbufferDCARB (HPBUFFERARB, HDC);
+  extern BOOL WINAPI wglDestroyPbufferARB (HPBUFFERARB);
+  extern BOOL WINAPI wglQueryPbufferARB (HPBUFFERARB, int, int *);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+  typedef HPBUFFERARB (WINAPI * PFNWGLCREATEPBUFFERARBPROC) (HDC hDC, int iPixelFormat, int iWidth, int iHeight, const int *piAttribList);
+  typedef HDC (WINAPI * PFNWGLGETPBUFFERDCARBPROC) (HPBUFFERARB hPbuffer);
+  typedef int (WINAPI * PFNWGLRELEASEPBUFFERDCARBPROC) (HPBUFFERARB hPbuffer, HDC hDC);
+  typedef BOOL (WINAPI * PFNWGLDESTROYPBUFFERARBPROC) (HPBUFFERARB hPbuffer);
+  typedef BOOL (WINAPI * PFNWGLQUERYPBUFFERARBPROC) (HPBUFFERARB hPbuffer, int iAttribute, int *piValue);
+#endif
+
+#ifndef WGL_ARB_render_texture
+#define WGL_ARB_render_texture 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+  extern BOOL WINAPI wglBindTexImageARB (HPBUFFERARB, int);
+  extern BOOL WINAPI wglReleaseTexImageARB (HPBUFFERARB, int);
+  extern BOOL WINAPI wglSetPbufferAttribARB (HPBUFFERARB, const int *);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+  typedef BOOL (WINAPI * PFNWGLBINDTEXIMAGEARBPROC) (HPBUFFERARB hPbuffer, int iBuffer);
+  typedef BOOL (WINAPI * PFNWGLRELEASETEXIMAGEARBPROC) (HPBUFFERARB hPbuffer, int iBuffer);
+  typedef BOOL (WINAPI * PFNWGLSETPBUFFERATTRIBARBPROC) (HPBUFFERARB hPbuffer, const int *piAttribList);
+#endif
+
+#ifndef WGL_ARB_pixel_format_float
+#define WGL_ARB_pixel_format_float 1
+#endif
+
+#ifndef WGL_EXT_display_color_table
+#define WGL_EXT_display_color_table 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+  extern GLboolean WINAPI wglCreateDisplayColorTableEXT (GLushort);
+  extern GLboolean WINAPI wglLoadDisplayColorTableEXT (const GLushort *, GLuint);
+  extern GLboolean WINAPI wglBindDisplayColorTableEXT (GLushort);
+  extern VOID WINAPI wglDestroyDisplayColorTableEXT (GLushort);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+  typedef GLboolean (WINAPI * PFNWGLCREATEDISPLAYCOLORTABLEEXTPROC) (GLushort id);
+  typedef GLboolean (WINAPI * PFNWGLLOADDISPLAYCOLORTABLEEXTPROC) (const GLushort *table, GLuint length);
+  typedef GLboolean (WINAPI * PFNWGLBINDDISPLAYCOLORTABLEEXTPROC) (GLushort id);
+  typedef VOID (WINAPI * PFNWGLDESTROYDISPLAYCOLORTABLEEXTPROC) (GLushort id);
+#endif
+
+#ifndef WGL_EXT_extensions_string
+#define WGL_EXT_extensions_string 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+  extern const char * WINAPI wglGetExtensionsStringEXT (void);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+  typedef const char * (WINAPI * PFNWGLGETEXTENSIONSSTRINGEXTPROC) (void);
+#endif
+
+#ifndef WGL_EXT_make_current_read
+#define WGL_EXT_make_current_read 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+  extern BOOL WINAPI wglMakeContextCurrentEXT (HDC, HDC, HGLRC);
+  extern HDC WINAPI wglGetCurrentReadDCEXT (void);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+  typedef BOOL (WINAPI * PFNWGLMAKECONTEXTCURRENTEXTPROC) (HDC hDrawDC, HDC hReadDC, HGLRC hglrc);
+  typedef HDC (WINAPI * PFNWGLGETCURRENTREADDCEXTPROC) (void);
+#endif
+
+#ifndef WGL_EXT_pbuffer
+#define WGL_EXT_pbuffer 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+  extern HPBUFFEREXT WINAPI wglCreatePbufferEXT (HDC, int, int, int, const int *);
+  extern HDC WINAPI wglGetPbufferDCEXT (HPBUFFEREXT);
+  extern int WINAPI wglReleasePbufferDCEXT (HPBUFFEREXT, HDC);
+  extern BOOL WINAPI wglDestroyPbufferEXT (HPBUFFEREXT);
+  extern BOOL WINAPI wglQueryPbufferEXT (HPBUFFEREXT, int, int *);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+  typedef HPBUFFEREXT (WINAPI * PFNWGLCREATEPBUFFEREXTPROC) (HDC hDC, int iPixelFormat, int iWidth, int iHeight, const int *piAttribList);
+  typedef HDC (WINAPI * PFNWGLGETPBUFFERDCEXTPROC) (HPBUFFEREXT hPbuffer);
+  typedef int (WINAPI * PFNWGLRELEASEPBUFFERDCEXTPROC) (HPBUFFEREXT hPbuffer, HDC hDC);
+  typedef BOOL (WINAPI * PFNWGLDESTROYPBUFFEREXTPROC) (HPBUFFEREXT hPbuffer);
+  typedef BOOL (WINAPI * PFNWGLQUERYPBUFFEREXTPROC) (HPBUFFEREXT hPbuffer, int iAttribute, int *piValue);
+#endif
+
+#ifndef WGL_EXT_pixel_format
+#define WGL_EXT_pixel_format 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+  extern BOOL WINAPI wglGetPixelFormatAttribivEXT (HDC, int, int, UINT, int *, int *);
+  extern BOOL WINAPI wglGetPixelFormatAttribfvEXT (HDC, int, int, UINT, int *, FLOAT *);
+  extern BOOL WINAPI wglChoosePixelFormatEXT (HDC, const int *, const FLOAT *, UINT, int *, UINT *);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+  typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVEXTPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, int *piAttributes, int *piValues);
+  typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBFVEXTPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, int *piAttributes, FLOAT *pfValues);
+  typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATEXTPROC) (HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
+#endif
+
+#ifndef WGL_EXT_swap_control
+#define WGL_EXT_swap_control 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+  extern BOOL WINAPI wglSwapIntervalEXT (int);
+  extern int WINAPI wglGetSwapIntervalEXT (void);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+  typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
+  typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
+#endif
+
+#ifndef WGL_EXT_depth_float
+#define WGL_EXT_depth_float 1
+#endif
+
+#ifndef WGL_NV_vertex_array_range
+#define WGL_NV_vertex_array_range 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+  extern void* WINAPI wglAllocateMemoryNV (GLsizei, GLfloat, GLfloat, GLfloat);
+  extern void WINAPI wglFreeMemoryNV (void *);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+  typedef void* (WINAPI * PFNWGLALLOCATEMEMORYNVPROC) (GLsizei size, GLfloat readfreq, GLfloat writefreq, GLfloat priority);
+  typedef void (WINAPI * PFNWGLFREEMEMORYNVPROC) (void *pointer);
+#endif
+
+#ifndef WGL_3DFX_multisample
+#define WGL_3DFX_multisample 1
+#endif
+
+#ifndef WGL_EXT_multisample
+#define WGL_EXT_multisample 1
+#endif
+
+#ifndef WGL_OML_sync_control
+#define WGL_OML_sync_control 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+  extern BOOL WINAPI wglGetSyncValuesOML (HDC, INT64 *, INT64 *, INT64 *);
+  extern BOOL WINAPI wglGetMscRateOML (HDC, INT32 *, INT32 *);
+  extern INT64 WINAPI wglSwapBuffersMscOML (HDC, INT64, INT64, INT64);
+  extern INT64 WINAPI wglSwapLayerBuffersMscOML (HDC, int, INT64, INT64, INT64);
+  extern BOOL WINAPI wglWaitForMscOML (HDC, INT64, INT64, INT64, INT64 *, INT64 *, INT64 *);
+  extern BOOL WINAPI wglWaitForSbcOML (HDC, INT64, INT64 *, INT64 *, INT64 *);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+  typedef BOOL (WINAPI * PFNWGLGETSYNCVALUESOMLPROC) (HDC hdc, INT64 *ust, INT64 *msc, INT64 *sbc);
+  typedef BOOL (WINAPI * PFNWGLGETMSCRATEOMLPROC) (HDC hdc, INT32 *numerator, INT32 *denominator);
+  typedef INT64 (WINAPI * PFNWGLSWAPBUFFERSMSCOMLPROC) (HDC hdc, INT64 target_msc, INT64 divisor, INT64 remainder);
+  typedef INT64 (WINAPI * PFNWGLSWAPLAYERBUFFERSMSCOMLPROC) (HDC hdc, int fuPlanes, INT64 target_msc, INT64 divisor, INT64 remainder);
+  typedef BOOL (WINAPI * PFNWGLWAITFORMSCOMLPROC) (HDC hdc, INT64 target_msc, INT64 divisor, INT64 remainder, INT64 *ust, INT64 *msc, INT64 *sbc);
+  typedef BOOL (WINAPI * PFNWGLWAITFORSBCOMLPROC) (HDC hdc, INT64 target_sbc, INT64 *ust, INT64 *msc, INT64 *sbc);
+#endif
+
+#ifndef WGL_I3D_digital_video_control
+#define WGL_I3D_digital_video_control 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+  extern BOOL WINAPI wglGetDigitalVideoParametersI3D (HDC, int, int *);
+  extern BOOL WINAPI wglSetDigitalVideoParametersI3D (HDC, int, const int *);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+  typedef BOOL (WINAPI * PFNWGLGETDIGITALVIDEOPARAMETERSI3DPROC) (HDC hDC, int iAttribute, int *piValue);
+  typedef BOOL (WINAPI * PFNWGLSETDIGITALVIDEOPARAMETERSI3DPROC) (HDC hDC, int iAttribute, const int *piValue);
+#endif
+
+#ifndef WGL_I3D_gamma
+#define WGL_I3D_gamma 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+  extern BOOL WINAPI wglGetGammaTableParametersI3D (HDC, int, int *);
+  extern BOOL WINAPI wglSetGammaTableParametersI3D (HDC, int, const int *);
+  extern BOOL WINAPI wglGetGammaTableI3D (HDC, int, USHORT *, USHORT *, USHORT *);
+  extern BOOL WINAPI wglSetGammaTableI3D (HDC, int, const USHORT *, const USHORT *, const USHORT *);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+  typedef BOOL (WINAPI * PFNWGLGETGAMMATABLEPARAMETERSI3DPROC) (HDC hDC, int iAttribute, int *piValue);
+  typedef BOOL (WINAPI * PFNWGLSETGAMMATABLEPARAMETERSI3DPROC) (HDC hDC, int iAttribute, const int *piValue);
+  typedef BOOL (WINAPI * PFNWGLGETGAMMATABLEI3DPROC) (HDC hDC, int iEntries, USHORT *puRed, USHORT *puGreen, USHORT *puBlue);
+  typedef BOOL (WINAPI * PFNWGLSETGAMMATABLEI3DPROC) (HDC hDC, int iEntries, const USHORT *puRed, const USHORT *puGreen, const USHORT *puBlue);
+#endif
+
+#ifndef WGL_I3D_genlock
+#define WGL_I3D_genlock 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+  extern BOOL WINAPI wglEnableGenlockI3D (HDC);
+  extern BOOL WINAPI wglDisableGenlockI3D (HDC);
+  extern BOOL WINAPI wglIsEnabledGenlockI3D (HDC, BOOL *);
+  extern BOOL WINAPI wglGenlockSourceI3D (HDC, UINT);
+  extern BOOL WINAPI wglGetGenlockSourceI3D (HDC, UINT *);
+  extern BOOL WINAPI wglGenlockSourceEdgeI3D (HDC, UINT);
+  extern BOOL WINAPI wglGetGenlockSourceEdgeI3D (HDC, UINT *);
+  extern BOOL WINAPI wglGenlockSampleRateI3D (HDC, UINT);
+  extern BOOL WINAPI wglGetGenlockSampleRateI3D (HDC, UINT *);
+  extern BOOL WINAPI wglGenlockSourceDelayI3D (HDC, UINT);
+  extern BOOL WINAPI wglGetGenlockSourceDelayI3D (HDC, UINT *);
+  extern BOOL WINAPI wglQueryGenlockMaxSourceDelayI3D (HDC, UINT *, UINT *);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+  typedef BOOL (WINAPI * PFNWGLENABLEGENLOCKI3DPROC) (HDC hDC);
+  typedef BOOL (WINAPI * PFNWGLDISABLEGENLOCKI3DPROC) (HDC hDC);
+  typedef BOOL (WINAPI * PFNWGLISENABLEDGENLOCKI3DPROC) (HDC hDC, BOOL *pFlag);
+  typedef BOOL (WINAPI * PFNWGLGENLOCKSOURCEI3DPROC) (HDC hDC, UINT uSource);
+  typedef BOOL (WINAPI * PFNWGLGETGENLOCKSOURCEI3DPROC) (HDC hDC, UINT *uSource);
+  typedef BOOL (WINAPI * PFNWGLGENLOCKSOURCEEDGEI3DPROC) (HDC hDC, UINT uEdge);
+  typedef BOOL (WINAPI * PFNWGLGETGENLOCKSOURCEEDGEI3DPROC) (HDC hDC, UINT *uEdge);
+  typedef BOOL (WINAPI * PFNWGLGENLOCKSAMPLERATEI3DPROC) (HDC hDC, UINT uRate);
+  typedef BOOL (WINAPI * PFNWGLGETGENLOCKSAMPLERATEI3DPROC) (HDC hDC, UINT *uRate);
+  typedef BOOL (WINAPI * PFNWGLGENLOCKSOURCEDELAYI3DPROC) (HDC hDC, UINT uDelay);
+  typedef BOOL (WINAPI * PFNWGLGETGENLOCKSOURCEDELAYI3DPROC) (HDC hDC, UINT *uDelay);
+  typedef BOOL (WINAPI * PFNWGLQUERYGENLOCKMAXSOURCEDELAYI3DPROC) (HDC hDC, UINT *uMaxLineDelay, UINT *uMaxPixelDelay);
+#endif
+
+#ifndef WGL_I3D_image_buffer
+#define WGL_I3D_image_buffer 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+  extern LPVOID WINAPI wglCreateImageBufferI3D (HDC, DWORD, UINT);
+  extern BOOL WINAPI wglDestroyImageBufferI3D (HDC, LPVOID);
+  extern BOOL WINAPI wglAssociateImageBufferEventsI3D (HDC, const HANDLE *, const LPVOID *, const DWORD *, UINT);
+  extern BOOL WINAPI wglReleaseImageBufferEventsI3D (HDC, const LPVOID *, UINT);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+  typedef LPVOID (WINAPI * PFNWGLCREATEIMAGEBUFFERI3DPROC) (HDC hDC, DWORD dwSize, UINT uFlags);
+  typedef BOOL (WINAPI * PFNWGLDESTROYIMAGEBUFFERI3DPROC) (HDC hDC, LPVOID pAddress);
+  typedef BOOL (WINAPI * PFNWGLASSOCIATEIMAGEBUFFEREVENTSI3DPROC) (HDC hDC, const HANDLE *pEvent, const LPVOID *pAddress, const DWORD *pSize, UINT count);
+  typedef BOOL (WINAPI * PFNWGLRELEASEIMAGEBUFFEREVENTSI3DPROC) (HDC hDC, const LPVOID *pAddress, UINT count);
+#endif
+
+#ifndef WGL_I3D_swap_frame_lock
+#define WGL_I3D_swap_frame_lock 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+  extern BOOL WINAPI wglEnableFrameLockI3D (void);
+  extern BOOL WINAPI wglDisableFrameLockI3D (void);
+  extern BOOL WINAPI wglIsEnabledFrameLockI3D (BOOL *);
+  extern BOOL WINAPI wglQueryFrameLockMasterI3D (BOOL *);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+  typedef BOOL (WINAPI * PFNWGLENABLEFRAMELOCKI3DPROC) (void);
+  typedef BOOL (WINAPI * PFNWGLDISABLEFRAMELOCKI3DPROC) (void);
+  typedef BOOL (WINAPI * PFNWGLISENABLEDFRAMELOCKI3DPROC) (BOOL *pFlag);
+  typedef BOOL (WINAPI * PFNWGLQUERYFRAMELOCKMASTERI3DPROC) (BOOL *pFlag);
+#endif
+
+#ifndef WGL_I3D_swap_frame_usage
+#define WGL_I3D_swap_frame_usage 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+  extern BOOL WINAPI wglGetFrameUsageI3D (float *);
+  extern BOOL WINAPI wglBeginFrameTrackingI3D (void);
+  extern BOOL WINAPI wglEndFrameTrackingI3D (void);
+  extern BOOL WINAPI wglQueryFrameTrackingI3D (DWORD *, DWORD *, float *);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+  typedef BOOL (WINAPI * PFNWGLGETFRAMEUSAGEI3DPROC) (float *pUsage);
+  typedef BOOL (WINAPI * PFNWGLBEGINFRAMETRACKINGI3DPROC) (void);
+  typedef BOOL (WINAPI * PFNWGLENDFRAMETRACKINGI3DPROC) (void);
+  typedef BOOL (WINAPI * PFNWGLQUERYFRAMETRACKINGI3DPROC) (DWORD *pFrameCount, DWORD *pMissedFrames, float *pLastMissedUsage);
+#endif
+
+#ifndef WGL_ATI_pixel_format_float
+#define WGL_ATI_pixel_format_float 1
+#endif
+
+#ifndef WGL_NV_render_depth_texture
+#define WGL_NV_render_depth_texture 1
+#endif
+
+#ifndef WGL_NV_render_texture_rectangle
+#define WGL_NV_render_texture_rectangle 1
+#endif
+
+#ifndef WGL_NV_float_buffer
+#define WGL_NV_float_buffer 1
+#endif
+
+#ifndef WGL_NV_swap_group
+#define WGL_NV_swap_group 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+  extern BOOL WINAPI wglJoinSwapGroupNV(HDC hDC, GLuint group);
+  extern BOOL WINAPI wglBindSwapBarrierNV(GLuint group, GLuint barrier);
+  extern BOOL WINAPI wglQuerySwapGroupNV(HDC hDC GLuint *group, GLuint *barrier);
+  extern BOOL WINAPI wglQueryMaxSwapGroupsNV(HDC hDC, GLuint *maxGroups, GLuint *maxBarriers);
+  extern BOOL WINAPI wglQueryFrameCountNV(HDC hDC, GLuint *count);
+  extern BOOL WINAPI wglResetFrameCountNV(HDC hDC);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+  typedef BOOL (WINAPI * PFNWGLJOINSWAPGROUPNVPROC) (HDC hDC, GLuint group);
+  typedef BOOL (WINAPI * PFNWGLBINDSWAPBARRIERNVPROC) (GLuint group, GLuint barrier);
+  typedef BOOL (WINAPI * PFNWGLQUERYSWAPGROUPNVPROC) (HDC hDC, GLuint *group, GLuint *barrier);
+  typedef BOOL (WINAPI * PFNWGLQUERYMAXSWAPGROUPSNVPROC) (HDC hDC, GLuint *maxGroups, GLuint *maxBarriers);
+  typedef BOOL (WINAPI * PFNWGLQUERYFRAMECOUNTNVPROC) (HDC hDC, GLuint *count);
+  typedef BOOL (WINAPI * PFNWGLRESETFRAMECOUNTNVPROC) (HDC hDC);
+#endif
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/print-test-results.sh b/print-test-results.sh
new file mode 100755
index 0000000..d3c41af
--- /dev/null
+++ b/print-test-results.sh
@@ -0,0 +1,64 @@
+#!/bin/bash
+
+ret=0
+
+tests=( query misc gdal wxs renderers )
+command_exists () {
+   type "$1" &> /dev/null ;
+}
+
+DIFF=diff
+COMPARE=
+if command_exists colordiff ; then
+   DIFF="colordiff"
+fi
+if command_exists compare ; then
+   COMPARE="compare"
+fi
+
+for testcase in "${tests[@]}"; do
+   cd msautotest/$testcase
+   if [ ! -d result ]; then
+      #"result" directory does not exist, all tests passed
+      cd ../..
+      continue
+   fi
+   cd result
+   rm -f *.aux.xml
+   #leftover .aux.xml files are valid for some gdal tests
+   failedtests=`find . -type f -printf "%f\n" `
+   if [ -z "$failedtests" ]; then
+      cd ../../..
+      continue
+   fi
+   #we have some failing tests
+   ret=1
+   for failedtest in $failedtests; do
+      echo ""
+      echo "######################################"
+      echo "# $testcase => $failedtest"
+      echo "######################################"
+      #for txt, gml and xml files, print a diff
+      if echo "$failedtest" | egrep -q "(txt|xml|gml)$"; then
+        $DIFF -u "../expected/$failedtest" "$failedtest"
+      fi
+      if echo "$failedtest" | egrep -q "(png|gif|tif)$"; then
+        if echo "$failedtest" | egrep -v -q "\\.diff\\.png$"; then
+           if [ -n $COMPARE ]; then
+              $COMPARE ../expected/$failedtest $failedtest -compose Src $failedtest.diff.png
+           fi
+        fi
+      fi
+   done
+   cd ../../..
+done
+
+if test "$ret" -eq "0"; then
+   echo ""
+   echo "######################################"
+   echo "#       All tests passed             #"
+   echo "######################################"
+   echo ""
+fi
+
+exit $ret
diff --git a/renderers/agg/include/agg_conv_clipper.h b/renderers/agg/include/agg_conv_clipper.h
index f5610a0..6db881d 100644
--- a/renderers/agg/include/agg_conv_clipper.h
+++ b/renderers/agg/include/agg_conv_clipper.h
@@ -24,7 +24,7 @@ namespace mapserver
 {
   enum clipper_op_e { clipper_or,
     clipper_and, clipper_xor, clipper_a_minus_b, clipper_b_minus_a };
-  enum clipper_PolyFillType {clipper_even_odd, clipper_non_zero};
+  enum clipper_PolyFillType {clipper_even_odd, clipper_non_zero, clipper_positive, clipper_negative};
 
   template<class VSA, class VSB> class conv_clipper
   {
@@ -41,11 +41,11 @@ namespace mapserver
     int										m_contour;
 	int										m_scaling_factor;
     clipper_op_e							m_operation;
-    pod_bvector<clipper::IntPoint, 8>		m_vertex_accumulator;
-    clipper::Polygons						m_poly_a;
-    clipper::Polygons						m_poly_b;
-    clipper::Polygons						m_result;
-    clipper::Clipper						m_clipper;
+    pod_bvector<ClipperLib::IntPoint, 8>		m_vertex_accumulator;
+    ClipperLib::Polygons						m_poly_a;
+    ClipperLib::Polygons						m_poly_b;
+    ClipperLib::Polygons						m_result;
+    ClipperLib::Clipper						m_clipper;
     clipper_PolyFillType					m_subjFillType;
     clipper_PolyFillType					m_clipFillType;
 
@@ -91,9 +91,9 @@ namespace mapserver
     bool next_vertex(double* x, double* y);
     void start_extracting();
     void add_vertex_(double &x, double &y);
-    void end_contour(clipper::Polygons &p);
+    void end_contour(ClipperLib::Polygons &p);
 
-	template<class VS> void add(VS &src, clipper::Polygons &p){
+	template<class VS> void add(VS &src, ClipperLib::Polygons &p){
 		unsigned cmd;
 		double x; double y; double start_x; double start_y;
 		bool starting_first_line;
@@ -149,46 +149,57 @@ namespace mapserver
     add( m_src_b , m_poly_b );
     m_result.resize(0);
 
-    clipper::PolyFillType pftSubj = (m_subjFillType == clipper_even_odd) ?
-      clipper::pftEvenOdd : clipper::pftNonZero;
-    clipper::PolyFillType pftClip = (m_clipFillType == clipper_even_odd) ?
-      clipper::pftEvenOdd : clipper::pftNonZero;
+    ClipperLib::PolyFillType pftSubj, pftClip;
+    switch (m_subjFillType)
+    {
+      case clipper_even_odd: pftSubj = ClipperLib::pftEvenOdd; break;
+      case clipper_non_zero: pftSubj = ClipperLib::pftNonZero; break;
+      case clipper_positive: pftSubj = ClipperLib::pftPositive; break;
+      default: pftSubj = ClipperLib::pftNegative;
+    }
+    switch (m_clipFillType)
+    {
+      case clipper_even_odd: pftClip = ClipperLib::pftEvenOdd; break;
+      case clipper_non_zero: pftClip = ClipperLib::pftNonZero; break;
+      case clipper_positive: pftClip = ClipperLib::pftPositive; break;
+      default: pftClip = ClipperLib::pftNegative;
+    }
 
     m_clipper.Clear();
     switch( m_operation ) {
       case clipper_or:
         {
-        m_clipper.AddPolygons( m_poly_a , clipper::ptSubject );
-        m_clipper.AddPolygons( m_poly_b , clipper::ptClip );
-        m_clipper.Execute( clipper::ctUnion , m_result , pftSubj, pftClip);
+        m_clipper.AddPolygons( m_poly_a , ClipperLib::ptSubject );
+        m_clipper.AddPolygons( m_poly_b , ClipperLib::ptClip );
+        m_clipper.Execute( ClipperLib::ctUnion , m_result , pftSubj, pftClip);
 		break;
         }
       case clipper_and:
         {
-        m_clipper.AddPolygons( m_poly_a , clipper::ptSubject );
-        m_clipper.AddPolygons( m_poly_b , clipper::ptClip );
-        m_clipper.Execute( clipper::ctIntersection , m_result, pftSubj, pftClip );
+        m_clipper.AddPolygons( m_poly_a , ClipperLib::ptSubject );
+        m_clipper.AddPolygons( m_poly_b , ClipperLib::ptClip );
+        m_clipper.Execute( ClipperLib::ctIntersection , m_result, pftSubj, pftClip );
 		break;
         }
       case clipper_xor:
         {
-        m_clipper.AddPolygons( m_poly_a , clipper::ptSubject );
-        m_clipper.AddPolygons( m_poly_b , clipper::ptClip );
-        m_clipper.Execute( clipper::ctXor , m_result, pftSubj, pftClip );
+        m_clipper.AddPolygons( m_poly_a , ClipperLib::ptSubject );
+        m_clipper.AddPolygons( m_poly_b , ClipperLib::ptClip );
+        m_clipper.Execute( ClipperLib::ctXor , m_result, pftSubj, pftClip );
 		break;
         }
       case clipper_a_minus_b:
         {
-        m_clipper.AddPolygons( m_poly_a , clipper::ptSubject );
-        m_clipper.AddPolygons( m_poly_b , clipper::ptClip );
-        m_clipper.Execute( clipper::ctDifference , m_result, pftSubj, pftClip );
+        m_clipper.AddPolygons( m_poly_a , ClipperLib::ptSubject );
+        m_clipper.AddPolygons( m_poly_b , ClipperLib::ptClip );
+        m_clipper.Execute( ClipperLib::ctDifference , m_result, pftSubj, pftClip );
 		break;
         }
       case clipper_b_minus_a:
         {
-        m_clipper.AddPolygons( m_poly_b , clipper::ptSubject );
-        m_clipper.AddPolygons( m_poly_a , clipper::ptClip );
-        m_clipper.Execute( clipper::ctDifference , m_result, pftSubj, pftClip );
+        m_clipper.AddPolygons( m_poly_b , ClipperLib::ptSubject );
+        m_clipper.AddPolygons( m_poly_a , ClipperLib::ptClip );
+        m_clipper.Execute( ClipperLib::ctDifference , m_result, pftSubj, pftClip );
 		break;
         }
     }
@@ -197,7 +208,7 @@ namespace mapserver
   //------------------------------------------------------------------------------
 
   template<class VSA, class VSB>
-  void conv_clipper<VSA, VSB>::end_contour( clipper::Polygons &p)
+  void conv_clipper<VSA, VSB>::end_contour( ClipperLib::Polygons &p)
   {
   unsigned i, len;
 
@@ -214,7 +225,7 @@ namespace mapserver
   template<class VSA, class VSB> 
   void conv_clipper<VSA, VSB>::add_vertex_(double &x, double &y)
   {
-	  clipper::IntPoint v;
+	  ClipperLib::IntPoint v;
 
 	  v.X = Round(x * m_scaling_factor);
 	  v.Y = Round(y * m_scaling_factor);
diff --git a/renderers/agg/include/agg_renderer_outline_aa.h b/renderers/agg/include/agg_renderer_outline_aa.h
index 5ff3f20..7a14588 100644
--- a/renderers/agg/include/agg_renderer_outline_aa.h
+++ b/renderers/agg/include/agg_renderer_outline_aa.h
@@ -1365,7 +1365,6 @@ namespace mapserver
         //---------------------------------------------------------------------
         void profile(const line_profile_aa& prof) { m_profile = &prof; }
         const line_profile_aa& profile() const { return *m_profile; }
-        line_profile_aa& profile() { return *m_profile; }
 
         //---------------------------------------------------------------------
         int subpixel_width() const { return m_profile->subpixel_width(); }
diff --git a/renderers/agg/include/clipper.hpp b/renderers/agg/include/clipper.hpp
index ad1ebe7..a56a461 100644
--- a/renderers/agg/include/clipper.hpp
+++ b/renderers/agg/include/clipper.hpp
@@ -1,8 +1,8 @@
 /*******************************************************************************
 *                                                                              *
 * Author    :  Angus Johnson                                                   *
-* Version   :  4.2.0                                                           *
-* Date      :  11 April 2011                                                   *
+* Version   :  4.6.3                                                           *
+* Date      :  11 November 2011                                                *
 * Website   :  http://www.angusj.com                                           *
 * Copyright :  Angus Johnson 2010-2011                                         *
 *                                                                              *
@@ -21,6 +21,14 @@
 * Springer; 1 edition (January 4, 2005)                                        *
 * http://books.google.com/books?q=vatti+clipping+agoston                       *
 *                                                                              *
+* See also:                                                                    *
+* "Polygon Offsetting by Computing Winding Numbers"                            *
+* Paper no. DETC2005-85513 pp. 565-575                                         *
+* ASME 2005 International Design Engineering Technical Conferences             *
+* and Computers and Information in Engineering Conference (IDETC/CIE2005)      *
+* September 24–28, 2005 , Long Beach, California, USA                          *
+* http://www.me.berkeley.edu/~mcmains/pubs/DAC05OffsetPolygon.pdf              *
+*                                                                              *
 *******************************************************************************/
 
 #ifndef clipper_hpp
@@ -30,27 +38,50 @@
 #include <stdexcept>
 #include <cstring>
 #include <cstdlib>
+#include <ostream>
 
-namespace clipper {
+namespace ClipperLib {
 
 enum ClipType { ctIntersection, ctUnion, ctDifference, ctXor };
 enum PolyType { ptSubject, ptClip };
-enum PolyFillType { pftEvenOdd, pftNonZero };
+//By far the most widely used winding rules for polygon filling are
+//EvenOdd & NonZero (GDI, GDI+, XLib, OpenGL, Cairo, AGG, Quartz, SVG, Gr32)
+//Others rules include Positive, Negative and ABS_GTR_EQ_TWO (only in OpenGL)
+//see http://glprogramming.com/red/chapter11.html
+enum PolyFillType { pftEvenOdd, pftNonZero, pftPositive, pftNegative };
 
 typedef signed long long long64;
+typedef unsigned long long ulong64;
 
 struct IntPoint {
+public:
   long64 X;
   long64 Y;
   IntPoint(long64 x = 0, long64 y = 0): X(x), Y(y) {};
+  friend std::ostream& operator <<(std::ostream &s, IntPoint &p);
 };
 
 typedef std::vector< IntPoint > Polygon;
 typedef std::vector< Polygon > Polygons;
 
-bool IsClockwise(const Polygon &poly);
+std::ostream& operator <<(std::ostream &s, Polygon &p);
+std::ostream& operator <<(std::ostream &s, Polygons &p);
+
+struct ExPolygon {
+  Polygon  outer;
+  Polygons holes;
+};
+typedef std::vector< ExPolygon > ExPolygons;
+
+enum JoinType { jtSquare, jtMiter, jtRound };
+
+bool Orientation(const Polygon &poly);
 double Area(const Polygon &poly);
-Polygons OffsetPolygons(const Polygons &pts, const float &delta);
+void OffsetPolygons(const Polygons &in_polys, Polygons &out_polys,
+  double delta, JoinType jointype = jtSquare, double MiterLimit = 2);
+
+void ReversePoints(Polygon& p);
+void ReversePoints(Polygons& p);
 
 //used internally ...
 enum EdgeSide { esLeft, esRight };
@@ -88,22 +119,35 @@ struct IntersectNode {
 };
 
 struct LocalMinima {
-  long64          Y;
+  long64        Y;
   TEdge        *leftBound;
   TEdge        *rightBound;
   LocalMinima  *next;
 };
 
 struct Scanbeam {
-  long64       Y;
+  long64    Y;
   Scanbeam *next;
 };
 
-struct PolyPt {
+struct OutPt; //forward declaration
+
+struct OutRec {
+  int     idx;
+  bool    isHole;
+  OutRec *FirstLeft;
+  OutRec *AppendLink;
+  OutPt  *pts;
+  OutPt  *bottomPt;
+  TEdge  *bottomE1;
+  TEdge  *bottomE2;
+};
+
+struct OutPt {
+  int     idx;
   IntPoint pt;
-  PolyPt  *next;
-  PolyPt  *prev;
-  bool     isHole;
+  OutPt   *next;
+  OutPt   *prev;
 };
 
 struct JoinRec {
@@ -116,13 +160,13 @@ struct JoinRec {
 };
 
 struct HorzJoinRec {
-  TEdge   *edge;
+  TEdge    *edge;
   int       savedIdx;
 };
 
 struct IntRect { long64 left; long64 top; long64 right; long64 bottom; };
 
-typedef std::vector < PolyPt* > PolyPtList;
+typedef std::vector < OutRec* > PolyOutList;
 typedef std::vector < TEdge* > EdgeList;
 typedef std::vector < JoinRec* > JoinList;
 typedef std::vector < HorzJoinRec* > HorzJoinList;
@@ -145,10 +189,10 @@ protected:
   void PopLocalMinima();
   virtual void Reset();
   void InsertLocalMinima(LocalMinima *newLm);
-  LocalMinima           *m_CurrentLM;
-  LocalMinima           *m_MinimaList;
-private:
-  EdgeList               m_edges;
+  LocalMinima      *m_CurrentLM;
+  LocalMinima      *m_MinimaList;
+  bool              m_UseFullRange;
+  EdgeList          m_edges;
 };
 
 class Clipper : public virtual ClipperBase
@@ -157,13 +201,21 @@ public:
   Clipper();
   ~Clipper();
   bool Execute(ClipType clipType,
-    Polygons &solution,
-    PolyFillType subjFillType = pftEvenOdd,
-    PolyFillType clipFillType = pftEvenOdd);
+  Polygons &solution,
+  PolyFillType subjFillType = pftEvenOdd,
+  PolyFillType clipFillType = pftEvenOdd);
+  bool Execute(ClipType clipType,
+  ExPolygons &solution,
+  PolyFillType subjFillType = pftEvenOdd,
+  PolyFillType clipFillType = pftEvenOdd);
+  void Clear();
+  bool ReverseSolution() {return m_ReverseOutput;};
+  void ReverseSolution(bool value) {m_ReverseOutput = value;};
 protected:
   void Reset();
+  virtual bool ExecuteInternal(bool fixHoleLinkages);
 private:
-  PolyPtList        m_PolyPts;
+  PolyOutList       m_PolyOuts;
   JoinList          m_Joins;
   HorzJoinList      m_HorizJoins;
   ClipType          m_ClipType;
@@ -174,10 +226,11 @@ private:
   bool              m_ExecuteLocked;
   PolyFillType      m_ClipFillType;
   PolyFillType      m_SubjFillType;
+  bool              m_ReverseOutput;
   void DisposeScanbeamList();
   void SetWindingCount(TEdge& edge);
-  bool IsNonZeroFillType(const TEdge& edge) const;
-  bool IsNonZeroAltFillType(const TEdge& edge) const;
+  bool IsEvenOddFillType(const TEdge& edge) const;
+  bool IsEvenOddAltFillType(const TEdge& edge) const;
   void InsertScanbeam(const long64 Y);
   long64 PopScanbeam();
   void InsertLocalMinimaIntoAEL(const long64 botY);
@@ -202,23 +255,30 @@ private:
   void DoBothEdges(TEdge *edge1, TEdge *edge2, const IntPoint &pt);
   void IntersectEdges(TEdge *e1, TEdge *e2,
     const IntPoint &pt, IntersectProtects protects);
-  PolyPt* AddPolyPt(TEdge *e, const IntPoint &pt);
+  OutRec* CreateOutRec();
+  void AddOutPt(TEdge *e, TEdge *altE, const IntPoint &pt);
   void DisposeAllPolyPts();
-  bool ProcessIntersections( const long64 topY);
+  void DisposeOutRec(PolyOutList::size_type index, bool ignorePts = false);
+  bool ProcessIntersections(const long64 botY, const long64 topY);
   void AddIntersectNode(TEdge *e1, TEdge *e2, const IntPoint &pt);
-  void BuildIntersectList(const long64 topY);
+  void BuildIntersectList(const long64 botY, const long64 topY);
   void ProcessIntersectList();
   void ProcessEdgesAtTopOfScanbeam(const long64 topY);
-  void BuildResult(Polygons& polypoly);
+  void BuildResult(Polygons& polys);
+  void BuildResultEx(ExPolygons& polys);
+  void SetHoleState(TEdge *e, OutRec *OutRec);
   void DisposeIntersectNodes();
   bool FixupIntersections();
+  void FixupOutPolygon(OutRec &outRec);
   bool IsHole(TEdge *e);
-  void AddJoin(TEdge *e1, TEdge *e2, int e1OutIdx = -1);
+  void FixHoleLinkage(OutRec *outRec);
+  void CheckHoleLinkages1(OutRec *outRec1, OutRec *outRec2);
+  void CheckHoleLinkages2(OutRec *outRec1, OutRec *outRec2);
+  void AddJoin(TEdge *e1, TEdge *e2, int e1OutIdx = -1, int e2OutIdx = -1);
   void ClearJoins();
   void AddHorzJoin(TEdge *e, int idx);
   void ClearHorzJoins();
-  void JoinCommonEdges();
-
+  void JoinCommonEdges(bool fixHoleLinkages);
 };
 
 //------------------------------------------------------------------------------
@@ -227,17 +287,16 @@ private:
 class clipperException : public std::exception
 {
   public:
-    clipperException(const char* description)
-      throw(): std::exception(), m_description (description) {}
+    clipperException(const char* description): m_descr(description) {}
     virtual ~clipperException() throw() {}
-    virtual const char* what() const throw() {return m_description.c_str();}
+    virtual const char* what() const throw() {return m_descr.c_str();}
   private:
-    std::string m_description;
+    std::string m_descr;
 };
 //------------------------------------------------------------------------------
-//------------------------------------------------------------------------------
 
-} //clipper namespace
+} //ClipperLib namespace
+
 #endif //clipper_hpp
 
 
diff --git a/renderers/agg/src/agg_font_freetype.cpp b/renderers/agg/src/agg_font_freetype.cpp
index e7ccaef..0663861 100644
--- a/renderers/agg/src/agg_font_freetype.cpp
+++ b/renderers/agg/src/agg_font_freetype.cpp
@@ -664,10 +664,14 @@ namespace mapserver
                     m_name = 0;
                 }
                 if( FT_Select_Charmap(m_cur_face, FT_ENCODING_UNICODE) ) {
-                    if( FT_Select_Charmap(m_cur_face, FT_ENCODING_APPLE_ROMAN) ) {
-                        m_char_map = FT_ENCODING_NONE;
+                    if( FT_Select_Charmap(m_cur_face, FT_ENCODING_MS_SYMBOL) ) {
+                        if( FT_Select_Charmap(m_cur_face, FT_ENCODING_APPLE_ROMAN) ) {
+                            m_char_map = FT_ENCODING_NONE;
+                        } else {
+                            m_char_map = FT_ENCODING_APPLE_ROMAN;
+                        }
                     } else {
-                        m_char_map = FT_ENCODING_APPLE_ROMAN;
+                        m_char_map = FT_ENCODING_MS_SYMBOL;
                     }
                 } else {
                     m_char_map = FT_ENCODING_UNICODE;
@@ -909,6 +913,14 @@ namespace mapserver
     //------------------------------------------------------------------------
     bool font_engine_freetype_base::prepare_glyph(unsigned glyph_code)
     {
+        /* FT_ENCODING_MS_SYMBOL hack inspired from GD's gdft.c:  */
+        /* I do not know the significance of the constant 0xf000. */
+        /* It was determined by inspection of the character codes */
+        /* stored in Microsoft font symbol.ttf                    */
+        if (m_cur_face->charmap &&
+            m_cur_face->charmap->encoding == FT_ENCODING_MS_SYMBOL)
+            glyph_code |= 0xf000;
+
         m_glyph_index = FT_Get_Char_Index(m_cur_face, glyph_code);
         m_last_error = FT_Load_Glyph(m_cur_face, 
                                      m_glyph_index, 
diff --git a/renderers/agg/src/clipper.cpp b/renderers/agg/src/clipper.cpp
index 67c006c..daea1d4 100644
--- a/renderers/agg/src/clipper.cpp
+++ b/renderers/agg/src/clipper.cpp
@@ -1,8 +1,8 @@
 /*******************************************************************************
 *                                                                              *
 * Author    :  Angus Johnson                                                   *
-* Version   :  4.2.0                                                           *
-* Date      :  11 April 2011                                                   *
+* Version   :  4.6.3                                                           *
+* Date      :  11 November 2011                                                *
 * Website   :  http://www.angusj.com                                           *
 * Copyright :  Angus Johnson 2010-2011                                         *
 *                                                                              *
@@ -21,6 +21,14 @@
 * Springer; 1 edition (January 4, 2005)                                        *
 * http://books.google.com/books?q=vatti+clipping+agoston                       *
 *                                                                              *
+* See also:                                                                    *
+* "Polygon Offsetting by Computing Winding Numbers"                            *
+* Paper no. DETC2005-85513 pp. 565-575                                         *
+* ASME 2005 International Design Engineering Technical Conferences             *
+* and Computers and Information in Engineering Conference (IDETC/CIE2005)      *
+* September 24–28, 2005 , Long Beach, California, USA                          *
+* http://www.me.berkeley.edu/~mcmains/pubs/DAC05OffsetPolygon.pdf              *
+*                                                                              *
 *******************************************************************************/
 
 /*******************************************************************************
@@ -32,51 +40,346 @@
 
 #include "clipper.hpp"
 #include <cmath>
-#include <ctime>
 #include <vector>
 #include <algorithm>
 #include <stdexcept>
 #include <cstring>
 #include <cstdlib>
+#include <ostream>
 
-namespace clipper {
+namespace ClipperLib {
 
-static double const horizontal = -3.4E+38;
-static double const pi = 3.14159265359;
+static long64 const loRange = 1518500249;            //sqrt(2^63 -1)/2
+static long64 const hiRange = 6521908912666391106LL; //sqrt(2^127 -1)/2
+static double const pi = 3.141592653589793238;
 enum Direction { dRightToLeft, dLeftToRight };
-enum Position  { pFirst, pMiddle, pSecond };
+enum RangeTest { rtLo, rtHi, rtError };
+
+#define HORIZONTAL (-1.0E+40)
+#define TOLERANCE (1.0e-20)
+#define NEAR_ZERO(val) (((val) > -TOLERANCE) && ((val) < TOLERANCE))
+#define NEAR_EQUAL(a, b) NEAR_ZERO((a) - (b))
+
+inline long64 Abs(long64 val)
+{
+  if (val < 0) return -val; else return val;
+}
+//------------------------------------------------------------------------------
+
+//------------------------------------------------------------------------------
+// Int128 class (enables safe math on signed 64bit integers)
+// eg Int128 val1((long64)9223372036854775807); //ie 2^63 -1
+//    Int128 val2((long64)9223372036854775807);
+//    Int128 val3 = val1 * val2;
+//    val3.AsString => "85070591730234615847396907784232501249" (8.5e+37)
+//------------------------------------------------------------------------------
+
+class Int128
+{
+  public:
+
+    Int128(long64 _lo = 0)
+    {
+      hi = 0;
+      if (_lo < 0) {
+        lo = -_lo;
+        Negate(*this);
+      } else
+          lo = _lo;
+    }
+
+    Int128(const Int128 &val): hi(val.hi), lo(val.lo){}
+
+    long64 operator = (const long64 &val)
+    {
+      hi = 0;
+      lo = Abs(val);
+      if (val < 0) Negate(*this);
+      return val;
+    }
+
+    bool operator == (const Int128 &val) const
+      {return (hi == val.hi && lo == val.lo);}
+
+    bool operator != (const Int128 &val) const { return !(*this == val);}
+
+    bool operator > (const Int128 &val) const
+    {
+      if (hi > val.hi) return true;
+      else if (hi < val.hi) return false;
+      else return ulong64(lo) > ulong64(val.lo);
+    }
+
+    bool operator < (const Int128 &val) const
+    {
+      if (hi < val.hi) return true;
+      else if (hi > val.hi) return false;
+      else return ulong64(lo) < ulong64(val.lo);
+    }
+
+    Int128& operator += (const Int128 &rhs)
+    {
+      hi += rhs.hi;
+      lo += rhs.lo;
+      if (ulong64(lo) < ulong64(rhs.lo)) hi++;
+      return *this;
+    }
+
+    Int128 operator + (const Int128 &rhs) const
+    {
+      Int128 result(*this);
+      result+= rhs;
+      return result;
+    }
+
+    Int128& operator -= (const Int128 &rhs)
+    {
+      Int128 tmp(rhs);
+      Negate(tmp);
+      *this += tmp;
+      return *this;
+    }
+
+    Int128 operator - (const Int128 &rhs) const
+    {
+      Int128 result(*this);
+      result-= rhs;
+      return result;
+    }
+
+    Int128 operator * (const Int128 &rhs) const {
+      if ( !(hi == 0 || hi == -1) || !(rhs.hi == 0 || rhs.hi == -1))
+        throw "Int128 operator*: overflow error";
+      bool negate = (hi < 0) != (rhs.hi < 0);
+
+      Int128 tmp(*this);
+      if (tmp.hi < 0) Negate(tmp);
+      ulong64 int1Hi = ulong64(tmp.lo) >> 32;
+      ulong64 int1Lo = ulong64(tmp.lo & 0xFFFFFFFF);
+
+      tmp = rhs;
+      if (tmp.hi < 0) Negate(tmp);
+      ulong64 int2Hi = ulong64(tmp.lo) >> 32;
+      ulong64 int2Lo = ulong64(tmp.lo & 0xFFFFFFFF);
+
+      //nb: see comments in clipper.pas
+      ulong64 a = int1Hi * int2Hi;
+      ulong64 b = int1Lo * int2Lo;
+      ulong64 c = int1Hi * int2Lo + int1Lo * int2Hi;
+
+      tmp.hi = long64(a + (c >> 32));
+      tmp.lo = long64(c << 32);
+      tmp.lo += long64(b);
+      if (ulong64(tmp.lo) < b) tmp.hi++;
+      if (negate) Negate(tmp);
+      return tmp;
+    }
+
+    Int128 operator/ (const Int128 &rhs) const
+    {
+      if (rhs.lo == 0 && rhs.hi == 0)
+        throw "Int128 operator/: divide by zero";
+      bool negate = (rhs.hi < 0) != (hi < 0);
+      Int128 result(*this), denom(rhs);
+      if (result.hi < 0) Negate(result);
+      if (denom.hi < 0)  Negate(denom);
+      if (denom > result) return Int128(0); //result is only a fraction of 1
+      Negate(denom);
+
+      Int128 p(0);
+      for (int i = 0; i < 128; ++i)
+      {
+        p.hi = p.hi << 1;
+        if (p.lo < 0) p.hi++;
+        p.lo = long64(p.lo) << 1;
+        if (result.hi < 0) p.lo++;
+        result.hi = result.hi << 1;
+        if (result.lo < 0) result.hi++;
+        result.lo = long64(result.lo) << 1;
+        Int128 p2(p);
+        p += denom;
+        if (p.hi < 0) p = p2;
+        else result.lo++;
+      }
+      if (negate) Negate(result);
+      return result;
+    }
+
+    double AsDouble() const
+    {
+      const double shift64 = 18446744073709551616.0; //2^64
+      const double bit64 = 9223372036854775808.0;
+      if (hi < 0)
+      {
+        Int128 tmp(*this);
+        Negate(tmp);
+        if (tmp.lo < 0)
+          return (double)tmp.lo - bit64 - tmp.hi * shift64;
+        else
+          return -(double)tmp.lo - tmp.hi * shift64;
+      }
+      else if (lo < 0)
+        return -(double)lo + bit64 + hi * shift64;
+      else
+        return (double)lo + (double)hi * shift64;
+    }
+
+    //for bug testing ...
+    std::string AsString() const
+    {
+      std::string result;
+      unsigned char r = 0;
+      Int128 tmp(0), val(*this);
+      if (hi < 0) Negate(val);
+      result.resize(50);
+      std::string::size_type i = result.size() -1;
+      while (val.hi != 0 || val.lo != 0)
+      {
+        Div10(val, tmp, r);
+        result[i--] = char('0' + r);
+        val = tmp;
+      }
+      if (hi < 0) result[i--] = '-';
+      result.erase(0,i+1);
+      if (result.size() == 0) result = "0";
+      return result;
+    }
+
+private:
+    long64 hi;
+    long64 lo;
+
+    static void Negate(Int128 &val)
+    {
+      if (val.lo == 0)
+      {
+        if( val.hi == 0) return;
+        val.lo = ~val.lo;
+        val.hi = ~val.hi +1;
+      }
+      else
+      {
+        val.lo = ~val.lo +1;
+        val.hi = ~val.hi;
+      }
+    }
+
+    //debugging only ...
+    void Div10(const Int128 val, Int128& result, unsigned char & remainder) const
+    {
+      remainder = 0;
+      result = 0;
+      for (int i = 63; i >= 0; --i)
+      {
+        if ((val.hi & ((long64)1 << i)) != 0)
+          remainder = char((remainder * 2) + 1); else
+          remainder *= char(2);
+        if (remainder >= 10)
+        {
+          result.hi += ((long64)1 << i);
+          remainder -= char(10);
+        }
+      }
+      for (int i = 63; i >= 0; --i)
+      {
+        if ((val.lo & ((long64)1 << i)) != 0)
+          remainder = char((remainder * 2) + 1); else
+          remainder *= char(2);
+        if (remainder >= 10)
+        {
+          result.lo += ((long64)1 << i);
+          remainder -= char(10);
+        }
+      }
+    }
+};
 
 //------------------------------------------------------------------------------
 //------------------------------------------------------------------------------
 
-bool IsClockwise(const Polygon &poly)
+RangeTest TestRange(const Polygon &pts)
 {
-  int highI = poly.size() -1;
+  RangeTest result = rtLo;
+  for (Polygon::size_type i = 0; i <  pts.size(); ++i)
+  {
+    if (Abs(pts[i].X) > hiRange || Abs(pts[i].Y) > hiRange)
+        return rtError;
+      else if (Abs(pts[i].X) > loRange || Abs(pts[i].Y) > loRange)
+        result = rtHi;
+  }
+  return result;
+}
+//------------------------------------------------------------------------------
+
+bool Orientation(const Polygon &poly)
+{
+  int highI = (int)poly.size() -1;
   if (highI < 2) return false;
-  double a;
-  a = static_cast<double>(poly[highI].X) * static_cast<double>(poly[0].Y) -
-    static_cast<double>(poly[0].X) * static_cast<double>(poly[highI].Y);
-  for (int i = 0; i < highI; ++i)
-    a += static_cast<double>(poly[i].X) * static_cast<double>(poly[i+1].Y) -
-      static_cast<double>(poly[i+1].X) * static_cast<double>(poly[i].Y);
-  //area := area/2;
-  return a > 0; //ie reverse of normal formula because assume Y axis inverted
+  bool UseFullInt64Range = false;
+
+  int j = 0, jplus, jminus;
+  for (int i = 0; i <= highI; ++i)
+  {
+    if (Abs(poly[i].X) > hiRange || Abs(poly[i].Y) > hiRange)
+    throw "Coordinate exceeds range bounds.";
+    if (Abs(poly[i].X) > loRange || Abs(poly[i].Y) > loRange)
+    UseFullInt64Range = true;
+    if (poly[i].Y < poly[j].Y) continue;
+    if ((poly[i].Y > poly[j].Y || poly[i].X < poly[j].X)) j = i;
+  };
+  if (j == highI) jplus = 0;
+  else jplus = j +1;
+  if (j == 0) jminus = highI;
+  else jminus = j -1;
+
+  IntPoint vec1, vec2;
+  //get cross product of vectors of the edges adjacent to highest point ...
+  vec1.X = poly[j].X - poly[jminus].X;
+  vec1.Y = poly[j].Y - poly[jminus].Y;
+  vec2.X = poly[jplus].X - poly[j].X;
+  vec2.Y = poly[jplus].Y - poly[j].Y;
+
+  if (UseFullInt64Range)
+  {
+    Int128 cross = Int128(vec1.X) * Int128(vec2.Y) -
+      Int128(vec2.X) * Int128(vec1.Y);
+    return cross > 0;
+  }
+  else
+  {
+    return (vec1.X * vec2.Y - vec2.X * vec1.Y) > 0;
+  }
 }
 //------------------------------------------------------------------------------
 
-bool IsClockwise(PolyPt *pt)
+bool Orientation(OutRec *outRec, bool UseFullInt64Range)
 {
-  double a = 0;
-  PolyPt* startPt = pt;
-  do
+  OutPt *opBottom = outRec->pts, *op = outRec->pts->next;
+  while (op != outRec->pts)
+  {
+    if (op->pt.Y >= opBottom->pt.Y)
+    {
+      if (op->pt.Y > opBottom->pt.Y || op->pt.X < opBottom->pt.X)
+      opBottom = op;
+    }
+    op = op->next;
+  }
+
+  IntPoint vec1, vec2;
+  vec1.X = op->pt.X - op->prev->pt.X;
+  vec1.Y = op->pt.Y - op->prev->pt.Y;
+  vec2.X = op->next->pt.X - op->pt.X;
+  vec2.Y = op->next->pt.Y - op->pt.Y;
+
+  if (UseFullInt64Range)
+  {
+    Int128 cross = Int128(vec1.X) * Int128(vec2.Y) - Int128(vec2.X) * Int128(vec1.Y);
+    return cross > 0;
+  }
+  else
   {
-    a += static_cast<double>(pt->pt.X) * static_cast<double>(pt->next->pt.Y) -
-      static_cast<double>(pt->next->pt.X) * static_cast<double>(pt->pt.Y);
-    pt = pt->next;
+    return (vec1.X * vec2.Y - vec2.X * vec1.Y) > 0;
   }
-  while (pt != startPt);
-  //area = area /2;
-  return a > 0; //ie reverse of normal formula because Y axis inverted
 }
 //------------------------------------------------------------------------------
 
@@ -88,21 +391,44 @@ inline bool PointsEqual( const IntPoint &pt1, const IntPoint &pt2)
 
 double Area(const Polygon &poly)
 {
-  int highI = poly.size() -1;
+  int highI = (int)poly.size() -1;
   if (highI < 2) return 0;
-  double a;
-  a = static_cast<double>(poly[highI].X) * static_cast<double>(poly[0].Y) -
-    static_cast<double>(poly[0].X) * static_cast<double>(poly[highI].Y);
-  for (int i = 0; i < highI; ++i)
-    a += static_cast<double>(poly[i].X) * static_cast<double>(poly[i+1].Y) -
-      static_cast<double>(poly[i+1].X) * static_cast<double>(poly[i].Y);
-  return a/2;
+  bool UseFullInt64Range;
+  RangeTest rt = TestRange(poly);
+  switch (rt) {
+    case rtLo:
+      UseFullInt64Range = false;
+      break;
+    case rtHi:
+      UseFullInt64Range = true;
+      break;
+    default:
+      throw "Coordinate exceeds range bounds.";
+  }
+
+  if (UseFullInt64Range) {
+    Int128 a(0);
+    a = (Int128(poly[highI].X) * Int128(poly[0].Y)) -
+      Int128(poly[0].X) * Int128(poly[highI].Y);
+    for (int i = 0; i < highI; ++i)
+      a += Int128(poly[i].X) * Int128(poly[i+1].Y) -
+        Int128(poly[i+1].X) * Int128(poly[i].Y);
+    return a.AsDouble() / 2;
+  }
+  else
+  {
+    double a;
+    a = (double)poly[highI].X * poly[0].Y - (double)poly[0].X * poly[highI].Y;
+    for (int i = 0; i < highI; ++i)
+      a += (double)poly[i].X * poly[i+1].Y - (double)poly[i+1].X * poly[i].Y;
+    return a/2;
+  }
 }
 //------------------------------------------------------------------------------
 
-bool PointIsVertex(const IntPoint &pt, PolyPt *pp)
+bool PointIsVertex(const IntPoint &pt, OutPt *pp)
 {
-  PolyPt *pp2 = pp;
+  OutPt *pp2 = pp;
   do
   {
     if (PointsEqual(pp2->pt, pt)) return true;
@@ -113,54 +439,87 @@ bool PointIsVertex(const IntPoint &pt, PolyPt *pp)
 }
 //------------------------------------------------------------------------------
 
-bool PointInPolygon(const IntPoint &pt, PolyPt *pp)
+bool PointInPolygon(const IntPoint &pt, OutPt *pp, bool UseFullInt64Range)
 {
-  PolyPt *pp2 = pp;
+  OutPt *pp2 = pp;
   bool result = false;
-  do
+  if (UseFullInt64Range) {
+    do
+    {
+      if ((((pp2->pt.Y <= pt.Y) && (pt.Y < pp2->prev->pt.Y)) ||
+          ((pp2->prev->pt.Y <= pt.Y) && (pt.Y < pp2->pt.Y))) &&
+          Int128(pt.X - pp2->pt.X) < (Int128(pp2->prev->pt.X - pp2->pt.X) *
+          Int128(pt.Y - pp2->pt.Y)) / Int128(pp2->prev->pt.Y - pp2->pt.Y))
+            result = !result;
+      pp2 = pp2->next;
+    }
+    while (pp2 != pp);
+  }
+  else
   {
-    if ((((pp2->pt.Y <= pt.Y) && (pt.Y < pp2->prev->pt.Y)) ||
-      ((pp2->prev->pt.Y <= pt.Y) && (pt.Y < pp2->pt.Y))) &&
-      (pt.X - pp2->pt.X < (pp2->prev->pt.X - pp2->pt.X) * (pt.Y - pp2->pt.Y) /
-      (pp2->prev->pt.Y - pp2->pt.Y))) result = !result;
-    pp2 = pp2->next;
+    do
+    {
+      if ((((pp2->pt.Y <= pt.Y) && (pt.Y < pp2->prev->pt.Y)) ||
+        ((pp2->prev->pt.Y <= pt.Y) && (pt.Y < pp2->pt.Y))) &&
+        (pt.X < (pp2->prev->pt.X - pp2->pt.X) * (pt.Y - pp2->pt.Y) /
+        (pp2->prev->pt.Y - pp2->pt.Y) + pp2->pt.X )) result = !result;
+      pp2 = pp2->next;
+    }
+    while (pp2 != pp);
   }
-  while (pp2 != pp);
   return result;
 }
 //------------------------------------------------------------------------------
 
-bool SlopesEqual(TEdge &e1, TEdge &e2)
+bool SlopesEqual(TEdge &e1, TEdge &e2, bool UseFullInt64Range)
 {
   if (e1.ybot == e1.ytop) return (e2.ybot == e2.ytop);
-  else if (e2.ybot == e2.ytop) return false;
-  else return (e1.ytop - e1.ybot)*(e2.xtop - e2.xbot) -
-      (e1.xtop - e1.xbot)*(e2.ytop - e2.ybot) == 0;
+  else if (e1.xbot == e1.xtop) return (e2.xbot == e2.xtop);
+  else if (UseFullInt64Range)
+    return Int128(e1.ytop - e1.ybot) * Int128(e2.xtop - e2.xbot) ==
+      Int128(e1.xtop - e1.xbot) * Int128(e2.ytop - e2.ybot);
+  else return (e1.ytop - e1.ybot)*(e2.xtop - e2.xbot) ==
+      (e1.xtop - e1.xbot)*(e2.ytop - e2.ybot);
 }
 //------------------------------------------------------------------------------
 
-bool SlopesEqual(const IntPoint pt1, const IntPoint pt2, const IntPoint pt3)
+bool SlopesEqual(const IntPoint pt1, const IntPoint pt2,
+  const IntPoint pt3, bool UseFullInt64Range)
 {
   if (pt1.Y == pt2.Y) return (pt2.Y == pt3.Y);
-  else if (pt2.Y == pt3.Y) return false;
-  else return
-    (pt1.Y-pt2.Y)*(pt2.X-pt3.X) - (pt1.X-pt2.X)*(pt2.Y-pt3.Y) == 0;
+  else if (pt1.X == pt2.X) return (pt2.X == pt3.X);
+  else if (UseFullInt64Range)
+    return Int128(pt1.Y-pt2.Y) * Int128(pt2.X-pt3.X) ==
+      Int128(pt1.X-pt2.X) * Int128(pt2.Y-pt3.Y);
+  else return (pt1.Y-pt2.Y)*(pt2.X-pt3.X) == (pt1.X-pt2.X)*(pt2.Y-pt3.Y);
 }
 //------------------------------------------------------------------------------
 
-void SetDx(TEdge &e)
+bool SlopesEqual(const IntPoint pt1, const IntPoint pt2,
+  const IntPoint pt3, const IntPoint pt4, bool UseFullInt64Range)
 {
-  if (e.ybot == e.ytop) e.dx = horizontal;
-  else e.dx =
-    static_cast<double>(e.xtop - e.xbot) / static_cast<double>(e.ytop - e.ybot);
+  if (pt1.Y == pt2.Y) return (pt3.Y == pt4.Y);
+  else if (pt1.X == pt2.X) return (pt3.X == pt4.X);
+  else if (UseFullInt64Range)
+    return Int128(pt1.Y-pt2.Y) * Int128(pt3.X-pt4.X) ==
+      Int128(pt1.X-pt2.X) * Int128(pt3.Y-pt4.Y);
+  else return (pt1.Y-pt2.Y)*(pt3.X-pt4.X) == (pt1.X-pt2.X)*(pt3.Y-pt4.Y);
 }
-//---------------------------------------------------------------------------
+//------------------------------------------------------------------------------
 
 double GetDx(const IntPoint pt1, const IntPoint pt2)
 {
-  if (pt1.Y == pt2.Y) return horizontal;
+  if (pt1.Y == pt2.Y) return HORIZONTAL;
   else return
-    static_cast<double>(pt2.X - pt1.X) / static_cast<double>(pt2.Y - pt1.Y);
+    (double)(pt2.X - pt1.X) / (double)(pt2.Y - pt1.Y);
+}
+//---------------------------------------------------------------------------
+
+void SetDx(TEdge &e)
+{
+  if (e.ybot == e.ytop) e.dx = HORIZONTAL;
+  else e.dx =
+    (double)(e.xtop - e.xbot) / (double)(e.ytop - e.ybot);
 }
 //---------------------------------------------------------------------------
 
@@ -187,12 +546,6 @@ inline long64 Round(double val)
 }
 //------------------------------------------------------------------------------
 
-inline long64 Abs(long64 val)
-{
-  if ((val < 0)) return -val; else return val;
-}
-//------------------------------------------------------------------------------
-
 long64 TopX(TEdge &edge, const long64 currentY)
 {
   if( currentY == edge.ytop ) return edge.xtop;
@@ -208,20 +561,21 @@ long64 TopX(const IntPoint pt1, const IntPoint pt2, const long64 currentY)
   else if (pt1.X == pt2.X) return pt1.X;
   else
   {
-    double q = static_cast<double>(pt1.X-pt2.X)/static_cast<double>(pt1.Y-pt2.Y);
-    return static_cast<long64>(pt1.X + (currentY - pt1.Y) *q);
+    double q = (double)(pt1.X-pt2.X)/(double)(pt1.Y-pt2.Y);
+    return Round(pt1.X + (currentY - pt1.Y) *q);
   }
 }
 //------------------------------------------------------------------------------
 
-bool IntersectPoint(TEdge &edge1, TEdge &edge2, IntPoint &ip)
+bool IntersectPoint(TEdge &edge1, TEdge &edge2,
+  IntPoint &ip, bool UseFullInt64Range)
 {
   double b1, b2;
-  if (SlopesEqual(edge1, edge2)) return false;
-  else if (edge1.dx == 0)
+  if (SlopesEqual(edge1, edge2, UseFullInt64Range)) return false;
+  else if (NEAR_ZERO(edge1.dx))
   {
     ip.X = edge1.xbot;
-    if (edge2.dx == horizontal)
+    if (NEAR_EQUAL(edge2.dx, HORIZONTAL))
     {
       ip.Y = edge2.ybot;
     } else
@@ -230,10 +584,10 @@ bool IntersectPoint(TEdge &edge1, TEdge &edge2, IntPoint &ip)
       ip.Y = Round(ip.X/edge2.dx + b2);
     }
   }
-  else if (edge2.dx == 0)
+  else if (NEAR_ZERO(edge2.dx))
   {
     ip.X = edge2.xbot;
-    if (edge1.dx == horizontal)
+    if (NEAR_EQUAL(edge1.dx, HORIZONTAL))
     {
       ip.Y = edge1.ybot;
     } else
@@ -258,9 +612,9 @@ bool IntersectPoint(TEdge &edge1, TEdge &edge2, IntPoint &ip)
 }
 //------------------------------------------------------------------------------
 
-void ReversePolyPtLinks(PolyPt &pp)
+void ReversePolyPtLinks(OutPt &pp)
 {
-  PolyPt *pp1, *pp2;
+  OutPt *pp1, *pp2;
   pp1 = &pp;
   do {
   pp2 = pp1->next;
@@ -271,14 +625,13 @@ void ReversePolyPtLinks(PolyPt &pp)
 }
 //------------------------------------------------------------------------------
 
-void DisposePolyPts(PolyPt*& pp)
+void DisposeOutPts(OutPt*& pp)
 {
   if (pp == 0) return;
-  PolyPt *tmpPp;
   pp->prev->next = 0;
   while( pp )
   {
-    tmpPp = pp;
+    OutPt *tmpPp = pp;
     pp = pp->next;
     delete tmpPp ;
   }
@@ -356,10 +709,10 @@ bool GetOverlapSegment(IntPoint pt1a, IntPoint pt1b, IntPoint pt2a,
 }
 //------------------------------------------------------------------------------
 
-PolyPt* PolygonBottom(PolyPt* pp)
+OutPt* PolygonBottom(OutPt* pp)
 {
-  PolyPt* p = pp->next;
-  PolyPt* result = pp;
+  OutPt* p = pp->next;
+  OutPt* result = pp;
   while (p != pp)
   {
     if (p->pt.Y > result->pt.Y) result = p;
@@ -370,14 +723,17 @@ PolyPt* PolygonBottom(PolyPt* pp)
 }
 //------------------------------------------------------------------------------
 
-bool FindSegment(PolyPt* &pp, const IntPoint pt1, const IntPoint pt2)
+bool FindSegment(OutPt* &pp, IntPoint &pt1, IntPoint &pt2)
 {
+  //outPt1 & outPt2 => the overlap segment (if the function returns true)
   if (!pp) return false;
-  PolyPt* pp2 = pp;
+  OutPt* pp2 = pp;
+  IntPoint pt1a = pt1, pt2a = pt2;
   do
   {
-    if (PointsEqual(pp->pt, pt1) &&
-      (PointsEqual(pp->next->pt, pt2) || PointsEqual(pp->prev->pt, pt2)))
+    if (SlopesEqual(pt1a, pt2a, pp->pt, pp->prev->pt, true) &&
+      SlopesEqual(pt1a, pt2a, pp->pt, true) &&
+      GetOverlapSegment(pt1a, pt2a, pp->pt, pp->prev->pt, pt1, pt2))
         return true;
     pp = pp->next;
   }
@@ -386,14 +742,6 @@ bool FindSegment(PolyPt* &pp, const IntPoint pt1, const IntPoint pt2)
 }
 //------------------------------------------------------------------------------
 
-Position GetPosition(const IntPoint pt1, const IntPoint pt2, const IntPoint pt)
-{
-  if (PointsEqual(pt1, pt)) return pFirst;
-  else if (PointsEqual(pt2, pt)) return pSecond;
-  else return pMiddle;
-}
-//------------------------------------------------------------------------------
-
 bool Pt3IsBetweenPt1AndPt2(const IntPoint pt1,
   const IntPoint pt2, const IntPoint pt3)
 {
@@ -403,11 +751,11 @@ bool Pt3IsBetweenPt1AndPt2(const IntPoint pt1,
 }
 //------------------------------------------------------------------------------
 
-PolyPt* InsertPolyPtBetween(PolyPt* p1, PolyPt* p2, const IntPoint pt)
+OutPt* InsertPolyPtBetween(OutPt* p1, OutPt* p2, const IntPoint pt)
 {
-  PolyPt* result = new PolyPt;
+  if (p1 == p2) throw "JoinError";
+  OutPt* result = new OutPt;
   result->pt = pt;
-  result->isHole = p1->isHole;
   if (p2 == p1->next)
   {
     p1->next = result;
@@ -432,6 +780,7 @@ ClipperBase::ClipperBase() //constructor
 {
   m_MinimaList = 0;
   m_CurrentLM = 0;
+  m_UseFullRange = true;
 }
 //------------------------------------------------------------------------------
 
@@ -443,19 +792,29 @@ ClipperBase::~ClipperBase() //destructor
 
 bool ClipperBase::AddPolygon( const Polygon &pg, PolyType polyType)
 {
-  int len = pg.size();
+  int len = (int)pg.size();
   if (len < 3) return false;
   Polygon p(len);
   p[0] = pg[0];
   int j = 0;
-  const long64 MaxVal = 1500000000; //~ Sqrt(2^63)/2
 
-  for (int i = 1; i < len; ++i)
+  long64 maxVal;
+  if (m_UseFullRange) maxVal = hiRange; else maxVal = loRange;
+
+  for (int i = 0; i < len; ++i)
   {
-    if (Abs(pg[i].X) > MaxVal|| Abs(pg[i].Y) > MaxVal)
-      throw clipperException("Integer exceeds range bounds");
-    else if (PointsEqual(p[j], pg[i])) continue;
-    else if (j > 0 && SlopesEqual(p[j-1], p[j], pg[i]))
+    if (Abs(pg[i].X) > maxVal || Abs(pg[i].Y) > maxVal)
+    {
+      if (m_UseFullRange)
+        throw "Coordinate exceeds range bounds";
+      maxVal = hiRange;
+      if (Abs(pg[i].X) > maxVal || Abs(pg[i].Y) > maxVal)
+        throw "Coordinate exceeds range bounds";
+      m_UseFullRange = true;
+    }
+
+    if (i == 0 || PointsEqual(p[j], pg[i])) continue;
+    else if (j > 0 && SlopesEqual(p[j-1], p[j], pg[i], m_UseFullRange))
     {
       if (PointsEqual(p[j-1], pg[i])) j--;
     } else j++;
@@ -468,10 +827,11 @@ bool ClipperBase::AddPolygon( const Polygon &pg, PolyType polyType)
   {
     //nb: test for point equality before testing slopes ...
     if (PointsEqual(p[j], p[0])) j--;
-    else if (PointsEqual(p[0], p[1]) || SlopesEqual(p[j], p[0], p[1]))
+    else if (PointsEqual(p[0], p[1]) ||
+      SlopesEqual(p[j], p[0], p[1], m_UseFullRange))
       p[0] = p[j--];
-    else if (SlopesEqual(p[j-1], p[j], p[0])) j--;
-    else if (SlopesEqual(p[0], p[1], p[2]))
+    else if (SlopesEqual(p[j-1], p[j], p[0], m_UseFullRange)) j--;
+    else if (SlopesEqual(p[0], p[1], p[2], m_UseFullRange))
     {
       for (int i = 2; i <= j; ++i) p[i-1] = p[i];
       j--;
@@ -509,7 +869,7 @@ bool ClipperBase::AddPolygon( const Polygon &pg, PolyType polyType)
 
   //make sure eHighest is positioned so the following loop works safely ...
   if (eHighest->windDelta > 0) eHighest = eHighest->next;
-  if (eHighest->dx == horizontal) eHighest = eHighest->next;
+  if (NEAR_EQUAL(eHighest->dx, HORIZONTAL)) eHighest = eHighest->next;
 
   //finally insert each local minima ...
   e = eHighest;
@@ -551,7 +911,7 @@ TEdge* ClipperBase::AddBoundsToLML(TEdge *e)
   e = e->next;
   for (;;)
   {
-    if ( e->dx == horizontal )
+    if (NEAR_EQUAL(e->dx, HORIZONTAL))
     {
       //nb: proceed through horizontals when approaching from their right,
       //    but break on horizontal minima if approaching from their left.
@@ -570,7 +930,7 @@ TEdge* ClipperBase::AddBoundsToLML(TEdge *e)
   newLm->next = 0;
   newLm->Y = e->prev->ybot;
 
-  if ( e->dx == horizontal ) //horizontal edges never start a left bound
+  if ( NEAR_EQUAL(e->dx, HORIZONTAL) ) //horizontal edges never start a left bound
   {
     if (e->xbot != e->prev->xbot) SwapX(*e);
     newLm->leftBound = e->prev;
@@ -590,10 +950,10 @@ TEdge* ClipperBase::AddBoundsToLML(TEdge *e)
 
   for (;;)
   {
-    if ( e->next->ytop == e->ytop && e->next->dx != horizontal ) break;
+    if ( e->next->ytop == e->ytop && !NEAR_EQUAL(e->next->dx, HORIZONTAL) ) break;
     e->nextInLML = e->next;
     e = e->next;
-    if ( e->dx == horizontal && e->xbot != e->prev->xtop) SwapX(*e);
+    if ( NEAR_EQUAL(e->dx, HORIZONTAL) && e->xbot != e->prev->xtop) SwapX(*e);
   }
   return e->next;
 }
@@ -601,9 +961,9 @@ TEdge* ClipperBase::AddBoundsToLML(TEdge *e)
 
 bool ClipperBase::AddPolygons(const Polygons &ppg, PolyType polyType)
 {
-  bool result = false;
+  bool result = true;
   for (Polygons::size_type i = 0; i < ppg.size(); ++i)
-    if (AddPolygon(ppg[i], polyType)) result = true;
+    if (AddPolygon(ppg[i], polyType)) result = false;
   return result;
 }
 //------------------------------------------------------------------------------
@@ -613,6 +973,7 @@ void ClipperBase::Clear()
   DisposeLocalMinimaList();
   for (EdgeList::size_type i = 0; i < m_edges.size(); ++i) delete [] m_edges[i];
   m_edges.clear();
+  m_UseFullRange = false;
 }
 //------------------------------------------------------------------------------
 
@@ -686,6 +1047,7 @@ IntRect ClipperBase::GetBounds()
       result.bottom = lm->leftBound->ybot;
     TEdge* e = lm->leftBound;
     for (;;) {
+      TEdge* bottomE = e;
       while (e->nextInLML)
       {
         if (e->xbot < result.left) result.left = e->xbot;
@@ -698,7 +1060,7 @@ IntRect ClipperBase::GetBounds()
       if (e->xtop > result.right) result.right = e->xtop;
       if (e->ytop < result.top) result.top = e->ytop;
 
-      if (e == lm->leftBound) e = lm->rightBound;
+      if (bottomE == lm->leftBound) e = lm->rightBound;
       else break;
     }
     lm = lm->next;
@@ -718,13 +1080,24 @@ Clipper::Clipper() : ClipperBase() //constructor
   m_SortedEdges = 0;
   m_IntersectNodes = 0;
   m_ExecuteLocked = false;
-};
+  m_UseFullRange = false;
+  m_ReverseOutput = false;
+}
 //------------------------------------------------------------------------------
 
 Clipper::~Clipper() //destructor
 {
+  Clear();
   DisposeScanbeamList();
-};
+}
+//------------------------------------------------------------------------------
+
+void Clipper::Clear()
+{
+  if (m_edges.size() == 0) return; //avoids problems with ClipperBase destructor
+  DisposeAllPolyPts();
+  ClipperBase::Clear();
+}
 //------------------------------------------------------------------------------
 
 void Clipper::DisposeScanbeamList()
@@ -757,44 +1130,138 @@ bool Clipper::Execute(ClipType clipType, Polygons &solution,
     PolyFillType subjFillType, PolyFillType clipFillType)
 {
   if( m_ExecuteLocked ) return false;
-  bool succeeded;
-  try {
-    m_ExecuteLocked = true;
-    solution.resize(0);
-    Reset();
-    if (!m_CurrentLM )
+  m_ExecuteLocked = true;
+  solution.resize(0);
+  m_SubjFillType = subjFillType;
+  m_ClipFillType = clipFillType;
+  m_ClipType = clipType;
+  bool succeeded = ExecuteInternal(false);
+  if (succeeded) BuildResult(solution);
+  m_ExecuteLocked = false;
+  return succeeded;
+}
+//------------------------------------------------------------------------------
+
+bool Clipper::Execute(ClipType clipType, ExPolygons &solution,
+    PolyFillType subjFillType, PolyFillType clipFillType)
+{
+  if( m_ExecuteLocked ) return false;
+  m_ExecuteLocked = true;
+  solution.resize(0);
+  m_SubjFillType = subjFillType;
+  m_ClipFillType = clipFillType;
+  m_ClipType = clipType;
+  bool succeeded = ExecuteInternal(true);
+  if (succeeded) BuildResultEx(solution);
+  m_ExecuteLocked = false;
+  return succeeded;
+}
+//------------------------------------------------------------------------------
+
+bool PolySort(OutRec *or1, OutRec *or2)
+{
+  if (or1 == or2) return false;
+  if (!or1->pts || !or2->pts)
+  {
+    if (or1->pts != or2->pts)
     {
-      m_ExecuteLocked = false;
-      return true;
+      if (or1->pts) return true; else return false;
+    }
+    else return false;
+  }
+  int i1, i2;
+  if (or1->isHole)
+    i1 = or1->FirstLeft->idx; else
+    i1 = or1->idx;
+  if (or2->isHole)
+    i2 = or2->FirstLeft->idx; else
+    i2 = or2->idx;
+  int result = i1 - i2;
+  if (result == 0 && (or1->isHole != or2->isHole))
+  {
+    if (or1->isHole) return false;
+    else return true;
+  }
+  else return result < 0;
+}
+//------------------------------------------------------------------------------
+
+OutRec* FindAppendLinkEnd(OutRec *outRec)
+{
+  while (outRec->AppendLink) outRec = outRec->AppendLink;
+  return outRec;
+}
+//------------------------------------------------------------------------------
+
+void Clipper::FixHoleLinkage(OutRec *outRec)
+{
+  OutRec *tmp;
+  if (outRec->bottomPt)
+    tmp = m_PolyOuts[outRec->bottomPt->idx]->FirstLeft;
+  else
+    tmp = outRec->FirstLeft;
+  if (outRec == tmp) throw clipperException("HoleLinkage error");
+
+  if (tmp)
+  {
+    if (tmp->AppendLink) tmp = FindAppendLinkEnd(tmp);
+    if (tmp == outRec) tmp = 0;
+    else if (tmp->isHole)
+    {
+      FixHoleLinkage(tmp);
+      tmp = tmp->FirstLeft;
     }
-    m_SubjFillType = subjFillType;
-    m_ClipFillType = clipFillType;
-    m_ClipType = clipType;
+  }
+  outRec->FirstLeft = tmp;
+  if (!tmp) outRec->isHole = false;
+  outRec->AppendLink = 0;
+}
+//------------------------------------------------------------------------------
 
+bool Clipper::ExecuteInternal(bool fixHoleLinkages)
+{
+  bool succeeded;
+  try {
+    Reset();
+    if (!m_CurrentLM ) return true;
     long64 botY = PopScanbeam();
     do {
       InsertLocalMinimaIntoAEL(botY);
       ClearHorzJoins();
       ProcessHorizontals();
       long64 topY = PopScanbeam();
-      succeeded = ProcessIntersections(topY);
-      if (succeeded) ProcessEdgesAtTopOfScanbeam(topY);
+      succeeded = ProcessIntersections(botY, topY);
+      if (!succeeded) break;
+      ProcessEdgesAtTopOfScanbeam(topY);
       botY = topY;
-    } while( succeeded && m_Scanbeam );
-
-    //build the return polygons ...
-    if (succeeded) BuildResult(solution);
+    } while( m_Scanbeam );
   }
   catch(...) {
-    ClearJoins();
-    ClearHorzJoins();
-    solution.resize(0);
     succeeded = false;
   }
+
+  if (succeeded)
+  {
+    //tidy up output polygons and fix orientations where necessary ...
+    for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
+    {
+      OutRec *outRec = m_PolyOuts[i];
+      if (!outRec->pts) continue;
+      FixupOutPolygon(*outRec);
+      if (!outRec->pts) continue;
+      if (outRec->isHole && fixHoleLinkages) FixHoleLinkage(outRec);
+      if (outRec->isHole ==
+        (m_ReverseOutput ^ Orientation(outRec, m_UseFullRange)))
+          ReversePolyPtLinks(*outRec->pts);
+    }
+
+    JoinCommonEdges(fixHoleLinkages);
+    if (fixHoleLinkages)
+      std::sort(m_PolyOuts.begin(), m_PolyOuts.end(), PolySort);
+  }
+
   ClearJoins();
   ClearHorzJoins();
-  DisposeAllPolyPts();
-  m_ExecuteLocked = false;
   return succeeded;
 }
 //------------------------------------------------------------------------------
@@ -837,9 +1304,18 @@ long64 Clipper::PopScanbeam()
 //------------------------------------------------------------------------------
 
 void Clipper::DisposeAllPolyPts(){
-  for (PolyPtList::size_type i = 0; i < m_PolyPts.size(); ++i)
-    DisposePolyPts(m_PolyPts[i]);
-  m_PolyPts.clear();
+  for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
+    DisposeOutRec(i);
+  m_PolyOuts.clear();
+}
+//------------------------------------------------------------------------------
+
+void Clipper::DisposeOutRec(PolyOutList::size_type index, bool ignorePts)
+{
+  OutRec *outRec = m_PolyOuts[index];
+  if (!ignorePts && outRec->pts) DisposeOutPts(outRec->pts);
+  delete outRec;
+  m_PolyOuts[index] = 0;
 }
 //------------------------------------------------------------------------------
 
@@ -853,9 +1329,15 @@ void Clipper::SetWindingCount(TEdge &edge)
     edge.windCnt = edge.windDelta;
     edge.windCnt2 = 0;
     e = m_ActiveEdges; //ie get ready to calc windCnt2
-  } else if ( IsNonZeroFillType(edge) )
+  } else if ( IsEvenOddFillType(edge) )
+  {
+    //EvenOdd filling ...
+    edge.windCnt = 1;
+    edge.windCnt2 = e->windCnt2;
+    e = e->nextInAEL; //ie get ready to calc windCnt2
+  } else
   {
-    //nonZero filling ...
+    //nonZero, Positive or Negative filling ...
     if ( e->windCnt * e->windDelta < 0 )
     {
       if (Abs(e->windCnt) > 1)
@@ -874,81 +1356,135 @@ void Clipper::SetWindingCount(TEdge &edge)
     }
     edge.windCnt2 = e->windCnt2;
     e = e->nextInAEL; //ie get ready to calc windCnt2
-  } else
-  {
-    //even-odd filling ...
-    edge.windCnt = 1;
-    edge.windCnt2 = e->windCnt2;
-    e = e->nextInAEL; //ie get ready to calc windCnt2
   }
 
   //update windCnt2 ...
-  if ( IsNonZeroAltFillType(edge) )
+  if ( IsEvenOddAltFillType(edge) )
   {
-    //nonZero filling ...
+    //EvenOdd filling ...
     while ( e != &edge )
     {
-      edge.windCnt2 += e->windDelta;
+      edge.windCnt2 = (edge.windCnt2 == 0) ? 1 : 0;
       e = e->nextInAEL;
     }
   } else
   {
-    //even-odd filling ...
+    //nonZero, Positive or Negative filling ...
     while ( e != &edge )
     {
-      edge.windCnt2 = (edge.windCnt2 == 0) ? 1 : 0;
+      edge.windCnt2 += e->windDelta;
       e = e->nextInAEL;
     }
   }
 }
 //------------------------------------------------------------------------------
 
-bool Clipper::IsNonZeroFillType(const TEdge& edge) const
+bool Clipper::IsEvenOddFillType(const TEdge& edge) const
 {
   if (edge.polyType == ptSubject)
-    return m_SubjFillType == pftNonZero; else
-    return m_ClipFillType == pftNonZero;
+    return m_SubjFillType == pftEvenOdd; else
+    return m_ClipFillType == pftEvenOdd;
 }
 //------------------------------------------------------------------------------
 
-bool Clipper::IsNonZeroAltFillType(const TEdge& edge) const
+bool Clipper::IsEvenOddAltFillType(const TEdge& edge) const
 {
   if (edge.polyType == ptSubject)
-    return m_ClipFillType == pftNonZero; else
-    return m_SubjFillType == pftNonZero;
+    return m_ClipFillType == pftEvenOdd; else
+    return m_SubjFillType == pftEvenOdd;
 }
 //------------------------------------------------------------------------------
 
 bool Clipper::IsContributing(const TEdge& edge) const
 {
-  switch( m_ClipType ){
+  PolyFillType pft, pft2;
+  if (edge.polyType == ptSubject)
+  {
+    pft = m_SubjFillType;
+    pft2 = m_ClipFillType;
+  } else
+  {
+    pft = m_ClipFillType;
+    pft2 = m_SubjFillType;
+  }
+
+  switch(pft)
+  {
+    case pftEvenOdd: 
+    case pftNonZero:
+      if (Abs(edge.windCnt) != 1) return false;
+      break;
+    case pftPositive: 
+      if (edge.windCnt != 1) return false;
+      break;
+    default: //pftNegative
+      if (edge.windCnt != -1) return false;
+  }
+
+  switch(m_ClipType)
+  {
     case ctIntersection:
-      if ( edge.polyType == ptSubject )
-        return Abs(edge.windCnt) == 1 && edge.windCnt2 != 0; else
-        return Abs(edge.windCnt2) > 0 && Abs(edge.windCnt) == 1;
+      switch(pft2)
+      {
+        case pftEvenOdd: 
+        case pftNonZero: 
+          return (edge.windCnt2 != 0);
+        case pftPositive: 
+          return (edge.windCnt2 > 0);
+        default: 
+          return (edge.windCnt2 < 0);
+      }
     case ctUnion:
-      return Abs(edge.windCnt) == 1 && edge.windCnt2 == 0;
+      switch(pft2)
+      {
+        case pftEvenOdd: 
+        case pftNonZero: 
+          return (edge.windCnt2 == 0);
+        case pftPositive: 
+          return (edge.windCnt2 <= 0);
+        default: 
+          return (edge.windCnt2 >= 0);
+      }
     case ctDifference:
-      if ( edge.polyType == ptSubject )
-        return std::abs(edge.windCnt) == 1 && edge.windCnt2 == 0; else
-        return std::abs(edge.windCnt) == 1 && edge.windCnt2 != 0;
-    default: //case ctXor:
-      return std::abs(edge.windCnt) == 1;
+      if (edge.polyType == ptSubject)
+        switch(pft2)
+        {
+          case pftEvenOdd: 
+          case pftNonZero: 
+            return (edge.windCnt2 == 0);
+          case pftPositive: 
+            return (edge.windCnt2 <= 0);
+          default: 
+            return (edge.windCnt2 >= 0);
+        }
+      else
+        switch(pft2)
+        {
+          case pftEvenOdd: 
+          case pftNonZero: 
+            return (edge.windCnt2 != 0);
+          case pftPositive: 
+            return (edge.windCnt2 > 0);
+          default: 
+            return (edge.windCnt2 < 0);
+        }
+    default:
+      return true;
   }
 }
 //------------------------------------------------------------------------------
 
 void Clipper::AddLocalMinPoly(TEdge *e1, TEdge *e2, const IntPoint &pt)
 {
-  if( e2->dx == horizontal || ( e1->dx > e2->dx ) )
+  if( NEAR_EQUAL(e2->dx, HORIZONTAL) || ( e1->dx > e2->dx ) )
   {
-    AddPolyPt( e1, pt );
+    AddOutPt( e1, e2, pt );
     e2->outIdx = e1->outIdx;
     e1->side = esLeft;
     e2->side = esRight;
   } else
   {
-    AddPolyPt( e2, pt );
+    AddOutPt( e2, e1, pt );
     e1->outIdx = e2->outIdx;
     e1->side = esRight;
     e2->side = esLeft;
@@ -958,7 +1494,7 @@ void Clipper::AddLocalMinPoly(TEdge *e1, TEdge *e2, const IntPoint &pt)
 
 void Clipper::AddLocalMaxPoly(TEdge *e1, TEdge *e2, const IntPoint &pt)
 {
-  AddPolyPt( e1, pt );
+  AddOutPt( e1, 0, pt );
   if( e1->outIdx == e2->outIdx )
   {
     e1->outIdx = -1;
@@ -1006,16 +1542,18 @@ void Clipper::CopyAELToSEL()
 }
 //------------------------------------------------------------------------------
 
-void Clipper::AddJoin(TEdge *e1, TEdge *e2, int e1OutIdx)
+void Clipper::AddJoin(TEdge *e1, TEdge *e2, int e1OutIdx, int e2OutIdx)
 {
   JoinRec* jr = new JoinRec;
   if (e1OutIdx >= 0)
     jr->poly1Idx = e1OutIdx; else
     jr->poly1Idx = e1->outIdx;
-  jr->pt1a = IntPoint(e1->xbot, e1->ybot);
+  jr->pt1a = IntPoint(e1->xcurr, e1->ycurr);
   jr->pt1b = IntPoint(e1->xtop, e1->ytop);
-  jr->poly2Idx = e2->outIdx;
-  jr->pt2a = IntPoint(e2->xbot, e2->ybot);
+  if (e2OutIdx >= 0)
+    jr->poly2Idx = e2OutIdx; else
+    jr->poly2Idx = e2->outIdx;
+  jr->pt2a = IntPoint(e2->xcurr, e2->ycurr);
   jr->pt2b = IntPoint(e2->xtop, e2->ytop);
   m_Joins.push_back(jr);
 }
@@ -1057,18 +1595,20 @@ void Clipper::InsertLocalMinimaIntoAEL( const long64 botY)
     InsertScanbeam( lb->ytop );
     InsertEdgeIntoAEL( rb );
 
-    if ( IsNonZeroFillType( *lb) )
-      rb->windDelta = -lb->windDelta;
-    else
+    if (IsEvenOddFillType(*lb))
     {
       lb->windDelta = 1;
       rb->windDelta = 1;
     }
+    else
+    {
+      rb->windDelta = -lb->windDelta;
+    }
     SetWindingCount( *lb );
     rb->windCnt = lb->windCnt;
     rb->windCnt2 = lb->windCnt2;
 
-    if(  rb->dx == horizontal )
+    if( NEAR_EQUAL(rb->dx, HORIZONTAL) )
     {
       //nb: only rightbounds can have a horizontal bottom edge
       AddEdgeToSEL( rb );
@@ -1083,13 +1623,13 @@ void Clipper::InsertLocalMinimaIntoAEL( const long64 botY)
     //if output polygons share an edge, they'll need joining later ...
     if (lb->outIdx >= 0 && lb->prevInAEL &&
       lb->prevInAEL->outIdx >= 0 && lb->prevInAEL->xcurr == lb->xbot &&
-       SlopesEqual(*lb, *lb->prevInAEL))
+       SlopesEqual(*lb, *lb->prevInAEL, m_UseFullRange))
          AddJoin(lb, lb->prevInAEL);
 
     //if any output polygons share an edge, they'll need joining later ...
     if (rb->outIdx >= 0)
     {
-      if (rb->dx == horizontal)
+      if (NEAR_EQUAL(rb->dx, HORIZONTAL))
       {
         for (HorzJoinList::size_type i = 0; i < m_HorizJoins.size(); ++i)
         {
@@ -1107,6 +1647,10 @@ void Clipper::InsertLocalMinimaIntoAEL( const long64 botY)
 
     if( lb->nextInAEL != rb )
     {
+      if (rb->outIdx >= 0 && rb->prevInAEL->outIdx >= 0 &&
+        SlopesEqual(*rb->prevInAEL, *rb, m_UseFullRange))
+          AddJoin(rb, rb->prevInAEL);
+
       TEdge* e = lb->nextInAEL;
       IntPoint pt = IntPoint(lb->xcurr, lb->ycurr);
       while( e != rb )
@@ -1140,7 +1684,7 @@ void Clipper::DeleteFromSEL(TEdge *e)
 {
   TEdge* SelPrev = e->prevInSEL;
   TEdge* SelNext = e->nextInSEL;
-  if(  !SelPrev &&  !SelNext && (e != m_SortedEdges) ) return; //already deleted
+  if( !SelPrev &&  !SelNext && (e != m_SortedEdges) ) return; //already deleted
   if( SelPrev ) SelPrev->nextInSEL = SelNext;
   else m_SortedEdges = SelNext;
   if( SelNext ) SelNext->prevInSEL = SelPrev;
@@ -1165,83 +1709,125 @@ void Clipper::IntersectEdges(TEdge *e1, TEdge *e2,
   //assumes that e1 will be to the right of e2 ABOVE the intersection
   if ( e1->polyType == e2->polyType )
   {
-    if ( IsNonZeroFillType( *e1) )
+    if ( IsEvenOddFillType( *e1) )
+    {
+      int oldE1WindCnt = e1->windCnt;
+      e1->windCnt = e2->windCnt;
+      e2->windCnt = oldE1WindCnt;
+    } else
     {
       if (e1->windCnt + e2->windDelta == 0 ) e1->windCnt = -e1->windCnt;
       else e1->windCnt += e2->windDelta;
       if ( e2->windCnt - e1->windDelta == 0 ) e2->windCnt = -e2->windCnt;
       else e2->windCnt -= e1->windDelta;
-    } else
-    {
-      int oldE1WindCnt = e1->windCnt;
-      e1->windCnt = e2->windCnt;
-      e2->windCnt = oldE1WindCnt;
     }
   } else
   {
-    if ( IsNonZeroFillType(*e2) ) e1->windCnt2 += e2->windDelta;
+    if (!IsEvenOddFillType(*e2)) e1->windCnt2 += e2->windDelta;
     else e1->windCnt2 = ( e1->windCnt2 == 0 ) ? 1 : 0;
-    if ( IsNonZeroFillType(*e1) ) e2->windCnt2 -= e1->windDelta;
+    if (!IsEvenOddFillType(*e1)) e2->windCnt2 -= e1->windDelta;
     else e2->windCnt2 = ( e2->windCnt2 == 0 ) ? 1 : 0;
   }
 
+  PolyFillType e1FillType, e2FillType, e1FillType2, e2FillType2;
+  if (e1->polyType == ptSubject)
+  {
+    e1FillType = m_SubjFillType;
+    e1FillType2 = m_ClipFillType;
+  } else
+  {
+    e1FillType = m_ClipFillType;
+    e1FillType2 = m_SubjFillType;
+  }
+  if (e2->polyType == ptSubject)
+  {
+    e2FillType = m_SubjFillType;
+    e2FillType2 = m_ClipFillType;
+  } else
+  {
+    e2FillType = m_ClipFillType;
+    e2FillType2 = m_SubjFillType;
+  }
+
+  long64 e1Wc, e2Wc;
+  switch (e1FillType)
+  {
+    case pftPositive: e1Wc = e1->windCnt; break;
+    case pftNegative: e1Wc = -e1->windCnt; break;
+    default: e1Wc = Abs(e1->windCnt);
+  }
+  switch(e2FillType)
+  {
+    case pftPositive: e2Wc = e2->windCnt; break;
+    case pftNegative: e2Wc = -e2->windCnt; break;
+    default: e2Wc = Abs(e2->windCnt);
+  }
+
   if ( e1Contributing && e2contributing )
   {
-    if ( e1stops || e2stops || std::abs(e1->windCnt) > 1 ||
-      std::abs(e2->windCnt) > 1 ||
+    if ( e1stops || e2stops || 
+      (e1Wc != 0 && e1Wc != 1) || (e2Wc != 0 && e2Wc != 1) ||
       (e1->polyType != e2->polyType && m_ClipType != ctXor) )
-        AddLocalMaxPoly(e1, e2, pt); else
+        AddLocalMaxPoly(e1, e2, pt); 
+    else
         DoBothEdges( e1, e2, pt );
   }
   else if ( e1Contributing )
   {
-    switch( m_ClipType ) {
-      case ctIntersection:
-        if ( (e2->polyType == ptSubject || e2->windCnt2 != 0) &&
-           std::abs(e2->windCnt) < 2 ) DoEdge1( e1, e2, pt);
-        break;
-      default:
-        if ( std::abs(e2->windCnt) < 2 ) DoEdge1(e1, e2, pt);
-    }
+    if ((e2Wc == 0 || e2Wc == 1) && 
+      (m_ClipType != ctIntersection || 
+      e2->polyType == ptSubject || (e2->windCnt2 != 0))) 
+        DoEdge1(e1, e2, pt);
   }
   else if ( e2contributing )
   {
-    if ( m_ClipType == ctIntersection )
+    if ((e1Wc == 0 || e1Wc == 1) && 
+      (m_ClipType != ctIntersection || 
+      e1->polyType == ptSubject || (e1->windCnt2 != 0))) 
+        DoEdge2(e1, e2, pt);
+  } 
+  else if ( (e1Wc == 0 || e1Wc == 1) && 
+    (e2Wc == 0 || e2Wc == 1) && !e1stops && !e2stops )
+  {
+    //neither edge is currently contributing ...
+
+    long64 e1Wc2, e2Wc2;
+    switch (e1FillType2)
     {
-        if ( (e1->polyType == ptSubject || e1->windCnt2 != 0) &&
-          std::abs(e1->windCnt) < 2 ) DoEdge2( e1, e2, pt );
+      case pftPositive: e1Wc2 = e1->windCnt2; break;
+      case pftNegative : e1Wc2 = -e1->windCnt2; break;
+      default: e1Wc2 = Abs(e1->windCnt2);
+    }
+    switch (e2FillType2)
+    {
+      case pftPositive: e2Wc2 = e2->windCnt2; break;
+      case pftNegative: e2Wc2 = -e2->windCnt2; break;
+      default: e2Wc2 = Abs(e2->windCnt2);
     }
-    else
-      if (std::abs(e1->windCnt) < 2) DoEdge2( e1, e2, pt );
 
-  } else
-  {
-    //neither edge is currently contributing ...
-    if ( std::abs(e1->windCnt) > 1 && std::abs(e2->windCnt) > 1 ) ;// do nothing
-    else if ( e1->polyType != e2->polyType && !e1stops && !e2stops &&
-      std::abs(e1->windCnt) < 2 && std::abs(e2->windCnt) < 2 )
+    if (e1->polyType != e2->polyType)
         AddLocalMinPoly(e1, e2, pt);
-    else if ( std::abs(e1->windCnt) == 1 && std::abs(e2->windCnt) == 1 )
+    else if (e1Wc == 1 && e2Wc == 1)
       switch( m_ClipType ) {
         case ctIntersection:
-          if ( std::abs(e1->windCnt2) > 0 && std::abs(e2->windCnt2) > 0 )
+          if (e1Wc2 > 0 && e2Wc2 > 0)
             AddLocalMinPoly(e1, e2, pt);
           break;
         case ctUnion:
-          if ( e1->windCnt2 == 0 && e2->windCnt2 == 0 )
+          if ( e1Wc2 <= 0 && e2Wc2 <= 0 )
             AddLocalMinPoly(e1, e2, pt);
           break;
         case ctDifference:
-          if ( (e1->polyType == ptClip && e2->polyType == ptClip &&
-            e1->windCnt2 != 0 && e2->windCnt2 != 0) ||
-            (e1->polyType == ptSubject && e2->polyType == ptSubject &&
-            e1->windCnt2 == 0 && e2->windCnt2 == 0) )
-              AddLocalMinPoly(e1, e2, pt);
+          if ((e1->polyType == ptClip && e2->polyType == ptClip && 
+              e1Wc2 > 0 && e2Wc2 > 0) || 
+              (e1->polyType == ptSubject && e2->polyType == ptSubject && 
+              e1Wc2 <= 0 && e2Wc2 <= 0)) 
+                AddLocalMinPoly(e1, e2, pt);
           break;
         case ctXor:
           AddLocalMinPoly(e1, e2, pt);
       }
-    else if ( std::abs(e1->windCnt) < 2 && std::abs(e2->windCnt) < 2 )
+    else
       SwapSides( *e1, *e2 );
   }
 
@@ -1258,41 +1844,86 @@ void Clipper::IntersectEdges(TEdge *e1, TEdge *e2,
 }
 //------------------------------------------------------------------------------
 
-void SetHoleState(PolyPt *pp, bool isHole)
+void Clipper::SetHoleState(TEdge *e, OutRec *outRec)
 {
-  PolyPt *pp2 = pp;
-  do
+  bool isHole = false;
+  TEdge *e2 = e->prevInAEL;
+  while (e2)
   {
-    pp2->isHole = isHole;
-    pp2 = pp2->next;
+    if (e2->outIdx >= 0)
+    {
+      isHole = !isHole;
+      if (! outRec->FirstLeft)
+        outRec->FirstLeft = m_PolyOuts[e2->outIdx];
+    }
+    e2 = e2->prevInAEL;
+  }
+  if (isHole) outRec->isHole = true;
+}
+//------------------------------------------------------------------------------
+
+bool GetNextNonDupOutPt(OutPt* pp, OutPt*& next)
+{
+  next = pp->next;
+  while (next != pp && PointsEqual(pp->pt, next->pt))
+    next = next->next;
+  return next != pp;
+}
+//------------------------------------------------------------------------------
+
+bool GetPrevNonDupOutPt(OutPt* pp, OutPt*& prev)
+{
+  prev = pp->prev;
+  while (prev != pp && PointsEqual(pp->pt, prev->pt))
+    prev = prev->prev;
+  return prev != pp;
+}
+//------------------------------------------------------------------------------
+
+OutRec* GetLowermostRec(OutRec *outRec1, OutRec *outRec2)
+{
+  //work out which polygon fragment has the correct hole state ...
+  OutPt *outPt1 = outRec1->bottomPt;
+  OutPt *outPt2 = outRec2->bottomPt;
+  if (outPt1->pt.Y > outPt2->pt.Y) return outRec1;
+  else if (outPt1->pt.Y < outPt2->pt.Y) return outRec2;
+  else if (outPt1->pt.X < outPt2->pt.X) return outRec1;
+  else if (outPt1->pt.X > outPt2->pt.X) return outRec2;
+  else if (outRec1->bottomE2 == 0) return outRec2;
+  else if (outRec2->bottomE2 == 0) return outRec1;
+  else
+  {
+    long64 y1 = std::max(outRec1->bottomE1->ybot, outRec1->bottomE2->ybot);
+    long64 y2 = std::max(outRec2->bottomE1->ybot, outRec2->bottomE2->ybot);
+    if (y2 == y1 || (y1 > outPt1->pt.Y && y2 > outPt1->pt.Y))
+    {
+      double dx1 = std::max(outRec1->bottomE1->dx, outRec1->bottomE2->dx);
+      double dx2 = std::max(outRec2->bottomE1->dx, outRec2->bottomE2->dx);
+      if (dx2 > dx1) return outRec2; else return outRec1;
+    }
+    else if (y2 > y1) return outRec2;
+    else return outRec1;
   }
-  while (pp2 != pp);
 }
 //------------------------------------------------------------------------------
 
 void Clipper::AppendPolygon(TEdge *e1, TEdge *e2)
 {
   //get the start and ends of both output polygons ...
-  PolyPt* p1_lft = m_PolyPts[e1->outIdx];
-  PolyPt* p1_rt = p1_lft->prev;
-  PolyPt* p2_lft = m_PolyPts[e2->outIdx];
-  PolyPt* p2_rt = p2_lft->prev;
+  OutRec *outRec1 = m_PolyOuts[e1->outIdx];
+  OutRec *outRec2 = m_PolyOuts[e2->outIdx];
+  OutRec *holeStateRec = GetLowermostRec(outRec1, outRec2);
 
-  //fixup orientation (hole) flag if necessary ...
-  if (p1_lft->isHole != p2_lft->isHole)
-  {
-    PolyPt *p;
-    PolyPt *bottom1 = PolygonBottom(p1_lft);
-    PolyPt *bottom2 = PolygonBottom(p2_lft);
-    if (bottom1->pt.Y > bottom2->pt.Y) p = p2_lft;
-    else if (bottom1->pt.Y < bottom2->pt.Y) p = p1_lft;
-    else if (bottom1->pt.X < bottom2->pt.X) p = p2_lft;
-    else if (bottom1->pt.X > bottom2->pt.X) p = p1_lft;
-    //todo - the following line really only a best guess ...
-    else if (bottom1->isHole) p = p1_lft; else p = p2_lft;
+  //fixup hole status ...
+  if (holeStateRec == outRec2)
+    outRec1->isHole = outRec2->isHole;
+  else
+    outRec2->isHole = outRec1->isHole;
 
-    SetHoleState(p, !p->isHole);
-  }
+  OutPt* p1_lft = outRec1->pts;
+  OutPt* p1_rt = p1_lft->prev;
+  OutPt* p2_lft = outRec2->pts;
+  OutPt* p2_rt = p2_lft->prev;
 
   EdgeSide side;
   //join e2 poly onto e1 poly and delete pointers to e2 ...
@@ -1306,7 +1937,7 @@ void Clipper::AppendPolygon(TEdge *e1, TEdge *e2)
       p1_lft->prev = p2_lft;
       p1_rt->next = p2_rt;
       p2_rt->prev = p1_rt;
-      m_PolyPts[e1->outIdx] = p2_rt;
+      outRec1->pts = p2_rt;
     } else
     {
       //x y z a b c
@@ -1314,7 +1945,7 @@ void Clipper::AppendPolygon(TEdge *e1, TEdge *e2)
       p1_lft->prev = p2_rt;
       p2_lft->prev = p1_rt;
       p1_rt->next = p2_lft;
-      m_PolyPts[e1->outIdx] = p2_lft;
+      outRec1->pts = p2_lft;
     }
     side = esLeft;
   } else
@@ -1338,9 +1969,21 @@ void Clipper::AppendPolygon(TEdge *e1, TEdge *e2)
     side = esRight;
   }
 
+  if (holeStateRec == outRec2)
+  {
+    outRec1->bottomPt = outRec2->bottomPt;
+    outRec1->bottomPt->idx = outRec1->idx;
+    outRec1->bottomE1 = outRec2->bottomE1;
+    outRec1->bottomE2 = outRec2->bottomE2;
+
+    if (outRec2->FirstLeft != outRec1)
+      outRec1->FirstLeft = outRec2->FirstLeft;
+  }
+  outRec2->pts = 0;
+  outRec2->bottomPt = 0;
+  outRec2->AppendLink = outRec1;
   int OKIdx = e1->outIdx;
   int ObsoleteIdx = e2->outIdx;
-  m_PolyPts[ObsoleteIdx] = 0;
 
   e1->outIdx = -1; //nb: safe because we only get here via AddLocalMaxPoly
   e2->outIdx = -1;
@@ -1372,34 +2015,58 @@ void Clipper::AppendPolygon(TEdge *e1, TEdge *e2)
 }
 //------------------------------------------------------------------------------
 
-PolyPt* Clipper::AddPolyPt(TEdge *e, const IntPoint &pt)
+OutRec* Clipper::CreateOutRec()
+{
+  OutRec* result = new OutRec;
+  result->isHole = false;
+  result->FirstLeft = 0;
+  result->AppendLink = 0;
+  result->pts = 0;
+  result->bottomPt = 0;
+  return result;
+}
+//------------------------------------------------------------------------------
+
+void Clipper::AddOutPt(TEdge *e, TEdge *altE, const IntPoint &pt)
 {
   bool ToFront = (e->side == esLeft);
   if(  e->outIdx < 0 )
   {
-    PolyPt* newPolyPt = new PolyPt;
-    newPolyPt->pt = pt;
-    newPolyPt->isHole = IsHole(e);
-    m_PolyPts.push_back(newPolyPt);
-    newPolyPt->next = newPolyPt;
-    newPolyPt->prev = newPolyPt;
-    e->outIdx = m_PolyPts.size()-1;
-    return newPolyPt;
+    OutRec *outRec = CreateOutRec();
+    m_PolyOuts.push_back(outRec);
+    outRec->idx = (int)m_PolyOuts.size()-1;
+    e->outIdx = outRec->idx;
+    OutPt* op = new OutPt;
+    outRec->pts = op;
+    outRec->bottomE1 = e;
+    outRec->bottomE2 = altE;
+    outRec->bottomPt = op;
+    op->pt = pt;
+    op->idx = outRec->idx;
+    op->next = op;
+    op->prev = op;
+    SetHoleState(e, outRec);
   } else
   {
-    PolyPt* pp = m_PolyPts[e->outIdx];
-    if (ToFront && PointsEqual(pt, pp->pt)) return pp;
-    if (!ToFront && PointsEqual(pt, pp->prev->pt)) return pp->prev;
-
-    PolyPt* newPolyPt = new PolyPt;
-    newPolyPt->pt = pt;
-    newPolyPt->isHole = pp->isHole;
-    newPolyPt->next = pp;
-    newPolyPt->prev = pp->prev;
-    newPolyPt->prev->next = newPolyPt;
-    pp->prev = newPolyPt;
-    if (ToFront) m_PolyPts[e->outIdx] = newPolyPt;
-    return newPolyPt;
+    OutRec *outRec = m_PolyOuts[e->outIdx];
+    OutPt* op = outRec->pts;
+    if ((ToFront && PointsEqual(pt, op->pt)) ||
+      (!ToFront && PointsEqual(pt, op->prev->pt))) return;
+    OutPt* op2 = new OutPt;
+    op2->pt = pt;
+    op2->idx = outRec->idx;
+    if (op2->pt.Y == outRec->bottomPt->pt.Y &&
+      op2->pt.X < outRec->bottomPt->pt.X)
+    {
+      outRec->bottomPt = op2;
+      outRec->bottomE1 = e;
+      outRec->bottomE2 = altE;
+    }
+    op2->next = op;
+    op2->prev = op->prev;
+    op2->prev->next = op2;
+    op->prev = op2;
+    if (ToFront) outRec->pts = op2;
   }
 }
 //------------------------------------------------------------------------------
@@ -1449,7 +2116,7 @@ bool IsIntermediate(TEdge *e, const long64 Y)
 
 TEdge *GetMaximaPair(TEdge *e)
 {
-  if( !IsMaxima(e->next, e->ytop) || (e->next->xtop != e->xtop) )
+  if( !IsMaxima(e->next, e->ytop) || e->next->xtop != e->xtop )
     return e->prev; else
     return e->next;
 }
@@ -1457,8 +2124,8 @@ TEdge *GetMaximaPair(TEdge *e)
 
 void Clipper::SwapPositionsInAEL(TEdge *edge1, TEdge *edge2)
 {
-  if(  !( edge1->nextInAEL ) &&  !( edge1->prevInAEL ) ) return;
-  if(  !( edge2->nextInAEL ) &&  !( edge2->prevInAEL ) ) return;
+  if(  !edge1->nextInAEL &&  !edge1->prevInAEL ) return;
+  if(  !edge2->nextInAEL &&  !edge2->prevInAEL ) return;
 
   if(  edge1->nextInAEL == edge2 )
   {
@@ -1579,12 +2246,15 @@ void Clipper::ProcessHorizontal(TEdge *horzEdge)
   while( e )
   {
     TEdge* eNext = GetNextInAEL( e, dir );
-    if( e->xcurr >= horzLeft && e->xcurr <= horzRight )
+
+    if (eMaxPair ||
+      ((dir == dLeftToRight) && (e->xcurr <= horzRight)) ||
+      ((dir == dRightToLeft) && (e->xcurr >= horzLeft)))
     {
       //ok, so far it looks like we're still in range of the horizontal edge
-      if ( e->xcurr == horzEdge->xtop && horzEdge->nextInLML)
+      if ( e->xcurr == horzEdge->xtop && !eMaxPair )
       {
-        if (SlopesEqual(*e, *horzEdge->nextInLML))
+        if (SlopesEqual(*e, *horzEdge->nextInLML, m_UseFullRange))
         {
           //if output polygons share an edge, they'll need joining later ...
           if (horzEdge->outIdx >= 0 && e->outIdx >= 0)
@@ -1604,9 +2274,10 @@ void Clipper::ProcessHorizontal(TEdge *horzEdge)
           IntersectEdges(horzEdge, e, IntPoint(e->xcurr, horzEdge->ycurr), ipNone);
         else
           IntersectEdges(e, horzEdge, IntPoint(e->xcurr, horzEdge->ycurr), ipNone);
+        if (eMaxPair->outIdx >= 0) throw clipperException("ProcessHorizontal error");
         return;
       }
-      else if( e->dx == horizontal &&  !IsMinima(e) && !(e->xcurr > e->xtop) )
+      else if( NEAR_EQUAL(e->dx, HORIZONTAL) &&  !IsMinima(e) && !(e->xcurr > e->xtop) )
       {
         //An overlapping horizontal edge. Overlapping horizontal edges are
         //processed as if layered with the current horizontal edge (horizEdge)
@@ -1631,17 +2302,15 @@ void Clipper::ProcessHorizontal(TEdge *horzEdge)
       }
       SwapPositionsInAEL( horzEdge, e );
     }
-    else if( dir == dLeftToRight &&
-      e->xcurr > horzRight  && m_SortedEdges ) break;
-    else if( dir == dRightToLeft &&
-      e->xcurr < horzLeft && m_SortedEdges ) break;
+    else if( (dir == dLeftToRight && e->xcurr > horzRight  && m_SortedEdges) ||
+     (dir == dRightToLeft && e->xcurr < horzLeft && m_SortedEdges) ) break;
     e = eNext;
   } //end while
 
   if( horzEdge->nextInLML )
   {
     if( horzEdge->outIdx >= 0 )
-      AddPolyPt( horzEdge, IntPoint(horzEdge->xtop, horzEdge->ytop));
+      AddOutPt( horzEdge, 0, IntPoint(horzEdge->xtop, horzEdge->ytop));
     UpdateEdgeIntoAEL( horzEdge );
   }
   else
@@ -1673,22 +2342,15 @@ void Clipper::UpdateEdgeIntoAEL(TEdge *&e)
   e = e->nextInLML;
   e->prevInAEL = AelPrev;
   e->nextInAEL = AelNext;
-  if( e->dx != horizontal )
-  {
-    InsertScanbeam( e->ytop );
-    //if output polygons share an edge, they'll need joining later ...
-    if (e->outIdx >= 0 && AelPrev && AelPrev->outIdx >= 0 &&
-      AelPrev->xbot == e->xcurr && SlopesEqual(*e, *AelPrev))
-        AddJoin(e, AelPrev);
-  }
+  if( !NEAR_EQUAL(e->dx, HORIZONTAL) ) InsertScanbeam( e->ytop );
 }
 //------------------------------------------------------------------------------
 
-bool Clipper::ProcessIntersections( const long64 topY)
+bool Clipper::ProcessIntersections(const long64 botY, const long64 topY)
 {
   if( !m_ActiveEdges ) return true;
   try {
-    BuildIntersectList(topY);
+    BuildIntersectList(botY, topY);
     if ( !m_IntersectNodes) return true;
     if ( FixupIntersections() ) ProcessIntersectList();
     else return false;
@@ -1713,7 +2375,7 @@ void Clipper::DisposeIntersectNodes()
 }
 //------------------------------------------------------------------------------
 
-void Clipper::BuildIntersectList(const long64 topY)
+void Clipper::BuildIntersectList(const long64 botY, const long64 topY)
 {
   if ( !m_ActiveEdges ) return;
 
@@ -1742,8 +2404,14 @@ void Clipper::BuildIntersectList(const long64 topY)
     {
       TEdge *eNext = e->nextInSEL;
       IntPoint pt;
-      if(e->tmpX > eNext->tmpX && IntersectPoint(*e, *eNext, pt))
+      if(e->tmpX > eNext->tmpX &&
+        IntersectPoint(*e, *eNext, pt, m_UseFullRange))
       {
+        if (pt.Y > botY)
+        {
+            pt.Y = botY;
+            pt.X = TopX(*e, pt.Y);
+        }
         AddIntersectNode( e, eNext, pt );
         SwapPositionsInSEL(e, eNext);
         isModified = true;
@@ -1766,12 +2434,12 @@ bool Process1Before2(IntersectNode &node1, IntersectNode &node2)
     if (node1.edge1 == node2.edge1 || node1.edge2 == node2.edge1)
     {
       result = node2.pt.X > node1.pt.X;
-      if (node2.edge1->dx > 0) return result; else return !result;
+      if (node2.edge1->dx > 0) return !result; else return result;
     }
     else if (node1.edge1 == node2.edge2 || node1.edge2 == node2.edge2)
     {
       result = node2.pt.X > node1.pt.X;
-      if (node2.edge2->dx > 0) return result; else return !result;
+      if (node2.edge2->dx > 0) return !result; else return result;
     }
     else return node2.pt.X > node1.pt.X;
   }
@@ -1850,7 +2518,7 @@ void Clipper::ProcessEdgesAtTopOfScanbeam(const long64 topY)
   {
     //1. process maxima, treating them as if they're 'bent' horizontal edges,
     //   but exclude maxima with horizontal edges. nb: e can't be a horizontal.
-    if( IsMaxima(e, topY) && GetMaximaPair(e)->dx != horizontal )
+    if( IsMaxima(e, topY) && !NEAR_EQUAL(GetMaximaPair(e)->dx, HORIZONTAL) )
     {
       //'e' might be removed from AEL, as may any following edges so ...
       TEdge* ePrior = e->prevInAEL;
@@ -1861,11 +2529,23 @@ void Clipper::ProcessEdgesAtTopOfScanbeam(const long64 topY)
     else
     {
       //2. promote horizontal edges, otherwise update xcurr and ycurr ...
-      if(  IsIntermediate(e, topY) && e->nextInLML->dx == horizontal )
+      if(  IsIntermediate(e, topY) && NEAR_EQUAL(e->nextInLML->dx, HORIZONTAL) )
       {
         if (e->outIdx >= 0)
         {
-          AddPolyPt(e, IntPoint(e->xtop, e->ytop));
+          AddOutPt(e, 0, IntPoint(e->xtop, e->ytop));
+
+          for (HorzJoinList::size_type i = 0; i < m_HorizJoins.size(); ++i)
+          {
+            IntPoint pt, pt2;
+            HorzJoinRec* hj = m_HorizJoins[i];
+            if (GetOverlapSegment(IntPoint(hj->edge->xbot, hj->edge->ybot),
+              IntPoint(hj->edge->xtop, hj->edge->ytop),
+              IntPoint(e->nextInLML->xbot, e->nextInLML->ybot),
+              IntPoint(e->nextInLML->xtop, e->nextInLML->ytop), pt, pt2))
+                AddJoin(hj->edge, e->nextInLML, hj->savedIdx, e->outIdx);
+          }
+
           AddHorzJoin(e->nextInLML, e->outIdx);
         }
         UpdateEdgeIntoAEL(e);
@@ -1889,36 +2569,69 @@ void Clipper::ProcessEdgesAtTopOfScanbeam(const long64 topY)
   {
     if( IsIntermediate( e, topY ) )
     {
-      if( e->outIdx >= 0 ) AddPolyPt(e, IntPoint(e->xtop,e->ytop));
+      if( e->outIdx >= 0 ) AddOutPt(e, 0, IntPoint(e->xtop,e->ytop));
       UpdateEdgeIntoAEL(e);
+
+      //if output polygons share an edge, they'll need joining later ...
+      if (e->outIdx >= 0 && e->prevInAEL && e->prevInAEL->outIdx >= 0 &&
+        e->prevInAEL->xcurr == e->xbot && e->prevInAEL->ycurr == e->ybot &&
+        SlopesEqual(IntPoint(e->xbot,e->ybot), IntPoint(e->xtop, e->ytop),
+          IntPoint(e->xbot,e->ybot),
+          IntPoint(e->prevInAEL->xtop, e->prevInAEL->ytop), m_UseFullRange))
+      {
+        AddOutPt(e->prevInAEL, 0, IntPoint(e->xbot, e->ybot));
+        AddJoin(e, e->prevInAEL);
+      }
+      else if (e->outIdx >= 0 && e->nextInAEL && e->nextInAEL->outIdx >= 0 &&
+        e->nextInAEL->ycurr > e->nextInAEL->ytop &&
+        e->nextInAEL->ycurr < e->nextInAEL->ybot &&
+        e->nextInAEL->xcurr == e->xbot && e->nextInAEL->ycurr == e->ybot &&
+        SlopesEqual(IntPoint(e->xbot,e->ybot), IntPoint(e->xtop, e->ytop),
+          IntPoint(e->xbot,e->ybot),
+          IntPoint(e->nextInAEL->xtop, e->nextInAEL->ytop), m_UseFullRange))
+      {
+        AddOutPt(e->nextInAEL, 0, IntPoint(e->xbot, e->ybot));
+        AddJoin(e, e->nextInAEL);
+      }
     }
     e = e->nextInAEL;
   }
 }
 //------------------------------------------------------------------------------
 
-PolyPt* FixupOutPolygon(PolyPt *p)
+void Clipper::FixupOutPolygon(OutRec &outRec)
 {
   //FixupOutPolygon() - removes duplicate points and simplifies consecutive
   //parallel edges by removing the middle vertex.
-  if (!p) return 0;
-  PolyPt *pp = p, *result = p, *lastOK = 0;
+  OutPt *lastOK = 0;
+  outRec.pts = outRec.bottomPt;
+  OutPt *pp = outRec.bottomPt;
+
   for (;;)
   {
     if (pp->prev == pp || pp->prev == pp->next )
     {
-      DisposePolyPts(pp);
-      return 0;
+      DisposeOutPts(pp);
+      outRec.pts = 0;
+      outRec.bottomPt = 0;
+      return;
     }
     //test for duplicate points and for same slope (cross-product) ...
     if ( PointsEqual(pp->pt, pp->next->pt) ||
-      SlopesEqual(pp->prev->pt, pp->pt, pp->next->pt) )
+      SlopesEqual(pp->prev->pt, pp->pt, pp->next->pt, m_UseFullRange) )
     {
       lastOK = 0;
+      OutPt *tmp = pp;
+      if (pp == outRec.bottomPt)
+      {
+          if (tmp->prev->pt.Y > tmp->next->pt.Y)
+            outRec.bottomPt = tmp->prev; else
+            outRec.bottomPt = tmp->next;
+          outRec.pts = outRec.bottomPt;
+          outRec.bottomPt->idx = outRec.idx;
+      }
       pp->prev->next = pp->next;
       pp->next->prev = pp->prev;
-      PolyPt* tmp = pp;
-      if (pp == result) result = pp->prev;
       pp = pp->prev;
       delete tmp;
     }
@@ -1929,40 +2642,66 @@ PolyPt* FixupOutPolygon(PolyPt *p)
       pp = pp->next;
     }
   }
-  return result;
 }
 //------------------------------------------------------------------------------
 
-void Clipper::BuildResult(Polygons &polypoly)
+void Clipper::BuildResult(Polygons &polys)
 {
-  for (PolyPtList::size_type i = 0; i < m_PolyPts.size(); ++i)
-    if (m_PolyPts[i])
-    {
-      m_PolyPts[i] = FixupOutPolygon(m_PolyPts[i]);
-      //fix orientation ...
-      PolyPt *p = m_PolyPts[i];
-      if (p && p->isHole == IsClockwise(p))
-        ReversePolyPtLinks(*p);
-    }
-  JoinCommonEdges();
-
   int k = 0;
-  polypoly.resize(m_PolyPts.size());
-  for (unsigned i = 0; i < m_PolyPts.size(); ++i) {
-    if (m_PolyPts[i]) {
-      Polygon* pg = &polypoly[k];
+  polys.resize(m_PolyOuts.size());
+  for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
+  {
+    if (m_PolyOuts[i]->pts)
+    {
+      Polygon* pg = &polys[k];
       pg->clear();
-      PolyPt* p = m_PolyPts[i];
-
-      do {
+      OutPt* p = m_PolyOuts[i]->pts;
+      do
+      {
         pg->push_back(p->pt);
         p = p->next;
-      } while (p != m_PolyPts[i]);
+      } while (p != m_PolyOuts[i]->pts);
       //make sure each polygon has at least 3 vertices ...
       if (pg->size() < 3) pg->clear(); else k++;
     }
   }
-  polypoly.resize(k);
+  polys.resize(k);
+}
+//------------------------------------------------------------------------------
+
+void Clipper::BuildResultEx(ExPolygons &polys)
+{
+  PolyOutList::size_type i = 0;
+  int k = 0;
+  polys.resize(0);
+  polys.reserve(m_PolyOuts.size());
+  while (i < m_PolyOuts.size() && m_PolyOuts[i]->pts)
+  {
+    ExPolygon epg;
+    OutPt* p = m_PolyOuts[i]->pts;
+    do {
+      epg.outer.push_back(p->pt);
+      p = p->next;
+    } while (p != m_PolyOuts[i]->pts);
+    i++;
+    //make sure polygons have at least 3 vertices ...
+    if (epg.outer.size() < 3) continue;
+    while (i < m_PolyOuts.size()
+      && m_PolyOuts[i]->pts && m_PolyOuts[i]->isHole)
+    {
+      Polygon pg;
+      p = m_PolyOuts[i]->pts;
+      do {
+        pg.push_back(p->pt);
+        p = p->next;
+      } while (p != m_PolyOuts[i]->pts);
+      epg.holes.push_back(pg);
+      i++;
+    }
+    polys.push_back(epg);
+    k++;
+  }
+  polys.resize(k);
 }
 //------------------------------------------------------------------------------
 
@@ -2060,7 +2799,7 @@ void Clipper::InsertEdgeIntoAEL(TEdge *edge)
 
 void Clipper::DoEdge1(TEdge *edge1, TEdge *edge2, const IntPoint &pt)
 {
-  AddPolyPt(edge1, pt);
+  AddOutPt(edge1, edge2, pt);
   SwapSides(*edge1, *edge2);
   SwapPolyIndexes(*edge1, *edge2);
 }
@@ -2068,7 +2807,7 @@ void Clipper::DoEdge1(TEdge *edge1, TEdge *edge2, const IntPoint &pt)
 
 void Clipper::DoEdge2(TEdge *edge1, TEdge *edge2, const IntPoint &pt)
 {
-  AddPolyPt(edge2, pt);
+  AddOutPt(edge2, edge1, pt);
   SwapSides(*edge1, *edge2);
   SwapPolyIndexes(*edge1, *edge2);
 }
@@ -2076,206 +2815,202 @@ void Clipper::DoEdge2(TEdge *edge1, TEdge *edge2, const IntPoint &pt)
 
 void Clipper::DoBothEdges(TEdge *edge1, TEdge *edge2, const IntPoint &pt)
 {
-  AddPolyPt(edge1, pt);
-  AddPolyPt(edge2, pt);
+  AddOutPt(edge1, edge2, pt);
+  AddOutPt(edge2, edge1, pt);
   SwapSides( *edge1 , *edge2 );
   SwapPolyIndexes( *edge1 , *edge2 );
 }
 //----------------------------------------------------------------------
 
-bool Clipper::IsHole(TEdge *e)
+void Clipper::CheckHoleLinkages1(OutRec *outRec1, OutRec *outRec2)
 {
-  bool hole = false;
-  TEdge *e2 = m_ActiveEdges;
-  while (e2 && e2 != e)
+  //when a polygon is split into 2 polygons, make sure any holes the original
+  //polygon contained link to the correct polygon ...
+  for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
   {
-    if (e2->outIdx >= 0) hole = !hole;
-    e2 = e2->nextInAEL;
+    OutRec *orec = m_PolyOuts[i];
+    if (orec->isHole && orec->bottomPt && orec->FirstLeft == outRec1 &&
+      !PointInPolygon(orec->bottomPt->pt, outRec1->pts, m_UseFullRange))
+        orec->FirstLeft = outRec2;
   }
-  return hole;
 }
 //----------------------------------------------------------------------
 
-PolyPt* DeletePolyPt(PolyPt* pp)
-{
-  if (pp->next == pp)
-  {
-    delete pp;
-    return 0;
-  } else
-  {
-    PolyPt* result = pp->prev;
-    pp->next->prev = result;
-    result->next = pp->next;
-    delete pp;
-    return result;
-  }
-}
-//------------------------------------------------------------------------------
-
-PolyPt* FixSpikes(PolyPt *pp)
+void Clipper::CheckHoleLinkages2(OutRec *outRec1, OutRec *outRec2)
 {
-  PolyPt *pp2 = pp, *pp3;
-  PolyPt *result = pp;
-  do
-  {
-    if (SlopesEqual(pp2->prev->pt, pp2->pt, pp2->next->pt) &&
-      ((((pp2->prev->pt.X < pp2->pt.X) == (pp2->next->pt.X < pp2->pt.X)) &&
-      ((pp2->prev->pt.X != pp2->pt.X) || (pp2->next->pt.X != pp2->pt.X))) ||
-      ((((pp2->prev->pt.Y < pp2->pt.Y) == (pp2->next->pt.Y < pp2->pt.Y))) &&
-      ((pp2->prev->pt.Y != pp2->pt.Y) || (pp2->next->pt.Y != pp2->pt.Y)))))
-    {
-      if (pp2 == result) result = pp2->prev;
-      pp3 = pp2->next;
-      DeletePolyPt(pp2);
-      pp2 = pp3;
-    } else
-      pp2 = pp2->next;
-  }
-  while (pp2 != result);
-  return result;
+  //if a hole is owned by outRec2 then make it owned by outRec1 ...
+  for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
+    if (m_PolyOuts[i]->isHole && m_PolyOuts[i]->bottomPt &&
+      m_PolyOuts[i]->FirstLeft == outRec2)
+        m_PolyOuts[i]->FirstLeft = outRec1;
 }
-//------------------------------------------------------------------------------
+//----------------------------------------------------------------------
 
-void Clipper::JoinCommonEdges()
+void Clipper::JoinCommonEdges(bool fixHoleLinkages)
 {
   for (JoinList::size_type i = 0; i < m_Joins.size(); i++)
   {
-    PolyPt *pp1a, *pp1b, *pp2a, *pp2b;
-    IntPoint pt1, pt2;
     JoinRec* j = m_Joins[i];
-
-    pp1a = m_PolyPts[j->poly1Idx];
-    pp2a = m_PolyPts[j->poly2Idx];
-    bool found = FindSegment(pp1a, j->pt1a, j->pt1b);
-    if (found)
+    OutRec *outRec1 = m_PolyOuts[j->poly1Idx];
+    OutPt *pp1a = outRec1->pts;
+    OutRec *outRec2 = m_PolyOuts[j->poly2Idx];
+    OutPt *pp2a = outRec2->pts;
+    IntPoint pt1 = j->pt2a, pt2 = j->pt2b;
+    IntPoint pt3 = j->pt1a, pt4 = j->pt1b;
+    if (!FindSegment(pp1a, pt1, pt2)) continue;
+    if (j->poly1Idx == j->poly2Idx)
     {
-      if (j->poly1Idx == j->poly2Idx)
-      {
-        //we're searching the same polygon for overlapping segments so
-        //we really don't want segment 2 to be the same as segment 1 ...
-        pp2a = pp1a->next;
-        found = FindSegment(pp2a, j->pt2a, j->pt2b) && (pp2a != pp1a);
-      }
-      else
-        found = FindSegment(pp2a, j->pt2a, j->pt2b);
+      //we're searching the same polygon for overlapping segments so
+      //segment 2 mustn't be the same as segment 1 ...
+      pp2a = pp1a->next;
+      if (!FindSegment(pp2a, pt3, pt4) || (pp2a == pp1a)) continue;
+    }
+    else if (!FindSegment(pp2a, pt3, pt4)) continue;
+
+    if (!GetOverlapSegment(pt1, pt2, pt3, pt4, pt1, pt2)) continue;
+
+    OutPt *p1, *p2, *p3, *p4;
+    OutPt *prev = pp1a->prev;
+    //get p1 & p2 polypts - the overlap start & endpoints on poly1
+    if (PointsEqual(pp1a->pt, pt1)) p1 = pp1a;
+    else if (PointsEqual(prev->pt, pt1)) p1 = prev;
+    else p1 = InsertPolyPtBetween(pp1a, prev, pt1);
+
+    if (PointsEqual(pp1a->pt, pt2)) p2 = pp1a;
+    else if (PointsEqual(prev->pt, pt2)) p2 = prev;
+    else if ((p1 == pp1a) || (p1 == prev))
+      p2 = InsertPolyPtBetween(pp1a, prev, pt2);
+    else if (Pt3IsBetweenPt1AndPt2(pp1a->pt, p1->pt, pt2))
+      p2 = InsertPolyPtBetween(pp1a, p1, pt2); else
+      p2 = InsertPolyPtBetween(p1, prev, pt2);
+
+    //get p3 & p4 polypts - the overlap start & endpoints on poly2
+    prev = pp2a->prev;
+    if (PointsEqual(pp2a->pt, pt1)) p3 = pp2a;
+    else if (PointsEqual(prev->pt, pt1)) p3 = prev;
+    else p3 = InsertPolyPtBetween(pp2a, prev, pt1);
+
+    if (PointsEqual(pp2a->pt, pt2)) p4 = pp2a;
+    else if (PointsEqual(prev->pt, pt2)) p4 = prev;
+    else if ((p3 == pp2a) || (p3 == prev))
+      p4 = InsertPolyPtBetween(pp2a, prev, pt2);
+    else if (Pt3IsBetweenPt1AndPt2(pp2a->pt, p3->pt, pt2))
+      p4 = InsertPolyPtBetween(pp2a, p3, pt2); else
+      p4 = InsertPolyPtBetween(p3, prev, pt2);
+
+    //p1.pt == p3.pt and p2.pt == p4.pt so join p1 to p3 and p2 to p4 ...
+    if (p1->next == p2 && p3->prev == p4)
+    {
+      p1->next = p3;
+      p3->prev = p1;
+      p2->prev = p4;
+      p4->next = p2;
+    }
+    else if (p1->prev == p2 && p3->next == p4)
+    {
+      p1->prev = p3;
+      p3->next = p1;
+      p2->next = p4;
+      p4->prev = p2;
     }
+    else
+      continue; //an orientation is probably wrong
 
-    if (found)
+    if (j->poly2Idx == j->poly1Idx)
     {
-      if (PointsEqual(pp1a->next->pt, j->pt1b))
-        pp1b = pp1a->next; else pp1b = pp1a->prev;
-      if (PointsEqual(pp2a->next->pt, j->pt2b))
-        pp2b = pp2a->next; else pp2b = pp2a->prev;
-      if (GetOverlapSegment(pp1a->pt, pp1b->pt, pp2a->pt, pp2b->pt, pt1, pt2))
+      //instead of joining two polygons, we've just created a new one by
+      //splitting one polygon into two.
+      outRec1->pts = PolygonBottom(p1);
+      outRec1->bottomPt = outRec1->pts;
+      outRec1->bottomPt->idx = outRec1->idx;
+      outRec2 = CreateOutRec();
+      m_PolyOuts.push_back(outRec2);
+      outRec2->idx = (int)m_PolyOuts.size()-1;
+      j->poly2Idx = outRec2->idx;
+      outRec2->pts = PolygonBottom(p2);
+      outRec2->bottomPt = outRec2->pts;
+      outRec2->bottomPt->idx = outRec2->idx;
+
+      if (PointInPolygon(outRec2->pts->pt, outRec1->pts, m_UseFullRange))
       {
-        PolyPt *p1, *p2, *p3, *p4;
-        //get p1 & p2 polypts - the overlap start & endpoints on poly1
-        Position pos1 = GetPosition(pp1a->pt, pp1b->pt, pt1);
-        if (pos1 == pFirst) p1 = pp1a;
-        else if (pos1 == pSecond) p1 = pp1b;
-        else p1 = InsertPolyPtBetween(pp1a, pp1b, pt1);
-        Position pos2 = GetPosition(pp1a->pt, pp1b->pt, pt2);
-        if (pos2 == pMiddle)
-        {
-          if (pos1 == pMiddle)
-          {
-            if (Pt3IsBetweenPt1AndPt2(pp1a->pt, p1->pt, pt2))
-              p2 = InsertPolyPtBetween(pp1a, p1, pt2); else
-              p2 = InsertPolyPtBetween(p1, pp1b, pt2);
-          }
-          else if (pos2 == pFirst) p2 = pp1a;
-          else p2 = pp1b;
-        }
-        else if (pos2 == pFirst) p2 = pp1a;
-        else p2 = pp1b;
-        //get p3 & p4 polypts - the overlap start & endpoints on poly2
-        pos1 = GetPosition(pp2a->pt, pp2b->pt, pt1);
-        if (pos1 == pFirst) p3 = pp2a;
-        else if (pos1 == pSecond) p3 = pp2b;
-        else p3 = InsertPolyPtBetween(pp2a, pp2b, pt1);
-        pos2 = GetPosition(pp2a->pt, pp2b->pt, pt2);
-        if (pos2 == pMiddle)
-        {
-          if (pos1 == pMiddle)
-          {
-            if (Pt3IsBetweenPt1AndPt2(pp2a->pt, p3->pt, pt2))
-              p4 = InsertPolyPtBetween(pp2a, p3, pt2); else
-              p4 = InsertPolyPtBetween(p3, pp2b, pt2);
-          }
-          else if (pos2 == pFirst) p4 = pp2a;
-          else p4 = pp2b;
-        }
-        else if (pos2 == pFirst) p4 = pp2a;
-        else p4 = pp2b;
-
-        //p1.pt should equal p3.pt and p2.pt should equal p4.pt here, so ...
-        //join p1 to p3 and p2 to p4 ...
-        if (p1->next == p2 && p3->prev == p4)
-        {
-          p1->next = p3;
-          p3->prev = p1;
-          p2->prev = p4;
-          p4->next = p2;
-        }
-        else if (p1->prev == p2 && p3->next == p4)
-        {
-          p1->prev = p3;
-          p3->next = p1;
-          p2->next = p4;
-          p4->prev = p2;
-        }
-        else
-          continue; //an orientation is probably wrong
-
-        //delete duplicate points  ...
-        if (PointsEqual(p1->pt, p3->pt)) DeletePolyPt(p3);
-        if (PointsEqual(p2->pt, p4->pt)) DeletePolyPt(p4);
-
-        if (j->poly2Idx == j->poly1Idx)
-        {
-          //instead of joining two polygons, we've just created
-          //a new one by splitting one polygon into two.
-          m_PolyPts[j->poly1Idx] = p1;
-          m_PolyPts.push_back(p2);
-          j->poly2Idx = m_PolyPts.size()-1;
-
-          if (PointInPolygon(p2->pt, p1)) SetHoleState(p2, !p1->isHole);
-          else if (PointInPolygon(p1->pt, p2)) SetHoleState(p1, !p2->isHole);
-
-          //now fixup any subsequent m_Joins that match this polygon
-          for (JoinList::size_type k = i+1; k < m_Joins.size(); k++)
-          {
-            JoinRec* j2 = m_Joins[k];
-            if (j2->poly1Idx == j->poly1Idx && PointIsVertex(j2->pt1a, p2))
-              j2->poly1Idx = j->poly2Idx;
-            if (j2->poly2Idx == j->poly1Idx && PointIsVertex(j2->pt2a, p2))
-              j2->poly2Idx = j->poly2Idx;
-          }
-        } else
-        {
-          //having joined 2 polygons together, delete the obsolete pointer ...
-          m_PolyPts[j->poly2Idx] = 0;
-
-          //now fixup any subsequent fJoins that match this polygon
-          for (JoinList::size_type k = i+1; k < m_Joins.size(); k++)
-          {
-            JoinRec* j2 = m_Joins[k];
-            if (j2->poly1Idx == j->poly2Idx) j2->poly1Idx = j->poly1Idx;
-            if (j2->poly2Idx == j->poly2Idx) j2->poly2Idx = j->poly1Idx;
-          }
-          j->poly2Idx = j->poly1Idx;
-        }
+        outRec2->isHole = !outRec1->isHole;
+        outRec2->FirstLeft = outRec1;
+        if (outRec2->isHole == Orientation(outRec2, m_UseFullRange))
+          ReversePolyPtLinks(*outRec2->pts);
+      } else if (PointInPolygon(outRec1->pts->pt, outRec2->pts, m_UseFullRange))
+      {
+        outRec2->isHole = outRec1->isHole;
+        outRec1->isHole = !outRec2->isHole;
+        outRec2->FirstLeft = outRec1->FirstLeft;
+        outRec1->FirstLeft = outRec2;
+        if (outRec1->isHole == Orientation(outRec1, m_UseFullRange))
+          ReversePolyPtLinks(*outRec1->pts);
+      } else
+      {
+        outRec2->isHole = outRec1->isHole;
+        outRec2->FirstLeft = outRec1->FirstLeft;
+        //make sure any contained holes now link to the correct polygon ...
+        if (fixHoleLinkages) CheckHoleLinkages1(outRec1, outRec2);
+      }
 
-        //now cleanup redundant edges too ...
-        m_PolyPts[j->poly1Idx] = FixSpikes(p1);
-        if (j->poly2Idx != j->poly1Idx)
-          m_PolyPts[j->poly2Idx] = FixSpikes(p2);
+      //now fixup any subsequent joins that match this polygon
+      for (JoinList::size_type k = i+1; k < m_Joins.size(); k++)
+      {
+        JoinRec* j2 = m_Joins[k];
+        if (j2->poly1Idx == j->poly1Idx && PointIsVertex(j2->pt1a, p2))
+          j2->poly1Idx = j->poly2Idx;
+        if (j2->poly2Idx == j->poly1Idx && PointIsVertex(j2->pt2a, p2))
+          j2->poly2Idx = j->poly2Idx;
+      }
 
+      //now cleanup redundant edges too ...
+      FixupOutPolygon(*outRec1);
+      FixupOutPolygon(*outRec2);
+    } else
+    {
+      //joined 2 polygons together ...
+
+      //make sure any holes contained by outRec2 now link to outRec1 ...
+      if (fixHoleLinkages) CheckHoleLinkages2(outRec1, outRec2);
+
+      //delete the obsolete pointer ...
+      int OKIdx = outRec1->idx;
+      int ObsoleteIdx = outRec2->idx;
+      outRec2->pts = 0;
+      outRec2->bottomPt = 0;
+      outRec2->AppendLink = outRec1;
+      //holes are practically always joined to outers, not vice versa ...
+      if (outRec1->isHole && !outRec2->isHole) outRec1->isHole = false;
+
+      //now fixup any subsequent Joins that match this polygon
+      for (JoinList::size_type k = i+1; k < m_Joins.size(); k++)
+      {
+        JoinRec* j2 = m_Joins[k];
+        if (j2->poly1Idx == ObsoleteIdx) j2->poly1Idx = OKIdx;
+        if (j2->poly2Idx == ObsoleteIdx) j2->poly2Idx = OKIdx;
       }
+
+      //now cleanup redundant edges too ...
+      if (outRec1->pts)
+        FixupOutPolygon(*outRec1);
+      else
+        FixupOutPolygon(*outRec2);
     }
   }
 }
+//------------------------------------------------------------------------------
+
+void ReversePoints(Polygon& p)
+{
+  std::reverse(p.begin(), p.end());
+}
+//------------------------------------------------------------------------------
+
+void ReversePoints(Polygons& p)
+{
+  for (Polygons::size_type i = 0; i < p.size(); ++i)
+    ReversePoints(p[i]);
+}
 
 //------------------------------------------------------------------------------
 // OffsetPolygon functions ...
@@ -2287,11 +3022,12 @@ struct DoublePoint
   double Y;
   DoublePoint(double x = 0, double y = 0) : X(x), Y(y) {}
 };
+//------------------------------------------------------------------------------
 
 Polygon BuildArc(const IntPoint &pt,
   const double a1, const double a2, const double r)
 {
-  int steps = std::max(6, int(std::sqrt(std::abs(r)) * std::abs(a2 - a1)));
+  int steps = std::max(6, int(std::sqrt(std::fabs(r)) * std::fabs(a2 - a1)));
   Polygon result(steps);
   int n = steps - 1;
   double da = (a2 - a1) / n;
@@ -2308,115 +3044,259 @@ Polygon BuildArc(const IntPoint &pt,
 
 DoublePoint GetUnitNormal( const IntPoint &pt1, const IntPoint &pt2)
 {
-  double dx = static_cast<double>(pt2.X - pt1.X);
-  double dy = static_cast<double>(pt2.Y - pt1.Y);
-  if(  ( dx == 0 ) && ( dy == 0 ) ) return DoublePoint( 0, 0 );
+  if(pt2.X == pt1.X && pt2.Y == pt1.Y) 
+    return DoublePoint(0, 0);
 
+  double dx = (double)(pt2.X - pt1.X);
+  double dy = (double)(pt2.Y - pt1.Y);
   double f = 1 *1.0/ std::sqrt( dx*dx + dy*dy );
   dx *= f;
   dy *= f;
   return DoublePoint(dy, -dx);
 }
+
+//------------------------------------------------------------------------------
 //------------------------------------------------------------------------------
 
-Polygons OffsetPolygons(const Polygons &pts, const float &delta)
+class PolyOffsetBuilder
 {
-  if (delta == 0) return pts;
+private:
+  Polygons m_p;
+  Polygon* m_curr_poly;
+  std::vector<DoublePoint> normals;
+  double m_delta, m_RMin, m_R;
+  size_t m_i, m_j, m_k;
+  static const int buffLength = 128;
+  JoinType m_jointype;
+ 
+public:
 
-  double deltaSq = delta*delta;
-  Polygons result(pts.size());
+PolyOffsetBuilder(const Polygons& in_polys, Polygons& out_polys,
+  double delta, JoinType jointype, double MiterLimit)
+{
+    //nb precondition - out_polys != ptsin_polys
+    if (NEAR_ZERO(delta))
+    {
+        out_polys = in_polys;
+        return;
+    }
 
-  for (int j = 0; j < (int)pts.size(); ++j)
-  {
-    int highI = (int)pts[j].size() -1;
-    //to minimize artefacts, strip out those polygons where
-    //it's shrinking and where its area < Sqr(delta) ...
-    double a1 = Area(pts[j]);
-    if (delta < 0) { if (a1 > 0 && a1 < deltaSq) highI = 0;}
-    else if (a1 < 0 && -a1 < deltaSq) highI = 0; //nb: a hole if area < 0
+    this->m_p = in_polys;
+    this->m_delta = delta;
+    this->m_jointype = jointype;
+    if (MiterLimit <= 1) MiterLimit = 1;
+    m_RMin = 2/(MiterLimit*MiterLimit);
+ 
+    double deltaSq = delta*delta;
+    out_polys.clear();
+    out_polys.resize(in_polys.size());
+    for (m_i = 0; m_i < in_polys.size(); m_i++)
+    {
+        m_curr_poly = &out_polys[m_i];
+        size_t len = in_polys[m_i].size();
+        if (len > 1 && m_p[m_i][0].X == m_p[m_i][len - 1].X &&
+            m_p[m_i][0].Y == m_p[m_i][len-1].Y) len--;
+
+        //when 'shrinking' polygons - to minimize artefacts
+        //strip those polygons that have an area < pi * delta^2 ...
+        double a1 = Area(in_polys[m_i]);
+        if (delta < 0) { if (a1 > 0 && a1 < deltaSq *pi) len = 0; }
+        else if (a1 < 0 && -a1 < deltaSq *pi) len = 0; //holes have neg. area
+
+        if (len == 0 || (len < 3 && delta <= 0))
+          continue;
+        else if (len == 1)
+        {
+            Polygon arc;
+            arc = BuildArc(in_polys[m_i][len-1], 0, 2 * pi, delta);
+            out_polys[m_i] = arc;
+            continue;
+        }
 
-    Polygon pg;
-    pg.reserve(highI*2+2);
+        //build normals ...
+        normals.clear();
+        normals.resize(len);
+        normals[len-1] = GetUnitNormal(in_polys[m_i][len-1], in_polys[m_i][0]);
+        for (m_j = 0; m_j < len -1; ++m_j)
+            normals[m_j] = GetUnitNormal(in_polys[m_i][m_j], in_polys[m_i][m_j+1]);
+        
+        m_k = len -1;
+        for (m_j = 0; m_j < len; ++m_j)
+        {
+          switch (jointype)
+          {
+            case jtMiter:
+            {
+              m_R = 1 + (normals[m_j].X*normals[m_k].X + 
+                normals[m_j].Y*normals[m_k].Y);
+              if (m_R >= m_RMin) DoMiter(); else DoSquare(MiterLimit);
+              break;
+            }
+            case jtSquare: DoSquare(); break;
+            case jtRound: DoRound(); break;
+          }
+        m_k = m_j;
+        }
+    }
 
-    if (highI < 2)
+    //finally, clean up untidy corners using Clipper ...
+    Clipper clpr;
+    clpr.AddPolygons(out_polys, ptSubject);
+    if (delta > 0)
+    {
+        if (!clpr.Execute(ctUnion, out_polys, pftPositive, pftPositive))
+            out_polys.clear();
+    }
+    else
     {
-      result.push_back(pg);
-      continue;
+        IntRect r = clpr.GetBounds();
+        Polygon outer(4);
+        outer[0] = IntPoint(r.left - 10, r.bottom + 10);
+        outer[1] = IntPoint(r.right + 10, r.bottom + 10);
+        outer[2] = IntPoint(r.right + 10, r.top - 10);
+        outer[3] = IntPoint(r.left - 10, r.top - 10);
+
+        clpr.AddPolygon(outer, ptSubject);
+        if (clpr.Execute(ctUnion, out_polys, pftNegative, pftNegative))
+        {
+            out_polys.erase(out_polys.begin());
+            ReversePoints(out_polys);
+
+        } else
+            out_polys.clear();
     }
+}
+//------------------------------------------------------------------------------
 
-    std::vector < DoublePoint > normals(highI+1);
-    normals[0] = GetUnitNormal(pts[j][highI], pts[j][0]);
-    for (int i = 1; i <= highI; ++i)
-      normals[i] = GetUnitNormal(pts[j][i-1], pts[j][i]);
+private:
 
-    for (int i = 0; i < highI; ++i)
+void AddPoint(const IntPoint& pt)
+{
+    Polygon::size_type len = m_curr_poly->size();
+    if (len == m_curr_poly->capacity())
+        m_curr_poly->reserve(len + buffLength);
+    m_curr_poly->push_back(pt);
+}
+//------------------------------------------------------------------------------
+
+void DoSquare(double mul = 1.0)
+{
+    IntPoint pt1 = IntPoint((long64)Round(m_p[m_i][m_j].X + normals[m_k].X * m_delta),
+        (long64)Round(m_p[m_i][m_j].Y + normals[m_k].Y * m_delta));
+    IntPoint pt2 = IntPoint((long64)Round(m_p[m_i][m_j].X + normals[m_j].X * m_delta),
+        (long64)Round(m_p[m_i][m_j].Y + normals[m_j].Y * m_delta));
+    if ((normals[m_k].X * normals[m_j].Y - normals[m_j].X * normals[m_k].Y) * m_delta >= 0)
     {
-      pg.push_back(IntPoint(pts[j][i].X + Round(delta *normals[i].X),
-        pts[j][i].Y + Round(delta *normals[i].Y)));
-      pg.push_back(IntPoint(pts[j][i].X + Round(delta *normals[i+1].X),
-        pts[j][i].Y + Round(delta *normals[i+1].Y)));
-    }
-    pg.push_back(IntPoint(pts[j][highI].X + Round(delta *normals[highI].X),
-      pts[j][highI].Y + Round(delta *normals[highI].Y)));
-    pg.push_back(IntPoint(pts[j][highI].X + Round(delta *normals[0].X),
-      pts[j][highI].Y + Round(delta *normals[0].Y)));
-
-    //round off reflex angles (ie > 180 deg) unless it's almost flat (ie < 10deg angle) ...
-    //cross product normals < 0 -> reflex angle; dot product normals == 1 -> no angle
-    if ((normals[highI].X *normals[0].Y - normals[0].X *normals[highI].Y) *delta > 0 &&
-    (normals[0].X *normals[highI].X + normals[0].Y *normals[highI].Y) < 0.985)
-    {
-      double a1 = std::atan2(normals[highI].Y, normals[highI].X);
-      double a2 = std::atan2(normals[0].Y, normals[0].X);
-      if (delta > 0 && a2 < a1) a2 = a2 + pi*2;
-      else if (delta < 0 && a2 > a1) a2 = a2 - pi*2;
-      Polygon arc = BuildArc(pts[j][highI], a1, a2, delta);
-      Polygon::iterator it = pg.begin() +highI*2+1;
-      pg.insert(it, arc.begin(), arc.end());
-    }
-    for (int i = highI; i > 0; --i)
-      if ((normals[i-1].X*normals[i].Y - normals[i].X*normals[i-1].Y) *delta > 0 &&
-      (normals[i].X*normals[i-1].X + normals[i].Y*normals[i-1].Y) < 0.985)
-      {
-        double a1 = std::atan2(normals[i-1].Y, normals[i-1].X);
-        double a2 = std::atan2(normals[i].Y, normals[i].X);
-        if (delta > 0 && a2 < a1) a2 = a2 + pi*2;
-        else if (delta < 0 && a2 > a1) a2 = a2 - pi*2;
-        Polygon arc = BuildArc(pts[j][i-1], a1, a2, delta);
-        Polygon::iterator it = pg.begin() +(i-1)*2+1;
-        pg.insert(it, arc.begin(), arc.end());
-      }
-    result.push_back(pg);
-  }
+        double a1 = std::atan2(normals[m_k].Y, normals[m_k].X);
+        double a2 = std::atan2(-normals[m_j].Y, -normals[m_j].X);
+        a1 = std::fabs(a2 - a1);
+        if (a1 > pi) a1 = pi * 2 - a1;
+        double dx = std::tan((pi - a1)/4) * std::fabs(m_delta * mul);
+        pt1 = IntPoint((long64)(pt1.X -normals[m_k].Y * dx),
+          (long64)(pt1.Y + normals[m_k].X * dx));
+        AddPoint(pt1);
+        pt2 = IntPoint((long64)(pt2.X + normals[m_j].Y * dx),
+          (long64)(pt2.Y -normals[m_j].X * dx));
+        AddPoint(pt2);
+    }
+    else
+    {
+        AddPoint(pt1);
+        AddPoint(m_p[m_i][m_j]);
+        AddPoint(pt2);
+    }
+}
+//------------------------------------------------------------------------------
 
-  //finally, clean up untidy corners ...
-  Clipper c4;
-  c4.AddPolygons(result, ptSubject);
-  if (delta > 0){
-    if(!c4.Execute(ctUnion, result, pftNonZero, pftNonZero))
-      result.clear();
-  }
-  else
-  {
-    IntRect r = c4.GetBounds();
-    Polygon outer(4);
-    outer[0] = IntPoint(r.left-10, r.bottom+10);
-    outer[1] = IntPoint(r.right+10, r.bottom+10);
-    outer[2] = IntPoint(r.right+10, r.top-10);
-    outer[3] = IntPoint(r.left-10, r.top-10);
-    c4.AddPolygon(outer, ptSubject);
-    if (c4.Execute(ctUnion, result, pftNonZero, pftNonZero))
+void DoMiter()
+{
+    if ((normals[m_k].X * normals[m_j].Y - normals[m_j].X * normals[m_k].Y) * m_delta >= 0)
+    {
+        double q = m_delta / m_R;
+        AddPoint(IntPoint((long64)Round(m_p[m_i][m_j].X + 
+            (normals[m_k].X + normals[m_j].X) * q),
+            (long64)Round(m_p[m_i][m_j].Y + (normals[m_k].Y + normals[m_j].Y) * q)));
+    }
+    else
+    {
+        IntPoint pt1 = IntPoint((long64)Round(m_p[m_i][m_j].X + normals[m_k].X *
+          m_delta), (long64)Round(m_p[m_i][m_j].Y + normals[m_k].Y * m_delta));
+        IntPoint pt2 = IntPoint((long64)Round(m_p[m_i][m_j].X + normals[m_j].X *
+          m_delta), (long64)Round(m_p[m_i][m_j].Y + normals[m_j].Y * m_delta));
+        AddPoint(pt1);
+        AddPoint(m_p[m_i][m_j]);
+        AddPoint(pt2);
+    }
+}
+//------------------------------------------------------------------------------
+
+void DoRound()
+{
+    IntPoint pt1 = IntPoint((long64)Round(m_p[m_i][m_j].X + normals[m_k].X * m_delta),
+        (long64)Round(m_p[m_i][m_j].Y + normals[m_k].Y * m_delta));
+    IntPoint pt2 = IntPoint((long64)Round(m_p[m_i][m_j].X + normals[m_j].X * m_delta),
+        (long64)Round(m_p[m_i][m_j].Y + normals[m_j].Y * m_delta));
+    AddPoint(pt1);
+    //round off reflex angles (ie > 180 deg) unless almost flat (ie < ~10deg).
+    if ((normals[m_k].X*normals[m_j].Y - normals[m_j].X*normals[m_k].Y) * m_delta >= 0)
     {
-      Polygons::iterator it = result.begin();
-      result.erase(it);
+      if (normals[m_j].X * normals[m_k].X + normals[m_j].Y * normals[m_k].Y < 0.985)
+      {
+        double a1 = std::atan2(normals[m_k].Y, normals[m_k].X);
+        double a2 = std::atan2(normals[m_j].Y, normals[m_j].X);
+        if (m_delta > 0 && a2 < a1) a2 += pi *2;
+        else if (m_delta < 0 && a2 > a1) a2 -= pi *2;
+        Polygon arc = BuildArc(m_p[m_i][m_j], a1, a2, m_delta);
+        for (Polygon::size_type m = 0; m < arc.size(); m++)
+          AddPoint(arc[m]);
+      }
     }
     else
-      result.clear();
+      AddPoint(m_p[m_i][m_j]);
+    AddPoint(pt2);
+}
+//--------------------------------------------------------------------------
+
+}; //end PolyOffsetBuilder
+
+//------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
+
+void OffsetPolygons(const Polygons &in_polys, Polygons &out_polys,
+  double delta, JoinType jointype, double MiterLimit)
+{
+  if (&out_polys == &in_polys)
+  {
+    Polygons poly2(in_polys);
+    PolyOffsetBuilder(poly2, out_polys, delta, jointype, MiterLimit);
   }
-  return result;
+  else PolyOffsetBuilder(in_polys, out_polys, delta, jointype, MiterLimit);
+}
+//------------------------------------------------------------------------------
+
+std::ostream& operator <<(std::ostream &s, IntPoint& p)
+{
+  s << p.X << ' ' << p.Y << "\n";
+  return s;
 }
 //------------------------------------------------------------------------------
 
-} //namespace clipper
+std::ostream& operator <<(std::ostream &s, Polygon &p)
+{
+  for (Polygon::size_type i = 0; i < p.size(); i++)
+    s << p[i];
+  s << "\n";
+  return s;
+}
+//------------------------------------------------------------------------------
 
+std::ostream& operator <<(std::ostream &s, Polygons &p)
+{
+  for (Polygons::size_type i = 0; i < p.size(); i++)
+    s << p[i];
+  s << "\n";
+  return s;
+}
+//------------------------------------------------------------------------------
 
+} //ClipperLib namespace
diff --git a/scalebar.c b/scalebar.c
index 29dbc46..8c7167b 100644
--- a/scalebar.c
+++ b/scalebar.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -29,7 +29,7 @@
 
 #include "mapserver.h"
 
-MS_CVSID("$Id$")
+
 
 int main(int argc, char *argv[])
 {
@@ -48,14 +48,14 @@ int main(int argc, char *argv[])
   }
 
   map = msLoadMap(argv[1], NULL);
-  if(!map) { 
+  if(!map) {
     msWriteError(stderr);
     exit(1);
   }
 
   image = msDrawScalebar(map);
 
-  if(!image) { 
+  if(!image) {
     msWriteError(stderr);
     exit(1);
   }
@@ -63,6 +63,6 @@ int main(int argc, char *argv[])
   msSaveImage(map, image, argv[2]);
   msFreeImage(image);
 
-  msFreeMap(map);  
+  msFreeMap(map);
   return(MS_TRUE);
 }
diff --git a/shp2img.c b/shp2img.c
index 0b067aa..690d190 100644
--- a/shp2img.c
+++ b/shp2img.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -30,15 +30,15 @@
 #include "mapserver.h"
 #include "maptime.h"
 
-MS_CVSID("$Id$")
+
 
 int main(int argc, char *argv[])
 {
   int i,j,k;
 
-  mapObj    	   *map=NULL;
+  mapObj         *map=NULL;
   imageObj         *image = NULL;
-     
+
   char **layers=NULL;
   int num_layers=0;
 
@@ -49,153 +49,148 @@ int main(int argc, char *argv[])
   int iterations = 1;
   int draws = 0;
 
-  for(i=1;i<argc;i++) { 
+  for(i=1; i<argc; i++) {
     if (strcmp(argv[i],"-c") == 0) { /* user specified number of draws */
       iterations = atoi(argv[i+1]);
       printf("We will draw %d times...\n", iterations);
       continue;
     }
 
-    if(strcmp(argv[i], "-all_debug") == 0 && i < argc-1 ) /* global debug */
-    {
-        int debug_level = atoi(argv[++i]);
+    if(strcmp(argv[i], "-all_debug") == 0 && i < argc-1 ) { /* global debug */
+      int debug_level = atoi(argv[++i]);
 
-        msSetGlobalDebugLevel(debug_level);
+      msSetGlobalDebugLevel(debug_level);
 
-        /* Send output to stderr by default */ 
-        if (msGetErrorFile() == NULL)
-            msSetErrorFile("stderr", NULL);
+      /* Send output to stderr by default */
+      if (msGetErrorFile() == NULL)
+        msSetErrorFile("stderr", NULL);
 
-        continue;
+      continue;
     }
-    
+
   }
-  
+
   for(draws=0; draws<iterations; draws++) {
 
-  struct mstimeval requeststarttime, requestendtime;
+    struct mstimeval requeststarttime, requestendtime;
 
-  if(msGetGlobalDebugLevel() >= MS_DEBUGLEVEL_TUNING) 
+    if(msGetGlobalDebugLevel() >= MS_DEBUGLEVEL_TUNING)
       msGettimeofday(&requeststarttime, NULL);
-      
-  if(argc > 1 && strcmp(argv[1], "-v") == 0) {
-    printf("%s\n", msGetVersion());
-    exit(0);
-  }
 
-  /* ---- check the number of arguments, return syntax if not correct ---- */
-  if( argc < 3 ) {
-    fprintf(stdout, "\nPurpose: convert a mapfile to an image\n\n");
-    fprintf(stdout,
-            "Syntax: shp2img -m mapfile [-o image] [-e minx miny maxx maxy] [-s sizex sizey]\n"
-            "               [-l \"layer1 [layers2...]\"] [-i format]\n"
-            "               [-all_debug n] [-map_debug n] [-layer_debug n] [-p n] [-c n] [-d layername datavalue]\n");
-
-
-    fprintf(stdout,"  -m mapfile: Map file to operate on - required\n" );
-    fprintf(stdout,"  -i format: Override the IMAGETYPE value to pick output format\n" );
-    fprintf(stdout,"  -o image: output filename (stdout if not provided)\n");
-    fprintf(stdout,"  -e minx miny maxx maxy: extents to render\n");
-    fprintf(stdout,"  -s sizex sizey: output image size\n");
-    fprintf(stdout,"  -l layers: layers / groups to enable - make sure they are quoted and space seperated if more than one listed\n" );
-    fprintf(stdout,"  -all_debug n: Set debug level for map and all layers\n" );
-    fprintf(stdout,"  -map_debug n: Set map debug level\n" );
-    fprintf(stdout,"  -layer_debug layer_name n: Set layer debug level\n" );
-    fprintf(stdout,"  -c n: draw map n number of times\n" );
-    fprintf(stdout,"  -p n: pause for n seconds after reading the map\n" );
-    fprintf(stdout,"  -d layername datavalue: change DATA value for layer\n" );
-
-
-    exit(0);
-  }
+    if(argc > 1 && strcmp(argv[1], "-v") == 0) {
+      printf("%s\n", msGetVersion());
+      exit(0);
+    }
 
-  if ( msSetup() != MS_SUCCESS )
-  {
+    /* ---- check the number of arguments, return syntax if not correct ---- */
+    if( argc < 3 ) {
+      fprintf(stdout, "\nPurpose: convert a mapfile to an image\n\n");
+      fprintf(stdout,
+              "Syntax: shp2img -m mapfile [-o image] [-e minx miny maxx maxy] [-s sizex sizey]\n"
+              "               [-l \"layer1 [layers2...]\"] [-i format]\n"
+              "               [-all_debug n] [-map_debug n] [-layer_debug n] [-p n] [-c n] [-d layername datavalue]\n");
+
+
+      fprintf(stdout,"  -m mapfile: Map file to operate on - required\n" );
+      fprintf(stdout,"  -i format: Override the IMAGETYPE value to pick output format\n" );
+      fprintf(stdout,"  -o image: output filename (stdout if not provided)\n");
+      fprintf(stdout,"  -e minx miny maxx maxy: extents to render\n");
+      fprintf(stdout,"  -s sizex sizey: output image size\n");
+      fprintf(stdout,"  -l layers: layers / groups to enable - make sure they are quoted and space seperated if more than one listed\n" );
+      fprintf(stdout,"  -all_debug n: Set debug level for map and all layers\n" );
+      fprintf(stdout,"  -map_debug n: Set map debug level\n" );
+      fprintf(stdout,"  -layer_debug layer_name n: Set layer debug level\n" );
+      fprintf(stdout,"  -c n: draw map n number of times\n" );
+      fprintf(stdout,"  -p n: pause for n seconds after reading the map\n" );
+      fprintf(stdout,"  -d layername datavalue: change DATA value for layer\n" );
+
+
+      exit(0);
+    }
+
+    if ( msSetup() != MS_SUCCESS ) {
       msWriteError(stderr);
       exit(1);
-  }
- 
-  /* Use MS_ERRORFILE and MS_DEBUGLEVEL env vars if set */
-  if ( msDebugInitFromEnv() != MS_SUCCESS )
-  {
+    }
+
+    /* Use MS_ERRORFILE and MS_DEBUGLEVEL env vars if set */
+    if ( msDebugInitFromEnv() != MS_SUCCESS ) {
       msWriteError(stderr);
-      msCleanup();
+      msCleanup(0);
       exit(1);
-  }
+    }
+
+    for(i=1; i<argc; i++) { /* Step though the user arguments, 1st to find map file */
 
-  for(i=1;i<argc;i++) { /* Step though the user arguments, 1st to find map file */
- 
-    if(strcmp(argv[i],"-m") == 0) {
-      map = msLoadMap(argv[i+1], NULL);
-      if(!map) {
-	msWriteError(stderr);
-        msCleanup();
-	exit(1);
+      if(strcmp(argv[i],"-m") == 0) {
+        map = msLoadMap(argv[i+1], NULL);
+        if(!map) {
+          msWriteError(stderr);
+          msCleanup(0);
+          exit(1);
+        }
+        msApplyDefaultSubstitutions(map);
       }
-      msApplyDefaultSubstitutions(map);
     }
-  }
 
-  if(!map) {
-    fprintf(stderr, "Mapfile (-m) option not specified.\n");
-    msCleanup();
-    exit(1);
-  }
+    if(!map) {
+      fprintf(stderr, "Mapfile (-m) option not specified.\n");
+      msCleanup(0);
+      exit(1);
+    }
 
 
-  for(i=1;i<argc;i++) { /* Step though the user arguments */
+    for(i=1; i<argc; i++) { /* Step though the user arguments */
 
-    if(strcmp(argv[i],"-m") == 0) { /* skip it */
-      i+=1;
-    }
+      if(strcmp(argv[i],"-m") == 0) { /* skip it */
+        i+=1;
+      }
 
-    if(strcmp(argv[i],"-p") == 0) {
+      if(strcmp(argv[i],"-p") == 0) {
         int pause_length = atoi(argv[i+1]);
         time_t start_time = time(NULL);
 
         printf( "Start pause of %d seconds.\n", pause_length );
         while( time(NULL) < start_time + pause_length ) {}
         printf( "Done pause.\n" );
-            
+
         i+=1;
-    }
+      }
 
-    if(strcmp(argv[i],"-o") == 0) { /* load the output image filename */
-      outfile = argv[i+1];
-      i+=1;
-    }
-    
-    if(strcmp(argv[i],"-i") == 0) { 
-      outputFormatObj *format;
+      if(strcmp(argv[i],"-o") == 0) { /* load the output image filename */
+        outfile = argv[i+1];
+        i+=1;
+      }
 
-      format = msSelectOutputFormat( map, argv[i+1] );
+      if(strcmp(argv[i],"-i") == 0) {
+        outputFormatObj *format;
 
-      if( format == NULL )
+        format = msSelectOutputFormat( map, argv[i+1] );
+
+        if( format == NULL )
           printf( "No such OUTPUTFORMAT as %s.\n", argv[i+1] );
-      else
-      {
+        else {
           msFree( (char *) map->imagetype );
           map->imagetype = msStrdup( argv[i+1] );
-          msApplyOutputFormat( &(map->outputformat), format, 
-                               map->transparent, map->interlace, 
+          msApplyOutputFormat( &(map->outputformat), format,
+                               map->transparent, map->interlace,
                                map->imagequality );
+        }
+        i+=1;
       }
-      i+=1;
-    }
 
-    if(strcmp(argv[i],"-d") == 0) { /* swap layer data */
-      for(j=0; j<map->numlayers; j++) {
-	 if(strcmp(GET_LAYER(map, j)->name, argv[i+1]) == 0) {
-	   free(GET_LAYER(map, j)->data);
-	   GET_LAYER(map, j)->data = msStrdup(argv[i+2]);
-	   break;
-	 }
+      if(strcmp(argv[i],"-d") == 0) { /* swap layer data */
+        for(j=0; j<map->numlayers; j++) {
+          if(strcmp(GET_LAYER(map, j)->name, argv[i+1]) == 0) {
+            free(GET_LAYER(map, j)->data);
+            GET_LAYER(map, j)->data = msStrdup(argv[i+2]);
+            break;
+          }
+        }
+        i+=2;
       }
-      i+=2;
-    }
 
-    if(strcmp(argv[i], "-all_debug") == 0 && i < argc-1 ) /* global debug */
-    {
+      if(strcmp(argv[i], "-all_debug") == 0 && i < argc-1 ) { /* global debug */
         int debug_level = atoi(argv[++i]);
 
         /* msSetGlobalDebugLevel() already called. Just need to force debug
@@ -203,125 +198,124 @@ int main(int argc, char *argv[])
          */
         map->debug = debug_level;
         for(j=0; j<map->numlayers; j++) {
-            GET_LAYER(map, j)->debug = debug_level;
+          GET_LAYER(map, j)->debug = debug_level;
         }
 
-    }
-    
-    if(strcmp(argv[i], "-map_debug") == 0 && i < argc-1 ) /* debug */
-    {
+      }
+
+      if(strcmp(argv[i], "-map_debug") == 0 && i < argc-1 ) { /* debug */
         map->debug = atoi(argv[++i]);
 
-        /* Send output to stderr by default */ 
+        /* Send output to stderr by default */
         if (msGetErrorFile() == NULL)
-            msSetErrorFile("stderr", NULL);
-    }
-    
-    if(strcmp(argv[i], "-layer_debug") == 0 && i < argc-1 ) /* debug */
-    {
+          msSetErrorFile("stderr", NULL);
+      }
+
+      if(strcmp(argv[i], "-layer_debug") == 0 && i < argc-1 ) { /* debug */
         const char *layer_name = argv[++i];
         int debug_level = atoi(argv[++i]);
         int got_layer = 0;
 
         for(j=0; j<map->numlayers; j++) {
-            if(strcmp(GET_LAYER(map, j)->name,layer_name) == 0 ) {
-                GET_LAYER(map, j)->debug = debug_level;
-                got_layer = 1;
-            }
+          if(strcmp(GET_LAYER(map, j)->name,layer_name) == 0 ) {
+            GET_LAYER(map, j)->debug = debug_level;
+            got_layer = 1;
+          }
         }
         if( !got_layer )
-            fprintf( stderr, 
-                     " Did not find layer '%s' from -layer_debug switch.\n", 
-                     layer_name );
+          fprintf( stderr,
+                   " Did not find layer '%s' from -layer_debug switch.\n",
+                   layer_name );
 
-        /* Send output to stderr by default */ 
+        /* Send output to stderr by default */
         if (msGetErrorFile() == NULL)
-            msSetErrorFile("stderr", NULL);
-    }
-    
-    if(strcmp(argv[i],"-e") == 0) { /* change extent */
+          msSetErrorFile("stderr", NULL);
+      }
+
+      if(strcmp(argv[i],"-e") == 0) { /* change extent */
         if( argc <= i+4 ) {
-            fprintf( stderr, 
-                     "Argument -e needs 4 space separated numbers as argument.\n" ); 
-            msCleanup();
-            exit(1);
+          fprintf( stderr,
+                   "Argument -e needs 4 space separated numbers as argument.\n" );
+          msCleanup(0);
+          exit(1);
         }
-      map->extent.minx = atof(argv[i+1]);
-      map->extent.miny = atof(argv[i+2]);
-      map->extent.maxx = atof(argv[i+3]);
-      map->extent.maxy = atof(argv[i+4]);
-      i+=4;
-    }
+        map->extent.minx = atof(argv[i+1]);
+        map->extent.miny = atof(argv[i+2]);
+        map->extent.maxx = atof(argv[i+3]);
+        map->extent.maxy = atof(argv[i+4]);
+        i+=4;
+      }
 
-    if (strcmp(argv[i], "-s") == 0) {
-      msMapSetSize(map, atoi(argv[i+1]), atoi(argv[i+2]));
-      i+=2;
-    }    
+      if (strcmp(argv[i], "-s") == 0) {
+        msMapSetSize(map, atoi(argv[i+1]), atoi(argv[i+2]));
+        i+=2;
+      }
 
-    if(strcmp(argv[i],"-l") == 0) { /* load layer list */
-      layers = msStringSplit(argv[i+1], ' ', &(num_layers));
+      if(strcmp(argv[i],"-l") == 0) { /* load layer list */
+        layers = msStringSplit(argv[i+1], ' ', &(num_layers));
 
-      for(j=0; j<num_layers; j++) { /* loop over -l */
+        for(j=0; j<num_layers; j++) { /* loop over -l */
           layer_found=0;
           for(k=0; k<map->numlayers; k++) {
-              if((GET_LAYER(map, k)->name && strcasecmp(GET_LAYER(map, k)->name, layers[j]) == 0) || (GET_LAYER(map, k)->group && strcasecmp(GET_LAYER(map, k)->group, layers[j]) == 0)) {
-                  layer_found = 1;
-                  break;
-              }
+            if((GET_LAYER(map, k)->name && strcasecmp(GET_LAYER(map, k)->name, layers[j]) == 0) || (GET_LAYER(map, k)->group && strcasecmp(GET_LAYER(map, k)->group, layers[j]) == 0)) {
+              layer_found = 1;
+              break;
+            }
           }
           if (layer_found==0) {
-              fprintf(stderr, "Layer (-l) \"%s\" not found\n", layers[j]);
-              msCleanup();
-              exit(1);
+            fprintf(stderr, "Layer (-l) \"%s\" not found\n", layers[j]);
+            msCleanup(0);
+            exit(1);
           }
-      }
+        }
 
-      for(j=0; j<map->numlayers; j++) {
-	if(GET_LAYER(map, j)->status == MS_DEFAULT)
-          continue;
-	else {
-	  GET_LAYER(map, j)->status = MS_OFF;
-	  for(k=0; k<num_layers; k++) {
-	    if(GET_LAYER(map, j)->name && strcasecmp(GET_LAYER(map, j)->name, layers[k]) == 0) {
-	      GET_LAYER(map, j)->status = MS_ON;
-	      break;
-	    }
-	  }
-	}
-      }
+        for(j=0; j<map->numlayers; j++) {
+          if(GET_LAYER(map, j)->status == MS_DEFAULT)
+            continue;
+          else {
+            GET_LAYER(map, j)->status = MS_OFF;
+            for(k=0; k<num_layers; k++) {
+              if((GET_LAYER(map, j)->name && strcasecmp(GET_LAYER(map, j)->name, layers[k]) == 0) ||
+                  (GET_LAYER(map, j)->group && strcasecmp(GET_LAYER(map, j)->group, layers[k]) == 0)) {
+                GET_LAYER(map, j)->status = MS_ON;
+                break;
+              }
+            }
+          }
+        }
 
-      msFreeCharArray(layers, num_layers);
+        msFreeCharArray(layers, num_layers);
 
-      i+=1;
-     }
-  }
-  
-  image = msDrawMap(map, MS_FALSE);
+        i+=1;
+      }
+    }
 
-  if(!image) {
-    msWriteError(stderr);
+    image = msDrawMap(map, MS_FALSE);
 
-    msFreeMap(map);
-    msCleanup();
-    exit(1);
-  }
+    if(!image) {
+      msWriteError(stderr);
 
-  if( msSaveImage(map, image, outfile) != MS_SUCCESS ) {
-    msWriteError(stderr);
-  }
+      msFreeMap(map);
+      msCleanup(0);
+      exit(1);
+    }
+
+    if( msSaveImage(map, image, outfile) != MS_SUCCESS ) {
+      msWriteError(stderr);
+    }
 
-  msFreeImage(image);
-  msFreeMap(map);
+    msFreeImage(image);
+    msFreeMap(map);
 
-  if(msGetGlobalDebugLevel() >= MS_DEBUGLEVEL_TUNING) {
-    msGettimeofday(&requestendtime, NULL);
-    msDebug("shp2img total time: %.3fs\n", 
-            (requestendtime.tv_sec+requestendtime.tv_usec/1.0e6)-
-            (requeststarttime.tv_sec+requeststarttime.tv_usec/1.0e6) );
-  }
+    if(msGetGlobalDebugLevel() >= MS_DEBUGLEVEL_TUNING) {
+      msGettimeofday(&requestendtime, NULL);
+      msDebug("shp2img total time: %.3fs\n",
+              (requestendtime.tv_sec+requestendtime.tv_usec/1.0e6)-
+              (requeststarttime.tv_sec+requeststarttime.tv_usec/1.0e6) );
+    }
 
-  msCleanup();
+    msCleanup(0);
 
-} /*   for(draws=0; draws<iterations; draws++) { */
+  } /*   for(draws=0; draws<iterations; draws++) { */
   return(0);
 } /* ---- END Main Routine ---- */
diff --git a/shp2mysql.pl b/shp2mysql.pl
deleted file mode 100755
index 905f567..0000000
--- a/shp2mysql.pl
+++ /dev/null
@@ -1,316 +0,0 @@
-#!/usr/bin/perl
-
-# Copyright (c) 2003, Attila Csipa, Manufaktura Internet Inzenjering doo
-
-
-$|=1;
-
-use DBI;
-use Geo::Shapelib qw/:all/;
-#use Shape qw/:all/; # use this if you have an older shapelib version installed and the above line fails (also change line 29)
-
-$dbname = "changeme";
-$host = "localhost";
-$dbuser = "root";
-$dbpass = "";
-
-$mac = 0;	# this is not a mac
-$ENDIAN = 1;    # 0 = big endian - mac, 1 = little endian - intel
-
-# --- do not edit below this line
-
-die "Configure database parameters on the beginning of this script file\n" if $dbname eq "changeme";
-$dbh = DBI->connect("DBI:mysql:$dbname:$host:3306",$dbuser,$dbpass) || die $DBI::errstr ;
-$dbh->{RaiseError} = 1;
-
-die "Usage: shp2mysql shpname\n\nwhere shpname is the name (with path) to the base name of the shape file (do not include file name extensions !)\n" unless $ARGV[0];
-die "Shapefile $ARGV[0] not found !" unless -f "$ARGV[0].shp";
-$shape = new Geo::Shapelib $ARGV[0];
-#$shape = new Shape $ARGV[0];
-
-$WKB_POINT = 1;
-$WKB_LINESTRING = 2;
-$WKB_POLYGON = 3;
-$WKB_MULTIPOINT = 4;
-$WKB_MULTILINESTRING = 5;
-$WKB_MULTIPOLYGON = 6;
-$WKB_GEOMETRYCOLLECTION = 7;
-
-sub query
-{
-    my $sth = $dbh->prepare(shift) or die "DBI error $!";
-    $sth->execute or die "DBI error $!";
-    return $sth;
-}
-
-sub rect
-{
-    my ($x0, $y0, $x1, $y1) = @_;
-    my $minx = $x0 <  $x1 ? $x0 : $x1;
-    my $maxx = $x0 >= $x1 ? $x0 : $x1;
-    my $miny = $y0 <  $y1 ? $y0 : $y1;
-    my $maxy = $y0 >= $y1 ? $y0 : $y1;
-    return ($minx, $miny, $maxx, $maxy);
-
-}
-
-
-$dbh->do("CREATE TABLE IF NOT EXISTS GEOMETRY_COLUMNS (
-      F_TABLE_CATALOG varchar(100) NOT NULL default '',
-      F_TABLE_SCHEMA varchar(100) NOT NULL default '',
-      F_TABLE_NAME varchar(100) NOT NULL default '',
-      F_GEOMETRY_COLUMN varchar(100) NOT NULL default '',
-      G_TABLE_CATALOG varchar(100) NOT NULL default '',
-      G_TABLE_SCHEMA varchar(100) NOT NULL default '',
-      G_TABLE_NAME varchar(100) NOT NULL default '',
-      STORAGE_TYPE int(11) NOT NULL default '0',
-      GEOMETRY_TYPE int(11) NOT NULL default '0',
-      COORD_DIMENSION int(11) NOT NULL default '0',
-      MAX_PPR int(11) NOT NULL default '0',
-      SRID int(11) NOT NULL default '0',
-      PRIMARY KEY  (F_TABLE_CATALOG,F_TABLE_SCHEMA,F_TABLE_NAME,F_GEOMETRY_COLUMN)
-    ) TYPE=MyISAM;");
-
-$dbh->do("CREATE TABLE IF NOT EXISTS SPATIAL_REF_SYS (
-      SRID int(11) NOT NULL default '0',
-      AUTH_NAME varchar(255) default NULL,
-      AUTH_SRID int(11) default NULL,
-      SRTEXT varchar(255) default NULL,
-      PRIMARY KEY  (SRID)
-    ) TYPE=MyISAM;");
-
-%sqlcreate = ( point => "  id int(11) NOT NULL auto_increment,
-  layer int(11) NOT NULL default '0',
-  x1 double default NULL,
-  y1 double default NULL,
-  x2 double default NULL,
-  y2 double default NULL,
-  vertices int(11) NOT NULL default '1',
-  GID int(11) NOT NULL,
-  PRIMARY KEY  (id),
-  FOREIGN KEY GID(GID, x1, y1, x2, y2) REFERENCES geometry_point_num (GID),
-  KEY layer (layer),
-  KEY turbo (x2,y2,x1,y1)",
-
-                arc => "  id int(11) NOT NULL auto_increment,
-  layer int(11) NOT NULL default '0',
-  x1 double default NULL,
-  y1 double default NULL,
-  x2 double default NULL,
-  y2 double default NULL,
-  vertices int(11) NOT NULL default '1',
-  GID int(11) NOT NULL,
-  PRIMARY KEY  (id),
-  FOREIGN KEY GID(GID, x1, y1, x2, y2) REFERENCES geometry_arc_num (GID),
-  KEY layer (layer),
-  KEY turbo (x2,y2,x1,y1)",
-
-                polygon => "  id int(11) NOT NULL auto_increment,
-  layer int(11) NOT NULL default '0',
-  x1 double default NULL,
-  y1 double default NULL,
-  x2 double default NULL,
-  y2 double default NULL,
-  vertices int(11) NOT NULL default '1',
-  GID int(11) NOT NULL,
-  PRIMARY KEY  (id),
-  FOREIGN KEY GID(GID, x1, y1, x2, y2) REFERENCES geometry_polygon_num (GID),
-  KEY layer (layer),
-  KEY turbo (x2,y2,x1,y1)",
-
-                annotation => "  id int(11) NOT NULL auto_increment,
-  layer int(11) NOT NULL default '0',
-  x1 double default NULL,
-  y1 double default NULL,
-  x2 double default NULL,
-  y2 double default NULL,
-  vertices int(11) NOT NULL default '1',
-  angle double default '0.0',
-  size int not null default '10',
-  txt VARCHAR(255) NOT NULL default '',
-  GID int(11) NOT NULL,
-  PRIMARY KEY  (id),
-  FOREIGN KEY GID(GID, x1, y1, x2, y2) REFERENCES geometry_annotation_num (GID),
-  KEY layer (layer),
-  KEY turbo (x2,y2,x1,y1)",
-
-                num => "  GID INTEGER NOT NULL,
-  ESEQ INTEGER NOT NULL,
-  ETYPE INTEGER NOT NULL,
-  SEQ INTEGER NOT NULL,
-  X1 double default NULL,
-  Y1 double default NULL,
-  X2 double default NULL,
-  Y2 double default NULL,
-  CONSTRAINT GID_PK PRIMARY KEY (GID, ESEQ, SEQ),
-  KEY x (X1,Y1)",
-                bin => "  GID INTEGER NOT NULL,
-  XMIN double default NULL,
-  YMIN double default NULL,
-  XMAX double default NULL,
-  YMAX double default NULL,
-  WKB_GEOMETRY BLOB,
-  KEY (GID),
-  KEY x (XMIN,YMIN,XMAX,YMAX)"
-);
-
-$sqlcreate{'3'} = $sqlcreate{'arc'};
-$sqlcreate{'line'} = $sqlcreate{'arc'};
-
-sub mklayer
-{
-    my ($sh, $type, $add) = @_;
-	  $sh =~ tr/-/_/;
-#    print "$sh/$type ($sqlcreate{$type})\n";
-        $dbh->do("drop table if exists $sh");
-        $dbh->do("drop table if exists $sh");
-        $dbh->do("drop table if exists ${sh}_num");
-        $dbh->do("drop table if exists ${sh}_bin");
-        $dbh->do("create table if not exists $sh ($sqlcreate{$type} $add)");
-        $dbh->do("create table if not exists ${sh}_num ($sqlcreate{num})");
-        $dbh->do("create table if not exists ${sh}_bin ($sqlcreate{bin})");
-        $dbh->do("delete from GEOMETRY_COLUMNS where F_TABLE_NAME = ".$dbh->quote($sh));
-        $dbh->do("insert into GEOMETRY_COLUMNS 
-        (F_TABLE_CATALOG,F_TABLE_SCHEMA,F_TABLE_NAME,F_GEOMETRY_COLUMN,G_TABLE_CATALOG,G_TABLE_SCHEMA,G_TABLE_NAME,STORAGE_TYPE,GEOMETRY_TYPE,COORD_DIMENSION,MAX_PPR,SRID)
-        values ('$dbname', '', ".$dbh->quote($sh).", 'GID', '$dbname', '', ".$dbh->quote("${sh}_bin").", 1, '$gtype{$type}', 2, 2, 0)");
-}
-
-sub wkb
-{
-    $int = $mac ? "N" : "V";
-    my ($poly, $end, $wkbt)= (shift, shift, shift);
-    my $wkb = pack("C$int$int", $end, $WKB_GEOMETRYCOLLECTION, 1);
-    $wkb .= pack("C$int", $end, $wkbt);
-    my $nr = shift;
-    if ($poly){
-        $wkb .= pack("$int", $nr);
-    }
-    while ($nr -- > 0){
-        my $pts = shift;
-        if ($wkbt != $WKB_POINT){
-            $wkb .= pack("$int", $pts);
-        }
-        $double = "";;
-        for (my $i=0; $i<$pts; $i++){
-            $double = pack("dd", shift, shift);
-            if ($mac){
-                @o = unpack("CCCCCCCCCCCCCCCC", $double);
-                $double = pack("CCCCCCCCCCCCCCCC", $o[7],$o[6],$o[5],$o[4],$o[3],$o[2],$o[1],$o[0],$o[15],$o[14],$o[13],$o[12],$o[11],$o[10],$o[9],$o[8]); 
-            }
-            $wkb .= $double;
-        }
-    }
-    return $wkb; 
-}
-
- at tmp = split(/\//, $ARGV[0]);
-$sh = pop @tmp;
-
-undef $fields;
-undef @field;
-undef $appendvars;
-undef $vars;
-#$shape->{FieldTypes} = ['Integer'];
-for (@{$shape->{FieldNames}}){
-	$fields .= ", f_$_ VARCHAR(255) NOT NULL DEFAULT ''";
-	push @field, "f_$_";
-	$appendvars .= ", f_$_ ";
-	$vars++;
-}
-	
-if ($shape->{Shapetype} eq POINT){
-	mklayer($sh , 'point', $fields);
-} elsif ($shape->{Shapetype} eq LINE or $shape->{Shapetype} eq 3){
-	mklayer($sh , 'line', $fields);
-} elsif ($shape->{Shapetype} eq ARC){
-        mklayer($sh , 'arc', $fields);
-} elsif ($shape->{Shapetype} eq POLYGON){
-	mklayer($sh , 'polygon', $fields);
-}
-	
-			       
-for (0..@{$shape->{Shapes}}-1){
-	undef $appenddata;
-	for ($v = 0; $v < $vars; $v++){
-		$appenddata .= ", ".$dbh->quote(${$shape->{ShapeRecords}}[$_][$v]);
-#print $dbh->quote(${$shape->{ShapeRecords}}[$_][$v]);
-	}
-	$vrt=-1;
-	while (${$shape->{Shapes}}[$_]{Vertices}[++$vrt][0] ne undef){
-         $gid++;
-         $feat++;
-	 undef %object;
-	 if ($shape->{Shapetype} eq LINE or $shape->{Shapetype} eq 3){
-		$object{x0} = ${$shape->{Shapes}}[$_]{Vertices}[$vrt-1][0];
-		$object{y0} = ${$shape->{Shapes}}[$_]{Vertices}[$vrt-1][1];
-		$object{x1} = ${$shape->{Shapes}}[$_]{Vertices}[$vrt][0];
-		$object{y1} = ${$shape->{Shapes}}[$_]{Vertices}[$vrt][1];
-		next unless $object{x0};
-# line
-	    print "-";
-            $dbh->do("insert into ${sh}_num (GID, ESEQ, SEQ, ETYPE, X1, Y1, X2, Y2) values ('$gid', 1, 1, 2, '$object{x0}','$object{y0}','$object{x1}','$object{y1}')");
-            $string =  wkb(0, $ENDIAN, $WKB_LINESTRING, 1, 2,$object{x0}, $object{y0}, $object{x1}, $object{y1});
-            my $sth = $dbh->prepare("insert into ${sh}_bin (GID, XMIN, YMIN, XMAX, YMAX, WKB_GEOMETRY) values ('$gid', '$object{x0}','$object{y0}','$object{x1}','$object{y1}', ? )");
-             $sth->execute($string);
-            $sth->finish;
-            ($minx, $miny, $maxx, $maxy) = rect($object{x0}, $object{y0}, $object{x1}, $object{y1});
-            $dbh->do("insert into $sh (id, layer, vertices, GID, x1, y1, x2, y2 $appendvars) values ('$feat', '$layer{$sh}', 1, '$gid', '$minx', '$miny', '$maxx', '$maxy' $appenddata)") if $vrt eq 0;
-
-	} elsif ($shape->{Shapetype} eq ARC){
-                $object{x0} = ${$shape->{Shapes}}[$_]{Vertices}[$vrt-1][0];
-                $object{y0} = ${$shape->{Shapes}}[$_]{Vertices}[$vrt-1][1];
-                $object{x1} = ${$shape->{Shapes}}[$_]{Vertices}[$vrt][0];
-                $object{y1} = ${$shape->{Shapes}}[$_]{Vertices}[$vrt][1];
-                next unless $object{x0};
-# line
-            print "-";
-            $dbh->do("insert into ${sh}_num (GID, ESEQ, SEQ, ETYPE, X1, Y1, X2, Y2) values ('$gid', 1, 1, 2, '$object{x0}','$object{y0}','$object{x1}','$object{y1}')");
-            $string =  wkb(0, $ENDIAN, $WKB_LINESTRING, 1, 2,$object{x0}, $object{y0}, $object{x1}, $object{y1});
-            my $sth = $dbh->prepare("insert into ${sh}_bin (GID, XMIN, YMIN, XMAX, YMAX, WKB_GEOMETRY) values ('$gid', '$object{x0}','$object{y0}','$object{x1}','$object{y1}', ? )");
-             $sth->execute($string);
-            $sth->finish;
-            ($minx, $miny, $maxx, $maxy) = rect($object{x0}, $object{y0}, $object{x1}, $object{y1});
-            $dbh->do("insert into $sh (id, layer, vertices, GID, x1, y1, x2, y2 $appendvars) values ('$feat', '$layer{$sh}', 1, '$gid', '$minx', '$miny', '$maxx', '$maxy' $appenddata)") if $vrt eq 0;
-
-
-	 } elsif ($shape->{Shapetype} eq POINT){
-		$object{x0} = ${$shape->{Shapes}}[$_]{Vertices}[$vrt][0];
-		$object{y0} = ${$shape->{Shapes}}[$_]{Vertices}[$vrt][1];
-# point
-
-	    print ".";
-            $dbh->do("insert into ${sh}_num (GID, ESEQ, SEQ, ETYPE, X1, Y1, X2, Y2) values ('$gid', 1, 1, 1, '$object{x0}','$object{y0}','0','0')");
-            my $sth = $dbh->prepare("insert into ${sh}_bin (GID, XMIN, YMIN, XMAX, YMAX, WKB_GEOMETRY) values ('$gid', '$object{x0}','$object{y0}','$object{x0}','$object{y0}', ?)");
-            $sth->execute(wkb(0, $ENDIAN, $WKB_POINT, 1, 1,$object{x0}, $object{y0}));
-            $sth->finish;
-            $dbh->do("insert into $sh (id, layer, vertices, GID, x1, y1, x2, y2 $appendvars) values ('$feat', '$layer{$sh}', 1, '$gid', '$object{x0}', '$object{y0}', '$object{x0}', '$object{y0}' $appenddata)");
-	    
-	 } elsif ($shape->{Shapetype} eq POLYGON){
-# poly
-
-	    print "O";
-		@vertex = @{${$shape->{Shapes}}[$_]{Vertices}};
-	    
-            ($minx, $miny, $maxx, $maxy) = rect($vertex[0][0], $vertex[0][1], $vertex[0][0], $vertex[0][1]);
-            $eseq=1;
-            push @vertices, $vertex[0][0], $vertex[0][1];
-            for ($v = 1; $v<=$#vertex; $v++) {
-                $dbh->do("insert into ${sh}_num (GID, ESEQ, SEQ, ETYPE, X1, Y1, X2, Y2) values ('$gid', 1, $v, 3, '$vertex[$v -1][0]','$vertex[$v -1][1]', '$vertex[$v][0]','$vertex[$v][1]')");
-                push @vertices, $vertex[$v][0], $vertex[$v][1];
-                $maxx = $vertex[$v][0] if ($vertex[$v][0] > $maxx);
-                $minx = $vertex[$v][0] if ($vertex[$v][0] < $minx);
-                $maxy = $vertex[$v][1] if ($vertex[$v][1] > $maxy);
-                $miny = $vertex[$v][1] if ($vertex[$v][1] < $miny);
-#                $dbh->do("insert into vertex (shape,x,y,z) values ('$shape_id','$vertex[$v][0]','$vertex[$v][1]','0')");
-            }
-            my $sth = $dbh->prepare("insert into ${sh}_bin (GID, XMIN, YMIN, XMAX, YMAX, WKB_GEOMETRY) values ('$gid', '$minx','$miny','$maxx','$maxy', ?)");
-            $sth->execute(wkb(1, $ENDIAN, $WKB_POLYGON, 1, $#vertex+1, @vertices));
-            $sth->finish;
-            undef @vertices;
-            $dbh->do("insert into $sh (id, layer, vertices, GID, x1, y1, x2, y2 $appendvars) values ('$feat', '$layer{$sh}', '$#vertex', '$gid', '$minx', '$miny', '$maxx', '$maxy' $appenddata)") if $vrt eq 0;
-	    $vrt = $#vertex;
-	 }
-
-	}
-}
-print "\n";
diff --git a/shptree.c b/shptree.c
index a9bb4d3..8399570 100644
--- a/shptree.c
+++ b/shptree.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -31,33 +31,34 @@
 #include "maptree.h"
 #include <string.h>
 
-MS_CVSID("$Id$")
 
-char* AddFileSuffix ( const char * Filename, const char * Suffix ) {
-  char	*pszFullname, *pszBasename;
-  int	i;
-  
+
+char* AddFileSuffix ( const char * Filename, const char * Suffix )
+{
+  char  *pszFullname, *pszBasename;
+  int i;
+
   /* -------------------------------------------------------------------- */
-  /*	Compute the base (layer) name.  If there is any extension	    */
-  /*	on the passed in filename we will strip it off.			    */
+  /*  Compute the base (layer) name.  If there is any extension     */
+  /*  on the passed in filename we will strip it off.         */
   /* -------------------------------------------------------------------- */
   pszBasename = (char *) msSmallMalloc(strlen(Filename)+5);
   strcpy( pszBasename, Filename );
-  for( i = strlen(pszBasename)-1; 
+  for( i = strlen(pszBasename)-1;
        i > 0 && pszBasename[i] != '.' && pszBasename[i] != '/'
-	 && pszBasename[i] != '\\';
+       && pszBasename[i] != '\\';
        i-- ) {}
-  
+
   if( pszBasename[i] == '.' )
     pszBasename[i] = '\0';
-  
+
   /* -------------------------------------------------------------------- */
-  /*	Open the .shp and .shx files.  Note that files pulled from	    */
-  /*	a PC to Unix with upper case filenames won't work!		    */
+  /*  Open the .shp and .shx files.  Note that files pulled from      */
+  /*  a PC to Unix with upper case filenames won't work!        */
   /* -------------------------------------------------------------------- */
   pszFullname = (char *) msSmallMalloc(strlen(pszBasename) + 5);
-  sprintf( pszFullname, "%s%s", pszBasename, Suffix); 
-  
+  sprintf( pszFullname, "%s%s", pszBasename, Suffix);
+
   free(pszBasename);
   return (pszFullname);
 }
@@ -77,61 +78,60 @@ int main(int argc, char *argv[])
   }
 
   /* -------------------------------------------------------------------- */
-  /*	Establish the byte order on this machine to decide default        */
+  /*  Establish the byte order on this machine to decide default        */
   /*    index format                                                      */
   /* -------------------------------------------------------------------- */
-    i = 1;
-    if( *((uchar *) &i) == 1 )
-      byte_order = MS_NEW_LSB_ORDER;
-    else
-      byte_order = MS_NEW_MSB_ORDER;
+  i = 1;
+  if( *((uchar *) &i) == 1 )
+    byte_order = MS_NEW_LSB_ORDER;
+  else
+    byte_order = MS_NEW_MSB_ORDER;
 
 
   if(argc<2) {
-   fprintf(stdout,"Syntax:\n");
-   fprintf(stdout,"    shptree <shpfile> [<depth>] [<index_format>]\n" );
-   fprintf(stdout,"Where:\n");
-   fprintf(stdout," <shpfile> is the name of the .shp file to index.\n");
-   fprintf(stdout," <depth>   (optional) is the maximum depth of the index\n");
-   fprintf(stdout,"           to create, default is 0 meaning that shptree\n");
-   fprintf(stdout,"           will calculate a reasonable default depth.\n");
-   fprintf(stdout," <index_format> (optional) is one of:\n");
-   fprintf(stdout,"           NL: LSB byte order, using new index format\n");
-   fprintf(stdout,"           NM: MSB byte order, using new index format\n");
-   fprintf(stdout,"       The following old format options are deprecated:\n");
-   fprintf(stdout,"           N:  Native byte order\n");
-   fprintf(stdout,"           L:  LSB (intel) byte order\n");
-   fprintf(stdout,"           M:  MSB byte order\n");
-   fprintf(stdout,"       The default index_format on this system is: %s\n\n",
-           (byte_order == MS_NEW_LSB_ORDER) ? "NL" : "NM" );
-   exit(0);
+    fprintf(stdout,"Syntax:\n");
+    fprintf(stdout,"    shptree <shpfile> [<depth>] [<index_format>]\n" );
+    fprintf(stdout,"Where:\n");
+    fprintf(stdout," <shpfile> is the name of the .shp file to index.\n");
+    fprintf(stdout," <depth>   (optional) is the maximum depth of the index\n");
+    fprintf(stdout,"           to create, default is 0 meaning that shptree\n");
+    fprintf(stdout,"           will calculate a reasonable default depth.\n");
+    fprintf(stdout," <index_format> (optional) is one of:\n");
+    fprintf(stdout,"           NL: LSB byte order, using new index format\n");
+    fprintf(stdout,"           NM: MSB byte order, using new index format\n");
+    fprintf(stdout,"       The following old format options are deprecated:\n");
+    fprintf(stdout,"           N:  Native byte order\n");
+    fprintf(stdout,"           L:  LSB (intel) byte order\n");
+    fprintf(stdout,"           M:  MSB byte order\n");
+    fprintf(stdout,"       The default index_format on this system is: %s\n\n",
+            (byte_order == MS_NEW_LSB_ORDER) ? "NL" : "NM" );
+    exit(0);
   }
 
   if(argc >= 3)
     depth = atoi(argv[2]);
 
-  if(argc >= 4)
-  {
+  if(argc >= 4) {
     if( !strcasecmp(argv[3],"N" ))
-      byte_order = MS_NATIVE_ORDER; 
+      byte_order = MS_NATIVE_ORDER;
     if( !strcasecmp(argv[3],"L" ))
-      byte_order = MS_LSB_ORDER; 
+      byte_order = MS_LSB_ORDER;
     if( !strcasecmp(argv[3],"M" ))
-      byte_order = MS_MSB_ORDER; 
+      byte_order = MS_MSB_ORDER;
     if( !strcasecmp(argv[3],"NL" ))
-      byte_order = MS_NEW_LSB_ORDER; 
+      byte_order = MS_NEW_LSB_ORDER;
     if( !strcasecmp(argv[3],"NM" ))
-      byte_order = MS_NEW_MSB_ORDER; 
+      byte_order = MS_NEW_MSB_ORDER;
   }
-    
+
   if(msShapefileOpen(&shapefile, "rb", argv[1], MS_TRUE) == -1) {
     fprintf(stdout, "Error opening shapefile %s.\n", argv[1]);
     exit(0);
   }
 
-  printf( "creating index of %s %s format\n",(byte_order < 1 ? "old (deprecated)" :"new"), 
-     ((byte_order == MS_NATIVE_ORDER) ? "native" : 
-     ((byte_order == MS_LSB_ORDER) || (byte_order == MS_NEW_LSB_ORDER)? " LSB":"MSB")));
+  printf( "creating index of %s %s format\n",(byte_order < 1 ? "old (deprecated)" :"new"),
+          ((byte_order == MS_NATIVE_ORDER) ? "native" :
+           ((byte_order == MS_LSB_ORDER) || (byte_order == MS_NEW_LSB_ORDER)? " LSB":"MSB")));
 
   tree = msCreateTree(&shapefile, depth);
   if(!tree) {
diff --git a/shptreetst.c b/shptreetst.c
index 4a8e7d4..efca502 100644
--- a/shptreetst.c
+++ b/shptreetst.c
@@ -34,146 +34,140 @@
 #endif
 #include <stdlib.h>
 
-MS_CVSID("$Id$")
+
 
 #ifdef SHPT_POLYGON
-   #undef MAPSERVER
+#undef MAPSERVER
 #else
-   #define MAPSERVER 1
-   #define SHPT_POLYGON MS_SHP_POLYGON
+#define MAPSERVER 1
+#define SHPT_POLYGON MS_SHP_POLYGON
 #endif
 
 
-char* AddFileSuffix ( const char * Filename, const char * Suffix ) {
-    char	*pszFullname, *pszBasename;
-    int	i;
+char* AddFileSuffix ( const char * Filename, const char * Suffix )
+{
+  char  *pszFullname, *pszBasename;
+  int i;
 
   /* -------------------------------------------------------------------- */
-  /*	Compute the base (layer) name.  If there is any extension	    */
-  /*	on the passed in filename we will strip it off.			    */
+  /*  Compute the base (layer) name.  If there is any extension     */
+  /*  on the passed in filename we will strip it off.         */
   /* -------------------------------------------------------------------- */
-    pszBasename = (char *) msSmallMalloc(strlen(Filename)+5);
-    strcpy( pszBasename, Filename );
-    for( i = strlen(pszBasename)-1;
+  pszBasename = (char *) msSmallMalloc(strlen(Filename)+5);
+  strcpy( pszBasename, Filename );
+  for( i = strlen(pszBasename)-1;
        i > 0 && pszBasename[i] != '.' && pszBasename[i] != '/'
-	 && pszBasename[i] != '\\';
+       && pszBasename[i] != '\\';
        i-- ) {}
 
-    if( pszBasename[i] == '.' )
-      pszBasename[i] = '\0';
+  if( pszBasename[i] == '.' )
+    pszBasename[i] = '\0';
 
   /* -------------------------------------------------------------------- */
-  /*	Open the .shp and .shx files.  Note that files pulled from	    */
-  /*	a PC to Unix with upper case filenames won't work!		    */
+  /*  Open the .shp and .shx files.  Note that files pulled from      */
+  /*  a PC to Unix with upper case filenames won't work!        */
   /* -------------------------------------------------------------------- */
-    pszFullname = (char *) msSmallMalloc(strlen(pszBasename) + 5);
-    sprintf( pszFullname, "%s%s", pszBasename, Suffix);
+  pszFullname = (char *) msSmallMalloc(strlen(pszBasename) + 5);
+  sprintf( pszFullname, "%s%s", pszBasename, Suffix);
 
-    return (pszFullname);
+  return (pszFullname);
 }
 
 
 int main( int argc, char ** argv )
 
 {
-    SHPTreeHandle	qix;
-
-    int		i, j;
-    rectObj	rect;
-
-    int		pos;
-    ms_bitarray bitmap = NULL;
-
-    char	mBigEndian;
-    treeNodeObj *node = NULL;
+  SHPTreeHandle qix;
 
+  int i,j;
+  rectObj rect;
 
-/* -------------------------------------------------------------------- */
-/*      Display a usage message.                                        */
-/* -------------------------------------------------------------------- */
-    if( argc <= 1 )
-    {
-	printf( "shptreetst shapefile {minx miny maxx maxy}\n" );
-	exit( 1 );
-    }
-
-    i = 1;
-    if( *((unsigned char *) &i) == 1 )
-      mBigEndian = 0;
-    else
-      mBigEndian = 1;
-
-
-    qix = msSHPDiskTreeOpen (AddFileSuffix(argv[1],".qix"), 0 /* no debug*/);
-    if( qix == NULL )
-    {
-      printf("unable to open index file %s \n", argv[1]);
-      exit(-1);
-    }
+  int   pos;
+  ms_bitarray bitmap = NULL;
 
-    printf ("This %s %s index supports a shapefile with %d shapes, %d depth \n",
-	(qix->version ? "new": "old"), (qix->LSB_order? "LSB": "MSB"), (int) qix->nShapes, (int) qix->nDepth);
+  /*
+  char  mBigEndian;
+  */
+  treeNodeObj *node = NULL;
 
-/* -------------------------------------------------------------------- */
-/*	Skim over the list of shapes, printing all the vertices.	*/
-/* -------------------------------------------------------------------- */
 
-    pos = ftell (qix->fp);
-    j = 0;
+  /* -------------------------------------------------------------------- */
+  /*      Display a usage message.                                        */
+  /* -------------------------------------------------------------------- */
+  if( argc <= 1 ) {
+    printf( "shptreetst shapefile {minx miny maxx maxy}\n" );
+    exit( 1 );
+  }
+  
+  /*
+  i = 1;
+  if( *((unsigned char *) &i) == 1 )
+    mBigEndian = 0;
+  else
+    mBigEndian = 1;
+  */
+
+  qix = msSHPDiskTreeOpen (AddFileSuffix(argv[1],".qix"), 0 /* no debug*/);
+  if( qix == NULL ) {
+    printf("unable to open index file %s \n", argv[1]);
+    exit(-1);
+  }
+
+  printf ("This %s %s index supports a shapefile with %d shapes, %d depth \n",
+          (qix->version ? "new": "old"), (qix->LSB_order? "LSB": "MSB"), (int) qix->nShapes, (int) qix->nDepth);
 
-    while( pos && j < 20)
-    {
-      j ++;
-/*      fprintf (stderr,"box %d, at %d pos \n", j, (int) ftell(qix));
-*/
+  /* -------------------------------------------------------------------- */
+  /*  Skim over the list of shapes, printing all the vertices.  */
+  /* -------------------------------------------------------------------- */
 
-      node = readTreeNode (qix);
-      if (node )
-      {
-        fprintf (stdout,"shapes %d, node %d, %f,%f,%f,%f \n",(int) node->numshapes,node->numsubnodes,node->rect.minx, node->rect.miny, node->rect.maxx, node->rect.maxy);
+  pos = ftell (qix->fp);
+  j = 0;
 
-      }
-      else
-      { pos = 0; }
-    }
-
-    printf ("read entire file now at quad box rec %d file pos %ld\n", j, ftell (qix->fp));
+  while( pos && j < 20) {
+    j ++;
+    /*      fprintf (stderr,"box %d, at %d pos \n", j, (int) ftell(qix));
+    */
 
-    j = qix->nShapes;
-    msSHPDiskTreeClose (qix);
+    node = readTreeNode (qix);
+    if (node ) {
+      fprintf (stdout,"shapes %d, node %d, %f,%f,%f,%f \n",(int) node->numshapes,node->numsubnodes,node->rect.minx, node->rect.miny, node->rect.maxx, node->rect.maxy);
 
-    if( argc >= 5 )
-    {
-      rect.minx = atof (argv[2]);
-      rect.miny = atof (argv[3]);
-      rect.maxx = atof (argv[4]);
-      rect.maxy = atof (argv[5]);
+    } else {
+      pos = 0;
     }
-    else
-    {
-      printf ("using last read box as a search \n");
-      rect.minx =  node->rect.minx;
-      rect.miny =  node->rect.miny;
-      rect.maxx =  node->rect.maxx;
-      rect.maxy =  node->rect.maxy;
-    }
-
-    bitmap = msSearchDiskTree( argv[1], rect, 0 /* no debug*/ );
-
-    if ( bitmap )
-    {
-      printf ("result of rectangle search was \n");
-      for ( i=0; i<j; i++)
-      {
-        if ( msGetBit(bitmap,i) )
-        {
-          printf(" %d,",i);
-        }
+  }
+
+  printf ("read entire file now at quad box rec %d file pos %ld\n", j, ftell (qix->fp));
+
+  j = qix->nShapes;
+  msSHPDiskTreeClose (qix);
+
+  if( argc >= 5 ) {
+    rect.minx = atof (argv[2]);
+    rect.miny = atof (argv[3]);
+    rect.maxx = atof (argv[4]);
+    rect.maxy = atof (argv[5]);
+  } else {
+    printf ("using last read box as a search \n");
+    rect.minx =  node->rect.minx;
+    rect.miny =  node->rect.miny;
+    rect.maxx =  node->rect.maxx;
+    rect.maxy =  node->rect.maxy;
+  }
+
+  bitmap = msSearchDiskTree( argv[1], rect, 0 /* no debug*/ );
+
+  if ( bitmap ) {
+    printf ("result of rectangle search was \n");
+    for ( i=0; i<j; i++) {
+      if ( msGetBit(bitmap,i) ) {
+        printf(" %d,",i);
       }
     }
-    printf("\n");
+  }
+  printf("\n");
 
 
 
-    return(0);
+  return(0);
 }
diff --git a/shptreevis.c b/shptreevis.c
index b2277d6..948222c 100644
--- a/shptreevis.c
+++ b/shptreevis.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -35,208 +35,211 @@
 #endif
 #include <stdlib.h>
 
-MS_CVSID("$Id$")
+
 
 #ifdef SHPT_POLYGON
-   #undef MAPSERVER
+#undef MAPSERVER
 #else
-   #define MAPSERVER 1
-   #define SHPT_POLYGON SHP_POLYGON
+#define MAPSERVER 1
+#define SHPT_POLYGON SHP_POLYGON
 #endif
 
-char* AddFileSuffix ( const char * Filename, const char * Suffix ) {
-    char	*pszFullname, *pszBasename;
-    int	i;
-      
+char* AddFileSuffix ( const char * Filename, const char * Suffix )
+{
+  char  *pszFullname, *pszBasename;
+  int i;
+
   /* -------------------------------------------------------------------- */
-  /*	Compute the base (layer) name.  If there is any extension	    */
-  /*	on the passed in filename we will strip it off.			    */
+  /*  Compute the base (layer) name.  If there is any extension     */
+  /*  on the passed in filename we will strip it off.         */
   /* -------------------------------------------------------------------- */
-    pszBasename = (char *) msSmallMalloc(strlen(Filename)+5);
-    strcpy( pszBasename, Filename );
-    for( i = strlen(pszBasename)-1; 
+  pszBasename = (char *) msSmallMalloc(strlen(Filename)+5);
+  strcpy( pszBasename, Filename );
+  for( i = strlen(pszBasename)-1;
        i > 0 && pszBasename[i] != '.' && pszBasename[i] != '/'
-	 && pszBasename[i] != '\\';
+       && pszBasename[i] != '\\';
        i-- ) {}
-  
-    if( pszBasename[i] == '.' )
-      pszBasename[i] = '\0';
-  
+
+  if( pszBasename[i] == '.' )
+    pszBasename[i] = '\0';
+
   /* -------------------------------------------------------------------- */
-  /*	Open the .shp and .shx files.  Note that files pulled from	    */
-  /*	a PC to Unix with upper case filenames won't work!		    */
+  /*  Open the .shp and .shx files.  Note that files pulled from      */
+  /*  a PC to Unix with upper case filenames won't work!        */
   /* -------------------------------------------------------------------- */
-    pszFullname = (char *) msSmallMalloc(strlen(pszBasename) + 5);
-    sprintf( pszFullname, "%s%s", pszBasename, Suffix); 
-      
-    return (pszFullname);
+  pszFullname = (char *) msSmallMalloc(strlen(pszBasename) + 5);
+  sprintf( pszFullname, "%s%s", pszBasename, Suffix);
+
+  return (pszFullname);
 }
 
 
 int main( int argc, char ** argv )
 
 {
-    SHPHandle	hSHP;
-    DBFHandle   hDBF;
-    SHPTreeHandle	qix;
-    
-    int		i;
-    char	*myfile = NULL;
+  SHPHandle hSHP;
+  DBFHandle   hDBF;
+  SHPTreeHandle qix;
+
+  char  *myfile = NULL;
 
-    treeNodeObj *node;    
+  treeNodeObj *node;
 
 #ifdef MAPSERVER
-    shapeObj	shape;
-    lineObj	line[3];
-    pointObj	pts[6];
+  shapeObj  shape;
+  lineObj line[3];
+  pointObj  pts[6];
 #else
-    SHPObject	*shape;
-    double	X[6], Y[6];
-#endif   
-    int		result;
-    char	mBigEndian;
-
-    int		this_rec, factor;
-
-/* -------------------------------------------------------------------- */
-/*      Display a usage message.                                        */
-/* -------------------------------------------------------------------- */
-    if( argc <= 2 )
-    {
-	printf( "shptreevis shapefile new_shapefile \n" );
-	exit( 1 );
-    }
-
-    i = 1;
-    if( *((unsigned char *) &i) == 1 )
-      mBigEndian = 0;
-    else
-      mBigEndian = 1;
-
-
-    qix = msSHPDiskTreeOpen (AddFileSuffix(argv[1],".qix"), 0 /* no debug*/);
-    if( qix == NULL )
-    {
-      printf("unable to open index file %s \n", argv[1]);
-      exit(-1);
-    }
-
-/* -------------------------------------------------------------------- */
-/*      Open the passed shapefile.                                      */
-/* -------------------------------------------------------------------- */
-    myfile = AddFileSuffix(argv[2],".shp");
+  SHPObject *shape;
+  double  X[6], Y[6];
+#endif
+  int   result;
+  
+  /*
+  char  mBigEndian;
+  int   i;
+  */
+
+  int   this_rec;
+
+  /* -------------------------------------------------------------------- */
+  /*      Display a usage message.                                        */
+  /* -------------------------------------------------------------------- */
+  if( argc <= 2 ) {
+    printf( "shptreevis shapefile new_shapefile \n" );
+    exit( 1 );
+  }
+
+  /*
+  i = 1;
+  if( *((unsigned char *) &i) == 1 )
+    mBigEndian = 0;
+  else
+    mBigEndian = 1;
+  */
+
+
+  qix = msSHPDiskTreeOpen (AddFileSuffix(argv[1],".qix"), 0 /* no debug*/);
+  if( qix == NULL ) {
+    printf("unable to open index file %s \n", argv[1]);
+    exit(-1);
+  }
+
+  /* -------------------------------------------------------------------- */
+  /*      Open the passed shapefile.                                      */
+  /* -------------------------------------------------------------------- */
+  myfile = AddFileSuffix(argv[2],".shp");
 
 #ifdef MAPSERVER
-    hSHP = msSHPCreate ( myfile, SHPT_POLYGON );
-    hDBF = msDBFCreate (  AddFileSuffix(argv[2],".dbf") );
-#else    
-    hSHP = SHPCreate ( myfile, SHPT_POLYGON );
-    hDBF = DBFCreate (  AddFileSuffix(argv[2],".dbf") );
+  hSHP = msSHPCreate ( myfile, SHPT_POLYGON );
+  hDBF = msDBFCreate (  AddFileSuffix(argv[2],".dbf") );
+#else
+  hSHP = SHPCreate ( myfile, SHPT_POLYGON );
+  hDBF = DBFCreate (  AddFileSuffix(argv[2],".dbf") );
 #endif
 
-    if ( (!hSHP) || (!hDBF) )
-    {
-      printf ("create error for %s    ... exiting \n", myfile);
-      exit (-1);
-    }
+  if ( (!hSHP) || (!hDBF) ) {
+    printf ("create error for %s    ... exiting \n", myfile);
+    exit (-1);
+  }
 
-    /* add fields to dbf */
+  /* add fields to dbf */
 #ifdef MAPSERVER
-    msDBFAddField ( hDBF, "ITEMS", FTInteger, 15,0 );
-    msDBFAddField ( hDBF, "SUBNODES", FTInteger, 15,0 );
-    msDBFAddField ( hDBF, "FACTOR", FTInteger, 15,0 );
+  msDBFAddField ( hDBF, "ITEMS", FTInteger, 15,0 );
+  msDBFAddField ( hDBF, "SUBNODES", FTInteger, 15,0 );
+  msDBFAddField ( hDBF, "FACTOR", FTInteger, 15,0 );
 #else
-    DBFAddField ( hDBF, "ITEMS", FTInteger, 15,0 );
-    DBFAddField ( hDBF, "SUBNODES", FTInteger, 15,0 );
-    DBFAddField ( hDBF, "FACTOR", FTInteger, 15,0 );
+  DBFAddField ( hDBF, "ITEMS", FTInteger, 15,0 );
+  DBFAddField ( hDBF, "SUBNODES", FTInteger, 15,0 );
+  DBFAddField ( hDBF, "FACTOR", FTInteger, 15,0 );
 #endif
 
 #ifndef MAPSERVER
-    SHPClose ( hSHP );
-    hSHP = SHPOpen ( myfile, "r+b" );
-    
-    DBFClose (hDBF);
-    hDBF = DBFOpen ( myfile, "r+b");
+  SHPClose ( hSHP );
+  hSHP = SHPOpen ( myfile, "r+b" );
+
+  DBFClose (hDBF);
+  hDBF = DBFOpen ( myfile, "r+b");
 #endif
 
-    printf ("This %s %s index supports a shapefile with %d shapes, %d depth \n",
-	(qix->version ? "new": "old"), (qix->LSB_order? "LSB": "MSB"), (int) qix->nShapes, (int) qix->nDepth);
+  printf ("This %s %s index supports a shapefile with %d shapes, %d depth \n",
+          (qix->version ? "new": "old"), (qix->LSB_order? "LSB": "MSB"), (int) qix->nShapes, (int) qix->nDepth);
 
 
-/* -------------------------------------------------------------------- */
-/*	Skim over the list of shapes, printing all the vertices.	*/
-/* -------------------------------------------------------------------- */
+  /* -------------------------------------------------------------------- */
+  /*  Skim over the list of shapes, printing all the vertices.  */
+  /* -------------------------------------------------------------------- */
 
-    while( 1 )
-    {
-      node = readTreeNode (qix);
-      if (node )
-      {
+  while( 1 ) {
+    node = readTreeNode (qix);
+    if (node ) {
 
-        this_rec = hDBF->nRecords;
+      this_rec = hDBF->nRecords;
 
 #ifdef  MAPSERVER
-        msDBFWriteIntegerAttribute( hDBF, this_rec, 0, node->numshapes);
-        msDBFWriteIntegerAttribute( hDBF, this_rec, 1, node->numsubnodes);
+      msDBFWriteIntegerAttribute( hDBF, this_rec, 0, node->numshapes);
+      msDBFWriteIntegerAttribute( hDBF, this_rec, 1, node->numsubnodes);
 #else
-        DBFWriteIntegerAttribute( hDBF, this_rec, 0, node->numshapes);
-        DBFWriteIntegerAttribute( hDBF, this_rec, 1, node->numsubnodes);
+      DBFWriteIntegerAttribute( hDBF, this_rec, 0, node->numshapes);
+      DBFWriteIntegerAttribute( hDBF, this_rec, 1, node->numsubnodes);
 #endif
-        factor = node->numshapes + node->numsubnodes;
-        
+
 #ifdef  MAPSERVER
-	shape.numlines = 1;
-	shape.type = SHPT_POLYGON;
-
-	pts[0].x = node->rect.minx;     pts[0].y = node->rect.miny;
-	pts[1].x = node->rect.maxx;     pts[1].y = node->rect.miny;
-	pts[2].x = node->rect.maxx;     pts[2].y = node->rect.maxy;
-	pts[3].x = node->rect.minx;     pts[3].y = node->rect.maxy;
-        pts[4].x = node->rect.minx;     pts[4].y = node->rect.miny;
-
-	line[0].numpoints = 5;
-	line[0].point = &pts[0];
-	shape.line = &line[0];
-	shape.bounds = node->rect;
-	
-	result = msSHPWriteShape ( hSHP, &shape );
-	if ( result < 0 )
-	{ 
-	  printf ("unable to write shape \n");  
-	  exit (0);
-	}
+      shape.numlines = 1;
+      shape.type = SHPT_POLYGON;
+
+      pts[0].x = node->rect.minx;
+      pts[0].y = node->rect.miny;
+      pts[1].x = node->rect.maxx;
+      pts[1].y = node->rect.miny;
+      pts[2].x = node->rect.maxx;
+      pts[2].y = node->rect.maxy;
+      pts[3].x = node->rect.minx;
+      pts[3].y = node->rect.maxy;
+      pts[4].x = node->rect.minx;
+      pts[4].y = node->rect.miny;
+
+      line[0].numpoints = 5;
+      line[0].point = &pts[0];
+      shape.line = &line[0];
+      shape.bounds = node->rect;
+
+      result = msSHPWriteShape ( hSHP, &shape );
+      if ( result < 0 ) {
+        printf ("unable to write shape \n");
+        exit (0);
+      }
 
 #else
-        X[0] = node->rect.minx;
-        X[1] = node->rect.maxx;
-        X[2] = node->rect.maxx;
-        X[3] = node->rect.minx;
-        X[4] = node->rect.minx;
-
-        Y[0] = node->rect.miny;
-        Y[1] = node->rect.miny;
-        Y[2] = node->rect.maxy;
-        Y[3] = node->rect.maxy;
-        Y[4] = node->rect.miny;
-        
-        shape = SHPCreateSimpleObject( SHPT_POLYGON, 5, X, Y, NULL);
-        SHPWriteObject(hSHP, -1, shape); 
-        SHPDestroyObject ( shape );
+      X[0] = node->rect.minx;
+      X[1] = node->rect.maxx;
+      X[2] = node->rect.maxx;
+      X[3] = node->rect.minx;
+      X[4] = node->rect.minx;
+
+      Y[0] = node->rect.miny;
+      Y[1] = node->rect.miny;
+      Y[2] = node->rect.maxy;
+      Y[3] = node->rect.maxy;
+      Y[4] = node->rect.miny;
+
+      shape = SHPCreateSimpleObject( SHPT_POLYGON, 5, X, Y, NULL);
+      SHPWriteObject(hSHP, -1, shape);
+      SHPDestroyObject ( shape );
 #endif
-        }
-        else 
-            break;
-    }
-
-#ifdef MAPSERVER   
-    msSHPClose( hSHP );
-    msDBFClose( hDBF );
+    } else
+      break;
+  }
+
+#ifdef MAPSERVER
+  msSHPClose( hSHP );
+  msDBFClose( hDBF );
 #else
-    SHPClose( hSHP );
-    DBFClose( hDBF );
+  SHPClose( hSHP );
+  DBFClose( hDBF );
 #endif
 
-    msSHPDiskTreeClose (qix);    
-    
-    return(0);
+  msSHPDiskTreeClose (qix);
+
+  return(0);
 }
diff --git a/sortshp.c b/sortshp.c
index e6e6fe0..4f439ef 100644
--- a/sortshp.c
+++ b/sortshp.c
@@ -2,8 +2,8 @@
  * $Id$
  *
  * Project:  MapServer
- * Purpose:  Command line utility to sort a shapefile based on a single 
- *           attribute in ascending or decending order. Useful for 
+ * Purpose:  Command line utility to sort a shapefile based on a single
+ *           attribute in ascending or decending order. Useful for
  *           prioritizing drawing or labeling of shapes.
  * Author:   Steve Lime and the MapServer team.
  *
@@ -17,7 +17,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -36,7 +36,7 @@
 
 #include "mapserver.h"
 
-MS_CVSID("$Id$")
+
 
 typedef struct {
   double number;
@@ -50,7 +50,7 @@ static int compare_string_descending(const void *a, const void *b)
   return(strcmp(j->string, i->string));
 }
 
-static int compare_string_ascending(const void *a, const void *b) 
+static int compare_string_ascending(const void *a, const void *b)
 {
   const sortStruct *i = a, *j = b;
   return(strcmp(i->string, j->string));
@@ -60,18 +60,18 @@ static int compare_number_descending(const void *a, const void *b)
 {
   const sortStruct *i = a, *j = b;
   if(i->number > j->number)
-    return(-1);  
-  if(i->number < j->number)  
+    return(-1);
+  if(i->number < j->number)
     return(1);
   return(0);
 }
 
-static int compare_number_ascending(const void *a, const void *b) 
+static int compare_number_ascending(const void *a, const void *b)
 {
   const sortStruct *i = a, *j = b;
   if(i->number > j->number)
-    return(1);  
-  if(i->number < j->number)  
+    return(1);
+  if(i->number < j->number)
     return(-1);
   return(0);
 }
@@ -79,18 +79,18 @@ static int compare_number_ascending(const void *a, const void *b)
 int main(int argc, char *argv[])
 {
   SHPHandle    inSHP,outSHP; /* ---- Shapefile file pointers ---- */
-  DBFHandle    inDBF,outDBF; /* ---- DBF file pointers ---- */  
+  DBFHandle    inDBF,outDBF; /* ---- DBF file pointers ---- */
   sortStruct   *array;
   shapeObj     shape;
   int          shpType, nShapes;
   int          fieldNumber=-1; /* ---- Field number of item to be sorted on ---- */
   DBFFieldType dbfField;
   char         fName[20];
-  int          fWidth,fnDecimals; 
+  int          fWidth,fnDecimals;
   char         buffer[1024];
   int i,j;
   int num_fields, num_records;
-  
+
   if(argc > 1 && strcmp(argv[1], "-v") == 0) {
     printf("%s\n", msGetVersion());
     exit(0);
@@ -100,8 +100,8 @@ int main(int argc, char *argv[])
   /*       Check the number of arguments, return syntax if not correct               */
   /* ------------------------------------------------------------------------------- */
   if( argc != 5 ) {
-      fprintf(stderr,"Syntax: sortshp [infile] [outfile] [item] [ascending|descending]\n" );
-      exit(1);
+    fprintf(stderr,"Syntax: sortshp [infile] [outfile] [item] [ascending|descending]\n" );
+    exit(1);
   }
 
   msSetErrorFile("stderr", NULL);
@@ -129,7 +129,7 @@ int main(int argc, char *argv[])
   num_fields = msDBFGetFieldCount(inDBF);
   num_records = msDBFGetRecordCount(inDBF);
 
-  for(i=0;i<num_fields;i++) {
+  for(i=0; i<num_fields; i++) {
     msDBFGetFieldInfo(inDBF,i,fName,NULL,NULL);
     if(strncasecmp(argv[3],fName,strlen(argv[3])) == 0) { /* ---- Found it ---- */
       fieldNumber = i;
@@ -140,67 +140,65 @@ int main(int argc, char *argv[])
   if(fieldNumber < 0) {
     fprintf(stderr,"Item %s doesn't exist in %s\n",argv[3],buffer);
     exit(1);
-  }  
+  }
 
   array = (sortStruct *)malloc(sizeof(sortStruct)*num_records); /* ---- Allocate the array ---- */
   if(!array) {
     fprintf(stderr, "Unable to allocate sort array.\n");
     exit(1);
   }
-  
+
   /* ------------------------------------------------------------------------------- */
   /*       Load the array to be sorted                                               */
   /* ------------------------------------------------------------------------------- */
   dbfField = msDBFGetFieldInfo(inDBF,fieldNumber,NULL,NULL,NULL);
   switch (dbfField) {
-  case FTString:
-    for(i=0;i<num_records;i++) {
-      strlcpy(array[i].string, msDBFReadStringAttribute( inDBF, i, fieldNumber), sizeof(array[i].string));
-      array[i].index = i;
-    }
+    case FTString:
+      for(i=0; i<num_records; i++) {
+        strlcpy(array[i].string, msDBFReadStringAttribute( inDBF, i, fieldNumber), sizeof(array[i].string));
+        array[i].index = i;
+      }
 
-    if(*argv[4] == 'd')
-      qsort(array, num_records, sizeof(sortStruct), compare_string_descending);
-    else
-      qsort(array, num_records, sizeof(sortStruct), compare_string_ascending);
-    break;
-  case FTInteger:
-  case FTDouble:
-    for(i=0;i<num_records;i++) {
-      array[i].number = msDBFReadDoubleAttribute( inDBF, i, fieldNumber);
-      array[i].index = i;
-    }
+      if(*argv[4] == 'd')
+        qsort(array, num_records, sizeof(sortStruct), compare_string_descending);
+      else
+        qsort(array, num_records, sizeof(sortStruct), compare_string_ascending);
+      break;
+    case FTInteger:
+    case FTDouble:
+      for(i=0; i<num_records; i++) {
+        array[i].number = msDBFReadDoubleAttribute( inDBF, i, fieldNumber);
+        array[i].index = i;
+      }
 
-    if(*argv[4] == 'd')
-      qsort(array, num_records, sizeof(sortStruct), compare_number_descending);
-    else
-      qsort(array, num_records, sizeof(sortStruct), compare_number_ascending);
+      if(*argv[4] == 'd')
+        qsort(array, num_records, sizeof(sortStruct), compare_number_descending);
+      else
+        qsort(array, num_records, sizeof(sortStruct), compare_number_ascending);
 
-    break;
-  default:
+      break;
+    default:
       fprintf(stderr,"Data type for item %s not supported.\n",argv[3]);
       exit(1);
-  } 
-  
+  }
+
   /* ------------------------------------------------------------------------------- */
   /*       Setup the output .shp/.shx and .dbf files                                 */
   /* ------------------------------------------------------------------------------- */
   outSHP = msSHPCreate(argv[2],shpType);
-  if( outSHP == NULL )
-  {
-      fprintf( stderr, "Failed to create file '%s'.\n", argv[2] );
-      exit( 1 );
+  if( outSHP == NULL ) {
+    fprintf( stderr, "Failed to create file '%s'.\n", argv[2] );
+    exit( 1 );
   }
 
   sprintf(buffer,"%s.dbf",argv[2]);
   outDBF = msDBFCreate(buffer);
-  if( outDBF == NULL )
-  {
-      fprintf( stderr, "Failed to create dbf file '%s'.\n", buffer );
-      exit( 1 );
+  if( outDBF == NULL ) {
+    fprintf( stderr, "Failed to create dbf file '%s'.\n", buffer );
+    exit( 1 );
   }
 
-  for(i=0;i<num_fields;i++) {
+  for(i=0; i<num_fields; i++) {
     dbfField = msDBFGetFieldInfo(inDBF,i,fName,&fWidth,&fnDecimals); /* ---- Get field info from in file ---- */
     msDBFAddField(outDBF,fName,dbfField,fWidth,fnDecimals);
   }
@@ -208,28 +206,28 @@ int main(int argc, char *argv[])
   /* ------------------------------------------------------------------------------- */
   /*       Write the sorted .shp/.shx and .dbf files                                 */
   /* ------------------------------------------------------------------------------- */
-  for(i=0;i<num_records;i++) { /* ---- For each shape/record ---- */
+  for(i=0; i<num_records; i++) { /* ---- For each shape/record ---- */
 
-    for(j=0;j<num_fields;j++) { /* ---- For each .dbf field ---- */
+    for(j=0; j<num_fields; j++) { /* ---- For each .dbf field ---- */
 
-      dbfField = msDBFGetFieldInfo(inDBF,j,fName,&fWidth,&fnDecimals); 
+      dbfField = msDBFGetFieldInfo(inDBF,j,fName,&fWidth,&fnDecimals);
 
       switch (dbfField) {
-      case FTInteger:
-	msDBFWriteIntegerAttribute(outDBF, i, j, msDBFReadIntegerAttribute( inDBF, array[i].index, j));
-        break;
-      case FTDouble:
-	msDBFWriteDoubleAttribute(outDBF, i, j, msDBFReadDoubleAttribute( inDBF, array[i].index, j));
-	break;
-      case FTString:
-	msDBFWriteStringAttribute(outDBF, i, j, msDBFReadStringAttribute( inDBF, array[i].index, j));
-	break;
-      default:
-	fprintf(stderr,"Unsupported data type for field: %s, exiting.\n",fName);
-        exit(0);
+        case FTInteger:
+          msDBFWriteIntegerAttribute(outDBF, i, j, msDBFReadIntegerAttribute( inDBF, array[i].index, j));
+          break;
+        case FTDouble:
+          msDBFWriteDoubleAttribute(outDBF, i, j, msDBFReadDoubleAttribute( inDBF, array[i].index, j));
+          break;
+        case FTString:
+          msDBFWriteStringAttribute(outDBF, i, j, msDBFReadStringAttribute( inDBF, array[i].index, j));
+          break;
+        default:
+          fprintf(stderr,"Unsupported data type for field: %s, exiting.\n",fName);
+          exit(0);
       }
     }
-    
+
     msSHPReadShape( inSHP, array[i].index, &shape );
     msSHPWriteShape( outSHP, &shape );
     msFreeShape( &shape );
diff --git a/stablemerge.sh b/stablemerge.sh
index 9dd107a..e038fac 100644
--- a/stablemerge.sh
+++ b/stablemerge.sh
@@ -20,6 +20,10 @@ git checkout branch-6-0
 if test $? -ne 0; then exit; fi
 git merge branch-5-6
 if test $? -ne 0; then exit; fi
-git checkout master
+git checkout branch-6-2
 if test $? -ne 0; then exit; fi
 git merge branch-6-0
+if test $? -ne 0; then exit; fi
+git checkout master
+if test $? -ne 0; then exit; fi
+git merge branch-6-2
diff --git a/strptime.c b/strptime.c
index 074598c..b7f9f83 100644
--- a/strptime.c
+++ b/strptime.c
@@ -1,18 +1,18 @@
 /*
  * Copyright (c) 1999 Kungliga Tekniska Högskolan
- * (Royal Institute of Technology, Stockholm, Sweden). 
- * All rights reserved. 
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without 
- * modification, are permitted provided that the following conditions 
- * are met: 
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright 
- *    notice, this list of conditions and the following disclaimer. 
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright 
- *    notice, this list of conditions and the following disclaimer in the 
- *    documentation and/or other materials provided with the distribution. 
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software without
@@ -41,67 +41,67 @@
 #include "mapserver.h"
 
 static const char *abb_weekdays[] = {
-    "Sun",
-    "Mon",
-    "Tue",
-    "Wed",
-    "Thu",
-    "Fri",
-    "Sat",
-    NULL
+  "Sun",
+  "Mon",
+  "Tue",
+  "Wed",
+  "Thu",
+  "Fri",
+  "Sat",
+  NULL
 };
 
 static const char *full_weekdays[] = {
-    "Sunday",
-    "Monday",
-    "Tuesday",
-    "Wednesday",
-    "Thursday",
-    "Friday",
-    "Saturday",
-    NULL
+  "Sunday",
+  "Monday",
+  "Tuesday",
+  "Wednesday",
+  "Thursday",
+  "Friday",
+  "Saturday",
+  NULL
 };
 
 static const char *abb_month[] = {
-    "Jan",
-    "Feb",
-    "Mar",
-    "Apr",
-    "May",
-    "Jun",
-    "Jul",
-    "Aug",
-    "Sep",
-    "Oct",
-    "Nov",
-    "Dec",
-    NULL
+  "Jan",
+  "Feb",
+  "Mar",
+  "Apr",
+  "May",
+  "Jun",
+  "Jul",
+  "Aug",
+  "Sep",
+  "Oct",
+  "Nov",
+  "Dec",
+  NULL
 };
 
 static const char *full_month[] = {
-    "January",
-    "February",
-    "Mars",
-    "April",
-    "May",
-    "June",
-    "July",
-    "August",
-    "September",
-    "October",
-    "November",
-    "December",
-    NULL,
+  "January",
+  "February",
+  "Mars",
+  "April",
+  "May",
+  "June",
+  "July",
+  "August",
+  "September",
+  "October",
+  "November",
+  "December",
+  NULL,
 };
 
 static const char *ampm[] = {
-    "am",
-    "pm",
-    NULL
+  "am",
+  "pm",
+  NULL
 };
 
 /*
- * tm_year is relative this year 
+ * tm_year is relative this year
  */
 const int tm_year_base = 1900;
 
@@ -112,35 +112,35 @@ const int tm_year_base = 1900;
 static int
 is_leap_year (int year)
 {
-    return (year % 4) == 0 && ((year % 100) != 0 || (year % 400) == 0);
+  return (year % 4) == 0 && ((year % 100) != 0 || (year % 400) == 0);
 }
 
 /* Needed for strptime. */
 static int
 match_string (const char **buf, const char **strs)
 {
-    int i = 0;
+  int i = 0;
 
-    for (i = 0; strs[i] != NULL; ++i) {
-	int len = strlen (strs[i]);
+  for (i = 0; strs[i] != NULL; ++i) {
+    int len = strlen (strs[i]);
 
-	if (strncasecmp (*buf, strs[i], len) == 0) {
-	    *buf += len;
-	    return i;
-	}
+    if (strncasecmp (*buf, strs[i], len) == 0) {
+      *buf += len;
+      return i;
     }
-    return -1;
+  }
+  return -1;
 }
 
 /* Needed for strptime. */
 static int
 first_day (int year)
 {
-    int ret = 4;
+  int ret = 4;
 
-    for (; year > 1970; --year)
-	ret = (ret + 365 + is_leap_year (year) ? 1 : 0) % 7;
-    return ret;
+  for (; year > 1970; --year)
+    ret = (ret + 365 + is_leap_year (year) ? 1 : 0) % 7;
+  return ret;
 }
 
 /*
@@ -151,13 +151,13 @@ first_day (int year)
 static void
 set_week_number_sun (struct tm *timeptr, int wnum)
 {
-    int fday = first_day (timeptr->tm_year + tm_year_base);
+  int fday = first_day (timeptr->tm_year + tm_year_base);
 
-    timeptr->tm_yday = wnum * 7 + timeptr->tm_wday - fday;
-    if (timeptr->tm_yday < 0) {
-	timeptr->tm_wday = fday;
-	timeptr->tm_yday = 0;
-    }
+  timeptr->tm_yday = wnum * 7 + timeptr->tm_wday - fday;
+  if (timeptr->tm_yday < 0) {
+    timeptr->tm_wday = fday;
+    timeptr->tm_yday = 0;
+  }
 }
 
 /*
@@ -168,13 +168,13 @@ set_week_number_sun (struct tm *timeptr, int wnum)
 static void
 set_week_number_mon (struct tm *timeptr, int wnum)
 {
-    int fday = (first_day (timeptr->tm_year + tm_year_base) + 6) % 7;
+  int fday = (first_day (timeptr->tm_year + tm_year_base) + 6) % 7;
 
-    timeptr->tm_yday = wnum * 7 + (timeptr->tm_wday + 6) % 7 - fday;
-    if (timeptr->tm_yday < 0) {
-	timeptr->tm_wday = (fday + 1) % 7;
-	timeptr->tm_yday = 0;
-    }
+  timeptr->tm_yday = wnum * 7 + (timeptr->tm_wday + 6) % 7 - fday;
+  if (timeptr->tm_yday < 0) {
+    timeptr->tm_wday = (fday + 1) % 7;
+    timeptr->tm_yday = 0;
+  }
 }
 
 /*
@@ -184,17 +184,17 @@ set_week_number_mon (struct tm *timeptr, int wnum)
 static void
 set_week_number_mon4 (struct tm *timeptr, int wnum)
 {
-    int fday = (first_day (timeptr->tm_year + tm_year_base) + 6) % 7;
-    int offset = 0;
+  int fday = (first_day (timeptr->tm_year + tm_year_base) + 6) % 7;
+  int offset = 0;
 
-    if (fday < 4)
-	offset += 7;
+  if (fday < 4)
+    offset += 7;
 
-    timeptr->tm_yday = offset + (wnum - 1) * 7 + timeptr->tm_wday - fday;
-    if (timeptr->tm_yday < 0) {
-	timeptr->tm_wday = fday;
-	timeptr->tm_yday = 0;
-    }
+  timeptr->tm_yday = offset + (wnum - 1) * 7 + timeptr->tm_wday - fday;
+  if (timeptr->tm_yday < 0) {
+    timeptr->tm_wday = fday;
+    timeptr->tm_yday = 0;
+  }
 }
 
 /* strptime: roken */
@@ -203,240 +203,240 @@ char *
 /* strptime (const char *buf, const char *format, struct tm *timeptr) */
 strptime (const char *buf, const char *format, struct tm *timeptr)
 {
-    char c;
+  char c;
 
-    for (; (c = *format) != '\0'; ++format) {
-	char *s;
-	int ret;
+  for (; (c = *format) != '\0'; ++format) {
+    char *s;
+    int ret;
 
-	if (isspace (c)) {
-	    while (isspace (*buf))
-		++buf;
-	} else if (c == '%' && format[1] != '\0') {
-	    c = *++format;
-	    if (c == 'E' || c == 'O')
-		c = *++format;
-	    switch (c) {
-	    case 'A' :
-		ret = match_string (&buf, full_weekdays);
-		if (ret < 0)
-		    return NULL;
-		timeptr->tm_wday = ret;
-		break;
-	    case 'a' :
-		ret = match_string (&buf, abb_weekdays);
-		if (ret < 0)
-		    return NULL;
-		timeptr->tm_wday = ret;
-		break;
-	    case 'B' :
-		ret = match_string (&buf, full_month);
-		if (ret < 0)
-		    return NULL;
-		timeptr->tm_mon = ret;
-		break;
-	    case 'b' :
-	    case 'h' :
-		ret = match_string (&buf, abb_month);
-		if (ret < 0)
-		    return NULL;
-		timeptr->tm_mon = ret;
-		break;
-	    case 'C' :
-		ret = strtol (buf, &s, 10);
-		if (s == buf)
-		    return NULL;
-		timeptr->tm_year = (ret * 100) - tm_year_base;
-		buf = s;
-		break;
-	    case 'c' :
-		abort ();
-	    case 'D' :		/* %m/%d/%y */
-		s = strptime (buf, "%m/%d/%y", timeptr);
-		if (s == NULL)
-		    return NULL;
-		buf = s;
-		break;
-	    case 'd' :
-	    case 'e' :
-		ret = strtol (buf, &s, 10);
-		if (s == buf)
-		    return NULL;
-		timeptr->tm_mday = ret;
-		buf = s;
-		break;
-	    case 'H' :
-	    case 'k' :
-		ret = strtol (buf, &s, 10);
-		if (s == buf)
-		    return NULL;
-		timeptr->tm_hour = ret;
-		buf = s;
-		break;
-	    case 'I' :
-	    case 'l' :
-		ret = strtol (buf, &s, 10);
-		if (s == buf)
-		    return NULL;
-		if (ret == 12)
-		    timeptr->tm_hour = 0;
-		else
-		    timeptr->tm_hour = ret;
-		buf = s;
-		break;
-	    case 'j' :
-		ret = strtol (buf, &s, 10);
-		if (s == buf)
-		    return NULL;
-		timeptr->tm_yday = ret - 1;
-		buf = s;
-		break;
-	    case 'm' :
-		ret = strtol (buf, &s, 10);
-		if (s == buf)
-		    return NULL;
-		timeptr->tm_mon = ret - 1;
-		buf = s;
-		break;
-	    case 'M' :
-		ret = strtol (buf, &s, 10);
-		if (s == buf)
-		    return NULL;
-		timeptr->tm_min = ret;
-		buf = s;
-		break;
-	    case 'n' :
-		if (*buf == '\n')
-		    ++buf;
-		else
-		    return NULL;
-		break;
-	    case 'p' :
-		ret = match_string (&buf, ampm);
-		if (ret < 0)
-		    return NULL;
-		if (timeptr->tm_hour == 0) {
-		    if (ret == 1)
-			timeptr->tm_hour = 12;
-		} else
-		    timeptr->tm_hour += 12;
-		break;
-	    case 'r' :		/* %I:%M:%S %p */
-		s = strptime (buf, "%I:%M:%S %p", timeptr);
-		if (s == NULL)
-		    return NULL;
-		buf = s;
-		break;
-	    case 'R' :		/* %H:%M */
-		s = strptime (buf, "%H:%M", timeptr);
-		if (s == NULL)
-		    return NULL;
-		buf = s;
-		break;
-	    case 'S' :
-		ret = strtol (buf, &s, 10);
-		if (s == buf)
-		    return NULL;
-		timeptr->tm_sec = ret;
-		buf = s;
-		break;
-	    case 't' :
-		if (*buf == '\t')
-		    ++buf;
-		else
-		    return NULL;
-		break;
-	    case 'T' :		/* %H:%M:%S */
-	    case 'X' :
-		s = strptime (buf, "%H:%M:%S", timeptr);
-		if (s == NULL)
-		    return NULL;
-		buf = s;
-		break;
-	    case 'u' :
-		ret = strtol (buf, &s, 10);
-		if (s == buf)
-		    return NULL;
-		timeptr->tm_wday = ret - 1;
-		buf = s;
-		break;
-	    case 'w' :
-		ret = strtol (buf, &s, 10);
-		if (s == buf)
-		    return NULL;
-		timeptr->tm_wday = ret;
-		buf = s;
-		break;
-	    case 'U' :
-		ret = strtol (buf, &s, 10);
-		if (s == buf)
-		    return NULL;
-		set_week_number_sun (timeptr, ret);
-		buf = s;
-		break;
-	    case 'V' :
-		ret = strtol (buf, &s, 10);
-		if (s == buf)
-		    return NULL;
-		set_week_number_mon4 (timeptr, ret);
-		buf = s;
-		break;
-	    case 'W' :
-		ret = strtol (buf, &s, 10);
-		if (s == buf)
-		    return NULL;
-		set_week_number_mon (timeptr, ret);
-		buf = s;
-		break;
-	    case 'x' :
-		s = strptime (buf, "%Y:%m:%d", timeptr);
-		if (s == NULL)
-		    return NULL;
-		buf = s;
-		break;
-	    case 'y' :
-		ret = strtol (buf, &s, 10);
-		if (s == buf)
-		    return NULL;
-		if (ret < 70)
-		    timeptr->tm_year = 100 + ret;
-		else
-		    timeptr->tm_year = ret;
-		buf = s;
-		break;
-	    case 'Y' :
-		ret = strtol (buf, &s, 10);
-		if (s == buf)
-		    return NULL;
-		timeptr->tm_year = ret - tm_year_base;
-		buf = s;
-		break;
-	    case 'Z' :
-		abort ();
-	    case '\0' :
-		--format;
-		/* FALLTHROUGH */
-	    case '%' :
-		if (*buf == '%')
-		    ++buf;
-		else
-		    return NULL;
-		break;
-	    default :
-		if (*buf == '%' || *++buf == c)
-		    ++buf;
-		else
-		    return NULL;
-		break;
-	    }
-	} else {
-	    if (*buf == c)
-		++buf;
-	    else
-		return NULL;
-	}
+    if (isspace (c)) {
+      while (isspace (*buf))
+        ++buf;
+    } else if (c == '%' && format[1] != '\0') {
+      c = *++format;
+      if (c == 'E' || c == 'O')
+        c = *++format;
+      switch (c) {
+        case 'A' :
+          ret = match_string (&buf, full_weekdays);
+          if (ret < 0)
+            return NULL;
+          timeptr->tm_wday = ret;
+          break;
+        case 'a' :
+          ret = match_string (&buf, abb_weekdays);
+          if (ret < 0)
+            return NULL;
+          timeptr->tm_wday = ret;
+          break;
+        case 'B' :
+          ret = match_string (&buf, full_month);
+          if (ret < 0)
+            return NULL;
+          timeptr->tm_mon = ret;
+          break;
+        case 'b' :
+        case 'h' :
+          ret = match_string (&buf, abb_month);
+          if (ret < 0)
+            return NULL;
+          timeptr->tm_mon = ret;
+          break;
+        case 'C' :
+          ret = strtol (buf, &s, 10);
+          if (s == buf)
+            return NULL;
+          timeptr->tm_year = (ret * 100) - tm_year_base;
+          buf = s;
+          break;
+        case 'c' :
+          abort ();
+        case 'D' :    /* %m/%d/%y */
+          s = strptime (buf, "%m/%d/%y", timeptr);
+          if (s == NULL)
+            return NULL;
+          buf = s;
+          break;
+        case 'd' :
+        case 'e' :
+          ret = strtol (buf, &s, 10);
+          if (s == buf)
+            return NULL;
+          timeptr->tm_mday = ret;
+          buf = s;
+          break;
+        case 'H' :
+        case 'k' :
+          ret = strtol (buf, &s, 10);
+          if (s == buf)
+            return NULL;
+          timeptr->tm_hour = ret;
+          buf = s;
+          break;
+        case 'I' :
+        case 'l' :
+          ret = strtol (buf, &s, 10);
+          if (s == buf)
+            return NULL;
+          if (ret == 12)
+            timeptr->tm_hour = 0;
+          else
+            timeptr->tm_hour = ret;
+          buf = s;
+          break;
+        case 'j' :
+          ret = strtol (buf, &s, 10);
+          if (s == buf)
+            return NULL;
+          timeptr->tm_yday = ret - 1;
+          buf = s;
+          break;
+        case 'm' :
+          ret = strtol (buf, &s, 10);
+          if (s == buf)
+            return NULL;
+          timeptr->tm_mon = ret - 1;
+          buf = s;
+          break;
+        case 'M' :
+          ret = strtol (buf, &s, 10);
+          if (s == buf)
+            return NULL;
+          timeptr->tm_min = ret;
+          buf = s;
+          break;
+        case 'n' :
+          if (*buf == '\n')
+            ++buf;
+          else
+            return NULL;
+          break;
+        case 'p' :
+          ret = match_string (&buf, ampm);
+          if (ret < 0)
+            return NULL;
+          if (timeptr->tm_hour == 0) {
+            if (ret == 1)
+              timeptr->tm_hour = 12;
+          } else
+            timeptr->tm_hour += 12;
+          break;
+        case 'r' :    /* %I:%M:%S %p */
+          s = strptime (buf, "%I:%M:%S %p", timeptr);
+          if (s == NULL)
+            return NULL;
+          buf = s;
+          break;
+        case 'R' :    /* %H:%M */
+          s = strptime (buf, "%H:%M", timeptr);
+          if (s == NULL)
+            return NULL;
+          buf = s;
+          break;
+        case 'S' :
+          ret = strtol (buf, &s, 10);
+          if (s == buf)
+            return NULL;
+          timeptr->tm_sec = ret;
+          buf = s;
+          break;
+        case 't' :
+          if (*buf == '\t')
+            ++buf;
+          else
+            return NULL;
+          break;
+        case 'T' :    /* %H:%M:%S */
+        case 'X' :
+          s = strptime (buf, "%H:%M:%S", timeptr);
+          if (s == NULL)
+            return NULL;
+          buf = s;
+          break;
+        case 'u' :
+          ret = strtol (buf, &s, 10);
+          if (s == buf)
+            return NULL;
+          timeptr->tm_wday = ret - 1;
+          buf = s;
+          break;
+        case 'w' :
+          ret = strtol (buf, &s, 10);
+          if (s == buf)
+            return NULL;
+          timeptr->tm_wday = ret;
+          buf = s;
+          break;
+        case 'U' :
+          ret = strtol (buf, &s, 10);
+          if (s == buf)
+            return NULL;
+          set_week_number_sun (timeptr, ret);
+          buf = s;
+          break;
+        case 'V' :
+          ret = strtol (buf, &s, 10);
+          if (s == buf)
+            return NULL;
+          set_week_number_mon4 (timeptr, ret);
+          buf = s;
+          break;
+        case 'W' :
+          ret = strtol (buf, &s, 10);
+          if (s == buf)
+            return NULL;
+          set_week_number_mon (timeptr, ret);
+          buf = s;
+          break;
+        case 'x' :
+          s = strptime (buf, "%Y:%m:%d", timeptr);
+          if (s == NULL)
+            return NULL;
+          buf = s;
+          break;
+        case 'y' :
+          ret = strtol (buf, &s, 10);
+          if (s == buf)
+            return NULL;
+          if (ret < 70)
+            timeptr->tm_year = 100 + ret;
+          else
+            timeptr->tm_year = ret;
+          buf = s;
+          break;
+        case 'Y' :
+          ret = strtol (buf, &s, 10);
+          if (s == buf)
+            return NULL;
+          timeptr->tm_year = ret - tm_year_base;
+          buf = s;
+          break;
+        case 'Z' :
+          abort ();
+        case '\0' :
+          --format;
+          /* FALLTHROUGH */
+        case '%' :
+          if (*buf == '%')
+            ++buf;
+          else
+            return NULL;
+          break;
+        default :
+          if (*buf == '%' || *++buf == c)
+            ++buf;
+          else
+            return NULL;
+          break;
+      }
+    } else {
+      if (*buf == c)
+        ++buf;
+      else
+        return NULL;
     }
-    return (char *)buf;
+  }
+  return (char *)buf;
 }
 
 #endif
diff --git a/sym2img.c b/sym2img.c
index 49985ca..f3f270c 100644
--- a/sym2img.c
+++ b/sym2img.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -32,7 +32,7 @@
 
 #include "mapserver.h"
 
-MS_CVSID("$Id$")
+
 
 #define MAXCOLORS 256
 #define CELLSIZE 100
@@ -53,10 +53,10 @@ int main(int argc, char *argv[])
   classObj class;
   symbolSetObj symbolSet;
 
-   /* ---- check the number of arguments, return syntax if not correct ---- */
+  /* ---- check the number of arguments, return syntax if not correct ---- */
   if( argc < 2 ) {
-      fprintf(stdout, "Syntax: sym2img [symbolset] [outfile]\n" );
-      exit(0);
+    fprintf(stdout, "Syntax: sym2img [symbolset] [outfile]\n" );
+    exit(0);
   }
 
   /* Initialize the polygon/polyline */
@@ -68,14 +68,14 @@ int main(int argc, char *argv[])
   /* Initialize the symbol and font sets */
   symbolSet.filename = msStrdup(argv[1]);
 
-  /* 
+  /*
   ** load the symbol file
   */
-  if(msLoadSymbolSet(&symbolSet) == -1) { 
+  if(msLoadSymbolSet(&symbolSet) == -1) {
     msWriteError(stderr);
     exit(1);
   }
-  
+
   ns = symbolSet.numsymbols;
 
   if(ns < NCOLS) {
@@ -100,54 +100,54 @@ int main(int argc, char *argv[])
 
   n=0;
 
-  for(i=0; n<ns;i+=CELLSIZE) {
-	k=0;
-    for(j=0; n<ns;j+=CELLSIZE) {
-	  if (k == ncols) break;
-	  k++;
+  for(i=0; n<ns; i+=CELLSIZE) {
+    k=0;
+    for(j=0; n<ns; j+=CELLSIZE) {
+      if (k == ncols) break;
+      k++;
       gdImageFilledRectangle(img,j,i,j+CELLSIZE, i+CELLSIZE, gray);
 
       class.symbol = n;
 
       switch(symbolSet.type) {
-      case(MS_MARKERSET):
-	class.sizescaled = RATIO*CELLSIZE;
-	p.line[0].point[0].x = MS_NINT(j + CELLSIZE/2);
-	p.line[0].point[0].y = MS_NINT(i + CELLSIZE/2);
-	p.line[0].numpoints = 1;
-	msDrawMarkerSymbol(&(symbolSet), img, &(p.line[0].point[0]), &(class));
-	break;
-
-      case(MS_LINESET):
-	class.sizescaled = 1;
-	p.line[0].point[0].x = j;
-        p.line[0].point[0].y = i + (CELLSIZE-LBUF) - 1;
-	p.line[0].point[1].x = j + MS_NINT((CELLSIZE-LBUF)/3.0) - 1;
-        p.line[0].point[1].y = i;
-        p.line[0].point[2].x = j + MS_NINT(2*(CELLSIZE-LBUF)/3.0) - 1;
-        p.line[0].point[2].y = i + (CELLSIZE-LBUF) - 1;
-	p.line[0].point[3].x = j + (CELLSIZE-LBUF) - 1;
-        p.line[0].point[3].y = i;
-	p.line[0].numpoints = 4;
-        msDrawLineSymbol(&(symbolSet), img, &p, &(class));
-	break;
-
-      case(MS_SHADESET):
-	class.sizescaled = 5;
-	p.line[0].point[0].x = j;
-	p.line[0].point[0].y = i;
-	p.line[0].point[1].x = j + CELLSIZE-1;
-	p.line[0].point[1].y = i;
-	p.line[0].point[2].x = j + CELLSIZE-1;
-	p.line[0].point[2].y = i + CELLSIZE-1 ;
-	p.line[0].point[3].x = j;
-	p.line[0].point[3].y = i + CELLSIZE-1;
-	p.line[0].numpoints = 4;
-	msDrawShadeSymbol(&(symbolSet), img, &p, &(class));
-	break;
-
-      default:
-	break;
+        case(MS_MARKERSET):
+          class.sizescaled = RATIO*CELLSIZE;
+          p.line[0].point[0].x = MS_NINT(j + CELLSIZE/2);
+          p.line[0].point[0].y = MS_NINT(i + CELLSIZE/2);
+          p.line[0].numpoints = 1;
+          msDrawMarkerSymbol(&(symbolSet), img, &(p.line[0].point[0]), &(class));
+          break;
+
+        case(MS_LINESET):
+          class.sizescaled = 1;
+          p.line[0].point[0].x = j;
+          p.line[0].point[0].y = i + (CELLSIZE-LBUF) - 1;
+          p.line[0].point[1].x = j + MS_NINT((CELLSIZE-LBUF)/3.0) - 1;
+          p.line[0].point[1].y = i;
+          p.line[0].point[2].x = j + MS_NINT(2*(CELLSIZE-LBUF)/3.0) - 1;
+          p.line[0].point[2].y = i + (CELLSIZE-LBUF) - 1;
+          p.line[0].point[3].x = j + (CELLSIZE-LBUF) - 1;
+          p.line[0].point[3].y = i;
+          p.line[0].numpoints = 4;
+          msDrawLineSymbol(&(symbolSet), img, &p, &(class));
+          break;
+
+        case(MS_SHADESET):
+          class.sizescaled = 5;
+          p.line[0].point[0].x = j;
+          p.line[0].point[0].y = i;
+          p.line[0].point[1].x = j + CELLSIZE-1;
+          p.line[0].point[1].y = i;
+          p.line[0].point[2].x = j + CELLSIZE-1;
+          p.line[0].point[2].y = i + CELLSIZE-1 ;
+          p.line[0].point[3].x = j;
+          p.line[0].point[3].y = i + CELLSIZE-1;
+          p.line[0].numpoints = 4;
+          msDrawShadeSymbol(&(symbolSet), img, &p, &(class));
+          break;
+
+        default:
+          break;
       }
 
       if(symbolSet.symbol[n]->name)
@@ -160,7 +160,7 @@ int main(int argc, char *argv[])
     }
   }
 
- if((stream = fopen(argv[2],"wb")) == NULL) { /* open the file */
+  if((stream = fopen(argv[2],"wb")) == NULL) { /* open the file */
     fprintf(stderr, "Unable to open output file: %s\n", argv[2]);
     exit(1);
   }
diff --git a/testcopy.c b/testcopy.c
index c22bcf4..782fa8a 100644
--- a/testcopy.c
+++ b/testcopy.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -29,56 +29,57 @@
 
 #include "mapserver.h"
 
-MS_CVSID("$Id$")
 
-void printAtts(mapObj*, const char*);
-
-int main(int argc, char *argv[]) {
 
-    mapObj *original_map, *clone_map;
+void printAtts(mapObj*, const char*);
 
-    /* ---------------------------------------------------------------------
-     * Test 1: free original before freeing clone
-     * --------------------------------------------------------------------- */
+int main(int argc, char *argv[])
+{
 
-    /* Load map file */
-    original_map = msLoadMap("tests/test.map", NULL);
-    
-    if (original_map ==  NULL)
-    {
-        /* Write errors */
-        msWriteError(stderr);
-        msResetErrorList();
-        exit(0);
-    }
+  mapObj *original_map, *clone_map;
 
-    /* Dump out some attributes */
-    printAtts(original_map, "Original"); 
+  /* ---------------------------------------------------------------------
+   * Test 1: free original before freeing clone
+   * --------------------------------------------------------------------- */
 
-    /* Clone it */
-    clone_map = msNewMapObj();
-    msCopyMap(clone_map, original_map);
+  /* Load map file */
+  original_map = msLoadMap("tests/test.map", NULL);
 
+  if (original_map ==  NULL) {
     /* Write errors */
     msWriteError(stderr);
     msResetErrorList();
+    exit(0);
+  }
+
+  /* Dump out some attributes */
+  printAtts(original_map, "Original");
+
+  /* Clone it */
+  clone_map = msNewMapObj();
+  msCopyMap(clone_map, original_map);
+
+  /* Write errors */
+  msWriteError(stderr);
+  msResetErrorList();
+
+  /* Free */
+  msFreeMap(original_map);
 
-    /* Free */
-    msFreeMap(original_map);
+  /* Dump clone's attributes */
+  printAtts(clone_map, "Clone");
 
-    /* Dump clone's attributes */
-    printAtts(clone_map, "Clone");
-  
-    /* Free clone */
-    msFreeMap(clone_map);
+  /* Free clone */
+  msFreeMap(clone_map);
 
-    exit(0);    
+  exit(0);
 }
 
-void printAtts(mapObj *map, const char *title) {
-    printf("\n%s Attributes\n----------------------\n", title);
-    printf("Map Name: %s\n", map->name);
-    printf("Numlayers: %d\n", map->numlayers);
-    printf("Map Fontset Filename: %s\n", map->fontset.filename);
-    printf("Map Symbolset Filename: %s\n", map->symbolset.filename);
+void printAtts(mapObj *map, const char *title)
+{
+  printf("\n%s Attributes\n----------------------\n", title);
+  printf("Map Name: %s\n", map->name);
+  printf("Numlayers: %d\n", map->numlayers);
+  printf("Map Fontset Filename: %s\n", map->fontset.filename);
+  printf("Map Symbolset Filename: %s\n", map->symbolset.filename);
 }
diff --git a/testexpr.c b/testexpr.c
index 2d1d32b..db306a0 100644
--- a/testexpr.c
+++ b/testexpr.c
@@ -15,7 +15,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -33,7 +33,7 @@
 #include "mapparser.h"
 #include "mapfile.h"
 
-MS_CVSID("$Id$")
+
 
 extern int msyyparse();
 extern int msyylex();
@@ -58,11 +58,11 @@ int main(int argc, char *argv[])
     exit(0);
   }
 
-  msyystate = MS_TOKENIZE_EXPRESSION; 
+  msyystate = MS_TOKENIZE_EXPRESSION;
   msyystring = argv[1];
 
   status = msyyparse();
-  if(status != 0) 
+  if(status != 0)
     printf("Error parsing expression near %s.\n", msyystring_buffer);
   else
     printf("Expression evalulated to: %d.\n", msyyresult);
diff --git a/tests/test.map b/tests/test.map
index 9d24f05..2ca3bdc 100644
--- a/tests/test.map
+++ b/tests/test.map
@@ -40,6 +40,7 @@ MAP
       "key2" "value2"
       "key3" "value3"
       "key4" "value4"
+      "ows_enable_request" "*"
     END
   END
 
@@ -55,7 +56,7 @@ MAP
     END
     DATA "raster.tif"
     PROCESSING "BANDS=1"
-    STATUS DEFAULT
+    STATUS ON # DEFAULT
   END
   
   LAYER
@@ -64,7 +65,7 @@ MAP
     PROJECTION
       "init=epsg:4326"
     END
-    STATUS DEFAULT
+    STATUS ON # DEFAULT
     DATA "polygon"
     METADATA
       "key1" "value1"
@@ -84,9 +85,9 @@ MAP
       STYLE
         COLOR 255 153 102
         OUTLINECOLOR 0 0 204
-        SYMBOL 1
-        SIZE 2
-      END
+        #SYMBOL 1
+        #SIZE 2
+      END      
     END
     CLASS
       NAME "1"
@@ -106,16 +107,17 @@ MAP
     PROJECTION
       "init=epsg:4326"
     END
-    TRANSPARENCY 1
-    STATUS DEFAULT
+    #TRANSPARENCY 1
+    STATUS ON # DEFAULT
     DATA "line"
     CLASSITEM "FNAME"
     CLASS
       NAME "0"
       STYLE
         COLOR 0 153 0
-        SYMBOL 1
-        SIZE 3
+        #SYMBOL 1
+        #SIZE 3
+        WIDTH 3
       END
     END
     CLASS
@@ -136,7 +138,7 @@ MAP
     PROJECTION
       "init=epsg:4326"
     END
-    STATUS DEFAULT
+    STATUS OFF # DEFAULT
     DATA "point"
     CLASSITEM "FNAME"
     LABELITEM "FNAME"
@@ -178,7 +180,7 @@ MAP
     PROJECTION
       "init=epsg:4326"
     END
-    STATUS DEFAULT
+    STATUS OFF # DEFAULT
     FEATURE
       POINTS -0.2 51.5 END
     END
@@ -223,7 +225,7 @@ LAYER
     PROJECTION
       "init=epsg:4326"
     END
-    STATUS DEFAULT
+    STATUS OFF # DEFAULT
     FEATURE
       POINTS 0.2 51.2 END
     END
diff --git a/tile4ms.c b/tile4ms.c
index df78577..445aced 100644
--- a/tile4ms.c
+++ b/tile4ms.c
@@ -2,7 +2,7 @@
  * $Id$
  *
  * Project:  MapServer
- * Purpose:  Create shapefile of rectangles from extents of several shapefiles 
+ * Purpose:  Create shapefile of rectangles from extents of several shapefiles
  *           (=tiles)
  *           Create DBF with file names for shape tiles, in column LOCATION as
  *           required by mapserv.
@@ -22,7 +22,7 @@
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
  *
- * The above copyright notice and this permission notice shall be included in 
+ * The above copyright notice and this permission notice shall be included in
  * all copies of this Software or works derived from this Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
@@ -43,53 +43,53 @@
 #include "mapserver.h"
 #include <string.h>
 
-MS_CVSID("$Id$")
+
 
 /***********************************************************************/
-int process_shapefiles(char *metaFileNameP, char *tileFileNameP, 
-                       int tile_path_only) 
+int process_shapefiles(char *metaFileNameP, char *tileFileNameP,
+                       int tile_path_only)
 {
-SHPHandle   hSHP, tileSHP;
-rectObj     extentRect;
-lineObj     line;
-shapeObj    shapeRect;
-DBFHandle   tileDBF;
-DBFHandle   shpDBF;
-
-typedef struct DBFFieldDef_struct {
-  DBFFieldType  type;
-  char          name[12];
-  int           width;
-  int           decimals;
-} DBFFieldDef;
-
-DBFFieldDef     *theFields = NULL;
-char            fldname[256];
-int             width;
-int             decimals;
-int             fieldCnt;
-int             i;
-
-FILE        *metaFP = NULL;
-char        *p;
-char        tileshapeName[256];
-char        tiledbfName[256];
-char        shapeFileName[256];
-int     entityNum;
-
-int     tilesFound = 0;
-int     tilesProcessed = 0;
+  SHPHandle   hSHP, tileSHP;
+  rectObj     extentRect;
+  lineObj     line;
+  shapeObj    shapeRect;
+  DBFHandle   tileDBF;
+  DBFHandle   shpDBF;
+
+  typedef struct DBFFieldDef_struct {
+    DBFFieldType  type;
+    char          name[12];
+    int           width;
+    int           decimals;
+  } DBFFieldDef;
+
+  DBFFieldDef     *theFields = NULL;
+  char            fldname[256];
+  int             width;
+  int             decimals;
+  int             fieldCnt;
+  int             i;
+
+  FILE        *metaFP = NULL;
+  char        *p;
+  char        tileshapeName[256];
+  char        tiledbfName[256];
+  char        shapeFileName[256];
+  int     entityNum;
+
+  int     tilesFound = 0;
+  int     tilesProcessed = 0;
 
   msInitShape(&shapeRect);
   line.point = (pointObj *)msSmallMalloc(sizeof(pointObj)*5);
   line.numpoints = 5;
- 
+
   /* open metafile */
   /* ------------- */
   if (NULL==(metaFP=fopen(metaFileNameP, "r"))) {
     printf( "Unable to open:%s\n", metaFileNameP);
     return(1);
-    }
+  }
 
 
   /* create new tileindex shapefiles and create a header */
@@ -100,9 +100,9 @@ int     tilesProcessed = 0;
     fclose(metaFP);
     printf("Unable to create %s.shp (.shx)\n", tileFileNameP);
     return(1);
-    }
+  }
+
 
-  
   /* create new tileindex dbf-file */
   /* ----------------------------- */
   snprintf(tiledbfName, sizeof(tiledbfName), "%s.dbf", tileFileNameP);
@@ -111,7 +111,7 @@ int     tilesProcessed = 0;
     msSHPClose(tileSHP);
     printf("DBFCreate(%s) failed.\n", tiledbfName);
     return(1);
-    }
+  }
 
   if(msDBFAddField(tileDBF, "LOCATION", FTString, 255, 0 )== -1 ) {
     fclose(metaFP);
@@ -119,75 +119,75 @@ int     tilesProcessed = 0;
     msDBFClose(tileDBF);
     printf("DBFAddField(fieldname='LOCATION') failed.\n");
     return(1);
-    }
+  }
 
 
 
   /* loop through files listed in metafile */
   /* ===================================== */
   while (fgets(shapeFileName, 255, metaFP)) {
-    
+
 
     if ((p=strchr(shapeFileName, '\n')) != NULL) *p='\0';
 
     if (!strlen(shapeFileName))
-        break;
+      break;
 
     tilesFound++;
 
     /* read the DBFFields for this shapefile */
     /* and save them if the first, otherwise compare them */
-    
+
     shpDBF = msDBFOpen(shapeFileName, "rb");
 
     if( shpDBF == NULL ) {
-        printf( "Aborted. Unable to open DBF:%s\n", shapeFileName);
-        break;
-        }
+      printf( "Aborted. Unable to open DBF:%s\n", shapeFileName);
+      break;
+    }
 
     if( theFields == NULL ) {
-        fieldCnt = msDBFGetFieldCount(shpDBF);
-        theFields = (DBFFieldDef *) msSmallCalloc(fieldCnt, sizeof(DBFFieldDef));
-        for (i=0; i<fieldCnt; i++) {
-            theFields[i].type = msDBFGetFieldInfo(shpDBF, i, 
-                    theFields[i].name, 
-                    &theFields[i].width, &theFields[i].decimals);
-            if( theFields[i].type == FTInvalid ) {
-                printf( "Aborted. DBF Invalid field (%d of %d) file:%s\n", 
-                        i, fieldCnt, shapeFileName);
-                break;
-            }
+      fieldCnt = msDBFGetFieldCount(shpDBF);
+      theFields = (DBFFieldDef *) msSmallCalloc(fieldCnt, sizeof(DBFFieldDef));
+      for (i=0; i<fieldCnt; i++) {
+        theFields[i].type = msDBFGetFieldInfo(shpDBF, i,
+                                              theFields[i].name,
+                                              &theFields[i].width, &theFields[i].decimals);
+        if( theFields[i].type == FTInvalid ) {
+          printf( "Aborted. DBF Invalid field (%d of %d) file:%s\n",
+                  i, fieldCnt, shapeFileName);
+          break;
         }
+      }
     } else {
-        fieldCnt = msDBFGetFieldCount(shpDBF);
-        for (i=0; i<fieldCnt; i++) {
-            if( theFields[i].type != msDBFGetFieldInfo(shpDBF, i, fldname, &width, &decimals) ||
-                strcmp(theFields[i].name, fldname) ||
-                theFields[i].width != width || theFields[i].decimals != decimals ) {
-                printf( "Aborted. DBF fields do not match for file:%s\n", shapeFileName);
-                break;
-            }
+      fieldCnt = msDBFGetFieldCount(shpDBF);
+      for (i=0; i<fieldCnt; i++) {
+        if( theFields[i].type != msDBFGetFieldInfo(shpDBF, i, fldname, &width, &decimals) ||
+            strcmp(theFields[i].name, fldname) ||
+            theFields[i].width != width || theFields[i].decimals != decimals ) {
+          printf( "Aborted. DBF fields do not match for file:%s\n", shapeFileName);
+          break;
         }
+      }
     }
     msDBFClose(shpDBF);
 
-        /* Get rid of .shp extension if it was included. */
-    if (strlen(shapeFileName) > 4 && 
-            (p=shapeFileName+strlen(shapeFileName)-4) &&
-            strcasecmp(p, ".shp") == 0)
-          *p = '\0';
+    /* Get rid of .shp extension if it was included. */
+    if (strlen(shapeFileName) > 4 &&
+        (p=shapeFileName+strlen(shapeFileName)-4) &&
+        strcasecmp(p, ".shp") == 0)
+      *p = '\0';
 
     if (!strlen(shapeFileName))
-        break;
+      break;
 
     /* read extent from shapefile */
     /* -------------------------- */
     hSHP = msSHPOpen(shapeFileName, "rb");
 
     if( hSHP == NULL )  {
-        printf( "Aborted. Unable to open SHP:%s\n", shapeFileName);
-        break;
-        }
+      printf( "Aborted. Unable to open SHP:%s\n", shapeFileName);
+      break;
+    }
 
     msSHPReadBounds(hSHP, -1, &extentRect);
     /* SHPGetInfo(hSHP, &nEntities, &nShapeType, adfBndsMin, adfBndsMax); */
@@ -215,21 +215,19 @@ int     tilesProcessed = 0;
 
     msAddLine(&shapeRect, &line);
     entityNum = msSHPWriteShape( tileSHP, &shapeRect );
-    
+
     msFreeShape(&shapeRect);
 
     /* store filepath of current shapefile as attribute of rectangle */
     /* ------------------------------------------------------------- */
 
     /* Strip off filename if requested */
-    if (tile_path_only)
-    {
-        char *pszTmp;
-        if ((pszTmp = strrchr(shapeFileName, '/')) != NULL ||
-            (pszTmp = strrchr(shapeFileName, '\\')) != NULL )
-        {
-            *(pszTmp+1) = '\0';  /* Keep the trailing '/' only. */
-        }
+    if (tile_path_only) {
+      char *pszTmp;
+      if ((pszTmp = strrchr(shapeFileName, '/')) != NULL ||
+          (pszTmp = strrchr(shapeFileName, '\\')) != NULL ) {
+        *(pszTmp+1) = '\0';  /* Keep the trailing '/' only. */
+      }
     }
 
     msDBFWriteStringAttribute(tileDBF, entityNum, 0, shapeFileName);
@@ -245,22 +243,23 @@ int     tilesProcessed = 0;
 
   free(line.point);
 
-  
+
   printf("Processed %i of %i files\n", tilesProcessed, tilesFound);
 
-  
+
   return (0);
 
 }
 
 /***********************************************************************/
-void print_usage_and_exit(void) {
+void print_usage_and_exit(void)
+{
 
-    printf("\nusage: tile4ms <meta-file> <tile-file> [-tile-path-only]\n");
-    printf("<meta-file>\tINPUT  file containing list of shapefile names\n\t\t(complete paths 255 chars max, no extension)\n");
-    printf("<tile-file>\tOUTPUT shape file of extent rectangles and names\n\t\tof tiles in <tile-file>.dbf\n");
-    printf("-tile-path-only\tOptional flag.  If specified then only the path to the \n\t\tshape files will be stored in the LOCATION field\n\t\tinstead of storing the full filename.\n\n");
-    exit(1);
+  printf("\nusage: tile4ms <meta-file> <tile-file> [-tile-path-only]\n");
+  printf("<meta-file>\tINPUT  file containing list of shapefile names\n\t\t(complete paths 255 chars max, no extension)\n");
+  printf("<tile-file>\tOUTPUT shape file of extent rectangles and names\n\t\tof tiles in <tile-file>.dbf\n");
+  printf("-tile-path-only\tOptional flag.  If specified then only the path to the \n\t\tshape files will be stored in the LOCATION field\n\t\tinstead of storing the full filename.\n\n");
+  exit(1);
 }
 
 
@@ -272,22 +271,19 @@ int main( int argc, char **argv )
 
   /* stun user with existence of help  */
   /* -------------------------------- */
-  if ((argc == 2)&&(strstr(argv[1], "-h"))) 
-  {
-      print_usage_and_exit();
+  if ((argc == 2)&&(strstr(argv[1], "-h"))) {
+    print_usage_and_exit();
   }
 
 
   /* check arguments */
   /* --------------- */
-  if( argc < 3 )
-  {
-      print_usage_and_exit();
+  if( argc < 3 ) {
+    print_usage_and_exit();
   }
 
-  if ( argc == 4 && strcmp(argv[3],"-tile-path-only") == 0) 
-  {
-      tile_path_only = 1;
+  if ( argc == 4 && strcmp(argv[3],"-tile-path-only") == 0) {
+    tile_path_only = 1;
   }
 
   process_shapefiles(argv[1], argv[2], tile_path_only);
diff --git a/xmlmapfile/mapfile.xsd b/xmlmapfile/mapfile.xsd
index e2df4c1..ed386e8 100644
--- a/xmlmapfile/mapfile.xsd
+++ b/xmlmapfile/mapfile.xsd
@@ -193,6 +193,7 @@
 			<xs:element name="Validation" type="ms:itemType" minOccurs="0"/>
 		</xs:sequence>
 	</xs:complexType>
+	<!-- OUTPUTFORMAT Definition -->
 	<xs:complexType name="OutputFormat">
 		<xs:sequence>
 			<xs:element name="driver" type="xs:string" minOccurs="0"/>
@@ -207,6 +208,7 @@
 						<xs:enumeration value="BYTE"/>
 						<xs:enumeration value="INT16"/>
 						<xs:enumeration value="FLOAT32"/>
+						<xs:enumeration value="FEATURE"/>
 					</xs:restriction>
 				</xs:simpleType>
 			</xs:element>
@@ -344,7 +346,7 @@
 					</xs:union>
 				</xs:simpleType>
 			</xs:element>
-			<xs:element name="Style" type="ms:Style" minOccurs="0"/>
+			<xs:element name="Style" type="ms:Style" minOccurs="0" maxOccurs="unbounded"/>
 			<xs:element name="wrap" type="xs:string" minOccurs="0"/>
 		</xs:sequence>
 		<xs:attribute name="type" use="required">
@@ -356,6 +358,14 @@
 			</xs:simpleType>
 		</xs:attribute>
 	</xs:complexType>
+    <!-- LABELLEADER Definition -->
+    <xs:complexType name="LabelLeader">
+        <xs:sequence>
+            <xs:element name="gridstep" type="xs:positiveInteger" minOccurs="0"/>
+            <xs:element name="maxdistance" type="xs:positiveInteger" minOccurs="0"/>
+            <xs:element name="Style"  type="ms:Style" minOccurs="0" maxOccurs="unbounded" />
+        </xs:sequence>
+    </xs:complexType>
 	<!-- STYLE Definition -->
 	<xs:complexType name="Style">
 		<xs:sequence>
@@ -389,6 +399,7 @@
 					</xs:restriction>
 				</xs:simpleType>
 			</xs:element>
+            <xs:element name="initialGap" type="xs:double" minOccurs="0"/>
 			<xs:element name="lineCap" default="BUTT" minOccurs="0">
 				<xs:simpleType>
 					<xs:restriction base="xs:string">
@@ -425,6 +436,11 @@
 					<xs:list itemType="xs:float"/>
 				</xs:simpleType>
 			</xs:element>
+            <xs:element name="polarOffset" minOccurs="0">
+                <xs:simpleType>
+                    <xs:union memberTypes="xs:positiveInteger ms:attributeType xs:positiveInteger ms:attributeType"/>
+                </xs:simpleType>
+            </xs:element>
 			<xs:element name="size" default="1" minOccurs="0">
 				<xs:simpleType>
 					<xs:union memberTypes="xs:positiveInteger ms:attributeType"/>
@@ -448,6 +464,7 @@
 			<xs:element name="group" type="xs:string" minOccurs="0"/>
 			<xs:element name="keyImage" type="xs:string" minOccurs="0"/>
 			<xs:element name="Label" type="ms:Label" minOccurs="0"/>
+            <xs:element name="LabelLeader" type="ms:LabelLeader" minOccurs="0"/>
 			<xs:element name="maxScaleDenom" type="xs:double" minOccurs="0"/>
 			<xs:element name="maxSize" type="xs:integer" default="50" minOccurs="0"/>
 			<xs:element name="minScaleDenom" type="xs:double" minOccurs="0"/>
@@ -468,6 +485,7 @@
 	<!-- SYMBOL Definition -->
 	<xs:complexType name="Symbol">
 		<xs:sequence>
+            <xs:element name="anchorPoint" type="ms:pointType" minOccurs="0"/>
 			<xs:element name="antialias" type="ms:booleanEnum" minOccurs="0"/>
 			<xs:element name="character" type="xs:string" minOccurs="0"/>
 			<xs:element name="filled" type="ms:booleanEnum" minOccurs="0"/>
@@ -630,6 +648,7 @@
 			<xs:element name="labelMaxScaleDenom" type="xs:double" minOccurs="0"/>
 			<xs:element name="labelMinScaleDenom" type="xs:double" minOccurs="0"/>
 			<xs:element name="labelRequires" type="xs:string" minOccurs="0"/>
+			<xs:element name="mask" type="xs:string" minOccurs="0"/>
 			<xs:element name="maxFeatures" type="xs:positiveInteger" minOccurs="0"/>
 			<xs:element name="maxGeoWidth" type="xs:double" minOccurs="0"/>
 			<xs:element name="maxScaleDenom" type="xs:double" minOccurs="0"/>
diff --git a/xmlmapfile/mapfile.xsl b/xmlmapfile/mapfile.xsl
index f5fe594..a113474 100644
--- a/xmlmapfile/mapfile.xsl
+++ b/xmlmapfile/mapfile.xsl
@@ -175,7 +175,7 @@
   </xsl:call-template>
 </xsl:template>
 
-<xsl:template match="ms:size | ms:offset | ms:keySize | ms:keySpacing | ms:shadowSize">
+<xsl:template match="ms:size | ms:offset | ms:keySize | ms:keySpacing | ms:shadowSize | ms:anchorPoint">
   <xsl:param name="indent"/>
   <xsl:choose>
     <xsl:when test="starts-with(name(), 'ms:')">
@@ -755,6 +755,29 @@
     </xsl:call-template>
   </xsl:template>
   
+  <xsl:template match="ms:LabelLeader">
+    <xsl:param name="indent"/>
+    <xsl:call-template name="print">
+      <xsl:with-param name="text" select="'LEADER'"/>
+      <xsl:with-param name="indent" select="$indent - 1"/>
+    </xsl:call-template>
+    <xsl:call-template name="print">
+      <xsl:with-param name="indent" select="$indent"/>
+      <xsl:with-param name="node" select="'ms:gridstep'"/>
+    </xsl:call-template>
+    <xsl:call-template name="print">
+      <xsl:with-param name="indent" select="$indent"/>
+      <xsl:with-param name="node" select="'ms:maxdistance'"/>
+    </xsl:call-template>
+    <xsl:apply-templates select="ms:Style">
+      <xsl:with-param name="indent" select="$indent + 1"/>
+    </xsl:apply-templates>
+    <xsl:call-template name="print">
+      <xsl:with-param name="text" select="'END'"/>
+      <xsl:with-param name="indent" select="$indent - 1"/>
+    </xsl:call-template>
+  </xsl:template>
+
   <xsl:template match="ms:Style">
     <xsl:param name="indent"/>
     <xsl:call-template name="print">
@@ -785,6 +808,10 @@
     </xsl:call-template>
     <xsl:call-template name="print">
       <xsl:with-param name="indent" select="$indent"/>
+      <xsl:with-param name="node" select="'ms:initialGap'"/>
+    </xsl:call-template>
+    <xsl:call-template name="print">
+      <xsl:with-param name="indent" select="$indent"/>
       <xsl:with-param name="node" select="'ms:maxSize'"/>
     </xsl:call-template>
     <xsl:call-template name="print">
@@ -818,6 +845,10 @@
     <xsl:apply-templates select="ms:pattern">
       <xsl:with-param name="indent" select="$indent"/>
     </xsl:apply-templates>
+    <xsl:call-template name="print">
+      <xsl:with-param name="indent" select="$indent"/>
+      <xsl:with-param name="node" select="'ms:polarOffset'"/>
+    </xsl:call-template>
     <xsl:apply-templates select="ms:offset">
       <xsl:with-param name="indent" select="$indent"/>
     </xsl:apply-templates>
@@ -895,6 +926,9 @@
     <xsl:apply-templates select="ms:Label">
       <xsl:with-param name="indent" select="$indent + 1"/>
     </xsl:apply-templates>
+    <xsl:apply-templates select="ms:LabelLeader">
+      <xsl:with-param name="indent" select="$indent + 1"/>
+    </xsl:apply-templates>
     <xsl:call-template name="print">
       <xsl:with-param name="indent" select="$indent"/>
       <xsl:with-param name="node" select="'ms:maxScaleDenom'"/>
@@ -963,6 +997,9 @@
       <xsl:with-param name="node" select="@type"/>
       <xsl:with-param name="quote" select="1"/>
     </xsl:call-template>
+    <xsl:apply-templates select="ms:anchorPoint">
+      <xsl:with-param name="indent" select="$indent"/>
+    </xsl:apply-templates>
     <xsl:call-template name="print">
       <xsl:with-param name="indent" select="$indent"/>
       <xsl:with-param name="node" select="'ms:antialias'"/>
@@ -1253,6 +1290,10 @@
     </xsl:call-template>
     <xsl:call-template name="print">
       <xsl:with-param name="indent" select="$indent"/>
+      <xsl:with-param name="node" select="'ms:mask'"/>
+    </xsl:call-template>
+    <xsl:call-template name="print">
+      <xsl:with-param name="indent" select="$indent"/>
       <xsl:with-param name="node" select="'ms:maxFeatures'"/>
     </xsl:call-template>
     <xsl:call-template name="print">
diff --git a/xmlmapfile/tests/layerset.xml b/xmlmapfile/tests/layerset.xml
index 93cb967..a347fb1 100644
--- a/xmlmapfile/tests/layerset.xml
+++ b/xmlmapfile/tests/layerset.xml
@@ -34,6 +34,13 @@
         <size>TINY</size>
         <wrap>\n</wrap>
       </Label>
+      <LabelLeader>
+        <gridstep>6</gridstep>
+        <maxdistance>15</maxdistance>
+            <Style>
+                <initialGap>2</initialGap>
+            </Style>
+      </LabelLeader>
       <maxScaleDenom>24000</maxScaleDenom>
       <maxSize>50</maxSize>
       <minScaleDenom>1000000</minScaleDenom>
@@ -62,6 +69,9 @@
         <symbol type="NAME">star.gif</symbol>
         <width>[myWidth]</width>
       </Style>
+            <Style>
+                <initialGap>2</initialGap>
+            </Style>
       <symbol type="ID">261</symbol>
       <template>http://mapgears.com/templates/myTemplates1.html</template>
       <text>myText1</text>
@@ -111,6 +121,7 @@
     <labelMaxScaleDenom>2334342</labelMaxScaleDenom>
     <labelMinScaleDenom>100000</labelMinScaleDenom>
     <labelRequires>![orthoquads]</labelRequires>
+    <mask>layerName</mask>
     <maxFeatures>250000</maxFeatures>
     <maxScaleDenom>300000</maxScaleDenom>
     <Metadata>
diff --git a/xmlmapfile/tests/mapfile-test.xml b/xmlmapfile/tests/mapfile-test.xml
index ecf5c6b..ccfc6d1 100644
--- a/xmlmapfile/tests/mapfile-test.xml
+++ b/xmlmapfile/tests/mapfile-test.xml
@@ -126,6 +126,11 @@
 			<size>SMALL</size>
                         <Style>
                           <geomTransform>VERTICES</geomTransform>
+                          <initialGap>20.5</initialGap>
+                          <polarOffset>[uv_length_2] [uv_angle]</polarOffset>
+                        </Style>
+                        <Style>
+                          <initialGap>2</initialGap>
                         </Style>
 			<wrap>\n</wrap>
 		</Label>
diff --git a/xmlmapfile/tests/symbolset.xml b/xmlmapfile/tests/symbolset.xml
index e4a2a17..d9dbdb6 100644
--- a/xmlmapfile/tests/symbolset.xml
+++ b/xmlmapfile/tests/symbolset.xml
@@ -12,6 +12,7 @@
 		<transparent>0</transparent>
 	</Symbol>
         <Symbol name="mySymbol222" type="SIMPLE">
+          <anchorPoint x="0.5" y="0.2"/>
           <antialias>FALSE</antialias>
           <character>C</character>
           <filled>TRUE</filled>

-- 
Mapserver



More information about the Pkg-grass-devel mailing list